Merge from Chromium at DEPS revision 251904

This commit was generated by merge_to_master.py.

Change-Id: I8ca36eee41eba7e9a56d6728a9d19e5883d7058c
diff --git a/Source/core/DEPS b/Source/core/DEPS
index da61cbd..d8be74f 100644
--- a/Source/core/DEPS
+++ b/Source/core/DEPS
@@ -12,13 +12,6 @@
     "!modules/encryptedmedia/MediaKeyNeededEvent.h",
     "!modules/encryptedmedia/MediaKeys.h",
     "!modules/filesystem/DraggedIsolatedFileSystem.h",
-    "!modules/geolocation/GeolocationClient.h",
-    "!modules/geolocation/GeolocationController.h",
-    "!modules/geolocation/GeolocationError.h",
-    "!modules/geolocation/GeolocationPosition.h",
-    "!modules/mediastream/MediaStreamRegistry.h",
-    "!modules/mediastream/MediaStreamTrackSourcesRequest.h",
-    "!modules/mediastream/RTCStatsResponse.h",
     "!modules/webaudio/MediaElementAudioSourceNode.h",
     "!modules/webdatabase/DatabaseManager.h",
     "!modules/webdatabase/DatabaseTask.h",
diff --git a/Source/core/Init.cpp b/Source/core/Init.cpp
index 8b7304d..b48d1f6 100644
--- a/Source/core/Init.cpp
+++ b/Source/core/Init.cpp
@@ -44,6 +44,8 @@
 #include "XMLNSNames.h"
 #include "XMLNames.h"
 #include "core/css/MediaFeatureNames.h"
+#include "core/html/parser/HTMLParserThread.h"
+#include "heap/Heap.h"
 #include "platform/EventTracer.h"
 #include "platform/Partitions.h"
 #include "platform/PlatformThreadData.h"
@@ -84,10 +86,16 @@
     PlatformThreadData::current();
 
     StringImpl::freezeStaticStrings();
+
+    // Creates HTMLParserThread::shared, but does not start the thread.
+    HTMLParserThread::init();
 }
 
 void shutdown()
 {
+    // Make sure we stop the HTMLParserThread before Platform::current() is cleared.
+    HTMLParserThread::shutdown();
+
     Partitions::shutdown();
 }
 
diff --git a/Source/core/OWNERS b/Source/core/OWNERS
index c82d8e6..28beb4c 100644
--- a/Source/core/OWNERS
+++ b/Source/core/OWNERS
@@ -1,4 +1,5 @@
 abarth@chromium.org
+acolwell@chromium.org
 adamk@chromium.org
 alexis.menard@intel.com
 apavlov@chromium.org
@@ -26,6 +27,7 @@
 jchaffraix@chromium.org
 jianli@chromium.org
 jochen@chromium.org
+junov@chromium.org
 kbr@chromium.org
 kenneth.r.christiansen@intel.com
 kinuko@chromium.org
@@ -37,6 +39,7 @@
 pdr@chromium.org
 pfeldman@chromium.org
 pkasting@chromium.org
+rob.buis@samsung.com
 schenney@chromium.org
 senorblanco@chromium.org
 steveblock@chromium.org
diff --git a/Source/core/accessibility/AXARIAGrid.h b/Source/core/accessibility/AXARIAGrid.h
index e108151..652512b 100644
--- a/Source/core/accessibility/AXARIAGrid.h
+++ b/Source/core/accessibility/AXARIAGrid.h
@@ -37,7 +37,7 @@
 class AXTableCell;
 class AXTableHeaderContainer;
 
-class AXARIAGrid : public AXTable {
+class AXARIAGrid FINAL : public AXTable {
 
 private:
     explicit AXARIAGrid(RenderObject*);
diff --git a/Source/core/accessibility/AXARIAGridCell.h b/Source/core/accessibility/AXARIAGridCell.h
index 0bf53fb..4e34c69 100644
--- a/Source/core/accessibility/AXARIAGridCell.h
+++ b/Source/core/accessibility/AXARIAGridCell.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class AXARIAGridCell : public AXTableCell {
+class AXARIAGridCell FINAL : public AXTableCell {
 
 private:
     explicit AXARIAGridCell(RenderObject*);
@@ -47,7 +47,7 @@
     virtual void columnIndexRange(pair<unsigned, unsigned>& columnRange) OVERRIDE;
 
 protected:
-    virtual AXObject* parentTable() const;
+    virtual AXObject* parentTable() const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/accessibility/AXARIAGridRow.h b/Source/core/accessibility/AXARIAGridRow.h
index 54dc1f0..1ec9528 100644
--- a/Source/core/accessibility/AXARIAGridRow.h
+++ b/Source/core/accessibility/AXARIAGridRow.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class AXARIAGridRow : public AXTableRow {
+class AXARIAGridRow FINAL : public AXTableRow {
 
 private:
     explicit AXARIAGridRow(RenderObject*);
@@ -47,7 +47,7 @@
     virtual AXObject* headerObject() OVERRIDE;
 
 private:
-    virtual bool isARIATreeGridRow() const;
+    virtual bool isARIATreeGridRow() const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/accessibility/AXImageMapLink.h b/Source/core/accessibility/AXImageMapLink.h
index 08276a8..bbef806 100644
--- a/Source/core/accessibility/AXImageMapLink.h
+++ b/Source/core/accessibility/AXImageMapLink.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class AXImageMapLink : public AXMockObject {
+class AXImageMapLink FINAL : public AXMockObject {
 
 private:
     AXImageMapLink();
@@ -57,7 +57,7 @@
     virtual Element* anchorElement() const OVERRIDE;
     virtual Element* actionElement() const OVERRIDE;
     virtual KURL url() const OVERRIDE;
-    virtual bool isLink() const { return true; }
+    virtual bool isLink() const OVERRIDE { return true; }
     virtual bool isLinked() const OVERRIDE { return true; }
     virtual String title() const OVERRIDE;
     virtual String accessibilityDescription() const OVERRIDE;
diff --git a/Source/core/accessibility/AXInlineTextBox.h b/Source/core/accessibility/AXInlineTextBox.h
index b80b558..715a62e 100644
--- a/Source/core/accessibility/AXInlineTextBox.h
+++ b/Source/core/accessibility/AXInlineTextBox.h
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-class AXInlineTextBox : public AXObject {
+class AXInlineTextBox FINAL : public AXObject {
 
 private:
     AXInlineTextBox(PassRefPtr<AbstractInlineTextBox>);
diff --git a/Source/core/accessibility/AXList.h b/Source/core/accessibility/AXList.h
index cba99d5..861b5d9 100644
--- a/Source/core/accessibility/AXList.h
+++ b/Source/core/accessibility/AXList.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class AXList : public AXRenderObject {
+class AXList FINAL : public AXRenderObject {
 
 private:
     explicit AXList(RenderObject*);
@@ -41,14 +41,14 @@
     static PassRefPtr<AXList> create(RenderObject*);
     virtual ~AXList();
 
-    virtual bool isList() const { return true; }
+    virtual bool isList() const OVERRIDE { return true; }
     bool isUnorderedList() const;
     bool isOrderedList() const;
     bool isDescriptionList() const;
 
-    virtual AccessibilityRole roleValue() const { return ListRole; }
+    virtual AccessibilityRole roleValue() const OVERRIDE { return ListRole; }
 private:
-    virtual bool computeAccessibilityIsIgnored() const;
+    virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/accessibility/AXListBox.h b/Source/core/accessibility/AXListBox.h
index 6d46e0e..6a055a6 100644
--- a/Source/core/accessibility/AXListBox.h
+++ b/Source/core/accessibility/AXListBox.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class AXListBox : public AXRenderObject {
+class AXListBox FINAL : public AXRenderObject {
 
 private:
     explicit AXListBox(RenderObject*);
diff --git a/Source/core/accessibility/AXListBoxOption.cpp b/Source/core/accessibility/AXListBoxOption.cpp
index 31eb9d1..3708ccd 100644
--- a/Source/core/accessibility/AXListBoxOption.cpp
+++ b/Source/core/accessibility/AXListBoxOption.cpp
@@ -60,7 +60,7 @@
     if (!m_optionElement)
         return false;
 
-    if (isHTMLOptGroupElement(m_optionElement))
+    if (m_optionElement->hasTagName(optgroupTag))
         return false;
 
     if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
@@ -155,7 +155,7 @@
     if (m_optionElement->hasTagName(optionTag))
         return toHTMLOptionElement(m_optionElement)->text();
 
-    if (isHTMLOptGroupElement(m_optionElement))
+    if (m_optionElement->hasTagName(optgroupTag))
         return toHTMLOptGroupElement(m_optionElement)->groupLabelText();
 
     return String();
@@ -201,7 +201,7 @@
     if (m_optionElement->hasTagName(optionTag))
         return toHTMLOptionElement(m_optionElement)->ownerSelectElement();
 
-    if (isHTMLOptGroupElement(m_optionElement))
+    if (m_optionElement->hasTagName(optgroupTag))
         return toHTMLOptGroupElement(m_optionElement)->ownerSelectElement();
 
     return 0;
diff --git a/Source/core/accessibility/AXListBoxOption.h b/Source/core/accessibility/AXListBoxOption.h
index 02e0433..6ea9ab8 100644
--- a/Source/core/accessibility/AXListBoxOption.h
+++ b/Source/core/accessibility/AXListBoxOption.h
@@ -40,7 +40,7 @@
 class HTMLElement;
 class HTMLSelectElement;
 
-class AXListBoxOption : public AXObject {
+class AXListBoxOption FINAL : public AXObject {
 
 private:
     AXListBoxOption();
diff --git a/Source/core/accessibility/AXMediaControls.cpp b/Source/core/accessibility/AXMediaControls.cpp
index 5f42630..52eebbe 100644
--- a/Source/core/accessibility/AXMediaControls.cpp
+++ b/Source/core/accessibility/AXMediaControls.cpp
@@ -113,14 +113,6 @@
         return queryString(WebLocalizedString::AXMediaMuteButton);
     case MediaPlayButton:
         return queryString(WebLocalizedString::AXMediaPlayButton);
-    case MediaSeekBackButton:
-        return queryString(WebLocalizedString::AXMediaSeekBackButton);
-    case MediaSeekForwardButton:
-        return queryString(WebLocalizedString::AXMediaSeekForwardButton);
-    case MediaRewindButton:
-        return queryString(WebLocalizedString::AXMediaRewindButton);
-    case MediaReturnToRealtimeButton:
-        return queryString(WebLocalizedString::AXMediaReturnToRealTime);
     case MediaUnMuteButton:
         return queryString(WebLocalizedString::AXMediaUnMuteButton);
     case MediaPauseButton:
@@ -151,14 +143,6 @@
         return queryString(WebLocalizedString::AXMediaMuteButtonHelp);
     case MediaPlayButton:
         return queryString(WebLocalizedString::AXMediaPlayButtonHelp);
-    case MediaSeekBackButton:
-        return queryString(WebLocalizedString::AXMediaSeekBackButtonHelp);
-    case MediaSeekForwardButton:
-        return queryString(WebLocalizedString::AXMediaSeekForwardButtonHelp);
-    case MediaRewindButton:
-        return queryString(WebLocalizedString::AXMediaRewindButtonHelp);
-    case MediaReturnToRealtimeButton:
-        return queryString(WebLocalizedString::AXMediaReturnToRealTimeHelp);
     case MediaUnMuteButton:
         return queryString(WebLocalizedString::AXMediaUnMuteButtonHelp);
     case MediaPauseButton:
@@ -193,10 +177,6 @@
     case MediaExitFullscreenButton:
     case MediaMuteButton:
     case MediaPlayButton:
-    case MediaSeekBackButton:
-    case MediaSeekForwardButton:
-    case MediaRewindButton:
-    case MediaReturnToRealtimeButton:
     case MediaUnMuteButton:
     case MediaPauseButton:
     case MediaShowClosedCaptionsButton:
diff --git a/Source/core/accessibility/AXMediaControls.h b/Source/core/accessibility/AXMediaControls.h
index cbf6a2f..0bc8582 100644
--- a/Source/core/accessibility/AXMediaControls.h
+++ b/Source/core/accessibility/AXMediaControls.h
@@ -43,19 +43,19 @@
 
     virtual AccessibilityRole roleValue() const OVERRIDE;
 
-    virtual String title() const OVERRIDE;
+    virtual String title() const OVERRIDE FINAL;
     virtual String accessibilityDescription() const OVERRIDE;
     virtual String helpText() const OVERRIDE;
 
 protected:
     explicit AccessibilityMediaControl(RenderObject*);
     MediaControlElementType controlType() const;
-    virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE;
+    virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE FINAL;
     virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
 };
 
 
-class AccessibilityMediaTimeline : public AXSlider {
+class AccessibilityMediaTimeline FINAL : public AXSlider {
 
 public:
     static PassRefPtr<AXObject> create(RenderObject*);
@@ -70,7 +70,7 @@
 };
 
 
-class AXMediaControlsContainer : public AccessibilityMediaControl {
+class AXMediaControlsContainer FINAL : public AccessibilityMediaControl {
 
 public:
     static PassRefPtr<AXObject> create(RenderObject*);
@@ -88,7 +88,7 @@
 };
 
 
-class AccessibilityMediaTimeDisplay : public AccessibilityMediaControl {
+class AccessibilityMediaTimeDisplay FINAL : public AccessibilityMediaControl {
 
 public:
     static PassRefPtr<AXObject> create(RenderObject*);
diff --git a/Source/core/accessibility/AXMenuList.h b/Source/core/accessibility/AXMenuList.h
index b7e3be0..93efd64 100644
--- a/Source/core/accessibility/AXMenuList.h
+++ b/Source/core/accessibility/AXMenuList.h
@@ -35,7 +35,7 @@
 class HTMLOptionElement;
 class RenderMenuList;
 
-class AXMenuList : public AXRenderObject {
+class AXMenuList FINAL : public AXRenderObject {
 public:
     static PassRefPtr<AXMenuList> create(RenderMenuList* renderer);
 
diff --git a/Source/core/accessibility/AXMenuListOption.h b/Source/core/accessibility/AXMenuListOption.h
index 8c20d8d..1faaca4 100644
--- a/Source/core/accessibility/AXMenuListOption.h
+++ b/Source/core/accessibility/AXMenuListOption.h
@@ -33,7 +33,7 @@
 class AXMenuListPopup;
 class HTMLElement;
 
-class AXMenuListOption : public AXMockObject {
+class AXMenuListOption FINAL : public AXMockObject {
 public:
     static PassRefPtr<AXMenuListOption> create() { return adoptRef(new AXMenuListOption); }
 
diff --git a/Source/core/accessibility/AXMenuListPopup.h b/Source/core/accessibility/AXMenuListPopup.h
index 44b8917..f9f204d 100644
--- a/Source/core/accessibility/AXMenuListPopup.h
+++ b/Source/core/accessibility/AXMenuListPopup.h
@@ -35,7 +35,7 @@
 class HTMLElement;
 class HTMLSelectElement;
 
-class AXMenuListPopup : public AXMockObject {
+class AXMenuListPopup FINAL : public AXMockObject {
 public:
     static PassRefPtr<AXMenuListPopup> create() { return adoptRef(new AXMenuListPopup); }
 
diff --git a/Source/core/accessibility/AXMockObject.h b/Source/core/accessibility/AXMockObject.h
index edd6179..fcb50aa 100644
--- a/Source/core/accessibility/AXMockObject.h
+++ b/Source/core/accessibility/AXMockObject.h
@@ -37,7 +37,7 @@
 public:
     virtual ~AXMockObject();
 
-    virtual void setParent(AXObject* parent) { m_parent = parent; };
+    virtual void setParent(AXObject* parent) { m_parent = parent; }
 
     // AXObject overrides.
     virtual AXObject* parentObject() const OVERRIDE { return m_parent; }
@@ -50,7 +50,7 @@
     virtual void detachFromParent() OVERRIDE { m_parent = 0; }
 
 private:
-    virtual bool isMockObject() const OVERRIDE { return true; }
+    virtual bool isMockObject() const OVERRIDE FINAL { return true; }
 
     virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
 };
diff --git a/Source/core/accessibility/AXNodeObject.cpp b/Source/core/accessibility/AXNodeObject.cpp
index 439e7cd..f57327e 100644
--- a/Source/core/accessibility/AXNodeObject.cpp
+++ b/Source/core/accessibility/AXNodeObject.cpp
@@ -32,14 +32,12 @@
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Text.h"
-#include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLFieldSetElement.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLLabelElement.h"
 #include "core/html/HTMLLegendElement.h"
 #include "core/html/HTMLSelectElement.h"
-#include "core/html/HTMLTextAreaElement.h"
 #include "core/rendering/RenderObject.h"
 #include "platform/UserGestureIndicator.h"
 #include "wtf/text/StringBuilder.h"
@@ -209,7 +207,7 @@
         HTMLSelectElement* selectElement = toHTMLSelectElement(node());
         return selectElement->multiple() ? ListBoxRole : PopUpButtonRole;
     }
-    if (isHTMLTextAreaElement(node()))
+    if (node()->hasTagName(textareaTag))
         return TextAreaRole;
     if (headingLevel())
         return HeadingRole;
@@ -217,7 +215,7 @@
         return DivRole;
     if (node()->hasTagName(pTag))
         return ParagraphRole;
-    if (isHTMLLabelElement(node()))
+    if (node()->hasTagName(labelTag))
         return LabelRole;
     if (node()->isElementNode() && toElement(node())->isFocusable())
         return GroupRole;
@@ -346,7 +344,7 @@
     }
 
     for (Element* parent = element->parentElement(); parent; parent = parent->parentElement()) {
-        if (isHTMLLabelElement(parent))
+        if (parent->hasTagName(labelTag))
             return toHTMLLabelElement(parent);
     }
 
@@ -577,7 +575,7 @@
     if (!node)
         return false;
 
-    if (isHTMLTextAreaElement(node))
+    if (node->hasTagName(textareaTag))
         return true;
 
     if (node->hasTagName(inputTag)) {
@@ -706,7 +704,7 @@
     if (!node)
         return true;
 
-    if (isHTMLTextAreaElement(node))
+    if (node->hasTagName(textareaTag))
         return toHTMLFormControlElement(node)->isReadOnly();
 
     if (node->hasTagName(inputTag)) {
@@ -883,7 +881,7 @@
     if (!node)
         return String();
 
-    if (isNativeTextControl() && (isHTMLTextAreaElement(node) || node->hasTagName(inputTag)))
+    if (isNativeTextControl() && (node->hasTagName(textareaTag) || node->hasTagName(inputTag)))
         return toHTMLTextFormControlElement(node)->value();
 
     if (!node->isElementNode())
@@ -932,8 +930,10 @@
     if (!equalIgnoringCase(type, "color"))
         return;
 
-    // HTMLInputElement::value always returns a string parseable by Color().
-    Color color(input->value());
+    // HTMLInputElement::value always returns a string parseable by Color.
+    Color color;
+    bool success = color.setFromString(input->value());
+    ASSERT_UNUSED(success, success);
     r = color.red();
     g = color.green();
     b = color.blue();
@@ -1447,7 +1447,7 @@
     // search up the DOM tree for an anchor element
     // NOTE: this assumes that any non-image with an anchor is an HTMLAnchorElement
     for ( ; node; node = node->parentNode()) {
-        if (isHTMLAnchorElement(node) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
+        if (node->hasTagName(aTag) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
             return toElement(node);
     }
 
@@ -1495,7 +1495,7 @@
 
     // find if this has a parent that is a label
     for (Node* parentNode = node(); parentNode; parentNode = parentNode->parentNode()) {
-        if (isHTMLLabelElement(parentNode))
+        if (parentNode->hasTagName(labelTag))
             return toHTMLLabelElement(parentNode);
     }
 
diff --git a/Source/core/accessibility/AXNodeObject.h b/Source/core/accessibility/AXNodeObject.h
index 829aaf1..9daabec 100644
--- a/Source/core/accessibility/AXNodeObject.h
+++ b/Source/core/accessibility/AXNodeObject.h
@@ -102,52 +102,52 @@
     virtual void init() OVERRIDE;
     virtual void detach() OVERRIDE;
     virtual bool isDetached() const OVERRIDE { return !m_node; }
-    virtual bool isAXNodeObject() const OVERRIDE { return true; }
+    virtual bool isAXNodeObject() const OVERRIDE FINAL { return true; }
 
     // Check object role or purpose.
-    virtual bool isAnchor() const OVERRIDE;
+    virtual bool isAnchor() const OVERRIDE FINAL;
     virtual bool isControl() const OVERRIDE;
-    virtual bool isFieldset() const OVERRIDE;
-    virtual bool isHeading() const OVERRIDE;
-    virtual bool isHovered() const OVERRIDE;
-    virtual bool isImage() const OVERRIDE;
+    virtual bool isFieldset() const OVERRIDE FINAL;
+    virtual bool isHeading() const OVERRIDE FINAL;
+    virtual bool isHovered() const OVERRIDE FINAL;
+    virtual bool isImage() const OVERRIDE FINAL;
     bool isImageButton() const;
-    virtual bool isInputImage() const OVERRIDE;
-    virtual bool isLink() const;
-    virtual bool isMenu() const OVERRIDE;
-    virtual bool isMenuButton() const OVERRIDE;
+    virtual bool isInputImage() const OVERRIDE FINAL;
+    virtual bool isLink() const OVERRIDE FINAL;
+    virtual bool isMenu() const OVERRIDE FINAL;
+    virtual bool isMenuButton() const OVERRIDE FINAL;
     virtual bool isMultiSelectable() const OVERRIDE;
     bool isNativeImage() const;
-    virtual bool isNativeTextControl() const OVERRIDE;
-    virtual bool isNonNativeTextControl() const OVERRIDE;
-    virtual bool isPasswordField() const OVERRIDE;
+    virtual bool isNativeTextControl() const OVERRIDE FINAL;
+    virtual bool isNonNativeTextControl() const OVERRIDE FINAL;
+    virtual bool isPasswordField() const OVERRIDE FINAL;
     virtual bool isProgressIndicator() const OVERRIDE;
     virtual bool isSlider() const OVERRIDE;
 
     // Check object state.
-    virtual bool isChecked() const OVERRIDE;
-    virtual bool isClickable() const OVERRIDE;
+    virtual bool isChecked() const OVERRIDE FINAL;
+    virtual bool isClickable() const OVERRIDE FINAL;
     virtual bool isEnabled() const OVERRIDE;
-    virtual bool isIndeterminate() const OVERRIDE;
-    virtual bool isPressed() const OVERRIDE;
+    virtual bool isIndeterminate() const OVERRIDE FINAL;
+    virtual bool isPressed() const OVERRIDE FINAL;
     virtual bool isReadOnly() const OVERRIDE;
-    virtual bool isRequired() const OVERRIDE;
+    virtual bool isRequired() const OVERRIDE FINAL;
 
     // Check whether certain properties can be modified.
     virtual bool canSetFocusAttribute() const OVERRIDE;
     virtual bool canSetValueAttribute() const OVERRIDE;
 
     // Properties of static elements.
-    virtual bool canvasHasFallbackContent() const OVERRIDE;
+    virtual bool canvasHasFallbackContent() const OVERRIDE FINAL;
     virtual bool exposesTitleUIElement() const OVERRIDE;
-    virtual int headingLevel() const OVERRIDE;
-    virtual unsigned hierarchicalLevel() const OVERRIDE;
+    virtual int headingLevel() const OVERRIDE FINAL;
+    virtual unsigned hierarchicalLevel() const OVERRIDE FINAL;
     virtual String text() const OVERRIDE;
     virtual AXObject* titleUIElement() const OVERRIDE;
 
     // Properties of interactive elements.
-    virtual AccessibilityButtonState checkboxOrRadioValue() const OVERRIDE;
-    virtual void colorValue(int& r, int& g, int& b) const OVERRIDE;
+    virtual AccessibilityButtonState checkboxOrRadioValue() const OVERRIDE FINAL;
+    virtual void colorValue(int& r, int& g, int& b) const OVERRIDE FINAL;
     virtual String valueDescription() const OVERRIDE;
     virtual float valueForRange() const OVERRIDE;
     virtual float maxValueForRange() const OVERRIDE;
@@ -155,9 +155,9 @@
     virtual String stringValue() const OVERRIDE;
 
     // ARIA attributes.
-    virtual String ariaDescribedByAttribute() const;
-    virtual String ariaLabeledByAttribute() const OVERRIDE;
-    virtual AccessibilityRole ariaRoleAttribute() const OVERRIDE;
+    virtual String ariaDescribedByAttribute() const OVERRIDE FINAL;
+    virtual String ariaLabeledByAttribute() const OVERRIDE FINAL;
+    virtual AccessibilityRole ariaRoleAttribute() const OVERRIDE FINAL;
 
     // Accessibility Text.
     virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE;
@@ -184,21 +184,21 @@
     void insertChild(AXObject*, unsigned index);
 
     // DOM and Render tree access.
-    virtual Element* actionElement() const OVERRIDE;
+    virtual Element* actionElement() const OVERRIDE FINAL;
     virtual Element* anchorElement() const OVERRIDE;
     virtual Document* document() const OVERRIDE;
     virtual Node* node() const OVERRIDE { return m_node; }
 
     // Modify or take an action on an object.
-    virtual void setFocused(bool) OVERRIDE;
-    virtual void increment() OVERRIDE;
-    virtual void decrement() OVERRIDE;
+    virtual void setFocused(bool) OVERRIDE FINAL;
+    virtual void increment() OVERRIDE FINAL;
+    virtual void decrement() OVERRIDE FINAL;
 
     // Notifications that this object may have changed.
     virtual void childrenChanged() OVERRIDE;
-    virtual void selectionChanged() OVERRIDE;
+    virtual void selectionChanged() OVERRIDE FINAL;
     virtual void textChanged() OVERRIDE;
-    virtual void updateAccessibilityRole() OVERRIDE;
+    virtual void updateAccessibilityRole() OVERRIDE FINAL;
 
 private:
     Node* m_node;
diff --git a/Source/core/accessibility/AXObject.cpp b/Source/core/accessibility/AXObject.cpp
index 24f3285..03cf996 100644
--- a/Source/core/accessibility/AXObject.cpp
+++ b/Source/core/accessibility/AXObject.cpp
@@ -183,6 +183,25 @@
     return role == ButtonRole || role == PopUpButtonRole || role == ToggleButtonRole;
 }
 
+bool AXObject::isLandmarkRelated() const
+{
+    switch (roleValue()) {
+    case ApplicationRole:
+    case ArticleRole:
+    case BannerRole:
+    case ComplementaryRole:
+    case ContentInfoRole:
+    case FooterRole:
+    case MainRole:
+    case NavigationRole:
+    case RegionRole:
+    case SearchRole:
+        return true;
+    default:
+        return false;
+    }
+}
+
 bool AXObject::isMenuRelated() const
 {
     switch (roleValue()) {
diff --git a/Source/core/accessibility/AXObject.h b/Source/core/accessibility/AXObject.h
index e66ba18..b3fa7fd 100644
--- a/Source/core/accessibility/AXObject.h
+++ b/Source/core/accessibility/AXObject.h
@@ -322,6 +322,7 @@
     virtual bool isImage() const { return false; }
     virtual bool isImageMapLink() const { return false; }
     virtual bool isInputImage() const { return false; }
+    bool isLandmarkRelated() const;
     virtual bool isLink() const { return false; }
     virtual bool isList() const { return false; }
     bool isListItem() const { return roleValue() == ListItemRole; }
@@ -340,7 +341,6 @@
     virtual bool isProgressIndicator() const { return false; }
     bool isRadioButton() const { return roleValue() == RadioButtonRole; }
     bool isScrollbar() const { return roleValue() == ScrollBarRole; }
-    bool isSeamlessWebArea() const { return roleValue() == SeamlessWebAreaRole; }
     virtual bool isSlider() const { return false; }
     virtual bool isSpinButton() const { return roleValue() == SpinButtonRole; }
     virtual bool isSpinButtonPart() const { return false; }
@@ -513,7 +513,6 @@
 
     // Selected text.
     virtual PlainTextRange selectedTextRange() const { return PlainTextRange(); }
-    virtual String selectedText() const { return String(); }
 
     // Modify or take an action on an object.
     virtual void increment() { }
diff --git a/Source/core/accessibility/AXObjectCache.cpp b/Source/core/accessibility/AXObjectCache.cpp
index 34d6f63..0c74d9a 100644
--- a/Source/core/accessibility/AXObjectCache.cpp
+++ b/Source/core/accessibility/AXObjectCache.cpp
@@ -167,7 +167,7 @@
     if (!focusedNode)
         focusedNode = focusedDocument;
 
-    if (isHTMLAreaElement(focusedNode))
+    if (focusedNode->hasTagName(areaTag))
         return focusedImageMapUIElement(toHTMLAreaElement(focusedNode));
 
     AXObject* obj = focusedNode->document().axObjectCache()->getOrCreate(focusedNode);
@@ -343,6 +343,11 @@
     // Will crash later if we have two objects for the same widget.
     ASSERT(!get(widget));
 
+    // Catch the case if an (unsupported) widget type is used. Only FrameView and ScrollBar are supported now.
+    ASSERT(newObj);
+    if (!newObj)
+        return 0;
+
     getAXID(newObj.get());
 
     m_widgetObjectMapping.set(widget, newObj->axObjectID());
@@ -826,7 +831,7 @@
         handleAriaRoleChanged(element);
     else if (attrName == altAttr || attrName == titleAttr)
         textChanged(element);
-    else if (attrName == forAttr && isHTMLLabelElement(element))
+    else if (attrName == forAttr && element->hasTagName(labelTag))
         labelChanged(element);
 
     if (!attrName.localName().string().startsWith("aria-"))
diff --git a/Source/core/accessibility/AXProgressIndicator.h b/Source/core/accessibility/AXProgressIndicator.h
index 13ea890..1d4dc78 100644
--- a/Source/core/accessibility/AXProgressIndicator.h
+++ b/Source/core/accessibility/AXProgressIndicator.h
@@ -28,12 +28,12 @@
 class HTMLProgressElement;
 class RenderProgress;
 
-class AXProgressIndicator : public AXRenderObject {
+class AXProgressIndicator FINAL : public AXRenderObject {
 public:
     static PassRefPtr<AXProgressIndicator> create(RenderProgress*);
 
 private:
-    virtual AccessibilityRole roleValue() const { return ProgressIndicatorRole; }
+    virtual AccessibilityRole roleValue() const OVERRIDE { return ProgressIndicatorRole; }
 
     virtual bool isProgressIndicator() const OVERRIDE { return true; }
 
diff --git a/Source/core/accessibility/AXRenderObject.cpp b/Source/core/accessibility/AXRenderObject.cpp
index 5951359..07eea95 100644
--- a/Source/core/accessibility/AXRenderObject.cpp
+++ b/Source/core/accessibility/AXRenderObject.cpp
@@ -44,7 +44,6 @@
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/frame/Frame.h"
-#include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLLabelElement.h"
 #include "core/html/HTMLOptionElement.h"
@@ -302,12 +301,8 @@
     if (node && node->hasTagName(canvasTag) && m_renderer->isCanvas())
         return CanvasRole;
 
-    if (cssBox && cssBox->isRenderView()) {
-        // If the iframe is seamless, it should not be announced as a web area to AT clients.
-        if (document() && document()->shouldDisplaySeamlesslyWithParent())
-            return SeamlessWebAreaRole;
+    if (cssBox && cssBox->isRenderView())
         return WebAreaRole;
-    }
 
     if (cssBox && cssBox->isTextField())
         return TextFieldRole;
@@ -362,7 +357,7 @@
     if (node && node->hasTagName(pTag))
         return ParagraphRole;
 
-    if (node && isHTMLLabelElement(node))
+    if (node && node->hasTagName(labelTag))
         return LabelRole;
 
     if (node && node->hasTagName(divTag))
@@ -393,7 +388,7 @@
         return DialogRole;
 
     // The HTML element should not be exposed as an element. That's what the RenderView element does.
-    if (node && isHTMLHtmlElement(node))
+    if (node && node->hasTagName(htmlTag))
         return IgnoredRole;
 
     // There should only be one banner/contentInfo per page. If header/footer are being used within an article or section
@@ -475,7 +470,7 @@
         return false;
 
     Element* anchor = anchorElement();
-    if (!anchor || !isHTMLAnchorElement(anchor))
+    if (!anchor || !anchor->hasTagName(aTag))
         return false;
 
     return !toHTMLAnchorElement(anchor)->href().isEmpty();
@@ -638,19 +633,23 @@
         if (m_renderer->isBR() || !renderText->firstTextBox())
             return true;
 
-        // static text beneath TextControls is reported along with the text control text so it's ignored.
+        // Don't ignore static text in editable text controls.
         for (AXObject* parent = parentObject(); parent; parent = parent->parentObject()) {
-            if (parent->roleValue() == TextFieldRole)
-                return true;
+            if (parent->roleValue() == TextFieldRole || parent->roleValue() == TextAreaRole)
+                return false;
         }
 
         // text elements that are just empty whitespace should not be returned
+        // FIXME(dmazzoni): we probably shouldn't ignore this if the style is 'pre', or similar...
         return renderText->text().impl()->containsOnlyWhitespace();
     }
 
     if (isHeading())
         return false;
 
+    if (isLandmarkRelated())
+        return false;
+
     if (isLink())
         return false;
 
@@ -663,7 +662,7 @@
 
     // don't ignore labels, because they serve as TitleUIElements
     Node* node = m_renderer->node();
-    if (node && isHTMLLabelElement(node))
+    if (node && node->hasTagName(labelTag))
         return false;
 
     // Anything that is content editable should not be ignored.
@@ -737,7 +736,7 @@
         // Otherwise fall through; use presence of help text, title, or description to decide.
     }
 
-    if (isWebArea() || isSeamlessWebArea() || m_renderer->isListMarker())
+    if (isWebArea() || m_renderer->isListMarker())
         return false;
 
     // Using the help text, title or accessibility description (so we
@@ -809,7 +808,7 @@
 
 KURL AXRenderObject::url() const
 {
-    if (isAnchor() && isHTMLAnchorElement(m_renderer->node())) {
+    if (isAnchor() && m_renderer->node()->hasTagName(aTag)) {
         if (HTMLAnchorElement* anchor = toHTMLAnchorElement(anchorElement()))
             return anchor->href();
     }
@@ -1265,7 +1264,7 @@
         return 0;
     Node* node = hitTestResult.innerNode()->deprecatedShadowAncestorNode();
 
-    if (isHTMLAreaElement(node))
+    if (node->hasTagName(areaTag))
         return accessibilityImageMapHitTest(toHTMLAreaElement(node), point);
 
     if (node->hasTagName(optionTag))
@@ -1327,7 +1326,7 @@
         return axObjectCache()->getOrCreate(parentObj);
 
     // WebArea's parent should be the scroll view containing it.
-    if (isWebArea() || isSeamlessWebArea())
+    if (isWebArea())
         return axObjectCache()->getOrCreate(m_renderer->frame()->view());
 
     return 0;
@@ -1336,7 +1335,7 @@
 AXObject* AXRenderObject::parentObjectIfExists() const
 {
     // WebArea's parent should be the scroll view containing it.
-    if (isWebArea() || isSeamlessWebArea())
+    if (isWebArea())
         return axObjectCache()->get(m_renderer->frame()->view());
 
     return axObjectCache()->get(renderParentObject());
@@ -1526,7 +1525,7 @@
     // NOTE: this assumes that any non-image with an anchor is an HTMLAnchorElement
     Node* node = currRenderer->node();
     for ( ; node; node = node->parentNode()) {
-        if (isHTMLAnchorElement(node) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
+        if (node->hasTagName(aTag) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
             return toElement(node);
     }
 
@@ -1568,24 +1567,6 @@
     return m_renderer->frame()->selection().selection();
 }
 
-String AXRenderObject::selectedText() const
-{
-    ASSERT(isTextControl());
-
-    if (isPasswordField())
-        return String(); // need to return something distinct from empty string
-
-    if (isNativeTextControl() && m_renderer->isTextControl()) {
-        HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
-        return textControl->selectedText();
-    }
-
-    if (ariaRoleAttribute() == UnknownRole)
-        return String();
-
-    return stringForRange(ariaSelectedTextRange());
-}
-
 //
 // Modify or take an action on an object.
 //
@@ -1801,23 +1782,6 @@
     }
 }
 
-// A substring of the text associated with this accessibility object that is
-// specified by the given character range.
-String AXRenderObject::stringForRange(const PlainTextRange& range) const
-{
-    if (!range.length)
-        return String();
-
-    if (!isTextControl())
-        return String();
-
-    String elementText = isPasswordField() ? String() : text();
-    if (range.start + range.length > elementText.length())
-        return String();
-
-    return elementText.substring(range.start, range.length);
-}
-
 //
 // Private.
 //
@@ -1937,7 +1901,7 @@
         return 0;
 
     // Right now, we do not support ARIA links as internal link elements
-    if (!isHTMLAnchorElement(element))
+    if (!element->hasTagName(aTag))
         return 0;
     HTMLAnchorElement* anchor = toHTMLAnchorElement(element);
 
@@ -2198,7 +2162,7 @@
 
     for (Element* current = ElementTraversal::firstWithin(*map); current; current = ElementTraversal::next(*current, map)) {
         // add an <area> element for this child if it has a link
-        if (isHTMLAreaElement(current) && current->isLink()) {
+        if (current->hasTagName(areaTag) && current->isLink()) {
             AXImageMapLink* areaObject = toAXImageMapLink(axObjectCache()->getOrCreate(ImageMapLinkRole));
             areaObject->setHTMLAreaElement(toHTMLAreaElement(current));
             areaObject->setHTMLMapElement(map);
@@ -2338,7 +2302,7 @@
 
     if (obj->isText())
         toRenderText(obj)->absoluteQuads(quads, 0, RenderText::ClipToEllipsis);
-    else if (isWebArea() || isSeamlessWebArea() || obj->isSVGRoot())
+    else if (isWebArea() || obj->isSVGRoot())
         obj->absoluteQuads(quads);
     else
         obj->absoluteFocusRingQuads(quads);
@@ -2350,7 +2314,7 @@
         offsetBoundingBoxForRemoteSVGElement(result);
 
     // The size of the web area should be the content size, not the clipped size.
-    if ((isWebArea() || isSeamlessWebArea()) && obj->frame()->view())
+    if (isWebArea() && obj->frame()->view())
         result.setSize(obj->frame()->view()->contentsSize());
 
     // Checkboxes and radio buttons include their label as part of their rect.
diff --git a/Source/core/accessibility/AXRenderObject.h b/Source/core/accessibility/AXRenderObject.h
index 160d0d7..550554b 100644
--- a/Source/core/accessibility/AXRenderObject.h
+++ b/Source/core/accessibility/AXRenderObject.h
@@ -64,7 +64,7 @@
     virtual ~AXRenderObject();
 
     // Public, overridden from AXObject.
-    virtual RenderObject* renderer() const OVERRIDE { return m_renderer; }
+    virtual RenderObject* renderer() const OVERRIDE FINAL { return m_renderer; }
     virtual LayoutRect elementRect() const OVERRIDE;
 
     void setRenderer(RenderObject*);
@@ -73,7 +73,7 @@
     Document* topDocument() const;
     bool shouldNotifyActiveDescendant() const;
     bool needsToUpdateChildren() const { return m_childrenDirty; }
-    ScrollableArea* getScrollableAreaIfScrollable() const;
+    virtual ScrollableArea* getScrollableAreaIfScrollable() const OVERRIDE FINAL;
     virtual AccessibilityRole determineAccessibilityRole() OVERRIDE;
     void checkCachedElementRect() const;
     void updateCachedElementRect() const;
@@ -181,7 +181,6 @@
 
     // Selected text.
     virtual PlainTextRange selectedTextRange() const OVERRIDE;
-    virtual String selectedText() const OVERRIDE;
 
     // Modify or take an action on an object.
     virtual void setSelectedTextRange(const PlainTextRange&) OVERRIDE;
@@ -227,7 +226,6 @@
     bool inheritsPresentationalRole() const;
     LayoutRect computeElementRect() const;
     VisibleSelection selection() const;
-    String stringForRange(const PlainTextRange&) const;
     int indexForVisiblePosition(const VisiblePosition&) const;
 };
 
diff --git a/Source/core/accessibility/AXSVGRoot.h b/Source/core/accessibility/AXSVGRoot.h
index 4febd09..183cac2 100644
--- a/Source/core/accessibility/AXSVGRoot.h
+++ b/Source/core/accessibility/AXSVGRoot.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class AXSVGRoot : public AXRenderObject {
+class AXSVGRoot FINAL : public AXRenderObject {
 
 protected:
     explicit AXSVGRoot(RenderObject*);
diff --git a/Source/core/accessibility/AXScrollView.h b/Source/core/accessibility/AXScrollView.h
index cf7e291..5da75f3 100644
--- a/Source/core/accessibility/AXScrollView.h
+++ b/Source/core/accessibility/AXScrollView.h
@@ -34,10 +34,10 @@
 class Scrollbar;
 class ScrollView;
 
-class AXScrollView : public AXObject {
+class AXScrollView FINAL : public AXObject {
 public:
     static PassRefPtr<AXScrollView> create(ScrollView*);
-    virtual AccessibilityRole roleValue() const { return ScrollAreaRole; }
+    virtual AccessibilityRole roleValue() const OVERRIDE { return ScrollAreaRole; }
     ScrollView* scrollView() const { return m_scrollView; }
 
     virtual ~AXScrollView();
diff --git a/Source/core/accessibility/AXScrollbar.h b/Source/core/accessibility/AXScrollbar.h
index 42eaca2..ec9bef0 100644
--- a/Source/core/accessibility/AXScrollbar.h
+++ b/Source/core/accessibility/AXScrollbar.h
@@ -35,7 +35,7 @@
 
 class Scrollbar;
 
-class AXScrollbar : public AXMockObject {
+class AXScrollbar FINAL : public AXMockObject {
 public:
     static PassRefPtr<AXScrollbar> create(Scrollbar*);
 
@@ -44,7 +44,7 @@
 private:
     explicit AXScrollbar(Scrollbar*);
 
-    virtual void detachFromParent();
+    virtual void detachFromParent() OVERRIDE;
 
     virtual bool canSetValueAttribute() const OVERRIDE { return true; }
 
diff --git a/Source/core/accessibility/AXSlider.h b/Source/core/accessibility/AXSlider.h
index 54b8a1b..aa9d01b 100644
--- a/Source/core/accessibility/AXSlider.h
+++ b/Source/core/accessibility/AXSlider.h
@@ -47,22 +47,22 @@
 
 private:
     HTMLInputElement* element() const;
-    virtual AXObject* elementAccessibilityHitTest(const IntPoint&) const OVERRIDE;
+    virtual AXObject* elementAccessibilityHitTest(const IntPoint&) const OVERRIDE FINAL;
 
     virtual AccessibilityRole roleValue() const OVERRIDE { return SliderRole; }
-    virtual bool isSlider() const OVERRIDE { return true; }
-    virtual bool isControl() const OVERRIDE { return true; }
+    virtual bool isSlider() const OVERRIDE FINAL { return true; }
+    virtual bool isControl() const OVERRIDE FINAL { return true; }
 
-    virtual void addChildren() OVERRIDE;
+    virtual void addChildren() OVERRIDE FINAL;
 
-    virtual bool canSetValueAttribute() const OVERRIDE { return true; }
+    virtual bool canSetValueAttribute() const OVERRIDE FINAL { return true; }
     const AtomicString& getAttribute(const QualifiedName& attribute) const;
 
-    virtual void setValue(const String&) OVERRIDE;
-    virtual AccessibilityOrientation orientation() const OVERRIDE;
+    virtual void setValue(const String&) OVERRIDE FINAL;
+    virtual AccessibilityOrientation orientation() const OVERRIDE FINAL;
 };
 
-class AXSliderThumb : public AXMockObject {
+class AXSliderThumb FINAL : public AXMockObject {
 
 public:
     static PassRefPtr<AXSliderThumb> create();
diff --git a/Source/core/accessibility/AXSpinButton.h b/Source/core/accessibility/AXSpinButton.h
index 12ae3ad..b26e6f7 100644
--- a/Source/core/accessibility/AXSpinButton.h
+++ b/Source/core/accessibility/AXSpinButton.h
@@ -32,7 +32,7 @@
 
 namespace WebCore {
 
-class AXSpinButton : public AXMockObject {
+class AXSpinButton FINAL : public AXMockObject {
 public:
     static PassRefPtr<AXSpinButton> create();
     virtual ~AXSpinButton();
@@ -52,7 +52,7 @@
     SpinButtonElement* m_spinButtonElement;
 };
 
-class AXSpinButtonPart : public AXMockObject {
+class AXSpinButtonPart FINAL : public AXMockObject {
 public:
     static PassRefPtr<AXSpinButtonPart> create();
     virtual ~AXSpinButtonPart() { }
diff --git a/Source/core/accessibility/AXTable.cpp b/Source/core/accessibility/AXTable.cpp
index f9f7530..bccdc18 100644
--- a/Source/core/accessibility/AXTable.cpp
+++ b/Source/core/accessibility/AXTable.cpp
@@ -106,7 +106,7 @@
 
     RenderTable* table = toRenderTable(m_renderer);
     Node* tableNode = table->node();
-    if (!tableNode || !isHTMLTableElement(tableNode))
+    if (!tableNode || !tableNode->hasTagName(tableTag))
         return false;
 
     // if there is a caption element, summary, THEAD, or TFOOT section, it's most certainly a data table
@@ -535,7 +535,7 @@
 
     // see if there is a caption
     Node* tableElement = m_renderer->node();
-    if (tableElement && isHTMLTableElement(tableElement)) {
+    if (tableElement && tableElement->hasTagName(tableTag)) {
         HTMLTableCaptionElement* caption = toHTMLTableElement(tableElement)->caption();
         if (caption)
             title = caption->innerText();
diff --git a/Source/core/accessibility/AXTable.h b/Source/core/accessibility/AXTable.h
index bca782c..c8dc807 100644
--- a/Source/core/accessibility/AXTable.h
+++ b/Source/core/accessibility/AXTable.h
@@ -45,15 +45,15 @@
     static PassRefPtr<AXTable> create(RenderObject*);
     virtual ~AXTable();
 
-    virtual void init() OVERRIDE;
+    virtual void init() OVERRIDE FINAL;
 
-    virtual bool isAXTable() const OVERRIDE;
-    virtual bool isDataTable() const OVERRIDE;
+    virtual bool isAXTable() const OVERRIDE FINAL;
+    virtual bool isDataTable() const OVERRIDE FINAL;
 
-    virtual AccessibilityRole roleValue() const OVERRIDE;
+    virtual AccessibilityRole roleValue() const OVERRIDE FINAL;
 
     virtual void addChildren() OVERRIDE;
-    virtual void clearChildren() OVERRIDE;
+    virtual void clearChildren() OVERRIDE FINAL;
 
     // To be overridden by AXARIAGrid.
     virtual bool isAriaTable() const { return false; }
@@ -64,9 +64,9 @@
 
     unsigned columnCount();
     unsigned rowCount();
-    virtual int tableLevel() const OVERRIDE;
+    virtual int tableLevel() const OVERRIDE FINAL;
 
-    virtual String title() const OVERRIDE;
+    virtual String title() const OVERRIDE FINAL;
 
     // all the cells in the table
     void cells(AccessibilityChildrenVector&);
@@ -86,7 +86,7 @@
 
     bool hasARIARole() const;
     virtual bool isTableExposableThroughAccessibility() const;
-    virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+    virtual bool computeAccessibilityIsIgnored() const OVERRIDE FINAL;
 };
 
 DEFINE_AX_OBJECT_TYPE_CASTS(AXTable, isAXTable());
diff --git a/Source/core/accessibility/AXTableCell.h b/Source/core/accessibility/AXTableCell.h
index c62d0d3..205eb70 100644
--- a/Source/core/accessibility/AXTableCell.h
+++ b/Source/core/accessibility/AXTableCell.h
@@ -41,7 +41,7 @@
     static PassRefPtr<AXTableCell> create(RenderObject*);
     virtual ~AXTableCell();
 
-    virtual bool isTableCell() const OVERRIDE;
+    virtual bool isTableCell() const OVERRIDE FINAL;
 
     // fills in the start location and row span of cell
     virtual void rowIndexRange(pair<unsigned, unsigned>& rowRange);
@@ -51,13 +51,13 @@
 protected:
     virtual AXObject* parentTable() const;
     int m_rowIndex;
-    virtual AccessibilityRole determineAccessibilityRole() OVERRIDE;
+    virtual AccessibilityRole determineAccessibilityRole() OVERRIDE FINAL;
 
 private:
     // If a table cell is not exposed as a table cell, a TH element can serve as its title UI element.
-    virtual AXObject* titleUIElement() const OVERRIDE;
-    virtual bool exposesTitleUIElement() const OVERRIDE { return true; }
-    virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+    virtual AXObject* titleUIElement() const OVERRIDE FINAL;
+    virtual bool exposesTitleUIElement() const OVERRIDE FINAL { return true; }
+    virtual bool computeAccessibilityIsIgnored() const OVERRIDE FINAL;
 };
 
 DEFINE_AX_OBJECT_TYPE_CASTS(AXTableCell, isTableCell());
diff --git a/Source/core/accessibility/AXTableColumn.h b/Source/core/accessibility/AXTableColumn.h
index 9da3187..0163fff 100644
--- a/Source/core/accessibility/AXTableColumn.h
+++ b/Source/core/accessibility/AXTableColumn.h
@@ -36,7 +36,7 @@
 
 class RenderTableSection;
 
-class AXTableColumn : public AXMockObject {
+class AXTableColumn FINAL : public AXMockObject {
 
 private:
     AXTableColumn();
diff --git a/Source/core/accessibility/AXTableHeaderContainer.h b/Source/core/accessibility/AXTableHeaderContainer.h
index 3870aa7..3997784 100644
--- a/Source/core/accessibility/AXTableHeaderContainer.h
+++ b/Source/core/accessibility/AXTableHeaderContainer.h
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-class AXTableHeaderContainer : public AXMockObject {
+class AXTableHeaderContainer FINAL : public AXMockObject {
 
 private:
     AXTableHeaderContainer();
diff --git a/Source/core/accessibility/AXTableRow.h b/Source/core/accessibility/AXTableRow.h
index 90eca7f..37364cf 100644
--- a/Source/core/accessibility/AXTableRow.h
+++ b/Source/core/accessibility/AXTableRow.h
@@ -41,11 +41,11 @@
     static PassRefPtr<AXTableRow> create(RenderObject*);
     virtual ~AXTableRow();
 
-    virtual bool isTableRow() const OVERRIDE;
+    virtual bool isTableRow() const OVERRIDE FINAL;
 
     // retrieves the "row" header (a th tag in the rightmost column)
     virtual AXObject* headerObject();
-    virtual AXObject* parentTable() const;
+    AXObject* parentTable() const;
 
     void setRowIndex(int rowIndex) { m_rowIndex = rowIndex; }
     int rowIndex() const { return m_rowIndex; }
@@ -55,13 +55,13 @@
     void appendChild(AXObject*);
 
 protected:
-    virtual AccessibilityRole determineAccessibilityRole() OVERRIDE;
+    virtual AccessibilityRole determineAccessibilityRole() OVERRIDE FINAL;
 
 private:
     int m_rowIndex;
 
-    virtual AXObject* observableObject() const OVERRIDE;
-    virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+    virtual AXObject* observableObject() const OVERRIDE FINAL;
+    virtual bool computeAccessibilityIsIgnored() const OVERRIDE FINAL;
 };
 
 DEFINE_AX_OBJECT_TYPE_CASTS(AXTableRow, isTableRow());
diff --git a/Source/core/animation/ActiveAnimations.cpp b/Source/core/animation/ActiveAnimations.cpp
index d27161d..317722a 100644
--- a/Source/core/animation/ActiveAnimations.cpp
+++ b/Source/core/animation/ActiveAnimations.cpp
@@ -31,15 +31,12 @@
 #include "config.h"
 #include "core/animation/ActiveAnimations.h"
 
-#include "core/frame/animation/AnimationController.h"
 #include "core/rendering/RenderObject.h"
 
 namespace WebCore {
 
 bool shouldCompositeForActiveAnimations(const RenderObject& renderer)
 {
-    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
-
     if (!renderer.node() || !renderer.node()->isElementNode())
         return false;
 
@@ -56,8 +53,6 @@
 
 bool hasActiveAnimations(const RenderObject& renderer, CSSPropertyID property)
 {
-    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
-
     if (!renderer.node() || !renderer.node()->isElementNode())
         return false;
 
@@ -70,8 +65,6 @@
 
 bool hasActiveAnimationsOnCompositor(const RenderObject& renderer, CSSPropertyID property)
 {
-    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
-
     if (!renderer.node() || !renderer.node()->isElementNode())
         return false;
 
diff --git a/Source/core/animation/AnimatableClipPathOperation.cpp b/Source/core/animation/AnimatableClipPathOperation.cpp
index f539df4..e72221b 100644
--- a/Source/core/animation/AnimatableClipPathOperation.cpp
+++ b/Source/core/animation/AnimatableClipPathOperation.cpp
@@ -33,19 +33,28 @@
 
 namespace WebCore {
 
-PassRefPtr<AnimatableValue> AnimatableClipPathOperation::interpolateTo(const AnimatableValue* value, double fraction) const
+bool AnimatableClipPathOperation::usesDefaultInterpolationWith(const AnimatableValue* value) const
 {
     const AnimatableClipPathOperation* toOperation = toAnimatableClipPathOperation(value);
 
     if (m_operation->type() != ClipPathOperation::SHAPE || toOperation->m_operation->type() != ClipPathOperation::SHAPE)
-        return defaultInterpolateTo(this, value, fraction);
+        return true;
 
     const BasicShape* fromShape = toShapeClipPathOperation(clipPathOperation())->basicShape();
     const BasicShape* toShape = toShapeClipPathOperation(toOperation->clipPathOperation())->basicShape();
 
-    if (!fromShape->canBlend(toShape))
+    return !fromShape->canBlend(toShape);
+}
+
+PassRefPtr<AnimatableValue> AnimatableClipPathOperation::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+    if (usesDefaultInterpolationWith(value))
         return defaultInterpolateTo(this, value, fraction);
 
+    const AnimatableClipPathOperation* toOperation = toAnimatableClipPathOperation(value);
+    const BasicShape* fromShape = toShapeClipPathOperation(clipPathOperation())->basicShape();
+    const BasicShape* toShape = toShapeClipPathOperation(toOperation->clipPathOperation())->basicShape();
+
     return AnimatableClipPathOperation::create(ShapeClipPathOperation::create(toShape->blend(fromShape, fraction)).get());
 }
 
diff --git a/Source/core/animation/AnimatableClipPathOperation.h b/Source/core/animation/AnimatableClipPathOperation.h
index 0a2401f..5d798c2 100644
--- a/Source/core/animation/AnimatableClipPathOperation.h
+++ b/Source/core/animation/AnimatableClipPathOperation.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class AnimatableClipPathOperation : public AnimatableValue {
+class AnimatableClipPathOperation FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableClipPathOperation() { }
     static PassRefPtr<AnimatableClipPathOperation> create(ClipPathOperation* operation)
@@ -47,6 +47,7 @@
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
     AnimatableClipPathOperation(ClipPathOperation* operation)
diff --git a/Source/core/animation/AnimatableColor.h b/Source/core/animation/AnimatableColor.h
index 57c8fd3..e5fc028 100644
--- a/Source/core/animation/AnimatableColor.h
+++ b/Source/core/animation/AnimatableColor.h
@@ -56,7 +56,7 @@
 // property. Currently it is used for all properties, even those which do not
 // support a separate 'visited link' color (eg SVG properties). This is correct
 // but inefficient.
-class AnimatableColor : public AnimatableValue {
+class AnimatableColor FINAL : public AnimatableValue {
 public:
     static PassRefPtr<AnimatableColor> create(const AnimatableColorImpl&, const AnimatableColorImpl& visitedLinkColor);
     Color color() const { return m_color.toColor(); }
diff --git a/Source/core/animation/AnimatableColorTest.cpp b/Source/core/animation/AnimatableColorTest.cpp
index 1e6ae35..12ecf85 100644
--- a/Source/core/animation/AnimatableColorTest.cpp
+++ b/Source/core/animation/AnimatableColorTest.cpp
@@ -40,10 +40,8 @@
 TEST(AnimationAnimatableColorTest, ToColor)
 {
     Color transparent = AnimatableColorImpl(Color::transparent).toColor();
-    EXPECT_TRUE(transparent.isValid());
     EXPECT_EQ(transparent.rgb(), Color::transparent);
     Color red = AnimatableColorImpl(Color(0xFFFF0000)).toColor();
-    EXPECT_TRUE(red.isValid());
     EXPECT_EQ(red.rgb(), 0xFFFF0000);
 }
 
diff --git a/Source/core/animation/AnimatableDouble.cpp b/Source/core/animation/AnimatableDouble.cpp
index 0e6cc0e..e509bf9 100644
--- a/Source/core/animation/AnimatableDouble.cpp
+++ b/Source/core/animation/AnimatableDouble.cpp
@@ -42,6 +42,12 @@
     return cssValuePool().createValue(m_number, CSSPrimitiveValue::CSS_NUMBER);
 }
 
+bool AnimatableDouble::usesDefaultInterpolationWith(const AnimatableValue* value) const
+{
+    const AnimatableDouble* other = toAnimatableDouble(value);
+    return (m_constraint == InterpolationIsNonContinuousWithZero) && (!m_number || !other->m_number);
+}
+
 PassRefPtr<AnimatableValue> AnimatableDouble::interpolateTo(const AnimatableValue* value, double fraction) const
 {
     const AnimatableDouble* other = toAnimatableDouble(value);
diff --git a/Source/core/animation/AnimatableDouble.h b/Source/core/animation/AnimatableDouble.h
index b2b7116..f05082e 100644
--- a/Source/core/animation/AnimatableDouble.h
+++ b/Source/core/animation/AnimatableDouble.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class AnimatableDouble : public AnimatableValue {
+class AnimatableDouble FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableDouble() { }
 
@@ -56,6 +56,7 @@
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
     virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
     AnimatableDouble(double number, Constraint constraint)
diff --git a/Source/core/animation/AnimatableFilterOperations.cpp b/Source/core/animation/AnimatableFilterOperations.cpp
index 31edeab..b116957 100644
--- a/Source/core/animation/AnimatableFilterOperations.cpp
+++ b/Source/core/animation/AnimatableFilterOperations.cpp
@@ -35,12 +35,18 @@
 
 namespace WebCore {
 
-PassRefPtr<AnimatableValue> AnimatableFilterOperations::interpolateTo(const AnimatableValue* value, double fraction) const
+bool AnimatableFilterOperations::usesDefaultInterpolationWith(const AnimatableValue* value) const
 {
     const AnimatableFilterOperations* target = toAnimatableFilterOperations(value);
-    if (!operations().canInterpolateWith(target->operations()))
+    return !operations().canInterpolateWith(target->operations());
+}
+
+PassRefPtr<AnimatableValue> AnimatableFilterOperations::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+    if (usesDefaultInterpolationWith(value))
         return defaultInterpolateTo(this, value, fraction);
 
+    const AnimatableFilterOperations* target = toAnimatableFilterOperations(value);
     FilterOperations result;
     size_t fromSize = operations().size();
     size_t toSize = target->operations().size();
diff --git a/Source/core/animation/AnimatableFilterOperations.h b/Source/core/animation/AnimatableFilterOperations.h
index 17c6944..a67264f 100644
--- a/Source/core/animation/AnimatableFilterOperations.h
+++ b/Source/core/animation/AnimatableFilterOperations.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class AnimatableFilterOperations : public AnimatableValue {
+class AnimatableFilterOperations FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableFilterOperations() { }
     static PassRefPtr<AnimatableFilterOperations> create(const FilterOperations& operations)
@@ -48,6 +48,7 @@
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
     virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
     AnimatableFilterOperations(const FilterOperations& operations)
diff --git a/Source/core/animation/AnimatableImage.cpp b/Source/core/animation/AnimatableImage.cpp
index eee86c3..28f4cd3 100644
--- a/Source/core/animation/AnimatableImage.cpp
+++ b/Source/core/animation/AnimatableImage.cpp
@@ -37,11 +37,28 @@
 
 namespace WebCore {
 
+// FIXME: Once cross-fade works on generated image types, remove this method.
+bool AnimatableImage::usesDefaultInterpolationWith(const AnimatableValue* value) const
+{
+    RefPtr<CSSValue> fromValue = toCSSValue();
+    if (fromValue->isImageGeneratorValue())
+        return true;
+    if (!fromValue->isImageValue() && !m_image->isImageResource())
+        return true;
+    const AnimatableImage* image = toAnimatableImage(value);
+    RefPtr<CSSValue> toValue = image->toCSSValue();
+    if (toValue->isImageGeneratorValue())
+        return true;
+    if (!toValue->isImageValue() && !image->m_image->isImageResource())
+        return true;
+    return false;
+}
+
 PassRefPtr<AnimatableValue> AnimatableImage::interpolateTo(const AnimatableValue* value, double fraction) const
 {
     if (fraction <= 0 || fraction >= 1)
         return defaultInterpolateTo(this, value, fraction);
-    RefPtr<CSSValue> fromValue = this->toCSSValue();
+    RefPtr<CSSValue> fromValue = toCSSValue();
     // FIXME: Once cross-fade works on generated image types, remove this check.
     if (fromValue->isImageGeneratorValue())
         return defaultInterpolateTo(this, value, fraction);
@@ -62,7 +79,7 @@
         ImageResource* resource = static_cast<ImageResource*>(image->m_image->data());
         toValue = CSSImageValue::create(resource->url(), image->m_image.get());
     }
-    RefPtr<CSSCrossfadeValue> crossfadeValue = CSSCrossfadeValue::create(fromValue, toValue);
+    RefPtrWillBeRawPtr<CSSCrossfadeValue> crossfadeValue = CSSCrossfadeValue::create(fromValue, toValue);
     crossfadeValue->setPercentage(CSSPrimitiveValue::create(fraction, CSSPrimitiveValue::CSS_NUMBER));
     return create(StyleGeneratedImage::create(crossfadeValue.get()).get());
 }
diff --git a/Source/core/animation/AnimatableImage.h b/Source/core/animation/AnimatableImage.h
index 40152f9..1557d06 100644
--- a/Source/core/animation/AnimatableImage.h
+++ b/Source/core/animation/AnimatableImage.h
@@ -37,7 +37,7 @@
 
 namespace WebCore {
 
-class AnimatableImage : public AnimatableValue {
+class AnimatableImage FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableImage() { }
     static PassRefPtr<AnimatableImage> create(StyleImage* image)
@@ -50,6 +50,7 @@
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
     virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
     AnimatableImage(StyleImage* image)
diff --git a/Source/core/animation/AnimatableLength.cpp b/Source/core/animation/AnimatableLength.cpp
index 38a4659..54724c1 100644
--- a/Source/core/animation/AnimatableLength.cpp
+++ b/Source/core/animation/AnimatableLength.cpp
@@ -90,6 +90,13 @@
     return toCSSPrimitiveValue(range)->convertToLength<AnyConversion>(conversionData);
 }
 
+bool AnimatableLength::usesDefaultInterpolationWith(const AnimatableValue* value) const
+{
+    const AnimatableLength* length = toAnimatableLength(value);
+    NumberUnitType type = commonUnitType(length);
+    return type == UnitTypeCalc && (isViewportUnit() || length->isViewportUnit());
+}
+
 PassRefPtr<AnimatableValue> AnimatableLength::interpolateTo(const AnimatableValue* value, double fraction) const
 {
     const AnimatableLength* length = toAnimatableLength(value);
@@ -131,7 +138,7 @@
     return m_number == length->m_number;
 }
 
-PassRefPtr<CSSCalcExpressionNode> AnimatableLength::toCSSCalcExpressionNode() const
+PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> AnimatableLength::toCSSCalcExpressionNode() const
 {
     if (isCalc())
         return m_calcExpression;
@@ -148,7 +155,7 @@
     return primitiveValue->getDoubleValue() >= 0;
 }
 
-PassRefPtr<CSSPrimitiveValue> AnimatableLength::toCSSPrimitiveValue(NumberRange range) const
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> AnimatableLength::toCSSPrimitiveValue(NumberRange range) const
 {
     if (!m_cachedCSSPrimitiveValue || !isCompatibleWithRange(m_cachedCSSPrimitiveValue.get(), range)) {
         if (isCalc())
diff --git a/Source/core/animation/AnimatableLength.h b/Source/core/animation/AnimatableLength.h
index 1474576..9462c3b 100644
--- a/Source/core/animation/AnimatableLength.h
+++ b/Source/core/animation/AnimatableLength.h
@@ -46,7 +46,7 @@
 // Handles animation of CSS length and percentage values including CSS calc.
 // See primitiveUnitToNumberType() for the list of supported units.
 // If created from a CSSPrimitiveValue this class will cache it to be returned in toCSSValue().
-class AnimatableLength : public AnimatableValue {
+class AnimatableLength FINAL : public AnimatableValue {
 public:
     enum NumberUnitType {
         UnitTypeCalc,
@@ -68,7 +68,7 @@
     {
         return adoptRef(new AnimatableLength(number, unitType, cssPrimitiveValue));
     }
-    static PassRefPtr<AnimatableLength> create(PassRefPtr<CSSCalcExpressionNode> calcExpression, CSSPrimitiveValue* cssPrimitiveValue = 0)
+    static PassRefPtr<AnimatableLength> create(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> calcExpression, CSSPrimitiveValue* cssPrimitiveValue = 0)
     {
         return adoptRef(new AnimatableLength(calcExpression, cssPrimitiveValue));
     }
@@ -78,6 +78,7 @@
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
     virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
     AnimatableLength(double number, NumberUnitType unitType, CSSPrimitiveValue* cssPrimitiveValue)
@@ -87,7 +88,7 @@
     {
         ASSERT(m_unitType != UnitTypeCalc);
     }
-    AnimatableLength(PassRefPtr<CSSCalcExpressionNode> calcExpression, CSSPrimitiveValue* cssPrimitiveValue)
+    AnimatableLength(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> calcExpression, CSSPrimitiveValue* cssPrimitiveValue)
         : m_unitType(UnitTypeCalc)
         , m_calcExpression(calcExpression)
         , m_cachedCSSPrimitiveValue(cssPrimitiveValue)
@@ -113,8 +114,8 @@
         return create(CSSCalcValue::createExpressionNode(leftAddend->toCSSCalcExpressionNode(), rightAddend->toCSSCalcExpressionNode(), CalcAdd));
     }
 
-    PassRefPtr<CSSPrimitiveValue> toCSSPrimitiveValue(NumberRange) const;
-    PassRefPtr<CSSCalcExpressionNode> toCSSCalcExpressionNode() const;
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> toCSSPrimitiveValue(NumberRange) const;
+    PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> toCSSCalcExpressionNode() const;
 
     PassRefPtr<AnimatableLength> scale(double) const;
     double clampedNumber(NumberRange range) const
@@ -152,9 +153,9 @@
     double m_number;
     const NumberUnitType m_unitType;
 
-    RefPtr<CSSCalcExpressionNode> m_calcExpression;
+    RefPtrWillBePersistent<CSSCalcExpressionNode> m_calcExpression;
 
-    mutable RefPtr<CSSPrimitiveValue> m_cachedCSSPrimitiveValue;
+    mutable RefPtrWillBePersistent<CSSPrimitiveValue> m_cachedCSSPrimitiveValue;
 
     friend class AnimationAnimatableLengthTest;
 };
diff --git a/Source/core/animation/AnimatableLengthBox.h b/Source/core/animation/AnimatableLengthBox.h
index b7ea5be..209ae90 100644
--- a/Source/core/animation/AnimatableLengthBox.h
+++ b/Source/core/animation/AnimatableLengthBox.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class AnimatableLengthBox : public AnimatableValue {
+class AnimatableLengthBox FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableLengthBox() { }
     static PassRefPtr<AnimatableLengthBox> create(PassRefPtr<AnimatableValue> left, PassRefPtr<AnimatableValue> right, PassRefPtr<AnimatableValue> top, PassRefPtr<AnimatableValue> bottom)
diff --git a/Source/core/animation/AnimatableLengthBoxAndBool.cpp b/Source/core/animation/AnimatableLengthBoxAndBool.cpp
index da92ac2..b4112a5 100644
--- a/Source/core/animation/AnimatableLengthBoxAndBool.cpp
+++ b/Source/core/animation/AnimatableLengthBoxAndBool.cpp
@@ -33,6 +33,14 @@
 
 namespace WebCore {
 
+bool AnimatableLengthBoxAndBool::usesDefaultInterpolationWith(const AnimatableValue* value) const
+{
+    const AnimatableLengthBoxAndBool* lengthBox = toAnimatableLengthBoxAndBool(value);
+    if (lengthBox->flag() != flag())
+        return true;
+    return AnimatableValue::usesDefaultInterpolation(lengthBox->box(), box());
+}
+
 PassRefPtr<AnimatableValue> AnimatableLengthBoxAndBool::interpolateTo(const AnimatableValue* value, double fraction) const
 {
     const AnimatableLengthBoxAndBool* lengthBox = toAnimatableLengthBoxAndBool(value);
diff --git a/Source/core/animation/AnimatableLengthBoxAndBool.h b/Source/core/animation/AnimatableLengthBoxAndBool.h
index 9e33797..96c1e6f 100644
--- a/Source/core/animation/AnimatableLengthBoxAndBool.h
+++ b/Source/core/animation/AnimatableLengthBoxAndBool.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class AnimatableLengthBoxAndBool : public AnimatableValue {
+class AnimatableLengthBoxAndBool FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableLengthBoxAndBool() { }
     static PassRefPtr<AnimatableLengthBoxAndBool> create(PassRefPtr<AnimatableValue> box, bool flag)
@@ -48,6 +48,7 @@
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
     virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
     AnimatableLengthBoxAndBool(PassRefPtr<AnimatableValue> box, bool flag)
diff --git a/Source/core/animation/AnimatableLengthPoint.h b/Source/core/animation/AnimatableLengthPoint.h
index 60b3e03..5728046 100644
--- a/Source/core/animation/AnimatableLengthPoint.h
+++ b/Source/core/animation/AnimatableLengthPoint.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class AnimatableLengthPoint : public AnimatableValue {
+class AnimatableLengthPoint FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableLengthPoint() { }
     static PassRefPtr<AnimatableLengthPoint> create(PassRefPtr<AnimatableValue> x, PassRefPtr<AnimatableValue> y)
diff --git a/Source/core/animation/AnimatableLengthSize.h b/Source/core/animation/AnimatableLengthSize.h
index 55dcc40..4e2c8d9 100644
--- a/Source/core/animation/AnimatableLengthSize.h
+++ b/Source/core/animation/AnimatableLengthSize.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class AnimatableLengthSize : public AnimatableValue {
+class AnimatableLengthSize FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableLengthSize() { }
     static PassRefPtr<AnimatableLengthSize> create(PassRefPtr<AnimatableValue> width, PassRefPtr<AnimatableValue> height)
diff --git a/Source/core/animation/AnimatableLengthTest.cpp b/Source/core/animation/AnimatableLengthTest.cpp
index 3574a66..fb6fbac 100644
--- a/Source/core/animation/AnimatableLengthTest.cpp
+++ b/Source/core/animation/AnimatableLengthTest.cpp
@@ -51,8 +51,8 @@
 protected:
     AnimationAnimatableLengthTest()
         : style(RenderStyle::createDefaultStyle())
-        , conversionDataZoom1(style.get(), style.get(), 1.0f)
-        , conversionDataZoom3(style.get(), style.get(), 3.0f)
+        , conversionDataZoom1(style.get(), style.get(), 0, 0, 1.0f)
+        , conversionDataZoom3(style.get(), style.get(), 0, 0, 3.0f)
     {
     }
 
@@ -66,7 +66,7 @@
         return AnimatableLength::create(createCalc(valueLeft, typeLeft, valueRight, typeRight).get());
     }
 
-    PassRefPtr<CSSCalcValue> createCalc(double valueLeft, CSSPrimitiveValue::UnitTypes typeLeft, double valueRight, CSSPrimitiveValue::UnitTypes typeRight)
+    PassRefPtrWillBeRawPtr<CSSCalcValue> createCalc(double valueLeft, CSSPrimitiveValue::UnitTypes typeLeft, double valueRight, CSSPrimitiveValue::UnitTypes typeRight)
     {
         return CSSCalcValue::create(CSSCalcValue::createExpressionNode(
             CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(valueLeft, typeLeft), valueLeft == trunc(valueLeft)),
diff --git a/Source/core/animation/AnimatableNeutral.h b/Source/core/animation/AnimatableNeutral.h
index 5b8759c..1001f58 100644
--- a/Source/core/animation/AnimatableNeutral.h
+++ b/Source/core/animation/AnimatableNeutral.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class AnimatableNeutral : public AnimatableValue {
+class AnimatableNeutral FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableNeutral() { }
 
diff --git a/Source/core/animation/AnimatableRepeatable.cpp b/Source/core/animation/AnimatableRepeatable.cpp
index a9f1ae6..5a66460 100644
--- a/Source/core/animation/AnimatableRepeatable.cpp
+++ b/Source/core/animation/AnimatableRepeatable.cpp
@@ -48,6 +48,22 @@
 
 namespace WebCore {
 
+bool AnimatableRepeatable::usesDefaultInterpolationWith(const AnimatableValue* value) const
+{
+    const Vector<RefPtr<AnimatableValue> >& fromValues = m_values;
+    const Vector<RefPtr<AnimatableValue> >& toValues = toAnimatableRepeatable(value)->m_values;
+    ASSERT(!fromValues.isEmpty() && !toValues.isEmpty());
+    size_t size = lowestCommonMultiple(fromValues.size(), toValues.size());
+    for (size_t i = 0; i < size; ++i) {
+        const AnimatableValue* from = fromValues[i % fromValues.size()].get();
+        const AnimatableValue* to = toValues[i % toValues.size()].get();
+        // Spec: If a pair of values cannot be interpolated, then the lists are not interpolable.
+        if (AnimatableValue::usesDefaultInterpolation(from, to))
+            return true;
+    }
+    return false;
+}
+
 bool AnimatableRepeatable::interpolateLists(const Vector<RefPtr<AnimatableValue> >& fromValues, const Vector<RefPtr<AnimatableValue> >& toValues, double fraction, Vector<RefPtr<AnimatableValue> >& interpolatedValues)
 {
     // Interpolation behaviour spec: http://www.w3.org/TR/css3-transitions/#animtype-repeatable-list
@@ -58,7 +74,7 @@
         const AnimatableValue* from = fromValues[i % fromValues.size()].get();
         const AnimatableValue* to = toValues[i % toValues.size()].get();
         // Spec: If a pair of values cannot be interpolated, then the lists are not interpolable.
-        if (!from->usesNonDefaultInterpolationWith(to))
+        if (AnimatableValue::usesDefaultInterpolation(from, to))
             return false;
         interpolatedValues.append(interpolate(from, to, fraction));
     }
diff --git a/Source/core/animation/AnimatableRepeatable.h b/Source/core/animation/AnimatableRepeatable.h
index b1c7494..bd13f35 100644
--- a/Source/core/animation/AnimatableRepeatable.h
+++ b/Source/core/animation/AnimatableRepeatable.h
@@ -62,14 +62,16 @@
 
     static bool interpolateLists(const Vector<RefPtr<AnimatableValue> >& fromValues, const Vector<RefPtr<AnimatableValue> >& toValues, double fraction, Vector<RefPtr<AnimatableValue> >& interpolatedValues);
 
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
+
     Vector<RefPtr<AnimatableValue> > m_values;
 
 private:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
-    virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+    virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE FINAL;
 
     virtual AnimatableType type() const OVERRIDE { return TypeRepeatable; }
-    virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+    virtual bool equalTo(const AnimatableValue*) const OVERRIDE FINAL;
 };
 
 DEFINE_TYPE_CASTS(AnimatableRepeatable, AnimatableValue, value, (value->isRepeatable() || value->isStrokeDasharrayList()), (value.isRepeatable() || value.isStrokeDasharrayList()));
diff --git a/Source/core/animation/AnimatableSVGLength.cpp b/Source/core/animation/AnimatableSVGLength.cpp
index 97f4158..e370a62 100644
--- a/Source/core/animation/AnimatableSVGLength.cpp
+++ b/Source/core/animation/AnimatableSVGLength.cpp
@@ -37,7 +37,7 @@
 
 PassRefPtr<AnimatableValue> AnimatableSVGLength::interpolateTo(const AnimatableValue* value, double fraction) const
 {
-    return create(toAnimatableSVGLength(value)->toSVGLength().blend(m_length, narrowPrecisionToFloat(fraction)));
+    return create(toAnimatableSVGLength(value)->toSVGLength()->blend(m_length.get(), narrowPrecisionToFloat(fraction)));
 }
 
 PassRefPtr<AnimatableValue> AnimatableSVGLength::addWith(const AnimatableValue* value) const
@@ -48,7 +48,7 @@
 
 bool AnimatableSVGLength::equalTo(const AnimatableValue* value) const
 {
-    return m_length == toAnimatableSVGLength(value)->m_length;
+    return *m_length == *toAnimatableSVGLength(value)->m_length;
 }
 
 } // namespace WebCore
diff --git a/Source/core/animation/AnimatableSVGLength.h b/Source/core/animation/AnimatableSVGLength.h
index 27dba9a..dd4a627 100644
--- a/Source/core/animation/AnimatableSVGLength.h
+++ b/Source/core/animation/AnimatableSVGLength.h
@@ -36,18 +36,18 @@
 
 namespace WebCore {
 
-class AnimatableSVGLength: public AnimatableValue {
+class AnimatableSVGLength FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableSVGLength() { }
 
-    static PassRefPtr<AnimatableSVGLength> create(const SVGLength& length)
+    static PassRefPtr<AnimatableSVGLength> create(PassRefPtr<SVGLength> length)
     {
         return adoptRef(new AnimatableSVGLength(length));
     }
 
-    const SVGLength& toSVGLength() const
+    SVGLength* toSVGLength() const
     {
-        return m_length;
+        return m_length.get();
     }
 
 protected:
@@ -55,15 +55,15 @@
     virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
 
 private:
-    AnimatableSVGLength(const SVGLength& length)
+    AnimatableSVGLength(PassRefPtr<SVGLength> length)
         : m_length(length)
     {
     }
 
-    virtual AnimatableType type() const { return TypeSVGLength; }
+    virtual AnimatableType type() const OVERRIDE { return TypeSVGLength; }
     virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
 
-    SVGLength m_length;
+    RefPtr<SVGLength> m_length;
 };
 
 DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableSVGLength, isSVGLength());
diff --git a/Source/core/animation/AnimatableSVGPaint.cpp b/Source/core/animation/AnimatableSVGPaint.cpp
index 784c9d3..e497ce4 100644
--- a/Source/core/animation/AnimatableSVGPaint.cpp
+++ b/Source/core/animation/AnimatableSVGPaint.cpp
@@ -33,6 +33,12 @@
 
 namespace WebCore {
 
+bool AnimatableSVGPaint::usesDefaultInterpolationWith(const AnimatableValue* value) const
+{
+    const AnimatableSVGPaint* svgPaint = toAnimatableSVGPaint(value);
+    return paintType() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR || svgPaint->paintType() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR;
+}
+
 PassRefPtr<AnimatableValue> AnimatableSVGPaint::interpolateTo(const AnimatableValue* value, double fraction) const
 {
     const AnimatableSVGPaint* svgPaint = toAnimatableSVGPaint(value);
diff --git a/Source/core/animation/AnimatableSVGPaint.h b/Source/core/animation/AnimatableSVGPaint.h
index 93ebd2e..939b888 100644
--- a/Source/core/animation/AnimatableSVGPaint.h
+++ b/Source/core/animation/AnimatableSVGPaint.h
@@ -37,7 +37,7 @@
 
 namespace WebCore {
 
-class AnimatableSVGPaint : public AnimatableValue {
+class AnimatableSVGPaint FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableSVGPaint() { }
     static PassRefPtr<AnimatableSVGPaint> create(SVGPaint::SVGPaintType type, const Color& color, const String& uri)
@@ -55,6 +55,7 @@
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
     virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
     AnimatableSVGPaint(SVGPaint::SVGPaintType type, const AnimatableColorImpl& color, const String& uri)
diff --git a/Source/core/animation/AnimatableShadow.h b/Source/core/animation/AnimatableShadow.h
index 23fb59b..3441c4c 100644
--- a/Source/core/animation/AnimatableShadow.h
+++ b/Source/core/animation/AnimatableShadow.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class AnimatableShadow : public AnimatableValue {
+class AnimatableShadow FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableShadow() { }
     static PassRefPtr<AnimatableShadow> create(PassRefPtr<ShadowList> shadowList)
diff --git a/Source/core/animation/AnimatableShapeValue.cpp b/Source/core/animation/AnimatableShapeValue.cpp
index 9b17295..1742bac 100644
--- a/Source/core/animation/AnimatableShapeValue.cpp
+++ b/Source/core/animation/AnimatableShapeValue.cpp
@@ -33,19 +33,27 @@
 
 namespace WebCore {
 
-PassRefPtr<AnimatableValue> AnimatableShapeValue::interpolateTo(const AnimatableValue* value, double fraction) const
+bool AnimatableShapeValue::usesDefaultInterpolationWith(const AnimatableValue* value) const
 {
     const AnimatableShapeValue* shapeValue = toAnimatableShapeValue(value);
 
     if (m_shape->type() != ShapeValue::Shape || shapeValue->m_shape->type() != ShapeValue::Shape)
-        return defaultInterpolateTo(this, value, fraction);
+        return true;
 
     const BasicShape* fromShape = this->m_shape->shape();
     const BasicShape* toShape = shapeValue->m_shape->shape();
 
-    if (!fromShape->canBlend(toShape))
+    return !fromShape->canBlend(toShape);
+}
+
+PassRefPtr<AnimatableValue> AnimatableShapeValue::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+    if (usesDefaultInterpolationWith(value))
         return defaultInterpolateTo(this, value, fraction);
 
+    const AnimatableShapeValue* shapeValue = toAnimatableShapeValue(value);
+    const BasicShape* fromShape = this->m_shape->shape();
+    const BasicShape* toShape = shapeValue->m_shape->shape();
     return AnimatableShapeValue::create(ShapeValue::createShapeValue(toShape->blend(fromShape, fraction)).get());
 }
 
diff --git a/Source/core/animation/AnimatableShapeValue.h b/Source/core/animation/AnimatableShapeValue.h
index 1d5382b..9924693 100644
--- a/Source/core/animation/AnimatableShapeValue.h
+++ b/Source/core/animation/AnimatableShapeValue.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class AnimatableShapeValue : public AnimatableValue {
+class AnimatableShapeValue FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableShapeValue() { }
     static PassRefPtr<AnimatableShapeValue> create(ShapeValue* shape)
@@ -47,6 +47,7 @@
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
     AnimatableShapeValue(ShapeValue* shape)
diff --git a/Source/core/animation/AnimatableStrokeDasharrayList.cpp b/Source/core/animation/AnimatableStrokeDasharrayList.cpp
index b8951cc..0c219e3 100644
--- a/Source/core/animation/AnimatableStrokeDasharrayList.cpp
+++ b/Source/core/animation/AnimatableStrokeDasharrayList.cpp
@@ -36,21 +36,30 @@
 
 namespace WebCore {
 
-AnimatableStrokeDasharrayList::AnimatableStrokeDasharrayList(const Vector<SVGLength>& lengths)
+AnimatableStrokeDasharrayList::AnimatableStrokeDasharrayList(PassRefPtr<SVGLengthList> passLengths)
 {
-    for (size_t i = 0; i < lengths.size(); ++i)
-        m_values.append(AnimatableSVGLength::create(lengths[i]));
+    RefPtr<SVGLengthList> lengths = passLengths;
+    SVGLengthList::ConstIterator it = lengths->begin();
+    SVGLengthList::ConstIterator itEnd = lengths->end();
+    for (; it != itEnd; ++it)
+        m_values.append(AnimatableSVGLength::create(*it));
 }
 
-Vector<SVGLength> AnimatableStrokeDasharrayList::toSVGLengthVector() const
+PassRefPtr<SVGLengthList> AnimatableStrokeDasharrayList::toSVGLengthList() const
 {
-    Vector<SVGLength> lengths(m_values.size());
+    RefPtr<SVGLengthList> lengths = SVGLengthList::create();
     for (size_t i = 0; i < m_values.size(); ++i) {
-        lengths[i] = toAnimatableSVGLength(m_values[i].get())->toSVGLength();
-        if (lengths[i].valueInSpecifiedUnits() < 0)
-            lengths[i].setValueInSpecifiedUnits(0);
+        RefPtr<SVGLength> length = toAnimatableSVGLength(m_values[i].get())->toSVGLength()->clone();
+        if (length->valueInSpecifiedUnits() < 0)
+            length->setValueInSpecifiedUnits(0);
+        lengths->append(length);
     }
-    return lengths;
+    return lengths.release();
+}
+
+bool AnimatableStrokeDasharrayList::usesDefaultInterpolationWith(const AnimatableValue* value) const
+{
+    return false;
 }
 
 PassRefPtr<AnimatableValue> AnimatableStrokeDasharrayList::interpolateTo(const AnimatableValue* value, double fraction) const
@@ -66,12 +75,7 @@
     if (from.isEmpty() && to.isEmpty())
         return takeConstRef(this);
     if (from.isEmpty() || to.isEmpty()) {
-        DEFINE_STATIC_REF(AnimatableSVGLength, zeroPixels, 0);
-        if (!zeroPixels) {
-            SVGLength length;
-            length.newValueSpecifiedUnits(LengthTypePX, 0, IGNORE_EXCEPTION);
-            zeroPixels = AnimatableSVGLength::create(length).leakRef();
-        }
+        DEFINE_STATIC_REF(AnimatableSVGLength, zeroPixels, AnimatableSVGLength::create(SVGLength::create()).leakRef());
         if (from.isEmpty()) {
             from.append(zeroPixels);
             from.append(zeroPixels);
diff --git a/Source/core/animation/AnimatableStrokeDasharrayList.h b/Source/core/animation/AnimatableStrokeDasharrayList.h
index d19b2e0..5c564f8 100644
--- a/Source/core/animation/AnimatableStrokeDasharrayList.h
+++ b/Source/core/animation/AnimatableStrokeDasharrayList.h
@@ -32,33 +32,34 @@
 #define AnimatableStrokeDasharrayList_h
 
 #include "core/animation/AnimatableRepeatable.h"
-#include "core/svg/SVGLength.h"
+#include "core/svg/SVGLengthList.h"
 
 namespace WebCore {
 
-class AnimatableStrokeDasharrayList: public AnimatableRepeatable {
+class AnimatableStrokeDasharrayList FINAL : public AnimatableRepeatable {
 public:
     virtual ~AnimatableStrokeDasharrayList() { }
 
-    static PassRefPtr<AnimatableStrokeDasharrayList> create(const Vector<SVGLength>& lengths)
+    static PassRefPtr<AnimatableStrokeDasharrayList> create(PassRefPtr<SVGLengthList> lengths)
     {
         return adoptRef(new AnimatableStrokeDasharrayList(lengths));
     }
 
-    Vector<SVGLength> toSVGLengthVector() const;
+    PassRefPtr<SVGLengthList> toSVGLengthList() const;
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
-    AnimatableStrokeDasharrayList(const Vector<SVGLength>&);
+    AnimatableStrokeDasharrayList(PassRefPtr<SVGLengthList>);
     // This will consume the vector passed into it.
     AnimatableStrokeDasharrayList(Vector<RefPtr<AnimatableValue> >& values)
         : AnimatableRepeatable(values)
     {
     }
 
-    virtual AnimatableType type() const { return TypeStrokeDasharrayList; }
+    virtual AnimatableType type() const OVERRIDE { return TypeStrokeDasharrayList; }
 };
 
 DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableStrokeDasharrayList, isStrokeDasharrayList());
diff --git a/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp b/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp
index 6a2756d..14315b9 100644
--- a/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp
+++ b/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp
@@ -39,21 +39,29 @@
 
 namespace {
 
+PassRefPtr<SVGLengthList> createSVGLengthList(size_t length)
+{
+    RefPtr<SVGLengthList> list = SVGLengthList::create();
+    for (size_t i = 0; i < length; ++i)
+        list->append(SVGLength::create());
+    return list.release();
+}
+
 TEST(AnimationAnimatableStrokeDasharrayListTest, EqualTo)
 {
-    Vector<SVGLength> vectorA(4);
-    Vector<SVGLength> vectorB(4);
-    RefPtr<AnimatableStrokeDasharrayList> listA = AnimatableStrokeDasharrayList::create(vectorA);
-    RefPtr<AnimatableStrokeDasharrayList> listB = AnimatableStrokeDasharrayList::create(vectorB);
+    RefPtr<SVGLengthList> svgListA = createSVGLengthList(4);
+    RefPtr<SVGLengthList> svgListB = createSVGLengthList(4);
+    RefPtr<AnimatableStrokeDasharrayList> listA = AnimatableStrokeDasharrayList::create(svgListA);
+    RefPtr<AnimatableStrokeDasharrayList> listB = AnimatableStrokeDasharrayList::create(svgListB);
     EXPECT_TRUE(listA->equals(listB.get()));
 
     TrackExceptionState exceptionState;
-    vectorB[3].newValueSpecifiedUnits(LengthTypePX, 50, exceptionState);
-    listB = AnimatableStrokeDasharrayList::create(vectorB);
+    svgListB->at(3)->newValueSpecifiedUnits(LengthTypePX, 50);
+    listB = AnimatableStrokeDasharrayList::create(svgListB);
     EXPECT_FALSE(listA->equals(listB.get()));
 
-    vectorB = Vector<SVGLength>(5);
-    listB = AnimatableStrokeDasharrayList::create(vectorB);
+    svgListB = createSVGLengthList(5);
+    listB = AnimatableStrokeDasharrayList::create(svgListB);
     EXPECT_FALSE(listA->equals(listB.get()));
 }
 
diff --git a/Source/core/animation/AnimatableTransform.h b/Source/core/animation/AnimatableTransform.h
index 7fa8532..2733bdf 100644
--- a/Source/core/animation/AnimatableTransform.h
+++ b/Source/core/animation/AnimatableTransform.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class AnimatableTransform : public AnimatableValue {
+class AnimatableTransform FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableTransform() { }
     static PassRefPtr<AnimatableTransform> create(const TransformOperations&);
diff --git a/Source/core/animation/AnimatableUnknown.h b/Source/core/animation/AnimatableUnknown.h
index 43be1c8..4080c4d 100644
--- a/Source/core/animation/AnimatableUnknown.h
+++ b/Source/core/animation/AnimatableUnknown.h
@@ -37,7 +37,7 @@
 
 namespace WebCore {
 
-class AnimatableUnknown : public AnimatableValue {
+class AnimatableUnknown FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableUnknown() { }
 
@@ -59,6 +59,8 @@
         return defaultInterpolateTo(this, value, fraction);
     }
 
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE { return true; }
+
 private:
     explicit AnimatableUnknown(PassRefPtr<CSSValue> value)
         : m_value(value)
diff --git a/Source/core/animation/AnimatableValue.h b/Source/core/animation/AnimatableValue.h
index 2e52c32..3771fb4 100644
--- a/Source/core/animation/AnimatableValue.h
+++ b/Source/core/animation/AnimatableValue.h
@@ -31,12 +31,13 @@
 #ifndef AnimatableValue_h
 #define AnimatableValue_h
 
+#include "core/animation/AnimationEffect.h"
 #include "core/css/CSSValue.h"
 #include "wtf/RefCounted.h"
 
 namespace WebCore {
 
-class AnimatableValue : public RefCounted<AnimatableValue> {
+class AnimatableValue : public AnimationEffect::CompositableValue {
 public:
     virtual ~AnimatableValue() { }
 
@@ -45,6 +46,10 @@
     static PassRefPtr<AnimatableValue> interpolate(const AnimatableValue*, const AnimatableValue*, double fraction);
     // For noncommutative values read add(A, B) to mean the value A with B composed onto it.
     static PassRefPtr<AnimatableValue> add(const AnimatableValue*, const AnimatableValue*);
+    static bool usesDefaultInterpolation(const AnimatableValue* from, const AnimatableValue* to)
+    {
+        return !from->isSameType(to) || from->usesDefaultInterpolationWith(to);
+    }
 
     bool equals(const AnimatableValue* value) const
     {
@@ -55,6 +60,9 @@
         return equals(&value);
     }
 
+    virtual bool dependsOnUnderlyingValue() const OVERRIDE FINAL { return false; }
+    virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue*) const OVERRIDE FINAL { return takeConstRef(this); }
+
     bool isClipPathOperation() const { return type() == TypeClipPathOperation; }
     bool isColor() const { return type() == TypeColor; }
     bool isDouble() const { return type() == TypeDouble; }
@@ -82,11 +90,6 @@
         return value->type() == type();
     }
 
-    bool usesNonDefaultInterpolationWith(const AnimatableValue* value) const
-    {
-        return isSameType(value) && !isUnknown();
-    }
-
 protected:
     enum AnimatableType {
         TypeClipPathOperation,
@@ -111,6 +114,7 @@
         TypeVisibility,
     };
 
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue* value) const { return false; }
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const = 0;
     static PassRefPtr<AnimatableValue> defaultInterpolateTo(const AnimatableValue* left, const AnimatableValue* right, double fraction) { return takeConstRef((fraction < 0.5) ? left : right); }
 
@@ -118,6 +122,8 @@
     virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const;
     static PassRefPtr<AnimatableValue> defaultAddWith(const AnimatableValue* left, const AnimatableValue* right) { return takeConstRef(right); }
 
+
+
     template <class T>
     static PassRefPtr<T> takeConstRef(const T* value) { return PassRefPtr<T>(const_cast<T*>(value)); }
 
@@ -125,6 +131,8 @@
     virtual AnimatableType type() const = 0;
     // Implementations can assume that the object being compared has the same type as the object this is called on
     virtual bool equalTo(const AnimatableValue*) const = 0;
+
+    friend class KeyframeEffectModel;
 };
 
 #define DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(thisType, predicate) \
diff --git a/Source/core/animation/AnimatableValueTestHelper.cpp b/Source/core/animation/AnimatableValueTestHelper.cpp
index da6958c..1dbea42 100644
--- a/Source/core/animation/AnimatableValueTestHelper.cpp
+++ b/Source/core/animation/AnimatableValueTestHelper.cpp
@@ -120,7 +120,7 @@
 void PrintTo(const AnimatableSVGLength& animSVGLength, ::std::ostream* os)
 {
     *os << "AnimatableSVGLength("
-        << animSVGLength.toSVGLength().valueAsString().utf8().data() << ")";
+        << animSVGLength.toSVGLength()->valueAsString().utf8().data() << ")";
 }
 
 void PrintTo(const AnimatableSVGPaint& animSVGPaint, ::std::ostream* os)
@@ -143,10 +143,11 @@
 void PrintTo(const AnimatableStrokeDasharrayList& animValue, ::std::ostream* os)
 {
     *os << "AnimatableStrokeDasharrayList(";
-    const Vector<SVGLength> v = animValue.toSVGLengthVector();
-    for (Vector<SVGLength>::const_iterator it = v.begin(); it != v.end(); ++it) {
-        *os << it->valueAsString().utf8().data();
-        if (it+1 != v.end())
+    RefPtr<SVGLengthList> list = animValue.toSVGLengthList();
+    size_t length = list->numberOfItems();
+    for (size_t i = 0; i < length; ++i) {
+        *os << list->at(i)->valueAsString().utf8().data();
+        if (i != length-1)
             *os << ", ";
     }
     *os << ")";
diff --git a/Source/core/animation/AnimatableValueTestHelperTest.cpp b/Source/core/animation/AnimatableValueTestHelperTest.cpp
index fad1a5a..5836421 100644
--- a/Source/core/animation/AnimatableValueTestHelperTest.cpp
+++ b/Source/core/animation/AnimatableValueTestHelperTest.cpp
@@ -114,9 +114,14 @@
         ::std::string("AnimatableRepeatable(AnimatableLength(3rem), AnimatableLength(4pt))"),
         PrintToString(AnimatableRepeatable::create(v1)));
 
+    RefPtr<SVGLength> length1cm = SVGLength::create(LengthModeOther);
+    RefPtr<SVGLength> length2cm = SVGLength::create(LengthModeOther);
+    length1cm->setValueAsString("1cm", ASSERT_NO_EXCEPTION);
+    length2cm->setValueAsString("2cm", ASSERT_NO_EXCEPTION);
+
     EXPECT_EQ(
         ::std::string("AnimatableSVGLength(1cm)"),
-        PrintToString(AnimatableSVGLength::create(SVGLength(LengthModeOther, "1cm"))));
+        PrintToString(AnimatableSVGLength::create(length1cm)));
 
     EXPECT_EQ(
         ::std::string("AnimatableSVGPaint(#ff0000)"),
@@ -130,12 +135,12 @@
         PrintToString(AnimatableShapeValue::create(ShapeValue::createShapeValue(BasicShapeCircle::create().get()).get())),
         testing::StartsWith("AnimatableShapeValue@"));
 
-    Vector<SVGLength> v2;
-    v2.append(SVGLength(LengthModeOther, "1cm"));
-    v2.append(SVGLength(LengthModeOther, "2cm"));
+    RefPtr<SVGLengthList> l2 = SVGLengthList::create();
+    l2->append(length1cm);
+    l2->append(length2cm);
     EXPECT_EQ(
         ::std::string("AnimatableStrokeDasharrayList(1cm, 2cm)"),
-        PrintToString(AnimatableStrokeDasharrayList::create(v2)));
+        PrintToString(AnimatableStrokeDasharrayList::create(l2)));
 
     TransformOperations operations1;
     operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
diff --git a/Source/core/animation/AnimatableVisibility.cpp b/Source/core/animation/AnimatableVisibility.cpp
index a395efa..8727081 100644
--- a/Source/core/animation/AnimatableVisibility.cpp
+++ b/Source/core/animation/AnimatableVisibility.cpp
@@ -33,6 +33,13 @@
 
 namespace WebCore {
 
+bool AnimatableVisibility::usesDefaultInterpolationWith(const AnimatableValue* value) const
+{
+    EVisibility from = m_visibility;
+    EVisibility to = toAnimatableVisibility(value)->m_visibility;
+    return from != VISIBLE && to != VISIBLE;
+}
+
 PassRefPtr<AnimatableValue> AnimatableVisibility::interpolateTo(const AnimatableValue* value, double fraction) const
 {
     EVisibility from = m_visibility;
diff --git a/Source/core/animation/AnimatableVisibility.h b/Source/core/animation/AnimatableVisibility.h
index bbd3771..c0c7433 100644
--- a/Source/core/animation/AnimatableVisibility.h
+++ b/Source/core/animation/AnimatableVisibility.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class AnimatableVisibility : public AnimatableValue {
+class AnimatableVisibility FINAL : public AnimatableValue {
 public:
     virtual ~AnimatableVisibility() { }
     static PassRefPtr<AnimatableVisibility> create(EVisibility visibility)
@@ -48,6 +48,7 @@
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+    virtual bool usesDefaultInterpolationWith(const AnimatableValue*) const OVERRIDE;
 
 private:
     explicit AnimatableVisibility(EVisibility visibility)
diff --git a/Source/core/animation/Animation.cpp b/Source/core/animation/Animation.cpp
index 102bfae..d81f8ee 100644
--- a/Source/core/animation/Animation.cpp
+++ b/Source/core/animation/Animation.cpp
@@ -31,11 +31,18 @@
 #include "config.h"
 #include "core/animation/Animation.h"
 
+#include "bindings/v8/Dictionary.h"
 #include "core/animation/ActiveAnimations.h"
+#include "core/animation/AnimationHelpers.h"
 #include "core/animation/CompositorAnimations.h"
-#include "core/animation/KeyframeAnimationEffect.h"
+#include "core/animation/DocumentTimeline.h"
+#include "core/animation/KeyframeEffectModel.h"
 #include "core/animation/Player.h"
+#include "core/css/parser/BisonCSSParser.h"
+#include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Element.h"
+#include "core/rendering/RenderLayer.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -44,6 +51,272 @@
     return adoptRef(new Animation(target, effect, timing, priority, eventDelegate));
 }
 
+static bool checkDocumentAndRenderer(Element* element)
+{
+    if (!element->inActiveDocument())
+        return false;
+    element->document().updateStyleIfNeeded();
+    if (!element->renderer())
+        return false;
+    return true;
+}
+
+PassRefPtr<Animation> Animation::create(Element* element, Vector<Dictionary> keyframeDictionaryVector, Dictionary timingInput)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsAPIEnabled());
+
+    // FIXME: This test will not be neccessary once resolution of keyframe values occurs at
+    // animation application time.
+    if (!checkDocumentAndRenderer(element))
+        return 0;
+
+    return createUnsafe(element, keyframeDictionaryVector, timingInput);
+}
+
+PassRefPtr<Animation> Animation::create(Element* element, Vector<Dictionary> keyframeDictionaryVector, double timingInput)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsAPIEnabled());
+
+    // FIXME: This test will not be neccessary once resolution of keyframe values occurs at
+    // animation application time.
+    if (!checkDocumentAndRenderer(element))
+        return 0;
+
+    return createUnsafe(element, keyframeDictionaryVector, timingInput);
+}
+
+PassRefPtr<Animation> Animation::create(Element* element, Vector<Dictionary> keyframeDictionaryVector)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsAPIEnabled());
+
+    // FIXME: This test will not be neccessary once resolution of keyframe values occurs at
+    // animation application time.
+    if (!checkDocumentAndRenderer(element))
+        return 0;
+
+    return createUnsafe(element, keyframeDictionaryVector);
+}
+
+void Animation::setStartDelay(Timing& timing, double startDelay)
+{
+    if (std::isfinite(startDelay))
+        timing.startDelay = startDelay;
+    else
+        timing.startDelay = 0;
+}
+
+void Animation::setEndDelay(Timing& timing, double endDelay)
+{
+    if (std::isfinite(endDelay))
+        timing.endDelay = endDelay;
+    else
+        timing.endDelay = 0;
+}
+
+void Animation::setFillMode(Timing& timing, String fillMode)
+{
+    if (fillMode == "none") {
+        timing.fillMode = Timing::FillModeNone;
+    } else if (fillMode == "backwards") {
+        timing.fillMode = Timing::FillModeBackwards;
+    } else if (fillMode == "both") {
+        timing.fillMode = Timing::FillModeBoth;
+    } else if (fillMode == "forwards") {
+        timing.fillMode = Timing::FillModeForwards;
+    } else {
+        timing.fillMode = Timing::FillModeAuto;
+    }
+}
+
+void Animation::setIterationStart(Timing& timing, double iterationStart)
+{
+    if (!std::isnan(iterationStart) && !std::isinf(iterationStart))
+        timing.iterationStart = std::max<double>(iterationStart, 0);
+    else
+        timing.iterationStart = 0;
+}
+
+void Animation::setIterationCount(Timing& timing, double iterationCount)
+{
+    if (!std::isnan(iterationCount))
+        timing.iterationCount = std::max<double>(iterationCount, 0);
+    else
+        timing.iterationCount = 1;
+}
+
+void Animation::setIterationDuration(Timing& timing, double iterationDuration)
+{
+    if (!std::isnan(iterationDuration) && iterationDuration >= 0)
+        timing.iterationDuration = iterationDuration;
+    else
+        timing.iterationDuration = std::numeric_limits<double>::quiet_NaN();
+}
+
+void Animation::setPlaybackRate(Timing& timing, double playbackRate)
+{
+    if (!std::isnan(playbackRate) && !std::isinf(playbackRate))
+        timing.playbackRate = playbackRate;
+    else
+        timing.playbackRate = 1;
+}
+
+void Animation::setPlaybackDirection(Timing& timing, String direction)
+{
+    if (direction == "reverse") {
+        timing.direction = Timing::PlaybackDirectionReverse;
+    } else if (direction == "alternate") {
+        timing.direction = Timing::PlaybackDirectionAlternate;
+    } else if (direction == "alternate-reverse") {
+        timing.direction = Timing::PlaybackDirectionAlternateReverse;
+    } else {
+        timing.direction = Timing::PlaybackDirectionNormal;
+    }
+}
+
+void Animation::setTimingFunction(Timing& timing, String timingFunctionString)
+{
+    RefPtr<CSSValue> timingFunctionValue = BisonCSSParser::parseAnimationTimingFunctionValue(timingFunctionString);
+    if (timingFunctionValue) {
+        RefPtr<TimingFunction> timingFunction = CSSToStyleMap::animationTimingFunction(timingFunctionValue.get(), false);
+        if (timingFunction) {
+            timing.timingFunction = timingFunction;
+            return;
+        }
+    }
+    timing.timingFunction = LinearTimingFunction::create();
+}
+
+void Animation::populateTiming(Timing& timing, Dictionary timingInputDictionary)
+{
+    // FIXME: This method needs to be refactored to handle invalid
+    // null, NaN, Infinity values better.
+    // See: http://www.w3.org/TR/WebIDL/#es-double
+    double startDelay = 0;
+    timingInputDictionary.get("delay", startDelay);
+    setStartDelay(timing, startDelay);
+
+    double endDelay = 0;
+    timingInputDictionary.get("endDelay", endDelay);
+    setEndDelay(timing, endDelay);
+
+    String fillMode;
+    timingInputDictionary.get("fill", fillMode);
+    setFillMode(timing, fillMode);
+
+    double iterationStart = 0;
+    timingInputDictionary.get("iterationStart", iterationStart);
+    setIterationStart(timing, iterationStart);
+
+    double iterationCount = 1;
+    timingInputDictionary.get("iterations", iterationCount);
+    setIterationCount(timing, iterationCount);
+
+    v8::Local<v8::Value> iterationDurationValue;
+    if (timingInputDictionary.get("duration", iterationDurationValue)) {
+        double iterationDuration = iterationDurationValue->NumberValue();
+        setIterationDuration(timing, iterationDuration);
+    }
+
+    double playbackRate = 1;
+    timingInputDictionary.get("playbackRate", playbackRate);
+    setPlaybackRate(timing, playbackRate);
+
+    String direction;
+    timingInputDictionary.get("direction", direction);
+    setPlaybackDirection(timing, direction);
+
+    String timingFunctionString;
+    timingInputDictionary.get("easing", timingFunctionString);
+    setTimingFunction(timing, timingFunctionString);
+
+    timing.assertValid();
+}
+
+static PassRefPtr<KeyframeEffectModel> createKeyframeEffectModel(Element* element, Vector<Dictionary> keyframeDictionaryVector)
+{
+    KeyframeEffectModel::KeyframeVector keyframes;
+    Vector<RefPtr<MutableStylePropertySet> > propertySetVector;
+
+    for (size_t i = 0; i < keyframeDictionaryVector.size(); ++i) {
+        RefPtr<MutableStylePropertySet> propertySet = MutableStylePropertySet::create();
+        propertySetVector.append(propertySet);
+
+        RefPtr<Keyframe> keyframe = Keyframe::create();
+        keyframes.append(keyframe);
+
+        double offset;
+        if (keyframeDictionaryVector[i].get("offset", offset)) {
+            keyframe->setOffset(offset);
+        }
+
+        String compositeString;
+        keyframeDictionaryVector[i].get("composite", compositeString);
+        if (compositeString == "add")
+            keyframe->setComposite(AnimationEffect::CompositeAdd);
+
+        String timingFunctionString;
+        if (keyframeDictionaryVector[i].get("easing", timingFunctionString)) {
+            RefPtr<CSSValue> timingFunctionValue = BisonCSSParser::parseAnimationTimingFunctionValue(timingFunctionString);
+            if (timingFunctionValue) {
+                keyframe->setEasing(CSSToStyleMap::animationTimingFunction(timingFunctionValue.get(), false));
+            }
+        }
+
+        Vector<String> keyframeProperties;
+        keyframeDictionaryVector[i].getOwnPropertyNames(keyframeProperties);
+
+        for (size_t j = 0; j < keyframeProperties.size(); ++j) {
+            String property = keyframeProperties[j];
+            CSSPropertyID id = camelCaseCSSPropertyNameToID(property);
+
+            // FIXME: There is no way to store invalid properties or invalid values
+            // in a Keyframe object, so for now I just skip over them. Eventually we
+            // will need to support getFrames(), which should return exactly the
+            // keyframes that were input through the API. We will add a layer to wrap
+            // KeyframeEffectModel, store input keyframes and implement getFrames.
+            if (id == CSSPropertyInvalid || !CSSAnimations::isAnimatableProperty(id))
+                continue;
+
+            String value;
+            keyframeDictionaryVector[i].get(property, value);
+            propertySet->setProperty(id, value);
+        }
+    }
+
+    // FIXME: Replace this with code that just parses, when that code is available.
+    RefPtr<KeyframeEffectModel> effect = StyleResolver::createKeyframeEffectModel(*element, propertySetVector, keyframes);
+    return effect;
+}
+
+PassRefPtr<Animation> Animation::createUnsafe(Element* element, Vector<Dictionary> keyframeDictionaryVector, Dictionary timingInput)
+{
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(element, keyframeDictionaryVector);
+
+    Timing timing;
+    populateTiming(timing, timingInput);
+
+    return create(element, effect, timing);
+}
+
+PassRefPtr<Animation> Animation::createUnsafe(Element* element, Vector<Dictionary> keyframeDictionaryVector, double timingInput)
+{
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(element, keyframeDictionaryVector);
+
+    Timing timing;
+    if (!std::isnan(timingInput))
+        timing.iterationDuration = std::max<double>(timingInput, 0);
+
+    return create(element, effect, timing);
+}
+
+PassRefPtr<Animation> Animation::createUnsafe(Element* element, Vector<Dictionary> keyframeDictionaryVector)
+{
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(element, keyframeDictionaryVector);
+    Timing timing;
+
+    return create(element, effect, timing);
+}
+
 Animation::Animation(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, Priority priority, PassOwnPtr<EventDelegate> eventDelegate)
     : TimedItem(timing, eventDelegate)
     , m_target(target)
@@ -99,10 +372,19 @@
     ASSERT(player());
     ASSERT(m_activeInAnimationStack);
     ensureAnimationStack(m_target.get()).remove(this);
-    cancelAnimationOnCompositor();
+
+    {
+        // FIXME: clearEffects is called from withins style recalc.
+        // This queries compositingState, which is not necessarily up to date.
+        // https://code.google.com/p/chromium/issues/detail?id=339847
+        DisableCompositingQueryAsserts disabler;
+        cancelAnimationOnCompositor();
+    }
+
     m_activeInAnimationStack = false;
     m_compositableValues.clear();
     m_target->setNeedsAnimationStyleRecalc();
+    invalidate();
 }
 
 bool Animation::updateChildrenAndEffects() const
@@ -120,28 +402,38 @@
     return false;
 }
 
-double Animation::calculateTimeToEffectChange(double localTime, double timeToNextIteration) const
+double Animation::calculateTimeToEffectChange(bool forwards, double localTime, double timeToNextIteration) const
 {
-    const double activeStartTime = startTime() + specified().startDelay;
+    const double start = startTime() + specifiedTiming().startDelay;
+    const double end = start + activeDuration();
+
     switch (phase()) {
     case PhaseBefore:
-        return activeStartTime - localTime;
+        ASSERT(start >= localTime);
+        return forwards
+            ? start - localTime
+            : std::numeric_limits<double>::infinity();
     case PhaseActive:
-        if (hasActiveAnimationsOnCompositor()) {
+        if (forwards && hasActiveAnimationsOnCompositor()) {
+            ASSERT(specifiedTiming().playbackRate == 1);
             // Need service to apply fill / fire events.
-            const double activeEndTime = activeStartTime + activeDuration();
-            return std::min(activeEndTime - localTime, timeToNextIteration);
+            return std::min(end - localTime, timeToNextIteration);
         }
         return 0;
     case PhaseAfter:
+        ASSERT(localTime >= end);
         // If this Animation is still in effect then it will need to update
         // when its parent goes out of effect. We have no way of knowing when
         // that will be, however, so the parent will need to supply it.
-        return std::numeric_limits<double>::infinity();
+        return forwards
+            ? std::numeric_limits<double>::infinity()
+            : localTime - end;
     case PhaseNone:
+        ASSERT(player() && player()->timeline() && !player()->timeline()->hasStarted());
+        return std::numeric_limits<double>::infinity();
     default:
         ASSERT_NOT_REACHED();
-        return 0;
+        return std::numeric_limits<double>::infinity();
     }
 }
 
@@ -149,7 +441,7 @@
 {
     if (!effect() || !m_target)
         return false;
-    return CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(specified(), *effect());
+    return CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(specifiedTiming(), *effect());
 }
 
 bool Animation::maybeStartAnimationOnCompositor()
@@ -159,7 +451,7 @@
         return false;
     if (!CompositorAnimations::instance()->canStartAnimationOnCompositor(*m_target.get()))
         return false;
-    if (!CompositorAnimations::instance()->startAnimationOnCompositor(*m_target.get(), specified(), *effect(), m_compositorAnimationIds))
+    if (!CompositorAnimations::instance()->startAnimationOnCompositor(*m_target.get(), specifiedTiming(), *effect(), m_compositorAnimationIds))
         return false;
     ASSERT(!m_compositorAnimationIds.isEmpty());
     return true;
diff --git a/Source/core/animation/Animation.h b/Source/core/animation/Animation.h
index f4ad206..04d7f15 100644
--- a/Source/core/animation/Animation.h
+++ b/Source/core/animation/Animation.h
@@ -38,6 +38,7 @@
 namespace WebCore {
 
 class Element;
+class Dictionary;
 
 class Animation FINAL : public TimedItem {
 
@@ -45,7 +46,24 @@
     enum Priority { DefaultPriority, TransitionPriority };
 
     static PassRefPtr<Animation> create(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, Priority = DefaultPriority, PassOwnPtr<EventDelegate> = nullptr);
-    virtual bool isAnimation() const OVERRIDE FINAL { return true; }
+    // Web Animations API Bindings constructors.
+    static PassRefPtr<Animation> create(Element*, Vector<Dictionary> keyframeDictionaryVector, Dictionary timingInput);
+    static PassRefPtr<Animation> create(Element*, Vector<Dictionary> keyframeDictionaryVector, double timingInput);
+    static PassRefPtr<Animation> create(Element*, Vector<Dictionary> keyframeDictionaryVector);
+
+    // FIXME: Move all of these setter methods out of Animation,
+    // possibly into a new class (TimingInput?).
+    static void setStartDelay(Timing&, double startDelay);
+    static void setEndDelay(Timing&, double endDelay);
+    static void setFillMode(Timing&, String fillMode);
+    static void setIterationStart(Timing&, double iterationStart);
+    static void setIterationCount(Timing&, double iterationCount);
+    static void setIterationDuration(Timing&, double iterationDuration);
+    static void setPlaybackRate(Timing&, double playbackRate);
+    static void setPlaybackDirection(Timing&, String direction);
+    static void setTimingFunction(Timing&, String timingFunctionString);
+
+    virtual bool isAnimation() const OVERRIDE { return true; }
 
     const AnimationEffect::CompositableValueList* compositableValues() const
     {
@@ -68,14 +86,20 @@
 
 protected:
     // Returns whether style recalc was triggered.
-    virtual bool applyEffects(bool previouslyInEffect);
-    virtual void clearEffects();
-    virtual bool updateChildrenAndEffects() const OVERRIDE FINAL;
-    virtual void didAttach() OVERRIDE FINAL;
-    virtual void willDetach() OVERRIDE FINAL;
-    virtual double calculateTimeToEffectChange(double inheritedTime, double timeToNextIteration) const OVERRIDE FINAL;
+    bool applyEffects(bool previouslyInEffect);
+    void clearEffects();
+    virtual bool updateChildrenAndEffects() const OVERRIDE;
+    virtual void didAttach() OVERRIDE;
+    virtual void willDetach() OVERRIDE;
+    virtual double calculateTimeToEffectChange(bool forwards, double inheritedTime, double timeToNextIteration) const OVERRIDE;
 
 private:
+    static void populateTiming(Timing&, Dictionary);
+    // createUnsafe should only be directly called from tests.
+    static PassRefPtr<Animation> createUnsafe(Element*, Vector<Dictionary> keyframeDictionaryVector, Dictionary timingInput);
+    static PassRefPtr<Animation> createUnsafe(Element*, Vector<Dictionary> keyframeDictionaryVector, double timingInput);
+    static PassRefPtr<Animation> createUnsafe(Element*, Vector<Dictionary> keyframeDictionaryVector);
+
     Animation(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, Priority, PassOwnPtr<EventDelegate>);
 
     RefPtr<Element> m_target;
@@ -89,6 +113,7 @@
     Vector<int> m_compositorAnimationIds;
 
     friend class CSSAnimations;
+    friend class AnimationAnimationTest;
 };
 
 DEFINE_TYPE_CASTS(Animation, TimedItem, timedItem, timedItem->isAnimation(), timedItem.isAnimation());
diff --git a/Source/core/html/HTMLImportDataClient.h b/Source/core/animation/Animation.idl
similarity index 82%
copy from Source/core/html/HTMLImportDataClient.h
copy to Source/core/animation/Animation.idl
index 0c26a22..ee19ab0 100644
--- a/Source/core/html/HTMLImportDataClient.h
+++ b/Source/core/animation/Animation.idl
@@ -28,17 +28,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef HTMLImportDataClient_h
-#define HTMLImportDataClient_h
-
-namespace WebCore {
-
-class HTMLImportDataClient {
-public:
-    virtual ~HTMLImportDataClient() { }
-    virtual void didFinish() = 0;
+[
+    RuntimeEnabled=WebAnimationsAPI,
+    Constructor(Element target, sequence<Dictionary> keyframes, Dictionary timingInput),
+    Constructor(Element target, sequence<Dictionary> keyframes, double timingInput),
+    Constructor(Element target, sequence<Dictionary> keyframes),
+] interface Animation : TimedItem {
 };
-
-}
-
-#endif // HTMLImportDataClient_h
diff --git a/Source/core/animation/AnimationEffect.h b/Source/core/animation/AnimationEffect.h
index d675a5f..7ea4d21 100644
--- a/Source/core/animation/AnimationEffect.h
+++ b/Source/core/animation/AnimationEffect.h
@@ -62,7 +62,7 @@
     virtual PassOwnPtr<CompositableValueList> sample(int iteration, double fraction) const = 0;
 
     virtual bool affects(CSSPropertyID) { return false; };
-    virtual bool isKeyframeAnimationEffect() const { return false; }
+    virtual bool isKeyframeEffectModel() const { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/animation/AnimationHelpers.h b/Source/core/animation/AnimationHelpers.h
new file mode 100644
index 0000000..daeb2d5
--- /dev/null
+++ b/Source/core/animation/AnimationHelpers.h
@@ -0,0 +1,33 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef AnimationHelpers_h
+#define AnimationHelpers_h
+
+#include "core/css/parser/BisonCSSParser.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+static inline CSSPropertyID camelCaseCSSPropertyNameToID(const String& propertyName)
+{
+    if (propertyName.find('-') != kNotFound)
+        return CSSPropertyInvalid;
+
+    StringBuilder builder;
+    size_t position = 0;
+    size_t end;
+    while ((end = propertyName.find(isASCIIUpper, position)) != kNotFound) {
+        builder.append(propertyName.substring(position, end - position) + "-" + toASCIILower((propertyName)[end]));
+        position = end + 1;
+    }
+    builder.append(propertyName.substring(position));
+    // Doesn't handle prefixed properties.
+    CSSPropertyID id = cssPropertyID(builder.toString());
+    return id;
+}
+
+} // namespace WebCore
+
+#endif // AnimationHelpers_h
diff --git a/Source/core/animation/AnimationHelpersTest.cpp b/Source/core/animation/AnimationHelpersTest.cpp
new file mode 100644
index 0000000..df3727f
--- /dev/null
+++ b/Source/core/animation/AnimationHelpersTest.cpp
@@ -0,0 +1,24 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/animation/AnimationHelpers.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+TEST(AnimationAnimationHelpersTest, ParseCamelCasePropertyNames)
+{
+    EXPECT_EQ(CSSPropertyInvalid, camelCaseCSSPropertyNameToID(String("line-height")));
+    EXPECT_EQ(CSSPropertyLineHeight, camelCaseCSSPropertyNameToID(String("lineHeight")));
+    EXPECT_EQ(CSSPropertyBorderTopWidth, camelCaseCSSPropertyNameToID(String("borderTopWidth")));
+    EXPECT_EQ(CSSPropertyWidth, camelCaseCSSPropertyNameToID(String("width")));
+    EXPECT_EQ(CSSPropertyInvalid, camelCaseCSSPropertyNameToID(String("Width")));
+    EXPECT_EQ(CSSPropertyInvalid, camelCaseCSSPropertyNameToID(String("-webkit-transform")));
+    EXPECT_EQ(CSSPropertyInvalid, camelCaseCSSPropertyNameToID(String("webkitTransform")));
+    EXPECT_EQ(CSSPropertyInvalid, camelCaseCSSPropertyNameToID(String("cssFloat")));
+}
+
+} // namespace WebCore
diff --git a/Source/core/animation/AnimationTest.cpp b/Source/core/animation/AnimationTest.cpp
new file mode 100644
index 0000000..9ea0e3f
--- /dev/null
+++ b/Source/core/animation/AnimationTest.cpp
@@ -0,0 +1,837 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/animation/Animation.h"
+
+#include "bindings/v8/Dictionary.h"
+#include "core/animation/AnimatableLength.h"
+#include "core/animation/AnimationClock.h"
+#include "core/animation/AnimationHelpers.h"
+#include "core/animation/DocumentTimeline.h"
+#include "core/animation/KeyframeEffectModel.h"
+#include "core/animation/TimedItemTiming.h"
+#include "platform/animation/TimingFunctionTestHelper.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+namespace {
+
+v8::Handle<v8::Value> stringToV8Value(String string)
+{
+    return v8::Handle<v8::Value>::Cast(v8String(v8::Isolate::GetCurrent(), string));
+}
+
+v8::Handle<v8::Value> doubleToV8Value(double number)
+{
+    return v8::Handle<v8::Value>::Cast(v8::Number::New(v8::Isolate::GetCurrent(), number));
+}
+
+void setV8ObjectPropertyAsString(v8::Handle<v8::Object> object, String name, String value)
+{
+    object->Set(stringToV8Value(name), stringToV8Value(value));
+}
+
+void setV8ObjectPropertyAsNumber(v8::Handle<v8::Object> object, String name, double value)
+{
+    object->Set(stringToV8Value(name), doubleToV8Value(value));
+}
+
+} // namespace
+
+class AnimationAnimationTest : public ::testing::Test {
+protected:
+    virtual void SetUp()
+    {
+        document = Document::create();
+        document->animationClock().resetTimeForTesting();
+        element = document->createElement("foo", ASSERT_NO_EXCEPTION);
+        document->timeline()->setZeroTime(0);
+        ASSERT_EQ(0, document->timeline()->currentTime());
+    }
+
+    RefPtr<Document> document;
+    RefPtr<Element> element;
+
+    PassRefPtr<Animation> createAnimation(Element* element, Vector<Dictionary> keyframeDictionaryVector, Dictionary timingInput)
+    {
+        return Animation::createUnsafe(element, keyframeDictionaryVector, timingInput);
+    }
+
+    PassRefPtr<Animation> createAnimation(Element* element, Vector<Dictionary> keyframeDictionaryVector, double timingInput)
+    {
+        return Animation::createUnsafe(element, keyframeDictionaryVector, timingInput);
+    }
+
+    PassRefPtr<Animation> createAnimation(Element* element, Vector<Dictionary> keyframeDictionaryVector)
+    {
+        return Animation::createUnsafe(element, keyframeDictionaryVector);
+    }
+
+    void populateTiming(Timing& timing, Dictionary timingInputDictionary)
+    {
+        Animation::populateTiming(timing, timingInputDictionary);
+    }
+
+    void applyTimingInputNumber(Timing& timing, v8::Isolate* isolate, String timingProperty, double timingPropertyValue)
+    {
+        v8::Handle<v8::Object> timingInput = v8::Object::New(isolate);
+        setV8ObjectPropertyAsNumber(timingInput, timingProperty, timingPropertyValue);
+        Dictionary timingInputDictionary = Dictionary(v8::Handle<v8::Value>::Cast(timingInput), isolate);
+        populateTiming(timing, timingInputDictionary);
+    }
+
+    void applyTimingInputString(Timing& timing, v8::Isolate* isolate, String timingProperty, String timingPropertyValue)
+    {
+        v8::Handle<v8::Object> timingInput = v8::Object::New(isolate);
+        setV8ObjectPropertyAsString(timingInput, timingProperty, timingPropertyValue);
+        Dictionary timingInputDictionary = Dictionary(v8::Handle<v8::Value>::Cast(timingInput), isolate);
+        populateTiming(timing, timingInputDictionary);
+    }
+};
+
+TEST_F(AnimationAnimationTest, CanCreateAnAnimation)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Vector<Dictionary> jsKeyframes;
+    v8::Handle<v8::Object> keyframe1 = v8::Object::New(isolate);
+    v8::Handle<v8::Object> keyframe2 = v8::Object::New(isolate);
+
+    setV8ObjectPropertyAsString(keyframe1, "width", "100px");
+    setV8ObjectPropertyAsString(keyframe1, "offset", "0");
+    setV8ObjectPropertyAsString(keyframe1, "easing", "ease-in-out");
+    setV8ObjectPropertyAsString(keyframe2, "width", "0px");
+    setV8ObjectPropertyAsString(keyframe2, "offset", "1");
+    setV8ObjectPropertyAsString(keyframe2, "easing", "cubic-bezier(1, 1, 0.3, 0.3)");
+
+    jsKeyframes.append(Dictionary(keyframe1, isolate));
+    jsKeyframes.append(Dictionary(keyframe2, isolate));
+
+    String value1;
+    ASSERT_TRUE(jsKeyframes[0].get("width", value1));
+    ASSERT_EQ("100px", value1);
+
+    String value2;
+    ASSERT_TRUE(jsKeyframes[1].get("width", value2));
+    ASSERT_EQ("0px", value2);
+
+    RefPtr<Animation> animation = createAnimation(element.get(), jsKeyframes, 0);
+
+    Element* target = animation->target();
+    EXPECT_EQ(*element.get(), *target);
+
+    const KeyframeEffectModel::KeyframeVector keyframes =
+        toKeyframeEffectModel(animation->effect())->getFrames();
+
+    EXPECT_EQ(0, keyframes[0]->offset());
+    EXPECT_EQ(1, keyframes[1]->offset());
+
+    const AnimatableValue* keyframe1Width = keyframes[0]->propertyValue(CSSPropertyWidth);
+    const AnimatableValue* keyframe2Width = keyframes[1]->propertyValue(CSSPropertyWidth);
+    ASSERT(keyframe1Width);
+    ASSERT(keyframe2Width);
+
+    EXPECT_TRUE(keyframe1Width->isLength());
+    EXPECT_TRUE(keyframe2Width->isLength());
+
+    EXPECT_EQ("100px", toAnimatableLength(keyframe1Width)->toCSSValue()->cssText());
+    EXPECT_EQ("0px", toAnimatableLength(keyframe2Width)->toCSSValue()->cssText());
+
+    EXPECT_EQ(*(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut)), *keyframes[0]->easing());
+    EXPECT_EQ(*(CubicBezierTimingFunction::create(1, 1, 0.3, 0.3).get()), *keyframes[1]->easing());
+}
+
+TEST_F(AnimationAnimationTest, CanSetDuration)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Vector<Dictionary, 0> jsKeyframes;
+    double duration = 2;
+
+    RefPtr<Animation> animation = createAnimation(element.get(), jsKeyframes, duration);
+
+    EXPECT_EQ(duration, animation->specifiedTiming().iterationDuration);
+}
+
+TEST_F(AnimationAnimationTest, CanOmitSpecifiedDuration)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Vector<Dictionary, 0> jsKeyframes;
+
+    RefPtr<Animation> animation = createAnimation(element.get(), jsKeyframes);
+
+    EXPECT_TRUE(std::isnan(animation->specifiedTiming().iterationDuration));
+}
+
+TEST_F(AnimationAnimationTest, ClipNegativeDurationToZero)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Vector<Dictionary, 0> jsKeyframes;
+
+    RefPtr<Animation> animation = createAnimation(element.get(), jsKeyframes, -2);
+
+    EXPECT_EQ(0, animation->specifiedTiming().iterationDuration);
+}
+
+TEST_F(AnimationAnimationTest, SpecifiedGetters)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Vector<Dictionary, 0> jsKeyframes;
+
+    v8::Handle<v8::Object> timingInput = v8::Object::New(isolate);
+    setV8ObjectPropertyAsNumber(timingInput, "delay", 2);
+    setV8ObjectPropertyAsNumber(timingInput, "endDelay", 0.5);
+    setV8ObjectPropertyAsString(timingInput, "fill", "backwards");
+    setV8ObjectPropertyAsNumber(timingInput, "iterationStart", 2);
+    setV8ObjectPropertyAsNumber(timingInput, "iterations", 10);
+    setV8ObjectPropertyAsNumber(timingInput, "playbackRate", 2);
+    setV8ObjectPropertyAsString(timingInput, "direction", "reverse");
+    setV8ObjectPropertyAsString(timingInput, "easing", "step-start");
+    Dictionary timingInputDictionary = Dictionary(v8::Handle<v8::Value>::Cast(timingInput), isolate);
+
+    RefPtr<Animation> animation = createAnimation(element.get(), jsKeyframes, timingInputDictionary);
+
+    RefPtr<TimedItemTiming> specified = animation->specified();
+    EXPECT_EQ(2, specified->delay());
+    EXPECT_EQ(0.5, specified->endDelay());
+    EXPECT_EQ("backwards", specified->fill());
+    EXPECT_EQ(2, specified->iterationStart());
+    EXPECT_EQ(10, specified->iterations());
+    EXPECT_EQ(2, specified->playbackRate());
+    EXPECT_EQ("reverse", specified->direction());
+    EXPECT_EQ("step-start", specified->easing());
+}
+
+TEST_F(AnimationAnimationTest, SpecifiedDurationGetter)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Vector<Dictionary, 0> jsKeyframes;
+
+    v8::Handle<v8::Object> timingInputWithDuration = v8::Object::New(isolate);
+    setV8ObjectPropertyAsNumber(timingInputWithDuration, "duration", 2.5);
+    Dictionary timingInputDictionaryWithDuration = Dictionary(v8::Handle<v8::Value>::Cast(timingInputWithDuration), isolate);
+
+    RefPtr<Animation> animationWithDuration = createAnimation(element.get(), jsKeyframes, timingInputDictionaryWithDuration);
+
+    RefPtr<TimedItemTiming> specifiedWithDuration = animationWithDuration->specified();
+    bool isNumber = false;
+    double numberDuration = std::numeric_limits<double>::quiet_NaN();
+    bool isString = false;
+    String stringDuration = "";
+    specifiedWithDuration->getDuration("duration", isNumber, numberDuration, isString, stringDuration);
+    EXPECT_TRUE(isNumber);
+    EXPECT_EQ(2.5, numberDuration);
+    EXPECT_FALSE(isString);
+    EXPECT_EQ("", stringDuration);
+
+
+    v8::Handle<v8::Object> timingInputNoDuration = v8::Object::New(isolate);
+    Dictionary timingInputDictionaryNoDuration = Dictionary(v8::Handle<v8::Value>::Cast(timingInputNoDuration), isolate);
+
+    RefPtr<Animation> animationNoDuration = createAnimation(element.get(), jsKeyframes, timingInputDictionaryNoDuration);
+
+    RefPtr<TimedItemTiming> specifiedNoDuration = animationNoDuration->specified();
+    isNumber = false;
+    numberDuration = std::numeric_limits<double>::quiet_NaN();
+    isString = false;
+    stringDuration = "";
+    specifiedNoDuration->getDuration("duration", isNumber, numberDuration, isString, stringDuration);
+    EXPECT_FALSE(isNumber);
+    EXPECT_TRUE(std::isnan(numberDuration));
+    EXPECT_TRUE(isString);
+    EXPECT_EQ("auto", stringDuration);
+}
+
+TEST_F(AnimationAnimationTest, SpecifiedSetters)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Vector<Dictionary, 0> jsKeyframes;
+    v8::Handle<v8::Object> timingInput = v8::Object::New(isolate);
+    Dictionary timingInputDictionary = Dictionary(v8::Handle<v8::Value>::Cast(timingInput), isolate);
+    RefPtr<Animation> animation = createAnimation(element.get(), jsKeyframes, timingInputDictionary);
+
+    RefPtr<TimedItemTiming> specified = animation->specified();
+
+    EXPECT_EQ(0, specified->delay());
+    specified->setDelay(2);
+    EXPECT_EQ(2, specified->delay());
+
+    EXPECT_EQ(0, specified->endDelay());
+    specified->setEndDelay(0.5);
+    EXPECT_EQ(0.5, specified->endDelay());
+
+    EXPECT_EQ("auto", specified->fill());
+    specified->setFill("backwards");
+    EXPECT_EQ("backwards", specified->fill());
+
+    EXPECT_EQ(0, specified->iterationStart());
+    specified->setIterationStart(2);
+    EXPECT_EQ(2, specified->iterationStart());
+
+    EXPECT_EQ(1, specified->iterations());
+    specified->setIterations(10);
+    EXPECT_EQ(10, specified->iterations());
+
+    EXPECT_EQ(1, specified->playbackRate());
+    specified->setPlaybackRate(2);
+    EXPECT_EQ(2, specified->playbackRate());
+
+    EXPECT_EQ("normal", specified->direction());
+    specified->setDirection("reverse");
+    EXPECT_EQ("reverse", specified->direction());
+
+    EXPECT_EQ("linear", specified->easing());
+    specified->setEasing("step-start");
+    EXPECT_EQ("step-start", specified->easing());
+}
+
+TEST_F(AnimationAnimationTest, SetSpecifiedDuration)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Vector<Dictionary, 0> jsKeyframes;
+    v8::Handle<v8::Object> timingInput = v8::Object::New(isolate);
+    Dictionary timingInputDictionary = Dictionary(v8::Handle<v8::Value>::Cast(timingInput), isolate);
+    RefPtr<Animation> animation = createAnimation(element.get(), jsKeyframes, timingInputDictionary);
+
+    RefPtr<TimedItemTiming> specified = animation->specified();
+
+    bool isNumber = false;
+    double numberDuration = std::numeric_limits<double>::quiet_NaN();
+    bool isString = false;
+    String stringDuration = "";
+    specified->getDuration("duration", isNumber, numberDuration, isString, stringDuration);
+    EXPECT_FALSE(isNumber);
+    EXPECT_TRUE(std::isnan(numberDuration));
+    EXPECT_TRUE(isString);
+    EXPECT_EQ("auto", stringDuration);
+
+    specified->setDuration("duration", 2.5);
+    isNumber = false;
+    numberDuration = std::numeric_limits<double>::quiet_NaN();
+    isString = false;
+    stringDuration = "";
+    specified->getDuration("duration", isNumber, numberDuration, isString, stringDuration);
+    EXPECT_TRUE(isNumber);
+    EXPECT_EQ(2.5, numberDuration);
+    EXPECT_FALSE(isString);
+    EXPECT_EQ("", stringDuration);
+}
+
+TEST_F(AnimationAnimationTest, TimingInputStartDelay)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing timing;
+    EXPECT_EQ(0, timing.startDelay);
+
+    applyTimingInputNumber(timing, isolate, "delay", 1.1);
+    EXPECT_EQ(1.1, timing.startDelay);
+    timing.startDelay = 0;
+
+    applyTimingInputNumber(timing, isolate, "delay", -1);
+    EXPECT_EQ(-1, timing.startDelay);
+    timing.startDelay = 0;
+
+    applyTimingInputString(timing, isolate, "delay", "1");
+    EXPECT_EQ(1, timing.startDelay);
+    timing.startDelay = 0;
+
+    applyTimingInputString(timing, isolate, "delay", "1s");
+    EXPECT_EQ(0, timing.startDelay);
+    timing.startDelay = 0;
+
+    applyTimingInputString(timing, isolate, "delay", "Infinity");
+    EXPECT_EQ(0, timing.startDelay);
+    timing.startDelay = 0;
+
+    applyTimingInputString(timing, isolate, "delay", "-Infinity");
+    EXPECT_EQ(0, timing.startDelay);
+    timing.startDelay = 0;
+
+    applyTimingInputString(timing, isolate, "delay", "NaN");
+    EXPECT_EQ(0, timing.startDelay);
+    timing.startDelay = 0;
+
+    applyTimingInputString(timing, isolate, "delay", "rubbish");
+    EXPECT_EQ(0, timing.startDelay);
+    timing.startDelay = 0;
+}
+
+TEST_F(AnimationAnimationTest, TimingInputEndDelay)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing timing;
+    applyTimingInputNumber(timing, isolate, "endDelay", 10);
+    EXPECT_EQ(10, timing.endDelay);
+    applyTimingInputNumber(timing, isolate, "endDelay", -2.5);
+    EXPECT_EQ(-2.5, timing.endDelay);
+}
+
+TEST_F(AnimationAnimationTest, TimingInputFillMode)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing timing;
+    Timing::FillMode defaultFillMode = Timing::FillModeAuto;
+    EXPECT_EQ(defaultFillMode, timing.fillMode);
+
+    applyTimingInputString(timing, isolate, "fill", "auto");
+    EXPECT_EQ(Timing::FillModeAuto, timing.fillMode);
+    timing.fillMode = defaultFillMode;
+
+    applyTimingInputString(timing, isolate, "fill", "forwards");
+    EXPECT_EQ(Timing::FillModeForwards, timing.fillMode);
+    timing.fillMode = defaultFillMode;
+
+    applyTimingInputString(timing, isolate, "fill", "none");
+    EXPECT_EQ(Timing::FillModeNone, timing.fillMode);
+    timing.fillMode = defaultFillMode;
+
+    applyTimingInputString(timing, isolate, "fill", "backwards");
+    EXPECT_EQ(Timing::FillModeBackwards, timing.fillMode);
+    timing.fillMode = defaultFillMode;
+
+    applyTimingInputString(timing, isolate, "fill", "both");
+    EXPECT_EQ(Timing::FillModeBoth, timing.fillMode);
+    timing.fillMode = defaultFillMode;
+
+    applyTimingInputString(timing, isolate, "fill", "everything!");
+    EXPECT_EQ(defaultFillMode, timing.fillMode);
+    timing.fillMode = defaultFillMode;
+
+    applyTimingInputString(timing, isolate, "fill", "backwardsandforwards");
+    EXPECT_EQ(defaultFillMode, timing.fillMode);
+    timing.fillMode = defaultFillMode;
+
+    applyTimingInputNumber(timing, isolate, "fill", 2);
+    EXPECT_EQ(defaultFillMode, timing.fillMode);
+    timing.fillMode = defaultFillMode;
+}
+
+TEST_F(AnimationAnimationTest, TimingInputIterationStart)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing timing;
+    EXPECT_EQ(0, timing.iterationStart);
+
+    applyTimingInputNumber(timing, isolate, "iterationStart", 1.1);
+    EXPECT_EQ(1.1, timing.iterationStart);
+    timing.iterationStart = 0;
+
+    applyTimingInputNumber(timing, isolate, "iterationStart", -1);
+    EXPECT_EQ(0, timing.iterationStart);
+    timing.iterationStart = 0;
+
+    applyTimingInputString(timing, isolate, "iterationStart", "Infinity");
+    EXPECT_EQ(0, timing.iterationStart);
+    timing.iterationStart = 0;
+
+    applyTimingInputString(timing, isolate, "iterationStart", "-Infinity");
+    EXPECT_EQ(0, timing.iterationStart);
+    timing.iterationStart = 0;
+
+    applyTimingInputString(timing, isolate, "iterationStart", "NaN");
+    EXPECT_EQ(0, timing.iterationStart);
+    timing.iterationStart = 0;
+
+    applyTimingInputString(timing, isolate, "iterationStart", "rubbish");
+    EXPECT_EQ(0, timing.iterationStart);
+    timing.iterationStart = 0;
+}
+
+TEST_F(AnimationAnimationTest, TimingInputIterationCount)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing timing;
+    EXPECT_EQ(1, timing.iterationCount);
+
+    applyTimingInputNumber(timing, isolate, "iterations", 2.1);
+    EXPECT_EQ(2.1, timing.iterationCount);
+    timing.iterationCount = 1;
+
+    applyTimingInputNumber(timing, isolate, "iterations", -1);
+    EXPECT_EQ(0, timing.iterationCount);
+    timing.iterationCount = 1;
+
+    applyTimingInputString(timing, isolate, "iterations", "Infinity");
+    EXPECT_TRUE(std::isinf(timing.iterationCount) && (timing.iterationCount > 0));
+    timing.iterationCount = 1;
+
+    applyTimingInputString(timing, isolate, "iterations", "-Infinity");
+    EXPECT_EQ(0, timing.iterationCount);
+    timing.iterationCount = 1;
+
+    applyTimingInputString(timing, isolate, "iterations", "NaN");
+    EXPECT_EQ(1, timing.iterationCount);
+    timing.iterationCount = 1;
+
+    applyTimingInputString(timing, isolate, "iterations", "rubbish");
+    EXPECT_EQ(1, timing.iterationCount);
+    timing.iterationCount = 1;
+}
+
+TEST_F(AnimationAnimationTest, TimingInputIterationDuration)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing timing;
+    EXPECT_TRUE(std::isnan(timing.iterationDuration));
+
+    applyTimingInputNumber(timing, isolate, "duration", 1.1);
+    EXPECT_EQ(1.1, timing.iterationDuration);
+    timing.iterationDuration = std::numeric_limits<double>::quiet_NaN();
+
+    applyTimingInputNumber(timing, isolate, "duration", -1);
+    EXPECT_TRUE(std::isnan(timing.iterationDuration));
+    timing.iterationDuration = std::numeric_limits<double>::quiet_NaN();
+
+    applyTimingInputString(timing, isolate, "duration", "1");
+    EXPECT_EQ(1, timing.iterationDuration);
+    timing.iterationDuration = std::numeric_limits<double>::quiet_NaN();
+
+    applyTimingInputString(timing, isolate, "duration", "Infinity");
+    EXPECT_TRUE(std::isinf(timing.iterationDuration) && (timing.iterationDuration > 0));
+    timing.iterationDuration = std::numeric_limits<double>::quiet_NaN();
+
+    applyTimingInputString(timing, isolate, "duration", "-Infinity");
+    EXPECT_TRUE(std::isnan(timing.iterationDuration));
+    timing.iterationDuration = std::numeric_limits<double>::quiet_NaN();
+
+    applyTimingInputString(timing, isolate, "duration", "NaN");
+    EXPECT_TRUE(std::isnan(timing.iterationDuration));
+    timing.iterationDuration = std::numeric_limits<double>::quiet_NaN();
+
+    applyTimingInputString(timing, isolate, "duration", "auto");
+    EXPECT_TRUE(std::isnan(timing.iterationDuration));
+    timing.iterationDuration = std::numeric_limits<double>::quiet_NaN();
+
+    applyTimingInputString(timing, isolate, "duration", "rubbish");
+    EXPECT_TRUE(std::isnan(timing.iterationDuration));
+    timing.iterationDuration = std::numeric_limits<double>::quiet_NaN();
+}
+
+TEST_F(AnimationAnimationTest, TimingInputPlaybackRate)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing timing;
+    EXPECT_EQ(1, timing.playbackRate);
+
+    applyTimingInputNumber(timing, isolate, "playbackRate", 2.1);
+    EXPECT_EQ(2.1, timing.playbackRate);
+    timing.playbackRate = 1;
+
+    applyTimingInputNumber(timing, isolate, "playbackRate", -1);
+    EXPECT_EQ(-1, timing.playbackRate);
+    timing.playbackRate = 1;
+
+    applyTimingInputString(timing, isolate, "playbackRate", "Infinity");
+    EXPECT_EQ(1, timing.playbackRate);
+    timing.playbackRate = 1;
+
+    applyTimingInputString(timing, isolate, "playbackRate", "-Infinity");
+    EXPECT_EQ(1, timing.playbackRate);
+    timing.playbackRate = 1;
+
+    applyTimingInputString(timing, isolate, "playbackRate", "NaN");
+    EXPECT_EQ(1, timing.playbackRate);
+    timing.playbackRate = 1;
+
+    applyTimingInputString(timing, isolate, "playbackRate", "rubbish");
+    EXPECT_EQ(1, timing.playbackRate);
+    timing.playbackRate = 1;
+}
+
+TEST_F(AnimationAnimationTest, TimingInputDirection)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing timing;
+    Timing::PlaybackDirection defaultPlaybackDirection = Timing::PlaybackDirectionNormal;
+    EXPECT_EQ(defaultPlaybackDirection, timing.direction);
+
+    applyTimingInputString(timing, isolate, "direction", "normal");
+    EXPECT_EQ(Timing::PlaybackDirectionNormal, timing.direction);
+    timing.direction = defaultPlaybackDirection;
+
+    applyTimingInputString(timing, isolate, "direction", "reverse");
+    EXPECT_EQ(Timing::PlaybackDirectionReverse, timing.direction);
+    timing.direction = defaultPlaybackDirection;
+
+    applyTimingInputString(timing, isolate, "direction", "alternate");
+    EXPECT_EQ(Timing::PlaybackDirectionAlternate, timing.direction);
+    timing.direction = defaultPlaybackDirection;
+
+    applyTimingInputString(timing, isolate, "direction", "alternate-reverse");
+    EXPECT_EQ(Timing::PlaybackDirectionAlternateReverse, timing.direction);
+    timing.direction = defaultPlaybackDirection;
+
+    applyTimingInputString(timing, isolate, "direction", "rubbish");
+    EXPECT_EQ(defaultPlaybackDirection, timing.direction);
+    timing.direction = defaultPlaybackDirection;
+
+    applyTimingInputNumber(timing, isolate, "direction", 2);
+    EXPECT_EQ(defaultPlaybackDirection, timing.direction);
+    timing.direction = defaultPlaybackDirection;
+}
+
+TEST_F(AnimationAnimationTest, TimingInputTimingFunction)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing timing;
+    const RefPtr<TimingFunction> defaultTimingFunction = LinearTimingFunction::create();
+    EXPECT_EQ(*defaultTimingFunction.get(), *timing.timingFunction.get());
+
+    applyTimingInputString(timing, isolate, "easing", "ease");
+    EXPECT_EQ(*(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease)), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "ease-in");
+    EXPECT_EQ(*(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn)), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "ease-out");
+    EXPECT_EQ(*(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut)), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "ease-in-out");
+    EXPECT_EQ(*(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut)), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "linear");
+    EXPECT_EQ(*(LinearTimingFunction::create()), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "initial");
+    EXPECT_EQ(*defaultTimingFunction.get(), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "step-start");
+    EXPECT_EQ(*(StepsTimingFunction::preset(StepsTimingFunction::Start)), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "step-end");
+    EXPECT_EQ(*(StepsTimingFunction::preset(StepsTimingFunction::End)), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "cubic-bezier(1, 1, 0.3, 0.3)");
+    EXPECT_EQ(*(CubicBezierTimingFunction::create(1, 1, 0.3, 0.3).get()), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "steps(3, start)");
+    EXPECT_EQ(*(StepsTimingFunction::create(3, true).get()), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "steps(5, end)");
+    EXPECT_EQ(*(StepsTimingFunction::create(5, false).get()), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "steps(5.6, end)");
+    EXPECT_EQ(*defaultTimingFunction.get(), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    // FIXME: Step-middle not yet implemented. Change this test when it is working.
+    applyTimingInputString(timing, isolate, "easing", "steps(5, middle)");
+    EXPECT_EQ(*defaultTimingFunction.get(), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "cubic-bezier(2, 2, 0.3, 0.3)");
+    EXPECT_EQ(*defaultTimingFunction.get(), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputString(timing, isolate, "easing", "rubbish");
+    EXPECT_EQ(*defaultTimingFunction.get(), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+
+    applyTimingInputNumber(timing, isolate, "easing", 2);
+    EXPECT_EQ(*defaultTimingFunction.get(), *timing.timingFunction.get());
+    timing.timingFunction = defaultTimingFunction;
+}
+
+TEST_F(AnimationAnimationTest, TimingInputEmpty)
+{
+    v8::Isolate* isolate = v8::Isolate::GetCurrent();
+    v8::HandleScope scope(isolate);
+    v8::Local<v8::Context> context = v8::Context::New(isolate);
+    v8::Context::Scope contextScope(context);
+
+    Timing updatedTiming;
+    Timing controlTiming;
+
+    v8::Handle<v8::Object> timingInput = v8::Object::New(isolate);
+    Dictionary timingInputDictionary = Dictionary(v8::Handle<v8::Value>::Cast(timingInput), isolate);
+    populateTiming(updatedTiming, timingInputDictionary);
+
+    EXPECT_EQ(controlTiming.startDelay, updatedTiming.startDelay);
+    EXPECT_EQ(controlTiming.fillMode, updatedTiming.fillMode);
+    EXPECT_EQ(controlTiming.iterationStart, updatedTiming.iterationStart);
+    EXPECT_EQ(controlTiming.iterationCount, updatedTiming.iterationCount);
+    EXPECT_TRUE(std::isnan(updatedTiming.iterationDuration));
+    EXPECT_EQ(controlTiming.playbackRate, updatedTiming.playbackRate);
+    EXPECT_EQ(controlTiming.direction, updatedTiming.direction);
+    EXPECT_EQ(*controlTiming.timingFunction.get(), *updatedTiming.timingFunction.get());
+}
+
+TEST_F(AnimationAnimationTest, TimeToEffectChange)
+{
+    Timing timing;
+    timing.iterationDuration = 100;
+    timing.startDelay = 100;
+    timing.endDelay = 100;
+    timing.fillMode = Timing::FillModeNone;
+    RefPtr<Animation> animation = Animation::create(0, 0, timing);
+    RefPtr<Player> player = document->timeline()->play(animation.get());
+    double inf = std::numeric_limits<double>::infinity();
+
+    EXPECT_EQ(100, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(inf, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(100);
+    EXPECT_EQ(0, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(0, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(199);
+    EXPECT_EQ(0, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(0, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(200);
+    // End-exclusive.
+    EXPECT_EQ(inf, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(0, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(300);
+    EXPECT_EQ(inf, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(100, animation->timeToReverseEffectChange());
+}
+
+TEST_F(AnimationAnimationTest, TimeToEffectChangeWithPlaybackRate)
+{
+    Timing timing;
+    timing.iterationDuration = 100;
+    timing.startDelay = 100;
+    timing.endDelay = 100;
+    timing.playbackRate = 2;
+    timing.fillMode = Timing::FillModeNone;
+    RefPtr<Animation> animation = Animation::create(0, 0, timing);
+    RefPtr<Player> player = document->timeline()->play(animation.get());
+    double inf = std::numeric_limits<double>::infinity();
+
+    EXPECT_EQ(100, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(inf, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(100);
+    EXPECT_EQ(0, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(0, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(149);
+    EXPECT_EQ(0, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(0, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(150);
+    // End-exclusive.
+    EXPECT_EQ(inf, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(0, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(200);
+    EXPECT_EQ(inf, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(50, animation->timeToReverseEffectChange());
+}
+
+TEST_F(AnimationAnimationTest, TimeToEffectChangeWithNegativePlaybackRate)
+{
+    Timing timing;
+    timing.iterationDuration = 100;
+    timing.startDelay = 100;
+    timing.endDelay = 100;
+    timing.playbackRate = -2;
+    timing.fillMode = Timing::FillModeNone;
+    RefPtr<Animation> animation = Animation::create(0, 0, timing);
+    RefPtr<Player> player = document->timeline()->play(animation.get());
+    double inf = std::numeric_limits<double>::infinity();
+
+    EXPECT_EQ(100, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(inf, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(100);
+    EXPECT_EQ(0, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(0, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(149);
+    EXPECT_EQ(0, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(0, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(150);
+    EXPECT_EQ(inf, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(0, animation->timeToReverseEffectChange());
+
+    player->setCurrentTime(200);
+    EXPECT_EQ(inf, animation->timeToForwardsEffectChange());
+    EXPECT_EQ(50, animation->timeToReverseEffectChange());
+}
+
+} // namespace WebCore
diff --git a/Source/core/animation/AnimationTranslationUtil.cpp b/Source/core/animation/AnimationTranslationUtil.cpp
new file mode 100644
index 0000000..e73df49
--- /dev/null
+++ b/Source/core/animation/AnimationTranslationUtil.cpp
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2012 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
+ */
+
+#include "config.h"
+
+#include "core/animation/AnimationTranslationUtil.h"
+
+#include "platform/graphics/filters/FilterOperations.h"
+#include "platform/graphics/filters/SkiaImageFilterBuilder.h"
+#include "platform/transforms/InterpolatedTransformOperation.h"
+#include "platform/transforms/Matrix3DTransformOperation.h"
+#include "platform/transforms/MatrixTransformOperation.h"
+#include "platform/transforms/PerspectiveTransformOperation.h"
+#include "platform/transforms/RotateTransformOperation.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/SkewTransformOperation.h"
+#include "platform/transforms/TransformOperations.h"
+#include "platform/transforms/TransformationMatrix.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+#include "public/platform/WebTransformOperations.h"
+
+using namespace std;
+using namespace blink;
+
+namespace WebCore {
+
+void toWebTransformOperations(const TransformOperations& transformOperations, WebTransformOperations* webTransformOperations)
+{
+    // We need to do a deep copy the transformOperations may contain ref pointers to TransformOperation objects.
+    for (size_t j = 0; j < transformOperations.size(); ++j) {
+        switch (transformOperations.operations()[j]->type()) {
+        case TransformOperation::ScaleX:
+        case TransformOperation::ScaleY:
+        case TransformOperation::ScaleZ:
+        case TransformOperation::Scale3D:
+        case TransformOperation::Scale: {
+            ScaleTransformOperation* transform = static_cast<ScaleTransformOperation*>(transformOperations.operations()[j].get());
+            webTransformOperations->appendScale(transform->x(), transform->y(), transform->z());
+            break;
+        }
+        case TransformOperation::TranslateX:
+        case TransformOperation::TranslateY:
+        case TransformOperation::TranslateZ:
+        case TransformOperation::Translate3D:
+        case TransformOperation::Translate: {
+            TranslateTransformOperation* transform = static_cast<TranslateTransformOperation*>(transformOperations.operations()[j].get());
+            ASSERT(transform->x().isFixed() && transform->y().isFixed());
+            webTransformOperations->appendTranslate(transform->x().value(), transform->y().value(), transform->z());
+            break;
+        }
+        case TransformOperation::RotateX:
+        case TransformOperation::RotateY:
+        case TransformOperation::Rotate3D:
+        case TransformOperation::Rotate: {
+            RotateTransformOperation* transform = static_cast<RotateTransformOperation*>(transformOperations.operations()[j].get());
+            webTransformOperations->appendRotate(transform->x(), transform->y(), transform->z(), transform->angle());
+            break;
+        }
+        case TransformOperation::SkewX:
+        case TransformOperation::SkewY:
+        case TransformOperation::Skew: {
+            SkewTransformOperation* transform = static_cast<SkewTransformOperation*>(transformOperations.operations()[j].get());
+            webTransformOperations->appendSkew(transform->angleX(), transform->angleY());
+            break;
+        }
+        case TransformOperation::Matrix: {
+            MatrixTransformOperation* transform = static_cast<MatrixTransformOperation*>(transformOperations.operations()[j].get());
+            TransformationMatrix m = transform->matrix();
+            webTransformOperations->appendMatrix(TransformationMatrix::toSkMatrix44(m));
+            break;
+        }
+        case TransformOperation::Matrix3D: {
+            Matrix3DTransformOperation* transform = static_cast<Matrix3DTransformOperation*>(transformOperations.operations()[j].get());
+            TransformationMatrix m = transform->matrix();
+            webTransformOperations->appendMatrix(TransformationMatrix::toSkMatrix44(m));
+            break;
+        }
+        case TransformOperation::Perspective: {
+            PerspectiveTransformOperation* transform = static_cast<PerspectiveTransformOperation*>(transformOperations.operations()[j].get());
+            webTransformOperations->appendPerspective(transform->perspective());
+            break;
+        }
+        case TransformOperation::Interpolated: {
+            TransformationMatrix m;
+            transformOperations.operations()[j]->apply(m, FloatSize());
+            webTransformOperations->appendMatrix(TransformationMatrix::toSkMatrix44(m));
+            break;
+        }
+        case TransformOperation::Identity:
+            webTransformOperations->appendIdentity();
+            break;
+        case TransformOperation::None:
+            // Do nothing.
+            break;
+        } // switch
+    } // for each operation
+}
+
+bool toWebFilterOperations(const FilterOperations& inOperations, WebFilterOperations* outOperations)
+{
+    SkiaImageFilterBuilder builder;
+    FilterOutsets outsets = inOperations.outsets();
+    builder.setCropOffset(FloatSize(outsets.left(), outsets.top()));
+    return builder.buildFilterOperations(inOperations, outOperations);
+}
+
+} // namespace WebCore
diff --git a/Source/core/frame/GraphicsLayerDebugInfo.h b/Source/core/animation/AnimationTranslationUtil.h
similarity index 74%
copy from Source/core/frame/GraphicsLayerDebugInfo.h
copy to Source/core/animation/AnimationTranslationUtil.h
index 26d2fce..c69635b 100644
--- a/Source/core/frame/GraphicsLayerDebugInfo.h
+++ b/Source/core/animation/AnimationTranslationUtil.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,23 +28,22 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef GraphicsLayerDebugInfo_h
-#define GraphicsLayerDebugInfo_h
+#ifndef AnimationTranslationUtil_h
+#define AnimationTranslationUtil_h
 
-#include "platform/geometry/LayoutRect.h"
-#include "public/platform/WebGraphicsLayerDebugInfo.h"
-
-#include "wtf/Vector.h"
+namespace blink {
+class WebTransformOperations;
+class WebFilterOperations;
+}
 
 namespace WebCore {
 
-class GraphicsLayerDebugInfo FINAL : public blink::WebGraphicsLayerDebugInfo {
-public:
-    virtual void appendAsTraceFormat(blink::WebString* out) const OVERRIDE;
-    virtual ~GraphicsLayerDebugInfo() { };
-    Vector<LayoutRect> m_currentLayoutRects;
-};
+class FilterOperations;
+class TransformOperations;
+
+void toWebTransformOperations(const TransformOperations& inOperations, blink::WebTransformOperations* outOperations);
+bool toWebFilterOperations(const FilterOperations& inOperations, blink::WebFilterOperations* outOperations);
 
 } // namespace WebCore
 
-#endif
+#endif // AnimationTranslationUtil_h
diff --git a/Source/core/animation/AnimationTranslationUtilTest.cpp b/Source/core/animation/AnimationTranslationUtilTest.cpp
new file mode 100644
index 0000000..d55e790
--- /dev/null
+++ b/Source/core/animation/AnimationTranslationUtilTest.cpp
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2012 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
+ */
+
+#include "config.h"
+
+#include "core/animation/AnimationTranslationUtil.h"
+
+#include "core/animation/css/CSSAnimationData.h"
+#include "platform/animation/KeyframeValueList.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/graphics/filters/FilterOperations.h"
+#include "platform/transforms/Matrix3DTransformOperation.h"
+#include "platform/transforms/RotateTransformOperation.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/TransformOperations.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+#include "public/platform/WebAnimation.h"
+#include "public/platform/WebFilterOperations.h"
+#include "public/platform/WebTransformOperations.h"
+#include "wtf/RefPtr.h"
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+using namespace blink;
+
+namespace {
+
+class WebTransformOperationsMock : public blink::WebTransformOperations {
+public:
+    MOCK_CONST_METHOD1(canBlendWith, bool(const WebTransformOperations&));
+    MOCK_METHOD3(appendTranslate, void(double, double, double));
+    MOCK_METHOD4(appendRotate, void(double, double, double, double));
+    MOCK_METHOD3(appendScale, void(double, double, double));
+    MOCK_METHOD2(appendSkew, void(double, double));
+    MOCK_METHOD1(appendPerspective, void(double));
+    MOCK_METHOD1(appendMatrix, void(const SkMatrix44&));
+    MOCK_METHOD0(appendIdentity, void());
+    MOCK_CONST_METHOD0(isIdentity, bool());
+};
+
+class WebFilterOperationsMock : public blink::WebFilterOperations {
+public:
+    MOCK_METHOD1(appendGrayscaleFilter, void(float));
+    MOCK_METHOD1(appendSepiaFilter, void(float));
+    MOCK_METHOD1(appendSaturateFilter, void(float));
+    MOCK_METHOD1(appendHueRotateFilter, void(float));
+    MOCK_METHOD1(appendInvertFilter, void(float));
+    MOCK_METHOD1(appendBrightnessFilter, void(float));
+    MOCK_METHOD1(appendContrastFilter, void(float));
+    MOCK_METHOD1(appendOpacityFilter, void(float));
+    MOCK_METHOD1(appendBlurFilter, void(float));
+    MOCK_METHOD3(appendDropShadowFilter, void(WebPoint, float, WebColor));
+    MOCK_METHOD1(appendColorMatrixFilter, void(SkScalar[20]));
+    MOCK_METHOD2(appendZoomFilter, void(float, int));
+    MOCK_METHOD1(appendSaturatingBrightnessFilter, void(float));
+    MOCK_METHOD1(appendReferenceFilter, void(SkImageFilter*));
+    MOCK_METHOD0(clear, void());
+};
+
+TEST(AnimationTranslationUtilTest, transformsWork)
+{
+    TransformOperations ops;
+    WebTransformOperationsMock outOps;
+
+    EXPECT_CALL(outOps, appendTranslate(2, 0, 0));
+    EXPECT_CALL(outOps, appendRotate(0.1, 0.2, 0.3, 200000.4));
+    EXPECT_CALL(outOps, appendScale(50.2, 100, -4));
+
+    ops.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+    ops.operations().append(RotateTransformOperation::create(0.1, 0.2, 0.3, 200000.4, TransformOperation::Rotate3D));
+    ops.operations().append(ScaleTransformOperation::create(50.2, 100, -4, TransformOperation::Scale3D));
+    toWebTransformOperations(ops, &outOps);
+}
+
+TEST(AnimationTranslationUtilTest, filtersWork)
+{
+    FilterOperations ops;
+    WebFilterOperationsMock outOps;
+
+    EXPECT_CALL(outOps, appendSaturateFilter(0.5));
+    EXPECT_CALL(outOps, appendGrayscaleFilter(0.2f));
+    EXPECT_CALL(outOps, appendSepiaFilter(0.8f));
+    EXPECT_CALL(outOps, appendOpacityFilter(0.1f));
+
+    ops.operations().append(BasicColorMatrixFilterOperation::create(0.5, FilterOperation::SATURATE));
+    ops.operations().append(BasicColorMatrixFilterOperation::create(0.2, FilterOperation::GRAYSCALE));
+    ops.operations().append(BasicColorMatrixFilterOperation::create(0.8, FilterOperation::SEPIA));
+    ops.operations().append(BasicColorMatrixFilterOperation::create(0.1, FilterOperation::OPACITY));
+    toWebFilterOperations(ops, &outOps);
+}
+
+}
+
diff --git a/Source/core/animation/CompositorAnimations.cpp b/Source/core/animation/CompositorAnimations.cpp
index 929f073..d578a6a 100644
--- a/Source/core/animation/CompositorAnimations.cpp
+++ b/Source/core/animation/CompositorAnimations.cpp
@@ -35,8 +35,8 @@
 #include "core/animation/AnimatableFilterOperations.h"
 #include "core/animation/AnimatableTransform.h"
 #include "core/animation/AnimatableValue.h"
+#include "core/animation/AnimationTranslationUtil.h"
 #include "core/animation/CompositorAnimationsImpl.h"
-#include "core/platform/animation/AnimationTranslationUtil.h"
 #include "core/rendering/CompositedLayerMapping.h"
 #include "core/rendering/RenderBoxModelObject.h"
 #include "core/rendering/RenderLayer.h"
@@ -58,7 +58,7 @@
 
 namespace {
 
-void getKeyframeValuesForProperty(const KeyframeAnimationEffect* effect, CSSPropertyID id, double scale, bool reverse, KeyframeVector& values)
+void getKeyframeValuesForProperty(const KeyframeEffectModel* effect, CSSPropertyID id, double scale, bool reverse, KeyframeVector& values)
 {
     ASSERT(values.isEmpty());
     const KeyframeVector& group = effect->getPropertySpecificKeyframes(id);
@@ -147,10 +147,10 @@
 
 bool CompositorAnimations::isCandidateForAnimationOnCompositor(const Timing& timing, const AnimationEffect& effect)
 {
-    const KeyframeAnimationEffect& keyframeEffect = *toKeyframeAnimationEffect(&effect);
+    const KeyframeEffectModel& keyframeEffect = *toKeyframeEffectModel(&effect);
 
     // Are the keyframes convertible?
-    const KeyframeAnimationEffect::KeyframeVector frames = keyframeEffect.getFrames();
+    const KeyframeEffectModel::KeyframeVector frames = keyframeEffect.getFrames();
     for (size_t i = 0; i < frames.size(); ++i) {
         // Only replace mode can be accelerated
         if (frames[i]->composite() != AnimationEffect::CompositeReplace)
@@ -258,7 +258,7 @@
     ASSERT(isCandidateForAnimationOnCompositor(timing, effect));
     ASSERT(canStartAnimationOnCompositor(element));
 
-    const KeyframeAnimationEffect& keyframeEffect = *toKeyframeAnimationEffect(&effect);
+    const KeyframeEffectModel& keyframeEffect = *toKeyframeEffectModel(&effect);
 
     RenderLayer* layer = toRenderBoxModelObject(element.renderer())->layer();
     ASSERT(layer);
@@ -292,6 +292,10 @@
 
 void CompositorAnimations::pauseAnimationForTestingOnCompositor(const Element& element, int id, double pauseTime)
 {
+    // FIXME: canStartAnimationOnCompositor queries compositingState, which is not necessarily up to date.
+    // https://code.google.com/p/chromium/issues/detail?id=339847
+    DisableCompositingQueryAsserts disabler;
+
     if (!canStartAnimationOnCompositor(element)) {
         ASSERT_NOT_REACHED();
         return;
@@ -318,7 +322,7 @@
     if ((std::floor(timing.iterationCount) != timing.iterationCount) || timing.iterationCount <= 0)
         return false;
 
-    if (!timing.iterationDuration)
+    if (std::isnan(timing.iterationDuration) || !timing.iterationDuration)
         return false;
 
     // FIXME: Support other playback rates
@@ -459,7 +463,7 @@
         }
         case blink::WebAnimationCurve::AnimationCurveTypeTransform: {
             OwnPtr<blink::WebTransformOperations> ops = adoptPtr(blink::Platform::current()->compositorSupport()->createTransformOperations());
-            toWebTransformOperations(toAnimatableTransform(value.get())->transformOperations(), FloatSize(), ops.get());
+            toWebTransformOperations(toAnimatableTransform(value.get())->transformOperations(), ops.get());
 
             blink::WebTransformKeyframe transformKeyframe(keyframes[i]->offset(), ops.release());
             blink::WebTransformAnimationCurve* transformCurve = static_cast<blink::WebTransformAnimationCurve*>(&curve);
@@ -472,8 +476,7 @@
     }
 }
 
-void CompositorAnimationsImpl::getAnimationOnCompositor(
-    const Timing& timing, const KeyframeAnimationEffect& effect, Vector<OwnPtr<blink::WebAnimation> >& animations)
+void CompositorAnimationsImpl::getAnimationOnCompositor(const Timing& timing, const KeyframeEffectModel& effect, Vector<OwnPtr<blink::WebAnimation> >& animations)
 {
     ASSERT(animations.isEmpty());
     CompositorTiming compositorTiming;
diff --git a/Source/core/animation/CompositorAnimations.h b/Source/core/animation/CompositorAnimations.h
index 9a52973..76c6b17 100644
--- a/Source/core/animation/CompositorAnimations.h
+++ b/Source/core/animation/CompositorAnimations.h
@@ -33,7 +33,7 @@
 
 #include "core/animation/AnimationEffect.h"
 #include "core/animation/Timing.h"
-#include "core/platform/animation/TimingFunction.h"
+#include "platform/animation/TimingFunction.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
diff --git a/Source/core/animation/CompositorAnimationsImpl.h b/Source/core/animation/CompositorAnimationsImpl.h
index 7c32705..9bf8889 100644
--- a/Source/core/animation/CompositorAnimationsImpl.h
+++ b/Source/core/animation/CompositorAnimationsImpl.h
@@ -29,14 +29,14 @@
  */
 
 #include "core/animation/AnimationEffect.h"
-#include "core/animation/KeyframeAnimationEffect.h"
+#include "core/animation/KeyframeEffectModel.h"
 #include "core/animation/Timing.h"
-#include "core/platform/animation/TimingFunction.h"
+#include "platform/animation/TimingFunction.h"
 #include "public/platform/WebAnimation.h"
 
 namespace WebCore {
 
-typedef KeyframeAnimationEffect::PropertySpecificKeyframeVector KeyframeVector;
+typedef KeyframeEffectModel::PropertySpecificKeyframeVector KeyframeVector;
 
 class CompositorAnimationsImpl {
 private:
@@ -50,7 +50,7 @@
 
     static bool convertTimingForCompositor(const Timing&, CompositorTiming& out);
 
-    static void getAnimationOnCompositor(const Timing&, const KeyframeAnimationEffect&, Vector<OwnPtr<blink::WebAnimation> >& animations);
+    static void getAnimationOnCompositor(const Timing&, const KeyframeEffectModel&, Vector<OwnPtr<blink::WebAnimation> >& animations);
 
     static void addKeyframesToCurve(blink::WebAnimationCurve&, const KeyframeVector&, const TimingFunction&);
 
diff --git a/Source/core/animation/CompositorAnimationsTest.cpp b/Source/core/animation/CompositorAnimationsTest.cpp
index 0cbc371..e06fdf9 100644
--- a/Source/core/animation/CompositorAnimationsTest.cpp
+++ b/Source/core/animation/CompositorAnimationsTest.cpp
@@ -38,7 +38,7 @@
 #include "core/animation/AnimatableValueTestHelper.h"
 #include "core/animation/CompositorAnimationsImpl.h"
 #include "core/animation/CompositorAnimationsTestHelper.h"
-#include "core/platform/animation/TimingFunctionTestHelper.h"
+#include "platform/animation/TimingFunctionTestHelper.h"
 #include "platform/geometry/IntSize.h"
 #include "platform/graphics/filters/FilterOperations.h"
 #include "platform/transforms/TransformOperations.h"
@@ -71,10 +71,10 @@
 
     Timing m_timing;
     CompositorAnimationsImpl::CompositorTiming m_compositorTiming;
-    KeyframeAnimationEffect::KeyframeVector m_keyframeVector2;
-    RefPtr<KeyframeAnimationEffect> m_keyframeAnimationEffect2;
-    KeyframeAnimationEffect::KeyframeVector m_keyframeVector5;
-    RefPtr<KeyframeAnimationEffect> m_keyframeAnimationEffect5;
+    KeyframeEffectModel::KeyframeVector m_keyframeVector2;
+    RefPtr<KeyframeEffectModel> m_keyframeAnimationEffect2;
+    KeyframeEffectModel::KeyframeVector m_keyframeVector5;
+    RefPtr<KeyframeEffectModel> m_keyframeAnimationEffect5;
 
     virtual void SetUp()
     {
@@ -92,10 +92,10 @@
         ASSERT(convertTimingForCompositor(m_timing, m_compositorTiming));
 
         m_keyframeVector2 = createCompositableFloatKeyframeVector(2);
-        m_keyframeAnimationEffect2 = KeyframeAnimationEffect::create(m_keyframeVector2);
+        m_keyframeAnimationEffect2 = KeyframeEffectModel::create(m_keyframeVector2);
 
         m_keyframeVector5 = createCompositableFloatKeyframeVector(5);
-        m_keyframeAnimationEffect5 = KeyframeAnimationEffect::create(m_keyframeVector5);
+        m_keyframeAnimationEffect5 = KeyframeEffectModel::create(m_keyframeVector5);
     }
 
 public:
@@ -108,7 +108,7 @@
     {
         return CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(timing, effect);
     }
-    void getAnimationOnCompositor(Timing& timing, KeyframeAnimationEffect& effect, Vector<OwnPtr<blink::WebAnimation> >& animations)
+    void getAnimationOnCompositor(Timing& timing, KeyframeEffectModel& effect, Vector<OwnPtr<blink::WebAnimation> >& animations)
     {
         return CompositorAnimationsImpl::getAnimationOnCompositor(timing, effect, animations);
     }
@@ -116,11 +116,11 @@
     bool isCandidateHelperForSingleKeyframe(Keyframe* frame)
     {
         EXPECT_EQ(frame->offset(), 0);
-        KeyframeAnimationEffect::KeyframeVector frames;
+        KeyframeEffectModel::KeyframeVector frames;
         frames.append(frame);
         EXPECT_EQ(m_keyframeVector2[1]->offset(), 1.0);
         frames.append(m_keyframeVector2[1]);
-        return isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(frames).get());
+        return isCandidateForAnimationOnCompositor(m_timing, *KeyframeEffectModel::create(frames).get());
     }
 
     // -------------------------------------------------------------------
@@ -132,7 +132,6 @@
         timing.fillMode = Timing::FillModeNone;
         timing.iterationStart = 0;
         timing.iterationCount = 1;
-        timing.hasIterationDuration = true;
         timing.iterationDuration = 1.0;
         timing.playbackRate = 1.0;
         timing.direction = Timing::PlaybackDirectionNormal;
@@ -163,7 +162,7 @@
         return keyframe;
     }
 
-    KeyframeAnimationEffect::KeyframeVector createCompositableFloatKeyframeVector(size_t n)
+    KeyframeEffectModel::KeyframeVector createCompositableFloatKeyframeVector(size_t n)
     {
         Vector<double> values;
         for (size_t i = 0; i < n; i++) {
@@ -172,9 +171,9 @@
         return createCompositableFloatKeyframeVector(values);
     }
 
-    KeyframeAnimationEffect::KeyframeVector createCompositableFloatKeyframeVector(Vector<double>& values)
+    KeyframeEffectModel::KeyframeVector createCompositableFloatKeyframeVector(Vector<double>& values)
     {
-        KeyframeAnimationEffect::KeyframeVector frames;
+        KeyframeEffectModel::KeyframeVector frames;
         for (size_t i = 0; i < values.size(); i++) {
             double offset = 1.0 / (values.size() - 1) * i;
             RefPtr<AnimatableDouble> value = AnimatableDouble::create(values[i]);
@@ -183,7 +182,7 @@
         return frames;
     }
 
-    PassRefPtr<KeyframeAnimationEffect> createKeyframeAnimationEffect(PassRefPtr<Keyframe> prpFrom, PassRefPtr<Keyframe> prpTo, PassRefPtr<Keyframe> prpC = 0, PassRefPtr<Keyframe> prpD = 0)
+    PassRefPtr<KeyframeEffectModel> createKeyframeEffectModel(PassRefPtr<Keyframe> prpFrom, PassRefPtr<Keyframe> prpTo, PassRefPtr<Keyframe> prpC = 0, PassRefPtr<Keyframe> prpD = 0)
     {
         RefPtr<Keyframe> from = prpFrom;
         RefPtr<Keyframe> to = prpTo;
@@ -191,7 +190,7 @@
         RefPtr<Keyframe> d = prpD;
 
         EXPECT_EQ(from->offset(), 0);
-        KeyframeAnimationEffect::KeyframeVector frames;
+        KeyframeEffectModel::KeyframeVector frames;
         frames.append(from);
         EXPECT_LE(from->offset(), to->offset());
         frames.append(to);
@@ -207,33 +206,13 @@
             EXPECT_EQ(to->offset(), 1.0);
         }
         if (!HasFatalFailure()) {
-            return KeyframeAnimationEffect::create(frames);
+            return KeyframeEffectModel::create(frames);
         }
-        return PassRefPtr<KeyframeAnimationEffect>();
+        return PassRefPtr<KeyframeEffectModel>();
     }
 
 };
 
-class CustomFilterOperationMock : public FilterOperation {
-public:
-    virtual bool operator==(const FilterOperation&) const OVERRIDE FINAL {
-        ASSERT_NOT_REACHED();
-        return false;
-    }
-
-    MOCK_CONST_METHOD2(blend, PassRefPtr<FilterOperation>(const FilterOperation*, double));
-
-    static PassRefPtr<CustomFilterOperationMock> create()
-    {
-        return adoptRef(new CustomFilterOperationMock());
-    }
-
-    CustomFilterOperationMock()
-        : FilterOperation(FilterOperation::CUSTOM)
-    {
-    }
-};
-
 // -----------------------------------------------------------------------
 // -----------------------------------------------------------------------
 
@@ -247,19 +226,9 @@
     keyframeBadMultipleOp->setPropertyValue(CSSPropertyWebkitTransform, AnimatableDouble::create(10.0).get());
     EXPECT_FALSE(isCandidateHelperForSingleKeyframe(keyframeBadMultipleOp.get()));
 
-    // Check both an unsupported property which hashes before and after the
-    // supported property.
-    typedef DefaultHash<CSSPropertyID>::Hash HashFunctions;
-
-    RefPtr<Keyframe> keyframeBadMultiple1ID = createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace);
-    keyframeBadMultiple1ID->setPropertyValue(CSSPropertyOpacity, AnimatableDouble::create(10.0).get());
-    EXPECT_FALSE(isCandidateHelperForSingleKeyframe(keyframeBadMultiple1ID.get()));
-    EXPECT_LT(HashFunctions::hash(CSSPropertyColor), HashFunctions::hash(CSSPropertyOpacity));
-
-    RefPtr<Keyframe> keyframeBadMultiple2ID = createDefaultKeyframe(CSSPropertyWebkitTransform, AnimationEffect::CompositeReplace);
-    keyframeBadMultiple2ID->setPropertyValue(CSSPropertyWidth, AnimatableDouble::create(10.0).get());
-    EXPECT_FALSE(isCandidateHelperForSingleKeyframe(keyframeBadMultiple2ID.get()));
-    EXPECT_GT(HashFunctions::hash(CSSPropertyWebkitTransform), HashFunctions::hash(CSSPropertyWidth));
+    RefPtr<Keyframe> keyframeBadMultipleID = createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace);
+    keyframeBadMultipleID->setPropertyValue(CSSPropertyOpacity, AnimatableDouble::create(10.0).get());
+    EXPECT_FALSE(isCandidateHelperForSingleKeyframe(keyframeBadMultipleID.get()));
 }
 
 TEST_F(AnimationCompositorAnimationsTest, isNotCandidateForCompositorAnimationTransformDependsOnBoxSize)
@@ -272,49 +241,43 @@
     ops.operations().append(TranslateTransformOperation::create(Length(50, WebCore::Percent), Length(2, WebCore::Fixed), TransformOperation::TranslateX));
     RefPtr<Keyframe> badKeyframe = createReplaceOpKeyframe(CSSPropertyWebkitTransform, AnimatableTransform::create(ops).get());
     EXPECT_FALSE(isCandidateHelperForSingleKeyframe(badKeyframe.get()));
+
+    TransformOperations ops2;
+    Length calcLength = Length(100, WebCore::Percent).blend(Length(100, WebCore::Fixed), 0.5, WebCore::ValueRangeAll);
+    ops2.operations().append(TranslateTransformOperation::create(calcLength, Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+    RefPtr<Keyframe> badKeyframe2 = createReplaceOpKeyframe(CSSPropertyWebkitTransform, AnimatableTransform::create(ops2).get());
+    EXPECT_FALSE(isCandidateHelperForSingleKeyframe(badKeyframe2.get()));
 }
 
-TEST_F(AnimationCompositorAnimationsTest, isNotCandidateForCompositorAnimationCustomFilter)
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorKeyframeEffectModelMultipleFramesOkay)
 {
-    FilterOperations ops;
-    ops.operations().append(BasicColorMatrixFilterOperation::create(0.5, FilterOperation::SATURATE));
-    RefPtr<Keyframe> goodKeyframe = createReplaceOpKeyframe(CSSPropertyWebkitFilter, AnimatableFilterOperations::create(ops).get());
-    EXPECT_TRUE(isCandidateHelperForSingleKeyframe(goodKeyframe.get()));
-
-    ops.operations().append(CustomFilterOperationMock::create());
-    RefPtr<Keyframe> badKeyframe = createReplaceOpKeyframe(CSSPropertyFilter, AnimatableFilterOperations::create(ops).get());
-    EXPECT_FALSE(isCandidateHelperForSingleKeyframe(badKeyframe.get()));
-}
-
-TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorKeyframeEffectMultipleFramesOkay)
-{
-    KeyframeAnimationEffect::KeyframeVector framesSame;
+    KeyframeEffectModel::KeyframeVector framesSame;
     framesSame.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
     framesSame.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 1.0).get());
-    EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesSame).get()));
+    EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeEffectModel::create(framesSame).get()));
 
-    KeyframeAnimationEffect::KeyframeVector framesMixed;
+    KeyframeEffectModel::KeyframeVector framesMixed;
     framesMixed.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
     framesMixed.append(createDefaultKeyframe(CSSPropertyWebkitTransform, AnimationEffect::CompositeReplace, 1.0).get());
-    EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesMixed).get()));
+    EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeEffectModel::create(framesMixed).get()));
 }
 
-TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorKeyframeEffectMultipleFramesNotOkay)
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorKeyframeEffectModel)
 {
-    KeyframeAnimationEffect::KeyframeVector framesSame;
+    KeyframeEffectModel::KeyframeVector framesSame;
     framesSame.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace, 0.0).get());
     framesSame.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace, 1.0).get());
-    EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesSame).get()));
+    EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeEffectModel::create(framesSame).get()));
 
-    KeyframeAnimationEffect::KeyframeVector framesMixedProperties;
+    KeyframeEffectModel::KeyframeVector framesMixedProperties;
     framesMixedProperties.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
     framesMixedProperties.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace, 1.0).get());
-    EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesMixedProperties).get()));
+    EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeEffectModel::create(framesMixedProperties).get()));
 
-    KeyframeAnimationEffect::KeyframeVector framesMixedOps;
+    KeyframeEffectModel::KeyframeVector framesMixedOps;
     framesMixedOps.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
     framesMixedOps.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeAdd, 1.0).get());
-    EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesMixedOps).get()));
+    EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeEffectModel::create(framesMixedOps).get()));
 }
 
 TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorStartDelay)
@@ -690,21 +653,21 @@
     Timing chainedTiming(createCompositableTiming());
     chainedTiming.timingFunction = chainedTimingFunc;
 
-    KeyframeAnimationEffect::KeyframeVector basicFramesVector;
+    KeyframeEffectModel::KeyframeVector basicFramesVector;
     basicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
     basicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 1.0).get());
-    RefPtr<KeyframeAnimationEffect> basicFrames = KeyframeAnimationEffect::create(basicFramesVector).get();
+    RefPtr<KeyframeEffectModel> basicFrames = KeyframeEffectModel::create(basicFramesVector).get();
 
     EXPECT_TRUE(isCandidateForAnimationOnCompositor(linearTiming, *basicFrames.get()));
     EXPECT_TRUE(isCandidateForAnimationOnCompositor(cubicTiming, *basicFrames.get()));
     // number of timing function and keyframes don't match
     EXPECT_FALSE(isCandidateForAnimationOnCompositor(chainedTiming, *basicFrames.get()));
 
-    KeyframeAnimationEffect::KeyframeVector nonBasicFramesVector;
+    KeyframeEffectModel::KeyframeVector nonBasicFramesVector;
     nonBasicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
     nonBasicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.5).get());
     nonBasicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 1.0).get());
-    RefPtr<KeyframeAnimationEffect> nonBasicFrames = KeyframeAnimationEffect::create(nonBasicFramesVector).get();
+    RefPtr<KeyframeEffectModel> nonBasicFrames = KeyframeEffectModel::create(nonBasicFramesVector).get();
 
     EXPECT_TRUE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(linearTiming, *nonBasicFrames.get()));
     EXPECT_FALSE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(cubicTiming, *nonBasicFrames.get()));
@@ -717,7 +680,7 @@
 TEST_F(AnimationCompositorAnimationsTest, createSimpleOpacityAnimation)
 {
     // Animation to convert
-    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
     // --
@@ -762,7 +725,7 @@
 TEST_F(AnimationCompositorAnimationsTest, createSimpleOpacityAnimationDuration)
 {
     // Animation to convert
-    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
 
@@ -809,7 +772,7 @@
 TEST_F(AnimationCompositorAnimationsTest, createMultipleKeyframeOpacityAnimationLinear)
 {
     // Animation to convert
-    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(-1.0).get(), 0.25),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(20.0).get(), 0.5),
@@ -862,7 +825,7 @@
 TEST_F(AnimationCompositorAnimationsTest, createSimpleOpacityAnimationStartDelay)
 {
     // Animation to convert
-    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
 
@@ -911,7 +874,7 @@
 TEST_F(AnimationCompositorAnimationsTest, createMultipleKeyframeOpacityAnimationChained)
 {
     // Animation to convert
-    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(-1.0).get(), 0.25),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(20.0).get(), 0.5),
@@ -971,7 +934,7 @@
 TEST_F(AnimationCompositorAnimationsTest, createReversedOpacityAnimation)
 {
     // Animation to convert
-    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(-1.0).get(), 0.25),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(20.0).get(), 0.5),
@@ -1031,7 +994,7 @@
 TEST_F(AnimationCompositorAnimationsTest, createReversedOpacityAnimationNegativeStartDelay)
 {
     // Animation to convert
-    RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+    RefPtr<KeyframeEffectModel> effect = createKeyframeEffectModel(
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
         createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
 
diff --git a/Source/core/animation/CompositorAnimationsTestHelper.h b/Source/core/animation/CompositorAnimationsTestHelper.h
index 732d346..bb2761f 100644
--- a/Source/core/animation/CompositorAnimationsTestHelper.h
+++ b/Source/core/animation/CompositorAnimationsTestHelper.h
@@ -131,7 +131,7 @@
         virtual void cryptographicallyRandomValues(unsigned char* buffer, size_t length) { ASSERT_NOT_REACHED(); }
     private:
         WebCompositorSupportMock** m_compositor;
-        blink::WebCompositorSupport* compositorSupport() OVERRIDE { return *m_compositor; }
+        virtual blink::WebCompositorSupport* compositorSupport() OVERRIDE { return *m_compositor; }
     };
 
     WebCompositorSupportMock* m_mockCompositor;
diff --git a/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp b/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp
index 550b7f5..102f4ef 100644
--- a/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp
+++ b/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp
@@ -32,7 +32,7 @@
 
 #include "core/animation/CompositorAnimations.h"
 
-#include "core/platform/animation/TimingFunctionTestHelper.h"
+#include "platform/animation/TimingFunctionTestHelper.h"
 
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
diff --git a/Source/core/animation/DocumentAnimation.h b/Source/core/animation/DocumentAnimation.h
new file mode 100644
index 0000000..4591091
--- /dev/null
+++ b/Source/core/animation/DocumentAnimation.h
@@ -0,0 +1,19 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef DocumentAnimation_h
+#define DocumentAnimation_h
+
+#include "core/dom/Document.h"
+
+namespace WebCore {
+
+class DocumentAnimation {
+public:
+    static DocumentTimeline* timeline(Document* document) { return document->timeline(); }
+};
+
+} // namespace WebCore
+
+#endif // DocumentAnimation_h
diff --git a/Source/core/animation/DocumentAnimation.idl b/Source/core/animation/DocumentAnimation.idl
new file mode 100644
index 0000000..2bfb6a7
--- /dev/null
+++ b/Source/core/animation/DocumentAnimation.idl
@@ -0,0 +1,9 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+    RuntimeEnabled=WebAnimationsAPI,
+] partial interface Document {
+    readonly attribute Timeline timeline;
+};
diff --git a/Source/core/animation/DocumentAnimations.cpp b/Source/core/animation/DocumentAnimations.cpp
index 34ea5ca..57770ca 100644
--- a/Source/core/animation/DocumentAnimations.cpp
+++ b/Source/core/animation/DocumentAnimations.cpp
@@ -46,9 +46,8 @@
 
 namespace {
 
-void updateAnimationTiming(Document& document, double monotonicAnimationStartTime)
+void updateAnimationTiming(Document& document)
 {
-    document.animationClock().updateTime(monotonicAnimationStartTime);
     bool didTriggerStyleRecalc = document.timeline()->serviceAnimations();
     didTriggerStyleRecalc |= document.transitionTimeline()->serviceAnimations();
     if (!didTriggerStyleRecalc)
@@ -71,33 +70,28 @@
 
 void DocumentAnimations::serviceOnAnimationFrame(Document& document, double monotonicAnimationStartTime)
 {
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-        return;
-
-    updateAnimationTiming(document, monotonicAnimationStartTime);
+    document.animationClock().updateTime(monotonicAnimationStartTime);
+    updateAnimationTiming(document);
     dispatchAnimationEvents(document);
 }
 
 void DocumentAnimations::serviceBeforeGetComputedStyle(Node& node, CSSPropertyID property)
 {
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+    if (!node.isElementNode())
         return;
-
-    if (node.isElementNode()) {
-        const Element& element = toElement(node);
-        if (const ActiveAnimations* activeAnimations = element.activeAnimations()) {
-            if (activeAnimations->hasActiveAnimationsOnCompositor(property))
-                updateAnimationTiming(element.document(), monotonicallyIncreasingTime());
-        }
+    const Element& element = toElement(node);
+    if (element.document().timeline()->hasPlayerNeedingUpdate()) {
+        updateAnimationTiming(element.document());
+        return;
     }
-
+    if (const ActiveAnimations* activeAnimations = element.activeAnimations()) {
+        if (activeAnimations->hasActiveAnimationsOnCompositor(property))
+            updateAnimationTiming(element.document());
+    }
 }
 
 void DocumentAnimations::serviceAfterStyleRecalc(Document& document)
 {
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-        return;
-
     if (document.cssPendingAnimations().startPendingAnimations() && document.view())
         document.view()->scheduleAnimation();
 
diff --git a/Source/core/animation/DocumentTimeline.cpp b/Source/core/animation/DocumentTimeline.cpp
index 21027f8..ba4b1e3 100644
--- a/Source/core/animation/DocumentTimeline.cpp
+++ b/Source/core/animation/DocumentTimeline.cpp
@@ -61,13 +61,19 @@
     ASSERT(document);
 }
 
+DocumentTimeline::~DocumentTimeline()
+{
+    for (HashSet<Player*>::iterator it = m_players.begin(); it != m_players.end(); ++it)
+        (*it)->timelineDestroyed();
+}
+
 Player* DocumentTimeline::createPlayer(TimedItem* child)
 {
     RefPtr<Player> player = Player::create(*this, child);
     Player* result = player.get();
-    m_players.append(player.release());
-    if (m_document->view())
-        m_timing->serviceOnNextFrame();
+    m_players.add(result);
+    m_currentPlayers.append(player.release());
+    setHasPlayerNeedingUpdate();
     return result;
 }
 
@@ -91,23 +97,23 @@
 
     double timeToNextEffect = std::numeric_limits<double>::infinity();
     bool didTriggerStyleRecalc = false;
-    for (int i = m_players.size() - 1; i >= 0; --i) {
-        double playerNextEffect;
+    for (int i = m_currentPlayers.size() - 1; i >= 0; --i) {
+        RefPtr<Player> player = m_currentPlayers[i].get();
         bool playerDidTriggerStyleRecalc;
-        if (!m_players[i]->update(&playerNextEffect, &playerDidTriggerStyleRecalc))
-            m_players.remove(i);
+        if (!player->update(&playerDidTriggerStyleRecalc))
+            m_currentPlayers.remove(i);
+        timeToNextEffect = std::min(timeToNextEffect, player->timeToEffectChange());
         didTriggerStyleRecalc |= playerDidTriggerStyleRecalc;
-        if (playerNextEffect < timeToNextEffect)
-            timeToNextEffect = playerNextEffect;
     }
 
-    if (!m_players.isEmpty()) {
+    if (!m_currentPlayers.isEmpty()) {
         if (timeToNextEffect < s_minimumDelay)
             m_timing->serviceOnNextFrame();
         else if (timeToNextEffect != std::numeric_limits<double>::infinity())
             m_timing->wakeAfter(timeToNextEffect - s_minimumDelay);
     }
 
+    m_hasPlayerNeedingUpdate = false;
     return didTriggerStyleRecalc;
 }
 
@@ -116,6 +122,7 @@
     ASSERT(isNull(m_zeroTime));
     m_zeroTime = zeroTime;
     ASSERT(!isNull(m_zeroTime));
+    serviceAnimations();
 }
 
 void DocumentTimeline::DocumentTimelineTiming::wakeAfter(double duration)
@@ -130,21 +137,29 @@
 
 void DocumentTimeline::DocumentTimelineTiming::serviceOnNextFrame()
 {
-    if (m_timeline->m_document->view())
+    if (m_timeline->m_document && m_timeline->m_document->view())
         m_timeline->m_document->view()->scheduleAnimation();
 }
 
 double DocumentTimeline::currentTime()
 {
+    if (!m_document)
+        return std::numeric_limits<double>::quiet_NaN();
     return m_document->animationClock().currentTime() - m_zeroTime;
 }
 
 void DocumentTimeline::pauseAnimationsForTesting(double pauseTime)
 {
-    for (size_t i = 0; i < m_players.size(); i++) {
-        m_players[i]->pauseForTesting();
-        m_players[i]->setCurrentTime(pauseTime);
-    }
+    for (size_t i = 0; i < m_currentPlayers.size(); i++)
+        m_currentPlayers[i]->pauseForTesting(pauseTime);
+    serviceAnimations();
+}
+
+void DocumentTimeline::setHasPlayerNeedingUpdate()
+{
+    m_hasPlayerNeedingUpdate = true;
+    if (m_document && m_document->view() && !m_document->view()->isServicingAnimations())
+        m_timing->serviceOnNextFrame();
 }
 
 void DocumentTimeline::dispatchEvents()
@@ -176,12 +191,16 @@
     if (isNull(m_zeroTime))
         return 0;
     size_t count = 0;
-    for (size_t i = 0; i < m_players.size(); ++i) {
-        const TimedItem* timedItem = m_players[i]->source();
-        if (m_players[i]->hasStartTime())
+    for (size_t i = 0; i < m_currentPlayers.size(); ++i) {
+        const TimedItem* timedItem = m_currentPlayers[i]->source();
+        if (m_currentPlayers[i]->hasStartTime())
             count += (timedItem && (timedItem->isCurrent() || timedItem->isInEffect()));
     }
     return count;
 }
 
+void DocumentTimeline::detachFromDocument() {
+    m_document = 0;
+}
+
 } // namespace
diff --git a/Source/core/animation/DocumentTimeline.h b/Source/core/animation/DocumentTimeline.h
index 25bf835..c334bd6 100644
--- a/Source/core/animation/DocumentTimeline.h
+++ b/Source/core/animation/DocumentTimeline.h
@@ -60,6 +60,7 @@
     };
 
     static PassRefPtr<DocumentTimeline> create(Document*, PassOwnPtr<PlatformTiming> = nullptr);
+    ~DocumentTimeline();
     // Returns whether style recalc was triggered.
     bool serviceAnimations();
 
@@ -67,6 +68,12 @@
     Player* createPlayer(TimedItem*);
     Player* play(TimedItem*);
 
+    void playerDestroyed(Player* player)
+    {
+        ASSERT(m_players.contains(player));
+        m_players.remove(player);
+    }
+
     // Called from setReadyState() in Document.cpp to set m_zeroTime to
     // performance.timing.domInteractive
     void setZeroTime(double);
@@ -75,6 +82,10 @@
     double currentTime();
     void pauseAnimationsForTesting(double);
     size_t numberOfActiveAnimationsForTesting() const;
+    const Vector<RefPtr<Player> >& currentPlayers() const { return m_currentPlayers; }
+
+    void setHasPlayerNeedingUpdate();
+    bool hasPlayerNeedingUpdate() const { return m_hasPlayerNeedingUpdate; }
 
     void addEventToDispatch(EventTarget* target, PassRefPtr<Event> event)
     {
@@ -84,6 +95,8 @@
     void dispatchEvents();
     void dispatchEventsAsync();
 
+    void detachFromDocument();
+
 protected:
     DocumentTimeline(Document*, PassOwnPtr<PlatformTiming>);
 
@@ -91,7 +104,9 @@
     double m_zeroTime;
     Document* m_document;
     Timer<DocumentTimeline> m_eventDistpachTimer;
-    Vector<RefPtr<Player> > m_players;
+    Vector<RefPtr<Player> > m_currentPlayers;
+    HashSet<Player*> m_players;
+    bool m_hasPlayerNeedingUpdate;
 
     void eventDispatchTimerFired(Timer<DocumentTimeline>*);
     void wake();
@@ -111,7 +126,7 @@
 
     OwnPtr<PlatformTiming> m_timing;
 
-    class DocumentTimelineTiming : public PlatformTiming {
+    class DocumentTimelineTiming FINAL : public PlatformTiming {
     public:
         DocumentTimelineTiming(DocumentTimeline* documentTimeline)
             : m_timeline(documentTimeline)
diff --git a/Source/core/animation/DocumentTimelineTest.cpp b/Source/core/animation/DocumentTimelineTest.cpp
index 41fad8c..b3c850e 100644
--- a/Source/core/animation/DocumentTimelineTest.cpp
+++ b/Source/core/animation/DocumentTimelineTest.cpp
@@ -33,7 +33,7 @@
 
 #include "core/animation/Animation.h"
 #include "core/animation/AnimationClock.h"
-#include "core/animation/KeyframeAnimationEffect.h"
+#include "core/animation/KeyframeEffectModel.h"
 #include "core/animation/TimedItem.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
@@ -132,7 +132,7 @@
 
 TEST_F(AnimationDocumentTimelineTest, EmptyKeyframeAnimation)
 {
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector());
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector());
     RefPtr<Animation> anim = Animation::create(element.get(), effect, timing);
 
     timeline->play(anim.get());
@@ -140,6 +140,25 @@
     platformTiming->expectNoMoreActions();
     updateClockAndService(0);
     EXPECT_FLOAT_EQ(0, timeline->currentTime());
+    EXPECT_FALSE(anim->isInEffect());
+
+    platformTiming->expectNoMoreActions();
+    updateClockAndService(100);
+    EXPECT_FLOAT_EQ(100, timeline->currentTime());
+}
+
+TEST_F(AnimationDocumentTimelineTest, EmptyForwardsKeyframeAnimation)
+{
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector());
+    timing.fillMode = Timing::FillModeForwards;
+    RefPtr<Animation> anim = Animation::create(element.get(), effect, timing);
+
+    timeline->play(anim.get());
+
+    platformTiming->expectNoMoreActions();
+    updateClockAndService(0);
+    EXPECT_FLOAT_EQ(0, timeline->currentTime());
+    EXPECT_TRUE(anim->isInEffect());
     EXPECT_TRUE(anim->compositableValues()->isEmpty());
 
     platformTiming->expectNoMoreActions();
@@ -163,7 +182,7 @@
 TEST_F(AnimationDocumentTimelineTest, EmptyTargetDoesNotTriggerStyleRecalc)
 {
     timing.iterationDuration = 200;
-    timeline->play(Animation::create(0, KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing).get());
+    timeline->play(Animation::create(0, KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector()), timing).get());
     document->animationClock().updateTime(100);
     EXPECT_FALSE(timeline->serviceAnimations());
 }
@@ -177,7 +196,8 @@
 
 TEST_F(AnimationDocumentTimelineTest, TriggerStyleRecalc)
 {
-    timeline->play(Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing).get());
+    timing.iterationDuration = 200;
+    timeline->play(Animation::create(element.get(), KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector()), timing).get());
     document->animationClock().updateTime(100);
     EXPECT_TRUE(timeline->serviceAnimations());
 }
@@ -203,8 +223,9 @@
 TEST_F(AnimationDocumentTimelineTest, PauseForTesting)
 {
     float seekTime = 1;
-    RefPtr<Animation> anim1 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing);
-    RefPtr<Animation> anim2  = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing);
+    timing.fillMode = Timing::FillModeForwards;
+    RefPtr<Animation> anim1 = Animation::create(element.get(), KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector()), timing);
+    RefPtr<Animation> anim2  = Animation::create(element.get(), KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector()), timing);
     Player* player1 = timeline->play(anim1.get());
     Player* player2 = timeline->play(anim2.get());
     timeline->pauseAnimationsForTesting(seekTime);
@@ -216,45 +237,47 @@
 TEST_F(AnimationDocumentTimelineTest, NumberOfActiveAnimations)
 {
     Timing timingForwardFill;
-    timingForwardFill.hasIterationDuration = true;
     timingForwardFill.iterationDuration = 2;
+    timingForwardFill.fillMode = Timing::FillModeForwards;
 
     Timing timingNoFill;
-    timingNoFill.hasIterationDuration = true;
     timingNoFill.iterationDuration = 2;
     timingNoFill.fillMode = Timing::FillModeNone;
 
     Timing timingBackwardFillDelay;
-    timingBackwardFillDelay.hasIterationDuration = true;
     timingBackwardFillDelay.iterationDuration = 1;
     timingBackwardFillDelay.fillMode = Timing::FillModeBackwards;
     timingBackwardFillDelay.startDelay = 1;
 
     Timing timingNoFillDelay;
-    timingNoFillDelay.hasIterationDuration = true;
     timingNoFillDelay.iterationDuration = 1;
     timingNoFillDelay.fillMode = Timing::FillModeNone;
     timingNoFillDelay.startDelay = 1;
 
-    RefPtr<Animation> anim1 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingForwardFill);
-    RefPtr<Animation> anim2 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingNoFill);
-    RefPtr<Animation> anim3 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingBackwardFillDelay);
-    RefPtr<Animation> anim4 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingNoFillDelay);
+    Timing timingAutoFill;
+    timingAutoFill.iterationDuration = 2;
+
+    RefPtr<Animation> anim1 = Animation::create(element.get(), KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector()), timingForwardFill);
+    RefPtr<Animation> anim2 = Animation::create(element.get(), KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector()), timingNoFill);
+    RefPtr<Animation> anim3 = Animation::create(element.get(), KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector()), timingBackwardFillDelay);
+    RefPtr<Animation> anim4 = Animation::create(element.get(), KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector()), timingNoFillDelay);
+    RefPtr<Animation> anim5 = Animation::create(element.get(), KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector()), timingAutoFill);
 
     timeline->play(anim1.get());
     timeline->play(anim2.get());
     timeline->play(anim3.get());
     timeline->play(anim4.get());
+    timeline->play(anim5.get());
 
     platformTiming->expectNextFrameAction();
     updateClockAndService(0);
-    EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
+    EXPECT_EQ(5U, timeline->numberOfActiveAnimationsForTesting());
     platformTiming->expectNextFrameAction();
     updateClockAndService(0.5);
-    EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
+    EXPECT_EQ(5U, timeline->numberOfActiveAnimationsForTesting());
     platformTiming->expectNextFrameAction();
     updateClockAndService(1.5);
-    EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
+    EXPECT_EQ(5U, timeline->numberOfActiveAnimationsForTesting());
     platformTiming->expectNoMoreActions();
     updateClockAndService(3);
     EXPECT_EQ(1U, timeline->numberOfActiveAnimationsForTesting());
@@ -262,7 +285,6 @@
 
 TEST_F(AnimationDocumentTimelineTest, DelayBeforeAnimationStart)
 {
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 2;
     timing.startDelay = 5;
 
@@ -284,4 +306,26 @@
     updateClockAndService(4.98);
 }
 
+TEST_F(AnimationDocumentTimelineTest, PlayAfterDocumentDeref)
+{
+    timing.iterationDuration = 2;
+    timing.startDelay = 5;
+
+    timeline = document->timeline();
+    element = 0;
+    document = 0;
+
+    RefPtr<Animation> anim = Animation::create(0, 0, timing);
+    // Test passes if this does not crash.
+    timeline->play(anim.get());
+}
+
+TEST_F(AnimationDocumentTimelineTest, UsePlayerAfterTimelineDeref)
+{
+    RefPtr<Player> player = timeline->createPlayer(0);
+    timeline.clear();
+    // Test passes if this does not crash.
+    player->setStartTime(0);
+}
+
 }
diff --git a/Source/core/animation/ElementAnimation.cpp b/Source/core/animation/ElementAnimation.cpp
new file mode 100644
index 0000000..24c7b7a
--- /dev/null
+++ b/Source/core/animation/ElementAnimation.cpp
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/animation/ElementAnimation.h"
+
+#include "bindings/v8/Dictionary.h"
+#include "core/animation/DocumentTimeline.h"
+#include "core/animation/css/CSSAnimations.h"
+
+namespace WebCore {
+
+Animation* ElementAnimation::animate(Element* element, Vector<Dictionary> keyframeDictionaryVector, Dictionary timingInput)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsAPIEnabled());
+
+    RefPtr<Animation> animation = Animation::create(element, keyframeDictionaryVector, timingInput);
+    DocumentTimeline* timeline = element->document().timeline();
+    ASSERT(timeline);
+    timeline->play(animation.get());
+
+    return animation.get();
+}
+
+Animation* ElementAnimation::animate(Element* element, Vector<Dictionary> keyframeDictionaryVector, double timingInput)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsAPIEnabled());
+
+    RefPtr<Animation> animation = Animation::create(element, keyframeDictionaryVector, timingInput);
+    DocumentTimeline* timeline = element->document().timeline();
+    ASSERT(timeline);
+    timeline->play(animation.get());
+
+    return animation.get();
+}
+
+Animation* ElementAnimation::animate(Element* element, Vector<Dictionary> keyframeDictionaryVector)
+{
+    ASSERT(RuntimeEnabledFeatures::webAnimationsAPIEnabled());
+
+    RefPtr<Animation> animation = Animation::create(element, keyframeDictionaryVector);
+    DocumentTimeline* timeline = element->document().timeline();
+    ASSERT(timeline);
+    timeline->play(animation.get());
+
+    return animation.get();
+}
+
+} // namespace WebCore
diff --git a/Source/core/frame/GraphicsLayerDebugInfo.h b/Source/core/animation/ElementAnimation.h
similarity index 77%
rename from Source/core/frame/GraphicsLayerDebugInfo.h
rename to Source/core/animation/ElementAnimation.h
index 26d2fce..66921a4 100644
--- a/Source/core/frame/GraphicsLayerDebugInfo.h
+++ b/Source/core/animation/ElementAnimation.h
@@ -28,23 +28,24 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef GraphicsLayerDebugInfo_h
-#define GraphicsLayerDebugInfo_h
-
-#include "platform/geometry/LayoutRect.h"
-#include "public/platform/WebGraphicsLayerDebugInfo.h"
+#ifndef ElementAnimation_h
+#define ElementAnimation_h
 
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
-class GraphicsLayerDebugInfo FINAL : public blink::WebGraphicsLayerDebugInfo {
+class Animation;
+class Dictionary;
+class Element;
+
+class ElementAnimation {
 public:
-    virtual void appendAsTraceFormat(blink::WebString* out) const OVERRIDE;
-    virtual ~GraphicsLayerDebugInfo() { };
-    Vector<LayoutRect> m_currentLayoutRects;
+    static Animation* animate(Element*, Vector<Dictionary> keyframesDictionaryVector, Dictionary timingInput);
+    static Animation* animate(Element*, Vector<Dictionary> keyframesDictionaryVector, double timingInput);
+    static Animation* animate(Element*, Vector<Dictionary> keyframesDictionaryVector);
 };
 
 } // namespace WebCore
 
-#endif
+#endif // ElementAnimation_h
diff --git a/Source/core/html/HTMLImportDataClient.h b/Source/core/animation/ElementAnimation.idl
similarity index 84%
copy from Source/core/html/HTMLImportDataClient.h
copy to Source/core/animation/ElementAnimation.idl
index 0c26a22..e5c5137 100644
--- a/Source/core/html/HTMLImportDataClient.h
+++ b/Source/core/animation/ElementAnimation.idl
@@ -28,17 +28,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef HTMLImportDataClient_h
-#define HTMLImportDataClient_h
-
-namespace WebCore {
-
-class HTMLImportDataClient {
-public:
-    virtual ~HTMLImportDataClient() { }
-    virtual void didFinish() = 0;
+[
+    RuntimeEnabled=WebAnimationsAPI,
+] partial interface Element {
+    Animation animate(sequence<Dictionary> keyframes, Dictionary timingInput);
+    Animation animate(sequence<Dictionary> keyframes, double timingInput);
+    Animation animate(sequence<Dictionary> keyframes);
 };
-
-}
-
-#endif // HTMLImportDataClient_h
diff --git a/Source/core/animation/InertAnimation.cpp b/Source/core/animation/InertAnimation.cpp
index 3cb2150..7343523 100644
--- a/Source/core/animation/InertAnimation.cpp
+++ b/Source/core/animation/InertAnimation.cpp
@@ -58,7 +58,7 @@
 }
 
 
-double InertAnimation::calculateTimeToEffectChange(double, double) const
+double InertAnimation::calculateTimeToEffectChange(bool, double, double) const
 {
     return std::numeric_limits<double>::infinity();
 }
diff --git a/Source/core/animation/InertAnimation.h b/Source/core/animation/InertAnimation.h
index a52ba53..7b220a5 100644
--- a/Source/core/animation/InertAnimation.h
+++ b/Source/core/animation/InertAnimation.h
@@ -46,9 +46,9 @@
     bool paused() const { return m_paused; }
 
 protected:
-    virtual bool updateChildrenAndEffects() const OVERRIDE { return false; };
-    virtual void willDetach() OVERRIDE { };
-    virtual double calculateTimeToEffectChange(double inheritedTime, double timeToNextIteration) const OVERRIDE FINAL;
+    virtual bool updateChildrenAndEffects() const OVERRIDE { return false; }
+    virtual void willDetach() OVERRIDE { }
+    virtual double calculateTimeToEffectChange(bool forwards, double inheritedTime, double timeToNextIteration) const OVERRIDE;
 
 private:
     InertAnimation(PassRefPtr<AnimationEffect>, const Timing&, bool paused);
diff --git a/Source/core/animation/KeyframeAnimationEffectTest.cpp b/Source/core/animation/KeyframeAnimationEffectTest.cpp
deleted file mode 100644
index 89c51bb..0000000
--- a/Source/core/animation/KeyframeAnimationEffectTest.cpp
+++ /dev/null
@@ -1,379 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/animation/KeyframeAnimationEffect.h"
-
-#include "core/animation/AnimatableLength.h"
-#include "core/animation/AnimatableUnknown.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-namespace {
-
-AnimatableValue* unknownAnimatableValue(double n)
-{
-    return AnimatableUnknown::create(CSSPrimitiveValue::create(n, CSSPrimitiveValue::CSS_UNKNOWN).get()).leakRef();
-}
-
-AnimatableValue* pixelAnimatableValue(double n)
-{
-    return AnimatableLength::create(CSSPrimitiveValue::create(n, CSSPrimitiveValue::CSS_PX).get()).leakRef();
-}
-
-KeyframeAnimationEffect::KeyframeVector keyframesAtZeroAndOne(AnimatableValue* zeroValue, AnimatableValue* oneValue)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(2);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, zeroValue);
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(1.0);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, oneValue);
-    return keyframes;
-}
-
-void expectDoubleValue(double expectedValue, PassRefPtr<AnimatableValue> value)
-{
-    ASSERT_TRUE(value->isLength() || value->isUnknown());
-
-    double actualValue;
-    if (value->isLength())
-        actualValue = toCSSPrimitiveValue(toAnimatableLength(value.get())->toCSSValue().get())->getDoubleValue();
-    else
-        actualValue = toCSSPrimitiveValue(toAnimatableUnknown(value.get())->toCSSValue().get())->getDoubleValue();
-
-    EXPECT_FLOAT_EQ(static_cast<float>(expectedValue), actualValue);
-}
-
-
-TEST(AnimationKeyframeAnimationEffectTest, BasicOperation)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
-    ASSERT_EQ(1UL, values->size());
-    EXPECT_EQ(CSSPropertyLeft, values->at(0).first);
-    expectDoubleValue(5.0, values->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, CompositeReplaceNonInterpolable)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
-    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
-    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, CompositeReplace)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
-    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
-    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(3.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, CompositeAdd)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
-    keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
-    keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, ExtrapolateReplaceNonInterpolable)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
-    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
-    expectDoubleValue(5.0, effect->sample(0, 1.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, ExtrapolateReplace)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
-    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
-    expectDoubleValue(3.0 * -0.6 + 5.0 * 1.6, effect->sample(0, 1.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, ExtrapolateAdd)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
-    keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
-    keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue((7.0 + 3.0) * -0.6 + (7.0 + 5.0) * 1.6, effect->sample(0, 1.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, ZeroKeyframes)
-{
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector());
-    EXPECT_TRUE(effect->sample(0, 0.5)->isEmpty());
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, SingleKeyframeAtOffsetZero)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(1);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(3.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, SingleKeyframeAtOffsetOne)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(1);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(1.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(5.0));
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(7.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, MoreThanTwoKeyframes)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(3);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(0.5);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(4.0));
-    keyframes[2] = Keyframe::create();
-    keyframes[2]->setOffset(1.0);
-    keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(4.0, effect->sample(0, 0.3)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    expectDoubleValue(5.0, effect->sample(0, 0.8)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, EndKeyframeOffsetsUnspecified)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(3);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(0.5);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(4.0));
-    keyframes[2] = Keyframe::create();
-    keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(3.0, effect->sample(0, 0.1)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    expectDoubleValue(4.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    expectDoubleValue(5.0, effect->sample(0, 0.9)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, SampleOnKeyframe)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(3);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(0.5);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(4.0));
-    keyframes[2] = Keyframe::create();
-    keyframes[2]->setOffset(1.0);
-    keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(3.0, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    expectDoubleValue(4.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    expectDoubleValue(5.0, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-// Note that this tests an implementation detail, not behaviour defined by the spec.
-TEST(AnimationKeyframeAnimationEffectTest, SampleReturnsSameAnimatableValueInstance)
-{
-    AnimatableValue* threePixelsValue = unknownAnimatableValue(3.0);
-    AnimatableValue* fourPixelsValue = unknownAnimatableValue(4.0);
-    AnimatableValue* fivePixelsValue = unknownAnimatableValue(5.0);
-
-    KeyframeAnimationEffect::KeyframeVector keyframes(3);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, threePixelsValue);
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(0.5);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, fourPixelsValue);
-    keyframes[2] = Keyframe::create();
-    keyframes[2]->setOffset(1.0);
-    keyframes[2]->setPropertyValue(CSSPropertyLeft, fivePixelsValue);
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    EXPECT_EQ(threePixelsValue, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    EXPECT_EQ(threePixelsValue, effect->sample(0, 0.1)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.4)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    EXPECT_EQ(fivePixelsValue, effect->sample(0, 0.9)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    EXPECT_EQ(fivePixelsValue, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, MultipleKeyframesWithSameOffset)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(7);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.1);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(1.0));
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(0.1);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(2.0));
-    keyframes[2] = Keyframe::create();
-    keyframes[2]->setOffset(0.5);
-    keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
-    keyframes[3] = Keyframe::create();
-    keyframes[3]->setOffset(0.5);
-    keyframes[3]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(4.0));
-    keyframes[4] = Keyframe::create();
-    keyframes[4]->setOffset(0.5);
-    keyframes[4]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
-    keyframes[5] = Keyframe::create();
-    keyframes[5]->setOffset(0.9);
-    keyframes[5]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(6.0));
-    keyframes[6] = Keyframe::create();
-    keyframes[6]->setOffset(0.9);
-    keyframes[6]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(7.0));
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(2.0, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
-    expectDoubleValue(2.0, effect->sample(0, 0.2)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
-    expectDoubleValue(3.0, effect->sample(0, 0.4)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
-    expectDoubleValue(5.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
-    expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
-    expectDoubleValue(6.0, effect->sample(0, 0.8)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
-    expectDoubleValue(6.0, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, PerKeyframeComposite)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(2);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(3.0));
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(1.0);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(5.0));
-    keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(3.0 * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, MultipleProperties)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(2);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
-    keyframes[0]->setPropertyValue(CSSPropertyRight, unknownAnimatableValue(4.0));
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(1.0);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
-    keyframes[1]->setPropertyValue(CSSPropertyRight, unknownAnimatableValue(6.0));
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
-    ASSERT_EQ(2UL, values->size());
-    ASSERT_TRUE(values->at(0).first == CSSPropertyLeft);
-    expectDoubleValue(5.0, values->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
-    ASSERT_TRUE(values->at(1).first == CSSPropertyRight);
-    expectDoubleValue(6.0, values->at(1).second->compositeOnto(unknownAnimatableValue(7.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, RecompositeCompositableValue)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
-    keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
-    keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
-    expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, values->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
-    expectDoubleValue((9.0 + 3.0) * 0.4 + (9.0 + 5.0) * 0.6, values->at(0).second->compositeOnto(pixelAnimatableValue(9.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, MultipleIterations)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(1.0), pixelAnimatableValue(3.0));
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    expectDoubleValue(2.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0)));
-    expectDoubleValue(2.0, effect->sample(1, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0)));
-    expectDoubleValue(2.0, effect->sample(2, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0)));
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, DependsOnUnderlyingValue)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(3);
-    keyframes[0] = Keyframe::create();
-    keyframes[0]->setOffset(0.0);
-    keyframes[0]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
-    keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
-    keyframes[1] = Keyframe::create();
-    keyframes[1]->setOffset(0.5);
-    keyframes[1]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
-    keyframes[2] = Keyframe::create();
-    keyframes[2]->setOffset(1.0);
-    keyframes[2]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
-
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-    EXPECT_TRUE(effect->sample(0, 0)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_TRUE(effect->sample(0, 0.1)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_TRUE(effect->sample(0, 0.25)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_TRUE(effect->sample(0, 0.4)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 0.5)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 0.6)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 0.75)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 0.8)->at(0).second->dependsOnUnderlyingValue());
-    EXPECT_FALSE(effect->sample(0, 1)->at(0).second->dependsOnUnderlyingValue());
-}
-
-TEST(AnimationKeyframeAnimationEffectTest, ToKeyframeAnimationEffect)
-{
-    KeyframeAnimationEffect::KeyframeVector keyframes(0);
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
-
-    AnimationEffect* baseEffect = effect.get();
-    EXPECT_TRUE(toKeyframeAnimationEffect(baseEffect));
-}
-
-} // namespace
diff --git a/Source/core/animation/KeyframeAnimationEffect.cpp b/Source/core/animation/KeyframeEffectModel.cpp
similarity index 64%
rename from Source/core/animation/KeyframeAnimationEffect.cpp
rename to Source/core/animation/KeyframeEffectModel.cpp
index dd6ffa3..82afcfa 100644
--- a/Source/core/animation/KeyframeAnimationEffect.cpp
+++ b/Source/core/animation/KeyframeEffectModel.cpp
@@ -29,7 +29,7 @@
  */
 
 #include "config.h"
-#include "core/animation/KeyframeAnimationEffect.h"
+#include "core/animation/KeyframeEffectModel.h"
 
 #include "core/animation/TimedItem.h"
 #include "wtf/text/StringHash.h"
@@ -38,39 +38,17 @@
 
 using namespace WebCore;
 
-class ReplaceCompositableValue : public AnimationEffect::CompositableValue {
-public:
-    static PassRefPtr<ReplaceCompositableValue> create(const AnimatableValue* value)
-    {
-        return adoptRef(new ReplaceCompositableValue(value));
-    }
-    virtual bool dependsOnUnderlyingValue() const
-    {
-        return false;
-    }
-    virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const
-    {
-        return PassRefPtr<AnimatableValue>(m_value);
-    }
-private:
-    ReplaceCompositableValue(const AnimatableValue* value)
-        : m_value(const_cast<AnimatableValue*>(value))
-    {
-    }
-    RefPtr<AnimatableValue> m_value;
-};
-
-class AddCompositableValue : public AnimationEffect::CompositableValue {
+class AddCompositableValue FINAL : public AnimationEffect::CompositableValue {
 public:
     static PassRefPtr<AddCompositableValue> create(const AnimatableValue* value)
     {
         return adoptRef(new AddCompositableValue(value));
     }
-    virtual bool dependsOnUnderlyingValue() const
+    virtual bool dependsOnUnderlyingValue() const OVERRIDE
     {
         return true;
     }
-    virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const
+    virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const OVERRIDE
     {
         return AnimatableValue::add(underlyingValue, m_value.get());
     }
@@ -82,17 +60,17 @@
     RefPtr<AnimatableValue> m_value;
 };
 
-class BlendedCompositableValue : public AnimationEffect::CompositableValue {
+class BlendedCompositableValue FINAL : public AnimationEffect::CompositableValue {
 public:
     static PassRefPtr<BlendedCompositableValue> create(const AnimationEffect::CompositableValue* before, const AnimationEffect::CompositableValue* after, double fraction)
     {
         return adoptRef(new BlendedCompositableValue(before, after, fraction));
     }
-    virtual bool dependsOnUnderlyingValue() const
+    virtual bool dependsOnUnderlyingValue() const OVERRIDE
     {
         return m_dependsOnUnderlyingValue;
     }
-    virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const
+    virtual PassRefPtr<AnimatableValue> compositeOnto(const AnimatableValue* underlyingValue) const OVERRIDE
     {
         return AnimatableValue::interpolate(m_before->compositeOnto(underlyingValue).get(), m_after->compositeOnto(underlyingValue).get(), m_fraction);
     }
@@ -109,6 +87,8 @@
     bool m_dependsOnUnderlyingValue;
 };
 
+const double accuracyForKeyframeEasing = 0.0000001;
+
 } // namespace
 
 
@@ -122,6 +102,7 @@
 Keyframe::Keyframe(const Keyframe& copyFrom)
     : m_offset(copyFrom.m_offset)
     , m_composite(copyFrom.m_composite)
+    , m_easing(copyFrom.m_easing)
 {
     for (PropertyValueMap::const_iterator iter = copyFrom.m_propertyValues.begin(); iter != copyFrom.m_propertyValues.end(); ++iter)
         setPropertyValue(iter->key, iter->value.get());
@@ -160,21 +141,20 @@
     return theClone.release();
 }
 
-KeyframeAnimationEffect::KeyframeAnimationEffect(const KeyframeVector& keyframes)
+KeyframeEffectModel::KeyframeEffectModel(const KeyframeVector& keyframes)
     : m_keyframes(keyframes)
 {
 }
 
-PropertySet KeyframeAnimationEffect::properties() const
+PropertySet KeyframeEffectModel::properties() const
 {
     PropertySet result;
-    const KeyframeVector& frames = getFrames();
-    if (!frames.size()) {
+    if (!m_keyframes.size()) {
         return result;
     }
-    result = frames[0]->properties();
-    for (size_t i = 1; i < frames.size(); i++) {
-        PropertySet extras = frames[i]->properties();
+    result = m_keyframes[0]->properties();
+    for (size_t i = 1; i < m_keyframes.size(); i++) {
+        PropertySet extras = m_keyframes[i]->properties();
         for (PropertySet::const_iterator it = extras.begin(); it != extras.end(); ++it) {
             result.add(*it);
         }
@@ -182,62 +162,102 @@
     return result;
 }
 
-PassOwnPtr<AnimationEffect::CompositableValueList> KeyframeAnimationEffect::sample(int iteration, double fraction) const
+PassOwnPtr<AnimationEffect::CompositableValueList> KeyframeEffectModel::sample(int iteration, double fraction) const
 {
     ASSERT(iteration >= 0);
     ASSERT(!isNull(fraction));
-    const_cast<KeyframeAnimationEffect*>(this)->ensureKeyframeGroups();
+    const_cast<KeyframeEffectModel*>(this)->ensureKeyframeGroups();
     OwnPtr<CompositableValueList> map = adoptPtr(new CompositableValueList());
     for (KeyframeGroupMap::const_iterator iter = m_keyframeGroups->begin(); iter != m_keyframeGroups->end(); ++iter)
         map->append(std::make_pair(iter->key, iter->value->sample(iteration, fraction)));
     return map.release();
 }
 
-KeyframeAnimationEffect::KeyframeVector KeyframeAnimationEffect::normalizedKeyframes() const
+KeyframeEffectModel::KeyframeVector KeyframeEffectModel::normalizedKeyframes(const KeyframeVector& keyframes)
 {
-    KeyframeVector keyframes = m_keyframes;
+    // keyframes [beginIndex, endIndex) will remain after removing all keyframes if they are not
+    // loosely sorted by offset, and after removing keyframes with positional offset outide [0, 1].
+    size_t beginIndex = 0;
+    size_t endIndex = keyframes.size();
 
-    // Set offsets at 0.0 and 1.0 at ends if unset.
-    if (keyframes.size() >= 2) {
-        Keyframe* firstKeyframe = keyframes.first().get();
-        if (isNull(firstKeyframe->offset()))
-            firstKeyframe->setOffset(0.0);
-    }
-    if (keyframes.size() >= 1) {
-        Keyframe* lastKeyframe = keyframes.last().get();
-        if (lastKeyframe && isNull(lastKeyframe->offset()))
-            lastKeyframe->setOffset(1.0);
+    // Becomes the most recent keyframe with an explicit offset.
+    size_t lastIndex = endIndex;
+    double lastOffset = std::numeric_limits<double>::quiet_NaN();
+
+    for (size_t i = 0; i < keyframes.size(); ++i) {
+        double offset = keyframes[i]->offset();
+        if (!isNull(offset)) {
+            if (lastIndex < i && offset < lastOffset) {
+                // The keyframes are not loosely sorted by offset. Exclude all.
+                endIndex = beginIndex;
+                break;
+            }
+
+            if (offset < 0) {
+                // Remove all keyframes up to and including this keyframe.
+                beginIndex = i + 1;
+            } else if (offset > 1) {
+                // Remove all keyframes from this keyframe onwards. Note we must complete our checking
+                // that the keyframes are loosely sorted by offset, so we can't exit the loop early.
+                endIndex = std::min(i, endIndex);
+            }
+
+            lastIndex = i;
+            lastOffset = offset;
+        }
     }
 
-    // FIXME: Distribute offsets where missing.
-    for (KeyframeVector::iterator iter = keyframes.begin(); iter != keyframes.end(); ++iter)
-        ASSERT(!isNull((*iter)->offset()));
+    KeyframeVector result;
+    if (beginIndex != endIndex) {
+        result.reserveCapacity(endIndex - beginIndex);
+        for (size_t i = beginIndex; i < endIndex; ++i) {
+            result.append(keyframes[i]->clone());
+        }
 
-    // Sort by offset.
-    std::stable_sort(keyframes.begin(), keyframes.end(), Keyframe::compareOffsets);
-    return keyframes;
+        if (isNull(result[result.size() - 1]->offset()))
+            result[result.size() - 1]->setOffset(1);
+
+        if (result.size() > 1 && isNull(result[0]->offset()))
+            result[0]->setOffset(0);
+
+        lastIndex = 0;
+        lastOffset = result[0]->offset();
+        for (size_t i = 1; i < result.size(); ++i) {
+            double offset = result[i]->offset();
+            if (!isNull(offset)) {
+                if (lastIndex + 1 < i) {
+                    for (size_t j = 1; j < i - lastIndex; ++j)
+                        result[lastIndex + j]->setOffset(lastOffset + (offset - lastOffset) * j / (i - lastIndex));
+                }
+                lastIndex = i;
+                lastOffset = offset;
+            }
+        }
+    }
+    return result;
 }
 
-void KeyframeAnimationEffect::ensureKeyframeGroups() const
+void KeyframeEffectModel::ensureKeyframeGroups() const
 {
     if (m_keyframeGroups)
         return;
 
     m_keyframeGroups = adoptPtr(new KeyframeGroupMap);
-    const KeyframeVector& keyframes = normalizedKeyframes();
+    const KeyframeVector keyframes = normalizedKeyframes(getFrames());
     for (KeyframeVector::const_iterator keyframeIter = keyframes.begin(); keyframeIter != keyframes.end(); ++keyframeIter) {
         const Keyframe* keyframe = keyframeIter->get();
         PropertySet keyframeProperties = keyframe->properties();
         for (PropertySet::const_iterator propertyIter = keyframeProperties.begin(); propertyIter != keyframeProperties.end(); ++propertyIter) {
             CSSPropertyID property = *propertyIter;
             KeyframeGroupMap::iterator groupIter = m_keyframeGroups->find(property);
-            if (groupIter == m_keyframeGroups->end()) {
-                KeyframeGroupMap::AddResult result = m_keyframeGroups->add(property, adoptPtr(new PropertySpecificKeyframeGroup));
-                ASSERT(result.isNewEntry);
-                groupIter = result.iterator;
-            }
-            groupIter->value->appendKeyframe(adoptPtr(
-                new PropertySpecificKeyframe(keyframe->offset(), keyframe->propertyValue(property), keyframe->composite())));
+            PropertySpecificKeyframeGroup* group;
+            if (groupIter == m_keyframeGroups->end())
+                group = m_keyframeGroups->add(property, adoptPtr(new PropertySpecificKeyframeGroup)).storedValue->value.get();
+            else
+                group = groupIter->value.get();
+
+            group->appendKeyframe(adoptPtr(
+                new PropertySpecificKeyframe(keyframe->offset(), keyframe->easing(), keyframe->propertyValue(property), keyframe->composite())));
         }
     }
 
@@ -249,34 +269,36 @@
 }
 
 
-KeyframeAnimationEffect::PropertySpecificKeyframe::PropertySpecificKeyframe(double offset, const AnimatableValue* value, CompositeOperation composite)
+KeyframeEffectModel::PropertySpecificKeyframe::PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, const AnimatableValue* value, CompositeOperation composite)
     : m_offset(offset)
+    , m_easing(easing)
     , m_value(composite == AnimationEffect::CompositeReplace ?
-        static_cast<PassRefPtr<CompositableValue> >(ReplaceCompositableValue::create(value)) :
+        AnimatableValue::takeConstRef(value) :
         static_cast<PassRefPtr<CompositableValue> >(AddCompositableValue::create(value)))
 {
 }
 
-KeyframeAnimationEffect::PropertySpecificKeyframe::PropertySpecificKeyframe(double offset, PassRefPtr<CompositableValue> value)
+KeyframeEffectModel::PropertySpecificKeyframe::PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, PassRefPtr<CompositableValue> value)
     : m_offset(offset)
+    , m_easing(easing)
     , m_value(value)
 {
     ASSERT(!isNull(m_offset));
 }
 
-PassOwnPtr<KeyframeAnimationEffect::PropertySpecificKeyframe> KeyframeAnimationEffect::PropertySpecificKeyframe::cloneWithOffset(double offset) const
+PassOwnPtr<KeyframeEffectModel::PropertySpecificKeyframe> KeyframeEffectModel::PropertySpecificKeyframe::cloneWithOffset(double offset) const
 {
-    return adoptPtr(new PropertySpecificKeyframe(offset, PassRefPtr<CompositableValue>(m_value)));
+    return adoptPtr(new PropertySpecificKeyframe(offset, m_easing, PassRefPtr<CompositableValue>(m_value)));
 }
 
 
-void KeyframeAnimationEffect::PropertySpecificKeyframeGroup::appendKeyframe(PassOwnPtr<PropertySpecificKeyframe> keyframe)
+void KeyframeEffectModel::PropertySpecificKeyframeGroup::appendKeyframe(PassOwnPtr<PropertySpecificKeyframe> keyframe)
 {
     ASSERT(m_keyframes.isEmpty() || m_keyframes.last()->offset() <= keyframe->offset());
     m_keyframes.append(keyframe);
 }
 
-void KeyframeAnimationEffect::PropertySpecificKeyframeGroup::removeRedundantKeyframes()
+void KeyframeEffectModel::PropertySpecificKeyframeGroup::removeRedundantKeyframes()
 {
     // As an optimization, removes keyframes in the following categories, as
     // they will never be used by sample().
@@ -295,7 +317,7 @@
     ASSERT(m_keyframes.size() >= 2);
 }
 
-void KeyframeAnimationEffect::PropertySpecificKeyframeGroup::addSyntheticKeyframeIfRequired()
+void KeyframeEffectModel::PropertySpecificKeyframeGroup::addSyntheticKeyframeIfRequired()
 {
     ASSERT(!m_keyframes.isEmpty());
     double offset = m_keyframes.first()->offset();
@@ -312,10 +334,10 @@
     if (!offset)
         appendKeyframe(m_keyframes.first()->cloneWithOffset(1.0));
     else
-        m_keyframes.insert(0, adoptPtr(new PropertySpecificKeyframe(0.0, AnimatableValue::neutralValue(), CompositeAdd)));
+        m_keyframes.insert(0, adoptPtr(new PropertySpecificKeyframe(0.0, 0, AnimatableValue::neutralValue(), CompositeAdd)));
 }
 
-PassRefPtr<AnimationEffect::CompositableValue> KeyframeAnimationEffect::PropertySpecificKeyframeGroup::sample(int iteration, double offset) const
+PassRefPtr<AnimationEffect::CompositableValue> KeyframeEffectModel::PropertySpecificKeyframeGroup::sample(int iteration, double offset) const
 {
     // FIXME: Implement accumulation.
     ASSERT_UNUSED(iteration, iteration >= 0);
@@ -360,8 +382,11 @@
         return const_cast<CompositableValue*>((*before)->value());
     if ((*after)->offset() == offset)
         return const_cast<CompositableValue*>((*after)->value());
-    return BlendedCompositableValue::create((*before)->value(), (*after)->value(),
-        (offset - (*before)->offset()) / ((*after)->offset() - (*before)->offset()));
+
+    double fraction = (offset - (*before)->offset()) / ((*after)->offset() - (*before)->offset());
+    if (const TimingFunction* timingFunction = (*before)->easing())
+        fraction = timingFunction->evaluate(fraction, accuracyForKeyframeEasing);
+    return BlendedCompositableValue::create((*before)->value(), (*after)->value(), fraction);
 }
 
 } // namespace
diff --git a/Source/core/animation/KeyframeAnimationEffect.h b/Source/core/animation/KeyframeEffectModel.h
similarity index 78%
rename from Source/core/animation/KeyframeAnimationEffect.h
rename to Source/core/animation/KeyframeEffectModel.h
index ee78429..78359d4 100644
--- a/Source/core/animation/KeyframeAnimationEffect.h
+++ b/Source/core/animation/KeyframeEffectModel.h
@@ -28,11 +28,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef KeyframeAnimationEffect_h
-#define KeyframeAnimationEffect_h
+#ifndef KeyframeEffectModel_h
+#define KeyframeEffectModel_h
 
 #include "core/animation/AnimatableValue.h"
 #include "core/animation/AnimationEffect.h"
+#include "platform/animation/TimingFunction.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/PassOwnPtr.h"
@@ -44,6 +45,8 @@
 
 typedef HashSet<CSSPropertyID> PropertySet;
 
+class KeyframeEffectModelTest;
+
 // Represents the keyframes set through the API.
 class Keyframe : public RefCounted<Keyframe> {
 public:
@@ -59,6 +62,8 @@
     double offset() const { return m_offset; }
     void setComposite(AnimationEffect::CompositeOperation composite) { m_composite = composite; }
     AnimationEffect::CompositeOperation composite() const { return m_composite; }
+    void setEasing(PassRefPtr<TimingFunction> easing) { m_easing = easing; }
+    TimingFunction* easing() const { return m_easing.get(); }
     void setPropertyValue(CSSPropertyID, const AnimatableValue*);
     void clearPropertyValue(CSSPropertyID);
     const AnimatableValue* propertyValue(CSSPropertyID) const;
@@ -70,19 +75,20 @@
     Keyframe(const Keyframe&);
     double m_offset;
     AnimationEffect::CompositeOperation m_composite;
+    RefPtr<TimingFunction> m_easing;
     typedef HashMap<CSSPropertyID, RefPtr<AnimatableValue> > PropertyValueMap;
     PropertyValueMap m_propertyValues;
 };
 
-class KeyframeAnimationEffect : public AnimationEffect {
+class KeyframeEffectModel FINAL : public AnimationEffect {
 public:
     class PropertySpecificKeyframe;
     typedef Vector<RefPtr<Keyframe> > KeyframeVector;
-    typedef Vector<OwnPtr<KeyframeAnimationEffect::PropertySpecificKeyframe> > PropertySpecificKeyframeVector;
+    typedef Vector<OwnPtr<PropertySpecificKeyframe> > PropertySpecificKeyframeVector;
     // FIXME: Implement accumulation.
-    static PassRefPtr<KeyframeAnimationEffect> create(const KeyframeVector& keyframes)
+    static PassRefPtr<KeyframeEffectModel> create(const KeyframeVector& keyframes)
     {
-        return adoptRef(new KeyframeAnimationEffect(keyframes));
+        return adoptRef(new KeyframeEffectModel(keyframes));
     }
 
     virtual bool affects(CSSPropertyID property) OVERRIDE
@@ -97,20 +103,22 @@
     // FIXME: Implement setFrames()
     const KeyframeVector& getFrames() const { return m_keyframes; }
 
-    virtual bool isKeyframeAnimationEffect() const OVERRIDE { return true; }
+    virtual bool isKeyframeEffectModel() const OVERRIDE { return true; }
 
     PropertySet properties() const;
 
     class PropertySpecificKeyframe {
     public:
-        PropertySpecificKeyframe(double offset, const AnimatableValue*, CompositeOperation);
+        PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, const AnimatableValue*, CompositeOperation);
         double offset() const { return m_offset; }
+        const TimingFunction* easing() const { return m_easing.get(); }
         const CompositableValue* value() const { return m_value.get(); }
         PassOwnPtr<PropertySpecificKeyframe> cloneWithOffset(double offset) const;
     private:
         // Used by cloneWithOffset().
-        PropertySpecificKeyframe(double offset, PassRefPtr<CompositableValue>);
+        PropertySpecificKeyframe(double offset, PassRefPtr<TimingFunction> easing, PassRefPtr<CompositableValue>);
         double m_offset;
+        RefPtr<TimingFunction> m_easing;
         RefPtr<CompositableValue> m_value;
     };
 
@@ -124,7 +132,7 @@
         void removeRedundantKeyframes();
         void addSyntheticKeyframeIfRequired();
 
-        friend class KeyframeAnimationEffect;
+        friend class KeyframeEffectModel;
     };
 
     const PropertySpecificKeyframeVector& getPropertySpecificKeyframes(CSSPropertyID id) const
@@ -134,9 +142,10 @@
     }
 
 private:
-    KeyframeAnimationEffect(const KeyframeVector& keyframes);
+    KeyframeEffectModel(const KeyframeVector& keyframes);
 
-    KeyframeVector normalizedKeyframes() const;
+    static KeyframeVector normalizedKeyframes(const KeyframeVector& keyframes);
+
     // Lazily computes the groups of property-specific keyframes.
     void ensureKeyframeGroups() const;
 
@@ -146,10 +155,12 @@
     // property-specific lists.
     typedef HashMap<CSSPropertyID, OwnPtr<PropertySpecificKeyframeGroup> > KeyframeGroupMap;
     mutable OwnPtr<KeyframeGroupMap> m_keyframeGroups;
+
+    friend class KeyframeEffectModelTest;
 };
 
-DEFINE_TYPE_CASTS(KeyframeAnimationEffect, AnimationEffect, value, value->isKeyframeAnimationEffect(), value.isKeyframeAnimationEffect());
+DEFINE_TYPE_CASTS(KeyframeEffectModel, AnimationEffect, value, value->isKeyframeEffectModel(), value.isKeyframeEffectModel());
 
 } // namespace WebCore
 
-#endif // KeyframeAnimationEffect_h
+#endif // KeyframeEffectModel_h
diff --git a/Source/core/animation/KeyframeEffectModelTest.cpp b/Source/core/animation/KeyframeEffectModelTest.cpp
new file mode 100644
index 0000000..75a6b21
--- /dev/null
+++ b/Source/core/animation/KeyframeEffectModelTest.cpp
@@ -0,0 +1,552 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/animation/KeyframeEffectModel.h"
+
+#include "core/animation/AnimatableLength.h"
+#include "core/animation/AnimatableUnknown.h"
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/parser/BisonCSSParser.h"
+#include "core/css/resolver/CSSToStyleMap.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+AnimatableValue* unknownAnimatableValue(double n)
+{
+    return AnimatableUnknown::create(CSSPrimitiveValue::create(n, CSSPrimitiveValue::CSS_UNKNOWN).get()).leakRef();
+}
+
+AnimatableValue* pixelAnimatableValue(double n)
+{
+    return AnimatableLength::create(CSSPrimitiveValue::create(n, CSSPrimitiveValue::CSS_PX).get()).leakRef();
+}
+
+KeyframeEffectModel::KeyframeVector keyframesAtZeroAndOne(AnimatableValue* zeroValue, AnimatableValue* oneValue)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(2);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, zeroValue);
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(1.0);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, oneValue);
+    return keyframes;
+}
+
+void expectDoubleValue(double expectedValue, PassRefPtr<AnimatableValue> value)
+{
+    ASSERT_TRUE(value->isLength() || value->isUnknown());
+
+    double actualValue;
+    if (value->isLength())
+        actualValue = toCSSPrimitiveValue(toAnimatableLength(value.get())->toCSSValue().get())->getDoubleValue();
+    else
+        actualValue = toCSSPrimitiveValue(toAnimatableUnknown(value.get())->toCSSValue().get())->getDoubleValue();
+
+    EXPECT_FLOAT_EQ(static_cast<float>(expectedValue), actualValue);
+}
+
+const AnimationEffect::CompositableValue* findValue(const AnimationEffect::CompositableValueList& values, CSSPropertyID id)
+{
+    for (size_t i = 0; i < values.size(); ++i) {
+        const std::pair<CSSPropertyID, RefPtr<AnimationEffect::CompositableValue> >& value = values.at(i);
+        if (value.first == id)
+            return value.second.get();
+    }
+    return 0;
+}
+
+
+TEST(AnimationKeyframeEffectModel, BasicOperation)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
+    ASSERT_EQ(1UL, values->size());
+    EXPECT_EQ(CSSPropertyLeft, values->at(0).first);
+    expectDoubleValue(5.0, values->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, CompositeReplaceNonInterpolable)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
+    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
+    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, CompositeReplace)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
+    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
+    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(3.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, CompositeAdd)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
+    keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
+    keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, CompositeEaseIn)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
+    RefPtr<CSSValue> timingFunction = BisonCSSParser::parseAnimationTimingFunctionValue("ease-in");
+    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
+    keyframes[0]->setEasing(CSSToStyleMap::animationTimingFunction(timingFunction.get(), false));
+    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(3.8582394, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, CompositeCubicBezier)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
+    RefPtr<CSSValue> timingFunction = BisonCSSParser::parseAnimationTimingFunctionValue("cubic-bezier(0.42, 0, 0.58, 1)");
+    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
+    keyframes[0]->setEasing(CSSToStyleMap::animationTimingFunction(timingFunction.get(), false));
+    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(4.3362322, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, ExtrapolateReplaceNonInterpolable)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
+    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
+    expectDoubleValue(5.0, effect->sample(0, 1.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, ExtrapolateReplace)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
+    keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
+    expectDoubleValue(3.0 * -0.6 + 5.0 * 1.6, effect->sample(0, 1.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, ExtrapolateAdd)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
+    keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
+    keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue((7.0 + 3.0) * -0.6 + (7.0 + 5.0) * 1.6, effect->sample(0, 1.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, ZeroKeyframes)
+{
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(KeyframeEffectModel::KeyframeVector());
+    EXPECT_TRUE(effect->sample(0, 0.5)->isEmpty());
+}
+
+TEST(AnimationKeyframeEffectModel, SingleKeyframeAtOffsetZero)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(1);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(3.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, SingleKeyframeAtOffsetOne)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(1);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(1.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(5.0));
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(7.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, MoreThanTwoKeyframes)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(3);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(0.5);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(4.0));
+    keyframes[2] = Keyframe::create();
+    keyframes[2]->setOffset(1.0);
+    keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(4.0, effect->sample(0, 0.3)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    expectDoubleValue(5.0, effect->sample(0, 0.8)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, EndKeyframeOffsetsUnspecified)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(3);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(0.5);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(4.0));
+    keyframes[2] = Keyframe::create();
+    keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(3.0, effect->sample(0, 0.1)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    expectDoubleValue(4.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    expectDoubleValue(5.0, effect->sample(0, 0.9)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, SampleOnKeyframe)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(3);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(0.5);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(4.0));
+    keyframes[2] = Keyframe::create();
+    keyframes[2]->setOffset(1.0);
+    keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(3.0, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    expectDoubleValue(4.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    expectDoubleValue(5.0, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+// Note that this tests an implementation detail, not behaviour defined by the spec.
+TEST(AnimationKeyframeEffectModel, SampleReturnsSameAnimatableValueInstance)
+{
+    AnimatableValue* threePixelsValue = unknownAnimatableValue(3.0);
+    AnimatableValue* fourPixelsValue = unknownAnimatableValue(4.0);
+    AnimatableValue* fivePixelsValue = unknownAnimatableValue(5.0);
+
+    KeyframeEffectModel::KeyframeVector keyframes(3);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, threePixelsValue);
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(0.5);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, fourPixelsValue);
+    keyframes[2] = Keyframe::create();
+    keyframes[2]->setOffset(1.0);
+    keyframes[2]->setPropertyValue(CSSPropertyLeft, fivePixelsValue);
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    EXPECT_EQ(threePixelsValue, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    EXPECT_EQ(threePixelsValue, effect->sample(0, 0.1)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.4)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    EXPECT_EQ(fivePixelsValue, effect->sample(0, 0.9)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+    EXPECT_EQ(fivePixelsValue, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, MultipleKeyframesWithSameOffset)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(7);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.1);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(1.0));
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(0.1);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(2.0));
+    keyframes[2] = Keyframe::create();
+    keyframes[2]->setOffset(0.5);
+    keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
+    keyframes[3] = Keyframe::create();
+    keyframes[3]->setOffset(0.5);
+    keyframes[3]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(4.0));
+    keyframes[4] = Keyframe::create();
+    keyframes[4]->setOffset(0.5);
+    keyframes[4]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
+    keyframes[5] = Keyframe::create();
+    keyframes[5]->setOffset(0.9);
+    keyframes[5]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(6.0));
+    keyframes[6] = Keyframe::create();
+    keyframes[6]->setOffset(0.9);
+    keyframes[6]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(7.0));
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(2.0, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+    expectDoubleValue(2.0, effect->sample(0, 0.2)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+    expectDoubleValue(3.0, effect->sample(0, 0.4)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+    expectDoubleValue(5.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+    expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+    expectDoubleValue(6.0, effect->sample(0, 0.8)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+    expectDoubleValue(6.0, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, PerKeyframeComposite)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(2);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(3.0));
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(1.0);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(5.0));
+    keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(3.0 * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, MultipleProperties)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(2);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
+    keyframes[0]->setPropertyValue(CSSPropertyRight, unknownAnimatableValue(4.0));
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(1.0);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
+    keyframes[1]->setPropertyValue(CSSPropertyRight, unknownAnimatableValue(6.0));
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
+    EXPECT_EQ(2UL, values->size());
+    const AnimationEffect::CompositableValue* leftValue = findValue(*values.get(), CSSPropertyLeft);
+    ASSERT_TRUE(leftValue);
+    expectDoubleValue(5.0, leftValue->compositeOnto(unknownAnimatableValue(7.0)));
+    const AnimationEffect::CompositableValue* rightValue = findValue(*values.get(), CSSPropertyRight);
+    ASSERT_TRUE(rightValue);
+    expectDoubleValue(6.0, rightValue->compositeOnto(unknownAnimatableValue(7.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, RecompositeCompositableValue)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
+    keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
+    keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
+    expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, values->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
+    expectDoubleValue((9.0 + 3.0) * 0.4 + (9.0 + 5.0) * 0.6, values->at(0).second->compositeOnto(pixelAnimatableValue(9.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, MultipleIterations)
+{
+    KeyframeEffectModel::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(1.0), pixelAnimatableValue(3.0));
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    expectDoubleValue(2.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0)));
+    expectDoubleValue(2.0, effect->sample(1, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0)));
+    expectDoubleValue(2.0, effect->sample(2, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0)));
+}
+
+TEST(AnimationKeyframeEffectModel, DependsOnUnderlyingValue)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(3);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.0);
+    keyframes[0]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
+    keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(0.5);
+    keyframes[1]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
+    keyframes[2] = Keyframe::create();
+    keyframes[2]->setOffset(1.0);
+    keyframes[2]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
+
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+    EXPECT_TRUE(effect->sample(0, 0)->at(0).second->dependsOnUnderlyingValue());
+    EXPECT_TRUE(effect->sample(0, 0.1)->at(0).second->dependsOnUnderlyingValue());
+    EXPECT_TRUE(effect->sample(0, 0.25)->at(0).second->dependsOnUnderlyingValue());
+    EXPECT_TRUE(effect->sample(0, 0.4)->at(0).second->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 0.5)->at(0).second->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 0.6)->at(0).second->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 0.75)->at(0).second->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 0.8)->at(0).second->dependsOnUnderlyingValue());
+    EXPECT_FALSE(effect->sample(0, 1)->at(0).second->dependsOnUnderlyingValue());
+}
+
+TEST(AnimationKeyframeEffectModel, ToKeyframeEffectModel)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(0);
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
+
+    AnimationEffect* baseEffect = effect.get();
+    EXPECT_TRUE(toKeyframeEffectModel(baseEffect));
+}
+
+} // namespace
+
+namespace WebCore {
+
+class KeyframeEffectModelTest : public ::testing::Test {
+public:
+    typedef KeyframeEffectModel::KeyframeVector KeyframeVector;
+
+    static KeyframeVector normalizedKeyframes(const KeyframeVector& keyframes)
+    {
+        return KeyframeEffectModel::normalizedKeyframes(keyframes);
+    }
+};
+
+TEST_F(KeyframeEffectModelTest, NotLooselySorted)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(4);
+    keyframes[0] = Keyframe::create();
+    keyframes[1] = Keyframe::create();
+    keyframes[1]->setOffset(9);
+    keyframes[2] = Keyframe::create();
+    keyframes[3] = Keyframe::create();
+    keyframes[3]->setOffset(1);
+
+    const KeyframeVector result = normalizedKeyframes(keyframes);
+    EXPECT_EQ(0U, result.size());
+}
+
+TEST_F(KeyframeEffectModelTest, LastOne)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(3);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(-1);
+    keyframes[1] = Keyframe::create();
+    keyframes[2] = Keyframe::create();
+    keyframes[2]->setOffset(2);
+
+    const KeyframeVector result = normalizedKeyframes(keyframes);
+    EXPECT_EQ(1U, result.size());
+    EXPECT_DOUBLE_EQ(1.0, result[0]->offset());
+}
+
+TEST_F(KeyframeEffectModelTest, FirstZero)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(3);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(-1);
+    keyframes[1] = Keyframe::create();
+    keyframes[2] = Keyframe::create();
+    keyframes[2]->setOffset(0.25);
+
+    const KeyframeVector result = normalizedKeyframes(keyframes);
+    EXPECT_EQ(2U, result.size());
+    EXPECT_DOUBLE_EQ(0.0, result[0]->offset());
+    EXPECT_DOUBLE_EQ(0.25, result[1]->offset());
+}
+
+TEST_F(KeyframeEffectModelTest, EvenlyDistributed1)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(5);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0.125);
+    keyframes[1] = Keyframe::create();
+    keyframes[2] = Keyframe::create();
+    keyframes[3] = Keyframe::create();
+    keyframes[4] = Keyframe::create();
+    keyframes[4]->setOffset(0.625);
+
+    const KeyframeVector result = normalizedKeyframes(keyframes);
+    EXPECT_EQ(5U, result.size());
+    EXPECT_DOUBLE_EQ(0.125, result[0]->offset());
+    EXPECT_DOUBLE_EQ(0.25, result[1]->offset());
+    EXPECT_DOUBLE_EQ(0.375, result[2]->offset());
+    EXPECT_DOUBLE_EQ(0.5, result[3]->offset());
+    EXPECT_DOUBLE_EQ(0.625, result[4]->offset());
+}
+
+TEST_F(KeyframeEffectModelTest, EvenlyDistributed2)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(8);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(-0.1);
+    keyframes[1] = Keyframe::create();
+    keyframes[2] = Keyframe::create();
+    keyframes[3] = Keyframe::create();
+    keyframes[4] = Keyframe::create();
+    keyframes[4]->setOffset(0.75);
+    keyframes[5] = Keyframe::create();
+    keyframes[6] = Keyframe::create();
+    keyframes[7] = Keyframe::create();
+    keyframes[7]->setOffset(1.1);
+
+    const KeyframeVector result = normalizedKeyframes(keyframes);
+    EXPECT_EQ(6U, result.size());
+    EXPECT_DOUBLE_EQ(0.0, result[0]->offset());
+    EXPECT_DOUBLE_EQ(0.25, result[1]->offset());
+    EXPECT_DOUBLE_EQ(0.5, result[2]->offset());
+    EXPECT_DOUBLE_EQ(0.75, result[3]->offset());
+    EXPECT_DOUBLE_EQ(0.875, result[4]->offset());
+    EXPECT_DOUBLE_EQ(1.0, result[5]->offset());
+}
+
+TEST_F(KeyframeEffectModelTest, EvenlyDistributed3)
+{
+    KeyframeEffectModel::KeyframeVector keyframes(12);
+    keyframes[0] = Keyframe::create();
+    keyframes[0]->setOffset(0);
+    keyframes[1] = Keyframe::create();
+    keyframes[2] = Keyframe::create();
+    keyframes[3] = Keyframe::create();
+    keyframes[4] = Keyframe::create();
+    keyframes[4]->setOffset(0.5);
+    keyframes[5] = Keyframe::create();
+    keyframes[6] = Keyframe::create();
+    keyframes[7] = Keyframe::create();
+    keyframes[7]->setOffset(0.8);
+    keyframes[8] = Keyframe::create();
+    keyframes[9] = Keyframe::create();
+    keyframes[10] = Keyframe::create();
+    keyframes[11] = Keyframe::create();
+
+    const KeyframeVector result = normalizedKeyframes(keyframes);
+    EXPECT_EQ(12U, result.size());
+    EXPECT_DOUBLE_EQ(0.0, result[0]->offset());
+    EXPECT_DOUBLE_EQ(0.125, result[1]->offset());
+    EXPECT_DOUBLE_EQ(0.25, result[2]->offset());
+    EXPECT_DOUBLE_EQ(0.375, result[3]->offset());
+    EXPECT_DOUBLE_EQ(0.5, result[4]->offset());
+    EXPECT_DOUBLE_EQ(0.6, result[5]->offset());
+    EXPECT_DOUBLE_EQ(0.7, result[6]->offset());
+    EXPECT_DOUBLE_EQ(0.8, result[7]->offset());
+    EXPECT_DOUBLE_EQ(0.85, result[8]->offset());
+    EXPECT_DOUBLE_EQ(0.9, result[9]->offset());
+    EXPECT_DOUBLE_EQ(0.95, result[10]->offset());
+    EXPECT_DOUBLE_EQ(1.0, result[11]->offset());
+}
+
+} // namespace WebCore
diff --git a/Source/core/animation/Player.cpp b/Source/core/animation/Player.cpp
index 63839ae..2b91b40 100644
--- a/Source/core/animation/Player.cpp
+++ b/Source/core/animation/Player.cpp
@@ -28,7 +28,6 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-
 #include "config.h"
 #include "core/animation/Player.h"
 
@@ -37,26 +36,22 @@
 
 namespace WebCore {
 
-namespace {
-
-double effectiveTime(double time) { return isNull(time) ? 0 : time; }
-
-} // namespace
-
 PassRefPtr<Player> Player::create(DocumentTimeline& timeline, TimedItem* content)
 {
     return adoptRef(new Player(timeline, content));
 }
 
 Player::Player(DocumentTimeline& timeline, TimedItem* content)
-    : m_pauseStartTime(nullValue())
-    , m_playbackRate(1)
-    , m_timeDrift(0)
+    : m_playbackRate(1)
     , m_startTime(nullValue())
-    , m_lastUpdateTime(nullValue())
+    , m_holdTime(nullValue())
+    , m_storedTimeLag(0)
     , m_content(content)
-    , m_timeline(timeline)
+    , m_timeline(&timeline)
+    , m_paused(false)
+    , m_held(false)
     , m_isPausedForTesting(false)
+    , m_needsUpdate(false)
 {
     if (m_content)
         m_content->attach(this);
@@ -66,21 +61,178 @@
 {
     if (m_content)
         m_content->detach();
+    if (m_timeline)
+        m_timeline->playerDestroyed(this);
 }
 
-void Player::setStartTime(double startTime)
+double Player::sourceEnd() const
 {
-    ASSERT(!isNull(startTime));
-    ASSERT(!hasStartTime());
-    m_startTime = startTime;
-    update();
+    return m_content ? m_content->endTime() : 0;
 }
 
-double Player::currentTimeBeforeDrift() const
+bool Player::limited(double currentTime) const
 {
-    if (isNull(m_startTime))
+    return (m_playbackRate < 0 && currentTime <= 0) || (m_playbackRate > 0 && currentTime >= sourceEnd());
+}
+
+double Player::currentTimeWithoutLag() const
+{
+    if (isNull(m_startTime) || !m_timeline)
         return 0;
-    return (effectiveTime(m_timeline.currentTime()) - startTime()) * m_playbackRate;
+    double timelineTime = m_timeline->currentTime();
+    if (isNull(timelineTime))
+        timelineTime = 0;
+    return (timelineTime - m_startTime) * m_playbackRate;
+}
+
+double Player::currentTimeWithLag() const
+{
+    ASSERT(!m_held);
+    double time = currentTimeWithoutLag();
+    return std::isinf(time) ? time : time - m_storedTimeLag;
+}
+
+void Player::updateTimingState(double newCurrentTime)
+{
+    ASSERT(!isNull(newCurrentTime));
+    m_held = m_paused || !m_playbackRate || limited(newCurrentTime);
+    if (m_held) {
+        m_holdTime = newCurrentTime;
+        m_storedTimeLag = nullValue();
+    } else {
+        m_holdTime = nullValue();
+        m_storedTimeLag = currentTimeWithoutLag() - newCurrentTime;
+    }
+    setNeedsUpdate();
+}
+
+void Player::updateCurrentTimingState()
+{
+    if (m_held) {
+        updateTimingState(m_holdTime);
+    } else {
+        updateTimingState(currentTimeWithLag());
+        if (m_held && limited(m_holdTime))
+            m_holdTime = m_playbackRate < 0 ? 0 : sourceEnd();
+    }
+}
+
+double Player::currentTime()
+{
+    updateCurrentTimingState();
+    if (m_held)
+        return m_holdTime;
+    return currentTimeWithLag();
+}
+
+void Player::setCurrentTime(double newCurrentTime)
+{
+    if (!std::isfinite(newCurrentTime))
+        return;
+    updateTimingState(newCurrentTime);
+}
+
+void Player::setStartTime(double newStartTime)
+{
+    if (!std::isfinite(newStartTime))
+        return;
+    updateCurrentTimingState(); // Update the value of held
+    m_startTime = newStartTime;
+    if (!m_held)
+        updateCurrentTimingState();
+}
+
+void Player::setSource(TimedItem* newSource)
+{
+    if (m_content == newSource)
+        return;
+    double storedCurrentTime = currentTime();
+    if (m_content)
+        m_content->detach();
+    if (newSource) {
+        // FIXME: This logic needs to be updated once groups are implemented
+        if (newSource->player())
+            newSource->detach();
+        newSource->attach(this);
+    }
+    m_content = newSource;
+    updateTimingState(storedCurrentTime);
+}
+
+void Player::pause()
+{
+    if (m_paused)
+        return;
+    m_paused = true;
+    updateTimingState(currentTime());
+    // FIXME: resume compositor animation rather than pull back to main-thread
+    cancelAnimationOnCompositor();
+}
+
+void Player::unpause()
+{
+    if (!m_paused)
+        return;
+    m_paused = false;
+    updateTimingState(currentTime());
+}
+
+void Player::play()
+{
+    unpause();
+    if (!m_content)
+        return;
+    double currentTime = this->currentTime();
+    if (m_playbackRate > 0 && (currentTime < 0 || currentTime >= sourceEnd()))
+        setCurrentTime(0);
+    else if (m_playbackRate < 0 && (currentTime <= 0 || currentTime > sourceEnd()))
+        setCurrentTime(sourceEnd());
+}
+
+void Player::reverse()
+{
+    if (!m_playbackRate)
+        return;
+    if (m_content) {
+        if (m_playbackRate > 0 && currentTime() > sourceEnd())
+            setCurrentTime(sourceEnd());
+        else if (m_playbackRate < 0 && currentTime() < 0)
+            setCurrentTime(0);
+    }
+    setPlaybackRate(-m_playbackRate);
+    unpause();
+}
+
+void Player::finish(ExceptionState& exceptionState)
+{
+    if (!m_playbackRate)
+        return;
+    if (m_playbackRate < 0) {
+        setCurrentTime(0);
+    } else {
+        if (sourceEnd() == std::numeric_limits<double>::infinity()) {
+            exceptionState.throwDOMException(InvalidStateError, "Player has source content whose end time is infinity.");
+            return;
+        }
+        setCurrentTime(sourceEnd());
+    }
+    ASSERT(finished());
+}
+
+void Player::setPlaybackRate(double playbackRate)
+{
+    if (!std::isfinite(playbackRate))
+        return;
+    double storedCurrentTime = currentTime();
+    m_playbackRate = playbackRate;
+    updateTimingState(storedCurrentTime);
+}
+
+void Player::setNeedsUpdate()
+{
+    m_needsUpdate = true;
+    if (m_timeline)
+        m_timeline->setHasPlayerNeedingUpdate();
 }
 
 bool Player::maybeStartAnimationOnCompositor()
@@ -88,7 +240,7 @@
     // FIXME: Support starting compositor animations that have a fixed
     // start time.
     ASSERT(!hasStartTime());
-    if (!m_content || !m_content->isAnimation())
+    if (!m_content || !m_content->isAnimation() || paused())
         return false;
 
     return toAnimation(m_content.get())->maybeStartAnimationOnCompositor();
@@ -107,46 +259,39 @@
         toAnimation(m_content.get())->cancelAnimationOnCompositor();
 }
 
-double Player::pausedTimeDrift() const
+bool Player::update(bool* didTriggerStyleRecalc)
 {
-    ASSERT(pausedInternal());
-    return currentTimeBeforeDrift() - m_pauseStartTime;
-}
+    if (!m_timeline)
+        return false;
 
-double Player::timeDrift() const
-{
-    return pausedInternal() ? pausedTimeDrift() : m_timeDrift;
-}
+    double inheritedTime = isNull(m_timeline->currentTime()) ? nullValue() : currentTime();
+    m_needsUpdate = false;
 
-double Player::currentTime() const
-{
-    return currentTimeBeforeDrift() - timeDrift();
-}
-
-bool Player::update(double* timeToEffectChange, bool* didTriggerStyleRecalc)
-{
     if (!m_content) {
-        if (timeToEffectChange)
-            *timeToEffectChange = std::numeric_limits<double>::infinity();
         if (didTriggerStyleRecalc)
             *didTriggerStyleRecalc = false;
         return false;
     }
 
-    double newTime = isNull(m_timeline.currentTime()) ? nullValue() : currentTime();
-    bool didTriggerStyleRecalcLocal = false;
-    // FIXME: Further checks will be required once the animation tree can be mutated.
-    if (newTime != m_lastUpdateTime) {
-        didTriggerStyleRecalcLocal = m_content->updateInheritedTime(newTime);
-        m_lastUpdateTime = newTime;
-    }
-    if (timeToEffectChange)
-        *timeToEffectChange = m_content->timeToEffectChange();
+    bool didTriggerStyleRecalcLocal = m_content->updateInheritedTime(inheritedTime);
+
     if (didTriggerStyleRecalc)
         *didTriggerStyleRecalc = didTriggerStyleRecalcLocal;
+
+    ASSERT(!m_needsUpdate);
     return m_content->isCurrent() || m_content->isInEffect();
 }
 
+double Player::timeToEffectChange()
+{
+    ASSERT(!m_needsUpdate);
+    if (!m_content || !m_playbackRate)
+        return std::numeric_limits<double>::infinity();
+    if (m_playbackRate > 0)
+        return m_content->timeToForwardsEffectChange() / m_playbackRate;
+    return m_content->timeToReverseEffectChange() / abs(m_playbackRate);
+}
+
 void Player::cancel()
 {
     if (!m_content)
@@ -157,53 +302,14 @@
     m_content = 0;
 }
 
-void Player::setCurrentTime(double seekTime)
-{
-    if (pausedInternal())
-        m_pauseStartTime = seekTime;
-    else
-        m_timeDrift = currentTimeBeforeDrift() - seekTime;
-
-    if (m_isPausedForTesting && hasActiveAnimationsOnCompositor())
-        toAnimation(m_content.get())->pauseAnimationForTestingOnCompositor(currentTime());
-    update();
-}
-
-void Player::pauseForTesting()
+void Player::pauseForTesting(double pauseTime)
 {
     RELEASE_ASSERT(!paused());
+    updateTimingState(pauseTime);
     if (!m_isPausedForTesting && hasActiveAnimationsOnCompositor())
         toAnimation(m_content.get())->pauseAnimationForTestingOnCompositor(currentTime());
     m_isPausedForTesting = true;
-    setPausedImpl(true);
-}
-
-void Player::setPaused(bool newValue)
-{
-    ASSERT(!m_isPausedForTesting);
-    setPausedImpl(newValue);
-}
-
-void Player::setPausedImpl(bool newValue)
-{
-    if (pausedInternal() == newValue)
-        return;
-
-    if (newValue) {
-        // FIXME: resume compositor animation rather than pull back to main-thread
-        cancelAnimationOnCompositor();
-        m_pauseStartTime = currentTime();
-    } else {
-        m_timeDrift = pausedTimeDrift();
-        m_pauseStartTime = nullValue();
-    }
-}
-
-void Player::setPlaybackRate(double newRate)
-{
-    double previousTime = currentTime();
-    m_playbackRate = newRate;
-    setCurrentTime(previousTime);
+    pause();
 }
 
 } // namespace
diff --git a/Source/core/animation/Player.h b/Source/core/animation/Player.h
index 54ba57b..7015c98 100644
--- a/Source/core/animation/Player.h
+++ b/Source/core/animation/Player.h
@@ -37,6 +37,7 @@
 namespace WebCore {
 
 class DocumentTimeline;
+class ExceptionState;
 
 class Player FINAL : public RefCounted<Player> {
 
@@ -45,33 +46,51 @@
     static PassRefPtr<Player> create(DocumentTimeline&, TimedItem*);
 
     // Returns whether this player is still current or in effect.
+    bool update(bool* didTriggerStyleRecalc = 0);
+
     // timeToEffectChange returns:
     //  infinity  - if this player is no longer in effect
     //  0         - if this player requires an update on the next frame
     //  n         - if this player requires an update after 'n' units of time
-    bool update(double* timeToEffectChange = 0, bool* didTriggerStyleRecalc = 0);
+    double timeToEffectChange();
+
     void cancel();
 
-    double currentTime() const;
-    void setCurrentTime(double);
+    double currentTime();
+    void setCurrentTime(double newCurrentTime);
 
-    bool paused() const { return !m_isPausedForTesting && pausedInternal(); }
-    void setPaused(bool);
+    bool paused() const { return m_paused && !m_isPausedForTesting; }
+    void pause();
+    void play();
+    void reverse();
+    void finish(ExceptionState&);
+    bool finished() { return limited(currentTime()); }
 
     double playbackRate() const { return m_playbackRate; }
     void setPlaybackRate(double);
-    double timeDrift() const;
-    DocumentTimeline& timeline() { return m_timeline; }
+    const DocumentTimeline* timeline() const { return m_timeline; }
+    DocumentTimeline* timeline() { return m_timeline; }
+
+    void timelineDestroyed() { m_timeline = 0; }
 
     bool hasStartTime() const { return !isNull(m_startTime); }
     double startTime() const { return m_startTime; }
     void setStartTime(double);
 
     TimedItem* source() { return m_content.get(); }
+    TimedItem* source(bool& isNull) { isNull = !m_content; return m_content.get(); }
+    void setSource(TimedItem*);
+
+    double timeLag() { return currentTimeWithoutLag() - currentTime(); }
 
     // Pausing via this method is not reflected in the value returned by
-    // paused() and must never overlap with pausing via setPaused().
-    void pauseForTesting();
+    // paused() and must never overlap with pausing via pause().
+    void pauseForTesting(double pauseTime);
+    // This should only be used for CSS
+    void unpause();
+
+    void setNeedsUpdate();
+    bool needsUpdate() { return m_needsUpdate; }
 
     bool maybeStartAnimationOnCompositor();
     void cancelAnimationOnCompositor();
@@ -79,23 +98,28 @@
 
 private:
     Player(DocumentTimeline&, TimedItem*);
-    inline double pausedTimeDrift() const;
-    inline double currentTimeBeforeDrift() const;
+    double sourceEnd() const;
+    bool limited(double currentTime) const;
+    double currentTimeWithoutLag() const;
+    double currentTimeWithLag() const;
+    void updateTimingState(double newCurrentTime);
+    void updateCurrentTimingState();
 
-
-    void setPausedImpl(bool);
-    // Reflects all pausing, including via pauseForTesting().
-    bool pausedInternal() const { return !isNull(m_pauseStartTime); }
-
-    double m_pauseStartTime;
     double m_playbackRate;
-    double m_timeDrift;
     double m_startTime;
-    double m_lastUpdateTime;
+    double m_holdTime;
+    double m_storedTimeLag;
 
     RefPtr<TimedItem> m_content;
-    DocumentTimeline& m_timeline;
+    // FIXME: We should keep the timeline alive and have this as non-null
+    // but this is tricky to do without Oilpan
+    DocumentTimeline* m_timeline;
+    // Reflects all pausing, including via pauseForTesting().
+    bool m_paused;
+    bool m_held;
     bool m_isPausedForTesting;
+
+    bool m_needsUpdate;
 };
 
 } // namespace
diff --git a/Source/core/html/ime/Composition.idl b/Source/core/animation/Player.idl
similarity index 76%
copy from Source/core/html/ime/Composition.idl
copy to Source/core/animation/Player.idl
index 494d2a0..1243c39 100644
--- a/Source/core/html/ime/Composition.idl
+++ b/Source/core/animation/Player.idl
@@ -28,12 +28,19 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-// http://www.w3.org/TR/ime-api/
 [
-    NoInterfaceObject
-] interface Composition {
-    readonly attribute DOMString text;
-    readonly attribute long selectionStart;
-    readonly attribute long selectionEnd;
-    sequence<unsigned long> getSegments();
+    RuntimeEnabled=WebAnimationsAPI,
+] interface Player {
+             attribute TimedItem? source;
+             attribute double     startTime;
+             attribute double     currentTime;
+    readonly attribute double     timeLag;
+             attribute double     playbackRate;
+    readonly attribute boolean    paused;
+    readonly attribute boolean    finished;
+    void cancel();
+    [RaisesException] void finish();
+    void play();
+    void pause();
+    void reverse();
 };
diff --git a/Source/core/animation/PlayerTest.cpp b/Source/core/animation/PlayerTest.cpp
index ee79f37..837d347 100644
--- a/Source/core/animation/PlayerTest.cpp
+++ b/Source/core/animation/PlayerTest.cpp
@@ -48,274 +48,562 @@
 protected:
     virtual void SetUp()
     {
+        setUpWithoutStartingTimeline();
+        startTimeline();
+    }
+
+    void setUpWithoutStartingTimeline()
+    {
         document = Document::create();
         document->animationClock().resetTimeForTesting();
         timeline = DocumentTimeline::create(document.get());
-        player = Player::create(*timeline, 0);
+        player = timeline->createPlayer(0);
         player->setStartTime(0);
-        timeline->setZeroTime(0);
+        player->setSource(makeAnimation().get());
     }
 
-    bool updateTimeline(double time, double* timeToEffectChange = 0)
+    void startTimeline()
+    {
+        timeline->setZeroTime(0);
+        updateTimeline(0);
+    }
+
+    PassRefPtr<Animation> makeAnimation(double duration = 30, double playbackRate = 1)
+    {
+        Timing timing;
+        timing.iterationDuration = duration;
+        timing.playbackRate = playbackRate;
+        return Animation::create(0, 0, timing);
+    }
+
+    bool updateTimeline(double time)
     {
         document->animationClock().updateTime(time);
         // The timeline does not know about our player, so we have to explicitly call update().
-        return player->update(timeToEffectChange);
+        return player->update();
     }
 
     RefPtr<Document> document;
     RefPtr<DocumentTimeline> timeline;
     RefPtr<Player> player;
+    TrackExceptionState exceptionState;
 };
 
 TEST_F(AnimationPlayerTest, InitialState)
 {
+    setUpWithoutStartingTimeline();
+    player = timeline->createPlayer(0);
+    EXPECT_TRUE(isNull(timeline->currentTime()));
+    EXPECT_EQ(0, player->currentTime());
+    EXPECT_FALSE(player->paused());
+    EXPECT_EQ(1, player->playbackRate());
+    EXPECT_EQ(0, player->timeLag());
+    EXPECT_FALSE(player->hasStartTime());
+    EXPECT_TRUE(isNull(player->startTime()));
+
+    startTimeline();
+    player->setStartTime(0);
     EXPECT_EQ(0, timeline->currentTime());
     EXPECT_EQ(0, player->currentTime());
     EXPECT_FALSE(player->paused());
     EXPECT_EQ(1, player->playbackRate());
     EXPECT_EQ(0, player->startTime());
-    EXPECT_EQ(0, player->timeDrift());
+    EXPECT_EQ(0, player->timeLag());
+    EXPECT_TRUE(player->hasStartTime());
 }
 
-TEST_F(AnimationPlayerTest, PauseUnpause)
-{
-    updateTimeline(200);
-    player->setPaused(true);
-    EXPECT_TRUE(player->paused());
-    EXPECT_EQ(200, player->currentTime());
-    EXPECT_EQ(0, player->timeDrift());
-
-    updateTimeline(400);
-    player->setPaused(false);
-    EXPECT_FALSE(player->paused());
-    EXPECT_EQ(200, player->currentTime());
-    EXPECT_EQ(200, player->timeDrift());
-
-    updateTimeline(600);
-    EXPECT_EQ(400, player->currentTime());
-    EXPECT_EQ(200, player->timeDrift());
-}
-
-TEST_F(AnimationPlayerTest, PauseBeforeTimelineStarted)
-{
-    player->setPaused(true);
-    EXPECT_TRUE(player->paused());
-    EXPECT_EQ(0, player->currentTime());
-    EXPECT_EQ(0, player->timeDrift());
-
-    player->setPaused(false);
-    EXPECT_FALSE(player->paused());
-    EXPECT_EQ(0, player->currentTime());
-    EXPECT_EQ(0, player->timeDrift());
-
-    player->setPaused(true);
-    updateTimeline(100);
-    EXPECT_TRUE(player->paused());
-    EXPECT_EQ(0, player->currentTime());
-    EXPECT_EQ(100, player->timeDrift());
-
-    player->setPaused(false);
-    EXPECT_EQ(0, player->currentTime());
-    EXPECT_EQ(100, player->timeDrift());
-}
-
-TEST_F(AnimationPlayerTest, PauseBeforeStartTimeSet)
-{
-    player = Player::create(*timeline, 0);
-    updateTimeline(100);
-    EXPECT_EQ(0, player->currentTime());
-
-    player->setPaused(true);
-    updateTimeline(200);
-    EXPECT_EQ(0, player->currentTime());
-
-    player->setStartTime(150);
-    EXPECT_EQ(0, player->currentTime());
-
-    player->setPaused(false);
-    EXPECT_EQ(0, player->currentTime());
-
-    updateTimeline(300);
-    EXPECT_EQ(100, player->currentTime());
-}
 
 TEST_F(AnimationPlayerTest, SetCurrentTime)
 {
-    updateTimeline(0);
-    player->setCurrentTime(250);
-    EXPECT_EQ(250, player->currentTime());
-    EXPECT_EQ(-250, player->timeDrift());
+    player->setCurrentTime(10);
+    EXPECT_EQ(10, player->currentTime());
+    updateTimeline(10);
+    EXPECT_EQ(20, player->currentTime());
 }
 
-TEST_F(AnimationPlayerTest, SetStartTime)
+TEST_F(AnimationPlayerTest, SetCurrentTimeNegative)
 {
-    updateTimeline(0);
-    player = Player::create(*timeline, 0);
-    EXPECT_FALSE(player->hasStartTime());
-    EXPECT_TRUE(isNull(player->startTime()));
-    EXPECT_EQ(0, player->currentTime());
+    player->setCurrentTime(-10);
+    EXPECT_EQ(-10, player->currentTime());
+    updateTimeline(20);
+    EXPECT_EQ(10, player->currentTime());
 
-    updateTimeline(100);
-    player->setStartTime(50);
-    EXPECT_TRUE(player->hasStartTime());
-    EXPECT_EQ(50, player->startTime());
+    player->setPlaybackRate(-2);
+    player->setCurrentTime(-10);
+    EXPECT_EQ(-10, player->currentTime());
+    updateTimeline(40);
+    EXPECT_EQ(-10, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetCurrentTimePastContentEnd)
+{
+    player->setCurrentTime(50);
+    EXPECT_EQ(50, player->currentTime());
+    updateTimeline(20);
     EXPECT_EQ(50, player->currentTime());
 
-    updateTimeline(200);
-    EXPECT_EQ(150, player->currentTime());
+    player->setPlaybackRate(-2);
+    player->setCurrentTime(50);
+    EXPECT_EQ(50, player->currentTime());
+    updateTimeline(40);
+    EXPECT_EQ(10, player->currentTime());
 }
 
-
 TEST_F(AnimationPlayerTest, SetCurrentTimeBeforeTimelineStarted)
 {
+    setUpWithoutStartingTimeline();
+    player->setCurrentTime(5);
+    EXPECT_EQ(5, player->currentTime());
+    startTimeline();
+    updateTimeline(10);
+    EXPECT_EQ(15, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetCurrentTimePastContentEndBeforeTimelineStarted)
+{
+    setUpWithoutStartingTimeline();
     player->setCurrentTime(250);
     EXPECT_EQ(250, player->currentTime());
-    EXPECT_EQ(-250, player->timeDrift());
-
-    updateTimeline(0);
+    startTimeline();
+    updateTimeline(10);
     EXPECT_EQ(250, player->currentTime());
 }
 
-TEST_F(AnimationPlayerTest, SetCurrentTimeBeforeStartTimeSet)
-{
-    updateTimeline(0);
-    player = Player::create(*timeline, 0);
-
-    player->setCurrentTime(250);
-    EXPECT_EQ(250, player->currentTime());
-    EXPECT_EQ(-250, player->timeDrift());
-
-    updateTimeline(100);
-    player->setStartTime(50);
-    EXPECT_EQ(300, player->currentTime());
-}
-
-TEST_F(AnimationPlayerTest, SetPlaybackRate)
-{
-    updateTimeline(0);
-    player->setPlaybackRate(2);
-    EXPECT_EQ(2, player->playbackRate());
-    EXPECT_EQ(0, player->currentTime());
-    EXPECT_EQ(0, player->timeDrift());
-
-    updateTimeline(100);
-    EXPECT_EQ(200, player->currentTime());
-    EXPECT_EQ(0, player->timeDrift());
-}
-
-TEST_F(AnimationPlayerTest, SetPlaybackRateBeforeTimelineStarted)
-{
-    player->setPlaybackRate(2);
-    EXPECT_EQ(0, player->currentTime());
-    EXPECT_EQ(0, player->timeDrift());
-
-    updateTimeline(100);
-    EXPECT_EQ(200, player->currentTime());
-    EXPECT_EQ(0, player->timeDrift());
-}
-
-TEST_F(AnimationPlayerTest, SetPlaybackRateWhilePaused)
-{
-    updateTimeline(100);
-    player->setPaused(true);
-    player->setPlaybackRate(2);
-    EXPECT_EQ(100, player->currentTime());
-    EXPECT_EQ(100, player->timeDrift());
-
-    updateTimeline(200);
-    player->setPaused(false);
-    EXPECT_EQ(100, player->currentTime());
-    EXPECT_EQ(300, player->timeDrift());
-
-    updateTimeline(250);
-    EXPECT_EQ(200, player->currentTime());
-    EXPECT_EQ(300, player->timeDrift());
-}
-
-TEST_F(AnimationPlayerTest, SetPlaybackRateNaN)
-{
-    updateTimeline(0);
-    player->setPlaybackRate(nullValue());
-    EXPECT_TRUE(isNull(player->playbackRate()));
-    EXPECT_TRUE(isNull(player->currentTime()));
-    EXPECT_TRUE(isNull(player->timeDrift()));
-
-    updateTimeline(100);
-    EXPECT_TRUE(isNull(player->currentTime()));
-    EXPECT_TRUE(isNull(player->timeDrift()));
-}
-
-TEST_F(AnimationPlayerTest, SetPlaybackRateInfinity)
-{
-    updateTimeline(0);
-    player->setPlaybackRate(std::numeric_limits<double>::infinity());
-    EXPECT_EQ(std::numeric_limits<double>::infinity(), player->playbackRate());
-    EXPECT_TRUE(isNull(player->currentTime()));
-    EXPECT_TRUE(isNull(player->timeDrift()));
-
-    updateTimeline(100);
-    EXPECT_TRUE(isNull(player->currentTime()));
-    EXPECT_TRUE(isNull(player->timeDrift()));
-}
-
-TEST_F(AnimationPlayerTest, SetPlaybackRateMax)
-{
-    updateTimeline(0);
-    player->setPlaybackRate(std::numeric_limits<double>::max());
-    EXPECT_EQ(std::numeric_limits<double>::max(), player->playbackRate());
-    EXPECT_EQ(0, player->currentTime());
-    EXPECT_EQ(0, player->timeDrift());
-
-    updateTimeline(100);
-    EXPECT_EQ(std::numeric_limits<double>::infinity(), player->currentTime());
-}
-
-TEST_F(AnimationPlayerTest, SetCurrentTimeNan)
-{
-    updateTimeline(0);
-    player->setCurrentTime(nullValue());
-    EXPECT_TRUE(isNull(player->currentTime()));
-    EXPECT_TRUE(isNull(player->timeDrift()));
-
-    updateTimeline(100);
-    EXPECT_TRUE(isNull(player->currentTime()));
-    EXPECT_TRUE(isNull(player->timeDrift()));
-}
-
-TEST_F(AnimationPlayerTest, SetCurrentTimeInfinity)
-{
-    updateTimeline(0);
-    player->setCurrentTime(std::numeric_limits<double>::infinity());
-    EXPECT_EQ(std::numeric_limits<double>::infinity(), player->currentTime());
-    EXPECT_EQ(-std::numeric_limits<double>::infinity(), player->timeDrift());
-
-    updateTimeline(100);
-    EXPECT_EQ(std::numeric_limits<double>::infinity(), player->currentTime());
-    EXPECT_EQ(-std::numeric_limits<double>::infinity(), player->timeDrift());
-}
-
 TEST_F(AnimationPlayerTest, SetCurrentTimeMax)
 {
-    updateTimeline(0);
     player->setCurrentTime(std::numeric_limits<double>::max());
     EXPECT_EQ(std::numeric_limits<double>::max(), player->currentTime());
-    EXPECT_EQ(-std::numeric_limits<double>::max(), player->timeDrift());
-
     updateTimeline(100);
     EXPECT_EQ(std::numeric_limits<double>::max(), player->currentTime());
-    EXPECT_EQ(-std::numeric_limits<double>::max(), player->timeDrift());
 }
 
+TEST_F(AnimationPlayerTest, SetCurrentTimeUnrestrictedDouble)
+{
+    updateTimeline(10);
+    player->setCurrentTime(nullValue());
+    EXPECT_EQ(10, player->currentTime());
+    player->setCurrentTime(std::numeric_limits<double>::infinity());
+    EXPECT_EQ(10, player->currentTime());
+    player->setCurrentTime(-std::numeric_limits<double>::infinity());
+    EXPECT_EQ(10, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetCurrentTimeBeforeStartTimeSet)
+{
+    player = timeline->createPlayer(0);
+    player->setSource(makeAnimation().get());
+    player->setCurrentTime(20);
+    EXPECT_EQ(20, player->currentTime());
+    updateTimeline(5);
+    EXPECT_EQ(20, player->currentTime());
+    player->setStartTime(10);
+    EXPECT_EQ(15, player->currentTime());
+}
+
+
+TEST_F(AnimationPlayerTest, TimeLag)
+{
+    player->setCurrentTime(10);
+    EXPECT_EQ(-10, player->timeLag());
+    updateTimeline(10);
+    EXPECT_EQ(-10, player->timeLag());
+    player->setCurrentTime(40);
+    EXPECT_EQ(-30, player->timeLag());
+    updateTimeline(20);
+    EXPECT_EQ(-20, player->timeLag());
+}
+
+
+TEST_F(AnimationPlayerTest, SetStartTime)
+{
+    updateTimeline(20);
+    EXPECT_EQ(0, player->startTime());
+    EXPECT_EQ(20, player->currentTime());
+    player->setStartTime(10);
+    EXPECT_EQ(10, player->startTime());
+    EXPECT_EQ(10, player->currentTime());
+    updateTimeline(30);
+    EXPECT_EQ(10, player->startTime());
+    EXPECT_EQ(20, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetStartTimeLimitsPlayer)
+{
+    player->setStartTime(-50);
+    EXPECT_EQ(30, player->currentTime());
+    player->setPlaybackRate(-1);
+    player->setStartTime(-100);
+    EXPECT_EQ(0, player->currentTime());
+    EXPECT_TRUE(player->finished());
+}
+
+TEST_F(AnimationPlayerTest, SetStartTimeOnLimitedPlayer)
+{
+    updateTimeline(30);
+    player->setStartTime(-10);
+    EXPECT_EQ(30, player->currentTime());
+    player->setCurrentTime(50);
+    player->setStartTime(-40);
+    EXPECT_EQ(50, player->currentTime());
+    EXPECT_TRUE(player->finished());
+}
+
+TEST_F(AnimationPlayerTest, SetStartTimeWhilePaused)
+{
+    updateTimeline(10);
+    player->pause();
+    player->setStartTime(-40);
+    EXPECT_EQ(10, player->currentTime());
+    updateTimeline(50);
+    player->setStartTime(60);
+    EXPECT_EQ(10, player->currentTime());
+}
+
+
+TEST_F(AnimationPlayerTest, PausePlay)
+{
+    updateTimeline(10);
+    player->pause();
+    EXPECT_TRUE(player->paused());
+    EXPECT_EQ(10, player->currentTime());
+    updateTimeline(20);
+    player->play();
+    EXPECT_FALSE(player->paused());
+    EXPECT_EQ(10, player->currentTime());
+    updateTimeline(30);
+    EXPECT_EQ(20, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, PauseBeforeTimelineStarted)
+{
+    setUpWithoutStartingTimeline();
+    player->pause();
+    EXPECT_TRUE(player->paused());
+    player->play();
+    EXPECT_FALSE(player->paused());
+
+    player->pause();
+    startTimeline();
+    updateTimeline(100);
+    EXPECT_TRUE(player->paused());
+    EXPECT_EQ(0, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, PauseBeforeStartTimeSet)
+{
+    player = timeline->createPlayer(0);
+    player->setSource(makeAnimation().get());
+    updateTimeline(100);
+    player->pause();
+    updateTimeline(200);
+    EXPECT_EQ(0, player->currentTime());
+
+    player->setStartTime(150);
+    player->play();
+    EXPECT_EQ(0, player->currentTime());
+    updateTimeline(220);
+    EXPECT_EQ(20, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, PlayRewindsToStart)
+{
+    player->setCurrentTime(30);
+    player->play();
+    EXPECT_EQ(0, player->currentTime());
+
+    player->setCurrentTime(40);
+    player->play();
+    EXPECT_EQ(0, player->currentTime());
+
+    player->setCurrentTime(-10);
+    player->play();
+    EXPECT_EQ(0, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, PlayRewindsToEnd)
+{
+    player->setPlaybackRate(-1);
+    player->play();
+    EXPECT_EQ(30, player->currentTime());
+
+    player->setCurrentTime(40);
+    player->play();
+    EXPECT_EQ(30, player->currentTime());
+
+    player->setCurrentTime(-10);
+    player->play();
+    EXPECT_EQ(30, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, PlayWithPlaybackRateZeroDoesNotSeek)
+{
+    player->setPlaybackRate(0);
+    player->play();
+    EXPECT_EQ(0, player->currentTime());
+
+    player->setCurrentTime(40);
+    player->play();
+    EXPECT_EQ(40, player->currentTime());
+
+    player->setCurrentTime(-10);
+    player->play();
+    EXPECT_EQ(-10, player->currentTime());
+}
+
+
+TEST_F(AnimationPlayerTest, Reverse)
+{
+    player->setCurrentTime(10);
+    player->pause();
+    player->reverse();
+    EXPECT_FALSE(player->paused());
+    EXPECT_EQ(-1, player->playbackRate());
+    EXPECT_EQ(10, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, ReverseDoesNothingWithPlaybackRateZero)
+{
+    player->setCurrentTime(10);
+    player->setPlaybackRate(0);
+    player->pause();
+    player->reverse();
+    EXPECT_TRUE(player->paused());
+    EXPECT_EQ(0, player->playbackRate());
+    EXPECT_EQ(10, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, ReverseDoesNotSeekWithNoSource)
+{
+    player->setSource(0);
+    player->setCurrentTime(10);
+    player->reverse();
+    EXPECT_EQ(10, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, ReverseSeeksToStart)
+{
+    player->setCurrentTime(-10);
+    player->setPlaybackRate(-1);
+    player->reverse();
+    EXPECT_EQ(0, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, ReverseSeeksToEnd)
+{
+    player->setCurrentTime(40);
+    player->reverse();
+    EXPECT_EQ(30, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, ReverseLimitsPlayer)
+{
+    player->setCurrentTime(40);
+    player->setPlaybackRate(-1);
+    player->reverse();
+    EXPECT_TRUE(player->finished());
+    EXPECT_EQ(40, player->currentTime());
+
+    player->setCurrentTime(-10);
+    player->reverse();
+    EXPECT_TRUE(player->finished());
+    EXPECT_EQ(-10, player->currentTime());
+}
+
+
+TEST_F(AnimationPlayerTest, Finish)
+{
+    player->finish(exceptionState);
+    EXPECT_EQ(30, player->currentTime());
+    EXPECT_TRUE(player->finished());
+
+    player->setPlaybackRate(-1);
+    player->finish(exceptionState);
+    EXPECT_EQ(0, player->currentTime());
+    EXPECT_TRUE(player->finished());
+
+    EXPECT_FALSE(exceptionState.hadException());
+}
+
+TEST_F(AnimationPlayerTest, FinishAfterSourceEnd)
+{
+    player->setCurrentTime(40);
+    player->finish(exceptionState);
+    EXPECT_EQ(30, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, FinishBeforeStart)
+{
+    player->setCurrentTime(-10);
+    player->setPlaybackRate(-1);
+    player->finish(exceptionState);
+    EXPECT_EQ(0, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, FinishDoesNothingWithPlaybackRateZero)
+{
+    player->setCurrentTime(10);
+    player->setPlaybackRate(0);
+    player->finish(exceptionState);
+    EXPECT_EQ(10, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, FinishRaisesException)
+{
+    Timing timing;
+    timing.iterationDuration = 1;
+    timing.iterationCount = std::numeric_limits<double>::infinity();
+    player->setSource(Animation::create(0, 0, timing).get());
+    player->setCurrentTime(10);
+
+    player->finish(exceptionState);
+    EXPECT_EQ(10, player->currentTime());
+    EXPECT_TRUE(exceptionState.hadException());
+    EXPECT_EQ(InvalidStateError, exceptionState.code());
+}
+
+
+TEST_F(AnimationPlayerTest, LimitingAtSourceEnd)
+{
+    updateTimeline(30);
+    EXPECT_EQ(30, player->currentTime());
+    EXPECT_TRUE(player->finished());
+    updateTimeline(40);
+    EXPECT_EQ(30, player->currentTime());
+    EXPECT_FALSE(player->paused());
+}
+
+TEST_F(AnimationPlayerTest, LimitingAtStart)
+{
+    updateTimeline(30);
+    player->setPlaybackRate(-2);
+    updateTimeline(45);
+    EXPECT_EQ(0, player->currentTime());
+    EXPECT_TRUE(player->finished());
+    updateTimeline(60);
+    EXPECT_EQ(0, player->currentTime());
+    EXPECT_FALSE(player->paused());
+}
+
+TEST_F(AnimationPlayerTest, LimitingWithNoSource)
+{
+    player->setSource(0);
+    EXPECT_TRUE(player->finished());
+    updateTimeline(30);
+    EXPECT_EQ(0, player->currentTime());
+}
+
+
+TEST_F(AnimationPlayerTest, SetPlaybackRate)
+{
+    player->setPlaybackRate(2);
+    EXPECT_EQ(2, player->playbackRate());
+    EXPECT_EQ(0, player->currentTime());
+    updateTimeline(10);
+    EXPECT_EQ(20, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetPlaybackRateBeforeTimelineStarted)
+{
+    setUpWithoutStartingTimeline();
+    player->setPlaybackRate(2);
+    EXPECT_EQ(2, player->playbackRate());
+    EXPECT_EQ(0, player->currentTime());
+    startTimeline();
+    updateTimeline(10);
+    EXPECT_EQ(20, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetPlaybackRateWhilePaused)
+{
+    updateTimeline(10);
+    player->pause();
+    player->setPlaybackRate(2);
+    updateTimeline(20);
+    player->play();
+    EXPECT_EQ(10, player->currentTime());
+    updateTimeline(25);
+    EXPECT_EQ(20, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetPlaybackRateWhileLimited)
+{
+    updateTimeline(40);
+    EXPECT_EQ(30, player->currentTime());
+    player->setPlaybackRate(2);
+    updateTimeline(50);
+    EXPECT_EQ(30, player->currentTime());
+    player->setPlaybackRate(-2);
+    EXPECT_FALSE(player->finished());
+    updateTimeline(60);
+    EXPECT_EQ(10, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetPlaybackRateZero)
+{
+    updateTimeline(10);
+    player->setPlaybackRate(0);
+    EXPECT_EQ(10, player->currentTime());
+    updateTimeline(20);
+    EXPECT_EQ(10, player->currentTime());
+    player->setCurrentTime(20);
+    EXPECT_EQ(20, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetPlaybackRateMax)
+{
+    player->setPlaybackRate(std::numeric_limits<double>::max());
+    EXPECT_EQ(std::numeric_limits<double>::max(), player->playbackRate());
+    EXPECT_EQ(0, player->currentTime());
+    updateTimeline(1);
+    EXPECT_EQ(30, player->currentTime());
+}
+
+
+TEST_F(AnimationPlayerTest, SetSource)
+{
+    player = timeline->createPlayer(0);
+    player->setStartTime(0);
+    RefPtr<TimedItem> source1 = makeAnimation();
+    RefPtr<TimedItem> source2 = makeAnimation();
+    player->setSource(source1.get());
+    EXPECT_EQ(source1, player->source());
+    EXPECT_EQ(0, player->currentTime());
+    player->setCurrentTime(15);
+    player->setSource(source2.get());
+    EXPECT_EQ(15, player->currentTime());
+    EXPECT_EQ(0, source1->player());
+    EXPECT_EQ(player.get(), source2->player());
+    EXPECT_EQ(source2, player->source());
+}
+
+TEST_F(AnimationPlayerTest, SetSourceLimitsPlayer)
+{
+    player->setCurrentTime(20);
+    player->setSource(makeAnimation(10).get());
+    EXPECT_EQ(20, player->currentTime());
+    EXPECT_TRUE(player->finished());
+    updateTimeline(10);
+    EXPECT_EQ(20, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetSourceUnlimitsPlayer)
+{
+    player->setCurrentTime(40);
+    player->setSource(makeAnimation(60).get());
+    EXPECT_FALSE(player->finished());
+    EXPECT_EQ(40, player->currentTime());
+    updateTimeline(10);
+    EXPECT_EQ(50, player->currentTime());
+}
+
+
 TEST_F(AnimationPlayerTest, EmptyPlayersDontUpdateEffects)
 {
-    double timeToNextEffect;
-    updateTimeline(0, &timeToNextEffect);
-    EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
+    player = timeline->createPlayer(0);
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), player->timeToEffectChange());
 
-    timeToNextEffect = 0;
-    updateTimeline(1234, &timeToNextEffect);
-    EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
+    updateTimeline(1234);
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), player->timeToEffectChange());
 }
 
 TEST_F(AnimationPlayerTest, PlayersReturnTimeToNextEffect)
@@ -323,29 +611,49 @@
     Timing timing;
     timing.startDelay = 1;
     timing.iterationDuration = 1;
-    timing.hasIterationDuration = true;
+    timing.endDelay = 1;
     RefPtr<Animation> animation = Animation::create(0, 0, timing);
-    player = Player::create(*timeline, animation.get());
+    player = timeline->createPlayer(animation.get());
     player->setStartTime(0);
 
-    double timeToNextEffect;
-    updateTimeline(0, &timeToNextEffect);
-    EXPECT_EQ(1, timeToNextEffect);
+    updateTimeline(0);
+    EXPECT_EQ(1, player->timeToEffectChange());
 
-    updateTimeline(0.5, &timeToNextEffect);
-    EXPECT_EQ(0.5, timeToNextEffect);
+    updateTimeline(0.5);
+    EXPECT_EQ(0.5, player->timeToEffectChange());
 
-    updateTimeline(1, &timeToNextEffect);
-    EXPECT_EQ(0, timeToNextEffect);
+    updateTimeline(1);
+    EXPECT_EQ(0, player->timeToEffectChange());
 
-    updateTimeline(1.5, &timeToNextEffect);
-    EXPECT_EQ(0, timeToNextEffect);
+    updateTimeline(1.5);
+    EXPECT_EQ(0, player->timeToEffectChange());
 
-    updateTimeline(2, &timeToNextEffect);
-    EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
+    updateTimeline(2);
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), player->timeToEffectChange());
 
-    updateTimeline(3, &timeToNextEffect);
-    EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
+    updateTimeline(3);
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), player->timeToEffectChange());
+
+    player->setCurrentTime(0);
+    player->update();
+    EXPECT_EQ(1, player->timeToEffectChange());
+
+    player->setPlaybackRate(2);
+    player->update();
+    EXPECT_EQ(0.5, player->timeToEffectChange());
+
+    player->setPlaybackRate(0);
+    player->update();
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), player->timeToEffectChange());
+
+    player->setCurrentTime(3);
+    player->setPlaybackRate(-1);
+    player->update();
+    EXPECT_EQ(1, player->timeToEffectChange());
+
+    player->setPlaybackRate(-2);
+    player->update();
+    EXPECT_EQ(0.5, player->timeToEffectChange());
 }
 
 TEST_F(AnimationPlayerTest, AttachedPlayers)
@@ -354,11 +662,12 @@
 
     Timing timing;
     RefPtr<Animation> animation = Animation::create(element, 0, timing);
-    RefPtr<Player> player = Player::create(*timeline, animation.get());
-    ASSERT_EQ(1U, element->activeAnimations()->players().find(player.get())->value);
+    RefPtr<Player> player = timeline->createPlayer(animation.get());
+    timeline->serviceAnimations();
+    EXPECT_EQ(1U, element->activeAnimations()->players().find(player.get())->value);
 
     player.release();
-    ASSERT_TRUE(element->activeAnimations()->players().isEmpty());
+    EXPECT_TRUE(element->activeAnimations()->players().isEmpty());
 }
 
 }
diff --git a/Source/core/animation/TimedItem.cpp b/Source/core/animation/TimedItem.cpp
index 43fd1bc..d837b66 100644
--- a/Source/core/animation/TimedItem.cpp
+++ b/Source/core/animation/TimedItem.cpp
@@ -30,10 +30,25 @@
 
 #include "config.h"
 #include "core/animation/TimedItem.h"
+
+#include "core/animation/Player.h"
 #include "core/animation/TimedItemCalculations.h"
 
 namespace WebCore {
 
+namespace {
+
+Timing::FillMode resolvedFillMode(Timing::FillMode fillMode, bool isAnimation)
+{
+    if (fillMode != Timing::FillModeAuto)
+        return fillMode;
+    if (isAnimation)
+        return Timing::FillModeNone;
+    return Timing::FillModeBoth;
+}
+
+} // namespace
+
 TimedItem::TimedItem(const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
     : m_parent(0)
     , m_startTime(0)
@@ -42,89 +57,134 @@
     , m_eventDelegate(eventDelegate)
     , m_calculated()
     , m_isFirstSample(true)
+    , m_needsUpdate(true)
+    , m_lastUpdateTime(nullValue())
 {
     m_specified.assertValid();
 }
 
+double TimedItem::iterationDuration() const
+{
+    double result = std::isnan(m_specified.iterationDuration) ? intrinsicIterationDuration() : m_specified.iterationDuration;
+    ASSERT(result >= 0);
+    return result;
+}
+
+double TimedItem::repeatedDuration() const
+{
+    const double result = multiplyZeroAlwaysGivesZero(iterationDuration(), m_specified.iterationCount);
+    ASSERT(result >= 0);
+    return result;
+}
+
+double TimedItem::activeDuration() const
+{
+    const double result = m_specified.playbackRate
+        ? repeatedDuration() / abs(m_specified.playbackRate)
+        : std::numeric_limits<double>::infinity();
+    ASSERT(result >= 0);
+    return result;
+}
+
+void TimedItem::updateSpecifiedTiming(const Timing& timing)
+{
+    m_specified = timing;
+    invalidate();
+    if (m_player)
+        m_player->setNeedsUpdate();
+}
+
 bool TimedItem::updateInheritedTime(double inheritedTime) const
 {
-    const double localTime = inheritedTime - m_startTime;
-    const double iterationDuration = m_specified.hasIterationDuration
-        ? m_specified.iterationDuration
-        : intrinsicIterationDuration();
-    ASSERT(iterationDuration >= 0);
-
-    // When iterationDuration = 0 and iterationCount = infinity, or vice-
-    // versa, repeatedDuration should be 0, not NaN as operator*() would give.
-    // FIXME: The spec is unclear about this.
-    const double repeatedDuration = multiplyZeroAlwaysGivesZero(iterationDuration, m_specified.iterationCount);
-    ASSERT(repeatedDuration >= 0);
-    const double activeDuration = m_specified.playbackRate
-        ? repeatedDuration / abs(m_specified.playbackRate)
-        : std::numeric_limits<double>::infinity();
-    ASSERT(activeDuration >= 0);
-
-    const Phase currentPhase = calculatePhase(activeDuration, localTime, m_specified);
-    // FIXME: parentPhase depends on groups being implemented.
-    const TimedItem::Phase parentPhase = TimedItem::PhaseActive;
-    const double activeTime = calculateActiveTime(activeDuration, localTime, parentPhase, currentPhase, m_specified);
-
-    double currentIteration;
-    double timeFraction;
-    double timeToNextIteration = std::numeric_limits<double>::infinity();
-    if (iterationDuration) {
-        const double startOffset = multiplyZeroAlwaysGivesZero(m_specified.iterationStart, iterationDuration);
-        ASSERT(startOffset >= 0);
-        const double scaledActiveTime = calculateScaledActiveTime(activeDuration, activeTime, startOffset, m_specified);
-        const double iterationTime = calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, m_specified);
-
-        currentIteration = calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, m_specified);
-        timeFraction = calculateTransformedTime(currentIteration, iterationDuration, iterationTime, m_specified) / iterationDuration;
-        if (!isNull(iterationTime))
-            timeToNextIteration = (iterationDuration - iterationTime) / abs(m_specified.playbackRate);
-    } else {
-        const double localIterationDuration = 1;
-        const double localRepeatedDuration = localIterationDuration * m_specified.iterationCount;
-        ASSERT(localRepeatedDuration >= 0);
-        const double localActiveDuration = m_specified.playbackRate ? localRepeatedDuration / abs(m_specified.playbackRate) : std::numeric_limits<double>::infinity();
-        ASSERT(localActiveDuration >= 0);
-        const double localLocalTime = localTime < m_specified.startDelay ? localTime : localActiveDuration + m_specified.startDelay;
-        const TimedItem::Phase localCurrentPhase = calculatePhase(localActiveDuration, localLocalTime, m_specified);
-        const double localActiveTime = calculateActiveTime(localActiveDuration, localLocalTime, parentPhase, localCurrentPhase, m_specified);
-        const double startOffset = m_specified.iterationStart * localIterationDuration;
-        ASSERT(startOffset >= 0);
-        const double scaledActiveTime = calculateScaledActiveTime(localActiveDuration, localActiveTime, startOffset, m_specified);
-        const double iterationTime = calculateIterationTime(localIterationDuration, localRepeatedDuration, scaledActiveTime, startOffset, m_specified);
-
-        currentIteration = calculateCurrentIteration(localIterationDuration, iterationTime, scaledActiveTime, m_specified);
-        timeFraction = calculateTransformedTime(currentIteration, localIterationDuration, iterationTime, m_specified);
-    }
+    bool needsUpdate = m_needsUpdate || (m_lastUpdateTime != inheritedTime && !(isNull(m_lastUpdateTime) && isNull(inheritedTime)));
+    m_needsUpdate = false;
+    m_lastUpdateTime = inheritedTime;
 
     const double previousIteration = m_calculated.currentIteration;
-    m_calculated.currentIteration = currentIteration;
-    m_calculated.activeDuration = activeDuration;
-    m_calculated.timeFraction = timeFraction;
-
     const Phase previousPhase = m_calculated.phase;
-    m_calculated.phase = currentPhase;
-    m_calculated.isInEffect = !isNull(activeTime);
-    m_calculated.isInPlay = phase() == PhaseActive && (!m_parent || m_parent->isInPlay());
-    m_calculated.isCurrent = phase() == PhaseBefore || isInPlay() || (m_parent && m_parent->isCurrent());
 
-    // This logic is specific to CSS animation events and assumes that all
-    // animations start after the DocumentTimeline has started.
-    if (m_eventDelegate && (m_isFirstSample || previousPhase != phase() || (phase() == PhaseActive && previousIteration != currentIteration)))
-        m_eventDelegate->onEventCondition(this, m_isFirstSample, previousPhase, previousIteration);
-    m_isFirstSample = false;
+    const double localTime = inheritedTime - m_startTime;
+    double timeToNextIteration = std::numeric_limits<double>::infinity();
+    if (needsUpdate) {
+        const double activeDuration = this->activeDuration();
 
-    // FIXME: This probably shouldn't be recursive.
-    bool didTriggerStyleRecalc = updateChildrenAndEffects();
+        const Phase currentPhase = calculatePhase(activeDuration, localTime, m_specified);
+        // FIXME: parentPhase depends on groups being implemented.
+        const TimedItem::Phase parentPhase = TimedItem::PhaseActive;
+        const double activeTime = calculateActiveTime(activeDuration, resolvedFillMode(m_specified.fillMode, isAnimation()), localTime, parentPhase, currentPhase, m_specified);
 
-    if (activeDuration - activeTime < timeToNextIteration)
-        timeToNextIteration = std::numeric_limits<double>::infinity();
+        double currentIteration;
+        double timeFraction;
+        if (const double iterationDuration = this->iterationDuration()) {
+            const double startOffset = multiplyZeroAlwaysGivesZero(m_specified.iterationStart, iterationDuration);
+            ASSERT(startOffset >= 0);
+            const double scaledActiveTime = calculateScaledActiveTime(activeDuration, activeTime, startOffset, m_specified);
+            const double iterationTime = calculateIterationTime(iterationDuration, repeatedDuration(), scaledActiveTime, startOffset, m_specified);
 
-    m_calculated.timeToEffectChange = calculateTimeToEffectChange(localTime, timeToNextIteration);
+            currentIteration = calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, m_specified);
+            timeFraction = calculateTransformedTime(currentIteration, iterationDuration, iterationTime, m_specified) / iterationDuration;
+
+            if (!isNull(iterationTime)) {
+                timeToNextIteration = (iterationDuration - iterationTime) / abs(m_specified.playbackRate);
+                if (activeDuration - activeTime < timeToNextIteration)
+                    timeToNextIteration = std::numeric_limits<double>::infinity();
+            }
+        } else {
+            const double localIterationDuration = 1;
+            const double localRepeatedDuration = localIterationDuration * m_specified.iterationCount;
+            ASSERT(localRepeatedDuration >= 0);
+            const double localActiveDuration = m_specified.playbackRate ? localRepeatedDuration / abs(m_specified.playbackRate) : std::numeric_limits<double>::infinity();
+            ASSERT(localActiveDuration >= 0);
+            const double localLocalTime = localTime < m_specified.startDelay ? localTime : localActiveDuration + m_specified.startDelay;
+            const TimedItem::Phase localCurrentPhase = calculatePhase(localActiveDuration, localLocalTime, m_specified);
+            const double localActiveTime = calculateActiveTime(localActiveDuration, resolvedFillMode(m_specified.fillMode, isAnimation()), localLocalTime, parentPhase, localCurrentPhase, m_specified);
+            const double startOffset = m_specified.iterationStart * localIterationDuration;
+            ASSERT(startOffset >= 0);
+            const double scaledActiveTime = calculateScaledActiveTime(localActiveDuration, localActiveTime, startOffset, m_specified);
+            const double iterationTime = calculateIterationTime(localIterationDuration, localRepeatedDuration, scaledActiveTime, startOffset, m_specified);
+
+            currentIteration = calculateCurrentIteration(localIterationDuration, iterationTime, scaledActiveTime, m_specified);
+            timeFraction = calculateTransformedTime(currentIteration, localIterationDuration, iterationTime, m_specified);
+        }
+
+        m_calculated.currentIteration = currentIteration;
+        m_calculated.timeFraction = timeFraction;
+
+        m_calculated.phase = currentPhase;
+        m_calculated.isInEffect = !isNull(activeTime);
+        m_calculated.isInPlay = phase() == PhaseActive && (!m_parent || m_parent->isInPlay());
+        m_calculated.isCurrent = phase() == PhaseBefore || isInPlay() || (m_parent && m_parent->isCurrent());
+        m_calculated.localTime = m_lastUpdateTime - m_startTime;
+    }
+
+    // Test for events even if timing didn't need an update as the player may have gained a start time.
+    // FIXME: Refactor so that we can ASSERT(m_player) here, this is currently required to be nullable for testing.
+    if (!m_player || m_player->hasStartTime()) {
+        // This logic is specific to CSS animation events and assumes that all
+        // animations start after the DocumentTimeline has started.
+        if (m_eventDelegate && (m_isFirstSample || previousPhase != phase() || (phase() == PhaseActive && previousIteration != m_calculated.currentIteration)))
+            m_eventDelegate->onEventCondition(this, m_isFirstSample, previousPhase, previousIteration);
+        m_isFirstSample = false;
+    }
+
+    bool didTriggerStyleRecalc = false;
+    if (needsUpdate)  {
+        // FIXME: This probably shouldn't be recursive.
+        didTriggerStyleRecalc = updateChildrenAndEffects();
+        m_calculated.timeToForwardsEffectChange = calculateTimeToEffectChange(true, localTime, timeToNextIteration);
+        m_calculated.timeToReverseEffectChange = calculateTimeToEffectChange(false, localTime, timeToNextIteration);
+    }
     return didTriggerStyleRecalc;
 }
 
+const TimedItem::CalculatedTiming& TimedItem::ensureCalculated() const
+{
+    if (!m_player)
+        return m_calculated;
+    if (m_player->needsUpdate())
+        m_player->update();
+    ASSERT(!m_player->needsUpdate());
+    return m_calculated;
+}
+
 } // namespace WebCore
diff --git a/Source/core/animation/TimedItem.h b/Source/core/animation/TimedItem.h
index ae95014..80ca2f0 100644
--- a/Source/core/animation/TimedItem.h
+++ b/Source/core/animation/TimedItem.h
@@ -31,6 +31,7 @@
 #ifndef TimedItem_h
 #define TimedItem_h
 
+#include "core/animation/TimedItemTiming.h"
 #include "core/animation/Timing.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
@@ -76,15 +77,25 @@
     bool isCurrent() const { return ensureCalculated().isCurrent; }
     bool isInEffect() const { return ensureCalculated().isInEffect; }
     bool isInPlay() const { return ensureCalculated().isInPlay; }
-    double timeToEffectChange() const { return ensureCalculated().timeToEffectChange; }
+    double timeToForwardsEffectChange() const { return ensureCalculated().timeToForwardsEffectChange; }
+    double timeToReverseEffectChange() const { return ensureCalculated().timeToReverseEffectChange; }
 
     double currentIteration() const { return ensureCalculated().currentIteration; }
-    double activeDuration() const { return ensureCalculated().activeDuration; }
+    double duration() const { return iterationDuration(); }
+    double activeDuration() const;
     double timeFraction() const { return ensureCalculated().timeFraction; }
     double startTime() const { return m_startTime; }
+    double endTime() const { return startTime() + specifiedTiming().startDelay + activeDuration() + specifiedTiming().endDelay; }
+
     const Player* player() const { return m_player; }
     Player* player() { return m_player; }
-    const Timing& specified() const { return m_specified; }
+    Player* player(bool& isNull) { isNull = !m_player; return m_player; }
+    const Timing& specifiedTiming() const { return m_specified; }
+    PassRefPtr<TimedItemTiming> specified() { return TimedItemTiming::create(this); }
+    void updateSpecifiedTiming(const Timing&);
+
+    double localTime(bool& isNull) const { isNull = !m_player; return ensureCalculated().localTime; }
+    double currentIteration(bool& isNull) const { isNull = !ensureCalculated().isInEffect; return ensureCalculated().currentIteration; }
 
 protected:
     TimedItem(const Timing&, PassOwnPtr<EventDelegate> = nullptr);
@@ -94,12 +105,17 @@
     // updateChildrenAndEffects.
     // Returns whether style recalc was triggered.
     bool updateInheritedTime(double inheritedTime) const;
+    void invalidate() const { m_needsUpdate = true; };
 
 private:
+
+    double iterationDuration() const;
+    double repeatedDuration() const;
+
     // Returns whether style recalc was triggered.
     virtual bool updateChildrenAndEffects() const = 0;
     virtual double intrinsicIterationDuration() const { return 0; };
-    virtual double calculateTimeToEffectChange(double localTime, double timeToNextIteration) const = 0;
+    virtual double calculateTimeToEffectChange(bool forwards, double localTime, double timeToNextIteration) const = 0;
     virtual void didAttach() { };
     virtual void willDetach() { };
 
@@ -123,21 +139,22 @@
     Timing m_specified;
     OwnPtr<EventDelegate> m_eventDelegate;
 
-    // FIXME: Should be versioned by monotonic value on player.
     mutable struct CalculatedTiming {
-        double activeDuration;
         Phase phase;
         double currentIteration;
         double timeFraction;
         bool isCurrent;
         bool isInEffect;
         bool isInPlay;
-        double timeToEffectChange;
+        double localTime;
+        double timeToForwardsEffectChange;
+        double timeToReverseEffectChange;
     } m_calculated;
     mutable bool m_isFirstSample;
+    mutable bool m_needsUpdate;
+    mutable double m_lastUpdateTime;
 
-    // FIXME: Should check the version and reinherit time if inconsistent.
-    const CalculatedTiming& ensureCalculated() const { return m_calculated; }
+    const CalculatedTiming& ensureCalculated() const;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/ime/Composition.idl b/Source/core/animation/TimedItem.idl
similarity index 77%
rename from Source/core/html/ime/Composition.idl
rename to Source/core/animation/TimedItem.idl
index 494d2a0..34fa04d 100644
--- a/Source/core/html/ime/Composition.idl
+++ b/Source/core/animation/TimedItem.idl
@@ -28,12 +28,19 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-// http://www.w3.org/TR/ime-api/
 [
-    NoInterfaceObject
-] interface Composition {
-    readonly attribute DOMString text;
-    readonly attribute long selectionStart;
-    readonly attribute long selectionEnd;
-    sequence<unsigned long> getSegments();
+    RuntimeEnabled=WebAnimationsAPI,
+] interface TimedItem {
+    // Playback state
+    readonly attribute double? localTime;
+    readonly attribute unsigned long? currentIteration;
+
+    // Calculated timing
+    readonly attribute double startTime;
+    readonly attribute double duration;
+    readonly attribute double activeDuration;
+    readonly attribute double endTime;
+
+    readonly attribute Timing specified;
+    readonly attribute Player? player;
 };
diff --git a/Source/core/animation/TimedItemCalculations.h b/Source/core/animation/TimedItemCalculations.h
index 409d140..5226395 100644
--- a/Source/core/animation/TimedItemCalculations.h
+++ b/Source/core/animation/TimedItemCalculations.h
@@ -72,22 +72,22 @@
     }
 }
 
-static inline double calculateActiveTime(double activeDuration, double localTime, TimedItem::Phase parentPhase, TimedItem::Phase phase, const Timing& specified)
+static inline double calculateActiveTime(double activeDuration, Timing::FillMode fillMode, double localTime, TimedItem::Phase parentPhase, TimedItem::Phase phase, const Timing& specified)
 {
     ASSERT(activeDuration >= 0);
     ASSERT(phase == calculatePhase(activeDuration, localTime, specified));
 
     switch (phase) {
     case TimedItem::PhaseBefore:
-        if (specified.fillMode == Timing::FillModeBackwards || specified.fillMode == Timing::FillModeBoth)
+        if (fillMode == Timing::FillModeBackwards || fillMode == Timing::FillModeBoth)
             return 0;
         return nullValue();
     case TimedItem::PhaseActive:
-        if (isActiveInParentPhase(parentPhase, specified.fillMode))
+        if (isActiveInParentPhase(parentPhase, fillMode))
             return localTime - specified.startDelay;
         return nullValue();
     case TimedItem::PhaseAfter:
-        if (specified.fillMode == Timing::FillModeForwards || specified.fillMode == Timing::FillModeBoth)
+        if (fillMode == Timing::FillModeForwards || fillMode == Timing::FillModeBoth)
             return activeDuration;
         return nullValue();
     case TimedItem::PhaseNone:
@@ -186,10 +186,8 @@
     double directedTime = calculateDirectedTime(currentIteration, iterationDuration, iterationTime, specified);
     if (isNull(directedTime))
         return nullValue();
-    if (!std::isfinite(directedTime)) {
-        ASSERT(!std::isfinite(iterationDuration));
+    if (!std::isfinite(iterationDuration))
         return directedTime;
-    }
     double timeFraction = directedTime / iterationDuration;
     ASSERT(timeFraction >= 0 && timeFraction <= 1);
     return specified.timingFunction
diff --git a/Source/core/animation/TimedItemCalculationsTest.cpp b/Source/core/animation/TimedItemCalculationsTest.cpp
index 9267301..e88c7d1 100644
--- a/Source/core/animation/TimedItemCalculationsTest.cpp
+++ b/Source/core/animation/TimedItemCalculationsTest.cpp
@@ -41,48 +41,35 @@
 {
     Timing timing;
 
-    // calculateActiveTime(activeDuration, localTime, parentPhase, phase, timing)
+    // calculateActiveTime(activeDuration, fillMode, localTime, parentPhase, phase, timing)
 
     // Before Phase
     timing.startDelay = 10;
-    timing.fillMode = Timing::FillModeForwards;
-    ASSERT_TRUE(isNull(calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing)));
-    timing.fillMode = Timing::FillModeNone;
-    ASSERT_TRUE(isNull(calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing)));
-    timing.fillMode = Timing::FillModeBackwards;
-    ASSERT_EQ(0, calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing));
-    timing.fillMode = Timing::FillModeBoth;
-    ASSERT_EQ(0, calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing));
+    EXPECT_TRUE(isNull(calculateActiveTime(20, Timing::FillModeForwards, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing)));
+    EXPECT_TRUE(isNull(calculateActiveTime(20, Timing::FillModeNone, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing)));
+    EXPECT_EQ(0, calculateActiveTime(20, Timing::FillModeBackwards, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing));
+    EXPECT_EQ(0, calculateActiveTime(20, Timing::FillModeBoth, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing));
 
     // Active Phase
     timing.startDelay = 10;
     // Active, and parent Before
-    timing.fillMode = Timing::FillModeNone;
-    ASSERT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseBefore, TimedItem::PhaseActive, timing)));
-    timing.fillMode = Timing::FillModeForwards;
-    ASSERT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseBefore, TimedItem::PhaseActive, timing)));
+    EXPECT_TRUE(isNull(calculateActiveTime(20, Timing::FillModeNone, 15, TimedItem::PhaseBefore, TimedItem::PhaseActive, timing)));
+    EXPECT_TRUE(isNull(calculateActiveTime(20, Timing::FillModeForwards, 15, TimedItem::PhaseBefore, TimedItem::PhaseActive, timing)));
     // Active, and parent After
-    timing.fillMode = Timing::FillModeNone;
-    ASSERT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseAfter, TimedItem::PhaseActive, timing)));
-    timing.fillMode = Timing::FillModeBackwards;
-    ASSERT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseAfter, TimedItem::PhaseActive, timing)));
+    EXPECT_TRUE(isNull(calculateActiveTime(20, Timing::FillModeNone, 15, TimedItem::PhaseAfter, TimedItem::PhaseActive, timing)));
+    EXPECT_TRUE(isNull(calculateActiveTime(20, Timing::FillModeBackwards, 15, TimedItem::PhaseAfter, TimedItem::PhaseActive, timing)));
     // Active, and parent Active
-    timing.fillMode = Timing::FillModeForwards;
-    ASSERT_EQ(5, calculateActiveTime(20, 15, TimedItem::PhaseActive, TimedItem::PhaseActive, timing));
+    EXPECT_EQ(5, calculateActiveTime(20, Timing::FillModeForwards, 15, TimedItem::PhaseActive, TimedItem::PhaseActive, timing));
 
     // After Phase
     timing.startDelay = 10;
-    timing.fillMode = Timing::FillModeForwards;
-    ASSERT_EQ(21, calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing));
-    timing.fillMode = Timing::FillModeBoth;
-    ASSERT_EQ(21, calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing));
-    timing.fillMode = Timing::FillModeBackwards;
-    ASSERT_TRUE(isNull(calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing)));
-    timing.fillMode = Timing::FillModeNone;
-    ASSERT_TRUE(isNull(calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing)));
+    EXPECT_EQ(21, calculateActiveTime(21, Timing::FillModeForwards, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing));
+    EXPECT_EQ(21, calculateActiveTime(21, Timing::FillModeBoth, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing));
+    EXPECT_TRUE(isNull(calculateActiveTime(21, Timing::FillModeBackwards, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing)));
+    EXPECT_TRUE(isNull(calculateActiveTime(21, Timing::FillModeNone, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing)));
 
     // None
-    ASSERT_TRUE(isNull(calculateActiveTime(32, nullValue(), TimedItem::PhaseNone, TimedItem::PhaseNone, timing)));
+    EXPECT_TRUE(isNull(calculateActiveTime(32, Timing::FillModeNone, nullValue(), TimedItem::PhaseNone, TimedItem::PhaseNone, timing)));
 }
 
 TEST(AnimationTimedItemCalculationsTest, ScaledActiveTime)
@@ -92,23 +79,23 @@
     // calculateScaledActiveTime(activeDuration, activeTime, startOffset, timing)
 
     // if the active time is null
-    ASSERT_TRUE(isNull(calculateScaledActiveTime(4, nullValue(), 5, timing)));
+    EXPECT_TRUE(isNull(calculateScaledActiveTime(4, nullValue(), 5, timing)));
 
     // if the playback rate is negative
     timing.playbackRate = -1;
-    ASSERT_EQ(35, calculateScaledActiveTime(40, 10, 5, timing));
+    EXPECT_EQ(35, calculateScaledActiveTime(40, 10, 5, timing));
 
     // otherwise
     timing.playbackRate = 0;
-    ASSERT_EQ(5, calculateScaledActiveTime(40, 10, 5, timing));
+    EXPECT_EQ(5, calculateScaledActiveTime(40, 10, 5, timing));
     timing.playbackRate = 1;
-    ASSERT_EQ(15, calculateScaledActiveTime(40, 10, 5, timing));
+    EXPECT_EQ(15, calculateScaledActiveTime(40, 10, 5, timing));
 
     // infinte activeTime
     timing.playbackRate = 0;
-    ASSERT_EQ(0, calculateScaledActiveTime(std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), 0, timing));
+    EXPECT_EQ(0, calculateScaledActiveTime(std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), 0, timing));
     timing.playbackRate = 1;
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), calculateScaledActiveTime(std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), 0, timing));
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), calculateScaledActiveTime(std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), 0, timing));
 }
 
 TEST(AnimationTimedItemCalculationsTest, IterationTime)
@@ -118,17 +105,17 @@
     // calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, timing)
 
     // if the scaled active time is null
-    ASSERT_TRUE(isNull(calculateIterationTime(1, 1, nullValue(), 1, timing)));
+    EXPECT_TRUE(isNull(calculateIterationTime(1, 1, nullValue(), 1, timing)));
 
     // if (complex-conditions)...
-    ASSERT_EQ(12, calculateIterationTime(12, 12, 12, 0, timing));
+    EXPECT_EQ(12, calculateIterationTime(12, 12, 12, 0, timing));
 
     // otherwise
     timing.iterationCount = 10;
-    ASSERT_EQ(5, calculateIterationTime(10, 100, 25, 4, timing));
-    ASSERT_EQ(7, calculateIterationTime(11, 110, 29, 1, timing));
+    EXPECT_EQ(5, calculateIterationTime(10, 100, 25, 4, timing));
+    EXPECT_EQ(7, calculateIterationTime(11, 110, 29, 1, timing));
     timing.iterationStart = 1.1;
-    ASSERT_EQ(8, calculateIterationTime(12, 120, 20, 7, timing));
+    EXPECT_EQ(8, calculateIterationTime(12, 120, 20, 7, timing));
 }
 
 TEST(AnimationTimedItemCalculationsTest, CurrentIteration)
@@ -138,18 +125,18 @@
     // calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, timing)
 
     // if the scaled active time is null
-    ASSERT_TRUE(isNull(calculateCurrentIteration(1, 1, nullValue(), timing)));
+    EXPECT_TRUE(isNull(calculateCurrentIteration(1, 1, nullValue(), timing)));
 
     // if the scaled active time is zero
-    ASSERT_EQ(0, calculateCurrentIteration(1, 1, 0, timing));
+    EXPECT_EQ(0, calculateCurrentIteration(1, 1, 0, timing));
 
     // if the iteration time equals the iteration duration
     timing.iterationStart = 4;
     timing.iterationCount = 7;
-    ASSERT_EQ(10, calculateCurrentIteration(5, 5, 9, timing));
+    EXPECT_EQ(10, calculateCurrentIteration(5, 5, 9, timing));
 
     // otherwise
-    ASSERT_EQ(3, calculateCurrentIteration(3.2, 3.1, 10, timing));
+    EXPECT_EQ(3, calculateCurrentIteration(3.2, 3.1, 10, timing));
 }
 
 TEST(AnimationTimedItemCalculationsTest, DirectedTime)
@@ -159,28 +146,28 @@
     // calculateDirectedTime(currentIteration, iterationDuration, iterationTime, timing)
 
     // if the iteration time is null
-    ASSERT_TRUE(isNull(calculateDirectedTime(1, 2, nullValue(), timing)));
+    EXPECT_TRUE(isNull(calculateDirectedTime(1, 2, nullValue(), timing)));
 
     // forwards
-    ASSERT_EQ(17, calculateDirectedTime(0, 20, 17, timing));
-    ASSERT_EQ(17, calculateDirectedTime(1, 20, 17, timing));
+    EXPECT_EQ(17, calculateDirectedTime(0, 20, 17, timing));
+    EXPECT_EQ(17, calculateDirectedTime(1, 20, 17, timing));
     timing.direction = Timing::PlaybackDirectionAlternate;
-    ASSERT_EQ(17, calculateDirectedTime(0, 20, 17, timing));
-    ASSERT_EQ(17, calculateDirectedTime(2, 20, 17, timing));
+    EXPECT_EQ(17, calculateDirectedTime(0, 20, 17, timing));
+    EXPECT_EQ(17, calculateDirectedTime(2, 20, 17, timing));
     timing.direction = Timing::PlaybackDirectionAlternateReverse;
-    ASSERT_EQ(17, calculateDirectedTime(1, 20, 17, timing));
-    ASSERT_EQ(17, calculateDirectedTime(3, 20, 17, timing));
+    EXPECT_EQ(17, calculateDirectedTime(1, 20, 17, timing));
+    EXPECT_EQ(17, calculateDirectedTime(3, 20, 17, timing));
 
     // reverse
     timing.direction = Timing::PlaybackDirectionReverse;
-    ASSERT_EQ(3, calculateDirectedTime(0, 20, 17, timing));
-    ASSERT_EQ(3, calculateDirectedTime(1, 20, 17, timing));
+    EXPECT_EQ(3, calculateDirectedTime(0, 20, 17, timing));
+    EXPECT_EQ(3, calculateDirectedTime(1, 20, 17, timing));
     timing.direction = Timing::PlaybackDirectionAlternate;
-    ASSERT_EQ(3, calculateDirectedTime(1, 20, 17, timing));
-    ASSERT_EQ(3, calculateDirectedTime(3, 20, 17, timing));
+    EXPECT_EQ(3, calculateDirectedTime(1, 20, 17, timing));
+    EXPECT_EQ(3, calculateDirectedTime(3, 20, 17, timing));
     timing.direction = Timing::PlaybackDirectionAlternateReverse;
-    ASSERT_EQ(3, calculateDirectedTime(0, 20, 17, timing));
-    ASSERT_EQ(3, calculateDirectedTime(2, 20, 17, timing));
+    EXPECT_EQ(3, calculateDirectedTime(0, 20, 17, timing));
+    EXPECT_EQ(3, calculateDirectedTime(2, 20, 17, timing));
 }
 
 TEST(AnimationTimedItemCalculationsTest, TransformedTime)
@@ -190,38 +177,38 @@
     // calculateTransformedTime(currentIteration, iterationDuration, iterationTime, timing)
 
     // Iteration time is null
-    ASSERT_TRUE(isNull(calculateTransformedTime(1, 2, nullValue(), timing)));
+    EXPECT_TRUE(isNull(calculateTransformedTime(1, 2, nullValue(), timing)));
 
     // PlaybackDirectionForwards
-    ASSERT_EQ(12, calculateTransformedTime(0, 20, 12, timing));
-    ASSERT_EQ(12, calculateTransformedTime(1, 20, 12, timing));
+    EXPECT_EQ(12, calculateTransformedTime(0, 20, 12, timing));
+    EXPECT_EQ(12, calculateTransformedTime(1, 20, 12, timing));
 
     // PlaybackDirectionForwards with timing function
     timing.timingFunction = StepsTimingFunction::create(4, false /* stepAtStart */);
-    ASSERT_EQ(10, calculateTransformedTime(0, 20, 12, timing));
-    ASSERT_EQ(10, calculateTransformedTime(1, 20, 12, timing));
+    EXPECT_EQ(10, calculateTransformedTime(0, 20, 12, timing));
+    EXPECT_EQ(10, calculateTransformedTime(1, 20, 12, timing));
 
     // PlaybackDirectionReverse
     timing.timingFunction = 0;
     timing.direction = Timing::PlaybackDirectionReverse;
-    ASSERT_EQ(8, calculateTransformedTime(0, 20, 12, timing));
-    ASSERT_EQ(8, calculateTransformedTime(1, 20, 12, timing));
+    EXPECT_EQ(8, calculateTransformedTime(0, 20, 12, timing));
+    EXPECT_EQ(8, calculateTransformedTime(1, 20, 12, timing));
 
     // PlaybackDirectionReverse with timing function
     timing.timingFunction = StepsTimingFunction::create(4, false /* stepAtStart */);
-    ASSERT_EQ(5, calculateTransformedTime(0, 20, 12, timing));
-    ASSERT_EQ(5, calculateTransformedTime(1, 20, 12, timing));
+    EXPECT_EQ(5, calculateTransformedTime(0, 20, 12, timing));
+    EXPECT_EQ(5, calculateTransformedTime(1, 20, 12, timing));
 
     // Timing function when directed time is null.
-    ASSERT_TRUE(isNull(calculateTransformedTime(1, 2, nullValue(), timing)));
+    EXPECT_TRUE(isNull(calculateTransformedTime(1, 2, nullValue(), timing)));
 
     // Timing function when iterationDuration is infinity
     timing.direction = Timing::PlaybackDirectionNormal;
-    ASSERT_EQ(0, calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 0, timing));
-    ASSERT_EQ(0, calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 1, timing));
+    EXPECT_EQ(0, calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 0, timing));
+    EXPECT_EQ(1, calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 1, timing));
     timing.direction = Timing::PlaybackDirectionReverse;
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 0, timing));
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 1, timing));
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 0, timing));
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 1, timing));
 }
 
 }
diff --git a/Source/core/animation/TimedItemTest.cpp b/Source/core/animation/TimedItemTest.cpp
index a7b5faa..3a6fec4 100644
--- a/Source/core/animation/TimedItemTest.cpp
+++ b/Source/core/animation/TimedItemTest.cpp
@@ -39,7 +39,7 @@
 
 class TestTimedItemEventDelegate : public TimedItem::EventDelegate {
 public:
-    void onEventCondition(const TimedItem* timedItem, bool isFirstSample, TimedItem::Phase previousPhase, double previousIteration) OVERRIDE
+    virtual void onEventCondition(const TimedItem* timedItem, bool isFirstSample, TimedItem::Phase previousPhase, double previousIteration) OVERRIDE
     {
         m_eventTriggered = true;
         m_phaseChanged = previousPhase != timedItem->phase();
@@ -75,16 +75,15 @@
         TimedItem::updateInheritedTime(time);
     }
 
-    bool updateChildrenAndEffects() const OVERRIDE { return false; }
+    virtual bool updateChildrenAndEffects() const OVERRIDE { return false; }
     void willDetach() { }
     TestTimedItemEventDelegate* eventDelegate() { return m_eventDelegate; }
-    double calculateTimeToEffectChange(double localTime, double timeToNextIteration) const OVERRIDE
+    virtual double calculateTimeToEffectChange(bool forwards, double localTime, double timeToNextIteration) const OVERRIDE
     {
         m_localTime = localTime;
         m_timeToNextIteration = timeToNextIteration;
         return -1;
     }
-
     double takeLocalTime()
     {
         const double result = m_localTime;
@@ -114,184 +113,193 @@
 TEST(AnimationTimedItemTest, Sanity)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 2;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
-    ASSERT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(0, timedItem->startTime());
 
     timedItem->updateInheritedTime(0);
 
-    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
-    ASSERT_TRUE(timedItem->isInPlay());
-    ASSERT_TRUE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->startTime());
-    ASSERT_EQ(2, timedItem->activeDuration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+    EXPECT_TRUE(timedItem->isInPlay());
+    EXPECT_TRUE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(2, timedItem->activeDuration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
 
-    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
-    ASSERT_TRUE(timedItem->isInPlay());
-    ASSERT_TRUE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->startTime());
-    ASSERT_EQ(2, timedItem->activeDuration());
-    ASSERT_EQ(0.5, timedItem->timeFraction());
+    EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+    EXPECT_TRUE(timedItem->isInPlay());
+    EXPECT_TRUE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(2, timedItem->activeDuration());
+    EXPECT_EQ(0.5, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(2);
 
-    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
-    ASSERT_FALSE(timedItem->isInPlay());
-    ASSERT_FALSE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->startTime());
-    ASSERT_EQ(2, timedItem->activeDuration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_FALSE(timedItem->isInPlay());
+    EXPECT_FALSE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(2, timedItem->activeDuration());
+    EXPECT_EQ(1, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(3);
 
-    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
-    ASSERT_FALSE(timedItem->isInPlay());
-    ASSERT_FALSE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->startTime());
-    ASSERT_EQ(2, timedItem->activeDuration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_FALSE(timedItem->isInPlay());
+    EXPECT_FALSE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(2, timedItem->activeDuration());
+    EXPECT_EQ(1, timedItem->timeFraction());
+}
+
+TEST(AnimationTimedItemTest, FillAuto)
+{
+    Timing timing;
+    timing.iterationDuration = 1;
+    RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
+
+    timedItem->updateInheritedTime(-1);
+    EXPECT_EQ(0, timedItem->timeFraction());
+
+    timedItem->updateInheritedTime(2);
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, FillForwards)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
+    timing.fillMode = Timing::FillModeForwards;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(2);
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, FillBackwards)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
     timing.fillMode = Timing::FillModeBackwards;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(2);
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 }
 
 TEST(AnimationTimedItemTest, FillBoth)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
     timing.fillMode = Timing::FillModeBoth;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(2);
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, StartDelay)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
+    timing.fillMode = Timing::FillModeForwards;
     timing.startDelay = 0.5;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(0);
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0.5);
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1.5);
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, ZeroIteration)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
+    timing.fillMode = Timing::FillModeForwards;
     timing.iterationCount = 0;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_EQ(0, timedItem->activeDuration());
-    ASSERT_TRUE(isNull(timedItem->currentIteration()));
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_EQ(0, timedItem->activeDuration());
+    EXPECT_TRUE(isNull(timedItem->currentIteration()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(0, timedItem->activeDuration());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->activeDuration());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, InfiniteIteration)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
+    timing.fillMode = Timing::FillModeForwards;
     timing.iterationCount = std::numeric_limits<double>::infinity();
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_TRUE(isNull(timedItem->currentIteration()));
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->currentIteration()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, Iteration)
 {
     Timing timing;
     timing.iterationCount = 2;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 2;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0.5, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0.5, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(2);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(2);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(5);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, IterationStart)
@@ -299,66 +307,63 @@
     Timing timing;
     timing.iterationStart = 1.2;
     timing.iterationCount = 2.2;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
     timing.fillMode = Timing::FillModeBoth;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
 
     timedItem->updateInheritedTime(10);
-    ASSERT_EQ(3, timedItem->currentIteration());
-    ASSERT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
+    EXPECT_EQ(3, timedItem->currentIteration());
+    EXPECT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
 }
 
 TEST(AnimationTimedItemTest, IterationAlternate)
 {
     Timing timing;
     timing.iterationCount = 10;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
     timing.direction = Timing::PlaybackDirectionAlternate;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(0.75);
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0.75, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0.75, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1.75);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(0.25, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(0.25, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(2.75);
-    ASSERT_EQ(2, timedItem->currentIteration());
-    ASSERT_EQ(0.75, timedItem->timeFraction());
+    EXPECT_EQ(2, timedItem->currentIteration());
+    EXPECT_EQ(0.75, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, IterationAlternateReverse)
 {
     Timing timing;
     timing.iterationCount = 10;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
     timing.direction = Timing::PlaybackDirectionAlternateReverse;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(0.75);
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0.25, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0.25, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1.75);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(0.75, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(0.75, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(2.75);
-    ASSERT_EQ(2, timedItem->currentIteration());
-    ASSERT_EQ(0.25, timedItem->timeFraction());
+    EXPECT_EQ(2, timedItem->currentIteration());
+    EXPECT_EQ(0.25, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationSanity)
@@ -366,44 +371,45 @@
     Timing timing;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
-    ASSERT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(0, timedItem->startTime());
 
     timedItem->updateInheritedTime(0);
 
-    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
-    ASSERT_FALSE(timedItem->isInPlay());
-    ASSERT_FALSE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->startTime());
-    ASSERT_EQ(0, timedItem->activeDuration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_FALSE(timedItem->isInPlay());
+    EXPECT_FALSE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(0, timedItem->activeDuration());
+    EXPECT_EQ(1, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
 
-    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
-    ASSERT_FALSE(timedItem->isInPlay());
-    ASSERT_FALSE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->startTime());
-    ASSERT_EQ(0, timedItem->activeDuration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_FALSE(timedItem->isInPlay());
+    EXPECT_FALSE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(0, timedItem->activeDuration());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationFillForwards)
 {
     Timing timing;
+    timing.fillMode = Timing::FillModeForwards;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationFillBackwards)
@@ -413,13 +419,13 @@
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(0);
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(1);
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationFillBoth)
@@ -429,29 +435,30 @@
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationStartDelay)
 {
     Timing timing;
+    timing.fillMode = Timing::FillModeForwards;
     timing.startDelay = 0.5;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(0);
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0.5);
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1.5);
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationIterationStartAndCount)
@@ -464,50 +471,52 @@
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(0.1, timedItem->timeFraction());
+    EXPECT_EQ(0.1, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(0.3);
-    ASSERT_DOUBLE_EQ(0.3, timedItem->timeFraction());
+    EXPECT_DOUBLE_EQ(0.3, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
-    ASSERT_DOUBLE_EQ(0.3, timedItem->timeFraction());
+    EXPECT_DOUBLE_EQ(0.3, timedItem->timeFraction());
 }
 
 // FIXME: Needs specification work.
 TEST(AnimationTimedItemTest, ZeroDurationInfiniteIteration)
 {
     Timing timing;
+    timing.fillMode = Timing::FillModeForwards;
     timing.iterationCount = std::numeric_limits<double>::infinity();
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_EQ(0, timedItem->activeDuration());
-    ASSERT_TRUE(isNull(timedItem->currentIteration()));
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_EQ(0, timedItem->activeDuration());
+    EXPECT_TRUE(isNull(timedItem->currentIteration()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(0, timedItem->activeDuration());
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->currentIteration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->activeDuration());
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->currentIteration());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationIteration)
 {
     Timing timing;
+    timing.fillMode = Timing::FillModeForwards;
     timing.iterationCount = 2;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_TRUE(isNull(timedItem->currentIteration()));
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->currentIteration()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(1, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationIterationStart)
@@ -519,233 +528,242 @@
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(3, timedItem->currentIteration());
-    ASSERT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
+    EXPECT_EQ(3, timedItem->currentIteration());
+    EXPECT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
 
     timedItem->updateInheritedTime(10);
-    ASSERT_EQ(3, timedItem->currentIteration());
-    ASSERT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
+    EXPECT_EQ(3, timedItem->currentIteration());
+    EXPECT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationIterationAlternate)
 {
     Timing timing;
+    timing.fillMode = Timing::FillModeForwards;
     timing.iterationCount = 2;
     timing.direction = Timing::PlaybackDirectionAlternate;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_TRUE(isNull(timedItem->currentIteration()));
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->currentIteration()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, ZeroDurationIterationAlternateReverse)
 {
     Timing timing;
+    timing.fillMode = Timing::FillModeForwards;
     timing.iterationCount = 2;
     timing.direction = Timing::PlaybackDirectionAlternateReverse;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     timedItem->updateInheritedTime(-1);
-    ASSERT_TRUE(isNull(timedItem->currentIteration()));
-    ASSERT_TRUE(isNull(timedItem->timeFraction()));
+    EXPECT_TRUE(isNull(timedItem->currentIteration()));
+    EXPECT_TRUE(isNull(timedItem->timeFraction()));
 
     timedItem->updateInheritedTime(0);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(1, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
-    ASSERT_EQ(1, timedItem->currentIteration());
-    ASSERT_EQ(1, timedItem->timeFraction());
+    EXPECT_EQ(1, timedItem->currentIteration());
+    EXPECT_EQ(1, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, InfiniteDurationSanity)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = std::numeric_limits<double>::infinity();
     timing.iterationCount = 1;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
-    ASSERT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(0, timedItem->startTime());
 
     timedItem->updateInheritedTime(0);
 
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
-    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
-    ASSERT_TRUE(timedItem->isInPlay());
-    ASSERT_TRUE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+    EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+    EXPECT_TRUE(timedItem->isInPlay());
+    EXPECT_TRUE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
 
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
-    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
-    ASSERT_TRUE(timedItem->isInPlay());
-    ASSERT_TRUE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+    EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+    EXPECT_TRUE(timedItem->isInPlay());
+    EXPECT_TRUE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 }
 
 // FIXME: Needs specification work.
 TEST(AnimationTimedItemTest, InfiniteDurationZeroIterations)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = std::numeric_limits<double>::infinity();
     timing.iterationCount = 0;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
-    ASSERT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(0, timedItem->startTime());
 
     timedItem->updateInheritedTime(0);
 
-    ASSERT_EQ(0, timedItem->activeDuration());
-    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
-    ASSERT_FALSE(timedItem->isInPlay());
-    ASSERT_FALSE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(0, timedItem->activeDuration());
+    EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_FALSE(timedItem->isInPlay());
+    EXPECT_FALSE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
 
-    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
-    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
-    ASSERT_FALSE(timedItem->isInPlay());
-    ASSERT_FALSE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_FALSE(timedItem->isInPlay());
+    EXPECT_FALSE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, InfiniteDurationInfiniteIterations)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = std::numeric_limits<double>::infinity();
     timing.iterationCount = std::numeric_limits<double>::infinity();
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
-    ASSERT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(0, timedItem->startTime());
 
     timedItem->updateInheritedTime(0);
 
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
-    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
-    ASSERT_TRUE(timedItem->isInPlay());
-    ASSERT_TRUE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+    EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+    EXPECT_TRUE(timedItem->isInPlay());
+    EXPECT_TRUE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(1);
 
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
-    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
-    ASSERT_TRUE(timedItem->isInPlay());
-    ASSERT_TRUE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+    EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+    EXPECT_TRUE(timedItem->isInPlay());
+    EXPECT_TRUE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 }
 
 TEST(AnimationTimedItemTest, InfiniteDurationZeroPlaybackRate)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = std::numeric_limits<double>::infinity();
     timing.playbackRate = 0;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
-    ASSERT_EQ(0, timedItem->startTime());
+    EXPECT_EQ(0, timedItem->startTime());
 
     timedItem->updateInheritedTime(0);
 
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
-    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
-    ASSERT_TRUE(timedItem->isInPlay());
-    ASSERT_TRUE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+    EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+    EXPECT_TRUE(timedItem->isInPlay());
+    EXPECT_TRUE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
 
     timedItem->updateInheritedTime(std::numeric_limits<double>::infinity());
 
-    ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
-    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
-    ASSERT_FALSE(timedItem->isInPlay());
-    ASSERT_FALSE(timedItem->isCurrent());
-    ASSERT_TRUE(timedItem->isInEffect());
-    ASSERT_EQ(0, timedItem->currentIteration());
-    ASSERT_EQ(0, timedItem->timeFraction());
+    EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+    EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_FALSE(timedItem->isInPlay());
+    EXPECT_FALSE(timedItem->isCurrent());
+    EXPECT_TRUE(timedItem->isInEffect());
+    EXPECT_EQ(0, timedItem->currentIteration());
+    EXPECT_EQ(0, timedItem->timeFraction());
+}
+
+TEST(AnimationTimedItemTest, EndTime)
+{
+    Timing timing;
+    timing.startDelay = 1;
+    timing.endDelay = 2;
+    timing.iterationDuration = 4;
+    timing.iterationCount = 2;
+    RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
+    EXPECT_EQ(11, timedItem->endTime());
 }
 
 TEST(AnimationTimedItemTest, Events)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
+    timing.fillMode = Timing::FillModeForwards;
     timing.iterationCount = 2;
     timing.startDelay = 1;
     RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
 
     // First sample
     timedItem->updateInheritedTime(0.0);
-    ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_TRUE(timedItem->eventDelegate()->eventTriggered());
 
     // Before start
     timedItem->updateInheritedTime(0.5);
-    ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_FALSE(timedItem->eventDelegate()->eventTriggered());
 
     // First iteration
     timedItem->updateInheritedTime(1.5);
-    ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_TRUE(timedItem->eventDelegate()->eventTriggered());
     EXPECT_TRUE(timedItem->eventDelegate()->phaseChanged());
     EXPECT_TRUE(timedItem->eventDelegate()->iterationChanged());
 
     timedItem->updateInheritedTime(1.6);
-    ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_FALSE(timedItem->eventDelegate()->eventTriggered());
 
     // Second iteration
     timedItem->updateInheritedTime(2.5);
-    ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_TRUE(timedItem->eventDelegate()->eventTriggered());
     EXPECT_FALSE(timedItem->eventDelegate()->phaseChanged());
     EXPECT_TRUE(timedItem->eventDelegate()->iterationChanged());
 
     timedItem->updateInheritedTime(2.6);
-    ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_FALSE(timedItem->eventDelegate()->eventTriggered());
 
     // After end
     timedItem->updateInheritedTime(3.5);
-    ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_TRUE(timedItem->eventDelegate()->eventTriggered());
     EXPECT_TRUE(timedItem->eventDelegate()->phaseChanged());
     EXPECT_FALSE(timedItem->eventDelegate()->iterationChanged());
 
     timedItem->updateInheritedTime(3.6);
-    ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
+    EXPECT_FALSE(timedItem->eventDelegate()->eventTriggered());
 }
 
 TEST(AnimationTimedItemTest, TimeToEffectChange)
 {
     Timing timing;
-    timing.hasIterationDuration = true;
     timing.iterationDuration = 1;
+    timing.fillMode = Timing::FillModeForwards;
     timing.iterationStart = 0.2;
     timing.iterationCount = 2.5;
     timing.startDelay = 1;
@@ -768,13 +786,13 @@
 
     // Item ends before iteration finishes.
     timedItem->updateInheritedTime(3.4);
-    ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
+    EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
     EXPECT_EQ(3.4, timedItem->takeLocalTime());
     EXPECT_TRUE(std::isinf(timedItem->takeTimeToNextIteration()));
 
     // Item has finished.
     timedItem->updateInheritedTime(3.5);
-    ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+    EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
     EXPECT_EQ(3.5, timedItem->takeLocalTime());
     EXPECT_TRUE(std::isinf(timedItem->takeTimeToNextIteration()));
 }
diff --git a/Source/core/animation/TimedItemTiming.cpp b/Source/core/animation/TimedItemTiming.cpp
new file mode 100644
index 0000000..4aa0894
--- /dev/null
+++ b/Source/core/animation/TimedItemTiming.cpp
@@ -0,0 +1,175 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/animation/TimedItemTiming.h"
+
+#include "core/animation/Animation.h"
+#include "core/animation/TimedItem.h"
+#include "platform/animation/TimingFunction.h"
+
+namespace WebCore {
+
+PassRefPtr<TimedItemTiming> TimedItemTiming::create(TimedItem* parent)
+{
+    return adoptRef(new TimedItemTiming(parent));
+}
+
+TimedItemTiming::TimedItemTiming(TimedItem* parent)
+: m_parent(parent)
+{
+}
+
+double TimedItemTiming::delay()
+{
+    return m_parent->specifiedTiming().startDelay;
+}
+
+double TimedItemTiming::endDelay()
+{
+    return m_parent->specifiedTiming().endDelay;
+}
+
+String TimedItemTiming::fill()
+{
+    Timing::FillMode fillMode = m_parent->specifiedTiming().fillMode;
+    switch (fillMode) {
+    case Timing::FillModeNone:
+        return "none";
+    case Timing::FillModeForwards:
+        return "forwards";
+    case Timing::FillModeBackwards:
+        return "backwards";
+    case Timing::FillModeBoth:
+        return "both";
+    case Timing::FillModeAuto:
+        return "auto";
+    }
+    ASSERT_NOT_REACHED();
+    return "auto";
+}
+
+double TimedItemTiming::iterationStart()
+{
+    return m_parent->specifiedTiming().iterationStart;
+}
+
+double TimedItemTiming::iterations()
+{
+    return m_parent->specifiedTiming().iterationCount;
+}
+
+// This logic was copied from the example in bindings/tests/idls/TestInterface.idl
+// and bindings/tests/results/V8TestInterface.cpp.
+// FIXME: It might be possible to have 'duration' defined as an attribute in the idl.
+// If possible, fix will be in a follow-up patch.
+void TimedItemTiming::getDuration(String propertyName, bool& element0Enabled, double& element0, bool& element1Enabled, String& element1)
+{
+    if (propertyName != "duration")
+        return;
+
+    if (std::isnan(m_parent->specifiedTiming().iterationDuration)) {
+        element1Enabled = true;
+        element1 = "auto";
+        return;
+    }
+    element0Enabled = true;
+    element0 = m_parent->specifiedTiming().iterationDuration;
+    return;
+}
+
+double TimedItemTiming::playbackRate()
+{
+    return m_parent->specifiedTiming().playbackRate;
+}
+
+String TimedItemTiming::direction()
+{
+    Timing::PlaybackDirection direction = m_parent->specifiedTiming().direction;
+    switch (direction) {
+    case Timing::PlaybackDirectionNormal:
+        return "normal";
+    case Timing::PlaybackDirectionReverse:
+        return "reverse";
+    case Timing::PlaybackDirectionAlternate:
+        return "alternate";
+    case Timing::PlaybackDirectionAlternateReverse:
+        return "alternate-reverse";
+    }
+    ASSERT_NOT_REACHED();
+    return "normal";
+}
+
+String TimedItemTiming::easing()
+{
+    return m_parent->specifiedTiming().timingFunction->toString();
+}
+
+void TimedItemTiming::setDelay(double delay)
+{
+    Timing timing = m_parent->specifiedTiming();
+    Animation::setStartDelay(timing, delay);
+    m_parent->updateSpecifiedTiming(timing);
+}
+
+void TimedItemTiming::setEndDelay(double endDelay)
+{
+    Timing timing = m_parent->specifiedTiming();
+    Animation::setEndDelay(timing, endDelay);
+    m_parent->updateSpecifiedTiming(timing);
+}
+
+void TimedItemTiming::setFill(String fill)
+{
+    Timing timing = m_parent->specifiedTiming();
+    Animation::setFillMode(timing, fill);
+    m_parent->updateSpecifiedTiming(timing);
+}
+
+void TimedItemTiming::setIterationStart(double iterationStart)
+{
+    Timing timing = m_parent->specifiedTiming();
+    Animation::setIterationStart(timing, iterationStart);
+    m_parent->updateSpecifiedTiming(timing);
+}
+
+void TimedItemTiming::setIterations(double iterations)
+{
+    Timing timing = m_parent->specifiedTiming();
+    Animation::setIterationCount(timing, iterations);
+    m_parent->updateSpecifiedTiming(timing);
+}
+
+bool TimedItemTiming::setDuration(String name, double duration)
+{
+    if (name != "duration")
+        return false;
+    Timing timing = m_parent->specifiedTiming();
+    Animation::setIterationDuration(timing, duration);
+    m_parent->updateSpecifiedTiming(timing);
+    return true;
+}
+
+void TimedItemTiming::setPlaybackRate(double playbackRate)
+{
+    Timing timing = m_parent->specifiedTiming();
+    Animation::setPlaybackRate(timing, playbackRate);
+    m_parent->updateSpecifiedTiming(timing);
+}
+
+void TimedItemTiming::setDirection(String direction)
+{
+    Timing timing = m_parent->specifiedTiming();
+    Animation::setPlaybackDirection(timing, direction);
+    m_parent->updateSpecifiedTiming(timing);
+}
+
+void TimedItemTiming::setEasing(String easing)
+{
+    Timing timing = m_parent->specifiedTiming();
+    Animation::setTimingFunction(timing, easing);
+    m_parent->updateSpecifiedTiming(timing);
+}
+
+} // namespace WebCore
diff --git a/Source/core/animation/TimedItemTiming.h b/Source/core/animation/TimedItemTiming.h
new file mode 100644
index 0000000..699fb41
--- /dev/null
+++ b/Source/core/animation/TimedItemTiming.h
@@ -0,0 +1,44 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef TimedItemTiming_h
+#define TimedItemTiming_h
+
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class TimedItem;
+
+class TimedItemTiming : public RefCounted<TimedItemTiming> {
+public:
+    static PassRefPtr<TimedItemTiming> create(TimedItem* parent);
+    double delay();
+    double endDelay();
+    String fill();
+    double iterationStart();
+    double iterations();
+    void getDuration(String propertyName, bool& element0Enabled, double& element0, bool& element1Enabled, String& element1);
+    double playbackRate();
+    String direction();
+    String easing();
+
+    void setDelay(double);
+    void setEndDelay(double);
+    void setFill(String);
+    void setIterationStart(double);
+    void setIterations(double);
+    bool setDuration(String name, double duration);
+    void setPlaybackRate(double);
+    void setDirection(String);
+    void setEasing(String);
+private:
+    RefPtr<TimedItem> m_parent;
+    TimedItemTiming(TimedItem* parent);
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/Source/core/animation/Timeline.idl b/Source/core/animation/Timeline.idl
new file mode 100644
index 0000000..47138f7
--- /dev/null
+++ b/Source/core/animation/Timeline.idl
@@ -0,0 +1,10 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+    RuntimeEnabled=WebAnimationsAPI,
+    ImplementedAs=DocumentTimeline,
+] interface Timeline {
+    Player play(TimedItem source);
+};
diff --git a/Source/core/animation/Timing.h b/Source/core/animation/Timing.h
index 9a3bc4e..fb2ef09 100644
--- a/Source/core/animation/Timing.h
+++ b/Source/core/animation/Timing.h
@@ -31,7 +31,7 @@
 #ifndef Timing_h
 #define Timing_h
 
-#include "core/platform/animation/TimingFunction.h"
+#include "platform/animation/TimingFunction.h"
 #include "wtf/MathExtras.h"
 #include "wtf/RefPtr.h"
 
@@ -39,6 +39,7 @@
 
 struct Timing {
     enum FillMode {
+        FillModeAuto,
         FillModeNone,
         FillModeForwards,
         FillModeBackwards,
@@ -54,11 +55,11 @@
 
     Timing()
         : startDelay(0)
-        , fillMode(FillModeForwards)
+        , endDelay(0)
+        , fillMode(FillModeAuto)
         , iterationStart(0)
         , iterationCount(1)
-        , hasIterationDuration(false)
-        , iterationDuration(0)
+        , iterationDuration(std::numeric_limits<double>::quiet_NaN())
         , playbackRate(1)
         , direction(PlaybackDirectionNormal)
         , timingFunction(LinearTimingFunction::create())
@@ -68,19 +69,20 @@
     void assertValid() const
     {
         ASSERT(std::isfinite(startDelay));
+        ASSERT(std::isfinite(endDelay));
         ASSERT(std::isfinite(iterationStart));
         ASSERT(iterationStart >= 0);
         ASSERT(iterationCount >= 0);
-        ASSERT(iterationDuration >= 0);
+        ASSERT(std::isnan(iterationDuration) || iterationDuration >= 0);
         ASSERT(std::isfinite(playbackRate));
         ASSERT(timingFunction);
     }
 
     double startDelay;
+    double endDelay;
     FillMode fillMode;
     double iterationStart;
     double iterationCount;
-    bool hasIterationDuration;
     double iterationDuration;
     // FIXME: Add activeDuration.
     double playbackRate;
diff --git a/Source/core/animation/Timing.idl b/Source/core/animation/Timing.idl
new file mode 100644
index 0000000..9da75c5
--- /dev/null
+++ b/Source/core/animation/Timing.idl
@@ -0,0 +1,28 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+    RuntimeEnabled=WebAnimationsAPI,
+    ImplementedAs=TimedItemTiming,
+] interface Timing {
+    attribute double delay;
+    attribute double endDelay;
+    attribute DOMString fill;
+    attribute double iterationStart;
+    attribute double iterations;
+
+    // FIXME: This uses a NamedPropertyGetter to implement the 'duration' attribute
+    // because duration has a union type (which is tricky to do with an attribute).
+    // Fix will be in a follow-up patch if there is a better solution.
+    [NotEnumerable, ImplementedAs=getDuration] getter (double or DOMString) (DOMString name);
+
+    // FIXME: If the user calls animation.specified.duration = "" (empty string) then duration
+    // gets set to 0 (This is correct behavior for IDL). Correct result is for duration to
+    // be set to 'auto'.
+    [StrictTypeChecking, ImplementedAs=setDuration] setter double (DOMString name, double duration);
+
+    attribute double playbackRate;
+    attribute DOMString direction;
+    attribute DOMString easing;
+};
diff --git a/Source/core/animation/css/CSSAnimatableValueFactory.cpp b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
index b9c3ffb..8701a23 100644
--- a/Source/core/animation/css/CSSAnimatableValueFactory.cpp
+++ b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
@@ -68,14 +68,6 @@
         return AnimatableLength::create(adjustFloatForAbsoluteZoom(length.value(), style), AnimatableLength::UnitTypePixels);
     case Percent:
         return AnimatableLength::create(length.value(), AnimatableLength::UnitTypePercentage);
-    case ViewportPercentageWidth:
-        return AnimatableLength::create(length.value(), AnimatableLength::UnitTypeViewportWidth);
-    case ViewportPercentageHeight:
-        return AnimatableLength::create(length.value(), AnimatableLength::UnitTypeViewportHeight);
-    case ViewportPercentageMin:
-        return AnimatableLength::create(length.value(), AnimatableLength::UnitTypeViewportMin);
-    case ViewportPercentageMax:
-        return AnimatableLength::create(length.value(), AnimatableLength::UnitTypeViewportMax);
     case Calculated:
         return AnimatableLength::create(CSSCalcValue::createExpressionNode(length.calculationValue()->expression(), style.effectiveZoom()));
     case Auto:
@@ -89,6 +81,8 @@
     case Undefined:
         return AnimatableUnknown::create(CSSValueNone);
     case ExtendToZoom: // Does not apply to elements.
+    case DeviceWidth:
+    case DeviceHeight:
         ASSERT_NOT_REACHED();
         return 0;
     }
@@ -181,6 +175,17 @@
     }
 }
 
+inline static PassRefPtr<AnimatableValue> createFromBackgroundPosition(const Length& length, bool originIsSet, BackgroundEdgeOrigin origin, const RenderStyle& style)
+{
+    if (!originIsSet || origin == LeftEdge || origin == TopEdge)
+        return createFromLength(length, style);
+
+    return AnimatableLength::create(CSSCalcValue::createExpressionNode(
+        CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(100, CSSPrimitiveValue::CSS_PERCENTAGE), true),
+        CSSCalcValue::createExpressionNode(length, style.effectiveZoom()),
+        CalcSubtract));
+}
+
 template<CSSPropertyID property>
 inline static PassRefPtr<AnimatableValue> createFromFillLayers(const FillLayer* fillLayer, const RenderStyle& style)
 {
@@ -194,11 +199,11 @@
         } else if (property == CSSPropertyBackgroundPositionX || property == CSSPropertyWebkitMaskPositionX) {
             if (!fillLayer->isXPositionSet())
                 break;
-            values.append(createFromLength(fillLayer->xPosition(), style));
+            values.append(createFromBackgroundPosition(fillLayer->xPosition(), fillLayer->isBackgroundXOriginSet(), fillLayer->backgroundXOrigin(), style));
         } else if (property == CSSPropertyBackgroundPositionY || property == CSSPropertyWebkitMaskPositionY) {
             if (!fillLayer->isYPositionSet())
                 break;
-            values.append(createFromLength(fillLayer->yPosition(), style));
+            values.append(createFromBackgroundPosition(fillLayer->yPosition(), fillLayer->isBackgroundYOriginSet(), fillLayer->backgroundYOrigin(), style));
         } else if (property == CSSPropertyBackgroundSize || property == CSSPropertyWebkitMaskSize) {
             if (!fillLayer->isSizeSet())
                 break;
@@ -215,19 +220,7 @@
 {
     Color color = style.colorIncludingFallback(property, false);
     Color visitedLinkColor = style.colorIncludingFallback(property, true);
-    Color fallbackColor = style.color();
-    Color fallbackVisitedLinkColor = style.visitedLinkColor();
-    Color resolvedColor;
-    if (color.isValid())
-        resolvedColor = color;
-    else
-        resolvedColor = fallbackColor;
-    Color resolvedVisitedLinkColor;
-    if (visitedLinkColor.isValid())
-        resolvedVisitedLinkColor = visitedLinkColor;
-    else
-        resolvedVisitedLinkColor = fallbackVisitedLinkColor;
-    return AnimatableColor::create(resolvedColor, resolvedVisitedLinkColor);
+    return AnimatableColor::create(color, visitedLinkColor);
 }
 
 inline static PassRefPtr<AnimatableValue> createFromShapeValue(ShapeValue* value)
@@ -240,6 +233,7 @@
 // FIXME: Generate this function.
 PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::create(CSSPropertyID property, const RenderStyle& style)
 {
+    ASSERT(CSSAnimations::isAnimatableProperty(property));
     switch (property) {
     case CSSPropertyBackgroundColor:
         return createFromColor(property, style);
@@ -386,7 +380,7 @@
     case CSSPropertyStroke:
         return AnimatableSVGPaint::create(style.svgStyle()->strokePaintType(), style.svgStyle()->strokePaintColor(), style.svgStyle()->strokePaintUri());
     case CSSPropertyTextDecorationColor:
-        return createFromColor(property, style);
+        return AnimatableColor::create(style.textDecorationColor().resolve(style.color()), style.visitedLinkTextDecorationColor().resolve(style.visitedLinkColor()));
     case CSSPropertyTextIndent:
         return createFromLength(style.textIndent(), style);
     case CSSPropertyTextShadow:
@@ -466,7 +460,6 @@
     case CSSPropertyZoom:
         return createFromDouble(style.zoom());
     default:
-        ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Create AnimatableValue from render style: %s", getPropertyNameString(property).utf8().data());
         ASSERT_NOT_REACHED();
         // This return value is to avoid a release crash if possible.
         return AnimatableUnknown::create(0);
diff --git a/Source/core/platform/animation/CSSAnimationData.cpp b/Source/core/animation/css/CSSAnimationData.cpp
similarity index 98%
rename from Source/core/platform/animation/CSSAnimationData.cpp
rename to Source/core/animation/css/CSSAnimationData.cpp
index 277944b..d1a9ce9 100644
--- a/Source/core/platform/animation/CSSAnimationData.cpp
+++ b/Source/core/animation/css/CSSAnimationData.cpp
@@ -20,7 +20,7 @@
  */
 
 #include "config.h"
-#include "core/platform/animation/CSSAnimationData.h"
+#include "core/animation/css/CSSAnimationData.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/animation/CSSAnimationData.h b/Source/core/animation/css/CSSAnimationData.h
similarity index 87%
rename from Source/core/platform/animation/CSSAnimationData.h
rename to Source/core/animation/css/CSSAnimationData.h
index 7f6e79a..01eeb6f 100644
--- a/Source/core/platform/animation/CSSAnimationData.h
+++ b/Source/core/animation/css/CSSAnimationData.h
@@ -26,8 +26,8 @@
 #define CSSAnimationData_h
 
 #include "CSSPropertyNames.h"
-#include "core/platform/animation/TimingFunction.h"
 #include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/animation/TimingFunction.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
@@ -64,11 +64,6 @@
                 && !m_delaySet && !m_timingFunctionSet && !m_propertySet);
     }
 
-    bool isEmptyOrZeroDuration() const
-    {
-        return isEmpty() || (m_duration == 0 && m_delay <= 0);
-    }
-
     void clearDelay() { m_delaySet = false; }
     void clearDirection() { m_directionSet = false; }
     void clearDuration() { m_durationSet = false; }
@@ -107,7 +102,6 @@
         AnimationDirectionAlternateReverse
     };
     AnimationDirection direction() const { return static_cast<AnimationDirection>(m_direction); }
-    bool directionIsForwards() const { return m_direction == AnimationDirectionNormal || m_direction == AnimationDirectionAlternate; }
 
     unsigned fillMode() const { return m_fillMode; }
 
@@ -134,15 +128,12 @@
 
     void setIsNoneAnimation(bool n) { m_isNone = n; }
 
-    CSSAnimationData& operator=(const CSSAnimationData& o);
+    CSSAnimationData& operator=(const CSSAnimationData&);
 
     // return true every CSSAnimationData in the chain (defined by m_next) match
     bool operator==(const CSSAnimationData& o) const { return animationsMatchForStyleRecalc(&o); }
     bool operator!=(const CSSAnimationData& o) const { return !(*this == o); }
 
-    bool fillsBackwards() const { return m_fillModeSet && (m_fillMode == AnimationFillModeBackwards || m_fillMode == AnimationFillModeBoth); }
-    bool fillsForwards() const { return m_fillModeSet && (m_fillMode == AnimationFillModeForwards || m_fillMode == AnimationFillModeBoth); }
-
 private:
     CSSAnimationData();
     explicit CSSAnimationData(const CSSAnimationData&);
@@ -163,17 +154,17 @@
 
     unsigned m_playState     : 2;
 
-    bool m_delaySet          : 1;
-    bool m_directionSet      : 1;
-    bool m_durationSet       : 1;
-    bool m_fillModeSet       : 1;
-    bool m_iterationCountSet : 1;
-    bool m_nameSet           : 1;
-    bool m_playStateSet      : 1;
-    bool m_propertySet       : 1;
-    bool m_timingFunctionSet : 1;
+    unsigned m_delaySet          : 1;
+    unsigned m_directionSet      : 1;
+    unsigned m_durationSet       : 1;
+    unsigned m_fillModeSet       : 1;
+    unsigned m_iterationCountSet : 1;
+    unsigned m_nameSet           : 1;
+    unsigned m_playStateSet      : 1;
+    unsigned m_propertySet       : 1;
+    unsigned m_timingFunctionSet : 1;
 
-    bool m_isNone            : 1;
+    unsigned m_isNone            : 1;
 
 public:
     static double initialAnimationDelay() { return 0; }
diff --git a/Source/core/platform/animation/CSSAnimationDataList.cpp b/Source/core/animation/css/CSSAnimationDataList.cpp
similarity index 97%
rename from Source/core/platform/animation/CSSAnimationDataList.cpp
rename to Source/core/animation/css/CSSAnimationDataList.cpp
index 5170e76..e130d93 100644
--- a/Source/core/platform/animation/CSSAnimationDataList.cpp
+++ b/Source/core/animation/css/CSSAnimationDataList.cpp
@@ -20,7 +20,7 @@
  */
 
 #include "config.h"
-#include "core/platform/animation/CSSAnimationDataList.h"
+#include "core/animation/css/CSSAnimationDataList.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/animation/CSSAnimationDataList.h b/Source/core/animation/css/CSSAnimationDataList.h
similarity index 94%
rename from Source/core/platform/animation/CSSAnimationDataList.h
rename to Source/core/animation/css/CSSAnimationDataList.h
index 48d8556..03a4ef0 100644
--- a/Source/core/platform/animation/CSSAnimationDataList.h
+++ b/Source/core/animation/css/CSSAnimationDataList.h
@@ -25,7 +25,7 @@
 #ifndef CSSAnimationDataList_h
 #define CSSAnimationDataList_h
 
-#include "core/platform/animation/CSSAnimationData.h"
+#include "core/animation/css/CSSAnimationData.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
 
@@ -38,7 +38,7 @@
     explicit CSSAnimationDataList(const CSSAnimationDataList&);
 
     void fillUnsetProperties();
-    bool operator==(const CSSAnimationDataList& o) const;
+    bool operator==(const CSSAnimationDataList&) const;
     bool operator!=(const CSSAnimationDataList& o) const
     {
         return !(*this == o);
diff --git a/Source/core/animation/css/CSSAnimations.cpp b/Source/core/animation/css/CSSAnimations.cpp
index f98c265..6b4179a 100644
--- a/Source/core/animation/css/CSSAnimations.cpp
+++ b/Source/core/animation/css/CSSAnimations.cpp
@@ -35,8 +35,10 @@
 #include "core/animation/ActiveAnimations.h"
 #include "core/animation/CompositorAnimations.h"
 #include "core/animation/DocumentTimeline.h"
-#include "core/animation/KeyframeAnimationEffect.h"
+#include "core/animation/KeyframeEffectModel.h"
 #include "core/animation/css/CSSAnimatableValueFactory.h"
+#include "core/animation/css/CSSAnimationDataList.h"
+#include "core/animation/css/CSSPropertyAnimation.h"
 #include "core/css/CSSKeyframeRule.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Element.h"
@@ -45,11 +47,10 @@
 #include "core/events/TransitionEvent.h"
 #include "core/events/WebKitAnimationEvent.h"
 #include "core/frame/UseCounter.h"
-#include "core/frame/animation/CSSPropertyAnimation.h"
-#include "core/platform/animation/CSSAnimationDataList.h"
-#include "core/platform/animation/TimingFunction.h"
+#include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/style/KeyframeList.h"
+#include "platform/animation/TimingFunction.h"
 #include "public/platform/Platform.h"
 #include "wtf/BitArray.h"
 #include "wtf/HashSet.h"
@@ -72,7 +73,7 @@
     return target > reference;
 }
 
-static PassRefPtr<TimingFunction> generateTimingFunction(const KeyframeAnimationEffect::KeyframeVector keyframes, const HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions)
+static PassRefPtr<TimingFunction> generateTimingFunction(const KeyframeEffectModel::KeyframeVector keyframes, const HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions)
 {
     // Generate the chained timing function. Note that timing functions apply
     // from the keyframe in which they're specified to the next keyframe.
@@ -92,11 +93,12 @@
     return chainedTimingFunction;
 }
 
-static void resolveKeyframes(StyleResolver* resolver, Element* element, const RenderStyle& style, const AtomicString& name, TimingFunction* defaultTimingFunction,
-    Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > >& keyframesAndTimingFunctions)
+static void resolveKeyframes(StyleResolver* resolver, Element* element, const Element& parentElement, const RenderStyle& style, RenderStyle* parentStyle, const AtomicString& name, TimingFunction* defaultTimingFunction,
+    Vector<std::pair<KeyframeEffectModel::KeyframeVector, RefPtr<TimingFunction> > >& keyframesAndTimingFunctions)
 {
-    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
-    const StyleRuleKeyframes* keyframesRule = CSSAnimations::matchScopedKeyframesRule(resolver, element, name.impl());
+    // When the element is null, use its parent for scoping purposes.
+    const Element* elementForScoping = element ? element : &parentElement;
+    const StyleRuleKeyframes* keyframesRule = CSSAnimations::matchScopedKeyframesRule(resolver, elementForScoping, name.impl());
     if (!keyframesRule)
         return;
 
@@ -106,11 +108,12 @@
 
     // Construct and populate the style for each keyframe
     PropertySet specifiedProperties;
-    KeyframeAnimationEffect::KeyframeVector keyframes;
+    KeyframeEffectModel::KeyframeVector keyframes;
     HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions;
     for (size_t i = 0; i < styleKeyframes.size(); ++i) {
         const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
-        RefPtr<RenderStyle> keyframeStyle = resolver->styleForKeyframe(element, style, styleKeyframe, name);
+        // It's OK to pass a null element here.
+        RefPtr<RenderStyle> keyframeStyle = resolver->styleForKeyframe(element, style, parentStyle, styleKeyframe, name);
         RefPtr<Keyframe> keyframe = Keyframe::create();
         const Vector<double>& offsets = styleKeyframe->keys();
         ASSERT(!offsets.isEmpty());
@@ -221,7 +224,7 @@
         ASSERT(count <= numKeyframes);
         if (count == numKeyframes)
             continue;
-        KeyframeAnimationEffect::KeyframeVector splitOutKeyframes;
+        KeyframeEffectModel::KeyframeVector splitOutKeyframes;
         for (size_t i = 0; i < numKeyframes; i++) {
             Keyframe* keyframe = keyframes[i].get();
             if (!keyframe->properties().contains(property)) {
@@ -265,10 +268,8 @@
 {
     if (animationData->isDelaySet())
         timing.startDelay = animationData->delay();
-    if (animationData->isDurationSet()) {
+    if (animationData->isDurationSet())
         timing.iterationDuration = animationData->duration();
-        timing.hasIterationDuration = true;
-    }
     if (animationData->isIterationCountSet()) {
         if (animationData->iterationCount() == CSSAnimationData::IterationCountInfinite)
             timing.iterationCount = std::numeric_limits<double>::infinity();
@@ -319,7 +320,7 @@
     timing.assertValid();
     ASSERT(!timing.iterationStart);
     ASSERT(timing.playbackRate == 1);
-    ASSERT(timing.iterationDuration >= 0 && std::isfinite(timing.iterationDuration));
+    ASSERT(!std::isinf(timing.iterationDuration));
 
     isPaused = animationData->isPlayStateSet() && animationData->playState() == AnimPlayStatePaused;
     return animationData->isTimingFunctionSet() ? animationData->timingFunction() : CSSAnimationData::initialAnimationTimingFunction();
@@ -344,21 +345,29 @@
     return 0;
 }
 
-PassOwnPtr<CSSAnimationUpdate> CSSAnimations::calculateUpdate(Element* element, const RenderStyle& style, StyleResolver* resolver)
+PassOwnPtr<CSSAnimationUpdate> CSSAnimations::calculateUpdate(Element* element, const Element& parentElement, const RenderStyle& style, RenderStyle* parentStyle, StyleResolver* resolver)
 {
-    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
     OwnPtr<CSSAnimationUpdate> update = adoptPtr(new CSSAnimationUpdate());
-    calculateAnimationUpdate(update.get(), element, style, resolver);
+    calculateAnimationUpdate(update.get(), element, parentElement, style, parentStyle, resolver);
     calculateAnimationCompositableValues(update.get(), element);
     calculateTransitionUpdate(update.get(), element, style);
     calculateTransitionCompositableValues(update.get(), element);
     return update->isEmpty() ? nullptr : update.release();
 }
 
-void CSSAnimations::calculateAnimationUpdate(CSSAnimationUpdate* update, Element* element, const RenderStyle& style, StyleResolver* resolver)
+void CSSAnimations::calculateAnimationUpdate(CSSAnimationUpdate* update, Element* element, const Element& parentElement, const RenderStyle& style, RenderStyle* parentStyle, StyleResolver* resolver)
 {
+    const ActiveAnimations* activeAnimations = element ? element->activeAnimations() : 0;
+
+#if ASSERT_DISABLED
+    // If we're in an animation style change, no animations can have started, been cancelled or changed play state.
+    // When ASSERT is enabled, we verify this optimization.
+    if (activeAnimations && activeAnimations->isAnimationStyleChange())
+        return;
+#endif
+
     const CSSAnimationDataList* animationDataList = style.animations();
-    const CSSAnimations* cssAnimations = element->activeAnimations() ? &element->activeAnimations()->cssAnimations() : 0;
+    const CSSAnimations* cssAnimations = activeAnimations ? &activeAnimations->cssAnimations() : 0;
 
     HashSet<AtomicString> inactive;
     if (cssAnimations)
@@ -387,8 +396,10 @@
                     for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter)
                         ASSERT((*iter)->paused() == isFirstPlayerPaused);
 #endif
-                    if ((animationData->playState() == AnimPlayStatePaused) != isFirstPlayerPaused)
+                    if ((animationData->playState() == AnimPlayStatePaused) != isFirstPlayerPaused) {
+                        ASSERT(!activeAnimations || !activeAnimations->isAnimationStyleChange());
                         update->toggleAnimationPaused(animationName);
+                    }
                     continue;
                 }
             }
@@ -396,24 +407,27 @@
             Timing timing;
             bool isPaused;
             RefPtr<TimingFunction> defaultTimingFunction = timingFromAnimationData(animationData, timing, isPaused);
-            Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > > keyframesAndTimingFunctions;
-            resolveKeyframes(resolver, element, style, animationName, defaultTimingFunction.get(), keyframesAndTimingFunctions);
+            Vector<std::pair<KeyframeEffectModel::KeyframeVector, RefPtr<TimingFunction> > > keyframesAndTimingFunctions;
+            resolveKeyframes(resolver, element, parentElement, style, parentStyle, animationName, defaultTimingFunction.get(), keyframesAndTimingFunctions);
             if (!keyframesAndTimingFunctions.isEmpty()) {
                 HashSet<RefPtr<InertAnimation> > animations;
                 for (size_t j = 0; j < keyframesAndTimingFunctions.size(); ++j) {
                     ASSERT(!keyframesAndTimingFunctions[j].first.isEmpty());
                     timing.timingFunction = keyframesAndTimingFunctions[j].second;
-                    // FIXME: crbug.com/268791 - Keyframes are already normalized, perhaps there should be a flag on KeyframeAnimationEffect to skip normalization.
-                    animations.add(InertAnimation::create(KeyframeAnimationEffect::create(keyframesAndTimingFunctions[j].first), timing, isPaused));
+                    // FIXME: crbug.com/268791 - Keyframes are already normalized, perhaps there should be a flag on KeyframeEffectModel to skip normalization.
+                    animations.add(InertAnimation::create(KeyframeEffectModel::create(keyframesAndTimingFunctions[j].first), timing, isPaused));
                 }
+                ASSERT(!activeAnimations || !activeAnimations->isAnimationStyleChange());
                 update->startAnimation(animationName, animations);
             }
         }
     }
 
     ASSERT(inactive.isEmpty() || cssAnimations);
-    for (HashSet<AtomicString>::const_iterator iter = inactive.begin(); iter != inactive.end(); ++iter)
+    for (HashSet<AtomicString>::const_iterator iter = inactive.begin(); iter != inactive.end(); ++iter) {
+        ASSERT(!activeAnimations || !activeAnimations->isAnimationStyleChange());
         update->cancelAnimation(*iter, cssAnimations->m_animations.get(*iter));
+    }
 }
 
 void CSSAnimations::maybeApplyPendingUpdate(Element* element)
@@ -427,6 +441,11 @@
 
     m_previousCompositableValuesForAnimations.swap(update->compositableValuesForAnimations());
 
+    // FIXME: cancelling, pausing, unpausing animations all query compositingState, which is not necessarily up to date here
+    // since we call this from recalc style.
+    // https://code.google.com/p/chromium/issues/detail?id=339847
+    DisableCompositingQueryAsserts disabler;
+
     for (Vector<AtomicString>::const_iterator iter = update->cancelledAnimationNames().begin(); iter != update->cancelledAnimationNames().end(); ++iter) {
         const HashSet<RefPtr<Player> >& players = m_animations.take(*iter);
         for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter)
@@ -440,7 +459,10 @@
         for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter) {
             Player* player = iter->get();
             ASSERT(player->paused() == isFirstPlayerPaused);
-            player->setPaused(!isFirstPlayerPaused);
+            if (isFirstPlayerPaused)
+                player->unpause();
+            else
+                player->pause();
         }
     }
 
@@ -451,9 +473,10 @@
             const InertAnimation* inertAnimation = animationsIter->get();
             // The event delegate is set on the the first animation only. We
             // rely on the behavior of OwnPtr::release() to achieve this.
-            RefPtr<Animation> animation = Animation::create(element, inertAnimation->effect(), inertAnimation->specified(), Animation::DefaultPriority, eventDelegate.release());
+            RefPtr<Animation> animation = Animation::create(element, inertAnimation->effect(), inertAnimation->specifiedTiming(), Animation::DefaultPriority, eventDelegate.release());
             Player* player = element->document().timeline()->createPlayer(animation.get());
-            player->setPaused(inertAnimation->paused());
+            if (inertAnimation->paused())
+                player->pause();
             element->document().cssPendingAnimations().add(player);
             player->update();
             players.add(player);
@@ -496,9 +519,9 @@
             double oldStartTime = oldTransition.second;
             double inheritedTime = isNull(oldStartTime) ? 0 : element->document().transitionTimeline()->currentTime() - oldStartTime;
             oldAnimation->updateInheritedTime(inheritedTime);
-            KeyframeAnimationEffect* oldEffect = toKeyframeAnimationEffect(inertAnimation->effect());
-            const KeyframeAnimationEffect::KeyframeVector& frames = oldEffect->getFrames();
-            KeyframeAnimationEffect::KeyframeVector newFrames;
+            KeyframeEffectModel* oldEffect = toKeyframeEffectModel(inertAnimation->effect());
+            const KeyframeEffectModel::KeyframeVector& frames = oldEffect->getFrames();
+            KeyframeEffectModel::KeyframeVector newFrames;
             newFrames.append(frames[0]->clone());
             newFrames[0]->clearPropertyValue(id);
             ASSERT(oldAnimation->compositableValues()->size() == 1);
@@ -506,9 +529,9 @@
             ASSERT(!compositableValue->dependsOnUnderlyingValue());
             newFrames[0]->setPropertyValue(id, compositableValue->compositeOnto(0).get());
             newFrames.append(frames[1]->clone());
-            effect = KeyframeAnimationEffect::create(newFrames);
+            effect = KeyframeEffectModel::create(newFrames);
         }
-        RefPtr<Animation> transition = Animation::create(element, effect, inertAnimation->specified(), Animation::TransitionPriority, eventDelegate.release());
+        RefPtr<Animation> transition = Animation::create(element, effect, inertAnimation->specifiedTiming(), Animation::TransitionPriority, eventDelegate.release());
         RefPtr<Player> player = element->document().transitionTimeline()->createPlayer(transition.get());
         player->update();
         element->document().cssPendingAnimations().add(player.get());
@@ -521,14 +544,11 @@
 
 void CSSAnimations::calculateTransitionUpdateForProperty(CSSPropertyID id, const CSSAnimationData* anim, const RenderStyle& oldStyle, const RenderStyle& style, const TransitionMap* activeTransitions, CSSAnimationUpdate* update, const Element* element)
 {
-    if (CSSPropertyAnimation::propertiesEqual(id, &oldStyle, &style))
-        return;
-
-    RefPtr<AnimatableValue> to = CSSAnimatableValueFactory::create(id, style);
-
+    RefPtr<AnimatableValue> to;
     if (activeTransitions) {
         TransitionMap::const_iterator activeTransitionIter = activeTransitions->find(id);
         if (activeTransitionIter != activeTransitions->end()) {
+            to = CSSAnimatableValueFactory::create(id, style);
             const AnimatableValue* activeTo = activeTransitionIter->value.to;
             if (to->equals(activeTo))
                 return;
@@ -537,13 +557,21 @@
         }
     }
 
+    if (anim->duration() + anim->delay() <= 0)
+        return;
+
+    if (CSSPropertyAnimation::propertiesEqual(id, &oldStyle, &style))
+        return;
+    if (!to)
+        to = CSSAnimatableValueFactory::create(id, style);
+
     RefPtr<AnimatableValue> from = CSSAnimatableValueFactory::create(id, oldStyle);
     // If we have multiple transitions on the same property, we will use the
     // last one since we iterate over them in order.
-    if (!from->usesNonDefaultInterpolationWith(to.get()))
+    if (AnimatableValue::usesDefaultInterpolation(to.get(), from.get()))
         return;
 
-    KeyframeAnimationEffect::KeyframeVector keyframes;
+    KeyframeEffectModel::KeyframeVector keyframes;
 
     RefPtr<Keyframe> startKeyframe = Keyframe::create();
     startKeyframe->setPropertyValue(id, from.get());
@@ -555,7 +583,7 @@
     endKeyframe->setOffset(1);
     keyframes.append(endKeyframe);
 
-    RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
+    RefPtr<KeyframeEffectModel> effect = KeyframeEffectModel::create(keyframes);
 
     Timing timing;
     bool isPaused;
@@ -571,11 +599,14 @@
 
 void CSSAnimations::calculateTransitionUpdate(CSSAnimationUpdate* update, const Element* element, const RenderStyle& style)
 {
+    if (!element)
+        return;
+
     ActiveAnimations* activeAnimations = element->activeAnimations();
     const TransitionMap* activeTransitions = activeAnimations ? &activeAnimations->cssAnimations().m_transitions : 0;
 
 #if ASSERT_DISABLED
-    // In release builds we avoid the cost of populating and testing listedProperties if the style recalc is due to animation.
+    // In release builds we avoid the cost of checking for new and interrupted transitions if the style recalc is due to animation.
     const bool animationStyleRecalc = activeAnimations && activeAnimations->isAnimationStyleChange();
 #else
     // In debug builds we verify that it would have been safe to avoid populating and testing listedProperties if the style recalc is due to animation.
@@ -591,7 +622,7 @@
         for (size_t i = 0; i < style.transitions()->size(); ++i) {
             const CSSAnimationData* anim = style.transitions()->animation(i);
             CSSAnimationData::AnimationMode mode = anim->animationMode();
-            if (anim->duration() + anim->delay() <= 0 || mode == CSSAnimationData::AnimateNone)
+            if (mode == CSSAnimationData::AnimateNone)
                 continue;
 
             bool animateAll = mode == CSSAnimationData::AnimateAll;
@@ -650,7 +681,7 @@
 
 void CSSAnimations::calculateAnimationCompositableValues(CSSAnimationUpdate* update, const Element* element)
 {
-    ActiveAnimations* activeAnimations = element->activeAnimations();
+    ActiveAnimations* activeAnimations = element ? element->activeAnimations() : 0;
     AnimationStack* animationStack = activeAnimations ? &activeAnimations->defaultStack() : 0;
 
     if (update->newAnimations().isEmpty() && update->cancelledAnimationPlayers().isEmpty()) {
@@ -671,7 +702,7 @@
 
 void CSSAnimations::calculateTransitionCompositableValues(CSSAnimationUpdate* update, const Element* element)
 {
-    ActiveAnimations* activeAnimations = element->activeAnimations();
+    ActiveAnimations* activeAnimations = element ? element->activeAnimations() : 0;
     AnimationStack* animationStack = activeAnimations ? &activeAnimations->defaultStack() : 0;
 
     AnimationEffect::CompositableValueMap compositableValuesForTransitions;
@@ -726,13 +757,13 @@
         // between a single pair of samples. See http://crbug.com/275263. For
         // compatibility with the existing implementation, this event uses
         // the elapsedTime for the first iteration in question.
-        ASSERT(timedItem->specified().hasIterationDuration);
-        const double elapsedTime = timedItem->specified().iterationDuration * (previousIteration + 1);
+        ASSERT(!std::isnan(timedItem->specifiedTiming().iterationDuration));
+        const double elapsedTime = timedItem->specifiedTiming().iterationDuration * (previousIteration + 1);
         maybeDispatch(Document::ANIMATIONITERATION_LISTENER, EventTypeNames::animationiteration, elapsedTime);
         return;
     }
     if ((isFirstSample || previousPhase == TimedItem::PhaseBefore) && isLaterPhase(currentPhase, TimedItem::PhaseBefore)) {
-        ASSERT(timedItem->specified().startDelay > 0 || isFirstSample);
+        ASSERT(timedItem->specifiedTiming().startDelay > 0 || isFirstSample);
         // The spec states that the elapsed time should be
         // 'delay < 0 ? -delay : 0', but we always use 0 to match the existing
         // implementation. See crbug.com/279611
@@ -751,7 +782,7 @@
     const TimedItem::Phase currentPhase = timedItem->phase();
     if (currentPhase == TimedItem::PhaseAfter && (isFirstSample || previousPhase != currentPhase) && m_target->document().hasListenerType(Document::TRANSITIONEND_LISTENER)) {
         String propertyName = getPropertyNameString(m_property);
-        const Timing& timing = timedItem->specified();
+        const Timing& timing = timedItem->specifiedTiming();
         double elapsedTime = timing.iterationDuration;
         const AtomicString& eventType = EventTypeNames::transitionend;
         String pseudoElement = PseudoElement::pseudoElementNameForEvents(m_target->pseudoId());
@@ -873,11 +904,6 @@
     case CSSPropertyZIndex:
     case CSSPropertyZoom:
         return true;
-    // FIXME: Shorthands should not be present in this list, but
-    // CSSPropertyAnimation implements animation of these shorthands
-    // directly and makes use of this method.
-    case CSSPropertyFlex:
-        return !RuntimeEnabledFeatures::webAnimationsCSSEnabled();
     default:
         return false;
     }
diff --git a/Source/core/animation/css/CSSAnimations.h b/Source/core/animation/css/CSSAnimations.h
index aacca5d..22b7a1f 100644
--- a/Source/core/animation/css/CSSAnimations.h
+++ b/Source/core/animation/css/CSSAnimations.h
@@ -34,9 +34,9 @@
 #include "core/animation/Animation.h"
 #include "core/animation/InertAnimation.h"
 #include "core/animation/Player.h"
+#include "core/animation/css/CSSAnimationData.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/Document.h"
-#include "core/platform/animation/CSSAnimationData.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "wtf/HashMap.h"
 #include "wtf/Vector.h"
@@ -149,7 +149,7 @@
     static const StylePropertyShorthand& animatableProperties();
     // FIXME: This should take a const ScopedStyleTree instead of a StyleResolver.
     // We should also change the Element* to a const Element*
-    static PassOwnPtr<CSSAnimationUpdate> calculateUpdate(Element*, const RenderStyle&, StyleResolver*);
+    static PassOwnPtr<CSSAnimationUpdate> calculateUpdate(Element*, const Element& parentElement, const RenderStyle&, RenderStyle* parentStyle, StyleResolver*);
 
     void setPendingUpdate(PassOwnPtr<CSSAnimationUpdate> update) { m_pendingUpdate = update; }
     void maybeApplyPendingUpdate(Element*);
@@ -174,7 +174,7 @@
 
     AnimationEffect::CompositableValueMap m_previousCompositableValuesForAnimations;
 
-    static void calculateAnimationUpdate(CSSAnimationUpdate*, Element*, const RenderStyle&, StyleResolver*);
+    static void calculateAnimationUpdate(CSSAnimationUpdate*, Element*, const Element& parentElement, const RenderStyle&, RenderStyle* parentStyle, StyleResolver*);
     static void calculateTransitionUpdate(CSSAnimationUpdate*, const Element*, const RenderStyle&);
     static void calculateTransitionUpdateForProperty(CSSPropertyID, const CSSAnimationData*, const RenderStyle& oldStyle, const RenderStyle&, const TransitionMap* activeTransitions, CSSAnimationUpdate*, const Element*);
 
diff --git a/Source/core/animation/css/CSSPendingAnimations.cpp b/Source/core/animation/css/CSSPendingAnimations.cpp
index 3a4ec03..eac01ad 100644
--- a/Source/core/animation/css/CSSPendingAnimations.cpp
+++ b/Source/core/animation/css/CSSPendingAnimations.cpp
@@ -34,6 +34,7 @@
 #include "core/animation/Animation.h"
 #include "core/animation/DocumentTimeline.h"
 #include "core/frame/FrameView.h"
+#include "core/rendering/RenderLayer.h"
 
 namespace WebCore {
 
@@ -43,12 +44,16 @@
     // The actual start time is either this value, or the time that
     // this animation, or an animation that it is synchronized with
     // is started on the compositor.
-    const double defaultStartTime = player->timeline().currentTime();
+    const double defaultStartTime = player->timeline()->currentTime();
     m_pending.append(std::make_pair(player, defaultStartTime));
 }
 
 bool CSSPendingAnimations::startPendingAnimations()
 {
+    // FIXME: This is called from within style recalc, at which point compositor state is not up to date.
+    // https://code.google.com/p/chromium/issues/detail?id=339847
+    DisableCompositingQueryAsserts disabler;
+
     bool startedOnCompositor = false;
     for (size_t i = 0; i < m_pending.size(); ++i) {
         if (m_pending[i].first->maybeStartAnimationOnCompositor())
@@ -62,8 +67,10 @@
         for (size_t i = 0; i < m_pending.size(); ++i)
             m_waitingForCompositorAnimationStart.append(m_pending[i].first);
     } else {
-        for (size_t i = 0; i < m_pending.size(); ++i)
+        for (size_t i = 0; i < m_pending.size(); ++i) {
             m_pending[i].first->setStartTime(m_pending[i].second);
+            m_pending[i].first->update();
+        }
     }
     m_pending.clear();
 
@@ -85,7 +92,8 @@
 {
     for (size_t i = 0; i < m_waitingForCompositorAnimationStart.size(); ++i) {
         Player* player = m_waitingForCompositorAnimationStart[i].get();
-        player->setStartTime(monotonicAnimationStartTime - player->timeline().zeroTime());
+        player->setStartTime(monotonicAnimationStartTime - player->timeline()->zeroTime());
+        player->update();
     }
 
     m_waitingForCompositorAnimationStart.clear();
diff --git a/Source/core/animation/css/CSSPendingAnimations.h b/Source/core/animation/css/CSSPendingAnimations.h
index 1bb3c28..ae04fc5 100644
--- a/Source/core/animation/css/CSSPendingAnimations.h
+++ b/Source/core/animation/css/CSSPendingAnimations.h
@@ -31,11 +31,12 @@
 #ifndef CSSPendingAnimations_h
 #define CSSPendingAnimations_h
 
-#include "core/animation/Player.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
+class Player;
+
 // Used to synchronize the start of main-thread animations with compositor
 // animations when both classes of CSS Animations are triggered by the same recalc
 class CSSPendingAnimations FINAL {
diff --git a/Source/core/animation/css/CSSPropertyAnimation.cpp b/Source/core/animation/css/CSSPropertyAnimation.cpp
new file mode 100644
index 0000000..bfc0885
--- /dev/null
+++ b/Source/core/animation/css/CSSPropertyAnimation.cpp
@@ -0,0 +1,610 @@
+/*
+ * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2012 Adobe Systems Incorporated. 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.
+ * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ *     its contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
+ */
+
+#include "config.h"
+#include "core/animation/css/CSSPropertyAnimation.h"
+
+#include <algorithm>
+#include "StylePropertyShorthand.h"
+#include "core/animation/css/CSSAnimations.h"
+#include "core/css/CSSCrossfadeValue.h"
+#include "core/css/CSSImageValue.h"
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/fetch/ImageResource.h"
+#include "core/rendering/ClipPathOperation.h"
+#include "core/rendering/RenderBox.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/style/ShadowList.h"
+#include "core/rendering/style/StyleFetchedImage.h"
+#include "core/rendering/style/StyleGeneratedImage.h"
+#include "platform/FloatConversion.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class AnimationPropertyWrapperBase {
+    WTF_MAKE_NONCOPYABLE(AnimationPropertyWrapperBase);
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    AnimationPropertyWrapperBase(CSSPropertyID prop)
+        : m_prop(prop)
+    {
+    }
+
+    virtual ~AnimationPropertyWrapperBase() { }
+
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const = 0;
+
+    CSSPropertyID property() const { return m_prop; }
+
+private:
+    CSSPropertyID m_prop;
+};
+
+static int gPropertyWrapperMap[numCSSProperties];
+static const int cInvalidPropertyWrapperIndex = -1;
+static Vector<AnimationPropertyWrapperBase*>* gPropertyWrappers = 0;
+
+static AnimationPropertyWrapperBase* wrapperForProperty(CSSPropertyID propertyID)
+{
+    int propIndex = propertyID - firstCSSProperty;
+    if (propIndex >= 0 && propIndex < numCSSProperties) {
+        int wrapperIndex = gPropertyWrapperMap[propIndex];
+        if (wrapperIndex >= 0)
+            return (*gPropertyWrappers)[wrapperIndex];
+    }
+    return 0;
+}
+
+template <typename T>
+class PropertyWrapperGetter : public AnimationPropertyWrapperBase {
+public:
+    PropertyWrapperGetter(CSSPropertyID prop, T (RenderStyle::*getter)() const)
+        : AnimationPropertyWrapperBase(prop)
+        , m_getter(getter)
+    {
+    }
+
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+    {
+        // If the style pointers are the same, don't bother doing the test.
+        // If either is null, return false. If both are null, return true.
+        if ((!a && !b) || a == b)
+            return true;
+        if (!a || !b)
+            return false;
+        return (a->*m_getter)() == (b->*m_getter)();
+    }
+
+protected:
+    T (RenderStyle::*m_getter)() const;
+};
+
+template <typename T>
+class PropertyWrapper : public PropertyWrapperGetter<T> {
+public:
+    PropertyWrapper(CSSPropertyID prop, T (RenderStyle::*getter)() const)
+        : PropertyWrapperGetter<T>(prop, getter)
+    {
+    }
+};
+
+template <typename T>
+class RefCountedPropertyWrapper : public PropertyWrapperGetter<T*> {
+public:
+    RefCountedPropertyWrapper(CSSPropertyID prop, T* (RenderStyle::*getter)() const)
+        : PropertyWrapperGetter<T*>(prop, getter)
+    {
+    }
+
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const OVERRIDE
+    {
+        if (a == b)
+            return true;
+        if (!a || !b)
+            return false;
+        const T* aValue = (a->*this->m_getter)();
+        const T* bValue = (b->*this->m_getter)();
+        if (aValue == bValue)
+            return true;
+        if (!aValue || !bValue)
+            return false;
+        return *aValue == *bValue;
+    }
+};
+
+
+class StyleImagePropertyWrapper FINAL : public RefCountedPropertyWrapper<StyleImage> {
+public:
+    StyleImagePropertyWrapper(CSSPropertyID prop, StyleImage* (RenderStyle::*getter)() const)
+        : RefCountedPropertyWrapper<StyleImage>(prop, getter)
+    {
+    }
+
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const OVERRIDE
+    {
+       // If the style pointers are the same, don't bother doing the test.
+       // If either is null, return false. If both are null, return true.
+       if (a == b)
+           return true;
+       if (!a || !b)
+            return false;
+
+        StyleImage* imageA = (a->*m_getter)();
+        StyleImage* imageB = (b->*m_getter)();
+        return StyleImage::imagesEquivalent(imageA, imageB);
+    }
+};
+
+class PropertyWrapperShadow FINAL : public AnimationPropertyWrapperBase {
+public:
+    PropertyWrapperShadow(CSSPropertyID prop, ShadowList* (RenderStyle::*getter)() const)
+        : AnimationPropertyWrapperBase(prop)
+        , m_getter(getter)
+    {
+    }
+
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const OVERRIDE
+    {
+        const ShadowList* shadowA = (a->*m_getter)();
+        const ShadowList* shadowB = (b->*m_getter)();
+        if (shadowA == shadowB)
+            return true;
+        if (shadowA && shadowB)
+            return *shadowA == *shadowB;
+        return false;
+    }
+
+    ShadowList* (RenderStyle::*m_getter)() const;
+};
+
+class PropertyWrapperMaybeInvalidStyleColor FINAL : public AnimationPropertyWrapperBase {
+public:
+    PropertyWrapperMaybeInvalidStyleColor(CSSPropertyID prop, StyleColor (RenderStyle::*getter)() const)
+        : AnimationPropertyWrapperBase(prop)
+        , m_getter(getter)
+    {
+    }
+
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const OVERRIDE
+    {
+        StyleColor fromColor = (a->*m_getter)();
+        StyleColor toColor = (b->*m_getter)();
+
+        if (fromColor.isCurrentColor() && toColor.isCurrentColor())
+            return true;
+
+        return fromColor.resolve(a->color()) == toColor.resolve(b->color());
+    }
+
+private:
+    StyleColor (RenderStyle::*m_getter)() const;
+};
+
+
+class PropertyWrapperVisitedAffectedColor FINAL : public AnimationPropertyWrapperBase {
+public:
+    PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, Color (RenderStyle::*visitedGetter)() const)
+        : AnimationPropertyWrapperBase(prop)
+        , m_wrapper(adoptPtr(new PropertyWrapper<Color>(prop, getter)))
+        , m_visitedWrapper(adoptPtr(new PropertyWrapper<Color>(prop, visitedGetter)))
+    {
+    }
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+    {
+        return m_wrapper->equals(a, b) && m_visitedWrapper->equals(a, b);
+    }
+
+private:
+    OwnPtr<AnimationPropertyWrapperBase> m_wrapper;
+    OwnPtr<AnimationPropertyWrapperBase> m_visitedWrapper;
+};
+
+class PropertyWrapperVisitedAffectedStyleColor FINAL : public AnimationPropertyWrapperBase {
+public:
+    PropertyWrapperVisitedAffectedStyleColor(CSSPropertyID prop, StyleColor (RenderStyle::*getter)() const, StyleColor (RenderStyle::*visitedGetter)() const)
+        : AnimationPropertyWrapperBase(prop)
+        , m_wrapper(adoptPtr(new PropertyWrapperMaybeInvalidStyleColor(prop, getter)))
+        , m_visitedWrapper(adoptPtr(new PropertyWrapperMaybeInvalidStyleColor(prop, visitedGetter)))
+    {
+    }
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const OVERRIDE
+    {
+        return m_wrapper->equals(a, b) && m_visitedWrapper->equals(a, b);
+    }
+
+private:
+    OwnPtr<AnimationPropertyWrapperBase> m_wrapper;
+    OwnPtr<AnimationPropertyWrapperBase> m_visitedWrapper;
+};
+
+// Wrapper base class for an animatable property in a FillLayer
+class FillLayerAnimationPropertyWrapperBase {
+public:
+    FillLayerAnimationPropertyWrapperBase()
+    {
+    }
+
+    virtual ~FillLayerAnimationPropertyWrapperBase() { }
+
+    virtual bool equals(const FillLayer*, const FillLayer*) const = 0;
+};
+
+template <typename T>
+class FillLayerPropertyWrapperGetter : public FillLayerAnimationPropertyWrapperBase {
+    WTF_MAKE_NONCOPYABLE(FillLayerPropertyWrapperGetter);
+public:
+    FillLayerPropertyWrapperGetter(T (FillLayer::*getter)() const)
+        : m_getter(getter)
+    {
+    }
+
+    virtual bool equals(const FillLayer* a, const FillLayer* b) const
+    {
+       // If the style pointers are the same, don't bother doing the test.
+       // If either is null, return false. If both are null, return true.
+       if ((!a && !b) || a == b)
+           return true;
+       if (!a || !b)
+            return false;
+        return (a->*m_getter)() == (b->*m_getter)();
+    }
+
+protected:
+    T (FillLayer::*m_getter)() const;
+};
+
+template <typename T>
+class FillLayerPropertyWrapper FINAL : public FillLayerPropertyWrapperGetter<T> {
+public:
+    FillLayerPropertyWrapper(T (FillLayer::*getter)() const)
+        : FillLayerPropertyWrapperGetter<T>(getter)
+    {
+    }
+};
+
+template <typename T>
+class FillLayerRefCountedPropertyWrapper : public FillLayerPropertyWrapperGetter<T*> {
+public:
+    FillLayerRefCountedPropertyWrapper(T* (FillLayer::*getter)() const)
+        : FillLayerPropertyWrapperGetter<T*>(getter)
+    {
+    }
+};
+
+class FillLayerStyleImagePropertyWrapper FINAL : public FillLayerRefCountedPropertyWrapper<StyleImage> {
+public:
+    FillLayerStyleImagePropertyWrapper(StyleImage* (FillLayer::*getter)() const)
+        : FillLayerRefCountedPropertyWrapper<StyleImage>(getter)
+    {
+    }
+
+    virtual bool equals(const FillLayer* a, const FillLayer* b) const OVERRIDE
+    {
+       // If the style pointers are the same, don't bother doing the test.
+       // If either is null, return false. If both are null, return true.
+       if (a == b)
+           return true;
+       if (!a || !b)
+            return false;
+
+        StyleImage* imageA = (a->*m_getter)();
+        StyleImage* imageB = (b->*m_getter)();
+        return StyleImage::imagesEquivalent(imageA, imageB);
+    }
+};
+
+
+class FillLayersPropertyWrapper FINAL : public AnimationPropertyWrapperBase {
+public:
+    typedef const FillLayer* (RenderStyle::*LayersGetter)() const;
+
+    FillLayersPropertyWrapper(CSSPropertyID prop, LayersGetter getter)
+        : AnimationPropertyWrapperBase(prop)
+        , m_layersGetter(getter)
+    {
+        switch (prop) {
+        case CSSPropertyBackgroundPositionX:
+        case CSSPropertyWebkitMaskPositionX:
+            m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<Length>(&FillLayer::xPosition);
+            break;
+        case CSSPropertyBackgroundPositionY:
+        case CSSPropertyWebkitMaskPositionY:
+            m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<Length>(&FillLayer::yPosition);
+            break;
+        case CSSPropertyBackgroundSize:
+        case CSSPropertyWebkitBackgroundSize:
+        case CSSPropertyWebkitMaskSize:
+            m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<LengthSize>(&FillLayer::sizeLength);
+            break;
+        case CSSPropertyBackgroundImage:
+            m_fillLayerPropertyWrapper = new FillLayerStyleImagePropertyWrapper(&FillLayer::image);
+            break;
+        default:
+            break;
+        }
+    }
+
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const OVERRIDE
+    {
+        const FillLayer* fromLayer = (a->*m_layersGetter)();
+        const FillLayer* toLayer = (b->*m_layersGetter)();
+
+        while (fromLayer && toLayer) {
+            if (!m_fillLayerPropertyWrapper->equals(fromLayer, toLayer))
+                return false;
+
+            fromLayer = fromLayer->next();
+            toLayer = toLayer->next();
+        }
+
+        return true;
+    }
+
+private:
+    FillLayerAnimationPropertyWrapperBase* m_fillLayerPropertyWrapper;
+
+    LayersGetter m_layersGetter;
+};
+
+class PropertyWrapperSVGPaint FINAL : public AnimationPropertyWrapperBase {
+public:
+    PropertyWrapperSVGPaint(CSSPropertyID prop, const SVGPaint::SVGPaintType& (RenderStyle::*paintTypeGetter)() const, Color (RenderStyle::*getter)() const)
+        : AnimationPropertyWrapperBase(prop)
+        , m_paintTypeGetter(paintTypeGetter)
+        , m_getter(getter)
+    {
+    }
+
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const OVERRIDE
+    {
+        if ((a->*m_paintTypeGetter)() != (b->*m_paintTypeGetter)())
+            return false;
+
+        // We only support animations between SVGPaints that are pure Color values.
+        // For everything else we must return true for this method, otherwise
+        // we will try to animate between values forever.
+        if ((a->*m_paintTypeGetter)() == SVGPaint::SVG_PAINTTYPE_RGBCOLOR) {
+            Color fromColor = (a->*m_getter)();
+            Color toColor = (b->*m_getter)();
+            return fromColor == toColor;
+        }
+        return true;
+    }
+
+private:
+    const SVGPaint::SVGPaintType& (RenderStyle::*m_paintTypeGetter)() const;
+    Color (RenderStyle::*m_getter)() const;
+};
+
+template <typename T>
+class RefCountedSVGPropertyWrapper : public AnimationPropertyWrapperBase {
+public:
+    RefCountedSVGPropertyWrapper(CSSPropertyID prop, PassRefPtr<T> (RenderStyle::*getter)() const)
+        : AnimationPropertyWrapperBase(prop)
+        , m_getter(getter)
+    {
+    }
+
+    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const OVERRIDE
+    {
+        if (a == b)
+            return true;
+        if (!a || !b)
+            return false;
+        RefPtr<T> aValue = (a->*this->m_getter)();
+        RefPtr<T> bValue = (b->*this->m_getter)();
+        if (aValue == bValue)
+            return true;
+        if (!aValue || !bValue)
+            return false;
+        return *aValue == *bValue;
+    }
+
+protected:
+    PassRefPtr<T> (RenderStyle::*m_getter)() const;
+};
+
+void CSSPropertyAnimation::ensurePropertyMap()
+{
+    // FIXME: This data is never destroyed. Maybe we should ref count it and toss it when the last AnimationController is destroyed?
+    if (gPropertyWrappers)
+        return;
+
+    gPropertyWrappers = new Vector<AnimationPropertyWrapperBase*>();
+
+    // build the list of property wrappers to do the comparisons and blends
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyLeft, &RenderStyle::left));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyRight, &RenderStyle::right));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyTop, &RenderStyle::top));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyBottom, &RenderStyle::bottom));
+
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWidth, &RenderStyle::width));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMinWidth, &RenderStyle::minWidth));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMaxWidth, &RenderStyle::maxWidth));
+
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyHeight, &RenderStyle::height));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMinHeight, &RenderStyle::minHeight));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMaxHeight, &RenderStyle::maxHeight));
+
+    gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderLeftWidth, &RenderStyle::borderLeftWidth));
+    gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderRightWidth, &RenderStyle::borderRightWidth));
+    gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderTopWidth, &RenderStyle::borderTopWidth));
+    gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderBottomWidth, &RenderStyle::borderBottomWidth));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginLeft, &RenderStyle::marginLeft));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginRight, &RenderStyle::marginRight));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginTop, &RenderStyle::marginTop));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginBottom, &RenderStyle::marginBottom));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingLeft, &RenderStyle::paddingLeft));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingRight, &RenderStyle::paddingRight));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingTop, &RenderStyle::paddingTop));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingBottom, &RenderStyle::paddingBottom));
+    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyColor, &RenderStyle::color, &RenderStyle::visitedLinkColor));
+
+    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedStyleColor(CSSPropertyBackgroundColor, &RenderStyle::backgroundColor, &RenderStyle::visitedLinkBackgroundColor));
+
+    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundImage, &RenderStyle::backgroundLayers));
+    gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyListStyleImage, &RenderStyle::listStyleImage));
+    gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyWebkitMaskImage, &RenderStyle::maskImage));
+
+    gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyBorderImageSource, &RenderStyle::borderImageSource));
+    gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyBorderImageSlice, &RenderStyle::borderImageSlices));
+    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyBorderImageWidth, &RenderStyle::borderImageWidth));
+    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyBorderImageOutset, &RenderStyle::borderImageOutset));
+
+    gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyWebkitMaskBoxImageSource, &RenderStyle::maskBoxImageSource));
+    gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyWebkitMaskBoxImageSlice, &RenderStyle::maskBoxImageSlices));
+    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyWebkitMaskBoxImageWidth, &RenderStyle::maskBoxImageWidth));
+    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyWebkitMaskBoxImageOutset, &RenderStyle::maskBoxImageOutset));
+
+    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionX, &RenderStyle::backgroundLayers));
+    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionY, &RenderStyle::backgroundLayers));
+    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundSize, &RenderStyle::backgroundLayers));
+    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitBackgroundSize, &RenderStyle::backgroundLayers));
+
+    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskPositionX, &RenderStyle::maskLayers));
+    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskPositionY, &RenderStyle::maskLayers));
+    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskSize, &RenderStyle::maskLayers));
+
+    gPropertyWrappers->append(new PropertyWrapper<LengthPoint>(CSSPropertyObjectPosition, &RenderStyle::objectPosition));
+
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFontSize,
+        // Must pass a specified size to setFontSize if Text Autosizing is enabled, but a computed size
+        // if text zoom is enabled (if neither is enabled it's irrelevant as they're probably the same).
+        // FIXME: Should we introduce an option to pass the computed font size here, allowing consumers to
+        // enable text zoom rather than Text Autosizing? See http://crbug.com/227545.
+        &RenderStyle::specifiedFontSize));
+    gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyWebkitColumnRuleWidth, &RenderStyle::columnRuleWidth));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitColumnGap, &RenderStyle::columnGap));
+    gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyWebkitColumnCount, &RenderStyle::columnCount));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitColumnWidth, &RenderStyle::columnWidth));
+    gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWebkitBorderHorizontalSpacing, &RenderStyle::horizontalBorderSpacing));
+    gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWebkitBorderVerticalSpacing, &RenderStyle::verticalBorderSpacing));
+    gPropertyWrappers->append(new PropertyWrapper<int>(CSSPropertyZIndex, &RenderStyle::zIndex));
+    gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyOrphans, &RenderStyle::orphans));
+    gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWidows, &RenderStyle::widows));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyLineHeight, &RenderStyle::specifiedLineHeight));
+    gPropertyWrappers->append(new PropertyWrapper<int>(CSSPropertyOutlineOffset, &RenderStyle::outlineOffset));
+    gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyOutlineWidth, &RenderStyle::outlineWidth));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyLetterSpacing, &RenderStyle::letterSpacing));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWordSpacing, &RenderStyle::wordSpacing));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyTextIndent, &RenderStyle::textIndent));
+
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitPerspective, &RenderStyle::perspective));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitPerspectiveOriginX, &RenderStyle::perspectiveOriginX));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitPerspectiveOriginY, &RenderStyle::perspectiveOriginY));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitTransformOriginX, &RenderStyle::transformOriginX));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitTransformOriginY, &RenderStyle::transformOriginY));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitTransformOriginZ, &RenderStyle::transformOriginZ));
+    gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderTopLeftRadius, &RenderStyle::borderTopLeftRadius));
+    gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderTopRightRadius, &RenderStyle::borderTopRightRadius));
+    gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderBottomLeftRadius, &RenderStyle::borderBottomLeftRadius));
+    gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderBottomRightRadius, &RenderStyle::borderBottomRightRadius));
+    gPropertyWrappers->append(new PropertyWrapper<EVisibility>(CSSPropertyVisibility, &RenderStyle::visibility));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyZoom, &RenderStyle::zoom));
+
+    gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyClip, &RenderStyle::clip));
+
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyOpacity, &RenderStyle::opacity));
+    gPropertyWrappers->append(new PropertyWrapper<const TransformOperations&>(CSSPropertyWebkitTransform, &RenderStyle::transform));
+    gPropertyWrappers->append(new PropertyWrapper<const FilterOperations&>(CSSPropertyWebkitFilter, &RenderStyle::filter));
+
+    gPropertyWrappers->append(new RefCountedPropertyWrapper<ClipPathOperation>(CSSPropertyWebkitClipPath, &RenderStyle::clipPath));
+
+    gPropertyWrappers->append(new RefCountedPropertyWrapper<ShapeValue>(CSSPropertyShapeInside, &RenderStyle::shapeInside));
+    gPropertyWrappers->append(new RefCountedPropertyWrapper<ShapeValue>(CSSPropertyShapeOutside, &RenderStyle::shapeOutside));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyShapeMargin, &RenderStyle::shapeMargin));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyShapeImageThreshold, &RenderStyle::shapeImageThreshold));
+
+    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedStyleColor(CSSPropertyWebkitColumnRuleColor, &RenderStyle::columnRuleColor, &RenderStyle::visitedLinkColumnRuleColor));
+    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedStyleColor(CSSPropertyWebkitTextStrokeColor, &RenderStyle::textStrokeColor, &RenderStyle::visitedLinkTextStrokeColor));
+    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedStyleColor(CSSPropertyBorderLeftColor, &RenderStyle::borderLeftColor, &RenderStyle::visitedLinkBorderLeftColor));
+    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedStyleColor(CSSPropertyBorderRightColor, &RenderStyle::borderRightColor, &RenderStyle::visitedLinkBorderRightColor));
+    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedStyleColor(CSSPropertyBorderTopColor, &RenderStyle::borderTopColor, &RenderStyle::visitedLinkBorderTopColor));
+    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedStyleColor(CSSPropertyBorderBottomColor, &RenderStyle::borderBottomColor, &RenderStyle::visitedLinkBorderBottomColor));
+    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedStyleColor(CSSPropertyOutlineColor, &RenderStyle::outlineColor, &RenderStyle::visitedLinkOutlineColor));
+
+    gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyBoxShadow, &RenderStyle::boxShadow));
+    gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyWebkitBoxShadow, &RenderStyle::boxShadow));
+    gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyTextShadow, &RenderStyle::textShadow));
+
+    gPropertyWrappers->append(new PropertyWrapperSVGPaint(CSSPropertyFill, &RenderStyle::fillPaintType, &RenderStyle::fillPaintColor));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFillOpacity, &RenderStyle::fillOpacity));
+
+    gPropertyWrappers->append(new PropertyWrapperSVGPaint(CSSPropertyStroke, &RenderStyle::strokePaintType, &RenderStyle::strokePaintColor));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeOpacity, &RenderStyle::strokeOpacity));
+    gPropertyWrappers->append(new RefCountedSVGPropertyWrapper<SVGLength>(CSSPropertyStrokeWidth, &RenderStyle::strokeWidth));
+    gPropertyWrappers->append(new RefCountedSVGPropertyWrapper<SVGLengthList>(CSSPropertyStrokeDasharray, &RenderStyle::strokeDashArray));
+    gPropertyWrappers->append(new RefCountedSVGPropertyWrapper<SVGLength>(CSSPropertyStrokeDashoffset, &RenderStyle::strokeDashOffset));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeMiterlimit, &RenderStyle::strokeMiterLimit));
+
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFloodOpacity, &RenderStyle::floodOpacity));
+    gPropertyWrappers->append(new PropertyWrapper<Color>(CSSPropertyFloodColor, &RenderStyle::floodColor));
+
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStopOpacity, &RenderStyle::stopOpacity));
+    gPropertyWrappers->append(new PropertyWrapper<Color>(CSSPropertyStopColor, &RenderStyle::stopColor));
+
+    gPropertyWrappers->append(new PropertyWrapper<Color>(CSSPropertyLightingColor, &RenderStyle::lightingColor));
+
+    gPropertyWrappers->append(new RefCountedSVGPropertyWrapper<SVGLength>(CSSPropertyBaselineShift, &RenderStyle::baselineShiftValue));
+    gPropertyWrappers->append(new RefCountedSVGPropertyWrapper<SVGLength>(CSSPropertyKerning, &RenderStyle::kerning));
+
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFlexGrow, &RenderStyle::flexGrow));
+    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFlexShrink, &RenderStyle::flexShrink));
+    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyFlexBasis, &RenderStyle::flexBasis));
+
+    // TODO:
+    //
+    //  CSSPropertyVerticalAlign
+
+    // Make sure unused slots have a value
+    for (unsigned int i = 0; i < static_cast<unsigned int>(numCSSProperties); ++i)
+        gPropertyWrapperMap[i] = cInvalidPropertyWrapperIndex;
+
+    size_t n = gPropertyWrappers->size();
+    for (unsigned int i = 0; i < n; ++i) {
+        CSSPropertyID property = (*gPropertyWrappers)[i]->property();
+        ASSERT_WITH_MESSAGE(CSSAnimations::isAnimatableProperty(property), "%s is not whitelisted for animation", getPropertyNameString(property).utf8().data());
+        ASSERT(property - firstCSSProperty < numCSSProperties);
+        gPropertyWrapperMap[property - firstCSSProperty] = i;
+    }
+}
+
+bool CSSPropertyAnimation::propertiesEqual(CSSPropertyID prop, const RenderStyle* a, const RenderStyle* b)
+{
+    // FIXME: transitions of text-decoration-color are broken
+    if (prop == CSSPropertyTextDecorationColor)
+        return true;
+
+    ensurePropertyMap();
+    return wrapperForProperty(prop)->equals(a, b);
+}
+
+
+}
diff --git a/Source/core/frame/animation/CSSPropertyAnimation.h b/Source/core/animation/css/CSSPropertyAnimation.h
similarity index 81%
rename from Source/core/frame/animation/CSSPropertyAnimation.h
rename to Source/core/animation/css/CSSPropertyAnimation.h
index 6ffd75c..148c9ca 100644
--- a/Source/core/frame/animation/CSSPropertyAnimation.h
+++ b/Source/core/animation/css/CSSPropertyAnimation.h
@@ -33,18 +33,12 @@
 
 namespace WebCore {
 
-class AnimationBase;
 class RenderStyle;
 
 class CSSPropertyAnimation {
 public:
-    static bool animationOfPropertyIsAccelerated(CSSPropertyID);
-    static bool propertiesEqual(CSSPropertyID, const RenderStyle* a, const RenderStyle* b);
-    static CSSPropertyID getPropertyAtIndex(int, bool& isShorthand);
-    static int getNumProperties();
+    static bool propertiesEqual(CSSPropertyID, const RenderStyle*, const RenderStyle*);
 
-    // Return true if we need to start software animation timers
-    static bool blendProperties(const AnimationBase*, CSSPropertyID, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress);
 private:
     static void ensurePropertyMap();
 };
diff --git a/Source/core/dom/Clipboard.cpp b/Source/core/clipboard/Clipboard.cpp
similarity index 95%
rename from Source/core/dom/Clipboard.cpp
rename to Source/core/clipboard/Clipboard.cpp
index fc3808e..34f9e5c 100644
--- a/Source/core/dom/Clipboard.cpp
+++ b/Source/core/clipboard/Clipboard.cpp
@@ -24,20 +24,20 @@
  */
 
 #include "config.h"
-#include "core/dom/Clipboard.h"
+#include "core/clipboard/Clipboard.h"
 
 #include "HTMLNames.h"
-#include "core/dom/DataTransferItem.h"
-#include "core/dom/DataTransferItemList.h"
+#include "core/clipboard/DataObject.h"
+#include "core/clipboard/DataTransferItem.h"
+#include "core/clipboard/DataTransferItemList.h"
 #include "core/editing/markup.h"
 #include "core/fetch/ImageResource.h"
 #include "core/fileapi/FileList.h"
-#include "core/html/HTMLImageElement.h"
 #include "core/frame/Frame.h"
-#include "core/platform/DragImage.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
+#include "core/html/HTMLImageElement.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderObject.h"
+#include "platform/DragImage.h"
 #include "platform/MIMETypeRegistry.h"
 #include "platform/clipboard/ClipboardMimeTypes.h"
 #include "platform/clipboard/ClipboardUtilities.h"
@@ -67,7 +67,7 @@
         return (DragOperation)(DragOperationLink | DragOperationGeneric | DragOperationMove);
     if (op == "all")
         return DragOperationEvery;
-    return DragOperationPrivate;  // really a marker for "no conversion"
+    return DragOperationPrivate; // really a marker for "no conversion"
 }
 
 static String IEOpFromDragOp(DragOperation op)
@@ -107,7 +107,7 @@
     return cleanType;
 }
 
-PassRefPtr<Clipboard> Clipboard::create(ClipboardType type, ClipboardAccessPolicy policy, PassRefPtr<ChromiumDataObject> dataObject)
+PassRefPtr<Clipboard> Clipboard::create(ClipboardType type, ClipboardAccessPolicy policy, PassRefPtr<DataObject> dataObject)
 {
     return adoptRef(new Clipboard(type, policy , dataObject));
 }
@@ -201,7 +201,7 @@
         return files.release();
 
     for (size_t i = 0; i < m_dataObject->length(); ++i) {
-        if (m_dataObject->item(i)->kind() == DataTransferItem::kindFile) {
+        if (m_dataObject->item(i)->kind() == DataObjectItem::FileKind) {
             RefPtr<Blob> blob = m_dataObject->item(i)->getAsFile();
             if (blob && blob->isFile())
                 files->append(toFile(blob.get()));
@@ -265,7 +265,7 @@
     return 0;
 }
 
-static void writeImageToDataObject(ChromiumDataObject* dataObject, Element* element, const KURL& url)
+static void writeImageToDataObject(DataObject* dataObject, Element* element, const KURL& url)
 {
     // Shove image data into a DataObject for use as a file
     ImageResource* cachedImage = getImageResource(element);
@@ -448,12 +448,12 @@
     return DataTransferItemList::create(this, m_dataObject);
 }
 
-PassRefPtr<ChromiumDataObject> Clipboard::dataObject() const
+PassRefPtr<DataObject> Clipboard::dataObject() const
 {
     return m_dataObject;
 }
 
-Clipboard::Clipboard(ClipboardType type, ClipboardAccessPolicy policy, PassRefPtr<ChromiumDataObject> dataObject)
+Clipboard::Clipboard(ClipboardType type, ClipboardAccessPolicy policy, PassRefPtr<DataObject> dataObject)
     : m_policy(policy)
     , m_dropEffect("uninitialized")
     , m_effectAllowed("uninitialized")
diff --git a/Source/core/dom/Clipboard.h b/Source/core/clipboard/Clipboard.h
similarity index 93%
rename from Source/core/dom/Clipboard.h
rename to Source/core/clipboard/Clipboard.h
index dfe2271..cca9fe8 100644
--- a/Source/core/dom/Clipboard.h
+++ b/Source/core/clipboard/Clipboard.h
@@ -25,7 +25,7 @@
 #define Clipboard_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ClipboardAccessPolicy.h"
+#include "core/clipboard/ClipboardAccessPolicy.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/page/DragActions.h"
 #include "platform/geometry/IntPoint.h"
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class ChromiumDataObject;
+class DataObject;
 class DataTransferItemList;
 class DragImage;
 class Element;
@@ -56,7 +56,7 @@
         DragAndDrop,
     };
 
-    static PassRefPtr<Clipboard> create(ClipboardType, ClipboardAccessPolicy, PassRefPtr<ChromiumDataObject>);
+    static PassRefPtr<Clipboard> create(ClipboardType, ClipboardAccessPolicy, PassRefPtr<DataObject>);
     ~Clipboard();
 
     bool isForCopyAndPaste() const { return m_clipboardType == CopyAndPaste; }
@@ -110,10 +110,10 @@
 
     PassRefPtr<DataTransferItemList> items();
 
-    PassRefPtr<ChromiumDataObject> dataObject() const;
+    PassRefPtr<DataObject> dataObject() const;
 
 private:
-    Clipboard(ClipboardType, ClipboardAccessPolicy, PassRefPtr<ChromiumDataObject>);
+    Clipboard(ClipboardType, ClipboardAccessPolicy, PassRefPtr<DataObject>);
 
     void setDragImage(ImageResource*, Node*, const IntPoint&);
 
@@ -125,7 +125,7 @@
     String m_dropEffect;
     String m_effectAllowed;
     ClipboardType m_clipboardType;
-    RefPtr<ChromiumDataObject> m_dataObject;
+    RefPtr<DataObject> m_dataObject;
 
     IntPoint m_dragLoc;
     ResourcePtr<ImageResource> m_dragImage;
diff --git a/Source/core/dom/Clipboard.idl b/Source/core/clipboard/Clipboard.idl
similarity index 100%
rename from Source/core/dom/Clipboard.idl
rename to Source/core/clipboard/Clipboard.idl
diff --git a/Source/core/dom/ClipboardAccessPolicy.h b/Source/core/clipboard/ClipboardAccessPolicy.h
similarity index 100%
rename from Source/core/dom/ClipboardAccessPolicy.h
rename to Source/core/clipboard/ClipboardAccessPolicy.h
diff --git a/Source/core/clipboard/DataObject.cpp b/Source/core/clipboard/DataObject.cpp
new file mode 100644
index 0000000..e3fb8a2
--- /dev/null
+++ b/Source/core/clipboard/DataObject.cpp
@@ -0,0 +1,269 @@
+/*
+ * Copyright (c) 2008, 2009, 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/clipboard/DataObject.h"
+
+#include "core/clipboard/Pasteboard.h"
+#include "platform/clipboard/ClipboardMimeTypes.h"
+#include "platform/clipboard/ClipboardUtilities.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebClipboard.h"
+
+namespace WebCore {
+
+PassRefPtr<DataObject> DataObject::createFromPasteboard(PasteMode pasteMode)
+{
+    RefPtr<DataObject> dataObject = create();
+    blink::WebClipboard::Buffer buffer = Pasteboard::generalPasteboard()->buffer();
+    uint64_t sequenceNumber = blink::Platform::current()->clipboard()->sequenceNumber(buffer);
+    bool ignored;
+    blink::WebVector<blink::WebString> webTypes = blink::Platform::current()->clipboard()->readAvailableTypes(buffer, &ignored);
+    ListHashSet<String> types;
+    for (size_t i = 0; i < webTypes.size(); ++i)
+        types.add(webTypes[i]);
+    for (ListHashSet<String>::const_iterator it = types.begin(); it != types.end(); ++it) {
+        if (pasteMode == PlainTextOnly && *it != mimeTypeTextPlain)
+            continue;
+        dataObject->m_itemList.append(DataObjectItem::createFromPasteboard(*it, sequenceNumber));
+    }
+    return dataObject.release();
+}
+
+PassRefPtr<DataObject> DataObject::create()
+{
+    return adoptRef(new DataObject());
+}
+
+PassRefPtr<DataObject> DataObject::copy() const
+{
+    return adoptRef(new DataObject(*this));
+}
+
+size_t DataObject::length() const
+{
+    return m_itemList.size();
+}
+
+PassRefPtr<DataObjectItem> DataObject::item(unsigned long index)
+{
+    if (index >= length())
+        return 0;
+    return m_itemList[index];
+}
+
+void DataObject::deleteItem(unsigned long index)
+{
+    if (index >= length())
+        return;
+    m_itemList.remove(index);
+}
+
+void DataObject::clearAll()
+{
+    m_itemList.clear();
+}
+
+PassRefPtr<DataObjectItem> DataObject::add(const String& data, const String& type)
+{
+    RefPtr<DataObjectItem> item = DataObjectItem::createFromString(type, data);
+    if (!internalAddStringItem(item))
+        return 0;
+    return item;
+}
+
+PassRefPtr<DataObjectItem> DataObject::add(PassRefPtr<File> file)
+{
+    if (!file)
+        return 0;
+
+    RefPtr<DataObjectItem> item = DataObjectItem::createFromFile(file);
+    m_itemList.append(item);
+    return item;
+}
+
+void DataObject::clearData(const String& type)
+{
+    for (size_t i = 0; i < m_itemList.size(); ++i) {
+        if (m_itemList[i]->kind() == DataObjectItem::StringKind && m_itemList[i]->type() == type) {
+            // Per the spec, type must be unique among all items of kind 'string'.
+            m_itemList.remove(i);
+            return;
+        }
+    }
+}
+
+void DataObject::clearAllExceptFiles()
+{
+    for (size_t i = 0; i < m_itemList.size(); ) {
+        if (m_itemList[i]->kind() != DataObjectItem::FileKind) {
+            m_itemList.remove(i);
+            continue;
+        }
+        ++i;
+    }
+}
+
+ListHashSet<String> DataObject::types() const
+{
+    ListHashSet<String> results;
+    bool containsFiles = false;
+    for (size_t i = 0; i < m_itemList.size(); ++i) {
+        switch (m_itemList[i]->kind()) {
+        case DataObjectItem::StringKind:
+            results.add(m_itemList[i]->type());
+            break;
+        case DataObjectItem::FileKind:
+            containsFiles = true;
+            break;
+        }
+    }
+    if (containsFiles)
+        results.add(mimeTypeFiles);
+    return results;
+}
+
+String DataObject::getData(const String& type) const
+{
+    for (size_t i = 0; i < m_itemList.size(); ++i)  {
+        if (m_itemList[i]->kind() == DataObjectItem::StringKind && m_itemList[i]->type() == type)
+            return m_itemList[i]->getAsString();
+    }
+    return String();
+}
+
+bool DataObject::setData(const String& type, const String& data)
+{
+    clearData(type);
+    if (!add(data, type))
+        ASSERT_NOT_REACHED();
+    return true;
+}
+
+void DataObject::urlAndTitle(String& url, String* title) const
+{
+    RefPtr<DataObjectItem> item = findStringItem(mimeTypeTextURIList);
+    if (!item)
+        return;
+    url = convertURIListToURL(item->getAsString());
+    if (title)
+        *title = item->title();
+}
+
+void DataObject::setURLAndTitle(const String& url, const String& title)
+{
+    clearData(mimeTypeTextURIList);
+    internalAddStringItem(DataObjectItem::createFromURL(url, title));
+}
+
+void DataObject::htmlAndBaseURL(String& html, KURL& baseURL) const
+{
+    RefPtr<DataObjectItem> item = findStringItem(mimeTypeTextHTML);
+    if (!item)
+        return;
+    html = item->getAsString();
+    baseURL = item->baseURL();
+}
+
+void DataObject::setHTMLAndBaseURL(const String& html, const KURL& baseURL)
+{
+    clearData(mimeTypeTextHTML);
+    internalAddStringItem(DataObjectItem::createFromHTML(html, baseURL));
+}
+
+bool DataObject::containsFilenames() const
+{
+    for (size_t i = 0; i < m_itemList.size(); ++i) {
+        if (m_itemList[i]->isFilename())
+            return true;
+    }
+    return false;
+}
+
+Vector<String> DataObject::filenames() const
+{
+    Vector<String> results;
+    for (size_t i = 0; i < m_itemList.size(); ++i) {
+        if (m_itemList[i]->isFilename())
+            results.append(static_cast<File*>(m_itemList[i]->getAsFile().get())->path());
+    }
+    return results;
+}
+
+void DataObject::addFilename(const String& filename, const String& displayName)
+{
+    internalAddFileItem(DataObjectItem::createFromFile(File::createWithName(filename, displayName, File::AllContentTypes)));
+}
+
+void DataObject::addSharedBuffer(const String& name, PassRefPtr<SharedBuffer> buffer)
+{
+    internalAddFileItem(DataObjectItem::createFromSharedBuffer(name, buffer));
+}
+
+DataObject::DataObject()
+    : m_modifierKeyState(0)
+{
+}
+
+DataObject::DataObject(const DataObject& other)
+    : RefCounted<DataObject>()
+    , m_itemList(other.m_itemList)
+    , m_modifierKeyState(0)
+{
+}
+
+PassRefPtr<DataObjectItem> DataObject::findStringItem(const String& type) const
+{
+    for (size_t i = 0; i < m_itemList.size(); ++i) {
+        if (m_itemList[i]->kind() == DataObjectItem::StringKind && m_itemList[i]->type() == type)
+            return m_itemList[i];
+    }
+    return 0;
+}
+
+bool DataObject::internalAddStringItem(PassRefPtr<DataObjectItem> item)
+{
+    ASSERT(item->kind() == DataObjectItem::StringKind);
+    for (size_t i = 0; i < m_itemList.size(); ++i) {
+        if (m_itemList[i]->kind() == DataObjectItem::StringKind && m_itemList[i]->type() == item->type())
+            return false;
+    }
+
+    m_itemList.append(item);
+    return true;
+}
+
+void DataObject::internalAddFileItem(PassRefPtr<DataObjectItem> item)
+{
+    ASSERT(item->kind() == DataObjectItem::FileKind);
+    m_itemList.append(item);
+}
+
+} // namespace WebCore
diff --git a/Source/core/platform/chromium/ChromiumDataObject.h b/Source/core/clipboard/DataObject.h
similarity index 74%
rename from Source/core/platform/chromium/ChromiumDataObject.h
rename to Source/core/clipboard/DataObject.h
index 63afbc8..7c489f9 100644
--- a/Source/core/platform/chromium/ChromiumDataObject.h
+++ b/Source/core/clipboard/DataObject.h
@@ -28,43 +28,43 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ChromiumDataObject_h
-#define ChromiumDataObject_h
+#ifndef DataObject_h
+#define DataObject_h
 
-#include "core/platform/chromium/ChromiumDataObjectItem.h"
+#include "core/clipboard/DataObjectItem.h"
 #include "platform/PasteMode.h"
 #include "platform/Supplementable.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 #include "wtf/text/StringHash.h"
 #include "wtf/text/WTFString.h"
-#include "wtf/Vector.h"
 
 namespace WebCore {
 
-class ExceptionState;
 class KURL;
 class SharedBuffer;
 
 // A data object for holding data that would be in a clipboard or moved
-// during a drag-n-drop operation.  This is the data that WebCore is aware
+// during a drag-n-drop operation. This is the data that WebCore is aware
 // of and is not specific to a platform.
-class ChromiumDataObject : public RefCounted<ChromiumDataObject>, public Supplementable<ChromiumDataObject> {
+class DataObject : public RefCounted<DataObject>, public Supplementable<DataObject> {
 public:
-    static PassRefPtr<ChromiumDataObject> createFromPasteboard(PasteMode);
-    static PassRefPtr<ChromiumDataObject> create();
+    static PassRefPtr<DataObject> createFromPasteboard(PasteMode);
+    static PassRefPtr<DataObject> create();
 
-    PassRefPtr<ChromiumDataObject> copy() const;
+    PassRefPtr<DataObject> copy() const;
 
     // DataTransferItemList support.
     size_t length() const;
-    PassRefPtr<ChromiumDataObjectItem> item(unsigned long index);
+    PassRefPtr<DataObjectItem> item(unsigned long index);
     // FIXME: Implement V8DataTransferItemList::indexedPropertyDeleter to get this called.
     void deleteItem(unsigned long index);
     void clearAll();
-    PassRefPtr<ChromiumDataObjectItem> add(const String& data, const String& type, ExceptionState&);
-    PassRefPtr<ChromiumDataObjectItem> add(PassRefPtr<File>);
+    // Returns null if an item already exists with the provided type.
+    PassRefPtr<DataObjectItem> add(const String& data, const String& type);
+    PassRefPtr<DataObjectItem> add(PassRefPtr<File>);
 
     // WebCore helpers.
     void clearData(const String& type);
@@ -91,14 +91,14 @@
     void setModifierKeyState(int modifierKeyState) { m_modifierKeyState = modifierKeyState; }
 
 private:
-    ChromiumDataObject();
-    explicit ChromiumDataObject(const ChromiumDataObject&);
+    DataObject();
+    explicit DataObject(const DataObject&);
 
-    PassRefPtr<ChromiumDataObjectItem> findStringItem(const String& type) const;
-    bool internalAddStringItem(PassRefPtr<ChromiumDataObjectItem>);
-    void internalAddFileItem(PassRefPtr<ChromiumDataObjectItem>);
+    PassRefPtr<DataObjectItem> findStringItem(const String& type) const;
+    bool internalAddStringItem(PassRefPtr<DataObjectItem>);
+    void internalAddFileItem(PassRefPtr<DataObjectItem>);
 
-    Vector<RefPtr<ChromiumDataObjectItem> > m_itemList;
+    Vector<RefPtr<DataObjectItem> > m_itemList;
 
     // State of Shift/Ctrl/Alt/Meta keys.
     int m_modifierKeyState;
diff --git a/Source/core/platform/chromium/ChromiumDataObjectItem.cpp b/Source/core/clipboard/DataObjectItem.cpp
similarity index 65%
rename from Source/core/platform/chromium/ChromiumDataObjectItem.cpp
rename to Source/core/clipboard/DataObjectItem.cpp
index 980a5db..c384eb4 100644
--- a/Source/core/platform/chromium/ChromiumDataObjectItem.cpp
+++ b/Source/core/clipboard/DataObjectItem.cpp
@@ -29,64 +29,62 @@
  */
 
 #include "config.h"
-#include "core/platform/chromium/ChromiumDataObjectItem.h"
+#include "core/clipboard/DataObjectItem.h"
 
-#include "core/dom/DataTransferItem.h"
-#include "core/dom/StringCallback.h"
+#include "core/clipboard/Pasteboard.h"
 #include "core/fileapi/Blob.h"
-#include "core/platform/Pasteboard.h"
 #include "platform/clipboard/ClipboardMimeTypes.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebClipboard.h"
 
 namespace WebCore {
 
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromString(const String& type, const String& data)
+PassRefPtr<DataObjectItem> DataObjectItem::createFromString(const String& type, const String& data)
 {
-    RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindString, type));
+    RefPtr<DataObjectItem> item = adoptRef(new DataObjectItem(StringKind, type));
     item->m_data = data;
     return item.release();
 }
 
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromFile(PassRefPtr<File> file)
+PassRefPtr<DataObjectItem> DataObjectItem::createFromFile(PassRefPtr<File> file)
 {
-    RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindFile, file->type()));
+    RefPtr<DataObjectItem> item = adoptRef(new DataObjectItem(FileKind, file->type()));
     item->m_file = file;
     return item.release();
 }
 
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromURL(const String& url, const String& title)
+PassRefPtr<DataObjectItem> DataObjectItem::createFromURL(const String& url, const String& title)
 {
-    RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindString, mimeTypeTextURIList));
+    RefPtr<DataObjectItem> item = adoptRef(new DataObjectItem(StringKind, mimeTypeTextURIList));
     item->m_data = url;
     item->m_title = title;
     return item.release();
 }
 
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromHTML(const String& html, const KURL& baseURL)
+PassRefPtr<DataObjectItem> DataObjectItem::createFromHTML(const String& html, const KURL& baseURL)
 {
-    RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindString, mimeTypeTextHTML));
+    RefPtr<DataObjectItem> item = adoptRef(new DataObjectItem(StringKind, mimeTypeTextHTML));
     item->m_data = html;
     item->m_baseURL = baseURL;
     return item.release();
 }
 
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromSharedBuffer(const String& name, PassRefPtr<SharedBuffer> buffer)
+PassRefPtr<DataObjectItem> DataObjectItem::createFromSharedBuffer(const String& name, PassRefPtr<SharedBuffer> buffer)
 {
-    RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindFile, String()));
+    RefPtr<DataObjectItem> item = adoptRef(new DataObjectItem(FileKind, String()));
     item->m_sharedBuffer = buffer;
     item->m_title = name;
     return item.release();
 }
 
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromPasteboard(const String& type, uint64_t sequenceNumber)
+PassRefPtr<DataObjectItem> DataObjectItem::createFromPasteboard(const String& type, uint64_t sequenceNumber)
 {
     if (type == mimeTypeImagePng)
-        return adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindFile, type, sequenceNumber));
-    return adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindString, type, sequenceNumber));
+        return adoptRef(new DataObjectItem(FileKind, type, sequenceNumber));
+    return adoptRef(new DataObjectItem(StringKind, type, sequenceNumber));
 }
 
-ChromiumDataObjectItem::ChromiumDataObjectItem(const String& kind, const String& type)
+DataObjectItem::DataObjectItem(Kind kind, const String& type)
     : m_source(InternalSource)
     , m_kind(kind)
     , m_type(type)
@@ -94,7 +92,7 @@
 {
 }
 
-ChromiumDataObjectItem::ChromiumDataObjectItem(const String& kind, const String& type, uint64_t sequenceNumber)
+DataObjectItem::DataObjectItem(Kind kind, const String& type, uint64_t sequenceNumber)
     : m_source(PasteboardSource)
     , m_kind(kind)
     , m_type(type)
@@ -102,17 +100,9 @@
 {
 }
 
-void ChromiumDataObjectItem::getAsString(PassOwnPtr<StringCallback> callback, ExecutionContext* context) const
+PassRefPtr<Blob> DataObjectItem::getAsFile() const
 {
-    if (!callback || kind() != DataTransferItem::kindString)
-        return;
-
-    StringCallback::scheduleCallback(callback, context, internalGetAsString());
-}
-
-PassRefPtr<Blob> ChromiumDataObjectItem::getAsFile() const
-{
-    if (kind() != DataTransferItem::kindFile)
+    if (kind() != FileKind)
         return 0;
 
     if (m_source == InternalSource) {
@@ -148,9 +138,9 @@
     return 0;
 }
 
-String ChromiumDataObjectItem::internalGetAsString() const
+String DataObjectItem::getAsString() const
 {
-    ASSERT(m_kind == DataTransferItem::kindString);
+    ASSERT(m_kind == StringKind);
 
     if (m_source == InternalSource)
         return m_data;
@@ -160,23 +150,24 @@
     blink::WebClipboard::Buffer buffer = Pasteboard::generalPasteboard()->buffer();
     String data;
     // This is ugly but there's no real alternative.
-    if (m_type == mimeTypeTextPlain)
+    if (m_type == mimeTypeTextPlain) {
         data = blink::Platform::current()->clipboard()->readPlainText(buffer);
-    else if (m_type == mimeTypeTextHTML) {
+    } else if (m_type == mimeTypeTextHTML) {
         blink::WebURL ignoredSourceURL;
         unsigned ignored;
         data = blink::Platform::current()->clipboard()->readHTML(buffer, &ignoredSourceURL, &ignored, &ignored);
-    } else
+    } else {
         data = blink::Platform::current()->clipboard()->readCustomData(buffer, m_type);
+    }
 
     return blink::Platform::current()->clipboard()->sequenceNumber(buffer) == m_sequenceNumber ? data : String();
 }
 
-bool ChromiumDataObjectItem::isFilename() const
+bool DataObjectItem::isFilename() const
 {
     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=81261: When we properly support File dragout,
     // we'll need to make sure this works as expected for DragDataChromium.
-    return m_kind == DataTransferItem::kindFile && m_file;
+    return m_kind == FileKind && m_file;
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/chromium/ChromiumDataObjectItem.h b/Source/core/clipboard/DataObjectItem.h
similarity index 68%
rename from Source/core/platform/chromium/ChromiumDataObjectItem.h
rename to Source/core/clipboard/DataObjectItem.h
index d9c4279..6896a93 100644
--- a/Source/core/platform/chromium/ChromiumDataObjectItem.h
+++ b/Source/core/clipboard/DataObjectItem.h
@@ -28,8 +28,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ChromiumDataObjectItem_h
-#define ChromiumDataObjectItem_h
+#ifndef DataObjectItem_h
+#define DataObjectItem_h
 
 #include "core/fileapi/File.h"
 #include "platform/SharedBuffer.h"
@@ -41,25 +41,27 @@
 namespace WebCore {
 
 class Blob;
-class ExecutionContext;
-class StringCallback;
 
-class ChromiumDataObjectItem : public RefCounted<ChromiumDataObjectItem> {
+class DataObjectItem : public RefCounted<DataObjectItem> {
 public:
-    static PassRefPtr<ChromiumDataObjectItem> createFromString(const String& type, const String& data);
-    static PassRefPtr<ChromiumDataObjectItem> createFromFile(PassRefPtr<File>);
-    static PassRefPtr<ChromiumDataObjectItem> createFromURL(const String& url, const String& title);
-    static PassRefPtr<ChromiumDataObjectItem> createFromHTML(const String& html, const KURL& baseURL);
-    static PassRefPtr<ChromiumDataObjectItem> createFromSharedBuffer(const String& filename, PassRefPtr<SharedBuffer>);
-    static PassRefPtr<ChromiumDataObjectItem> createFromPasteboard(const String& type, uint64_t sequenceNumber);
+    enum Kind {
+        StringKind,
+        FileKind
+    };
 
-    String kind() const { return m_kind; }
+    static PassRefPtr<DataObjectItem> createFromString(const String& type, const String& data);
+    static PassRefPtr<DataObjectItem> createFromFile(PassRefPtr<File>);
+    static PassRefPtr<DataObjectItem> createFromURL(const String& url, const String& title);
+    static PassRefPtr<DataObjectItem> createFromHTML(const String& html, const KURL& baseURL);
+    static PassRefPtr<DataObjectItem> createFromSharedBuffer(const String& filename, PassRefPtr<SharedBuffer>);
+    static PassRefPtr<DataObjectItem> createFromPasteboard(const String& type, uint64_t sequenceNumber);
+
+    Kind kind() const { return m_kind; }
     String type() const { return m_type; }
-    void getAsString(PassOwnPtr<StringCallback>, ExecutionContext*) const;
+    String getAsString() const;
     PassRefPtr<Blob> getAsFile() const;
 
     // Used to support legacy DataTransfer APIs and renderer->browser serialization.
-    String internalGetAsString() const;
     PassRefPtr<SharedBuffer> sharedBuffer() const { return m_sharedBuffer; }
     String title() const { return m_title; }
     KURL baseURL() const { return m_baseURL; }
@@ -71,11 +73,11 @@
         InternalSource,
     };
 
-    ChromiumDataObjectItem(const String& kind, const String& type);
-    ChromiumDataObjectItem(const String& kind, const String& type, uint64_t sequenceNumber);
+    DataObjectItem(Kind, const String& type);
+    DataObjectItem(Kind, const String& type, uint64_t sequenceNumber);
 
     DataSource m_source;
-    String m_kind;
+    Kind m_kind;
     String m_type;
 
     String m_data;
@@ -90,4 +92,4 @@
 
 } // namespace WebCore
 
-#endif // ChromiumDataObjectItem_h
+#endif // DataObjectItem_h
diff --git a/Source/core/dom/DataTransferItem.cpp b/Source/core/clipboard/DataTransferItem.cpp
similarity index 77%
rename from Source/core/dom/DataTransferItem.cpp
rename to Source/core/clipboard/DataTransferItem.cpp
index 369b7f1..0ae522f 100644
--- a/Source/core/dom/DataTransferItem.cpp
+++ b/Source/core/clipboard/DataTransferItem.cpp
@@ -29,19 +29,17 @@
  */
 
 #include "config.h"
-#include "core/dom/DataTransferItem.h"
+#include "core/clipboard/DataTransferItem.h"
 
 #include "bindings/v8/V8Binding.h"
-#include "core/dom/Clipboard.h"
+#include "core/clipboard/Clipboard.h"
+#include "core/clipboard/DataObjectItem.h"
 #include "core/dom/StringCallback.h"
-#include "core/platform/chromium/ChromiumDataObjectItem.h"
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
-const char DataTransferItem::kindString[] = "string";
-const char DataTransferItem::kindFile[] = "file";
-
-PassRefPtr<DataTransferItem> DataTransferItem::create(PassRefPtr<Clipboard> clipboard, PassRefPtr<ChromiumDataObjectItem> item)
+PassRefPtr<DataTransferItem> DataTransferItem::create(PassRefPtr<Clipboard> clipboard, PassRefPtr<DataObjectItem> item)
 {
     return adoptRef(new DataTransferItem(clipboard, item));
 }
@@ -52,9 +50,18 @@
 
 String DataTransferItem::kind() const
 {
+    DEFINE_STATIC_LOCAL(const String, kindString, ("string"));
+    DEFINE_STATIC_LOCAL(const String, kindFile, ("file"));
     if (!m_clipboard->canReadTypes())
         return String();
-    return m_item->kind();
+    switch (m_item->kind()) {
+    case DataObjectItem::StringKind:
+        return kindString;
+    case DataObjectItem::FileKind:
+        return kindFile;
+    }
+    ASSERT_NOT_REACHED();
+    return String();
 }
 
 String DataTransferItem::type() const
@@ -68,8 +75,10 @@
 {
     if (!m_clipboard->canReadData())
         return;
+    if (!callback || m_item->kind() != DataObjectItem::StringKind)
+        return;
 
-    m_item->getAsString(callback, context);
+    StringCallback::scheduleCallback(callback, context, m_item->getAsString());
 }
 
 PassRefPtr<Blob> DataTransferItem::getAsFile() const
@@ -80,7 +89,7 @@
     return m_item->getAsFile();
 }
 
-DataTransferItem::DataTransferItem(PassRefPtr<Clipboard> clipboard, PassRefPtr<ChromiumDataObjectItem> item)
+DataTransferItem::DataTransferItem(PassRefPtr<Clipboard> clipboard, PassRefPtr<DataObjectItem> item)
     : m_clipboard(clipboard)
     , m_item(item)
 {
diff --git a/Source/core/dom/DataTransferItem.h b/Source/core/clipboard/DataTransferItem.h
similarity index 87%
rename from Source/core/dom/DataTransferItem.h
rename to Source/core/clipboard/DataTransferItem.h
index 03dd377..74dd384 100644
--- a/Source/core/dom/DataTransferItem.h
+++ b/Source/core/clipboard/DataTransferItem.h
@@ -39,7 +39,7 @@
 namespace WebCore {
 
 class Blob;
-class ChromiumDataObjectItem;
+class DataObjectItem;
 class Clipboard;
 class File;
 class StringCallback;
@@ -47,12 +47,9 @@
 
 class DataTransferItem : public RefCounted<DataTransferItem>, public ScriptWrappable {
 public:
-    static PassRefPtr<DataTransferItem> create(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObjectItem>);
+    static PassRefPtr<DataTransferItem> create(PassRefPtr<Clipboard>, PassRefPtr<DataObjectItem>);
     ~DataTransferItem();
 
-    static const char kindString[];
-    static const char kindFile[];
-
     String kind() const;
     String type() const;
 
@@ -60,13 +57,13 @@
     PassRefPtr<Blob> getAsFile() const;
 
     Clipboard* clipboard() { return m_clipboard.get(); }
-    ChromiumDataObjectItem* dataObjectItem() { return m_item.get(); }
+    DataObjectItem* dataObjectItem() { return m_item.get(); }
 
 private:
-    DataTransferItem(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObjectItem>);
+    DataTransferItem(PassRefPtr<Clipboard>, PassRefPtr<DataObjectItem>);
 
     RefPtr<Clipboard> m_clipboard;
-    RefPtr<ChromiumDataObjectItem> m_item;
+    RefPtr<DataObjectItem> m_item;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/DataTransferItem.idl b/Source/core/clipboard/DataTransferItem.idl
similarity index 100%
rename from Source/core/dom/DataTransferItem.idl
rename to Source/core/clipboard/DataTransferItem.idl
diff --git a/Source/core/dom/DataTransferItemList.cpp b/Source/core/clipboard/DataTransferItemList.cpp
similarity index 81%
rename from Source/core/dom/DataTransferItemList.cpp
rename to Source/core/clipboard/DataTransferItemList.cpp
index d4f44d2..063a740 100644
--- a/Source/core/dom/DataTransferItemList.cpp
+++ b/Source/core/clipboard/DataTransferItemList.cpp
@@ -25,17 +25,17 @@
  */
 
 #include "config.h"
-#include "core/dom/DataTransferItemList.h"
+#include "core/clipboard/DataTransferItemList.h"
 
 #include "bindings/v8/ExceptionState.h"
-#include "core/dom/Clipboard.h"
-#include "core/dom/DataTransferItem.h"
+#include "core/clipboard/Clipboard.h"
+#include "core/clipboard/DataObject.h"
+#include "core/clipboard/DataTransferItem.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
 
 namespace WebCore {
 
-PassRefPtr<DataTransferItemList> DataTransferItemList::create(PassRefPtr<Clipboard> clipboard, PassRefPtr<ChromiumDataObject> list)
+PassRefPtr<DataTransferItemList> DataTransferItemList::create(PassRefPtr<Clipboard> clipboard, PassRefPtr<DataObject> list)
 {
     return adoptRef(new DataTransferItemList(clipboard, list));
 }
@@ -55,7 +55,7 @@
 {
     if (!m_clipboard->canReadTypes())
         return 0;
-    RefPtr<ChromiumDataObjectItem> item = m_dataObject->item(index);
+    RefPtr<DataObjectItem> item = m_dataObject->item(index);
     if (!item)
         return 0;
 
@@ -65,7 +65,7 @@
 void DataTransferItemList::deleteItem(unsigned long index, ExceptionState& exceptionState)
 {
     if (!m_clipboard->canWriteData()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "The list is not writable.");
         return;
     }
     m_dataObject->deleteItem(index);
@@ -82,9 +82,11 @@
 {
     if (!m_clipboard->canWriteData())
         return 0;
-    RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(data, type, exceptionState);
-    if (!item)
+    RefPtr<DataObjectItem> item = m_dataObject->add(data, type);
+    if (!item) {
+        exceptionState.throwDOMException(NotSupportedError, "An item already exists for type '" + type + "'.");
         return 0;
+    }
     return DataTransferItem::create(m_clipboard, item);
 }
 
@@ -92,13 +94,13 @@
 {
     if (!m_clipboard->canWriteData())
         return 0;
-    RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(file);
+    RefPtr<DataObjectItem> item = m_dataObject->add(file);
     if (!item)
         return 0;
     return DataTransferItem::create(m_clipboard, item);
 }
 
-DataTransferItemList::DataTransferItemList(PassRefPtr<Clipboard> clipboard, PassRefPtr<ChromiumDataObject> dataObject)
+DataTransferItemList::DataTransferItemList(PassRefPtr<Clipboard> clipboard, PassRefPtr<DataObject> dataObject)
     : m_clipboard(clipboard)
     , m_dataObject(dataObject)
 {
diff --git a/Source/core/dom/DataTransferItemList.h b/Source/core/clipboard/DataTransferItemList.h
similarity index 92%
rename from Source/core/dom/DataTransferItemList.h
rename to Source/core/clipboard/DataTransferItemList.h
index f296c7b..04c521a 100644
--- a/Source/core/dom/DataTransferItemList.h
+++ b/Source/core/clipboard/DataTransferItemList.h
@@ -38,7 +38,7 @@
 
 namespace WebCore {
 
-class ChromiumDataObject;
+class DataObject;
 class Clipboard;
 class DataTransferItem;
 class File;
@@ -47,7 +47,7 @@
 
 class DataTransferItemList : public RefCounted<DataTransferItemList>, public ScriptWrappable {
 public:
-    static PassRefPtr<DataTransferItemList> create(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObject>);
+    static PassRefPtr<DataTransferItemList> create(PassRefPtr<Clipboard>, PassRefPtr<DataObject>);
     ~DataTransferItemList();
 
     size_t length() const;
@@ -58,10 +58,10 @@
     PassRefPtr<DataTransferItem> add(PassRefPtr<File>);
 
 private:
-    DataTransferItemList(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObject>);
+    DataTransferItemList(PassRefPtr<Clipboard>, PassRefPtr<DataObject>);
 
     RefPtr<Clipboard> m_clipboard;
-    RefPtr<ChromiumDataObject> m_dataObject;
+    RefPtr<DataObject> m_dataObject;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/DataTransferItemList.idl b/Source/core/clipboard/DataTransferItemList.idl
similarity index 100%
rename from Source/core/dom/DataTransferItemList.idl
rename to Source/core/clipboard/DataTransferItemList.idl
diff --git a/Source/core/platform/Pasteboard.cpp b/Source/core/clipboard/Pasteboard.cpp
similarity index 74%
rename from Source/core/platform/Pasteboard.cpp
rename to Source/core/clipboard/Pasteboard.cpp
index a8a2946..46dc29c 100644
--- a/Source/core/platform/Pasteboard.cpp
+++ b/Source/core/clipboard/Pasteboard.cpp
@@ -29,16 +29,9 @@
  */
 
 #include "config.h"
-#include "core/platform/Pasteboard.h"
+#include "core/clipboard/Pasteboard.h"
 
-#include "HTMLNames.h"
-#include "SVGNames.h"
-#include "XLinkNames.h"
-#include "core/dom/Element.h"
-#include "core/fetch/ImageResource.h"
-#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
-#include "core/rendering/RenderImage.h"
+#include "core/clipboard/DataObject.h"
 #include "platform/clipboard/ClipboardUtilities.h"
 #include "platform/graphics/Image.h"
 #include "platform/graphics/skia/NativeImageSkia.h"
@@ -85,39 +78,19 @@
 #endif
 }
 
-void Pasteboard::writeImage(Node* node, const KURL&, const String& title)
+void Pasteboard::writeImage(Image* image, const KURL& url, const String& title)
 {
-    ASSERT(node);
-
-    if (!(node->renderer() && node->renderer()->isImage()))
-        return;
-
-    RenderImage* renderer = toRenderImage(node->renderer());
-    ImageResource* cachedImage = renderer->cachedImage();
-    if (!cachedImage || cachedImage->errorOccurred())
-        return;
-    Image* image = cachedImage->imageForRenderer(renderer);
     ASSERT(image);
 
     RefPtr<NativeImageSkia> bitmap = image->nativeImageForCurrentFrame();
     if (!bitmap)
         return;
 
-    // If the image is wrapped in a link, |url| points to the target of the
-    // link. This isn't useful to us, so get the actual image URL.
-    AtomicString urlString;
-    if (node->hasTagName(HTMLNames::imgTag) || node->hasTagName(HTMLNames::inputTag))
-        urlString = toElement(node)->getAttribute(HTMLNames::srcAttr);
-    else if (node->hasTagName(SVGNames::imageTag))
-        urlString = toElement(node)->getAttribute(XLinkNames::hrefAttr);
-    else if (node->hasTagName(HTMLNames::embedTag) || node->hasTagName(HTMLNames::objectTag))
-        urlString = toElement(node)->imageSourceURL();
-    KURL url = urlString.isEmpty() ? KURL() : node->document().completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
     blink::WebImage webImage = bitmap->bitmap();
     blink::Platform::current()->clipboard()->writeImage(webImage, blink::WebURL(url), blink::WebString(title));
 }
 
-void Pasteboard::writeDataObject(PassRefPtr<ChromiumDataObject> dataObject)
+void Pasteboard::writeDataObject(PassRefPtr<DataObject> dataObject)
 {
     blink::Platform::current()->clipboard()->writeDataObject(dataObject);
 }
diff --git a/Source/core/platform/Pasteboard.h b/Source/core/clipboard/Pasteboard.h
similarity index 87%
rename from Source/core/platform/Pasteboard.h
rename to Source/core/clipboard/Pasteboard.h
index b060a5e..93036ca 100644
--- a/Source/core/platform/Pasteboard.h
+++ b/Source/core/clipboard/Pasteboard.h
@@ -29,18 +29,14 @@
 #include "public/platform/WebClipboard.h"
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
-#include "wtf/text/WTFString.h"
 #include "wtf/Vector.h"
-
-// FIXME: This class is too high-level to be in the platform directory, since it
-// uses the DOM and makes calls to Editor. It should either be divested of its
-// knowledge of the frame and editor or moved into the editing directory.
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-class ChromiumDataObject;
+class DataObject;
+class Image;
 class KURL;
-class Node;
 
 class Pasteboard {
     WTF_MAKE_NONCOPYABLE(Pasteboard); WTF_MAKE_FAST_ALLOCATED;
@@ -52,8 +48,8 @@
 
     static Pasteboard* generalPasteboard();
     void writePlainText(const String&, SmartReplaceOption);
-    void writeImage(Node*, const KURL&, const String& title);
-    void writeDataObject(PassRefPtr<ChromiumDataObject>);
+    void writeImage(Image*, const KURL&, const String& title);
+    void writeDataObject(PassRefPtr<DataObject>);
     bool canSmartReplace();
     bool isHTMLAvailable();
     String plainText();
diff --git a/Source/core/core.gyp b/Source/core/core.gyp
index 882565d..dbbaddc 100644
--- a/Source/core/core.gyp
+++ b/Source/core/core.gyp
@@ -100,7 +100,6 @@
             '--output_dir', '<(SHARED_INTERMEDIATE_DIR)/blink',
           ],
           'message': 'Generating Inspector protocol backend sources from protocol.json',
-          'msvs_cygwin_shell': 1,
         },
       ]
     },
@@ -120,7 +119,6 @@
           'outputs': [
             '<(SHARED_INTERMEDIATE_DIR)/blink/InspectorCanvasInstrumentationInl.h',
             '<(SHARED_INTERMEDIATE_DIR)/blink/InspectorConsoleInstrumentationInl.h',
-            '<(SHARED_INTERMEDIATE_DIR)/blink/InspectorDatabaseInstrumentationInl.h',
             '<(SHARED_INTERMEDIATE_DIR)/blink/InspectorInstrumentationInl.h',
             '<(SHARED_INTERMEDIATE_DIR)/blink/InspectorOverridesInl.h',
             '<(SHARED_INTERMEDIATE_DIR)/blink/InstrumentingAgentsInl.h',
@@ -133,7 +131,6 @@
             '--output_dir', '<(SHARED_INTERMEDIATE_DIR)/blink',
           ],
           'message': 'Generating Inspector instrumentation code from InspectorInstrumentation.idl',
-          'msvs_cygwin_shell': 1,
         }
       ]
     },
@@ -206,20 +203,20 @@
       'includes': [ '../build/ConvertFileToHeaderWithCharacterArray.gypi' ],
     },
     {
-      'target_name': 'webcore_derived',
+      'target_name': 'webcore_generated',
       'type': 'static_library',
       'hard_dependency': 1,
       'dependencies': [
         'webcore_prerequisites',
-        '../bindings/derived_sources.gyp:bindings_derived_sources',
-        'core_derived_sources.gyp:make_core_derived_sources',
+        '../bindings/generated_bindings.gyp:generated_bindings',
+        'core_generated.gyp:make_core_generated',
         'inspector_overlay_page',
         'inspector_protocol_sources',
         'inspector_instrumentation_sources',
         'injected_canvas_script_source',
         'injected_script_source',
         'debugger_script_source',
-        '../platform/platform_derived_sources.gyp:make_platform_derived_sources',
+        '../platform/platform_generated.gyp:make_platform_generated',
         '../wtf/wtf.gyp:wtf',
         '<(DEPTH)/gin/gin.gyp:gin',
         '<(DEPTH)/skia/skia.gyp:skia',
@@ -250,14 +247,14 @@
       'sources': [
         # These files include all the .cpp files generated from the .idl files
         # in webcore_files.
-        '<@(derived_sources_aggregate_files)',
+        '<@(aggregate_generated_bindings_files)',
         '<@(bindings_files)',
 
         # Additional .cpp files for HashTools.h
         '<(SHARED_INTERMEDIATE_DIR)/blink/CSSPropertyNames.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/CSSValueKeywords.cpp',
 
-        # Additional .cpp files from make_core_derived_sources actions.
+        # Additional .cpp files from make_core_generated actions.
         '<(SHARED_INTERMEDIATE_DIR)/blink/Event.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/EventHeaders.h',
         '<(SHARED_INTERMEDIATE_DIR)/blink/EventInterfaces.h',
@@ -290,13 +287,13 @@
         # Generated from CSSTokenizer-in.cpp
         '<(SHARED_INTERMEDIATE_DIR)/blink/CSSTokenizer.cpp',
 
-        # Generated from CSSParser-in.cpp
-        '<(SHARED_INTERMEDIATE_DIR)/blink/CSSParser.cpp',
+        # Generated from BisonCSSParser-in.cpp
+        '<(SHARED_INTERMEDIATE_DIR)/blink/BisonCSSParser.cpp',
 
         # Generated from HTMLMetaElement-in.cpp
         '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLMetaElement.cpp',
 
-        # Additional .cpp files from the make_core_derived_sources rules.
+        # Additional .cpp files from the make_core_generated rules.
         '<(SHARED_INTERMEDIATE_DIR)/blink/CSSGrammar.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/XPathGrammar.cpp',
 
@@ -355,8 +352,8 @@
         'inspector_overlay_page',
         'inspector_protocol_sources',
         'inspector_instrumentation_sources',
-        '../bindings/derived_sources.gyp:bindings_derived_sources',
-        'core_derived_sources.gyp:make_core_derived_sources',
+        '../bindings/generated_bindings.gyp:generated_bindings',
+        'core_generated.gyp:make_core_generated',
         '../wtf/wtf.gyp:wtf',
         '../config.gyp:config',
         '../heap/blink_heap.gyp:blink_heap',
@@ -450,6 +447,13 @@
             ['exclude', 'accessibility/'],
           ],
         }],
+        ['OS in ("linux", "android") and "WTF_USE_WEBAUDIO_IPP=1" in feature_defines', {
+          'direct_dependent_settings': {
+            'cflags': [
+              '<!@(pkg-config --cflags-only-I ipp)',
+            ],
+          },
+        }],
         ['OS=="mac"', {
           'direct_dependent_settings': {
             'defines': [
@@ -472,10 +476,9 @@
               # If this is unhandled, the console will receive log messages
               # such as:
               # com.google.Chrome[] objc[]: Class ScrollbarPrefsObserver is implemented in both .../Google Chrome.app/Contents/Versions/.../Google Chrome Helper.app/Contents/MacOS/../../../Google Chrome Framework.framework/Google Chrome Framework and /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/WebCore. One of the two will be used. Which one is undefined.
-              'WebCoreFlippedView=ChromiumWebCoreObjCWebCoreFlippedView',
               'WebCoreTextFieldCell=ChromiumWebCoreObjCWebCoreTextFieldCell',
               'WebCoreRenderThemeNotificationObserver=ChromiumWebCoreObjCWebCoreRenderThemeNotificationObserver',
-             ],
+            ],
             'postbuilds': [
               {
                 # This step ensures that any Objective-C names that aren't
@@ -496,13 +499,6 @@
             ],
           },
         }],
-        ['OS in ("linux", "android") and "WTF_USE_WEBAUDIO_IPP=1" in feature_defines', {
-          'direct_dependent_settings': {
-            'cflags': [
-              '<!@(pkg-config --cflags-only-I ipp)',
-            ],
-          },
-        }],
         ['"WTF_USE_WEBAUDIO_FFMPEG=1" in feature_defines', {
           # This directory needs to be on the include path for multiple sub-targets of webcore.
           'direct_dependent_settings': {
@@ -572,102 +568,6 @@
       ],
     },
     {
-      'target_name': 'webcore_platform',
-      'type': 'static_library',
-      'dependencies': [
-        'webcore_prerequisites',
-      ],
-      # Disable c4267 warnings until we fix size_t to int truncations.
-      # Disable c4724 warnings which is generated in VS2012 due to improper
-      # compiler optimizations, see crbug.com/237063
-      'msvs_disabled_warnings': [ 4267, 4334, 4724 ],
-      'sources': [
-        '<@(webcore_platform_files)',
-      ],
-      'sources/': [
-        # FIXME: Figure out how to store these patterns in a variable.
-        ['exclude', '(cf|cg|harfbuzz|mac|opentype|svg|win)/'],
-        ['exclude', '(?<!Chromium)(CF|CG|Mac|Win)\\.(cpp|mm?)$'],
-
-        # Used only by mac.
-        ['exclude', 'platform/Theme\\.cpp$'],
-      ],
-      'conditions': [
-        ['OS!="linux"', {
-          'sources/': [
-            ['exclude', 'Linux\\.cpp$'],
-          ],
-        }],
-        ['toolkit_uses_gtk == 0', {
-          'sources/': [
-            ['exclude', 'platform/chromium/KeyCodeConversionGtk\\.cpp$'],
-          ],
-        }],
-        ['OS=="mac"', {
-          'sources': [
-            'editing/SmartReplaceCF.cpp',
-          ],
-          'link_settings': {
-            'libraries': [
-              '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
-            ],
-          },
-          'sources/': [
-            # Additional files from the WebCore Mac build that are presently
-            # used in the WebCore Chromium Mac build too.
-
-            # The Mac build is USE(CF).
-            ['include', 'CF\\.cpp$'],
-
-            # Cherry-pick some files that can't be included by broader regexps.
-            # Some of these are used instead of Chromium platform files, see
-            # the specific exclusions in the "exclude" list below.
-            ['include', 'platform/mac/ThemeMac\\.h$'],
-            ['include', 'platform/mac/ThemeMac\\.mm$'],
-            ['include', 'platform/mac/WebCoreSystemInterface\\.h$'],
-            ['include', 'platform/mac/WebCoreTextRenderer\\.mm$'],
-            ['include', 'platform/text/mac/ShapeArabic\\.c$'],
-            ['include', 'platform/text/mac/String(Impl)?Mac\\.mm$'],
-            # Use USE_NEW_THEME on Mac.
-            ['include', 'platform/Theme\\.cpp$'],
-          ],
-        }],
-        ['OS=="win"', {
-          'sources/': [
-            ['exclude', 'Posix\\.cpp$'],
-          ],
-        },{ # OS!="win"
-          'sources/': [
-            ['exclude', 'Win\\.cpp$'],
-          ],
-        }],
-        ['OS=="win" and chromium_win_pch==1', {
-          'sources/': [
-            ['include', '<(DEPTH)/third_party/WebKit/Source/build/win/Precompile.cpp'],
-          ],
-        }],
-        ['OS=="android"', {
-          'sources/': [
-            ['include', 'platform/chromium/ClipboardChromiumLinux\\.cpp$'],
-            ['include', 'platform/chromium/FileSystemChromiumLinux\\.cpp$'],
-          ],
-        }, { # OS!="android"
-          'sources/': [
-            ['exclude', 'Android\\.cpp$'],
-          ],
-        }],
-        ['use_default_render_theme==1', {
-          'sources/': [
-            ['exclude', 'platform/chromium/PlatformThemeChromiumWin\\.(cpp|h)'],
-          ],
-        }, { # use_default_render_theme==0
-          'sources/': [
-            ['exclude', 'platform/chromium/PlatformThemeChromiumDefault\\.(cpp|h)'],
-          ],
-        }],
-      ],
-    },
-    {
       'target_name': 'webcore_rendering',
       'type': 'static_library',
       'dependencies': [
@@ -697,11 +597,6 @@
             ['exclude', 'rendering/RenderThemeChromiumDefault.*'],
           ],
         }],
-        ['use_default_render_theme==1', {
-          'sources/': [
-            ['exclude', 'RenderThemeChromiumWin.*'],
-          ],
-        }],
         ['OS=="win"', {
           'sources/': [
             ['exclude', 'Posix\\.cpp$'],
@@ -795,7 +690,33 @@
         }, { # OS!="android"
           'sources/': [['exclude', 'Android\\.cpp$']]
         }],
-        ['OS!="mac"', {
+        ['OS=="mac"', {
+          'sources': [
+            'editing/SmartReplaceCF.cpp',
+          ],
+          'link_settings': {
+            'libraries': [
+              '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
+            ],
+          },
+          'sources/': [
+            # Additional files from the WebCore Mac build that are presently
+            # used in the WebCore Chromium Mac build too.
+
+            # The Mac build is USE(CF).
+            ['include', 'CF\\.cpp$'],
+
+            # Cherry-pick some files that can't be included by broader regexps.
+            # Some of these are used instead of Chromium platform files, see
+            # the specific exclusions in the "exclude" list below.
+            ['include', 'platform/mac/WebCoreSystemInterface\\.h$'],
+            ['include', 'platform/mac/WebCoreTextRenderer\\.mm$'],
+            ['include', 'platform/text/mac/ShapeArabic\\.c$'],
+            ['include', 'platform/text/mac/String(Impl)?Mac\\.mm$'],
+            # Use USE_NEW_THEME on Mac.
+            ['include', 'platform/Theme\\.cpp$'],
+          ],
+        }, { # OS!="mac"
           'sources/': [['exclude', 'Mac\\.(cpp|mm?)$']]
         }],
         ['OS=="win" and chromium_win_pch==1', {
@@ -813,12 +734,11 @@
       'dependencies': [
         'webcore_dom',
         'webcore_html',
-        'webcore_platform',
         'webcore_remaining',
         'webcore_rendering',
         'webcore_svg',
         # Exported.
-        'webcore_derived',
+        'webcore_generated',
         '../wtf/wtf.gyp:wtf',
         '<(DEPTH)/skia/skia.gyp:skia',
         '<(DEPTH)/third_party/npapi/npapi.gyp:npapi',
@@ -828,7 +748,7 @@
       ],
       'export_dependent_settings': [
         '../wtf/wtf.gyp:wtf',
-        'webcore_derived',
+        'webcore_generated',
         '<(DEPTH)/skia/skia.gyp:skia',
         '<(DEPTH)/third_party/npapi/npapi.gyp:npapi',
         '<(DEPTH)/third_party/qcms/qcms.gyp:qcms',
@@ -863,7 +783,7 @@
       ],
     },
     {
-      'target_name': 'webcore_test_support',
+      'target_name': 'webcore_testing',
       'type': 'static_library',
       'dependencies': [
         '../config.gyp:config',
@@ -879,7 +799,7 @@
         'testing/v8',
       ],
       'sources': [
-        '<@(webcore_test_support_files)',
+        '<@(webcore_testing_files)',
         '<(SHARED_INTERMEDIATE_DIR)/blink/bindings/V8GCObservation.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/blink/bindings/V8GCObservation.h',
         '<(SHARED_INTERMEDIATE_DIR)/blink/bindings/V8MallocStatistics.cpp',
diff --git a/Source/core/core.gypi b/Source/core/core.gypi
index 220a8be..8862cf7 100644
--- a/Source/core/core.gypi
+++ b/Source/core/core.gypi
@@ -1,6 +1,15 @@
 {
     'variables': {
+        # Files for which bindings (.cpp and .h files) will be generated
         'core_idl_files': [
+            'animation/Animation.idl',
+            'animation/Player.idl',
+            'animation/TimedItem.idl',
+            'animation/Timeline.idl',
+            'animation/Timing.idl',
+            'clipboard/Clipboard.idl',
+            'clipboard/DataTransferItem.idl',
+            'clipboard/DataTransferItemList.idl',
             'css/CSS.idl',
             'css/CSSCharsetRule.idl',
             'css/CSSFontFaceLoadEvent.idl',
@@ -22,13 +31,11 @@
             # 'css/CSSUnknownRule.idl',
             'css/CSSValue.idl',
             'css/CSSValueList.idl',
-            'css/CSSVariablesMap.idl',
-            'css/CSSVariablesMapForEachCallback.idl',
             'css/CSSViewportRule.idl',
             'css/Counter.idl',
-            'css/DocumentFontFaceSet.idl',
             'css/FontFace.idl',
             'css/FontFaceSet.idl',
+            'css/FontFaceSetForEachCallback.idl',
             'css/MediaList.idl',
             'css/MediaQueryList.idl',
             'css/RGBColor.idl',
@@ -39,16 +46,12 @@
             'css/WebKitCSSFilterRule.idl',
             'css/WebKitCSSFilterValue.idl',
             'css/WebKitCSSMatrix.idl',
-            'css/WebKitCSSMixFunctionValue.idl',
-            'css/WebKitCSSRegionRule.idl',
             'css/WebKitCSSTransformValue.idl',
             'dom/Attr.idl',
             'dom/CDATASection.idl',
             'dom/CharacterData.idl',
-            'dom/ChildNode.idl',
             'dom/ClientRect.idl',
             'dom/ClientRectList.idl',
-            'dom/Clipboard.idl',
             'dom/Comment.idl',
             'dom/DOMError.idl',
             'dom/DOMException.idl',
@@ -57,15 +60,10 @@
             'dom/DOMStringList.idl',
             'dom/DOMStringMap.idl',
             'dom/DOMTokenList.idl',
-            'dom/DataTransferItem.idl',
-            'dom/DataTransferItemList.idl',
             'dom/Document.idl',
             'dom/DocumentFragment.idl',
-            'dom/DocumentFullscreen.idl',
             'dom/DocumentType.idl',
             'dom/Element.idl',
-            'dom/Entity.idl',
-            'dom/GlobalEventHandlers.idl',
             'dom/MessageChannel.idl',
             'dom/MessagePort.idl',
             'dom/MutationObserver.idl',
@@ -76,7 +74,6 @@
             'dom/NodeIterator.idl',
             'dom/NodeList.idl',
             'dom/Notation.idl',
-            'dom/ParentNode.idl',
             'dom/ProcessingInstruction.idl',
             'dom/Promise.idl',
             'dom/Range.idl',
@@ -87,10 +84,7 @@
             'dom/TouchList.idl',
             'dom/TreeWalker.idl',
             'dom/URL.idl',
-            'dom/URLUtils.idl',
-            'dom/URLUtilsReadOnly.idl',
-            'dom/WebKitNamedFlow.idl',
-            'dom/WebKitNamedFlowCollection.idl',
+            'dom/XMLDocument.idl',
             'dom/shadow/ShadowRoot.idl',
             'events/AutocompleteErrorEvent.idl',
             'events/BeforeLoadEvent.idl',
@@ -106,7 +100,6 @@
             'events/MessageEvent.idl',
             'events/MouseEvent.idl',
             'events/MutationEvent.idl',
-            'events/NavigatorEvents.idl',
             'events/OverflowEvent.idl',
             'events/PageTransitionEvent.idl',
             'events/PopStateEvent.idl',
@@ -133,15 +126,9 @@
             'frame/ImageBitmap.idl',
             'frame/Location.idl',
             'frame/Navigator.idl',
-            'frame/NavigatorID.idl',
-            'frame/NavigatorOnLine.idl',
             'frame/Screen.idl',
-            'frame/SecurityPolicy.idl',
             'frame/WebKitPoint.idl',
             'frame/Window.idl',
-            'frame/WindowBase64.idl',
-            'frame/WindowEventHandlers.idl',
-            'frame/WindowTimers.idl',
             'html/FormData.idl',
             'html/HTMLAllCollection.idl',
             'html/HTMLAnchorElement.idl',
@@ -264,7 +251,6 @@
             'html/canvas/WebGLTexture.idl',
             'html/canvas/WebGLUniformLocation.idl',
             'html/canvas/WebGLVertexArrayObjectOES.idl',
-            'html/ime/Composition.idl',
             'html/ime/InputMethodContext.idl',
             'html/shadow/HTMLContentElement.idl',
             'html/shadow/HTMLShadowElement.idl',
@@ -284,7 +270,6 @@
             'page/EventSource.idl',
             'page/PagePopupController.idl',
             'page/Selection.idl',
-            'page/WindowPagePopup.idl',
             'plugins/MimeType.idl',
             'plugins/MimeTypeArray.idl',
             'plugins/Plugin.idl',
@@ -294,43 +279,11 @@
             'speech/SpeechInputResultList.idl',
             'storage/Storage.idl',
             'storage/StorageEvent.idl',
-            'timing/MemoryInfo.idl',
-            'timing/Performance.idl',
-            'timing/PerformanceEntry.idl',
-            'timing/PerformanceMark.idl',
-            'timing/PerformanceMeasure.idl',
-            'timing/PerformanceNavigation.idl',
-            'timing/PerformanceResourceTiming.idl',
-            'timing/PerformanceTiming.idl',
-            'workers/AbstractWorker.idl',
-            'workers/DedicatedWorkerGlobalScope.idl',
-            'workers/SharedWorker.idl',
-            'workers/SharedWorkerGlobalScope.idl',
-            'workers/Worker.idl',
-            'workers/WorkerConsole.idl',
-            'workers/WorkerGlobalScope.idl',
-            'workers/WorkerLocation.idl',
-            'workers/WorkerNavigator.idl',
-            'xml/DOMParser.idl',
-            'xml/DocumentXPathEvaluator.idl',
-            'xml/XMLHttpRequest.idl',
-            'xml/XMLHttpRequestEventTarget.idl',
-            'xml/XMLHttpRequestProgressEvent.idl',
-            'xml/XMLHttpRequestUpload.idl',
-            'xml/XMLSerializer.idl',
-            'xml/XPathEvaluator.idl',
-            'xml/XPathExpression.idl',
-            'xml/XPathNSResolver.idl',
-            'xml/XPathResult.idl',
-            'xml/XSLTProcessor.idl',
-        ],
-        'svg_idl_files': [
             'svg/SVGAElement.idl',
             'svg/SVGAltGlyphDefElement.idl',
             'svg/SVGAltGlyphElement.idl',
             'svg/SVGAltGlyphItemElement.idl',
             'svg/SVGAngle.idl',
-            'svg/SVGAnimateColorElement.idl',
             'svg/SVGAnimateElement.idl',
             'svg/SVGAnimateMotionElement.idl',
             'svg/SVGAnimateTransformElement.idl',
@@ -349,17 +302,15 @@
             'svg/SVGAnimationElement.idl',
             'svg/SVGCircleElement.idl',
             'svg/SVGClipPathElement.idl',
-            'svg/SVGColor.idl',
             'svg/SVGComponentTransferFunctionElement.idl',
             'svg/SVGCursorElement.idl',
             'svg/SVGDefsElement.idl',
             'svg/SVGDescElement.idl',
-            'svg/SVGDocument.idl',
+            'svg/SVGDiscardElement.idl',
             'svg/SVGElement.idl',
             'svg/SVGElementInstance.idl',
             'svg/SVGElementInstanceList.idl',
             'svg/SVGEllipseElement.idl',
-            'svg/SVGExternalResourcesRequired.idl',
             'svg/SVGFEBlendElement.idl',
             'svg/SVGFEColorMatrixElement.idl',
             'svg/SVGFEComponentTransferElement.idl',
@@ -386,8 +337,6 @@
             'svg/SVGFETileElement.idl',
             'svg/SVGFETurbulenceElement.idl',
             'svg/SVGFilterElement.idl',
-            'svg/SVGFilterPrimitiveStandardAttributes.idl',
-            'svg/SVGFitToViewBox.idl',
             'svg/SVGFontElement.idl',
             'svg/SVGFontFaceElement.idl',
             'svg/SVGFontFaceFormatElement.idl',
@@ -415,7 +364,6 @@
             'svg/SVGMissingGlyphElement.idl',
             'svg/SVGNumber.idl',
             'svg/SVGNumberList.idl',
-            'svg/SVGPaint.idl',
             'svg/SVGPathElement.idl',
             'svg/SVGPathSeg.idl',
             'svg/SVGPathSegArcAbs.idl',
@@ -457,7 +405,6 @@
             'svg/SVGSwitchElement.idl',
             'svg/SVGSymbolElement.idl',
             'svg/SVGTSpanElement.idl',
-            'svg/SVGTests.idl',
             'svg/SVGTextContentElement.idl',
             'svg/SVGTextElement.idl',
             'svg/SVGTextPathElement.idl',
@@ -465,14 +412,66 @@
             'svg/SVGTitleElement.idl',
             'svg/SVGTransform.idl',
             'svg/SVGTransformList.idl',
-            'svg/SVGURIReference.idl',
             'svg/SVGUnitTypes.idl',
             'svg/SVGUseElement.idl',
             'svg/SVGVKernElement.idl',
             'svg/SVGViewElement.idl',
             'svg/SVGViewSpec.idl',
-            'svg/SVGZoomAndPan.idl',
             'svg/SVGZoomEvent.idl',
+            'timing/MemoryInfo.idl',
+            'timing/Performance.idl',
+            'timing/PerformanceEntry.idl',
+            'timing/PerformanceMark.idl',
+            'timing/PerformanceMeasure.idl',
+            'timing/PerformanceNavigation.idl',
+            'timing/PerformanceResourceTiming.idl',
+            'timing/PerformanceTiming.idl',
+            'workers/DedicatedWorkerGlobalScope.idl',
+            'workers/SharedWorker.idl',
+            'workers/SharedWorkerGlobalScope.idl',
+            'workers/Worker.idl',
+            'workers/WorkerConsole.idl',
+            'workers/WorkerGlobalScope.idl',
+            'workers/WorkerLocation.idl',
+            'workers/WorkerNavigator.idl',
+            'xml/DOMParser.idl',
+            'xml/XMLHttpRequest.idl',
+            'xml/XMLHttpRequestEventTarget.idl',
+            'xml/XMLHttpRequestProgressEvent.idl',
+            'xml/XMLHttpRequestUpload.idl',
+            'xml/XMLSerializer.idl',
+            'xml/XPathEvaluator.idl',
+            'xml/XPathExpression.idl',
+            'xml/XPathNSResolver.idl',
+            'xml/XPathResult.idl',
+            'xml/XSLTProcessor.idl',
+        ],
+        # 'partial interface' or target (right side of) 'implements'
+        'core_dependency_idl_files': [
+            'animation/DocumentAnimation.idl',
+            'animation/ElementAnimation.idl',
+            'css/DocumentFontFaceSet.idl',
+            'dom/ChildNode.idl',
+            'dom/DocumentFullscreen.idl',
+            'dom/GlobalEventHandlers.idl',
+            'dom/ParentNode.idl',
+            'dom/URLUtils.idl',
+            'dom/URLUtilsReadOnly.idl',
+            'events/NavigatorEvents.idl',
+            'frame/NavigatorID.idl',
+            'frame/NavigatorOnLine.idl',
+            'frame/WindowBase64.idl',
+            'frame/WindowEventHandlers.idl',
+            'frame/WindowTimers.idl',
+            'page/WindowPagePopup.idl',
+            'svg/SVGDocument.idl',
+            'svg/SVGFilterPrimitiveStandardAttributes.idl',
+            'svg/SVGFitToViewBox.idl',
+            'svg/SVGTests.idl',
+            'svg/SVGURIReference.idl',
+            'svg/SVGZoomAndPan.idl',
+            'workers/AbstractWorker.idl',
+            'xml/DocumentXPathEvaluator.idl',
         ],
         'webcore_files': [
             'Init.cpp',
@@ -577,33 +576,59 @@
             'animation/Animation.h',
             'animation/AnimationClock.h',
             'animation/AnimationEffect.h',
+            'animation/AnimationHelpers.h',
             'animation/AnimationStack.cpp',
             'animation/AnimationStack.h',
+            'animation/AnimationTranslationUtil.cpp',
+            'animation/AnimationTranslationUtil.h',
             'animation/CompositorAnimations.cpp',
             'animation/CompositorAnimations.h',
             'animation/CompositorAnimationsImpl.h',
+            'animation/DocumentAnimation.h',
             'animation/DocumentAnimations.cpp',
             'animation/DocumentAnimations.h',
             'animation/DocumentTimeline.cpp',
             'animation/DocumentTimeline.h',
+            'animation/ElementAnimation.cpp',
+            'animation/ElementAnimation.h',
             'animation/InertAnimation.cpp',
             'animation/InertAnimation.h',
-            'animation/KeyframeAnimationEffect.cpp',
-            'animation/KeyframeAnimationEffect.h',
+            'animation/KeyframeEffectModel.cpp',
+            'animation/KeyframeEffectModel.h',
             'animation/Player.cpp',
             'animation/Player.h',
             'animation/TimedItem.cpp',
             'animation/TimedItem.h',
             'animation/TimedItemCalculations.h',
+            'animation/TimedItemTiming.cpp',
+            'animation/TimedItemTiming.h',
             'animation/Timing.h',
             'animation/css/CSSAnimatableValueFactory.cpp',
             'animation/css/CSSAnimatableValueFactory.h',
             'animation/css/CSSAnimations.cpp',
             'animation/css/CSSAnimations.h',
+            'animation/css/CSSAnimationData.cpp',
+            'animation/css/CSSAnimationData.h',
+            'animation/css/CSSAnimationDataList.cpp',
+            'animation/css/CSSAnimationDataList.h',
             'animation/css/CSSPendingAnimations.cpp',
             'animation/css/CSSPendingAnimations.h',
+            'animation/css/CSSPropertyAnimation.cpp',
+            'animation/css/CSSPropertyAnimation.h',
             'animation/css/TransitionTimeline.cpp',
             'animation/css/TransitionTimeline.h',
+            'clipboard/Clipboard.cpp',
+            'clipboard/Clipboard.h',
+            'clipboard/DataObject.cpp',
+            'clipboard/DataObject.h',
+            'clipboard/DataObjectItem.cpp',
+            'clipboard/DataObjectItem.h',
+            'clipboard/DataTransferItem.cpp',
+            'clipboard/DataTransferItem.h',
+            'clipboard/DataTransferItemList.cpp',
+            'clipboard/DataTransferItemList.h',
+            'clipboard/Pasteboard.cpp',
+            'clipboard/Pasteboard.h',
             'css/BasicShapeFunctions.cpp',
             'css/CSSArrayFunctionValue.cpp',
             'css/CSSArrayFunctionValue.h',
@@ -645,6 +670,7 @@
             'css/CSSFontFeatureValue.h',
             'css/CSSFontSelector.cpp',
             'css/CSSFontSelector.h',
+            'css/CSSFontSelectorClient.h',
             'css/CSSFontValue.cpp',
             'css/CSSFontValue.h',
             'css/CSSFunctionValue.cpp',
@@ -653,8 +679,8 @@
             'css/CSSGradientValue.h',
             'css/CSSGridLineNamesValue.cpp',
             'css/CSSGridLineNamesValue.h',
-            'css/CSSGridTemplateValue.cpp',
-            'css/CSSGridTemplateValue.h',
+            'css/CSSGridTemplateAreasValue.cpp',
+            'css/CSSGridTemplateAreasValue.h',
             'css/CSSGroupingRule.cpp',
             'css/CSSGroupingRule.h',
             'css/CSSImageGeneratorValue.cpp',
@@ -670,20 +696,18 @@
             'css/CSSKeyframeRule.h',
             'css/CSSKeyframesRule.cpp',
             'css/CSSKeyframesRule.h',
-            'css/CSSLengthFunctions.cpp',
-            'css/CSSLengthFunctions.h',
             'css/CSSLineBoxContainValue.cpp',
             'css/CSSMatrix.cpp',
             'css/CSSMatrix.h',
+            'css/CSSMarkup.cpp',
+            'css/CSSMarkup.h',
             'css/CSSMediaRule.cpp',
             'css/CSSMediaRule.h',
-            'css/CSSMixFunctionValue.cpp',
-            'css/CSSMixFunctionValue.h',
             'css/CSSOMUtils.cpp',
             'css/CSSOMUtils.h',
             'css/CSSPageRule.cpp',
             'css/CSSPageRule.h',
-            'css/CSSParser.h',
+            'css/parser/BisonCSSParser.h',
             'css/CSSParserMode.cpp',
             'css/CSSParserMode.h',
             'css/CSSParserValues.cpp',
@@ -692,24 +716,19 @@
             'css/CSSProperty.cpp',
             'css/CSSPropertySourceData.cpp',
             'css/CSSReflectValue.cpp',
-            'css/CSSRegionRule.cpp',
-            'css/CSSRegionRule.h',
             'css/CSSRule.cpp',
             'css/CSSRule.h',
             'css/CSSRuleList.cpp',
             'css/CSSRuleList.h',
+            'css/CSSSVGDocumentValue.cpp',
+            'css/CSSSVGDocumentValue.h',
             'css/CSSSegmentedFontFace.cpp',
             'css/CSSSegmentedFontFace.h',
-            'css/CSSSegmentedFontFaceCache.cpp',
-            'css/CSSSegmentedFontFaceCache.h',
             'css/CSSSelector.cpp',
             'css/CSSSelectorList.cpp',
             'css/CSSSelectorList.h',
-            'css/CSSShaderValue.cpp',
-            'css/CSSShaderValue.h',
             'css/CSSShadowValue.cpp',
             'css/CSSShadowValue.h',
-            'css/CSSStyleDeclaration.cpp',
             'css/CSSStyleDeclaration.h',
             'css/CSSStyleRule.cpp',
             'css/CSSStyleRule.h',
@@ -717,13 +736,11 @@
             'css/CSSStyleSheet.h',
             'css/CSSSupportsRule.cpp',
             'css/CSSSupportsRule.h',
-            'css/CSSSVGDocumentValue.cpp',
-            'css/CSSSVGDocumentValue.h',
             'css/CSSTimingFunctionValue.cpp',
             'css/CSSTimingFunctionValue.h',
-            'css/CSSTokenizer.h',
             'css/CSSToLengthConversionData.cpp',
             'css/CSSToLengthConversionData.h',
+            'css/CSSTokenizer.h',
             'css/CSSTransformValue.cpp',
             'css/CSSUnicodeRangeValue.cpp',
             'css/CSSUnicodeRangeValue.h',
@@ -732,29 +749,26 @@
             'css/CSSValueList.cpp',
             'css/CSSValuePool.cpp',
             'css/CSSValuePool.h',
-            'css/CSSVariablesIterator.h',
-            'css/CSSVariablesMap.cpp',
-            'css/CSSVariablesMap.h',
-            'css/CSSVariablesMapForEachCallback.h',
-            'css/CSSVariableValue.h',
-            'css/CSSViewportRule.h',
             'css/CSSViewportRule.cpp',
+            'css/CSSViewportRule.h',
+            'css/Counter.cpp',
             'css/Counter.h',
             'css/DOMWindowCSS.cpp',
             'css/DOMWindowCSS.h',
-            'css/DocumentFontFaceSet.h',
             'css/DocumentFontFaceSet.cpp',
+            'css/DocumentFontFaceSet.h',
             'css/ElementRuleCollector.cpp',
             'css/ElementRuleCollector.h',
-            'css/FontFaceSet.h',
-            'css/FontFaceSet.cpp',
             'css/FontFace.cpp',
             'css/FontFace.h',
+            'css/FontFaceCache.cpp',
+            'css/FontFaceCache.h',
+            'css/FontFaceSet.cpp',
+            'css/FontFaceSet.h',
+            'css/FontFaceSetForEachCallback.h',
             'css/FontSize.cpp',
             'css/FontSize.h',
             'css/HashTools.h',
-            'css/InspectorCSSOMWrappers.cpp',
-            'css/InspectorCSSOMWrappers.h',
             'css/MediaFeatureNames.cpp',
             'css/MediaFeatureNames.h',
             'css/MediaList.cpp',
@@ -773,6 +787,8 @@
             'css/MediaQueryMatcher.h',
             'css/PageRuleCollector.cpp',
             'css/PageRuleCollector.h',
+            'css/Pair.cpp',
+            'css/Pair.h',
             'css/PropertySetCSSStyleDeclaration.cpp',
             'css/PropertySetCSSStyleDeclaration.h',
             'css/PseudoStyleRequest.h',
@@ -783,6 +799,8 @@
             'css/RuleFeature.h',
             'css/RuleSet.cpp',
             'css/RuleSet.h',
+            'css/RuntimeCSSEnabled.cpp',
+            'css/RuntimeCSSEnabled.h',
             'css/SVGCSSComputedStyleDeclaration.cpp',
             'css/SVGCSSParser.cpp',
             'css/SelectorChecker.cpp',
@@ -814,6 +832,8 @@
             'css/StyleSheetList.h',
             'css/TreeBoundaryCrossingRules.cpp',
             'css/TreeBoundaryCrossingRules.h',
+            'css/analyzer/DescendantInvalidationSet.h',
+            'css/analyzer/DescendantInvalidationSet.cpp',
             'css/resolver/AnimatedStyleBuilder.cpp',
             'css/resolver/AnimatedStyleBuilder.h',
             'css/resolver/CSSToStyleMap.cpp',
@@ -826,11 +846,11 @@
             'css/resolver/FilterOperationResolver.h',
             'css/resolver/FontBuilder.cpp',
             'css/resolver/FontBuilder.h',
-            'css/resolver/MatchedPropertiesCache.cpp',
-            'css/resolver/MatchedPropertiesCache.h',
+            'css/resolver/MatchRequest.h',
             'css/resolver/MatchResult.cpp',
             'css/resolver/MatchResult.h',
-            'css/resolver/MatchRequest.h',
+            'css/resolver/MatchedPropertiesCache.cpp',
+            'css/resolver/MatchedPropertiesCache.h',
             'css/resolver/MediaQueryResult.h',
             'css/resolver/ScopedStyleResolver.cpp',
             'css/resolver/ScopedStyleResolver.h',
@@ -845,7 +865,6 @@
             'css/resolver/StyleBuilderCustom.cpp',
             'css/resolver/StyleResolver.cpp',
             'css/resolver/StyleResolver.h',
-            'css/resolver/StyleResolverIncludes.h',
             'css/resolver/StyleResolverState.cpp',
             'css/resolver/StyleResolverState.h',
             'css/resolver/StyleResolverStats.cpp',
@@ -873,6 +892,8 @@
             'editing/DeleteFromTextNodeCommand.h',
             'editing/DeleteSelectionCommand.cpp',
             'editing/EditCommand.cpp',
+            'editing/EditingBehavior.cpp',
+            'editing/EditingBehavior.h',
             'editing/EditingStyle.cpp',
             'editing/Editor.cpp',
             'editing/EditorCommand.cpp',
@@ -901,11 +922,9 @@
             'editing/MarkupAccumulator.h',
             'editing/MergeIdenticalElementsCommand.cpp',
             'editing/MergeIdenticalElementsCommand.h',
-            'editing/ModifySelectionListLevel.cpp',
-            'editing/ModifySelectionListLevel.h',
             'editing/MoveSelectionCommand.cpp',
-            'editing/PlainTextRange.h',
             'editing/PlainTextRange.cpp',
+            'editing/PlainTextRange.h',
             'editing/RemoveCSSPropertyCommand.cpp',
             'editing/RemoveCSSPropertyCommand.h',
             'editing/RemoveFormatCommand.cpp',
@@ -922,17 +941,13 @@
             'editing/SelectionType.h',
             'editing/SetNodeAttributeCommand.cpp',
             'editing/SetNodeAttributeCommand.h',
-            'editing/SetSelectionCommand.cpp',
-            'editing/SetSelectionCommand.h',
             'editing/SimplifyMarkupCommand.cpp',
             'editing/SmartReplaceCF.cpp',
             'editing/SmartReplaceICU.cpp',
-            'editing/SpellChecker.cpp',
-            'editing/SpellChecker.h',
             'editing/SpellCheckRequester.cpp',
             'editing/SpellCheckRequester.h',
-            'editing/SpellingCorrectionCommand.cpp',
-            'editing/SpellingCorrectionCommand.h',
+            'editing/SpellChecker.cpp',
+            'editing/SpellChecker.h',
             'editing/SplitElementCommand.cpp',
             'editing/SplitElementCommand.h',
             'editing/SplitTextNodeCommand.cpp',
@@ -959,23 +974,26 @@
             'editing/WrapContentsInDummySpanCommand.h',
             'editing/htmlediting.cpp',
             'editing/markup.cpp',
+            'fetch/CSSStyleSheetResource.cpp',
+            'fetch/CSSStyleSheetResource.h',
             'fetch/CachedMetadata.cpp',
             'fetch/CachedMetadata.h',
             'fetch/CrossOriginAccessControl.cpp',
             'fetch/CrossOriginAccessControl.h',
-            'fetch/CSSStyleSheetResource.cpp',
-            'fetch/CSSStyleSheetResource.h',
             'fetch/DocumentResource.cpp',
             'fetch/DocumentResource.h',
             'fetch/DocumentResourceReference.h',
             'fetch/FetchContext.cpp',
             'fetch/FetchContext.h',
+            'fetch/FetchInitiatorInfo.h',
             'fetch/FetchRequest.cpp',
             'fetch/FetchRequest.h',
             'fetch/FontResource.cpp',
             'fetch/FontResource.h',
             'fetch/ImageResource.cpp',
             'fetch/ImageResource.h',
+            'fetch/MemoryCache.cpp',
+            'fetch/MemoryCache.h',
             'fetch/RawResource.cpp',
             'fetch/RawResource.h',
             'fetch/Resource.cpp',
@@ -983,30 +1001,23 @@
             'fetch/ResourceClientWalker.h',
             'fetch/ResourceFetcher.cpp',
             'fetch/ResourceFetcher.h',
+            'fetch/ResourceLoadPriorityOptimizer.cpp',
+            'fetch/ResourceLoadPriorityOptimizer.h',
             'fetch/ResourceLoader.cpp',
             'fetch/ResourceLoader.h',
             'fetch/ResourceLoaderOptions.h',
             'fetch/ResourceLoaderSet.cpp',
             'fetch/ResourceLoaderSet.h',
-            'fetch/ResourceLoadPriorityOptimizer.cpp',
-            'fetch/ResourceLoadPriorityOptimizer.h',
             'fetch/ResourcePtr.cpp',
             'fetch/ResourcePtr.h',
-            'fetch/FetchInitiatorInfo.h',
             'fetch/ScriptResource.cpp',
             'fetch/ScriptResource.h',
             'fetch/ShaderResource.cpp',
             'fetch/ShaderResource.h',
-            'fetch/TextResourceDecoder.cpp',
-            'fetch/TextResourceDecoder.h',
             'fetch/XSLStyleSheetResource.cpp',
             'fetch/XSLStyleSheetResource.h',
-            'fetch/MemoryCache.cpp',
-            'fetch/MemoryCache.h',
             'fileapi/Blob.cpp',
             'fileapi/Blob.h',
-            'fileapi/BlobBuilder.cpp',
-            'fileapi/BlobBuilder.h',
             'fileapi/File.cpp',
             'fileapi/File.h',
             'fileapi/FileError.cpp',
@@ -1022,7 +1033,62 @@
             'fileapi/FileReaderSync.h',
             'fileapi/Stream.cpp',
             'fileapi/Stream.h',
-            'history/HistoryItem.cpp',
+            'frame/BarProp.cpp',
+            'frame/BarProp.h',
+            'frame/Console.cpp',
+            'frame/Console.h',
+            'frame/ConsoleBase.cpp',
+            'frame/ConsoleBase.h',
+            'frame/ContentSecurityPolicy.cpp',
+            'frame/ContentSecurityPolicyResponseHeaders.cpp',
+            'frame/DOMPoint.h',
+            'frame/DOMTimer.cpp',
+            'frame/DOMTimer.h',
+            'frame/DOMWindow.cpp',
+            'frame/DOMWindow.h',
+            'frame/DOMWindowBase64.cpp',
+            'frame/DOMWindowBase64.h',
+            'frame/DOMWindowEventHandlers.h',
+            'frame/DOMWindowLifecycleNotifier.cpp',
+            'frame/DOMWindowLifecycleNotifier.h',
+            'frame/DOMWindowLifecycleObserver.cpp',
+            'frame/DOMWindowLifecycleObserver.h',
+            'frame/DOMWindowProperty.cpp',
+            'frame/DOMWindowProperty.h',
+            'frame/DOMWindowTimers.cpp',
+            'frame/DOMWindowTimers.h',
+            'frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp',
+            'frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.h',
+            'frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp',
+            'frame/DeprecatedScheduleStyleRecalcDuringLayout.h',
+            'frame/Frame.cpp',
+            'frame/Frame.h',
+            'frame/FrameDestructionObserver.cpp',
+            'frame/FrameDestructionObserver.h',
+            'frame/FrameHost.cpp',
+            'frame/FrameHost.h',
+            'frame/FrameView.cpp',
+            'frame/History.cpp',
+            'frame/History.h',
+            'frame/ImageBitmap.cpp',
+            'frame/ImageBitmap.h',
+            'frame/Location.cpp',
+            'frame/Location.h',
+            'frame/Navigator.cpp',
+            'frame/Navigator.h',
+            'frame/NavigatorBase.h',
+            'frame/NavigatorID.cpp',
+            'frame/NavigatorID.h',
+            'frame/NavigatorOnLine.h',
+            'frame/PageConsole.cpp',
+            'frame/Screen.cpp',
+            'frame/Screen.h',
+            'frame/Settings.cpp',
+            'frame/SettingsDelegate.cpp',
+            'frame/SettingsDelegate.h',
+            'frame/SuspendableTimer.cpp',
+            'frame/SuspendableTimer.h',
+            'frame/UseCounter.cpp',
             'inspector/AsyncCallStackTracker.cpp',
             'inspector/AsyncCallStackTracker.h',
             'inspector/BindingVisitors.h',
@@ -1049,7 +1115,6 @@
             'inspector/InjectedScriptManager.h',
             'inspector/InjectedScriptModule.cpp',
             'inspector/InjectedScriptModule.h',
-            'inspector/InspectorAgent.cpp',
             'inspector/InspectorApplicationCacheAgent.cpp',
             'inspector/InspectorApplicationCacheAgent.h',
             'inspector/InspectorBaseAgent.cpp',
@@ -1070,15 +1135,8 @@
             'inspector/InspectorDOMDebuggerAgent.h',
             'inspector/InspectorDOMStorageAgent.cpp',
             'inspector/InspectorDOMStorageAgent.h',
-            'inspector/InspectorDatabaseAgent.cpp',
-            'inspector/InspectorDatabaseAgent.h',
-            'inspector/InspectorDatabaseInstrumentation.h',
-            'inspector/InspectorDatabaseResource.cpp',
-            'inspector/InspectorDatabaseResource.h',
             'inspector/InspectorDebuggerAgent.cpp',
             'inspector/InspectorDebuggerAgent.h',
-            'inspector/InspectorFileSystemAgent.cpp',
-            'inspector/InspectorFileSystemAgent.h',
             'inspector/InspectorFrontendChannel.h',
             'inspector/InspectorFrontendHost.cpp',
             'inspector/InspectorFrontendHost.h',
@@ -1086,10 +1144,9 @@
             'inspector/InspectorHeapProfilerAgent.h',
             'inspector/InspectorHistory.cpp',
             'inspector/InspectorHistory.h',
-            'inspector/InspectorIndexedDBAgent.cpp',
-            'inspector/InspectorIndexedDBAgent.h',
             'inspector/InspectorInputAgent.cpp',
             'inspector/InspectorInputAgent.h',
+            'inspector/InspectorInspectorAgent.cpp',
             'inspector/InspectorInstrumentation.cpp',
             'inspector/InspectorInstrumentation.h',
             'inspector/InspectorInstrumentationCustomInl.h',
@@ -1121,10 +1178,10 @@
             'inspector/InspectorWorkerAgent.cpp',
             'inspector/InspectorWorkerAgent.h',
             'inspector/InstrumentingAgents.h',
-            'inspector/JavaScriptCallFrame.cpp',
-            'inspector/JavaScriptCallFrame.h',
             'inspector/JSONParser.cpp',
             'inspector/JSONParser.h',
+            'inspector/JavaScriptCallFrame.cpp',
+            'inspector/JavaScriptCallFrame.h',
             'inspector/NetworkResourcesData.cpp',
             'inspector/NetworkResourcesData.h',
             'inspector/PageConsoleAgent.cpp',
@@ -1166,12 +1223,13 @@
             'loader/EmptyClients.h',
             'loader/FormState.cpp',
             'loader/FormSubmission.cpp',
-            'loader/FrameFetchContext.h',
             'loader/FrameFetchContext.cpp',
+            'loader/FrameFetchContext.h',
             'loader/FrameLoadRequest.h',
             'loader/FrameLoader.cpp',
             'loader/FrameLoaderStateMachine.cpp',
-            'loader/HistoryController.cpp',
+            'loader/HistoryItem.cpp',
+            'loader/HistoryItem.h',
             'loader/ImageLoader.cpp',
             'loader/ImageLoader.h',
             'loader/LinkLoader.cpp',
@@ -1203,6 +1261,10 @@
             'loader/ThreadableLoaderClientWrapper.h',
             'loader/UniqueIdentifier.cpp',
             'loader/UniqueIdentifier.h',
+            'loader/WorkerLoaderClientBridge.cpp',
+            'loader/WorkerLoaderClientBridge.h',
+            'loader/WorkerLoaderClientBridgeSyncHelper.cpp',
+            'loader/WorkerLoaderClientBridgeSyncHelper.h',
             'loader/WorkerThreadableLoader.cpp',
             'loader/WorkerThreadableLoader.h',
             'loader/appcache/ApplicationCache.cpp',
@@ -1210,60 +1272,28 @@
             'loader/appcache/ApplicationCacheHost.h',
             'page/AutoscrollController.cpp',
             'page/AutoscrollController.h',
-            'frame/BarProp.cpp',
-            'frame/BarProp.h',
             'page/BackForwardClient.h',
             'page/Chrome.cpp',
-            'frame/Console.cpp',
-            'frame/Console.h',
-            'frame/ConsoleBase.cpp',
-            'frame/ConsoleBase.h',
-            'frame/ContentSecurityPolicy.cpp',
-            'frame/ContentSecurityPolicyResponseHeaders.cpp',
             'page/ContextMenuController.cpp',
             'page/ContextMenuProvider.h',
             'page/CreateWindow.cpp',
             'page/CreateWindow.h',
-            'frame/DOMPoint.h',
-            'frame/DOMSecurityPolicy.cpp',
             'page/DOMSelection.cpp',
             'page/DOMSelection.h',
-            'frame/DOMTimer.cpp',
-            'frame/DOMTimer.h',
-            'frame/DOMWindow.cpp',
-            'frame/DOMWindow.h',
-            'frame/DOMWindowBase64.cpp',
-            'frame/DOMWindowBase64.h',
-            'frame/DOMWindowEventHandlers.h',
-            'frame/DOMWindowLifecycleNotifier.cpp',
-            'frame/DOMWindowLifecycleNotifier.h',
-            'frame/DOMWindowLifecycleObserver.cpp',
-            'frame/DOMWindowLifecycleObserver.h',
-            'frame/DOMWindowTimers.cpp',
-            'frame/DOMWindowTimers.h',
             'page/DOMWindowPagePopup.cpp',
             'page/DOMWindowPagePopup.h',
-            'frame/DOMWindowProperty.cpp',
-            'frame/DOMWindowProperty.h',
             'page/DragController.cpp',
             'page/DragData.cpp',
             'page/EventHandler.cpp',
             'page/EventSource.cpp',
             'page/EventSource.h',
             'page/FocusController.cpp',
-            'frame/Frame.cpp',
-            'frame/FrameDestructionObserver.cpp',
-            'frame/FrameDestructionObserver.h',
+            'page/FocusType.h',
             'page/FrameTree.cpp',
-            'frame/FrameView.cpp',
-            'frame/GraphicsLayerDebugInfo.cpp',
-            'frame/History.cpp',
-            'frame/History.h',
-            'frame/ImageBitmap.cpp',
-            'frame/ImageBitmap.h',
-            'frame/Location.cpp',
-            'frame/Location.h',
-            'timing/MemoryInfo.cpp',
+            'page/HistoryController.cpp',
+            'page/HistoryController.h',
+            'page/InjectedStyleSheets.cpp',
+            'page/InjectedStyleSheets.h',
             'page/MouseEventWithHitTestResults.cpp',
             'page/MouseEventWithHitTestResults.h',
             'frame/Navigator.cpp',
@@ -1272,10 +1302,13 @@
             'frame/NavigatorID.cpp',
             'frame/NavigatorID.h',
             'frame/NavigatorOnLine.h',
+            'frame/SettingsDelegate.cpp',
+            'frame/SettingsDelegate.h',
+            'frame/SmartClip.cpp',
+            'frame/SmartClip.h',
             'page/NetworkStateNotifier.cpp',
             'page/NetworkStateNotifier.h',
             'page/Page.cpp',
-            'page/PageConsole.cpp',
             'page/PageGroup.cpp',
             'page/PageGroupLoadDeferrer.cpp',
             'page/PageGroupLoadDeferrer.h',
@@ -1283,62 +1316,25 @@
             'page/PageLifecycleNotifier.h',
             'page/PageLifecycleObserver.cpp',
             'page/PageLifecycleObserver.h',
-            'page/PagePopupController.cpp',
-            'page/PagePopupController.h',
             'page/PagePopupClient.cpp',
             'page/PagePopupClient.h',
+            'page/PagePopupController.cpp',
+            'page/PagePopupController.h',
             'page/PageScaleConstraints.cpp',
             'page/PageScaleConstraints.h',
             'page/PageSerializer.cpp',
             'page/PageVisibilityState.cpp',
-            'timing/Performance.cpp',
-            'timing/Performance.h',
-            'timing/PerformanceEntry.cpp',
-            'timing/PerformanceEntry.h',
-            'timing/PerformanceMark.h',
-            'timing/PerformanceMeasure.h',
-            'timing/PerformanceNavigation.cpp',
-            'timing/PerformanceNavigation.h',
-            'timing/PerformanceResourceTiming.cpp',
-            'timing/PerformanceResourceTiming.h',
-            'timing/PerformanceTiming.cpp',
-            'timing/PerformanceTiming.h',
-            'timing/PerformanceUserTiming.cpp',
-            'timing/PerformanceUserTiming.h',
             'page/PointerLockController.cpp',
             'page/PointerLockController.h',
             'page/PopupOpeningObserver.h',
             'page/PrintContext.cpp',
-            'timing/ResourceTimingInfo.h',
-            'page/RuntimeCSSEnabled.cpp',
-            'page/RuntimeCSSEnabled.h',
-            'frame/Screen.cpp',
-            'frame/Screen.h',
-            'page/Settings.cpp',
             'page/SpatialNavigation.cpp',
-            'frame/SuspendableTimer.cpp',
-            'frame/SuspendableTimer.h',
             'page/TouchAdjustment.cpp',
             'page/TouchAdjustment.h',
             'page/TouchDisambiguation.cpp',
             'page/TouchDisambiguation.h',
-            'frame/UseCounter.cpp',
             'page/WindowFeatures.cpp',
             'page/WindowFocusAllowedIndicator.cpp',
-            'workers/WorkerNavigator.cpp',
-            'workers/WorkerNavigator.h',
-            'frame/animation/AnimationBase.cpp',
-            'frame/animation/AnimationBase.h',
-            'frame/animation/AnimationController.cpp',
-            'frame/animation/AnimationControllerPrivate.h',
-            'frame/animation/CompositeAnimation.cpp',
-            'frame/animation/CompositeAnimation.h',
-            'frame/animation/CSSPropertyAnimation.cpp',
-            'frame/animation/CSSPropertyAnimation.h',
-            'frame/animation/ImplicitAnimation.cpp',
-            'frame/animation/ImplicitAnimation.h',
-            'frame/animation/KeyframeAnimation.cpp',
-            'frame/animation/KeyframeAnimation.h',
             'page/scrolling/ScrollingConstraints.cpp',
             'page/scrolling/ScrollingConstraints.h',
             'page/scrolling/ScrollingCoordinator.cpp',
@@ -1358,14 +1354,12 @@
             'rendering/AbstractInlineTextBox.h',
             'rendering/AutoTableLayout.cpp',
             'rendering/AutoTableLayout.h',
-            'rendering/BidiRun.cpp',
             'rendering/BidiRun.h',
             'rendering/ClipRect.cpp',
             'rendering/ClipRect.h',
             'rendering/CompositedLayerMapping.cpp',
             'rendering/CompositedLayerMapping.h',
             'rendering/CompositedLayerMappingPtr.h',
-            'rendering/CompositingReasons.h',
             'rendering/CounterNode.cpp',
             'rendering/CounterNode.h',
             'rendering/EllipsisBox.cpp',
@@ -1382,31 +1376,23 @@
             'rendering/FlowThreadController.h',
             'rendering/GraphicsContextAnnotator.cpp',
             'rendering/GraphicsContextAnnotator.h',
-            'rendering/TextAutosizer.cpp',
-            'rendering/TextAutosizer.h',
-            'rendering/HitTestingTransformState.cpp',
-            'rendering/HitTestingTransformState.h',
             'rendering/HitTestLocation.cpp',
             'rendering/HitTestLocation.h',
             'rendering/HitTestResult.cpp',
+            'rendering/HitTestingTransformState.cpp',
+            'rendering/HitTestingTransformState.h',
+            'rendering/ImageQualityController.cpp',
+            'rendering/ImageQualityController.h',
             'rendering/InlineBox.cpp',
             'rendering/InlineFlowBox.cpp',
             'rendering/InlineIterator.h',
             'rendering/InlineTextBox.cpp',
-            'rendering/ImageQualityController.h',
-            'rendering/ImageQualityController.cpp',
+            'rendering/LayoutRectRecorder.cpp',
+            'rendering/LayoutRepainter.cpp',
             'rendering/LayoutState.cpp',
             'rendering/OrderIterator.cpp',
             'rendering/OrderIterator.h',
-            'rendering/LayoutIndicator.cpp',
-            'rendering/LayoutIndicator.h',
-            'rendering/LayoutRectRecorder.cpp',
-            'rendering/LayoutRepainter.cpp',
-            'rendering/LineWidth.cpp',
-            'rendering/LineWidth.h',
             'rendering/PartialLayoutState.h',
-            'rendering/Pagination.cpp',
-            'rendering/Pagination.h',
             'rendering/PointerEventsHitRules.cpp',
             'rendering/PointerEventsHitRules.h',
             'rendering/RenderApplet.cpp',
@@ -1442,10 +1428,10 @@
             'rendering/RenderFrameSet.h',
             'rendering/RenderFullScreen.cpp',
             'rendering/RenderFullScreen.h',
-            'rendering/RenderGrid.cpp',
-            'rendering/RenderGrid.h',
             'rendering/RenderGeometryMap.cpp',
             'rendering/RenderGeometryMap.h',
+            'rendering/RenderGrid.cpp',
+            'rendering/RenderGrid.h',
             'rendering/RenderHTMLCanvas.cpp',
             'rendering/RenderHTMLCanvas.h',
             'rendering/RenderIFrame.cpp',
@@ -1458,17 +1444,18 @@
             'rendering/RenderInputSpeech.cpp',
             'rendering/RenderInputSpeech.h',
             'rendering/RenderLayer.cpp',
+            'rendering/RenderLayerBlendInfo.cpp',
             'rendering/RenderLayerClipper.cpp',
             'rendering/RenderLayerCompositor.cpp',
             'rendering/RenderLayerCompositor.h',
             'rendering/RenderLayerFilterInfo.cpp',
             'rendering/RenderLayerFilterInfo.h',
+            'rendering/RenderLayerModelObject.cpp',
+            'rendering/RenderLayerReflectionInfo.cpp',
+            'rendering/RenderLayerRepainter.cpp',
             'rendering/RenderLayerScrollableArea.cpp',
             'rendering/RenderLayerStackingNode.cpp',
             'rendering/RenderLayerStackingNodeIterator.cpp',
-            'rendering/RenderLayerReflectionInfo.cpp',
-            'rendering/RenderLayerRepainter.cpp',
-            'rendering/RenderLayerModelObject.cpp',
             'rendering/RenderLineBoxList.cpp',
             'rendering/RenderListBox.cpp',
             'rendering/RenderListBox.h',
@@ -1493,10 +1480,6 @@
             'rendering/RenderMultiColumnFlowThread.h',
             'rendering/RenderMultiColumnSet.cpp',
             'rendering/RenderMultiColumnSet.h',
-            'rendering/RenderNamedFlowFragment.cpp',
-            'rendering/RenderNamedFlowFragment.h',
-            'rendering/RenderNamedFlowThread.cpp',
-            'rendering/RenderNamedFlowThread.h',
             'rendering/RenderObject.cpp',
             'rendering/RenderObjectChildList.cpp',
             'rendering/RenderPart.cpp',
@@ -1565,8 +1548,6 @@
             'rendering/RenderThemeChromiumMac.mm',
             'rendering/RenderThemeChromiumSkia.cpp',
             'rendering/RenderThemeChromiumSkia.h',
-            'rendering/RenderThemeChromiumWin.cpp',
-            'rendering/RenderThemeChromiumWin.h',
             'rendering/RenderTreeAsText.cpp',
             'rendering/RenderVTTCue.cpp',
             'rendering/RenderVTTCue.h',
@@ -1577,16 +1558,23 @@
             'rendering/RenderWordBreak.cpp',
             'rendering/RenderWordBreak.h',
             'rendering/RootInlineBox.cpp',
-            'rendering/ScrollBehavior.cpp',
+            'rendering/ScrollAlignment.cpp',
             'rendering/SubtreeLayoutScope.cpp',
             'rendering/SubtreeLayoutScope.h',
             'rendering/TableLayout.h',
+            'rendering/TextAutosizer.cpp',
+            'rendering/TextAutosizer.h',
             'rendering/TrailingFloatsRootInlineBox.h',
             'rendering/VerticalPositionCache.h',
             'rendering/break_lines.cpp',
             'rendering/break_lines.h',
-            'rendering/animation/WebAnimationProvider.cpp',
-            'rendering/animation/WebAnimationProvider.h',
+            'rendering/line/BreakingContext.cpp',
+            'rendering/line/LineBreaker.cpp',
+            'rendering/line/LineBreaker.h',
+            'rendering/line/LineWidth.cpp',
+            'rendering/line/LineWidth.h',
+            'rendering/line/TrailingObjects.h',
+            'rendering/line/TrailingObjects.cpp',
             'rendering/shapes/BoxShape.cpp',
             'rendering/shapes/BoxShape.h',
             'rendering/shapes/PolygonShape.cpp',
@@ -1625,15 +1613,9 @@
             'rendering/style/ShadowList.h',
             'rendering/style/StyleBackgroundData.cpp',
             'rendering/style/StyleBoxData.cpp',
+            'rendering/style/StyleDeprecatedFlexibleBoxData.cpp',
             'rendering/style/StyleFetchedImage.cpp',
             'rendering/style/StyleFetchedImageSet.cpp',
-            'rendering/style/StyleFetchedShader.h',
-            'rendering/style/StyleFetchedShader.cpp',
-            'rendering/style/StyleCustomFilterProgramCache.cpp',
-            'rendering/style/StyleCustomFilterProgramCache.h',
-            'rendering/style/StyleCustomFilterProgram.cpp',
-            'rendering/style/StyleCustomFilterProgram.h',
-            'rendering/style/StyleDeprecatedFlexibleBoxData.cpp',
             'rendering/style/StyleFilterData.cpp',
             'rendering/style/StyleFlexibleBoxData.cpp',
             'rendering/style/StyleGeneratedImage.cpp',
@@ -1643,10 +1625,8 @@
             'rendering/style/StyleMarqueeData.cpp',
             'rendering/style/StyleMultiColData.cpp',
             'rendering/style/StylePendingImage.h',
-            'rendering/style/StylePendingShader.h',
             'rendering/style/StyleRareInheritedData.cpp',
             'rendering/style/StyleRareNonInheritedData.cpp',
-            'rendering/style/StyleShader.h',
             'rendering/style/StyleSurroundData.cpp',
             'rendering/style/StyleTransformData.cpp',
             'rendering/style/StyleVisualData.cpp',
@@ -1705,10 +1685,28 @@
             'speech/SpeechInputResultList.h',
             'storage/Storage.cpp',
             'storage/Storage.h',
+            'storage/StorageArea.cpp',
             'storage/StorageArea.h',
             'storage/StorageEvent.cpp',
             'storage/StorageEvent.h',
+            'storage/StorageNamespace.cpp',
             'storage/StorageNamespace.h',
+            'timing/MemoryInfo.cpp',
+            'timing/Performance.cpp',
+            'timing/Performance.h',
+            'timing/PerformanceEntry.cpp',
+            'timing/PerformanceEntry.h',
+            'timing/PerformanceMark.h',
+            'timing/PerformanceMeasure.h',
+            'timing/PerformanceNavigation.cpp',
+            'timing/PerformanceNavigation.h',
+            'timing/PerformanceResourceTiming.cpp',
+            'timing/PerformanceResourceTiming.h',
+            'timing/PerformanceTiming.cpp',
+            'timing/PerformanceTiming.h',
+            'timing/PerformanceUserTiming.cpp',
+            'timing/PerformanceUserTiming.h',
+            'timing/ResourceTimingInfo.h',
             'workers/AbstractWorker.cpp',
             'workers/AbstractWorker.h',
             'workers/DedicatedWorkerGlobalScope.cpp',
@@ -1729,15 +1727,17 @@
             'workers/WorkerConsole.h',
             'workers/WorkerEventQueue.cpp',
             'workers/WorkerEventQueue.h',
-            'workers/WorkerGlobalScopeProxy.h',
-            'workers/WorkerGlobalScopeProxyProvider.h',
-            'workers/WorkerGlobalScopeProxyProvider.cpp',
             'workers/WorkerGlobalScope.cpp',
             'workers/WorkerGlobalScope.h',
+            'workers/WorkerGlobalScopeProxy.h',
+            'workers/WorkerGlobalScopeProxyProvider.cpp',
+            'workers/WorkerGlobalScopeProxyProvider.h',
             'workers/WorkerLoaderProxy.h',
             'workers/WorkerLocation.h',
             'workers/WorkerMessagingProxy.cpp',
             'workers/WorkerMessagingProxy.h',
+            'workers/WorkerNavigator.cpp',
+            'workers/WorkerNavigator.h',
             'workers/WorkerObjectProxy.cpp',
             'workers/WorkerObjectProxy.h',
             'workers/WorkerReportingProxy.h',
@@ -1748,16 +1748,10 @@
             'workers/WorkerThread.cpp',
             'workers/WorkerThreadStartupData.cpp',
             'workers/WorkerThreadStartupData.h',
-            'xml/parser/MarkupTokenizerInlines.h',
-            'xml/parser/XMLDocumentParser.cpp',
-            'xml/parser/XMLDocumentParser.h',
-            'xml/parser/XMLDocumentParserScope.cpp',
-            'xml/parser/XMLDocumentParserScope.h',
-            'xml/parser/XMLParserInput.h',
-            'xml/DocumentXPathEvaluator.cpp',
-            'xml/DocumentXPathEvaluator.h',
             'xml/DOMParser.cpp',
             'xml/DOMParser.h',
+            'xml/DocumentXPathEvaluator.cpp',
+            'xml/DocumentXPathEvaluator.h',
             'xml/NativeXPathNSResolver.cpp',
             'xml/NativeXPathNSResolver.h',
             'xml/XMLErrors.cpp',
@@ -1813,6 +1807,12 @@
             'xml/XSLTProcessorLibxslt.cpp',
             'xml/XSLTUnicodeSort.cpp',
             'xml/XSLTUnicodeSort.h',
+            'xml/parser/MarkupTokenizerInlines.h',
+            'xml/parser/XMLDocumentParser.cpp',
+            'xml/parser/XMLDocumentParser.h',
+            'xml/parser/XMLDocumentParserScope.cpp',
+            'xml/parser/XMLDocumentParserScope.h',
+            'xml/parser/XMLParserInput.h',
         ],
         'webcore_dom_files': [
             'dom/ActiveDOMObject.cpp',
@@ -1827,13 +1827,12 @@
             'dom/ChildListMutationScope.h',
             'dom/ChildNodeList.cpp',
             'dom/ChildNodeList.h',
-            'dom/ClassNodeList.cpp',
-            'dom/ClassNodeList.h',
+            'dom/ClassCollection.cpp',
+            'dom/ClassCollection.h',
             'dom/ClientRect.cpp',
             'dom/ClientRect.h',
             'dom/ClientRectList.cpp',
             'dom/ClientRectList.h',
-            'dom/Clipboard.cpp',
             'dom/Comment.cpp',
             'dom/Comment.h',
             'dom/ContainerNode.cpp',
@@ -1848,13 +1847,10 @@
             'dom/CrossThreadTask.h',
             'dom/DatasetDOMStringMap.cpp',
             'dom/DatasetDOMStringMap.h',
-            'dom/DataTransferItem.cpp',
-            'dom/DataTransferItem.h',
-            'dom/DataTransferItemList.cpp',
-            'dom/DataTransferItemList.h',
             'dom/DecodedDataDocumentParser.cpp',
             'dom/DecodedDataDocumentParser.h',
             'dom/Document.cpp',
+            'dom/DocumentEncodingData.cpp',
             'dom/DocumentEncodingData.h',
             'dom/DocumentFragment.cpp',
             'dom/DocumentFullscreen.cpp',
@@ -1873,17 +1869,16 @@
             'dom/DocumentOrderedList.h',
             'dom/DocumentOrderedMap.cpp',
             'dom/DocumentParser.cpp',
-            'dom/DocumentSharedObjectPool.cpp',
             'dom/DocumentStyleSheetCollection.cpp',
             'dom/DocumentStyleSheetCollection.h',
+            'dom/DocumentStyleSheetCollector.cpp',
+            'dom/DocumentStyleSheetCollector.h',
             'dom/DocumentType.cpp',
             'dom/DOMError.cpp',
             'dom/DOMError.h',
             'dom/DOMException.cpp',
             'dom/DOMException.h',
             'dom/DOMImplementation.cpp',
-            'dom/DOMNamedFlowCollection.cpp',
-            'dom/DOMNamedFlowCollection.h',
             'dom/DOMSettableTokenList.cpp',
             'dom/DOMSettableTokenList.h',
             'dom/DOMStringList.cpp',
@@ -1902,10 +1897,13 @@
             'dom/Element.h',
             'dom/ElementData.cpp',
             'dom/ElementData.h',
+            'dom/ElementDataCache.cpp',
+            'dom/ElementDataCache.h',
             'dom/ElementRareData.cpp',
             'dom/ElementRareData.h',
             'dom/ElementTraversal.h',
-            'dom/Entity.h',
+            'dom/EmptyNodeList.cpp',
+            'dom/EmptyNodeList.h',
             'dom/ExecutionContextTask.cpp',
             'dom/ExecutionContextTask.h',
             'dom/MainThreadTaskRunner.cpp',
@@ -1936,10 +1934,6 @@
             'dom/MutationObserverRegistration.h',
             'dom/MutationRecord.cpp',
             'dom/MutationRecord.h',
-            'dom/NamedFlow.cpp',
-            'dom/NamedFlow.h',
-            'dom/NamedFlowCollection.cpp',
-            'dom/NamedFlowCollection.h',
             'dom/NamedNodeMap.cpp',
             'dom/NamedNodesCollection.cpp',
             'dom/NamedNodesCollection.h',
@@ -1954,11 +1948,10 @@
             'dom/NodeFilterCondition.h',
             'dom/NodeIterator.cpp',
             'dom/NodeIterator.h',
-            'dom/NodeList.cpp',
             'dom/NodeRareData.cpp',
             'dom/NodeRareData.h',
-            'dom/NodeRenderingContext.cpp',
-            'dom/NodeRenderingContext.h',
+            'dom/RenderTreeBuilder.cpp',
+            'dom/RenderTreeBuilder.h',
             'dom/NodeRenderingTraversal.cpp',
             'dom/NodeRenderingTraversal.h',
             'dom/NodeRenderStyle.h',
@@ -1997,18 +1990,16 @@
             'dom/SecurityContext.h',
             'dom/SelectorQuery.cpp',
             'dom/SelectorQuery.h',
+            'dom/XMLDocument.cpp',
+            'dom/XMLDocument.h',
             'dom/custom/CustomElement.cpp',
             'dom/custom/CustomElement.h',
-            'dom/custom/CustomElementBaseElementQueue.cpp',
-            'dom/custom/CustomElementBaseElementQueue.h',
             'dom/custom/CustomElementCallbackDispatcher.cpp',
             'dom/custom/CustomElementCallbackDispatcher.h',
             'dom/custom/CustomElementCallbackInvocation.cpp',
             'dom/custom/CustomElementCallbackInvocation.h',
             'dom/custom/CustomElementCallbackQueue.cpp',
             'dom/custom/CustomElementCallbackQueue.h',
-            'dom/custom/CustomElementCallbackScheduler.cpp',
-            'dom/custom/CustomElementCallbackScheduler.h',
             'dom/custom/CustomElementDefinition.cpp',
             'dom/custom/CustomElementDefinition.h',
             'dom/custom/CustomElementDescriptor.h',
@@ -2016,12 +2007,24 @@
             'dom/custom/CustomElementException.cpp',
             'dom/custom/CustomElementException.h',
             'dom/custom/CustomElementLifecycleCallbacks.h',
+            'dom/custom/CustomElementMicrotaskDispatcher.cpp',
+            'dom/custom/CustomElementMicrotaskDispatcher.h',
+            'dom/custom/CustomElementMicrotaskImportStep.cpp',
+            'dom/custom/CustomElementMicrotaskImportStep.h',
+            'dom/custom/CustomElementMicrotaskQueue.cpp',
+            'dom/custom/CustomElementMicrotaskQueue.h',
+            'dom/custom/CustomElementMicrotaskResolutionStep.cpp',
+            'dom/custom/CustomElementMicrotaskResolutionStep.h',
+            'dom/custom/CustomElementMicrotaskStep.h',
             'dom/custom/CustomElementObserver.cpp',
             'dom/custom/CustomElementObserver.h',
+            'dom/custom/CustomElementProcessingStep.h',
             'dom/custom/CustomElementRegistrationContext.cpp',
             'dom/custom/CustomElementRegistrationContext.h',
             'dom/custom/CustomElementRegistry.cpp',
             'dom/custom/CustomElementRegistry.h',
+            'dom/custom/CustomElementScheduler.cpp',
+            'dom/custom/CustomElementScheduler.h',
             'dom/custom/CustomElementUpgradeCandidateMap.cpp',
             'dom/custom/CustomElementUpgradeCandidateMap.h',
             'dom/shadow/ComposedTreeWalker.cpp',
@@ -2049,14 +2052,14 @@
             'dom/StyleElement.h',
             'dom/StyleEngine.cpp',
             'dom/StyleEngine.h',
+            'dom/StyleSheetCandidate.cpp',
+            'dom/StyleSheetCandidate.h',
             'dom/StyleSheetCollection.cpp',
             'dom/StyleSheetCollection.h',
             'dom/StyleSheetScopingNodeList.cpp',
             'dom/StyleSheetScopingNodeList.h',
-            'dom/StyleTreeScopeTracker.cpp',
-            'dom/StyleTreeScopeTracker.h',
-            'dom/TagNodeList.cpp',
-            'dom/TagNodeList.h',
+            'dom/TagCollection.cpp',
+            'dom/TagCollection.h',
             'dom/Text.cpp',
             'dom/TextLinkColors.cpp',
             'dom/TextLinkColors.h',
@@ -2072,6 +2075,8 @@
             'dom/TreeScope.h',
             'dom/TreeScopeAdopter.cpp',
             'dom/TreeScopeAdopter.h',
+            'dom/TreeScopeStyleSheetCollection.cpp',
+            'dom/TreeScopeStyleSheetCollection.h',
             'dom/TreeShared.h',
             'dom/TreeWalker.cpp',
             'dom/TreeWalker.h',
@@ -2100,8 +2105,6 @@
             'events/ErrorEvent.cpp',
             'events/ErrorEvent.h',
             'events/Event.cpp',
-            'events/EventContext.cpp',
-            'events/EventContext.h',
             'events/EventDispatcher.cpp',
             'events/EventDispatcher.h',
             'events/EventDispatchMediator.cpp',
@@ -2110,8 +2113,6 @@
             'events/EventPath.cpp',
             'events/EventPath.h',
             'events/EventQueue.h',
-            'events/EventRetargeter.cpp',
-            'events/EventRetargeter.h',
             'events/EventSender.h',
             'events/EventTarget.cpp',
             'events/FocusEvent.cpp',
@@ -2130,6 +2131,8 @@
             'events/MutationEvent.h',
             'events/NavigatorEvents.cpp',
             'events/NavigatorEvents.h',
+            'events/NodeEventContext.cpp',
+            'events/NodeEventContext.h',
             'events/OverflowEvent.cpp',
             'events/OverflowEvent.h',
             'events/PageTransitionEvent.cpp',
@@ -2148,8 +2151,12 @@
             'events/ThreadLocalEventNames.h',
             'events/TouchEvent.cpp',
             'events/TouchEvent.h',
+            'events/TouchEventContext.cpp',
+            'events/TouchEventContext.h',
             'events/TransitionEvent.cpp',
             'events/TransitionEvent.h',
+            'events/TreeScopeEventContext.cpp',
+            'events/TreeScopeEventContext.h',
             'events/UIEvent.cpp',
             'events/UIEventWithKeyState.cpp',
             'events/WebKitAnimationEvent.cpp',
@@ -2239,11 +2246,12 @@
             'html/HTMLImportChild.cpp',
             'html/HTMLImportChild.h',
             'html/HTMLImportChildClient.h',
-            'html/HTMLImportData.cpp',
-            'html/HTMLImportData.h',
-            'html/HTMLImportDataClient.h',
-            'html/HTMLImportResourceOwner.cpp',
-            'html/HTMLImportResourceOwner.h',
+            'html/HTMLImportLoader.cpp',
+            'html/HTMLImportLoader.h',
+            'html/HTMLImportLoaderClient.h',
+            'html/HTMLImportState.h',
+            'html/HTMLImportStateResolver.cpp',
+            'html/HTMLImportStateResolver.h',
             'html/HTMLInputElement.cpp',
             'html/HTMLKeygenElement.cpp',
             'html/HTMLKeygenElement.h',
@@ -2269,6 +2277,10 @@
             'html/HTMLModElement.h',
             'html/HTMLNameCollection.cpp',
             'html/HTMLNameCollection.h',
+            'html/HTMLNoEmbedElement.cpp',
+            'html/HTMLNoEmbedElement.h',
+            'html/HTMLNoScriptElement.cpp',
+            'html/HTMLNoScriptElement.h',
             'html/HTMLOListElement.cpp',
             'html/HTMLOListElement.h',
             'html/HTMLObjectElement.cpp',
@@ -2293,6 +2305,10 @@
             'html/HTMLProgressElement.h',
             'html/HTMLQuoteElement.cpp',
             'html/HTMLQuoteElement.h',
+            'html/HTMLRTElement.cpp',
+            'html/HTMLRTElement.h',
+            'html/HTMLRubyElement.cpp',
+            'html/HTMLRubyElement.h',
             'html/HTMLScriptElement.cpp',
             'html/HTMLScriptElement.h',
             'html/HTMLSelectElement.cpp',
@@ -2335,6 +2351,8 @@
             'html/HTMLVideoElement.h',
             'html/HTMLViewSourceDocument.cpp',
             'html/HTMLViewSourceDocument.h',
+            'html/HTMLWBRElement.cpp',
+            'html/HTMLWBRElement.h',
             'html/ImageData.cpp',
             'html/ImageData.h',
             'html/ImageDocument.cpp',
@@ -2484,8 +2502,6 @@
             'html/forms/ButtonInputType.h',
             'html/forms/CheckboxInputType.cpp',
             'html/forms/CheckboxInputType.h',
-            'html/forms/CheckedRadioButtons.cpp',
-            'html/forms/CheckedRadioButtons.h',
             'html/forms/ColorInputType.cpp',
             'html/forms/ColorInputType.h',
             'html/forms/DateInputType.cpp',
@@ -2514,6 +2530,8 @@
             'html/forms/NumberInputType.h',
             'html/forms/PasswordInputType.cpp',
             'html/forms/PasswordInputType.h',
+            'html/forms/RadioButtonGroupScope.cpp',
+            'html/forms/RadioButtonGroupScope.h',
             'html/forms/RadioInputType.cpp',
             'html/forms/RadioInputType.h',
             'html/forms/RangeInputType.cpp',
@@ -2564,8 +2582,6 @@
             'html/parser/HTMLEntityTable.h',
             'html/parser/HTMLFormattingElementList.cpp',
             'html/parser/HTMLFormattingElementList.h',
-            'html/parser/HTMLIdentifier.cpp',
-            'html/parser/HTMLIdentifier.h',
             'html/parser/HTMLInputStream.h',
             'html/parser/HTMLMetaCharsetParser.cpp',
             'html/parser/HTMLMetaCharsetParser.h',
@@ -2601,6 +2617,8 @@
             'html/parser/NestingLevelIncrementer.h',
             'html/parser/TextDocumentParser.cpp',
             'html/parser/TextDocumentParser.h',
+            'html/parser/TextResourceDecoder.cpp',
+            'html/parser/TextResourceDecoder.h',
             'html/parser/XSSAuditor.cpp',
             'html/parser/XSSAuditor.h',
             'html/parser/XSSAuditorDelegate.cpp',
@@ -2625,16 +2643,14 @@
             'html/shadow/HTMLContentElement.h',
             'html/shadow/HTMLShadowElement.cpp',
             'html/shadow/HTMLShadowElement.h',
-            'html/shadow/MediaControls.cpp',
-            'html/shadow/MediaControls.h',
             'html/shadow/MediaControlElementTypes.cpp',
             'html/shadow/MediaControlElementTypes.h',
             'html/shadow/MediaControlElements.cpp',
             'html/shadow/MediaControlElements.h',
-            'html/shadow/MediaControlsChromium.cpp',
-            'html/shadow/MediaControlsChromium.h',
-            'html/shadow/MediaControlsChromiumAndroid.cpp',
-            'html/shadow/MediaControlsChromiumAndroid.h',
+            'html/shadow/MediaControls.cpp',
+            'html/shadow/MediaControls.h',
+            'html/shadow/MediaControlsAndroid.cpp',
+            'html/shadow/MediaControlsAndroid.h',
             'html/shadow/MeterShadowElement.cpp',
             'html/shadow/MeterShadowElement.h',
             'html/shadow/PasswordGeneratorButtonElement.cpp',
@@ -2649,8 +2665,6 @@
             'html/shadow/SpinButtonElement.h',
             'html/shadow/TextControlInnerElements.cpp',
             'html/shadow/TextControlInnerElements.h',
-            'html/ime/Composition.cpp',
-            'html/ime/Composition.h',
             'html/ime/InputMethodContext.cpp',
             'html/ime/InputMethodContext.h',
             'html/track/InbandTextTrack.cpp',
@@ -2664,6 +2678,7 @@
             'html/track/TextTrackCueList.cpp',
             'html/track/TextTrackCueList.h',
             'html/track/TextTrackList.cpp',
+            'html/track/TrackBase.cpp',
             'html/track/TrackBase.h',
             'html/track/TrackEvent.cpp',
             'html/track/vtt/BufferedLineReader.cpp',
@@ -2678,49 +2693,12 @@
             'html/track/vtt/VTTRegion.h',
             'html/track/vtt/VTTRegionList.cpp',
             'html/track/vtt/VTTRegionList.h',
+            'html/track/vtt/VTTScanner.cpp',
+            'html/track/vtt/VTTScanner.h',
             'html/track/vtt/VTTToken.h',
             'html/track/vtt/VTTTokenizer.cpp',
             'html/track/vtt/VTTTokenizer.h',
         ],
-        'webcore_platform_files': [
-            'platform/DragImage.cpp',
-            'platform/Pasteboard.cpp',
-            'platform/Pasteboard.h',
-            'platform/animation/AnimationTranslationUtil.cpp',
-            'platform/animation/AnimationTranslationUtil.h',
-            'platform/animation/AnimationValue.h',
-            'platform/animation/CSSAnimationData.cpp',
-            'platform/animation/CSSAnimationDataList.cpp',
-            'platform/animation/KeyframeValueList.cpp',
-            'platform/animation/KeyframeValueList.h',
-            'platform/chromium/ChromiumDataObject.cpp',
-            'platform/chromium/ChromiumDataObject.h',
-            'platform/chromium/ChromiumDataObjectItem.cpp',
-            'platform/chromium/ChromiumDataObjectItem.h',
-            'platform/chromium/FramelessScrollView.cpp',
-            'platform/chromium/FramelessScrollView.h',
-            'platform/chromium/FramelessScrollViewClient.h',
-            'platform/chromium/KeyCodeConversion.h',
-            'platform/chromium/KeyCodeConversionAndroid.cpp',
-            'platform/chromium/KeyCodeConversionGtk.cpp',
-            'platform/chromium/KeyboardCodes.h',
-            'platform/mac/ThemeMac.h',
-            'platform/mac/ThemeMac.mm',
-            'platform/mediastream/MediaStreamCenter.cpp',
-            'platform/mediastream/MediaStreamCenter.h',
-            'platform/mediastream/MediaStreamDescriptor.cpp',
-            'platform/mediastream/MediaStreamDescriptor.h',
-            'platform/mediastream/RTCDataChannelHandler.cpp',
-            'platform/mediastream/RTCDataChannelHandler.h',
-            'platform/mediastream/RTCDataChannelHandlerClient.h',
-            'platform/mediastream/RTCPeerConnectionHandler.cpp',
-            'platform/mediastream/RTCPeerConnectionHandler.h',
-            'platform/mediastream/RTCPeerConnectionHandlerClient.h',
-            'platform/mediastream/RTCStatsRequest.h',
-            'platform/mock/GeolocationClientMock.cpp',
-            'platform/mock/PlatformSpeechSynthesizerMock.cpp',
-            'platform/mock/PlatformSpeechSynthesizerMock.h',
-        ],
         'webcore_svg_files': [
             'rendering/style/SVGRenderStyle.cpp',
             'rendering/style/SVGRenderStyleDefs.cpp',
@@ -2846,24 +2824,16 @@
             'svg/SVGAltGlyphItemElement.cpp',
             'svg/SVGAltGlyphItemElement.h',
             'svg/SVGAngle.cpp',
-            'svg/SVGAnimateColorElement.cpp',
-            'svg/SVGAnimateColorElement.h',
             'svg/SVGAnimatedAngle.cpp',
-            'svg/SVGAnimatedBoolean.cpp',
             'svg/SVGAnimatedColor.cpp',
             'svg/SVGAnimatedEnumeration.cpp',
             'svg/SVGAnimatedInteger.cpp',
             'svg/SVGAnimatedIntegerOptionalInteger.cpp',
             'svg/SVGAnimatedLength.cpp',
-            'svg/SVGAnimatedLengthList.cpp',
+            'svg/SVGAnimatedNewPropertyAnimator.cpp',
             'svg/SVGAnimatedNumber.cpp',
-            'svg/SVGAnimatedNumberList.cpp',
             'svg/SVGAnimatedNumberOptionalNumber.cpp',
             'svg/SVGAnimatedPath.cpp',
-            'svg/SVGAnimatedPointList.cpp',
-            'svg/SVGAnimatedPreserveAspectRatio.cpp',
-            'svg/SVGAnimatedRect.cpp',
-            'svg/SVGAnimatedString.cpp',
             'svg/SVGAnimatedTransformList.cpp',
             'svg/SVGAnimatedType.cpp',
             'svg/SVGAnimatedTypeAnimator.cpp',
@@ -2876,6 +2846,8 @@
             'svg/SVGAnimateTransformElement.h',
             'svg/SVGAnimationElement.cpp',
             'svg/SVGAnimationElement.h',
+            'svg/SVGBoolean.cpp',
+            'svg/SVGBoolean.h',
             'svg/SVGCircleElement.cpp',
             'svg/SVGCircleElement.h',
             'svg/SVGClipPathElement.cpp',
@@ -2889,6 +2861,8 @@
             'svg/SVGDefsElement.h',
             'svg/SVGDescElement.cpp',
             'svg/SVGDescElement.h',
+            'svg/SVGDiscardElement.cpp',
+            'svg/SVGDiscardElement.h',
             'svg/SVGDocument.cpp',
             'svg/SVGDocument.h',
             'svg/SVGDocumentExtensions.cpp',
@@ -2900,8 +2874,6 @@
             'svg/SVGElementRareData.h',
             'svg/SVGEllipseElement.cpp',
             'svg/SVGEllipseElement.h',
-            'svg/SVGExternalResourcesRequired.cpp',
-            'svg/SVGExternalResourcesRequired.h',
             'svg/SVGFEBlendElement.cpp',
             'svg/SVGFEBlendElement.h',
             'svg/SVGFEColorMatrixElement.cpp',
@@ -2995,11 +2967,14 @@
             'svg/SVGImageElement.h',
             'svg/SVGImageLoader.cpp',
             'svg/SVGImageLoader.h',
-            'svg/SVGLangSpace.cpp',
-            'svg/SVGLangSpace.h',
+            'svg/SVGInteger.cpp',
+            'svg/SVGInteger.h',
+            'svg/SVGIntegerOptionalInteger.cpp',
+            'svg/SVGIntegerOptionalInteger.h',
             'svg/SVGLength.cpp',
             'svg/SVGLengthContext.cpp',
             'svg/SVGLengthList.cpp',
+            'svg/SVGLengthTearOff.cpp',
             'svg/SVGLineElement.cpp',
             'svg/SVGLineElement.h',
             'svg/SVGLinearGradientElement.cpp',
@@ -3015,6 +2990,11 @@
             'svg/SVGMissingGlyphElement.cpp',
             'svg/SVGMissingGlyphElement.h',
             'svg/SVGNumber.h',
+            'svg/SVGNumber.cpp',
+            'svg/SVGNumberOptionalNumber.cpp',
+            'svg/SVGNumberOptionalNumber.h',
+            'svg/SVGNumberTearOff.cpp',
+            'svg/SVGNumberTearOff.h',
             'svg/SVGNumberList.cpp',
             'svg/SVGNumberList.h',
             'svg/SVGPaint.cpp',
@@ -3079,7 +3059,10 @@
             'svg/SVGPathUtilities.h',
             'svg/SVGPatternElement.cpp',
             'svg/SVGPatternElement.h',
+            'svg/SVGPoint.cpp',
             'svg/SVGPoint.h',
+            'svg/SVGPointTearOff.cpp',
+            'svg/SVGPointTearOff.h',
             'svg/SVGPointList.cpp',
             'svg/SVGPointList.h',
             'svg/SVGPolyElement.cpp',
@@ -3089,11 +3072,15 @@
             'svg/SVGPolylineElement.cpp',
             'svg/SVGPolylineElement.h',
             'svg/SVGPreserveAspectRatio.cpp',
+            'svg/SVGPreserveAspectRatioTearOff.cpp',
             'svg/SVGRadialGradientElement.cpp',
             'svg/SVGRadialGradientElement.h',
+            'svg/SVGRect.cpp',
             'svg/SVGRect.h',
             'svg/SVGRectElement.cpp',
             'svg/SVGRectElement.h',
+            'svg/SVGRectTearOff.cpp',
+            'svg/SVGRectTearOff.h',
             'svg/SVGRenderingIntent.h',
             'svg/SVGSVGElement.cpp',
             'svg/SVGSVGElement.h',
@@ -3101,10 +3088,16 @@
             'svg/SVGScriptElement.h',
             'svg/SVGSetElement.cpp',
             'svg/SVGSetElement.h',
+            'svg/SVGStaticStringList.cpp',
+            'svg/SVGStaticStringList.h',
             'svg/SVGStopElement.cpp',
             'svg/SVGStopElement.h',
+            'svg/SVGString.cpp',
+            'svg/SVGString.h',
             'svg/SVGStringList.cpp',
             'svg/SVGStringList.h',
+            'svg/SVGStringListTearOff.cpp',
+            'svg/SVGStringListTearOff.h',
             'svg/SVGStyleElement.cpp',
             'svg/SVGStyleElement.h',
             'svg/SVGSwitchElement.cpp',
@@ -3152,6 +3145,7 @@
             'svg/animation/SVGSMILElement.cpp',
             'svg/graphics/SVGImageCache.cpp',
             'svg/graphics/SVGImageCache.h',
+            'svg/graphics/SVGImageChromeClient.cpp',
             'svg/graphics/SVGImageChromeClient.h',
             'svg/graphics/SVGImage.cpp',
             'svg/graphics/SVGImage.h',
@@ -3163,13 +3157,15 @@
             'svg/graphics/filters/SVGFilter.h',
             'svg/graphics/filters/SVGFilterBuilder.cpp',
             'svg/graphics/filters/SVGFilterBuilder.h',
+            'svg/properties/NewSVGAnimatedProperty.cpp',
+            'svg/properties/NewSVGPropertyTearOff.cpp',
             'svg/properties/SVGAnimatedProperty.cpp',
             'svg/properties/SVGAnimatedProperty.h',
             'svg/properties/SVGAttributeToPropertyMap.cpp',
             'svg/properties/SVGAnimatedPathSegListPropertyTearOff.h',
             'svg/properties/SVGPathSegListPropertyTearOff.cpp',
         ],
-        'webcore_testing_support_idl_files': [
+        'webcore_testing_idl_files': [
           'testing/GCObservation.idl',
           'testing/Internals.idl',
           'testing/InternalProfilers.idl',
@@ -3179,11 +3175,11 @@
           'testing/MallocStatistics.idl',
           'testing/TypeConversions.idl',
         ],
-        'generated_webcore_testing_support_idl_files': [
+        'generated_webcore_testing_idl_files': [
           '<(SHARED_INTERMEDIATE_DIR)/blink/InternalSettingsGenerated.idl',
           '<(SHARED_INTERMEDIATE_DIR)/blink/InternalRuntimeFlags.idl',
         ],
-        'webcore_test_support_files': [
+        'webcore_testing_files': [
             'testing/v8/WebCoreTestSupport.cpp',
             'testing/v8/WebCoreTestSupport.h',
             'testing/DummyPageHolder.cpp',
@@ -3208,18 +3204,6 @@
             '<(SHARED_INTERMEDIATE_DIR)/blink/InternalSettingsGenerated.cpp',
             '<(SHARED_INTERMEDIATE_DIR)/blink/InternalSettingsGenerated.h',
         ],
-        'webcore_platform_support_files': [
-            'platform/chromium/support/WebArrayBuffer.cpp',
-            'platform/chromium/support/WebCrypto.cpp',
-            'platform/chromium/support/WebCursorInfo.cpp',
-            'platform/chromium/support/WebMediaStream.cpp',
-            'platform/chromium/support/WebMediaStreamTrack.cpp',
-            'platform/chromium/support/WebRTCSessionDescription.cpp',
-            'platform/chromium/support/WebRTCSessionDescriptionRequest.cpp',
-            'platform/chromium/support/WebRTCStatsRequest.cpp',
-            'platform/chromium/support/WebScrollbarThemeGeometryNative.cpp',
-            'platform/chromium/support/WebScrollbarThemeGeometryNative.h',
-        ],
         'core_unittest_files': [
             'animation/AnimatableColorTest.cpp',
             'animation/AnimatableDoubleTest.cpp',
@@ -3231,36 +3215,48 @@
             'animation/AnimatableValueTestHelper.h',
             'animation/AnimatableValueTestHelperTest.cpp',
             'animation/AnimationClockTest.cpp',
+            'animation/AnimationHelpersTest.cpp',
+            'animation/AnimationTest.cpp',
+            'animation/AnimationTranslationUtilTest.cpp',
             'animation/CompositorAnimationsTest.cpp',
             'animation/CompositorAnimationsTestHelper.h',
             'animation/CompositorAnimationsTimingFunctionReverserTest.cpp',
             'animation/DocumentTimelineTest.cpp',
-            'animation/KeyframeAnimationEffectTest.cpp',
+            'animation/KeyframeEffectModelTest.cpp',
             'animation/PlayerTest.cpp',
             'animation/TimedItemCalculationsTest.cpp',
             'animation/TimedItemTest.cpp',
-            'css/CSSParserValuesTest.cpp',
             'css/CSSCalculationValueTest.cpp',
+            'css/CSSTestHelper.cpp',
+            'css/CSSTestHelper.h',
             'css/CSSValueTestHelper.h',
+            'css/CSSParserValuesTest.cpp',
+            'css/CSSSelectorTest.cpp',
+            'css/CSSValueTestHelper.h',
+            'css/DragUpdateTest.cpp',
+            'css/HoverUpdateTest.cpp',
+            'css/RuleSetTest.cpp',
+            'dom/DOMImplementationTest.cpp',
             'dom/DocumentMarkerControllerTest.cpp',
-            'editing/TextIteratorTest.cpp',
+            'dom/DocumentTest.cpp',
             'dom/MainThreadTaskRunnerTest.cpp',
+            'editing/TextIteratorTest.cpp',
+            'fetch/CachingCorrectnessTest.cpp',
             'fetch/ImageResourceTest.cpp',
             'fetch/MemoryCacheTest.cpp',
             'fetch/RawResourceTest.cpp',
             'fetch/ResourceFetcherTest.cpp',
+            'frame/ImageBitmapTest.cpp',
             'html/HTMLDimensionTest.cpp',
             'html/LinkRelAttributeTest.cpp',
             'html/TimeRangesTest.cpp',
+            'html/parser/HTMLParserThreadTest.cpp',
             'html/track/vtt/BufferedLineReaderTest.cpp',
-            'frame/ImageBitmapTest.cpp',
-            'platform/animation/AnimationTranslationUtilTest.cpp',
-            'platform/animation/TimingFunctionTestHelper.h',
-            'platform/animation/TimingFunctionTestHelper.cpp',
-            'platform/animation/TimingFunctionTestHelperTest.cpp',
+            'html/track/vtt/VTTScannerTest.cpp',
             'rendering/RenderOverflowTest.cpp',
-            'testing/UnitTestHelpers.h',
+            'rendering/shapes/BoxShapeTest.cpp',
             'testing/UnitTestHelpers.cpp',
+            'testing/UnitTestHelpers.h',
         ],
     }
 }
diff --git a/Source/core/core_derived_sources.gyp b/Source/core/core_generated.gyp
similarity index 93%
rename from Source/core/core_derived_sources.gyp
rename to Source/core/core_generated.gyp
index 1ff6624..90c8eea 100644
--- a/Source/core/core_derived_sources.gyp
+++ b/Source/core/core_generated.gyp
@@ -38,7 +38,7 @@
 
   'targets': [
     {
-      'target_name': 'generate_test_support_idls',
+      'target_name': 'generated_testing_idls',
       'type': 'none',
       'actions': [
         {
@@ -50,7 +50,7 @@
             '../build/scripts/templates/InternalSettingsGenerated.cpp.tmpl',
             '../build/scripts/templates/InternalSettingsGenerated.h.tmpl',
             '../build/scripts/templates/SettingsMacros.h.tmpl',
-            'page/Settings.in',
+            'frame/Settings.in',
           ],
           'outputs': [
             '<(SHARED_INTERMEDIATE_DIR)/blink/SettingsMacros.h',
@@ -61,7 +61,7 @@
           'action': [
             'python',
             '../build/scripts/make_settings.py',
-            'page/Settings.in',
+            'frame/Settings.in',
             '--output_dir',
             '<(SHARED_INTERMEDIATE_DIR)/blink',
           ],
@@ -90,11 +90,11 @@
       ]
     },
     {
-      'target_name': 'make_core_derived_sources',
+      'target_name': 'make_core_generated',
       'type': 'none',
       'hard_dependency': 1,
       'dependencies': [
-        'generate_test_support_idls',
+        'generated_testing_idls',
         '../config.gyp:config',
       ],
       'sources': [
@@ -104,24 +104,6 @@
       ],
       'actions': [
         {
-          'action_name': 'generateV8ArrayBufferViewCustomScript',
-          'inputs': [
-            '<(bindings_dir)/v8/custom/V8ArrayBufferViewCustomScript.js',
-          ],
-          'outputs': [
-            '<(SHARED_INTERMEDIATE_DIR)/blink/V8ArrayBufferViewCustomScript.h',
-          ],
-          'action': [
-            'python',
-            '../build/scripts/xxd.py',
-            'V8ArrayBufferViewCustomScript_js',
-            '<@(_inputs)',
-            '<@(_outputs)'
-          ],
-          'message': 'Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js',
-          'msvs_cygwin_shell': 0,
-        },
-        {
           'action_name': 'generateXMLViewerCSS',
           'inputs': [
             'xml/XMLViewer.css',
@@ -136,7 +118,6 @@
             '<@(_inputs)',
             '<@(_outputs)'
           ],
-          'msvs_cygwin_shell': 0,
         },
         {
           'action_name': 'generateXMLViewerJS',
@@ -153,7 +134,6 @@
             '<@(_inputs)',
             '<@(_outputs)'
           ],
-          'msvs_cygwin_shell': 0,
         },
         {
           'action_name': 'HTMLEntityTable',
@@ -195,9 +175,9 @@
             '<@(in_files)',
             '--output_dir',
             '<(SHARED_INTERMEDIATE_DIR)/blink',
+            '--gperf', '<(gperf_exe)',
             '--defines', '<(feature_defines)',
           ],
-          'msvs_cygwin_shell': 1,
         },
         {
           'action_name': 'StylePropertyShorthand',
@@ -261,13 +241,14 @@
             '<(SHARED_INTERMEDIATE_DIR)/blink/CSSValueKeywords.h',
           ],
           'action': [
+             'python',
              '../build/scripts/make_css_value_keywords.py',
              '<@(in_files)',
              '--output_dir',
              '<(SHARED_INTERMEDIATE_DIR)/blink',
+            '--gperf', '<(gperf_exe)',
             '--defines', '<(feature_defines)',
           ],
-          'msvs_cygwin_shell': 1,
         },
         {
           'action_name': 'HTMLElementFactory',
@@ -455,8 +436,9 @@
             '<@(scripts)',
             '--',
             '--defines', '<(feature_defines)',
+            '<@(preprocessor)',
+            '--perl', '<(perl_exe)',
           ],
-          'msvs_cygwin_shell': 1,
         },
         {
           'action_name': 'FetchInitiatorTypeNames',
@@ -588,16 +570,16 @@
           'inputs': [
             '<@(scripts_for_in_files)',
             '../build/scripts/make_token_matcher.py',
-            '../core/css/CSSParser-in.cpp',
+            '../core/css/parser/BisonCSSParser-in.cpp',
           ],
           'outputs': [
-            '<(SHARED_INTERMEDIATE_DIR)/blink/CSSParser.cpp',
+            '<(SHARED_INTERMEDIATE_DIR)/blink/BisonCSSParser.cpp',
           ],
           'action': [
             'python',
             '../build/scripts/make_token_matcher.py',
-            '../core/css/CSSParser-in.cpp',
-            '<(SHARED_INTERMEDIATE_DIR)/blink/CSSParser.cpp',
+            '../core/css/parser/BisonCSSParser-in.cpp',
+            '<(SHARED_INTERMEDIATE_DIR)/blink/BisonCSSParser.cpp',
           ],
         },
         {
@@ -654,7 +636,6 @@
             '<(SHARED_INTERMEDIATE_DIR)/blink',
             '<(bison_exe)',
           ],
-          'msvs_cygwin_shell': 1,
         },
       ],
     },
diff --git a/Source/core/css/BasicShapeFunctions.cpp b/Source/core/css/BasicShapeFunctions.cpp
index a49ea14..5bd3a01 100644
--- a/Source/core/css/BasicShapeFunctions.cpp
+++ b/Source/core/css/BasicShapeFunctions.cpp
@@ -33,12 +33,51 @@
 #include "core/css/CSSBasicShapes.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/CSSValuePool.h"
+#include "core/css/Pair.h"
 #include "core/css/resolver/StyleResolverState.h"
 #include "core/rendering/style/BasicShapes.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
 
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> valueForCenterCoordinate(CSSValuePool& pool, const RenderStyle& style, const BasicShapeCenterCoordinate& center)
+{
+    CSSValueID keyword = CSSValueInvalid;
+    switch (center.keyword()) {
+    case BasicShapeCenterCoordinate::None:
+        return pool.createValue(center.length(), style);
+    case BasicShapeCenterCoordinate::Top:
+        keyword = CSSValueTop;
+        break;
+    case BasicShapeCenterCoordinate::Right:
+        keyword = CSSValueRight;
+        break;
+    case BasicShapeCenterCoordinate::Bottom:
+        keyword = CSSValueBottom;
+        break;
+    case BasicShapeCenterCoordinate::Left:
+        keyword = CSSValueLeft;
+        break;
+    }
+
+    return pool.createValue(Pair::create(pool.createIdentifierValue(keyword), pool.createValue(center.length(), style), Pair::DropIdenticalValues));
+}
+
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> basicShapeRadiusToCSSValue(CSSValuePool& pool, const RenderStyle& style, const BasicShapeRadius& radius)
+{
+    switch (radius.type()) {
+    case BasicShapeRadius::Value:
+        return pool.createValue(radius.value(), style);
+    case BasicShapeRadius::ClosestSide:
+        return pool.createIdentifierValue(CSSValueClosestSide);
+    case BasicShapeRadius::FarthestSide:
+        return pool.createIdentifierValue(CSSValueFarthestSide);
+    }
+
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
 PassRefPtr<CSSValue> valueForBasicShape(const RenderStyle& style, const BasicShape* basicShape)
 {
     CSSValuePool& pool = cssValuePool();
@@ -59,9 +98,9 @@
         basicShapeValue = rectangleValue.release();
         break;
     }
-    case BasicShape::BasicShapeCircleType: {
-        const BasicShapeCircle* circle = static_cast<const BasicShapeCircle*>(basicShape);
-        RefPtr<CSSBasicShapeCircle> circleValue = CSSBasicShapeCircle::create();
+    case BasicShape::DeprecatedBasicShapeCircleType: {
+        const DeprecatedBasicShapeCircle* circle = static_cast<const DeprecatedBasicShapeCircle*>(basicShape);
+        RefPtr<CSSDeprecatedBasicShapeCircle> circleValue = CSSDeprecatedBasicShapeCircle::create();
 
         circleValue->setCenterX(pool.createValue(circle->centerX(), style));
         circleValue->setCenterY(pool.createValue(circle->centerY(), style));
@@ -70,9 +109,19 @@
         basicShapeValue = circleValue.release();
         break;
     }
-    case BasicShape::BasicShapeEllipseType: {
-        const BasicShapeEllipse* ellipse = static_cast<const BasicShapeEllipse*>(basicShape);
-        RefPtr<CSSBasicShapeEllipse> ellipseValue = CSSBasicShapeEllipse::create();
+    case BasicShape::BasicShapeCircleType: {
+        const BasicShapeCircle* circle = static_cast<const BasicShapeCircle*>(basicShape);
+        RefPtr<CSSBasicShapeCircle> circleValue = CSSBasicShapeCircle::create();
+
+        circleValue->setCenterX(valueForCenterCoordinate(pool, style, circle->centerX()));
+        circleValue->setCenterY(valueForCenterCoordinate(pool, style, circle->centerY()));
+        circleValue->setRadius(basicShapeRadiusToCSSValue(pool, style, circle->radius()));
+        basicShapeValue = circleValue.release();
+        break;
+    }
+    case BasicShape::DeprecatedBasicShapeEllipseType: {
+        const DeprecatedBasicShapeEllipse* ellipse = static_cast<const DeprecatedBasicShapeEllipse*>(basicShape);
+        RefPtr<CSSDeprecatedBasicShapeEllipse> ellipseValue = CSSDeprecatedBasicShapeEllipse::create();
 
         ellipseValue->setCenterX(pool.createValue(ellipse->centerX(), style));
         ellipseValue->setCenterY(pool.createValue(ellipse->centerY(), style));
@@ -82,6 +131,17 @@
         basicShapeValue = ellipseValue.release();
         break;
     }
+    case BasicShape::BasicShapeEllipseType: {
+        const BasicShapeEllipse* ellipse = static_cast<const BasicShapeEllipse*>(basicShape);
+        RefPtr<CSSBasicShapeEllipse> ellipseValue = CSSBasicShapeEllipse::create();
+
+        ellipseValue->setCenterX(valueForCenterCoordinate(pool, style, ellipse->centerX()));
+        ellipseValue->setCenterY(valueForCenterCoordinate(pool, style, ellipse->centerY()));
+        ellipseValue->setRadiusX(basicShapeRadiusToCSSValue(pool, style, ellipse->radiusX()));
+        ellipseValue->setRadiusY(basicShapeRadiusToCSSValue(pool, style, ellipse->radiusY()));
+        basicShapeValue = ellipseValue.release();
+        break;
+    }
     case BasicShape::BasicShapePolygonType: {
         const BasicShapePolygon* polygon = static_cast<const BasicShapePolygon*>(basicShape);
         RefPtr<CSSBasicShapePolygon> polygonValue = CSSBasicShapePolygon::create();
@@ -108,17 +168,96 @@
         basicShapeValue = rectangleValue.release();
         break;
     }
+    case BasicShape::BasicShapeInsetType: {
+        const BasicShapeInset* inset = static_cast<const BasicShapeInset*>(basicShape);
+        RefPtr<CSSBasicShapeInset> insetValue = CSSBasicShapeInset::create();
+
+        insetValue->setTop(CSSPrimitiveValue::create(inset->top()));
+        insetValue->setRight(CSSPrimitiveValue::create(inset->right()));
+        insetValue->setBottom(CSSPrimitiveValue::create(inset->bottom()));
+        insetValue->setLeft(CSSPrimitiveValue::create(inset->left()));
+
+        insetValue->setTopLeftRadius(CSSPrimitiveValue::create(inset->topLeftRadius()));
+        insetValue->setTopRightRadius(CSSPrimitiveValue::create(inset->topRightRadius()));
+        insetValue->setBottomRightRadius(CSSPrimitiveValue::create(inset->bottomRightRadius()));
+        insetValue->setBottomLeftRadius(CSSPrimitiveValue::create(inset->bottomLeftRadius()));
+
+        basicShapeValue = insetValue.release();
+        break;
+    }
     default:
         break;
     }
+
+    if (basicShape->layoutBox() != BoxMissing)
+        basicShapeValue->setLayoutBox(pool.createValue(basicShape->layoutBox()));
+
     return pool.createValue(basicShapeValue.release());
 }
 
 static Length convertToLength(const StyleResolverState& state, CSSPrimitiveValue* value)
 {
+    if (!value)
+        return Length(0, Fixed);
     return value->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
 }
 
+static LengthSize convertToLengthSize(const StyleResolverState& state, CSSPrimitiveValue* value)
+{
+    if (!value)
+        return LengthSize(Length(0, Fixed), Length(0, Fixed));
+
+    Pair* pair = value->getPairValue();
+    return LengthSize(convertToLength(state, pair->first()), convertToLength(state, pair->second()));
+}
+
+static BasicShapeCenterCoordinate convertToCenterCoordinate(const StyleResolverState& state, CSSPrimitiveValue* value)
+{
+    if (Pair* pair = value->getPairValue()) {
+        BasicShapeCenterCoordinate::Keyword keyword = BasicShapeCenterCoordinate::None;
+        switch (pair->first()->getValueID()) {
+        case CSSValueTop:
+            keyword = BasicShapeCenterCoordinate::Top;
+            break;
+        case CSSValueRight:
+            keyword = BasicShapeCenterCoordinate::Right;
+            break;
+        case CSSValueBottom:
+            keyword = BasicShapeCenterCoordinate::Bottom;
+            break;
+        case CSSValueLeft:
+            keyword = BasicShapeCenterCoordinate::Left;
+            break;
+        default:
+            ASSERT_NOT_REACHED();
+            break;
+        }
+        return BasicShapeCenterCoordinate(keyword, convertToLength(state, pair->second()));
+    }
+
+    return BasicShapeCenterCoordinate(convertToLength(state, value));
+}
+
+static BasicShapeRadius cssValueToBasicShapeRadius(const StyleResolverState& state, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> radius)
+{
+    if (!radius)
+        return BasicShapeRadius(BasicShapeRadius::ClosestSide);
+
+    if (radius->isValueID()) {
+        switch (radius->getValueID()) {
+        case CSSValueClosestSide:
+            return BasicShapeRadius(BasicShapeRadius::ClosestSide);
+        case CSSValueFarthestSide:
+            return BasicShapeRadius(BasicShapeRadius::FarthestSide);
+        default:
+            ASSERT_NOT_REACHED();
+            break;
+        }
+    }
+
+    return BasicShapeRadius(convertToLength(state, radius.get()));
+}
+
 PassRefPtr<BasicShape> basicShapeForValue(const StyleResolverState& state, const CSSBasicShape* basicShapeValue)
 {
     RefPtr<BasicShape> basicShape;
@@ -146,9 +285,9 @@
         basicShape = rect.release();
         break;
     }
-    case CSSBasicShape::CSSBasicShapeCircleType: {
-        const CSSBasicShapeCircle* circleValue = static_cast<const CSSBasicShapeCircle *>(basicShapeValue);
-        RefPtr<BasicShapeCircle> circle = BasicShapeCircle::create();
+    case CSSBasicShape::CSSDeprecatedBasicShapeCircleType: {
+        const CSSDeprecatedBasicShapeCircle* circleValue = static_cast<const CSSDeprecatedBasicShapeCircle *>(basicShapeValue);
+        RefPtr<DeprecatedBasicShapeCircle> circle = DeprecatedBasicShapeCircle::create();
 
         circle->setCenterX(convertToLength(state, circleValue->centerX()));
         circle->setCenterY(convertToLength(state, circleValue->centerY()));
@@ -157,9 +296,25 @@
         basicShape = circle.release();
         break;
     }
-    case CSSBasicShape::CSSBasicShapeEllipseType: {
-        const CSSBasicShapeEllipse* ellipseValue = static_cast<const CSSBasicShapeEllipse *>(basicShapeValue);
-        RefPtr<BasicShapeEllipse> ellipse = BasicShapeEllipse::create();
+    case CSSBasicShape::CSSBasicShapeCircleType: {
+        const CSSBasicShapeCircle* circleValue = static_cast<const CSSBasicShapeCircle *>(basicShapeValue);
+        RefPtr<BasicShapeCircle> circle = BasicShapeCircle::create();
+
+        if (circleValue->centerX() && circleValue->centerY()) {
+            circle->setCenterX(convertToCenterCoordinate(state, circleValue->centerX()));
+            circle->setCenterY(convertToCenterCoordinate(state, circleValue->centerY()));
+        } else {
+            circle->setCenterX(BasicShapeCenterCoordinate(Length(50, Percent)));
+            circle->setCenterY(BasicShapeCenterCoordinate(Length(50, Percent)));
+        }
+        circle->setRadius(cssValueToBasicShapeRadius(state, circleValue->radius()));
+
+        basicShape = circle.release();
+        break;
+    }
+    case CSSBasicShape::CSSDeprecatedBasicShapeEllipseType: {
+        const CSSDeprecatedBasicShapeEllipse* ellipseValue = static_cast<const CSSDeprecatedBasicShapeEllipse *>(basicShapeValue);
+        RefPtr<DeprecatedBasicShapeEllipse> ellipse = DeprecatedBasicShapeEllipse::create();
 
         ellipse->setCenterX(convertToLength(state, ellipseValue->centerX()));
         ellipse->setCenterY(convertToLength(state, ellipseValue->centerY()));
@@ -169,6 +324,23 @@
         basicShape = ellipse.release();
         break;
     }
+    case CSSBasicShape::CSSBasicShapeEllipseType: {
+        const CSSBasicShapeEllipse* ellipseValue = static_cast<const CSSBasicShapeEllipse *>(basicShapeValue);
+        RefPtr<BasicShapeEllipse> ellipse = BasicShapeEllipse::create();
+
+        if (ellipseValue->centerX() && ellipseValue->centerY()) {
+            ellipse->setCenterX(convertToCenterCoordinate(state, ellipseValue->centerX()));
+            ellipse->setCenterY(convertToCenterCoordinate(state, ellipseValue->centerY()));
+        } else {
+            ellipse->setCenterX(BasicShapeCenterCoordinate(Length(50, Percent)));
+            ellipse->setCenterY(BasicShapeCenterCoordinate(Length(50, Percent)));
+        }
+        ellipse->setRadiusX(cssValueToBasicShapeRadius(state, ellipseValue->radiusX()));
+        ellipse->setRadiusY(cssValueToBasicShapeRadius(state, ellipseValue->radiusY()));
+
+        basicShape = ellipse.release();
+        break;
+    }
     case CSSBasicShape::CSSBasicShapePolygonType: {
         const CSSBasicShapePolygon* polygonValue = static_cast<const CSSBasicShapePolygon *>(basicShapeValue);
         RefPtr<BasicShapePolygon> polygon = BasicShapePolygon::create();
@@ -203,9 +375,63 @@
         basicShape = rect.release();
         break;
     }
+    case CSSBasicShape::CSSBasicShapeInsetType: {
+        const CSSBasicShapeInset* rectValue = static_cast<const CSSBasicShapeInset* >(basicShapeValue);
+        RefPtr<BasicShapeInset> rect = BasicShapeInset::create();
+
+        rect->setTop(convertToLength(state, rectValue->top()));
+        rect->setRight(convertToLength(state, rectValue->right()));
+        rect->setBottom(convertToLength(state, rectValue->bottom()));
+        rect->setLeft(convertToLength(state, rectValue->left()));
+
+        rect->setTopLeftRadius(convertToLengthSize(state, rectValue->topLeftRadius()));
+        rect->setTopRightRadius(convertToLengthSize(state, rectValue->topRightRadius()));
+        rect->setBottomRightRadius(convertToLengthSize(state, rectValue->bottomRightRadius()));
+        rect->setBottomLeftRadius(convertToLengthSize(state, rectValue->bottomLeftRadius()));
+
+        basicShape = rect.release();
+        break;
+    }
     default:
         break;
     }
+
+    if (basicShapeValue->layoutBox())
+        basicShape->setLayoutBox(LayoutBox(*basicShapeValue->layoutBox()));
+
     return basicShape.release();
 }
+
+FloatPoint floatPointForCenterCoordinate(const BasicShapeCenterCoordinate& centerX, const BasicShapeCenterCoordinate& centerY, FloatSize boxSize)
+{
+    FloatPoint p;
+    float offset = floatValueForLength(centerX.length(), boxSize.width());
+    switch (centerX.keyword()) {
+    case BasicShapeCenterCoordinate::None:
+    case BasicShapeCenterCoordinate::Left:
+        p.setX(offset);
+        break;
+    case BasicShapeCenterCoordinate::Right:
+        p.setX(boxSize.width() - offset);
+        break;
+    default:
+        ASSERT_NOT_REACHED();
+    }
+
+    offset = floatValueForLength(centerY.length(), boxSize.height());
+    switch (centerY.keyword()) {
+    case BasicShapeCenterCoordinate::None:
+    case BasicShapeCenterCoordinate::Top:
+        p.setY(offset);
+        break;
+    case BasicShapeCenterCoordinate::Bottom:
+        p.setY(boxSize.height() - offset);
+        break;
+    default:
+        ASSERT_NOT_REACHED();
+    }
+
+    return p;
+}
+
 }
diff --git a/Source/core/css/BasicShapeFunctions.h b/Source/core/css/BasicShapeFunctions.h
index 7d07e31..f3565d9 100644
--- a/Source/core/css/BasicShapeFunctions.h
+++ b/Source/core/css/BasicShapeFunctions.h
@@ -30,6 +30,7 @@
 #ifndef BasicShapeFunctions_h
 #define BasicShapeFunctions_h
 
+#include "core/rendering/style/BasicShapes.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
@@ -37,11 +38,13 @@
 class BasicShape;
 class CSSBasicShape;
 class CSSValue;
+class FloatPoint;
 class StyleResolverState;
 class RenderStyle;
 
 PassRefPtr<CSSValue> valueForBasicShape(const RenderStyle&, const BasicShape*);
 PassRefPtr<BasicShape> basicShapeForValue(const StyleResolverState&, const CSSBasicShape*);
+FloatPoint floatPointForCenterCoordinate(const BasicShapeCenterCoordinate&, const BasicShapeCenterCoordinate&, FloatSize);
 
 }
 #endif
diff --git a/Source/core/css/CSSArrayFunctionValue.cpp b/Source/core/css/CSSArrayFunctionValue.cpp
index 3ead9d8..ed55fc8 100644
--- a/Source/core/css/CSSArrayFunctionValue.cpp
+++ b/Source/core/css/CSSArrayFunctionValue.cpp
@@ -47,9 +47,9 @@
     return "array(" + CSSValueList::customCSSText() + ')';
 }
 
-PassRefPtr<CSSArrayFunctionValue> CSSArrayFunctionValue::cloneForCSSOM() const
+PassRefPtrWillBeRawPtr<CSSArrayFunctionValue> CSSArrayFunctionValue::cloneForCSSOM() const
 {
-    return adoptRef(new CSSArrayFunctionValue(*this));
+    return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSArrayFunctionValue(*this));
 }
 
 bool CSSArrayFunctionValue::equals(const CSSArrayFunctionValue& other) const
diff --git a/Source/core/css/CSSArrayFunctionValue.h b/Source/core/css/CSSArrayFunctionValue.h
index fffc616..b92e5d4 100644
--- a/Source/core/css/CSSArrayFunctionValue.h
+++ b/Source/core/css/CSSArrayFunctionValue.h
@@ -37,17 +37,19 @@
 
 class CSSArrayFunctionValue : public CSSValueList {
 public:
-    static PassRefPtr<CSSArrayFunctionValue> create()
+    static PassRefPtrWillBeRawPtr<CSSArrayFunctionValue> create()
     {
-        return adoptRef(new CSSArrayFunctionValue());
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSArrayFunctionValue());
     }
 
     String customCSSText() const;
 
-    PassRefPtr<CSSArrayFunctionValue> cloneForCSSOM() const;
+    PassRefPtrWillBeRawPtr<CSSArrayFunctionValue> cloneForCSSOM() const;
 
     bool equals(const CSSArrayFunctionValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValueList::traceAfterDispatch(visitor); }
+
 private:
     CSSArrayFunctionValue();
     explicit CSSArrayFunctionValue(const CSSArrayFunctionValue& cloneFrom);
diff --git a/Source/core/css/CSSAspectRatioValue.h b/Source/core/css/CSSAspectRatioValue.h
index a92ac34..fc9aa47 100644
--- a/Source/core/css/CSSAspectRatioValue.h
+++ b/Source/core/css/CSSAspectRatioValue.h
@@ -35,9 +35,9 @@
 
 class CSSAspectRatioValue : public CSSValue {
 public:
-    static PassRefPtr<CSSAspectRatioValue> create(float numeratorValue, float denominatorValue)
+    static PassRefPtrWillBeRawPtr<CSSAspectRatioValue> create(float numeratorValue, float denominatorValue)
     {
-        return adoptRef(new CSSAspectRatioValue(numeratorValue, denominatorValue));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSAspectRatioValue(numeratorValue, denominatorValue));
     }
 
     String customCSSText() const;
@@ -47,6 +47,8 @@
 
     bool equals(const CSSAspectRatioValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     CSSAspectRatioValue(float numeratorValue, float denominatorValue)
         : CSSValue(AspectRatioClass)
diff --git a/Source/core/css/CSSBasicShapes.cpp b/Source/core/css/CSSBasicShapes.cpp
index 1104f17..f914c11 100644
--- a/Source/core/css/CSSBasicShapes.cpp
+++ b/Source/core/css/CSSBasicShapes.cpp
@@ -30,19 +30,20 @@
 #include "config.h"
 #include "core/css/CSSBasicShapes.h"
 
+#include "core/css/Pair.h"
 #include "wtf/text/StringBuilder.h"
 
 using namespace WTF;
 
 namespace WebCore {
 
-static String buildRectangleString(const String& x, const String& y, const String& width, const String& height, const String& radiusX, const String& radiusY)
+static String buildRectangleString(const String& x, const String& y, const String& width, const String& height, const String& radiusX, const String& radiusY, const String& layoutBox)
 {
-    char opening[] = "rectangle(";
-    char separator[] = ", ";
+    const char opening[] = "rectangle(";
+    const char separator[] = ", ";
     StringBuilder result;
     // Compute the required capacity in advance to reduce allocations.
-    result.reserveCapacity((sizeof(opening) - 1) + (5 * (sizeof(separator) - 1)) + 1 + x.length() + y.length() + width.length() + height.length() + radiusX.length() + radiusY.length());
+    result.reserveCapacity((sizeof(opening) - 1) + (5 * (sizeof(separator) - 1)) + 1 + x.length() + y.length() + width.length() + height.length() + radiusX.length() + radiusY.length() + (layoutBox.isEmpty() ? 0 : layoutBox.length() + 1));
     result.appendLiteral(opening);
     result.append(x);
     result.appendLiteral(separator);
@@ -59,6 +60,10 @@
             result.append(radiusY);
         }
     }
+    if (!layoutBox.isEmpty()) {
+        result.append(' ');
+        result.append(layoutBox);
+    }
     result.append(')');
     return result.toString();
 }
@@ -70,7 +75,8 @@
         m_width->cssText(),
         m_height->cssText(),
         m_radiusX.get() ? m_radiusX->cssText() : String(),
-        m_radiusY.get() ? m_radiusY->cssText() : String());
+        m_radiusY.get() ? m_radiusY->cssText() : String(),
+        m_layoutBox ? m_layoutBox->cssText() : String());
 }
 
 bool CSSBasicShapeRectangle::equals(const CSSBasicShape& shape) const
@@ -84,37 +90,42 @@
         && compareCSSValuePtr(m_width, other.m_width)
         && compareCSSValuePtr(m_height, other.m_height)
         && compareCSSValuePtr(m_radiusX, other.m_radiusX)
-        && compareCSSValuePtr(m_radiusY, other.m_radiusY);
+        && compareCSSValuePtr(m_radiusY, other.m_radiusY)
+        && compareCSSValuePtr(m_layoutBox, other.m_layoutBox);
 }
 
-String CSSBasicShapeRectangle::serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
+static String buildCircleString(const String& radius, const String& centerX, const String& centerY, const String& layoutBox)
 {
-    return buildRectangleString(m_x->serializeResolvingVariables(variables),
-        m_y->serializeResolvingVariables(variables),
-        m_width->serializeResolvingVariables(variables),
-        m_height->serializeResolvingVariables(variables),
-        m_radiusX.get() ? m_radiusX->serializeResolvingVariables(variables) : String(),
-        m_radiusY.get() ? m_radiusY->serializeResolvingVariables(variables) : String());
-}
+    char at[] = "at";
+    char separator[] = " ";
+    StringBuilder result;
+    result.appendLiteral("circle(");
+    if (!radius.isNull())
+        result.append(radius);
 
-bool CSSBasicShapeRectangle::hasVariableReference() const
-{
-    return m_x->hasVariableReference()
-        || m_y->hasVariableReference()
-        || m_width->hasVariableReference()
-        || m_height->hasVariableReference()
-        || (m_radiusX.get() && m_radiusX->hasVariableReference())
-        || (m_radiusY.get() && m_radiusY->hasVariableReference());
-}
-
-static String buildCircleString(const String& x, const String& y, const String& radius)
-{
-    return "circle(" + x + ", " + y + ", " + radius + ')';
+    if (!centerX.isNull() || !centerY.isNull()) {
+        if (!radius.isNull())
+            result.appendLiteral(separator);
+        result.append(at);
+        result.appendLiteral(separator);
+        result.append(centerX);
+        result.appendLiteral(separator);
+        result.append(centerY);
+    }
+    result.append(")");
+    if (layoutBox.length()) {
+        result.appendLiteral(separator);
+        result.append(layoutBox);
+    }
+    return result.toString();
 }
 
 String CSSBasicShapeCircle::cssText() const
 {
-    return buildCircleString(m_centerX->cssText(), m_centerY->cssText(), m_radius->cssText());
+    return buildCircleString(m_radius ? m_radius->cssText() : String(),
+        m_centerX ? m_centerX->cssText() : String(),
+        m_centerY ? m_centerY->cssText() : String(),
+        m_layoutBox ? m_layoutBox->cssText() : String());
 }
 
 bool CSSBasicShapeCircle::equals(const CSSBasicShape& shape) const
@@ -125,31 +136,73 @@
     const CSSBasicShapeCircle& other = static_cast<const CSSBasicShapeCircle&>(shape);
     return compareCSSValuePtr(m_centerX, other.m_centerX)
         && compareCSSValuePtr(m_centerY, other.m_centerY)
+        && compareCSSValuePtr(m_radius, other.m_radius)
+        && compareCSSValuePtr(m_layoutBox, other.m_layoutBox);
+}
+
+static String buildDeprecatedCircleString(const String& x, const String& y, const String& radius)
+{
+    return "circle(" + x + ", " + y + ", " + radius + ')';
+}
+
+String CSSDeprecatedBasicShapeCircle::cssText() const
+{
+    return buildDeprecatedCircleString(m_centerX->cssText(), m_centerY->cssText(), m_radius->cssText());
+}
+
+bool CSSDeprecatedBasicShapeCircle::equals(const CSSBasicShape& shape) const
+{
+    if (shape.type() != CSSDeprecatedBasicShapeCircleType)
+        return false;
+
+    const CSSDeprecatedBasicShapeCircle& other = static_cast<const CSSDeprecatedBasicShapeCircle&>(shape);
+    return compareCSSValuePtr(m_centerX, other.m_centerX)
+        && compareCSSValuePtr(m_centerY, other.m_centerY)
         && compareCSSValuePtr(m_radius, other.m_radius);
 }
 
-String CSSBasicShapeCircle::serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
+static String buildEllipseString(const String& radiusX, const String& radiusY, const String& centerX, const String& centerY, const String& box)
 {
-    return buildCircleString(m_centerX->serializeResolvingVariables(variables),
-        m_centerY->serializeResolvingVariables(variables),
-        m_radius->serializeResolvingVariables(variables));
-}
+    char at[] = "at";
+    char separator[] = " ";
+    StringBuilder result;
+    result.appendLiteral("ellipse(");
+    bool needsSeparator = false;
+    if (!radiusX.isNull()) {
+        result.append(radiusX);
+        needsSeparator = true;
+    }
+    if (!radiusY.isNull()) {
+        if (needsSeparator)
+            result.appendLiteral(separator);
+        result.append(radiusY);
+        needsSeparator = true;
+    }
 
-bool CSSBasicShapeCircle::hasVariableReference() const
-{
-    return m_centerX->hasVariableReference()
-        || m_centerY->hasVariableReference()
-        || m_radius->hasVariableReference();
-}
-
-static String buildEllipseString(const String& x, const String& y, const String& radiusX, const String& radiusY)
-{
-    return "ellipse(" + x + ", " + y + ", " + radiusX + ", " + radiusY + ')';
+    if (!centerX.isNull() || !centerY.isNull()) {
+        if (needsSeparator)
+            result.appendLiteral(separator);
+        result.appendLiteral(at);
+        result.appendLiteral(separator);
+        result.append(centerX);
+        result.appendLiteral(separator);
+        result.append(centerY);
+    }
+    result.append(")");
+    if (box.length()) {
+        result.appendLiteral(separator);
+        result.append(box);
+    }
+    return result.toString();
 }
 
 String CSSBasicShapeEllipse::cssText() const
 {
-    return buildEllipseString(m_centerX->cssText(), m_centerY->cssText(), m_radiusX->cssText(), m_radiusY->cssText());
+    return buildEllipseString(m_radiusX ? m_radiusX->cssText() : String(),
+        m_radiusY ? m_radiusY->cssText() : String(),
+        m_centerX ? m_centerX->cssText() : String(),
+        m_centerY ? m_centerY->cssText() : String(),
+        m_layoutBox ? m_layoutBox->cssText() : String());
 }
 
 bool CSSBasicShapeEllipse::equals(const CSSBasicShape& shape) const
@@ -161,33 +214,40 @@
     return compareCSSValuePtr(m_centerX, other.m_centerX)
         && compareCSSValuePtr(m_centerY, other.m_centerY)
         && compareCSSValuePtr(m_radiusX, other.m_radiusX)
+        && compareCSSValuePtr(m_radiusY, other.m_radiusY)
+        && compareCSSValuePtr(m_layoutBox, other.m_layoutBox);
+}
+
+static String buildDeprecatedEllipseString(const String& x, const String& y, const String& radiusX, const String& radiusY)
+{
+    return "ellipse(" + x + ", " + y + ", " + radiusX + ", " + radiusY + ')';
+}
+
+String CSSDeprecatedBasicShapeEllipse::cssText() const
+{
+    return buildDeprecatedEllipseString(m_centerX->cssText(), m_centerY->cssText(), m_radiusX->cssText(), m_radiusY->cssText());
+}
+
+bool CSSDeprecatedBasicShapeEllipse::equals(const CSSBasicShape& shape) const
+{
+    if (shape.type() != CSSDeprecatedBasicShapeEllipseType)
+        return false;
+
+    const CSSDeprecatedBasicShapeEllipse& other = static_cast<const CSSDeprecatedBasicShapeEllipse&>(shape);
+    return compareCSSValuePtr(m_centerX, other.m_centerX)
+        && compareCSSValuePtr(m_centerY, other.m_centerY)
+        && compareCSSValuePtr(m_radiusX, other.m_radiusX)
         && compareCSSValuePtr(m_radiusY, other.m_radiusY);
 }
 
-String CSSBasicShapeEllipse::serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-{
-    return buildEllipseString(m_centerX->serializeResolvingVariables(variables),
-        m_centerY->serializeResolvingVariables(variables),
-        m_radiusX->serializeResolvingVariables(variables),
-        m_radiusY->serializeResolvingVariables(variables));
-}
-
-bool CSSBasicShapeEllipse::hasVariableReference() const
-{
-    return m_centerX->hasVariableReference()
-        || m_centerY->hasVariableReference()
-        || m_radiusX->hasVariableReference()
-        || m_radiusY->hasVariableReference();
-}
-
-static String buildPolygonString(const WindRule& windRule, const Vector<String>& points)
+static String buildPolygonString(const WindRule& windRule, const Vector<String>& points, const String& layoutBox)
 {
     ASSERT(!(points.size() % 2));
 
     StringBuilder result;
-    char evenOddOpening[] = "polygon(evenodd, ";
-    char nonZeroOpening[] = "polygon(nonzero, ";
-    char commaSeparator[] = ", ";
+    const char evenOddOpening[] = "polygon(evenodd, ";
+    const char nonZeroOpening[] = "polygon(nonzero, ";
+    const char commaSeparator[] = ", ";
     COMPILE_ASSERT(sizeof(evenOddOpening) == sizeof(nonZeroOpening), polygon_string_openings_have_same_length);
 
     // Compute the required capacity in advance to reduce allocations.
@@ -198,6 +258,8 @@
         // add length of two strings, plus one for the space separator.
         length += points[i].length() + 1 + points[i + 1].length();
     }
+    if (!layoutBox.isEmpty())
+        length += layoutBox.length() + 1;
     result.reserveCapacity(length);
 
     if (windRule == RULE_EVENODD)
@@ -215,6 +277,11 @@
 
     result.append(')');
 
+    if (!layoutBox.isEmpty()) {
+        result.append(' ');
+        result.append(layoutBox);
+    }
+
     return result.toString();
 }
 
@@ -226,7 +293,7 @@
     for (size_t i = 0; i < m_values.size(); ++i)
         points.append(m_values.at(i)->cssText());
 
-    return buildPolygonString(m_windRule, points);
+    return buildPolygonString(m_windRule, points, m_layoutBox ? m_layoutBox->cssText() : String());
 }
 
 bool CSSBasicShapePolygon::equals(const CSSBasicShape& shape) const
@@ -235,36 +302,20 @@
         return false;
 
     const CSSBasicShapePolygon& rhs = static_cast<const CSSBasicShapePolygon&>(shape);
+
+    if (!compareCSSValuePtr(m_layoutBox, rhs.m_layoutBox))
+        return false;
+
     return compareCSSValueVector<CSSPrimitiveValue>(m_values, rhs.m_values);
 }
 
-String CSSBasicShapePolygon::serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
+static String buildInsetRectangleString(const String& top, const String& right, const String& bottom, const String& left, const String& radiusX, const String& radiusY, const String& layoutBox)
 {
-    Vector<String> points;
-    points.reserveInitialCapacity(m_values.size());
-
-    for (size_t i = 0; i < m_values.size(); ++i)
-        points.append(m_values.at(i)->serializeResolvingVariables(variables));
-
-    return buildPolygonString(m_windRule, points);
-}
-
-bool CSSBasicShapePolygon::hasVariableReference() const
-{
-    for (size_t i = 0; i < m_values.size(); ++i) {
-        if (m_values.at(i)->hasVariableReference())
-            return true;
-    }
-    return false;
-}
-
-static String buildInsetRectangleString(const String& top, const String& right, const String& bottom, const String& left, const String& radiusX, const String& radiusY)
-{
-    char opening[] = "inset-rectangle(";
-    char separator[] = ", ";
+    const char opening[] = "inset-rectangle(";
+    const char separator[] = ", ";
     StringBuilder result;
     // Compute the required capacity in advance to reduce allocations.
-    result.reserveCapacity((sizeof(opening) - 1) + (5 * (sizeof(separator) - 1)) + 1 + top.length() + right.length() + bottom.length() + left.length() + radiusX.length() + radiusY.length());
+    result.reserveCapacity((sizeof(opening) - 1) + (5 * (sizeof(separator) - 1)) + 1 + top.length() + right.length() + bottom.length() + left.length() + radiusX.length() + radiusY.length() + (layoutBox.isEmpty() ? 0 : layoutBox.length() + 1));
     result.appendLiteral(opening);
     result.append(top);
     result.appendLiteral(separator);
@@ -282,6 +333,12 @@
         }
     }
     result.append(')');
+
+    if (!layoutBox.isEmpty()) {
+        result.append(' ');
+        result.append(layoutBox);
+    }
+
     return result.toString();
 }
 
@@ -292,7 +349,8 @@
         m_bottom->cssText(),
         m_left->cssText(),
         m_radiusX.get() ? m_radiusX->cssText() : String(),
-        m_radiusY.get() ? m_radiusY->cssText() : String());
+        m_radiusY.get() ? m_radiusY->cssText() : String(),
+        m_layoutBox ? m_layoutBox->cssText() : String());
 }
 
 bool CSSBasicShapeInsetRectangle::equals(const CSSBasicShape& shape) const
@@ -306,27 +364,120 @@
         && compareCSSValuePtr(m_bottom, other.m_bottom)
         && compareCSSValuePtr(m_left, other.m_left)
         && compareCSSValuePtr(m_radiusX, other.m_radiusX)
-        && compareCSSValuePtr(m_radiusY, other.m_radiusY);
+        && compareCSSValuePtr(m_radiusY, other.m_radiusY)
+        && compareCSSValuePtr(m_layoutBox, other.m_layoutBox);
 }
 
-String CSSBasicShapeInsetRectangle::serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
+static String buildInsetString(const String& top, const String& right, const String& bottom, const String& left,
+    const String& topLeftRadiusWidth, const String& topLeftRadiusHeight,
+    const String& topRightRadiusWidth, const String& topRightRadiusHeight,
+    const String& bottomRightRadiusWidth, const String& bottomRightRadiusHeight,
+    const String& bottomLeftRadiusWidth, const String& bottomLeftRadiusHeight)
 {
-    return buildInsetRectangleString(m_top->serializeResolvingVariables(variables),
-        m_right->serializeResolvingVariables(variables),
-        m_bottom->serializeResolvingVariables(variables),
-        m_left->serializeResolvingVariables(variables),
-        m_radiusX.get() ? m_radiusX->serializeResolvingVariables(variables) : String(),
-        m_radiusY.get() ? m_radiusY->serializeResolvingVariables(variables) : String());
+    char opening[] = "inset(";
+    char separator[] = " ";
+    char cornersSeparator[] = "round";
+    StringBuilder result;
+    result.appendLiteral(opening);
+    result.append(top);
+    if (!right.isNull()) {
+        result.appendLiteral(separator);
+        result.append(right);
+    }
+    if (!bottom.isNull()) {
+        result.appendLiteral(separator);
+        result.append(bottom);
+    }
+    if (!left.isNull()) {
+        result.appendLiteral(separator);
+        result.append(left);
+    }
+
+    if (!topLeftRadiusWidth.isNull() && !topLeftRadiusHeight.isNull()) {
+        result.appendLiteral(separator);
+        result.appendLiteral(cornersSeparator);
+        result.appendLiteral(separator);
+
+        result.append(topLeftRadiusWidth);
+        result.appendLiteral(separator);
+        result.append(topRightRadiusWidth);
+        result.appendLiteral(separator);
+        result.append(bottomRightRadiusWidth);
+        result.appendLiteral(separator);
+        result.append(bottomLeftRadiusWidth);
+
+        result.appendLiteral(separator);
+        result.appendLiteral("/");
+        result.appendLiteral(separator);
+
+        result.append(topLeftRadiusHeight);
+        result.appendLiteral(separator);
+        result.append(topRightRadiusHeight);
+        result.appendLiteral(separator);
+        result.append(bottomRightRadiusHeight);
+        result.appendLiteral(separator);
+        result.append(bottomLeftRadiusHeight);
+    }
+    result.append(')');
+
+    return result.toString();
 }
 
-bool CSSBasicShapeInsetRectangle::hasVariableReference() const
+static inline void updateCornerRadiusWidthAndHeight(CSSPrimitiveValue* corner, String& width, String& height)
 {
-    return m_top->hasVariableReference()
-        || m_right->hasVariableReference()
-        || m_bottom->hasVariableReference()
-        || m_left->hasVariableReference()
-        || (m_radiusX.get() && m_radiusX->hasVariableReference())
-        || (m_radiusY.get() && m_radiusY->hasVariableReference());
+    if (!corner)
+        return;
+
+    Pair* radius = corner->getPairValue();
+    width = radius->first() ? radius->first()->cssText() : String("0");
+    if (radius->second())
+        height = radius->second()->cssText();
+}
+
+String CSSBasicShapeInset::cssText() const
+{
+    String topLeftRadiusWidth;
+    String topLeftRadiusHeight;
+    String topRightRadiusWidth;
+    String topRightRadiusHeight;
+    String bottomRightRadiusWidth;
+    String bottomRightRadiusHeight;
+    String bottomLeftRadiusWidth;
+    String bottomLeftRadiusHeight;
+
+    updateCornerRadiusWidthAndHeight(topLeftRadius(), topLeftRadiusWidth, topLeftRadiusHeight);
+    updateCornerRadiusWidthAndHeight(topRightRadius(), topRightRadiusWidth, topRightRadiusHeight);
+    updateCornerRadiusWidthAndHeight(bottomRightRadius(), bottomRightRadiusWidth, bottomRightRadiusHeight);
+    updateCornerRadiusWidthAndHeight(bottomLeftRadius(), bottomLeftRadiusWidth, bottomLeftRadiusHeight);
+
+    return buildInsetString(m_top ? m_top->cssText() : String(),
+        m_right ? m_right->cssText() : String(),
+        m_bottom ? m_bottom->cssText() : String(),
+        m_left ? m_left->cssText() : String(),
+        topLeftRadiusWidth,
+        topLeftRadiusHeight,
+        topRightRadiusWidth,
+        topRightRadiusHeight,
+        bottomRightRadiusWidth,
+        bottomRightRadiusHeight,
+        bottomLeftRadiusWidth,
+        bottomLeftRadiusHeight);
+}
+
+bool CSSBasicShapeInset::equals(const CSSBasicShape& shape) const
+{
+    if (shape.type() != CSSBasicShapeInsetType)
+        return false;
+
+    const CSSBasicShapeInset& other = static_cast<const CSSBasicShapeInset&>(shape);
+    return compareCSSValuePtr(m_top, other.m_top)
+        && compareCSSValuePtr(m_right, other.m_right)
+        && compareCSSValuePtr(m_bottom, other.m_bottom)
+        && compareCSSValuePtr(m_left, other.m_left)
+        && compareCSSValuePtr(m_topLeftRadius, other.m_topLeftRadius)
+        && compareCSSValuePtr(m_topRightRadius, other.m_topRightRadius)
+        && compareCSSValuePtr(m_bottomRightRadius, other.m_bottomRightRadius)
+        && compareCSSValuePtr(m_bottomLeftRadius, other.m_bottomLeftRadius);
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSBasicShapes.h b/Source/core/css/CSSBasicShapes.h
index ca8c661..8b48fbb 100644
--- a/Source/core/css/CSSBasicShapes.h
+++ b/Source/core/css/CSSBasicShapes.h
@@ -41,28 +41,32 @@
 class CSSBasicShape : public RefCounted<CSSBasicShape> {
 public:
     enum Type {
-        CSSBasicShapeRectangleType = 1,
-        CSSBasicShapeCircleType = 2,
-        CSSBasicShapeEllipseType = 3,
-        CSSBasicShapePolygonType = 4,
-        CSSBasicShapeInsetRectangleType = 5
+        CSSBasicShapeRectangleType,
+        CSSDeprecatedBasicShapeCircleType,
+        CSSDeprecatedBasicShapeEllipseType,
+        CSSBasicShapeEllipseType,
+        CSSBasicShapePolygonType,
+        CSSBasicShapeInsetRectangleType,
+        CSSBasicShapeCircleType,
+        CSSBasicShapeInsetType
     };
 
     virtual Type type() const = 0;
     virtual String cssText() const = 0;
     virtual bool equals(const CSSBasicShape&) const = 0;
 
-    virtual String serializeResolvingVariables(const HashMap<AtomicString, String>&) const = 0;
-    virtual bool hasVariableReference() const = 0;
+    CSSPrimitiveValue* layoutBox() const { return m_layoutBox.get(); }
+    void setLayoutBox(PassRefPtr<CSSPrimitiveValue> layoutBox) { m_layoutBox = layoutBox; }
 
 public:
     virtual ~CSSBasicShape() { }
 
 protected:
     CSSBasicShape() { }
+    RefPtr<CSSPrimitiveValue> m_layoutBox;
 };
 
-class CSSBasicShapeRectangle : public CSSBasicShape {
+class CSSBasicShapeRectangle FINAL : public CSSBasicShape {
 public:
     static PassRefPtr<CSSBasicShapeRectangle> create() { return adoptRef(new CSSBasicShapeRectangle); }
 
@@ -80,12 +84,9 @@
     void setRadiusX(PassRefPtr<CSSPrimitiveValue> radiusX) { m_radiusX = radiusX; }
     void setRadiusY(PassRefPtr<CSSPrimitiveValue> radiusY) { m_radiusY = radiusY; }
 
-    virtual Type type() const { return CSSBasicShapeRectangleType; }
-    virtual String cssText() const;
-    virtual bool equals(const CSSBasicShape&) const;
-
-    virtual String serializeResolvingVariables(const HashMap<AtomicString, String>&) const;
-    virtual bool hasVariableReference() const;
+    virtual Type type() const OVERRIDE { return CSSBasicShapeRectangleType; }
+    virtual String cssText() const OVERRIDE;
+    virtual bool equals(const CSSBasicShape&) const OVERRIDE;
 
 private:
     CSSBasicShapeRectangle() { }
@@ -98,7 +99,7 @@
     RefPtr<CSSPrimitiveValue> m_radiusY;
 };
 
-class CSSBasicShapeInsetRectangle : public CSSBasicShape {
+class CSSBasicShapeInsetRectangle FINAL : public CSSBasicShape {
 public:
     static PassRefPtr<CSSBasicShapeInsetRectangle> create() { return adoptRef(new CSSBasicShapeInsetRectangle); }
 
@@ -116,12 +117,9 @@
     void setRadiusX(PassRefPtr<CSSPrimitiveValue> radiusX) { m_radiusX = radiusX; }
     void setRadiusY(PassRefPtr<CSSPrimitiveValue> radiusY) { m_radiusY = radiusY; }
 
-    virtual Type type() const { return CSSBasicShapeInsetRectangleType; }
-    virtual String cssText() const;
-    virtual bool equals(const CSSBasicShape&) const;
-
-    virtual String serializeResolvingVariables(const HashMap<AtomicString, String>&) const;
-    virtual bool hasVariableReference() const;
+    virtual Type type() const OVERRIDE { return CSSBasicShapeInsetRectangleType; }
+    virtual String cssText() const OVERRIDE;
+    virtual bool equals(const CSSBasicShape&) const OVERRIDE;
 
 private:
     CSSBasicShapeInsetRectangle() { }
@@ -134,10 +132,14 @@
     RefPtr<CSSPrimitiveValue> m_radiusY;
 };
 
-class CSSBasicShapeCircle : public CSSBasicShape {
+class CSSBasicShapeCircle FINAL : public CSSBasicShape {
 public:
     static PassRefPtr<CSSBasicShapeCircle> create() { return adoptRef(new CSSBasicShapeCircle); }
 
+    virtual Type type() const OVERRIDE { return CSSBasicShapeCircleType; }
+    virtual String cssText() const OVERRIDE;
+    virtual bool equals(const CSSBasicShape&) const OVERRIDE;
+
     CSSPrimitiveValue* centerX() const { return m_centerX.get(); }
     CSSPrimitiveValue* centerY() const { return m_centerY.get(); }
     CSSPrimitiveValue* radius() const { return m_radius.get(); }
@@ -146,25 +148,47 @@
     void setCenterY(PassRefPtr<CSSPrimitiveValue> centerY) { m_centerY = centerY; }
     void setRadius(PassRefPtr<CSSPrimitiveValue> radius) { m_radius = radius; }
 
-    virtual Type type() const { return CSSBasicShapeCircleType; }
-    virtual String cssText() const;
-    virtual bool equals(const CSSBasicShape&) const;
-
-    virtual String serializeResolvingVariables(const HashMap<AtomicString, String>&) const;
-    virtual bool hasVariableReference() const;
-
 private:
     CSSBasicShapeCircle() { }
 
+    RefPtr<CSSPrimitiveValue> m_centerX;
+    RefPtr<CSSPrimitiveValue> m_centerY;
+    RefPtr<CSSPrimitiveValue> m_radius;
+};
+
+class CSSDeprecatedBasicShapeCircle FINAL : public CSSBasicShape {
+public:
+    static PassRefPtr<CSSDeprecatedBasicShapeCircle> create() { return adoptRef(new CSSDeprecatedBasicShapeCircle); }
+
+    CSSPrimitiveValue* centerX() const { return m_centerX.get(); }
+    CSSPrimitiveValue* centerY() const { return m_centerY.get(); }
+    CSSPrimitiveValue* radius() const { return m_radius.get(); }
+
+    void setCenterX(PassRefPtr<CSSPrimitiveValue> centerX) { m_centerX = centerX; }
+    void setCenterY(PassRefPtr<CSSPrimitiveValue> centerY) { m_centerY = centerY; }
+    void setRadius(PassRefPtr<CSSPrimitiveValue> radius) { m_radius = radius; }
+
+    virtual Type type() const OVERRIDE { return CSSDeprecatedBasicShapeCircleType; }
+
+    virtual String cssText() const OVERRIDE;
+    virtual bool equals(const CSSBasicShape&) const OVERRIDE;
+
+private:
+    CSSDeprecatedBasicShapeCircle() { }
+
     RefPtr<CSSPrimitiveValue> m_centerY;
     RefPtr<CSSPrimitiveValue> m_centerX;
     RefPtr<CSSPrimitiveValue> m_radius;
 };
 
-class CSSBasicShapeEllipse : public CSSBasicShape {
+class CSSBasicShapeEllipse FINAL : public CSSBasicShape {
 public:
     static PassRefPtr<CSSBasicShapeEllipse> create() { return adoptRef(new CSSBasicShapeEllipse); }
 
+    virtual Type type() const OVERRIDE { return CSSBasicShapeEllipseType; }
+    virtual String cssText() const OVERRIDE;
+    virtual bool equals(const CSSBasicShape&) const OVERRIDE;
+
     CSSPrimitiveValue* centerX() const { return m_centerX.get(); }
     CSSPrimitiveValue* centerY() const { return m_centerY.get(); }
     CSSPrimitiveValue* radiusX() const { return m_radiusX.get(); }
@@ -175,13 +199,6 @@
     void setRadiusX(PassRefPtr<CSSPrimitiveValue> radiusX) { m_radiusX = radiusX; }
     void setRadiusY(PassRefPtr<CSSPrimitiveValue> radiusY) { m_radiusY = radiusY; }
 
-    virtual Type type() const { return CSSBasicShapeEllipseType; }
-    virtual String cssText() const;
-    virtual bool equals(const CSSBasicShape&) const;
-
-    virtual String serializeResolvingVariables(const HashMap<AtomicString, String>&) const;
-    virtual bool hasVariableReference() const;
-
 private:
     CSSBasicShapeEllipse() { }
 
@@ -191,7 +208,34 @@
     RefPtr<CSSPrimitiveValue> m_radiusY;
 };
 
-class CSSBasicShapePolygon : public CSSBasicShape {
+class CSSDeprecatedBasicShapeEllipse FINAL : public CSSBasicShape {
+public:
+    static PassRefPtr<CSSDeprecatedBasicShapeEllipse> create() { return adoptRef(new CSSDeprecatedBasicShapeEllipse); }
+
+    CSSPrimitiveValue* centerX() const { return m_centerX.get(); }
+    CSSPrimitiveValue* centerY() const { return m_centerY.get(); }
+    CSSPrimitiveValue* radiusX() const { return m_radiusX.get(); }
+    CSSPrimitiveValue* radiusY() const { return m_radiusY.get(); }
+
+    void setCenterX(PassRefPtr<CSSPrimitiveValue> centerX) { m_centerX = centerX; }
+    void setCenterY(PassRefPtr<CSSPrimitiveValue> centerY) { m_centerY = centerY; }
+    void setRadiusX(PassRefPtr<CSSPrimitiveValue> radiusX) { m_radiusX = radiusX; }
+    void setRadiusY(PassRefPtr<CSSPrimitiveValue> radiusY) { m_radiusY = radiusY; }
+
+    virtual Type type() const OVERRIDE { return CSSDeprecatedBasicShapeEllipseType; }
+    virtual String cssText() const OVERRIDE;
+    virtual bool equals(const CSSBasicShape&) const OVERRIDE;
+
+private:
+    CSSDeprecatedBasicShapeEllipse() { }
+
+    RefPtr<CSSPrimitiveValue> m_centerX;
+    RefPtr<CSSPrimitiveValue> m_centerY;
+    RefPtr<CSSPrimitiveValue> m_radiusX;
+    RefPtr<CSSPrimitiveValue> m_radiusY;
+};
+
+class CSSBasicShapePolygon FINAL : public CSSBasicShape {
 public:
     static PassRefPtr<CSSBasicShapePolygon> create() { return adoptRef(new CSSBasicShapePolygon); }
 
@@ -208,12 +252,9 @@
     void setWindRule(WindRule w) { m_windRule = w; }
     WindRule windRule() const { return m_windRule; }
 
-    virtual Type type() const { return CSSBasicShapePolygonType; }
-    virtual String cssText() const;
-    virtual bool equals(const CSSBasicShape&) const;
-    virtual String serializeResolvingVariables(const HashMap<AtomicString, String>&) const;
-    virtual bool hasVariableReference() const;
-
+    virtual Type type() const OVERRIDE { return CSSBasicShapePolygonType; }
+    virtual String cssText() const OVERRIDE;
+    virtual bool equals(const CSSBasicShape&) const OVERRIDE;
 private:
     CSSBasicShapePolygon()
         : m_windRule(RULE_NONZERO)
@@ -224,6 +265,72 @@
     WindRule m_windRule;
 };
 
+class CSSBasicShapeInset : public CSSBasicShape {
+public:
+    static PassRefPtr<CSSBasicShapeInset> create() { return adoptRef(new CSSBasicShapeInset); }
+
+    CSSPrimitiveValue* top() const { return m_top.get(); }
+    CSSPrimitiveValue* right() const { return m_right.get(); }
+    CSSPrimitiveValue* bottom() const { return m_bottom.get(); }
+    CSSPrimitiveValue* left() const { return m_left.get(); }
+
+    CSSPrimitiveValue* topLeftRadius() const { return m_topLeftRadius.get(); }
+    CSSPrimitiveValue* topRightRadius() const { return m_topRightRadius.get(); }
+    CSSPrimitiveValue* bottomRightRadius() const { return m_bottomRightRadius.get(); }
+    CSSPrimitiveValue* bottomLeftRadius() const { return m_bottomLeftRadius.get(); }
+
+    void setTop(PassRefPtr<CSSPrimitiveValue> top) { m_top = top; }
+    void setRight(PassRefPtr<CSSPrimitiveValue> right) { m_right = right; }
+    void setBottom(PassRefPtr<CSSPrimitiveValue> bottom) { m_bottom = bottom; }
+    void setLeft(PassRefPtr<CSSPrimitiveValue> left) { m_left = left; }
+
+    void updateShapeSize4Values(CSSPrimitiveValue* top, CSSPrimitiveValue* right, CSSPrimitiveValue* bottom, CSSPrimitiveValue* left)
+    {
+        setTop(top);
+        setRight(right);
+        setBottom(bottom);
+        setLeft(left);
+    }
+
+    void updateShapeSize1Value(CSSPrimitiveValue* value1)
+    {
+        updateShapeSize4Values(value1, value1, value1, value1);
+    }
+
+    void updateShapeSize2Values(CSSPrimitiveValue* value1,  CSSPrimitiveValue* value2)
+    {
+        updateShapeSize4Values(value1, value2, value1, value2);
+    }
+
+    void updateShapeSize3Values(CSSPrimitiveValue* value1, CSSPrimitiveValue* value2,  CSSPrimitiveValue* value3)
+    {
+        updateShapeSize4Values(value1, value2, value3, value2);
+    }
+
+
+    void setTopLeftRadius(PassRefPtr<CSSPrimitiveValue> radius) { m_topLeftRadius = radius; }
+    void setTopRightRadius(PassRefPtr<CSSPrimitiveValue> radius) { m_topRightRadius = radius; }
+    void setBottomRightRadius(PassRefPtr<CSSPrimitiveValue> radius) { m_bottomRightRadius = radius; }
+    void setBottomLeftRadius(PassRefPtr<CSSPrimitiveValue> radius) { m_bottomLeftRadius = radius; }
+
+    virtual Type type() const OVERRIDE { return CSSBasicShapeInsetType; }
+    virtual String cssText() const OVERRIDE;
+    virtual bool equals(const CSSBasicShape&) const OVERRIDE;
+
+private:
+    CSSBasicShapeInset() { }
+
+    RefPtr<CSSPrimitiveValue> m_top;
+    RefPtr<CSSPrimitiveValue> m_right;
+    RefPtr<CSSPrimitiveValue> m_bottom;
+    RefPtr<CSSPrimitiveValue> m_left;
+
+    RefPtr<CSSPrimitiveValue> m_topLeftRadius;
+    RefPtr<CSSPrimitiveValue> m_topRightRadius;
+    RefPtr<CSSPrimitiveValue> m_bottomRightRadius;
+    RefPtr<CSSPrimitiveValue> m_bottomLeftRadius;
+};
+
 } // namespace WebCore
 
 #endif // CSSBasicShapes_h
diff --git a/Source/core/css/CSSBorderImage.cpp b/Source/core/css/CSSBorderImage.cpp
index d62711d..9b7cab9 100644
--- a/Source/core/css/CSSBorderImage.cpp
+++ b/Source/core/css/CSSBorderImage.cpp
@@ -22,15 +22,15 @@
 
 namespace WebCore {
 
-PassRefPtr<CSSValueList> createBorderImageValue(PassRefPtr<CSSValue> image, PassRefPtr<CSSValue> imageSlice, PassRefPtr<CSSValue> borderSlice,
+PassRefPtrWillBeRawPtr<CSSValueList> createBorderImageValue(PassRefPtr<CSSValue> image, PassRefPtr<CSSValue> imageSlice, PassRefPtr<CSSValue> borderSlice,
                                                 PassRefPtr<CSSValue> outset, PassRefPtr<CSSValue> repeat)
 {
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     if (image)
         list->append(image);
 
     if (borderSlice || outset) {
-        RefPtr<CSSValueList> listSlash = CSSValueList::createSlashSeparated();
+        RefPtrWillBeRawPtr<CSSValueList> listSlash = CSSValueList::createSlashSeparated();
         if (imageSlice)
             listSlash->append(imageSlice);
 
diff --git a/Source/core/css/CSSBorderImage.h b/Source/core/css/CSSBorderImage.h
index bdf13fe..42d2a1f 100644
--- a/Source/core/css/CSSBorderImage.h
+++ b/Source/core/css/CSSBorderImage.h
@@ -26,8 +26,8 @@
 
 namespace WebCore {
 
-PassRefPtr<CSSValueList> createBorderImageValue(PassRefPtr<CSSValue> image, PassRefPtr<CSSValue> imageSlice, PassRefPtr<CSSValue> borderSlice,
-                                                PassRefPtr<CSSValue> outset, PassRefPtr<CSSValue> repeat);
+PassRefPtrWillBeRawPtr<CSSValueList> createBorderImageValue(PassRefPtr<CSSValue> image, PassRefPtr<CSSValue> imageSlice, PassRefPtr<CSSValue> borderSlice,
+    PassRefPtr<CSSValue> outset, PassRefPtr<CSSValue> repeat);
 
 } // namespace WebCore
 
diff --git a/Source/core/css/CSSBorderImageSliceValue.cpp b/Source/core/css/CSSBorderImageSliceValue.cpp
index 7ffac3a..34400a8 100644
--- a/Source/core/css/CSSBorderImageSliceValue.cpp
+++ b/Source/core/css/CSSBorderImageSliceValue.cpp
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-CSSBorderImageSliceValue::CSSBorderImageSliceValue(PassRefPtr<CSSPrimitiveValue> slices, bool fill)
+CSSBorderImageSliceValue::CSSBorderImageSliceValue(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> slices, bool fill)
     : CSSValue(BorderImageSliceClass)
     , m_slices(slices)
     , m_fill(fill)
@@ -53,4 +53,10 @@
     return m_fill == other.m_fill && compareCSSValuePtr(m_slices, other.m_slices);
 }
 
+void CSSBorderImageSliceValue::traceAfterDispatch(Visitor* visitor)
+{
+    visitor->trace(m_slices);
+    CSSValue::traceAfterDispatch(visitor);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSBorderImageSliceValue.h b/Source/core/css/CSSBorderImageSliceValue.h
index 7d297ea..6243cf4 100644
--- a/Source/core/css/CSSBorderImageSliceValue.h
+++ b/Source/core/css/CSSBorderImageSliceValue.h
@@ -36,9 +36,9 @@
 
 class CSSBorderImageSliceValue : public CSSValue {
 public:
-    static PassRefPtr<CSSBorderImageSliceValue> create(PassRefPtr<CSSPrimitiveValue> slices, bool fill)
+    static PassRefPtrWillBeRawPtr<CSSBorderImageSliceValue> create(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> slices, bool fill)
     {
-        return adoptRef(new CSSBorderImageSliceValue(slices, fill));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSBorderImageSliceValue(slices, fill));
     }
 
     String customCSSText() const;
@@ -47,13 +47,15 @@
 
     bool equals(const CSSBorderImageSliceValue&) const;
 
+    void traceAfterDispatch(Visitor*);
+
     // These four values are used to make "cuts" in the border image. They can be numbers
     // or percentages.
-    RefPtr<CSSPrimitiveValue> m_slices;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_slices;
     bool m_fill;
 
 private:
-    CSSBorderImageSliceValue(PassRefPtr<CSSPrimitiveValue> slices, bool fill);
+    CSSBorderImageSliceValue(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> slices, bool fill);
 };
 
 DEFINE_CSS_VALUE_TYPE_CASTS(CSSBorderImageSliceValue, isBorderImageSliceValue());
diff --git a/Source/core/css/CSSCalculationValue.cpp b/Source/core/css/CSSCalculationValue.cpp
index e27cba3..58ce6d7 100644
--- a/Source/core/css/CSSCalculationValue.cpp
+++ b/Source/core/css/CSSCalculationValue.cpp
@@ -47,6 +47,8 @@
 
 namespace WebCore {
 
+DEFINE_GC_INFO(CSSCalcExpressionNode);
+
 static CalculationCategory unitCategory(CSSPrimitiveValue::UnitTypes type)
 {
     switch (type) {
@@ -65,9 +67,11 @@
     case CSSPrimitiveValue::CSS_PC:
     case CSSPrimitiveValue::CSS_REMS:
     case CSSPrimitiveValue::CSS_CHS:
+    case CSSPrimitiveValue::CSS_VW:
+    case CSSPrimitiveValue::CSS_VH:
+    case CSSPrimitiveValue::CSS_VMIN:
+    case CSSPrimitiveValue::CSS_VMAX:
         return CalcLength;
-    case CSSPrimitiveValue::CSS_VARIABLE_NAME:
-        return CalcVariable;
     default:
         return CalcOther;
     }
@@ -126,7 +130,6 @@
     case CSSPrimitiveValue::CSS_CALC:
     case CSSPrimitiveValue::CSS_CALC_PERCENTAGE_WITH_NUMBER:
     case CSSPrimitiveValue::CSS_CALC_PERCENTAGE_WITH_LENGTH:
-    case CSSPrimitiveValue::CSS_VARIABLE_NAME:
     case CSSPrimitiveValue::CSS_PROPERTY_ID:
     case CSSPrimitiveValue::CSS_VALUE_ID:
         return false;
@@ -158,16 +161,6 @@
     return compareCSSValuePtr(m_expression, other.m_expression);
 }
 
-String CSSCalcValue::customSerializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-{
-    return buildCSSText(m_expression->serializeResolvingVariables(variables));
-}
-
-bool CSSCalcValue::hasVariableReference() const
-{
-    return m_expression->hasVariableReference();
-}
-
 double CSSCalcValue::clampToPermittedRange(double value) const
 {
     return m_nonNegative && value < 0 ? 0 : value;
@@ -187,43 +180,33 @@
 {
 }
 
-class CSSCalcPrimitiveValue : public CSSCalcExpressionNode {
-    WTF_MAKE_FAST_ALLOCATED;
+class CSSCalcPrimitiveValue FINAL : public CSSCalcExpressionNode {
+    WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
 public:
 
-    static PassRefPtr<CSSCalcPrimitiveValue> create(PassRefPtr<CSSPrimitiveValue> value, bool isInteger)
+    static PassRefPtrWillBeRawPtr<CSSCalcPrimitiveValue> create(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> value, bool isInteger)
     {
-        return adoptRef(new CSSCalcPrimitiveValue(value, isInteger));
+        return adoptRefWillBeNoop(new CSSCalcPrimitiveValue(value, isInteger));
     }
 
-    static PassRefPtr<CSSCalcPrimitiveValue> create(double value, CSSPrimitiveValue::UnitTypes type, bool isInteger)
+    static PassRefPtrWillBeRawPtr<CSSCalcPrimitiveValue> create(double value, CSSPrimitiveValue::UnitTypes type, bool isInteger)
     {
         if (std::isnan(value) || std::isinf(value))
             return 0;
-        return adoptRef(new CSSCalcPrimitiveValue(CSSPrimitiveValue::create(value, type).get(), isInteger));
+        return adoptRefWillBeNoop(new CSSCalcPrimitiveValue(CSSPrimitiveValue::create(value, type).get(), isInteger));
     }
 
-    virtual bool isZero() const
+    virtual bool isZero() const OVERRIDE
     {
         return !m_value->getDoubleValue();
     }
 
-    virtual String customCSSText() const
+    virtual String customCSSText() const OVERRIDE
     {
         return m_value->cssText();
     }
 
-    virtual String serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-    {
-        return m_value->customSerializeResolvingVariables(variables);
-    }
-
-    virtual bool hasVariableReference() const
-    {
-        return m_value->isVariableName();
-    }
-
-    virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const CSSToLengthConversionData& conversionData) const
+    virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const CSSToLengthConversionData& conversionData) const OVERRIDE
     {
         switch (m_category) {
         case CalcNumber:
@@ -231,23 +214,18 @@
         case CalcLength:
             return adoptPtr(new CalcExpressionLength(Length(m_value->computeLength<float>(conversionData), WebCore::Fixed)));
         case CalcPercent:
-        case CalcPercentLength: {
-            CSSPrimitiveValue* primitiveValue = m_value.get();
-            return adoptPtr(new CalcExpressionLength(primitiveValue
-                ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(conversionData)
-                : Length(Undefined)));
-        }
+        case CalcPercentLength:
+            return adoptPtr(new CalcExpressionLength(m_value->convertToLength<FixedConversion | PercentConversion>(conversionData)));
         // Only types that could be part of a Length expression can be converted
         // to a CalcExpressionNode. CalcPercentNumber makes no sense as a Length.
         case CalcPercentNumber:
-        case CalcVariable:
         case CalcOther:
             ASSERT_NOT_REACHED();
         }
         return nullptr;
     }
 
-    virtual double doubleValue() const
+    virtual double doubleValue() const OVERRIDE
     {
         if (hasDoubleValue(primitiveType()))
             return m_value->getDoubleValue();
@@ -255,7 +233,7 @@
         return 0;
     }
 
-    virtual double computeLengthPx(const CSSToLengthConversionData& conversionData) const
+    virtual double computeLengthPx(const CSSToLengthConversionData& conversionData) const OVERRIDE
     {
         switch (m_category) {
         case CalcLength:
@@ -265,7 +243,6 @@
             return m_value->getDoubleValue();
         case CalcPercentLength:
         case CalcPercentNumber:
-        case CalcVariable:
         case CalcOther:
             ASSERT_NOT_REACHED();
             break;
@@ -274,7 +251,7 @@
         return 0;
     }
 
-    virtual bool equals(const CSSCalcExpressionNode& other) const
+    virtual bool equals(const CSSCalcExpressionNode& other) const OVERRIDE
     {
         if (type() != other.type())
             return false;
@@ -282,20 +259,27 @@
         return compareCSSValuePtr(m_value, static_cast<const CSSCalcPrimitiveValue&>(other).m_value);
     }
 
-    virtual Type type() const { return CssCalcPrimitiveValue; }
-    virtual CSSPrimitiveValue::UnitTypes primitiveType() const
+    virtual Type type() const OVERRIDE { return CssCalcPrimitiveValue; }
+    virtual CSSPrimitiveValue::UnitTypes primitiveType() const OVERRIDE
     {
         return CSSPrimitiveValue::UnitTypes(m_value->primitiveType());
     }
 
+
+    virtual void trace(Visitor* visitor)
+    {
+        visitor->trace(m_value);
+        CSSCalcExpressionNode::trace(visitor);
+    }
+
 private:
-    explicit CSSCalcPrimitiveValue(PassRefPtr<CSSPrimitiveValue> value, bool isInteger)
+    CSSCalcPrimitiveValue(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> value, bool isInteger)
         : CSSCalcExpressionNode(unitCategory((CSSPrimitiveValue::UnitTypes)value->primitiveType()), isInteger)
         , m_value(value)
     {
     }
 
-    RefPtr<CSSPrimitiveValue> m_value;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_value;
 };
 
 static const CalculationCategory addSubtractResult[CalcOther][CalcOther] = {
@@ -315,9 +299,6 @@
     if (leftCategory == CalcOther || rightCategory == CalcOther)
         return CalcOther;
 
-    if (leftCategory == CalcVariable || rightCategory == CalcVariable)
-        return CalcVariable;
-
     switch (op) {
     case CalcAdd:
     case CalcSubtract:
@@ -344,10 +325,9 @@
     return op != CalcDivide && leftSide->isInteger() && rightSide->isInteger();
 }
 
-class CSSCalcBinaryOperation : public CSSCalcExpressionNode {
-
+class CSSCalcBinaryOperation FINAL : public CSSCalcExpressionNode {
 public:
-    static PassRefPtr<CSSCalcExpressionNode> create(PassRefPtr<CSSCalcExpressionNode> leftSide, PassRefPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
+    static PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> create(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> leftSide, PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
     {
         ASSERT(leftSide->category() != CalcOther && rightSide->category() != CalcOther);
 
@@ -355,10 +335,10 @@
         if (newCategory == CalcOther)
             return 0;
 
-        return adoptRef(new CSSCalcBinaryOperation(leftSide, rightSide, op, newCategory));
+        return adoptRefWillBeNoop(new CSSCalcBinaryOperation(leftSide, rightSide, op, newCategory));
     }
 
-    static PassRefPtr<CSSCalcExpressionNode> createSimplified(PassRefPtr<CSSCalcExpressionNode> leftSide, PassRefPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
+    static PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> createSimplified(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> leftSide, PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
     {
         CalculationCategory leftCategory = leftSide->category();
         CalculationCategory rightCategory = rightSide->category();
@@ -415,12 +395,12 @@
         return create(leftSide, rightSide, op);
     }
 
-    virtual bool isZero() const
+    virtual bool isZero() const OVERRIDE
     {
         return !doubleValue();
     }
 
-    virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const CSSToLengthConversionData& conversionData) const
+    virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const CSSToLengthConversionData& conversionData) const OVERRIDE
     {
         OwnPtr<CalcExpressionNode> left(m_leftSide->toCalcValue(conversionData));
         if (!left)
@@ -431,12 +411,12 @@
         return adoptPtr(new CalcExpressionBinaryOperation(left.release(), right.release(), m_operator));
     }
 
-    virtual double doubleValue() const
+    virtual double doubleValue() const OVERRIDE
     {
         return evaluate(m_leftSide->doubleValue(), m_rightSide->doubleValue());
     }
 
-    virtual double computeLengthPx(const CSSToLengthConversionData& conversionData) const
+    virtual double computeLengthPx(const CSSToLengthConversionData& conversionData) const OVERRIDE
     {
         const double leftValue = m_leftSide->computeLengthPx(conversionData);
         const double rightValue = m_rightSide->computeLengthPx(conversionData);
@@ -457,22 +437,12 @@
         return result.toString();
     }
 
-    virtual String customCSSText() const
+    virtual String customCSSText() const OVERRIDE
     {
         return buildCSSText(m_leftSide->customCSSText(), m_rightSide->customCSSText(), m_operator);
     }
 
-    virtual String serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-    {
-        return buildCSSText(m_leftSide->serializeResolvingVariables(variables), m_rightSide->serializeResolvingVariables(variables), m_operator);
-    }
-
-    virtual bool hasVariableReference() const
-    {
-        return m_leftSide->hasVariableReference() || m_rightSide->hasVariableReference();
-    }
-
-    virtual bool equals(const CSSCalcExpressionNode& exp) const
+    virtual bool equals(const CSSCalcExpressionNode& exp) const OVERRIDE
     {
         if (type() != exp.type())
             return false;
@@ -483,9 +453,9 @@
             && m_operator == other.m_operator;
     }
 
-    virtual Type type() const { return CssCalcBinaryOperation; }
+    virtual Type type() const OVERRIDE { return CssCalcBinaryOperation; }
 
-    virtual CSSPrimitiveValue::UnitTypes primitiveType() const
+    virtual CSSPrimitiveValue::UnitTypes primitiveType() const OVERRIDE
     {
         switch (m_category) {
         case CalcNumber:
@@ -504,8 +474,6 @@
                 return leftType;
             return CSSPrimitiveValue::CSS_UNKNOWN;
         }
-        case CalcVariable:
-            return CSSPrimitiveValue::CSS_VARIABLE_NAME;
         case CalcPercentLength:
         case CalcPercentNumber:
         case CalcOther:
@@ -515,9 +483,15 @@
         return CSSPrimitiveValue::CSS_UNKNOWN;
     }
 
+    virtual void trace(Visitor* visitor)
+    {
+        visitor->trace(m_leftSide);
+        visitor->trace(m_rightSide);
+        CSSCalcExpressionNode::trace(visitor);
+    }
 
 private:
-    CSSCalcBinaryOperation(PassRefPtr<CSSCalcExpressionNode> leftSide, PassRefPtr<CSSCalcExpressionNode> rightSide, CalcOperator op, CalculationCategory category)
+    CSSCalcBinaryOperation(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> leftSide, PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op, CalculationCategory category)
         : CSSCalcExpressionNode(category, isIntegerResult(leftSide.get(), rightSide.get(), op))
         , m_leftSide(leftSide)
         , m_rightSide(rightSide)
@@ -556,8 +530,8 @@
         return 0;
     }
 
-    const RefPtr<CSSCalcExpressionNode> m_leftSide;
-    const RefPtr<CSSCalcExpressionNode> m_rightSide;
+    const RefPtrWillBeMember<CSSCalcExpressionNode> m_leftSide;
+    const RefPtrWillBeMember<CSSCalcExpressionNode> m_rightSide;
     const CalcOperator m_operator;
 };
 
@@ -572,8 +546,9 @@
 }
 
 class CSSCalcExpressionNodeParser {
+    DISALLOW_ALLOCATION(); // Is only ever stack allocated.
 public:
-    PassRefPtr<CSSCalcExpressionNode> parseCalc(CSSParserValueList* tokens)
+    PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> parseCalc(CSSParserValueList* tokens)
     {
         unsigned index = 0;
         Value result;
@@ -586,7 +561,9 @@
 
 private:
     struct Value {
-        RefPtr<CSSCalcExpressionNode> value;
+        DISALLOW_ALLOCATION(); // Is only ever stack allocated.
+    public:
+        RefPtrWillBeRawPtr<CSSCalcExpressionNode> value;
     };
 
     char operatorValue(CSSParserValueList* tokens, unsigned index)
@@ -603,7 +580,7 @@
     bool parseValue(CSSParserValueList* tokens, unsigned* index, Value* result)
     {
         CSSParserValue* parserValue = tokens->valueAt(*index);
-        if (parserValue->unit == CSSParserValue::Operator || parserValue->unit == CSSParserValue::Function)
+        if (parserValue->unit == CSSParserValue::Operator)
             return false;
 
         RefPtr<CSSValue> value = parserValue->createCSSValue();
@@ -695,17 +672,17 @@
     }
 };
 
-PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(PassRefPtr<CSSPrimitiveValue> value, bool isInteger)
+PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> value, bool isInteger)
 {
     return CSSCalcPrimitiveValue::create(value, isInteger);
 }
 
-PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(PassRefPtr<CSSCalcExpressionNode> leftSide, PassRefPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
+PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> leftSide, PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
 {
     return CSSCalcBinaryOperation::create(leftSide, rightSide, op);
 }
 
-PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const CalcExpressionNode* node, float zoom)
+PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const CalcExpressionNode* node, float zoom)
 {
     switch (node->type()) {
     case CalcExpressionNodeNumber: {
@@ -742,14 +719,10 @@
     return 0;
 }
 
-PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const Length& length, float zoom)
+PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const Length& length, float zoom)
 {
     switch (length.type()) {
     case Percent:
-    case ViewportPercentageWidth:
-    case ViewportPercentageHeight:
-    case ViewportPercentageMin:
-    case ViewportPercentageMax:
     case Fixed:
         return createExpressionNode(CSSPrimitiveValue::create(length, zoom), length.value() == trunc(length.value()));
     case Calculated:
@@ -762,6 +735,8 @@
     case FillAvailable:
     case FitContent:
     case ExtendToZoom:
+    case DeviceWidth:
+    case DeviceHeight:
     case Undefined:
         ASSERT_NOT_REACHED();
         return 0;
@@ -770,21 +745,27 @@
     return 0;
 }
 
-PassRefPtr<CSSCalcValue> CSSCalcValue::create(CSSParserString name, CSSParserValueList* parserValueList, ValueRange range)
+PassRefPtrWillBeRawPtr<CSSCalcValue> CSSCalcValue::create(CSSParserString name, CSSParserValueList* parserValueList, ValueRange range)
 {
     CSSCalcExpressionNodeParser parser;
-    RefPtr<CSSCalcExpressionNode> expression;
+    RefPtrWillBeRawPtr<CSSCalcExpressionNode> expression;
 
     if (equalIgnoringCase(name, "calc(") || equalIgnoringCase(name, "-webkit-calc("))
         expression = parser.parseCalc(parserValueList);
     // FIXME calc (http://webkit.org/b/16662) Add parsing for min and max here
 
-    return expression ? adoptRef(new CSSCalcValue(expression, range)) : 0;
+    return expression ? adoptRefCountedWillBeRefCountedGarbageCollected(new CSSCalcValue(expression, range)) : 0;
 }
 
-PassRefPtr<CSSCalcValue> CSSCalcValue::create(PassRefPtr<CSSCalcExpressionNode> expression, ValueRange range)
+PassRefPtrWillBeRawPtr<CSSCalcValue> CSSCalcValue::create(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> expression, ValueRange range)
 {
-    return adoptRef(new CSSCalcValue(expression, range));
+    return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSCalcValue(expression, range));
+}
+
+void CSSCalcValue::traceAfterDispatch(Visitor* visitor)
+{
+    visitor->trace(m_expression);
+    CSSValue::traceAfterDispatch(visitor);
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSCalculationValue.h b/Source/core/css/CSSCalculationValue.h
index 6d58d60..836cffc 100644
--- a/Source/core/css/CSSCalculationValue.h
+++ b/Source/core/css/CSSCalculationValue.h
@@ -53,11 +53,11 @@
     CalcPercent,
     CalcPercentNumber,
     CalcPercentLength,
-    CalcVariable,
     CalcOther
 };
 
-class CSSCalcExpressionNode : public RefCounted<CSSCalcExpressionNode> {
+class CSSCalcExpressionNode : public RefCountedWillBeGarbageCollected<CSSCalcExpressionNode> {
+    DECLARE_GC_INFO;
 public:
     enum Type {
         CssCalcPrimitiveValue = 1,
@@ -70,8 +70,6 @@
     virtual double doubleValue() const = 0;
     virtual double computeLengthPx(const CSSToLengthConversionData&) const = 0;
     virtual String customCSSText() const = 0;
-    virtual String serializeResolvingVariables(const HashMap<AtomicString, String>&) const = 0;
-    virtual bool hasVariableReference() const = 0;
     virtual bool equals(const CSSCalcExpressionNode& other) const { return m_category == other.m_category && m_isInteger == other.m_isInteger; }
     virtual Type type() const = 0;
 
@@ -79,6 +77,8 @@
     virtual CSSPrimitiveValue::UnitTypes primitiveType() const = 0;
     bool isInteger() const { return m_isInteger; }
 
+    virtual void trace(Visitor*) { }
+
 protected:
     CSSCalcExpressionNode(CalculationCategory category, bool isInteger)
         : m_category(category)
@@ -92,14 +92,14 @@
 
 class CSSCalcValue : public CSSValue {
 public:
-    static PassRefPtr<CSSCalcValue> create(CSSParserString name, CSSParserValueList*, ValueRange);
-    static PassRefPtr<CSSCalcValue> create(PassRefPtr<CSSCalcExpressionNode>, ValueRange = ValueRangeAll);
-    static PassRefPtr<CSSCalcValue> create(const CalculationValue* value, float zoom) { return adoptRef(new CSSCalcValue(value, zoom)); }
+    static PassRefPtrWillBeRawPtr<CSSCalcValue> create(CSSParserString name, CSSParserValueList*, ValueRange);
+    static PassRefPtrWillBeRawPtr<CSSCalcValue> create(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode>, ValueRange = ValueRangeAll);
+    static PassRefPtrWillBeRawPtr<CSSCalcValue> create(const CalculationValue* value, float zoom) { return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSCalcValue(value, zoom)); }
 
-    static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(PassRefPtr<CSSPrimitiveValue>, bool isInteger = false);
-    static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(PassRefPtr<CSSCalcExpressionNode>, PassRefPtr<CSSCalcExpressionNode>, CalcOperator);
-    static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(const CalcExpressionNode*, float zoom);
-    static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(const Length&, float zoom);
+    static PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> createExpressionNode(PassRefPtrWillBeRawPtr<CSSPrimitiveValue>, bool isInteger = false);
+    static PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> createExpressionNode(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode>, PassRefPtrWillBeRawPtr<CSSCalcExpressionNode>, CalcOperator);
+    static PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> createExpressionNode(const CalcExpressionNode*, float zoom);
+    static PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> createExpressionNode(const Length&, float zoom);
 
     PassRefPtr<CalculationValue> toCalcValue(const CSSToLengthConversionData& conversionData) const
     {
@@ -115,11 +115,11 @@
 
     String customCSSText() const;
     bool equals(const CSSCalcValue&) const;
-    String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
-    bool hasVariableReference() const;
+
+    void traceAfterDispatch(Visitor*);
 
 private:
-    CSSCalcValue(PassRefPtr<CSSCalcExpressionNode> expression, ValueRange range)
+    CSSCalcValue(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> expression, ValueRange range)
         : CSSValue(CalculationClass)
         , m_expression(expression)
         , m_nonNegative(range == ValueRangeNonNegative)
@@ -134,7 +134,7 @@
 
     double clampToPermittedRange(double) const;
 
-    const RefPtr<CSSCalcExpressionNode> m_expression;
+    const RefPtrWillBeMember<CSSCalcExpressionNode> m_expression;
     const bool m_nonNegative;
 };
 
diff --git a/Source/core/css/CSSCalculationValueTest.cpp b/Source/core/css/CSSCalculationValueTest.cpp
index 5787552..31a5960 100644
--- a/Source/core/css/CSSCalculationValueTest.cpp
+++ b/Source/core/css/CSSCalculationValueTest.cpp
@@ -42,20 +42,20 @@
 
 namespace {
 
-void testExpression(PassRefPtr<CSSCalcExpressionNode> expression, const RenderStyle* style)
+void testExpression(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> expression, const RenderStyle* style)
 {
     EXPECT_TRUE(
         expression->equals(
             *CSSCalcValue::createExpressionNode(
-                expression->toCalcValue(CSSToLengthConversionData(style, style)).get(),
+                expression->toCalcValue(CSSToLengthConversionData(style, style, 0)).get(),
                 style->effectiveZoom()).get()));
 }
 
 TEST(CSSCalculationValue, CreateExpressionNodeFromLength)
 {
     RefPtr<RenderStyle> style = RenderStyle::create();
-    RefPtr<CSSCalcExpressionNode> expected;
-    RefPtr<CSSCalcExpressionNode> actual;
+    RefPtrWillBeRawPtr<CSSCalcExpressionNode> expected;
+    RefPtrWillBeRawPtr<CSSCalcExpressionNode> actual;
 
     expected = CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_PX), true);
     actual = CSSCalcValue::createExpressionNode(Length(10, WebCore::Fixed), style->effectiveZoom());
@@ -109,7 +109,7 @@
 
 TEST(CSSCalculationValue, CreateExpressionNodeFromLengthFromExpressionNode)
 {
-    RefPtr<CSSCalcExpressionNode> expression;
+    RefPtrWillBeRawPtr<CSSCalcExpressionNode> expression;
     RefPtr<RenderStyle> style = RenderStyle::createDefaultStyle();
     style->setEffectiveZoom(5);
 
diff --git a/Source/core/css/CSSCanvasValue.h b/Source/core/css/CSSCanvasValue.h
index bb2325f..df13d9d 100644
--- a/Source/core/css/CSSCanvasValue.h
+++ b/Source/core/css/CSSCanvasValue.h
@@ -35,7 +35,10 @@
 
 class CSSCanvasValue : public CSSImageGeneratorValue {
 public:
-    static PassRefPtr<CSSCanvasValue> create(const String& name) { return adoptRef(new CSSCanvasValue(name)); }
+    static PassRefPtrWillBeRawPtr<CSSCanvasValue> create(const String& name)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSCanvasValue(name));
+    }
     ~CSSCanvasValue();
 
     String customCSSText() const;
@@ -49,6 +52,8 @@
 
     bool equals(const CSSCanvasValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSImageGeneratorValue::traceAfterDispatch(visitor); }
+
 private:
     explicit CSSCanvasValue(const String& name)
         : CSSImageGeneratorValue(CanvasClass)
@@ -60,19 +65,19 @@
 
     // NOTE: We put the CanvasObserver in a member instead of inheriting from it
     // to avoid adding a vptr to CSSCanvasValue.
-    class CanvasObserverProxy : public CanvasObserver {
+    class CanvasObserverProxy FINAL : public CanvasObserver {
     public:
         CanvasObserverProxy(CSSCanvasValue* ownerValue) : m_ownerValue(ownerValue) { }
         virtual ~CanvasObserverProxy() { }
-        virtual void canvasChanged(HTMLCanvasElement* canvas, const FloatRect& changedRect)
+        virtual void canvasChanged(HTMLCanvasElement* canvas, const FloatRect& changedRect) OVERRIDE
         {
             m_ownerValue->canvasChanged(canvas, changedRect);
         }
-        virtual void canvasResized(HTMLCanvasElement* canvas)
+        virtual void canvasResized(HTMLCanvasElement* canvas) OVERRIDE
         {
             m_ownerValue->canvasResized(canvas);
         }
-        virtual void canvasDestroyed(HTMLCanvasElement* canvas)
+        virtual void canvasDestroyed(HTMLCanvasElement* canvas) OVERRIDE
         {
             m_ownerValue->canvasDestroyed(canvas);
         }
diff --git a/Source/core/css/CSSCharsetRule.h b/Source/core/css/CSSCharsetRule.h
index 26ae5fd..ee91bd3 100644
--- a/Source/core/css/CSSCharsetRule.h
+++ b/Source/core/css/CSSCharsetRule.h
@@ -28,7 +28,7 @@
 
 class ExceptionState;
 
-class CSSCharsetRule : public CSSRule {
+class CSSCharsetRule FINAL : public CSSRule {
 public:
     static PassRefPtr<CSSCharsetRule> create(CSSStyleSheet* parent, const String& encoding)
     {
diff --git a/Source/core/css/CSSComputedStyleDeclaration.cpp b/Source/core/css/CSSComputedStyleDeclaration.cpp
index b359b28..d6912a5 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -39,10 +39,9 @@
 #include "core/css/CSSFontValue.h"
 #include "core/css/CSSFunctionValue.h"
 #include "core/css/CSSGridLineNamesValue.h"
-#include "core/css/CSSGridTemplateValue.h"
+#include "core/css/CSSGridTemplateAreasValue.h"
 #include "core/css/CSSLineBoxContainValue.h"
-#include "core/css/CSSMixFunctionValue.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/CSSReflectValue.h"
@@ -54,16 +53,14 @@
 #include "core/css/CSSValuePool.h"
 #include "core/css/Pair.h"
 #include "core/css/Rect.h"
+#include "core/css/RuntimeCSSEnabled.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/PseudoElement.h"
-#include "core/page/RuntimeCSSEnabled.h"
-#include "core/frame/animation/AnimationController.h"
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderGrid.h"
-#include "core/rendering/RenderView.h"
 #include "core/rendering/style/ContentData.h"
 #include "core/rendering/style/CounterContent.h"
 #include "core/rendering/style/CursorList.h"
@@ -73,13 +70,6 @@
 #include "platform/fonts/FontFeatureSettings.h"
 #include "wtf/text/StringBuilder.h"
 
-#include "core/rendering/style/StyleCustomFilterProgram.h"
-#include "platform/graphics/filters/custom/CustomFilterArrayParameter.h"
-#include "platform/graphics/filters/custom/CustomFilterNumberParameter.h"
-#include "platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "platform/graphics/filters/custom/CustomFilterTransformParameter.h"
-
 namespace WebCore {
 
 // List of all properties we know how to compute, omitting shorthands.
@@ -142,10 +132,12 @@
     CSSPropertyFontSize,
     CSSPropertyFontStyle,
     CSSPropertyFontVariant,
+    CSSPropertyFontVariantLigatures,
     CSSPropertyFontWeight,
     CSSPropertyHeight,
     CSSPropertyImageRendering,
     CSSPropertyIsolation,
+    CSSPropertyJustifySelf,
     CSSPropertyLeft,
     CSSPropertyLetterSpacing,
     CSSPropertyLineHeight,
@@ -183,6 +175,7 @@
     CSSPropertyPosition,
     CSSPropertyResize,
     CSSPropertyRight,
+    CSSPropertyScrollBehavior,
     CSSPropertySpeak,
     CSSPropertyTableLayout,
     CSSPropertyTabSize,
@@ -271,24 +264,20 @@
     CSSPropertyFlexWrap,
     CSSPropertyJustifyContent,
     CSSPropertyWebkitFontSmoothing,
-    CSSPropertyWebkitFontVariantLigatures,
     CSSPropertyGridAutoColumns,
     CSSPropertyGridAutoFlow,
     CSSPropertyGridAutoRows,
     CSSPropertyGridColumnEnd,
     CSSPropertyGridColumnStart,
-    CSSPropertyGridDefinitionColumns,
-    CSSPropertyGridDefinitionRows,
+    CSSPropertyGridTemplateColumns,
+    CSSPropertyGridTemplateRows,
     CSSPropertyGridRowEnd,
     CSSPropertyGridRowStart,
     CSSPropertyWebkitHighlight,
     CSSPropertyWebkitHyphenateCharacter,
-    CSSPropertyWebkitLineAlign,
     CSSPropertyWebkitLineBoxContain,
     CSSPropertyWebkitLineBreak,
     CSSPropertyWebkitLineClamp,
-    CSSPropertyWebkitLineGrid,
-    CSSPropertyWebkitLineSnap,
     CSSPropertyWebkitLocale,
     CSSPropertyWebkitMarginBeforeCollapse,
     CSSPropertyWebkitMarginAfterCollapse,
@@ -337,12 +326,6 @@
     CSSPropertyWebkitUserModify,
     CSSPropertyWebkitUserSelect,
     CSSPropertyWebkitWritingMode,
-    CSSPropertyWebkitFlowInto,
-    CSSPropertyWebkitFlowFrom,
-    CSSPropertyWebkitRegionBreakAfter,
-    CSSPropertyWebkitRegionBreakBefore,
-    CSSPropertyWebkitRegionBreakInside,
-    CSSPropertyWebkitRegionFragment,
     CSSPropertyWebkitAppRegion,
     CSSPropertyWebkitWrapFlow,
     CSSPropertyWebkitWrapThrough,
@@ -410,13 +393,13 @@
     }
 }
 
-static PassRefPtr<CSSBorderImageSliceValue> valueForNinePieceImageSlice(const NinePieceImage& image)
+static PassRefPtrWillBeRawPtr<CSSBorderImageSliceValue> valueForNinePieceImageSlice(const NinePieceImage& image)
 {
     // Create the slices.
-    RefPtr<CSSPrimitiveValue> top;
-    RefPtr<CSSPrimitiveValue> right;
-    RefPtr<CSSPrimitiveValue> bottom;
-    RefPtr<CSSPrimitiveValue> left;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> top;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> right;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> bottom;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> left;
 
     if (image.imageSlices().top().isPercent())
         top = cssValuePool().createValue(image.imageSlices().top().value(), CSSPrimitiveValue::CSS_PERCENTAGE);
@@ -463,13 +446,13 @@
     return CSSBorderImageSliceValue::create(cssValuePool().createValue(quad.release()), image.fill());
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForNinePieceImageQuad(const BorderImageLengthBox& box, const RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> valueForNinePieceImageQuad(const BorderImageLengthBox& box, const RenderStyle& style)
 {
     // Create the slices.
-    RefPtr<CSSPrimitiveValue> top;
-    RefPtr<CSSPrimitiveValue> right;
-    RefPtr<CSSPrimitiveValue> bottom;
-    RefPtr<CSSPrimitiveValue> left;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> top;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> right;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> bottom;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> left;
 
     if (box.top().isNumber())
         top = cssValuePool().createValue(box.top().number(), CSSPrimitiveValue::CSS_NUMBER);
@@ -517,8 +500,8 @@
 
 static PassRefPtr<CSSValue> valueForNinePieceImageRepeat(const NinePieceImage& image)
 {
-    RefPtr<CSSPrimitiveValue> horizontalRepeat;
-    RefPtr<CSSPrimitiveValue> verticalRepeat;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> horizontalRepeat;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> verticalRepeat;
 
     horizontalRepeat = cssValuePool().createIdentifierValue(valueForRepeatRule(image.horizontalRule()));
     if (image.horizontalRule() == image.verticalRule())
@@ -539,7 +522,7 @@
         imageValue = image.image()->cssValue();
 
     // Create the image slice.
-    RefPtr<CSSBorderImageSliceValue> imageSlices = valueForNinePieceImageSlice(image);
+    RefPtrWillBeRawPtr<CSSBorderImageSliceValue> imageSlices = valueForNinePieceImageSlice(image);
 
     // Create the border area slices.
     RefPtr<CSSValue> borderSlices = valueForNinePieceImageQuad(image.borderSlices(), style);
@@ -553,17 +536,17 @@
     return createBorderImageValue(imageValue.release(), imageSlices.release(), borderSlices.release(), outset.release(), repeat.release());
 }
 
-inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedPixelValue(double value, const RenderStyle& style)
+inline static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> zoomAdjustedPixelValue(double value, const RenderStyle& style)
 {
     return cssValuePool().createValue(adjustFloatForAbsoluteZoom(value, style), CSSPrimitiveValue::CSS_PX);
 }
 
-inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedNumberValue(double value, const RenderStyle& style)
+inline static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> zoomAdjustedNumberValue(double value, const RenderStyle& style)
 {
     return cssValuePool().createValue(value / style.effectiveZoom(), CSSPrimitiveValue::CSS_NUMBER);
 }
 
-static PassRefPtr<CSSPrimitiveValue> zoomAdjustedPixelValueForLength(const Length& length, const RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> zoomAdjustedPixelValueForLength(const Length& length, const RenderStyle& style)
 {
     if (length.isFixed())
         return zoomAdjustedPixelValue(length.value(), style);
@@ -575,13 +558,13 @@
     if (!reflection)
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
-    RefPtr<CSSPrimitiveValue> offset;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> offset;
     if (reflection->offset().isPercent())
         offset = cssValuePool().createValue(reflection->offset().percent(), CSSPrimitiveValue::CSS_PERCENTAGE);
     else
         offset = zoomAdjustedPixelValue(reflection->offset().value(), style);
 
-    RefPtr<CSSPrimitiveValue> direction;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> direction;
     switch (reflection->direction()) {
     case ReflectionBelow:
         direction = cssValuePool().createIdentifierValue(CSSValueBelow);
@@ -600,18 +583,23 @@
     return CSSReflectValue::create(direction.release(), offset.release(), valueForNinePieceImage(reflection->mask(), style));
 }
 
-static PassRefPtr<CSSValueList> createPositionListForLayer(CSSPropertyID propertyID, const FillLayer* layer, const RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSValueList> createPositionListForLayer(CSSPropertyID propertyID, const FillLayer* layer, const RenderStyle& style)
 {
-    ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPosition || propertyID == CSSPropertyWebkitMaskPosition);
-    RefPtr<CSSValueList> positionList = CSSValueList::createSpaceSeparated();
-    positionList->append(cssValuePool().createValue(layer->backgroundXOrigin()));
+    RefPtrWillBeRawPtr<CSSValueList> positionList = CSSValueList::createSpaceSeparated();
+    if (layer->isBackgroundXOriginSet()) {
+        ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPosition || propertyID == CSSPropertyWebkitMaskPosition);
+        positionList->append(cssValuePool().createValue(layer->backgroundXOrigin()));
+    }
     positionList->append(zoomAdjustedPixelValueForLength(layer->xPosition(), style));
-    positionList->append(cssValuePool().createValue(layer->backgroundYOrigin()));
+    if (layer->isBackgroundYOriginSet()) {
+        ASSERT(propertyID == CSSPropertyBackgroundPosition || propertyID == CSSPropertyWebkitMaskPosition);
+        positionList->append(cssValuePool().createValue(layer->backgroundYOrigin()));
+    }
     positionList->append(zoomAdjustedPixelValueForLength(layer->yPosition(), style));
     return positionList.release();
 }
 
-static PassRefPtr<CSSValue> valueForPositionOffset(RenderStyle& style, CSSPropertyID propertyID, const RenderObject* renderer, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForPositionOffset(RenderStyle& style, CSSPropertyID propertyID, const RenderObject* renderer)
 {
     Length l;
     switch (propertyID) {
@@ -635,10 +623,8 @@
         LayoutUnit containingBlockSize = (propertyID == CSSPropertyLeft || propertyID == CSSPropertyRight) ?
             toRenderBox(renderer)->containingBlockLogicalWidthForContent() :
             toRenderBox(renderer)->containingBlockLogicalHeightForContent(ExcludeMarginBorderPadding);
-        return zoomAdjustedPixelValue(valueForLength(l, containingBlockSize, 0), style);
+        return zoomAdjustedPixelValue(valueForLength(l, containingBlockSize), style);
     }
-    if (l.isViewportPercentage())
-        return zoomAdjustedPixelValue(valueForLength(l, 0, renderView), style);
     if (l.isAuto()) {
         // FIXME: It's not enough to simply return "auto" values for one offset if the other side is defined.
         // In other words if left is auto and right is not auto, then left's computed value is negative right().
@@ -649,17 +635,15 @@
     return zoomAdjustedPixelValueForLength(l, style);
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(const RenderStyle& style, const Color& color) const
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(const RenderStyle& style, const StyleColor& color) const
 {
     // This function does NOT look at visited information, so that computed style doesn't expose that.
-    if (!color.isValid())
-        return cssValuePool().createColorValue(style.color().rgb());
-    return cssValuePool().createColorValue(color.rgb());
+    return cssValuePool().createColorValue(color.resolve(style.color()).rgb());
 }
 
-static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle& style)
 {
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     if (radius.width().type() == Percent)
         list->append(cssValuePool().createValue(radius.width().percent(), CSSPrimitiveValue::CSS_PERCENTAGE));
     else
@@ -673,15 +657,15 @@
 
 static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle& style)
 {
-    RefPtr<CSSValueList> list = valuesForBorderRadiusCorner(radius, style);
+    RefPtrWillBeRawPtr<CSSValueList> list = valuesForBorderRadiusCorner(radius, style);
     if (list->item(0)->equals(*list->item(1)))
         return list->item(0);
     return list.release();
 }
 
-static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle& style)
 {
-    RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
 
     bool showHorizontalBottomLeft = style.borderTopRightRadius().width() != style.borderBottomLeftRadius().width();
     bool showHorizontalBottomRight = showHorizontalBottomLeft || (style.borderBottomRightRadius().width() != style.borderTopLeftRadius().width());
@@ -691,12 +675,12 @@
     bool showVerticalBottomRight = showVerticalBottomLeft || (style.borderBottomRightRadius().height() != style.borderTopLeftRadius().height());
     bool showVerticalTopRight = showVerticalBottomRight || (style.borderTopRightRadius().height() != style.borderTopLeftRadius().height());
 
-    RefPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style.borderTopLeftRadius(), style);
-    RefPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style.borderTopRightRadius(), style);
-    RefPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style.borderBottomRightRadius(), style);
-    RefPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style.borderBottomLeftRadius(), style);
+    RefPtrWillBeRawPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style.borderTopLeftRadius(), style);
+    RefPtrWillBeRawPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style.borderTopRightRadius(), style);
+    RefPtrWillBeRawPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style.borderBottomRightRadius(), style);
+    RefPtrWillBeRawPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style.borderBottomLeftRadius(), style);
 
-    RefPtr<CSSValueList> horizontalRadii = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> horizontalRadii = CSSValueList::createSpaceSeparated();
     horizontalRadii->append(topLeftRadius->item(0));
     if (showHorizontalTopRight)
         horizontalRadii->append(topRightRadius->item(0));
@@ -707,7 +691,7 @@
 
     list->append(horizontalRadii.release());
 
-    RefPtr<CSSValueList> verticalRadii = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> verticalRadii = CSSValueList::createSpaceSeparated();
     verticalRadii->append(topLeftRadius->item(1));
     if (showVerticalTopRight)
         verticalRadii->append(topRightRadius->item(1));
@@ -731,9 +715,9 @@
     return box->style()->boxSizing() == BORDER_BOX ? box->borderBoxRect() : box->computedCSSContentBoxRect();
 }
 
-static PassRefPtr<CSSTransformValue> valueForMatrixTransform(const TransformationMatrix& transform, const RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSTransformValue> valueForMatrixTransform(const TransformationMatrix& transform, const RenderStyle& style)
 {
-    RefPtr<CSSTransformValue> transformValue;
+    RefPtrWillBeRawPtr<CSSTransformValue> transformValue;
     if (transform.isAffine()) {
         transformValue = CSSTransformValue::create(CSSTransformValue::MatrixTransformOperation);
 
@@ -783,65 +767,20 @@
     style.applyTransform(transform, box.size(), RenderStyle::ExcludeTransformOrigin);
 
     // FIXME: Need to print out individual functions (https://bugs.webkit.org/show_bug.cgi?id=23924)
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     list->append(valueForMatrixTransform(transform, style));
 
     return list.release();
 }
 
-static PassRefPtr<CSSValue> valueForCustomFilterArrayParameter(const CustomFilterArrayParameter* arrayParameter)
-{
-    RefPtr<CSSArrayFunctionValue> arrayParameterValue = CSSArrayFunctionValue::create();
-    for (unsigned i = 0, size = arrayParameter->size(); i < size; ++i)
-        arrayParameterValue->append(cssValuePool().createValue(arrayParameter->valueAt(i), CSSPrimitiveValue::CSS_NUMBER));
-    return arrayParameterValue.release();
-}
-
-static PassRefPtr<CSSValue> valueForCustomFilterNumberParameter(const CustomFilterNumberParameter* numberParameter)
-{
-    RefPtr<CSSValueList> numberParameterValue = CSSValueList::createSpaceSeparated();
-    for (unsigned i = 0; i < numberParameter->size(); ++i)
-        numberParameterValue->append(cssValuePool().createValue(numberParameter->valueAt(i), CSSPrimitiveValue::CSS_NUMBER));
-    return numberParameterValue.release();
-}
-
-static PassRefPtr<CSSValue> valueForCustomFilterTransformParameter(const RenderObject* renderer, const RenderStyle& style, const CustomFilterTransformParameter* transformParameter)
-{
-    IntSize size;
-    if (renderer && renderer->isBox())
-        size = pixelSnappedIntRect(toRenderBox(renderer)->borderBoxRect()).size();
-
-    TransformationMatrix transform;
-    transformParameter->applyTransform(transform, size);
-    // FIXME: Need to print out individual functions (https://bugs.webkit.org/show_bug.cgi?id=23924)
-    return valueForMatrixTransform(transform, style);
-}
-
-static PassRefPtr<CSSValue> valueForCustomFilterParameter(const RenderObject* renderer, const RenderStyle& style, const CustomFilterParameter* parameter)
-{
-    // FIXME: Add here computed style for the other types: boolean, transform, matrix, texture.
-    ASSERT(parameter);
-    switch (parameter->parameterType()) {
-    case CustomFilterParameter::Array:
-        return valueForCustomFilterArrayParameter(static_cast<const CustomFilterArrayParameter*>(parameter));
-    case CustomFilterParameter::Number:
-        return valueForCustomFilterNumberParameter(static_cast<const CustomFilterNumberParameter*>(parameter));
-    case CustomFilterParameter::Transform:
-        return valueForCustomFilterTransformParameter(renderer, style, static_cast<const CustomFilterTransformParameter*>(parameter));
-    }
-
-    ASSERT_NOT_REACHED();
-    return 0;
-}
-
 PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForFilter(const RenderObject* renderer, const RenderStyle& style) const
 {
     if (style.filter().operations().isEmpty())
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
 
-    RefPtr<CSSFilterValue> filterValue;
+    RefPtrWillBeRawPtr<CSSFilterValue> filterValue;
 
     Vector<RefPtr<FilterOperation> >::const_iterator end = style.filter().operations().end();
     for (Vector<RefPtr<FilterOperation> >::const_iterator it = style.filter().operations().begin(); it != end; ++it) {
@@ -895,68 +834,6 @@
             filterValue->append(valueForShadowData(shadow, style, false));
             break;
         }
-        case FilterOperation::VALIDATED_CUSTOM:
-            // ValidatedCustomFilterOperation is not supposed to end up in the RenderStyle.
-            ASSERT_NOT_REACHED();
-            break;
-        case FilterOperation::CUSTOM: {
-            CustomFilterOperation* customOperation = toCustomFilterOperation(filterOperation);
-            filterValue = CSSFilterValue::create(CSSFilterValue::CustomFilterOperation);
-
-            // The output should be verbose, even if the values are the default ones.
-
-            ASSERT(customOperation->program());
-            StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customOperation->program());
-
-            RefPtr<CSSValueList> shadersList = CSSValueList::createSpaceSeparated();
-            if (program->vertexShader())
-                shadersList->append(program->vertexShader()->cssValue());
-            else
-                shadersList->append(cssValuePool().createIdentifierValue(CSSValueNone));
-
-            const CustomFilterProgramMixSettings mixSettings = program->mixSettings();
-            if (program->fragmentShader()) {
-                if (program->programType() == ProgramTypeBlendsElementTexture) {
-                    RefPtr<CSSMixFunctionValue> mixFunction = CSSMixFunctionValue::create();
-                    mixFunction->append(program->fragmentShader()->cssValue());
-                    mixFunction->append(cssValuePool().createValue(mixSettings.blendMode));
-                    mixFunction->append(cssValuePool().createValue(mixSettings.compositeOperator));
-                    shadersList->append(mixFunction.release());
-                } else
-                    shadersList->append(program->fragmentShader()->cssValue());
-            }
-            else
-                shadersList->append(cssValuePool().createIdentifierValue(CSSValueNone));
-
-            filterValue->append(shadersList.release());
-
-            RefPtr<CSSValueList> meshParameters = CSSValueList::createSpaceSeparated();
-            meshParameters->append(cssValuePool().createValue(customOperation->meshColumns(), CSSPrimitiveValue::CSS_NUMBER));
-            meshParameters->append(cssValuePool().createValue(customOperation->meshRows(), CSSPrimitiveValue::CSS_NUMBER));
-
-            // FIXME: The specification doesn't have any "attached" identifier. Should we add one?
-            // https://bugs.webkit.org/show_bug.cgi?id=72700
-            if (customOperation->meshType() == MeshTypeDetached)
-                meshParameters->append(cssValuePool().createIdentifierValue(CSSValueDetached));
-
-            filterValue->append(meshParameters.release());
-
-            const CustomFilterParameterList& parameters = customOperation->parameters();
-            size_t parametersSize = parameters.size();
-            if (!parametersSize)
-                break;
-            RefPtr<CSSValueList> parametersCSSValue = CSSValueList::createCommaSeparated();
-            for (size_t i = 0; i < parametersSize; ++i) {
-                const CustomFilterParameter* parameter = parameters.at(i).get();
-                RefPtr<CSSValueList> parameterCSSNameAndValue = CSSValueList::createSpaceSeparated();
-                parameterCSSNameAndValue->append(cssValuePool().createValue(parameter->name(), CSSPrimitiveValue::CSS_STRING));
-                parameterCSSNameAndValue->append(valueForCustomFilterParameter(renderer, style, parameter));
-                parametersCSSValue->append(parameterCSSNameAndValue.release());
-            }
-
-            filterValue->append(parametersCSSValue.release());
-            break;
-        }
         default:
             filterValue = CSSFilterValue::create(CSSFilterValue::UnknownFilterOperation);
             break;
@@ -967,7 +844,7 @@
     return list.release();
 }
 
-static PassRefPtr<CSSValue> specifiedValueForGridTrackBreadth(const GridLength& trackBreadth, const RenderStyle& style, RenderView* renderView)
+static PassRefPtr<CSSValue> specifiedValueForGridTrackBreadth(const GridLength& trackBreadth, const RenderStyle& style)
 {
     if (!trackBreadth.isLength())
         return cssValuePool().createValue(trackBreadth.flex(), CSSPrimitiveValue::CSS_FR);
@@ -975,20 +852,18 @@
     const Length& trackBreadthLength = trackBreadth.length();
     if (trackBreadthLength.isAuto())
         return cssValuePool().createIdentifierValue(CSSValueAuto);
-    if (trackBreadthLength.isViewportPercentage())
-        return zoomAdjustedPixelValue(valueForLength(trackBreadthLength, 0, renderView), style);
     return zoomAdjustedPixelValueForLength(trackBreadthLength, style);
 }
 
-static PassRefPtr<CSSValue> specifiedValueForGridTrackSize(const GridTrackSize& trackSize, const RenderStyle& style, RenderView* renderView)
+static PassRefPtr<CSSValue> specifiedValueForGridTrackSize(const GridTrackSize& trackSize, const RenderStyle& style)
 {
     switch (trackSize.type()) {
     case LengthTrackSizing:
-        return specifiedValueForGridTrackBreadth(trackSize.length(), style, renderView);
+        return specifiedValueForGridTrackBreadth(trackSize.length(), style);
     case MinMaxTrackSizing:
-        RefPtr<CSSValueList> minMaxTrackBreadths = CSSValueList::createCommaSeparated();
-        minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.minTrackBreadth(), style, renderView));
-        minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.maxTrackBreadth(), style, renderView));
+        RefPtrWillBeRawPtr<CSSValueList> minMaxTrackBreadths = CSSValueList::createCommaSeparated();
+        minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.minTrackBreadth(), style));
+        minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.maxTrackBreadth(), style));
         return CSSFunctionValue::create("minmax(", minMaxTrackBreadths);
     }
     ASSERT_NOT_REACHED();
@@ -1001,15 +876,15 @@
     if (namedGridLines.isEmpty())
         return;
 
-    RefPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
+    RefPtrWillBeRawPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
     for (size_t j = 0; j < namedGridLines.size(); ++j)
         lineNames->append(cssValuePool().createValue(namedGridLines[j], CSSPrimitiveValue::CSS_STRING));
     list.append(lineNames.release());
 }
 
-static PassRefPtr<CSSValue> valueForGridTrackList(GridTrackSizingDirection direction, RenderObject* renderer, const RenderStyle& style, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForGridTrackList(GridTrackSizingDirection direction, RenderObject* renderer, const RenderStyle& style)
 {
-    const Vector<GridTrackSize>& trackSizes = direction == ForColumns ? style.gridDefinitionColumns() : style.gridDefinitionRows();
+    const Vector<GridTrackSize>& trackSizes = direction == ForColumns ? style.gridTemplateColumns() : style.gridTemplateRows();
     const OrderedNamedGridLines& orderedNamedGridLines = direction == ForColumns ? style.orderedNamedGridColumnLines() : style.orderedNamedGridRowLines();
 
     // Handle the 'none' case here.
@@ -1018,7 +893,7 @@
         return cssValuePool().createIdentifierValue(CSSValueNone);
     }
 
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     if (renderer && renderer->isRenderGrid()) {
         const Vector<LayoutUnit>& trackPositions = direction == ForColumns ? toRenderGrid(renderer)->columnPositions() : toRenderGrid(renderer)->rowPositions();
         // There are at least #tracks + 1 grid lines (trackPositions). Apart from that, the grid container can generate implicit grid tracks,
@@ -1032,7 +907,7 @@
     } else {
         for (size_t i = 0; i < trackSizes.size(); ++i) {
             addValuesForNamedGridLinesAtIndex(orderedNamedGridLines, i, *list);
-            list->append(specifiedValueForGridTrackSize(trackSizes[i], style, renderView));
+            list->append(specifiedValueForGridTrackSize(trackSizes[i], style));
         }
     }
     // Those are the trailing <string>* allowed in the syntax.
@@ -1048,7 +923,7 @@
     if (position.isNamedGridArea())
         return cssValuePool().createValue(position.namedGridLine(), CSSPrimitiveValue::CSS_STRING);
 
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     if (position.isSpan()) {
         list->append(cssValuePool().createIdentifierValue(CSSValueSpan));
         list->append(cssValuePool().createValue(position.spanPosition(), CSSPrimitiveValue::CSS_NUMBER));
@@ -1072,7 +947,7 @@
 }
 static PassRefPtr<CSSValue> valueForTransitionProperty(const CSSAnimationDataList* animList)
 {
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     if (animList) {
         for (size_t i = 0; i < animList->size(); ++i)
             list->append(createTransitionPropertyValue(animList->animation(i)));
@@ -1083,7 +958,7 @@
 
 static PassRefPtr<CSSValue> valueForAnimationDelay(const CSSAnimationDataList* animList)
 {
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     if (animList) {
         for (size_t i = 0; i < animList->size(); ++i)
             list->append(cssValuePool().createValue(animList->animation(i)->delay(), CSSPrimitiveValue::CSS_S));
@@ -1096,7 +971,7 @@
 
 static PassRefPtr<CSSValue> valueForAnimationDuration(const CSSAnimationDataList* animList)
 {
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     if (animList) {
         for (size_t i = 0; i < animList->size(); ++i)
             list->append(cssValuePool().createValue(animList->animation(i)->duration(), CSSPrimitiveValue::CSS_S));
@@ -1164,7 +1039,7 @@
 
 static PassRefPtr<CSSValue> valueForAnimationTimingFunction(const CSSAnimationDataList* animList)
 {
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     if (animList) {
         for (size_t i = 0; i < animList->size(); ++i)
             list->append(createTimingFunctionValue(animList->animation(i)->timingFunction()));
@@ -1302,12 +1177,12 @@
 
 PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadowData(const ShadowData& shadow, const RenderStyle& style, bool useSpread) const
 {
-    RefPtr<CSSPrimitiveValue> x = zoomAdjustedPixelValue(shadow.x(), style);
-    RefPtr<CSSPrimitiveValue> y = zoomAdjustedPixelValue(shadow.y(), style);
-    RefPtr<CSSPrimitiveValue> blur = zoomAdjustedPixelValue(shadow.blur(), style);
-    RefPtr<CSSPrimitiveValue> spread = useSpread ? zoomAdjustedPixelValue(shadow.spread(), style) : PassRefPtr<CSSPrimitiveValue>();
-    RefPtr<CSSPrimitiveValue> shadowStyle = shadow.style() == Normal ? PassRefPtr<CSSPrimitiveValue>() : cssValuePool().createIdentifierValue(CSSValueInset);
-    RefPtr<CSSPrimitiveValue> color = currentColorOrValidColor(style, shadow.color());
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> x = zoomAdjustedPixelValue(shadow.x(), style);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> y = zoomAdjustedPixelValue(shadow.y(), style);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> blur = zoomAdjustedPixelValue(shadow.blur(), style);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> spread = useSpread ? zoomAdjustedPixelValue(shadow.spread(), style) : PassRefPtrWillBeRawPtr<CSSPrimitiveValue>();
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> shadowStyle = shadow.style() == Normal ? PassRefPtrWillBeRawPtr<CSSPrimitiveValue>() : cssValuePool().createIdentifierValue(CSSValueInset);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> color = currentColorOrValidColor(style, shadow.color());
     return CSSShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), shadowStyle.release(), color.release());
 }
 
@@ -1316,7 +1191,7 @@
     if (!shadowList)
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     size_t shadowCount = shadowList->shadows().size();
     for (size_t i = 0; i < shadowCount; ++i)
         list->append(valueForShadowData(shadowList->shadows()[i], style, useSpread));
@@ -1345,7 +1220,7 @@
     return CSSValueInvalid;
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForFamily(const AtomicString& family)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> valueForFamily(const AtomicString& family)
 {
     if (CSSValueID familyIdentifier = identifierForFamily(family))
         return cssValuePool().createIdentifierValue(familyIdentifier);
@@ -1355,7 +1230,7 @@
 static PassRefPtr<CSSValue> renderTextDecorationFlagsToCSSValue(int textDecoration)
 {
     // Blink value is ignored.
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     if (textDecoration & TextDecorationUnderline)
         list->append(cssValuePool().createIdentifierValue(CSSValueUnderline));
     if (textDecoration & TextDecorationOverline)
@@ -1398,7 +1273,7 @@
     if (xRepeat == NoRepeatFill && yRepeat == RepeatFill)
         return cssValuePool().createIdentifierValue(CSSValueRepeatY);
 
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     list->append(cssValuePool().createValue(xRepeat));
     list->append(cssValuePool().createValue(yRepeat));
     return list.release();
@@ -1429,7 +1304,7 @@
     if (fillSize.size.height().isAuto())
         return zoomAdjustedPixelValueForLength(fillSize.size.width(), style);
 
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     list->append(zoomAdjustedPixelValueForLength(fillSize.size.width(), style));
     list->append(zoomAdjustedPixelValueForLength(fillSize.size.height(), style));
     return list.release();
@@ -1437,7 +1312,7 @@
 
 static PassRefPtr<CSSValue> valueForContentData(const RenderStyle& style)
 {
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     for (const ContentData* contentData = style.contentData(); contentData; contentData = contentData->next()) {
         if (contentData->isCounter()) {
             const CounterContent* counter = static_cast<const CounterContentData*>(contentData)->counter();
@@ -1450,8 +1325,6 @@
         } else if (contentData->isText())
             list->append(cssValuePool().createValue(static_cast<const TextContentData*>(contentData)->text(), CSSPrimitiveValue::CSS_STRING));
     }
-    if (style.hasFlowFrom())
-        list->append(cssValuePool().createValue(style.regionThread(), CSSPrimitiveValue::CSS_STRING));
     return list.release();
 }
 
@@ -1461,7 +1334,7 @@
     if (!map)
         return 0;
 
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     for (CounterDirectiveMap::const_iterator it = map->begin(); it != map->end(); ++it) {
         list->append(cssValuePool().createValue(it->key, CSSPrimitiveValue::CSS_STRING));
         short number = propertyID == CSSPropertyCounterIncrement ? it->value.incrementValue() : it->value.resetValue();
@@ -1479,44 +1352,44 @@
     WTF_LOG_ERROR("WebKit does not yet implement getComputedStyle for '%s'.", getPropertyName(propertyID));
 }
 
-static PassRefPtr<CSSValueList> valueForFontFamily(RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSValueList> valueForFontFamily(RenderStyle& style)
 {
     const FontFamily& firstFamily = style.fontDescription().family();
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     for (const FontFamily* family = &firstFamily; family; family = family->next())
         list->append(valueForFamily(family->family()));
     return list.release();
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForLineHeight(RenderStyle& style, RenderView* renderView)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> valueForLineHeight(RenderStyle& style)
 {
     Length length = style.lineHeight();
     if (length.isNegative())
         return cssValuePool().createIdentifierValue(CSSValueNormal);
 
-    return zoomAdjustedPixelValue(floatValueForLength(length, style.fontDescription().specifiedSize(), renderView), style);
+    return zoomAdjustedPixelValue(floatValueForLength(length, style.fontDescription().specifiedSize()), style);
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForFontSize(RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> valueForFontSize(RenderStyle& style)
 {
     return zoomAdjustedPixelValue(style.fontDescription().computedPixelSize(), style);
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForFontStyle(RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> valueForFontStyle(RenderStyle& style)
 {
     if (style.fontDescription().italic())
         return cssValuePool().createIdentifierValue(CSSValueItalic);
     return cssValuePool().createIdentifierValue(CSSValueNormal);
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForFontVariant(RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> valueForFontVariant(RenderStyle& style)
 {
     if (style.fontDescription().smallCaps())
         return cssValuePool().createIdentifierValue(CSSValueSmallCaps);
     return cssValuePool().createIdentifierValue(CSSValueNormal);
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueForFontWeight(RenderStyle& style)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> valueForFontWeight(RenderStyle& style)
 {
     switch (style.fontDescription().weight()) {
     case FontWeight100:
@@ -1542,6 +1415,24 @@
     return cssValuePool().createIdentifierValue(CSSValueNormal);
 }
 
+static PassRefPtr<CSSValue> touchActionFlagsToCSSValue(TouchAction touchAction)
+{
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    if (touchAction == TouchActionAuto)
+        list->append(cssValuePool().createIdentifierValue(CSSValueAuto));
+    if (touchAction & TouchActionNone) {
+        ASSERT(touchAction == TouchActionNone);
+        list->append(cssValuePool().createIdentifierValue(CSSValueNone));
+    }
+    if (touchAction & TouchActionPanX)
+        list->append(cssValuePool().createIdentifierValue(CSSValuePanX));
+    if (touchAction & TouchActionPanY)
+        list->append(cssValuePool().createIdentifierValue(CSSValuePanY));
+
+    ASSERT(list->length());
+    return list.release();
+}
+
 static bool isLayoutDependent(CSSPropertyID propertyID, PassRefPtr<RenderStyle> style, RenderObject* renderer)
 {
     // Some properties only depend on layout in certain conditions which
@@ -1551,8 +1442,8 @@
     // FIXME: Some of these cases could be narrowed down or optimized better.
     switch (propertyID) {
     case CSSPropertyBottom:
-    case CSSPropertyGridDefinitionColumns:
-    case CSSPropertyGridDefinitionRows:
+    case CSSPropertyGridTemplateColumns:
+    case CSSPropertyGridTemplateRows:
     case CSSPropertyHeight:
     case CSSPropertyLeft:
     case CSSPropertyRight:
@@ -1592,16 +1483,6 @@
 {
     Node* styledNode = this->styledNode();
     ASSERT(styledNode);
-    RenderObject* renderer = styledNode->renderer();
-    if (renderer && renderer->compositingState() == PaintsIntoOwnBacking
-        && !RuntimeEnabledFeatures::webAnimationsCSSEnabled() && AnimationController::supportsAcceleratedAnimationOfProperty(propertyID)) {
-        AnimationUpdateBlock animationUpdateBlock(renderer->animation());
-        if (m_pseudoElementSpecifier && !styledNode->isPseudoElement()) {
-            // FIXME: This cached pseudo style will only exist if the animation has been run at least once.
-            return renderer->animation().getAnimatedStyleForRenderer(renderer)->getCachedPseudoStyle(m_pseudoElementSpecifier);
-        }
-        return renderer->animation().getAnimatedStyleForRenderer(renderer);
-    }
     return styledNode->computedStyle(styledNode->isPseudoElement() ? NOPSEUDO : m_pseudoElementSpecifier);
 }
 
@@ -1616,6 +1497,15 @@
     return m_node.get();
 }
 
+static PassRefPtrWillBeRawPtr<CSSValueList> valueForItemPositionWithOverflowAlignment(ItemPosition itemPosition, OverflowAlignment overflowAlignment)
+{
+    RefPtrWillBeRawPtr<CSSValueList> result = CSSValueList::createSpaceSeparated();
+    result->append(CSSPrimitiveValue::create(itemPosition));
+    if (itemPosition >= ItemPositionCenter && overflowAlignment != OverflowAlignmentDefault)
+        result->append(CSSPrimitiveValue::create(overflowAlignment));
+    return result.release();
+}
+
 PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropertyID propertyID, EUpdateLayout updateLayout) const
 {
     Node* styledNode = this->styledNode();
@@ -1627,8 +1517,9 @@
     if (updateLayout) {
         Document& document = styledNode->document();
 
-        // If a compositor animation is running we may need to service animations
-        // in order to generate an up to date value.
+        // If a compositor animation is running or animations have been updated
+        // via the api we may need to service animations in order to generate
+        // an up to date value.
         DocumentAnimations::serviceBeforeGetComputedStyle(*styledNode, propertyID);
 
         document.updateStyleForNodeIfNeeded(styledNode);
@@ -1642,8 +1533,7 @@
 
         bool forceFullLayout = isLayoutDependent(propertyID, style, renderer)
             || styledNode->isInShadowTree()
-            || (document.ownerElement() && document.ensureStyleResolver().hasViewportDependentMediaQueries())
-            || document.seamlessParentIFrame();
+            || (document.ownerElement() && document.ensureStyleResolver().hasViewportDependentMediaQueries());
 
         if (forceFullLayout) {
             document.updateLayoutIgnorePendingStylesheets();
@@ -1662,11 +1552,10 @@
 
     switch (propertyID) {
         case CSSPropertyInvalid:
-        case CSSPropertyVariable:
             break;
 
         case CSSPropertyBackgroundColor:
-            return cssValuePool().createColorValue(m_allowVisitedStyle? style->visitedDependentColor(CSSPropertyBackgroundColor).rgb() : style->backgroundColor().rgb());
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBackgroundColor).rgb()) : currentColorOrValidColor(*style, style->backgroundColor());
         case CSSPropertyBackgroundImage:
         case CSSPropertyWebkitMaskImage: {
             const FillLayer* layers = propertyID == CSSPropertyWebkitMaskImage ? style->maskLayers() : style->backgroundLayers();
@@ -1680,7 +1569,7 @@
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             }
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next()) {
                 if (currLayer->image())
                     list->append(currLayer->image()->cssValue());
@@ -1696,7 +1585,7 @@
             if (!layers->next())
                 return valueForFillSize(layers->size(), *style);
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
                 list->append(valueForFillSize(currLayer->size(), *style));
 
@@ -1708,7 +1597,7 @@
             if (!layers->next())
                 return valueForFillRepeat(layers->repeatX(), layers->repeatY());
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
                 list->append(valueForFillRepeat(currLayer->repeatX(), currLayer->repeatY()));
 
@@ -1723,7 +1612,7 @@
             if (!layers->next())
                 return valueForFillSourceType(layers->maskSourceType());
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
                 list->append(valueForFillSourceType(currLayer->maskSourceType()));
 
@@ -1735,7 +1624,7 @@
             if (!layers->next())
                 return cssValuePool().createValue(layers->composite());
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
                 list->append(cssValuePool().createValue(currLayer->composite()));
 
@@ -1746,7 +1635,7 @@
             if (!layers->next())
                 return cssValuePool().createValue(layers->attachment());
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
                 list->append(cssValuePool().createValue(currLayer->attachment()));
 
@@ -1765,7 +1654,7 @@
                 return cssValuePool().createValue(box);
             }
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next()) {
                 EFillBox box = isClip ? currLayer->clip() : currLayer->origin();
                 list->append(cssValuePool().createValue(box));
@@ -1779,7 +1668,7 @@
             if (!layers->next())
                 return createPositionListForLayer(propertyID, layers, *style);
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
                 list->append(createPositionListForLayer(propertyID, currLayer, *style));
             return list.release();
@@ -1790,7 +1679,7 @@
             if (!layers->next())
                 return cssValuePool().createValue(layers->xPosition());
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
                 list->append(cssValuePool().createValue(currLayer->xPosition()));
 
@@ -1802,7 +1691,7 @@
             if (!layers->next())
                 return cssValuePool().createValue(layers->yPosition());
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
                 list->append(cssValuePool().createValue(currLayer->yPosition()));
 
@@ -1813,7 +1702,7 @@
                 return cssValuePool().createIdentifierValue(CSSValueCollapse);
             return cssValuePool().createIdentifierValue(CSSValueSeparate);
         case CSSPropertyBorderSpacing: {
-            RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
             list->append(zoomAdjustedPixelValue(style->horizontalBorderSpacing(), *style));
             list->append(zoomAdjustedPixelValue(style->verticalBorderSpacing(), *style));
             return list.release();
@@ -1851,7 +1740,7 @@
         case CSSPropertyBorderLeftWidth:
             return zoomAdjustedPixelValue(style->borderLeftWidth(), *style);
         case CSSPropertyBottom:
-            return valueForPositionOffset(*style, CSSPropertyBottom, renderer, m_node->document().renderView());
+            return valueForPositionOffset(*style, CSSPropertyBottom, renderer);
         case CSSPropertyWebkitBoxAlign:
             return cssValuePool().createValue(style->boxAlign());
         case CSSPropertyWebkitBoxDecorationBreak:
@@ -1921,14 +1810,8 @@
             return zoomAdjustedPixelValue(style->columnWidth(), *style);
         case CSSPropertyTabSize:
             return cssValuePool().createValue(style->tabSize(), CSSPrimitiveValue::CSS_NUMBER);
-        case CSSPropertyWebkitRegionBreakAfter:
-            return cssValuePool().createValue(style->regionBreakAfter());
-        case CSSPropertyWebkitRegionBreakBefore:
-            return cssValuePool().createValue(style->regionBreakBefore());
-        case CSSPropertyWebkitRegionBreakInside:
-            return cssValuePool().createValue(style->regionBreakInside());
         case CSSPropertyCursor: {
-            RefPtr<CSSValueList> list;
+            RefPtrWillBeRawPtr<CSSValueList> list;
             CursorList* cursors = style->cursors();
             if (cursors && cursors->size() > 0) {
                 list = CSSValueList::createCommaSeparated();
@@ -1952,15 +1835,18 @@
         case CSSPropertyAlignContent:
             return cssValuePool().createValue(style->alignContent());
         case CSSPropertyAlignItems:
-            return cssValuePool().createValue(style->alignItems());
-        case CSSPropertyAlignSelf:
-            if (style->alignSelf() == AlignAuto) {
+            return valueForItemPositionWithOverflowAlignment(style->alignItems(), style->alignItemsOverflowAlignment());
+        case CSSPropertyAlignSelf: {
+            ItemPosition alignSelf = style->alignSelf();
+            if (alignSelf == ItemPositionAuto) {
                 Node* parent = styledNode->parentNode();
                 if (parent && parent->computedStyle())
-                    return cssValuePool().createValue(parent->computedStyle()->alignItems());
-                return cssValuePool().createValue(AlignStretch);
+                    alignSelf = parent->computedStyle()->alignItems();
+                else
+                    alignSelf = ItemPositionStretch;
             }
-            return cssValuePool().createValue(style->alignSelf());
+            return valueForItemPositionWithOverflowAlignment(alignSelf, style->alignSelfOverflowAlignment());
+        }
         case CSSPropertyFlex:
             return valuesForShorthandProperty(flexShorthand());
         case CSSPropertyFlexBasis:
@@ -1984,17 +1870,17 @@
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             return cssValuePool().createValue(style->floating());
         case CSSPropertyFont: {
-            RefPtr<CSSFontValue> computedFont = CSSFontValue::create();
+            RefPtrWillBeRawPtr<CSSFontValue> computedFont = CSSFontValue::create();
             computedFont->style = valueForFontStyle(*style);
             computedFont->variant = valueForFontVariant(*style);
             computedFont->weight = valueForFontWeight(*style);
             computedFont->size = valueForFontSize(*style);
-            computedFont->lineHeight = valueForLineHeight(*style, m_node->document().renderView());
+            computedFont->lineHeight = valueForLineHeight(*style);
             computedFont->family = valueForFontFamily(*style);
             return computedFont.release();
         }
         case CSSPropertyFontFamily: {
-            RefPtr<CSSValueList> fontFamilyList = valueForFontFamily(*style);
+            RefPtrWillBeRawPtr<CSSValueList> fontFamilyList = valueForFontFamily(*style);
             // If there's only a single family, return that as a CSSPrimitiveValue.
             // NOTE: Gecko always returns this as a comma-separated CSSPrimitiveValue string.
             if (fontFamilyList->length() == 1)
@@ -2013,10 +1899,10 @@
             const FontFeatureSettings* featureSettings = style->fontDescription().featureSettings();
             if (!featureSettings || !featureSettings->size())
                 return cssValuePool().createIdentifierValue(CSSValueNormal);
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (unsigned i = 0; i < featureSettings->size(); ++i) {
                 const FontFeature& feature = featureSettings->at(i);
-                RefPtr<CSSFontFeatureValue> featureValue = CSSFontFeatureValue::create(feature.tag(), feature.value());
+                RefPtrWillBeRawPtr<CSSFontFeatureValue> featureValue = CSSFontFeatureValue::create(feature.tag(), feature.value());
                 list->append(featureValue.release());
             }
             return list.release();
@@ -2030,14 +1916,14 @@
         // depending on the size of the explicit grid or the number of implicit tracks added to the grid. See
         // http://lists.w3.org/Archives/Public/www-style/2013Nov/0014.html
         case CSSPropertyGridAutoColumns:
-            return specifiedValueForGridTrackSize(style->gridAutoColumns(), *style, m_node->document().renderView());
+            return specifiedValueForGridTrackSize(style->gridAutoColumns(), *style);
         case CSSPropertyGridAutoRows:
-            return specifiedValueForGridTrackSize(style->gridAutoRows(), *style, m_node->document().renderView());
+            return specifiedValueForGridTrackSize(style->gridAutoRows(), *style);
 
-        case CSSPropertyGridDefinitionColumns:
-            return valueForGridTrackList(ForColumns, renderer, *style, m_node->document().renderView());
-        case CSSPropertyGridDefinitionRows:
-            return valueForGridTrackList(ForRows, renderer, *style, m_node->document().renderView());
+        case CSSPropertyGridTemplateColumns:
+            return valueForGridTrackList(ForColumns, renderer, *style);
+        case CSSPropertyGridTemplateRows:
+            return valueForGridTrackList(ForRows, renderer, *style);
 
         case CSSPropertyGridColumnStart:
             return valueForGridPosition(style->gridColumnStart());
@@ -2054,13 +1940,13 @@
         case CSSPropertyGridArea:
             return valuesForGridShorthand(gridAreaShorthand());
 
-        case CSSPropertyGridTemplate:
+        case CSSPropertyGridTemplateAreas:
             if (!style->namedGridAreaRowCount()) {
                 ASSERT(!style->namedGridAreaColumnCount());
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             }
 
-            return CSSGridTemplateValue::create(style->namedGridArea(), style->namedGridAreaRowCount(), style->namedGridAreaColumnCount());
+            return CSSGridTemplateAreasValue::create(style->namedGridArea(), style->namedGridAreaRowCount(), style->namedGridAreaColumnCount());
 
         case CSSPropertyHeight:
             if (renderer) {
@@ -2087,8 +1973,10 @@
             return CSSPrimitiveValue::create(style->imageRendering());
         case CSSPropertyIsolation:
             return cssValuePool().createValue(style->isolation());
+        case CSSPropertyJustifySelf:
+            return valueForItemPositionWithOverflowAlignment(style->justifySelf(), style->justifySelfOverflowAlignment());
         case CSSPropertyLeft:
-            return valueForPositionOffset(*style, CSSPropertyLeft, renderer, m_node->document().renderView());
+            return valueForPositionOffset(*style, CSSPropertyLeft, renderer);
         case CSSPropertyLetterSpacing:
             if (!style->letterSpacing())
                 return cssValuePool().createIdentifierValue(CSSValueNormal);
@@ -2098,7 +1986,7 @@
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             return cssValuePool().createValue(style->lineClamp().value(), style->lineClamp().isPercentage() ? CSSPrimitiveValue::CSS_PERCENTAGE : CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyLineHeight:
-            return valueForLineHeight(*style, m_node->document().renderView());
+            return valueForLineHeight(*style);
         case CSSPropertyListStyleImage:
             if (style->listStyleImage())
                 return style->listStyleImage()->cssValue();
@@ -2122,11 +2010,11 @@
             if (marginRight.isFixed() || !renderer || !renderer->isBox())
                 return zoomAdjustedPixelValueForLength(marginRight, *style);
             float value;
-            if (marginRight.isPercent() || marginRight.isViewportPercentage()) {
+            if (marginRight.isPercent()) {
                 // RenderBox gives a marginRight() that is the distance between the right-edge of the child box
                 // and the right-edge of the containing box, when display == BLOCK. Let's calculate the absolute
                 // value of the specified margin-right % instead of relying on RenderBox's marginRight() value.
-                value = minimumValueForLength(marginRight, toRenderBox(renderer)->containingBlockLogicalWidthForContent(), m_node->document().renderView());
+                value = minimumValueForLength(marginRight, toRenderBox(renderer)->containingBlockLogicalWidthForContent());
             } else {
                 value = toRenderBox(renderer)->marginRight();
             }
@@ -2238,9 +2126,11 @@
         case CSSPropertyPosition:
             return cssValuePool().createValue(style->position());
         case CSSPropertyRight:
-            return valueForPositionOffset(*style, CSSPropertyRight, renderer, m_node->document().renderView());
+            return valueForPositionOffset(*style, CSSPropertyRight, renderer);
         case CSSPropertyWebkitRubyPosition:
             return cssValuePool().createValue(style->rubyPosition());
+        case CSSPropertyScrollBehavior:
+            return cssValuePool().createValue(style->scrollBehavior());
         case CSSPropertyTableLayout:
             return cssValuePool().createValue(style->tableLayout());
         case CSSPropertyTextAlign:
@@ -2281,7 +2171,7 @@
             case TextEmphasisMarkDoubleCircle:
             case TextEmphasisMarkTriangle:
             case TextEmphasisMarkSesame: {
-                RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+                RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
                 list->append(cssValuePool().createValue(style->textEmphasisFill()));
                 list->append(cssValuePool().createValue(style->textEmphasisMark()));
                 return list.release();
@@ -2290,7 +2180,7 @@
         case CSSPropertyTextIndent: {
             RefPtr<CSSValue> textIndent = zoomAdjustedPixelValueForLength(style->textIndent(), *style);
             if (RuntimeEnabledFeatures::css3TextEnabled() && style->textIndentLine() == TextIndentEachLine) {
-                RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+                RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
                 list->append(textIndent.release());
                 list->append(cssValuePool().createIdentifierValue(CSSValueEachLine));
                 return list.release();
@@ -2314,9 +2204,9 @@
         case CSSPropertyTextTransform:
             return cssValuePool().createValue(style->textTransform());
         case CSSPropertyTop:
-            return valueForPositionOffset(*style, CSSPropertyTop, renderer, m_node->document().renderView());
+            return valueForPositionOffset(*style, CSSPropertyTop, renderer);
         case CSSPropertyTouchAction:
-            return cssValuePool().createValue(style->touchAction());
+            return touchActionFlagsToCSSValue(style->touchAction());
         case CSSPropertyTouchActionDelay:
             return cssValuePool().createValue(style->touchActionDelay());
         case CSSPropertyUnicodeBidi:
@@ -2377,7 +2267,7 @@
             return cssValuePool().createValue(style->fontDescription().kerning());
         case CSSPropertyWebkitFontSmoothing:
             return cssValuePool().createValue(style->fontDescription().fontSmoothing());
-        case CSSPropertyWebkitFontVariantLigatures: {
+        case CSSPropertyFontVariantLigatures: {
             FontDescription::LigaturesState commonLigaturesState = style->fontDescription().commonLigaturesState();
             FontDescription::LigaturesState discretionaryLigaturesState = style->fontDescription().discretionaryLigaturesState();
             FontDescription::LigaturesState historicalLigaturesState = style->fontDescription().historicalLigaturesState();
@@ -2385,7 +2275,7 @@
                 && historicalLigaturesState == FontDescription::NormalLigaturesState)
                 return cssValuePool().createIdentifierValue(CSSValueNormal);
 
-            RefPtr<CSSValueList> valueList = CSSValueList::createSpaceSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> valueList = CSSValueList::createSpaceSeparated();
             if (commonLigaturesState != FontDescription::NormalLigaturesState)
                 valueList->append(cssValuePool().createIdentifierValue(commonLigaturesState == FontDescription::DisabledLigaturesState ? CSSValueNoCommonLigatures : CSSValueCommonLigatures));
             if (discretionaryLigaturesState != FontDescription::NormalLigaturesState)
@@ -2413,7 +2303,7 @@
         case CSSPropertyAnimationDirection:
             ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationDirection: {
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
             if (t) {
                 for (size_t i = 0; i < t->size(); ++i)
@@ -2429,7 +2319,7 @@
         case CSSPropertyAnimationFillMode:
             ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationFillMode: {
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
             if (t) {
                 for (size_t i = 0; i < t->size(); ++i)
@@ -2441,7 +2331,7 @@
         case CSSPropertyAnimationIterationCount:
             ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationIterationCount: {
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
             if (t) {
                 for (size_t i = 0; i < t->size(); ++i) {
@@ -2458,7 +2348,7 @@
         case CSSPropertyAnimationName:
             ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationName: {
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
             if (t) {
                 for (size_t i = 0; i < t->size(); ++i)
@@ -2470,7 +2360,7 @@
         case CSSPropertyAnimationPlayState:
             ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationPlayState: {
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
             if (t) {
                 for (size_t i = 0; i < t->size(); ++i) {
@@ -2492,9 +2382,9 @@
         case CSSPropertyWebkitAnimation: {
             const CSSAnimationDataList* animations = style->animations();
             if (animations) {
-                RefPtr<CSSValueList> animationsList = CSSValueList::createCommaSeparated();
+                RefPtrWillBeRawPtr<CSSValueList> animationsList = CSSValueList::createCommaSeparated();
                 for (size_t i = 0; i < animations->size(); ++i) {
-                    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+                    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
                     const CSSAnimationData* animation = animations->animation(i);
                     list->append(cssValuePool().createValue(animation->name(), CSSPrimitiveValue::CSS_STRING));
                     list->append(cssValuePool().createValue(animation->duration(), CSSPrimitiveValue::CSS_S));
@@ -2515,7 +2405,7 @@
                 return animationsList.release();
             }
 
-            RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
             // animation-name default value.
             list->append(cssValuePool().createIdentifierValue(CSSValueNone));
             list->append(cssValuePool().createValue(CSSAnimationData::initialAnimationDuration(), CSSPrimitiveValue::CSS_S));
@@ -2574,15 +2464,14 @@
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             return zoomAdjustedPixelValue(style->perspective(), *style);
         case CSSPropertyWebkitPerspectiveOrigin: {
-            RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
             if (renderer) {
                 LayoutRect box;
                 if (renderer->isBox())
                     box = toRenderBox(renderer)->borderBoxRect();
 
-                RenderView* renderView = m_node->document().renderView();
-                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginX(), box.width(), renderView), *style));
-                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginY(), box.height(), renderView), *style));
+                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginX(), box.width()), *style));
+                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginY(), box.height()), *style));
             }
             else {
                 list->append(zoomAdjustedPixelValueForLength(style->perspectiveOriginX(), *style));
@@ -2622,15 +2511,14 @@
         case CSSPropertyWebkitTransform:
             return computedTransform(renderer, *style);
         case CSSPropertyWebkitTransformOrigin: {
-            RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
             if (renderer) {
                 LayoutRect box;
                 if (renderer->isBox())
                     box = toRenderBox(renderer)->borderBoxRect();
 
-                RenderView* renderView = m_node->document().renderView();
-                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginX(), box.width(), renderView), *style));
-                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginY(), box.height(), renderView), *style));
+                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginX(), box.width()), *style));
+                list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginY(), box.height()), *style));
                 if (style->transformOriginZ() != 0)
                     list->append(zoomAdjustedPixelValue(style->transformOriginZ(), *style));
             } else {
@@ -2659,9 +2547,9 @@
         case CSSPropertyWebkitTransition: {
             const CSSAnimationDataList* animList = style->transitions();
             if (animList) {
-                RefPtr<CSSValueList> transitionsList = CSSValueList::createCommaSeparated();
+                RefPtrWillBeRawPtr<CSSValueList> transitionsList = CSSValueList::createCommaSeparated();
                 for (size_t i = 0; i < animList->size(); ++i) {
-                    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+                    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
                     const CSSAnimationData* animation = animList->animation(i);
                     list->append(createTransitionPropertyValue(animation));
                     list->append(cssValuePool().createValue(animation->duration(), CSSPrimitiveValue::CSS_S));
@@ -2672,7 +2560,7 @@
                 return transitionsList.release();
             }
 
-            RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
             // transition-property default value.
             list->append(cssValuePool().createIdentifierValue(CSSValueAll));
             list->append(cssValuePool().createValue(CSSAnimationData::initialAnimationDuration(), CSSPrimitiveValue::CSS_S));
@@ -2682,14 +2570,6 @@
         }
         case CSSPropertyPointerEvents:
             return cssValuePool().createValue(style->pointerEvents());
-        case CSSPropertyWebkitLineGrid:
-            if (style->lineGrid().isNull())
-                return cssValuePool().createIdentifierValue(CSSValueNone);
-            return cssValuePool().createValue(style->lineGrid(), CSSPrimitiveValue::CSS_STRING);
-        case CSSPropertyWebkitLineSnap:
-            return CSSPrimitiveValue::create(style->lineSnap());
-        case CSSPropertyWebkitLineAlign:
-            return CSSPrimitiveValue::create(style->lineAlign());
         case CSSPropertyWebkitWritingMode:
             return cssValuePool().createValue(style->writingMode());
         case CSSPropertyWebkitTextCombine:
@@ -2712,16 +2592,6 @@
                     return CSSPrimitiveValue::create(toReferenceClipPathOperation(operation)->url(), CSSPrimitiveValue::CSS_URI);
             }
             return cssValuePool().createIdentifierValue(CSSValueNone);
-        case CSSPropertyWebkitFlowInto:
-            if (style->flowThread().isNull())
-                return cssValuePool().createIdentifierValue(CSSValueNone);
-            return cssValuePool().createValue(style->flowThread(), CSSPrimitiveValue::CSS_STRING);
-        case CSSPropertyWebkitFlowFrom:
-            if (!style->hasFlowFrom())
-                return cssValuePool().createIdentifierValue(CSSValueNone);
-            return cssValuePool().createValue(style->regionThread(), CSSPrimitiveValue::CSS_STRING);
-        case CSSPropertyWebkitRegionFragment:
-            return cssValuePool().createValue(style->regionFragment());
         case CSSPropertyWebkitWrapFlow:
             return cssValuePool().createValue(style->wrapFlow());
         case CSSPropertyShapeMargin:
@@ -2732,7 +2602,7 @@
             return cssValuePool().createValue(style->shapeImageThreshold(), CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyShapeInside:
             if (!style->shapeInside())
-                return cssValuePool().createIdentifierValue(CSSValueAuto);
+                return cssValuePool().createIdentifierValue(CSSValueNone);
             if (style->shapeInside()->type() == ShapeValue::Box)
                 return cssValuePool().createValue(style->shapeInside()->layoutBox());
             if (style->shapeInside()->type() == ShapeValue::Outside)
@@ -2746,7 +2616,7 @@
             return valueForBasicShape(*style, style->shapeInside()->shape());
         case CSSPropertyShapeOutside:
             if (!style->shapeOutside())
-                return cssValuePool().createIdentifierValue(CSSValueAuto);
+                return cssValuePool().createIdentifierValue(CSSValueNone);
             if (style->shapeOutside()->type() == ShapeValue::Box)
                 return cssValuePool().createValue(style->shapeOutside()->layoutBox());
             if (style->shapeOutside()->type() == ShapeValue::Image) {
@@ -2768,7 +2638,7 @@
             if (!layers->next())
                 return cssValuePool().createValue(layers->blendMode());
 
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
                 list->append(cssValuePool().createValue(currLayer->blendMode()));
 
@@ -3016,9 +2886,9 @@
     return copyPropertiesInSet(computableProperties());
 }
 
-PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForShorthandProperty(const StylePropertyShorthand& shorthand) const
+PassRefPtrWillBeRawPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForShorthandProperty(const StylePropertyShorthand& shorthand) const
 {
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     for (size_t i = 0; i < shorthand.length(); ++i) {
         RefPtr<CSSValue> value = getPropertyCSSValue(shorthand.properties()[i], DoNotUpdateLayout);
         list->append(value);
@@ -3026,9 +2896,9 @@
     return list.release();
 }
 
-PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForSidesShorthand(const StylePropertyShorthand& shorthand) const
+PassRefPtrWillBeRawPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForSidesShorthand(const StylePropertyShorthand& shorthand) const
 {
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     // Assume the properties are in the usual order top, right, bottom, left.
     RefPtr<CSSValue> topValue = getPropertyCSSValue(shorthand.properties()[0], DoNotUpdateLayout);
     RefPtr<CSSValue> rightValue = getPropertyCSSValue(shorthand.properties()[1], DoNotUpdateLayout);
@@ -3054,9 +2924,9 @@
     return list.release();
 }
 
-PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForGridShorthand(const StylePropertyShorthand& shorthand) const
+PassRefPtrWillBeRawPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForGridShorthand(const StylePropertyShorthand& shorthand) const
 {
-    RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
     for (size_t i = 0; i < shorthand.length(); ++i) {
         RefPtr<CSSValue> value = getPropertyCSSValue(shorthand.properties()[i], DoNotUpdateLayout);
         list->append(value.release());
@@ -3140,89 +3010,7 @@
     exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore the '" + getPropertyNameString(id) + "' property is read-only.");
 }
 
-const HashMap<AtomicString, String>* CSSComputedStyleDeclaration::variableMap() const
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    Node* styledNode = this->styledNode();
-    if (!styledNode)
-        return 0;
-    RefPtr<RenderStyle> style = styledNode->computedStyle(styledNode->isPseudoElement() ? NOPSEUDO : m_pseudoElementSpecifier);
-    if (!style)
-        return 0;
-    return style->variables();
-}
-
-unsigned CSSComputedStyleDeclaration::variableCount() const
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    const HashMap<AtomicString, String>* variables = variableMap();
-    if (!variables)
-        return 0;
-    return variables->size();
-}
-
-String CSSComputedStyleDeclaration::variableValue(const AtomicString& name) const
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    const HashMap<AtomicString, String>* variables = variableMap();
-    if (!variables)
-        return emptyString();
-    HashMap<AtomicString, String>::const_iterator it = variables->find(name);
-    if (it == variables->end())
-        return emptyString();
-    return it->value;
-}
-
-bool CSSComputedStyleDeclaration::setVariableValue(const AtomicString& name, const String&, ExceptionState& exceptionState)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore the '" + name + "' property is read-only.");
-    return false;
-}
-
-bool CSSComputedStyleDeclaration::removeVariable(const AtomicString&)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    return false;
-}
-
-bool CSSComputedStyleDeclaration::clearVariables(ExceptionState& exceptionState)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore variables may not be cleared.");
-    return false;
-}
-
-CSSComputedStyleDeclaration::ComputedCSSVariablesIterator::ComputedCSSVariablesIterator(const HashMap<AtomicString, String>* variables)
-    : m_active(variables)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    if (m_active) {
-        m_it = variables->begin();
-        m_end = variables->end();
-    }
-}
-
-void CSSComputedStyleDeclaration::ComputedCSSVariablesIterator::advance()
-{
-    ASSERT(m_active);
-    ++m_it;
-    m_active = !atEnd();
-}
-
-AtomicString CSSComputedStyleDeclaration::ComputedCSSVariablesIterator::name() const
-{
-    ASSERT(m_active);
-    return m_it->key;
-}
-
-String CSSComputedStyleDeclaration::ComputedCSSVariablesIterator::value() const
-{
-    ASSERT(m_active);
-    return m_it->value;
-}
-
-PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForBackgroundShorthand() const
+PassRefPtrWillBeRawPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForBackgroundShorthand() const
 {
     static const CSSPropertyID propertiesBeforeSlashSeperator[5] = { CSSPropertyBackgroundColor, CSSPropertyBackgroundImage,
                                                                      CSSPropertyBackgroundRepeat, CSSPropertyBackgroundAttachment,
@@ -3230,7 +3018,7 @@
     static const CSSPropertyID propertiesAfterSlashSeperator[3] = { CSSPropertyBackgroundSize, CSSPropertyBackgroundOrigin,
                                                                     CSSPropertyBackgroundClip };
 
-    RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
     list->append(valuesForShorthandProperty(StylePropertyShorthand(CSSPropertyBackground, propertiesBeforeSlashSeperator, WTF_ARRAY_LENGTH(propertiesBeforeSlashSeperator))));
     list->append(valuesForShorthandProperty(StylePropertyShorthand(CSSPropertyBackground, propertiesAfterSlashSeperator, WTF_ARRAY_LENGTH(propertiesAfterSlashSeperator))));
     return list.release();
diff --git a/Source/core/css/CSSComputedStyleDeclaration.h b/Source/core/css/CSSComputedStyleDeclaration.h
index a3ff877..04793a4 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/Source/core/css/CSSComputedStyleDeclaration.h
@@ -33,9 +33,6 @@
 
 class CSSPrimitiveValue;
 class CSSValueList;
-class Color;
-class CustomFilterNumberParameter;
-class CustomFilterParameter;
 class ExceptionState;
 class MutableStylePropertySet;
 class Node;
@@ -44,29 +41,13 @@
 class SVGPaint;
 class ShadowData;
 class ShadowList;
+class StyleColor;
 class StylePropertySet;
 class StylePropertyShorthand;
 
 enum EUpdateLayout { DoNotUpdateLayout = false, UpdateLayout = true };
 
-class CSSComputedStyleDeclaration : public CSSStyleDeclaration {
-private:
-    class ComputedCSSVariablesIterator : public CSSVariablesIterator {
-    public:
-        virtual ~ComputedCSSVariablesIterator() { }
-        static PassRefPtr<ComputedCSSVariablesIterator> create(const HashMap<AtomicString, String>* variableMap) { return adoptRef(new ComputedCSSVariablesIterator(variableMap)); }
-    private:
-        explicit ComputedCSSVariablesIterator(const HashMap<AtomicString, String>* variableMap);
-        virtual void advance() OVERRIDE;
-        virtual bool atEnd() const OVERRIDE { return m_it == m_end; }
-        virtual AtomicString name() const OVERRIDE;
-        virtual String value() const OVERRIDE;
-        bool m_active;
-        typedef HashMap<AtomicString, String>::const_iterator VariablesMapIterator;
-        VariablesMapIterator m_it;
-        VariablesMapIterator m_end;
-    };
-
+class CSSComputedStyleDeclaration FINAL : public CSSStyleDeclaration {
 public:
     static PassRefPtr<CSSComputedStyleDeclaration> create(PassRefPtr<Node> node, bool allowVisitedStyle = false, const String& pseudoElementName = String())
     {
@@ -101,44 +82,36 @@
     Node* styledNode() const;
 
     // CSSOM functions. Don't make these public.
-    virtual CSSRule* parentRule() const;
-    virtual unsigned length() const;
-    virtual String item(unsigned index) const;
+    virtual CSSRule* parentRule() const OVERRIDE;
+    virtual unsigned length() const OVERRIDE;
+    virtual String item(unsigned index) const OVERRIDE;
     PassRefPtr<RenderStyle> computeRenderStyle(CSSPropertyID) const;
-    virtual PassRefPtr<CSSValue> getPropertyCSSValue(const String& propertyName);
-    virtual String getPropertyValue(const String& propertyName);
-    virtual String getPropertyPriority(const String& propertyName);
-    virtual String getPropertyShorthand(const String& propertyName);
-    virtual bool isPropertyImplicit(const String& propertyName);
-    virtual void setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState&);
-    virtual String removeProperty(const String& propertyName, ExceptionState&);
-    virtual String cssText() const;
-    virtual void setCSSText(const String&, ExceptionState&);
-    virtual PassRefPtr<CSSValue> getPropertyCSSValueInternal(CSSPropertyID);
-    virtual String getPropertyValueInternal(CSSPropertyID);
-    virtual void setPropertyInternal(CSSPropertyID, const String& value, bool important, ExceptionState&);
-
-    const HashMap<AtomicString, String>* variableMap() const;
-    virtual unsigned variableCount() const OVERRIDE;
-    virtual String variableValue(const AtomicString& name) const OVERRIDE;
-    virtual bool setVariableValue(const AtomicString& name, const String& value, ExceptionState&) OVERRIDE;
-    virtual bool removeVariable(const AtomicString& name) OVERRIDE;
-    virtual bool clearVariables(ExceptionState&) OVERRIDE;
-    virtual PassRefPtr<CSSVariablesIterator> variablesIterator() const OVERRIDE { return ComputedCSSVariablesIterator::create(variableMap()); }
+    virtual PassRefPtr<CSSValue> getPropertyCSSValue(const String& propertyName) OVERRIDE;
+    virtual String getPropertyValue(const String& propertyName) OVERRIDE;
+    virtual String getPropertyPriority(const String& propertyName) OVERRIDE;
+    virtual String getPropertyShorthand(const String& propertyName) OVERRIDE;
+    virtual bool isPropertyImplicit(const String& propertyName) OVERRIDE;
+    virtual void setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState&) OVERRIDE;
+    virtual String removeProperty(const String& propertyName, ExceptionState&) OVERRIDE;
+    virtual String cssText() const OVERRIDE;
+    virtual void setCSSText(const String&, ExceptionState&) OVERRIDE;
+    virtual PassRefPtr<CSSValue> getPropertyCSSValueInternal(CSSPropertyID) OVERRIDE;
+    virtual String getPropertyValueInternal(CSSPropertyID) OVERRIDE;
+    virtual void setPropertyInternal(CSSPropertyID, const String& value, bool important, ExceptionState&) OVERRIDE;
 
     virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const OVERRIDE;
 
     PassRefPtr<CSSValue> valueForShadowData(const ShadowData&, const RenderStyle&, bool useSpread) const;
     PassRefPtr<CSSValue> valueForShadowList(const ShadowList*, const RenderStyle&, bool useSpread) const;
-    PassRefPtr<CSSPrimitiveValue> currentColorOrValidColor(const RenderStyle&, const Color&) const;
-    PassRefPtr<SVGPaint> adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint>, RenderStyle&) const;
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> currentColorOrValidColor(const RenderStyle&, const StyleColor&) const;
+    PassRefPtrWillBeRawPtr<SVGPaint> adjustSVGPaintForCurrentColor(PassRefPtrWillBeRawPtr<SVGPaint>, RenderStyle&) const;
 
     PassRefPtr<CSSValue> valueForFilter(const RenderObject*, const RenderStyle&) const;
 
-    PassRefPtr<CSSValueList> valuesForShorthandProperty(const StylePropertyShorthand&) const;
-    PassRefPtr<CSSValueList> valuesForSidesShorthand(const StylePropertyShorthand&) const;
-    PassRefPtr<CSSValueList> valuesForBackgroundShorthand() const;
-    PassRefPtr<CSSValueList> valuesForGridShorthand(const StylePropertyShorthand&) const;
+    PassRefPtrWillBeRawPtr<CSSValueList> valuesForShorthandProperty(const StylePropertyShorthand&) const;
+    PassRefPtrWillBeRawPtr<CSSValueList> valuesForSidesShorthand(const StylePropertyShorthand&) const;
+    PassRefPtrWillBeRawPtr<CSSValueList> valuesForBackgroundShorthand() const;
+    PassRefPtrWillBeRawPtr<CSSValueList> valuesForGridShorthand(const StylePropertyShorthand&) const;
 
     RefPtr<Node> m_node;
     PseudoId m_pseudoElementSpecifier;
diff --git a/Source/core/css/CSSCrossfadeValue.cpp b/Source/core/css/CSSCrossfadeValue.cpp
index 801cbb6..2aec542 100644
--- a/Source/core/css/CSSCrossfadeValue.cpp
+++ b/Source/core/css/CSSCrossfadeValue.cpp
@@ -218,4 +218,10 @@
         && compareCSSValuePtr(m_percentageValue, other.m_percentageValue);
 }
 
+void CSSCrossfadeValue::traceAfterDispatch(Visitor* visitor)
+{
+    visitor->trace(m_percentageValue);
+    CSSImageGeneratorValue::traceAfterDispatch(visitor);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSCrossfadeValue.h b/Source/core/css/CSSCrossfadeValue.h
index ffb46ae..8fc0bbf 100644
--- a/Source/core/css/CSSCrossfadeValue.h
+++ b/Source/core/css/CSSCrossfadeValue.h
@@ -43,9 +43,9 @@
 class CSSCrossfadeValue : public CSSImageGeneratorValue {
     friend class CrossfadeSubimageObserverProxy;
 public:
-    static PassRefPtr<CSSCrossfadeValue> create(PassRefPtr<CSSValue> fromValue, PassRefPtr<CSSValue> toValue)
+    static PassRefPtrWillBeRawPtr<CSSCrossfadeValue> create(PassRefPtr<CSSValue> fromValue, PassRefPtr<CSSValue> toValue)
     {
-        return adoptRef(new CSSCrossfadeValue(fromValue, toValue));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSCrossfadeValue(fromValue, toValue));
     }
 
     ~CSSCrossfadeValue();
@@ -61,12 +61,14 @@
 
     void loadSubimages(ResourceFetcher*);
 
-    void setPercentage(PassRefPtr<CSSPrimitiveValue> percentageValue) { m_percentageValue = percentageValue; }
+    void setPercentage(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> percentageValue) { m_percentageValue = percentageValue; }
 
     bool hasFailedOrCanceledSubresources() const;
 
     bool equals(const CSSCrossfadeValue&) const;
 
+    void traceAfterDispatch(Visitor*);
+
 private:
     CSSCrossfadeValue(PassRefPtr<CSSValue> fromValue, PassRefPtr<CSSValue> toValue)
         : CSSImageGeneratorValue(CrossfadeClass)
@@ -76,7 +78,7 @@
         , m_cachedToImage(0)
         , m_crossfadeSubimageObserver(this) { }
 
-    class CrossfadeSubimageObserverProxy : public ImageResourceClient {
+    class CrossfadeSubimageObserverProxy FINAL : public ImageResourceClient {
     public:
         CrossfadeSubimageObserverProxy(CSSCrossfadeValue* ownerValue)
         : m_ownerValue(ownerValue)
@@ -94,7 +96,7 @@
 
     RefPtr<CSSValue> m_fromValue;
     RefPtr<CSSValue> m_toValue;
-    RefPtr<CSSPrimitiveValue> m_percentageValue;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_percentageValue;
 
     ResourcePtr<ImageResource> m_cachedFromImage;
     ResourcePtr<ImageResource> m_cachedToImage;
diff --git a/Source/core/css/CSSCursorImageValue.cpp b/Source/core/css/CSSCursorImageValue.cpp
index 878fd89..2deb9ae 100644
--- a/Source/core/css/CSSCursorImageValue.cpp
+++ b/Source/core/css/CSSCursorImageValue.cpp
@@ -34,6 +34,7 @@
 #include "core/svg/SVGLengthContext.h"
 #include "core/svg/SVGURIReference.h"
 #include "wtf/MathExtras.h"
+#include "wtf/text/StringBuilder.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -42,7 +43,7 @@
 {
     Element* element = SVGURIReference::targetElementFromIRIString(url, document);
     if (element && element->hasTagName(SVGNames::cursorTag))
-        return static_cast<SVGCursorElement*>(element);
+        return toSVGCursorElement(element);
 
     return 0;
 }
@@ -99,13 +100,13 @@
         // FIXME: This will override hot spot specified in CSS, which is probably incorrect.
         SVGLengthContext lengthContext(0);
         m_hasHotSpot = true;
-        float x = roundf(cursorElement->xCurrentValue().value(lengthContext));
+        float x = roundf(cursorElement->x()->currentValue()->value(lengthContext));
         m_hotSpot.setX(static_cast<int>(x));
 
-        float y = roundf(cursorElement->yCurrentValue().value(lengthContext));
+        float y = roundf(cursorElement->y()->currentValue()->value(lengthContext));
         m_hotSpot.setY(static_cast<int>(y));
 
-        if (cachedImageURL() != element->document().completeURL(cursorElement->hrefCurrentValue()))
+        if (cachedImageURL() != element->document().completeURL(cursorElement->href()->currentValue()->value()))
             clearImageResource();
 
         SVGElement* svgElement = toSVGElement(element);
@@ -130,10 +131,10 @@
         // to change the URL of the CSSImageValue (which would then change behavior like cssText),
         // we create an alternate CSSImageValue to use.
         if (isSVGCursor() && loader && loader->document()) {
-            RefPtr<CSSImageValue> imageValue = toCSSImageValue(m_imageValue.get());
+            RefPtrWillBeRawPtr<CSSImageValue> imageValue = toCSSImageValue(m_imageValue.get());
             // FIXME: This will fail if the <cursor> element is in a shadow DOM (bug 59827)
             if (SVGCursorElement* cursorElement = resourceReferencedByCursorElement(imageValue->url(), *loader->document())) {
-                RefPtr<CSSImageValue> svgImageValue = CSSImageValue::create(cursorElement->hrefCurrentValue());
+                RefPtrWillBeRawPtr<CSSImageValue> svgImageValue = CSSImageValue::create(loader->document()->completeURL(cursorElement->href()->currentValue()->value()));
                 StyleFetchedImage* cachedImage = svgImageValue->cachedImage(loader);
                 m_image = cachedImage;
                 return cachedImage;
@@ -164,7 +165,7 @@
 bool CSSCursorImageValue::isSVGCursor() const
 {
     if (m_imageValue->isImageValue()) {
-        RefPtr<CSSImageValue> imageValue = toCSSImageValue(m_imageValue.get());
+        RefPtrWillBeRawPtr<CSSImageValue> imageValue = toCSSImageValue(m_imageValue.get());
         KURL kurl(ParsedURLString, imageValue->url());
         return kurl.hasFragmentIdentifier();
     }
@@ -195,4 +196,9 @@
         && compareCSSValuePtr(m_imageValue, other.m_imageValue);
 }
 
+void CSSCursorImageValue::traceAfterDispatch(Visitor* visitor)
+{
+    CSSValue::traceAfterDispatch(visitor);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSCursorImageValue.h b/Source/core/css/CSSCursorImageValue.h
index 17bba31..4d343a2 100644
--- a/Source/core/css/CSSCursorImageValue.h
+++ b/Source/core/css/CSSCursorImageValue.h
@@ -32,9 +32,9 @@
 
 class CSSCursorImageValue : public CSSValue {
 public:
-    static PassRefPtr<CSSCursorImageValue> create(PassRefPtr<CSSValue> imageValue, bool hasHotSpot, const IntPoint& hotSpot)
+    static PassRefPtrWillBeRawPtr<CSSCursorImageValue> create(PassRefPtr<CSSValue> imageValue, bool hasHotSpot, const IntPoint& hotSpot)
     {
-        return adoptRef(new CSSCursorImageValue(imageValue, hasHotSpot, hotSpot));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSCursorImageValue(imageValue, hasHotSpot, hotSpot));
     }
 
     ~CSSCursorImageValue();
@@ -58,6 +58,8 @@
 
     bool equals(const CSSCursorImageValue&) const;
 
+    void traceAfterDispatch(Visitor*);
+
 private:
     CSSCursorImageValue(PassRefPtr<CSSValue> imageValue, bool hasHotSpot, const IntPoint& hotSpot);
 
diff --git a/Source/core/css/CSSDefaultStyleSheets.cpp b/Source/core/css/CSSDefaultStyleSheets.cpp
index cdd7948..574aca6 100644
--- a/Source/core/css/CSSDefaultStyleSheets.cpp
+++ b/Source/core/css/CSSDefaultStyleSheets.cpp
@@ -36,26 +36,17 @@
 #include "core/dom/FullscreenElementStack.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLVideoElement.h"
 #include "core/rendering/RenderTheme.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
-RuleSet* CSSDefaultStyleSheets::defaultStyle;
-RuleSet* CSSDefaultStyleSheets::defaultViewportStyle;
-RuleSet* CSSDefaultStyleSheets::defaultQuirksStyle;
-RuleSet* CSSDefaultStyleSheets::defaultPrintStyle;
-RuleSet* CSSDefaultStyleSheets::defaultViewSourceStyle;
-RuleSet* CSSDefaultStyleSheets::defaultXHTMLMobileProfileStyle;
-
-StyleSheetContents* CSSDefaultStyleSheets::defaultStyleSheet;
-StyleSheetContents* CSSDefaultStyleSheets::viewportStyleSheet;
-StyleSheetContents* CSSDefaultStyleSheets::quirksStyleSheet;
-StyleSheetContents* CSSDefaultStyleSheets::svgStyleSheet;
-StyleSheetContents* CSSDefaultStyleSheets::mediaControlsStyleSheet;
-StyleSheetContents* CSSDefaultStyleSheets::fullscreenStyleSheet;
+CSSDefaultStyleSheets& CSSDefaultStyleSheets::instance()
+{
+    DEFINE_STATIC_LOCAL(CSSDefaultStyleSheets, cssDefaultStyleSheets, ());
+    return cssDefaultStyleSheets;
+}
 
 static const MediaQueryEvaluator& screenEval()
 {
@@ -71,9 +62,9 @@
 
 static StyleSheetContents* parseUASheet(const String& str)
 {
-    StyleSheetContents* sheet = StyleSheetContents::create(CSSParserContext(UASheetMode)).leakRef(); // leak the sheet on purpose
+    RefPtr<StyleSheetContents> sheet = StyleSheetContents::create(CSSParserContext(UASheetMode, 0));
     sheet->parseString(str);
-    return sheet;
+    return sheet.release().leakRef(); // leak the sheet on purpose
 }
 
 static StyleSheetContents* parseUASheet(const char* characters, unsigned size)
@@ -81,88 +72,93 @@
     return parseUASheet(String(characters, size));
 }
 
-void CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary()
+CSSDefaultStyleSheets::CSSDefaultStyleSheets()
+    : m_defaultStyle(0)
+    , m_defaultViewportStyle(0)
+    , m_defaultQuirksStyle(0)
+    , m_defaultPrintStyle(0)
+    , m_defaultViewSourceStyle(0)
+    , m_defaultXHTMLMobileProfileStyle(0)
+    , m_defaultStyleSheet(0)
+    , m_viewportStyleSheet(0)
+    , m_quirksStyleSheet(0)
+    , m_svgStyleSheet(0)
+    , m_mediaControlsStyleSheet(0)
+    , m_fullscreenStyleSheet(0)
 {
-    if (!defaultStyle)
-        loadDefaultStyle();
-}
-
-void CSSDefaultStyleSheets::loadDefaultStyle()
-{
-    ASSERT(!defaultStyle);
-    defaultStyle = RuleSet::create().leakPtr();
-    defaultViewportStyle = RuleSet::create().leakPtr();
-    defaultPrintStyle = RuleSet::create().leakPtr();
-    defaultQuirksStyle = RuleSet::create().leakPtr();
+    m_defaultStyle = RuleSet::create().leakPtr();
+    m_defaultViewportStyle = RuleSet::create().leakPtr();
+    m_defaultPrintStyle = RuleSet::create().leakPtr();
+    m_defaultQuirksStyle = RuleSet::create().leakPtr();
 
     // Strict-mode rules.
     String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet();
-    defaultStyleSheet = parseUASheet(defaultRules);
-    defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
+    m_defaultStyleSheet = parseUASheet(defaultRules);
+    m_defaultStyle->addRulesFromSheet(m_defaultStyleSheet, screenEval());
 #if OS(ANDROID)
     String viewportRules(viewportAndroidUserAgentStyleSheet, sizeof(viewportAndroidUserAgentStyleSheet));
 #else
     String viewportRules;
 #endif
-    viewportStyleSheet = parseUASheet(viewportRules);
-    defaultViewportStyle->addRulesFromSheet(viewportStyleSheet, screenEval());
-    defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());
+    m_viewportStyleSheet = parseUASheet(viewportRules);
+    m_defaultViewportStyle->addRulesFromSheet(m_viewportStyleSheet, screenEval());
+    m_defaultPrintStyle->addRulesFromSheet(m_defaultStyleSheet, printEval());
 
     // Quirks-mode rules.
     String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet();
-    quirksStyleSheet = parseUASheet(quirksRules);
-    defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
+    m_quirksStyleSheet = parseUASheet(quirksRules);
+    m_defaultQuirksStyle->addRulesFromSheet(m_quirksStyleSheet, screenEval());
 }
 
-RuleSet* CSSDefaultStyleSheets::viewSourceStyle()
+RuleSet* CSSDefaultStyleSheets::defaultViewSourceStyle()
 {
-    if (!defaultViewSourceStyle) {
-        defaultViewSourceStyle = RuleSet::create().leakPtr();
-        defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
+    if (!m_defaultViewSourceStyle) {
+        m_defaultViewSourceStyle = RuleSet::create().leakPtr();
+        m_defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
     }
-    return defaultViewSourceStyle;
+    return m_defaultViewSourceStyle;
 }
 
-RuleSet* CSSDefaultStyleSheets::xhtmlMobileProfileStyle()
+RuleSet* CSSDefaultStyleSheets::defaultXHTMLMobileProfileStyle()
 {
-    if (!defaultXHTMLMobileProfileStyle) {
-        defaultXHTMLMobileProfileStyle = RuleSet::create().leakPtr();
-        defaultXHTMLMobileProfileStyle->addRulesFromSheet(parseUASheet(xhtmlmpUserAgentStyleSheet, sizeof(xhtmlmpUserAgentStyleSheet)), screenEval());
+    if (!m_defaultXHTMLMobileProfileStyle) {
+        m_defaultXHTMLMobileProfileStyle = RuleSet::create().leakPtr();
+        m_defaultXHTMLMobileProfileStyle->addRulesFromSheet(parseUASheet(xhtmlmpUserAgentStyleSheet, sizeof(xhtmlmpUserAgentStyleSheet)), screenEval());
     }
-    return defaultXHTMLMobileProfileStyle;
+    return m_defaultXHTMLMobileProfileStyle;
 }
 
 void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(Element* element, bool& changedDefaultStyle)
 {
     // FIXME: We should assert that the sheet only styles SVG elements.
-    if (element->isSVGElement() && !svgStyleSheet) {
-        svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
-        defaultStyle->addRulesFromSheet(svgStyleSheet, screenEval());
-        defaultPrintStyle->addRulesFromSheet(svgStyleSheet, printEval());
+    if (element->isSVGElement() && !m_svgStyleSheet) {
+        m_svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
+        m_defaultStyle->addRulesFromSheet(m_svgStyleSheet, screenEval());
+        m_defaultPrintStyle->addRulesFromSheet(m_svgStyleSheet, printEval());
         changedDefaultStyle = true;
     }
 
     // FIXME: We should assert that this sheet only contains rules for <video> and <audio>.
-    if (!mediaControlsStyleSheet && (isHTMLVideoElement(element) || element->hasTagName(audioTag))) {
+    if (!m_mediaControlsStyleSheet && (element->hasTagName(videoTag) || element->hasTagName(audioTag))) {
         String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::theme().extraMediaControlsStyleSheet();
-        mediaControlsStyleSheet = parseUASheet(mediaRules);
-        defaultStyle->addRulesFromSheet(mediaControlsStyleSheet, screenEval());
-        defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet, printEval());
+        m_mediaControlsStyleSheet = parseUASheet(mediaRules);
+        m_defaultStyle->addRulesFromSheet(m_mediaControlsStyleSheet, screenEval());
+        m_defaultPrintStyle->addRulesFromSheet(m_mediaControlsStyleSheet, printEval());
         changedDefaultStyle = true;
     }
 
     // FIXME: This only works because we Force recalc the entire document so the new sheet
     // is loaded for <html> and the correct styles apply to everyone.
-    if (!fullscreenStyleSheet && FullscreenElementStack::isFullScreen(&element->document())) {
+    if (!m_fullscreenStyleSheet && FullscreenElementStack::isFullScreen(&element->document())) {
         String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::theme().extraFullScreenStyleSheet();
-        fullscreenStyleSheet = parseUASheet(fullscreenRules);
-        defaultStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
-        defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
+        m_fullscreenStyleSheet = parseUASheet(fullscreenRules);
+        m_defaultStyle->addRulesFromSheet(m_fullscreenStyleSheet, screenEval());
+        m_defaultQuirksStyle->addRulesFromSheet(m_fullscreenStyleSheet, screenEval());
         changedDefaultStyle = true;
     }
 
-    ASSERT(defaultStyle->features().idsInRules.isEmpty());
-    ASSERT(defaultStyle->features().siblingRules.isEmpty());
+    ASSERT(!m_defaultStyle->features().hasIdsInSelectors());
+    ASSERT(m_defaultStyle->features().siblingRules.isEmpty());
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSDefaultStyleSheets.h b/Source/core/css/CSSDefaultStyleSheets.h
index c85fd22..69e69db 100644
--- a/Source/core/css/CSSDefaultStyleSheets.h
+++ b/Source/core/css/CSSDefaultStyleSheets.h
@@ -31,31 +31,42 @@
 
 class CSSDefaultStyleSheets {
 public:
-    static RuleSet* defaultStyle;
-    static RuleSet* defaultViewportStyle;
-    static RuleSet* defaultQuirksStyle;
-    static RuleSet* defaultPrintStyle;
-    static RuleSet* defaultViewSourceStyle;
-    static RuleSet* defaultXHTMLMobileProfileStyle;
+    static CSSDefaultStyleSheets& instance();
 
-    static StyleSheetContents* defaultStyleSheet;
-    static StyleSheetContents* viewportStyleSheet;
-    static StyleSheetContents* quirksStyleSheet;
-    static StyleSheetContents* svgStyleSheet;
-    static StyleSheetContents* mediaControlsStyleSheet;
-    static StyleSheetContents* fullscreenStyleSheet;
+    void ensureDefaultStyleSheetsForElement(Element*, bool& changedDefaultStyle);
 
-    static void ensureDefaultStyleSheetsForElement(Element*, bool& changedDefaultStyle);
-    // FIXME: defaultStyleSheet should have an accessor which incorporates this branch:
-    static void loadDefaultStylesheetIfNecessary();
-
-    static RuleSet* viewSourceStyle();
+    RuleSet* defaultStyle() { return m_defaultStyle;}
+    RuleSet* defaultViewportStyle() { return m_defaultViewportStyle;}
+    RuleSet* defaultQuirksStyle() { return m_defaultQuirksStyle;}
+    RuleSet* defaultPrintStyle() { return m_defaultPrintStyle;}
+    RuleSet* defaultViewSourceStyle();
 
     // FIXME: Remove WAP support.
-    static RuleSet* xhtmlMobileProfileStyle();
+    RuleSet* defaultXHTMLMobileProfileStyle();
+
+    StyleSheetContents* defaultStyleSheet() { return m_viewportStyleSheet; }
+    StyleSheetContents* viewportStyleSheet() { return m_viewportStyleSheet; }
+    StyleSheetContents* quirksStyleSheet() { return m_quirksStyleSheet; }
+    StyleSheetContents* svgStyleSheet() { return m_svgStyleSheet; }
+    StyleSheetContents* mediaControlsStyleSheet() { return m_mediaControlsStyleSheet; }
+    StyleSheetContents* fullscreenStyleSheet() { return m_fullscreenStyleSheet; }
 
 private:
-    static void loadDefaultStyle();
+    CSSDefaultStyleSheets();
+
+    RuleSet* m_defaultStyle;
+    RuleSet* m_defaultViewportStyle;
+    RuleSet* m_defaultQuirksStyle;
+    RuleSet* m_defaultPrintStyle;
+    RuleSet* m_defaultViewSourceStyle;
+    RuleSet* m_defaultXHTMLMobileProfileStyle;
+
+    StyleSheetContents* m_defaultStyleSheet;
+    StyleSheetContents* m_viewportStyleSheet;
+    StyleSheetContents* m_quirksStyleSheet;
+    StyleSheetContents* m_svgStyleSheet;
+    StyleSheetContents* m_mediaControlsStyleSheet;
+    StyleSheetContents* m_fullscreenStyleSheet;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSFilterRule.h b/Source/core/css/CSSFilterRule.h
index 9bb1b19..a8d5477 100644
--- a/Source/core/css/CSSFilterRule.h
+++ b/Source/core/css/CSSFilterRule.h
@@ -38,7 +38,7 @@
 class StyleRuleFilter;
 class StyleRuleCSSStyleDeclaration;
 
-class CSSFilterRule : public CSSRule {
+class CSSFilterRule FINAL : public CSSRule {
 public:
     static PassRefPtr<CSSFilterRule> create(StyleRuleFilter* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSFilterRule(rule, sheet)); }
 
diff --git a/Source/core/css/CSSFilterValue.cpp b/Source/core/css/CSSFilterValue.cpp
index 75567a7..1515614 100644
--- a/Source/core/css/CSSFilterValue.cpp
+++ b/Source/core/css/CSSFilterValue.cpp
@@ -26,66 +26,60 @@
 #include "config.h"
 #include "core/css/CSSFilterValue.h"
 
-#include "wtf/text/WTFString.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
 CSSFilterValue::CSSFilterValue(FilterOperationType operationType)
-    : CSSValueList(CSSFilterClass, typeUsesSpaceSeparator(operationType) ? SpaceSeparator : CommaSeparator)
+    : CSSValueList(CSSFilterClass, CommaSeparator)
     , m_type(operationType)
 {
 }
 
-bool CSSFilterValue::typeUsesSpaceSeparator(FilterOperationType operationType)
-{
-    return operationType != CustomFilterOperation;
-}
-
 String CSSFilterValue::customCSSText() const
 {
-    String result;
+    StringBuilder result;
     switch (m_type) {
     case ReferenceFilterOperation:
-        result = "url(";
+        result.append("url(");
         break;
     case GrayscaleFilterOperation:
-        result = "grayscale(";
+        result.append("grayscale(");
         break;
     case SepiaFilterOperation:
-        result = "sepia(";
+        result.append("sepia(");
         break;
     case SaturateFilterOperation:
-        result = "saturate(";
+        result.append("saturate(");
         break;
     case HueRotateFilterOperation:
-        result = "hue-rotate(";
+        result.append("hue-rotate(");
         break;
     case InvertFilterOperation:
-        result = "invert(";
+        result.append("invert(");
         break;
     case OpacityFilterOperation:
-        result = "opacity(";
+        result.append("opacity(");
         break;
     case BrightnessFilterOperation:
-        result = "brightness(";
+        result.append("brightness(");
         break;
     case ContrastFilterOperation:
-        result = "contrast(";
+        result.append("contrast(");
         break;
     case BlurFilterOperation:
-        result = "blur(";
+        result.append("blur(");
         break;
     case DropShadowFilterOperation:
-        result = "drop-shadow(";
-        break;
-    case CustomFilterOperation:
-        result = "custom(";
+        result.append("drop-shadow(");
         break;
     default:
         break;
     }
 
-    return result + CSSValueList::customCSSText() + ")";
+    result.append(CSSValueList::customCSSText());
+    result.append(')');
+    return result.toString();
 }
 
 CSSFilterValue::CSSFilterValue(const CSSFilterValue& cloneFrom)
@@ -94,9 +88,9 @@
 {
 }
 
-PassRefPtr<CSSFilterValue> CSSFilterValue::cloneForCSSOM() const
+PassRefPtrWillBeRawPtr<CSSFilterValue> CSSFilterValue::cloneForCSSOM() const
 {
-    return adoptRef(new CSSFilterValue(*this));
+    return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSFilterValue(*this));
 }
 
 bool CSSFilterValue::equals(const CSSFilterValue& other) const
diff --git a/Source/core/css/CSSFilterValue.h b/Source/core/css/CSSFilterValue.h
index 7a2f80c..1e3ab2a 100644
--- a/Source/core/css/CSSFilterValue.h
+++ b/Source/core/css/CSSFilterValue.h
@@ -47,24 +47,25 @@
         ContrastFilterOperation,
         BlurFilterOperation,
         DropShadowFilterOperation,
-        CustomFilterOperation
     };
 
     static bool typeUsesSpaceSeparator(FilterOperationType);
 
-    static PassRefPtr<CSSFilterValue> create(FilterOperationType type)
+    static PassRefPtrWillBeRawPtr<CSSFilterValue> create(FilterOperationType type)
     {
-        return adoptRef(new CSSFilterValue(type));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSFilterValue(type));
     }
 
     String customCSSText() const;
 
     FilterOperationType operationType() const { return m_type; }
 
-    PassRefPtr<CSSFilterValue> cloneForCSSOM() const;
+    PassRefPtrWillBeRawPtr<CSSFilterValue> cloneForCSSOM() const;
 
     bool equals(const CSSFilterValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValueList::traceAfterDispatch(visitor); }
+
 private:
     explicit CSSFilterValue(FilterOperationType);
     explicit CSSFilterValue(const CSSFilterValue& cloneFrom);
diff --git a/Source/core/css/CSSFontFace.cpp b/Source/core/css/CSSFontFace.cpp
index c21c912..bfb995e 100644
--- a/Source/core/css/CSSFontFace.cpp
+++ b/Source/core/css/CSSFontFace.cpp
@@ -35,50 +35,6 @@
 
 namespace WebCore {
 
-CSSFontFace::~CSSFontFace()
-{
-    m_fontFace->cssFontFaceDestroyed();
-}
-
-PassRefPtr<CSSFontFace> CSSFontFace::createFromStyleRule(Document* document, const StyleRuleFontFace* fontFaceRule)
-{
-    RefPtr<FontFace> fontFace = FontFace::create(fontFaceRule);
-    if (!fontFace || fontFace->family().isEmpty())
-        return 0;
-
-    unsigned traitsMask = fontFace->traitsMask();
-    if (!traitsMask)
-        return 0;
-
-    // FIXME: Plumbing back into createCSSFontFace seems odd.
-    // Maybe move FontFace::createCSSFontFace logic here?
-    RefPtr<CSSFontFace> cssFontFace = fontFace->createCSSFontFace(document);
-    if (!cssFontFace || !cssFontFace->isValid())
-        return 0;
-
-    return cssFontFace;
-}
-
-bool CSSFontFace::isLoaded() const
-{
-    size_t size = m_sources.size();
-    for (size_t i = 0; i < size; i++) {
-        if (!m_sources[i]->isLoaded())
-            return false;
-    }
-    return true;
-}
-
-bool CSSFontFace::isValid() const
-{
-    size_t size = m_sources.size();
-    for (size_t i = 0; i < size; i++) {
-        if (m_sources[i]->isValid())
-            return true;
-    }
-    return false;
-}
-
 void CSSFontFace::addSource(PassOwnPtr<CSSFontFaceSource> source)
 {
     source->setFontFace(this);
@@ -91,13 +47,14 @@
     m_segmentedFontFace = segmentedFontFace;
 }
 
-void CSSFontFace::beginLoadIfNeeded(CSSFontFaceSource* source)
+void CSSFontFace::beginLoadIfNeeded(CSSFontFaceSource* source, CSSFontSelector* fontSelector)
 {
-    if (!m_segmentedFontFace)
-        return;
-
     if (source->resource() && source->resource()->stillNeedsLoad()) {
-        CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
+        if (!fontSelector) {
+            if (!m_segmentedFontFace)
+                return;
+            fontSelector = m_segmentedFontFace->fontSelector();
+        }
         fontSelector->beginLoadingFontSoon(source->resource());
     }
 
@@ -107,48 +64,41 @@
 
 void CSSFontFace::fontLoaded(CSSFontFaceSource* source)
 {
-    if (source != m_activeSource)
-        return;
-    m_activeSource = 0;
-
-    // FIXME: Can we assert that m_segmentedFontFace is non-null? That may
-    // require stopping in-progress font loading when the last
-    // CSSSegmentedFontFace is removed.
-    if (!m_segmentedFontFace)
+    if (!isValid() || source != m_sources.first())
         return;
 
-    CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
-    fontSelector->fontLoaded();
-
-    if (fontSelector->document() && loadStatus() == FontFace::Loading) {
+    if (loadStatus() == FontFace::Loading) {
         if (source->ensureFontData()) {
             setLoadStatus(FontFace::Loaded);
-            if (source->isSVGFontFaceSource())
-                UseCounter::count(*fontSelector->document(), UseCounter::SVGFontInCSS);
+            Document* document = m_segmentedFontFace ? m_segmentedFontFace->fontSelector()->document() : 0;
+            if (document && source->isSVGFontFaceSource())
+                UseCounter::count(*document, UseCounter::SVGFontInCSS);
+        } else {
+            m_sources.removeFirst();
+            if (!isValid())
+                setLoadStatus(FontFace::Error);
         }
-        else if (!isValid())
-            setLoadStatus(FontFace::Error);
     }
 
-    m_segmentedFontFace->fontLoaded(this);
+    if (m_segmentedFontFace)
+        m_segmentedFontFace->fontLoaded(this);
 }
 
 PassRefPtr<SimpleFontData> CSSFontFace::getFontData(const FontDescription& fontDescription)
 {
-    m_activeSource = 0;
     if (!isValid())
         return 0;
 
-    size_t size = m_sources.size();
-    for (size_t i = 0; i < size; ++i) {
-        if (RefPtr<SimpleFontData> result = m_sources[i]->getFontData(fontDescription)) {
-            m_activeSource = m_sources[i].get();
-            if (loadStatus() == FontFace::Unloaded && (m_sources[i]->isLoading() || m_sources[i]->isLoaded()))
+    while (!m_sources.isEmpty()) {
+        OwnPtr<CSSFontFaceSource>& source = m_sources.first();
+        if (RefPtr<SimpleFontData> result = source->getFontData(fontDescription)) {
+            if (loadStatus() == FontFace::Unloaded && (source->isLoading() || source->isLoaded()))
                 setLoadStatus(FontFace::Loading);
-            if (loadStatus() == FontFace::Loading && m_sources[i]->isLoaded())
+            if (loadStatus() == FontFace::Loading && source->isLoaded())
                 setLoadStatus(FontFace::Loaded);
             return result.release();
         }
+        m_sources.removeFirst();
     }
 
     if (loadStatus() == FontFace::Unloaded)
@@ -160,30 +110,42 @@
 
 void CSSFontFace::willUseFontData(const FontDescription& fontDescription)
 {
-    if (loadStatus() != FontFace::Unloaded || m_activeSource)
-        return;
-
     // Kicks off font load here only if the @font-face has no unicode-range.
     // @font-faces with unicode-range will be loaded when a GlyphPage for the
     // font is created.
     // FIXME: Pass around the text to render from RenderText, and kick download
     // if m_ranges intersects with the text. Make sure this does not cause
     // performance regression.
-    if (!m_ranges.isEntireRange())
+    if (m_ranges.isEntireRange())
+        load(fontDescription);
+}
+
+void CSSFontFace::load(const FontDescription& fontDescription, CSSFontSelector* fontSelector)
+{
+    if (loadStatus() != FontFace::Unloaded)
         return;
+    setLoadStatus(FontFace::Loading);
 
-    ASSERT(m_segmentedFontFace);
-
-    size_t size = m_sources.size();
-    for (size_t i = 0; i < size; ++i) {
-        if (!m_sources[i]->isValid() || (m_sources[i]->isLocal() && !m_sources[i]->isLocalFontAvailable(fontDescription)))
-            continue;
-        if (!m_sources[i]->isLocal() && !m_sources[i]->isLoaded()) {
-            m_activeSource = m_sources[i].get();
-            beginLoadIfNeeded(m_activeSource);
+    while (!m_sources.isEmpty()) {
+        OwnPtr<CSSFontFaceSource>& source = m_sources.first();
+        if (source->isValid()) {
+            if (source->isLocal()) {
+                if (source->isLocalFontAvailable(fontDescription)) {
+                    setLoadStatus(FontFace::Loaded);
+                    return;
+                }
+            } else {
+                if (!source->isLoaded()) {
+                    beginLoadIfNeeded(source.get(), fontSelector);
+                } else {
+                    setLoadStatus(FontFace::Loaded);
+                }
+                return;
+            }
         }
-        break;
+        m_sources.removeFirst();
     }
+    setLoadStatus(FontFace::Error);
 }
 
 void CSSFontFace::setLoadStatus(FontFace::LoadStatus newStatus)
@@ -199,13 +161,13 @@
 
     switch (newStatus) {
     case FontFace::Loading:
-        FontFaceSet::from(document)->beginFontLoading(m_fontFace.get());
+        FontFaceSet::from(document)->beginFontLoading(m_fontFace);
         break;
     case FontFace::Loaded:
-        FontFaceSet::from(document)->fontLoaded(m_fontFace.get());
+        FontFaceSet::from(document)->fontLoaded(m_fontFace);
         break;
     case FontFace::Error:
-        FontFaceSet::from(document)->loadError(m_fontFace.get());
+        FontFaceSet::from(document)->loadError(m_fontFace);
         break;
     default:
         break;
diff --git a/Source/core/css/CSSFontFace.h b/Source/core/css/CSSFontFace.h
index e4ad5f0..4ce02b2 100644
--- a/Source/core/css/CSSFontFace.h
+++ b/Source/core/css/CSSFontFace.h
@@ -28,42 +28,43 @@
 
 #include "core/css/CSSFontFaceSource.h"
 #include "core/css/FontFace.h"
+#include "wtf/Deque.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
+class CSSFontSelector;
 class CSSSegmentedFontFace;
 class Document;
 class FontDescription;
 class SimpleFontData;
 class StyleRuleFontFace;
 
-// FIXME: Can this be a subclass of FontFace?
-class CSSFontFace : public RefCounted<CSSFontFace> {
+class CSSFontFace {
 public:
-    static PassRefPtr<CSSFontFace> create(PassRefPtr<FontFace> fontFace) { return adoptRef(new CSSFontFace(fontFace)); }
-    static PassRefPtr<CSSFontFace> createFromStyleRule(Document*, const StyleRuleFontFace*);
-
     class UnicodeRangeSet;
 
-    ~CSSFontFace();
+    CSSFontFace(FontFace* fontFace)
+        : m_segmentedFontFace(0)
+        , m_fontFace(fontFace)
+    {
+        ASSERT(m_fontFace);
+    }
 
-    FontFace* fontFace() const { return m_fontFace.get(); }
+    FontFace* fontFace() const { return m_fontFace; }
 
     UnicodeRangeSet& ranges() { return m_ranges; }
 
     void setSegmentedFontFace(CSSSegmentedFontFace*);
     void clearSegmentedFontFace() { m_segmentedFontFace = 0; }
 
-    bool isLoaded() const;
-    bool isValid() const;
+    bool isValid() const { return !m_sources.isEmpty(); }
 
     void addSource(PassOwnPtr<CSSFontFaceSource>);
 
-    void beginLoadIfNeeded(CSSFontFaceSource*);
+    void beginLoadIfNeeded(CSSFontFaceSource*, CSSFontSelector* = 0);
     void fontLoaded(CSSFontFaceSource*);
 
     PassRefPtr<SimpleFontData> getFontData(const FontDescription&);
@@ -97,22 +98,15 @@
 
     FontFace::LoadStatus loadStatus() const { return m_fontFace->loadStatus(); }
     void willUseFontData(const FontDescription&);
+    void load(const FontDescription&, CSSFontSelector* = 0);
 
 private:
-    CSSFontFace(PassRefPtr<FontFace> fontFace)
-        : m_segmentedFontFace(0)
-        , m_activeSource(0)
-        , m_fontFace(fontFace)
-    {
-        ASSERT(m_fontFace);
-    }
     void setLoadStatus(FontFace::LoadStatus);
 
     UnicodeRangeSet m_ranges;
     CSSSegmentedFontFace* m_segmentedFontFace;
-    Vector<OwnPtr<CSSFontFaceSource> > m_sources;
-    CSSFontFaceSource* m_activeSource;
-    RefPtr<FontFace> m_fontFace;
+    Deque<OwnPtr<CSSFontFaceSource> > m_sources;
+    FontFace* m_fontFace;
 };
 
 }
diff --git a/Source/core/css/CSSFontFaceLoadEvent.h b/Source/core/css/CSSFontFaceLoadEvent.h
index e77ca32..6d6b982 100644
--- a/Source/core/css/CSSFontFaceLoadEvent.h
+++ b/Source/core/css/CSSFontFaceLoadEvent.h
@@ -44,7 +44,7 @@
     FontFaceArray fontfaces;
 };
 
-class CSSFontFaceLoadEvent : public Event {
+class CSSFontFaceLoadEvent FINAL : public Event {
 public:
     static PassRefPtr<CSSFontFaceLoadEvent> create()
     {
@@ -65,7 +65,7 @@
 
     FontFaceArray fontfaces() const { return m_fontfaces; }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     CSSFontFaceLoadEvent();
diff --git a/Source/core/css/CSSFontFaceRule.h b/Source/core/css/CSSFontFaceRule.h
index 0b88f9b..2b779a2 100644
--- a/Source/core/css/CSSFontFaceRule.h
+++ b/Source/core/css/CSSFontFaceRule.h
@@ -30,7 +30,7 @@
 class StyleRuleFontFace;
 class StyleRuleCSSStyleDeclaration;
 
-class CSSFontFaceRule : public CSSRule {
+class CSSFontFaceRule FINAL : public CSSRule {
 public:
     static PassRefPtr<CSSFontFaceRule> create(StyleRuleFontFace* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSFontFaceRule(rule, sheet)); }
 
diff --git a/Source/core/css/CSSFontFaceSource.cpp b/Source/core/css/CSSFontFaceSource.cpp
index d235aea..baef101 100644
--- a/Source/core/css/CSSFontFaceSource.cpp
+++ b/Source/core/css/CSSFontFaceSource.cpp
@@ -144,7 +144,7 @@
     AtomicString emptyFontFamily = "";
     FontCacheKey key = fontDescription.cacheKey(emptyFontFamily);
 
-    RefPtr<SimpleFontData>& fontData = m_fontDataTable.add(key.hash(), 0).iterator->value;
+    RefPtr<SimpleFontData>& fontData = m_fontDataTable.add(key.hash(), 0).storedValue->value;
     if (fontData)
         return fontData; // No release, because fontData is a reference to a RefPtr that is held in the m_fontDataTable.
 
@@ -219,6 +219,10 @@
         // This temporary font is not retained and should not be returned.
         FontCachePurgePreventer fontCachePurgePreventer;
         SimpleFontData* temporaryFont = FontCache::fontCache()->getNonRetainedLastResortFallbackFont(fontDescription);
+        if (!temporaryFont) {
+            ASSERT_NOT_REACHED();
+            return 0;
+        }
         RefPtr<CSSCustomFontData> cssFontData = CSSCustomFontData::create(true);
         cssFontData->setCSSFontFaceSource(this);
         fontData = SimpleFontData::create(temporaryFont->platformData(), cssFontData);
diff --git a/Source/core/css/CSSFontFaceSource.h b/Source/core/css/CSSFontFaceSource.h
index 8ba3f02..0d434f7 100644
--- a/Source/core/css/CSSFontFaceSource.h
+++ b/Source/core/css/CSSFontFaceSource.h
@@ -44,7 +44,7 @@
 #endif
 
 
-class CSSFontFaceSource : public FontResourceClient {
+class CSSFontFaceSource FINAL : public FontResourceClient {
 public:
     CSSFontFaceSource(const String&, FontResource* = 0);
     virtual ~CSSFontFaceSource();
@@ -58,7 +58,7 @@
     void setFontFace(CSSFontFace* face) { m_face = face; }
 
     virtual void didStartFontLoad(FontResource*) OVERRIDE;
-    virtual void fontLoaded(FontResource*);
+    virtual void fontLoaded(FontResource*) OVERRIDE;
 
     PassRefPtr<SimpleFontData> getFontData(const FontDescription&);
 
diff --git a/Source/core/css/CSSFontFaceSrcValue.cpp b/Source/core/css/CSSFontFaceSrcValue.cpp
index 9e7f212..5ccf754 100644
--- a/Source/core/css/CSSFontFaceSrcValue.cpp
+++ b/Source/core/css/CSSFontFaceSrcValue.cpp
@@ -81,12 +81,6 @@
     return result.toString();
 }
 
-void CSSFontFaceSrcValue::addSubresourceStyleURLs(ListHashSet<KURL>& urls, const StyleSheetContents* styleSheet) const
-{
-    if (!isLocal())
-        addSubresourceURL(urls, styleSheet->completeURL(m_resource));
-}
-
 bool CSSFontFaceSrcValue::hasFailedOrCanceledSubresources() const
 {
     if (!m_fetched)
diff --git a/Source/core/css/CSSFontFaceSrcValue.h b/Source/core/css/CSSFontFaceSrcValue.h
index 1be94d6..c394924 100644
--- a/Source/core/css/CSSFontFaceSrcValue.h
+++ b/Source/core/css/CSSFontFaceSrcValue.h
@@ -39,13 +39,13 @@
 
 class CSSFontFaceSrcValue : public CSSValue {
 public:
-    static PassRefPtr<CSSFontFaceSrcValue> create(const String& resource)
+    static PassRefPtrWillBeRawPtr<CSSFontFaceSrcValue> create(const String& resource)
     {
-        return adoptRef(new CSSFontFaceSrcValue(resource, false));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSFontFaceSrcValue(resource, false));
     }
-    static PassRefPtr<CSSFontFaceSrcValue> createLocal(const String& resource)
+    static PassRefPtrWillBeRawPtr<CSSFontFaceSrcValue> createLocal(const String& resource)
     {
-        return adoptRef(new CSSFontFaceSrcValue(resource, true));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSFontFaceSrcValue(resource, true));
     }
 
     const String& resource() const { return m_resource; }
@@ -65,14 +65,14 @@
 
     String customCSSText() const;
 
-    void addSubresourceStyleURLs(ListHashSet<KURL>&, const StyleSheetContents*) const;
-
     bool hasFailedOrCanceledSubresources() const;
 
     FontResource* fetch(Document*);
 
     bool equals(const CSSFontFaceSrcValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     CSSFontFaceSrcValue(const String& resource, bool local)
         : CSSValue(FontFaceSrcClass)
diff --git a/Source/core/css/CSSFontFeatureValue.h b/Source/core/css/CSSFontFeatureValue.h
index 8a0367f..b7148c4 100644
--- a/Source/core/css/CSSFontFeatureValue.h
+++ b/Source/core/css/CSSFontFeatureValue.h
@@ -33,9 +33,9 @@
 
 class CSSFontFeatureValue : public CSSValue {
 public:
-    static PassRefPtr<CSSFontFeatureValue> create(const AtomicString& tag, int value)
+    static PassRefPtrWillBeRawPtr<CSSFontFeatureValue> create(const AtomicString& tag, int value)
     {
-        return adoptRef(new CSSFontFeatureValue(tag, value));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSFontFeatureValue(tag, value));
     }
 
     const AtomicString& tag() const { return m_tag; }
@@ -44,6 +44,8 @@
 
     bool equals(const CSSFontFeatureValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     CSSFontFeatureValue(const AtomicString& tag, int value);
 
diff --git a/Source/core/css/CSSFontSelector.cpp b/Source/core/css/CSSFontSelector.cpp
index 4f98ea0..be43180 100644
--- a/Source/core/css/CSSFontSelector.cpp
+++ b/Source/core/css/CSSFontSelector.cpp
@@ -28,18 +28,16 @@
 #include "core/css/CSSFontSelector.h"
 
 #include "RuntimeEnabledFeatures.h"
-#include "core/css/CSSFontFace.h"
-#include "core/css/CSSFontFaceRule.h"
-#include "core/css/CSSFontFaceSource.h"
 #include "core/css/CSSSegmentedFontFace.h"
 #include "core/css/CSSValueList.h"
+#include "core/css/FontFaceSet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/fetch/FontResource.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/loader/FrameLoader.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/fonts/SimpleFontData.h"
 #include "wtf/text/AtomicString.h"
@@ -117,6 +115,7 @@
     ASSERT(m_document);
     ASSERT(m_document->frame());
     FontCache::fontCache()->addClient(this);
+    FontFaceSet::from(document)->addFontFacesToFontFaceCache(&m_fontFaceCache, this);
 }
 
 CSSFontSelector::~CSSFontSelector()
@@ -125,19 +124,19 @@
     FontCache::fontCache()->removeClient(this);
 }
 
-void CSSFontSelector::registerForInvalidationCallbacks(FontSelectorClient* client)
+void CSSFontSelector::registerForInvalidationCallbacks(CSSFontSelectorClient* client)
 {
     m_clients.add(client);
 }
 
-void CSSFontSelector::unregisterForInvalidationCallbacks(FontSelectorClient* client)
+void CSSFontSelector::unregisterForInvalidationCallbacks(CSSFontSelectorClient* client)
 {
     m_clients.remove(client);
 }
 
 void CSSFontSelector::dispatchInvalidationCallbacks()
 {
-    Vector<FontSelectorClient*> clients;
+    Vector<CSSFontSelectorClient*> clients;
     copyToVector(m_clients, clients);
     for (size_t i = 0; i < clients.size(); ++i)
         clients[i]->fontsNeedUpdate(this);
@@ -153,16 +152,6 @@
     dispatchInvalidationCallbacks();
 }
 
-void CSSFontSelector::addFontFaceRule(const StyleRuleFontFace* fontFaceRule, PassRefPtr<CSSFontFace> cssFontFace)
-{
-    m_cssSegmentedFontFaceCache.add(this, fontFaceRule, cssFontFace);
-}
-
-void CSSFontSelector::removeFontFaceRule(const StyleRuleFontFace* fontFaceRule)
-{
-    m_cssSegmentedFontFaceCache.remove(fontFaceRule);
-}
-
 static AtomicString familyNameFromSettings(const GenericFontFamilySettings& settings, const FontDescription& fontDescription, const AtomicString& genericFamilyName)
 {
     UScriptCode script = fontDescription.script();
@@ -193,7 +182,7 @@
 
 PassRefPtr<FontData> CSSFontSelector::getFontData(const FontDescription& fontDescription, const AtomicString& familyName)
 {
-    if (CSSSegmentedFontFace* face = m_cssSegmentedFontFaceCache.get(fontDescription, familyName))
+    if (CSSSegmentedFontFace* face = m_fontFaceCache.get(fontDescription, familyName))
         return face->getFontData(fontDescription);
 
     // Try to return the correct font based off our settings, in case we were handed the generic font family name.
@@ -204,14 +193,9 @@
     return FontCache::fontCache()->getFontData(fontDescription, settingsFamilyName);
 }
 
-CSSSegmentedFontFace* CSSFontSelector::getFontFace(const FontDescription& fontDescription, const AtomicString& familyName)
-{
-    return m_cssSegmentedFontFaceCache.get(fontDescription, familyName);
-}
-
 void CSSFontSelector::willUseFontData(const FontDescription& fontDescription, const AtomicString& family)
 {
-    CSSSegmentedFontFace* face = getFontFace(fontDescription, family);
+    CSSSegmentedFontFace* face = m_fontFaceCache.get(fontDescription, family);
     if (face)
         face->willUseFontData(fontDescription);
 }
@@ -232,4 +216,10 @@
     m_fontLoader.loadPendingFonts();
 }
 
+void CSSFontSelector::updateGenericFontFamilySettings(Document& document)
+{
+    ASSERT(document.settings());
+    m_genericFontFamilySettings = document.settings()->genericFontFamilySettings();
+}
+
 }
diff --git a/Source/core/css/CSSFontSelector.h b/Source/core/css/CSSFontSelector.h
index 34d33a8..cb6e392 100644
--- a/Source/core/css/CSSFontSelector.h
+++ b/Source/core/css/CSSFontSelector.h
@@ -26,7 +26,7 @@
 #ifndef CSSFontSelector_h
 #define CSSFontSelector_h
 
-#include "core/css/CSSSegmentedFontFaceCache.h"
+#include "core/css/FontFaceCache.h"
 #include "core/fetch/ResourcePtr.h"
 #include "platform/Timer.h"
 #include "platform/fonts/FontSelector.h"
@@ -39,6 +39,7 @@
 
 class CSSFontFace;
 class CSSFontFaceRule;
+class CSSFontSelectorClient;
 class CSSSegmentedFontFace;
 class FontResource;
 class Document;
@@ -62,7 +63,7 @@
     ResourceFetcher* m_resourceFetcher;
 };
 
-class CSSFontSelector : public FontSelector {
+class CSSFontSelector FINAL : public FontSelector {
 public:
     static PassRefPtr<CSSFontSelector> create(Document* document)
     {
@@ -70,26 +71,26 @@
     }
     virtual ~CSSFontSelector();
 
-    virtual unsigned version() const OVERRIDE { return m_cssSegmentedFontFaceCache.version(); }
+    virtual unsigned version() const OVERRIDE { return m_fontFaceCache.version(); }
 
-    virtual PassRefPtr<FontData> getFontData(const FontDescription&, const AtomicString&);
-    CSSSegmentedFontFace* getFontFace(const FontDescription&, const AtomicString& family);
+    virtual PassRefPtr<FontData> getFontData(const FontDescription&, const AtomicString&) OVERRIDE;
     virtual void willUseFontData(const FontDescription&, const AtomicString& family) OVERRIDE;
 
     void clearDocument();
 
-    void addFontFaceRule(const StyleRuleFontFace*, PassRefPtr<CSSFontFace>);
-    void removeFontFaceRule(const StyleRuleFontFace*);
-
     void fontLoaded();
-    virtual void fontCacheInvalidated();
 
-    virtual void registerForInvalidationCallbacks(FontSelectorClient*);
-    virtual void unregisterForInvalidationCallbacks(FontSelectorClient*);
+    // FontCacheClient implementation
+    virtual void fontCacheInvalidated() OVERRIDE;
+
+    void registerForInvalidationCallbacks(CSSFontSelectorClient*);
+    void unregisterForInvalidationCallbacks(CSSFontSelectorClient*);
 
     Document* document() const { return m_document; }
+    FontFaceCache* fontFaceCache() { return &m_fontFaceCache; }
 
     const GenericFontFamilySettings& genericFontFamilySettings() const { return m_genericFontFamilySettings; }
+    void updateGenericFontFamilySettings(Document&);
 
     void beginLoadingFontSoon(FontResource*);
     void loadPendingFonts();
@@ -101,8 +102,8 @@
 
     Document* m_document;
     // FIXME: Move to Document or StyleEngine.
-    CSSSegmentedFontFaceCache m_cssSegmentedFontFaceCache;
-    HashSet<FontSelectorClient*> m_clients;
+    FontFaceCache m_fontFaceCache;
+    HashSet<CSSFontSelectorClient*> m_clients;
 
     FontLoader m_fontLoader;
     GenericFontFamilySettings m_genericFontFamilySettings;
diff --git a/Source/core/platform/chromium/KeyCodeConversion.h b/Source/core/css/CSSFontSelectorClient.h
similarity index 82%
rename from Source/core/platform/chromium/KeyCodeConversion.h
rename to Source/core/css/CSSFontSelectorClient.h
index 0257f5b..28a6c87 100644
--- a/Source/core/platform/chromium/KeyCodeConversion.h
+++ b/Source/core/css/CSSFontSelectorClient.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,13 +28,20 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef KeyCodeConversion_h
-#define KeyCodeConversion_h
+#ifndef CSSFontSelectorClient_h
+#define CSSFontSelectorClient_h
 
 namespace WebCore {
 
-    int windowsKeyCodeForKeyEvent(unsigned keycode);
+class CSSFontSelector;
+
+class CSSFontSelectorClient {
+public:
+    virtual ~CSSFontSelectorClient() { }
+
+    virtual void fontsNeedUpdate(CSSFontSelector*) = 0;
+};
 
 } // namespace WebCore
 
-#endif
+#endif // CSSFontSelectorClient_h
diff --git a/Source/core/css/CSSFontValue.cpp b/Source/core/css/CSSFontValue.cpp
index aee5a97..522c7f8 100644
--- a/Source/core/css/CSSFontValue.cpp
+++ b/Source/core/css/CSSFontValue.cpp
@@ -74,4 +74,16 @@
         && compareCSSValuePtr(family, other.family);
 }
 
+void CSSFontValue::traceAfterDispatch(Visitor* visitor)
+{
+
+    visitor->trace(style);
+    visitor->trace(variant);
+    visitor->trace(weight);
+    visitor->trace(size);
+    visitor->trace(lineHeight);
+    visitor->trace(family);
+    CSSValue::traceAfterDispatch(visitor);
+}
+
 }
diff --git a/Source/core/css/CSSFontValue.h b/Source/core/css/CSSFontValue.h
index f0c99d5..cf3e97e 100644
--- a/Source/core/css/CSSFontValue.h
+++ b/Source/core/css/CSSFontValue.h
@@ -32,21 +32,23 @@
 
 class CSSFontValue : public CSSValue {
 public:
-    static PassRefPtr<CSSFontValue> create()
+    static PassRefPtrWillBeRawPtr<CSSFontValue> create()
     {
-        return adoptRef(new CSSFontValue);
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSFontValue);
     }
 
     String customCSSText() const;
 
     bool equals(const CSSFontValue&) const;
 
-    RefPtr<CSSPrimitiveValue> style;
-    RefPtr<CSSPrimitiveValue> variant;
-    RefPtr<CSSPrimitiveValue> weight;
-    RefPtr<CSSPrimitiveValue> size;
-    RefPtr<CSSPrimitiveValue> lineHeight;
-    RefPtr<CSSValueList> family;
+    void traceAfterDispatch(Visitor*);
+
+    RefPtrWillBeMember<CSSPrimitiveValue> style;
+    RefPtrWillBeMember<CSSPrimitiveValue> variant;
+    RefPtrWillBeMember<CSSPrimitiveValue> weight;
+    RefPtrWillBeMember<CSSPrimitiveValue> size;
+    RefPtrWillBeMember<CSSPrimitiveValue> lineHeight;
+    RefPtrWillBeMember<CSSValueList> family;
 
 private:
     CSSFontValue()
diff --git a/Source/core/css/CSSFunctionValue.cpp b/Source/core/css/CSSFunctionValue.cpp
index 7cbbf86..9fb04dc 100644
--- a/Source/core/css/CSSFunctionValue.cpp
+++ b/Source/core/css/CSSFunctionValue.cpp
@@ -40,7 +40,7 @@
         m_args = CSSValueList::createFromParserValueList(function->args.get());
 }
 
-CSSFunctionValue::CSSFunctionValue(String name, PassRefPtr<CSSValueList> args)
+CSSFunctionValue::CSSFunctionValue(String name, PassRefPtrWillBeRawPtr<CSSValueList> args)
     : CSSValue(FunctionClass)
     , m_name(name)
     , m_args(args)
@@ -62,4 +62,10 @@
     return m_name == other.m_name && compareCSSValuePtr(m_args, other.m_args);
 }
 
+void CSSFunctionValue::traceAfterDispatch(Visitor* visitor)
+{
+    visitor->trace(m_args);
+    CSSValue::traceAfterDispatch(visitor);
+}
+
 }
diff --git a/Source/core/css/CSSFunctionValue.h b/Source/core/css/CSSFunctionValue.h
index 87fa8af..b094a5e 100644
--- a/Source/core/css/CSSFunctionValue.h
+++ b/Source/core/css/CSSFunctionValue.h
@@ -35,14 +35,14 @@
 
 class CSSFunctionValue : public CSSValue {
 public:
-    static PassRefPtr<CSSFunctionValue> create(CSSParserFunction* function)
+    static PassRefPtrWillBeRawPtr<CSSFunctionValue> create(CSSParserFunction* function)
     {
-        return adoptRef(new CSSFunctionValue(function));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSFunctionValue(function));
     }
 
-    static PassRefPtr<CSSFunctionValue> create(String name, PassRefPtr<CSSValueList> args)
+    static PassRefPtrWillBeRawPtr<CSSFunctionValue> create(String name, PassRefPtrWillBeRawPtr<CSSValueList> args)
     {
-        return adoptRef(new CSSFunctionValue(name, args));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSFunctionValue(name, args));
     }
 
     String customCSSText() const;
@@ -51,12 +51,14 @@
 
     CSSValueList* arguments() const { return m_args.get(); }
 
+    void traceAfterDispatch(Visitor*);
+
 private:
     explicit CSSFunctionValue(CSSParserFunction*);
-    CSSFunctionValue(String, PassRefPtr<CSSValueList>);
+    CSSFunctionValue(String, PassRefPtrWillBeRawPtr<CSSValueList>);
 
     String m_name;
-    RefPtr<CSSValueList> m_args;
+    RefPtrWillBeMember<CSSValueList> m_args;
 };
 
 DEFINE_CSS_VALUE_TYPE_CASTS(CSSFunctionValue, isFunctionValue());
diff --git a/Source/core/css/CSSGradientValue.cpp b/Source/core/css/CSSGradientValue.cpp
index 6826997..a5bbb78 100644
--- a/Source/core/css/CSSGradientValue.cpp
+++ b/Source/core/css/CSSGradientValue.cpp
@@ -43,6 +43,12 @@
 
 namespace WebCore {
 
+void CSSGradientColorStop::trace(Visitor* visitor)
+{
+    visitor->trace(m_position);
+    visitor->trace(m_color);
+}
+
 PassRefPtr<Image> CSSGradientValue::image(RenderObject* renderer, const IntSize& size)
 {
     if (size.isEmpty())
@@ -63,7 +69,7 @@
     RefPtr<Gradient> gradient;
 
     RenderStyle* rootStyle = renderer->document().documentElement()->renderStyle();
-    CSSToLengthConversionData conversionData(renderer->style(), rootStyle);
+    CSSToLengthConversionData conversionData(renderer->style(), rootStyle, renderer->view());
     if (isLinearGradientValue())
         gradient = toCSSLinearGradientValue(this)->createGradient(conversionData, size);
     else
@@ -106,7 +112,7 @@
     { }
 };
 
-PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(const TextLinkColors& textLinkColors, Color currentColor)
+PassRefPtrWillBeRawPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(const TextLinkColors& textLinkColors, Color currentColor)
 {
     bool derived = false;
     for (unsigned i = 0; i < m_stops.size(); i++)
@@ -116,7 +122,7 @@
             break;
         }
 
-    RefPtr<CSSGradientValue> result;
+    RefPtrWillBeRawPtr<CSSGradientValue> result;
     if (!derived)
         result = this;
     else if (isLinearGradientValue())
@@ -262,7 +268,6 @@
             stops.first().offset = 0;
             stops.first().color = stops.last().color;
             stops.shrink(1);
-            numStops = 1;
         } else {
             float maxExtent = 1;
 
@@ -460,6 +465,16 @@
     return true;
 }
 
+void CSSGradientValue::traceAfterDispatch(Visitor* visitor)
+{
+    visitor->trace(m_firstX);
+    visitor->trace(m_firstY);
+    visitor->trace(m_secondX);
+    visitor->trace(m_secondY);
+    visitor->trace(m_stops);
+    CSSImageGeneratorValue::traceAfterDispatch(visitor);
+}
+
 String CSSLinearGradientValue::customCSSText() const
 {
     StringBuilder result;
@@ -733,6 +748,12 @@
     return equalXandY && m_stops == other.m_stops;
 }
 
+void CSSLinearGradientValue::traceAfterDispatch(Visitor* visitor)
+{
+    visitor->trace(m_angle);
+    CSSGradientValue::traceAfterDispatch(visitor);
+}
+
 String CSSRadialGradientValue::customCSSText() const
 {
     StringBuilder result;
@@ -1161,4 +1182,15 @@
     return equalShape && equalSizingBehavior && equalHorizontalAndVerticalSize && m_stops == other.m_stops;
 }
 
+void CSSRadialGradientValue::traceAfterDispatch(Visitor* visitor)
+{
+    visitor->trace(m_firstRadius);
+    visitor->trace(m_secondRadius);
+    visitor->trace(m_shape);
+    visitor->trace(m_sizingBehavior);
+    visitor->trace(m_endHorizontalSize);
+    visitor->trace(m_endVerticalSize);
+    CSSGradientValue::traceAfterDispatch(visitor);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSGradientValue.h b/Source/core/css/CSSGradientValue.h
index 7179b6f..9b29da6 100644
--- a/Source/core/css/CSSGradientValue.h
+++ b/Source/core/css/CSSGradientValue.h
@@ -47,10 +47,17 @@
 };
 enum CSSGradientRepeat { NonRepeating, Repeating };
 
+// This struct is stack allocated and allocated as part of vectors.
+// When allocated on the stack its members are found by conservative
+// stack scanning. When allocated as part of Vectors in heap-allocated
+// objects its members are visited via the containing object's
+// (CSSGradientValue) traceAfterDispatch method.
 struct CSSGradientColorStop {
+    ALLOW_ONLY_INLINE_ALLOCATION();
+public:
     CSSGradientColorStop() : m_colorIsDerivedFromElement(false) { };
-    RefPtr<CSSPrimitiveValue> m_position; // percentage or length
-    RefPtr<CSSPrimitiveValue> m_color;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_position; // percentage or length
+    RefPtrWillBeMember<CSSPrimitiveValue> m_color;
     Color m_resolvedColor;
     bool m_colorIsDerivedFromElement;
     bool operator==(const CSSGradientColorStop& other) const
@@ -58,16 +65,18 @@
         return compareCSSValuePtr(m_color, other.m_color)
             && compareCSSValuePtr(m_position, other.m_position);
     }
+
+    void trace(Visitor*);
 };
 
 class CSSGradientValue : public CSSImageGeneratorValue {
 public:
     PassRefPtr<Image> image(RenderObject*, const IntSize&);
 
-    void setFirstX(PassRefPtr<CSSPrimitiveValue> val) { m_firstX = val; }
-    void setFirstY(PassRefPtr<CSSPrimitiveValue> val) { m_firstY = val; }
-    void setSecondX(PassRefPtr<CSSPrimitiveValue> val) { m_secondX = val; }
-    void setSecondY(PassRefPtr<CSSPrimitiveValue> val) { m_secondY = val; }
+    void setFirstX(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_firstX = val; }
+    void setFirstY(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_firstY = val; }
+    void setSecondX(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_secondX = val; }
+    void setSecondY(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_secondY = val; }
 
     void addStop(const CSSGradientColorStop& stop) { m_stops.append(stop); }
 
@@ -86,7 +95,9 @@
     bool knownToBeOpaque(const RenderObject*) const;
 
     void loadSubimages(ResourceFetcher*) { }
-    PassRefPtr<CSSGradientValue> gradientWithStylesResolved(const TextLinkColors&, Color currentColor);
+    PassRefPtrWillBeRawPtr<CSSGradientValue> gradientWithStylesResolved(const TextLinkColors&, Color currentColor);
+
+    void traceAfterDispatch(Visitor*);
 
 protected:
     CSSGradientValue(ClassType classType, CSSGradientRepeat repeat, CSSGradientType gradientType)
@@ -118,14 +129,14 @@
     bool isCacheable() const;
 
     // Points. Some of these may be null.
-    RefPtr<CSSPrimitiveValue> m_firstX;
-    RefPtr<CSSPrimitiveValue> m_firstY;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_firstX;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_firstY;
 
-    RefPtr<CSSPrimitiveValue> m_secondX;
-    RefPtr<CSSPrimitiveValue> m_secondY;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_secondX;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_secondY;
 
     // Stops
-    Vector<CSSGradientColorStop, 2> m_stops;
+    WillBeHeapVector<CSSGradientColorStop, 2> m_stops;
     bool m_stopsSorted;
     CSSGradientType m_gradientType;
     bool m_repeating;
@@ -136,25 +147,27 @@
 class CSSLinearGradientValue : public CSSGradientValue {
 public:
 
-    static PassRefPtr<CSSLinearGradientValue> create(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSLinearGradient)
+    static PassRefPtrWillBeRawPtr<CSSLinearGradientValue> create(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSLinearGradient)
     {
-        return adoptRef(new CSSLinearGradientValue(repeat, gradientType));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSLinearGradientValue(repeat, gradientType));
     }
 
-    void setAngle(PassRefPtr<CSSPrimitiveValue> val) { m_angle = val; }
+    void setAngle(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_angle = val; }
 
     String customCSSText() const;
 
     // Create the gradient for a given size.
     PassRefPtr<Gradient> createGradient(const CSSToLengthConversionData&, const IntSize&);
 
-    PassRefPtr<CSSLinearGradientValue> clone() const
+    PassRefPtrWillBeRawPtr<CSSLinearGradientValue> clone() const
     {
-        return adoptRef(new CSSLinearGradientValue(*this));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSLinearGradientValue(*this));
     }
 
     bool equals(const CSSLinearGradientValue&) const;
 
+    void traceAfterDispatch(Visitor*);
+
 private:
     CSSLinearGradientValue(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSLinearGradient)
         : CSSGradientValue(LinearGradientClass, repeat, gradientType)
@@ -167,39 +180,41 @@
     {
     }
 
-    RefPtr<CSSPrimitiveValue> m_angle; // may be null.
+    RefPtrWillBeMember<CSSPrimitiveValue> m_angle; // may be null.
 };
 
 DEFINE_CSS_VALUE_TYPE_CASTS(CSSLinearGradientValue, isLinearGradientValue());
 
 class CSSRadialGradientValue : public CSSGradientValue {
 public:
-    static PassRefPtr<CSSRadialGradientValue> create(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSRadialGradient)
+    static PassRefPtrWillBeRawPtr<CSSRadialGradientValue> create(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSRadialGradient)
     {
-        return adoptRef(new CSSRadialGradientValue(repeat, gradientType));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSRadialGradientValue(repeat, gradientType));
     }
 
-    PassRefPtr<CSSRadialGradientValue> clone() const
+    PassRefPtrWillBeRawPtr<CSSRadialGradientValue> clone() const
     {
-        return adoptRef(new CSSRadialGradientValue(*this));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSRadialGradientValue(*this));
     }
 
     String customCSSText() const;
 
-    void setFirstRadius(PassRefPtr<CSSPrimitiveValue> val) { m_firstRadius = val; }
-    void setSecondRadius(PassRefPtr<CSSPrimitiveValue> val) { m_secondRadius = val; }
+    void setFirstRadius(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_firstRadius = val; }
+    void setSecondRadius(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_secondRadius = val; }
 
-    void setShape(PassRefPtr<CSSPrimitiveValue> val) { m_shape = val; }
-    void setSizingBehavior(PassRefPtr<CSSPrimitiveValue> val) { m_sizingBehavior = val; }
+    void setShape(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_shape = val; }
+    void setSizingBehavior(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_sizingBehavior = val; }
 
-    void setEndHorizontalSize(PassRefPtr<CSSPrimitiveValue> val) { m_endHorizontalSize = val; }
-    void setEndVerticalSize(PassRefPtr<CSSPrimitiveValue> val) { m_endVerticalSize = val; }
+    void setEndHorizontalSize(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_endHorizontalSize = val; }
+    void setEndVerticalSize(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_endVerticalSize = val; }
 
     // Create the gradient for a given size.
     PassRefPtr<Gradient> createGradient(const CSSToLengthConversionData&, const IntSize&);
 
     bool equals(const CSSRadialGradientValue&) const;
 
+    void traceAfterDispatch(Visitor*);
+
 private:
     CSSRadialGradientValue(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSRadialGradient)
         : CSSGradientValue(RadialGradientClass, repeat, gradientType)
@@ -222,15 +237,15 @@
     float resolveRadius(CSSPrimitiveValue*, const CSSToLengthConversionData&, float* widthOrHeight = 0);
 
     // These may be null for non-deprecated gradients.
-    RefPtr<CSSPrimitiveValue> m_firstRadius;
-    RefPtr<CSSPrimitiveValue> m_secondRadius;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_firstRadius;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_secondRadius;
 
     // The below are only used for non-deprecated gradients. Any of them may be null.
-    RefPtr<CSSPrimitiveValue> m_shape;
-    RefPtr<CSSPrimitiveValue> m_sizingBehavior;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_shape;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_sizingBehavior;
 
-    RefPtr<CSSPrimitiveValue> m_endHorizontalSize;
-    RefPtr<CSSPrimitiveValue> m_endVerticalSize;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_endHorizontalSize;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_endVerticalSize;
 };
 
 DEFINE_CSS_VALUE_TYPE_CASTS(CSSRadialGradientValue, isRadialGradientValue());
diff --git a/Source/core/css/CSSGrammar.y b/Source/core/css/CSSGrammar.y
index 73a3c1f..149ea00 100644
--- a/Source/core/css/CSSGrammar.y
+++ b/Source/core/css/CSSGrammar.y
@@ -29,7 +29,7 @@
 #include "HTMLNames.h"
 #include "core/css/CSSKeyframeRule.h"
 #include "core/css/CSSKeyframesRule.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSParserMode.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSSelector.h"
@@ -62,8 +62,8 @@
 
 %pure_parser
 
-%parse-param { CSSParser* parser }
-%lex-param { CSSParser* parser }
+%parse-param { BisonCSSParser* parser }
+%lex-param { BisonCSSParser* parser }
 
 %union {
     bool boolean;
@@ -114,12 +114,11 @@
     case FUNCTION:
     case ANYFUNCTION:
     case HOSTFUNCTION:
+    case ANCESTORFUNCTION:
     case NOTFUNCTION:
     case CALCFUNCTION:
     case MINFUNCTION:
     case MAXFUNCTION:
-    case VARFUNCTION:
-    case VAR_DEFINITION:
     case UNICODERANGE:
         return true;
     default:
@@ -194,8 +193,6 @@
 %token INTERNAL_SUPPORTS_CONDITION_SYM
 %token KEYFRAMES_SYM
 %token WEBKIT_KEYFRAMES_SYM
-%token WEBKIT_REGION_RULE_SYM
-%token WEBKIT_FILTER_RULE_SYM
 %token <marginBox> TOPLEFTCORNER_SYM
 %token <marginBox> TOPLEFT_SYM
 %token <marginBox> TOPCENTER_SYM
@@ -267,9 +264,8 @@
 %token <string> CALCFUNCTION
 %token <string> MINFUNCTION
 %token <string> MAXFUNCTION
-%token <string> VARFUNCTION
-%token <string> VAR_DEFINITION
 %token <string> HOSTFUNCTION
+%token <string> ANCESTORFUNCTION
 
 %token <string> UNICODERANGE
 
@@ -287,16 +283,10 @@
 %type <rule> valid_rule
 %type <ruleList> block_rule_body
 %type <ruleList> block_rule_list
-%type <ruleList> region_block_rule_body
-%type <ruleList> region_block_rule_list
 %type <rule> block_rule
 %type <rule> block_valid_rule
-%type <rule> region_block_rule
-%type <rule> region_block_valid_rule
-%type <rule> region
 %type <rule> supports
 %type <rule> viewport
-%type <rule> filter
 %type <boolean> keyframes_rule_start
 
 %type <string> maybe_ns_prefix
@@ -342,7 +332,6 @@
 %type <selector> relative_selector
 %type <selectorList> selector_list
 %type <selectorList> simple_selector_list
-%type <selectorList> region_selector
 %type <selector> class
 %type <selector> attrib
 %type <selector> pseudo
@@ -511,10 +500,8 @@
   | keyframes
   | namespace
   | import
-  | region
   | supports
   | viewport
-  | filter
   ;
 
 before_rule:
@@ -547,46 +534,12 @@
     }
     ;
 
-region_block_rule_body:
-    region_block_rule_list
-  | region_block_rule_list block_rule_recovery
-    ;
-
-region_block_rule_list:
-    /* empty */ { $$ = 0; }
-  | region_block_rule_list region_block_rule maybe_sgml {
-        $$ = parser->appendRule($1, $2);
-    }
-  ;
-
-region_block_rule:
-    before_rule region_block_valid_rule {
-        $$ = $2;
-        parser->endRule(!!$$);
-    }
-  | before_rule invalid_rule {
-        $$ = 0;
-        parser->endRule(false);
-    }
-  ;
-
 block_rule_recovery:
     before_rule invalid_rule_header {
         parser->endRule(false);
     }
   ;
 
-region_block_valid_rule:
-    ruleset
-  | page
-  | font_face
-  | media
-  | keyframes
-  | supports
-  | viewport
-  | filter
-  ;
-
 block_valid_rule:
     ruleset
   | page
@@ -595,9 +548,7 @@
   | keyframes
   | supports
   | viewport
-  | filter
   | namespace
-  | region
   ;
 
 block_rule:
@@ -676,7 +627,7 @@
         $$ = parser->createFloatingMediaQueryExpList();
         $$->append(parser->sinkFloatingMediaQueryExp($1));
     }
-    | media_query_exp_list space MEDIA_AND space media_query_exp {
+    | media_query_exp_list maybe_space MEDIA_AND maybe_space media_query_exp {
         $$ = $1;
         $$->append(parser->sinkFloatingMediaQueryExp($5));
     }
@@ -686,7 +637,7 @@
     maybe_space {
         $$ = parser->createFloatingMediaQueryExpList();
     }
-    | space MEDIA_AND space media_query_exp_list maybe_space {
+    | maybe_space MEDIA_AND maybe_space media_query_exp_list maybe_space {
         $$ = $4;
     }
     ;
@@ -695,10 +646,10 @@
     /*empty*/ {
         $$ = MediaQuery::None;
     }
-    | MEDIA_ONLY space {
+    | MEDIA_ONLY maybe_space {
         $$ = MediaQuery::Only;
     }
-    | MEDIA_NOT space {
+    | MEDIA_NOT maybe_space {
         $$ = MediaQuery::Not;
     }
     ;
@@ -716,11 +667,11 @@
 media_query:
     valid_media_query
     | valid_media_query error error_location rule_error_recovery {
-        parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
+        parser->reportError(parser->lastLocationLabel(), InvalidMediaQueryCSSError);
         $$ = parser->createFloatingNotAllQuery();
     }
     | error error_location rule_error_recovery {
-        parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
+        parser->reportError(parser->lastLocationLabel(), InvalidMediaQueryCSSError);
         $$ = parser->createFloatingNotAllQuery();
     }
     ;
@@ -846,7 +797,7 @@
     }
     | supports_declaration_condition
     | '(' error error_location error_recovery closing_parenthesis maybe_space {
-        parser->reportError($3, CSSParser::InvalidSupportsConditionError);
+        parser->reportError($3, InvalidSupportsConditionCSSError);
         $$ = false;
     }
     ;
@@ -868,7 +819,7 @@
     }
     | '(' maybe_space IDENT maybe_space ':' maybe_space error error_recovery closing_parenthesis maybe_space {
         $$ = false;
-        parser->endProperty(false, false, CSSParser::GeneralError);
+        parser->endProperty(false, false, GeneralCSSError);
     }
     ;
 
@@ -953,7 +904,7 @@
 
 keyframes_error_recovery:
     error rule_error_recovery {
-        parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidKeyframeSelectorError);
+        parser->reportError(parser->lastLocationLabel(), InvalidKeyframeSelectorCSSError);
     }
     ;
 
@@ -1089,40 +1040,6 @@
     }
 ;
 
-region_selector:
-    selector_list {
-        parser->setReusableRegionSelectorVector($1);
-        $$ = parser->reusableRegionSelectorVector();
-    }
-;
-
-before_region_rule:
-    /* empty */ {
-        parser->startRuleHeader(CSSRuleSourceData::REGION_RULE);
-    }
-    ;
-
-region:
-    before_region_rule WEBKIT_REGION_RULE_SYM maybe_space region_selector at_rule_header_end '{' at_rule_body_start maybe_space region_block_rule_body closing_brace {
-        $$ = parser->createRegionRule($4, $9);
-    }
-;
-
-before_filter_rule:
-    /* empty */ {
-        parser->startRuleHeader(CSSRuleSourceData::FILTER_RULE);
-        parser->m_inFilterRule = true;
-    }
-    ;
-
-filter:
-    before_filter_rule WEBKIT_FILTER_RULE_SYM maybe_space IDENT at_rule_header_end_maybe_space
-    '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
-        parser->m_inFilterRule = false;
-        $$ = parser->createFilterRule($4);
-    }
-    ;
-
 combinator:
     '+' maybe_space { $$ = CSSSelector::DirectAdjacent; }
     | '~' maybe_space { $$ = CSSSelector::IndirectAdjacent; }
@@ -1420,7 +1337,7 @@
         $$->setValue($3);
         CSSSelector::PseudoType type = $$->pseudoType();
         if (type == CSSSelector::PseudoUnknown) {
-            parser->reportError($2, CSSParser::InvalidSelectorPseudoError);
+            parser->reportError($2, InvalidSelectorPseudoCSSError);
             YYERROR;
         }
     }
@@ -1434,7 +1351,7 @@
         // FIXME: This call is needed to force selector to compute the pseudoType early enough.
         CSSSelector::PseudoType type = $$->pseudoType();
         if (type == CSSSelector::PseudoUnknown) {
-            parser->reportError($3, CSSParser::InvalidSelectorPseudoError);
+            parser->reportError($3, InvalidSelectorPseudoCSSError);
             YYERROR;
         }
     }
@@ -1562,6 +1479,29 @@
     | ':' HOSTFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
+    | ':' ANCESTORFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
+        $$ = parser->createFloatingSelector();
+        $$->setMatch(CSSSelector::PseudoClass);
+        $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($4));
+        parser->tokenToLowerCase($2);
+        $$->setValue($2);
+        CSSSelector::PseudoType type = $$->pseudoType();
+        if (type != CSSSelector::PseudoAncestor)
+            YYERROR;
+    }
+    //  used by :ancestor()
+    | ':' ANCESTORFUNCTION maybe_space closing_parenthesis {
+        $$ = parser->createFloatingSelector();
+        $$->setMatch(CSSSelector::PseudoClass);
+        parser->tokenToLowerCase($2);
+        $$->setValue($2.atomicSubstring(0, $2.length() - 1));
+        CSSSelector::PseudoType type = $$->pseudoType();
+        if (type != CSSSelector::PseudoAncestor)
+            YYERROR;
+    }
+    | ':' ANCESTORFUNCTION selector_recovery closing_parenthesis {
+        YYERROR;
+    }
   ;
 
 selector_recovery:
@@ -1588,12 +1528,6 @@
     ;
 
 declaration:
-    VAR_DEFINITION maybe_space ':' maybe_space expr prio {
-        parser->storeVariableDeclaration($1, parser->sinkFloatingValueList($5), $6);
-        $$ = true;
-        parser->endProperty($6, true);
-    }
-    |
     property ':' maybe_space error_location expr prio {
         $$ = false;
         bool isPropertyParsed = false;
@@ -1603,7 +1537,7 @@
             $$ = parser->parseValue($1, $6);
             if (!$$) {
                 parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
-                parser->reportError($4, CSSParser::InvalidPropertyValueError);
+                parser->reportError($4, InvalidPropertyValueCSSError);
             } else
                 isPropertyParsed = true;
             parser->m_valueList = nullptr;
@@ -1613,25 +1547,25 @@
     |
     property ':' maybe_space error_location expr prio error error_recovery {
         /* When we encounter something like p {color: red !important fail;} we should drop the declaration */
-        parser->reportError($4, CSSParser::InvalidPropertyValueError);
+        parser->reportError($4, InvalidPropertyValueCSSError);
         parser->endProperty(false, false);
         $$ = false;
     }
     |
     property ':' maybe_space error_location error error_recovery {
-        parser->reportError($4, CSSParser::InvalidPropertyValueError);
+        parser->reportError($4, InvalidPropertyValueCSSError);
         parser->endProperty(false, false);
         $$ = false;
     }
     |
     property error error_location error_recovery {
-        parser->reportError($3, CSSParser::PropertyDeclarationError);
-        parser->endProperty(false, false, CSSParser::GeneralError);
+        parser->reportError($3, PropertyDeclarationCSSError);
+        parser->endProperty(false, false, GeneralCSSError);
         $$ = false;
     }
     |
     error error_location error_recovery {
-        parser->reportError($2, CSSParser::PropertyDeclarationError);
+        parser->reportError($2, PropertyDeclarationCSSError);
         $$ = false;
     }
   ;
@@ -1641,7 +1575,7 @@
         $$ = cssPropertyID($2);
         parser->setCurrentProperty($$);
         if ($$ == CSSPropertyInvalid)
-            parser->reportError($1, CSSParser::InvalidPropertyError);
+            parser->reportError($1, InvalidPropertyCSSError);
     }
   ;
 
@@ -1691,7 +1625,7 @@
 
 expr_recovery:
     error error_location error_recovery {
-        parser->reportError($2, CSSParser::PropertyDeclarationError);
+        parser->reportError($2, PropertyDeclarationCSSError);
     }
   ;
 
@@ -1716,14 +1650,6 @@
   | UNICODERANGE maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_UNICODE_RANGE; }
   | HEX maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; }
   | '#' maybe_space { $$.id = CSSValueInvalid; $$.string = CSSParserString(); $$.unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; } /* Handle error case: "color: #;" */
-  | VARFUNCTION maybe_space IDENT closing_parenthesis maybe_space {
-      $$.id = CSSValueInvalid;
-      $$.string = $3;
-      $$.unit = CSSPrimitiveValue::CSS_VARIABLE_NAME;
-  }
-  | VARFUNCTION maybe_space expr_recovery closing_parenthesis {
-      YYERROR;
-  }
   /* FIXME: according to the specs a function can have a unary_operator in front. I know no case where this makes sense */
   | function maybe_space
   | calc_function maybe_space
@@ -1785,11 +1711,6 @@
 
 calc_func_term:
   unary_term
-  | VARFUNCTION maybe_space IDENT closing_parenthesis {
-      $$.id = CSSValueInvalid;
-      $$.string = $3;
-      $$.unit = CSSPrimitiveValue::CSS_VARIABLE_NAME;
-  }
   | unary_operator unary_term { $$ = $2; $$.fValue *= $1; }
   ;
 
@@ -1837,7 +1758,7 @@
     | calc_func_expr calc_func_operator calc_func_paren_expr {
         $$ = $1;
         $$->addValue(makeOperatorValue($2));
-        $$->extend(*($3));
+        $$->stealValues(*($3));
     }
     | calc_func_paren_expr
   ;
@@ -1847,7 +1768,7 @@
     | calc_func_expr_list ',' maybe_space calc_func_expr calc_maybe_space {
         $$ = $1;
         $$->addValue(makeOperatorValue(','));
-        $$->extend(*($4));
+        $$->stealValues(*($4));
     }
   ;
 
@@ -1886,7 +1807,7 @@
 
 at_rule_header_recovery:
     error error_location rule_error_recovery {
-        parser->reportError($2, CSSParser::InvalidRuleError);
+        parser->reportError($2, InvalidRuleCSSError);
     }
     ;
 
@@ -1900,25 +1821,23 @@
   | before_page_rule PAGE_SYM at_rule_header_recovery
   | before_font_face_rule FONT_FACE_SYM at_rule_header_recovery
   | before_supports_rule SUPPORTS_SYM error error_location rule_error_recovery {
-        parser->reportError($4, CSSParser::InvalidSupportsConditionError);
+        parser->reportError($4, InvalidSupportsConditionCSSError);
         parser->popSupportsRuleData();
     }
   | before_viewport_rule VIEWPORT_RULE_SYM at_rule_header_recovery {
         parser->markViewportRuleBodyEnd();
     }
-  | before_filter_rule WEBKIT_FILTER_RULE_SYM at_rule_header_recovery
   | import_rule_start at_rule_header_recovery
   | NAMESPACE_SYM at_rule_header_recovery
-  | before_region_rule WEBKIT_REGION_RULE_SYM at_rule_header_recovery
   | error_location invalid_at at_rule_header_recovery {
         parser->resumeErrorLogging();
-        parser->reportError($1, CSSParser::InvalidRuleError);
+        parser->reportError($1, InvalidRuleCSSError);
     }
   ;
 
 invalid_rule:
     error error_location rule_error_recovery at_invalid_rule_header_end invalid_block {
-        parser->reportError($2, CSSParser::InvalidRuleError);
+        parser->reportError($2, InvalidRuleCSSError);
     }
   | regular_invalid_at_rule_header at_invalid_rule_header_end ';'
   | regular_invalid_at_rule_header at_invalid_rule_header_end invalid_block
@@ -1927,7 +1846,7 @@
 
 invalid_rule_header:
     error error_location rule_error_recovery at_invalid_rule_header_end {
-        parser->reportError($2, CSSParser::InvalidRuleError);
+        parser->reportError($2, InvalidRuleCSSError);
     }
   | regular_invalid_at_rule_header at_invalid_rule_header_end
   | media_rule_start maybe_media_list
@@ -1953,7 +1872,7 @@
     opening_parenthesis error_recovery closing_parenthesis;
 
 opening_parenthesis:
-    '(' | FUNCTION | CALCFUNCTION | VARFUNCTION | MINFUNCTION | MAXFUNCTION | ANYFUNCTION | NOTFUNCTION | CUEFUNCTION | DISTRIBUTEDFUNCTION | HOSTFUNCTION
+    '(' | FUNCTION | CALCFUNCTION | MINFUNCTION | MAXFUNCTION | ANYFUNCTION | NOTFUNCTION | CUEFUNCTION | DISTRIBUTEDFUNCTION | HOSTFUNCTION
     ;
 
 error_location: {
diff --git a/Source/core/css/CSSGridLineNamesValue.cpp b/Source/core/css/CSSGridLineNamesValue.cpp
index 3a2877d..4e52aac 100644
--- a/Source/core/css/CSSGridLineNamesValue.cpp
+++ b/Source/core/css/CSSGridLineNamesValue.cpp
@@ -43,9 +43,9 @@
 {
 }
 
-PassRefPtr<CSSGridLineNamesValue> CSSGridLineNamesValue::cloneForCSSOM() const
+PassRefPtrWillBeRawPtr<CSSGridLineNamesValue> CSSGridLineNamesValue::cloneForCSSOM() const
 {
-    return adoptRef(new CSSGridLineNamesValue(*this));
+    return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSGridLineNamesValue(*this));
 }
 
 }
diff --git a/Source/core/css/CSSGridLineNamesValue.h b/Source/core/css/CSSGridLineNamesValue.h
index da97e05..3cc8004 100644
--- a/Source/core/css/CSSGridLineNamesValue.h
+++ b/Source/core/css/CSSGridLineNamesValue.h
@@ -38,14 +38,16 @@
 
 class CSSGridLineNamesValue : public CSSValueList {
 public:
-    static PassRefPtr<CSSGridLineNamesValue> create()
+    static PassRefPtrWillBeRawPtr<CSSGridLineNamesValue> create()
     {
-        return adoptRef(new CSSGridLineNamesValue());
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSGridLineNamesValue());
     }
 
     String customCSSText() const;
 
-    PassRefPtr<CSSGridLineNamesValue> cloneForCSSOM() const;
+    PassRefPtrWillBeRawPtr<CSSGridLineNamesValue> cloneForCSSOM() const;
+
+    void traceAfterDispatch(Visitor* visitor) { CSSValueList::traceAfterDispatch(visitor); }
 
 private:
     CSSGridLineNamesValue();
diff --git a/Source/core/css/CSSGridTemplateValue.cpp b/Source/core/css/CSSGridTemplateAreasValue.cpp
similarity index 91%
rename from Source/core/css/CSSGridTemplateValue.cpp
rename to Source/core/css/CSSGridTemplateAreasValue.cpp
index d1ad1d8..d27c5b6 100644
--- a/Source/core/css/CSSGridTemplateValue.cpp
+++ b/Source/core/css/CSSGridTemplateAreasValue.cpp
@@ -29,14 +29,14 @@
  */
 
 #include "config.h"
-#include "core/css/CSSGridTemplateValue.h"
+#include "core/css/CSSGridTemplateAreasValue.h"
 
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
-CSSGridTemplateValue::CSSGridTemplateValue(const NamedGridAreaMap& gridAreaMap, size_t rowCount, size_t columnCount)
-    : CSSValue(GridTemplateClass)
+CSSGridTemplateAreasValue::CSSGridTemplateAreasValue(const NamedGridAreaMap& gridAreaMap, size_t rowCount, size_t columnCount)
+    : CSSValue(GridTemplateAreasClass)
     , m_gridAreaMap(gridAreaMap)
     , m_rowCount(rowCount)
     , m_columnCount(columnCount)
@@ -66,7 +66,7 @@
     return ".";
 }
 
-String CSSGridTemplateValue::customCSSText() const
+String CSSGridTemplateAreasValue::customCSSText() const
 {
     StringBuilder builder;
     for (size_t row = 0; row < m_rowCount; ++row) {
diff --git a/Source/core/css/CSSGridTemplateValue.h b/Source/core/css/CSSGridTemplateAreasValue.h
similarity index 73%
rename from Source/core/css/CSSGridTemplateValue.h
rename to Source/core/css/CSSGridTemplateAreasValue.h
index faa9880..da1d130 100644
--- a/Source/core/css/CSSGridTemplateValue.h
+++ b/Source/core/css/CSSGridTemplateAreasValue.h
@@ -28,8 +28,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CSSGridTemplateValue_h
-#define CSSGridTemplateValue_h
+#ifndef CSSGridTemplateAreasValue_h
+#define CSSGridTemplateAreasValue_h
 
 #include "core/css/CSSValue.h"
 #include "core/rendering/style/GridCoordinate.h"
@@ -37,10 +37,13 @@
 
 namespace WebCore {
 
-class CSSGridTemplateValue : public CSSValue {
+class CSSGridTemplateAreasValue : public CSSValue {
 public:
-    static PassRefPtr<CSSGridTemplateValue> create(const NamedGridAreaMap& gridAreaMap, size_t rowCount, size_t columnCount) { return adoptRef(new CSSGridTemplateValue(gridAreaMap, rowCount, columnCount)); }
-    ~CSSGridTemplateValue() { }
+    static PassRefPtrWillBeRawPtr<CSSGridTemplateAreasValue> create(const NamedGridAreaMap& gridAreaMap, size_t rowCount, size_t columnCount)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSGridTemplateAreasValue(gridAreaMap, rowCount, columnCount));
+    }
+    ~CSSGridTemplateAreasValue() { }
 
     String customCSSText() const;
 
@@ -48,16 +51,18 @@
     size_t rowCount() const { return m_rowCount; }
     size_t columnCount() const { return m_columnCount; }
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
-    CSSGridTemplateValue(const NamedGridAreaMap&, size_t rowCount, size_t columnCount);
+    CSSGridTemplateAreasValue(const NamedGridAreaMap&, size_t rowCount, size_t columnCount);
 
     NamedGridAreaMap m_gridAreaMap;
     size_t m_rowCount;
     size_t m_columnCount;
 };
 
-DEFINE_CSS_VALUE_TYPE_CASTS(CSSGridTemplateValue, isGridTemplateValue());
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSGridTemplateAreasValue, isGridTemplateAreasValue());
 
 } // namespace WebCore
 
-#endif // CSSGridTemplateValue_h
+#endif // CSSGridTemplateAreasValue_h
diff --git a/Source/core/css/CSSGroupingRule.cpp b/Source/core/css/CSSGroupingRule.cpp
index 0c0bf2a..768f795 100644
--- a/Source/core/css/CSSGroupingRule.cpp
+++ b/Source/core/css/CSSGroupingRule.cpp
@@ -32,10 +32,13 @@
 #include "core/css/CSSGroupingRule.h"
 
 #include "bindings/v8/ExceptionState.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSStyleSheet.h"
+#include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/UseCounter.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
@@ -60,13 +63,23 @@
 {
     ASSERT(m_childRuleCSSOMWrappers.size() == m_groupRule->childRules().size());
 
+    CSSStyleSheet* styleSheet = parentStyleSheet();
+    if (styleSheet) {
+        if (Document* document = styleSheet->ownerDocument()) {
+            if (!document->contentSecurityPolicy()->allowStyleEval()) {
+                exceptionState.throwSecurityError(document->contentSecurityPolicy()->styleEvalDisabledErrorMessage());
+                return 0;
+            }
+        }
+    }
+
     if (index > m_groupRule->childRules().size()) {
         exceptionState.throwDOMException(IndexSizeError, "the index " + String::number(index) + " must be less than or equal to the length of the rule list.");
         return 0;
     }
 
-    CSSStyleSheet* styleSheet = parentStyleSheet();
-    CSSParser parser(parserContext(), UseCounter::getFrom(styleSheet));
+    CSSParserContext context(parserContext(), UseCounter::getFrom(styleSheet));
+    BisonCSSParser parser(context);
     RefPtr<StyleRuleBase> newRule = parser.parseRule(styleSheet ? styleSheet->contents() : 0, ruleString);
     if (!newRule) {
         exceptionState.throwDOMException(SyntaxError, "the rule '" + ruleString + "' is invalid and cannot be parsed.");
diff --git a/Source/core/css/CSSImageGeneratorValue.cpp b/Source/core/css/CSSImageGeneratorValue.cpp
index fa3f22a..f492f1e 100644
--- a/Source/core/css/CSSImageGeneratorValue.cpp
+++ b/Source/core/css/CSSImageGeneratorValue.cpp
@@ -87,7 +87,9 @@
         SizeAndCount& sizeCount = it->value;
         IntSize oldSize = sizeCount.size;
         if (oldSize != size) {
+#if !ENABLE_OILPAN
             RefPtr<CSSImageGeneratorValue> protect(this);
+#endif
             removeClient(renderer);
             addClient(renderer, size);
         }
diff --git a/Source/core/css/CSSImageGeneratorValue.h b/Source/core/css/CSSImageGeneratorValue.h
index d5803d3..7192baf 100644
--- a/Source/core/css/CSSImageGeneratorValue.h
+++ b/Source/core/css/CSSImageGeneratorValue.h
@@ -67,6 +67,8 @@
 
     void loadSubimages(ResourceFetcher*);
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 protected:
     explicit CSSImageGeneratorValue(ClassType);
 
diff --git a/Source/core/css/CSSImageSetValue.cpp b/Source/core/css/CSSImageSetValue.cpp
index ef63219..502004f 100644
--- a/Source/core/css/CSSImageSetValue.cpp
+++ b/Source/core/css/CSSImageSetValue.cpp
@@ -88,7 +88,7 @@
     return image;
 }
 
-StyleFetchedImageSet* CSSImageSetValue::cachedImageSet(ResourceFetcher* loader, float deviceScaleFactor)
+StyleFetchedImageSet* CSSImageSetValue::cachedImageSet(ResourceFetcher* loader, float deviceScaleFactor, const ResourceLoaderOptions& options)
 {
     ASSERT(loader);
 
@@ -103,7 +103,11 @@
         // and any CSS transforms. https://bugs.webkit.org/show_bug.cgi?id=81698
         ImageWithScale image = bestImageForScaleFactor();
         if (Document* document = loader->document()) {
-            FetchRequest request(ResourceRequest(document->completeURL(image.imageURL)), FetchInitiatorTypeNames::css);
+            FetchRequest request(ResourceRequest(document->completeURL(image.imageURL)), FetchInitiatorTypeNames::css, options);
+
+            if (options.corsEnabled == IsCORSEnabled)
+                request.setCrossOriginAccessControl(loader->document()->securityOrigin(), options.allowCredentials);
+
             if (ResourcePtr<ImageResource> cachedImage = loader->fetchImage(request)) {
                 m_imageSet = StyleFetchedImageSet::create(cachedImage.get(), image.scaleFactor, this);
                 m_accessedBestFitImage = true;
@@ -114,6 +118,11 @@
     return (m_imageSet && m_imageSet->isImageResourceSet()) ? toStyleFetchedImageSet(m_imageSet) : 0;
 }
 
+StyleFetchedImageSet* CSSImageSetValue::cachedImageSet(ResourceFetcher* fetcher, float deviceScaleFactor)
+{
+    return cachedImageSet(fetcher, deviceScaleFactor, ResourceFetcher::defaultResourceOptions());
+}
+
 StyleImage* CSSImageSetValue::cachedOrPendingImageSet(float deviceScaleFactor)
 {
     if (!m_imageSet) {
@@ -176,9 +185,9 @@
     // Non-CSSValueList data is not accessible through CSS OM, no need to clone.
 }
 
-PassRefPtr<CSSImageSetValue> CSSImageSetValue::cloneForCSSOM() const
+PassRefPtrWillBeRawPtr<CSSImageSetValue> CSSImageSetValue::cloneForCSSOM() const
 {
-    return adoptRef(new CSSImageSetValue(*this));
+    return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSImageSetValue(*this));
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSImageSetValue.h b/Source/core/css/CSSImageSetValue.h
index ee6e86b..3ad6029 100644
--- a/Source/core/css/CSSImageSetValue.h
+++ b/Source/core/css/CSSImageSetValue.h
@@ -27,6 +27,7 @@
 #define CSSImageSetValue_h
 
 #include "core/css/CSSValueList.h"
+#include "core/fetch/ResourceFetcher.h"
 
 namespace WebCore {
 
@@ -37,12 +38,13 @@
 class CSSImageSetValue : public CSSValueList {
 public:
 
-    static PassRefPtr<CSSImageSetValue> create()
+    static PassRefPtrWillBeRawPtr<CSSImageSetValue> create()
     {
-        return adoptRef(new CSSImageSetValue());
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSImageSetValue());
     }
     ~CSSImageSetValue();
 
+    StyleFetchedImageSet* cachedImageSet(ResourceFetcher*, float deviceScaleFactor, const ResourceLoaderOptions&);
     StyleFetchedImageSet* cachedImageSet(ResourceFetcher*, float deviceScaleFactor);
 
     // Returns a StyleFetchedImageSet if the best fit image has been cached already, otherwise a StylePendingImage.
@@ -59,7 +61,9 @@
 
     bool hasFailedOrCanceledSubresources() const;
 
-    PassRefPtr<CSSImageSetValue> cloneForCSSOM() const;
+    PassRefPtrWillBeRawPtr<CSSImageSetValue> cloneForCSSOM() const;
+
+    void traceAfterDispatch(Visitor* visitor) { CSSValueList::traceAfterDispatch(visitor); }
 
 protected:
     ImageWithScale bestImageForScaleFactor();
diff --git a/Source/core/css/CSSImageValue.cpp b/Source/core/css/CSSImageValue.cpp
index 4dd0799..f424da7 100644
--- a/Source/core/css/CSSImageValue.cpp
+++ b/Source/core/css/CSSImageValue.cpp
@@ -22,26 +22,27 @@
 #include "core/css/CSSImageValue.h"
 
 #include "FetchInitiatorTypeNames.h"
-#include "core/css/CSSParser.h"
+#include "core/css/CSSMarkup.h"
 #include "core/dom/Document.h"
 #include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ImageResource.h"
 #include "core/rendering/style/StyleFetchedImage.h"
 #include "core/rendering/style/StylePendingImage.h"
+#include "platform/weborigin/KURL.h"
 
 namespace WebCore {
 
-CSSImageValue::CSSImageValue(const String& url)
+CSSImageValue::CSSImageValue(const KURL& url)
     : CSSValue(ImageClass)
-    , m_url(url)
+    , m_url(url.string())
     , m_accessedImage(false)
 {
 }
 
-CSSImageValue::CSSImageValue(const String& url, StyleImage* image)
+CSSImageValue::CSSImageValue(const KURL& url, StyleImage* image)
     : CSSValue(ImageClass)
-    , m_url(url)
+    , m_url(url.string())
     , m_image(image)
     , m_accessedImage(true)
 {
@@ -59,17 +60,17 @@
     return m_image.get();
 }
 
-StyleFetchedImage* CSSImageValue::cachedImage(ResourceFetcher* fetcher, const ResourceLoaderOptions& options, CORSEnabled corsEnabled)
+StyleFetchedImage* CSSImageValue::cachedImage(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
 {
     ASSERT(fetcher);
 
     if (!m_accessedImage) {
         m_accessedImage = true;
 
-        FetchRequest request(ResourceRequest(fetcher->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, options);
+        FetchRequest request(ResourceRequest(m_url), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, options);
 
-        if (corsEnabled == PotentiallyCORSEnabled)
-            updateRequestForAccessControl(request.mutableResourceRequest(), fetcher->document()->securityOrigin(), options.allowCredentials);
+        if (options.corsEnabled == IsCORSEnabled)
+            request.setCrossOriginAccessControl(fetcher->document()->securityOrigin(), options.allowCredentials);
 
         if (ResourcePtr<ImageResource> cachedImage = fetcher->fetchImage(request))
             m_image = StyleFetchedImage::create(cachedImage.get());
@@ -100,7 +101,7 @@
 PassRefPtr<CSSValue> CSSImageValue::cloneForCSSOM() const
 {
     // NOTE: We expose CSSImageValues as URI primitive values in CSSOM to maintain old behavior.
-    RefPtr<CSSPrimitiveValue> uriValue = CSSPrimitiveValue::create(m_url, CSSPrimitiveValue::CSS_URI);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> uriValue = CSSPrimitiveValue::create(m_url, CSSPrimitiveValue::CSS_URI);
     uriValue->setCSSOMSafe();
     return uriValue.release();
 }
@@ -110,4 +111,9 @@
     return m_image ? m_image->knownToBeOpaque(renderer) : false;
 }
 
+void CSSImageValue::traceAfterDispatch(Visitor* visitor)
+{
+    CSSValue::traceAfterDispatch(visitor);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSImageValue.h b/Source/core/css/CSSImageValue.h
index a84afa5..29f2c9d 100644
--- a/Source/core/css/CSSImageValue.h
+++ b/Source/core/css/CSSImageValue.h
@@ -28,18 +28,25 @@
 namespace WebCore {
 
 class Element;
+class KURL;
 class StyleFetchedImage;
 class StyleImage;
 class RenderObject;
 
 class CSSImageValue : public CSSValue {
 public:
-    static PassRefPtr<CSSImageValue> create(const String& url) { return adoptRef(new CSSImageValue(url)); }
-    static PassRefPtr<CSSImageValue> create(const String& url, StyleImage* image) { return adoptRef(new CSSImageValue(url, image)); }
+    static PassRefPtrWillBeRawPtr<CSSImageValue> create(const KURL& url)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSImageValue(url));
+    }
+    static PassRefPtrWillBeRawPtr<CSSImageValue> create(const KURL& url, StyleImage* image)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSImageValue(url, image));
+    }
     ~CSSImageValue();
 
-    StyleFetchedImage* cachedImage(ResourceFetcher*, const ResourceLoaderOptions&, CORSEnabled);
-    StyleFetchedImage* cachedImage(ResourceFetcher* fetcher) { return cachedImage(fetcher, ResourceFetcher::defaultResourceOptions(), NotCORSEnabled); }
+    StyleFetchedImage* cachedImage(ResourceFetcher*, const ResourceLoaderOptions&);
+    StyleFetchedImage* cachedImage(ResourceFetcher* fetcher) { return cachedImage(fetcher, ResourceFetcher::defaultResourceOptions()); }
     // Returns a StyleFetchedImage if the image is cached already, otherwise a StylePendingImage.
     StyleImage* cachedOrPendingImage();
 
@@ -57,9 +64,11 @@
 
     void setInitiator(const AtomicString& name) { m_initiatorName = name; }
 
+    void traceAfterDispatch(Visitor*);
+
 private:
-    explicit CSSImageValue(const String& url);
-    CSSImageValue(const String& url, StyleImage*);
+    explicit CSSImageValue(const KURL&);
+    CSSImageValue(const KURL&, StyleImage*);
 
     String m_url;
     RefPtr<StyleImage> m_image;
diff --git a/Source/core/css/CSSImportRule.h b/Source/core/css/CSSImportRule.h
index 0abfc9a..95df9c7 100644
--- a/Source/core/css/CSSImportRule.h
+++ b/Source/core/css/CSSImportRule.h
@@ -31,7 +31,7 @@
 class MediaQuerySet;
 class StyleRuleImport;
 
-class CSSImportRule : public CSSRule {
+class CSSImportRule FINAL : public CSSRule {
 public:
     static PassRefPtr<CSSImportRule> create(StyleRuleImport* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSImportRule(rule, sheet)); }
 
diff --git a/Source/core/css/CSSInheritedValue.h b/Source/core/css/CSSInheritedValue.h
index 7367707..a5fe550 100644
--- a/Source/core/css/CSSInheritedValue.h
+++ b/Source/core/css/CSSInheritedValue.h
@@ -28,15 +28,17 @@
 
 class CSSInheritedValue : public CSSValue {
 public:
-    static PassRefPtr<CSSInheritedValue> create()
+    static PassRefPtrWillBeRawPtr<CSSInheritedValue> create()
     {
-        return adoptRef(new CSSInheritedValue);
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSInheritedValue);
     }
 
     String customCSSText() const;
 
     bool equals(const CSSInheritedValue&) const { return true; }
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     CSSInheritedValue()
         : CSSValue(InheritedClass)
diff --git a/Source/core/css/CSSInitialValue.h b/Source/core/css/CSSInitialValue.h
index f8f9e51..c9a7d4f 100644
--- a/Source/core/css/CSSInitialValue.h
+++ b/Source/core/css/CSSInitialValue.h
@@ -28,13 +28,13 @@
 
 class CSSInitialValue : public CSSValue {
 public:
-    static PassRefPtr<CSSInitialValue> createExplicit()
+    static PassRefPtrWillBeRawPtr<CSSInitialValue> createExplicit()
     {
-        return adoptRef(new CSSInitialValue(/* implicit */ false));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSInitialValue(/* implicit */ false));
     }
-    static PassRefPtr<CSSInitialValue> createImplicit()
+    static PassRefPtrWillBeRawPtr<CSSInitialValue> createImplicit()
     {
-        return adoptRef(new CSSInitialValue(/* implicit */ true));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSInitialValue(/* implicit */ true));
     }
 
     String customCSSText() const;
@@ -43,6 +43,8 @@
 
     bool equals(const CSSInitialValue&) const { return true; }
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     explicit CSSInitialValue(bool implicit)
         : CSSValue(InitialClass)
diff --git a/Source/core/css/CSSKeyframeRule.cpp b/Source/core/css/CSSKeyframeRule.cpp
index 65aa307..a49ef8e 100644
--- a/Source/core/css/CSSKeyframeRule.cpp
+++ b/Source/core/css/CSSKeyframeRule.cpp
@@ -27,9 +27,10 @@
 #include "core/css/CSSKeyframeRule.h"
 
 #include "core/css/CSSKeyframesRule.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/PropertySetCSSStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
+#include "core/frame/UseCounter.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
@@ -76,7 +77,7 @@
         // Keys can only be cleared by setting the key text from JavaScript
         // and this can never be null.
         ASSERT(!m_keyText.isNull());
-        m_keys = CSSParser(HTMLStandardMode).parseKeyframeKeyList(m_keyText);
+        m_keys = BisonCSSParser(strictCSSParserContext()).parseKeyframeKeyList(m_keyText);
     }
     // If an invalid key string was set, m_keys may be empty.
     ASSERT(m_keys);
diff --git a/Source/core/css/CSSKeyframeRule.h b/Source/core/css/CSSKeyframeRule.h
index 5943148..5e7fbee 100644
--- a/Source/core/css/CSSKeyframeRule.h
+++ b/Source/core/css/CSSKeyframeRule.h
@@ -52,7 +52,7 @@
 
     // Used by StyleResolver.
     const Vector<double>& keys() const;
-    // Used by CSSParser when constructing a new StyleKeyframe.
+    // Used by BisonCSSParser when constructing a new StyleKeyframe.
     void setKeys(PassOwnPtr<Vector<double> >);
 
     const StylePropertySet* properties() const { return m_properties.get(); }
diff --git a/Source/core/css/CSSKeyframesRule.cpp b/Source/core/css/CSSKeyframesRule.cpp
index 94d5dff..6b5576c 100644
--- a/Source/core/css/CSSKeyframesRule.cpp
+++ b/Source/core/css/CSSKeyframesRule.cpp
@@ -26,10 +26,14 @@
 #include "config.h"
 #include "core/css/CSSKeyframesRule.h"
 
+#include "bindings/v8/ExceptionState.h"
 #include "core/css/CSSKeyframeRule.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSStyleSheet.h"
+#include "core/dom/Document.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/UseCounter.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
@@ -110,12 +114,22 @@
     m_keyframesRule->setName(name);
 }
 
-void CSSKeyframesRule::insertRule(const String& ruleText)
+void CSSKeyframesRule::insertRule(const String& ruleText, ExceptionState& exceptionState)
 {
     ASSERT(m_childRuleCSSOMWrappers.size() == m_keyframesRule->keyframes().size());
 
     CSSStyleSheet* styleSheet = parentStyleSheet();
-    CSSParser parser(parserContext(), UseCounter::getFrom(styleSheet));
+    if (styleSheet) {
+        if (Document* document = styleSheet->ownerDocument()) {
+            if (!document->contentSecurityPolicy()->allowStyleEval()) {
+                exceptionState.throwSecurityError(document->contentSecurityPolicy()->styleEvalDisabledErrorMessage());
+                return;
+            }
+        }
+    }
+
+    CSSParserContext context(parserContext(), UseCounter::getFrom(styleSheet));
+    BisonCSSParser parser(context);
     RefPtr<StyleKeyframe> keyframe = parser.parseKeyframeRule(styleSheet ? styleSheet->contents() : 0, ruleText);
     if (!keyframe)
         return;
diff --git a/Source/core/css/CSSKeyframesRule.h b/Source/core/css/CSSKeyframesRule.h
index d74cf68..0be3fd1 100644
--- a/Source/core/css/CSSKeyframesRule.h
+++ b/Source/core/css/CSSKeyframesRule.h
@@ -36,6 +36,7 @@
 class CSSRuleList;
 class StyleKeyframe;
 class CSSKeyframeRule;
+class ExceptionState;
 
 class StyleRuleKeyframes FINAL : public StyleRuleBase {
 public:
@@ -85,7 +86,7 @@
 
     CSSRuleList* cssRules();
 
-    void insertRule(const String& rule);
+    void insertRule(const String& rule, ExceptionState&);
     void deleteRule(const String& key);
     CSSKeyframeRule* findRule(const String& key);
 
diff --git a/Source/core/css/CSSKeyframesRule.idl b/Source/core/css/CSSKeyframesRule.idl
index d97dd4a..ee408d9 100644
--- a/Source/core/css/CSSKeyframesRule.idl
+++ b/Source/core/css/CSSKeyframesRule.idl
@@ -31,8 +31,8 @@
     attribute DOMString name;
     readonly attribute CSSRuleList cssRules;
 
-    [ImplementedAs=item, NotEnumerable] getter CSSKeyframeRule(unsigned long index);
-    void insertRule([Default=Undefined] optional DOMString rule);
+    [ImplementedAs=item, NotEnumerable] getter CSSKeyframeRule (unsigned long index);
+    [RaisesException] void insertRule([Default=Undefined] optional DOMString rule);
     void deleteRule([Default=Undefined] optional DOMString key);
     CSSKeyframeRule findRule([Default=Undefined] optional DOMString key);
 };
diff --git a/Source/core/css/CSSLengthFunctions.cpp b/Source/core/css/CSSLengthFunctions.cpp
deleted file mode 100644
index 94acda3..0000000
--- a/Source/core/css/CSSLengthFunctions.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
-    Copyright (C) 1999 Lars Knoll (knoll@kde.org)
-    Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
-    Copyright (C) 2011 Rik Cabanier (cabanier@adobe.com)
-    Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
-    Copyright (C) 2012 Motorola Mobility, Inc. All rights reserved.
-    Copyright (C) 2013 Google, Inc. All rights reserved.
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Library General Public
-    License as published by the Free Software Foundation; either
-    version 2 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Library General Public License for more details.
-
-    You should have received a copy of the GNU Library General Public License
-    along with this library; see the file COPYING.LIB.  If not, write to
-    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-    Boston, MA 02110-1301, USA.
-*/
-
-#include "config.h"
-#include "core/css/CSSLengthFunctions.h"
-
-#include "core/rendering/RenderView.h"
-#include "platform/LayoutUnit.h"
-#include "platform/Length.h"
-#include "platform/LengthFunctions.h"
-
-namespace WebCore {
-
-int minimumIntValueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
-{
-    return static_cast<int>(minimumValueForLength(length, maximumValue, renderView, roundPercentages));
-}
-
-int intValueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
-{
-    return static_cast<int>(valueForLength(length, maximumValue, renderView, roundPercentages));
-}
-
-LayoutUnit minimumValueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
-{
-    switch (length.type()) {
-    case Fixed:
-        return length.value();
-    case Percent:
-        if (roundPercentages)
-            return static_cast<LayoutUnit>(round(maximumValue * length.percent() / 100.0f));
-        // Don't remove the extra cast to float. It is needed for rounding on 32-bit Intel machines that use the FPU stack.
-        return static_cast<float>(maximumValue * length.percent() / 100.0f);
-    case Calculated:
-        return length.nonNanCalculatedValue(maximumValue);
-    case ViewportPercentageWidth:
-        return renderView ? renderView->viewportPercentageWidth(length.viewportPercentageLength()) : LayoutUnit(0);
-    case ViewportPercentageHeight:
-        return renderView ? renderView->viewportPercentageHeight(length.viewportPercentageLength()) : LayoutUnit(0);
-    case ViewportPercentageMin:
-        return renderView ? renderView->viewportPercentageMin(length.viewportPercentageLength()) : LayoutUnit(0);
-    case ViewportPercentageMax:
-        return renderView ? renderView->viewportPercentageMax(length.viewportPercentageLength()) : LayoutUnit(0);
-    case FillAvailable:
-    case Auto:
-        return 0;
-    case Intrinsic:
-    case MinIntrinsic:
-    case MinContent:
-    case MaxContent:
-    case FitContent:
-    case ExtendToZoom:
-    case Undefined:
-        ASSERT_NOT_REACHED();
-        return 0;
-    }
-    ASSERT_NOT_REACHED();
-    return 0;
-}
-
-LayoutUnit valueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
-{
-    switch (length.type()) {
-    case Fixed:
-    case Percent:
-    case Calculated:
-    case ViewportPercentageWidth:
-    case ViewportPercentageHeight:
-    case ViewportPercentageMin:
-    case ViewportPercentageMax:
-        return minimumValueForLength(length, maximumValue, renderView, roundPercentages);
-    case FillAvailable:
-    case Auto:
-        return maximumValue;
-    case Intrinsic:
-    case MinIntrinsic:
-    case MinContent:
-    case MaxContent:
-    case FitContent:
-    case ExtendToZoom:
-    case Undefined:
-        ASSERT_NOT_REACHED();
-        return 0;
-    }
-    ASSERT_NOT_REACHED();
-    return 0;
-}
-
-// This method has code duplicated in platform/LengthFunctions.cpp.
-// Any changes here most likely also need to be applied there.
-float floatValueForLength(const Length& length, float maximumValue, RenderView* renderView)
-{
-    if (!renderView)
-        return floatValueForLength(length, maximumValue);
-
-    switch (length.type()) {
-    case Fixed:
-        return length.getFloatValue();
-    case Percent:
-        return static_cast<float>(maximumValue * length.percent() / 100.0f);
-    case FillAvailable:
-    case Auto:
-        return static_cast<float>(maximumValue);
-    case Calculated:
-        return length.nonNanCalculatedValue(maximumValue);
-    case ViewportPercentageWidth:
-        return static_cast<int>(renderView->viewportPercentageWidth(length.viewportPercentageLength()));
-    case ViewportPercentageHeight:
-        return static_cast<int>(renderView->viewportPercentageHeight(length.viewportPercentageLength()));
-    case ViewportPercentageMin:
-        return static_cast<int>(renderView->viewportPercentageMin(length.viewportPercentageLength()));
-    case ViewportPercentageMax:
-        return static_cast<int>(renderView->viewportPercentageMax(length.viewportPercentageLength()));
-    case Intrinsic:
-    case MinIntrinsic:
-    case MinContent:
-    case MaxContent:
-    case FitContent:
-    case ExtendToZoom:
-    case Undefined:
-        ASSERT_NOT_REACHED();
-        return 0;
-    }
-    ASSERT_NOT_REACHED();
-    return 0;
-}
-
-} // namespace WebCore
diff --git a/Source/core/css/CSSLengthFunctions.h b/Source/core/css/CSSLengthFunctions.h
deleted file mode 100644
index 46e3540..0000000
--- a/Source/core/css/CSSLengthFunctions.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
-    Copyright (C) 1999 Lars Knoll (knoll@kde.org)
-    Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
-    Copyright (C) 2011 Rik Cabanier (cabanier@adobe.com)
-    Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
-    Copyright (C) 2012 Motorola Mobility, Inc. All rights reserved.
-    Copyright (C) 2013 Google, Inc. All rights reserved.
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Library General Public
-    License as published by the Free Software Foundation; either
-    version 2 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Library General Public License for more details.
-
-    You should have received a copy of the GNU Library General Public License
-    along with this library; see the file COPYING.LIB.  If not, write to
-    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-    Boston, MA 02110-1301, USA.
-*/
-
-#ifndef CSSLengthFunctions_h
-#define CSSLengthFunctions_h
-
-namespace WebCore {
-
-class LayoutUnit;
-class Length;
-class RenderView;
-
-int minimumIntValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
-int intValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
-LayoutUnit minimumValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
-LayoutUnit valueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
-float floatValueForLength(const Length&, float maximumValue, RenderView*);
-
-} // namespace WebCore
-
-#endif // CSSLengthFunctions_h
diff --git a/Source/core/css/CSSLineBoxContainValue.h b/Source/core/css/CSSLineBoxContainValue.h
index 657578a..38185ce 100644
--- a/Source/core/css/CSSLineBoxContainValue.h
+++ b/Source/core/css/CSSLineBoxContainValue.h
@@ -40,15 +40,17 @@
 // Used for text-CSSLineBoxContain and box-CSSLineBoxContain
 class CSSLineBoxContainValue : public CSSValue {
 public:
-    static PassRefPtr<CSSLineBoxContainValue> create(LineBoxContain value)
+    static PassRefPtrWillBeRawPtr<CSSLineBoxContainValue> create(LineBoxContain value)
     {
-        return adoptRef(new CSSLineBoxContainValue(value));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSLineBoxContainValue(value));
     }
 
     String customCSSText() const;
     bool equals(const CSSLineBoxContainValue& other) const { return m_value == other.m_value; }
     LineBoxContain value() const { return m_value; }
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     LineBoxContain m_value;
 
diff --git a/Source/core/css/CSSMarkup.cpp b/Source/core/css/CSSMarkup.cpp
new file mode 100644
index 0000000..cc47353
--- /dev/null
+++ b/Source/core/css/CSSMarkup.cpp
@@ -0,0 +1,189 @@
+/*
+ * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
+ * Copyright (C) 2012 Intel Corporation. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/css/CSSMarkup.h"
+
+#include "wtf/HexNumber.h"
+#include "wtf/text/StringBuffer.h"
+
+namespace WebCore {
+
+template <typename CharacterType>
+static inline bool isCSSTokenizerIdentifier(const CharacterType* characters, unsigned length)
+{
+    const CharacterType* end = characters + length;
+
+    // -?
+    if (characters != end && characters[0] == '-')
+        ++characters;
+
+    // {nmstart}
+    if (characters == end || !(characters[0] == '_' || characters[0] >= 128 || isASCIIAlpha(characters[0])))
+        return false;
+    ++characters;
+
+    // {nmchar}*
+    for (; characters != end; ++characters) {
+        if (!(characters[0] == '_' || characters[0] == '-' || characters[0] >= 128 || isASCIIAlphanumeric(characters[0])))
+            return false;
+    }
+
+    return true;
+}
+
+// "ident" from the CSS tokenizer, minus backslash-escape sequences
+static bool isCSSTokenizerIdentifier(const String& string)
+{
+    unsigned length = string.length();
+
+    if (!length)
+        return false;
+
+    if (string.is8Bit())
+        return isCSSTokenizerIdentifier(string.characters8(), length);
+    return isCSSTokenizerIdentifier(string.characters16(), length);
+}
+
+template <typename CharacterType>
+static inline bool isCSSTokenizerURL(const CharacterType* characters, unsigned length)
+{
+    const CharacterType* end = characters + length;
+
+    for (; characters != end; ++characters) {
+        CharacterType c = characters[0];
+        switch (c) {
+        case '!':
+        case '#':
+        case '$':
+        case '%':
+        case '&':
+            break;
+        default:
+            if (c < '*')
+                return false;
+            if (c <= '~')
+                break;
+            if (c < 128)
+                return false;
+        }
+    }
+
+    return true;
+}
+
+// "url" from the CSS tokenizer, minus backslash-escape sequences
+static bool isCSSTokenizerURL(const String& string)
+{
+    unsigned length = string.length();
+
+    if (!length)
+        return true;
+
+    if (string.is8Bit())
+        return isCSSTokenizerURL(string.characters8(), length);
+    return isCSSTokenizerURL(string.characters16(), length);
+}
+
+template <typename CharacterType>
+static inline String quoteCSSStringInternal(const CharacterType* characters, unsigned length)
+{
+    // For efficiency, we first pre-calculate the length of the quoted string, then we build the actual one.
+    // Please see below for the actual logic.
+    unsigned quotedStringSize = 2; // Two quotes surrounding the entire string.
+    bool afterEscape = false;
+    for (unsigned i = 0; i < length; ++i) {
+        CharacterType ch = characters[i];
+        if (ch == '\\' || ch == '\'') {
+            quotedStringSize += 2;
+            afterEscape = false;
+        } else if (ch < 0x20 || ch == 0x7F) {
+            quotedStringSize += 2 + (ch >= 0x10);
+            afterEscape = true;
+        } else {
+            quotedStringSize += 1 + (afterEscape && (isASCIIHexDigit(ch) || ch == ' '));
+            afterEscape = false;
+        }
+    }
+
+    StringBuffer<CharacterType> buffer(quotedStringSize);
+    unsigned index = 0;
+    buffer[index++] = '\'';
+    afterEscape = false;
+    for (unsigned i = 0; i < length; ++i) {
+        CharacterType ch = characters[i];
+        if (ch == '\\' || ch == '\'') {
+            buffer[index++] = '\\';
+            buffer[index++] = ch;
+            afterEscape = false;
+        } else if (ch < 0x20 || ch == 0x7F) { // Control characters.
+            buffer[index++] = '\\';
+            placeByteAsHexCompressIfPossible(ch, buffer, index, Lowercase);
+            afterEscape = true;
+        } else {
+            // Space character may be required to separate backslash-escape sequence and normal characters.
+            if (afterEscape && (isASCIIHexDigit(ch) || ch == ' '))
+                buffer[index++] = ' ';
+            buffer[index++] = ch;
+            afterEscape = false;
+        }
+    }
+    buffer[index++] = '\'';
+
+    ASSERT(quotedStringSize == index);
+    return String::adopt(buffer);
+}
+
+// We use single quotes for now because markup.cpp uses double quotes.
+String quoteCSSString(const String& string)
+{
+    // This function expands each character to at most 3 characters ('\u0010' -> '\' '1' '0') as well as adds
+    // 2 quote characters (before and after). Make sure the resulting size (3 * length + 2) will not overflow unsigned.
+
+    unsigned length = string.length();
+
+    if (!length)
+        return String("\'\'");
+
+    if (length > std::numeric_limits<unsigned>::max() / 3 - 2)
+        return emptyString();
+
+    if (string.is8Bit())
+        return quoteCSSStringInternal(string.characters8(), length);
+    return quoteCSSStringInternal(string.characters16(), length);
+}
+
+String quoteCSSStringIfNeeded(const String& string)
+{
+    return isCSSTokenizerIdentifier(string) ? string : quoteCSSString(string);
+}
+
+String quoteCSSURLIfNeeded(const String& string)
+{
+    return isCSSTokenizerURL(string) ? string : quoteCSSString(string);
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/CSSMarkup.h b/Source/core/css/CSSMarkup.h
new file mode 100644
index 0000000..9d37fff
--- /dev/null
+++ b/Source/core/css/CSSMarkup.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2009 - 2010  Torch Mobile (Beijing) Co. Ltd. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef CSSMarkup_h
+#define CSSMarkup_h
+
+#include "wtf/text/WTFString.h"
+
+// Helper functions for converting from CSSValues to text.
+// FIXME: This file has a similar purpose to
+// CSSOMUtils.h. Perhaps the two should be combined?
+
+namespace WebCore {
+
+String quoteCSSString(const String&);
+String quoteCSSStringIfNeeded(const String&);
+String quoteCSSURLIfNeeded(const String&);
+
+} // namespace WebCore
+
+#endif // CSSMarkup_h
diff --git a/Source/core/css/CSSMatrix.cpp b/Source/core/css/CSSMatrix.cpp
index 4926df9..f1138ba 100644
--- a/Source/core/css/CSSMatrix.cpp
+++ b/Source/core/css/CSSMatrix.cpp
@@ -29,7 +29,7 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "bindings/v8/ExceptionState.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSToLengthConversionData.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/TransformBuilder.h"
@@ -58,7 +58,7 @@
         return;
 
     RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create();
-    if (CSSParser::parseValue(styleDeclaration.get(), CSSPropertyWebkitTransform, string, true, HTMLStandardMode, 0)) {
+    if (BisonCSSParser::parseValue(styleDeclaration.get(), CSSPropertyWebkitTransform, string, true, HTMLStandardMode, 0)) {
         // Convert to TransformOperations. This can fail if a property
         // requires style (i.e., param uses 'ems' or 'exs')
         RefPtr<CSSValue> value = styleDeclaration->getPropertyCSSValue(CSSPropertyWebkitTransform);
@@ -69,22 +69,22 @@
 
         DEFINE_STATIC_REF(RenderStyle, defaultStyle, RenderStyle::createDefaultStyle());
         TransformOperations operations;
-        if (!TransformBuilder::createTransformOperations(value.get(), CSSToLengthConversionData(defaultStyle, defaultStyle), operations)) {
-            exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        if (!TransformBuilder::createTransformOperations(value.get(), CSSToLengthConversionData(defaultStyle, defaultStyle, 0, 0, 1.0f), operations)) {
+            exceptionState.throwDOMException(SyntaxError, "Failed to interpret '" + string + "' as a transformation operation.");
             return;
         }
 
         // Convert transform operations to a TransformationMatrix. This can fail
         // if a param has a percentage ('%')
         if (operations.dependsOnBoxSize())
-            exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+            exceptionState.throwDOMException(SyntaxError, "The transformation depends on the box size, which is not supported.");
         TransformationMatrix t;
         operations.apply(FloatSize(0, 0), t);
 
         // set the matrix
         m_matrix = t;
     } else { // There is something there but parsing failed.
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "Failed to parse '" + string + "'.");
     }
 }
 
@@ -100,7 +100,7 @@
 PassRefPtr<CSSMatrix> CSSMatrix::inverse(ExceptionState& exceptionState) const
 {
     if (!m_matrix.isInvertible()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The matrix is not invertable.");
         return 0;
     }
 
diff --git a/Source/core/css/CSSMediaRule.h b/Source/core/css/CSSMediaRule.h
index 380c062..3e46410 100644
--- a/Source/core/css/CSSMediaRule.h
+++ b/Source/core/css/CSSMediaRule.h
@@ -30,7 +30,7 @@
 
 class StyleRuleMedia;
 
-class CSSMediaRule : public CSSGroupingRule {
+class CSSMediaRule FINAL : public CSSGroupingRule {
 public:
     static PassRefPtr<CSSMediaRule> create(StyleRuleMedia* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSMediaRule(rule, sheet)); }
 
diff --git a/Source/core/css/CSSMixFunctionValue.cpp b/Source/core/css/CSSMixFunctionValue.cpp
deleted file mode 100644
index 0dd07a5..0000000
--- a/Source/core/css/CSSMixFunctionValue.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#include "config.h"
-#include "core/css/CSSMixFunctionValue.h"
-
-namespace WebCore {
-
-CSSMixFunctionValue::CSSMixFunctionValue()
-    : CSSValueList(CSSMixFunctionValueClass, SpaceSeparator)
-{
-}
-
-CSSMixFunctionValue::CSSMixFunctionValue(const CSSMixFunctionValue& cloneFrom)
-    : CSSValueList(cloneFrom)
-{
-}
-
-String CSSMixFunctionValue::customCSSText() const
-{
-    return "mix(" + CSSValueList::customCSSText() + ")";
-}
-
-PassRefPtr<CSSMixFunctionValue> CSSMixFunctionValue::cloneForCSSOM() const
-{
-    return adoptRef(new CSSMixFunctionValue(*this));
-}
-
-bool CSSMixFunctionValue::equals(const CSSMixFunctionValue& other) const
-{
-    return CSSValueList::equals(other);
-}
-
-} // namespace WebCore
-
diff --git a/Source/core/css/CSSMixFunctionValue.h b/Source/core/css/CSSMixFunctionValue.h
deleted file mode 100644
index 04a5e2d..0000000
--- a/Source/core/css/CSSMixFunctionValue.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef CSSMixFunctionValue_h
-#define CSSMixFunctionValue_h
-
-#include "core/css/CSSValueList.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-class CSSMixFunctionValue : public CSSValueList {
-public:
-    static PassRefPtr<CSSMixFunctionValue> create()
-    {
-        return adoptRef(new CSSMixFunctionValue());
-    }
-
-    String customCSSText() const;
-
-    PassRefPtr<CSSMixFunctionValue> cloneForCSSOM() const;
-
-    bool equals(const CSSMixFunctionValue&) const;
-
-private:
-    CSSMixFunctionValue();
-    CSSMixFunctionValue(const CSSMixFunctionValue& cloneFrom);
-};
-
-DEFINE_CSS_VALUE_TYPE_CASTS(CSSMixFunctionValue, isMixFunctionValue());
-
-} // namespace WebCore
-
-
-#endif
diff --git a/Source/core/css/CSSOMUtils.cpp b/Source/core/css/CSSOMUtils.cpp
index 36545dd..1e7882f 100644
--- a/Source/core/css/CSSOMUtils.cpp
+++ b/Source/core/css/CSSOMUtils.cpp
@@ -49,13 +49,6 @@
     appendTo.append(' ');
 }
 
-void serializeIdentifier(const String& identifier, String& appendTo)
-{
-    StringBuilder addend;
-    serializeIdentifier(identifier, addend);
-    appendTo.append(addend.toString());
-}
-
 void serializeIdentifier(const String& identifier, StringBuilder& appendTo)
 {
     bool isFirst = true;
@@ -85,13 +78,6 @@
     }
 }
 
-void serializeString(const String& string, String& appendTo)
-{
-    StringBuilder addend;
-    serializeString(string, addend);
-    appendTo.append(addend.toString());
-}
-
 void serializeString(const String& string, StringBuilder& appendTo)
 {
     appendTo.append('\"');
diff --git a/Source/core/css/CSSOMUtils.h b/Source/core/css/CSSOMUtils.h
index 3239ada..813396b 100644
--- a/Source/core/css/CSSOMUtils.h
+++ b/Source/core/css/CSSOMUtils.h
@@ -35,15 +35,15 @@
 #include "wtf/unicode/Unicode.h"
 
 // Utilities for CSSOM http://dev.w3.org/csswg/cssom/
+// FIXME: This file has a similar purpose to
+// CSSMarkup.h. Perhaps the two should be combined?
 
 namespace WebCore {
 
 // Common serializing methods. See: http://dev.w3.org/csswg/cssom/#common-serializing-idioms
 void serializeCharacter(UChar32, StringBuilder& appendTo);
 void serializeCharacterAsCodePoint(UChar32, StringBuilder& appendTo);
-void serializeIdentifier(const String& identifier, String& appendTo);
 void serializeIdentifier(const String& identifier, StringBuilder& appendTo);
-void serializeString(const String&, String& appendTo);
 void serializeString(const String&, StringBuilder& appendTo);
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSPageRule.cpp b/Source/core/css/CSSPageRule.cpp
index 0513e92..ff1544b 100644
--- a/Source/core/css/CSSPageRule.cpp
+++ b/Source/core/css/CSSPageRule.cpp
@@ -22,7 +22,7 @@
 #include "config.h"
 #include "core/css/CSSPageRule.h"
 
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/PropertySetCSSStyleDeclaration.h"
@@ -68,7 +68,8 @@
 
 void CSSPageRule::setSelectorText(const String& selectorText)
 {
-    CSSParser parser(parserContext());
+    CSSParserContext context(parserContext(), 0);
+    BisonCSSParser parser(context);
     CSSSelectorList selectorList;
     parser.parseSelector(selectorText, selectorList);
     if (!selectorList.isValid())
diff --git a/Source/core/css/CSSPageRule.h b/Source/core/css/CSSPageRule.h
index 4aa0f69..1a49ec6 100644
--- a/Source/core/css/CSSPageRule.h
+++ b/Source/core/css/CSSPageRule.h
@@ -31,7 +31,7 @@
 class StyleRulePage;
 class StyleRuleCSSStyleDeclaration;
 
-class CSSPageRule : public CSSRule {
+class CSSPageRule FINAL : public CSSRule {
 public:
     static PassRefPtr<CSSPageRule> create(StyleRulePage* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSPageRule(rule, sheet)); }
 
diff --git a/Source/core/css/CSSParserMode.cpp b/Source/core/css/CSSParserMode.cpp
index 420ecfa..e8951b8 100644
--- a/Source/core/css/CSSParserMode.cpp
+++ b/Source/core/css/CSSParserMode.cpp
@@ -28,23 +28,35 @@
 #include "core/css/CSSParserMode.h"
 
 #include "core/dom/Document.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 
 namespace WebCore {
 
-CSSParserContext::CSSParserContext(CSSParserMode mode)
+CSSParserContext::CSSParserContext(CSSParserMode mode, UseCounter* useCounter)
     : m_mode(mode)
     , m_isHTMLDocument(false)
     , m_useLegacyBackgroundSizeShorthandBehavior(false)
+    , m_useCounter(useCounter)
 {
 }
 
-CSSParserContext::CSSParserContext(const Document& document, const KURL& baseURL, const String& charset)
+CSSParserContext::CSSParserContext(const Document& document, UseCounter* useCounter, const KURL& baseURL, const String& charset)
     : m_baseURL(baseURL.isNull() ? document.baseURL() : baseURL)
     , m_charset(charset)
     , m_mode(document.inQuirksMode() ? HTMLQuirksMode : HTMLStandardMode)
     , m_isHTMLDocument(document.isHTMLDocument())
     , m_useLegacyBackgroundSizeShorthandBehavior(document.settings() ? document.settings()->useLegacyBackgroundSizeShorthandBehavior() : false)
+    , m_useCounter(useCounter)
+{
+}
+
+CSSParserContext::CSSParserContext(const CSSParserContext& other, UseCounter* useCounter)
+    : m_baseURL(other.m_baseURL)
+    , m_charset(other.m_charset)
+    , m_mode(other.m_mode)
+    , m_isHTMLDocument(other.m_isHTMLDocument)
+    , m_useLegacyBackgroundSizeShorthandBehavior(other.m_useLegacyBackgroundSizeShorthandBehavior)
+    , m_useCounter(useCounter)
 {
 }
 
@@ -59,8 +71,17 @@
 
 const CSSParserContext& strictCSSParserContext()
 {
-    DEFINE_STATIC_LOCAL(CSSParserContext, strictContext, (HTMLStandardMode));
+    DEFINE_STATIC_LOCAL(CSSParserContext, strictContext, (HTMLStandardMode, 0));
     return strictContext;
 }
 
+KURL CSSParserContext::completeURL(const String& url) const
+{
+    if (url.isNull())
+        return KURL();
+    if (charset().isEmpty())
+        return KURL(baseURL(), url);
+    return KURL(baseURL(), url, charset());
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSParserMode.h b/Source/core/css/CSSParserMode.h
index efcac21..078b74f 100644
--- a/Source/core/css/CSSParserMode.h
+++ b/Source/core/css/CSSParserMode.h
@@ -37,7 +37,7 @@
 
 class Document;
 
-// Must not grow beyond 3 bytes, due to packing in StylePropertySet.
+// Must not grow beyond 3 bits, due to packing in StylePropertySet.
 enum CSSParserMode {
     HTMLStandardMode,
     HTMLQuirksMode,
@@ -88,11 +88,18 @@
     return mode != UASheetMode;
 }
 
+class UseCounter;
+
 class CSSParserContext {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    CSSParserContext(CSSParserMode);
-    CSSParserContext(const Document&, const KURL& baseURL = KURL(), const String& charset = emptyString());
+    CSSParserContext(CSSParserMode, UseCounter*);
+    // FIXME: We shouldn't need the UseCounter argument as we could infer it from the Document
+    // but some callers want to disable use counting (e.g. the WebInspector).
+    CSSParserContext(const Document&, UseCounter*, const KURL& baseURL = KURL(), const String& charset = emptyString());
+    // FIXME: This constructor shouldn't exist if we properly piped the UseCounter through the CSS
+    // subsystem. Currently the UseCounter life time is too crazy and we need a way to override it.
+    CSSParserContext(const CSSParserContext&, UseCounter*);
 
     bool operator==(const CSSParserContext&) const;
     bool operator!=(const CSSParserContext& other) const { return !(*this == other); }
@@ -113,12 +120,18 @@
     void setBaseURL(const KURL& baseURL) { m_baseURL = baseURL; }
     void setCharset(const String& charset) { m_charset = charset; }
 
+    KURL completeURL(const String& url) const;
+
+    UseCounter* useCounter() const { return m_useCounter; }
+
 private:
     KURL m_baseURL;
     String m_charset;
     CSSParserMode m_mode;
     bool m_isHTMLDocument;
     bool m_useLegacyBackgroundSizeShorthandBehavior;
+
+    UseCounter* m_useCounter;
 };
 
 const CSSParserContext& strictCSSParserContext();
diff --git a/Source/core/css/CSSParserValues.cpp b/Source/core/css/CSSParserValues.cpp
index 10a940a..bde7fb7 100644
--- a/Source/core/css/CSSParserValues.cpp
+++ b/Source/core/css/CSSParserValues.cpp
@@ -75,10 +75,11 @@
     m_values.remove(i);
 }
 
-void CSSParserValueList::extend(CSSParserValueList& valueList)
+void CSSParserValueList::stealValues(CSSParserValueList& valueList)
 {
     for (unsigned int i = 0; i < valueList.size(); ++i)
         m_values.append(*(valueList.valueAt(i)));
+    valueList.clear();
 }
 
 PassRefPtr<CSSValue> CSSParserValue::createCSSValue()
@@ -88,12 +89,13 @@
         return CSSPrimitiveValue::createIdentifier(id);
 
     if (unit == CSSParserValue::Operator) {
-        RefPtr<CSSPrimitiveValue> primitiveValue = CSSPrimitiveValue::createParserOperator(iValue);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> primitiveValue = CSSPrimitiveValue::createParserOperator(iValue);
         primitiveValue->setPrimitiveType(CSSPrimitiveValue::CSS_PARSER_OPERATOR);
         return primitiveValue;
     }
-    if (unit == CSSParserValue::Function)
+    if (unit == CSSParserValue::Function) {
         return CSSFunctionValue::create(function);
+    }
     if (unit == CSSParserValue::ValueList)
         return CSSValueList::createFromParserValueList(valueList);
     if (unit >= CSSParserValue::Q_EMS)
@@ -109,7 +111,6 @@
         return CSSPrimitiveValue::create(fValue, isInt ? CSSPrimitiveValue::CSS_PARSER_INTEGER : CSSPrimitiveValue::CSS_NUMBER);
     case CSSPrimitiveValue::CSS_STRING:
     case CSSPrimitiveValue::CSS_URI:
-    case CSSPrimitiveValue::CSS_VARIABLE_NAME:
     case CSSPrimitiveValue::CSS_PARSER_HEXCOLOR:
         return CSSPrimitiveValue::create(string, primitiveUnit);
     case CSSPrimitiveValue::CSS_PERCENTAGE:
diff --git a/Source/core/css/CSSParserValues.h b/Source/core/css/CSSParserValues.h
index 7d423e7..d2879a4 100644
--- a/Source/core/css/CSSParserValues.h
+++ b/Source/core/css/CSSParserValues.h
@@ -176,7 +176,7 @@
     void addValue(const CSSParserValue&);
     void insertValueAt(unsigned, const CSSParserValue&);
     void deleteValueAt(unsigned);
-    void extend(CSSParserValueList&);
+    void stealValues(CSSParserValueList&);
 
     unsigned size() const { return m_values.size(); }
     unsigned currentIndex() { return m_current; }
@@ -262,7 +262,10 @@
 {
     id = CSSValueInvalid;
     isInt = false;
-    fValue = value;
+    if (std::isfinite(value))
+        fValue = value;
+    else
+        fValue = 0;
     this->unit = unit;
 }
 
diff --git a/Source/core/css/CSSPrimitiveValue.cpp b/Source/core/css/CSSPrimitiveValue.cpp
index eb350e7..d4d8810 100644
--- a/Source/core/css/CSSPrimitiveValue.cpp
+++ b/Source/core/css/CSSPrimitiveValue.cpp
@@ -25,7 +25,7 @@
 #include "core/css/CSSBasicShapes.h"
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSHelper.h"
-#include "core/css/CSSParser.h"
+#include "core/css/CSSMarkup.h"
 #include "core/css/CSSToLengthConversionData.h"
 #include "core/css/Counter.h"
 #include "core/css/Pair.h"
@@ -105,7 +105,6 @@
     case CSSPrimitiveValue::CSS_UNICODE_RANGE:
     case CSSPrimitiveValue::CSS_UNKNOWN:
     case CSSPrimitiveValue::CSS_URI:
-    case CSSPrimitiveValue::CSS_VARIABLE_NAME:
         return false;
     }
 
@@ -140,11 +139,6 @@
     case CSS_HZ:
     case CSS_KHZ:
         return CSSPrimitiveValue::UFrequency;
-    case CSS_VW:
-    case CSS_VH:
-    case CSS_VMIN:
-    case CSS_VMAX:
-        return CSSPrimitiveValue::UViewportPercentageLength;
     case CSS_DPPX:
     case CSS_DPI:
     case CSS_DPCM:
@@ -194,8 +188,6 @@
         return CSS_CALC_PERCENTAGE_WITH_NUMBER;
     case CalcPercentLength:
         return CSS_CALC_PERCENTAGE_WITH_LENGTH;
-    case CalcVariable:
-        return CSS_UNKNOWN; // The type of a calculation containing a variable cannot be known until the value of the variable is determined.
     case CalcOther:
         return CSS_UNKNOWN;
     }
@@ -265,6 +257,11 @@
         m_value.string->ref();
 }
 
+CSSPrimitiveValue::CSSPrimitiveValue(const LengthSize& lengthSize)
+    : CSSValue(PrimitiveClass)
+{
+    init(lengthSize);
+}
 
 CSSPrimitiveValue::CSSPrimitiveValue(RGBA32 color)
     : CSSValue(PrimitiveClass)
@@ -286,10 +283,6 @@
     case FitContent:
     case ExtendToZoom:
     case Percent:
-    case ViewportPercentageWidth:
-    case ViewportPercentageHeight:
-    case ViewportPercentageMin:
-    case ViewportPercentageMax:
         init(length);
         return;
     case Fixed:
@@ -299,12 +292,50 @@
     case Calculated:
         init(CSSCalcValue::create(length.calculationValue(), zoom));
         return;
+    case DeviceWidth:
+    case DeviceHeight:
     case Undefined:
         ASSERT_NOT_REACHED();
         break;
     }
 }
 
+// Remove below specialized constructors once all callers of CSSPrimitiveValue(...)
+// have been converted to PassRefPtrWillBeRawPtr, ie. when
+//    template<typename T> CSSPrimitiveValue(T* val)
+//    template<typename T> CSSPrimitiveValue(PassRefPtr<T> val)
+// both can be converted to use PassRefPtrWillBeRawPtr.
+CSSPrimitiveValue::CSSPrimitiveValue(CSSCalcValue* value)
+    : CSSValue(PrimitiveClass)
+{
+    init(PassRefPtrWillBeRawPtr<CSSCalcValue>(value));
+}
+CSSPrimitiveValue::CSSPrimitiveValue(PassRefPtrWillBeRawPtr<CSSCalcValue> value)
+    : CSSValue(PrimitiveClass)
+{
+    init(value);
+}
+CSSPrimitiveValue::CSSPrimitiveValue(Pair* value)
+    : CSSValue(PrimitiveClass)
+{
+    init(PassRefPtrWillBeRawPtr<Pair>(value));
+}
+CSSPrimitiveValue::CSSPrimitiveValue(PassRefPtrWillBeRawPtr<Pair> value)
+    : CSSValue(PrimitiveClass)
+{
+    init(value);
+}
+CSSPrimitiveValue::CSSPrimitiveValue(Counter* value)
+    : CSSValue(PrimitiveClass)
+{
+    init(PassRefPtrWillBeRawPtr<Counter>(value));
+}
+CSSPrimitiveValue::CSSPrimitiveValue(PassRefPtrWillBeRawPtr<Counter> value)
+    : CSSValue(PrimitiveClass)
+{
+    init(value);
+}
+
 void CSSPrimitiveValue::init(const Length& length)
 {
     switch (length.type()) {
@@ -349,22 +380,8 @@
             ASSERT(std::isfinite(length.percent()));
             m_value.num = length.percent();
             break;
-        case ViewportPercentageWidth:
-            m_primitiveUnitType = CSS_VW;
-            m_value.num = length.viewportPercentageLength();
-            break;
-        case ViewportPercentageHeight:
-            m_primitiveUnitType = CSS_VH;
-            m_value.num = length.viewportPercentageLength();
-            break;
-        case ViewportPercentageMin:
-            m_primitiveUnitType = CSS_VMIN;
-            m_value.num = length.viewportPercentageLength();
-            break;
-        case ViewportPercentageMax:
-            m_primitiveUnitType = CSS_VMAX;
-            m_value.num = length.viewportPercentageLength();
-            break;
+        case DeviceWidth:
+        case DeviceHeight:
         case Calculated:
         case Undefined:
             ASSERT_NOT_REACHED();
@@ -372,7 +389,14 @@
     }
 }
 
-void CSSPrimitiveValue::init(PassRefPtr<Counter> c)
+void CSSPrimitiveValue::init(const LengthSize& lengthSize)
+{
+    m_primitiveUnitType = CSS_PAIR;
+    m_hasCachedCSSText = false;
+    m_value.pair = Pair::create(create(lengthSize.width()), create(lengthSize.height()), Pair::KeepIdenticalValues).leakRef();
+}
+
+void CSSPrimitiveValue::init(PassRefPtrWillBeRawPtr<Counter> c)
 {
     m_primitiveUnitType = CSS_COUNTER;
     m_hasCachedCSSText = false;
@@ -393,14 +417,14 @@
     m_value.quad = quad.leakRef();
 }
 
-void CSSPrimitiveValue::init(PassRefPtr<Pair> p)
+void CSSPrimitiveValue::init(PassRefPtrWillBeRawPtr<Pair> p)
 {
     m_primitiveUnitType = CSS_PAIR;
     m_hasCachedCSSText = false;
     m_value.pair = p.leakRef();
 }
 
-void CSSPrimitiveValue::init(PassRefPtr<CSSCalcValue> c)
+void CSSPrimitiveValue::init(PassRefPtrWillBeRawPtr<CSSCalcValue> c)
 {
     m_primitiveUnitType = CSS_CALC;
     m_hasCachedCSSText = false;
@@ -426,13 +450,15 @@
     case CSS_URI:
     case CSS_ATTR:
     case CSS_COUNTER_NAME:
-    case CSS_VARIABLE_NAME:
     case CSS_PARSER_HEXCOLOR:
         if (m_value.string)
             m_value.string->deref();
         break;
     case CSS_COUNTER:
+        // We must not call deref() when oilpan is enabled because m_value.counter is traced.
+#if !ENABLE(OILPAN)
         m_value.counter->deref();
+#endif
         break;
     case CSS_RECT:
         m_value.rect->deref();
@@ -441,10 +467,16 @@
         m_value.quad->deref();
         break;
     case CSS_PAIR:
+        // We must not call deref() when oilpan is enabled because m_value.pair is traced.
+#if !ENABLE(OILPAN)
         m_value.pair->deref();
+#endif
         break;
     case CSS_CALC:
+        // We must not call deref() when oilpan is enabled because m_value.calc is traced.
+#if !ENABLE(OILPAN)
         m_value.calc->deref();
+#endif
         break;
     case CSS_CALC_PERCENTAGE_WITH_NUMBER:
     case CSS_CALC_PERCENTAGE_WITH_LENGTH:
@@ -600,6 +632,18 @@
         case CSS_PC:
             factor = cssPixelsPerPica;
             break;
+        case CSS_VW:
+            factor = conversionData.viewportWidthPercent();
+            break;
+        case CSS_VH:
+            factor = conversionData.viewportHeightPercent();
+            break;
+        case CSS_VMIN:
+            factor = conversionData.viewportMinPercent();
+            break;
+        case CSS_VMAX:
+            factor = conversionData.viewportMaxPercent();
+            break;
         case CSS_CALC_PERCENTAGE_WITH_LENGTH:
         case CSS_CALC_PERCENTAGE_WITH_NUMBER:
             ASSERT_NOT_REACHED();
@@ -624,7 +668,7 @@
     // Keeping values immutable makes optimizations easier and allows sharing of the primitive value objects.
     // No other engine supports mutating style through this API. Computed style is always read-only anyway.
     // Supporting setter would require making primitive value copy-on-write and taking care of style invalidation.
-    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwDOMException(NoModificationAllowedError, "CSSPrimitiveValue objects are read-only.");
 }
 
 double CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(unsigned short unitType)
@@ -684,7 +728,7 @@
     double result = 0;
     bool success = getDoubleValueInternal(static_cast<UnitTypes>(unitType), &result);
     if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "Failed to obtain a double value.");
         return 0.0;
     }
 
@@ -705,7 +749,7 @@
 
 CSSPrimitiveValue::UnitTypes CSSPrimitiveValue::canonicalUnitTypeForCategory(UnitCategory category)
 {
-    // The canonical unit type is chosen according to the way CSSParser::validUnit() chooses the default unit
+    // The canonical unit type is chosen according to the way BisonCSSParser::validUnit() chooses the default unit
     // in each category (based on unitflags).
     switch (category) {
     case UNumber:
@@ -720,8 +764,6 @@
         return CSS_DEG;
     case UFrequency:
         return CSS_HZ;
-    case UViewportPercentageLength:
-        return CSS_UNKNOWN; // Cannot convert between numbers and relative lengths.
     case UResolution:
         return CSS_DPPX;
     default:
@@ -759,7 +801,7 @@
     }
 
     if (sourceUnitType == CSS_NUMBER) {
-        // We interpret conversion from CSS_NUMBER in the same way as CSSParser::validUnit() while using non-strict mode.
+        // We interpret conversion from CSS_NUMBER in the same way as BisonCSSParser::validUnit() while using non-strict mode.
         sourceUnitType = canonicalUnitTypeForCategory(targetCategory);
         if (sourceUnitType == CSS_UNKNOWN)
             return false;
@@ -784,7 +826,7 @@
     // Keeping values immutable makes optimizations easier and allows sharing of the primitive value objects.
     // No other engine supports mutating style through this API. Computed style is always read-only anyway.
     // Supporting setter would require making primitive value copy-on-write and taking care of style invalidation.
-    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwDOMException(NoModificationAllowedError, "CSSPrimitiveValue objects are read-only.");
 }
 
 String CSSPrimitiveValue::getStringValue(ExceptionState& exceptionState) const
@@ -793,14 +835,13 @@
         case CSS_STRING:
         case CSS_ATTR:
         case CSS_URI:
-        case CSS_VARIABLE_NAME:
             return m_value.string;
         case CSS_VALUE_ID:
             return valueName(m_value.valueID);
         case CSS_PROPERTY_ID:
             return propertyName(m_value.propertyID);
         default:
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+            exceptionState.throwDOMException(InvalidAccessError, "This object's value cannot be represented as a string.");
             break;
     }
 
@@ -813,7 +854,6 @@
         case CSS_STRING:
         case CSS_ATTR:
         case CSS_URI:
-        case CSS_VARIABLE_NAME:
             return m_value.string;
         case CSS_VALUE_ID:
             return valueName(m_value.valueID);
@@ -829,7 +869,7 @@
 Counter* CSSPrimitiveValue::getCounterValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_COUNTER) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "This object is not a counter value.");
         return 0;
     }
 
@@ -839,7 +879,7 @@
 Rect* CSSPrimitiveValue::getRectValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_RECT) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "This object is not a rect value.");
         return 0;
     }
 
@@ -849,7 +889,7 @@
 Quad* CSSPrimitiveValue::getQuadValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_QUAD) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "This object is not a quad value.");
         return 0;
     }
 
@@ -859,7 +899,7 @@
 PassRefPtr<RGBColor> CSSPrimitiveValue::getRGBColorValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_RGBCOLOR) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "This object is not an RGB color value.");
         return 0;
     }
 
@@ -870,7 +910,7 @@
 Pair* CSSPrimitiveValue::getPairValue(ExceptionState& exceptionState) const
 {
     if (m_primitiveUnitType != CSS_PAIR) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "This object is not a pair value.");
         return 0;
     }
 
@@ -1046,32 +1086,7 @@
             if (m_primitiveUnitType == CSS_PARSER_HEXCOLOR)
                 Color::parseHexColor(m_value.string, rgbColor);
             Color color(rgbColor);
-
-            StringBuilder result;
-            result.reserveCapacity(32);
-            bool colorHasAlpha = color.hasAlpha();
-            if (colorHasAlpha)
-                result.append("rgba(", 5);
-            else
-                result.append("rgb(", 4);
-
-            result.appendNumber(static_cast<unsigned char>(color.red()));
-            result.append(", ", 2);
-
-            result.appendNumber(static_cast<unsigned char>(color.green()));
-            result.append(", ", 2);
-
-            result.appendNumber(static_cast<unsigned char>(color.blue()));
-            if (colorHasAlpha) {
-                result.append(", ", 2);
-
-                NumberToStringBuffer buffer;
-                const char* alphaString = numberToFixedPrecisionString(color.alpha() / 255.0f, 6, buffer, true);
-                result.append(alphaString, strlen(alphaString));
-            }
-
-            result.append(')');
-            text = result.toString();
+            text = color.serializedAsCSSComponentValue();
             break;
         }
         case CSS_FR:
@@ -1106,9 +1121,6 @@
         case CSS_VMAX:
             text = formatNumber(m_value.num, "vmax");
             break;
-        case CSS_VARIABLE_NAME:
-            text = "var(" + String(m_value.string) + ")";
-            break;
     }
 
     ASSERT(!cssTextCache().contains(this));
@@ -1117,73 +1129,9 @@
     return text;
 }
 
-String CSSPrimitiveValue::customSerializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> CSSPrimitiveValue::cloneForCSSOM() const
 {
-    if (isVariableName()) {
-        AtomicString variableName(m_value.string);
-        if (variables.contains(variableName))
-            return variables.get(variableName);
-    }
-    if (CSSCalcValue* calcValue = cssCalcValue())
-        return calcValue->customSerializeResolvingVariables(variables);
-    if (Pair* pairValue = getPairValue())
-        return pairValue->serializeResolvingVariables(variables);
-    if (Rect* rectVal = getRectValue())
-        return rectVal->serializeResolvingVariables(variables);
-    if (Quad* quadVal = getQuadValue())
-        return quadVal->serializeResolvingVariables(variables);
-    if (CSSBasicShape* shapeValue = getShapeValue())
-        return shapeValue->serializeResolvingVariables(variables);
-    return customCSSText();
-}
-
-bool CSSPrimitiveValue::hasVariableReference() const
-{
-    if (CSSCalcValue* calcValue = cssCalcValue())
-        return calcValue->hasVariableReference();
-    if (Pair* pairValue = getPairValue())
-        return pairValue->hasVariableReference();
-    if (Quad* quadValue = getQuadValue())
-        return quadValue->hasVariableReference();
-    if (Rect* rectValue = getRectValue())
-        return rectValue->hasVariableReference();
-    if (CSSBasicShape* shapeValue = getShapeValue())
-        return shapeValue->hasVariableReference();
-    return isVariableName();
-}
-
-void CSSPrimitiveValue::addSubresourceStyleURLs(ListHashSet<KURL>& urls, const StyleSheetContents* styleSheet) const
-{
-    if (m_primitiveUnitType == CSS_URI)
-        addSubresourceURL(urls, styleSheet->completeURL(m_value.string));
-}
-
-Length CSSPrimitiveValue::viewportPercentageLength()
-{
-    ASSERT(isViewportPercentageLength());
-    Length viewportLength;
-    switch (m_primitiveUnitType) {
-    case CSS_VW:
-        viewportLength = Length(getDoubleValue(), ViewportPercentageWidth);
-        break;
-    case CSS_VH:
-        viewportLength = Length(getDoubleValue(), ViewportPercentageHeight);
-        break;
-    case CSS_VMIN:
-        viewportLength = Length(getDoubleValue(), ViewportPercentageMin);
-        break;
-    case CSS_VMAX:
-        viewportLength = Length(getDoubleValue(), ViewportPercentageMax);
-        break;
-    default:
-        break;
-    }
-    return viewportLength;
-}
-
-PassRefPtr<CSSPrimitiveValue> CSSPrimitiveValue::cloneForCSSOM() const
-{
-    RefPtr<CSSPrimitiveValue> result;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> result;
 
     switch (m_primitiveUnitType) {
     case CSS_STRING:
@@ -1315,7 +1263,6 @@
     case CSS_COUNTER_NAME:
     case CSS_PARSER_IDENTIFIER:
     case CSS_PARSER_HEXCOLOR:
-    case CSS_VARIABLE_NAME:
         return equal(m_value.string, other.m_value.string);
     case CSS_COUNTER:
         return m_value.counter && other.m_value.counter && m_value.counter->equals(*other.m_value.counter);
@@ -1337,4 +1284,22 @@
     return false;
 }
 
+void CSSPrimitiveValue::traceAfterDispatch(Visitor* visitor)
+{
+    switch (m_primitiveUnitType) {
+    case CSS_COUNTER:
+        visitor->trace(m_value.counter);
+        break;
+    case CSS_PAIR:
+        visitor->trace(m_value.pair);
+        break;
+    case CSS_CALC:
+        visitor->trace(m_value.calc);
+        break;
+    default:
+        break;
+    }
+    CSSValue::traceAfterDispatch(visitor);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSPrimitiveValue.h b/Source/core/css/CSSPrimitiveValue.h
index 65b1cfb..0c53c77 100644
--- a/Source/core/css/CSSPrimitiveValue.h
+++ b/Source/core/css/CSSPrimitiveValue.h
@@ -38,6 +38,7 @@
 class Counter;
 class ExceptionState;
 class Length;
+class LengthSize;
 class Pair;
 class Quad;
 class RGBColor;
@@ -130,13 +131,12 @@
         CSS_CALC = 113,
         CSS_CALC_PERCENTAGE_WITH_NUMBER = 114,
         CSS_CALC_PERCENTAGE_WITH_LENGTH = 115,
-        CSS_VARIABLE_NAME = 116,
 
         CSS_PROPERTY_ID = 117,
         CSS_VALUE_ID = 118
     };
 
-    // This enum follows the CSSParser::Units enum augmented with UNIT_FREQUENCY for frequencies.
+    // This enum follows the BisonCSSParser::Units enum augmented with UNIT_FREQUENCY for frequencies.
     enum UnitCategory {
         UNumber,
         UPercent,
@@ -144,7 +144,6 @@
         UAngle,
         UTime,
         UFrequency,
-        UViewportPercentageLength,
         UResolution,
         UOther
     };
@@ -170,7 +169,7 @@
     bool isLength() const
     {
         unsigned short type = primitiveType();
-        return (type >= CSS_EMS && type <= CSS_PC) || type == CSS_REMS || type == CSS_CHS;
+        return (type >= CSS_EMS && type <= CSS_PC) || type == CSS_REMS || type == CSS_CHS || isViewportPercentageLength();
     }
     bool isNumber() const { return primitiveType() == CSS_NUMBER; }
     bool isPercentage() const { return primitiveType() == CSS_PERCENTAGE; }
@@ -192,34 +191,57 @@
         unsigned short type = primitiveType();
         return type >= CSS_DPPX && type <= CSS_DPCM;
     }
-    bool isVariableName() const { return primitiveType() == CSS_VARIABLE_NAME; }
     bool isViewportPercentageLength() const { return m_primitiveUnitType >= CSS_VW && m_primitiveUnitType <= CSS_VMAX; }
     bool isFlex() const { return primitiveType() == CSS_FR; }
     bool isValueID() const { return m_primitiveUnitType == CSS_VALUE_ID; }
     bool colorIsDerivedFromElement() const;
 
-    static PassRefPtr<CSSPrimitiveValue> createIdentifier(CSSValueID valueID) { return adoptRef(new CSSPrimitiveValue(valueID)); }
-    static PassRefPtr<CSSPrimitiveValue> createIdentifier(CSSPropertyID propertyID) { return adoptRef(new CSSPrimitiveValue(propertyID)); }
-    static PassRefPtr<CSSPrimitiveValue> createParserOperator(int parserOperator) { return adoptRef(new CSSPrimitiveValue(parserOperator)); }
-    static PassRefPtr<CSSPrimitiveValue> createColor(unsigned rgbValue) { return adoptRef(new CSSPrimitiveValue(rgbValue)); }
-    static PassRefPtr<CSSPrimitiveValue> create(double value, UnitTypes type) { return adoptRef(new CSSPrimitiveValue(value, type)); }
-    static PassRefPtr<CSSPrimitiveValue> create(const String& value, UnitTypes type) { return adoptRef(new CSSPrimitiveValue(value, type)); }
-    static PassRefPtr<CSSPrimitiveValue> create(const Length& value, float zoom) { return adoptRef(new CSSPrimitiveValue(value, zoom)); }
-
-    template<typename T> static PassRefPtr<CSSPrimitiveValue> create(T value)
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createIdentifier(CSSValueID valueID)
     {
-        return adoptRef(new CSSPrimitiveValue(value));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSPrimitiveValue(valueID));
+    }
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createIdentifier(CSSPropertyID propertyID)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSPrimitiveValue(propertyID));
+    }
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createParserOperator(int parserOperator)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSPrimitiveValue(parserOperator));
+    }
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createColor(unsigned rgbValue)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSPrimitiveValue(rgbValue));
+    }
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> create(double value, UnitTypes type)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSPrimitiveValue(value, type));
+    }
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> create(const String& value, UnitTypes type)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSPrimitiveValue(value, type));
+    }
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> create(const Length& value, float zoom)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSPrimitiveValue(value, zoom));
+    }
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> create(const LengthSize& value)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSPrimitiveValue(value));
+    }
+    template<typename T> static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> create(T value)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSPrimitiveValue(value));
     }
 
     // This value is used to handle quirky margins in reflow roots (body, td, and th) like WinIE.
     // The basic idea is that a stylesheet can use the value __qem (for quirky em) instead of em.
     // When the quirky value is used, if you're in quirks mode, the margin will collapse away
     // inside a table cell.
-    static PassRefPtr<CSSPrimitiveValue> createAllowingMarginQuirk(double value, UnitTypes type)
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createAllowingMarginQuirk(double value, UnitTypes type)
     {
         CSSPrimitiveValue* quirkValue = new CSSPrimitiveValue(value, type);
         quirkValue->m_isQuirkValue = true;
-        return adoptRef(quirkValue);
+        return adoptRefCountedWillBeRefCountedGarbageCollected(quirkValue);
     }
 
     ~CSSPrimitiveValue();
@@ -308,20 +330,16 @@
     template<typename T> inline operator T() const; // Defined in CSSPrimitiveValueMappings.h
 
     String customCSSText(CSSTextFormattingFlags = QuoteCSSStringIfNeeded) const;
-    String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
-    bool hasVariableReference() const;
 
     bool isQuirkValue() { return m_isQuirkValue; }
 
-    void addSubresourceStyleURLs(ListHashSet<KURL>&, const StyleSheetContents*) const;
-
-    Length viewportPercentageLength();
-
-    PassRefPtr<CSSPrimitiveValue> cloneForCSSOM() const;
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> cloneForCSSOM() const;
     void setCSSOMSafe() { m_isCSSOMSafe = true; }
 
     bool equals(const CSSPrimitiveValue&) const;
 
+    void traceAfterDispatch(Visitor*);
+
     static UnitTypes canonicalUnitTypeForCategory(UnitCategory);
     static double conversionToCanonicalUnitsScaleFactor(unsigned short unitType);
 
@@ -337,6 +355,7 @@
         init(length);
     }
     CSSPrimitiveValue(const Length&, float zoom);
+    CSSPrimitiveValue(const LengthSize&);
     CSSPrimitiveValue(const String&, UnitTypes);
     CSSPrimitiveValue(double, UnitTypes);
 
@@ -353,17 +372,27 @@
         init(val);
     }
 
+    // Remove below overloaded constructors once all callers of CSSPrimitiveValue(...)
+    // have been converted to PassRefPtrWillBeRawPtr.
+    explicit CSSPrimitiveValue(CSSCalcValue*);
+    explicit CSSPrimitiveValue(PassRefPtrWillBeRawPtr<CSSCalcValue>);
+    explicit CSSPrimitiveValue(Pair*);
+    explicit CSSPrimitiveValue(PassRefPtrWillBeRawPtr<Pair>);
+    explicit CSSPrimitiveValue(Counter*);
+    explicit CSSPrimitiveValue(PassRefPtrWillBeRawPtr<Counter>);
+
     static void create(int); // compile-time guard
     static void create(unsigned); // compile-time guard
     template<typename T> operator T*(); // compile-time guard
 
     void init(const Length&);
-    void init(PassRefPtr<Counter>);
+    void init(const LengthSize&);
+    void init(PassRefPtrWillBeRawPtr<Counter>);
     void init(PassRefPtr<Rect>);
-    void init(PassRefPtr<Pair>);
+    void init(PassRefPtrWillBeRawPtr<Pair>);
     void init(PassRefPtr<Quad>);
     void init(PassRefPtr<CSSBasicShape>);
-    void init(PassRefPtr<CSSCalcValue>);
+    void init(PassRefPtrWillBeRawPtr<CSSCalcValue>);
     bool getDoubleValueInternal(UnitTypes targetUnitType, double* result) const;
 
     double computeLengthDouble(const CSSToLengthConversionData&);
@@ -374,13 +403,14 @@
         int parserOperator;
         double num;
         StringImpl* string;
-        Counter* counter;
         Rect* rect;
         Quad* quad;
         unsigned rgbcolor;
-        Pair* pair;
         CSSBasicShape* shape;
+        // FIXME: oilpan: Should be members, but no support for members in unions. Just trace the raw ptr for now.
         CSSCalcValue* calc;
+        Counter* counter;
+        Pair* pair;
     } m_value;
 };
 
diff --git a/Source/core/css/CSSPrimitiveValueMappings.h b/Source/core/css/CSSPrimitiveValueMappings.h
index 4b5b0a4..fb459a0 100644
--- a/Source/core/css/CSSPrimitiveValueMappings.h
+++ b/Source/core/css/CSSPrimitiveValueMappings.h
@@ -45,6 +45,7 @@
 #include "platform/fonts/TextRenderingMode.h"
 #include "platform/graphics/GraphicsTypes.h"
 #include "platform/graphics/Path.h"
+#include "platform/scroll/ScrollableArea.h"
 #include "platform/text/TextDirection.h"
 #include "platform/text/UnicodeBidi.h"
 #include "platform/text/WritingMode.h"
@@ -61,11 +62,8 @@
 
 template<> inline CSSPrimitiveValue::operator short() const
 {
-    if (m_primitiveUnitType == CSS_NUMBER)
-        return clampTo<short>(m_value.num);
-
-    ASSERT_NOT_REACHED();
-    return 0;
+    ASSERT(isNumber());
+    return clampTo<short>(getDoubleValue());
 }
 
 template<> inline CSSPrimitiveValue::CSSPrimitiveValue(unsigned short i)
@@ -77,29 +75,20 @@
 
 template<> inline CSSPrimitiveValue::operator unsigned short() const
 {
-    if (m_primitiveUnitType == CSS_NUMBER)
-        return clampTo<unsigned short>(m_value.num);
-
-    ASSERT_NOT_REACHED();
-    return 0;
+    ASSERT(isNumber());
+    return clampTo<unsigned short>(getDoubleValue());
 }
 
 template<> inline CSSPrimitiveValue::operator int() const
 {
-    if (m_primitiveUnitType == CSS_NUMBER)
-        return clampTo<int>(m_value.num);
-
-    ASSERT_NOT_REACHED();
-    return 0;
+    ASSERT(isNumber());
+    return clampTo<int>(getDoubleValue());
 }
 
 template<> inline CSSPrimitiveValue::operator unsigned() const
 {
-    if (m_primitiveUnitType == CSS_NUMBER)
-        return clampTo<unsigned>(m_value.num);
-
-    ASSERT_NOT_REACHED();
-    return 0;
+    ASSERT(isNumber());
+    return clampTo<unsigned>(getDoubleValue());
 }
 
 
@@ -112,11 +101,8 @@
 
 template<> inline CSSPrimitiveValue::operator float() const
 {
-    if (m_primitiveUnitType == CSS_NUMBER)
-        return clampTo<float>(m_value.num);
-
-    ASSERT_NOT_REACHED();
-    return 0.0f;
+    ASSERT(isNumber());
+    return clampTo<float>(getDoubleValue());
 }
 
 template<> inline CSSPrimitiveValue::CSSPrimitiveValue(LineClampValue i)
@@ -460,18 +446,6 @@
     case MediaMuteButtonPart:
         m_value.valueID = CSSValueMediaMuteButton;
         break;
-    case MediaSeekBackButtonPart:
-        m_value.valueID = CSSValueMediaSeekBackButton;
-        break;
-    case MediaSeekForwardButtonPart:
-        m_value.valueID = CSSValueMediaSeekForwardButton;
-        break;
-    case MediaRewindButtonPart:
-        m_value.valueID = CSSValueMediaRewindButton;
-        break;
-    case MediaReturnToRealtimeButtonPart:
-        m_value.valueID = CSSValueMediaReturnToRealtimeButton;
-        break;
     case MediaToggleClosedCaptionsButtonPart:
         m_value.valueID = CSSValueMediaToggleClosedCaptionsButton;
         break;
@@ -487,9 +461,6 @@
     case MediaVolumeSliderPart:
         m_value.valueID = CSSValueMediaVolumeSlider;
         break;
-    case MediaVolumeSliderMuteButtonPart:
-        m_value.valueID = CSSValueMediaVolumeSliderMuteButton;
-        break;
     case MediaVolumeSliderThumbPart:
         m_value.valueID = CSSValueMediaVolumeSliderthumb;
         break;
@@ -1346,56 +1317,6 @@
     return SHOW;
 }
 
-template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EAlignItems e)
-    : CSSValue(PrimitiveClass)
-{
-    m_primitiveUnitType = CSS_VALUE_ID;
-    switch (e) {
-    case AlignAuto:
-        m_value.valueID = CSSValueAuto;
-        break;
-    case AlignFlexStart:
-        m_value.valueID = CSSValueFlexStart;
-        break;
-    case AlignFlexEnd:
-        m_value.valueID = CSSValueFlexEnd;
-        break;
-    case AlignCenter:
-        m_value.valueID = CSSValueCenter;
-        break;
-    case AlignStretch:
-        m_value.valueID = CSSValueStretch;
-        break;
-    case AlignBaseline:
-        m_value.valueID = CSSValueBaseline;
-        break;
-    }
-}
-
-template<> inline CSSPrimitiveValue::operator EAlignItems() const
-{
-    ASSERT(isValueID());
-    switch (m_value.valueID) {
-    case CSSValueAuto:
-        return AlignAuto;
-    case CSSValueFlexStart:
-        return AlignFlexStart;
-    case CSSValueFlexEnd:
-        return AlignFlexEnd;
-    case CSSValueCenter:
-        return AlignCenter;
-    case CSSValueStretch:
-        return AlignStretch;
-    case CSSValueBaseline:
-        return AlignBaseline;
-    default:
-        break;
-    }
-
-    ASSERT_NOT_REACHED();
-    return AlignFlexStart;
-}
-
 template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EJustifyContent e)
     : CSSValue(PrimitiveClass)
 {
@@ -2014,36 +1935,6 @@
     return MNONE;
 }
 
-template<> inline CSSPrimitiveValue::CSSPrimitiveValue(RegionFragment e)
-    : CSSValue(PrimitiveClass)
-{
-    m_primitiveUnitType = CSS_VALUE_ID;
-    switch (e) {
-    case AutoRegionFragment:
-        m_value.valueID = CSSValueAuto;
-        break;
-    case BreakRegionFragment:
-        m_value.valueID = CSSValueBreak;
-        break;
-    }
-}
-
-template<> inline CSSPrimitiveValue::operator RegionFragment() const
-{
-    ASSERT(isValueID());
-    switch (m_value.valueID) {
-    case CSSValueAuto:
-        return AutoRegionFragment;
-    case CSSValueBreak:
-        return BreakRegionFragment;
-    default:
-        break;
-    }
-
-    ASSERT_NOT_REACHED();
-    return AutoRegionFragment;
-}
-
 template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EMarqueeDirection e)
     : CSSValue(PrimitiveClass)
 {
@@ -3697,71 +3588,6 @@
     return AutoTextRendering;
 }
 
-template<> inline CSSPrimitiveValue::CSSPrimitiveValue(LineSnap gridSnap)
-    : CSSValue(PrimitiveClass)
-{
-    m_primitiveUnitType = CSS_VALUE_ID;
-    switch (gridSnap) {
-    case LineSnapNone:
-        m_value.valueID = CSSValueNone;
-        break;
-    case LineSnapBaseline:
-        m_value.valueID = CSSValueBaseline;
-        break;
-    case LineSnapContain:
-        m_value.valueID = CSSValueContain;
-        break;
-    }
-}
-
-template<> inline CSSPrimitiveValue::operator LineSnap() const
-{
-    ASSERT(isValueID());
-    switch (m_value.valueID) {
-    case CSSValueNone:
-        return LineSnapNone;
-    case CSSValueBaseline:
-        return LineSnapBaseline;
-    case CSSValueContain:
-        return LineSnapContain;
-    default:
-        break;
-    }
-
-    ASSERT_NOT_REACHED();
-    return LineSnapNone;
-}
-
-template<> inline CSSPrimitiveValue::CSSPrimitiveValue(LineAlign lineAlign)
-    : CSSValue(PrimitiveClass)
-{
-    m_primitiveUnitType = CSS_VALUE_ID;
-    switch (lineAlign) {
-    case LineAlignNone:
-        m_value.valueID = CSSValueNone;
-        break;
-    case LineAlignEdges:
-        m_value.valueID = CSSValueEdges;
-        break;
-    }
-}
-
-template<> inline CSSPrimitiveValue::operator LineAlign() const
-{
-    ASSERT(isValueID());
-    switch (m_value.valueID) {
-    case CSSValueNone:
-        return LineAlignNone;
-    case CSSValueEdges:
-        return LineAlignEdges;
-    default:
-        break;
-    }
-
-    ASSERT_NOT_REACHED();
-    return LineAlignNone;
-}
-
 template<> inline CSSPrimitiveValue::CSSPrimitiveValue(ESpeak e)
     : CSSValue(PrimitiveClass)
 {
@@ -4443,7 +4269,6 @@
 
 template<int supported> Length CSSPrimitiveValue::convertToLength(const CSSToLengthConversionData& conversionData)
 {
-    ASSERT(!hasVariableReference());
     if ((supported & FixedConversion) && isLength())
         return computeLength<Length>(conversionData);
     if ((supported & PercentConversion) && isPercentage())
@@ -4452,9 +4277,8 @@
         return Length(Auto);
     if ((supported & FixedConversion) && (supported & PercentConversion) && isCalculated())
         return Length(cssCalcValue()->toCalcValue(conversionData));
-    if ((supported & FixedConversion) && isViewportPercentageLength())
-        return viewportPercentageLength();
-    return Length(Undefined);
+    ASSERT_NOT_REACHED();
+    return Length(0, Fixed);
 }
 
 template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EBufferedRendering e)
@@ -4866,20 +4690,6 @@
     return MT_LUMINANCE;
 }
 
-template<> inline CSSPrimitiveValue::CSSPrimitiveValue(TouchAction t)
-    : CSSValue(PrimitiveClass)
-{
-    m_primitiveUnitType = CSS_VALUE_ID;
-    switch (t) {
-    case TouchActionNone:
-        m_value.valueID = CSSValueNone;
-        break;
-    case TouchActionAuto:
-        m_value.valueID = CSSValueAuto;
-        break;
-    }
-}
-
 template<> inline CSSPrimitiveValue::operator TouchAction() const
 {
     ASSERT(isValueID());
@@ -4888,6 +4698,10 @@
         return TouchActionNone;
     case CSSValueAuto:
         return TouchActionAuto;
+    case CSSValuePanX:
+        return TouchActionPanX;
+    case CSSValuePanY:
+        return TouchActionPanY;
     default:
         break;
     }
@@ -4972,6 +4786,9 @@
     case ContentBox:
         m_value.valueID = CSSValueContentBox;
         break;
+    case BoxMissing:
+        // The missing box should convert to a null primitive value.
+        ASSERT_NOT_REACHED();
     }
 }
 
@@ -4993,6 +4810,147 @@
     return ContentBox;
 }
 
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(ItemPosition itemPosition)
+    : CSSValue(PrimitiveClass)
+{
+    m_primitiveUnitType = CSS_VALUE_ID;
+    switch (itemPosition) {
+    case ItemPositionAuto:
+        m_value.valueID = CSSValueAuto;
+        break;
+    case ItemPositionStretch:
+        m_value.valueID = CSSValueStretch;
+        break;
+    case ItemPositionBaseline:
+        m_value.valueID = CSSValueBaseline;
+        break;
+    case ItemPositionCenter:
+        m_value.valueID = CSSValueCenter;
+        break;
+    case ItemPositionStart:
+        m_value.valueID = CSSValueStart;
+        break;
+    case ItemPositionEnd:
+        m_value.valueID = CSSValueEnd;
+        break;
+    case ItemPositionSelfStart:
+        m_value.valueID = CSSValueSelfStart;
+        break;
+    case ItemPositionSelfEnd:
+        m_value.valueID = CSSValueSelfEnd;
+        break;
+    case ItemPositionFlexStart:
+        m_value.valueID = CSSValueFlexStart;
+        break;
+    case ItemPositionFlexEnd:
+        m_value.valueID = CSSValueFlexEnd;
+        break;
+    case ItemPositionLeft:
+        m_value.valueID = CSSValueLeft;
+        break;
+    case ItemPositionRight:
+        m_value.valueID = CSSValueRight;
+        break;
+    }
+}
+
+template<> inline CSSPrimitiveValue::operator ItemPosition() const
+{
+    switch (m_value.valueID) {
+    case CSSValueAuto:
+        return ItemPositionAuto;
+    case CSSValueStretch:
+        return ItemPositionStretch;
+    case CSSValueBaseline:
+        return ItemPositionBaseline;
+    case CSSValueCenter:
+        return ItemPositionCenter;
+    case CSSValueStart:
+        return ItemPositionStart;
+    case CSSValueEnd:
+        return ItemPositionEnd;
+    case CSSValueSelfStart:
+        return ItemPositionSelfStart;
+    case CSSValueSelfEnd:
+        return ItemPositionSelfEnd;
+    case CSSValueFlexStart:
+        return ItemPositionFlexStart;
+    case CSSValueFlexEnd:
+        return ItemPositionFlexEnd;
+    case CSSValueLeft:
+        return ItemPositionLeft;
+    case CSSValueRight:
+        return ItemPositionRight;
+    default:
+        break;
+    }
+    ASSERT_NOT_REACHED();
+    return ItemPositionAuto;
+}
+
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(OverflowAlignment overflowAlignment)
+    : CSSValue(PrimitiveClass)
+{
+    m_primitiveUnitType = CSS_VALUE_ID;
+    switch (overflowAlignment) {
+    case OverflowAlignmentDefault:
+        m_value.valueID = CSSValueDefault;
+        break;
+    case OverflowAlignmentTrue:
+        m_value.valueID = CSSValueTrue;
+        break;
+    case OverflowAlignmentSafe:
+        m_value.valueID = CSSValueSafe;
+        break;
+    }
+}
+
+template<> inline CSSPrimitiveValue::operator OverflowAlignment() const
+{
+    switch (m_value.valueID) {
+    case CSSValueTrue:
+        return OverflowAlignmentTrue;
+    case CSSValueSafe:
+        return OverflowAlignmentSafe;
+    default:
+        break;
+    }
+    ASSERT_NOT_REACHED();
+    return OverflowAlignmentTrue;
+}
+
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(ScrollBehavior behavior)
+    : CSSValue(PrimitiveClass)
+{
+    m_primitiveUnitType = CSS_VALUE_ID;
+    switch (behavior) {
+    case ScrollBehaviorInstant:
+        m_value.valueID = CSSValueInstant;
+        break;
+    case ScrollBehaviorSmooth:
+        m_value.valueID = CSSValueSmooth;
+        break;
+    case ScrollBehaviorAuto:
+        // Behavior 'auto' is only allowed in ScrollOptions arguments passed to
+        // CSSOM scroll APIs.
+        ASSERT_NOT_REACHED();
+    }
+}
+
+template<> inline CSSPrimitiveValue::operator ScrollBehavior() const
+{
+    switch (getValueID()) {
+    case CSSValueInstant:
+        return ScrollBehaviorInstant;
+    case CSSValueSmooth:
+        return ScrollBehaviorSmooth;
+    default:
+        break;
+    }
+    ASSERT_NOT_REACHED();
+    return ScrollBehaviorInstant;
+}
+
 }
 
 #endif
diff --git a/Source/core/css/CSSProperties.in b/Source/core/css/CSSProperties.in
index 3b1657f..b3926cd 100644
--- a/Source/core/css/CSSProperties.in
+++ b/Source/core/css/CSSProperties.in
@@ -3,8 +3,6 @@
 // Note: Mandatory blank line to skip parameter parsing phase
 
 align-content
-align-items
-align-self type_name=EAlignItems
 background-attachment custom_all
 background-blend-mode custom_all
 background-clip custom_all
@@ -62,6 +60,7 @@
 font-size custom_all
 font-style custom_all
 font-variant custom_all
+font-variant-ligatures custom_all
 font-weight custom_all
 grid-auto-flow type_name=GridAutoFlow
 height type_name=Length, initial=initialSize, converter=convertLengthSizing
@@ -107,6 +106,7 @@
 position
 resize custom_value
 right type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
+scroll-behavior type_name=ScrollBehavior
 shape-image-threshold type_name=float
 shape-inside type_name=ShapeValue*, custom_value
 shape-margin type_name=Length, converter=convertLength
@@ -129,7 +129,7 @@
 text-shadow converter=convertShadow
 text-transform
 top type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
-touch-action type_name=TouchAction, initial=initialTouchAction
+touch-action type_name=TouchAction, custom_value
 touch-action-delay type_name=TouchActionDelay, initial=initialTouchActionDelay
 unicode-bidi
 vertical-align custom_value
@@ -187,17 +187,11 @@
 -webkit-column-rule-width type_name=unsigned short, converter=convertLineWidth<unsigned short>
 -webkit-column-span type_name=ColumnSpan
 -webkit-column-width type_name=float, custom_all
--webkit-flow-from type_name=AtomicString, name_for_methods=RegionThread, converter=convertString<CSSValueNone>
--webkit-flow-into type_name=AtomicString, name_for_methods=FlowThread, converter=convertString<CSSValueNone>
 -webkit-font-smoothing custom_all
--webkit-font-variant-ligatures custom_all
 -webkit-highlight type_name=AtomicString, converter=convertString<CSSValueNone>
 -webkit-hyphenate-character type_name=AtomicString, name_for_methods=HyphenationString, converter=convertString<CSSValueAuto>
--webkit-line-align type_name=LineAlign
 -webkit-line-break type_name=LineBreak
 -webkit-line-clamp type_name=LineClampValue
--webkit-line-grid type_name=AtomicString, converter=convertString<CSSValueNone>
--webkit-line-snap type_name=LineSnap
 -webkit-margin-after-collapse type_name=EMarginCollapse
 -webkit-margin-before-collapse type_name=EMarginCollapse
 -webkit-margin-bottom-collapse type_name=EMarginCollapse, name_for_methods=MarginAfterCollapse
@@ -225,10 +219,6 @@
 -webkit-perspective-origin-x type_name=Length, converter=convertLength
 -webkit-perspective-origin-y type_name=Length, converter=convertLength
 -webkit-print-color-adjust type_name=PrintColorAdjust
--webkit-region-break-after type_name=EPageBreak, initial=initialPageBreak
--webkit-region-break-before type_name=EPageBreak, initial=initialPageBreak
--webkit-region-break-inside type_name=EPageBreak, initial=initialPageBreak
--webkit-region-fragment type_name=RegionFragment
 -webkit-rtl-ordering type_name=Order, getter=rtlOrdering, setter=setRTLOrdering, initial=initialRTLOrdering
 -webkit-ruby-position type_name=RubyPosition
 -webkit-text-combine type_name=TextCombine
diff --git a/Source/core/css/CSSProperty.cpp b/Source/core/css/CSSProperty.cpp
index 59e3d9e..337d26f 100644
--- a/Source/core/css/CSSProperty.cpp
+++ b/Source/core/css/CSSProperty.cpp
@@ -317,7 +317,6 @@
     case CSSPropertyTextShadow:
     case CSSPropertyTextTransform:
     case CSSPropertyTouchActionDelay:
-    case CSSPropertyVariable:
     case CSSPropertyVisibility:
     case CSSPropertyWebkitAspectRatio:
     case CSSPropertyWebkitBorderHorizontalSpacing:
@@ -326,15 +325,12 @@
     case CSSPropertyWebkitFontFeatureSettings:
     case CSSPropertyFontKerning:
     case CSSPropertyWebkitFontSmoothing:
-    case CSSPropertyWebkitFontVariantLigatures:
+    case CSSPropertyFontVariantLigatures:
     case CSSPropertyWebkitLocale:
     case CSSPropertyWebkitHighlight:
     case CSSPropertyWebkitHyphenateCharacter:
-    case CSSPropertyWebkitLineAlign:
     case CSSPropertyWebkitLineBoxContain:
     case CSSPropertyWebkitLineBreak:
-    case CSSPropertyWebkitLineGrid:
-    case CSSPropertyWebkitLineSnap:
     case CSSPropertyWebkitPrintColorAdjust:
     case CSSPropertyWebkitRtlOrdering:
     case CSSPropertyWebkitRubyPosition:
@@ -439,6 +435,7 @@
     case CSSPropertyFontStretch:
     case CSSPropertyHeight:
     case CSSPropertyIsolation:
+    case CSSPropertyJustifySelf:
     case CSSPropertyLeft:
     case CSSPropertyLightingColor:
     case CSSPropertyMargin:
@@ -478,6 +475,7 @@
     case CSSPropertyPaintOrder:
     case CSSPropertyPosition:
     case CSSPropertyRight:
+    case CSSPropertyScrollBehavior:
     case CSSPropertySize:
     case CSSPropertySrc:
     case CSSPropertyStopColor:
@@ -591,12 +589,12 @@
     case CSSPropertyGridColumn:
     case CSSPropertyGridColumnEnd:
     case CSSPropertyGridColumnStart:
-    case CSSPropertyGridDefinitionColumns:
-    case CSSPropertyGridDefinitionRows:
+    case CSSPropertyGridTemplateColumns:
+    case CSSPropertyGridTemplateRows:
     case CSSPropertyGridRow:
     case CSSPropertyGridRowEnd:
     case CSSPropertyGridRowStart:
-    case CSSPropertyGridTemplate:
+    case CSSPropertyGridTemplateAreas:
     case CSSPropertyJustifyContent:
     case CSSPropertyWebkitLineClamp:
     case CSSPropertyWebkitLogicalHeight:
@@ -658,12 +656,6 @@
     case CSSPropertyWebkitTransitionProperty:
     case CSSPropertyWebkitTransitionTimingFunction:
     case CSSPropertyWebkitUserDrag:
-    case CSSPropertyWebkitFlowInto:
-    case CSSPropertyWebkitFlowFrom:
-    case CSSPropertyWebkitRegionBreakAfter:
-    case CSSPropertyWebkitRegionBreakBefore:
-    case CSSPropertyWebkitRegionBreakInside:
-    case CSSPropertyWebkitRegionFragment:
     case CSSPropertyWebkitWrapFlow:
     case CSSPropertyShapeMargin:
     case CSSPropertyShapeImageThreshold:
diff --git a/Source/core/css/CSSProperty.h b/Source/core/css/CSSProperty.h
index a0fb377..0f391d8 100644
--- a/Source/core/css/CSSProperty.h
+++ b/Source/core/css/CSSProperty.h
@@ -58,7 +58,6 @@
         : m_metadata(propertyID, isSetFromShorthand, indexInShorthandsVector, important, implicit, isInheritedProperty(propertyID))
         , m_value(value)
     {
-    ASSERT((propertyID == CSSPropertyVariable) == (m_value && m_value->isVariableValue()));
     }
 
     // FIXME: Remove this.
@@ -66,7 +65,6 @@
         : m_metadata(metadata)
         , m_value(value)
     {
-    ASSERT((metadata.m_propertyID == CSSPropertyVariable) == (m_value && m_value->isVariableValue()));
     }
 
     CSSPropertyID id() const { return static_cast<CSSPropertyID>(m_metadata.m_propertyID); }
@@ -190,7 +188,7 @@
 } // namespace WebCore
 
 namespace WTF {
-template <> struct VectorTraits<WebCore::CSSProperty> : VectorTraitsBase<false, WebCore::CSSProperty> {
+template <> struct VectorTraits<WebCore::CSSProperty> : VectorTraitsBase<WebCore::CSSProperty> {
     static const bool canInitializeWithMemset = true;
     static const bool canMoveWithMemcpy = true;
 };
diff --git a/Source/core/css/CSSPropertyNames.in b/Source/core/css/CSSPropertyNames.in
index 880cb61..a172b0a 100644
--- a/Source/core/css/CSSPropertyNames.in
+++ b/Source/core/css/CSSPropertyNames.in
@@ -49,11 +49,11 @@
 font-size
 font-style
 font-variant
+font-variant-ligatures
 font-weight
 text-rendering
 -webkit-font-feature-settings
 -webkit-font-smoothing
--webkit-font-variant-ligatures
 -webkit-locale
 -webkit-text-orientation
 -epub-text-orientation alias_for=-webkit-text-orientation
@@ -136,6 +136,7 @@
 height
 image-rendering
 isolation
+justify-self
 left
 letter-spacing
 list-style
@@ -183,6 +184,7 @@
 quotes
 resize
 right
+scroll-behavior
 size
 src
 speak
@@ -321,20 +323,17 @@
 grid-column
 grid-column-end
 grid-column-start
-grid-definition-columns
-grid-definition-rows
+grid-template-columns
+grid-template-rows
 grid-row
 grid-row-end
 grid-row-start
-grid-template
+grid-template-areas
 -webkit-highlight
 -webkit-hyphenate-character
 -webkit-line-box-contain
--webkit-line-align
 -webkit-line-break
 -webkit-line-clamp
--webkit-line-grid
--webkit-line-snap
 -webkit-logical-width
 -webkit-logical-height
 -webkit-margin-after-collapse
@@ -405,12 +404,6 @@
 -webkit-user-drag
 -webkit-user-modify
 -webkit-user-select
--webkit-flow-into
--webkit-flow-from
--webkit-region-fragment
--webkit-region-break-after
--webkit-region-break-before
--webkit-region-break-inside
 -webkit-shape-inside alias_for=shape-inside
 -webkit-shape-outside alias_for=shape-outside
 -webkit-shape-margin alias_for=shape-margin
diff --git a/Source/core/css/CSSPropertySourceData.h b/Source/core/css/CSSPropertySourceData.h
index 7b964d4..b5d51e2 100644
--- a/Source/core/css/CSSPropertySourceData.h
+++ b/Source/core/css/CSSPropertySourceData.h
@@ -94,7 +94,6 @@
         FONT_FACE_RULE,
         PAGE_RULE,
         KEYFRAMES_RULE,
-        REGION_RULE,
         VIEWPORT_RULE,
         SUPPORTS_RULE,
         FILTER_RULE
diff --git a/Source/core/css/CSSReflectValue.cpp b/Source/core/css/CSSReflectValue.cpp
index b13006c..cbb2cdd 100644
--- a/Source/core/css/CSSReflectValue.cpp
+++ b/Source/core/css/CSSReflectValue.cpp
@@ -39,19 +39,6 @@
     return m_direction->cssText() + ' ' + m_offset->cssText();
 }
 
-String CSSReflectValue::customSerializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-{
-    if (m_mask)
-        return m_direction->customSerializeResolvingVariables(variables) + ' ' + m_offset->customSerializeResolvingVariables(variables) + ' ' + m_mask->serializeResolvingVariables(variables);
-    return m_direction->customSerializeResolvingVariables(variables) + ' ' + m_offset->customSerializeResolvingVariables(variables);
-}
-
-void CSSReflectValue::addSubresourceStyleURLs(ListHashSet<KURL>& urls, const StyleSheetContents* styleSheet) const
-{
-    if (m_mask)
-        m_mask->addSubresourceStyleURLs(urls, styleSheet);
-}
-
 bool CSSReflectValue::equals(const CSSReflectValue& other) const
 {
     return m_direction == other.m_direction
@@ -59,4 +46,11 @@
         && compareCSSValuePtr(m_mask, other.m_mask);
 }
 
+void CSSReflectValue::traceAfterDispatch(Visitor* visitor)
+{
+    visitor->trace(m_direction);
+    visitor->trace(m_offset);
+    CSSValue::traceAfterDispatch(visitor);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSReflectValue.h b/Source/core/css/CSSReflectValue.h
index 0fd92a0..a810242 100644
--- a/Source/core/css/CSSReflectValue.h
+++ b/Source/core/css/CSSReflectValue.h
@@ -36,10 +36,10 @@
 
 class CSSReflectValue : public CSSValue {
 public:
-    static PassRefPtr<CSSReflectValue> create(PassRefPtr<CSSPrimitiveValue> direction,
-        PassRefPtr<CSSPrimitiveValue> offset, PassRefPtr<CSSValue> mask)
+    static PassRefPtrWillBeRawPtr<CSSReflectValue> create(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> direction,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> offset, PassRefPtr<CSSValue> mask)
     {
-        return adoptRef(new CSSReflectValue(direction, offset, mask));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSReflectValue(direction, offset, mask));
     }
 
     CSSPrimitiveValue* direction() const { return m_direction.get(); }
@@ -47,14 +47,13 @@
     CSSValue* mask() const { return m_mask.get(); }
 
     String customCSSText() const;
-    String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
-
-    void addSubresourceStyleURLs(ListHashSet<KURL>&, const StyleSheetContents*) const;
 
     bool equals(const CSSReflectValue&) const;
 
+    void traceAfterDispatch(Visitor*);
+
 private:
-    CSSReflectValue(PassRefPtr<CSSPrimitiveValue> direction, PassRefPtr<CSSPrimitiveValue> offset, PassRefPtr<CSSValue> mask)
+    CSSReflectValue(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> direction, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> offset, PassRefPtr<CSSValue> mask)
         : CSSValue(ReflectClass)
         , m_direction(direction)
         , m_offset(offset)
@@ -62,8 +61,8 @@
     {
     }
 
-    RefPtr<CSSPrimitiveValue> m_direction;
-    RefPtr<CSSPrimitiveValue> m_offset;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_direction;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_offset;
     RefPtr<CSSValue> m_mask;
 };
 
diff --git a/Source/core/css/CSSRegionRule.cpp b/Source/core/css/CSSRegionRule.cpp
deleted file mode 100644
index 94e9d0b..0000000
--- a/Source/core/css/CSSRegionRule.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2012 Apple Inc. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-#include "config.h"
-
-#include "core/css/CSSRegionRule.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/css/StyleRule.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-CSSRegionRule::CSSRegionRule(StyleRuleRegion* regionRule, CSSStyleSheet* parent)
-    : CSSGroupingRule(regionRule, parent)
-{
-    ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
-}
-
-String CSSRegionRule::cssText() const
-{
-    StringBuilder result;
-    result.appendLiteral("@-webkit-region ");
-
-    // First add the selectors.
-    result.append(toStyleRuleRegion(m_groupRule.get())->selectorList().selectorsText());
-
-    // Then add the rules.
-    result.appendLiteral(" { \n");
-    appendCSSTextForItems(result);
-    result.append('}');
-    return result.toString();
-}
-
-} // namespace WebCore
diff --git a/Source/core/css/CSSRegionRule.h b/Source/core/css/CSSRegionRule.h
deleted file mode 100644
index e095da4..0000000
--- a/Source/core/css/CSSRegionRule.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2012 Apple Inc. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef CSSRegionRule_h
-#define CSSRegionRule_h
-
-#include "core/css/CSSGroupingRule.h"
-
-namespace WebCore {
-
-class StyleRuleRegion;
-
-class CSSRegionRule : public CSSGroupingRule {
-public:
-    static PassRefPtr<CSSRegionRule> create(StyleRuleRegion* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSRegionRule(rule, sheet)); }
-
-    virtual CSSRule::Type type() const OVERRIDE { return WEBKIT_REGION_RULE; }
-    virtual String cssText() const OVERRIDE;
-
-private:
-    CSSRegionRule(StyleRuleRegion*, CSSStyleSheet* parent);
-};
-
-DEFINE_CSS_RULE_TYPE_CASTS(CSSRegionRule, WEBKIT_REGION_RULE);
-
-}
-
-#endif // CSSRegionRule_h
diff --git a/Source/core/css/CSSRule.cpp b/Source/core/css/CSSRule.cpp
index 7673640..8819570 100644
--- a/Source/core/css/CSSRule.cpp
+++ b/Source/core/css/CSSRule.cpp
@@ -37,8 +37,6 @@
 
 COMPILE_ASSERT(sizeof(CSSRule) == sizeof(SameSizeAsCSSRule), CSSRule_should_stay_small);
 
-COMPILE_ASSERT(StyleRuleBase::Region == static_cast<StyleRuleBase::Type>(CSSRule::WEBKIT_REGION_RULE), enums_should_match);
-
 COMPILE_ASSERT(StyleRuleBase::Viewport == static_cast<StyleRuleBase::Type>(CSSRule::VIEWPORT_RULE), enums_should_match);
 
 void CSSRule::setCSSText(const String&)
diff --git a/Source/core/css/CSSRule.h b/Source/core/css/CSSRule.h
index 9cd6608..a66dc50 100644
--- a/Source/core/css/CSSRule.h
+++ b/Source/core/css/CSSRule.h
@@ -53,7 +53,6 @@
         WEBKIT_KEYFRAME_RULE = KEYFRAME_RULE,
         SUPPORTS_RULE = 12,
         VIEWPORT_RULE = 15,
-        WEBKIT_REGION_RULE = 16,
         WEBKIT_FILTER_RULE = 17
     };
 
diff --git a/Source/core/css/CSSRule.idl b/Source/core/css/CSSRule.idl
index 9dadad9..494e16a 100644
--- a/Source/core/css/CSSRule.idl
+++ b/Source/core/css/CSSRule.idl
@@ -38,7 +38,6 @@
     const unsigned short WEBKIT_KEYFRAME_RULE = 8;
     const unsigned short SUPPORTS_RULE = 12;
     [RuntimeEnabled=CSSViewport] const unsigned short VIEWPORT_RULE = 15;
-    [RuntimeEnabled=CSSRegions] const unsigned short WEBKIT_REGION_RULE = 16;
     const unsigned short WEBKIT_FILTER_RULE = 17;
 
     readonly attribute unsigned short   type;
diff --git a/Source/core/css/CSSRuleList.h b/Source/core/css/CSSRuleList.h
index f65b366..ca26dc3 100644
--- a/Source/core/css/CSSRuleList.h
+++ b/Source/core/css/CSSRuleList.h
@@ -48,23 +48,23 @@
     CSSRuleList();
 };
 
-class StaticCSSRuleList : public CSSRuleList {
+class StaticCSSRuleList FINAL : public CSSRuleList {
 public:
     static PassRefPtr<StaticCSSRuleList> create() { return adoptRef(new StaticCSSRuleList()); }
 
-    virtual void ref() { ++m_refCount; }
-    virtual void deref();
+    virtual void ref() OVERRIDE { ++m_refCount; }
+    virtual void deref() OVERRIDE;
 
     Vector<RefPtr<CSSRule> >& rules() { return m_rules; }
 
-    virtual CSSStyleSheet* styleSheet() const { return 0; }
+    virtual CSSStyleSheet* styleSheet() const OVERRIDE { return 0; }
 
 private:
     StaticCSSRuleList();
-    ~StaticCSSRuleList();
+    virtual ~StaticCSSRuleList();
 
-    virtual unsigned length() const { return m_rules.size(); }
-    virtual CSSRule* item(unsigned index) const { return index < m_rules.size() ? m_rules[index].get() : 0; }
+    virtual unsigned length() const OVERRIDE { return m_rules.size(); }
+    virtual CSSRule* item(unsigned index) const OVERRIDE { return index < m_rules.size() ? m_rules[index].get() : 0; }
 
     Vector<RefPtr<CSSRule> > m_rules;
     unsigned m_refCount;
@@ -72,17 +72,17 @@
 
 // The rule owns the live list.
 template <class Rule>
-class LiveCSSRuleList : public CSSRuleList {
+class LiveCSSRuleList FINAL : public CSSRuleList {
 public:
     LiveCSSRuleList(Rule* rule) : m_rule(rule) { }
 
-    virtual void ref() { m_rule->ref(); }
-    virtual void deref() { m_rule->deref(); }
+    virtual void ref() OVERRIDE { m_rule->ref(); }
+    virtual void deref() OVERRIDE { m_rule->deref(); }
 
 private:
-    virtual unsigned length() const { return m_rule->length(); }
-    virtual CSSRule* item(unsigned index) const  { return m_rule->item(index); }
-    virtual CSSStyleSheet* styleSheet() const { return m_rule->parentStyleSheet(); }
+    virtual unsigned length() const OVERRIDE { return m_rule->length(); }
+    virtual CSSRule* item(unsigned index) const OVERRIDE { return m_rule->item(index); }
+    virtual CSSStyleSheet* styleSheet() const OVERRIDE { return m_rule->parentStyleSheet(); }
 
     Rule* m_rule;
 };
diff --git a/Source/core/css/CSSSVGDocumentValue.cpp b/Source/core/css/CSSSVGDocumentValue.cpp
index d0912d4..81bddc8 100644
--- a/Source/core/css/CSSSVGDocumentValue.cpp
+++ b/Source/core/css/CSSSVGDocumentValue.cpp
@@ -27,7 +27,7 @@
 #include "core/css/CSSSVGDocumentValue.h"
 
 #include "FetchInitiatorTypeNames.h"
-#include "core/css/CSSParser.h"
+#include "core/css/CSSMarkup.h"
 #include "core/dom/Document.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ResourceFetcher.h"
diff --git a/Source/core/css/CSSSVGDocumentValue.h b/Source/core/css/CSSSVGDocumentValue.h
index d2decc4..386d4df 100644
--- a/Source/core/css/CSSSVGDocumentValue.h
+++ b/Source/core/css/CSSSVGDocumentValue.h
@@ -35,7 +35,10 @@
 
 class CSSSVGDocumentValue : public CSSValue {
 public:
-    static PassRefPtr<CSSSVGDocumentValue> create(const String& url) { return adoptRef(new CSSSVGDocumentValue(url)); }
+    static PassRefPtrWillBeRawPtr<CSSSVGDocumentValue> create(const String& url)
+    {
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSSVGDocumentValue(url));
+    }
     ~CSSSVGDocumentValue();
 
     DocumentResource* cachedSVGDocument() const { return m_document.get(); }
@@ -46,6 +49,8 @@
     bool loadRequested() const { return m_loadRequested; }
     bool equals(const CSSSVGDocumentValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     CSSSVGDocumentValue(const String& url);
 
diff --git a/Source/core/css/CSSSegmentedFontFace.cpp b/Source/core/css/CSSSegmentedFontFace.cpp
index eaa1223..f6d2f8a 100644
--- a/Source/core/css/CSSSegmentedFontFace.cpp
+++ b/Source/core/css/CSSSegmentedFontFace.cpp
@@ -28,6 +28,7 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSFontFace.h"
+#include "core/css/CSSFontSelector.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/fonts/SegmentedFontData.h"
@@ -38,15 +39,15 @@
 CSSSegmentedFontFace::CSSSegmentedFontFace(CSSFontSelector* fontSelector, FontTraitsMask traitsMask)
     : m_fontSelector(fontSelector)
     , m_traitsMask(traitsMask)
+    , m_firstNonCssConnectedFace(m_fontFaces.end())
 {
 }
 
 CSSSegmentedFontFace::~CSSSegmentedFontFace()
 {
     pruneTable();
-    unsigned size = m_fontFaces.size();
-    for (unsigned i = 0; i < size; i++)
-        m_fontFaces[i]->clearSegmentedFontFace();
+    for (FontFaceList::iterator it = m_fontFaces.begin(); it != m_fontFaces.end(); ++it)
+        (*it)->cssFontFace()->clearSegmentedFontFace();
 }
 
 void CSSSegmentedFontFace::pruneTable()
@@ -61,9 +62,8 @@
 bool CSSSegmentedFontFace::isValid() const
 {
     // Valid if at least one font face is valid.
-    unsigned size = m_fontFaces.size();
-    for (unsigned i = 0; i < size; i++) {
-        if (m_fontFaces[i]->isValid())
+    for (FontFaceList::const_iterator it = m_fontFaces.begin(); it != m_fontFaces.end(); ++it) {
+        if ((*it)->cssFontFace()->isValid())
             return true;
     }
     return false;
@@ -71,6 +71,8 @@
 
 void CSSSegmentedFontFace::fontLoaded(CSSFontFace*)
 {
+    m_fontSelector->fontLoaded();
+
     pruneTable();
 
     if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && !isLoading()) {
@@ -85,21 +87,34 @@
     }
 }
 
-void CSSSegmentedFontFace::appendFontFace(PassRefPtr<CSSFontFace> fontFace)
+void CSSSegmentedFontFace::addFontFace(PassRefPtr<FontFace> prpFontFace, bool cssConnected)
 {
+    RefPtr<FontFace> fontFace = prpFontFace;
     pruneTable();
-    fontFace->setSegmentedFontFace(this);
-    m_fontFaces.append(fontFace);
+    fontFace->cssFontFace()->setSegmentedFontFace(this);
+    if (cssConnected) {
+        m_fontFaces.insertBefore(m_firstNonCssConnectedFace, fontFace);
+    } else {
+        // This is the only place in Blink that is using addReturnIterator.
+        FontFaceList::iterator iterator = m_fontFaces.addReturnIterator(fontFace);
+        if (m_firstNonCssConnectedFace == m_fontFaces.end())
+            m_firstNonCssConnectedFace = iterator;
+    }
 }
 
-void CSSSegmentedFontFace::removeFontFace(PassRefPtr<CSSFontFace> fontFace)
+void CSSSegmentedFontFace::removeFontFace(PassRefPtr<FontFace> prpFontFace)
 {
-    size_t index = m_fontFaces.find(fontFace);
-    if (index != kNotFound) {
-        pruneTable();
-        m_fontFaces.remove(index);
-        fontFace->clearSegmentedFontFace();
-    }
+    RefPtr<FontFace> fontFace = prpFontFace;
+    FontFaceList::iterator it = m_fontFaces.find(fontFace);
+    if (it == m_fontFaces.end())
+        return;
+
+    if (it == m_firstNonCssConnectedFace)
+        ++m_firstNonCssConnectedFace;
+    m_fontFaces.remove(it);
+
+    pruneTable();
+    fontFace->cssFontFace()->clearSegmentedFontFace();
 }
 
 static void appendFontData(SegmentedFontData* newFontData, PassRefPtr<SimpleFontData> prpFaceFontData, const CSSFontFace::UnicodeRangeSet& ranges)
@@ -124,7 +139,7 @@
     AtomicString emptyFontFamily = "";
     FontCacheKey key = fontDescription.cacheKey(emptyFontFamily, desiredTraitsMask);
 
-    RefPtr<SegmentedFontData>& fontData = m_fontDataTable.add(key.hash(), 0).iterator->value;
+    RefPtr<SegmentedFontData>& fontData = m_fontDataTable.add(key.hash(), 0).storedValue->value;
     if (fontData && fontData->numRanges())
         return fontData; // No release, we have a reference to an object in the cache which should retain the ref count it has.
 
@@ -136,10 +151,10 @@
     requestedFontDescription.setSyntheticBold(!(m_traitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)) && (desiredTraitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)));
     requestedFontDescription.setSyntheticItalic(!(m_traitsMask & FontStyleItalicMask) && (desiredTraitsMask & FontStyleItalicMask));
 
-    for (int i = m_fontFaces.size() - 1; i >= 0; --i) {
-        if (!m_fontFaces[i]->isValid())
+    for (FontFaceList::reverse_iterator it = m_fontFaces.rbegin(); it != m_fontFaces.rend(); ++it) {
+        if (!(*it)->cssFontFace()->isValid())
             continue;
-        if (RefPtr<SimpleFontData> faceFontData = m_fontFaces[i]->getFontData(requestedFontDescription)) {
+        if (RefPtr<SimpleFontData> faceFontData = (*it)->cssFontFace()->getFontData(requestedFontDescription)) {
             ASSERT(!faceFontData->isSegmented());
 #if ENABLE(SVG_FONTS)
             // For SVG Fonts that specify that they only support the "normal" variant, we will assume they are incapable
@@ -147,7 +162,7 @@
             if (faceFontData->isSVGFont() && (desiredTraitsMask & FontVariantSmallCapsMask) && !(m_traitsMask & FontVariantSmallCapsMask))
                 continue;
 #endif
-            appendFontData(fontData.get(), faceFontData.release(), m_fontFaces[i]->ranges());
+            appendFontData(fontData.get(), faceFontData.release(), (*it)->cssFontFace()->ranges());
         }
     }
     if (fontData->numRanges())
@@ -158,9 +173,8 @@
 
 bool CSSSegmentedFontFace::isLoading() const
 {
-    unsigned size = m_fontFaces.size();
-    for (unsigned i = 0; i < size; i++) {
-        if (m_fontFaces[i]->loadStatus() == FontFace::Loading)
+    for (FontFaceList::const_iterator it = m_fontFaces.begin(); it != m_fontFaces.end(); ++it) {
+        if ((*it)->loadStatus() == FontFace::Loading)
             return true;
     }
     return false;
@@ -168,9 +182,8 @@
 
 bool CSSSegmentedFontFace::isLoaded() const
 {
-    unsigned size = m_fontFaces.size();
-    for (unsigned i = 0; i < size; i++) {
-        if (m_fontFaces[i]->loadStatus() != FontFace::Loaded)
+    for (FontFaceList::const_iterator it = m_fontFaces.begin(); it != m_fontFaces.end(); ++it) {
+        if ((*it)->loadStatus() != FontFace::Loaded)
             return false;
     }
     return true;
@@ -178,16 +191,14 @@
 
 void CSSSegmentedFontFace::willUseFontData(const FontDescription& fontDescription)
 {
-    unsigned size = m_fontFaces.size();
-    for (unsigned i = 0; i < size; i++)
-        m_fontFaces[i]->willUseFontData(fontDescription);
+    for (FontFaceList::iterator it = m_fontFaces.begin(); it != m_fontFaces.end(); ++it)
+        (*it)->cssFontFace()->willUseFontData(fontDescription);
 }
 
 bool CSSSegmentedFontFace::checkFont(const String& text) const
 {
-    unsigned size = m_fontFaces.size();
-    for (unsigned i = 0; i < size; i++) {
-        if (m_fontFaces[i]->loadStatus() != FontFace::Loaded && m_fontFaces[i]->ranges().intersectsWith(text))
+    for (FontFaceList::const_iterator it = m_fontFaces.begin(); it != m_fontFaces.end(); ++it) {
+        if ((*it)->loadStatus() != FontFace::Loaded && (*it)->cssFontFace()->ranges().intersectsWith(text))
             return false;
     }
     return true;
@@ -195,13 +206,9 @@
 
 void CSSSegmentedFontFace::loadFont(const FontDescription& fontDescription, const String& text, PassRefPtr<LoadFontCallback> callback)
 {
-    unsigned size = m_fontFaces.size();
-    for (unsigned i = 0; i < size; i++) {
-        if (m_fontFaces[i]->loadStatus() == FontFace::Unloaded && m_fontFaces[i]->ranges().intersectsWith(text)) {
-            RefPtr<SimpleFontData> fontData = m_fontFaces[i]->getFontData(fontDescription);
-            if (fontData->customFontData())
-                fontData->customFontData()->beginLoadIfNeeded();
-        }
+    for (FontFaceList::iterator it = m_fontFaces.begin(); it != m_fontFaces.end(); ++it) {
+        if ((*it)->loadStatus() == FontFace::Unloaded && (*it)->cssFontFace()->ranges().intersectsWith(text))
+            (*it)->cssFontFace()->load(fontDescription);
     }
 
     if (callback) {
@@ -214,15 +221,4 @@
     }
 }
 
-Vector<RefPtr<FontFace> > CSSSegmentedFontFace::fontFaces(const String& text) const
-{
-    Vector<RefPtr<FontFace> > fontFaces;
-    unsigned size = m_fontFaces.size();
-    for (unsigned i = 0; i < size; i++) {
-        if (m_fontFaces[i]->ranges().intersectsWith(text))
-            fontFaces.append(m_fontFaces[i]->fontFace());
-    }
-    return fontFaces;
-}
-
 }
diff --git a/Source/core/css/CSSSegmentedFontFace.h b/Source/core/css/CSSSegmentedFontFace.h
index 26c5bb1..52b443e 100644
--- a/Source/core/css/CSSSegmentedFontFace.h
+++ b/Source/core/css/CSSSegmentedFontFace.h
@@ -28,6 +28,7 @@
 
 #include "platform/fonts/FontTraitsMask.h"
 #include "wtf/HashMap.h"
+#include "wtf/ListHashSet.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
@@ -52,8 +53,8 @@
 
     void fontLoaded(CSSFontFace*);
 
-    void appendFontFace(PassRefPtr<CSSFontFace>);
-    void removeFontFace(PassRefPtr<CSSFontFace>);
+    void addFontFace(PassRefPtr<FontFace>, bool cssConnected);
+    void removeFontFace(PassRefPtr<FontFace>);
     bool isEmpty() const { return m_fontFaces.isEmpty(); }
 
     PassRefPtr<FontData> getFontData(const FontDescription&);
@@ -67,7 +68,6 @@
 
     bool checkFont(const String&) const;
     void loadFont(const FontDescription&, const String&, PassRefPtr<LoadFontCallback>);
-    Vector<RefPtr<FontFace> > fontFaces(const String& text) const;
     void willUseFontData(const FontDescription&);
 
 private:
@@ -78,10 +78,14 @@
     bool isLoading() const;
     bool isLoaded() const;
 
+    typedef ListHashSet<RefPtr<FontFace> > FontFaceList;
+
     CSSFontSelector* m_fontSelector;
     FontTraitsMask m_traitsMask;
     HashMap<unsigned, RefPtr<SegmentedFontData> > m_fontDataTable;
-    Vector<RefPtr<CSSFontFace>, 1> m_fontFaces;
+    // All non-CSS-connected FontFaces are stored after the CSS-connected ones.
+    FontFaceList m_fontFaces;
+    FontFaceList::iterator m_firstNonCssConnectedFace;
     Vector<RefPtr<LoadFontCallback> > m_callbacks;
 };
 
diff --git a/Source/core/css/CSSSelector.cpp b/Source/core/css/CSSSelector.cpp
index b744726..845ba54 100644
--- a/Source/core/css/CSSSelector.cpp
+++ b/Source/core/css/CSSSelector.cpp
@@ -36,6 +36,10 @@
 #include "wtf/text/StringBuilder.h"
 #include "wtf/text/StringHash.h"
 
+#ifndef NDEBUG
+#include <stdio.h>
+#endif
+
 namespace WebCore {
 
 using namespace HTMLNames;
@@ -52,8 +56,10 @@
     ASSERT(m_match != Tag);
     if (m_hasRareData)
         return;
-    // Move the value to the rare data stucture.
-    m_data.m_rareData = RareData::create(adoptRef(m_data.m_value)).leakRef();
+    AtomicString value(m_data.m_value);
+    if (m_data.m_value)
+        m_data.m_value->deref();
+    m_data.m_rareData = RareData::create(value).leakRef();
     m_hasRareData = true;
 }
 
@@ -94,7 +100,7 @@
     case Id:
         return 0x10000;
     case PseudoClass:
-        if (pseudoType() == PseudoHost)
+        if (pseudoType() == PseudoHost || pseudoType() == PseudoAncestor)
             return 0;
         // fall through.
     case Exact:
@@ -183,12 +189,6 @@
         return SCROLLBAR_TRACK_PIECE;
     case PseudoResizer:
         return RESIZER;
-    case PseudoFullScreen:
-        return FULL_SCREEN;
-    case PseudoFullScreenDocument:
-        return FULL_SCREEN_DOCUMENT;
-    case PseudoFullScreenAncestor:
-        return FULL_SCREEN_ANCESTOR;
     case PseudoUnknown:
     case PseudoEmpty:
     case PseudoFirstChild:
@@ -250,11 +250,14 @@
     case PseudoCue:
     case PseudoFutureCue:
     case PseudoPastCue:
-    case PseudoSeamlessDocument:
     case PseudoDistributed:
     case PseudoUnresolved:
     case PseudoContent:
     case PseudoHost:
+    case PseudoAncestor:
+    case PseudoFullScreen:
+    case PseudoFullScreenDocument:
+    case PseudoFullScreenAncestor:
         return NOPSEUDO;
     case PseudoNotParsed:
         ASSERT_NOT_REACHED();
@@ -338,7 +341,6 @@
     DEFINE_STATIC_LOCAL(AtomicString, cueWithoutParen, ("cue", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, futureCue, ("future", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, pastCue, ("past", AtomicString::ConstructFromLiteral));
-    DEFINE_STATIC_LOCAL(AtomicString, seamlessDocument, ("-webkit-seamless-document", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, distributed, ("-webkit-distributed(", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, inRange, ("in-range", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, outOfRange, ("out-of-range", AtomicString::ConstructFromLiteral));
@@ -347,6 +349,8 @@
     DEFINE_STATIC_LOCAL(AtomicString, content, ("content", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, host, ("host", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, hostWithParams, ("host(", AtomicString::ConstructFromLiteral));
+    DEFINE_STATIC_LOCAL(AtomicString, ancestor, ("ancestor", AtomicString::ConstructFromLiteral));
+    DEFINE_STATIC_LOCAL(AtomicString, ancestorWithParams, ("ancestor(", AtomicString::ConstructFromLiteral));
 
     static HashMap<StringImpl*, CSSSelector::PseudoType>* nameToPseudoType = 0;
     if (!nameToPseudoType) {
@@ -422,21 +426,51 @@
         nameToPseudoType->set(cueWithoutParen.impl(), CSSSelector::PseudoWebKitCustomElement);
         nameToPseudoType->set(futureCue.impl(), CSSSelector::PseudoFutureCue);
         nameToPseudoType->set(pastCue.impl(), CSSSelector::PseudoPastCue);
-        nameToPseudoType->set(seamlessDocument.impl(), CSSSelector::PseudoSeamlessDocument);
         nameToPseudoType->set(distributed.impl(), CSSSelector::PseudoDistributed);
         nameToPseudoType->set(inRange.impl(), CSSSelector::PseudoInRange);
         nameToPseudoType->set(outOfRange.impl(), CSSSelector::PseudoOutOfRange);
+        nameToPseudoType->set(unresolved.impl(), CSSSelector::PseudoUnresolved);
         if (RuntimeEnabledFeatures::shadowDOMEnabled()) {
             nameToPseudoType->set(host.impl(), CSSSelector::PseudoHost);
             nameToPseudoType->set(hostWithParams.impl(), CSSSelector::PseudoHost);
+            nameToPseudoType->set(ancestor.impl(), CSSSelector::PseudoAncestor);
+            nameToPseudoType->set(ancestorWithParams.impl(), CSSSelector::PseudoAncestor);
             nameToPseudoType->set(content.impl(), CSSSelector::PseudoContent);
         }
-        if (RuntimeEnabledFeatures::customElementsEnabled())
-            nameToPseudoType->set(unresolved.impl(), CSSSelector::PseudoUnresolved);
     }
     return nameToPseudoType;
 }
 
+#ifndef NDEBUG
+void CSSSelector::show(int indent) const
+{
+    printf("%*sselectorText(): %s\n", indent, "", selectorText().ascii().data());
+    printf("%*sm_match: %d\n", indent, "", m_match);
+    printf("%*sisCustomPseudoElement(): %d\n", indent, "", isCustomPseudoElement());
+    if (m_match != Tag)
+        printf("%*svalue(): %s\n", indent, "", value().ascii().data());
+    printf("%*spseudoType(): %d\n", indent, "", pseudoType());
+    if (m_match == Tag)
+        printf("%*stagQName().localName: %s\n", indent, "", tagQName().localName().ascii().data());
+    printf("%*sisAttributeSelector(): %d\n", indent, "", isAttributeSelector());
+    if (isAttributeSelector())
+        printf("%*sattribute(): %s\n", indent, "", attribute().localName().ascii().data());
+    printf("%*sargument(): %s\n", indent, "", argument().ascii().data());
+    printf("%*sspecificity(): %u\n", indent, "", specificity());
+    if (tagHistory()) {
+        printf("\n%*s--> (relation == %d)\n", indent, "", relation());
+        tagHistory()->show(indent + 2);
+    }
+}
+
+void CSSSelector::show() const
+{
+    printf("\n******* CSSSelector::show(\"%s\") *******\n", selectorText().ascii().data());
+    show(2);
+    printf("******* end *******\n");
+}
+#endif
+
 CSSSelector::PseudoType CSSSelector::parsePseudoType(const AtomicString& name)
 {
     if (name.isNull())
@@ -449,7 +483,7 @@
 
     if (name.startsWith("-webkit-"))
         return PseudoWebKitCustomElement;
-    if (name.startsWith("x-") || name.startsWith("cue"))
+    if (name.startsWith("cue"))
         return PseudoUserAgentCustomElement;
 
     return PseudoUnknown;
@@ -543,12 +577,12 @@
     case PseudoFullScreen:
     case PseudoFullScreenDocument:
     case PseudoFullScreenAncestor:
-    case PseudoSeamlessDocument:
     case PseudoInRange:
     case PseudoOutOfRange:
     case PseudoFutureCue:
     case PseudoPastCue:
     case PseudoHost:
+    case PseudoAncestor:
     case PseudoUnresolved:
         break;
     case PseudoFirstPage:
@@ -640,7 +674,7 @@
                 break;
             case PseudoAny: {
                 const CSSSelector* firstSubSelector = cs->selectorList()->first();
-                for (const CSSSelector* subSelector = firstSubSelector; subSelector; subSelector = CSSSelectorList::next(subSelector)) {
+                for (const CSSSelector* subSelector = firstSubSelector; subSelector; subSelector = CSSSelectorList::next(*subSelector)) {
                     if (subSelector != firstSubSelector)
                         str.append(',');
                     str.append(subSelector->selectorText());
@@ -648,10 +682,11 @@
                 str.append(')');
                 break;
             }
-            case PseudoHost: {
+            case PseudoHost:
+            case PseudoAncestor: {
                 if (cs->selectorList()) {
                     const CSSSelector* firstSubSelector = cs->selectorList()->first();
-                    for (const CSSSelector* subSelector = firstSubSelector; subSelector; subSelector = CSSSelectorList::next(subSelector)) {
+                    for (const CSSSelector* subSelector = firstSubSelector; subSelector; subSelector = CSSSelectorList::next(*subSelector)) {
                         if (subSelector != firstSubSelector)
                             str.append(',');
                         str.append(subSelector->selectorText());
@@ -800,6 +835,7 @@
     case CSSSelector::PseudoLastOfType:
     case CSSSelector::PseudoOnlyOfType:
     case CSSSelector::PseudoHost:
+    case CSSSelector::PseudoAncestor:
         return true;
     default:
         return false;
@@ -843,8 +879,8 @@
     return m_data.m_rareData->matchNth(count);
 }
 
-CSSSelector::RareData::RareData(PassRefPtr<StringImpl> value)
-    : m_value(value.leakRef())
+CSSSelector::RareData::RareData(const AtomicString& value)
+    : m_value(value)
     , m_a(0)
     , m_b(0)
     , m_attribute(anyQName())
@@ -854,8 +890,6 @@
 
 CSSSelector::RareData::~RareData()
 {
-    if (m_value)
-        m_value->deref();
 }
 
 // a helper function for parsing nth-arguments
diff --git a/Source/core/css/CSSSelector.h b/Source/core/css/CSSSelector.h
index b009468..b7a1ab1 100644
--- a/Source/core/css/CSSSelector.h
+++ b/Source/core/css/CSSSelector.h
@@ -30,7 +30,57 @@
 namespace WebCore {
     class CSSSelectorList;
 
-    // this class represents a selector for a StyleRule
+    // This class represents a selector for a StyleRule.
+
+    // CSS selector representation is somewhat complicated and subtle. A representative list of selectors is
+    // in CSSSelectorTest; run it in a debug build to see useful debugging output.
+    //
+    // ** tagHistory() and relation():
+    //
+    // Selectors are represented as a linked list of simple selectors (defined more or less according to
+    // http://www.w3.org/TR/css3-selectors/#simple-selectors-dfn). The tagHistory() method returns the next
+    // simple selector in the list. The relation() method returns the relationship of the current simple selector to
+    // the one in tagHistory(). For example, the CSS selector .a.b #c is represented as:
+    //
+    // selectorText(): .a.b .c
+    // --> (relation == Descendant)
+    //   selectorText(): .a.b
+    //   --> (relation == SubSelector)
+    //     selectorText(): .b
+    //
+    // Note that currently a bare selector such as ".a" has a relation() of Descendant. This is a bug - instead the relation should be
+    // "None".
+    //
+    // The order of tagHistory() varies depending on the situation.
+    // * Relations using combinators (http://www.w3.org/TR/css3-selectors/#combinators), such as descendant, sibling, etc., are parsed
+    //   right-to-left (in the example above, this is why .c is earlier in the tagHistory() chain than .a.b).
+    // * SubSelector relations are parsed left-to-right in most cases (such as the .a.b example above); a counter-example is the
+    //   ::content pseudo-element. Most (all?) other pseudo elements and pseudo classes are parsed left-to-right.
+    // * ShadowPseudo relations are parsed right-to-left. Example: summary::-webkit-details-marker is parsed as:
+    //   selectorText(): summary::-webkit-details-marker
+    //    --> (relation == ShadowPseudo)
+    //     selectorText(): summary
+    //
+    // ** match():
+    //
+    // The match of the current simple selector tells us the type of selector, such as class, id, tagname, or pseudo-class.
+    // Inline comments in the Match enum give examples of when each type would occur.
+    //
+    // ** value(), attribute():
+    //
+    // value() tells you the value of the simple selector. For example, for class selectors, value() will tell you the class string,
+    // and for id selectors it will tell you the id(). See below for the special case of attribute selectors.
+    //
+    // ** Attribute selectors.
+    //
+    // Attribute selectors return the attribute name in the attribute() method. The value() method returns the value matched against
+    // in case of selectors like [attr="value"].
+    //
+    // ** isCustomPseudoElement():
+    //
+    // It appears this is used only for pseudo elements that appear in user-agent shadow DOM. They are not exposed to author-created
+    // shadow DOM.
+
     class CSSSelector {
         WTF_MAKE_FAST_ALLOCATED;
     public:
@@ -50,36 +100,38 @@
 
         // tag == -1 means apply to all elements (Selector = *)
 
+        // http://www.w3.org/TR/css3-selectors/#specificity
+        // We use 256 as the base of the specificity number system.
         unsigned specificity() const;
 
         /* how the attribute value has to match.... Default is Exact */
         enum Match {
             Unknown = 0,
-            Tag,
-            Id,
-            Class,
-            Exact,
-            Set,
-            List,
-            Hyphen,
-            PseudoClass,
-            PseudoElement,
+            Tag, // Example: div
+            Id, // Example: #id
+            Class, // example: .class
+            Exact, // Example: E[foo="bar"]
+            Set, // Example: E[foo]
+            List, // Example: E[foo~="bar"]
+            Hyphen, // Example: E[foo|="bar"]
+            PseudoClass, // Example:  :nth-child(2)
+            PseudoElement, // Example: ::first-line
             Contain, // css3: E[foo*="bar"]
             Begin, // css3: E[foo^="bar"]
             End, // css3: E[foo$="bar"]
-            PagePseudoClass
+            PagePseudoClass // ??
         };
 
         enum Relation {
-            Descendant = 0,
-            Child,
-            DirectAdjacent,
-            IndirectAdjacent,
-            SubSelector,
-            ShadowPseudo,
+            Descendant = 0, // "Space" combinator
+            Child, // > combinator
+            DirectAdjacent, // + combinator
+            IndirectAdjacent, // ~ combinator
+            SubSelector, // "No space" combinator
+            ShadowPseudo, // Special case of shadow DOM pseudo elements
             // FIXME: rename ChildTree and DescendantTree when the spec for this is written down.
-            ChildTree,
-            DescendantTree
+            ChildTree, // ^ operator for shadow DOM
+            DescendantTree // ^^ operator for shadow DOM
         };
 
         enum PseudoType {
@@ -161,11 +213,11 @@
             PseudoCue,
             PseudoFutureCue,
             PseudoPastCue,
-            PseudoSeamlessDocument,
             PseudoDistributed,
             PseudoUnresolved,
             PseudoContent,
-            PseudoHost
+            PseudoHost,
+            PseudoAncestor
         };
 
         enum MarginBoxType {
@@ -210,9 +262,15 @@
         // how you use the returned QualifiedName.
         // http://www.w3.org/TR/css3-selectors/#attrnmsp
         const QualifiedName& attribute() const;
+        // Returns the argument of a parameterized selector. For example, nth-child(2) would have an argument of 2.
         const AtomicString& argument() const { return m_hasRareData ? m_data.m_rareData->m_argument : nullAtom; }
         const CSSSelectorList* selectorList() const { return m_hasRareData ? m_data.m_rareData->m_selectorList.get() : 0; }
 
+#ifndef NDEBUG
+        void show() const;
+        void show(int indent) const;
+#endif
+
         void setValue(const AtomicString&);
         void setAttribute(const QualifiedName&);
         void setArgument(const AtomicString&);
@@ -232,6 +290,8 @@
         bool isContentPseudoElement() const;
         bool isHostPseudoClass() const;
 
+        // FIXME: selectors with no tagHistory() get a relation() of Descendant. It should instead be
+        // None.
         Relation relation() const { return static_cast<Relation>(m_relation); }
 
         bool isLastInSelectorList() const { return m_isLastInSelectorList; }
@@ -269,13 +329,13 @@
         CSSSelector& operator=(const CSSSelector&);
 
         struct RareData : public RefCounted<RareData> {
-            static PassRefPtr<RareData> create(PassRefPtr<StringImpl> value) { return adoptRef(new RareData(value)); }
+            static PassRefPtr<RareData> create(const AtomicString& value) { return adoptRef(new RareData(value)); }
             ~RareData();
 
             bool parseNth();
             bool matchNth(int count);
 
-            StringImpl* m_value; // Plain pointer to keep things uniform with the union.
+            AtomicString m_value;
             int m_a; // Used for :nth-*
             int m_b; // Used for :nth-*
             QualifiedName m_attribute; // used for attribute selector
@@ -283,7 +343,7 @@
             OwnPtr<CSSSelectorList> m_selectorList; // Used for :-webkit-any and :not
 
         private:
-            RareData(PassRefPtr<StringImpl> value);
+            RareData(const AtomicString& value);
         };
         void createRareData();
 
@@ -369,10 +429,7 @@
     ASSERT(m_pseudoType == PseudoNotParsed);
     // Need to do ref counting manually for the union.
     if (m_hasRareData) {
-        if (m_data.m_rareData->m_value)
-            m_data.m_rareData->m_value->deref();
-        m_data.m_rareData->m_value = value.impl();
-        m_data.m_rareData->m_value->ref();
+        m_data.m_rareData->m_value = value;
         return;
     }
     if (m_data.m_value)
@@ -454,12 +511,13 @@
 inline const AtomicString& CSSSelector::value() const
 {
     ASSERT(m_match != Tag);
+    if (m_hasRareData)
+        return m_data.m_rareData->m_value;
     // AtomicString is really just a StringImpl* so the cast below is safe.
     // FIXME: Perhaps call sites could be changed to accept StringImpl?
-    return *reinterpret_cast<const AtomicString*>(m_hasRareData ? &m_data.m_rareData->m_value : &m_data.m_value);
+    return *reinterpret_cast<const AtomicString*>(&m_data.m_value);
 }
 
-
 } // namespace WebCore
 
 #endif // CSSSelector_h
diff --git a/Source/core/css/CSSSelectorList.cpp b/Source/core/css/CSSSelectorList.cpp
index 3f183e1..26892fd 100644
--- a/Source/core/css/CSSSelectorList.cpp
+++ b/Source/core/css/CSSSelectorList.cpp
@@ -99,8 +99,12 @@
     if (!m_selectorArray)
         return;
 
-    for (CSSSelector* s = m_selectorArray; !s->isLastInSelectorList(); ++s)
+    bool finished = false;
+    for (CSSSelector* s = m_selectorArray; !finished; ++s) {
+        finished = s->isLastInSelectorList();
         s->~CSSSelector();
+    }
+
     fastFree(m_selectorArray);
 }
 
@@ -108,7 +112,7 @@
 {
     StringBuilder result;
 
-    for (const CSSSelector* s = first(); s; s = next(s)) {
+    for (const CSSSelector* s = first(); s; s = next(*s)) {
         if (s != first())
             result.append(", ");
         result.append(s->selectorText());
@@ -118,20 +122,19 @@
 }
 
 template <typename Functor>
-static bool forEachTagSelector(Functor& functor, const CSSSelector* selector)
+static bool forEachTagSelector(Functor& functor, const CSSSelector& selector)
 {
-    ASSERT(selector);
-
+    const CSSSelector* current = &selector;
     do {
-        if (functor(selector))
+        if (functor(*current))
             return true;
-        if (const CSSSelectorList* selectorList = selector->selectorList()) {
-            for (const CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
-                if (forEachTagSelector(functor, subSelector))
+        if (const CSSSelectorList* selectorList = current->selectorList()) {
+            for (const CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(*subSelector)) {
+                if (forEachTagSelector(functor, *subSelector))
                     return true;
             }
         }
-    } while ((selector = selector->tagHistory()));
+    } while ((current = current->tagHistory()));
 
     return false;
 }
@@ -139,8 +142,8 @@
 template <typename Functor>
 static bool forEachSelector(Functor& functor, const CSSSelectorList* selectorList)
 {
-    for (const CSSSelector* selector = selectorList->first(); selector; selector = CSSSelectorList::next(selector)) {
-        if (forEachTagSelector(functor, selector))
+    for (const CSSSelector* selector = selectorList->first(); selector; selector = CSSSelectorList::next(*selector)) {
+        if (forEachTagSelector(functor, *selector))
             return true;
     }
 
@@ -149,11 +152,11 @@
 
 class SelectorNeedsNamespaceResolutionFunctor {
 public:
-    bool operator()(const CSSSelector* selector)
+    bool operator()(const CSSSelector& selector)
     {
-        if (selector->m_match == CSSSelector::Tag && selector->tagQName().prefix() != nullAtom && selector->tagQName().prefix() != starAtom)
+        if (selector.m_match == CSSSelector::Tag && selector.tagQName().prefix() != nullAtom && selector.tagQName().prefix() != starAtom)
             return true;
-        if (selector->isAttributeSelector() && selector->attribute().prefix() != nullAtom && selector->attribute().prefix() != starAtom)
+        if (selector.isAttributeSelector() && selector.attribute().prefix() != nullAtom && selector.attribute().prefix() != starAtom)
             return true;
         return false;
     }
@@ -167,9 +170,9 @@
 
 class SelectorHasShadowDistributed {
 public:
-    bool operator()(const CSSSelector* selector)
+    bool operator()(const CSSSelector& selector)
     {
-        return selector->relationIsAffectedByPseudoContent();
+        return selector.relationIsAffectedByPseudoContent();
     }
 };
 
@@ -181,9 +184,9 @@
 
 class SelectorHasCombinatorCrossingTreeBoundary {
 public:
-    bool operator()(const CSSSelector* selector)
+    bool operator()(const CSSSelector& selector)
     {
-        return selector->relation() == CSSSelector::ChildTree || selector->relation() == CSSSelector::DescendantTree;
+        return selector.relation() == CSSSelector::ChildTree || selector.relation() == CSSSelector::DescendantTree;
     }
 };
 
diff --git a/Source/core/css/CSSSelectorList.h b/Source/core/css/CSSSelectorList.h
index 320de3b..f90b287 100644
--- a/Source/core/css/CSSSelectorList.h
+++ b/Source/core/css/CSSSelectorList.h
@@ -45,17 +45,17 @@
 
     bool isValid() const { return !!m_selectorArray; }
     const CSSSelector* first() const { return m_selectorArray; }
-    static const CSSSelector* next(const CSSSelector*);
-    bool hasOneSelector() const { return m_selectorArray && !next(m_selectorArray); }
-    const CSSSelector* selectorAt(size_t index) const { return &m_selectorArray[index]; }
+    static const CSSSelector* next(const CSSSelector&);
+    bool hasOneSelector() const { return m_selectorArray && !next(*m_selectorArray); }
+    const CSSSelector& selectorAt(size_t index) const { return m_selectorArray[index]; }
 
     size_t indexOfNextSelectorAfter(size_t index) const
     {
-        const CSSSelector* current = selectorAt(index);
-        current = next(current);
-        if (!current)
+        const CSSSelector& current = selectorAt(index);
+        const CSSSelector* next = this->next(current);
+        if (!next)
             return kNotFound;
-        return current - m_selectorArray;
+        return next - m_selectorArray;
     }
 
     bool selectorsNeedNamespaceResolution();
@@ -77,12 +77,13 @@
     CSSSelector* m_selectorArray;
 };
 
-inline const CSSSelector* CSSSelectorList::next(const CSSSelector* current)
+inline const CSSSelector* CSSSelectorList::next(const CSSSelector& current)
 {
     // Skip subparts of compound selectors.
-    while (!current->isLastInTagHistory())
-        current++;
-    return current->isLastInSelectorList() ? 0 : current + 1;
+    const CSSSelector* last = &current;
+    while (!last->isLastInTagHistory())
+        last++;
+    return last->isLastInSelectorList() ? 0 : last + 1;
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSSelectorTest.cpp b/Source/core/css/CSSSelectorTest.cpp
new file mode 100644
index 0000000..baf0465
--- /dev/null
+++ b/Source/core/css/CSSSelectorTest.cpp
@@ -0,0 +1,58 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/css/CSSTestHelper.h"
+#include "core/css/RuleSet.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+TEST(CSSSelector, Representations)
+{
+    CSSTestHelper helper;
+
+    const char* cssRules =
+    "summary::-webkit-details-marker { }"
+    "* {}"
+    "div {}"
+    "#id {}"
+    ".class {}"
+    "[attr] {}"
+    "div:hover {}"
+    "div:nth-child(2){}"
+    ".class#id { }"
+    "#id.class { }"
+    "[attr]#id { }"
+    "div[attr]#id { }"
+    "div::content { }"
+    "div::first-line { }"
+    ".a.b.c { }"
+    "div:not(.a) { }" // without class a
+    "div:not(:visited) { }" // without the visited pseudo class
+
+    "[attr=\"value\"] { }" // Exact equality
+    "[attr~=\"value\"] { }" // One of a space-separated list
+    "[attr^=\"value\"] { }" // Begins with
+    "[attr$=\"value\"] { }" // Ends with
+    "[attr*=\"value\"] { }" // Substring equal to
+    "[attr|=\"value\"] { }" // One of a hyphen-separated list
+
+    ".a .b { }" // .b is a descendant of .a
+    ".a > .b { }" // .b is a direct descendant of .a
+    ".a ~ .b { }" // .a precedes .b in sibling order
+    ".a + .b { }" // .a element immediately precedes .b in sibling order
+    ".a, .b { }" // matches .a or .b
+
+    ".a.b .c {}";
+
+    helper.addCSSRules(cssRules);
+    EXPECT_EQ(30u, helper.ruleSet().ruleCount()); // .a, .b counts as two rules.
+#ifndef NDEBUG
+    helper.ruleSet().show();
+#endif
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/CSSShaderValue.cpp b/Source/core/css/CSSShaderValue.cpp
deleted file mode 100644
index 1fafe30..0000000
--- a/Source/core/css/CSSShaderValue.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#include "config.h"
-
-#include "core/css/CSSShaderValue.h"
-
-#include "FetchInitiatorTypeNames.h"
-#include "core/css/CSSParser.h"
-#include "core/dom/Document.h"
-#include "core/fetch/FetchRequest.h"
-#include "core/fetch/ResourceFetcher.h"
-#include "core/rendering/style/StyleFetchedShader.h"
-#include "core/rendering/style/StylePendingShader.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-CSSShaderValue::CSSShaderValue(const String& url)
-    : CSSValue(CSSShaderClass)
-    , m_url(url)
-    , m_accessedShader(false)
-{
-}
-
-CSSShaderValue::~CSSShaderValue()
-{
-}
-
-KURL CSSShaderValue::completeURL(ResourceFetcher* loader) const
-{
-    return loader->document()->completeURL(m_url);
-}
-
-StyleFetchedShader* CSSShaderValue::resource(ResourceFetcher* loader)
-{
-    ASSERT(loader);
-
-    if (!m_accessedShader) {
-        m_accessedShader = true;
-
-        FetchRequest request(ResourceRequest(completeURL(loader)), FetchInitiatorTypeNames::css);
-        if (ResourcePtr<ShaderResource> resource = loader->fetchShader(request))
-            m_shader = StyleFetchedShader::create(resource.get());
-    }
-
-    return (m_shader && m_shader->isShaderResource()) ? static_cast<StyleFetchedShader*>(m_shader.get()) : 0;
-}
-
-StyleShader* CSSShaderValue::cachedOrPendingShader()
-{
-    if (!m_shader)
-        m_shader = StylePendingShader::create(this);
-
-    return m_shader.get();
-}
-
-String CSSShaderValue::customCSSText() const
-{
-    StringBuilder result;
-    result.appendLiteral("url(");
-    result.append(quoteCSSURLIfNeeded(m_url));
-    result.append(')');
-    if (!m_format.isEmpty()) {
-        result.appendLiteral(" format('");
-        result.append(m_format);
-        result.appendLiteral("')");
-    }
-    return result.toString();
-}
-
-bool CSSShaderValue::equals(const CSSShaderValue& other) const
-{
-    return m_url == other.m_url;
-}
-
-} // namespace WebCore
-
diff --git a/Source/core/css/CSSShaderValue.h b/Source/core/css/CSSShaderValue.h
deleted file mode 100644
index 9c73626..0000000
--- a/Source/core/css/CSSShaderValue.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef CSSShaderValue_h
-#define CSSShaderValue_h
-
-#include "core/css/CSSValue.h"
-
-namespace WebCore {
-
-class ResourceFetcher;
-class KURL;
-class StyleFetchedShader;
-class StyleShader;
-
-class CSSShaderValue : public CSSValue {
-public:
-    static PassRefPtr<CSSShaderValue> create(const String& url) { return adoptRef(new CSSShaderValue(url)); }
-    ~CSSShaderValue();
-
-    const String& format() const { return m_format; }
-    void setFormat(const String& format) { m_format = format; }
-
-    KURL completeURL(ResourceFetcher*) const;
-    StyleFetchedShader* resource(ResourceFetcher*);
-    StyleShader* cachedOrPendingShader();
-
-    String customCSSText() const;
-
-    bool equals(const CSSShaderValue&) const;
-
-private:
-    CSSShaderValue(const String& url);
-
-    String m_url;
-    String m_format;
-    RefPtr<StyleShader> m_shader;
-    bool m_accessedShader;
-};
-
-DEFINE_CSS_VALUE_TYPE_CASTS(CSSShaderValue, isShaderValue());
-
-} // namespace WebCore
-
-
-#endif // CSSShaderValue_h
diff --git a/Source/core/css/CSSShadowValue.cpp b/Source/core/css/CSSShadowValue.cpp
index 35ecefb..4bdecf5 100644
--- a/Source/core/css/CSSShadowValue.cpp
+++ b/Source/core/css/CSSShadowValue.cpp
@@ -27,12 +27,12 @@
 namespace WebCore {
 
 // Used for text-shadow and box-shadow
-CSSShadowValue::CSSShadowValue(PassRefPtr<CSSPrimitiveValue> x,
-    PassRefPtr<CSSPrimitiveValue> y,
-    PassRefPtr<CSSPrimitiveValue> blur,
-    PassRefPtr<CSSPrimitiveValue> spread,
-    PassRefPtr<CSSPrimitiveValue> style,
-    PassRefPtr<CSSPrimitiveValue> color)
+CSSShadowValue::CSSShadowValue(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> x,
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> y,
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> blur,
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> spread,
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> style,
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> color)
     : CSSValue(ShadowClass)
     , x(x)
     , y(y)
@@ -88,4 +88,15 @@
         && compareCSSValuePtr(style, other.style);
 }
 
+void CSSShadowValue::traceAfterDispatch(Visitor* visitor)
+{
+    visitor->trace(x);
+    visitor->trace(y);
+    visitor->trace(blur);
+    visitor->trace(spread);
+    visitor->trace(style);
+    visitor->trace(color);
+    CSSValue::traceAfterDispatch(visitor);
+}
+
 }
diff --git a/Source/core/css/CSSShadowValue.h b/Source/core/css/CSSShadowValue.h
index 79fe736..9a76368 100644
--- a/Source/core/css/CSSShadowValue.h
+++ b/Source/core/css/CSSShadowValue.h
@@ -32,34 +32,36 @@
 // Used for text-shadow and box-shadow
 class CSSShadowValue : public CSSValue {
 public:
-    static PassRefPtr<CSSShadowValue> create(PassRefPtr<CSSPrimitiveValue> x,
-        PassRefPtr<CSSPrimitiveValue> y,
-        PassRefPtr<CSSPrimitiveValue> blur,
-        PassRefPtr<CSSPrimitiveValue> spread,
-        PassRefPtr<CSSPrimitiveValue> style,
-        PassRefPtr<CSSPrimitiveValue> color)
+    static PassRefPtrWillBeRawPtr<CSSShadowValue> create(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> x,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> y,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> blur,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> spread,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> style,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> color)
     {
-        return adoptRef(new CSSShadowValue(x, y, blur, spread, style, color));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSShadowValue(x, y, blur, spread, style, color));
     }
 
     String customCSSText() const;
 
     bool equals(const CSSShadowValue&) const;
 
-    RefPtr<CSSPrimitiveValue> x;
-    RefPtr<CSSPrimitiveValue> y;
-    RefPtr<CSSPrimitiveValue> blur;
-    RefPtr<CSSPrimitiveValue> spread;
-    RefPtr<CSSPrimitiveValue> style;
-    RefPtr<CSSPrimitiveValue> color;
+    RefPtrWillBeMember<CSSPrimitiveValue> x;
+    RefPtrWillBeMember<CSSPrimitiveValue> y;
+    RefPtrWillBeMember<CSSPrimitiveValue> blur;
+    RefPtrWillBeMember<CSSPrimitiveValue> spread;
+    RefPtrWillBeMember<CSSPrimitiveValue> style;
+    RefPtrWillBeMember<CSSPrimitiveValue> color;
+
+    void traceAfterDispatch(Visitor*);
 
 private:
-    CSSShadowValue(PassRefPtr<CSSPrimitiveValue> x,
-        PassRefPtr<CSSPrimitiveValue> y,
-        PassRefPtr<CSSPrimitiveValue> blur,
-        PassRefPtr<CSSPrimitiveValue> spread,
-        PassRefPtr<CSSPrimitiveValue> style,
-        PassRefPtr<CSSPrimitiveValue> color);
+    CSSShadowValue(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> x,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> y,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> blur,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> spread,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> style,
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> color);
 };
 
 DEFINE_CSS_VALUE_TYPE_CASTS(CSSShadowValue, isShadowValue());
diff --git a/Source/core/css/CSSStyleDeclaration.cpp b/Source/core/css/CSSStyleDeclaration.cpp
deleted file mode 100644
index 1347f99..0000000
--- a/Source/core/css/CSSStyleDeclaration.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-#include "core/css/CSSStyleDeclaration.h"
-
-
-namespace WebCore {
-
-PassRefPtr<CSSVariablesMap> CSSStyleDeclaration::var()
-{
-    if (!m_variablesMap)
-        m_variablesMap = CSSVariablesMap::create(this);
-    return m_variablesMap;
-}
-
-CSSStyleDeclaration::~CSSStyleDeclaration()
-{
-    if (m_variablesMap)
-        m_variablesMap->clearStyleDeclaration();
-}
-
-} // namespace WebCore
diff --git a/Source/core/css/CSSStyleDeclaration.h b/Source/core/css/CSSStyleDeclaration.h
index 5c2445a..9d1de6f 100644
--- a/Source/core/css/CSSStyleDeclaration.h
+++ b/Source/core/css/CSSStyleDeclaration.h
@@ -23,8 +23,6 @@
 
 #include "CSSPropertyNames.h"
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/css/CSSVariablesIterator.h"
-#include "core/css/CSSVariablesMap.h"
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
 
@@ -36,12 +34,11 @@
 class CSSValue;
 class ExceptionState;
 class MutableStylePropertySet;
-class VariablesIterator;
 
 class CSSStyleDeclaration : public ScriptWrappable {
     WTF_MAKE_NONCOPYABLE(CSSStyleDeclaration); WTF_MAKE_FAST_ALLOCATED;
 public:
-    virtual ~CSSStyleDeclaration();
+    virtual ~CSSStyleDeclaration() { }
 
     virtual void ref() = 0;
     virtual void deref() = 0;
@@ -59,14 +56,6 @@
     virtual void setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState&) = 0;
     virtual String removeProperty(const String& propertyName, ExceptionState&) = 0;
 
-    PassRefPtr<CSSVariablesMap> var();
-    virtual unsigned variableCount() const = 0;
-    virtual String variableValue(const AtomicString& name) const = 0;
-    virtual bool setVariableValue(const AtomicString& name, const String& value, ExceptionState&) = 0; // Return value indicates whether variable was added.
-    virtual bool removeVariable(const AtomicString& name) = 0;
-    virtual bool clearVariables(ExceptionState&) = 0;
-    virtual PassRefPtr<CSSVariablesIterator> variablesIterator() const = 0;
-
     // CSSPropertyID versions of the CSSOM functions to support bindings and editing.
     // Use the non-virtual methods in the concrete subclasses when possible.
     // The CSSValue returned by this function should not be exposed to the web as it may be used by multiple documents at the same time.
@@ -84,7 +73,6 @@
     {
         ScriptWrappable::init(this);
     }
-    RefPtr<CSSVariablesMap> m_variablesMap;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSStyleDeclaration.idl b/Source/core/css/CSSStyleDeclaration.idl
index f552573..63bd8ff 100644
--- a/Source/core/css/CSSStyleDeclaration.idl
+++ b/Source/core/css/CSSStyleDeclaration.idl
@@ -25,7 +25,6 @@
              [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter] attribute DOMString        cssText;
 
     [TreatReturnedNullStringAs=Null] DOMString          getPropertyValue([Default=Undefined] optional DOMString propertyName);
-    CSSValue           getPropertyCSSValue([Default=Undefined] optional DOMString propertyName);
     [TreatReturnedNullStringAs=Null, RaisesException] DOMString          removeProperty([Default=Undefined] optional DOMString propertyName);
     [TreatReturnedNullStringAs=Null] DOMString          getPropertyPriority([Default=Undefined] optional DOMString propertyName);
      [RaisesException] void setProperty([Default=Undefined] optional DOMString propertyName,
@@ -34,9 +33,13 @@
 
     readonly attribute unsigned long    length;
     getter DOMString          item([Default=Undefined] optional unsigned long index);
-    [Custom, CustomEnumerateProperty] getter (DOMString or float) (DOMString name);
+    [Custom=PropertyGetter|PropertyEnumerator|PropertyQuery] getter (DOMString or float) (DOMString name);
     [Custom] setter void (DOMString propertyName, [TreatNullAs=NullString] DOMString propertyValue);
     readonly attribute CSSRule          parentRule;
-    [RuntimeEnabled=CSSVariables] readonly attribute CSSVariablesMap var;
+
+    // Deprecated as of 2003: http://lists.w3.org/Archives/Public/www-style/2003Oct/0347.html
+    // FIXME: This should be DeprecateAs=, but currently too many LayoutTests use
+    // this function and would need CONSOLE: message rebaselines!
+    [MeasureAs=CSSStyleDeclarationGetPropertyCSSValue] CSSValue           getPropertyCSSValue([Default=Undefined] optional DOMString propertyName);
 };
 
diff --git a/Source/core/css/CSSStyleRule.cpp b/Source/core/css/CSSStyleRule.cpp
index 1ab4c52..a3fe6aa 100644
--- a/Source/core/css/CSSStyleRule.cpp
+++ b/Source/core/css/CSSStyleRule.cpp
@@ -22,7 +22,7 @@
 #include "config.h"
 #include "core/css/CSSStyleRule.h"
 
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/PropertySetCSSStyleDeclaration.h"
@@ -67,7 +67,7 @@
 String CSSStyleRule::generateSelectorText() const
 {
     StringBuilder builder;
-    for (const CSSSelector* selector = m_styleRule->selectorList().first(); selector; selector = CSSSelectorList::next(selector)) {
+    for (const CSSSelector* selector = m_styleRule->selectorList().first(); selector; selector = CSSSelectorList::next(*selector)) {
         if (selector != m_styleRule->selectorList().first())
             builder.append(", ");
         builder.append(selector->selectorText());
@@ -91,7 +91,8 @@
 
 void CSSStyleRule::setSelectorText(const String& selectorText)
 {
-    CSSParser p(parserContext());
+    CSSParserContext context(parserContext(), 0);
+    BisonCSSParser p(context);
     CSSSelectorList selectorList;
     p.parseSelector(selectorText, selectorList);
     if (!selectorList.isValid())
diff --git a/Source/core/css/CSSStyleRule.h b/Source/core/css/CSSStyleRule.h
index 12b4562..6059179 100644
--- a/Source/core/css/CSSStyleRule.h
+++ b/Source/core/css/CSSStyleRule.h
@@ -30,13 +30,13 @@
 class StyleRuleCSSStyleDeclaration;
 class StyleRule;
 
-class CSSStyleRule : public CSSRule {
+class CSSStyleRule FINAL : public CSSRule {
 public:
     static PassRefPtr<CSSStyleRule> create(StyleRule* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSStyleRule(rule, sheet)); }
 
     virtual ~CSSStyleRule();
 
-    virtual CSSRule::Type type() const { return STYLE_RULE; }
+    virtual CSSRule::Type type() const OVERRIDE { return STYLE_RULE; }
     virtual String cssText() const OVERRIDE;
     virtual void reattach(StyleRuleBase*) OVERRIDE;
 
diff --git a/Source/core/css/CSSStyleSheet.cpp b/Source/core/css/CSSStyleSheet.cpp
index e7fe16e..13adbc4 100644
--- a/Source/core/css/CSSStyleSheet.cpp
+++ b/Source/core/css/CSSStyleSheet.cpp
@@ -24,17 +24,18 @@
 #include "HTMLNames.h"
 #include "SVGNames.h"
 #include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/V8PerIsolateData.h"
 #include "core/css/CSSCharsetRule.h"
 #include "core/css/CSSImportRule.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSRuleList.h"
-#include "core/css/CSSStyleRule.h"
 #include "core/css/MediaList.h"
 #include "core/css/StyleRule.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/Node.h"
+#include "core/frame/ContentSecurityPolicy.h"
 #include "core/frame/UseCounter.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "platform/weborigin/SecurityOrigin.h"
@@ -42,18 +43,18 @@
 
 namespace WebCore {
 
-class StyleSheetCSSRuleList : public CSSRuleList {
+class StyleSheetCSSRuleList FINAL : public CSSRuleList {
 public:
     StyleSheetCSSRuleList(CSSStyleSheet* sheet) : m_styleSheet(sheet) { }
 
 private:
-    virtual void ref() { m_styleSheet->ref(); }
-    virtual void deref() { m_styleSheet->deref(); }
+    virtual void ref() OVERRIDE { m_styleSheet->ref(); }
+    virtual void deref() OVERRIDE { m_styleSheet->deref(); }
 
-    virtual unsigned length() const { return m_styleSheet->length(); }
-    virtual CSSRule* item(unsigned index) const { return m_styleSheet->item(index); }
+    virtual unsigned length() const OVERRIDE { return m_styleSheet->length(); }
+    virtual CSSRule* item(unsigned index) const OVERRIDE { return m_styleSheet->item(index); }
 
-    virtual CSSStyleSheet* styleSheet() const { return m_styleSheet; }
+    virtual CSSStyleSheet* styleSheet() const OVERRIDE { return m_styleSheet; }
 
     CSSStyleSheet* m_styleSheet;
 };
@@ -81,9 +82,15 @@
     return adoptRef(new CSSStyleSheet(sheet, ownerNode, false, TextPosition::minimumPosition()));
 }
 
+PassRefPtr<CSSStyleSheet> CSSStyleSheet::createInline(PassRefPtr<StyleSheetContents> sheet, Node* ownerNode, const TextPosition& startPosition)
+{
+    ASSERT(sheet);
+    return adoptRef(new CSSStyleSheet(sheet, ownerNode, true, startPosition));
+}
+
 PassRefPtr<CSSStyleSheet> CSSStyleSheet::createInline(Node* ownerNode, const KURL& baseURL, const TextPosition& startPosition, const String& encoding)
 {
-    CSSParserContext parserContext(ownerNode->document(), baseURL, encoding);
+    CSSParserContext parserContext(ownerNode->document(), 0, baseURL, encoding);
     RefPtr<StyleSheetContents> sheet = StyleSheetContents::create(baseURL.string(), parserContext);
     return adoptRef(new CSSStyleSheet(sheet.release(), ownerNode, true, startPosition));
 }
@@ -95,6 +102,7 @@
     , m_ownerNode(0)
     , m_ownerRule(ownerRule)
     , m_startPosition(TextPosition::minimumPosition())
+    , m_loadCompleted(false)
 {
     m_contents->registerClient(this);
 }
@@ -106,6 +114,7 @@
     , m_ownerNode(ownerNode)
     , m_ownerRule(0)
     , m_startPosition(startPosition)
+    , m_loadCompleted(false)
 {
     ASSERT(isAcceptableCSSStyleSheetParent(ownerNode));
     m_contents->registerClient(this);
@@ -121,53 +130,26 @@
             m_childRuleCSSOMWrappers[i]->setParentStyleSheet(0);
     }
 
-    for (unsigned i = 0; i < m_extraChildRuleCSSOMWrappers.size(); ++i)
-        m_extraChildRuleCSSOMWrappers[i]->setParentStyleSheet(0);
-
     if (m_mediaCSSOMWrapper)
         m_mediaCSSOMWrapper->clearParentStyleSheet();
 
     m_contents->unregisterClient(this);
 }
 
-void CSSStyleSheet::extraCSSOMWrapperIndices(Vector<unsigned>& indices)
-{
-    indices.grow(m_extraChildRuleCSSOMWrappers.size());
-
-    for (unsigned i = 0; i < m_extraChildRuleCSSOMWrappers.size(); ++i) {
-        CSSRule* cssRule = m_extraChildRuleCSSOMWrappers[i].get();
-        ASSERT(cssRule->type() == CSSRule::STYLE_RULE);
-        StyleRule* styleRule = toCSSStyleRule(cssRule)->styleRule();
-
-        bool didFindIndex = false;
-        for (unsigned j = 0; j < m_contents->ruleCount(); ++j) {
-            if (m_contents->ruleAt(j) == styleRule) {
-                didFindIndex = true;
-                indices[i] = j;
-                break;
-            }
-        }
-        ASSERT(didFindIndex);
-        if (!didFindIndex)
-            indices[i] = 0;
-    }
-}
-
 void CSSStyleSheet::willMutateRules()
 {
     InspectorInstrumentation::willMutateRules(this);
     // If we are the only client it is safe to mutate.
     if (m_contents->hasOneClient() && !m_contents->isInMemoryCache()) {
         m_contents->clearRuleSet();
+        if (m_contents->maybeCacheable())
+            StyleEngine::removeSheet(m_contents.get());
         m_contents->setMutable();
         return;
     }
     // Only cacheable stylesheets should have multiple clients.
     ASSERT(m_contents->isCacheable());
 
-    Vector<unsigned> indices;
-    extraCSSOMWrapperIndices(indices);
-
     // Copy-on-write.
     m_contents->unregisterClient(this);
     m_contents = m_contents->copy();
@@ -176,7 +158,7 @@
     m_contents->setMutable();
 
     // Any existing CSSOM wrappers need to be connected to the copied child rules.
-    reattachChildRuleCSSOMWrappers(indices);
+    reattachChildRuleCSSOMWrappers();
 }
 
 void CSSStyleSheet::didMutateRules()
@@ -200,17 +182,8 @@
     owner->modifiedStyleSheet(this, RecalcStyleDeferred, updateMode);
 }
 
-void CSSStyleSheet::registerExtraChildRuleCSSOMWrapper(PassRefPtr<CSSRule> rule)
+void CSSStyleSheet::reattachChildRuleCSSOMWrappers()
 {
-    m_extraChildRuleCSSOMWrappers.append(rule);
-}
-
-void CSSStyleSheet::reattachChildRuleCSSOMWrappers(const Vector<unsigned>& extraCSSOMWrapperIndices)
-{
-    ASSERT(extraCSSOMWrapperIndices.size() == m_extraChildRuleCSSOMWrappers.size());
-    for (unsigned i = 0; i < extraCSSOMWrapperIndices.size(); ++i)
-        m_extraChildRuleCSSOMWrappers[i]->reattach(m_contents->ruleAt(extraCSSOMWrapperIndices[i]));
-
     for (unsigned i = 0; i < m_childRuleCSSOMWrappers.size(); ++i) {
         if (!m_childRuleCSSOMWrappers[i])
             continue;
@@ -298,22 +271,30 @@
 {
     ASSERT(m_childRuleCSSOMWrappers.isEmpty() || m_childRuleCSSOMWrappers.size() == m_contents->ruleCount());
 
+    if (Document* document = ownerDocument()) {
+        if (!document->contentSecurityPolicy()->allowStyleEval()) {
+            exceptionState.throwSecurityError(document->contentSecurityPolicy()->styleEvalDisabledErrorMessage());
+            return 0;
+        }
+    }
+
     if (index > length()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is larger than the maximum index (" + String::number(length()) + ").");
         return 0;
     }
-    CSSParser p(m_contents->parserContext(), UseCounter::getFrom(this));
+    CSSParserContext context(m_contents->parserContext(), UseCounter::getFrom(this));
+    BisonCSSParser p(context);
     RefPtr<StyleRuleBase> rule = p.parseRule(m_contents.get(), ruleString);
 
     if (!rule) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "Failed to parse the rule '" + ruleString + "'.");
         return 0;
     }
     RuleMutationScope mutationScope(this);
 
     bool success = m_contents->wrapperInsertRule(rule, index);
     if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwDOMException(HierarchyRequestError, "Failed to insert the rule.");
         return 0;
     }
     if (!m_childRuleCSSOMWrappers.isEmpty())
@@ -324,7 +305,7 @@
 
 unsigned CSSStyleSheet::insertRule(const String& rule, ExceptionState& exceptionState)
 {
-    UseCounter::countDeprecation(activeExecutionContext(), UseCounter::CSSStyleSheetInsertRuleOptionalArg);
+    UseCounter::countDeprecation(activeExecutionContext(V8PerIsolateData::mainThreadIsolate()), UseCounter::CSSStyleSheetInsertRuleOptionalArg);
     return insertRule(rule, 0, exceptionState);
 }
 
@@ -333,7 +314,7 @@
     ASSERT(m_childRuleCSSOMWrappers.isEmpty() || m_childRuleCSSOMWrappers.size() == m_contents->ruleCount());
 
     if (index >= length()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is larger than the maximum index (" + String::number(length() - 1) + ").");
         return;
     }
     RuleMutationScope mutationScope(this);
@@ -420,4 +401,16 @@
     m_childRuleCSSOMWrappers.clear();
 }
 
+bool CSSStyleSheet::sheetLoaded()
+{
+    m_loadCompleted = m_ownerNode->sheetLoaded();
+    return m_loadCompleted;
+}
+
+void CSSStyleSheet::startLoadingDynamicSheet()
+{
+    m_loadCompleted = false;
+    m_ownerNode->startLoadingDynamicSheet();
+}
+
 }
diff --git a/Source/core/css/CSSStyleSheet.h b/Source/core/css/CSSStyleSheet.h
index 3c02c23..13ab90f 100644
--- a/Source/core/css/CSSStyleSheet.h
+++ b/Source/core/css/CSSStyleSheet.h
@@ -30,7 +30,7 @@
 
 class CSSCharsetRule;
 class CSSImportRule;
-class CSSParser;
+class BisonCSSParser;
 class CSSRule;
 class CSSRuleList;
 class CSSStyleSheet;
@@ -46,11 +46,12 @@
     EntireStyleSheetUpdate
 };
 
-class CSSStyleSheet : public StyleSheet {
+class CSSStyleSheet FINAL : public StyleSheet {
 public:
     static PassRefPtr<CSSStyleSheet> create(PassRefPtr<StyleSheetContents>, CSSImportRule* ownerRule = 0);
     static PassRefPtr<CSSStyleSheet> create(PassRefPtr<StyleSheetContents>, Node* ownerNode);
     static PassRefPtr<CSSStyleSheet> createInline(Node*, const KURL&, const TextPosition& startPosition = TextPosition::minimumPosition(), const String& encoding = String());
+    static PassRefPtr<CSSStyleSheet> createInline(PassRefPtr<StyleSheetContents>, Node* ownerNode, const TextPosition& startPosition = TextPosition::minimumPosition());
 
     virtual ~CSSStyleSheet();
 
@@ -105,22 +106,23 @@
 
     void clearChildRuleCSSOMWrappers();
 
-    void registerExtraChildRuleCSSOMWrapper(PassRefPtr<CSSRule>);
-
     StyleSheetContents* contents() const { return m_contents.get(); }
 
     bool isInline() const { return m_isInlineStylesheet; }
     TextPosition startPositionInSource() const { return m_startPosition; }
 
+    bool sheetLoaded();
+    bool loadCompleted() const { return m_loadCompleted; }
+    void startLoadingDynamicSheet();
+
 private:
     CSSStyleSheet(PassRefPtr<StyleSheetContents>, CSSImportRule* ownerRule);
     CSSStyleSheet(PassRefPtr<StyleSheetContents>, Node* ownerNode, bool isInlineStylesheet, const TextPosition& startPosition);
 
-    virtual bool isCSSStyleSheet() const { return true; }
-    virtual String type() const { return "text/css"; }
+    virtual bool isCSSStyleSheet() const OVERRIDE { return true; }
+    virtual String type() const OVERRIDE { return "text/css"; }
 
-    void extraCSSOMWrapperIndices(Vector<unsigned>& indices);
-    void reattachChildRuleCSSOMWrappers(const Vector<unsigned>& extraCSSOMWrapperIndices);
+    void reattachChildRuleCSSOMWrappers();
 
     bool canAccessRules() const;
 
@@ -134,12 +136,10 @@
     CSSRule* m_ownerRule;
 
     TextPosition m_startPosition;
+    bool m_loadCompleted;
 
     mutable RefPtr<MediaList> m_mediaCSSOMWrapper;
     mutable Vector<RefPtr<CSSRule> > m_childRuleCSSOMWrappers;
-    // These are CSSOMWrappers that come from getMatchedCSSRules and thus don't map 1-1 to
-    // the StyleRules in the StyleSheetContents.
-    mutable Vector<RefPtr<CSSRule> > m_extraChildRuleCSSOMWrappers;
     mutable OwnPtr<CSSRuleList> m_ruleListCSSOMWrapper;
 };
 
diff --git a/Source/core/css/CSSStyleSheet.idl b/Source/core/css/CSSStyleSheet.idl
index 88a49fe..71619f3 100644
--- a/Source/core/css/CSSStyleSheet.idl
+++ b/Source/core/css/CSSStyleSheet.idl
@@ -20,7 +20,7 @@
 
 // Introduced in DOM Level 2:
 [
-    GenerateVisitDOMWrapper=ownerNode,
+    SetWrapperReferenceFrom=ownerNode,
 ] interface CSSStyleSheet : StyleSheet {
     readonly attribute CSSRule          ownerRule;
     readonly attribute CSSRuleList      cssRules;
@@ -29,11 +29,10 @@
     [RaisesException] void deleteRule(unsigned long index);
 
     // IE Extensions
-    readonly attribute CSSRuleList      rules;
+    [MeasureAs=CSSStyleSheetRules] readonly attribute CSSRuleList rules;
 
-    [RaisesException] long addRule([Default=Undefined] optional DOMString selector,
-                 [Default=Undefined] optional DOMString style,
-                 optional unsigned long index);
-    [RaisesException] void removeRule([Default=Undefined] optional unsigned long index);
+    [RaisesException, MeasureAs=CSSStyleSheetAddRule] long addRule([Default=Undefined] optional DOMString selector,
+                                                                   [Default=Undefined] optional DOMString style,
+                                                                   optional unsigned long index);
+    [RaisesException, MeasureAs=CSSStyleSheetRemoveRule] void removeRule([Default=Undefined] optional unsigned long index);
 };
-
diff --git a/Source/core/css/CSSSupportsRule.h b/Source/core/css/CSSSupportsRule.h
index 4d15dd2..1e461f8 100644
--- a/Source/core/css/CSSSupportsRule.h
+++ b/Source/core/css/CSSSupportsRule.h
@@ -36,7 +36,7 @@
 class CSSRule;
 class StyleRuleSupports;
 
-class CSSSupportsRule : public CSSGroupingRule {
+class CSSSupportsRule FINAL : public CSSGroupingRule {
 public:
     static PassRefPtr<CSSSupportsRule> create(StyleRuleSupports* rule, CSSStyleSheet* sheet)
     {
diff --git a/Source/core/css/CSSTestHelper.cpp b/Source/core/css/CSSTestHelper.cpp
new file mode 100644
index 0000000..d0fac9f
--- /dev/null
+++ b/Source/core/css/CSSTestHelper.cpp
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2014, Google Inc. 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.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE
+ * COPYRIGHT HOLDER 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.
+ */
+
+#include "config.h"
+#include "CSSTestHelper.h"
+
+#include "core/css/CSSRuleList.h"
+#include "core/css/CSSStyleSheet.h"
+#include "core/css/RuleSet.h"
+#include "core/css/StyleSheetContents.h"
+#include "core/dom/Document.h"
+#include "wtf/text/WTFString.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+CSSTestHelper::~CSSTestHelper()
+{
+}
+
+CSSTestHelper::CSSTestHelper()
+{
+    m_document = Document::create();
+    TextPosition position;
+    m_styleSheet = CSSStyleSheet::createInline(m_document.get(), KURL(), position, "UTF-8");
+}
+
+RuleSet& CSSTestHelper::ruleSet()
+{
+    RuleSet& ruleSet = m_styleSheet->contents()->ensureRuleSet(MediaQueryEvaluator(), RuleHasNoSpecialState);
+    ruleSet.compactRulesIfNeeded();
+    return ruleSet;
+}
+
+void CSSTestHelper::addCSSRules(const char* cssText)
+{
+    TextPosition position;
+    unsigned sheetLength = m_styleSheet->length();
+    ASSERT_TRUE(m_styleSheet->contents()->parseStringAtPosition(cssText, position, true));
+    ASSERT_TRUE(m_styleSheet->length() > sheetLength);
+}
+
+int CSSTestHelper::numRules(const RuleData* ruleData)
+{
+    if (!ruleData)
+        return 0;
+    int count = 1;
+    while (!ruleData->isLastInArray()) {
+        ruleData++;
+        count++;
+    }
+    return count;
+}
+
+const RuleData& CSSTestHelper::getRule(const RuleData* ruleData, int index)
+{
+    int count = 0;
+    while (!ruleData->isLastInArray() && count < index) {
+        ruleData++;
+        count++;
+    }
+    return *ruleData;
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/CSSTestHelper.h b/Source/core/css/CSSTestHelper.h
new file mode 100644
index 0000000..ea87f1e
--- /dev/null
+++ b/Source/core/css/CSSTestHelper.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2014, Google Inc. 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.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE
+ * COPYRIGHT HOLDER 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.
+ */
+
+#ifndef CSSTestHelper_h
+#define CSSTestHelper_h
+
+#include "core/css/RuleSet.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class Document;
+class CSSStyleSheet;
+
+// A helper class for writing tests of CSS rules. Example usage:
+//
+// CSSTestHelper helper;
+// helper.addCSSRule("body { color: red} #a { position: absolute }");
+// RuleSet& ruleSet = helper.ruleSet();
+// ... examine RuleSet to find the rule and test properties on it.
+
+class CSSTestHelper {
+public:
+    CSSTestHelper();
+    ~CSSTestHelper();
+
+    void addCSSRules(const char* ruleText);
+    RuleSet& ruleSet();
+
+    // Returns the number of rules in the given RuleData array.
+    static int numRules(const RuleData*);
+    // Returns the data at index i (must be less than numNules())
+    static const RuleData& getRule(const RuleData*, int index);
+private:
+    RefPtr<Document> m_document;
+    RefPtr<CSSStyleSheet> m_styleSheet;
+};
+
+} // namespace WebCore
+
+#endif // CSSTestHelper_h
diff --git a/Source/core/css/CSSTimingFunctionValue.h b/Source/core/css/CSSTimingFunctionValue.h
index 54f5661..10778e8 100644
--- a/Source/core/css/CSSTimingFunctionValue.h
+++ b/Source/core/css/CSSTimingFunctionValue.h
@@ -33,9 +33,9 @@
 
 class CSSCubicBezierTimingFunctionValue : public CSSValue {
 public:
-    static PassRefPtr<CSSCubicBezierTimingFunctionValue> create(double x1, double y1, double x2, double y2)
+    static PassRefPtrWillBeRawPtr<CSSCubicBezierTimingFunctionValue> create(double x1, double y1, double x2, double y2)
     {
-        return adoptRef(new CSSCubicBezierTimingFunctionValue(x1, y1, x2, y2));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSCubicBezierTimingFunctionValue(x1, y1, x2, y2));
     }
 
     String customCSSText() const;
@@ -47,6 +47,8 @@
 
     bool equals(const CSSCubicBezierTimingFunctionValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     CSSCubicBezierTimingFunctionValue(double x1, double y1, double x2, double y2)
         : CSSValue(CubicBezierTimingFunctionClass)
@@ -67,9 +69,9 @@
 
 class CSSStepsTimingFunctionValue : public CSSValue {
 public:
-    static PassRefPtr<CSSStepsTimingFunctionValue> create(int steps, bool stepAtStart)
+    static PassRefPtrWillBeRawPtr<CSSStepsTimingFunctionValue> create(int steps, bool stepAtStart)
     {
-        return adoptRef(new CSSStepsTimingFunctionValue(steps, stepAtStart));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSStepsTimingFunctionValue(steps, stepAtStart));
     }
 
     int numberOfSteps() const { return m_steps; }
@@ -79,6 +81,8 @@
 
     bool equals(const CSSStepsTimingFunctionValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     CSSStepsTimingFunctionValue(int steps, bool stepAtStart)
         : CSSValue(StepsTimingFunctionClass)
diff --git a/Source/core/css/CSSToLengthConversionData.cpp b/Source/core/css/CSSToLengthConversionData.cpp
index 6085a69..6658396 100644
--- a/Source/core/css/CSSToLengthConversionData.cpp
+++ b/Source/core/css/CSSToLengthConversionData.cpp
@@ -31,10 +31,45 @@
 #include "config.h"
 #include "core/css/CSSToLengthConversionData.h"
 
+#include "core/rendering/RenderView.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
 
+CSSToLengthConversionData::CSSToLengthConversionData(const RenderStyle* style, const RenderStyle* rootStyle, const RenderView* renderView, float zoom, bool computingFontSize)
+    : m_style(style)
+    , m_rootStyle(rootStyle)
+    , m_viewportWidth(renderView ? renderView->layoutViewportWidth() : 0)
+    , m_viewportHeight(renderView ? renderView->layoutViewportHeight() : 0)
+    , m_zoom(zoom)
+    , m_useEffectiveZoom(false)
+    , m_computingFontSize(computingFontSize)
+{
+    ASSERT(zoom > 0);
+}
+
+CSSToLengthConversionData::CSSToLengthConversionData(const RenderStyle* style, const RenderStyle* rootStyle, const RenderView* renderView, bool computingFontSize)
+    : m_style(style)
+    , m_rootStyle(rootStyle)
+    , m_viewportWidth(renderView ? renderView->layoutViewportWidth() : 0)
+    , m_viewportHeight(renderView ? renderView->layoutViewportHeight() : 0)
+    , m_useEffectiveZoom(true)
+    , m_computingFontSize(computingFontSize)
+{
+}
+
+CSSToLengthConversionData::CSSToLengthConversionData(const RenderStyle* style, const RenderStyle* rootStyle, float viewportWidth, float viewportHeight, float zoom, bool computingFontSize)
+    : m_style(style)
+    , m_rootStyle(rootStyle)
+    , m_viewportWidth(viewportWidth)
+    , m_viewportHeight(viewportHeight)
+    , m_zoom(zoom)
+    , m_useEffectiveZoom(false)
+    , m_computingFontSize(computingFontSize)
+{
+    ASSERT(zoom > 0);
+}
+
 float CSSToLengthConversionData::zoom() const
 {
     if (m_useEffectiveZoom)
@@ -42,4 +77,25 @@
     return m_zoom;
 }
 
+double CSSToLengthConversionData::viewportWidthPercent() const
+{
+    m_style->setHasViewportUnits();
+    return m_viewportWidth / 100;
+}
+double CSSToLengthConversionData::viewportHeightPercent() const
+{
+    m_style->setHasViewportUnits();
+    return m_viewportHeight / 100;
+}
+double CSSToLengthConversionData::viewportMinPercent() const
+{
+    m_style->setHasViewportUnits();
+    return std::min(m_viewportWidth, m_viewportHeight) / 100;
+}
+double CSSToLengthConversionData::viewportMaxPercent() const
+{
+    m_style->setHasViewportUnits();
+    return std::max(m_viewportWidth, m_viewportHeight) / 100;
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/CSSToLengthConversionData.h b/Source/core/css/CSSToLengthConversionData.h
index 975be5f..f110b23 100644
--- a/Source/core/css/CSSToLengthConversionData.h
+++ b/Source/core/css/CSSToLengthConversionData.h
@@ -37,41 +37,38 @@
 namespace WebCore {
 
 class RenderStyle;
+class RenderView;
 
 class CSSToLengthConversionData {
 public:
-    CSSToLengthConversionData(const RenderStyle* style, const RenderStyle* rootStyle, float zoom, bool computingFontSize = false)
-        : m_style(style)
-        , m_rootStyle(rootStyle)
-        , m_zoom(zoom)
-        , m_useEffectiveZoom(false)
-        , m_computingFontSize(computingFontSize)
-    {
-        ASSERT(zoom > 0);
-    }
-    CSSToLengthConversionData(const RenderStyle* style, const RenderStyle* rootStyle, bool computingFontSize = false)
-        : m_style(style)
-        , m_rootStyle(rootStyle)
-        , m_useEffectiveZoom(true)
-        , m_computingFontSize(computingFontSize)
-    {
-    }
+    CSSToLengthConversionData(const RenderStyle* currStyle, const RenderStyle* rootStyle, const RenderView*, float zoom, bool computingFontSize = false);
+    CSSToLengthConversionData(const RenderStyle* currStyle, const RenderStyle* rootStyle, const RenderView*, bool computingFontSize = false);
+    CSSToLengthConversionData(const RenderStyle* currStyle, const RenderStyle* rootStyle, float viewportWidth, float viewportHeight, float zoom, bool computingFontSize = false);
+
     const RenderStyle& style() const { return *m_style; }
     const RenderStyle& rootStyle() const { return *m_rootStyle; }
     float zoom() const;
     bool computingFontSize() const { return m_computingFontSize; }
 
+    // Accessing these marks the style as having viewport units
+    double viewportWidthPercent() const;
+    double viewportHeightPercent() const;
+    double viewportMinPercent() const;
+    double viewportMaxPercent() const;
+
     void setStyle(const RenderStyle* style) { m_style = style; }
     void setRootStyle(const RenderStyle* rootStyle) { m_rootStyle = rootStyle; }
 
     CSSToLengthConversionData copyWithAdjustedZoom(float newZoom) const
     {
-        return CSSToLengthConversionData(m_style, m_rootStyle, newZoom, m_computingFontSize);
+        return CSSToLengthConversionData(m_style, m_rootStyle, m_viewportWidth, m_viewportHeight, newZoom, m_computingFontSize);
     }
 
 private:
     const RenderStyle* m_style;
     const RenderStyle* m_rootStyle;
+    float m_viewportWidth;
+    float m_viewportHeight;
     float m_zoom;
     bool m_useEffectiveZoom;
     bool m_computingFontSize;
diff --git a/Source/core/css/CSSTokenizer-in.cpp b/Source/core/css/CSSTokenizer-in.cpp
index 5ee194a..9c3fb0a 100644
--- a/Source/core/css/CSSTokenizer-in.cpp
+++ b/Source/core/css/CSSTokenizer-in.cpp
@@ -28,7 +28,7 @@
 #include "core/css/CSSTokenizer.h"
 
 #include "core/css/CSSKeyframeRule.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSParserValues.h"
 #include "core/css/MediaQuery.h"
 #include "core/css/StyleRule.h"
@@ -719,12 +719,6 @@
             m_token = CUEFUNCTION;
             return true;
         }
-        CASE("var") {
-            if (!RuntimeEnabledFeatures::cssVariablesEnabled())
-                return false;
-            m_token = VARFUNCTION;
-            return true;
-        }
         CASE("calc") {
             m_token = CALCFUNCTION;
             return true;
@@ -733,6 +727,10 @@
             m_token = HOSTFUNCTION;
             return true;
         }
+        CASE("ancestor") {
+            m_token = ANCESTORFUNCTION;
+            return true;
+        }
         CASE("nth-child") {
             m_parsingMode = NthChildMode;
             return true;
@@ -1009,14 +1007,6 @@
             if (LIKELY(!hasEscape && m_internal))
                 m_token = INTERNAL_RULE_SYM;
         }
-        CASE("-webkit-region") {
-            if (LIKELY(!hasEscape))
-                m_token = WEBKIT_REGION_RULE_SYM;
-        }
-        CASE("-webkit-filter") {
-            if (LIKELY(!hasEscape))
-                m_token = WEBKIT_FILTER_RULE_SYM;
-        }
         CASE("-internal-decls") {
             if (LIKELY(!hasEscape && m_internal))
                 m_token = INTERNAL_DECLS_SYM;
@@ -1075,18 +1065,6 @@
     }
 }
 
-template <typename CharacterType>
-inline void CSSTokenizer::detectCSSVariableDefinitionToken(int length)
-{
-    static const int prefixLength = static_cast<int>(sizeof("var-") - 1);
-    if (length <= prefixLength)
-        return;
-    CharacterType* name = tokenStart<CharacterType>();
-    COMPILE_ASSERT(prefixLength > 0, CSS_variable_prefix_must_be_nonempty);
-    if (name[prefixLength - 1] == '-' && isIdentifierStartAfterDash(name + prefixLength) && isEqualToCSSCaseSensitiveIdentifier(name, "var"))
-        m_token = VAR_DEFINITION;
-}
-
 template <typename SrcCharacterType>
 int CSSTokenizer::realLex(void* yylvalWithoutType)
 {
@@ -1176,8 +1154,6 @@
                     }
                 }
             }
-        } else if (UNLIKELY(RuntimeEnabledFeatures::cssVariablesEnabled())) {
-            detectCSSVariableDefinitionToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
         }
         break;
 
@@ -1388,9 +1364,9 @@
         // Ignore comments. They are not even considered as white spaces.
         if (*currentCharacter<SrcCharacterType>() == '*') {
             const CSSParserLocation startLocation = currentLocation();
-            if (m_parser.m_sourceDataHandler) {
+            if (m_parser.m_observer) {
                 unsigned startOffset = currentCharacter<SrcCharacterType>() - dataStart<SrcCharacterType>() - 1; // Start with a slash.
-                m_parser.m_sourceDataHandler->startComment(startOffset - m_parsedTextPrefixLength);
+                m_parser.m_observer->startComment(startOffset - m_parsedTextPrefixLength);
             }
             ++currentCharacter<SrcCharacterType>();
             while (currentCharacter<SrcCharacterType>()[0] != '*' || currentCharacter<SrcCharacterType>()[1] != '/') {
@@ -1399,16 +1375,16 @@
                 if (*currentCharacter<SrcCharacterType>() == '\0') {
                     // Unterminated comments are simply ignored.
                     currentCharacter<SrcCharacterType>() -= 2;
-                    m_parser.reportError(startLocation, CSSParser::UnterminatedCommentError);
+                    m_parser.reportError(startLocation, UnterminatedCommentCSSError);
                     break;
                 }
                 ++currentCharacter<SrcCharacterType>();
             }
             currentCharacter<SrcCharacterType>() += 2;
-            if (m_parser.m_sourceDataHandler) {
+            if (m_parser.m_observer) {
                 unsigned endOffset = currentCharacter<SrcCharacterType>() - dataStart<SrcCharacterType>();
                 unsigned userTextEndOffset = static_cast<unsigned>(m_length - 1 - m_parsedTextSuffixLength);
-                m_parser.m_sourceDataHandler->endComment(std::min(endOffset, userTextEndOffset) - m_parsedTextPrefixLength);
+                m_parser.m_observer->endComment(std::min(endOffset, userTextEndOffset) - m_parsedTextPrefixLength);
             }
             goto restartAfterComment;
         }
diff --git a/Source/core/css/CSSTokenizer.h b/Source/core/css/CSSTokenizer.h
index 05b319c..5d8fae1 100644
--- a/Source/core/css/CSSTokenizer.h
+++ b/Source/core/css/CSSTokenizer.h
@@ -29,7 +29,7 @@
 
 namespace WebCore {
 
-class CSSParser;
+class BisonCSSParser;
 struct CSSParserLocation;
 struct CSSParserString;
 
@@ -37,9 +37,9 @@
     WTF_MAKE_NONCOPYABLE(CSSTokenizer);
 public:
     // FIXME: This should not be needed but there are still some ties between the 2 classes.
-    friend class CSSParser;
+    friend class BisonCSSParser;
 
-    CSSTokenizer(CSSParser& parser)
+    CSSTokenizer(BisonCSSParser& parser)
         : m_parser(parser)
         , m_parsedTextPrefixLength(0)
         , m_parsedTextSuffixLength(0)
@@ -133,13 +133,11 @@
     inline void detectAtToken(int, bool);
     template <typename CharacterType>
     inline void detectSupportsToken(int);
-    template <typename CharacterType>
-    inline void detectCSSVariableDefinitionToken(int);
 
     template <typename SourceCharacterType>
     int realLex(void* yylval);
 
-    CSSParser& m_parser;
+    BisonCSSParser& m_parser;
 
     size_t m_parsedTextPrefixLength;
     size_t m_parsedTextSuffixLength;
diff --git a/Source/core/css/CSSTransformValue.cpp b/Source/core/css/CSSTransformValue.cpp
index de98194..06021d8 100644
--- a/Source/core/css/CSSTransformValue.cpp
+++ b/Source/core/css/CSSTransformValue.cpp
@@ -76,20 +76,15 @@
     return transformValueToCssString(m_type, CSSValueList::customCSSText());
 }
 
-String CSSTransformValue::customSerializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-{
-    return transformValueToCssString(m_type, CSSValueList::customSerializeResolvingVariables(variables));
-}
-
 CSSTransformValue::CSSTransformValue(const CSSTransformValue& cloneFrom)
     : CSSValueList(cloneFrom)
     , m_type(cloneFrom.m_type)
 {
 }
 
-PassRefPtr<CSSTransformValue> CSSTransformValue::cloneForCSSOM() const
+PassRefPtrWillBeRawPtr<CSSTransformValue> CSSTransformValue::cloneForCSSOM() const
 {
-    return adoptRef(new CSSTransformValue(*this));
+    return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSTransformValue(*this));
 }
 
 }
diff --git a/Source/core/css/CSSTransformValue.h b/Source/core/css/CSSTransformValue.h
index 1ca3bbd..bd8f69a 100644
--- a/Source/core/css/CSSTransformValue.h
+++ b/Source/core/css/CSSTransformValue.h
@@ -59,18 +59,19 @@
         Matrix3DTransformOperation
     };
 
-    static PassRefPtr<CSSTransformValue> create(TransformOperationType type)
+    static PassRefPtrWillBeRawPtr<CSSTransformValue> create(TransformOperationType type)
     {
-        return adoptRef(new CSSTransformValue(type));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSTransformValue(type));
     }
 
     String customCSSText() const;
     bool equals(const CSSTransformValue& other) const { return m_type == other.m_type && CSSValueList::equals(other); }
-    String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
 
     TransformOperationType operationType() const { return m_type; }
 
-    PassRefPtr<CSSTransformValue> cloneForCSSOM() const;
+    PassRefPtrWillBeRawPtr<CSSTransformValue> cloneForCSSOM() const;
+
+    void traceAfterDispatch(Visitor* visitor) { CSSValueList::traceAfterDispatch(visitor); }
 
 private:
     CSSTransformValue(TransformOperationType);
diff --git a/Source/core/css/CSSUnicodeRangeValue.h b/Source/core/css/CSSUnicodeRangeValue.h
index 3ce02a9..acfc0a6 100644
--- a/Source/core/css/CSSUnicodeRangeValue.h
+++ b/Source/core/css/CSSUnicodeRangeValue.h
@@ -33,9 +33,9 @@
 
 class CSSUnicodeRangeValue : public CSSValue {
 public:
-    static PassRefPtr<CSSUnicodeRangeValue> create(UChar32 from, UChar32 to)
+    static PassRefPtrWillBeRawPtr<CSSUnicodeRangeValue> create(UChar32 from, UChar32 to)
     {
-        return adoptRef(new CSSUnicodeRangeValue(from, to));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSUnicodeRangeValue(from, to));
     }
 
     UChar32 from() const { return m_from; }
@@ -45,6 +45,8 @@
 
     bool equals(const CSSUnicodeRangeValue&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     CSSUnicodeRangeValue(UChar32 from, UChar32 to)
         : CSSValue(UnicodeRangeClass)
diff --git a/Source/core/css/CSSUnknownRule.h b/Source/core/css/CSSUnknownRule.h
index 629aaea..ada0b6e 100644
--- a/Source/core/css/CSSUnknownRule.h
+++ b/Source/core/css/CSSUnknownRule.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class CSSUnknownRule : public CSSRule {
+class CSSUnknownRule FINAL : public CSSRule {
 public:
     CSSUnknownRule() : CSSRule(0) { }
     virtual ~CSSUnknownRule() { }
diff --git a/Source/core/css/CSSValue.cpp b/Source/core/css/CSSValue.cpp
index 6d74434..a02a034 100644
--- a/Source/core/css/CSSValue.cpp
+++ b/Source/core/css/CSSValue.cpp
@@ -41,29 +41,28 @@
 #include "core/css/CSSFunctionValue.h"
 #include "core/css/CSSGradientValue.h"
 #include "core/css/CSSGridLineNamesValue.h"
-#include "core/css/CSSGridTemplateValue.h"
+#include "core/css/CSSGridTemplateAreasValue.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSImageValue.h"
 #include "core/css/CSSInheritedValue.h"
 #include "core/css/CSSInitialValue.h"
 #include "core/css/CSSLineBoxContainValue.h"
-#include "core/css/CSSMixFunctionValue.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSReflectValue.h"
 #include "core/css/CSSSVGDocumentValue.h"
-#include "core/css/CSSShaderValue.h"
 #include "core/css/CSSShadowValue.h"
 #include "core/css/CSSTimingFunctionValue.h"
 #include "core/css/CSSTransformValue.h"
 #include "core/css/CSSUnicodeRangeValue.h"
 #include "core/css/CSSValueList.h"
-#include "core/css/CSSVariableValue.h"
 #include "core/svg/SVGColor.h"
 #include "core/svg/SVGPaint.h"
 
 namespace WebCore {
 
-struct SameSizeAsCSSValue : public RefCounted<SameSizeAsCSSValue> {
+DEFINE_GC_INFO(CSSValue);
+
+struct SameSizeAsCSSValue : public RefCountedWillBeRefCountedGarbageCollected<SameSizeAsCSSValue> {
     uint32_t bitfields;
 };
 
@@ -75,6 +74,8 @@
 
     String cssText() const { return m_cssText; }
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 private:
     TextCloneCSSValue(ClassType classType, const String& text)
         : CSSValue(classType, /*isCSSOMSafe*/ true)
@@ -106,21 +107,6 @@
     return CSS_CUSTOM;
 }
 
-void CSSValue::addSubresourceStyleURLs(ListHashSet<KURL>& urls, const StyleSheetContents* styleSheet) const
-{
-    // This should get called for internal instances only.
-    ASSERT(!isCSSOMSafe());
-
-    if (isPrimitiveValue())
-        toCSSPrimitiveValue(this)->addSubresourceStyleURLs(urls, styleSheet);
-    else if (isValueList())
-        toCSSValueList(this)->addSubresourceStyleURLs(urls, styleSheet);
-    else if (classType() == FontFaceSrcClass)
-        toCSSFontFaceSrcValue(this)->addSubresourceStyleURLs(urls, styleSheet);
-    else if (classType() == ReflectClass)
-        toCSSReflectValue(this)->addSubresourceStyleURLs(urls, styleSheet);
-}
-
 bool CSSValue::hasFailedOrCanceledSubresources() const
 {
     // This should get called for internal instances only.
@@ -185,8 +171,8 @@
             return compareCSSValues<CSSInitialValue>(*this, other);
         case GridLineNamesClass:
             return compareCSSValues<CSSGridLineNamesValue>(*this, other);
-        case GridTemplateClass:
-            return compareCSSValues<CSSGridTemplateValue>(*this, other);
+        case GridTemplateAreasClass:
+            return compareCSSValues<CSSGridTemplateAreasValue>(*this, other);
         case PrimitiveClass:
             return compareCSSValues<CSSPrimitiveValue>(*this, other);
         case ReflectClass:
@@ -213,12 +199,6 @@
             return compareCSSValues<CSSFilterValue>(*this, other);
         case CSSArrayFunctionValueClass:
             return compareCSSValues<CSSArrayFunctionValue>(*this, other);
-        case CSSMixFunctionValueClass:
-            return compareCSSValues<CSSMixFunctionValue>(*this, other);
-        case CSSShaderClass:
-            return compareCSSValues<CSSShaderValue>(*this, other);
-        case VariableClass:
-            return compareCSSValues<CSSVariableValue>(*this, other);
         case SVGColorClass:
             return compareCSSValues<SVGColor>(*this, other);
         case SVGPaintClass:
@@ -275,8 +255,8 @@
         return toCSSInitialValue(this)->customCSSText();
     case GridLineNamesClass:
         return toCSSGridLineNamesValue(this)->customCSSText();
-    case GridTemplateClass:
-        return toCSSGridTemplateValue(this)->customCSSText();
+    case GridTemplateAreasClass:
+        return toCSSGridTemplateAreasValue(this)->customCSSText();
     case PrimitiveClass:
         return toCSSPrimitiveValue(this)->customCSSText();
     case ReflectClass:
@@ -303,12 +283,6 @@
         return toCSSFilterValue(this)->customCSSText();
     case CSSArrayFunctionValueClass:
         return toCSSArrayFunctionValue(this)->customCSSText();
-    case CSSMixFunctionValueClass:
-        return toCSSMixFunctionValue(this)->customCSSText();
-    case CSSShaderClass:
-        return toCSSShaderValue(this)->customCSSText();
-    case VariableClass:
-        return toCSSVariableValue(this)->value();
     case SVGColorClass:
         return toSVGColor(this)->customCSSText();
     case SVGPaintClass:
@@ -320,22 +294,6 @@
     return String();
 }
 
-String CSSValue::serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-{
-    switch (classType()) {
-    case PrimitiveClass:
-        return toCSSPrimitiveValue(this)->customSerializeResolvingVariables(variables);
-    case ReflectClass:
-        return toCSSReflectValue(this)->customSerializeResolvingVariables(variables);
-    case ValueListClass:
-        return toCSSValueList(this)->customSerializeResolvingVariables(variables);
-    case CSSTransformClass:
-        return toCSSTransformValue(this)->customSerializeResolvingVariables(variables);
-    default:
-        return cssText();
-    }
-}
-
 void CSSValue::destroy()
 {
     if (m_isTextClone) {
@@ -391,8 +349,8 @@
     case GridLineNamesClass:
         delete toCSSGridLineNamesValue(this);
         return;
-    case GridTemplateClass:
-        delete toCSSGridTemplateValue(this);
+    case GridTemplateAreasClass:
+        delete toCSSGridTemplateAreasValue(this);
         return;
     case PrimitiveClass:
         delete toCSSPrimitiveValue(this);
@@ -433,15 +391,6 @@
     case CSSArrayFunctionValueClass:
         delete toCSSArrayFunctionValue(this);
         return;
-    case CSSMixFunctionValueClass:
-        delete toCSSMixFunctionValue(this);
-        return;
-    case CSSShaderClass:
-        delete toCSSShaderValue(this);
-        return;
-    case VariableClass:
-        delete toCSSVariableValue(this);
-        return;
     case SVGColorClass:
         delete toSVGColor(this);
         return;
@@ -455,6 +404,226 @@
     ASSERT_NOT_REACHED();
 }
 
+void CSSValue::finalize()
+{
+    if (m_isTextClone) {
+        ASSERT(isCSSOMSafe());
+        static_cast<TextCloneCSSValue*>(this)->~TextCloneCSSValue();
+        return;
+    }
+    ASSERT(!isCSSOMSafe() || isSubtypeExposedToCSSOM());
+
+    switch (classType()) {
+    case AspectRatioClass:
+        static_cast<CSSAspectRatioValue*>(this)->~CSSAspectRatioValue();
+        return;
+    case BorderImageSliceClass:
+        static_cast<CSSBorderImageSliceValue*>(this)->~CSSBorderImageSliceValue();
+        return;
+    case CanvasClass:
+        static_cast<CSSCanvasValue*>(this)->~CSSCanvasValue();
+        return;
+    case CursorImageClass:
+        static_cast<CSSCursorImageValue*>(this)->~CSSCursorImageValue();
+        return;
+    case FontClass:
+        static_cast<CSSFontValue*>(this)->~CSSFontValue();
+        return;
+    case FontFaceSrcClass:
+        static_cast<CSSFontFaceSrcValue*>(this)->~CSSFontFaceSrcValue();
+        return;
+    case FontFeatureClass:
+        static_cast<CSSFontFeatureValue*>(this)->~CSSFontFeatureValue();
+        return;
+    case FunctionClass:
+        static_cast<CSSFunctionValue*>(this)->~CSSFunctionValue();
+        return;
+    case LinearGradientClass:
+        static_cast<CSSLinearGradientValue*>(this)->~CSSLinearGradientValue();
+        return;
+    case RadialGradientClass:
+        static_cast<CSSRadialGradientValue*>(this)->~CSSRadialGradientValue();
+        return;
+    case CrossfadeClass:
+        static_cast<CSSCrossfadeValue*>(this)->~CSSCrossfadeValue();
+        return;
+    case ImageClass:
+        static_cast<CSSImageValue*>(this)->~CSSImageValue();
+        return;
+    case InheritedClass:
+        static_cast<CSSInheritedValue*>(this)->~CSSInheritedValue();
+        return;
+    case InitialClass:
+        static_cast<CSSInitialValue*>(this)->~CSSInitialValue();
+        return;
+    case GridLineNamesClass:
+        static_cast<CSSGridLineNamesValue*>(this)->~CSSGridLineNamesValue();
+        return;
+    case GridTemplateAreasClass:
+        static_cast<CSSGridTemplateAreasValue*>(this)->~CSSGridTemplateAreasValue();
+        return;
+    case PrimitiveClass:
+        static_cast<CSSPrimitiveValue*>(this)->~CSSPrimitiveValue();
+        return;
+    case ReflectClass:
+        static_cast<CSSReflectValue*>(this)->~CSSReflectValue();
+        return;
+    case ShadowClass:
+        static_cast<CSSShadowValue*>(this)->~CSSShadowValue();
+        return;
+    case CubicBezierTimingFunctionClass:
+        static_cast<CSSCubicBezierTimingFunctionValue*>(this)->~CSSCubicBezierTimingFunctionValue();
+        return;
+    case StepsTimingFunctionClass:
+        static_cast<CSSStepsTimingFunctionValue*>(this)->~CSSStepsTimingFunctionValue();
+        return;
+    case UnicodeRangeClass:
+        static_cast<CSSUnicodeRangeValue*>(this)->~CSSUnicodeRangeValue();
+        return;
+    case ValueListClass:
+        static_cast<CSSValueList*>(this)->~CSSValueList();
+        return;
+    case CSSTransformClass:
+        static_cast<CSSTransformValue*>(this)->~CSSTransformValue();
+        return;
+    case LineBoxContainClass:
+        static_cast<CSSLineBoxContainValue*>(this)->~CSSLineBoxContainValue();
+        return;
+    case CalculationClass:
+        static_cast<CSSCalcValue*>(this)->~CSSCalcValue();
+        return;
+    case ImageSetClass:
+        static_cast<CSSImageSetValue*>(this)->~CSSImageSetValue();
+        return;
+    case CSSFilterClass:
+        static_cast<CSSFilterValue*>(this)->~CSSFilterValue();
+        return;
+    case CSSArrayFunctionValueClass:
+        static_cast<CSSArrayFunctionValue*>(this)->~CSSArrayFunctionValue();
+        return;
+    case SVGColorClass:
+        static_cast<SVGColor*>(this)->~SVGColor();
+        return;
+    case SVGPaintClass:
+        static_cast<SVGPaint*>(this)->~SVGPaint();
+        return;
+    case CSSSVGDocumentClass:
+        static_cast<CSSSVGDocumentValue*>(this)->~CSSSVGDocumentValue();
+        return;
+    }
+    ASSERT_NOT_REACHED();
+}
+
+void CSSValue::trace(Visitor* visitor)
+{
+    if (m_isTextClone) {
+        ASSERT(isCSSOMSafe());
+        static_cast<TextCloneCSSValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    }
+    ASSERT(!isCSSOMSafe() || isSubtypeExposedToCSSOM());
+
+    switch (classType()) {
+    case AspectRatioClass:
+        static_cast<CSSAspectRatioValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case BorderImageSliceClass:
+        static_cast<CSSBorderImageSliceValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case CanvasClass:
+        static_cast<CSSCanvasValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case CursorImageClass:
+        static_cast<CSSCursorImageValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case FontClass:
+        static_cast<CSSFontValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case FontFaceSrcClass:
+        static_cast<CSSFontFaceSrcValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case FontFeatureClass:
+        static_cast<CSSFontFeatureValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case FunctionClass:
+        static_cast<CSSFunctionValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case LinearGradientClass:
+        static_cast<CSSLinearGradientValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case RadialGradientClass:
+        static_cast<CSSRadialGradientValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case CrossfadeClass:
+        static_cast<CSSCrossfadeValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case ImageClass:
+        static_cast<CSSImageValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case InheritedClass:
+        static_cast<CSSInheritedValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case InitialClass:
+        static_cast<CSSInitialValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case GridLineNamesClass:
+        static_cast<CSSGridLineNamesValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case GridTemplateAreasClass:
+        static_cast<CSSGridTemplateAreasValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case PrimitiveClass:
+        static_cast<CSSPrimitiveValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case ReflectClass:
+        static_cast<CSSReflectValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case ShadowClass:
+        static_cast<CSSShadowValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case CubicBezierTimingFunctionClass:
+        static_cast<CSSCubicBezierTimingFunctionValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case StepsTimingFunctionClass:
+        static_cast<CSSStepsTimingFunctionValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case UnicodeRangeClass:
+        static_cast<CSSUnicodeRangeValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case ValueListClass:
+        static_cast<CSSValueList*>(this)->traceAfterDispatch(visitor);
+        return;
+    case CSSTransformClass:
+        static_cast<CSSTransformValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case LineBoxContainClass:
+        static_cast<CSSLineBoxContainValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case CalculationClass:
+        static_cast<CSSCalcValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case ImageSetClass:
+        static_cast<CSSImageSetValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case CSSFilterClass:
+        static_cast<CSSFilterValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case CSSArrayFunctionValueClass:
+        static_cast<CSSArrayFunctionValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    case SVGColorClass:
+        static_cast<SVGColor*>(this)->traceAfterDispatch(visitor);
+        return;
+    case SVGPaintClass:
+        static_cast<SVGPaint*>(this)->traceAfterDispatch(visitor);
+        return;
+    case CSSSVGDocumentClass:
+        static_cast<CSSSVGDocumentValue*>(this)->traceAfterDispatch(visitor);
+        return;
+    }
+    ASSERT_NOT_REACHED();
+}
+
 PassRefPtr<CSSValue> CSSValue::cloneForCSSOM() const
 {
     switch (classType()) {
@@ -469,8 +638,6 @@
         return toCSSFilterValue(this)->cloneForCSSOM();
     case CSSArrayFunctionValueClass:
         return toCSSArrayFunctionValue(this)->cloneForCSSOM();
-    case CSSMixFunctionValueClass:
-        return toCSSMixFunctionValue(this)->cloneForCSSOM();
     case CSSTransformClass:
         return toCSSTransformValue(this)->cloneForCSSOM();
     case ImageSetClass:
diff --git a/Source/core/css/CSSValue.h b/Source/core/css/CSSValue.h
index e6b21b8..2d6cdff 100644
--- a/Source/core/css/CSSValue.h
+++ b/Source/core/css/CSSValue.h
@@ -22,6 +22,7 @@
 #define CSSValue_h
 
 #include "core/dom/ExceptionCode.h"
+#include "heap/Handle.h"
 #include "platform/weborigin/KURL.h"
 #include "wtf/HashMap.h"
 #include "wtf/ListHashSet.h"
@@ -40,7 +41,8 @@
 // They should be handled by separate wrapper classes.
 
 // Please don't expose more CSSValue types to the web.
-class CSSValue : public RefCounted<CSSValue> {
+class CSSValue : public RefCountedWillBeRefCountedGarbageCollected<CSSValue> {
+    DECLARE_GC_INFO;
 public:
     enum Type {
         CSS_INHERIT = 0,
@@ -53,17 +55,20 @@
 
     // Override RefCounted's deref() to ensure operator delete is called on
     // the appropriate subclass type.
+    // When oilpan is enabled the finalize method is called by the garbage
+    // collector and not immediately when deref reached zero.
+#if !ENABLE(OILPAN)
     void deref()
     {
         if (derefBase())
             destroy();
     }
+#endif // !ENABLE(OILPAN)
 
     Type cssValueType() const;
 
     String cssText() const;
     void setCSSText(const String&, ExceptionState&) { } // FIXME: Not implemented.
-    String serializeResolvingVariables(const HashMap<AtomicString, String>&) const;
 
     bool isPrimitiveValue() const { return m_classType == PrimitiveClass; }
     bool isValueList() const { return m_classType >= ValueListClass; }
@@ -98,10 +103,7 @@
     bool isCalcValue() const {return m_classType == CalculationClass; }
     bool isFilterValue() const { return m_classType == CSSFilterClass; }
     bool isArrayFunctionValue() const { return m_classType == CSSArrayFunctionValueClass; }
-    bool isMixFunctionValue() const { return m_classType == CSSMixFunctionValueClass; }
-    bool isShaderValue() const { return m_classType == CSSShaderClass; }
-    bool isVariableValue() const { return m_classType == VariableClass; }
-    bool isGridTemplateValue() const { return m_classType == GridTemplateClass; }
+    bool isGridTemplateAreasValue() const { return m_classType == GridTemplateAreasClass; }
     bool isSVGColor() const { return m_classType == SVGColorClass || m_classType == SVGPaintClass; }
     bool isSVGPaint() const { return m_classType == SVGPaintClass; }
     bool isSVGDocumentValue() const { return m_classType == CSSSVGDocumentClass; }
@@ -116,12 +118,14 @@
 
     PassRefPtr<CSSValue> cloneForCSSOM() const;
 
-    void addSubresourceStyleURLs(ListHashSet<KURL>&, const StyleSheetContents*) const;
-
     bool hasFailedOrCanceledSubresources() const;
 
     bool equals(const CSSValue&) const;
 
+    void finalize();
+    void traceAfterDispatch(Visitor*) { }
+    void trace(Visitor*);
+
 protected:
 
     static const size_t ClassTypeBits = 6;
@@ -158,9 +162,7 @@
         UnicodeRangeClass,
         LineBoxContainClass,
         CalculationClass,
-        CSSShaderClass,
-        VariableClass,
-        GridTemplateClass,
+        GridTemplateAreasClass,
 
         // SVG classes.
         SVGColorClass,
@@ -172,7 +174,6 @@
         ImageSetClass,
         CSSFilterClass,
         CSSArrayFunctionValueClass,
-        CSSMixFunctionValueClass,
         CSSTransformClass,
         GridLineNamesClass,
         // Do not append non-list class types here.
@@ -246,6 +247,18 @@
     return first ? second && first->equals(*second) : !second;
 }
 
+template<typename CSSValueType>
+inline bool compareCSSValuePtr(const RawPtr<CSSValueType>& first, const RawPtr<CSSValueType>& second)
+{
+    return first ? second && first->equals(*second) : !second;
+}
+
+template<typename CSSValueType>
+inline bool compareCSSValuePtr(const Member<CSSValueType>& first, const Member<CSSValueType>& second)
+{
+    return first ? second && first->equals(*second) : !second;
+}
+
 #define DEFINE_CSS_VALUE_TYPE_CASTS(thisType, predicate) \
     DEFINE_TYPE_CASTS(thisType, CSSValue, value, value->predicate, value.predicate)
 
diff --git a/Source/core/css/CSSValueKeywords.in b/Source/core/css/CSSValueKeywords.in
index 5ef30f8..eb6235f 100644
--- a/Source/core/css/CSSValueKeywords.in
+++ b/Source/core/css/CSSValueKeywords.in
@@ -52,7 +52,7 @@
 //normal
 small-caps
 
-// -webkit-font-variant-ligatures:
+// font-variant-ligatures:
 //
 // normal
 common-ligatures
@@ -663,17 +663,12 @@
 media-mute-button
 media-play-button
 media-overlay-play-button
-media-seek-back-button
-media-seek-forward-button
-media-rewind-button
-media-return-to-realtime-button
 media-toggle-closed-captions-button
 media-slider
 media-sliderthumb
 media-volume-slider-container
 media-volume-slider
 media-volume-sliderthumb
-media-volume-slider-mute-button
 media-controls-background
 media-controls-fullscreen-background
 media-current-time-display
@@ -916,10 +911,9 @@
 nonzero
 evenodd
 outside-shape
-
-// -webkit-region-fragment
-// auto
-break
+at
+// closest-side
+// farthest-side
 
 // -webkit-wrap-flow
 // auto
@@ -933,9 +927,6 @@
 wrap
 // none
 
-// -webkit-line-align
-edges
-
 alphabetic
 
 // position
@@ -1013,3 +1004,27 @@
 // touch-action-delay
 // none
 script
+
+// touch-action
+pan-x
+pan-y
+
+// justify-self
+// auto
+// stretch
+// baseline
+// center
+// start
+// end
+self-start
+self-end
+// flex-start
+// flex-end
+// left
+// right
+true
+safe
+
+// scroll-behavior
+instant
+smooth
diff --git a/Source/core/css/CSSValueList.cpp b/Source/core/css/CSSValueList.cpp
index e1505c2..9c0a989 100644
--- a/Source/core/css/CSSValueList.cpp
+++ b/Source/core/css/CSSValueList.cpp
@@ -73,9 +73,9 @@
     return false;
 }
 
-PassRefPtr<CSSValueList> CSSValueList::copy()
+PassRefPtrWillBeRawPtr<CSSValueList> CSSValueList::copy()
 {
-    RefPtr<CSSValueList> newList;
+    RefPtrWillBeRawPtr<CSSValueList> newList;
     switch (m_valueListSeparator) {
     case SpaceSeparator:
         newList = createSpaceSeparated();
@@ -129,8 +129,7 @@
 {
     // FIXME: the explicit Vector conversion copies into a temporary and is
     // wasteful.
-    return m_valueListSeparator == other.m_valueListSeparator && compareCSSValueVector<CSSValue>(Vector<RefPtr<CSSValue> >(m_values), Vector<RefPtr<CSSValue> >(other.m_values));
-}
+    return m_valueListSeparator == other.m_valueListSeparator && compareCSSValueVector<CSSValue>(Vector<RefPtr<CSSValue> >(m_values), Vector<RefPtr<CSSValue> >(other.m_values));}
 
 bool CSSValueList::equals(const CSSValue& other) const
 {
@@ -141,41 +140,6 @@
     return value && value->equals(other);
 }
 
-String CSSValueList::customSerializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-{
-    StringBuilder result;
-    String separator;
-    switch (m_valueListSeparator) {
-    case SpaceSeparator:
-        separator = " ";
-        break;
-    case CommaSeparator:
-        separator = ", ";
-        break;
-    case SlashSeparator:
-        separator = " / ";
-        break;
-    default:
-        ASSERT_NOT_REACHED();
-    }
-
-    unsigned size = m_values.size();
-    for (unsigned i = 0; i < size; i++) {
-        if (!result.isEmpty())
-            result.append(separator);
-        result.append(m_values[i]->serializeResolvingVariables(variables));
-    }
-
-    return result.toString();
-}
-
-void CSSValueList::addSubresourceStyleURLs(ListHashSet<KURL>& urls, const StyleSheetContents* styleSheet) const
-{
-    size_t size = m_values.size();
-    for (size_t i = 0; i < size; ++i)
-        m_values[i]->addSubresourceStyleURLs(urls, styleSheet);
-}
-
 bool CSSValueList::hasFailedOrCanceledSubresources() const
 {
     for (unsigned i = 0; i < m_values.size(); ++i) {
@@ -194,9 +158,14 @@
         m_values[i] = cloneFrom.m_values[i]->cloneForCSSOM();
 }
 
-PassRefPtr<CSSValueList> CSSValueList::cloneForCSSOM() const
+PassRefPtrWillBeRawPtr<CSSValueList> CSSValueList::cloneForCSSOM() const
 {
-    return adoptRef(new CSSValueList(*this));
+    return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSValueList(*this));
+}
+
+void CSSValueList::traceAfterDispatch(Visitor* visitor)
+{
+    CSSValue::traceAfterDispatch(visitor);
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSValueList.h b/Source/core/css/CSSValueList.h
index 2f08014..9ce1e53 100644
--- a/Source/core/css/CSSValueList.h
+++ b/Source/core/css/CSSValueList.h
@@ -31,21 +31,21 @@
 
 class CSSValueList : public CSSValue {
 public:
-    static PassRefPtr<CSSValueList> createCommaSeparated()
+    static PassRefPtrWillBeRawPtr<CSSValueList> createCommaSeparated()
     {
-        return adoptRef(new CSSValueList(CommaSeparator));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSValueList(CommaSeparator));
     }
-    static PassRefPtr<CSSValueList> createSpaceSeparated()
+    static PassRefPtrWillBeRawPtr<CSSValueList> createSpaceSeparated()
     {
-        return adoptRef(new CSSValueList(SpaceSeparator));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSValueList(SpaceSeparator));
     }
-    static PassRefPtr<CSSValueList> createSlashSeparated()
+    static PassRefPtrWillBeRawPtr<CSSValueList> createSlashSeparated()
     {
-        return adoptRef(new CSSValueList(SlashSeparator));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSValueList(SlashSeparator));
     }
-    static PassRefPtr<CSSValueList> createFromParserValueList(CSSParserValueList* list)
+    static PassRefPtrWillBeRawPtr<CSSValueList> createFromParserValueList(CSSParserValueList* list)
     {
-        return adoptRef(new CSSValueList(list));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new CSSValueList(list));
     }
 
     size_t length() const { return m_values.size(); }
@@ -57,18 +57,17 @@
     void prepend(PassRefPtr<CSSValue> value) { m_values.prepend(value); }
     bool removeAll(CSSValue*);
     bool hasValue(CSSValue*) const;
-    PassRefPtr<CSSValueList> copy();
+    PassRefPtrWillBeRawPtr<CSSValueList> copy();
 
     String customCSSText(CSSTextFormattingFlags = QuoteCSSStringIfNeeded) const;
     bool equals(const CSSValueList&) const;
     bool equals(const CSSValue&) const;
-    String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
-
-    void addSubresourceStyleURLs(ListHashSet<KURL>&, const StyleSheetContents*) const;
 
     bool hasFailedOrCanceledSubresources() const;
 
-    PassRefPtr<CSSValueList> cloneForCSSOM() const;
+    PassRefPtrWillBeRawPtr<CSSValueList> cloneForCSSOM() const;
+
+    void traceAfterDispatch(Visitor*);
 
 protected:
     CSSValueList(ClassType, ValueListSeparator);
diff --git a/Source/core/css/CSSValuePool.cpp b/Source/core/css/CSSValuePool.cpp
index 4550915..4e6e9f2 100644
--- a/Source/core/css/CSSValuePool.cpp
+++ b/Source/core/css/CSSValuePool.cpp
@@ -26,16 +26,23 @@
 #include "config.h"
 #include "core/css/CSSValuePool.h"
 
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSValueList.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
 
+DEFINE_GC_INFO(CSSValuePool);
+
 CSSValuePool& cssValuePool()
 {
+#if ENABLE(OILPAN)
+    DEFINE_STATIC_LOCAL(Persistent<CSSValuePool>, pool, (new CSSValuePool()));
+    return *pool;
+#else
     DEFINE_STATIC_LOCAL(CSSValuePool, pool, ());
     return pool;
+#endif // ENABLE(OILPAN)
 }
 
 CSSValuePool::CSSValuePool()
@@ -46,9 +53,13 @@
     , m_colorWhite(CSSPrimitiveValue::createColor(Color::white))
     , m_colorBlack(CSSPrimitiveValue::createColor(Color::black))
 {
+    m_identifierValueCache.resize(numCSSValueKeywords);
+    m_pixelValueCache.resize(maximumCacheableIntegerValue + 1);
+    m_percentValueCache.resize(maximumCacheableIntegerValue + 1);
+    m_numberValueCache.resize(maximumCacheableIntegerValue + 1);
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSValuePool::createIdentifierValue(CSSValueID ident)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> CSSValuePool::createIdentifierValue(CSSValueID ident)
 {
     if (ident <= 0)
         return CSSPrimitiveValue::createIdentifier(ident);
@@ -58,12 +69,12 @@
     return m_identifierValueCache[ident];
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSValuePool::createIdentifierValue(CSSPropertyID ident)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> CSSValuePool::createIdentifierValue(CSSPropertyID ident)
 {
     return CSSPrimitiveValue::createIdentifier(ident);
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSValuePool::createColorValue(unsigned rgbValue)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> CSSValuePool::createColorValue(unsigned rgbValue)
 {
     // These are the empty and deleted values of the hash table.
     if (rgbValue == Color::transparent)
@@ -79,14 +90,14 @@
     if (m_colorValueCache.size() > maximumColorCacheSize)
         m_colorValueCache.clear();
 
-    RefPtr<CSSPrimitiveValue> dummyValue;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> dummyValue;
     ColorValueCache::AddResult entry = m_colorValueCache.add(rgbValue, dummyValue);
     if (entry.isNewEntry)
-        entry.iterator->value = CSSPrimitiveValue::createColor(rgbValue);
-    return entry.iterator->value;
+        entry.storedValue->value = CSSPrimitiveValue::createColor(rgbValue);
+    return entry.storedValue->value;
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSValuePool::createValue(double value, CSSPrimitiveValue::UnitTypes type)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> CSSValuePool::createValue(double value, CSSPrimitiveValue::UnitTypes type)
 {
     if (value < 0 || value > maximumCacheableIntegerValue)
         return CSSPrimitiveValue::create(value, type);
@@ -95,50 +106,65 @@
     if (value != intValue)
         return CSSPrimitiveValue::create(value, type);
 
-    RefPtr<CSSPrimitiveValue>* cache;
     switch (type) {
     case CSSPrimitiveValue::CSS_PX:
-        cache = m_pixelValueCache;
-        break;
+        if (!m_pixelValueCache[intValue])
+            m_pixelValueCache[intValue] = CSSPrimitiveValue::create(value, type);
+        return m_pixelValueCache[intValue];
     case CSSPrimitiveValue::CSS_PERCENTAGE:
-        cache = m_percentValueCache;
-        break;
+        if (!m_percentValueCache[intValue])
+            m_percentValueCache[intValue] = CSSPrimitiveValue::create(value, type);
+        return m_percentValueCache[intValue];
     case CSSPrimitiveValue::CSS_NUMBER:
-        cache = m_numberValueCache;
-        break;
+        if (!m_numberValueCache[intValue])
+            m_numberValueCache[intValue] = CSSPrimitiveValue::create(value, type);
+        return m_numberValueCache[intValue];
     default:
         return CSSPrimitiveValue::create(value, type);
     }
-
-    if (!cache[intValue])
-        cache[intValue] = CSSPrimitiveValue::create(value, type);
-    return cache[intValue];
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSValuePool::createValue(const Length& value, const RenderStyle& style)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> CSSValuePool::createValue(const Length& value, const RenderStyle& style)
 {
     return CSSPrimitiveValue::create(value, style.effectiveZoom());
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSValuePool::createFontFamilyValue(const String& familyName)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> CSSValuePool::createFontFamilyValue(const String& familyName)
 {
-    RefPtr<CSSPrimitiveValue>& value = m_fontFamilyValueCache.add(familyName, 0).iterator->value;
+    RefPtrWillBeMember<CSSPrimitiveValue>& value = m_fontFamilyValueCache.add(familyName, 0).storedValue->value;
     if (!value)
         value = CSSPrimitiveValue::create(familyName, CSSPrimitiveValue::CSS_STRING);
     return value;
 }
 
-PassRefPtr<CSSValueList> CSSValuePool::createFontFaceValue(const AtomicString& string)
+PassRefPtrWillBeRawPtr<CSSValueList> CSSValuePool::createFontFaceValue(const AtomicString& string)
 {
     // Just wipe out the cache and start rebuilding if it gets too big.
     const unsigned maximumFontFaceCacheSize = 128;
     if (m_fontFaceValueCache.size() > maximumFontFaceCacheSize)
         m_fontFaceValueCache.clear();
 
-    RefPtr<CSSValueList>& value = m_fontFaceValueCache.add(string, 0).iterator->value;
+    RefPtrWillBeMember<CSSValueList>& value = m_fontFaceValueCache.add(string, 0).storedValue->value;
     if (!value)
-        value = CSSParser::parseFontFaceValue(string);
+        value = BisonCSSParser::parseFontFaceValue(string);
     return value;
 }
 
+void CSSValuePool::trace(Visitor* visitor)
+{
+    visitor->trace(m_inheritedValue);
+    visitor->trace(m_implicitInitialValue);
+    visitor->trace(m_explicitInitialValue);
+    visitor->trace(m_identifierValueCache);
+    visitor->trace(m_colorValueCache);
+    visitor->trace(m_colorTransparent);
+    visitor->trace(m_colorWhite);
+    visitor->trace(m_colorBlack);
+    visitor->trace(m_pixelValueCache);
+    visitor->trace(m_percentValueCache);
+    visitor->trace(m_numberValueCache);
+    visitor->trace(m_fontFaceValueCache);
+    visitor->trace(m_fontFamilyValueCache);
+}
+
 }
diff --git a/Source/core/css/CSSValuePool.h b/Source/core/css/CSSValuePool.h
index 75b8984..9ed7f39 100644
--- a/Source/core/css/CSSValuePool.h
+++ b/Source/core/css/CSSValuePool.h
@@ -39,48 +39,51 @@
 
 class CSSValueList;
 
-class CSSValuePool {
-    WTF_MAKE_FAST_ALLOCATED;
+class CSSValuePool :  public NoBaseWillBeGarbageCollected<CSSValuePool> {
+    DECLARE_GC_INFO;
+    WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
 public:
-    PassRefPtr<CSSValueList> createFontFaceValue(const AtomicString&);
-    PassRefPtr<CSSPrimitiveValue> createFontFamilyValue(const String&);
-    PassRefPtr<CSSInheritedValue> createInheritedValue() { return m_inheritedValue; }
-    PassRefPtr<CSSInitialValue> createImplicitInitialValue() { return m_implicitInitialValue; }
-    PassRefPtr<CSSInitialValue> createExplicitInitialValue() { return m_explicitInitialValue; }
-    PassRefPtr<CSSPrimitiveValue> createIdentifierValue(CSSValueID identifier);
-    PassRefPtr<CSSPrimitiveValue> createIdentifierValue(CSSPropertyID identifier);
-    PassRefPtr<CSSPrimitiveValue> createColorValue(unsigned rgbValue);
-    PassRefPtr<CSSPrimitiveValue> createValue(double value, CSSPrimitiveValue::UnitTypes);
-    PassRefPtr<CSSPrimitiveValue> createValue(const String& value, CSSPrimitiveValue::UnitTypes type) { return CSSPrimitiveValue::create(value, type); }
-    PassRefPtr<CSSPrimitiveValue> createValue(const Length& value, const RenderStyle&);
-    PassRefPtr<CSSPrimitiveValue> createValue(const Length& value, float zoom) { return CSSPrimitiveValue::create(value, zoom); }
-    template<typename T> static PassRefPtr<CSSPrimitiveValue> createValue(T value) { return CSSPrimitiveValue::create(value); }
+    PassRefPtrWillBeRawPtr<CSSValueList> createFontFaceValue(const AtomicString&);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createFontFamilyValue(const String&);
+    PassRefPtrWillBeRawPtr<CSSInheritedValue> createInheritedValue() { return m_inheritedValue; }
+    PassRefPtrWillBeRawPtr<CSSInitialValue> createImplicitInitialValue() { return m_implicitInitialValue; }
+    PassRefPtrWillBeRawPtr<CSSInitialValue> createExplicitInitialValue() { return m_explicitInitialValue; }
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createIdentifierValue(CSSValueID identifier);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createIdentifierValue(CSSPropertyID identifier);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createColorValue(unsigned rgbValue);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createValue(double value, CSSPrimitiveValue::UnitTypes);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createValue(const String& value, CSSPrimitiveValue::UnitTypes type) { return CSSPrimitiveValue::create(value, type); }
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createValue(const Length& value, const RenderStyle&);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createValue(const Length& value, float zoom) { return CSSPrimitiveValue::create(value, zoom); }
+    template<typename T> static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createValue(T value) { return CSSPrimitiveValue::create(value); }
+
+    void trace(Visitor*);
 
 private:
     CSSValuePool();
 
-    RefPtr<CSSInheritedValue> m_inheritedValue;
-    RefPtr<CSSInitialValue> m_implicitInitialValue;
-    RefPtr<CSSInitialValue> m_explicitInitialValue;
+    RefPtrWillBeMember<CSSInheritedValue> m_inheritedValue;
+    RefPtrWillBeMember<CSSInitialValue> m_implicitInitialValue;
+    RefPtrWillBeMember<CSSInitialValue> m_explicitInitialValue;
 
-    RefPtr<CSSPrimitiveValue> m_identifierValueCache[numCSSValueKeywords];
+    WillBeHeapVector<RefPtrWillBeMember<CSSPrimitiveValue>, numCSSValueKeywords> m_identifierValueCache;
 
-    typedef HashMap<unsigned, RefPtr<CSSPrimitiveValue> > ColorValueCache;
+    typedef WillBeHeapHashMap<unsigned, RefPtrWillBeMember<CSSPrimitiveValue> > ColorValueCache;
     ColorValueCache m_colorValueCache;
-    RefPtr<CSSPrimitiveValue> m_colorTransparent;
-    RefPtr<CSSPrimitiveValue> m_colorWhite;
-    RefPtr<CSSPrimitiveValue> m_colorBlack;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_colorTransparent;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_colorWhite;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_colorBlack;
 
     static const int maximumCacheableIntegerValue = 255;
 
-    RefPtr<CSSPrimitiveValue> m_pixelValueCache[maximumCacheableIntegerValue + 1];
-    RefPtr<CSSPrimitiveValue> m_percentValueCache[maximumCacheableIntegerValue + 1];
-    RefPtr<CSSPrimitiveValue> m_numberValueCache[maximumCacheableIntegerValue + 1];
+    WillBeHeapVector<RefPtrWillBeMember<CSSPrimitiveValue>, maximumCacheableIntegerValue + 1> m_pixelValueCache;
+    WillBeHeapVector<RefPtrWillBeMember<CSSPrimitiveValue>, maximumCacheableIntegerValue + 1> m_percentValueCache;
+    WillBeHeapVector<RefPtrWillBeMember<CSSPrimitiveValue>, maximumCacheableIntegerValue + 1> m_numberValueCache;
 
-    typedef HashMap<AtomicString, RefPtr<CSSValueList> > FontFaceValueCache;
+    typedef WillBeHeapHashMap<AtomicString, RefPtrWillBeMember<CSSValueList> > FontFaceValueCache;
     FontFaceValueCache m_fontFaceValueCache;
 
-    typedef HashMap<String, RefPtr<CSSPrimitiveValue> > FontFamilyValueCache;
+    typedef WillBeHeapHashMap<String, RefPtrWillBeMember<CSSPrimitiveValue> > FontFamilyValueCache;
     FontFamilyValueCache m_fontFamilyValueCache;
 
     friend CSSValuePool& cssValuePool();
diff --git a/Source/core/css/CSSVariableValue.h b/Source/core/css/CSSVariableValue.h
deleted file mode 100644
index 525581a..0000000
--- a/Source/core/css/CSSVariableValue.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef CSSVariableValue_h
-#define CSSVariableValue_h
-
-#include "CSSPropertyNames.h"
-#include "core/css/CSSParserValues.h"
-#include "core/css/CSSValue.h"
-
-namespace WebCore {
-
-class CSSVariableValue : public CSSValue {
-public:
-    static PassRefPtr<CSSVariableValue> create(const AtomicString& name, const String& value)
-    {
-        return adoptRef(new CSSVariableValue(name, value));
-    }
-
-    const AtomicString& name() const { return m_name; }
-    const String& value() const { return m_value; }
-
-    bool equals(const CSSVariableValue& other) const { return m_name == other.m_name && m_value == other.m_value; }
-
-private:
-    CSSVariableValue(const AtomicString& name, const String& value)
-        : CSSValue(VariableClass)
-        , m_name(name)
-        , m_value(value)
-    {
-    }
-
-    const AtomicString m_name;
-    const String m_value;
-};
-
-DEFINE_CSS_VALUE_TYPE_CASTS(CSSVariableValue, isVariableValue());
-
-}
-
-#endif /* CSSVariableValue_h */
diff --git a/Source/core/css/CSSVariablesIterator.h b/Source/core/css/CSSVariablesIterator.h
deleted file mode 100644
index edfe3a7..0000000
--- a/Source/core/css/CSSVariablesIterator.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef CSSVariablesIterator_h
-#define CSSVariablesIterator_h
-
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class CSSVariablesIterator : public RefCounted<CSSVariablesIterator> {
-public:
-    virtual ~CSSVariablesIterator() { }
-    virtual void advance() = 0;
-    virtual bool atEnd() const = 0;
-    virtual AtomicString name() const = 0;
-    virtual String value() const = 0;
-    virtual void addedVariable(const AtomicString& name) { }
-    virtual void removedVariable(const AtomicString& name) { }
-    virtual void clearedVariables() { }
-};
-
-}
-
-#endif // CSSVariablesIterator_h
diff --git a/Source/core/css/CSSVariablesMap.cpp b/Source/core/css/CSSVariablesMap.cpp
deleted file mode 100644
index eb6232d..0000000
--- a/Source/core/css/CSSVariablesMap.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-#include "core/css/CSSVariablesMap.h"
-
-#include "core/css/CSSStyleDeclaration.h"
-
-namespace WebCore {
-
-unsigned CSSVariablesMap::size() const
-{
-    if (m_styleDeclaration)
-        return m_styleDeclaration->variableCount();
-    return 0;
-}
-
-String CSSVariablesMap::get(const AtomicString& name) const
-{
-    if (m_styleDeclaration)
-        return m_styleDeclaration->variableValue(name);
-    return String();
-}
-
-bool CSSVariablesMap::has(const AtomicString& name) const
-{
-    if (m_styleDeclaration)
-        return !get(name).isEmpty();
-    return false;
-}
-
-void CSSVariablesMap::set(const AtomicString& name, const String& value, ExceptionState& exceptionState)
-{
-    if (!m_styleDeclaration)
-        return;
-    if (m_styleDeclaration->setVariableValue(name, value, exceptionState)) {
-        Iterators::iterator end = m_activeIterators.end();
-        for (Iterators::iterator it = m_activeIterators.begin(); it != end; ++it)
-            (*it)->addedVariable(name);
-    }
-}
-
-bool CSSVariablesMap::remove(const AtomicString& name)
-{
-    if (!m_styleDeclaration)
-        return false;
-    if (m_styleDeclaration->removeVariable(name)) {
-        Iterators::iterator end = m_activeIterators.end();
-        for (Iterators::iterator it = m_activeIterators.begin(); it != end; ++it)
-            (*it)->removedVariable(name);
-        return true;
-    }
-    return false;
-}
-
-void CSSVariablesMap::clear(ExceptionState& exceptionState)
-{
-    if (!m_styleDeclaration)
-        return;
-    if (m_styleDeclaration->clearVariables(exceptionState)) {
-        Iterators::iterator end = m_activeIterators.end();
-        for (Iterators::iterator it = m_activeIterators.begin(); it != end; ++it)
-            (*it)->clearedVariables();
-    }
-}
-
-void CSSVariablesMap::forEach(PassOwnPtr<CSSVariablesMapForEachCallback> callback, ScriptValue& thisArg) const
-{
-    forEach(callback, &thisArg);
-}
-
-void CSSVariablesMap::forEach(PassOwnPtr<CSSVariablesMapForEachCallback> callback) const
-{
-    forEach(callback, 0);
-}
-
-void CSSVariablesMap::forEach(PassOwnPtr<CSSVariablesMapForEachCallback> callback, ScriptValue* thisArg) const
-{
-    if (!m_styleDeclaration)
-        return;
-    RefPtr<CSSVariablesIterator> iterator = m_styleDeclaration->variablesIterator();
-    m_activeIterators.append(iterator.get());
-    while (!iterator->atEnd()) {
-        String name = iterator->name();
-        String value = iterator->value();
-        if (thisArg)
-            callback->handleItem(*thisArg, value, name, const_cast<CSSVariablesMap*>(this));
-        else
-            callback->handleItem(value, name, const_cast<CSSVariablesMap*>(this));
-        iterator->advance();
-    }
-    ASSERT(m_activeIterators.last() == iterator.get());
-    m_activeIterators.removeLast();
-}
-
-} // namespace WebCore
diff --git a/Source/core/css/CSSVariablesMap.h b/Source/core/css/CSSVariablesMap.h
deleted file mode 100644
index 12b1bee..0000000
--- a/Source/core/css/CSSVariablesMap.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef CSSVariablesMap_h
-#define CSSVariablesMap_h
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/css/CSSVariablesMapForEachCallback.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class CSSStyleDeclaration;
-class CSSVariablesIterator;
-class ExceptionState;
-
-class CSSVariablesMap FINAL : public RefCounted<CSSVariablesMap> {
-public:
-    static PassRefPtr<CSSVariablesMap> create(CSSStyleDeclaration* styleDeclaration)
-    {
-        return adoptRef(new CSSVariablesMap(styleDeclaration));
-    }
-
-    unsigned size() const;
-    String get(const AtomicString& name) const;
-    bool has(const AtomicString& name) const;
-    void set(const AtomicString& name, const String& value, ExceptionState&);
-    bool remove(const AtomicString& name);
-    void clear(ExceptionState&);
-    void forEach(PassOwnPtr<CSSVariablesMapForEachCallback>, ScriptValue& thisArg) const;
-    void forEach(PassOwnPtr<CSSVariablesMapForEachCallback>) const;
-
-    void clearStyleDeclaration() { m_styleDeclaration = 0; }
-
-private:
-    explicit CSSVariablesMap(CSSStyleDeclaration* styleDeclaration)
-        : m_styleDeclaration(styleDeclaration)
-    {
-        ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    }
-
-    void forEach(PassOwnPtr<CSSVariablesMapForEachCallback>, ScriptValue* thisArg) const;
-
-    CSSStyleDeclaration* m_styleDeclaration;
-    typedef Vector<CSSVariablesIterator*> Iterators;
-    mutable Iterators m_activeIterators;
-};
-
-} // namespace WebCore
-
-#endif // CSSVariablesMap_h
diff --git a/Source/core/css/CSSVariablesMap.idl b/Source/core/css/CSSVariablesMap.idl
deleted file mode 100644
index 3c88025..0000000
--- a/Source/core/css/CSSVariablesMap.idl
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-interface CSSVariablesMap {
-    readonly attribute unsigned long size;
-    DOMString get(DOMString name);
-    boolean has(DOMString name);
-    [RaisesException] void set(DOMString name, DOMString value);
-    [ImplementedAs=remove] boolean delete(DOMString name);
-    [RaisesException] void clear();
-    void forEach(CSSVariablesMapForEachCallback callback, optional any thisArg);
-};
diff --git a/Source/core/css/CSSVariablesMapForEachCallback.h b/Source/core/css/CSSVariablesMapForEachCallback.h
deleted file mode 100644
index 4a6f884..0000000
--- a/Source/core/css/CSSVariablesMapForEachCallback.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef CSSVariablesMapForEachCallback_h
-#define CSSVariablesMapForEachCallback_h
-
-#include "bindings/v8/ScriptValue.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class CSSVariablesMap;
-
-class CSSVariablesMapForEachCallback {
-public:
-    virtual ~CSSVariablesMapForEachCallback() { }
-    virtual bool handleItem(ScriptValue thisValue, const String& value, const String& name, CSSVariablesMap*) = 0;
-    virtual bool handleItem(const String& value, const String& name, CSSVariablesMap*) = 0;
-};
-
-} // namespace WebCore
-
-#endif // CSSVariablesMapForEachCallback_h
diff --git a/Source/core/css/CSSVariablesMapForEachCallback.idl b/Source/core/css/CSSVariablesMapForEachCallback.idl
deleted file mode 100644
index d66eb61..0000000
--- a/Source/core/css/CSSVariablesMapForEachCallback.idl
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-callback interface CSSVariablesMapForEachCallback {
-    [CallWith=ThisValue] boolean handleItem(DOMString value, DOMString name, CSSVariablesMap map);
-    boolean handleItem(DOMString value, DOMString name, CSSVariablesMap map);
-};
diff --git a/Source/core/css/CSSViewportRule.h b/Source/core/css/CSSViewportRule.h
index 2ef8c81..50cd88a 100644
--- a/Source/core/css/CSSViewportRule.h
+++ b/Source/core/css/CSSViewportRule.h
@@ -39,13 +39,13 @@
 class StyleRuleViewport;
 class StyleRuleCSSStyleDeclaration;
 
-class CSSViewportRule: public CSSRule {
+class CSSViewportRule FINAL: public CSSRule {
 public:
     static PassRefPtr<CSSViewportRule> create(StyleRuleViewport* viewportRule, CSSStyleSheet* sheet)
     {
         return adoptRef(new CSSViewportRule(viewportRule, sheet));
     }
-    ~CSSViewportRule();
+    virtual ~CSSViewportRule();
 
     virtual CSSRule::Type type() const OVERRIDE { return VIEWPORT_RULE; }
     virtual String cssText() const OVERRIDE;
diff --git a/Source/core/css/Counter.cpp b/Source/core/css/Counter.cpp
new file mode 100644
index 0000000..4e27e48
--- /dev/null
+++ b/Source/core/css/Counter.cpp
@@ -0,0 +1,19 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/css/Counter.h"
+
+namespace WebCore {
+
+DEFINE_GC_INFO(Counter);
+
+void Counter::trace(Visitor* visitor)
+{
+    visitor->trace(m_identifier);
+    visitor->trace(m_listStyle);
+    visitor->trace(m_separator);
+}
+
+}
diff --git a/Source/core/css/Counter.h b/Source/core/css/Counter.h
index cb73a3d..d27ff18 100644
--- a/Source/core/css/Counter.h
+++ b/Source/core/css/Counter.h
@@ -26,11 +26,12 @@
 
 namespace WebCore {
 
-class Counter : public RefCounted<Counter> {
+class Counter : public RefCountedWillBeGarbageCollected<Counter> {
+    DECLARE_GC_INFO;
 public:
-    static PassRefPtr<Counter> create(PassRefPtr<CSSPrimitiveValue> identifier, PassRefPtr<CSSPrimitiveValue> listStyle, PassRefPtr<CSSPrimitiveValue> separator)
+    static PassRefPtrWillBeRawPtr<Counter> create(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> identifier, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> listStyle, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> separator)
     {
-        return adoptRef(new Counter(identifier, listStyle, separator));
+        return adoptRefWillBeNoop(new Counter(identifier, listStyle, separator));
     }
 
     String identifier() const { return m_identifier ? m_identifier->getStringValue() : String(); }
@@ -39,9 +40,9 @@
 
     CSSValueID listStyleIdent() const { return m_listStyle ? m_listStyle->getValueID() : CSSValueInvalid; }
 
-    void setIdentifier(PassRefPtr<CSSPrimitiveValue> identifier) { m_identifier = identifier; }
-    void setListStyle(PassRefPtr<CSSPrimitiveValue> listStyle) { m_listStyle = listStyle; }
-    void setSeparator(PassRefPtr<CSSPrimitiveValue> separator) { m_separator = separator; }
+    void setIdentifier(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> identifier) { m_identifier = identifier; }
+    void setListStyle(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> listStyle) { m_listStyle = listStyle; }
+    void setSeparator(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> separator) { m_separator = separator; }
 
     bool equals(const Counter& other) const
     {
@@ -50,24 +51,26 @@
             && separator() == other.separator();
     }
 
-    PassRefPtr<Counter> cloneForCSSOM() const
+    PassRefPtrWillBeRawPtr<Counter> cloneForCSSOM() const
     {
         return create(m_identifier ? m_identifier->cloneForCSSOM() : 0
             , m_listStyle ? m_listStyle->cloneForCSSOM() : 0
             , m_separator ? m_separator->cloneForCSSOM() : 0);
     }
 
+    void trace(Visitor*);
+
 private:
-    Counter(PassRefPtr<CSSPrimitiveValue> identifier, PassRefPtr<CSSPrimitiveValue> listStyle, PassRefPtr<CSSPrimitiveValue> separator)
+    Counter(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> identifier, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> listStyle, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> separator)
         : m_identifier(identifier)
         , m_listStyle(listStyle)
         , m_separator(separator)
     {
     }
 
-    RefPtr<CSSPrimitiveValue> m_identifier; // string
-    RefPtr<CSSPrimitiveValue> m_listStyle; // ident
-    RefPtr<CSSPrimitiveValue> m_separator; // string
+    RefPtrWillBeMember<CSSPrimitiveValue> m_identifier; // string
+    RefPtrWillBeMember<CSSPrimitiveValue> m_listStyle; // ident
+    RefPtrWillBeMember<CSSPrimitiveValue> m_separator; // string
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/Counter.idl b/Source/core/css/Counter.idl
index 7006aa5..886436e 100644
--- a/Source/core/css/Counter.idl
+++ b/Source/core/css/Counter.idl
@@ -19,6 +19,7 @@
 
 // Introduced in DOM Level 2:
 [
+    WillBeGarbageCollected
 ] interface Counter {
     readonly attribute DOMString identifier;
     readonly attribute DOMString listStyle;
diff --git a/Source/core/css/DOMWindowCSS.cpp b/Source/core/css/DOMWindowCSS.cpp
index 69b7a32..229e127 100644
--- a/Source/core/css/DOMWindowCSS.cpp
+++ b/Source/core/css/DOMWindowCSS.cpp
@@ -30,9 +30,9 @@
 #include "config.h"
 #include "core/css/DOMWindowCSS.h"
 
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
+#include "core/css/RuntimeCSSEnabled.h"
 #include "core/css/StylePropertySet.h"
-#include "core/page/RuntimeCSSEnabled.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -65,7 +65,7 @@
     if (!RuntimeCSSEnabled::isCSSPropertyEnabled(propertyID))
         return false;
 
-    // CSSParser::parseValue() won't work correctly if !important is present,
+    // BisonCSSParser::parseValue() won't work correctly if !important is present,
     // so just get rid of it. It doesn't matter to supports() if it's actually
     // there or not, provided how it's specified in the value is correct.
     String normalizedValue = value.stripWhiteSpace().simplifyWhiteSpace();
@@ -75,13 +75,13 @@
         return false;
 
     RefPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
-    return CSSParser::parseValue(dummyStyle.get(), propertyID, normalizedValue, false, HTMLStandardMode, 0);
+    return BisonCSSParser::parseValue(dummyStyle.get(), propertyID, normalizedValue, false, HTMLStandardMode, 0);
 }
 
 bool DOMWindowCSS::supports(const String& conditionText) const
 {
-    CSSParserContext context(HTMLStandardMode);
-    CSSParser parser(context);
+    CSSParserContext context(HTMLStandardMode, 0);
+    BisonCSSParser parser(context);
     return parser.parseSupportsCondition(conditionText);
 }
 
diff --git a/Source/core/css/DocumentFontFaceSet.idl b/Source/core/css/DocumentFontFaceSet.idl
index 820fdc8..fc2cbc7 100644
--- a/Source/core/css/DocumentFontFaceSet.idl
+++ b/Source/core/css/DocumentFontFaceSet.idl
@@ -28,6 +28,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-partial interface Document {
-    [RuntimeEnabled=FontLoadEvents] readonly attribute FontFaceSet fonts;
+[
+    RuntimeEnabled=FontLoadEvents,
+] partial interface Document {
+    readonly attribute FontFaceSet fonts;
 };
diff --git a/Source/core/css/DragUpdateTest.cpp b/Source/core/css/DragUpdateTest.cpp
new file mode 100644
index 0000000..5542887
--- /dev/null
+++ b/Source/core/css/DragUpdateTest.cpp
@@ -0,0 +1,69 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/dom/Element.h"
+#include "core/frame/FrameView.h"
+#include "core/html/HTMLDocument.h"
+#include "core/html/HTMLElement.h"
+#include "core/testing/DummyPageHolder.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+TEST(DragUpdateTest, AffectedByDragUpdate)
+{
+    // Check that when dragging the div in the document below, you only get a
+    // single element style recalc.
+
+    OwnPtr<DummyPageHolder> dummyPageHolder = DummyPageHolder::create(IntSize(800, 600));
+    HTMLDocument* document = toHTMLDocument(&dummyPageHolder->document());
+    document->documentElement()->setInnerHTML("<style>div {width:100px;height:100px} div:-webkit-drag { background-color: green }</style>"
+        "<div>"
+        "<span></span>"
+        "<span></span>"
+        "<span></span>"
+        "<span></span>"
+        "</div>", ASSERT_NO_EXCEPTION);
+
+    document->view()->updateLayoutAndStyleIfNeededRecursive();
+    unsigned startCount = document->styleEngine()->resolverAccessCount();
+
+    document->documentElement()->renderer()->updateDragState(true);
+    document->view()->updateLayoutAndStyleIfNeededRecursive();
+
+    unsigned accessCount = document->styleEngine()->resolverAccessCount() - startCount;
+
+    ASSERT_EQ(1U, accessCount);
+}
+
+TEST(DragUpdateTest, ChildrenAffectedByDragUpdate)
+{
+    // Check that when dragging the div in the document below, you get a
+    // full subtree style recalc.
+
+    OwnPtr<DummyPageHolder> dummyPageHolder = DummyPageHolder::create(IntSize(800, 600));
+    HTMLDocument* document = toHTMLDocument(&dummyPageHolder->document());
+    document->documentElement()->setInnerHTML("<style>div {width:100px;height:100px} div:-webkit-drag span { background-color: green }</style>"
+        "<div>"
+        "<span></span>"
+        "<span></span>"
+        "<span></span>"
+        "<span></span>"
+        "</div>", ASSERT_NO_EXCEPTION);
+
+    document->updateLayout();
+    unsigned startCount = document->styleEngine()->resolverAccessCount();
+
+    document->documentElement()->renderer()->updateDragState(true);
+    document->updateLayout();
+
+    unsigned accessCount = document->styleEngine()->resolverAccessCount() - startCount;
+
+    ASSERT_EQ(5U, accessCount);
+}
+
+} // namespace
diff --git a/Source/core/css/ElementRuleCollector.cpp b/Source/core/css/ElementRuleCollector.cpp
index 4fdd44c..53bd4fb 100644
--- a/Source/core/css/ElementRuleCollector.cpp
+++ b/Source/core/css/ElementRuleCollector.cpp
@@ -29,31 +29,32 @@
 #include "config.h"
 #include "core/css/ElementRuleCollector.h"
 
+#include "core/css/CSSImportRule.h"
+#include "core/css/CSSKeyframesRule.h"
+#include "core/css/CSSMediaRule.h"
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSStyleRule.h"
 #include "core/css/CSSStyleSheet.h"
+#include "core/css/CSSSupportsRule.h"
 #include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/rendering/RenderRegion.h"
 
 namespace WebCore {
 
 ElementRuleCollector::ElementRuleCollector(const ElementResolveContext& context,
-    const SelectorFilter& filter, RenderStyle* style, ShouldIncludeStyleSheetInCSSOMWrapper includeStyleSheet)
+    const SelectorFilter& filter, RenderStyle* style)
     : m_context(context)
     , m_selectorFilter(filter)
     , m_style(style)
-    , m_regionForStyling(0)
     , m_pseudoStyleRequest(NOPSEUDO)
     , m_mode(SelectorChecker::ResolvingStyle)
     , m_canUseFastReject(m_selectorFilter.parentStackIsConsistent(context.parentNode()))
     , m_sameOriginOnly(false)
     , m_matchingUARules(false)
-    , m_includeStyleSheet(includeStyleSheet)
 { }
 
 ElementRuleCollector::~ElementRuleCollector()
@@ -77,11 +78,11 @@
     return m_cssRuleList.release();
 }
 
-inline void ElementRuleCollector::addMatchedRule(const RuleData* rule, unsigned specificity, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex)
+inline void ElementRuleCollector::addMatchedRule(const RuleData* rule, unsigned specificity, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex, const CSSStyleSheet* parentStyleSheet)
 {
     if (!m_matchedRules)
         m_matchedRules = adoptPtr(new Vector<MatchedRule, 32>);
-    m_matchedRules->append(MatchedRule(rule, specificity, cascadeScope, cascadeOrder, styleSheetIndex));
+    m_matchedRules->append(MatchedRule(rule, specificity, cascadeScope, cascadeOrder, styleSheetIndex, parentStyleSheet));
 }
 
 void ElementRuleCollector::clearMatchedRules()
@@ -131,9 +132,6 @@
     // d) the rules comes from a scoped style sheet within an active shadow root whose host is the given element
     if (element->isInShadowTree() && (behaviorAtBoundary & SelectorChecker::ScopeIsShadowHost) && scopingNode == element->containingShadowRoot()->host())
         return true;
-    // e) the rules can cross boundaries
-    if ((behaviorAtBoundary & SelectorChecker::BoundaryBehaviorMask) == SelectorChecker::CrossesBoundary)
-        return true;
     return false;
 }
 
@@ -146,7 +144,7 @@
     const AtomicString& pseudoId = element.shadowPseudoId();
     if (!pseudoId.isEmpty()) {
         ASSERT(element.isStyledElement());
-        collectMatchingRulesForList(matchRequest.ruleSet->shadowPseudoElementRules(pseudoId.impl()), behaviorAtBoundary, ignoreCascadeScope, cascadeOrder, matchRequest, ruleRange);
+        collectMatchingRulesForList(matchRequest.ruleSet->shadowPseudoElementRules(pseudoId), behaviorAtBoundary, ignoreCascadeScope, cascadeOrder, matchRequest, ruleRange);
     }
 
     if (element.isVTTElement())
@@ -164,65 +162,64 @@
     // We need to collect the rules for id, class, tag, and everything else into a buffer and
     // then sort the buffer.
     if (element.hasID())
-        collectMatchingRulesForList(matchRequest.ruleSet->idRules(element.idForStyleResolution().impl()), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
+        collectMatchingRulesForList(matchRequest.ruleSet->idRules(element.idForStyleResolution()), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
     if (element.isStyledElement() && element.hasClass()) {
         for (size_t i = 0; i < element.classNames().size(); ++i)
-            collectMatchingRulesForList(matchRequest.ruleSet->classRules(element.classNames()[i].impl()), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
+            collectMatchingRulesForList(matchRequest.ruleSet->classRules(element.classNames()[i]), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
     }
 
     if (element.isLink())
         collectMatchingRulesForList(matchRequest.ruleSet->linkPseudoClassRules(), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
     if (SelectorChecker::matchesFocusPseudoClass(element))
         collectMatchingRulesForList(matchRequest.ruleSet->focusPseudoClassRules(), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
-    collectMatchingRulesForList(matchRequest.ruleSet->tagRules(element.localName().impl()), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
+    collectMatchingRulesForList(matchRequest.ruleSet->tagRules(element.localName()), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
     collectMatchingRulesForList(matchRequest.ruleSet->universalRules(), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
 }
 
-void ElementRuleCollector::collectMatchingRulesForRegion(const MatchRequest& matchRequest, RuleRange& ruleRange, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
+CSSRuleList* ElementRuleCollector::nestedRuleList(CSSRule* rule)
 {
-    if (!m_regionForStyling)
-        return;
-
-    unsigned size = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.size();
-    for (unsigned i = 0; i < size; ++i) {
-        const CSSSelector* regionSelector = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.at(i).selector;
-        if (checkRegionSelector(regionSelector, toElement(m_regionForStyling->nodeForRegion()))) {
-            RuleSet* regionRules = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
-            ASSERT(regionRules);
-            collectMatchingRules(MatchRequest(regionRules, matchRequest.includeEmptyRules, matchRequest.scope), ruleRange, behaviorAtBoundary, cascadeScope, cascadeOrder);
-        }
+    switch (rule->type()) {
+    case CSSRule::MEDIA_RULE:
+        return toCSSMediaRule(rule)->cssRules();
+    case CSSRule::KEYFRAMES_RULE:
+        return toCSSKeyframesRule(rule)->cssRules();
+    case CSSRule::SUPPORTS_RULE:
+        return toCSSSupportsRule(rule)->cssRules();
+    default:
+        return 0;
     }
 }
 
-
-static CSSStyleSheet* findStyleSheet(StyleEngine* styleEngine, StyleRule* rule)
+template<class CSSRuleCollection>
+CSSRule* ElementRuleCollector::findStyleRule(CSSRuleCollection* cssRules, StyleRule* styleRule)
 {
-    // FIXME: StyleEngine has a bunch of different accessors for StyleSheet lists, is this the only one we need to care about?
-    const Vector<RefPtr<CSSStyleSheet> >& stylesheets = styleEngine->activeAuthorStyleSheets();
-    for (size_t i = 0; i < stylesheets.size(); ++i) {
-        CSSStyleSheet* sheet = stylesheets[i].get();
-        for (unsigned j = 0; j < sheet->length(); ++j) {
-            CSSRule* cssRule = sheet->item(j);
-            if (cssRule->type() != CSSRule::STYLE_RULE)
-                continue;
+    if (!cssRules)
+        return 0;
+    CSSRule* result = 0;
+    for (unsigned i = 0; i < cssRules->length() && !result; ++i) {
+        CSSRule* cssRule = cssRules->item(i);
+        CSSRule::Type cssRuleType = cssRule->type();
+        if (cssRuleType == CSSRule::STYLE_RULE) {
             CSSStyleRule* cssStyleRule = toCSSStyleRule(cssRule);
-            if (cssStyleRule->styleRule() == rule)
-                return sheet;
+            if (cssStyleRule->styleRule() == styleRule)
+                result = cssRule;
+        } else if (cssRuleType == CSSRule::IMPORT_RULE) {
+            CSSImportRule* cssImportRule = toCSSImportRule(cssRule);
+            result = findStyleRule(cssImportRule->styleSheet(), styleRule);
+        } else {
+            result = findStyleRule(nestedRuleList(cssRule), styleRule);
         }
     }
-    return 0;
+    return result;
 }
 
-void ElementRuleCollector::appendCSSOMWrapperForRule(StyleRule* rule)
+void ElementRuleCollector::appendCSSOMWrapperForRule(CSSStyleSheet* parentStyleSheet, StyleRule* rule)
 {
-    // FIXME: There should be no codepath that creates a CSSOMWrapper without a parent stylesheet or rule because
-    // then that codepath can lead to the CSSStyleSheet contents not getting correctly copied when the rule is modified
-    // through the wrapper (e.g. rule.selectorText="div"). Right now, the inspector uses the pointers for identity though,
-    // so calling CSSStyleSheet->willMutateRules breaks the inspector.
-    CSSStyleSheet* sheet = m_includeStyleSheet == IncludeStyleSheetInCSSOMWrapper ? findStyleSheet(m_context.element()->document().styleEngine(), rule) : 0;
-    RefPtr<CSSRule> cssRule = rule->createCSSOMWrapper(sheet);
-    if (sheet)
-        sheet->registerExtraChildRuleCSSOMWrapper(cssRule);
+    // |parentStyleSheet| is 0 if and only if the |rule| is coming from User Agent. In this case,
+    // it is safe to create CSSOM wrappers without parentStyleSheets as they will be used only
+    // by inspector which will not try to edit them.
+    RefPtr<CSSRule> cssRule = parentStyleSheet ? findStyleRule(parentStyleSheet, rule) : rule->createCSSOMWrapper();
+    ASSERT(!parentStyleSheet || cssRule);
     ensureRuleList()->rules().append(cssRule);
 }
 
@@ -242,7 +239,7 @@
 
     if (m_mode == SelectorChecker::CollectingCSSRules) {
         for (unsigned i = 0; i < matchedRules.size(); ++i)
-            appendCSSOMWrapperForRule(matchedRules[i].ruleData()->rule());
+            appendCSSOMWrapperForRule(const_cast<CSSStyleSheet*>(matchedRules[i].parentStyleSheet()), matchedRules[i].ruleData()->rule());
         return;
     }
 
@@ -271,7 +268,7 @@
             if (!ruleData.hasMultipartSelector())
                 return true;
         }
-        if (ruleData.selector()->m_match == CSSSelector::Tag && !SelectorChecker::tagMatches(*m_context.element(), ruleData.selector()->tagQName()))
+        if (ruleData.selector().m_match == CSSSelector::Tag && !SelectorChecker::tagMatches(*m_context.element(), ruleData.selector().tagQName()))
             return false;
         SelectorCheckerFastPath selectorCheckerFastPath(ruleData.selector(), *m_context.element());
         if (!selectorCheckerFastPath.matchesRightmostAttributeSelector())
@@ -329,7 +326,7 @@
                 ruleRange.firstRuleIndex = ruleRange.lastRuleIndex;
 
             // Add this rule to our list of matched rules.
-            addMatchedRule(&ruleData, result.specificity, cascadeScope, cascadeOrder, matchRequest.styleSheetIndex);
+            addMatchedRule(&ruleData, result.specificity, cascadeScope, cascadeOrder, matchRequest.styleSheetIndex, matchRequest.styleSheet);
             return;
         }
     }
@@ -363,9 +360,6 @@
     if (specificity1 != specificity2)
         return specificity1 < specificity2;
 
-    if (matchedRule1.styleSheetIndex() != matchedRule2.styleSheetIndex())
-        return matchedRule1.styleSheetIndex() < matchedRule2.styleSheetIndex();
-
     return matchedRule1.position() < matchedRule2.position();
 }
 
diff --git a/Source/core/css/ElementRuleCollector.h b/Source/core/css/ElementRuleCollector.h
index cf47567..dbab0fe 100644
--- a/Source/core/css/ElementRuleCollector.h
+++ b/Source/core/css/ElementRuleCollector.h
@@ -27,14 +27,13 @@
 #include "core/css/resolver/ElementResolveContext.h"
 #include "core/css/resolver/MatchRequest.h"
 #include "core/css/resolver/MatchResult.h"
-#include "core/css/resolver/StyleResolverIncludes.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
+class CSSStyleSheet;
 class CSSRuleList;
-class RenderRegion;
 class RuleData;
 class RuleSet;
 class ScopedStyleResolver;
@@ -50,29 +49,30 @@
 class MatchedRule {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit MatchedRule(const RuleData* ruleData, unsigned specificity, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex)
+    explicit MatchedRule(const RuleData* ruleData, unsigned specificity, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex, const CSSStyleSheet* parentStyleSheet)
         : m_ruleData(ruleData)
         , m_specificity(specificity)
         , m_cascadeScope(cascadeScope)
-        , m_styleSheetIndex(styleSheetIndex)
+        , m_parentStyleSheet(parentStyleSheet)
     {
         ASSERT(m_ruleData);
         static const unsigned BitsForPositionInRuleData = 18;
-        m_position = (cascadeOrder << BitsForPositionInRuleData) + m_ruleData->position();
+        static const unsigned BitsForStyleSheetIndex = 32;
+        m_position = ((uint64_t)cascadeOrder << (BitsForStyleSheetIndex + BitsForPositionInRuleData)) + ((uint64_t)styleSheetIndex << BitsForPositionInRuleData)+ m_ruleData->position();
     }
 
     const RuleData* ruleData() const { return m_ruleData; }
     uint32_t cascadeScope() const { return m_cascadeScope; }
-    uint32_t position() const { return m_position; }
+    uint64_t position() const { return m_position; }
     unsigned specificity() const { return ruleData()->specificity() + m_specificity; }
-    uint32_t styleSheetIndex() const { return m_styleSheetIndex; }
+    const CSSStyleSheet* parentStyleSheet() const { return m_parentStyleSheet; }
 
 private:
     const RuleData* m_ruleData;
     unsigned m_specificity;
     CascadeScope m_cascadeScope;
-    uint32_t m_position;
-    uint32_t m_styleSheetIndex;
+    uint64_t m_position;
+    const CSSStyleSheet* m_parentStyleSheet;
 };
 
 class StyleRuleList : public RefCounted<StyleRuleList> {
@@ -88,13 +88,12 @@
 class ElementRuleCollector {
     WTF_MAKE_NONCOPYABLE(ElementRuleCollector);
 public:
-    ElementRuleCollector(const ElementResolveContext&, const SelectorFilter&, RenderStyle* = 0, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
+    ElementRuleCollector(const ElementResolveContext&, const SelectorFilter&, RenderStyle* = 0);
     ~ElementRuleCollector();
 
     void setMode(SelectorChecker::Mode mode) { m_mode = mode; }
     void setPseudoStyleRequest(const PseudoStyleRequest& request) { m_pseudoStyleRequest = request; }
     void setSameOriginOnly(bool f) { m_sameOriginOnly = f; }
-    void setRegionForStyling(const RenderRegion* regionForStyling) { m_regionForStyling = regionForStyling; }
 
     void setMatchingUARules(bool matchingUARules) { m_matchingUARules = matchingUARules; }
     bool hasAnyMatchingRules(RuleSet*);
@@ -104,7 +103,6 @@
     PassRefPtr<CSSRuleList> matchedCSSRuleList();
 
     void collectMatchingRules(const MatchRequest&, RuleRange&, SelectorChecker::BehaviorAtBoundary = SelectorChecker::DoesNotCrossBoundary, CascadeScope = ignoreCascadeScope, CascadeOrder = ignoreCascadeOrder);
-    void collectMatchingRulesForRegion(const MatchRequest&, RuleRange&, SelectorChecker::BehaviorAtBoundary = SelectorChecker::DoesNotCrossBoundary, CascadeScope = ignoreCascadeScope, CascadeOrder = ignoreCascadeOrder);
     void sortAndTransferMatchedRules();
     void clearMatchedRules();
     void addElementStyleProperties(const StylePropertySet*, bool isCacheable = true);
@@ -119,11 +117,13 @@
     void collectMatchingRulesForList(const RuleData*, SelectorChecker::BehaviorAtBoundary, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
     bool ruleMatches(const RuleData&, const ContainerNode* scope, SelectorChecker::BehaviorAtBoundary, SelectorChecker::MatchResult*);
 
-    void appendCSSOMWrapperForRule(StyleRule*);
+    CSSRuleList* nestedRuleList(CSSRule*);
+    template<class CSSRuleCollection>
+    CSSRule* findStyleRule(CSSRuleCollection*, StyleRule*);
+    void appendCSSOMWrapperForRule(CSSStyleSheet*, StyleRule*);
 
     void sortMatchedRules();
-    void addMatchedRule(const RuleData*, unsigned specificity, CascadeScope, CascadeOrder);
-    void addMatchedRule(const RuleData*, unsigned specificity, CascadeScope, CascadeOrder, unsigned styleSheetIndex);
+    void addMatchedRule(const RuleData*, unsigned specificity, CascadeScope, CascadeOrder, unsigned styleSheetIndex, const CSSStyleSheet* parentStyleSheet);
 
     StaticCSSRuleList* ensureRuleList();
     StyleRuleList* ensureStyleRuleList();
@@ -133,13 +133,11 @@
     const SelectorFilter& m_selectorFilter;
     RefPtr<RenderStyle> m_style; // FIXME: This can be mutated during matching!
 
-    const RenderRegion* m_regionForStyling;
     PseudoStyleRequest m_pseudoStyleRequest;
     SelectorChecker::Mode m_mode;
     bool m_canUseFastReject;
     bool m_sameOriginOnly;
     bool m_matchingUARules;
-    bool m_includeStyleSheet;
 
     OwnPtr<Vector<MatchedRule, 32> > m_matchedRules;
 
diff --git a/Source/core/css/FontFace.cpp b/Source/core/css/FontFace.cpp
index d170b95..6169ab4 100644
--- a/Source/core/css/FontFace.cpp
+++ b/Source/core/css/FontFace.cpp
@@ -40,21 +40,22 @@
 #include "bindings/v8/ScriptState.h"
 #include "core/css/CSSFontFace.h"
 #include "core/css/CSSFontFaceSrcValue.h"
-#include "core/css/CSSParser.h"
+#include "core/css/CSSFontSelector.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSUnicodeRangeValue.h"
 #include "core/css/CSSValueList.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/dom/DOMError.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/dom/StyleEngine.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/svg/SVGFontFaceElement.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/fonts/FontTraitsMask.h"
-#include "platform/fonts/SimpleFontData.h"
 
 namespace WebCore {
 
@@ -89,64 +90,65 @@
     RefPtr<ScriptPromiseResolver> m_resolver;
 };
 
-static PassRefPtr<CSSValue> parseCSSValue(const String& s, CSSPropertyID propertyID)
+static PassRefPtr<CSSValue> parseCSSValue(const Document* document, const String& s, CSSPropertyID propertyID)
 {
     if (s.isEmpty())
         return 0;
     RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
-    CSSParser::parseValue(parsedStyle.get(), propertyID, s, true, HTMLStandardMode, 0);
+    BisonCSSParser::parseValue(parsedStyle.get(), propertyID, s, true, *document);
     return parsedStyle->getPropertyCSSValue(propertyID);
 }
 
-PassRefPtr<FontFace> FontFace::create(const AtomicString& family, const String& source, const Dictionary& descriptors, ExceptionState& exceptionState)
+PassRefPtr<FontFace> FontFace::create(ExecutionContext* context, const AtomicString& family, const String& source, const Dictionary& descriptors, ExceptionState& exceptionState)
 {
-    RefPtr<CSSValue> src = parseCSSValue(source, CSSPropertySrc);
+    RefPtr<CSSValue> src = parseCSSValue(toDocument(context), source, CSSPropertySrc);
     if (!src || !src->isValueList()) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The source provided ('" + source + "') could not be parsed as a value list.");
         return 0;
     }
 
     RefPtr<FontFace> fontFace = adoptRef<FontFace>(new FontFace(src));
-    fontFace->setFamily(family, exceptionState);
+    fontFace->setFamily(context, family, exceptionState);
     if (exceptionState.hadException())
         return 0;
 
     String value;
     if (descriptors.get("style", value)) {
-        fontFace->setStyle(value, exceptionState);
+        fontFace->setStyle(context, value, exceptionState);
         if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("weight", value)) {
-        fontFace->setWeight(value, exceptionState);
+        fontFace->setWeight(context, value, exceptionState);
         if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("stretch", value)) {
-        fontFace->setStretch(value, exceptionState);
+        fontFace->setStretch(context, value, exceptionState);
         if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("unicodeRange", value)) {
-        fontFace->setUnicodeRange(value, exceptionState);
+        fontFace->setUnicodeRange(context, value, exceptionState);
         if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("variant", value)) {
-        fontFace->setVariant(value, exceptionState);
+        fontFace->setVariant(context, value, exceptionState);
         if (exceptionState.hadException())
             return 0;
     }
     if (descriptors.get("featureSettings", value)) {
-        fontFace->setFeatureSettings(value, exceptionState);
+        fontFace->setFeatureSettings(context, value, exceptionState);
         if (exceptionState.hadException())
             return 0;
     }
 
+    fontFace->initCSSFontFace(toDocument(context));
     return fontFace;
 }
 
-PassRefPtr<FontFace> FontFace::create(const StyleRuleFontFace* fontFaceRule)
+PassRefPtr<FontFace> FontFace::create(Document* document, const StyleRuleFontFace* fontFaceRule)
 {
     const StylePropertySet* properties = fontFaceRule->properties();
 
@@ -166,15 +168,18 @@
         && fontFace->setPropertyFromStyle(properties, CSSPropertyFontStretch)
         && fontFace->setPropertyFromStyle(properties, CSSPropertyUnicodeRange)
         && fontFace->setPropertyFromStyle(properties, CSSPropertyFontVariant)
-        && fontFace->setPropertyFromStyle(properties, CSSPropertyWebkitFontFeatureSettings))
+        && fontFace->setPropertyFromStyle(properties, CSSPropertyWebkitFontFeatureSettings)
+        && !fontFace->family().isEmpty()
+        && fontFace->traitsMask()) {
+        fontFace->initCSSFontFace(document);
         return fontFace;
+    }
     return 0;
 }
 
 FontFace::FontFace(PassRefPtr<CSSValue> src)
     : m_src(src)
     , m_status(Unloaded)
-    , m_cssFontFace(0)
 {
 }
 
@@ -212,41 +217,41 @@
     return m_featureSettings ? m_featureSettings->cssText() : "normal";
 }
 
-void FontFace::setStyle(const String& s, ExceptionState& exceptionState)
+void FontFace::setStyle(ExecutionContext* context, const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyFontStyle, exceptionState);
+    setPropertyFromString(toDocument(context), s, CSSPropertyFontStyle, exceptionState);
 }
 
-void FontFace::setWeight(const String& s, ExceptionState& exceptionState)
+void FontFace::setWeight(ExecutionContext* context, const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyFontWeight, exceptionState);
+    setPropertyFromString(toDocument(context), s, CSSPropertyFontWeight, exceptionState);
 }
 
-void FontFace::setStretch(const String& s, ExceptionState& exceptionState)
+void FontFace::setStretch(ExecutionContext* context, const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyFontStretch, exceptionState);
+    setPropertyFromString(toDocument(context), s, CSSPropertyFontStretch, exceptionState);
 }
 
-void FontFace::setUnicodeRange(const String& s, ExceptionState& exceptionState)
+void FontFace::setUnicodeRange(ExecutionContext* context, const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyUnicodeRange, exceptionState);
+    setPropertyFromString(toDocument(context), s, CSSPropertyUnicodeRange, exceptionState);
 }
 
-void FontFace::setVariant(const String& s, ExceptionState& exceptionState)
+void FontFace::setVariant(ExecutionContext* context, const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyFontVariant, exceptionState);
+    setPropertyFromString(toDocument(context), s, CSSPropertyFontVariant, exceptionState);
 }
 
-void FontFace::setFeatureSettings(const String& s, ExceptionState& exceptionState)
+void FontFace::setFeatureSettings(ExecutionContext* context, const String& s, ExceptionState& exceptionState)
 {
-    setPropertyFromString(s, CSSPropertyWebkitFontFeatureSettings, exceptionState);
+    setPropertyFromString(toDocument(context), s, CSSPropertyWebkitFontFeatureSettings, exceptionState);
 }
 
-void FontFace::setPropertyFromString(const String& s, CSSPropertyID propertyID, ExceptionState& exceptionState)
+void FontFace::setPropertyFromString(const Document* document, const String& s, CSSPropertyID propertyID, ExceptionState& exceptionState)
 {
-    RefPtr<CSSValue> value = parseCSSValue(s, propertyID);
+    RefPtr<CSSValue> value = parseCSSValue(document, s, propertyID);
     if (!value || !setPropertyValue(value, propertyID))
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "Failed to set '" + s + "' as a property value.");
 }
 
 bool FontFace::setPropertyFromStyle(const StylePropertySet* properties, CSSPropertyID propertyID)
@@ -348,10 +353,9 @@
         resolveReadyPromises();
 }
 
-void FontFace::load()
+void FontFace::load(ExecutionContext* context)
 {
-    // FIXME: This does not load FontFace created by JavaScript, since m_cssFontFace is null.
-    if (m_status != Unloaded || !m_cssFontFace)
+    if (m_status != Unloaded)
         return;
 
     FontDescription fontDescription;
@@ -360,9 +364,9 @@
     fontDescription.setFamily(fontFamily);
     fontDescription.setTraitsMask(static_cast<FontTraitsMask>(traitsMask()));
 
-    RefPtr<SimpleFontData> fontData = m_cssFontFace->getFontData(fontDescription);
-    if (fontData && fontData->customFontData())
-        fontData->customFontData()->beginLoadIfNeeded();
+    CSSFontSelector* fontSelector = toDocument(context)->styleEngine()->fontSelector();
+    m_cssFontFace->load(fontDescription, fontSelector);
+    fontSelector->loadPendingFonts();
 }
 
 ScriptPromise FontFace::ready(ExecutionContext* context)
@@ -437,10 +441,12 @@
         case CSSValue200:
             traitsMask |= FontWeight200Mask;
             break;
+        case CSSValueLighter:
         case CSSValue100:
             traitsMask |= FontWeight100Mask;
             break;
         default:
+            ASSERT_NOT_REACHED();
             break;
         }
     } else {
@@ -450,7 +456,7 @@
     if (RefPtr<CSSValue> fontVariant = m_variant) {
         // font-variant descriptor can be a value list.
         if (fontVariant->isPrimitiveValue()) {
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             list->append(fontVariant);
             fontVariant = list;
         } else if (!fontVariant->isValueList()) {
@@ -480,13 +486,10 @@
     return traitsMask;
 }
 
-PassRefPtr<CSSFontFace> FontFace::createCSSFontFace(Document* document)
+void FontFace::initCSSFontFace(Document* document)
 {
-    if (m_cssFontFace)
-        return m_cssFontFace;
-
-    RefPtr<CSSFontFace> cssFontFace = CSSFontFace::create(this);
-    m_cssFontFace = cssFontFace.get();
+    ASSERT(!m_cssFontFace);
+    m_cssFontFace = adoptPtr(new CSSFontFace(this));
 
     // Each item in the src property's list is a single CSSFontFaceSource. Put them all into a CSSFontFace.
     CSSValueList* srcList = toCSSValueList(m_src.get());
@@ -523,7 +526,7 @@
 #if ENABLE(SVG_FONTS)
             source->setSVGFontFaceElement(item->svgFontFaceElement());
 #endif
-            cssFontFace->addSource(source.release());
+            m_cssFontFace->addSource(source.release());
         }
     }
 
@@ -531,10 +534,9 @@
         unsigned numRanges = rangeList->length();
         for (unsigned i = 0; i < numRanges; i++) {
             CSSUnicodeRangeValue* range = toCSSUnicodeRangeValue(rangeList->itemWithoutBoundsCheck(i));
-            cssFontFace->ranges().add(range->from(), range->to());
+            m_cssFontFace->ranges().add(range->from(), range->to());
         }
     }
-    return cssFontFace;
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/FontFace.h b/Source/core/css/FontFace.h
index 900d3a7..4acea31 100644
--- a/Source/core/css/FontFace.h
+++ b/Source/core/css/FontFace.h
@@ -53,8 +53,8 @@
 public:
     enum LoadStatus { Unloaded, Loading, Loaded, Error };
 
-    static PassRefPtr<FontFace> create(const AtomicString& family, const String& source, const Dictionary&, ExceptionState&);
-    static PassRefPtr<FontFace> create(const StyleRuleFontFace*);
+    static PassRefPtr<FontFace> create(ExecutionContext*, const AtomicString& family, const String& source, const Dictionary&, ExceptionState&);
+    static PassRefPtr<FontFace> create(Document*, const StyleRuleFontFace*);
 
     ~FontFace();
 
@@ -67,29 +67,29 @@
     String featureSettings() const;
 
     // FIXME: Changing these attributes should affect font matching.
-    void setFamily(const AtomicString& s, ExceptionState&) { m_family = s; }
-    void setStyle(const String&, ExceptionState&);
-    void setWeight(const String&, ExceptionState&);
-    void setStretch(const String&, ExceptionState&);
-    void setUnicodeRange(const String&, ExceptionState&);
-    void setVariant(const String&, ExceptionState&);
-    void setFeatureSettings(const String&, ExceptionState&);
+    void setFamily(ExecutionContext*, const AtomicString& s, ExceptionState&) { m_family = s; }
+    void setStyle(ExecutionContext*, const String&, ExceptionState&);
+    void setWeight(ExecutionContext*, const String&, ExceptionState&);
+    void setStretch(ExecutionContext*, const String&, ExceptionState&);
+    void setUnicodeRange(ExecutionContext*, const String&, ExceptionState&);
+    void setVariant(ExecutionContext*, const String&, ExceptionState&);
+    void setFeatureSettings(ExecutionContext*, const String&, ExceptionState&);
 
     String status() const;
 
-    void load();
+    void load(ExecutionContext*);
     ScriptPromise ready(ExecutionContext*);
 
     LoadStatus loadStatus() const { return m_status; }
     void setLoadStatus(LoadStatus);
     unsigned traitsMask() const;
-    PassRefPtr<CSSFontFace> createCSSFontFace(Document*);
-    void cssFontFaceDestroyed() { m_cssFontFace = 0; }
+    CSSFontFace* cssFontFace() { return m_cssFontFace.get(); }
 
 private:
     FontFace(PassRefPtr<CSSValue> source);
 
-    void setPropertyFromString(const String&, CSSPropertyID, ExceptionState&);
+    void initCSSFontFace(Document*);
+    void setPropertyFromString(const Document*, const String&, CSSPropertyID, ExceptionState&);
     bool setPropertyFromStyle(const StylePropertySet*, CSSPropertyID);
     bool setPropertyValue(PassRefPtr<CSSValue>, CSSPropertyID);
     bool setFamilyValue(CSSValueList*);
@@ -106,7 +106,7 @@
     LoadStatus m_status;
 
     Vector<OwnPtr<FontFaceReadyPromiseResolver> > m_readyResolvers;
-    CSSFontFace* m_cssFontFace;
+    OwnPtr<CSSFontFace> m_cssFontFace;
 };
 
 typedef Vector<RefPtr<FontFace> > FontFaceArray;
diff --git a/Source/core/css/FontFace.idl b/Source/core/css/FontFace.idl
index fcfef2d..922be52 100644
--- a/Source/core/css/FontFace.idl
+++ b/Source/core/css/FontFace.idl
@@ -38,19 +38,20 @@
 [
     RuntimeEnabled=FontLoadEvents,
     Constructor(DOMString family, DOMString source, Dictionary descriptors),
+    ConstructorCallWith=ExecutionContext,
     RaisesException=Constructor
 ] interface FontFace {
 
-    [RaisesException=Setter] attribute DOMString family;
-    [RaisesException=Setter] attribute DOMString style;
-    [RaisesException=Setter] attribute DOMString weight;
-    [RaisesException=Setter] attribute DOMString stretch;
-    [RaisesException=Setter] attribute DOMString unicodeRange;
-    [RaisesException=Setter] attribute DOMString variant;
-    [RaisesException=Setter] attribute DOMString featureSettings;
+    [RaisesException=Setter, SetterCallWith=ExecutionContext] attribute DOMString family;
+    [RaisesException=Setter, SetterCallWith=ExecutionContext] attribute DOMString style;
+    [RaisesException=Setter, SetterCallWith=ExecutionContext] attribute DOMString weight;
+    [RaisesException=Setter, SetterCallWith=ExecutionContext] attribute DOMString stretch;
+    [RaisesException=Setter, SetterCallWith=ExecutionContext] attribute DOMString unicodeRange;
+    [RaisesException=Setter, SetterCallWith=ExecutionContext] attribute DOMString variant;
+    [RaisesException=Setter, SetterCallWith=ExecutionContext] attribute DOMString featureSettings;
 
     readonly attribute FontFaceLoadStatus status;
 
-    void load();
+    [CallWith=ExecutionContext] void load();
     [CallWith=ExecutionContext] Promise ready();
 };
diff --git a/Source/core/css/CSSSegmentedFontFaceCache.cpp b/Source/core/css/FontFaceCache.cpp
similarity index 84%
rename from Source/core/css/CSSSegmentedFontFaceCache.cpp
rename to Source/core/css/FontFaceCache.cpp
index 17803d8..6c4c9b5 100644
--- a/Source/core/css/CSSSegmentedFontFaceCache.cpp
+++ b/Source/core/css/FontFaceCache.cpp
@@ -26,14 +26,13 @@
 
 
 #include "config.h"
-#include "CSSSegmentedFontFaceCache.h"
+#include "FontFaceCache.h"
 
 #include "FontFamilyNames.h"
-#include "core/css/CSSFontFace.h"
-#include "core/css/CSSFontFaceSource.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSSegmentedFontFace.h"
 #include "core/css/CSSValueList.h"
+#include "core/css/FontFace.h"
 #include "core/css/StyleRule.h"
 #include "core/fetch/FontResource.h"
 #include "core/fetch/ResourceFetcher.h"
@@ -42,61 +41,79 @@
 
 namespace WebCore {
 
-CSSSegmentedFontFaceCache::CSSSegmentedFontFaceCache()
+FontFaceCache::FontFaceCache()
     : m_version(0)
 {
 }
 
-void CSSSegmentedFontFaceCache::add(CSSFontSelector* cssFontSelector, const StyleRuleFontFace* fontFaceRule, PassRefPtr<CSSFontFace> prpCssFontFace)
+void FontFaceCache::add(CSSFontSelector* cssFontSelector, const StyleRuleFontFace* fontFaceRule, PassRefPtr<FontFace> prpFontFace)
 {
-    RefPtr<CSSFontFace> cssFontFace = prpCssFontFace;
-
-    if (!m_styleRuleToFontFace.add(fontFaceRule, cssFontFace).isNewEntry)
+    RefPtr<FontFace> fontFace = prpFontFace;
+    if (!m_styleRuleToFontFace.add(fontFaceRule, fontFace).isNewEntry)
         return;
+    addFontFace(cssFontSelector, fontFace, true);
+}
 
-    FontFace* fontFace = cssFontFace->fontFace();
+void FontFaceCache::addFontFace(CSSFontSelector* cssFontSelector, PassRefPtr<FontFace> prpFontFace, bool cssConnected)
+{
+    RefPtr<FontFace> fontFace = prpFontFace;
 
-    OwnPtr<TraitsMap>& familyFontFaces = m_fontFaces.add(fontFace->family(), nullptr).iterator->value;
+    OwnPtr<TraitsMap>& familyFontFaces = m_fontFaces.add(fontFace->family(), nullptr).storedValue->value;
     if (!familyFontFaces)
         familyFontFaces = adoptPtr(new TraitsMap);
 
-    RefPtr<CSSSegmentedFontFace>& segmentedFontFace = familyFontFaces->add(fontFace->traitsMask(), 0).iterator->value;
+    RefPtr<CSSSegmentedFontFace>& segmentedFontFace = familyFontFaces->add(fontFace->traitsMask(), 0).storedValue->value;
     if (!segmentedFontFace)
         segmentedFontFace = CSSSegmentedFontFace::create(cssFontSelector, static_cast<FontTraitsMask>(fontFace->traitsMask()));
 
-    segmentedFontFace->appendFontFace(cssFontFace);
+    segmentedFontFace->addFontFace(fontFace, cssConnected);
+    if (cssConnected)
+        m_cssConnectedFontFaces.add(fontFace);
 
     ++m_version;
 }
 
-void CSSSegmentedFontFaceCache::remove(const StyleRuleFontFace* fontFaceRule)
+void FontFaceCache::remove(const StyleRuleFontFace* fontFaceRule)
 {
-    StyleRuleToFontFace::iterator styleRuleToFontFaceIter = m_styleRuleToFontFace.find(fontFaceRule);
-    if (styleRuleToFontFaceIter == m_styleRuleToFontFace.end())
-        return;
-    RefPtr<CSSFontFace> cssFontFace = styleRuleToFontFaceIter->value;
+    StyleRuleToFontFace::iterator it = m_styleRuleToFontFace.find(fontFaceRule);
+    if (it != m_styleRuleToFontFace.end()) {
+        removeFontFace(it->value.get(), true);
+        m_styleRuleToFontFace.remove(it);
+    }
+}
 
-    FamilyToTraitsMap::iterator fontFacesIter = m_fontFaces.find(cssFontFace->fontFace()->family());
+void FontFaceCache::removeFontFace(FontFace* fontFace, bool cssConnected)
+{
+    FamilyToTraitsMap::iterator fontFacesIter = m_fontFaces.find(fontFace->family());
     if (fontFacesIter == m_fontFaces.end())
         return;
     TraitsMap* familyFontFaces = fontFacesIter->value.get();
 
-    TraitsMap::iterator familyFontFacesIter = familyFontFaces->find(cssFontFace->fontFace()->traitsMask());
+    TraitsMap::iterator familyFontFacesIter = familyFontFaces->find(fontFace->traitsMask());
     if (familyFontFacesIter == familyFontFaces->end())
         return;
     RefPtr<CSSSegmentedFontFace> segmentedFontFace = familyFontFacesIter->value;
 
-    segmentedFontFace->removeFontFace(cssFontFace);
+    segmentedFontFace->removeFontFace(fontFace);
     if (segmentedFontFace->isEmpty()) {
         familyFontFaces->remove(familyFontFacesIter);
         if (familyFontFaces->isEmpty())
             m_fontFaces.remove(fontFacesIter);
     }
-    m_styleRuleToFontFace.remove(styleRuleToFontFaceIter);
     m_fonts.clear();
+    if (cssConnected)
+        m_cssConnectedFontFaces.remove(fontFace);
+
     ++m_version;
 }
 
+void FontFaceCache::clear()
+{
+    for (StyleRuleToFontFace::iterator it = m_styleRuleToFontFace.begin(); it != m_styleRuleToFontFace.end(); ++it)
+        removeFontFace(it->value.get(), true);
+    m_styleRuleToFontFace.clear();
+}
+
 static inline bool compareFontFaces(CSSSegmentedFontFace* first, CSSSegmentedFontFace* second, FontTraitsMask desiredTraitsMask)
 {
     FontTraitsMask firstTraitsMask = first->traitsMask();
@@ -177,19 +194,19 @@
     return false;
 }
 
-CSSSegmentedFontFace* CSSSegmentedFontFaceCache::get(const FontDescription& fontDescription, const AtomicString& family)
+CSSSegmentedFontFace* FontFaceCache::get(const FontDescription& fontDescription, const AtomicString& family)
 {
     TraitsMap* familyFontFaces = m_fontFaces.get(family);
     if (!familyFontFaces || familyFontFaces->isEmpty())
         return 0;
 
-    OwnPtr<TraitsMap>& segmentedFontFaceCache = m_fonts.add(family, nullptr).iterator->value;
+    OwnPtr<TraitsMap>& segmentedFontFaceCache = m_fonts.add(family, nullptr).storedValue->value;
     if (!segmentedFontFaceCache)
         segmentedFontFaceCache = adoptPtr(new TraitsMap);
 
     FontTraitsMask traitsMask = fontDescription.traitsMask();
 
-    RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache->add(traitsMask, 0).iterator->value;
+    RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache->add(traitsMask, 0).storedValue->value;
     if (!face) {
         for (TraitsMap::const_iterator i = familyFontFaces->begin(); i != familyFontFaces->end(); ++i) {
             CSSSegmentedFontFace* candidate = i->value.get();
diff --git a/Source/core/css/CSSSegmentedFontFaceCache.h b/Source/core/css/FontFaceCache.h
similarity index 79%
rename from Source/core/css/CSSSegmentedFontFaceCache.h
rename to Source/core/css/FontFaceCache.h
index c182209..1b6873b 100644
--- a/Source/core/css/CSSSegmentedFontFaceCache.h
+++ b/Source/core/css/FontFaceCache.h
@@ -24,42 +24,50 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CSSSegmentedFontFaceCache_h
-#define CSSSegmentedFontFaceCache_h
+#ifndef FontFaceCache_h
+#define FontFaceCache_h
 
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
+#include "wtf/ListHashSet.h"
 #include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
-class CSSFontFace;
+class FontFace;
 class CSSFontSelector;
 class CSSSegmentedFontFace;
 class FontDescription;
 class StyleRuleFontFace;
 
-class CSSSegmentedFontFaceCache {
+class FontFaceCache {
 public:
-    CSSSegmentedFontFaceCache();
+    FontFaceCache();
 
     // FIXME: Remove CSSFontSelector as argument. Passing CSSFontSelector here is
-    // a result of egregious spaghettification in CSSFontFace/FontFaceSet.
-    void add(CSSFontSelector*, const StyleRuleFontFace*, PassRefPtr<CSSFontFace>);
+    // a result of egregious spaghettification in FontFace/FontFaceSet.
+    void add(CSSFontSelector*, const StyleRuleFontFace*, PassRefPtr<FontFace>);
     void remove(const StyleRuleFontFace*);
+    void clear();
+    void addFontFace(CSSFontSelector*, PassRefPtr<FontFace>, bool cssConnected);
+    void removeFontFace(FontFace*, bool cssConnected);
+
     // FIXME: It's sort of weird that add/remove uses StyleRuleFontFace* as key,
     // but this function uses FontDescription/family pair.
     CSSSegmentedFontFace* get(const FontDescription&, const AtomicString& family);
 
+    const ListHashSet<RefPtr<FontFace> >& cssConnectedFontFaces() const { return m_cssConnectedFontFaces; }
+
     unsigned version() const { return m_version; }
 
 private:
     typedef HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > TraitsMap;
     typedef HashMap<String, OwnPtr<TraitsMap>, CaseFoldingHash> FamilyToTraitsMap;
-    typedef HashMap<const StyleRuleFontFace*, RefPtr<CSSFontFace> > StyleRuleToFontFace;
+    typedef HashMap<const StyleRuleFontFace*, RefPtr<FontFace> > StyleRuleToFontFace;
     FamilyToTraitsMap m_fontFaces;
     FamilyToTraitsMap m_fonts;
     StyleRuleToFontFace m_styleRuleToFontFace;
+    ListHashSet<RefPtr<FontFace> > m_cssConnectedFontFaces;
 
     // FIXME: See if this could be ditched
     // Used to compare Font instances, and the usage seems suspect.
diff --git a/Source/core/css/FontFaceSet.cpp b/Source/core/css/FontFaceSet.cpp
index 38165b8..af5f8d5 100644
--- a/Source/core/css/FontFaceSet.cpp
+++ b/Source/core/css/FontFaceSet.cpp
@@ -32,10 +32,10 @@
 #include "bindings/v8/ScriptScope.h"
 #include "bindings/v8/ScriptState.h"
 #include "core/css/CSSFontFaceLoadEvent.h"
-#include "core/css/CSSFontFaceSource.h"
 #include "core/css/CSSFontSelector.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSSegmentedFontFace.h"
+#include "core/css/FontFaceCache.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
@@ -58,10 +58,10 @@
         return adoptRef<LoadFontPromiseResolver>(new LoadFontPromiseResolver(numFamilies, promise, context));
     }
 
-    virtual void notifyLoaded(CSSSegmentedFontFace*) OVERRIDE;
-    virtual void notifyError(CSSSegmentedFontFace*) OVERRIDE;
-    void loaded(Document*);
-    void error(Document*);
+    virtual void notifyLoaded(CSSSegmentedFontFace*) OVERRIDE { loaded(); }
+    virtual void notifyError(CSSSegmentedFontFace*) OVERRIDE { error(); }
+    void loaded();
+    void error();
 
 private:
     LoadFontPromiseResolver(int numLoading, ScriptPromise promise, ExecutionContext* context)
@@ -77,10 +77,10 @@
     RefPtr<ScriptPromiseResolver> m_resolver;
 };
 
-void LoadFontPromiseResolver::loaded(Document* document)
+void LoadFontPromiseResolver::loaded()
 {
     m_numLoading--;
-    if (m_numLoading || !document)
+    if (m_numLoading)
         return;
 
     ScriptScope scope(m_scriptState);
@@ -90,20 +90,10 @@
         m_resolver->resolve(ScriptValue::createNull());
 }
 
-void LoadFontPromiseResolver::error(Document* document)
+void LoadFontPromiseResolver::error()
 {
     m_errorOccured = true;
-    loaded(document);
-}
-
-void LoadFontPromiseResolver::notifyLoaded(CSSSegmentedFontFace* face)
-{
-    loaded(face->fontSelector()->document());
-}
-
-void LoadFontPromiseResolver::notifyError(CSSSegmentedFontFace* face)
-{
-    error(face->fontSelector()->document());
+    loaded();
 }
 
 class FontsReadyPromiseResolver {
@@ -146,6 +136,18 @@
     return toDocument(executionContext());
 }
 
+bool FontFaceSet::inActiveDocumentContext() const
+{
+    ExecutionContext* context = executionContext();
+    return context && toDocument(context)->isActive();
+}
+
+void FontFaceSet::addFontFacesToFontFaceCache(FontFaceCache* fontFaceCache, CSSFontSelector* fontSelector)
+{
+    for (ListHashSet<RefPtr<FontFace> >::iterator it = m_nonCSSConnectedFaces.begin(); it != m_nonCSSConnectedFaces.end(); ++it)
+        fontFaceCache->addFontFace(fontSelector, *it, false);
+}
+
 const AtomicString& FontFaceSet::interfaceName() const
 {
     return EventTargetNames::FontFaceSet;
@@ -215,13 +217,7 @@
     m_histogram.incrementCount();
     if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
         return;
-
-    if (!m_loadingCount && !hasLoadedFonts()) {
-        ASSERT(!m_shouldFireLoadingEvent);
-        m_shouldFireLoadingEvent = true;
-        handlePendingEventsAndPromisesSoon();
-    }
-    ++m_loadingCount;
+    incrementLoadingCount();
 }
 
 void FontFaceSet::fontLoaded(FontFace* fontFace)
@@ -229,7 +225,7 @@
     if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
         return;
     m_loadedFonts.append(fontFace);
-    queueDoneEvent(fontFace);
+    decrementLoadingCount();
 }
 
 void FontFaceSet::loadError(FontFace* fontFace)
@@ -237,10 +233,19 @@
     if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
         return;
     m_failedFonts.append(fontFace);
-    queueDoneEvent(fontFace);
+    decrementLoadingCount();
 }
 
-void FontFaceSet::queueDoneEvent(FontFace* fontFace)
+void FontFaceSet::incrementLoadingCount()
+{
+    if (!m_loadingCount && !hasLoadedFonts()) {
+        m_shouldFireLoadingEvent = true;
+        handlePendingEventsAndPromisesSoon();
+    }
+    ++m_loadingCount;
+}
+
+void FontFaceSet::decrementLoadingCount()
 {
     ASSERT(m_loadingCount > 0);
     --m_loadingCount;
@@ -250,6 +255,8 @@
 
 ScriptPromise FontFaceSet::ready()
 {
+    if (!inActiveDocumentContext())
+        return ScriptPromise();
     ScriptPromise promise = ScriptPromise::createPending(executionContext());
     OwnPtr<FontsReadyPromiseResolver> resolver = FontsReadyPromiseResolver::create(promise, executionContext());
     m_readyResolvers.append(resolver.release());
@@ -257,6 +264,122 @@
     return promise;
 }
 
+void FontFaceSet::add(FontFace* fontFace, ExceptionState& exceptionState)
+{
+    if (!inActiveDocumentContext())
+        return;
+    if (!fontFace) {
+        exceptionState.throwTypeError("The argument is not a FontFace.");
+        return;
+    }
+    if (m_nonCSSConnectedFaces.contains(fontFace))
+        return;
+    if (isCSSConnectedFontFace(fontFace)) {
+        exceptionState.throwDOMException(InvalidModificationError, "Cannot add a CSS-connected FontFace.");
+        return;
+    }
+    CSSFontSelector* fontSelector = document()->styleEngine()->fontSelector();
+    m_nonCSSConnectedFaces.add(fontFace);
+    fontSelector->fontFaceCache()->addFontFace(fontSelector, fontFace, false);
+    if (fontFace->loadStatus() == FontFace::Loading)
+        incrementLoadingCount();
+}
+
+void FontFaceSet::clear()
+{
+    if (!inActiveDocumentContext())
+        return;
+    FontFaceCache* fontFaceCache = document()->styleEngine()->fontSelector()->fontFaceCache();
+    for (ListHashSet<RefPtr<FontFace> >::iterator it = m_nonCSSConnectedFaces.begin(); it != m_nonCSSConnectedFaces.end(); ++it) {
+        fontFaceCache->removeFontFace(it->get(), false);
+        if ((*it)->loadStatus() == FontFace::Loading)
+            decrementLoadingCount();
+    }
+    m_nonCSSConnectedFaces.clear();
+}
+
+bool FontFaceSet::remove(FontFace* fontFace, ExceptionState& exceptionState)
+{
+    if (!inActiveDocumentContext())
+        return false;
+    if (!fontFace) {
+        exceptionState.throwTypeError("The argument is not a FontFace.");
+        return false;
+    }
+    ListHashSet<RefPtr<FontFace> >::iterator it = m_nonCSSConnectedFaces.find(fontFace);
+    if (it != m_nonCSSConnectedFaces.end()) {
+        m_nonCSSConnectedFaces.remove(it);
+        document()->styleEngine()->fontSelector()->fontFaceCache()->removeFontFace(fontFace, false);
+        if (fontFace->loadStatus() == FontFace::Loading)
+            decrementLoadingCount();
+        return true;
+    }
+    if (isCSSConnectedFontFace(fontFace))
+        exceptionState.throwDOMException(InvalidModificationError, "Cannot delete a CSS-connected FontFace.");
+    return false;
+}
+
+bool FontFaceSet::has(FontFace* fontFace, ExceptionState& exceptionState) const
+{
+    if (!inActiveDocumentContext())
+        return false;
+    if (!fontFace) {
+        exceptionState.throwTypeError("The argument is not a FontFace.");
+        return false;
+    }
+    return m_nonCSSConnectedFaces.contains(fontFace) || isCSSConnectedFontFace(fontFace);
+}
+
+const ListHashSet<RefPtr<FontFace> >& FontFaceSet::cssConnectedFontFaceList() const
+{
+    Document* d = document();
+    d->ensureStyleResolver(); // Flush pending style changes.
+    return d->styleEngine()->fontSelector()->fontFaceCache()->cssConnectedFontFaces();
+}
+
+bool FontFaceSet::isCSSConnectedFontFace(FontFace* fontFace) const
+{
+    return cssConnectedFontFaceList().contains(fontFace);
+}
+
+void FontFaceSet::forEach(PassOwnPtr<FontFaceSetForEachCallback> callback, ScriptValue& thisArg) const
+{
+    forEachInternal(callback, &thisArg);
+}
+
+void FontFaceSet::forEach(PassOwnPtr<FontFaceSetForEachCallback> callback) const
+{
+    forEachInternal(callback, 0);
+}
+
+void FontFaceSet::forEachInternal(PassOwnPtr<FontFaceSetForEachCallback> callback, ScriptValue* thisArg) const
+{
+    if (!inActiveDocumentContext())
+        return;
+    const ListHashSet<RefPtr<FontFace> >& cssConnectedFaces = cssConnectedFontFaceList();
+    Vector<RefPtr<FontFace> > fontFaces;
+    fontFaces.reserveInitialCapacity(cssConnectedFaces.size() + m_nonCSSConnectedFaces.size());
+    for (ListHashSet<RefPtr<FontFace> >::const_iterator it = cssConnectedFaces.begin(); it != cssConnectedFaces.end(); ++it)
+        fontFaces.append(*it);
+    for (ListHashSet<RefPtr<FontFace> >::const_iterator it = m_nonCSSConnectedFaces.begin(); it != m_nonCSSConnectedFaces.end(); ++it)
+        fontFaces.append(*it);
+
+    for (size_t i = 0; i < fontFaces.size(); ++i) {
+        FontFace* face = fontFaces[i].get();
+        if (thisArg)
+            callback->handleItem(*thisArg, face, face, const_cast<FontFaceSet*>(this));
+        else
+            callback->handleItem(face, face, const_cast<FontFaceSet*>(this));
+    }
+}
+
+unsigned long FontFaceSet::size() const
+{
+    if (!inActiveDocumentContext())
+        return m_nonCSSConnectedFaces.size();
+    return cssConnectedFontFaceList().size() + m_nonCSSConnectedFaces.size();
+}
+
 void FontFaceSet::fireDoneEventIfPossible()
 {
     if (m_shouldFireLoadingEvent)
@@ -299,57 +422,48 @@
     return s.isNull() ? space : s;
 }
 
-Vector<RefPtr<FontFace> > FontFaceSet::match(const String& fontString, const String& text, ExceptionState& exceptionState)
-{
-    Vector<RefPtr<FontFace> > matchedFonts;
-
-    Font font;
-    if (!resolveFontStyle(fontString, font)) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
-        return matchedFonts;
-    }
-
-    for (const FontFamily* f = &font.family(); f; f = f->next()) {
-        CSSSegmentedFontFace* face = document()->styleEngine()->fontSelector()->getFontFace(font.fontDescription(), f->family());
-        if (face)
-            matchedFonts.append(face->fontFaces(nullToSpace(text)));
-    }
-    return matchedFonts;
-}
-
 ScriptPromise FontFaceSet::load(const String& fontString, const String& text, ExceptionState& exceptionState)
 {
+    if (!inActiveDocumentContext())
+        return ScriptPromise();
+
     Font font;
     if (!resolveFontStyle(fontString, font)) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "Could not resolve '" + fontString + "' as a font.");
         return ScriptPromise();
     }
 
-    Document* d = document();
+    CSSFontSelector* fontSelector = document()->styleEngine()->fontSelector();
+    FontFaceCache* fontFaceCache = fontSelector->fontFaceCache();
     ScriptPromise promise = ScriptPromise::createPending(executionContext());
-    RefPtr<LoadFontPromiseResolver> resolver = LoadFontPromiseResolver::create(font.family(), promise, executionContext());
-    for (const FontFamily* f = &font.family(); f; f = f->next()) {
-        CSSSegmentedFontFace* face = d->styleEngine()->fontSelector()->getFontFace(font.fontDescription(), f->family());
+    RefPtr<LoadFontPromiseResolver> resolver = LoadFontPromiseResolver::create(font.fontDescription().family(), promise, executionContext());
+    for (const FontFamily* f = &font.fontDescription().family(); f; f = f->next()) {
+        CSSSegmentedFontFace* face = fontFaceCache->get(font.fontDescription(), f->family());
         if (!face) {
-            resolver->error(d);
+            resolver->error();
             continue;
         }
         face->loadFont(font.fontDescription(), nullToSpace(text), resolver);
     }
+    fontSelector->loadPendingFonts();
     return promise;
 }
 
 bool FontFaceSet::check(const String& fontString, const String& text, ExceptionState& exceptionState)
 {
+    if (!inActiveDocumentContext())
+        return false;
+
     Font font;
     if (!resolveFontStyle(fontString, font)) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "Could not resolve '" + fontString + "' as a font.");
         return false;
     }
 
-    for (const FontFamily* f = &font.family(); f; f = f->next()) {
-        CSSSegmentedFontFace* face = document()->styleEngine()->fontSelector()->getFontFace(font.fontDescription(), f->family());
-        if (!face || !face->checkFont(nullToSpace(text)))
+    FontFaceCache* fontFaceCache = document()->styleEngine()->fontSelector()->fontFaceCache();
+    for (const FontFamily* f = &font.fontDescription().family(); f; f = f->next()) {
+        CSSSegmentedFontFace* face = fontFaceCache->get(font.fontDescription(), f->family());
+        if (face && !face->checkFont(nullToSpace(text)))
             return false;
     }
     return true;
@@ -362,7 +476,7 @@
 
     // Interpret fontString in the same way as the 'font' attribute of CanvasRenderingContext2D.
     RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
-    CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, HTMLStandardMode, 0);
+    BisonCSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, HTMLStandardMode, 0);
     if (parsedStyle->isEmpty())
         return false;
 
diff --git a/Source/core/css/FontFaceSet.h b/Source/core/css/FontFaceSet.h
index ebad132..9b50984 100644
--- a/Source/core/css/FontFaceSet.h
+++ b/Source/core/css/FontFaceSet.h
@@ -28,6 +28,7 @@
 
 #include "bindings/v8/ScriptPromise.h"
 #include "core/css/FontFace.h"
+#include "core/css/FontFaceSetForEachCallback.h"
 #include "core/dom/ActiveDOMObject.h"
 #include "core/events/EventListener.h"
 #include "core/events/EventTarget.h"
@@ -45,16 +46,19 @@
 
 namespace WebCore {
 
+class CSSFontFace;
 class CSSFontFaceSource;
+class CSSFontSelector;
 class Dictionary;
 class Document;
 class ExceptionState;
 class Font;
+class FontFaceCache;
 class FontResource;
 class FontsReadyPromiseResolver;
 class ExecutionContext;
 
-class FontFaceSet : public RefCountedSupplement<Document, FontFaceSet>, public ActiveDOMObject, public EventTargetWithInlineData {
+class FontFaceSet FINAL : public RefCountedSupplement<Document, FontFaceSet>, public ActiveDOMObject, public EventTargetWithInlineData {
     REFCOUNTED_EVENT_TARGET(FontFaceSet);
 public:
     virtual ~FontFaceSet();
@@ -63,11 +67,18 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(loadingdone);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(loadingerror);
 
-    Vector<RefPtr<FontFace> > match(const String& font, const String& text, ExceptionState&);
     bool check(const String& font, const String& text, ExceptionState&);
     ScriptPromise load(const String& font, const String& text, ExceptionState&);
     ScriptPromise ready();
 
+    void add(FontFace*, ExceptionState&);
+    void clear();
+    bool remove(FontFace*, ExceptionState&);
+    void forEach(PassOwnPtr<FontFaceSetForEachCallback>, ScriptValue& thisArg) const;
+    void forEach(PassOwnPtr<FontFaceSetForEachCallback>) const;
+    bool has(FontFace*, ExceptionState&) const;
+
+    unsigned long size() const;
     AtomicString status() const;
 
     virtual ExecutionContext* executionContext() const OVERRIDE;
@@ -88,6 +99,8 @@
     static PassRefPtr<FontFaceSet> from(Document*);
     static void didLayout(Document*);
 
+    void addFontFacesToFontFaceCache(FontFaceCache*, CSSFontSelector*);
+
 private:
     typedef RefCountedSupplement<Document, FontFaceSet> SupplementType;
 
@@ -111,18 +124,24 @@
 
     bool hasLoadedFonts() const { return !m_loadedFonts.isEmpty() || !m_failedFonts.isEmpty(); }
 
-    void queueDoneEvent(FontFace*);
+    bool inActiveDocumentContext() const;
+    void forEachInternal(PassOwnPtr<FontFaceSetForEachCallback>, ScriptValue* thisArg) const;
+    void incrementLoadingCount();
+    void decrementLoadingCount();
     void fireLoadingEvent();
     void fireDoneEventIfPossible();
     bool resolveFontStyle(const String&, Font&);
     void handlePendingEventsAndPromisesSoon();
     void handlePendingEventsAndPromises();
+    const ListHashSet<RefPtr<FontFace> >& cssConnectedFontFaceList() const;
+    bool isCSSConnectedFontFace(FontFace*) const;
 
     unsigned m_loadingCount;
     bool m_shouldFireLoadingEvent;
     Vector<OwnPtr<FontsReadyPromiseResolver> > m_readyResolvers;
     FontFaceArray m_loadedFonts;
     FontFaceArray m_failedFonts;
+    ListHashSet<RefPtr<FontFace> > m_nonCSSConnectedFaces;
 
     AsyncMethodRunner<FontFaceSet> m_asyncRunner;
 
diff --git a/Source/core/css/FontFaceSet.idl b/Source/core/css/FontFaceSet.idl
index 643c335..7f5b6ce 100644
--- a/Source/core/css/FontFaceSet.idl
+++ b/Source/core/css/FontFaceSet.idl
@@ -32,7 +32,7 @@
 
 [
     ActiveDOMObject,
-    GenerateVisitDOMWrapper=document,
+    SetWrapperReferenceFrom=document,
     NoInterfaceObject,
     RuntimeEnabled=FontLoadEvents,
 ] interface FontFaceSet : EventTarget {
@@ -41,10 +41,16 @@
     attribute EventHandler onloadingdone;
     attribute EventHandler onloadingerror;
 
-    [RaisesException] sequence<FontFace> match(DOMString font, [Default=NullString] optional DOMString text);
     [RaisesException] boolean check(DOMString font, [Default=NullString] optional DOMString text);
     [RaisesException] Promise load(DOMString font, [Default=NullString] optional DOMString text);
     Promise ready();
 
+    [RaisesException] void add(FontFace fontFace);
+    void clear();
+    [RaisesException, ImplementedAs=remove] boolean delete(FontFace fontFace);
+    void forEach(FontFaceSetForEachCallback callback, optional any thisArg);
+    [RaisesException] boolean has(FontFace fontFace);
+
+    readonly attribute unsigned long size;
     readonly attribute FontFaceSetLoadStatus status;
 };
diff --git a/Source/core/css/FontFaceSetForEachCallback.h b/Source/core/css/FontFaceSetForEachCallback.h
new file mode 100644
index 0000000..8550e24
--- /dev/null
+++ b/Source/core/css/FontFaceSetForEachCallback.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2013 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
+ */
+
+#ifndef FontFaceSetForEachCallback_h
+#define FontFaceSetForEachCallback_h
+
+#include "bindings/v8/ScriptValue.h"
+
+namespace WebCore {
+
+class FontFace;
+class FontFaceSet;
+
+class FontFaceSetForEachCallback {
+public:
+    virtual ~FontFaceSetForEachCallback() { }
+    virtual bool handleItem(ScriptValue thisValue, FontFace*, FontFace*, FontFaceSet*) = 0;
+    virtual bool handleItem(FontFace*, FontFace*, FontFaceSet*) = 0;
+};
+
+} // namespace WebCore
+
+#endif // FontFaceSetForEachCallback_h
diff --git a/Source/core/html/HTMLImportDataClient.h b/Source/core/css/FontFaceSetForEachCallback.idl
similarity index 86%
copy from Source/core/html/HTMLImportDataClient.h
copy to Source/core/css/FontFaceSetForEachCallback.idl
index 0c26a22..6b9fdab 100644
--- a/Source/core/html/HTMLImportDataClient.h
+++ b/Source/core/css/FontFaceSetForEachCallback.idl
@@ -28,17 +28,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef HTMLImportDataClient_h
-#define HTMLImportDataClient_h
-
-namespace WebCore {
-
-class HTMLImportDataClient {
-public:
-    virtual ~HTMLImportDataClient() { }
-    virtual void didFinish() = 0;
+callback interface FontFaceSetForEachCallback {
+    [CallWith=ThisValue] boolean handleItem(FontFace fontFace, FontFace fontFaceAgain, FontFaceSet set);
+    boolean handleItem(FontFace fontFace, FontFace fontFaceAgain, FontFaceSet set);
 };
-
-}
-
-#endif // HTMLImportDataClient_h
diff --git a/Source/core/css/FontSize.cpp b/Source/core/css/FontSize.cpp
index d24fd14..4b545c4 100644
--- a/Source/core/css/FontSize.cpp
+++ b/Source/core/css/FontSize.cpp
@@ -31,7 +31,7 @@
 
 #include "CSSValueKeywords.h"
 #include "core/dom/Document.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/HoverUpdateTest.cpp b/Source/core/css/HoverUpdateTest.cpp
new file mode 100644
index 0000000..23845c6
--- /dev/null
+++ b/Source/core/css/HoverUpdateTest.cpp
@@ -0,0 +1,49 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "HTMLNames.h"
+#include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/html/HTMLDocument.h"
+#include "core/html/HTMLElement.h"
+#include "core/page/EventHandler.h"
+#include "core/testing/DummyPageHolder.h"
+#include "platform/PlatformMouseEvent.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+TEST(HoverUpdateTest, AffectedByHoverUpdate)
+{
+    // Check that when hovering the div in the document below, you only get a
+    // single element style recalc.
+
+    OwnPtr<DummyPageHolder> dummyPageHolder = DummyPageHolder::create(IntSize(800, 600));
+    HTMLDocument* document = toHTMLDocument(&dummyPageHolder->document());
+    document->documentElement()->setInnerHTML("<style>div {width:100px;height:100px} div:hover { background-color: green }</style>"
+        "<div>"
+        "<span></span>"
+        "<span></span>"
+        "<span></span>"
+        "<span></span>"
+        "</div>", ASSERT_NO_EXCEPTION);
+
+    document->view()->updateLayoutAndStyleIfNeededRecursive();
+    unsigned startCount = document->styleEngine()->resolverAccessCount();
+
+    PlatformMouseEvent moveEvent(IntPoint(20, 20), IntPoint(20, 20), NoButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
+    document->frame()->eventHandler().handleMouseMoveEvent(moveEvent);
+    document->view()->updateLayoutAndStyleIfNeededRecursive();
+
+    unsigned accessCount = document->styleEngine()->resolverAccessCount() - startCount;
+
+    ASSERT_EQ(1U, accessCount);
+}
+
+} // namespace
diff --git a/Source/core/css/InspectorCSSOMWrappers.cpp b/Source/core/css/InspectorCSSOMWrappers.cpp
deleted file mode 100644
index 5a99c07..0000000
--- a/Source/core/css/InspectorCSSOMWrappers.cpp
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
- * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
- * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
- * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/css/InspectorCSSOMWrappers.h"
-
-#include "core/css/CSSDefaultStyleSheets.h"
-#include "core/css/CSSImportRule.h"
-#include "core/css/CSSMediaRule.h"
-#include "core/css/CSSRegionRule.h"
-#include "core/css/CSSRule.h"
-#include "core/css/CSSStyleRule.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/CSSSupportsRule.h"
-#include "core/css/StyleSheetContents.h"
-#include "core/dom/StyleEngine.h"
-
-namespace WebCore {
-
-void InspectorCSSOMWrappers::collectFromStyleSheetIfNeeded(CSSStyleSheet* styleSheet)
-{
-    if (!m_styleRuleToCSSOMWrapperMap.isEmpty())
-        collect(styleSheet);
-}
-
-void InspectorCSSOMWrappers::reset()
-{
-    m_styleRuleToCSSOMWrapperMap.clear();
-    m_styleSheetCSSOMWrapperSet.clear();
-}
-
-template <class ListType>
-void InspectorCSSOMWrappers::collect(ListType* listType)
-{
-    if (!listType)
-        return;
-    unsigned size = listType->length();
-    for (unsigned i = 0; i < size; ++i) {
-        CSSRule* cssRule = listType->item(i);
-        switch (cssRule->type()) {
-        case CSSRule::IMPORT_RULE:
-            collect(toCSSImportRule(cssRule)->styleSheet());
-            break;
-        case CSSRule::MEDIA_RULE:
-            collect(toCSSMediaRule(cssRule));
-            break;
-        case CSSRule::SUPPORTS_RULE:
-            collect(toCSSSupportsRule(cssRule));
-            break;
-        case CSSRule::WEBKIT_REGION_RULE:
-            collect(toCSSRegionRule(cssRule));
-            break;
-        case CSSRule::STYLE_RULE:
-            m_styleRuleToCSSOMWrapperMap.add(toCSSStyleRule(cssRule)->styleRule(), toCSSStyleRule(cssRule));
-            break;
-        default:
-            break;
-        }
-    }
-}
-
-void InspectorCSSOMWrappers::collectFromStyleSheetContents(HashSet<RefPtr<CSSStyleSheet> >& sheetWrapperSet, StyleSheetContents* styleSheet)
-{
-    if (!styleSheet)
-        return;
-    RefPtr<CSSStyleSheet> styleSheetWrapper = CSSStyleSheet::create(styleSheet);
-    sheetWrapperSet.add(styleSheetWrapper);
-    collect(styleSheetWrapper.get());
-}
-
-void InspectorCSSOMWrappers::collectFromStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& sheets)
-{
-    for (unsigned i = 0; i < sheets.size(); ++i)
-        collect(sheets[i].get());
-}
-
-void InspectorCSSOMWrappers::collectFromStyleEngine(StyleEngine* styleSheetCollection)
-{
-    Vector<const Vector<RefPtr<CSSStyleSheet> >*> activeAuthorStyleSheets;
-    styleSheetCollection->getActiveAuthorStyleSheets(activeAuthorStyleSheets);
-    for (size_t i = 0; i < activeAuthorStyleSheets.size(); ++i)
-        collectFromStyleSheets(*activeAuthorStyleSheets[i]);
-}
-
-CSSStyleRule* InspectorCSSOMWrappers::getWrapperForRuleInSheets(StyleRule* rule, StyleEngine* styleSheetCollection)
-{
-    if (m_styleRuleToCSSOMWrapperMap.isEmpty()) {
-        collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::defaultStyleSheet);
-        collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::viewportStyleSheet);
-        collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::quirksStyleSheet);
-        collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::svgStyleSheet);
-        collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::mediaControlsStyleSheet);
-        collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::fullscreenStyleSheet);
-
-        collectFromStyleEngine(styleSheetCollection);
-    }
-    return m_styleRuleToCSSOMWrapperMap.get(rule);
-}
-
-} // namespace WebCore
diff --git a/Source/core/css/InspectorCSSOMWrappers.h b/Source/core/css/InspectorCSSOMWrappers.h
deleted file mode 100644
index fda8789..0000000
--- a/Source/core/css/InspectorCSSOMWrappers.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef InspectorCSSOMWrappers_h
-#define InspectorCSSOMWrappers_h
-
-#include "wtf/Forward.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class CSSStyleRule;
-class CSSStyleSheet;
-class StyleRule;
-class StyleEngine;
-class StyleSheetContents;
-
-class InspectorCSSOMWrappers {
-public:
-    // WARNING. This will construct CSSOM wrappers for all style rules and cache them in a map for significant memory cost.
-    // It is here to support inspector. Don't use for any regular engine functions.
-    CSSStyleRule* getWrapperForRuleInSheets(StyleRule*, StyleEngine*);
-    void collectFromStyleSheetIfNeeded(CSSStyleSheet*);
-    void reset();
-
-private:
-    template <class ListType>
-    void collect(ListType*);
-
-    void collectFromStyleSheetContents(HashSet<RefPtr<CSSStyleSheet> >& sheetWrapperSet, StyleSheetContents*);
-    void collectFromStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&);
-    void collectFromStyleEngine(StyleEngine*);
-
-    HashMap<StyleRule*, RefPtr<CSSStyleRule> > m_styleRuleToCSSOMWrapperMap;
-    HashSet<RefPtr<CSSStyleSheet> > m_styleSheetCSSOMWrapperSet;
-};
-
-} // namespace WebCore
-
-#endif // InspectorCSSOMWrappers_h
diff --git a/Source/core/css/MediaFeatureNames.h b/Source/core/css/MediaFeatureNames.h
index b249625..7624372 100644
--- a/Source/core/css/MediaFeatureNames.h
+++ b/Source/core/css/MediaFeatureNames.h
@@ -27,7 +27,6 @@
 namespace MediaFeatureNames {
 
 #define CSS_MEDIAQUERY_NAMES_FOR_EACH_MEDIAFEATURE(macro) \
-    macro(deprecatedTransition, "-webkit-transition") \
     macro(color, "color") \
     macro(colorIndex, "color-index") \
     macro(grid, "grid") \
diff --git a/Source/core/css/MediaList.cpp b/Source/core/css/MediaList.cpp
index 4a4442f..11ae84b 100644
--- a/Source/core/css/MediaList.cpp
+++ b/Source/core/css/MediaList.cpp
@@ -21,7 +21,7 @@
 #include "core/css/MediaList.h"
 
 #include "bindings/v8/ExceptionState.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/MediaFeatureNames.h"
 #include "core/css/MediaQuery.h"
@@ -73,7 +73,7 @@
     if (mediaString.isEmpty())
         return MediaQuerySet::create();
 
-    CSSParser parser(HTMLStandardMode);
+    BisonCSSParser parser(strictCSSParserContext());
     return parser.parseMediaQueryList(mediaString);
 }
 
@@ -201,7 +201,7 @@
 
     bool success = m_mediaQueries->remove(medium);
     if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "Failed to delete '" + medium + "'.");
         return;
     }
     if (m_parentStyleSheet)
@@ -214,7 +214,7 @@
 
     bool success = m_mediaQueries->add(medium);
     if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwDOMException(InvalidCharacterError, "The value provided ('" + medium + "') is not a valid medium.");
         return;
     }
 
@@ -239,17 +239,17 @@
     DEFINE_STATIC_LOCAL(String, lengthUnitInch, ("inch"));
     DEFINE_STATIC_LOCAL(String, lengthUnitCentimeter, ("centimeter"));
 
-    String message;
+    StringBuilder message;
     if (value->isDotsPerInch())
-        message = String(mediaQueryMessage).replace("%replacementUnits%", mediaValueDPI).replace("%lengthUnit%", lengthUnitInch);
+        message.append(String(mediaQueryMessage).replace("%replacementUnits%", mediaValueDPI).replace("%lengthUnit%", lengthUnitInch));
     else if (value->isDotsPerCentimeter())
-        message = String(mediaQueryMessage).replace("%replacementUnits%", mediaValueDPCM).replace("%lengthUnit%", lengthUnitCentimeter);
+        message.append(String(mediaQueryMessage).replace("%replacementUnits%", mediaValueDPCM).replace("%lengthUnit%", lengthUnitCentimeter));
     else
         ASSERT_NOT_REACHED();
 
     message.append(serializedExpression);
 
-    document->addConsoleMessage(CSSMessageSource, DebugMessageLevel, message);
+    document->addConsoleMessage(CSSMessageSource, DebugMessageLevel, message.toString());
 }
 
 static inline bool isResolutionMediaFeature(const AtomicString& mediaFeature)
diff --git a/Source/core/css/MediaQueryEvaluator.cpp b/Source/core/css/MediaQueryEvaluator.cpp
index 47a9bae..07006bb 100644
--- a/Source/core/css/MediaQueryEvaluator.cpp
+++ b/Source/core/css/MediaQueryEvaluator.cpp
@@ -40,11 +40,11 @@
 #include "core/css/MediaQuery.h"
 #include "core/css/resolver/MediaQueryResult.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/inspector/InspectorInstrumentation.h"
 #include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/RenderStyle.h"
@@ -189,7 +189,7 @@
 
 static bool colorMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
 {
-    int bitsPerComponent = screenDepthPerComponent(frame->page()->mainFrame()->view());
+    int bitsPerComponent = screenDepthPerComponent(frame->view());
     float number;
     if (value)
         return numberValue(value, number) && compareValue(bitsPerComponent, static_cast<int>(number), op);
@@ -211,7 +211,7 @@
 
 static bool monochromeMediaFeatureEval(CSSValue* value, RenderStyle* style, Frame* frame, MediaFeaturePrefix op)
 {
-    if (!screenIsMonochrome(frame->page()->mainFrame()->view())) {
+    if (!screenIsMonochrome(frame->view())) {
         if (value) {
             float number;
             return numberValue(value, number) && compareValue(0, static_cast<int>(number), op);
@@ -258,7 +258,7 @@
 static bool deviceAspectRatioMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
 {
     if (value) {
-        FloatRect sg = screenRect(frame->page()->mainFrame()->view());
+        FloatRect sg = screenRect(frame->view());
         return compareAspectRatioValue(value, static_cast<int>(sg.width()), static_cast<int>(sg.height()), op);
     }
 
@@ -317,6 +317,8 @@
 
 static bool devicePixelRatioMediaFeatureEval(CSSValue *value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
 {
+    UseCounter::count(frame->document(), UseCounter::PrefixedDevicePixelRatioMediaFeature);
+
     return (!value || toCSSPrimitiveValue(value)->isNumber()) && evalResolution(value, frame, op);
 }
 
@@ -350,7 +352,8 @@
     if (primitiveValue->isLength()) {
         // Relative (like EM) and root relative (like REM) units are always resolved against
         // the initial values for media queries, hence the two initialStyle parameters.
-        result = primitiveValue->computeLength<int>(CSSToLengthConversionData(initialStyle, initialStyle, 1.0 /* zoom */, true /* computingFontSize */));
+        // FIXME: We need to plumb viewport unit support down to here.
+        result = primitiveValue->computeLength<int>(CSSToLengthConversionData(initialStyle, initialStyle, 0, 1.0 /* zoom */, true /* computingFontSize */));
         return true;
     }
 
@@ -363,9 +366,9 @@
         int length;
         if (!computeLength(value, !frame->document()->inQuirksMode(), style, length))
             return false;
-        int height = static_cast<int>(screenRect(frame->page()->mainFrame()->view()).height());
+        int height = static_cast<int>(screenRect(frame->view()).height());
         if (frame->settings()->reportScreenSizeInPhysicalPixelsQuirk())
-            height = lroundf(height * frame->page()->deviceScaleFactor());
+            height = lroundf(height * frame->host()->deviceScaleFactor());
         return compareValue(height, length, op);
     }
     // ({,min-,max-}device-height)
@@ -379,9 +382,9 @@
         int length;
         if (!computeLength(value, !frame->document()->inQuirksMode(), style, length))
             return false;
-        int width = static_cast<int>(screenRect(frame->page()->mainFrame()->view()).width());
+        int width = static_cast<int>(screenRect(frame->view()).width());
         if (frame->settings()->reportScreenSizeInPhysicalPixelsQuirk())
-            width = lroundf(width * frame->page()->deviceScaleFactor());
+            width = lroundf(width * frame->host()->deviceScaleFactor());
         return compareValue(width, length, op);
     }
     // ({,min-,max-}device-width)
@@ -473,11 +476,15 @@
 
 static bool minDevicePixelRatioMediaFeatureEval(CSSValue* value, RenderStyle* style, Frame* frame, MediaFeaturePrefix)
 {
+    UseCounter::count(frame->document(), UseCounter::PrefixedMinDevicePixelRatioMediaFeature);
+
     return devicePixelRatioMediaFeatureEval(value, style, frame, MinPrefix);
 }
 
 static bool maxDevicePixelRatioMediaFeatureEval(CSSValue* value, RenderStyle* style, Frame* frame, MediaFeaturePrefix)
 {
+    UseCounter::count(frame->document(), UseCounter::PrefixedMaxDevicePixelRatioMediaFeature);
+
     return devicePixelRatioMediaFeatureEval(value, style, frame, MaxPrefix);
 }
 
@@ -531,18 +538,9 @@
     return resolutionMediaFeatureEval(value, style, frame, MaxPrefix);
 }
 
-static bool animationMediaFeatureEval(CSSValue* value, RenderStyle*, Frame*, MediaFeaturePrefix op)
+static bool animationMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
 {
-    if (value) {
-        float number;
-        return numberValue(value, number) && compareValue(1, static_cast<int>(number), op);
-    }
-    return true;
-}
-
-static bool deprecatedTransitionMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
-{
-    UseCounter::countDeprecation(frame->document(), UseCounter::PrefixedTransitionMediaFeature);
+    UseCounter::count(frame->document(), UseCounter::PrefixedAnimationMediaFeature);
 
     if (value) {
         float number;
@@ -551,8 +549,10 @@
     return true;
 }
 
-static bool transform2dMediaFeatureEval(CSSValue* value, RenderStyle*, Frame*, MediaFeaturePrefix op)
+static bool transform2dMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
 {
+    UseCounter::count(frame->document(), UseCounter::PrefixedTransform2dMediaFeature);
+
     if (value) {
         float number;
         return numberValue(value, number) && compareValue(1, static_cast<int>(number), op);
@@ -562,6 +562,8 @@
 
 static bool transform3dMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
 {
+    UseCounter::count(frame->document(), UseCounter::PrefixedTransform3dMediaFeature);
+
     bool returnValueIfNoParameter;
     int have3dRendering;
 
@@ -581,6 +583,8 @@
 
 static bool viewModeMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix)
 {
+    UseCounter::count(frame->document(), UseCounter::PrefixedViewModeMediaFeature);
+
     if (!value)
         return true;
 
diff --git a/Source/core/css/MediaQueryExp.cpp b/Source/core/css/MediaQueryExp.cpp
index 05c0e5c..a7c5cf5 100644
--- a/Source/core/css/MediaQueryExp.cpp
+++ b/Source/core/css/MediaQueryExp.cpp
@@ -32,7 +32,7 @@
 
 #include "CSSValueKeywords.h"
 #include "core/css/CSSAspectRatioValue.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -129,7 +129,6 @@
 
     return mediaFeature == MediaFeatureNames::transform2dMediaFeature
         || mediaFeature == MediaFeatureNames::transform3dMediaFeature
-        || mediaFeature == MediaFeatureNames::deprecatedTransitionMediaFeature
         || mediaFeature == MediaFeatureNames::animationMediaFeature
         || mediaFeature == MediaFeatureNames::devicePixelRatioMediaFeature
         || mediaFeature == MediaFeatureNames::maxDevicePixelRatioMediaFeature
@@ -172,7 +171,6 @@
         || mediaFeature == MediaFeatureNames::hoverMediaFeature
         || mediaFeature == MediaFeatureNames::transform2dMediaFeature
         || mediaFeature == MediaFeatureNames::transform3dMediaFeature
-        || mediaFeature == MediaFeatureNames::deprecatedTransitionMediaFeature
         || mediaFeature == MediaFeatureNames::animationMediaFeature
         || mediaFeature == MediaFeatureNames::viewModeMediaFeature
         || mediaFeature == MediaFeatureNames::pointerMediaFeature
diff --git a/Source/core/css/Pair.cpp b/Source/core/css/Pair.cpp
new file mode 100644
index 0000000..650b213
--- /dev/null
+++ b/Source/core/css/Pair.cpp
@@ -0,0 +1,18 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/css/Pair.h"
+
+namespace WebCore {
+
+DEFINE_GC_INFO(Pair);
+
+void Pair::trace(Visitor* visitor)
+{
+    visitor->trace(m_first);
+    visitor->trace(m_second);
+}
+
+}
diff --git a/Source/core/css/Pair.h b/Source/core/css/Pair.h
index fc2edaa..e36d8d4 100644
--- a/Source/core/css/Pair.h
+++ b/Source/core/css/Pair.h
@@ -32,25 +32,23 @@
 // and border-spacing (all of which are space-separated sets of two values).  At the moment we are only using it for
 // border-radius and background-size, but (FIXME) border-spacing and background-position could be converted over to use
 // it (eliminating some extra -webkit- internal properties).
-class Pair FINAL : public RefCounted<Pair> {
+class Pair FINAL : public RefCountedWillBeGarbageCollected<Pair> {
+    DECLARE_GC_INFO;
 public:
     enum IdenticalValuesPolicy { DropIdenticalValues, KeepIdenticalValues };
 
-    static PassRefPtr<Pair> create()
+    static PassRefPtrWillBeRawPtr<Pair> create(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> first, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> second,
+        IdenticalValuesPolicy identicalValuesPolicy)
     {
-        return adoptRef(new Pair);
-    }
-    static PassRefPtr<Pair> create(PassRefPtr<CSSPrimitiveValue> first, PassRefPtr<CSSPrimitiveValue> second, IdenticalValuesPolicy identicalValuesPolicy)
-    {
-        return adoptRef(new Pair(first, second, identicalValuesPolicy));
+        return adoptRefWillBeNoop(new Pair(first, second, identicalValuesPolicy));
     }
 
     CSSPrimitiveValue* first() const { return m_first.get(); }
     CSSPrimitiveValue* second() const { return m_second.get(); }
     IdenticalValuesPolicy identicalValuesPolicy() const { return m_identicalValuesPolicy; }
 
-    void setFirst(PassRefPtr<CSSPrimitiveValue> first) { m_first = first; }
-    void setSecond(PassRefPtr<CSSPrimitiveValue> second) { m_second = second; }
+    void setFirst(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> first) { m_first = first; }
+    void setSecond(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> second) { m_second = second; }
     void setIdenticalValuesPolicy(IdenticalValuesPolicy identicalValuesPolicy) { m_identicalValuesPolicy = identicalValuesPolicy; }
 
     String cssText() const
@@ -65,15 +63,7 @@
             && m_identicalValuesPolicy == other.m_identicalValuesPolicy;
     }
 
-    String serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-    {
-        return generateCSSString(
-            first()->customSerializeResolvingVariables(variables),
-            second()->customSerializeResolvingVariables(variables),
-            m_identicalValuesPolicy);
-    }
-
-    bool hasVariableReference() const { return first()->hasVariableReference() || second()->hasVariableReference(); }
+    void trace(Visitor*);
 
 private:
     Pair()
@@ -81,7 +71,7 @@
         , m_second(0)
         , m_identicalValuesPolicy(DropIdenticalValues) { }
 
-    Pair(PassRefPtr<CSSPrimitiveValue> first, PassRefPtr<CSSPrimitiveValue> second, IdenticalValuesPolicy identicalValuesPolicy)
+    Pair(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> first, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> second, IdenticalValuesPolicy identicalValuesPolicy)
         : m_first(first)
         , m_second(second)
         , m_identicalValuesPolicy(identicalValuesPolicy) { }
@@ -93,8 +83,8 @@
         return first + ' ' + second;
     }
 
-    RefPtr<CSSPrimitiveValue> m_first;
-    RefPtr<CSSPrimitiveValue> m_second;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_first;
+    RefPtrWillBeMember<CSSPrimitiveValue> m_second;
     IdenticalValuesPolicy m_identicalValuesPolicy;
 };
 
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.cpp b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
index e30610a..3b17129 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.cpp
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
@@ -25,12 +25,14 @@
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ExceptionState.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/StylePropertySet.h"
+#include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/MutationObserverInterestGroup.h"
 #include "core/dom/MutationRecord.h"
+#include "core/frame/ContentSecurityPolicy.h"
 #include "core/inspector/InspectorInstrumentation.h"
 
 using namespace std;
@@ -42,7 +44,7 @@
 class StyleAttributeMutationScope {
     WTF_MAKE_NONCOPYABLE(StyleAttributeMutationScope);
 public:
-    StyleAttributeMutationScope(PropertySetCSSStyleDeclaration* decl)
+    StyleAttributeMutationScope(AbstractPropertySetCSSStyleDeclaration* decl)
     {
         InspectorInstrumentation::willMutateStyle(decl);
         ++s_scopeCount;
@@ -86,7 +88,7 @@
         s_shouldDeliver = false;
 
         // We have to clear internal state before calling Inspector's code.
-        PropertySetCSSStyleDeclaration* localCopyStyleDecl = s_currentDecl;
+        AbstractPropertySetCSSStyleDeclaration* localCopyStyleDecl = s_currentDecl;
         s_currentDecl = 0;
         InspectorInstrumentation::didMutateStyle(localCopyStyleDecl, localCopyStyleDecl->parentElement());
 
@@ -110,7 +112,7 @@
 
 private:
     static unsigned s_scopeCount;
-    static PropertySetCSSStyleDeclaration* s_currentDecl;
+    static AbstractPropertySetCSSStyleDeclaration* s_currentDecl;
     static bool s_shouldNotifyInspector;
     static bool s_shouldDeliver;
 
@@ -119,7 +121,7 @@
 };
 
 unsigned StyleAttributeMutationScope::s_scopeCount = 0;
-PropertySetCSSStyleDeclaration* StyleAttributeMutationScope::s_currentDecl = 0;
+AbstractPropertySetCSSStyleDeclaration* StyleAttributeMutationScope::s_currentDecl = 0;
 bool StyleAttributeMutationScope::s_shouldNotifyInspector = false;
 bool StyleAttributeMutationScope::s_shouldDeliver = false;
 
@@ -135,80 +137,88 @@
     m_propertySet->deref();
 }
 
-unsigned PropertySetCSSStyleDeclaration::length() const
+unsigned AbstractPropertySetCSSStyleDeclaration::length() const
 {
-    return m_propertySet->propertyCount();
+    return propertySet()->propertyCount();
 }
 
-String PropertySetCSSStyleDeclaration::item(unsigned i) const
+String AbstractPropertySetCSSStyleDeclaration::item(unsigned i) const
 {
-    if (i >= m_propertySet->propertyCount())
+    if (i >= propertySet()->propertyCount())
         return "";
-    return m_propertySet->propertyAt(i).cssName();
+    return propertySet()->propertyAt(i).cssName();
 }
 
-String PropertySetCSSStyleDeclaration::cssText() const
+String AbstractPropertySetCSSStyleDeclaration::cssText() const
 {
-    return m_propertySet->asText();
+    return propertySet()->asText();
 }
 
-void PropertySetCSSStyleDeclaration::setCSSText(const String& text, ExceptionState& exceptionState)
+void AbstractPropertySetCSSStyleDeclaration::setCSSText(const String& text, ExceptionState& exceptionState)
 {
+    if (parentElement()) {
+        ContentSecurityPolicy* csp = parentElement()->document().contentSecurityPolicy();
+        if (!csp->allowStyleEval()) {
+            exceptionState.throwSecurityError(csp->styleEvalDisabledErrorMessage());
+            return;
+        }
+    }
+
     StyleAttributeMutationScope mutationScope(this);
     willMutate();
 
     // FIXME: Detect syntax errors and set exceptionState.
-    m_propertySet->parseDeclaration(text, contextStyleSheet());
+    propertySet()->parseDeclaration(text, contextStyleSheet());
 
     didMutate(PropertyChanged);
 
     mutationScope.enqueueMutationRecord();
 }
 
-PassRefPtr<CSSValue> PropertySetCSSStyleDeclaration::getPropertyCSSValue(const String& propertyName)
+PassRefPtr<CSSValue> AbstractPropertySetCSSStyleDeclaration::getPropertyCSSValue(const String& propertyName)
 {
     CSSPropertyID propertyID = cssPropertyID(propertyName);
     if (!propertyID)
         return 0;
-    return cloneAndCacheForCSSOM(m_propertySet->getPropertyCSSValue(propertyID).get());
+    return cloneAndCacheForCSSOM(propertySet()->getPropertyCSSValue(propertyID).get());
 }
 
-String PropertySetCSSStyleDeclaration::getPropertyValue(const String &propertyName)
+String AbstractPropertySetCSSStyleDeclaration::getPropertyValue(const String &propertyName)
 {
     CSSPropertyID propertyID = cssPropertyID(propertyName);
     if (!propertyID)
         return String();
-    return m_propertySet->getPropertyValue(propertyID);
+    return propertySet()->getPropertyValue(propertyID);
 }
 
-String PropertySetCSSStyleDeclaration::getPropertyPriority(const String& propertyName)
+String AbstractPropertySetCSSStyleDeclaration::getPropertyPriority(const String& propertyName)
 {
     CSSPropertyID propertyID = cssPropertyID(propertyName);
     if (!propertyID)
         return String();
-    return m_propertySet->propertyIsImportant(propertyID) ? "important" : "";
+    return propertySet()->propertyIsImportant(propertyID) ? "important" : "";
 }
 
-String PropertySetCSSStyleDeclaration::getPropertyShorthand(const String& propertyName)
+String AbstractPropertySetCSSStyleDeclaration::getPropertyShorthand(const String& propertyName)
 {
     CSSPropertyID propertyID = cssPropertyID(propertyName);
     if (!propertyID)
         return String();
-    CSSPropertyID shorthandID = m_propertySet->getPropertyShorthand(propertyID);
+    CSSPropertyID shorthandID = propertySet()->getPropertyShorthand(propertyID);
     if (!shorthandID)
         return String();
     return getPropertyNameString(shorthandID);
 }
 
-bool PropertySetCSSStyleDeclaration::isPropertyImplicit(const String& propertyName)
+bool AbstractPropertySetCSSStyleDeclaration::isPropertyImplicit(const String& propertyName)
 {
     CSSPropertyID propertyID = cssPropertyID(propertyName);
     if (!propertyID)
         return false;
-    return m_propertySet->isPropertyImplicit(propertyID);
+    return propertySet()->isPropertyImplicit(propertyID);
 }
 
-void PropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState& exceptionState)
+void AbstractPropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState& exceptionState)
 {
     StyleAttributeMutationScope mutationScope(this);
     CSSPropertyID propertyID = cssPropertyID(propertyName);
@@ -219,7 +229,7 @@
 
     willMutate();
 
-    bool changed = m_propertySet->setProperty(propertyID, value, important, contextStyleSheet());
+    bool changed = propertySet()->setProperty(propertyID, value, important, contextStyleSheet());
 
     didMutate(changed ? PropertyChanged : NoChanges);
 
@@ -230,7 +240,7 @@
     }
 }
 
-String PropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionState& exceptionState)
+String AbstractPropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionState& exceptionState)
 {
     StyleAttributeMutationScope mutationScope(this);
     CSSPropertyID propertyID = cssPropertyID(propertyName);
@@ -240,7 +250,7 @@
     willMutate();
 
     String result;
-    bool changed = m_propertySet->removeProperty(propertyID, &result);
+    bool changed = propertySet()->removeProperty(propertyID, &result);
 
     didMutate(changed ? PropertyChanged : NoChanges);
 
@@ -249,22 +259,22 @@
     return result;
 }
 
-PassRefPtr<CSSValue> PropertySetCSSStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
+PassRefPtr<CSSValue> AbstractPropertySetCSSStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
 {
-    return m_propertySet->getPropertyCSSValue(propertyID);
+    return propertySet()->getPropertyCSSValue(propertyID);
 }
 
-String PropertySetCSSStyleDeclaration::getPropertyValueInternal(CSSPropertyID propertyID)
+String AbstractPropertySetCSSStyleDeclaration::getPropertyValueInternal(CSSPropertyID propertyID)
 {
-    return m_propertySet->getPropertyValue(propertyID);
+    return propertySet()->getPropertyValue(propertyID);
 }
 
-void PropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionState&)
+void AbstractPropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionState&)
 {
     StyleAttributeMutationScope mutationScope(this);
     willMutate();
 
-    bool changed = m_propertySet->setProperty(propertyID, value, important, contextStyleSheet());
+    bool changed = propertySet()->setProperty(propertyID, value, important, contextStyleSheet());
 
     didMutate(changed ? PropertyChanged : NoChanges);
 
@@ -272,60 +282,7 @@
         mutationScope.enqueueMutationRecord();
 }
 
-unsigned PropertySetCSSStyleDeclaration::variableCount() const
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    return m_propertySet->variableCount();
-}
-
-String PropertySetCSSStyleDeclaration::variableValue(const AtomicString& name) const
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    return m_propertySet->variableValue(name);
-}
-
-bool PropertySetCSSStyleDeclaration::setVariableValue(const AtomicString& name, const String& value, ExceptionState&)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    StyleAttributeMutationScope mutationScope(this);
-    willMutate();
-    bool changed = m_propertySet->setVariableValue(name, value);
-    didMutate(changed ? PropertyChanged : NoChanges);
-    if (changed)
-        mutationScope.enqueueMutationRecord();
-    return changed;
-}
-
-bool PropertySetCSSStyleDeclaration::removeVariable(const AtomicString& name)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    StyleAttributeMutationScope mutationScope(this);
-    willMutate();
-    bool changed = m_propertySet->removeVariable(name);
-    didMutate(changed ? PropertyChanged : NoChanges);
-    if (changed)
-        mutationScope.enqueueMutationRecord();
-    return changed;
-}
-
-bool PropertySetCSSStyleDeclaration::clearVariables(ExceptionState&)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    StyleAttributeMutationScope mutationScope(this);
-    willMutate();
-    bool changed = m_propertySet->clearVariables();
-    didMutate(changed ? PropertyChanged : NoChanges);
-    if (changed)
-        mutationScope.enqueueMutationRecord();
-    return changed;
-}
-
-PassRefPtr<CSSVariablesIterator> PropertySetCSSStyleDeclaration::variablesIterator() const
-{
-    return m_propertySet->variablesIterator();
-}
-
-CSSValue* PropertySetCSSStyleDeclaration::cloneAndCacheForCSSOM(CSSValue* internalValue)
+CSSValue* AbstractPropertySetCSSStyleDeclaration::cloneAndCacheForCSSOM(CSSValue* internalValue)
 {
     if (!internalValue)
         return 0;
@@ -335,30 +292,30 @@
     if (!m_cssomCSSValueClones)
         m_cssomCSSValueClones = adoptPtr(new HashMap<CSSValue*, RefPtr<CSSValue> >);
 
-    RefPtr<CSSValue>& clonedValue = m_cssomCSSValueClones->add(internalValue, RefPtr<CSSValue>()).iterator->value;
+    RefPtr<CSSValue>& clonedValue = m_cssomCSSValueClones->add(internalValue, RefPtr<CSSValue>()).storedValue->value;
     if (!clonedValue)
         clonedValue = internalValue->cloneForCSSOM();
     return clonedValue.get();
 }
 
-StyleSheetContents* PropertySetCSSStyleDeclaration::contextStyleSheet() const
+StyleSheetContents* AbstractPropertySetCSSStyleDeclaration::contextStyleSheet() const
 {
     CSSStyleSheet* cssStyleSheet = parentStyleSheet();
     return cssStyleSheet ? cssStyleSheet->contents() : 0;
 }
 
-PassRefPtr<MutableStylePropertySet> PropertySetCSSStyleDeclaration::copyProperties() const
+PassRefPtr<MutableStylePropertySet> AbstractPropertySetCSSStyleDeclaration::copyProperties() const
 {
-    return m_propertySet->mutableCopy();
+    return propertySet()->mutableCopy();
 }
 
-bool PropertySetCSSStyleDeclaration::cssPropertyMatches(CSSPropertyID propertyID, const CSSValue* propertyValue) const
+bool AbstractPropertySetCSSStyleDeclaration::cssPropertyMatches(CSSPropertyID propertyID, const CSSValue* propertyValue) const
 {
-    return m_propertySet->propertyMatches(propertyID, propertyValue);
+    return propertySet()->propertyMatches(propertyID, propertyValue);
 }
 
-StyleRuleCSSStyleDeclaration::StyleRuleCSSStyleDeclaration(MutableStylePropertySet* propertySet, CSSRule* parentRule)
-    : PropertySetCSSStyleDeclaration(propertySet)
+StyleRuleCSSStyleDeclaration::StyleRuleCSSStyleDeclaration(MutableStylePropertySet* propertySetArg, CSSRule* parentRule)
+    : PropertySetCSSStyleDeclaration(propertySetArg)
     , m_refCount(1)
     , m_parentRule(parentRule)
 {
@@ -411,6 +368,11 @@
     m_propertySet->ref();
 }
 
+MutableStylePropertySet* InlineCSSStyleDeclaration::propertySet() const
+{
+    return m_parentElement->ensureMutableInlineStyle();
+}
+
 void InlineCSSStyleDeclaration::didMutate(MutationType type)
 {
     if (type == NoChanges)
@@ -421,6 +383,7 @@
     if (!m_parentElement)
         return;
 
+    m_parentElement->clearMutableInlineStyleIfEmpty();
     m_parentElement->setNeedsStyleRecalc(LocalStyleChange);
     m_parentElement->invalidateStyleAttribute();
     StyleAttributeMutationScope(this).didInvalidateStyleAttr();
@@ -431,4 +394,14 @@
     return m_parentElement ? m_parentElement->document().elementSheet() : 0;
 }
 
+void InlineCSSStyleDeclaration::ref()
+{
+    m_parentElement->ref();
+}
+
+void InlineCSSStyleDeclaration::deref()
+{
+    m_parentElement->deref();
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.h b/Source/core/css/PropertySetCSSStyleDeclaration.h
index 20b3685..6860e4c 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.h
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.h
@@ -40,43 +40,31 @@
 class MutableStylePropertySet;
 class StyleSheetContents;
 
-class PropertySetCSSStyleDeclaration : public CSSStyleDeclaration {
+class AbstractPropertySetCSSStyleDeclaration : public CSSStyleDeclaration {
 public:
-    PropertySetCSSStyleDeclaration(MutableStylePropertySet* propertySet) : m_propertySet(propertySet) { }
-
     virtual Element* parentElement() const { return 0; }
     virtual void clearParentElement() { ASSERT_NOT_REACHED(); }
     StyleSheetContents* contextStyleSheet() const;
 
-    virtual void ref() OVERRIDE;
-    virtual void deref() OVERRIDE;
-
 private:
-    virtual CSSRule* parentRule() const OVERRIDE { return 0; };
-    virtual unsigned length() const OVERRIDE;
-    virtual String item(unsigned index) const OVERRIDE;
-    virtual PassRefPtr<CSSValue> getPropertyCSSValue(const String& propertyName) OVERRIDE;
-    virtual String getPropertyValue(const String& propertyName) OVERRIDE;
-    virtual String getPropertyPriority(const String& propertyName) OVERRIDE;
-    virtual String getPropertyShorthand(const String& propertyName) OVERRIDE;
-    virtual bool isPropertyImplicit(const String& propertyName) OVERRIDE;
-    virtual void setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState&) OVERRIDE;
-    virtual String removeProperty(const String& propertyName, ExceptionState&) OVERRIDE;
-    virtual String cssText() const OVERRIDE;
-    virtual void setCSSText(const String&, ExceptionState&) OVERRIDE;
-    virtual PassRefPtr<CSSValue> getPropertyCSSValueInternal(CSSPropertyID) OVERRIDE;
-    virtual String getPropertyValueInternal(CSSPropertyID) OVERRIDE;
-    virtual void setPropertyInternal(CSSPropertyID, const String& value, bool important, ExceptionState&) OVERRIDE;
+    virtual CSSRule* parentRule() const OVERRIDE { return 0; }
+    virtual unsigned length() const OVERRIDE FINAL;
+    virtual String item(unsigned index) const OVERRIDE FINAL;
+    virtual PassRefPtr<CSSValue> getPropertyCSSValue(const String& propertyName) OVERRIDE FINAL;
+    virtual String getPropertyValue(const String& propertyName) OVERRIDE FINAL;
+    virtual String getPropertyPriority(const String& propertyName) OVERRIDE FINAL;
+    virtual String getPropertyShorthand(const String& propertyName) OVERRIDE FINAL;
+    virtual bool isPropertyImplicit(const String& propertyName) OVERRIDE FINAL;
+    virtual void setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState&) OVERRIDE FINAL;
+    virtual String removeProperty(const String& propertyName, ExceptionState&) OVERRIDE FINAL;
+    virtual String cssText() const OVERRIDE FINAL;
+    virtual void setCSSText(const String&, ExceptionState&) OVERRIDE FINAL;
+    virtual PassRefPtr<CSSValue> getPropertyCSSValueInternal(CSSPropertyID) OVERRIDE FINAL;
+    virtual String getPropertyValueInternal(CSSPropertyID) OVERRIDE FINAL;
+    virtual void setPropertyInternal(CSSPropertyID, const String& value, bool important, ExceptionState&) OVERRIDE FINAL;
 
-    virtual unsigned variableCount() const OVERRIDE;
-    virtual String variableValue(const AtomicString& name) const OVERRIDE;
-    virtual bool setVariableValue(const AtomicString& name, const String& value, ExceptionState&) OVERRIDE;
-    virtual bool removeVariable(const AtomicString& name) OVERRIDE;
-    virtual bool clearVariables(ExceptionState&) OVERRIDE;
-    virtual PassRefPtr<CSSVariablesIterator> variablesIterator() const OVERRIDE;
-
-    virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const OVERRIDE;
-    virtual PassRefPtr<MutableStylePropertySet> copyProperties() const OVERRIDE;
+    virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const OVERRIDE FINAL;
+    virtual PassRefPtr<MutableStylePropertySet> copyProperties() const OVERRIDE FINAL;
 
     CSSValue* cloneAndCacheForCSSOM(CSSValue*);
 
@@ -84,12 +72,25 @@
     enum MutationType { NoChanges, PropertyChanged };
     virtual void willMutate() { }
     virtual void didMutate(MutationType) { }
+    virtual MutableStylePropertySet* propertySet() const = 0;
 
-    MutableStylePropertySet* m_propertySet;
     OwnPtr<HashMap<CSSValue*, RefPtr<CSSValue> > > m_cssomCSSValueClones;
 };
 
-class StyleRuleCSSStyleDeclaration : public PropertySetCSSStyleDeclaration
+class PropertySetCSSStyleDeclaration : public AbstractPropertySetCSSStyleDeclaration {
+public:
+    PropertySetCSSStyleDeclaration(MutableStylePropertySet* propertySet) : m_propertySet(propertySet) { }
+
+    virtual void ref() OVERRIDE;
+    virtual void deref() OVERRIDE;
+
+protected:
+    virtual MutableStylePropertySet* propertySet() const OVERRIDE FINAL { return m_propertySet; }
+
+    MutableStylePropertySet* m_propertySet;
+};
+
+class StyleRuleCSSStyleDeclaration FINAL : public PropertySetCSSStyleDeclaration
 {
 public:
     static PassRefPtr<StyleRuleCSSStyleDeclaration> create(MutableStylePropertySet* propertySet, CSSRule* parentRule)
@@ -119,16 +120,18 @@
     CSSRule* m_parentRule;
 };
 
-class InlineCSSStyleDeclaration : public PropertySetCSSStyleDeclaration
+class InlineCSSStyleDeclaration FINAL : public AbstractPropertySetCSSStyleDeclaration
 {
 public:
-    InlineCSSStyleDeclaration(MutableStylePropertySet* propertySet, Element* parentElement)
-        : PropertySetCSSStyleDeclaration(propertySet)
-        , m_parentElement(parentElement)
+    explicit InlineCSSStyleDeclaration(Element* parentElement)
+        : m_parentElement(parentElement)
     {
     }
 
 private:
+    virtual MutableStylePropertySet* propertySet() const OVERRIDE;
+    virtual void ref() OVERRIDE;
+    virtual void deref() OVERRIDE;
     virtual CSSStyleSheet* parentStyleSheet() const OVERRIDE;
     virtual Element* parentElement() const OVERRIDE { return m_parentElement; }
     virtual void clearParentElement() OVERRIDE { m_parentElement = 0; }
diff --git a/Source/core/css/RGBColor.cpp b/Source/core/css/RGBColor.cpp
index 6b131d0..b441d4e 100644
--- a/Source/core/css/RGBColor.cpp
+++ b/Source/core/css/RGBColor.cpp
@@ -35,34 +35,34 @@
     return adoptRef(new RGBColor(rgbColor));
 }
 
-PassRefPtr<CSSPrimitiveValue> RGBColor::red()
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> RGBColor::red()
 {
     unsigned value = (m_rgbColor >> 16) & 0xFF;
-    RefPtr<CSSPrimitiveValue> result = CSSPrimitiveValue::create(value, CSSPrimitiveValue::CSS_NUMBER);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> result = CSSPrimitiveValue::create(value, CSSPrimitiveValue::CSS_NUMBER);
     result->setCSSOMSafe();
     return result.release();
 }
 
-PassRefPtr<CSSPrimitiveValue> RGBColor::green()
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> RGBColor::green()
 {
     unsigned value = (m_rgbColor >> 8) & 0xFF;
-    RefPtr<CSSPrimitiveValue> result = CSSPrimitiveValue::create(value, CSSPrimitiveValue::CSS_NUMBER);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> result = CSSPrimitiveValue::create(value, CSSPrimitiveValue::CSS_NUMBER);
     result->setCSSOMSafe();
     return result.release();
 }
 
-PassRefPtr<CSSPrimitiveValue> RGBColor::blue()
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> RGBColor::blue()
 {
     unsigned value = m_rgbColor & 0xFF;
-    RefPtr<CSSPrimitiveValue> result = CSSPrimitiveValue::create(value, CSSPrimitiveValue::CSS_NUMBER);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> result = CSSPrimitiveValue::create(value, CSSPrimitiveValue::CSS_NUMBER);
     result->setCSSOMSafe();
     return result.release();
 }
 
-PassRefPtr<CSSPrimitiveValue> RGBColor::alpha()
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> RGBColor::alpha()
 {
     float value = static_cast<float>((m_rgbColor >> 24) & 0xFF) / 0xFF;
-    RefPtr<CSSPrimitiveValue> result = CSSPrimitiveValue::create(value, CSSPrimitiveValue::CSS_NUMBER);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> result = CSSPrimitiveValue::create(value, CSSPrimitiveValue::CSS_NUMBER);
     result->setCSSOMSafe();
     return result.release();
 }
diff --git a/Source/core/css/RGBColor.h b/Source/core/css/RGBColor.h
index 5cd4697..6ed676e 100644
--- a/Source/core/css/RGBColor.h
+++ b/Source/core/css/RGBColor.h
@@ -38,10 +38,10 @@
     public:
         static PassRefPtr<RGBColor> create(unsigned rgbColor);
 
-        PassRefPtr<CSSPrimitiveValue> red();
-        PassRefPtr<CSSPrimitiveValue> green();
-        PassRefPtr<CSSPrimitiveValue> blue();
-        PassRefPtr<CSSPrimitiveValue> alpha();
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> red();
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> green();
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> blue();
+        PassRefPtrWillBeRawPtr<CSSPrimitiveValue> alpha();
 
         Color color() const { return Color(m_rgbColor); }
 
diff --git a/Source/core/css/Rect.h b/Source/core/css/Rect.h
index 21978cd..3808888 100644
--- a/Source/core/css/Rect.h
+++ b/Source/core/css/Rect.h
@@ -34,10 +34,10 @@
     CSSPrimitiveValue* bottom() const { return m_bottom.get(); }
     CSSPrimitiveValue* left() const { return m_left.get(); }
 
-    void setTop(PassRefPtr<CSSPrimitiveValue> top) { m_top = top; }
-    void setRight(PassRefPtr<CSSPrimitiveValue> right) { m_right = right; }
-    void setBottom(PassRefPtr<CSSPrimitiveValue> bottom) { m_bottom = bottom; }
-    void setLeft(PassRefPtr<CSSPrimitiveValue> left) { m_left = left; }
+    void setTop(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> top) { m_top = top; }
+    void setRight(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> right) { m_right = right; }
+    void setBottom(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> bottom) { m_bottom = bottom; }
+    void setLeft(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> left) { m_left = left; }
 
     bool equals(const RectBase& other) const
     {
@@ -47,14 +47,6 @@
             && compareCSSValuePtr(m_bottom, other.m_bottom);
     }
 
-    bool hasVariableReference() const
-    {
-        return m_top->hasVariableReference()
-            || m_right->hasVariableReference()
-            || m_bottom->hasVariableReference()
-            || m_left->hasVariableReference();
-    }
-
 protected:
     RectBase() { }
     RectBase(const RectBase& cloneFrom)
@@ -85,14 +77,6 @@
         return generateCSSString(top()->cssText(), right()->cssText(), bottom()->cssText(), left()->cssText());
     }
 
-    String serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-    {
-        return generateCSSString(top()->customSerializeResolvingVariables(variables),
-            right()->customSerializeResolvingVariables(variables),
-            bottom()->customSerializeResolvingVariables(variables),
-            left()->customSerializeResolvingVariables(variables));
-    }
-
 private:
     Rect() { }
     Rect(const Rect& cloneFrom) : RectBase(cloneFrom), RefCounted<Rect>() { }
@@ -113,14 +97,6 @@
         return generateCSSString(top()->cssText(), right()->cssText(), bottom()->cssText(), left()->cssText());
     }
 
-    String serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
-    {
-        return generateCSSString(top()->customSerializeResolvingVariables(variables),
-            right()->customSerializeResolvingVariables(variables),
-            bottom()->customSerializeResolvingVariables(variables),
-            left()->customSerializeResolvingVariables(variables));
-    }
-
 private:
     Quad() { }
     Quad(const Quad& cloneFrom) : RectBase(cloneFrom), RefCounted<Quad>() { }
diff --git a/Source/core/css/RuleFeature.cpp b/Source/core/css/RuleFeature.cpp
index 7c8f160..b52569a 100644
--- a/Source/core/css/RuleFeature.cpp
+++ b/Source/core/css/RuleFeature.cpp
@@ -30,69 +30,399 @@
 #include "core/css/RuleFeature.h"
 
 #include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSSelectorList.h"
+#include "core/css/RuleSet.h"
+#include "core/dom/Document.h"
+#include "core/dom/Element.h"
+#include "core/dom/Node.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "wtf/BitVector.h"
 
 namespace WebCore {
 
-void RuleFeatureSet::collectFeaturesFromSelector(const CSSSelector* selector)
+static bool isSkippableComponentForInvalidation(const CSSSelector& selector)
 {
-    if (selector->m_match == CSSSelector::Id)
-        idsInRules.add(selector->value());
-    else if (selector->m_match == CSSSelector::Class)
-        classesInRules.add(selector->value());
-    else if (selector->isAttributeSelector())
-        attrsInRules.add(selector->attribute().localName());
-    switch (selector->pseudoType()) {
-    case CSSSelector::PseudoFirstLine:
-        m_usesFirstLineRules = true;
-        break;
-        break;
-    case CSSSelector::PseudoHost:
-        collectFeaturesFromSelectorList(selector->selectorList());
-        break;
-    default:
-        break;
-    }
+    if (selector.matchesPseudoElement() || selector.pseudoType() == CSSSelector::PseudoHost)
+        return false;
+    return true;
 }
 
-void RuleFeatureSet::collectFeaturesFromSelectorList(const CSSSelectorList* selectorList)
+// This method is somewhat conservative in what it acceptss.
+static bool supportsClassDescendantInvalidation(const CSSSelector& selector)
+{
+    bool foundDescendantRelation = false;
+    bool foundAncestorIdent = false;
+    bool foundIdent = false;
+    for (const CSSSelector* component = &selector; component; component = component->tagHistory()) {
+
+        // FIXME: We should allow pseudo elements, but we need to change how they hook
+        // into recalcStyle by moving them to recalcOwnStyle instead of recalcChildStyle.
+
+        // FIXME: next up: Tag and Id.
+        if (component->m_match == CSSSelector::Class) {
+            if (!foundDescendantRelation)
+                foundIdent = true;
+            else
+                foundAncestorIdent = true;
+        } else if (!isSkippableComponentForInvalidation(*component)) {
+            return false;
+        }
+        // FIXME: We can probably support ChildTree and DescendantTree.
+        switch (component->relation()) {
+        case CSSSelector::Descendant:
+        case CSSSelector::Child:
+            foundDescendantRelation = true;
+            // Fall through!
+        case CSSSelector::SubSelector:
+            continue;
+        default:
+            return false;
+        }
+    }
+    return foundDescendantRelation && foundAncestorIdent && foundIdent;
+}
+
+void extractClassIdOrTag(const CSSSelector& selector, Vector<AtomicString>& classes, AtomicString& id, AtomicString& tagName)
+{
+    if (selector.m_match == CSSSelector::Tag)
+        tagName = selector.tagQName().localName();
+    else if (selector.m_match == CSSSelector::Id)
+        id = selector.value();
+    else if (selector.m_match == CSSSelector::Class)
+        classes.append(selector.value());
+}
+
+RuleFeatureSet::RuleFeatureSet()
+    : m_targetedStyleRecalcEnabled(RuntimeEnabledFeatures::targetedStyleRecalcEnabled())
+{
+}
+
+bool RuleFeatureSet::updateClassInvalidationSets(const CSSSelector& selector)
+{
+    if (!supportsClassDescendantInvalidation(selector))
+        return false;
+
+    Vector<AtomicString> classes;
+    AtomicString id;
+    AtomicString tagName;
+
+    const CSSSelector* lastSelector = &selector;
+    for (; lastSelector->relation() == CSSSelector::SubSelector; lastSelector = lastSelector->tagHistory()) {
+        extractClassIdOrTag(*lastSelector, classes, id, tagName);
+    }
+    extractClassIdOrTag(*lastSelector, classes, id, tagName);
+
+    for (const CSSSelector* current = &selector ; current; current = current->tagHistory()) {
+        if (current->m_match == CSSSelector::Class) {
+            DescendantInvalidationSet& invalidationSet = ensureClassInvalidationSet(current->value());
+            if (!id.isEmpty())
+                invalidationSet.addId(id);
+            if (!tagName.isEmpty())
+                invalidationSet.addTagName(tagName);
+            for (Vector<AtomicString>::const_iterator it = classes.begin(); it != classes.end(); ++it) {
+                invalidationSet.addClass(*it);
+            }
+        }
+    }
+    return true;
+}
+
+void RuleFeatureSet::addAttributeInASelector(const AtomicString& attributeName)
+{
+    m_metadata.attrsInRules.add(attributeName);
+}
+
+void RuleFeatureSet::collectFeaturesFromRuleData(const RuleData& ruleData)
+{
+    FeatureMetadata metadata;
+    bool selectorUsesClassInvalidationSet = false;
+    if (m_targetedStyleRecalcEnabled)
+        selectorUsesClassInvalidationSet = updateClassInvalidationSets(ruleData.selector());
+
+    SelectorFeatureCollectionMode collectionMode;
+    if (selectorUsesClassInvalidationSet)
+        collectionMode = DontProcessClasses;
+    else
+        collectionMode = ProcessClasses;
+    collectFeaturesFromSelector(ruleData.selector(), metadata, collectionMode);
+    m_metadata.add(metadata);
+
+    if (metadata.foundSiblingSelector)
+        siblingRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
+    if (ruleData.containsUncommonAttributeSelector())
+        uncommonAttributeRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
+}
+
+bool RuleFeatureSet::classInvalidationRequiresSubtreeRecalc(const AtomicString& className)
+{
+    DescendantInvalidationSet* set = m_classInvalidationSets.get(className);
+    return set && set->wholeSubtreeInvalid();
+}
+
+DescendantInvalidationSet& RuleFeatureSet::ensureClassInvalidationSet(const AtomicString& className)
+{
+    InvalidationSetMap::AddResult addResult = m_classInvalidationSets.add(className, 0);
+    if (addResult.isNewEntry)
+        addResult.storedValue->value = DescendantInvalidationSet::create();
+    return *addResult.storedValue->value;
+}
+
+void RuleFeatureSet::collectFeaturesFromSelector(const CSSSelector& selector)
+{
+    collectFeaturesFromSelector(selector, m_metadata, ProcessClasses);
+}
+
+void RuleFeatureSet::collectFeaturesFromSelector(const CSSSelector& selector, RuleFeatureSet::FeatureMetadata& metadata, SelectorFeatureCollectionMode collectionMode)
+{
+    unsigned maxDirectAdjacentSelectors = 0;
+
+    for (const CSSSelector* current = &selector; current; current = current->tagHistory()) {
+        if (current->m_match == CSSSelector::Id) {
+            metadata.idsInRules.add(current->value());
+        } else if (current->m_match == CSSSelector::Class && collectionMode == ProcessClasses) {
+            DescendantInvalidationSet& invalidationSet = ensureClassInvalidationSet(current->value());
+            invalidationSet.setWholeSubtreeInvalid();
+        } else if (current->isAttributeSelector()) {
+            metadata.attrsInRules.add(current->attribute().localName());
+        }
+        if (current->pseudoType() == CSSSelector::PseudoFirstLine)
+            metadata.usesFirstLineRules = true;
+        if (current->isDirectAdjacentSelector()) {
+            maxDirectAdjacentSelectors++;
+        } else if (maxDirectAdjacentSelectors) {
+            if (maxDirectAdjacentSelectors > metadata.maxDirectAdjacentSelectors)
+                metadata.maxDirectAdjacentSelectors = maxDirectAdjacentSelectors;
+            maxDirectAdjacentSelectors = 0;
+        }
+        if (current->isSiblingSelector())
+            metadata.foundSiblingSelector = true;
+
+        collectFeaturesFromSelectorList(current->selectorList(), metadata, collectionMode);
+    }
+
+    ASSERT(!maxDirectAdjacentSelectors);
+}
+
+void RuleFeatureSet::collectFeaturesFromSelectorList(const CSSSelectorList* selectorList, RuleFeatureSet::FeatureMetadata& metadata, SelectorFeatureCollectionMode collectionMode)
 {
     if (!selectorList)
         return;
 
-    for (const CSSSelector* selector = selectorList->first(); selector; selector = CSSSelectorList::next(selector)) {
+    for (const CSSSelector* selector = selectorList->first(); selector; selector = CSSSelectorList::next(*selector)) {
         for (const CSSSelector* subSelector = selector; subSelector; subSelector = subSelector->tagHistory())
-            collectFeaturesFromSelector(subSelector);
+            collectFeaturesFromSelector(*subSelector, metadata, collectionMode);
     }
 }
 
+void RuleFeatureSet::FeatureMetadata::add(const FeatureMetadata& other)
+{
+    usesFirstLineRules = usesFirstLineRules || other.usesFirstLineRules;
+    maxDirectAdjacentSelectors = std::max(maxDirectAdjacentSelectors, other.maxDirectAdjacentSelectors);
+
+    HashSet<AtomicString>::const_iterator end = other.idsInRules.end();
+    for (HashSet<AtomicString>::const_iterator it = other.idsInRules.begin(); it != end; ++it)
+        idsInRules.add(*it);
+    end = other.attrsInRules.end();
+    for (HashSet<AtomicString>::const_iterator it = other.attrsInRules.begin(); it != end; ++it)
+        attrsInRules.add(*it);
+}
+
+void RuleFeatureSet::FeatureMetadata::clear()
+{
+
+    idsInRules.clear();
+    attrsInRules.clear();
+    usesFirstLineRules = false;
+    foundSiblingSelector = false;
+    maxDirectAdjacentSelectors = 0;
+}
+
 void RuleFeatureSet::add(const RuleFeatureSet& other)
 {
-    HashSet<AtomicString>::const_iterator end = other.idsInRules.end();
-    for (HashSet<AtomicString>::const_iterator it = other.idsInRules.begin(); it != end; ++it)
-        idsInRules.add(*it);
-    end = other.classesInRules.end();
-    for (HashSet<AtomicString>::const_iterator it = other.classesInRules.begin(); it != end; ++it)
-        classesInRules.add(*it);
-    end = other.attrsInRules.end();
-    for (HashSet<AtomicString>::const_iterator it = other.attrsInRules.begin(); it != end; ++it)
-        attrsInRules.add(*it);
+    for (InvalidationSetMap::const_iterator it = other.m_classInvalidationSets.begin(); it != other.m_classInvalidationSets.end(); ++it) {
+        ensureClassInvalidationSet(it->key).combine(*it->value);
+    }
+
+    m_metadata.add(other.m_metadata);
+
     siblingRules.append(other.siblingRules);
     uncommonAttributeRules.append(other.uncommonAttributeRules);
-    m_usesFirstLineRules = m_usesFirstLineRules || other.m_usesFirstLineRules;
-    m_maxDirectAdjacentSelectors = std::max(m_maxDirectAdjacentSelectors, other.maxDirectAdjacentSelectors());
 }
 
 void RuleFeatureSet::clear()
 {
-    idsInRules.clear();
-    classesInRules.clear();
-    attrsInRules.clear();
+    m_metadata.clear();
     siblingRules.clear();
     uncommonAttributeRules.clear();
-    m_usesFirstLineRules = false;
-    m_maxDirectAdjacentSelectors = 0;
+}
+
+void RuleFeatureSet::scheduleStyleInvalidationForClassChange(const SpaceSplitString& changedClasses, Element* element)
+{
+    if (computeInvalidationSetsForClassChange(changedClasses, element)) {
+        // FIXME: remove eager calls to setNeedsStyleRecalc here, and instead reuse the invalidation tree walk.
+        // This code remains for now out of conservatism about avoiding performance regressions before TargetedStyleRecalc is launched.
+        element->setNeedsStyleRecalc(SubtreeStyleChange);
+    }
+}
+
+void RuleFeatureSet::scheduleStyleInvalidationForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, Element* element)
+{
+    if (computeInvalidationSetsForClassChange(oldClasses, newClasses, element)) {
+        // FIXME: remove eager calls to setNeedsStyleRecalc here, and instead reuse the invalidation tree walk.
+        // This code remains for now out of conservatism about avoiding performance regressions before TargetedStyleRecalc is launched.
+        element->setNeedsStyleRecalc(SubtreeStyleChange);
+    }
+}
+
+bool RuleFeatureSet::computeInvalidationSetsForClassChange(const SpaceSplitString& changedClasses, Element* element)
+{
+    unsigned changedSize = changedClasses.size();
+    for (unsigned i = 0; i < changedSize; ++i) {
+        if (classInvalidationRequiresSubtreeRecalc(changedClasses[i]))
+            return true;
+        addClassToInvalidationSet(changedClasses[i], element);
+    }
+    return false;
+}
+
+bool RuleFeatureSet::computeInvalidationSetsForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, Element* element)
+{
+    if (!oldClasses.size())
+        return computeInvalidationSetsForClassChange(newClasses, element);
+
+    // Class vectors tend to be very short. This is faster than using a hash table.
+    BitVector remainingClassBits;
+    remainingClassBits.ensureSize(oldClasses.size());
+
+    for (unsigned i = 0; i < newClasses.size(); ++i) {
+        bool found = false;
+        for (unsigned j = 0; j < oldClasses.size(); ++j) {
+            if (newClasses[i] == oldClasses[j]) {
+                // Mark each class that is still in the newClasses so we can skip doing
+                // an n^2 search below when looking for removals. We can't break from
+                // this loop early since a class can appear more than once.
+                remainingClassBits.quickSet(j);
+                found = true;
+            }
+        }
+        // Class was added.
+        if (!found) {
+            if (classInvalidationRequiresSubtreeRecalc(newClasses[i]))
+                return true;
+            addClassToInvalidationSet(newClasses[i], element);
+        }
+    }
+
+    for (unsigned i = 0; i < oldClasses.size(); ++i) {
+        if (remainingClassBits.quickGet(i))
+            continue;
+
+        // Class was removed.
+        if (classInvalidationRequiresSubtreeRecalc(oldClasses[i]))
+            return true;
+        addClassToInvalidationSet(oldClasses[i], element);
+    }
+    return false;
+}
+
+void RuleFeatureSet::addClassToInvalidationSet(const AtomicString& className, Element* element)
+{
+    if (DescendantInvalidationSet* invalidationSet = m_classInvalidationSets.get(className)) {
+        ensurePendingInvalidationList(element).append(invalidationSet);
+        element->setNeedsStyleInvalidation();
+    }
+}
+
+RuleFeatureSet::InvalidationList& RuleFeatureSet::ensurePendingInvalidationList(Element* element)
+{
+    PendingInvalidationMap::AddResult addResult = m_pendingInvalidationMap.add(element, 0);
+    if (addResult.isNewEntry)
+        addResult.storedValue->value = new InvalidationList;
+    return *addResult.storedValue->value;
+}
+
+void RuleFeatureSet::computeStyleInvalidation(Document& document)
+{
+    Vector<AtomicString> invalidationClasses;
+    if (Element* documentElement = document.documentElement()) {
+        if (documentElement->childNeedsStyleInvalidation()) {
+            invalidateStyleForClassChange(documentElement, invalidationClasses, false);
+        }
+    }
+    document.clearChildNeedsStyleInvalidation();
+    m_pendingInvalidationMap.clear();
+}
+
+bool RuleFeatureSet::invalidateStyleForClassChangeOnChildren(Element* element, Vector<AtomicString>& invalidationClasses, bool foundInvalidationSet)
+{
+    bool someChildrenNeedStyleRecalc = false;
+    for (ShadowRoot* root = element->youngestShadowRoot(); root; root = root->olderShadowRoot()) {
+        for (Node* child = root->firstChild(); child; child = child->nextSibling()) {
+            if (child->isElementNode()) {
+                Element* childElement = toElement(child);
+                bool childRecalced = invalidateStyleForClassChange(childElement, invalidationClasses, foundInvalidationSet);
+                someChildrenNeedStyleRecalc = someChildrenNeedStyleRecalc || childRecalced;
+            }
+        }
+    }
+    for (Node* child = element->firstChild(); child; child = child->nextSibling()) {
+        if (child->isElementNode()) {
+            Element* childElement = toElement(child);
+            bool childRecalced = invalidateStyleForClassChange(childElement, invalidationClasses, foundInvalidationSet);
+            someChildrenNeedStyleRecalc = someChildrenNeedStyleRecalc || childRecalced;
+        }
+    }
+    return someChildrenNeedStyleRecalc;
+}
+
+bool RuleFeatureSet::invalidateStyleForClassChange(Element* element, Vector<AtomicString>& invalidationClasses, bool foundInvalidationSet)
+{
+    int oldSize = invalidationClasses.size();
+    if (element->needsStyleInvalidation()) {
+        if (InvalidationList* invalidationList = m_pendingInvalidationMap.get(element)) {
+            foundInvalidationSet = true;
+            for (InvalidationList::const_iterator it = invalidationList->begin(); it != invalidationList->end(); ++it) {
+                if ((*it)->wholeSubtreeInvalid()) {
+                    element->setNeedsStyleRecalc(SubtreeStyleChange);
+                    invalidationClasses.remove(oldSize, invalidationClasses.size() - oldSize);
+                    element->clearChildNeedsStyleInvalidation();
+                    return true;
+                }
+                (*it)->getClasses(invalidationClasses);
+            }
+        }
+    }
+
+    bool thisElementNeedsStyleRecalc = false;
+
+    if (element->hasClass()) {
+        const SpaceSplitString& classNames = element->classNames();
+        for (Vector<AtomicString>::const_iterator it = invalidationClasses.begin(); it != invalidationClasses.end(); ++it) {
+            if (classNames.contains(*it)) {
+                thisElementNeedsStyleRecalc = true;
+                break;
+            }
+        }
+    }
+
+    // foundInvalidationSet will be true if we are in a subtree of a node with a DescendantInvalidationSet on it.
+    // We need to check all nodes in the subtree of such a node.
+    if (foundInvalidationSet || element->childNeedsStyleInvalidation()) {
+        bool someChildrenNeedStyleRecalc = invalidateStyleForClassChangeOnChildren(element, invalidationClasses, foundInvalidationSet);
+        // We only need to possibly recalc style if this node is in the subtree of a node with a DescendantInvalidationSet on it.
+        if (foundInvalidationSet)
+            thisElementNeedsStyleRecalc = thisElementNeedsStyleRecalc || someChildrenNeedStyleRecalc;
+    }
+
+    if (thisElementNeedsStyleRecalc)
+        element->setNeedsStyleRecalc(LocalStyleChange);
+
+    invalidationClasses.remove(oldSize, invalidationClasses.size() - oldSize);
+    element->clearChildNeedsStyleInvalidation();
+    return thisElementNeedsStyleRecalc;
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/RuleFeature.h b/Source/core/css/RuleFeature.h
index b51863c..bdce85f 100644
--- a/Source/core/css/RuleFeature.h
+++ b/Source/core/css/RuleFeature.h
@@ -22,15 +22,20 @@
 #ifndef RuleFeature_h
 #define RuleFeature_h
 
+#include "core/css/analyzer/DescendantInvalidationSet.h"
 #include "wtf/Forward.h"
 #include "wtf/HashSet.h"
 #include "wtf/text/AtomicStringHash.h"
 
 namespace WebCore {
 
+class Document;
+class ShadowRoot;
 class StyleRule;
 class CSSSelector;
 class CSSSelectorList;
+class RuleData;
+class SpaceSplitString;
 
 struct RuleFeature {
     RuleFeature(StyleRule* rule, unsigned selectorIndex, bool hasDocumentSecurityOrigin)
@@ -46,50 +51,103 @@
 
 class RuleFeatureSet {
 public:
-    RuleFeatureSet()
-        : m_usesFirstLineRules(false)
-        , m_maxDirectAdjacentSelectors(0)
-    { }
+    RuleFeatureSet();
 
     void add(const RuleFeatureSet&);
     void clear();
 
-    void collectFeaturesFromSelector(const CSSSelector*);
+    void collectFeaturesFromSelector(const CSSSelector&);
+    void collectFeaturesFromRuleData(const RuleData&);
 
     bool usesSiblingRules() const { return !siblingRules.isEmpty(); }
-    bool usesFirstLineRules() const { return m_usesFirstLineRules; }
+    bool usesFirstLineRules() const { return m_metadata.usesFirstLineRules; }
 
-    unsigned maxDirectAdjacentSelectors() const { return m_maxDirectAdjacentSelectors; }
-    void setMaxDirectAdjacentSelectors(unsigned value)  { m_maxDirectAdjacentSelectors = std::max(value, m_maxDirectAdjacentSelectors); }
+    unsigned maxDirectAdjacentSelectors() const { return m_metadata.maxDirectAdjacentSelectors; }
+    void setMaxDirectAdjacentSelectors(unsigned value)  { m_metadata.maxDirectAdjacentSelectors = std::max(value, m_metadata.maxDirectAdjacentSelectors); }
 
     inline bool hasSelectorForAttribute(const AtomicString& attributeName) const
     {
         ASSERT(!attributeName.isEmpty());
-        return attrsInRules.contains(attributeName);
+        return m_metadata.attrsInRules.contains(attributeName);
     }
 
     inline bool hasSelectorForClass(const AtomicString& classValue) const
     {
         ASSERT(!classValue.isEmpty());
-        return classesInRules.contains(classValue);
+        return m_classInvalidationSets.get(classValue);
+
     }
 
     inline bool hasSelectorForId(const AtomicString& idValue) const
     {
-        ASSERT(!idValue.isEmpty());
-        return idsInRules.contains(idValue);
+        return m_metadata.idsInRules.contains(idValue);
     }
 
-    HashSet<AtomicString> idsInRules;
-    HashSet<AtomicString> classesInRules;
-    HashSet<AtomicString> attrsInRules;
+    void scheduleStyleInvalidationForClassChange(const SpaceSplitString& changedClasses, Element*);
+    void scheduleStyleInvalidationForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, Element*);
+
+    void computeStyleInvalidation(Document&);
+
+    int hasIdsInSelectors() const
+    {
+        return m_metadata.idsInRules.size() > 0;
+    }
+
+    // Marks the given attribute name as "appearing in a selector". Used for
+    // CSS properties such as content: ... attr(...) ...
+    void addAttributeInASelector(const AtomicString& attributeName);
+
     Vector<RuleFeature> siblingRules;
     Vector<RuleFeature> uncommonAttributeRules;
-private:
-    void collectFeaturesFromSelectorList(const CSSSelectorList*);
 
-    bool m_usesFirstLineRules;
-    unsigned m_maxDirectAdjacentSelectors;
+private:
+    typedef HashMap<AtomicString, RefPtr<DescendantInvalidationSet> > InvalidationSetMap;
+    typedef Vector<DescendantInvalidationSet*> InvalidationList;
+    typedef HashMap<Element*, InvalidationList*> PendingInvalidationMap;
+    struct FeatureMetadata {
+        FeatureMetadata()
+            : usesFirstLineRules(false)
+            , foundSiblingSelector(false)
+            , maxDirectAdjacentSelectors(0)
+        { }
+        void add(const FeatureMetadata& other);
+        void clear();
+
+        bool usesFirstLineRules;
+        bool foundSiblingSelector;
+        unsigned maxDirectAdjacentSelectors;
+        HashSet<AtomicString> idsInRules;
+        HashSet<AtomicString> attrsInRules;
+    };
+
+    // These return true if setNeedsStyleRecalc() should be run on the Element, as a fallback.
+    bool computeInvalidationSetsForClassChange(const SpaceSplitString& changedClasses, Element*);
+    bool computeInvalidationSetsForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, Element*);
+
+    enum SelectorFeatureCollectionMode {
+        ProcessClasses,
+        DontProcessClasses
+    };
+
+    void collectFeaturesFromSelector(const CSSSelector&, FeatureMetadata&, SelectorFeatureCollectionMode processClasses);
+    void collectFeaturesFromSelectorList(const CSSSelectorList*, FeatureMetadata&, SelectorFeatureCollectionMode processClasses);
+
+    bool classInvalidationRequiresSubtreeRecalc(const AtomicString& className);
+    DescendantInvalidationSet& ensureClassInvalidationSet(const AtomicString& className);
+    bool updateClassInvalidationSets(const CSSSelector&);
+
+    void addClassToInvalidationSet(const AtomicString& className, Element*);
+
+    bool invalidateStyleForClassChange(Element*, Vector<AtomicString>&, bool foundInvalidationSet);
+    bool invalidateStyleForClassChangeOnChildren(Element*, Vector<AtomicString>& invalidationClasses, bool foundInvalidationSet);
+
+    InvalidationList& ensurePendingInvalidationList(Element*);
+
+    FeatureMetadata m_metadata;
+    InvalidationSetMap m_classInvalidationSets;
+    PendingInvalidationMap m_pendingInvalidationMap;
+
+    bool m_targetedStyleRecalcEnabled;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/RuleSet.cpp b/Source/core/css/RuleSet.cpp
index f7a0325..7e048b8 100644
--- a/Source/core/css/RuleSet.cpp
+++ b/Source/core/css/RuleSet.cpp
@@ -40,6 +40,7 @@
 #include "core/css/StyleRuleImport.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/html/track/TextTrackCue.h"
+#include "platform/TraceEvent.h"
 #include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
@@ -48,20 +49,21 @@
 
 // -----------------------------------------------------------------
 
-static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
+static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector& selector)
 {
-    ASSERT(selector);
-    if (selector->m_match == CSSSelector::Tag) {
-        const AtomicString& selectorNamespace = selector->tagQName().namespaceURI();
+    if (selector.m_match == CSSSelector::Tag) {
+        const AtomicString& selectorNamespace = selector.tagQName().namespaceURI();
         if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
             return false;
-        if (selector->relation() == CSSSelector::SubSelector)
-            return isSelectorMatchingHTMLBasedOnRuleHash(selector->tagHistory());
+        if (selector.relation() == CSSSelector::SubSelector) {
+            ASSERT(selector.tagHistory());
+            return isSelectorMatchingHTMLBasedOnRuleHash(*selector.tagHistory());
+        }
         return true;
     }
     if (SelectorChecker::isCommonPseudoClassSelector(selector))
         return true;
-    return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
+    return selector.m_match == CSSSelector::Id || selector.m_match == CSSSelector::Class;
 }
 
 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
@@ -69,7 +71,7 @@
     const CSSSelectorList* selectorList = selector->selectorList();
     if (!selectorList)
         return false;
-    for (const CSSSelector* selector = selectorList->first(); selector; selector = CSSSelectorList::next(selector)) {
+    for (const CSSSelector* selector = selectorList->first(); selector; selector = CSSSelectorList::next(*selector)) {
         for (const CSSSelector* component = selector; component; component = component->tagHistory()) {
             if (component->isAttributeSelector())
                 return true;
@@ -84,34 +86,33 @@
     return attribute == typeAttr || attribute == readonlyAttr;
 }
 
-static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
+static inline bool containsUncommonAttributeSelector(const CSSSelector& selector)
 {
-    for (; selector; selector = selector->tagHistory()) {
+    const CSSSelector* current = &selector;
+    for (; current; current = current->tagHistory()) {
         // Allow certain common attributes (used in the default style) in the selectors that match the current element.
-        if (selector->isAttributeSelector() && !isCommonAttributeSelectorAttribute(selector->attribute()))
+        if (current->isAttributeSelector() && !isCommonAttributeSelectorAttribute(current->attribute()))
             return true;
-        if (selectorListContainsUncommonAttributeSelector(selector))
+        if (selectorListContainsUncommonAttributeSelector(current))
             return true;
-        if (selector->relation() != CSSSelector::SubSelector) {
-            selector = selector->tagHistory();
+        if (current->relation() != CSSSelector::SubSelector) {
+            current = current->tagHistory();
             break;
         }
     }
 
-    for (; selector; selector = selector->tagHistory()) {
-        if (selector->isAttributeSelector())
+    for (; current; current = current->tagHistory()) {
+        if (current->isAttributeSelector())
             return true;
-        if (selectorListContainsUncommonAttributeSelector(selector))
+        if (selectorListContainsUncommonAttributeSelector(current))
             return true;
     }
     return false;
 }
 
-static inline PropertyWhitelistType determinePropertyWhitelistType(const AddRuleFlags addRuleFlags, const CSSSelector* selector)
+static inline PropertyWhitelistType determinePropertyWhitelistType(const AddRuleFlags addRuleFlags, const CSSSelector& selector)
 {
-    if (addRuleFlags & RuleIsInRegionRule)
-        return PropertyWhitelistRegion;
-    for (const CSSSelector* component = selector; component; component = component->tagHistory()) {
+    for (const CSSSelector* component = &selector; component; component = component->tagHistory()) {
         if (component->pseudoType() == CSSSelector::PseudoCue || (component->m_match == CSSSelector::PseudoElement && component->value() == TextTrackCue::cueShadowPseudoId()))
             return PropertyWhitelistCue;
     }
@@ -194,8 +195,8 @@
     , m_isLastInArray(false)
     , m_position(position)
     , m_hasFastCheckableSelector((addRuleFlags & RuleCanUseFastCheckSelector) && SelectorCheckerFastPath::canUse(selector()))
-    , m_specificity(selector()->specificity())
-    , m_hasMultipartSelector(!!selector()->tagHistory())
+    , m_specificity(selector().specificity())
+    , m_hasMultipartSelector(!!selector().tagHistory())
     , m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash(isSelectorMatchingHTMLBasedOnRuleHash(selector()))
     , m_containsUncommonAttributeSelector(WebCore::containsUncommonAttributeSelector(selector()))
     , m_linkMatchType(SelectorChecker::determineLinkMatchType(selector()))
@@ -207,66 +208,74 @@
     SelectorFilter::collectIdentifierHashes(selector(), m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
 }
 
-static void collectFeaturesFromRuleData(RuleFeatureSet& features, const RuleData& ruleData)
+void RuleSet::addToRuleSet(const AtomicString& key, PendingRuleMap& map, const RuleData& ruleData)
 {
-    bool foundSiblingSelector = false;
-    unsigned maxDirectAdjacentSelectors = 0;
-    for (const CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
-        features.collectFeaturesFromSelector(selector);
-
-        if (const CSSSelectorList* selectorList = selector->selectorList()) {
-            for (const CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
-                // FIXME: Shouldn't this be checking subSelector->isSiblingSelector()?
-                if (!foundSiblingSelector && selector->isSiblingSelector())
-                    foundSiblingSelector = true;
-                if (subSelector->isDirectAdjacentSelector())
-                    maxDirectAdjacentSelectors++;
-                features.collectFeaturesFromSelector(subSelector);
-            }
-        } else {
-            if (!foundSiblingSelector && selector->isSiblingSelector())
-                foundSiblingSelector = true;
-            if (selector->isDirectAdjacentSelector())
-                maxDirectAdjacentSelectors++;
-        }
-    }
-    features.setMaxDirectAdjacentSelectors(maxDirectAdjacentSelectors);
-    if (foundSiblingSelector)
-        features.siblingRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
-    if (ruleData.containsUncommonAttributeSelector())
-        features.uncommonAttributeRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
-}
-
-void RuleSet::addToRuleSet(StringImpl* key, PendingRuleMap& map, const RuleData& ruleData)
-{
-    if (!key)
-        return;
-    OwnPtr<LinkedStack<RuleData> >& rules = map.add(key, nullptr).iterator->value;
+    OwnPtr<LinkedStack<RuleData> >& rules = map.add(key, nullptr).storedValue->value;
     if (!rules)
         rules = adoptPtr(new LinkedStack<RuleData>);
     rules->push(ruleData);
 }
 
-bool RuleSet::findBestRuleSetAndAdd(const CSSSelector* component, RuleData& ruleData)
+static void extractValuesforSelector(const CSSSelector* selector, AtomicString& id, AtomicString& className, AtomicString& customPseudoElementName, AtomicString& tagName)
 {
-    if (component->m_match == CSSSelector::Id) {
-        addToRuleSet(component->value().impl(), ensurePendingRules()->idRules, ruleData);
+    switch (selector->m_match) {
+    case CSSSelector::Id:
+        id = selector->value();
+        break;
+    case CSSSelector::Class:
+        className = selector->value();
+        break;
+    case CSSSelector::Tag:
+        if (selector->tagQName().localName() != starAtom)
+            tagName = selector->tagQName().localName();
+        break;
+    }
+    if (selector->isCustomPseudoElement())
+        customPseudoElementName = selector->value();
+}
+
+bool RuleSet::findBestRuleSetAndAdd(const CSSSelector& component, RuleData& ruleData)
+{
+    AtomicString id;
+    AtomicString className;
+    AtomicString customPseudoElementName;
+    AtomicString tagName;
+
+#ifndef NDEBUG
+    m_allRules.append(ruleData);
+#endif
+
+    const CSSSelector* it = &component;
+    for (; it->relation() == CSSSelector::SubSelector; it = it->tagHistory()) {
+        extractValuesforSelector(it, id, className, customPseudoElementName, tagName);
+    }
+    extractValuesforSelector(it, id, className, customPseudoElementName, tagName);
+
+    // Prefer rule sets in order of most likely to apply infrequently.
+    if (!id.isEmpty()) {
+        addToRuleSet(id, ensurePendingRules()->idRules, ruleData);
         return true;
     }
-    if (component->m_match == CSSSelector::Class) {
-        addToRuleSet(component->value().impl(), ensurePendingRules()->classRules, ruleData);
+    if (!className.isEmpty()) {
+        addToRuleSet(className, ensurePendingRules()->classRules, ruleData);
         return true;
     }
-    if (component->isCustomPseudoElement()) {
-        addToRuleSet(component->value().impl(), ensurePendingRules()->shadowPseudoElementRules, ruleData);
+    if (!customPseudoElementName.isEmpty()) {
+        // Custom pseudos come before ids and classes in the order of tagHistory, and have a relation of
+        // ShadowPseudo between them. Therefore we should never be a situation where extractValuesforSelector
+        // finsd id and className in addition to custom pseudo.
+        ASSERT(id.isEmpty() && className.isEmpty());
+        addToRuleSet(customPseudoElementName, ensurePendingRules()->shadowPseudoElementRules, ruleData);
         return true;
     }
-    if (component->pseudoType() == CSSSelector::PseudoCue) {
+
+    if (component.pseudoType() == CSSSelector::PseudoCue) {
         m_cuePseudoRules.append(ruleData);
         return true;
     }
+
     if (SelectorChecker::isCommonPseudoClassSelector(component)) {
-        switch (component->pseudoType()) {
+        switch (component.pseudoType()) {
         case CSSSelector::PseudoLink:
         case CSSSelector::PseudoVisited:
         case CSSSelector::PseudoAnyLink:
@@ -281,25 +290,18 @@
         }
     }
 
-    if (component->m_match == CSSSelector::Tag) {
-        if (component->tagQName().localName() != starAtom) {
-            // If this is part of a subselector chain, recurse ahead to find a narrower set (ID/class.)
-            if (component->relation() == CSSSelector::SubSelector
-                && (component->tagHistory()->m_match == CSSSelector::Class || component->tagHistory()->m_match == CSSSelector::Id || SelectorChecker::isCommonPseudoClassSelector(component->tagHistory()))
-                && findBestRuleSetAndAdd(component->tagHistory(), ruleData))
-                return true;
-
-            addToRuleSet(component->tagQName().localName().impl(), ensurePendingRules()->tagRules, ruleData);
-            return true;
-        }
+    if (!tagName.isEmpty()) {
+        addToRuleSet(tagName, ensurePendingRules()->tagRules, ruleData);
+        return true;
     }
+
     return false;
 }
 
 void RuleSet::addRule(StyleRule* rule, unsigned selectorIndex, AddRuleFlags addRuleFlags)
 {
     RuleData ruleData(rule, selectorIndex, m_ruleCount++, addRuleFlags);
-    collectFeaturesFromRuleData(m_features, ruleData);
+    m_features.collectFeaturesFromRuleData(ruleData);
 
     if (!findBestRuleSetAndAdd(ruleData.selector(), ruleData)) {
         // If we didn't find a specialized map to stick it in, file under universal rules.
@@ -331,31 +333,6 @@
     m_keyframesRules.append(rule);
 }
 
-void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
-{
-    ensurePendingRules(); // So that m_regionSelectorsAndRuleSets.shrinkToFit() gets called.
-    OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
-    // The region rule set should take into account the position inside the parent rule set.
-    // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
-    // the stylesheet that contains the region block.
-    regionRuleSet->m_ruleCount = m_ruleCount;
-
-    // Collect the region rules into a rule set
-    // FIXME: Should this add other types of rules? (i.e. use addChildRules() directly?)
-    const Vector<RefPtr<StyleRuleBase> >& childRules = regionRule->childRules();
-    AddRuleFlags addRuleFlags = hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
-    addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleIsInRegionRule | RuleCanUseFastCheckSelector);
-    for (unsigned i = 0; i < childRules.size(); ++i) {
-        StyleRuleBase* regionStylingRule = childRules[i].get();
-        if (regionStylingRule->isStyleRule())
-            regionRuleSet->addStyleRule(toStyleRule(regionStylingRule), addRuleFlags);
-    }
-    // Update the "global" rule count so that proper order is maintained
-    m_ruleCount = regionRuleSet->m_ruleCount;
-
-    m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
-}
-
 void RuleSet::addChildRules(const Vector<RefPtr<StyleRuleBase> >& rules, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
 {
     for (unsigned i = 0; i < rules.size(); ++i) {
@@ -384,8 +361,6 @@
             addFontFaceRule(toStyleRuleFontFace(rule));
         } else if (rule->isKeyframesRule()) {
             addKeyframesRule(toStyleRuleKeyframes(rule));
-        } else if (rule->isRegionRule()) {
-            addRegionRule(toStyleRuleRegion(rule), addRuleFlags & RuleHasDocumentSecurityOrigin);
         } else if (rule->isViewportRule()) {
             addViewportRule(toStyleRuleViewport(rule));
         } else if (rule->isSupportsRule() && toStyleRuleSupports(rule)->conditionIsSupported()) {
@@ -396,6 +371,8 @@
 
 void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
 {
+    TRACE_EVENT0("webkit", "RuleSet::addRulesFromSheet");
+
     ASSERT(sheet);
 
     addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleCanUseFastCheckSelector);
@@ -420,7 +397,7 @@
     PendingRuleMap::iterator end = pendingMap.end();
     for (PendingRuleMap::iterator it = pendingMap.begin(); it != end; ++it) {
         OwnPtr<LinkedStack<RuleData> > pendingRules = it->value.release();
-        CompactRuleMap::iterator compactRules = compactMap.add(it->key, nullptr).iterator;
+        CompactRuleMap::ValueType* compactRules = compactMap.add(it->key, nullptr).storedValue;
 
         TerminatedArrayBuilder<RuleData> builder(compactRules->value.release());
         builder.grow(pendingRules->size());
@@ -453,4 +430,13 @@
     m_shadowDistributedRules.shrinkToFit();
 }
 
+#ifndef NDEBUG
+
+void RuleSet::show()
+{
+    for (Vector<RuleData>::const_iterator it = m_allRules.begin(); it != m_allRules.end(); ++it)
+        it->selector().show();
+}
+#endif
+
 } // namespace WebCore
diff --git a/Source/core/css/RuleSet.h b/Source/core/css/RuleSet.h
index d8249a3..1bee268 100644
--- a/Source/core/css/RuleSet.h
+++ b/Source/core/css/RuleSet.h
@@ -37,18 +37,15 @@
     RuleHasNoSpecialState         = 0,
     RuleHasDocumentSecurityOrigin = 1,
     RuleCanUseFastCheckSelector   = 1 << 1,
-    RuleIsInRegionRule            = 1 << 2,
 };
 
 enum PropertyWhitelistType {
     PropertyWhitelistNone   = 0,
-    PropertyWhitelistRegion,
     PropertyWhitelistCue
 };
 
 class CSSSelector;
 class MediaQueryEvaluator;
-class StyleRuleRegion;
 class StyleSheetContents;
 
 struct MinimalRuleData {
@@ -71,7 +68,7 @@
 
     unsigned position() const { return m_position; }
     StyleRule* rule() const { return m_rule; }
-    const CSSSelector* selector() const { return m_rule->selectorList().selectorAt(m_selectorIndex); }
+    const CSSSelector& selector() const { return m_rule->selectorList().selectorAt(m_selectorIndex); }
     unsigned selectorIndex() const { return m_selectorIndex; }
 
     bool isLastInArray() const { return m_isLastInArray; }
@@ -128,10 +125,10 @@
 
     const RuleFeatureSet& features() const { return m_features; }
 
-    const RuleData* idRules(StringImpl* key) const { ASSERT(!m_pendingRules); return m_idRules.get(key); }
-    const RuleData* classRules(StringImpl* key) const { ASSERT(!m_pendingRules); return m_classRules.get(key); }
-    const RuleData* tagRules(StringImpl* key) const { ASSERT(!m_pendingRules); return m_tagRules.get(key); }
-    const RuleData* shadowPseudoElementRules(StringImpl* key) const { ASSERT(!m_pendingRules); return m_shadowPseudoElementRules.get(key); }
+    const RuleData* idRules(const AtomicString& key) const { ASSERT(!m_pendingRules); return m_idRules.get(key); }
+    const RuleData* classRules(const AtomicString& key) const { ASSERT(!m_pendingRules); return m_classRules.get(key); }
+    const RuleData* tagRules(const AtomicString& key) const { ASSERT(!m_pendingRules); return m_tagRules.get(key); }
+    const RuleData* shadowPseudoElementRules(const AtomicString& key) const { ASSERT(!m_pendingRules); return m_shadowPseudoElementRules.get(key); }
     const Vector<RuleData>* linkPseudoClassRules() const { ASSERT(!m_pendingRules); return &m_linkPseudoClassRules; }
     const Vector<RuleData>* cuePseudoRules() const { ASSERT(!m_pendingRules); return &m_cuePseudoRules; }
     const Vector<RuleData>* focusPseudoClassRules() const { ASSERT(!m_pendingRules); return &m_focusPseudoClassRules; }
@@ -153,6 +150,10 @@
         compactRules();
     }
 
+#ifndef NDEBUG
+    void show();
+#endif
+
     struct RuleSetSelectorPair {
         RuleSetSelectorPair(const CSSSelector* selector, PassOwnPtr<RuleSet> ruleSet) : selector(selector), ruleSet(ruleSet) { }
         RuleSetSelectorPair(const RuleSetSelectorPair& rs) : selector(rs.selector), ruleSet(const_cast<RuleSetSelectorPair*>(&rs)->ruleSet.release()) { }
@@ -161,26 +162,23 @@
         OwnPtr<RuleSet> ruleSet;
     };
 
-    Vector<RuleSetSelectorPair> m_regionSelectorsAndRuleSets;
-
 private:
-    typedef HashMap<StringImpl*, OwnPtr<LinkedStack<RuleData> > > PendingRuleMap;
-    typedef HashMap<StringImpl*, OwnPtr<RuleData> > CompactRuleMap;
+    typedef HashMap<AtomicString, OwnPtr<LinkedStack<RuleData> > > PendingRuleMap;
+    typedef HashMap<AtomicString, OwnPtr<RuleData> > CompactRuleMap;
 
     RuleSet()
         : m_ruleCount(0)
     {
     }
 
-    void addToRuleSet(StringImpl* key, PendingRuleMap&, const RuleData&);
+    void addToRuleSet(const AtomicString& key, PendingRuleMap&, const RuleData&);
     void addPageRule(StyleRulePage*);
     void addViewportRule(StyleRuleViewport*);
     void addFontFaceRule(StyleRuleFontFace*);
     void addKeyframesRule(StyleRuleKeyframes*);
-    void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
 
     void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, AddRuleFlags);
-    bool findBestRuleSetAndAdd(const CSSSelector*, RuleData&);
+    bool findBestRuleSetAndAdd(const CSSSelector&, RuleData&);
 
     void compactRules();
     static void compactPendingRules(PendingRuleMap&, CompactRuleMap&);
@@ -219,6 +217,10 @@
 
     unsigned m_ruleCount;
     OwnPtr<PendingRuleMaps> m_pendingRules;
+
+#ifndef NDEBUG
+    Vector<RuleData> m_allRules;
+#endif
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/RuleSetTest.cpp b/Source/core/css/RuleSetTest.cpp
new file mode 100644
index 0000000..7fb09a4
--- /dev/null
+++ b/Source/core/css/RuleSetTest.cpp
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2014, Google Inc. 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.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE
+ * COPYRIGHT HOLDER 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.
+ */
+
+#include "config.h"
+#include "core/css/CSSTestHelper.h"
+#include "core/css/RuleSet.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+TEST(RuleSetTest, findBestRuleSetAndAdd_CustomPseudoElements)
+{
+    CSSTestHelper helper;
+
+    helper.addCSSRules("summary::-webkit-details-marker { }");
+    RuleSet& ruleSet = helper.ruleSet();
+    AtomicString str("-webkit-details-marker");
+    const RuleData* ruleData = ruleSet.shadowPseudoElementRules(str);
+    ASSERT_EQ(1, CSSTestHelper::numRules(ruleData));
+    ASSERT_EQ(str, CSSTestHelper::getRule(ruleData, 0).selector().value());
+}
+
+TEST(RuleSetTest, findBestRuleSetAndAdd_Id)
+{
+    CSSTestHelper helper;
+
+    helper.addCSSRules("#id { }");
+    RuleSet& ruleSet = helper.ruleSet();
+    AtomicString str("id");
+    const RuleData* ruleData = ruleSet.idRules(str);
+    ASSERT_EQ(1, CSSTestHelper::numRules(ruleData));
+    ASSERT_EQ(str, CSSTestHelper::getRule(ruleData, 0).selector().value());
+}
+
+TEST(RuleSetTest, findBestRuleSetAndAdd_NthChild)
+{
+    CSSTestHelper helper;
+
+    helper.addCSSRules("div:nth-child(2) { }");
+    RuleSet& ruleSet = helper.ruleSet();
+    AtomicString str("div");
+    const RuleData* ruleData = ruleSet.tagRules(str);
+    ASSERT_EQ(1, CSSTestHelper::numRules(ruleData));
+    ASSERT_EQ(str, CSSTestHelper::getRule(ruleData, 0).selector().tagQName().localName());
+}
+
+TEST(RuleSetTest, findBestRuleSetAndAdd_ClassThenId)
+{
+    CSSTestHelper helper;
+
+    helper.addCSSRules(".class#id { }");
+    RuleSet& ruleSet = helper.ruleSet();
+    AtomicString str("id");
+    // id is prefered over class even if class preceeds it in the selector.
+    const RuleData* ruleData = ruleSet.idRules(str);
+    ASSERT_EQ(1, CSSTestHelper::numRules(ruleData));
+    AtomicString classStr("class");
+    ASSERT_EQ(classStr, CSSTestHelper::getRule(ruleData, 0).selector().value());
+}
+
+TEST(RuleSetTest, findBestRuleSetAndAdd_IdThenClass)
+{
+    CSSTestHelper helper;
+
+    helper.addCSSRules("#id.class { }");
+    RuleSet& ruleSet = helper.ruleSet();
+    AtomicString str("id");
+    const RuleData* ruleData = ruleSet.idRules(str);
+    ASSERT_EQ(1, CSSTestHelper::numRules(ruleData));
+    ASSERT_EQ(str, CSSTestHelper::getRule(ruleData, 0).selector().value());
+}
+
+TEST(RuleSetTest, findBestRuleSetAndAdd_AttrThenId)
+{
+    CSSTestHelper helper;
+
+    helper.addCSSRules("[attr]#id { }");
+    RuleSet& ruleSet = helper.ruleSet();
+    AtomicString str("id");
+    const RuleData* ruleData = ruleSet.idRules(str);
+    ASSERT_EQ(1, CSSTestHelper::numRules(ruleData));
+    AtomicString attrStr("attr");
+    ASSERT_EQ(attrStr, CSSTestHelper::getRule(ruleData, 0).selector().attribute().localName());
+}
+
+TEST(RuleSetTest, findBestRuleSetAndAdd_TagThenAttrThenId)
+{
+    CSSTestHelper helper;
+
+    helper.addCSSRules("div[attr]#id { }");
+    RuleSet& ruleSet = helper.ruleSet();
+    AtomicString str("id");
+    const RuleData* ruleData = ruleSet.idRules(str);
+    ASSERT_EQ(1, CSSTestHelper::numRules(ruleData));
+    AtomicString tagStr("div");
+    ASSERT_EQ(tagStr, CSSTestHelper::getRule(ruleData, 0).selector().tagQName().localName());
+}
+
+TEST(RuleSetTest, findBestRuleSetAndAdd_DivWithContent)
+{
+    CSSTestHelper helper;
+
+    helper.addCSSRules("div::content { }");
+    RuleSet& ruleSet = helper.ruleSet();
+    AtomicString str("div");
+    const RuleData* ruleData = ruleSet.tagRules(str);
+    ASSERT_EQ(1, CSSTestHelper::numRules(ruleData));
+    AtomicString valueStr("content");
+    ASSERT_EQ(valueStr, CSSTestHelper::getRule(ruleData, 0).selector().value());
+}
+
+} // namespace WebCore
diff --git a/Source/core/page/RuntimeCSSEnabled.cpp b/Source/core/css/RuntimeCSSEnabled.cpp
similarity index 86%
rename from Source/core/page/RuntimeCSSEnabled.cpp
rename to Source/core/css/RuntimeCSSEnabled.cpp
index 55b1c54..d4c8b20 100644
--- a/Source/core/page/RuntimeCSSEnabled.cpp
+++ b/Source/core/css/RuntimeCSSEnabled.cpp
@@ -28,7 +28,8 @@
  */
 
 #include "config.h"
-#include "core/page/RuntimeCSSEnabled.h"
+#include "core/css/RuntimeCSSEnabled.h"
+
 #include "RuntimeEnabledFeatures.h"
 
 namespace WebCore {
@@ -44,15 +45,6 @@
 
 static void setPropertySwitchesFromRuntimeFeatures()
 {
-    CSSPropertyID regionProperites[] = {
-        CSSPropertyWebkitFlowInto,
-        CSSPropertyWebkitFlowFrom,
-        CSSPropertyWebkitRegionFragment,
-        CSSPropertyWebkitRegionBreakAfter,
-        CSSPropertyWebkitRegionBreakBefore,
-        CSSPropertyWebkitRegionBreakInside
-    };
-    setCSSPropertiesEnabled(regionProperites, WTF_ARRAY_LENGTH(regionProperites), RuntimeEnabledFeatures::cssRegionsEnabled());
     CSSPropertyID exclusionProperties[] = {
         CSSPropertyWebkitWrapFlow,
         CSSPropertyWebkitWrapThrough,
@@ -81,8 +73,8 @@
     CSSPropertyID cssGridLayoutProperties[] = {
         CSSPropertyGridAutoColumns,
         CSSPropertyGridAutoRows,
-        CSSPropertyGridDefinitionColumns,
-        CSSPropertyGridDefinitionRows,
+        CSSPropertyGridTemplateColumns,
+        CSSPropertyGridTemplateRows,
         CSSPropertyGridColumnStart,
         CSSPropertyGridColumnEnd,
         CSSPropertyGridRowStart,
@@ -91,7 +83,8 @@
         CSSPropertyGridRow,
         CSSPropertyGridArea,
         CSSPropertyGridAutoFlow,
-        CSSPropertyGridTemplate
+        CSSPropertyGridTemplateAreas,
+        CSSPropertyJustifySelf
     };
     setCSSPropertiesEnabled(cssGridLayoutProperties, WTF_ARRAY_LENGTH(cssGridLayoutProperties), RuntimeEnabledFeatures::cssGridLayoutEnabled());
     CSSPropertyID cssObjectFitPositionProperties[] = {
@@ -117,10 +110,11 @@
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyMixBlendMode, RuntimeEnabledFeatures::cssCompositingEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyIsolation, RuntimeEnabledFeatures::cssCompositingEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyTouchAction, RuntimeEnabledFeatures::cssTouchActionEnabled());
+    RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyTouchActionDelay, RuntimeEnabledFeatures::cssTouchActionDelayEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyPaintOrder, RuntimeEnabledFeatures::svgPaintOrderEnabled());
-    RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyVariable, RuntimeEnabledFeatures::cssVariablesEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyMaskSourceType, RuntimeEnabledFeatures::cssMaskSourceTypeEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyColumnFill, RuntimeEnabledFeatures::regionBasedColumnsEnabled());
+    RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyScrollBehavior, RuntimeEnabledFeatures::cssomSmoothScrollEnabled());
 
     // InternalCallback is an implementation detail, rather than an experimental feature, and should never be exposed to the web.
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyInternalCallback, false);
@@ -131,8 +125,7 @@
     static BoolVector* switches = 0;
     if (!switches) {
         switches = new BoolVector;
-        // Accomodate CSSPropertyIDs that fall outside the firstCSSProperty, lastCSSProperty range (eg. CSSPropertyVariable).
-        switches->fill(true, lastCSSProperty + 1);
+        switches->fill(true, numCSSProperties);
         setPropertySwitchesFromRuntimeFeatures();
     }
     return *switches;
@@ -140,9 +133,9 @@
 
 size_t indexForProperty(CSSPropertyID propertyId)
 {
-    RELEASE_ASSERT(propertyId >= 0 && propertyId <= lastCSSProperty);
-    ASSERT(propertyId != CSSPropertyInvalid);
-    return static_cast<size_t>(propertyId);
+    RELEASE_ASSERT(propertyId >= firstCSSProperty && propertyId <= lastCSSProperty);
+    // Values all start at 0. Vector RELEASE_ASSERTS will catch if we're ever wrong.
+    return static_cast<size_t>(propertyId - firstCSSProperty);
 }
 
 bool RuntimeCSSEnabled::isCSSPropertyEnabled(CSSPropertyID propertyId)
diff --git a/Source/core/page/RuntimeCSSEnabled.h b/Source/core/css/RuntimeCSSEnabled.h
similarity index 100%
rename from Source/core/page/RuntimeCSSEnabled.h
rename to Source/core/css/RuntimeCSSEnabled.h
diff --git a/Source/core/css/SVGCSSComputedStyleDeclaration.cpp b/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
index c972f87..4cdac90 100644
--- a/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-static PassRefPtr<CSSPrimitiveValue> glyphOrientationToCSSPrimitiveValue(EGlyphOrientation orientation)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> glyphOrientationToCSSPrimitiveValue(EGlyphOrientation orientation)
 {
     switch (orientation) {
         case GO_0DEG:
@@ -46,14 +46,17 @@
     }
 }
 
-static PassRefPtr<CSSValue> strokeDashArrayToCSSValueList(const Vector<SVGLength>& dashes)
+static PassRefPtr<CSSValue> strokeDashArrayToCSSValueList(PassRefPtr<SVGLengthList> passDashes)
 {
-    if (dashes.isEmpty())
+    RefPtr<SVGLengthList> dashes = passDashes;
+
+    if (dashes->isEmpty())
         return CSSPrimitiveValue::createIdentifier(CSSValueNone);
 
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
-    const Vector<SVGLength>::const_iterator end = dashes.end();
-    for (Vector<SVGLength>::const_iterator it = dashes.begin(); it != end; ++it)
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    SVGLengthList::ConstIterator it = dashes->begin();
+    SVGLengthList::ConstIterator itEnd = dashes->end();
+    for (; it != itEnd; ++it)
         list->append(SVGLength::toCSSPrimitiveValue(*it));
 
     return list.release();
@@ -61,7 +64,7 @@
 
 static PassRefPtr<CSSValue> paintOrderToCSSValueList(EPaintOrder paintorder)
 {
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     do {
         EPaintOrderType paintOrderType = (EPaintOrderType)(paintorder & ((1 << kPaintOrderBitwidth) - 1));
         switch (paintOrderType) {
@@ -80,9 +83,9 @@
     return list.release();
 }
 
-PassRefPtr<SVGPaint> CSSComputedStyleDeclaration::adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint> newPaint, RenderStyle& style) const
+PassRefPtrWillBeRawPtr<SVGPaint> CSSComputedStyleDeclaration::adjustSVGPaintForCurrentColor(PassRefPtrWillBeRawPtr<SVGPaint> newPaint, RenderStyle& style) const
 {
-    RefPtr<SVGPaint> paint = newPaint;
+    RefPtrWillBeRawPtr<SVGPaint> paint = newPaint;
     if (paint->paintType() == SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR || paint->paintType() == SVGPaint::SVG_PAINTTYPE_URI_CURRENTCOLOR)
         paint->setColor(style.color());
     return paint.release();
@@ -202,7 +205,7 @@
         case CSSPropertyGlyphOrientationHorizontal:
             return glyphOrientationToCSSPrimitiveValue(svgStyle->glyphOrientationHorizontal());
         case CSSPropertyGlyphOrientationVertical: {
-            if (RefPtr<CSSPrimitiveValue> value = glyphOrientationToCSSPrimitiveValue(svgStyle->glyphOrientationVertical()))
+            if (RefPtrWillBeRawPtr<CSSPrimitiveValue> value = glyphOrientationToCSSPrimitiveValue(svgStyle->glyphOrientationVertical()))
                 return value.release();
 
             if (svgStyle->glyphOrientationVertical() == GO_AUTO)
diff --git a/Source/core/css/SVGCSSParser.cpp b/Source/core/css/SVGCSSParser.cpp
index 8c07b14..d6e080e 100644
--- a/Source/core/css/SVGCSSParser.cpp
+++ b/Source/core/css/SVGCSSParser.cpp
@@ -25,7 +25,7 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "RuntimeEnabledFeatures.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSValueList.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/svg/SVGPaint.h"
@@ -39,7 +39,7 @@
     return (id >= CSSValueActiveborder && id <= CSSValueWindowtext) || id == CSSValueMenu;
 }
 
-bool CSSParser::parseSVGValue(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseSVGValue(CSSPropertyID propId, bool important)
 {
     CSSParserValue* value = m_valueList->current();
     if (!value)
@@ -197,6 +197,8 @@
                         parsedValue = SVGPaint::createURIAndColor(value->string, c);
                     else if (m_valueList->current()->id == CSSValueNone)
                         parsedValue = SVGPaint::createURIAndNone(value->string);
+                    else if (m_valueList->current()->id == CSSValueCurrentcolor)
+                        parsedValue = SVGPaint::createURIAndCurrentColor(value->string);
                 }
                 if (!parsedValue)
                     parsedValue = SVGPaint::createURI(value->string);
@@ -285,7 +287,7 @@
     case CSSPropertyMarker:
     {
         ShorthandScope scope(this, propId);
-        CSSParser::ImplicitScope implicitScope(this, PropertyImplicit);
+        BisonCSSParser::ImplicitScope implicitScope(this, PropertyImplicit);
         if (!parseValue(CSSPropertyMarkerStart, important))
             return false;
         if (m_valueList->current()) {
@@ -299,7 +301,7 @@
     }
     default:
         // If you crash here, it's because you added a css property and are not handling it
-        // in either this switch statement or the one in CSSParser::parseValue
+        // in either this switch statement or the one in BisonCSSParser::parseValue
         ASSERT_WITH_MESSAGE(0, "unimplemented propertyID: %d", propId);
         return false;
     }
@@ -328,9 +330,9 @@
     return true;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseSVGStrokeDasharray()
+PassRefPtr<CSSValue> BisonCSSParser::parseSVGStrokeDasharray()
 {
-    RefPtr<CSSValueList> ret = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> ret = CSSValueList::createCommaSeparated();
     CSSParserValue* value = m_valueList->current();
     bool valid_primitive = true;
     while (value) {
@@ -350,7 +352,7 @@
     return ret.release();
 }
 
-PassRefPtr<CSSValue> CSSParser::parseSVGPaint()
+PassRefPtr<CSSValue> BisonCSSParser::parseSVGPaint()
 {
     RGBA32 c = Color::transparent;
     if (!parseColorFromValue(m_valueList->current(), c))
@@ -358,7 +360,7 @@
     return SVGPaint::createColor(Color(c));
 }
 
-PassRefPtr<CSSValue> CSSParser::parseSVGColor()
+PassRefPtr<CSSValue> BisonCSSParser::parseSVGColor()
 {
     RGBA32 c = Color::transparent;
     if (!parseColorFromValue(m_valueList->current(), c))
@@ -367,7 +369,7 @@
 }
 
 // normal | [ fill || stroke || markers ]
-PassRefPtr<CSSValue> CSSParser::parsePaintOrder() const
+PassRefPtr<CSSValue> BisonCSSParser::parsePaintOrder() const
 {
     if (m_valueList->size() > 3)
         return 0;
@@ -376,7 +378,7 @@
     if (!value)
         return 0;
 
-    RefPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
 
     // The default paint-order is: Fill, Stroke, Markers.
     bool seenFill = false,
diff --git a/Source/core/css/SelectorChecker.cpp b/Source/core/css/SelectorChecker.cpp
index 15474ce..3a00ae5 100644
--- a/Source/core/css/SelectorChecker.cpp
+++ b/Source/core/css/SelectorChecker.cpp
@@ -32,17 +32,16 @@
 #include "core/css/CSSSelectorList.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/dom/Document.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/FullscreenElementStack.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
-#include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLOptGroupElement.h"
 #include "core/html/HTMLOptionElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/track/vtt/VTTElement.h"
@@ -66,24 +65,22 @@
 {
 }
 
-static bool matchesCustomPseudoElement(const Element* element, const CSSSelector* selector)
+static bool matchesCustomPseudoElement(const Element* element, const CSSSelector& selector)
 {
     ShadowRoot* root = element->containingShadowRoot();
-    if (!root)
+    if (!root || root->type() != ShadowRoot::UserAgentShadowRoot)
         return false;
 
-    const AtomicString& pseudoId = selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement ? element->shadowPseudoId() : element->pseudo();
-    if (pseudoId != selector->value())
+    if (element->shadowPseudoId() != selector.value())
         return false;
-    if (selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement && root->type() != ShadowRoot::UserAgentShadowRoot)
-        return false;
+
     return true;
 }
 
-Element* SelectorChecker::parentElement(const SelectorCheckingContext& context) const
+Element* SelectorChecker::parentElement(const SelectorCheckingContext& context, bool allowToCrossBoundary) const
 {
     // CrossesBoundary means we don't care any context.scope. So we can walk up from a shadow root to its shadow host.
-    if ((context.behaviorAtBoundary & SelectorChecker::BoundaryBehaviorMask) == SelectorChecker::CrossesBoundary)
+    if (allowToCrossBoundary)
         return context.element->parentOrShadowHostElement();
 
     // If context.scope is not a shadow host, we cannot walk up from a shadow root to its shadow host.
@@ -137,7 +134,7 @@
 
     if (context.selector->m_match == CSSSelector::PseudoElement) {
         if (context.selector->isCustomPseudoElement()) {
-            if (!matchesCustomPseudoElement(context.element, context.selector))
+            if (!matchesCustomPseudoElement(context.element, *context.selector))
                 return SelectorFailsLocally;
         } else if (context.selector->isContentPseudoElement()) {
             if (!context.element->isInShadowTree() || !context.element->isInsertionPoint())
@@ -269,7 +266,7 @@
             if (Element* parent = parentElement(context))
                 parent->setChildrenAffectedByDirectAdjacentRules();
         }
-        nextContext.element = context.element->previousElementSibling();
+        nextContext.element = ElementTraversal::previousSibling(*context.element);
         if (!nextContext.element)
             return SelectorFailsAllSiblings;
         nextContext.isSubSelector = false;
@@ -281,10 +278,10 @@
             if (Element* parent = parentElement(context))
                 parent->setChildrenAffectedByForwardPositionalRules();
         }
-        nextContext.element = context.element->previousElementSibling();
+        nextContext.element = ElementTraversal::previousSibling(*context.element);
         nextContext.isSubSelector = false;
         nextContext.elementStyle = 0;
-        for (; nextContext.element; nextContext.element = nextContext.element->previousElementSibling()) {
+        for (; nextContext.element; nextContext.element = ElementTraversal::previousSibling(*nextContext.element)) {
             Match match = this->match(nextContext, siblingTraversalStrategy, result);
             if (match == SelectorMatches || match == SelectorFailsAllSiblings || match == SelectorFailsCompletely)
                 return match;
@@ -311,7 +308,7 @@
         {
             nextContext.isSubSelector = false;
             nextContext.elementStyle = 0;
-            for (nextContext.element = parentElement(context); nextContext.element; nextContext.element = parentElement(nextContext)) {
+            for (nextContext.element = parentElement(context, true); nextContext.element; nextContext.element = parentElement(nextContext, true)) {
                 Match match = this->match(nextContext, siblingTraversalStrategy, result);
                 if (match == SelectorMatches || match == SelectorFailsCompletely)
                     return match;
@@ -441,9 +438,6 @@
         return false;
 
     const AtomicString& selectorValue =  selector.value();
-    // Case sensitivity for attribute matching is looser than hasAttribute or
-    // Element::shouldIgnoreAttributeCase() for now. Unclear if that's correct.
-    bool caseSensitive = !element.document().isHTMLDocument() || HTMLDocument::isCaseSensitiveAttribute(selectorAttr);
 
     for (size_t i = 0; i < element.attributeCount(); ++i) {
         const Attribute* attributeItem = element.attributeItem(i);
@@ -451,8 +445,19 @@
         if (!attributeItem->matches(selectorAttr))
             continue;
 
-        if (attributeValueMatches(attributeItem, match, selectorValue, caseSensitive))
+        if (attributeValueMatches(attributeItem, match, selectorValue, true))
             return true;
+
+        // Case sensitivity for attribute matching is looser than hasAttribute or
+        // Element::shouldIgnoreAttributeCase() for now. Unclear if that's correct.
+        bool caseSensitive = !element.document().isHTMLDocument() || HTMLDocument::isCaseSensitiveAttribute(selectorAttr);
+
+        // If case-insensitive, re-check, and count if result differs.
+        // See http://code.google.com/p/chromium/issues/detail?id=327060
+        if (!caseSensitive && attributeValueMatches(attributeItem, match, selectorValue, false)) {
+            UseCounter::count(element.document(), UseCounter::CaseInsensitiveAttrSelectorMatch);
+            return true;
+        }
     }
 
     return false;
@@ -463,33 +468,34 @@
 {
     ASSERT(context.element);
     Element& element = *context.element;
-    const CSSSelector* const & selector = context.selector;
-    ASSERT(selector);
+    ASSERT(context.selector);
+    const CSSSelector& selector = *context.selector;
+
     bool elementIsHostInItsShadowTree = isHostInItsShadowTree(element, context.behaviorAtBoundary, context.scope);
 
-    if (selector->m_match == CSSSelector::Tag)
-        return SelectorChecker::tagMatches(element, selector->tagQName(), elementIsHostInItsShadowTree ? MatchingHostInItsShadowTree : MatchingElement);
+    if (selector.m_match == CSSSelector::Tag)
+        return SelectorChecker::tagMatches(element, selector.tagQName(), elementIsHostInItsShadowTree ? MatchingHostInItsShadowTree : MatchingElement);
 
-    if (selector->m_match == CSSSelector::Class)
-        return element.hasClass() && element.classNames().contains(selector->value()) && !elementIsHostInItsShadowTree;
+    if (selector.m_match == CSSSelector::Class)
+        return element.hasClass() && element.classNames().contains(selector.value()) && !elementIsHostInItsShadowTree;
 
-    if (selector->m_match == CSSSelector::Id)
-        return element.hasID() && element.idForStyleResolution() == selector->value() && !elementIsHostInItsShadowTree;
+    if (selector.m_match == CSSSelector::Id)
+        return element.hasID() && element.idForStyleResolution() == selector.value() && !elementIsHostInItsShadowTree;
 
-    if (selector->isAttributeSelector()) {
+    if (selector.isAttributeSelector()) {
         if (elementIsHostInItsShadowTree)
             return false;
-        if (!anyAttributeMatches(element, static_cast<CSSSelector::Match>(selector->m_match), *selector))
+        if (!anyAttributeMatches(element, static_cast<CSSSelector::Match>(selector.m_match), selector))
             return false;
     }
 
-    if (selector->m_match == CSSSelector::PseudoClass) {
+    if (selector.m_match == CSSSelector::PseudoClass) {
         // Handle :not up front.
-        if (selector->pseudoType() == CSSSelector::PseudoNot) {
+        if (selector.pseudoType() == CSSSelector::PseudoNot) {
             SelectorCheckingContext subContext(context);
             subContext.isSubSelector = true;
-            ASSERT(selector->selectorList());
-            for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = subContext.selector->tagHistory()) {
+            ASSERT(selector.selectorList());
+            for (subContext.selector = selector.selectorList()->first(); subContext.selector; subContext.selector = subContext.selector->tagHistory()) {
                 // :not cannot nest. I don't really know why this is a
                 // restriction in CSS3, but it is, so let's honor it.
                 // the parser enforces that this never occurs
@@ -505,12 +511,12 @@
             // (since there are no elements involved).
             return checkScrollbarPseudoClass(context, &element.document(), selector);
         } else if (context.hasSelectionPseudo) {
-            if (selector->pseudoType() == CSSSelector::PseudoWindowInactive)
+            if (selector.pseudoType() == CSSSelector::PseudoWindowInactive)
                 return !element.document().page()->focusController().isActive();
         }
 
         // Normal element pseudo class checking.
-        switch (selector->pseudoType()) {
+        switch (selector.pseudoType()) {
             // Pseudo classes:
         case CSSSelector::PseudoNot:
             break; // Already handled up above.
@@ -542,7 +548,7 @@
         case CSSSelector::PseudoFirstChild:
             // first-child matches the first child that is an element
             if (Element* parent = element.parentElement()) {
-                bool result = siblingTraversalStrategy.isFirstChild(&element);
+                bool result = siblingTraversalStrategy.isFirstChild(element);
                 if (m_mode == ResolvingStyle) {
                     RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element.renderStyle();
                     parent->setChildrenAffectedByFirstChildRules();
@@ -555,7 +561,7 @@
         case CSSSelector::PseudoFirstOfType:
             // first-of-type matches the first element of its type
             if (Element* parent = element.parentElement()) {
-                bool result = siblingTraversalStrategy.isFirstOfType(&element, element.tagQName());
+                bool result = siblingTraversalStrategy.isFirstOfType(element, element.tagQName());
                 if (m_mode == ResolvingStyle)
                     parent->setChildrenAffectedByForwardPositionalRules();
                 return result;
@@ -564,7 +570,7 @@
         case CSSSelector::PseudoLastChild:
             // last-child matches the last child that is an element
             if (Element* parent = element.parentElement()) {
-                bool result = parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(&element);
+                bool result = parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element);
                 if (m_mode == ResolvingStyle) {
                     RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element.renderStyle();
                     parent->setChildrenAffectedByLastChildRules();
@@ -581,13 +587,13 @@
                     parent->setChildrenAffectedByBackwardPositionalRules();
                 if (!parent->isFinishedParsingChildren())
                     return false;
-                return siblingTraversalStrategy.isLastOfType(&element, element.tagQName());
+                return siblingTraversalStrategy.isLastOfType(element, element.tagQName());
             }
             break;
         case CSSSelector::PseudoOnlyChild:
             if (Element* parent = element.parentElement()) {
-                bool firstChild = siblingTraversalStrategy.isFirstChild(&element);
-                bool onlyChild = firstChild && parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(&element);
+                bool firstChild = siblingTraversalStrategy.isFirstChild(element);
+                bool onlyChild = firstChild && parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element);
                 if (m_mode == ResolvingStyle) {
                     RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element.renderStyle();
                     parent->setChildrenAffectedByFirstChildRules();
@@ -609,14 +615,14 @@
                 }
                 if (!parent->isFinishedParsingChildren())
                     return false;
-                return siblingTraversalStrategy.isFirstOfType(&element, element.tagQName()) && siblingTraversalStrategy.isLastOfType(&element, element.tagQName());
+                return siblingTraversalStrategy.isFirstOfType(element, element.tagQName()) && siblingTraversalStrategy.isLastOfType(element, element.tagQName());
             }
             break;
         case CSSSelector::PseudoNthChild:
-            if (!selector->parseNth())
+            if (!selector.parseNth())
                 break;
             if (Element* parent = element.parentElement()) {
-                int count = 1 + siblingTraversalStrategy.countElementsBefore(&element);
+                int count = 1 + siblingTraversalStrategy.countElementsBefore(element);
                 if (m_mode == ResolvingStyle) {
                     RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element.renderStyle();
                     element.setChildIndex(count);
@@ -625,37 +631,37 @@
                     parent->setChildrenAffectedByForwardPositionalRules();
                 }
 
-                if (selector->matchNth(count))
+                if (selector.matchNth(count))
                     return true;
             }
             break;
         case CSSSelector::PseudoNthOfType:
-            if (!selector->parseNth())
+            if (!selector.parseNth())
                 break;
             if (Element* parent = element.parentElement()) {
-                int count = 1 + siblingTraversalStrategy.countElementsOfTypeBefore(&element, element.tagQName());
+                int count = 1 + siblingTraversalStrategy.countElementsOfTypeBefore(element, element.tagQName());
                 if (m_mode == ResolvingStyle)
                     parent->setChildrenAffectedByForwardPositionalRules();
 
-                if (selector->matchNth(count))
+                if (selector.matchNth(count))
                     return true;
             }
             break;
         case CSSSelector::PseudoNthLastChild:
-            if (!selector->parseNth())
+            if (!selector.parseNth())
                 break;
             if (Element* parent = element.parentElement()) {
                 if (m_mode == ResolvingStyle)
                     parent->setChildrenAffectedByBackwardPositionalRules();
                 if (!parent->isFinishedParsingChildren())
                     return false;
-                int count = 1 + siblingTraversalStrategy.countElementsAfter(&element);
-                if (selector->matchNth(count))
+                int count = 1 + siblingTraversalStrategy.countElementsAfter(element);
+                if (selector.matchNth(count))
                     return true;
             }
             break;
         case CSSSelector::PseudoNthLastOfType:
-            if (!selector->parseNth())
+            if (!selector.parseNth())
                 break;
             if (Element* parent = element.parentElement()) {
                 if (m_mode == ResolvingStyle)
@@ -663,8 +669,8 @@
                 if (!parent->isFinishedParsingChildren())
                     return false;
 
-                int count = 1 + siblingTraversalStrategy.countElementsOfTypeAfter(&element, element.tagQName());
-                if (selector->matchNth(count))
+                int count = 1 + siblingTraversalStrategy.countElementsOfTypeAfter(element, element.tagQName());
+                if (selector.matchNth(count))
                     return true;
             }
             break;
@@ -676,8 +682,8 @@
             {
                 SelectorCheckingContext subContext(context);
                 subContext.isSubSelector = true;
-                ASSERT(selector->selectorList());
-                for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(subContext.selector)) {
+                ASSERT(selector.selectorList());
+                for (subContext.selector = selector.selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(*subContext.selector)) {
                     if (match(subContext, siblingTraversalStrategy) == SelectorMatches)
                         return true;
                 }
@@ -715,7 +721,7 @@
         case CSSSelector::PseudoHover:
             // If we're in quirks mode, then hover should never match anchors with no
             // href and *:hover should not match anything. This is important for sites like wsj.com.
-            if (m_strictParsing || context.isSubSelector || (selector->m_match == CSSSelector::Tag && selector->tagQName() != anyQName() && !isHTMLAnchorElement(element)) || element.isLink()) {
+            if (m_strictParsing || context.isSubSelector || (selector.m_match == CSSSelector::Tag && selector.tagQName() != anyQName() && !element.hasTagName(aTag)) || element.isLink()) {
                 if (m_mode == ResolvingStyle) {
                     if (context.elementStyle)
                         context.elementStyle->setAffectedByHover();
@@ -729,7 +735,7 @@
         case CSSSelector::PseudoActive:
             // If we're in quirks mode, then :active should never match anchors with no
             // href and *:active should not match anything.
-            if (m_strictParsing || context.isSubSelector || (selector->m_match == CSSSelector::Tag && selector->tagQName() != anyQName() && !isHTMLAnchorElement(element)) || element.isLink()) {
+            if (m_strictParsing || context.isSubSelector || (selector.m_match == CSSSelector::Tag && selector.tagQName() != anyQName() && !element.hasTagName(aTag)) || element.isLink()) {
                 if (m_mode == ResolvingStyle) {
                     if (context.elementStyle)
                         context.elementStyle->setAffectedByActive();
@@ -741,7 +747,7 @@
             }
             break;
         case CSSSelector::PseudoEnabled:
-            if (element.isFormControlElement() || element.hasTagName(optionTag) || isHTMLOptGroupElement(element))
+            if (element.isFormControlElement() || element.hasTagName(optionTag) || element.hasTagName(optgroupTag))
                 return !element.isDisabledFormControl();
             break;
         case CSSSelector::PseudoFullPageMedia:
@@ -750,7 +756,7 @@
         case CSSSelector::PseudoDefault:
             return element.isDefaultButtonForForm();
         case CSSSelector::PseudoDisabled:
-            if (element.isFormControlElement() || element.hasTagName(optionTag) || isHTMLOptGroupElement(element))
+            if (element.isFormControlElement() || element.hasTagName(optionTag) || element.hasTagName(optgroupTag))
                 return element.isDisabledFormControl();
             break;
         case CSSSelector::PseudoReadOnly:
@@ -795,7 +801,7 @@
                     value = toVTTElement(element).language();
                 else
                     value = element.computeInheritedLanguage();
-                const AtomicString& argument = selector->argument();
+                const AtomicString& argument = selector.argument();
                 if (value.isEmpty() || !value.startsWith(argument, false))
                     break;
                 if (value.length() != argument.length() && value[argument.length()] != '-')
@@ -823,10 +829,6 @@
             if (!FullscreenElementStack::isFullScreen(&element.document()))
                 return false;
             return true;
-        case CSSSelector::PseudoSeamlessDocument:
-            // While a document is rendered in a seamless iframe, the 'seamless-document' pseudoclass applies
-            // to all elements of that Document.
-            return element.document().shouldDisplaySeamlesslyWithParent();
         case CSSSelector::PseudoInRange:
             element.document().setContainsValidityStyleRules();
             return element.isInRange();
@@ -840,7 +842,7 @@
 
         case CSSSelector::PseudoScope:
             {
-                const Node* contextualReferenceNode = !context.scope || (context.behaviorAtBoundary & BoundaryBehaviorMask) == CrossesBoundary ? element.document().documentElement() : context.scope;
+                const Node* contextualReferenceNode = !context.scope ? element.document().documentElement() : context.scope;
                 if (element == contextualReferenceNode)
                     return true;
                 break;
@@ -852,6 +854,7 @@
             break;
 
         case CSSSelector::PseudoHost:
+        case CSSSelector::PseudoAncestor:
             {
                 // :host only matches a shadow host when :host is in a shadow tree of the shadow host.
                 if (!context.scope || !(context.behaviorAtBoundary & ScopeIsShadowHost) || context.scope != element)
@@ -859,7 +862,7 @@
                 ASSERT(element.shadow());
 
                 // For empty parameter case, i.e. just :host or :host().
-                if (!selector->selectorList()) // Use *'s specificity. So just 0.
+                if (!selector.selectorList()) // Use *'s specificity. So just 0.
                     return true;
 
                 SelectorCheckingContext subContext(context);
@@ -869,11 +872,12 @@
                 unsigned maxSpecificity = 0;
 
                 // If one of simple selectors matches an element, returns SelectorMatches. Just "OR".
-                for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(subContext.selector)) {
+                for (subContext.selector = selector.selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(*subContext.selector)) {
                     subContext.behaviorAtBoundary = ScopeIsShadowHostInPseudoHostParameter;
                     subContext.scope = context.scope;
                     // Use NodeRenderingTraversal to traverse a composed ancestor list of a given element.
-                    for (Element* nextElement = &element; nextElement; nextElement = NodeRenderingTraversal::parentElement(nextElement)) {
+                    Element* nextElement = &element;
+                    do {
                         MatchResult subResult;
                         subContext.element = nextElement;
                         if (match(subContext, siblingTraversalStrategy, &subResult) == SelectorMatches) {
@@ -882,9 +886,14 @@
                             maxSpecificity = std::max(maxSpecificity, subContext.selector->specificity() + subResult.specificity);
                             break;
                         }
-                        subContext.behaviorAtBoundary = CrossesBoundary;
+                        subContext.behaviorAtBoundary = DoesNotCrossBoundary;
                         subContext.scope = 0;
-                    }
+
+                        if (selector.pseudoType() == CSSSelector::PseudoHost)
+                            break;
+
+                        nextElement = NodeRenderingTraversal::parentElement(nextElement);
+                    } while (nextElement);
                 }
                 if (matched) {
                     if (specificity)
@@ -913,14 +922,14 @@
             break;
         }
         return false;
-    }
-    else if (selector->m_match == CSSSelector::PseudoElement && selector->pseudoType() == CSSSelector::PseudoCue) {
+    } else if (selector.m_match == CSSSelector::PseudoElement && selector.pseudoType() == CSSSelector::PseudoCue) {
         SelectorCheckingContext subContext(context);
         subContext.isSubSelector = true;
         subContext.behaviorAtBoundary = StaysWithinTreeScope;
 
-        const CSSSelector* const & selector = context.selector;
-        for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(subContext.selector)) {
+        const CSSSelector* contextSelector = context.selector;
+        ASSERT(contextSelector);
+        for (subContext.selector = contextSelector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(*subContext.selector)) {
             if (match(subContext, siblingTraversalStrategy) == SelectorMatches)
                 return true;
         }
@@ -930,21 +939,21 @@
     return true;
 }
 
-bool SelectorChecker::checkScrollbarPseudoClass(const SelectorCheckingContext& context, Document* document, const CSSSelector* selector) const
+bool SelectorChecker::checkScrollbarPseudoClass(const SelectorCheckingContext& context, Document* document, const CSSSelector& selector) const
 {
     RenderScrollbar* scrollbar = context.scrollbar;
     ScrollbarPart part = context.scrollbarPart;
 
     // FIXME: This is a temporary hack for resizers and scrollbar corners. Eventually :window-inactive should become a real
     // pseudo class and just apply to everything.
-    if (selector->pseudoType() == CSSSelector::PseudoWindowInactive)
+    if (selector.pseudoType() == CSSSelector::PseudoWindowInactive)
         return !document->page()->focusController().isActive();
 
     if (!scrollbar)
         return false;
 
-    ASSERT(selector->m_match == CSSSelector::PseudoClass);
-    switch (selector->pseudoType()) {
+    ASSERT(selector.m_match == CSSSelector::PseudoClass);
+    switch (selector.pseudoType()) {
     case CSSSelector::PseudoEnabled:
         return scrollbar->enabled();
     case CSSSelector::PseudoDisabled:
@@ -1011,19 +1020,19 @@
     }
 }
 
-unsigned SelectorChecker::determineLinkMatchType(const CSSSelector* selector)
+unsigned SelectorChecker::determineLinkMatchType(const CSSSelector& selector)
 {
     unsigned linkMatchType = MatchAll;
 
     // Statically determine if this selector will match a link in visited, unvisited or any state, or never.
     // :visited never matches other elements than the innermost link element.
-    for (; selector; selector = selector->tagHistory()) {
-        switch (selector->pseudoType()) {
+    for (const CSSSelector* current = &selector; current; current = current->tagHistory()) {
+        switch (current->pseudoType()) {
         case CSSSelector::PseudoNot:
             {
                 // :not(:visited) is equivalent to :link. Parser enforces that :not can't nest.
-                ASSERT(selector->selectorList());
-                for (const CSSSelector* subSelector = selector->selectorList()->first(); subSelector; subSelector = subSelector->tagHistory()) {
+                ASSERT(current->selectorList());
+                for (const CSSSelector* subSelector = current->selectorList()->first(); subSelector; subSelector = subSelector->tagHistory()) {
                     CSSSelector::PseudoType subType = subSelector->pseudoType();
                     if (subType == CSSSelector::PseudoVisited)
                         linkMatchType &= ~SelectorChecker::MatchVisited;
@@ -1042,7 +1051,7 @@
             // We don't support :link and :visited inside :-webkit-any.
             break;
         }
-        CSSSelector::Relation relation = selector->relation();
+        CSSSelector::Relation relation = current->relation();
         if (relation == CSSSelector::SubSelector)
             continue;
         if (relation != CSSSelector::Descendant && relation != CSSSelector::Child)
diff --git a/Source/core/css/SelectorChecker.h b/Source/core/css/SelectorChecker.h
index 13d7d7d..fd98ccc 100644
--- a/Source/core/css/SelectorChecker.h
+++ b/Source/core/css/SelectorChecker.h
@@ -49,14 +49,14 @@
     explicit SelectorChecker(Document&, Mode);
     enum BehaviorAtBoundary {
         DoesNotCrossBoundary = 0,
-        CrossesBoundary = 1,
+        // FIXME: refactor to remove BoundaryBehavior (i.e. DoesNotCrossBoundary and StaysWithinTreeScope).
         StaysWithinTreeScope = 2,
         BoundaryBehaviorMask = 3, // 2bit for boundary behavior
         ScopeContainsLastMatchedElement = 4,
         ScopeIsShadowHost = 8,
         TreatShadowHostAsNormalScope = 16,
 
-        ScopeIsShadowHostInPseudoHostParameter = CrossesBoundary | ScopeIsShadowHost | TreatShadowHostAsNormalScope
+        ScopeIsShadowHostInPseudoHostParameter = ScopeIsShadowHost | TreatShadowHostAsNormalScope
     };
 
     enum MatchingTagType {
@@ -66,8 +66,8 @@
 
     struct SelectorCheckingContext {
         // Initial selector constructor
-        SelectorCheckingContext(const CSSSelector* selector, Element* element, VisitedMatchType visitedMatchType)
-            : selector(selector)
+        SelectorCheckingContext(const CSSSelector& selector, Element* element, VisitedMatchType visitedMatchType)
+            : selector(&selector)
             , element(element)
             , scope(0)
             , visitedMatchType(visitedMatchType)
@@ -115,12 +115,12 @@
     Mode mode() const { return m_mode; }
 
     static bool tagMatches(const Element&, const QualifiedName&, MatchingTagType = MatchingElement);
-    static bool isCommonPseudoClassSelector(const CSSSelector*);
+    static bool isCommonPseudoClassSelector(const CSSSelector&);
     static bool matchesFocusPseudoClass(const Element&);
     static bool checkExactAttribute(const Element&, const QualifiedName& selectorAttributeName, const StringImpl* value);
 
     enum LinkMatchMask { MatchLink = 1, MatchVisited = 2, MatchAll = MatchLink | MatchVisited };
-    static unsigned determineLinkMatchType(const CSSSelector*);
+    static unsigned determineLinkMatchType(const CSSSelector&);
 
     static bool isHostInItsShadowTree(const Element&, BehaviorAtBoundary, const ContainerNode* scope);
 
@@ -132,8 +132,8 @@
     template<typename SiblingTraversalStrategy>
     Match matchForShadowDistributed(const Element*, const SiblingTraversalStrategy&, SelectorCheckingContext& nextContext, MatchResult* = 0) const;
 
-    bool checkScrollbarPseudoClass(const SelectorCheckingContext&, Document*, const CSSSelector*) const;
-    Element* parentElement(const SelectorCheckingContext&) const;
+    bool checkScrollbarPseudoClass(const SelectorCheckingContext&, Document*, const CSSSelector&) const;
+    Element* parentElement(const SelectorCheckingContext&, bool allowToCrossBoundary = false) const;
     bool scopeContainsLastMatchedElement(const SelectorCheckingContext&) const;
 
     static bool isFrameFocused(const Element&);
@@ -143,11 +143,11 @@
     Mode m_mode;
 };
 
-inline bool SelectorChecker::isCommonPseudoClassSelector(const CSSSelector* selector)
+inline bool SelectorChecker::isCommonPseudoClassSelector(const CSSSelector& selector)
 {
-    if (selector->m_match != CSSSelector::PseudoClass)
+    if (selector.m_match != CSSSelector::PseudoClass)
         return false;
-    CSSSelector::PseudoType pseudoType = selector->pseudoType();
+    CSSSelector::PseudoType pseudoType = selector.pseudoType();
     return pseudoType == CSSSelector::PseudoLink
         || pseudoType == CSSSelector::PseudoAnyLink
         || pseudoType == CSSSelector::PseudoVisited
diff --git a/Source/core/css/SelectorCheckerFastPath.cpp b/Source/core/css/SelectorCheckerFastPath.cpp
index 557f043..943e262 100644
--- a/Source/core/css/SelectorCheckerFastPath.cpp
+++ b/Source/core/css/SelectorCheckerFastPath.cpp
@@ -39,11 +39,11 @@
 
 namespace {
 
-template <bool checkValue(const Element&, const CSSSelector*)>
+template <bool checkValue(const Element&, const CSSSelector&)>
 inline bool fastCheckSingleSelector(const CSSSelector*& selector, const Element*& element, const CSSSelector*& topChildOrSubselector, const Element*& topChildOrSubselectorMatchElement)
 {
     for (; element; element = element->parentElement()) {
-        if (checkValue(*element, selector)) {
+        if (checkValue(*element, *selector)) {
             if (selector->relation() == CSSSelector::Descendant)
                 topChildOrSubselector = 0;
             else if (!topChildOrSubselector) {
@@ -73,29 +73,29 @@
     return false;
 }
 
-inline bool checkClassValue(const Element& element, const CSSSelector* selector)
+inline bool checkClassValue(const Element& element, const CSSSelector& selector)
 {
-    return element.hasClass() && element.classNames().contains(selector->value());
+    return element.hasClass() && element.classNames().contains(selector.value());
 }
 
-inline bool checkIDValue(const Element& element, const CSSSelector* selector)
+inline bool checkIDValue(const Element& element, const CSSSelector& selector)
 {
-    return element.hasID() && element.idForStyleResolution() == selector->value();
+    return element.hasID() && element.idForStyleResolution() == selector.value();
 }
 
-inline bool checkExactAttributeValue(const Element& element, const CSSSelector* selector)
+inline bool checkExactAttributeValue(const Element& element, const CSSSelector& selector)
 {
-    return SelectorChecker::checkExactAttribute(element, selector->attribute(), selector->value().impl());
+    return SelectorChecker::checkExactAttribute(element, selector.attribute(), selector.value().impl());
 }
 
-inline bool checkTagValue(const Element& element, const CSSSelector* selector)
+inline bool checkTagValue(const Element& element, const CSSSelector& selector)
 {
-    return SelectorChecker::tagMatches(element, selector->tagQName());
+    return SelectorChecker::tagMatches(element, selector.tagQName());
 }
 
 }
 
-SelectorCheckerFastPath::SelectorCheckerFastPath(const CSSSelector* selector, const Element& element)
+SelectorCheckerFastPath::SelectorCheckerFastPath(const CSSSelector& selector, const Element& element)
     : m_selector(selector)
     , m_element(element)
 {
@@ -105,7 +105,7 @@
 {
     ASSERT(SelectorCheckerFastPath::canUse(m_selector));
 
-    switch (m_selector->m_match) {
+    switch (m_selector.m_match) {
     case CSSSelector::Tag:
         return checkTagValue(m_element, m_selector);
     case CSSSelector::Class:
@@ -126,7 +126,7 @@
 bool SelectorCheckerFastPath::matches() const
 {
     ASSERT(matchesRightmostSelector(SelectorChecker::VisitedMatchEnabled));
-    const CSSSelector* selector = m_selector;
+    const CSSSelector* selector = &m_selector;
     const Element* element = &m_element;
 
     const CSSSelector* topChildOrSubselector = 0;
@@ -171,33 +171,33 @@
     return relation == CSSSelector::Descendant || relation == CSSSelector::Child || relation == CSSSelector::SubSelector;
 }
 
-static inline bool isFastCheckableMatch(const CSSSelector* selector)
+static inline bool isFastCheckableMatch(const CSSSelector& selector)
 {
-    if (selector->m_match == CSSSelector::Set) {
+    if (selector.m_match == CSSSelector::Set) {
         // Style attribute is generated lazily but the fast path doesn't trigger it.
         // Disallow them here rather than making the fast path more branchy.
-        return selector->attribute() != styleAttr;
+        return selector.attribute() != styleAttr;
     }
-    if (selector->m_match == CSSSelector::Exact)
-        return selector->attribute() != styleAttr && HTMLDocument::isCaseSensitiveAttribute(selector->attribute());
-    return selector->m_match == CSSSelector::Tag || selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
+    if (selector.m_match == CSSSelector::Exact)
+        return selector.attribute() != styleAttr && HTMLDocument::isCaseSensitiveAttribute(selector.attribute());
+    return selector.m_match == CSSSelector::Tag || selector.m_match == CSSSelector::Id || selector.m_match == CSSSelector::Class;
 }
 
-static inline bool isFastCheckableRightmostSelector(const CSSSelector* selector)
+static inline bool isFastCheckableRightmostSelector(const CSSSelector& selector)
 {
-    if (!isFastCheckableRelation(selector->relation()))
+    if (!isFastCheckableRelation(selector.relation()))
         return false;
     return isFastCheckableMatch(selector) || SelectorChecker::isCommonPseudoClassSelector(selector);
 }
 
-bool SelectorCheckerFastPath::canUse(const CSSSelector* selector)
+bool SelectorCheckerFastPath::canUse(const CSSSelector& selector)
 {
     if (!isFastCheckableRightmostSelector(selector))
         return false;
-    for (selector = selector->tagHistory(); selector; selector = selector->tagHistory()) {
-        if (!isFastCheckableRelation(selector->relation()))
+    for (const CSSSelector* current = selector.tagHistory(); current; current = current->tagHistory()) {
+        if (!isFastCheckableRelation(current->relation()))
             return false;
-        if (!isFastCheckableMatch(selector))
+        if (!isFastCheckableMatch(*current))
             return false;
     }
     return true;
@@ -206,7 +206,7 @@
 bool SelectorCheckerFastPath::commonPseudoClassSelectorMatches(SelectorChecker::VisitedMatchType visitedMatchType) const
 {
     ASSERT(SelectorChecker::isCommonPseudoClassSelector(m_selector));
-    switch (m_selector->pseudoType()) {
+    switch (m_selector.pseudoType()) {
     case CSSSelector::PseudoLink:
     case CSSSelector::PseudoAnyLink:
         return m_element.isLink();
diff --git a/Source/core/css/SelectorCheckerFastPath.h b/Source/core/css/SelectorCheckerFastPath.h
index 1a37b9a..3e0d946 100644
--- a/Source/core/css/SelectorCheckerFastPath.h
+++ b/Source/core/css/SelectorCheckerFastPath.h
@@ -36,26 +36,26 @@
 
 class SelectorCheckerFastPath {
 public:
-    SelectorCheckerFastPath(const CSSSelector*, const Element&);
+    SelectorCheckerFastPath(const CSSSelector&, const Element&);
 
     bool matches() const;
     bool matchesRightmostSelector(SelectorChecker::VisitedMatchType) const;
     bool matchesRightmostAttributeSelector() const;
 
-    static bool canUse(const CSSSelector*);
+    static bool canUse(const CSSSelector&);
 
 private:
     bool commonPseudoClassSelectorMatches(SelectorChecker::VisitedMatchType) const;
 
-    const CSSSelector* m_selector;
+    const CSSSelector& m_selector;
     const Element& m_element;
 };
 
 inline bool SelectorCheckerFastPath::matchesRightmostAttributeSelector() const
 {
-    if (m_selector->m_match == CSSSelector::Exact || m_selector->m_match == CSSSelector::Set)
-        return SelectorChecker::checkExactAttribute(m_element, m_selector->attribute(), m_selector->value().impl());
-    ASSERT(!m_selector->isAttributeSelector());
+    if (m_selector.m_match == CSSSelector::Exact || m_selector.m_match == CSSSelector::Set)
+        return SelectorChecker::checkExactAttribute(m_element, m_selector.attribute(), m_selector.value().impl());
+    ASSERT(!m_selector.isAttributeSelector());
     return true;
 }
 
diff --git a/Source/core/css/SelectorFilter.cpp b/Source/core/css/SelectorFilter.cpp
index 50d13de..352ae8f 100644
--- a/Source/core/css/SelectorFilter.cpp
+++ b/Source/core/css/SelectorFilter.cpp
@@ -108,41 +108,41 @@
     pushParentStackFrame(parent);
 }
 
-static inline void collectDescendantSelectorIdentifierHashes(const CSSSelector* selector, unsigned*& hash)
+static inline void collectDescendantSelectorIdentifierHashes(const CSSSelector& selector, unsigned*& hash)
 {
-    switch (selector->m_match) {
+    switch (selector.m_match) {
     case CSSSelector::Id:
-        if (!selector->value().isEmpty())
-            (*hash++) = selector->value().impl()->existingHash() * IdAttributeSalt;
+        if (!selector.value().isEmpty())
+            (*hash++) = selector.value().impl()->existingHash() * IdAttributeSalt;
         break;
     case CSSSelector::Class:
-        if (!selector->value().isEmpty())
-            (*hash++) = selector->value().impl()->existingHash() * ClassAttributeSalt;
+        if (!selector.value().isEmpty())
+            (*hash++) = selector.value().impl()->existingHash() * ClassAttributeSalt;
         break;
     case CSSSelector::Tag:
-        if (selector->tagQName().localName() != starAtom)
-            (*hash++) = selector->tagQName().localName().impl()->existingHash() * TagNameSalt;
+        if (selector.tagQName().localName() != starAtom)
+            (*hash++) = selector.tagQName().localName().impl()->existingHash() * TagNameSalt;
         break;
     default:
         break;
     }
 }
 
-void SelectorFilter::collectIdentifierHashes(const CSSSelector* selector, unsigned* identifierHashes, unsigned maximumIdentifierCount)
+void SelectorFilter::collectIdentifierHashes(const CSSSelector& selector, unsigned* identifierHashes, unsigned maximumIdentifierCount)
 {
     unsigned* hash = identifierHashes;
     unsigned* end = identifierHashes + maximumIdentifierCount;
-    CSSSelector::Relation relation = selector->relation();
-    bool relationIsAffectedByPseudoContent = selector->relationIsAffectedByPseudoContent();
+    CSSSelector::Relation relation = selector.relation();
+    bool relationIsAffectedByPseudoContent = selector.relationIsAffectedByPseudoContent();
 
     // Skip the topmost selector. It is handled quickly by the rule hashes.
     bool skipOverSubselectors = true;
-    for (selector = selector->tagHistory(); selector; selector = selector->tagHistory()) {
+    for (const CSSSelector* current = selector.tagHistory(); current; current = current->tagHistory()) {
         // Only collect identifiers that match ancestors.
         switch (relation) {
         case CSSSelector::SubSelector:
             if (!skipOverSubselectors)
-                collectDescendantSelectorIdentifierHashes(selector, hash);
+                collectDescendantSelectorIdentifierHashes(*current, hash);
             break;
         case CSSSelector::DirectAdjacent:
         case CSSSelector::IndirectAdjacent:
@@ -160,13 +160,13 @@
         case CSSSelector::ChildTree:
         case CSSSelector::DescendantTree:
             skipOverSubselectors = false;
-            collectDescendantSelectorIdentifierHashes(selector, hash);
+            collectDescendantSelectorIdentifierHashes(*current, hash);
             break;
         }
         if (hash == end)
             return;
-        relation = selector->relation();
-        relationIsAffectedByPseudoContent = selector->relationIsAffectedByPseudoContent();
+        relation = current->relation();
+        relationIsAffectedByPseudoContent = current->relationIsAffectedByPseudoContent();
     }
     *hash = 0;
 }
diff --git a/Source/core/css/SelectorFilter.h b/Source/core/css/SelectorFilter.h
index 905edb6..8a2e852 100644
--- a/Source/core/css/SelectorFilter.h
+++ b/Source/core/css/SelectorFilter.h
@@ -50,7 +50,7 @@
 
     template <unsigned maximumIdentifierCount>
     inline bool fastRejectSelector(const unsigned* identifierHashes) const;
-    static void collectIdentifierHashes(const CSSSelector*, unsigned* identifierHashes, unsigned maximumIdentifierCount);
+    static void collectIdentifierHashes(const CSSSelector&, unsigned* identifierHashes, unsigned maximumIdentifierCount);
 
 private:
     struct ParentStackFrame {
diff --git a/Source/core/css/SiblingTraversalStrategies.h b/Source/core/css/SiblingTraversalStrategies.h
index b082fa6..c14d3e5 100644
--- a/Source/core/css/SiblingTraversalStrategies.h
+++ b/Source/core/css/SiblingTraversalStrategies.h
@@ -30,63 +30,64 @@
 #define SiblingTraversalStrategies_h
 
 #include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
 
 struct DOMSiblingTraversalStrategy {
-    bool isFirstChild(Element*) const;
-    bool isLastChild(Element*) const;
-    bool isFirstOfType(Element*, const QualifiedName&) const;
-    bool isLastOfType(Element*, const QualifiedName&) const;
+    bool isFirstChild(Element&) const;
+    bool isLastChild(Element&) const;
+    bool isFirstOfType(Element&, const QualifiedName&) const;
+    bool isLastOfType(Element&, const QualifiedName&) const;
 
-    int countElementsBefore(Element*) const;
-    int countElementsAfter(Element*) const;
-    int countElementsOfTypeBefore(Element*, const QualifiedName&) const;
-    int countElementsOfTypeAfter(Element*, const QualifiedName&) const;
+    int countElementsBefore(Element&) const;
+    int countElementsAfter(Element&) const;
+    int countElementsOfTypeBefore(Element&, const QualifiedName&) const;
+    int countElementsOfTypeAfter(Element&, const QualifiedName&) const;
 };
 
-inline bool DOMSiblingTraversalStrategy::isFirstChild(Element* element) const
+inline bool DOMSiblingTraversalStrategy::isFirstChild(Element& element) const
 {
-    return !element->previousElementSibling();
+    return !ElementTraversal::previousSibling(element);
 }
 
-inline bool DOMSiblingTraversalStrategy::isLastChild(Element* element) const
+inline bool DOMSiblingTraversalStrategy::isLastChild(Element& element) const
 {
-    return !element->nextElementSibling();
+    return !ElementTraversal::nextSibling(element);
 }
 
-inline bool DOMSiblingTraversalStrategy::isFirstOfType(Element* element, const QualifiedName& type) const
+inline bool DOMSiblingTraversalStrategy::isFirstOfType(Element& element, const QualifiedName& type) const
 {
-    for (const Element* sibling = element->previousElementSibling(); sibling; sibling = sibling->previousElementSibling()) {
+    for (const Element* sibling = ElementTraversal::previousSibling(element); sibling; sibling = ElementTraversal::previousSibling(*sibling)) {
         if (sibling->hasTagName(type))
             return false;
     }
     return true;
 }
 
-inline bool DOMSiblingTraversalStrategy::isLastOfType(Element* element, const QualifiedName& type) const
+inline bool DOMSiblingTraversalStrategy::isLastOfType(Element& element, const QualifiedName& type) const
 {
-    for (const Element* sibling = element->nextElementSibling(); sibling; sibling = sibling->nextElementSibling()) {
+    for (const Element* sibling = ElementTraversal::nextSibling(element); sibling; sibling = ElementTraversal::nextSibling(*sibling)) {
         if (sibling->hasTagName(type))
             return false;
     }
     return true;
 }
 
-inline int DOMSiblingTraversalStrategy::countElementsBefore(Element* element) const
+inline int DOMSiblingTraversalStrategy::countElementsBefore(Element& element) const
 {
     int count = 0;
-    for (const Element* sibling = element->previousElementSibling(); sibling; sibling = sibling->previousElementSibling())
+    for (const Element* sibling = ElementTraversal::previousSibling(element); sibling; sibling = ElementTraversal::previousSibling(*sibling))
         count++;
 
     return count;
 }
 
-inline int DOMSiblingTraversalStrategy::countElementsOfTypeBefore(Element* element, const QualifiedName& type) const
+inline int DOMSiblingTraversalStrategy::countElementsOfTypeBefore(Element& element, const QualifiedName& type) const
 {
     int count = 0;
-    for (const Element* sibling = element->previousElementSibling(); sibling; sibling = sibling->previousElementSibling()) {
+    for (const Element* sibling = ElementTraversal::previousSibling(element); sibling; sibling = ElementTraversal::previousSibling(*sibling)) {
         if (sibling->hasTagName(type))
             ++count;
     }
@@ -94,19 +95,19 @@
     return count;
 }
 
-inline int DOMSiblingTraversalStrategy::countElementsAfter(Element* element) const
+inline int DOMSiblingTraversalStrategy::countElementsAfter(Element& element) const
 {
     int count = 0;
-    for (const Element* sibling = element->nextElementSibling(); sibling; sibling = sibling->nextElementSibling())
+    for (const Element* sibling = ElementTraversal::nextSibling(element); sibling; sibling = ElementTraversal::nextSibling(*sibling))
         ++count;
 
     return count;
 }
 
-inline int DOMSiblingTraversalStrategy::countElementsOfTypeAfter(Element* element, const QualifiedName& type) const
+inline int DOMSiblingTraversalStrategy::countElementsOfTypeAfter(Element& element, const QualifiedName& type) const
 {
     int count = 0;
-    for (const Element* sibling = element->nextElementSibling(); sibling; sibling = sibling->nextElementSibling()) {
+    for (const Element* sibling = ElementTraversal::nextSibling(element); sibling; sibling = ElementTraversal::nextSibling(*sibling)) {
         if (sibling->hasTagName(type))
             ++count;
     }
@@ -121,22 +122,22 @@
     {
     }
 
-    bool isFirstChild(Element*) const;
-    bool isLastChild(Element*) const;
-    bool isFirstOfType(Element*, const QualifiedName&) const;
-    bool isLastOfType(Element*, const QualifiedName&) const;
+    bool isFirstChild(Element&) const;
+    bool isLastChild(Element&) const;
+    bool isFirstOfType(Element&, const QualifiedName&) const;
+    bool isLastOfType(Element&, const QualifiedName&) const;
 
-    int countElementsBefore(Element*) const;
-    int countElementsAfter(Element*) const;
-    int countElementsOfTypeBefore(Element*, const QualifiedName&) const;
-    int countElementsOfTypeAfter(Element*, const QualifiedName&) const;
+    int countElementsBefore(Element&) const;
+    int countElementsAfter(Element&) const;
+    int countElementsOfTypeBefore(Element&, const QualifiedName&) const;
+    int countElementsOfTypeAfter(Element&, const QualifiedName&) const;
 
 private:
     const Vector<Node*, 32>& m_siblings;
     int m_nth;
 };
 
-inline bool ShadowDOMSiblingTraversalStrategy::isFirstChild(Element* element) const
+inline bool ShadowDOMSiblingTraversalStrategy::isFirstChild(Element& element) const
 {
     ASSERT(element == toElement(m_siblings[m_nth]));
 
@@ -148,7 +149,7 @@
     return true;
 }
 
-inline bool ShadowDOMSiblingTraversalStrategy::isLastChild(Element* element) const
+inline bool ShadowDOMSiblingTraversalStrategy::isLastChild(Element& element) const
 {
     ASSERT(element == toElement(m_siblings[m_nth]));
 
@@ -160,7 +161,7 @@
     return true;
 }
 
-inline bool ShadowDOMSiblingTraversalStrategy::isFirstOfType(Element* element, const QualifiedName& type) const
+inline bool ShadowDOMSiblingTraversalStrategy::isFirstOfType(Element& element, const QualifiedName& type) const
 {
     ASSERT(element == toElement(m_siblings[m_nth]));
 
@@ -172,7 +173,7 @@
     return true;
 }
 
-inline bool ShadowDOMSiblingTraversalStrategy::isLastOfType(Element* element, const QualifiedName& type) const
+inline bool ShadowDOMSiblingTraversalStrategy::isLastOfType(Element& element, const QualifiedName& type) const
 {
     ASSERT(element == toElement(m_siblings[m_nth]));
 
@@ -184,7 +185,7 @@
     return true;
 }
 
-inline int ShadowDOMSiblingTraversalStrategy::countElementsBefore(Element* element) const
+inline int ShadowDOMSiblingTraversalStrategy::countElementsBefore(Element& element) const
 {
     ASSERT(element == toElement(m_siblings[m_nth]));
 
@@ -197,7 +198,7 @@
     return count;
 }
 
-inline int ShadowDOMSiblingTraversalStrategy::countElementsAfter(Element* element) const
+inline int ShadowDOMSiblingTraversalStrategy::countElementsAfter(Element& element) const
 {
     ASSERT(element == toElement(m_siblings[m_nth]));
 
@@ -210,7 +211,7 @@
     return count;
 }
 
-inline int ShadowDOMSiblingTraversalStrategy::countElementsOfTypeBefore(Element* element, const QualifiedName& type) const
+inline int ShadowDOMSiblingTraversalStrategy::countElementsOfTypeBefore(Element& element, const QualifiedName& type) const
 {
     ASSERT(element == toElement(m_siblings[m_nth]));
 
@@ -223,7 +224,7 @@
     return count;
 }
 
-inline int ShadowDOMSiblingTraversalStrategy::countElementsOfTypeAfter(Element* element, const QualifiedName& type) const
+inline int ShadowDOMSiblingTraversalStrategy::countElementsOfTypeAfter(Element& element, const QualifiedName& type) const
 {
     ASSERT(element == toElement(m_siblings[m_nth]));
 
diff --git a/Source/core/css/StyleColor.h b/Source/core/css/StyleColor.h
index 1f58584..3c26609 100644
--- a/Source/core/css/StyleColor.h
+++ b/Source/core/css/StyleColor.h
@@ -32,79 +32,30 @@
 #define StyleColor_h
 
 #include "platform/graphics/Color.h"
-#include "wtf/FastAllocBase.h"
 
 namespace WebCore {
 
 class StyleColor {
-    WTF_MAKE_FAST_ALLOCATED;
 public:
-    StyleColor()
-        : m_color()
-        , m_valid(false)
-        , m_currentColor(false) { }
-    StyleColor(Color color)
-        : m_color(color)
-        , m_valid(true)
-        , m_currentColor(false) { }
-    StyleColor(RGBA32 color, bool valid = true, bool currentColor = false)
-        : m_color(color)
-        , m_valid(valid)
-        , m_currentColor(currentColor) { }
-    StyleColor(int r, int g, int b)
-        : m_color(Color(r, g, b))
-        , m_valid(true)
-        , m_currentColor(false) { }
-    StyleColor(int r, int g, int b, int a)
-        : m_color(Color(r, g, b, a))
-        , m_valid(true)
-        , m_currentColor(false) { }
-    StyleColor(const StyleColor& other)
-        : m_color(other.m_color)
-        , m_valid(other.m_valid)
-        , m_currentColor(other.m_currentColor) { }
+    StyleColor(Color color) : m_color(color), m_currentColor(false) { }
+    static StyleColor currentColor() { return StyleColor(); }
 
-    Color color() const { return m_color; }
-    bool isValid() const { return m_valid; }
     bool isCurrentColor() const { return m_currentColor; }
-    bool hasAlpha() const { return m_color.hasAlpha(); }
+    Color color() const { ASSERT(!isCurrentColor()); return m_color; }
 
-    void setRGB(int r, int g, int b)
-    {
-        m_color.setRGB(r, g, b);
-        m_valid = true;
-        m_currentColor = false;
-    }
-
-    RGBA32 rgb() const { return m_color.rgb(); } // Preserve the alpha.
-    int red() const { return m_color.red(); }
-    int green() const { return m_color.green(); }
-    int blue() const { return m_color.blue(); }
-    int alpha() const { return m_color.alpha(); }
-
-    static const StyleColor invalid()
-    {
-        return StyleColor(false, false);
-    }
-    static const StyleColor currentColor()
-    {
-        return StyleColor(true, true);
-    }
+    Color resolve(Color currentColor) const { return m_currentColor ? currentColor : m_color; }
 
 private:
-    StyleColor(bool invalid, bool currentColor)
-        : m_color()
-        , m_valid(invalid)
-        , m_currentColor(currentColor) { }
-
+    StyleColor() : m_currentColor(true) { }
     Color m_color;
-    bool m_valid;
     bool m_currentColor;
 };
 
 inline bool operator==(const StyleColor& a, const StyleColor& b)
 {
-    return a.rgb() == b.rgb() && a.isValid() == b.isValid() && a.isCurrentColor() == b.isCurrentColor();
+    if (a.isCurrentColor() || b.isCurrentColor())
+        return a.isCurrentColor() && b.isCurrentColor();
+    return a.color() == b.color();
 }
 
 inline bool operator!=(const StyleColor& a, const StyleColor& b)
diff --git a/Source/core/css/StyleInvalidationAnalysis.cpp b/Source/core/css/StyleInvalidationAnalysis.cpp
index 440e17f..bc59425 100644
--- a/Source/core/css/StyleInvalidationAnalysis.cpp
+++ b/Source/core/css/StyleInvalidationAnalysis.cpp
@@ -46,7 +46,7 @@
 
 static bool determineSelectorScopes(const CSSSelectorList& selectorList, HashSet<StringImpl*>& idScopes, HashSet<StringImpl*>& classScopes)
 {
-    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector)) {
+    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(*selector)) {
         const CSSSelector* scopeSelector = 0;
         // This picks the widest scope, not the narrowest, to minimize the number of found scopes.
         for (const CSSSelector* current = selector; current; current = current->tagHistory()) {
@@ -56,6 +56,10 @@
             else if (current->m_match == CSSSelector::Class && (!scopeSelector || scopeSelector->m_match != CSSSelector::Id))
                 scopeSelector = current;
             CSSSelector::Relation relation = current->relation();
+            // FIXME: it would be better to use setNeedsStyleRecalc for all shadow hosts matching
+            // scopeSelector. Currently requests full style recalc.
+            if (relation == CSSSelector::DescendantTree || relation == CSSSelector::ChildTree)
+                return false;
             if (relation != CSSSelector::Descendant && relation != CSSSelector::Child && relation != CSSSelector::SubSelector)
                 break;
         }
@@ -123,7 +127,6 @@
     case StyleRule::Supports: // If we evaluated the supports-clause we could avoid recalc.
     case StyleRule::Viewport: // If the viewport doesn't match, we could avoid recalcing.
     // FIXME: Unclear if any of the rest need to cause style recalc:
-    case StyleRule::Region:
     case StyleRule::Filter:
         return true;
 
@@ -198,7 +201,7 @@
 
     if (!m_scopingNodes.isEmpty()) {
         for (unsigned i = 0; i < m_scopingNodes.size(); ++i)
-            m_scopingNodes.at(i)->setNeedsStyleRecalc();
+            m_scopingNodes.at(i)->setNeedsStyleRecalc(SubtreeStyleChange);
     }
 
     if (m_idScopes.isEmpty() && m_classScopes.isEmpty())
@@ -206,7 +209,7 @@
     Element* element = ElementTraversal::firstWithin(document);
     while (element) {
         if (elementMatchesSelectorScopes(element, m_idScopes, m_classScopes)) {
-            element->setNeedsStyleRecalc();
+            element->setNeedsStyleRecalc(SubtreeStyleChange);
             // The whole subtree is now invalidated, we can skip to the next sibling.
             element = ElementTraversal::nextSkippingChildren(*element);
             continue;
diff --git a/Source/core/css/StylePropertySerializer.cpp b/Source/core/css/StylePropertySerializer.cpp
index 98b62aa..171e6a3 100644
--- a/Source/core/css/StylePropertySerializer.cpp
+++ b/Source/core/css/StylePropertySerializer.cpp
@@ -25,7 +25,7 @@
 
 #include "CSSValueKeywords.h"
 #include "StylePropertyShorthand.h"
-#include "core/page/RuntimeCSSEnabled.h"
+#include "core/css/RuntimeCSSEnabled.h"
 #include "wtf/BitArray.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -69,11 +69,6 @@
         String value;
 
         switch (propertyID) {
-        case CSSPropertyVariable:
-            if (numDecls++)
-                result.append(' ');
-            result.append(property.cssText());
-            continue;
         case CSSPropertyBackgroundPositionX:
             positionXPropertyIndex = n;
             continue;
diff --git a/Source/core/css/StylePropertySet.cpp b/Source/core/css/StylePropertySet.cpp
index fa008ea..6a333f6 100644
--- a/Source/core/css/StylePropertySet.cpp
+++ b/Source/core/css/StylePropertySet.cpp
@@ -25,12 +25,12 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "StylePropertyShorthand.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSValuePool.h"
-#include "core/css/CSSVariableValue.h"
+#include "core/css/RuntimeCSSEnabled.h"
 #include "core/css/StylePropertySerializer.h"
 #include "core/css/StyleSheetContents.h"
-#include "core/page/RuntimeCSSEnabled.h"
+#include "core/frame/UseCounter.h"
 #include "wtf/text/StringBuilder.h"
 
 #ifndef NDEBUG
@@ -123,26 +123,6 @@
     return propertyAt(foundPropertyIndex).value();
 }
 
-unsigned StylePropertySet::variableCount() const
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    unsigned count = 0;
-    for (unsigned i = 0; i < propertyCount(); ++i) {
-        if (propertyAt(i).id() == CSSPropertyVariable)
-            count++;
-    }
-    return count;
-}
-
-String StylePropertySet::variableValue(const AtomicString& name) const
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    size_t index = findVariableIndex(name);
-    if (index == kNotFound)
-        return String();
-    return toCSSVariableValue(propertyAt(index).value())->value();
-}
-
 bool MutableStylePropertySet::removeShorthandProperty(CSSPropertyID propertyID)
 {
     StylePropertyShorthand shorthand = shorthandForProperty(propertyID);
@@ -237,7 +217,7 @@
 
     // When replacing an existing property value, this moves the property to the end of the list.
     // Firefox preserves the position, and MSIE moves the property to the beginning.
-    return CSSParser::parseValue(this, propertyID, value, important, cssParserMode(), contextStyleSheet);
+    return BisonCSSParser::parseValue(this, propertyID, value, important, cssParserMode(), contextStyleSheet);
 }
 
 void MutableStylePropertySet::setProperty(CSSPropertyID propertyID, PassRefPtr<CSSValue> prpValue, bool important)
@@ -279,28 +259,6 @@
     return indexOfShorthandForLonghand(prefixedShorthand, shorthands);
 }
 
-bool MutableStylePropertySet::setVariableValue(const AtomicString& name, const String& value, bool important)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    if (value.isEmpty())
-        return removeVariable(name);
-
-    size_t index = findVariableIndex(name);
-    if (index != kNotFound) {
-        const CSSValue* cssValue = m_propertyVector.at(index).value();
-        if (toCSSVariableValue(cssValue)->value() == value)
-            return false;
-    }
-
-    CSSProperty property(CSSPropertyVariable, CSSVariableValue::create(name, value), important);
-    if (index == kNotFound) {
-        m_propertyVector.append(property);
-        return true;
-    }
-    m_propertyVector.at(index) = property;
-    return false;
-}
-
 void MutableStylePropertySet::appendPrefixingVariantProperty(const CSSProperty& property)
 {
     m_propertyVector.append(property);
@@ -335,13 +293,13 @@
 {
     m_propertyVector.clear();
 
-    CSSParserContext context(cssParserMode());
+    CSSParserContext context(cssParserMode(), UseCounter::getFrom(contextStyleSheet));
     if (contextStyleSheet) {
         context = contextStyleSheet->parserContext();
         context.setMode(cssParserMode());
     }
 
-    CSSParser parser(context, UseCounter::getFrom(contextStyleSheet));
+    BisonCSSParser parser(context);
     parser.parseDeclaration(this, styleDeclaration, 0, contextStyleSheet);
 }
 
@@ -364,11 +322,6 @@
     return StylePropertySerializer(*this).asText();
 }
 
-bool StylePropertySet::hasCSSOMWrapper() const
-{
-    return m_isMutable && toMutableStylePropertySet(this)->m_cssomWrapper;
-}
-
 void MutableStylePropertySet::mergeAndOverrideOnConflict(const StylePropertySet* other)
 {
     unsigned size = other->propertyCount();
@@ -382,13 +335,6 @@
     }
 }
 
-void StylePropertySet::addSubresourceStyleURLs(ListHashSet<KURL>& urls, StyleSheetContents* contextStyleSheet) const
-{
-    unsigned size = propertyCount();
-    for (unsigned i = 0; i < size; ++i)
-        propertyAt(i).value()->addSubresourceStyleURLs(urls, contextStyleSheet);
-}
-
 bool StylePropertySet::hasFailedOrCanceledSubresources() const
 {
     unsigned size = propertyCount();
@@ -417,9 +363,6 @@
     CSSPropertyPageBreakAfter,
     CSSPropertyPageBreakBefore,
     CSSPropertyPageBreakInside,
-    CSSPropertyWebkitRegionBreakAfter,
-    CSSPropertyWebkitRegionBreakBefore,
-    CSSPropertyWebkitRegionBreakInside,
     CSSPropertyTextAlign,
     CSSPropertyTextAlignLast,
     CSSPropertyTextIndent,
@@ -494,17 +437,6 @@
     return -1;
 }
 
-size_t StylePropertySet::findVariableIndex(const AtomicString& name) const
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    for (int i = propertyCount() - 1; i >= 0; --i) {
-        const PropertyReference& property = propertyAt(i);
-        if (property.id() == CSSPropertyVariable && toCSSVariableValue(property.value())->name() == name)
-            return i;
-    }
-    return kNotFound;
-}
-
 CSSProperty* MutableStylePropertySet::findCSSPropertyWithID(CSSPropertyID propertyID)
 {
     int foundPropertyIndex = findPropertyIndex(propertyID);
@@ -549,75 +481,6 @@
         removeProperty(propertiesToRemove[i]);
 }
 
-bool MutableStylePropertySet::removeVariable(const AtomicString& name)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    size_t index = findVariableIndex(name);
-    if (index == kNotFound)
-        return false;
-    m_propertyVector.remove(index);
-    return true;
-}
-
-bool MutableStylePropertySet::clearVariables()
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    CSSPropertyID variablesId = CSSPropertyVariable;
-    return removePropertiesInSet(&variablesId, 1);
-}
-
-PassRefPtr<MutableStylePropertySet::VariablesIterator> MutableStylePropertySet::VariablesIterator::create(MutableStylePropertySet* propertySet)
-{
-    ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
-    const size_t propertyCount = propertySet->propertyCount();
-    size_t variableCount = 0;
-    Vector<AtomicString> remainingNames(propertyCount);
-    for (int i = propertyCount; i--; ) {
-        const PropertyReference& property = propertySet->propertyAt(i);
-        if (property.id() == CSSPropertyVariable)
-            remainingNames[variableCount++] = toCSSVariableValue(property.value())->name();
-    }
-    remainingNames.shrink(variableCount);
-
-    RefPtr<VariablesIterator> iterator = adoptRef(new VariablesIterator(propertySet));
-    // FIXME: Make use of the Vector move constructor when rvalues are supported on all platforms.
-    iterator->takeRemainingNames(remainingNames);
-    return iterator.release();
-}
-
-void MutableStylePropertySet::VariablesIterator::addedVariable(const AtomicString& name)
-{
-    ASSERT(!m_remainingNames.contains(name));
-    ASSERT(!m_newNames.contains(name));
-    m_newNames.append(name);
-}
-
-void MutableStylePropertySet::VariablesIterator::removedVariable(const AtomicString& name)
-{
-    size_t index = m_remainingNames.find(name);
-    if (index != kNotFound)
-        m_remainingNames.remove(index);
-    index = m_newNames.find(name);
-    if (index != kNotFound)
-        m_newNames.remove(index);
-}
-
-void MutableStylePropertySet::VariablesIterator::clearedVariables()
-{
-    m_remainingNames.clear();
-    m_newNames.clear();
-}
-
-void MutableStylePropertySet::VariablesIterator::advance()
-{
-    if (!atEnd())
-        m_remainingNames.removeLast();
-    if (!m_newNames.isEmpty()) {
-        m_remainingNames.appendVector(m_newNames);
-        m_newNames.clear();
-    }
-}
-
 PassRefPtr<MutableStylePropertySet> StylePropertySet::mutableCopy() const
 {
     return adoptRef(new MutableStylePropertySet(*this));
@@ -635,13 +498,10 @@
     return MutableStylePropertySet::create(list.data(), list.size());
 }
 
-PropertySetCSSStyleDeclaration* MutableStylePropertySet::cssStyleDeclaration()
-{
-    return m_cssomWrapper.get();
-}
-
 CSSStyleDeclaration* MutableStylePropertySet::ensureCSSStyleDeclaration()
 {
+    // FIXME: get rid of this weirdness of a CSSStyleDeclaration inside of a
+    // style property set.
     if (m_cssomWrapper) {
         ASSERT(!static_cast<CSSStyleDeclaration*>(m_cssomWrapper.get())->parentRule());
         ASSERT(!m_cssomWrapper->parentElement());
@@ -651,16 +511,6 @@
     return m_cssomWrapper.get();
 }
 
-CSSStyleDeclaration* MutableStylePropertySet::ensureInlineCSSStyleDeclaration(Element* parentElement)
-{
-    if (m_cssomWrapper) {
-        ASSERT(m_cssomWrapper->parentElement() == parentElement);
-        return m_cssomWrapper.get();
-    }
-    m_cssomWrapper = adoptPtr(new InlineCSSStyleDeclaration(this, parentElement));
-    return m_cssomWrapper.get();
-}
-
 unsigned StylePropertySet::averageSizeInBytes()
 {
     // Please update this if the storage scheme changes so that this longer reflects the actual size.
@@ -692,11 +542,6 @@
 
 String StylePropertySet::PropertyReference::cssName() const
 {
-    if (id() == CSSPropertyVariable) {
-        if (!propertyValue()->isVariableValue())
-            return emptyString(); // Should not happen, but if it does, avoid a bad cast.
-        return "var-" + toCSSVariableValue(propertyValue())->name();
-    }
     return getPropertyNameString(id());
 }
 
diff --git a/Source/core/css/StylePropertySet.h b/Source/core/css/StylePropertySet.h
index 1003f3b..73e7bf5 100644
--- a/Source/core/css/StylePropertySet.h
+++ b/Source/core/css/StylePropertySet.h
@@ -25,7 +25,6 @@
 #include "core/css/CSSParserMode.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSProperty.h"
-#include "core/css/CSSVariablesIterator.h"
 #include "core/css/PropertySetCSSStyleDeclaration.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/Vector.h"
@@ -87,12 +86,9 @@
     bool isEmpty() const;
     PropertyReference propertyAt(unsigned index) const { return PropertyReference(*this, index); }
     int findPropertyIndex(CSSPropertyID) const;
-    size_t findVariableIndex(const AtomicString& name) const;
 
     PassRefPtr<CSSValue> getPropertyCSSValue(CSSPropertyID) const;
     String getPropertyValue(CSSPropertyID) const;
-    unsigned variableCount() const;
-    String variableValue(const AtomicString& name) const;
 
     bool propertyIsImportant(CSSPropertyID) const;
     CSSPropertyID getPropertyShorthand(CSSPropertyID) const;
@@ -102,8 +98,6 @@
 
     CSSParserMode cssParserMode() const { return static_cast<CSSParserMode>(m_cssParserMode); }
 
-    void addSubresourceStyleURLs(ListHashSet<KURL>&, StyleSheetContents* contextStyleSheet) const;
-
     PassRefPtr<MutableStylePropertySet> mutableCopy() const;
     PassRefPtr<ImmutableStylePropertySet> immutableCopyIfNeeded() const;
 
@@ -112,7 +106,6 @@
     String asText() const;
 
     bool isMutable() const { return m_isMutable; }
-    bool hasCSSOMWrapper() const;
 
     bool hasFailedOrCanceledSubresources() const;
 
@@ -187,7 +180,6 @@
     static PassRefPtr<MutableStylePropertySet> create(const CSSProperty* properties, unsigned count);
 
     unsigned propertyCount() const { return m_propertyVector.size(); }
-    PropertySetCSSStyleDeclaration* cssStyleDeclaration();
 
     void addParsedProperties(const Vector<CSSProperty, 256>&);
     void addParsedProperty(const CSSProperty&);
@@ -202,7 +194,6 @@
     void appendPrefixingVariantProperty(const CSSProperty&);
     void setPrefixingVariantProperty(const CSSProperty&);
     void setProperty(const CSSProperty&, CSSProperty* slot = 0);
-    bool setVariableValue(const AtomicString& name, const String& value, bool important = false);
 
     bool removeProperty(CSSPropertyID, String* returnText = 0);
     void removePrefixedOrUnprefixedProperty(CSSPropertyID);
@@ -210,10 +201,6 @@
     bool removePropertiesInSet(const CSSPropertyID* set, unsigned length);
     void removeEquivalentProperties(const StylePropertySet*);
     void removeEquivalentProperties(const CSSStyleDeclaration*);
-    bool removeVariable(const AtomicString& name);
-    bool clearVariables();
-
-    PassRefPtr<CSSVariablesIterator> variablesIterator() { return VariablesIterator::create(this); }
 
     void mergeAndOverrideOnConflict(const StylePropertySet*);
 
@@ -221,31 +208,10 @@
     void parseDeclaration(const String& styleDeclaration, StyleSheetContents* contextStyleSheet);
 
     CSSStyleDeclaration* ensureCSSStyleDeclaration();
-    CSSStyleDeclaration* ensureInlineCSSStyleDeclaration(Element* parentElement);
 
     Vector<CSSProperty, 4> m_propertyVector;
 
 private:
-    class VariablesIterator : public CSSVariablesIterator {
-    public:
-        virtual ~VariablesIterator() { }
-        static PassRefPtr<VariablesIterator> create(MutableStylePropertySet*);
-    private:
-        explicit VariablesIterator(MutableStylePropertySet* propertySet) : m_propertySet(propertySet) { }
-        void takeRemainingNames(Vector<AtomicString>& remainingNames) { m_remainingNames.swap(remainingNames); }
-        virtual void advance() OVERRIDE;
-        virtual bool atEnd() const OVERRIDE { return m_remainingNames.isEmpty(); }
-        virtual AtomicString name() const OVERRIDE { return m_remainingNames.last(); }
-        virtual String value() const OVERRIDE { return m_propertySet->variableValue(name()); }
-        virtual void addedVariable(const AtomicString& name) OVERRIDE;
-        virtual void removedVariable(const AtomicString& name) OVERRIDE;
-        virtual void clearedVariables() OVERRIDE;
-
-        RefPtr<MutableStylePropertySet> m_propertySet;
-        Vector<AtomicString> m_remainingNames;
-        Vector<AtomicString> m_newNames;
-    };
-
     explicit MutableStylePropertySet(CSSParserMode);
     explicit MutableStylePropertySet(const StylePropertySet&);
     MutableStylePropertySet(const CSSProperty* properties, unsigned count);
diff --git a/Source/core/css/StyleRule.cpp b/Source/core/css/StyleRule.cpp
index 7a23e2d..669c523 100644
--- a/Source/core/css/StyleRule.cpp
+++ b/Source/core/css/StyleRule.cpp
@@ -22,14 +22,12 @@
 #include "config.h"
 #include "core/css/StyleRule.h"
 
-#include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSFilterRule.h"
 #include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSImportRule.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSMediaRule.h"
 #include "core/css/CSSPageRule.h"
-#include "core/css/CSSRegionRule.h"
 #include "core/css/CSSStyleRule.h"
 #include "core/css/CSSSupportsRule.h"
 #include "core/css/CSSViewportRule.h"
@@ -72,9 +70,6 @@
     case Supports:
         delete toStyleRuleSupports(this);
         return;
-    case Region:
-        delete toStyleRuleRegion(this);
-        return;
     case Import:
         delete toStyleRuleImport(this);
         return;
@@ -100,27 +95,25 @@
 {
     switch (type()) {
     case Style:
-        return static_cast<const StyleRule*>(this)->copy();
+        return toStyleRule(this)->copy();
     case Page:
-        return static_cast<const StyleRulePage*>(this)->copy();
+        return toStyleRulePage(this)->copy();
     case FontFace:
-        return static_cast<const StyleRuleFontFace*>(this)->copy();
+        return toStyleRuleFontFace(this)->copy();
     case Media:
-        return static_cast<const StyleRuleMedia*>(this)->copy();
+        return toStyleRuleMedia(this)->copy();
     case Supports:
-        return static_cast<const StyleRuleSupports*>(this)->copy();
-    case Region:
-        return static_cast<const StyleRuleRegion*>(this)->copy();
+        return toStyleRuleSupports(this)->copy();
     case Import:
         // FIXME: Copy import rules.
         ASSERT_NOT_REACHED();
         return 0;
     case Keyframes:
-        return static_cast<const StyleRuleKeyframes*>(this)->copy();
+        return toStyleRuleKeyframes(this)->copy();
     case Viewport:
-        return static_cast<const StyleRuleViewport*>(this)->copy();
+        return toStyleRuleViewport(this)->copy();
     case Filter:
-        return static_cast<const StyleRuleFilter*>(this)->copy();
+        return toStyleRuleFilter(this)->copy();
     case Unknown:
     case Charset:
     case Keyframe:
@@ -151,9 +144,6 @@
     case Supports:
         rule = CSSSupportsRule::create(toStyleRuleSupports(self), parentSheet);
         break;
-    case Region:
-        rule = CSSRegionRule::create(toStyleRuleRegion(self), parentSheet);
-        break;
     case Import:
         rule = CSSImportRule::create(toStyleRuleImport(self), parentSheet);
         break;
@@ -316,20 +306,6 @@
 {
 }
 
-StyleRuleRegion::StyleRuleRegion(Vector<OwnPtr<CSSParserSelector> >* selectors, Vector<RefPtr<StyleRuleBase> >& adoptRules)
-    : StyleRuleGroup(Region, adoptRules)
-{
-    ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
-    m_selectorList.adoptSelectorVector(*selectors);
-}
-
-StyleRuleRegion::StyleRuleRegion(const StyleRuleRegion& o)
-    : StyleRuleGroup(o)
-    , m_selectorList(o.m_selectorList)
-{
-    ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
-}
-
 StyleRuleViewport::StyleRuleViewport()
     : StyleRuleBase(Viewport)
 {
diff --git a/Source/core/css/StyleRule.h b/Source/core/css/StyleRule.h
index e1216eb..c868971 100644
--- a/Source/core/css/StyleRule.h
+++ b/Source/core/css/StyleRule.h
@@ -49,7 +49,6 @@
         Keyframe, // Not used. These are internally non-rule StyleKeyframe objects.
         Supports = 12,
         Viewport = 15,
-        Region = 16,
         Filter = 17
     };
 
@@ -61,7 +60,6 @@
     bool isMediaRule() const { return type() == Media; }
     bool isPageRule() const { return type() == Page; }
     bool isStyleRule() const { return type() == Style; }
-    bool isRegionRule() const { return type() == Region; }
     bool isSupportsRule() const { return type() == Supports; }
     bool isViewportRule() const { return type() == Viewport; }
     bool isImportRule() const { return type() == Import; }
@@ -216,24 +214,6 @@
     bool m_conditionIsSupported;
 };
 
-class StyleRuleRegion : public StyleRuleGroup {
-public:
-    static PassRefPtr<StyleRuleRegion> create(Vector<OwnPtr<CSSParserSelector> >* selectors, Vector<RefPtr<StyleRuleBase> >& adoptRules)
-    {
-        return adoptRef(new StyleRuleRegion(selectors, adoptRules));
-    }
-
-    const CSSSelectorList& selectorList() const { return m_selectorList; }
-
-    PassRefPtr<StyleRuleRegion> copy() const { return adoptRef(new StyleRuleRegion(*this)); }
-
-private:
-    StyleRuleRegion(Vector<OwnPtr<CSSParserSelector> >*, Vector<RefPtr<StyleRuleBase> >& adoptRules);
-    StyleRuleRegion(const StyleRuleRegion&);
-
-    CSSSelectorList m_selectorList;
-};
-
 class StyleRuleViewport : public StyleRuleBase {
 public:
     static PassRefPtr<StyleRuleViewport> create() { return adoptRef(new StyleRuleViewport); }
@@ -285,7 +265,6 @@
 DEFINE_STYLE_RULE_TYPE_CASTS(Page);
 DEFINE_STYLE_RULE_TYPE_CASTS(Media);
 DEFINE_STYLE_RULE_TYPE_CASTS(Supports);
-DEFINE_STYLE_RULE_TYPE_CASTS(Region);
 DEFINE_STYLE_RULE_TYPE_CASTS(Viewport);
 DEFINE_STYLE_RULE_TYPE_CASTS(Filter);
 
diff --git a/Source/core/css/StyleRuleImport.cpp b/Source/core/css/StyleRuleImport.cpp
index aff60cb..0c6732a 100644
--- a/Source/core/css/StyleRuleImport.cpp
+++ b/Source/core/css/StyleRuleImport.cpp
@@ -62,7 +62,7 @@
     if (m_styleSheet)
         m_styleSheet->clearOwnerRule();
 
-    CSSParserContext context = m_parentStyleSheet ? m_parentStyleSheet->parserContext() : HTMLStandardMode;
+    CSSParserContext context = m_parentStyleSheet ? m_parentStyleSheet->parserContext() : strictCSSParserContext();
     context.setCharset(charset);
     if (!baseURL.isNull())
         context.setBaseURL(baseURL);
diff --git a/Source/core/css/StyleRuleImport.h b/Source/core/css/StyleRuleImport.h
index 8af664e..687ca8a 100644
--- a/Source/core/css/StyleRuleImport.h
+++ b/Source/core/css/StyleRuleImport.h
@@ -54,11 +54,11 @@
 private:
     // NOTE: We put the StyleSheetResourceClient in a member instead of inheriting from it
     // to avoid adding a vptr to StyleRuleImport.
-    class ImportedStyleSheetClient : public StyleSheetResourceClient {
+    class ImportedStyleSheetClient FINAL : public StyleSheetResourceClient {
     public:
         ImportedStyleSheetClient(StyleRuleImport* ownerRule) : m_ownerRule(ownerRule) { }
         virtual ~ImportedStyleSheetClient() { }
-        virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* sheet)
+        virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* sheet) OVERRIDE
         {
             m_ownerRule->setCSSStyleSheet(href, baseURL, charset, sheet);
         }
diff --git a/Source/core/css/StyleSheet.idl b/Source/core/css/StyleSheet.idl
index e3e13b3..1071475 100644
--- a/Source/core/css/StyleSheet.idl
+++ b/Source/core/css/StyleSheet.idl
@@ -21,7 +21,7 @@
 // Introduced in DOM Level 2:
 [
     Custom=Wrap,
-    GenerateVisitDOMWrapper=ownerNode,
+    SetWrapperReferenceFrom=ownerNode,
 ] interface StyleSheet {
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString        type;
              attribute boolean          disabled;
diff --git a/Source/core/css/StyleSheetContents.cpp b/Source/core/css/StyleSheetContents.cpp
index 14d8978..87e4144 100644
--- a/Source/core/css/StyleSheetContents.cpp
+++ b/Source/core/css/StyleSheetContents.cpp
@@ -21,22 +21,25 @@
 #include "config.h"
 #include "core/css/StyleSheetContents.h"
 
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/MediaList.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
 #include "core/css/StyleRuleImport.h"
-#include "core/css/resolver/StyleResolver.h"
+#include "core/dom/Document.h"
 #include "core/dom/Node.h"
 #include "core/dom/StyleEngine.h"
 #include "core/fetch/CSSStyleSheetResource.h"
+#include "core/frame/UseCounter.h"
 #include "platform/TraceEvent.h"
 #include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Deque.h"
 
 namespace WebCore {
 
+DEFINE_GC_INFO(StyleSheetContents);
+
 // Rough size estimate for the memory cache.
 unsigned StyleSheetContents::estimatedSizeInBytes() const
 {
@@ -44,7 +47,7 @@
     // The assumption is that nearly all of of them are atomic and would exist anyway.
     unsigned size = sizeof(*this);
 
-    // FIXME: This ignores the children of media and region rules.
+    // FIXME: This ignores the children of media rules.
     // Most rules are StyleRules.
     size += ruleCount() * StyleRule::averageSizeInBytes();
 
@@ -58,32 +61,31 @@
 StyleSheetContents::StyleSheetContents(StyleRuleImport* ownerRule, const String& originalURL, const CSSParserContext& context)
     : m_ownerRule(ownerRule)
     , m_originalURL(originalURL)
-    , m_loadCompleted(false)
     , m_hasSyntacticallyValidCSSHeader(true)
     , m_didLoadErrorOccur(false)
     , m_usesRemUnits(false)
     , m_isMutable(false)
     , m_isInMemoryCache(false)
     , m_hasFontFaceRule(false)
+    , m_hasMediaQueries(false)
     , m_parserContext(context)
 {
 }
 
 StyleSheetContents::StyleSheetContents(const StyleSheetContents& o)
-    : RefCounted<StyleSheetContents>()
-    , m_ownerRule(0)
+    : m_ownerRule(0)
     , m_originalURL(o.m_originalURL)
     , m_encodingFromCharsetRule(o.m_encodingFromCharsetRule)
     , m_importRules(o.m_importRules.size())
     , m_childRules(o.m_childRules.size())
     , m_namespaces(o.m_namespaces)
-    , m_loadCompleted(true)
     , m_hasSyntacticallyValidCSSHeader(o.m_hasSyntacticallyValidCSSHeader)
     , m_didLoadErrorOccur(false)
     , m_usesRemUnits(o.m_usesRemUnits)
     , m_isMutable(false)
     , m_isInMemoryCache(false)
     , m_hasFontFaceRule(o.m_hasFontFaceRule)
+    , m_hasMediaQueries(o.m_hasMediaQueries)
     , m_parserContext(o.m_parserContext)
 {
     ASSERT(o.isCacheable());
@@ -97,10 +99,18 @@
 
 StyleSheetContents::~StyleSheetContents()
 {
+    StyleEngine::removeSheet(this);
     clearRules();
 }
 
-bool StyleSheetContents::isCacheable() const
+void StyleSheetContents::setHasSyntacticallyValidCSSHeader(bool isValidCss)
+{
+    if (maybeCacheable() && !isValidCss)
+        StyleEngine::removeSheet(this);
+    m_hasSyntacticallyValidCSSHeader = isValidCss;
+}
+
+bool StyleSheetContents::maybeCacheable() const
 {
     // FIXME: StyleSheets with media queries can't be cached because their RuleSet
     // is processed differently based off the media queries, which might resolve
@@ -115,9 +125,6 @@
     // FIXME: Support cached stylesheets in import rules.
     if (m_ownerRule)
         return false;
-    // This would require dealing with multiple clients for load callbacks.
-    if (!m_loadCompleted)
-        return false;
     if (m_didLoadErrorOccur)
         return false;
     // It is not the original sheet anymore.
@@ -130,6 +137,14 @@
     return true;
 }
 
+bool StyleSheetContents::isCacheable() const
+{
+    // This would require dealing with multiple clients for load callbacks.
+    if (!loadCompleted())
+        return false;
+    return maybeCacheable();
+}
+
 void StyleSheetContents::parserAppendRule(PassRefPtr<StyleRuleBase> rule)
 {
     ASSERT(!rule->isCharsetRule());
@@ -231,7 +246,12 @@
         // Inserting non-import rule before @import is not allowed.
         if (!rule->isImportRule())
             return false;
-        m_importRules.insert(childVectorIndex, toStyleRuleImport(rule.get()));
+
+        StyleRuleImport* importRule = toStyleRuleImport(rule.get());
+        if (importRule->mediaQueries())
+            setHasMediaQueries();
+
+        m_importRules.insert(childVectorIndex, importRule);
         m_importRules[childVectorIndex]->setParentStyleSheet(this);
         m_importRules[childVectorIndex]->requestStyleSheet();
         // FIXME: Stylesheet doesn't actually change meaningfully before the imported sheets are loaded.
@@ -240,8 +260,14 @@
     // Inserting @import rule after a non-import rule is not allowed.
     if (rule->isImportRule())
         return false;
+
+    if (rule->isMediaRule())
+        setHasMediaQueries();
+
     childVectorIndex -= m_importRules.size();
 
+    if (rule->isFontFaceRule())
+        setHasFontFaceRule(true);
     m_childRules.insert(childVectorIndex, rule);
     return true;
 }
@@ -261,11 +287,15 @@
     }
     if (childVectorIndex < m_importRules.size()) {
         m_importRules[childVectorIndex]->clearParentStyleSheet();
+        if (m_importRules[childVectorIndex]->isFontFaceRule())
+            notifyRemoveFontFaceRule(toStyleRuleFontFace(m_importRules[childVectorIndex].get()));
         m_importRules.remove(childVectorIndex);
         return;
     }
     childVectorIndex -= m_importRules.size();
 
+    if (m_childRules[childVectorIndex]->isFontFaceRule())
+        notifyRemoveFontFaceRule(toStyleRuleFontFace(m_childRules[childVectorIndex].get()));
     m_childRules.remove(childVectorIndex);
 }
 
@@ -276,7 +306,7 @@
     PrefixNamespaceURIMap::AddResult result = m_namespaces.add(prefix, uri);
     if (result.isNewEntry)
         return;
-    result.iterator->value = uri;
+    result.storedValue->value = uri;
 }
 
 const AtomicString& StyleSheetContents::determineNamespace(const AtomicString& prefix)
@@ -298,7 +328,8 @@
     bool hasValidMIMEType = false;
     String sheetText = cachedStyleSheet->sheetText(enforceMIMEType, &hasValidMIMEType);
 
-    CSSParser p(parserContext(), UseCounter::getFrom(this));
+    CSSParserContext context(parserContext(), UseCounter::getFrom(this));
+    BisonCSSParser p(context);
     p.parseSheet(this, sheetText, TextPosition::minimumPosition(), 0, true);
 
     // If we're loading a stylesheet cross-origin, and the MIME type is not standard, require the CSS
@@ -320,7 +351,8 @@
 
 bool StyleSheetContents::parseStringAtPosition(const String& sheetText, const TextPosition& startPosition, bool createdByParser)
 {
-    CSSParser p(parserContext(), UseCounter::getFrom(this));
+    CSSParserContext context(parserContext(), UseCounter::getFrom(this));
+    BisonCSSParser p(context);
     p.parseSheet(this, sheetText, startPosition, 0, createdByParser);
 
     return true;
@@ -335,6 +367,20 @@
     return false;
 }
 
+bool StyleSheetContents::loadCompleted() const
+{
+    StyleSheetContents* parentSheet = parentStyleSheet();
+    if (parentSheet)
+        return parentSheet->loadCompleted();
+
+    StyleSheetContents* root = rootStyleSheet();
+    for (unsigned i = 0; i < root->m_clients.size(); ++i) {
+        if (!root->m_clients[i]->loadCompleted())
+            return false;
+    }
+    return true;
+}
+
 void StyleSheetContents::checkLoaded()
 {
     if (isLoading())
@@ -348,17 +394,26 @@
     StyleSheetContents* parentSheet = parentStyleSheet();
     if (parentSheet) {
         parentSheet->checkLoaded();
-        m_loadCompleted = true;
         return;
     }
-    RefPtr<Node> ownerNode = singleOwnerNode();
-    if (!ownerNode) {
-        m_loadCompleted = true;
+
+    StyleSheetContents* root = rootStyleSheet();
+    if (root->m_clients.isEmpty())
         return;
+
+    Vector<CSSStyleSheet*> clients(root->m_clients);
+    for (unsigned i = 0; i < clients.size(); ++i) {
+        // Avoid |CSSSStyleSheet| and |ownerNode| being deleted by scripts that run via
+        // ScriptableDocumentParser::executeScriptsWaitingForResources().
+        RefPtr<CSSStyleSheet> protectClient(clients[i]);
+
+        if (clients[i]->loadCompleted())
+            continue;
+
+        RefPtr<Node> ownerNode = clients[i]->ownerNode();
+        if (clients[i]->sheetLoaded())
+            ownerNode->notifyLoadedSheetAndAllCriticalSubresources(m_didLoadErrorOccur);
     }
-    m_loadCompleted = ownerNode->sheetLoaded();
-    if (m_loadCompleted)
-        ownerNode->notifyLoadedSheetAndAllCriticalSubresources(m_didLoadErrorOccur);
 }
 
 void StyleSheetContents::notifyLoadedSheet(const CSSStyleSheetResource* sheet)
@@ -373,8 +428,9 @@
 
 void StyleSheetContents::startLoadingDynamicSheet()
 {
-    if (Node* owner = singleOwnerNode())
-        owner->startLoadingDynamicSheet();
+    StyleSheetContents* root = rootStyleSheet();
+    for (unsigned i = 0; i < root->m_clients.size(); ++i)
+        root->m_clients[i]->startLoadingDynamicSheet();
 }
 
 StyleSheetContents* StyleSheetContents::rootStyleSheet() const
@@ -410,32 +466,8 @@
 
 KURL StyleSheetContents::completeURL(const String& url) const
 {
-    return CSSParser::completeURL(m_parserContext, url);
-}
-
-void StyleSheetContents::addSubresourceStyleURLs(ListHashSet<KURL>& urls)
-{
-    Deque<StyleSheetContents*> styleSheetQueue;
-    styleSheetQueue.append(this);
-
-    while (!styleSheetQueue.isEmpty()) {
-        StyleSheetContents* styleSheet = styleSheetQueue.takeFirst();
-
-        for (unsigned i = 0; i < styleSheet->m_importRules.size(); ++i) {
-            StyleRuleImport* importRule = styleSheet->m_importRules[i].get();
-            if (importRule->styleSheet()) {
-                styleSheetQueue.append(importRule->styleSheet());
-                addSubresourceURL(urls, importRule->styleSheet()->baseURL());
-            }
-        }
-        for (unsigned i = 0; i < styleSheet->m_childRules.size(); ++i) {
-            StyleRuleBase* rule = styleSheet->m_childRules[i].get();
-            if (rule->isStyleRule())
-                toStyleRule(rule)->properties()->addSubresourceStyleURLs(urls, this);
-            else if (rule->isFontFaceRule())
-                toStyleRuleFontFace(rule)->properties()->addSubresourceStyleURLs(urls, this);
-        }
-    }
+    // FIXME: This is only OK when we have a singleOwnerNode, right?
+    return m_parserContext.completeURL(url);
 }
 
 static bool childRulesHaveFailedOrCanceledSubresources(const Vector<RefPtr<StyleRuleBase> >& rules)
@@ -444,19 +476,15 @@
         const StyleRuleBase* rule = rules[i].get();
         switch (rule->type()) {
         case StyleRuleBase::Style:
-            if (static_cast<const StyleRule*>(rule)->properties()->hasFailedOrCanceledSubresources())
+            if (toStyleRule(rule)->properties()->hasFailedOrCanceledSubresources())
                 return true;
             break;
         case StyleRuleBase::FontFace:
-            if (static_cast<const StyleRuleFontFace*>(rule)->properties()->hasFailedOrCanceledSubresources())
+            if (toStyleRuleFontFace(rule)->properties()->hasFailedOrCanceledSubresources())
                 return true;
             break;
         case StyleRuleBase::Media:
-            if (childRulesHaveFailedOrCanceledSubresources(static_cast<const StyleRuleMedia*>(rule)->childRules()))
-                return true;
-            break;
-        case StyleRuleBase::Region:
-            if (childRulesHaveFailedOrCanceledSubresources(static_cast<const StyleRuleRegion*>(rule)->childRules()))
+            if (childRulesHaveFailedOrCanceledSubresources(toStyleRuleMedia(rule)->childRules()))
                 return true;
             break;
         case StyleRuleBase::Import:
@@ -548,5 +576,45 @@
     m_ruleSet.clear();
 }
 
+void StyleSheetContents::notifyRemoveFontFaceRule(const StyleRuleFontFace* fontFaceRule)
+{
+    StyleSheetContents* root = rootStyleSheet();
+
+    for (unsigned i = 0; i < root->m_clients.size(); ++i) {
+        if (Node* ownerNode = root->m_clients[0]->ownerNode())
+            ownerNode->document().styleEngine()->removeFontFaceRules(Vector<const StyleRuleFontFace*>(1, fontFaceRule));
+    }
+}
+
+static void findFontFaceRulesFromRules(const Vector<RefPtr<StyleRuleBase> >& rules, Vector<const StyleRuleFontFace*>& fontFaceRules)
+{
+    for (unsigned i = 0; i < rules.size(); ++i) {
+        StyleRuleBase* rule = rules[i].get();
+
+        if (rule->isFontFaceRule()) {
+            fontFaceRules.append(toStyleRuleFontFace(rule));
+        } else if (rule->isMediaRule()) {
+            StyleRuleMedia* mediaRule = toStyleRuleMedia(rule);
+            // We cannot know whether the media rule matches or not, but
+            // for safety, remove @font-face in the media rule (if exists).
+            findFontFaceRulesFromRules(mediaRule->childRules(), fontFaceRules);
+        }
+    }
+}
+
+void StyleSheetContents::findFontFaceRules(Vector<const StyleRuleFontFace*>& fontFaceRules)
+{
+    for (unsigned i = 0; i < m_importRules.size(); ++i) {
+        if (!m_importRules[i]->styleSheet())
+            continue;
+        m_importRules[i]->styleSheet()->findFontFaceRules(fontFaceRules);
+    }
+
+    findFontFaceRulesFromRules(childRules(), fontFaceRules);
+}
+
+void StyleSheetContents::trace(Visitor*)
+{
+}
 
 }
diff --git a/Source/core/css/StyleSheetContents.h b/Source/core/css/StyleSheetContents.h
index 7d59d80..b71d392 100644
--- a/Source/core/css/StyleSheetContents.h
+++ b/Source/core/css/StyleSheetContents.h
@@ -41,21 +41,23 @@
 class Node;
 class SecurityOrigin;
 class StyleRuleBase;
+class StyleRuleFontFace;
 class StyleRuleImport;
 
-class StyleSheetContents : public RefCounted<StyleSheetContents> {
+class StyleSheetContents : public RefCountedWillBeRefCountedGarbageCollected<StyleSheetContents> {
+    DECLARE_GC_INFO
 public:
-    static PassRefPtr<StyleSheetContents> create(const CSSParserContext& context = CSSParserContext(HTMLStandardMode))
+    static PassRefPtrWillBeRawPtr<StyleSheetContents> create(const CSSParserContext& context)
     {
-        return adoptRef(new StyleSheetContents(0, String(), context));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new StyleSheetContents(0, String(), context));
     }
-    static PassRefPtr<StyleSheetContents> create(const String& originalURL, const CSSParserContext& context)
+    static PassRefPtrWillBeRawPtr<StyleSheetContents> create(const String& originalURL, const CSSParserContext& context)
     {
-        return adoptRef(new StyleSheetContents(0, originalURL, context));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new StyleSheetContents(0, originalURL, context));
     }
-    static PassRefPtr<StyleSheetContents> create(StyleRuleImport* ownerRule, const String& originalURL, const CSSParserContext& context)
+    static PassRefPtrWillBeRawPtr<StyleSheetContents> create(StyleRuleImport* ownerRule, const String& originalURL, const CSSParserContext& context)
     {
-        return adoptRef(new StyleSheetContents(ownerRule, originalURL, context));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new StyleSheetContents(ownerRule, originalURL, context));
     }
 
     ~StyleSheetContents();
@@ -69,6 +71,7 @@
     bool parseStringAtPosition(const String&, const TextPosition&, bool);
 
     bool isCacheable() const;
+    bool maybeCacheable() const;
 
     bool isLoading() const;
 
@@ -82,17 +85,17 @@
 
     const String& charset() const { return m_parserContext.charset(); }
 
-    bool loadCompleted() const { return m_loadCompleted; }
+    bool loadCompleted() const;
     bool hasFailedOrCanceledSubresources() const;
 
     KURL completeURL(const String& url) const;
-    void addSubresourceStyleURLs(ListHashSet<KURL>&);
 
-    void setHasSyntacticallyValidCSSHeader(bool b) { m_hasSyntacticallyValidCSSHeader = b; }
+    void setHasSyntacticallyValidCSSHeader(bool isValidCss);
     bool hasSyntacticallyValidCSSHeader() const { return m_hasSyntacticallyValidCSSHeader; }
 
     void setHasFontFaceRule(bool b) { m_hasFontFaceRule = b; }
     bool hasFontFaceRule() const { return m_hasFontFaceRule; }
+    void findFontFaceRules(Vector<const StyleRuleFontFace*>& fontFaceRules);
 
     void parserAddNamespace(const AtomicString& prefix, const AtomicString& uri);
     void parserAppendRule(PassRefPtr<StyleRuleBase>);
@@ -150,9 +153,12 @@
     RuleSet& ensureRuleSet(const MediaQueryEvaluator&, AddRuleFlags);
     void clearRuleSet();
 
+    void trace(Visitor*);
+
 private:
     StyleSheetContents(StyleRuleImport* ownerRule, const String& originalURL, const CSSParserContext&);
     StyleSheetContents(const StyleSheetContents&);
+    void notifyRemoveFontFaceRule(const StyleRuleFontFace*);
 
     void clearCharsetRule();
 
@@ -166,7 +172,6 @@
     typedef HashMap<AtomicString, AtomicString> PrefixNamespaceURIMap;
     PrefixNamespaceURIMap m_namespaces;
 
-    bool m_loadCompleted : 1;
     bool m_hasSyntacticallyValidCSSHeader : 1;
     bool m_didLoadErrorOccur : 1;
     bool m_usesRemUnits : 1;
diff --git a/Source/core/css/StyleSheetList.h b/Source/core/css/StyleSheetList.h
index c9c1540..9750565 100644
--- a/Source/core/css/StyleSheetList.h
+++ b/Source/core/css/StyleSheetList.h
@@ -43,7 +43,8 @@
 
     HTMLStyleElement* getNamedItem(const AtomicString&) const;
 
-    Document* document() { return m_treeScope->documentScope(); }
+    // FIXME: Should return a reference.
+    Document* document() { return &m_treeScope->document(); }
 
     void detachFromDocument();
     CSSStyleSheet* anonymousNamedGetter(const AtomicString&);
diff --git a/Source/core/css/StyleSheetList.idl b/Source/core/css/StyleSheetList.idl
index 7341728..104a387 100644
--- a/Source/core/css/StyleSheetList.idl
+++ b/Source/core/css/StyleSheetList.idl
@@ -20,10 +20,9 @@
 
 // Introduced in DOM Level 2:
 [
-    GenerateVisitDOMWrapper=document,
+    SetWrapperReferenceFrom=document,
 ] interface StyleSheetList {
-    readonly attribute unsigned long    length;
-    getter StyleSheet         item(unsigned long index);
-    [ImplementedAs=anonymousNamedGetter, NotEnumerable] getter CSSStyleSheet (DOMString name);
+    readonly attribute unsigned long length;
+    getter StyleSheet item(unsigned long index);
+    [NotEnumerable] getter CSSStyleSheet (DOMString name);
 };
-
diff --git a/Source/core/css/TreeBoundaryCrossingRules.h b/Source/core/css/TreeBoundaryCrossingRules.h
index bba30ed..9c7be24 100644
--- a/Source/core/css/TreeBoundaryCrossingRules.h
+++ b/Source/core/css/TreeBoundaryCrossingRules.h
@@ -45,6 +45,7 @@
 
     DocumentOrderedList::iterator begin() { return m_scopingNodes.begin(); }
     DocumentOrderedList::iterator end() { return m_scopingNodes.end(); }
+    size_t size() const { return m_scopingNodes.size(); }
     RuleSet* ruleSetScopedBy(const ContainerNode* scopingNode) { return m_treeBoundaryCrossingRuleSetMap.get(scopingNode); }
 
 private:
diff --git a/Source/core/css/WebKitCSSFilterValue.idl b/Source/core/css/WebKitCSSFilterValue.idl
index db2fb1d..dd9aff4 100644
--- a/Source/core/css/WebKitCSSFilterValue.idl
+++ b/Source/core/css/WebKitCSSFilterValue.idl
@@ -25,7 +25,7 @@
 
 [
     DoNotCheckConstants,
-    ImplementedAs=CSSFilterValue
+    ImplementedAs=CSSFilterValue,
 ] interface WebKitCSSFilterValue : CSSValueList {
 
     // OperationTypes
@@ -44,5 +44,5 @@
     const unsigned short CSS_FILTER_CUSTOM = 12;
 
     readonly attribute unsigned short operationType;
-    [ImplementedAs=item] getter CSSValue(unsigned long index);
+    [ImplementedAs=item] getter CSSValue (unsigned long index);
 };
diff --git a/Source/core/css/WebKitCSSMixFunctionValue.idl b/Source/core/css/WebKitCSSMixFunctionValue.idl
deleted file mode 100644
index 57f3125..0000000
--- a/Source/core/css/WebKitCSSMixFunctionValue.idl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-[
-    ImplementedAs=CSSMixFunctionValue
-] interface WebKitCSSMixFunctionValue : CSSValueList {
-};
-
diff --git a/Source/core/css/WebKitCSSRegionRule.idl b/Source/core/css/WebKitCSSRegionRule.idl
deleted file mode 100644
index 6811344..0000000
--- a/Source/core/css/WebKitCSSRegionRule.idl
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-[
-    RuntimeEnabled=CSSRegions,
-    ImplementedAs=CSSRegionRule
-] interface WebKitCSSRegionRule : CSSRule {
-    readonly attribute CSSRuleList cssRules;
-};
-
diff --git a/Source/core/css/WebKitCSSTransformValue.idl b/Source/core/css/WebKitCSSTransformValue.idl
index 836bcc6..a17e482 100644
--- a/Source/core/css/WebKitCSSTransformValue.idl
+++ b/Source/core/css/WebKitCSSTransformValue.idl
@@ -28,7 +28,7 @@
 
 [
     DoNotCheckConstants,
-    ImplementedAs=CSSTransformValue
+    ImplementedAs=CSSTransformValue,
 ] interface WebKitCSSTransformValue : CSSValueList {
 
     // OperationTypes
@@ -56,6 +56,6 @@
     const unsigned short CSS_MATRIX3D    = 21;
 
     readonly attribute unsigned short operationType;
-    [ImplementedAs=item] getter CSSValue(unsigned long index);
+    [ImplementedAs=item] getter CSSValue (unsigned long index);
 };
 
diff --git a/Source/core/css/analyzer/DescendantInvalidationSet.cpp b/Source/core/css/analyzer/DescendantInvalidationSet.cpp
new file mode 100644
index 0000000..e4c04af
--- /dev/null
+++ b/Source/core/css/analyzer/DescendantInvalidationSet.cpp
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/css/analyzer/DescendantInvalidationSet.h"
+
+#include "core/css/resolver/StyleResolver.h"
+#include "core/dom/Element.h"
+
+namespace WebCore {
+
+DescendantInvalidationSet::DescendantInvalidationSet()
+    : m_allDescendantsMightBeInvalid(false)
+{
+}
+
+void DescendantInvalidationSet::combine(const DescendantInvalidationSet& other)
+{
+    m_allDescendantsMightBeInvalid = m_allDescendantsMightBeInvalid || other.m_allDescendantsMightBeInvalid;
+    // No longer bother combining data structures, since the whole subtree is deemed invalid.
+    if (m_allDescendantsMightBeInvalid)
+        return;
+
+    HashSet<AtomicString>::const_iterator end = other.m_classes.end();
+    for (HashSet<AtomicString>::const_iterator it = other.m_classes.begin(); it != end; ++it)
+        addClass(*it);
+
+    end = other.m_ids.end();
+    for (HashSet<AtomicString>::const_iterator it = other.m_ids.begin(); it != end; ++it)
+        addId(*it);
+
+    end = other.m_tagNames.end();
+    for (HashSet<AtomicString>::const_iterator it = other.m_tagNames.begin(); it != end; ++it)
+        addTagName(*it);
+}
+
+void DescendantInvalidationSet::addClass(const AtomicString& className)
+{
+    m_classes.add(className);
+}
+
+void DescendantInvalidationSet::addId(const AtomicString& id)
+{
+    m_ids.add(id);
+}
+
+void DescendantInvalidationSet::addTagName(const AtomicString& tagName)
+{
+    m_tagNames.add(tagName);
+}
+
+void DescendantInvalidationSet::getClasses(Vector<AtomicString>& classes)
+{
+    for (HashSet<AtomicString>::const_iterator it = m_classes.begin(); it != m_classes.end(); ++it)
+        classes.append(*it);
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/analyzer/DescendantInvalidationSet.h b/Source/core/css/analyzer/DescendantInvalidationSet.h
new file mode 100644
index 0000000..38e58b7
--- /dev/null
+++ b/Source/core/css/analyzer/DescendantInvalidationSet.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef DescendantInvalidationSet_h
+#define DescendantInvalidationSet_h
+
+#include "wtf/Forward.h"
+#include "wtf/HashSet.h"
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/AtomicStringHash.h"
+#include "wtf/text/StringHash.h"
+
+namespace WebCore {
+
+class Element;
+
+// Tracks data to determine which elements of a DOM subtree need to have style
+// recalculated.
+class DescendantInvalidationSet FINAL : public RefCounted<DescendantInvalidationSet> {
+public:
+    static PassRefPtr<DescendantInvalidationSet> create()
+    {
+        return adoptRef(new DescendantInvalidationSet);
+    }
+
+    void combine(const DescendantInvalidationSet& other);
+
+    void addClass(const AtomicString& className);
+    void addId(const AtomicString& id);
+    void addTagName(const AtomicString& tagName);
+
+    // Appends the classes in this DescendantInvalidationSet to the vector.
+    void getClasses(Vector<AtomicString>& classes);
+
+    void setWholeSubtreeInvalid() { m_allDescendantsMightBeInvalid = true; };
+    bool wholeSubtreeInvalid() { return m_allDescendantsMightBeInvalid; }
+private:
+    DescendantInvalidationSet();
+
+    bool invalidateElementSubtreeInternal(Element*);
+    // If true, all descendants might be invalidated, so a full subtree recalc is required.
+    bool m_allDescendantsMightBeInvalid;
+
+    // FIXME: optimize this if it becomes a memory issue.
+    HashSet<AtomicString> m_classes;
+    HashSet<AtomicString> m_ids;
+    HashSet<AtomicString> m_tagNames;
+};
+
+} // namespace WebCore
+
+#endif // DescendantInvalidationSet_h
diff --git a/Source/core/css/fullscreen.css b/Source/core/css/fullscreen.css
index 5ea5f06..7ecffc6 100644
--- a/Source/core/css/fullscreen.css
+++ b/Source/core/css/fullscreen.css
@@ -24,6 +24,8 @@
 video:-webkit-full-screen, audio:-webkit-full-screen {
     background-color: transparent !important;
     position: relative !important;
+    left: 0 !important;
+    top: 0 ! important;
     margin: 0 !important;
     height: 100% !important;
     width: 100% !important;
diff --git a/Source/core/css/html.css b/Source/core/css/html.css
index af23edc..df9dd1e 100644
--- a/Source/core/css/html.css
+++ b/Source/core/css/html.css
@@ -59,10 +59,6 @@
     margin: 8px
 }
 
-body:-webkit-seamless-document {
-    margin: 0px
-}
-
 body:-webkit-full-page-media {
     background-color: rgb(0, 0, 0)
 }
@@ -448,6 +444,13 @@
     flex: none;
     -webkit-user-modify: read-only !important;
     -webkit-margin-start: 2px;
+    opacity: 0;
+    pionter-events: none;
+}
+
+input:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-clear-button {
+    opacity: 1;
+    pointer-events: auto;
 }
 
 input[type="search"]::-webkit-search-cancel-button {
@@ -582,7 +585,9 @@
 input[type="time"],
 input[type="week"] {
     align-items: center;
-    -webkit-appearance: menulist-button;
+    -webkit-appearance: menulist;
+    background-color: ButtonFace;
+    border: 1px solid #a9a9a9;
     display: -webkit-inline-flex;
     overflow: hidden;
     width: 10em;
@@ -607,6 +612,13 @@
     flex: none;
     -webkit-user-select: none;
     -webkit-user-modify: read-only !important;
+    opacity: 0;
+    pointer-events: none;
+}
+
+input:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-inner-spin-button {
+    opacity: 1;
+    pointer-events: auto;
 }
 
 #if defined(ENABLE_INPUT_SPEECH) && ENABLE_INPUT_SPEECH
@@ -801,12 +813,19 @@
     height: 0.66em;
     padding: 0.17em 0.34em;
     -webkit-user-modify: read-only !important;
+    opacity: 0;
+    pointer-events: none;
 }
 
 input::-webkit-calendar-picker-indicator:hover {
     background-color: #eee;
 }
 
+input:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-calendar-picker-indicator {
+    opacity: 1;
+    pointer-events: auto;
+}
+
 input[type="date"]:disabled::-webkit-clear-button,
 input[type="date"]:disabled::-webkit-inner-spin-button,
 input[type="datetime-local"]:disabled::-webkit-clear-button,
@@ -891,7 +910,7 @@
 }
 
 meter::-webkit-meter-bar {
-    background: -webkit-gradient(linear, left top, left bottom, from(#ddd), to(#ddd), color-stop(0.20, #eee), color-stop(0.45, #ccc), color-stop(0.55, #ccc));
+    background: linear-gradient(to bottom, #ddd, #eee 20%, #ccc 45%, #ccc 55%, #ddd);
     height: 100%;
     width: 100%;
     -webkit-user-modify: read-only !important;
@@ -899,21 +918,21 @@
 }
 
 meter::-webkit-meter-optimum-value {
-    background: -webkit-gradient(linear, left top, left bottom, from(#ad7), to(#ad7), color-stop(0.20, #cea), color-stop(0.45, #7a3), color-stop(0.55, #7a3));
+    background: linear-gradient(to bottom, #ad7, #cea 20%, #7a3 45%, #7a3 55%, #ad7);
     height: 100%;
     -webkit-user-modify: read-only !important;
     box-sizing: border-box;
 }
 
 meter::-webkit-meter-suboptimum-value {
-    background: -webkit-gradient(linear, left top, left bottom, from(#fe7), to(#fe7), color-stop(0.20, #ffc), color-stop(0.45, #db3), color-stop(0.55, #db3));
+    background: linear-gradient(to bottom, #fe7, #ffc 20%, #db3 45%, #db3 55%, #fe7);
     height: 100%;
     -webkit-user-modify: read-only !important;
     box-sizing: border-box;
 }
 
 meter::-webkit-meter-even-less-good-value {
-    background: -webkit-gradient(linear, left top, left bottom, from(#f77), to(#f77), color-stop(0.20, #fcc), color-stop(0.45, #d44), color-stop(0.55, #d44));
+    background: linear-gradient(to bottom, #f77, #fcc 20%, #d44 45%, #d44 55%, #f77);
     height: 100%;
     -webkit-user-modify: read-only !important;
     box-sizing: border-box;
@@ -1087,14 +1106,10 @@
     border-color: inherit
 }
 
-iframe:not([seamless]) {
+iframe {
     border: 2px inset
 }
 
-iframe[seamless] {
-    display: block
-}
-
 details {
     display: block
 }
diff --git a/Source/core/css/make-css-file-arrays.pl b/Source/core/css/make-css-file-arrays.pl
index 66eb7df..d111cb3 100755
--- a/Source/core/css/make-css-file-arrays.pl
+++ b/Source/core/css/make-css-file-arrays.pl
@@ -34,8 +34,10 @@
 my $out = $ARGV[0];
 shift;
 
-open HEADER, ">", $header or die;
-open OUT, ">", $out or die;
+$header =~ s|\\|/|g;
+$out =~ s|\\|/|g;
+open HEADER, ">", $header or die "$!\n";
+open OUT, ">", $out or die "$!\n";
 
 print HEADER "namespace WebCore {\n";
 print OUT "namespace WebCore {\n";
diff --git a/Source/core/css/mediaControls.css b/Source/core/css/mediaControls.css
index a2efc1d..9aa9d39 100644
--- a/Source/core/css/mediaControls.css
+++ b/Source/core/css/mediaControls.css
@@ -231,26 +231,6 @@
     margin-right: -7px;
 }
 
-audio::-webkit-media-controls-seek-back-button, video::-webkit-media-controls-seek-back-button {
-    -webkit-appearance: media-seek-back-button;
-    display: flex;
-    width: 16px;
-    height: 16px;
-    background-color: initial;
-    border: initial;
-    color: inherit;
-}
-
-audio::-webkit-media-controls-seek-forward-button, video::-webkit-media-controls-seek-forward-button {
-    -webkit-appearance: media-seek-forward-button;
-    display: flex;
-    width: 16px;
-    height: 16px;
-    background-color: initial;
-    border: initial;
-    color: inherit;
-}
-
 audio::-webkit-media-controls-fullscreen-button, video::-webkit-media-controls-fullscreen-button {
     -webkit-appearance: media-enter-fullscreen-button;
     display: flex;
@@ -267,20 +247,6 @@
     color: inherit;
 }
 
-audio::-webkit-media-controls-rewind-button, video::-webkit-media-controls-rewind-button {
-    display: none;
-    background-color: initial;
-    border: initial;
-    color: inherit;
-}
-
-audio::-webkit-media-controls-return-to-realtime-button, video::-webkit-media-controls-return-to-realtime-button {
-    display: none;
-    background-color: initial;
-    border: initial;
-    color: inherit;
-}
-
 audio::-webkit-media-controls-toggle-closed-captions-button {
     display: none;
 }
@@ -301,14 +267,6 @@
     color: inherit;
 }
 
-audio::-webkit-media-controls-volume-slider-mute-button, video::-webkit-media-controls-volume-slider-mute-button {
-    -webkit-appearance: media-volume-slider-mute-button;
-    display: none;
-    background-color: initial;
-    border: initial;
-    color: inherit;
-}
-
 audio::-webkit-media-controls-fullscreen-volume-slider, video::-webkit-media-controls-fullscreen-volume-slider {
     display: none;
 }
diff --git a/Source/core/css/CSSParser-in.cpp b/Source/core/css/parser/BisonCSSParser-in.cpp
similarity index 82%
rename from Source/core/css/CSSParser-in.cpp
rename to Source/core/css/parser/BisonCSSParser-in.cpp
index be3c9a6..6376586 100644
--- a/Source/core/css/CSSParser-in.cpp
+++ b/Source/core/css/parser/BisonCSSParser-in.cpp
@@ -25,7 +25,7 @@
  */
 
 #include "config.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 
 #include "CSSValueKeywords.h"
 #include "RuntimeEnabledFeatures.h"
@@ -42,7 +42,7 @@
 #include "core/css/CSSFunctionValue.h"
 #include "core/css/CSSGradientValue.h"
 #include "core/css/CSSGridLineNamesValue.h"
-#include "core/css/CSSGridTemplateValue.h"
+#include "core/css/CSSGridTemplateAreasValue.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSImageValue.h"
 #include "core/css/CSSInheritedValue.h"
@@ -50,13 +50,11 @@
 #include "core/css/CSSKeyframeRule.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSLineBoxContainValue.h"
-#include "core/css/CSSMixFunctionValue.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSPropertySourceData.h"
 #include "core/css/CSSReflectValue.h"
 #include "core/css/CSSSVGDocumentValue.h"
 #include "core/css/CSSSelector.h"
-#include "core/css/CSSShaderValue.h"
 #include "core/css/CSSShadowValue.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/CSSTimingFunctionValue.h"
@@ -64,7 +62,6 @@
 #include "core/css/CSSUnicodeRangeValue.h"
 #include "core/css/CSSValueList.h"
 #include "core/css/CSSValuePool.h"
-#include "core/css/CSSVariableValue.h"
 #include "core/css/Counter.h"
 #include "core/css/HashTools.h"
 #include "core/css/MediaList.h"
@@ -75,11 +72,13 @@
 #include "core/css/StyleRule.h"
 #include "core/css/StyleRuleImport.h"
 #include "core/css/StyleSheetContents.h"
+#include "core/css/parser/CSSParserIdioms.h"
 #include "core/dom/Document.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/PageConsole.h"
+#include "core/frame/Settings.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/PageConsole.h"
-#include "core/page/Settings.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/svg/SVGParserUtilities.h"
 #include "platform/FloatConversion.h"
@@ -97,7 +96,7 @@
 extern int cssyydebug;
 #endif
 
-extern int cssyyparse(WebCore::CSSParser*);
+int cssyyparse(WebCore::BisonCSSParser*);
 
 using namespace std;
 using namespace WTF;
@@ -134,7 +133,7 @@
     return equalIgnoringCase(value->string, b);
 }
 
-static PassRefPtr<CSSPrimitiveValue> createPrimitiveValuePair(PassRefPtr<CSSPrimitiveValue> first, PassRefPtr<CSSPrimitiveValue> second, Pair::IdenticalValuesPolicy identicalValuesPolicy = Pair::DropIdenticalValues)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createPrimitiveValuePair(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> first, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> second, Pair::IdenticalValuesPolicy identicalValuesPolicy = Pair::DropIdenticalValues)
 {
     return cssValuePool().createValue(Pair::create(first, second, identicalValuesPolicy));
 }
@@ -184,7 +183,7 @@
     bool m_hasSeenAnimationPropertyKeyword;
 };
 
-CSSParser::CSSParser(const CSSParserContext& context, UseCounter* counter)
+BisonCSSParser::BisonCSSParser(const CSSParserContext& context)
     : m_context(context)
     , m_important(false)
     , m_id(CSSPropertyInvalid)
@@ -199,15 +198,13 @@
     , m_hadSyntacticallyValidCSSRule(false)
     , m_logErrors(false)
     , m_ignoreErrors(false)
-    , m_inFilterRule(false)
     , m_defaultNamespace(starAtom)
-    , m_sourceDataHandler(0)
+    , m_observer(0)
     , m_source(0)
     , m_ruleHeaderType(CSSRuleSourceData::UNKNOWN_RULE)
     , m_allowImportRules(true)
     , m_allowNamespaceDeclarations(true)
     , m_inViewport(false)
-    , m_useCounter(counter)
     , m_tokenizer(*this)
 {
 #if YYDEBUG > 0
@@ -216,7 +213,7 @@
     CSSPropertySourceData::init();
 }
 
-CSSParser::~CSSParser()
+BisonCSSParser::~BisonCSSParser()
 {
     clearProperties();
 
@@ -226,18 +223,18 @@
     deleteAllValues(m_floatingFunctions);
 }
 
-void CSSParser::setupParser(const char* prefix, unsigned prefixLength, const String& string, const char* suffix, unsigned suffixLength)
+void BisonCSSParser::setupParser(const char* prefix, unsigned prefixLength, const String& string, const char* suffix, unsigned suffixLength)
 {
     m_tokenizer.setupTokenizer(prefix, prefixLength, string, suffix, suffixLength);
     m_ruleHasHeader = true;
 }
 
-void CSSParser::parseSheet(StyleSheetContents* sheet, const String& string, const TextPosition& startPosition, SourceDataHandler* sourceDataHandler, bool logErrors)
+void BisonCSSParser::parseSheet(StyleSheetContents* sheet, const String& string, const TextPosition& startPosition, CSSParserObserver* observer, bool logErrors)
 {
     setStyleSheet(sheet);
     m_defaultNamespace = starAtom; // Reset the default namespace.
-    m_sourceDataHandler = sourceDataHandler;
-    m_logErrors = logErrors && sheet->singleOwnerDocument() && !sheet->baseURL().isEmpty() && sheet->singleOwnerDocument()->page();
+    TemporaryChange<CSSParserObserver*> scopedObsever(m_observer, observer);
+    m_logErrors = logErrors && sheet->singleOwnerDocument() && !sheet->baseURL().isEmpty() && sheet->singleOwnerDocument()->frameHost();
     m_ignoreErrors = false;
     m_tokenizer.m_lineNumber = 0;
     m_startPosition = startPosition;
@@ -247,7 +244,6 @@
     cssyyparse(this);
     sheet->shrinkToFit();
     m_source = 0;
-    m_sourceDataHandler = 0;
     m_rule = 0;
     m_lineEndings.clear();
     m_ignoreErrors = false;
@@ -255,7 +251,7 @@
     m_tokenizer.m_internal = true;
 }
 
-PassRefPtr<StyleRuleBase> CSSParser::parseRule(StyleSheetContents* sheet, const String& string)
+PassRefPtr<StyleRuleBase> BisonCSSParser::parseRule(StyleSheetContents* sheet, const String& string)
 {
     setStyleSheet(sheet);
     m_allowNamespaceDeclarations = false;
@@ -264,7 +260,7 @@
     return m_rule.release();
 }
 
-PassRefPtr<StyleKeyframe> CSSParser::parseKeyframeRule(StyleSheetContents* sheet, const String& string)
+PassRefPtr<StyleKeyframe> BisonCSSParser::parseKeyframeRule(StyleSheetContents* sheet, const String& string)
 {
     setStyleSheet(sheet);
     setupParser("@-internal-keyframe-rule ", string, "");
@@ -272,7 +268,7 @@
     return m_keyframe.release();
 }
 
-PassOwnPtr<Vector<double> > CSSParser::parseKeyframeKeyList(const String& string)
+PassOwnPtr<Vector<double> > BisonCSSParser::parseKeyframeKeyList(const String& string)
 {
     setupParser("@-internal-keyframe-key-list ", string, "");
     cssyyparse(this);
@@ -280,7 +276,7 @@
     return StyleKeyframe::createKeyList(m_valueList.get());
 }
 
-bool CSSParser::parseSupportsCondition(const String& string)
+bool BisonCSSParser::parseSupportsCondition(const String& string)
 {
     m_supportsCondition = false;
     setupParser("@-internal-supports-condition ", string, "");
@@ -342,7 +338,7 @@
         return true;
     }
     RGBA32 color;
-    if (!CSSParser::fastParseColor(color, string, !quirksMode && string[0] != '#'))
+    if (!BisonCSSParser::fastParseColor(color, string, !quirksMode && string[0] != '#'))
         return false;
     RefPtr<CSSValue> value = cssValuePool().createColorValue(color);
     declaration->addParsedProperty(CSSProperty(propertyId, value.release(), important));
@@ -395,7 +391,7 @@
 }
 
 template <typename CharacterType>
-static inline bool parseSimpleLength(const CharacterType* characters, unsigned& length, CSSPrimitiveValue::UnitTypes& unit, double& number)
+static inline bool parseSimpleLength(const CharacterType* characters, unsigned length, CSSPrimitiveValue::UnitTypes& unit, double& number)
 {
     if (length > 2 && (characters[length - 2] | 0x20) == 'p' && (characters[length - 1] | 0x20) == 'x') {
         length -= 2;
@@ -577,6 +573,9 @@
         if (valueID == CSSValueNone || valueID == CSSValueBoth || valueID == CSSValueHorizontal || valueID == CSSValueVertical || valueID == CSSValueAuto)
             return true;
         break;
+    case CSSPropertyScrollBehavior: // instant | smooth
+        if (valueID == CSSValueInstant || valueID == CSSValueSmooth)
+            return RuntimeEnabledFeatures::cssomSmoothScrollEnabled();
     case CSSPropertySpeak: // none | normal | spell-out | digits | literal-punctuation | no-punctuation | inherit
         if (valueID == CSSValueNone || valueID == CSSValueNormal || valueID == CSSValueSpellOut || valueID == CSSValueDigits || valueID == CSSValueLiteralPunctuation || valueID == CSSValueNoPunctuation)
             return true;
@@ -621,12 +620,8 @@
         if ((valueID >= CSSValueCapitalize && valueID <= CSSValueLowercase) || valueID == CSSValueNone)
             return true;
         break;
-    case CSSPropertyTouchAction: // auto | none
-        if (RuntimeEnabledFeatures::cssTouchActionEnabled() && (valueID == CSSValueAuto || valueID == CSSValueNone))
-            return true;
-        break;
     case CSSPropertyTouchActionDelay: // none | script
-        if (RuntimeEnabledFeatures::cssTouchActionEnabled() && (valueID == CSSValueScript || valueID == CSSValueNone))
+        if (RuntimeEnabledFeatures::cssTouchActionDelayEnabled() && (valueID == CSSValueScript || valueID == CSSValueNone))
             return true;
         break;
     case CSSPropertyVisibility: // visible | hidden | collapse | inherit
@@ -687,14 +682,17 @@
         }
         break;
     case CSSPropertyAlignContent:
+        // FIXME: Per CSS alignment, this property should accept an optional <overflow-position>. We should share this parsing code with 'justify-self'.
          if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueSpaceBetween || valueID == CSSValueSpaceAround || valueID == CSSValueStretch)
              return true;
          break;
     case CSSPropertyAlignItems:
+        // FIXME: Per CSS alignment, this property should accept the same arguments as 'justify-self' so we should share its parsing code.
         if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueBaseline || valueID == CSSValueStretch)
             return true;
         break;
     case CSSPropertyAlignSelf:
+        // FIXME: Per CSS alignment, this property should accept the same arguments as 'justify-self' so we should share its parsing code.
         if (valueID == CSSValueAuto || valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueBaseline || valueID == CSSValueStretch)
             return true;
         break;
@@ -707,6 +705,7 @@
              return true;
         break;
     case CSSPropertyJustifyContent:
+        // FIXME: Per CSS alignment, this property should accept an optional <overflow-position>. We should share this parsing code with 'justify-self'.
         if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueSpaceBetween || valueID == CSSValueSpaceAround)
             return true;
         break;
@@ -722,18 +721,10 @@
         if (valueID == CSSValueNone || valueID == CSSValueRow || valueID == CSSValueColumn)
             return RuntimeEnabledFeatures::cssGridLayoutEnabled();
         break;
-    case CSSPropertyWebkitLineAlign:
-        if (valueID == CSSValueNone || valueID == CSSValueEdges)
-            return true;
-        break;
     case CSSPropertyWebkitLineBreak: // auto | loose | normal | strict | after-white-space
         if (valueID == CSSValueAuto || valueID == CSSValueLoose || valueID == CSSValueNormal || valueID == CSSValueStrict || valueID == CSSValueAfterWhiteSpace)
             return true;
         break;
-    case CSSPropertyWebkitLineSnap:
-        if (valueID == CSSValueNone || valueID == CSSValueBaseline || valueID == CSSValueContain)
-            return true;
-        break;
     case CSSPropertyWebkitMarginAfterCollapse:
     case CSSPropertyWebkitMarginBeforeCollapse:
     case CSSPropertyWebkitMarginBottomCollapse:
@@ -754,19 +745,6 @@
         if (valueID == CSSValueExact || valueID == CSSValueEconomy)
             return true;
         break;
-    case CSSPropertyWebkitRegionBreakAfter:
-    case CSSPropertyWebkitRegionBreakBefore:
-        if (RuntimeEnabledFeatures::cssRegionsEnabled() && (valueID == CSSValueAuto || valueID == CSSValueAlways || valueID == CSSValueAvoid || valueID == CSSValueLeft || valueID == CSSValueRight))
-            return true;
-        break;
-    case CSSPropertyWebkitRegionBreakInside:
-        if (RuntimeEnabledFeatures::cssRegionsEnabled() && (valueID == CSSValueAuto || valueID == CSSValueAvoid))
-            return true;
-        break;
-    case CSSPropertyWebkitRegionFragment:
-        if (RuntimeEnabledFeatures::cssRegionsEnabled() && (valueID == CSSValueAuto || valueID == CSSValueBreak))
-            return true;
-        break;
     case CSSPropertyWebkitRtlOrdering:
         if (valueID == CSSValueLogical || valueID == CSSValueVisual)
             return true;
@@ -869,6 +847,7 @@
     case CSSPropertyPointerEvents:
     case CSSPropertyPosition:
     case CSSPropertyResize:
+    case CSSPropertyScrollBehavior:
     case CSSPropertySpeak:
     case CSSPropertyTableLayout:
     case CSSPropertyTextAlignLast:
@@ -882,7 +861,6 @@
     case CSSPropertyTextTransform:
     case CSSPropertyTextUnderlineMode:
     case CSSPropertyTextUnderlineStyle:
-    case CSSPropertyTouchAction:
     case CSSPropertyTouchActionDelay:
     case CSSPropertyVisibility:
     case CSSPropertyWebkitAppearance:
@@ -905,17 +883,13 @@
     case CSSPropertyColumnFill:
     case CSSPropertyWebkitColumnRuleStyle:
     case CSSPropertyAlignContent:
-    case CSSPropertyAlignItems:
-    case CSSPropertyAlignSelf:
     case CSSPropertyFlexDirection:
     case CSSPropertyFlexWrap:
     case CSSPropertyJustifyContent:
     case CSSPropertyFontKerning:
     case CSSPropertyWebkitFontSmoothing:
     case CSSPropertyGridAutoFlow:
-    case CSSPropertyWebkitLineAlign:
     case CSSPropertyWebkitLineBreak:
-    case CSSPropertyWebkitLineSnap:
     case CSSPropertyWebkitMarginAfterCollapse:
     case CSSPropertyWebkitMarginBeforeCollapse:
     case CSSPropertyWebkitMarginBottomCollapse:
@@ -923,10 +897,6 @@
     case CSSPropertyInternalMarqueeDirection:
     case CSSPropertyInternalMarqueeStyle:
     case CSSPropertyWebkitPrintColorAdjust:
-    case CSSPropertyWebkitRegionBreakAfter:
-    case CSSPropertyWebkitRegionBreakBefore:
-    case CSSPropertyWebkitRegionBreakInside:
-    case CSSPropertyWebkitRegionFragment:
     case CSSPropertyWebkitRtlOrdering:
     case CSSPropertyWebkitRubyPosition:
     case CSSPropertyWebkitTextCombine:
@@ -943,6 +913,9 @@
     case CSSPropertyWordBreak:
     case CSSPropertyWordWrap:
         return true;
+    case CSSPropertyAlignItems:
+    case CSSPropertyAlignSelf:
+        return !RuntimeEnabledFeatures::cssGridLayoutEnabled();
     default:
         return false;
     }
@@ -958,7 +931,7 @@
         if (lowerCaseString != "initial" && lowerCaseString != "inherit")
             return false;
 
-        // Parse initial/inherit shorthands using the CSSParser.
+        // Parse initial/inherit shorthands using the BisonCSSParser.
         if (shorthandForProperty(propertyId).length())
             return false;
     }
@@ -984,75 +957,120 @@
     return true;
 }
 
-template <typename CharacterType>
-static bool parseTransformTranslateArguments(CSSTransformValue* transformValue, CharacterType* characters, unsigned length, unsigned start, unsigned expectedCount)
+template <typename CharType>
+static bool parseTransformTranslateArguments(CharType*& pos, CharType* end, unsigned expectedCount, CSSTransformValue* transformValue)
 {
     while (expectedCount) {
-        size_t end = WTF::find(characters, length, expectedCount == 1 ? ')' : ',', start);
-        if (end == kNotFound || (expectedCount == 1 && end != length - 1))
+        size_t delimiter = WTF::find(pos, end - pos, expectedCount == 1 ? ')' : ',');
+        if (delimiter == kNotFound)
             return false;
-        unsigned argumentLength = end - start;
+        unsigned argumentLength = static_cast<unsigned>(delimiter);
         CSSPrimitiveValue::UnitTypes unit = CSSPrimitiveValue::CSS_NUMBER;
         double number;
-        if (!parseSimpleLength(characters + start, argumentLength, unit, number))
+        if (!parseSimpleLength(pos, argumentLength, unit, number))
             return false;
         if (unit != CSSPrimitiveValue::CSS_PX && (number || unit != CSSPrimitiveValue::CSS_NUMBER))
             return false;
         transformValue->append(cssValuePool().createValue(number, CSSPrimitiveValue::CSS_PX));
-        start = end + 1;
+        pos += argumentLength + 1;
         --expectedCount;
     }
     return true;
 }
 
-static bool parseTranslateTransformValue(MutableStylePropertySet* properties, CSSPropertyID propertyID, const String& string, bool important)
+template <typename CharType>
+static PassRefPtrWillBeRawPtr<CSSTransformValue> parseTranslateTransformValue(CharType*& pos, CharType* end)
 {
-    if (propertyID != CSSPropertyWebkitTransform)
-        return false;
-    static const unsigned shortestValidTransformStringLength = 12;
-    static const unsigned likelyMultipartTransformStringLengthCutoff = 32;
-    if (string.length() < shortestValidTransformStringLength || string.length() > likelyMultipartTransformStringLengthCutoff)
-        return false;
-    if (!string.startsWith("translate", false))
-        return false;
-    UChar c9 = toASCIILower(string[9]);
-    UChar c10 = toASCIILower(string[10]);
+    static const int shortestValidTransformStringLength = 12;
+
+    if (end - pos < shortestValidTransformStringLength)
+        return 0;
+
+    if ((pos[0] != 't' && pos[0] != 'T')
+        || (pos[1] != 'r' && pos[1] != 'R')
+        || (pos[2] != 'a' && pos[2] != 'A')
+        || (pos[3] != 'n' && pos[3] != 'N')
+        || (pos[4] != 's' && pos[4] != 'S')
+        || (pos[5] != 'l' && pos[5] != 'L')
+        || (pos[6] != 'a' && pos[6] != 'A')
+        || (pos[7] != 't' && pos[7] != 'T')
+        || (pos[8] != 'e' && pos[8] != 'E'))
+        return 0;
 
     CSSTransformValue::TransformOperationType transformType;
     unsigned expectedArgumentCount = 1;
     unsigned argumentStart = 11;
-    if (c9 == 'x' && c10 == '(')
+    if ((pos[9] == 'x' || pos[9] == 'X') && pos[10] == '(') {
         transformType = CSSTransformValue::TranslateXTransformOperation;
-    else if (c9 == 'y' && c10 == '(')
+    } else if ((pos[9] == 'y' || pos[9] == 'Y') && pos[10] == '(') {
         transformType = CSSTransformValue::TranslateYTransformOperation;
-    else if (c9 == 'z' && c10 == '(')
+    } else if ((pos[9] == 'z' || pos[9] == 'Z') && pos[10] == '(') {
         transformType = CSSTransformValue::TranslateZTransformOperation;
-    else if (c9 == '(') {
+    } else if (pos[9] == '(') {
         transformType = CSSTransformValue::TranslateTransformOperation;
         expectedArgumentCount = 2;
         argumentStart = 10;
-    } else if (c9 == '3' && c10 == 'd' && string[11] == '(') {
+    } else if (pos[9] == '3' && (pos[10] == 'd' || pos[10] == 'D') && pos[11] == '(') {
         transformType = CSSTransformValue::Translate3DTransformOperation;
         expectedArgumentCount = 3;
         argumentStart = 12;
-    } else
-        return false;
+    } else {
+        return 0;
+    }
+    pos += argumentStart;
 
-    RefPtr<CSSTransformValue> transformValue = CSSTransformValue::create(transformType);
-    bool success;
-    if (string.is8Bit())
-        success = parseTransformTranslateArguments(transformValue.get(), string.characters8(), string.length(), argumentStart, expectedArgumentCount);
-    else
-        success = parseTransformTranslateArguments(transformValue.get(), string.characters16(), string.length(), argumentStart, expectedArgumentCount);
-    if (!success)
+    RefPtrWillBeRawPtr<CSSTransformValue> transformValue = CSSTransformValue::create(transformType);
+    if (!parseTransformTranslateArguments(pos, end, expectedArgumentCount, transformValue.get()))
+        return 0;
+    return transformValue.release();
+}
+
+template <typename CharType>
+static PassRefPtrWillBeRawPtr<CSSValueList> parseTranslateTransformList(CharType*& pos, CharType* end)
+{
+    RefPtrWillBeRawPtr<CSSValueList> transformList;
+    while (pos < end) {
+        while (pos < end && isCSSSpace(*pos))
+            ++pos;
+        RefPtrWillBeRawPtr<CSSTransformValue> transformValue = parseTranslateTransformValue(pos, end);
+        if (!transformValue)
+            return 0;
+        if (!transformList)
+            transformList = CSSValueList::createSpaceSeparated();
+        transformList->append(transformValue.release());
+        if (pos < end) {
+            if (isCSSSpace(*pos))
+                return 0;
+        }
+    }
+    return transformList.release();
+}
+
+static bool parseTranslateTransform(MutableStylePropertySet* properties, CSSPropertyID propertyID, const String& string, bool important)
+{
+    if (propertyID != CSSPropertyWebkitTransform)
         return false;
-    RefPtr<CSSValueList> result = CSSValueList::createSpaceSeparated();
-    result->append(transformValue.release());
-    properties->addParsedProperty(CSSProperty(CSSPropertyWebkitTransform, result.release(), important));
+    if (string.isEmpty())
+        return false;
+    RefPtrWillBeRawPtr<CSSValueList> transformList;
+    if (string.is8Bit()) {
+        const LChar* pos = string.characters8();
+        const LChar* end = pos + string.length();
+        transformList = parseTranslateTransformList(pos, end);
+        if (!transformList)
+            return false;
+    } else {
+        const UChar* pos = string.characters16();
+        const UChar* end = pos + string.length();
+        transformList = parseTranslateTransformList(pos, end);
+        if (!transformList)
+            return false;
+    }
+    properties->addParsedProperty(CSSProperty(CSSPropertyWebkitTransform, transformList.release(), important));
     return true;
 }
 
-PassRefPtr<CSSValueList> CSSParser::parseFontFaceValue(const AtomicString& string)
+PassRefPtrWillBeRawPtr<CSSValueList> BisonCSSParser::parseFontFaceValue(const AtomicString& string)
 {
     if (string.isEmpty())
         return 0;
@@ -1067,11 +1085,22 @@
     return toCSSValueList(dummyStyle->getPropertyCSSValue(CSSPropertyFontFamily).get());
 }
 
-bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, const Document& document)
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationTimingFunctionValue(const String& string)
+{
+    if (string.isEmpty())
+        return 0;
+    RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
+    if (!parseValue(style.get(), CSSPropertyAnimationTimingFunction, string, false, HTMLStandardMode, 0))
+        return 0;
+
+    return style->getPropertyCSSValue(CSSPropertyAnimationTimingFunction);
+}
+
+bool BisonCSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, const Document& document)
 {
     ASSERT(!string.isEmpty());
 
-    CSSParserContext context(document);
+    CSSParserContext context(document, UseCounter::getFrom(&document));
 
     if (parseSimpleLengthValue(declaration, propertyID, string, important, context.mode()))
         return true;
@@ -1080,11 +1109,11 @@
     if (parseKeywordValue(declaration, propertyID, string, important, context))
         return true;
 
-    CSSParser parser(context, UseCounter::getFrom(&document));
+    BisonCSSParser parser(context);
     return parser.parseValue(declaration, propertyID, string, important, static_cast<StyleSheetContents*>(0));
 }
 
-bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, CSSParserMode cssParserMode, StyleSheetContents* contextStyleSheet)
+bool BisonCSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, CSSParserMode cssParserMode, StyleSheetContents* contextStyleSheet)
 {
     ASSERT(!string.isEmpty());
     if (parseSimpleLengthValue(declaration, propertyID, string, important, cssParserMode))
@@ -1092,7 +1121,7 @@
     if (parseColorValue(declaration, propertyID, string, important, cssParserMode))
         return true;
 
-    CSSParserContext context(cssParserMode);
+    CSSParserContext context(cssParserMode, 0);
     if (contextStyleSheet) {
         context = contextStyleSheet->parserContext();
         context.setMode(cssParserMode);
@@ -1100,19 +1129,19 @@
 
     if (parseKeywordValue(declaration, propertyID, string, important, context))
         return true;
-    if (parseTranslateTransformValue(declaration, propertyID, string, important))
+    if (parseTranslateTransform(declaration, propertyID, string, important))
         return true;
 
-    CSSParser parser(context);
+    BisonCSSParser parser(context);
     return parser.parseValue(declaration, propertyID, string, important, contextStyleSheet);
 }
 
-bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, StyleSheetContents* contextStyleSheet)
+bool BisonCSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, StyleSheetContents* contextStyleSheet)
 {
     // FIXME: Check RuntimeCSSEnabled::isPropertyEnabled or isValueEnabledForProperty.
 
-    if (m_useCounter)
-        m_useCounter->count(m_context, propertyID);
+    if (m_context.useCounter())
+        m_context.useCounter()->count(m_context, propertyID);
 
     setStyleSheet(contextStyleSheet);
 
@@ -1143,13 +1172,13 @@
 
 // The color will only be changed when string contains a valid CSS color, so callers
 // can set it to a default color and ignore the boolean result.
-bool CSSParser::parseColor(RGBA32& color, const String& string, bool strict)
+bool BisonCSSParser::parseColor(RGBA32& color, const String& string, bool strict)
 {
     // First try creating a color specified by name, rgba(), rgb() or "#" syntax.
     if (fastParseColor(color, string, strict))
         return true;
 
-    CSSParser parser(HTMLStandardMode);
+    BisonCSSParser parser(strictCSSParserContext());
 
     // In case the fast-path parser didn't understand the color, try the full parser.
     if (!parser.parseColor(string))
@@ -1167,7 +1196,7 @@
     return true;
 }
 
-bool CSSParser::parseColor(const String& string)
+bool BisonCSSParser::parseColor(const String& string)
 {
     setupParser("@-internal-decls color:", string, "");
     cssyyparse(this);
@@ -1176,22 +1205,29 @@
     return !m_parsedProperties.isEmpty() && m_parsedProperties.first().id() == CSSPropertyColor;
 }
 
-bool CSSParser::parseSystemColor(RGBA32& color, const String& string, Document* document)
+// FIXME: This is copied from SVGCSSParser.cpp
+static bool isSystemColor(int id)
 {
-    if (!document || !document->page())
+    return (id >= CSSValueActiveborder && id <= CSSValueWindowtext) || id == CSSValueMenu;
+}
+
+bool BisonCSSParser::parseSystemColor(RGBA32& color, const String& string, Document* document)
+{
+    if (!document)
         return false;
 
     CSSParserString cssColor;
     cssColor.init(string);
     CSSValueID id = cssValueKeywordID(cssColor);
-    if (id <= 0)
+    if (!isSystemColor(id))
         return false;
 
-    color = RenderTheme::theme().systemColor(id).rgb();
+    Color parsedColor = RenderTheme::theme().systemColor(id);
+    color = parsedColor.rgb();
     return true;
 }
 
-void CSSParser::parseSelector(const String& string, CSSSelectorList& selectorList)
+void BisonCSSParser::parseSelector(const String& string, CSSSelectorList& selectorList)
 {
     m_selectorListForParseSelector = &selectorList;
 
@@ -1202,15 +1238,15 @@
     m_selectorListForParseSelector = 0;
 }
 
-PassRefPtr<ImmutableStylePropertySet> CSSParser::parseInlineStyleDeclaration(const String& string, Element* element)
+PassRefPtr<ImmutableStylePropertySet> BisonCSSParser::parseInlineStyleDeclaration(const String& string, Element* element)
 {
     Document& document = element->document();
-    CSSParserContext context = document.elementSheet()->contents()->parserContext();
+    CSSParserContext context = CSSParserContext(document.elementSheet()->contents()->parserContext(), UseCounter::getFrom(&document));
     context.setMode((element->isHTMLElement() && !document.inQuirksMode()) ? HTMLStandardMode : HTMLQuirksMode);
-    return CSSParser(context, UseCounter::getFrom(&document)).parseDeclaration(string, document.elementSheet()->contents());
+    return BisonCSSParser(context).parseDeclaration(string, document.elementSheet()->contents());
 }
 
-PassRefPtr<ImmutableStylePropertySet> CSSParser::parseDeclaration(const String& string, StyleSheetContents* contextStyleSheet)
+PassRefPtr<ImmutableStylePropertySet> BisonCSSParser::parseDeclaration(const String& string, StyleSheetContents* contextStyleSheet)
 {
     setStyleSheet(contextStyleSheet);
 
@@ -1227,17 +1263,17 @@
 }
 
 
-bool CSSParser::parseDeclaration(MutableStylePropertySet* declaration, const String& string, SourceDataHandler* sourceDataHandler, StyleSheetContents* contextStyleSheet)
+bool BisonCSSParser::parseDeclaration(MutableStylePropertySet* declaration, const String& string, CSSParserObserver* observer, StyleSheetContents* contextStyleSheet)
 {
     setStyleSheet(contextStyleSheet);
 
-    m_sourceDataHandler = sourceDataHandler;
+    TemporaryChange<CSSParserObserver*> scopedObsever(m_observer, observer);
 
     setupParser("@-internal-decls ", string, "");
-    if (m_sourceDataHandler) {
-        m_sourceDataHandler->startRuleHeader(CSSRuleSourceData::STYLE_RULE, 0);
-        m_sourceDataHandler->endRuleHeader(1);
-        m_sourceDataHandler->startRuleBody(0);
+    if (m_observer) {
+        m_observer->startRuleHeader(CSSRuleSourceData::STYLE_RULE, 0);
+        m_observer->endRuleHeader(1);
+        m_observer->startRuleBody(0);
     }
 
     {
@@ -1256,14 +1292,13 @@
         clearProperties();
     }
 
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->endRuleBody(string.length(), false);
-    m_sourceDataHandler = 0;
+    if (m_observer)
+        m_observer->endRuleBody(string.length(), false);
 
     return ok;
 }
 
-PassRefPtr<MediaQuerySet> CSSParser::parseMediaQueryList(const String& string)
+PassRefPtr<MediaQuerySet> BisonCSSParser::parseMediaQueryList(const String& string)
 {
     ASSERT(!m_mediaList);
 
@@ -1276,20 +1311,13 @@
     return m_mediaList.release();
 }
 
-static inline void filterProperties(bool important, const CSSParser::ParsedPropertyVector& input, Vector<CSSProperty, 256>& output, size_t& unusedEntries, BitArray<numCSSProperties>& seenProperties, HashSet<AtomicString>& seenVariables)
+static inline void filterProperties(bool important, const BisonCSSParser::ParsedPropertyVector& input, Vector<CSSProperty, 256>& output, size_t& unusedEntries, BitArray<numCSSProperties>& seenProperties)
 {
     // Add properties in reverse order so that highest priority definitions are reached first. Duplicate definitions can then be ignored when found.
     for (int i = input.size() - 1; i >= 0; --i) {
         const CSSProperty& property = input[i];
         if (property.isImportant() != important)
             continue;
-        if (property.id() == CSSPropertyVariable) {
-            const AtomicString& name = toCSSVariableValue(property.value())->name();
-            if (!seenVariables.add(name).isNewEntry)
-                continue;
-            output[--unusedEntries] = property;
-            continue;
-        }
         const unsigned propertyIDIndex = property.id() - firstCSSProperty;
         if (seenProperties.get(propertyIDIndex))
             continue;
@@ -1298,16 +1326,15 @@
     }
 }
 
-PassRefPtr<ImmutableStylePropertySet> CSSParser::createStylePropertySet()
+PassRefPtr<ImmutableStylePropertySet> BisonCSSParser::createStylePropertySet()
 {
     BitArray<numCSSProperties> seenProperties;
     size_t unusedEntries = m_parsedProperties.size();
     Vector<CSSProperty, 256> results(unusedEntries);
 
     // Important properties have higher priority, so add them first. Duplicate definitions can then be ignored when found.
-    HashSet<AtomicString> seenVariables;
-    filterProperties(true, m_parsedProperties, results, unusedEntries, seenProperties, seenVariables);
-    filterProperties(false, m_parsedProperties, results, unusedEntries, seenProperties, seenVariables);
+    filterProperties(true, m_parsedProperties, results, unusedEntries, seenProperties);
+    filterProperties(false, m_parsedProperties, results, unusedEntries, seenProperties);
     if (unusedEntries)
         results.remove(0, unusedEntries);
 
@@ -1316,7 +1343,7 @@
     return ImmutableStylePropertySet::create(results.data(), results.size(), mode);
 }
 
-void CSSParser::addPropertyWithPrefixingVariant(CSSPropertyID propId, PassRefPtr<CSSValue> value, bool important, bool implicit)
+void BisonCSSParser::addPropertyWithPrefixingVariant(CSSPropertyID propId, PassRefPtr<CSSValue> value, bool important, bool implicit)
 {
     RefPtr<CSSValue> val = value.get();
     addProperty(propId, value, important, implicit);
@@ -1335,11 +1362,10 @@
     }
 }
 
-void CSSParser::addProperty(CSSPropertyID propId, PassRefPtr<CSSValue> value, bool important, bool implicit)
+void BisonCSSParser::addProperty(CSSPropertyID propId, PassRefPtr<CSSValue> value, bool important, bool implicit)
 {
-    CSSPrimitiveValue* primitiveValue = value->isPrimitiveValue() ? toCSSPrimitiveValue(value.get()) : 0;
-    // This property doesn't belong to a shorthand or is a CSS variable (which will be resolved later).
-    if (!m_currentShorthand || (primitiveValue && primitiveValue->isVariableName())) {
+    // This property doesn't belong to a shorthand.
+    if (!m_currentShorthand) {
         m_parsedProperties.append(CSSProperty(propId, value, important, false, CSSPropertyInvalid, m_implicitShorthand || implicit));
         return;
     }
@@ -1353,36 +1379,26 @@
         m_parsedProperties.append(CSSProperty(propId, value, important, true, indexOfShorthandForLonghand(m_currentShorthand, shorthands), m_implicitShorthand || implicit));
 }
 
-void CSSParser::rollbackLastProperties(int num)
+void BisonCSSParser::rollbackLastProperties(int num)
 {
     ASSERT(num >= 0);
     ASSERT(m_parsedProperties.size() >= static_cast<unsigned>(num));
     m_parsedProperties.shrink(m_parsedProperties.size() - num);
 }
 
-void CSSParser::clearProperties()
+void BisonCSSParser::clearProperties()
 {
     m_parsedProperties.clear();
     m_numParsedPropertiesBeforeMarginBox = INVALID_NUM_PARSED_PROPERTIES;
     m_hasFontFaceOnlyValues = false;
 }
 
-// FIXME: Move to CSSParserContext?
-KURL CSSParser::completeURL(const CSSParserContext& context, const String& url)
+KURL BisonCSSParser::completeURL(const String& url) const
 {
-    if (url.isNull())
-        return KURL();
-    if (context.charset().isEmpty())
-        return KURL(context.baseURL(), url);
-    return KURL(context.baseURL(), url, context.charset());
+    return m_context.completeURL(url);
 }
 
-KURL CSSParser::completeURL(const String& url) const
-{
-    return completeURL(m_context, url);
-}
-
-bool CSSParser::validCalculationUnit(CSSParserValue* value, Units unitflags, ReleaseParsedCalcValueCondition releaseCalc)
+bool BisonCSSParser::validCalculationUnit(CSSParserValue* value, Units unitflags, ReleaseParsedCalcValueCondition releaseCalc)
 {
     bool mustBeNonNegative = unitflags & FNonNeg;
 
@@ -1412,9 +1428,6 @@
     case CalcPercentNumber:
         b = (unitflags & FPercent) && (unitflags & FNumber);
         break;
-    case CalcVariable:
-        b = true;
-        break;
     case CalcOther:
         break;
     }
@@ -1423,23 +1436,19 @@
     return b;
 }
 
-inline bool CSSParser::shouldAcceptUnitLessValues(CSSParserValue* value, Units unitflags, CSSParserMode cssParserMode)
+inline bool BisonCSSParser::shouldAcceptUnitLessValues(CSSParserValue* value, Units unitflags, CSSParserMode cssParserMode)
 {
     // Quirks mode and presentation attributes accept unit less values.
     return (unitflags & (FLength | FAngle | FTime)) && (!value->fValue || isUnitLessLengthParsingEnabledForMode(cssParserMode));
 }
 
-bool CSSParser::validUnit(CSSParserValue* value, Units unitflags, CSSParserMode cssParserMode, ReleaseParsedCalcValueCondition releaseCalc)
+bool BisonCSSParser::validUnit(CSSParserValue* value, Units unitflags, CSSParserMode cssParserMode, ReleaseParsedCalcValueCondition releaseCalc)
 {
     if (isCalculation(value))
         return validCalculationUnit(value, unitflags, releaseCalc);
 
     bool b = false;
     switch (value->unit) {
-    case CSSPrimitiveValue::CSS_VARIABLE_NAME:
-        // Variables are checked at the point they are dereferenced because unit type is not available here.
-        b = true;
-        break;
     case CSSPrimitiveValue::CSS_NUMBER:
         b = (unitflags & FNumber);
         if (!b && shouldAcceptUnitLessValues(value, unitflags, cssParserMode)) {
@@ -1498,11 +1507,8 @@
     return b;
 }
 
-inline PassRefPtr<CSSPrimitiveValue> CSSParser::createPrimitiveNumericValue(CSSParserValue* value)
+inline PassRefPtrWillBeRawPtr<CSSPrimitiveValue> BisonCSSParser::createPrimitiveNumericValue(CSSParserValue* value)
 {
-    if (value->unit == CSSPrimitiveValue::CSS_VARIABLE_NAME)
-        return createPrimitiveVariableNameValue(value);
-
     if (m_parsedCalculation) {
         ASSERT(isCalculation(value));
         return CSSPrimitiveValue::create(m_parsedCalculation.release());
@@ -1515,18 +1521,12 @@
     return cssValuePool().createValue(value->fValue, static_cast<CSSPrimitiveValue::UnitTypes>(value->unit));
 }
 
-inline PassRefPtr<CSSPrimitiveValue> CSSParser::createPrimitiveStringValue(CSSParserValue* value)
+inline PassRefPtrWillBeRawPtr<CSSPrimitiveValue> BisonCSSParser::createPrimitiveStringValue(CSSParserValue* value)
 {
     ASSERT(value->unit == CSSPrimitiveValue::CSS_STRING || value->unit == CSSPrimitiveValue::CSS_IDENT);
     return cssValuePool().createValue(value->string, CSSPrimitiveValue::CSS_STRING);
 }
 
-inline PassRefPtr<CSSPrimitiveValue> CSSParser::createPrimitiveVariableNameValue(CSSParserValue* value)
-{
-    ASSERT(value->unit == CSSPrimitiveValue::CSS_VARIABLE_NAME);
-    return CSSPrimitiveValue::create(value->string, CSSPrimitiveValue::CSS_VARIABLE_NAME);
-}
-
 static inline bool isComma(CSSParserValue* value)
 {
     return value && value->unit == CSSParserValue::Operator && value->iValue == ',';
@@ -1556,7 +1556,7 @@
         || equalIgnoringCase(val->function->name, "-webkit-cross-fade(");
 }
 
-bool CSSParser::validWidthOrHeight(CSSParserValue* value)
+bool BisonCSSParser::validWidthOrHeight(CSSParserValue* value)
 {
     int id = value->id;
     if (id == CSSValueIntrinsic || id == CSSValueMinIntrinsic || id == CSSValueWebkitMinContent || id == CSSValueWebkitMaxContent || id == CSSValueWebkitFillAvailable || id == CSSValueWebkitFitContent)
@@ -1564,7 +1564,7 @@
     return !id && validUnit(value, FLength | FPercent | FNonNeg);
 }
 
-inline PassRefPtr<CSSPrimitiveValue> CSSParser::parseValidPrimitive(CSSValueID identifier, CSSParserValue* value)
+inline PassRefPtrWillBeRawPtr<CSSPrimitiveValue> BisonCSSParser::parseValidPrimitive(CSSValueID identifier, CSSParserValue* value)
 {
     if (identifier)
         return cssValuePool().createIdentifierValue(identifier);
@@ -1578,8 +1578,6 @@
         return createPrimitiveNumericValue(value);
     if (value->unit >= CSSPrimitiveValue::CSS_DPPX && value->unit <= CSSPrimitiveValue::CSS_DPCM)
         return createPrimitiveNumericValue(value);
-    if (value->unit == CSSPrimitiveValue::CSS_VARIABLE_NAME)
-        return createPrimitiveVariableNameValue(value);
     if (value->unit >= CSSParserValue::Q_EMS)
         return CSSPrimitiveValue::createAllowingMarginQuirk(value->fValue, CSSPrimitiveValue::CSS_EMS);
     if (isCalculation(value))
@@ -1588,7 +1586,7 @@
     return 0;
 }
 
-void CSSParser::addExpandedPropertyForValue(CSSPropertyID propId, PassRefPtr<CSSValue> prpValue, bool important)
+void BisonCSSParser::addExpandedPropertyForValue(CSSPropertyID propId, PassRefPtr<CSSValue> prpValue, bool important)
 {
     const StylePropertyShorthand& shorthand = shorthandForProperty(propId);
     unsigned shorthandLength = shorthand.length();
@@ -1604,19 +1602,19 @@
         addProperty(longhands[i], value, important);
 }
 
-void CSSParser::setCurrentProperty(CSSPropertyID propId)
+void BisonCSSParser::setCurrentProperty(CSSPropertyID propId)
 {
     m_id = propId;
 }
 
-bool CSSParser::parseValue(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseValue(CSSPropertyID propId, bool important)
 {
     if (!isInternalPropertyAndValueParsingEnabledForMode(m_context.mode()) && isInternalProperty(propId))
         return false;
 
     // We don't count the UA style sheet in our statistics.
-    if (m_useCounter)
-        m_useCounter->count(m_context, propId);
+    if (m_context.useCounter())
+        m_context.useCounter()->count(m_context, propId);
 
     if (!m_valueList)
         return false;
@@ -1655,13 +1653,6 @@
         return true;
     }
 
-    if (!id && value->unit == CSSPrimitiveValue::CSS_VARIABLE_NAME && num == 1) {
-        addProperty(propId, createPrimitiveVariableNameValue(value), important);
-        m_valueList->next();
-        return true;
-    }
-    ASSERT(propId != CSSPropertyVariable);
-
     if (isKeywordPropertyID(propId)) {
         if (!isValidKeywordPropertyAndValue(propId, id, m_context))
             return false;
@@ -1808,7 +1799,7 @@
         // ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | text | wait | help |
         // vertical-text | cell | context-menu | alias | copy | no-drop | not-allowed | -webkit-zoom-in
         // -webkit-zoom-out | all-scroll | -webkit-grab | -webkit-grabbing ] ] | inherit
-        RefPtr<CSSValueList> list;
+        RefPtrWillBeRawPtr<CSSValueList> list;
         while (value) {
             RefPtr<CSSValue> image = 0;
             if (value->unit == CSSPrimitiveValue::CSS_URI) {
@@ -2041,17 +2032,18 @@
             validPrimitive = (!id && validUnit(value, FLength | FPercent));
         break;
 
-    case CSSPropertyZIndex:              // auto | <integer> | inherit
-        if (id == CSSValueAuto) {
-            validPrimitive = true;
-            break;
-        }
-        /* nobreak */
     case CSSPropertyOrphans: // <integer> | inherit | auto (We've added support for auto for backwards compatibility)
     case CSSPropertyWidows: // <integer> | inherit | auto (Ditto)
         if (id == CSSValueAuto)
             validPrimitive = true;
         else
+            validPrimitive = (!id && validUnit(value, FPositiveInteger, HTMLQuirksMode));
+        break;
+
+    case CSSPropertyZIndex: // auto | <integer> | inherit
+        if (id == CSSValueAuto)
+            validPrimitive = true;
+        else
             validPrimitive = (!id && validUnit(value, FInteger, HTMLQuirksMode));
         break;
 
@@ -2107,8 +2099,6 @@
         break;
 
     case CSSPropertySrc: // Only used within @font-face and @-webkit-filter, so cannot use inherit | initial or be !important. This is a list of urls or local references.
-        if (m_inFilterRule)
-            return parseFilterRuleSrc();
         return parseFontFaceSrc();
 
     case CSSPropertyUnicodeRange:
@@ -2129,7 +2119,7 @@
 
     case CSSPropertyBorderImageOutset:
     case CSSPropertyWebkitMaskBoxImageOutset: {
-        RefPtr<CSSPrimitiveValue> result;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> result;
         if (parseBorderImageOutset(result)) {
             addProperty(propId, result, important);
             return true;
@@ -2147,7 +2137,7 @@
     }
     case CSSPropertyBorderImageSlice:
     case CSSPropertyWebkitMaskBoxImageSlice: {
-        RefPtr<CSSBorderImageSliceValue> result;
+        RefPtrWillBeRawPtr<CSSBorderImageSliceValue> result;
         if (parseBorderImageSlice(propId, result)) {
             addProperty(propId, result, important);
             return true;
@@ -2156,7 +2146,7 @@
     }
     case CSSPropertyBorderImageWidth:
     case CSSPropertyWebkitMaskBoxImageWidth: {
-        RefPtr<CSSPrimitiveValue> result;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> result;
         if (parseBorderImageWidth(result)) {
             addProperty(propId, result, important);
             return true;
@@ -2172,8 +2162,8 @@
         validPrimitive = validUnit(value, FLength | FPercent | FNonNeg);
         if (!validPrimitive)
             return false;
-        RefPtr<CSSPrimitiveValue> parsedValue1 = createPrimitiveNumericValue(value);
-        RefPtr<CSSPrimitiveValue> parsedValue2;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue1 = createPrimitiveNumericValue(value);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue2;
         if (num == 2) {
             value = m_valueList->next();
             validPrimitive = validUnit(value, FLength | FPercent | FNonNeg);
@@ -2203,7 +2193,7 @@
         if (id == CSSValueNone)
             validPrimitive = true;
         else {
-            RefPtr<CSSValueList> shadowValueList = parseShadow(m_valueList.get(), propId);
+            RefPtrWillBeRawPtr<CSSValueList> shadowValueList = parseShadow(m_valueList.get(), propId);
             if (shadowValueList) {
                 addProperty(propId, shadowValueList.release(), important);
                 m_valueList->next();
@@ -2264,16 +2254,7 @@
         validPrimitive = validUnit(value, FNumber | FNonNeg);
         break;
     case CSSPropertyOrder:
-        if (validUnit(value, FInteger, HTMLStandardMode)) {
-            if (value->unit != CSSPrimitiveValue::CSS_VARIABLE_NAME) {
-                // We restrict the smallest value to int min + 2 because we use int min and int min + 1 as special values in a hash set.
-                parsedValue = cssValuePool().createValue(max(static_cast<double>(std::numeric_limits<int>::min() + 2), value->fValue),
-                    static_cast<CSSPrimitiveValue::UnitTypes>(value->unit));
-                m_valueList->next();
-            } else {
-                validPrimitive = true;
-            }
-        }
+        validPrimitive = validUnit(value, FInteger, HTMLStandardMode);
         break;
     case CSSPropertyInternalMarqueeIncrement:
         if (id == CSSValueSmall || id == CSSValueLarge || id == CSSValueMedium)
@@ -2293,14 +2274,6 @@
         else
             validPrimitive = validUnit(value, FTime | FInteger | FNonNeg);
         break;
-    case CSSPropertyWebkitFlowInto:
-        if (!RuntimeEnabledFeatures::cssRegionsEnabled())
-            return false;
-        return parseFlowThread(propId, important);
-    case CSSPropertyWebkitFlowFrom:
-        if (!RuntimeEnabledFeatures::cssRegionsEnabled())
-            return false;
-        return parseRegionThread(propId, important);
     case CSSPropertyWebkitTransform:
         if (id == CSSValueNone)
             validPrimitive = true;
@@ -2395,6 +2368,11 @@
         return false;
     }
 
+    case CSSPropertyJustifySelf:
+        if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
+            return false;
+
+        return parseItemPositionOverflowPosition(propId, important);
     case CSSPropertyGridAutoColumns:
     case CSSPropertyGridAutoRows:
         if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
@@ -2402,8 +2380,8 @@
         parsedValue = parseGridTrackSize(*m_valueList);
         break;
 
-    case CSSPropertyGridDefinitionColumns:
-    case CSSPropertyGridDefinitionRows:
+    case CSSPropertyGridTemplateColumns:
+    case CSSPropertyGridTemplateRows:
         if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
             return false;
         return parseGridTrackList(propId, important);
@@ -2428,10 +2406,10 @@
             return false;
         return parseGridAreaShorthand(important);
 
-    case CSSPropertyGridTemplate:
+    case CSSPropertyGridTemplateAreas:
         if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
             return false;
-        parsedValue = parseGridTemplate();
+        parsedValue = parseGridTemplateAreas();
         break;
 
     case CSSPropertyWebkitMarginCollapse: {
@@ -2510,17 +2488,6 @@
             validPrimitive = true;
         break;
 
-    case CSSPropertyWebkitLineGrid:
-        if (id == CSSValueNone)
-            validPrimitive = true;
-        else if (value->unit == CSSPrimitiveValue::CSS_IDENT) {
-            String lineGridValue = String(value->string);
-            if (!lineGridValue.isEmpty()) {
-                addProperty(propId, cssValuePool().createValue(lineGridValue, CSSPrimitiveValue::CSS_STRING), important);
-                return true;
-            }
-        }
-        break;
     case CSSPropertyWebkitLocale:
         if (id == CSSValueAuto || value->unit == CSSPrimitiveValue::CSS_STRING)
             validPrimitive = true;
@@ -2665,7 +2632,7 @@
             return parseFontFeatureSettings(important);
         break;
 
-    case CSSPropertyWebkitFontVariantLigatures:
+    case CSSPropertyFontVariantLigatures:
         if (id == CSSValueNormal)
             validPrimitive = true;
         else
@@ -2675,7 +2642,7 @@
         if (id == CSSValueNone) {
             validPrimitive = true;
         } else if (value->unit == CSSParserValue::Function) {
-            return parseBasicShape(propId, important);
+            parsedValue = parseBasicShape();
         } else if (value->unit == CSSPrimitiveValue::CSS_URI) {
             parsedValue = CSSPrimitiveValue::create(value->string, CSSPrimitiveValue::CSS_URI);
             addProperty(propId, parsedValue.release(), important);
@@ -2684,20 +2651,7 @@
         break;
     case CSSPropertyShapeInside:
     case CSSPropertyShapeOutside:
-        if (!RuntimeEnabledFeatures::cssShapesEnabled())
-            return false;
-        if (id == CSSValueAuto)
-            validPrimitive = true;
-        else if (id == CSSValueContentBox || id == CSSValuePaddingBox || id == CSSValueBorderBox || id == CSSValueMarginBox)
-            validPrimitive = true;
-        else if (propId == CSSPropertyShapeInside && id == CSSValueOutsideShape)
-            validPrimitive = true;
-        else if (value->unit == CSSParserValue::Function)
-            return parseBasicShape(propId, important);
-        else if (value->unit == CSSPrimitiveValue::CSS_URI) {
-            parsedValue = CSSImageValue::create(completeURL(value->string));
-            m_valueList->next();
-        }
+        parsedValue = parseShapeProperty(propId);
         break;
     case CSSPropertyShapeMargin:
     case CSSPropertyShapePadding:
@@ -2706,6 +2660,19 @@
     case CSSPropertyShapeImageThreshold:
         validPrimitive = (RuntimeEnabledFeatures::cssShapesEnabled() && !id && validUnit(value, FNumber));
         break;
+
+    case CSSPropertyTouchAction:
+        // auto | none | [pan-x || pan-y]
+        return parseTouchAction(important);
+
+    case CSSPropertyAlignSelf:
+        ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
+        return parseItemPositionOverflowPosition(propId, important);
+
+    case CSSPropertyAlignItems:
+        ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
+        return parseItemPositionOverflowPosition(propId, important);
+
     case CSSPropertyBorderBottomStyle:
     case CSSPropertyBorderCollapse:
     case CSSPropertyBorderLeftStyle:
@@ -2746,9 +2713,7 @@
     case CSSPropertyTextTransform:
     case CSSPropertyTextUnderlineMode:
     case CSSPropertyTextUnderlineStyle:
-    case CSSPropertyTouchAction:
     case CSSPropertyTouchActionDelay:
-    case CSSPropertyVariable:
     case CSSPropertyVisibility:
     case CSSPropertyWebkitAppearance:
     case CSSPropertyWebkitBackfaceVisibility:
@@ -2770,17 +2735,13 @@
     case CSSPropertyColumnFill:
     case CSSPropertyWebkitColumnRuleStyle:
     case CSSPropertyAlignContent:
-    case CSSPropertyAlignItems:
-    case CSSPropertyAlignSelf:
     case CSSPropertyFlexDirection:
     case CSSPropertyFlexWrap:
     case CSSPropertyJustifyContent:
     case CSSPropertyFontKerning:
     case CSSPropertyWebkitFontSmoothing:
     case CSSPropertyGridAutoFlow:
-    case CSSPropertyWebkitLineAlign:
     case CSSPropertyWebkitLineBreak:
-    case CSSPropertyWebkitLineSnap:
     case CSSPropertyWebkitMarginAfterCollapse:
     case CSSPropertyWebkitMarginBeforeCollapse:
     case CSSPropertyWebkitMarginBottomCollapse:
@@ -2788,10 +2749,6 @@
     case CSSPropertyInternalMarqueeDirection:
     case CSSPropertyInternalMarqueeStyle:
     case CSSPropertyWebkitPrintColorAdjust:
-    case CSSPropertyWebkitRegionBreakAfter:
-    case CSSPropertyWebkitRegionBreakBefore:
-    case CSSPropertyWebkitRegionBreakInside:
-    case CSSPropertyWebkitRegionFragment:
     case CSSPropertyWebkitRtlOrdering:
     case CSSPropertyWebkitRubyPosition:
     case CSSPropertyWebkitTextCombine:
@@ -2839,14 +2796,14 @@
     return false;
 }
 
-void CSSParser::addFillValue(RefPtr<CSSValue>& lval, PassRefPtr<CSSValue> rval)
+void BisonCSSParser::addFillValue(RefPtr<CSSValue>& lval, PassRefPtr<CSSValue> rval)
 {
     if (lval) {
         if (lval->isBaseValueList())
             toCSSValueList(lval.get())->append(rval);
         else {
             PassRefPtr<CSSValue> oldlVal(lval.release());
-            PassRefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            PassRefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             list->append(oldlVal);
             list->append(rval);
             lval = list;
@@ -2866,14 +2823,14 @@
     return false;
 }
 
-bool CSSParser::useLegacyBackgroundSizeShorthandBehavior() const
+bool BisonCSSParser::useLegacyBackgroundSizeShorthandBehavior() const
 {
     return m_context.useLegacyBackgroundSizeShorthandBehavior();
 }
 
 const int cMaxFillProperties = 9;
 
-bool CSSParser::parseFillShorthand(CSSPropertyID propId, const CSSPropertyID* properties, int numProperties, bool important)
+bool BisonCSSParser::parseFillShorthand(CSSPropertyID propId, const CSSPropertyID* properties, int numProperties, bool important)
 {
     ASSERT(numProperties <= cMaxFillProperties);
     if (numProperties > cMaxFillProperties)
@@ -3022,38 +2979,14 @@
     return true;
 }
 
-void CSSParser::storeVariableDeclaration(const CSSParserString& name, PassOwnPtr<CSSParserValueList> value, bool important)
-{
-    // When CSSGrammar.y encounters an invalid declaration it passes null for the CSSParserValueList, just bail.
-    if (!value)
-        return;
-
-    static const unsigned prefixLength = sizeof("var-") - 1;
-
-    ASSERT(name.length() > prefixLength);
-    AtomicString variableName = name.atomicSubstring(prefixLength, name.length() - prefixLength);
-
-    StringBuilder builder;
-    for (unsigned i = 0, size = value->size(); i < size; i++) {
-        if (i)
-            builder.append(' ');
-        RefPtr<CSSValue> cssValue = value->valueAt(i)->createCSSValue();
-        if (!cssValue)
-            return;
-        builder.append(cssValue->cssText());
-    }
-
-    addProperty(CSSPropertyVariable, CSSVariableValue::create(variableName, builder.toString()), important, false);
-}
-
-void CSSParser::addAnimationValue(RefPtr<CSSValue>& lval, PassRefPtr<CSSValue> rval)
+void BisonCSSParser::addAnimationValue(RefPtr<CSSValue>& lval, PassRefPtr<CSSValue> rval)
 {
     if (lval) {
         if (lval->isValueList())
             toCSSValueList(lval.get())->append(rval);
         else {
             PassRefPtr<CSSValue> oldVal(lval.release());
-            PassRefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            PassRefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             list->append(oldVal);
             list->append(rval);
             lval = list;
@@ -3063,7 +2996,7 @@
         lval = rval;
 }
 
-bool CSSParser::parseAnimationShorthand(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseAnimationShorthand(CSSPropertyID propId, bool important)
 {
     const StylePropertyShorthand& animationProperties = parsingShorthandForProperty(propId);
     const unsigned numProperties = 8;
@@ -3125,7 +3058,7 @@
     return true;
 }
 
-bool CSSParser::parseTransitionShorthand(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseTransitionShorthand(CSSPropertyID propId, bool important)
 {
     const unsigned numProperties = 4;
     const StylePropertyShorthand& shorthand = shorthandForProperty(propId);
@@ -3187,7 +3120,7 @@
     return true;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseColumnWidth()
+PassRefPtr<CSSValue> BisonCSSParser::parseColumnWidth()
 {
     CSSParserValue* value = m_valueList->current();
     // Always parse lengths in strict mode here, since it would be ambiguous otherwise when used in
@@ -3201,7 +3134,7 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseColumnCount()
+PassRefPtr<CSSValue> BisonCSSParser::parseColumnCount()
 {
     CSSParserValue* value = m_valueList->current();
     if (value->id == CSSValueAuto
@@ -3213,7 +3146,7 @@
     return 0;
 }
 
-bool CSSParser::parseColumnsShorthand(bool important)
+bool BisonCSSParser::parseColumnsShorthand(bool important)
 {
     RefPtr <CSSValue> columnWidth;
     RefPtr <CSSValue> columnCount;
@@ -3268,7 +3201,7 @@
     return true;
 }
 
-bool CSSParser::parseShorthand(CSSPropertyID propId, const StylePropertyShorthand& shorthand, bool important)
+bool BisonCSSParser::parseShorthand(CSSPropertyID propId, const StylePropertyShorthand& shorthand, bool important)
 {
     // We try to match as many properties as possible
     // We set up an array of booleans to mark which property has been found,
@@ -3277,14 +3210,14 @@
 
     bool found = false;
     unsigned propertiesParsed = 0;
-    bool propertyFound[6]= { false, false, false, false, false, false }; // 6 is enough size.
+    bool propertyFound[6] = { false, false, false, false, false, false }; // 6 is enough size.
 
     while (m_valueList->current()) {
         found = false;
         for (unsigned propIndex = 0; !found && propIndex < shorthand.length(); ++propIndex) {
             if (!propertyFound[propIndex] && parseValue(shorthand.properties()[propIndex], important)) {
-                    propertyFound[propIndex] = found = true;
-                    propertiesParsed++;
+                propertyFound[propIndex] = found = true;
+                propertiesParsed++;
             }
         }
 
@@ -3315,7 +3248,7 @@
     return true;
 }
 
-bool CSSParser::parse4Values(CSSPropertyID propId, const CSSPropertyID *properties,  bool important)
+bool BisonCSSParser::parse4Values(CSSPropertyID propId, const CSSPropertyID *properties,  bool important)
 {
     /* From the CSS 2 specs, 8.3
      * If there is only one value, it applies to all sides. If there are two values, the top and
@@ -3374,7 +3307,7 @@
 }
 
 // auto | <identifier>
-bool CSSParser::parsePage(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parsePage(CSSPropertyID propId, bool important)
 {
     ASSERT(propId == CSSPropertyPage);
 
@@ -3396,7 +3329,7 @@
 }
 
 // <length>{1,2} | auto | [ <page-size> || [ portrait | landscape] ]
-bool CSSParser::parseSize(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseSize(CSSPropertyID propId, bool important)
 {
     ASSERT(propId == CSSPropertySize);
 
@@ -3407,7 +3340,7 @@
     if (!value)
         return false;
 
-    RefPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
 
     // First parameter.
     SizeParameterType paramType = parseSizeParameter(parsedValues.get(), value, None);
@@ -3426,7 +3359,7 @@
     return true;
 }
 
-CSSParser::SizeParameterType CSSParser::parseSizeParameter(CSSValueList* parsedValues, CSSParserValue* value, SizeParameterType prevParamType)
+BisonCSSParser::SizeParameterType BisonCSSParser::parseSizeParameter(CSSValueList* parsedValues, CSSParserValue* value, SizeParameterType prevParamType)
 {
     switch (value->id) {
     case CSSValueAuto:
@@ -3470,9 +3403,9 @@
 
 // [ <string> <string> ]+ | inherit | none
 // inherit and none are handled in parseValue.
-bool CSSParser::parseQuotes(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseQuotes(CSSPropertyID propId, bool important)
 {
-    RefPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
     while (CSSParserValue* val = m_valueList->current()) {
         RefPtr<CSSValue> parsedValue;
         if (val->unit == CSSPrimitiveValue::CSS_STRING)
@@ -3493,9 +3426,9 @@
 // [ <string> | <uri> | <counter> | attr(X) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit
 // in CSS 2.1 this got somewhat reduced:
 // [ <string> | attr(X) | open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit
-bool CSSParser::parseContent(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseContent(CSSPropertyID propId, bool important)
 {
-    RefPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
 
     while (CSSParserValue* val = m_valueList->current()) {
         RefPtr<CSSValue> parsedValue;
@@ -3566,7 +3499,7 @@
     return false;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAttr(CSSParserValueList* args)
+PassRefPtr<CSSValue> BisonCSSParser::parseAttr(CSSParserValueList* args)
 {
     if (args->size() != 1)
         return 0;
@@ -3589,7 +3522,7 @@
     return cssValuePool().createValue(attrName, CSSPrimitiveValue::CSS_ATTR);
 }
 
-PassRefPtr<CSSValue> CSSParser::parseBackgroundColor()
+PassRefPtr<CSSValue> BisonCSSParser::parseBackgroundColor()
 {
     CSSValueID id = m_valueList->current()->id;
     if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu || id == CSSValueCurrentcolor ||
@@ -3598,7 +3531,7 @@
     return parseColor();
 }
 
-bool CSSParser::parseFillImage(CSSParserValueList* valueList, RefPtr<CSSValue>& value)
+bool BisonCSSParser::parseFillImage(CSSParserValueList* valueList, RefPtr<CSSValue>& value)
 {
     if (valueList->current()->id == CSSValueNone) {
         value = cssValuePool().createIdentifierValue(CSSValueNone);
@@ -3621,7 +3554,7 @@
     return false;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseFillPositionX(CSSParserValueList* valueList)
+PassRefPtr<CSSValue> BisonCSSParser::parseFillPositionX(CSSParserValueList* valueList)
 {
     int id = valueList->current()->id;
     if (id == CSSValueLeft || id == CSSValueRight || id == CSSValueCenter) {
@@ -3637,7 +3570,7 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseFillPositionY(CSSParserValueList* valueList)
+PassRefPtr<CSSValue> BisonCSSParser::parseFillPositionY(CSSParserValueList* valueList)
 {
     int id = valueList->current()->id;
     if (id == CSSValueTop || id == CSSValueBottom || id == CSSValueCenter) {
@@ -3653,7 +3586,7 @@
     return 0;
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSParser::parseFillPositionComponent(CSSParserValueList* valueList, unsigned& cumulativeFlags, FillPositionFlag& individualFlag, FillPositionParsingMode parsingMode)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> BisonCSSParser::parseFillPositionComponent(CSSParserValueList* valueList, unsigned& cumulativeFlags, FillPositionFlag& individualFlag, FillPositionParsingMode parsingMode)
 {
     CSSValueID id = valueList->current()->id;
     if (id == CSSValueLeft || id == CSSValueTop || id == CSSValueRight || id == CSSValueBottom || id == CSSValueCenter) {
@@ -3718,7 +3651,7 @@
     return value == CSSValueLeft || value == CSSValueTop || value == CSSValueBottom || value == CSSValueRight || value == CSSValueCenter;
 }
 
-void CSSParser::parse4ValuesFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2, PassRefPtr<CSSPrimitiveValue> parsedValue1, PassRefPtr<CSSPrimitiveValue> parsedValue2)
+void BisonCSSParser::parse4ValuesFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue1, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue2)
 {
     // [ left | right ] [ <percentage] | <length> ] && [ top | bottom ] [ <percentage> | <length> ]
     // In the case of 4 values <position> requires the second value to be a length or a percentage.
@@ -3727,7 +3660,7 @@
 
     unsigned cumulativeFlags = 0;
     FillPositionFlag value3Flag = InvalidFillPosition;
-    RefPtr<CSSPrimitiveValue> value3 = parseFillPositionComponent(valueList, cumulativeFlags, value3Flag, ResolveValuesAsKeyword);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> value3 = parseFillPositionComponent(valueList, cumulativeFlags, value3Flag, ResolveValuesAsKeyword);
     if (!value3)
         return;
 
@@ -3750,7 +3683,7 @@
 
     cumulativeFlags = 0;
     FillPositionFlag value4Flag = InvalidFillPosition;
-    RefPtr<CSSPrimitiveValue> value4 = parseFillPositionComponent(valueList, cumulativeFlags, value4Flag, ResolveValuesAsKeyword);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> value4 = parseFillPositionComponent(valueList, cumulativeFlags, value4Flag, ResolveValuesAsKeyword);
     if (!value4)
         return;
 
@@ -3766,11 +3699,11 @@
 
     valueList->next();
 }
-void CSSParser::parse3ValuesFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2, PassRefPtr<CSSPrimitiveValue> parsedValue1, PassRefPtr<CSSPrimitiveValue> parsedValue2)
+void BisonCSSParser::parse3ValuesFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue1, PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue2)
 {
     unsigned cumulativeFlags = 0;
     FillPositionFlag value3Flag = InvalidFillPosition;
-    RefPtr<CSSPrimitiveValue> value3 = parseFillPositionComponent(valueList, cumulativeFlags, value3Flag, ResolveValuesAsKeyword);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> value3 = parseFillPositionComponent(valueList, cumulativeFlags, value3Flag, ResolveValuesAsKeyword);
 
     // value3 is not an expected value, we return.
     if (!value3)
@@ -3814,8 +3747,8 @@
         value1 = createPrimitiveValuePair(parsedValue1, parsedValue2);
         value2 = createPrimitiveValuePair(cssValuePool().createIdentifierValue(secondPositionKeyword), cssValuePool().createValue(50, CSSPrimitiveValue::CSS_PERCENTAGE));
     } else {
-        RefPtr<CSSPrimitiveValue> firstPositionValue;
-        RefPtr<CSSPrimitiveValue> secondPositionValue;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> firstPositionValue;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> secondPositionValue;
 
         if (isFillPositionKeyword(ident2)) {
             // To match CSS grammar, we should only accept: [ center | left | right | bottom | top ] [ left | right | top | bottom ] [ <percentage> | <length> ].
@@ -3857,12 +3790,12 @@
 #endif
 }
 
-inline bool CSSParser::isPotentialPositionValue(CSSParserValue* value)
+inline bool BisonCSSParser::isPotentialPositionValue(CSSParserValue* value)
 {
     return isFillPositionKeyword(value->id) || validUnit(value, FPercent | FLength, ReleaseParsedCalcValue);
 }
 
-void CSSParser::parseFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2)
+void BisonCSSParser::parseFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2)
 {
     unsigned numberOfValues = 0;
     for (unsigned i = valueList->currentIndex(); i < valueList->size(); ++i, ++numberOfValues) {
@@ -3896,7 +3829,7 @@
     if (!value1)
         return;
 
-    value = valueList->next();
+    valueList->next();
 
     // In case we are parsing more than two values, relax the check inside of parseFillPositionComponent. top 20px is
     // a valid start for <position>.
@@ -3909,8 +3842,8 @@
         return;
     }
 
-    RefPtr<CSSPrimitiveValue> parsedValue1 = toCSSPrimitiveValue(value1.get());
-    RefPtr<CSSPrimitiveValue> parsedValue2 = toCSSPrimitiveValue(value2.get());
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue1 = toCSSPrimitiveValue(value1.get());
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue2 = toCSSPrimitiveValue(value2.get());
 
     value1.clear();
     value2.clear();
@@ -3925,7 +3858,7 @@
         parse4ValuesFillPosition(valueList, value1, value2, parsedValue1.release(), parsedValue2.release());
 }
 
-void CSSParser::parse2ValuesFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2)
+void BisonCSSParser::parse2ValuesFillPosition(CSSParserValueList* valueList, RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2)
 {
     CSSParserValue* value = valueList->current();
 
@@ -3969,7 +3902,7 @@
         value1.swap(value2);
 }
 
-void CSSParser::parseFillRepeat(RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2)
+void BisonCSSParser::parseFillRepeat(RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2)
 {
     CSSValueID id = m_valueList->current()->id;
     if (id == CSSValueRepeatX) {
@@ -4010,7 +3943,7 @@
     value2 = cssValuePool().createIdentifierValue(toCSSPrimitiveValue(value1.get())->getValueID());
 }
 
-PassRefPtr<CSSValue> CSSParser::parseFillSize(CSSPropertyID propId, bool& allowComma)
+PassRefPtr<CSSValue> BisonCSSParser::parseFillSize(CSSPropertyID propId, bool& allowComma)
 {
     allowComma = true;
     CSSParserValue* value = m_valueList->current();
@@ -4018,7 +3951,7 @@
     if (value->id == CSSValueContain || value->id == CSSValueCover)
         return cssValuePool().createIdentifierValue(value->id);
 
-    RefPtr<CSSPrimitiveValue> parsedValue1;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue1;
 
     if (value->id == CSSValueAuto)
         parsedValue1 = cssValuePool().createIdentifierValue(CSSValueAuto);
@@ -4028,7 +3961,7 @@
         parsedValue1 = createPrimitiveNumericValue(value);
     }
 
-    RefPtr<CSSPrimitiveValue> parsedValue2;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue2;
     if ((value = m_valueList->next())) {
         if (value->unit == CSSParserValue::Operator && value->iValue == ',')
             allowComma = false;
@@ -4053,11 +3986,11 @@
     return createPrimitiveValuePair(parsedValue1.release(), parsedValue2.release());
 }
 
-bool CSSParser::parseFillProperty(CSSPropertyID propId, CSSPropertyID& propId1, CSSPropertyID& propId2,
+bool BisonCSSParser::parseFillProperty(CSSPropertyID propId, CSSPropertyID& propId1, CSSPropertyID& propId2,
                                   RefPtr<CSSValue>& retValue1, RefPtr<CSSValue>& retValue2)
 {
-    RefPtr<CSSValueList> values;
-    RefPtr<CSSValueList> values2;
+    RefPtrWillBeRawPtr<CSSValueList> values;
+    RefPtrWillBeRawPtr<CSSValueList> values2;
     CSSParserValue* val;
     RefPtr<CSSValue> value;
     RefPtr<CSSValue> value2;
@@ -4242,7 +4175,7 @@
     return false;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAnimationDelay()
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationDelay()
 {
     CSSParserValue* value = m_valueList->current();
     if (validUnit(value, FTime))
@@ -4250,7 +4183,7 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAnimationDirection()
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationDirection()
 {
     CSSParserValue* value = m_valueList->current();
     if (value->id == CSSValueNormal || value->id == CSSValueAlternate || value->id == CSSValueReverse || value->id == CSSValueAlternateReverse)
@@ -4258,7 +4191,7 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAnimationDuration()
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationDuration()
 {
     CSSParserValue* value = m_valueList->current();
     if (validUnit(value, FTime | FNonNeg))
@@ -4266,7 +4199,7 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAnimationFillMode()
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationFillMode()
 {
     CSSParserValue* value = m_valueList->current();
     if (value->id == CSSValueNone || value->id == CSSValueForwards || value->id == CSSValueBackwards || value->id == CSSValueBoth)
@@ -4274,7 +4207,7 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAnimationIterationCount()
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationIterationCount()
 {
     CSSParserValue* value = m_valueList->current();
     if (value->id == CSSValueInfinite)
@@ -4284,7 +4217,7 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAnimationName()
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationName()
 {
     CSSParserValue* value = m_valueList->current();
     if (value->unit == CSSPrimitiveValue::CSS_STRING || value->unit == CSSPrimitiveValue::CSS_IDENT) {
@@ -4297,7 +4230,7 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAnimationPlayState()
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationPlayState()
 {
     CSSParserValue* value = m_valueList->current();
     if (value->id == CSSValueRunning || value->id == CSSValuePaused)
@@ -4305,7 +4238,7 @@
     return 0;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAnimationProperty(AnimationParseContext& context)
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationProperty(AnimationParseContext& context)
 {
     CSSParserValue* value = m_valueList->current();
     if (value->unit != CSSPrimitiveValue::CSS_IDENT)
@@ -4325,7 +4258,7 @@
     return 0;
 }
 
-bool CSSParser::parseTransformOriginShorthand(RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2, RefPtr<CSSValue>& value3)
+bool BisonCSSParser::parseTransformOriginShorthand(RefPtr<CSSValue>& value1, RefPtr<CSSValue>& value2, RefPtr<CSSValue>& value3)
 {
     parse2ValuesFillPosition(m_valueList.get(), value1, value2);
 
@@ -4342,7 +4275,7 @@
     return true;
 }
 
-bool CSSParser::parseCubicBezierTimingFunctionValue(CSSParserValueList*& args, double& result)
+bool BisonCSSParser::parseCubicBezierTimingFunctionValue(CSSParserValueList*& args, double& result)
 {
     CSSParserValue* v = args->current();
     if (!validUnit(v, FNumber))
@@ -4358,7 +4291,7 @@
     return true;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseAnimationTimingFunction()
+PassRefPtr<CSSValue> BisonCSSParser::parseAnimationTimingFunction()
 {
     CSSParserValue* value = m_valueList->current();
     if (value->id == CSSValueEase || value->id == CSSValueLinear || value->id == CSSValueEaseIn || value->id == CSSValueEaseOut
@@ -4428,9 +4361,9 @@
     return 0;
 }
 
-bool CSSParser::parseAnimationProperty(CSSPropertyID propId, RefPtr<CSSValue>& result, AnimationParseContext& context)
+bool BisonCSSParser::parseAnimationProperty(CSSPropertyID propId, RefPtr<CSSValue>& result, AnimationParseContext& context)
 {
-    RefPtr<CSSValueList> values;
+    RefPtrWillBeRawPtr<CSSValueList> values;
     CSSParserValue* val;
     RefPtr<CSSValue> value;
     bool allowComma = false;
@@ -4548,7 +4481,7 @@
 }
 
 // The function parses [ <integer> || <string> ] in <grid-line> (which can be stand alone or with 'span').
-bool CSSParser::parseIntegerOrStringFromGridPosition(RefPtr<CSSPrimitiveValue>& numericValue, RefPtr<CSSPrimitiveValue>& gridLineName)
+bool BisonCSSParser::parseIntegerOrStringFromGridPosition(RefPtrWillBeRawPtr<CSSPrimitiveValue>& numericValue, RefPtrWillBeRawPtr<CSSPrimitiveValue>& gridLineName)
 {
     CSSParserValue* value = m_valueList->current();
     if (validUnit(value, FInteger) && value->fValue) {
@@ -4574,7 +4507,7 @@
     return false;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseGridPosition()
+PassRefPtr<CSSValue> BisonCSSParser::parseGridPosition()
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
 
@@ -4589,8 +4522,8 @@
         return cssValuePool().createValue(value->string, CSSPrimitiveValue::CSS_STRING);
     }
 
-    RefPtr<CSSPrimitiveValue> numericValue;
-    RefPtr<CSSPrimitiveValue> gridLineName;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> numericValue;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> gridLineName;
     bool hasSeenSpanKeyword = false;
 
     if (parseIntegerOrStringFromGridPosition(numericValue, gridLineName)) {
@@ -4618,7 +4551,7 @@
     if (hasSeenSpanKeyword && numericValue && numericValue->getIntValue() < 0)
         return 0;
 
-    RefPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
     if (hasSeenSpanKeyword)
         values->append(cssValuePool().createIdentifierValue(CSSValueSpan));
     if (numericValue)
@@ -4637,7 +4570,7 @@
     return cssValuePool().createIdentifierValue(CSSValueAuto);
 }
 
-bool CSSParser::parseGridItemPositionShorthand(CSSPropertyID shorthandId, bool important)
+bool BisonCSSParser::parseGridItemPositionShorthand(CSSPropertyID shorthandId, bool important)
 {
     ShorthandScope scope(this, shorthandId);
     const StylePropertyShorthand& shorthand = shorthandForProperty(shorthandId);
@@ -4667,7 +4600,7 @@
     return true;
 }
 
-bool CSSParser::parseGridAreaShorthand(bool important)
+bool BisonCSSParser::parseGridAreaShorthand(bool important)
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
 
@@ -4707,7 +4640,7 @@
     return true;
 }
 
-bool CSSParser::parseSingleGridAreaLonghand(RefPtr<CSSValue>& property)
+bool BisonCSSParser::parseSingleGridAreaLonghand(RefPtr<CSSValue>& property)
 {
     if (!m_valueList->current())
         return true;
@@ -4722,7 +4655,7 @@
     return true;
 }
 
-void CSSParser::parseGridLineNames(CSSParserValueList* parserValueList, CSSValueList& valueList)
+void BisonCSSParser::parseGridLineNames(CSSParserValueList* parserValueList, CSSValueList& valueList)
 {
     ASSERT(parserValueList->current() && parserValueList->current()->unit == CSSParserValue::ValueList);
 
@@ -4732,10 +4665,10 @@
         return;
     }
 
-    RefPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
+    RefPtrWillBeRawPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
     while (CSSParserValue* identValue = identList->current()) {
         ASSERT(identValue->unit == CSSPrimitiveValue::CSS_IDENT);
-        RefPtr<CSSPrimitiveValue> lineName = createPrimitiveStringValue(identValue);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> lineName = createPrimitiveStringValue(identValue);
         lineNames->append(lineName.release());
         identList->next();
     }
@@ -4744,7 +4677,7 @@
     parserValueList->next();
 }
 
-bool CSSParser::parseGridTrackList(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseGridTrackList(CSSPropertyID propId, bool important)
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
 
@@ -4757,7 +4690,7 @@
         return true;
     }
 
-    RefPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
     // Handle leading  <ident>*.
     value = m_valueList->current();
     if (value && value->unit == CSSParserValue::ValueList)
@@ -4790,7 +4723,7 @@
     return true;
 }
 
-bool CSSParser::parseGridTrackRepeatFunction(CSSValueList& list)
+bool BisonCSSParser::parseGridTrackRepeatFunction(CSSValueList& list)
 {
     CSSParserValueList* arguments = m_valueList->current()->function->args.get();
     if (!arguments || arguments->size() < 3 || !validUnit(arguments->valueAt(0), FPositiveInteger) || !isComma(arguments->valueAt(1)))
@@ -4798,7 +4731,7 @@
 
     ASSERT_WITH_SECURITY_IMPLICATION(arguments->valueAt(0)->fValue > 0);
     size_t repetitions = arguments->valueAt(0)->fValue;
-    RefPtr<CSSValueList> repeatedValues = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> repeatedValues = CSSValueList::createSpaceSeparated();
     arguments->next(); // Skip the repetition count.
     arguments->next(); // Skip the comma.
 
@@ -4830,7 +4763,7 @@
     return true;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseGridTrackSize(CSSParserValueList& inputList)
+PassRefPtr<CSSValue> BisonCSSParser::parseGridTrackSize(CSSParserValueList& inputList)
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
 
@@ -4846,15 +4779,15 @@
         if (!arguments || arguments->size() != 3 || !isComma(arguments->valueAt(1)))
             return 0;
 
-        RefPtr<CSSPrimitiveValue> minTrackBreadth = parseGridBreadth(arguments->valueAt(0));
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> minTrackBreadth = parseGridBreadth(arguments->valueAt(0));
         if (!minTrackBreadth)
             return 0;
 
-        RefPtr<CSSPrimitiveValue> maxTrackBreadth = parseGridBreadth(arguments->valueAt(2));
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> maxTrackBreadth = parseGridBreadth(arguments->valueAt(2));
         if (!maxTrackBreadth)
             return 0;
 
-        RefPtr<CSSValueList> parsedArguments = CSSValueList::createCommaSeparated();
+        RefPtrWillBeRawPtr<CSSValueList> parsedArguments = CSSValueList::createCommaSeparated();
         parsedArguments->append(minTrackBreadth);
         parsedArguments->append(maxTrackBreadth);
         return CSSFunctionValue::create("minmax(", parsedArguments);
@@ -4863,7 +4796,7 @@
     return parseGridBreadth(currentValue);
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSParser::parseGridBreadth(CSSParserValue* currentValue)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> BisonCSSParser::parseGridBreadth(CSSParserValue* currentValue)
 {
     if (currentValue->id == CSSValueMinContent || currentValue->id == CSSValueMaxContent)
         return cssValuePool().createIdentifierValue(currentValue->id);
@@ -4884,7 +4817,7 @@
     return createPrimitiveNumericValue(currentValue);
 }
 
-PassRefPtr<CSSValue> CSSParser::parseGridTemplate()
+PassRefPtr<CSSValue> BisonCSSParser::parseGridTemplateAreas()
 {
     NamedGridAreaMap gridAreaMap;
     size_t rowCount = 0;
@@ -4954,10 +4887,10 @@
     if (!rowCount || !columnCount)
         return 0;
 
-    return CSSGridTemplateValue::create(gridAreaMap, rowCount, columnCount);
+    return CSSGridTemplateAreasValue::create(gridAreaMap, rowCount, columnCount);
 }
 
-PassRefPtr<CSSValue> CSSParser::parseCounterContent(CSSParserValueList* args, bool counters)
+PassRefPtr<CSSValue> BisonCSSParser::parseCounterContent(CSSParserValueList* args, bool counters)
 {
     unsigned numArgs = args->size();
     if (counters && numArgs != 3 && numArgs != 5)
@@ -4968,9 +4901,9 @@
     CSSParserValue* i = args->current();
     if (i->unit != CSSPrimitiveValue::CSS_IDENT)
         return 0;
-    RefPtr<CSSPrimitiveValue> identifier = createPrimitiveStringValue(i);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> identifier = createPrimitiveStringValue(i);
 
-    RefPtr<CSSPrimitiveValue> separator;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> separator;
     if (!counters)
         separator = cssValuePool().createValue(String(), CSSPrimitiveValue::CSS_STRING);
     else {
@@ -4985,7 +4918,7 @@
         separator = createPrimitiveStringValue(i);
     }
 
-    RefPtr<CSSPrimitiveValue> listStyle;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> listStyle;
     i = args->next();
     if (!i) // Make the list style default decimal
         listStyle = cssValuePool().createIdentifierValue(CSSValueDecimal);
@@ -5009,7 +4942,7 @@
     return cssValuePool().createValue(Counter::create(identifier.release(), listStyle.release(), separator.release()));
 }
 
-bool CSSParser::parseClipShape(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseClipShape(CSSPropertyID propId, bool important)
 {
     CSSParserValue* value = m_valueList->current();
     CSSParserValueList* args = value->function->args.get();
@@ -5028,7 +4961,7 @@
         valid = a->id == CSSValueAuto || validUnit(a, FLength);
         if (!valid)
             break;
-        RefPtr<CSSPrimitiveValue> length = a->id == CSSValueAuto ?
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> length = a->id == CSSValueAuto ?
             cssValuePool().createIdentifierValue(CSSValueAuto) :
             createPrimitiveNumericValue(a);
         if (i == 0)
@@ -5058,7 +4991,194 @@
     return false;
 }
 
-PassRefPtr<CSSBasicShape> CSSParser::parseBasicShapeRectangle(CSSParserValueList* args)
+static void completeBorderRadii(RefPtrWillBeRawPtr<CSSPrimitiveValue> radii[4])
+{
+    if (radii[3])
+        return;
+    if (!radii[2]) {
+        if (!radii[1])
+            radii[1] = radii[0];
+        radii[2] = radii[0];
+    }
+    radii[3] = radii[1];
+}
+
+// FIXME: This should be refactored with CSSParser::parseBorderRadius.
+// CSSParser::parseBorderRadius contains support for some legacy radius construction.
+PassRefPtr<CSSBasicShape> BisonCSSParser::parseInsetRoundedCorners(PassRefPtr<CSSBasicShapeInset> shape, CSSParserValueList* args)
+{
+    CSSParserValue* argument = args->next();
+
+    if (!argument)
+        return 0;
+
+    CSSParserValueList radiusArguments;
+    while (argument) {
+        radiusArguments.addValue(*argument);
+        argument = args->next();
+    }
+
+    unsigned num = radiusArguments.size();
+    if (!num || num > 9)
+        return 0;
+
+    // FIXME: Refactor completeBorderRadii and the array
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> radii[2][4];
+
+    unsigned indexAfterSlash = 0;
+    for (unsigned i = 0; i < num; ++i) {
+        CSSParserValue* value = radiusArguments.valueAt(i);
+        if (value->unit == CSSParserValue::Operator) {
+            if (value->iValue != '/')
+                return 0;
+
+            if (!i || indexAfterSlash || i + 1 == num)
+                return 0;
+
+            indexAfterSlash = i + 1;
+            completeBorderRadii(radii[0]);
+            continue;
+        }
+
+        if (i - indexAfterSlash >= 4)
+            return 0;
+
+        if (!validUnit(value, FLength | FPercent | FNonNeg))
+            return 0;
+
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> radius = createPrimitiveNumericValue(value);
+
+        if (!indexAfterSlash)
+            radii[0][i] = radius;
+        else
+            radii[1][i - indexAfterSlash] = radius.release();
+    }
+
+    if (!indexAfterSlash) {
+        completeBorderRadii(radii[0]);
+        for (unsigned i = 0; i < 4; ++i)
+            radii[1][i] = radii[0][i];
+    } else {
+        completeBorderRadii(radii[1]);
+    }
+    shape->setTopLeftRadius(createPrimitiveValuePair(radii[0][0].release(), radii[1][0].release()));
+    shape->setTopRightRadius(createPrimitiveValuePair(radii[0][1].release(), radii[1][1].release()));
+    shape->setBottomRightRadius(createPrimitiveValuePair(radii[0][2].release(), radii[1][2].release()));
+    shape->setBottomLeftRadius(createPrimitiveValuePair(radii[0][3].release(), radii[1][3].release()));
+
+    return shape;
+}
+
+PassRefPtr<CSSBasicShape> BisonCSSParser::parseBasicShapeInset(CSSParserValueList* args)
+{
+    ASSERT(args);
+
+    RefPtr<CSSBasicShapeInset> shape = CSSBasicShapeInset::create();
+
+    CSSParserValue* argument = args->current();
+    WillBeHeapVector<RefPtrWillBeMember<CSSPrimitiveValue> > widthArguments;
+    bool hasRoundedInset = false;
+
+    while (argument) {
+        if (argument->unit == CSSPrimitiveValue::CSS_IDENT && equalIgnoringCase(argument->string, "round")) {
+            hasRoundedInset = true;
+            break;
+        }
+
+        Units unitFlags = FLength | FPercent;
+        if (!validUnit(argument, unitFlags) || widthArguments.size() > 4)
+            return 0;
+
+        widthArguments.append(createPrimitiveNumericValue(argument));
+        argument = args->next();
+    }
+
+    switch (widthArguments.size()) {
+    case 1: {
+        shape->updateShapeSize1Value(widthArguments[0].get());
+        break;
+    }
+    case 2: {
+        shape->updateShapeSize2Values(widthArguments[0].get(), widthArguments[1].get());
+        break;
+        }
+    case 3: {
+        shape->updateShapeSize3Values(widthArguments[0].get(), widthArguments[1].get(), widthArguments[2].get());
+        break;
+    }
+    case 4: {
+        shape->updateShapeSize4Values(widthArguments[0].get(), widthArguments[1].get(), widthArguments[2].get(), widthArguments[3].get());
+        break;
+    }
+    default:
+        return 0;
+    }
+
+    if (hasRoundedInset)
+        return parseInsetRoundedCorners(shape, args);
+    return shape;
+}
+
+static bool isItemPositionKeyword(CSSValueID id)
+{
+    return id == CSSValueStart || id == CSSValueEnd || id == CSSValueCenter
+        || id == CSSValueSelfStart || id == CSSValueSelfEnd || id == CSSValueFlexStart
+        || id == CSSValueFlexEnd || id == CSSValueLeft || id == CSSValueRight;
+}
+
+bool BisonCSSParser::parseItemPositionOverflowPosition(CSSPropertyID propId, bool important)
+{
+    // auto | baseline | stretch | [<item-position> && <overflow-position>? ]
+    // <item-position> = center | start | end | self-start | self-end | flex-start | flex-end | left | right;
+    // <overflow-position> = true | safe
+
+    CSSParserValue* value = m_valueList->current();
+
+    if (value->id == CSSValueAuto || value->id == CSSValueBaseline || value->id == CSSValueStretch) {
+        if (m_valueList->next())
+            return false;
+
+        addProperty(propId, cssValuePool().createIdentifierValue(value->id), important);
+        return true;
+    }
+
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> position = 0;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> overflowAlignmentKeyword = 0;
+    if (isItemPositionKeyword(value->id)) {
+        position = cssValuePool().createIdentifierValue(value->id);
+        value = m_valueList->next();
+        if (value) {
+            if (value->id == CSSValueTrue || value->id == CSSValueSafe)
+                overflowAlignmentKeyword = cssValuePool().createIdentifierValue(value->id);
+            else
+                return false;
+        }
+    } else if (value->id == CSSValueTrue || value->id == CSSValueSafe) {
+        overflowAlignmentKeyword = cssValuePool().createIdentifierValue(value->id);
+        value = m_valueList->next();
+        if (value) {
+            if (isItemPositionKeyword(value->id))
+                position = cssValuePool().createIdentifierValue(value->id);
+            else
+                return false;
+        }
+    } else {
+        return false;
+    }
+
+    if (m_valueList->next())
+        return false;
+
+    ASSERT(position);
+    if (overflowAlignmentKeyword)
+        addProperty(propId, createPrimitiveValuePair(position, overflowAlignmentKeyword), important);
+    else
+        addProperty(propId, position.release(), important);
+
+    return true;
+}
+
+PassRefPtr<CSSBasicShape> BisonCSSParser::parseBasicShapeRectangle(CSSParserValueList* args)
 {
     ASSERT(args);
 
@@ -5079,7 +5199,7 @@
         if (!validUnit(argument, unitFlags))
             return 0;
 
-        RefPtr<CSSPrimitiveValue> length = createPrimitiveNumericValue(argument);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> length = createPrimitiveNumericValue(argument);
         ASSERT(argumentNumber < 6);
         switch (argumentNumber) {
         case 0:
@@ -5116,7 +5236,7 @@
     return shape;
 }
 
-PassRefPtr<CSSBasicShape> CSSParser::parseBasicShapeInsetRectangle(CSSParserValueList* args)
+PassRefPtr<CSSBasicShape> BisonCSSParser::parseBasicShapeInsetRectangle(CSSParserValueList* args)
 {
     ASSERT(args);
 
@@ -5133,7 +5253,7 @@
         if (!validUnit(argument, unitFlags))
             return 0;
 
-        RefPtr<CSSPrimitiveValue> length = createPrimitiveNumericValue(argument);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> length = createPrimitiveNumericValue(argument);
         ASSERT(argumentNumber < 6);
         switch (argumentNumber) {
         case 0:
@@ -5170,7 +5290,65 @@
     return shape;
 }
 
-PassRefPtr<CSSBasicShape> CSSParser::parseBasicShapeCircle(CSSParserValueList* args)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> BisonCSSParser::parseShapeRadius(CSSParserValue* value)
+{
+    if (value->id == CSSValueClosestSide || value->id == CSSValueFarthestSide)
+        return cssValuePool().createIdentifierValue(value->id);
+
+    if (!validUnit(value, FLength | FPercent | FNonNeg))
+        return 0;
+
+    return createPrimitiveNumericValue(value);
+}
+
+PassRefPtr<CSSBasicShape> BisonCSSParser::parseBasicShapeCircle(CSSParserValueList* args)
+{
+    ASSERT(args);
+
+    // circle(radius)
+    // circle(radius at <position>
+    // circle(at <position>)
+    // where position defines centerX and centerY using a CSS <position> data type.
+    RefPtr<CSSBasicShapeCircle> shape = CSSBasicShapeCircle::create();
+
+    for (CSSParserValue* argument = args->current(); argument; argument = args->next()) {
+        // The call to parseFillPosition below should consume all of the
+        // arguments except the first two. Thus, and index greater than one
+        // indicates an invalid production.
+        if (args->currentIndex() > 1)
+            return 0;
+
+        if (!args->currentIndex() && argument->id != CSSValueAt) {
+            if (RefPtrWillBeRawPtr<CSSPrimitiveValue> radius = parseShapeRadius(argument)) {
+                shape->setRadius(radius);
+                continue;
+            }
+
+            return 0;
+        }
+
+        if (argument->id == CSSValueAt) {
+            RefPtr<CSSValue> centerX;
+            RefPtr<CSSValue> centerY;
+            args->next(); // set list to start of position center
+            parseFillPosition(args, centerX, centerY);
+            if (centerX && centerY) {
+                ASSERT(centerX->isPrimitiveValue());
+                ASSERT(centerY->isPrimitiveValue());
+                shape->setCenterX(toCSSPrimitiveValue(centerX.get()));
+                shape->setCenterY(toCSSPrimitiveValue(centerY.get()));
+            } else {
+                return 0;
+            }
+        } else {
+            return 0;
+        }
+    }
+
+    return shape;
+}
+
+PassRefPtr<CSSBasicShape> BisonCSSParser::parseDeprecatedBasicShapeCircle(CSSParserValueList* args)
 {
     ASSERT(args);
 
@@ -5178,7 +5356,7 @@
     if (args->size() != 5)
         return 0;
 
-    RefPtr<CSSBasicShapeCircle> shape = CSSBasicShapeCircle::create();
+    RefPtr<CSSDeprecatedBasicShapeCircle> shape = CSSDeprecatedBasicShapeCircle::create();
 
     unsigned argumentNumber = 0;
     CSSParserValue* argument = args->current();
@@ -5192,7 +5370,7 @@
         if (!validUnit(argument, unitFlags))
             return 0;
 
-        RefPtr<CSSPrimitiveValue> length = createPrimitiveNumericValue(argument);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> length = createPrimitiveNumericValue(argument);
         ASSERT(argumentNumber < 3);
         switch (argumentNumber) {
         case 0:
@@ -5220,7 +5398,56 @@
     return shape;
 }
 
-PassRefPtr<CSSBasicShape> CSSParser::parseBasicShapeEllipse(CSSParserValueList* args)
+PassRefPtr<CSSBasicShape> BisonCSSParser::parseBasicShapeEllipse(CSSParserValueList* args)
+{
+    ASSERT(args);
+
+    // ellipse(radiusX)
+    // ellipse(radiusX at <position>
+    // ellipse(radiusX radiusY)
+    // ellipse(radiusX radiusY at <position>
+    // ellipse(at <position>)
+    // where position defines centerX and centerY using a CSS <position> data type.
+    RefPtr<CSSBasicShapeEllipse> shape = CSSBasicShapeEllipse::create();
+
+    for (CSSParserValue* argument = args->current(); argument; argument = args->next()) {
+        // The call to parseFillPosition below should consume all of the
+        // arguments except the first three. Thus, an index greater than two
+        // indicates an invalid production.
+        if (args->currentIndex() > 2)
+            return 0;
+
+        if (args->currentIndex() < 2 && argument->id != CSSValueAt) {
+            if (RefPtrWillBeRawPtr<CSSPrimitiveValue> radius = parseShapeRadius(argument)) {
+                if (!shape->radiusX())
+                    shape->setRadiusX(radius);
+                else
+                    shape->setRadiusY(radius);
+                continue;
+            }
+
+            return 0;
+        }
+
+        if (argument->id != CSSValueAt)
+            return 0;
+        RefPtr<CSSValue> centerX;
+        RefPtr<CSSValue> centerY;
+        args->next(); // set list to start of position center
+        parseFillPosition(args, centerX, centerY);
+        if (!centerX || !centerY)
+            return 0;
+
+        ASSERT(centerX->isPrimitiveValue());
+        ASSERT(centerY->isPrimitiveValue());
+        shape->setCenterX(toCSSPrimitiveValue(centerX.get()));
+        shape->setCenterY(toCSSPrimitiveValue(centerY.get()));
+    }
+
+    return shape;
+}
+
+PassRefPtr<CSSBasicShape> BisonCSSParser::parseDeprecatedBasicShapeEllipse(CSSParserValueList* args)
 {
     ASSERT(args);
 
@@ -5228,7 +5455,7 @@
     if (args->size() != 7)
         return 0;
 
-    RefPtr<CSSBasicShapeEllipse> shape = CSSBasicShapeEllipse::create();
+    RefPtr<CSSDeprecatedBasicShapeEllipse> shape = CSSDeprecatedBasicShapeEllipse::create();
     unsigned argumentNumber = 0;
     CSSParserValue* argument = args->current();
     while (argument) {
@@ -5240,7 +5467,7 @@
         if (!validUnit(argument, unitFlags))
             return 0;
 
-        RefPtr<CSSPrimitiveValue> length = createPrimitiveNumericValue(argument);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> length = createPrimitiveNumericValue(argument);
         ASSERT(argumentNumber < 4);
         switch (argumentNumber) {
         case 0:
@@ -5271,7 +5498,7 @@
     return shape;
 }
 
-PassRefPtr<CSSBasicShape> CSSParser::parseBasicShapePolygon(CSSParserValueList* args)
+PassRefPtr<CSSBasicShape> BisonCSSParser::parseBasicShapePolygon(CSSParserValueList* args)
 {
     ASSERT(args);
 
@@ -5305,8 +5532,8 @@
         if (!argumentY || !validUnit(argumentY, FLength | FPercent))
             return 0;
 
-        RefPtr<CSSPrimitiveValue> xLength = createPrimitiveNumericValue(argumentX);
-        RefPtr<CSSPrimitiveValue> yLength = createPrimitiveNumericValue(argumentY);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> xLength = createPrimitiveNumericValue(argumentX);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> yLength = createPrimitiveNumericValue(argumentY);
 
         shape->appendPoint(xLength.release(), yLength.release());
 
@@ -5322,37 +5549,132 @@
     return shape;
 }
 
-bool CSSParser::parseBasicShape(CSSPropertyID propId, bool important)
+static bool isBoxValue(CSSValueID valueId)
+{
+    switch (valueId) {
+    case CSSValueContentBox:
+    case CSSValuePaddingBox:
+    case CSSValueBorderBox:
+    case CSSValueMarginBox:
+        return true;
+    default:
+        break;
+    }
+
+    return false;
+}
+
+// FIXME This function is temporary to allow for an orderly transition between
+// the new CSS Shapes circle and ellipse syntax. It will be removed when the
+// old syntax is removed.
+static bool isDeprecatedBasicShape(CSSParserValueList* args)
+{
+    for (unsigned i = args->currentIndex(); i < args->size(); ++i) {
+        CSSParserValue* value = args->valueAt(i);
+        if (isComma(value))
+            return true;
+    }
+
+    return false;
+}
+
+PassRefPtr<CSSValue> BisonCSSParser::parseShapeProperty(CSSPropertyID propId)
+{
+    if (!RuntimeEnabledFeatures::cssShapesEnabled())
+        return 0;
+
+    CSSParserValue* value = m_valueList->current();
+    CSSValueID valueId = value->id;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> boxValue;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> shapeValue;
+
+    if (valueId == CSSValueNone
+        || (valueId == CSSValueOutsideShape && propId == CSSPropertyShapeInside)) {
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> keywordValue = parseValidPrimitive(valueId, value);
+        m_valueList->next();
+        return keywordValue.release();
+    }
+
+    RefPtr<CSSValue> imageValue;
+    if (valueId != CSSValueNone && parseFillImage(m_valueList.get(), imageValue)) {
+        m_valueList->next();
+        return imageValue.release();
+    }
+
+    if (value->unit == CSSParserValue::Function) {
+        shapeValue = parseBasicShape();
+        if (!shapeValue)
+            return 0;
+    } else if (isBoxValue(valueId)) {
+        boxValue = parseValidPrimitive(valueId, value);
+        m_valueList->next();
+    } else {
+        return 0;
+    }
+
+    ASSERT(shapeValue || boxValue);
+    value = m_valueList->current();
+
+    if (value) {
+        valueId = value->id;
+        if (boxValue && value->unit == CSSParserValue::Function) {
+            shapeValue = parseBasicShape();
+            if (!shapeValue)
+                return 0;
+        } else if (shapeValue && isBoxValue(valueId)) {
+            boxValue = parseValidPrimitive(valueId, value);
+            m_valueList->next();
+        } else {
+            return 0;
+        }
+
+        ASSERT(shapeValue && boxValue);
+        shapeValue->getShapeValue()->setLayoutBox(boxValue.release());
+    }
+
+    if (shapeValue)
+        return shapeValue.release();
+    return boxValue.release();
+}
+
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> BisonCSSParser::parseBasicShape()
 {
     CSSParserValue* value = m_valueList->current();
     ASSERT(value->unit == CSSParserValue::Function);
     CSSParserValueList* args = value->function->args.get();
 
     if (!args)
-        return false;
+        return 0;
 
     RefPtr<CSSBasicShape> shape;
     if (equalIgnoringCase(value->function->name, "rectangle("))
         shape = parseBasicShapeRectangle(args);
     else if (equalIgnoringCase(value->function->name, "circle("))
-        shape = parseBasicShapeCircle(args);
+        if (isDeprecatedBasicShape(args))
+            shape = parseDeprecatedBasicShapeCircle(args);
+        else
+            shape = parseBasicShapeCircle(args);
     else if (equalIgnoringCase(value->function->name, "ellipse("))
-        shape = parseBasicShapeEllipse(args);
+        if (isDeprecatedBasicShape(args))
+            shape = parseDeprecatedBasicShapeEllipse(args);
+        else
+            shape = parseBasicShapeEllipse(args);
     else if (equalIgnoringCase(value->function->name, "polygon("))
         shape = parseBasicShapePolygon(args);
     else if (equalIgnoringCase(value->function->name, "inset-rectangle("))
         shape = parseBasicShapeInsetRectangle(args);
+    else if (equalIgnoringCase(value->function->name, "inset("))
+        shape = parseBasicShapeInset(args);
 
     if (!shape)
-        return false;
+        return 0;
 
-    addProperty(propId, cssValuePool().createValue(shape.release()), important);
     m_valueList->next();
-    return true;
+    return cssValuePool().createValue(shape.release());
 }
 
 // [ 'font-style' || 'font-variant' || 'font-weight' ]? 'font-size' [ / 'line-height' ]? 'font-family'
-bool CSSParser::parseFont(bool important)
+bool BisonCSSParser::parseFont(bool important)
 {
     // Let's check if there is an inherit or initial somewhere in the shorthand.
     for (unsigned i = 0; i < m_valueList->size(); ++i) {
@@ -5459,9 +5781,9 @@
     CSSValueList* m_list;
 };
 
-PassRefPtr<CSSValueList> CSSParser::parseFontFamily()
+PassRefPtrWillBeRawPtr<CSSValueList> BisonCSSParser::parseFontFamily()
 {
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     CSSParserValue* value = m_valueList->current();
 
     FontFamilyValueBuilder familyBuilder(list.get());
@@ -5533,7 +5855,7 @@
     return list.release();
 }
 
-bool CSSParser::parseLineHeight(bool important)
+bool BisonCSSParser::parseLineHeight(bool important)
 {
     CSSParserValue* value = m_valueList->current();
     CSSValueID id = value->id;
@@ -5548,7 +5870,7 @@
     return validPrimitive;
 }
 
-bool CSSParser::parseFontSize(bool important)
+bool BisonCSSParser::parseFontSize(bool important)
 {
     CSSParserValue* value = m_valueList->current();
     CSSValueID id = value->id;
@@ -5563,15 +5885,15 @@
     return validPrimitive;
 }
 
-bool CSSParser::parseFontVariant(bool important)
+bool BisonCSSParser::parseFontVariant(bool important)
 {
-    RefPtr<CSSValueList> values;
+    RefPtrWillBeRawPtr<CSSValueList> values;
     if (m_valueList->size() > 1)
         values = CSSValueList::createCommaSeparated();
     CSSParserValue* val;
     bool expectComma = false;
     while ((val = m_valueList->current())) {
-        RefPtr<CSSPrimitiveValue> parsedValue;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> parsedValue;
         if (!expectComma) {
             expectComma = true;
             if (val->id == CSSValueNormal || val->id == CSSValueSmallCaps)
@@ -5610,7 +5932,7 @@
     return false;
 }
 
-bool CSSParser::parseFontWeight(bool important)
+bool BisonCSSParser::parseFontWeight(bool important)
 {
     CSSParserValue* value = m_valueList->current();
     if ((value->id >= CSSValueNormal) && (value->id <= CSSValue900)) {
@@ -5627,9 +5949,9 @@
     return false;
 }
 
-bool CSSParser::parseFontFaceSrcURI(CSSValueList* valueList)
+bool BisonCSSParser::parseFontFaceSrcURI(CSSValueList* valueList)
 {
-    RefPtr<CSSFontFaceSrcValue> uriValue(CSSFontFaceSrcValue::create(completeURL(m_valueList->current()->string)));
+    RefPtrWillBeRawPtr<CSSFontFaceSrcValue> uriValue(CSSFontFaceSrcValue::create(completeURL(m_valueList->current()->string)));
 
     CSSParserValue* value = m_valueList->next();
     if (!value) {
@@ -5658,7 +5980,7 @@
     return true;
 }
 
-bool CSSParser::parseFontFaceSrcLocal(CSSValueList* valueList)
+bool BisonCSSParser::parseFontFaceSrcLocal(CSSValueList* valueList)
 {
     CSSParserValueList* args = m_valueList->current()->function->args.get();
     if (!args || !args->size())
@@ -5686,9 +6008,9 @@
     return true;
 }
 
-bool CSSParser::parseFontFaceSrc()
+bool BisonCSSParser::parseFontFaceSrc()
 {
-    RefPtr<CSSValueList> values(CSSValueList::createCommaSeparated());
+    RefPtrWillBeRawPtr<CSSValueList> values(CSSValueList::createCommaSeparated());
 
     while (CSSParserValue* value = m_valueList->current()) {
         if (value->unit == CSSPrimitiveValue::CSS_URI) {
@@ -5708,9 +6030,9 @@
     return true;
 }
 
-bool CSSParser::parseFontFaceUnicodeRange()
+bool BisonCSSParser::parseFontFaceUnicodeRange()
 {
-    RefPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
     bool failed = false;
     bool operatorExpected = false;
     for (; m_valueList->current(); m_valueList->next(), operatorExpected = !operatorExpected) {
@@ -6087,7 +6409,7 @@
 }
 
 template<typename StringType>
-bool CSSParser::fastParseColor(RGBA32& rgb, const StringType& name, bool strict)
+bool BisonCSSParser::fastParseColor(RGBA32& rgb, const StringType& name, bool strict)
 {
     unsigned length = name.length();
     bool parseResult;
@@ -6105,15 +6427,13 @@
 
     // Try named colors.
     Color tc;
-    tc.setNamedColor(name);
-    if (tc.isValid()) {
-        rgb = tc.rgb();
-        return true;
-    }
-    return false;
+    if (!tc.setNamedColor(name))
+        return false;
+    rgb = tc.rgb();
+    return true;
 }
 
-inline double CSSParser::parsedDouble(CSSParserValue *v, ReleaseParsedCalcValueCondition releaseCalc)
+inline double BisonCSSParser::parsedDouble(CSSParserValue *v, ReleaseParsedCalcValueCondition releaseCalc)
 {
     const double result = m_parsedCalculation ? m_parsedCalculation->doubleValue() : v->fValue;
     if (releaseCalc == ReleaseParsedCalcValue)
@@ -6121,7 +6441,7 @@
     return result;
 }
 
-bool CSSParser::isCalculation(CSSParserValue* value)
+bool BisonCSSParser::isCalculation(CSSParserValue* value)
 {
     return (value->unit == CSSParserValue::Function)
         && (equalIgnoringCase(value->function->name, "calc(")
@@ -6130,7 +6450,7 @@
             || equalIgnoringCase(value->function->name, "-webkit-max("));
 }
 
-inline int CSSParser::colorIntFromValue(CSSParserValue* v)
+inline int BisonCSSParser::colorIntFromValue(CSSParserValue* v)
 {
     bool isPercent;
 
@@ -6156,7 +6476,7 @@
     return static_cast<int>(value);
 }
 
-bool CSSParser::parseColorParameters(CSSParserValue* value, int* colorArray, bool parseAlpha)
+bool BisonCSSParser::parseColorParameters(CSSParserValue* value, int* colorArray, bool parseAlpha)
 {
     CSSParserValueList* args = value->function->args.get();
     CSSParserValue* v = args->current();
@@ -6199,7 +6519,7 @@
 // and with alpha, the format is
 // hsla(<number>, <percent>, <percent>, <number>)
 // The first value, HUE, is in an angle with a value between 0 and 360
-bool CSSParser::parseHSLParameters(CSSParserValue* value, double* colorArray, bool parseAlpha)
+bool BisonCSSParser::parseHSLParameters(CSSParserValue* value, double* colorArray, bool parseAlpha)
 {
     CSSParserValueList* args = value->function->args.get();
     CSSParserValue* v = args->current();
@@ -6229,7 +6549,7 @@
     return true;
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSParser::parseColor(CSSParserValue* value)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> BisonCSSParser::parseColor(CSSParserValue* value)
 {
     RGBA32 c = Color::transparent;
     if (!parseColorFromValue(value ? value : m_valueList->current(), c))
@@ -6237,7 +6557,7 @@
     return cssValuePool().createColorValue(c);
 }
 
-bool CSSParser::parseColorFromValue(CSSParserValue* value, RGBA32& c)
+bool BisonCSSParser::parseColorFromValue(CSSParserValue* value, RGBA32& c)
 {
     if (inQuirksMode() && value->unit == CSSPrimitiveValue::CSS_NUMBER
         && value->fValue >= 0. && value->fValue < 1000000.) {
@@ -6293,7 +6613,9 @@
 // This class tracks parsing state for shadow values.  If it goes out of scope (e.g., due to an early return)
 // without the allowBreak bit being set, then it will clean up all of the objects and destroy them.
 struct ShadowParseContext {
-    ShadowParseContext(CSSPropertyID prop, CSSParser* parser)
+    DISALLOW_ALLOCATION();
+public:
+    ShadowParseContext(CSSPropertyID prop, BisonCSSParser* parser)
         : property(prop)
         , m_parser(parser)
         , allowX(true)
@@ -6338,7 +6660,7 @@
 
     void commitLength(CSSParserValue* v)
     {
-        RefPtr<CSSPrimitiveValue> val = m_parser->createPrimitiveNumericValue(v);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> val = m_parser->createPrimitiveNumericValue(v);
 
         if (allowX) {
             x = val.release();
@@ -6364,7 +6686,7 @@
         }
     }
 
-    void commitColor(PassRefPtr<CSSPrimitiveValue> val)
+    void commitColor(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val)
     {
         color = val;
         allowColor = false;
@@ -6392,15 +6714,15 @@
     }
 
     CSSPropertyID property;
-    CSSParser* m_parser;
+    BisonCSSParser* m_parser;
 
-    RefPtr<CSSValueList> values;
-    RefPtr<CSSPrimitiveValue> x;
-    RefPtr<CSSPrimitiveValue> y;
-    RefPtr<CSSPrimitiveValue> blur;
-    RefPtr<CSSPrimitiveValue> spread;
-    RefPtr<CSSPrimitiveValue> style;
-    RefPtr<CSSPrimitiveValue> color;
+    RefPtrWillBeRawPtr<CSSValueList> values;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> x;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> y;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> blur;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> spread;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> style;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> color;
 
     bool allowX;
     bool allowY;
@@ -6411,7 +6733,7 @@
     bool allowBreak;
 };
 
-PassRefPtr<CSSValueList> CSSParser::parseShadow(CSSParserValueList* valueList, CSSPropertyID propId)
+PassRefPtrWillBeRawPtr<CSSValueList> BisonCSSParser::parseShadow(CSSParserValueList* valueList, CSSPropertyID propId)
 {
     ShadowParseContext context(propId, this);
     CSSParserValue* val;
@@ -6442,7 +6764,7 @@
             context.commitStyle(val);
         } else {
             // The only other type of value that's ok is a color value.
-            RefPtr<CSSPrimitiveValue> parsedColor;
+            RefPtrWillBeRawPtr<CSSPrimitiveValue> parsedColor;
             bool isColor = ((val->id >= CSSValueAqua && val->id <= CSSValueWindowtext) || val->id == CSSValueMenu
                             || (val->id >= CSSValueWebkitFocusRingColor && val->id <= CSSValueWebkitText && inQuirksMode())
                             || val->id == CSSValueCurrentcolor);
@@ -6475,30 +6797,27 @@
     return 0;
 }
 
-bool CSSParser::parseReflect(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseReflect(CSSPropertyID propId, bool important)
 {
     // box-reflect: <direction> <offset> <mask>
 
     // Direction comes first.
     CSSParserValue* val = m_valueList->current();
-    RefPtr<CSSPrimitiveValue> direction;
-    if (val->unit == CSSPrimitiveValue::CSS_VARIABLE_NAME)
-        direction = createPrimitiveVariableNameValue(val);
-    else
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> direction;
     switch (val->id) {
-        case CSSValueAbove:
-        case CSSValueBelow:
-        case CSSValueLeft:
-        case CSSValueRight:
-            direction = cssValuePool().createIdentifierValue(val->id);
-            break;
-        default:
-            return false;
+    case CSSValueAbove:
+    case CSSValueBelow:
+    case CSSValueLeft:
+    case CSSValueRight:
+        direction = cssValuePool().createIdentifierValue(val->id);
+        break;
+    default:
+        return false;
     }
 
     // The offset comes next.
     val = m_valueList->next();
-    RefPtr<CSSPrimitiveValue> offset;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> offset;
     if (!val)
         offset = cssValuePool().createValue(0, CSSPrimitiveValue::CSS_PX);
     else {
@@ -6516,20 +6835,20 @@
             return false;
     }
 
-    RefPtr<CSSReflectValue> reflectValue = CSSReflectValue::create(direction.release(), offset.release(), mask.release());
+    RefPtrWillBeRawPtr<CSSReflectValue> reflectValue = CSSReflectValue::create(direction.release(), offset.release(), mask.release());
     addProperty(propId, reflectValue.release(), important);
     m_valueList->next();
     return true;
 }
 
-bool CSSParser::parseFlex(CSSParserValueList* args, bool important)
+bool BisonCSSParser::parseFlex(CSSParserValueList* args, bool important)
 {
     if (!args || !args->size() || args->size() > 3)
         return false;
     static const double unsetValue = -1;
     double flexGrow = unsetValue;
     double flexShrink = unsetValue;
-    RefPtr<CSSPrimitiveValue> flexBasis;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> flexBasis;
 
     while (CSSParserValue* arg = args->current()) {
         if (validUnit(arg, FNumber | FNonNeg)) {
@@ -6566,7 +6885,7 @@
     return true;
 }
 
-bool CSSParser::parseObjectPosition(bool important)
+bool BisonCSSParser::parseObjectPosition(bool important)
 {
     RefPtr<CSSValue> xValue;
     RefPtr<CSSValue> yValue;
@@ -6581,6 +6900,8 @@
 }
 
 struct BorderImageParseContext {
+    DISALLOW_ALLOCATION();
+public:
     BorderImageParseContext()
     : m_canAdvance(false)
     , m_allowCommit(true)
@@ -6613,7 +6934,7 @@
         m_allowImageSlice = !m_imageSlice;
         m_allowRepeat = !m_repeat;
     }
-    void commitImageSlice(PassRefPtr<CSSBorderImageSliceValue> slice)
+    void commitImageSlice(PassRefPtrWillBeRawPtr<CSSBorderImageSliceValue> slice)
     {
         m_imageSlice = slice;
         m_canAdvance = true;
@@ -6634,7 +6955,7 @@
             m_requireWidth = false;
         }
     }
-    void commitBorderWidth(PassRefPtr<CSSPrimitiveValue> slice)
+    void commitBorderWidth(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> slice)
     {
         m_borderSlice = slice;
         m_canAdvance = true;
@@ -6643,7 +6964,7 @@
         m_allowImage = !m_image;
         m_allowRepeat = !m_repeat;
     }
-    void commitBorderOutset(PassRefPtr<CSSPrimitiveValue> outset)
+    void commitBorderOutset(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> outset)
     {
         m_outset = outset;
         m_canAdvance = true;
@@ -6667,7 +6988,7 @@
         return createBorderImageValue(m_image, m_imageSlice, m_borderSlice, m_outset, m_repeat);
     }
 
-    void commitMaskBoxImage(CSSParser* parser, bool important)
+    void commitMaskBoxImage(BisonCSSParser* parser, bool important)
     {
         commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageSource, parser, m_image, important);
         commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageSlice, parser, m_imageSlice, important);
@@ -6676,7 +6997,7 @@
         commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageRepeat, parser, m_repeat, important);
     }
 
-    void commitBorderImage(CSSParser* parser, bool important)
+    void commitBorderImage(BisonCSSParser* parser, bool important)
     {
         commitBorderImageProperty(CSSPropertyBorderImageSource, parser, m_image, important);
         commitBorderImageProperty(CSSPropertyBorderImageSlice, parser, m_imageSlice, important);
@@ -6685,7 +7006,7 @@
         commitBorderImageProperty(CSSPropertyBorderImageRepeat, parser, m_repeat, important);
     }
 
-    void commitBorderImageProperty(CSSPropertyID propId, CSSParser* parser, PassRefPtr<CSSValue> value, bool important)
+    void commitBorderImageProperty(CSSPropertyID propId, BisonCSSParser* parser, PassRefPtr<CSSValue> value, bool important)
     {
         if (value)
             parser->addProperty(propId, value, important);
@@ -6705,14 +7026,14 @@
     bool m_requireOutset;
 
     RefPtr<CSSValue> m_image;
-    RefPtr<CSSBorderImageSliceValue> m_imageSlice;
-    RefPtr<CSSPrimitiveValue> m_borderSlice;
-    RefPtr<CSSPrimitiveValue> m_outset;
+    RefPtrWillBeRawPtr<CSSBorderImageSliceValue> m_imageSlice;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_borderSlice;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_outset;
 
     RefPtr<CSSValue> m_repeat;
 };
 
-static bool buildBorderImageParseContext(CSSParser& parser, CSSPropertyID propId, BorderImageParseContext& context)
+static bool buildBorderImageParseContext(BisonCSSParser& parser, CSSPropertyID propId, BorderImageParseContext& context)
 {
     ShorthandScope scope(&parser, propId);
     while (CSSParserValue* val = parser.m_valueList->current()) {
@@ -6723,7 +7044,7 @@
 
         if (!context.canAdvance() && context.allowImage()) {
             if (val->unit == CSSPrimitiveValue::CSS_URI) {
-                context.commitImage(CSSImageValue::create(parser.completeURL(parser.m_context, val->string)));
+                context.commitImage(CSSImageValue::create(parser.m_context.completeURL(val->string)));
             } else if (isGeneratedImageValue(val)) {
                 RefPtr<CSSValue> value;
                 if (parser.parseGeneratedImage(parser.m_valueList.get(), value))
@@ -6741,7 +7062,7 @@
         }
 
         if (!context.canAdvance() && context.allowImageSlice()) {
-            RefPtr<CSSBorderImageSliceValue> imageSlice;
+            RefPtrWillBeRawPtr<CSSBorderImageSliceValue> imageSlice;
             if (parser.parseBorderImageSlice(propId, imageSlice))
                 context.commitImageSlice(imageSlice.release());
         }
@@ -6753,13 +7074,13 @@
         }
 
         if (!context.canAdvance() && context.requireWidth()) {
-            RefPtr<CSSPrimitiveValue> borderSlice;
+            RefPtrWillBeRawPtr<CSSPrimitiveValue> borderSlice;
             if (parser.parseBorderImageWidth(borderSlice))
                 context.commitBorderWidth(borderSlice.release());
         }
 
         if (!context.canAdvance() && context.requireOutset()) {
-            RefPtr<CSSPrimitiveValue> borderOutset;
+            RefPtrWillBeRawPtr<CSSPrimitiveValue> borderOutset;
             if (parser.parseBorderImageOutset(borderOutset))
                 context.commitBorderOutset(borderOutset.release());
         }
@@ -6773,7 +7094,7 @@
     return context.allowCommit();
 }
 
-bool CSSParser::parseBorderImageShorthand(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseBorderImageShorthand(CSSPropertyID propId, bool important)
 {
     BorderImageParseContext context;
     if (buildBorderImageParseContext(*this, propId, context)) {
@@ -6792,7 +7113,7 @@
     return false;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseBorderImage(CSSPropertyID propId)
+PassRefPtr<CSSValue> BisonCSSParser::parseBorderImage(CSSPropertyID propId)
 {
     BorderImageParseContext context;
     if (buildBorderImageParseContext(*this, propId, context)) {
@@ -6806,10 +7127,10 @@
     return id == CSSValueStretch || id == CSSValueRepeat || id == CSSValueSpace || id == CSSValueRound;
 }
 
-bool CSSParser::parseBorderImageRepeat(RefPtr<CSSValue>& result)
+bool BisonCSSParser::parseBorderImageRepeat(RefPtr<CSSValue>& result)
 {
-    RefPtr<CSSPrimitiveValue> firstValue;
-    RefPtr<CSSPrimitiveValue> secondValue;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> firstValue;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> secondValue;
     CSSParserValue* val = m_valueList->current();
     if (!val)
         return false;
@@ -6839,8 +7160,9 @@
 }
 
 class BorderImageSliceParseContext {
+    DISALLOW_ALLOCATION();
 public:
-    BorderImageSliceParseContext(CSSParser* parser)
+    BorderImageSliceParseContext(BisonCSSParser* parser)
     : m_parser(parser)
     , m_allowNumber(true)
     , m_allowFill(true)
@@ -6855,7 +7177,7 @@
 
     void commitNumber(CSSParserValue* v)
     {
-        RefPtr<CSSPrimitiveValue> val = m_parser->createPrimitiveNumericValue(v);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> val = m_parser->createPrimitiveNumericValue(v);
         if (!m_top)
             m_top = val;
         else if (!m_right)
@@ -6873,7 +7195,7 @@
 
     void commitFill() { m_fill = true; m_allowFill = false; m_allowNumber = !m_top; }
 
-    PassRefPtr<CSSBorderImageSliceValue> commitBorderImageSlice()
+    PassRefPtrWillBeRawPtr<CSSBorderImageSliceValue> commitBorderImageSlice()
     {
         // We need to clone and repeat values for any omissions.
         ASSERT(m_top);
@@ -6901,21 +7223,21 @@
     }
 
 private:
-    CSSParser* m_parser;
+    BisonCSSParser* m_parser;
 
     bool m_allowNumber;
     bool m_allowFill;
     bool m_allowFinalCommit;
 
-    RefPtr<CSSPrimitiveValue> m_top;
-    RefPtr<CSSPrimitiveValue> m_right;
-    RefPtr<CSSPrimitiveValue> m_bottom;
-    RefPtr<CSSPrimitiveValue> m_left;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_top;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_right;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_bottom;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_left;
 
     bool m_fill;
 };
 
-bool CSSParser::parseBorderImageSlice(CSSPropertyID propId, RefPtr<CSSBorderImageSliceValue>& result)
+bool BisonCSSParser::parseBorderImageSlice(CSSPropertyID propId, RefPtrWillBeRawPtr<CSSBorderImageSliceValue>& result)
 {
     BorderImageSliceParseContext context(this);
     CSSParserValue* val;
@@ -6954,7 +7276,7 @@
 
 class BorderImageQuadParseContext {
 public:
-    BorderImageQuadParseContext(CSSParser* parser)
+    BorderImageQuadParseContext(BisonCSSParser* parser)
     : m_parser(parser)
     , m_allowNumber(true)
     , m_allowFinalCommit(false)
@@ -6966,7 +7288,7 @@
 
     void commitNumber(CSSParserValue* v)
     {
-        RefPtr<CSSPrimitiveValue> val;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> val;
         if (v->id == CSSValueAuto)
             val = cssValuePool().createIdentifierValue(v->id);
         else
@@ -6988,9 +7310,9 @@
     }
 
     void setAllowFinalCommit() { m_allowFinalCommit = true; }
-    void setTop(PassRefPtr<CSSPrimitiveValue> val) { m_top = val; }
+    void setTop(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> val) { m_top = val; }
 
-    PassRefPtr<CSSPrimitiveValue> commitBorderImageQuad()
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> commitBorderImageQuad()
     {
         // We need to clone and repeat values for any omissions.
         ASSERT(m_top);
@@ -7018,18 +7340,18 @@
     }
 
 private:
-    CSSParser* m_parser;
+    BisonCSSParser* m_parser;
 
     bool m_allowNumber;
     bool m_allowFinalCommit;
 
-    RefPtr<CSSPrimitiveValue> m_top;
-    RefPtr<CSSPrimitiveValue> m_right;
-    RefPtr<CSSPrimitiveValue> m_bottom;
-    RefPtr<CSSPrimitiveValue> m_left;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_top;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_right;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_bottom;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> m_left;
 };
 
-bool CSSParser::parseBorderImageQuad(Units validUnits, RefPtr<CSSPrimitiveValue>& result)
+bool BisonCSSParser::parseBorderImageQuad(Units validUnits, RefPtrWillBeRawPtr<CSSPrimitiveValue>& result)
 {
     BorderImageQuadParseContext context(this);
     CSSParserValue* val;
@@ -7055,36 +7377,24 @@
     return false;
 }
 
-bool CSSParser::parseBorderImageWidth(RefPtr<CSSPrimitiveValue>& result)
+bool BisonCSSParser::parseBorderImageWidth(RefPtrWillBeRawPtr<CSSPrimitiveValue>& result)
 {
     return parseBorderImageQuad(FLength | FNumber | FNonNeg | FPercent, result);
 }
 
-bool CSSParser::parseBorderImageOutset(RefPtr<CSSPrimitiveValue>& result)
+bool BisonCSSParser::parseBorderImageOutset(RefPtrWillBeRawPtr<CSSPrimitiveValue>& result)
 {
     return parseBorderImageQuad(FLength | FNumber | FNonNeg, result);
 }
 
-static void completeBorderRadii(RefPtr<CSSPrimitiveValue> radii[4])
-{
-    if (radii[3])
-        return;
-    if (!radii[2]) {
-        if (!radii[1])
-            radii[1] = radii[0];
-        radii[2] = radii[0];
-    }
-    radii[3] = radii[1];
-}
-
-bool CSSParser::parseBorderRadius(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseBorderRadius(CSSPropertyID propId, bool important)
 {
     unsigned num = m_valueList->size();
     if (num > 9)
         return false;
 
     ShorthandScope scope(this, propId);
-    RefPtr<CSSPrimitiveValue> radii[2][4];
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> radii[2][4];
 
     unsigned indexAfterSlash = 0;
     for (unsigned i = 0; i < num; ++i) {
@@ -7107,7 +7417,7 @@
         if (!validUnit(value, FLength | FPercent | FNonNeg))
             return false;
 
-        RefPtr<CSSPrimitiveValue> radius = createPrimitiveNumericValue(value);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> radius = createPrimitiveNumericValue(value);
 
         if (!indexAfterSlash) {
             radii[0][i] = radius;
@@ -7136,7 +7446,7 @@
     return true;
 }
 
-bool CSSParser::parseAspectRatio(bool important)
+bool BisonCSSParser::parseAspectRatio(bool important)
 {
     unsigned num = m_valueList->size();
     if (num == 1 && m_valueList->valueAt(0)->id == CSSValueNone) {
@@ -7165,12 +7475,12 @@
     return true;
 }
 
-bool CSSParser::parseCounter(CSSPropertyID propId, int defaultValue, bool important)
+bool BisonCSSParser::parseCounter(CSSPropertyID propId, int defaultValue, bool important)
 {
     enum { ID, VAL } state = ID;
 
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
-    RefPtr<CSSPrimitiveValue> counterName;
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> counterName;
 
     while (true) {
         CSSParserValue* val = m_valueList->current();
@@ -7208,9 +7518,9 @@
 }
 
 // This should go away once we drop support for -webkit-gradient
-static PassRefPtr<CSSPrimitiveValue> parseDeprecatedGradientPoint(CSSParserValue* a, bool horizontal)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parseDeprecatedGradientPoint(CSSParserValue* a, bool horizontal)
 {
-    RefPtr<CSSPrimitiveValue> result;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> result;
     if (a->unit == CSSPrimitiveValue::CSS_IDENT) {
         if ((equalIgnoringCase(a, "left") && horizontal)
             || (equalIgnoringCase(a, "top") && !horizontal))
@@ -7225,7 +7535,7 @@
     return result;
 }
 
-static bool parseDeprecatedGradientColorStop(CSSParser* p, CSSParserValue* a, CSSGradientColorStop& stop)
+static bool parseDeprecatedGradientColorStop(BisonCSSParser* p, CSSParserValue* a, CSSGradientColorStop& stop)
 {
     if (a->unit != CSSParserValue::Function)
         return false;
@@ -7289,7 +7599,7 @@
     return true;
 }
 
-bool CSSParser::parseDeprecatedGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient)
+bool BisonCSSParser::parseDeprecatedGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient)
 {
     // Walk the arguments.
     CSSParserValueList* args = valueList->current()->function->args.get();
@@ -7332,7 +7642,7 @@
     a = args->next();
     if (!a)
         return false;
-    RefPtr<CSSPrimitiveValue> point = parseDeprecatedGradientPoint(a, true);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> point = parseDeprecatedGradientPoint(a, true);
     if (!point)
         return false;
     result->setFirstX(point.release());
@@ -7422,7 +7732,7 @@
     return true;
 }
 
-static PassRefPtr<CSSPrimitiveValue> valueFromSideKeyword(CSSParserValue* a, bool& isHorizontal)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> valueFromSideKeyword(CSSParserValue* a, bool& isHorizontal)
 {
     if (a->unit != CSSPrimitiveValue::CSS_IDENT)
         return 0;
@@ -7442,7 +7752,7 @@
     return cssValuePool().createIdentifierValue(a->id);
 }
 
-static PassRefPtr<CSSPrimitiveValue> parseGradientColorOrKeyword(CSSParser* p, CSSParserValue* value)
+static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parseGradientColorOrKeyword(BisonCSSParser* p, CSSParserValue* value)
 {
     CSSValueID id = value->id;
     if (id == CSSValueWebkitText || (id >= CSSValueAqua && id <= CSSValueWindowtext) || id == CSSValueMenu || id == CSSValueCurrentcolor)
@@ -7451,9 +7761,9 @@
     return p->parseColor(value);
 }
 
-bool CSSParser::parseDeprecatedLinearGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
+bool BisonCSSParser::parseDeprecatedLinearGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
 {
-    RefPtr<CSSLinearGradientValue> result = CSSLinearGradientValue::create(repeating, CSSPrefixedLinearGradient);
+    RefPtrWillBeRawPtr<CSSLinearGradientValue> result = CSSLinearGradientValue::create(repeating, CSSPrefixedLinearGradient);
 
     // Walk the arguments.
     CSSParserValueList* args = valueList->current()->function->args.get();
@@ -7473,9 +7783,9 @@
         expectComma = true;
     } else {
         // Look one or two optional keywords that indicate a side or corner.
-        RefPtr<CSSPrimitiveValue> startX, startY;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> startX, startY;
 
-        RefPtr<CSSPrimitiveValue> location;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> location;
         bool isHorizontal = false;
         if ((location = valueFromSideKeyword(a, isHorizontal))) {
             if (isHorizontal)
@@ -7519,9 +7829,9 @@
     return true;
 }
 
-bool CSSParser::parseDeprecatedRadialGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
+bool BisonCSSParser::parseDeprecatedRadialGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
 {
-    RefPtr<CSSRadialGradientValue> result = CSSRadialGradientValue::create(repeating, CSSPrefixedRadialGradient);
+    RefPtrWillBeRawPtr<CSSRadialGradientValue> result = CSSRadialGradientValue::create(repeating, CSSPrefixedRadialGradient);
 
     // Walk the arguments.
     CSSParserValueList* args = valueList->current()->function->args.get();
@@ -7559,8 +7869,8 @@
     result->setFirstY(toCSSPrimitiveValue(centerY.get()));
     result->setSecondY(toCSSPrimitiveValue(centerY.get()));
 
-    RefPtr<CSSPrimitiveValue> shapeValue;
-    RefPtr<CSSPrimitiveValue> sizeValue;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> shapeValue;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> sizeValue;
 
     // Optional shape and/or size in any order.
     for (int i = 0; i < 2; ++i) {
@@ -7600,8 +7910,8 @@
     result->setSizingBehavior(sizeValue);
 
     // Or, two lengths or percentages
-    RefPtr<CSSPrimitiveValue> horizontalSize;
-    RefPtr<CSSPrimitiveValue> verticalSize;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> horizontalSize;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> verticalSize;
 
     if (!shapeValue && !sizeValue) {
         if (validUnit(a, FLength | FPercent)) {
@@ -7637,9 +7947,9 @@
     return true;
 }
 
-bool CSSParser::parseLinearGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
+bool BisonCSSParser::parseLinearGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
 {
-    RefPtr<CSSLinearGradientValue> result = CSSLinearGradientValue::create(repeating, CSSLinearGradient);
+    RefPtrWillBeRawPtr<CSSLinearGradientValue> result = CSSLinearGradientValue::create(repeating, CSSLinearGradient);
 
     CSSParserValueList* args = valueList->current()->function->args.get();
     if (!args || !args->size())
@@ -7662,8 +7972,8 @@
         if (!a)
             return false;
 
-        RefPtr<CSSPrimitiveValue> endX, endY;
-        RefPtr<CSSPrimitiveValue> location;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> endX, endY;
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> location;
         bool isHorizontal = false;
 
         location = valueFromSideKeyword(a, isHorizontal);
@@ -7709,9 +8019,9 @@
     return true;
 }
 
-bool CSSParser::parseRadialGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
+bool BisonCSSParser::parseRadialGradient(CSSParserValueList* valueList, RefPtr<CSSValue>& gradient, CSSGradientRepeat repeating)
 {
-    RefPtr<CSSRadialGradientValue> result = CSSRadialGradientValue::create(repeating, CSSRadialGradient);
+    RefPtrWillBeRawPtr<CSSRadialGradientValue> result = CSSRadialGradientValue::create(repeating, CSSRadialGradient);
 
     CSSParserValueList* args = valueList->current()->function->args.get();
     if (!args || !args->size())
@@ -7723,10 +8033,10 @@
 
     bool expectComma = false;
 
-    RefPtr<CSSPrimitiveValue> shapeValue;
-    RefPtr<CSSPrimitiveValue> sizeValue;
-    RefPtr<CSSPrimitiveValue> horizontalSize;
-    RefPtr<CSSPrimitiveValue> verticalSize;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> shapeValue;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> sizeValue;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> horizontalSize;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> verticalSize;
 
     // First part of grammar, the size/shape clause:
     // [ circle || <length> ] |
@@ -7832,7 +8142,7 @@
     return true;
 }
 
-bool CSSParser::parseGradientColorStops(CSSParserValueList* valueList, CSSGradientValue* gradient, bool expectComma)
+bool BisonCSSParser::parseGradientColorStops(CSSParserValueList* valueList, CSSGradientValue* gradient, bool expectComma)
 {
     CSSParserValue* a = valueList->current();
 
@@ -7870,36 +8180,55 @@
     return gradient->stopCount() >= 2;
 }
 
-bool CSSParser::parseGeneratedImage(CSSParserValueList* valueList, RefPtr<CSSValue>& value)
+bool BisonCSSParser::parseGeneratedImage(CSSParserValueList* valueList, RefPtr<CSSValue>& value)
 {
     CSSParserValue* val = valueList->current();
 
     if (val->unit != CSSParserValue::Function)
         return false;
 
-    if (equalIgnoringCase(val->function->name, "-webkit-gradient("))
+    if (equalIgnoringCase(val->function->name, "-webkit-gradient(")) {
+        // FIXME: This should send a deprecation message.
+        if (m_context.useCounter())
+            m_context.useCounter()->count(UseCounter::DeprecatedWebKitGradient);
         return parseDeprecatedGradient(valueList, value);
+    }
 
-    if (equalIgnoringCase(val->function->name, "-webkit-linear-gradient("))
+    if (equalIgnoringCase(val->function->name, "-webkit-linear-gradient(")) {
+        // FIXME: This should send a deprecation message.
+        if (m_context.useCounter())
+            m_context.useCounter()->count(UseCounter::DeprecatedWebKitLinearGradient);
         return parseDeprecatedLinearGradient(valueList, value, NonRepeating);
+    }
 
     if (equalIgnoringCase(val->function->name, "linear-gradient("))
         return parseLinearGradient(valueList, value, NonRepeating);
 
-    if (equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient("))
+    if (equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient(")) {
+        // FIXME: This should send a deprecation message.
+        if (m_context.useCounter())
+            m_context.useCounter()->count(UseCounter::DeprecatedWebKitRepeatingLinearGradient);
         return parseDeprecatedLinearGradient(valueList, value, Repeating);
+    }
 
     if (equalIgnoringCase(val->function->name, "repeating-linear-gradient("))
         return parseLinearGradient(valueList, value, Repeating);
 
-    if (equalIgnoringCase(val->function->name, "-webkit-radial-gradient("))
+    if (equalIgnoringCase(val->function->name, "-webkit-radial-gradient(")) {
+        // FIXME: This should send a deprecation message.
+        if (m_context.useCounter())
+            m_context.useCounter()->count(UseCounter::DeprecatedWebKitRadialGradient);
         return parseDeprecatedRadialGradient(valueList, value, NonRepeating);
+    }
 
     if (equalIgnoringCase(val->function->name, "radial-gradient("))
         return parseRadialGradient(valueList, value, NonRepeating);
 
-    if (equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient("))
+    if (equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient(")) {
+        if (m_context.useCounter())
+            m_context.useCounter()->count(UseCounter::DeprecatedWebKitRepeatingRadialGradient);
         return parseDeprecatedRadialGradient(valueList, value, Repeating);
+    }
 
     if (equalIgnoringCase(val->function->name, "repeating-radial-gradient("))
         return parseRadialGradient(valueList, value, Repeating);
@@ -7913,10 +8242,8 @@
     return false;
 }
 
-bool CSSParser::parseCrossfade(CSSParserValueList* valueList, RefPtr<CSSValue>& crossfade)
+bool BisonCSSParser::parseCrossfade(CSSParserValueList* valueList, RefPtr<CSSValue>& crossfade)
 {
-    RefPtr<CSSCrossfadeValue> result;
-
     // Walk the arguments.
     CSSParserValueList* args = valueList->current()->function->args.get();
     if (!args || args->size() != 5)
@@ -7946,7 +8273,7 @@
     a = args->next();
 
     // The third argument is the crossfade value. It is a percentage or a fractional number.
-    RefPtr<CSSPrimitiveValue> percentage;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> percentage;
     if (!a)
         return false;
 
@@ -7957,7 +8284,7 @@
     else
         return false;
 
-    result = CSSCrossfadeValue::create(fromImageValue, toImageValue);
+    RefPtrWillBeRawPtr<CSSCrossfadeValue> result = CSSCrossfadeValue::create(fromImageValue, toImageValue);
     result->setPercentage(percentage);
 
     crossfade = result;
@@ -7965,7 +8292,7 @@
     return true;
 }
 
-bool CSSParser::parseCanvas(CSSParserValueList* valueList, RefPtr<CSSValue>& canvas)
+bool BisonCSSParser::parseCanvas(CSSParserValueList* valueList, RefPtr<CSSValue>& canvas)
 {
     // Walk the arguments.
     CSSParserValueList* args = valueList->current()->function->args.get();
@@ -7981,7 +8308,7 @@
     return true;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseImageSet(CSSParserValueList* valueList)
+PassRefPtr<CSSValue> BisonCSSParser::parseImageSet(CSSParserValueList* valueList)
 {
     CSSParserValue* function = valueList->current();
 
@@ -7992,7 +8319,7 @@
     if (!functionArgs || !functionArgs->size() || !functionArgs->current())
         return 0;
 
-    RefPtr<CSSImageSetValue> imageSet = CSSImageSetValue::create();
+    RefPtrWillBeRawPtr<CSSImageSetValue> imageSet = CSSImageSetValue::create();
 
     CSSParserValue* arg = functionArgs->current();
     while (arg) {
@@ -8044,7 +8371,7 @@
         : m_type(CSSTransformValue::UnknownTransformOperation)
         , m_argCount(1)
         , m_allowSingleArgument(false)
-        , m_unit(CSSParser::FUnknown)
+        , m_unit(BisonCSSParser::FUnknown)
     {
         const UChar* characters;
         unsigned nameLength = name.length();
@@ -8062,97 +8389,97 @@
 
         SWITCH(characters, nameLength) {
             CASE("skew(") {
-                m_unit = CSSParser::FAngle;
+                m_unit = BisonCSSParser::FAngle;
                 m_type = CSSTransformValue::SkewTransformOperation;
                 m_allowSingleArgument = true;
                 m_argCount = 3;
             }
             CASE("scale(") {
-                m_unit = CSSParser::FNumber;
+                m_unit = BisonCSSParser::FNumber;
                 m_type = CSSTransformValue::ScaleTransformOperation;
                 m_allowSingleArgument = true;
                 m_argCount = 3;
             }
             CASE("skewx(") {
-                m_unit = CSSParser::FAngle;
+                m_unit = BisonCSSParser::FAngle;
                 m_type = CSSTransformValue::SkewXTransformOperation;
             }
             CASE("skewy(") {
-                m_unit = CSSParser::FAngle;
+                m_unit = BisonCSSParser::FAngle;
                 m_type = CSSTransformValue::SkewYTransformOperation;
             }
             CASE("matrix(") {
-                m_unit = CSSParser::FNumber;
+                m_unit = BisonCSSParser::FNumber;
                 m_type = CSSTransformValue::MatrixTransformOperation;
                 m_argCount = 11;
             }
             CASE("rotate(") {
-                m_unit = CSSParser::FAngle;
+                m_unit = BisonCSSParser::FAngle;
                 m_type = CSSTransformValue::RotateTransformOperation;
             }
             CASE("scalex(") {
-                m_unit = CSSParser::FNumber;
+                m_unit = BisonCSSParser::FNumber;
                 m_type = CSSTransformValue::ScaleXTransformOperation;
             }
             CASE("scaley(") {
-                m_unit = CSSParser::FNumber;
+                m_unit = BisonCSSParser::FNumber;
                 m_type = CSSTransformValue::ScaleYTransformOperation;
             }
             CASE("scalez(") {
-                m_unit = CSSParser::FNumber;
+                m_unit = BisonCSSParser::FNumber;
                 m_type = CSSTransformValue::ScaleZTransformOperation;
             }
             CASE("scale3d(") {
-                m_unit = CSSParser::FNumber;
+                m_unit = BisonCSSParser::FNumber;
                 m_type = CSSTransformValue::Scale3DTransformOperation;
                 m_argCount = 5;
             }
             CASE("rotatex(") {
-                m_unit = CSSParser::FAngle;
+                m_unit = BisonCSSParser::FAngle;
                 m_type = CSSTransformValue::RotateXTransformOperation;
             }
             CASE("rotatey(") {
-                m_unit = CSSParser::FAngle;
+                m_unit = BisonCSSParser::FAngle;
                 m_type = CSSTransformValue::RotateYTransformOperation;
             }
             CASE("rotatez(") {
-                m_unit = CSSParser::FAngle;
+                m_unit = BisonCSSParser::FAngle;
                 m_type = CSSTransformValue::RotateZTransformOperation;
             }
             CASE("matrix3d(") {
-                m_unit = CSSParser::FNumber;
+                m_unit = BisonCSSParser::FNumber;
                 m_type = CSSTransformValue::Matrix3DTransformOperation;
                 m_argCount = 31;
             }
             CASE("rotate3d(") {
-                m_unit = CSSParser::FNumber;
+                m_unit = BisonCSSParser::FNumber;
                 m_type = CSSTransformValue::Rotate3DTransformOperation;
                 m_argCount = 7;
             }
             CASE("translate(") {
-                m_unit = CSSParser::FLength | CSSParser::FPercent;
+                m_unit = BisonCSSParser::FLength | BisonCSSParser::FPercent;
                 m_type = CSSTransformValue::TranslateTransformOperation;
                 m_allowSingleArgument = true;
                 m_argCount = 3;
             }
             CASE("translatex(") {
-                m_unit = CSSParser::FLength | CSSParser::FPercent;
+                m_unit = BisonCSSParser::FLength | BisonCSSParser::FPercent;
                 m_type = CSSTransformValue::TranslateXTransformOperation;
             }
             CASE("translatey(") {
-                m_unit = CSSParser::FLength | CSSParser::FPercent;
+                m_unit = BisonCSSParser::FLength | BisonCSSParser::FPercent;
                 m_type = CSSTransformValue::TranslateYTransformOperation;
             }
             CASE("translatez(") {
-                m_unit = CSSParser::FLength | CSSParser::FPercent;
+                m_unit = BisonCSSParser::FLength | BisonCSSParser::FPercent;
                 m_type = CSSTransformValue::TranslateZTransformOperation;
             }
             CASE("perspective(") {
-                m_unit = CSSParser::FNumber;
+                m_unit = BisonCSSParser::FNumber;
                 m_type = CSSTransformValue::PerspectiveTransformOperation;
             }
             CASE("translate3d(") {
-                m_unit = CSSParser::FLength | CSSParser::FPercent;
+                m_unit = BisonCSSParser::FLength | BisonCSSParser::FPercent;
                 m_type = CSSTransformValue::Translate3DTransformOperation;
                 m_argCount = 5;
             }
@@ -8161,7 +8488,7 @@
 
     CSSTransformValue::TransformOperationType type() const { return m_type; }
     unsigned argCount() const { return m_argCount; }
-    CSSParser::Units unit() const { return m_unit; }
+    BisonCSSParser::Units unit() const { return m_unit; }
 
     bool unknown() const { return m_type == CSSTransformValue::UnknownTransformOperation; }
     bool hasCorrectArgCount(unsigned argCount) { return m_argCount == argCount || (m_allowSingleArgument && argCount == 1); }
@@ -8170,15 +8497,15 @@
     CSSTransformValue::TransformOperationType m_type;
     unsigned m_argCount;
     bool m_allowSingleArgument;
-    CSSParser::Units m_unit;
+    BisonCSSParser::Units m_unit;
 };
 
-PassRefPtr<CSSValueList> CSSParser::parseTransform()
+PassRefPtrWillBeRawPtr<CSSValueList> BisonCSSParser::parseTransform()
 {
     if (!m_valueList)
         return 0;
 
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) {
         RefPtr<CSSValue> parsedTransformValue = parseTransformValue(value);
         if (!parsedTransformValue)
@@ -8190,7 +8517,7 @@
     return list.release();
 }
 
-PassRefPtr<CSSValue> CSSParser::parseTransformValue(CSSParserValue *value)
+PassRefPtr<CSSValue> BisonCSSParser::parseTransformValue(CSSParserValue *value)
 {
     if (value->unit != CSSParserValue::Function || !value->function)
         return 0;
@@ -8212,13 +8539,13 @@
     // We collect a list of CSSTransformValues, where each value specifies a single operation.
 
     // Create the new CSSTransformValue for this operation and add it to our list.
-    RefPtr<CSSTransformValue> transformValue = CSSTransformValue::create(info.type());
+    RefPtrWillBeRawPtr<CSSTransformValue> transformValue = CSSTransformValue::create(info.type());
 
     // Snag our values.
     CSSParserValue* a = args->current();
     unsigned argNumber = 0;
     while (a) {
-        CSSParser::Units unit = info.unit();
+        BisonCSSParser::Units unit = info.unit();
 
         if (info.type() == CSSTransformValue::Rotate3DTransformOperation && argNumber == 3) {
             // 4th param of rotate3d() is an angle rather than a bare number, validate it as such
@@ -8255,14 +8582,14 @@
     return transformValue.release();
 }
 
-bool CSSParser::isBlendMode(CSSValueID valueID)
+bool BisonCSSParser::isBlendMode(CSSValueID valueID)
 {
     return (valueID >= CSSValueMultiply && valueID <= CSSValueLuminosity)
         || valueID == CSSValueNormal
         || valueID == CSSValueOverlay;
 }
 
-bool CSSParser::isCompositeOperator(CSSValueID valueID)
+bool BisonCSSParser::isCompositeOperator(CSSValueID valueID)
 {
     // FIXME: Add CSSValueDestination and CSSValueLighter when the Compositing spec updates.
     return valueID >= CSSValueClear && valueID <= CSSValueXor;
@@ -8292,425 +8619,11 @@
         filterType = CSSFilterValue::DropShadowFilterOperation;
         maximumArgumentCount = 4;  // x-offset, y-offset, blur-radius, color -- spread and inset style not allowed.
     }
-    else if (equalIgnoringCase(name, "custom("))
-        filterType = CSSFilterValue::CustomFilterOperation;
 }
 
-static bool acceptCommaOperator(CSSParserValueList* argsList)
+PassRefPtrWillBeRawPtr<CSSFilterValue> BisonCSSParser::parseBuiltinFilterArguments(CSSParserValueList* args, CSSFilterValue::FilterOperationType filterType)
 {
-    if (CSSParserValue* arg = argsList->current()) {
-        if (!isComma(arg))
-            return false;
-        argsList->next();
-    }
-    return true;
-}
-
-PassRefPtr<CSSArrayFunctionValue> CSSParser::parseCustomFilterArrayFunction(CSSParserValue* value)
-{
-    ASSERT(value->unit == CSSParserValue::Function && value->function);
-
-    if (!equalIgnoringCase(value->function->name, "array("))
-        return 0;
-
-    CSSParserValueList* arrayArgsParserValueList = value->function->args.get();
-    if (!arrayArgsParserValueList || !arrayArgsParserValueList->size())
-        return 0;
-
-    // array() values are comma separated.
-    RefPtr<CSSArrayFunctionValue> arrayFunction = CSSArrayFunctionValue::create();
-    while (true) {
-        // We parse pairs <Value, Comma> at each step.
-        CSSParserValue* currentParserValue = arrayArgsParserValueList->current();
-        if (!currentParserValue || !validUnit(currentParserValue, FNumber, HTMLStandardMode))
-            return 0;
-
-        RefPtr<CSSValue> arrayValue = cssValuePool().createValue(currentParserValue->fValue, CSSPrimitiveValue::CSS_NUMBER);
-        arrayFunction->append(arrayValue.release());
-
-        CSSParserValue* nextParserValue = arrayArgsParserValueList->next();
-        if (!nextParserValue)
-            break;
-
-        if (!isComma(nextParserValue))
-            return 0;
-
-        arrayArgsParserValueList->next();
-    }
-
-    return arrayFunction;
-}
-
-PassRefPtr<CSSMixFunctionValue> CSSParser::parseMixFunction(CSSParserValue* value)
-{
-    ASSERT(value->unit == CSSParserValue::Function && value->function);
-
-    if (!equalIgnoringCase(value->function->name, "mix("))
-        return 0;
-
-    CSSParserValueList* argsList = value->function->args.get();
-    if (!argsList)
-        return 0;
-
-    unsigned numArgs = argsList->size();
-    if (numArgs < 1 || numArgs > 3)
-        return 0;
-
-    RefPtr<CSSMixFunctionValue> mixFunction = CSSMixFunctionValue::create();
-
-    bool hasBlendMode = false;
-    bool hasAlphaCompositing = false;
-
-    for (CSSParserValue* arg = argsList->current(); arg; arg = argsList->next()) {
-        RefPtr<CSSValue> value;
-
-        unsigned argNumber = argsList->currentIndex();
-        if (!argNumber) {
-            if (arg->unit == CSSPrimitiveValue::CSS_URI) {
-                KURL shaderURL = completeURL(arg->string);
-                value = CSSShaderValue::create(shaderURL.string());
-            }
-        } else if (argNumber == 1 || argNumber == 2) {
-            if (!hasBlendMode && isBlendMode(arg->id)) {
-                hasBlendMode = true;
-                value = cssValuePool().createIdentifierValue(arg->id);
-            } else if (!hasAlphaCompositing && isCompositeOperator(arg->id)) {
-                hasAlphaCompositing = true;
-                value = cssValuePool().createIdentifierValue(arg->id);
-            }
-        }
-
-        if (!value)
-            return 0;
-
-        mixFunction->append(value.release());
-    }
-
-    return mixFunction;
-}
-
-PassRefPtr<CSSValueList> CSSParser::parseCustomFilterParameters(CSSParserValueList* argsList)
-{
-    //
-    // params:      [<param-def>[,<param-def>*]]
-    // param-def:   <param-name>wsp<param-value>
-    // param-name:  <ident>
-    // param-value: true|false[wsp+true|false]{0-3} |
-    //              <number>[wsp+<number>]{0-3} |
-    //              <array> |
-    //              <transform> |
-    //              <texture(<uri>)>
-    // array: 'array('<number>[wsp<number>]*')'
-    // css-3d-transform: <transform-function>;[<transform-function>]*
-    // transform:   <css-3d-transform> | <mat>
-    // mat:         'mat2('<number>(,<number>){3}')' |
-    //              'mat3('<number>(,<number>){8}')' |
-    //              'mat4('<number>(,<number>){15}')' )
-    //
-
-    RefPtr<CSSValueList> paramList = CSSValueList::createCommaSeparated();
-
-    while (CSSParserValue* arg = argsList->current()) {
-        if (arg->unit != CSSPrimitiveValue::CSS_IDENT)
-            return 0;
-
-        RefPtr<CSSValueList> parameter = CSSValueList::createSpaceSeparated();
-        parameter->append(createPrimitiveStringValue(arg));
-
-        arg = argsList->next();
-        if (!arg)
-            return 0;
-
-        RefPtr<CSSValue> parameterValue;
-
-        if (arg->unit == CSSParserValue::Function && arg->function) {
-            // FIXME: Implement parsing for the other parameter types.
-            // textures: https://bugs.webkit.org/show_bug.cgi?id=71442
-            // mat2, mat3, mat4: https://bugs.webkit.org/show_bug.cgi?id=71444
-            if (equalIgnoringCase(arg->function->name, "array(")) {
-                parameterValue = parseCustomFilterArrayFunction(arg);
-                // This parsing step only consumes function arguments,
-                // argsList is therefore moved forward explicitely.
-                argsList->next();
-            } else
-                parameterValue = parseCustomFilterTransform(argsList);
-        } else {
-            RefPtr<CSSValueList> paramValueList = CSSValueList::createSpaceSeparated();
-            arg = argsList->current();
-            while (arg) {
-                // If we hit a comma, it means that we finished this parameter's values.
-                if (isComma(arg))
-                    break;
-                if (!validUnit(arg, FNumber, HTMLStandardMode))
-                    return 0;
-                paramValueList->append(cssValuePool().createValue(arg->fValue, CSSPrimitiveValue::CSS_NUMBER));
-                arg = argsList->next();
-            }
-            if (!paramValueList->length() || paramValueList->length() > 4)
-                return 0;
-            parameterValue = paramValueList.release();
-        }
-
-        if (!parameterValue || !acceptCommaOperator(argsList))
-            return 0;
-
-        parameter->append(parameterValue.release());
-        paramList->append(parameter.release());
-    }
-
-    return paramList;
-}
-
-PassRefPtr<CSSFilterValue> CSSParser::parseCustomFilterFunctionWithAtRuleReferenceSyntax(CSSParserValue* value)
-{
-    //
-    // Custom filter function "at-rule reference" syntax:
-    //
-    // custom(<filter-name>wsp[,wsp<params>])
-    //
-    // filter-name: <filter-name>
-    // params: See the comment in CSSParser::parseCustomFilterParameters.
-    //
-
-    ASSERT(value->function);
-
-    CSSParserValueList* argsList = value->function->args.get();
-    if (!argsList || !argsList->size())
-        return 0;
-
-    // 1. Parse the filter name.
-    CSSParserValue* arg = argsList->current();
-    if (arg->unit != CSSPrimitiveValue::CSS_IDENT)
-        return 0;
-
-    RefPtr<CSSFilterValue> filterValue = CSSFilterValue::create(CSSFilterValue::CustomFilterOperation);
-
-    RefPtr<CSSValue> filterName = createPrimitiveStringValue(arg);
-    filterValue->append(filterName);
-    argsList->next();
-
-    if (!acceptCommaOperator(argsList))
-        return 0;
-
-    // 2. Parse the parameters.
-    RefPtr<CSSValueList> paramList = parseCustomFilterParameters(argsList);
-    if (!paramList)
-        return 0;
-
-    if (paramList->length())
-        filterValue->append(paramList.release());
-
-    return filterValue;
-}
-
-// FIXME: The custom filters "inline" syntax is deprecated. We will remove it eventually.
-PassRefPtr<CSSFilterValue> CSSParser::parseCustomFilterFunctionWithInlineSyntax(CSSParserValue* value)
-{
-    //
-    // Custom filter function "inline" syntax:
-    //
-    // custom(<vertex-shader>[wsp<fragment-shader>][,<vertex-mesh>][,<params>])
-    //
-    // vertexShader:    <uri> | none
-    // fragmentShader:  <uri> | none | mix(<uri> [ <blend-mode> || <alpha-compositing> ]?)
-    //
-    // blend-mode: normal | multiply | screen | overlay | darken | lighten | color-dodge |
-    //             color-burn | hard-light | soft-light | difference | exclusion | hue |
-    //             saturation | color | luminosity
-    // alpha-compositing: clear | src | dst | src-over | dst-over | src-in | dst-in |
-    //                    src-out | dst-out | src-atop | dst-atop | xor | plus
-    //
-    // vertexMesh:  +<integer>{1,2}[wsp<box>][wsp'detached']
-    // box: filter-box | border-box | padding-box | content-box
-    //
-    // params: See the comment in CSSParser::parseCustomFilterParameters.
-    //
-
-    ASSERT(value->function);
-
-    CSSParserValueList* argsList = value->function->args.get();
-    if (!argsList)
-        return 0;
-
-    RefPtr<CSSFilterValue> filterValue = CSSFilterValue::create(CSSFilterValue::CustomFilterOperation);
-
-    // 1. Parse the shader URLs: <vertex-shader>[wsp<fragment-shader>]
-    RefPtr<CSSValueList> shadersList = CSSValueList::createSpaceSeparated();
-    bool hadAtLeastOneCustomShader = false;
-    CSSParserValue* arg;
-    for (arg = argsList->current(); arg; arg = argsList->next()) {
-        RefPtr<CSSValue> value;
-        if (arg->id == CSSValueNone)
-            value = cssValuePool().createIdentifierValue(CSSValueNone);
-        else if (arg->unit == CSSPrimitiveValue::CSS_URI) {
-            KURL shaderURL = completeURL(arg->string);
-            value = CSSShaderValue::create(shaderURL.string());
-            hadAtLeastOneCustomShader = true;
-        } else if (argsList->currentIndex() == 1 && arg->unit == CSSParserValue::Function) {
-            if (!(value = parseMixFunction(arg)))
-                return 0;
-            hadAtLeastOneCustomShader = true;
-        }
-
-        if (!value)
-            break;
-        shadersList->append(value.release());
-    }
-
-    if (!shadersList->length() || !hadAtLeastOneCustomShader || shadersList->length() > 2 || !acceptCommaOperator(argsList))
-        return 0;
-
-    filterValue->append(shadersList.release());
-
-    // 2. Parse the mesh size <vertex-mesh>
-    RefPtr<CSSValueList> meshSizeList = CSSValueList::createSpaceSeparated();
-
-    for (arg = argsList->current(); arg; arg = argsList->next()) {
-        if (!validUnit(arg, FInteger | FNonNeg, HTMLStandardMode))
-            break;
-        int integerValue = clampToInteger(arg->fValue);
-        // According to the specification we can only accept positive non-zero values.
-        if (integerValue < 1)
-            return 0;
-        meshSizeList->append(cssValuePool().createValue(integerValue, CSSPrimitiveValue::CSS_NUMBER));
-    }
-
-    if (meshSizeList->length() > 2)
-        return 0;
-
-    // FIXME: For legacy content, we accept the mesh box types. We don't do anything else with them.
-    // Eventually, we'll remove them completely.
-    // https://bugs.webkit.org/show_bug.cgi?id=103778
-    if ((arg = argsList->current()) && (arg->id == CSSValueBorderBox || arg->id == CSSValuePaddingBox
-        || arg->id == CSSValueContentBox || arg->id == CSSValueFilterBox))
-        argsList->next();
-
-    if ((arg = argsList->current()) && arg->id == CSSValueDetached) {
-        meshSizeList->append(cssValuePool().createIdentifierValue(arg->id));
-        argsList->next();
-    }
-
-    if (meshSizeList->length()) {
-        if (!acceptCommaOperator(argsList))
-            return 0;
-        filterValue->append(meshSizeList.release());
-    }
-
-    // 3. Parse the parameters.
-    RefPtr<CSSValueList> paramList = parseCustomFilterParameters(argsList);
-    if (!paramList)
-        return 0;
-
-    if (paramList->length())
-        filterValue->append(paramList.release());
-
-    return filterValue;
-}
-
-PassRefPtr<CSSFilterValue> CSSParser::parseCustomFilterFunction(CSSParserValue* value)
-{
-    ASSERT(value->function);
-
-    // Look ahead to determine which syntax the custom function is using.
-    // Both the at-rule reference syntax and the inline syntax require at least one argument.
-    CSSParserValueList* argsList = value->function->args.get();
-    if (!argsList || !argsList->size())
-        return 0;
-
-    // The at-rule reference syntax expects a single ident or an ident followed by a comma.
-    // e.g. custom(my-filter) or custom(my-filter, ...)
-    // In contrast, when the inline syntax starts with an ident like "none", it expects a uri or a mix function next.
-    // e.g. custom(none url(...)) or custom(none mix(...)
-    bool isAtRuleReferenceSyntax = argsList->valueAt(0)->unit == CSSPrimitiveValue::CSS_IDENT
-        && (argsList->size() == 1 || isComma(argsList->valueAt(1)));
-    return isAtRuleReferenceSyntax ? parseCustomFilterFunctionWithAtRuleReferenceSyntax(value) : parseCustomFilterFunctionWithInlineSyntax(value);
-}
-
-PassRefPtr<CSSValueList> CSSParser::parseCustomFilterTransform(CSSParserValueList* valueList)
-{
-    if (!valueList)
-        return 0;
-
-    // CSS Shaders' custom() transforms are space separated and comma terminated.
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    for (CSSParserValue* value = valueList->current(); value; value = valueList->next()) {
-        if (isComma(value))
-            break;
-
-        RefPtr<CSSValue> parsedTransformValue = parseTransformValue(value);
-        if (!parsedTransformValue)
-            return 0;
-
-        list->append(parsedTransformValue.release());
-    }
-
-    return list.release();
-}
-
-PassRefPtr<CSSShaderValue> CSSParser::parseFilterRuleSrcUriAndFormat(CSSParserValueList* valueList)
-{
-    CSSParserValue* value = valueList->current();
-    ASSERT(value && value->unit == CSSPrimitiveValue::CSS_URI);
-    RefPtr<CSSShaderValue> shaderValue = CSSShaderValue::create(completeURL(value->string));
-
-    value = valueList->next();
-    if (value && value->unit == CSSParserValue::Function && equalIgnoringCase(value->function->name, "format(")) {
-        CSSParserValueList* args = value->function->args.get();
-        if (!args || args->size() != 1)
-            return 0;
-
-        CSSParserValue* arg = args->current();
-        if (arg->unit != CSSPrimitiveValue::CSS_STRING)
-            return 0;
-
-        shaderValue->setFormat(arg->string);
-        valueList->next();
-    }
-
-    return shaderValue.release();
-}
-
-bool CSSParser::parseFilterRuleSrc()
-{
-    RefPtr<CSSValueList> srcList = CSSValueList::createCommaSeparated();
-
-    CSSParserValue* value = m_valueList->current();
-    while (value) {
-        if (value->unit != CSSPrimitiveValue::CSS_URI)
-            return false;
-
-        RefPtr<CSSShaderValue> shaderValue = parseFilterRuleSrcUriAndFormat(m_valueList.get());
-        if (!shaderValue)
-            return false;
-        srcList->append(shaderValue.release());
-
-        if (!acceptCommaOperator(m_valueList.get()))
-            return false;
-
-        value = m_valueList->current();
-    }
-
-    if (!srcList->length())
-        return false;
-
-    addProperty(CSSPropertySrc, srcList.release(), m_important);
-    return true;
-}
-
-StyleRuleBase* CSSParser::createFilterRule(const CSSParserString& filterName)
-{
-    RefPtr<StyleRuleFilter> rule = StyleRuleFilter::create(filterName);
-    rule->setProperties(createStylePropertySet());
-    clearProperties();
-    StyleRuleFilter* result = rule.get();
-    m_parsedRules.append(rule.release());
-    return result;
-}
-
-
-PassRefPtr<CSSFilterValue> CSSParser::parseBuiltinFilterArguments(CSSParserValueList* args, CSSFilterValue::FilterOperationType filterType)
-{
-    RefPtr<CSSFilterValue> filterValue = CSSFilterValue::create(filterType);
+    RefPtrWillBeRawPtr<CSSFilterValue> filterValue = CSSFilterValue::create(filterType);
     ASSERT(args);
 
     switch (filterType) {
@@ -8787,7 +8700,7 @@
     }
     case CSSFilterValue::DropShadowFilterOperation: {
         // drop-shadow() takes a single shadow.
-        RefPtr<CSSValueList> shadowValueList = parseShadow(args, CSSPropertyWebkitFilter);
+        RefPtrWillBeRawPtr<CSSValueList> shadowValueList = parseShadow(args, CSSPropertyWebkitFilter);
         if (!shadowValueList || shadowValueList->length() != 1)
             return 0;
 
@@ -8800,13 +8713,13 @@
     return filterValue.release();
 }
 
-PassRefPtr<CSSValueList> CSSParser::parseFilter()
+PassRefPtrWillBeRawPtr<CSSValueList> BisonCSSParser::parseFilter()
 {
     if (!m_valueList)
         return 0;
 
     // The filter is a list of functional primitives that specify individual operations.
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) {
         if (value->unit != CSSPrimitiveValue::CSS_URI && (value->unit != CSSParserValue::Function || !value->function))
             return 0;
@@ -8815,7 +8728,7 @@
 
         // See if the specified primitive is one we understand.
         if (value->unit == CSSPrimitiveValue::CSS_URI) {
-            RefPtr<CSSFilterValue> referenceFilterValue = CSSFilterValue::create(CSSFilterValue::ReferenceFilterOperation);
+            RefPtrWillBeRawPtr<CSSFilterValue> referenceFilterValue = CSSFilterValue::create(CSSFilterValue::ReferenceFilterOperation);
             list->append(referenceFilterValue);
             referenceFilterValue->append(CSSSVGDocumentValue::create(value->string));
         } else {
@@ -8827,22 +8740,11 @@
             if (filterType == CSSFilterValue::UnknownFilterOperation)
                 return 0;
 
-            if (filterType == CSSFilterValue::CustomFilterOperation) {
-                // Make sure parsing fails if custom filters are disabled.
-                if (!RuntimeEnabledFeatures::cssCustomFilterEnabled())
-                    return 0;
-
-                RefPtr<CSSFilterValue> filterValue = parseCustomFilterFunction(value);
-                if (!filterValue)
-                    return 0;
-                list->append(filterValue.release());
-                continue;
-            }
             CSSParserValueList* args = value->function->args.get();
             if (!args)
                 return 0;
 
-            RefPtr<CSSFilterValue> filterValue = parseBuiltinFilterArguments(args, filterType);
+            RefPtrWillBeRawPtr<CSSFilterValue> filterValue = parseBuiltinFilterArguments(args, filterType);
             if (!filterValue)
                 return 0;
 
@@ -8853,89 +8755,7 @@
     return list.release();
 }
 
-static bool validFlowName(const String& flowName)
-{
-    return !(equalIgnoringCase(flowName, "auto")
-            || equalIgnoringCase(flowName, "default")
-            || equalIgnoringCase(flowName, "inherit")
-            || equalIgnoringCase(flowName, "initial")
-            || equalIgnoringCase(flowName, "none"));
-}
-
-bool CSSParser::parseFlowThread(const String& flowName)
-{
-    setupParser("@-internal-decls -webkit-flow-into:", flowName, "");
-    cssyyparse(this);
-
-    m_rule = 0;
-
-    return ((m_parsedProperties.size() == 1) && (m_parsedProperties.first().id() == CSSPropertyWebkitFlowInto));
-}
-
-// none | <ident>
-bool CSSParser::parseFlowThread(CSSPropertyID propId, bool important)
-{
-    ASSERT(propId == CSSPropertyWebkitFlowInto);
-    ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
-
-    if (m_valueList->size() != 1)
-        return false;
-
-    CSSParserValue* value = m_valueList->current();
-    if (!value)
-        return false;
-
-    if (value->unit != CSSPrimitiveValue::CSS_IDENT)
-        return false;
-
-    if (value->id == CSSValueNone) {
-        addProperty(propId, cssValuePool().createIdentifierValue(value->id), important);
-        return true;
-    }
-
-    String inputProperty = String(value->string);
-    if (!inputProperty.isEmpty()) {
-        if (!validFlowName(inputProperty))
-            return false;
-        addProperty(propId, cssValuePool().createValue(inputProperty, CSSPrimitiveValue::CSS_STRING), important);
-    } else
-        addProperty(propId, cssValuePool().createIdentifierValue(CSSValueNone), important);
-
-    return true;
-}
-
-// -webkit-flow-from: none | <ident>
-bool CSSParser::parseRegionThread(CSSPropertyID propId, bool important)
-{
-    ASSERT(propId == CSSPropertyWebkitFlowFrom);
-    ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
-
-    if (m_valueList->size() != 1)
-        return false;
-
-    CSSParserValue* value = m_valueList->current();
-    if (!value)
-        return false;
-
-    if (value->unit != CSSPrimitiveValue::CSS_IDENT)
-        return false;
-
-    if (value->id == CSSValueNone)
-        addProperty(propId, cssValuePool().createIdentifierValue(value->id), important);
-    else {
-        String inputProperty = String(value->string);
-        if (!inputProperty.isEmpty()) {
-            if (!validFlowName(inputProperty))
-                return false;
-            addProperty(propId, cssValuePool().createValue(inputProperty, CSSPrimitiveValue::CSS_STRING), important);
-        } else
-            addProperty(propId, cssValuePool().createIdentifierValue(CSSValueNone), important);
-    }
-
-    return true;
-}
-
-bool CSSParser::parseTransformOrigin(CSSPropertyID propId, CSSPropertyID& propId1, CSSPropertyID& propId2, CSSPropertyID& propId3, RefPtr<CSSValue>& value, RefPtr<CSSValue>& value2, RefPtr<CSSValue>& value3)
+bool BisonCSSParser::parseTransformOrigin(CSSPropertyID propId, CSSPropertyID& propId1, CSSPropertyID& propId2, CSSPropertyID& propId3, RefPtr<CSSValue>& value, RefPtr<CSSValue>& value2, RefPtr<CSSValue>& value3)
 {
     propId1 = propId;
     propId2 = propId;
@@ -8979,7 +8799,7 @@
     return value;
 }
 
-bool CSSParser::parsePerspectiveOrigin(CSSPropertyID propId, CSSPropertyID& propId1, CSSPropertyID& propId2, RefPtr<CSSValue>& value, RefPtr<CSSValue>& value2)
+bool BisonCSSParser::parsePerspectiveOrigin(CSSPropertyID propId, CSSPropertyID& propId1, CSSPropertyID& propId2, RefPtr<CSSValue>& value, RefPtr<CSSValue>& value2)
 {
     propId1 = propId;
     propId2 = propId;
@@ -9014,7 +8834,50 @@
     return value;
 }
 
-void CSSParser::addTextDecorationProperty(CSSPropertyID propId, PassRefPtr<CSSValue> value, bool important)
+bool BisonCSSParser::parseTouchAction(bool important)
+{
+    if (!RuntimeEnabledFeatures::cssTouchActionEnabled())
+        return false;
+
+    CSSParserValue* value = m_valueList->current();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    if (m_valueList->size() == 1 && value && (value->id == CSSValueAuto || value->id == CSSValueNone)) {
+        list->append(cssValuePool().createIdentifierValue(value->id));
+        addProperty(CSSPropertyTouchAction, list.release(), important);
+        m_valueList->next();
+        return true;
+    }
+
+    bool isValid = true;
+    while (isValid && value) {
+        switch (value->id) {
+        case CSSValuePanX:
+        case CSSValuePanY: {
+            RefPtr<CSSValue> panValue = cssValuePool().createIdentifierValue(value->id);
+            if (list->hasValue(panValue.get())) {
+                isValid = false;
+                break;
+            }
+            list->append(panValue.release());
+            break;
+        }
+        default:
+            isValid = false;
+            break;
+        }
+        if (isValid)
+            value = m_valueList->next();
+    }
+
+    if (list->length() && isValid) {
+        addProperty(CSSPropertyTouchAction, list.release(), important);
+        return true;
+    }
+
+    return false;
+}
+
+void BisonCSSParser::addTextDecorationProperty(CSSPropertyID propId, PassRefPtr<CSSValue> value, bool important)
 {
     // The text-decoration-line property takes priority over text-decoration, unless the latter has important priority set.
     if (propId == CSSPropertyTextDecoration && !important && !inShorthand()) {
@@ -9026,7 +8889,7 @@
     addProperty(propId, value, important);
 }
 
-bool CSSParser::parseTextDecoration(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseTextDecoration(CSSPropertyID propId, bool important)
 {
     if (propId == CSSPropertyTextDecorationLine
         && !RuntimeEnabledFeatures::css3TextDecorationsEnabled())
@@ -9039,7 +8902,7 @@
         return true;
     }
 
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
     bool isValid = true;
     while (isValid && value) {
         switch (value->id) {
@@ -9066,7 +8929,7 @@
     return false;
 }
 
-bool CSSParser::parseTextUnderlinePosition(bool important)
+bool BisonCSSParser::parseTextUnderlinePosition(bool important)
 {
     // The text-underline-position property has syntax "auto | [ under || [ left | right ] ]".
     // However, values 'left' and 'right' are not implemented yet, so we will parse syntax
@@ -9084,12 +8947,12 @@
     }
 }
 
-bool CSSParser::parseTextEmphasisStyle(bool important)
+bool BisonCSSParser::parseTextEmphasisStyle(bool important)
 {
     unsigned valueListSize = m_valueList->size();
 
-    RefPtr<CSSPrimitiveValue> fill;
-    RefPtr<CSSPrimitiveValue> shape;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> fill;
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> shape;
 
     for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) {
         if (value->unit == CSSPrimitiveValue::CSS_STRING) {
@@ -9123,7 +8986,7 @@
     }
 
     if (fill && shape) {
-        RefPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
+        RefPtrWillBeRawPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
         parsedValues->append(fill.release());
         parsedValues->append(shape.release());
         addProperty(CSSPropertyWebkitTextEmphasisStyle, parsedValues.release(), important);
@@ -9141,9 +9004,9 @@
     return false;
 }
 
-PassRefPtr<CSSValue> CSSParser::parseTextIndent()
+PassRefPtr<CSSValue> BisonCSSParser::parseTextIndent()
 {
-    RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
 
     // <length> | <percentage> | inherit
     if (m_valueList->size() == 1) {
@@ -9186,7 +9049,7 @@
     return 0;
 }
 
-bool CSSParser::parseLineBoxContain(bool important)
+bool BisonCSSParser::parseLineBoxContain(bool important)
 {
     LineBoxContain lineBoxContain = LineBoxContainNone;
 
@@ -9226,7 +9089,7 @@
     return true;
 }
 
-bool CSSParser::parseFontFeatureTag(CSSValueList* settings)
+bool BisonCSSParser::parseFontFeatureTag(CSSValueList* settings)
 {
     // Feature tag name consists of 4-letter characters.
     static const unsigned tagNameLength = 4;
@@ -9263,16 +9126,16 @@
     return true;
 }
 
-bool CSSParser::parseFontFeatureSettings(bool important)
+bool BisonCSSParser::parseFontFeatureSettings(bool important)
 {
     if (m_valueList->size() == 1 && m_valueList->current()->id == CSSValueNormal) {
-        RefPtr<CSSPrimitiveValue> normalValue = cssValuePool().createIdentifierValue(CSSValueNormal);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> normalValue = cssValuePool().createIdentifierValue(CSSValueNormal);
         m_valueList->next();
         addProperty(CSSPropertyWebkitFontFeatureSettings, normalValue.release(), important);
         return true;
     }
 
-    RefPtr<CSSValueList> settings = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> settings = CSSValueList::createCommaSeparated();
     for (CSSParserValue* value = m_valueList->current(); value; value = m_valueList->next()) {
         if (!parseFontFeatureTag(settings.get()))
             return false;
@@ -9289,9 +9152,9 @@
     return false;
 }
 
-bool CSSParser::parseFontVariantLigatures(bool important)
+bool BisonCSSParser::parseFontVariantLigatures(bool important)
 {
-    RefPtr<CSSValueList> ligatureValues = CSSValueList::createSpaceSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> ligatureValues = CSSValueList::createSpaceSeparated();
     bool sawCommonLigaturesValue = false;
     bool sawDiscretionaryLigaturesValue = false;
     bool sawHistoricalLigaturesValue = false;
@@ -9330,11 +9193,11 @@
     if (!ligatureValues->length())
         return false;
 
-    addProperty(CSSPropertyWebkitFontVariantLigatures, ligatureValues.release(), important);
+    addProperty(CSSPropertyFontVariantLigatures, ligatureValues.release(), important);
     return true;
 }
 
-bool CSSParser::parseCalculation(CSSParserValue* value, ValueRange range)
+bool BisonCSSParser::parseCalculation(CSSParserValue* value, ValueRange range)
 {
     ASSERT(isCalculation(value));
 
@@ -9353,27 +9216,27 @@
 
 #define END_TOKEN 0
 
-void CSSParser::ensureLineEndings()
+void BisonCSSParser::ensureLineEndings()
 {
     if (!m_lineEndings)
         m_lineEndings = lineEndings(*m_source);
 }
 
-CSSParserSelector* CSSParser::createFloatingSelectorWithTagName(const QualifiedName& tagQName)
+CSSParserSelector* BisonCSSParser::createFloatingSelectorWithTagName(const QualifiedName& tagQName)
 {
     CSSParserSelector* selector = new CSSParserSelector(tagQName);
     m_floatingSelectors.append(selector);
     return selector;
 }
 
-CSSParserSelector* CSSParser::createFloatingSelector()
+CSSParserSelector* BisonCSSParser::createFloatingSelector()
 {
     CSSParserSelector* selector = new CSSParserSelector;
     m_floatingSelectors.append(selector);
     return selector;
 }
 
-PassOwnPtr<CSSParserSelector> CSSParser::sinkFloatingSelector(CSSParserSelector* selector)
+PassOwnPtr<CSSParserSelector> BisonCSSParser::sinkFloatingSelector(CSSParserSelector* selector)
 {
     if (selector) {
         size_t index = m_floatingSelectors.reverseFind(selector);
@@ -9383,14 +9246,14 @@
     return adoptPtr(selector);
 }
 
-Vector<OwnPtr<CSSParserSelector> >* CSSParser::createFloatingSelectorVector()
+Vector<OwnPtr<CSSParserSelector> >* BisonCSSParser::createFloatingSelectorVector()
 {
     Vector<OwnPtr<CSSParserSelector> >* selectorVector = new Vector<OwnPtr<CSSParserSelector> >;
     m_floatingSelectorVectors.append(selectorVector);
     return selectorVector;
 }
 
-PassOwnPtr<Vector<OwnPtr<CSSParserSelector> > > CSSParser::sinkFloatingSelectorVector(Vector<OwnPtr<CSSParserSelector> >* selectorVector)
+PassOwnPtr<Vector<OwnPtr<CSSParserSelector> > > BisonCSSParser::sinkFloatingSelectorVector(Vector<OwnPtr<CSSParserSelector> >* selectorVector)
 {
     if (selectorVector) {
         size_t index = m_floatingSelectorVectors.reverseFind(selectorVector);
@@ -9400,14 +9263,14 @@
     return adoptPtr(selectorVector);
 }
 
-CSSParserValueList* CSSParser::createFloatingValueList()
+CSSParserValueList* BisonCSSParser::createFloatingValueList()
 {
     CSSParserValueList* list = new CSSParserValueList;
     m_floatingValueLists.append(list);
     return list;
 }
 
-PassOwnPtr<CSSParserValueList> CSSParser::sinkFloatingValueList(CSSParserValueList* list)
+PassOwnPtr<CSSParserValueList> BisonCSSParser::sinkFloatingValueList(CSSParserValueList* list)
 {
     if (list) {
         size_t index = m_floatingValueLists.reverseFind(list);
@@ -9417,14 +9280,14 @@
     return adoptPtr(list);
 }
 
-CSSParserFunction* CSSParser::createFloatingFunction()
+CSSParserFunction* BisonCSSParser::createFloatingFunction()
 {
     CSSParserFunction* function = new CSSParserFunction;
     m_floatingFunctions.append(function);
     return function;
 }
 
-CSSParserFunction* CSSParser::createFloatingFunction(const CSSParserString& name, PassOwnPtr<CSSParserValueList> args)
+CSSParserFunction* BisonCSSParser::createFloatingFunction(const CSSParserString& name, PassOwnPtr<CSSParserValueList> args)
 {
     CSSParserFunction* function = createFloatingFunction();
     function->name = name;
@@ -9432,7 +9295,7 @@
     return function;
 }
 
-PassOwnPtr<CSSParserFunction> CSSParser::sinkFloatingFunction(CSSParserFunction* function)
+PassOwnPtr<CSSParserFunction> BisonCSSParser::sinkFloatingFunction(CSSParserFunction* function)
 {
     if (function) {
         size_t index = m_floatingFunctions.reverseFind(function);
@@ -9442,7 +9305,7 @@
     return adoptPtr(function);
 }
 
-CSSParserValue& CSSParser::sinkFloatingValue(CSSParserValue& value)
+CSSParserValue& BisonCSSParser::sinkFloatingValue(CSSParserValue& value)
 {
     if (value.unit == CSSParserValue::Function) {
         size_t index = m_floatingFunctions.reverseFind(value.function);
@@ -9452,65 +9315,65 @@
     return value;
 }
 
-MediaQueryExp* CSSParser::createFloatingMediaQueryExp(const AtomicString& mediaFeature, CSSParserValueList* values)
+MediaQueryExp* BisonCSSParser::createFloatingMediaQueryExp(const AtomicString& mediaFeature, CSSParserValueList* values)
 {
     m_floatingMediaQueryExp = MediaQueryExp::create(mediaFeature, values);
     return m_floatingMediaQueryExp.get();
 }
 
-PassOwnPtr<MediaQueryExp> CSSParser::sinkFloatingMediaQueryExp(MediaQueryExp* expression)
+PassOwnPtr<MediaQueryExp> BisonCSSParser::sinkFloatingMediaQueryExp(MediaQueryExp* expression)
 {
     ASSERT_UNUSED(expression, expression == m_floatingMediaQueryExp);
     return m_floatingMediaQueryExp.release();
 }
 
-Vector<OwnPtr<MediaQueryExp> >* CSSParser::createFloatingMediaQueryExpList()
+Vector<OwnPtr<MediaQueryExp> >* BisonCSSParser::createFloatingMediaQueryExpList()
 {
     m_floatingMediaQueryExpList = adoptPtr(new Vector<OwnPtr<MediaQueryExp> >);
     return m_floatingMediaQueryExpList.get();
 }
 
-PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > CSSParser::sinkFloatingMediaQueryExpList(Vector<OwnPtr<MediaQueryExp> >* list)
+PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > BisonCSSParser::sinkFloatingMediaQueryExpList(Vector<OwnPtr<MediaQueryExp> >* list)
 {
     ASSERT_UNUSED(list, list == m_floatingMediaQueryExpList);
     return m_floatingMediaQueryExpList.release();
 }
 
-MediaQuery* CSSParser::createFloatingMediaQuery(MediaQuery::Restrictor restrictor, const AtomicString& mediaType, PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions)
+MediaQuery* BisonCSSParser::createFloatingMediaQuery(MediaQuery::Restrictor restrictor, const AtomicString& mediaType, PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions)
 {
     m_floatingMediaQuery = adoptPtr(new MediaQuery(restrictor, mediaType, expressions));
     return m_floatingMediaQuery.get();
 }
 
-MediaQuery* CSSParser::createFloatingMediaQuery(PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions)
+MediaQuery* BisonCSSParser::createFloatingMediaQuery(PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions)
 {
     return createFloatingMediaQuery(MediaQuery::None, AtomicString("all", AtomicString::ConstructFromLiteral), expressions);
 }
 
-MediaQuery* CSSParser::createFloatingNotAllQuery()
+MediaQuery* BisonCSSParser::createFloatingNotAllQuery()
 {
     return createFloatingMediaQuery(MediaQuery::Not, AtomicString("all", AtomicString::ConstructFromLiteral), sinkFloatingMediaQueryExpList(createFloatingMediaQueryExpList()));
 }
 
-PassOwnPtr<MediaQuery> CSSParser::sinkFloatingMediaQuery(MediaQuery* query)
+PassOwnPtr<MediaQuery> BisonCSSParser::sinkFloatingMediaQuery(MediaQuery* query)
 {
     ASSERT_UNUSED(query, query == m_floatingMediaQuery);
     return m_floatingMediaQuery.release();
 }
 
-Vector<RefPtr<StyleKeyframe> >* CSSParser::createFloatingKeyframeVector()
+Vector<RefPtr<StyleKeyframe> >* BisonCSSParser::createFloatingKeyframeVector()
 {
     m_floatingKeyframeVector = adoptPtr(new Vector<RefPtr<StyleKeyframe> >());
     return m_floatingKeyframeVector.get();
 }
 
-PassOwnPtr<Vector<RefPtr<StyleKeyframe> > > CSSParser::sinkFloatingKeyframeVector(Vector<RefPtr<StyleKeyframe> >* keyframeVector)
+PassOwnPtr<Vector<RefPtr<StyleKeyframe> > > BisonCSSParser::sinkFloatingKeyframeVector(Vector<RefPtr<StyleKeyframe> >* keyframeVector)
 {
     ASSERT_UNUSED(keyframeVector, m_floatingKeyframeVector == keyframeVector);
     return m_floatingKeyframeVector.release();
 }
 
-MediaQuerySet* CSSParser::createMediaQuerySet()
+MediaQuerySet* BisonCSSParser::createMediaQuerySet()
 {
     RefPtr<MediaQuerySet> queries = MediaQuerySet::create();
     MediaQuerySet* result = queries.get();
@@ -9518,7 +9381,7 @@
     return result;
 }
 
-StyleRuleBase* CSSParser::createImportRule(const CSSParserString& url, MediaQuerySet* media)
+StyleRuleBase* BisonCSSParser::createImportRule(const CSSParserString& url, MediaQuerySet* media)
 {
     if (!media || !m_allowImportRules)
         return 0;
@@ -9528,7 +9391,7 @@
     return result;
 }
 
-StyleRuleBase* CSSParser::createMediaRule(MediaQuerySet* media, RuleList* rules)
+StyleRuleBase* BisonCSSParser::createMediaRule(MediaQuerySet* media, RuleList* rules)
 {
     m_allowImportRules = m_allowNamespaceDeclarations = false;
     RefPtr<StyleRuleMedia> rule;
@@ -9543,7 +9406,7 @@
     return result;
 }
 
-StyleRuleBase* CSSParser::createSupportsRule(bool conditionIsSupported, RuleList* rules)
+StyleRuleBase* BisonCSSParser::createSupportsRule(bool conditionIsSupported, RuleList* rules)
 {
     m_allowImportRules = m_allowNamespaceDeclarations = false;
 
@@ -9571,7 +9434,7 @@
     return result;
 }
 
-void CSSParser::markSupportsRuleHeaderStart()
+void BisonCSSParser::markSupportsRuleHeaderStart()
 {
     if (!m_supportsRuleDataStack)
         m_supportsRuleDataStack = adoptPtr(new RuleSourceDataList());
@@ -9581,7 +9444,7 @@
     m_supportsRuleDataStack->append(data);
 }
 
-void CSSParser::markSupportsRuleHeaderEnd()
+void BisonCSSParser::markSupportsRuleHeaderEnd()
 {
     ASSERT(m_supportsRuleDataStack && !m_supportsRuleDataStack->isEmpty());
 
@@ -9591,7 +9454,7 @@
         m_supportsRuleDataStack->last()->ruleHeaderRange.end = m_tokenizer.tokenStart<UChar>() - m_tokenizer.m_dataStart16.get();
 }
 
-PassRefPtr<CSSRuleSourceData> CSSParser::popSupportsRuleData()
+PassRefPtr<CSSRuleSourceData> BisonCSSParser::popSupportsRuleData()
 {
     ASSERT(m_supportsRuleDataStack && !m_supportsRuleDataStack->isEmpty());
     RefPtr<CSSRuleSourceData> data = m_supportsRuleDataStack->last();
@@ -9599,7 +9462,7 @@
     return data.release();
 }
 
-CSSParser::RuleList* CSSParser::createRuleList()
+BisonCSSParser::RuleList* BisonCSSParser::createRuleList()
 {
     OwnPtr<RuleList> list = adoptPtr(new RuleList);
     RuleList* listPtr = list.get();
@@ -9608,7 +9471,7 @@
     return listPtr;
 }
 
-CSSParser::RuleList* CSSParser::appendRule(RuleList* ruleList, StyleRuleBase* rule)
+BisonCSSParser::RuleList* BisonCSSParser::appendRule(RuleList* ruleList, StyleRuleBase* rule)
 {
     if (rule) {
         if (!ruleList)
@@ -9636,7 +9499,7 @@
     }
 }
 
-void CSSParser::tokenToLowerCase(const CSSParserString& token)
+void BisonCSSParser::tokenToLowerCase(const CSSParserString& token)
 {
     size_t length = token.length();
     if (m_tokenizer.is8BitSource()) {
@@ -9648,7 +9511,7 @@
     }
 }
 
-void CSSParser::endInvalidRuleHeader()
+void BisonCSSParser::endInvalidRuleHeader()
 {
     if (m_ruleHeaderType == CSSRuleSourceData::UNKNOWN_RULE)
         return;
@@ -9661,26 +9524,25 @@
     else
         location.token.init(m_tokenizer.m_dataStart16.get() + m_ruleHeaderStartOffset, 0);
 
-    reportError(location, m_ruleHeaderType == CSSRuleSourceData::STYLE_RULE ? InvalidSelectorError : InvalidRuleError);
+    reportError(location, m_ruleHeaderType == CSSRuleSourceData::STYLE_RULE ? InvalidSelectorCSSError : InvalidRuleCSSError);
 
     endRuleHeader();
 }
 
-void CSSParser::reportError(const CSSParserLocation&, ErrorType)
+void BisonCSSParser::reportError(const CSSParserLocation&, CSSParserError)
 {
     // FIXME: error reporting temporatily disabled.
 }
 
-bool CSSParser::isLoggingErrors()
+bool BisonCSSParser::isLoggingErrors()
 {
     return m_logErrors && !m_ignoreErrors;
 }
 
-void CSSParser::logError(const String& message, const CSSParserLocation& location)
+void BisonCSSParser::logError(const String& message, const CSSParserLocation& location)
 {
     unsigned lineNumberInStyleSheet;
     unsigned columnNumber = 0;
-    PageConsole& console = m_styleSheet->singleOwnerDocument()->page()->console();
     if (InspectorInstrumentation::hasFrontends()) {
         ensureLineEndings();
         TextPosition tokenPosition = TextPosition::fromOffsetAndLineEndings(location.offset, *m_lineEndings);
@@ -9689,10 +9551,11 @@
     } else {
         lineNumberInStyleSheet = location.lineNumber;
     }
+    PageConsole& console = m_styleSheet->singleOwnerDocument()->frameHost()->console();
     console.addMessage(CSSMessageSource, WarningMessageLevel, message, m_styleSheet->baseURL().string(), lineNumberInStyleSheet + m_startPosition.m_line.zeroBasedInt() + 1, columnNumber + 1);
 }
 
-StyleRuleKeyframes* CSSParser::createKeyframesRule(const String& name, PassOwnPtr<Vector<RefPtr<StyleKeyframe> > > popKeyframes, bool isPrefixed)
+StyleRuleKeyframes* BisonCSSParser::createKeyframesRule(const String& name, PassOwnPtr<Vector<RefPtr<StyleKeyframe> > > popKeyframes, bool isPrefixed)
 {
     OwnPtr<Vector<RefPtr<StyleKeyframe> > > keyframes = popKeyframes;
     m_allowImportRules = m_allowNamespaceDeclarations = false;
@@ -9706,7 +9569,7 @@
     return rulePtr;
 }
 
-StyleRuleBase* CSSParser::createStyleRule(Vector<OwnPtr<CSSParserSelector> >* selectors)
+StyleRuleBase* BisonCSSParser::createStyleRule(Vector<OwnPtr<CSSParserSelector> >* selectors)
 {
     StyleRule* result = 0;
     if (selectors) {
@@ -9723,7 +9586,7 @@
     return result;
 }
 
-StyleRuleBase* CSSParser::createFontFaceRule()
+StyleRuleBase* BisonCSSParser::createFontFaceRule()
 {
     m_allowImportRules = m_allowNamespaceDeclarations = false;
     for (unsigned i = 0; i < m_parsedProperties.size(); ++i) {
@@ -9749,7 +9612,7 @@
     return result;
 }
 
-void CSSParser::addNamespace(const AtomicString& prefix, const AtomicString& uri)
+void BisonCSSParser::addNamespace(const AtomicString& prefix, const AtomicString& uri)
 {
     if (!m_styleSheet || !m_allowNamespaceDeclarations)
         return;
@@ -9759,14 +9622,14 @@
         m_defaultNamespace = uri;
 }
 
-QualifiedName CSSParser::determineNameInNamespace(const AtomicString& prefix, const AtomicString& localName)
+QualifiedName BisonCSSParser::determineNameInNamespace(const AtomicString& prefix, const AtomicString& localName)
 {
     if (!m_styleSheet)
         return QualifiedName(prefix, localName, m_defaultNamespace);
     return QualifiedName(prefix, localName, m_styleSheet->determineNamespace(prefix));
 }
 
-CSSParserSelector* CSSParser::rewriteSpecifiersWithNamespaceIfNeeded(CSSParserSelector* specifiers)
+CSSParserSelector* BisonCSSParser::rewriteSpecifiersWithNamespaceIfNeeded(CSSParserSelector* specifiers)
 {
     if (m_defaultNamespace != starAtom || specifiers->needsCrossingTreeScopeBoundary())
         return rewriteSpecifiersWithElementName(nullAtom, starAtom, specifiers, /*tagIsForNamespaceRule*/true);
@@ -9777,7 +9640,7 @@
     return specifiers;
 }
 
-CSSParserSelector* CSSParser::rewriteSpecifiersWithElementName(const AtomicString& namespacePrefix, const AtomicString& elementName, CSSParserSelector* specifiers, bool tagIsForNamespaceRule)
+CSSParserSelector* BisonCSSParser::rewriteSpecifiersWithElementName(const AtomicString& namespacePrefix, const AtomicString& elementName, CSSParserSelector* specifiers, bool tagIsForNamespaceRule)
 {
     AtomicString determinedNamespace = namespacePrefix != nullAtom && m_styleSheet ? m_styleSheet->determineNamespace(namespacePrefix) : m_defaultNamespace;
     QualifiedName tag(namespacePrefix, elementName, determinedNamespace);
@@ -9800,10 +9663,10 @@
     return specifiers;
 }
 
-CSSParserSelector* CSSParser::rewriteSpecifiersWithElementNameForCustomPseudoElement(const QualifiedName& tag, const AtomicString& elementName, CSSParserSelector* specifiers, bool tagIsForNamespaceRule)
+CSSParserSelector* BisonCSSParser::rewriteSpecifiersWithElementNameForCustomPseudoElement(const QualifiedName& tag, const AtomicString& elementName, CSSParserSelector* specifiers, bool tagIsForNamespaceRule)
 {
-    if (m_useCounter && specifiers->pseudoType() == CSSSelector::PseudoUserAgentCustomElement)
-        m_useCounter->count(UseCounter::CSSPseudoElementUserAgentCustomPseudo);
+    if (m_context.useCounter() && specifiers->pseudoType() == CSSSelector::PseudoUserAgentCustomElement)
+        m_context.useCounter()->count(UseCounter::CSSPseudoElementUserAgentCustomPseudo);
 
     CSSParserSelector* lastShadowPseudo = specifiers;
     CSSParserSelector* history = specifiers;
@@ -9827,7 +9690,7 @@
     return specifiers;
 }
 
-CSSParserSelector* CSSParser::rewriteSpecifiersWithElementNameForContentPseudoElement(const QualifiedName& tag, const AtomicString& elementName, CSSParserSelector* specifiers, bool tagIsForNamespaceRule)
+CSSParserSelector* BisonCSSParser::rewriteSpecifiersWithElementNameForContentPseudoElement(const QualifiedName& tag, const AtomicString& elementName, CSSParserSelector* specifiers, bool tagIsForNamespaceRule)
 {
     CSSParserSelector* last = specifiers;
     CSSParserSelector* history = specifiers;
@@ -9851,10 +9714,10 @@
     return specifiers;
 }
 
-CSSParserSelector* CSSParser::rewriteSpecifiersForShadowDistributed(CSSParserSelector* specifiers, CSSParserSelector* distributedPseudoElementSelector)
+CSSParserSelector* BisonCSSParser::rewriteSpecifiersForShadowDistributed(CSSParserSelector* specifiers, CSSParserSelector* distributedPseudoElementSelector)
 {
-    if (m_useCounter)
-        m_useCounter->count(UseCounter::CSSPseudoElementPrefixedDistributed);
+    if (m_context.useCounter())
+        m_context.useCounter()->count(UseCounter::CSSPseudoElementPrefixedDistributed);
     CSSParserSelector* argumentSelector = distributedPseudoElementSelector->functionArgumentSelector();
     ASSERT(argumentSelector);
     ASSERT(!specifiers->isDistributedPseudoElement());
@@ -9879,7 +9742,7 @@
     }
 }
 
-CSSParserSelector* CSSParser::rewriteSpecifiers(CSSParserSelector* specifiers, CSSParserSelector* newSpecifier)
+CSSParserSelector* BisonCSSParser::rewriteSpecifiers(CSSParserSelector* specifiers, CSSParserSelector* newSpecifier)
 {
     if (newSpecifier->needsCrossingTreeScopeBoundary()) {
         // Unknown pseudo element always goes at the top of selector chain.
@@ -9903,7 +9766,7 @@
     return specifiers;
 }
 
-StyleRuleBase* CSSParser::createPageRule(PassOwnPtr<CSSParserSelector> pageSelector)
+StyleRuleBase* BisonCSSParser::createPageRule(PassOwnPtr<CSSParserSelector> pageSelector)
 {
     // FIXME: Margin at-rules are ignored.
     m_allowImportRules = m_allowNamespaceDeclarations = false;
@@ -9921,33 +9784,7 @@
     return pageRule;
 }
 
-void CSSParser::setReusableRegionSelectorVector(Vector<OwnPtr<CSSParserSelector> >* selectors)
-{
-    if (selectors)
-        m_reusableRegionSelectorVector.swap(*selectors);
-}
-
-StyleRuleBase* CSSParser::createRegionRule(Vector<OwnPtr<CSSParserSelector> >* regionSelector, RuleList* rules)
-{
-    if (m_useCounter)
-        m_useCounter->count(UseCounter::CSSWebkitRegionAtRule);
-
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !regionSelector || !rules)
-        return 0;
-
-    m_allowImportRules = m_allowNamespaceDeclarations = false;
-
-    RefPtr<StyleRuleRegion> regionRule = StyleRuleRegion::create(regionSelector, *rules);
-
-    StyleRuleRegion* result = regionRule.get();
-    m_parsedRules.append(regionRule.release());
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->startEndUnknownRule();
-
-    return result;
-}
-
-StyleRuleBase* CSSParser::createMarginAtRule(CSSSelector::MarginBoxType /* marginBox */)
+StyleRuleBase* BisonCSSParser::createMarginAtRule(CSSSelector::MarginBoxType /* marginBox */)
 {
     // FIXME: Implement margin at-rule here, using:
     //        - marginBox: margin box
@@ -9958,18 +9795,18 @@
     return 0; // until this method is implemented.
 }
 
-void CSSParser::startDeclarationsForMarginBox()
+void BisonCSSParser::startDeclarationsForMarginBox()
 {
     m_numParsedPropertiesBeforeMarginBox = m_parsedProperties.size();
 }
 
-void CSSParser::endDeclarationsForMarginBox()
+void BisonCSSParser::endDeclarationsForMarginBox()
 {
     rollbackLastProperties(m_parsedProperties.size() - m_numParsedPropertiesBeforeMarginBox);
     m_numParsedPropertiesBeforeMarginBox = INVALID_NUM_PARSED_PROPERTIES;
 }
 
-void CSSParser::deleteFontFaceOnlyValues()
+void BisonCSSParser::deleteFontFaceOnlyValues()
 {
     ASSERT(m_hasFontFaceOnlyValues);
     for (unsigned i = 0; i < m_parsedProperties.size();) {
@@ -9982,7 +9819,7 @@
     }
 }
 
-StyleKeyframe* CSSParser::createKeyframe(CSSParserValueList* keys)
+StyleKeyframe* BisonCSSParser::createKeyframe(CSSParserValueList* keys)
 {
     OwnPtr<Vector<double> > keyVector = StyleKeyframe::createKeyList(keys);
     if (keyVector->isEmpty())
@@ -9999,93 +9836,93 @@
     return keyframePtr;
 }
 
-void CSSParser::invalidBlockHit()
+void BisonCSSParser::invalidBlockHit()
 {
     if (m_styleSheet && !m_hadSyntacticallyValidCSSRule)
         m_styleSheet->setHasSyntacticallyValidCSSHeader(false);
 }
 
-void CSSParser::startRule()
+void BisonCSSParser::startRule()
 {
-    if (!m_sourceDataHandler)
+    if (!m_observer)
         return;
 
     ASSERT(m_ruleHasHeader);
     m_ruleHasHeader = false;
 }
 
-void CSSParser::endRule(bool valid)
+void BisonCSSParser::endRule(bool valid)
 {
-    if (!m_sourceDataHandler)
+    if (!m_observer)
         return;
 
     if (m_ruleHasHeader)
-        m_sourceDataHandler->endRuleBody(m_tokenizer.safeUserStringTokenOffset(), !valid);
+        m_observer->endRuleBody(m_tokenizer.safeUserStringTokenOffset(), !valid);
     m_ruleHasHeader = true;
 }
 
-void CSSParser::startRuleHeader(CSSRuleSourceData::Type ruleType)
+void BisonCSSParser::startRuleHeader(CSSRuleSourceData::Type ruleType)
 {
     resumeErrorLogging();
     m_ruleHeaderType = ruleType;
     m_ruleHeaderStartOffset = m_tokenizer.safeUserStringTokenOffset();
     m_ruleHeaderStartLineNumber = m_tokenizer.m_tokenStartLineNumber;
-    if (m_sourceDataHandler) {
+    if (m_observer) {
         ASSERT(!m_ruleHasHeader);
-        m_sourceDataHandler->startRuleHeader(ruleType, m_ruleHeaderStartOffset);
+        m_observer->startRuleHeader(ruleType, m_ruleHeaderStartOffset);
         m_ruleHasHeader = true;
     }
 }
 
-void CSSParser::endRuleHeader()
+void BisonCSSParser::endRuleHeader()
 {
     ASSERT(m_ruleHeaderType != CSSRuleSourceData::UNKNOWN_RULE);
     m_ruleHeaderType = CSSRuleSourceData::UNKNOWN_RULE;
-    if (m_sourceDataHandler) {
+    if (m_observer) {
         ASSERT(m_ruleHasHeader);
-        m_sourceDataHandler->endRuleHeader(m_tokenizer.safeUserStringTokenOffset());
+        m_observer->endRuleHeader(m_tokenizer.safeUserStringTokenOffset());
     }
 }
 
-void CSSParser::startSelector()
+void BisonCSSParser::startSelector()
 {
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->startSelector(m_tokenizer.safeUserStringTokenOffset());
+    if (m_observer)
+        m_observer->startSelector(m_tokenizer.safeUserStringTokenOffset());
 }
 
-void CSSParser::endSelector()
+void BisonCSSParser::endSelector()
 {
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->endSelector(m_tokenizer.safeUserStringTokenOffset());
+    if (m_observer)
+        m_observer->endSelector(m_tokenizer.safeUserStringTokenOffset());
 }
 
-void CSSParser::startRuleBody()
+void BisonCSSParser::startRuleBody()
 {
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->startRuleBody(m_tokenizer.safeUserStringTokenOffset());
+    if (m_observer)
+        m_observer->startRuleBody(m_tokenizer.safeUserStringTokenOffset());
 }
 
-void CSSParser::startProperty()
+void BisonCSSParser::startProperty()
 {
     resumeErrorLogging();
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->startProperty(m_tokenizer.safeUserStringTokenOffset());
+    if (m_observer)
+        m_observer->startProperty(m_tokenizer.safeUserStringTokenOffset());
 }
 
-void CSSParser::endProperty(bool isImportantFound, bool isPropertyParsed, ErrorType errorType)
+void BisonCSSParser::endProperty(bool isImportantFound, bool isPropertyParsed, CSSParserError errorType)
 {
     m_id = CSSPropertyInvalid;
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->endProperty(isImportantFound, isPropertyParsed, m_tokenizer.safeUserStringTokenOffset(), errorType);
+    if (m_observer)
+        m_observer->endProperty(isImportantFound, isPropertyParsed, m_tokenizer.safeUserStringTokenOffset(), errorType);
 }
 
-void CSSParser::startEndUnknownRule()
+void BisonCSSParser::startEndUnknownRule()
 {
-    if (m_sourceDataHandler)
-        m_sourceDataHandler->startEndUnknownRule();
+    if (m_observer)
+        m_observer->startEndUnknownRule();
 }
 
-StyleRuleBase* CSSParser::createViewportRule()
+StyleRuleBase* BisonCSSParser::createViewportRule()
 {
     // Allow @viewport rules from UA stylesheets even if the feature is disabled.
     if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode()))
@@ -10104,7 +9941,7 @@
     return result;
 }
 
-bool CSSParser::parseViewportProperty(CSSPropertyID propId, bool important)
+bool BisonCSSParser::parseViewportProperty(CSSPropertyID propId, bool important)
 {
     ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode()));
 
@@ -10164,7 +10001,7 @@
     return false;
 }
 
-bool CSSParser::parseViewportShorthand(CSSPropertyID propId, CSSPropertyID first, CSSPropertyID second, bool important)
+bool BisonCSSParser::parseViewportShorthand(CSSPropertyID propId, CSSPropertyID first, CSSPropertyID second, bool important)
 {
     ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode()));
     unsigned numValues = m_valueList->size();
@@ -10255,161 +10092,6 @@
     return string.is8Bit() ? cssValueKeywordID(string.characters8(), length) : cssValueKeywordID(string.characters16(), length);
 }
 
-template <typename CharacterType>
-static inline bool isCSSTokenizerIdentifier(const CharacterType* characters, unsigned length)
-{
-    const CharacterType* end = characters + length;
-
-    // -?
-    if (characters != end && characters[0] == '-')
-        ++characters;
-
-    // {nmstart}
-    if (characters == end || !(characters[0] == '_' || characters[0] >= 128 || isASCIIAlpha(characters[0])))
-        return false;
-    ++characters;
-
-    // {nmchar}*
-    for (; characters != end; ++characters) {
-        if (!(characters[0] == '_' || characters[0] == '-' || characters[0] >= 128 || isASCIIAlphanumeric(characters[0])))
-            return false;
-    }
-
-    return true;
-}
-
-// "ident" from the CSS tokenizer, minus backslash-escape sequences
-static bool isCSSTokenizerIdentifier(const String& string)
-{
-    unsigned length = string.length();
-
-    if (!length)
-        return false;
-
-    if (string.is8Bit())
-        return isCSSTokenizerIdentifier(string.characters8(), length);
-    return isCSSTokenizerIdentifier(string.characters16(), length);
-}
-
-template <typename CharacterType>
-static inline bool isCSSTokenizerURL(const CharacterType* characters, unsigned length)
-{
-    const CharacterType* end = characters + length;
-
-    for (; characters != end; ++characters) {
-        CharacterType c = characters[0];
-        switch (c) {
-            case '!':
-            case '#':
-            case '$':
-            case '%':
-            case '&':
-                break;
-            default:
-                if (c < '*')
-                    return false;
-                if (c <= '~')
-                    break;
-                if (c < 128)
-                    return false;
-        }
-    }
-
-    return true;
-}
-
-// "url" from the CSS tokenizer, minus backslash-escape sequences
-static bool isCSSTokenizerURL(const String& string)
-{
-    unsigned length = string.length();
-
-    if (!length)
-        return true;
-
-    if (string.is8Bit())
-        return isCSSTokenizerURL(string.characters8(), length);
-    return isCSSTokenizerURL(string.characters16(), length);
-}
-
-
-template <typename CharacterType>
-static inline String quoteCSSStringInternal(const CharacterType* characters, unsigned length)
-{
-    // For efficiency, we first pre-calculate the length of the quoted string, then we build the actual one.
-    // Please see below for the actual logic.
-    unsigned quotedStringSize = 2; // Two quotes surrounding the entire string.
-    bool afterEscape = false;
-    for (unsigned i = 0; i < length; ++i) {
-        CharacterType ch = characters[i];
-        if (ch == '\\' || ch == '\'') {
-            quotedStringSize += 2;
-            afterEscape = false;
-        } else if (ch < 0x20 || ch == 0x7F) {
-            quotedStringSize += 2 + (ch >= 0x10);
-            afterEscape = true;
-        } else {
-            quotedStringSize += 1 + (afterEscape && (isASCIIHexDigit(ch) || ch == ' '));
-            afterEscape = false;
-        }
-    }
-
-    StringBuffer<CharacterType> buffer(quotedStringSize);
-    unsigned index = 0;
-    buffer[index++] = '\'';
-    afterEscape = false;
-    for (unsigned i = 0; i < length; ++i) {
-        CharacterType ch = characters[i];
-        if (ch == '\\' || ch == '\'') {
-            buffer[index++] = '\\';
-            buffer[index++] = ch;
-            afterEscape = false;
-        } else if (ch < 0x20 || ch == 0x7F) { // Control characters.
-            buffer[index++] = '\\';
-            placeByteAsHexCompressIfPossible(ch, buffer, index, Lowercase);
-            afterEscape = true;
-        } else {
-            // Space character may be required to separate backslash-escape sequence and normal characters.
-            if (afterEscape && (isASCIIHexDigit(ch) || ch == ' '))
-                buffer[index++] = ' ';
-            buffer[index++] = ch;
-            afterEscape = false;
-        }
-    }
-    buffer[index++] = '\'';
-
-    ASSERT(quotedStringSize == index);
-    return String::adopt(buffer);
-}
-
-// We use single quotes for now because markup.cpp uses double quotes.
-String quoteCSSString(const String& string)
-{
-    // This function expands each character to at most 3 characters ('\u0010' -> '\' '1' '0') as well as adds
-    // 2 quote characters (before and after). Make sure the resulting size (3 * length + 2) will not overflow unsigned.
-
-    unsigned length = string.length();
-
-    if (!length)
-        return String("\'\'");
-
-    if (length > std::numeric_limits<unsigned>::max() / 3 - 2)
-        return emptyString();
-
-    if (string.is8Bit())
-        return quoteCSSStringInternal(string.characters8(), length);
-    return quoteCSSStringInternal(string.characters16(), length);
-}
-
-String quoteCSSStringIfNeeded(const String& string)
-{
-    return isCSSTokenizerIdentifier(string) ? string : quoteCSSString(string);
-}
-
-String quoteCSSURLIfNeeded(const String& string)
-{
-    return isCSSTokenizerURL(string) ? string : quoteCSSString(string);
-}
-
 bool isValidNthToken(const CSSParserString& token)
 {
     // The tokenizer checks for the construct of an+b.
diff --git a/Source/core/css/CSSParser.h b/Source/core/css/parser/BisonCSSParser.h
similarity index 80%
rename from Source/core/css/CSSParser.h
rename to Source/core/css/parser/BisonCSSParser.h
index 5cea558..1a32e94 100644
--- a/Source/core/css/CSSParser.h
+++ b/Source/core/css/parser/BisonCSSParser.h
@@ -20,8 +20,8 @@
  * Boston, MA 02110-1301, USA.
  */
 
-#ifndef CSSParser_h
-#define CSSParser_h
+#ifndef BisonCSSParser_h
+#define BisonCSSParser_h
 
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
@@ -36,7 +36,7 @@
 #include "core/css/CSSTokenizer.h"
 #include "core/css/MediaQuery.h"
 #include "core/css/StylePropertySet.h"
-#include "core/frame/UseCounter.h"
+#include "core/css/parser/CSSParserObserver.h"
 #include "platform/graphics/Color.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
@@ -49,13 +49,12 @@
 class AnimationParseContext;
 class CSSArrayFunctionValue;
 class CSSBorderImageSliceValue;
-class CSSMixFunctionValue;
 class CSSPrimitiveValue;
 class CSSSelectorList;
-class CSSShaderValue;
 class CSSValue;
 class CSSValueList;
 class CSSBasicShape;
+class CSSBasicShapeInset;
 class Document;
 class Element;
 class ImmutableStylePropertySet;
@@ -68,6 +67,7 @@
 class StyleRuleKeyframes;
 class StyleKeyframe;
 class StyleSheetContents;
+class UseCounter;
 
 // FIXME: This class is shared with CSSTokenizer so should we rename it to CSSSourceLocation?
 struct CSSParserLocation {
@@ -76,40 +76,25 @@
     CSSParserString token;
 };
 
-class CSSParser {
-    friend inline int cssyylex(void*, CSSParser*);
+class BisonCSSParser {
+    friend inline int cssyylex(void*, BisonCSSParser*);
 
 public:
-    class SourceDataHandler;
-    enum ErrorType {
-        NoError,
-        PropertyDeclarationError,
-        InvalidPropertyValueError,
-        InvalidPropertyError,
-        InvalidSelectorError,
-        InvalidSupportsConditionError,
-        InvalidRuleError,
-        InvalidMediaQueryError,
-        InvalidKeyframeSelectorError,
-        InvalidSelectorPseudoError,
-        UnterminatedCommentError,
-        GeneralError
-    };
+    BisonCSSParser(const CSSParserContext&);
 
-    CSSParser(const CSSParserContext&, UseCounter* = 0);
+    ~BisonCSSParser();
 
-    ~CSSParser();
-
-    void parseSheet(StyleSheetContents*, const String&, const TextPosition& startPosition = TextPosition::minimumPosition(), SourceDataHandler* = 0, bool = false);
+    void parseSheet(StyleSheetContents*, const String&, const TextPosition& startPosition = TextPosition::minimumPosition(), CSSParserObserver* = 0, bool = false);
     PassRefPtr<StyleRuleBase> parseRule(StyleSheetContents*, const String&);
     PassRefPtr<StyleKeyframe> parseKeyframeRule(StyleSheetContents*, const String&);
     bool parseSupportsCondition(const String&);
     static bool parseValue(MutableStylePropertySet*, CSSPropertyID, const String&, bool important, CSSParserMode, StyleSheetContents*);
     static bool parseColor(RGBA32& color, const String&, bool strict = false);
     static bool parseSystemColor(RGBA32& color, const String&, Document*);
-    static PassRefPtr<CSSValueList> parseFontFaceValue(const AtomicString&);
-    PassRefPtr<CSSPrimitiveValue> parseValidPrimitive(CSSValueID ident, CSSParserValue*);
-    bool parseDeclaration(MutableStylePropertySet*, const String&, SourceDataHandler*, StyleSheetContents* contextStyleSheet);
+    static PassRefPtrWillBeRawPtr<CSSValueList> parseFontFaceValue(const AtomicString&);
+    static PassRefPtr<CSSValue> parseAnimationTimingFunctionValue(const String&);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parseValidPrimitive(CSSValueID ident, CSSParserValue*);
+    bool parseDeclaration(MutableStylePropertySet*, const String&, CSSParserObserver*, StyleSheetContents* contextStyleSheet);
     static PassRefPtr<ImmutableStylePropertySet> parseInlineStyleDeclaration(const String&, Element*);
     PassRefPtr<MediaQuerySet> parseMediaQueryList(const String&);
     PassOwnPtr<Vector<double> > parseKeyframeKeyList(const String&);
@@ -128,7 +113,6 @@
     bool parseQuotes(CSSPropertyID, bool important);
 
     static bool parseValue(MutableStylePropertySet*, CSSPropertyID, const String&, bool important, const Document&);
-    void storeVariableDeclaration(const CSSParserString&, PassOwnPtr<CSSParserValueList>, bool important);
 
     PassRefPtr<CSSValue> parseAttr(CSSParserValueList* args);
 
@@ -138,14 +122,14 @@
 
     enum FillPositionFlag { InvalidFillPosition = 0, AmbiguousFillPosition = 1, XFillPosition = 2, YFillPosition = 4 };
     enum FillPositionParsingMode { ResolveValuesAsPercent = 0, ResolveValuesAsKeyword = 1 };
-    PassRefPtr<CSSPrimitiveValue> parseFillPositionComponent(CSSParserValueList*, unsigned& cumulativeFlags, FillPositionFlag& individualFlag, FillPositionParsingMode = ResolveValuesAsPercent);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parseFillPositionComponent(CSSParserValueList*, unsigned& cumulativeFlags, FillPositionFlag& individualFlag, FillPositionParsingMode = ResolveValuesAsPercent);
     PassRefPtr<CSSValue> parseFillPositionX(CSSParserValueList*);
     PassRefPtr<CSSValue> parseFillPositionY(CSSParserValueList*);
     void parse2ValuesFillPosition(CSSParserValueList*, RefPtr<CSSValue>&, RefPtr<CSSValue>&);
     bool isPotentialPositionValue(CSSParserValue*);
     void parseFillPosition(CSSParserValueList*, RefPtr<CSSValue>&, RefPtr<CSSValue>&);
-    void parse3ValuesFillPosition(CSSParserValueList*, RefPtr<CSSValue>&, RefPtr<CSSValue>&, PassRefPtr<CSSPrimitiveValue>, PassRefPtr<CSSPrimitiveValue>);
-    void parse4ValuesFillPosition(CSSParserValueList*, RefPtr<CSSValue>&, RefPtr<CSSValue>&, PassRefPtr<CSSPrimitiveValue>, PassRefPtr<CSSPrimitiveValue>);
+    void parse3ValuesFillPosition(CSSParserValueList*, RefPtr<CSSValue>&, RefPtr<CSSValue>&, PassRefPtrWillBeRawPtr<CSSPrimitiveValue>, PassRefPtrWillBeRawPtr<CSSPrimitiveValue>);
+    void parse4ValuesFillPosition(CSSParserValueList*, RefPtr<CSSValue>&, RefPtr<CSSValue>&, PassRefPtrWillBeRawPtr<CSSPrimitiveValue>, PassRefPtrWillBeRawPtr<CSSPrimitiveValue>);
 
     void parseFillRepeat(RefPtr<CSSValue>&, RefPtr<CSSValue>&);
     PassRefPtr<CSSValue> parseFillSize(CSSPropertyID, bool &allowComma);
@@ -178,35 +162,43 @@
     bool parseColumnsShorthand(bool important);
 
     PassRefPtr<CSSValue> parseGridPosition();
-    bool parseIntegerOrStringFromGridPosition(RefPtr<CSSPrimitiveValue>& numericValue, RefPtr<CSSPrimitiveValue>& gridLineName);
+    bool parseIntegerOrStringFromGridPosition(RefPtrWillBeRawPtr<CSSPrimitiveValue>& numericValue, RefPtrWillBeRawPtr<CSSPrimitiveValue>& gridLineName);
     bool parseGridItemPositionShorthand(CSSPropertyID, bool important);
     bool parseGridAreaShorthand(bool important);
     bool parseSingleGridAreaLonghand(RefPtr<CSSValue>&);
     bool parseGridTrackList(CSSPropertyID, bool important);
     bool parseGridTrackRepeatFunction(CSSValueList&);
     PassRefPtr<CSSValue> parseGridTrackSize(CSSParserValueList& inputList);
-    PassRefPtr<CSSPrimitiveValue> parseGridBreadth(CSSParserValue*);
-    PassRefPtr<CSSValue> parseGridTemplate();
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parseGridBreadth(CSSParserValue*);
+    PassRefPtr<CSSValue> parseGridTemplateAreas();
     void parseGridLineNames(CSSParserValueList* inputList, CSSValueList&);
 
     bool parseClipShape(CSSPropertyID, bool important);
 
-    bool parseBasicShape(CSSPropertyID, bool important);
+    bool parseItemPositionOverflowPosition(CSSPropertyID, bool important);
+
+    PassRefPtr<CSSValue> parseShapeProperty(CSSPropertyID propId);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parseBasicShape();
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parseShapeRadius(CSSParserValue*);
+
     PassRefPtr<CSSBasicShape> parseBasicShapeRectangle(CSSParserValueList* args);
     PassRefPtr<CSSBasicShape> parseBasicShapeCircle(CSSParserValueList* args);
+    PassRefPtr<CSSBasicShape> parseDeprecatedBasicShapeCircle(CSSParserValueList* args);
     PassRefPtr<CSSBasicShape> parseBasicShapeEllipse(CSSParserValueList* args);
+    PassRefPtr<CSSBasicShape> parseDeprecatedBasicShapeEllipse(CSSParserValueList*);
     PassRefPtr<CSSBasicShape> parseBasicShapePolygon(CSSParserValueList* args);
     PassRefPtr<CSSBasicShape> parseBasicShapeInsetRectangle(CSSParserValueList* args);
+    PassRefPtr<CSSBasicShape> parseBasicShapeInset(CSSParserValueList* args);
 
     bool parseFont(bool important);
-    PassRefPtr<CSSValueList> parseFontFamily();
+    PassRefPtrWillBeRawPtr<CSSValueList> parseFontFamily();
 
     bool parseCounter(CSSPropertyID, int defaultValue, bool important);
     PassRefPtr<CSSValue> parseCounterContent(CSSParserValueList* args, bool counters);
 
     bool parseColorParameters(CSSParserValue*, int* colorValues, bool parseAlpha);
     bool parseHSLParameters(CSSParserValue*, double* colorValues, bool parseAlpha);
-    PassRefPtr<CSSPrimitiveValue> parseColor(CSSParserValue* = 0);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> parseColor(CSSParserValue* = 0);
     bool parseColorFromValue(CSSParserValue*, RGBA32&);
     void parseSelector(const String&, CSSSelectorList&);
 
@@ -228,13 +220,13 @@
     PassRefPtr<CSSValue> parsePaintOrder() const;
 
     // CSS3 Parsing Routines (for properties specific to CSS3)
-    PassRefPtr<CSSValueList> parseShadow(CSSParserValueList*, CSSPropertyID);
+    PassRefPtrWillBeRawPtr<CSSValueList> parseShadow(CSSParserValueList*, CSSPropertyID);
     bool parseBorderImageShorthand(CSSPropertyID, bool important);
     PassRefPtr<CSSValue> parseBorderImage(CSSPropertyID);
     bool parseBorderImageRepeat(RefPtr<CSSValue>&);
-    bool parseBorderImageSlice(CSSPropertyID, RefPtr<CSSBorderImageSliceValue>&);
-    bool parseBorderImageWidth(RefPtr<CSSPrimitiveValue>&);
-    bool parseBorderImageOutset(RefPtr<CSSPrimitiveValue>&);
+    bool parseBorderImageSlice(CSSPropertyID, RefPtrWillBeRawPtr<CSSBorderImageSliceValue>&);
+    bool parseBorderImageWidth(RefPtrWillBeRawPtr<CSSPrimitiveValue>&);
+    bool parseBorderImageOutset(RefPtrWillBeRawPtr<CSSPrimitiveValue>&);
     bool parseBorderRadius(CSSPropertyID, bool important);
 
     bool parseAspectRatio(bool important);
@@ -259,28 +251,21 @@
 
     PassRefPtr<CSSValue> parseImageSet(CSSParserValueList*);
 
-    PassRefPtr<CSSValueList> parseFilter();
-    PassRefPtr<CSSFilterValue> parseBuiltinFilterArguments(CSSParserValueList*, CSSFilterValue::FilterOperationType);
-    PassRefPtr<CSSMixFunctionValue> parseMixFunction(CSSParserValue*);
-    PassRefPtr<CSSArrayFunctionValue> parseCustomFilterArrayFunction(CSSParserValue*);
-    PassRefPtr<CSSValueList> parseCustomFilterTransform(CSSParserValueList*);
-    PassRefPtr<CSSValueList> parseCustomFilterParameters(CSSParserValueList*);
-    PassRefPtr<CSSFilterValue> parseCustomFilterFunctionWithAtRuleReferenceSyntax(CSSParserValue*);
-    PassRefPtr<CSSFilterValue> parseCustomFilterFunctionWithInlineSyntax(CSSParserValue*);
-    PassRefPtr<CSSFilterValue> parseCustomFilterFunction(CSSParserValue*);
-    bool parseFilterRuleSrc();
-    PassRefPtr<CSSShaderValue> parseFilterRuleSrcUriAndFormat(CSSParserValueList*);
+    PassRefPtrWillBeRawPtr<CSSValueList> parseFilter();
+    PassRefPtrWillBeRawPtr<CSSFilterValue> parseBuiltinFilterArguments(CSSParserValueList*, CSSFilterValue::FilterOperationType);
 
     static bool isBlendMode(CSSValueID);
     static bool isCompositeOperator(CSSValueID);
 
-    PassRefPtr<CSSValueList> parseTransform();
+    PassRefPtrWillBeRawPtr<CSSValueList> parseTransform();
     PassRefPtr<CSSValue> parseTransformValue(CSSParserValue*);
     bool parseTransformOrigin(CSSPropertyID propId, CSSPropertyID& propId1, CSSPropertyID& propId2, CSSPropertyID& propId3, RefPtr<CSSValue>&, RefPtr<CSSValue>&, RefPtr<CSSValue>&);
     bool parsePerspectiveOrigin(CSSPropertyID propId, CSSPropertyID& propId1, CSSPropertyID& propId2,  RefPtr<CSSValue>&, RefPtr<CSSValue>&);
 
     bool parseTextEmphasisStyle(bool important);
 
+    bool parseTouchAction(bool important);
+
     void addTextDecorationProperty(CSSPropertyID, PassRefPtr<CSSValue>, bool important);
     bool parseTextDecoration(CSSPropertyID propId, bool important);
     bool parseTextUnderlinePosition(bool important);
@@ -293,10 +278,6 @@
     bool parseFontFeatureTag(CSSValueList*);
     bool parseFontFeatureSettings(bool important);
 
-    bool parseFlowThread(const String& flowName);
-    bool parseFlowThread(CSSPropertyID, bool important);
-    bool parseRegionThread(CSSPropertyID, bool important);
-
     bool parseFontVariantLigatures(bool important);
 
     bool parseGeneratedImage(CSSParserValueList*, RefPtr<CSSValue>&);
@@ -329,14 +310,12 @@
     StyleRuleBase* createStyleRule(Vector<OwnPtr<CSSParserSelector> >* selectors);
     StyleRuleBase* createFontFaceRule();
     StyleRuleBase* createPageRule(PassOwnPtr<CSSParserSelector> pageSelector);
-    StyleRuleBase* createRegionRule(Vector<OwnPtr<CSSParserSelector> >* regionSelector, RuleList* rules);
     StyleRuleBase* createMarginAtRule(CSSSelector::MarginBoxType);
     StyleRuleBase* createSupportsRule(bool conditionIsSupported, RuleList*);
     void markSupportsRuleHeaderStart();
     void markSupportsRuleHeaderEnd();
     PassRefPtr<CSSRuleSourceData> popSupportsRuleData();
     StyleRuleBase* createHostRule(RuleList* rules);
-    StyleRuleBase* createFilterRule(const CSSParserString&);
 
     void startDeclarationsForMarginBox();
     void endDeclarationsForMarginBox();
@@ -367,9 +346,6 @@
 
     Vector<OwnPtr<CSSParserSelector> >* reusableSelectorVector() { return &m_reusableSelectorVector; }
 
-    void setReusableRegionSelectorVector(Vector<OwnPtr<CSSParserSelector> >* selectors);
-    Vector<OwnPtr<CSSParserSelector> >* reusableRegionSelectorVector() { return &m_reusableRegionSelectorVector; }
-
     void clearProperties();
 
     PassRefPtr<ImmutableStylePropertySet> createStylePropertySet();
@@ -400,13 +376,12 @@
     bool m_logErrors;
     bool m_ignoreErrors;
 
-    bool m_inFilterRule;
-
     AtomicString m_defaultNamespace;
 
     // tokenizer methods and data
-    SourceDataHandler* m_sourceDataHandler;
+    CSSParserObserver* m_observer;
 
+    // Local functions which just call into CSSParserObserver if non-null.
     void startRule();
     void endRule(bool valid);
     void startRuleHeader(CSSRuleSourceData::Type);
@@ -415,11 +390,11 @@
     void endSelector();
     void startRuleBody();
     void startProperty();
-    void endProperty(bool isImportantFound, bool isPropertyParsed, ErrorType = NoError);
+    void endProperty(bool isImportantFound, bool isPropertyParsed, CSSParserError = NoCSSError);
     void startEndUnknownRule();
 
     void endInvalidRuleHeader();
-    void reportError(const CSSParserLocation&, ErrorType = GeneralError);
+    void reportError(const CSSParserLocation&, CSSParserError = GeneralCSSError);
     void resumeErrorLogging() { m_ignoreErrors = false; }
     void setLocationLabel(const CSSParserLocation& location) { m_locationLabel = location; }
     const CSSParserLocation& lastLocationLabel() const { return m_locationLabel; }
@@ -430,11 +405,8 @@
     void markViewportRuleBodyEnd() { m_inViewport = false; }
     StyleRuleBase* createViewportRule();
 
-    PassRefPtr<CSSPrimitiveValue> createPrimitiveNumericValue(CSSParserValue*);
-    PassRefPtr<CSSPrimitiveValue> createPrimitiveStringValue(CSSParserValue*);
-    PassRefPtr<CSSPrimitiveValue> createPrimitiveVariableNameValue(CSSParserValue*);
-
-    static KURL completeURL(const CSSParserContext&, const String& url);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createPrimitiveNumericValue(CSSParserValue*);
+    PassRefPtrWillBeRawPtr<CSSPrimitiveValue> createPrimitiveStringValue(CSSParserValue*);
 
     CSSParserLocation currentLocation() { return m_tokenizer.currentLocation(); }
 
@@ -447,10 +419,10 @@
     class ImplicitScope {
         WTF_MAKE_NONCOPYABLE(ImplicitScope);
     public:
-        ImplicitScope(WebCore::CSSParser* parser, PropertyType propertyType)
+        ImplicitScope(WebCore::BisonCSSParser* parser, PropertyType propertyType)
             : m_parser(parser)
         {
-            m_parser->m_implicitShorthand = propertyType == CSSParser::PropertyImplicit;
+            m_parser->m_implicitShorthand = propertyType == BisonCSSParser::PropertyImplicit;
         }
 
         ~ImplicitScope()
@@ -459,13 +431,13 @@
         }
 
     private:
-        WebCore::CSSParser* m_parser;
+        WebCore::BisonCSSParser* m_parser;
     };
 
     class StyleDeclarationScope {
         WTF_MAKE_NONCOPYABLE(StyleDeclarationScope);
     public:
-        StyleDeclarationScope(CSSParser* parser, const StylePropertySet* declaration)
+        StyleDeclarationScope(BisonCSSParser* parser, const StylePropertySet* declaration)
             : m_parser(parser)
             , m_mode(declaration->cssParserMode())
         {
@@ -482,7 +454,7 @@
         }
 
     private:
-        CSSParser* m_parser;
+        BisonCSSParser* m_parser;
         CSSParserMode m_mode;
     };
 
@@ -512,6 +484,8 @@
     bool parseValue(MutableStylePropertySet*, CSSPropertyID, const String&, bool important, StyleSheetContents* contextStyleSheet);
     PassRefPtr<ImmutableStylePropertySet> parseDeclaration(const String&, StyleSheetContents* contextStyleSheet);
 
+    PassRefPtr<CSSBasicShape> parseInsetRoundedCorners(PassRefPtr<CSSBasicShapeInset>, CSSParserValueList*);
+
     enum SizeParameterType {
         None,
         Auto,
@@ -566,9 +540,8 @@
     OwnPtr<Vector<RefPtr<StyleKeyframe> > > m_floatingKeyframeVector;
 
     Vector<OwnPtr<CSSParserSelector> > m_reusableSelectorVector;
-    Vector<OwnPtr<CSSParserSelector> > m_reusableRegionSelectorVector;
 
-    RefPtr<CSSCalcValue> m_parsedCalculation;
+    RefPtrWillBePersistent<CSSCalcValue> m_parsedCalculation;
 
     OwnPtr<RuleSourceDataList> m_supportsRuleDataStack;
 
@@ -608,13 +581,11 @@
     inline bool validUnit(CSSParserValue* value, Units unitflags, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue) { return validUnit(value, unitflags, m_context.mode(), releaseCalc); }
     bool validUnit(CSSParserValue*, Units, CSSParserMode, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue);
 
-    bool parseBorderImageQuad(Units, RefPtr<CSSPrimitiveValue>&);
+    bool parseBorderImageQuad(Units, RefPtrWillBeRawPtr<CSSPrimitiveValue>&);
     int colorIntFromValue(CSSParserValue*);
     double parsedDouble(CSSParserValue*, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue);
     bool isCalculation(CSSParserValue*);
 
-    UseCounter* m_useCounter;
-
     CSSTokenizer m_tokenizer;
 
     friend class TransformOperationInfo;
@@ -628,7 +599,7 @@
 class ShorthandScope {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    ShorthandScope(CSSParser* parser, CSSPropertyID propId) : m_parser(parser)
+    ShorthandScope(BisonCSSParser* parser, CSSPropertyID propId) : m_parser(parser)
     {
         if (!(m_parser->m_inParseShorthand++))
             m_parser->m_currentShorthand = propId;
@@ -640,35 +611,16 @@
     }
 
 private:
-    CSSParser* m_parser;
+    BisonCSSParser* m_parser;
 };
 
-class CSSParser::SourceDataHandler {
-public:
-    virtual void startRuleHeader(CSSRuleSourceData::Type, unsigned offset) = 0;
-    virtual void endRuleHeader(unsigned offset) = 0;
-    virtual void startSelector(unsigned offset) = 0;
-    virtual void endSelector(unsigned offset) = 0;
-    virtual void startRuleBody(unsigned offset) = 0;
-    virtual void endRuleBody(unsigned offset, bool error) = 0;
-    virtual void startEndUnknownRule() = 0;
-    virtual void startProperty(unsigned offset) = 0;
-    virtual void endProperty(bool isImportant, bool isParsed, unsigned offset, CSSParser::ErrorType) = 0;
-    virtual void startComment(unsigned offset) = 0;
-    virtual void endComment(unsigned offset) = 0;
-};
-
-String quoteCSSString(const String&);
-String quoteCSSStringIfNeeded(const String&);
-String quoteCSSURLIfNeeded(const String&);
-
 bool isValidNthToken(const CSSParserString&);
 
-inline int cssyylex(void* yylval, CSSParser* parser)
+inline int cssyylex(void* yylval, BisonCSSParser* parser)
 {
     return parser->m_tokenizer.lex(yylval);
 }
 
 } // namespace WebCore
 
-#endif // CSSParser_h
+#endif // BisonCSSParser_h
diff --git a/Source/core/rendering/LayoutIndicator.cpp b/Source/core/css/parser/CSSParserIdioms.h
similarity index 85%
copy from Source/core/rendering/LayoutIndicator.cpp
copy to Source/core/css/parser/CSSParserIdioms.h
index a57c53c..d0e0b24 100644
--- a/Source/core/rendering/LayoutIndicator.cpp
+++ b/Source/core/css/parser/CSSParserIdioms.h
@@ -28,15 +28,20 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/rendering/LayoutIndicator.h"
+#ifndef CSSParserIdioms_h
+#define CSSParserIdioms_h
+
+#include "wtf/unicode/Unicode.h"
 
 namespace WebCore {
 
-#ifndef NDEBUG
-
-size_t LayoutIndicator::s_inLayout = 0;
-
-#endif
+// Space characters as defined by the CSS specification.
+// http://www.w3.org/TR/css3-syntax/
+inline bool isCSSSpace(UChar c)
+{
+    return c == ' ' || c == '\t' || c == '\n';
+}
 
 }
+
+#endif
diff --git a/Source/core/css/parser/CSSParserObserver.h b/Source/core/css/parser/CSSParserObserver.h
new file mode 100644
index 0000000..c795f50
--- /dev/null
+++ b/Source/core/css/parser/CSSParserObserver.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2009 - 2010  Torch Mobile (Beijing) Co. Ltd. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef CSSParserObserver_h
+#define CSSParserObserver_h
+
+#include "core/css/CSSPropertySourceData.h"
+
+namespace WebCore {
+
+// FIXME: Although the parser produces these, they're all ignored!
+enum CSSParserError {
+    NoCSSError,
+    PropertyDeclarationCSSError,
+    InvalidPropertyValueCSSError,
+    InvalidPropertyCSSError,
+    InvalidSelectorCSSError,
+    InvalidSupportsConditionCSSError,
+    InvalidRuleCSSError,
+    InvalidMediaQueryCSSError,
+    InvalidKeyframeSelectorCSSError,
+    InvalidSelectorPseudoCSSError,
+    UnterminatedCommentCSSError,
+    GeneralCSSError
+};
+
+// FIXME: What are these actually used for? There is probably
+// a better way for the parser to communicate this information
+// to the Inspector.
+
+// This only implemented by StyleSheetHandler in InspectorStyleSheet.cpp.
+class CSSParserObserver {
+public:
+    virtual void startRuleHeader(CSSRuleSourceData::Type, unsigned offset) = 0;
+    virtual void endRuleHeader(unsigned offset) = 0;
+    virtual void startSelector(unsigned offset) = 0;
+    virtual void endSelector(unsigned offset) = 0;
+    virtual void startRuleBody(unsigned offset) = 0;
+    virtual void endRuleBody(unsigned offset, bool error) = 0;
+    virtual void startEndUnknownRule() = 0;
+    virtual void startProperty(unsigned offset) = 0;
+    virtual void endProperty(bool isImportant, bool isParsed, unsigned offset, CSSParserError) = 0;
+    virtual void startComment(unsigned offset) = 0;
+    virtual void endComment(unsigned offset) = 0;
+};
+
+} // namespace WebCore
+
+#endif // CSSParserObserver_h
diff --git a/Source/core/css/resolver/AnimatedStyleBuilder.cpp b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
index dbfd63b..c193849 100644
--- a/Source/core/css/resolver/AnimatedStyleBuilder.cpp
+++ b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
@@ -134,12 +134,12 @@
         state.styleMap().mapFillSize(property, fillLayer, toAnimatableUnknown(value)->toCSSValue().get());
 }
 
-SVGLength animatableValueToNonNegativeSVGLength(const AnimatableValue* value)
+PassRefPtr<SVGLength> animatableValueToNonNegativeSVGLength(const AnimatableValue* value)
 {
-    SVGLength length = toAnimatableSVGLength(value)->toSVGLength();
-    if (length.valueInSpecifiedUnits() < 0)
-        length.setValueInSpecifiedUnits(0);
-    return length;
+    RefPtr<SVGLength> length = toAnimatableSVGLength(value)->toSVGLength();
+    if (length->valueInSpecifiedUnits() < 0)
+        length->setValueInSpecifiedUnits(0);
+    return length.release();
 }
 
 template <CSSPropertyID property>
@@ -230,6 +230,7 @@
 // FIXME: Generate this function.
 void AnimatedStyleBuilder::applyProperty(CSSPropertyID property, StyleResolverState& state, const AnimatableValue* value)
 {
+    ASSERT(CSSAnimations::isAnimatableProperty(property));
     if (value->isUnknown()) {
         StyleBuilder::applyProperty(property, state, toAnimatableUnknown(value)->toCSSValue().get());
         return;
@@ -443,7 +444,7 @@
         style->setStopOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
         return;
     case CSSPropertyStrokeDasharray:
-        style->setStrokeDashArray(toAnimatableStrokeDasharrayList(value)->toSVGLengthVector());
+        style->setStrokeDashArray(toAnimatableStrokeDasharrayList(value)->toSVGLengthList());
         return;
     case CSSPropertyStrokeDashoffset:
         style->setStrokeDashOffset(toAnimatableSVGLength(value)->toSVGLength());
@@ -589,7 +590,6 @@
         style->setZoom(clampTo<float>(toAnimatableDouble(value)->toDouble(), std::numeric_limits<float>::denorm_min()));
         return;
     default:
-        ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Unable to apply AnimatableValue to RenderStyle: %s", getPropertyNameString(property).utf8().data());
         ASSERT_NOT_REACHED();
     }
 }
diff --git a/Source/core/css/resolver/CSSToStyleMap.cpp b/Source/core/css/resolver/CSSToStyleMap.cpp
index 33dceb0..406b16c 100644
--- a/Source/core/css/resolver/CSSToStyleMap.cpp
+++ b/Source/core/css/resolver/CSSToStyleMap.cpp
@@ -29,6 +29,7 @@
 #include "core/css/resolver/CSSToStyleMap.h"
 
 #include "CSSValueKeywords.h"
+#include "core/animation/css/CSSAnimationData.h"
 #include "core/css/CSSBorderImageSliceValue.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
@@ -36,7 +37,6 @@
 #include "core/css/Pair.h"
 #include "core/css/Rect.h"
 #include "core/css/resolver/StyleResolverState.h"
-#include "core/platform/animation/CSSAnimationData.h"
 #include "core/rendering/style/BorderImageLengthBox.h"
 #include "core/rendering/style/FillLayer.h"
 
@@ -211,9 +211,6 @@
         secondLength = Length();
     }
 
-    if (firstLength.isUndefined() || secondLength.isUndefined())
-        return;
-
     b.setWidth(firstLength);
     b.setHeight(secondLength);
     layer->setSizeLength(b);
@@ -221,6 +218,11 @@
 
 void CSSToStyleMap::mapFillXPosition(CSSPropertyID propertyID, FillLayer* layer, CSSValue* value) const
 {
+    if (value->isInitialValue()) {
+        layer->setXPosition(FillLayer::initialFillXPosition(layer->type()));
+        return;
+    }
+
     if (!value->isPrimitiveValue())
         return;
 
@@ -232,7 +234,6 @@
     }
 
     Length length = primitiveValue->convertToLength<FixedConversion | PercentConversion>(cssToLengthConversionData());
-    ASSERT(!length.isUndefined());
 
     layer->setXPosition(length);
     if (pair)
@@ -241,6 +242,11 @@
 
 void CSSToStyleMap::mapFillYPosition(CSSPropertyID propertyID, FillLayer* layer, CSSValue* value) const
 {
+    if (value->isInitialValue()) {
+        layer->setYPosition(FillLayer::initialFillYPosition(layer->type()));
+        return;
+    }
+
     if (!value->isPrimitiveValue())
         return;
 
@@ -252,7 +258,6 @@
     }
 
     Length length = primitiveValue->convertToLength<FixedConversion | PercentConversion>(cssToLengthConversionData());
-    ASSERT(!length.isUndefined());
 
     layer->setYPosition(length);
     if (pair)
@@ -443,50 +448,58 @@
     }
 }
 
-void CSSToStyleMap::mapAnimationTimingFunction(CSSAnimationData* animation, CSSValue* value) const
+PassRefPtr<TimingFunction> CSSToStyleMap::animationTimingFunction(CSSValue* value, bool allowInitial)
 {
-    if (value->isInitialValue()) {
-        animation->setTimingFunction(CSSAnimationData::initialAnimationTimingFunction());
-        return;
+    if (allowInitial && value->isInitialValue()) {
+        return CSSAnimationData::initialAnimationTimingFunction();
     }
 
     if (value->isPrimitiveValue()) {
         CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
         switch (primitiveValue->getValueID()) {
         case CSSValueLinear:
-            animation->setTimingFunction(LinearTimingFunction::create());
+            return LinearTimingFunction::create();
             break;
         case CSSValueEase:
-            animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease));
+            return CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease);
             break;
         case CSSValueEaseIn:
-            animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn));
+            return CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
             break;
         case CSSValueEaseOut:
-            animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut));
+            return CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
             break;
         case CSSValueEaseInOut:
-            animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut));
+            return CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut);
             break;
         case CSSValueStepStart:
-            animation->setTimingFunction(StepsTimingFunction::preset(StepsTimingFunction::Start));
+            return StepsTimingFunction::preset(StepsTimingFunction::Start);
             break;
         case CSSValueStepEnd:
-            animation->setTimingFunction(StepsTimingFunction::preset(StepsTimingFunction::End));
+            return StepsTimingFunction::preset(StepsTimingFunction::End);
             break;
         default:
             break;
         }
-        return;
+        return 0;
     }
 
     if (value->isCubicBezierTimingFunctionValue()) {
         CSSCubicBezierTimingFunctionValue* cubicTimingFunction = toCSSCubicBezierTimingFunctionValue(value);
-        animation->setTimingFunction(CubicBezierTimingFunction::create(cubicTimingFunction->x1(), cubicTimingFunction->y1(), cubicTimingFunction->x2(), cubicTimingFunction->y2()));
+        return CubicBezierTimingFunction::create(cubicTimingFunction->x1(), cubicTimingFunction->y1(), cubicTimingFunction->x2(), cubicTimingFunction->y2());
     } else if (value->isStepsTimingFunctionValue()) {
         CSSStepsTimingFunctionValue* stepsTimingFunction = toCSSStepsTimingFunctionValue(value);
-        animation->setTimingFunction(StepsTimingFunction::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart()));
+        return StepsTimingFunction::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart());
     }
+
+    return 0;
+}
+
+void CSSToStyleMap::mapAnimationTimingFunction(CSSAnimationData* animation, CSSValue* value) const
+{
+    RefPtr<TimingFunction> timingFunction = animationTimingFunction(value, true);
+    if (timingFunction)
+        animation->setTimingFunction(timingFunction);
 }
 
 void CSSToStyleMap::mapNinePieceImage(RenderStyle* mutableStyle, CSSPropertyID property, CSSValue* value, NinePieceImage& image)
diff --git a/Source/core/css/resolver/CSSToStyleMap.h b/Source/core/css/resolver/CSSToStyleMap.h
index b994b6f..b84b025 100644
--- a/Source/core/css/resolver/CSSToStyleMap.h
+++ b/Source/core/css/resolver/CSSToStyleMap.h
@@ -24,6 +24,7 @@
 
 #include "CSSPropertyNames.h"
 #include "core/css/resolver/ElementStyleResources.h"
+#include "platform/animation/TimingFunction.h"
 #include "wtf/Noncopyable.h"
 
 namespace WebCore {
@@ -68,6 +69,7 @@
     void mapAnimationName(CSSAnimationData*, CSSValue*) const;
     void mapAnimationPlayState(CSSAnimationData*, CSSValue*) const;
     void mapAnimationProperty(CSSAnimationData*, CSSValue*) const;
+    static PassRefPtr<TimingFunction> animationTimingFunction(CSSValue*, bool allowInitial);
     void mapAnimationTimingFunction(CSSAnimationData*, CSSValue*) const;
 
     void mapNinePieceImage(RenderStyle* mutableStyle, CSSPropertyID, CSSValue*, NinePieceImage&);
diff --git a/Source/core/css/resolver/ElementStyleResources.cpp b/Source/core/css/resolver/ElementStyleResources.cpp
index d8b0817..2eb83af 100644
--- a/Source/core/css/resolver/ElementStyleResources.cpp
+++ b/Source/core/css/resolver/ElementStyleResources.cpp
@@ -33,8 +33,7 @@
 namespace WebCore {
 
 ElementStyleResources::ElementStyleResources()
-    : m_hasNewCustomFilterProgram(false)
-    , m_deviceScaleFactor(1)
+    : m_deviceScaleFactor(1)
 {
 }
 
diff --git a/Source/core/css/resolver/ElementStyleResources.h b/Source/core/css/resolver/ElementStyleResources.h
index 354b022..4049452 100644
--- a/Source/core/css/resolver/ElementStyleResources.h
+++ b/Source/core/css/resolver/ElementStyleResources.h
@@ -24,6 +24,7 @@
 #define ElementStyleResources_h
 
 #include "CSSPropertyNames.h"
+#include "heap/Handle.h"
 #include "platform/graphics/Color.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
@@ -40,7 +41,7 @@
 class StyleImage;
 class TextLinkColors;
 
-typedef HashMap<FilterOperation*, RefPtr<CSSSVGDocumentValue> > PendingSVGDocumentMap;
+typedef WillBePersistentHeapHashMap<FilterOperation*, RefPtrWillBeMember<CSSSVGDocumentValue> > PendingSVGDocumentMap;
 typedef HashMap<CSSPropertyID, RefPtr<CSSValue> > PendingImagePropertyMap;
 
 // Holds information about resources, requested by stylesheets.
@@ -60,9 +61,6 @@
     const PendingImagePropertyMap& pendingImageProperties() const { return m_pendingImageProperties; }
     const PendingSVGDocumentMap& pendingSVGDocuments() const { return m_pendingSVGDocuments; }
 
-    void setHasNewCustomFilterProgram(bool hasNewCustomFilterProgram) { m_hasNewCustomFilterProgram = hasNewCustomFilterProgram; }
-    bool hasNewCustomFilterProgram() const { return m_hasNewCustomFilterProgram; }
-
     float deviceScaleFactor() const { return m_deviceScaleFactor; }
     void setDeviceScaleFactor(float deviceScaleFactor) { m_deviceScaleFactor = deviceScaleFactor; }
 
@@ -71,7 +69,6 @@
 private:
     PendingImagePropertyMap m_pendingImageProperties;
     PendingSVGDocumentMap m_pendingSVGDocuments;
-    bool m_hasNewCustomFilterProgram;
     float m_deviceScaleFactor;
 };
 
diff --git a/Source/core/css/resolver/FilterOperationResolver.cpp b/Source/core/css/resolver/FilterOperationResolver.cpp
index 37706e6..167558d 100644
--- a/Source/core/css/resolver/FilterOperationResolver.cpp
+++ b/Source/core/css/resolver/FilterOperationResolver.cpp
@@ -30,23 +30,12 @@
 #include "core/css/resolver/FilterOperationResolver.h"
 
 #include "core/css/CSSFilterValue.h"
-#include "core/css/CSSMixFunctionValue.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
-#include "core/css/CSSShaderValue.h"
 #include "core/css/CSSShadowValue.h"
 #include "core/css/resolver/TransformBuilder.h"
-#include "core/rendering/style/StyleCustomFilterProgram.h"
-#include "core/rendering/style/StyleShader.h"
 #include "core/rendering/svg/ReferenceFilterBuilder.h"
 #include "core/svg/SVGURIReference.h"
-#include "platform/graphics/filters/custom/CustomFilterArrayParameter.h"
-#include "platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "platform/graphics/filters/custom/CustomFilterNumberParameter.h"
-#include "platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "platform/graphics/filters/custom/CustomFilterTransformParameter.h"
 
 namespace WebCore {
 
@@ -75,277 +64,12 @@
         return FilterOperation::BLUR;
     case CSSFilterValue::DropShadowFilterOperation:
         return FilterOperation::DROP_SHADOW;
-    case CSSFilterValue::CustomFilterOperation:
-        return FilterOperation::CUSTOM;
     case CSSFilterValue::UnknownFilterOperation:
         return FilterOperation::NONE;
     }
     return FilterOperation::NONE;
 }
 
-static StyleShader* styleShader(CSSValue* value)
-{
-    if (value->isShaderValue())
-        return toCSSShaderValue(value)->cachedOrPendingShader();
-    return 0;
-}
-
-static PassRefPtr<CustomFilterParameter> parseCustomFilterArrayParameter(const String& name, CSSValueList* values)
-{
-    RefPtr<CustomFilterArrayParameter> arrayParameter = CustomFilterArrayParameter::create(name);
-    for (unsigned i = 0, length = values->length(); i < length; ++i) {
-        CSSValue* value = values->itemWithoutBoundsCheck(i);
-        if (!value->isPrimitiveValue())
-            return 0;
-        CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-        if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
-            return 0;
-        arrayParameter->addValue(primitiveValue->getDoubleValue());
-    }
-    return arrayParameter.release();
-}
-
-static PassRefPtr<CustomFilterParameter> parseCustomFilterNumberParameter(const String& name, CSSValueList* values)
-{
-    RefPtr<CustomFilterNumberParameter> numberParameter = CustomFilterNumberParameter::create(name);
-    for (unsigned i = 0; i < values->length(); ++i) {
-        CSSValue* value = values->itemWithoutBoundsCheck(i);
-        if (!value->isPrimitiveValue())
-            return 0;
-        CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-        if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
-            return 0;
-        numberParameter->addValue(primitiveValue->getDoubleValue());
-    }
-    return numberParameter.release();
-}
-
-static PassRefPtr<CustomFilterParameter> parseCustomFilterTransformParameter(const String& name, CSSValueList* values, StyleResolverState& state)
-{
-    RefPtr<CustomFilterTransformParameter> transformParameter = CustomFilterTransformParameter::create(name);
-    TransformOperations operations;
-    TransformBuilder::createTransformOperations(values, state.cssToLengthConversionData(), operations);
-    transformParameter->setOperations(operations);
-    return transformParameter.release();
-}
-
-static PassRefPtr<CustomFilterParameter> parseCustomFilterParameter(const String& name, CSSValue* parameterValue, StyleResolverState& state)
-{
-    // FIXME: Implement other parameters types parsing.
-    // booleans: https://bugs.webkit.org/show_bug.cgi?id=76438
-    // textures: https://bugs.webkit.org/show_bug.cgi?id=71442
-    // mat2, mat3, mat4: https://bugs.webkit.org/show_bug.cgi?id=71444
-    // Number parameters are wrapped inside a CSSValueList and all
-    // the other functions values inherit from CSSValueList.
-    if (!parameterValue->isValueList())
-        return 0;
-
-    CSSValueList* values = toCSSValueList(parameterValue);
-    if (!values->length())
-        return 0;
-
-    if (parameterValue->isArrayFunctionValue())
-        return parseCustomFilterArrayParameter(name, values);
-
-    // If the first value of the list is a transform function,
-    // then we could safely assume that all the remaining items
-    // are transforms. parseCustomFilterTransformParameter will
-    // return 0 if that assumption is incorrect.
-    if (values->itemWithoutBoundsCheck(0)->isTransformValue())
-        return parseCustomFilterTransformParameter(name, values, state);
-
-    // We can have only arrays of booleans or numbers, so use the first value to choose between those two.
-    // We need up to 4 values (all booleans or all numbers).
-    if (!values->itemWithoutBoundsCheck(0)->isPrimitiveValue() || values->length() > 4)
-        return 0;
-
-    CSSPrimitiveValue* firstPrimitiveValue = toCSSPrimitiveValue(values->itemWithoutBoundsCheck(0));
-    if (firstPrimitiveValue->primitiveType() == CSSPrimitiveValue::CSS_NUMBER)
-        return parseCustomFilterNumberParameter(name, values);
-
-    // FIXME: Implement the boolean array parameter here.
-    // https://bugs.webkit.org/show_bug.cgi?id=76438
-
-    return 0;
-}
-
-static bool parseCustomFilterParameterList(CSSValue* parametersValue, CustomFilterParameterList& parameterList, StyleResolverState& state)
-{
-    HashSet<String> knownParameterNames;
-    CSSValueListIterator parameterIterator(parametersValue);
-    for (; parameterIterator.hasMore(); parameterIterator.advance()) {
-        if (!parameterIterator.value()->isValueList())
-            return false;
-        CSSValueListIterator iterator(parameterIterator.value());
-        if (!iterator.isPrimitiveValue())
-            return false;
-        CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(iterator.value());
-        if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_STRING)
-            return false;
-
-        String name = primitiveValue->getStringValue();
-        // Do not allow duplicate parameter names.
-        if (!knownParameterNames.add(name).isNewEntry)
-            return false;
-
-        iterator.advance();
-
-        if (!iterator.hasMore())
-            return false;
-
-        RefPtr<CustomFilterParameter> parameter = parseCustomFilterParameter(name, iterator.value(), state);
-        if (!parameter)
-            return false;
-        parameterList.append(parameter.release());
-    }
-
-    // Make sure we sort the parameters before passing them down to the CustomFilterOperation.
-    parameterList.sortParametersByName();
-
-    return true;
-}
-
-static PassRefPtr<CustomFilterOperation> createCustomFilterOperationWithAtRuleReferenceSyntax(CSSFilterValue*)
-{
-    // FIXME: Implement style resolution for the custom filter at-rule reference syntax.
-    return 0;
-}
-
-static PassRefPtr<CustomFilterProgram> createCustomFilterProgram(CSSShaderValue* vertexShader, CSSShaderValue* fragmentShader,
-    CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType,
-    StyleResolverState& state)
-{
-    ResourceFetcher* fetcher = state.document().fetcher();
-    KURL vertexShaderURL = vertexShader ? vertexShader->completeURL(fetcher) : KURL();
-    KURL fragmentShaderURL = fragmentShader ? fragmentShader->completeURL(fetcher) : KURL();
-    // We re-resolve the custom filter style after the shaders are loaded.
-    // We always create a StyleCustomFilterProgram here, and later replace it with a program from the StyleCustomFilterProgramCache, if available.
-    StyleShader* styleVertexShader = vertexShader ? styleShader(vertexShader) : 0;
-    StyleShader* styleFragmentShader = fragmentShader ? styleShader(fragmentShader) : 0;
-    RefPtr<StyleCustomFilterProgram> program = StyleCustomFilterProgram::create(vertexShaderURL, styleVertexShader,
-        fragmentShaderURL, styleFragmentShader, programType, mixSettings, meshType);
-    state.elementStyleResources().setHasNewCustomFilterProgram(true);
-    return program.release();
-}
-
-static PassRefPtr<CustomFilterOperation> createCustomFilterOperationWithInlineSyntax(CSSFilterValue* filterValue, StyleResolverState& state)
-{
-    CSSValue* shadersValue = filterValue->itemWithoutBoundsCheck(0);
-    ASSERT_WITH_SECURITY_IMPLICATION(shadersValue->isValueList());
-    CSSValueList* shadersList = toCSSValueList(shadersValue);
-
-    unsigned shadersListLength = shadersList->length();
-    ASSERT(shadersListLength);
-
-    CSSShaderValue* vertexShader = 0;
-    CSSShaderValue* fragmentShader = 0;
-
-    if (shadersList->itemWithoutBoundsCheck(0)->isShaderValue())
-        vertexShader = toCSSShaderValue(shadersList->itemWithoutBoundsCheck(0));
-
-    CustomFilterProgramType programType = ProgramTypeBlendsElementTexture;
-    CustomFilterProgramMixSettings mixSettings;
-
-    if (shadersListLength > 1) {
-        CSSValue* fragmentShaderOrMixFunction = shadersList->itemWithoutBoundsCheck(1);
-        if (fragmentShaderOrMixFunction->isMixFunctionValue()) {
-            CSSMixFunctionValue* mixFunction = toCSSMixFunctionValue(fragmentShaderOrMixFunction);
-            CSSValueListIterator iterator(mixFunction);
-
-            ASSERT(mixFunction->length());
-            if (iterator.value()->isShaderValue())
-                fragmentShader = toCSSShaderValue(iterator.value());
-
-            iterator.advance();
-
-            ASSERT(mixFunction->length() <= 3);
-            while (iterator.hasMore()) {
-                CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(iterator.value());
-                if (CSSParser::isBlendMode(primitiveValue->getValueID()))
-                    mixSettings.blendMode = *primitiveValue;
-                else if (CSSParser::isCompositeOperator(primitiveValue->getValueID()))
-                    mixSettings.compositeOperator = *primitiveValue;
-                else
-                    ASSERT_NOT_REACHED();
-                iterator.advance();
-            }
-        } else {
-            programType = ProgramTypeNoElementTexture;
-            if (fragmentShaderOrMixFunction->isShaderValue())
-                fragmentShader = toCSSShaderValue(fragmentShaderOrMixFunction);
-        }
-    }
-
-    if (!vertexShader && !fragmentShader)
-        return 0;
-
-    unsigned meshRows = 1;
-    unsigned meshColumns = 1;
-    CustomFilterMeshType meshType = MeshTypeAttached;
-
-    CSSValue* parametersValue = 0;
-
-    if (filterValue->length() > 1) {
-        CSSValueListIterator iterator(filterValue->itemWithoutBoundsCheck(1));
-
-        // The second value might be the mesh box or the list of parameters:
-        // If it starts with a number or any of the mesh-box identifiers it is
-        // the mesh-box list, if not it means it is the parameters list.
-
-        if (iterator.hasMore() && iterator.isPrimitiveValue()) {
-            CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(iterator.value());
-            if (primitiveValue->isNumber()) {
-                // If only one integer value is specified, it will set both
-                // the rows and the columns.
-                meshColumns = meshRows = primitiveValue->getIntValue();
-                iterator.advance();
-
-                // Try to match another number for the rows.
-                if (iterator.hasMore() && iterator.isPrimitiveValue()) {
-                    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(iterator.value());
-                    if (primitiveValue->isNumber()) {
-                        meshRows = primitiveValue->getIntValue();
-                        iterator.advance();
-                    }
-                }
-            }
-        }
-
-        if (iterator.hasMore() && iterator.isPrimitiveValue()) {
-            CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(iterator.value());
-            if (primitiveValue->getValueID() == CSSValueDetached) {
-                meshType = MeshTypeDetached;
-                iterator.advance();
-            }
-        }
-
-        if (!iterator.index()) {
-            // If no value was consumed from the mesh value, then it is just a parameter list, meaning that we end up
-            // having just two CSSListValues: list of shaders and list of parameters.
-            ASSERT(filterValue->length() == 2);
-            parametersValue = filterValue->itemWithoutBoundsCheck(1);
-        }
-    }
-
-    if (filterValue->length() > 2 && !parametersValue)
-        parametersValue = filterValue->itemWithoutBoundsCheck(2);
-
-    CustomFilterParameterList parameterList;
-    if (parametersValue && !parseCustomFilterParameterList(parametersValue, parameterList, state))
-        return 0;
-
-    RefPtr<CustomFilterProgram> program = createCustomFilterProgram(vertexShader, fragmentShader, programType, mixSettings, meshType, state);
-    return CustomFilterOperation::create(program.release(), parameterList, meshRows, meshColumns, meshType);
-}
-
-static PassRefPtr<CustomFilterOperation> createCustomFilterOperation(CSSFilterValue* filterValue, StyleResolverState& state)
-{
-    ASSERT(filterValue->length());
-    bool isAtRuleReferenceSyntax = filterValue->itemWithoutBoundsCheck(0)->isPrimitiveValue();
-    return isAtRuleReferenceSyntax ? createCustomFilterOperationWithAtRuleReferenceSyntax(filterValue) : createCustomFilterOperationWithInlineSyntax(filterValue, state);
-}
-
-
 bool FilterOperationResolver::createFilterOperations(CSSValue* inValue, const CSSToLengthConversionData& unadjustedConversionData, FilterOperations& outOperations, StyleResolverState& state)
 {
     ASSERT(outOperations.isEmpty());
@@ -373,19 +97,6 @@
         CSSFilterValue* filterValue = toCSSFilterValue(i.value());
         FilterOperation::OperationType operationType = filterOperationForType(filterValue->operationType());
 
-        if (operationType == FilterOperation::VALIDATED_CUSTOM) {
-            // ValidatedCustomFilterOperation is not supposed to end up in the RenderStyle.
-            ASSERT_NOT_REACHED();
-            continue;
-        }
-        if (operationType == FilterOperation::CUSTOM) {
-            RefPtr<CustomFilterOperation> operation = createCustomFilterOperation(filterValue, state);
-            if (!operation)
-                return false;
-
-            operations.operations().append(operation);
-            continue;
-        }
         if (operationType == FilterOperation::REFERENCE) {
             if (filterValue->length() != 1)
                 continue;
@@ -397,7 +108,7 @@
             CSSSVGDocumentValue* svgDocumentValue = toCSSSVGDocumentValue(argument);
             KURL url = state.document().completeURL(svgDocumentValue->url());
 
-            RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), url.fragmentIdentifier());
+            RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), AtomicString(url.fragmentIdentifier()));
             if (SVGURIReference::isExternalURIReference(svgDocumentValue->url(), state.document())) {
                 if (!svgDocumentValue->loadRequested())
                     state.elementStyleResources().addPendingSVGDocument(operation.get(), svgDocumentValue);
@@ -463,9 +174,6 @@
             Length stdDeviation = Length(0, Fixed);
             if (filterValue->length() >= 1)
                 stdDeviation = firstValue->convertToLength<FixedConversion | PercentConversion>(conversionData);
-            if (stdDeviation.isUndefined())
-                return false;
-
             operations.operations().append(BlurFilterOperation::create(stdDeviation));
             break;
         }
@@ -480,11 +188,11 @@
             CSSShadowValue* item = toCSSShadowValue(cssValue);
             IntPoint location(item->x->computeLength<int>(conversionData), item->y->computeLength<int>(conversionData));
             int blur = item->blur ? item->blur->computeLength<int>(conversionData) : 0;
-            Color shadowColor;
+            Color shadowColor = Color::transparent;
             if (item->color)
                 shadowColor = state.document().textLinkColors().colorFromPrimitiveValue(item->color.get(), state.style()->color());
 
-            operations.operations().append(DropShadowFilterOperation::create(location, blur, shadowColor.isValid() ? shadowColor : Color::transparent));
+            operations.operations().append(DropShadowFilterOperation::create(location, blur, shadowColor));
             break;
         }
         case CSSFilterValue::UnknownFilterOperation:
diff --git a/Source/core/css/resolver/FontBuilder.cpp b/Source/core/css/resolver/FontBuilder.cpp
index 5073434..b165a53 100644
--- a/Source/core/css/resolver/FontBuilder.cpp
+++ b/Source/core/css/resolver/FontBuilder.cpp
@@ -28,7 +28,7 @@
 #include "core/css/CSSToLengthConversionData.h"
 #include "core/css/FontSize.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
 #include "platform/text/LocaleToScriptMapping.h"
@@ -62,6 +62,7 @@
 FontBuilder::FontBuilder()
     : m_document(0)
     , m_useSVGZoomRules(false)
+    , m_fontSizehasViewportUnits(false)
     , m_fontDirty(false)
 {
 }
@@ -324,16 +325,22 @@
         scope.fontDescription().setIsAbsoluteSize(parentIsAbsoluteSize && (valueID == CSSValueLarger || valueID == CSSValueSmaller));
     } else {
         scope.fontDescription().setIsAbsoluteSize(parentIsAbsoluteSize || !(primitiveValue->isPercentage() || primitiveValue->isFontRelativeLength()));
-        if (primitiveValue->isLength())
-            size = primitiveValue->computeLength<float>(CSSToLengthConversionData(parentStyle, rootElementStyle, 1.0, true));
-        else if (primitiveValue->isPercentage())
+        if (primitiveValue->isPercentage()) {
             size = (primitiveValue->getFloatValue() * parentSize) / 100.0f;
-        else if (primitiveValue->isCalculatedPercentageWithLength())
-            size = primitiveValue->cssCalcValue()->toCalcValue(CSSToLengthConversionData(parentStyle, rootElementStyle, 1.0f))->evaluate(parentSize);
-        else if (primitiveValue->isViewportPercentageLength())
-            size = valueForLength(primitiveValue->viewportPercentageLength(), 0, m_document->renderView());
-        else
-            return;
+        } else {
+            // If we have viewport units the conversion will mark the parent style as having viewport units.
+            bool parentHasViewportUnits = parentStyle->hasViewportUnits();
+            parentStyle->setHasViewportUnits(false);
+            CSSToLengthConversionData conversionData(parentStyle, rootElementStyle, m_document->renderView(), 1.0f, true);
+            if (primitiveValue->isLength())
+                size = primitiveValue->computeLength<float>(conversionData);
+            else if (primitiveValue->isCalculatedPercentageWithLength())
+                size = primitiveValue->cssCalcValue()->toCalcValue(conversionData)->evaluate(parentSize);
+            else
+                ASSERT_NOT_REACHED();
+            m_fontSizehasViewportUnits = parentStyle->hasViewportUnits();
+            parentStyle->setHasViewportUnits(parentHasViewportUnits);
+        }
     }
 
     if (size < 0)
diff --git a/Source/core/css/resolver/FontBuilder.h b/Source/core/css/resolver/FontBuilder.h
index b573b51..ab44a4f 100644
--- a/Source/core/css/resolver/FontBuilder.h
+++ b/Source/core/css/resolver/FontBuilder.h
@@ -83,6 +83,8 @@
     // FontBuilder calls at the callsite.
     void createFontForDocument(PassRefPtr<FontSelector>, RenderStyle*);
 
+    bool fontSizeHasViewportUnits() { return m_fontSizehasViewportUnits; }
+
     // FIXME: These should not be necessary eventually.
     void setFontDirty(bool fontDirty) { m_fontDirty = fontDirty; }
     // FIXME: This is only used by an ASSERT in StyleResolver. Remove?
@@ -102,6 +104,7 @@
 
     const Document* m_document;
     bool m_useSVGZoomRules;
+    bool m_fontSizehasViewportUnits;
     // FIXME: This member is here on a short-term lease. The plan is to remove
     // any notion of RenderStyle from here, allowing FontBuilder to build Font objects
     // directly, rather than as a byproduct of calling RenderStyle::setFontDescription.
diff --git a/Source/core/css/resolver/MatchRequest.h b/Source/core/css/resolver/MatchRequest.h
index df0207f..652a420 100644
--- a/Source/core/css/resolver/MatchRequest.h
+++ b/Source/core/css/resolver/MatchRequest.h
@@ -23,6 +23,7 @@
 #ifndef MatchRequest_h
 #define MatchRequest_h
 
+#include "core/css/CSSStyleSheet.h"
 #include "core/css/RuleSet.h"
 
 namespace WebCore {
@@ -31,12 +32,13 @@
 
 class MatchRequest {
 public:
-    MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0, bool elementApplyAuthorStyles = true, unsigned styleSheetIndex = 0)
+    MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0, bool elementApplyAuthorStyles = true, unsigned styleSheetIndex = 0, const CSSStyleSheet* cssSheet = 0)
         : ruleSet(ruleSet)
         , includeEmptyRules(includeEmptyRules)
         , scope(scope)
         , elementApplyAuthorStyles(elementApplyAuthorStyles)
         , styleSheetIndex(styleSheetIndex)
+        , styleSheet(cssSheet)
     {
         // Now that we're about to read from the RuleSet, we're done adding more
         // rules to the set and we should make sure it's compacted.
@@ -48,6 +50,7 @@
     const ContainerNode* scope;
     const bool elementApplyAuthorStyles;
     const unsigned styleSheetIndex;
+    const CSSStyleSheet* styleSheet;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/MatchedPropertiesCache.cpp b/Source/core/css/resolver/MatchedPropertiesCache.cpp
index d3c222a..860c5c0 100644
--- a/Source/core/css/resolver/MatchedPropertiesCache.cpp
+++ b/Source/core/css/resolver/MatchedPropertiesCache.cpp
@@ -95,9 +95,9 @@
     ASSERT(hash);
     Cache::AddResult addResult = m_cache.add(hash, nullptr);
     if (addResult.isNewEntry)
-        addResult.iterator->value = adoptPtr(new CachedMatchedProperties);
+        addResult.storedValue->value = adoptPtr(new CachedMatchedProperties);
 
-    CachedMatchedProperties* cacheItem = addResult.iterator->value.get();
+    CachedMatchedProperties* cacheItem = addResult.storedValue->value.get();
     if (!addResult.isNewEntry)
         cacheItem->clear();
 
@@ -109,6 +109,18 @@
     m_cache.clear();
 }
 
+void MatchedPropertiesCache::clearViewportDependent()
+{
+    Vector<unsigned, 16> toRemove;
+    for (Cache::iterator it = m_cache.begin(); it != m_cache.end(); ++it) {
+        CachedMatchedProperties* cacheItem = it->value.get();
+        if (cacheItem->renderStyle->hasViewportUnits())
+            toRemove.append(it->key);
+    }
+    for (size_t i = 0; i < toRemove.size(); ++i)
+        m_cache.remove(toRemove[i]);
+}
+
 void MatchedPropertiesCache::sweep(Timer<MatchedPropertiesCache>*)
 {
     // Look for cache entries containing a style declaration with a single ref and remove them.
diff --git a/Source/core/css/resolver/MatchedPropertiesCache.h b/Source/core/css/resolver/MatchedPropertiesCache.h
index 2e5297d..d86bf01 100644
--- a/Source/core/css/resolver/MatchedPropertiesCache.h
+++ b/Source/core/css/resolver/MatchedPropertiesCache.h
@@ -54,6 +54,7 @@
     void add(const RenderStyle*, const RenderStyle* parentStyle, unsigned hash, const MatchResult&);
 
     void clear();
+    void clearViewportDependent();
 
     static bool isCacheable(const Element*, const RenderStyle*, const RenderStyle* parentStyle);
 
diff --git a/Source/core/css/resolver/ScopedStyleResolver.cpp b/Source/core/css/resolver/ScopedStyleResolver.cpp
index 706f5d8..f63a5df 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -50,7 +50,7 @@
     if (!sheetDocument)
         return 0;
     Node* ownerNode = sheet->ownerNode();
-    if (!ownerNode || !isHTMLStyleElement(ownerNode))
+    if (!ownerNode || !ownerNode->hasTagName(HTMLNames::styleTag))
         return &document;
 
     HTMLStyleElement* styleElement = toHTMLStyleElement(ownerNode);
@@ -67,9 +67,10 @@
     return (parent->isElementNode() || parent->isShadowRoot()) ? parent : 0;
 }
 
-void ScopedStyleResolver::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, StyleResolver* resolver)
+void ScopedStyleResolver::addRulesFromSheet(CSSStyleSheet* cssSheet, const MediaQueryEvaluator& medium, StyleResolver* resolver)
 {
-    m_authorStyleSheets.append(sheet);
+    m_authorStyleSheets.append(cssSheet);
+    StyleSheetContents* sheet = cssSheet->contents();
 
     AddRuleFlags addRuleFlags = resolver->document().securityOrigin()->canRequest(sheet->baseURL()) ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
     const RuleSet& ruleSet = sheet->ensureRuleSet(medium, addRuleFlags);
@@ -80,7 +81,7 @@
 void ScopedStyleResolver::collectFeaturesTo(RuleFeatureSet& features)
 {
     for (size_t i = 0; i < m_authorStyleSheets.size(); ++i)
-        features.add(m_authorStyleSheets[i]->ruleSet().features());
+        features.add(m_authorStyleSheets[i]->contents()->ruleSet().features());
 }
 
 void ScopedStyleResolver::resetAuthorStyle()
@@ -89,19 +90,6 @@
     m_keyframesRuleMap.clear();
 }
 
-bool ScopedStyleResolver::checkRegionStyle(Element* regionElement)
-{
-    for (size_t i = 0; i < m_authorStyleSheets.size(); ++i) {
-        const RuleSet& ruleSet = m_authorStyleSheets[i]->ruleSet();
-        for (unsigned i = 0; i < ruleSet.m_regionSelectorsAndRuleSets.size(); ++i) {
-            ASSERT(ruleSet.m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
-            if (checkRegionSelector(ruleSet.m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
-                return true;
-        }
-    }
-    return false;
-}
-
 const StyleRuleKeyframes* ScopedStyleResolver::keyframeStylesForAnimation(const StringImpl* animationName)
 {
     if (m_keyframesRuleMap.isEmpty())
@@ -143,9 +131,8 @@
 
     RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
     for (size_t i = 0; i < m_authorStyleSheets.size(); ++i) {
-        MatchRequest matchRequest(&m_authorStyleSheets[i]->ruleSet(), includeEmptyRules, scopingNode, applyAuthorStyles, i);
+        MatchRequest matchRequest(&m_authorStyleSheets[i]->contents()->ruleSet(), includeEmptyRules, scopingNode, applyAuthorStyles, i, m_authorStyleSheets[i]);
         collector.collectMatchingRules(matchRequest, ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary), cascadeScope, cascadeOrder);
-        collector.collectMatchingRulesForRegion(matchRequest, ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary), cascadeScope, cascadeOrder);
     }
 }
 
@@ -154,7 +141,7 @@
     // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
     ASSERT(m_scopingNode.isDocumentNode());
     for (size_t i = 0; i < m_authorStyleSheets.size(); ++i)
-        collector.matchPageRules(&m_authorStyleSheets[i]->ruleSet());
+        collector.matchPageRules(&m_authorStyleSheets[i]->contents()->ruleSet());
 }
 
 void ScopedStyleResolver::collectViewportRulesTo(StyleResolver* resolver) const
@@ -162,7 +149,7 @@
     if (!m_scopingNode.isDocumentNode())
         return;
     for (size_t i = 0; i < m_authorStyleSheets.size(); ++i)
-        resolver->viewportStyleResolver()->collectViewportRules(&m_authorStyleSheets[i]->ruleSet(), ViewportStyleResolver::AuthorOrigin);
+        resolver->viewportStyleResolver()->collectViewportRules(&m_authorStyleSheets[i]->contents()->ruleSet(), ViewportStyleResolver::AuthorOrigin);
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/ScopedStyleResolver.h b/Source/core/css/resolver/ScopedStyleResolver.h
index 7aa1a1a..824b68a 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.h
+++ b/Source/core/css/resolver/ScopedStyleResolver.h
@@ -55,13 +55,12 @@
     ScopedStyleResolver* parent() { return m_parent; }
 
 public:
-    bool checkRegionStyle(Element*);
     const StyleRuleKeyframes* keyframeStylesForAnimation(const StringImpl* animationName);
     void addKeyframeStyle(PassRefPtr<StyleRuleKeyframes>);
 
     void collectMatchingAuthorRules(ElementRuleCollector&, bool includeEmptyRules, bool applyAuthorStyles, CascadeScope, CascadeOrder = ignoreCascadeOrder);
     void matchPageRules(PageRuleCollector&);
-    void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver*);
+    void addRulesFromSheet(CSSStyleSheet*, const MediaQueryEvaluator&, StyleResolver*);
     void collectFeaturesTo(RuleFeatureSet&);
     void resetAuthorStyle();
     void collectViewportRulesTo(StyleResolver*) const;
@@ -69,12 +68,10 @@
 private:
     explicit ScopedStyleResolver(ContainerNode& scopingNode) : m_scopingNode(scopingNode), m_parent(0) { }
 
-    RuleSet* ensureAuthorStyle();
-
     ContainerNode& m_scopingNode;
     ScopedStyleResolver* m_parent;
 
-    Vector<StyleSheetContents*> m_authorStyleSheets;
+    Vector<CSSStyleSheet*> m_authorStyleSheets;
 
     typedef HashMap<const StringImpl*, RefPtr<StyleRuleKeyframes> > KeyframesRuleMap;
     KeyframesRuleMap m_keyframesRuleMap;
diff --git a/Source/core/css/resolver/ScopedStyleTree.cpp b/Source/core/css/resolver/ScopedStyleTree.cpp
index 729faf1..1938fd7 100644
--- a/Source/core/css/resolver/ScopedStyleTree.cpp
+++ b/Source/core/css/resolver/ScopedStyleTree.cpp
@@ -58,12 +58,12 @@
     HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::AddResult addResult = m_authorStyles.add(&scopingNode, nullptr);
 
     if (addResult.isNewEntry) {
-        addResult.iterator->value = ScopedStyleResolver::create(scopingNode);
+        addResult.storedValue->value = ScopedStyleResolver::create(scopingNode);
         if (scopingNode.isDocumentNode())
-            m_scopedResolverForDocument = addResult.iterator->value.get();
+            m_scopedResolverForDocument = addResult.storedValue->value.get();
     }
     isNewEntry = addResult.isNewEntry;
-    return addResult.iterator->value.get();
+    return addResult.storedValue->value.get();
 }
 
 void ScopedStyleTree::setupScopedStylesTree(ScopedStyleResolver* target)
@@ -138,6 +138,10 @@
     TreeScope& treeScope = element->treeScope();
     bool applyAuthorStyles = treeScope.applyAuthorStyles();
 
+    // Add resolvers for shadow roots hosted by the given element.
+    collectScopedResolversForHostedShadowTrees(element, resolvers);
+
+    // Add resolvers while walking up DOM tree from the given element.
     for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent()) {
         if (scopedResolver->treeScope() == treeScope || (applyAuthorStyles && scopedResolver->treeScope() == document))
             resolvers.append(scopedResolver);
diff --git a/Source/core/css/resolver/SharedStyleFinder.cpp b/Source/core/css/resolver/SharedStyleFinder.cpp
index 92890d6..ac80231 100644
--- a/Source/core/css/resolver/SharedStyleFinder.cpp
+++ b/Source/core/css/resolver/SharedStyleFinder.cpp
@@ -42,6 +42,7 @@
 #include "core/dom/QualifiedName.h"
 #include "core/dom/SpaceSplitString.h"
 #include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/InsertionPoint.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLOptGroupElement.h"
@@ -100,7 +101,7 @@
 {
     unsigned count = classNames.size();
     for (unsigned i = 0; i < count; ++i) {
-        if (m_features.classesInRules.contains(classNames[i]))
+        if (m_features.hasSelectorForClass(classNames[i]))
             return true;
     }
     return false;
@@ -157,11 +158,33 @@
     return true;
 }
 
+bool SharedStyleFinder::sharingCandidateShadowHasSharedStyleSheetContents(Element& candidate) const
+{
+    if (!element().shadow() || !element().shadow()->containsActiveStyles())
+        return false;
+
+    return element().shadow()->hasSameStyles(candidate.shadow());
+}
+
+bool SharedStyleFinder::sharingCandidateDistributedToSameInsertionPoint(Element& candidate) const
+{
+    Vector<InsertionPoint*, 8> insertionPoints, candidateInsertionPoints;
+    collectDestinationInsertionPoints(element(), insertionPoints);
+    collectDestinationInsertionPoints(candidate, candidateInsertionPoints);
+    if (insertionPoints.size() != candidateInsertionPoints.size())
+        return false;
+    for (size_t i = 0; i < insertionPoints.size(); ++i) {
+        if (insertionPoints[i] != candidateInsertionPoints[i])
+            return false;
+    }
+    return true;
+}
+
 bool SharedStyleFinder::canShareStyleWithElement(Element& candidate) const
 {
     if (element() == candidate)
         return false;
-    Element* parent = candidate.parentElement();
+    Element* parent = candidate.parentOrShadowHostElement();
     RenderStyle* style = candidate.renderStyle();
     if (!style)
         return false;
@@ -169,7 +192,7 @@
         return false;
     if (!parent)
         return false;
-    if (element().parentElement()->renderStyle() != parent->renderStyle())
+    if (element().parentOrShadowHostElement()->renderStyle() != parent->renderStyle())
         return false;
     if (candidate.tagQName() != element().tagQName())
         return false;
@@ -195,12 +218,16 @@
         return false;
     if (candidate.additionalPresentationAttributeStyle() != element().additionalPresentationAttributeStyle())
         return false;
-    if (candidate.hasID() && m_features.idsInRules.contains(candidate.idForStyleResolution()))
+    if (candidate.hasID() && m_features.hasSelectorForId(candidate.idForStyleResolution()))
         return false;
     if (candidate.hasScopedHTMLStyleChild())
         return false;
-    if (candidate.shadow() && candidate.shadow()->containsActiveStyles())
-        return 0;
+    if (candidate.shadow() && candidate.shadow()->containsActiveStyles() && !sharingCandidateShadowHasSharedStyleSheetContents(candidate))
+        return false;
+    if (!sharingCandidateDistributedToSameInsertionPoint(candidate))
+        return false;
+    if (candidate.isInTopLayer() != element().isInTopLayer())
+        return false;
 
     bool isControl = candidate.isFormControlElement();
 
@@ -220,7 +247,7 @@
     if (candidate.isUnresolvedCustomElement() != element().isUnresolvedCustomElement())
         return false;
 
-    if (element().parentElement() != parent) {
+    if (element().parentOrShadowHostElement() != parent) {
         if (!parent->isStyledElement())
             return false;
         if (parent->hasScopedHTMLStyleChild())
@@ -229,7 +256,7 @@
             return false;
         if (parent->isSVGElement() && toSVGElement(parent)->animatedSMILStyleProperties())
             return false;
-        if (parent->hasID() && m_features.idsInRules.contains(parent->idForStyleResolution()))
+        if (parent->hasID() && m_features.hasSelectorForId(parent->idForStyleResolution()))
             return false;
         if (!parent->childrenSupportStyleSharing())
             return false;
@@ -304,7 +331,7 @@
     }
 
     // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
-    if (!element().parentElement()->childrenSupportStyleSharing()) {
+    if (!element().parentOrShadowHostElement()->childrenSupportStyleSharing()) {
         INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleRejectedByParent);
         return 0;
     }
diff --git a/Source/core/css/resolver/SharedStyleFinder.h b/Source/core/css/resolver/SharedStyleFinder.h
index e65c5c0..0c263cd 100644
--- a/Source/core/css/resolver/SharedStyleFinder.h
+++ b/Source/core/css/resolver/SharedStyleFinder.h
@@ -63,6 +63,8 @@
     bool canShareStyleWithElement(Element& candidate) const;
     bool canShareStyleWithControl(Element& candidate) const;
     bool sharingCandidateHasIdenticalStyleAffectingAttributes(Element& candidate) const;
+    bool sharingCandidateShadowHasSharedStyleSheetContents(Element& candidate) const;
+    bool sharingCandidateDistributedToSameInsertionPoint(Element& candidate) const;
     bool matchesRuleSet(RuleSet*);
 
     Element& element() const { return *m_context.element(); }
diff --git a/Source/core/css/resolver/StyleAdjuster.cpp b/Source/core/css/resolver/StyleAdjuster.cpp
index 5898dda..7e8b3ee 100644
--- a/Source/core/css/resolver/StyleAdjuster.cpp
+++ b/Source/core/css/resolver/StyleAdjuster.cpp
@@ -34,14 +34,11 @@
 #include "core/dom/ContainerNode.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
-#include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLTableElement.h"
 #include "core/html/HTMLTextAreaElement.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Settings.h"
-#include "core/rendering/Pagination.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/style/GridPosition.h"
 #include "core/rendering/style/RenderStyle.h"
@@ -177,7 +174,7 @@
             if (e->hasTagName(tdTag)) {
                 style->setDisplay(TABLE_CELL);
                 style->setFloating(NoFloat);
-            } else if (isHTMLTableElement(e)) {
+            } else if (e->hasTagName(tableTag)) {
                 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
             }
         }
@@ -195,7 +192,7 @@
         }
 
         // Tables never support the -webkit-* values for text-align and will reset back to the default.
-        if (e && isHTMLTableElement(e) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
+        if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
             style->setTextAlign(TASTART);
 
         // Frames and framesets never honor position:relative or position:absolute. This is necessary to
@@ -237,7 +234,7 @@
         // on some sites).
         if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
             || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW)
-            && style->hasInFlowPosition())
+            && style->position() == RelativePosition)
             style->setPosition(StaticPosition);
 
         // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
@@ -278,12 +275,11 @@
         || style->position() == StickyPosition
         || (style->position() == FixedPosition && e && e->document().settings() && e->document().settings()->fixedPositionCreatesStackingContext())
         || isInTopLayer(e, style)
-        || style->hasFlowFrom()
         ))
         style->setZIndex(0);
 
     // Textarea considers overflow visible as auto.
-    if (e && isHTMLTextAreaElement(e)) {
+    if (e && e->hasTagName(textareaTag)) {
         style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
         style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
     }
@@ -309,12 +305,6 @@
         style->setOverflowY(OAUTO);
     }
 
-    // Call setStylesForPaginationMode() if a pagination mode is set for any non-root elements. If these
-    // styles are specified on a root element, then they will be incorporated in
-    // StyleAdjuster::styleForDocument().
-    if ((style->overflowY() == OPAGEDX || style->overflowY() == OPAGEDY) && !(e && (isHTMLHtmlElement(e) || e->hasTagName(bodyTag))))
-        Pagination::setStylesForPaginationMode(WebCore::paginationModeForRenderStyle(style), style);
-
     // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
     // FIXME: Eventually table sections will support auto and scroll.
     if (style->display() == TABLE || style->display() == INLINE_TABLE
@@ -358,10 +348,6 @@
         || style->hasFilter()))
         style->setTransformStyle3D(TransformStyle3DFlat);
 
-    // Seamless iframes behave like blocks. Map their display to inline-block when marked inline.
-    if (e && e->hasTagName(iframeTag) && style->display() == INLINE && toHTMLIFrameElement(e)->shouldDisplaySeamlessly())
-        style->setDisplay(INLINE_BLOCK);
-
     adjustGridItemPosition(style, parentStyle);
 
     if (e && e->isSVGElement()) {
diff --git a/Source/core/css/resolver/StyleBuilderConverter.cpp b/Source/core/css/resolver/StyleBuilderConverter.cpp
index d3ffb15..5c208f2 100644
--- a/Source/core/css/resolver/StyleBuilderConverter.cpp
+++ b/Source/core/css/resolver/StyleBuilderConverter.cpp
@@ -34,19 +34,18 @@
 
 namespace WebCore {
 
-String StyleBuilderConverter::convertFragmentIdentifier(StyleResolverState& state, CSSValue* value)
+AtomicString StyleBuilderConverter::convertFragmentIdentifier(StyleResolverState& state, CSSValue* value)
 {
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
     if (primitiveValue->isURI())
         return SVGURIReference::fragmentIdentifierFromIRIString(primitiveValue->getStringValue(), state.document());
-    return String();
+    return nullAtom;
 }
 
 Length StyleBuilderConverter::convertLength(StyleResolverState& state, CSSValue* value)
 {
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
     Length result = primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
-    ASSERT(!result.isUndefined());
     result.setQuirk(primitiveValue->isQuirkValue());
     return result;
 }
@@ -55,7 +54,6 @@
 {
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
     Length result = primitiveValue->convertToLength<FixedConversion | PercentConversion | AutoConversion>(state.cssToLengthConversionData());
-    ASSERT(!result.isUndefined());
     result.setQuirk(primitiveValue->isQuirkValue());
     return result;
 }
@@ -138,20 +136,17 @@
     ShadowDataVector shadows;
     for (size_t i = 0; i < shadowCount; ++i) {
         const CSSShadowValue* item = toCSSShadowValue(valueList->item(i));
-        int x = item->x->computeLength<int>(state.cssToLengthConversionData());
-        int y = item->y->computeLength<int>(state.cssToLengthConversionData());
-        int blur = item->blur ? item->blur->computeLength<int>(state.cssToLengthConversionData()) : 0;
-        int spread = item->spread ? item->spread->computeLength<int>(state.cssToLengthConversionData()) : 0;
+        float x = item->x->computeLength<float>(state.cssToLengthConversionData());
+        float y = item->y->computeLength<float>(state.cssToLengthConversionData());
+        float blur = item->blur ? item->blur->computeLength<float>(state.cssToLengthConversionData()) : 0;
+        float spread = item->spread ? item->spread->computeLength<float>(state.cssToLengthConversionData()) : 0;
         ShadowStyle shadowStyle = item->style && item->style->getValueID() == CSSValueInset ? Inset : Normal;
         Color color;
         if (item->color)
             color = state.document().textLinkColors().colorFromPrimitiveValue(item->color.get(), state.style()->color());
         else
             color = state.style()->color();
-
-        if (!color.isValid())
-            color = Color::transparent;
-        shadows.append(ShadowData(IntPoint(x, y), blur, spread, shadowStyle, color));
+        shadows.append(ShadowData(FloatPoint(x, y), blur, spread, shadowStyle, color));
     }
     return ShadowList::adopt(shadows);
 }
@@ -166,7 +161,7 @@
     return primitiveValue->computeLength<float>(state.cssToLengthConversionData());
 }
 
-SVGLength StyleBuilderConverter::convertSVGLength(StyleResolverState&, CSSValue* value)
+PassRefPtr<SVGLength> StyleBuilderConverter::convertSVGLength(StyleResolverState&, CSSValue* value)
 {
     return SVGLength::fromCSSPrimitiveValue(toCSSPrimitiveValue(value));
 }
diff --git a/Source/core/css/resolver/StyleBuilderConverter.h b/Source/core/css/resolver/StyleBuilderConverter.h
index 12f03ec..1d97e6b 100644
--- a/Source/core/css/resolver/StyleBuilderConverter.h
+++ b/Source/core/css/resolver/StyleBuilderConverter.h
@@ -40,7 +40,7 @@
 
 class StyleBuilderConverter {
 public:
-    static String convertFragmentIdentifier(StyleResolverState&, CSSValue*);
+    static AtomicString convertFragmentIdentifier(StyleResolverState&, CSSValue*);
     template <typename T> static T convertComputedLength(StyleResolverState&, CSSValue*);
     template <typename T> static T convertLineWidth(StyleResolverState&, CSSValue*);
     static Length convertLength(StyleResolverState&, CSSValue*);
@@ -53,7 +53,7 @@
     static PassRefPtr<ShadowList> convertShadow(StyleResolverState&, CSSValue*);
     static float convertSpacing(StyleResolverState&, CSSValue*);
     template <CSSValueID IdForNone> static AtomicString convertString(StyleResolverState&, CSSValue*);
-    static SVGLength convertSVGLength(StyleResolverState&, CSSValue*);
+    static PassRefPtr<SVGLength> convertSVGLength(StyleResolverState&, CSSValue*);
 };
 
 template <typename T>
@@ -73,8 +73,6 @@
         return 3;
     if (valueID == CSSValueThick)
         return 5;
-    if (primitiveValue->isViewportPercentageLength())
-        return intValueForLength(primitiveValue->viewportPercentageLength(), 0, state.document().renderView());
     if (valueID == CSSValueInvalid) {
         // Any original result that was >= 1 should not be allowed to fall below 1.
         // This keeps border lines from vanishing.
@@ -96,7 +94,7 @@
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
     if (primitiveValue->getValueID() == IdForNone)
         return nullAtom;
-    return primitiveValue->getStringValue();
+    return AtomicString(primitiveValue->getStringValue());
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/StyleBuilderCustom.cpp b/Source/core/css/resolver/StyleBuilderCustom.cpp
index c19beb0..a30084f 100644
--- a/Source/core/css/resolver/StyleBuilderCustom.cpp
+++ b/Source/core/css/resolver/StyleBuilderCustom.cpp
@@ -49,16 +49,16 @@
 #include "core/css/CSSFunctionValue.h"
 #include "core/css/CSSGradientValue.h"
 #include "core/css/CSSGridLineNamesValue.h"
-#include "core/css/CSSGridTemplateValue.h"
+#include "core/css/CSSGridTemplateAreasValue.h"
 #include "core/css/CSSHelper.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSLineBoxContainValue.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/CSSProperty.h"
 #include "core/css/CSSReflectValue.h"
-#include "core/css/CSSVariableValue.h"
 #include "core/css/Counter.h"
+#include "core/css/Pair.h"
 #include "core/css/Rect.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
@@ -68,7 +68,7 @@
 #include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/TransformBuilder.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/style/CounterContent.h"
 #include "core/rendering/style/CursorList.h"
 #include "core/rendering/style/QuotesData.h"
@@ -126,6 +126,39 @@
     }
 }
 
+void StyleBuilderFunctions::applyInitialCSSPropertyColor(StyleResolverState& state)
+{
+    Color color = RenderStyle::initialColor();
+    if (state.applyPropertyToRegularStyle())
+        state.style()->setColor(color);
+    if (state.applyPropertyToVisitedLinkStyle())
+        state.style()->setVisitedLinkColor(color);
+}
+
+void StyleBuilderFunctions::applyInheritCSSPropertyColor(StyleResolverState& state)
+{
+    Color color = state.parentStyle()->color();
+    if (state.applyPropertyToRegularStyle())
+        state.style()->setColor(color);
+    if (state.applyPropertyToVisitedLinkStyle())
+        state.style()->setVisitedLinkColor(color);
+}
+
+void StyleBuilderFunctions::applyValueCSSPropertyColor(StyleResolverState& state, CSSValue* value)
+{
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+    // As per the spec, 'color: currentColor' is treated as 'color: inherit'
+    if (primitiveValue->getValueID() == CSSValueCurrentcolor) {
+        applyInheritCSSPropertyColor(state);
+        return;
+    }
+
+    if (state.applyPropertyToRegularStyle())
+        state.style()->setColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color()));
+    if (state.applyPropertyToVisitedLinkStyle())
+        state.style()->setVisitedLinkColor(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color(), state.element()->isLink() /* forVisitedLink */));
+}
+
 void StyleBuilderFunctions::applyInitialCSSPropertyCursor(StyleResolverState& state)
 {
     state.style()->clearCursorList();
@@ -251,9 +284,11 @@
         ASSERT_NOT_REACHED();
         break;
     case CSSValueBolder:
+        state.fontBuilder().setWeight(state.parentStyle()->fontDescription().weight());
         state.fontBuilder().setWeightBolder();
         break;
     case CSSValueLighter:
+        state.fontBuilder().setWeight(state.parentStyle()->fontDescription().weight());
         state.fontBuilder().setWeightLighter();
         break;
     default:
@@ -280,8 +315,6 @@
         lineHeight = Length((state.style()->computedFontSize() * primitiveValue->getIntValue()) / 100.0, Fixed);
     } else if (primitiveValue->isNumber()) {
         lineHeight = Length(primitiveValue->getDoubleValue() * 100.0, Percent);
-    } else if (primitiveValue->isViewportPercentageLength()) {
-        lineHeight = primitiveValue->viewportPercentageLength();
     } else if (primitiveValue->isCalculated()) {
         double multiplier = state.style()->effectiveZoom();
         if (Frame* frame = state.document().frame())
@@ -439,7 +472,7 @@
             height = second->computeLength<Length>(state.cssToLengthConversionData().copyWithAdjustedZoom(1.0));
         } else {
             // <page-size> <orientation>
-            // The value order is guaranteed. See CSSParser::parseSizeParameter.
+            // The value order is guaranteed. See BisonCSSParser::parseSizeParameter.
             if (!getPageSizeFromName(first, second, width, height))
                 return;
         }
@@ -533,13 +566,12 @@
         return;
 
     // [ <length> | <percentage> ] each-line
-    // The order is guaranteed. See CSSParser::parseTextIndent.
+    // The order is guaranteed. See BisonCSSParser::parseTextIndent.
     // The second value, each-line is handled only when css3TextEnabled() returns true.
 
     CSSValueList* valueList = toCSSValueList(value);
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(valueList->itemWithoutBoundsCheck(0));
     Length lengthOrPercentageValue = primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
-    ASSERT(!lengthOrPercentageValue.isUndefined());
     state.style()->setTextIndent(lengthOrPercentageValue);
 
     ASSERT(valueList->length() <= 2);
@@ -564,6 +596,15 @@
     state.style()->setVerticalAlignLength(primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData()));
 }
 
+void StyleBuilderFunctions::applyValueCSSPropertyTouchAction(StyleResolverState& state, CSSValue* value)
+{
+    TouchAction action = RenderStyle::initialTouchAction();
+    for (CSSValueListIterator i(value); i.hasMore(); i.advance())
+        action |= *toCSSPrimitiveValue(i.value());
+
+    state.style()->setTouchAction(action);
+}
+
 static void resetEffectiveZoom(StyleResolverState& state)
 {
     // Reset the zoom in effect. This allows the setZoom method to accurately compute a new zoom in effect.
@@ -655,22 +696,22 @@
             String cssURLValue = primitiveValue->getStringValue();
             KURL url = state.document().completeURL(cssURLValue);
             // FIXME: It doesn't work with forward or external SVG references (see https://bugs.webkit.org/show_bug.cgi?id=90405)
-            state.style()->setClipPath(ReferenceClipPathOperation::create(cssURLValue, url.fragmentIdentifier()));
+            state.style()->setClipPath(ReferenceClipPathOperation::create(cssURLValue, AtomicString(url.fragmentIdentifier())));
         }
     }
 }
 
-void StyleBuilderFunctions::applyInitialCSSPropertyWebkitFontVariantLigatures(StyleResolverState& state)
+void StyleBuilderFunctions::applyInitialCSSPropertyFontVariantLigatures(StyleResolverState& state)
 {
     state.fontBuilder().setFontVariantLigaturesInitial();
 }
 
-void StyleBuilderFunctions::applyInheritCSSPropertyWebkitFontVariantLigatures(StyleResolverState& state)
+void StyleBuilderFunctions::applyInheritCSSPropertyFontVariantLigatures(StyleResolverState& state)
 {
     state.fontBuilder().setFontVariantLigaturesInherit(state.parentFontDescription());
 }
 
-void StyleBuilderFunctions::applyValueCSSPropertyWebkitFontVariantLigatures(StyleResolverState& state, CSSValue* value)
+void StyleBuilderFunctions::applyValueCSSPropertyFontVariantLigatures(StyleResolverState& state, CSSValue* value)
 {
     state.fontBuilder().setFontVariantLigaturesValue(value);
 }
@@ -696,9 +737,8 @@
             break;
         }
     } else {
-        Length marqueeLength = primitiveValue ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData()) : Length(Undefined);
-        if (!marqueeLength.isUndefined())
-            state.style()->setMarqueeIncrement(marqueeLength);
+        Length marqueeLength = primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
+        state.style()->setMarqueeIncrement(marqueeLength);
     }
 }
 
@@ -853,56 +893,32 @@
     return; \
 }
 
-static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, const StyleResolverState& state, GridLength& workingLength)
+static GridLength createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, const StyleResolverState& state)
 {
-    if (primitiveValue->getValueID() == CSSValueMinContent) {
-        workingLength = Length(MinContent);
-        return true;
-    }
+    if (primitiveValue->getValueID() == CSSValueMinContent)
+        return Length(MinContent);
 
-    if (primitiveValue->getValueID() == CSSValueMaxContent) {
-        workingLength = Length(MaxContent);
-        return true;
-    }
+    if (primitiveValue->getValueID() == CSSValueMaxContent)
+        return Length(MaxContent);
 
-    if (primitiveValue->isFlex()) {
-        // Fractional unit.
-        workingLength.setFlex(primitiveValue->getDoubleValue());
-        return true;
-    }
+    // Fractional unit.
+    if (primitiveValue->isFlex())
+        return GridLength(primitiveValue->getDoubleValue());
 
-    workingLength = primitiveValue->convertToLength<FixedConversion | PercentConversion | AutoConversion>(state.cssToLengthConversionData());
-    if (workingLength.length().isUndefined())
-        return false;
-
-    if (primitiveValue->isLength())
-        workingLength.length().setQuirk(primitiveValue->isQuirkValue());
-
-    return true;
+    return primitiveValue->convertToLength<FixedConversion | PercentConversion | AutoConversion>(state.cssToLengthConversionData());
 }
 
-static bool createGridTrackSize(CSSValue* value, GridTrackSize& trackSize, const StyleResolverState& state)
+static GridTrackSize createGridTrackSize(CSSValue* value, const StyleResolverState& state)
 {
-    if (value->isPrimitiveValue()) {
-        CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-        GridLength workingLength;
-        if (!createGridTrackBreadth(primitiveValue, state, workingLength))
-            return false;
-
-        trackSize.setLength(workingLength);
-        return true;
-    }
+    if (value->isPrimitiveValue())
+        return GridTrackSize(createGridTrackBreadth(toCSSPrimitiveValue(value), state));
 
     CSSFunctionValue* minmaxFunction = toCSSFunctionValue(value);
     CSSValueList* arguments = minmaxFunction->arguments();
     ASSERT_WITH_SECURITY_IMPLICATION(arguments->length() == 2);
-    GridLength minTrackBreadth;
-    GridLength maxTrackBreadth;
-    if (!createGridTrackBreadth(toCSSPrimitiveValue(arguments->itemWithoutBoundsCheck(0)), state, minTrackBreadth) || !createGridTrackBreadth(toCSSPrimitiveValue(arguments->itemWithoutBoundsCheck(1)), state, maxTrackBreadth))
-        return false;
-
-    trackSize.setMinMax(minTrackBreadth, maxTrackBreadth);
-    return true;
+    GridLength minTrackBreadth(createGridTrackBreadth(toCSSPrimitiveValue(arguments->itemWithoutBoundsCheck(0)), state));
+    GridLength maxTrackBreadth(createGridTrackBreadth(toCSSPrimitiveValue(arguments->itemWithoutBoundsCheck(1)), state));
+    return GridTrackSize(minTrackBreadth, maxTrackBreadth);
 }
 
 static bool createGridTrackList(CSSValue* value, Vector<GridTrackSize>& trackSizes, NamedGridLinesMap& namedGridLines, OrderedNamedGridLines& orderedNamedGridLines, const StyleResolverState& state)
@@ -924,19 +940,15 @@
             for (CSSValueListIterator j = lineNamesValue; j.hasMore(); j.advance()) {
                 String namedGridLine = toCSSPrimitiveValue(j.value())->getStringValue();
                 NamedGridLinesMap::AddResult result = namedGridLines.add(namedGridLine, Vector<size_t>());
-                result.iterator->value.append(currentNamedGridLine);
+                result.storedValue->value.append(currentNamedGridLine);
                 OrderedNamedGridLines::AddResult orderedInsertionResult = orderedNamedGridLines.add(currentNamedGridLine, Vector<String>());
-                orderedInsertionResult.iterator->value.append(namedGridLine);
+                orderedInsertionResult.storedValue->value.append(namedGridLine);
             }
             continue;
         }
 
         ++currentNamedGridLine;
-        GridTrackSize trackSize;
-        if (!createGridTrackSize(currValue, trackSize, state))
-            return false;
-
-        trackSizes.append(trackSize);
+        trackSizes.append(createGridTrackSize(currValue, state));
     }
 
     // The parser should have rejected any <track-list> without any <track-size> as
@@ -1092,68 +1104,9 @@
     return false;
 }
 
-static bool hasVariableReference(CSSValue* value)
-{
-    if (value->isPrimitiveValue()) {
-        CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-        return primitiveValue->hasVariableReference();
-    }
-
-    if (value->isCalcValue())
-        return toCSSCalcValue(value)->hasVariableReference();
-
-    if (value->isReflectValue()) {
-        CSSReflectValue* reflectValue = toCSSReflectValue(value);
-        CSSPrimitiveValue* direction = reflectValue->direction();
-        CSSPrimitiveValue* offset = reflectValue->offset();
-        CSSValue* mask = reflectValue->mask();
-        return (direction && hasVariableReference(direction)) || (offset && hasVariableReference(offset)) || (mask && hasVariableReference(mask));
-    }
-
-    for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
-        if (hasVariableReference(i.value()))
-            return true;
-    }
-
-    return false;
-}
-
-// FIXME: Resolving variables should be factored better. Maybe a resover-style class?
-static void resolveVariables(StyleResolverState& state, CSSPropertyID id, CSSValue* value, Vector<std::pair<CSSPropertyID, String> >& knownExpressions)
-{
-    std::pair<CSSPropertyID, String> expression(id, value->serializeResolvingVariables(*state.style()->variables()));
-
-    if (knownExpressions.contains(expression))
-        return; // cycle detected.
-
-    knownExpressions.append(expression);
-
-    // FIXME: It would be faster not to re-parse from strings, but for now CSS property validation lives inside the parser so we do it there.
-    RefPtr<MutableStylePropertySet> resultSet = MutableStylePropertySet::create();
-    if (!CSSParser::parseValue(resultSet.get(), id, expression.second, false, state.document()))
-        return; // expression failed to parse.
-
-    for (unsigned i = 0; i < resultSet->propertyCount(); i++) {
-        StylePropertySet::PropertyReference property = resultSet->propertyAt(i);
-        if (property.id() != CSSPropertyVariable && hasVariableReference(property.value())) {
-            resolveVariables(state, property.id(), property.value(), knownExpressions);
-        } else {
-            StyleBuilder::applyProperty(property.id(), state, property.value());
-            // All properties become dependent on their parent style when they use variables.
-            state.style()->setHasExplicitlyInheritedProperties();
-        }
-    }
-}
 
 void StyleBuilder::applyProperty(CSSPropertyID id, StyleResolverState& state, CSSValue* value)
 {
-    if (RuntimeEnabledFeatures::cssVariablesEnabled() && id != CSSPropertyVariable && hasVariableReference(value)) {
-        Vector<std::pair<CSSPropertyID, String> > knownExpressions;
-        resolveVariables(state, id, value, knownExpressions);
-        return;
-    }
-
-    // CSS variables don't resolve shorthands at parsing time, so this should be *after* handling variables.
     ASSERT_WITH_MESSAGE(!isExpandedShorthand(id), "Shorthand property id = %d wasn't expanded at parsing time", id);
 
     bool isInherit = state.parentNode() && value->isInheritedValue();
@@ -1174,15 +1127,6 @@
     if (isInherit && !state.parentStyle()->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(id))
         state.parentStyle()->setHasExplicitlyInheritedProperties();
 
-    if (id == CSSPropertyVariable) {
-        ASSERT_WITH_SECURITY_IMPLICATION(value->isVariableValue());
-        CSSVariableValue* variable = toCSSVariableValue(value);
-        ASSERT(!variable->name().isEmpty());
-        ASSERT(!variable->value().isEmpty());
-        state.style()->setVariable(variable->name(), variable->value());
-        return;
-    }
-
     if (StyleBuilder::applyProperty(id, state, value, isInitial, isInherit))
         return;
 
@@ -1606,29 +1550,23 @@
     }
     case CSSPropertyGridAutoColumns: {
         HANDLE_INHERIT_AND_INITIAL(gridAutoColumns, GridAutoColumns);
-        GridTrackSize trackSize;
-        if (!createGridTrackSize(value, trackSize, state))
-            return;
-        state.style()->setGridAutoColumns(trackSize);
+        state.style()->setGridAutoColumns(createGridTrackSize(value, state));
         return;
     }
     case CSSPropertyGridAutoRows: {
         HANDLE_INHERIT_AND_INITIAL(gridAutoRows, GridAutoRows);
-        GridTrackSize trackSize;
-        if (!createGridTrackSize(value, trackSize, state))
-            return;
-        state.style()->setGridAutoRows(trackSize);
+        state.style()->setGridAutoRows(createGridTrackSize(value, state));
         return;
     }
-    case CSSPropertyGridDefinitionColumns: {
+    case CSSPropertyGridTemplateColumns: {
         if (isInherit) {
-            state.style()->setGridDefinitionColumns(state.parentStyle()->gridDefinitionColumns());
+            state.style()->setGridTemplateColumns(state.parentStyle()->gridTemplateColumns());
             state.style()->setNamedGridColumnLines(state.parentStyle()->namedGridColumnLines());
             state.style()->setOrderedNamedGridColumnLines(state.parentStyle()->orderedNamedGridColumnLines());
             return;
         }
         if (isInitial) {
-            state.style()->setGridDefinitionColumns(RenderStyle::initialGridDefinitionColumns());
+            state.style()->setGridTemplateColumns(RenderStyle::initialGridTemplateColumns());
             state.style()->setNamedGridColumnLines(RenderStyle::initialNamedGridColumnLines());
             state.style()->setOrderedNamedGridColumnLines(RenderStyle::initialOrderedNamedGridColumnLines());
             return;
@@ -1639,20 +1577,20 @@
         OrderedNamedGridLines orderedNamedGridLines;
         if (!createGridTrackList(value, trackSizes, namedGridLines, orderedNamedGridLines, state))
             return;
-        state.style()->setGridDefinitionColumns(trackSizes);
+        state.style()->setGridTemplateColumns(trackSizes);
         state.style()->setNamedGridColumnLines(namedGridLines);
         state.style()->setOrderedNamedGridColumnLines(orderedNamedGridLines);
         return;
     }
-    case CSSPropertyGridDefinitionRows: {
+    case CSSPropertyGridTemplateRows: {
         if (isInherit) {
-            state.style()->setGridDefinitionRows(state.parentStyle()->gridDefinitionRows());
+            state.style()->setGridTemplateRows(state.parentStyle()->gridTemplateRows());
             state.style()->setNamedGridRowLines(state.parentStyle()->namedGridRowLines());
             state.style()->setOrderedNamedGridRowLines(state.parentStyle()->orderedNamedGridRowLines());
             return;
         }
         if (isInitial) {
-            state.style()->setGridDefinitionRows(RenderStyle::initialGridDefinitionRows());
+            state.style()->setGridTemplateRows(RenderStyle::initialGridTemplateRows());
             state.style()->setNamedGridRowLines(RenderStyle::initialNamedGridRowLines());
             state.style()->setOrderedNamedGridRowLines(RenderStyle::initialOrderedNamedGridRowLines());
             return;
@@ -1663,7 +1601,7 @@
         OrderedNamedGridLines orderedNamedGridLines;
         if (!createGridTrackList(value, trackSizes, namedGridLines, orderedNamedGridLines, state))
             return;
-        state.style()->setGridDefinitionRows(trackSizes);
+        state.style()->setGridTemplateRows(trackSizes);
         state.style()->setNamedGridRowLines(namedGridLines);
         state.style()->setOrderedNamedGridRowLines(orderedNamedGridLines);
         return;
@@ -1703,7 +1641,7 @@
         return;
     }
 
-    case CSSPropertyGridTemplate: {
+    case CSSPropertyGridTemplateAreas: {
         if (isInherit) {
             state.style()->setNamedGridArea(state.parentStyle()->namedGridArea());
             state.style()->setNamedGridAreaRowCount(state.parentStyle()->namedGridAreaRowCount());
@@ -1722,10 +1660,46 @@
             return;
         }
 
-        CSSGridTemplateValue* gridTemplateValue = toCSSGridTemplateValue(value);
-        state.style()->setNamedGridArea(gridTemplateValue->gridAreaMap());
-        state.style()->setNamedGridAreaRowCount(gridTemplateValue->rowCount());
-        state.style()->setNamedGridAreaColumnCount(gridTemplateValue->columnCount());
+        CSSGridTemplateAreasValue* gridTemplateAreasValue = toCSSGridTemplateAreasValue(value);
+        state.style()->setNamedGridArea(gridTemplateAreasValue->gridAreaMap());
+        state.style()->setNamedGridAreaRowCount(gridTemplateAreasValue->rowCount());
+        state.style()->setNamedGridAreaColumnCount(gridTemplateAreasValue->columnCount());
+        return;
+    }
+
+    case CSSPropertyJustifySelf: {
+        HANDLE_INHERIT_AND_INITIAL(justifySelf, JustifySelf);
+        CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+        if (Pair* pairValue = primitiveValue->getPairValue()) {
+            state.style()->setJustifySelf(*pairValue->first());
+            state.style()->setJustifySelfOverflowAlignment(*pairValue->second());
+        } else {
+            state.style()->setJustifySelf(*primitiveValue);
+        }
+        return;
+    }
+
+    case CSSPropertyAlignSelf: {
+        HANDLE_INHERIT_AND_INITIAL(alignSelf, AlignSelf);
+        CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+        if (Pair* pairValue = primitiveValue->getPairValue()) {
+            state.style()->setAlignSelf(*pairValue->first());
+            state.style()->setAlignSelfOverflowAlignment(*pairValue->second());
+        } else {
+            state.style()->setAlignSelf(*primitiveValue);
+        }
+        return;
+    }
+
+    case CSSPropertyAlignItems: {
+        HANDLE_INHERIT_AND_INITIAL(alignItems, AlignItems);
+        CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+        if (Pair* pairValue = primitiveValue->getPairValue()) {
+            state.style()->setAlignItems(*pairValue->first());
+            state.style()->setAlignItemsOverflowAlignment(*pairValue->second());
+        } else {
+            state.style()->setAlignItems(*primitiveValue);
+        }
         return;
     }
 
@@ -1795,6 +1769,7 @@
     case CSSPropertyFontSize:
     case CSSPropertyFontStyle:
     case CSSPropertyFontVariant:
+    case CSSPropertyFontVariantLigatures:
     case CSSPropertyFontWeight:
     case CSSPropertyHeight:
     case CSSPropertyImageRendering:
@@ -1835,6 +1810,7 @@
     case CSSPropertyPosition:
     case CSSPropertyResize:
     case CSSPropertyRight:
+    case CSSPropertyScrollBehavior:
     case CSSPropertySize:
     case CSSPropertySpeak:
     case CSSPropertyTabSize:
@@ -1855,7 +1831,6 @@
     case CSSPropertyTouchAction:
     case CSSPropertyTouchActionDelay:
     case CSSPropertyUnicodeBidi:
-    case CSSPropertyVariable:
     case CSSPropertyVerticalAlign:
     case CSSPropertyVisibility:
     case CSSPropertyWebkitAnimationDelay:
@@ -1901,8 +1876,6 @@
     case CSSPropertyWebkitColumnSpan:
     case CSSPropertyWebkitColumnWidth:
     case CSSPropertyAlignContent:
-    case CSSPropertyAlignItems:
-    case CSSPropertyAlignSelf:
     case CSSPropertyFlexBasis:
     case CSSPropertyFlexDirection:
     case CSSPropertyFlexGrow:
@@ -1910,17 +1883,11 @@
     case CSSPropertyFlexWrap:
     case CSSPropertyJustifyContent:
     case CSSPropertyOrder:
-    case CSSPropertyWebkitFlowFrom:
-    case CSSPropertyWebkitFlowInto:
     case CSSPropertyWebkitFontSmoothing:
-    case CSSPropertyWebkitFontVariantLigatures:
     case CSSPropertyWebkitHighlight:
     case CSSPropertyWebkitHyphenateCharacter:
-    case CSSPropertyWebkitLineAlign:
     case CSSPropertyWebkitLineBreak:
     case CSSPropertyWebkitLineClamp:
-    case CSSPropertyWebkitLineGrid:
-    case CSSPropertyWebkitLineSnap:
     case CSSPropertyInternalMarqueeDirection:
     case CSSPropertyInternalMarqueeIncrement:
     case CSSPropertyInternalMarqueeRepetition:
@@ -1945,10 +1912,6 @@
     case CSSPropertyWebkitPerspectiveOriginX:
     case CSSPropertyWebkitPerspectiveOriginY:
     case CSSPropertyWebkitPrintColorAdjust:
-    case CSSPropertyWebkitRegionBreakAfter:
-    case CSSPropertyWebkitRegionBreakBefore:
-    case CSSPropertyWebkitRegionBreakInside:
-    case CSSPropertyWebkitRegionFragment:
     case CSSPropertyWebkitRtlOrdering:
     case CSSPropertyWebkitRubyPosition:
     case CSSPropertyWebkitTextCombine:
@@ -2108,7 +2071,7 @@
 
         CSSValueList* dashes = toCSSValueList(value);
 
-        Vector<SVGLength> array;
+        RefPtr<SVGLengthList> array = SVGLengthList::create();
         size_t length = dashes->length();
         for (size_t i = 0; i < length; ++i) {
             CSSValue* currValue = dashes->itemWithoutBoundsCheck(i);
@@ -2116,10 +2079,10 @@
                 continue;
 
             CSSPrimitiveValue* dash = toCSSPrimitiveValue(dashes->itemWithoutBoundsCheck(i));
-            array.append(SVGLength::fromCSSPrimitiveValue(dash));
+            array->append(SVGLength::fromCSSPrimitiveValue(dash));
         }
 
-        state.style()->accessSVGStyle()->setStrokeDashArray(array);
+        state.style()->accessSVGStyle()->setStrokeDashArray(array.release());
         break;
     }
     case CSSPropertyStopColor:
diff --git a/Source/core/css/resolver/StyleBuilderCustom.h b/Source/core/css/resolver/StyleBuilderCustom.h
deleted file mode 100644
index 1729604..0000000
--- a/Source/core/css/resolver/StyleBuilderCustom.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef StyleBuilderCustom_h
-#define StyleBuilderCustom_h
-
-#include "core/css/CSSValue.h"
-#include "core/css/resolver/StyleResolverState.h"
-#include "core/rendering/RenderView.h"
-#include "core/rendering/style/ShadowList.h"
-#include "core/svg/SVGLength.h"
-#include "platform/LengthSize.h"
-
-namespace WebCore {
-
-// Note that we assume the parser only allows valid CSSValue types.
-
-class StyleBuilderConverter {
-public:
-    static String convertFragmentIdentifier(StyleResolverState&, CSSValue*);
-    template <typename T> static T convertComputedLength(StyleResolverState&, CSSValue*);
-    template <typename T> static T convertLineWidth(StyleResolverState&, CSSValue*);
-    static Length convertLength(StyleResolverState&, CSSValue*);
-    static Length convertLengthOrAuto(StyleResolverState&, CSSValue*);
-    static Length convertLengthSizing(StyleResolverState&, CSSValue*);
-    static Length convertLengthMaxSizing(StyleResolverState&, CSSValue*);
-    static LengthPoint convertLengthPoint(StyleResolverState&, CSSValue*);
-    static float convertNumberOrPercentage(StyleResolverState&, CSSValue*);
-    static LengthSize convertRadius(StyleResolverState&, CSSValue*);
-    static PassRefPtr<ShadowList> convertShadow(StyleResolverState&, CSSValue*);
-    static float convertSpacing(StyleResolverState&, CSSValue*);
-    template <CSSValueID IdForNone> static AtomicString convertString(StyleResolverState&, CSSValue*);
-    static SVGLength convertSVGLength(StyleResolverState&, CSSValue*);
-};
-
-template <typename T>
-T StyleBuilderConverter::convertComputedLength(StyleResolverState& state, CSSValue* value)
-{
-    return toCSSPrimitiveValue(value)->computeLength<T>(state.cssToLengthConversionData());
-}
-
-template <typename T>
-T StyleBuilderConverter::convertLineWidth(StyleResolverState& state, CSSValue* value)
-{
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-    CSSValueID valueID = primitiveValue->getValueID();
-    if (valueID == CSSValueThin)
-        return 1;
-    if (valueID == CSSValueMedium)
-        return 3;
-    if (valueID == CSSValueThick)
-        return 5;
-    if (primitiveValue->isViewportPercentageLength())
-        return intValueForLength(primitiveValue->viewportPercentageLength(), 0, state.document().renderView());
-    if (valueID == CSSValueInvalid) {
-        // Any original result that was >= 1 should not be allowed to fall below 1.
-        // This keeps border lines from vanishing.
-        T result = primitiveValue->computeLength<T>(state.cssToLengthConversionData());
-        if (state.style()->effectiveZoom() < 1.0f && result < 1.0) {
-            T originalLength = primitiveValue->computeLength<T>(state.cssToLengthConversionData().copyWithAdjustedZoom(1.0));
-            if (originalLength >= 1.0)
-                return 1.0;
-        }
-        return result;
-    }
-    ASSERT_NOT_REACHED();
-    return 0;
-}
-
-template <CSSValueID IdForNone>
-AtomicString StyleBuilderConverter::convertString(StyleResolverState&, CSSValue* value)
-{
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-    if (primitiveValue->getValueID() == IdForNone)
-        return nullAtom;
-    return AtomicString(primitiveValue->getStringValue());
-}
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index d742743..7daa31e 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -42,18 +42,17 @@
 #include "core/animation/css/CSSAnimations.h"
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSDefaultStyleSheets.h"
-#include "core/css/CSSFontFace.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSKeyframeRule.h"
 #include "core/css/CSSKeyframesRule.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSReflectValue.h"
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSStyleRule.h"
 #include "core/css/CSSValueList.h"
-#include "core/css/CSSVariableValue.h"
 #include "core/css/ElementRuleCollector.h"
+#include "core/css/FontFace.h"
 #include "core/css/MediaQueryEvaluator.h"
 #include "core/css/PageRuleCollector.h"
 #include "core/css/StylePropertySet.h"
@@ -78,7 +77,6 @@
 #include "core/frame/FrameView.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/KeyframeList.h"
-#include "core/rendering/style/StyleCustomFilterProgramCache.h"
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGFontFaceElement.h"
@@ -94,7 +92,7 @@
 {
     // If any changes to CSS Animations were detected, stash the update away for application after the
     // render object is updated if we're in the appropriate scope.
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && state.animationUpdate())
+    if (state.animationUpdate())
         element.ensureActiveAnimations()->cssAnimations().setPendingUpdate(state.takeAnimationUpdate());
 }
 
@@ -124,9 +122,9 @@
 
 static void addFontFaceRule(Document* document, CSSFontSelector* cssFontSelector, const StyleRuleFontFace* fontFaceRule)
 {
-    RefPtr<CSSFontFace> cssFontFace = CSSFontFace::createFromStyleRule(document, fontFaceRule);
-    if (cssFontFace)
-        cssFontSelector->addFontFaceRule(fontFaceRule, cssFontFace);
+    RefPtr<FontFace> fontFace = FontFace::create(document, fontFaceRule);
+    if (fontFace)
+        cssFontSelector->fontFaceCache()->add(cssFontSelector, fontFaceRule, fontFace);
 }
 
 StyleResolver::StyleResolver(Document& document)
@@ -137,9 +135,6 @@
     , m_styleResolverStatsSequence(0)
     , m_accessCount(0)
 {
-    // FIXME: Why do this here instead of as part of resolving style on the root?
-    CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary();
-
     // Construct document root element default style. This is needed
     // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
     // This is here instead of constructor because when constructor is run,
@@ -202,15 +197,13 @@
     if (cssSheet->mediaQueries() && !m_medium->eval(cssSheet->mediaQueries(), &m_viewportDependentMediaQueryResults))
         return;
 
-    StyleSheetContents* sheet = cssSheet->contents();
     ContainerNode* scopingNode = ScopedStyleResolver::scopingNodeFor(document(), cssSheet);
     if (!scopingNode)
         return;
 
     ScopedStyleResolver* resolver = ensureScopedStyleResolver(scopingNode);
     ASSERT(resolver);
-    resolver->addRulesFromSheet(sheet, *m_medium, this);
-    m_inspectorCSSOMWrappers.collectFromStyleSheetIfNeeded(cssSheet);
+    resolver->addRulesFromSheet(cssSheet, *m_medium, this);
 }
 
 void StyleResolver::appendPendingAuthorStyleSheets()
@@ -316,11 +309,12 @@
     // Collect all ids and rules using sibling selectors (:first-child and similar)
     // in the current set of stylesheets. Style sharing code uses this information to reject
     // sharing candidates.
-    if (CSSDefaultStyleSheets::defaultStyle)
-        m_features.add(CSSDefaultStyleSheets::defaultStyle->features());
+    CSSDefaultStyleSheets& defaultStyleSheets = CSSDefaultStyleSheets::instance();
+    if (defaultStyleSheets.defaultStyle())
+        m_features.add(defaultStyleSheets.defaultStyle()->features());
 
     if (document().isViewSource())
-        m_features.add(CSSDefaultStyleSheets::viewSourceStyle()->features());
+        m_features.add(defaultStyleSheets.defaultViewSourceStyle()->features());
 
     if (m_watchedSelectorsRules)
         m_features.add(m_watchedSelectorsRules->features());
@@ -336,7 +330,7 @@
 
 bool StyleResolver::hasRulesForId(const AtomicString& id) const
 {
-    return m_features.idsInRules.contains(id);
+    return m_features.hasSelectorForId(id);
 }
 
 void StyleResolver::addToStyleSharingList(Element& element)
@@ -356,10 +350,10 @@
     m_styleSharingList.clear();
 }
 
-void StyleResolver::fontsNeedUpdate(FontSelector* fontSelector)
+void StyleResolver::fontsNeedUpdate(CSSFontSelector* fontSelector)
 {
     invalidateMatchedPropertiesCache();
-    m_document.setNeedsStyleRecalc();
+    m_document.setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 void StyleResolver::pushParentElement(Element& parent)
@@ -413,14 +407,22 @@
 
     RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
 
-    CascadeOrder cascadeOrder = 0;
+    // When comparing rules declared in outer treescopes, outer's rules win.
+    CascadeOrder outerCascadeOrder = m_treeBoundaryCrossingRules.size() + m_treeBoundaryCrossingRules.size();
+    // When comparing rules declared in inner treescopes, inner's rules win.
+    CascadeOrder innerCascadeOrder = m_treeBoundaryCrossingRules.size();
 
-    DocumentOrderedList::iterator it = m_treeBoundaryCrossingRules.end();
-    while (it != m_treeBoundaryCrossingRules.begin()) {
-        --it;
+    for (DocumentOrderedList::iterator it = m_treeBoundaryCrossingRules.begin(); it != m_treeBoundaryCrossingRules.end(); ++it) {
         const ContainerNode* scopingNode = toContainerNode(*it);
+
+        if (ShadowRoot* shadowRoot = scopingNode->containingShadowRoot()) {
+            if (!shadowRoot->isActiveForStyling())
+                continue;
+        }
+
         RuleSet* ruleSet = m_treeBoundaryCrossingRules.ruleSetScopedBy(scopingNode);
-        unsigned boundaryBehavior = SelectorChecker::CrossesBoundary | SelectorChecker::ScopeContainsLastMatchedElement;
+        unsigned boundaryBehavior = SelectorChecker::ScopeContainsLastMatchedElement;
+        bool isInnerTreeScope = element->treeScope().isInclusiveAncestorOf(scopingNode->treeScope());
 
         // If a given scoping node is a shadow root and a given element is in a descendant tree of tree hosted by
         // the scoping node's shadow host, we should use ScopeIsShadowHost.
@@ -429,7 +431,12 @@
                 boundaryBehavior |= SelectorChecker::ScopeIsShadowHost;
             scopingNode = toShadowRoot(scopingNode)->host();
         }
-        collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, scopingNode), ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(boundaryBehavior), ignoreCascadeScope, cascadeOrder++);
+
+        CascadeOrder cascadeOrder = isInnerTreeScope ? innerCascadeOrder : outerCascadeOrder;
+
+        collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, scopingNode), ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(boundaryBehavior), ignoreCascadeScope, cascadeOrder);
+        ++innerCascadeOrder;
+        --outerCascadeOrder;
     }
 }
 
@@ -509,7 +516,6 @@
     MatchRequest matchRequest(m_watchedSelectorsRules.get());
     RuleRange ruleRange = collector.matchedResult().ranges.userRuleRange();
     collector.collectMatchingRules(matchRequest, ruleRange);
-    collector.collectMatchingRulesForRegion(matchRequest, ruleRange);
 
     collector.sortAndTransferMatchedRules();
 }
@@ -518,17 +524,18 @@
 {
     collector.setMatchingUARules(true);
 
+    CSSDefaultStyleSheets& defaultStyleSheets = CSSDefaultStyleSheets::instance();
     RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
-        ? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle;
+        ? defaultStyleSheets.defaultPrintStyle() : defaultStyleSheets.defaultStyle();
     matchUARules(collector, userAgentStyleSheet);
 
     // In quirks mode, we match rules from the quirks user agent sheet.
     if (document().inQuirksMode())
-        matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle);
+        matchUARules(collector, defaultStyleSheets.defaultQuirksStyle());
 
     // If document uses view source styles (in view source mode or in xml viewer mode), then we match rules from the view source style sheet.
     if (document().isViewSource())
-        matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle());
+        matchUARules(collector, defaultStyleSheets.defaultViewSourceStyle());
 
     collector.setMatchingUARules(false);
 
@@ -586,29 +593,16 @@
 {
     const Frame* frame = document.frame();
 
-    // HTML5 states that seamless iframes should replace default CSS values
-    // with values inherited from the containing iframe element. However,
-    // some values (such as the case of designMode = "on") still need to
-    // be set by this "document style".
     RefPtr<RenderStyle> documentStyle = RenderStyle::create();
-    bool seamlessWithParent = document.shouldDisplaySeamlesslyWithParent();
-    if (seamlessWithParent) {
-        RenderStyle* iframeStyle = document.seamlessParentIFrame()->renderStyle();
-        if (iframeStyle)
-            documentStyle->inheritFrom(iframeStyle);
-    }
-
-    // FIXME: It's not clear which values below we want to override in the seamless case!
     documentStyle->setDisplay(BLOCK);
-    if (!seamlessWithParent) {
-        documentStyle->setRTLOrdering(document.visuallyOrdered() ? VisualOrder : LogicalOrder);
-        documentStyle->setZoom(frame && !document.printing() ? frame->pageZoomFactor() : 1);
-        documentStyle->setLocale(document.contentLanguage());
-    }
+    documentStyle->setRTLOrdering(document.visuallyOrdered() ? VisualOrder : LogicalOrder);
+    documentStyle->setZoom(frame && !document.printing() ? frame->pageZoomFactor() : 1);
+    documentStyle->setLocale(document.contentLanguage());
+
     // This overrides any -webkit-user-modify inherited from the parent iframe.
     documentStyle->setUserModify(document.inDesignMode() ? READ_WRITE : READ_ONLY);
 
-    document.setStyleDependentState(documentStyle.get());
+    document.setupFontBuilder(documentStyle.get());
     return documentStyle.release();
 }
 
@@ -631,11 +625,11 @@
 static void addContentAttrValuesToFeatures(const Vector<AtomicString>& contentAttrValues, RuleFeatureSet& features)
 {
     for (size_t i = 0; i < contentAttrValues.size(); ++i)
-        features.attrsInRules.add(contentAttrValues[i]);
+        features.addAttributeInASelector(contentAttrValues[i]);
 }
 
 PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderStyle* defaultParent, StyleSharingBehavior sharingBehavior,
-    RuleMatchingBehavior matchingBehavior, RenderRegion* regionForStyling)
+    RuleMatchingBehavior matchingBehavior)
 {
     ASSERT(document().frame());
     ASSERT(documentSettings());
@@ -658,9 +652,9 @@
 
     if (element == document().documentElement())
         resetDirectionAndWritingModeOnDocument(document());
-    StyleResolverState state(document(), element, defaultParent, regionForStyling);
+    StyleResolverState state(document(), element, defaultParent);
 
-    if (sharingBehavior == AllowStyleSharing && !state.distributedToInsertionPoint() && state.parentStyle()) {
+    if (sharingBehavior == AllowStyleSharing && state.parentStyle()) {
         SharedStyleFinder styleFinder(state.elementContext(), m_features, m_siblingRuleSet.get(), m_uncommonAttributeRuleSet.get(), *this);
         if (RefPtr<RenderStyle> sharedStyle = styleFinder.findSharedStyle())
             return sharedStyle.release();
@@ -696,15 +690,12 @@
     }
 
     bool needsCollection = false;
-    CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(element, needsCollection);
-    if (needsCollection) {
+    CSSDefaultStyleSheets::instance().ensureDefaultStyleSheetsForElement(element, needsCollection);
+    if (needsCollection)
         collectFeatures();
-        m_inspectorCSSOMWrappers.reset();
-    }
 
     {
         ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style());
-        collector.setRegionForStyling(regionForStyling);
 
         if (matchingBehavior == MatchOnlyUserAgentRules)
             matchUARules(collector);
@@ -731,11 +722,14 @@
 
     setAnimationUpdateIfNeeded(state, *element);
 
+    if (state.style()->hasViewportUnits())
+        document().setHasViewportUnits();
+
     // Now return the style.
     return state.takeStyle();
 }
 
-PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(Element* element, const RenderStyle& elementStyle, const StyleKeyframe* keyframe, const AtomicString& animationName)
+PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(Element* element, const RenderStyle& elementStyle, RenderStyle* parentStyle, const StyleKeyframe* keyframe, const AtomicString& animationName)
 {
     ASSERT(document().frame());
     ASSERT(documentSettings());
@@ -743,7 +737,7 @@
 
     if (element == document().documentElement())
         resetDirectionAndWritingModeOnDocument(document());
-    StyleResolverState state(document(), element);
+    StyleResolverState state(document(), element, parentStyle);
 
     MatchResult result;
     if (keyframe->properties())
@@ -773,7 +767,6 @@
     // decl, there's nothing to override. So just add the first properties.
     bool inheritedOnly = false;
     if (keyframe->properties()) {
-        // FIXME: Can't keyframes contain variables?
         applyMatchedProperties<AnimationProperties>(state, result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
         applyMatchedProperties<HighPriorityProperties>(state, result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
     }
@@ -802,76 +795,64 @@
     return state.takeStyle();
 }
 
-void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle& elementStyle, KeyframeList& list)
+// This function is used by the WebAnimations JavaScript API method animate().
+// FIXME: Remove this when animate() switches away from resolution-dependent parsing.
+PassRefPtr<KeyframeEffectModel> StyleResolver::createKeyframeEffectModel(Element& element, const Vector<RefPtr<MutableStylePropertySet> >& propertySetVector, KeyframeEffectModel::KeyframeVector& keyframes)
 {
-    ASSERT(!RuntimeEnabledFeatures::webAnimationsCSSEnabled());
-    list.clear();
+    ASSERT(propertySetVector.size() == keyframes.size());
 
-    // Get the keyframesRule for this name
-    if (!e || list.animationName().isEmpty())
-        return;
+    StyleResolverState state(element.document(), &element);
+    state.setStyle(RenderStyle::create());
 
-    ASSERT(!hasPendingAuthorStyleSheets());
-    const StyleRuleKeyframes* keyframesRule = CSSAnimations::matchScopedKeyframesRule(this, e, list.animationName().impl());
-    if (!keyframesRule)
-        return;
-
-    // Construct and populate the style for each keyframe
-    const AtomicString& name = list.animationName();
-    const Vector<RefPtr<StyleKeyframe> >& keyframes = keyframesRule->keyframes();
-    for (unsigned i = 0; i < keyframes.size(); ++i) {
-        // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
-        const StyleKeyframe* keyframe = keyframes[i].get();
-
-        KeyframeValue keyframeValue(0, 0);
-        keyframeValue.setStyle(styleForKeyframe(e, elementStyle, keyframe, name));
-        keyframeValue.addProperties(keyframe->properties());
-
-        // Add this keyframe style to all the indicated key times
-        const Vector<double>& keys = keyframe->keys();
-        for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
-            keyframeValue.setKey(keys[keyIndex]);
-            list.insert(keyframeValue);
+    for (unsigned i = 0; i < propertySetVector.size(); ++i) {
+        for (unsigned j = 0; j < propertySetVector[i]->propertyCount(); ++j) {
+            CSSPropertyID id = propertySetVector[i]->propertyAt(j).id();
+            StyleBuilder::applyProperty(id, state, propertySetVector[i]->getPropertyCSSValue(id).get());
+            keyframes[i]->setPropertyValue(id, CSSAnimatableValueFactory::create(id, *state.style()).get());
         }
     }
-
-    // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
-    int initialListSize = list.size();
-    if (initialListSize > 0 && list[0].key()) {
-        static StyleKeyframe* zeroPercentKeyframe;
-        if (!zeroPercentKeyframe) {
-            zeroPercentKeyframe = StyleKeyframe::create().leakRef();
-            zeroPercentKeyframe->setKeyText("0%");
-        }
-        KeyframeValue keyframeValue(0, 0);
-        keyframeValue.setStyle(styleForKeyframe(e, elementStyle, zeroPercentKeyframe, name));
-        keyframeValue.addProperties(zeroPercentKeyframe->properties());
-        list.insert(keyframeValue);
-    }
-
-    // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
-    if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
-        static StyleKeyframe* hundredPercentKeyframe;
-        if (!hundredPercentKeyframe) {
-            hundredPercentKeyframe = StyleKeyframe::create().leakRef();
-            hundredPercentKeyframe->setKeyText("100%");
-        }
-        KeyframeValue keyframeValue(1, 0);
-        keyframeValue.setStyle(styleForKeyframe(e, elementStyle, hundredPercentKeyframe, name));
-        keyframeValue.addProperties(hundredPercentKeyframe->properties());
-        list.insert(keyframeValue);
-    }
+    return KeyframeEffectModel::create(keyframes);
 }
 
-PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* element, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle)
+PassRefPtr<PseudoElement> StyleResolver::createPseudoElementIfNeeded(Element& parent, PseudoId pseudoId)
+{
+    RenderObject* parentRenderer = parent.renderer();
+    if (!parentRenderer)
+        return 0;
+
+    if (pseudoId < FIRST_INTERNAL_PSEUDOID && !parentRenderer->style()->hasPseudoStyle(pseudoId))
+        return 0;
+
+    if (pseudoId == BACKDROP && !parent.isInTopLayer())
+        return 0;
+
+    if (!parentRenderer->canHaveGeneratedChildren())
+        return 0;
+
+    RenderStyle* parentStyle = parentRenderer->style();
+    StyleResolverState state(document(), &parent, parentStyle);
+    if (!pseudoStyleForElementInternal(parent, pseudoId, parentStyle, state))
+        return 0;
+    RefPtr<RenderStyle> style = state.takeStyle();
+    ASSERT(style);
+
+    if (!pseudoElementRendererIsNeeded(style.get()))
+        return 0;
+
+    parentStyle->addCachedPseudoStyle(style.release());
+    RefPtr<PseudoElement> pseudo = PseudoElement::create(&parent, pseudoId);
+
+    setAnimationUpdateIfNeeded(state, *pseudo);
+    if (ActiveAnimations* activeAnimations = pseudo->activeAnimations())
+        activeAnimations->cssAnimations().maybeApplyPendingUpdate(pseudo.get());
+    return pseudo.release();
+}
+
+bool StyleResolver::pseudoStyleForElementInternal(Element& element, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, StyleResolverState& state)
 {
     ASSERT(document().frame());
     ASSERT(documentSettings());
-    ASSERT(parentStyle);
-    if (!element)
-        return 0;
-
-    StyleResolverState state(document(), element, parentStyle);
+    ASSERT(pseudoStyleRequest.pseudoId != FIRST_LINE_INHERITED);
 
     if (pseudoStyleRequest.allowsInheritance(state.parentStyle())) {
         state.setStyle(RenderStyle::create());
@@ -895,7 +876,7 @@
         matchAuthorRules(state.element(), collector, false);
 
         if (collector.matchedResult().matchedProperties.isEmpty())
-            return 0;
+            return false;
 
         state.style()->setStyleType(pseudoStyleRequest.pseudoId);
 
@@ -913,10 +894,26 @@
     // FIXME: The CSSWG wants to specify that the effects of animations are applied before
     // important rules, but this currently happens here as we require adjustment to have happened
     // before deciding which properties to transition.
-    applyAnimatedProperties(state, element->pseudoElement(pseudoStyleRequest.pseudoId));
+    applyAnimatedProperties(state, element.pseudoElement(pseudoStyleRequest.pseudoId));
 
     didAccess();
 
+    if (state.style()->hasViewportUnits())
+        document().setHasViewportUnits();
+
+    return true;
+}
+
+PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* element, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle)
+{
+    ASSERT(parentStyle);
+    if (!element)
+        return 0;
+
+    StyleResolverState state(document(), element, parentStyle);
+    if (!pseudoStyleForElementInternal(*element, pseudoStyleRequest, parentStyle, state))
+        return 0;
+
     if (PseudoElement* pseudoElement = element->pseudoElement(pseudoStyleRequest.pseudoId))
         setAnimationUpdateIfNeeded(state, *pseudoElement);
 
@@ -939,7 +936,7 @@
 
     PageRuleCollector collector(rootElementStyle, pageIndex);
 
-    collector.matchPageRules(CSSDefaultStyleSheets::defaultPrintStyle);
+    collector.matchPageRules(CSSDefaultStyleSheets::instance().defaultPrintStyle());
 
     if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument())
         scopedResolver->matchPageRules(collector);
@@ -948,7 +945,6 @@
     bool inheritedOnly = false;
 
     MatchResult& result = collector.matchedResult();
-    applyMatchedProperties<VariableDefinitions>(state, result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
     applyMatchedProperties<HighPriorityProperties>(state, result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
 
     // If our font got dirtied, go ahead and update it now.
@@ -974,13 +970,14 @@
 
 void StyleResolver::collectViewportRules()
 {
-    viewportStyleResolver()->collectViewportRules(CSSDefaultStyleSheets::defaultStyle, ViewportStyleResolver::UserAgentOrigin);
+    CSSDefaultStyleSheets& defaultStyleSheets = CSSDefaultStyleSheets::instance();
+    viewportStyleResolver()->collectViewportRules(defaultStyleSheets.defaultStyle(), ViewportStyleResolver::UserAgentOrigin);
 
     if (!InspectorInstrumentation::applyViewportStyleOverride(&document(), this))
-        viewportStyleResolver()->collectViewportRules(CSSDefaultStyleSheets::defaultViewportStyle, ViewportStyleResolver::UserAgentOrigin);
+        viewportStyleResolver()->collectViewportRules(defaultStyleSheets.defaultViewportStyle(), ViewportStyleResolver::UserAgentOrigin);
 
     if (document().isMobileDocument())
-        viewportStyleResolver()->collectViewportRules(CSSDefaultStyleSheets::xhtmlMobileProfileStyle(), ViewportStyleResolver::UserAgentOrigin);
+        viewportStyleResolver()->collectViewportRules(defaultStyleSheets.defaultXHTMLMobileProfileStyle(), ViewportStyleResolver::UserAgentOrigin);
 
     if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument())
         scopedResolver->collectViewportRulesTo(this);
@@ -1011,20 +1008,11 @@
     return parentNode->renderStyle();
 }
 
-bool StyleResolver::checkRegionStyle(Element* regionElement)
-{
-    // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
-    // so all region rules are global by default. Verify whether that can stand or needs changing.
-    if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument()) {
-        if (scopedResolver->checkRegionStyle(regionElement))
-            return true;
-    }
-    return false;
-}
-
 void StyleResolver::updateFont(StyleResolverState& state)
 {
     state.fontBuilder().createFont(document().styleEngine()->fontSelector(), state.parentStyle(), state.style());
+    if (state.fontBuilder().fontSizeHasViewportUnits())
+        state.style()->setHasViewportUnits();
 }
 
 PassRefPtr<StyleRuleList> StyleResolver::styleRulesForElement(Element* element, unsigned rulesToInclude)
@@ -1037,19 +1025,19 @@
     return collector.matchedStyleRuleList();
 }
 
-PassRefPtr<CSSRuleList> StyleResolver::pseudoCSSRulesForElement(Element* element, PseudoId pseudoId, unsigned rulesToInclude, ShouldIncludeStyleSheetInCSSOMWrapper includeDocument)
+PassRefPtr<CSSRuleList> StyleResolver::pseudoCSSRulesForElement(Element* element, PseudoId pseudoId, unsigned rulesToInclude)
 {
     ASSERT(element);
     StyleResolverState state(document(), element);
-    ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style(), includeDocument);
+    ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style());
     collector.setMode(SelectorChecker::CollectingCSSRules);
     collectPseudoRulesForElement(element, collector, pseudoId, rulesToInclude);
     return collector.matchedCSSRuleList();
 }
 
-PassRefPtr<CSSRuleList> StyleResolver::cssRulesForElement(Element* element, unsigned rulesToInclude, ShouldIncludeStyleSheetInCSSOMWrapper includeDocument)
+PassRefPtr<CSSRuleList> StyleResolver::cssRulesForElement(Element* element, unsigned rulesToInclude)
 {
-    return pseudoCSSRulesForElement(element, NOPSEUDO, rulesToInclude, includeDocument);
+    return pseudoCSSRulesForElement(element, NOPSEUDO, rulesToInclude);
 }
 
 void StyleResolver::collectPseudoRulesForElement(Element* element, ElementRuleCollector& collector, PseudoId pseudoId, unsigned rulesToInclude)
@@ -1070,19 +1058,23 @@
 
 void StyleResolver::applyAnimatedProperties(StyleResolverState& state, Element* animatingElement)
 {
-    // animatingElement may be null, for example if we're calculating the
-    // style for a potential pseudo element that has yet to be created.
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled() || !animatingElement)
-        return;
+    const Element* element = state.element();
+    ASSERT(element);
 
-    if (!animatingElement->hasActiveAnimations()
+    // The animating element may be this element, or its pseudo element. It is
+    // null when calculating the style for a potential pseudo element that has
+    // yet to be created.
+    ASSERT(animatingElement == element || !animatingElement || animatingElement->parentOrShadowHostElement() == element);
+
+    if (!(animatingElement && animatingElement->hasActiveAnimations())
         && !(state.style()->transitions() && !state.style()->transitions()->isEmpty())
         && !(state.style()->animations() && !state.style()->animations()->isEmpty()))
         return;
 
-    state.setAnimationUpdate(CSSAnimations::calculateUpdate(animatingElement, *state.style(), this));
+    state.setAnimationUpdate(CSSAnimations::calculateUpdate(animatingElement, *element, *state.style(), state.parentStyle(), this));
     if (!state.animationUpdate())
         return;
+
     const AnimationEffect::CompositableValueMap& compositableValuesForAnimations = state.animationUpdate()->compositableValuesForAnimations();
     const AnimationEffect::CompositableValueMap& compositableValuesForTransitions = state.animationUpdate()->compositableValuesForTransitions();
     applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForAnimations);
@@ -1101,8 +1093,6 @@
 template <StyleResolver::StyleApplicationPass pass>
 void StyleResolver::applyAnimatedProperties(StyleResolverState& state, const AnimationEffect::CompositableValueMap& compositableValues)
 {
-    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
-    ASSERT(pass != VariableDefinitions);
     ASSERT(pass != AnimationProperties);
 
     for (AnimationEffect::CompositableValueMap::const_iterator iter = compositableValues.begin(); iter != compositableValues.end(); ++iter) {
@@ -1115,21 +1105,6 @@
     }
 }
 
-// http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
-// FIXME: add incremental support for other region styling properties.
-static inline bool isValidRegionStyleProperty(CSSPropertyID id)
-{
-    switch (id) {
-    case CSSPropertyBackgroundColor:
-    case CSSPropertyColor:
-        return true;
-    default:
-        break;
-    }
-
-    return false;
-}
-
 static inline bool isValidCueStyleProperty(CSSPropertyID id)
 {
     switch (id) {
@@ -1181,7 +1156,6 @@
 template <StyleResolver::StyleApplicationPass pass>
 bool StyleResolver::isPropertyForPass(CSSPropertyID property)
 {
-    COMPILE_ASSERT(CSSPropertyVariable < firstCSSProperty, CSS_variable_is_before_first_property);
     const CSSPropertyID firstAnimationProperty = CSSPropertyDisplay;
     const CSSPropertyID lastAnimationProperty = CSSPropertyTransitionTimingFunction;
     COMPILE_ASSERT(firstCSSProperty == firstAnimationProperty, CSS_first_animation_property_should_be_first_property);
@@ -1191,8 +1165,6 @@
     COMPILE_ASSERT(CSSPropertyLineHeight == firstHighPriorityProperty + 17, CSS_line_height_is_end_of_high_prioity_property_range);
     COMPILE_ASSERT(CSSPropertyZoom == lastHighPriorityProperty - 1, CSS_zoom_is_before_line_height);
     switch (pass) {
-    case VariableDefinitions:
-        return property == CSSPropertyVariable;
     case AnimationProperties:
         return property >= firstAnimationProperty && property <= lastAnimationProperty;
     case HighPriorityProperties:
@@ -1207,7 +1179,6 @@
 template <StyleResolver::StyleApplicationPass pass>
 void StyleResolver::applyProperties(StyleResolverState& state, const StylePropertySet* properties, StyleRule* rule, bool isImportant, bool inheritedOnly, PropertyWhitelistType propertyWhitelistType)
 {
-    ASSERT((propertyWhitelistType != PropertyWhitelistRegion) || state.regionForStyling());
     state.setCurrentRule(rule);
 
     unsigned propertyCount = properties->propertyCount();
@@ -1224,8 +1195,6 @@
         }
         CSSPropertyID property = current.id();
 
-        if (propertyWhitelistType == PropertyWhitelistRegion && !isValidRegionStyleProperty(property))
-            continue;
         if (propertyWhitelistType == PropertyWhitelistCue && !isValidCueStyleProperty(property))
             continue;
         if (!isPropertyForPass<pass>(property))
@@ -1273,6 +1242,12 @@
     m_matchedPropertiesCache.clear();
 }
 
+void StyleResolver::notifyResizeForViewportUnits()
+{
+    collectViewportRules();
+    m_matchedPropertiesCache.clearViewportDependent();
+}
+
 void StyleResolver::applyMatchedProperties(StyleResolverState& state, const MatchResult& matchResult)
 {
     const Element* element = state.element();
@@ -1291,7 +1266,8 @@
         // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
         // element context. This is fast and saves memory by reusing the style data structures.
         state.style()->copyNonInheritedFrom(cachedMatchedProperties->renderStyle.get());
-        if (state.parentStyle()->inheritedDataShared(cachedMatchedProperties->parentRenderStyle.get()) && !isAtShadowBoundary(element)) {
+        if (state.parentStyle()->inheritedDataShared(cachedMatchedProperties->parentRenderStyle.get()) && !isAtShadowBoundary(element)
+            && (!state.distributedToInsertionPoint() || state.style()->userModify() == READ_ONLY)) {
             INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyCacheInheritedHit);
 
             EInsideLink linkStatus = state.style()->insideLink();
@@ -1301,16 +1277,11 @@
 
             // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
             state.style()->setInsideLink(linkStatus);
+            return;
         }
         applyInheritedOnly = true;
     }
 
-    // First apply all variable definitions, as they may be used during application of later properties.
-    applyMatchedProperties<VariableDefinitions>(state, matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
-    applyMatchedProperties<VariableDefinitions>(state, matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
-    applyMatchedProperties<VariableDefinitions>(state, matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
-    applyMatchedProperties<VariableDefinitions>(state, matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
-
     // Apply animation properties in order to apply animation results and trigger transitions below.
     applyMatchedProperties<AnimationProperties>(state, matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
     applyMatchedProperties<AnimationProperties>(state, matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
@@ -1437,7 +1408,7 @@
         m_viewportDependentMediaQueryResults.append(list[i]);
 }
 
-bool StyleResolver::affectedByViewportChange() const
+bool StyleResolver::mediaQueryAffectedByViewportChange() const
 {
     for (unsigned i = 0; i < m_viewportDependentMediaQueryResults.size(); ++i) {
         if (m_medium->eval(&m_viewportDependentMediaQueryResults[i]->m_expression) != m_viewportDependentMediaQueryResults[i]->m_result)
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index af3c2ac..5dc926a 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -22,8 +22,8 @@
 #ifndef StyleResolver_h
 #define StyleResolver_h
 
-#include "core/animation/KeyframeAnimationEffect.h"
-#include "core/css/InspectorCSSOMWrappers.h"
+#include "core/animation/KeyframeEffectModel.h"
+#include "core/css/CSSFontSelectorClient.h"
 #include "core/css/PseudoStyleRequest.h"
 #include "core/css/RuleFeature.h"
 #include "core/css/RuleSet.h"
@@ -35,7 +35,6 @@
 #include "core/css/resolver/ScopedStyleResolver.h"
 #include "core/css/resolver/ScopedStyleTree.h"
 #include "core/css/resolver/StyleBuilder.h"
-#include "core/css/resolver/StyleResolverIncludes.h"
 #include "core/css/resolver/StyleResolverState.h"
 #include "core/css/resolver/StyleResourceLoader.h"
 #include "wtf/Deque.h"
@@ -62,7 +61,6 @@
 class KeyframeValue;
 class MediaQueryEvaluator;
 class MediaQueryResult;
-class RenderRegion;
 class RuleData;
 class Settings;
 class StyleKeyframe;
@@ -102,11 +100,11 @@
 };
 
 // This class selects a RenderStyle for a given element based on a collection of stylesheets.
-class StyleResolver : public FontSelectorClient {
+class StyleResolver FINAL : public CSSFontSelectorClient {
     WTF_MAKE_NONCOPYABLE(StyleResolver); WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit StyleResolver(Document&);
-    ~StyleResolver();
+    virtual ~StyleResolver();
 
     // FIXME: StyleResolver should not be keeping tree-walk state.
     // These should move to some global tree-walk state, or should be contained in a
@@ -118,12 +116,10 @@
     void popParentShadowRoot(const ShadowRoot&);
 
     PassRefPtr<RenderStyle> styleForElement(Element*, RenderStyle* parentStyle = 0, StyleSharingBehavior = AllowStyleSharing,
-        RuleMatchingBehavior = MatchAllRules, RenderRegion* regionForStyling = 0);
+        RuleMatchingBehavior = MatchAllRules);
 
-    // FIXME: keyframeStylesForAnimation is only used in the legacy animations implementation
-    // and should be removed when that is replaced by Web Animations.
-    void keyframeStylesForAnimation(Element*, const RenderStyle&, KeyframeList&);
-    PassRefPtr<RenderStyle> styleForKeyframe(Element*, const RenderStyle&, const StyleKeyframe*, const AtomicString& animationName);
+    PassRefPtr<RenderStyle> styleForKeyframe(Element*, const RenderStyle&, RenderStyle* parentStyle, const StyleKeyframe*, const AtomicString& animationName);
+    static PassRefPtr<KeyframeEffectModel> createKeyframeEffectModel(Element&, const Vector<RefPtr<MutableStylePropertySet> >&, KeyframeEffectModel::KeyframeVector&);
 
     PassRefPtr<RenderStyle> pseudoStyleForElement(Element*, const PseudoStyleRequest&, RenderStyle* parentStyle);
 
@@ -178,8 +174,8 @@
         AllButEmptyCSSRules = UAAndUserCSSRules | AuthorCSSRules | CrossOriginCSSRules,
         AllCSSRules         = AllButEmptyCSSRules | EmptyCSSRules,
     };
-    PassRefPtr<CSSRuleList> cssRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
-    PassRefPtr<CSSRuleList> pseudoCSSRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
+    PassRefPtr<CSSRuleList> cssRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules);
+    PassRefPtr<CSSRuleList> pseudoCSSRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules);
     PassRefPtr<StyleRuleList> styleRulesForElement(Element*, unsigned rulesToInclude);
 
     // |properties| is an array with |count| elements.
@@ -190,21 +186,17 @@
     void addMediaQueryResults(const MediaQueryResultList&);
     MediaQueryResultList* viewportDependentMediaQueryResults() { return &m_viewportDependentMediaQueryResults; }
     bool hasViewportDependentMediaQueries() const { return !m_viewportDependentMediaQueryResults.isEmpty(); }
-    bool affectedByViewportChange() const;
-
-    // FIXME: Regions should not require special logic in StyleResolver.
-    bool checkRegionStyle(Element* regionElement);
+    bool mediaQueryAffectedByViewportChange() const;
 
     // FIXME: Rename to reflect the purpose, like didChangeFontSize or something.
     void invalidateMatchedPropertiesCache();
 
+    void notifyResizeForViewportUnits();
+
     // Exposed for RenderStyle::isStyleAvilable().
     static RenderStyle* styleNotYetAvailable() { return s_styleNotYetAvailable; }
 
-    // FIXME: StyleResolver should not have this member or method.
-    InspectorCSSOMWrappers& inspectorCSSOMWrappers() { return m_inspectorCSSOMWrappers; }
-
-    const RuleFeatureSet& ensureRuleFeatureSet()
+    RuleFeatureSet& ensureRuleFeatureSet()
     {
         if (hasPendingAuthorStyleSheets())
             appendPendingAuthorStyleSheets();
@@ -228,9 +220,11 @@
     unsigned accessCount() const { return m_accessCount; }
     void didAccess() { ++m_accessCount; }
 
+    PassRefPtr<PseudoElement> createPseudoElementIfNeeded(Element& parent, PseudoId);
+
 private:
-    // FontSelectorClient implementation.
-    virtual void fontsNeedUpdate(FontSelector*);
+    // CSSFontSelectorClient implementation.
+    virtual void fontsNeedUpdate(CSSFontSelector*) OVERRIDE;
 
 private:
     void initWatchedSelectorRules(const Vector<RefPtr<StyleRule> >& watchedSelectors);
@@ -260,7 +254,6 @@
     void applyAnimatedProperties(StyleResolverState&, Element* animatingElement);
 
     enum StyleApplicationPass {
-        VariableDefinitions,
         AnimationProperties,
         HighPriorityProperties,
         LowPriorityProperties
@@ -283,6 +276,8 @@
     bool isFirstPage(int pageIndex) const;
     String pageName(int pageIndex) const;
 
+    bool pseudoStyleForElementInternal(Element&, const PseudoStyleRequest&, RenderStyle* parentStyle, StyleResolverState&);
+
     // FIXME: This likely belongs on RuleSet.
     typedef HashMap<StringImpl*, RefPtr<StyleRuleKeyframes> > KeyframesRuleMap;
     KeyframesRuleMap m_keyframesRuleMap;
@@ -307,7 +302,7 @@
 
     ScopedStyleTree m_styleTree;
 
-    // FIXME: The entire logic of collecting features on StyleResolver, as well astransferring them
+    // FIXME: The entire logic of collecting features on StyleResolver, as well as transferring them
     // between various parts of machinery smells wrong. This needs to be better somehow.
     RuleFeatureSet m_features;
     OwnPtr<RuleSet> m_siblingRuleSet;
@@ -319,8 +314,6 @@
 
     bool m_needCollectFeatures;
 
-    InspectorCSSOMWrappers m_inspectorCSSOMWrappers;
-
     StyleResourceLoader m_styleResourceLoader;
 
     StyleSharingList m_styleSharingList;
@@ -329,23 +322,10 @@
     OwnPtr<StyleResolverStats> m_styleResolverStatsTotals;
     unsigned m_styleResolverStatsSequence;
 
+    // Use only for Internals::updateStyleAndReturnAffectedElementCount.
     unsigned m_accessCount;
 };
 
-inline bool checkRegionSelector(const CSSSelector* regionSelector, Element* regionElement)
-{
-    if (!regionSelector || !regionElement)
-        return false;
-
-    SelectorChecker selectorChecker(regionElement->document(), SelectorChecker::QueryingRules);
-    for (const CSSSelector* s = regionSelector; s; s = CSSSelectorList::next(s)) {
-        SelectorChecker::SelectorCheckingContext selectorCheckingContext(s, regionElement, SelectorChecker::VisitedMatchDisabled);
-        if (selectorChecker.match(selectorCheckingContext, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches)
-            return true;
-    }
-    return false;
-}
-
 } // namespace WebCore
 
 #endif // StyleResolver_h
diff --git a/Source/core/css/resolver/StyleResolverIncludes.h b/Source/core/css/resolver/StyleResolverIncludes.h
deleted file mode 100644
index 380c1eb..0000000
--- a/Source/core/css/resolver/StyleResolverIncludes.h
+++ /dev/null
@@ -1,13 +0,0 @@
-#ifndef StyleResolverIncludes_h
-#define StyleResolverIncludes_h
-
-namespace WebCore {
-
-enum ShouldIncludeStyleSheetInCSSOMWrapper {
-    IncludeStyleSheetInCSSOMWrapper,
-    DoNotIncludeStyleSheetInCSSOMWrapper,
-};
-
-}
-
-#endif // StyleResolverIncludes_h
diff --git a/Source/core/css/resolver/StyleResolverState.cpp b/Source/core/css/resolver/StyleResolverState.cpp
index 6df8002..3e59ff1 100644
--- a/Source/core/css/resolver/StyleResolverState.cpp
+++ b/Source/core/css/resolver/StyleResolverState.cpp
@@ -22,19 +22,19 @@
 #include "config.h"
 #include "core/css/resolver/StyleResolverState.h"
 
+#include "core/animation/css/CSSAnimations.h"
 #include "core/dom/Node.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/page/Page.h"
+#include "core/frame/FrameHost.h"
 
 namespace WebCore {
 
-StyleResolverState::StyleResolverState(Document& document, Element* element, RenderStyle* parentStyle, RenderRegion* regionForStyling)
+StyleResolverState::StyleResolverState(Document& document, Element* element, RenderStyle* parentStyle)
     : m_elementContext(element ? ElementResolveContext(*element) : ElementResolveContext())
     , m_document(document)
     , m_style(0)
-    , m_cssToLengthConversionData(0, rootElementStyle())
+    , m_cssToLengthConversionData(0, rootElementStyle(), document.renderView())
     , m_parentStyle(parentStyle)
-    , m_regionForStyling(regionForStyling)
     , m_applyPropertyToRegularStyle(true)
     , m_applyPropertyToVisitedLinkStyle(false)
     , m_lineHeightValue(0)
@@ -46,9 +46,26 @@
     else if (!parentStyle && m_elementContext.parentNode())
         m_parentStyle = m_elementContext.parentNode()->renderStyle();
 
-    // FIXME: How can we not have a page here?
-    if (Page* page = document.page())
-        m_elementStyleResources.setDeviceScaleFactor(page->deviceScaleFactor());
+    // FIXME: Animation unitests will start animations on non-active documents!
+    // http://crbug.com/330095
+    // ASSERT(document.isActive());
+    if (!document.isActive())
+        return;
+    m_elementStyleResources.setDeviceScaleFactor(document.frameHost()->deviceScaleFactor());
+}
+
+StyleResolverState::~StyleResolverState()
+{
+}
+
+void StyleResolverState::setAnimationUpdate(PassOwnPtr<CSSAnimationUpdate> update)
+{
+    m_animationUpdate = update;
+}
+
+PassOwnPtr<CSSAnimationUpdate> StyleResolverState::takeAnimationUpdate()
+{
+    return m_animationUpdate.release();
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/StyleResolverState.h b/Source/core/css/resolver/StyleResolverState.h
index 18095bd..9c93a43 100644
--- a/Source/core/css/resolver/StyleResolverState.h
+++ b/Source/core/css/resolver/StyleResolverState.h
@@ -24,7 +24,6 @@
 
 #include "CSSPropertyNames.h"
 
-#include "core/animation/css/CSSAnimations.h"
 #include "core/css/CSSSVGDocumentValue.h"
 #include "core/css/CSSToLengthConversionData.h"
 #include "core/css/resolver/CSSToStyleMap.h"
@@ -38,14 +37,15 @@
 
 namespace WebCore {
 
+class CSSAnimationUpdate;
 class FontDescription;
-class RenderRegion;
 class StyleRule;
 
 class StyleResolverState {
 WTF_MAKE_NONCOPYABLE(StyleResolverState);
 public:
-    StyleResolverState(Document&, Element*, RenderStyle* parentStyle = 0, RenderRegion* regionForStyling = 0);
+    StyleResolverState(Document&, Element*, RenderStyle* parentStyle = 0);
+    ~StyleResolverState();
 
     // In FontFaceSet and CanvasRenderingContext2D, we don't have an element to grab the document from.
     // This is why we have to store the document separately.
@@ -66,16 +66,14 @@
 
     const CSSToLengthConversionData& cssToLengthConversionData() const { return m_cssToLengthConversionData; }
 
-    void setAnimationUpdate(PassOwnPtr<CSSAnimationUpdate> update) { m_animationUpdate = update; }
+    void setAnimationUpdate(PassOwnPtr<CSSAnimationUpdate>);
     const CSSAnimationUpdate* animationUpdate() { return m_animationUpdate.get(); }
-    PassOwnPtr<CSSAnimationUpdate> takeAnimationUpdate() { return m_animationUpdate.release(); }
+    PassOwnPtr<CSSAnimationUpdate> takeAnimationUpdate();
 
     void setParentStyle(PassRefPtr<RenderStyle> parentStyle) { m_parentStyle = parentStyle; }
     const RenderStyle* parentStyle() const { return m_parentStyle.get(); }
     RenderStyle* parentStyle() { return m_parentStyle.get(); }
 
-    const RenderRegion* regionForStyling() const { return m_regionForStyling; }
-
     void setCurrentRule(StyleRule* currentRule) { m_currentRule = currentRule; }
     const StyleRule* currentRule() const { return m_currentRule; }
 
@@ -149,11 +147,6 @@
 
     OwnPtr<CSSAnimationUpdate> m_animationUpdate;
 
-    // Required to ASSERT in applyProperties.
-    // FIXME: Regions should not need special state on StyleResolverState
-    // no other @rule does.
-    RenderRegion* m_regionForStyling;
-
     bool m_applyPropertyToRegularStyle;
     bool m_applyPropertyToVisitedLinkStyle;
 
diff --git a/Source/core/css/resolver/StyleResourceLoader.cpp b/Source/core/css/resolver/StyleResourceLoader.cpp
index 04405c3..0b20f73 100644
--- a/Source/core/css/resolver/StyleResourceLoader.cpp
+++ b/Source/core/css/resolver/StyleResourceLoader.cpp
@@ -27,29 +27,22 @@
 #include "core/css/CSSCursorImageValue.h"
 #include "core/css/CSSImageValue.h"
 #include "core/css/CSSSVGDocumentValue.h"
-#include "core/css/CSSShaderValue.h"
 #include "core/css/resolver/ElementStyleResources.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/rendering/style/ContentData.h"
 #include "core/rendering/style/CursorList.h"
 #include "core/rendering/style/FillLayer.h"
 #include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/StyleCustomFilterProgram.h"
-#include "core/rendering/style/StyleCustomFilterProgramCache.h"
 #include "core/rendering/style/StyleFetchedImage.h"
 #include "core/rendering/style/StyleFetchedImageSet.h"
-#include "core/rendering/style/StyleFetchedShader.h"
 #include "core/rendering/style/StyleGeneratedImage.h"
 #include "core/rendering/style/StylePendingImage.h"
-#include "core/rendering/style/StylePendingShader.h"
 #include "core/rendering/svg/ReferenceFilterBuilder.h"
-#include "platform/graphics/filters/custom/CustomFilterOperation.h"
 
 namespace WebCore {
 
 StyleResourceLoader::StyleResourceLoader(ResourceFetcher* fetcher)
-    : m_customFilterProgramCache(StyleCustomFilterProgramCache::create())
-    , m_fetcher(fetcher)
+    : m_fetcher(fetcher)
 {
 }
 
@@ -77,33 +70,33 @@
     }
 }
 
-PassRefPtr<StyleImage> StyleResourceLoader::loadPendingImage(StylePendingImage* pendingImage, float deviceScaleFactor)
+static PassRefPtr<StyleImage> doLoadPendingImage(ResourceFetcher* fetcher, StylePendingImage* pendingImage, float deviceScaleFactor, const ResourceLoaderOptions& options)
 {
-    if (pendingImage->cssImageValue()) {
-        CSSImageValue* imageValue = pendingImage->cssImageValue();
-        return imageValue->cachedImage(m_fetcher);
-    }
+    if (CSSImageValue* imageValue = pendingImage->cssImageValue())
+        return imageValue->cachedImage(fetcher, options);
 
-    if (pendingImage->cssImageGeneratorValue()) {
-        CSSImageGeneratorValue* imageGeneratorValue = pendingImage->cssImageGeneratorValue();
-        imageGeneratorValue->loadSubimages(m_fetcher);
+    if (CSSImageGeneratorValue* imageGeneratorValue
+        = pendingImage->cssImageGeneratorValue()) {
+        imageGeneratorValue->loadSubimages(fetcher);
         return StyleGeneratedImage::create(imageGeneratorValue);
     }
 
-    if (pendingImage->cssCursorImageValue()) {
-        CSSCursorImageValue* cursorImageValue = pendingImage->cssCursorImageValue();
-        return cursorImageValue->cachedImage(m_fetcher, deviceScaleFactor);
-    }
+    if (CSSCursorImageValue* cursorImageValue
+        = pendingImage->cssCursorImageValue())
+        return cursorImageValue->cachedImage(fetcher, deviceScaleFactor);
 
-    if (pendingImage->cssImageSetValue()) {
-        CSSImageSetValue* imageSetValue = pendingImage->cssImageSetValue();
-        return imageSetValue->cachedImageSet(m_fetcher, deviceScaleFactor);
-    }
+    if (CSSImageSetValue* imageSetValue = pendingImage->cssImageSetValue())
+        return imageSetValue->cachedImageSet(fetcher, deviceScaleFactor, options);
 
     return 0;
 }
 
-void StyleResourceLoader::loadPendingShapeImage(RenderStyle* renderStyle, ShapeValue* shapeValue)
+PassRefPtr<StyleImage> StyleResourceLoader::loadPendingImage(StylePendingImage* pendingImage, float deviceScaleFactor)
+{
+    return doLoadPendingImage(m_fetcher, pendingImage, deviceScaleFactor, ResourceFetcher::defaultResourceOptions());
+}
+
+void StyleResourceLoader::loadPendingShapeImage(RenderStyle* renderStyle, ShapeValue* shapeValue, float deviceScaleFactor)
 {
     if (!shapeValue)
         return;
@@ -112,13 +105,11 @@
     if (!image || !image->isPendingImage())
         return;
 
-    StylePendingImage* pendingImage = toStylePendingImage(image);
-    CSSImageValue* cssImageValue =  pendingImage->cssImageValue();
-
     ResourceLoaderOptions options = ResourceFetcher::defaultResourceOptions();
     options.allowCredentials = DoNotAllowStoredCredentials;
+    options.corsEnabled = IsCORSEnabled;
 
-    shapeValue->setImage(cssImageValue->cachedImage(m_fetcher, options, PotentiallyCORSEnabled));
+    shapeValue->setImage(doLoadPendingImage(m_fetcher, toStylePendingImage(image), deviceScaleFactor, options));
 }
 
 void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementStyleResources& elementStyleResources)
@@ -196,10 +187,10 @@
             break;
         }
         case CSSPropertyShapeInside:
-            loadPendingShapeImage(style, style->shapeInside());
+            loadPendingShapeImage(style, style->shapeInside(), elementStyleResources.deviceScaleFactor());
             break;
         case CSSPropertyShapeOutside:
-            loadPendingShapeImage(style, style->shapeOutside());
+            loadPendingShapeImage(style, style->shapeOutside(), elementStyleResources.deviceScaleFactor());
             break;
         default:
             ASSERT_NOT_REACHED();
@@ -207,49 +198,11 @@
     }
 }
 
-void StyleResourceLoader::loadPendingShaders(RenderStyle* style, const ElementStyleResources& elementStyleResources)
-{
-    if (!style->hasFilter() || !elementStyleResources.hasNewCustomFilterProgram())
-        return;
-
-    Vector<RefPtr<FilterOperation> >& filterOperations = style->mutableFilter().operations();
-    for (unsigned i = 0; i < filterOperations.size(); ++i) {
-        RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
-        if (filterOperation->type() == FilterOperation::CUSTOM) {
-            CustomFilterOperation* customFilter = toCustomFilterOperation(filterOperation.get());
-            ASSERT(customFilter->program());
-            StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customFilter->program());
-            // Note that the StylePendingShaders could be already resolved to StyleFetchedShaders. That's because the rule was matched before.
-            // However, the StyleCustomFilterProgram that was initially created could have been removed from the cache in the meanwhile,
-            // meaning that we get a new StyleCustomFilterProgram here that is not yet in the cache, but already has loaded StyleShaders.
-            if (!program->hasPendingShaders() && program->inCache())
-                continue;
-            RefPtr<StyleCustomFilterProgram> styleProgram = m_customFilterProgramCache->lookup(program);
-            if (styleProgram.get()) {
-                customFilter->setProgram(styleProgram.release());
-            } else {
-                if (program->vertexShader() && program->vertexShader()->isPendingShader()) {
-                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->vertexShader())->cssShaderValue();
-                    program->setVertexShader(shaderValue->resource(m_fetcher));
-                }
-                if (program->fragmentShader() && program->fragmentShader()->isPendingShader()) {
-                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->fragmentShader())->cssShaderValue();
-                    program->setFragmentShader(shaderValue->resource(m_fetcher));
-                }
-                m_customFilterProgramCache->add(program);
-            }
-        }
-    }
-}
-
 void StyleResourceLoader::loadPendingResources(RenderStyle* renderStyle, ElementStyleResources& elementStyleResources)
 {
     // Start loading images referenced by this style.
     loadPendingImages(renderStyle, elementStyleResources);
 
-    // Start loading the shaders referenced by this style.
-    loadPendingShaders(renderStyle, elementStyleResources);
-
     // Start loading the SVG Documents referenced by this style.
     loadPendingSVGDocuments(renderStyle, elementStyleResources);
 }
diff --git a/Source/core/css/resolver/StyleResourceLoader.h b/Source/core/css/resolver/StyleResourceLoader.h
index 4b33efe..0715a6b 100644
--- a/Source/core/css/resolver/StyleResourceLoader.h
+++ b/Source/core/css/resolver/StyleResourceLoader.h
@@ -29,34 +29,29 @@
 namespace WebCore {
 
 class ElementStyleResources;
-class ResourceFetcher;
 class RenderStyle;
+class ResourceFetcher;
 class ShapeValue;
 class StyleImage;
 class StylePendingImage;
-class StyleCustomFilterProgramCache;
 
 // Manages loading of resources, requested by the stylesheets.
-// Expects the same lifetime as StyleResolver, because:
-// 1) it expects ResourceFetcher to never change, and
-// 2) it also holds the StyleCustomFilterProgramCache.
+// Expects the same lifetime as StyleResolver, because
+// it expects ResourceFetcher to never change.
 class StyleResourceLoader {
 WTF_MAKE_NONCOPYABLE(StyleResourceLoader);
 public:
     explicit StyleResourceLoader(ResourceFetcher*);
 
     void loadPendingResources(RenderStyle*, ElementStyleResources&);
-    StyleCustomFilterProgramCache* customFilterProgramCache() const { return m_customFilterProgramCache.get(); }
 
 private:
     void loadPendingSVGDocuments(RenderStyle*, const ElementStyleResources&);
-    void loadPendingShaders(RenderStyle*, const ElementStyleResources&);
 
     PassRefPtr<StyleImage> loadPendingImage(StylePendingImage*, float deviceScaleFactor);
     void loadPendingImages(RenderStyle*, const ElementStyleResources&);
-    void loadPendingShapeImage(RenderStyle*, ShapeValue*);
+    void loadPendingShapeImage(RenderStyle*, ShapeValue*, float deviceScaleFactor);
 
-    OwnPtr<StyleCustomFilterProgramCache> m_customFilterProgramCache;
     ResourceFetcher* m_fetcher;
 };
 
diff --git a/Source/core/css/resolver/TransformBuilder.cpp b/Source/core/css/resolver/TransformBuilder.cpp
index 3779a01..bd8de37 100644
--- a/Source/core/css/resolver/TransformBuilder.cpp
+++ b/Source/core/css/resolver/TransformBuilder.cpp
@@ -53,7 +53,8 @@
 
 static Length convertToFloatLength(CSSPrimitiveValue* primitiveValue, const CSSToLengthConversionData& conversionData)
 {
-    return primitiveValue ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(conversionData) : Length(Undefined);
+    ASSERT(primitiveValue);
+    return primitiveValue->convertToLength<FixedConversion | PercentConversion>(conversionData);
 }
 
 static TransformOperation::OperationType getTransformOperationType(CSSTransformValue::TransformOperationType type)
@@ -180,19 +181,16 @@
                 }
             }
 
-            if (tx.isUndefined() || ty.isUndefined())
-                return false;
-
-            operations.operations().append(TranslateTransformOperation::create(tx, ty, Length(0, Fixed), getTransformOperationType(transformValue->operationType())));
+            operations.operations().append(TranslateTransformOperation::create(tx, ty, 0, getTransformOperationType(transformValue->operationType())));
             break;
         }
         case CSSTransformValue::TranslateZTransformOperation:
         case CSSTransformValue::Translate3DTransformOperation: {
             Length tx = Length(0, Fixed);
             Length ty = Length(0, Fixed);
-            Length tz = Length(0, Fixed);
+            double tz = 0;
             if (transformValue->operationType() == CSSTransformValue::TranslateZTransformOperation)
-                tz = convertToFloatLength(firstValue, conversionData);
+                tz = firstValue->computeLength<double>(conversionData);
             else if (transformValue->operationType() == CSSTransformValue::TranslateYTransformOperation)
                 ty = convertToFloatLength(firstValue, conversionData);
             else {
@@ -200,7 +198,7 @@
                 if (transformValue->operationType() != CSSTransformValue::TranslateXTransformOperation) {
                     if (transformValue->length() > 2) {
                         CSSPrimitiveValue* thirdValue = toCSSPrimitiveValue(transformValue->itemWithoutBoundsCheck(2));
-                        tz = convertToFloatLength(thirdValue, conversionData);
+                        tz = thirdValue->computeLength<double>(conversionData);
                     }
                     if (transformValue->length() > 1) {
                         CSSPrimitiveValue* secondValue = toCSSPrimitiveValue(transformValue->itemWithoutBoundsCheck(1));
@@ -209,9 +207,6 @@
                 }
             }
 
-            if (tx.isUndefined() || ty.isUndefined() || tz.isUndefined())
-                return false;
-
             operations.operations().append(TranslateTransformOperation::create(tx, ty, tz, getTransformOperationType(transformValue->operationType())));
             break;
         }
@@ -305,18 +300,17 @@
             break;
         }
         case CSSTransformValue::PerspectiveTransformOperation: {
-            Length p = Length(0, Fixed);
+            double p;
             if (firstValue->isLength())
-                p = convertToFloatLength(firstValue, conversionData);
+                p = firstValue->computeLength<double>(conversionData);
             else {
                 // This is a quirk that should go away when 3d transforms are finalized.
                 double val = firstValue->getDoubleValue();
-                p = val >= 0 ? Length(clampToPositiveInteger(val), Fixed) : Length(Undefined);
+                if (val < 0)
+                    return false;
+                p = clampToPositiveInteger(val);
             }
 
-            if (p.isUndefined())
-                return false;
-
             operations.operations().append(PerspectiveTransformOperation::create(p));
             break;
         }
diff --git a/Source/core/css/resolver/ViewportStyleResolver.cpp b/Source/core/css/resolver/ViewportStyleResolver.cpp
index 61894a2..f10190a 100644
--- a/Source/core/css/resolver/ViewportStyleResolver.cpp
+++ b/Source/core/css/resolver/ViewportStyleResolver.cpp
@@ -31,12 +31,14 @@
 #include "core/css/resolver/ViewportStyleResolver.h"
 
 #include "CSSValueKeywords.h"
+#include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/CSSToLengthConversionData.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
 #include "core/dom/Document.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/ViewportDescription.h"
+#include "core/frame/FrameView.h"
 
 namespace WebCore {
 
@@ -183,25 +185,25 @@
 
     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
 
-    if (primitiveValue->isLength())
-        return primitiveValue->computeLength<Length>(CSSToLengthConversionData(m_document->renderStyle(), m_document->renderStyle(), 1.0f));
-
-    if (primitiveValue->isViewportPercentageLength())
-        return primitiveValue->viewportPercentageLength();
-
-    if (primitiveValue->isPercentage())
-        return Length(primitiveValue->getFloatValue(), Percent);
-
-    switch (primitiveValue->getValueID()) {
-    case CSSValueInternalExtendToZoom:
+    if (primitiveValue->getValueID() == CSSValueInternalExtendToZoom)
         return Length(ExtendToZoom);
-    case CSSValueAuto:
-        return Length();
-    default:
-        // Unrecognized keyword.
-        ASSERT_NOT_REACHED();
-        return Length(0, Fixed);
-    }
+
+    RenderStyle* documentStyle = m_document->renderStyle();
+
+    // If we have viewport units the conversion will mark the document style as having viewport units.
+    bool documentStyleHasViewportUnits = documentStyle->hasViewportUnits();
+    documentStyle->setHasViewportUnits(false);
+
+    FrameView* view = m_document->view();
+    float width = view ? view->width() : 0;
+    float height = view ? view->height() : 0;
+
+    Length result = primitiveValue->convertToLength<AnyConversion>(CSSToLengthConversionData(documentStyle, documentStyle, width, height, 1.0f));
+    if (documentStyle->hasViewportUnits())
+        m_document->setHasViewportUnits();
+    documentStyle->setHasViewportUnits(documentStyleHasViewportUnits);
+
+    return result;
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/themeChromiumAndroid.css b/Source/core/css/themeChromiumAndroid.css
index be5488f..3ff3183 100644
--- a/Source/core/css/themeChromiumAndroid.css
+++ b/Source/core/css/themeChromiumAndroid.css
@@ -35,7 +35,22 @@
 select[size][multiple] {
     -webkit-appearance: menulist;
     align-items: center;
-    border: 1px solid;
+    background-color: ButtonFace;
+    border: 1px solid #a9a9a9;
     border-radius: initial;
     white-space: pre;
 }
+
+input[type="date"]:disabled,
+input[type="datetime-local"]:disabled,
+input[type="month"]:disabled,
+input[type="time"]:disabled,
+input[type="week"]:disabled,
+input[type="date"]:read-only,
+input[type="datetime-local"]:read-only,
+input[type="month"]:read-only,
+input[type="time"]:read-only,
+input[type="week"]:read-only {
+    background-color: ButtonFace;
+    color: GrayText;
+}
\ No newline at end of file
diff --git a/Source/core/css/themeChromiumLinux.css b/Source/core/css/themeChromiumLinux.css
index f41a476..7d15d64 100644
--- a/Source/core/css/themeChromiumLinux.css
+++ b/Source/core/css/themeChromiumLinux.css
@@ -37,10 +37,6 @@
     background-color: ButtonFace;
 }
 
-select:disabled option:checked, option:disabled:checked {
-    color: GrayText;
-}
-
 input[type=range] {
     color: #9d968E;
 }
diff --git a/Source/core/css/themeWin.css b/Source/core/css/themeWin.css
index b7a6f0b..3c727d3 100644
--- a/Source/core/css/themeWin.css
+++ b/Source/core/css/themeWin.css
@@ -111,6 +111,15 @@
 select[size="0"],
 select[size="1"] {
     border-radius: 0;
+    /* Same as native_theme_base. */
+    border-color: #a9a9a9;
+}
+
+select[size],
+select[multiple],
+select[size][multiple] {
+    /* Same as native_theme_base. */
+    border: 1px solid #a9a9a9;
 }
 
 /* Option font must be inherited because we depend on computing the size of the
@@ -120,10 +129,8 @@
     font: inherit !important;
 }
 
-select:disabled option:checked, option:disabled:checked {
-    color: #d2d2d2
-}
-
 textarea {
-  font-family: monospace;
+    font-family: monospace;
+    /* Same as native_theme_base. */
+    border-color: #a9a9a9;
 }
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index b67b281..93c3c94 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -23,14 +23,11 @@
 #include "config.h"
 #include "core/dom/Attr.h"
 
-#include "XMLNSNames.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Element.h"
-#include "core/dom/ExceptionCode.h"
 #include "core/dom/Text.h"
 #include "core/events/ScopedEventQueue.h"
-#include "core/frame/UseCounter.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -90,31 +87,6 @@
     }
 }
 
-void Attr::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
-{
-    UseCounter::count(document(), UseCounter::AttributeSetPrefix);
-
-    checkSetPrefix(prefix, exceptionState);
-    if (exceptionState.hadException())
-        return;
-
-    if (prefix == xmlnsAtom && namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
-        exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlnsAtom + "' may not be used on the namespace '" + namespaceURI() + "'.");
-        return;
-    }
-
-    if (this->qualifiedName() == xmlnsAtom) {
-        exceptionState.throwDOMException(NamespaceError, "The prefix '" + prefix + "' may not be used as a namespace prefix for attributes whose qualified name is '" + xmlnsAtom + "'.");
-        return;
-    }
-
-    const AtomicString& newPrefix = prefix.isEmpty() ? nullAtom : prefix;
-
-    if (m_element)
-        elementAttribute().setPrefix(newPrefix);
-    m_name.setPrefix(newPrefix);
-}
-
 void Attr::setValue(const AtomicString& value)
 {
     EventQueueScope scope;
@@ -143,7 +115,9 @@
 
 void Attr::setNodeValue(const String& v)
 {
-    setValue(v, IGNORE_EXCEPTION);
+    // Attr uses AtomicString type for its value to save memory as there
+    // is duplication among Elements' attributes values.
+    setValue(AtomicString(v), IGNORE_EXCEPTION);
 }
 
 PassRefPtr<Node> Attr::cloneNode(bool /*deep*/)
@@ -185,11 +159,6 @@
         m_element->attributeChanged(qualifiedName(), newValue);
 }
 
-bool Attr::isId() const
-{
-    return qualifiedName().matches(document().idAttributeName());
-}
-
 const AtomicString& Attr::value() const
 {
     if (m_element)
diff --git a/Source/core/dom/Attr.h b/Source/core/dom/Attr.h
index 40d812b..579a5d8 100644
--- a/Source/core/dom/Attr.h
+++ b/Source/core/dom/Attr.h
@@ -30,9 +30,7 @@
 
 namespace WebCore {
 
-class CSSStyleDeclaration;
 class ExceptionState;
-class MutableStylePropertySet;
 
 // Attr can have Text children
 // therefore it has to be a fullblown Node. The plan
@@ -56,16 +54,12 @@
 
     const QualifiedName& qualifiedName() const { return m_name; }
 
-    bool isId() const;
-
     void attachToElement(Element*);
     void detachFromElementWithValue(const AtomicString&);
 
     virtual const AtomicString& localName() const OVERRIDE { return m_name.localName(); }
     virtual const AtomicString& namespaceURI() const OVERRIDE { return m_name.namespaceURI(); }
-    virtual const AtomicString& prefix() const OVERRIDE { return m_name.prefix(); }
-
-    virtual void setPrefix(const AtomicString&, ExceptionState&) OVERRIDE;
+    const AtomicString& prefix() const { return m_name.prefix(); }
 
 private:
     Attr(Element&, const QualifiedName&);
@@ -77,13 +71,13 @@
     virtual NodeType nodeType() const OVERRIDE { return ATTRIBUTE_NODE; }
 
     virtual String nodeValue() const OVERRIDE { return value(); }
-    virtual void setNodeValue(const String&);
-    virtual PassRefPtr<Node> cloneNode(bool deep = true);
+    virtual void setNodeValue(const String&) OVERRIDE;
+    virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE;
 
-    virtual bool isAttributeNode() const { return true; }
-    virtual bool childTypeAllowed(NodeType) const;
+    virtual bool isAttributeNode() const OVERRIDE { return true; }
+    virtual bool childTypeAllowed(NodeType) const OVERRIDE;
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
     Attribute& elementAttribute();
 
diff --git a/Source/core/dom/Attr.idl b/Source/core/dom/Attr.idl
index 00d9205..2403170 100644
--- a/Source/core/dom/Attr.idl
+++ b/Source/core/dom/Attr.idl
@@ -24,21 +24,13 @@
 
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString name;
 
-    [MeasureAs=AttributeSpecified] readonly attribute boolean specified;
+    [DeprecateAs=AttributeSpecified] readonly attribute boolean specified;
 
     [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter, CustomElementCallbacks] attribute DOMString value;
 
-    // DOM Level 2
-
-    [MeasureAs=AttributeOwnerElement] readonly attribute Element ownerElement;
-
-    // DOM Level 3
-
-    [MeasureAs=AttributeIsId] readonly attribute boolean isId;
-
     // DOM 4
 
-    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter] attribute DOMString prefix;
+    [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString prefix;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString namespaceURI;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString localName;
 };
diff --git a/Source/core/dom/CDATASection.cpp b/Source/core/dom/CDATASection.cpp
index ec61f09..430d64d 100644
--- a/Source/core/dom/CDATASection.cpp
+++ b/Source/core/dom/CDATASection.cpp
@@ -47,11 +47,6 @@
     return CDATA_SECTION_NODE;
 }
 
-bool CDATASection::childTypeAllowed(NodeType) const
-{
-    return false;
-}
-
 PassRefPtr<Text> CDATASection::cloneWithData(const String& data)
 {
     return create(document(), data);
diff --git a/Source/core/dom/CDATASection.h b/Source/core/dom/CDATASection.h
index 338866f..e4c3d02 100644
--- a/Source/core/dom/CDATASection.h
+++ b/Source/core/dom/CDATASection.h
@@ -34,9 +34,8 @@
 private:
     CDATASection(Document&, const String&);
 
-    virtual String nodeName() const;
-    virtual NodeType nodeType() const;
-    virtual bool childTypeAllowed(NodeType) const;
+    virtual String nodeName() const OVERRIDE;
+    virtual NodeType nodeType() const OVERRIDE;
     virtual PassRefPtr<Text> cloneWithData(const String&) OVERRIDE;
 };
 
diff --git a/Source/core/dom/CSSSelectorWatch.cpp b/Source/core/dom/CSSSelectorWatch.cpp
index 074d6b2..b6ac2e3 100644
--- a/Source/core/dom/CSSSelectorWatch.cpp
+++ b/Source/core/dom/CSSSelectorWatch.cpp
@@ -31,7 +31,7 @@
 #include "config.h"
 #include "core/dom/CSSSelectorWatch.h"
 
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSSelectorList.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/Document.h"
@@ -131,7 +131,7 @@
 
 static bool allCompound(const CSSSelectorList& selectorList)
 {
-    for (const CSSSelector* selector = selectorList.first(); selector; selector = selectorList.next(selector)) {
+    for (const CSSSelector* selector = selectorList.first(); selector; selector = selectorList.next(*selector)) {
         if (!selector->isCompound())
             return false;
     }
@@ -141,8 +141,7 @@
 void CSSSelectorWatch::watchCSSSelectors(const Vector<String>& selectors)
 {
     m_watchedCallbackSelectors.clear();
-    CSSParserContext context(UASheetMode);
-    CSSParser parser(context);
+    BisonCSSParser parser(CSSParserContext(UASheetMode, 0));
 
     const CSSProperty callbackProperty(CSSPropertyInternalCallback, CSSPrimitiveValue::createIdentifier(CSSValueInternalPresence));
     const RefPtr<StylePropertySet> callbackPropertySet = ImmutableStylePropertySet::create(&callbackProperty, 1, UASheetMode);
diff --git a/Source/core/dom/CharacterData.cpp b/Source/core/dom/CharacterData.cpp
index d0344f2..2eecf98 100644
--- a/Source/core/dom/CharacterData.cpp
+++ b/Source/core/dom/CharacterData.cpp
@@ -70,7 +70,7 @@
 void CharacterData::parserAppendData(const String& string)
 {
     unsigned oldLength = m_data.length();
-    m_data.append(string);
+    m_data = m_data + string;
 
     ASSERT(!renderer() || isTextNode());
     if (isTextNode())
diff --git a/Source/core/dom/CharacterData.h b/Source/core/dom/CharacterData.h
index 1163622..a89eccd 100644
--- a/Source/core/dom/CharacterData.h
+++ b/Source/core/dom/CharacterData.h
@@ -33,7 +33,7 @@
 class CharacterData : public Node {
 public:
     void atomize();
-    String data() const { return m_data; }
+    const String& data() const { return m_data; }
     void setData(const String&);
     unsigned length() const { return m_data.length(); }
     String substringData(unsigned offset, unsigned count, ExceptionState&);
diff --git a/Source/core/dom/ChildListMutationScope.cpp b/Source/core/dom/ChildListMutationScope.cpp
index 1d00364..699b554 100644
--- a/Source/core/dom/ChildListMutationScope.cpp
+++ b/Source/core/dom/ChildListMutationScope.cpp
@@ -65,10 +65,10 @@
     AccumulatorMap::AddResult result = accumulatorMap().add(&target, 0);
     RefPtr<ChildListMutationAccumulator> accumulator;
     if (!result.isNewEntry)
-        accumulator = result.iterator->value;
+        accumulator = result.storedValue->value;
     else {
         accumulator = adoptRef(new ChildListMutationAccumulator(PassRefPtr<Node>(target), MutationObserverInterestGroup::createForChildListMutation(target)));
-        result.iterator->value = accumulator.get();
+        result.storedValue->value = accumulator.get();
     }
     return accumulator.release();
 }
diff --git a/Source/core/dom/ChildNode.h b/Source/core/dom/ChildNode.h
new file mode 100644
index 0000000..79aa891
--- /dev/null
+++ b/Source/core/dom/ChildNode.h
@@ -0,0 +1,36 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef ChildNode_h
+#define ChildNode_h
+
+#include "core/dom/ElementTraversal.h"
+#include "core/dom/Node.h"
+
+namespace WebCore {
+
+class ChildNode {
+public:
+    static Element* previousElementSibling(Node* node)
+    {
+        ASSERT(node);
+        return ElementTraversal::previousSibling(*node);
+    }
+
+    static Element* nextElementSibling(Node* node)
+    {
+        ASSERT(node);
+        return ElementTraversal::nextSibling(*node);
+    }
+
+    static void remove(Node* node, ExceptionState& exceptionState)
+    {
+        ASSERT(node);
+        return node->remove(exceptionState);
+    }
+};
+
+} // namespace WebCore
+
+#endif // ChildNode_h
diff --git a/Source/core/dom/ChildNode.idl b/Source/core/dom/ChildNode.idl
index 21441f6..f4a8ba8 100644
--- a/Source/core/dom/ChildNode.idl
+++ b/Source/core/dom/ChildNode.idl
@@ -21,8 +21,7 @@
  */
 
 [
-    NoInterfaceObject,
-    LegacyImplementedInBaseClass
+    NoInterfaceObject
 ] interface ChildNode {
     [PerWorldBindings] readonly attribute Element previousElementSibling;
     [PerWorldBindings] readonly attribute Element nextElementSibling;
diff --git a/Source/core/dom/ChildNodeList.cpp b/Source/core/dom/ChildNodeList.cpp
index 4144c04..ee585c4 100644
--- a/Source/core/dom/ChildNodeList.cpp
+++ b/Source/core/dom/ChildNodeList.cpp
@@ -1,8 +1,9 @@
-/**
+/*
  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
  *           (C) 2001 Dirk Mueller (mueller@kde.org)
  * Copyright (C) 2004, 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -28,21 +29,36 @@
 
 namespace WebCore {
 
-ChildNodeList::ChildNodeList(PassRefPtr<Node> node)
-    : LiveNodeList(node, ChildNodeListType, DoNotInvalidateOnAttributeChanges)
+ChildNodeList::ChildNodeList(PassRefPtr<ContainerNode> parent)
+    : m_parent(parent)
 {
+    ASSERT(m_parent);
+}
+
+Node* ChildNodeList::virtualOwnerNode() const
+{
+    return ownerNode();
 }
 
 ChildNodeList::~ChildNodeList()
 {
-    ownerNode()->nodeLists()->removeChildNodeList(this);
+    m_parent->nodeLists()->removeChildNodeList(this);
 }
 
-bool ChildNodeList::nodeMatches(Element* testNode) const
+Node* ChildNodeList::itemBefore(const Node* previous) const
 {
-    // This function will be called only by LiveNodeList::namedItem,
-    // for an element that was located with getElementById.
-    return testNode->parentNode() == rootNode();
+    return LIKELY(!!previous) ? previous->previousSibling() : rootNode().lastChild();
+}
+
+Node* ChildNodeList::traverseForwardToOffset(unsigned offset, Node& currentNode, unsigned& currentOffset, const ContainerNode&) const
+{
+    ASSERT(currentOffset < offset);
+    Node* next = &currentNode;
+    while ((next = next->nextSibling())) {
+        if (++currentOffset == offset)
+            return next;
+    }
+    return 0;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/ChildNodeList.h b/Source/core/dom/ChildNodeList.h
index 46f5bea..0fe38cc 100644
--- a/Source/core/dom/ChildNodeList.h
+++ b/Source/core/dom/ChildNodeList.h
@@ -3,6 +3,7 @@
  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
  *           (C) 2001 Dirk Mueller (mueller@kde.org)
  * Copyright (C) 2004, 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -24,26 +25,48 @@
 #ifndef ChildNodeList_h
 #define ChildNodeList_h
 
-#include "core/dom/LiveNodeList.h"
+#include "core/dom/NodeList.h"
+#include "core/html/CollectionIndexCache.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
-class ChildNodeList FINAL : public LiveNodeList {
+class ChildNodeList FINAL : public NodeList {
 public:
-    static PassRefPtr<ChildNodeList> create(PassRefPtr<Node> rootNode)
+    static PassRefPtr<ChildNodeList> create(PassRefPtr<ContainerNode> rootNode)
     {
         return adoptRef(new ChildNodeList(rootNode));
     }
 
     virtual ~ChildNodeList();
 
-protected:
-    explicit ChildNodeList(PassRefPtr<Node> rootNode);
+    // DOM API.
+    virtual unsigned length() const OVERRIDE { return m_collectionIndexCache.nodeCount(*this); }
+    virtual Node* item(unsigned index) const OVERRIDE { return m_collectionIndexCache.nodeAt(*this, index); }
 
-    virtual bool nodeMatches(Element*) const OVERRIDE;
+    // Non-DOM API.
+    void invalidateCache() { m_collectionIndexCache.invalidate(); }
+    ContainerNode* ownerNode() const { return m_parent.get(); }
+
+    // CollectionIndexCache API.
+    ContainerNode& rootNode() const { return *m_parent; }
+    bool canTraverseBackward() const { return true; }
+    Node* itemBefore(const Node* previousItem) const;
+    Node* traverseToFirstElement(const ContainerNode& root) const { return root.firstChild(); }
+    Node* traverseForwardToOffset(unsigned offset, Node& currentNode, unsigned& currentOffset, const ContainerNode& root) const;
+
+private:
+    explicit ChildNodeList(PassRefPtr<ContainerNode> rootNode);
+
+    virtual bool isChildNodeList() const OVERRIDE { return true; }
+    virtual Node* virtualOwnerNode() const OVERRIDE;
+
+    RefPtr<ContainerNode> m_parent;
+    mutable CollectionIndexCache<ChildNodeList, Node> m_collectionIndexCache;
 };
 
+DEFINE_TYPE_CASTS(ChildNodeList, NodeList, nodeList, nodeList->isChildNodeList(), nodeList.isChildNodeList());
+
 } // namespace WebCore
 
 #endif // ChildNodeList_h
diff --git a/Source/core/dom/ClassNodeList.cpp b/Source/core/dom/ClassCollection.cpp
similarity index 81%
rename from Source/core/dom/ClassNodeList.cpp
rename to Source/core/dom/ClassCollection.cpp
index 8b36218..59099c0 100644
--- a/Source/core/dom/ClassNodeList.cpp
+++ b/Source/core/dom/ClassCollection.cpp
@@ -28,28 +28,23 @@
  */
 
 #include "config.h"
-#include "core/dom/ClassNodeList.h"
+#include "core/dom/ClassCollection.h"
 
 #include "core/dom/Document.h"
 #include "core/dom/NodeRareData.h"
 
 namespace WebCore {
 
-ClassNodeList::ClassNodeList(PassRefPtr<Node> rootNode, const String& classNames)
-    : LiveNodeList(rootNode, ClassNodeListType, InvalidateOnClassAttrChange)
+ClassCollection::ClassCollection(ContainerNode* rootNode, const AtomicString& classNames)
+    : HTMLCollection(rootNode, ClassCollectionType, DoesNotOverrideItemAfter)
     , m_classNames(classNames, document().inQuirksMode())
     , m_originalClassNames(classNames)
 {
 }
 
-ClassNodeList::~ClassNodeList()
+ClassCollection::~ClassCollection()
 {
-    ownerNode()->nodeLists()->removeCacheWithName(this, ClassNodeListType, m_originalClassNames);
-}
-
-bool ClassNodeList::nodeMatches(Element* testNode) const
-{
-    return nodeMatchesInlined(testNode);
+    ownerNode()->nodeLists()->removeCache(this, ClassCollectionType, m_originalClassNames);
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/ClassNodeList.h b/Source/core/dom/ClassCollection.h
similarity index 65%
rename from Source/core/dom/ClassNodeList.h
rename to Source/core/dom/ClassCollection.h
index 2e08ea8..a906537 100644
--- a/Source/core/dom/ClassNodeList.h
+++ b/Source/core/dom/ClassCollection.h
@@ -27,49 +27,49 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ClassNodeList_h
-#define ClassNodeList_h
+#ifndef ClassCollection_h
+#define ClassCollection_h
 
 #include "core/dom/Element.h"
-#include "core/dom/LiveNodeList.h"
-#include "core/dom/Node.h"
 #include "core/dom/SpaceSplitString.h"
+#include "core/html/HTMLCollection.h"
 
 namespace WebCore {
 
-class ClassNodeList FINAL : public LiveNodeList {
+class ClassCollection FINAL : public HTMLCollection {
 public:
-    static PassRefPtr<ClassNodeList> create(PassRefPtr<Node> rootNode, const String& classNames)
+    // classNames argument is an AtomicString because it is common for Elements to share the same class names.
+    // It is also used to construct a SpaceSplitString (m_classNames) and its constructor requires an AtomicString.
+    static PassRefPtr<ClassCollection> create(ContainerNode* rootNode, CollectionType type, const AtomicString& classNames)
     {
-        return adoptRef(new ClassNodeList(rootNode, classNames));
+        ASSERT_UNUSED(type, type == ClassCollectionType);
+        return adoptRef(new ClassCollection(rootNode, classNames));
     }
 
-    virtual ~ClassNodeList();
+    virtual ~ClassCollection();
 
-    bool nodeMatchesInlined(Element*) const;
+    bool elementMatches(const Element&) const;
 
 private:
-    ClassNodeList(PassRefPtr<Node> rootNode, const String& classNames);
-
-    virtual bool nodeMatches(Element*) const OVERRIDE;
+    ClassCollection(ContainerNode* rootNode, const AtomicString& classNames);
 
     SpaceSplitString m_classNames;
-    String m_originalClassNames;
+    AtomicString m_originalClassNames;
 };
 
-inline bool ClassNodeList::nodeMatchesInlined(Element* testNode) const
+inline bool ClassCollection::elementMatches(const Element& testElement) const
 {
-    if (!testNode->hasClass())
+    if (!testElement.hasClass())
         return false;
     if (!m_classNames.size())
         return false;
     // FIXME: DOM4 allows getElementsByClassName to return non StyledElement.
     // https://bugs.webkit.org/show_bug.cgi?id=94718
-    if (!testNode->isStyledElement())
+    if (!testElement.isStyledElement())
         return false;
-    return testNode->classNames().containsAll(m_classNames);
+    return testElement.classNames().containsAll(m_classNames);
 }
 
 } // namespace WebCore
 
-#endif // ClassNodeList_h
+#endif // ClassCollection_h
diff --git a/Source/core/dom/Comment.cpp b/Source/core/dom/Comment.cpp
index 90fb91b..1fc329d 100644
--- a/Source/core/dom/Comment.cpp
+++ b/Source/core/dom/Comment.cpp
@@ -52,9 +52,4 @@
     return create(document(), data());
 }
 
-bool Comment::childTypeAllowed(NodeType) const
-{
-    return false;
-}
-
 } // namespace WebCore
diff --git a/Source/core/dom/Comment.h b/Source/core/dom/Comment.h
index b0625f4..93a03db 100644
--- a/Source/core/dom/Comment.h
+++ b/Source/core/dom/Comment.h
@@ -36,10 +36,9 @@
 private:
     Comment(Document&, const String&);
 
-    virtual String nodeName() const;
-    virtual NodeType nodeType() const;
-    virtual PassRefPtr<Node> cloneNode(bool deep = true);
-    virtual bool childTypeAllowed(NodeType) const;
+    virtual String nodeName() const OVERRIDE;
+    virtual NodeType nodeType() const OVERRIDE;
+    virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE;
 };
 
 DEFINE_NODE_TYPE_CASTS(Comment, nodeType() == Node::COMMENT_NODE);
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index 3f8352c..d63b98e 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -25,17 +25,21 @@
 
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ChildListMutationScope.h"
+#include "core/dom/ClassCollection.h"
 #include "core/dom/ContainerNodeAlgorithms.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/FullscreenElementStack.h"
+#include "core/dom/NameNodeList.h"
 #include "core/dom/NodeChildRemovalTracker.h"
 #include "core/dom/NodeRareData.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeTraversal.h"
+#include "core/dom/SelectorQuery.h"
 #include "core/events/MutationEvent.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/html/HTMLCollection.h"
+#include "core/html/RadioNodeList.h"
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/RenderTheme.h"
@@ -46,6 +50,8 @@
 
 namespace WebCore {
 
+using namespace HTMLNames;
+
 static void dispatchChildInsertionEvents(Node&);
 static void dispatchChildRemovalEvents(Node&);
 
@@ -106,7 +112,7 @@
 
 bool ContainerNode::containsConsideringHostElements(const Node& newChild) const
 {
-    if (isInShadowTree() || document() == document().templateDocument())
+    if (isInShadowTree() || document().isTemplateDocument())
         return newChild.containsIncludingHostElements(*this);
     return newChild.contains(this);
 }
@@ -262,7 +268,7 @@
     ASSERT(newChild);
     ASSERT(nextChild.parentNode() == this);
     ASSERT(!newChild->isDocumentFragment());
-    ASSERT(!hasTagName(HTMLNames::templateTag));
+    ASSERT(!hasTagName(templateTag));
 
     if (nextChild.previousSibling() == newChild || nextChild == newChild) // nothing to do
         return;
@@ -382,7 +388,7 @@
     getChildNodes(*this, children);
 
     ChildListMutationScope mutation(*this);
-    for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) {
+    for (NodeVector::const_iterator it = children.begin(); it != children.end(); ++it) {
         ASSERT(*it);
         Node& child = **it;
         mutation.willRemoveChild(child);
@@ -407,7 +413,10 @@
     RefPtr<Node> protect(this);
 
     // NotFoundError: Raised if oldChild is not a child of this node.
-    if (!oldChild || oldChild->parentNode() != this) {
+    // FIXME: We should never really get PseudoElements in here, but editing will sometimes
+    // attempt to remove them still. We should fix that and enable this ASSERT.
+    // ASSERT(!oldChild->isPseudoElement())
+    if (!oldChild || oldChild->parentNode() != this || oldChild->isPseudoElement()) {
         exceptionState.throwDOMException(NotFoundError, "The node to be removed is not a child of this node.");
         return;
     }
@@ -605,7 +614,7 @@
     ASSERT(newChild);
     ASSERT(!newChild->parentNode()); // Use appendChild if you need to handle reparenting (and want DOM mutation events).
     ASSERT(!newChild->isDocumentFragment());
-    ASSERT(!hasTagName(HTMLNames::templateTag));
+    ASSERT(!hasTagName(templateTag));
 
     if (document() != newChild->document())
         document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
@@ -666,7 +675,6 @@
         return false;
     // What is this code really trying to do?
     RenderObject* o = renderer();
-    RenderObject* p = o;
 
     if (!o->isInline() || o->isReplaced()) {
         point = o->localToAbsolute(FloatPoint(), UseTransforms);
@@ -675,7 +683,7 @@
 
     // find the next text/image child, to get a position
     while (o) {
-        p = o;
+        RenderObject* p = o;
         if (o->firstChild()) {
             o = o->firstChild();
         } else if (o->nextSibling()) {
@@ -803,10 +811,9 @@
     // FIXME: This could probably setNeedsStyleRecalc(LocalStyleChange) in the affectedByFocus case
     // and only setNeedsStyleRecalc(SubtreeStyleChange) in the childrenAffectedByFocus case.
     if (renderStyle()->affectedByFocus() || (isElementNode() && toElement(this)->childrenAffectedByFocus()))
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
     if (renderer() && renderer()->style()->hasAppearance())
         RenderTheme::theme().stateChanged(renderer(), FocusState);
-    InspectorInstrumentation::pseudoStateChanged(this);
 }
 
 void ContainerNode::setFocus(bool received)
@@ -819,7 +826,7 @@
     focusStateChanged();
     // If :focus sets display: none, we lose focus but still need to recalc our style.
     if (!renderer() && !received)
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 void ContainerNode::setActive(bool down)
@@ -831,11 +838,13 @@
 
     // FIXME: Why does this not need to handle the display: none transition like :hover does?
     if (renderer()) {
-        if (renderStyle()->affectedByActive() || (isElementNode() && toElement(this)->childrenAffectedByActive()))
-            setNeedsStyleRecalc();
+        if (isElementNode() && toElement(this)->childrenAffectedByActive())
+            setNeedsStyleRecalc(SubtreeStyleChange);
+        else if (renderStyle()->affectedByActive())
+            setNeedsStyleRecalc(LocalStyleChange);
+
         if (renderStyle()->hasAppearance())
             RenderTheme::theme().stateChanged(renderer(), PressedState);
-        InspectorInstrumentation::pseudoStateChanged(this);
     }
 }
 
@@ -848,48 +857,27 @@
 
     // If :hover sets display: none we lose our hover but still need to recalc our style.
     if (!renderer()) {
-        if (!over)
-            setNeedsStyleRecalc();
-        InspectorInstrumentation::pseudoStateChanged(this);
+        if (over)
+            return;
+        if (isElementNode() && toElement(this)->childrenAffectedByHover())
+            setNeedsStyleRecalc(SubtreeStyleChange);
+        else
+            setNeedsStyleRecalc(LocalStyleChange);
         return;
     }
 
-    if (renderer()) {
-        if (renderStyle()->affectedByHover() || (isElementNode() && toElement(this)->childrenAffectedByHover()))
-            setNeedsStyleRecalc();
-        if (renderer() && renderer()->style()->hasAppearance())
-            RenderTheme::theme().stateChanged(renderer(), HoverState);
-        InspectorInstrumentation::pseudoStateChanged(this);
-    }
+    if (isElementNode() && toElement(this)->childrenAffectedByHover())
+        setNeedsStyleRecalc(SubtreeStyleChange);
+    else if (renderStyle()->affectedByHover())
+        setNeedsStyleRecalc(LocalStyleChange);
+
+    if (renderer()->style()->hasAppearance())
+        RenderTheme::theme().stateChanged(renderer(), HoverState);
 }
 
 PassRefPtr<HTMLCollection> ContainerNode::children()
 {
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, NodeChildren);
-}
-
-Element* ContainerNode::firstElementChild() const
-{
-    return ElementTraversal::firstWithin(*this);
-}
-
-Element* ContainerNode::lastElementChild() const
-{
-    Node* n = lastChild();
-    while (n && !n->isElementNode())
-        n = n->previousSibling();
-    return toElement(n);
-}
-
-unsigned ContainerNode::childElementCount() const
-{
-    unsigned count = 0;
-    Node* n = firstChild();
-    while (n) {
-        count += n->isElementNode();
-        n = n->nextSibling();
-    }
-    return count;
+    return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(this, NodeChildren);
 }
 
 unsigned ContainerNode::childNodeCount() const
@@ -910,6 +898,32 @@
     return n;
 }
 
+PassRefPtr<Element> ContainerNode::querySelector(const AtomicString& selectors, ExceptionState& exceptionState)
+{
+    if (selectors.isEmpty()) {
+        exceptionState.throwDOMException(SyntaxError, "The provided selector is empty.");
+        return 0;
+    }
+
+    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), exceptionState);
+    if (!selectorQuery)
+        return 0;
+    return selectorQuery->queryFirst(*this);
+}
+
+PassRefPtr<NodeList> ContainerNode::querySelectorAll(const AtomicString& selectors, ExceptionState& exceptionState)
+{
+    if (selectors.isEmpty()) {
+        exceptionState.throwDOMException(SyntaxError, "The provided selector is empty.");
+        return 0;
+    }
+
+    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), exceptionState);
+    if (!selectorQuery)
+        return 0;
+    return selectorQuery->queryAll(*this);
+}
+
 static void dispatchChildInsertionEvents(Node& child)
 {
     if (child.isInShadowTree())
@@ -972,6 +986,48 @@
     dispatchChildInsertionEvents(child);
 }
 
+PassRefPtr<HTMLCollection> ContainerNode::getElementsByTagName(const AtomicString& localName)
+{
+    if (localName.isNull())
+        return 0;
+
+    if (document().isHTMLDocument())
+        return ensureRareData().ensureNodeLists().addCache<HTMLTagCollection>(this, HTMLTagCollectionType, localName);
+    return ensureRareData().ensureNodeLists().addCache<TagCollection>(this, TagCollectionType, localName);
+}
+
+PassRefPtr<HTMLCollection> ContainerNode::getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName)
+{
+    if (localName.isNull())
+        return 0;
+
+    if (namespaceURI == starAtom)
+        return getElementsByTagName(localName);
+
+    return ensureRareData().ensureNodeLists().addCache(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localName);
+}
+
+// Takes an AtomicString in argument because it is common for elements to share the same name attribute.
+// Therefore, the NameNodeList factory function expects an AtomicString type.
+PassRefPtr<NodeList> ContainerNode::getElementsByName(const AtomicString& elementName)
+{
+    return ensureRareData().ensureNodeLists().addCache<NameNodeList>(this, NameNodeListType, elementName);
+}
+
+// Takes an AtomicString in argument because it is common for elements to share the same set of class names.
+// Therefore, the ClassNodeList factory function expects an AtomicString type.
+PassRefPtr<HTMLCollection> ContainerNode::getElementsByClassName(const AtomicString& classNames)
+{
+    return ensureRareData().ensureNodeLists().addCache<ClassCollection>(this, ClassCollectionType, classNames);
+}
+
+PassRefPtr<RadioNodeList> ContainerNode::radioNodeList(const AtomicString& name, bool onlyMatchImgElements)
+{
+    ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
+    CollectionType type = onlyMatchImgElements ? RadioImgNodeListType : RadioNodeListType;
+    return ensureRareData().ensureNodeLists().addCache<RadioNodeList>(this, type, name);
+}
+
 #ifndef NDEBUG
 bool childAttachedAllowedWhenAttachingChildren(ContainerNode* node)
 {
diff --git a/Source/core/dom/ContainerNode.h b/Source/core/dom/ContainerNode.h
index d64d782..b0b1ee5 100644
--- a/Source/core/dom/ContainerNode.h
+++ b/Source/core/dom/ContainerNode.h
@@ -87,20 +87,25 @@
     bool hasOneChild() const { return m_firstChild && !m_firstChild->nextSibling(); }
     bool hasOneTextChild() const { return hasOneChild() && m_firstChild->isTextNode(); }
 
-    // ParentNode interface API
     PassRefPtr<HTMLCollection> children();
-    Element* firstElementChild() const;
-    Element* lastElementChild() const;
-    unsigned childElementCount() const;
 
     unsigned childNodeCount() const;
     Node* childNode(unsigned index) const;
 
+    PassRefPtr<Element> querySelector(const AtomicString& selectors, ExceptionState&);
+    PassRefPtr<NodeList> querySelectorAll(const AtomicString& selectors, ExceptionState&);
+
     void insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& = ASSERT_NO_EXCEPTION);
     void replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& = ASSERT_NO_EXCEPTION);
     void removeChild(Node* child, ExceptionState& = ASSERT_NO_EXCEPTION);
     void appendChild(PassRefPtr<Node> newChild, ExceptionState& = ASSERT_NO_EXCEPTION);
 
+    PassRefPtr<HTMLCollection> getElementsByTagName(const AtomicString&);
+    PassRefPtr<HTMLCollection> getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName);
+    PassRefPtr<NodeList> getElementsByName(const AtomicString& elementName);
+    PassRefPtr<HTMLCollection> getElementsByClassName(const AtomicString& classNames);
+    PassRefPtr<RadioNodeList> radioNodeList(const AtomicString&, bool onlyMatchImgElements = false);
+
     // These methods are only used during parsing.
     // They don't send DOM mutation events or handle reparenting.
     // However, arbitrary code may be run by beforeload handlers.
@@ -115,7 +120,7 @@
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual LayoutRect boundingBox() const OVERRIDE;
+    virtual LayoutRect boundingBox() const OVERRIDE FINAL;
     virtual void setFocus(bool) OVERRIDE;
     void focusStateChanged();
     virtual void setActive(bool = true) OVERRIDE;
@@ -130,8 +135,6 @@
 
     void disconnectDescendantFrames();
 
-    virtual bool childShouldCreateRenderer(const Node& child) const { return true; }
-
 protected:
     ContainerNode(TreeScope*, ConstructionType = CreateContainer);
 
diff --git a/Source/core/dom/ContextFeatures.cpp b/Source/core/dom/ContextFeatures.cpp
index 86b980e..980dde1 100644
--- a/Source/core/dom/ContextFeatures.cpp
+++ b/Source/core/dom/ContextFeatures.cpp
@@ -27,9 +27,9 @@
 #include "config.h"
 #include "core/dom/ContextFeatures.h"
 
+#include "RuntimeEnabledFeatures.h"
 #include "core/dom/Document.h"
 #include "core/page/Page.h"
-#include "RuntimeEnabledFeatures.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index ff898a5..661d4f5 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -36,6 +36,7 @@
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/dom/XMLDocument.h"
 #include "core/dom/custom/CustomElementRegistrationContext.h"
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLMediaElement.h"
@@ -46,6 +47,7 @@
 #include "core/html/TextDocument.h"
 #include "core/loader/FrameLoader.h"
 #include "core/frame/Frame.h"
+#include "core/frame/UseCounter.h"
 #include "core/page/Page.h"
 #include "core/svg/SVGDocument.h"
 #include "platform/ContentType.h"
@@ -146,7 +148,6 @@
         addString(svgFeatures, "Cursor");
         addString(svgFeatures, "Hyperlinking");
         addString(svgFeatures, "XlinkAttribute");
-        addString(svgFeatures, "ExternalResourcesRequired");
         addString(svgFeatures, "View");
         addString(svgFeatures, "Script");
         addString(svgFeatures, "Animation");
@@ -178,6 +179,15 @@
     return true;
 }
 
+bool DOMImplementation::hasFeatureForBindings(const String& feature, const String& version)
+{
+    if (!hasFeature(feature, version)) {
+        UseCounter::count(m_document, UseCounter::DOMImplementationHasFeatureReturnFalse);
+        return false;
+    }
+    return true;
+}
+
 PassRefPtr<DocumentType> DOMImplementation::createDocumentType(const AtomicString& qualifiedName,
     const String& publicId, const String& systemId, ExceptionState& exceptionState)
 {
@@ -193,17 +203,19 @@
     return 0;
 }
 
-PassRefPtr<Document> DOMImplementation::createDocument(const AtomicString& namespaceURI,
+PassRefPtr<XMLDocument> DOMImplementation::createDocument(const AtomicString& namespaceURI,
     const AtomicString& qualifiedName, DocumentType* doctype, ExceptionState& exceptionState)
 {
-    RefPtr<Document> doc;
+    RefPtr<XMLDocument> doc;
     DocumentInit init = DocumentInit::fromContext(m_document.contextDocument());
     if (namespaceURI == SVGNames::svgNamespaceURI) {
+        // FIXME: This should be an XMLDocument as per DOM4 but we need to get rid of SVGDocument first.
+        // SVGDocument no longer exists in SVG2.
         doc = SVGDocument::create(init);
     } else if (namespaceURI == HTMLNames::xhtmlNamespaceURI) {
-        doc = Document::createXHTML(init.withRegistrationContext(m_document.registrationContext()));
+        doc = XMLDocument::createXHTML(init.withRegistrationContext(m_document.registrationContext()));
     } else {
-        doc = Document::create(init);
+        doc = XMLDocument::create(init);
     }
 
     doc->setSecurityOrigin(m_document.securityOrigin()->isolatedCopy());
@@ -228,29 +240,26 @@
 {
     // FIXME: Title should be set.
     // FIXME: Media could have wrong syntax, in which case we should generate an exception.
-    RefPtr<CSSStyleSheet> sheet = CSSStyleSheet::create(StyleSheetContents::create());
+    RefPtr<CSSStyleSheet> sheet = CSSStyleSheet::create(StyleSheetContents::create(strictCSSParserContext()));
     sheet->setMediaQueries(MediaQuerySet::create(media));
     return sheet;
 }
 
 bool DOMImplementation::isXMLMIMEType(const String& mimeType)
 {
-    if (mimeType == "text/xml" || mimeType == "application/xml" || mimeType == "text/xsl")
+    if (equalIgnoringCase(mimeType, "text/xml")
+        || equalIgnoringCase(mimeType, "application/xml")
+        || equalIgnoringCase(mimeType, "text/xsl"))
         return true;
 
-    // Per RFCs 3023 and 2045 a mime type is of the form:
+    // Per RFCs 3023 and 2045, an XML MIME type is of the form:
     // ^[0-9a-zA-Z_\\-+~!$\\^{}|.%'`#&*]+/[0-9a-zA-Z_\\-+~!$\\^{}|.%'`#&*]+\+xml$
 
     int length = mimeType.length();
     if (length < 7)
         return false;
 
-    if (mimeType[0] == '/' ||
-        mimeType[length - 5] == '/' ||
-        mimeType[length - 4] != '+' ||
-        mimeType[length - 3] != 'x' ||
-        mimeType[length - 2] != 'm' ||
-        mimeType[length - 1] != 'l')
+    if (mimeType[0] == '/' || mimeType[length - 5] == '/' || !mimeType.endsWith("+xml", false))
         return false;
 
     bool hasSlash = false;
@@ -294,15 +303,36 @@
     return true;
 }
 
+bool DOMImplementation::isJSONMIMEType(const String& mimeType)
+{
+    if (mimeType.startsWith("application/json", false))
+        return true;
+    if (mimeType.startsWith("application/", false)) {
+        size_t subtype = mimeType.find("+json", 12, false);
+        if (subtype != kNotFound) {
+            // Just check that a parameter wasn't matched.
+            size_t parameterMarker = mimeType.find(";");
+            if (parameterMarker == kNotFound) {
+                unsigned endSubtype = static_cast<unsigned>(subtype) + 5;
+                return endSubtype == mimeType.length() || isASCIISpace(mimeType[endSubtype]);
+            }
+            return parameterMarker > subtype;
+        }
+    }
+    return false;
+}
+
+static bool isTextPlainType(const String& mimeType)
+{
+    return mimeType.startsWith("text/", false)
+        && !(equalIgnoringCase(mimeType, "text/html")
+            || equalIgnoringCase(mimeType, "text/xml")
+            || equalIgnoringCase(mimeType, "text/xsl"));
+}
+
 bool DOMImplementation::isTextMIMEType(const String& mimeType)
 {
-    if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType)
-        || mimeType == "application/json" // Render JSON as text/plain.
-        || (mimeType.startsWith("text/") && mimeType != "text/html"
-            && mimeType != "text/xml" && mimeType != "text/xsl"))
-        return true;
-
-    return false;
+    return MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType) || isJSONMIMEType(mimeType) || isTextPlainType(mimeType);
 }
 
 PassRefPtr<HTMLDocument> DOMImplementation::createHTMLDocument(const String& title)
@@ -333,7 +363,7 @@
     if (type == "text/html")
         return HTMLDocument::create(init);
     if (type == "application/xhtml+xml")
-        return Document::createXHTML(init);
+        return XMLDocument::createXHTML(init);
 
     PluginData* pluginData = 0;
     if (init.frame() && init.frame()->page() && init.frame()->loader().allowPlugins(NotAboutToInstantiatePlugin))
@@ -360,7 +390,7 @@
     if (type == "image/svg+xml")
         return SVGDocument::create(init);
     if (isXMLMIMEType(type))
-        return Document::create(init);
+        return XMLDocument::create(init);
 
     return HTMLDocument::create(init);
 }
diff --git a/Source/core/dom/DOMImplementation.h b/Source/core/dom/DOMImplementation.h
index b710d2a..7a93cc0 100644
--- a/Source/core/dom/DOMImplementation.h
+++ b/Source/core/dom/DOMImplementation.h
@@ -38,6 +38,7 @@
 class Frame;
 class HTMLDocument;
 class KURL;
+class XMLDocument;
 
 class DOMImplementation : public ScriptWrappable {
     WTF_MAKE_FAST_ALLOCATED;
@@ -50,8 +51,9 @@
 
     // DOM methods & attributes for DOMImplementation
     static bool hasFeature(const String& feature, const String& version);
+    bool hasFeatureForBindings(const String& feature, const String& version);
     PassRefPtr<DocumentType> createDocumentType(const AtomicString& qualifiedName, const String& publicId, const String& systemId, ExceptionState&);
-    PassRefPtr<Document> createDocument(const AtomicString& namespaceURI, const AtomicString& qualifiedName, DocumentType*, ExceptionState&);
+    PassRefPtr<XMLDocument> createDocument(const AtomicString& namespaceURI, const AtomicString& qualifiedName, DocumentType*, ExceptionState&);
 
     DOMImplementation* getInterface(const String& feature);
 
@@ -62,11 +64,12 @@
     PassRefPtr<HTMLDocument> createHTMLDocument(const String& title);
 
     // Other methods (not part of DOM)
-    static PassRefPtr<Document> createDocument(const String& MIMEType, Frame*, const KURL&, bool inViewSourceMode);
-    static PassRefPtr<Document> createDocument(const String& type, const DocumentInit&, bool inViewSourceMode);
+    static PassRefPtr<Document> createDocument(const String& mimeType, Frame*, const KURL&, bool inViewSourceMode);
+    static PassRefPtr<Document> createDocument(const String& mimeType, const DocumentInit&, bool inViewSourceMode);
 
-    static bool isXMLMIMEType(const String& MIMEType);
-    static bool isTextMIMEType(const String& MIMEType);
+    static bool isXMLMIMEType(const String&);
+    static bool isTextMIMEType(const String&);
+    static bool isJSONMIMEType(const String&);
 
 private:
     explicit DOMImplementation(Document&);
diff --git a/Source/core/dom/DOMImplementation.idl b/Source/core/dom/DOMImplementation.idl
index 7630c5e..7f31def 100644
--- a/Source/core/dom/DOMImplementation.idl
+++ b/Source/core/dom/DOMImplementation.idl
@@ -19,11 +19,12 @@
  */
 
 [
-    GenerateVisitDOMWrapper=document,
+    SetWrapperReferenceFrom=document,
 ] interface DOMImplementation {
 
     // DOM Level 1
 
+    [ImplementedAs=hasFeatureForBindings, MeasureAs=DOMImplementationHasFeature]
     boolean hasFeature(DOMString feature, [TreatNullAs=NullString] DOMString version);
 
     // DOM Level 2
@@ -31,13 +32,13 @@
     [RaisesException] DocumentType createDocumentType(DOMString qualifiedName,
                                                       DOMString publicId,
                                                       DOMString systemId);
-    [RaisesException] Document createDocument([TreatNullAs=NullString] DOMString namespaceURI,
-                                              [TreatNullAs=NullString] DOMString qualifiedName,
-                                              [Default=Undefined] optional DocumentType doctype);
+    [RaisesException] XMLDocument createDocument([TreatNullAs=NullString] DOMString namespaceURI,
+                                                 [TreatNullAs=NullString] DOMString qualifiedName,
+                                                 [Default=Undefined] optional DocumentType doctype);
 
     // DOMImplementationCSS interface from DOM Level 2 CSS
 
-    [MeasureAs=DOMImplementationCreateCSSStyleSheet]
+    [DeprecateAs=DOMImplementationCreateCSSStyleSheet]
     CSSStyleSheet createCSSStyleSheet([Default=Undefined] optional DOMString title,
                                       [Default=Undefined] optional DOMString media);
 
diff --git a/Source/core/dom/DOMImplementationTest.cpp b/Source/core/dom/DOMImplementationTest.cpp
new file mode 100644
index 0000000..73b2f8d
--- /dev/null
+++ b/Source/core/dom/DOMImplementationTest.cpp
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE
+ * COPYRIGHT HOLDER 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.
+ */
+
+#include "config.h"
+#include "core/dom/DOMImplementation.h"
+
+#include "wtf/text/WTFString.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+TEST(DOMImplementationTest, TextMIMEType)
+{
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("text/plain"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("text/javascript"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("TEXT/JavaScript"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/json"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/jSON"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/json;foo=2"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/json  "));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/+json"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/x-javascript-like+json;a=2;c=4"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/javascript"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("Application/Javascript"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/x-custom+json;b=3"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/x-custom+json"));
+    // Outside of RFC-2045 grammar, but robustly accept/allow.
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/x-what+json;"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/json;"));
+    EXPECT_TRUE(DOMImplementation::isTextMIMEType("application/json "));
+
+    EXPECT_FALSE(DOMImplementation::isTextMIMEType("application/x-custom;a=a+json"));
+    EXPECT_FALSE(DOMImplementation::isTextMIMEType("application/x-custom;a=a+json ;"));
+    EXPECT_FALSE(DOMImplementation::isTextMIMEType("application/x-custom+jsonsoup"));
+    EXPECT_FALSE(DOMImplementation::isTextMIMEType("application/x-custom+jsonsoup  "));
+    EXPECT_FALSE(DOMImplementation::isTextMIMEType("text/html"));
+    EXPECT_FALSE(DOMImplementation::isTextMIMEType("text/xml"));
+    EXPECT_FALSE(DOMImplementation::isTextMIMEType("text/xsl"));
+}
+
+TEST(DOMImplementationTest, TextXMLType)
+{
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("text/xml"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("Text/xml"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("tEXt/XML"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("application/xml"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("application/XML"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("application/x-tra+xML"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("application/xslt+xml"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("application/rdf+Xml"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("image/svg+xml"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("text/xsl"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("text/XSL"));
+    EXPECT_TRUE(DOMImplementation::isXMLMIMEType("application/x+xml"));
+
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/x-custom;a=a+xml"));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/x-custom;a=a+xml ;"));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/x-custom+xml2"));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/x-custom+xml2  "));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/x-custom+exml"));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("text/html"));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/xml;"));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/xml "));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/x-what+xml;"));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/x-tra+xML;a=2"));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/+xML"));
+    EXPECT_FALSE(DOMImplementation::isXMLMIMEType("application/+xml"));
+}
+
+}
diff --git a/Source/core/dom/DOMNamedFlowCollection.cpp b/Source/core/dom/DOMNamedFlowCollection.cpp
deleted file mode 100644
index 9fbf981..0000000
--- a/Source/core/dom/DOMNamedFlowCollection.cpp
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-#include "config.h"
-#include "core/dom/DOMNamedFlowCollection.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/dom/NamedFlow.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-DOMNamedFlowCollection::DOMNamedFlowCollection(const Vector<NamedFlow*>& namedFlows)
-{
-    ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
-    ScriptWrappable::init(this);
-    for (Vector<NamedFlow*>::const_iterator it = namedFlows.begin(); it != namedFlows.end(); ++it)
-        m_namedFlows.add(*it);
-}
-
-unsigned long DOMNamedFlowCollection::length() const
-{
-    return m_namedFlows.size();
-}
-
-PassRefPtr<NamedFlow> DOMNamedFlowCollection::item(unsigned long index) const
-{
-    if (index >= static_cast<unsigned long>(m_namedFlows.size()))
-        return 0;
-    DOMNamedFlowSet::const_iterator it = m_namedFlows.begin();
-    for (unsigned long i = 0; i < index; ++i)
-        ++it;
-    return *it;
-}
-
-PassRefPtr<NamedFlow> DOMNamedFlowCollection::namedItem(const AtomicString& name) const
-{
-    DOMNamedFlowSet::const_iterator it = m_namedFlows.find<DOMNamedFlowHashTranslator, String>(name);
-    if (it != m_namedFlows.end())
-        return *it;
-    return 0;
-}
-
-bool DOMNamedFlowCollection::hasNamedItem(const AtomicString& name) const
-{
-    return namedItem(name);
-}
-
-// The HashFunctions object used by the HashSet to compare between RefPtr<NamedFlows>.
-// It is safe to set safeToCompareToEmptyOrDeleted because the HashSet will never contain null pointers or deleted values.
-struct DOMNamedFlowCollection::DOMNamedFlowHashFunctions {
-    static unsigned hash(PassRefPtr<NamedFlow> key) { return DefaultHash<String>::Hash::hash(key->name()); }
-    static bool equal(PassRefPtr<NamedFlow> a, PassRefPtr<NamedFlow> b) { return a->name() == b->name(); }
-    static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-// The HashTranslator is used to lookup a RefPtr<NamedFlow> in the set using a name.
-struct DOMNamedFlowCollection::DOMNamedFlowHashTranslator {
-    static unsigned hash(const String& key) { return DefaultHash<String>::Hash::hash(key); }
-    static bool equal(PassRefPtr<NamedFlow> a, const String& b) { return a->name() == b; }
-};
-} // namespace WebCore
-
-
-
diff --git a/Source/core/dom/DOMNamedFlowCollection.h b/Source/core/dom/DOMNamedFlowCollection.h
deleted file mode 100644
index c7e6a6c..0000000
--- a/Source/core/dom/DOMNamedFlowCollection.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-#ifndef DOMNamedFlowCollection_h
-#define DOMNamedFlowCollection_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/NamedFlowCollection.h"
-#include "wtf/ListHashSet.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class Document;
-class NamedFlow;
-
-class DOMNamedFlowCollection : public ScriptWrappable, public RefCounted<DOMNamedFlowCollection> {
-public:
-    static PassRefPtr<DOMNamedFlowCollection> create(const Vector<NamedFlow*>& namedFlows)
-    {
-        return adoptRef(new DOMNamedFlowCollection(namedFlows));
-    }
-
-    unsigned long length() const;
-    PassRefPtr<NamedFlow> item(unsigned long index) const;
-    PassRefPtr<NamedFlow> namedItem(const AtomicString& name) const;
-
-    bool hasNamedItem(const AtomicString& name) const;
-
-private:
-    struct DOMNamedFlowHashFunctions;
-    struct DOMNamedFlowHashTranslator;
-
-    typedef ListHashSet<RefPtr<NamedFlow>, 1, DOMNamedFlowHashFunctions> DOMNamedFlowSet;
-    explicit DOMNamedFlowCollection(const Vector<NamedFlow*>&);
-    DOMNamedFlowSet m_namedFlows;
-};
-
-} // namespace WebCore
-#endif
-
diff --git a/Source/core/dom/DOMSettableTokenList.cpp b/Source/core/dom/DOMSettableTokenList.cpp
index 2d69533..07098c9 100644
--- a/Source/core/dom/DOMSettableTokenList.cpp
+++ b/Source/core/dom/DOMSettableTokenList.cpp
@@ -58,9 +58,9 @@
 
     for (size_t i = 0; i < tokens.size(); ++i) {
         if (m_tokens.isNull())
-            m_tokens.set(tokens[i], false);
+            m_tokens.set(AtomicString(tokens[i]), false);
         else
-            m_tokens.add(tokens[i]);
+            m_tokens.add(AtomicString(tokens[i]));
     }
 }
 
@@ -77,7 +77,7 @@
 {
     DOMTokenList::remove(tokens, exceptionState);
     for (size_t i = 0; i < tokens.size(); ++i)
-        m_tokens.remove(tokens[i]);
+        m_tokens.remove(AtomicString(tokens[i]));
 }
 
 void DOMSettableTokenList::removeInternal(const AtomicString& token)
diff --git a/Source/core/dom/DOMSettableTokenList.h b/Source/core/dom/DOMSettableTokenList.h
index 234b505..2a59e85 100644
--- a/Source/core/dom/DOMSettableTokenList.h
+++ b/Source/core/dom/DOMSettableTokenList.h
@@ -34,7 +34,7 @@
 
 class ExceptionState;
 
-class DOMSettableTokenList : public DOMTokenList, public RefCounted<DOMSettableTokenList> {
+class DOMSettableTokenList FINAL : public DOMTokenList, public RefCounted<DOMSettableTokenList> {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassRefPtr<DOMSettableTokenList> create()
@@ -52,7 +52,7 @@
     virtual void add(const Vector<String>&, ExceptionState&) OVERRIDE;
     virtual void remove(const Vector<String>&, ExceptionState&) OVERRIDE;
 
-    virtual AtomicString value() const OVERRIDE { return m_value; }
+    virtual const AtomicString& value() const OVERRIDE { return m_value; }
     virtual void setValue(const AtomicString&) OVERRIDE;
 
     const SpaceSplitString& tokens() const { return m_tokens; }
diff --git a/Source/core/dom/DOMSettableTokenList.idl b/Source/core/dom/DOMSettableTokenList.idl
index 18142d0..e02dd69 100644
--- a/Source/core/dom/DOMSettableTokenList.idl
+++ b/Source/core/dom/DOMSettableTokenList.idl
@@ -23,7 +23,7 @@
  */
 
 interface DOMSettableTokenList : DOMTokenList {
-    [TreatReturnedNullStringAs=Null, ImplementedAs=item] getter DOMString(unsigned long index);
+    [TreatReturnedNullStringAs=Null, ImplementedAs=item] getter DOMString (unsigned long index);
     attribute DOMString value;
 };
 
diff --git a/Source/core/dom/DOMStringMap.h b/Source/core/dom/DOMStringMap.h
index 22ce974..fb4d17b 100644
--- a/Source/core/dom/DOMStringMap.h
+++ b/Source/core/dom/DOMStringMap.h
@@ -28,6 +28,7 @@
 
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ScriptWrappable.h"
+#include "bindings/v8/V8Binding.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/Vector.h"
 #include "wtf/text/WTFString.h"
@@ -48,24 +49,16 @@
     virtual String item(const String& name) = 0;
     virtual bool contains(const String& name) = 0;
     virtual void setItem(const String& name, const String& value, ExceptionState&) = 0;
-    virtual void deleteItem(const String& name, ExceptionState&) = 0;
+    virtual bool deleteItem(const String& name) = 0;
     bool anonymousNamedSetter(const String& name, const String& value, ExceptionState& exceptionState)
     {
         setItem(name, value, exceptionState);
         return true;
     }
-    bool anonymousNamedDeleter(const AtomicString& name, ExceptionState&)
+    DeleteResult anonymousNamedDeleter(const AtomicString& name)
     {
-        // FIXME: Remove ExceptionState parameter.
-
-        TrackExceptionState exceptionState;
-        deleteItem(name, exceptionState);
-        bool result = !exceptionState.hadException();
-        // DOMStringMap deleter should ignore exception.
-        // Behavior of Firefox and Opera are same.
-        // delete document.body.dataset["-foo"] // false instead of DOM Exception 12
-        // LayoutTests/fast/dom/HTMLSelectElement/select-selectedIndex-multiple.html
-        return result;
+        bool knownProperty = deleteItem(name);
+        return knownProperty ? DeleteSuccess : DeleteUnknownProperty;
     }
     void namedPropertyEnumerator(Vector<String>& names, ExceptionState&)
     {
@@ -81,9 +74,9 @@
     {
         return anonymousNamedSetter(String::number(index), value, exceptionState);
     }
-    bool anonymousIndexedDeleter(uint32_t index, ExceptionState& exceptionState)
+    DeleteResult anonymousIndexedDeleter(uint32_t index)
     {
-        return anonymousNamedDeleter(AtomicString::number(index), exceptionState);
+        return anonymousNamedDeleter(AtomicString::number(index));
     }
 
     virtual Element* element() = 0;
diff --git a/Source/core/dom/DOMStringMap.idl b/Source/core/dom/DOMStringMap.idl
index fcbbf89..b3590a9 100644
--- a/Source/core/dom/DOMStringMap.idl
+++ b/Source/core/dom/DOMStringMap.idl
@@ -24,13 +24,14 @@
  */
 
 [
-    GenerateVisitDOMWrapper=element,
+    OverrideBuiltins,
+    SetWrapperReferenceFrom=element,
 ] interface DOMStringMap {
-    [ImplementedAs=anonymousIndexedGetter, NotEnumerable] getter DOMString (unsigned long index);
-    [ImplementedAs=anonymousIndexedSetter, RaisesException, NotEnumerable] setter DOMString (unsigned long index, DOMString value);
-    [ImplementedAs=anonymousIndexedDeleter, RaisesException, NotEnumerable] deleter boolean (unsigned long index);
-    [ImplementedAs=item, OverrideBuiltins] getter DOMString (DOMString name);
-    [ImplementedAs=anonymousNamedSetter, RaisesException, OverrideBuiltins] setter DOMString (DOMString name, DOMString value);
-    [ImplementedAs=anonymousNamedDeleter, RaisesException] deleter boolean (DOMString name);
-};
+    [NotEnumerable] getter DOMString (unsigned long index);
+    [RaisesException] setter DOMString (unsigned long index, DOMString value);
+    deleter boolean (unsigned long index);
 
+    [ImplementedAs=item] getter DOMString (DOMString name);
+    [RaisesException] setter DOMString (DOMString name, DOMString value);
+    deleter boolean (DOMString name);
+};
diff --git a/Source/core/dom/DOMTokenList.cpp b/Source/core/dom/DOMTokenList.cpp
index 41255b2..d4aa1a5 100644
--- a/Source/core/dom/DOMTokenList.cpp
+++ b/Source/core/dom/DOMTokenList.cpp
@@ -32,7 +32,7 @@
 
 namespace WebCore {
 
-bool DOMTokenList::validateToken(const AtomicString& token, ExceptionState& exceptionState)
+bool DOMTokenList::validateToken(const String& token, ExceptionState& exceptionState)
 {
     if (token.isEmpty()) {
         exceptionState.throwDOMException(SyntaxError, "The token provided must not be empty.");
@@ -74,6 +74,8 @@
     add(tokens, exceptionState);
 }
 
+// Optimally, this should take a Vector<AtomicString> const ref in argument but the
+// bindings generator does not handle that.
 void DOMTokenList::add(const Vector<String>& tokens, ExceptionState& exceptionState)
 {
     Vector<String> filteredTokens;
@@ -81,7 +83,7 @@
     for (size_t i = 0; i < tokens.size(); ++i) {
         if (!validateToken(tokens[i], exceptionState))
             return;
-        if (containsInternal(tokens[i]))
+        if (containsInternal(AtomicString(tokens[i])))
             continue;
         if (filteredTokens.contains(tokens[i]))
             continue;
@@ -101,6 +103,8 @@
     remove(tokens, exceptionState);
 }
 
+// Optimally, this should take a Vector<AtomicString> const ref in argument but the
+// bindings generator does not handle that.
 void DOMTokenList::remove(const Vector<String>& tokens, ExceptionState& exceptionState)
 {
     if (!validateTokens(tokens, exceptionState))
@@ -110,7 +114,7 @@
     // through the string character by character.
     bool found = false;
     for (size_t i = 0; i < tokens.size(); ++i) {
-        if (containsInternal(tokens[i])) {
+        if (containsInternal(AtomicString(tokens[i]))) {
             found = true;
             break;
         }
@@ -161,14 +165,16 @@
     setValue(removeToken(value(), token));
 }
 
-String DOMTokenList::addToken(const AtomicString& input, const AtomicString& token)
+AtomicString DOMTokenList::addToken(const AtomicString& input, const AtomicString& token)
 {
     Vector<String> tokens;
     tokens.append(token.string());
     return addTokens(input, tokens);
 }
 
-String DOMTokenList::addTokens(const AtomicString& input, const Vector<String>& tokens)
+// This returns an AtomicString because it is always passed as argument to setValue() and setValue()
+// takes an AtomicString in argument.
+AtomicString DOMTokenList::addTokens(const AtomicString& input, const Vector<String>& tokens)
 {
     bool needsSpace = false;
 
@@ -185,17 +191,19 @@
         needsSpace = true;
     }
 
-    return builder.toString();
+    return builder.toAtomicString();
 }
 
-String DOMTokenList::removeToken(const AtomicString& input, const AtomicString& token)
+AtomicString DOMTokenList::removeToken(const AtomicString& input, const AtomicString& token)
 {
     Vector<String> tokens;
     tokens.append(token.string());
     return removeTokens(input, tokens);
 }
 
-String DOMTokenList::removeTokens(const AtomicString& input, const Vector<String>& tokens)
+// This returns an AtomicString because it is always passed as argument to setValue() and setValue()
+// takes an AtomicString in argument.
+AtomicString DOMTokenList::removeTokens(const AtomicString& input, const Vector<String>& tokens)
 {
     // Algorithm defined at http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#remove-a-token-from-a-string
     // New spec is at http://dom.spec.whatwg.org/#remove-a-token-from-a-string
@@ -238,7 +246,7 @@
         }
     }
 
-    return output.toString();
+    return output.toAtomicString();
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DOMTokenList.h b/Source/core/dom/DOMTokenList.h
index d758214..bd5204e 100644
--- a/Source/core/dom/DOMTokenList.h
+++ b/Source/core/dom/DOMTokenList.h
@@ -57,24 +57,24 @@
     bool toggle(const AtomicString&, ExceptionState&);
     bool toggle(const AtomicString&, bool force, ExceptionState&);
 
-    AtomicString toString() const { return value(); }
+    const AtomicString& toString() const { return value(); }
 
     virtual Element* element() { return 0; }
 
 protected:
-    virtual AtomicString value() const = 0;
+    virtual const AtomicString& value() const = 0;
     virtual void setValue(const AtomicString&) = 0;
 
     virtual void addInternal(const AtomicString&);
     virtual bool containsInternal(const AtomicString&) const = 0;
     virtual void removeInternal(const AtomicString&);
 
-    static bool validateToken(const AtomicString&, ExceptionState&);
+    static bool validateToken(const String&, ExceptionState&);
     static bool validateTokens(const Vector<String>&, ExceptionState&);
-    static String addToken(const AtomicString&, const AtomicString&);
-    static String addTokens(const AtomicString&, const Vector<String>&);
-    static String removeToken(const AtomicString&, const AtomicString&);
-    static String removeTokens(const AtomicString&, const Vector<String>&);
+    static AtomicString addToken(const AtomicString&, const AtomicString&);
+    static AtomicString addTokens(const AtomicString&, const Vector<String>&);
+    static AtomicString removeToken(const AtomicString&, const AtomicString&);
+    static AtomicString removeTokens(const AtomicString&, const Vector<String>&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/DOMTokenList.idl b/Source/core/dom/DOMTokenList.idl
index 9830b7e..6072629 100644
--- a/Source/core/dom/DOMTokenList.idl
+++ b/Source/core/dom/DOMTokenList.idl
@@ -23,7 +23,7 @@
  */
 
 [
-    GenerateVisitDOMWrapper=element,
+    SetWrapperReferenceFrom=element,
 ] interface DOMTokenList {
     readonly attribute unsigned long length;
     [TreatReturnedNullStringAs=Null] getter DOMString item(unsigned long index);
diff --git a/Source/core/dom/DatasetDOMStringMap.cpp b/Source/core/dom/DatasetDOMStringMap.cpp
index 9215319..14c082d 100644
--- a/Source/core/dom/DatasetDOMStringMap.cpp
+++ b/Source/core/dom/DatasetDOMStringMap.cpp
@@ -107,7 +107,9 @@
     return true;
 }
 
-static String convertPropertyNameToAttributeName(const String& name)
+// This returns an AtomicString because attribute names are always stored
+// as AtomicString types in Element (see setAttribute()).
+static AtomicString convertPropertyNameToAttributeName(const String& name)
 {
     StringBuilder builder;
     builder.append("data-");
@@ -122,7 +124,7 @@
             builder.append(character);
     }
 
-    return builder.toString();
+    return builder.toAtomicString();
 }
 
 void DatasetDOMStringMap::ref()
@@ -185,17 +187,19 @@
         return;
     }
 
-    m_element->setAttribute(convertPropertyNameToAttributeName(name), value, exceptionState);
+    m_element->setAttribute(convertPropertyNameToAttributeName(name), AtomicString(value), exceptionState);
 }
 
-void DatasetDOMStringMap::deleteItem(const String& name, ExceptionState& exceptionState)
+bool DatasetDOMStringMap::deleteItem(const String& name)
 {
-    if (!isValidPropertyName(name)) {
-        exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToDelete(name, "DOMStringMap", "'" + name + "' is not a valid property name."));
-        return;
+    if (isValidPropertyName(name)) {
+        AtomicString attributeName = convertPropertyNameToAttributeName(name);
+        if (m_element->hasAttribute(attributeName)) {
+            m_element->removeAttribute(attributeName);
+            return true;
+        }
     }
-
-    m_element->removeAttribute(convertPropertyNameToAttributeName(name));
+    return false;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DatasetDOMStringMap.h b/Source/core/dom/DatasetDOMStringMap.h
index 9bbd1d0..9d2220f 100644
--- a/Source/core/dom/DatasetDOMStringMap.h
+++ b/Source/core/dom/DatasetDOMStringMap.h
@@ -34,23 +34,23 @@
 class Element;
 class ExceptionState;
 
-class DatasetDOMStringMap : public DOMStringMap {
+class DatasetDOMStringMap FINAL : public DOMStringMap {
 public:
     static PassOwnPtr<DatasetDOMStringMap> create(Element* element)
     {
         return adoptPtr(new DatasetDOMStringMap(element));
     }
 
-    virtual void ref();
-    virtual void deref();
+    virtual void ref() OVERRIDE;
+    virtual void deref() OVERRIDE;
 
-    virtual void getNames(Vector<String>&);
-    virtual String item(const String& name);
-    virtual bool contains(const String& name);
-    virtual void setItem(const String& name, const String& value, ExceptionState&);
-    virtual void deleteItem(const String& name, ExceptionState&);
+    virtual void getNames(Vector<String>&) OVERRIDE;
+    virtual String item(const String& name) OVERRIDE;
+    virtual bool contains(const String& name) OVERRIDE;
+    virtual void setItem(const String& name, const String& value, ExceptionState&) OVERRIDE;
+    virtual bool deleteItem(const String& name) OVERRIDE;
 
-    virtual Element* element() { return m_element; }
+    virtual Element* element() OVERRIDE { return m_element; }
 
 private:
     explicit DatasetDOMStringMap(Element* element)
diff --git a/Source/core/dom/DecodedDataDocumentParser.cpp b/Source/core/dom/DecodedDataDocumentParser.cpp
index 7f3c01f..d5a118c 100644
--- a/Source/core/dom/DecodedDataDocumentParser.cpp
+++ b/Source/core/dom/DecodedDataDocumentParser.cpp
@@ -28,13 +28,13 @@
 
 #include "core/dom/Document.h"
 #include "core/dom/DocumentEncodingData.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 
 namespace WebCore {
 
 DecodedDataDocumentParser::DecodedDataDocumentParser(Document* document)
     : DocumentParser(document)
-    , m_hasAppendedData(false)
+    , m_needsDecoder(true)
 {
 }
 
@@ -44,6 +44,10 @@
 
 void DecodedDataDocumentParser::setDecoder(PassOwnPtr<TextResourceDecoder> decoder)
 {
+    // If the decoder is explicitly unset rather than having ownership
+    // transferred away by takeDecoder(), we need to make sure it's recreated
+    // next time data is appended.
+    m_needsDecoder = !decoder;
     m_decoder = decoder;
 }
 
@@ -52,9 +56,9 @@
     return m_decoder.get();
 }
 
-void DecodedDataDocumentParser::setHasAppendedData()
+PassOwnPtr<TextResourceDecoder> DecodedDataDocumentParser::takeDecoder()
 {
-    m_hasAppendedData = true;
+    return m_decoder.release();
 }
 
 void DecodedDataDocumentParser::appendBytes(const char* data, size_t length)
@@ -91,22 +95,10 @@
 
 void DecodedDataDocumentParser::updateDocument(String& decodedData)
 {
-    DocumentEncodingData encodingData;
-    encodingData.encoding = m_decoder->encoding();
-    encodingData.wasDetectedHeuristically = m_decoder->encodingWasDetectedHeuristically();
-    encodingData.sawDecodingError = m_decoder->sawError();
-    document()->setEncodingData(encodingData);
+    document()->setEncodingData(DocumentEncodingData(*m_decoder.get()));
 
-    if (decodedData.isEmpty())
-        return;
-
-    append(decodedData.releaseImpl());
-    // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
-    if (!m_hasAppendedData) {
-        m_hasAppendedData = true;
-        if (m_decoder->encoding().usesVisualOrdering())
-            document()->setVisuallyOrdered();
-    }
+    if (!decodedData.isEmpty())
+        append(decodedData.releaseImpl());
 }
 
 };
diff --git a/Source/core/dom/DecodedDataDocumentParser.h b/Source/core/dom/DecodedDataDocumentParser.h
index 453147d..6264bbb 100644
--- a/Source/core/dom/DecodedDataDocumentParser.h
+++ b/Source/core/dom/DecodedDataDocumentParser.h
@@ -42,10 +42,11 @@
     // The below functions are used by DocumentWriter (the loader).
     virtual void appendBytes(const char* bytes, size_t length) OVERRIDE;
     virtual void flush() OVERRIDE;
-    virtual bool needsDecoder() const OVERRIDE { return !m_decoder; }
+    virtual bool needsDecoder() const OVERRIDE FINAL { return m_needsDecoder; }
     virtual void setDecoder(PassOwnPtr<TextResourceDecoder>) OVERRIDE;
-    virtual TextResourceDecoder* decoder() OVERRIDE;
-    virtual void setHasAppendedData() OVERRIDE;
+    virtual TextResourceDecoder* decoder() OVERRIDE FINAL;
+
+    PassOwnPtr<TextResourceDecoder> takeDecoder();
 
 protected:
     explicit DecodedDataDocumentParser(Document*);
@@ -57,7 +58,7 @@
 
     void updateDocument(String& decodedData);
 
-    bool m_hasAppendedData;
+    bool m_needsDecoder;
     OwnPtr<TextResourceDecoder> m_decoder;
 };
 
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index 2e9ebcf..13a6cc2 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -46,7 +46,6 @@
 #include "core/animation/DocumentAnimations.h"
 #include "core/animation/DocumentTimeline.h"
 #include "core/animation/css/TransitionTimeline.h"
-#include "core/css/CSSDefaultStyleSheets.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSStyleDeclaration.h"
 #include "core/css/CSSStyleSheet.h"
@@ -63,19 +62,18 @@
 #include "core/dom/Comment.h"
 #include "core/dom/ContextFeatures.h"
 #include "core/dom/DOMImplementation.h"
-#include "core/dom/DOMNamedFlowCollection.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/DocumentLifecycleNotifier.h"
 #include "core/dom/DocumentLifecycleObserver.h"
 #include "core/dom/DocumentMarkerController.h"
-#include "core/dom/DocumentSharedObjectPool.h"
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementDataCache.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExecutionContextTask.h"
 #include "core/dom/MainThreadTaskRunner.h"
-#include "core/dom/NamedFlowCollection.h"
+#include "core/dom/MutationObserver.h"
 #include "core/dom/NodeChildRemovalTracker.h"
 #include "core/dom/NodeFilter.h"
 #include "core/dom/NodeIterator.h"
@@ -95,6 +93,7 @@
 #include "core/dom/TransformSource.h"
 #include "core/dom/TreeWalker.h"
 #include "core/dom/VisitedLinkState.h"
+#include "core/dom/XMLDocument.h"
 #include "core/dom/custom/CustomElementRegistrationContext.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -110,14 +109,14 @@
 #include "core/events/ScopedEventQueue.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/fetch/ResourceFetcher.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/frame/ContentSecurityPolicy.h"
-#include "core/frame/DOMSecurityPolicy.h"
 #include "core/frame/DOMWindow.h"
 #include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
 #include "core/frame/FrameView.h"
 #include "core/frame/History.h"
-#include "core/frame/animation/AnimationController.h"
+#include "core/frame/PageConsole.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLAllCollection.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLCanvasElement.h"
@@ -126,11 +125,11 @@
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLHeadElement.h"
-#include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLImport.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLLinkElement.h"
+#include "core/html/HTMLMetaElement.h"
 #include "core/html/HTMLNameCollection.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/HTMLStyleElement.h"
@@ -140,6 +139,7 @@
 #include "core/html/parser/HTMLDocumentParser.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/NestingLevelIncrementer.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/inspector/InspectorCounters.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/inspector/ScriptCallStack.h"
@@ -152,12 +152,11 @@
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/EventHandler.h"
+#include "core/page/FocusController.h"
 #include "core/page/FrameTree.h"
 #include "core/page/MouseEventWithHitTestResults.h"
 #include "core/page/Page.h"
-#include "core/page/PageConsole.h"
 #include "core/page/PointerLockController.h"
-#include "core/page/Settings.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/rendering/FastTextAutosizer.h"
 #include "core/rendering/HitTestResult.h"
@@ -167,6 +166,8 @@
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGFontFaceElement.h"
 #include "core/svg/SVGStyleElement.h"
+#include "core/svg/SVGUseElement.h"
+#include "core/workers/SharedWorkerRepositoryClient.h"
 #include "core/xml/XSLTProcessor.h"
 #include "core/xml/parser/XMLDocumentParser.h"
 #include "platform/DateComponents.h"
@@ -341,39 +342,63 @@
 
 uint64_t Document::s_globalTreeVersion = 0;
 
-// This class should be passed only to Document::postTask.
-class CheckFocusedElementTask FINAL : public ExecutionContextTask {
+// This class doesn't work with non-Document ExecutionContext.
+class AutofocusTask FINAL : public ExecutionContextTask {
 public:
-    static PassOwnPtr<CheckFocusedElementTask> create()
+    static PassOwnPtr<AutofocusTask> create()
     {
-        return adoptPtr(new CheckFocusedElementTask());
+        return adoptPtr(new AutofocusTask());
     }
-    virtual ~CheckFocusedElementTask() { }
+    virtual ~AutofocusTask() { }
 
 private:
-    CheckFocusedElementTask() { }
+    AutofocusTask() { }
     virtual void performTask(ExecutionContext* context) OVERRIDE
     {
-        ASSERT(context->isDocument());
         Document* document = toDocument(context);
-        document->didRunCheckFocusedElementTask();
-        Element* element = document->focusedElement();
-        if (!element)
-            return;
-        if (document->childNeedsStyleRecalc()) {
-            document->setNeedsFocusedElementCheck();
-            return;
+        if (RefPtr<Element> element = document->autofocusElement()) {
+            document->setAutofocusElement(0);
+            element->focus();
         }
-        if (element->renderer() && element->renderer()->needsLayout())
-            return;
-        if (!element->isFocusable())
-            document->setFocusedElement(0);
     }
 };
 
+DocumentVisibilityObserver::DocumentVisibilityObserver(Document& document)
+    : m_document(0)
+{
+    registerObserver(document);
+}
+
+DocumentVisibilityObserver::~DocumentVisibilityObserver()
+{
+    unregisterObserver();
+}
+
+void DocumentVisibilityObserver::unregisterObserver()
+{
+    if (m_document) {
+        m_document->unregisterVisibilityObserver(this);
+        m_document = 0;
+    }
+}
+
+void DocumentVisibilityObserver::registerObserver(Document& document)
+{
+    ASSERT(!m_document);
+    m_document = &document;
+    if (m_document)
+        m_document->registerVisibilityObserver(this);
+}
+
+void DocumentVisibilityObserver::setObservedDocument(Document& document)
+{
+    unregisterObserver();
+    registerObserver(document);
+}
+
 Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
     : ContainerNode(0, CreateDocument)
-    , TreeScope(this)
+    , TreeScope(*this)
     , m_hasNodesWithPlaceholderStyle(false)
     , m_needsNotifyRemoveAllPendingStylesheet(false)
     , m_evaluateMediaQueriesOnStyleRecalc(false)
@@ -388,16 +413,15 @@
     , m_paginatedForScreen(false)
     , m_compatibilityMode(NoQuirksMode)
     , m_compatibilityModeLocked(false)
-    , m_didPostCheckFocusedElementTask(false)
+    , m_hasAutofocused(false)
+    , m_clearFocusedElementTimer(this, &Document::clearFocusedElementTimerFired)
     , m_domTreeVersion(++s_globalTreeVersion)
     , m_listenerTypes(0)
     , m_mutationObserverTypes(0)
     , m_visitedLinkState(VisitedLinkState::create(*this))
     , m_visuallyOrdered(false)
     , m_readyState(Complete)
-    , m_bParsing(false)
-    , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
-    , m_inStyleRecalc(false)
+    , m_isParsing(false)
     , m_gotoAnchorNeededAfterStylesheetsLoad(false)
     , m_containsValidityStyleRules(false)
     , m_updateFocusAppearanceRestoresSelection(false)
@@ -409,7 +433,6 @@
     , m_cssTarget(0)
     , m_loadEventProgress(LoadEventNotRun)
     , m_startTime(currentTime())
-    , m_overMinimumLayoutThreshold(false)
     , m_scriptRunner(ScriptRunner::create(this))
     , m_xmlVersion("1.0")
     , m_xmlStandalone(StandaloneUnspecified)
@@ -423,14 +446,14 @@
     , m_sawElementsInKnownNamespaces(false)
     , m_isSrcdocDocument(false)
     , m_isMobileDocument(false)
-    , m_mayDisplaySeamlesslyWithParent(false)
     , m_renderView(0)
     , m_weakFactory(this)
     , m_contextDocument(initializer.contextDocument())
-    , m_idAttributeName(idAttr)
     , m_hasFullscreenElementStack(false)
     , m_loadEventDelayCount(0)
     , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
+    , m_pluginLoadingTimer(this, &Document::pluginLoadingTimerFired)
+    , m_didSetReferrerPolicy(false)
     , m_referrerPolicy(ReferrerPolicyDefault)
     , m_directionSetOnDocumentElement(false)
     , m_writingModeSetOnDocumentElement(false)
@@ -439,7 +462,7 @@
     , m_lastHandledUserGestureTimestamp(0)
     , m_taskRunner(MainThreadTaskRunner::create(this))
     , m_registrationContext(initializer.registrationContext(this))
-    , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
+    , m_elementDataCacheClearTimer(this, &Document::elementDataCacheClearTimerFired)
 #ifndef NDEBUG
     , m_didDispatchViewportPropertiesChanged(false)
 #endif
@@ -448,6 +471,7 @@
     , m_transitionTimeline(TransitionTimeline::create(this))
     , m_templateDocumentHost(0)
     , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
+    , m_hasViewportUnits(false)
 {
     setClient(this);
     ScriptWrappable::init(this);
@@ -455,7 +479,7 @@
     if (m_frame) {
         provideContextFeaturesToDocumentFrom(this, m_frame->page());
 
-        m_fetcher = m_frame->loader().activeDocumentLoader()->fetcher();
+        m_fetcher = m_frame->loader().documentLoader()->fetcher();
     }
 
     if (!m_fetcher)
@@ -478,7 +502,7 @@
 
     InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
 
-    m_lifecyle.advanceTo(DocumentLifecycle::Inactive);
+    m_lifecycle.advanceTo(DocumentLifecycle::Inactive);
 
     // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
     // CSSFontSelector, need to initialize m_styleEngine after initializing
@@ -490,14 +514,12 @@
 {
     ASSERT(!renderView());
     ASSERT(m_ranges.isEmpty());
-    ASSERT(!m_parentTreeScope);
+    ASSERT(!parentTreeScope());
     ASSERT(!hasGuardRefCount());
+    ASSERT(m_visibilityObservers.isEmpty());
 
     if (m_templateDocument)
-        m_templateDocument->setTemplateDocumentHost(0); // balanced in templateDocument().
-
-    if (Document* ownerDocument = this->ownerDocument())
-        ownerDocument->didRemoveEventTargetNode(this);
+        m_templateDocument->m_templateDocumentHost = 0; // balanced in ensureTemplateDocument().
 
     m_scriptRunner.clear();
 
@@ -523,6 +545,14 @@
         m_import = 0;
     }
 
+    if (m_timeline) {
+        m_timeline->detachFromDocument();
+    }
+
+    if (m_transitionTimeline) {
+        m_transitionTimeline->detachFromDocument();
+    }
+
     m_styleEngine.clear(); // We need to destory CSSFontSelector before destroying m_fetcher.
 
     if (m_elemSheet)
@@ -544,7 +574,6 @@
     for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
         ASSERT(!m_nodeListCounts[i]);
 
-    clearDocumentScope();
     setClient(0);
 
     InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
@@ -558,7 +587,7 @@
     m_docType = 0;
     m_focusedElement = 0;
     m_hoverNode = 0;
-    m_activeElement = 0;
+    m_activeHoverElement = 0;
     m_titleElement = 0;
     m_documentElement = 0;
     m_contextFeatures = ContextFeatures::defaultSwitch();
@@ -593,7 +622,7 @@
     if (svgExtensions())
         accessSVGExtensions()->pauseAnimations();
 
-    m_lifecyle.advanceTo(DocumentLifecycle::Disposed);
+    m_lifecycle.advanceTo(DocumentLifecycle::Disposed);
     lifecycleNotifier().notifyDocumentWasDisposed();
 }
 
@@ -657,7 +686,7 @@
 
 bool Document::hasManifest() const
 {
-    return documentElement() && isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
+    return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttribute(manifestAttr);
 }
 
 Location* Document::location() const
@@ -683,55 +712,76 @@
 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
 {
     if (!isValidName(name)) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
         return 0;
     }
 
     if (isXHTMLDocument() || isHTMLDocument())
-        return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, document(), 0, false);
+        return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, *this, 0, false);
 
-    return createElement(QualifiedName(nullAtom, name, nullAtom), false);
+    return Element::create(QualifiedName(nullAtom, name, nullAtom), this);
 }
 
 PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
 {
     if (!isValidName(localName)) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + localName + "') is not a valid name.");
         return 0;
     }
 
     RefPtr<Element> element;
 
-    if (RuntimeEnabledFeatures::customElementsEnabled() && CustomElement::isValidName(localName) && registrationContext())
+    if (CustomElement::isValidName(localName) && registrationContext()) {
         element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
-    else
+    } else {
         element = createElement(localName, exceptionState);
+        if (exceptionState.hadException())
+            return 0;
+    }
 
-    if (RuntimeEnabledFeatures::customElementsEnabled() && !typeExtension.isNull() && !typeExtension.isEmpty())
+    if (!typeExtension.isEmpty())
         CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
 
     return element;
 }
 
-PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
+static inline QualifiedName createQualifiedName(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
 {
     AtomicString prefix, localName;
-    if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
-        return 0;
+    if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
+        return nullQName();
 
     QualifiedName qName(prefix, localName, namespaceURI);
-    if (!hasValidNamespaceForElements(qName)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
-        return 0;
+    if (!Document::hasValidNamespaceForElements(qName)) {
+        exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
+        return nullQName();
     }
 
+    return qName;
+}
+
+PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
+{
+    QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
+    if (qName == nullQName())
+        return 0;
+
+    return createElement(qName, false);
+}
+
+PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
+{
+    QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
+    if (qName == nullQName())
+        return 0;
+
     RefPtr<Element> element;
     if (CustomElement::isValidName(qName.localName()) && registrationContext())
         element = registrationContext()->createCustomTagElement(*this, qName);
     else
-        element = createElementNS(namespaceURI, qualifiedName, exceptionState);
+        element = createElement(qName, false);
 
-    if (!typeExtension.isNull() && !typeExtension.isEmpty())
+    if (!typeExtension.isEmpty())
         CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
 
     return element;
@@ -745,7 +795,7 @@
 ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
 {
     if (!registrationContext()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "No element registration context is available.");
         return ScriptValue();
     }
 
@@ -767,12 +817,29 @@
 
 bool Document::haveImportsLoaded() const
 {
-    return !m_import || !m_import->isBlocked();
+    return !m_import || !m_import->state().shouldBlockScriptExecution();
+}
+
+DOMWindow* Document::executingWindow()
+{
+    if (DOMWindow* owningWindow = domWindow())
+        return owningWindow;
+    if (HTMLImport* import = this->import())
+        return import->master()->domWindow();
+    return 0;
+}
+
+Frame* Document::executingFrame()
+{
+    DOMWindow* window = executingWindow();
+    if (!window)
+        return 0;
+    return window->frame();
 }
 
 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
 {
-    return DocumentFragment::create(document());
+    return DocumentFragment::create(*this);
 }
 
 PassRefPtr<Text> Document::createTextNode(const String& data)
@@ -788,7 +855,7 @@
 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
 {
     if (isHTMLDocument()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "This operation is not supported for HTML documents.");
         return 0;
     }
     if (data.contains("]]>")) {
@@ -816,15 +883,10 @@
     return Text::createEditingText(*this, text);
 }
 
-PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
-{
-    return MutableStylePropertySet::create()->ensureCSSStyleDeclaration();
-}
-
 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
 {
     if (!importedNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The node provided is invalid.");
         return 0;
     }
 
@@ -837,12 +899,16 @@
         return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
     case COMMENT_NODE:
         return createComment(importedNode->nodeValue());
+    case DOCUMENT_TYPE_NODE: {
+        DocumentType* doctype = toDocumentType(importedNode);
+        return DocumentType::create(this, doctype->name(), doctype->publicId(), doctype->systemId());
+    }
     case ELEMENT_NODE: {
         Element* oldElement = toElement(importedNode);
         // FIXME: The following check might be unnecessary. Is it possible that
         // oldElement has mismatched prefix/namespace?
         if (!hasValidNamespaceForElements(oldElement->tagQName())) {
-            exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
+            exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
             return 0;
         }
         RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
@@ -863,12 +929,13 @@
         return newElement.release();
     }
     case ATTRIBUTE_NODE:
-        return Attr::create(*this, QualifiedName(nullAtom, toAttr(importedNode)->name(), nullAtom), toAttr(importedNode)->value());
+        return Attr::create(*this, QualifiedName(nullAtom, AtomicString(toAttr(importedNode)->name()), nullAtom), toAttr(importedNode)->value());
     case DOCUMENT_FRAGMENT_NODE: {
         if (importedNode->isShadowRoot()) {
             // ShadowRoot nodes should not be explicitly importable.
             // Either they are imported along with their host node, or created implicitly.
-            break;
+            exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
+            return 0;
         }
         DocumentFragment* oldFragment = toDocumentFragment(importedNode);
         RefPtr<DocumentFragment> newFragment = createDocumentFragment();
@@ -885,35 +952,28 @@
 
         return newFragment.release();
     }
-    case ENTITY_NODE:
-    case NOTATION_NODE:
-        // FIXME: It should be possible to import these node types, however in DOM3 the DocumentType is readonly, so there isn't much sense in doing that.
-        // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
     case DOCUMENT_NODE:
-    case DOCUMENT_TYPE_NODE:
-    case XPATH_NAMESPACE_NODE:
-        break;
+        exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
+        return 0;
     }
-    exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+
+    ASSERT_NOT_REACHED();
     return 0;
 }
 
 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& exceptionState)
 {
     if (!source) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The node provided is invalid.");
         return 0;
     }
 
     EventQueueScope scope;
 
     switch (source->nodeType()) {
-    case ENTITY_NODE:
-    case NOTATION_NODE:
     case DOCUMENT_NODE:
     case DOCUMENT_TYPE_NODE:
-    case XPATH_NAMESPACE_NODE:
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The node provided is of type '" + source->nodeName() + "', which may not be adopted.");
         return 0;
     case ATTRIBUTE_NODE: {
         Attr* attr = toAttr(source.get());
@@ -924,14 +984,14 @@
     default:
         if (source->isShadowRoot()) {
             // ShadowRoot cannot disconnect itself from the host node.
-            exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+            exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
             return 0;
         }
 
         if (source->isFrameOwnerElement()) {
             HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
             if (frame() && frame()->tree().isDescendantOf(frameOwnerElement->contentFrame())) {
-                exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+                exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
                 return 0;
             }
         }
@@ -958,21 +1018,14 @@
 
     // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
     // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
-    // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
-    if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
-        return false;
-
-    return true;
+    // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
+    if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
+        return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
+    return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
 }
 
 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
 {
-    // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS
-    if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
-        // Note: The case of an "xmlns" qualified name with a namespace of
-        // xmlnsNamespaceURI is specifically allowed (See <http://www.w3.org/2000/xmlns/>).
-        return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
-    }
     return hasValidNamespaceForElements(qName);
 }
 
@@ -983,14 +1036,14 @@
 
     // FIXME: Use registered namespaces and look up in a hash to find the right factory.
     if (qName.namespaceURI() == xhtmlNamespaceURI)
-        e = HTMLElementFactory::createHTMLElement(qName.localName(), document(), 0, createdByParser);
+        e = HTMLElementFactory::createHTMLElement(qName.localName(), *this, 0, createdByParser);
     else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
-        e = SVGElementFactory::createSVGElement(qName.localName(), document(), createdByParser);
+        e = SVGElementFactory::createSVGElement(qName.localName(), *this, createdByParser);
 
     if (e)
         m_sawElementsInKnownNamespaces = true;
     else
-        e = Element::create(qName, &document());
+        e = Element::create(qName, this);
 
     if (e->prefix() != qName.prefix())
         e->setTagNameForCreateElementNS(qName);
@@ -1005,39 +1058,6 @@
     return settings() && settings()->regionBasedColumnsEnabled();
 }
 
-PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
-{
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderView())
-        return 0;
-
-    updateStyleIfNeeded();
-
-    return namedFlows()->createCSSOMSnapshot();
-}
-
-NamedFlowCollection* Document::namedFlows()
-{
-    if (!m_namedFlows)
-        m_namedFlows = NamedFlowCollection::create(this);
-
-    return m_namedFlows.get();
-}
-
-PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
-{
-    AtomicString prefix, localName;
-    if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
-        return 0;
-
-    QualifiedName qName(prefix, localName, namespaceURI);
-    if (!hasValidNamespaceForElements(qName)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
-        return 0;
-    }
-
-    return createElement(qName, false);
-}
-
 String Document::readyState() const
 {
     DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
@@ -1066,8 +1086,7 @@
     case Loading:
         if (!m_documentTiming.domLoading) {
             m_documentTiming.domLoading = monotonicallyIncreasingTime();
-            if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-                m_timeline->setZeroTime(m_documentTiming.domLoading);
+            m_timeline->setZeroTime(m_documentTiming.domLoading);
         }
         break;
     case Interactive:
@@ -1113,7 +1132,7 @@
     if (!encoding.isValid())
         return;
     DocumentEncodingData newEncodingData = m_encodingData;
-    newEncodingData.encoding = encoding;
+    newEncodingData.setEncoding(encoding);
     setEncodingData(newEncodingData);
 }
 
@@ -1124,18 +1143,18 @@
     m_contentLanguage = language;
 
     // Document's style depends on the content language.
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
 {
     if (!implementation()->hasFeature("XML", String())) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "This document does not support XML.");
         return;
     }
 
     if (!XMLDocumentParser::supportsXMLVersion(version)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "This document does not support the XML version '" + version + "'.");
         return;
     }
 
@@ -1145,7 +1164,7 @@
 void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
 {
     if (!implementation()->hasFeature("XML", String())) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "This document does not support XML.");
         return;
     }
 
@@ -1171,10 +1190,13 @@
 
 String Document::suggestedMIMEType() const
 {
-    if (isXHTMLDocument())
-        return "application/xhtml+xml";
-    if (isSVGDocument())
-        return "image/svg+xml";
+    if (isXMLDocument()) {
+        if (isXHTMLDocument())
+            return "application/xhtml+xml";
+        if (isSVGDocument())
+            return "image/svg+xml";
+        return "application/xml";
+    }
     if (xmlStandalone())
         return "text/xml";
     if (isHTMLDocument())
@@ -1197,8 +1219,8 @@
 {
     if (!renderView())
         return 0;
-    LayoutPoint localPoint;
-    RenderObject* renderer = rendererFromPoint(this, x, y, &localPoint);
+    HitTestResult result = hitTestInDocument(this, x, y);
+    RenderObject* renderer = result.renderer();
     if (!renderer)
         return 0;
 
@@ -1210,7 +1232,7 @@
         return Range::create(*this, container, offset, container, offset);
     }
 
-    PositionWithAffinity positionWithAffinity = renderer->positionForPoint(localPoint);
+    PositionWithAffinity positionWithAffinity = renderer->positionForPoint(result.localPoint());
     if (positionWithAffinity.position().isNull())
         return 0;
 
@@ -1302,15 +1324,15 @@
         m_titleElement = 0;
     else if (!m_titleElement) {
         if (HTMLElement* headElement = head()) {
-            m_titleElement = createElement(titleTag, false);
+            m_titleElement = HTMLTitleElement::create(*this);
             headElement->appendChild(m_titleElement);
         }
     }
 
-    updateTitle(title);
-
-    if (m_titleElement && isHTMLTitleElement(m_titleElement.get()))
+    if (m_titleElement && m_titleElement->hasTagName(titleTag))
         toHTMLTitleElement(m_titleElement)->setText(title);
+    else
+        updateTitle(title);
 }
 
 void Document::setTitleElement(const String& title, Element* titleElement)
@@ -1336,8 +1358,8 @@
     // FIXME: This is broken for SVG.
     // Update title based on first title element in the head, if one exists.
     if (HTMLElement* headElement = head()) {
-        for (Element* element = headElement->firstElementChild(); element; element = element->nextElementSibling()) {
-            if (!isHTMLTitleElement(element))
+        for (Element* element = ElementTraversal::firstWithin(*headElement); element; element = ElementTraversal::nextSibling(*element)) {
+            if (!element->hasTagName(titleTag))
                 continue;
             HTMLTitleElement* title = toHTMLTitleElement(element);
             setTitleElement(title->text(), title);
@@ -1370,18 +1392,28 @@
     return pageVisibilityState() != PageVisibilityStateVisible;
 }
 
-void Document::dispatchVisibilityStateChangeEvent()
+void Document::didChangeVisibilityState()
 {
     dispatchEvent(Event::create(EventTypeNames::visibilitychange));
     // Also send out the deprecated version until it can be removed.
     dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
+
+    PageVisibilityState state = pageVisibilityState();
+    HashSet<DocumentVisibilityObserver*>::const_iterator observerEnd = m_visibilityObservers.end();
+    for (HashSet<DocumentVisibilityObserver*>::const_iterator it = m_visibilityObservers.begin(); it != observerEnd; ++it)
+        (*it)->didChangeVisibilityState(state);
 }
 
-DOMSecurityPolicy* Document::securityPolicy()
+void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
 {
-    if (!m_domSecurityPolicy)
-        m_domSecurityPolicy = DOMSecurityPolicy::create(this);
-    return m_domSecurityPolicy.get();
+    ASSERT(!m_visibilityObservers.contains(observer));
+    m_visibilityObservers.add(observer);
+}
+
+void Document::unregisterVisibilityObserver(DocumentVisibilityObserver* observer)
+{
+    ASSERT(m_visibilityObservers.contains(observer));
+    m_visibilityObservers.remove(observer);
 }
 
 String Document::nodeName() const
@@ -1425,6 +1457,11 @@
     return m_frame ? m_frame->page() : 0;
 }
 
+FrameHost* Document::frameHost() const
+{
+    return m_frame ? m_frame->host() : 0;
+}
+
 Settings* Document::settings() const
 {
     return m_frame ? m_frame->settings() : 0;
@@ -1439,7 +1476,7 @@
 {
     // FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
     if (!root) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
         return 0;
     }
     return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
@@ -1448,7 +1485,7 @@
 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
 {
     if (!root) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
         return 0;
     }
     // FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
@@ -1459,7 +1496,7 @@
 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
 {
     if (!root) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
         return 0;
     }
     // FIXME: Ditto.
@@ -1469,7 +1506,7 @@
 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
 {
     if (!root) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
         return 0;
     }
     return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
@@ -1478,7 +1515,7 @@
 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
 {
     if (!root) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
         return 0;
     }
     return TreeWalker::create(root, whatToShow, PassRefPtr<NodeFilter>());
@@ -1487,50 +1524,52 @@
 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
 {
     if (!root) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
         return 0;
     }
     return TreeWalker::create(root, whatToShow, filter);
 }
 
+bool Document::shouldCallRecalcStyleForDocument()
+{
+    if (!isActive() || !view())
+        return false;
+    return needsStyleRecalc() || childNeedsStyleRecalc() || childNeedsDistributionRecalc() || !m_useElementsNeedingUpdate.isEmpty() || childNeedsStyleInvalidation();
+}
+
+bool Document::shouldScheduleStyleRecalc()
+{
+    if (!isActive())
+        return false;
+    if (hasPendingStyleRecalc())
+        return false;
+    if (inStyleRecalc())
+        return false;
+    // InPreLayout will recalc style itself. There's no reason to schedule another recalc.
+    if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
+        return false;
+    if (!shouldScheduleLayout())
+        return false;
+    return true;
+}
+
 void Document::scheduleStyleRecalc()
 {
-    if (shouldDisplaySeamlesslyWithParent()) {
-        // When we're seamless, our parent document manages our style recalcs.
-        ownerElement()->setNeedsStyleRecalc();
-        ownerElement()->document().scheduleStyleRecalc();
-        return;
-    }
-
-    if (m_styleRecalcTimer.isActive())
+    if (!shouldScheduleStyleRecalc())
         return;
 
-    ASSERT(needsStyleRecalc() || childNeedsStyleRecalc() || childNeedsDistributionRecalc());
+    ASSERT(shouldCallRecalcStyleForDocument());
 
-    m_styleRecalcTimer.startOneShot(0);
+    if (!view()->isServicingAnimations())
+        view()->scheduleAnimation();
+    m_lifecycle.advanceTo(DocumentLifecycle::StyleRecalcPending);
 
     InspectorInstrumentation::didScheduleStyleRecalculation(this);
 }
 
-void Document::unscheduleStyleRecalc()
-{
-    ASSERT(!isActive() || (!needsStyleRecalc() && !childNeedsStyleRecalc()));
-    m_styleRecalcTimer.stop();
-}
-
-bool Document::hasPendingStyleRecalc() const
-{
-    return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
-}
-
 bool Document::hasPendingForcedStyleRecalc() const
 {
-    return hasPendingStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
-}
-
-void Document::styleRecalcTimerFired(Timer<Document>*)
-{
-    updateStyleIfNeeded();
+    return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
 }
 
 void Document::updateDistributionIfNeeded()
@@ -1541,6 +1580,21 @@
     recalcDistribution();
 }
 
+void Document::updateStyleInvalidationIfNeeded()
+{
+    if (!childNeedsStyleInvalidation())
+        return;
+    TRACE_EVENT0("webkit", "Document::computeNeedsStyleRecalcState");
+    if (!styleResolver()) {
+        clearChildNeedsStyleInvalidation();
+        return;
+    }
+
+    // FIXME: the style resolver can be deleted at present. Either resolve
+    // crbug.com/335964 or move the invalidation data elsewhere.
+    styleResolver()->ensureRuleFeatureSet().computeStyleInvalidation(*this);
+}
+
 void Document::updateDistributionForNodeIfNeeded(Node* node)
 {
     if (node->inDocument()) {
@@ -1556,20 +1610,8 @@
         root->recalcDistribution();
 }
 
-void Document::setStyleDependentState(RenderStyle* documentStyle)
+void Document::setupFontBuilder(RenderStyle* documentStyle)
 {
-    const Pagination& pagination = view()->pagination();
-    if (pagination.mode != Pagination::Unpaginated) {
-        Pagination::setStylesForPaginationMode(pagination.mode, documentStyle);
-        documentStyle->setColumnGap(pagination.gap);
-        if (renderView()->hasColumns())
-            renderView()->updateColumnInfoFromStyle(documentStyle);
-    }
-
-    // Seamless iframes want to inherit their font from their parent iframe, so early return before setting the font.
-    if (shouldDisplaySeamlesslyWithParent())
-        return;
-
     FontBuilder fontBuilder;
     fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
     RefPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
@@ -1587,10 +1629,11 @@
 
     WritingMode rootWritingMode = documentElementStyle->writingMode();
     TextDirection rootDirection = documentElementStyle->direction();
-    HTMLElement* body = this->body();
 
+    HTMLElement* body = this->body();
+    RefPtr<RenderStyle> bodyStyle;
     if (body) {
-        RefPtr<RenderStyle> bodyStyle = body->renderStyle();
+        bodyStyle = body->renderStyle();
         if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
             bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
         if (!writingModeSetOnDocumentElement())
@@ -1599,70 +1642,123 @@
             rootDirection = bodyStyle->direction();
     }
 
+    RefPtr<RenderStyle> overflowStyle;
+    if (Element* element = viewportDefiningElement(documentElementStyle.get())) {
+        if (element == body) {
+            overflowStyle = bodyStyle;
+        } else {
+            ASSERT(element == documentElement());
+            overflowStyle = documentElementStyle;
+        }
+    }
+
+    // Resolved rem units are stored in the matched properties cache so we need to make sure to
+    // invalidate the cache if the documentElement needed to reattach or the font size changed
+    // and then trigger a full document recalc. We also need to clear it here since the
+    // call to styleForElement on the body above can cache bad values for rem units if the
+    // documentElement's style was dirty. We could keep track of which elements depend on
+    // rem units like we do for viewport styles, but we assume root font size changes are
+    // rare and just invalidate the cache for now.
+    if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
+        ensureStyleResolver().invalidateMatchedPropertiesCache();
+        documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
+    }
+
     RefPtr<RenderStyle> documentStyle = renderView()->style();
-    if (documentStyle->writingMode() != rootWritingMode || documentStyle->direction() != rootDirection) {
+    if (documentStyle->writingMode() != rootWritingMode
+        || documentStyle->direction() != rootDirection
+        || (overflowStyle && (documentStyle->overflowX() != overflowStyle->overflowX() || documentStyle->overflowY() != overflowStyle->overflowY()))) {
         RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
         newStyle->setWritingMode(rootWritingMode);
         newStyle->setDirection(rootDirection);
+        EOverflow overflowX = OAUTO;
+        EOverflow overflowY = OAUTO;
+        if (overflowStyle) {
+            overflowX = overflowStyle->overflowX();
+            overflowY = overflowStyle->overflowY();
+            // Visible overflow on the viewport is meaningless, and the spec says to treat it as 'auto':
+            if (overflowX == OVISIBLE)
+                overflowX = OAUTO;
+            if (overflowY == OVISIBLE)
+                overflowY = OAUTO;
+
+            // Column-gap is (ab)used by the current paged overflow implementation (in lack of other
+            // ways to specify gaps between pages), so we have to propagate it too.
+            newStyle->setColumnGap(overflowStyle->columnGap());
+        }
+        newStyle->setOverflowX(overflowX);
+        newStyle->setOverflowY(overflowY);
         renderView()->setStyle(newStyle);
-        setStyleDependentState(newStyle.get());
+        setupFontBuilder(newStyle.get());
     }
 
     if (body) {
         if (RenderStyle* style = body->renderStyle()) {
             if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
-                body->setNeedsStyleRecalc();
+                body->setNeedsStyleRecalc(SubtreeStyleChange);
         }
     }
 
     if (RenderStyle* style = documentElement()->renderStyle()) {
         if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
-            documentElement()->setNeedsStyleRecalc();
+            documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
     }
 }
 
-void Document::recalcStyle(StyleRecalcChange change)
+void Document::updateStyleIfNeeded()
 {
-    // we should not enter style recalc while painting
-    RELEASE_ASSERT(!view() || !view()->isPainting());
+    updateStyle(NoChange);
+}
 
-    // FIXME: We should never enter here without a FrameView or with an inactive document.
-    if (!isActive() || !view())
+// FIXME: We need a better name than updateStyleIfNeeded. It's performing style invalidation,
+// style recalc, distribution and <use> shadow tree creation.
+void Document::updateStyle(StyleRecalcChange change)
+{
+    ASSERT(isMainThread());
+
+    if (!shouldCallRecalcStyleForDocument())
         return;
 
-    if (m_inStyleRecalc)
+    if (inStyleRecalc())
         return;
 
+    // Entering here from inside layout or paint would be catastrophic since recalcStyle can
+    // tear down the render tree or (unfortunately) run script. Kill the whole renderer if
+    // someone managed to get into here from inside layout or paint.
+    RELEASE_ASSERT(!view()->isInPerformLayout());
+    RELEASE_ASSERT(!view()->isPainting());
+
+    // Script can run below in PostAttachCallbacks or WidgetUpdates, so protect the Frame.
+    RefPtr<Frame> protect(m_frame);
+
     TRACE_EVENT0("webkit", "Document::recalcStyle");
     TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "RecalcStyle");
 
-    updateDistributionIfNeeded();
-
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
 
+    updateDistributionIfNeeded();
+    updateUseShadowTreesIfNeeded();
+    updateStyleInvalidationIfNeeded();
+
     if (m_evaluateMediaQueriesOnStyleRecalc) {
         m_evaluateMediaQueriesOnStyleRecalc = false;
         evaluateMediaQueryList();
     }
 
-    // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
+    // FIXME: We should update style on our ancestor chain before proceeding
     // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
     // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
     // resolves style (here) and then when we resolve style on the parent chain, we may end up
     // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
     // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
 
-    if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
-        m_styleEngine->updateActiveStyleSheets(FullStyleUpdate);
-
     if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
         m_styleEngine->setUsesRemUnit(true);
 
     {
         PostAttachCallbacks::SuspendScope suspendPostAttachCallbacks;
         RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
-        FrameView::DeferredRepaintScope deferRepaints(*view());
-        TemporaryChange<bool> changeInStyleRecalc(m_inStyleRecalc, true);
+        m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
 
         if (styleChangeType() >= SubtreeStyleChange)
             change = Force;
@@ -1672,7 +1768,7 @@
         // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
         // mac when accessing the resolver by what appears to be a viewport size difference.
 
-        if (change == Force || (change >= Inherit && shouldDisplaySeamlesslyWithParent())) {
+        if (change == Force) {
             m_hasNodesWithPlaceholderStyle = false;
             RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleEngine->fontSelector());
             StyleRecalcChange localChange = RenderStyle::compare(documentStyle.get(), renderView()->style());
@@ -1693,7 +1789,7 @@
 
         if (Element* documentElement = this->documentElement()) {
             inheritHtmlAndBodyElementStyles(change);
-            if (shouldRecalcStyle(change, documentElement))
+            if (documentElement->shouldCallRecalcStyle(change))
                 documentElement->recalcStyle(change);
         }
 
@@ -1702,12 +1798,6 @@
         view()->updateCompositingLayersAfterStyleChange();
 
         clearChildNeedsStyleRecalc();
-        unscheduleStyleRecalc();
-
-        // FIXME: SVG <use> element can schedule a recalc in the middle of an already running one.
-        // See StyleEngine::updateActiveStyleSheets.
-        if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
-            setNeedsStyleRecalc();
 
         if (m_styleEngine->hasResolver()) {
             // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
@@ -1715,39 +1805,43 @@
             m_styleEngine->resetCSSFeatureFlags(resolver.ensureRuleFeatureSet());
             resolver.clearStyleSharingList();
         }
-    }
 
-    InspectorInstrumentation::didRecalculateStyle(cookie);
+        ASSERT(!needsStyleRecalc());
+        ASSERT(!childNeedsStyleRecalc());
+        ASSERT(inStyleRecalc());
+        m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
+    }
 
     // As a result of the style recalculation, the currently hovered element might have been
     // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
     // to check if any other elements ended up under the mouse pointer due to re-layout.
     if (hoverNode() && !hoverNode()->renderer() && frame())
         frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
-}
 
-void Document::updateStyleIfNeeded()
-{
-    ASSERT(isMainThread());
-    ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
+    if (m_focusedElement && !m_focusedElement->isFocusable())
+        clearFocusedElementSoon();
 
-    if (!needsStyleRecalc() && !childNeedsStyleRecalc() && !childNeedsDistributionRecalc())
-        return;
-
-    AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : 0);
-    recalcStyle(NoChange);
     DocumentAnimations::serviceAfterStyleRecalc(*this);
+
+    InspectorInstrumentation::didRecalculateStyle(cookie);
 }
 
 void Document::updateStyleForNodeIfNeeded(Node* node)
 {
-    if (!hasPendingForcedStyleRecalc() && !childNeedsStyleRecalc() && !needsStyleRecalc())
+    if (!shouldCallRecalcStyleForDocument())
         return;
 
-    bool needsStyleRecalc = hasPendingForcedStyleRecalc();
-    for (Node* ancestor = node; ancestor && !needsStyleRecalc; ancestor = ancestor->parentOrShadowHostNode())
-        needsStyleRecalc = ancestor->needsStyleRecalc();
-    if (needsStyleRecalc)
+    // At this point, we know that we need to recalc some style on the document in order to fully update styles.
+    // However, style on 'node' only needs to be recalculated if a global recomputation is needed, or a node on
+    // the path from 'node' to the root needs style recalc.
+
+    // Global needed.
+    bool needsRecalc = needsStyleRecalc() || childNeedsDistributionRecalc() || !m_useElementsNeedingUpdate.isEmpty() || childNeedsStyleInvalidation();
+
+    // On the path.
+    for (Node* ancestor = node; ancestor && !needsRecalc; ancestor = ancestor->parentOrShadowHostNode())
+        needsRecalc = ancestor->needsStyleRecalc();
+    if (needsRecalc)
         updateStyleIfNeeded();
 }
 
@@ -1756,7 +1850,7 @@
     ASSERT(isMainThread());
 
     RefPtr<FrameView> frameView = view();
-    if (frameView && frameView->isInLayout()) {
+    if (frameView && frameView->isInPerformLayout()) {
         // View layout should not be re-entrant.
         ASSERT_NOT_REACHED();
         return;
@@ -1773,17 +1867,26 @@
 
     if (isActive() && frameView)
         frameView->partialLayout().reset();
-
-    setNeedsFocusedElementCheck();
 }
 
 void Document::setNeedsFocusedElementCheck()
 {
-    // FIXME: Using a Task doesn't look a good idea.
-    if (!m_focusedElement || m_didPostCheckFocusedElementTask)
-        return;
-    m_taskRunner->postTask(CheckFocusedElementTask::create());
-    m_didPostCheckFocusedElementTask = true;
+    setNeedsStyleRecalc(LocalStyleChange);
+}
+
+void Document::clearFocusedElementSoon()
+{
+    if (!m_clearFocusedElementTimer.isActive())
+        m_clearFocusedElementTimer.startOneShot(0);
+}
+
+void Document::clearFocusedElementTimerFired(Timer<Document>*)
+{
+    updateStyleIfNeeded();
+    m_clearFocusedElementTimer.stop();
+
+    if (m_focusedElement && !m_focusedElement->isFocusable())
+        setFocusedElement(0);
 }
 
 void Document::recalcStyleForLayoutIgnoringPendingStylesheets()
@@ -1808,7 +1911,7 @@
         // If new nodes have been added or style recalc has been done with style sheets still
         // pending, some nodes may not have had their real style calculated yet. Normally this
         // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
-        recalcStyle(Force);
+        updateStyle(Force);
     }
 }
 
@@ -1879,7 +1982,6 @@
 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
 {
     RefPtr<RenderStyle> style = styleForPage(pageIndex);
-    RenderView* view = renderView();
 
     int width = pageSize.width();
     int height = pageSize.height();
@@ -1898,8 +2000,8 @@
         LengthSize size = style->pageSize();
         ASSERT(size.width().isFixed());
         ASSERT(size.height().isFixed());
-        width = valueForLength(size.width(), 0, view);
-        height = valueForLength(size.height(), 0, view);
+        width = valueForLength(size.width(), 0);
+        height = valueForLength(size.height(), 0);
         break;
     }
     default:
@@ -1909,10 +2011,10 @@
 
     // The percentage is calculated with respect to the width even for margin top and bottom.
     // http://www.w3.org/TR/CSS2/box.html#margin-properties
-    marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
-    marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
-    marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
-    marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
+    marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
+    marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
+    marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
+    marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
 }
 
 void Document::setIsViewSource(bool isViewSource)
@@ -1925,6 +2027,31 @@
     didUpdateSecurityOrigin();
 }
 
+void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
+{
+    m_useElementsNeedingUpdate.add(&element);
+    scheduleStyleRecalc();
+}
+
+void Document::unscheduleUseShadowTreeUpdate(SVGUseElement& element)
+{
+    m_useElementsNeedingUpdate.remove(&element);
+}
+
+void Document::updateUseShadowTreesIfNeeded()
+{
+    if (m_useElementsNeedingUpdate.isEmpty())
+        return;
+
+    Vector<SVGUseElement*> elements;
+    copyToVector(m_useElementsNeedingUpdate, elements);
+    m_useElementsNeedingUpdate.clear();
+
+    Vector<SVGUseElement*>::iterator end = elements.end();
+    for (Vector<SVGUseElement*>::iterator it = elements.begin(); it != end; ++it)
+        (*it)->buildPendingResource();
+}
+
 StyleResolver* Document::styleResolver() const
 {
     return m_styleEngine->resolver();
@@ -1942,7 +2069,7 @@
 
 void Document::attach(const AttachContext& context)
 {
-    ASSERT(m_lifecyle.state() == DocumentLifecycle::Inactive);
+    ASSERT(m_lifecycle.state() == DocumentLifecycle::Inactive);
     ASSERT(!m_axObjectCache || this != topDocument());
 
     m_renderView = new RenderView(this);
@@ -1952,21 +2079,22 @@
     m_renderView->setStyle(StyleResolver::styleForDocument(*this));
     view()->updateCompositingLayersAfterStyleChange();
 
-    m_styleEngine->didAttach();
-
     ContainerNode::attach(context);
 
-    m_lifecyle.advanceTo(DocumentLifecycle::Active);
+    m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
 }
 
 void Document::detach(const AttachContext& context)
 {
     ASSERT(isActive());
-    m_lifecyle.advanceTo(DocumentLifecycle::Stopping);
+    m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
 
     if (page())
         page()->documentDetached(this);
 
+    if (m_frame->loader().client()->sharedWorkerRepositoryClient())
+        m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
+
     if (this == topDocument())
         clearAXObjectCache();
 
@@ -2002,19 +2130,18 @@
 
     m_hoverNode = 0;
     m_focusedElement = 0;
-    m_activeElement = 0;
+    m_activeHoverElement = 0;
+    m_autofocusElement = 0;
 
     ContainerNode::detach(context);
 
-    unscheduleStyleRecalc();
-
     m_styleEngine->didDetach();
 
     if (renderView)
         renderView->destroy();
 
-    if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
-        parentDocument()->didRemoveEventTargetNode(this);
+    if (Document* parentDoc = parentDocument())
+        parentDoc->didClearTouchEventHandlers(this);
 
     // This is required, as our Frame might delete itself as soon as it detaches
     // us. However, this violates Node::detach() semantics, as it's never
@@ -2027,7 +2154,7 @@
         m_mediaQueryMatcher->documentDestroyed();
 
     lifecycleNotifier().notifyDocumentWasDetached();
-    m_lifecyle.advanceTo(DocumentLifecycle::Stopped);
+    m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
 }
 
 void Document::prepareForDestruction()
@@ -2046,7 +2173,7 @@
 
 void Document::removeAllEventListeners()
 {
-    EventTarget::removeAllEventListeners();
+    ContainerNode::removeAllEventListeners();
 
     if (DOMWindow* domWindow = this->domWindow())
         domWindow->removeAllEventListeners();
@@ -2096,19 +2223,10 @@
     return topDocument->m_axObjectCache.get();
 }
 
-void Document::setVisuallyOrdered()
-{
-    m_visuallyOrdered = true;
-    // FIXME: How is possible to not have a renderer here?
-    if (renderView())
-        renderView()->style()->setRTLOrdering(VisualOrder);
-    setNeedsStyleRecalc();
-}
-
 PassRefPtr<DocumentParser> Document::createParser()
 {
     if (isHTMLDocument()) {
-        bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(this->page());
+        bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(page());
         return HTMLDocumentParser::create(toHTMLDocument(this), reportErrors);
     }
     // FIXME: this should probably pass the frame instead
@@ -2193,12 +2311,6 @@
 
     setCompatibilityMode(NoQuirksMode);
 
-    // Documents rendered seamlessly should start out requiring a stylesheet
-    // collection update in order to ensure they inherit all the relevant data
-    // from their parent.
-    if (shouldDisplaySeamlesslyWithParent())
-        styleResolverChanged(RecalcStyleDeferred);
-
     m_parser = createParser();
     setParsing(true);
     setReadyState(Loading);
@@ -2223,13 +2335,17 @@
 {
     RefPtr<HTMLElement> newBody = prpNewBody;
 
-    if (!newBody || !documentElement()) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+    if (!newBody) {
+        exceptionState.throwDOMException(HierarchyRequestError, "The node provided is invalid.");
+        return;
+    }
+    if (!documentElement()) {
+        exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
         return;
     }
 
     if (!newBody->hasTagName(bodyTag) && !newBody->hasTagName(framesetTag)) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwDOMException(HierarchyRequestError, "The new body element is of type '" + newBody->tagName() + "'. It must be either a 'BODY' or 'FRAMESET' element.");
         return;
     }
 
@@ -2256,6 +2372,28 @@
     return 0;
 }
 
+Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
+{
+    // If a BODY element sets non-visible overflow, it is to be propagated to the viewport, as long
+    // as the following conditions are all met:
+    // (1) The root element is HTML.
+    // (2) It is the primary BODY element (we only assert for this, expecting callers to behave).
+    // (3) The root element has visible overflow.
+    // Otherwise it's the root element's properties that are to be propagated.
+    Element* rootElement = documentElement();
+    Element* bodyElement = body();
+    if (!rootElement)
+        return 0;
+    if (!rootStyle) {
+        rootStyle = rootElement->renderStyle();
+        if (!rootStyle)
+            return 0;
+    }
+    if (bodyElement && rootStyle->isOverflowVisible() && rootElement->hasTagName(htmlTag))
+        return bodyElement;
+    return rootElement;
+}
+
 void Document::close()
 {
     // FIXME: We should follow the specification more closely:
@@ -2323,8 +2461,7 @@
     // those two functions repeatedly and don't save them on the stack.
 
     // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
-    // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
-    // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
+    // here, instead of doing it from SVGElement::finishedParsingChildren.
     if (svgExtensions())
         accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
 
@@ -2349,14 +2486,12 @@
         // Just bail out. Before or during the onload we were shifted to another page.
         // The old i-Bench suite does this. When this happens don't bother painting or laying out.
         m_loadEventProgress = LoadEventCompleted;
-        view()->unscheduleRelayout();
         return;
     }
 
     // We used to force a synchronous display and flush here.  This really isn't
     // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
     // (if your platform is syncing flushes and limiting them to 60fps).
-    m_overMinimumLayoutThreshold = true;
     if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
         updateStyleIfNeeded();
 
@@ -2479,13 +2614,10 @@
 
 void Document::setParsing(bool b)
 {
-    m_bParsing = b;
+    m_isParsing = b;
 
-    if (m_bParsing && !m_sharedObjectPool)
-        m_sharedObjectPool = DocumentSharedObjectPool::create();
-
-    if (!m_bParsing && view())
-        view()->scheduleRelayout();
+    if (m_isParsing && !m_elementDataCache)
+        m_elementDataCache = ElementDataCache::create();
 }
 
 bool Document::shouldScheduleLayout()
@@ -2497,24 +2629,12 @@
     //    (b) Only schedule layout once we have a body element.
 
     return (haveStylesheetsLoaded() && body())
-        || (documentElement() && !isHTMLHtmlElement(documentElement()));
+        || (documentElement() && !documentElement()->hasTagName(htmlTag));
 }
 
 bool Document::shouldParserYieldAgressivelyBeforeScriptExecution()
 {
-    return view() && view()->layoutPending() && !minimumLayoutDelay();
-}
-
-int Document::minimumLayoutDelay()
-{
-    if (m_overMinimumLayoutThreshold)
-        return 0;
-
-    int elapsed = elapsedTime();
-    m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
-
-    // We'll want to schedule the timer to fire at the minimum layout threshold.
-    return max(0, cLayoutScheduleThreshold - elapsed);
+    return view() && view()->layoutPending();
 }
 
 int Document::elapsedTime() const
@@ -2533,8 +2653,11 @@
        return;
 
     bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
-    if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
+
+    if (!hasInsertionPoint && m_ignoreDestructiveWriteCount) {
+        addConsoleMessage(JSMessageSource, WarningMessageLevel, ExceptionMessages::failedToExecute("write", "Document", "It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened."));
         return;
+    }
 
     if (!hasInsertionPoint)
         open(ownerDocument);
@@ -2589,7 +2712,6 @@
         return;
 
     m_url = newURL;
-    m_documentURI = m_url.string();
     updateBaseURL();
     contextFeatures()->urlDidChange(this);
 }
@@ -2599,18 +2721,14 @@
     KURL oldBaseURL = m_baseURL;
     // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
     // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
-    // from the Document interface otherwise.
+    // from the Document interface otherwise (which we store, preparsed, in m_url).
     if (!m_baseElementURL.isEmpty())
         m_baseURL = m_baseElementURL;
     else if (!m_baseURLOverride.isEmpty())
         m_baseURL = m_baseURLOverride;
-    else {
-        // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
-        // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
-        // and DOM 3 Core does not specify how it should be resolved.
-        // FIXME: Now that we don't support Objective-C this can probably be removed.
-        m_baseURL = KURL(ParsedURLString, documentURI());
-    }
+    else
+        m_baseURL = m_url;
+
     selectorQueryCache().invalidate();
 
     if (!m_baseURL.isValid())
@@ -2629,7 +2747,7 @@
         // Base URL change changes any relative visited links.
         // FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
         for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::next(*element)) {
-            if (isHTMLAnchorElement(element))
+            if (element->hasTagName(aTag))
                 toHTMLAnchorElement(element)->invalidateCachedVisitedLinkHash();
         }
     }
@@ -2768,13 +2886,6 @@
     return 0;
 }
 
-
-void Document::seamlessParentUpdatedStylesheets()
-{
-    m_styleEngine->didModifySeamlessParentStyleSheet();
-    styleResolverChanged(RecalcStyleImmediately);
-}
-
 void Document::didRemoveAllPendingStylesheet()
 {
     m_needsNotifyRemoveAllPendingStylesheet = false;
@@ -2802,40 +2913,36 @@
     return m_elemSheet.get();
 }
 
-void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content)
+void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement)
 {
     ASSERT(!equiv.isNull() && !content.isNull());
 
-    if (equalIgnoringCase(equiv, "default-style"))
+    if (equalIgnoringCase(equiv, "default-style")) {
         processHttpEquivDefaultStyle(content);
-    else if (equalIgnoringCase(equiv, "refresh"))
+    } else if (equalIgnoringCase(equiv, "refresh")) {
         processHttpEquivRefresh(content);
-    else if (equalIgnoringCase(equiv, "set-cookie"))
+    } else if (equalIgnoringCase(equiv, "set-cookie")) {
         processHttpEquivSetCookie(content);
-    else if (equalIgnoringCase(equiv, "content-language"))
+    } else if (equalIgnoringCase(equiv, "content-language")) {
         setContentLanguage(content);
-    else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
+    } else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) {
         parseDNSPrefetchControlHeader(content);
-    else if (equalIgnoringCase(equiv, "x-frame-options"))
+    } else if (equalIgnoringCase(equiv, "x-frame-options")) {
         processHttpEquivXFrameOptions(content);
-    else if (equalIgnoringCase(equiv, "content-security-policy")
-        || equalIgnoringCase(equiv, "content-security-policy-report-only")
-        || equalIgnoringCase(equiv, "x-webkit-csp")
-        || equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
-        processHttpEquivContentSecurityPolicy(equiv, content);
+    } else if (equalIgnoringCase(equiv, "content-security-policy") || equalIgnoringCase(equiv, "content-security-policy-report-only")) {
+        if (inDocumentHeadElement)
+            processHttpEquivContentSecurityPolicy(equiv, content);
+        else
+            contentSecurityPolicy()->reportMetaOutsideHead(content);
+    }
 }
 
 void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
 {
     if (equalIgnoringCase(equiv, "content-security-policy"))
-        contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
+        contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce, ContentSecurityPolicy::HeaderSourceMeta);
     else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
-        contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
-    // FIXME: Remove deprecation messages after the next release branch.
-    else if (equalIgnoringCase(equiv, "x-webkit-csp"))
-        UseCounter::countDeprecation(this, UseCounter::PrefixedContentSecurityPolicy);
-    else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
-        UseCounter::countDeprecation(this, UseCounter::PrefixedContentSecurityPolicyReportOnly);
+        contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report, ContentSecurityPolicy::HeaderSourceMeta);
     else
         ASSERT_NOT_REACHED();
 }
@@ -2910,7 +3017,7 @@
         // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
         // intent, we must navigate away from the possibly partially-rendered document to a location that
         // doesn't inherit the parent's SecurityOrigin.
-        frame->navigationScheduler().scheduleLocationChange(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
+        frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
         addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
     }
 }
@@ -2951,7 +3058,7 @@
 #ifndef NDEBUG
         m_didDispatchViewportPropertiesChanged = true;
 #endif
-        page()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
+        frameHost()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
     }
 }
 
@@ -2959,14 +3066,50 @@
 {
     ASSERT(!policy.isNull());
 
-    m_referrerPolicy = ReferrerPolicyDefault;
+    if (equalIgnoringCase(policy, "never")) {
+        setReferrerPolicy(ReferrerPolicyNever);
+    } else if (equalIgnoringCase(policy, "always")) {
+        setReferrerPolicy(ReferrerPolicyAlways);
+    } else if (equalIgnoringCase(policy, "origin")) {
+        setReferrerPolicy(ReferrerPolicyOrigin);
+    } else if (equalIgnoringCase(policy, "default")) {
+        setReferrerPolicy(ReferrerPolicyDefault);
+    } else {
+        addConsoleMessage(RenderingMessageSource, ErrorMessageLevel, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'.");
+        setReferrerPolicy(ReferrerPolicyNever);
+    }
+}
 
-    if (equalIgnoringCase(policy, "never"))
-        m_referrerPolicy = ReferrerPolicyNever;
-    else if (equalIgnoringCase(policy, "always"))
-        m_referrerPolicy = ReferrerPolicyAlways;
-    else if (equalIgnoringCase(policy, "origin"))
-        m_referrerPolicy = ReferrerPolicyOrigin;
+void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
+{
+    // FIXME: Can we adopt the CSP referrer policy merge algorithm? Or does the web rely on being able to modify the referrer policy in-flight?
+    if (m_didSetReferrerPolicy)
+        UseCounter::count(this, UseCounter::ResetReferrerPolicy);
+    m_didSetReferrerPolicy = true;
+
+    m_referrerPolicy = referrerPolicy;
+}
+
+String Document::outgoingReferrer()
+{
+    // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
+    // for why we walk the parent chain for srcdoc documents.
+    Document* referrerDocument = this;
+    if (Frame* frame = m_frame) {
+        while (frame->document()->isSrcdocDocument()) {
+            frame = frame->tree().parent();
+            // Srcdoc documents cannot be top-level documents, by definition,
+            // because they need to be contained in iframes with the srcdoc.
+            ASSERT(frame);
+        }
+        referrerDocument = frame->document();
+    }
+    return referrerDocument->m_url.strippedForUseAsReferrer();
+}
+
+String Document::outgoingOrigin() const
+{
+    return securityOrigin()->toString();
 }
 
 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
@@ -2999,10 +3142,7 @@
     case CDATA_SECTION_NODE:
     case DOCUMENT_FRAGMENT_NODE:
     case DOCUMENT_NODE:
-    case ENTITY_NODE:
-    case NOTATION_NODE:
     case TEXT_NODE:
-    case XPATH_NAMESPACE_NODE:
         return false;
     case COMMENT_NODE:
     case PROCESSING_INSTRUCTION_NODE:
@@ -3053,10 +3193,7 @@
             case CDATA_SECTION_NODE:
             case DOCUMENT_FRAGMENT_NODE:
             case DOCUMENT_NODE:
-            case ENTITY_NODE:
-            case NOTATION_NODE:
             case TEXT_NODE:
-            case XPATH_NAMESPACE_NODE:
                 return false;
             case COMMENT_NODE:
             case PROCESSING_INSTRUCTION_NODE:
@@ -3075,10 +3212,7 @@
         case CDATA_SECTION_NODE:
         case DOCUMENT_FRAGMENT_NODE:
         case DOCUMENT_NODE:
-        case ENTITY_NODE:
-        case NOTATION_NODE:
         case TEXT_NODE:
-        case XPATH_NAMESPACE_NODE:
             return false;
         case COMMENT_NODE:
         case PROCESSING_INSTRUCTION_NODE:
@@ -3110,8 +3244,11 @@
 PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
 {
     DocumentInit init(url());
-    if (isXHTMLDocument())
-        return createXHTML(init.withRegistrationContext(registrationContext()));
+    if (isXMLDocument()) {
+        if (isXHTMLDocument())
+            return XMLDocument::createXHTML(init.withRegistrationContext(registrationContext()));
+        return XMLDocument::create(init);
+    }
     return create(init);
 }
 
@@ -3152,6 +3289,14 @@
         m_mediaQueryMatcher->styleResolverChanged();
 }
 
+void Document::notifyResizeForViewportUnits()
+{
+    if (!hasViewportUnits())
+        return;
+    ensureStyleResolver().notifyResizeForViewportUnits();
+    setNeedsStyleRecalcForViewportUnits();
+}
+
 void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
 {
     // styleResolverChanged() can be invoked during Document destruction.
@@ -3171,41 +3316,25 @@
         return;
 
     m_evaluateMediaQueriesOnStyleRecalc = true;
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
 
     if (updateTime == RecalcStyleImmediately)
         updateStyleIfNeeded();
 }
 
-void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
-{
-    // If we're not in a frame yet any potential child documents won't have a StyleResolver to update.
-    if (!frame())
-        return;
-
-    // Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
-    for (Frame* child = frame()->tree().firstChild(); child; child = child->tree().nextSibling()) {
-        Document* childDocument = child->document();
-        if (childDocument->shouldDisplaySeamlesslyWithParent()) {
-            ASSERT(childDocument->seamlessParentIFrame()->document() == this);
-            childDocument->seamlessParentUpdatedStylesheets();
-        }
-    }
-}
-
 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
 {
     m_hoverNode = newHoverNode;
 }
 
-void Document::setActiveElement(PassRefPtr<Element> newActiveElement)
+void Document::setActiveHoverElement(PassRefPtr<Element> newActiveElement)
 {
     if (!newActiveElement) {
-        m_activeElement.clear();
+        m_activeHoverElement.clear();
         return;
     }
 
-    m_activeElement = newActiveElement;
+    m_activeHoverElement = newActiveElement;
 }
 
 void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
@@ -3245,17 +3374,17 @@
 
 void Document::activeChainNodeDetached(Node* node)
 {
-    if (!m_activeElement)
+    if (!m_activeHoverElement)
         return;
 
-    if (node != m_activeElement && (!m_activeElement->isTextNode() || node != NodeRenderingTraversal::parent(m_activeElement.get())))
+    if (node != m_activeHoverElement && (!m_activeHoverElement->isTextNode() || node != NodeRenderingTraversal::parent(m_activeHoverElement.get())))
         return;
 
     Node* activeNode = NodeRenderingTraversal::parent(node);
     while (activeNode && activeNode->isElementNode() && !activeNode->renderer())
         activeNode = NodeRenderingTraversal::parent(activeNode);
 
-    m_activeElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
+    m_activeHoverElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
 }
 
 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
@@ -3269,8 +3398,10 @@
     setAnnotatedRegionsDirty(false);
 }
 
-bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusDirection direction)
+bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusType type)
 {
+    m_clearFocusedElementTimer.stop();
+
     RefPtr<Element> newFocusedElement = prpNewFocusedElement;
 
     // Make sure newFocusedNode is actually in this document
@@ -3296,28 +3427,27 @@
 
         oldFocusedElement->setFocus(false);
 
-        // Dispatch a change event for text fields or textareas that have been edited
-        if (oldFocusedElement->wasChangedSinceLastFormControlChangeEvent())
-            oldFocusedElement->dispatchFormControlChangeEvent();
-
         // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
-        oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
+        // If page lost focus, blur event will have already been dispatched
+        if (page() && (page()->focusController().isFocused())) {
+            oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
 
-        if (m_focusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            newFocusedElement = 0;
-        }
+            if (m_focusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                newFocusedElement = 0;
+            }
 
-        oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
-        // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
-        // on it, probably when <rdar://problem/8503958> is resolved.
-        oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
+            oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
+            // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
+            // on it, probably when <rdar://problem/8503958> is resolved.
+            oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
 
-        if (m_focusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            newFocusedElement = 0;
+            if (m_focusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                newFocusedElement = 0;
+            }
         }
 
         if (view()) {
@@ -3327,11 +3457,6 @@
             else
                 view()->setFocus(false);
         }
-
-        // Autofill client may have modified the value of newFocusedElement, thus require
-        // a layout update here, otherwise it will assert at newFocusedElement->isFocusable().
-        // See crbug.com/251163.
-        updateLayoutIgnorePendingStylesheets();
     }
 
     if (newFocusedElement && newFocusedElement->isFocusable()) {
@@ -3344,31 +3469,36 @@
         m_focusedElement = newFocusedElement;
 
         // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
-        m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), direction);
+        // If page lost focus, event will be dispatched on page focus, don't duplicate
+        if (page() && (page()->focusController().isFocused())) {
+            m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), type);
 
-        if (m_focusedElement != newFocusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            goto SetFocusedElementDone;
+
+            if (m_focusedElement != newFocusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                goto SetFocusedElementDone;
+            }
+
+            m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
+
+            if (m_focusedElement != newFocusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                goto SetFocusedElementDone;
+            }
+
+            // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
+            // on it, probably when <rdar://problem/8503958> is m.
+            m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get()); // DOM level 2 for compatibility.
+
+            if (m_focusedElement != newFocusedElement) {
+                // handler shifted focus
+                focusChangeBlocked = true;
+                goto SetFocusedElementDone;
+            }
         }
 
-        m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
-
-        if (m_focusedElement != newFocusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            goto SetFocusedElementDone;
-        }
-
-        // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
-        // on it, probably when <rdar://problem/8503958> is m.
-        m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get()); // DOM level 2 for compatibility.
-
-        if (m_focusedElement != newFocusedElement) {
-            // handler shifted focus
-            focusChangeBlocked = true;
-            goto SetFocusedElementDone;
-        }
         m_focusedElement->setFocus(true);
 
         if (m_focusedElement->isRootEditableElement())
@@ -3399,8 +3529,8 @@
             cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
     }
 
-    if (!focusChangeBlocked && page())
-        page()->chrome().focusedNodeChanged(m_focusedElement.get());
+    if (!focusChangeBlocked && frameHost())
+        frameHost()->chrome().focusedNodeChanged(m_focusedElement.get());
 
 SetFocusedElementDone:
     updateStyleIfNeeded();
@@ -3420,8 +3550,6 @@
 
 void Document::registerNodeList(LiveNodeListBase* list)
 {
-    if (list->hasIdNameCache())
-        m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
     m_nodeListCounts[list->invalidationType()]++;
     if (list->isRootedAtDocument())
         m_listsInvalidatedAtDocument.add(list);
@@ -3429,8 +3557,6 @@
 
 void Document::unregisterNodeList(LiveNodeListBase* list)
 {
-    if (list->hasIdNameCache())
-        m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
     m_nodeListCounts[list->invalidationType()]--;
     if (list->isRootedAtDocument()) {
         ASSERT(m_listsInvalidatedAtDocument.contains(list));
@@ -3450,14 +3576,14 @@
     m_nodeIterators.remove(ni);
 }
 
-void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
+void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
 {
     HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
     HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
     for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
         if ((*it)->root() == node) {
             detachNodeIterator(*it);
-            newDocument->attachNodeIterator(*it);
+            newDocument.attachNodeIterator(*it);
         }
     }
 }
@@ -3568,20 +3694,20 @@
     // FIXME: This should update markers for spelling and grammar checking.
 }
 
-void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld)
+void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
 {
     DOMWindow* domWindow = this->domWindow();
     if (!domWindow)
         return;
-    domWindow->setAttributeEventListener(eventType, listener, isolatedWorld);
+    domWindow->setAttributeEventListener(eventType, listener);
 }
 
-EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld)
+EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
 {
     DOMWindow* domWindow = this->domWindow();
     if (!domWindow)
         return 0;
-    return domWindow->getAttributeEventListener(eventType, isolatedWorld);
+    return domWindow->getAttributeEventListener(eventType);
 }
 
 EventQueue* Document::eventQueue() const
@@ -3617,10 +3743,22 @@
     if (event)
         return event.release();
 
-    exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+    exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
     return 0;
 }
 
+PassRefPtr<Event> Document::createEvent(ExceptionState& exceptionState)
+{
+    if (!isSVGDocument()) {
+        exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(1, 0));
+        return 0;
+    }
+
+    UseCounter::count(this, UseCounter::DocumentCreateEventOptionalArgument);
+    // Legacy SVGDocument behavior.
+    return createEvent("undefined", exceptionState);
+}
+
 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
 {
     if (ContextFeatures::mutationEventsEnabled(this))
@@ -3780,7 +3918,7 @@
 
     securityOrigin()->setDomainFromDOM(newDomain);
     if (m_frame)
-        m_frame->script().updateSecurityOrigin();
+        m_frame->script().updateSecurityOrigin(securityOrigin());
 }
 
 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
@@ -3892,7 +4030,7 @@
         U16_NEXT(characters, i, length, c)
         if (c == ':') {
             if (sawColon) {
-                exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
+                exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') contains multiple colons.");
                 return false; // multiple colons: not allowed
             }
             nameStart = true;
@@ -3900,13 +4038,25 @@
             colonPos = i - 1;
         } else if (nameStart) {
             if (!isValidNameStart(c)) {
-                exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+                StringBuilder message;
+                message.appendLiteral("The qualified name provided ('");
+                message.append(qualifiedName);
+                message.appendLiteral("') contains the invalid name-start character '");
+                message.append(c);
+                message.appendLiteral("'.");
+                exceptionState.throwDOMException(InvalidCharacterError, message.toString());
                 return false;
             }
             nameStart = false;
         } else {
             if (!isValidNamePart(c)) {
-                exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+                StringBuilder message;
+                message.appendLiteral("The qualified name provided ('");
+                message.append(qualifiedName);
+                message.appendLiteral("') contains the invalid character '");
+                message.append(c);
+                message.appendLiteral("'.");
+                exceptionState.throwDOMException(InvalidCharacterError, message.toString());
                 return false;
             }
         }
@@ -3918,7 +4068,7 @@
     } else {
         prefix = AtomicString(characters, colonPos);
         if (prefix.isEmpty()) {
-            exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
+            exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty namespace prefix.");
             return false;
         }
         int prefixStart = colonPos + 1;
@@ -3926,7 +4076,7 @@
     }
 
     if (localName.isEmpty()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
+        exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty local name.");
         return false;
     }
 
@@ -3938,7 +4088,7 @@
     unsigned length = qualifiedName.length();
 
     if (!length) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
         return false;
     }
 
@@ -3956,29 +4106,50 @@
     // document's title so that the user doesn't see an incorrectly decoded title
     // in the title bar.
     if (m_titleElement
-        && encoding() != newData.encoding
-        && !m_titleElement->firstElementChild()
+        && encoding() != newData.encoding()
+        && !ElementTraversal::firstWithin(*m_titleElement)
         && encoding() == Latin1Encoding()
         && m_titleElement->textContent().containsOnlyLatin1()) {
 
         CString originalBytes = m_titleElement->textContent().latin1();
-        OwnPtr<TextCodec> codec = newTextCodec(newData.encoding);
+        OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
         String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), true);
         m_titleElement->setTextContent(correctlyDecodedTitle);
     }
 
     m_encodingData = newData;
+
+    // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
+    bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
+    if (shouldUseVisualOrdering != m_visuallyOrdered) {
+        m_visuallyOrdered = shouldUseVisualOrdering;
+        // FIXME: How is possible to not have a renderer here?
+        if (renderView())
+            renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
+        setNeedsStyleRecalc(SubtreeStyleChange);
+    }
 }
 
-KURL Document::completeURL(const String& url, const KURL& baseURLOverride) const
+KURL Document::completeURL(const String& url) const
+{
+    return completeURLWithOverride(url, m_baseURL);
+}
+
+KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
 {
     // Always return a null URL when passed a null string.
     // FIXME: Should we change the KURL constructor to have this behavior?
     // See also [CSS]StyleSheet::completeURL(const String&)
     if (url.isNull())
         return KURL();
+    // This logic is deliberately spread over many statements in an attempt to track down http://crbug.com/312410.
     const KURL* baseURLFromParent = 0;
-    if (baseURLOverride.isEmpty() || baseURLOverride == blankURL()) {
+    bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
+    if (!shouldUseParentBaseURL) {
+        const KURL& aboutBlankURL = blankURL();
+        shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
+    }
+    if (shouldUseParentBaseURL) {
         if (Document* parent = parentDocument())
             baseURLFromParent = &parent->baseURL();
     }
@@ -3988,11 +4159,6 @@
     return KURL(baseURL, url, encoding());
 }
 
-KURL Document::completeURL(const String& url) const
-{
-    return completeURL(url, m_baseURL);
-}
-
 // Support for Javascript execCommand, and related methods
 
 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
@@ -4007,6 +4173,22 @@
 
 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
 {
+    // We don't allow recusrive |execCommand()| to protect against attack code.
+    // Recursive call of |execCommand()| could be happened by moving iframe
+    // with script triggered by insertion, e.g. <iframe src="javascript:...">
+    // <iframe onload="...">. This usage is valid as of the specification
+    // although, it isn't common use case, rather it is used as attack code.
+    static bool inExecCommand = false;
+    if (inExecCommand) {
+        String message = "We don't execute document.execCommand() this time, because it is called recursively.";
+        addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
+        return false;
+    }
+    TemporaryChange<bool> executeScope(inExecCommand, true);
+
+    // Postpone DOM mutation events, which can execute scripts and change
+    // DOM tree against implementation assumption.
+    EventQueueScope eventQueueScope;
     return command(this, commandName, userInterface).execute(value);
 }
 
@@ -4052,7 +4234,7 @@
         return KURL();
 
     RefPtr<HTMLCollection> children = head()->children();
-    for (unsigned i = 0; Node* child = children->item(i); i++) {
+    for (unsigned i = 0; Element* child = children->item(i); i++) {
         if (!child->hasTagName(linkTag))
             continue;
         HTMLLinkElement* linkElement = toHTMLLinkElement(child);
@@ -4104,7 +4286,7 @@
 {
     m_designMode = value;
     for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
-        frame->document()->setNeedsStyleRecalc();
+        frame->document()->setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 Document::InheritedBool Document::getDesignMode() const
@@ -4152,23 +4334,13 @@
 
 PassRefPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
 {
-    return createAttributeNS(nullAtom, name, exceptionState, true);
-}
-
-PassRefPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
-{
     AtomicString prefix, localName;
-    if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
+    if (!parseQualifiedName(name, prefix, localName, exceptionState))
         return 0;
 
-    QualifiedName qName(prefix, localName, namespaceURI);
+    QualifiedName qName(prefix, localName, nullAtom);
 
-    if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
-        return 0;
-    }
-
-    return Attr::create(*this, qName, emptyString());
+    return Attr::create(*this, qName, emptyAtom);
 }
 
 const SVGDocumentExtensions* Document::svgExtensions()
@@ -4190,7 +4362,7 @@
 
 PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
 {
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, type);
+    return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(this, type);
 }
 
 PassRefPtr<HTMLCollection> Document::images()
@@ -4236,17 +4408,17 @@
 
 PassRefPtr<HTMLCollection> Document::all()
 {
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLAllCollection>(this, DocAll);
+    return ensureRareData().ensureNodeLists().addCache<HTMLAllCollection>(this, DocAll);
 }
 
 PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
 {
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLNameCollection>(this, WindowNamedItems, name);
+    return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(this, WindowNamedItems, name);
 }
 
 PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
 {
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLNameCollection>(this, DocumentNamedItems, name);
+    return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(this, DocumentNamedItems, name);
 }
 
 void Document::finishedParsing()
@@ -4280,12 +4452,11 @@
         InspectorInstrumentation::domContentLoadedEventFired(f.get());
     }
 
-    // Schedule dropping of the DocumentSharedObjectPool. We keep it alive for a while after parsing finishes
+    // Schedule dropping of the ElementDataCache. We keep it alive for a while after parsing finishes
     // so that dynamically inserted content can also benefit from sharing optimizations.
-    // Note that we don't refresh the timer on pool access since that could lead to huge caches being kept
+    // Note that we don't refresh the timer on cache access since that could lead to huge caches being kept
     // alive indefinitely by something innocuous like JS setting .innerHTML repeatedly on a timer.
-    static const int timeToKeepSharedObjectPoolAliveAfterParsingFinishedInSeconds = 10;
-    m_sharedObjectPoolClearTimer.startOneShot(timeToKeepSharedObjectPoolAliveAfterParsingFinishedInSeconds);
+    m_elementDataCacheClearTimer.startOneShot(10);
 
     // Parser should have picked up all preloads by now
     m_fetcher->clearPreloads();
@@ -4294,9 +4465,9 @@
         m_import->didFinishParsing();
 }
 
-void Document::sharedObjectPoolClearTimerFired(Timer<Document>*)
+void Document::elementDataCacheClearTimerFired(Timer<Document>*)
 {
-    m_sharedObjectPool.clear();
+    m_elementDataCache.clear();
 }
 
 Vector<IconURL> Document::iconURLs(int iconTypesMask)
@@ -4310,7 +4481,7 @@
     RefPtr<HTMLCollection> children = head() ? head()->children() : 0;
     unsigned length = children ? children->length() : 0;
     for (unsigned i = 0; i < length; i++) {
-        Node* child = children->item(i);
+        Element* child = children->item(i);
         if (!child->hasTagName(linkTag))
             continue;
         HTMLLinkElement* linkElement = toHTMLLinkElement(child);
@@ -4318,10 +4489,8 @@
             continue;
         if (linkElement->href().isEmpty())
             continue;
-#if !ENABLE(TOUCH_ICON_LOADING)
-        if (linkElement->iconType() != Favicon)
+        if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
             continue;
-#endif
 
         IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
         if (linkElement->iconType() == Favicon) {
@@ -4421,10 +4590,6 @@
         setBaseURLOverride(initializer.parentBaseURL());
     }
 
-    // FIXME: What happens if we inherit the security origin? This check may need to be later.
-    // <iframe seamless src="about:blank"> likely won't work as-is.
-    m_mayDisplaySeamlesslyWithParent = initializer.isSeamlessAllowedFor(this);
-
     if (!shouldInheritSecurityOriginFromOwner(m_url))
         return;
 
@@ -4468,9 +4633,10 @@
     // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handler-attributes
     // Also, if the listening node came from other document, which happens on context-less event dispatching,
     // we also need to ask the owner document of the node.
-    if (!m_frame)
+    Frame* frame = executingFrame();
+    if (!frame)
         return false;
-    if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript))
+    if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
         return false;
     if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
         return false;
@@ -4483,11 +4649,12 @@
     // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
     // viewless document but this'll do for now.
     // See http://bugs.webkit.org/show_bug.cgi?id=5727
-    if (!frame() && !import())
+    Frame* frame = executingFrame();
+    if (!frame)
         return false;
-    if (!node->document().frame() && !node->document().import())
+    if (!node->document().executingFrame())
         return false;
-    if (!contextDocument().get()->frame()->script().canExecuteScripts(AboutToExecuteScript))
+    if (!frame->script().canExecuteScripts(AboutToExecuteScript))
         return false;
     return true;
 }
@@ -4502,7 +4669,7 @@
 {
     if (!m_frame)
         return;
-    m_frame->script().updateSecurityOrigin();
+    m_frame->script().updateSecurityOrigin(securityOrigin());
 }
 
 bool Document::isContextThread() const
@@ -4556,7 +4723,7 @@
 
 HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
 {
-    RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, 0).iterator->value;
+    RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, 0).storedValue->value;
     if (!element) {
         element = HTMLCanvasElement::create(*this);
         element->setAccelerationDisabled(true);
@@ -4605,8 +4772,8 @@
         m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
         return;
     }
-    Page* page = this->page();
-    if (!page)
+    FrameHost* host = frameHost();
+    if (!host)
         return;
 
     String messageURL = sourceURL;
@@ -4618,7 +4785,7 @@
                 lineNumber = parser->lineNumber().oneBasedInt();
         }
     }
-    page->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, state, 0);
+    host->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, state, 0);
 }
 
 void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
@@ -4628,8 +4795,8 @@
         return;
     }
 
-    if (Page* page = this->page())
-        page->console().addMessage(source, level, message, String(), 0, 0, 0, 0, requestIdentifier);
+    if (FrameHost* host = frameHost())
+        host->console().addMessage(source, level, message, String(), 0, 0, 0, 0, requestIdentifier);
 }
 
 // FIXME(crbug.com/305497): This should be removed after ExecutionContext-DOMWindow migration.
@@ -4656,6 +4823,8 @@
         m_parser->resumeScheduledTasks();
     if (m_scriptedAnimationController)
         m_scriptedAnimationController->resume();
+
+    MutationObserver::resumeSuspendedObservers();
 }
 
 // FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
@@ -4748,6 +4917,18 @@
         frame()->loader().checkCompleted();
 }
 
+void Document::loadPluginsSoon()
+{
+    // FIXME: Remove this timer once we don't need to compute layout to load plugins.
+    if (!m_pluginLoadingTimer.isActive())
+        m_pluginLoadingTimer.startOneShot(0);
+}
+
+void Document::pluginLoadingTimerFired(Timer<Document>*)
+{
+    updateLayout();
+}
+
 ScriptedAnimationController& Document::ensureScriptedAnimationController()
 {
     if (!m_scriptedAnimationController) {
@@ -4795,55 +4976,75 @@
 
 void Document::didAddTouchEventHandler(Node* handler)
 {
+    // The node should either be in this document, or be the Document node of a child
+    // of this document.
+    ASSERT(&handler->document() == this
+        || (handler->isDocumentNode() && toDocument(handler)->parentDocument() == this));
     if (!m_touchEventTargets.get())
         m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
-    m_touchEventTargets->add(handler);
-    if (Document* parent = parentDocument()) {
-        parent->didAddTouchEventHandler(this);
+    bool isFirstHandler = m_touchEventTargets->isEmpty();
+
+    if (!m_touchEventTargets->add(handler).isNewEntry) {
+        // Just incremented refcount, no real change.
+        // If this is a child document node, then the count should never go above 1.
+        ASSERT(!handler->isDocumentNode() || &handler->document() == this);
         return;
     }
-    if (Page* page = this->page()) {
-        if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
-            scrollingCoordinator->touchEventTargetRectsDidChange(this);
-        if (m_touchEventTargets->size() == 1)
-            page->chrome().client().needTouchEvents(true);
+
+    if (isFirstHandler) {
+        if (Document* parent = parentDocument()) {
+            parent->didAddTouchEventHandler(this);
+        } else {
+            // This is the first touch handler on the whole page.
+            if (FrameHost* frameHost = this->frameHost())
+                frameHost->chrome().client().needTouchEvents(true);
+        }
+    }
+
+    // When we're all done with all frames, ensure touch hit rects are marked as dirty.
+    if (!handler->isDocumentNode() || handler == this) {
+        if (Page* page = this->page()) {
+            if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+                scrollingCoordinator->touchEventTargetRectsDidChange();
+        }
     }
 }
 
-void Document::didRemoveTouchEventHandler(Node* handler)
+void Document::didRemoveTouchEventHandler(Node* handler, bool clearAll)
 {
+    // Note that we can't assert that |handler| is in this document because it might be in
+    // the process of moving out of it.
+    ASSERT(clearAll || m_touchEventTargets->contains(handler));
     if (!m_touchEventTargets.get())
         return;
-    ASSERT(m_touchEventTargets->contains(handler));
-    m_touchEventTargets->remove(handler);
-    if (Document* parent = parentDocument()) {
-        parent->didRemoveTouchEventHandler(this);
-        return;
-    }
 
-    Page* page = this->page();
-    if (!page)
-        return;
-    if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
-        scrollingCoordinator->touchEventTargetRectsDidChange(this);
-    if (m_touchEventTargets->size())
-        return;
-    for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (frame->document() && frame->document()->hasTouchEventHandlers())
+    if (clearAll) {
+        if (!m_touchEventTargets->contains(handler))
+            return;
+        m_touchEventTargets->removeAll(handler);
+    } else {
+        if (!m_touchEventTargets->remove(handler))
+            // Just decremented refcount, no real update.
             return;
     }
-    page->chrome().client().needTouchEvents(false);
-}
 
-void Document::didRemoveEventTargetNode(Node* handler)
-{
-    if (m_touchEventTargets && !m_touchEventTargets->isEmpty()) {
-        if (handler == this)
-            m_touchEventTargets->clear();
-        else
-            m_touchEventTargets->removeAll(handler);
-        if (m_touchEventTargets->isEmpty() && parentDocument())
-            parentDocument()->didRemoveEventTargetNode(this);
+    if (m_touchEventTargets->isEmpty()) {
+        if (Document* parent = parentDocument()) {
+            // This was the last handler in this document, update the parent document too.
+            parent->didRemoveTouchEventHandler(this, clearAll);
+        } else {
+            // We just removed the last touch handler on the whole page.
+            if (FrameHost* frameHost = this->frameHost())
+                frameHost->chrome().client().needTouchEvents(false);
+        }
+    }
+
+    // When we're all done with all frames, ensure touch hit rects are marked as dirty.
+    if (!handler->isDocumentNode() || handler == this) {
+        if (Page* page = this->page()) {
+            if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+                scrollingCoordinator->touchEventTargetRectsDidChange();
+        }
     }
 }
 
@@ -4852,24 +5053,6 @@
     m_lastHandledUserGestureTimestamp = currentTime();
 }
 
-HTMLIFrameElement* Document::seamlessParentIFrame() const
-{
-    if (!shouldDisplaySeamlesslyWithParent())
-        return 0;
-
-    return toHTMLIFrameElement(this->ownerElement());
-}
-
-bool Document::shouldDisplaySeamlesslyWithParent() const
-{
-    if (!RuntimeEnabledFeatures::seamlessIFramesEnabled())
-        return false;
-    HTMLFrameOwnerElement* ownerElement = this->ownerElement();
-    if (!ownerElement)
-        return false;
-    return m_mayDisplaySeamlesslyWithParent && ownerElement->hasTagName(iframeTag) && ownerElement->fastHasAttribute(seamlessAttr);
-}
-
 DocumentLoader* Document::loader() const
 {
     if (!m_frame)
@@ -4980,7 +5163,7 @@
         innerElementInDocument = innerElementInDocument->document().ownerElement();
     }
 
-    Element* oldActiveElement = activeElement();
+    Element* oldActiveElement = activeHoverElement();
     if (oldActiveElement && !request.active()) {
         // We are clearing the :active chain because the mouse has been released.
         for (RenderObject* curr = oldActiveElement->renderer(); curr; curr = curr->parent()) {
@@ -4990,7 +5173,7 @@
                 m_userActionElements.setInActiveChain(curr->node(), false);
             }
         }
-        setActiveElement(0);
+        setActiveHoverElement(0);
     } else {
         Element* newActiveElement = innerElementInDocument;
         if (!oldActiveElement && newActiveElement && request.active() && !request.touchMove()) {
@@ -5001,12 +5184,12 @@
                     m_userActionElements.setInActiveChain(curr->node(), true);
             }
 
-            setActiveElement(newActiveElement);
+            setActiveHoverElement(newActiveElement);
         }
     }
     // If the mouse has just been pressed, set :active on the chain. Those (and only those)
     // nodes should remain :active until the mouse is released.
-    bool allowActiveChanges = !oldActiveElement && activeElement();
+    bool allowActiveChanges = !oldActiveElement && activeHoverElement();
 
     // If the mouse is down and if this is a mouse move event, we want to restrict changes in
     // :hover/:active to only apply to elements that are in the :active chain that we froze
@@ -5015,11 +5198,6 @@
 
     RefPtr<Node> oldHoverNode = hoverNode();
 
-    // A touch release does not set a new hover target; setting the element we're working with to 0
-    // will clear the chain of hovered elements all the way to the top of the tree.
-    if (request.touchRelease())
-        innerElementInDocument = 0;
-
     // Check to see if the hovered node has changed.
     // If it hasn't, we do not need to do anything.
     Node* newHoverNode = innerElementInDocument;
@@ -5128,23 +5306,26 @@
         return Locale::defaultLocale();
     LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
     if (result.isNewEntry)
-        result.iterator->value = Locale::create(localeKey);
-    return *(result.iterator->value);
+        result.storedValue->value = Locale::create(localeKey);
+    return *(result.storedValue->value);
 }
 
 Document& Document::ensureTemplateDocument()
 {
-    if (const Document* document = templateDocument())
-        return *const_cast<Document*>(document);
+    if (isTemplateDocument())
+        return *this;
+
+    if (m_templateDocument)
+        return *m_templateDocument;
 
     if (isHTMLDocument()) {
-        DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL());
+        DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
         m_templateDocument = HTMLDocument::create(init);
     } else {
         m_templateDocument = Document::create(DocumentInit(blankURL()));
     }
 
-    m_templateDocument->setTemplateDocumentHost(this); // balanced in dtor.
+    m_templateDocument->m_templateDocumentHost = this; // balanced in dtor.
 
     return *m_templateDocument.get();
 }
@@ -5220,4 +5401,50 @@
     return m_fastTextAutosizer.get();
 }
 
+void Document::setAutofocusElement(Element* element)
+{
+    if (!element) {
+        m_autofocusElement = 0;
+        return;
+    }
+    if (m_hasAutofocused)
+        return;
+    m_hasAutofocused = true;
+    ASSERT(!m_autofocusElement);
+    m_autofocusElement = element;
+    m_taskRunner->postTask(AutofocusTask::create());
+}
+
+Element* Document::activeElement() const
+{
+    if (Element* element = treeScope().adjustedFocusedElement())
+        return element;
+    return body();
+}
+
+bool Document::hasFocus() const
+{
+    Page* page = this->page();
+    if (!page)
+        return false;
+    if (!page->focusController().isActive() || !page->focusController().isFocused())
+        return false;
+    if (Frame* focusedFrame = page->focusController().focusedFrame()) {
+        if (focusedFrame->tree().isDescendantOf(frame()))
+            return true;
+    }
+    return false;
+}
+
+// FIXME: Remove this code once we have input routing in the browser
+// process. See http://crbug.com/339659.
+void Document::defaultEventHandler(Event* event)
+{
+    if (frame() && frame()->remotePlatformLayer()) {
+        frame()->chromeClient().forwardInputEvent(this, event);
+        return;
+    }
+    Node::defaultEventHandler(event);
+}
+
 } // namespace WebCore
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index a9a6446..43ed676 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -47,10 +47,11 @@
 #include "core/dom/ViewportDescription.h"
 #include "core/dom/custom/CustomElement.h"
 #include "core/html/CollectionType.h"
-#include "core/page/FocusDirection.h"
+#include "core/page/FocusType.h"
 #include "core/page/PageVisibilityState.h"
 #include "core/rendering/HitTestRequest.h"
 #include "platform/Timer.h"
+#include "platform/weborigin/KURL.h"
 #include "platform/weborigin/ReferrerPolicy.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
@@ -76,11 +77,8 @@
 class ContextFeatures;
 class CustomElementRegistrationContext;
 class DOMImplementation;
-class DOMNamedFlowCollection;
-class DOMSecurityPolicy;
 class DOMSelection;
 class DOMWindow;
-class DOMWrapperWorld;
 class Database;
 class DatabaseThread;
 class DocumentFragment;
@@ -89,19 +87,20 @@
 class DocumentLoader;
 class DocumentMarkerController;
 class DocumentParser;
-class DocumentSharedObjectPool;
 class DocumentTimeline;
 class DocumentType;
 class Element;
+class ElementDataCache;
 class Event;
 class EventListener;
 class ExceptionState;
-class MainThreadTaskRunner;
 class FastTextAutosizer;
 class FloatQuad;
 class FloatRect;
+class FontFaceSet;
 class FormController;
 class Frame;
+class FrameHost;
 class FrameView;
 class HTMLAllCollection;
 class HTMLCanvasElement;
@@ -125,10 +124,10 @@
 class LiveNodeListBase;
 class Locale;
 class Location;
+class MainThreadTaskRunner;
 class MediaQueryList;
 class MediaQueryMatcher;
 class MouseEventWithHitTestResults;
-class NamedFlowCollection;
 class NodeFilter;
 class NodeIterator;
 class Page;
@@ -140,6 +139,7 @@
 class RequestAnimationFrameCallback;
 class ResourceFetcher;
 class SVGDocumentExtensions;
+class SVGUseElement;
 class ScriptElementData;
 class ScriptResource;
 class ScriptRunner;
@@ -166,8 +166,6 @@
 
 struct AnnotatedRegionValue;
 
-class FontFaceSet;
-
 typedef int ExceptionCode;
 
 enum RecalcStyleTime {
@@ -190,7 +188,6 @@
     InvalidateOnForAttrChange,
     InvalidateForFormControls,
     InvalidateOnHRefAttrChange,
-    InvalidateOnItemAttrChange,
     InvalidateOnAnyAttrChange,
 };
 const int numNodeListInvalidationTypes = InvalidateOnAnyAttrChange + 1;
@@ -205,10 +202,31 @@
     PluginDocumentClass = 1 << 3,
     MediaDocumentClass = 1 << 4,
     SVGDocumentClass = 1 << 5,
+    XMLDocumentClass = 1 << 6,
 };
 
 typedef unsigned char DocumentClassFlags;
 
+class Document;
+
+class DocumentVisibilityObserver {
+public:
+    DocumentVisibilityObserver(Document&);
+    virtual ~DocumentVisibilityObserver();
+
+    virtual void didChangeVisibilityState(PageVisibilityState) = 0;
+
+    // Classes that inherit Node and DocumentVisibilityObserver must have a
+    // virtual override of Node::didMoveToNewDocument that calls
+    // DocumentVisibilityObserver::setDocument
+    void setObservedDocument(Document&);
+
+private:
+    void registerObserver(Document&);
+    void unregisterObserver();
+    Document* m_document;
+};
+
 class Document : public ContainerNode, public TreeScope, public SecurityContext, public ExecutionContext, public ExecutionContextClient
     , public DocumentSupplementable, public LifecycleContext<Document> {
 public:
@@ -216,10 +234,6 @@
     {
         return adoptRef(new Document(initializer));
     }
-    static PassRefPtr<Document> createXHTML(const DocumentInit& initializer = DocumentInit())
-    {
-        return adoptRef(new Document(initializer, XHTMLDocumentClass));
-    }
     virtual ~Document();
 
     MediaQueryMatcher& mediaQueryMatcher();
@@ -232,10 +246,14 @@
     using SecurityContext::contentSecurityPolicy;
     using ExecutionContextClient::addConsoleMessage;
 
-    virtual bool canContainRangeEndPoint() const { return true; }
+    virtual bool canContainRangeEndPoint() const OVERRIDE { return true; }
 
     SelectorQueryCache& selectorQueryCache();
 
+    // Focus Management.
+    Element* activeElement() const;
+    bool hasFocus() const;
+
     // DOM methods & attributes for Document
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
@@ -268,9 +286,12 @@
 #endif
     bool hasLegacyViewportTag() const { return m_legacyViewportDescription.isLegacyViewportType(); }
 
-    void setReferrerPolicy(ReferrerPolicy referrerPolicy) { m_referrerPolicy = referrerPolicy; }
+    void setReferrerPolicy(ReferrerPolicy);
     ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
 
+    String outgoingReferrer();
+    String outgoingOrigin() const;
+
     void setDoctype(PassRefPtr<DocumentType>);
     DocumentType* doctype() const { return m_docType.get(); }
 
@@ -292,16 +313,11 @@
     PassRefPtr<CDATASection> createCDATASection(const String& data, ExceptionState&);
     PassRefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionState&);
     PassRefPtr<Attr> createAttribute(const AtomicString& name, ExceptionState&);
-    PassRefPtr<Attr> createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&, bool shouldIgnoreNamespaceChecks = false);
     PassRefPtr<Node> importNode(Node* importedNode, ExceptionState& ec) { return importNode(importedNode, true, ec); }
     PassRefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionState&);
     PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&);
     PassRefPtr<Element> createElement(const QualifiedName&, bool createdByParser);
 
-    PassRefPtr<DOMNamedFlowCollection> webkitGetNamedFlows();
-
-    NamedFlowCollection* namedFlows();
-
     bool regionBasedColumnsEnabled() const;
 
     /**
@@ -352,15 +368,11 @@
     void setXMLStandalone(bool, ExceptionState&);
     void setHasXMLDeclaration(bool hasXMLDeclaration) { m_hasXMLDeclaration = hasXMLDeclaration ? 1 : 0; }
 
-    String documentURI() const { return m_documentURI; }
-
-    virtual KURL baseURI() const;
+    virtual KURL baseURI() const OVERRIDE FINAL;
 
     String visibilityState() const;
     bool hidden() const;
-    void dispatchVisibilityStateChangeEvent();
-
-    DOMSecurityPolicy* securityPolicy();
+    void didChangeVisibilityState();
 
     PassRefPtr<Node> adoptNode(PassRefPtr<Node> source, ExceptionState&);
 
@@ -379,6 +391,7 @@
 
     bool isHTMLDocument() const { return m_documentClasses & HTMLDocumentClass; }
     bool isXHTMLDocument() const { return m_documentClasses & XHTMLDocumentClass; }
+    bool isXMLDocument() const { return m_documentClasses & XMLDocumentClass; }
     bool isImageDocument() const { return m_documentClasses & ImageDocumentClass; }
     bool isSVGDocument() const { return m_documentClasses & SVGDocumentClass; }
     bool isPluginDocument() const { return m_documentClasses & PluginDocumentClass; }
@@ -422,6 +435,9 @@
     void modifiedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
     void changedSelectorWatch() { styleResolverChanged(RecalcStyleDeferred); }
 
+    void scheduleUseShadowTreeUpdate(SVGUseElement&);
+    void unscheduleUseShadowTreeUpdate(SVGUseElement&);
+
     void evaluateMediaQueryList();
 
     // Never returns 0.
@@ -431,6 +447,7 @@
 
     FrameView* view() const; // can be null
     Frame* frame() const { return m_frame; } // can be null
+    FrameHost* frameHost() const; // can be null
     Page* page() const; // can be null
     Settings* settings() const; // can be null
 
@@ -447,12 +464,10 @@
     PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
 
     // Special support for editing
-    PassRefPtr<CSSStyleDeclaration> createCSSStyleDeclaration();
     PassRefPtr<Text> createEditingTextNode(const String&);
 
-    void setStyleDependentState(RenderStyle* documentStyle);
-    void inheritHtmlAndBodyElementStyles(StyleRecalcChange);
-    void recalcStyle(StyleRecalcChange);
+    void setupFontBuilder(RenderStyle* documentStyle);
+
     void updateStyleIfNeeded();
     void updateStyleForNodeIfNeeded(Node*);
     void updateLayout();
@@ -489,7 +504,6 @@
     void clearAXObjectCache();
 
     // to get visually ordered hebrew and arabic pages right
-    void setVisuallyOrdered();
     bool visuallyOrdered() const { return m_visuallyOrdered; }
 
     DocumentLoader* loader() const;
@@ -534,14 +548,14 @@
     void setBaseURLOverride(const KURL&);
     const KURL& baseURLOverride() const { return m_baseURLOverride; }
     const KURL& baseElementURL() const { return m_baseElementURL; }
-    const String& baseTarget() const { return m_baseTarget; }
+    const AtomicString& baseTarget() const { return m_baseTarget; }
     void processBaseElement();
 
     KURL completeURL(const String&) const;
-    KURL completeURL(const String&, const KURL& baseURLOverride) const;
+    KURL completeURLWithOverride(const String&, const KURL& baseURLOverride) const;
 
-    virtual String userAgent(const KURL&) const;
-    virtual void disableEval(const String& errorMessage);
+    virtual String userAgent(const KURL&) const OVERRIDE FINAL;
+    virtual void disableEval(const String& errorMessage) OVERRIDE FINAL;
 
     bool canNavigate(Frame* targetFrame);
     Frame* findUnsafeParentScrollPropagationBoundary();
@@ -581,8 +595,7 @@
     bool isLoadCompleted();
 
     void setParsing(bool);
-    bool parsing() const { return m_bParsing; }
-    int minimumLayoutDelay();
+    bool parsing() const { return m_isParsing; }
 
     bool shouldScheduleLayout();
     bool shouldParserYieldAgressivelyBeforeScriptExecution();
@@ -601,18 +614,19 @@
     String selectedStylesheetSet() const;
     void setSelectedStylesheetSet(const String&);
 
-    bool setFocusedElement(PassRefPtr<Element>, FocusDirection = FocusDirectionNone);
+    bool setFocusedElement(PassRefPtr<Element>, FocusType = FocusTypeNone);
     Element* focusedElement() const { return m_focusedElement.get(); }
     UserActionElementSet& userActionElements()  { return m_userActionElements; }
     const UserActionElementSet& userActionElements() const { return m_userActionElements; }
     void setNeedsFocusedElementCheck();
-    void didRunCheckFocusedElementTask() { m_didPostCheckFocusedElementTask = false; }
+    void setAutofocusElement(Element*);
+    Element* autofocusElement() const { return m_autofocusElement.get(); }
 
     void setHoverNode(PassRefPtr<Node>);
     Node* hoverNode() const { return m_hoverNode.get(); }
 
-    void setActiveElement(PassRefPtr<Element>);
-    Element* activeElement() const { return m_activeElement.get(); }
+    void setActiveHoverElement(PassRefPtr<Element>);
+    Element* activeHoverElement() const { return m_activeHoverElement.get(); }
 
     void removeFocusedElementOfSubtree(Node*, bool amongChildrenOnly = false);
     void hoveredNodeDetached(Node*);
@@ -625,19 +639,18 @@
     Element* cssTarget() const { return m_cssTarget; }
 
     void scheduleStyleRecalc();
-    void unscheduleStyleRecalc();
-    bool hasPendingStyleRecalc() const;
     bool hasPendingForcedStyleRecalc() const;
-    void styleRecalcTimerFired(Timer<Document>*);
 
     void registerNodeList(LiveNodeListBase*);
     void unregisterNodeList(LiveNodeListBase*);
+    void incrementNodeListWithIdNameCacheCount();
+    void decrementNodeListWithIdNameCacheCount();
     bool shouldInvalidateNodeListCaches(const QualifiedName* attrName = 0) const;
     void invalidateNodeListCaches(const QualifiedName* attrName);
 
     void attachNodeIterator(NodeIterator*);
     void detachNodeIterator(NodeIterator*);
-    void moveNodeIteratorsToNewDocument(Node*, Document*);
+    void moveNodeIteratorsToNewDocument(Node&, Document&);
 
     void attachRange(Range*);
     void detachRange(Range*);
@@ -658,10 +671,11 @@
     DOMWindow* domWindow() const { return m_domWindow; }
 
     // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
-    void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, DOMWrapperWorld* isolatedWorld = 0);
-    EventListener* getWindowAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld);
+    void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>);
+    EventListener* getWindowAttributeEventListener(const AtomicString& eventType);
 
     PassRefPtr<Event> createEvent(const String& eventType, ExceptionState&);
+    PassRefPtr<Event> createEvent(ExceptionState&);
 
     // keep track of what types of event listeners are registered, so we don't
     // dispatch events unnecessarily
@@ -702,9 +716,9 @@
      *
      * @param equiv The http header name (value of the meta tag's "equiv" attribute)
      * @param content The header value (value of the meta tag's "content" attribute)
+     * @param inDocumentHeadElement Is the element in the document's <head> element?
      */
-    void processHttpEquiv(const AtomicString& equiv, const AtomicString& content);
-    void processViewport(const String& features, ViewportDescription::Type origin);
+    void processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement);
     void updateViewportDescription();
     void processReferrerPolicy(const String& policy);
 
@@ -712,9 +726,6 @@
     // Returns 0 if this is the top level document.
     HTMLFrameOwnerElement* ownerElement() const;
 
-    HTMLIFrameElement* seamlessParentIFrame() const;
-    bool shouldDisplaySeamlesslyWithParent() const;
-
     String title() const { return m_title; }
     void setTitle(const String&);
 
@@ -766,6 +777,12 @@
 
     HTMLHeadElement* head();
 
+    // Decide which element is to define the viewport's overflow policy. If |rootStyle| is set, use
+    // that as the style for the root element, rather than obtaining it on our own. The reason for
+    // this is that style may not have been associated with the elements yet - in which case it may
+    // have been calculated on the fly (without associating it with the actual element) somewhere.
+    Element* viewportDefiningElement(RenderStyle* rootStyle = 0) const;
+
     DocumentMarkerController* markers() const { return m_markers.get(); }
 
     bool directionSetOnDocumentElement() const { return m_directionSetOnDocumentElement; }
@@ -805,7 +822,7 @@
     void setTransformSource(PassOwnPtr<TransformSource>);
     TransformSource* transformSource() const { return m_transformSource.get(); }
 
-    void incDOMTreeVersion() { m_domTreeVersion = ++s_globalTreeVersion; }
+    void incDOMTreeVersion() { ASSERT(!inStyleRecalc()); m_domTreeVersion = ++s_globalTreeVersion; }
     uint64_t domTreeVersion() const { return m_domTreeVersion; }
 
     enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
@@ -833,19 +850,19 @@
     // FIXME(crbug.com/305497): This should be removed once DOMWindow is an ExecutionContext.
     virtual void postTask(PassOwnPtr<ExecutionContextTask>) OVERRIDE; // Executes the task on context's thread asynchronously.
 
-    virtual void tasksWereSuspended() OVERRIDE;
-    virtual void tasksWereResumed() OVERRIDE;
-    virtual void suspendScheduledTasks() OVERRIDE;
-    virtual void resumeScheduledTasks() OVERRIDE;
-    virtual bool tasksNeedSuspension() OVERRIDE;
+    virtual void tasksWereSuspended() OVERRIDE FINAL;
+    virtual void tasksWereResumed() OVERRIDE FINAL;
+    virtual void suspendScheduledTasks() OVERRIDE FINAL;
+    virtual void resumeScheduledTasks() OVERRIDE FINAL;
+    virtual bool tasksNeedSuspension() OVERRIDE FINAL;
 
     void finishedParsing();
 
     void setEncodingData(const DocumentEncodingData& newData);
-    const WTF::TextEncoding& encoding() const { return m_encodingData.encoding; }
+    const WTF::TextEncoding& encoding() const { return m_encodingData.encoding(); }
 
-    bool encodingWasDetectedHeuristically() const { return m_encodingData.wasDetectedHeuristically; }
-    bool sawDecodingError() const { return m_encodingData.sawDecodingError; }
+    bool encodingWasDetectedHeuristically() const { return m_encodingData.wasDetectedHeuristically(); }
+    bool sawDecodingError() const { return m_encodingData.sawDecodingError(); }
 
     void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
     bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
@@ -854,7 +871,7 @@
     const Vector<AnnotatedRegionValue>& annotatedRegions() const;
     void setAnnotatedRegions(const Vector<AnnotatedRegionValue>&);
 
-    virtual void removeAllEventListeners();
+    virtual void removeAllEventListeners() OVERRIDE FINAL;
 
     const SVGDocumentExtensions* svgExtensions();
     SVGDocumentExtensions* accessSVGExtensions();
@@ -882,12 +899,13 @@
     bool loadEventStillNeeded() const { return m_loadEventProgress == LoadEventNotRun; }
     bool processingLoadEvent() const { return m_loadEventProgress == LoadEventInProgress; }
     bool loadEventFinished() const { return m_loadEventProgress >= LoadEventCompleted; }
+    bool unloadStarted() const { return m_loadEventProgress >= PageHideInProgress; }
 
     void setContainsPlugins() { m_containsPlugins = true; }
     bool containsPlugins() const { return m_containsPlugins; }
 
-    virtual bool isContextThread() const;
-    virtual bool isJSExecutionForbidden() const { return false; }
+    virtual bool isContextThread() const OVERRIDE FINAL;
+    virtual bool isJSExecutionForbidden() const OVERRIDE FINAL { return false; }
 
     bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
     void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
@@ -896,8 +914,6 @@
     void enqueueScrollEventForNode(Node*);
     void enqueueAnimationFrameEvent(PassRefPtr<Event>);
 
-    const QualifiedName& idAttributeName() const { return m_idAttributeName; }
-
     bool hasFullscreenElementStack() const { return m_hasFullscreenElementStack; }
     void setHasFullscreenElementStack() { m_hasFullscreenElementStack = true; }
 
@@ -908,6 +924,7 @@
     void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
     void decrementLoadEventDelayCount();
     bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
+    void loadPluginsSoon();
 
     PassRefPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const;
     PassRefPtr<TouchList> createTouchList(Vector<RefPtr<Touch> >&) const;
@@ -918,8 +935,8 @@
     void cancelAnimationFrame(int id);
     void serviceScriptedAnimations(double monotonicAnimationStartTime);
 
-    virtual EventTarget* errorEventTarget();
-    virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>);
+    virtual EventTarget* errorEventTarget() OVERRIDE FINAL;
+    virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) OVERRIDE FINAL;
 
     void initDNSPrefetch();
 
@@ -928,10 +945,16 @@
 
     bool hasTouchEventHandlers() const { return (m_touchEventTargets.get()) ? m_touchEventTargets->size() : false; }
 
+    // Called when a single touch event handler has been added or removed for a node.
+    // The Node should always be in this Document, except for child Documents which report
+    // themselves to their parent exactly once if they have any touch handlers.
+    // Handlers added/removed from the DOMWindow are reported as the Document.
     void didAddTouchEventHandler(Node*);
-    void didRemoveTouchEventHandler(Node*);
+    void didRemoveTouchEventHandler(Node* handler) { didRemoveTouchEventHandler(handler, false); }
 
-    void didRemoveEventTargetNode(Node*);
+    // Called whenever all touch event handlers have been removed for a node (such as when the
+    // node itself is being removed from the document).
+    void didClearTouchEventHandlers(Node* handler) { didRemoveTouchEventHandler(handler, true); }
 
     const TouchEventTargetSet* touchEventTargets() const { return m_touchEventTargets.get(); }
 
@@ -966,14 +989,13 @@
     void setContextFeatures(PassRefPtr<ContextFeatures>);
     ContextFeatures* contextFeatures() const { return m_contextFeatures.get(); }
 
-    DocumentSharedObjectPool* sharedObjectPool() { return m_sharedObjectPool.get(); }
+    ElementDataCache* elementDataCache() { return m_elementDataCache.get(); }
 
     void didRemoveAllPendingStylesheet();
     void setNeedsNotifyRemoveAllPendingStylesheet() { m_needsNotifyRemoveAllPendingStylesheet = true; }
     void clearStyleResolver();
-    void notifySeamlessChildDocumentsOfStylesheetUpdate() const;
 
-    bool inStyleRecalc() { return m_inStyleRecalc; }
+    bool inStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::InStyleRecalc; }
 
     // Return a Locale for the default locale if the argument is null or empty.
     Locale& getCachedLocale(const AtomicString& locale = nullAtom);
@@ -988,21 +1010,23 @@
     const Vector<RefPtr<Element> >& topLayerElements() const { return m_topLayerElements; }
     HTMLDialogElement* activeModalDialog() const;
 
-    const Document* templateDocument() const;
+    // A non-null m_templateDocumentHost implies that |this| was created by ensureTemplateDocument().
+    bool isTemplateDocument() const { return !!m_templateDocumentHost; }
     Document& ensureTemplateDocument();
-    void setTemplateDocumentHost(Document* templateDocumentHost) { m_templateDocumentHost = templateDocumentHost; }
     Document* templateDocumentHost() { return m_templateDocumentHost; }
 
     void didAssociateFormControl(Element*);
 
     void addConsoleMessageWithRequestIdentifier(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier);
 
-    virtual DOMWindow* executingWindow() OVERRIDE { return domWindow(); }
-    virtual void userEventWasHandled() OVERRIDE { resetLastHandledUserGestureTimestamp(); }
+    virtual DOMWindow* executingWindow() OVERRIDE FINAL;
+    virtual void userEventWasHandled() OVERRIDE FINAL { resetLastHandledUserGestureTimestamp(); }
+    Frame* executingFrame();
 
     DocumentLifecycleNotifier& lifecycleNotifier();
-    bool isActive() const { return m_lifecyle.state() == DocumentLifecycle::Active; }
-    bool isStopped() const { return m_lifecyle.state() == DocumentLifecycle::Stopped; }
+    DocumentLifecycle& lifecycle() { return m_lifecycle; }
+    bool isActive() const { return m_lifecycle.isActive(); }
+    bool isStopped() const { return m_lifecycle.state() == DocumentLifecycle::Stopped; }
 
     enum HttpRefreshType {
         HttpRefreshFromHeader,
@@ -1013,10 +1037,21 @@
     void updateSecurityOrigin(PassRefPtr<SecurityOrigin>);
     PassOwnPtr<LifecycleNotifier<Document> > createLifecycleNotifier();
 
+    void setHasViewportUnits() { m_hasViewportUnits = true; }
+    bool hasViewportUnits() const { return m_hasViewportUnits; }
+    void notifyResizeForViewportUnits();
+
+    void registerVisibilityObserver(DocumentVisibilityObserver*);
+    void unregisterVisibilityObserver(DocumentVisibilityObserver*);
+
+    // FIXME: Remove this method once we have input routing in the browser
+    // process. See http://crbug.com/339659.
+    virtual void defaultEventHandler(Event*) OVERRIDE;
+
 protected:
     Document(const DocumentInit&, DocumentClassFlags = DefaultDocumentClass);
 
-    virtual void didUpdateSecurityOrigin() OVERRIDE;
+    virtual void didUpdateSecurityOrigin() OVERRIDE FINAL;
 
     void clearXMLVersion() { m_xmlVersion = String(); }
 
@@ -1029,48 +1064,55 @@
     friend class IgnoreDestructiveWriteCountIncrementer;
 
     ScriptedAnimationController& ensureScriptedAnimationController();
-    virtual SecurityContext& securityContext() OVERRIDE { return *this; }
-    virtual EventQueue* eventQueue() const FINAL;
+    virtual SecurityContext& securityContext() OVERRIDE FINAL { return *this; }
+    virtual EventQueue* eventQueue() const OVERRIDE FINAL;
+
+    void inheritHtmlAndBodyElementStyles(StyleRecalcChange);
 
     void updateDistributionIfNeeded();
+    void updateStyleInvalidationIfNeeded();
+    void updateUseShadowTreesIfNeeded();
+
+    void updateStyle(StyleRecalcChange);
 
     void detachParser();
 
-    virtual bool isDocument() const OVERRIDE { return true; }
+    virtual bool isDocument() const OVERRIDE FINAL { return true; }
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual String nodeName() const;
-    virtual NodeType nodeType() const;
-    virtual bool childTypeAllowed(NodeType) const;
-    virtual PassRefPtr<Node> cloneNode(bool deep = true);
+    virtual String nodeName() const OVERRIDE FINAL;
+    virtual NodeType nodeType() const OVERRIDE FINAL;
+    virtual bool childTypeAllowed(NodeType) const OVERRIDE FINAL;
+    virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE FINAL;
     void cloneDataFromDocument(const Document&);
 
-    virtual void refExecutionContext() { ref(); }
-    virtual void derefExecutionContext() { deref(); }
+    virtual void refExecutionContext() OVERRIDE FINAL { ref(); }
+    virtual void derefExecutionContext() OVERRIDE FINAL { deref(); }
 
-    virtual const KURL& virtualURL() const; // Same as url(), but needed for ExecutionContext to implement it without a performance loss for direct calls.
-    virtual KURL virtualCompleteURL(const String&) const; // Same as completeURL() for the same reason as above.
+    virtual const KURL& virtualURL() const OVERRIDE FINAL; // Same as url(), but needed for ExecutionContext to implement it without a performance loss for direct calls.
+    virtual KURL virtualCompleteURL(const String&) const OVERRIDE FINAL; // Same as completeURL() for the same reason as above.
 
-    virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE;
-    virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*);
+    virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE FINAL;
+    virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*) OVERRIDE FINAL;
     void internalAddMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
 
-    virtual double timerAlignmentInterval() const;
+    virtual double timerAlignmentInterval() const OVERRIDE FINAL;
 
     void updateTitle(const String&);
     void updateFocusAppearanceTimerFired(Timer<Document>*);
     void updateBaseURL();
 
-    void executeScriptsWaitingForResourcesIfNeeded();
+    bool hasPendingStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::StyleRecalcPending; }
 
-    void seamlessParentUpdatedStylesheets();
+    void executeScriptsWaitingForResourcesIfNeeded();
 
     void recalcStyleForLayoutIgnoringPendingStylesheets();
 
     PassRefPtr<NodeList> handleZeroPadding(const HitTestRequest&, HitTestResult&) const;
 
     void loadEventDelayTimerFired(Timer<Document>*);
+    void pluginLoadingTimerFired(Timer<Document>*);
 
     PageVisibilityState pageVisibilityState() const;
 
@@ -1085,7 +1127,9 @@
     void addMutationEventListenerTypeIfEnabled(ListenerType);
 
     void didAssociateFormControlsTimerFired(Timer<Document>*);
-    void styleResolverThrowawayTimerFired(Timer<Document>*);
+
+    void clearFocusedElementSoon();
+    void clearFocusedElementTimerFired(Timer<Document>*);
 
     void processHttpEquivDefaultStyle(const AtomicString& content);
     void processHttpEquivRefresh(const AtomicString& content);
@@ -1093,7 +1137,13 @@
     void processHttpEquivXFrameOptions(const AtomicString& content);
     void processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content);
 
-    DocumentLifecycle m_lifecyle;
+    void didRemoveTouchEventHandler(Node*, bool clearAll);
+
+    // Returns true if Document::recalcStyle() needs to be run.
+    bool shouldCallRecalcStyleForDocument();
+    bool shouldScheduleStyleRecalc();
+
+    DocumentLifecycle m_lifecycle;
 
     bool m_hasNodesWithPlaceholderStyle;
     bool m_needsNotifyRemoveAllPendingStylesheet;
@@ -1122,14 +1172,7 @@
     KURL m_baseElementURL; // The URL set by the <base> element.
     KURL m_cookieURL; // The URL to use for cookie access.
 
-    // Document.documentURI:
-    // Although URL-like, Document.documentURI can actually be set to any
-    // string by content.  Document.documentURI affects m_baseURL unless the
-    // document contains a <base> element, in which case the <base> element
-    // takes precedence.
-    String m_documentURI;
-
-    String m_baseTarget;
+    AtomicString m_baseTarget;
 
     RefPtr<DocumentType> m_docType;
     OwnPtr<DOMImplementation> m_implementation;
@@ -1142,10 +1185,12 @@
     CompatibilityMode m_compatibilityMode;
     bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
 
-    bool m_didPostCheckFocusedElementTask;
+    bool m_hasAutofocused;
+    Timer<Document> m_clearFocusedElementTimer;
+    RefPtr<Element> m_autofocusElement;
     RefPtr<Element> m_focusedElement;
     RefPtr<Node> m_hoverNode;
-    RefPtr<Element> m_activeElement;
+    RefPtr<Element> m_activeHoverElement;
     RefPtr<Element> m_documentElement;
     UserActionElementSet m_userActionElements;
 
@@ -1167,13 +1212,9 @@
     TextLinkColors m_textLinkColors;
     const OwnPtr<VisitedLinkState> m_visitedLinkState;
 
-    bool m_loadingSheet;
     bool m_visuallyOrdered;
     ReadyState m_readyState;
-    bool m_bParsing;
-
-    Timer<Document> m_styleRecalcTimer;
-    bool m_inStyleRecalc;
+    bool m_isParsing;
 
     bool m_gotoAnchorNeededAfterStylesheetsLoad;
     bool m_isDNSPrefetchEnabled;
@@ -1200,7 +1241,6 @@
     LoadEventProgress m_loadEventProgress;
 
     double m_startTime;
-    bool m_overMinimumLayoutThreshold;
 
     OwnPtr<ScriptRunner> m_scriptRunner;
 
@@ -1241,27 +1281,24 @@
     bool m_sawElementsInKnownNamespaces;
     bool m_isSrcdocDocument;
     bool m_isMobileDocument;
-    // Set in Document::initSecurityContext() at Document creation, per:
-    // http://www.whatwg.org/specs/web-apps/current-work/#attr-iframe-seamless
-    bool m_mayDisplaySeamlesslyWithParent;
 
     RenderView* m_renderView;
 
     WeakPtrFactory<Document> m_weakFactory;
     WeakPtr<Document> m_contextDocument;
 
-    QualifiedName m_idAttributeName;
-
     bool m_hasFullscreenElementStack; // For early return in FullscreenElementStack::fromIfExists()
 
     Vector<RefPtr<Element> > m_topLayerElements;
 
     int m_loadEventDelayCount;
     Timer<Document> m_loadEventDelayTimer;
+    Timer<Document> m_pluginLoadingTimer;
 
     ViewportDescription m_viewportDescription;
     ViewportDescription m_legacyViewportDescription;
 
+    bool m_didSetReferrerPolicy;
     ReferrerPolicy m_referrerPolicy;
 
     bool m_directionSetOnDocumentElement;
@@ -1282,14 +1319,10 @@
 
     RefPtr<CustomElementRegistrationContext> m_registrationContext;
 
-    RefPtr<NamedFlowCollection> m_namedFlows;
+    void elementDataCacheClearTimerFired(Timer<Document>*);
+    Timer<Document> m_elementDataCacheClearTimer;
 
-    RefPtr<DOMSecurityPolicy> m_domSecurityPolicy;
-
-    void sharedObjectPoolClearTimerFired(Timer<Document>*);
-    Timer<Document> m_sharedObjectPoolClearTimer;
-
-    OwnPtr<DocumentSharedObjectPool> m_sharedObjectPool;
+    OwnPtr<ElementDataCache> m_elementDataCache;
 
 #ifndef NDEBUG
     bool m_didDispatchViewportPropertiesChanged;
@@ -1308,6 +1341,12 @@
 
     Timer<Document> m_didAssociateFormControlsTimer;
     HashSet<RefPtr<Element> > m_associatedFormControls;
+
+    HashSet<SVGUseElement*> m_useElementsNeedingUpdate;
+
+    bool m_hasViewportUnits;
+
+    HashSet<DocumentVisibilityObserver*> m_visibilityObservers;
 };
 
 inline void Document::notifyRemovePendingSheetIfNeeded()
@@ -1316,15 +1355,6 @@
         didRemoveAllPendingStylesheet();
 }
 
-inline const Document* Document::templateDocument() const
-{
-    // If DOCUMENT does not have a browsing context, Let TEMPLATE CONTENTS OWNER be DOCUMENT and abort these steps.
-    if (!m_frame)
-        return this;
-
-    return m_templateDocument.get();
-}
-
 inline bool Document::shouldOverrideLegacyDescription(ViewportDescription::Type origin)
 {
     // The different (legacy) meta tags have different priorities based on the type
@@ -1333,18 +1363,19 @@
     return origin >= m_legacyViewportDescription.type;
 }
 
-inline Document* toDocument(ExecutionContext* executionContext)
+inline void Document::incrementNodeListWithIdNameCacheCount()
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!executionContext || executionContext->isDocument());
-    return static_cast<Document*>(executionContext);
+    m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
 }
 
-inline const Document* toDocument(const ExecutionContext* executionContext)
+inline void Document::decrementNodeListWithIdNameCacheCount()
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!executionContext || executionContext->isDocument());
-    return static_cast<const Document*>(executionContext);
+    ASSERT(m_nodeListCounts[InvalidateOnIdNameAttrChange] > 0);
+    m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
 }
 
+DEFINE_TYPE_CASTS(Document, ExecutionContextClient, client, client->isDocument(), client.isDocument());
+DEFINE_TYPE_CASTS(Document, ExecutionContext, context, context->isDocument(), context.isDocument());
 DEFINE_NODE_TYPE_CASTS(Document, isDocumentNode());
 
 #define DEFINE_DOCUMENT_TYPE_CASTS(thisType) \
@@ -1362,7 +1393,7 @@
 
 inline bool Node::isDocumentNode() const
 {
-    return this == documentInternal();
+    return this == document();
 }
 
 Node* eventTargetNodeForDocument(Document*);
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index 772a3ad..158f5bb 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -21,7 +21,7 @@
 callback CustomElementConstructor = Element ();
 
 [
-    SpecialWrapFor=HTMLDocument|SVGDocument
+    SpecialWrapFor=HTMLDocument|XMLDocument
 ] interface Document : Node {
 
     // DOM Level 1 Core
@@ -36,15 +36,13 @@
     [RaisesException, MeasureAs=DocumentCreateCDATASection] CDATASection createCDATASection([Default=Undefined] optional DOMString data); // Removed from DOM4.
     [RaisesException] ProcessingInstruction createProcessingInstruction(DOMString target, DOMString data);
     [RaisesException, MeasureAs=DocumentCreateAttribute] Attr createAttribute([Default=Undefined] optional DOMString name); // Removed from DOM4.
-    [PerWorldBindings] NodeList getElementsByTagName(DOMString localName);
+    [PerWorldBindings] HTMLCollection getElementsByTagName(DOMString localName);
 
     // Introduced in DOM Level 2:
 
     [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node importNode(Node node, optional boolean deep);
     [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName);
-    [RaisesException, MeasureAs=DocumentCreateAttributeNS] Attr createAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                                                                                  [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName); // Removed from DOM4.
-    NodeList getElementsByTagNameNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
+    HTMLCollection getElementsByTagNameNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
     [PerWorldBindings] Element getElementById(DOMString elementId);
 
     // DOM Level 3 Core
@@ -57,11 +55,11 @@
 
     [RaisesException, CustomElementCallbacks] Node adoptNode(Node node);
 
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString documentURI;
+    [TreatReturnedNullStringAs=Null, ImplementedAs=url] readonly attribute DOMString documentURI;
 
     // DOM Level 2 Events (DocumentEvents interface)
 
-    [RaisesException] Event createEvent(DOMString eventType);
+    [RaisesException] Event createEvent(optional DOMString eventType);
 
     // DOM Level 2 Traversal and Range (DocumentRange interface)
 
@@ -78,7 +76,7 @@
 
     // DOM Level 2 Abstract Views (DocumentView interface)
 
-    [ImplementedAs=domWindow] readonly attribute Window defaultView;
+    [ImplementedAs=executingWindow] readonly attribute Window defaultView;
 
     // DOM Level 2 Style (DocumentStyle interface)
 
@@ -110,7 +108,7 @@
 
              [TreatNullAs=NullString, RaisesException] attribute DOMString cookie;
 
-             [RaisesException=Setter, CustomElementCallbacks] attribute HTMLElement body;
+             [RaisesException=Setter, CustomElementCallbacks, PerWorldBindings] attribute HTMLElement body;
 
     readonly attribute HTMLHeadElement head;
     readonly attribute HTMLCollection images;
@@ -146,7 +144,9 @@
     CanvasRenderingContext getCSSCanvasContext(DOMString contextId, DOMString name, long width, long height);
 
     // HTML 5
-    NodeList getElementsByClassName(DOMString classNames);
+    HTMLCollection getElementsByClassName(DOMString classNames);
+    readonly attribute Element activeElement;
+    boolean hasFocus();
 
     readonly attribute DOMString compatMode;
 
@@ -157,8 +157,6 @@
     void webkitExitPointerLock();
     readonly attribute Element webkitPointerLockElement;
 
-    [RuntimeEnabled=CSSRegions] WebKitNamedFlowCollection webkitGetNamedFlows();
-
     // Event handler attributes
     attribute EventHandler onbeforecopy;
     attribute EventHandler onbeforecut;
@@ -194,8 +192,7 @@
                                                [Default=Undefined] optional float webkitForce);
     [RuntimeEnabled=Touch] TouchList createTouchList(Touch... touches);
 
-    [DeprecateAs=PrefixedDocumentRegister, RuntimeEnabled=CustomElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks, RaisesException] CustomElementConstructor webkitRegister(DOMString name, optional Dictionary options);
-    [RuntimeEnabled=CustomElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks, RaisesException] CustomElementConstructor register(DOMString name, optional Dictionary options);
+    [CallWith=ScriptState, CustomElementCallbacks, RaisesException] CustomElementConstructor registerElement(DOMString name, optional Dictionary options);
     [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElement(DOMString localName, [TreatNullAs=NullString] DOMString typeExtension);
     [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName,
                             [TreatNullAs=NullString] DOMString typeExtension);
@@ -210,11 +207,9 @@
     [MeasureAs=PrefixedPageVisibility, ImplementedAs=visibilityState] readonly attribute DOMString webkitVisibilityState;
     [MeasureAs=PrefixedPageVisibility, ImplementedAs=hidden] readonly attribute boolean webkitHidden;
 
-    // Security Policy API: http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html#script-interfaces
-    [RuntimeEnabled=ExperimentalContentSecurityPolicyFeatures] readonly attribute SecurityPolicy securityPolicy;
-
     readonly attribute HTMLScriptElement currentScript;
 };
 
 Document implements GlobalEventHandlers;
 Document implements ParentNode;
+
diff --git a/Source/core/html/HTMLImportResourceOwner.cpp b/Source/core/dom/DocumentEncodingData.cpp
similarity index 74%
rename from Source/core/html/HTMLImportResourceOwner.cpp
rename to Source/core/dom/DocumentEncodingData.cpp
index 3a3109c..23d69f5 100644
--- a/Source/core/html/HTMLImportResourceOwner.cpp
+++ b/Source/core/dom/DocumentEncodingData.cpp
@@ -29,32 +29,28 @@
  */
 
 #include "config.h"
-#include "core/html/HTMLImportResourceOwner.h"
+#include "core/dom/DocumentEncodingData.h"
+
+#include "core/html/parser/TextResourceDecoder.h"
 
 namespace WebCore {
 
-HTMLImportResourceOwner::HTMLImportResourceOwner()
+DocumentEncodingData::DocumentEncodingData()
+    : m_wasDetectedHeuristically(false)
+    , m_sawDecodingError(false)
 {
 }
 
-HTMLImportResourceOwner::~HTMLImportResourceOwner()
+DocumentEncodingData::DocumentEncodingData(const TextResourceDecoder& decoder)
 {
-    clearResource();
+    m_encoding = decoder.encoding();
+    m_wasDetectedHeuristically = decoder.encodingWasDetectedHeuristically();
+    m_sawDecodingError = decoder.sawError();
 }
 
-void HTMLImportResourceOwner::setResource(const ResourcePtr<RawResource>& resource)
+void DocumentEncodingData::setEncoding(const WTF::TextEncoding& encoding)
 {
-    ASSERT(!hasResource());
-    m_resource = resource;
-    m_resource->addClient(this);
-}
-
-void HTMLImportResourceOwner::clearResource()
-{
-    if (!hasResource())
-        return;
-    m_resource->removeClient(this);
-    m_resource = 0;
+    m_encoding = encoding;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentEncodingData.h b/Source/core/dom/DocumentEncodingData.h
index 5a696af..2016aa5 100644
--- a/Source/core/dom/DocumentEncodingData.h
+++ b/Source/core/dom/DocumentEncodingData.h
@@ -34,19 +34,31 @@
 #include "wtf/text/TextEncoding.h"
 
 namespace WebCore {
+class TextResourceDecoder;
 
-struct DocumentEncodingData {
-    DocumentEncodingData()
-        : wasDetectedHeuristically(false)
-        , sawDecodingError(false)
-    {
-    }
+class DocumentEncodingData {
+public:
+    DocumentEncodingData();
+    explicit DocumentEncodingData(const TextResourceDecoder&);
 
-    WTF::TextEncoding encoding;
-    bool wasDetectedHeuristically;
-    bool sawDecodingError;
+    const WTF::TextEncoding& encoding() const { return m_encoding; }
+    void setEncoding(const WTF::TextEncoding&);
+    bool wasDetectedHeuristically() const { return m_wasDetectedHeuristically; }
+    bool sawDecodingError() const { return m_sawDecodingError; }
+
+private:
+    WTF::TextEncoding m_encoding;
+    bool m_wasDetectedHeuristically;
+    bool m_sawDecodingError;
 };
 
+inline bool operator!=(const DocumentEncodingData& a, const DocumentEncodingData& b)
+{
+    return a.encoding() != b.encoding()
+        || a.wasDetectedHeuristically() != b.wasDetectedHeuristically()
+        || a.sawDecodingError() != b.sawDecodingError();
+}
+
 } // namespace WebCore
 
 #endif // DocumentEncodingData_h
diff --git a/Source/core/dom/DocumentFragment.h b/Source/core/dom/DocumentFragment.h
index 4730abc..2bf1418 100644
--- a/Source/core/dom/DocumentFragment.h
+++ b/Source/core/dom/DocumentFragment.h
@@ -38,17 +38,17 @@
     void parseHTML(const String&, Element* contextElement, ParserContentPolicy = AllowScriptingContent);
     bool parseXML(const String&, Element* contextElement, ParserContentPolicy = AllowScriptingContent);
 
-    virtual bool canContainRangeEndPoint() const { return true; }
+    virtual bool canContainRangeEndPoint() const OVERRIDE FINAL { return true; }
     virtual bool isTemplateContent() const { return false; }
 
 protected:
     DocumentFragment(Document*, ConstructionType = CreateContainer);
-    virtual String nodeName() const;
+    virtual String nodeName() const OVERRIDE FINAL;
 
 private:
-    virtual NodeType nodeType() const;
-    virtual PassRefPtr<Node> cloneNode(bool deep = true);
-    virtual bool childTypeAllowed(NodeType) const;
+    virtual NodeType nodeType() const OVERRIDE FINAL;
+    virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE;
+    virtual bool childTypeAllowed(NodeType) const OVERRIDE;
 };
 
 DEFINE_NODE_TYPE_CASTS(DocumentFragment, nodeType() == Node::DOCUMENT_FRAGMENT_NODE);
diff --git a/Source/core/dom/DocumentFullscreen.idl b/Source/core/dom/DocumentFullscreen.idl
index 561ad80..917d481 100644
--- a/Source/core/dom/DocumentFullscreen.idl
+++ b/Source/core/dom/DocumentFullscreen.idl
@@ -18,15 +18,18 @@
  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  * Boston, MA 02110-1301, USA.
  */
-partial interface Document {
+
+[
+    RuntimeEnabled=Fullscreen,
+] partial interface Document {
     // Mozilla version
-    [RuntimeEnabled=Fullscreen] readonly attribute boolean webkitIsFullScreen;
-    [RuntimeEnabled=Fullscreen] readonly attribute boolean webkitFullScreenKeyboardInputAllowed;
-    [RuntimeEnabled=Fullscreen] readonly attribute Element webkitCurrentFullScreenElement;
-    [RuntimeEnabled=Fullscreen] void webkitCancelFullScreen();
+    readonly attribute boolean webkitIsFullScreen;
+    readonly attribute boolean webkitFullScreenKeyboardInputAllowed;
+    readonly attribute Element webkitCurrentFullScreenElement;
+    void webkitCancelFullScreen();
 
     // W3C version
-    [RuntimeEnabled=Fullscreen] readonly attribute boolean webkitFullscreenEnabled;
-    [RuntimeEnabled=Fullscreen] readonly attribute Element webkitFullscreenElement;
-    [RuntimeEnabled=Fullscreen] void webkitExitFullscreen();
+    readonly attribute boolean webkitFullscreenEnabled;
+    readonly attribute Element webkitFullscreenElement;
+    void webkitExitFullscreen();
 };
diff --git a/Source/core/dom/DocumentInit.cpp b/Source/core/dom/DocumentInit.cpp
index 90b4dd9..0c3013a 100644
--- a/Source/core/dom/DocumentInit.cpp
+++ b/Source/core/dom/DocumentInit.cpp
@@ -68,6 +68,7 @@
     , m_owner(ownerDocument(frame))
     , m_contextDocument(contextDocument)
     , m_import(import)
+    , m_createNewRegistrationContext(false)
 {
 }
 
@@ -79,6 +80,7 @@
     , m_contextDocument(other.m_contextDocument)
     , m_import(other.m_import)
     , m_registrationContext(other.m_registrationContext)
+    , m_createNewRegistrationContext(other.m_createNewRegistrationContext)
 {
 }
 
@@ -97,19 +99,6 @@
     return m_parent && m_frame->loader().shouldTreatURLAsSrcdocDocument(m_url);
 }
 
-bool DocumentInit::isSeamlessAllowedFor(Document* child) const
-{
-    if (!m_parent)
-        return false;
-    if (m_parent->isSandboxed(SandboxSeamlessIframes))
-        return false;
-    if (child->isSrcdocDocument())
-        return true;
-    if (m_parent->securityOrigin()->canAccess(child->securityOrigin()))
-        return true;
-    return m_parent->securityOrigin()->canRequest(child->url());
-}
-
 Frame* DocumentInit::frameForSecurityContext() const
 {
     if (m_frame)
@@ -138,23 +127,27 @@
 
 DocumentInit& DocumentInit::withRegistrationContext(CustomElementRegistrationContext* registrationContext)
 {
-    ASSERT(!m_registrationContext);
+    ASSERT(!m_createNewRegistrationContext && !m_registrationContext);
     m_registrationContext = registrationContext;
     return *this;
 }
 
+DocumentInit& DocumentInit::withNewRegistrationContext()
+{
+    ASSERT(!m_createNewRegistrationContext && !m_registrationContext);
+    m_createNewRegistrationContext = true;
+    return *this;
+}
+
 PassRefPtr<CustomElementRegistrationContext> DocumentInit::registrationContext(Document* document) const
 {
-    if (!RuntimeEnabledFeatures::customElementsEnabled() && !RuntimeEnabledFeatures::embedderCustomElementsEnabled())
-        return 0;
-
     if (!document->isHTMLDocument() && !document->isXHTMLDocument())
         return 0;
 
-    if (m_registrationContext)
-        return m_registrationContext.get();
+    if (m_createNewRegistrationContext)
+        return CustomElementRegistrationContext::create();
 
-    return CustomElementRegistrationContext::create();
+    return m_registrationContext.get();
 }
 
 WeakPtr<Document> DocumentInit::contextDocument() const
diff --git a/Source/core/dom/DocumentInit.h b/Source/core/dom/DocumentInit.h
index 911d14f..9bc28cd 100644
--- a/Source/core/dom/DocumentInit.h
+++ b/Source/core/dom/DocumentInit.h
@@ -66,7 +66,7 @@
     Settings* settings() const;
 
     DocumentInit& withRegistrationContext(CustomElementRegistrationContext*);
-
+    DocumentInit& withNewRegistrationContext();
     PassRefPtr<CustomElementRegistrationContext> registrationContext(Document*) const;
     WeakPtr<Document> contextDocument() const;
 
@@ -82,6 +82,7 @@
     WeakPtr<Document> m_contextDocument;
     HTMLImport* m_import;
     RefPtr<CustomElementRegistrationContext> m_registrationContext;
+    bool m_createNewRegistrationContext;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentLifecycle.cpp b/Source/core/dom/DocumentLifecycle.cpp
index 157548f..e1451fc 100644
--- a/Source/core/dom/DocumentLifecycle.cpp
+++ b/Source/core/dom/DocumentLifecycle.cpp
@@ -35,6 +35,32 @@
 
 namespace WebCore {
 
+static DocumentLifecycle::DeprecatedTransition* s_deprecatedTransitionStack = 0;
+
+DocumentLifecycle::Scope::Scope(DocumentLifecycle& lifecycle, State finalState)
+    : m_lifecycle(lifecycle)
+    , m_finalState(finalState)
+{
+}
+
+DocumentLifecycle::Scope::~Scope()
+{
+    m_lifecycle.advanceTo(m_finalState);
+}
+
+DocumentLifecycle::DeprecatedTransition::DeprecatedTransition(State from, State to)
+    : m_previous(s_deprecatedTransitionStack)
+    , m_from(from)
+    , m_to(to)
+{
+    s_deprecatedTransitionStack = this;
+}
+
+DocumentLifecycle::DeprecatedTransition::~DeprecatedTransition()
+{
+    s_deprecatedTransitionStack = m_previous;
+}
+
 DocumentLifecycle::DocumentLifecycle()
     : m_state(Uninitialized)
 {
@@ -44,11 +70,92 @@
 {
 }
 
+#if !ASSERT_DISABLED
+
+bool DocumentLifecycle::canAdvanceTo(State state) const
+{
+    // This transition is bogus, but we've whitelisted it anyway.
+    if (s_deprecatedTransitionStack && m_state == s_deprecatedTransitionStack->from() && state == s_deprecatedTransitionStack->to())
+        return true;
+    if (state > m_state)
+        return true;
+    if (m_state == Disposed) {
+        // FIXME: We can dispose a document multiple times. This seems wrong.
+        // See https://code.google.com/p/chromium/issues/detail?id=301668.
+        return state == Disposed;
+    }
+    if (m_state == StyleClean) {
+        if (state == StyleRecalcPending)
+            return true;
+        // We can synchronously recalc style.
+        if (state == InStyleRecalc)
+            return true;
+        // We can synchronously perform layout.
+        if (state == InPreLayout)
+            return true;
+        if (state == InPerformLayout)
+            return true;
+        // We can redundant arrive in the style clean state.
+        if (state == StyleClean)
+            return true;
+        return false;
+    }
+    if (m_state == InPreLayout) {
+        if (state == InStyleRecalc)
+            return true;
+        if (state == StyleClean)
+            return true;
+        if (state == InPreLayout)
+            return true;
+        return false;
+    }
+    if (m_state == AfterPerformLayout) {
+        if (state == InPreLayout)
+            return true;
+        // If we're doing a partial layout, we won't actually end up cleaning
+        // out all the layout dirty bits. Instead, we'll return to StyleClean.
+        if (state == StyleClean)
+            return true;
+        return false;
+    }
+    if (m_state == LayoutClean) {
+        if (state == StyleRecalcPending)
+            return true;
+        // We can synchronously recalc style.
+        if (state == InStyleRecalc)
+            return true;
+        // We can synchronously perform layout.
+        if (state == InPreLayout)
+            return true;
+        if (state == InPerformLayout)
+            return true;
+        // We can redundant arrive in the layout clean state. This situation
+        // can happen when we call layout recursively and we unwind the stack.
+        if (state == LayoutClean)
+            return true;
+        if (state == StyleClean)
+            return true;
+        return false;
+    }
+    if (m_state == CompositingClean) {
+        if (state == StyleRecalcPending)
+            return true;
+        if (state == InStyleRecalc)
+            return true;
+        if (state == InPreLayout)
+            return true;
+        if (state == InCompositingUpdate)
+            return true;
+        return false;
+    }
+    return false;
+}
+
+#endif
+
 void DocumentLifecycle::advanceTo(State state)
 {
-    // FIXME: We can dispose a document multiple times. This seems wrong.
-    // See https://code.google.com/p/chromium/issues/detail?id=301668.
-    ASSERT(state > m_state || (state == Disposed && m_state == Disposed));
+    ASSERT(canAdvanceTo(state));
     m_state = state;
 }
 
diff --git a/Source/core/dom/DocumentLifecycle.h b/Source/core/dom/DocumentLifecycle.h
index c3f9196..df58bea 100644
--- a/Source/core/dom/DocumentLifecycle.h
+++ b/Source/core/dom/DocumentLifecycle.h
@@ -41,20 +41,70 @@
     enum State {
         Uninitialized,
         Inactive,
-        Active,
+
+        // When the document is active, it traverses these states.
+
+        StyleRecalcPending,
+        InStyleRecalc,
+        StyleClean,
+
+        InPreLayout,
+        InPerformLayout,
+        AfterPerformLayout,
+        LayoutClean,
+
+        InCompositingUpdate,
+        CompositingClean,
+
+        // Once the document starts shuting down, we cannot return
+        // to the style/layout/rendering states.
         Stopping,
         Stopped,
         Disposed,
     };
 
+    class Scope {
+        WTF_MAKE_NONCOPYABLE(Scope);
+    public:
+        Scope(DocumentLifecycle&, State finalState);
+        ~Scope();
+
+        void setFinalState(State finalState) { m_finalState = finalState; }
+
+    private:
+        DocumentLifecycle& m_lifecycle;
+        State m_finalState;
+    };
+
+    class DeprecatedTransition {
+        WTF_MAKE_NONCOPYABLE(DeprecatedTransition);
+    public:
+        DeprecatedTransition(State from, State to);
+        ~DeprecatedTransition();
+
+        State from() const { return m_from; }
+        State to() const { return m_to; }
+
+    private:
+        DeprecatedTransition* m_previous;
+        State m_from;
+        State m_to;
+    };
+
     DocumentLifecycle();
     ~DocumentLifecycle();
 
+    bool isActive() const { return m_state > Inactive && m_state < Stopping; }
     State state() const { return m_state; }
 
     void advanceTo(State);
+    void rewindTo(State);
 
 private:
+#if !ASSERT_DISABLED
+    bool canAdvanceTo(State) const;
+#endif
+
     State m_state;
 };
 
diff --git a/Source/core/dom/DocumentLifecycleNotifier.h b/Source/core/dom/DocumentLifecycleNotifier.h
index 07888bd..f8a9f99 100644
--- a/Source/core/dom/DocumentLifecycleNotifier.h
+++ b/Source/core/dom/DocumentLifecycleNotifier.h
@@ -41,8 +41,8 @@
     void notifyDocumentWasDetached();
     void notifyDocumentWasDisposed();
 
-    virtual void addObserver(Observer*) OVERRIDE;
-    virtual void removeObserver(Observer*) OVERRIDE;
+    virtual void addObserver(Observer*) OVERRIDE FINAL;
+    virtual void removeObserver(Observer*) OVERRIDE FINAL;
 
 private:
     explicit DocumentLifecycleNotifier(Document*);
diff --git a/Source/core/dom/DocumentMarker.cpp b/Source/core/dom/DocumentMarker.cpp
index 12b9039..5796c8e 100644
--- a/Source/core/dom/DocumentMarker.cpp
+++ b/Source/core/dom/DocumentMarker.cpp
@@ -37,12 +37,12 @@
 {
 }
 
-class DocumentMarkerDescription : public DocumentMarkerDetails {
+class DocumentMarkerDescription FINAL : public DocumentMarkerDetails {
 public:
     static PassRefPtr<DocumentMarkerDescription> create(const String&);
 
     const String& description() const { return m_description; }
-    virtual bool isDescription() const { return true; }
+    virtual bool isDescription() const OVERRIDE { return true; }
 
 private:
     DocumentMarkerDescription(const String& description)
@@ -66,12 +66,12 @@
 }
 
 
-class DocumentMarkerTextMatch : public DocumentMarkerDetails {
+class DocumentMarkerTextMatch FINAL : public DocumentMarkerDetails {
 public:
     static PassRefPtr<DocumentMarkerTextMatch> instanceFor(bool);
 
     bool activeMatch() const { return m_match; }
-    virtual bool isTextMatch() const { return true; }
+    virtual bool isTextMatch() const OVERRIDE { return true; }
 
 private:
     explicit DocumentMarkerTextMatch(bool match)
diff --git a/Source/core/dom/DocumentMarkerController.cpp b/Source/core/dom/DocumentMarkerController.cpp
index ef4fa82..78b731c 100644
--- a/Source/core/dom/DocumentMarkerController.cpp
+++ b/Source/core/dom/DocumentMarkerController.cpp
@@ -200,7 +200,7 @@
 
     m_possiblyExistingMarkerTypes.add(newMarker.type());
 
-    OwnPtr<MarkerLists>& markers = m_markers.add(node, nullptr).iterator->value;
+    OwnPtr<MarkerLists>& markers = m_markers.add(node, nullptr).storedValue->value;
     if (!markers) {
         markers = adoptPtr(new MarkerLists);
         markers->grow(DocumentMarker::MarkerTypeIndexesCount);
diff --git a/Source/core/dom/DocumentOrderedList.h b/Source/core/dom/DocumentOrderedList.h
index 133a34d..37b4385 100644
--- a/Source/core/dom/DocumentOrderedList.h
+++ b/Source/core/dom/DocumentOrderedList.h
@@ -45,6 +45,7 @@
     void remove(const Node*);
     bool isEmpty() const { return m_nodes.isEmpty(); }
     void clear() { m_nodes.clear(); }
+    size_t size() const { return m_nodes.size(); }
 
     typedef ListHashSet<Node*, 32>::iterator iterator;
 
diff --git a/Source/core/dom/DocumentOrderedMap.cpp b/Source/core/dom/DocumentOrderedMap.cpp
index 494d266..cd28b03 100644
--- a/Source/core/dom/DocumentOrderedMap.cpp
+++ b/Source/core/dom/DocumentOrderedMap.cpp
@@ -35,7 +35,6 @@
 #include "core/dom/Element.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/TreeScope.h"
-#include "core/html/HTMLLabelElement.h"
 #include "core/html/HTMLMapElement.h"
 
 namespace WebCore {
@@ -59,13 +58,7 @@
 
 inline bool keyMatchesLabelForAttribute(StringImpl* key, Element* element)
 {
-    return isHTMLLabelElement(element) && element->getAttribute(forAttr).impl() == key;
-}
-
-void DocumentOrderedMap::clear()
-{
-    m_map.clear();
-    m_duplicateCounts.clear();
+    return element->hasTagName(labelTag) && element->getAttribute(forAttr).impl() == key;
 }
 
 void DocumentOrderedMap::add(StringImpl* key, Element* element)
@@ -73,29 +66,15 @@
     ASSERT(key);
     ASSERT(element);
 
-    if (!m_duplicateCounts.contains(key)) {
-        // Fast path. The key is not already in m_duplicateCounts, so we assume that it's
-        // also not already in m_map and try to add it. If that add succeeds, we're done.
-        Map::AddResult addResult = m_map.add(key, element);
-        if (addResult.isNewEntry)
-            return;
+    Map::AddResult addResult = m_map.add(key, adoptPtr(new MapEntry(element)));
+    if (addResult.isNewEntry)
+        return;
 
-        // The add failed, so this key was already cached in m_map.
-        // There are multiple elements with this key. Remove the m_map
-        // cache for this key so get searches for it next time it is called.
-        m_map.remove(addResult.iterator);
-        m_duplicateCounts.add(key);
-    } else {
-        // There are multiple elements with this key. Remove the m_map
-        // cache for this key so get will search for it next time it is called.
-        Map::iterator cachedItem = m_map.find(key);
-        if (cachedItem != m_map.end()) {
-            m_map.remove(cachedItem);
-            m_duplicateCounts.add(key);
-        }
-    }
-
-    m_duplicateCounts.add(key);
+    OwnPtr<MapEntry>& entry = addResult.storedValue->value;
+    ASSERT(entry->count);
+    entry->element = 0;
+    entry->count++;
+    entry->orderedList.clear();
 }
 
 void DocumentOrderedMap::remove(StringImpl* key, Element* element)
@@ -103,11 +82,23 @@
     ASSERT(key);
     ASSERT(element);
 
-    Map::iterator cachedItem = m_map.find(key);
-    if (cachedItem != m_map.end() && cachedItem->value == element)
-        m_map.remove(cachedItem);
-    else
-        m_duplicateCounts.remove(key);
+    Map::iterator it = m_map.find(key);
+    if (it == m_map.end())
+        return;
+
+    OwnPtr<MapEntry>& entry = it->value;
+    ASSERT(entry->count);
+    if (entry->count == 1) {
+        ASSERT(!entry->element || entry->element == element);
+        m_map.remove(it);
+    } else {
+        if (entry->element == element) {
+            ASSERT(entry->orderedList.isEmpty() || entry->orderedList.first() == element);
+            entry->element = entry->orderedList.size() > 1 ? entry->orderedList[1] : 0;
+        }
+        entry->count--;
+        entry->orderedList.clear();
+    }
 }
 
 template<bool keyMatches(StringImpl*, Element*)>
@@ -116,23 +107,22 @@
     ASSERT(key);
     ASSERT(scope);
 
-    Element* element = m_map.get(key);
-    if (element)
+    MapEntry* entry = m_map.get(key);
+    if (!entry)
+        return 0;
+
+    ASSERT(entry->count);
+    if (entry->element)
+        return entry->element;
+
+    // We know there's at least one node that matches; iterate to find the first one.
+    for (Element* element = ElementTraversal::firstWithin(scope->rootNode()); element; element = ElementTraversal::next(*element)) {
+        if (!keyMatches(key, element))
+            continue;
+        entry->element = element;
         return element;
-
-    if (m_duplicateCounts.contains(key)) {
-        // We know there's at least one node that matches; iterate to find the first one.
-        ASSERT(scope->rootNode());
-        for (element = ElementTraversal::firstWithin(*scope->rootNode()); element; element = ElementTraversal::next(*element)) {
-            if (!keyMatches(key, element))
-                continue;
-            m_duplicateCounts.remove(key);
-            m_map.set(key, element);
-            return element;
-        }
-        ASSERT_NOT_REACHED();
     }
-
+    ASSERT_NOT_REACHED();
     return 0;
 }
 
@@ -141,6 +131,34 @@
     return get<keyMatchesId>(key, scope);
 }
 
+const Vector<Element*>& DocumentOrderedMap::getAllElementsById(StringImpl* key, const TreeScope* scope) const
+{
+    ASSERT(key);
+    ASSERT(scope);
+    DEFINE_STATIC_LOCAL(Vector<Element*>, emptyVector, ());
+
+    Map::iterator it = m_map.find(key);
+    if (it == m_map.end())
+        return emptyVector;
+
+    OwnPtr<MapEntry>& entry = it->value;
+    ASSERT(entry->count);
+
+    if (entry->orderedList.isEmpty()) {
+        entry->orderedList.reserveCapacity(entry->count);
+        for (Element* element = entry->element ? entry->element : ElementTraversal::firstWithin(scope->rootNode()); entry->orderedList.size() < entry->count; element = ElementTraversal::next(*element)) {
+            ASSERT(element);
+            if (!keyMatchesId(key, element))
+                continue;
+            entry->orderedList.uncheckedAppend(element);
+        }
+        if (!entry->element)
+            entry->element = entry->orderedList.first();
+    }
+
+    return entry->orderedList;
+}
+
 Element* DocumentOrderedMap::getElementByMapName(StringImpl* key, const TreeScope* scope) const
 {
     return get<keyMatchesMapName>(key, scope);
diff --git a/Source/core/dom/DocumentOrderedMap.h b/Source/core/dom/DocumentOrderedMap.h
index b6fc8e0..19c470e 100644
--- a/Source/core/dom/DocumentOrderedMap.h
+++ b/Source/core/dom/DocumentOrderedMap.h
@@ -31,8 +31,8 @@
 #ifndef DocumentOrderedMap_h
 #define DocumentOrderedMap_h
 
-#include "wtf/HashCountedSet.h"
 #include "wtf/HashMap.h"
+#include "wtf/Vector.h"
 #include "wtf/text/StringImpl.h"
 
 namespace WebCore {
@@ -44,38 +44,44 @@
 public:
     void add(StringImpl*, Element*);
     void remove(StringImpl*, Element*);
-    void clear();
 
     bool contains(StringImpl*) const;
     bool containsMultiple(StringImpl*) const;
     // concrete instantiations of the get<>() method template
     Element* getElementById(StringImpl*, const TreeScope*) const;
+    const Vector<Element*>& getAllElementsById(StringImpl*, const TreeScope*) const;
     Element* getElementByMapName(StringImpl*, const TreeScope*) const;
     Element* getElementByLowercasedMapName(StringImpl*, const TreeScope*) const;
     Element* getElementByLabelForAttribute(StringImpl*, const TreeScope*) const;
 
-    void checkConsistency() const;
-
 private:
     template<bool keyMatches(StringImpl*, Element*)> Element* get(StringImpl*, const TreeScope*) const;
 
-    typedef HashMap<StringImpl*, Element*> Map;
+    struct MapEntry {
+        explicit MapEntry(Element* firstElement)
+            : element(firstElement)
+            , count(1)
+        { }
 
-    // We maintain the invariant that m_duplicateCounts is the count of all elements with a given key
-    // excluding the one referenced in m_map, if any. This means it one less than the total count
-    // when the first node with a given key is cached, otherwise the same as the total count.
+        Element* element;
+        unsigned count;
+        Vector<Element*> orderedList;
+    };
+
+    typedef HashMap<StringImpl*, OwnPtr<MapEntry> > Map;
+
     mutable Map m_map;
-    mutable HashCountedSet<StringImpl*> m_duplicateCounts;
 };
 
 inline bool DocumentOrderedMap::contains(StringImpl* id) const
 {
-    return m_map.contains(id) || m_duplicateCounts.contains(id);
+    return m_map.contains(id);
 }
 
 inline bool DocumentOrderedMap::containsMultiple(StringImpl* id) const
 {
-    return m_duplicateCounts.contains(id);
+    Map::const_iterator it = m_map.find(id);
+    return it != m_map.end() && it->value->count > 1;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentParser.cpp b/Source/core/dom/DocumentParser.cpp
index ac2ffa9..2b93e66 100644
--- a/Source/core/dom/DocumentParser.cpp
+++ b/Source/core/dom/DocumentParser.cpp
@@ -25,7 +25,7 @@
 
 #include "config.h"
 #include "core/dom/DocumentParser.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 
 #include "wtf/Assertions.h"
 
diff --git a/Source/core/dom/DocumentSharedObjectPool.cpp b/Source/core/dom/DocumentSharedObjectPool.cpp
deleted file mode 100644
index 985f04c..0000000
--- a/Source/core/dom/DocumentSharedObjectPool.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2012, 2013 Apple Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- *
- */
-
-#include "config.h"
-#include "core/dom/DocumentSharedObjectPool.h"
-
-#include "core/dom/Element.h"
-
-namespace WebCore {
-
-class ShareableElementDataCacheKey {
-public:
-    ShareableElementDataCacheKey(const Attribute* attributes, unsigned attributeCount)
-        : m_attributes(attributes)
-        , m_attributeCount(attributeCount)
-    { }
-
-    bool operator!=(const ShareableElementDataCacheKey& other) const
-    {
-        if (m_attributeCount != other.m_attributeCount)
-            return true;
-        return memcmp(m_attributes, other.m_attributes, sizeof(Attribute) * m_attributeCount);
-    }
-
-    unsigned hash() const
-    {
-        return StringHasher::hashMemory(m_attributes, m_attributeCount * sizeof(Attribute));
-    }
-
-private:
-    const Attribute* m_attributes;
-    unsigned m_attributeCount;
-};
-
-class ShareableElementDataCacheEntry {
-public:
-    ShareableElementDataCacheEntry(const ShareableElementDataCacheKey& k, PassRefPtr<ShareableElementData> v)
-        : key(k)
-        , value(v)
-    { }
-
-    ShareableElementDataCacheKey key;
-    RefPtr<ShareableElementData> value;
-};
-
-PassRefPtr<ShareableElementData> DocumentSharedObjectPool::cachedShareableElementDataWithAttributes(const Vector<Attribute>& attributes)
-{
-    ASSERT(!attributes.isEmpty());
-
-    ShareableElementDataCacheKey cacheKey(attributes.data(), attributes.size());
-    unsigned cacheHash = cacheKey.hash();
-
-    ShareableElementDataCache::iterator cacheIterator = m_shareableElementDataCache.add(cacheHash, nullptr).iterator;
-    if (cacheIterator->value && cacheIterator->value->key != cacheKey)
-        cacheHash = 0;
-
-    RefPtr<ShareableElementData> elementData;
-    if (cacheHash && cacheIterator->value)
-        elementData = cacheIterator->value->value;
-    else
-        elementData = ShareableElementData::createWithAttributes(attributes);
-
-    if (!cacheHash || cacheIterator->value)
-        return elementData.release();
-
-    cacheIterator->value = adoptPtr(new ShareableElementDataCacheEntry(ShareableElementDataCacheKey(elementData->m_attributeArray, elementData->length()), elementData));
-
-    return elementData.release();
-}
-
-DocumentSharedObjectPool::DocumentSharedObjectPool()
-{
-}
-
-DocumentSharedObjectPool::~DocumentSharedObjectPool()
-{
-}
-
-}
diff --git a/Source/core/dom/DocumentStyleSheetCollection.cpp b/Source/core/dom/DocumentStyleSheetCollection.cpp
index 5d4736f..c252e12 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -33,13 +33,15 @@
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
+#include "core/dom/DocumentStyleSheetCollector.h"
 #include "core/dom/Element.h"
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/StyleEngine.h"
+#include "core/dom/StyleSheetCandidate.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLStyleElement.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/svg/SVGStyleElement.h"
 
 namespace WebCore {
@@ -47,143 +49,101 @@
 using namespace HTMLNames;
 
 DocumentStyleSheetCollection::DocumentStyleSheetCollection(TreeScope& treeScope)
-    : StyleSheetCollection(treeScope)
+    : TreeScopeStyleSheetCollection(treeScope)
 {
-    ASSERT(treeScope.rootNode() == treeScope.rootNode()->document());
+    ASSERT(treeScope.rootNode() == treeScope.rootNode().document());
 }
 
-void DocumentStyleSheetCollection::collectStyleSheetsFromCandidates(StyleEngine* engine, StyleSheetCollectionBase& collection, DocumentStyleSheetCollection::CollectFor collectFor)
+void DocumentStyleSheetCollection::collectStyleSheetsFromCandidates(StyleEngine* engine, DocumentStyleSheetCollector& collector)
 {
     DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin();
     DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end();
     for (DocumentOrderedList::iterator it = begin; it != end; ++it) {
         Node* n = *it;
-        StyleSheet* sheet = 0;
-        CSSStyleSheet* activeSheet = 0;
-        if (n->nodeType() == Node::PROCESSING_INSTRUCTION_NODE && !document()->isHTMLDocument()) {
+        StyleSheetCandidate candidate(*n);
+
+        if (candidate.isXSL()) {
             // Processing instruction (XML documents only).
             // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
-            ProcessingInstruction* pi = toProcessingInstruction(n);
             // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
-            if (RuntimeEnabledFeatures::xsltEnabled() && pi->isXSL() && !document()->transformSourceDocument()) {
+            if (RuntimeEnabledFeatures::xsltEnabled() && !document().transformSourceDocument()) {
+                ProcessingInstruction* pi = toProcessingInstruction(n);
                 // Don't apply XSL transforms until loading is finished.
-                if (!document()->parsing() && !pi->isLoading())
-                    document()->applyXSLTransform(pi);
+                if (!document().parsing() && !pi->isLoading())
+                    document().applyXSLTransform(pi);
                 return;
             }
-            sheet = pi->sheet();
-            if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
-                activeSheet = toCSSStyleSheet(sheet);
-        } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))) || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))) {
-            Element* e = toElement(n);
-            AtomicString title = e->getAttribute(titleAttr);
-            bool enabledViaScript = false;
-            if (e->hasLocalName(linkTag)) {
-                // <LINK> element
-                HTMLLinkElement* linkElement = toHTMLLinkElement(n);
-                enabledViaScript = linkElement->isEnabledViaScript();
-                if (!linkElement->isDisabled() && linkElement->styleSheetIsLoading()) {
-                    // it is loading but we should still decide which style sheet set to use
-                    if (!enabledViaScript && !title.isEmpty() && engine->preferredStylesheetSetName().isEmpty()) {
-                        const AtomicString& rel = e->getAttribute(relAttr);
-                        if (!rel.contains("alternate")) {
-                            engine->setPreferredStylesheetSetName(title);
-                            engine->setSelectedStylesheetSetName(title);
-                        }
-                    }
 
-                    continue;
-                }
-                sheet = linkElement->sheet();
-                if (!sheet)
-                    title = nullAtom;
-            } else if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag)) {
-                sheet = toSVGStyleElement(n)->sheet();
-            } else {
-                sheet = toHTMLStyleElement(n)->sheet();
-            }
-
-            if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
-                activeSheet = toCSSStyleSheet(sheet);
-
-            // Check to see if this sheet belongs to a styleset
-            // (thus making it PREFERRED or ALTERNATE rather than
-            // PERSISTENT).
-            AtomicString rel = e->getAttribute(relAttr);
-            if (!enabledViaScript && sheet && !title.isEmpty()) {
-                // Yes, we have a title.
-                if (engine->preferredStylesheetSetName().isEmpty()) {
-                    // No preferred set has been established. If
-                    // we are NOT an alternate sheet, then establish
-                    // us as the preferred set. Otherwise, just ignore
-                    // this sheet.
-                    if (e->hasLocalName(styleTag) || !rel.contains("alternate")) {
-                        engine->setPreferredStylesheetSetName(title);
-                        engine->setSelectedStylesheetSetName(title);
-                    }
-                }
-                if (title != engine->preferredStylesheetSetName())
-                    activeSheet = 0;
-            }
-
-            if (rel.contains("alternate") && title.isEmpty())
-                activeSheet = 0;
+            continue;
         }
 
-        if (sheet && collectFor == CollectForList)
-            collection.appendSheetForList(sheet);
-        if (activeSheet)
-            collection.appendActiveStyleSheet(activeSheet);
+        if (candidate.isImport()) {
+            Document* document = candidate.importedDocument();
+            if (!document)
+                continue;
+            document->styleEngine()->updateStyleSheetsInImport(collector);
+            continue;
+        }
+
+        if (candidate.isEnabledAndLoading()) {
+            // it is loading but we should still decide which style sheet set to use
+            if (candidate.hasPreferrableName(engine->preferredStylesheetSetName()))
+                engine->selectStylesheetSetName(candidate.title());
+            continue;
+        }
+
+        StyleSheet* sheet = candidate.sheet();
+        if (!sheet)
+            continue;
+
+        if (candidate.hasPreferrableName(engine->preferredStylesheetSetName()))
+            engine->selectStylesheetSetName(candidate.title());
+        collector.appendSheetForList(sheet);
+        if (candidate.canBeActivated(engine->preferredStylesheetSetName()))
+            collector.appendActiveStyleSheet(toCSSStyleSheet(sheet));
     }
 }
 
-static void collectActiveCSSStyleSheetsFromSeamlessParents(StyleSheetCollectionBase& collection, Document* document)
+void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* engine, DocumentStyleSheetCollector& collector)
 {
-    HTMLIFrameElement* seamlessParentIFrame = document->seamlessParentIFrame();
-    if (!seamlessParentIFrame)
-        return;
-    collection.appendActiveStyleSheets(seamlessParentIFrame->document().styleEngine()->activeAuthorStyleSheets());
-}
-
-void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* engine, StyleSheetCollectionBase& collection, DocumentStyleSheetCollection::CollectFor colletFor)
-{
-    ASSERT(document()->styleEngine() == engine);
-    collection.appendActiveStyleSheets(engine->injectedAuthorStyleSheets());
-    collection.appendActiveStyleSheets(engine->documentAuthorStyleSheets());
-    collectActiveCSSStyleSheetsFromSeamlessParents(collection, document());
-    collectStyleSheetsFromCandidates(engine, collection, colletFor);
+    ASSERT(document().styleEngine() == engine);
+    collector.appendActiveStyleSheets(engine->injectedAuthorStyleSheets());
+    collector.appendActiveStyleSheets(engine->documentAuthorStyleSheets());
+    collectStyleSheetsFromCandidates(engine, collector);
 }
 
 bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleEngine* engine, StyleResolverUpdateMode updateMode)
 {
-    StyleSheetCollectionBase collection;
-    engine->collectDocumentActiveStyleSheets(collection);
+    StyleSheetCollection collection;
+    ActiveDocumentStyleSheetCollector collector(collection);
+    collectStyleSheets(engine, collector);
 
     StyleSheetChange change;
     analyzeStyleSheetChange(updateMode, collection, change);
 
     if (change.styleResolverUpdateType == Reconstruct) {
         engine->clearMasterResolver();
-        engine->resetFontSelector();
+        // FIMXE: The following depends on whether StyleRuleFontFace was modified or not.
+        // No need to always-clear font cache.
+        engine->clearFontCache();
     } else if (StyleResolver* styleResolver = engine->resolver()) {
         // FIXME: We might have already had styles in child treescope. In this case, we cannot use buildScopedStyleTreeInDocumentOrder.
         // Need to change "false" to some valid condition.
         styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
         if (change.styleResolverUpdateType != Additive) {
-            ASSERT(change.styleResolverUpdateType == Reset || change.styleResolverUpdateType == ResetStyleResolverAndFontSelector);
+            ASSERT(change.styleResolverUpdateType == Reset);
             resetAllRuleSetsInTreeScope(styleResolver);
-            if (change.styleResolverUpdateType == ResetStyleResolverAndFontSelector)
-                engine->resetFontSelector();
+            engine->removeFontFaceRules(change.fontFaceRulesToRemove);
             styleResolver->removePendingAuthorStyleSheets(m_activeAuthorStyleSheets);
             styleResolver->lazyAppendAuthorStyleSheets(0, collection.activeAuthorStyleSheets());
         } else {
             styleResolver->lazyAppendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), collection.activeAuthorStyleSheets());
         }
-    } else if (change.styleResolverUpdateType == ResetStyleResolverAndFontSelector) {
-        engine->resetFontSelector();
     }
     m_scopingNodesForStyleScoped.didRemoveScopingNodes();
+
     collection.swap(*this);
+
     updateUsesRemUnits();
 
     return change.requiresFullStyleRecalc;
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index 9920ad8..e277d24 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -28,31 +28,26 @@
 #ifndef DocumentStyleSheetCollection_h
 #define DocumentStyleSheetCollection_h
 
-#include "core/dom/StyleSheetCollection.h"
+#include "core/dom/TreeScopeStyleSheetCollection.h"
 
 namespace WebCore {
 
 class CSSStyleSheet;
+class DocumentStyleSheetCollector;
 class StyleSheet;
-class StyleSheetCollection;
 class StyleEngine;
 class TreeScope;
 
-class DocumentStyleSheetCollection FINAL : public StyleSheetCollection {
+class DocumentStyleSheetCollection FINAL : public TreeScopeStyleSheetCollection {
     WTF_MAKE_NONCOPYABLE(DocumentStyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit DocumentStyleSheetCollection(TreeScope&);
 
-    enum CollectFor {
-        CollectForList,
-        DontCollectForList
-    };
-
     bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
-    void collectStyleSheets(StyleEngine*, StyleSheetCollectionBase&, CollectFor);
+    void collectStyleSheets(StyleEngine*, DocumentStyleSheetCollector&);
 
 private:
-    void collectStyleSheetsFromCandidates(StyleEngine*, StyleSheetCollectionBase&, CollectFor);
+    void collectStyleSheetsFromCandidates(StyleEngine*, DocumentStyleSheetCollector&);
 };
 
 }
diff --git a/Source/core/dom/DocumentStyleSheetCollector.cpp b/Source/core/dom/DocumentStyleSheetCollector.cpp
new file mode 100644
index 0000000..f3dd8a6
--- /dev/null
+++ b/Source/core/dom/DocumentStyleSheetCollector.cpp
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/dom/DocumentStyleSheetCollector.h"
+
+#include "core/css/CSSStyleSheet.h"
+#include "core/css/StyleSheet.h"
+#include "core/dom/DocumentStyleSheetCollection.h"
+
+namespace WebCore {
+
+DocumentStyleSheetCollector::DocumentStyleSheetCollector(Vector<RefPtr<StyleSheet> >& sheetsForList, Vector<RefPtr<CSSStyleSheet> >& activeList)
+    : m_styleSheetsForStyleSheetList(sheetsForList)
+    , m_activeAuthorStyleSheets(activeList)
+{
+}
+
+DocumentStyleSheetCollector::~DocumentStyleSheetCollector()
+{
+}
+
+void DocumentStyleSheetCollector::appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& sheets)
+{
+    m_activeAuthorStyleSheets.append(sheets);
+}
+
+void DocumentStyleSheetCollector::appendActiveStyleSheet(CSSStyleSheet* sheet)
+{
+    m_activeAuthorStyleSheets.append(sheet);
+}
+
+void DocumentStyleSheetCollector::appendSheetForList(StyleSheet* sheet)
+{
+    m_styleSheetsForStyleSheetList.append(sheet);
+}
+
+ActiveDocumentStyleSheetCollector::ActiveDocumentStyleSheetCollector(StyleSheetCollection& collection)
+    : DocumentStyleSheetCollector(collection.m_styleSheetsForStyleSheetList, collection.m_activeAuthorStyleSheets)
+{
+}
+
+ImportedDocumentStyleSheetCollector::ImportedDocumentStyleSheetCollector(DocumentStyleSheetCollector& collector, Vector<RefPtr<StyleSheet> >& sheetForList)
+    : DocumentStyleSheetCollector(sheetForList, collector.m_activeAuthorStyleSheets)
+{
+}
+
+}
diff --git a/Source/core/dom/DocumentStyleSheetCollector.h b/Source/core/dom/DocumentStyleSheetCollector.h
new file mode 100644
index 0000000..fef627c
--- /dev/null
+++ b/Source/core/dom/DocumentStyleSheetCollector.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef DocumentStyleSheetCollector_h
+#define DocumentStyleSheetCollector_h
+
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class CSSStyleSheet;
+class StyleSheet;
+class StyleSheetCollection;
+
+class DocumentStyleSheetCollector {
+public:
+    friend class ImportedDocumentStyleSheetCollector;
+
+    DocumentStyleSheetCollector(Vector<RefPtr<StyleSheet> >& sheetsForList, Vector<RefPtr<CSSStyleSheet> >& activeList);
+    ~DocumentStyleSheetCollector();
+
+    void appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&);
+    void appendActiveStyleSheet(CSSStyleSheet*);
+    void appendSheetForList(StyleSheet*);
+
+private:
+    Vector<RefPtr<StyleSheet> >& m_styleSheetsForStyleSheetList;
+    Vector<RefPtr<CSSStyleSheet> >& m_activeAuthorStyleSheets;
+};
+
+class ActiveDocumentStyleSheetCollector FINAL : public DocumentStyleSheetCollector {
+public:
+    ActiveDocumentStyleSheetCollector(StyleSheetCollection&);
+};
+
+class ImportedDocumentStyleSheetCollector FINAL : public DocumentStyleSheetCollector {
+public:
+    ImportedDocumentStyleSheetCollector(DocumentStyleSheetCollector&, Vector<RefPtr<StyleSheet> >&);
+};
+
+} // namespace WebCore
+
+#endif // DocumentStyleSheetCollector_h
diff --git a/Source/core/dom/DocumentTest.cpp b/Source/core/dom/DocumentTest.cpp
new file mode 100644
index 0000000..99fac54
--- /dev/null
+++ b/Source/core/dom/DocumentTest.cpp
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2014, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/dom/Document.h"
+
+#include "core/testing/DummyPageHolder.h"
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+class DocumentTest : public ::testing::Test {
+protected:
+    virtual void SetUp() OVERRIDE;
+
+    Document& document() const { return m_dummyPageHolder->document(); }
+    Page& page() const { return m_dummyPageHolder->page(); }
+
+private:
+    OwnPtr<DummyPageHolder> m_dummyPageHolder;
+};
+
+void DocumentTest::SetUp()
+{
+    m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600));
+}
+
+class MockDocumentVisibilityObserver : public DocumentVisibilityObserver {
+public:
+    MockDocumentVisibilityObserver(Document& document) : DocumentVisibilityObserver(document) { }
+
+    MOCK_METHOD1(didChangeVisibilityState, void(PageVisibilityState));
+};
+
+TEST_F(DocumentTest, VisibilityOberver)
+{
+    page().setVisibilityState(PageVisibilityStateVisible, true); // initial state
+    MockDocumentVisibilityObserver observer1(document());
+
+    {
+        MockDocumentVisibilityObserver observer2(document());
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateHidden)).Times(0);
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateVisible)).Times(0);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateHidden)).Times(0);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateVisible)).Times(0);
+        ::testing::Mock::VerifyAndClearExpectations(&observer1);
+        ::testing::Mock::VerifyAndClearExpectations(&observer2);
+
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateHidden)).Times(1);
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateVisible)).Times(0);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateHidden)).Times(1);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateVisible)).Times(0);
+        page().setVisibilityState(PageVisibilityStateHidden, false);
+        ::testing::Mock::VerifyAndClearExpectations(&observer1);
+        ::testing::Mock::VerifyAndClearExpectations(&observer2);
+
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateHidden)).Times(0);
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateVisible)).Times(0);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateHidden)).Times(0);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateVisible)).Times(0);
+        page().setVisibilityState(PageVisibilityStateHidden, false);
+        ::testing::Mock::VerifyAndClearExpectations(&observer1);
+        ::testing::Mock::VerifyAndClearExpectations(&observer2);
+
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateHidden)).Times(0);
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateVisible)).Times(1);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateHidden)).Times(0);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateVisible)).Times(0);
+        OwnPtr<DummyPageHolder> alternatePage = DummyPageHolder::create(IntSize(800, 600));
+        Document& alternateDocument = alternatePage->document();
+        observer2.setObservedDocument(alternateDocument);
+        page().setVisibilityState(PageVisibilityStateVisible, false);
+        ::testing::Mock::VerifyAndClearExpectations(&observer1);
+        ::testing::Mock::VerifyAndClearExpectations(&observer2);
+
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateHidden)).Times(1);
+        EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateVisible)).Times(0);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateHidden)).Times(1);
+        EXPECT_CALL(observer2, didChangeVisibilityState(PageVisibilityStateVisible)).Times(0);
+        observer2.setObservedDocument(document());
+        page().setVisibilityState(PageVisibilityStateHidden, false);
+        ::testing::Mock::VerifyAndClearExpectations(&observer1);
+        ::testing::Mock::VerifyAndClearExpectations(&observer2);
+    }
+
+    // observer2 destroyed
+    EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateHidden)).Times(0);
+    EXPECT_CALL(observer1, didChangeVisibilityState(PageVisibilityStateVisible)).Times(1);
+    page().setVisibilityState(PageVisibilityStateVisible, false);
+}
+
+} // unnamed namespace
diff --git a/Source/core/dom/DocumentType.h b/Source/core/dom/DocumentType.h
index 6aa51fe..4ea5f07 100644
--- a/Source/core/dom/DocumentType.h
+++ b/Source/core/dom/DocumentType.h
@@ -37,11 +37,6 @@
         return adoptRef(new DocumentType(document, name, publicId, systemId));
     }
 
-    // FIXME: These wre removed from DOM4, we should add a UseCounter and see if
-    // we can remove them since they never worked anyway.
-    NamedNodeMap* entities() const { return 0; }
-    NamedNodeMap* notations() const { return 0; }
-
     const String& name() const { return m_name; }
     const String& publicId() const { return m_publicId; }
     const String& systemId() const { return m_systemId; }
@@ -64,7 +59,7 @@
     String m_subset;
 };
 
-DEFINE_NODE_TYPE_CASTS(DocumentType, nodeType() == Node::DOCUMENT_TYPE_NODE);
+DEFINE_NODE_TYPE_CASTS(DocumentType, isDocumentTypeNode());
 
 } // namespace WebCore
 
diff --git a/Source/core/dom/DocumentType.idl b/Source/core/dom/DocumentType.idl
index 510240a..330aa72 100644
--- a/Source/core/dom/DocumentType.idl
+++ b/Source/core/dom/DocumentType.idl
@@ -22,8 +22,6 @@
     // DOM Level 1
 
     readonly attribute DOMString name;
-    [MeasureAs=DocumentTypeEntities] readonly attribute NamedNodeMap entities; // Removed from DOM4.
-    [MeasureAs=DocumentTypeNotations] readonly attribute NamedNodeMap notations; // Removed from DOM4.
 
     // DOM Level 2
 
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index 369bf39..5f2ae80 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -30,33 +30,35 @@
 #include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "XMLNames.h"
+#include "bindings/v8/Dictionary.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/animation/DocumentTimeline.h"
 #include "core/animation/css/CSSAnimations.h"
-#include "core/css/CSSParser.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/CSSValuePool.h"
 #include "core/css/PropertySetCSSStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Attr.h"
 #include "core/dom/CSSSelectorWatch.h"
 #include "core/dom/ClientRect.h"
 #include "core/dom/ClientRectList.h"
 #include "core/dom/DatasetDOMStringMap.h"
-#include "core/dom/DocumentSharedObjectPool.h"
+#include "core/dom/ElementDataCache.h"
 #include "core/dom/ElementRareData.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/FullscreenElementStack.h"
 #include "core/dom/MutationObserverInterestGroup.h"
 #include "core/dom/MutationRecord.h"
 #include "core/dom/NamedNodeMap.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/PostAttachCallbacks.h"
 #include "core/dom/PresentationAttributeStyle.h"
 #include "core/dom/PseudoElement.h"
+#include "core/dom/RenderTreeBuilder.h"
 #include "core/dom/ScriptableDocumentParser.h"
 #include "core/dom/SelectorQuery.h"
 #include "core/dom/Text.h"
@@ -73,6 +75,7 @@
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
+#include "core/frame/UseCounter.h"
 #include "core/html/ClassList.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLDocument.h"
@@ -88,15 +91,16 @@
 #include "core/page/FocusController.h"
 #include "core/page/Page.h"
 #include "core/page/PointerLockController.h"
-#include "core/rendering/FlowThreadController.h"
-#include "core/rendering/RenderNamedFlowFragment.h"
+#include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGElement.h"
+#include "platform/scroll/ScrollableArea.h"
 #include "wtf/BitVector.h"
 #include "wtf/HashFunctions.h"
 #include "wtf/text/CString.h"
+#include "wtf/text/StringBuilder.h"
 #include "wtf/text/TextPosition.h"
 
 namespace WebCore {
@@ -164,7 +168,7 @@
     ASSERT(!attrNodeListMap().contains(element));
     element->setHasSyntheticAttrChildNodes(true);
     AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
-    return *result.iterator->value;
+    return *result.storedValue->value;
 }
 
 static void removeAttrNodeListForElement(Element* element)
@@ -192,26 +196,10 @@
 
 Element::~Element()
 {
-    // When the document is not destroyed, an element that was part of a named flow
-    // content nodes should have been removed from the content nodes collection
-    // and the inNamedFlow flag reset.
-    ASSERT(!document().renderView() || !inNamedFlow());
+    ASSERT(needsAttach());
 
-    if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
-        cssomWrapper->clearParentElement();
-
-    if (hasRareData()) {
-        ElementRareData* data = elementRareData();
-        data->setPseudoElement(BEFORE, 0);
-        data->setPseudoElement(AFTER, 0);
-        data->setPseudoElement(BACKDROP, 0);
-        data->clearShadow();
-
-        if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
-            if (ActiveAnimations* activeAnimations = data->activeAnimations())
-                activeAnimations->cssAnimations().cancel();
-        }
-    }
+    if (hasRareData())
+        elementRareData()->clearShadow();
 
     if (isCustomElement())
         CustomElement::wasDestroyed(this);
@@ -272,9 +260,7 @@
     // FIXME: These asserts should be in Node::isFocusable, but there are some
     // callsites like Document::setFocusedElement that would currently fail on
     // them. See crbug.com/251163
-    if (renderer()) {
-        ASSERT(!renderer()->needsLayout());
-    } else {
+    if (!renderer()) {
         // We can't just use needsStyleRecalc() because if the node is in a
         // display:none tree it might say it needs style recalc but the whole
         // document is actually up to date.
@@ -390,9 +376,6 @@
 
 bool Element::hasActiveAnimations() const
 {
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-        return false;
-
     if (!hasRareData())
         return false;
 
@@ -414,6 +397,9 @@
 {
     if (!elementData())
         return;
+    // NOTE: anyAttributeMatches in SelectorChecker.cpp
+    // currently assumes that all lazy attributes have a null namespace.
+    // If that ever changes we'll need to fix that code.
     if (elementData()->m_styleAttributeIsDirty) {
         ASSERT(isStyledElement());
         synchronizeStyleAttributeInternal();
@@ -435,6 +421,8 @@
     }
     if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
         ASSERT(isSVGElement());
+        // See comment in the AtomicString version of synchronizeAttribute()
+        // also.
         toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
     }
 }
@@ -452,8 +440,17 @@
     }
     if (elementData()->m_animatedSVGAttributesAreDirty) {
         // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
-        ASSERT(isSVGElement());
-        static_cast<const SVGElement*>(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
+
+        // FIXME: this code is called regardless of whether name is an
+        // animated SVG Attribute. It would seem we should only call this method
+        // if SVGElement::isAnimatableAttribute is true, but the list of
+        // animatable attributes in isAnimatableAttribute does not suffice to
+        // pass all layout tests. Also, m_animatedSVGAttributesAreDirty stays
+        // dirty unless synchronizeAnimatedSVGAttribute is called with
+        // anyQName(). This means that even if Element::synchronizeAttribute()
+        // is called on all attributes, m_animatedSVGAttributesAreDirty remains
+        // true.
+        toSVGElement(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
     }
 }
 
@@ -594,7 +591,7 @@
     return 0;
 }
 
-Element* Element::bindingsOffsetParent()
+Element* Element::offsetParentForBindings()
 {
     Element* element = offsetParent();
     if (!element || !element->isInShadowTree())
@@ -740,6 +737,27 @@
     }
 }
 
+void Element::setScrollLeft(const Dictionary& scrollOptionsHorizontal, ExceptionState& exceptionState)
+{
+    String scrollBehaviorString;
+    ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
+    if (scrollOptionsHorizontal.get("behavior", scrollBehaviorString)) {
+        if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
+            exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
+            return;
+        }
+    }
+
+    int position;
+    if (!scrollOptionsHorizontal.get("x", position)) {
+        exceptionState.throwTypeError("ScrollOptionsHorizontal must include an 'x' member.");
+        return;
+    }
+
+    // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
+    setScrollLeft(position);
+}
+
 void Element::setScrollTop(int newTop)
 {
     document().updateLayoutIgnorePendingStylesheets();
@@ -765,6 +783,27 @@
     }
 }
 
+void Element::setScrollTop(const Dictionary& scrollOptionsVertical, ExceptionState& exceptionState)
+{
+    String scrollBehaviorString;
+    ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
+    if (scrollOptionsVertical.get("behavior", scrollBehaviorString)) {
+        if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
+            exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
+            return;
+        }
+    }
+
+    int position;
+    if (!scrollOptionsVertical.get("y", position)) {
+        exceptionState.throwTypeError("ScrollOptionsVertical must include a 'y' member.");
+        return;
+    }
+
+    // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
+    setScrollTop(position);
+}
+
 int Element::scrollWidth()
 {
     document().updateLayoutIgnorePendingStylesheets();
@@ -885,7 +924,7 @@
 void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& exceptionState)
 {
     if (!Document::isValidName(localName)) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
+        exceptionState.throwDOMException(InvalidCharacterError, "'" + localName + "' is not a valid attribute name.");
         return;
     }
 
@@ -993,8 +1032,6 @@
         classAttributeChanged(newValue);
     } else if (name == HTMLNames::nameAttr) {
         setHasName(!newValue.isNull());
-    } else if (name == HTMLNames::pseudoAttr) {
-        shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
     }
 
     invalidateNodeListCachesInAncestors(&name, this);
@@ -1003,7 +1040,7 @@
     shouldInvalidateStyle |= !styleResolver;
 
     if (shouldInvalidateStyle)
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
 
     if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->handleAttributeChanged(name, this);
@@ -1043,77 +1080,27 @@
     return classStringHasClassName(newClassString.characters16(), length);
 }
 
-template<typename Checker>
-static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker)
-{
-    unsigned changedSize = changedClasses.size();
-    for (unsigned i = 0; i < changedSize; ++i) {
-        if (checker.hasSelectorForClass(changedClasses[i]))
-            return true;
-    }
-    return false;
-}
-
-template<typename Checker>
-static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
-{
-    if (!oldClasses.size())
-        return checkSelectorForClassChange(newClasses, checker);
-
-    // Class vectors tend to be very short. This is faster than using a hash table.
-    BitVector remainingClassBits;
-    remainingClassBits.ensureSize(oldClasses.size());
-
-    for (unsigned i = 0; i < newClasses.size(); ++i) {
-        bool found = false;
-        for (unsigned j = 0; j < oldClasses.size(); ++j) {
-            if (newClasses[i] == oldClasses[j]) {
-                // Mark each class that is still in the newClasses so we can skip doing
-                // an n^2 search below when looking for removals. We can't break from
-                // this loop early since a class can appear more than once.
-                remainingClassBits.quickSet(j);
-                found = true;
-            }
-        }
-        // Class was added.
-        if (!found && checker.hasSelectorForClass(newClasses[i]))
-            return true;
-    }
-
-    for (unsigned i = 0; i < oldClasses.size(); ++i) {
-        if (remainingClassBits.quickGet(i))
-            continue;
-        // Class was removed.
-        if (checker.hasSelectorForClass(oldClasses[i]))
-            return true;
-    }
-
-    return false;
-}
-
 void Element::classAttributeChanged(const AtomicString& newClassString)
 {
     StyleResolver* styleResolver = document().styleResolver();
     bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
-    bool shouldInvalidateStyle = false;
 
     if (classStringHasClassName(newClassString)) {
         const bool shouldFoldCase = document().inQuirksMode();
         const SpaceSplitString oldClasses = elementData()->classNames();
         elementData()->setClass(newClassString, shouldFoldCase);
         const SpaceSplitString& newClasses = elementData()->classNames();
-        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ensureRuleFeatureSet());
+        if (testShouldInvalidateStyle)
+            styleResolver->ensureRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, newClasses, this);
     } else {
         const SpaceSplitString& oldClasses = elementData()->classNames();
-        shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ensureRuleFeatureSet());
+        if (testShouldInvalidateStyle)
+            styleResolver->ensureRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, this);
         elementData()->clearClass();
     }
 
     if (hasRareData())
         elementRareData()->clearClassListValueForQuirksMode();
-
-    if (shouldInvalidateStyle)
-        setNeedsStyleRecalc();
 }
 
 bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
@@ -1138,11 +1125,11 @@
             const bool shouldFoldCase = document().inQuirksMode();
             const SpaceSplitString& oldClasses = elementData()->classNames();
             const SpaceSplitString newClasses(newClassString, shouldFoldCase);
-            if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
+            if (featureSet.checkSelectorsForClassChange(oldClasses, newClasses))
                 return true;
         } else {
             const SpaceSplitString& oldClasses = elementData()->classNames();
-            if (checkSelectorForClassChange(oldClasses, featureSet))
+            if (featureSet.checkSelectorsForClassChange(oldClasses))
                 return true;
         }
     }
@@ -1191,8 +1178,8 @@
     if (attributeVector.isEmpty())
         return;
 
-    if (document().sharedObjectPool())
-        m_elementData = document().sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
+    if (document().elementDataCache())
+        m_elementData = document().elementDataCache()->cachedShareableElementDataWithAttributes(attributeVector);
     else
         m_elementData = ShareableElementData::createWithAttributes(attributeVector);
 
@@ -1225,23 +1212,57 @@
     return m_tagName.toString();
 }
 
-String Element::nodeNamePreservingCase() const
-{
-    return m_tagName.toString();
-}
-
 void Element::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
 {
-    checkSetPrefix(prefix, exceptionState);
+    UseCounter::count(document(), UseCounter::ElementSetPrefix);
+
+    if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
+        exceptionState.throwDOMException(InvalidCharacterError, "The prefix '" + prefix + "' is not a valid name.");
+        return;
+    }
+
+    // FIXME: Raise NamespaceError if prefix is malformed per the Namespaces in XML specification.
+
+    const AtomicString& nodeNamespaceURI = namespaceURI();
+    if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
+        exceptionState.throwDOMException(NamespaceError, "No namespace is set, so a namespace prefix may not be set.");
+        return;
+    }
+
+    if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
+        exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'.");
+        return;
+    }
+
     if (exceptionState.hadException())
         return;
 
     m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
 }
 
+const AtomicString& Element::locateNamespacePrefix(const AtomicString& namespaceToLocate) const
+{
+    if (!prefix().isNull() && namespaceURI() == namespaceToLocate)
+        return prefix();
+
+    if (hasAttributes()) {
+        for (unsigned i = 0; i < attributeCount(); i++) {
+            const Attribute* attr = attributeItem(i);
+
+            if (attr->prefix() == xmlnsAtom && attr->value() == namespaceToLocate)
+                return attr->localName();
+        }
+    }
+
+    if (Element* parent = parentElement())
+        return parent->locateNamespacePrefix(namespaceToLocate);
+
+    return nullAtom;
+}
+
 KURL Element::baseURI() const
 {
-    const AtomicString& baseAttribute = getAttribute(baseAttr);
+    const AtomicString& baseAttribute = fastGetAttribute(baseAttr);
     KURL base(KURL(), baseAttribute);
     if (!base.protocol().isEmpty())
         return base;
@@ -1377,7 +1398,7 @@
             data->resetStyleState();
     }
 
-    NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
+    RenderTreeBuilder(this, context.resolvedStyle).createRendererForElementIfNeeded();
 
     addCallbackSelectors();
 
@@ -1403,29 +1424,25 @@
                 document().updateFocusAppearanceSoon(false /* don't restore selection */);
             data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
         }
+        if (!renderer()) {
+            if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
+                activeAnimations->cssAnimations().cancel();
+                activeAnimations->setAnimationStyleChange(false);
+            }
+        }
     }
 
     InspectorInstrumentation::didRecalculateStyleForElement(this);
 }
 
-void Element::unregisterNamedFlowContentNode()
-{
-    if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document().renderView())
-        document().renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
-}
-
 void Element::detach(const AttachContext& context)
 {
     RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
-    unregisterNamedFlowContentNode();
     cancelFocusAppearanceUpdate();
     removeCallbackSelectors();
     if (hasRareData()) {
         ElementRareData* data = elementRareData();
-        data->setPseudoElement(BEFORE, 0);
-        data->setPseudoElement(AFTER, 0);
-        data->setPseudoElement(BACKDROP, 0);
-        data->setIsInsideRegion(false);
+        data->clearPseudoElements();
 
         // attach() will perform the below steps for us when inside recalcStyle.
         if (!document().inStyleRecalc()) {
@@ -1434,19 +1451,23 @@
             data->resetDynamicRestyleObservations();
         }
 
-        if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
-            if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
-                if (context.performingReattach) {
-                    // FIXME: restart compositor animations rather than pull back to the main thread
-                    activeAnimations->cancelAnimationOnCompositor();
-                } else {
-                    activeAnimations->cssAnimations().cancel();
-                }
+        if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
+            if (context.performingReattach) {
+                // FIXME: We call detach from withing style recalc, so compositingState is not up to date.
+                // https://code.google.com/p/chromium/issues/detail?id=339847
+                DisableCompositingQueryAsserts disabler;
+
+                // FIXME: restart compositor animations rather than pull back to the main thread
+                activeAnimations->cancelAnimationOnCompositor();
+            } else {
+                activeAnimations->cssAnimations().cancel();
+                activeAnimations->setAnimationStyleChange(false);
             }
         }
+
+        if (ElementShadow* shadow = data->shadow())
+            shadow->detach(context);
     }
-    if (ElementShadow* shadow = this->shadow())
-        shadow->detach(context);
     ContainerNode::detach(context);
 }
 
@@ -1543,9 +1564,10 @@
     }
 
     // If we reattached we don't need to recalc the style of our descendants anymore.
-    if ((change >= Inherit && change < Reattach) || childNeedsStyleRecalc())
+    if ((change >= UpdatePseudoElements && change < Reattach) || childNeedsStyleRecalc()) {
         recalcChildStyle(change);
-    clearChildNeedsStyleRecalc();
+        clearChildNeedsStyleRecalc();
+    }
 
     if (hasCustomStyleCallbacks())
         didRecalcStyle(change);
@@ -1583,7 +1605,7 @@
 
     if (RenderObject* renderer = this->renderer()) {
         if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || shouldNotifyRendererWithIdenticalStyles()) {
-            renderer->setAnimatableStyle(newStyle.get());
+            renderer->setStyle(newStyle.get());
         } else {
             // Although no change occurred, we use the new style so that the cousin style sharing code won't get
             // fooled into believing this style is the same.
@@ -1593,68 +1615,67 @@
         }
     }
 
-    // If "rem" units are used anywhere in the document, and if the document element's font size changes, then go ahead and force font updating
-    // all the way down the tree. This is simpler than having to maintain a cache of objects (and such font size changes should be rare anyway).
-    if (document().styleEngine()->usesRemUnits() && document().documentElement() == this && oldStyle->fontSize() != newStyle->fontSize()) {
-        // Cached RenderStyles may depend on the re units.
-        document().ensureStyleResolver().invalidateMatchedPropertiesCache();
-        return Force;
-    }
-
     if (styleChangeType() >= SubtreeStyleChange)
         return Force;
 
-    return max(localChange, change);
+    if (change > Inherit || localChange > Inherit)
+        return max(localChange, change);
+
+    if (localChange < Inherit && (oldStyle->hasPseudoElementStyle() || newStyle->hasPseudoElementStyle()))
+        return UpdatePseudoElements;
+
+    return localChange;
 }
 
 void Element::recalcChildStyle(StyleRecalcChange change)
 {
     ASSERT(document().inStyleRecalc());
-    ASSERT(change >= Inherit || childNeedsStyleRecalc());
+    ASSERT(change >= UpdatePseudoElements || childNeedsStyleRecalc());
     ASSERT(!needsStyleRecalc());
 
     StyleResolverParentPusher parentPusher(*this);
 
-    for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
-        if (shouldRecalcStyle(change, root)) {
-            parentPusher.push();
-            root->recalcStyle(change);
+    if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
+        for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
+            if (root->shouldCallRecalcStyle(change)) {
+                parentPusher.push();
+                root->recalcStyle(change);
+            }
         }
     }
 
-    if (shouldRecalcStyle(change, this))
-        updatePseudoElement(BEFORE, change);
+    updatePseudoElement(BEFORE, change);
 
     if (change < Force && hasRareData() && childNeedsStyleRecalc())
         checkForChildrenAdjacentRuleChanges();
 
-    // This loop is deliberately backwards because we use insertBefore in the rendering tree, and want to avoid
-    // a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
-    // child and work our way back means in the common case, we'll find the insertion point in O(1) time.
-    // See crbug.com/288225
-    StyleResolver& styleResolver = document().ensureStyleResolver();
-    Text* lastTextNode = 0;
-    for (Node* child = lastChild(); child; child = child->previousSibling()) {
-        if (child->isTextNode()) {
-            toText(child)->recalcTextStyle(change, lastTextNode);
-            lastTextNode = toText(child);
-        } else if (child->isElementNode()) {
-            Element* element = toElement(child);
-            if (shouldRecalcStyle(change, element)) {
-                parentPusher.push();
-                element->recalcStyle(change, lastTextNode);
-            } else if (element->supportsStyleSharing()) {
-                styleResolver.addToStyleSharingList(*element);
+    if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
+        // This loop is deliberately backwards because we use insertBefore in the rendering tree, and want to avoid
+        // a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
+        // child and work our way back means in the common case, we'll find the insertion point in O(1) time.
+        // See crbug.com/288225
+        StyleResolver& styleResolver = document().ensureStyleResolver();
+        Text* lastTextNode = 0;
+        for (Node* child = lastChild(); child; child = child->previousSibling()) {
+            if (child->isTextNode()) {
+                toText(child)->recalcTextStyle(change, lastTextNode);
+                lastTextNode = toText(child);
+            } else if (child->isElementNode()) {
+                Element* element = toElement(child);
+                if (element->shouldCallRecalcStyle(change)) {
+                    parentPusher.push();
+                    element->recalcStyle(change, lastTextNode);
+                } else if (element->supportsStyleSharing()) {
+                    styleResolver.addToStyleSharingList(*element);
+                }
+                if (element->renderer())
+                    lastTextNode = 0;
             }
-            if (element->renderer())
-                lastTextNode = 0;
         }
     }
 
-    if (shouldRecalcStyle(change, this)) {
-        updatePseudoElement(AFTER, change);
-        updatePseudoElement(BACKDROP, change);
-    }
+    updatePseudoElement(AFTER, change);
+    updatePseudoElement(BACKDROP, change);
 }
 
 void Element::checkForChildrenAdjacentRuleChanges()
@@ -1675,7 +1696,7 @@
         bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
 
         if (forceCheckOfNextElementCount || forceCheckOfAnyElementSibling)
-            element->setNeedsStyleRecalc();
+            element->setNeedsStyleRecalc(SubtreeStyleChange);
 
         if (forceCheckOfNextElementCount)
             forceCheckOfNextElementCount--;
@@ -1720,7 +1741,7 @@
 
 void Element::didAffectSelector(AffectedSelectorMask mask)
 {
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
     if (ElementShadow* elementShadow = shadowWhereNodeCanBeDistributed(*this))
         elementShadow->didAffectSelector(mask);
 }
@@ -1736,7 +1757,7 @@
     if (styleChangeType() != NoStyleChange)
         return;
 
-    setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+    setNeedsStyleRecalc(LocalStyleChange);
     setAnimationStyleChange(true);
 }
 
@@ -1745,16 +1766,14 @@
     if (alwaysCreateUserAgentShadowRoot())
         ensureUserAgentShadowRoot();
 
-    if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
-        return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
-
-    // Since some elements recreates shadow root dynamically, multiple shadow
-    // subtrees won't work well in that element. Until they are fixed, we disable
-    // adding author shadow root for them.
-    if (!areAuthorShadowsAllowed()) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+    // Some elements make assumptions about what kind of renderers they allow
+    // as children so we can't allow author shadows on them for now. An override
+    // flag is provided for testing how author shadows interact on these elements.
+    if (!areAuthorShadowsAllowed() && !RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled()) {
+        exceptionState.throwDOMException(HierarchyRequestError, "Author-created shadow roots are disabled for this element.");
         return 0;
     }
+
     return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
 }
 
@@ -1815,7 +1834,7 @@
         return;
 
     if (!style || (styleAffectedByEmpty() && (!style->emptyState() || hasChildNodes())))
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 void Element::checkForSiblingStyleChanges(bool finishedParsingCallback, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -1839,7 +1858,7 @@
     // For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids
     // here. recalcStyle will then force a walk of the children when it sees that this has happened.
     if ((childrenAffectedByForwardPositionalRules() && afterChange) || (childrenAffectedByBackwardPositionalRules() && beforeChange)) {
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
         return;
     }
 
@@ -1848,47 +1867,47 @@
     // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
     if (childrenAffectedByFirstChildRules() && afterChange) {
         // Find our new first child.
-        Node* newFirstChild = firstElementChild();
+        Element* newFirstChild = ElementTraversal::firstWithin(*this);
         RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
 
         // Find the first element node following |afterChange|
-        Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling();
+        Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : ElementTraversal::nextSibling(*afterChange);
         RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
 
         // This is the insert/append case.
         if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
-            firstElementAfterInsertion->setNeedsStyleRecalc();
+            firstElementAfterInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
 
         // We also have to handle node removal.
         if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
-            newFirstChild->setNeedsStyleRecalc();
+            newFirstChild->setNeedsStyleRecalc(SubtreeStyleChange);
     }
 
     // :last-child.  In the parser callback case, we don't have to check anything, since we were right the first time.
     // In the DOM case, we only need to do something if |afterChange| is not 0.
     if (childrenAffectedByLastChildRules() && beforeChange) {
         // Find our new last child.
-        Node* newLastChild = lastElementChild();
+        Node* newLastChild = ElementTraversal::lastWithin(*this);
         RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
 
         // Find the last element node going backwards from |beforeChange|
-        Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : beforeChange->previousElementSibling();
+        Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : ElementTraversal::previousSibling(*beforeChange);
         RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
 
         if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
-            lastElementBeforeInsertion->setNeedsStyleRecalc();
+            lastElementBeforeInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
 
         // We also have to handle node removal.  The parser callback case is similar to node removal as well in that we need to change the last child
         // to match now.
         if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
-            newLastChild->setNeedsStyleRecalc();
+            newLastChild->setNeedsStyleRecalc(SubtreeStyleChange);
     }
 
     // The + selector.  We need to invalidate the first element following the insertion point.  It is the only possible element
     // that could be affected by this DOM change.
     if (childrenAffectedByDirectAdjacentRules() && afterChange) {
-        if (Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling())
-            firstElementAfterInsertion->setNeedsStyleRecalc();
+        if (Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : ElementTraversal::nextSibling(*afterChange))
+            firstElementAfterInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
     }
 }
 
@@ -1911,14 +1930,9 @@
         shadow->removeAllEventListeners();
 }
 
-void Element::beginParsingChildren()
-{
-    clearIsParsingChildrenFinished();
-}
-
 void Element::finishParsingChildren()
 {
-    setIsParsingChildrenFinished();
+    setIsFinishedParsingChildren(true);
     checkForSiblingStyleChanges(this, lastChild(), 0, 0);
 }
 
@@ -1959,7 +1973,7 @@
 PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& exceptionState)
 {
     if (!attrNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The node provided is invalid.");
         return 0;
     }
 
@@ -1970,7 +1984,7 @@
     // InUseAttributeError: Raised if node is an Attr that is already an attribute of another Element object.
     // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
     if (attrNode->ownerElement()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InUseAttributeError);
+        exceptionState.throwDOMException(InUseAttributeError, "The node provided is an attribute node that is already an attribute of another Element; attribute nodes must be explicitly cloned.");
         return 0;
     }
 
@@ -1994,19 +2008,14 @@
     return oldAttrNode.release();
 }
 
-PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& exceptionState)
-{
-    return setAttributeNode(attr, exceptionState);
-}
-
 PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& exceptionState)
 {
     if (!attr) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The node provided is invalid.");
         return 0;
     }
     if (attr->ownerElement() != this) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided is owned by another element.");
         return 0;
     }
 
@@ -2016,7 +2025,7 @@
 
     size_t index = elementData()->getAttrIndex(attr);
     if (index == kNotFound) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The attribute was not found on this element.");
         return 0;
     }
 
@@ -2035,7 +2044,7 @@
     QualifiedName qName(prefix, localName, namespaceURI);
 
     if (!Document::hasValidNamespaceForAttributes(qName)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
+        exceptionState.throwDOMException(NamespaceError, "'" + namespaceURI + "' is an invalid namespace for attributes.");
         return false;
     }
 
@@ -2144,7 +2153,7 @@
     return elementData()->getAttributeItem(qName);
 }
 
-void Element::focus(bool restorePreviousSelection, FocusDirection direction)
+void Element::focus(bool restorePreviousSelection, FocusType type)
 {
     if (!inDocument())
         return;
@@ -2171,7 +2180,7 @@
         // If a focus event handler changes the focus to a different node it
         // does not make sense to continue and update appearence.
         protect = this;
-        if (!page->focusController().setFocusedElement(this, doc.frame(), direction))
+        if (!page->focusController().setFocusedElement(this, doc.frame(), type))
             return;
     }
 
@@ -2233,7 +2242,7 @@
     return isFocusable();
 }
 
-void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
+void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusType)
 {
     RefPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::focus, false, false, document().domWindow(), 0, oldFocusedElement);
     EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
@@ -2282,10 +2291,15 @@
 void Element::setOuterHTML(const String& html, ExceptionState& exceptionState)
 {
     Node* p = parentNode();
-    if (!p || !p->isElementNode()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    if (!p) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "This element has no parent node.");
         return;
     }
+    if (!p->isElementNode()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "This element's parent is of type '" + p->nodeName() + "', which is not an element node.");
+        return;
+    }
+
     RefPtr<Element> parent = toElement(p);
     RefPtr<Node> prev = previousSibling();
     RefPtr<Node> next = nextSibling();
@@ -2354,6 +2368,24 @@
     return 0;
 }
 
+Element* Element::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& exceptionState)
+{
+    if (!newChild) {
+        // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
+        exceptionState.throwTypeError("The node provided is null.");
+        return 0;
+    }
+
+    Node* returnValue = insertAdjacent(where, newChild, exceptionState);
+    return toElement(returnValue);
+}
+
+void Element::insertAdjacentText(const String& where, const String& text, ExceptionState& exceptionState)
+{
+    RefPtr<Text> textNode = document().createTextNode(text);
+    insertAdjacent(where, textNode.get(), exceptionState);
+}
+
 void Element::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& exceptionState)
 {
     RefPtr<Element> contextElement = contextElementForInsertion(where, this, exceptionState);
@@ -2427,15 +2459,19 @@
     return content.toString();
 }
 
-// pseudo is used via shadowPseudoId.
-const AtomicString& Element::pseudo() const
+const AtomicString& Element::shadowPseudoId() const
 {
-    return getAttribute(pseudoAttr);
+    if (ShadowRoot* root = containingShadowRoot()) {
+        if (root->type() == ShadowRoot::UserAgentShadowRoot)
+            return fastGetAttribute(pseudoAttr);
+    }
+    return nullAtom;
 }
 
-void Element::setPseudo(const AtomicString& value)
+void Element::setShadowPseudoId(const AtomicString& id)
 {
-    setAttribute(pseudoAttr, value);
+    ASSERT(CSSSelector::parsePseudoType(id) == CSSSelector::PseudoWebKitCustomElement || CSSSelector::parsePseudoType(id) == CSSSelector::PseudoUserAgentCustomElement);
+    setAttribute(pseudoAttr, id);
 }
 
 bool Element::isInDescendantTreeOf(const Element* shadowHost) const
@@ -2641,29 +2677,6 @@
     return hasRareData() && elementRareData()->isInCanvasSubtree();
 }
 
-void Element::setIsInsideRegion(bool value)
-{
-    if (value == isInsideRegion())
-        return;
-
-    ensureElementRareData().setIsInsideRegion(value);
-}
-
-bool Element::isInsideRegion() const
-{
-    return hasRareData() ? elementRareData()->isInsideRegion() : false;
-}
-
-void Element::setRegionOversetState(RegionOversetState state)
-{
-    ensureElementRareData().setRegionOversetState(state);
-}
-
-RegionOversetState Element::regionOversetState() const
-{
-    return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
-}
-
 AtomicString Element::computeInheritedLanguage() const
 {
     const Node* n = this;
@@ -2714,8 +2727,10 @@
 
 void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
 {
+    ASSERT(!needsStyleRecalc());
     PseudoElement* element = pseudoElement(pseudoId);
-    if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
+    if (element && (change == UpdatePseudoElements || element->shouldCallRecalcStyle(change))) {
+
         // Need to clear the cached style if the PseudoElement wants a recalc so it
         // computes a new style.
         if (element->needsStyleRecalc())
@@ -2724,7 +2739,7 @@
         // PseudoElement styles hang off their parent element's style so if we needed
         // a style recalc we should Force one on the pseudo.
         // FIXME: We should figure out the right text sibling to pass.
-        element->recalcStyle(needsStyleRecalc() ? Force : change);
+        element->recalcStyle(change == UpdatePseudoElements ? Force : change);
 
         // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
         // is false, otherwise we could continously create and destroy PseudoElements
@@ -2732,32 +2747,20 @@
         // PseudoElement's renderer for each style recalc.
         if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
             elementRareData()->setPseudoElement(pseudoId, 0);
-    } else if (change >= Inherit || needsStyleRecalc())
+    } else if (change >= UpdatePseudoElements) {
         createPseudoElementIfNeeded(pseudoId);
+    }
 }
 
 void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
 {
-    if (needsPseudoElement(pseudoId))
-        createPseudoElement(pseudoId);
-}
+    if (isPseudoElement())
+        return;
 
-bool Element::needsPseudoElement(PseudoId pseudoId) const
-{
-    if (pseudoId == BACKDROP && !isInTopLayer())
-        return false;
-    if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
-        return false;
-    if (!renderer()->canHaveGeneratedChildren())
-        return false;
-    return true;
-}
+    RefPtr<PseudoElement> element = document().ensureStyleResolver().createPseudoElementIfNeeded(*this, pseudoId);
+    if (!element)
+        return;
 
-void Element::createPseudoElement(PseudoId pseudoId)
-{
-    ASSERT(needsPseudoElement(pseudoId));
-    ASSERT(!isPseudoElement());
-    RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
     if (pseudoId == BACKDROP)
         document().addToTopLayer(element.get(), this);
     element->insertedInto(this);
@@ -2780,14 +2783,9 @@
     return 0;
 }
 
-bool Element::webkitMatchesSelector(const String& selector, ExceptionState& exceptionState)
+bool Element::matches(const String& selectors, ExceptionState& exceptionState)
 {
-    if (selector.isEmpty()) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
-        return false;
-    }
-
-    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selector, document(), exceptionState);
+    SelectorQuery* selectorQuery = document().selectorQueryCache().add(AtomicString(selectors), document(), exceptionState);
     if (!selectorQuery)
         return false;
     return selectorQuery->matches(*this);
@@ -2851,6 +2849,11 @@
 
 void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
 {
+    // Range restrictions are enforced for unsigned IDL attributes that
+    // reflect content attributes,
+    //   http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
+    if (value > 0x7fffffffu)
+        value = 0;
     setAttribute(attributeName, AtomicString::number(value));
 }
 
@@ -2864,15 +2867,6 @@
     setAttribute(attributeName, AtomicString::number(value));
 }
 
-bool Element::childShouldCreateRenderer(const Node& child) const
-{
-    // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
-    if (child.isSVGElement())
-        return child.hasTagName(SVGNames::svgTag) || isSVGElement();
-
-    return ContainerNode::childShouldCreateRenderer(child);
-}
-
 void Element::webkitRequestFullscreen()
 {
     FullscreenElementStack::from(&document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
@@ -2931,7 +2925,7 @@
 
 SpellcheckAttributeState Element::spellcheckAttributeState() const
 {
-    const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
+    const AtomicString& value = fastGetAttribute(spellcheckAttr);
     if (value == nullAtom)
         return SpellcheckAttributeDefault;
     if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
@@ -2958,79 +2952,6 @@
     return true;
 }
 
-RenderRegion* Element::renderRegion() const
-{
-    if (renderer() && renderer()->isRenderNamedFlowFragmentContainer())
-        return toRenderBlockFlow(renderer())->renderNamedFlowFragment();
-
-    return 0;
-}
-
-bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
-{
-    ASSERT(styleToUse);
-
-    if (FullscreenElementStack::isActiveFullScreenElement(this))
-        return false;
-
-    if (isInShadowTree())
-        return false;
-
-    if (styleToUse->flowThread().isEmpty())
-        return false;
-
-    return !isRegisteredWithNamedFlow();
-}
-
-const AtomicString& Element::webkitRegionOverset() const
-{
-    DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled())
-        return undefinedState;
-
-    document().updateLayoutIgnorePendingStylesheets();
-
-    if (!renderRegion())
-        return undefinedState;
-
-    switch (renderRegion()->regionOversetState()) {
-    case RegionFit: {
-        DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
-        return fitState;
-    }
-    case RegionEmpty: {
-        DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
-        return emptyState;
-    }
-    case RegionOverset: {
-        DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
-        return overflowState;
-    }
-    case RegionUndefined:
-        return undefinedState;
-    }
-
-    ASSERT_NOT_REACHED();
-    return undefinedState;
-}
-
-Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
-{
-    Vector<RefPtr<Range> > rangeObjects;
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled())
-        return rangeObjects;
-
-    document().updateLayoutIgnorePendingStylesheets();
-
-    if (renderer() && renderer()->isRenderNamedFlowFragmentContainer()) {
-        RenderNamedFlowFragment* region = toRenderBlockFlow(renderer())->renderNamedFlowFragment();
-        if (region->isValid())
-            region->getRanges(rangeObjects);
-    }
-
-    return rangeObjects;
-}
-
 #ifndef NDEBUG
 bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
 {
@@ -3038,7 +2959,7 @@
         return false;
 
     if (isSVGElement())
-        return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
+        return !toSVGElement(this)->isAnimatableAttribute(name);
 
     return true;
 }
@@ -3123,7 +3044,7 @@
 
     if (oldValue != newValue) {
         if (inActiveDocument() && hasSelectorForAttribute(&document(), name.localName()))
-           setNeedsStyleRecalc();
+            setNeedsStyleRecalc(SubtreeStyleChange);
 
         if (isUpgradedCustomElement())
             CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
@@ -3200,18 +3121,17 @@
     if (HTMLCollection* collection = cachedHTMLCollection(type))
         return collection;
 
-    RefPtr<HTMLCollection> collection;
     if (type == TableRows) {
         ASSERT(hasTagName(tableTag));
-        return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
+        return ensureRareData().ensureNodeLists().addCache<HTMLTableRowsCollection>(this, type);
     } else if (type == SelectOptions) {
         ASSERT(hasTagName(selectTag));
-        return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
+        return ensureRareData().ensureNodeLists().addCache<HTMLOptionsCollection>(this, type);
     } else if (type == FormControls) {
         ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
-        return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
+        return ensureRareData().ensureNodeLists().addCache<HTMLFormControlsCollection>(this, type);
     }
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, type);
+    return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(this, type);
 }
 
 static void scheduleLayerUpdateCallback(Node* node)
@@ -3231,7 +3151,7 @@
 
 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
 {
-    return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
+    return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cached<HTMLCollection>(type) : 0;
 }
 
 IntSize Element::savedLayerScrollOffset() const
@@ -3343,12 +3263,10 @@
         ownerDocumentsHaveDifferentCaseSensitivity = other.document().inQuirksMode() != document().inQuirksMode();
 
     // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
-    // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
-    // and sharing the data won't result in different case sensitivity of class or id.
+    // We can only do this if there are no presentation attributes and sharing the data won't result in different case sensitivity of class or id.
     if (other.m_elementData->isUnique()
         && !ownerDocumentsHaveDifferentCaseSensitivity
-        && !other.m_elementData->presentationAttributeStyle()
-        && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
+        && !other.m_elementData->presentationAttributeStyle())
         const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
 
     if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
@@ -3409,15 +3327,16 @@
     ASSERT(elementData());
     ASSERT(elementData()->m_styleAttributeIsDirty);
     elementData()->m_styleAttributeIsDirty = false;
-    if (const StylePropertySet* inlineStyle = this->inlineStyle())
-        const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
+    const StylePropertySet* inlineStyle = this->inlineStyle();
+    const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr,
+        inlineStyle ? AtomicString(inlineStyle->asText()) : nullAtom);
 }
 
 CSSStyleDeclaration* Element::style()
 {
     if (!isStyledElement())
         return 0;
-    return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
+    return ensureElementRareData().ensureInlineCSSStyleDeclaration(this);
 }
 
 MutableStylePropertySet* Element::ensureMutableInlineStyle()
@@ -3433,13 +3352,11 @@
     return toMutableStylePropertySet(inlineStyle);
 }
 
-PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
+void Element::clearMutableInlineStyleIfEmpty()
 {
-    if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
-        return 0;
-    PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
-    ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
-    return cssomWrapper;
+    if (ensureMutableInlineStyle()->isEmpty()) {
+        ensureUniqueElementData()->m_inlineStyle.clear();
+    }
 }
 
 inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
@@ -3457,7 +3374,7 @@
         inlineStyle.clear();
 
     if (!inlineStyle) {
-        inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
+        inlineStyle = BisonCSSParser::parseInlineStyleDeclaration(newStyleString, this);
     } else {
         ASSERT(inlineStyle->isMutable());
         static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document().elementSheet()->contents());
@@ -3472,8 +3389,6 @@
         startLineNumber = document().scriptableDocumentParser()->lineNumber();
 
     if (newStyleString.isNull()) {
-        if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
-            cssomWrapper->clearParentElement();
         ensureUniqueElementData()->m_inlineStyle.clear();
     } else if (modificationReason == ModifiedByCloning || document().contentSecurityPolicy()->allowInlineStyle(document().url(), startLineNumber)) {
         setInlineStyleFromString(newStyleString);
@@ -3541,19 +3456,12 @@
 void Element::removeAllInlineStyleProperties()
 {
     ASSERT(isStyledElement());
-    if (!inlineStyle() || inlineStyle()->isEmpty())
+    if (!inlineStyle())
         return;
     ensureMutableInlineStyle()->clear();
     inlineStyleChanged();
 }
 
-void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    ASSERT(isStyledElement());
-    if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
-        inlineStyle->addSubresourceStyleURLs(urls, document().elementSheet()->contents());
-}
-
 void Element::updatePresentationAttributeStyle()
 {
     // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
@@ -3582,7 +3490,7 @@
 
 bool Element::supportsStyleSharing() const
 {
-    if (!isStyledElement() || !parentElement())
+    if (!isStyledElement() || !parentOrShadowHostElement())
         return false;
     // If the element has inline style it is probably unique.
     if (inlineStyle())
@@ -3600,7 +3508,7 @@
         return false;
     if (focused())
         return false;
-    if (!parentElement()->childrenSupportStyleSharing())
+    if (!parentOrShadowHostElement()->childrenSupportStyleSharing())
         return false;
     if (hasScopedHTMLStyleChild())
         return false;
@@ -3610,8 +3518,6 @@
         return false;
     if (hasActiveAnimations())
         return false;
-    if (shadow() && shadow()->containsActiveStyles())
-        return false;
     // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
     // See comments in RenderObject::setStyle().
     // FIXME: Why does gaining a layer from outside the style system require disabling sharing?
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index eca5712..742ebf4 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -33,8 +33,7 @@
 #include "core/dom/ElementData.h"
 #include "core/dom/SpaceSplitString.h"
 #include "core/html/CollectionType.h"
-#include "core/page/FocusDirection.h"
-#include "core/rendering/RegionOversetState.h"
+#include "core/page/FocusType.h"
 #include "platform/scroll/ScrollTypes.h"
 
 namespace WebCore {
@@ -56,7 +55,6 @@
 class MutableStylePropertySet;
 class PropertySetCSSStyleDeclaration;
 class PseudoElement;
-class RenderRegion;
 class ShadowRoot;
 class StylePropertySet;
 
@@ -100,8 +98,11 @@
 
     bool hasAttribute(const QualifiedName&) const;
     const AtomicString& getAttribute(const QualifiedName&) const;
+
+    // Passing nullAtom as the second parameter removes the attribute when calling either of these set methods.
     void setAttribute(const QualifiedName&, const AtomicString& value);
     void setSynchronizedLazyAttribute(const QualifiedName&, const AtomicString& value);
+
     void removeAttribute(const QualifiedName&);
 
     // Typed getters and setters for language bindings.
@@ -172,8 +173,8 @@
     int offsetHeight();
 
     // FIXME: Replace uses of offsetParent in the platform with calls
-    // to the render layer and merge bindingsOffsetParent and offsetParent.
-    Element* bindingsOffsetParent();
+    // to the render layer and merge offsetParentForBindings and offsetParent.
+    Element* offsetParentForBindings();
 
     Element* offsetParent();
     int clientLeft();
@@ -183,7 +184,9 @@
     virtual int scrollLeft();
     virtual int scrollTop();
     virtual void setScrollLeft(int);
+    virtual void setScrollLeft(const Dictionary& scrollOptionsHorizontal, ExceptionState&);
     virtual void setScrollTop(int);
+    virtual void setScrollTop(const Dictionary& scrollOptionsVertical, ExceptionState&);
     virtual int scrollWidth();
     virtual int scrollHeight();
 
@@ -205,7 +208,6 @@
     PassRefPtr<Attr> getAttributeNode(const AtomicString& name);
     PassRefPtr<Attr> getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName);
     PassRefPtr<Attr> setAttributeNode(Attr*, ExceptionState&);
-    PassRefPtr<Attr> setAttributeNodeNS(Attr*, ExceptionState&);
     PassRefPtr<Attr> removeAttributeNode(Attr*, ExceptionState&);
 
     PassRefPtr<Attr> attrIfExists(const QualifiedName&);
@@ -226,13 +228,15 @@
     bool hasLocalName(const AtomicString& other) const { return m_tagName.localName() == other; }
     bool hasLocalName(const QualifiedName& other) const { return m_tagName.localName() == other.localName(); }
 
-    virtual const AtomicString& localName() const OVERRIDE { return m_tagName.localName(); }
-    virtual const AtomicString& prefix() const OVERRIDE { return m_tagName.prefix(); }
-    virtual const AtomicString& namespaceURI() const OVERRIDE { return m_tagName.namespaceURI(); }
+    virtual const AtomicString& localName() const OVERRIDE FINAL { return m_tagName.localName(); }
+    const AtomicString& prefix() const { return m_tagName.prefix(); }
+    virtual const AtomicString& namespaceURI() const OVERRIDE FINAL { return m_tagName.namespaceURI(); }
+
+    const AtomicString& locateNamespacePrefix(const AtomicString& namespaceURI) const;
 
     virtual KURL baseURI() const OVERRIDE FINAL;
 
-    virtual String nodeName() const;
+    virtual String nodeName() const OVERRIDE;
 
     PassRefPtr<Element> cloneElementWithChildren();
     PassRefPtr<Element> cloneElementWithoutChildren();
@@ -240,7 +244,6 @@
     void scheduleLayerUpdate();
 
     void normalizeAttributes();
-    String nodeNamePreservingCase() const;
 
     void setBooleanAttribute(const QualifiedName& name, bool);
 
@@ -316,7 +319,6 @@
     virtual void didAddShadowRoot(ShadowRoot&);
     ShadowRoot* userAgentShadowRoot() const;
     ShadowRoot& ensureUserAgentShadowRoot();
-    const AtomicString& shadowPseudoId() const;
     bool isInDescendantTreeOf(const Element* shadowHost) const;
 
     RenderStyle* computedStyle(PseudoId = NOPSEUDO);
@@ -355,12 +357,6 @@
     bool isUpgradedCustomElement() { return customElementState() == Upgraded; }
     bool isUnresolvedCustomElement() { return customElementState() == WaitingForUpgrade; }
 
-    void setIsInsideRegion(bool);
-    bool isInsideRegion() const;
-
-    void setRegionOversetState(RegionOversetState);
-    RegionOversetState regionOversetState() const;
-
     AtomicString computeInheritedLanguage() const;
     Locale& locale() const;
 
@@ -373,10 +369,9 @@
     KURL getNonEmptyURLAttribute(const QualifiedName&) const;
 
     virtual const AtomicString imageSourceURL() const;
-    virtual String target() const { return String(); }
     virtual Image* imageContents() { return 0; }
 
-    virtual void focus(bool restorePreviousSelection = true, FocusDirection = FocusDirectionNone);
+    virtual void focus(bool restorePreviousSelection = true, FocusType = FocusTypeNone);
     virtual void updateFocusAppearance(bool restorePreviousSelection);
     virtual void blur();
     // Whether this element can receive focus at all. Most elements are not
@@ -388,7 +383,7 @@
     bool isFocusable() const;
     virtual bool isKeyboardFocusable() const;
     virtual bool isMouseFocusable() const;
-    virtual void dispatchFocusEvent(Element* oldFocusedElement, FocusDirection);
+    virtual void dispatchFocusEvent(Element* oldFocusedElement, FocusType);
     virtual void dispatchBlurEvent(Element* newFocusedElement);
     void dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement);
     void dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement);
@@ -399,14 +394,17 @@
     String outerHTML() const;
     void setInnerHTML(const String&, ExceptionState&);
     void setOuterHTML(const String&, ExceptionState&);
+
+    Element* insertAdjacentElement(const String& where, Element* newChild, ExceptionState&);
+    void insertAdjacentText(const String& where, const String& text, ExceptionState&);
     void insertAdjacentHTML(const String& where, const String& html, ExceptionState&);
 
     String textFromChildren();
 
     virtual String title() const { return String(); }
 
-    virtual const AtomicString& pseudo() const;
-    void setPseudo(const AtomicString&);
+    virtual const AtomicString& shadowPseudoId() const;
+    void setShadowPseudoId(const AtomicString&);
 
     LayoutSize minimumSizeForResizing() const;
     void setMinimumSizeForResizing(const LayoutSize&);
@@ -414,16 +412,24 @@
     virtual void didBecomeFullscreenElement() { }
     virtual void willStopBeingFullscreenElement() { }
 
-    bool isFinishedParsingChildren() const { return isParsingChildrenFinished(); }
+    using Node::isFinishedParsingChildren; // make public for SelectorChecker
+
+    // Called by the parser when this element's close tag is reached,
+    // signaling that all child tags have been parsed and added.
+    // This is needed for <applet> and <object> elements, which can't lay themselves out
+    // until they know all of their nested <param>s. [Radar 3603191, 4040848].
+    // Also used for script elements and some SVG elements for similar purposes,
+    // but making parsing a special case in this respect should be avoided if possible.
     virtual void finishParsingChildren();
-    virtual void beginParsingChildren() OVERRIDE FINAL;
+
+    void beginParsingChildren() { setIsFinishedParsingChildren(false); }
 
     PseudoElement* pseudoElement(PseudoId) const;
     RenderObject* pseudoElementRenderer(PseudoId) const;
 
     virtual bool matchesReadOnlyPseudoClass() const { return false; }
     virtual bool matchesReadWritePseudoClass() const { return false; }
-    bool webkitMatchesSelector(const String& selectors, ExceptionState&);
+    bool matches(const String& selectors, ExceptionState&);
     virtual bool shouldAppearIndeterminate() const { return false; }
 
     DOMTokenList* classList();
@@ -455,22 +461,12 @@
     virtual bool isPasswordGeneratorButtonElement() const { return false; }
     virtual bool isClearButtonElement() const { return false; }
 
-    virtual bool canContainRangeEndPoint() const { return true; }
-
-    virtual const AtomicString& formControlType() const { return nullAtom; }
-
-    // FIXME: Only HTMLInputElement uses these, they don't need to be virtual.
-    virtual bool wasChangedSinceLastFormControlChangeEvent() const { return false; }
-    virtual void setChangedSinceLastFormControlChangeEvent(bool) { }
-    virtual void dispatchFormControlChangeEvent() { }
+    virtual bool canContainRangeEndPoint() const OVERRIDE { return true; }
 
     // Used for disabled form elements; if true, prevents mouse events from being dispatched
     // to event listeners, and prevents DOMActivate events from being sent at all.
     virtual bool isDisabledFormControl() const { return false; }
 
-    virtual bool shouldBeReparentedUnderRenderView(const RenderStyle*) const { return isInTopLayer(); }
-
-    virtual bool childShouldCreateRenderer(const Node& child) const;
     bool hasPendingResources() const;
     void setHasPendingResources();
     void clearHasPendingResources();
@@ -496,14 +492,9 @@
 
     bool isSpellCheckingEnabled() const;
 
-    // FIXME: public for NodeRenderingContext, we shouldn't expose this though.
+    // FIXME: public for RenderTreeBuilder, we shouldn't expose this though.
     PassRefPtr<RenderStyle> styleForRenderer();
 
-    RenderRegion* renderRegion() const;
-    virtual bool shouldMoveToFlowThread(RenderStyle*) const;
-    const AtomicString& webkitRegionOverset() const;
-    Vector<RefPtr<Range> > webkitGetRegionFlowRanges() const;
-
     bool hasID() const;
     bool hasClass() const;
     const SpaceSplitString& classNames() const;
@@ -518,10 +509,13 @@
     InputMethodContext* inputMethodContext();
     bool hasInputMethodContext() const;
 
-    virtual void setPrefix(const AtomicString&, ExceptionState&) OVERRIDE FINAL;
+    void setPrefix(const AtomicString&, ExceptionState&);
 
     void synchronizeAttribute(const AtomicString& localName) const;
 
+    MutableStylePropertySet* ensureMutableInlineStyle();
+    void clearMutableInlineStyleIfEmpty();
+
 protected:
     Element(const QualifiedName& tagName, Document* document, ConstructionType type)
         : ContainerNode(document, type)
@@ -534,8 +528,6 @@
     void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes);
     void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, const String& value);
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
@@ -577,7 +569,6 @@
     void inlineStyleChanged();
     PropertySetCSSStyleDeclaration* inlineStyleCSSOMWrapper();
     void setInlineStyleFromString(const AtomicString&);
-    MutableStylePropertySet* ensureMutableInlineStyle();
 
     StyleRecalcChange recalcOwnStyle(StyleRecalcChange);
     void recalcChildStyle(StyleRecalcChange);
@@ -591,8 +582,6 @@
     void updatePseudoElement(PseudoId, StyleRecalcChange);
 
     inline void createPseudoElementIfNeeded(PseudoId);
-    inline bool needsPseudoElement(PseudoId) const;
-    void createPseudoElement(PseudoId);
 
     // FIXME: Everyone should allow author shadows.
     virtual bool areAuthorShadowsAllowed() const { return true; }
@@ -627,14 +616,14 @@
     void attributeChangedFromParserOrByCloning(const QualifiedName&, const AtomicString&, AttributeModificationReason);
 
 #ifndef NDEBUG
-    virtual void formatForDebugger(char* buffer, unsigned length) const;
+    virtual void formatForDebugger(char* buffer, unsigned length) const OVERRIDE;
 #endif
 
     bool pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle);
 
     void cancelFocusAppearanceUpdate();
 
-    virtual RenderStyle* virtualComputedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) { return computedStyle(pseudoElementSpecifier); }
+    virtual RenderStyle* virtualComputedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) OVERRIDE { return computedStyle(pseudoElementSpecifier); }
 
     inline void updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle);
     inline void removeCallbackSelectors();
@@ -663,8 +652,6 @@
     void updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName);
     void updateExtraNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName);
 
-    void unregisterNamedFlowContentNode();
-
     void createUniqueElementData();
 
     bool shouldInvalidateDistributionWhenAttributeChanged(ElementShadow*, const QualifiedName&, const AtomicString&);
@@ -699,22 +686,6 @@
     return parent && parent->isElementNode() ? toElement(parent) : 0;
 }
 
-inline Element* Node::previousElementSibling() const
-{
-    Node* n = previousSibling();
-    while (n && !n->isElementNode())
-        n = n->previousSibling();
-    return toElement(n);
-}
-
-inline Element* Node::nextElementSibling() const
-{
-    Node* n = nextSibling();
-    while (n && !n->isElementNode())
-        n = n->nextSibling();
-    return toElement(n);
-}
-
 inline bool Element::fastHasAttribute(const QualifiedName& name) const
 {
     ASSERT(fastAttributeLookupAllowed(name));
@@ -742,23 +713,18 @@
     return elementData()->idForStyleResolution();
 }
 
-inline const AtomicString& Element::shadowPseudoId() const
-{
-    return pseudo();
-}
-
 inline bool Element::isIdAttributeName(const QualifiedName& attributeName) const
 {
     // FIXME: This check is probably not correct for the case where the document has an id attribute
     // with a non-null namespace, because it will return false, a false negative, if the prefixes
     // don't match but the local name and namespace both do. However, since this has been like this
     // for a while and the code paths may be hot, we'll have to measure performance if we fix it.
-    return attributeName == document().idAttributeName();
+    return attributeName == HTMLNames::idAttr;
 }
 
 inline const AtomicString& Element::getIdAttribute() const
 {
-    return hasID() ? fastGetAttribute(document().idAttributeName()) : nullAtom;
+    return hasID() ? fastGetAttribute(HTMLNames::idAttr) : nullAtom;
 }
 
 inline const AtomicString& Element::getNameAttribute() const
@@ -782,7 +748,7 @@
 
 inline void Element::setIdAttribute(const AtomicString& value)
 {
-    setAttribute(document().idAttributeName(), value);
+    setAttribute(HTMLNames::idAttr, value);
 }
 
 inline const SpaceSplitString& Element::classNames() const
@@ -855,7 +821,7 @@
     ASSERT(insertionPoint->inDocument() || isContainerNode());
     if (insertionPoint->inDocument())
         clearFlag(InDocumentFlag);
-    if (isInShadowTree() && !treeScope().rootNode()->isShadowRoot())
+    if (isInShadowTree() && !treeScope().rootNode().isShadowRoot())
         clearFlag(IsInShadowTreeFlag);
 }
 
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index b839383..a715874 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -26,55 +26,56 @@
 
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString tagName;
 
-    [TreatReturnedNullStringAs=Null] DOMString getAttribute([Default=Undefined] optional DOMString name);
-    [RaisesException, CustomElementCallbacks] void setAttribute([Default=Undefined] optional DOMString name, [Default=Undefined] optional DOMString value);
-    [CustomElementCallbacks] void removeAttribute([Default=Undefined] optional DOMString name);
+    [TreatReturnedNullStringAs=Null] DOMString getAttribute(DOMString name);
+    [RaisesException, CustomElementCallbacks] void setAttribute(DOMString name, DOMString value);
+    [CustomElementCallbacks] void removeAttribute(DOMString name);
     [MeasureAs=ElementGetAttributeNode] Attr getAttributeNode([Default=Undefined] optional DOMString name); // Removed from DOM4.
     [RaisesException, CustomElementCallbacks, MeasureAs=ElementSetAttributeNode] Attr setAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr newAttr); // Removed from DOM4.
     [RaisesException, CustomElementCallbacks, MeasureAs=ElementRemoveAttributeNode] Attr removeAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr oldAttr); // Removed from DOM4.
-    [PerWorldBindings] NodeList getElementsByTagName([Default=Undefined] optional DOMString name);
+    [PerWorldBindings] HTMLCollection getElementsByTagName(DOMString name);
 
     [PerWorldBindings] readonly attribute NamedNodeMap     attributes;
     [MeasureAs=HasAttributes] boolean hasAttributes();
 
     // DOM Level 2 Core
 
-    DOMString getAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                             [Default=Undefined] optional DOMString localName);
-    [RaisesException, CustomElementCallbacks] void setAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                                                                  [Default=Undefined] optional DOMString qualifiedName,
-                                                                  [Default=Undefined] optional DOMString value);
+    DOMString getAttributeNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
+    [RaisesException, CustomElementCallbacks] void setAttributeNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName, DOMString value);
     [CustomElementCallbacks] void removeAttributeNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
-    NodeList getElementsByTagNameNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                                    [Default=Undefined] optional DOMString localName);
+    HTMLCollection getElementsByTagNameNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
     [MeasureAs=ElementGetAttributeNodeNS] Attr getAttributeNodeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
                                                                   [Default=Undefined] optional DOMString localName); // Removed from DOM4.
-    [RaisesException, CustomElementCallbacks, MeasureAs=ElementSetAttributeNodeNS] Attr setAttributeNodeNS([Default=Undefined, StrictTypeChecking] optional Attr newAttr); // Removed from DOM4.
     boolean hasAttribute(DOMString name);
-    boolean hasAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                           [Default=Undefined] optional DOMString localName);
+    boolean hasAttributeNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
 
     [PerWorldBindings] readonly attribute CSSStyleDeclaration style;
 
     // DOM4
-    [Reflect] attribute DOMString id;
+    [Reflect, PerWorldBindings] attribute DOMString id;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString namespaceURI;
     [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter] attribute DOMString prefix;
     [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString localName;
 
+    [RaisesException] boolean matches(DOMString selectors);
+
     // Common extensions
 
     [PerWorldBindings] readonly attribute long offsetLeft;
     [PerWorldBindings] readonly attribute long offsetTop;
     [PerWorldBindings] readonly attribute long offsetWidth;
     [PerWorldBindings] readonly attribute long offsetHeight;
-    [ImplementedAs=bindingsOffsetParent, PerWorldBindings] readonly attribute Element offsetParent;
+    [ImplementedAs=offsetParentForBindings, PerWorldBindings] readonly attribute Element offsetParent;
     [PerWorldBindings] readonly attribute long clientLeft;
     [PerWorldBindings] readonly attribute long clientTop;
     [PerWorldBindings] readonly attribute long clientWidth;
     [PerWorldBindings] readonly attribute long clientHeight;
-    [PerWorldBindings] attribute long scrollLeft;
-    [PerWorldBindings] attribute long scrollTop;
+
+    // FIXME: should be:
+    // [PerWorldBindings] attribute (Dictionary or long) scrollLeft;
+    // [PerWorldBindings] attribute (Dictionary or long) scrollTop;
+    // http://crbug.com/240176
+    [PerWorldBindings, Custom=Setter] attribute long scrollLeft;
+    [PerWorldBindings, Custom=Setter] attribute long scrollTop;
     [PerWorldBindings] readonly attribute long scrollWidth;
     [PerWorldBindings] readonly attribute long scrollHeight;
 
@@ -89,9 +90,12 @@
     void scrollByPages([Default=Undefined] optional long pages);
 
     // HTML 5
-    NodeList getElementsByClassName([Default=Undefined] optional DOMString name);
+    HTMLCollection getElementsByClassName(DOMString classNames);
     [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, RaisesException=Setter] attribute DOMString innerHTML;
     [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter] attribute DOMString outerHTML;
+
+    [RaisesException, CustomElementCallbacks, MeasureAs=InsertAdjacentElement] Element insertAdjacentElement(DOMString where, Element element);
+    [RaisesException, MeasureAs=InsertAdjacentText] void insertAdjacentText(DOMString where, DOMString text);
     [CustomElementCallbacks, RaisesException] void insertAdjacentHTML(DOMString where, DOMString html);
 
     [Reflect=class, PerWorldBindings] attribute DOMString className;
@@ -104,16 +108,14 @@
     [RaisesException] NodeList querySelectorAll(DOMString selectors);
 
     // WebKit extension
-    [RaisesException, MeasureAs=ElementPrefixedMatchesSelector] boolean webkitMatchesSelector([Default=Undefined] optional DOMString selectors);
+    [RaisesException, ImplementedAs=matches, MeasureAs=ElementPrefixedMatchesSelector] boolean webkitMatchesSelector(DOMString selectors);
 
     // Shadow DOM API
-    [RuntimeEnabled=ShadowDOM, Reflect, TreatNullAs=NullString, PerWorldBindings] attribute DOMString pseudo;
     [RuntimeEnabled=ShadowDOM, RaisesException] ShadowRoot createShadowRoot();
     [RuntimeEnabled=ShadowDOM, PerWorldBindings] readonly attribute ShadowRoot shadowRoot;
     [RuntimeEnabled=ShadowDOM, PerWorldBindings] NodeList getDestinationInsertionPoints();
 
     // To-be-deprecated prefixed Shadow DOM API
-    [Reflect=pseudo, TreatNullAs=NullString, ImplementedAs=pseudo, PerWorldBindings, MeasureAs=ShadowDOMPrefixedPseudo] attribute DOMString webkitPseudo;
     [ImplementedAs=createShadowRoot, RaisesException, MeasureAs=ShadowDOMPrefixedCreateShadowRoot] ShadowRoot webkitCreateShadowRoot();
     [ImplementedAs=shadowRoot, PerWorldBindings, MeasureAs=ShadowDOMPrefixedShadowRoot] readonly attribute ShadowRoot webkitShadowRoot;
 
@@ -130,10 +132,6 @@
 
     void webkitRequestPointerLock();
 
-    // CSS Regions API
-    [RuntimeEnabled=CSSRegions, PerWorldBindings] readonly attribute DOMString webkitRegionOverset;
-    [RuntimeEnabled=CSSRegions] sequence<Range> webkitGetRegionFlowRanges();
-
     // Event handler attributes
     attribute EventHandler onbeforecopy;
     attribute EventHandler onbeforecut;
diff --git a/Source/core/dom/ElementData.cpp b/Source/core/dom/ElementData.cpp
index 2ce4aa0..82c7712 100644
--- a/Source/core/dom/ElementData.cpp
+++ b/Source/core/dom/ElementData.cpp
@@ -164,7 +164,6 @@
     ASSERT(!other.m_presentationAttributeStyle);
 
     if (other.m_inlineStyle) {
-        ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
         m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
     }
 
diff --git a/Source/core/dom/ElementData.h b/Source/core/dom/ElementData.h
index 2426667..76451f8 100644
--- a/Source/core/dom/ElementData.h
+++ b/Source/core/dom/ElementData.h
@@ -42,6 +42,8 @@
 class StylePropertySet;
 class UniqueElementData;
 
+// ElementData represents very common, but not necessarily unique to an element,
+// data such as attributes, inline style, and parsed class names and ids.
 class ElementData : public RefCounted<ElementData> {
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -81,6 +83,7 @@
     explicit ElementData(unsigned arraySize);
     ElementData(const ElementData&, bool isUnique);
 
+    // Keep the type in a bitfield instead of using virtual destructors to avoid adding a vtable.
     unsigned m_isUnique : 1;
     unsigned m_arraySize : 28;
     mutable unsigned m_presentationAttributeStyleIsDirty : 1;
@@ -111,7 +114,11 @@
 #pragma warning(disable: 4200) // Disable "zero-sized array in struct/union" warning
 #endif
 
-class ShareableElementData : public ElementData {
+// SharableElementData is managed by ElementDataCache and is produced by
+// the parser during page load for elements that have identical attributes. This
+// is a memory optimization since it's very common for many elements to have
+// duplicate sets of attributes (ex. the same classes).
+class ShareableElementData FINAL : public ElementData {
 public:
     static PassRefPtr<ShareableElementData> createWithAttributes(const Vector<Attribute>&);
 
@@ -126,7 +133,13 @@
 #pragma warning(pop)
 #endif
 
-class UniqueElementData : public ElementData {
+// UniqueElementData is created when an element needs to mutate its attributes
+// or gains presentation attribute style (ex. width="10"). It does not need to
+// be created to fill in values in the ElementData that are derived from
+// attributes. For example populating the m_inlineStyle from the style attribute
+// doesn't require a UniqueElementData as all elements with the same style
+// attribute will have the same inline style.
+class UniqueElementData FINAL : public ElementData {
 public:
     static PassRefPtr<UniqueElementData> create();
     PassRefPtr<ShareableElementData> makeShareableCopy() const;
@@ -142,6 +155,10 @@
     explicit UniqueElementData(const ShareableElementData&);
     explicit UniqueElementData(const UniqueElementData&);
 
+    // FIXME: We might want to support sharing element data for elements with
+    // presentation attribute style. Lots of table cells likely have the same
+    // attributes. Most modern pages don't use presentation attributes though
+    // so this might not make sense.
     mutable RefPtr<StylePropertySet> m_presentationAttributeStyle;
     Vector<Attribute, 4> m_attributeVector;
 };
diff --git a/Source/core/dom/ElementDataCache.cpp b/Source/core/dom/ElementDataCache.cpp
new file mode 100644
index 0000000..1b3cf32
--- /dev/null
+++ b/Source/core/dom/ElementDataCache.cpp
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2012, 2013 Apple Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
+ *
+ */
+
+#include "config.h"
+#include "core/dom/ElementDataCache.h"
+
+#include "core/dom/ElementData.h"
+
+namespace WebCore {
+
+inline unsigned attributeHash(const Vector<Attribute>& attributes)
+{
+    return StringHasher::hashMemory(attributes.data(), attributes.size() * sizeof(Attribute));
+}
+
+inline bool hasSameAttributes(const Vector<Attribute>& attributes, ShareableElementData& elementData)
+{
+    if (attributes.size() != elementData.length())
+        return false;
+    return !memcmp(attributes.data(), elementData.m_attributeArray, attributes.size() * sizeof(Attribute));
+}
+
+PassRefPtr<ShareableElementData> ElementDataCache::cachedShareableElementDataWithAttributes(const Vector<Attribute>& attributes)
+{
+    ASSERT(!attributes.isEmpty());
+
+    ShareableElementDataCache::ValueType* it = m_shareableElementDataCache.add(attributeHash(attributes), 0).storedValue;
+
+    // FIXME: This prevents sharing when there's a hash collision.
+    if (it->value && !hasSameAttributes(attributes, *it->value))
+        return ShareableElementData::createWithAttributes(attributes);
+
+    if (!it->value)
+        it->value = ShareableElementData::createWithAttributes(attributes);
+
+    return it->value.get();
+}
+
+ElementDataCache::ElementDataCache()
+{
+}
+
+ElementDataCache::~ElementDataCache()
+{
+}
+
+}
diff --git a/Source/core/dom/DocumentSharedObjectPool.h b/Source/core/dom/ElementDataCache.h
similarity index 81%
rename from Source/core/dom/DocumentSharedObjectPool.h
rename to Source/core/dom/ElementDataCache.h
index 2f827db..d275f1e 100644
--- a/Source/core/dom/DocumentSharedObjectPool.h
+++ b/Source/core/dom/ElementDataCache.h
@@ -24,11 +24,14 @@
  *
  */
 
-#ifndef DocumentSharedObjectPool_h
-#define DocumentSharedObjectPool_h
+#ifndef ElementDataCache_h
+#define ElementDataCache_h
 
 #include "wtf/HashMap.h"
 #include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 #include "wtf/text/StringHash.h"
 
 namespace WebCore {
@@ -37,17 +40,17 @@
 class ShareableElementData;
 class ShareableElementDataCacheEntry;
 
-class DocumentSharedObjectPool {
+class ElementDataCache {
 public:
-    static PassOwnPtr<DocumentSharedObjectPool> create() { return adoptPtr(new DocumentSharedObjectPool); }
-    ~DocumentSharedObjectPool();
+    static PassOwnPtr<ElementDataCache> create() { return adoptPtr(new ElementDataCache); }
+    ~ElementDataCache();
 
     PassRefPtr<ShareableElementData> cachedShareableElementDataWithAttributes(const Vector<Attribute>&);
 
 private:
-    DocumentSharedObjectPool();
+    ElementDataCache();
 
-    typedef HashMap<unsigned, OwnPtr<ShareableElementDataCacheEntry>, AlreadyHashed> ShareableElementDataCache;
+    typedef HashMap<unsigned, RefPtr<ShareableElementData>, AlreadyHashed> ShareableElementDataCache;
     ShareableElementDataCache m_shareableElementDataCache;
 };
 
diff --git a/Source/core/dom/ElementRareData.cpp b/Source/core/dom/ElementRareData.cpp
index ef6d2c2..85889c3 100644
--- a/Source/core/dom/ElementRareData.cpp
+++ b/Source/core/dom/ElementRareData.cpp
@@ -31,7 +31,6 @@
 #include "config.h"
 #include "core/dom/ElementRareData.h"
 
-#include "core/rendering/RegionOversetState.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
@@ -39,12 +38,19 @@
 struct SameSizeAsElementRareData : NodeRareData {
     short indices[2];
     unsigned bitfields;
-    RegionOversetState regionOversetState;
     LayoutSize sizeForResizing;
     IntSize scrollOffset;
-    void* pointers[10];
+    void* pointers[11];
 };
 
+CSSStyleDeclaration* ElementRareData::ensureInlineCSSStyleDeclaration(Element* ownerElement)
+{
+    if (!m_cssomWrapper)
+        m_cssomWrapper = adoptPtr(new InlineCSSStyleDeclaration(ownerElement));
+    return m_cssomWrapper.get();
+}
+
+
 COMPILE_ASSERT(sizeof(ElementRareData) == sizeof(SameSizeAsElementRareData), ElementRareDataShouldStaySmall);
 
 } // namespace WebCore
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index a187997..a492285 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -63,12 +63,6 @@
     bool isInCanvasSubtree() const { return m_isInCanvasSubtree; }
     void setIsInCanvasSubtree(bool value) { m_isInCanvasSubtree = value; }
 
-    bool isInsideRegion() const { return m_isInsideRegion; }
-    void setIsInsideRegion(bool value) { m_isInsideRegion = value; }
-
-    RegionOversetState regionOversetState() const { return m_regionOversetState; }
-    void setRegionOversetState(RegionOversetState state) { m_regionOversetState = state; }
-
     bool containsFullScreenElement() { return m_containsFullScreenElement; }
     void setContainsFullScreenElement(bool value) { m_containsFullScreenElement = value; }
 
@@ -97,6 +91,8 @@
     unsigned childIndex() const { return m_childIndex; }
     void setChildIndex(unsigned index) { m_childIndex = index; }
 
+    CSSStyleDeclaration* ensureInlineCSSStyleDeclaration(Element* ownerElement);
+
     void clearShadow() { m_shadow = nullptr; }
     ElementShadow* shadow() const { return m_shadow.get(); }
     ElementShadow& ensureShadow()
@@ -149,6 +145,7 @@
     }
 
     bool hasPseudoElements() const;
+    void clearPseudoElements();
 
 private:
     short m_tabIndex;
@@ -173,9 +170,6 @@
     unsigned m_childrenAffectedByForwardPositionalRules : 1;
     unsigned m_childrenAffectedByBackwardPositionalRules : 1;
 
-    unsigned m_isInsideRegion : 1;
-    RegionOversetState m_regionOversetState;
-
     LayoutSize m_minimumSizeForResizing;
     IntSize m_savedLayerScrollOffset;
     RefPtr<RenderStyle> m_computedStyle;
@@ -186,6 +180,7 @@
     OwnPtr<NamedNodeMap> m_attributeMap;
     OwnPtr<InputMethodContext> m_inputMethodContext;
     OwnPtr<ActiveAnimations> m_activeAnimations;
+    OwnPtr<InlineCSSStyleDeclaration> m_cssomWrapper;
 
     RefPtr<PseudoElement> m_generatedBefore;
     RefPtr<PseudoElement> m_generatedAfter;
@@ -219,8 +214,6 @@
     , m_childrenAffectedByDirectAdjacentRules(false)
     , m_childrenAffectedByForwardPositionalRules(false)
     , m_childrenAffectedByBackwardPositionalRules(false)
-    , m_isInsideRegion(false)
-    , m_regionOversetState(RegionUndefined)
     , m_minimumSizeForResizing(defaultMinimumSizeForResizing())
 {
 }
@@ -238,6 +231,13 @@
     return m_generatedBefore || m_generatedAfter || m_backdrop;
 }
 
+inline void ElementRareData::clearPseudoElements()
+{
+    setPseudoElement(BEFORE, 0);
+    setPseudoElement(AFTER, 0);
+    setPseudoElement(BACKDROP, 0);
+}
+
 inline void ElementRareData::setPseudoElement(PseudoId pseudoId, PassRefPtr<PseudoElement> element)
 {
     switch (pseudoId) {
diff --git a/Source/core/dom/ElementTraversal.h b/Source/core/dom/ElementTraversal.h
index 274725d..6bcf1d1 100644
--- a/Source/core/dom/ElementTraversal.h
+++ b/Source/core/dom/ElementTraversal.h
@@ -32,9 +32,11 @@
 
 namespace ElementTraversal {
 
-// First element child of the node.
+// First / Last element child of the node.
 Element* firstWithin(const Node&);
 Element* firstWithin(const ContainerNode&);
+Element* lastWithin(const Node&);
+Element* lastWithin(const ContainerNode&);
 
 // Pre-order traversal skipping non-element nodes.
 Element* next(const Node&);
@@ -56,6 +58,10 @@
 // Utility function to traverse only the element and pseudo-element siblings of a node.
 Element* pseudoAwarePreviousSibling(const Node&);
 
+// Previous / Next sibling.
+Element* previousSibling(const Node&);
+Element* nextSibling(const Node&);
+
 template <class NodeType>
 inline Element* firstElementWithinTemplate(NodeType& current)
 {
@@ -69,6 +75,17 @@
 inline Element* firstWithin(const Node& current) { return firstElementWithinTemplate(current); }
 
 template <class NodeType>
+inline Element* lastWithinTemplate(NodeType& current)
+{
+    Node* node = current.lastChild();
+    while (node && !node->isElementNode())
+        node = node->previousSibling();
+    return toElement(node);
+}
+inline Element* lastWithin(const ContainerNode& current) { return lastWithinTemplate(current); }
+inline Element* lastWithin(const Node& current) { return lastWithinTemplate(current); }
+
+template <class NodeType>
 inline Element* traverseNextElementTemplate(NodeType& current)
 {
     Node* node = NodeTraversal::next(current);
@@ -144,6 +161,22 @@
     return toElement(node);
 }
 
+inline Element* previousSibling(const Node& current)
+{
+    Node* node = current.previousSibling();
+    while (node && !node->isElementNode())
+        node = node->previousSibling();
+    return toElement(node);
+}
+
+inline Element* nextSibling(const Node& current)
+{
+    Node* node = current.nextSibling();
+    while (node && !node->isElementNode())
+        node = node->nextSibling();
+    return toElement(node);
+}
+
 }
 
 }
diff --git a/Source/core/rendering/LayoutIndicator.cpp b/Source/core/dom/EmptyNodeList.cpp
similarity index 79%
copy from Source/core/rendering/LayoutIndicator.cpp
copy to Source/core/dom/EmptyNodeList.cpp
index a57c53c..8705936 100644
--- a/Source/core/rendering/LayoutIndicator.cpp
+++ b/Source/core/dom/EmptyNodeList.cpp
@@ -1,5 +1,6 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,14 +30,21 @@
  */
 
 #include "config.h"
-#include "core/rendering/LayoutIndicator.h"
+#include "EmptyNodeList.h"
+
+#include "core/dom/Node.h"
+#include "core/dom/NodeRareData.h"
 
 namespace WebCore {
 
-#ifndef NDEBUG
-
-size_t LayoutIndicator::s_inLayout = 0;
-
-#endif
-
+EmptyNodeList::~EmptyNodeList()
+{
+    m_owner->nodeLists()->removeEmptyChildNodeList(this);
 }
+
+Node* EmptyNodeList::virtualOwnerNode() const
+{
+    return ownerNode();
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/NodeList.cpp b/Source/core/dom/EmptyNodeList.h
similarity index 63%
copy from Source/core/dom/NodeList.cpp
copy to Source/core/dom/EmptyNodeList.h
index fb06c70..06f895f 100644
--- a/Source/core/dom/NodeList.cpp
+++ b/Source/core/dom/EmptyNodeList.h
@@ -1,5 +1,6 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,30 +29,37 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/dom/NodeList.h"
+#ifndef EmptyNodeList_h
+#define EmptyNodeList_h
 
-#include "core/dom/Node.h"
+#include "core/dom/NodeList.h"
 
 namespace WebCore {
 
-void NodeList::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<Node>& returnValue0, bool& returnValue1Enabled, unsigned& returnValue1)
-{
-    // Length property cannot be overridden.
-    DEFINE_STATIC_LOCAL(const AtomicString, length, ("length", AtomicString::ConstructFromLiteral));
-    if (name == length) {
-        returnValue1Enabled = true;
-        returnValue1 = this->length();
-        return;
+class EmptyNodeList FINAL : public NodeList {
+public:
+    static PassRefPtr<EmptyNodeList> create(Node* rootNode)
+    {
+        return adoptRef(new EmptyNodeList(rootNode));
     }
+    virtual ~EmptyNodeList();
 
-    Node* result = namedItem(name);
-    if (!result)
-        return;
+    Node* ownerNode() const { return m_owner.get(); }
 
-    returnValue0Enabled = true;
-    returnValue0 = result;
-}
+private:
+    explicit EmptyNodeList(Node* rootNode) : m_owner(rootNode) { }
 
+    virtual unsigned length() const OVERRIDE { return 0; }
+    virtual Node* item(unsigned) const OVERRIDE { return 0; }
+
+    virtual bool isEmptyNodeList() const OVERRIDE { return true; }
+    virtual Node* virtualOwnerNode() const OVERRIDE;
+
+    RefPtr<Node> m_owner;
+};
+
+DEFINE_TYPE_CASTS(EmptyNodeList, NodeList, nodeList, nodeList->isEmptyNodeList(), nodeList.isEmptyNodeList());
 
 } // namespace WebCore
+
+#endif // EmptyNodeList_h
diff --git a/Source/core/dom/Entity.h b/Source/core/dom/Entity.h
deleted file mode 100644
index e1a7a00..0000000
--- a/Source/core/dom/Entity.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2000 Peter Kelly (pmk@post.com)
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef Entity_h
-#define Entity_h
-
-#include "core/dom/ContainerNode.h"
-
-namespace WebCore {
-
-class Entity : public ContainerNode {
-private:
-    Entity(); // Left unimplemented on purpose.
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/dom/Entity.idl b/Source/core/dom/Entity.idl
deleted file mode 100644
index 151572f..0000000
--- a/Source/core/dom/Entity.idl
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-// FIXME: Remove Entity interface. We never create Entity objects. We have this
-// interface to provide window.Entity.
-interface Entity : Node {
-    // We don't need to provide any attributes.
-};
-
diff --git a/Source/core/dom/ExecutionContext.cpp b/Source/core/dom/ExecutionContext.cpp
index 1f62b74..0740d82 100644
--- a/Source/core/dom/ExecutionContext.cpp
+++ b/Source/core/dom/ExecutionContext.cpp
@@ -199,7 +199,7 @@
     }
     TimeoutMap::AddResult result = m_timeouts.add(timeoutID, DOMTimer::create(this, action, timeout, singleShot, timeoutID));
     ASSERT(result.isNewEntry);
-    DOMTimer* timer = result.iterator->value.get();
+    DOMTimer* timer = result.storedValue->value.get();
 
     timer->suspendIfNeeded();
 
diff --git a/Source/core/dom/ExecutionContext.h b/Source/core/dom/ExecutionContext.h
index 06b6370..3fb01bb 100644
--- a/Source/core/dom/ExecutionContext.h
+++ b/Source/core/dom/ExecutionContext.h
@@ -67,7 +67,7 @@
     // Delegating to ExecutionContextClient
     void setClient(ExecutionContextClient* client) { m_client = client; }
     bool isDocument() const { return m_client && m_client->isDocument(); }
-    bool isWorkerGlobalScope() { return m_client && m_client->isWorkerGlobalScope(); }
+    bool isWorkerGlobalScope() const { return m_client && m_client->isWorkerGlobalScope(); }
     bool isJSExecutionForbidden() { return m_client && m_client->isJSExecutionForbidden(); }
     SecurityOrigin* securityOrigin() const;
     ContentSecurityPolicy* contentSecurityPolicy() const;
diff --git a/Source/core/dom/ExecutionContextTask.h b/Source/core/dom/ExecutionContextTask.h
index 9d07d75..dbc98d3 100644
--- a/Source/core/dom/ExecutionContextTask.h
+++ b/Source/core/dom/ExecutionContextTask.h
@@ -47,7 +47,7 @@
     virtual bool isCleanupTask() const { return false; }
 };
 
-class CallClosureTask : public ExecutionContextTask {
+class CallClosureTask FINAL : public ExecutionContextTask {
 public:
     static PassOwnPtr<CallClosureTask> create(const Closure& closure)
     {
diff --git a/Source/core/dom/FullscreenElementStack.cpp b/Source/core/dom/FullscreenElementStack.cpp
index ea6d058..635639b 100644
--- a/Source/core/dom/FullscreenElementStack.cpp
+++ b/Source/core/dom/FullscreenElementStack.cpp
@@ -31,12 +31,12 @@
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
 #include "core/events/Event.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/frame/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
 #include "core/rendering/RenderFullScreen.h"
 #include "platform/UserGestureIndicator.h"
 
@@ -240,7 +240,7 @@
         // 5. Return, and run the remaining steps asynchronously.
         // 6. Optionally, perform some animation.
         m_areKeysEnabledInFullScreen = flags & Element::ALLOW_KEYBOARD_INPUT;
-        document()->page()->chrome().client().enterFullScreenForElement(element);
+        document()->frameHost()->chrome().client().enterFullScreenForElement(element);
 
         // 7. Optionally, display a message indicating how the user can exit displaying the context object fullscreen.
         return;
@@ -274,6 +274,7 @@
 
     // 1. Let doc be the context object. (i.e. "this")
     Document* currentDoc = document();
+    ASSERT(currentDoc->isActive());
 
     // 2. If doc's fullscreen element stack is empty, terminate these steps.
     if (m_fullScreenElementStack.isEmpty())
@@ -325,18 +326,23 @@
     // 6. Return, and run the remaining steps asynchronously.
     // 7. Optionally, perform some animation.
 
-    if (!document()->page())
+    FrameHost* host = document()->frameHost();
+
+    // Speculative fix for engaget.com/videos per crbug.com/336239.
+    // FIXME: This check is wrong. We ASSERT(document->isActive()) above
+    // so this should be redundant and should be removed!
+    if (!host)
         return;
 
     // Only exit out of full screen window mode if there are no remaining elements in the
     // full screen stack.
     if (!newTop) {
-        document()->page()->chrome().client().exitFullScreenForElement(m_fullScreenElement.get());
+        host->chrome().client().exitFullScreenForElement(m_fullScreenElement.get());
         return;
     }
 
     // Otherwise, notify the chrome of the new full screen element.
-    document()->page()->chrome().client().enterFullScreenForElement(newTop);
+    host->chrome().client().enterFullScreenForElement(newTop);
 }
 
 bool FullscreenElementStack::webkitFullscreenEnabled(Document* document)
@@ -351,15 +357,11 @@
 
 void FullscreenElementStack::webkitWillEnterFullScreenForElement(Element* element)
 {
+    ASSERT(element);
     if (!document()->isActive())
         return;
 
-    ASSERT(element);
-
-    // Protect against being called after the document has been removed from the page.
-    if (!document()->settings())
-        return;
-
+    ASSERT(document()->settings()); // If we're active we must have settings.
     ASSERT(document()->settings()->fullScreenEnabled());
 
     if (m_fullScreenRenderer)
@@ -383,7 +385,9 @@
 
     m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
 
-    document()->recalcStyle(Force);
+    // FIXME: This should not call updateStyleIfNeeded.
+    document()->setNeedsStyleRecalc(SubtreeStyleChange);
+    document()->updateStyleIfNeeded();
 }
 
 void FullscreenElementStack::webkitDidEnterFullScreenForElement(Element*)
@@ -426,7 +430,7 @@
         m_fullScreenRenderer->unwrapRenderer();
 
     m_fullScreenElement = 0;
-    document()->setNeedsStyleRecalc();
+    document()->setNeedsStyleRecalc(SubtreeStyleChange);
 
     // When webkitCancelFullScreen is called, we call webkitExitFullScreen on the topDocument(). That
     // means that the events will be queued there. So if we have no events here, start the timer on
diff --git a/Source/core/dom/FullscreenElementStack.h b/Source/core/dom/FullscreenElementStack.h
index 4211a83..346ea1e 100644
--- a/Source/core/dom/FullscreenElementStack.h
+++ b/Source/core/dom/FullscreenElementStack.h
@@ -46,7 +46,7 @@
 class RenderStyle;
 class ExecutionContext;
 
-class FullscreenElementStack
+class FullscreenElementStack FINAL
     : public DocumentSupplement
     , public DocumentLifecycleObserver {
 public:
diff --git a/Source/core/dom/GlobalEventHandlers.h b/Source/core/dom/GlobalEventHandlers.h
index 8da83b9..304a563 100644
--- a/Source/core/dom/GlobalEventHandlers.h
+++ b/Source/core/dom/GlobalEventHandlers.h
@@ -81,6 +81,7 @@
 DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(progress);
 DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(ratechange);
 DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(reset);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(resize);
 DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(scroll);
 DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeked);
 DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeking);
diff --git a/Source/core/dom/GlobalEventHandlers.idl b/Source/core/dom/GlobalEventHandlers.idl
index 8800382..5a65c5b 100644
--- a/Source/core/dom/GlobalEventHandlers.idl
+++ b/Source/core/dom/GlobalEventHandlers.idl
@@ -77,6 +77,7 @@
     attribute EventHandler onprogress;
     attribute EventHandler onratechange;
     attribute EventHandler onreset;
+    attribute EventHandler onresize;
     attribute EventHandler onscroll;
     attribute EventHandler onseeked;
     attribute EventHandler onseeking;
@@ -87,6 +88,7 @@
     attribute EventHandler onsubmit;
     attribute EventHandler onsuspend;
     attribute EventHandler ontimeupdate;
+    //attribute EventHandler ontoggle;
     attribute EventHandler onvolumechange;
     attribute EventHandler onwaiting;
 };
diff --git a/Source/core/dom/IconURL.h b/Source/core/dom/IconURL.h
index adec2a7..d35b360 100644
--- a/Source/core/dom/IconURL.h
+++ b/Source/core/dom/IconURL.h
@@ -35,12 +35,6 @@
 
 namespace WebCore {
 
-#if ENABLE(TOUCH_ICON_LOADING)
-#define ICON_COUNT 3
-#else
-#define ICON_COUNT 1
-#endif
-
 enum IconType {
     InvalidIcon = 0,
     Favicon = 1,
@@ -75,8 +69,6 @@
 
 bool operator==(const IconURL&, const IconURL&);
 
-typedef Vector<IconURL, ICON_COUNT> IconURLs;
-
 }
 
 #endif // IconURL_h
diff --git a/Source/core/dom/IdTargetObserverRegistry.cpp b/Source/core/dom/IdTargetObserverRegistry.cpp
index 19d297a..80bd6b3 100644
--- a/Source/core/dom/IdTargetObserverRegistry.cpp
+++ b/Source/core/dom/IdTargetObserverRegistry.cpp
@@ -42,9 +42,9 @@
 
     IdToObserverSetMap::AddResult result = m_registry.add(id.impl(), nullptr);
     if (result.isNewEntry)
-        result.iterator->value = adoptPtr(new ObserverSet());
+        result.storedValue->value = adoptPtr(new ObserverSet());
 
-    result.iterator->value->add(observer);
+    result.storedValue->value->add(observer);
 }
 
 void IdTargetObserverRegistry::removeObserver(const AtomicString& id, IdTargetObserver* observer)
@@ -82,4 +82,12 @@
     m_notifyingObserversInSet = 0;
 }
 
+bool IdTargetObserverRegistry::hasObservers(const AtomicString& id) const
+{
+    if (id.isEmpty() || m_registry.isEmpty())
+        return false;
+    ObserverSet* set = m_registry.get(id.impl());
+    return set && !set->isEmpty();
+}
+
 } // namespace WebCore
diff --git a/Source/core/dom/IdTargetObserverRegistry.h b/Source/core/dom/IdTargetObserverRegistry.h
index 4af563a..b60af69 100644
--- a/Source/core/dom/IdTargetObserverRegistry.h
+++ b/Source/core/dom/IdTargetObserverRegistry.h
@@ -42,6 +42,7 @@
 public:
     static PassOwnPtr<IdTargetObserverRegistry> create();
     void notifyObservers(const AtomicString& id);
+    bool hasObservers(const AtomicString& id) const;
 
 private:
     IdTargetObserverRegistry() : m_notifyingObserversInSet(0) { }
diff --git a/Source/core/dom/LiveNodeList.cpp b/Source/core/dom/LiveNodeList.cpp
index 5343cb9..d43ce2f 100644
--- a/Source/core/dom/LiveNodeList.cpp
+++ b/Source/core/dom/LiveNodeList.cpp
@@ -28,67 +28,34 @@
 
 namespace WebCore {
 
-Node& LiveNodeListBase::rootNode() const
+ContainerNode& LiveNodeListBase::rootNode() const
 {
     if (isRootedAtDocument() && m_ownerNode->inDocument())
         return m_ownerNode->document();
     return *m_ownerNode;
 }
 
-ContainerNode* LiveNodeListBase::rootContainerNode() const
+void LiveNodeListBase::didMoveToDocument(Document& oldDocument, Document& newDocument)
 {
-    Node& rootNode = this->rootNode();
-    if (!rootNode.isContainerNode())
-        return 0;
-    return toContainerNode(&rootNode);
-}
-
-void LiveNodeListBase::invalidateCache() const
-{
-    m_cachedItem = 0;
-    m_isLengthCacheValid = false;
-    m_isItemCacheValid = false;
-    m_isNameCacheValid = false;
-    m_isItemRefElementsCacheValid = false;
-    if (isNodeList(type()))
-        return;
-
-    const HTMLCollection* cacheBase = static_cast<const HTMLCollection*>(this);
-    cacheBase->m_idCache.clear();
-    cacheBase->m_nameCache.clear();
-    cacheBase->m_cachedElementsArrayOffset = 0;
+    invalidateCache(&oldDocument);
+    oldDocument.unregisterNodeList(this);
+    newDocument.registerNodeList(this);
 }
 
 void LiveNodeListBase::invalidateIdNameCacheMaps() const
 {
     ASSERT(hasIdNameCache());
-    const HTMLCollection* cacheBase = static_cast<const HTMLCollection*>(this);
-    cacheBase->m_idCache.clear();
-    cacheBase->m_nameCache.clear();
+    static_cast<const HTMLCollection*>(this)->invalidateIdNameCacheMaps();
 }
 
-Node* LiveNodeList::namedItem(const AtomicString& elementId) const
+Node* LiveNodeList::virtualOwnerNode() const
 {
-    Node& rootNode = this->rootNode();
+    return ownerNode();
+}
 
-    if (rootNode.inDocument()) {
-        Element* element = rootNode.treeScope().getElementById(elementId);
-        if (element && nodeMatches(element) && element->isDescendantOf(&rootNode))
-            return element;
-        if (!element)
-            return 0;
-        // In the case of multiple nodes with the same name, just fall through.
-    }
-
-    unsigned length = this->length();
-    for (unsigned i = 0; i < length; i++) {
-        Node* node = item(i);
-        // FIXME: This should probably be using getIdAttribute instead of idForStyleResolution.
-        if (node->hasID() && toElement(node)->idForStyleResolution() == elementId)
-            return node;
-    }
-
-    return 0;
+void LiveNodeList::invalidateCache(Document*) const
+{
+    m_collectionIndexCache.invalidate();
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/LiveNodeList.h b/Source/core/dom/LiveNodeList.h
index 2145b24..422e6bc 100644
--- a/Source/core/dom/LiveNodeList.h
+++ b/Source/core/dom/LiveNodeList.h
@@ -27,6 +27,7 @@
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
 #include "core/dom/NodeList.h"
+#include "core/html/CollectionIndexCache.h"
 #include "core/html/CollectionType.h"
 #include "wtf/Forward.h"
 #include "wtf/RefPtr.h"
@@ -41,51 +42,36 @@
     NodeListIsRootedAtDocumentIfOwnerHasItemrefAttr,
 };
 
-class LiveNodeListBase : public NodeList {
+class LiveNodeListBase {
 public:
-    enum ItemAfterOverrideType {
-        OverridesItemAfter,
-        DoesNotOverrideItemAfter,
-    };
-
-    LiveNodeListBase(Node* ownerNode, NodeListRootType rootType, NodeListInvalidationType invalidationType,
-        bool shouldOnlyIncludeDirectChildren, CollectionType collectionType, ItemAfterOverrideType itemAfterOverrideType)
+    LiveNodeListBase(ContainerNode* ownerNode, NodeListRootType rootType, NodeListInvalidationType invalidationType,
+        CollectionType collectionType)
         : m_ownerNode(ownerNode)
-        , m_cachedItem(0)
-        , m_isLengthCacheValid(false)
-        , m_isItemCacheValid(false)
         , m_rootType(rootType)
         , m_invalidationType(invalidationType)
-        , m_shouldOnlyIncludeDirectChildren(shouldOnlyIncludeDirectChildren)
-        , m_isNameCacheValid(false)
         , m_collectionType(collectionType)
-        , m_overridesItemAfter(itemAfterOverrideType == OverridesItemAfter)
-        , m_isItemRefElementsCacheValid(false)
     {
+        ASSERT(m_ownerNode);
         ASSERT(m_rootType == static_cast<unsigned>(rootType));
         ASSERT(m_invalidationType == static_cast<unsigned>(invalidationType));
         ASSERT(m_collectionType == static_cast<unsigned>(collectionType));
-        ASSERT(!m_overridesItemAfter || !isNodeList(collectionType));
 
-        if (collectionType != ChildNodeListType)
-            document().registerNodeList(this);
+        document().registerNodeList(this);
     }
 
     virtual ~LiveNodeListBase()
     {
-        if (type() != ChildNodeListType)
-            document().unregisterNodeList(this);
+        document().unregisterNodeList(this);
     }
 
-    // DOM API
-    virtual unsigned length() const OVERRIDE;
-    virtual Node* item(unsigned offset) const OVERRIDE;
+    ContainerNode& rootNode() const;
 
-    ALWAYS_INLINE bool hasIdNameCache() const { return !isNodeList(type()); }
+    void didMoveToDocument(Document& oldDocument, Document& newDocument);
+    ALWAYS_INLINE bool hasIdNameCache() const { return !isLiveNodeListType(type()); }
     ALWAYS_INLINE bool isRootedAtDocument() const { return m_rootType == NodeListIsRootedAtDocument || m_rootType == NodeListIsRootedAtDocumentIfOwnerHasItemrefAttr; }
     ALWAYS_INLINE NodeListInvalidationType invalidationType() const { return static_cast<NodeListInvalidationType>(m_invalidationType); }
     ALWAYS_INLINE CollectionType type() const { return static_cast<CollectionType>(m_collectionType); }
-    Node* ownerNode() const { return m_ownerNode.get(); }
+    ContainerNode* ownerNode() const { return m_ownerNode.get(); }
     ALWAYS_INLINE void invalidateCache(const QualifiedName* attrName) const
     {
         if (!attrName || shouldInvalidateTypeOnAttributeChange(invalidationType(), *attrName))
@@ -93,72 +79,27 @@
         else if (hasIdNameCache() && (*attrName == HTMLNames::idAttr || *attrName == HTMLNames::nameAttr))
             invalidateIdNameCacheMaps();
     }
-    void invalidateCache() const;
-    void invalidateIdNameCacheMaps() const;
+    virtual void invalidateCache(Document* oldDocument = 0) const = 0;
 
     static bool shouldInvalidateTypeOnAttributeChange(NodeListInvalidationType, const QualifiedName&);
 
 protected:
     Document& document() const { return m_ownerNode->document(); }
-    Node& rootNode() const;
-    ContainerNode* rootContainerNode() const;
-    bool overridesItemAfter() const { return m_overridesItemAfter; }
-
-    ALWAYS_INLINE bool isItemCacheValid() const { return m_isItemCacheValid; }
-    ALWAYS_INLINE Node* cachedItem() const { return m_cachedItem; }
-    ALWAYS_INLINE unsigned cachedItemOffset() const { return m_cachedItemOffset; }
-
-    ALWAYS_INLINE bool isLengthCacheValid() const { return m_isLengthCacheValid; }
-    ALWAYS_INLINE unsigned cachedLength() const { return m_cachedLength; }
-    ALWAYS_INLINE void setLengthCache(unsigned length) const
-    {
-        m_cachedLength = length;
-        m_isLengthCacheValid = true;
-    }
-    ALWAYS_INLINE void setItemCache(Node* item, unsigned offset) const
-    {
-        ASSERT(item);
-        m_cachedItem = item;
-        m_cachedItemOffset = offset;
-        m_isItemCacheValid = true;
-    }
-    void setItemCache(Node* item, unsigned offset, unsigned elementsArrayOffset) const;
-
-    ALWAYS_INLINE bool isItemRefElementsCacheValid() const { return m_isItemRefElementsCacheValid; }
-    ALWAYS_INLINE void setItemRefElementsCacheValid() const { m_isItemRefElementsCacheValid = true; }
 
     ALWAYS_INLINE NodeListRootType rootType() const { return static_cast<NodeListRootType>(m_rootType); }
 
-    bool hasNameCache() const { return m_isNameCacheValid; }
-    void setHasNameCache() const { m_isNameCacheValid = true; }
-
-    bool shouldOnlyIncludeDirectChildren() const { return m_shouldOnlyIncludeDirectChildren; }
+    template <typename Collection>
+    static Element* iterateForPreviousNode(const Collection&, Node* current);
+    template <typename Collection>
+    static Element* itemBefore(const Collection&, const Element* previousItem);
 
 private:
-    Node* itemBeforeOrAfterCachedItem(unsigned offset, ContainerNode* root) const;
-    Node* traverseChildNodeListForwardToOffset(unsigned offset, Node* currentNode, unsigned& currentOffset) const;
-    Element* traverseLiveNodeListFirstElement(ContainerNode& root) const;
-    Element* traverseLiveNodeListForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, ContainerNode* root) const;
-    bool isLastItemCloserThanLastOrCachedItem(unsigned offset) const;
-    bool isFirstItemCloserThanCachedItem(unsigned offset) const;
-    Node* iterateForPreviousNode(Node* current) const;
-    Node* itemBefore(Node* previousItem) const;
+    void invalidateIdNameCacheMaps() const;
 
-    RefPtr<Node> m_ownerNode;
-    mutable Node* m_cachedItem;
-    mutable unsigned m_cachedLength;
-    mutable unsigned m_cachedItemOffset;
-    mutable unsigned m_isLengthCacheValid : 1;
-    mutable unsigned m_isItemCacheValid : 1;
+    RefPtr<ContainerNode> m_ownerNode; // Cannot be null.
     const unsigned m_rootType : 2;
     const unsigned m_invalidationType : 4;
-    const unsigned m_shouldOnlyIncludeDirectChildren : 1;
-
-    // From HTMLCollection
-    mutable unsigned m_isNameCacheValid : 1;
     const unsigned m_collectionType : 5;
-    const unsigned m_overridesItemAfter : 1;
-    mutable unsigned m_isItemRefElementsCacheValid : 1;
 };
 
 ALWAYS_INLINE bool LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(NodeListInvalidationType type, const QualifiedName& attrName)
@@ -177,7 +118,6 @@
             || attrName == HTMLNames::formAttr || attrName == HTMLNames::typeAttr;
     case InvalidateOnHRefAttrChange:
         return attrName == HTMLNames::hrefAttr;
-    case InvalidateOnItemAttrChange:
     case DoNotInvalidateOnAttributeChanges:
         return false;
     case InvalidateOnAnyAttrChange:
@@ -186,18 +126,30 @@
     return false;
 }
 
-class LiveNodeList : public LiveNodeListBase {
+class LiveNodeList : public NodeList, public LiveNodeListBase {
 public:
-    LiveNodeList(PassRefPtr<Node> ownerNode, CollectionType collectionType, NodeListInvalidationType invalidationType, NodeListRootType rootType = NodeListIsRootedAtNode)
-        : LiveNodeListBase(ownerNode.get(), rootType, invalidationType, collectionType == ChildNodeListType,
-        collectionType, DoesNotOverrideItemAfter)
+    LiveNodeList(PassRefPtr<ContainerNode> ownerNode, CollectionType collectionType, NodeListInvalidationType invalidationType, NodeListRootType rootType = NodeListIsRootedAtNode)
+        : LiveNodeListBase(ownerNode.get(), rootType, invalidationType,
+        collectionType)
     { }
 
-    virtual Node* namedItem(const AtomicString&) const OVERRIDE;
-    virtual bool nodeMatches(Element*) const = 0;
+    virtual unsigned length() const OVERRIDE FINAL { return m_collectionIndexCache.nodeCount(*this); }
+    virtual Node* item(unsigned offset) const OVERRIDE FINAL { return m_collectionIndexCache.nodeAt(*this, offset); }
+    virtual bool nodeMatches(const Element&) const = 0;
+
+    virtual void invalidateCache(Document* oldDocument) const OVERRIDE FINAL;
+    bool shouldOnlyIncludeDirectChildren() const { return false; }
+
+    // Collection IndexCache API.
+    bool canTraverseBackward() const { return true; }
+    Element* itemBefore(const Element* previousItem) const;
+    Element* traverseToFirstElement(const ContainerNode& root) const;
+    Element* traverseForwardToOffset(unsigned offset, Element& currentNode, unsigned& currentOffset, const ContainerNode& root) const;
 
 private:
-    virtual bool isLiveNodeList() const OVERRIDE { return true; }
+    virtual Node* virtualOwnerNode() const OVERRIDE FINAL;
+
+    mutable CollectionIndexCache<LiveNodeList, Element> m_collectionIndexCache;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/MessageChannel.idl b/Source/core/dom/MessageChannel.idl
index f5b5165..fbd8bab 100644
--- a/Source/core/dom/MessageChannel.idl
+++ b/Source/core/dom/MessageChannel.idl
@@ -25,8 +25,8 @@
  */
 
 [
+    CustomConstructor,
     GlobalContext=Window&WorkerGlobalScope,
-    CustomConstructor
 ] interface MessageChannel {
     readonly attribute MessagePort port1;
     readonly attribute MessagePort port2;
diff --git a/Source/core/dom/MessagePort.cpp b/Source/core/dom/MessagePort.cpp
index 85254e4..769a4ef 100644
--- a/Source/core/dom/MessagePort.cpp
+++ b/Source/core/dom/MessagePort.cpp
@@ -77,7 +77,7 @@
         for (unsigned int i = 0; i < ports->size(); ++i) {
             MessagePort* dataPort = (*ports)[i].get();
             if (dataPort == this) {
-                exceptionState.throwDOMException(DataCloneError, "Item #" + String::number(i) + " in the array of ports contains the source port.");
+                exceptionState.throwDOMException(DataCloneError, "Port at index " + String::number(i) + " contains the source port.");
                 return;
             }
         }
@@ -212,7 +212,7 @@
                 type = "already neutered";
             else
                 type = "a duplicate";
-            exceptionState.throwDOMException(DataCloneError, "Item #"  + String::number(i) + " in the array of ports is " + type + ".");
+            exceptionState.throwDOMException(DataCloneError, "Port at index "  + String::number(i) + " is " + type + ".");
             return nullptr;
         }
         portSet.add(port);
diff --git a/Source/core/dom/MessagePort.h b/Source/core/dom/MessagePort.h
index c5f78ea..65e0cba 100644
--- a/Source/core/dom/MessagePort.h
+++ b/Source/core/dom/MessagePort.h
@@ -56,7 +56,7 @@
 // Not to be confused with blink::WebMessagePortChannelArray; this one uses Vector and OwnPtr instead of WebVector and raw pointers.
 typedef Vector<OwnPtr<blink::WebMessagePortChannel>, 1> MessagePortChannelArray;
 
-class MessagePort : public RefCounted<MessagePort>
+class MessagePort FINAL : public RefCounted<MessagePort>
     , public ActiveDOMObject
     , public EventTargetWithInlineData
     , public ScriptWrappable
@@ -84,18 +84,18 @@
 
     virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual ExecutionContext* executionContext() const OVERRIDE { return ActiveDOMObject::executionContext(); }
-    MessagePort* toMessagePort() OVERRIDE { return this; }
+    virtual MessagePort* toMessagePort() OVERRIDE { return this; }
 
     // ActiveDOMObject implementation.
     virtual bool hasPendingActivity() const OVERRIDE;
     virtual void stop() OVERRIDE { close(); }
 
-    void setOnmessage(PassRefPtr<EventListener> listener, DOMWrapperWorld* world)
+    void setOnmessage(PassRefPtr<EventListener> listener)
     {
-        setAttributeEventListener(EventTypeNames::message, listener, world);
+        setAttributeEventListener(EventTypeNames::message, listener);
         start();
     }
-    EventListener* onmessage(DOMWrapperWorld* world) { return getAttributeEventListener(EventTypeNames::message, world); }
+    EventListener* onmessage() { return getAttributeEventListener(EventTypeNames::message); }
 
     // A port starts out its life entangled, and remains entangled until it is closed or is cloned.
     bool isEntangled() const { return !m_closed && !isNeutered(); }
diff --git a/Source/core/dom/MessagePort.idl b/Source/core/dom/MessagePort.idl
index 17ae449..14845be 100644
--- a/Source/core/dom/MessagePort.idl
+++ b/Source/core/dom/MessagePort.idl
@@ -28,7 +28,7 @@
 [
     ActiveDOMObject
 ] interface MessagePort : EventTarget {
-    [Custom, RaisesException] void postMessage(any message, optional Array messagePorts);
+    [Custom, RaisesException] void postMessage(any message, optional MessagePort[] messagePorts);
 
     void start();
     void close();
diff --git a/Source/core/dom/Microtask.cpp b/Source/core/dom/Microtask.cpp
index 27cd217..d26cde4 100644
--- a/Source/core/dom/Microtask.cpp
+++ b/Source/core/dom/Microtask.cpp
@@ -31,26 +31,41 @@
 #include "config.h"
 #include "core/dom/Microtask.h"
 
-#include "core/dom/MutationObserver.h"
-#include "core/dom/custom/CustomElementCallbackDispatcher.h"
+#include "bindings/v8/V8PerIsolateData.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
+typedef Vector<MicrotaskCallback> MicrotaskQueue;
+
+static MicrotaskQueue& microtaskQueue()
+{
+    DEFINE_STATIC_LOCAL(MicrotaskQueue, microtaskQueue, ());
+    return microtaskQueue;
+}
+
 void Microtask::performCheckpoint()
 {
-    static bool performingCheckpoint = false;
-    if (performingCheckpoint)
+    V8PerIsolateData* isolateData = V8PerIsolateData::current();
+    ASSERT(isolateData);
+    if (isolateData->performingMicrotaskCheckpoint())
         return;
-    performingCheckpoint = true;
+    isolateData->setPerformingMicrotaskCheckpoint(true);
 
-    bool anyWorkDone;
-    do {
-        MutationObserver::deliverAllMutations();
-        anyWorkDone = CustomElementCallbackDispatcher::instance().dispatch();
-    } while (anyWorkDone);
+    while (!microtaskQueue().isEmpty()) {
+        Vector<MicrotaskCallback> microtasks;
+        microtasks.swap(microtaskQueue());
+        for (size_t i = 0; i < microtasks.size(); ++i) {
+            microtasks[i]();
+        }
+    }
 
-    performingCheckpoint = false;
+    isolateData->setPerformingMicrotaskCheckpoint(false);
+}
+
+void Microtask::enqueueMicrotask(MicrotaskCallback callback)
+{
+    microtaskQueue().append(callback);
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/Microtask.h b/Source/core/dom/Microtask.h
index 27f72cb..63e7b95 100644
--- a/Source/core/dom/Microtask.h
+++ b/Source/core/dom/Microtask.h
@@ -33,9 +33,12 @@
 
 namespace WebCore {
 
+typedef void (*MicrotaskCallback)();
+
 class Microtask {
 public:
     static void performCheckpoint();
+    static void enqueueMicrotask(MicrotaskCallback);
 
 private:
     explicit Microtask();
diff --git a/Source/core/dom/MutationObserver.cpp b/Source/core/dom/MutationObserver.cpp
index 06e610a..21bdd69 100644
--- a/Source/core/dom/MutationObserver.cpp
+++ b/Source/core/dom/MutationObserver.cpp
@@ -36,10 +36,12 @@
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/dom/Microtask.h"
 #include "core/dom/MutationCallback.h"
 #include "core/dom/MutationObserverRegistration.h"
 #include "core/dom/MutationRecord.h"
 #include "core/dom/Node.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "wtf/MainThread.h"
 
 namespace WebCore {
@@ -69,6 +71,8 @@
 MutationObserver::~MutationObserver()
 {
     ASSERT(m_registrations.isEmpty());
+    if (!m_records.isEmpty())
+        InspectorInstrumentation::didClearAllMutationRecords(m_callback->executionContext(), this);
 }
 
 void MutationObserver::observe(Node* node, const Dictionary& optionsDictionary, ExceptionState& exceptionState)
@@ -140,12 +144,14 @@
 {
     Vector<RefPtr<MutationRecord> > records;
     records.swap(m_records);
+    InspectorInstrumentation::didClearAllMutationRecords(m_callback->executionContext(), this);
     return records;
 }
 
 void MutationObserver::disconnect()
 {
     m_records.clear();
+    InspectorInstrumentation::didClearAllMutationRecords(m_callback->executionContext(), this);
     HashSet<MutationObserverRegistration*> registrations(m_registrations);
     for (HashSet<MutationObserverRegistration*>::iterator iter = registrations.begin(); iter != registrations.end(); ++iter)
         (*iter)->unregister();
@@ -177,17 +183,26 @@
     return suspendedObservers;
 }
 
+static void activateObserver(PassRefPtr<MutationObserver> observer)
+{
+    if (activeMutationObservers().isEmpty())
+        Microtask::enqueueMicrotask(&MutationObserver::deliverMutations);
+
+    activeMutationObservers().add(observer);
+}
+
 void MutationObserver::enqueueMutationRecord(PassRefPtr<MutationRecord> mutation)
 {
     ASSERT(isMainThread());
     m_records.append(mutation);
-    activeMutationObservers().add(this);
+    activateObserver(this);
+    InspectorInstrumentation::didEnqueueMutationRecord(m_callback->executionContext(), this);
 }
 
 void MutationObserver::setHasTransientRegistration()
 {
     ASSERT(isMainThread());
-    activeMutationObservers().add(this);
+    activateObserver(this);
 }
 
 HashSet<Node*> MutationObserver::getObservedNodes() const
@@ -223,43 +238,40 @@
     Vector<RefPtr<MutationRecord> > records;
     records.swap(m_records);
 
+    InspectorInstrumentation::willDeliverMutationRecords(m_callback->executionContext(), this);
     m_callback->call(records, this);
+    InspectorInstrumentation::didDeliverMutationRecords(m_callback->executionContext());
 }
 
-void MutationObserver::deliverAllMutations()
+void MutationObserver::resumeSuspendedObservers()
 {
     ASSERT(isMainThread());
-    static bool deliveryInProgress = false;
-    if (deliveryInProgress)
+    if (suspendedMutationObservers().isEmpty())
         return;
-    deliveryInProgress = true;
 
-    if (!suspendedMutationObservers().isEmpty()) {
-        Vector<RefPtr<MutationObserver> > suspended;
-        copyToVector(suspendedMutationObservers(), suspended);
-        for (size_t i = 0; i < suspended.size(); ++i) {
-            if (!suspended[i]->canDeliver())
-                continue;
-
+    Vector<RefPtr<MutationObserver> > suspended;
+    copyToVector(suspendedMutationObservers(), suspended);
+    for (size_t i = 0; i < suspended.size(); ++i) {
+        if (suspended[i]->canDeliver()) {
             suspendedMutationObservers().remove(suspended[i]);
-            activeMutationObservers().add(suspended[i]);
+            activateObserver(suspended[i]);
         }
     }
+}
 
-    while (!activeMutationObservers().isEmpty()) {
-        Vector<RefPtr<MutationObserver> > observers;
-        copyToVector(activeMutationObservers(), observers);
-        activeMutationObservers().clear();
-        std::sort(observers.begin(), observers.end(), ObserverLessThan());
-        for (size_t i = 0; i < observers.size(); ++i) {
-            if (observers[i]->canDeliver())
-                observers[i]->deliver();
-            else
-                suspendedMutationObservers().add(observers[i]);
-        }
+void MutationObserver::deliverMutations()
+{
+    ASSERT(isMainThread());
+    Vector<RefPtr<MutationObserver> > observers;
+    copyToVector(activeMutationObservers(), observers);
+    activeMutationObservers().clear();
+    std::sort(observers.begin(), observers.end(), ObserverLessThan());
+    for (size_t i = 0; i < observers.size(); ++i) {
+        if (observers[i]->canDeliver())
+            observers[i]->deliver();
+        else
+            suspendedMutationObservers().add(observers[i]);
     }
-
-    deliveryInProgress = false;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/MutationObserver.h b/Source/core/dom/MutationObserver.h
index 062d01e..a5f3aa3 100644
--- a/Source/core/dom/MutationObserver.h
+++ b/Source/core/dom/MutationObserver.h
@@ -71,7 +71,8 @@
     };
 
     static PassRefPtr<MutationObserver> create(PassOwnPtr<MutationCallback>);
-    static void deliverAllMutations();
+    static void resumeSuspendedObservers();
+    static void deliverMutations();
 
     ~MutationObserver();
 
diff --git a/Source/core/dom/MutationObserver.idl b/Source/core/dom/MutationObserver.idl
index e87fa44..05acb2a 100644
--- a/Source/core/dom/MutationObserver.idl
+++ b/Source/core/dom/MutationObserver.idl
@@ -29,7 +29,8 @@
  */
 
 [
-    CustomConstructor(MutationCallback callback)
+    CustomConstructor(MutationCallback callback),
+    Custom=VisitDOMWrapper
 ] interface MutationObserver {
     [RaisesException] void observe(Node target, Dictionary options);
     sequence<MutationRecord> takeRecords();
diff --git a/Source/core/dom/NameNodeList.cpp b/Source/core/dom/NameNodeList.cpp
index 69634c9..6393eba 100644
--- a/Source/core/dom/NameNodeList.cpp
+++ b/Source/core/dom/NameNodeList.cpp
@@ -31,7 +31,7 @@
 
 using namespace HTMLNames;
 
-NameNodeList::NameNodeList(PassRefPtr<Node> rootNode, const AtomicString& name)
+NameNodeList::NameNodeList(PassRefPtr<ContainerNode> rootNode, const AtomicString& name)
     : LiveNodeList(rootNode, NameNodeListType, InvalidateOnNameAttrChange)
     , m_name(name)
 {
@@ -39,12 +39,12 @@
 
 NameNodeList::~NameNodeList()
 {
-    ownerNode()->nodeLists()->removeCacheWithAtomicName(this, NameNodeListType, m_name);
+    ownerNode()->nodeLists()->removeCache(this, NameNodeListType, m_name);
 }
 
-bool NameNodeList::nodeMatches(Element* testNode) const
+bool NameNodeList::nodeMatches(const Element& testNode) const
 {
-    return testNode->getNameAttribute() == m_name;
+    return testNode.getNameAttribute() == m_name;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/NameNodeList.h b/Source/core/dom/NameNodeList.h
index 5a595d8..2212fb1 100644
--- a/Source/core/dom/NameNodeList.h
+++ b/Source/core/dom/NameNodeList.h
@@ -33,7 +33,7 @@
 // NodeList which lists all Nodes in a Element with a given "name" attribute
 class NameNodeList FINAL : public LiveNodeList {
 public:
-    static PassRefPtr<NameNodeList> create(PassRefPtr<Node> rootNode, CollectionType type, const AtomicString& name)
+    static PassRefPtr<NameNodeList> create(PassRefPtr<ContainerNode> rootNode, CollectionType type, const AtomicString& name)
     {
         ASSERT_UNUSED(type, type == NameNodeListType);
         return adoptRef(new NameNodeList(rootNode, name));
@@ -42,9 +42,9 @@
     virtual ~NameNodeList();
 
 private:
-    NameNodeList(PassRefPtr<Node> rootNode, const AtomicString& name);
+    NameNodeList(PassRefPtr<ContainerNode> rootNode, const AtomicString& name);
 
-    virtual bool nodeMatches(Element*) const OVERRIDE;
+    virtual bool nodeMatches(const Element&) const OVERRIDE;
 
     AtomicString m_name;
 };
diff --git a/Source/core/dom/NamedFlow.cpp b/Source/core/dom/NamedFlow.cpp
deleted file mode 100644
index 04f1c08..0000000
--- a/Source/core/dom/NamedFlow.cpp
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-#include "config.h"
-#include "core/dom/NamedFlow.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/dom/NamedFlowCollection.h"
-#include "core/dom/StaticNodeList.h"
-#include "core/events/ThreadLocalEventNames.h"
-#include "core/events/UIEvent.h"
-#include "core/rendering/RenderNamedFlowFragment.h"
-#include "core/rendering/RenderNamedFlowThread.h"
-
-namespace WebCore {
-
-NamedFlow::NamedFlow(PassRefPtr<NamedFlowCollection> manager, const AtomicString& flowThreadName)
-    : m_flowThreadName(flowThreadName)
-    , m_flowManager(manager)
-    , m_parentFlowThread(0)
-{
-    ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
-    ScriptWrappable::init(this);
-}
-
-NamedFlow::~NamedFlow()
-{
-    // The named flow is not "strong" referenced from anywhere at this time so it shouldn't be reused if the named flow is recreated.
-    m_flowManager->discardNamedFlow(this);
-}
-
-PassRefPtr<NamedFlow> NamedFlow::create(PassRefPtr<NamedFlowCollection> manager, const AtomicString& flowThreadName)
-{
-    return adoptRef(new NamedFlow(manager, flowThreadName));
-}
-
-const AtomicString& NamedFlow::name() const
-{
-    return m_flowThreadName;
-}
-
-bool NamedFlow::overset() const
-{
-    if (m_flowManager->document())
-        m_flowManager->document()->updateLayoutIgnorePendingStylesheets();
-
-    // The renderer may be destroyed or created after the style update.
-    // Because this is called from JS, where the wrapper keeps a reference to the NamedFlow, no guard is necessary.
-    return m_parentFlowThread ? m_parentFlowThread->overset() : true;
-}
-
-static inline bool inFlowThread(RenderObject* renderer, RenderNamedFlowThread* flowThread)
-{
-    if (!renderer)
-        return false;
-    RenderFlowThread* currentFlowThread = renderer->flowThreadContainingBlock();
-    if (flowThread == currentFlowThread)
-        return true;
-    if (renderer->flowThreadState() != RenderObject::InsideInFlowThread)
-        return false;
-
-    // An in-flow flow thread can be nested inside an out-of-flow one, so we have to recur up to check.
-    return inFlowThread(currentFlowThread->containingBlock(), flowThread);
-}
-
-int NamedFlow::firstEmptyRegionIndex() const
-{
-    if (m_flowManager->document())
-        m_flowManager->document()->updateLayoutIgnorePendingStylesheets();
-
-    if (!m_parentFlowThread)
-        return -1;
-
-    const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
-    if (regionList.isEmpty())
-        return -1;
-
-    int countNonPseudoRegions = -1;
-    RenderRegionList::const_iterator iter = regionList.begin();
-    for (int index = 0; iter != regionList.end(); ++index, ++iter) {
-        const RenderNamedFlowFragment* renderRegion = toRenderNamedFlowFragment(*iter);
-        // FIXME: Pseudo-elements are not included in the list.
-        // They will be included when we will properly support the Region interface
-        // http://dev.w3.org/csswg/css-regions/#the-region-interface
-        if (!renderRegion->isElementBasedRegion())
-            continue;
-        countNonPseudoRegions++;
-        if (renderRegion->regionOversetState() == RegionEmpty)
-            return countNonPseudoRegions;
-    }
-    return -1;
-}
-
-PassRefPtr<NodeList> NamedFlow::getRegionsByContent(Node* contentNode)
-{
-    Vector<RefPtr<Node> > regionNodes;
-
-    if (!contentNode)
-        return StaticNodeList::adopt(regionNodes);
-
-    if (m_flowManager->document())
-        m_flowManager->document()->updateLayoutIgnorePendingStylesheets();
-
-    // The renderer may be destroyed or created after the style update.
-    // Because this is called from JS, where the wrapper keeps a reference to the NamedFlow, no guard is necessary.
-    if (!m_parentFlowThread)
-        return StaticNodeList::adopt(regionNodes);
-
-    if (inFlowThread(contentNode->renderer(), m_parentFlowThread)) {
-        const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
-        for (RenderRegionList::const_iterator iter = regionList.begin(); iter != regionList.end(); ++iter) {
-            const RenderNamedFlowFragment* renderRegion = toRenderNamedFlowFragment(*iter);
-            // They will be included when we will properly support the Region interface
-            // http://dev.w3.org/csswg/css-regions/#the-region-interface
-            if (!renderRegion->isElementBasedRegion())
-                continue;
-            if (m_parentFlowThread->objectInFlowRegion(contentNode->renderer(), renderRegion))
-                regionNodes.append(renderRegion->nodeForRegion());
-        }
-    }
-
-    return StaticNodeList::adopt(regionNodes);
-}
-
-PassRefPtr<NodeList> NamedFlow::getRegions()
-{
-    Vector<RefPtr<Node> > regionNodes;
-
-    if (m_flowManager->document())
-        m_flowManager->document()->updateLayoutIgnorePendingStylesheets();
-
-    // The renderer may be destroyed or created after the style update.
-    // Because this is called from JS, where the wrapper keeps a reference to the NamedFlow, no guard is necessary.
-    if (!m_parentFlowThread)
-        return StaticNodeList::adopt(regionNodes);
-
-    const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
-    for (RenderRegionList::const_iterator iter = regionList.begin(); iter != regionList.end(); ++iter) {
-        const RenderNamedFlowFragment* renderRegion = toRenderNamedFlowFragment(*iter);
-        // They will be included when we will properly support the Region interface
-        // http://dev.w3.org/csswg/css-regions/#the-region-interface
-        if (!renderRegion->isElementBasedRegion())
-            continue;
-        regionNodes.append(renderRegion->nodeForRegion());
-    }
-
-    return StaticNodeList::adopt(regionNodes);
-}
-
-PassRefPtr<NodeList> NamedFlow::getContent()
-{
-    Vector<RefPtr<Node> > contentNodes;
-
-    if (m_flowManager->document())
-        m_flowManager->document()->updateLayoutIgnorePendingStylesheets();
-
-    // The renderer may be destroyed or created after the style update.
-    // Because this is called from JS, where the wrapper keeps a reference to the NamedFlow, no guard is necessary.
-    if (!m_parentFlowThread)
-        return StaticNodeList::adopt(contentNodes);
-
-    const NamedFlowContentNodes& contentNodesList = m_parentFlowThread->contentNodes();
-    for (NamedFlowContentNodes::const_iterator it = contentNodesList.begin(); it != contentNodesList.end(); ++it) {
-        Node* node = *it;
-        ASSERT(node->computedStyle()->flowThread() == m_parentFlowThread->flowThreadName());
-        contentNodes.append(node);
-    }
-
-    return StaticNodeList::adopt(contentNodes);
-}
-
-void NamedFlow::setRenderer(RenderNamedFlowThread* parentFlowThread)
-{
-    // The named flow can either go from a no_renderer->renderer or renderer->no_renderer state; anything else could indicate a bug.
-    ASSERT((!m_parentFlowThread && parentFlowThread) || (m_parentFlowThread && !parentFlowThread));
-
-    // If parentFlowThread is 0, the flow thread will move in the "NULL" state.
-    m_parentFlowThread = parentFlowThread;
-}
-
-void NamedFlow::dispatchRegionLayoutUpdateEvent()
-{
-    ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
-
-    // If the flow is in the "NULL" state the event should not be dispatched any more.
-    if (flowState() == FlowStateNull)
-        return;
-
-    RefPtr<Event> event = UIEvent::create(EventTypeNames::webkitregionlayoutupdate, false, false, m_flowManager->document()->domWindow(), 0);
-
-    dispatchEvent(event);
-}
-
-void NamedFlow::dispatchRegionOversetChangeEvent()
-{
-    ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
-
-    // If the flow is in the "NULL" state the event should not be dispatched any more.
-    if (flowState() == FlowStateNull)
-        return;
-
-    RefPtr<Event> event = UIEvent::create(EventTypeNames::webkitregionoversetchange, false, false, m_flowManager->document()->domWindow(), 0);
-
-    dispatchEvent(event);
-}
-
-const AtomicString& NamedFlow::interfaceName() const
-{
-    return EventTargetNames::NamedFlow;
-}
-
-ExecutionContext* NamedFlow::executionContext() const
-{
-    return m_flowManager->document();
-}
-
-Node* NamedFlow::ownerNode() const
-{
-    return m_flowManager->document();
-}
-
-} // namespace WebCore
-
diff --git a/Source/core/dom/NamedFlow.h b/Source/core/dom/NamedFlow.h
deleted file mode 100644
index 75f2bd5..0000000
--- a/Source/core/dom/NamedFlow.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef NamedFlow_h
-#define NamedFlow_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/events/EventTarget.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class Document;
-class NamedFlowCollection;
-class Node;
-class NodeList;
-class RenderNamedFlowThread;
-class ExecutionContext;
-
-class NamedFlow : public RefCounted<NamedFlow>, public ScriptWrappable, public EventTargetWithInlineData {
-    REFCOUNTED_EVENT_TARGET(NamedFlow);
-public:
-    static PassRefPtr<NamedFlow> create(PassRefPtr<NamedFlowCollection> manager, const AtomicString& flowThreadName);
-
-    ~NamedFlow();
-
-    const AtomicString& name() const;
-    bool overset() const;
-    int firstEmptyRegionIndex() const;
-    PassRefPtr<NodeList> getRegionsByContent(Node*);
-    PassRefPtr<NodeList> getRegions();
-    PassRefPtr<NodeList> getContent();
-
-    virtual const AtomicString& interfaceName() const OVERRIDE;
-    virtual ExecutionContext* executionContext() const OVERRIDE;
-
-    // This function is called from the JS binding code to determine if the NamedFlow object is reachable or not.
-    // If the object has listeners, the object should only be discarded if the parent Document is not reachable.
-    Node* ownerNode() const;
-
-    void setRenderer(RenderNamedFlowThread* parentFlowThread);
-
-    enum FlowState {
-        FlowStateCreated,
-        FlowStateNull
-    };
-
-    FlowState flowState() const { return m_parentFlowThread ? FlowStateCreated : FlowStateNull; }
-
-    void dispatchRegionLayoutUpdateEvent();
-    void dispatchRegionOversetChangeEvent();
-
-private:
-    NamedFlow(PassRefPtr<NamedFlowCollection>, const AtomicString&);
-
-    // The name of the flow thread as specified in CSS.
-    AtomicString m_flowThreadName;
-
-    RefPtr<NamedFlowCollection> m_flowManager;
-    RenderNamedFlowThread* m_parentFlowThread;
-};
-
-}
-
-#endif
diff --git a/Source/core/dom/NamedFlowCollection.cpp b/Source/core/dom/NamedFlowCollection.cpp
deleted file mode 100644
index 2b48c7b..0000000
--- a/Source/core/dom/NamedFlowCollection.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-#include "config.h"
-#include "core/dom/NamedFlowCollection.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/dom/DOMNamedFlowCollection.h"
-#include "core/dom/Document.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-NamedFlowCollection::NamedFlowCollection(Document* document)
-    : DocumentLifecycleObserver(document)
-{
-    ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
-}
-
-Vector<RefPtr<NamedFlow> > NamedFlowCollection::namedFlows()
-{
-    Vector<RefPtr<NamedFlow> > namedFlows;
-
-    for (NamedFlowSet::iterator it = m_namedFlows.begin(); it != m_namedFlows.end(); ++it) {
-        if ((*it)->flowState() == NamedFlow::FlowStateNull)
-            continue;
-
-        namedFlows.append(RefPtr<NamedFlow>(*it));
-    }
-
-    return namedFlows;
-}
-
-NamedFlow* NamedFlowCollection::flowByName(const String& flowName)
-{
-    NamedFlowSet::iterator it = m_namedFlows.find<NamedFlowHashTranslator>(flowName);
-    if (it == m_namedFlows.end() || (*it)->flowState() == NamedFlow::FlowStateNull)
-        return 0;
-
-    return *it;
-}
-
-PassRefPtr<NamedFlow> NamedFlowCollection::ensureFlowWithName(const String& flowName)
-{
-    NamedFlowSet::iterator it = m_namedFlows.find<NamedFlowHashTranslator>(flowName);
-    if (it != m_namedFlows.end()) {
-        NamedFlow* namedFlow = *it;
-        ASSERT(namedFlow->flowState() == NamedFlow::FlowStateNull);
-
-        return namedFlow;
-    }
-
-    RefPtr<NamedFlow> newFlow = NamedFlow::create(this, flowName);
-    m_namedFlows.add(newFlow.get());
-
-    InspectorInstrumentation::didCreateNamedFlow(document(), newFlow.get());
-
-    return newFlow.release();
-}
-
-void NamedFlowCollection::discardNamedFlow(NamedFlow* namedFlow)
-{
-    // The document is not valid anymore so the collection will be destroyed anyway.
-    if (!document())
-        return;
-
-    ASSERT(namedFlow->flowState() == NamedFlow::FlowStateNull);
-    ASSERT(m_namedFlows.contains(namedFlow));
-
-    InspectorInstrumentation::willRemoveNamedFlow(document(), namedFlow);
-
-    m_namedFlows.remove(namedFlow);
-}
-
-Document* NamedFlowCollection::document() const
-{
-    return lifecycleContext();
-}
-
-PassRefPtr<DOMNamedFlowCollection> NamedFlowCollection::createCSSOMSnapshot()
-{
-    Vector<NamedFlow*> createdFlows;
-    for (NamedFlowSet::iterator it = m_namedFlows.begin(); it != m_namedFlows.end(); ++it)
-        if ((*it)->flowState() == NamedFlow::FlowStateCreated)
-            createdFlows.append(*it);
-    return DOMNamedFlowCollection::create(createdFlows);
-}
-
-// The HashFunctions object used by the HashSet to compare between NamedFlows.
-// It is safe to set safeToCompareToEmptyOrDeleted because the HashSet will never contain null pointers or deleted values.
-struct NamedFlowCollection::NamedFlowHashFunctions {
-    static unsigned hash(NamedFlow* key) { return DefaultHash<String>::Hash::hash(key->name()); }
-    static bool equal(NamedFlow* a, NamedFlow* b) { return a->name() == b->name(); }
-    static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-// The HashTranslator is used to lookup a NamedFlow in the set using a name.
-struct NamedFlowCollection::NamedFlowHashTranslator {
-    static unsigned hash(const String& key) { return DefaultHash<String>::Hash::hash(key); }
-    static bool equal(NamedFlow* a, const String& b) { return a->name() == b; }
-};
-
-} // namespace WebCore
diff --git a/Source/core/dom/NamedFlowCollection.h b/Source/core/dom/NamedFlowCollection.h
deleted file mode 100644
index f9c4b9c..0000000
--- a/Source/core/dom/NamedFlowCollection.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef NamedFlowCollection_h
-#define NamedFlowCollection_h
-
-#include "core/dom/DocumentLifecycleObserver.h"
-#include "core/dom/NamedFlow.h"
-#include "wtf/Forward.h"
-#include "wtf/ListHashSet.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class Document;
-class DOMNamedFlowCollection;
-
-class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public DocumentLifecycleObserver {
-public:
-    static PassRefPtr<NamedFlowCollection> create(Document* doc) { return adoptRef(new NamedFlowCollection(doc)); }
-
-    Vector<RefPtr<NamedFlow> > namedFlows();
-    NamedFlow* flowByName(const String&);
-    PassRefPtr<NamedFlow> ensureFlowWithName(const String&);
-
-    void discardNamedFlow(NamedFlow*);
-
-    Document* document() const;
-
-    virtual ~NamedFlowCollection() { }
-
-    PassRefPtr<DOMNamedFlowCollection> createCSSOMSnapshot();
-
-private:
-    struct NamedFlowHashFunctions;
-    struct NamedFlowHashTranslator;
-
-    typedef ListHashSet<NamedFlow*, 1, NamedFlowHashFunctions> NamedFlowSet;
-
-    explicit NamedFlowCollection(Document*);
-
-    NamedFlowSet m_namedFlows;
-};
-
-} // namespace WebCore
-
-#endif // NamedFlowCollection_h
diff --git a/Source/core/dom/NamedNodeMap.cpp b/Source/core/dom/NamedNodeMap.cpp
index 2265972..499f7b6 100644
--- a/Source/core/dom/NamedNodeMap.cpp
+++ b/Source/core/dom/NamedNodeMap.cpp
@@ -59,7 +59,7 @@
 {
     size_t index = m_element->hasAttributes() ? m_element->getAttributeItemIndex(name, m_element->shouldIgnoreAttributeCase()) : kNotFound;
     if (index == kNotFound) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No item with name '" + name + "' was found.");
         return 0;
     }
     return m_element->detachAttribute(index);
@@ -69,7 +69,7 @@
 {
     size_t index = m_element->hasAttributes() ? m_element->getAttributeItemIndex(QualifiedName(nullAtom, localName, namespaceURI)) : kNotFound;
     if (index == kNotFound) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No item with name '" + namespaceURI + "::" + localName + "' was found.");
         return 0;
     }
     return m_element->detachAttribute(index);
@@ -78,13 +78,13 @@
 PassRefPtr<Node> NamedNodeMap::setNamedItem(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided was null.");
         return 0;
     }
 
     // Not mentioned in spec: throw a HIERARCHY_REQUEST_ERROR if the user passes in a non-attribute node
     if (!node->isAttributeNode()) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwDOMException(HierarchyRequestError, "The node provided is not an attribute node.");
         return 0;
     }
 
diff --git a/Source/core/dom/NamedNodeMap.h b/Source/core/dom/NamedNodeMap.h
index f01102c..d167e77 100644
--- a/Source/core/dom/NamedNodeMap.h
+++ b/Source/core/dom/NamedNodeMap.h
@@ -68,7 +68,7 @@
     explicit NamedNodeMap(Element* element)
         : m_element(element)
     {
-        // Only supports NamedNodeMaps with Element associated, DocumentType.entities and DocumentType.notations are not supported yet.
+        // Only supports NamedNodeMaps with Element associated.
         ASSERT(m_element);
         ScriptWrappable::init(this);
     }
diff --git a/Source/core/dom/NamedNodeMap.idl b/Source/core/dom/NamedNodeMap.idl
index 0f51574..783611a 100644
--- a/Source/core/dom/NamedNodeMap.idl
+++ b/Source/core/dom/NamedNodeMap.idl
@@ -19,7 +19,7 @@
  */
 
 [
-    GenerateVisitDOMWrapper=element,
+    SetWrapperReferenceFrom=element,
 ] interface NamedNodeMap {
 
     Node getNamedItem([Default=Undefined] optional DOMString name);
diff --git a/Source/core/dom/NamedNodesCollection.cpp b/Source/core/dom/NamedNodesCollection.cpp
index fb6b772..0b1701c 100644
--- a/Source/core/dom/NamedNodesCollection.cpp
+++ b/Source/core/dom/NamedNodesCollection.cpp
@@ -41,14 +41,4 @@
     return 0;
 }
 
-Node* NamedNodesCollection::namedItem(const AtomicString& id) const
-{
-    for (unsigned i = 0; i < m_nodes.size(); ++i) {
-        Node* node = m_nodes[i].get();
-        if (node->hasID() && toElement(node)->getIdAttribute() == id)
-            return node;
-    }
-    return 0;
-}
-
 } // namespace WebCore
diff --git a/Source/core/dom/NamedNodesCollection.h b/Source/core/dom/NamedNodesCollection.h
index b202bcf..6c33cac 100644
--- a/Source/core/dom/NamedNodesCollection.h
+++ b/Source/core/dom/NamedNodesCollection.h
@@ -41,20 +41,19 @@
 
 class NamedNodesCollection FINAL : public NodeList {
 public:
-    static PassRefPtr<NodeList> create(const Vector<RefPtr<Node> >& nodes)
+    static PassRefPtr<NodeList> create(const Vector<RefPtr<Element> >& nodes)
     {
         return adoptRef(new NamedNodesCollection(nodes));
     }
 
     virtual unsigned length() const OVERRIDE { return m_nodes.size(); }
     virtual Node* item(unsigned) const OVERRIDE;
-    virtual Node* namedItem(const AtomicString&) const OVERRIDE;
 
 private:
-    explicit NamedNodesCollection(const Vector<RefPtr<Node> >& nodes)
+    explicit NamedNodesCollection(const Vector<RefPtr<Element> >& nodes)
         : m_nodes(nodes) { }
 
-    Vector<RefPtr<Node> > m_nodes;
+    Vector<RefPtr<Element> > m_nodes;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index c9fae12..1671ca9 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -28,12 +28,12 @@
 #include "HTMLNames.h"
 #include "XMLNames.h"
 #include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/ScriptCallStackFactory.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/Attr.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/ChildListMutationScope.h"
 #include "core/dom/ChildNodeList.h"
-#include "core/dom/ClassNodeList.h"
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
@@ -41,15 +41,15 @@
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
 #include "core/dom/ElementRareData.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/LiveNodeList.h"
-#include "core/dom/NameNodeList.h"
 #include "core/dom/NodeRareData.h"
+#include "core/dom/NodeRenderingTraversal.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/Range.h"
-#include "core/dom/SelectorQuery.h"
-#include "core/dom/TagNodeList.h"
+#include "core/dom/StaticNodeList.h"
 #include "core/dom/TemplateContentDocumentFragment.h"
 #include "core/dom/Text.h"
 #include "core/dom/TreeScopeAdopter.h"
@@ -77,12 +77,11 @@
 #include "core/html/HTMLDialogElement.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLStyleElement.h"
-#include "core/html/RadioNodeList.h"
 #include "core/page/ContextMenuController.h"
 #include "core/page/EventHandler.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/RenderBox.h"
 #include "core/svg/graphics/SVGImage.h"
@@ -112,11 +111,6 @@
     partitionFree(ptr);
 }
 
-bool Node::isSupported(const String& feature, const String& version)
-{
-    return DOMImplementation::hasFeature(feature, version);
-}
-
 #if DUMP_NODE_STATISTICS
 static HashSet<Node*> liveNodeSet;
 #endif
@@ -131,13 +125,10 @@
     size_t textNodes = 0;
     size_t cdataNodes = 0;
     size_t commentNodes = 0;
-    size_t entityNodes = 0;
     size_t piNodes = 0;
     size_t documentNodes = 0;
     size_t docTypeNodes = 0;
     size_t fragmentNodes = 0;
-    size_t notationNodes = 0;
-    size_t xpathNSNodes = 0;
     size_t shadowRootNodes = 0;
 
     HashMap<String, size_t> perTagCount;
@@ -168,7 +159,7 @@
                 Element* element = toElement(node);
                 HashMap<String, size_t>::AddResult result = perTagCount.add(element->tagName(), 1);
                 if (!result.isNewEntry)
-                    result.iterator->value++;
+                    result.storedValue->value++;
 
                 if (ElementData* elementData = element->elementData()) {
                     attributes += elementData->length();
@@ -197,10 +188,6 @@
                 ++commentNodes;
                 break;
             }
-            case ENTITY_NODE: {
-                ++entityNodes;
-                break;
-            }
             case PROCESSING_INSTRUCTION_NODE: {
                 ++piNodes;
                 break;
@@ -220,14 +207,6 @@
                     ++fragmentNodes;
                 break;
             }
-            case NOTATION_NODE: {
-                ++notationNodes;
-                break;
-            }
-            case XPATH_NAMESPACE_NODE: {
-                ++xpathNSNodes;
-                break;
-            }
         }
     }
 
@@ -240,13 +219,10 @@
     printf("  Number of Text nodes: %zu\n", textNodes);
     printf("  Number of CDATASection nodes: %zu\n", cdataNodes);
     printf("  Number of Comment nodes: %zu\n", commentNodes);
-    printf("  Number of Entity nodes: %zu\n", entityNodes);
     printf("  Number of ProcessingInstruction nodes: %zu\n", piNodes);
     printf("  Number of Document nodes: %zu\n", documentNodes);
     printf("  Number of DocumentType nodes: %zu\n", docTypeNodes);
     printf("  Number of DocumentFragment nodes: %zu\n", fragmentNodes);
-    printf("  Number of Notation nodes: %zu\n", notationNodes);
-    printf("  Number of XPathNS nodes: %zu\n", xpathNSNodes);
     printf("  Number of ShadowRoot nodes: %zu\n", shadowRootNodes);
 
     printf("Element tag name distibution:\n");
@@ -298,26 +274,28 @@
     if (m_next)
         m_next->setPreviousSibling(0);
 
-    m_treeScope->guardDeref();
+    if (m_treeScope)
+        m_treeScope->guardDeref();
 
     InspectorCounters::decrementCounter(InspectorCounters::NodeCounter);
 }
 
 void Node::willBeDeletedFromDocument()
 {
-    Document* document = documentInternal();
-    if (!document)
+    if (!isTreeScopeInitialized())
         return;
 
+    Document& document = this->document();
+
     if (hasEventTargetData()) {
-        document->didRemoveEventTargetNode(this);
         clearEventTargetData();
+        document.didClearTouchEventHandlers(this);
     }
 
-    if (AXObjectCache* cache = document->existingAXObjectCache())
+    if (AXObjectCache* cache = document.existingAXObjectCache())
         cache->remove(this);
 
-    document->markers()->removeMarkers(this);
+    document.markers()->removeMarkers(this);
 }
 
 NodeRareData* Node::rareData() const
@@ -379,7 +357,9 @@
 
 PassRefPtr<NodeList> Node::childNodes()
 {
-    return ensureRareData().ensureNodeLists().ensureChildNodeList(this);
+    if (isContainerNode())
+        return ensureRareData().ensureNodeLists().ensureChildNodeList(toContainerNode(this));
+    return ensureRareData().ensureNodeLists().ensureEmptyChildNodeList(this);
 }
 
 Node& Node::lastDescendant() const
@@ -508,20 +488,6 @@
     }
 }
 
-const AtomicString& Node::prefix() const
-{
-    // For nodes other than elements and attributes, the prefix is always null
-    return nullAtom;
-}
-
-void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionState& exceptionState)
-{
-    // The spec says that for nodes other than elements and attributes, prefix is always null.
-    // It does not say what to do when the user tries to set the prefix on another type of
-    // node, however Mozilla throws a NamespaceError exception.
-    exceptionState.throwDOMException(NamespaceError, "Prefixes are only supported on element and attribute nodes.");
-}
-
 const AtomicString& Node::localName() const
 {
     return nullAtom;
@@ -617,21 +583,6 @@
     return LayoutRect();
 }
 
-LayoutRect Node::renderRect(bool* isReplaced)
-{
-    RenderObject* hitRenderer = this->renderer();
-    ASSERT(hitRenderer);
-    RenderObject* renderer = hitRenderer;
-    while (renderer && !renderer->isBody() && !renderer->isRoot()) {
-        if (renderer->isRenderBlock() || renderer->isInlineBlockOrInlineTable() || renderer->isReplaced()) {
-            *isReplaced = renderer->isReplaced();
-            return renderer->absoluteBoundingBoxRect();
-        }
-        renderer = renderer->parent();
-    }
-    return LayoutRect();
-}
-
 bool Node::hasNonEmptyBoundingBox() const
 {
     // Before calling absoluteRects, check for the common case where the renderer
@@ -689,6 +640,20 @@
     setFlag(isLink && !SVGImage::isInSVGImage(toElement(this)), IsLinkFlag);
 }
 
+void Node::setNeedsStyleInvalidation()
+{
+    setFlag(NeedsStyleInvalidation);
+    markAncestorsWithChildNeedsStyleInvalidation();
+}
+
+void Node::markAncestorsWithChildNeedsStyleInvalidation()
+{
+    for (Node* node = this; node && !node->childNeedsStyleInvalidation(); node = node->parentOrShadowHostNode())
+        node->setChildNeedsStyleInvalidation();
+    if (document().childNeedsStyleInvalidation())
+        document().scheduleStyleRecalc();
+}
+
 void Node::markAncestorsWithChildNeedsDistributionRecalc()
 {
     for (Node* node = this; node && !node->childNeedsDistributionRecalc(); node = node->parentOrShadowHostNode())
@@ -697,6 +662,79 @@
         document().scheduleStyleRecalc();
 }
 
+namespace {
+
+unsigned styledSubtreeSize(const Node*);
+
+unsigned styledSubtreeSizeIgnoringSelfAndShadowRoots(const Node* rootNode)
+{
+    unsigned nodeCount = 0;
+    for (Node* child = rootNode->firstChild(); child; child = child->nextSibling())
+        nodeCount += styledSubtreeSize(child);
+    return nodeCount;
+}
+
+unsigned styledSubtreeSize(const Node* rootNode)
+{
+    if (rootNode->isTextNode())
+        return 1;
+    if (!rootNode->isElementNode())
+        return 0;
+
+    // FIXME: We should use a shadow-tree aware node-iterator when such exists.
+    unsigned nodeCount = 1 + styledSubtreeSizeIgnoringSelfAndShadowRoots(rootNode);
+
+    // ShadowRoots don't have style (so don't count them), but their children might.
+    for (ShadowRoot* shadowRoot = rootNode->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot())
+        nodeCount += styledSubtreeSizeIgnoringSelfAndShadowRoots(shadowRoot);
+
+    return nodeCount;
+}
+
+PassRefPtr<JSONArray> jsStackAsJSONArray()
+{
+    RefPtr<JSONArray> jsonArray = JSONArray::create();
+    RefPtr<ScriptCallStack> stack = createScriptCallStack(10);
+    if (!stack)
+        return jsonArray.release();
+    for (size_t i = 0; i < stack->size(); i++)
+        jsonArray->pushString(stack->at(i).functionName());
+    return jsonArray.release();
+}
+
+PassRefPtr<JSONObject> jsonObjectForStyleInvalidation(unsigned nodeCount, const Node* rootNode)
+{
+    RefPtr<JSONObject> jsonObject = JSONObject::create();
+    jsonObject->setNumber("node_count", nodeCount);
+    jsonObject->setString("root_node", rootNode->debugName());
+    jsonObject->setArray("js_stack", jsStackAsJSONArray());
+    return jsonObject.release();
+}
+
+} // anonymous namespace'd functions supporting traceStyleChange
+
+void Node::traceStyleChange(StyleChangeType changeType)
+{
+    static const unsigned kMinLoggedSize = 100;
+    unsigned nodeCount = styledSubtreeSize(this);
+    if (nodeCount < kMinLoggedSize)
+        return;
+
+    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("style.debug"),
+        "Node::setNeedsStyleRecalc",
+        "data", jsonObjectForStyleInvalidation(nodeCount, this)->toJSONString().ascii()
+    );
+}
+
+void Node::traceStyleChangeIfNeeded(StyleChangeType changeType)
+{
+    // TRACE_EVENT_CATEGORY_GROUP_ENABLED macro loads a global static bool into our local bool.
+    bool styleTracingEnabled;
+    TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("style.debug"), &styleTracingEnabled);
+    if (UNLIKELY(styleTracingEnabled))
+        traceStyleChange(changeType);
+}
+
 inline void Node::setStyleChange(StyleChangeType changeType)
 {
     m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
@@ -721,8 +759,11 @@
         setFlag(NotifyRendererWithIdenticalStyles);
 
     StyleChangeType existingChangeType = styleChangeType();
-    if (changeType > existingChangeType)
+    if (changeType > existingChangeType) {
         setStyleChange(changeType);
+        if (changeType >= SubtreeStyleChange)
+            traceStyleChangeIfNeeded(changeType);
+    }
 
     if (existingChangeType == NoStyleChange)
         markAncestorsWithChildNeedsStyleRecalc();
@@ -759,7 +800,7 @@
 bool Node::isInert() const
 {
     const HTMLDialogElement* dialog = document().activeModalDialog();
-    if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
+    if (dialog && this != document() && !NodeRenderingTraversal::contains(dialog, this))
         return true;
     return document().ownerElement() && document().ownerElement()->isInert();
 }
@@ -824,11 +865,8 @@
     document().invalidateNodeListCaches(attrName);
 
     for (Node* node = this; node; node = node->parentNode()) {
-        if (!node->hasRareData())
-            continue;
-        NodeRareData* data = node->rareData();
-        if (data->nodeLists())
-            data->nodeLists()->invalidateCaches(attrName);
+        if (NodeListsNodeData* lists = node->nodeLists())
+            lists->invalidateCaches(attrName);
     }
 }
 
@@ -842,31 +880,6 @@
     rareData()->clearNodeLists();
 }
 
-void Node::checkSetPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
-{
-    // Perform error checking as required by spec for setting Node.prefix. Used by
-    // Element::setPrefix() and Attr::setPrefix()
-
-    if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
-        exceptionState.throwDOMException(InvalidCharacterError, "The prefix '" + prefix + "' is not a valid name.");
-        return;
-    }
-
-    // FIXME: Raise NamespaceError if prefix is malformed per the Namespaces in XML specification.
-
-    const AtomicString& nodeNamespaceURI = namespaceURI();
-    if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
-        exceptionState.throwDOMException(NamespaceError, "No namespace is set, so a namespace prefix may not be set.");
-        return;
-    }
-
-    if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
-        exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'.");
-        return;
-    }
-    // Attribute-specific checks are in Attr::setPrefix().
-}
-
 bool Node::isDescendantOf(const Node *other) const
 {
     // Return true if other is an ancestor of this, otherwise false
@@ -931,20 +944,20 @@
     return false;
 }
 
-Node* Node::commonAncestorOverShadowBoundary(const Node& other)
+Node* Node::commonAncestor(const Node& other, Node* (*parent)(const Node&))
 {
     if (this == other)
         return this;
     if (document() != other.document())
         return 0;
     int thisDepth = 0;
-    for (Node* node = this; node; node = node->parentOrShadowHostNode()) {
+    for (Node* node = this; node; node = parent(*node)) {
         if (node == &other)
             return node;
         thisDepth++;
     }
     int otherDepth = 0;
-    for (const Node* node = &other; node; node = node->parentOrShadowHostNode()) {
+    for (const Node* node = &other; node; node = parent(*node)) {
         if (node == this)
             return this;
         otherDepth++;
@@ -953,16 +966,16 @@
     const Node* otherIterator = &other;
     if (thisDepth > otherDepth) {
         for (int i = thisDepth; i > otherDepth; --i)
-            thisIterator = thisIterator->parentOrShadowHostNode();
+            thisIterator = parent(*thisIterator);
     } else if (otherDepth > thisDepth) {
         for (int i = otherDepth; i > thisDepth; --i)
-            otherIterator = otherIterator->parentOrShadowHostNode();
+            otherIterator = parent(*otherIterator);
     }
     while (thisIterator) {
         if (thisIterator == otherIterator)
             return thisIterator;
-        thisIterator = thisIterator->parentOrShadowHostNode();
-        otherIterator = otherIterator->parentOrShadowHostNode();
+        thisIterator = parent(*thisIterator);
+        otherIterator = parent(*otherIterator);
     }
     ASSERT(!otherIterator);
     return 0;
@@ -987,10 +1000,8 @@
 
     clearNeedsStyleRecalc();
 
-    if (Document* doc = documentInternal()) {
-        if (AXObjectCache* cache = doc->axObjectCache())
-            cache->updateCacheAfterNodeIsAttached(this);
-    }
+    if (AXObjectCache* cache = document().axObjectCache())
+        cache->updateCacheAfterNodeIsAttached(this);
 }
 
 #ifndef NDEBUG
@@ -1132,11 +1143,6 @@
     return parentOrShadowHostNode() ? parentOrShadowHostNode()->canStartSelection() : true;
 }
 
-bool Node::isRegisteredWithNamedFlow() const
-{
-    return document().renderView()->flowThreadController()->isContentNodeRegisteredWithAnyNamedFlow(this);
-}
-
 Element* Node::shadowHost() const
 {
     if (ShadowRoot* root = containingShadowRoot())
@@ -1154,8 +1160,8 @@
 
 ShadowRoot* Node::containingShadowRoot() const
 {
-    Node* root = treeScope().rootNode();
-    return root && root->isShadowRoot() ? toShadowRoot(root) : 0;
+    Node& root = treeScope().rootNode();
+    return root.isShadowRoot() ? toShadowRoot(&root) : 0;
 }
 
 Node* Node::nonBoundaryShadowTreeRootNode()
@@ -1257,69 +1263,6 @@
 
 // FIXME: End of obviously misplaced HTML editing functions.  Try to move these out of Node.
 
-PassRefPtr<NodeList> Node::getElementsByTagName(const AtomicString& localName)
-{
-    if (localName.isNull())
-        return 0;
-
-    if (document().isHTMLDocument())
-        return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLTagNodeList>(this, HTMLTagNodeListType, localName);
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<TagNodeList>(this, TagNodeListType, localName);
-}
-
-PassRefPtr<NodeList> Node::getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName)
-{
-    if (localName.isNull())
-        return 0;
-
-    if (namespaceURI == starAtom)
-        return getElementsByTagName(localName);
-
-    return ensureRareData().ensureNodeLists().addCacheWithQualifiedName(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localName);
-}
-
-PassRefPtr<NodeList> Node::getElementsByName(const String& elementName)
-{
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<NameNodeList>(this, NameNodeListType, elementName);
-}
-
-PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
-{
-    return ensureRareData().ensureNodeLists().addCacheWithName<ClassNodeList>(this, ClassNodeListType, classNames);
-}
-
-PassRefPtr<RadioNodeList> Node::radioNodeList(const AtomicString& name)
-{
-    ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<RadioNodeList>(this, RadioNodeListType, name);
-}
-
-PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionState& exceptionState)
-{
-    if (selectors.isEmpty()) {
-        exceptionState.throwDOMException(SyntaxError,  "The provided selector is empty.");
-        return 0;
-    }
-
-    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), exceptionState);
-    if (!selectorQuery)
-        return 0;
-    return selectorQuery->queryFirst(*this);
-}
-
-PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionState& exceptionState)
-{
-    if (selectors.isEmpty()) {
-        exceptionState.throwDOMException(SyntaxError, "The provided selector is empty.");
-        return 0;
-    }
-
-    SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), exceptionState);
-    if (!selectorQuery)
-        return 0;
-    return selectorQuery->queryAll(*this);
-}
-
 Document* Node::ownerDocument() const
 {
     Document* doc = &document();
@@ -1349,9 +1292,6 @@
     if (namespaceURI() != other->namespaceURI())
         return false;
 
-    if (prefix() != other->prefix())
-        return false;
-
     if (nodeValue() != other->nodeValue())
         return false;
 
@@ -1372,7 +1312,7 @@
     if (otherChild)
         return false;
 
-    if (nodeType == DOCUMENT_TYPE_NODE) {
+    if (isDocumentTypeNode()) {
         const DocumentType* documentTypeThis = toDocumentType(this);
         const DocumentType* documentTypeOther = toDocumentType(other);
 
@@ -1384,8 +1324,6 @@
 
         if (documentTypeThis->internalSubset() != documentTypeOther->internalSubset())
             return false;
-
-        // FIXME: We don't compare entities or notations because currently both are always empty.
     }
 
     return true;
@@ -1411,8 +1349,8 @@
                 }
             }
 
-            if (Element* ancestor = ancestorElement())
-                return ancestor->isDefaultNamespace(namespaceURI);
+            if (Element* parent = parentElement())
+                return parent->isDefaultNamespace(namespaceURI);
 
             return false;
         }
@@ -1420,8 +1358,6 @@
             if (Element* de = toDocument(this)->documentElement())
                 return de->isDefaultNamespace(namespaceURI);
             return false;
-        case ENTITY_NODE:
-        case NOTATION_NODE:
         case DOCUMENT_TYPE_NODE:
         case DOCUMENT_FRAGMENT_NODE:
             return false;
@@ -1432,8 +1368,8 @@
             return false;
         }
         default:
-            if (Element* ancestor = ancestorElement())
-                return ancestor->isDefaultNamespace(namespaceURI);
+            if (Element* parent = parentElement())
+                return parent->isDefaultNamespace(namespaceURI);
             return false;
     }
 }
@@ -1441,34 +1377,37 @@
 const AtomicString& Node::lookupPrefix(const AtomicString& namespaceURI) const
 {
     // Implemented according to
-    // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
+    // http://dom.spec.whatwg.org/#dom-node-lookupprefix
 
-    if (namespaceURI.isEmpty())
+    if (namespaceURI.isEmpty() || namespaceURI.isNull())
         return nullAtom;
 
+    const Element* context;
+
     switch (nodeType()) {
         case ELEMENT_NODE:
-            return lookupNamespacePrefix(namespaceURI, toElement(this));
+            context = toElement(this);
+            break;
         case DOCUMENT_NODE:
-            if (Element* de = toDocument(this)->documentElement())
-                return de->lookupPrefix(namespaceURI);
-            return nullAtom;
-        case ENTITY_NODE:
-        case NOTATION_NODE:
+            context = toDocument(this)->documentElement();
+            break;
         case DOCUMENT_FRAGMENT_NODE:
         case DOCUMENT_TYPE_NODE:
-            return nullAtom;
-        case ATTRIBUTE_NODE: {
-            const Attr *attr = static_cast<const Attr *>(this);
-            if (attr->ownerElement())
-                return attr->ownerElement()->lookupPrefix(namespaceURI);
-            return nullAtom;
-        }
+            context = 0;
+            break;
+        // FIXME: Remove this when Attr no longer extends Node (CR305105)
+        case ATTRIBUTE_NODE:
+            context = toAttr(this)->ownerElement();
+            break;
         default:
-            if (Element* ancestor = ancestorElement())
-                return ancestor->lookupPrefix(namespaceURI);
-            return nullAtom;
+            context = parentElement();
+            break;
     }
+
+    if (!context)
+        return nullAtom;
+
+    return context->locateNamespacePrefix(namespaceURI);
 }
 
 const AtomicString& Node::lookupNamespaceURI(const String& prefix) const
@@ -1503,59 +1442,31 @@
                     }
                 }
             }
-            if (Element* ancestor = ancestorElement())
-                return ancestor->lookupNamespaceURI(prefix);
+            if (Element* parent = parentElement())
+                return parent->lookupNamespaceURI(prefix);
             return nullAtom;
         }
         case DOCUMENT_NODE:
             if (Element* de = toDocument(this)->documentElement())
                 return de->lookupNamespaceURI(prefix);
             return nullAtom;
-        case ENTITY_NODE:
-        case NOTATION_NODE:
         case DOCUMENT_TYPE_NODE:
         case DOCUMENT_FRAGMENT_NODE:
             return nullAtom;
         case ATTRIBUTE_NODE: {
-            const Attr *attr = static_cast<const Attr *>(this);
-
+            const Attr *attr = toAttr(this);
             if (attr->ownerElement())
                 return attr->ownerElement()->lookupNamespaceURI(prefix);
             else
                 return nullAtom;
         }
         default:
-            if (Element* ancestor = ancestorElement())
-                return ancestor->lookupNamespaceURI(prefix);
+            if (Element* parent = parentElement())
+                return parent->lookupNamespaceURI(prefix);
             return nullAtom;
     }
 }
 
-const AtomicString& Node::lookupNamespacePrefix(const AtomicString& _namespaceURI, const Element* originalElement) const
-{
-    if (_namespaceURI.isNull())
-        return nullAtom;
-
-    if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
-        return prefix();
-
-    ASSERT(isElementNode());
-    const Element* thisElement = toElement(this);
-    if (thisElement->hasAttributes()) {
-        for (unsigned i = 0; i < thisElement->attributeCount(); i++) {
-            const Attribute* attr = thisElement->attributeItem(i);
-
-            if (attr->prefix() == xmlnsAtom && attr->value() == _namespaceURI
-                    && originalElement->lookupNamespaceURI(attr->localName()) == _namespaceURI)
-                return attr->localName();
-        }
-    }
-
-    if (Element* ancestor = ancestorElement())
-        return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
-    return nullAtom;
-}
-
 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
 {
     switch (node->nodeType()) {
@@ -1579,7 +1490,6 @@
         }
     // Fall through.
     case Node::ATTRIBUTE_NODE:
-    case Node::ENTITY_NODE:
     case Node::DOCUMENT_FRAGMENT_NODE:
         isNullString = false;
         for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
@@ -1591,8 +1501,6 @@
 
     case Node::DOCUMENT_NODE:
     case Node::DOCUMENT_TYPE_NODE:
-    case Node::NOTATION_NODE:
-    case Node::XPATH_NAMESPACE_NODE:
         break;
     }
 }
@@ -1616,7 +1524,6 @@
             return;
         case ELEMENT_NODE:
         case ATTRIBUTE_NODE:
-        case ENTITY_NODE:
         case DOCUMENT_FRAGMENT_NODE: {
             RefPtr<ContainerNode> container = toContainerNode(this);
             ChildListMutationScope mutation(*this);
@@ -1627,24 +1534,12 @@
         }
         case DOCUMENT_NODE:
         case DOCUMENT_TYPE_NODE:
-        case NOTATION_NODE:
-        case XPATH_NAMESPACE_NODE:
             // Do nothing.
             return;
     }
     ASSERT_NOT_REACHED();
 }
 
-Element* Node::ancestorElement() const
-{
-    // In theory, there can be EntityReference nodes between elements, but this is currently not supported.
-    for (ContainerNode* n = parentNode(); n; n = n->parentNode()) {
-        if (n->isElementNode())
-            return toElement(n);
-    }
-    return 0;
-}
-
 bool Node::offsetInCharacters() const
 {
     return false;
@@ -1785,8 +1680,7 @@
         return renderer()->localToAbsolute(p, UseTransforms);
 
     // Otherwise go up the tree looking for a renderer
-    Element *parent = ancestorElement();
-    if (parent)
+    if (Element* parent = parentElement())
         return parent->convertToPage(p);
 
     // No parent - no conversion needed
@@ -1800,8 +1694,7 @@
         return renderer()->absoluteToLocal(p, UseTransforms);
 
     // Otherwise go up the tree looking for a renderer
-    Element *parent = ancestorElement();
-    if (parent)
+    if (Element* parent = parentElement())
         return parent->convertFromPage(p);
 
     // No parent - no conversion needed
@@ -1900,11 +1793,12 @@
                     if (previous->nodeName() == node->nodeName())
                         ++count;
                 if (hasIdAttr)
-                    fprintf(stderr, "[@id=\"%s\" and position()=%d]", idattr.string().utf8().data(), count);
+                    fprintf(stderr, "[@id=\"%s\" and position()=%d]", idattr.utf8().data(), count);
                 else
                     fprintf(stderr, "[%d]", count);
-            } else if (hasIdAttr)
-                fprintf(stderr, "[@id=\"%s\"]", idattr.string().utf8().data());
+            } else if (hasIdAttr) {
+                fprintf(stderr, "[@id=\"%s\"]", idattr.utf8().data());
+            }
             break;
         }
         case TEXT_NODE:
@@ -2008,24 +1902,6 @@
 
 // --------
 
-void NodeListsNodeData::invalidateCaches(const QualifiedName* attrName)
-{
-    NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end();
-    for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it)
-        it->value->invalidateCache(attrName);
-
-    NodeListNameCacheMap::const_iterator nameCacheEnd = m_nameCaches.end();
-    for (NodeListNameCacheMap::const_iterator it = m_nameCaches.begin(); it != nameCacheEnd; ++it)
-        it->value->invalidateCache(attrName);
-
-    if (attrName)
-        return;
-
-    TagNodeListCacheNS::iterator tagCacheEnd = m_tagNodeListCacheNS.end();
-    for (TagNodeListCacheNS::iterator it = m_tagNodeListCacheNS.begin(); it != tagCacheEnd; ++it)
-        it->value->invalidateCache();
-}
-
 Node* Node::enclosingLinkEventParentOrSelf()
 {
     for (Node* node = this; node; node = node->parentOrShadowHostNode()) {
@@ -2142,6 +2018,12 @@
     return tryRemoveEventListener(this, eventType, listener, useCapture);
 }
 
+void Node::removeAllEventListeners()
+{
+    EventTarget::removeAllEventListeners();
+    document().didClearTouchEventHandlers(this);
+}
+
 typedef HashMap<Node*, OwnPtr<EventTargetData> > EventTargetDataMap;
 
 static EventTargetDataMap& eventTargetDataMap()
@@ -2201,7 +2083,7 @@
             MutationRecordDeliveryOptions deliveryOptions = registration.deliveryOptions();
             HashMap<MutationObserver*, MutationRecordDeliveryOptions>::AddResult result = observers.add(registration.observer(), deliveryOptions);
             if (!result.isNewEntry)
-                result.iterator->value |= deliveryOptions;
+                result.storedValue->value |= deliveryOptions;
         }
     }
 }
@@ -2373,6 +2255,9 @@
 
 bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
 {
+    if (!RuntimeEnabledFeatures::beforeLoadEnabled())
+        return true;
+
     if (!document().hasListenerType(Document::BEFORELOAD_LISTENER))
         return true;
 
@@ -2387,11 +2272,6 @@
     return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document().domWindow()));
 }
 
-void Node::dispatchChangeEvent()
-{
-    dispatchScopedEvent(Event::createBubble(EventTypeNames::change));
-}
-
 void Node::dispatchInputEvent()
 {
     dispatchScopedEvent(Event::createBubble(EventTypeNames::input));
@@ -2492,12 +2372,12 @@
         dispose();
 #if !ASSERT_DISABLED
         // We need to do this right now since guardDeref() can delete this.
-        rootNode()->m_inRemovedLastRefFunction = false;
+        rootNode().m_inRemovedLastRefFunction = false;
 #endif
         guardDeref();
     } else {
 #if !ASSERT_DISABLED
-        rootNode()->m_inRemovedLastRefFunction = false;
+        rootNode().m_inRemovedLastRefFunction = false;
 #endif
 #if SECURITY_ASSERT_ENABLED
         beginDeletion();
@@ -2524,13 +2404,6 @@
     delete this;
 }
 
-void Node::textRects(Vector<IntRect>& rects) const
-{
-    RefPtr<Range> range = Range::create(document());
-    range->selectNodeContents(const_cast<Node*>(this), IGNORE_EXCEPTION);
-    range->textRects(rects);
-}
-
 unsigned Node::connectedSubframeCount() const
 {
     return hasRareData() ? rareData()->connectedSubframeCount() : 0;
@@ -2668,7 +2541,7 @@
     setFlag(newState == Upgraded, CustomElementUpgraded);
 
     if (oldState == NotCustomElement || newState == Upgraded)
-        setNeedsStyleRecalc(); // :unresolved has changed
+        setNeedsStyleRecalc(SubtreeStyleChange); // :unresolved has changed
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index 382652d..3ee5488 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -47,13 +47,12 @@
 namespace WebCore {
 
 class Attribute;
-class ClassNodeList;
+class ClassCollection;
 class ContainerNode;
 class DOMSettableTokenList;
 class Document;
 class Element;
 class Event;
-class EventContext;
 class EventDispatchMediator;
 class EventListener;
 class ExceptionState;
@@ -65,10 +64,10 @@
 class NSResolver;
 class NameNodeList;
 class NamedNodeMap;
+class NodeEventContext;
 class NodeList;
 class NodeListsNodeData;
 class NodeRareData;
-class NodeRenderingContext;
 class PlatformGestureEvent;
 class PlatformKeyboardEvent;
 class PlatformMouseEvent;
@@ -81,7 +80,7 @@
 class RenderObject;
 class RenderStyle;
 class ShadowRoot;
-class TagNodeList;
+class TagCollection;
 class Text;
 class TouchEvent;
 
@@ -127,22 +126,22 @@
         ATTRIBUTE_NODE = 2,
         TEXT_NODE = 3,
         CDATA_SECTION_NODE = 4,
-        ENTITY_NODE = 6,
         PROCESSING_INSTRUCTION_NODE = 7,
         COMMENT_NODE = 8,
         DOCUMENT_NODE = 9,
         DOCUMENT_TYPE_NODE = 10,
         DOCUMENT_FRAGMENT_NODE = 11,
-        NOTATION_NODE = 12,
-        XPATH_NAMESPACE_NODE = 13,
     };
 
-    // EntityReference nodes are deprecated and impossible to create in WebKit.
-    // We want Node.ENTITY_REFERNCE_NODE to exist in JS and this enum, makes the bindings
+    // Entity, EntityReference, Notation, and XPathNamespace nodes are impossible to create in Blink.
+    // But for compatibility reasons we want these enum values exist in JS, and this enum makes the bindings
     // generation not complain about ENTITY_REFERENCE_NODE being missing from the implementation
     // while not requiring all switch(NodeType) blocks to include this deprecated constant.
     enum DeprecatedNodeType {
-        ENTITY_REFERENCE_NODE = 5
+        ENTITY_REFERENCE_NODE = 5,
+        ENTITY_NODE = 6,
+        NOTATION_NODE = 12,
+        XPATH_NAMESPACE_NODE = 13,
     };
 
     enum DocumentPosition {
@@ -160,7 +159,6 @@
     void* operator new(size_t);
     void operator delete(void*);
 
-    static bool isSupported(const String& feature, const String& version);
     static void dumpStatistics();
 
     virtual ~Node();
@@ -180,9 +178,6 @@
     Node* firstChild() const;
     Node* lastChild() const;
 
-    // ChildNode interface API
-    Element* previousElementSibling() const;
-    Element* nextElementSibling() const;
     void remove(ExceptionState&);
 
     Node* pseudoAwareNextSibling() const;
@@ -203,8 +198,6 @@
     virtual PassRefPtr<Node> cloneNode(bool deep = false) = 0;
     virtual const AtomicString& localName() const;
     virtual const AtomicString& namespaceURI() const;
-    virtual const AtomicString& prefix() const;
-    virtual void setPrefix(const AtomicString&, ExceptionState&);
     void normalize();
 
     bool isSameNode(Node* other) const { return this == other; }
@@ -212,7 +205,6 @@
     bool isDefaultNamespace(const AtomicString& namespaceURI) const;
     const AtomicString& lookupPrefix(const AtomicString& namespaceURI) const;
     const AtomicString& lookupNamespaceURI(const String& prefix) const;
-    const AtomicString& lookupNamespacePrefix(const AtomicString& namespaceURI, const Element* originalElement) const;
 
     String textContent(bool convertBRsToNewlines = false) const;
     void setTextContent(const String&);
@@ -265,16 +257,13 @@
     bool isStyledElement() const { return isHTMLElement() || isSVGElement(); }
 
     bool isDocumentNode() const;
-    bool isTreeScope() const { return treeScope().rootNode() == this; }
+    bool isTreeScope() const { return &treeScope().rootNode() == this; }
     bool isDocumentFragment() const { return getFlag(IsDocumentFragmentFlag); }
     bool isShadowRoot() const { return isDocumentFragment() && isTreeScope(); }
     bool isInsertionPoint() const { return getFlag(IsInsertionPointFlag); }
 
-    bool inNamedFlow() const { return getFlag(InNamedFlowFlag); }
     bool hasCustomStyleCallbacks() const { return getFlag(HasCustomStyleCallbacksFlag); }
 
-    bool isRegisteredWithNamedFlow() const;
-
     bool hasSyntheticAttrChildNodes() const { return getFlag(HasSyntheticAttrChildNodesFlag); }
     void setHasSyntheticAttrChildNodes(bool flag) { setFlag(flag, HasSyntheticAttrChildNodesFlag); }
 
@@ -340,15 +329,6 @@
 
     bool inSameContainingBlockFlowElement(Node*);
 
-    // Called by the parser when this element's close tag is reached,
-    // signaling that all child tags have been parsed and added.
-    // This is needed for <applet> and <object> elements, which can't lay themselves out
-    // until they know all of their nested <param>s. [Radar 3603191, 4040848].
-    // Also used for script elements and some SVG elements for similar purposes,
-    // but making parsing a special case in this respect should be avoided if possible.
-    virtual void finishParsingChildren() { }
-    virtual void beginParsingChildren() { }
-
     // For <link> and <style> elements.
     virtual bool sheetLoaded() { return true; }
     virtual void notifyLoadedSheetAndAllCriticalSubresources(bool /* error loading subresource */) { }
@@ -377,7 +357,7 @@
     void setChildNeedsStyleRecalc() { setFlag(ChildNeedsStyleRecalcFlag); }
     void clearChildNeedsStyleRecalc() { clearFlag(ChildNeedsStyleRecalcFlag); }
 
-    void setNeedsStyleRecalc(StyleChangeType = SubtreeStyleChange, StyleChangeSource = StyleChangeFromCSS);
+    void setNeedsStyleRecalc(StyleChangeType, StyleChangeSource = StyleChangeFromCSS);
     void clearNeedsStyleRecalc();
 
     bool childNeedsDistributionRecalc() const { return getFlag(ChildNeedsDistributionRecalc); }
@@ -385,15 +365,19 @@
     void clearChildNeedsDistributionRecalc()  { clearFlag(ChildNeedsDistributionRecalc); }
     void markAncestorsWithChildNeedsDistributionRecalc();
 
+    bool childNeedsStyleInvalidation() const { return getFlag(ChildNeedsStyleInvalidation); }
+    void setChildNeedsStyleInvalidation()  { setFlag(ChildNeedsStyleInvalidation); }
+    void clearChildNeedsStyleInvalidation()  { clearFlag(ChildNeedsStyleInvalidation); }
+    void markAncestorsWithChildNeedsStyleInvalidation();
+    bool needsStyleInvalidation() { return getFlag(NeedsStyleInvalidation); }
+    void setNeedsStyleInvalidation();
+
     void recalcDistribution();
 
     bool shouldNotifyRendererWithIdenticalStyles() const { return getFlag(NotifyRendererWithIdenticalStyles); }
 
     void setIsLink(bool f);
 
-    void setInNamedFlow() { setFlag(InNamedFlowFlag); }
-    void clearInNamedFlow() { clearFlag(InNamedFlowFlag); }
-
     bool hasScopedHTMLStyleChild() const { return getFlag(HasScopedHTMLStyleChildFlag); }
     void setHasScopedHTMLStyleChild(bool flag) { setFlag(flag, HasScopedHTMLStyleChildFlag); }
 
@@ -401,7 +385,8 @@
     void setHasEventTargetData(bool flag) { setFlag(flag, HasEventTargetDataFlag); }
 
     bool isV8CollectableDuringMinorGC() const { return getFlag(V8CollectableDuringMinorGCFlag); }
-    void setV8CollectableDuringMinorGC(bool flag) { setFlag(flag, V8CollectableDuringMinorGCFlag); }
+    void markV8CollectableDuringMinorGC() { setFlag(true, V8CollectableDuringMinorGCFlag); }
+    void clearV8CollectableDuringMinorGC() { setFlag(false, V8CollectableDuringMinorGCFlag); }
 
     virtual void setFocus(bool flag);
     virtual void setActive(bool flag = true);
@@ -451,8 +436,6 @@
     virtual bool shouldUseInputMethod();
     virtual LayoutRect boundingBox() const;
     IntRect pixelSnappedBoundingBox() const { return pixelSnappedIntRect(boundingBox()); }
-    LayoutRect renderRect(bool* isReplaced);
-    IntRect pixelSnappedRenderRect(bool* isReplaced) { return pixelSnappedIntRect(renderRect(isReplaced)); }
 
     // Returns true if the node has a non-empty bounding box in layout.
     // This does not 100% guarantee the user can see it, but is pretty close.
@@ -468,12 +451,14 @@
     // Returns the document associated with this node. A Document node returns itself.
     Document& document() const
     {
-        ASSERT(this);
-        ASSERT(documentInternal());
-        return *documentInternal();
+        return treeScope().document();
     }
 
-    TreeScope& treeScope() const { return *m_treeScope; }
+    TreeScope& treeScope() const
+    {
+        ASSERT(m_treeScope);
+        return *m_treeScope;
+    }
 
     bool inActiveDocument() const;
 
@@ -481,7 +466,6 @@
     // node tree, false otherwise.
     bool inDocument() const
     {
-        ASSERT(documentInternal() || !getFlag(InDocumentFlag));
         return getFlag(InDocumentFlag);
     }
     bool isInShadowTree() const { return getFlag(IsInShadowTreeFlag); }
@@ -492,15 +476,11 @@
     unsigned childNodeCount() const;
     Node* childNode(unsigned index) const;
 
-    void checkSetPrefix(const AtomicString& prefix, ExceptionState&);
     bool isDescendantOf(const Node*) const;
     bool contains(const Node*) const;
     bool containsIncludingShadowDOM(const Node*) const;
     bool containsIncludingHostElements(const Node&) const;
-    Node* commonAncestorOverShadowBoundary(const Node&);
-
-    // FIXME: Remove this when crbug.com/265716 cleans up contains semantics.
-    bool bindingsContains(const Node* node) const { return containsIncludingShadowDOM(node); }
+    Node* commonAncestor(const Node&, Node* (*parent)(const Node&));
 
     // Used to determine whether range offsets use characters or node indices.
     virtual bool offsetInCharacters() const;
@@ -557,6 +537,9 @@
     void reattach(const AttachContext& = AttachContext());
     void lazyReattachIfAttached();
 
+    // Returns true if recalcStyle should be called on the object, if there is such a method (on Document and Element).
+    bool shouldCallRecalcStyle(StyleRecalcChange);
+
     // Wrapper for nodes that don't have a renderer, but still cache the style (like HTMLOptionElement).
     RenderStyle* renderStyle() const;
     RenderStyle* parentRenderStyle() const;
@@ -610,19 +593,10 @@
     NodeListsNodeData* nodeLists();
     void clearNodeLists();
 
-    PassRefPtr<NodeList> getElementsByTagName(const AtomicString&);
-    PassRefPtr<NodeList> getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName);
-    PassRefPtr<NodeList> getElementsByName(const String& elementName);
-    PassRefPtr<NodeList> getElementsByClassName(const String& classNames);
-    PassRefPtr<RadioNodeList> radioNodeList(const AtomicString&);
-
     virtual bool willRespondToMouseMoveEvents();
     virtual bool willRespondToMouseClickEvents();
     virtual bool willRespondToTouchEvents();
 
-    PassRefPtr<Element> querySelector(const AtomicString& selectors, ExceptionState&);
-    PassRefPtr<NodeList> querySelectorAll(const AtomicString& selectors, ExceptionState&);
-
     unsigned short compareDocumentPosition(const Node*) const;
 
     enum ShadowTreesTreatment {
@@ -632,13 +606,14 @@
 
     unsigned short compareDocumentPositionInternal(const Node*, ShadowTreesTreatment) const;
 
-    virtual Node* toNode();
+    virtual Node* toNode() OVERRIDE FINAL;
 
     virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual ExecutionContext* executionContext() const OVERRIDE;
 
-    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
-    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
+    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE;
+    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE;
+    virtual void removeAllEventListeners() OVERRIDE;
 
     // Handlers to do/undo actions on the target node before an event is dispatched to it and after the event
     // has been dispatched.  The data pointer is handed back by the preDispatch and passed to postDispatch.
@@ -665,8 +640,7 @@
     void dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions = SendNoEvents);
 
     virtual bool dispatchBeforeLoadEvent(const String& sourceURL);
-    virtual void dispatchChangeEvent();
-    virtual void dispatchInputEvent();
+    void dispatchInputEvent();
 
     // Perform the default action for an event.
     virtual void defaultEventHandler(Event*);
@@ -686,8 +660,6 @@
     virtual void unregisterScopedHTMLStyleChild();
     size_t numberOfScopedHTMLStyleChildren() const;
 
-    void textRects(Vector<IntRect>&) const;
-
     unsigned connectedSubframeCount() const;
     void incrementConnectedSubframeCount(unsigned amount = 1);
     void decrementConnectedSubframeCount(unsigned amount = 1);
@@ -717,8 +689,9 @@
 
         // These bits are used by derived classes, pulled up here so they can
         // be stored in the same memory word as the Node bits above.
-        IsParsingChildrenFinishedFlag = 1 << 12, // Element
-        HasSVGRareDataFlag = 1 << 13, // SVGElement
+        IsFinishedParsingChildrenFlag = 1 << 12, // Element
+
+        AlreadySpellCheckedFlag = 1 << 13,
 
         StyleChangeMask = 1 << nodeStyleChangeShift | 1 << (nodeStyleChangeShift + 1),
 
@@ -726,7 +699,8 @@
 
         HasNameOrIsEditingTextFlag = 1 << 17,
 
-        InNamedFlowFlag = 1 << 18,
+        // Bit 18 is available
+
         HasSyntheticAttrChildNodesFlag = 1 << 19,
         HasCustomStyleCallbacksFlag = 1 << 20,
         HasScopedHTMLStyleChildFlag = 1 << 21,
@@ -740,9 +714,10 @@
         CustomElement = 1 << 27,
         CustomElementUpgraded = 1 << 28,
 
-        AlreadySpellCheckedFlag = 1 << 29,
+        ChildNeedsStyleInvalidation = 1 << 29,
+        NeedsStyleInvalidation = 1 << 30,
 
-        DefaultNodeFlags = IsParsingChildrenFinishedFlag | ChildNeedsStyleRecalcFlag | NeedsReattachStyleChange
+        DefaultNodeFlags = IsFinishedParsingChildrenFlag | ChildNeedsStyleRecalcFlag | NeedsReattachStyleChange
     };
 
     // 3 bits remaining.
@@ -774,10 +749,10 @@
         , m_previous(0)
         , m_next(0)
     {
+        ASSERT(m_treeScope || type == CreateDocument || type == CreateShadowRoot);
         ScriptWrappable::init(this);
-        if (!m_treeScope)
-            m_treeScope = TreeScope::noDocumentInstance();
-        m_treeScope->guardRef();
+        if (m_treeScope)
+            m_treeScope->guardRef();
 
 #if !defined(NDEBUG) || (defined(DUMP_NODE_STATISTICS) && DUMP_NODE_STATISTICS)
         trackForDebugging();
@@ -787,8 +762,6 @@
 
     virtual void didMoveToNewDocument(Document& oldDocument);
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const { }
-
     static void reattachWhitespaceSiblings(Text* start);
 
     void willBeDeletedFromDocument();
@@ -803,11 +776,18 @@
 
     void setHasCustomStyleCallbacks() { setFlag(true, HasCustomStyleCallbacksFlag); }
 
-    Document* documentInternal() const { return treeScope().documentScope(); }
     void setTreeScope(TreeScope* scope) { m_treeScope = scope; }
 
+    // isTreeScopeInitialized() can be false
+    // - in the destruction of Document or ShadowRoot where m_treeScope is set to null or
+    // - in the Node constructor called by these two classes where m_treeScope is set by TreeScope ctor.
+    bool isTreeScopeInitialized() const { return m_treeScope; }
+
     void markAncestorsWithChildNeedsStyleRecalc();
 
+    bool isFinishedParsingChildren() const { return getFlag(IsFinishedParsingChildrenFlag); }
+    void setIsFinishedParsingChildren(bool value) { setFlag(value, IsFinishedParsingChildrenFlag); }
+
 private:
     friend class TreeShared<Node>;
 
@@ -829,14 +809,14 @@
     bool isUserActionElementHovered() const;
     bool isUserActionElementFocused() const;
 
+    void traceStyleChange(StyleChangeType);
+    void traceStyleChangeIfNeeded(StyleChangeType);
     void setStyleChange(StyleChangeType);
 
     virtual RenderStyle* nonRendererStyle() const { return 0; }
 
     virtual RenderStyle* virtualComputedStyle(PseudoId = NOPSEUDO);
 
-    Element* ancestorElement() const;
-
     void trackForDebugging();
 
     Vector<OwnPtr<MutationObserverRegistration> >* mutationObserverRegistry();
@@ -853,24 +833,8 @@
         RenderObject* m_renderer;
         NodeRareDataBase* m_rareData;
     } m_data;
-
-protected:
-    bool isParsingChildrenFinished() const { return getFlag(IsParsingChildrenFinishedFlag); }
-    void setIsParsingChildrenFinished() { setFlag(IsParsingChildrenFinishedFlag); }
-    void clearIsParsingChildrenFinished() { clearFlag(IsParsingChildrenFinishedFlag); }
-
-    bool hasSVGRareData() const { return getFlag(HasSVGRareDataFlag); }
-    void setHasSVGRareData() { setFlag(HasSVGRareDataFlag); }
-    void clearHasSVGRareData() { clearFlag(HasSVGRareDataFlag); }
 };
 
-// Used in Node::addSubresourceAttributeURLs() and in addSubresourceStyleURLs()
-inline void addSubresourceURL(ListHashSet<KURL>& urls, const KURL& url)
-{
-    if (!url.isNull())
-        urls.add(url);
-}
-
 inline void Node::setParentOrShadowHostNode(ContainerNode* parent)
 {
     ASSERT(isMainThread());
@@ -902,9 +866,9 @@
     markAncestorsWithChildNeedsStyleRecalc();
 }
 
-inline bool shouldRecalcStyle(StyleRecalcChange change, const Node* node)
+inline bool Node::shouldCallRecalcStyle(StyleRecalcChange change)
 {
-    return change >= Inherit || node->childNeedsStyleRecalc() || node->needsStyleRecalc();
+    return change >= Inherit || needsStyleRecalc() || childNeedsStyleRecalc();
 }
 
 inline bool isTreeScopeRoot(const Node* node)
diff --git a/Source/core/dom/Node.idl b/Source/core/dom/Node.idl
index c67bbeb..690190d 100644
--- a/Source/core/dom/Node.idl
+++ b/Source/core/dom/Node.idl
@@ -60,11 +60,7 @@
     [CustomElementCallbacks] void normalize();
 
     // Introduced in DOM Level 2:
-    [MeasureAs=NodeIsSupported] boolean isSupported([Default=Undefined] optional DOMString feature,
-                                                    [TreatNullAs=NullString,Default=Undefined] optional DOMString version); // Removed in DOM4.
-
     [TreatReturnedNullStringAs=Null, PerWorldBindings, MeasureAs=NodeNamespaceURI] readonly attribute DOMString namespaceURI; // Moved to Element and Attr in DOM4.
-    [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter, MeasureAs=NodePrefix] attribute DOMString prefix; // Moved to Element and Attr in DOM4.
     [TreatReturnedNullStringAs=Null, PerWorldBindings, MeasureAs=NodeLocalName] readonly attribute DOMString localName; // Moved to Element and Attr in DOM4.
 
     // Introduced in DOM Level 3:
@@ -89,7 +85,7 @@
     unsigned short compareDocumentPosition(Node other);
 
     // Introduced in DOM4
-    [ImplementedAs=bindingsContains] boolean contains(Node other);
+    [ImplementedAs=containsIncludingShadowDOM] boolean contains(Node other);
 
     // IE extensions
     [PerWorldBindings] readonly attribute Element parentElement;
diff --git a/Source/core/dom/NodeIterator.idl b/Source/core/dom/NodeIterator.idl
index 9c636c4..c47c809 100644
--- a/Source/core/dom/NodeIterator.idl
+++ b/Source/core/dom/NodeIterator.idl
@@ -20,7 +20,7 @@
 
 // Introduced in DOM Level 2:
 [
-    SetReference(NodeFilter filter)
+    SetWrapperReferenceTo(NodeFilter filter)
 ] interface NodeIterator {
     readonly attribute Node root;
     readonly attribute unsigned long whatToShow;
diff --git a/Source/core/dom/NodeList.h b/Source/core/dom/NodeList.h
index 1d77043..76c51da 100644
--- a/Source/core/dom/NodeList.h
+++ b/Source/core/dom/NodeList.h
@@ -39,11 +39,12 @@
     // DOM methods & attributes for NodeList
     virtual unsigned length() const = 0;
     virtual Node* item(unsigned index) const = 0;
-    virtual Node* namedItem(const AtomicString&) const = 0;
 
     // Other methods (not part of DOM)
-    virtual bool isLiveNodeList() const { return false; }
-    void anonymousNamedGetter(const AtomicString&, bool&, RefPtr<Node>&, bool&, unsigned&);
+    virtual bool isEmptyNodeList() const { return false; }
+    virtual bool isChildNodeList() const { return false; }
+
+    virtual Node* virtualOwnerNode() const { return 0; }
 
 protected:
     NodeList()
diff --git a/Source/core/dom/NodeList.idl b/Source/core/dom/NodeList.idl
index 19ccec6..b6f81a1 100644
--- a/Source/core/dom/NodeList.idl
+++ b/Source/core/dom/NodeList.idl
@@ -19,14 +19,9 @@
  */
 
 [
-    Custom=VisitDOMWrapper,
     DependentLifetime,
+    SetWrapperReferenceFrom=virtualOwnerNode,
 ] interface NodeList {
-
     getter Node item(unsigned long index);
-    [ImplementedAs=anonymousNamedGetter, OverrideBuiltins, NotEnumerable] getter (Node or unsigned long) (DOMString name);
-
     readonly attribute unsigned long length;
-
 };
-
diff --git a/Source/core/dom/NodeRareData.cpp b/Source/core/dom/NodeRareData.cpp
index bbd863e..82717cb 100644
--- a/Source/core/dom/NodeRareData.cpp
+++ b/Source/core/dom/NodeRareData.cpp
@@ -40,4 +40,19 @@
 
 COMPILE_ASSERT(sizeof(NodeRareData) == sizeof(SameSizeAsNodeRareData), NodeRareDataShouldStaySmall);
 
+void NodeListsNodeData::invalidateCaches(const QualifiedName* attrName)
+{
+    NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end();
+    for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it)
+        it->value->invalidateCache(attrName);
+
+    if (attrName)
+        return;
+
+    TagCollectionCacheNS::iterator tagCacheEnd = m_tagCollectionCacheNS.end();
+    for (TagCollectionCacheNS::iterator it = m_tagCollectionCacheNS.begin(); it != tagCacheEnd; ++it)
+        it->value->invalidateCache();
+}
+
+
 } // namespace WebCore
diff --git a/Source/core/dom/NodeRareData.h b/Source/core/dom/NodeRareData.h
index 38dd440..3572d14 100644
--- a/Source/core/dom/NodeRareData.h
+++ b/Source/core/dom/NodeRareData.h
@@ -23,10 +23,11 @@
 #define NodeRareData_h
 
 #include "core/dom/ChildNodeList.h"
+#include "core/dom/EmptyNodeList.h"
 #include "core/dom/LiveNodeList.h"
 #include "core/dom/MutationObserverRegistration.h"
 #include "core/dom/QualifiedName.h"
-#include "core/dom/TagNodeList.h"
+#include "core/dom/TagCollection.h"
 #include "core/page/Page.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
@@ -45,19 +46,28 @@
 public:
     void clearChildNodeListCache()
     {
-        if (m_childNodeList)
-            m_childNodeList->invalidateCache();
+        if (m_childNodeList && m_childNodeList->isChildNodeList())
+            toChildNodeList(m_childNodeList)->invalidateCache();
     }
 
-    PassRefPtr<ChildNodeList> ensureChildNodeList(Node* node)
+    PassRefPtr<ChildNodeList> ensureChildNodeList(ContainerNode* node)
     {
         if (m_childNodeList)
-            return m_childNodeList;
+            return toChildNodeList(m_childNodeList);
         RefPtr<ChildNodeList> list = ChildNodeList::create(node);
         m_childNodeList = list.get();
         return list.release();
     }
 
+    PassRefPtr<EmptyNodeList> ensureEmptyChildNodeList(Node* node)
+    {
+        if (m_childNodeList)
+            return toEmptyNodeList(m_childNodeList);
+        RefPtr<EmptyNodeList> list = EmptyNodeList::create(node);
+        m_childNodeList = list.get();
+        return list.release();
+    }
+
     void removeChildNodeList(ChildNodeList* list)
     {
         ASSERT(m_childNodeList == list);
@@ -66,76 +76,69 @@
         m_childNodeList = 0;
     }
 
-    template <typename StringType>
-    struct NodeListCacheMapEntryHash {
-        static unsigned hash(const std::pair<unsigned char, StringType>& entry)
+    void removeEmptyChildNodeList(EmptyNodeList* list)
+    {
+        ASSERT(m_childNodeList == list);
+        if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
+            return;
+        m_childNodeList = 0;
+    }
+
+    struct NodeListAtomicCacheMapEntryHash {
+        static unsigned hash(const std::pair<unsigned char, StringImpl*>& entry)
         {
-            return DefaultHash<StringType>::Hash::hash(entry.second) + entry.first;
+            return DefaultHash<StringImpl*>::Hash::hash(entry.second) + entry.first;
         }
-        static bool equal(const std::pair<unsigned char, StringType>& a, const std::pair<unsigned char, StringType>& b) { return a == b; }
-        static const bool safeToCompareToEmptyOrDeleted = DefaultHash<StringType>::Hash::safeToCompareToEmptyOrDeleted;
+        static bool equal(const std::pair<unsigned char, StringImpl*>& a, const std::pair<unsigned char, StringImpl*>& b) { return a == b; }
+        static const bool safeToCompareToEmptyOrDeleted = DefaultHash<StringImpl*>::Hash::safeToCompareToEmptyOrDeleted;
     };
 
-    typedef HashMap<std::pair<unsigned char, AtomicString>, LiveNodeListBase*, NodeListCacheMapEntryHash<AtomicString> > NodeListAtomicNameCacheMap;
-    typedef HashMap<std::pair<unsigned char, String>, LiveNodeListBase*, NodeListCacheMapEntryHash<String> > NodeListNameCacheMap;
-    typedef HashMap<QualifiedName, TagNodeList*> TagNodeListCacheNS;
+    typedef HashMap<std::pair<unsigned char, StringImpl*>, LiveNodeListBase*, NodeListAtomicCacheMapEntryHash> NodeListAtomicNameCacheMap;
+    typedef HashMap<QualifiedName, TagCollection*> TagCollectionCacheNS;
 
     template<typename T>
-    PassRefPtr<T> addCacheWithAtomicName(Node* node, CollectionType collectionType, const AtomicString& name)
+    PassRefPtr<T> addCache(ContainerNode* node, CollectionType collectionType, const AtomicString& name)
     {
         NodeListAtomicNameCacheMap::AddResult result = m_atomicNameCaches.add(namedNodeListKey(collectionType, name), 0);
         if (!result.isNewEntry)
-            return static_cast<T*>(result.iterator->value);
+            return static_cast<T*>(result.storedValue->value);
 
         RefPtr<T> list = T::create(node, collectionType, name);
-        result.iterator->value = list.get();
+        result.storedValue->value = list.get();
         return list.release();
     }
 
-    // FIXME: This function should be renamed since it doesn't have an atomic name.
     template<typename T>
-    PassRefPtr<T> addCacheWithAtomicName(Node* node, CollectionType collectionType)
+    PassRefPtr<T> addCache(ContainerNode* node, CollectionType collectionType)
     {
         NodeListAtomicNameCacheMap::AddResult result = m_atomicNameCaches.add(namedNodeListKey(collectionType, starAtom), 0);
         if (!result.isNewEntry)
-            return static_cast<T*>(result.iterator->value);
+            return static_cast<T*>(result.storedValue->value);
 
         RefPtr<T> list = T::create(node, collectionType);
-        result.iterator->value = list.get();
+        result.storedValue->value = list.get();
         return list.release();
     }
 
     template<typename T>
-    T* cacheWithAtomicName(CollectionType collectionType)
+    T* cached(CollectionType collectionType)
     {
         return static_cast<T*>(m_atomicNameCaches.get(namedNodeListKey(collectionType, starAtom)));
     }
 
-    template<typename T>
-    PassRefPtr<T> addCacheWithName(Node* node, CollectionType collectionType, const String& name)
-    {
-        NodeListNameCacheMap::AddResult result = m_nameCaches.add(namedNodeListKey(collectionType, name), 0);
-        if (!result.isNewEntry)
-            return static_cast<T*>(result.iterator->value);
-
-        RefPtr<T> list = T::create(node, name);
-        result.iterator->value = list.get();
-        return list.release();
-    }
-
-    PassRefPtr<TagNodeList> addCacheWithQualifiedName(Node* node, const AtomicString& namespaceURI, const AtomicString& localName)
+    PassRefPtr<TagCollection> addCache(ContainerNode* node, const AtomicString& namespaceURI, const AtomicString& localName)
     {
         QualifiedName name(nullAtom, localName, namespaceURI);
-        TagNodeListCacheNS::AddResult result = m_tagNodeListCacheNS.add(name, 0);
+        TagCollectionCacheNS::AddResult result = m_tagCollectionCacheNS.add(name, 0);
         if (!result.isNewEntry)
-            return result.iterator->value;
+            return result.storedValue->value;
 
-        RefPtr<TagNodeList> list = TagNodeList::create(node, namespaceURI, localName);
-        result.iterator->value = list.get();
+        RefPtr<TagCollection> list = TagCollection::create(node, namespaceURI, localName);
+        result.storedValue->value = list.get();
         return list.release();
     }
 
-    void removeCacheWithAtomicName(LiveNodeListBase* list, CollectionType collectionType, const AtomicString& name = starAtom)
+    void removeCache(LiveNodeListBase* list, CollectionType collectionType, const AtomicString& name = starAtom)
     {
         ASSERT(list == m_atomicNameCaches.get(namedNodeListKey(collectionType, name)));
         if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
@@ -143,21 +146,13 @@
         m_atomicNameCaches.remove(namedNodeListKey(collectionType, name));
     }
 
-    void removeCacheWithName(LiveNodeListBase* list, CollectionType collectionType, const String& name)
-    {
-        ASSERT(list == m_nameCaches.get(namedNodeListKey(collectionType, name)));
-        if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
-            return;
-        m_nameCaches.remove(namedNodeListKey(collectionType, name));
-    }
-
-    void removeCacheWithQualifiedName(LiveNodeList* list, const AtomicString& namespaceURI, const AtomicString& localName)
+    void removeCache(LiveNodeListBase* list, const AtomicString& namespaceURI, const AtomicString& localName)
     {
         QualifiedName name(nullAtom, localName, namespaceURI);
-        ASSERT(list == m_tagNodeListCacheNS.get(name));
+        ASSERT(list == m_tagCollectionCacheNS.get(name));
         if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
             return;
-        m_tagNodeListCacheNS.remove(name);
+        m_tagCollectionCacheNS.remove(name);
     }
 
     static PassOwnPtr<NodeListsNodeData> create()
@@ -168,7 +163,7 @@
     void invalidateCaches(const QualifiedName* attrName = 0);
     bool isEmpty() const
     {
-        return m_atomicNameCaches.isEmpty() && m_nameCaches.isEmpty() && m_tagNodeListCacheNS.isEmpty();
+        return m_atomicNameCaches.isEmpty() && m_tagCollectionCacheNS.isEmpty();
     }
 
     void adoptTreeScope()
@@ -176,32 +171,21 @@
         invalidateCaches();
     }
 
-    void adoptDocument(Document* oldDocument, Document* newDocument)
+    void adoptDocument(Document& oldDocument, Document& newDocument)
     {
-        invalidateCaches();
+        ASSERT(oldDocument != newDocument);
 
-        if (oldDocument != newDocument) {
-            NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end();
-            for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it) {
-                LiveNodeListBase* list = it->value;
-                oldDocument->unregisterNodeList(list);
-                newDocument->registerNodeList(list);
-            }
+        NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end();
+        for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it) {
+            LiveNodeListBase* list = it->value;
+            list->didMoveToDocument(oldDocument, newDocument);
+        }
 
-            NodeListNameCacheMap::const_iterator nameCacheEnd = m_nameCaches.end();
-            for (NodeListNameCacheMap::const_iterator it = m_nameCaches.begin(); it != nameCacheEnd; ++it) {
-                LiveNodeListBase* list = it->value;
-                oldDocument->unregisterNodeList(list);
-                newDocument->registerNodeList(list);
-            }
-
-            TagNodeListCacheNS::const_iterator tagEnd = m_tagNodeListCacheNS.end();
-            for (TagNodeListCacheNS::const_iterator it = m_tagNodeListCacheNS.begin(); it != tagEnd; ++it) {
-                LiveNodeListBase* list = it->value;
-                ASSERT(!list->isRootedAtDocument());
-                oldDocument->unregisterNodeList(list);
-                newDocument->registerNodeList(list);
-            }
+        TagCollectionCacheNS::const_iterator tagEnd = m_tagCollectionCacheNS.end();
+        for (TagCollectionCacheNS::const_iterator it = m_tagCollectionCacheNS.begin(); it != tagEnd; ++it) {
+            LiveNodeListBase* list = it->value;
+            ASSERT(!list->isRootedAtDocument());
+            list->didMoveToDocument(oldDocument, newDocument);
         }
     }
 
@@ -210,24 +194,19 @@
         : m_childNodeList(0)
     { }
 
-    std::pair<unsigned char, AtomicString> namedNodeListKey(CollectionType type, const AtomicString& name)
+    std::pair<unsigned char, StringImpl*> namedNodeListKey(CollectionType type, const AtomicString& name)
     {
-        return std::pair<unsigned char, AtomicString>(type, name);
-    }
-
-    std::pair<unsigned char, String> namedNodeListKey(CollectionType type, const String& name)
-    {
-        return std::pair<unsigned char, String>(type, name);
+        // Holding the raw StringImpl is safe because |name| is retained by the NodeList and the NodeList
+        // is reponsible for removing itself from the cache on deletion.
+        return std::pair<unsigned char, StringImpl*>(type, name.impl());
     }
 
     bool deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(Node*);
 
-    // FIXME: m_childNodeList should be merged into m_atomicNameCaches or at least be shared with HTMLCollection returned by Element::children
-    // but it's tricky because invalidateCaches shouldn't invalidate this cache and adoptTreeScope shouldn't call registerNodeList or unregisterNodeList.
-    ChildNodeList* m_childNodeList;
+    // Can be a ChildNodeList or an EmptyNodeList.
+    NodeList* m_childNodeList;
     NodeListAtomicNameCacheMap m_atomicNameCaches;
-    NodeListNameCacheMap m_nameCaches;
-    TagNodeListCacheNS m_tagNodeListCacheNS;
+    TagCollectionCacheNS m_tagCollectionCacheNS;
 };
 
 class NodeMutationObserverData {
@@ -293,7 +272,7 @@
 {
     ASSERT(ownerNode);
     ASSERT(ownerNode->nodeLists() == this);
-    if ((m_childNodeList ? 1 : 0) + m_atomicNameCaches.size() + m_nameCaches.size() + m_tagNodeListCacheNS.size() != 1)
+    if ((m_childNodeList ? 1 : 0) + m_atomicNameCaches.size() + m_tagCollectionCacheNS.size() != 1)
         return false;
     ownerNode->clearNodeLists();
     return true;
diff --git a/Source/core/dom/NodeRenderStyle.h b/Source/core/dom/NodeRenderStyle.h
index a9487ab..deef2fd 100644
--- a/Source/core/dom/NodeRenderStyle.h
+++ b/Source/core/dom/NodeRenderStyle.h
@@ -25,6 +25,7 @@
 #ifndef NodeRenderStyle_h
 #define NodeRenderStyle_h
 
+#include "HTMLNames.h"
 #include "core/dom/Node.h"
 #include "core/dom/NodeRenderingTraversal.h"
 #include "core/rendering/RenderObject.h"
@@ -34,11 +35,14 @@
 
 inline RenderStyle* Node::renderStyle() const
 {
-    // Using a ternary here confuses the Solaris Studio 12/12.1/12.2 compilers:
-    // Bug is CR 6569194, "Problem with question operator binding in inline function"
     if (RenderObject* renderer = this->renderer())
         return renderer->style();
-    return nonRendererStyle();
+    // <option> and <optgroup> can be styled even though they never get renderers,
+    // so they store their style internally and return it through nonRendererStyle().
+    // We check here explicitly to avoid the virtual call in the common case.
+    if (hasTagName(HTMLNames::optgroupTag) || hasTagName(HTMLNames::optionTag))
+        return nonRendererStyle();
+    return 0;
 }
 
 inline RenderStyle* Node::parentRenderStyle() const
diff --git a/Source/core/dom/NodeRenderingContext.cpp b/Source/core/dom/NodeRenderingContext.cpp
deleted file mode 100644
index 2d2b4a4..0000000
--- a/Source/core/dom/NodeRenderingContext.cpp
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 1999 Antti Koivisto (koivisto@kde.org)
- *           (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/dom/NodeRenderingContext.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/ContainerNode.h"
-#include "core/dom/FullscreenElementStack.h"
-#include "core/dom/Node.h"
-#include "core/dom/Text.h"
-#include "core/dom/shadow/InsertionPoint.h"
-#include "core/rendering/FlowThreadController.h"
-#include "core/rendering/RenderFullScreen.h"
-#include "core/rendering/RenderNamedFlowThread.h"
-#include "core/rendering/RenderObject.h"
-#include "core/rendering/RenderText.h"
-#include "core/rendering/RenderView.h"
-
-namespace WebCore {
-
-static bool isRendererReparented(const RenderObject* renderer)
-{
-    if (!renderer->node()->isElementNode())
-        return false;
-    if (renderer->style() && !renderer->style()->flowThread().isEmpty())
-        return true;
-    if (toElement(renderer->node())->shouldBeReparentedUnderRenderView(renderer->style()))
-        return true;
-    return false;
-}
-
-RenderObject* NodeRenderingContext::nextRenderer() const
-{
-    if (RenderObject* renderer = m_node->renderer())
-        return renderer->nextSibling();
-
-    Element* element = m_node->isElementNode() ? toElement(m_node) : 0;
-    if (element && element->shouldBeReparentedUnderRenderView(m_style.get())) {
-        // FIXME: Reparented renderers not in the top layer should probably be
-        // ordered in DOM tree order. We don't have a good way to do that yet,
-        // since NodeRenderingTraversal isn't aware of reparenting. It's safe to
-        // just append for now; it doesn't disrupt the top layer rendering as
-        // the layer collection in RenderLayer only requires that top layer
-        // renderers are orderered correctly relative to each other.
-        if (!element->isInTopLayer())
-            return 0;
-
-        const Vector<RefPtr<Element> >& topLayerElements = element->document().topLayerElements();
-        size_t position = topLayerElements.find(element);
-        ASSERT(position != kNotFound);
-        for (size_t i = position + 1; i < topLayerElements.size(); ++i) {
-            if (RenderObject* renderer = topLayerElements[i]->renderer())
-                return renderer;
-        }
-        return 0;
-    }
-
-    if (m_parentFlowRenderer)
-        return m_parentFlowRenderer->nextRendererForNode(m_node);
-
-    // Avoid an O(N^2) walk over the children when reattaching all children of a node.
-    if (m_renderingParent && m_renderingParent->needsAttach())
-        return 0;
-
-    for (Node* sibling = NodeRenderingTraversal::nextSibling(m_node); sibling; sibling = NodeRenderingTraversal::nextSibling(sibling)) {
-        RenderObject* renderer = sibling->renderer();
-        if (renderer && !isRendererReparented(renderer))
-            return renderer;
-    }
-
-    return 0;
-}
-
-RenderObject* NodeRenderingContext::previousRenderer() const
-{
-    if (RenderObject* renderer = m_node->renderer())
-        return renderer->previousSibling();
-
-    // FIXME: This doesn't work correctly for reparented elements that are
-    // display: none. We'd need to duplicate the logic in nextRenderer, but since
-    // nothing needs that yet just assert.
-    ASSERT(!m_node->isElementNode() || !toElement(m_node)->shouldBeReparentedUnderRenderView(m_style.get()));
-
-    if (m_parentFlowRenderer)
-        return m_parentFlowRenderer->previousRendererForNode(m_node);
-
-    // FIXME: We should have the same O(N^2) avoidance as nextRenderer does
-    // however, when I tried adding it, several tests failed.
-    for (Node* sibling = NodeRenderingTraversal::previousSibling(m_node); sibling; sibling = NodeRenderingTraversal::previousSibling(sibling)) {
-        RenderObject* renderer = sibling->renderer();
-        if (renderer && !isRendererReparented(renderer))
-            return renderer;
-    }
-
-    return 0;
-}
-
-RenderObject* NodeRenderingContext::parentRenderer() const
-{
-    if (RenderObject* renderer = m_node->renderer())
-        return renderer->parent();
-
-    if (m_node->isElementNode() && toElement(m_node)->shouldBeReparentedUnderRenderView(m_style.get())) {
-        // The parent renderer of reparented elements is the RenderView, but only
-        // if the normal parent would have had a renderer.
-        // FIXME: This behavior isn't quite right as the spec for top layer
-        // only talks about display: none ancestors so putting a <dialog> inside
-        // an <optgroup> seems like it should still work even though this check
-        // will prevent it.
-        if (!m_renderingParent || !m_renderingParent->renderer())
-            return 0;
-        return m_node->document().renderView();
-    }
-
-    if (m_parentFlowRenderer)
-        return m_parentFlowRenderer;
-
-    return m_renderingParent ? m_renderingParent->renderer() : 0;
-}
-
-bool NodeRenderingContext::shouldCreateRenderer() const
-{
-    if (!m_renderingParent)
-        return false;
-    RenderObject* parentRenderer = this->parentRenderer();
-    if (!parentRenderer)
-        return false;
-    if (!parentRenderer->canHaveChildren())
-        return false;
-    if (!m_renderingParent->childShouldCreateRenderer(*m_node))
-        return false;
-    return true;
-}
-
-// Check the specific case of elements that are children of regions but are flowed into a flow thread themselves.
-bool NodeRenderingContext::elementInsideRegionNeedsRenderer()
-{
-    Element* element = toElement(m_node);
-    bool elementInsideRegionNeedsRenderer = false;
-    RenderObject* parentRenderer = this->parentRenderer();
-    if ((parentRenderer && !parentRenderer->canHaveChildren() && parentRenderer->isRenderNamedFlowFragmentContainer())
-        || (!parentRenderer && element->parentElement() && element->parentElement()->isInsideRegion())) {
-
-        if (!m_style)
-            m_style = element->styleForRenderer();
-
-        elementInsideRegionNeedsRenderer = element->shouldMoveToFlowThread(m_style.get());
-
-        // Children of this element will only be allowed to be flowed into other flow-threads if display is NOT none.
-        if (element->rendererIsNeeded(*m_style))
-            element->setIsInsideRegion(true);
-    }
-
-    return elementInsideRegionNeedsRenderer;
-}
-
-void NodeRenderingContext::moveToFlowThreadIfNeeded()
-{
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled())
-        return;
-
-    Element* element = toElement(m_node);
-
-    if (!element->shouldMoveToFlowThread(m_style.get()))
-        return;
-
-    ASSERT(m_node->document().renderView());
-    FlowThreadController* flowThreadController = m_node->document().renderView()->flowThreadController();
-    m_parentFlowRenderer = flowThreadController->ensureRenderFlowThreadWithName(m_style->flowThread());
-    flowThreadController->registerNamedFlowContentNode(m_node, m_parentFlowRenderer);
-}
-
-void NodeRenderingContext::createRendererForElementIfNeeded()
-{
-    ASSERT(!m_node->renderer());
-
-    Element* element = toElement(m_node);
-
-    element->setIsInsideRegion(false);
-
-    if (!shouldCreateRenderer() && !elementInsideRegionNeedsRenderer())
-        return;
-
-    if (!m_style)
-        m_style = element->styleForRenderer();
-
-    moveToFlowThreadIfNeeded();
-
-    if (!element->rendererIsNeeded(*m_style))
-        return;
-
-    RenderObject* newRenderer = element->createRenderer(m_style.get());
-    if (!newRenderer)
-        return;
-
-    RenderObject* parentRenderer = this->parentRenderer();
-
-    if (!parentRenderer->isChildAllowed(newRenderer, m_style.get())) {
-        newRenderer->destroy();
-        return;
-    }
-
-    // Make sure the RenderObject already knows it is going to be added to a RenderFlowThread before we set the style
-    // for the first time. Otherwise code using inRenderFlowThread() in the styleWillChange and styleDidChange will fail.
-    newRenderer->setFlowThreadState(parentRenderer->flowThreadState());
-
-    RenderObject* nextRenderer = this->nextRenderer();
-    element->setRenderer(newRenderer);
-    newRenderer->setAnimatableStyle(m_style.release()); // setAnimatableStyle() can depend on renderer() already being set.
-
-    if (FullscreenElementStack::isActiveFullScreenElement(element)) {
-        newRenderer = RenderFullScreen::wrapRenderer(newRenderer, parentRenderer, &element->document());
-        if (!newRenderer)
-            return;
-    }
-
-    // Note: Adding newRenderer instead of renderer(). renderer() may be a child of newRenderer.
-    parentRenderer->addChild(newRenderer, nextRenderer);
-}
-
-void NodeRenderingContext::createRendererForTextIfNeeded()
-{
-    ASSERT(!m_node->renderer());
-
-    Text* textNode = toText(m_node);
-
-    if (!shouldCreateRenderer())
-        return;
-
-    RenderObject* parentRenderer = this->parentRenderer();
-
-    if (m_parentDetails.resetStyleInheritance())
-        m_style = textNode->document().ensureStyleResolver().defaultStyleForElement();
-    else
-        m_style = parentRenderer->style();
-
-    if (!textNode->textRendererIsNeeded(*this))
-        return;
-
-    RenderText* newRenderer = textNode->createTextRenderer(m_style.get());
-    if (!parentRenderer->isChildAllowed(newRenderer, m_style.get())) {
-        newRenderer->destroy();
-        return;
-    }
-
-    // Make sure the RenderObject already knows it is going to be added to a RenderFlowThread before we set the style
-    // for the first time. Otherwise code using inRenderFlowThread() in the styleWillChange and styleDidChange will fail.
-    newRenderer->setFlowThreadState(parentRenderer->flowThreadState());
-
-    RenderObject* nextRenderer = this->nextRenderer();
-    textNode->setRenderer(newRenderer);
-    // Parent takes care of the animations, no need to call setAnimatableStyle.
-    newRenderer->setStyle(m_style.release());
-    parentRenderer->addChild(newRenderer, nextRenderer);
-}
-
-}
diff --git a/Source/core/dom/NodeRenderingTraversal.cpp b/Source/core/dom/NodeRenderingTraversal.cpp
index b30c66a..b6f1db3 100644
--- a/Source/core/dom/NodeRenderingTraversal.cpp
+++ b/Source/core/dom/NodeRenderingTraversal.cpp
@@ -27,13 +27,24 @@
 #include "config.h"
 #include "core/dom/NodeRenderingTraversal.h"
 
+#include "HTMLNames.h"
 #include "core/dom/PseudoElement.h"
 #include "core/dom/shadow/ComposedTreeWalker.h"
+#include "core/rendering/RenderObject.h"
 
 namespace WebCore {
 
 namespace NodeRenderingTraversal {
 
+static bool isRendererReparented(const RenderObject* renderer)
+{
+    if (!renderer->node()->isElementNode())
+        return false;
+    if (toElement(renderer->node())->isInTopLayer())
+        return true;
+    return false;
+}
+
 void ParentDetails::didTraverseInsertionPoint(const InsertionPoint* insertionPoint)
 {
     if (!m_insertionPoint) {
@@ -59,6 +70,16 @@
     return toContainerNode(walker.traverseParent(walker.get(), details));
 }
 
+bool contains(const ContainerNode* container, const Node* node)
+{
+    while (node) {
+        if (node == container)
+            return true;
+        node = NodeRenderingTraversal::parent(node);
+    }
+    return false;
+}
+
 Node* nextSibling(const Node* node)
 {
     ComposedTreeWalker walker(node);
@@ -97,6 +118,40 @@
     return 0;
 }
 
+RenderObject* nextSiblingRenderer(const Node* node)
+{
+    for (Node* sibling = NodeRenderingTraversal::nextSibling(node); sibling; sibling = NodeRenderingTraversal::nextSibling(sibling)) {
+        RenderObject* renderer = sibling->renderer();
+        if (renderer && !isRendererReparented(renderer))
+            return renderer;
+    }
+    return 0;
+}
+
+RenderObject* previousSiblingRenderer(const Node* node)
+{
+    for (Node* sibling = NodeRenderingTraversal::previousSibling(node); sibling; sibling = NodeRenderingTraversal::previousSibling(sibling)) {
+        RenderObject* renderer = sibling->renderer();
+        if (renderer && !isRendererReparented(renderer))
+            return renderer;
+    }
+    return 0;
+}
+
+RenderObject* nextInTopLayer(const Element* element)
+{
+    if (!element->isInTopLayer())
+        return 0;
+    const Vector<RefPtr<Element> >& topLayerElements = element->document().topLayerElements();
+    size_t position = topLayerElements.find(element);
+    ASSERT(position != kNotFound);
+    for (size_t i = position + 1; i < topLayerElements.size(); ++i) {
+        if (RenderObject* renderer = topLayerElements[i]->renderer())
+            return renderer;
+    }
+    return 0;
+}
+
 }
 
 } // namespace
diff --git a/Source/core/dom/NodeRenderingTraversal.h b/Source/core/dom/NodeRenderingTraversal.h
index 8935ae6..fab1bc3 100644
--- a/Source/core/dom/NodeRenderingTraversal.h
+++ b/Source/core/dom/NodeRenderingTraversal.h
@@ -32,6 +32,7 @@
 namespace WebCore {
 
 class InsertionPoint;
+class RenderObject;
 
 namespace NodeRenderingTraversal {
 
@@ -61,8 +62,12 @@
 
 ContainerNode* parent(const Node*);
 ContainerNode* parent(const Node*, ParentDetails*);
+bool contains(const ContainerNode*, const Node*);
 Node* nextSibling(const Node*);
 Node* previousSibling(const Node*);
+RenderObject* nextSiblingRenderer(const Node*);
+RenderObject* previousSiblingRenderer(const Node*);
+RenderObject* nextInTopLayer(const Element*);
 
 inline ContainerNode* parent(const Node* node)
 {
diff --git a/Source/core/dom/NodeTraversal.cpp b/Source/core/dom/NodeTraversal.cpp
index 631a8b9..b5eba51 100644
--- a/Source/core/dom/NodeTraversal.cpp
+++ b/Source/core/dom/NodeTraversal.cpp
@@ -160,14 +160,5 @@
     return previousAncestorSiblingPostOrder(current, stayWithin);
 }
 
-Node* previousSkippingChildrenPostOrder(const Node& current, const Node* stayWithin)
-{
-    if (current == stayWithin)
-        return 0;
-    if (current.previousSibling())
-        return current.previousSibling();
-    return previousAncestorSiblingPostOrder(current, stayWithin);
-}
-
 }
 }
diff --git a/Source/core/dom/NodeTraversal.h b/Source/core/dom/NodeTraversal.h
index 438b0c0..995613a 100644
--- a/Source/core/dom/NodeTraversal.h
+++ b/Source/core/dom/NodeTraversal.h
@@ -55,9 +55,8 @@
 // Like next, but visits parents after their children.
 Node* nextPostOrder(const Node&, const Node* stayWithin = 0);
 
-// Like previous/previousSkippingChildren, but visits parents before their children.
+// Like previous, but visits parents before their children.
 Node* previousPostOrder(const Node&, const Node* stayWithin = 0);
-Node* previousSkippingChildrenPostOrder(const Node&, const Node* stayWithin = 0);
 
 // Pre-order traversal including the pseudo-elements.
 Node* previousIncludingPseudo(const Node&, const Node* stayWithin = 0);
diff --git a/Source/core/dom/Notation.h b/Source/core/dom/Notation.h
index 30401f2..8ac0250 100644
--- a/Source/core/dom/Notation.h
+++ b/Source/core/dom/Notation.h
@@ -28,11 +28,7 @@
 
 class Notation : public ContainerNode {
 private:
-    Notation(TreeScope* treeScope) : ContainerNode(treeScope)
-    {
-        ASSERT_NOT_REACHED();
-        ScriptWrappable::init(this);
-    }
+    Notation(); // Left unimplemented on purpose.
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/ParentNode.h b/Source/core/dom/ParentNode.h
index 9fb949a..45f146c 100644
--- a/Source/core/dom/ParentNode.h
+++ b/Source/core/dom/ParentNode.h
@@ -32,6 +32,7 @@
 #define ParentNode_h
 
 #include "core/dom/ContainerNode.h"
+#include "core/dom/ElementTraversal.h"
 
 namespace WebCore {
 
@@ -44,17 +45,23 @@
 
     static Element* firstElementChild(ContainerNode* node)
     {
-        return node->firstElementChild();
+        ASSERT(node);
+        return ElementTraversal::firstWithin(*node);
     }
 
     static Element* lastElementChild(ContainerNode* node)
     {
-        return node->lastElementChild();
+        ASSERT(node);
+        return ElementTraversal::lastWithin(*node);
     }
 
     static unsigned childElementCount(ContainerNode* node)
     {
-        return node->childElementCount();
+        ASSERT(node);
+        unsigned count = 0;
+        for (Element* child = ElementTraversal::firstWithin(*node); child; child = ElementTraversal::nextSibling(*child))
+            ++count;
+        return count;
     }
 };
 
diff --git a/Source/core/dom/PendingScript.cpp b/Source/core/dom/PendingScript.cpp
index 6ad05cf..b448c8b 100644
--- a/Source/core/dom/PendingScript.cpp
+++ b/Source/core/dom/PendingScript.cpp
@@ -33,8 +33,6 @@
 
 PendingScript::~PendingScript()
 {
-    if (m_resource)
-        m_resource->removeClient(this);
 }
 
 PassRefPtr<Element> PendingScript::releaseElementAndClear()
@@ -47,18 +45,7 @@
 
 void PendingScript::setScriptResource(ScriptResource* resource)
 {
-    if (m_resource == resource)
-        return;
-    if (m_resource)
-        m_resource->removeClient(this);
-    m_resource = resource;
-    if (m_resource)
-        m_resource->addClient(this);
-}
-
-ScriptResource* PendingScript::resource() const
-{
-    return m_resource.get();
+    setResource(resource);
 }
 
 void PendingScript::notifyFinished(Resource*)
diff --git a/Source/core/dom/PendingScript.h b/Source/core/dom/PendingScript.h
index 0f169a9..a5c5855 100644
--- a/Source/core/dom/PendingScript.h
+++ b/Source/core/dom/PendingScript.h
@@ -27,22 +27,23 @@
 #define PendingScript_h
 
 #include "core/fetch/ResourceClient.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
+#include "core/fetch/ScriptResource.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 #include "wtf/text/TextPosition.h"
 
 namespace WebCore {
 
-class ScriptResource;
 class Element;
+class ScriptResource;
 
 // A container for an external script which may be loaded and executed.
 //
 // A ResourcePtr alone does not prevent the underlying Resource
 // from purging its data buffer. This class holds a dummy client open for its
 // lifetime in order to guarantee that the data buffer will not be purged.
-class PendingScript : public ResourceClient {
+class PendingScript : public ResourceOwner<ScriptResource> {
 public:
     PendingScript()
         : m_watchingForLoad(false)
@@ -58,7 +59,7 @@
     }
 
     PendingScript(const PendingScript& other)
-        : ResourceClient(other)
+        : ResourceOwner(other)
         , m_watchingForLoad(other.m_watchingForLoad)
         , m_element(other.m_element)
         , m_startingPosition(other.m_startingPosition)
@@ -76,7 +77,7 @@
         m_watchingForLoad = other.m_watchingForLoad;
         m_element = other.m_element;
         m_startingPosition = other.m_startingPosition;
-        setScriptResource(other.resource());
+        this->ResourceOwner<ScriptResource, ResourceClient>::operator=(other);
 
         return *this;
     }
@@ -91,7 +92,6 @@
     void setElement(Element* element) { m_element = element; }
     PassRefPtr<Element> releaseElementAndClear();
 
-    ScriptResource* resource() const;
     void setScriptResource(ScriptResource*);
 
     virtual void notifyFinished(Resource*);
@@ -100,7 +100,6 @@
     bool m_watchingForLoad;
     RefPtr<Element> m_element;
     TextPosition m_startingPosition; // Only used for inline script tags.
-    ResourcePtr<ScriptResource> m_resource;
 };
 
 }
diff --git a/Source/core/dom/Position.cpp b/Source/core/dom/Position.cpp
index 1ce44d8..91832ed 100644
--- a/Source/core/dom/Position.cpp
+++ b/Source/core/dom/Position.cpp
@@ -35,10 +35,8 @@
 #include "core/editing/VisiblePosition.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
-#include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLTableElement.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/Logging.h"
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/InlineTextBox.h"
@@ -211,13 +209,13 @@
 
     // FIXME: This should only be necessary for legacy positions, but is also needed for positions before and after Tables
     if (m_offset <= 0 && (m_anchorType != PositionIsAfterAnchor && m_anchorType != PositionIsAfterChildren)) {
-        if (m_anchorNode->parentNode() && (editingIgnoresContent(m_anchorNode.get()) || isTableElement(m_anchorNode.get())))
+        if (m_anchorNode->parentNode() && (editingIgnoresContent(m_anchorNode.get()) || isRenderedTableElement(m_anchorNode.get())))
             return positionInParentBeforeNode(m_anchorNode.get());
         return Position(m_anchorNode.get(), 0, PositionIsOffsetInAnchor);
     }
     if (!m_anchorNode->offsetInCharacters()
         && (m_anchorType == PositionIsAfterAnchor || m_anchorType == PositionIsAfterChildren || static_cast<unsigned>(m_offset) == m_anchorNode->childNodeCount())
-        && (editingIgnoresContent(m_anchorNode.get()) || isTableElement(m_anchorNode.get()))
+        && (editingIgnoresContent(m_anchorNode.get()) || isRenderedTableElement(m_anchorNode.get()))
         && containerNode()) {
         return positionInParentAfterNode(m_anchorNode.get());
     }
@@ -546,7 +544,7 @@
         return true;
 
     // Don't include inline tables.
-    if (isHTMLTableElement(node))
+    if (node->hasTagName(tableTag))
         return false;
 
     // There is a VisiblePosition inside an empty inline-block container.
@@ -635,7 +633,7 @@
             return lastVisible;
 
         // Return position after tables and nodes which have content that can be ignored.
-        if (editingIgnoresContent(currentNode) || isTableElement(currentNode)) {
+        if (editingIgnoresContent(currentNode) || isRenderedTableElement(currentNode)) {
             if (currentPos.atEndOfNode())
                 return positionAfterNode(currentNode);
             continue;
@@ -763,7 +761,7 @@
             lastVisible = currentPos;
 
         // Return position before tables and nodes which have content that can be ignored.
-        if (editingIgnoresContent(currentNode) || isTableElement(currentNode)) {
+        if (editingIgnoresContent(currentNode) || isRenderedTableElement(currentNode)) {
             if (currentPos.offsetInLeafNode() <= renderer->caretMinOffset())
                 return createLegacyEditingPosition(currentNode, renderer->caretMinOffset());
             continue;
@@ -889,10 +887,10 @@
     if (renderer->isText())
         return !nodeIsUserSelectNone(deprecatedNode()) && inRenderedText();
 
-    if (isTableElement(deprecatedNode()) || editingIgnoresContent(deprecatedNode()))
+    if (isRenderedTableElement(deprecatedNode()) || editingIgnoresContent(deprecatedNode()))
         return (atFirstEditingPositionForNode() || atLastEditingPositionForNode()) && !nodeIsUserSelectNone(deprecatedNode()->parentNode());
 
-    if (isHTMLHtmlElement(m_anchorNode.get()))
+    if (m_anchorNode->hasTagName(htmlTag))
         return false;
 
     if (renderer->isRenderBlockFlow()) {
@@ -1048,7 +1046,7 @@
 // This assumes that it starts in editable content.
 Position Position::leadingWhitespacePosition(EAffinity affinity, bool considerNonCollapsibleWhitespace) const
 {
-    ASSERT(isEditablePosition(*this));
+    ASSERT(isEditablePosition(*this, ContentIsEditable, DoNotUpdateStyle));
     if (isNull())
         return Position();
 
@@ -1070,7 +1068,7 @@
 // This assumes that it starts in editable content.
 Position Position::trailingWhitespacePosition(EAffinity, bool considerNonCollapsibleWhitespace) const
 {
-    ASSERT(isEditablePosition(*this));
+    ASSERT(isEditablePosition(*this, ContentIsEditable, DoNotUpdateStyle));
     if (isNull())
         return Position();
 
diff --git a/Source/core/dom/PositionIterator.cpp b/Source/core/dom/PositionIterator.cpp
index f94c0ae..d99beaa 100644
--- a/Source/core/dom/PositionIterator.cpp
+++ b/Source/core/dom/PositionIterator.cpp
@@ -28,7 +28,6 @@
 
 #include "HTMLNames.h"
 #include "core/editing/htmlediting.h"
-#include "core/html/HTMLHtmlElement.h"
 #include "core/rendering/RenderBlock.h"
 
 namespace WebCore {
@@ -156,10 +155,10 @@
     if (renderer->isText())
         return !Position::nodeIsUserSelectNone(m_anchorNode) && Position(*this).inRenderedText();
 
-    if (isTableElement(m_anchorNode) || editingIgnoresContent(m_anchorNode))
+    if (isRenderedTableElement(m_anchorNode) || editingIgnoresContent(m_anchorNode))
         return (atStartOfNode() || atEndOfNode()) && !Position::nodeIsUserSelectNone(m_anchorNode->parentNode());
 
-    if (!isHTMLHtmlElement(m_anchorNode) && renderer->isRenderBlockFlow()) {
+    if (!m_anchorNode->hasTagName(htmlTag) && renderer->isRenderBlockFlow()) {
         if (toRenderBlock(renderer)->logicalHeight() || m_anchorNode->hasTagName(bodyTag)) {
             if (!Position::hasRenderedNonAnonymousDescendantsWithHeight(renderer))
                 return atStartOfNode() && !Position::nodeIsUserSelectNone(m_anchorNode);
diff --git a/Source/core/dom/PresentationAttributeStyle.cpp b/Source/core/dom/PresentationAttributeStyle.cpp
index e9ced65..ce45b4b 100644
--- a/Source/core/dom/PresentationAttributeStyle.cpp
+++ b/Source/core/dom/PresentationAttributeStyle.cpp
@@ -163,18 +163,18 @@
 
     unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
 
-    PresentationAttributeCache::iterator cacheIterator;
+    PresentationAttributeCache::ValueType* cacheValue;
     if (cacheHash) {
-        cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
-        if (cacheIterator->value && cacheIterator->value->key != cacheKey)
+        cacheValue = presentationAttributeCache().add(cacheHash, nullptr).storedValue;
+        if (cacheValue->value && cacheValue->value->key != cacheKey)
             cacheHash = 0;
     } else {
-        cacheIterator = presentationAttributeCache().end();
+        cacheValue = 0;
     }
 
     RefPtr<StylePropertySet> style;
-    if (cacheHash && cacheIterator->value) {
-        style = cacheIterator->value->value;
+    if (cacheHash && cacheValue->value) {
+        style = cacheValue->value->value;
         cacheCleaner.didHitPresentationAttributeCache();
     } else {
         style = MutableStylePropertySet::create(element.isSVGElement() ? SVGAttributeMode : HTMLAttributeMode);
@@ -185,7 +185,7 @@
         }
     }
 
-    if (!cacheHash || cacheIterator->value)
+    if (!cacheHash || cacheValue->value)
         return style.release();
 
     OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
@@ -199,7 +199,7 @@
         presentationAttributeCache().clear();
         presentationAttributeCache().set(cacheHash, newEntry.release());
     } else {
-        cacheIterator->value = newEntry.release();
+        cacheValue->value = newEntry.release();
     }
 
     return style.release();
diff --git a/Source/core/dom/ProcessingInstruction.cpp b/Source/core/dom/ProcessingInstruction.cpp
index 2cc8386..ab493bf 100644
--- a/Source/core/dom/ProcessingInstruction.cpp
+++ b/Source/core/dom/ProcessingInstruction.cpp
@@ -39,7 +39,6 @@
 inline ProcessingInstruction::ProcessingInstruction(Document& document, const String& target, const String& data)
     : CharacterData(document, data, CreateOther)
     , m_target(target)
-    , m_resource(0)
     , m_loading(false)
     , m_alternate(false)
     , m_createdByParser(false)
@@ -59,9 +58,6 @@
     if (m_sheet)
         m_sheet->clearOwnerNode();
 
-    if (m_resource)
-        m_resource->removeClient(this);
-
     if (inDocument())
         document().styleEngine()->removeStyleSheetCandidateNode(this);
 }
@@ -123,35 +119,28 @@
                 m_loading = false;
             }
         } else {
-            if (m_resource) {
-                m_resource->removeClient(this);
-                m_resource = 0;
-            }
+            clearResource();
 
             String url = document().completeURL(href).string();
             if (!dispatchBeforeLoadEvent(url))
                 return;
 
-            m_loading = true;
-            document().styleEngine()->addPendingSheet();
+            ResourcePtr<StyleSheetResource> resource;
             FetchRequest request(ResourceRequest(document().completeURL(href)), FetchInitiatorTypeNames::processinginstruction);
-            if (m_isXSL)
-                m_resource = document().fetcher()->fetchXSLStyleSheet(request);
-            else
-            {
+            if (m_isXSL) {
+                resource = document().fetcher()->fetchXSLStyleSheet(request);
+            } else {
                 String charset = attrs.get("charset");
                 if (charset.isEmpty())
                     charset = document().charset();
                 request.setCharset(charset);
-
-                m_resource = document().fetcher()->fetchCSSStyleSheet(request);
+                resource = document().fetcher()->fetchCSSStyleSheet(request);
             }
-            if (m_resource)
-                m_resource->addClient(this);
-            else {
-                // The request may have been denied if (for example) the stylesheet is local and the document is remote.
-                m_loading = false;
-                document().styleEngine()->removePendingSheet(this);
+
+            if (resource) {
+                m_loading = true;
+                document().styleEngine()->addPendingSheet();
+                setResource(resource);
             }
         }
     }
@@ -183,7 +172,7 @@
     }
 
     ASSERT(m_isCSS);
-    CSSParserContext parserContext(document(), baseURL, charset);
+    CSSParserContext parserContext(document(), 0, baseURL, charset);
 
     RefPtr<StyleSheetContents> newSheet = StyleSheetContents::create(href, parserContext);
 
@@ -214,10 +203,7 @@
     else if (m_isXSL)
         toXSLStyleSheet(m_sheet.get())->parseString(sheet);
 
-    if (m_resource)
-        m_resource->removeClient(this);
-    m_resource = 0;
-
+    clearResource();
     m_loading = false;
 
     if (m_isCSS)
@@ -228,21 +214,13 @@
 
 void ProcessingInstruction::setCSSStyleSheet(PassRefPtr<CSSStyleSheet> sheet)
 {
-    ASSERT(!m_resource);
+    ASSERT(!resource());
     ASSERT(!m_loading);
     m_sheet = sheet;
     sheet->setTitle(m_title);
     sheet->setDisabled(m_alternate);
 }
 
-void ProcessingInstruction::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    if (!sheet())
-        return;
-
-    addSubresourceURL(urls, sheet()->baseURL());
-}
-
 Node::InsertionNotificationRequest ProcessingInstruction::insertedInto(ContainerNode* insertionPoint)
 {
     CharacterData::insertedInto(insertionPoint);
@@ -274,10 +252,4 @@
         document().removedStyleSheet(removedSheet.get());
 }
 
-void ProcessingInstruction::finishParsingChildren()
-{
-    m_createdByParser = false;
-    CharacterData::finishParsingChildren();
-}
-
 } // namespace
diff --git a/Source/core/dom/ProcessingInstruction.h b/Source/core/dom/ProcessingInstruction.h
index b95c670..374534f 100644
--- a/Source/core/dom/ProcessingInstruction.h
+++ b/Source/core/dom/ProcessingInstruction.h
@@ -23,7 +23,8 @@
 #define ProcessingInstruction_h
 
 #include "core/dom/CharacterData.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
+#include "core/fetch/StyleSheetResource.h"
 #include "core/fetch/StyleSheetResourceClient.h"
 
 namespace WebCore {
@@ -31,7 +32,7 @@
 class StyleSheet;
 class CSSStyleSheet;
 
-class ProcessingInstruction FINAL : public CharacterData, private StyleSheetResourceClient {
+class ProcessingInstruction FINAL : public CharacterData, private ResourceOwner<StyleSheetResource> {
 public:
     static PassRefPtr<ProcessingInstruction> create(Document&, const String& target, const String& data);
     virtual ~ProcessingInstruction();
@@ -40,8 +41,6 @@
 
     void setCreatedByParser(bool createdByParser) { m_createdByParser = createdByParser; }
 
-    virtual void finishParsingChildren();
-
     const String& localHref() const { return m_localHref; }
     StyleSheet* sheet() const { return m_sheet.get(); }
     void setCSSStyleSheet(PassRefPtr<CSSStyleSheet>);
@@ -55,20 +54,18 @@
     friend class CharacterData;
     ProcessingInstruction(Document&, const String& target, const String& data);
 
-    virtual String nodeName() const;
-    virtual NodeType nodeType() const;
-    virtual PassRefPtr<Node> cloneNode(bool deep = true);
+    virtual String nodeName() const OVERRIDE;
+    virtual NodeType nodeType() const OVERRIDE;
+    virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE;
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
     void checkStyleSheet();
-    virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*);
-    virtual void setXSLStyleSheet(const String& href, const KURL& baseURL, const String& sheet);
+    virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*) OVERRIDE;
+    virtual void setXSLStyleSheet(const String& href, const KURL& baseURL, const String& sheet) OVERRIDE;
 
-    virtual bool sheetLoaded();
-
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
+    virtual bool sheetLoaded() OVERRIDE;
 
     void parseStyleSheet(const String& sheet);
 
@@ -76,7 +73,6 @@
     String m_localHref;
     String m_title;
     String m_media;
-    ResourcePtr<Resource> m_resource;
     RefPtr<StyleSheet> m_sheet;
     bool m_loading;
     bool m_alternate;
diff --git a/Source/core/dom/Promise.idl b/Source/core/dom/Promise.idl
index 77b3976..45989d4 100644
--- a/Source/core/dom/Promise.idl
+++ b/Source/core/dom/Promise.idl
@@ -31,8 +31,8 @@
 callback PromiseInit = void (any resolve, any reject);
 callback AnyCallback = any (optional any value);
 [
-   GlobalContext=Window&WorkerGlobalScope,
    CustomConstructor(PromiseInit init),
+   GlobalContext=Window&WorkerGlobalScope,
 ] interface Promise {
    [Custom] Promise then(optional AnyCallback fulfillCallback, optional AnyCallback rejectCallback);
    [Custom] Promise catch(optional AnyCallback rejectCallback);
diff --git a/Source/core/dom/PseudoElement.cpp b/Source/core/dom/PseudoElement.cpp
index 9512d82..b87dadd 100644
--- a/Source/core/dom/PseudoElement.cpp
+++ b/Source/core/dom/PseudoElement.cpp
@@ -70,6 +70,8 @@
 
 void PseudoElement::dispose()
 {
+    ASSERT(parentOrShadowHostElement());
+
     InspectorInstrumentation::pseudoElementDestroyed(this);
 
     ASSERT(!nextSibling());
@@ -91,8 +93,6 @@
     if (!renderer)
         return;
     RenderStyle* style = renderer->style();
-    if (style->hasFlowFrom())
-        return;
     if (style->styleType() != BEFORE && style->styleType() != AFTER)
         return;
     ASSERT(style->contentData());
diff --git a/Source/core/dom/PseudoElement.h b/Source/core/dom/PseudoElement.h
index 6f10933..8fbd1da 100644
--- a/Source/core/dom/PseudoElement.h
+++ b/Source/core/dom/PseudoElement.h
@@ -44,10 +44,6 @@
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
-    // As per http://dev.w3.org/csswg/css3-regions/#flow-into, pseudo-elements such as ::first-line, ::first-letter, ::before or ::after
-    // cannot be directly collected into a named flow.
-    virtual bool shouldMoveToFlowThread(RenderStyle*) const OVERRIDE { return false; }
-
     virtual bool canStartSelection() const OVERRIDE { return false; }
     virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
 
@@ -68,7 +64,7 @@
 
 inline bool pseudoElementRendererIsNeeded(const RenderStyle* style)
 {
-    return style && style->display() != NONE && (style->styleType() == BACKDROP || style->contentData() || style->hasFlowFrom());
+    return style && style->display() != NONE && (style->styleType() == BACKDROP || style->contentData());
 }
 
 DEFINE_NODE_TYPE_CASTS(PseudoElement, isPseudoElement());
diff --git a/Source/core/dom/QualifiedName.cpp b/Source/core/dom/QualifiedName.cpp
index 1912986..4400201 100644
--- a/Source/core/dom/QualifiedName.cpp
+++ b/Source/core/dom/QualifiedName.cpp
@@ -77,24 +77,11 @@
 {
     QualifiedNameComponents components = { p.impl(), l.impl(), n.isEmpty() ? nullAtom.impl() : n.impl() };
     QualifiedNameCache::AddResult addResult = qualifiedNameCache().add<QNameComponentsTranslator>(components);
-    m_impl = *addResult.iterator;
-    if (!addResult.isNewEntry)
-        m_impl->ref();
+    m_impl = addResult.isNewEntry ? adoptRef(*addResult.storedValue) : *addResult.storedValue;
 }
 
 QualifiedName::~QualifiedName()
 {
-    deref();
-}
-
-void QualifiedName::deref()
-{
-#ifdef QNAME_DEFAULT_CONSTRUCTOR
-    if (!m_impl)
-        return;
-#endif
-    ASSERT(!isHashTableDeletedValue());
-    m_impl->deref();
 }
 
 QualifiedName::QualifiedNameImpl::~QualifiedNameImpl()
diff --git a/Source/core/dom/QualifiedName.h b/Source/core/dom/QualifiedName.h
index b42f9e4..638ce0b 100644
--- a/Source/core/dom/QualifiedName.h
+++ b/Source/core/dom/QualifiedName.h
@@ -67,15 +67,17 @@
     };
 
     QualifiedName(const AtomicString& prefix, const AtomicString& localName, const AtomicString& namespaceURI);
-    QualifiedName(WTF::HashTableDeletedValueType) : m_impl(hashTableDeletedValue()) { }
-    bool isHashTableDeletedValue() const { return m_impl == hashTableDeletedValue(); }
     ~QualifiedName();
 #ifdef QNAME_DEFAULT_CONSTRUCTOR
-    QualifiedName() : m_impl(0) { }
+    QualifiedName() { }
 #endif
 
-    QualifiedName(const QualifiedName& other) : m_impl(other.m_impl) { ref(); }
-    const QualifiedName& operator=(const QualifiedName& other) { other.ref(); deref(); m_impl = other.m_impl; return *this; }
+    QualifiedName(const QualifiedName& other) : m_impl(other.m_impl) { }
+    const QualifiedName& operator=(const QualifiedName& other) { m_impl = other.m_impl; return *this; }
+
+    // Hash table deleted values, which are only constructed and never copied or destroyed.
+    QualifiedName(WTF::HashTableDeletedValueType) : m_impl(WTF::HashTableDeletedValue) { }
+    bool isHashTableDeletedValue() const { return m_impl.isHashTableDeletedValue(); }
 
     bool operator==(const QualifiedName& other) const { return m_impl == other.m_impl; }
     bool operator!=(const QualifiedName& other) const { return !(*this == other); }
@@ -96,18 +98,13 @@
 
     String toString() const;
 
-    QualifiedNameImpl* impl() const { return m_impl; }
+    QualifiedNameImpl* impl() const { return m_impl.get(); }
 
     // Init routine for globals
     static void init();
 
 private:
-    void ref() const { m_impl->ref(); }
-    void deref();
-
-    static QualifiedNameImpl* hashTableDeletedValue() { return RefPtr<QualifiedNameImpl>::hashTableDeletedValue(); }
-
-    QualifiedNameImpl* m_impl;
+    RefPtr<QualifiedNameImpl> m_impl;
 };
 
 #ifndef WEBCORE_QUALIFIEDNAME_HIDE_GLOBALS
diff --git a/Source/core/dom/Range.cpp b/Source/core/dom/Range.cpp
index 5b75ea2..9c9ac34 100644
--- a/Source/core/dom/Range.cpp
+++ b/Source/core/dom/Range.cpp
@@ -25,7 +25,6 @@
 #include "config.h"
 #include "core/dom/Range.h"
 
-#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ClientRect.h"
 #include "core/dom/ClientRectList.h"
@@ -217,7 +216,7 @@
     }
 
     if (!refNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided was null.");
         return;
     }
 
@@ -245,7 +244,7 @@
     }
 
     if (!refNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided was null.");
         return;
     }
 
@@ -298,7 +297,7 @@
     }
 
     if (!refNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwDOMException(HierarchyRequestError, "The node provided was null.");
         return false;
     }
 
@@ -326,12 +325,17 @@
     }
 
     if (!refNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwDOMException(HierarchyRequestError, "The node provided was null.");
         return 0;
     }
 
-    if (!refNode->inActiveDocument() || refNode->document() != m_ownerDocument) {
-        exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
+    if (!refNode->inActiveDocument()) {
+        exceptionState.throwDOMException(WrongDocumentError, "The node provided is not in an active document.");
+        return 0;
+    }
+
+    if (refNode->document() != m_ownerDocument) {
+        exceptionState.throwDOMException(WrongDocumentError, "The node provided is not in this Range's Document.");
         return 0;
     }
 
@@ -361,12 +365,12 @@
     // before and after(surrounds), or inside the range, respectively
 
     if (!refNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided was null.");
         return NODE_BEFORE;
     }
 
     if (!m_start.container() && refNode->inActiveDocument()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "This Range is detached, and the provided node is not.");
         return NODE_BEFORE;
     }
 
@@ -386,7 +390,7 @@
     if (!parentNode) {
         // if the node is the top document we should return NODE_BEFORE_AND_AFTER
         // but we throw to match firefox behavior
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The provided node has no parent.");
         return NODE_BEFORE;
     }
 
@@ -409,7 +413,7 @@
     }
 
     if (!sourceRange) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The source range provided was null.");
         return 0;
     }
 
@@ -421,7 +425,7 @@
         return 0;
 
     if (thisCont->document() != sourceCont->document()) {
-        exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
+        exceptionState.throwDOMException(WrongDocumentError, "The source range is in a different document than this range.");
         return 0;
     }
 
@@ -432,7 +436,7 @@
     while (sourceTop->parentNode())
         sourceTop = sourceTop->parentNode();
     if (thisTop != sourceTop) { // in different DocumentFragments
-        exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
+        exceptionState.throwDOMException(WrongDocumentError, "The source range is in a different document than this range.");
         return 0;
     }
 
@@ -447,7 +451,7 @@
             return compareBoundaryPoints(m_start, sourceRange->m_end, exceptionState);
     }
 
-    exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+    exceptionState.throwDOMException(SyntaxError, "The comparison method provided must be one of 'START_TO_START', 'START_TO_END', 'END_TO_END', or 'END_TO_START'.");
     return 0;
 }
 
@@ -513,7 +517,7 @@
     // ### we need to do a traversal here instead
     Node* commonAncestor = commonAncestorContainer(containerA, containerB);
     if (!commonAncestor) {
-        exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
+        exceptionState.throwDOMException(WrongDocumentError, "The two ranges are in separate documents.");
         return 0;
     }
     Node* childA = containerA;
@@ -575,7 +579,7 @@
         return false;
     }
     if (!refNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided is null.");
         return false;
     }
 
@@ -590,7 +594,7 @@
     if (!parentNode) {
         // if the node is the top document we should return NODE_BEFORE_AND_AFTER
         // but we throw to match firefox behavior
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided has no parent.");
         return false;
     }
 
@@ -652,12 +656,9 @@
         return toProcessingInstruction(node)->data().length();
     case Node::ELEMENT_NODE:
     case Node::ATTRIBUTE_NODE:
-    case Node::ENTITY_NODE:
     case Node::DOCUMENT_NODE:
     case Node::DOCUMENT_TYPE_NODE:
     case Node::DOCUMENT_FRAGMENT_NODE:
-    case Node::NOTATION_NODE:
-    case Node::XPATH_NAMESPACE_NODE:
         return node->childNodeCount();
     }
     ASSERT_NOT_REACHED();
@@ -824,12 +825,9 @@
         break;
     case Node::ELEMENT_NODE:
     case Node::ATTRIBUTE_NODE:
-    case Node::ENTITY_NODE:
     case Node::DOCUMENT_NODE:
     case Node::DOCUMENT_TYPE_NODE:
     case Node::DOCUMENT_FRAGMENT_NODE:
-    case Node::NOTATION_NODE:
-    case Node::XPATH_NAMESPACE_NODE:
         // FIXME: Should we assert that some nodes never appear here?
         if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
             if (fragment)
@@ -879,7 +877,7 @@
         ancestors.append(n);
 
     RefPtr<Node> firstChildInAncestorToProcess = direction == ProcessContentsForward ? container->nextSibling() : container->previousSibling();
-    for (Vector<RefPtr<Node> >::const_iterator it = ancestors.begin(); it != ancestors.end(); it++) {
+    for (Vector<RefPtr<Node> >::const_iterator it = ancestors.begin(); it != ancestors.end(); ++it) {
         RefPtr<Node> ancestor = *it;
         if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
             if (RefPtr<Node> clonedAncestor = ancestor->cloneNode(false)) { // Might have been removed already during mutation event.
@@ -898,7 +896,7 @@
             child = (direction == ProcessContentsForward) ? child->nextSibling() : child->previousSibling())
             nodes.append(child);
 
-        for (NodeVector::const_iterator it = nodes.begin(); it != nodes.end(); it++) {
+        for (NodeVector::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
             Node* child = it->get();
             switch (action) {
             case DELETE_CONTENTS:
@@ -953,7 +951,7 @@
     }
 
     if (!newNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided is null.");
         return;
     }
 
@@ -963,7 +961,7 @@
     // an extra one here - if a text node is going to split, it must have a parent to insert into
     bool startIsText = m_start.container()->isTextNode();
     if (startIsText && !m_start.container()->parentNode()) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwDOMException(HierarchyRequestError, "This operation would split a text node, but there's no parent into which to insert.");
         return;
     }
 
@@ -982,7 +980,7 @@
         numNewChildren = 0;
         for (Node* c = newNode->firstChild(); c; c = c->nextSibling()) {
             if (!checkAgainst->childTypeAllowed(c->nodeType())) {
-                exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+                exceptionState.throwDOMException(HierarchyRequestError, "The node to be inserted contains a '" + c->nodeName() + "' node, which may not be inserted here.");
                 return;
             }
             ++numNewChildren;
@@ -990,14 +988,14 @@
     } else {
         numNewChildren = 1;
         if (!checkAgainst->childTypeAllowed(newNodeType)) {
-            exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+            exceptionState.throwDOMException(HierarchyRequestError, "The node to be inserted is a '" + newNode->nodeName() + "' node, which may not be inserted here.");
             return;
         }
     }
 
     for (Node* n = m_start.container(); n; n = n->parentNode()) {
         if (n == newNode) {
-            exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+            exceptionState.throwDOMException(HierarchyRequestError, "The node to be inserted contains the insertion point; it may not be inserted into itself.");
             return;
         }
     }
@@ -1005,14 +1003,12 @@
     // InvalidNodeTypeError: Raised if newNode is an Attr, Entity, Notation, ShadowRoot or Document node.
     switch (newNodeType) {
     case Node::ATTRIBUTE_NODE:
-    case Node::ENTITY_NODE:
-    case Node::NOTATION_NODE:
     case Node::DOCUMENT_NODE:
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+        exceptionState.throwDOMException(InvalidNodeTypeError, "The node to be inserted is a '" + newNode->nodeName() + "' node, which may not be inserted here.");
         return;
     default:
         if (newNode->isShadowRoot()) {
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwDOMException(InvalidNodeTypeError, "The node to be inserted is a shadow root, which may not be inserted here.");
             return;
         }
         break;
@@ -1136,30 +1132,27 @@
 {
     switch (n->nodeType()) {
         case Node::DOCUMENT_TYPE_NODE:
-        case Node::ENTITY_NODE:
-        case Node::NOTATION_NODE:
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + n->nodeName() + "'.");
             return 0;
         case Node::CDATA_SECTION_NODE:
         case Node::COMMENT_NODE:
         case Node::TEXT_NODE:
             if (static_cast<unsigned>(offset) > toCharacterData(n)->length())
-                exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+                exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is larger than or equal to the node's length (" + String::number(toCharacterData(n)->length()) + ").");
             return 0;
         case Node::PROCESSING_INSTRUCTION_NODE:
             if (static_cast<unsigned>(offset) > toProcessingInstruction(n)->data().length())
-                exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+                exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is larger than or equal to than the node's length (" + String::number(toProcessingInstruction(n)->data().length()) + ").");
             return 0;
         case Node::ATTRIBUTE_NODE:
         case Node::DOCUMENT_FRAGMENT_NODE:
         case Node::DOCUMENT_NODE:
-        case Node::ELEMENT_NODE:
-        case Node::XPATH_NAMESPACE_NODE: {
+        case Node::ELEMENT_NODE: {
             if (!offset)
                 return 0;
             Node* childBefore = n->childNode(offset - 1);
             if (!childBefore)
-                exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+                exceptionState.throwDOMException(IndexSizeError, "There is no child at offset " + String::number(offset) + ".");
             return childBefore;
         }
     }
@@ -1175,7 +1168,7 @@
     }
 
     if (!n) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided is null.");
         return;
     }
 
@@ -1192,9 +1185,7 @@
         case Node::ATTRIBUTE_NODE:
         case Node::DOCUMENT_FRAGMENT_NODE:
         case Node::DOCUMENT_NODE:
-        case Node::ENTITY_NODE:
-        case Node::NOTATION_NODE:
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + n->nodeName() + "'.");
             return;
         case Node::CDATA_SECTION_NODE:
         case Node::COMMENT_NODE:
@@ -1202,7 +1193,6 @@
         case Node::ELEMENT_NODE:
         case Node::PROCESSING_INSTRUCTION_NODE:
         case Node::TEXT_NODE:
-        case Node::XPATH_NAMESPACE_NODE:
             break;
     }
 
@@ -1219,12 +1209,9 @@
         case Node::CDATA_SECTION_NODE:
         case Node::COMMENT_NODE:
         case Node::DOCUMENT_TYPE_NODE:
-        case Node::ENTITY_NODE:
-        case Node::NOTATION_NODE:
         case Node::PROCESSING_INSTRUCTION_NODE:
         case Node::TEXT_NODE:
-        case Node::XPATH_NAMESPACE_NODE:
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + n->nodeName() + "'.");
             return;
     }
 }
@@ -1274,7 +1261,7 @@
     }
 
     if (!refNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided is null.");
         return;
     }
 
@@ -1296,12 +1283,9 @@
             case Node::ELEMENT_NODE:
             case Node::PROCESSING_INSTRUCTION_NODE:
             case Node::TEXT_NODE:
-            case Node::XPATH_NAMESPACE_NODE:
                 break;
             case Node::DOCUMENT_TYPE_NODE:
-            case Node::ENTITY_NODE:
-            case Node::NOTATION_NODE:
-                exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+                exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided has an ancestor of type '" + anc->nodeName() + "'.");
                 return;
         }
     }
@@ -1313,14 +1297,11 @@
         case Node::ELEMENT_NODE:
         case Node::PROCESSING_INSTRUCTION_NODE:
         case Node::TEXT_NODE:
-        case Node::XPATH_NAMESPACE_NODE:
             break;
         case Node::ATTRIBUTE_NODE:
         case Node::DOCUMENT_FRAGMENT_NODE:
         case Node::DOCUMENT_NODE:
-        case Node::ENTITY_NODE:
-        case Node::NOTATION_NODE:
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + refNode->nodeName() + "'.");
             return;
     }
 
@@ -1339,7 +1320,7 @@
     }
 
     if (!refNode) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided is null.");
         return;
     }
 
@@ -1355,12 +1336,9 @@
             case Node::ELEMENT_NODE:
             case Node::PROCESSING_INSTRUCTION_NODE:
             case Node::TEXT_NODE:
-            case Node::XPATH_NAMESPACE_NODE:
                 break;
             case Node::DOCUMENT_TYPE_NODE:
-            case Node::ENTITY_NODE:
-            case Node::NOTATION_NODE:
-                exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+                exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + refNode->nodeName() + "'.");
                 return;
         }
     }
@@ -1382,7 +1360,7 @@
     }
 
     if (!newParent) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The node provided is null.");
         return;
     }
 
@@ -1393,16 +1371,13 @@
         case Node::DOCUMENT_FRAGMENT_NODE:
         case Node::DOCUMENT_NODE:
         case Node::DOCUMENT_TYPE_NODE:
-        case Node::ENTITY_NODE:
-        case Node::NOTATION_NODE:
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+            exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + newParent->nodeName() + "'.");
             return;
         case Node::CDATA_SECTION_NODE:
         case Node::COMMENT_NODE:
         case Node::ELEMENT_NODE:
         case Node::PROCESSING_INSTRUCTION_NODE:
         case Node::TEXT_NODE:
-        case Node::XPATH_NAMESPACE_NODE:
             break;
     }
 
@@ -1414,13 +1389,19 @@
     // although this will fail below for another reason).
     if (parentOfNewParent->isCharacterDataNode())
         parentOfNewParent = parentOfNewParent->parentNode();
-    if (!parentOfNewParent || !parentOfNewParent->childTypeAllowed(newParent->nodeType())) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+
+    if (!parentOfNewParent) {
+        exceptionState.throwDOMException(HierarchyRequestError, "The container node is a detached character data node; no parent node is available for insertion.");
+        return;
+    }
+
+    if (!parentOfNewParent->childTypeAllowed(newParent->nodeType())) {
+        exceptionState.throwDOMException(HierarchyRequestError, "The node provided is of type '" + newParent->nodeName() + "', which may not be inserted here.");
         return;
     }
 
     if (newParent->contains(m_start.container())) {
-        exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        exceptionState.throwDOMException(HierarchyRequestError, "The node provided contains the insertion point; it may not be inserted into itself.");
         return;
     }
 
@@ -1435,7 +1416,7 @@
     if (endNonTextContainer->nodeType() == Node::TEXT_NODE)
         endNonTextContainer = endNonTextContainer->parentNode();
     if (startNonTextContainer != endNonTextContainer) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "The Range has partially selected a non-Text node.");
         return;
     }
 
@@ -1477,8 +1458,8 @@
 
     Node* pastLast = pastLastNode();
     for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(*n)) {
-        if (n->nodeType() == Node::DOCUMENT_TYPE_NODE) {
-            exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
+        if (n->isDocumentTypeNode()) {
+            exceptionState.throwDOMException(HierarchyRequestError, "The Range contains a doctype node.");
             return;
         }
     }
diff --git a/Source/core/dom/RawDataDocumentParser.h b/Source/core/dom/RawDataDocumentParser.h
index f2adeed..ade8afe 100644
--- a/Source/core/dom/RawDataDocumentParser.h
+++ b/Source/core/dom/RawDataDocumentParser.h
@@ -38,7 +38,7 @@
     {
     }
 
-    virtual void finish()
+    virtual void finish() OVERRIDE
     {
         if (!isStopped())
             document()->finishedParsing();
@@ -51,11 +51,11 @@
         appendBytes(0, 0);
     }
 
-    virtual void insert(const SegmentedString&)
+    virtual void insert(const SegmentedString&) OVERRIDE
     {
     }
 
-    virtual void append(PassRefPtr<StringImpl>)
+    virtual void append(PassRefPtr<StringImpl>) OVERRIDE
     {
         ASSERT_NOT_REACHED();
     }
diff --git a/Source/core/dom/RenderTreeBuilder.cpp b/Source/core/dom/RenderTreeBuilder.cpp
new file mode 100644
index 0000000..168fcce
--- /dev/null
+++ b/Source/core/dom/RenderTreeBuilder.cpp
@@ -0,0 +1,189 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/dom/RenderTreeBuilder.h"
+
+#include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
+#include "SVGNames.h"
+#include "core/css/resolver/StyleResolver.h"
+#include "core/dom/FullscreenElementStack.h"
+#include "core/dom/Node.h"
+#include "core/dom/Text.h"
+#include "core/rendering/RenderFullScreen.h"
+#include "core/rendering/RenderObject.h"
+#include "core/rendering/RenderText.h"
+#include "core/rendering/RenderView.h"
+#include "core/svg/SVGElement.h"
+
+namespace WebCore {
+
+RenderObject* RenderTreeBuilder::nextRenderer() const
+{
+    ASSERT(m_renderingParent);
+
+    Element* element = m_node->isElementNode() ? toElement(m_node) : 0;
+
+    if (element && element->isInTopLayer())
+        return NodeRenderingTraversal::nextInTopLayer(element);
+
+    // Avoid an O(N^2) walk over the children when reattaching all children of a node.
+    if (m_renderingParent->needsAttach())
+        return 0;
+
+    return NodeRenderingTraversal::nextSiblingRenderer(m_node);
+}
+
+RenderObject* RenderTreeBuilder::parentRenderer() const
+{
+    ASSERT(m_renderingParent);
+
+    Element* element = m_node->isElementNode() ? toElement(m_node) : 0;
+
+    if (element && m_renderingParent->renderer()) {
+        // FIXME: Guarding this by m_renderingParent->renderer() isn't quite right as the spec for
+        // top layer only talks about display: none ancestors so putting a <dialog> inside an
+        // <optgroup> seems like it should still work even though this check will prevent it.
+        if (element->isInTopLayer())
+            return m_node->document().renderView();
+    }
+
+    return m_renderingParent->renderer();
+}
+
+bool RenderTreeBuilder::shouldCreateRenderer() const
+{
+    if (!m_renderingParent)
+        return false;
+    if (m_node->isSVGElement()) {
+        // SVG elements only render when inside <svg>, or if the element is an <svg> itself.
+        if (!m_node->hasTagName(SVGNames::svgTag) && !m_renderingParent->isSVGElement())
+            return false;
+        if (!toSVGElement(m_node)->isValid())
+            return false;
+    }
+    RenderObject* parentRenderer = this->parentRenderer();
+    if (!parentRenderer)
+        return false;
+    if (!parentRenderer->canHaveChildren())
+        return false;
+    return true;
+}
+
+RenderStyle& RenderTreeBuilder::style() const
+{
+    if (!m_style)
+        m_style = toElement(m_node)->styleForRenderer();
+    return *m_style;
+}
+
+void RenderTreeBuilder::createRendererForElementIfNeeded()
+{
+    ASSERT(!m_node->renderer());
+
+    // If we're out of composition then we can't render since there's no parent to inherit from.
+    if (!m_renderingParent)
+        return;
+
+    Element* element = toElement(m_node);
+
+    if (!shouldCreateRenderer())
+        return;
+
+    RenderStyle& style = this->style();
+
+    if (!element->rendererIsNeeded(style))
+        return;
+
+    RenderObject* newRenderer = element->createRenderer(&style);
+    if (!newRenderer)
+        return;
+
+    RenderObject* parentRenderer = this->parentRenderer();
+
+    if (!parentRenderer->isChildAllowed(newRenderer, &style)) {
+        newRenderer->destroy();
+        return;
+    }
+
+    // Make sure the RenderObject already knows it is going to be added to a RenderFlowThread before we set the style
+    // for the first time. Otherwise code using inRenderFlowThread() in the styleWillChange and styleDidChange will fail.
+    newRenderer->setFlowThreadState(parentRenderer->flowThreadState());
+
+    RenderObject* nextRenderer = this->nextRenderer();
+    element->setRenderer(newRenderer);
+    newRenderer->setStyle(&style); // setStyle() can depend on renderer() already being set.
+
+    if (FullscreenElementStack::isActiveFullScreenElement(element)) {
+        newRenderer = RenderFullScreen::wrapRenderer(newRenderer, parentRenderer, &element->document());
+        if (!newRenderer)
+            return;
+    }
+
+    // Note: Adding newRenderer instead of renderer(). renderer() may be a child of newRenderer.
+    parentRenderer->addChild(newRenderer, nextRenderer);
+}
+
+void RenderTreeBuilder::createRendererForTextIfNeeded()
+{
+    ASSERT(!m_node->renderer());
+
+    // If we're out of composition then we can't render since there's no parent to inherit from.
+    if (!m_renderingParent)
+        return;
+
+    if (!shouldCreateRenderer())
+        return;
+
+    Text* textNode = toText(m_node);
+    RenderObject* parentRenderer = this->parentRenderer();
+
+    if (m_parentDetails.resetStyleInheritance())
+        m_style = textNode->document().ensureStyleResolver().defaultStyleForElement();
+    else
+        m_style = parentRenderer->style();
+
+    if (!textNode->textRendererIsNeeded(*m_style, *parentRenderer))
+        return;
+
+    RenderText* newRenderer = textNode->createTextRenderer(m_style.get());
+    if (!parentRenderer->isChildAllowed(newRenderer, m_style.get())) {
+        newRenderer->destroy();
+        return;
+    }
+
+    // Make sure the RenderObject already knows it is going to be added to a RenderFlowThread before we set the style
+    // for the first time. Otherwise code using inRenderFlowThread() in the styleWillChange and styleDidChange will fail.
+    newRenderer->setFlowThreadState(parentRenderer->flowThreadState());
+
+    RenderObject* nextRenderer = this->nextRenderer();
+    textNode->setRenderer(newRenderer);
+    // Parent takes care of the animations, no need to call setAnimatableStyle.
+    newRenderer->setStyle(m_style.release());
+    parentRenderer->addChild(newRenderer, nextRenderer);
+}
+
+}
diff --git a/Source/core/dom/NodeRenderingContext.h b/Source/core/dom/RenderTreeBuilder.h
similarity index 69%
rename from Source/core/dom/NodeRenderingContext.h
rename to Source/core/dom/RenderTreeBuilder.h
index ac2bab3..3a98514 100644
--- a/Source/core/dom/NodeRenderingContext.h
+++ b/Source/core/dom/RenderTreeBuilder.h
@@ -23,52 +23,53 @@
  *
  */
 
-#ifndef NodeRenderingContext_h
-#define NodeRenderingContext_h
+#ifndef RenderTreeBuilder_h
+#define RenderTreeBuilder_h
 
+#include "core/dom/Document.h"
+#include "core/dom/Node.h"
 #include "core/dom/NodeRenderingTraversal.h"
-
 #include "wtf/RefPtr.h"
 
 namespace WebCore {
 
 class ContainerNode;
-class Node;
-class RenderNamedFlowThread;
 class RenderObject;
 class RenderStyle;
 
-class NodeRenderingContext {
+class RenderTreeBuilder {
 public:
-    explicit NodeRenderingContext(Node* node, RenderStyle* style = 0)
+    RenderTreeBuilder(Node* node, RenderStyle* style)
         : m_node(node)
         , m_renderingParent(0)
         , m_style(style)
-        , m_parentFlowRenderer(0)
     {
+        ASSERT(!node->renderer());
+        ASSERT(node->needsAttach());
+        ASSERT(node->document().inStyleRecalc());
+
+        // FIXME: We should be able to ASSERT(node->inActiveDocument()) but childrenChanged is called
+        // before ChildNodeInsertionNotifier in ContainerNode's methods and some implementations
+        // will trigger a layout inside childrenChanged.
+        // Mainly HTMLTextAreaElement::childrenChanged calls HTMLTextFormControlElement::setSelectionRange
+        // which does an updateLayoutIgnorePendingStylesheets.
+
         m_renderingParent = NodeRenderingTraversal::parent(node, &m_parentDetails);
     }
 
     void createRendererForTextIfNeeded();
     void createRendererForElementIfNeeded();
 
-    Node* node() const { return m_node; }
+private:
     RenderObject* parentRenderer() const;
     RenderObject* nextRenderer() const;
-    RenderObject* previousRenderer() const;
-
-    const RenderStyle* style() const { return m_style.get(); }
-
-private:
     bool shouldCreateRenderer() const;
-    void moveToFlowThreadIfNeeded();
-    bool elementInsideRegionNeedsRenderer();
+    RenderStyle& style() const;
 
     Node* m_node;
     ContainerNode* m_renderingParent;
     NodeRenderingTraversal::ParentDetails m_parentDetails;
-    RefPtr<RenderStyle> m_style;
-    RenderNamedFlowThread* m_parentFlowRenderer;
+    mutable RefPtr<RenderStyle> m_style;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/RenderedDocumentMarker.h b/Source/core/dom/RenderedDocumentMarker.h
index 9e6966a..fb0bdfd 100644
--- a/Source/core/dom/RenderedDocumentMarker.h
+++ b/Source/core/dom/RenderedDocumentMarker.h
@@ -62,10 +62,7 @@
         invalidate();
 }
 
-inline RenderedDocumentMarker* toRenderedDocumentMarker(DocumentMarker* marker)
-{
-    return static_cast<RenderedDocumentMarker*>(marker);
-}
+DEFINE_TYPE_CASTS(RenderedDocumentMarker, DocumentMarker, marker, true, true);
 
 } // namespace
 
diff --git a/Source/core/dom/RequestAnimationFrameCallback.h b/Source/core/dom/RequestAnimationFrameCallback.h
index d2b212b..417f671 100644
--- a/Source/core/dom/RequestAnimationFrameCallback.h
+++ b/Source/core/dom/RequestAnimationFrameCallback.h
@@ -36,7 +36,7 @@
 class RequestAnimationFrameCallback {
 public:
     virtual ~RequestAnimationFrameCallback() { }
-    virtual bool handleEvent(double highResTimeMs) = 0;
+    virtual void handleEvent(double highResTimeMs) = 0;
 
     int m_id;
     bool m_cancelled;
diff --git a/Source/core/dom/RequestAnimationFrameCallback.idl b/Source/core/dom/RequestAnimationFrameCallback.idl
index d2f1d22..cb0ec66 100644
--- a/Source/core/dom/RequestAnimationFrameCallback.idl
+++ b/Source/core/dom/RequestAnimationFrameCallback.idl
@@ -31,5 +31,5 @@
 callback interface RequestAnimationFrameCallback{
     // highResTime is passed as high resolution timestamp, see
     // http://www.w3.org/TR/hr-time/ for details.
-    boolean handleEvent(double highResTime);
+    void handleEvent(double highResTime);
 };
diff --git a/Source/core/dom/SandboxFlags.h b/Source/core/dom/SandboxFlags.h
index fa072d1..54d0a88 100644
--- a/Source/core/dom/SandboxFlags.h
+++ b/Source/core/dom/SandboxFlags.h
@@ -42,9 +42,8 @@
     SandboxTopNavigation = 1 << 5,
     SandboxPopups = 1 << 6, // See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12393
     SandboxAutomaticFeatures = 1 << 7,
-    SandboxSeamlessIframes = 1 << 8,
-    SandboxPointerLock = 1 << 9,
-    SandboxDocumentDomain = 1 << 10,
+    SandboxPointerLock = 1 << 8,
+    SandboxDocumentDomain = 1 << 9,
     SandboxAll = -1 // Mask with all bits set to 1.
 };
 
diff --git a/Source/core/dom/ScriptLoader.cpp b/Source/core/dom/ScriptLoader.cpp
index eaa0e45..ac91a97 100644
--- a/Source/core/dom/ScriptLoader.cpp
+++ b/Source/core/dom/ScriptLoader.cpp
@@ -65,7 +65,6 @@
     , m_willExecuteWhenDocumentFinishedParsing(false)
     , m_forceAsync(!parserInserted)
     , m_willExecuteInOrder(false)
-    , m_isPotentiallyCORSEnabled(false)
 {
     ASSERT(m_element);
     if (parserInserted && element->document().scriptableDocumentParser() && !element->document().isInDocumentWrite())
@@ -159,7 +158,7 @@
         type = "text/" + language.lower();
         if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(type) || isLegacySupportedJavaScriptLanguage(language))
             return true;
-    } else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(type.stripWhiteSpace().lower()) || (supportLegacyTypes == AllowLegacyTypeInTypeAttribute && isLegacySupportedJavaScriptLanguage(type))) {
+    } else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(type.stripWhiteSpace()) || (supportLegacyTypes == AllowLegacyTypeInTypeAttribute && isLegacySupportedJavaScriptLanguage(type))) {
         return true;
     }
 
@@ -241,8 +240,7 @@
         // Reset line numbering for nested writes.
         TextPosition position = elementDocument.isInDocumentWrite() ? TextPosition() : scriptStartPosition;
         KURL scriptURL = (!elementDocument.isInDocumentWrite() && m_parserInserted) ? elementDocument.url() : KURL();
-        if (!executePotentiallyCrossOriginScript(ScriptSourceCode(scriptContent(), scriptURL, position)))
-            return false;
+        executeScript(ScriptSourceCode(scriptContent(), scriptURL, position));
     }
 
     return true;
@@ -262,12 +260,9 @@
     if (!stripLeadingAndTrailingHTMLSpaces(sourceUrl).isEmpty()) {
         FetchRequest request(ResourceRequest(elementDocument->completeURL(sourceUrl)), m_element->localName());
 
-        String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
-        if (!crossOriginMode.isNull()) {
-            StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
-            request.setCrossOriginAccessControl(elementDocument->securityOrigin(), allowCredentials);
-            m_isPotentiallyCORSEnabled = true;
-        }
+        AtomicString crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
+        if (!crossOriginMode.isNull())
+            request.setCrossOriginAccessControl(elementDocument->securityOrigin(), crossOriginMode);
         request.setCharset(scriptCharset());
 
         bool isValidScriptNonce = elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr));
@@ -363,18 +358,6 @@
     resource->removeClient(this);
 }
 
-bool ScriptLoader::executePotentiallyCrossOriginScript(const ScriptSourceCode& sourceCode)
-{
-    if (sourceCode.resource()
-        && isPotentiallyCORSEnabled()
-        && !m_element->document().fetcher()->canAccess(sourceCode.resource(), PotentiallyCORSEnabled)) {
-        dispatchErrorEvent();
-        return false;
-    }
-    executeScript(sourceCode);
-    return true;
-}
-
 void ScriptLoader::notifyFinished(Resource* resource)
 {
     ASSERT(!m_willBeParserExecuted);
@@ -391,13 +374,11 @@
     ASSERT_UNUSED(resource, resource == m_resource);
     if (!m_resource)
         return;
-    CORSEnabled corsEnabled = isPotentiallyCORSEnabled() ? PotentiallyCORSEnabled : NotCORSEnabled;
-    if (!elementDocument->fetcher()->canAccess(m_resource.get(), corsEnabled)) {
+    if (m_resource->errorOccurred()) {
         dispatchErrorEvent();
         contextDocument->scriptRunner()->notifyScriptLoadError(this, m_willExecuteInOrder ? ScriptRunner::IN_ORDER_EXECUTION : ScriptRunner::ASYNC_EXECUTION);
         return;
     }
-
     if (m_willExecuteInOrder)
         contextDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::IN_ORDER_EXECUTION);
     else
diff --git a/Source/core/dom/ScriptLoader.h b/Source/core/dom/ScriptLoader.h
index 72f5197..83acaec 100644
--- a/Source/core/dom/ScriptLoader.h
+++ b/Source/core/dom/ScriptLoader.h
@@ -35,7 +35,7 @@
 class ScriptSourceCode;
 
 
-class ScriptLoader : private ResourceClient {
+class ScriptLoader FINAL : private ResourceClient {
 public:
     static PassOwnPtr<ScriptLoader> create(Element*, bool createdByParser, bool isEvaluated);
     virtual ~ScriptLoader();
@@ -50,12 +50,6 @@
     void executeScript(const ScriptSourceCode&);
     void execute(ScriptResource*);
 
-    // Check if potentially cross-origin enabled script is accessible
-    // prior to execution. Returns 'false' if not accessible, signalling
-    // that callers must not dispatch load events as the cross-origin
-    // fetch failed.
-    bool executePotentiallyCrossOriginScript(const ScriptSourceCode&);
-
     // XML parser calls these
     void dispatchLoadEvent();
     void dispatchErrorEvent();
@@ -71,7 +65,6 @@
     bool isParserInserted() const { return m_parserInserted; }
     bool alreadyStarted() const { return m_alreadyStarted; }
     bool forceAsync() const { return m_forceAsync; }
-    bool isPotentiallyCORSEnabled() const { return m_isPotentiallyCORSEnabled; }
 
     // Helper functions used by our parent classes.
     void didNotifySubtreeInsertionsToDocument();
@@ -105,7 +98,6 @@
     bool m_willExecuteWhenDocumentFinishedParsing : 1;
     bool m_forceAsync : 1;
     bool m_willExecuteInOrder : 1;
-    bool m_isPotentiallyCORSEnabled : 1;
     String m_characterEncoding;
     String m_fallbackCharacterEncoding;
 };
diff --git a/Source/core/dom/ScriptableDocumentParser.cpp b/Source/core/dom/ScriptableDocumentParser.cpp
index 504e6f3..5e8f2f3 100644
--- a/Source/core/dom/ScriptableDocumentParser.cpp
+++ b/Source/core/dom/ScriptableDocumentParser.cpp
@@ -27,7 +27,7 @@
 #include "core/dom/ScriptableDocumentParser.h"
 
 #include "core/dom/Document.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ScriptableDocumentParser.h b/Source/core/dom/ScriptableDocumentParser.h
index 18a2f93..5cb8a50 100644
--- a/Source/core/dom/ScriptableDocumentParser.h
+++ b/Source/core/dom/ScriptableDocumentParser.h
@@ -57,7 +57,7 @@
     explicit ScriptableDocumentParser(Document*, ParserContentPolicy = AllowScriptingContent);
 
 private:
-    virtual ScriptableDocumentParser* asScriptableDocumentParser() { return this; }
+    virtual ScriptableDocumentParser* asScriptableDocumentParser() OVERRIDE FINAL { return this; }
 
     // http://www.whatwg.org/specs/web-apps/current-work/#script-created-parser
     bool m_wasCreatedByScript;
diff --git a/Source/core/dom/SelectorQuery.cpp b/Source/core/dom/SelectorQuery.cpp
index 5fcf2ac..e43511f 100644
--- a/Source/core/dom/SelectorQuery.cpp
+++ b/Source/core/dom/SelectorQuery.cpp
@@ -1,5 +1,6 @@
 /*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2011, 2013 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -27,7 +28,7 @@
 #include "core/dom/SelectorQuery.h"
 
 #include "bindings/v8/ExceptionState.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/SelectorChecker.h"
 #include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/SiblingTraversalStrategies.h"
@@ -38,76 +39,45 @@
 
 namespace WebCore {
 
-class SimpleNodeList {
-public:
-    virtual ~SimpleNodeList() { }
-    virtual bool isEmpty() const = 0;
-    virtual Node* next() = 0;
+struct SingleElementSelectorQueryTrait {
+    typedef Element* OutputType;
+    static const bool shouldOnlyMatchFirstElement = true;
+    ALWAYS_INLINE static void appendElement(OutputType& output, Element& element)
+    {
+        ASSERT(!output);
+        output = &element;
+    }
 };
 
-class SingleNodeList : public SimpleNodeList {
-public:
-    explicit SingleNodeList(Node* rootNode) : m_currentNode(rootNode) { }
-
-    bool isEmpty() const { return !m_currentNode; }
-
-    Node* next()
+struct AllElementsSelectorQueryTrait {
+    typedef Vector<RefPtr<Node> > OutputType;
+    static const bool shouldOnlyMatchFirstElement = false;
+    ALWAYS_INLINE static void appendElement(OutputType& output, Node& element)
     {
-        Node* current = m_currentNode;
-        m_currentNode = 0;
-        return current;
+        output.append(RefPtr<Node>(element));
     }
-
-private:
-    Node* m_currentNode;
 };
 
-class ClassRootNodeList : public SimpleNodeList {
+enum ClassElementListBehavior { AllElements, OnlyRoots };
+
+template <ClassElementListBehavior onlyRoots>
+class ClassElementList {
 public:
-    ClassRootNodeList(Node& rootNode, const AtomicString& className)
-        : m_className(className)
-        , m_rootNode(rootNode)
-        , m_currentElement(nextInternal(ElementTraversal::firstWithin(m_rootNode))) { }
-
-    bool isEmpty() const { return !m_currentElement; }
-
-    Node* next()
-    {
-        Node* current = m_currentElement;
-        ASSERT(current);
-        m_currentElement = nextInternal(ElementTraversal::nextSkippingChildren(*m_currentElement, &m_rootNode));
-        return current;
-    }
-
-private:
-    Element* nextInternal(Element* element)
-    {
-        for (; element; element = ElementTraversal::next(*element, &m_rootNode)) {
-            if (element->hasClass() && element->classNames().contains(m_className))
-                return element;
-        }
-        return 0;
-    }
-
-    const AtomicString& m_className;
-    Node& m_rootNode;
-    Element* m_currentElement;
-};
-
-class ClassElementList : public SimpleNodeList {
-public:
-    ClassElementList(Node& rootNode, const AtomicString& className)
+    ClassElementList(ContainerNode& rootNode, const AtomicString& className)
         : m_className(className)
         , m_rootNode(rootNode)
         , m_currentElement(nextInternal(ElementTraversal::firstWithin(rootNode))) { }
 
     bool isEmpty() const { return !m_currentElement; }
 
-    Node* next()
+    Element* next()
     {
-        Node* current = m_currentElement;
+        Element* current = m_currentElement;
         ASSERT(current);
-        m_currentElement = nextInternal(ElementTraversal::next(*m_currentElement, &m_rootNode));
+        if (onlyRoots)
+            m_currentElement = nextInternal(ElementTraversal::nextSkippingChildren(*m_currentElement, &m_rootNode));
+        else
+            m_currentElement = nextInternal(ElementTraversal::next(*m_currentElement, &m_rootNode));
         return current;
     }
 
@@ -122,7 +92,7 @@
     }
 
     const AtomicString& m_className;
-    Node& m_rootNode;
+    ContainerNode& m_rootNode;
     Element* m_currentElement;
 };
 
@@ -131,15 +101,15 @@
     ASSERT(m_selectors.isEmpty());
 
     unsigned selectorCount = 0;
-    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector))
+    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(*selector))
         selectorCount++;
 
     m_selectors.reserveInitialCapacity(selectorCount);
-    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector))
-        m_selectors.uncheckedAppend(SelectorData(selector, SelectorCheckerFastPath::canUse(selector)));
+    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(*selector))
+        m_selectors.uncheckedAppend(SelectorData(*selector, SelectorCheckerFastPath::canUse(*selector)));
 }
 
-inline bool SelectorDataList::selectorMatches(const SelectorData& selectorData, Element& element, const Node& rootNode) const
+inline bool SelectorDataList::selectorMatches(const SelectorData& selectorData, Element& element, const ContainerNode& rootNode) const
 {
     if (selectorData.isFastCheckable && !element.isSVGElement()) {
         SelectorCheckerFastPath selectorCheckerFastPath(selectorData.selector, element);
@@ -151,7 +121,7 @@
     SelectorChecker selectorChecker(element.document(), SelectorChecker::QueryingRules);
     SelectorChecker::SelectorCheckingContext selectorCheckingContext(selectorData.selector, &element, SelectorChecker::VisitedMatchDisabled);
     selectorCheckingContext.behaviorAtBoundary = SelectorChecker::StaysWithinTreeScope;
-    selectorCheckingContext.scope = !rootNode.isDocumentNode() && rootNode.isContainerNode() ? &toContainerNode(rootNode) : 0;
+    selectorCheckingContext.scope = !rootNode.isDocumentNode() ? &rootNode : 0;
     return selectorChecker.match(selectorCheckingContext, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches;
 }
 
@@ -166,58 +136,50 @@
     return false;
 }
 
-PassRefPtr<NodeList> SelectorDataList::queryAll(Node& rootNode) const
+PassRefPtr<NodeList> SelectorDataList::queryAll(ContainerNode& rootNode) const
 {
     Vector<RefPtr<Node> > result;
-    executeQueryAll(rootNode, result);
+    execute<AllElementsSelectorQueryTrait>(rootNode, result);
     return StaticNodeList::adopt(result);
 }
 
-PassRefPtr<Element> SelectorDataList::queryFirst(Node& rootNode) const
+PassRefPtr<Element> SelectorDataList::queryFirst(ContainerNode& rootNode) const
 {
-    return executeQueryFirst(rootNode);
+    Element* matchedElement = 0;
+    execute<SingleElementSelectorQueryTrait>(rootNode, matchedElement);
+    return matchedElement;
 }
 
-void SelectorDataList::collectElementsByClassName(Node& rootNode, const AtomicString& className, Vector<RefPtr<Node> >& traversalRoots) const
+template <typename SelectorQueryTrait>
+void SelectorDataList::collectElementsByClassName(ContainerNode& rootNode, const AtomicString& className,  typename SelectorQueryTrait::OutputType& output) const
 {
     for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
-        if (element->hasClass() && element->classNames().contains(className))
-            traversalRoots.append(element);
+        if (element->hasClass() && element->classNames().contains(className)) {
+            SelectorQueryTrait::appendElement(output, *element);
+            if (SelectorQueryTrait::shouldOnlyMatchFirstElement)
+                return;
+        }
     }
 }
 
-void SelectorDataList::collectElementsByTagName(Node& rootNode, const QualifiedName& tagName, Vector<RefPtr<Node> >& traversalRoots) const
+template <typename SelectorQueryTrait>
+void SelectorDataList::collectElementsByTagName(ContainerNode& rootNode, const QualifiedName& tagName,  typename SelectorQueryTrait::OutputType& output) const
 {
     for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
-        if (SelectorChecker::tagMatches(*element, tagName))
-            traversalRoots.append(element);
+        if (SelectorChecker::tagMatches(*element, tagName)) {
+            SelectorQueryTrait::appendElement(output, *element);
+            if (SelectorQueryTrait::shouldOnlyMatchFirstElement)
+                return;
+        }
     }
 }
 
-Element* SelectorDataList::findElementByClassName(Node& rootNode, const AtomicString& className) const
-{
-    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
-        if (element->hasClass() && element->classNames().contains(className))
-            return element;
-    }
-    return 0;
-}
-
-Element* SelectorDataList::findElementByTagName(Node& rootNode, const QualifiedName& tagName) const
-{
-    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
-        if (SelectorChecker::tagMatches(*element, tagName))
-            return element;
-    }
-    return 0;
-}
-
-inline bool SelectorDataList::canUseFastQuery(const Node& rootNode) const
+inline bool SelectorDataList::canUseFastQuery(const ContainerNode& rootNode) const
 {
     return m_selectors.size() == 1 && rootNode.inDocument() && !rootNode.document().inQuirksMode();
 }
 
-inline bool ancestorHasClassName(Node& rootNode, const AtomicString& className)
+inline bool ancestorHasClassName(ContainerNode& rootNode, const AtomicString& className)
 {
     if (!rootNode.isElementNode())
         return false;
@@ -237,48 +199,53 @@
 //
 // The travseralRoots may be empty, regardless of the returned bool value, if this method finds that the selectors won't
 // match any element.
-PassOwnPtr<SimpleNodeList> SelectorDataList::findTraverseRoots(Node& rootNode, bool& matchTraverseRoots) const
+template <typename SelectorQueryTrait>
+void SelectorDataList::findTraverseRootsAndExecute(ContainerNode& rootNode, typename SelectorQueryTrait::OutputType& output) const
 {
     // We need to return the matches in document order. To use id lookup while there is possiblity of multiple matches
     // we would need to sort the results. For now, just traverse the document in that case.
     ASSERT(m_selectors.size() == 1);
-    ASSERT(m_selectors[0].selector);
 
     bool isRightmostSelector = true;
     bool startFromParent = false;
 
-    for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) {
+    for (const CSSSelector* selector = &m_selectors[0].selector; selector; selector = selector->tagHistory()) {
         if (selector->m_match == CSSSelector::Id && !rootNode.document().containsMultipleElementsWithId(selector->value())) {
             Element* element = rootNode.treeScope().getElementById(selector->value());
-            Node* adjustedNode = &rootNode;
+            ContainerNode* adjustedNode = &rootNode;
             if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)))
                 adjustedNode = element;
             else if (!element || isRightmostSelector)
                 adjustedNode = 0;
             if (isRightmostSelector) {
-                matchTraverseRoots = true;
-                return adoptPtr(new SingleNodeList(adjustedNode));
+                executeForTraverseRoot<SelectorQueryTrait>(m_selectors[0], adjustedNode, MatchesTraverseRoots, rootNode, output);
+                return;
             }
+
             if (startFromParent && adjustedNode)
                 adjustedNode = adjustedNode->parentNode();
 
-            matchTraverseRoots = false;
-            return adoptPtr(new SingleNodeList(adjustedNode));
+            executeForTraverseRoot<SelectorQueryTrait>(m_selectors[0], adjustedNode, DoesNotMatchTraverseRoots, rootNode, output);
+            return;
         }
 
         // If we have both CSSSelector::Id and CSSSelector::Class at the same time, we should use Id
         // to find traverse root.
-        if (!startFromParent && selector->m_match == CSSSelector::Class) {
+        if (!SelectorQueryTrait::shouldOnlyMatchFirstElement && !startFromParent && selector->m_match == CSSSelector::Class) {
             if (isRightmostSelector) {
-                matchTraverseRoots = true;
-                return adoptPtr(new ClassElementList(rootNode, selector->value()));
+                ClassElementList<AllElements> traverseRoots(rootNode, selector->value());
+                executeForTraverseRoots<SelectorQueryTrait>(m_selectors[0], traverseRoots, MatchesTraverseRoots, rootNode, output);
+                return;
             }
-            matchTraverseRoots = false;
             // Since there exists some ancestor element which has the class name, we need to see all children of rootNode.
-            if (ancestorHasClassName(rootNode, selector->value()))
-                return adoptPtr(new SingleNodeList(&rootNode));
+            if (ancestorHasClassName(rootNode, selector->value())) {
+                executeForTraverseRoot<SelectorQueryTrait>(m_selectors[0], &rootNode, DoesNotMatchTraverseRoots, rootNode, output);
+                return;
+            }
 
-            return adoptPtr(new ClassRootNodeList(rootNode, selector->value()));
+            ClassElementList<OnlyRoots> traverseRoots(rootNode, selector->value());
+            executeForTraverseRoots<SelectorQueryTrait>(m_selectors[0], traverseRoots, DoesNotMatchTraverseRoots, rootNode, output);
+            return;
         }
 
         if (selector->relation() == CSSSelector::SubSelector)
@@ -290,182 +257,140 @@
             startFromParent = false;
     }
 
-    matchTraverseRoots = false;
-    return adoptPtr(new SingleNodeList(&rootNode));
+    executeForTraverseRoot<SelectorQueryTrait>(m_selectors[0], &rootNode, DoesNotMatchTraverseRoots, rootNode, output);
 }
 
-void SelectorDataList::executeSlowQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const
+template <typename SelectorQueryTrait>
+void SelectorDataList::executeForTraverseRoot(const SelectorData& selector, ContainerNode* traverseRoot, MatchTraverseRootState matchTraverseRoot, ContainerNode& rootNode, typename SelectorQueryTrait::OutputType& output) const
+{
+    if (!traverseRoot)
+        return;
+
+    if (matchTraverseRoot) {
+        if (selectorMatches(selector, toElement(*traverseRoot), rootNode))
+            SelectorQueryTrait::appendElement(output, toElement(*traverseRoot));
+        return;
+    }
+
+    for (Element* element = ElementTraversal::firstWithin(*traverseRoot); element; element = ElementTraversal::next(*element, traverseRoot)) {
+        if (selectorMatches(selector, *element, rootNode)) {
+            SelectorQueryTrait::appendElement(output, *element);
+            if (SelectorQueryTrait::shouldOnlyMatchFirstElement)
+                return;
+        }
+    }
+}
+
+template <typename SelectorQueryTrait, typename SimpleElementListType>
+void SelectorDataList::executeForTraverseRoots(const SelectorData& selector, SimpleElementListType& traverseRoots, MatchTraverseRootState matchTraverseRoots, ContainerNode& rootNode, typename SelectorQueryTrait::OutputType& output) const
+{
+    if (traverseRoots.isEmpty())
+        return;
+
+    if (matchTraverseRoots) {
+        while (!traverseRoots.isEmpty()) {
+            Element& element = *traverseRoots.next();
+            if (selectorMatches(selector, element, rootNode)) {
+                SelectorQueryTrait::appendElement(output, element);
+                if (SelectorQueryTrait::shouldOnlyMatchFirstElement)
+                    return;
+            }
+        }
+        return;
+    }
+
+    while (!traverseRoots.isEmpty()) {
+        Element& traverseRoot = *traverseRoots.next();
+        for (Element* element = ElementTraversal::firstWithin(traverseRoot); element; element = ElementTraversal::next(*element, &traverseRoot)) {
+            if (selectorMatches(selector, *element, rootNode)) {
+                SelectorQueryTrait::appendElement(output, *element);
+                if (SelectorQueryTrait::shouldOnlyMatchFirstElement)
+                    return;
+            }
+        }
+    }
+}
+
+template <typename SelectorQueryTrait>
+void SelectorDataList::executeSlow(ContainerNode& rootNode, typename SelectorQueryTrait::OutputType& output) const
 {
     for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
         for (unsigned i = 0; i < m_selectors.size(); ++i) {
             if (selectorMatches(m_selectors[i], *element, rootNode)) {
-                matchedElements.append(element);
+                SelectorQueryTrait::appendElement(output, *element);
+                if (SelectorQueryTrait::shouldOnlyMatchFirstElement)
+                    return;
                 break;
             }
         }
     }
 }
 
-void SelectorDataList::executeQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const
+const CSSSelector* SelectorDataList::selectorForIdLookup(const CSSSelector& firstSelector) const
 {
-    if (!canUseFastQuery(rootNode))
-        return executeSlowQueryAll(rootNode, matchedElements);
+    for (const CSSSelector* selector = &firstSelector; selector; selector = selector->tagHistory()) {
+        if (selector->m_match == CSSSelector::Id)
+            return selector;
+        if (selector->relation() != CSSSelector::SubSelector)
+            break;
+    }
+    return 0;
+}
 
-    ASSERT(m_selectors.size() == 1);
-    ASSERT(m_selectors[0].selector);
-
-    const CSSSelector* firstSelector = m_selectors[0].selector;
-
-    if (!firstSelector->tagHistory()) {
-        // Fast path for querySelectorAll('#id'), querySelectorAl('.foo'), and querySelectorAll('div').
-        switch (firstSelector->m_match) {
-        case CSSSelector::Id:
-            {
-                if (rootNode.document().containsMultipleElementsWithId(firstSelector->value()))
-                    break;
-
-                // Just the same as getElementById.
-                Element* element = rootNode.treeScope().getElementById(firstSelector->value());
-                if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)))
-                    matchedElements.append(element);
-                return;
-            }
-        case CSSSelector::Class:
-            return collectElementsByClassName(rootNode, firstSelector->value(), matchedElements);
-        case CSSSelector::Tag:
-            return collectElementsByTagName(rootNode, firstSelector->tagQName(), matchedElements);
-        default:
-            break; // If we need another fast path, add here.
-        }
+template <typename SelectorQueryTrait>
+void SelectorDataList::execute(ContainerNode& rootNode, typename SelectorQueryTrait::OutputType& output) const
+{
+    if (!canUseFastQuery(rootNode)) {
+        executeSlow<SelectorQueryTrait>(rootNode, output);
+        return;
     }
 
-    bool matchTraverseRoots;
-    OwnPtr<SimpleNodeList> traverseRoots = findTraverseRoots(rootNode, matchTraverseRoots);
-    if (traverseRoots->isEmpty())
-        return;
+    ASSERT(m_selectors.size() == 1);
 
     const SelectorData& selector = m_selectors[0];
-    if (matchTraverseRoots) {
-        while (!traverseRoots->isEmpty()) {
-            Node& node = *traverseRoots->next();
-            Element& element = toElement(node);
-            if (selectorMatches(selector, element, rootNode))
-                matchedElements.append(&element);
+    const CSSSelector& firstSelector = selector.selector;
+
+    // Fast path for querySelector*('#id'), querySelector*('tag#id').
+    if (const CSSSelector* idSelector = selectorForIdLookup(firstSelector)) {
+        const AtomicString& idToMatch = idSelector->value();
+        if (rootNode.treeScope().containsMultipleElementsWithId(idToMatch)) {
+            const Vector<Element*>& elements = rootNode.treeScope().getAllElementsById(idToMatch);
+            size_t count = elements.size();
+            for (size_t i = 0; i < count; ++i) {
+                Element& element = *elements[i];
+                if (!(isTreeScopeRoot(rootNode) || element.isDescendantOf(&rootNode)))
+                    continue;
+                if (selectorMatches(selector, element, rootNode)) {
+                    SelectorQueryTrait::appendElement(output, element);
+                    if (SelectorQueryTrait::shouldOnlyMatchFirstElement)
+                        return;
+                }
+            }
+            return;
         }
+        Element* element = rootNode.treeScope().getElementById(idToMatch);
+        if (!element || !(isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)))
+            return;
+        if (selectorMatches(selector, *element, rootNode))
+            SelectorQueryTrait::appendElement(output, *element);
         return;
     }
 
-    while (!traverseRoots->isEmpty()) {
-        Node* traverseRoot = traverseRoots->next();
-        ASSERT(traverseRoot);
-        for (Element* element = ElementTraversal::firstWithin(*traverseRoot); element; element = ElementTraversal::next(*element, traverseRoot)) {
-            if (selectorMatches(selector, *element, rootNode))
-                matchedElements.append(element);
-        }
-    }
-}
-
-// If matchTraverseRoot is true, the returned Node is the single Element that may match the selector query.
-//
-// If matchTraverseRoot is false, the returned Node is the rootNode parameter or a descendant of rootNode representing
-// the subtree for which we can limit the querySelector traversal.
-//
-// The returned Node may be 0, regardless of matchTraverseRoot, if this method finds that the selectors won't
-// match any element.
-Node* SelectorDataList::findTraverseRoot(Node& rootNode, bool& matchTraverseRoot) const
-{
-    // We need to return the matches in document order. To use id lookup while there is possiblity of multiple matches
-    // we would need to sort the results. For now, just traverse the document in that case.
-    ASSERT(m_selectors.size() == 1);
-    ASSERT(m_selectors[0].selector);
-
-    bool matchSingleNode = true;
-    bool startFromParent = false;
-    for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) {
-        if (selector->m_match == CSSSelector::Id && !rootNode.document().containsMultipleElementsWithId(selector->value())) {
-            Element* element = rootNode.treeScope().getElementById(selector->value());
-            Node* adjustedRootNode = &rootNode;
-            if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)))
-                adjustedRootNode = element;
-            else if (!element || matchSingleNode)
-                adjustedRootNode = 0;
-            if (matchSingleNode) {
-                matchTraverseRoot = true;
-                return adjustedRootNode;
-            }
-            if (startFromParent && adjustedRootNode)
-                adjustedRootNode = adjustedRootNode->parentNode();
-            matchTraverseRoot = false;
-            return adjustedRootNode;
-        }
-        if (selector->relation() == CSSSelector::SubSelector)
-            continue;
-        matchSingleNode = false;
-        if (selector->relation() == CSSSelector::DirectAdjacent || selector->relation() == CSSSelector::IndirectAdjacent)
-            startFromParent = true;
-        else
-            startFromParent = false;
-    }
-    matchTraverseRoot = false;
-    return &rootNode;
-}
-
-Element* SelectorDataList::executeSlowQueryFirst(Node& rootNode) const
-{
-    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
-        for (unsigned i = 0; i < m_selectors.size(); ++i) {
-            if (selectorMatches(m_selectors[i], *element, rootNode))
-                return element;
-        }
-    }
-    return 0;
-}
-
-Element* SelectorDataList::executeQueryFirst(Node& rootNode) const
-{
-    if (!canUseFastQuery(rootNode))
-        return executeSlowQueryFirst(rootNode);
-
-
-    const CSSSelector* selector = m_selectors[0].selector;
-    ASSERT(selector);
-
-    if (!selector->tagHistory()) {
-        // Fast path for querySelector('#id'), querySelector('.foo'), and querySelector('div').
-        // Many web developers uses querySelector with these simple selectors.
-        switch (selector->m_match) {
-        case CSSSelector::Id:
-            {
-                if (rootNode.document().containsMultipleElementsWithId(selector->value()))
-                    break;
-                Element* element = rootNode.treeScope().getElementById(selector->value());
-                return element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)) ? element : 0;
-            }
+    if (!firstSelector.tagHistory()) {
+        // Fast path for querySelector*('.foo'), and querySelector*('div').
+        switch (firstSelector.m_match) {
         case CSSSelector::Class:
-            return findElementByClassName(rootNode, selector->value());
+            collectElementsByClassName<SelectorQueryTrait>(rootNode, firstSelector.value(), output);
+            return;
         case CSSSelector::Tag:
-            return findElementByTagName(rootNode, selector->tagQName());
+            collectElementsByTagName<SelectorQueryTrait>(rootNode, firstSelector.tagQName(), output);
+            return;
         default:
             break; // If we need another fast path, add here.
         }
     }
 
-    bool matchTraverseRoot;
-    Node* traverseRootNode = findTraverseRoot(rootNode, matchTraverseRoot);
-    if (!traverseRootNode)
-        return 0;
-    if (matchTraverseRoot) {
-        ASSERT(m_selectors.size() == 1);
-        ASSERT(traverseRootNode->isElementNode());
-        Element& element = toElement(*traverseRootNode);
-        return selectorMatches(m_selectors[0], element, rootNode) ? &element : 0;
-    }
-
-    for (Element* element = ElementTraversal::firstWithin(*traverseRootNode); element; element = ElementTraversal::next(*element, traverseRootNode)) {
-        if (selectorMatches(m_selectors[0], *element, rootNode))
-            return element;
-    }
-    return 0;
+    findTraverseRootsAndExecute<SelectorQueryTrait>(rootNode, output);
 }
 
 SelectorQuery::SelectorQuery(const CSSSelectorList& selectorList)
@@ -479,12 +404,12 @@
     return m_selectors.matches(element);
 }
 
-PassRefPtr<NodeList> SelectorQuery::queryAll(Node& rootNode) const
+PassRefPtr<NodeList> SelectorQuery::queryAll(ContainerNode& rootNode) const
 {
     return m_selectors.queryAll(rootNode);
 }
 
-PassRefPtr<Element> SelectorQuery::queryFirst(Node& rootNode) const
+PassRefPtr<Element> SelectorQuery::queryFirst(ContainerNode& rootNode) const
 {
     return m_selectors.queryFirst(rootNode);
 }
@@ -495,7 +420,7 @@
     if (it != m_entries.end())
         return it->value.get();
 
-    CSSParser parser(document);
+    BisonCSSParser parser(CSSParserContext(document, 0));
     CSSSelectorList selectorList;
     parser.parseSelector(selectors, selectorList);
 
diff --git a/Source/core/dom/SelectorQuery.h b/Source/core/dom/SelectorQuery.h
index fb787ab..c413f3a 100644
--- a/Source/core/dom/SelectorQuery.h
+++ b/Source/core/dom/SelectorQuery.h
@@ -1,5 +1,6 @@
 /*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2011, 2013 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -34,6 +35,7 @@
 namespace WebCore {
 
 class CSSSelector;
+class ContainerNode;
 class Document;
 class Element;
 class ExceptionState;
@@ -46,28 +48,38 @@
 public:
     void initialize(const CSSSelectorList&);
     bool matches(Element&) const;
-    PassRefPtr<NodeList> queryAll(Node& rootNode) const;
-    PassRefPtr<Element> queryFirst(Node& rootNode) const;
+    PassRefPtr<NodeList> queryAll(ContainerNode& rootNode) const;
+    PassRefPtr<Element> queryFirst(ContainerNode& rootNode) const;
 
 private:
     struct SelectorData {
-        SelectorData(const CSSSelector* selector, bool isFastCheckable) : selector(selector), isFastCheckable(isFastCheckable) { }
-        const CSSSelector* selector;
+        SelectorData(const CSSSelector& selector, bool isFastCheckable) : selector(selector), isFastCheckable(isFastCheckable) { }
+        const CSSSelector& selector;
         bool isFastCheckable;
     };
 
-    bool canUseFastQuery(const Node& rootNode) const;
-    bool selectorMatches(const SelectorData&, Element&, const Node&) const;
-    void collectElementsByClassName(Node& rootNode, const AtomicString& className, Vector<RefPtr<Node> >&) const;
-    Element* findElementByClassName(Node& rootNode, const AtomicString& className) const;
-    void collectElementsByTagName(Node& rootNode, const QualifiedName& tagName, Vector<RefPtr<Node> >&) const;
-    Element* findElementByTagName(Node& rootNode, const QualifiedName& tagName) const;
-    PassOwnPtr<SimpleNodeList> findTraverseRoots(Node& rootNode, bool& matchTraverseRoots) const;
-    void executeSlowQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const;
-    void executeQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const;
-    Node* findTraverseRoot(Node& rootNode, bool& matchTraverseRoot) const;
-    Element* executeSlowQueryFirst(Node& rootNode) const;
-    Element* executeQueryFirst(Node& rootNode) const;
+    bool canUseFastQuery(const ContainerNode& rootNode) const;
+    bool selectorMatches(const SelectorData&, Element&, const ContainerNode&) const;
+
+    template <typename SelectorQueryTrait>
+    void collectElementsByClassName(ContainerNode& rootNode, const AtomicString& className, typename SelectorQueryTrait::OutputType&) const;
+    template <typename SelectorQueryTrait>
+    void collectElementsByTagName(ContainerNode& rootNode, const QualifiedName& tagName, typename SelectorQueryTrait::OutputType&) const;
+
+    template <typename SelectorQueryTrait>
+    void findTraverseRootsAndExecute(ContainerNode& rootNode, typename SelectorQueryTrait::OutputType&) const;
+
+    enum MatchTraverseRootState { DoesNotMatchTraverseRoots, MatchesTraverseRoots };
+    template <typename SelectorQueryTrait>
+    void executeForTraverseRoot(const SelectorData&, ContainerNode* traverseRoot, MatchTraverseRootState, ContainerNode& rootNode, typename SelectorQueryTrait::OutputType&) const;
+    template <typename SelectorQueryTrait, typename SimpleElementListType>
+    void executeForTraverseRoots(const SelectorData&, SimpleElementListType& traverseRoots, MatchTraverseRootState, ContainerNode& rootNode, typename SelectorQueryTrait::OutputType&) const;
+
+    template <typename SelectorQueryTrait>
+    void executeSlow(ContainerNode& rootNode, typename SelectorQueryTrait::OutputType&) const;
+    template <typename SelectorQueryTrait>
+    void execute(ContainerNode& rootNode, typename SelectorQueryTrait::OutputType&) const;
+    const CSSSelector* selectorForIdLookup(const CSSSelector&) const;
 
     Vector<SelectorData> m_selectors;
 };
@@ -78,8 +90,8 @@
 public:
     explicit SelectorQuery(const CSSSelectorList&);
     bool matches(Element&) const;
-    PassRefPtr<NodeList> queryAll(Node& rootNode) const;
-    PassRefPtr<Element> queryFirst(Node& rootNode) const;
+    PassRefPtr<NodeList> queryAll(ContainerNode& rootNode) const;
+    PassRefPtr<Element> queryFirst(ContainerNode& rootNode) const;
 private:
     SelectorDataList m_selectors;
     CSSSelectorList m_selectorList;
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
index f682a4f..6a74608 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
@@ -34,18 +34,17 @@
 #include "core/dom/StyleEngine.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLStyleElement.h"
-#include "core/page/Settings.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
 ShadowTreeStyleSheetCollection::ShadowTreeStyleSheetCollection(ShadowRoot& shadowRoot)
-    : StyleSheetCollection(shadowRoot)
+    : TreeScopeStyleSheetCollection(shadowRoot)
 {
 }
 
-void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleEngine* engine, StyleSheetCollectionBase& collection)
+void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleEngine* engine, StyleSheetCollection& collection)
 {
     DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin();
     DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end();
@@ -58,7 +57,7 @@
             continue;
 
         Element* element = toElement(node);
-        AtomicString title = element->getAttribute(titleAttr);
+        const AtomicString& title = element->fastGetAttribute(titleAttr);
         bool enabledViaScript = false;
 
         sheet = toHTMLStyleElement(node)->sheet();
@@ -68,7 +67,7 @@
         // FIXME: clarify how PREFERRED or ALTERNATE works in shadow trees.
         // Should we set preferred/selected stylesheets name in shadow trees and
         // use the name in document?
-        AtomicString rel = element->getAttribute(relAttr);
+        const AtomicString& rel = element->fastGetAttribute(relAttr);
         if (!enabledViaScript && sheet && !title.isEmpty()) {
             if (engine->preferredStylesheetSetName().isEmpty()) {
                 if (element->hasLocalName(styleTag) || !rel.contains("alternate")) {
@@ -92,7 +91,7 @@
 
 bool ShadowTreeStyleSheetCollection::updateActiveStyleSheets(StyleEngine* engine, StyleResolverUpdateMode updateMode)
 {
-    StyleSheetCollectionBase collection;
+    StyleSheetCollection collection;
     collectStyleSheets(engine, collection);
 
     StyleSheetChange change;
@@ -113,7 +112,7 @@
         }
     }
     if (change.requiresFullStyleRecalc)
-        toShadowRoot(m_treeScope.rootNode())->host()->setNeedsStyleRecalc();
+        toShadowRoot(m_treeScope.rootNode()).host()->setNeedsStyleRecalc(SubtreeStyleChange);
 
     m_scopingNodesForStyleScoped.didRemoveScopingNodes();
     collection.swap(*this);
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.h b/Source/core/dom/ShadowTreeStyleSheetCollection.h
index b7c13cb..25323d4 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.h
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.h
@@ -28,7 +28,7 @@
 #ifndef ShadowTreeStyleSheetCollection_h
 #define ShadowTreeStyleSheetCollection_h
 
-#include "core/dom/StyleSheetCollection.h"
+#include "core/dom/TreeScopeStyleSheetCollection.h"
 
 namespace WebCore {
 
@@ -38,7 +38,7 @@
 class StyleSheetCollection;
 class StyleEngine;
 
-class ShadowTreeStyleSheetCollection FINAL : public StyleSheetCollection {
+class ShadowTreeStyleSheetCollection FINAL : public TreeScopeStyleSheetCollection {
     WTF_MAKE_NONCOPYABLE(ShadowTreeStyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit ShadowTreeStyleSheetCollection(ShadowRoot&);
@@ -46,7 +46,7 @@
     bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
 
 private:
-    void collectStyleSheets(StyleEngine*, StyleSheetCollectionBase&);
+    void collectStyleSheets(StyleEngine*, StyleSheetCollection&);
 };
 
 }
diff --git a/Source/core/dom/SpaceSplitString.cpp b/Source/core/dom/SpaceSplitString.cpp
index 63c3da1..4bec8c0 100644
--- a/Source/core/dom/SpaceSplitString.cpp
+++ b/Source/core/dom/SpaceSplitString.cpp
@@ -164,7 +164,7 @@
     if (shouldFoldCase && hasNonASCIIOrUpper(string))
         string = string.foldCase();
 
-    m_data = SpaceSplitStringData::create(string);
+    m_data = SpaceSplitStringData::create(AtomicString(string));
 }
 
 SpaceSplitStringData::~SpaceSplitStringData()
@@ -175,7 +175,7 @@
 
 PassRefPtr<SpaceSplitStringData> SpaceSplitStringData::create(const AtomicString& string)
 {
-    SpaceSplitStringData*& data = sharedDataMap().add(string, 0).iterator->value;
+    SpaceSplitStringData*& data = sharedDataMap().add(string, 0).storedValue->value;
     if (!data) {
         data = new SpaceSplitStringData(string);
         return adoptRef(data);
diff --git a/Source/core/dom/StaticNodeList.cpp b/Source/core/dom/StaticNodeList.cpp
index 10f4b28..ba3cfb3 100644
--- a/Source/core/dom/StaticNodeList.cpp
+++ b/Source/core/dom/StaticNodeList.cpp
@@ -33,6 +33,21 @@
 
 namespace WebCore {
 
+PassRefPtr<StaticNodeList> StaticNodeList::adopt(Vector<RefPtr<Node> >& nodes)
+{
+    RefPtr<StaticNodeList> nodeList = adoptRef(new StaticNodeList);
+    nodeList->m_nodes.swap(nodes);
+    if (nodeList->AllocationSize() > externalMemoryReportSizeLimit)
+        v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(nodeList->AllocationSize());
+    return nodeList.release();
+}
+
+StaticNodeList::~StaticNodeList()
+{
+    if (AllocationSize() > externalMemoryReportSizeLimit)
+        v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(-AllocationSize());
+}
+
 unsigned StaticNodeList::length() const
 {
     return m_nodes.size();
@@ -45,16 +60,4 @@
     return 0;
 }
 
-Node* StaticNodeList::namedItem(const AtomicString& elementId) const
-{
-    size_t length = m_nodes.size();
-    for (size_t i = 0; i < length; ++i) {
-        Node* node = m_nodes[i].get();
-        if (node->isElementNode() && toElement(node)->getIdAttribute() == elementId)
-            return node;
-    }
-
-    return 0;
-}
-
 } // namespace WebCore
diff --git a/Source/core/dom/StaticNodeList.h b/Source/core/dom/StaticNodeList.h
index fd66b3a..1875132 100644
--- a/Source/core/dom/StaticNodeList.h
+++ b/Source/core/dom/StaticNodeList.h
@@ -29,6 +29,7 @@
 #ifndef StaticNodeList_h
 #define StaticNodeList_h
 
+#include "core/dom/Node.h"
 #include "core/dom/NodeList.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
@@ -40,23 +41,28 @@
 
 class StaticNodeList FINAL : public NodeList {
 public:
-    static PassRefPtr<StaticNodeList> adopt(Vector<RefPtr<Node> >& nodes)
-    {
-        RefPtr<StaticNodeList> nodeList = adoptRef(new StaticNodeList);
-        nodeList->m_nodes.swap(nodes);
-        return nodeList.release();
-    }
+    static PassRefPtr<StaticNodeList> adopt(Vector<RefPtr<Node> >& nodes);
 
     static PassRefPtr<StaticNodeList> createEmpty()
     {
         return adoptRef(new StaticNodeList);
     }
 
+    virtual ~StaticNodeList();
+
     virtual unsigned length() const OVERRIDE;
     virtual Node* item(unsigned index) const OVERRIDE;
-    virtual Node* namedItem(const AtomicString&) const OVERRIDE;
 
 private:
+    // If AllocationSize() is larger than this, we report it as external
+    // allocated memory to V8.
+    const static ptrdiff_t externalMemoryReportSizeLimit = 1024;
+
+    ptrdiff_t AllocationSize()
+    {
+        return m_nodes.capacity() * sizeof(RefPtr<Node>);
+    }
+
     Vector<RefPtr<Node> > m_nodes;
 };
 
diff --git a/Source/core/dom/StringCallback.cpp b/Source/core/dom/StringCallback.cpp
index 1a1a5fc..1b02920 100644
--- a/Source/core/dom/StringCallback.cpp
+++ b/Source/core/dom/StringCallback.cpp
@@ -39,14 +39,14 @@
 
 namespace {
 
-class DispatchCallbackTask : public ExecutionContextTask {
+class DispatchCallbackTask FINAL : public ExecutionContextTask {
 public:
     static PassOwnPtr<DispatchCallbackTask> create(PassOwnPtr<StringCallback> callback, const String& data)
     {
         return adoptPtr(new DispatchCallbackTask(callback, data));
     }
 
-    virtual void performTask(ExecutionContext*)
+    virtual void performTask(ExecutionContext*) OVERRIDE
     {
         m_callback->handleEvent(m_data);
     }
diff --git a/Source/core/dom/StringCallback.h b/Source/core/dom/StringCallback.h
index 0e5b4c9..fdd260f 100644
--- a/Source/core/dom/StringCallback.h
+++ b/Source/core/dom/StringCallback.h
@@ -40,7 +40,7 @@
 class StringCallback {
 public:
     virtual ~StringCallback() { }
-    virtual bool handleEvent(const String& data) = 0;
+    virtual void handleEvent(const String& data) = 0;
 
     // Helper to post callback task.
     static void scheduleCallback(PassOwnPtr<StringCallback>, ExecutionContext*, const String& data);
diff --git a/Source/core/dom/StringCallback.idl b/Source/core/dom/StringCallback.idl
index 9ab79c1..b26a090 100644
--- a/Source/core/dom/StringCallback.idl
+++ b/Source/core/dom/StringCallback.idl
@@ -29,5 +29,5 @@
  */
 
 callback interface StringCallback {
-    boolean handleEvent(DOMString data);
+    void handleEvent(DOMString data);
 };
diff --git a/Source/core/dom/StyleElement.cpp b/Source/core/dom/StyleElement.cpp
index 8233785..e744c9b 100644
--- a/Source/core/dom/StyleElement.cpp
+++ b/Source/core/dom/StyleElement.cpp
@@ -83,7 +83,7 @@
         m_sheet->clearOwnerNode();
 
     if (element->inDocument())
-        document.styleEngine()->removeStyleSheetCandidateNode(element, isHTMLStyleElement(element) ? toHTMLStyleElement(element)->scopingNode() :  0);
+        document.styleEngine()->removeStyleSheetCandidateNode(element, element->hasTagName(HTMLNames::styleTag) ? toHTMLStyleElement(element)->scopingNode() :  0);
 }
 
 void StyleElement::childrenChanged(Element* element)
@@ -128,22 +128,17 @@
 
     // If type is empty or CSS, this is a CSS style sheet.
     const AtomicString& type = this->type();
-    bool passesContentSecurityPolicyChecks = document.contentSecurityPolicy()->allowStyleNonce(e->fastGetAttribute(HTMLNames::nonceAttr)) || document.contentSecurityPolicy()->allowInlineStyle(e->document().url(), m_startPosition.m_line);
+    bool passesContentSecurityPolicyChecks = document.contentSecurityPolicy()->allowStyleHash(text) || document.contentSecurityPolicy()->allowStyleNonce(e->fastGetAttribute(HTMLNames::nonceAttr)) || document.contentSecurityPolicy()->allowInlineStyle(e->document().url(), m_startPosition.m_line);
     if (isCSS(e, type) && passesContentSecurityPolicyChecks) {
         RefPtr<MediaQuerySet> mediaQueries = MediaQuerySet::create(media());
 
         MediaQueryEvaluator screenEval("screen", true);
         MediaQueryEvaluator printEval("print", true);
         if (screenEval.eval(mediaQueries.get()) || printEval.eval(mediaQueries.get())) {
-            document.styleEngine()->addPendingSheet();
             m_loading = true;
-
             TextPosition startPosition = m_startPosition == TextPosition::belowRangePosition() ? TextPosition::minimumPosition() : m_startPosition;
-            m_sheet = CSSStyleSheet::createInline(e, KURL(), startPosition, document.inputEncoding());
+            m_sheet = StyleEngine::createSheet(e, text, startPosition, m_createdByParser);
             m_sheet->setMediaQueries(mediaQueries.release());
-            m_sheet->setTitle(e->title());
-            m_sheet->contents()->parseStringAtPosition(text, startPosition, m_createdByParser);
-
             m_loading = false;
         }
     }
diff --git a/Source/core/dom/StyleEngine.cpp b/Source/core/dom/StyleEngine.cpp
index 0c8385f..8f329f8 100644
--- a/Source/core/dom/StyleEngine.cpp
+++ b/Source/core/dom/StyleEngine.cpp
@@ -32,8 +32,10 @@
 #include "SVGNames.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSStyleSheet.h"
+#include "core/css/FontFaceCache.h"
 #include "core/css/StyleInvalidationAnalysis.h"
 #include "core/css/StyleSheetContents.h"
+#include "core/dom/DocumentStyleSheetCollector.h"
 #include "core/dom/Element.h"
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/ShadowTreeStyleSheetCollection.h"
@@ -41,11 +43,10 @@
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLImport.h"
 #include "core/html/HTMLLinkElement.h"
-#include "core/html/HTMLStyleElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Page.h"
 #include "core/page/PageGroup.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/svg/SVGStyleElement.h"
 #include "platform/URLPatternMatcher.h"
 
@@ -53,14 +54,27 @@
 
 using namespace HTMLNames;
 
+static HashMap<AtomicString, StyleSheetContents*>& textToSheetCache()
+{
+    typedef HashMap<AtomicString, StyleSheetContents*> TextToSheetCache;
+    DEFINE_STATIC_LOCAL(TextToSheetCache, cache, ());
+    return cache;
+}
+
+static HashMap<StyleSheetContents*, AtomicString>& sheetToTextCache()
+{
+    typedef HashMap<StyleSheetContents*, AtomicString> SheetToTextCache;
+    DEFINE_STATIC_LOCAL(SheetToTextCache, cache, ());
+    return cache;
+}
+
 StyleEngine::StyleEngine(Document& document)
     : m_document(document)
     , m_isMaster(HTMLImport::isMaster(&document))
     , m_pendingStylesheets(0)
     , m_injectedStyleSheetCacheValid(false)
-    , m_needsUpdateActiveStylesheetsOnStyleRecalc(false)
     , m_documentStyleSheetCollection(document)
-    , m_dirtyTreeScopes(document)
+    , m_documentScopeDirty(true)
     , m_usesSiblingRules(false)
     , m_usesSiblingRulesOverride(false)
     , m_usesFirstLineRules(false)
@@ -69,8 +83,6 @@
     , m_maxDirectAdjacentSelectors(0)
     , m_ignorePendingStylesheets(false)
     , m_didCalculateResolver(false)
-    , m_lastResolverAccessCount(0)
-    , m_resolverThrowawayTimer(this, &StyleEngine::resolverThrowawayTimerFired)
     // We don't need to create CSSFontSelector for imported document or
     // HTMLTemplateElement's document, because those documents have no frame.
     , m_fontSelector(document.frame() ? CSSFontSelector::create(&document) : 0)
@@ -83,6 +95,12 @@
         m_injectedAuthorStyleSheets[i]->clearOwnerNode();
     for (unsigned i = 0; i < m_authorStyleSheets.size(); ++i)
         m_authorStyleSheets[i]->clearOwnerNode();
+
+    if (m_fontSelector) {
+        m_fontSelector->clearDocument();
+        if (m_resolver)
+            m_fontSelector->unregisterForInvalidationCallbacks(m_resolver.get());
+    }
 }
 
 inline Document* StyleEngine::master()
@@ -122,23 +140,23 @@
     treeScopes.insertBefore(followingTreeScope, treeScope);
 }
 
-StyleSheetCollection* StyleEngine::ensureStyleSheetCollectionFor(TreeScope& treeScope)
+TreeScopeStyleSheetCollection* StyleEngine::ensureStyleSheetCollectionFor(TreeScope& treeScope)
 {
     if (treeScope == m_document)
         return &m_documentStyleSheetCollection;
 
-    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::AddResult result = m_styleSheetCollectionMap.add(&treeScope, nullptr);
+    HashMap<TreeScope*, OwnPtr<TreeScopeStyleSheetCollection> >::AddResult result = m_styleSheetCollectionMap.add(&treeScope, nullptr);
     if (result.isNewEntry)
-        result.iterator->value = adoptPtr(new ShadowTreeStyleSheetCollection(toShadowRoot(treeScope)));
-    return result.iterator->value.get();
+        result.storedValue->value = adoptPtr(new ShadowTreeStyleSheetCollection(toShadowRoot(treeScope)));
+    return result.storedValue->value.get();
 }
 
-StyleSheetCollection* StyleEngine::styleSheetCollectionFor(TreeScope& treeScope)
+TreeScopeStyleSheetCollection* StyleEngine::styleSheetCollectionFor(TreeScope& treeScope)
 {
     if (treeScope == m_document)
         return &m_documentStyleSheetCollection;
 
-    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::iterator it = m_styleSheetCollectionMap.find(&treeScope);
+    HashMap<TreeScope*, OwnPtr<TreeScopeStyleSheetCollection> >::iterator it = m_styleSheetCollectionMap.find(&treeScope);
     if (it == m_styleSheetCollectionMap.end())
         return 0;
     return it->value.get();
@@ -157,19 +175,6 @@
     return m_documentStyleSheetCollection.activeAuthorStyleSheets();
 }
 
-void StyleEngine::getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const
-{
-    activeAuthorStyleSheets.append(&m_documentStyleSheetCollection.activeAuthorStyleSheets());
-
-    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::const_iterator::Values begin = m_styleSheetCollectionMap.values().begin();
-    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::const_iterator::Values end = m_styleSheetCollectionMap.values().end();
-    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::const_iterator::Values it = begin;
-    for (; it != end; ++it) {
-        const StyleSheetCollection* collection = it->get();
-        activeAuthorStyleSheets.append(&collection->activeAuthorStyleSheets());
-    }
-}
-
 void StyleEngine::combineCSSFeatureFlags(const RuleFeatureSet& features)
 {
     // Delay resetting the flags until after next style recalc since unapplying the style may not work without these set (this is true at least with before/after).
@@ -202,24 +207,23 @@
     if (!owningPage)
         return;
 
-    const PageGroup& pageGroup = owningPage->group();
-    const InjectedStyleSheetVector& sheets = pageGroup.injectedStyleSheets();
-    for (unsigned i = 0; i < sheets.size(); ++i) {
-        const InjectedStyleSheet* sheet = sheets[i].get();
-        if (sheet->injectedFrames() == InjectStyleInTopFrameOnly && m_document.ownerElement())
+    const InjectedStyleSheetEntryVector& entries = InjectedStyleSheets::instance().entries();
+    for (unsigned i = 0; i < entries.size(); ++i) {
+        const InjectedStyleSheetEntry* entry = entries[i].get();
+        if (entry->injectedFrames() == InjectStyleInTopFrameOnly && m_document.ownerElement())
             continue;
-        if (!URLPatternMatcher::matchesPatterns(m_document.url(), sheet->whitelist()))
+        if (!URLPatternMatcher::matchesPatterns(m_document.url(), entry->whitelist()))
             continue;
         RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(&m_document), KURL());
         m_injectedAuthorStyleSheets.append(groupSheet);
-        groupSheet->contents()->parseString(sheet->source());
+        groupSheet->contents()->parseString(entry->source());
     }
 }
 
 void StyleEngine::invalidateInjectedStyleSheetCache()
 {
     m_injectedStyleSheetCacheValid = false;
-    m_dirtyTreeScopes.markDocument();
+    markDocumentDirty();
     // FIXME: updateInjectedStyleSheetCache is called inside StyleSheetCollection::updateActiveStyleSheets
     // and batch updates lots of sheets so we can't call addedStyleSheet() or removedStyleSheet().
     m_document.styleResolverChanged(RecalcStyleDeferred);
@@ -229,7 +233,7 @@
 {
     m_authorStyleSheets.append(CSSStyleSheet::create(authorSheet, &m_document));
     m_document.addedStyleSheet(m_authorStyleSheets.last().get(), RecalcStyleImmediately);
-    m_dirtyTreeScopes.markDocument();
+    markDocumentDirty();
 }
 
 void StyleEngine::addPendingSheet()
@@ -240,8 +244,8 @@
 // This method is called whenever a top-level stylesheet has finished loading.
 void StyleEngine::removePendingSheet(Node* styleSheetCandidateNode, RemovePendingSheetNotificationType notification)
 {
-    TreeScope* treeScope = isHTMLStyleElement(styleSheetCandidateNode) ? &styleSheetCandidateNode->treeScope() : &m_document;
-    m_dirtyTreeScopes.mark(*treeScope);
+    TreeScope* treeScope = styleSheetCandidateNode->hasTagName(styleTag) ? &styleSheetCandidateNode->treeScope() : &m_document;
+    markTreeScopeDirty(*treeScope);
     master()->styleEngine()->notifyPendingStyleSheetRemoved(notification);
 }
 
@@ -280,11 +284,10 @@
     if (!node || !node->inDocument())
         return;
 
-    TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
-    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+    TreeScope& treeScope = node->hasTagName(styleTag) ? node->treeScope() : m_document;
+    ASSERT(node->hasTagName(styleTag) || treeScope == m_document);
 
-
-    m_dirtyTreeScopes.mark(treeScope);
+    markTreeScopeDirty(treeScope);
 }
 
 void StyleEngine::addStyleSheetCandidateNode(Node* node, bool createdByParser)
@@ -292,14 +295,14 @@
     if (!node->inDocument())
         return;
 
-    TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
-    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+    TreeScope& treeScope = node->hasTagName(styleTag) ? node->treeScope() : m_document;
+    ASSERT(node->hasTagName(styleTag) || treeScope == m_document);
 
-    StyleSheetCollection* collection = ensureStyleSheetCollectionFor(treeScope);
+    TreeScopeStyleSheetCollection* collection = ensureStyleSheetCollectionFor(treeScope);
     ASSERT(collection);
     collection->addStyleSheetCandidateNode(node, createdByParser);
 
-    m_dirtyTreeScopes.mark(treeScope);
+    markTreeScopeDirty(treeScope);
     if (treeScope != m_document)
         insertTreeScopeInDocumentOrder(m_activeTreeScopes, &treeScope);
 }
@@ -307,13 +310,13 @@
 void StyleEngine::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
 {
     TreeScope& treeScope = scopingNode ? scopingNode->treeScope() : m_document;
-    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+    ASSERT(node->hasTagName(styleTag) || treeScope == m_document);
 
-    StyleSheetCollection* collection = styleSheetCollectionFor(treeScope);
+    TreeScopeStyleSheetCollection* collection = styleSheetCollectionFor(treeScope);
     ASSERT(collection);
     collection->removeStyleSheetCandidateNode(node, scopingNode);
 
-    m_dirtyTreeScopes.mark(treeScope);
+    markTreeScopeDirty(treeScope);
     m_activeTreeScopes.remove(&treeScope);
 }
 
@@ -322,14 +325,14 @@
     if (!node->inDocument())
         return;
 
-    TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
-    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
-    m_dirtyTreeScopes.mark(treeScope);
+    TreeScope& treeScope = node->hasTagName(styleTag) ? node->treeScope() : m_document;
+    ASSERT(node->hasTagName(styleTag) || treeScope == m_document);
+    markTreeScopeDirty(treeScope);
 }
 
 bool StyleEngine::shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode updateMode)
 {
-    return !m_dirtyTreeScopes.isSubscopeMarked() || updateMode == FullStyleUpdate;
+    return !m_dirtyTreeScopes.isEmpty() || updateMode == FullStyleUpdate;
 }
 
 void StyleEngine::clearMediaQueryRuleSetOnTreeScopeStyleSheets(TreeScopeSet treeScopes)
@@ -347,49 +350,32 @@
 {
     m_documentStyleSheetCollection.clearMediaQueryRuleSetStyleSheets();
     clearMediaQueryRuleSetOnTreeScopeStyleSheets(m_activeTreeScopes);
-    clearMediaQueryRuleSetOnTreeScopeStyleSheets(m_dirtyTreeScopes.subscope());
+    clearMediaQueryRuleSetOnTreeScopeStyleSheets(m_dirtyTreeScopes);
 }
 
-void StyleEngine::collectDocumentActiveStyleSheets(StyleSheetCollectionBase& collection)
+void StyleEngine::updateStyleSheetsInImport(DocumentStyleSheetCollector& parentCollector)
 {
-    ASSERT(isMaster());
-
-    if (HTMLImport* rootImport = m_document.import()) {
-        for (HTMLImport* import = traverseFirstPostOrder(rootImport); import; import = traverseNextPostOrder(import)) {
-            Document* document = import->document();
-            if (!document)
-                continue;
-            StyleEngine* engine = document->styleEngine();
-            DocumentStyleSheetCollection::CollectFor collectFor = document == &m_document ?
-                DocumentStyleSheetCollection::CollectForList : DocumentStyleSheetCollection::DontCollectForList;
-            engine->m_documentStyleSheetCollection.collectStyleSheets(engine, collection, collectFor);
-        }
-    } else {
-        m_documentStyleSheetCollection.collectStyleSheets(this, collection, DocumentStyleSheetCollection::CollectForList);
-    }
+    ASSERT(!isMaster());
+    Vector<RefPtr<StyleSheet> > sheetsForList;
+    ImportedDocumentStyleSheetCollector subcollector(parentCollector, sheetsForList);
+    m_documentStyleSheetCollection.collectStyleSheets(this, subcollector);
+    m_documentStyleSheetCollection.swapSheetsForSheetList(sheetsForList);
 }
 
 bool StyleEngine::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
 {
     ASSERT(isMaster());
+    ASSERT(!m_document.inStyleRecalc());
 
-    if (m_document.inStyleRecalc()) {
-        // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
-        // https://bugs.webkit.org/show_bug.cgi?id=54344
-        // FIXME: This should be fixed in SVG and the call site replaced by ASSERT(!m_inStyleRecalc).
-        m_needsUpdateActiveStylesheetsOnStyleRecalc = true;
-        return false;
-
-    }
     if (!m_document.isActive())
         return false;
 
     bool requiresFullStyleRecalc = false;
-    if (m_dirtyTreeScopes.isDocumentMarked() || updateMode == FullStyleUpdate)
+    if (m_documentScopeDirty || updateMode == FullStyleUpdate)
         requiresFullStyleRecalc = m_documentStyleSheetCollection.updateActiveStyleSheets(this, updateMode);
 
     if (shouldUpdateShadowTreeStyleSheetCollection(updateMode)) {
-        TreeScopeSet treeScopes = updateMode == FullStyleUpdate ? m_activeTreeScopes : m_dirtyTreeScopes.subscope();
+        TreeScopeSet treeScopes = updateMode == FullStyleUpdate ? m_activeTreeScopes : m_dirtyTreeScopes;
         HashSet<TreeScope*> treeScopesRemoved;
 
         for (TreeScopeSet::iterator it = treeScopes.begin(); it != treeScopes.end(); ++it) {
@@ -405,39 +391,36 @@
             for (HashSet<TreeScope*>::iterator it = treeScopesRemoved.begin(); it != treeScopesRemoved.end(); ++it)
                 m_activeTreeScopes.remove(*it);
     }
-    m_needsUpdateActiveStylesheetsOnStyleRecalc = false;
-    activeStyleSheetsUpdatedForInspector();
+
+    InspectorInstrumentation::activeStyleSheetsUpdated(&m_document);
     m_usesRemUnits = m_documentStyleSheetCollection.usesRemUnits();
 
-    if (m_dirtyTreeScopes.isDocumentMarked() || updateMode == FullStyleUpdate)
-        m_document.notifySeamlessChildDocumentsOfStylesheetUpdate();
-
     m_dirtyTreeScopes.clear();
+    m_documentScopeDirty = false;
 
     return requiresFullStyleRecalc;
 }
 
-void StyleEngine::activeStyleSheetsUpdatedForInspector()
+const Vector<RefPtr<StyleSheet> > StyleEngine::activeStyleSheetsForInspector() const
 {
-    if (m_activeTreeScopes.isEmpty()) {
-        InspectorInstrumentation::activeStyleSheetsUpdated(&m_document, m_documentStyleSheetCollection.styleSheetsForStyleSheetList());
-        return;
-    }
+    if (m_activeTreeScopes.isEmpty())
+        return m_documentStyleSheetCollection.styleSheetsForStyleSheetList();
+
     Vector<RefPtr<StyleSheet> > activeStyleSheets;
 
     activeStyleSheets.append(m_documentStyleSheetCollection.styleSheetsForStyleSheetList());
 
-    TreeScopeSet::iterator begin = m_activeTreeScopes.begin();
-    TreeScopeSet::iterator end = m_activeTreeScopes.end();
-    for (TreeScopeSet::iterator it = begin; it != end; ++it) {
-        if (StyleSheetCollection* collection = m_styleSheetCollectionMap.get(*it))
+    TreeScopeSet::const_iterator begin = m_activeTreeScopes.begin();
+    TreeScopeSet::const_iterator end = m_activeTreeScopes.end();
+    for (TreeScopeSet::const_iterator it = begin; it != end; ++it) {
+        if (TreeScopeStyleSheetCollection* collection = m_styleSheetCollectionMap.get(*it))
             activeStyleSheets.append(collection->styleSheetsForStyleSheetList());
     }
 
     // FIXME: Inspector needs a vector which has all active stylesheets.
     // However, creating such a large vector might cause performance regression.
     // Need to implement some smarter solution.
-    InspectorInstrumentation::activeStyleSheetsUpdated(&m_document, activeStyleSheets);
+    return activeStyleSheets;
 }
 
 void StyleEngine::didRemoveShadowRoot(ShadowRoot* shadowRoot)
@@ -455,7 +438,7 @@
     TreeScopeSet::iterator begin = m_activeTreeScopes.begin();
     TreeScopeSet::iterator end = m_activeTreeScopes.end();
     for (TreeScopeSet::iterator it = begin; it != end; ++it) {
-        if (StyleSheetCollection* collection = m_styleSheetCollectionMap.get(*it)) {
+        if (TreeScopeStyleSheetCollection* collection = m_styleSheetCollectionMap.get(*it)) {
             m_resolver->setBuildScopedStyleTreeInDocumentOrder(!collection->scopingNodesForStyleScoped());
             m_resolver->appendAuthorStyleSheets(0, collection->activeAuthorStyleSheets());
         }
@@ -500,21 +483,8 @@
     return m_resolver ? m_resolver->accessCount() : 0;
 }
 
-void StyleEngine::resolverThrowawayTimerFired(Timer<StyleEngine>*)
-{
-    if (resolverAccessCount() == m_lastResolverAccessCount)
-        clearResolver();
-    m_lastResolverAccessCount = resolverAccessCount();
-}
-
-void StyleEngine::didAttach()
-{
-    m_resolverThrowawayTimer.startRepeating(60);
-}
-
 void StyleEngine::didDetach()
 {
-    m_resolverThrowawayTimer.stop();
     clearResolver();
 }
 
@@ -550,26 +520,100 @@
     return change;
 }
 
-void StyleEngine::resetFontSelector()
+void StyleEngine::clearFontCache()
+{
+    // We should not recreate FontSelector. Instead, clear fontFaceCache.
+    if (m_fontSelector)
+        m_fontSelector->fontFaceCache()->clear();
+    if (m_resolver)
+        m_resolver->invalidateMatchedPropertiesCache();
+}
+
+void StyleEngine::updateGenericFontFamilySettings()
 {
     if (!m_fontSelector)
         return;
 
-    m_fontSelector->clearDocument();
-    if (m_resolver) {
-        m_fontSelector->unregisterForInvalidationCallbacks(m_resolver.get());
+    m_fontSelector->updateGenericFontFamilySettings(m_document);
+    if (m_resolver)
         m_resolver->invalidateMatchedPropertiesCache();
+}
+
+void StyleEngine::removeFontFaceRules(const Vector<const StyleRuleFontFace*>& fontFaceRules)
+{
+    if (!m_fontSelector)
+        return;
+
+    FontFaceCache* cache = m_fontSelector->fontFaceCache();
+    for (unsigned i = 0; i < fontFaceRules.size(); ++i)
+        cache->remove(fontFaceRules[i]);
+    if (m_resolver)
+        m_resolver->invalidateMatchedPropertiesCache();
+}
+
+void StyleEngine::markTreeScopeDirty(TreeScope& scope)
+{
+    if (scope == m_document) {
+        markDocumentDirty();
+        return;
     }
 
-    // If the document has been already detached, we don't need to recreate
-    // CSSFontSelector.
-    if (m_document.isActive()) {
-        m_fontSelector = CSSFontSelector::create(&m_document);
-        if (m_resolver)
-            m_fontSelector->registerForInvalidationCallbacks(m_resolver.get());
+    m_dirtyTreeScopes.add(&scope);
+}
+
+void StyleEngine::markDocumentDirty()
+{
+    m_documentScopeDirty = true;
+    if (!HTMLImport::isMaster(&m_document))
+        m_document.import()->master()->styleEngine()->markDocumentDirty();
+}
+
+PassRefPtr<CSSStyleSheet> StyleEngine::createSheet(Element* e, const String& text, TextPosition startPosition, bool createdByParser)
+{
+    RefPtr<CSSStyleSheet> styleSheet;
+
+    e->document().styleEngine()->addPendingSheet();
+
+    if (!e->document().inQuirksMode()) {
+        AtomicString textContent(text);
+
+        HashMap<AtomicString, StyleSheetContents*>::AddResult result = textToSheetCache().add(textContent, 0);
+        if (result.isNewEntry || !result.storedValue->value) {
+            styleSheet = StyleEngine::parseSheet(e, text, startPosition, createdByParser);
+            if (result.isNewEntry && styleSheet->contents()->maybeCacheable()) {
+                result.storedValue->value = styleSheet->contents();
+                sheetToTextCache().add(styleSheet->contents(), textContent);
+            }
+        } else {
+            ASSERT(result.storedValue->value->maybeCacheable());
+            styleSheet = CSSStyleSheet::createInline(result.storedValue->value, e, startPosition);
+        }
     } else {
-        m_fontSelector = 0;
+        // FIXME: currently we don't cache StyleSheetContents inQuirksMode.
+        styleSheet = StyleEngine::parseSheet(e, text, startPosition, createdByParser);
     }
+
+    ASSERT(styleSheet);
+    styleSheet->setTitle(e->title());
+    return styleSheet;
+}
+
+PassRefPtr<CSSStyleSheet> StyleEngine::parseSheet(Element* e, const String& text, TextPosition startPosition, bool createdByParser)
+{
+    RefPtr<CSSStyleSheet> styleSheet;
+    styleSheet = CSSStyleSheet::createInline(e, KURL(), startPosition, e->document().inputEncoding());
+    styleSheet->contents()->parseStringAtPosition(text, startPosition, createdByParser);
+    return styleSheet;
+}
+
+void StyleEngine::removeSheet(StyleSheetContents* contents)
+{
+    HashMap<StyleSheetContents*, AtomicString>::iterator it = sheetToTextCache().find(contents);
+    if (it == sheetToTextCache().end())
+        return;
+
+    textToSheetCache().remove(it->value);
+    sheetToTextCache().remove(contents);
 }
 
 }
diff --git a/Source/core/dom/StyleEngine.h b/Source/core/dom/StyleEngine.h
index 36c4b9d..d924848 100644
--- a/Source/core/dom/StyleEngine.h
+++ b/Source/core/dom/StyleEngine.h
@@ -32,7 +32,6 @@
 #include "core/dom/Document.h"
 #include "core/dom/DocumentOrderedList.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
-#include "core/dom/StyleTreeScopeTracker.h"
 #include "wtf/FastAllocBase.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/RefPtr.h"
@@ -49,6 +48,7 @@
 class RuleFeatureSet;
 class ShadowTreeStyleSheetCollection;
 class StyleResolver;
+class StyleRuleFontFace;
 class StyleSheet;
 class StyleSheetCollection;
 class StyleSheetContents;
@@ -95,6 +95,8 @@
     const Vector<RefPtr<CSSStyleSheet> >& documentAuthorStyleSheets() const { return m_authorStyleSheets; }
     const Vector<RefPtr<CSSStyleSheet> >& injectedAuthorStyleSheets() const;
 
+    const Vector<RefPtr<StyleSheet> > activeStyleSheetsForInspector() const;
+
     void modifiedStyleSheet(StyleSheet*);
     void addStyleSheetCandidateNode(Node*, bool createdByParser);
     void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode = 0);
@@ -105,9 +107,8 @@
 
     void addAuthorSheet(PassRefPtr<StyleSheetContents> authorSheet);
 
-    bool needsUpdateActiveStylesheetsOnStyleRecalc() const { return m_needsUpdateActiveStylesheetsOnStyleRecalc; }
-
     void clearMediaQueryRuleSetStyleSheets();
+    void updateStyleSheetsInImport(DocumentStyleSheetCollector& parentCollector);
     bool updateActiveStyleSheets(StyleResolverUpdateMode);
 
     String preferredStylesheetSetName() const { return m_preferredStylesheetSetName; }
@@ -115,6 +116,12 @@
     void setPreferredStylesheetSetName(const String& name) { m_preferredStylesheetSetName = name; }
     void setSelectedStylesheetSetName(const String& name) { m_selectedStylesheetSetName = name; }
 
+    void selectStylesheetSetName(const String& name)
+    {
+        setPreferredStylesheetSetName(name);
+        setSelectedStylesheetSetName(name);
+    }
+
     void addPendingSheet();
     enum RemovePendingSheetNotificationType {
         RemovePendingSheetNotifyImmediately,
@@ -139,10 +146,8 @@
     void combineCSSFeatureFlags(const RuleFeatureSet&);
     void resetCSSFeatureFlags(const RuleFeatureSet&);
 
-    void didModifySeamlessParentStyleSheet() { m_dirtyTreeScopes.markDocument(); }
     void didRemoveShadowRoot(ShadowRoot*);
     void appendActiveAuthorStyleSheets();
-    void getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const;
 
     StyleResolver* resolver() const
     {
@@ -164,25 +169,29 @@
     void clearMasterResolver();
 
     CSSFontSelector* fontSelector() { return m_fontSelector.get(); }
-    void resetFontSelector();
+    void removeFontFaceRules(const Vector<const StyleRuleFontFace*>&);
+    void clearFontCache();
+    // updateGenericFontFamilySettings is used from WebSettingsImpl.
+    void updateGenericFontFamilySettings();
 
-    void didAttach();
     void didDetach();
     bool shouldClearResolver() const;
     StyleResolverChange resolverChanged(RecalcStyleTime, StyleResolverUpdateMode);
     unsigned resolverAccessCount() const;
 
-    void collectDocumentActiveStyleSheets(StyleSheetCollectionBase&);
-    void markDocumentDirty() { m_dirtyTreeScopes.markDocument(); }
+    void markDocumentDirty();
+
+    static PassRefPtr<CSSStyleSheet> createSheet(Element*, const String& text, TextPosition startPosition, bool createdByParser);
+    static void removeSheet(StyleSheetContents*);
 
 private:
     StyleEngine(Document&);
 
-    StyleSheetCollection* ensureStyleSheetCollectionFor(TreeScope&);
-    StyleSheetCollection* styleSheetCollectionFor(TreeScope&);
-    void activeStyleSheetsUpdatedForInspector();
+    TreeScopeStyleSheetCollection* ensureStyleSheetCollectionFor(TreeScope&);
+    TreeScopeStyleSheetCollection* styleSheetCollectionFor(TreeScope&);
     bool shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode);
-    void resolverThrowawayTimerFired(Timer<StyleEngine>*);
+
+    void markTreeScopeDirty(TreeScope&);
 
     bool isMaster() const { return m_isMaster; }
     Document* master();
@@ -196,6 +205,8 @@
     void notifyPendingStyleSheetAdded();
     void notifyPendingStyleSheetRemoved(RemovePendingSheetNotificationType);
 
+    static PassRefPtr<CSSStyleSheet> parseSheet(Element*, const String& text, TextPosition startPosition, bool createdByParser);
+
     Document& m_document;
     bool m_isMaster;
 
@@ -210,12 +221,11 @@
 
     Vector<RefPtr<CSSStyleSheet> > m_authorStyleSheets;
 
-    bool m_needsUpdateActiveStylesheetsOnStyleRecalc;
-
     DocumentStyleSheetCollection m_documentStyleSheetCollection;
-    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> > m_styleSheetCollectionMap;
+    HashMap<TreeScope*, OwnPtr<TreeScopeStyleSheetCollection> > m_styleSheetCollectionMap;
 
-    StyleTreeScopeTracker m_dirtyTreeScopes;
+    bool m_documentScopeDirty;
+    TreeScopeSet m_dirtyTreeScopes;
     TreeScopeSet m_activeTreeScopes;
 
     String m_preferredStylesheetSetName;
@@ -230,8 +240,6 @@
 
     bool m_ignorePendingStylesheets;
     bool m_didCalculateResolver;
-    unsigned m_lastResolverAccessCount;
-    Timer<StyleEngine> m_resolverThrowawayTimer;
     OwnPtr<StyleResolver> m_resolver;
 
     RefPtr<CSSFontSelector> m_fontSelector;
diff --git a/Source/core/dom/StyleSheetCandidate.cpp b/Source/core/dom/StyleSheetCandidate.cpp
new file mode 100644
index 0000000..f090e25
--- /dev/null
+++ b/Source/core/dom/StyleSheetCandidate.cpp
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/dom/StyleSheetCandidate.h"
+
+#include "HTMLNames.h"
+#include "core/dom/Element.h"
+#include "core/dom/ProcessingInstruction.h"
+#include "core/dom/StyleEngine.h"
+#include "core/html/HTMLImport.h"
+#include "core/html/HTMLLinkElement.h"
+#include "core/html/HTMLStyleElement.h"
+#include "core/svg/SVGStyleElement.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AtomicString StyleSheetCandidate::title() const
+{
+    return isElement() ? toElement(m_node).fastGetAttribute(titleAttr) : nullAtom;
+}
+
+bool StyleSheetCandidate::isXSL() const
+{
+    return !m_node.document().isHTMLDocument() && m_type == Pi && toProcessingInstruction(m_node).isXSL();
+}
+
+bool StyleSheetCandidate::isImport() const
+{
+    return m_type == HTMLLink && toHTMLLinkElement(m_node).isImport();
+}
+
+Document* StyleSheetCandidate::importedDocument() const
+{
+    ASSERT(isImport());
+    // The stylesheet update traversal shouldn't go into shared import
+    // to prevent it from stepping into cycle.
+    HTMLLinkElement& element = toHTMLLinkElement(m_node);
+    if (!element.importOwnsLoader())
+        return 0;
+    return element.import();
+}
+
+bool StyleSheetCandidate::isAlternate() const
+{
+    if (!isElement())
+        return false;
+    return toElement(m_node).getAttribute(relAttr).contains("alternate");
+}
+
+bool StyleSheetCandidate::isEnabledViaScript() const
+{
+    return isHTMLLink() && toHTMLLinkElement(m_node).isEnabledViaScript();
+}
+
+bool StyleSheetCandidate::isEnabledAndLoading() const
+{
+    return isHTMLLink() && !toHTMLLinkElement(m_node).isDisabled() && toHTMLLinkElement(m_node).styleSheetIsLoading();
+}
+
+bool StyleSheetCandidate::hasPreferrableName(const String& currentPreferrableName) const
+{
+    ASSERT(isEnabledAndLoading() || sheet());
+    return !isEnabledViaScript() && !title().isEmpty() && !isAlternate() && currentPreferrableName.isEmpty();
+}
+
+bool StyleSheetCandidate::canBeActivated(const String& currentPreferrableName) const
+{
+    StyleSheet* sheet = this->sheet();
+    if (!sheet || sheet->disabled() || !sheet->isCSSStyleSheet())
+        return false;
+    const AtomicString& title = this->title();
+    if (!isEnabledViaScript() && !title.isEmpty() && title != currentPreferrableName)
+        return false;
+    if (isAlternate() && title.isEmpty())
+        return false;
+
+    return true;
+}
+
+StyleSheetCandidate::Type StyleSheetCandidate::typeOf(Node& node)
+{
+    if (node.nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
+        return Pi;
+
+    if (node.isHTMLElement()) {
+        if (node.hasTagName(linkTag))
+            return HTMLLink;
+        if (node.hasTagName(styleTag))
+            return HTMLStyle;
+
+        ASSERT_NOT_REACHED();
+        return HTMLStyle;
+    }
+
+    if (node.isSVGElement() && node.hasTagName(SVGNames::styleTag))
+        return SVGStyle;
+
+    ASSERT_NOT_REACHED();
+    return HTMLStyle;
+}
+
+StyleSheet* StyleSheetCandidate::sheet() const
+{
+    switch (m_type) {
+    case HTMLLink:
+        return toHTMLLinkElement(m_node).sheet();
+    case HTMLStyle:
+        return toHTMLStyleElement(m_node).sheet();
+    case SVGStyle:
+        return toSVGStyleElement(m_node).sheet();
+    case Pi:
+        return toProcessingInstruction(m_node).sheet();
+    }
+
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
+}
diff --git a/Source/core/dom/StyleSheetCandidate.h b/Source/core/dom/StyleSheetCandidate.h
new file mode 100644
index 0000000..742e862
--- /dev/null
+++ b/Source/core/dom/StyleSheetCandidate.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef StyleSheetCandidate_h
+#define StyleSheetCandidate_h
+
+#include "wtf/text/AtomicString.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class Document;
+class Node;
+class StyleSheet;
+
+class StyleSheetCandidate {
+public:
+    enum Type {
+        HTMLLink,
+        HTMLStyle,
+        SVGStyle,
+        Pi
+    };
+
+    StyleSheetCandidate(Node& node)
+        : m_node(node)
+        , m_type(typeOf(node))
+    { }
+
+    bool isXSL() const;
+    bool isImport() const;
+    bool isAlternate() const;
+    bool isEnabledViaScript() const;
+    bool isEnabledAndLoading() const;
+    bool hasPreferrableName(const String& currentPreferrableName) const;
+    bool canBeActivated(const String& currentPreferrableName) const;
+
+    StyleSheet* sheet() const;
+    AtomicString title() const;
+    Document* importedDocument() const;
+
+private:
+    bool isElement() const { return m_type != Pi; }
+    bool isHTMLLink() const { return m_type == HTMLLink; }
+
+    static Type typeOf(Node&);
+
+    Node& m_node;
+    Type m_type;
+};
+
+}
+
+#endif
+
diff --git a/Source/core/dom/StyleSheetCollection.cpp b/Source/core/dom/StyleSheetCollection.cpp
index df49206..8603903 100644
--- a/Source/core/dom/StyleSheetCollection.cpp
+++ b/Source/core/dom/StyleSheetCollection.cpp
@@ -28,238 +28,43 @@
 #include "core/dom/StyleSheetCollection.h"
 
 #include "core/css/CSSStyleSheet.h"
-#include "core/css/StyleInvalidationAnalysis.h"
-#include "core/css/StyleRuleImport.h"
-#include "core/css/StyleSheetContents.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/Element.h"
-#include "core/dom/StyleEngine.h"
-#include "core/html/HTMLStyleElement.h"
-#include "core/page/Settings.h"
 
 namespace WebCore {
 
-StyleSheetCollectionBase::StyleSheetCollectionBase()
+StyleSheetCollection::StyleSheetCollection()
 {
 }
 
-StyleSheetCollectionBase::~StyleSheetCollectionBase()
+StyleSheetCollection::~StyleSheetCollection()
 {
 }
 
-void StyleSheetCollectionBase::swap(StyleSheetCollectionBase& other)
+void StyleSheetCollection::swap(StyleSheetCollection& other)
 {
     m_styleSheetsForStyleSheetList.swap(other.m_styleSheetsForStyleSheetList);
     m_activeAuthorStyleSheets.swap(other.m_activeAuthorStyleSheets);
 }
 
-void StyleSheetCollectionBase::appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& sheets)
+void StyleSheetCollection::swapSheetsForSheetList(Vector<RefPtr<StyleSheet> >& sheets)
+{
+    // Only called for collection of HTML Imports that never has active sheets.
+    ASSERT(m_activeAuthorStyleSheets.isEmpty());
+    m_styleSheetsForStyleSheetList.swap(sheets);
+}
+
+void StyleSheetCollection::appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& sheets)
 {
     m_activeAuthorStyleSheets.append(sheets);
 }
 
-void StyleSheetCollectionBase::appendActiveStyleSheet(CSSStyleSheet* sheet)
+void StyleSheetCollection::appendActiveStyleSheet(CSSStyleSheet* sheet)
 {
     m_activeAuthorStyleSheets.append(sheet);
 }
 
-void StyleSheetCollectionBase::appendSheetForList(StyleSheet* sheet)
+void StyleSheetCollection::appendSheetForList(StyleSheet* sheet)
 {
     m_styleSheetsForStyleSheetList.append(sheet);
 }
 
-
-StyleSheetCollection::StyleSheetCollection(TreeScope& treeScope)
-    : m_treeScope(treeScope)
-    , m_hadActiveLoadingStylesheet(false)
-    , m_usesRemUnits(false)
-{
-}
-
-void StyleSheetCollection::addStyleSheetCandidateNode(Node* node, bool createdByParser)
-{
-    if (!node->inDocument())
-        return;
-
-    // Until the <body> exists, we have no choice but to compare document positions,
-    // since styles outside of the body and head continue to be shunted into the head
-    // (and thus can shift to end up before dynamically added DOM content that is also
-    // outside the body).
-    if (createdByParser && document()->body())
-        m_styleSheetCandidateNodes.parserAdd(node);
-    else
-        m_styleSheetCandidateNodes.add(node);
-
-    if (!isHTMLStyleElement(node))
-        return;
-
-    ContainerNode* scopingNode = toHTMLStyleElement(node)->scopingNode();
-    if (!isTreeScopeRoot(scopingNode))
-        m_scopingNodesForStyleScoped.add(scopingNode);
-}
-
-void StyleSheetCollection::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
-{
-    m_styleSheetCandidateNodes.remove(node);
-
-    if (!isTreeScopeRoot(scopingNode))
-        m_scopingNodesForStyleScoped.remove(scopingNode);
-}
-
-StyleSheetCollection::StyleResolverUpdateType StyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets)
-{
-    unsigned newStyleSheetCount = newStylesheets.size();
-    unsigned oldStyleSheetCount = oldStyleSheets.size();
-    ASSERT(newStyleSheetCount >= oldStyleSheetCount);
-
-    if (!newStyleSheetCount)
-        return Reconstruct;
-
-    unsigned newIndex = 0;
-    for (unsigned oldIndex = 0; oldIndex < oldStyleSheetCount; ++oldIndex) {
-        while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) {
-            addedSheets.append(newStylesheets[newIndex]->contents());
-            if (++newIndex == newStyleSheetCount)
-                return Reconstruct;
-        }
-        if (++newIndex == newStyleSheetCount)
-            return Reconstruct;
-    }
-    bool hasInsertions = !addedSheets.isEmpty();
-    while (newIndex < newStyleSheetCount) {
-        addedSheets.append(newStylesheets[newIndex]->contents());
-        ++newIndex;
-    }
-    // If all new sheets were added at the end of the list we can just add them to existing StyleResolver.
-    // If there were insertions we need to re-add all the stylesheets so rules are ordered correctly.
-    return hasInsertions ? Reset : Additive;
-}
-
-bool StyleSheetCollection::activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets)
-{
-    // StyleSheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
-    bool hasActiveLoadingStylesheet = false;
-    unsigned newStylesheetCount = newStyleSheets.size();
-    for (unsigned i = 0; i < newStylesheetCount; ++i) {
-        if (newStyleSheets[i]->isLoading())
-            hasActiveLoadingStylesheet = true;
-    }
-    if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
-        m_hadActiveLoadingStylesheet = false;
-        return true;
-    }
-    m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
-    return false;
-}
-
-static bool styleSheetContentsHasFontFaceRule(Vector<StyleSheetContents*> sheets)
-{
-    for (unsigned i = 0; i < sheets.size(); ++i) {
-        ASSERT(sheets[i]);
-        if (sheets[i]->hasFontFaceRule())
-            return true;
-    }
-    return false;
-}
-
-static bool cssStyleSheetHasFontFaceRule(const Vector<RefPtr<CSSStyleSheet> > sheets)
-{
-    for (unsigned i = 0; i < sheets.size(); ++i) {
-        ASSERT(sheets[i]);
-        if (sheets[i]->contents()->hasFontFaceRule())
-            return true;
-    }
-    return false;
-}
-
-void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const StyleSheetCollectionBase& newCollection, StyleSheetChange& change)
-{
-    if (activeLoadingStyleSheetLoaded(newCollection.activeAuthorStyleSheets()))
-        return;
-
-    if (updateMode != AnalyzedStyleUpdate)
-        return;
-
-    // Find out which stylesheets are new.
-    Vector<StyleSheetContents*> addedSheets;
-    if (m_activeAuthorStyleSheets.size() <= newCollection.activeAuthorStyleSheets().size()) {
-        change.styleResolverUpdateType = compareStyleSheets(m_activeAuthorStyleSheets, newCollection.activeAuthorStyleSheets(), addedSheets);
-    } else {
-        StyleResolverUpdateType updateType = compareStyleSheets(newCollection.activeAuthorStyleSheets(), m_activeAuthorStyleSheets, addedSheets);
-        if (updateType != Additive) {
-            change.styleResolverUpdateType = updateType;
-        } else {
-            if (styleSheetContentsHasFontFaceRule(addedSheets)) {
-                change.styleResolverUpdateType = ResetStyleResolverAndFontSelector;
-                return;
-            }
-            // FIXME: since currently all stylesheets are re-added after reseting styleresolver,
-            // fontSelector should be always reset. After creating RuleSet for each StyleSheetContents,
-            // we can avoid appending all stylesheetcontents in reset case.
-            // So we can remove "styleSheetContentsHasFontFaceRule(newSheets)".
-            if (cssStyleSheetHasFontFaceRule(newCollection.activeAuthorStyleSheets()))
-                change.styleResolverUpdateType = ResetStyleResolverAndFontSelector;
-            else
-                change.styleResolverUpdateType = Reset;
-        }
-    }
-
-    // FIXME: If styleResolverUpdateType is Reconstruct, we should return early here since
-    // we need to recalc the whole document. It's wrong to use StyleInvalidationAnalysis since
-    // it only looks at the addedSheets.
-
-    // No point in doing the analysis work if we're just going to recalc the whole document anyways.
-    // This needs to be done after the compareStyleSheets calls above to ensure we don't throw away
-    // the StyleResolver if we don't need to.
-    if (document()->hasPendingForcedStyleRecalc())
-        return;
-
-    // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
-    if (!document()->body() || document()->hasNodesWithPlaceholderStyle())
-        return;
-    StyleInvalidationAnalysis invalidationAnalysis(addedSheets);
-    if (invalidationAnalysis.dirtiesAllStyle())
-        return;
-    invalidationAnalysis.invalidateStyle(*document());
-    change.requiresFullStyleRecalc = false;
-    return;
-}
-
-void StyleSheetCollection::clearMediaQueryRuleSetStyleSheets()
-{
-    for (size_t i = 0; i < m_activeAuthorStyleSheets.size(); ++i) {
-        StyleSheetContents* contents = m_activeAuthorStyleSheets[i]->contents();
-        if (contents->hasMediaQueries())
-            contents->clearRuleSet();
-    }
-}
-
-void StyleSheetCollection::resetAllRuleSetsInTreeScope(StyleResolver* styleResolver)
-{
-    // FIXME: If many web developers use style scoped, implement reset RuleSets in per-scoping node manner.
-    if (DocumentOrderedList* styleScopedScopingNodes = scopingNodesForStyleScoped()) {
-        for (DocumentOrderedList::iterator it = styleScopedScopingNodes->begin(); it != styleScopedScopingNodes->end(); ++it)
-            styleResolver->resetAuthorStyle(toContainerNode(*it));
-    }
-    if (ListHashSet<Node*, 4>* removedNodes = scopingNodesRemoved()) {
-        for (ListHashSet<Node*, 4>::iterator it = removedNodes->begin(); it != removedNodes->end(); ++it)
-            styleResolver->resetAuthorStyle(toContainerNode(*it));
-    }
-    styleResolver->resetAuthorStyle(toContainerNode(m_treeScope.rootNode()));
-}
-
-static bool styleSheetsUseRemUnits(const Vector<RefPtr<CSSStyleSheet> >& sheets)
-{
-    for (unsigned i = 0; i < sheets.size(); ++i) {
-        if (sheets[i]->contents()->usesRemUnits())
-            return true;
-    }
-    return false;
-}
-
-void StyleSheetCollection::updateUsesRemUnits()
-{
-    m_usesRemUnits = styleSheetsUseRemUnits(m_activeAuthorStyleSheets);
-}
-
 }
diff --git a/Source/core/dom/StyleSheetCollection.h b/Source/core/dom/StyleSheetCollection.h
index 9c90233..47b89ce 100644
--- a/Source/core/dom/StyleSheetCollection.h
+++ b/Source/core/dom/StyleSheetCollection.h
@@ -28,43 +28,31 @@
 #ifndef StyleSheetCollection_h
 #define StyleSheetCollection_h
 
-#include "core/dom/Document.h"
-#include "core/dom/DocumentOrderedList.h"
-#include "core/dom/StyleSheetScopingNodeList.h"
-#include "core/dom/TreeScope.h"
 #include "wtf/FastAllocBase.h"
-#include "wtf/HashMap.h"
-#include "wtf/ListHashSet.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-class ContainerNode;
 class CSSStyleSheet;
-class StyleEngine;
-class Node;
 class StyleSheet;
-class StyleSheetContents;
-class StyleSheetList;
 
-// FIXME: Should be in separate file and be renamed like:
-// - StyleSheetCollectionBase -> StyleSheetCollection
-// - StyleSheetCollection -> ScopeStyleSheetCollection
-//
-class StyleSheetCollectionBase {
-    WTF_MAKE_NONCOPYABLE(StyleSheetCollectionBase); WTF_MAKE_FAST_ALLOCATED;
+class StyleSheetCollection {
+    WTF_MAKE_NONCOPYABLE(StyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
 public:
-    StyleSheetCollectionBase();
-    ~StyleSheetCollectionBase();
+    friend class ActiveDocumentStyleSheetCollector;
+    friend class ImportedDocumentStyleSheetCollector;
+
+    StyleSheetCollection();
+    ~StyleSheetCollection();
 
     Vector<RefPtr<CSSStyleSheet> >& activeAuthorStyleSheets() { return m_activeAuthorStyleSheets; }
     Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList() { return m_styleSheetsForStyleSheetList; }
     const Vector<RefPtr<CSSStyleSheet> >& activeAuthorStyleSheets() const { return m_activeAuthorStyleSheets; }
     const Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList() const { return m_styleSheetsForStyleSheetList; }
 
-    void swap(StyleSheetCollectionBase&);
+    void swap(StyleSheetCollection&);
+    void swapSheetsForSheetList(Vector<RefPtr<StyleSheet> >&);
     void appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&);
     void appendActiveStyleSheet(CSSStyleSheet*);
     void appendSheetForList(StyleSheet*);
@@ -74,60 +62,6 @@
     Vector<RefPtr<CSSStyleSheet> > m_activeAuthorStyleSheets;
 };
 
-
-class StyleSheetCollection : public StyleSheetCollectionBase {
-public:
-    void addStyleSheetCandidateNode(Node*, bool createdByParser);
-    void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode);
-    bool hasStyleSheetCandidateNodes() const { return !m_styleSheetCandidateNodes.isEmpty(); }
-
-
-    bool usesRemUnits() const { return m_usesRemUnits; }
-
-    DocumentOrderedList& styleSheetCandidateNodes() { return m_styleSheetCandidateNodes; }
-    DocumentOrderedList* scopingNodesForStyleScoped() { return m_scopingNodesForStyleScoped.scopingNodes(); }
-    ListHashSet<Node*, 4>* scopingNodesRemoved() { return m_scopingNodesForStyleScoped.scopingNodesRemoved(); }
-
-    void clearMediaQueryRuleSetStyleSheets();
-
-protected:
-    explicit StyleSheetCollection(TreeScope&);
-
-    Document* document() { return m_treeScope.documentScope(); }
-
-    enum StyleResolverUpdateType {
-        Reconstruct,
-        Reset,
-        Additive,
-        ResetStyleResolverAndFontSelector
-    };
-
-    struct StyleSheetChange {
-        StyleResolverUpdateType styleResolverUpdateType;
-        bool requiresFullStyleRecalc;
-
-        StyleSheetChange()
-            : styleResolverUpdateType(Reconstruct)
-            , requiresFullStyleRecalc(true) { }
-    };
-
-    void analyzeStyleSheetChange(StyleResolverUpdateMode, const StyleSheetCollectionBase&, StyleSheetChange&);
-    void resetAllRuleSetsInTreeScope(StyleResolver*);
-    void updateUsesRemUnits();
-
-private:
-    static StyleResolverUpdateType compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets);
-    bool activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets);
-
-protected:
-    TreeScope& m_treeScope;
-    bool m_hadActiveLoadingStylesheet;
-    bool m_usesRemUnits;
-
-    DocumentOrderedList m_styleSheetCandidateNodes;
-    StyleSheetScopingNodeList m_scopingNodesForStyleScoped;
-};
-
 }
 
 #endif
diff --git a/Source/core/dom/StyleTreeScopeTracker.cpp b/Source/core/dom/StyleTreeScopeTracker.cpp
deleted file mode 100644
index 9cbedc2..0000000
--- a/Source/core/dom/StyleTreeScopeTracker.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/dom/StyleTreeScopeTracker.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/StyleEngine.h" // FIXME: This dependency is unfortuante. Probably we should flatten this class again to StyleEngine.
-#include "core/html/HTMLImport.h"
-
-namespace WebCore {
-
-StyleTreeScopeTracker::StyleTreeScopeTracker(Document& document)
-    : m_document(document)
-    , m_isDocumentMarked(true)
-{
-}
-
-void StyleTreeScopeTracker::markDocument()
-{
-    m_isDocumentMarked = true;
-    if (!HTMLImport::isMaster(&m_document))
-        m_document.import()->master()->styleEngine()->markDocumentDirty();
-}
-
-void StyleTreeScopeTracker::mark(TreeScope& scope)
-{
-    if (scope == m_document) {
-        markDocument();
-        return;
-    }
-
-    m_set.add(&scope);
-}
-
-void StyleTreeScopeTracker::clear()
-{
-    m_set.clear();
-    m_isDocumentMarked = false;
-}
-
-}
diff --git a/Source/core/dom/StyleTreeScopeTracker.h b/Source/core/dom/StyleTreeScopeTracker.h
deleted file mode 100644
index 998226a..0000000
--- a/Source/core/dom/StyleTreeScopeTracker.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef StyleTreeScopeTracker_h
-#define StyleTreeScopeTracker_h
-
-#include "wtf/ListHashSet.h"
-
-namespace WebCore {
-
-class Document;
-class TreeScope;
-
-class StyleTreeScopeTracker {
-public:
-    typedef ListHashSet<TreeScope*, 16> TreeScopeSet;
-
-    explicit StyleTreeScopeTracker(Document&);
-
-    void mark(TreeScope&);
-    void markDocument();
-    bool isSubscopeMarked() const { return m_set.isEmpty(); }
-    bool isDocumentMarked() const { return m_isDocumentMarked; }
-    void clear();
-    TreeScopeSet& subscope() { return m_set; }
-
-private:
-    Document& m_document;
-    bool m_isDocumentMarked;
-    TreeScopeSet m_set;
-};
-
-}
-
-#endif
diff --git a/Source/core/dom/TagNodeList.cpp b/Source/core/dom/TagCollection.cpp
similarity index 65%
rename from Source/core/dom/TagNodeList.cpp
rename to Source/core/dom/TagCollection.cpp
index 3944634..275d942 100644
--- a/Source/core/dom/TagNodeList.cpp
+++ b/Source/core/dom/TagCollection.cpp
@@ -22,47 +22,42 @@
  */
 
 #include "config.h"
-#include "core/dom/TagNodeList.h"
+#include "core/dom/TagCollection.h"
 
 #include "core/dom/NodeRareData.h"
 #include "wtf/Assertions.h"
 
 namespace WebCore {
 
-TagNodeList::TagNodeList(PassRefPtr<Node> rootNode, CollectionType type, const AtomicString& namespaceURI, const AtomicString& localName)
-    : LiveNodeList(rootNode, type, DoNotInvalidateOnAttributeChanges)
+TagCollection::TagCollection(ContainerNode* rootNode, CollectionType type, const AtomicString& namespaceURI, const AtomicString& localName)
+    : HTMLCollection(rootNode, type, DoesNotOverrideItemAfter)
     , m_namespaceURI(namespaceURI)
     , m_localName(localName)
 {
     ASSERT(m_namespaceURI.isNull() || !m_namespaceURI.isEmpty());
 }
 
-TagNodeList::~TagNodeList()
+TagCollection::~TagCollection()
 {
     if (m_namespaceURI == starAtom)
-        ownerNode()->nodeLists()->removeCacheWithAtomicName(this, type(), m_localName);
+        ownerNode()->nodeLists()->removeCache(this, type(), m_localName);
     else
-        ownerNode()->nodeLists()->removeCacheWithQualifiedName(this, m_namespaceURI, m_localName);
+        ownerNode()->nodeLists()->removeCache(this, m_namespaceURI, m_localName);
 }
 
-bool TagNodeList::nodeMatches(Element* testNode) const
+bool TagCollection::elementMatches(const Element& testNode) const
 {
     // Implements http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#concept-getelementsbytagnamens
-    if (m_localName != starAtom && m_localName != testNode->localName())
+    if (m_localName != starAtom && m_localName != testNode.localName())
         return false;
 
-    return m_namespaceURI == starAtom || m_namespaceURI == testNode->namespaceURI();
+    return m_namespaceURI == starAtom || m_namespaceURI == testNode.namespaceURI();
 }
 
-HTMLTagNodeList::HTMLTagNodeList(PassRefPtr<Node> rootNode, const AtomicString& localName)
-    : TagNodeList(rootNode, HTMLTagNodeListType, starAtom, localName)
+HTMLTagCollection::HTMLTagCollection(ContainerNode* rootNode, const AtomicString& localName)
+    : TagCollection(rootNode, HTMLTagCollectionType, starAtom, localName)
     , m_loweredLocalName(localName.lower())
 {
 }
 
-bool HTMLTagNodeList::nodeMatches(Element* testNode) const
-{
-    return nodeMatchesInlined(testNode);
-}
-
 } // namespace WebCore
diff --git a/Source/core/dom/TagCollection.h b/Source/core/dom/TagCollection.h
new file mode 100644
index 0000000..393741e
--- /dev/null
+++ b/Source/core/dom/TagCollection.h
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef TagCollection_h
+#define TagCollection_h
+
+#include "core/dom/Element.h"
+#include "core/html/HTMLCollection.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+// Collection that limits to a particular tag.
+class TagCollection : public HTMLCollection {
+public:
+    static PassRefPtr<TagCollection> create(ContainerNode* rootNode, const AtomicString& namespaceURI, const AtomicString& localName)
+    {
+        ASSERT(namespaceURI != starAtom);
+        return adoptRef(new TagCollection(rootNode, TagCollectionType, namespaceURI, localName));
+    }
+
+    static PassRefPtr<TagCollection> create(ContainerNode* rootNode, CollectionType type, const AtomicString& localName)
+    {
+        ASSERT_UNUSED(type, type == TagCollectionType);
+        return adoptRef(new TagCollection(rootNode, TagCollectionType, starAtom, localName));
+    }
+
+    virtual ~TagCollection();
+
+    bool elementMatches(const Element&) const;
+
+protected:
+    TagCollection(ContainerNode* rootNode, CollectionType, const AtomicString& namespaceURI, const AtomicString& localName);
+
+    AtomicString m_namespaceURI;
+    AtomicString m_localName;
+};
+
+class HTMLTagCollection FINAL : public TagCollection {
+public:
+    static PassRefPtr<HTMLTagCollection> create(ContainerNode* rootNode, CollectionType type, const AtomicString& localName)
+    {
+        ASSERT_UNUSED(type, type == HTMLTagCollectionType);
+        return adoptRef(new HTMLTagCollection(rootNode, localName));
+    }
+
+    bool elementMatches(const Element&) const;
+
+private:
+    HTMLTagCollection(ContainerNode* rootNode, const AtomicString& localName);
+
+    AtomicString m_loweredLocalName;
+};
+
+inline bool HTMLTagCollection::elementMatches(const Element& testElement) const
+{
+    // Implements http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#concept-getelementsbytagname
+    if (m_localName != starAtom) {
+        const AtomicString& localName = testElement.isHTMLElement() ? m_loweredLocalName : m_localName;
+        if (localName != testElement.localName())
+            return false;
+    }
+    ASSERT(m_namespaceURI == starAtom);
+    return true;
+}
+
+} // namespace WebCore
+
+#endif // TagCollection_h
diff --git a/Source/core/dom/TagNodeList.h b/Source/core/dom/TagNodeList.h
deleted file mode 100644
index 8ec4193..0000000
--- a/Source/core/dom/TagNodeList.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 1999 Antti Koivisto (koivisto@kde.org)
- *           (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef TagNodeList_h
-#define TagNodeList_h
-
-#include "core/dom/Element.h"
-#include "core/dom/LiveNodeList.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-// NodeList that limits to a particular tag.
-class TagNodeList : public LiveNodeList {
-public:
-    static PassRefPtr<TagNodeList> create(PassRefPtr<Node> rootNode, const AtomicString& namespaceURI, const AtomicString& localName)
-    {
-        ASSERT(namespaceURI != starAtom);
-        return adoptRef(new TagNodeList(rootNode, TagNodeListType, namespaceURI, localName));
-    }
-
-    static PassRefPtr<TagNodeList> create(PassRefPtr<Node> rootNode, CollectionType type, const AtomicString& localName)
-    {
-        ASSERT_UNUSED(type, type == TagNodeListType);
-        return adoptRef(new TagNodeList(rootNode, TagNodeListType, starAtom, localName));
-    }
-
-    virtual ~TagNodeList();
-
-protected:
-    TagNodeList(PassRefPtr<Node> rootNode, CollectionType, const AtomicString& namespaceURI, const AtomicString& localName);
-
-    virtual bool nodeMatches(Element*) const;
-
-    AtomicString m_namespaceURI;
-    AtomicString m_localName;
-};
-
-class HTMLTagNodeList FINAL : public TagNodeList {
-public:
-    static PassRefPtr<HTMLTagNodeList> create(PassRefPtr<Node> rootNode, CollectionType type, const AtomicString& localName)
-    {
-        ASSERT_UNUSED(type, type == HTMLTagNodeListType);
-        return adoptRef(new HTMLTagNodeList(rootNode, localName));
-    }
-
-    bool nodeMatchesInlined(Element*) const;
-
-private:
-    HTMLTagNodeList(PassRefPtr<Node> rootNode, const AtomicString& localName);
-
-    virtual bool nodeMatches(Element*) const OVERRIDE;
-
-    AtomicString m_loweredLocalName;
-};
-
-inline bool HTMLTagNodeList::nodeMatchesInlined(Element* testNode) const
-{
-    // Implements http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#concept-getelementsbytagname
-    if (m_localName != starAtom) {
-        const AtomicString& localName = testNode->isHTMLElement() ? m_loweredLocalName : m_localName;
-        if (localName != testNode->localName())
-            return false;
-    }
-    ASSERT(m_namespaceURI == starAtom);
-    return true;
-}
-
-} // namespace WebCore
-
-#endif // TagNodeList_h
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index f43f6ec..cf67098 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -28,10 +28,11 @@
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/dom/NodeRenderingContext.h"
+#include "core/dom/NodeRenderingTraversal.h"
 #include "core/dom/NodeTraversal.h"
-#include "core/events/ScopedEventQueue.h"
+#include "core/dom/RenderTreeBuilder.h"
 #include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/ScopedEventQueue.h"
 #include "core/rendering/RenderCombineText.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/svg/RenderSVGInlineText.h"
@@ -239,7 +240,7 @@
     return cloneWithData(data());
 }
 
-bool Text::textRendererIsNeeded(const NodeRenderingContext& context)
+bool Text::textRendererIsNeeded(const RenderStyle& style, const RenderObject& parent)
 {
     if (isEditingText())
         return true;
@@ -247,39 +248,38 @@
     if (!length())
         return false;
 
-    if (context.style()->display() == NONE)
+    if (style.display() == NONE)
         return false;
 
     if (!containsOnlyWhitespace())
         return true;
 
-    RenderObject* parent = context.parentRenderer();
-    if (!parent->canHaveWhitespaceChildren())
+    if (!parent.canHaveWhitespaceChildren())
         return false;
 
-    if (context.style()->preserveNewline()) // pre/pre-wrap/pre-line always make renderers.
+    if (style.preserveNewline()) // pre/pre-wrap/pre-line always make renderers.
         return true;
 
-    RenderObject* prev = context.previousRenderer();
+    const RenderObject* prev = NodeRenderingTraversal::previousSiblingRenderer(this);
     if (prev && prev->isBR()) // <span><br/> <br/></span>
         return false;
 
-    if (parent->isRenderInline()) {
+    if (parent.isRenderInline()) {
         // <span><div/> <div/></span>
         if (prev && !prev->isInline())
             return false;
     } else {
-        if (parent->isRenderBlock() && !parent->childrenInline() && (!prev || !prev->isInline()))
+        if (parent.isRenderBlock() && !parent.childrenInline() && (!prev || !prev->isInline()))
             return false;
 
         // Avoiding creation of a Renderer for the text node is a non-essential memory optimization.
         // So to avoid blowing up on very wide DOMs, we limit the number of siblings to visit.
         unsigned maxSiblingsToVisit = 50;
 
-        RenderObject* first = parent->firstChild();
+        RenderObject* first = parent.firstChild();
         while (first && first->isFloatingOrOutOfFlowPositioned() && maxSiblingsToVisit--)
             first = first->nextSibling();
-        if (!first || context.nextRenderer() == first)
+        if (!first || NodeRenderingTraversal::nextSiblingRenderer(this) == first)
             // Whitespace at the start of a block just goes away.  Don't even
             // make a render object for this text.
             return false;
@@ -306,7 +306,7 @@
 
 void Text::attach(const AttachContext& context)
 {
-    NodeRenderingContext(this, context.resolvedStyle).createRendererForTextIfNeeded();
+    RenderTreeBuilder(this, context.resolvedStyle).createRendererForTextIfNeeded();
     CharacterData::attach(context);
 }
 
@@ -339,7 +339,7 @@
     if (!inActiveDocument())
         return;
     RenderText* textRenderer = toRenderText(renderer());
-    if (!textRenderer || !textRendererIsNeeded(NodeRenderingContext(this, textRenderer->style()))) {
+    if (!textRenderer || !textRendererIsNeeded(*textRenderer->style(), *textRenderer->parent())) {
         lazyReattachIfAttached();
         // FIXME: Editing should be updated so this is not neccesary.
         if (recalcStyleBehavior == DeprecatedRecalcStyleImmediatlelyForEditing)
@@ -349,11 +349,6 @@
     textRenderer->setTextWithOffset(dataImpl(), offsetOfReplacedData, lengthOfReplacedData);
 }
 
-bool Text::childTypeAllowed(NodeType) const
-{
-    return false;
-}
-
 PassRefPtr<Text> Text::cloneWithData(const String& data)
 {
     return create(document(), data);
diff --git a/Source/core/dom/Text.h b/Source/core/dom/Text.h
index 79540c0..5408c4c 100644
--- a/Source/core/dom/Text.h
+++ b/Source/core/dom/Text.h
@@ -49,7 +49,7 @@
     PassRefPtr<Text> replaceWholeText(const String&);
 
     void recalcTextStyle(StyleRecalcChange, Text* nextTextSibling);
-    bool textRendererIsNeeded(const NodeRenderingContext&);
+    bool textRendererIsNeeded(const RenderStyle&, const RenderObject& parent);
     RenderText* createTextRenderer(RenderStyle*);
     void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, RecalcStyleBehavior = DoNotRecalcStyle);
 
@@ -68,14 +68,13 @@
 private:
     virtual String nodeName() const OVERRIDE;
     virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE FINAL;
-    virtual bool childTypeAllowed(NodeType) const OVERRIDE;
 
     bool needsWhitespaceRenderer();
 
     virtual PassRefPtr<Text> cloneWithData(const String&);
 
 #ifndef NDEBUG
-    virtual void formatForDebugger(char* buffer, unsigned length) const;
+    virtual void formatForDebugger(char* buffer, unsigned length) const OVERRIDE;
 #endif
 };
 
diff --git a/Source/core/dom/TextLinkColors.cpp b/Source/core/dom/TextLinkColors.cpp
index 42b61c7..b2d5b46 100644
--- a/Source/core/dom/TextLinkColors.cpp
+++ b/Source/core/dom/TextLinkColors.cpp
@@ -54,7 +54,7 @@
 
 void TextLinkColors::resetActiveLinkColor()
 {
-    m_activeLinkColor.setNamedColor("red");
+    m_activeLinkColor = Color(255, 0, 0);
 }
 
 static Color colorForCSSValue(CSSValueID cssValueId)
@@ -110,7 +110,8 @@
     case CSSValueWebkitActivelink:
         return activeLinkColor();
     case CSSValueWebkitFocusRingColor:
-        return RenderTheme::focusRingColor();
+        return RenderTheme::theme().focusRingColor();
+    case CSSValueInvert: // We don't support outline-color: invert
     case CSSValueCurrentcolor:
         return currentColor;
     default:
diff --git a/Source/core/dom/TouchController.cpp b/Source/core/dom/TouchController.cpp
deleted file mode 100644
index a24bc81..0000000
--- a/Source/core/dom/TouchController.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2013 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * 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 THE COPYRIGHT HOLDERS ``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 THE COPYRIGHT OWNER 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.
- */
-
-#include "config.h"
-#include "core/dom/TouchController.h"
-
-#include "core/dom/Document.h"
-#include "core/events/ThreadLocalEventNames.h"
-#include "core/events/TouchEvent.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
-#include "core/frame/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/scrolling/ScrollingCoordinator.h"
-
-namespace WebCore {
-
-TouchController::TouchController(Document* document)
-    : DOMWindowLifecycleObserver(document->domWindow())
-    , DocumentLifecycleObserver(document)
-{
-}
-
-TouchController::~TouchController()
-{
-}
-
-const char* TouchController::supplementName()
-{
-    return "TouchController";
-}
-
-TouchController* TouchController::from(Document* document)
-{
-    TouchController* controller = static_cast<TouchController*>(DocumentSupplement::from(document, supplementName()));
-    if (!controller) {
-        controller = new TouchController(document);
-        DocumentSupplement::provideTo(document, supplementName(), adoptPtr(controller));
-    }
-    return controller;
-}
-
-void TouchController::didAddTouchEventHandler(Document* document, Node* handler)
-{
-    if (!m_touchEventTargets)
-        m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
-    m_touchEventTargets->add(handler);
-    if (Document* parent = document->parentDocument()) {
-        TouchController::from(parent)->didAddTouchEventHandler(parent, document);
-        return;
-    }
-    if (Page* page = document->page()) {
-        if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
-            scrollingCoordinator->touchEventTargetRectsDidChange(document);
-        if (m_touchEventTargets->size() == 1)
-            page->chrome().client().needTouchEvents(true);
-    }
-}
-
-void TouchController::didRemoveTouchEventHandler(Document* document, Node* handler)
-{
-    if (!m_touchEventTargets)
-        return;
-    ASSERT(m_touchEventTargets->contains(handler));
-    m_touchEventTargets->remove(handler);
-    if (Document* parent = document->parentDocument()) {
-        TouchController::from(parent)->didRemoveTouchEventHandler(parent, document);
-        return;
-    }
-
-    Page* page = document->page();
-    if (!page)
-        return;
-    if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
-        scrollingCoordinator->touchEventTargetRectsDidChange(document);
-    if (m_touchEventTargets->size())
-        return;
-    for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (frame->document() && TouchController::from(frame->document())->hasTouchEventHandlers())
-            return;
-    }
-    page->chrome().client().needTouchEvents(false);
-}
-
-void TouchController::didRemoveEventTargetNode(Document* document, Node* handler)
-{
-    if (m_touchEventTargets && !m_touchEventTargets->isEmpty()) {
-        if (handler == document)
-            m_touchEventTargets->clear();
-        else
-            m_touchEventTargets->removeAll(handler);
-        Document* parent = document->parentDocument();
-        if (m_touchEventTargets->isEmpty() && parent)
-            TouchController::from(parent)->didRemoveEventTargetNode(parent, document);
-    }
-}
-
-void TouchController::didAddEventListener(DOMWindow* window, const AtomicString& eventType)
-{
-    if (isTouchEventType(eventType)) {
-        Document* document = window->document();
-        didAddTouchEventHandler(document, document);
-    }
-}
-
-void TouchController::didRemoveEventListener(DOMWindow* window, const AtomicString& eventType)
-{
-    if (isTouchEventType(eventType)) {
-        Document* document = window->document();
-        didRemoveTouchEventHandler(document, document);
-    }
-}
-
-void TouchController::didRemoveAllEventListeners(DOMWindow* window)
-{
-    if (Document* document = window->document())
-        didRemoveEventTargetNode(document, document);
-}
-
-void TouchController::documentWasDetached()
-{
-    Document* document = static_cast<Document*>(executionContext());
-    Document* parentDocument = document->parentDocument();
-
-    if (parentDocument) {
-        TouchController* parentController = TouchController::from(parentDocument);
-        if (parentController->hasTouchEventHandlers())
-            parentController->didRemoveEventTargetNode(parentDocument, document);
-    }
-}
-
-void TouchController::documentBeingDestroyed()
-{
-    Document* document = static_cast<Document*>(executionContext());
-
-    if (Document* ownerDocument = document->ownerDocument())
-        TouchController::from(ownerDocument)->didRemoveEventTargetNode(ownerDocument, document);
-}
-
-} // namespace WebCore
diff --git a/Source/core/dom/TouchController.h b/Source/core/dom/TouchController.h
deleted file mode 100644
index 8ce5e13..0000000
--- a/Source/core/dom/TouchController.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
-* Copyright (C) 2013 Google, Inc. All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions
-* are met:
-*  * Redistributions of source code must retain the above copyright
-*    notice, this list of conditions and the following disclaimer.
-*  * 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 THE COPYRIGHT HOLDERS ``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 THE COPYRIGHT OWNER 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.
-*/
-
-#ifndef TouchController_h
-#define TouchController_h
-
-#include "core/dom/DocumentLifecycleObserver.h"
-#include "core/events/Event.h"
-#include "core/dom/Node.h"
-#include "core/frame/DOMWindowLifecycleObserver.h"
-#include "platform/Supplementable.h"
-#include "wtf/HashSet.h"
-
-namespace WebCore {
-
-typedef HashCountedSet<Node*> TouchEventTargetSet;
-
-class Document;
-class DOMWindow;
-
-class TouchController : public DocumentSupplement, public DOMWindowLifecycleObserver, public DocumentLifecycleObserver {
-
-public:
-    virtual ~TouchController();
-
-    static const char* supplementName();
-    static TouchController* from(Document*);
-
-    bool hasTouchEventHandlers() const { return m_touchEventTargets ? m_touchEventTargets->size() : false; }
-
-    void didAddTouchEventHandler(Document*, Node*);
-    void didRemoveTouchEventHandler(Document*, Node*);
-    void didRemoveEventTargetNode(Document*, Node*);
-
-    const TouchEventTargetSet* touchEventTargets() const { return m_touchEventTargets.get(); }
-
-    // Inherited from DOMWindowLifecycleObserver
-    virtual void didAddEventListener(DOMWindow*, const AtomicString&) OVERRIDE;
-    virtual void didRemoveEventListener(DOMWindow*, const AtomicString&) OVERRIDE;
-    virtual void didRemoveAllEventListeners(DOMWindow*) OVERRIDE;
-
-    // Inherited from DocumentLifecycleObserver
-    virtual void documentWasDetached() OVERRIDE;
-    virtual void documentBeingDestroyed() OVERRIDE;
-
-private:
-    explicit TouchController(Document*);
-
-    OwnPtr<TouchEventTargetSet> m_touchEventTargets;
-};
-
-} // namespace WebCore
-
-#endif // TouchController_h
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index 3e0494c..bd2bcb4 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -33,6 +33,7 @@
 #include "core/dom/Element.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/IdTargetObserverRegistry.h"
+#include "core/dom/NodeRenderStyle.h"
 #include "core/dom/TreeScopeAdopter.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -52,53 +53,34 @@
 
 namespace WebCore {
 
-struct SameSizeAsTreeScope {
-    virtual ~SameSizeAsTreeScope();
-    void* pointers[8];
-    int ints[1];
-};
-
-COMPILE_ASSERT(sizeof(TreeScope) == sizeof(SameSizeAsTreeScope), treescope_should_stay_small);
-
 using namespace HTMLNames;
 
-TreeScope::TreeScope(ContainerNode* rootNode, Document* document)
+TreeScope::TreeScope(ContainerNode& rootNode, Document& document)
     : m_rootNode(rootNode)
-    , m_documentScope(document)
-    , m_parentTreeScope(document)
+    , m_document(&document)
+    , m_parentTreeScope(&document)
     , m_guardRefCount(0)
     , m_idTargetObserverRegistry(IdTargetObserverRegistry::create())
 {
-    ASSERT(rootNode);
-    ASSERT(document);
     ASSERT(rootNode != document);
     m_parentTreeScope->guardRef();
-    m_rootNode->setTreeScope(this);
+    m_rootNode.setTreeScope(this);
 }
 
-TreeScope::TreeScope(Document* document)
+TreeScope::TreeScope(Document& document)
     : m_rootNode(document)
-    , m_documentScope(document)
+    , m_document(&document)
     , m_parentTreeScope(0)
     , m_guardRefCount(0)
     , m_idTargetObserverRegistry(IdTargetObserverRegistry::create())
 {
-    ASSERT(document);
-    m_rootNode->setTreeScope(this);
-}
-
-TreeScope::TreeScope()
-    : m_rootNode(0)
-    , m_documentScope(0)
-    , m_parentTreeScope(0)
-    , m_guardRefCount(0)
-{
+    m_rootNode.setTreeScope(this);
 }
 
 TreeScope::~TreeScope()
 {
     ASSERT(!m_guardRefCount);
-    m_rootNode->setTreeScope(noDocumentInstance());
+    m_rootNode.setTreeScope(0);
 
     if (m_selection) {
         m_selection->clearTreeScope();
@@ -109,9 +91,27 @@
         m_parentTreeScope->guardDeref();
 }
 
+TreeScope* TreeScope::olderShadowRootOrParentTreeScope() const
+{
+    if (rootNode().isShadowRoot()) {
+        if (ShadowRoot* olderShadowRoot = toShadowRoot(rootNode()).olderShadowRoot())
+            return olderShadowRoot;
+    }
+    return parentTreeScope();
+}
+
+bool TreeScope::isInclusiveOlderSiblingShadowRootOrAncestorTreeScopeOf(const TreeScope& scope) const
+{
+    for (const TreeScope* current = &scope; current; current = current->olderShadowRootOrParentTreeScope()) {
+        if (current == this)
+            return true;
+    }
+    return false;
+}
+
 bool TreeScope::rootNodeHasTreeSharedParent() const
 {
-    return rootNode()->hasTreeSharedParent();
+    return rootNode().hasTreeSharedParent();
 }
 
 void TreeScope::destroyTreeScopeData()
@@ -121,24 +121,16 @@
     m_labelsByForAttribute.clear();
 }
 
-void TreeScope::clearDocumentScope()
-{
-    ASSERT(rootNode()->isDocumentNode());
-    m_documentScope = 0;
-}
-
-void TreeScope::setParentTreeScope(TreeScope* newParentScope)
+void TreeScope::setParentTreeScope(TreeScope& newParentScope)
 {
     // A document node cannot be re-parented.
-    ASSERT(!rootNode()->isDocumentNode());
-    // Every scope other than document needs a parent scope.
-    ASSERT(newParentScope);
+    ASSERT(!rootNode().isDocumentNode());
 
-    newParentScope->guardRef();
+    newParentScope.guardRef();
     if (m_parentTreeScope)
         m_parentTreeScope->guardDeref();
-    m_parentTreeScope = newParentScope;
-    setDocumentScope(newParentScope->documentScope());
+    m_parentTreeScope = &newParentScope;
+    setDocument(newParentScope.document());
 }
 
 Element* TreeScope::getElementById(const AtomicString& elementId) const
@@ -150,6 +142,16 @@
     return m_elementsById->getElementById(elementId.impl(), this);
 }
 
+const Vector<Element*>& TreeScope::getAllElementsById(const AtomicString& elementId) const
+{
+    DEFINE_STATIC_LOCAL(Vector<Element*>, emptyVector, ());
+    if (elementId.isEmpty())
+        return emptyVector;
+    if (!m_elementsById)
+        return emptyVector;
+    return m_elementsById->getAllElementsById(elementId.impl(), this);
+}
+
 void TreeScope::addElementById(const AtomicString& elementId, Element* element)
 {
     if (!m_elementsById)
@@ -208,44 +210,38 @@
         return 0;
     size_t hashPos = url.find('#');
     String name = (hashPos == kNotFound ? url : url.substring(hashPos + 1)).impl();
-    if (rootNode()->document().isHTMLDocument())
+    if (rootNode().document().isHTMLDocument())
         return toHTMLMapElement(m_imageMapsByName->getElementByLowercasedMapName(AtomicString(name.lower()).impl(), this));
     return toHTMLMapElement(m_imageMapsByName->getElementByMapName(AtomicString(name).impl(), this));
 }
 
-RenderObject* rendererFromPoint(Document* document, int x, int y, LayoutPoint* localPoint)
+HitTestResult hitTestInDocument(const Document* document, int x, int y)
 {
     Frame* frame = document->frame();
 
     if (!frame)
-        return 0;
+        return HitTestResult();
     FrameView* frameView = frame->view();
     if (!frameView)
-        return 0;
+        return HitTestResult();
 
     float scaleFactor = frame->pageZoomFactor();
     IntPoint point = roundedIntPoint(FloatPoint(x * scaleFactor  + frameView->scrollX(), y * scaleFactor + frameView->scrollY()));
 
     if (!frameView->visibleContentRect().contains(point))
-        return 0;
+        return HitTestResult();
 
     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
     HitTestResult result(point);
     document->renderView()->hitTest(request, result);
-
-    if (localPoint)
-        *localPoint = result.localPoint();
-
-    return result.renderer();
+    return result;
 }
 
 Element* TreeScope::elementFromPoint(int x, int y) const
 {
-    RenderObject* renderer = rendererFromPoint(&rootNode()->document(), x, y);
-    if (!renderer)
-        return 0;
-    Node* node = renderer->node();
-    if (!node)
+    HitTestResult result = hitTestInDocument(&rootNode().document(), x, y);
+    Node* node = result.innerNode();
+    if (!node || node->isDocumentNode())
         return 0;
     if (node->isPseudoElement() || node->isTextNode())
         node = node->parentOrShadowHostNode();
@@ -276,9 +272,8 @@
     if (!m_labelsByForAttribute) {
         // Populate the map on first access.
         m_labelsByForAttribute = adoptPtr(new DocumentOrderedMap);
-        ASSERT(rootNode());
-        for (Element* element = ElementTraversal::firstWithin(*rootNode()); element; element = ElementTraversal::next(*element)) {
-            if (isHTMLLabelElement(element)) {
+        for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::next(*element)) {
+            if (element->hasTagName(labelTag)) {
                 HTMLLabelElement* label = toHTMLLabelElement(element);
                 const AtomicString& forValue = label->fastGetAttribute(forAttr);
                 if (!forValue.isEmpty())
@@ -292,7 +287,7 @@
 
 DOMSelection* TreeScope::getSelection() const
 {
-    if (!rootNode()->document().frame())
+    if (!rootNode().document().frame())
         return 0;
 
     if (m_selection)
@@ -309,13 +304,12 @@
 {
     if (name.isEmpty())
         return 0;
-    if (Element* element = getElementById(name))
+    if (Element* element = getElementById(AtomicString(name)))
         return element;
-    ASSERT(rootNode());
-    for (Element* element = ElementTraversal::firstWithin(*rootNode()); element; element = ElementTraversal::next(*element)) {
-        if (isHTMLAnchorElement(element)) {
+    for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::next(*element)) {
+        if (element->hasTagName(aTag)) {
             HTMLAnchorElement* anchor = toHTMLAnchorElement(element);
-            if (rootNode()->document().inQuirksMode()) {
+            if (rootNode().document().inQuirksMode()) {
                 // Quirks mode, case insensitive comparison of names.
                 if (equalIgnoringCase(anchor->name(), name))
                     return anchor;
@@ -331,7 +325,7 @@
 
 bool TreeScope::applyAuthorStyles() const
 {
-    return !rootNode()->isShadowRoot() || toShadowRoot(rootNode())->applyAuthorStyles();
+    return !rootNode().isShadowRoot() || toShadowRoot(rootNode()).applyAuthorStyles();
 }
 
 void TreeScope::adoptIfNeeded(Node& node)
@@ -355,7 +349,7 @@
 
 Element* TreeScope::adjustedFocusedElement() const
 {
-    Document& document = rootNode()->document();
+    Document& document = rootNode().document();
     Element* element = document.focusedElement();
     if (!element && document.page())
         element = focusedFrameOwnerElement(document.page()->focusController().focusedFrame(), document.frame());
@@ -398,12 +392,12 @@
         const TreeScope* child1 = chain1[--index1];
         const TreeScope* child2 = chain2[--index2];
         if (child1 != child2) {
-            Node* shadowHost1 = child1->rootNode()->parentOrShadowHostNode();
-            Node* shadowHost2 = child2->rootNode()->parentOrShadowHostNode();
+            Node* shadowHost1 = child1->rootNode().parentOrShadowHostNode();
+            Node* shadowHost2 = child2->rootNode().parentOrShadowHostNode();
             if (shadowHost1 != shadowHost2)
                 return shadowHost1->compareDocumentPositionInternal(shadowHost2, Node::TreatShadowTreesAsDisconnected);
 
-            for (const ShadowRoot* child = toShadowRoot(child2->rootNode())->olderShadowRoot(); child; child = child->olderShadowRoot())
+            for (const ShadowRoot* child = toShadowRoot(child2->rootNode()).olderShadowRoot(); child; child = child->olderShadowRoot())
                 if (child == child1)
                     return Node::DOCUMENT_POSITION_FOLLOWING;
 
@@ -454,21 +448,18 @@
 #if SECURITY_ASSERT_ENABLED
 bool TreeScope::deletionHasBegun()
 {
-    return rootNode() && rootNode()->m_deletionHasBegun;
+    return rootNode().m_deletionHasBegun;
 }
 
 void TreeScope::beginDeletion()
 {
-    ASSERT(this != noDocumentInstance());
-    rootNode()->m_deletionHasBegun = true;
+    rootNode().m_deletionHasBegun = true;
 }
 #endif
 
 int TreeScope::refCount() const
 {
-    if (Node* root = rootNode())
-        return root->refCount();
-    return 0;
+    return rootNode().refCount();
 }
 
 bool TreeScope::isInclusiveAncestorOf(const TreeScope& scope) const
@@ -485,9 +476,8 @@
     if (key.isEmpty())
         return 0;
     Element* result = 0;
-    Node* root = rootNode();
-    ASSERT(root);
-    for (Element* element = ElementTraversal::firstWithin(*root); element; element = ElementTraversal::next(*element, root)) {
+    Node& root = rootNode();
+    for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(*element, &root)) {
         if (equalIgnoringCase(element->fastGetAttribute(accesskeyAttr), key))
             result = element;
         for (ShadowRoot* shadowRoot = element->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
@@ -498,4 +488,15 @@
     return result;
 }
 
+void TreeScope::setNeedsStyleRecalcForViewportUnits()
+{
+    for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
+        for (ShadowRoot* root = element->youngestShadowRoot(); root; root = root->olderShadowRoot())
+            root->setNeedsStyleRecalcForViewportUnits();
+        RenderStyle* style = element->renderStyle();
+        if (style && style->hasViewportUnits())
+            element->setNeedsStyleRecalc(LocalStyleChange);
+    }
+}
+
 } // namespace WebCore
diff --git a/Source/core/dom/TreeScope.h b/Source/core/dom/TreeScope.h
index 26154da..6a7703a 100644
--- a/Source/core/dom/TreeScope.h
+++ b/Source/core/dom/TreeScope.h
@@ -39,6 +39,7 @@
 class Element;
 class HTMLLabelElement;
 class HTMLMapElement;
+class HitTestResult;
 class LayoutPoint;
 class IdTargetObserverRegistry;
 class Node;
@@ -48,21 +49,25 @@
 // so that the Node destructor no longer does problematic NodeList cache manipulation in
 // the destructor.
 class TreeScope {
-    friend class Document;
-    friend class TreeScopeAdopter;
-
 public:
     TreeScope* parentTreeScope() const { return m_parentTreeScope; }
-    void setParentTreeScope(TreeScope*);
+
+    TreeScope* olderShadowRootOrParentTreeScope() const;
+    bool isInclusiveOlderSiblingShadowRootOrAncestorTreeScopeOf(const TreeScope&) const;
 
     Element* adjustedFocusedElement() const;
     Element* getElementById(const AtomicString&) const;
+    const Vector<Element*>& getAllElementsById(const AtomicString&) const;
     bool hasElementWithId(StringImpl* id) const;
     bool containsMultipleElementsWithId(const AtomicString& id) const;
     void addElementById(const AtomicString& elementId, Element*);
     void removeElementById(const AtomicString& elementId, Element*);
 
-    Document* documentScope() const { return m_documentScope; }
+    Document& document() const
+    {
+        ASSERT(m_document);
+        return *m_document;
+    }
 
     Node* ancestorInThisScope(Node*) const;
 
@@ -92,16 +97,10 @@
     // Used by the basic DOM mutation methods (e.g., appendChild()).
     void adoptIfNeeded(Node&);
 
-    Node* rootNode() const { return m_rootNode; }
+    Node& rootNode() const { return m_rootNode; }
 
     IdTargetObserverRegistry& idTargetObserverRegistry() const { return *m_idTargetObserverRegistry.get(); }
 
-    static TreeScope* noDocumentInstance()
-    {
-        DEFINE_STATIC_LOCAL(TreeScope, instance, ());
-        return &instance;
-    }
-
     // Nodes belonging to this scope hold guard references -
     // these are enough to keep the scope from being destroyed, but
     // not enough to keep it from removing its children. This allows a
@@ -117,7 +116,7 @@
     {
         ASSERT(!deletionHasBegun());
         --m_guardRefCount;
-        if (!m_guardRefCount && !refCount() && this != noDocumentInstance() && !rootNodeHasTreeSharedParent()) {
+        if (!m_guardRefCount && !refCount() && !rootNodeHasTreeSharedParent()) {
             beginDeletion();
             delete this;
         }
@@ -131,24 +130,19 @@
     Element* getElementByAccessKey(const String& key) const;
 
 protected:
-    TreeScope(ContainerNode*, Document*);
-    TreeScope(Document*);
+    TreeScope(ContainerNode&, Document&);
+    TreeScope(Document&);
     virtual ~TreeScope();
 
     void destroyTreeScopeData();
-    void clearDocumentScope();
-    void setDocumentScope(Document* document)
-    {
-        ASSERT(document);
-        ASSERT(this != noDocumentInstance());
-        m_documentScope = document;
-    }
+    void setDocument(Document& document) { m_document = &document; }
+    void setParentTreeScope(TreeScope&);
 
     bool hasGuardRefCount() const { return m_guardRefCount; }
 
-private:
-    TreeScope();
+    void setNeedsStyleRecalcForViewportUnits();
 
+private:
     virtual void dispose() { }
 
     int refCount() const;
@@ -162,8 +156,8 @@
 
     bool rootNodeHasTreeSharedParent() const;
 
-    Node* m_rootNode;
-    Document* m_documentScope;
+    Node& m_rootNode;
+    Document* m_document;
     TreeScope* m_parentTreeScope;
     int m_guardRefCount;
 
@@ -194,7 +188,7 @@
 inline bool operator!=(const TreeScope& a, const TreeScope* b) { return !(a == b); }
 inline bool operator!=(const TreeScope* a, const TreeScope& b) { return !(a == b); }
 
-RenderObject* rendererFromPoint(Document*, int x, int y, LayoutPoint* localPoint = 0);
+HitTestResult hitTestInDocument(const Document*, int x, int y);
 TreeScope* commonTreeScope(Node*, Node*);
 
 } // namespace WebCore
diff --git a/Source/core/dom/TreeScopeAdopter.cpp b/Source/core/dom/TreeScopeAdopter.cpp
index 366b4af..109d47c 100644
--- a/Source/core/dom/TreeScopeAdopter.cpp
+++ b/Source/core/dom/TreeScopeAdopter.cpp
@@ -44,18 +44,17 @@
     // that element may contain stale data as changes made to it will have updated the DOMTreeVersion
     // of the document it was moved to. By increasing the DOMTreeVersion of the donating document here
     // we ensure that the collection cache will be invalidated as needed when the element is moved back.
-    Document* oldDocument = m_oldScope.documentScope();
-    ASSERT(oldDocument);
-    Document* newDocument = m_newScope.documentScope();
+    Document& oldDocument = m_oldScope.document();
+    Document& newDocument = m_newScope.document();
     bool willMoveToNewDocument = oldDocument != newDocument;
     if (willMoveToNewDocument)
-        oldDocument->incDOMTreeVersion();
+        oldDocument.incDOMTreeVersion();
 
     for (Node* node = &root; node; node = NodeTraversal::next(*node, &root)) {
         updateTreeScope(*node);
 
         if (willMoveToNewDocument)
-            moveNodeToNewDocument(*node, *oldDocument, newDocument);
+            moveNodeToNewDocument(*node, oldDocument, newDocument);
         else if (node->hasRareData()) {
             NodeRareData* rareData = node->rareData();
             if (rareData->nodeLists())
@@ -72,17 +71,18 @@
         }
 
         for (ShadowRoot* shadow = node->youngestShadowRoot(); shadow; shadow = shadow->olderShadowRoot()) {
-            shadow->setParentTreeScope(&m_newScope);
+            shadow->setParentTreeScope(m_newScope);
             if (willMoveToNewDocument)
-                moveTreeToNewDocument(*shadow, *oldDocument, newDocument);
+                moveTreeToNewDocument(*shadow, oldDocument, newDocument);
         }
     }
 
     m_oldScope.guardDeref();
 }
 
-void TreeScopeAdopter::moveTreeToNewDocument(Node& root, Document& oldDocument, Document* newDocument) const
+void TreeScopeAdopter::moveTreeToNewDocument(Node& root, Document& oldDocument, Document& newDocument) const
 {
+    ASSERT(oldDocument != newDocument);
     for (Node* node = &root; node; node = NodeTraversal::next(*node, &root)) {
         moveNodeToNewDocument(*node, oldDocument, newDocument);
         for (ShadowRoot* shadow = node->youngestShadowRoot(); shadow; shadow = shadow->olderShadowRoot())
@@ -111,20 +111,20 @@
     node.setTreeScope(&m_newScope);
 }
 
-inline void TreeScopeAdopter::moveNodeToNewDocument(Node& node, Document& oldDocument, Document* newDocument) const
+inline void TreeScopeAdopter::moveNodeToNewDocument(Node& node, Document& oldDocument, Document& newDocument) const
 {
-    ASSERT(!node.inDocument() || oldDocument != newDocument);
+    ASSERT(oldDocument != newDocument);
 
     if (node.hasRareData()) {
         NodeRareData* rareData = node.rareData();
         if (rareData->nodeLists())
-            rareData->nodeLists()->adoptDocument(&oldDocument, newDocument);
+            rareData->nodeLists()->adoptDocument(oldDocument, newDocument);
     }
 
-    oldDocument.moveNodeIteratorsToNewDocument(&node, newDocument);
+    oldDocument.moveNodeIteratorsToNewDocument(node, newDocument);
 
     if (node.isShadowRoot())
-        toShadowRoot(node).setDocumentScope(newDocument);
+        toShadowRoot(node).setDocument(newDocument);
 
 #ifndef NDEBUG
     didMoveToNewDocumentWasCalled = false;
diff --git a/Source/core/dom/TreeScopeAdopter.h b/Source/core/dom/TreeScopeAdopter.h
index 17742ba..ad4de3b 100644
--- a/Source/core/dom/TreeScopeAdopter.h
+++ b/Source/core/dom/TreeScopeAdopter.h
@@ -47,8 +47,8 @@
 private:
     void updateTreeScope(Node&) const;
     void moveTreeToNewScope(Node&) const;
-    void moveTreeToNewDocument(Node&, Document& oldDocument, Document* newDocument) const;
-    void moveNodeToNewDocument(Node&, Document& oldDocument, Document* newDocument) const;
+    void moveTreeToNewDocument(Node&, Document& oldDocument, Document& newDocument) const;
+    void moveNodeToNewDocument(Node&, Document& oldDocument, Document& newDocument) const;
 
     Node& m_toAdopt;
     TreeScope& m_newScope;
diff --git a/Source/core/dom/TreeScopeStyleSheetCollection.cpp b/Source/core/dom/TreeScopeStyleSheetCollection.cpp
new file mode 100644
index 0000000..ea7eef7
--- /dev/null
+++ b/Source/core/dom/TreeScopeStyleSheetCollection.cpp
@@ -0,0 +1,221 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/dom/TreeScopeStyleSheetCollection.h"
+
+#include "core/css/CSSStyleSheet.h"
+#include "core/css/StyleInvalidationAnalysis.h"
+#include "core/css/StyleRuleImport.h"
+#include "core/css/StyleSheetContents.h"
+#include "core/css/resolver/StyleResolver.h"
+#include "core/dom/Element.h"
+#include "core/dom/StyleEngine.h"
+#include "core/html/HTMLStyleElement.h"
+
+namespace WebCore {
+
+TreeScopeStyleSheetCollection::TreeScopeStyleSheetCollection(TreeScope& treeScope)
+    : m_treeScope(treeScope)
+    , m_hadActiveLoadingStylesheet(false)
+    , m_usesRemUnits(false)
+{
+}
+
+void TreeScopeStyleSheetCollection::addStyleSheetCandidateNode(Node* node, bool createdByParser)
+{
+    if (!node->inDocument())
+        return;
+
+    // Until the <body> exists, we have no choice but to compare document positions,
+    // since styles outside of the body and head continue to be shunted into the head
+    // (and thus can shift to end up before dynamically added DOM content that is also
+    // outside the body).
+    if (createdByParser && document().body())
+        m_styleSheetCandidateNodes.parserAdd(node);
+    else
+        m_styleSheetCandidateNodes.add(node);
+
+    if (!node->hasTagName(HTMLNames::styleTag))
+        return;
+
+    ContainerNode* scopingNode = toHTMLStyleElement(node)->scopingNode();
+    if (!isTreeScopeRoot(scopingNode))
+        m_scopingNodesForStyleScoped.add(scopingNode);
+}
+
+void TreeScopeStyleSheetCollection::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
+{
+    m_styleSheetCandidateNodes.remove(node);
+
+    if (!isTreeScopeRoot(scopingNode))
+        m_scopingNodesForStyleScoped.remove(scopingNode);
+}
+
+TreeScopeStyleSheetCollection::StyleResolverUpdateType TreeScopeStyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets)
+{
+    unsigned newStyleSheetCount = newStylesheets.size();
+    unsigned oldStyleSheetCount = oldStyleSheets.size();
+    ASSERT(newStyleSheetCount >= oldStyleSheetCount);
+
+    if (!newStyleSheetCount)
+        return Reconstruct;
+
+    unsigned newIndex = 0;
+    for (unsigned oldIndex = 0; oldIndex < oldStyleSheetCount; ++oldIndex) {
+        while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) {
+            addedSheets.append(newStylesheets[newIndex]->contents());
+            if (++newIndex == newStyleSheetCount)
+                return Reconstruct;
+        }
+        if (++newIndex == newStyleSheetCount)
+            return Reconstruct;
+    }
+    bool hasInsertions = !addedSheets.isEmpty();
+    while (newIndex < newStyleSheetCount) {
+        addedSheets.append(newStylesheets[newIndex]->contents());
+        ++newIndex;
+    }
+    // If all new sheets were added at the end of the list we can just add them to existing StyleResolver.
+    // If there were insertions we need to re-add all the stylesheets so rules are ordered correctly.
+    return hasInsertions ? Reset : Additive;
+}
+
+bool TreeScopeStyleSheetCollection::activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets)
+{
+    // StyleSheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
+    bool hasActiveLoadingStylesheet = false;
+    unsigned newStylesheetCount = newStyleSheets.size();
+    for (unsigned i = 0; i < newStylesheetCount; ++i) {
+        if (newStyleSheets[i]->isLoading())
+            hasActiveLoadingStylesheet = true;
+    }
+    if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
+        m_hadActiveLoadingStylesheet = false;
+        return true;
+    }
+    m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
+    return false;
+}
+
+static bool findFontFaceRulesFromStyleSheetContents(Vector<StyleSheetContents*> sheets, Vector<const StyleRuleFontFace*>& fontFaceRules)
+{
+    bool hasFontFaceRule = false;
+
+    for (unsigned i = 0; i < sheets.size(); ++i) {
+        ASSERT(sheets[i]);
+        if (sheets[i]->hasFontFaceRule()) {
+            // FIXME: We don't need this for styles in shadow tree.
+            sheets[i]->findFontFaceRules(fontFaceRules);
+            hasFontFaceRule = true;
+        }
+    }
+    return hasFontFaceRule;
+}
+
+void TreeScopeStyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const StyleSheetCollection& newCollection, StyleSheetChange& change)
+{
+    if (activeLoadingStyleSheetLoaded(newCollection.activeAuthorStyleSheets()))
+        return;
+
+    if (updateMode != AnalyzedStyleUpdate)
+        return;
+
+    // Find out which stylesheets are new.
+    Vector<StyleSheetContents*> addedSheets;
+    if (m_activeAuthorStyleSheets.size() <= newCollection.activeAuthorStyleSheets().size()) {
+        change.styleResolverUpdateType = compareStyleSheets(m_activeAuthorStyleSheets, newCollection.activeAuthorStyleSheets(), addedSheets);
+    } else {
+        StyleResolverUpdateType updateType = compareStyleSheets(newCollection.activeAuthorStyleSheets(), m_activeAuthorStyleSheets, addedSheets);
+        if (updateType != Additive) {
+            change.styleResolverUpdateType = updateType;
+        } else {
+            change.styleResolverUpdateType = Reset;
+            // If @font-face is removed, needs full style recalc.
+            if (findFontFaceRulesFromStyleSheetContents(addedSheets, change.fontFaceRulesToRemove))
+                return;
+        }
+    }
+
+    // FIXME: If styleResolverUpdateType is Reconstruct, we should return early here since
+    // we need to recalc the whole document. It's wrong to use StyleInvalidationAnalysis since
+    // it only looks at the addedSheets.
+
+    // No point in doing the analysis work if we're just going to recalc the whole document anyways.
+    // This needs to be done after the compareStyleSheets calls above to ensure we don't throw away
+    // the StyleResolver if we don't need to.
+    if (document().hasPendingForcedStyleRecalc())
+        return;
+
+    // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
+    if (!document().body() || document().hasNodesWithPlaceholderStyle())
+        return;
+    StyleInvalidationAnalysis invalidationAnalysis(addedSheets);
+    if (invalidationAnalysis.dirtiesAllStyle())
+        return;
+    invalidationAnalysis.invalidateStyle(document());
+    change.requiresFullStyleRecalc = false;
+    return;
+}
+
+void TreeScopeStyleSheetCollection::clearMediaQueryRuleSetStyleSheets()
+{
+    for (size_t i = 0; i < m_activeAuthorStyleSheets.size(); ++i) {
+        StyleSheetContents* contents = m_activeAuthorStyleSheets[i]->contents();
+        if (contents->hasMediaQueries())
+            contents->clearRuleSet();
+    }
+}
+
+void TreeScopeStyleSheetCollection::resetAllRuleSetsInTreeScope(StyleResolver* styleResolver)
+{
+    // FIXME: If many web developers use style scoped, implement reset RuleSets in per-scoping node manner.
+    if (DocumentOrderedList* styleScopedScopingNodes = scopingNodesForStyleScoped()) {
+        for (DocumentOrderedList::iterator it = styleScopedScopingNodes->begin(); it != styleScopedScopingNodes->end(); ++it)
+            styleResolver->resetAuthorStyle(toContainerNode(*it));
+    }
+    if (ListHashSet<Node*, 4>* removedNodes = scopingNodesRemoved()) {
+        for (ListHashSet<Node*, 4>::iterator it = removedNodes->begin(); it != removedNodes->end(); ++it)
+            styleResolver->resetAuthorStyle(toContainerNode(*it));
+    }
+    styleResolver->resetAuthorStyle(toContainerNode(&m_treeScope.rootNode()));
+}
+
+static bool styleSheetsUseRemUnits(const Vector<RefPtr<CSSStyleSheet> >& sheets)
+{
+    for (unsigned i = 0; i < sheets.size(); ++i) {
+        if (sheets[i]->contents()->usesRemUnits())
+            return true;
+    }
+    return false;
+}
+
+void TreeScopeStyleSheetCollection::updateUsesRemUnits()
+{
+    m_usesRemUnits = styleSheetsUseRemUnits(m_activeAuthorStyleSheets);
+}
+
+}
diff --git a/Source/core/dom/TreeScopeStyleSheetCollection.h b/Source/core/dom/TreeScopeStyleSheetCollection.h
new file mode 100644
index 0000000..6d24219
--- /dev/null
+++ b/Source/core/dom/TreeScopeStyleSheetCollection.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef TreeScopeStyleSheetCollection_h
+#define TreeScopeStyleSheetCollection_h
+
+#include "core/dom/Document.h"
+#include "core/dom/DocumentOrderedList.h"
+#include "core/dom/StyleSheetCollection.h"
+#include "core/dom/StyleSheetScopingNodeList.h"
+#include "core/dom/TreeScope.h"
+#include "wtf/FastAllocBase.h"
+#include "wtf/HashMap.h"
+#include "wtf/ListHashSet.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class ContainerNode;
+class DocumentStyleSheetCollector;
+class StyleEngine;
+class Node;
+class StyleSheetContents;
+class StyleSheetList;
+class StyleRuleFontFace;
+
+class TreeScopeStyleSheetCollection : public StyleSheetCollection {
+public:
+    void addStyleSheetCandidateNode(Node*, bool createdByParser);
+    void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode);
+    bool hasStyleSheetCandidateNodes() const { return !m_styleSheetCandidateNodes.isEmpty(); }
+
+
+    bool usesRemUnits() const { return m_usesRemUnits; }
+
+    DocumentOrderedList& styleSheetCandidateNodes() { return m_styleSheetCandidateNodes; }
+    DocumentOrderedList* scopingNodesForStyleScoped() { return m_scopingNodesForStyleScoped.scopingNodes(); }
+    ListHashSet<Node*, 4>* scopingNodesRemoved() { return m_scopingNodesForStyleScoped.scopingNodesRemoved(); }
+
+    void clearMediaQueryRuleSetStyleSheets();
+
+protected:
+    explicit TreeScopeStyleSheetCollection(TreeScope&);
+
+    Document& document() const { return m_treeScope.document(); }
+
+    enum StyleResolverUpdateType {
+        Reconstruct,
+        Reset,
+        Additive
+    };
+
+    struct StyleSheetChange {
+        StyleResolverUpdateType styleResolverUpdateType;
+        bool requiresFullStyleRecalc;
+        Vector<const StyleRuleFontFace*> fontFaceRulesToRemove;
+
+        StyleSheetChange()
+            : styleResolverUpdateType(Reconstruct)
+            , requiresFullStyleRecalc(true) { }
+    };
+
+    void analyzeStyleSheetChange(StyleResolverUpdateMode, const StyleSheetCollection&, StyleSheetChange&);
+    void resetAllRuleSetsInTreeScope(StyleResolver*);
+    void updateUsesRemUnits();
+
+private:
+    static StyleResolverUpdateType compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets);
+    bool activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets);
+
+protected:
+    TreeScope& m_treeScope;
+    bool m_hadActiveLoadingStylesheet;
+    bool m_usesRemUnits;
+
+    DocumentOrderedList m_styleSheetCandidateNodes;
+    StyleSheetScopingNodeList m_scopingNodesForStyleScoped;
+};
+
+}
+
+#endif
+
diff --git a/Source/core/dom/TreeShared.h b/Source/core/dom/TreeShared.h
index f57076a..8637dc6 100644
--- a/Source/core/dom/TreeShared.h
+++ b/Source/core/dom/TreeShared.h
@@ -82,13 +82,6 @@
         }
     }
 
-    bool hasOneRef() const
-    {
-        ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
-        ASSERT(!m_inRemovedLastRefFunction);
-        return m_refCount == 1;
-    }
-
     int refCount() const
     {
         return m_refCount;
diff --git a/Source/core/dom/TreeWalker.idl b/Source/core/dom/TreeWalker.idl
index 6a92eb0..eecb1ed 100644
--- a/Source/core/dom/TreeWalker.idl
+++ b/Source/core/dom/TreeWalker.idl
@@ -20,7 +20,7 @@
 
 // Introduced in DOM Level 2:
 [
-    SetReference(NodeFilter filter)
+    SetWrapperReferenceTo(NodeFilter filter)
 ] interface TreeWalker {
     readonly attribute Node root;
     readonly attribute unsigned long whatToShow;
diff --git a/Source/core/dom/URL.idl b/Source/core/dom/URL.idl
index 30c96c6..67dbb1e 100644
--- a/Source/core/dom/URL.idl
+++ b/Source/core/dom/URL.idl
@@ -36,5 +36,4 @@
     [CallWith=ExecutionContext] static void revokeObjectURL(DOMString url);
 };
 
-// force rebuild: crbug.com/307023
 URL implements URLUtils;
diff --git a/Source/core/dom/ViewportDescription.cpp b/Source/core/dom/ViewportDescription.cpp
index 77f924e..7f63c6a 100644
--- a/Source/core/dom/ViewportDescription.cpp
+++ b/Source/core/dom/ViewportDescription.cpp
@@ -54,17 +54,17 @@
     if (length.type() == ExtendToZoom)
         return ViewportDescription::ValueExtendToZoom;
 
-    if ((length.type() == Percent && direction == Horizontal) || length.type() == ViewportPercentageWidth)
+    if (length.type() == Percent && direction == Horizontal)
         return initialViewportSize.width() * length.getFloatValue() / 100.0f;
 
-    if ((length.type() == Percent && direction == Vertical) || length.type() == ViewportPercentageHeight)
+    if (length.type() == Percent && direction == Vertical)
         return initialViewportSize.height() * length.getFloatValue() / 100.0f;
 
-    if (length.type() == ViewportPercentageMin)
-        return min(initialViewportSize.width(), initialViewportSize.height()) * length.viewportPercentageLength() / 100.0f;
+    if (length.type() == DeviceWidth)
+        return initialViewportSize.width();
 
-    if (length.type() == ViewportPercentageMax)
-        return max(initialViewportSize.width(), initialViewportSize.height()) * length.viewportPercentageLength() / 100.0f;
+    if (length.type() == DeviceHeight)
+        return initialViewportSize.height();
 
     ASSERT_NOT_REACHED();
     return ViewportDescription::ValueAuto;
diff --git a/Source/core/dom/VisitedLinkState.cpp b/Source/core/dom/VisitedLinkState.cpp
index f715a3d..d134243 100644
--- a/Source/core/dom/VisitedLinkState.cpp
+++ b/Source/core/dom/VisitedLinkState.cpp
@@ -49,7 +49,7 @@
 static inline LinkHash linkHashForElement(const Element& element, const AtomicString& attribute = AtomicString())
 {
     ASSERT(attribute.isNull() || linkAttribute(element) == attribute);
-    if (isHTMLAnchorElement(element))
+    if (element.hasTagName(HTMLNames::aTag))
         return toHTMLAnchorElement(element).visitedLinkHash();
     return visitedLinkHash(element.document().baseURL(), attribute.isNull() ? linkAttribute(element) : attribute);
 }
@@ -65,7 +65,7 @@
         return;
     for (Element* element = ElementTraversal::firstWithin(m_document); element; element = ElementTraversal::next(*element)) {
         if (element->isLink())
-            element->setNeedsStyleRecalc();
+            element->setNeedsStyleRecalc(SubtreeStyleChange);
     }
 }
 
@@ -75,7 +75,7 @@
         return;
     for (Element* element = ElementTraversal::firstWithin(m_document); element; element = ElementTraversal::next(*element)) {
         if (element->isLink() && linkHashForElement(*element) == linkHash)
-            element->setNeedsStyleRecalc();
+            element->setNeedsStyleRecalc(SubtreeStyleChange);
     }
 }
 
diff --git a/Source/core/dom/WebKitNamedFlow.idl b/Source/core/dom/WebKitNamedFlow.idl
deleted file mode 100644
index 800e26d..0000000
--- a/Source/core/dom/WebKitNamedFlow.idl
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-[
-    GenerateVisitDOMWrapper=ownerNode,
-    ImplementedAs=NamedFlow,
-    NoInterfaceObject,
-    RuntimeEnabled=CSSRegions,
-] interface WebKitNamedFlow : EventTarget {
-    readonly attribute DOMString name;
-    readonly attribute boolean overset;
-    readonly attribute long firstEmptyRegionIndex;
-    NodeList getRegionsByContent(Node contentNode);
-    NodeList getRegions();
-    NodeList getContent();
-};
diff --git a/Source/core/dom/WebKitNamedFlowCollection.idl b/Source/core/dom/WebKitNamedFlowCollection.idl
deleted file mode 100644
index 4744e06..0000000
--- a/Source/core/dom/WebKitNamedFlowCollection.idl
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-[
-    NoInterfaceObject,
-    RuntimeEnabled=CSSRegions,
-    ImplementedAs=DOMNamedFlowCollection
-] interface WebKitNamedFlowCollection {
-    readonly attribute unsigned long length;
-    getter WebKitNamedFlow item(unsigned long index);
-    WebKitNamedFlow namedItem(DOMString name);
-    [NotEnumerable, ImplementedAs=namedItem] getter WebKitNamedFlow (DOMString name);
-};
diff --git a/Source/core/dom/WheelController.h b/Source/core/dom/WheelController.h
index 550cb09..5f25f98 100644
--- a/Source/core/dom/WheelController.h
+++ b/Source/core/dom/WheelController.h
@@ -35,7 +35,7 @@
 
 class DOMWindow;
 
-class WheelController : public DocumentSupplement, public DOMWindowLifecycleObserver {
+class WheelController FINAL : public DocumentSupplement, public DOMWindowLifecycleObserver {
 
 public:
     virtual ~WheelController();
diff --git a/Source/core/svg/SVGAnimateColorElement.idl b/Source/core/dom/XMLDocument.cpp
similarity index 62%
copy from Source/core/svg/SVGAnimateColorElement.idl
copy to Source/core/dom/XMLDocument.cpp
index 69a58eb..3fb1b8f 100644
--- a/Source/core/svg/SVGAnimateColorElement.idl
+++ b/Source/core/dom/XMLDocument.cpp
@@ -1,19 +1,19 @@
 /*
- * Copyright (C) 2006 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. 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
+ *  * 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
+ *  * 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 APPLE INC. ``AS IS'' AND ANY
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 APPLE INC. OR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER 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
@@ -23,6 +23,15 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGAnimateColorElement : SVGAnimationElement {
-};
+#include "config.h"
+#include "XMLDocument.h"
 
+namespace WebCore {
+
+XMLDocument::XMLDocument(const DocumentInit& initializer, DocumentClassFlags documentClasses)
+    : Document(initializer, documentClasses)
+{
+    ScriptWrappable::init(this);
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/XMLDocument.h b/Source/core/dom/XMLDocument.h
new file mode 100644
index 0000000..b65b19c
--- /dev/null
+++ b/Source/core/dom/XMLDocument.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * 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 THE COPYRIGHT HOLDERS ``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 THE COPYRIGHT OWNER 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.
+ */
+
+#ifndef XMLDocument_h
+#define XMLDocument_h
+
+#include "core/dom/Document.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class XMLDocument : public Document {
+public:
+    static PassRefPtr<XMLDocument> create(const DocumentInit& initializer = DocumentInit())
+    {
+        return adoptRef(new XMLDocument(initializer, XMLDocumentClass));
+    }
+
+    static PassRefPtr<XMLDocument> createXHTML(const DocumentInit& initializer = DocumentInit())
+    {
+        return adoptRef(new XMLDocument(initializer, XMLDocumentClass | XHTMLDocumentClass));
+    }
+
+protected:
+    XMLDocument(const DocumentInit&, DocumentClassFlags documentClasses);
+};
+
+DEFINE_DOCUMENT_TYPE_CASTS(XMLDocument);
+
+} // namespace WebCore
+
+#endif // XMLDocument_h
diff --git a/Source/core/svg/SVGAnimateColorElement.idl b/Source/core/dom/XMLDocument.idl
similarity index 73%
rename from Source/core/svg/SVGAnimateColorElement.idl
rename to Source/core/dom/XMLDocument.idl
index 69a58eb..a41fb18 100644
--- a/Source/core/svg/SVGAnimateColorElement.idl
+++ b/Source/core/dom/XMLDocument.idl
@@ -1,19 +1,19 @@
 /*
- * Copyright (C) 2006 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. 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
+ *  * 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
+ *  * 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 APPLE INC. ``AS IS'' AND ANY
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 APPLE INC. OR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER 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
@@ -23,6 +23,5 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGAnimateColorElement : SVGAnimationElement {
+interface XMLDocument : Document {
 };
-
diff --git a/Source/core/dom/custom/CustomElement.cpp b/Source/core/dom/custom/CustomElement.cpp
index eea313c..2415e4d 100644
--- a/Source/core/dom/custom/CustomElement.cpp
+++ b/Source/core/dom/custom/CustomElement.cpp
@@ -33,14 +33,18 @@
 
 #include "HTMLNames.h"
 #include "MathMLNames.h"
-#include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "core/dom/Element.h"
-#include "core/dom/custom/CustomElementCallbackScheduler.h"
 #include "core/dom/custom/CustomElementObserver.h"
+#include "core/dom/custom/CustomElementScheduler.h"
 
 namespace WebCore {
 
+CustomElementMicrotaskImportStep* CustomElement::didCreateImport(HTMLImportChild* import)
+{
+    return CustomElementScheduler::scheduleImport(import);
+}
+
 Vector<AtomicString>& CustomElement::embedderCustomElementNames()
 {
     DEFINE_STATIC_LOCAL(Vector<AtomicString>, names, ());
@@ -55,15 +59,8 @@
     embedderCustomElementNames().append(lower);
 }
 
-static CustomElement::NameSet enabledNameSet()
-{
-    return CustomElement::NameSet((RuntimeEnabledFeatures::customElementsEnabled() ? CustomElement::StandardNames : 0) | (RuntimeEnabledFeatures::embedderCustomElementsEnabled() ? CustomElement::EmbedderNames : 0));
-}
-
 bool CustomElement::isValidName(const AtomicString& name, NameSet validNames)
 {
-    validNames = NameSet(validNames & enabledNameSet());
-
     if ((validNames & EmbedderNames) && kNotFound != embedderCustomElementNames().find(name))
         return Document::isValidName(name);
 
@@ -101,7 +98,7 @@
 
     case Element::WaitingForUpgrade:
         definitions().add(element, definition);
-        CustomElementCallbackScheduler::scheduleCreatedCallback(definition->callbacks(), element);
+        CustomElementScheduler::scheduleCreatedCallback(definition->callbacks(), element);
         break;
     }
 }
@@ -116,7 +113,7 @@
 void CustomElement::attributeDidChange(Element* element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
 {
     ASSERT(element->customElementState() == Element::Upgraded);
-    CustomElementCallbackScheduler::scheduleAttributeChangedCallback(definitionFor(element)->callbacks(), element, name, oldValue, newValue);
+    CustomElementScheduler::scheduleAttributeChangedCallback(definitionFor(element)->callbacks(), element, name, oldValue, newValue);
 }
 
 void CustomElement::didEnterDocument(Element* element, const Document& document)
@@ -124,7 +121,7 @@
     ASSERT(element->customElementState() == Element::Upgraded);
     if (!document.domWindow())
         return;
-    CustomElementCallbackScheduler::scheduleEnteredViewCallback(definitionFor(element)->callbacks(), element);
+    CustomElementScheduler::scheduleAttachedCallback(definitionFor(element)->callbacks(), element);
 }
 
 void CustomElement::didLeaveDocument(Element* element, const Document& document)
@@ -132,7 +129,7 @@
     ASSERT(element->customElementState() == Element::Upgraded);
     if (!document.domWindow())
         return;
-    CustomElementCallbackScheduler::scheduleLeftViewCallback(definitionFor(element)->callbacks(), element);
+    CustomElementScheduler::scheduleDetachedCallback(definitionFor(element)->callbacks(), element);
 }
 
 void CustomElement::wasDestroyed(Element* element)
diff --git a/Source/core/dom/custom/CustomElement.h b/Source/core/dom/custom/CustomElement.h
index c50bc08..2fb4add 100644
--- a/Source/core/dom/custom/CustomElement.h
+++ b/Source/core/dom/custom/CustomElement.h
@@ -41,8 +41,10 @@
 
 namespace WebCore {
 
+class CustomElementMicrotaskImportStep;
 class Document;
 class Element;
+class HTMLImportChild;
 
 class CustomElement {
 public:
@@ -54,6 +56,9 @@
     static bool isValidName(const AtomicString& name, NameSet validNames = AllNames);
     static void addEmbedderCustomElementName(const AtomicString& name);
 
+    // API to notify of document-level changes
+    static CustomElementMicrotaskImportStep* didCreateImport(HTMLImportChild*);
+
     // API for registration contexts
     static void define(Element*, PassRefPtr<CustomElementDefinition>);
 
@@ -62,7 +67,6 @@
 
     // API for Element to kick off changes
 
-    static void didFinishParsingChildren(Element*);
     static void attributeDidChange(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
     static void didEnterDocument(Element*, const Document&);
     static void didLeaveDocument(Element*, const Document&);
diff --git a/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp b/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp
index 450af4e..5bd4866 100644
--- a/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp
+++ b/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp
@@ -32,7 +32,7 @@
 #include "core/dom/custom/CustomElementCallbackDispatcher.h"
 
 #include "core/dom/custom/CustomElementCallbackQueue.h"
-#include "core/dom/custom/CustomElementCallbackScheduler.h"
+#include "core/dom/custom/CustomElementScheduler.h"
 #include "wtf/MainThread.h"
 
 namespace WebCore {
@@ -48,17 +48,6 @@
     return instance;
 }
 
-bool CustomElementCallbackDispatcher::dispatch()
-{
-    ASSERT(isMainThread());
-    if (inCallbackDeliveryScope())
-        return false;
-
-    bool didWork = m_baseElementQueue.dispatch(baseElementQueue());
-    CustomElementCallbackScheduler::clearElementCallbackQueueMap();
-    return didWork;
-}
-
 // Dispatches callbacks when popping the processing stack.
 void CustomElementCallbackDispatcher::processElementQueueAndPop()
 {
@@ -68,7 +57,7 @@
 void CustomElementCallbackDispatcher::processElementQueueAndPop(size_t start, size_t end)
 {
     ASSERT(isMainThread());
-    ElementQueue thisQueue = currentElementQueue();
+    CustomElementCallbackQueue::ElementQueueId thisQueue = currentElementQueue();
 
     for (size_t i = start; i < end; i++) {
         {
@@ -86,23 +75,21 @@
     m_flattenedProcessingStack.resize(start);
     s_elementQueueEnd = start;
 
-    if (start == kNumSentinels && m_baseElementQueue.isEmpty())
-        CustomElementCallbackScheduler::clearElementCallbackQueueMap();
+    if (s_elementQueueStart == kNumSentinels)
+        CustomElementScheduler::callbackDispatcherDidFinish();
 }
 
 void CustomElementCallbackDispatcher::enqueue(CustomElementCallbackQueue* callbackQueue)
 {
+    ASSERT(inCallbackDeliveryScope());
+
     if (callbackQueue->owner() == currentElementQueue())
         return;
 
     callbackQueue->setOwner(currentElementQueue());
 
-    if (inCallbackDeliveryScope()) {
-        m_flattenedProcessingStack.append(callbackQueue);
-        ++s_elementQueueEnd;
-    } else {
-        m_baseElementQueue.enqueue(callbackQueue);
-    }
+    m_flattenedProcessingStack.append(callbackQueue);
+    ++s_elementQueueEnd;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElementCallbackDispatcher.h b/Source/core/dom/custom/CustomElementCallbackDispatcher.h
index 1792191..3e505c8 100644
--- a/Source/core/dom/custom/CustomElementCallbackDispatcher.h
+++ b/Source/core/dom/custom/CustomElementCallbackDispatcher.h
@@ -31,19 +31,18 @@
 #ifndef CustomElementCallbackDispatcher_h
 #define CustomElementCallbackDispatcher_h
 
-#include "core/dom/custom/CustomElementBaseElementQueue.h"
+#include "core/dom/custom/CustomElementCallbackQueue.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
-class CustomElementCallbackQueue;
-class CustomElementCallbackScheduler;
+class CustomElementScheduler;
 
+// FIXME: Rename this CustomElementProcessingStack. It only handles
+// the processing stack.
 class CustomElementCallbackDispatcher {
     WTF_MAKE_NONCOPYABLE(CustomElementCallbackDispatcher);
 public:
-    static CustomElementCallbackDispatcher& instance();
-
     // This is stack allocated in many DOM callbacks. Make it cheap.
     class CallbackDeliveryScope {
     public:
@@ -64,13 +63,11 @@
         size_t m_savedElementQueueStart;
     };
 
-    // Returns true if more work may have to be performed at the
-    // checkpoint by this or other workers (for example, this work
-    // invoked author scripts)
-    bool dispatch();
+    static bool inCallbackDeliveryScope() { return s_elementQueueStart; }
 
 protected:
-    friend class CustomElementCallbackScheduler;
+    friend class CustomElementScheduler;
+    static CustomElementCallbackDispatcher& instance();
     void enqueue(CustomElementCallbackQueue*);
 
 private:
@@ -95,20 +92,11 @@
     // stack. A cache of instance().m_flattenedProcessingStack.size().
     static size_t s_elementQueueEnd;
 
-    static bool inCallbackDeliveryScope() { return s_elementQueueStart; }
-
-    typedef int ElementQueue;
-    static ElementQueue baseElementQueue() { return ElementQueue(0); }
-    static ElementQueue currentElementQueue() { return ElementQueue(s_elementQueueStart); }
+    static CustomElementCallbackQueue::ElementQueueId currentElementQueue() { return CustomElementCallbackQueue::ElementQueueId(s_elementQueueStart); }
 
     static void processElementQueueAndPop();
     void processElementQueueAndPop(size_t start, size_t end);
 
-    // The base element queue, used when no CallbackDeliveryScope is
-    // active. Callbacks for elements created by the parser are
-    // enqueued here.
-    CustomElementBaseElementQueue m_baseElementQueue;
-
     // The processing stack, flattened. Element queues lower in the
     // stack appear toward the head of the vector. The first element
     // is a null sentinel value.
diff --git a/Source/core/dom/custom/CustomElementCallbackInvocation.cpp b/Source/core/dom/custom/CustomElementCallbackInvocation.cpp
index 7263ffc..b7eb8e4 100644
--- a/Source/core/dom/custom/CustomElementCallbackInvocation.cpp
+++ b/Source/core/dom/custom/CustomElementCallbackInvocation.cpp
@@ -32,32 +32,13 @@
 #include "core/dom/custom/CustomElementCallbackInvocation.h"
 
 #include "core/dom/Element.h"
-#include "core/dom/custom/CustomElementCallbackScheduler.h"
+#include "core/dom/custom/CustomElementScheduler.h"
 
 namespace WebCore {
 
-class CreatedInvocation : public CustomElementCallbackInvocation {
+class AttachedDetachedInvocation : public CustomElementCallbackInvocation {
 public:
-    CreatedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
-        : CustomElementCallbackInvocation(callbacks)
-    {
-    }
-
-private:
-    virtual void dispatch(Element*) OVERRIDE;
-    virtual bool isCreated() const OVERRIDE { return true; }
-};
-
-void CreatedInvocation::dispatch(Element* element)
-{
-    if (element->inDocument() && element->document().domWindow())
-        CustomElementCallbackScheduler::scheduleEnteredViewCallback(callbacks(), element);
-    callbacks()->created(element);
-}
-
-class EnteredLeftViewInvocation : public CustomElementCallbackInvocation {
-public:
-    EnteredLeftViewInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, CustomElementLifecycleCallbacks::CallbackType which);
+    AttachedDetachedInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, CustomElementLifecycleCallbacks::CallbackType which);
 
 private:
     virtual void dispatch(Element*) OVERRIDE;
@@ -65,21 +46,21 @@
     CustomElementLifecycleCallbacks::CallbackType m_which;
 };
 
-EnteredLeftViewInvocation::EnteredLeftViewInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, CustomElementLifecycleCallbacks::CallbackType which)
+AttachedDetachedInvocation::AttachedDetachedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, CustomElementLifecycleCallbacks::CallbackType which)
     : CustomElementCallbackInvocation(callbacks)
     , m_which(which)
 {
-    ASSERT(m_which == CustomElementLifecycleCallbacks::EnteredView || m_which == CustomElementLifecycleCallbacks::LeftView);
+    ASSERT(m_which == CustomElementLifecycleCallbacks::Attached || m_which == CustomElementLifecycleCallbacks::Detached);
 }
 
-void EnteredLeftViewInvocation::dispatch(Element* element)
+void AttachedDetachedInvocation::dispatch(Element* element)
 {
     switch (m_which) {
-    case CustomElementLifecycleCallbacks::EnteredView:
-        callbacks()->enteredView(element);
+    case CustomElementLifecycleCallbacks::Attached:
+        callbacks()->attached(element);
         break;
-    case CustomElementLifecycleCallbacks::LeftView:
-        callbacks()->leftView(element);
+    case CustomElementLifecycleCallbacks::Detached:
+        callbacks()->detached(element);
         break;
     default:
         ASSERT_NOT_REACHED();
@@ -111,16 +92,34 @@
     callbacks()->attributeChanged(element, m_name, m_oldValue, m_newValue);
 }
 
+class CreatedInvocation : public CustomElementCallbackInvocation {
+public:
+    CreatedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
+        : CustomElementCallbackInvocation(callbacks)
+    {
+    }
+
+private:
+    virtual void dispatch(Element*) OVERRIDE;
+    virtual bool isCreated() const OVERRIDE { return true; }
+};
+
+void CreatedInvocation::dispatch(Element* element)
+{
+    if (element->inDocument() && element->document().domWindow())
+        CustomElementScheduler::scheduleAttachedCallback(callbacks(), element);
+    callbacks()->created(element);
+}
+
 PassOwnPtr<CustomElementCallbackInvocation> CustomElementCallbackInvocation::createInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, CustomElementLifecycleCallbacks::CallbackType which)
 {
     switch (which) {
     case CustomElementLifecycleCallbacks::Created:
         return adoptPtr(new CreatedInvocation(callbacks));
 
-    case CustomElementLifecycleCallbacks::EnteredView:
-    case CustomElementLifecycleCallbacks::LeftView:
-        return adoptPtr(new EnteredLeftViewInvocation(callbacks, which));
-
+    case CustomElementLifecycleCallbacks::Attached:
+    case CustomElementLifecycleCallbacks::Detached:
+        return adoptPtr(new AttachedDetachedInvocation(callbacks, which));
     default:
         ASSERT_NOT_REACHED();
         return PassOwnPtr<CustomElementCallbackInvocation>();
diff --git a/Source/core/dom/custom/CustomElementCallbackInvocation.h b/Source/core/dom/custom/CustomElementCallbackInvocation.h
index 097e091..615a3f4 100644
--- a/Source/core/dom/custom/CustomElementCallbackInvocation.h
+++ b/Source/core/dom/custom/CustomElementCallbackInvocation.h
@@ -32,6 +32,7 @@
 #define CustomElementCallbackInvocation_h
 
 #include "core/dom/custom/CustomElementLifecycleCallbacks.h"
+#include "core/dom/custom/CustomElementProcessingStep.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
@@ -39,18 +40,12 @@
 
 namespace WebCore {
 
-class Element;
-
-class CustomElementCallbackInvocation {
+class CustomElementCallbackInvocation : public CustomElementProcessingStep {
     WTF_MAKE_NONCOPYABLE(CustomElementCallbackInvocation);
 public:
     static PassOwnPtr<CustomElementCallbackInvocation> createInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, CustomElementLifecycleCallbacks::CallbackType);
     static PassOwnPtr<CustomElementCallbackInvocation> createAttributeChangedInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
 
-    virtual ~CustomElementCallbackInvocation() { }
-    virtual void dispatch(Element*) = 0;
-    virtual bool isCreated() const { return false; }
-
 protected:
     CustomElementCallbackInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
         : m_callbacks(callbacks)
diff --git a/Source/core/dom/custom/CustomElementCallbackQueue.cpp b/Source/core/dom/custom/CustomElementCallbackQueue.cpp
index 7da3b71..fe74598 100644
--- a/Source/core/dom/custom/CustomElementCallbackQueue.cpp
+++ b/Source/core/dom/custom/CustomElementCallbackQueue.cpp
@@ -46,9 +46,10 @@
 {
 }
 
-void CustomElementCallbackQueue::processInElementQueue(ElementQueue caller)
+bool CustomElementCallbackQueue::processInElementQueue(ElementQueueId caller)
 {
     ASSERT(!m_inCreatedCallback);
+    bool didWork = false;
 
     while (m_index < m_queue.size() && owner() == caller) {
         m_inCreatedCallback = m_queue[m_index]->isCreated();
@@ -58,6 +59,7 @@
         // detects this recursion and cedes processing.
         m_queue[m_index++]->dispatch(m_element.get());
         m_inCreatedCallback = false;
+        didWork = true;
     }
 
     if (owner() == caller && m_index == m_queue.size()) {
@@ -66,6 +68,8 @@
         m_queue.resize(0);
         m_owner = -1;
     }
+
+    return didWork;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElementCallbackQueue.h b/Source/core/dom/custom/CustomElementCallbackQueue.h
index 269bfd2..cae5855 100644
--- a/Source/core/dom/custom/CustomElementCallbackQueue.h
+++ b/Source/core/dom/custom/CustomElementCallbackQueue.h
@@ -32,7 +32,8 @@
 #define CustomElementCallbackQueue_h
 
 #include "core/dom/Element.h"
-#include "core/dom/custom/CustomElementCallbackInvocation.h"
+#include "core/dom/custom/CustomElementProcessingStep.h"
+#include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
@@ -40,14 +41,17 @@
 
 namespace WebCore {
 
+// FIXME: Rename this because it contains resolution and upgrade as
+// well as callbacks.
 class CustomElementCallbackQueue {
     WTF_MAKE_NONCOPYABLE(CustomElementCallbackQueue);
 public:
     static PassOwnPtr<CustomElementCallbackQueue> create(PassRefPtr<Element>);
 
-    typedef int ElementQueue;
-    ElementQueue owner() { return m_owner; }
-    void setOwner(ElementQueue newOwner)
+    typedef int ElementQueueId;
+    ElementQueueId owner() const { return m_owner; }
+
+    void setOwner(ElementQueueId newOwner)
     {
         // ElementCallbackQueues only migrate towards the top of the
         // processing stack.
@@ -55,16 +59,17 @@
         m_owner = newOwner;
     }
 
-    void append(PassOwnPtr<CustomElementCallbackInvocation> invocation) { m_queue.append(invocation); }
-    void processInElementQueue(ElementQueue);
+    bool processInElementQueue(ElementQueueId);
+
+    void append(PassOwnPtr<CustomElementProcessingStep> invocation) { m_queue.append(invocation); }
     bool inCreatedCallback() const { return m_inCreatedCallback; }
 
 private:
     CustomElementCallbackQueue(PassRefPtr<Element>);
 
     RefPtr<Element> m_element;
-    Vector<OwnPtr<CustomElementCallbackInvocation> > m_queue;
-    ElementQueue m_owner;
+    Vector<OwnPtr<CustomElementProcessingStep> > m_queue;
+    ElementQueueId m_owner;
     size_t m_index;
     bool m_inCreatedCallback;
 };
diff --git a/Source/core/dom/custom/CustomElementCallbackScheduler.cpp b/Source/core/dom/custom/CustomElementCallbackScheduler.cpp
deleted file mode 100644
index 2d36478..0000000
--- a/Source/core/dom/custom/CustomElementCallbackScheduler.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. 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.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/dom/custom/CustomElementCallbackScheduler.h"
-
-#include "core/dom/Element.h"
-#include "core/dom/custom/CustomElementCallbackDispatcher.h"
-#include "core/dom/custom/CustomElementLifecycleCallbacks.h"
-
-namespace WebCore {
-
-void CustomElementCallbackScheduler::scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
-{
-    if (!callbacks->hasAttributeChangedCallback())
-        return;
-
-    CustomElementCallbackQueue* queue = instance().schedule(element);
-    queue->append(CustomElementCallbackInvocation::createAttributeChangedInvocation(callbacks, name, oldValue, newValue));
-}
-
-void CustomElementCallbackScheduler::scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
-{
-    if (!callbacks->hasCreatedCallback())
-        return;
-
-    CustomElementCallbackQueue* queue = instance().scheduleInCurrentElementQueue(element);
-    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Created));
-}
-
-void CustomElementCallbackScheduler::scheduleEnteredViewCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
-{
-    if (!callbacks->hasEnteredViewCallback())
-        return;
-
-    CustomElementCallbackQueue* queue = instance().schedule(element);
-    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::EnteredView));
-}
-
-void CustomElementCallbackScheduler::scheduleLeftViewCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
-{
-    if (!callbacks->hasLeftViewCallback())
-        return;
-
-    CustomElementCallbackQueue* queue = instance().schedule(element);
-    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::LeftView));
-}
-
-CustomElementCallbackScheduler& CustomElementCallbackScheduler::instance()
-{
-    DEFINE_STATIC_LOCAL(CustomElementCallbackScheduler, instance, ());
-    return instance;
-}
-
-CustomElementCallbackQueue* CustomElementCallbackScheduler::ensureCallbackQueue(PassRefPtr<Element> element)
-{
-    Element* key = element.get();
-    ElementCallbackQueueMap::iterator it = m_elementCallbackQueueMap.find(key);
-    if (it == m_elementCallbackQueueMap.end())
-        it = m_elementCallbackQueueMap.add(key, CustomElementCallbackQueue::create(element)).iterator;
-    return it->value.get();
-}
-
-void CustomElementCallbackScheduler::clearElementCallbackQueueMap()
-{
-    ElementCallbackQueueMap emptyMap;
-    instance().m_elementCallbackQueueMap.swap(emptyMap);
-}
-
-// Finds or creates the callback queue for element. If the
-// createdCallback has not finished running, the callback queue is not
-// moved to the top-of-stack. Otherwise like
-// scheduleInCurrentElementQueue.
-CustomElementCallbackQueue* CustomElementCallbackScheduler::schedule(PassRefPtr<Element> element)
-{
-    CustomElementCallbackQueue* callbackQueue = ensureCallbackQueue(element);
-    if (!callbackQueue->inCreatedCallback())
-        CustomElementCallbackDispatcher::instance().enqueue(callbackQueue);
-    return callbackQueue;
-}
-
-// Finds or creates the callback queue for element. If the element's
-// callback queue is scheduled in an earlier processing stack frame,
-// its owner is set to the element queue on the top of the processing
-// stack. Because callback queues are processed exhaustively, this
-// effectively moves the callback queue to the top of the stack.
-CustomElementCallbackQueue* CustomElementCallbackScheduler::scheduleInCurrentElementQueue(PassRefPtr<Element> element)
-{
-    CustomElementCallbackQueue* callbackQueue = ensureCallbackQueue(element);
-    CustomElementCallbackDispatcher::instance().enqueue(callbackQueue);
-    return callbackQueue;
-}
-
-} // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElementException.cpp b/Source/core/dom/custom/CustomElementException.cpp
index 331548a..ddaf1fc 100644
--- a/Source/core/dom/custom/CustomElementException.cpp
+++ b/Source/core/dom/custom/CustomElementException.cpp
@@ -57,23 +57,23 @@
         return;
 
     case ContextDestroyedCreatingCallbacks:
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "The context is no longer valid.");
         return;
 
     case ContextDestroyedRegisteringDefinition:
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "The context is no longer valid.");
         return;
 
     case ExtendsIsInvalidName:
-        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + "The tag name specified in 'extends' is not a valid tag name.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "The tag name specified in 'extends' is not a valid tag name.");
         return;
 
     case ExtendsIsCustomElementName:
-        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + "The tag name specified in 'extends' is a custom element name. Use inheritance instead.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "The tag name specified in 'extends' is a custom element name. Use inheritance instead.");
         return;
 
     case InvalidName:
-        exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + "The type name is invalid.");
+        exceptionState.throwDOMException(SyntaxError, preamble(type) + "The type name is invalid.");
         return;
 
     case PrototypeInUse:
@@ -81,11 +81,11 @@
         return;
 
     case PrototypeNotAnObject:
-        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "The prototype option is not an object.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "The prototype option is not an object.");
         return;
 
     case TypeAlreadyRegistered:
-        exceptionState.throwDOMException(InvalidStateError, preamble(type) + "A type with that name is already registered.");
+        exceptionState.throwDOMException(NotSupportedError, preamble(type) + "A type with that name is already registered.");
         return;
     }
 
diff --git a/Source/core/dom/custom/CustomElementLifecycleCallbacks.h b/Source/core/dom/custom/CustomElementLifecycleCallbacks.h
index eb2f32f..aa182e6 100644
--- a/Source/core/dom/custom/CustomElementLifecycleCallbacks.h
+++ b/Source/core/dom/custom/CustomElementLifecycleCallbacks.h
@@ -45,11 +45,11 @@
     bool hasCreatedCallback() const { return m_which & Created; }
     virtual void created(Element*) = 0;
 
-    bool hasEnteredViewCallback() const { return m_which & EnteredView; }
-    virtual void enteredView(Element*) = 0;
+    bool hasAttachedCallback() const { return m_which & Attached; }
+    virtual void attached(Element*) = 0;
 
-    bool hasLeftViewCallback() const { return m_which & LeftView; }
-    virtual void leftView(Element*) = 0;
+    bool hasDetachedCallback() const { return m_which & Detached; }
+    virtual void detached(Element*) = 0;
 
     bool hasAttributeChangedCallback() const { return m_which & AttributeChanged; }
     virtual void attributeChanged(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue) = 0;
@@ -57,8 +57,8 @@
     enum CallbackType {
         None             = 0,
         Created          = 1 << 0,
-        EnteredView      = 1 << 1,
-        LeftView         = 1 << 2,
+        Attached         = 1 << 1,
+        Detached         = 1 << 2,
         AttributeChanged = 1 << 3
     };
 
diff --git a/Source/core/dom/custom/CustomElementMicrotaskDispatcher.cpp b/Source/core/dom/custom/CustomElementMicrotaskDispatcher.cpp
new file mode 100644
index 0000000..a569ad2
--- /dev/null
+++ b/Source/core/dom/custom/CustomElementMicrotaskDispatcher.cpp
@@ -0,0 +1,96 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/dom/custom/CustomElementMicrotaskDispatcher.h"
+
+#include "core/dom/Microtask.h"
+#include "core/dom/custom/CustomElementCallbackDispatcher.h"
+#include "core/dom/custom/CustomElementCallbackQueue.h"
+#include "core/dom/custom/CustomElementMicrotaskImportStep.h"
+#include "core/dom/custom/CustomElementScheduler.h"
+#include "core/html/HTMLImport.h"
+#include "wtf/MainThread.h"
+
+namespace WebCore {
+
+static const CustomElementCallbackQueue::ElementQueueId kMicrotaskQueueId = 0;
+
+CustomElementMicrotaskDispatcher::CustomElementMicrotaskDispatcher()
+    : m_hasScheduledMicrotask(false)
+    , m_phase(Quiescent)
+{
+}
+
+CustomElementMicrotaskDispatcher& CustomElementMicrotaskDispatcher::instance()
+{
+    DEFINE_STATIC_LOCAL(CustomElementMicrotaskDispatcher, instance, ());
+    return instance;
+}
+
+void CustomElementMicrotaskDispatcher::enqueue(HTMLImport* import, PassOwnPtr<CustomElementMicrotaskStep> step)
+{
+    ASSERT(m_phase == Quiescent || m_phase == DispatchingCallbacks);
+    ensureMicrotaskScheduled();
+    if (import && import->customElementMicrotaskStep())
+        import->customElementMicrotaskStep()->enqueue(step);
+    else
+        m_resolutionAndImports.enqueue(step);
+}
+
+void CustomElementMicrotaskDispatcher::enqueue(CustomElementCallbackQueue* queue)
+{
+    ASSERT(m_phase == Quiescent || m_phase == Resolving);
+    ensureMicrotaskScheduled();
+    queue->setOwner(kMicrotaskQueueId);
+    m_elements.append(queue);
+}
+
+void CustomElementMicrotaskDispatcher::importDidFinish(CustomElementMicrotaskImportStep* step)
+{
+    ASSERT(m_phase == Quiescent || m_phase == DispatchingCallbacks);
+    ensureMicrotaskScheduled();
+}
+
+void CustomElementMicrotaskDispatcher::ensureMicrotaskScheduled()
+{
+    if (!m_hasScheduledMicrotask) {
+        Microtask::enqueueMicrotask(&dispatch);
+        m_hasScheduledMicrotask = true;
+    }
+}
+
+void CustomElementMicrotaskDispatcher::dispatch()
+{
+    instance().doDispatch();
+}
+
+void CustomElementMicrotaskDispatcher::doDispatch()
+{
+    ASSERT(isMainThread());
+
+    ASSERT(m_phase == Quiescent && m_hasScheduledMicrotask);
+    m_hasScheduledMicrotask = false;
+
+    // Finishing microtask work deletes all
+    // CustomElementCallbackQueues. Being in a callback delivery scope
+    // implies those queues could still be in use.
+    ASSERT_WITH_SECURITY_IMPLICATION(!CustomElementCallbackDispatcher::inCallbackDeliveryScope());
+
+    m_phase = Resolving;
+    m_resolutionAndImports.dispatch();
+
+    m_phase = DispatchingCallbacks;
+    for (Vector<CustomElementCallbackQueue*>::iterator it = m_elements.begin();it != m_elements.end(); ++it) {
+        // Created callback may enqueue an attached callback.
+        CustomElementCallbackDispatcher::CallbackDeliveryScope scope;
+        (*it)->processInElementQueue(kMicrotaskQueueId);
+    }
+
+    m_elements.clear();
+    CustomElementScheduler::microtaskDispatcherDidFinish();
+    m_phase = Quiescent;
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElementMicrotaskDispatcher.h b/Source/core/dom/custom/CustomElementMicrotaskDispatcher.h
new file mode 100644
index 0000000..2d24e9e
--- /dev/null
+++ b/Source/core/dom/custom/CustomElementMicrotaskDispatcher.h
@@ -0,0 +1,55 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CustomElementMicrotaskDispatcher_h
+#define CustomElementMicrotaskDispatcher_h
+
+#include "core/dom/custom/CustomElementMicrotaskQueue.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class CustomElementCallbackQueue;
+class CustomElementMicrotaskImportStep;
+class CustomElementMicrotaskStep;
+class HTMLImport;
+
+class CustomElementMicrotaskDispatcher {
+    WTF_MAKE_NONCOPYABLE(CustomElementMicrotaskDispatcher);
+public:
+    ~CustomElementMicrotaskDispatcher() { }
+
+    static CustomElementMicrotaskDispatcher& instance();
+
+    void enqueue(HTMLImport*, PassOwnPtr<CustomElementMicrotaskStep>);
+    void enqueue(CustomElementCallbackQueue*);
+
+    void importDidFinish(CustomElementMicrotaskImportStep*);
+
+    bool elementQueueIsEmpty() { return m_elements.isEmpty(); }
+
+private:
+    CustomElementMicrotaskDispatcher();
+
+    void ensureMicrotaskScheduled();
+
+    static void dispatch();
+    void doDispatch();
+
+    bool m_hasScheduledMicrotask;
+    enum {
+        Quiescent,
+        Resolving,
+        DispatchingCallbacks
+    } m_phase;
+
+    CustomElementMicrotaskQueue m_resolutionAndImports;
+    Vector<CustomElementCallbackQueue*> m_elements;
+};
+
+}
+
+#endif // CustomElementMicrotaskDispatcher_h
diff --git a/Source/core/dom/custom/CustomElementBaseElementQueue.cpp b/Source/core/dom/custom/CustomElementMicrotaskImportStep.cpp
similarity index 62%
copy from Source/core/dom/custom/CustomElementBaseElementQueue.cpp
copy to Source/core/dom/custom/CustomElementMicrotaskImportStep.cpp
index 0e8561d..9dcc851 100644
--- a/Source/core/dom/custom/CustomElementBaseElementQueue.cpp
+++ b/Source/core/dom/custom/CustomElementMicrotaskImportStep.cpp
@@ -29,36 +29,39 @@
  */
 
 #include "config.h"
-#include "core/dom/custom/CustomElementBaseElementQueue.h"
+#include "core/dom/custom/CustomElementMicrotaskImportStep.h"
 
-#include "core/dom/custom/CustomElementCallbackDispatcher.h"
-#include "core/dom/custom/CustomElementCallbackQueue.h"
+#include "core/dom/custom/CustomElementMicrotaskDispatcher.h"
 
 namespace WebCore {
 
-void CustomElementBaseElementQueue::enqueue(CustomElementCallbackQueue* queue)
+PassOwnPtr<CustomElementMicrotaskImportStep> CustomElementMicrotaskImportStep::create()
 {
-    m_queue.append(queue);
+    return adoptPtr(new CustomElementMicrotaskImportStep());
 }
 
-bool CustomElementBaseElementQueue::dispatch(ElementQueue baseQueueId)
+void CustomElementMicrotaskImportStep::enqueue(PassOwnPtr<CustomElementMicrotaskStep> step)
 {
-    ASSERT(!m_inDispatch);
-    m_inDispatch = true;
+    // work should not be being created after the import is done
+    // because the parser is done
+    ASSERT(!m_importFinished);
+    m_queue.enqueue(step);
+}
 
-    bool didWork = m_queue.size();
+void CustomElementMicrotaskImportStep::importDidFinish()
+{
+    // imports should only "finish" once
+    ASSERT(!m_importFinished);
+    m_importFinished = true;
+    CustomElementMicrotaskDispatcher::instance().importDidFinish(this);
+}
 
-    for (Vector<CustomElementCallbackQueue*>::iterator it = m_queue.begin(); it != m_queue.end(); ++it) {
-        // The created callback may schedule entered document
-        // callbacks.
-        CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope;
-        (*it)->processInElementQueue(baseQueueId);
-    }
-
-    m_queue.resize(0);
-    m_inDispatch = 0;
-
-    return didWork;
+CustomElementMicrotaskStep::Result CustomElementMicrotaskImportStep::process()
+{
+    Result result = m_queue.dispatch();
+    if (!m_importFinished)
+        result = Result(result | ShouldStop);
+    return result;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElementMicrotaskImportStep.h b/Source/core/dom/custom/CustomElementMicrotaskImportStep.h
new file mode 100644
index 0000000..8b5d3f3
--- /dev/null
+++ b/Source/core/dom/custom/CustomElementMicrotaskImportStep.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2013 Google Inc. 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.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ *    may be used to endorse or promote products derived from this
+ *    software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef CustomElementMicrotaskImportStep_h
+#define CustomElementMicrotaskImportStep_h
+
+#include "core/dom/custom/CustomElementMicrotaskQueue.h"
+#include "core/dom/custom/CustomElementMicrotaskStep.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+// Processes the Custom Elements in an HTML Import. This is a
+// composite step which processes the Custom Elements created by
+// parsing the import, and its sub-imports.
+//
+// This step blocks further Custom Element microtask processing if its
+// import isn't "ready" (finished parsing and running script.)
+class CustomElementMicrotaskImportStep : public CustomElementMicrotaskStep {
+    WTF_MAKE_NONCOPYABLE(CustomElementMicrotaskImportStep);
+public:
+    static PassOwnPtr<CustomElementMicrotaskImportStep> create();
+    virtual ~CustomElementMicrotaskImportStep() { }
+
+    // API for CustomElementScheduler
+    void enqueue(PassOwnPtr<CustomElementMicrotaskStep>);
+
+    // API for HTML Imports
+    void importDidFinish();
+
+private:
+    CustomElementMicrotaskImportStep() : m_importFinished(false) { }
+
+    // CustomElementMicrotaskStep
+    virtual Result process() OVERRIDE FINAL;
+
+    bool m_importFinished;
+    CustomElementMicrotaskQueue m_queue;
+};
+
+}
+
+#endif // CustomElementMicrotaskImportStep_h
diff --git a/Source/core/dom/custom/CustomElementBaseElementQueue.cpp b/Source/core/dom/custom/CustomElementMicrotaskQueue.cpp
similarity index 69%
rename from Source/core/dom/custom/CustomElementBaseElementQueue.cpp
rename to Source/core/dom/custom/CustomElementMicrotaskQueue.cpp
index 0e8561d..c6af626 100644
--- a/Source/core/dom/custom/CustomElementBaseElementQueue.cpp
+++ b/Source/core/dom/custom/CustomElementMicrotaskQueue.cpp
@@ -29,36 +29,36 @@
  */
 
 #include "config.h"
-#include "core/dom/custom/CustomElementBaseElementQueue.h"
+#include "core/dom/custom/CustomElementMicrotaskQueue.h"
 
 #include "core/dom/custom/CustomElementCallbackDispatcher.h"
-#include "core/dom/custom/CustomElementCallbackQueue.h"
 
 namespace WebCore {
 
-void CustomElementBaseElementQueue::enqueue(CustomElementCallbackQueue* queue)
+void CustomElementMicrotaskQueue::enqueue(PassOwnPtr<CustomElementMicrotaskStep> step)
 {
-    m_queue.append(queue);
+    m_queue.append(step);
 }
 
-bool CustomElementBaseElementQueue::dispatch(ElementQueue baseQueueId)
+CustomElementMicrotaskStep::Result CustomElementMicrotaskQueue::dispatch()
 {
-    ASSERT(!m_inDispatch);
-    m_inDispatch = true;
+    Result result = Result(0);
 
-    bool didWork = m_queue.size();
+    unsigned i;
+    for (i = 0; i < m_queue.size(); ++i) {
+        result = Result(result | m_queue[i]->process());
 
-    for (Vector<CustomElementCallbackQueue*>::iterator it = m_queue.begin(); it != m_queue.end(); ++it) {
-        // The created callback may schedule entered document
-        // callbacks.
-        CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope;
-        (*it)->processInElementQueue(baseQueueId);
+        if (result & CustomElementMicrotaskStep::ShouldStop)
+            break;
     }
 
-    m_queue.resize(0);
-    m_inDispatch = 0;
+    bool wasStopped = i < m_queue.size();
+    if (wasStopped)
+        m_queue.remove(0, i);
+    else
+        m_queue.resize(0);
 
-    return didWork;
+    return result;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElementBaseElementQueue.h b/Source/core/dom/custom/CustomElementMicrotaskQueue.h
similarity index 73%
rename from Source/core/dom/custom/CustomElementBaseElementQueue.h
rename to Source/core/dom/custom/CustomElementMicrotaskQueue.h
index 78882aa..4ae22d2 100644
--- a/Source/core/dom/custom/CustomElementBaseElementQueue.h
+++ b/Source/core/dom/custom/CustomElementMicrotaskQueue.h
@@ -28,31 +28,31 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CustomElementBaseElementQueue_h
-#define CustomElementBaseElementQueue_h
+#ifndef CustomElementMicrotaskQueue_h
+#define CustomElementMicrotaskQueue_h
 
+#include "core/dom/custom/CustomElementMicrotaskStep.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
-class CustomElementCallbackQueue;
-
-class CustomElementBaseElementQueue {
-    WTF_MAKE_NONCOPYABLE(CustomElementBaseElementQueue);
+class CustomElementMicrotaskQueue {
+    WTF_MAKE_NONCOPYABLE(CustomElementMicrotaskQueue);
 public:
-    CustomElementBaseElementQueue() : m_inDispatch(false) { }
+    CustomElementMicrotaskQueue() { }
 
-    bool isEmpty() const { return m_queue.isEmpty(); }
-    void enqueue(CustomElementCallbackQueue*);
+    bool isEmpty() { return m_queue.isEmpty(); }
+    void enqueue(PassOwnPtr<CustomElementMicrotaskStep>);
 
-    typedef int ElementQueue;
-    bool dispatch(ElementQueue baseQueueId);
+    typedef CustomElementMicrotaskStep::Result Result;
+    Result dispatch();
 
 private:
-    bool m_inDispatch;
-    Vector<CustomElementCallbackQueue*> m_queue;
+    Vector<OwnPtr<CustomElementMicrotaskStep> > m_queue;
 };
 
 }
 
-#endif // CustomElementBaseElementQueue_h
+#endif // CustomElementMicrotaskQueue_h
diff --git a/Source/core/dom/custom/CustomElementBaseElementQueue.cpp b/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.cpp
similarity index 61%
copy from Source/core/dom/custom/CustomElementBaseElementQueue.cpp
copy to Source/core/dom/custom/CustomElementMicrotaskResolutionStep.cpp
index 0e8561d..e5edad0 100644
--- a/Source/core/dom/custom/CustomElementBaseElementQueue.cpp
+++ b/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.cpp
@@ -29,36 +29,33 @@
  */
 
 #include "config.h"
-#include "core/dom/custom/CustomElementBaseElementQueue.h"
+#include "core/dom/custom/CustomElementMicrotaskResolutionStep.h"
 
-#include "core/dom/custom/CustomElementCallbackDispatcher.h"
-#include "core/dom/custom/CustomElementCallbackQueue.h"
+#include "core/dom/Element.h"
+#include "core/dom/custom/CustomElementRegistrationContext.h"
 
 namespace WebCore {
 
-void CustomElementBaseElementQueue::enqueue(CustomElementCallbackQueue* queue)
+PassOwnPtr<CustomElementMicrotaskResolutionStep> CustomElementMicrotaskResolutionStep::create(PassRefPtr<CustomElementRegistrationContext> context, PassRefPtr<Element> element, const CustomElementDescriptor& descriptor)
 {
-    m_queue.append(queue);
+    return adoptPtr(new CustomElementMicrotaskResolutionStep(context, element, descriptor));
 }
 
-bool CustomElementBaseElementQueue::dispatch(ElementQueue baseQueueId)
+CustomElementMicrotaskResolutionStep::CustomElementMicrotaskResolutionStep(PassRefPtr<CustomElementRegistrationContext> context, PassRefPtr<Element> element, const CustomElementDescriptor& descriptor)
+    : m_context(context)
+    , m_element(element)
+    , m_descriptor(descriptor)
 {
-    ASSERT(!m_inDispatch);
-    m_inDispatch = true;
+}
 
-    bool didWork = m_queue.size();
+CustomElementMicrotaskResolutionStep::~CustomElementMicrotaskResolutionStep()
+{
+}
 
-    for (Vector<CustomElementCallbackQueue*>::iterator it = m_queue.begin(); it != m_queue.end(); ++it) {
-        // The created callback may schedule entered document
-        // callbacks.
-        CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope;
-        (*it)->processInElementQueue(baseQueueId);
-    }
-
-    m_queue.resize(0);
-    m_inDispatch = 0;
-
-    return didWork;
+CustomElementMicrotaskStep::Result CustomElementMicrotaskResolutionStep::process()
+{
+    m_context->resolve(m_element.get(), m_descriptor);
+    return CustomElementMicrotaskStep::Continue;
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElementBaseElementQueue.h b/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.h
similarity index 60%
copy from Source/core/dom/custom/CustomElementBaseElementQueue.h
copy to Source/core/dom/custom/CustomElementMicrotaskResolutionStep.h
index 78882aa..f77b2a8 100644
--- a/Source/core/dom/custom/CustomElementBaseElementQueue.h
+++ b/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.h
@@ -28,31 +28,37 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CustomElementBaseElementQueue_h
-#define CustomElementBaseElementQueue_h
+#ifndef CustomElementMicrotaskResolutionStep_h
+#define CustomElementMicrotaskResolutionStep_h
 
-#include "wtf/Vector.h"
+#include "core/dom/custom/CustomElementDescriptor.h"
+#include "core/dom/custom/CustomElementMicrotaskStep.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
-class CustomElementCallbackQueue;
+class CustomElementRegistrationContext;
+class Element;
 
-class CustomElementBaseElementQueue {
-    WTF_MAKE_NONCOPYABLE(CustomElementBaseElementQueue);
+class CustomElementMicrotaskResolutionStep : public CustomElementMicrotaskStep {
+    WTF_MAKE_NONCOPYABLE(CustomElementMicrotaskResolutionStep);
 public:
-    CustomElementBaseElementQueue() : m_inDispatch(false) { }
+    static PassOwnPtr<CustomElementMicrotaskResolutionStep> create(PassRefPtr<CustomElementRegistrationContext>, PassRefPtr<Element>, const CustomElementDescriptor&);
 
-    bool isEmpty() const { return m_queue.isEmpty(); }
-    void enqueue(CustomElementCallbackQueue*);
-
-    typedef int ElementQueue;
-    bool dispatch(ElementQueue baseQueueId);
+    virtual ~CustomElementMicrotaskResolutionStep();
 
 private:
-    bool m_inDispatch;
-    Vector<CustomElementCallbackQueue*> m_queue;
+    CustomElementMicrotaskResolutionStep(PassRefPtr<CustomElementRegistrationContext>, PassRefPtr<Element>, const CustomElementDescriptor&);
+
+    virtual Result process() OVERRIDE;
+
+    RefPtr<CustomElementRegistrationContext> m_context;
+    RefPtr<Element> m_element;
+    CustomElementDescriptor m_descriptor;
 };
 
 }
 
-#endif // CustomElementBaseElementQueue_h
+#endif // CustomElementMicrotaskResolutionStep_h
diff --git a/Source/core/dom/custom/CustomElementBaseElementQueue.h b/Source/core/dom/custom/CustomElementMicrotaskStep.h
similarity index 72%
copy from Source/core/dom/custom/CustomElementBaseElementQueue.h
copy to Source/core/dom/custom/CustomElementMicrotaskStep.h
index 78882aa..625067e 100644
--- a/Source/core/dom/custom/CustomElementBaseElementQueue.h
+++ b/Source/core/dom/custom/CustomElementMicrotaskStep.h
@@ -28,31 +28,27 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CustomElementBaseElementQueue_h
-#define CustomElementBaseElementQueue_h
+#ifndef CustomElementMicrotaskStep_h
+#define CustomElementMicrotaskStep_h
 
-#include "wtf/Vector.h"
+#include "wtf/Noncopyable.h"
 
 namespace WebCore {
 
-class CustomElementCallbackQueue;
-
-class CustomElementBaseElementQueue {
-    WTF_MAKE_NONCOPYABLE(CustomElementBaseElementQueue);
+class CustomElementMicrotaskStep {
+    WTF_MAKE_NONCOPYABLE(CustomElementMicrotaskStep);
 public:
-    CustomElementBaseElementQueue() : m_inDispatch(false) { }
+    CustomElementMicrotaskStep() { }
+    virtual ~CustomElementMicrotaskStep() { }
 
-    bool isEmpty() const { return m_queue.isEmpty(); }
-    void enqueue(CustomElementCallbackQueue*);
+    enum Result {
+        Continue   = 1 << 0,
+        ShouldStop = 1 << 1
+    };
 
-    typedef int ElementQueue;
-    bool dispatch(ElementQueue baseQueueId);
-
-private:
-    bool m_inDispatch;
-    Vector<CustomElementCallbackQueue*> m_queue;
+    virtual Result process() = 0;
 };
 
 }
 
-#endif // CustomElementBaseElementQueue_h
+#endif // CustomElementMicrotaskStep_h
diff --git a/Source/core/dom/custom/CustomElementBaseElementQueue.h b/Source/core/dom/custom/CustomElementProcessingStep.h
similarity index 72%
copy from Source/core/dom/custom/CustomElementBaseElementQueue.h
copy to Source/core/dom/custom/CustomElementProcessingStep.h
index 78882aa..c92451b 100644
--- a/Source/core/dom/custom/CustomElementBaseElementQueue.h
+++ b/Source/core/dom/custom/CustomElementProcessingStep.h
@@ -28,31 +28,25 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CustomElementBaseElementQueue_h
-#define CustomElementBaseElementQueue_h
+#ifndef CustomElementProcessingStep_h
+#define CustomElementProcessingStep_h
 
-#include "wtf/Vector.h"
+#include "wtf/Noncopyable.h"
 
 namespace WebCore {
 
-class CustomElementCallbackQueue;
+class Element;
 
-class CustomElementBaseElementQueue {
-    WTF_MAKE_NONCOPYABLE(CustomElementBaseElementQueue);
+class CustomElementProcessingStep {
+    WTF_MAKE_NONCOPYABLE(CustomElementProcessingStep);
 public:
-    CustomElementBaseElementQueue() : m_inDispatch(false) { }
+    CustomElementProcessingStep() { }
 
-    bool isEmpty() const { return m_queue.isEmpty(); }
-    void enqueue(CustomElementCallbackQueue*);
-
-    typedef int ElementQueue;
-    bool dispatch(ElementQueue baseQueueId);
-
-private:
-    bool m_inDispatch;
-    Vector<CustomElementCallbackQueue*> m_queue;
+    virtual ~CustomElementProcessingStep() { }
+    virtual void dispatch(Element*) = 0;
+    virtual bool isCreated() const { return false; }
 };
 
 }
 
-#endif // CustomElementBaseElementQueue_h
+#endif // CustomElementProcessingStep_h
diff --git a/Source/core/dom/custom/CustomElementRegistrationContext.cpp b/Source/core/dom/custom/CustomElementRegistrationContext.cpp
index e248ab7..bf15f69 100644
--- a/Source/core/dom/custom/CustomElementRegistrationContext.cpp
+++ b/Source/core/dom/custom/CustomElementRegistrationContext.cpp
@@ -36,8 +36,8 @@
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Element.h"
 #include "core/dom/custom/CustomElement.h"
-#include "core/dom/custom/CustomElementCallbackScheduler.h"
 #include "core/dom/custom/CustomElementDefinition.h"
+#include "core/dom/custom/CustomElementScheduler.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLUnknownElement.h"
 #include "core/svg/SVGUnknownElement.h"
@@ -55,7 +55,7 @@
     // Upgrade elements that were waiting for this definition.
     const CustomElementUpgradeCandidateMap::ElementSet& upgradeCandidates = m_candidates.takeUpgradeCandidatesFor(definition->descriptor());
     for (CustomElementUpgradeCandidateMap::ElementSet::const_iterator it = upgradeCandidates.begin(); it != upgradeCandidates.end(); ++it)
-        didResolveElement(definition, *it);
+        CustomElement::define(*it, definition);
 }
 
 PassRefPtr<Element> CustomElementRegistrationContext::createCustomTagElement(Document& document, const QualifiedName& tagName)
@@ -74,16 +74,16 @@
     }
 
     element->setCustomElementState(Element::WaitingForUpgrade);
-    resolve(element.get(), nullAtom);
+    resolveOrScheduleResolution(element.get(), nullAtom);
     return element.release();
 }
 
 void CustomElementRegistrationContext::didGiveTypeExtension(Element* element, const AtomicString& type)
 {
-    resolve(element, type);
+    resolveOrScheduleResolution(element, type);
 }
 
-void CustomElementRegistrationContext::resolve(Element* element, const AtomicString& typeExtension)
+void CustomElementRegistrationContext::resolveOrScheduleResolution(Element* element, const AtomicString& typeExtension)
 {
     // If an element has a custom tag name it takes precedence over
     // the "is" attribute (if any).
@@ -93,22 +93,20 @@
     ASSERT(!type.isNull());
 
     CustomElementDescriptor descriptor(type, element->namespaceURI(), element->localName());
-    CustomElementDefinition* definition = m_registry.find(descriptor);
-    if (definition)
-        didResolveElement(definition, element);
-    else
-        didCreateUnresolvedElement(descriptor, element);
-}
-
-void CustomElementRegistrationContext::didResolveElement(CustomElementDefinition* definition, Element* element)
-{
-    CustomElement::define(element, definition);
-}
-
-void CustomElementRegistrationContext::didCreateUnresolvedElement(const CustomElementDescriptor& descriptor, Element* element)
-{
     ASSERT(element->customElementState() == Element::WaitingForUpgrade);
-    m_candidates.add(descriptor, element);
+
+    CustomElementScheduler::resolveOrScheduleResolution(this, element, descriptor);
+}
+
+void CustomElementRegistrationContext::resolve(Element* element, const CustomElementDescriptor& descriptor)
+{
+    CustomElementDefinition* definition = m_registry.find(descriptor);
+    if (definition) {
+        CustomElement::define(element, definition);
+    } else {
+        ASSERT(element->customElementState() == Element::WaitingForUpgrade);
+        m_candidates.add(descriptor, element);
+    }
 }
 
 PassRefPtr<CustomElementRegistrationContext> CustomElementRegistrationContext::create()
diff --git a/Source/core/dom/custom/CustomElementRegistrationContext.h b/Source/core/dom/custom/CustomElementRegistrationContext.h
index 97dbc5f..40740c1 100644
--- a/Source/core/dom/custom/CustomElementRegistrationContext.h
+++ b/Source/core/dom/custom/CustomElementRegistrationContext.h
@@ -36,6 +36,7 @@
 #include "core/dom/custom/CustomElementRegistry.h"
 #include "core/dom/custom/CustomElementUpgradeCandidateMap.h"
 #include "wtf/HashMap.h"
+#include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/text/AtomicString.h"
 
@@ -60,6 +61,8 @@
     static void setIsAttributeAndTypeExtension(Element*, const AtomicString& type);
     static void setTypeExtension(Element*, const AtomicString& type);
 
+    void resolve(Element*, const CustomElementDescriptor&);
+
 protected:
     CustomElementRegistrationContext() { }
 
@@ -67,9 +70,7 @@
     void didGiveTypeExtension(Element*, const AtomicString& type);
 
 private:
-    void resolve(Element*, const AtomicString& typeExtension);
-    void didResolveElement(CustomElementDefinition*, Element*);
-    void didCreateUnresolvedElement(const CustomElementDescriptor&, Element*);
+    void resolveOrScheduleResolution(Element*, const AtomicString& typeExtension);
 
     CustomElementRegistry m_registry;
 
diff --git a/Source/core/dom/custom/CustomElementScheduler.cpp b/Source/core/dom/custom/CustomElementScheduler.cpp
new file mode 100644
index 0000000..f0ba5cf
--- /dev/null
+++ b/Source/core/dom/custom/CustomElementScheduler.cpp
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2013 Google Inc. 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.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ *    may be used to endorse or promote products derived from this
+ *    software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementScheduler.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/Element.h"
+#include "core/dom/custom/CustomElementCallbackDispatcher.h"
+#include "core/dom/custom/CustomElementCallbackInvocation.h"
+#include "core/dom/custom/CustomElementLifecycleCallbacks.h"
+#include "core/dom/custom/CustomElementMicrotaskDispatcher.h"
+#include "core/dom/custom/CustomElementMicrotaskImportStep.h"
+#include "core/dom/custom/CustomElementMicrotaskResolutionStep.h"
+#include "core/dom/custom/CustomElementRegistrationContext.h"
+#include "core/html/HTMLImportChild.h"
+
+namespace WebCore {
+
+class HTMLImport;
+
+void CustomElementScheduler::scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+{
+    CustomElementCallbackQueue* queue = instance().schedule(element);
+    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Created));
+}
+
+void CustomElementScheduler::scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
+{
+    if (!callbacks->hasAttributeChangedCallback())
+        return;
+
+    CustomElementCallbackQueue* queue = instance().schedule(element);
+    queue->append(CustomElementCallbackInvocation::createAttributeChangedInvocation(callbacks, name, oldValue, newValue));
+}
+
+void CustomElementScheduler::scheduleAttachedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+{
+    if (!callbacks->hasAttachedCallback())
+        return;
+
+    CustomElementCallbackQueue* queue = instance().schedule(element);
+    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Attached));
+}
+
+void CustomElementScheduler::scheduleDetachedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+{
+    if (!callbacks->hasDetachedCallback())
+        return;
+
+    CustomElementCallbackQueue* queue = instance().schedule(element);
+    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Detached));
+}
+
+void CustomElementScheduler::resolveOrScheduleResolution(PassRefPtr<CustomElementRegistrationContext> context, PassRefPtr<Element> element, const CustomElementDescriptor& descriptor)
+{
+    if (CustomElementCallbackDispatcher::inCallbackDeliveryScope()) {
+        context->resolve(element.get(), descriptor);
+        return;
+    }
+
+    HTMLImport* import = element->document().import();
+    OwnPtr<CustomElementMicrotaskResolutionStep> step = CustomElementMicrotaskResolutionStep::create(context, element, descriptor);
+    CustomElementMicrotaskDispatcher::instance().enqueue(import, step.release());
+}
+
+CustomElementMicrotaskImportStep* CustomElementScheduler::scheduleImport(HTMLImportChild* import)
+{
+    ASSERT(!import->isDone());
+    ASSERT(import->parent());
+
+    OwnPtr<CustomElementMicrotaskImportStep> step = CustomElementMicrotaskImportStep::create();
+    CustomElementMicrotaskImportStep* rawStep = step.get();
+
+    // Ownership of the new step is transferred to the parent
+    // processing step, or the base queue.
+    CustomElementMicrotaskDispatcher::instance().enqueue(import->parent(), step.release());
+
+    return rawStep;
+}
+
+CustomElementScheduler& CustomElementScheduler::instance()
+{
+    DEFINE_STATIC_LOCAL(CustomElementScheduler, instance, ());
+    return instance;
+}
+
+CustomElementCallbackQueue* CustomElementScheduler::ensureCallbackQueue(PassRefPtr<Element> element)
+{
+    Element* key = element.get();
+    ElementCallbackQueueMap::iterator it = m_elementCallbackQueueMap.find(key);
+    if (it == m_elementCallbackQueueMap.end())
+        return m_elementCallbackQueueMap.add(key, CustomElementCallbackQueue::create(element)).storedValue->value.get();
+    return it->value.get();
+}
+
+void CustomElementScheduler::callbackDispatcherDidFinish()
+{
+    if (CustomElementMicrotaskDispatcher::instance().elementQueueIsEmpty())
+        instance().clearElementCallbackQueueMap();
+}
+
+void CustomElementScheduler::microtaskDispatcherDidFinish()
+{
+    ASSERT(!CustomElementCallbackDispatcher::inCallbackDeliveryScope());
+    instance().clearElementCallbackQueueMap();
+}
+
+void CustomElementScheduler::clearElementCallbackQueueMap()
+{
+    ElementCallbackQueueMap emptyMap;
+    m_elementCallbackQueueMap.swap(emptyMap);
+}
+
+// Finds or creates the callback queue for element.
+CustomElementCallbackQueue* CustomElementScheduler::schedule(PassRefPtr<Element> passElement)
+{
+    RefPtr<Element> element(passElement);
+
+    CustomElementCallbackQueue* callbackQueue = ensureCallbackQueue(element);
+    if (callbackQueue->inCreatedCallback()) {
+        // Don't move it. Authors use the createdCallback like a
+        // constructor. By not moving it, the createdCallback
+        // completes before any other callbacks are entered for this
+        // element.
+        return callbackQueue;
+    }
+
+    if (CustomElementCallbackDispatcher::inCallbackDeliveryScope()) {
+        // The processing stack is active.
+        CustomElementCallbackDispatcher::instance().enqueue(callbackQueue);
+        return callbackQueue;
+    }
+
+    CustomElementMicrotaskDispatcher::instance().enqueue(callbackQueue);
+    return callbackQueue;
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/custom/CustomElementCallbackScheduler.h b/Source/core/dom/custom/CustomElementScheduler.h
similarity index 68%
rename from Source/core/dom/custom/CustomElementCallbackScheduler.h
rename to Source/core/dom/custom/CustomElementScheduler.h
index 0311d05..3bebdf3 100644
--- a/Source/core/dom/custom/CustomElementCallbackScheduler.h
+++ b/Source/core/dom/custom/CustomElementScheduler.h
@@ -28,8 +28,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef CustomElementCallbackScheduler_h
-#define CustomElementCallbackScheduler_h
+#ifndef CustomElementScheduler_h
+#define CustomElementScheduler_h
 
 #include "core/dom/custom/CustomElementCallbackQueue.h"
 #include "wtf/HashMap.h"
@@ -39,33 +39,44 @@
 
 namespace WebCore {
 
+class CustomElementDescriptor;
 class CustomElementLifecycleCallbacks;
+class CustomElementMicrotaskImportStep;
 class Element;
+class HTMLImportChild;
 
-class CustomElementCallbackScheduler {
+class CustomElementScheduler {
 public:
-    static void scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
     static void scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
-    static void scheduleEnteredViewCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
-    static void scheduleLeftViewCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+    static void scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
+    static void scheduleAttachedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+    static void scheduleDetachedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
 
-protected:
-    friend class CustomElementCallbackDispatcher;
-    static void clearElementCallbackQueueMap();
+    static void resolveOrScheduleResolution(PassRefPtr<CustomElementRegistrationContext>, PassRefPtr<Element>, const CustomElementDescriptor&);
+    static CustomElementMicrotaskImportStep* scheduleImport(HTMLImportChild*);
+
+    static void microtaskDispatcherDidFinish();
+    static void callbackDispatcherDidFinish();
 
 private:
-    CustomElementCallbackScheduler() { }
+    CustomElementScheduler() { }
 
-    static CustomElementCallbackScheduler& instance();
+    static CustomElementScheduler& instance();
 
     CustomElementCallbackQueue* ensureCallbackQueue(PassRefPtr<Element>);
     CustomElementCallbackQueue* schedule(PassRefPtr<Element>);
-    CustomElementCallbackQueue* scheduleInCurrentElementQueue(PassRefPtr<Element>);
 
+    // FIXME: Consider moving the element's callback queue to
+    // ElementRareData. Then the scheduler can become completely
+    // static.
+    void clearElementCallbackQueueMap();
+
+    // The element -> callback queue map is populated by the scheduler
+    // and owns the lifetimes of the CustomElementCallbackQueues.
     typedef HashMap<Element*, OwnPtr<CustomElementCallbackQueue> > ElementCallbackQueueMap;
     ElementCallbackQueueMap m_elementCallbackQueueMap;
 };
 
 }
 
-#endif // CustomElementCallbackScheduler_h
+#endif // CustomElementScheduler_h
diff --git a/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp b/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
index b7ea628..ccbbed3 100644
--- a/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
+++ b/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
@@ -50,9 +50,12 @@
     ASSERT_UNUSED(result, result.isNewEntry);
 
     UnresolvedDefinitionMap::iterator it = m_unresolvedDefinitions.find(descriptor);
+    ElementSet* elements;
     if (it == m_unresolvedDefinitions.end())
-        it = m_unresolvedDefinitions.add(descriptor, ElementSet()).iterator;
-    it->value.add(element);
+        elements = &m_unresolvedDefinitions.add(descriptor, ElementSet()).storedValue->value;
+    else
+        elements = &it->value;
+    elements->add(element);
 }
 
 void CustomElementUpgradeCandidateMap::remove(Element* element)
diff --git a/Source/core/dom/shadow/ComposedTreeWalker.cpp b/Source/core/dom/shadow/ComposedTreeWalker.cpp
index 2a15612..3ffc70c 100644
--- a/Source/core/dom/shadow/ComposedTreeWalker.cpp
+++ b/Source/core/dom/shadow/ComposedTreeWalker.cpp
@@ -30,7 +30,6 @@
 
 #include "core/dom/Element.h"
 #include "core/dom/shadow/ElementShadow.h"
-#include "core/html/shadow/HTMLContentElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 
 namespace WebCore {
@@ -73,7 +72,7 @@
     const InsertionPoint* insertionPoint = toInsertionPoint(node);
     if (Node* found = traverseDistributedNodes(direction == TraversalDirectionForward ? insertionPoint->first() : insertionPoint->last(), insertionPoint, direction))
         return found;
-    ASSERT(isHTMLShadowElement(node) || (isHTMLContentElement(node) && !node->hasChildNodes()));
+    ASSERT(node->hasTagName(HTMLNames::shadowTag) || (node->hasTagName(HTMLNames::contentTag) && !node->hasChildNodes()));
     return 0;
 }
 
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 913bb93..17ee8ba 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -27,6 +27,8 @@
 #include "config.h"
 #include "core/dom/shadow/ElementShadow.h"
 
+
+#include "core/css/StyleSheetList.h"
 #include "core/dom/ContainerNodeAlgorithms.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/NodeTraversal.h"
@@ -86,7 +88,7 @@
         if (m_distributed[i])
             continue;
 
-        if (isHTMLContentElement(insertionPoint) && !toHTMLContentElement(insertionPoint)->canSelectNode(m_nodes, i))
+        if (insertionPoint->hasTagName(HTMLNames::contentTag) && !toHTMLContentElement(insertionPoint)->canSelectNode(m_nodes, i))
             continue;
 
         Node* node = m_nodes[i];
@@ -134,18 +136,18 @@
 
 ElementShadow::~ElementShadow()
 {
-    removeAllShadowRoots();
+    removeDetachedShadowRoots();
 }
 
 ShadowRoot& ElementShadow::addShadowRoot(Element& shadowHost, ShadowRoot::ShadowRootType type)
 {
-    RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(&shadowHost.document(), type);
+    RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(shadowHost.document(), type);
 
     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot())
         root->lazyReattachIfAttached();
 
     shadowRoot->setParentOrShadowHostNode(&shadowHost);
-    shadowRoot->setParentTreeScope(&shadowHost.treeScope());
+    shadowRoot->setParentTreeScope(shadowHost.treeScope());
     m_shadowRoots.push(shadowRoot.get());
     ChildNodeInsertionNotifier(shadowHost).notify(*shadowRoot);
     setNeedsDistributionRecalc();
@@ -162,7 +164,7 @@
     return *m_shadowRoots.head();
 }
 
-void ElementShadow::removeAllShadowRoots()
+void ElementShadow::removeDetachedShadowRoots()
 {
     // Dont protect this ref count.
     Element* shadowHost = host();
@@ -173,11 +175,11 @@
         shadowHost->document().removeFocusedElementOfSubtree(oldRoot.get());
         m_shadowRoots.removeHead();
         oldRoot->setParentOrShadowHostNode(0);
-        oldRoot->setParentTreeScope(&shadowHost->document());
+        oldRoot->setParentTreeScope(shadowHost->document());
         oldRoot->setPrev(0);
         oldRoot->setNext(0);
-        ChildNodeRemovalNotifier(*shadowHost).notify(*oldRoot);
     }
+
 }
 
 void ElementShadow::attach(const Node::AttachContext& context)
@@ -239,6 +241,31 @@
     return false;
 }
 
+bool ElementShadow::hasSameStyles(ElementShadow *other) const
+{
+    ShadowRoot* root = youngestShadowRoot();
+    ShadowRoot* otherRoot = other->youngestShadowRoot();
+    while (root || otherRoot) {
+        if (!root || !otherRoot)
+            return false;
+
+        StyleSheetList* list = root->styleSheets();
+        StyleSheetList* otherList = otherRoot->styleSheets();
+
+        if (list->length() != otherList->length())
+            return false;
+
+        for (size_t i = 0; i < list->length(); i++) {
+            if (toCSSStyleSheet(list->item(i))->contents() != toCSSStyleSheet(otherList->item(i))->contents())
+                return false;
+        }
+        root = root->olderShadowRoot();
+        otherRoot = otherRoot->olderShadowRoot();
+    }
+
+    return true;
+}
+
 bool ElementShadow::resolveApplyAuthorStyles() const
 {
     for (const ShadowRoot* shadowRoot = youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
@@ -264,7 +291,7 @@
 
 void ElementShadow::distribute()
 {
-    host()->setNeedsStyleRecalc();
+    host()->setNeedsStyleRecalc(SubtreeStyleChange);
     Vector<HTMLShadowElement*, 32> shadowInsertionPoints;
     DistributionPool pool(*host());
 
@@ -275,22 +302,16 @@
             InsertionPoint* point = insertionPoints[i].get();
             if (!point->isActive())
                 continue;
-            if (isHTMLShadowElement(point)) {
-                if (!shadowInsertionPoint)
-                    shadowInsertionPoint = toHTMLShadowElement(point);
+            if (point->hasTagName(HTMLNames::shadowTag)) {
+                ASSERT(!shadowInsertionPoint);
+                shadowInsertionPoint = toHTMLShadowElement(point);
+                shadowInsertionPoints.append(shadowInsertionPoint);
             } else {
                 pool.distributeTo(point, this);
                 if (ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*point))
                     shadow->setNeedsDistributionRecalc();
             }
         }
-        if (shadowInsertionPoint) {
-            shadowInsertionPoints.append(shadowInsertionPoint);
-            if (shadowInsertionPoint->hasChildNodes())
-                pool.populateChildren(*shadowInsertionPoint);
-        } else {
-            pool.clear();
-        }
     }
 
     for (size_t i = shadowInsertionPoints.size(); i > 0; --i) {
@@ -314,7 +335,7 @@
 void ElementShadow::didDistributeNode(const Node* node, InsertionPoint* insertionPoint)
 {
     NodeToDestinationInsertionPoints::AddResult result = m_nodeToInsertionPoints.add(node, DestinationInsertionPoints());
-    result.iterator->value.append(insertionPoint);
+    result.storedValue->value.append(insertionPoint);
 }
 
 const SelectRuleFeatureSet& ElementShadow::ensureSelectFeatureSet()
@@ -337,12 +358,12 @@
     for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(*element, &root)) {
         if (ElementShadow* shadow = element->shadow())
             m_selectFeatures.add(shadow->ensureSelectFeatureSet());
-        if (!isHTMLContentElement(element))
+        if (!element->hasTagName(HTMLNames::contentTag))
             continue;
         const CSSSelectorList& list = toHTMLContentElement(element)->selectorList();
-        for (const CSSSelector* selector = list.first(); selector; selector = CSSSelectorList::next(selector)) {
+        for (const CSSSelector* selector = list.first(); selector; selector = CSSSelectorList::next(*selector)) {
             for (const CSSSelector* component = selector; component; component = component->tagHistory())
-                m_selectFeatures.collectFeaturesFromSelector(component);
+                m_selectFeatures.collectFeaturesFromSelector(*component);
         }
     }
 }
diff --git a/Source/core/dom/shadow/ElementShadow.h b/Source/core/dom/shadow/ElementShadow.h
index 9017ddc..aaeff7b 100644
--- a/Source/core/dom/shadow/ElementShadow.h
+++ b/Source/core/dom/shadow/ElementShadow.h
@@ -55,6 +55,7 @@
     bool applyAuthorStyles() const { return m_applyAuthorStyles; }
     bool didAffectApplyAuthorStyles();
     bool containsActiveStyles() const;
+    bool hasSameStyles(ElementShadow *) const;
 
     void attach(const Node::AttachContext&);
     void detach(const Node::AttachContext&);
@@ -76,7 +77,7 @@
 private:
     ElementShadow();
 
-    void removeAllShadowRoots();
+    void removeDetachedShadowRoots();
     bool resolveApplyAuthorStyles() const;
 
     void distribute();
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
index e3c5d4d..4099b88 100644
--- a/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -36,8 +36,6 @@
 #include "core/dom/QualifiedName.h"
 #include "core/dom/StaticNodeList.h"
 #include "core/dom/shadow/ElementShadow.h"
-#include "core/html/shadow/HTMLContentElement.h"
-#include "core/html/shadow/HTMLShadowElement.h"
 
 namespace WebCore {
 
@@ -100,7 +98,7 @@
 void InsertionPoint::attach(const AttachContext& context)
 {
     // We need to attach the distribution here so that they're inserted in the right order
-    // otherwise the n^2 protection inside NodeRenderingContext will cause them to be
+    // otherwise the n^2 protection inside RenderTreeBuilder will cause them to be
     // inserted in the wrong place later. This also lets distributed nodes benefit from
     // the n^2 protection.
     for (size_t i = 0; i < m_distribution.size(); ++i) {
@@ -136,16 +134,9 @@
 {
     if (!isInShadowTree())
         return false;
-    bool foundShadowElementInAncestors = false;
-    bool thisIsContentHTMLElement = isHTMLContentElement(this);
     for (Node* node = parentNode(); node; node = node->parentNode()) {
-        if (node->isInsertionPoint()) {
-            // For HTMLContentElement, at most one HTMLShadowElement may appear in its ancestors.
-            if (thisIsContentHTMLElement && isHTMLShadowElement(node) && !foundShadowElementInAncestors)
-                foundShadowElementInAncestors = true;
-            else
-                return false;
-        }
+        if (node->isInsertionPoint())
+            return false;
     }
     return true;
 }
@@ -155,15 +146,16 @@
     if (!canBeActive())
         return false;
     ShadowRoot* shadowRoot = containingShadowRoot();
-    ASSERT(shadowRoot);
-    if (!isHTMLShadowElement(this) || shadowRoot->descendantShadowElementCount() <= 1)
+    if (!shadowRoot)
+        return false;
+    if (!hasTagName(shadowTag) || shadowRoot->descendantShadowElementCount() <= 1)
         return true;
 
     // Slow path only when there are more than one shadow elements in a shadow tree. That should be a rare case.
     const Vector<RefPtr<InsertionPoint> >& insertionPoints = shadowRoot->descendantInsertionPoints();
     for (size_t i = 0; i < insertionPoints.size(); ++i) {
         InsertionPoint* point = insertionPoints[i].get();
-        if (isHTMLShadowElement(point))
+        if (point->hasTagName(shadowTag))
             return point == this;
     }
     return true;
@@ -171,12 +163,12 @@
 
 bool InsertionPoint::isShadowInsertionPoint() const
 {
-    return isHTMLShadowElement(this) && isActive();
+    return hasTagName(shadowTag) && isActive();
 }
 
 bool InsertionPoint::isContentInsertionPoint() const
 {
-    return isHTMLContentElement(this) && isActive();
+    return hasTagName(contentTag) && isActive();
 }
 
 PassRefPtr<NodeList> InsertionPoint::getDistributedNodes()
@@ -260,7 +252,7 @@
     if (name == reset_style_inheritanceAttr) {
         if (!inDocument() || !isActive())
             return;
-        containingShadowRoot()->host()->setNeedsStyleRecalc();
+        containingShadowRoot()->host()->setNeedsStyleRecalc(SubtreeStyleChange);
     } else
         HTMLElement::parseAttribute(name, value);
 }
diff --git a/Source/core/dom/shadow/InsertionPoint.h b/Source/core/dom/shadow/InsertionPoint.h
index 639a52f..05f2ac9 100644
--- a/Source/core/dom/shadow/InsertionPoint.h
+++ b/Source/core/dom/shadow/InsertionPoint.h
@@ -87,23 +87,7 @@
 
 typedef Vector<RefPtr<InsertionPoint> > DestinationInsertionPoints;
 
-inline InsertionPoint* toInsertionPoint(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isInsertionPoint());
-    return static_cast<InsertionPoint*>(node);
-}
-
-inline const InsertionPoint* toInsertionPoint(const Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isInsertionPoint());
-    return static_cast<const InsertionPoint*>(node);
-}
-
-inline const InsertionPoint& toInsertionPoint(const Node& node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(node.isInsertionPoint());
-    return static_cast<const InsertionPoint&>(node);
-}
+DEFINE_NODE_TYPE_CASTS(InsertionPoint, isInsertionPoint());
 
 inline bool isActiveInsertionPoint(const Node& node)
 {
diff --git a/Source/core/dom/shadow/SelectRuleFeatureSet.cpp b/Source/core/dom/shadow/SelectRuleFeatureSet.cpp
index 4f6f526..25757e6 100644
--- a/Source/core/dom/shadow/SelectRuleFeatureSet.cpp
+++ b/Source/core/dom/shadow/SelectRuleFeatureSet.cpp
@@ -33,6 +33,8 @@
 
 #include "core/css/CSSSelector.h"
 
+#include "wtf/BitVector.h"
+
 namespace WebCore {
 
 SelectRuleFeatureSet::SelectRuleFeatureSet()
@@ -52,11 +54,11 @@
     m_featureFlags = 0;
 }
 
-void SelectRuleFeatureSet::collectFeaturesFromSelector(const CSSSelector* selector)
+void SelectRuleFeatureSet::collectFeaturesFromSelector(const CSSSelector& selector)
 {
     m_cssRuleFeatureSet.collectFeaturesFromSelector(selector);
 
-    switch (selector->pseudoType()) {
+    switch (selector.pseudoType()) {
     case CSSSelector::PseudoChecked:
         setSelectRuleFeature(AffectedSelectorChecked);
         break;
@@ -83,5 +85,53 @@
     }
 }
 
+bool SelectRuleFeatureSet::checkSelectorsForClassChange(const SpaceSplitString& changedClasses) const
+{
+    unsigned changedSize = changedClasses.size();
+    for (unsigned i = 0; i < changedSize; ++i) {
+        if (hasSelectorForClass(changedClasses[i]))
+            return true;
+    }
+    return false;
+}
+
+bool SelectRuleFeatureSet::checkSelectorsForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses) const
+{
+    if (!oldClasses.size())
+        return checkSelectorsForClassChange(newClasses);
+
+    // Class vectors tend to be very short. This is faster than using a hash table.
+    BitVector remainingClassBits;
+    remainingClassBits.ensureSize(oldClasses.size());
+
+    for (unsigned i = 0; i < newClasses.size(); ++i) {
+        bool found = false;
+        for (unsigned j = 0; j < oldClasses.size(); ++j) {
+            if (newClasses[i] == oldClasses[j]) {
+                // Mark each class that is still in the newClasses so we can skip doing
+                // an n^2 search below when looking for removals. We can't break from
+                // this loop early since a class can appear more than once.
+                remainingClassBits.quickSet(j);
+                found = true;
+            }
+        }
+        // Class was added.
+        if (!found) {
+            if (hasSelectorForClass(newClasses[i]))
+                return true;
+        }
+    }
+
+    for (unsigned i = 0; i < oldClasses.size(); ++i) {
+        if (remainingClassBits.quickGet(i))
+            continue;
+
+        // Class was removed.
+        if (hasSelectorForClass(oldClasses[i]))
+            return true;
+    }
+    return false;
+}
+
 }
 
diff --git a/Source/core/dom/shadow/SelectRuleFeatureSet.h b/Source/core/dom/shadow/SelectRuleFeatureSet.h
index 429d277..41c3134 100644
--- a/Source/core/dom/shadow/SelectRuleFeatureSet.h
+++ b/Source/core/dom/shadow/SelectRuleFeatureSet.h
@@ -36,13 +36,16 @@
 
 namespace WebCore {
 
+class Element;
+class SpaceSplitString;
+
 class SelectRuleFeatureSet {
 public:
     SelectRuleFeatureSet();
 
     void add(const SelectRuleFeatureSet&);
     void clear();
-    void collectFeaturesFromSelector(const CSSSelector*);
+    void collectFeaturesFromSelector(const CSSSelector&);
 
     bool hasSelectorForId(const AtomicString&) const;
     bool hasSelectorForClass(const AtomicString&) const;
@@ -58,6 +61,9 @@
 
     bool hasSelectorFor(AffectedSelectorMask features) const { return m_featureFlags & features; }
 
+    bool checkSelectorsForClassChange(const SpaceSplitString& changedClasses) const;
+    bool checkSelectorsForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses) const;
+
 private:
     void setSelectRuleFeature(AffectedSelectorType feature) { m_featureFlags |= feature; }
 
@@ -68,19 +74,19 @@
 inline bool SelectRuleFeatureSet::hasSelectorForId(const AtomicString& idValue) const
 {
     ASSERT(!idValue.isEmpty());
-    return m_cssRuleFeatureSet.idsInRules.contains(idValue);
+    return m_cssRuleFeatureSet.hasSelectorForId(idValue);
 }
 
 inline bool SelectRuleFeatureSet::hasSelectorForClass(const AtomicString& classValue) const
 {
     ASSERT(!classValue.isEmpty());
-    return m_cssRuleFeatureSet.classesInRules.contains(classValue);
+    return m_cssRuleFeatureSet.hasSelectorForClass(classValue);
 }
 
 inline bool SelectRuleFeatureSet::hasSelectorForAttribute(const AtomicString& attributeName) const
 {
     ASSERT(!attributeName.isEmpty());
-    return m_cssRuleFeatureSet.attrsInRules.contains(attributeName);
+    return m_cssRuleFeatureSet.hasSelectorForAttribute(attributeName);
 }
 
 }
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index c9f7909..80be155 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -37,6 +37,7 @@
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRootRareData.h"
 #include "core/editing/markup.h"
+#include "core/html/shadow/HTMLShadowElement.h"
 #include "public/platform/Platform.h"
 
 namespace WebCore {
@@ -54,9 +55,9 @@
     ShadowRootUsageOriginMax
 };
 
-ShadowRoot::ShadowRoot(Document* document, ShadowRootType type)
+ShadowRoot::ShadowRoot(Document& document, ShadowRootType type)
     : DocumentFragment(0, CreateShadowRoot)
-    , TreeScope(this, document)
+    , TreeScope(*this, document)
     , m_prev(0)
     , m_next(0)
     , m_numberOfStyles(0)
@@ -66,11 +67,10 @@
     , m_registeredWithParentShadowRoot(false)
     , m_descendantInsertionPointsIsValid(false)
 {
-    ASSERT(document);
     ScriptWrappable::init(this);
 
     if (type == ShadowRoot::AuthorShadowRoot) {
-        ShadowRootUsageOriginType usageType = document->url().protocolIsInHTTPFamily() ? ShadowRootUsageOriginWeb : ShadowRootUsageOriginNotWeb;
+        ShadowRootUsageOriginType usageType = document.url().protocolIsInHTTPFamily() ? ShadowRootUsageOriginWeb : ShadowRootUsageOriginNotWeb;
         blink::Platform::current()->histogramEnumeration("WebCore.ShadowRoot.constructor", usageType, ShadowRootUsageOriginMax);
     }
 }
@@ -83,7 +83,7 @@
     if (m_shadowRootRareData && m_shadowRootRareData->styleSheets())
         m_shadowRootRareData->styleSheets()->detachFromDocument();
 
-    documentInternal()->styleEngine()->didRemoveShadowRoot(this);
+    document().styleEngine()->didRemoveShadowRoot(this);
 
     // We cannot let ContainerNode destructor call willBeDeletedFromDocument()
     // for this ShadowRoot instance because TreeScope destructor
@@ -107,7 +107,7 @@
     removeDetachedChildren();
 }
 
-ShadowRoot* ShadowRoot::bindingsOlderShadowRoot() const
+ShadowRoot* ShadowRoot::olderShadowRootForBindings() const
 {
     ShadowRoot* older = olderShadowRoot();
     while (older && !older->shouldExposeToBindings())
@@ -147,25 +147,16 @@
         replaceChildrenWithFragment(this, fragment.release(), exceptionState);
 }
 
-bool ShadowRoot::childTypeAllowed(NodeType type) const
-{
-    switch (type) {
-    case ELEMENT_NODE:
-    case PROCESSING_INSTRUCTION_NODE:
-    case COMMENT_NODE:
-    case TEXT_NODE:
-    case CDATA_SECTION_NODE:
-        return true;
-    default:
-        return false;
-    }
-}
-
 void ShadowRoot::recalcStyle(StyleRecalcChange change)
 {
     // ShadowRoot doesn't support custom callbacks.
     ASSERT(!hasCustomStyleCallbacks());
 
+    // If we're propagating an Inherit change and this ShadowRoot resets
+    // inheritance we don't need to look at the children.
+    if (change <= Inherit && resetStyleInheritance() && !needsStyleRecalc() && !childNeedsStyleRecalc())
+        return;
+
     StyleResolver& styleResolver = document().ensureStyleResolver();
     styleResolver.pushParentShadowRoot(*this);
 
@@ -182,7 +173,7 @@
             toText(child)->recalcTextStyle(change, lastTextNode);
             lastTextNode = toText(child);
         } else if (child->isElementNode()) {
-            if (shouldRecalcStyle(change, child))
+            if (child->shouldCallRecalcStyle(change))
                 toElement(child)->recalcStyle(change, lastTextNode);
             if (child->renderer())
                 lastTextNode = 0;
@@ -194,12 +185,16 @@
     clearChildNeedsStyleRecalc();
 }
 
-bool ShadowRoot::isActive() const
+bool ShadowRoot::isActiveForStyling() const
 {
-    for (ShadowRoot* shadowRoot = youngerShadowRoot(); shadowRoot; shadowRoot = shadowRoot->youngerShadowRoot())
-        if (!shadowRoot->containsShadowElements())
-            return false;
-    return true;
+    if (!youngerShadowRoot())
+        return true;
+
+    if (InsertionPoint* point = shadowInsertionPointOfYoungerShadowRoot()) {
+        if (point->containingShadowRoot())
+            return true;
+    }
+    return false;
 }
 
 void ShadowRoot::setApplyAuthorStyles(bool value)
@@ -211,13 +206,13 @@
         return;
 
     m_applyAuthorStyles = value;
-    if (!isActive())
+    if (!isActiveForStyling())
         return;
 
     ASSERT(host());
     ASSERT(host()->shadow());
     if (host()->shadow()->didAffectApplyAuthorStyles())
-        host()->setNeedsStyleRecalc();
+        host()->setNeedsStyleRecalc(SubtreeStyleChange);
 
     // Since styles in shadow trees can select shadow hosts, set shadow host's needs-recalc flag true.
     // FIXME: host->setNeedsStyleRecalc() should take care of all elements in its shadow tree.
@@ -225,7 +220,7 @@
     // no recalc style is invoked for any elements in its shadow tree.
     // This problem occurs when using getComputedStyle() API.
     // So currently host and shadow root's needsStyleRecalc flags are set to be true.
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 void ShadowRoot::setResetStyleInheritance(bool value)
@@ -237,10 +232,10 @@
         return;
 
     m_resetStyleInheritance = value;
-    if (!isActive())
+    if (!isActiveForStyling())
         return;
 
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 void ShadowRoot::attach(const AttachContext& context)
diff --git a/Source/core/dom/shadow/ShadowRoot.h b/Source/core/dom/shadow/ShadowRoot.h
index 768f78b..98ca4ce 100644
--- a/Source/core/dom/shadow/ShadowRoot.h
+++ b/Source/core/dom/shadow/ShadowRoot.h
@@ -54,19 +54,22 @@
         AuthorShadowRoot
     };
 
-    static PassRefPtr<ShadowRoot> create(Document* document, ShadowRootType type)
+    static PassRefPtr<ShadowRoot> create(Document& document, ShadowRootType type)
     {
         return adoptRef(new ShadowRoot(document, type));
     }
 
     void recalcStyle(StyleRecalcChange);
 
+    // Disambiguate between Node and TreeScope hierarchies; TreeScope's implementation is simpler.
+    using TreeScope::document;
+
     Element* host() const { return toElement(parentOrShadowHostNode()); }
     ElementShadow* owner() const { return host() ? host()->shadow() : 0; }
 
     ShadowRoot* youngerShadowRoot() const { return prev(); }
 
-    ShadowRoot* bindingsOlderShadowRoot() const;
+    ShadowRoot* olderShadowRootForBindings() const;
     bool shouldExposeToBindings() const { return type() == AuthorShadowRoot; }
 
     bool isYoungest() const { return !youngerShadowRoot(); }
@@ -100,6 +103,10 @@
 
     ShadowRootType type() const { return static_cast<ShadowRootType>(m_type); }
 
+    // Make protected methods from base class public here.
+    using TreeScope::setDocument;
+    using TreeScope::setParentTreeScope;
+
 public:
     Element* activeElement() const;
 
@@ -118,13 +125,13 @@
     PassRefPtr<Node> cloneNode(ExceptionState& exceptionState) { return cloneNode(true, exceptionState); }
 
     StyleSheetList* styleSheets();
+    bool isActiveForStyling() const;
 
 private:
-    ShadowRoot(Document*, ShadowRootType);
+    ShadowRoot(Document&, ShadowRootType);
     virtual ~ShadowRoot();
 
     virtual void dispose() OVERRIDE;
-    virtual bool childTypeAllowed(NodeType) const OVERRIDE;
     virtual void childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) OVERRIDE;
 
     ShadowRootRareData* ensureShadowRootRareData();
@@ -138,7 +145,6 @@
 
     // FIXME: This shouldn't happen. https://bugs.webkit.org/show_bug.cgi?id=88834
     bool isOrphan() const { return !host(); }
-    bool isActive() const;
 
     ShadowRoot* m_prev;
     ShadowRoot* m_next;
@@ -156,45 +162,8 @@
     return adjustedFocusedElement();
 }
 
-inline const ShadowRoot* toShadowRoot(const Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isShadowRoot());
-    return static_cast<const ShadowRoot*>(node);
-}
-
-inline ShadowRoot* toShadowRoot(Node* node)
-{
-    return const_cast<ShadowRoot*>(toShadowRoot(static_cast<const Node*>(node)));
-}
-
-inline ShadowRoot& toShadowRoot(Node& node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(node.isShadowRoot());
-    return static_cast<ShadowRoot&>(node);
-}
-
-inline const ShadowRoot& toShadowRoot(const Node& node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(node.isShadowRoot());
-    return static_cast<const ShadowRoot&>(node);
-}
-
-inline const ShadowRoot* toShadowRoot(const TreeScope* treeScope)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!treeScope || (treeScope->rootNode() && treeScope->rootNode()->isShadowRoot()));
-    return static_cast<const ShadowRoot*>(treeScope);
-}
-
-inline ShadowRoot* toShadowRoot(TreeScope* treeScope)
-{
-    return const_cast<ShadowRoot*>(toShadowRoot(static_cast<const TreeScope*>(treeScope)));
-}
-
-inline ShadowRoot& toShadowRoot(TreeScope& treeScope)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(treeScope.rootNode() && treeScope.rootNode()->isShadowRoot());
-    return static_cast<ShadowRoot&>(treeScope);
-}
+DEFINE_NODE_TYPE_CASTS(ShadowRoot, isShadowRoot());
+DEFINE_TYPE_CASTS(ShadowRoot, TreeScope, treeScope, treeScope->rootNode().isShadowRoot(), treeScope.rootNode().isShadowRoot());
 
 } // namespace
 
diff --git a/Source/core/dom/shadow/ShadowRoot.idl b/Source/core/dom/shadow/ShadowRoot.idl
index c84d177..241c2f6 100644
--- a/Source/core/dom/shadow/ShadowRoot.idl
+++ b/Source/core/dom/shadow/ShadowRoot.idl
@@ -28,19 +28,19 @@
     NoInterfaceObject
 ] interface ShadowRoot : DocumentFragment {
     readonly attribute Element activeElement;
-    attribute boolean applyAuthorStyles;
+    [DeprecateAs=ShadowRootApplyAuthorStyles] attribute boolean applyAuthorStyles;
     attribute boolean resetStyleInheritance;
-    [RuntimeEnabled=ShadowDOM, ImplementedAs=bindingsOlderShadowRoot] readonly attribute ShadowRoot olderShadowRoot;
+    [RuntimeEnabled=ShadowDOM, ImplementedAs=olderShadowRootForBindings] readonly attribute ShadowRoot olderShadowRoot;
 
     [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, RaisesException=Setter] attribute DOMString innerHTML;
 
     [RaisesException] Node cloneNode([Default=Undefined] optional boolean deep);
     Selection getSelection();
     Element getElementById([Default=Undefined] optional DOMString elementId);
-    NodeList getElementsByClassName([Default=Undefined] optional DOMString className);
-    NodeList getElementsByTagName([Default=Undefined] optional DOMString tagName);
-    NodeList getElementsByTagNameNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
-                                    [Default=Undefined] optional DOMString localName);
+    HTMLCollection getElementsByClassName([Default=Undefined] optional DOMString className);
+    HTMLCollection getElementsByTagName([Default=Undefined] optional DOMString tagName);
+    HTMLCollection getElementsByTagNameNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
+                                          [Default=Undefined] optional DOMString localName);
 
     Element elementFromPoint([Default=Undefined] optional long x,
                              [Default=Undefined] optional long y);
diff --git a/Source/core/dom/shadow/ShadowRootRareData.h b/Source/core/dom/shadow/ShadowRootRareData.h
index dae72a7..7ad8ef6 100644
--- a/Source/core/dom/shadow/ShadowRootRareData.h
+++ b/Source/core/dom/shadow/ShadowRootRareData.h
@@ -32,8 +32,6 @@
 #define ShadowRootRareData_h
 
 #include "core/dom/shadow/InsertionPoint.h"
-#include "core/html/shadow/HTMLContentElement.h"
-#include "core/html/shadow/HTMLShadowElement.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
 
@@ -83,9 +81,9 @@
 
 inline void ShadowRootRareData::didAddInsertionPoint(InsertionPoint* point)
 {
-    if (isHTMLShadowElement(point))
+    if (point->hasTagName(HTMLNames::shadowTag))
         ++m_descendantShadowElementCount;
-    else if (isHTMLContentElement(point))
+    else if (point->hasTagName(HTMLNames::contentTag))
         ++m_descendantContentElementCount;
     else
         ASSERT_NOT_REACHED();
@@ -93,9 +91,9 @@
 
 inline void ShadowRootRareData::didRemoveInsertionPoint(InsertionPoint* point)
 {
-    if (isHTMLShadowElement(point))
+    if (point->hasTagName(HTMLNames::shadowTag))
         --m_descendantShadowElementCount;
-    else if (isHTMLContentElement(point))
+    else if (point->hasTagName(HTMLNames::contentTag))
         --m_descendantContentElementCount;
     else
         ASSERT_NOT_REACHED();
diff --git a/Source/core/editing/AppendNodeCommand.h b/Source/core/editing/AppendNodeCommand.h
index 1f7a5ae..fe35353 100644
--- a/Source/core/editing/AppendNodeCommand.h
+++ b/Source/core/editing/AppendNodeCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class AppendNodeCommand : public SimpleEditCommand {
+class AppendNodeCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<AppendNodeCommand> create(PassRefPtr<ContainerNode> parent, PassRefPtr<Node> node)
     {
diff --git a/Source/core/editing/ApplyBlockElementCommand.h b/Source/core/editing/ApplyBlockElementCommand.h
index 72fdc91..d8c6fd6 100644
--- a/Source/core/editing/ApplyBlockElementCommand.h
+++ b/Source/core/editing/ApplyBlockElementCommand.h
@@ -46,7 +46,7 @@
     const QualifiedName tagName() const { return m_tagName; }
 
 private:
-    virtual void doApply();
+    virtual void doApply() OVERRIDE FINAL;
     virtual void formatRange(const Position& start, const Position& end, const Position& endOfSelection, RefPtr<Element>&) = 0;
     void rangeForParagraphSplittingTextNodesIfNeeded(const VisiblePosition&, Position&, Position&);
     VisiblePosition endOfNextParagrahSplittingTextNodesIfNeeded(VisiblePosition&, Position&, Position&);
diff --git a/Source/core/editing/ApplyStyleCommand.cpp b/Source/core/editing/ApplyStyleCommand.cpp
index ec1b5f3..bda5ae2 100644
--- a/Source/core/editing/ApplyStyleCommand.cpp
+++ b/Source/core/editing/ApplyStyleCommand.cpp
@@ -400,7 +400,7 @@
         }
         if (currentFontSize != desiredFontSize) {
             inlineStyle->setProperty(CSSPropertyFontSize, cssValuePool().createValue(desiredFontSize, CSSPrimitiveValue::CSS_PX), false);
-            setNodeAttribute(element.get(), styleAttr, inlineStyle->asText());
+            setNodeAttribute(element.get(), styleAttr, AtomicString(inlineStyle->asText()));
         }
         if (inlineStyle->isEmpty()) {
             removeNodeAttribute(element.get(), styleAttr);
@@ -496,9 +496,7 @@
     if (!block)
         return;
 
-    Node* parent = 0;
-    for (Node* n = node->parentNode(); n != block && n != unsplitAncestor; n = parent) {
-        parent = n->parentNode();
+    for (Node* n = node->parentNode(); n != block && n != unsplitAncestor; n = n->parentNode()) {
         if (!n->isStyledElement())
             continue;
 
@@ -519,7 +517,7 @@
             RefPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
             inlineStyle->setProperty(CSSPropertyUnicodeBidi, CSSValueNormal);
             inlineStyle->removeProperty(CSSPropertyDirection);
-            setNodeAttribute(element, styleAttr, inlineStyle->asText());
+            setNodeAttribute(element, styleAttr, AtomicString(inlineStyle->asText()));
             if (isSpanWithoutAttributesOrUnstyledStyleSpan(element))
                 removeNodePreservingChildren(element);
         }
@@ -766,7 +764,7 @@
                 continue;
             RefPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
             inlineStyle->mergeAndOverrideOnConflict(style->style());
-            setNodeAttribute(element, styleAttr, inlineStyle->asText());
+            setNodeAttribute(element, styleAttr, AtomicString(inlineStyle->asText()));
             continue;
         }
 
@@ -901,15 +899,12 @@
     return removed;
 }
 
-void ApplyStyleCommand::replaceWithSpanOrRemoveIfWithoutAttributes(HTMLElement*& elem)
+void ApplyStyleCommand::replaceWithSpanOrRemoveIfWithoutAttributes(HTMLElement* elem)
 {
     if (hasNoAttributeOrOnlyStyleAttribute(elem, StyleAttributeShouldBeEmpty))
         removeNodePreservingChildren(elem);
-    else {
-        HTMLElement* newSpanElement = replaceElementWithSpanPreservingChildrenAndAttributes(elem);
-        ASSERT(newSpanElement && newSpanElement->inDocument());
-        elem = newSpanElement;
-    }
+    else
+        replaceElementWithSpanPreservingChildrenAndAttributes(elem);
 }
 
 bool ApplyStyleCommand::removeImplicitlyStyledElement(EditingStyle* style, HTMLElement* element, InlineStyleRemovalMode mode, EditingStyle* extractedStyle)
@@ -957,10 +952,6 @@
     for (size_t i = 0; i < properties.size(); i++)
         removeCSSProperty(element, properties[i]);
 
-    // No need to serialize <foo style=""> if we just removed the last css property
-    if (element->inlineStyle()->isEmpty())
-        removeNodeAttribute(element, styleAttr);
-
     if (isSpanWithoutAttributesOrUnstyledStyleSpan(element))
         removeNodePreservingChildren(element);
 
@@ -1005,11 +996,11 @@
     // Since addInlineStyleIfNeeded can't add styles to block-flow render objects, add style attribute instead.
     // FIXME: applyInlineStyleToRange should be used here instead.
     if ((node->renderer()->isRenderBlockFlow() || node->childNodeCount()) && node->isHTMLElement()) {
-        setNodeAttribute(toHTMLElement(node), styleAttr, newInlineStyle->style()->asText());
+        setNodeAttribute(toHTMLElement(node), styleAttr, AtomicString(newInlineStyle->style()->asText()));
         return;
     }
 
-    if (node->renderer()->isText() && static_cast<RenderText*>(node->renderer())->isAllCollapsibleWhitespace())
+    if (node->renderer()->isText() && toRenderText(node->renderer())->isAllCollapsibleWhitespace())
         return;
 
     // We can't wrap node with the styled element here because new styled element will never be removed if we did.
@@ -1166,17 +1157,6 @@
         && comparePositions(lastPositionInOrAfterNode(node).upstream(), end) <= 0;
 }
 
-bool ApplyStyleCommand::nodeFullyUnselected(Node *node, const Position &start, const Position &end) const
-{
-    ASSERT(node);
-    ASSERT(node->isElementNode());
-
-    bool isFullyBeforeStart = comparePositions(lastPositionInOrAfterNode(node).upstream(), start) < 0;
-    bool isFullyAfterEnd = comparePositions(firstPositionInOrBeforeNode(node), end) > 0;
-
-    return isFullyBeforeStart || isFullyAfterEnd;
-}
-
 void ApplyStyleCommand::splitTextAtStart(const Position& start, const Position& end)
 {
     ASSERT(start.containerNode()->isTextNode());
@@ -1271,7 +1251,6 @@
             return false;
 
         startNode = startNode->parentNode();
-        startOffset = 0;
     }
 
     if (!startNode->isElementNode())
@@ -1337,12 +1316,11 @@
     ASSERT(passedStartNode);
     ASSERT(endNode);
     ASSERT(elementToInsert);
-    RefPtr<Node> startNode = passedStartNode;
+    RefPtr<Node> node = passedStartNode;
     RefPtr<Element> element = elementToInsert;
 
-    insertNodeBefore(element, startNode);
+    insertNodeBefore(element, node);
 
-    RefPtr<Node> node = startNode;
     while (node) {
         RefPtr<Node> next = node->nextSibling();
         if (node->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable)) {
@@ -1387,7 +1365,7 @@
             cssText.append(' ');
         cssText.append(decl->asText());
     }
-    setNodeAttribute(block, styleAttr, cssText.toString());
+    setNodeAttribute(block, styleAttr, cssText.toAtomicString());
 }
 
 void ApplyStyleCommand::addInlineStyleIfNeeded(EditingStyle* style, PassRefPtr<Node> passedStart, PassRefPtr<Node> passedEnd, EAddStyledElement addStyledElement)
@@ -1510,6 +1488,7 @@
     if (!style)
         return 0;
 
+    // FIXME: oilpan: Change to RefPtrWillBeRawPtr when changing CSSValue.
     RefPtr<CSSPrimitiveValue> value = static_pointer_cast<CSSPrimitiveValue>(style->getPropertyCSSValue(CSSPropertyFontSize));
     if (!value)
         return 0;
diff --git a/Source/core/editing/ApplyStyleCommand.h b/Source/core/editing/ApplyStyleCommand.h
index 363e09e..561679e 100644
--- a/Source/core/editing/ApplyStyleCommand.h
+++ b/Source/core/editing/ApplyStyleCommand.h
@@ -41,7 +41,7 @@
     IgnoreTypingStyle
 };
 
-class ApplyStyleCommand : public CompositeEditCommand {
+class ApplyStyleCommand FINAL : public CompositeEditCommand {
 public:
     enum EPropertyLevel { PropertyDefault, ForceBlockProperties };
     enum InlineStyleRemovalMode { RemoveIfNeeded, RemoveAlways, RemoveNone };
@@ -71,8 +71,8 @@
     ApplyStyleCommand(PassRefPtr<Element>, bool removeOnly, EditAction);
     ApplyStyleCommand(Document&, const EditingStyle*, bool (*isInlineElementToRemove)(const Element*), EditAction);
 
-    virtual void doApply();
-    virtual EditAction editingAction() const;
+    virtual void doApply() OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE;
 
     // style-removal helpers
     bool isStyledInlineElementToRemove(Element*) const;
@@ -80,7 +80,7 @@
     void removeConflictingInlineStyleFromRun(EditingStyle*, RefPtr<Node>& runStart, RefPtr<Node>& runEnd, PassRefPtr<Node> pastEndNode);
     bool removeInlineStyleFromElement(EditingStyle*, PassRefPtr<HTMLElement>, InlineStyleRemovalMode = RemoveIfNeeded, EditingStyle* extractedStyle = 0);
     inline bool shouldRemoveInlineStyleFromElement(EditingStyle* style, HTMLElement* element) {return removeInlineStyleFromElement(style, element, RemoveNone);}
-    void replaceWithSpanOrRemoveIfWithoutAttributes(HTMLElement*&);
+    void replaceWithSpanOrRemoveIfWithoutAttributes(HTMLElement*);
     bool removeImplicitlyStyledElement(EditingStyle*, HTMLElement*, InlineStyleRemovalMode, EditingStyle* extractedStyle);
     bool removeCSSStyle(EditingStyle*, HTMLElement*, InlineStyleRemovalMode = RemoveIfNeeded, EditingStyle* extractedStyle = 0);
     HTMLElement* highestAncestorWithConflictingInlineStyle(EditingStyle*, Node*);
@@ -88,7 +88,6 @@
     void pushDownInlineStyleAroundNode(EditingStyle*, Node*);
     void removeInlineStyle(EditingStyle* , const Position& start, const Position& end);
     bool nodeFullySelected(Node*, const Position& start, const Position& end) const;
-    bool nodeFullyUnselected(Node*, const Position& start, const Position& end) const;
 
     // style-application helpers
     void applyBlockStyle(EditingStyle*);
diff --git a/Source/core/editing/BreakBlockquoteCommand.h b/Source/core/editing/BreakBlockquoteCommand.h
index 359777c..9678704 100644
--- a/Source/core/editing/BreakBlockquoteCommand.h
+++ b/Source/core/editing/BreakBlockquoteCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class BreakBlockquoteCommand : public CompositeEditCommand {
+class BreakBlockquoteCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<BreakBlockquoteCommand> create(Document& document)
     {
@@ -39,7 +39,7 @@
 
 private:
     explicit BreakBlockquoteCommand(Document&);
-    virtual void doApply();
+    virtual void doApply() OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/editing/Caret.cpp b/Source/core/editing/Caret.cpp
index 4501cc8..64f0508 100644
--- a/Source/core/editing/Caret.cpp
+++ b/Source/core/editing/Caret.cpp
@@ -29,7 +29,7 @@
 #include "core/dom/Document.h"
 #include "core/editing/htmlediting.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderView.h"
 
diff --git a/Source/core/editing/CompositeEditCommand.cpp b/Source/core/editing/CompositeEditCommand.cpp
index 24acf2d..3f7dbda 100644
--- a/Source/core/editing/CompositeEditCommand.cpp
+++ b/Source/core/editing/CompositeEditCommand.cpp
@@ -31,9 +31,9 @@
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/DocumentMarkerController.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Range.h"
-#include "core/events/ScopedEventQueue.h"
 #include "core/dom/Text.h"
 #include "core/editing/AppendNodeCommand.h"
 #include "core/editing/ApplyStyleCommand.h"
@@ -61,6 +61,7 @@
 #include "core/editing/WrapContentsInDummySpanCommand.h"
 #include "core/editing/htmlediting.h"
 #include "core/editing/markup.h"
+#include "core/events/ScopedEventQueue.h"
 #include "core/html/HTMLElement.h"
 #include "core/frame/Frame.h"
 #include "core/rendering/InlineTextBox.h"
@@ -73,24 +74,6 @@
 
 using namespace HTMLNames;
 
-namespace {
-class ReentrancyGuard {
-public:
-    static bool isRecursiveCall() { return s_nestingCounter; }
-
-    class Scope {
-    public:
-        Scope() { ++s_nestingCounter; }
-        ~Scope() { --s_nestingCounter; }
-    };
-    friend class Scope;
-
-private:
-    static int s_nestingCounter;
-};
-int ReentrancyGuard::s_nestingCounter;
-}
-
 PassRefPtr<EditCommandComposition> EditCommandComposition::create(Document* document,
     const VisibleSelection& startingSelection, const VisibleSelection& endingSelection, EditAction editAction)
 {
@@ -182,14 +165,6 @@
 
 void CompositeEditCommand::apply()
 {
-    // We don't allow recusrive |apply()| to protect against attack code.
-    // Recursive call of |apply()| could be happened by moving iframe
-    // with script triggered by insertion, e.g. <iframe src="javascript:...">
-    // <iframe onload="...">. This usage is valid as of the specification
-    // although, it isn't common use case, rather it is used as attack code.
-    if (ReentrancyGuard::isRecursiveCall())
-        return;
-
     if (!endingSelection().isContentRichlyEditable()) {
         switch (editingAction()) {
         case EditActionTyping:
@@ -215,7 +190,6 @@
     ASSERT(frame);
     {
         EventQueueScope eventQueueScope;
-        ReentrancyGuard::Scope reentrancyGuardScope;
         doApply();
     }
 
@@ -236,11 +210,6 @@
     return command->m_composition.get();
 }
 
-bool CompositeEditCommand::isCreateLinkCommand() const
-{
-    return false;
-}
-
 bool CompositeEditCommand::preservesTypingStyle() const
 {
     return false;
@@ -251,11 +220,6 @@
     return false;
 }
 
-bool CompositeEditCommand::shouldRetainAutocorrectionIndicator() const
-{
-    return false;
-}
-
 void CompositeEditCommand::setShouldRetainAutocorrectionIndicator(bool)
 {
 }
@@ -311,11 +275,6 @@
     applyCommandToComposite(InsertParagraphSeparatorCommand::create(document(), useDefaultParagraphElement, pasteBlockqutoeIntoUnquotedArea));
 }
 
-void CompositeEditCommand::insertLineBreak()
-{
-    applyCommandToComposite(InsertLineBreakCommand::create(document()));
-}
-
 bool CompositeEditCommand::isRemovableBlock(const Node* node)
 {
     if (!node->hasTagName(divTag))
@@ -355,7 +314,7 @@
 
 void CompositeEditCommand::insertNodeAt(PassRefPtr<Node> insertChild, const Position& editingPosition)
 {
-    ASSERT(isEditablePosition(editingPosition));
+    ASSERT(isEditablePosition(editingPosition, ContentIsEditable, DoNotUpdateStyle));
     // For editing positions like [table, 0], insert before the table,
     // likewise for replaced elements, brs, etc.
     Position p = editingPosition.parentAnchoredEquivalent();
@@ -583,16 +542,16 @@
     insertNodeAt(node, positionOutsideTabSpan(pos));
 }
 
-void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
+void CompositeEditCommand::deleteSelection(bool smartDelete, bool mergeBlocksAfterDelete, bool expandForSpecialElements, bool sanitizeMarkup)
 {
     if (endingSelection().isRange())
-        applyCommandToComposite(DeleteSelectionCommand::create(document(), smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements, sanitizeMarkup));
+        applyCommandToComposite(DeleteSelectionCommand::create(document(), smartDelete, mergeBlocksAfterDelete, expandForSpecialElements, sanitizeMarkup));
 }
 
-void CompositeEditCommand::deleteSelection(const VisibleSelection &selection, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
+void CompositeEditCommand::deleteSelection(const VisibleSelection &selection, bool smartDelete, bool mergeBlocksAfterDelete, bool expandForSpecialElements, bool sanitizeMarkup)
 {
     if (selection.isRange())
-        applyCommandToComposite(DeleteSelectionCommand::create(selection, smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements, sanitizeMarkup));
+        applyCommandToComposite(DeleteSelectionCommand::create(selection, smartDelete, mergeBlocksAfterDelete, expandForSpecialElements, sanitizeMarkup));
 }
 
 void CompositeEditCommand::removeCSSProperty(PassRefPtr<Element> element, CSSPropertyID property)
@@ -790,7 +749,6 @@
         int gapLen = gapEnd - gapStart;
         if (indicesIntersect && gapLen > 0) {
             gapStart = max(gapStart, start);
-            gapEnd = min(gapEnd, end);
             if (str.isNull())
                 str = textNode->data().substring(start, end - start);
             // remove text in the gap
@@ -1010,7 +968,7 @@
     if (outerNode->isRootEditableElement()) {
         lastNode = blockElement;
     } else {
-        lastNode = outerNode->cloneNode(isTableElement(outerNode.get()));
+        lastNode = outerNode->cloneNode(isRenderedTableElement(outerNode.get()));
         appendNode(lastNode, blockElement);
     }
 
@@ -1025,7 +983,7 @@
 
         for (size_t i = ancestors.size(); i != 0; --i) {
             Node* item = ancestors[i - 1].get();
-            RefPtr<Node> child = item->cloneNode(isTableElement(item));
+            RefPtr<Node> child = item->cloneNode(isRenderedTableElement(item));
             appendNode(child, toElement(lastNode));
             lastNode = child.release();
         }
@@ -1326,8 +1284,8 @@
     if (!newBlock)
         newBlock = createDefaultParagraphElement(document());
 
-    RefPtr<Node> previousListNode = emptyListItem->isElementNode() ? toElement(emptyListItem)->previousElementSibling(): emptyListItem->previousSibling();
-    RefPtr<Node> nextListNode = emptyListItem->isElementNode() ? toElement(emptyListItem)->nextElementSibling(): emptyListItem->nextSibling();
+    RefPtr<Node> previousListNode = emptyListItem->isElementNode() ? ElementTraversal::previousSibling(*emptyListItem): emptyListItem->previousSibling();
+    RefPtr<Node> nextListNode = emptyListItem->isElementNode() ? ElementTraversal::nextSibling(*emptyListItem): emptyListItem->nextSibling();
     if (isListItem(nextListNode.get()) || isListElement(nextListNode.get())) {
         // If emptyListItem follows another list item or nested list, split the list node.
         if (isListItem(previousListNode.get()) || isListElement(previousListNode.get()))
diff --git a/Source/core/editing/CompositeEditCommand.h b/Source/core/editing/CompositeEditCommand.h
index 9b3ec17..007c306 100644
--- a/Source/core/editing/CompositeEditCommand.h
+++ b/Source/core/editing/CompositeEditCommand.h
@@ -38,14 +38,14 @@
 class HTMLElement;
 class Text;
 
-class EditCommandComposition : public UndoStep {
+class EditCommandComposition FINAL : public UndoStep {
 public:
     static PassRefPtr<EditCommandComposition> create(Document*, const VisibleSelection&, const VisibleSelection&, EditAction);
 
     virtual bool belongsTo(const Frame&) const OVERRIDE;
     virtual void unapply() OVERRIDE;
     virtual void reapply() OVERRIDE;
-    EditAction editingAction() const OVERRIDE { return m_editAction; }
+    virtual EditAction editingAction() const OVERRIDE { return m_editAction; }
     void append(SimpleEditCommand*);
     bool wasCreateLinkCommand() const { return m_editAction == EditActionCreateLink; }
 
@@ -77,10 +77,8 @@
     EditCommandComposition* composition() { return m_composition.get(); }
     EditCommandComposition* ensureComposition();
 
-    virtual bool isCreateLinkCommand() const;
     virtual bool isTypingCommand() const;
     virtual bool preservesTypingStyle() const;
-    virtual bool shouldRetainAutocorrectionIndicator() const;
     virtual void setShouldRetainAutocorrectionIndicator(bool);
     virtual bool shouldStopCaretBlinking() const { return false; }
 
@@ -97,8 +95,8 @@
     void applyStyle(const EditingStyle*, const Position& start, const Position& end, EditAction = EditActionChangeAttributes);
     void applyStyledElement(PassRefPtr<Element>);
     void removeStyledElement(PassRefPtr<Element>);
-    void deleteSelection(bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool replace = false, bool expandForSpecialElements = true, bool sanitizeMarkup = true);
-    void deleteSelection(const VisibleSelection&, bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool replace = false, bool expandForSpecialElements = true, bool sanitizeMarkup = true);
+    void deleteSelection(bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool expandForSpecialElements = true, bool sanitizeMarkup = true);
+    void deleteSelection(const VisibleSelection&, bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool expandForSpecialElements = true, bool sanitizeMarkup = true);
     virtual void deleteTextFromNode(PassRefPtr<Text>, unsigned offset, unsigned count);
     bool isRemovableBlock(const Node*);
     void insertNodeAfter(PassRefPtr<Node>, PassRefPtr<Node> refChild);
@@ -106,7 +104,6 @@
     void insertNodeAtTabSpanPosition(PassRefPtr<Node>, const Position&);
     void insertNodeBefore(PassRefPtr<Node>, PassRefPtr<Node> refChild, ShouldAssumeContentIsAlwaysEditable = DoNotAssumeContentIsAlwaysEditable);
     void insertParagraphSeparator(bool useDefaultParagraphElement = false, bool pasteBlockqutoeIntoUnquotedArea = false);
-    void insertLineBreak();
     void insertTextIntoNode(PassRefPtr<Text>, unsigned offset, const String& text);
     void mergeIdenticalElements(PassRefPtr<Element>, PassRefPtr<Element>);
     void rebalanceWhitespace();
@@ -168,17 +165,12 @@
     Vector<RefPtr<EditCommand> > m_commands;
 
 private:
-    bool isCompositeEditCommand() const OVERRIDE { return true; }
+    virtual bool isCompositeEditCommand() const OVERRIDE FINAL { return true; }
 
     RefPtr<EditCommandComposition> m_composition;
 };
 
-inline CompositeEditCommand* toCompositeEditCommand(EditCommand* command)
-{
-    ASSERT(command);
-    ASSERT(command->isCompositeEditCommand());
-    return static_cast<CompositeEditCommand*>(command);
-}
+DEFINE_TYPE_CASTS(CompositeEditCommand, EditCommand, command, command->isCompositeEditCommand(), command.isCompositeEditCommand());
 
 } // namespace WebCore
 
diff --git a/Source/core/editing/CreateLinkCommand.cpp b/Source/core/editing/CreateLinkCommand.cpp
index 88f969e..7f8adff 100644
--- a/Source/core/editing/CreateLinkCommand.cpp
+++ b/Source/core/editing/CreateLinkCommand.cpp
@@ -43,7 +43,7 @@
         return;
 
     RefPtr<HTMLAnchorElement> anchorElement = HTMLAnchorElement::create(document());
-    anchorElement->setHref(m_url);
+    anchorElement->setHref(AtomicString(m_url));
 
     if (endingSelection().isRange())
         applyStyledElement(anchorElement.get());
diff --git a/Source/core/editing/CreateLinkCommand.h b/Source/core/editing/CreateLinkCommand.h
index af489fe..a1eaf81 100644
--- a/Source/core/editing/CreateLinkCommand.h
+++ b/Source/core/editing/CreateLinkCommand.h
@@ -30,20 +30,18 @@
 
 namespace WebCore {
 
-class CreateLinkCommand : public CompositeEditCommand {
+class CreateLinkCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<CreateLinkCommand> create(Document& document, const String& linkURL)
     {
         return adoptRef(new CreateLinkCommand(document, linkURL));
     }
 
-    bool isCreateLinkCommand() const { return true; }
-
 private:
     CreateLinkCommand(Document&, const String& linkURL);
 
-    virtual void doApply();
-    virtual EditAction editingAction() const { return EditActionCreateLink; }
+    virtual void doApply() OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE { return EditActionCreateLink; }
 
     String m_url;
 };
diff --git a/Source/core/editing/DeleteFromTextNodeCommand.h b/Source/core/editing/DeleteFromTextNodeCommand.h
index 192e8a9..c6f2c12 100644
--- a/Source/core/editing/DeleteFromTextNodeCommand.h
+++ b/Source/core/editing/DeleteFromTextNodeCommand.h
@@ -32,7 +32,7 @@
 
 class Text;
 
-class DeleteFromTextNodeCommand : public SimpleEditCommand {
+class DeleteFromTextNodeCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<DeleteFromTextNodeCommand> create(PassRefPtr<Text> node, unsigned offset, unsigned count)
     {
diff --git a/Source/core/editing/DeleteSelectionCommand.cpp b/Source/core/editing/DeleteSelectionCommand.cpp
index ce27bb7..0303cbb 100644
--- a/Source/core/editing/DeleteSelectionCommand.cpp
+++ b/Source/core/editing/DeleteSelectionCommand.cpp
@@ -36,7 +36,6 @@
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLTableElement.h"
 #include "core/frame/Frame.h"
 #include "core/rendering/RenderTableCell.h"
 
@@ -67,13 +66,12 @@
     return true;
 }
 
-DeleteSelectionCommand::DeleteSelectionCommand(Document& document, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
+DeleteSelectionCommand::DeleteSelectionCommand(Document& document, bool smartDelete, bool mergeBlocksAfterDelete, bool expandForSpecialElements, bool sanitizeMarkup)
     : CompositeEditCommand(document)
     , m_hasSelectionToDelete(false)
     , m_smartDelete(smartDelete)
     , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
     , m_needPlaceholder(false)
-    , m_replace(replace)
     , m_expandForSpecialElements(expandForSpecialElements)
     , m_pruneStartBlockIfNecessary(false)
     , m_startsAtEmptyLine(false)
@@ -85,13 +83,12 @@
 {
 }
 
-DeleteSelectionCommand::DeleteSelectionCommand(const VisibleSelection& selection, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
+DeleteSelectionCommand::DeleteSelectionCommand(const VisibleSelection& selection, bool smartDelete, bool mergeBlocksAfterDelete, bool expandForSpecialElements, bool sanitizeMarkup)
     : CompositeEditCommand(*selection.start().document())
     , m_hasSelectionToDelete(true)
     , m_smartDelete(smartDelete)
     , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
     , m_needPlaceholder(false)
-    , m_replace(replace)
     , m_expandForSpecialElements(expandForSpecialElements)
     , m_pruneStartBlockIfNecessary(false)
     , m_startsAtEmptyLine(false)
@@ -454,7 +451,7 @@
     makeStylingElementsDirectChildrenOfEditableRootToPreventStyleLoss();
 
     // Never remove the start block unless it's a table, in which case we won't merge content in.
-    if (startNode->isSameNode(m_startBlock.get()) && !startOffset && canHaveChildrenForEditing(startNode) && !isHTMLTableElement(startNode)) {
+    if (startNode->isSameNode(m_startBlock.get()) && !startOffset && canHaveChildrenForEditing(startNode) && !startNode->hasTagName(tableTag)) {
         startOffset = 0;
         startNode = NodeTraversal::next(*startNode);
         if (!startNode)
@@ -634,11 +631,21 @@
     if (mergeDestination == startOfParagraphToMove)
         return;
 
-    VisiblePosition endOfParagraphToMove = endOfParagraph(startOfParagraphToMove);
+    VisiblePosition endOfParagraphToMove = endOfParagraph(startOfParagraphToMove, CanSkipOverEditingBoundary);
 
     if (mergeDestination == endOfParagraphToMove)
         return;
 
+    // If the merge destination and source to be moved are both list items of different lists, merge them into single list.
+    Node* listItemInFirstParagraph = enclosingNodeOfType(m_upstreamStart, isListItem);
+    Node* listItemInSecondParagraph = enclosingNodeOfType(m_downstreamEnd, isListItem);
+    if (listItemInFirstParagraph && listItemInSecondParagraph
+        && canMergeLists(listItemInFirstParagraph->parentElement(), listItemInSecondParagraph->parentElement())) {
+        mergeIdenticalElements(listItemInFirstParagraph->parentElement(), listItemInSecondParagraph->parentElement());
+        m_endingPosition = mergeDestination.deepEquivalent();
+        return;
+    }
+
     // The rule for merging into an empty block is: only do so if its farther to the right.
     // FIXME: Consider RTL.
     if (!m_startsAtEmptyLine && isStartOfParagraph(mergeDestination) && startOfParagraphToMove.absoluteCaretBounds().x() > mergeDestination.absoluteCaretBounds().x()) {
diff --git a/Source/core/editing/DeleteSelectionCommand.h b/Source/core/editing/DeleteSelectionCommand.h
index 8234bb3..d61817a 100644
--- a/Source/core/editing/DeleteSelectionCommand.h
+++ b/Source/core/editing/DeleteSelectionCommand.h
@@ -32,49 +32,46 @@
 
 class EditingStyle;
 
-class DeleteSelectionCommand : public CompositeEditCommand {
+class DeleteSelectionCommand FINAL : public CompositeEditCommand {
 public:
-    static PassRefPtr<DeleteSelectionCommand> create(Document& document, bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool replace = false, bool expandForSpecialElements = false, bool sanitizeMarkup = true)
+    static PassRefPtr<DeleteSelectionCommand> create(Document& document, bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool expandForSpecialElements = false, bool sanitizeMarkup = true)
     {
-        return adoptRef(new DeleteSelectionCommand(document, smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements, sanitizeMarkup));
+        return adoptRef(new DeleteSelectionCommand(document, smartDelete, mergeBlocksAfterDelete, expandForSpecialElements, sanitizeMarkup));
     }
-    static PassRefPtr<DeleteSelectionCommand> create(const VisibleSelection& selection, bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool replace = false, bool expandForSpecialElements = false, bool sanitizeMarkup = true)
+    static PassRefPtr<DeleteSelectionCommand> create(const VisibleSelection& selection, bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool expandForSpecialElements = false, bool sanitizeMarkup = true)
     {
-        return adoptRef(new DeleteSelectionCommand(selection, smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements, sanitizeMarkup));
+        return adoptRef(new DeleteSelectionCommand(selection, smartDelete, mergeBlocksAfterDelete, expandForSpecialElements, sanitizeMarkup));
     }
 
 private:
-    DeleteSelectionCommand(Document&, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool santizeMarkup);
-    DeleteSelectionCommand(const VisibleSelection&, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup);
+    DeleteSelectionCommand(Document&, bool smartDelete, bool mergeBlocksAfterDelete, bool expandForSpecialElements, bool santizeMarkup);
+    DeleteSelectionCommand(const VisibleSelection&, bool smartDelete, bool mergeBlocksAfterDelete, bool expandForSpecialElements, bool sanitizeMarkup);
 
-    virtual void doApply();
-    virtual EditAction editingAction() const;
+    virtual void doApply() OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE;
 
-    virtual bool preservesTypingStyle() const;
+    virtual bool preservesTypingStyle() const OVERRIDE;
 
     void initializeStartEnd(Position&, Position&);
     void setStartingSelectionOnSmartDelete(const Position&, const Position&);
     void initializePositionData();
     void saveTypingStyleState();
-    void insertPlaceholderForAncestorBlockContent();
     bool handleSpecialCaseBRDelete();
     void handleGeneralDelete();
     void fixupWhitespace();
     void mergeParagraphs();
     void removePreviouslySelectedEmptyTableRows();
-    void calculateEndingPosition();
     void calculateTypingStyleAfterDelete();
     void clearTransientState();
     void makeStylingElementsDirectChildrenOfEditableRootToPreventStyleLoss();
-    virtual void removeNode(PassRefPtr<Node>, ShouldAssumeContentIsAlwaysEditable = DoNotAssumeContentIsAlwaysEditable);
-    virtual void deleteTextFromNode(PassRefPtr<Text>, unsigned, unsigned);
+    virtual void removeNode(PassRefPtr<Node>, ShouldAssumeContentIsAlwaysEditable = DoNotAssumeContentIsAlwaysEditable) OVERRIDE;
+    virtual void deleteTextFromNode(PassRefPtr<Text>, unsigned, unsigned) OVERRIDE;
     void removeRedundantBlocks();
 
     bool m_hasSelectionToDelete;
     bool m_smartDelete;
     bool m_mergeBlocksAfterDelete;
     bool m_needPlaceholder;
-    bool m_replace;
     bool m_expandForSpecialElements;
     bool m_pruneStartBlockIfNecessary;
     bool m_startsAtEmptyLine;
diff --git a/Source/core/editing/EditCommand.h b/Source/core/editing/EditCommand.h
index 41d3edf..7d54068 100644
--- a/Source/core/editing/EditCommand.h
+++ b/Source/core/editing/EditCommand.h
@@ -52,7 +52,6 @@
 
     virtual bool isSimpleEditCommand() const { return false; }
     virtual bool isCompositeEditCommand() const { return false; }
-    virtual bool isEditCommandComposition() const { return false; }
     bool isTopLevelCommand() const { return !m_parent; }
 
     virtual void doApply() = 0;
@@ -87,15 +86,10 @@
     explicit SimpleEditCommand(Document& document) : EditCommand(document) { }
 
 private:
-    virtual bool isSimpleEditCommand() const OVERRIDE { return true; }
+    virtual bool isSimpleEditCommand() const OVERRIDE FINAL { return true; }
 };
 
-inline SimpleEditCommand* toSimpleEditCommand(EditCommand* command)
-{
-    ASSERT(command);
-    ASSERT_WITH_SECURITY_IMPLICATION(command->isSimpleEditCommand());
-    return static_cast<SimpleEditCommand*>(command);
-}
+DEFINE_TYPE_CASTS(SimpleEditCommand, EditCommand, command, command->isSimpleEditCommand(), command.isSimpleEditCommand());
 
 } // namespace WebCore
 
diff --git a/Source/core/editing/EditingBehavior.cpp b/Source/core/editing/EditingBehavior.cpp
new file mode 100644
index 0000000..df9d097
--- /dev/null
+++ b/Source/core/editing/EditingBehavior.cpp
@@ -0,0 +1,267 @@
+/*
+ * Copyright (C) 2006, 2007 Apple, Inc.  All rights reserved.
+ * Copyright (C) 2012 Google, Inc.  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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
+ */
+
+#include "config.h"
+#include "core/editing/EditingBehavior.h"
+
+#include "core/events/KeyboardEvent.h"
+#include "platform/KeyboardCodes.h"
+#include "platform/PlatformKeyboardEvent.h"
+
+namespace WebCore {
+
+//
+// The below code was adapted from the WebKit file webview.cpp
+//
+
+static const unsigned CtrlKey = 1 << 0;
+static const unsigned AltKey = 1 << 1;
+static const unsigned ShiftKey = 1 << 2;
+static const unsigned MetaKey = 1 << 3;
+#if OS(MACOSX)
+// Aliases for the generic key defintions to make kbd shortcuts definitions more
+// readable on OS X.
+static const unsigned OptionKey  = AltKey;
+
+// Do not use this constant for anything but cursor movement commands. Keys
+// with cmd set have their |isSystemKey| bit set, so chances are the shortcut
+// will not be executed. Another, less important, reason is that shortcuts
+// defined in the renderer do not blink the menu item that they triggered. See
+// http://crbug.com/25856 and the bugs linked from there for details.
+static const unsigned CommandKey = MetaKey;
+#endif
+
+// Keys with special meaning. These will be delegated to the editor using
+// the execCommand() method
+struct KeyDownEntry {
+    unsigned virtualKey;
+    unsigned modifiers;
+    const char* name;
+};
+
+struct KeyPressEntry {
+    unsigned charCode;
+    unsigned modifiers;
+    const char* name;
+};
+
+// Key bindings with command key on Mac and alt key on other platforms are
+// marked as system key events and will be ignored (with the exception
+// of Command-B and Command-I) so they shouldn't be added here.
+static const KeyDownEntry keyDownEntries[] = {
+    { VKEY_LEFT,   0,                  "MoveLeft"                             },
+    { VKEY_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"           },
+#if OS(MACOSX)
+    { VKEY_LEFT,   OptionKey,          "MoveWordLeft"                         },
+    { VKEY_LEFT,   OptionKey | ShiftKey,
+        "MoveWordLeftAndModifySelection"                                      },
+#else
+    { VKEY_LEFT,   CtrlKey,            "MoveWordLeft"                         },
+    { VKEY_LEFT,   CtrlKey | ShiftKey,
+        "MoveWordLeftAndModifySelection"                                      },
+#endif
+    { VKEY_RIGHT,  0,                  "MoveRight"                            },
+    { VKEY_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"          },
+#if OS(MACOSX)
+    { VKEY_RIGHT,  OptionKey,          "MoveWordRight"                        },
+    { VKEY_RIGHT,  OptionKey | ShiftKey, "MoveWordRightAndModifySelection"    },
+#else
+    { VKEY_RIGHT,  CtrlKey,            "MoveWordRight"                        },
+    { VKEY_RIGHT,  CtrlKey | ShiftKey, "MoveWordRightAndModifySelection"      },
+#endif
+    { VKEY_UP,     0,                  "MoveUp"                               },
+    { VKEY_UP,     ShiftKey,           "MoveUpAndModifySelection"             },
+    { VKEY_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"         },
+    { VKEY_DOWN,   0,                  "MoveDown"                             },
+    { VKEY_DOWN,   ShiftKey,           "MoveDownAndModifySelection"           },
+    { VKEY_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"       },
+#if !OS(MACOSX)
+    { VKEY_UP,     CtrlKey,            "MoveParagraphBackward"                },
+    { VKEY_UP,     CtrlKey | ShiftKey, "MoveParagraphBackwardAndModifySelection" },
+    { VKEY_DOWN,   CtrlKey,            "MoveParagraphForward"                },
+    { VKEY_DOWN,   CtrlKey | ShiftKey, "MoveParagraphForwardAndModifySelection" },
+    { VKEY_PRIOR,  0,                  "MovePageUp"                           },
+    { VKEY_NEXT,   0,                  "MovePageDown"                         },
+#endif
+    { VKEY_HOME,   0,                  "MoveToBeginningOfLine"                },
+    { VKEY_HOME,   ShiftKey,
+        "MoveToBeginningOfLineAndModifySelection"                             },
+#if OS(MACOSX)
+    { VKEY_PRIOR,  OptionKey,          "MovePageUp"                           },
+    { VKEY_NEXT,   OptionKey,          "MovePageDown"                         },
+#endif
+#if !OS(MACOSX)
+    { VKEY_HOME,   CtrlKey,            "MoveToBeginningOfDocument"            },
+    { VKEY_HOME,   CtrlKey | ShiftKey,
+        "MoveToBeginningOfDocumentAndModifySelection"                         },
+#endif
+    { VKEY_END,    0,                  "MoveToEndOfLine"                      },
+    { VKEY_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"    },
+#if !OS(MACOSX)
+    { VKEY_END,    CtrlKey,            "MoveToEndOfDocument"                  },
+    { VKEY_END,    CtrlKey | ShiftKey,
+        "MoveToEndOfDocumentAndModifySelection"                               },
+#endif
+    { VKEY_BACK,   0,                  "DeleteBackward"                       },
+    { VKEY_BACK,   ShiftKey,           "DeleteBackward"                       },
+    { VKEY_DELETE, 0,                  "DeleteForward"                        },
+#if OS(MACOSX)
+    { VKEY_BACK,   OptionKey,          "DeleteWordBackward"                   },
+    { VKEY_DELETE, OptionKey,          "DeleteWordForward"                    },
+#else
+    { VKEY_BACK,   CtrlKey,            "DeleteWordBackward"                   },
+    { VKEY_DELETE, CtrlKey,            "DeleteWordForward"                    },
+#endif
+#if OS(MACOSX)
+    { 'B',         CommandKey,         "ToggleBold"                           },
+    { 'I',         CommandKey,         "ToggleItalic"                         },
+#else
+    { 'B',         CtrlKey,            "ToggleBold"                           },
+    { 'I',         CtrlKey,            "ToggleItalic"                         },
+#endif
+    { 'U',         CtrlKey,            "ToggleUnderline"                      },
+    { VKEY_ESCAPE, 0,                  "Cancel"                               },
+    { VKEY_OEM_PERIOD, CtrlKey,        "Cancel"                               },
+    { VKEY_TAB,    0,                  "InsertTab"                            },
+    { VKEY_TAB,    ShiftKey,           "InsertBacktab"                        },
+    { VKEY_RETURN, 0,                  "InsertNewline"                        },
+    { VKEY_RETURN, CtrlKey,            "InsertNewline"                        },
+    { VKEY_RETURN, AltKey,             "InsertNewline"                        },
+    { VKEY_RETURN, AltKey | ShiftKey,  "InsertNewline"                        },
+    { VKEY_RETURN, ShiftKey,           "InsertLineBreak"                      },
+    { VKEY_INSERT, CtrlKey,            "Copy"                                 },
+    { VKEY_INSERT, ShiftKey,           "Paste"                                },
+    { VKEY_DELETE, ShiftKey,           "Cut"                                  },
+#if !OS(MACOSX)
+    // On OS X, we pipe these back to the browser, so that it can do menu item
+    // blinking.
+    { 'C',         CtrlKey,            "Copy"                                 },
+    { 'V',         CtrlKey,            "Paste"                                },
+    { 'V',         CtrlKey | ShiftKey, "PasteAndMatchStyle"                   },
+    { 'X',         CtrlKey,            "Cut"                                  },
+    { 'A',         CtrlKey,            "SelectAll"                            },
+    { 'Z',         CtrlKey,            "Undo"                                 },
+    { 'Z',         CtrlKey | ShiftKey, "Redo"                                 },
+    { 'Y',         CtrlKey,            "Redo"                                 },
+#endif
+    { VKEY_INSERT, 0,                  "OverWrite"                            },
+};
+
+static const KeyPressEntry keyPressEntries[] = {
+    { '\t',   0,                  "InsertTab"                                 },
+    { '\t',   ShiftKey,           "InsertBacktab"                             },
+    { '\r',   0,                  "InsertNewline"                             },
+    { '\r',   CtrlKey,            "InsertNewline"                             },
+    { '\r',   ShiftKey,           "InsertLineBreak"                           },
+    { '\r',   AltKey,             "InsertNewline"                             },
+    { '\r',   AltKey | ShiftKey,  "InsertNewline"                             },
+};
+
+const char* EditingBehavior::interpretKeyEvent(const KeyboardEvent& event) const
+{
+    const PlatformKeyboardEvent* keyEvent = event.keyEvent();
+    if (!keyEvent)
+        return "";
+
+    static HashMap<int, const char*>* keyDownCommandsMap = 0;
+    static HashMap<int, const char*>* keyPressCommandsMap = 0;
+
+    if (!keyDownCommandsMap) {
+        keyDownCommandsMap = new HashMap<int, const char*>;
+        keyPressCommandsMap = new HashMap<int, const char*>;
+
+        for (unsigned i = 0; i < arraysize(keyDownEntries); i++) {
+            keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
+        }
+
+        for (unsigned i = 0; i < arraysize(keyPressEntries); i++) {
+            keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
+        }
+    }
+
+    unsigned modifiers = 0;
+    if (keyEvent->shiftKey())
+        modifiers |= ShiftKey;
+    if (keyEvent->altKey())
+        modifiers |= AltKey;
+    if (keyEvent->ctrlKey())
+        modifiers |= CtrlKey;
+    if (keyEvent->metaKey())
+        modifiers |= MetaKey;
+
+    if (keyEvent->type() == PlatformEvent::RawKeyDown) {
+        int mapKey = modifiers << 16 | event.keyCode();
+        return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
+    }
+
+    int mapKey = modifiers << 16 | event.charCode();
+    return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
+}
+
+bool EditingBehavior::shouldInsertCharacter(const KeyboardEvent& event) const
+{
+    if (event.keyEvent()->text().length() != 1)
+        return true;
+
+    // On Gtk/Linux, it emits key events with ASCII text and ctrl on for ctrl-<x>.
+    // In Webkit, EditorClient::handleKeyboardEvent in
+    // WebKit/gtk/WebCoreSupport/EditorClientGtk.cpp drop such events.
+    // On Mac, it emits key events with ASCII text and meta on for Command-<x>.
+    // These key events should not emit text insert event.
+    // Alt key would be used to insert alternative character, so we should let
+    // through. Also note that Ctrl-Alt combination equals to AltGr key which is
+    // also used to insert alternative character.
+    // http://code.google.com/p/chromium/issues/detail?id=10846
+    // Windows sets both alt and meta are on when "Alt" key pressed.
+    // http://code.google.com/p/chromium/issues/detail?id=2215
+    // Also, we should not rely on an assumption that keyboards don't
+    // send ASCII characters when pressing a control key on Windows,
+    // which may be configured to do it so by user.
+    // See also http://en.wikipedia.org/wiki/Keyboard_Layout
+    // FIXME(ukai): investigate more detail for various keyboard layout.
+    UChar ch = event.keyEvent()->text()[0U];
+
+    // Don't insert null or control characters as they can result in
+    // unexpected behaviour
+    if (ch < ' ')
+        return false;
+#if !OS(WIN)
+    // Don't insert ASCII character if ctrl w/o alt or meta is on.
+    // On Mac, we should ignore events when meta is on (Command-<x>).
+    if (ch < 0x80) {
+        if (event.keyEvent()->ctrlKey() && !event.keyEvent()->altKey())
+            return false;
+#if OS(MACOSX)
+        if (event.keyEvent()->metaKey())
+            return false;
+#endif
+    }
+#endif
+
+    return true;
+}
+} // namespace WebCore
+
diff --git a/Source/core/editing/EditingBehavior.h b/Source/core/editing/EditingBehavior.h
index ec1a775..0adab85 100644
--- a/Source/core/editing/EditingBehavior.h
+++ b/Source/core/editing/EditingBehavior.h
@@ -24,6 +24,7 @@
 #include "core/editing/EditingBehaviorTypes.h"
 
 namespace WebCore {
+class KeyboardEvent;
 
 class EditingBehavior {
 
@@ -90,6 +91,11 @@
         return m_type != EditingWindowsBehavior && m_type != EditingMacBehavior;
     }
 
+    // Convert a KeyboardEvent to a command name like "Copy", "Undo" and so on.
+    // If nothing, return empty string.
+    const char* interpretKeyEvent(const KeyboardEvent&) const;
+
+    bool shouldInsertCharacter(const KeyboardEvent&) const;
 private:
     EditingBehaviorType m_type;
 };
diff --git a/Source/core/editing/EditingStyle.cpp b/Source/core/editing/EditingStyle.cpp
index ce6ee11..29a8fbe 100644
--- a/Source/core/editing/EditingStyle.cpp
+++ b/Source/core/editing/EditingStyle.cpp
@@ -30,11 +30,12 @@
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/css/CSSComputedStyleDeclaration.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSStyleRule.h"
 #include "core/css/CSSValueList.h"
 #include "core/css/FontSize.h"
+#include "core/css/RuntimeCSSEnabled.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
 #include "core/css/resolver/StyleResolver.h"
@@ -48,9 +49,8 @@
 #include "core/editing/FrameSelection.h"
 #include "core/editing/HTMLInterchange.h"
 #include "core/editing/htmlediting.h"
-#include "core/html/HTMLFontElement.h"
 #include "core/frame/Frame.h"
-#include "core/page/RuntimeCSSEnabled.h"
+#include "core/html/HTMLFontElement.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
@@ -169,7 +169,7 @@
     HTMLElementEquivalent(CSSPropertyID, const QualifiedName& tagName);
     HTMLElementEquivalent(CSSPropertyID, CSSValueID primitiveValue, const QualifiedName& tagName);
     const CSSPropertyID m_propertyID;
-    const RefPtr<CSSPrimitiveValue> m_primitiveValue;
+    const RefPtrWillBePersistent<CSSPrimitiveValue> m_primitiveValue;
     const QualifiedName* m_tagName; // We can store a pointer because HTML tag names are const global.
 };
 
@@ -210,8 +210,8 @@
     {
         return adoptPtr(new HTMLTextDecorationEquivalent(primitiveValue, tagName));
     }
-    virtual bool propertyExistsInStyle(const StylePropertySet*) const;
-    virtual bool valueIsPresentInStyle(Element*, StylePropertySet*) const;
+    virtual bool propertyExistsInStyle(const StylePropertySet*) const OVERRIDE;
+    virtual bool valueIsPresentInStyle(Element*, StylePropertySet*) const OVERRIDE;
 
 private:
     HTMLTextDecorationEquivalent(CSSValueID primitiveValue, const QualifiedName& tagName);
@@ -248,10 +248,10 @@
         return adoptPtr(new HTMLAttributeEquivalent(propertyID, attrName));
     }
 
-    bool matches(const Element* elem) const { return HTMLElementEquivalent::matches(elem) && elem->hasAttribute(m_attrName); }
-    virtual bool hasAttribute() const { return true; }
-    virtual bool valueIsPresentInStyle(Element*, StylePropertySet*) const;
-    virtual void addToStyle(Element*, EditingStyle*) const;
+    virtual bool matches(const Element* elem) const OVERRIDE { return HTMLElementEquivalent::matches(elem) && elem->hasAttribute(m_attrName); }
+    virtual bool hasAttribute() const OVERRIDE { return true; }
+    virtual bool valueIsPresentInStyle(Element*, StylePropertySet*) const OVERRIDE;
+    virtual void addToStyle(Element*, EditingStyle*) const OVERRIDE;
     virtual PassRefPtr<CSSValue> attributeValueAsCSSValue(Element*) const;
     inline const QualifiedName& attributeName() const { return m_attrName; }
 
@@ -299,13 +299,13 @@
     return dummyStyle->getPropertyCSSValue(m_propertyID);
 }
 
-class HTMLFontSizeEquivalent : public HTMLAttributeEquivalent {
+class HTMLFontSizeEquivalent FINAL : public HTMLAttributeEquivalent {
 public:
     static PassOwnPtr<HTMLFontSizeEquivalent> create()
     {
         return adoptPtr(new HTMLFontSizeEquivalent());
     }
-    virtual PassRefPtr<CSSValue> attributeValueAsCSSValue(Element*) const;
+    virtual PassRefPtr<CSSValue> attributeValueAsCSSValue(Element*) const OVERRIDE;
 
 private:
     HTMLFontSizeEquivalent();
@@ -357,14 +357,6 @@
     extractFontSizeDelta();
 }
 
-EditingStyle::EditingStyle(const CSSStyleDeclaration* style)
-    : m_mutableStyle(style ? style->copyProperties() : 0)
-    , m_shouldUseFixedDefaultFontSize(false)
-    , m_fontSizeDelta(NoFontDelta)
-{
-    extractFontSizeDelta();
-}
-
 EditingStyle::EditingStyle(CSSPropertyID propertyID, const String& value)
     : m_mutableStyle(0)
     , m_shouldUseFixedDefaultFontSize(false)
@@ -387,7 +379,7 @@
         return primitiveColor->getRGBA32Value();
 
     RGBA32 rgba = 0;
-    CSSParser::parseColor(rgba, colorValue->cssText());
+    BisonCSSParser::parseColor(rgba, colorValue->cssText());
     return rgba;
 }
 
@@ -473,12 +465,12 @@
 
 void EditingStyle::removeTextFillAndStrokeColorsIfNeeded(RenderStyle* renderStyle)
 {
-    // If a node's text fill color is invalid, then its children use
+    // If a node's text fill color is currentColor, then its children use
     // their font-color as their text fill color (they don't
     // inherit it).  Likewise for stroke color.
-    if (!renderStyle->textFillColor().isValid())
+    if (renderStyle->textFillColor().isCurrentColor())
         m_mutableStyle->removeProperty(CSSPropertyWebkitTextFillColor);
-    if (!renderStyle->textStrokeColor().isValid())
+    if (renderStyle->textStrokeColor().isCurrentColor())
         m_mutableStyle->removeProperty(CSSPropertyWebkitTextStrokeColor);
 }
 
@@ -557,15 +549,6 @@
     return false;
 }
 
-void EditingStyle::setStyle(PassRefPtr<MutableStylePropertySet> style)
-{
-    m_mutableStyle = style;
-    // FIXME: We should be able to figure out whether or not font is fixed width for mutable style.
-    // We need to check font-family is monospace as in FontDescription but we don't want to duplicate code here.
-    m_shouldUseFixedDefaultFontSize = false;
-    extractFontSizeDelta();
-}
-
 void EditingStyle::overrideWithStyle(const StylePropertySet* style)
 {
     if (!style || style->isEmpty())
@@ -633,8 +616,8 @@
         return;
     RefPtr<MutableStylePropertySet> parentStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node->parentNode()), AllEditingProperties);
     RefPtr<MutableStylePropertySet> nodeStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node), AllEditingProperties);
-    nodeStyle->removeEquivalentProperties(parentStyle->ensureCSSStyleDeclaration());
-    m_mutableStyle->removeEquivalentProperties(nodeStyle->ensureCSSStyleDeclaration());
+    nodeStyle->removeEquivalentProperties(parentStyle.get());
+    m_mutableStyle->removeEquivalentProperties(nodeStyle.get());
 }
 
 void EditingStyle::removeStyleConflictingWithStyleOfNode(Node* node)
@@ -644,7 +627,7 @@
 
     RefPtr<MutableStylePropertySet> parentStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node->parentNode()), AllEditingProperties);
     RefPtr<MutableStylePropertySet> nodeStyle = editingStyleFromComputedStyle(CSSComputedStyleDeclaration::create(node), AllEditingProperties);
-    nodeStyle->removeEquivalentProperties(parentStyle->ensureCSSStyleDeclaration());
+    nodeStyle->removeEquivalentProperties(parentStyle.get());
 
     unsigned propertyCount = nodeStyle->propertyCount();
     for (unsigned i = 0; i < propertyCount; ++i)
@@ -1449,7 +1432,7 @@
         DEFINE_STATIC_REF(CSSPrimitiveValue, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
         DEFINE_STATIC_REF(CSSPrimitiveValue, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
 
-        RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
+        RefPtrWillBeRawPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
         if (newTextDecoration->removeAll(underline))
             m_applyUnderline = true;
         if (newTextDecoration->removeAll(lineThrough))
@@ -1498,7 +1481,7 @@
     if (!textDecoration || !textDecoration->isValueList() || !refTextDecoration || !refTextDecoration->isValueList())
         return;
 
-    RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
+    RefPtrWillBeRawPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
     CSSValueList* valuesInRefTextDecoration = toCSSValueList(refTextDecoration);
 
     for (size_t i = 0; i < valuesInRefTextDecoration->length(); i++)
diff --git a/Source/core/editing/EditingStyle.h b/Source/core/editing/EditingStyle.h
index fbfa6e8..43434ea 100644
--- a/Source/core/editing/EditingStyle.h
+++ b/Source/core/editing/EditingStyle.h
@@ -87,11 +87,6 @@
         return adoptRef(new EditingStyle(style));
     }
 
-    static PassRefPtr<EditingStyle> create(const CSSStyleDeclaration* style)
-    {
-        return adoptRef(new EditingStyle(style));
-    }
-
     static PassRefPtr<EditingStyle> create(CSSPropertyID propertyID, const String& value)
     {
         return adoptRef(new EditingStyle(propertyID, value));
@@ -102,7 +97,6 @@
     MutableStylePropertySet* style() { return m_mutableStyle.get(); }
     bool textDirection(WritingDirection&) const;
     bool isEmpty() const;
-    void setStyle(PassRefPtr<MutableStylePropertySet>);
     void overrideWithStyle(const StylePropertySet*);
     void clear();
     PassRefPtr<EditingStyle> copy() const;
@@ -142,7 +136,6 @@
 
     float fontSizeDelta() const { return m_fontSizeDelta; }
     bool hasFontSizeDelta() const { return m_fontSizeDelta != NoFontDelta; }
-    bool shouldUseFixedDefaultFontSize() const { return m_shouldUseFixedDefaultFontSize; }
 
     static PassRefPtr<EditingStyle> styleAtSelectionStart(const VisibleSelection&, bool shouldUseBackgroundColorInEffect = false);
     static WritingDirection textDirectionForSelection(const VisibleSelection&, EditingStyle* typingStyle, bool& hasNestedOrMultipleEmbeddings);
@@ -151,7 +144,6 @@
     EditingStyle(Node*, PropertiesToInclude);
     EditingStyle(const Position&, PropertiesToInclude);
     explicit EditingStyle(const StylePropertySet*);
-    explicit EditingStyle(const CSSStyleDeclaration*);
     EditingStyle(CSSPropertyID, const String& value);
     void init(Node*, PropertiesToInclude);
     void removeTextFillAndStrokeColorsIfNeeded(RenderStyle*);
diff --git a/Source/core/editing/Editor.cpp b/Source/core/editing/Editor.cpp
index c901524..a8cee67 100644
--- a/Source/core/editing/Editor.cpp
+++ b/Source/core/editing/Editor.cpp
@@ -29,11 +29,15 @@
 
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
+#include "SVGNames.h"
+#include "XLinkNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
+#include "core/clipboard/Clipboard.h"
+#include "core/clipboard/DataObject.h"
+#include "core/clipboard/Pasteboard.h"
 #include "core/css/CSSComputedStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
-#include "core/dom/Clipboard.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/DocumentMarkerController.h"
 #include "core/dom/NodeList.h"
@@ -45,7 +49,6 @@
 #include "core/editing/IndentOutdentCommand.h"
 #include "core/editing/InputMethodController.h"
 #include "core/editing/InsertListCommand.h"
-#include "core/editing/ModifySelectionListLevel.h"
 #include "core/editing/RemoveFormatCommand.h"
 #include "core/editing/RenderedPosition.h"
 #include "core/editing/ReplaceSelectionCommand.h"
@@ -61,22 +64,24 @@
 #include "core/events/ScopedEventQueue.h"
 #include "core/events/TextEvent.h"
 #include "core/events/ThreadLocalEventNames.h"
+#include "core/fetch/ImageResource.h"
 #include "core/fetch/ResourceFetcher.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLTextAreaElement.h"
+#include "core/html/parser/HTMLParserIdioms.h"
 #include "core/loader/EmptyClients.h"
 #include "core/page/EditorClient.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FocusController.h"
-#include "core/frame/Frame.h"
-#include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/Pasteboard.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/RenderImage.h"
 #include "platform/KillRing.h"
+#include "platform/weborigin/KURL.h"
 #include "wtf/unicode/CharacterNames.h"
 
 namespace WebCore {
@@ -110,7 +115,7 @@
     // If the target is a text control, and the current selection is outside of its shadow tree,
     // then use the saved selection for that text control.
     HTMLTextFormControlElement* textFormControlOfSelectionStart = enclosingTextFormControl(selection.start());
-    HTMLTextFormControlElement* textFromControlOfTarget = isHTMLTextFormControlElement(event->target()->toNode()) ? toHTMLTextFormControlElement(event->target()->toNode()) : 0;
+    HTMLTextFormControlElement* textFromControlOfTarget = isHTMLTextFormControlElement(*event->target()->toNode()) ? toHTMLTextFormControlElement(event->target()->toNode()) : 0;
     if (textFromControlOfTarget && (selection.start().isNull() || textFromControlOfTarget != textFormControlOfSelectionStart)) {
         if (RefPtr<Range> range = textFromControlOfTarget->selection())
             return VisibleSelection(range.get(), DOWNSTREAM, selection.isDirectional());
@@ -418,6 +423,34 @@
     pasteboard->writeHTML(html, url, plainText, canSmartCopyOrDelete());
 }
 
+static void writeImageNodeToPasteboard(Pasteboard* pasteboard, Node* node, const String& title)
+{
+    ASSERT(pasteboard);
+    ASSERT(node);
+
+    if (!(node->renderer() && node->renderer()->isImage()))
+        return;
+
+    RenderImage* renderer = toRenderImage(node->renderer());
+    ImageResource* cachedImage = renderer->cachedImage();
+    if (!cachedImage || cachedImage->errorOccurred())
+        return;
+    Image* image = cachedImage->imageForRenderer(renderer);
+    ASSERT(image);
+
+    // FIXME: This should probably be reconciled with HitTestResult::absoluteImageURL.
+    AtomicString urlString;
+    if (node->hasTagName(imgTag) || node->hasTagName(inputTag))
+        urlString = toElement(node)->getAttribute(srcAttr);
+    else if (node->hasTagName(SVGNames::imageTag))
+        urlString = toElement(node)->getAttribute(XLinkNames::hrefAttr);
+    else if (node->hasTagName(embedTag) || node->hasTagName(objectTag))
+        urlString = toElement(node)->imageSourceURL();
+    KURL url = urlString.isEmpty() ? KURL() : node->document().completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
+
+    pasteboard->writeImage(image, url, title);
+}
+
 // Returns whether caller should continue with "the default processing", which is the same as
 // the event handler NOT setting the return value to false
 bool Editor::dispatchCPPEvent(const AtomicString &eventType, ClipboardAccessPolicy policy, PasteMode pasteMode)
@@ -430,14 +463,14 @@
         Clipboard::CopyAndPaste,
         policy,
         policy == ClipboardWritable
-            ? ChromiumDataObject::create()
-            : ChromiumDataObject::createFromPasteboard(pasteMode));
+            ? DataObject::create()
+            : DataObject::createFromPasteboard(pasteMode));
 
     RefPtr<Event> evt = ClipboardEvent::create(eventType, true, true, clipboard);
     target->dispatchEvent(evt, IGNORE_EXCEPTION);
     bool noDefaultProcessing = evt->defaultPrevented();
     if (noDefaultProcessing && policy == ClipboardWritable) {
-        RefPtr<ChromiumDataObject> dataObject = clipboard->dataObject();
+        RefPtr<DataObject> dataObject = clipboard->dataObject();
         Pasteboard::generalPasteboard()->writeDataObject(dataObject.release());
     }
 
@@ -539,83 +572,6 @@
     return FalseTriState;
 }
 
-PassRefPtr<Node> Editor::insertOrderedList()
-{
-    if (!canEditRichly())
-        return 0;
-
-    ASSERT(m_frame.document());
-    RefPtr<Node> newList = InsertListCommand::insertList(*m_frame.document(), InsertListCommand::OrderedList);
-    revealSelectionAfterEditingOperation();
-    return newList;
-}
-
-PassRefPtr<Node> Editor::insertUnorderedList()
-{
-    if (!canEditRichly())
-        return 0;
-
-    ASSERT(m_frame.document());
-    RefPtr<Node> newList = InsertListCommand::insertList(*m_frame.document(), InsertListCommand::UnorderedList);
-    revealSelectionAfterEditingOperation();
-    return newList;
-}
-
-bool Editor::canIncreaseSelectionListLevel()
-{
-    ASSERT(m_frame.document());
-    return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(*m_frame.document());
-}
-
-bool Editor::canDecreaseSelectionListLevel()
-{
-    ASSERT(m_frame.document());
-    return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(*m_frame.document());
-}
-
-PassRefPtr<Node> Editor::increaseSelectionListLevel()
-{
-    if (!canEditRichly() || m_frame.selection().isNone())
-        return 0;
-
-    ASSERT(m_frame.document());
-    RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(*m_frame.document());
-    revealSelectionAfterEditingOperation();
-    return newList;
-}
-
-PassRefPtr<Node> Editor::increaseSelectionListLevelOrdered()
-{
-    if (!canEditRichly() || m_frame.selection().isNone())
-        return 0;
-
-    ASSERT(m_frame.document());
-    RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(*m_frame.document());
-    revealSelectionAfterEditingOperation();
-    return newList.release();
-}
-
-PassRefPtr<Node> Editor::increaseSelectionListLevelUnordered()
-{
-    if (!canEditRichly() || m_frame.selection().isNone())
-        return 0;
-
-    ASSERT(m_frame.document());
-    RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(*m_frame.document());
-    revealSelectionAfterEditingOperation();
-    return newList.release();
-}
-
-void Editor::decreaseSelectionListLevel()
-{
-    if (!canEditRichly() || m_frame.selection().isNone())
-        return;
-
-    ASSERT(m_frame.document());
-    DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(*m_frame.document());
-    revealSelectionAfterEditingOperation();
-}
-
 void Editor::removeFormattingAndStyle()
 {
     ASSERT(m_frame.document());
@@ -922,7 +878,7 @@
     } else {
         Document* document = m_frame.document();
         if (HTMLImageElement* imageElement = imageElementFromImageDocument(document))
-            Pasteboard::generalPasteboard()->writeImage(imageElement, document->url(), document->title());
+            writeImageNodeToPasteboard(Pasteboard::generalPasteboard(), imageElement, document->title());
         else
             writeSelectionToPasteboard(Pasteboard::generalPasteboard(), selectedRange().get(), m_frame.selectedTextForClipboard());
     }
@@ -968,11 +924,7 @@
 
 void Editor::copyImage(const HitTestResult& result)
 {
-    KURL url = result.absoluteLinkURL();
-    if (url.isEmpty())
-        url = result.absoluteImageURL();
-
-    Pasteboard::generalPasteboard()->writeImage(result.innerNonSharedNode(), url, result.altDisplayString());
+    writeImageNodeToPasteboard(Pasteboard::generalPasteboard(), result.innerNonSharedNode(), result.altDisplayString());
 }
 
 bool Editor::canUndo()
@@ -1004,7 +956,7 @@
 void Editor::setBaseWritingDirection(WritingDirection direction)
 {
     Node* focusedElement = frame().document()->focusedElement();
-    if (focusedElement && isHTMLTextFormControlElement(focusedElement)) {
+    if (focusedElement && isHTMLTextFormControlElement(*focusedElement)) {
         if (direction == NaturalWritingDirection)
             return;
         toHTMLElement(focusedElement)->setAttribute(dirAttr, direction == LeftToRightWritingDirection ? "ltr" : "rtl");
diff --git a/Source/core/editing/Editor.h b/Source/core/editing/Editor.h
index 15b1ba6..1ff3e22 100644
--- a/Source/core/editing/Editor.h
+++ b/Source/core/editing/Editor.h
@@ -26,7 +26,7 @@
 #ifndef Editor_h
 #define Editor_h
 
-#include "core/dom/ClipboardAccessPolicy.h"
+#include "core/clipboard/ClipboardAccessPolicy.h"
 #include "core/dom/DocumentMarker.h"
 #include "core/editing/EditAction.h"
 #include "core/editing/EditingBehavior.h"
@@ -112,14 +112,6 @@
 
     TriState selectionUnorderedListState() const;
     TriState selectionOrderedListState() const;
-    PassRefPtr<Node> insertOrderedList();
-    PassRefPtr<Node> insertUnorderedList();
-    bool canIncreaseSelectionListLevel();
-    bool canDecreaseSelectionListLevel();
-    PassRefPtr<Node> increaseSelectionListLevel();
-    PassRefPtr<Node> increaseSelectionListLevelOrdered();
-    PassRefPtr<Node> increaseSelectionListLevelUnordered();
-    void decreaseSelectionListLevel();
 
     void removeFormattingAndStyle();
 
@@ -163,7 +155,6 @@
     };
     Command command(const String& commandName); // Command source is CommandFromMenuOrKeyBinding.
     Command command(const String& commandName, EditorCommandSource);
-    static bool commandIsSupportedFromMenuOrKeyBinding(const String& commandName); // Works without a frame.
 
     bool insertText(const String&, Event* triggeringEvent);
     bool insertTextWithoutSendingTextEvent(const String&, bool selectInsertedText, TextEvent* triggeringEvent);
@@ -240,9 +231,6 @@
     };
     friend class RevealSelectionScope;
 
-    // Export interpretKeyEvent only for testing
-    static const char* interpretKeyEvent(const WebCore::KeyboardEvent*);
-
 private:
     Frame& m_frame;
     RefPtr<CompositeEditCommand> m_lastEditCommand;
diff --git a/Source/core/editing/EditorCommand.cpp b/Source/core/editing/EditorCommand.cpp
index 8c6291a..e1b207b 100644
--- a/Source/core/editing/EditorCommand.cpp
+++ b/Source/core/editing/EditorCommand.cpp
@@ -33,10 +33,10 @@
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/clipboard/Pasteboard.h"
 #include "core/css/CSSValueList.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/DocumentFragment.h"
-#include "core/events/Event.h"
 #include "core/editing/CreateLinkCommand.h"
 #include "core/editing/FormatBlockCommand.h"
 #include "core/editing/IndentOutdentCommand.h"
@@ -46,20 +46,21 @@
 #include "core/editing/TypingCommand.h"
 #include "core/editing/UnlinkCommand.h"
 #include "core/editing/markup.h"
+#include "core/events/Event.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLFontElement.h"
 #include "core/html/HTMLHRElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/page/Chrome.h"
 #include "core/page/EditorClient.h"
 #include "core/page/EventHandler.h"
-#include "core/frame/Frame.h"
-#include "core/frame/FrameView.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/Pasteboard.h"
 #include "core/rendering/RenderBox.h"
 #include "platform/KillRing.h"
 #include "platform/scroll/Scrollbar.h"
+#include "public/platform/Platform.h"
 #include "wtf/text/AtomicString.h"
 
 namespace WebCore {
@@ -68,6 +69,7 @@
 
 class EditorInternalCommand {
 public:
+    int idForUserMetrics;
     bool (*execute)(Frame&, Event*, EditorCommandSource, const String&);
     bool (*isSupportedFromDOM)(Frame*);
     bool (*isEnabled)(Frame&, Event*, EditorCommandSource);
@@ -140,7 +142,7 @@
     RefPtr<CSSValue> selectedCSSValue = selectionStyle->style()->getPropertyCSSValue(propertyID);
     String newStyle("none");
     if (selectedCSSValue->isValueList()) {
-        RefPtr<CSSValueList> selectedCSSValueList = toCSSValueList(selectedCSSValue.get());
+        RefPtrWillBeRawPtr<CSSValueList> selectedCSSValueList = toCSSValueList(selectedCSSValue.get());
         if (!selectedCSSValueList->removeAll(value))
             selectedCSSValueList->append(value);
         if (selectedCSSValueList->length())
@@ -489,7 +491,7 @@
     ASSERT(frame.document());
     RefPtr<HTMLHRElement> rule = HTMLHRElement::create(*frame.document());
     if (!value.isEmpty())
-        rule->setIdAttribute(value);
+        rule->setIdAttribute(AtomicString(value));
     return executeInsertNode(frame, rule.release());
 }
 
@@ -954,10 +956,10 @@
 
 static bool executePrint(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    Page* page = frame.page();
-    if (!page)
+    FrameHost* host = frame.host();
+    if (!host)
         return false;
-    page->chrome().print(&frame);
+    host->chrome().print(&frame);
     return true;
 }
 
@@ -975,32 +977,32 @@
 
 static bool executeScrollPageBackward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler().logicalScrollRecursively(ScrollBlockDirectionBackward, ScrollByPage);
+    return frame.eventHandler().bubblingScroll(ScrollBlockDirectionBackward, ScrollByPage);
 }
 
 static bool executeScrollPageForward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler().logicalScrollRecursively(ScrollBlockDirectionForward, ScrollByPage);
+    return frame.eventHandler().bubblingScroll(ScrollBlockDirectionForward, ScrollByPage);
 }
 
 static bool executeScrollLineUp(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler().scrollRecursively(ScrollUp, ScrollByLine);
+    return frame.eventHandler().bubblingScroll(ScrollUp, ScrollByLine);
 }
 
 static bool executeScrollLineDown(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler().scrollRecursively(ScrollDown, ScrollByLine);
+    return frame.eventHandler().bubblingScroll(ScrollDown, ScrollByLine);
 }
 
 static bool executeScrollToBeginningOfDocument(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler().logicalScrollRecursively(ScrollBlockDirectionBackward, ScrollByDocument);
+    return frame.eventHandler().bubblingScroll(ScrollBlockDirectionBackward, ScrollByDocument);
 }
 
 static bool executeScrollToEndOfDocument(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.eventHandler().logicalScrollRecursively(ScrollBlockDirectionForward, ScrollByDocument);
+    return frame.eventHandler().bubblingScroll(ScrollBlockDirectionForward, ScrollByDocument);
 }
 
 static bool executeSelectAll(Frame& frame, Event*, EditorCommandSource, const String&)
@@ -1047,7 +1049,7 @@
 
 static bool executeStrikethrough(Frame& frame, Event*, EditorCommandSource source, const String&)
 {
-    RefPtr<CSSPrimitiveValue> lineThrough = CSSPrimitiveValue::createIdentifier(CSSValueLineThrough);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> lineThrough = CSSPrimitiveValue::createIdentifier(CSSValueLineThrough);
     return executeToggleStyleInList(frame, source, EditActionUnderline, CSSPropertyWebkitTextDecorationsInEffect, lineThrough.get());
 }
 
@@ -1102,7 +1104,7 @@
 
 static bool executeUnderline(Frame& frame, Event*, EditorCommandSource source, const String&)
 {
-    RefPtr<CSSPrimitiveValue> underline = CSSPrimitiveValue::createIdentifier(CSSValueUnderline);
+    RefPtrWillBeRawPtr<CSSPrimitiveValue> underline = CSSPrimitiveValue::createIdentifier(CSSValueUnderline);
     return executeToggleStyleInList(frame, source, EditActionUnderline, CSSPropertyWebkitTextDecorationsInEffect, underline.get());
 }
 
@@ -1434,146 +1436,148 @@
 
 static const CommandMap& createCommandMap()
 {
+    // If you add new commands, you should assign new Id to each idForUserMetrics and update MappedEditingCommands
+    // in chrome/trunk/src/tools/metrics/histograms/histograms.xml.
     static const CommandEntry commands[] = {
-        { "AlignCenter", { executeJustifyCenter, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "AlignJustified", { executeJustifyFull, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "AlignLeft", { executeJustifyLeft, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "AlignRight", { executeJustifyRight, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "BackColor", { executeBackColor, supported, enabledInRichlyEditableText, stateNone, valueBackColor, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "BackwardDelete", { executeDeleteBackward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } }, // FIXME: remove BackwardDelete when Safari for Windows stops using it.
-        { "Bold", { executeToggleBold, supported, enabledInRichlyEditableText, stateBold, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Copy", { executeCopy, supportedCopyCut, enabledCopy, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
-        { "CreateLink", { executeCreateLink, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Cut", { executeCut, supportedCopyCut, enabledCut, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
-        { "DefaultParagraphSeparator", { executeDefaultParagraphSeparator, supported, enabled, stateNone, valueDefaultParagraphSeparator, notTextInsertion, doNotAllowExecutionWhenDisabled} },
-        { "Delete", { executeDelete, supported, enabledDelete, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteBackward", { executeDeleteBackward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteBackwardByDecomposingPreviousCharacter", { executeDeleteBackwardByDecomposingPreviousCharacter, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteForward", { executeDeleteForward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteToBeginningOfLine", { executeDeleteToBeginningOfLine, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteToBeginningOfParagraph", { executeDeleteToBeginningOfParagraph, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteToEndOfLine", { executeDeleteToEndOfLine, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteToEndOfParagraph", { executeDeleteToEndOfParagraph, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteToMark", { executeDeleteToMark, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteWordBackward", { executeDeleteWordBackward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "DeleteWordForward", { executeDeleteWordForward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "FindString", { executeFindString, supported, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "FontName", { executeFontName, supported, enabledInEditableText, stateNone, valueFontName, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "FontSize", { executeFontSize, supported, enabledInEditableText, stateNone, valueFontSize, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "FontSizeDelta", { executeFontSizeDelta, supported, enabledInEditableText, stateNone, valueFontSizeDelta, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ForeColor", { executeForeColor, supported, enabledInRichlyEditableText, stateNone, valueForeColor, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "FormatBlock", { executeFormatBlock, supported, enabledInRichlyEditableText, stateNone, valueFormatBlock, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ForwardDelete", { executeForwardDelete, supported, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "HiliteColor", { executeBackColor, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "IgnoreSpelling", { executeIgnoreSpelling, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Indent", { executeIndent, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertBacktab", { executeInsertBacktab, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertHTML", { executeInsertHTML, supported, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertHorizontalRule", { executeInsertHorizontalRule, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertImage", { executeInsertImage, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertLineBreak", { executeInsertLineBreak, supported, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertNewline", { executeInsertNewline, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertNewlineInQuotedContent", { executeInsertNewlineInQuotedContent, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertOrderedList", { executeInsertOrderedList, supported, enabledInRichlyEditableText, stateOrderedList, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertParagraph", { executeInsertParagraph, supported, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertTab", { executeInsertTab, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertText", { executeInsertText, supported, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "InsertUnorderedList", { executeInsertUnorderedList, supported, enabledInRichlyEditableText, stateUnorderedList, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Italic", { executeToggleItalic, supported, enabledInRichlyEditableText, stateItalic, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "JustifyCenter", { executeJustifyCenter, supported, enabledInRichlyEditableText, stateJustifyCenter, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "JustifyFull", { executeJustifyFull, supported, enabledInRichlyEditableText, stateJustifyFull, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "JustifyLeft", { executeJustifyLeft, supported, enabledInRichlyEditableText, stateJustifyLeft, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "JustifyNone", { executeJustifyLeft, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "JustifyRight", { executeJustifyRight, supported, enabledInRichlyEditableText, stateJustifyRight, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MakeTextWritingDirectionLeftToRight", { executeMakeTextWritingDirectionLeftToRight, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateTextWritingDirectionLeftToRight, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MakeTextWritingDirectionNatural", { executeMakeTextWritingDirectionNatural, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateTextWritingDirectionNatural, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MakeTextWritingDirectionRightToLeft", { executeMakeTextWritingDirectionRightToLeft, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateTextWritingDirectionRightToLeft, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveBackward", { executeMoveBackward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveBackwardAndModifySelection", { executeMoveBackwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveDown", { executeMoveDown, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveDownAndModifySelection", { executeMoveDownAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveForward", { executeMoveForward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveForwardAndModifySelection", { executeMoveForwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveLeft", { executeMoveLeft, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveLeftAndModifySelection", { executeMoveLeftAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MovePageDown", { executeMovePageDown, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MovePageDownAndModifySelection", { executeMovePageDownAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MovePageUp", { executeMovePageUp, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MovePageUpAndModifySelection", { executeMovePageUpAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveParagraphBackward", { executeMoveParagraphBackward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveParagraphBackwardAndModifySelection", { executeMoveParagraphBackwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveParagraphForward", { executeMoveParagraphForward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveParagraphForwardAndModifySelection", { executeMoveParagraphForwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveRight", { executeMoveRight, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveRightAndModifySelection", { executeMoveRightAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToBeginningOfDocument", { executeMoveToBeginningOfDocument, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToBeginningOfDocumentAndModifySelection", { executeMoveToBeginningOfDocumentAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToBeginningOfLine", { executeMoveToBeginningOfLine, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToBeginningOfLineAndModifySelection", { executeMoveToBeginningOfLineAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToBeginningOfParagraph", { executeMoveToBeginningOfParagraph, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToBeginningOfParagraphAndModifySelection", { executeMoveToBeginningOfParagraphAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToBeginningOfSentence", { executeMoveToBeginningOfSentence, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToBeginningOfSentenceAndModifySelection", { executeMoveToBeginningOfSentenceAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToEndOfDocument", { executeMoveToEndOfDocument, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToEndOfDocumentAndModifySelection", { executeMoveToEndOfDocumentAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToEndOfLine", { executeMoveToEndOfLine, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToEndOfLineAndModifySelection", { executeMoveToEndOfLineAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToEndOfParagraph", { executeMoveToEndOfParagraph, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToEndOfParagraphAndModifySelection", { executeMoveToEndOfParagraphAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToEndOfSentence", { executeMoveToEndOfSentence, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToEndOfSentenceAndModifySelection", { executeMoveToEndOfSentenceAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToLeftEndOfLine", { executeMoveToLeftEndOfLine, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToLeftEndOfLineAndModifySelection", { executeMoveToLeftEndOfLineAndModifySelection, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToRightEndOfLine", { executeMoveToRightEndOfLine, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveToRightEndOfLineAndModifySelection", { executeMoveToRightEndOfLineAndModifySelection, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveUp", { executeMoveUp, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveUpAndModifySelection", { executeMoveUpAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveWordBackward", { executeMoveWordBackward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveWordBackwardAndModifySelection", { executeMoveWordBackwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveWordForward", { executeMoveWordForward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveWordForwardAndModifySelection", { executeMoveWordForwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveWordLeft", { executeMoveWordLeft, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveWordLeftAndModifySelection", { executeMoveWordLeftAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveWordRight", { executeMoveWordRight, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "MoveWordRightAndModifySelection", { executeMoveWordRightAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Outdent", { executeOutdent, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "OverWrite", { executeToggleOverwrite, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Paste", { executePaste, supportedPaste, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
-        { "PasteAndMatchStyle", { executePasteAndMatchStyle, supportedPaste, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
-        { "PasteGlobalSelection", { executePasteGlobalSelection, supportedFromMenuOrKeyBinding, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
-        { "Print", { executePrint, supported, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Redo", { executeRedo, supported, enabledRedo, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "RemoveFormat", { executeRemoveFormat, supported, enabledRangeInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ScrollPageBackward", { executeScrollPageBackward, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ScrollPageForward", { executeScrollPageForward, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ScrollLineUp", { executeScrollLineUp, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ScrollLineDown", { executeScrollLineDown, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ScrollToBeginningOfDocument", { executeScrollToBeginningOfDocument, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ScrollToEndOfDocument", { executeScrollToEndOfDocument, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "SelectAll", { executeSelectAll, supported, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "SelectLine", { executeSelectLine, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "SelectParagraph", { executeSelectParagraph, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "SelectSentence", { executeSelectSentence, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "SelectToMark", { executeSelectToMark, supportedFromMenuOrKeyBinding, enabledVisibleSelectionAndMark, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "SelectWord", { executeSelectWord, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "SetMark", { executeSetMark, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Strikethrough", { executeStrikethrough, supported, enabledInRichlyEditableText, stateStrikethrough, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "StyleWithCSS", { executeStyleWithCSS, supported, enabled, stateStyleWithCSS, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Subscript", { executeSubscript, supported, enabledInRichlyEditableText, stateSubscript, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Superscript", { executeSuperscript, supported, enabledInRichlyEditableText, stateSuperscript, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "SwapWithMark", { executeSwapWithMark, supportedFromMenuOrKeyBinding, enabledVisibleSelectionAndMark, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ToggleBold", { executeToggleBold, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateBold, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ToggleItalic", { executeToggleItalic, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateItalic, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "ToggleUnderline", { executeUnderline, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateUnderline, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Transpose", { executeTranspose, supported, enableCaretInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Underline", { executeUnderline, supported, enabledInRichlyEditableText, stateUnderline, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Undo", { executeUndo, supported, enabledUndo, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Unlink", { executeUnlink, supported, enabledRangeInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Unscript", { executeUnscript, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Unselect", { executeUnselect, supported, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "UseCSS", { executeUseCSS, supported, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "Yank", { executeYank, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
-        { "YankAndSelect", { executeYankAndSelect, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "AlignCenter", {139, executeJustifyCenter, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "AlignJustified", {1, executeJustifyFull, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "AlignLeft", {2, executeJustifyLeft, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "AlignRight", {3, executeJustifyRight, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "BackColor", {4, executeBackColor, supported, enabledInRichlyEditableText, stateNone, valueBackColor, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "BackwardDelete", {5, executeDeleteBackward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } }, // FIXME: remove BackwardDelete when Safari for Windows stops using it.
+        { "Bold", {6, executeToggleBold, supported, enabledInRichlyEditableText, stateBold, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Copy", {7, executeCopy, supportedCopyCut, enabledCopy, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
+        { "CreateLink", {8, executeCreateLink, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Cut", {9, executeCut, supportedCopyCut, enabledCut, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
+        { "DefaultParagraphSeparator", {10, executeDefaultParagraphSeparator, supported, enabled, stateNone, valueDefaultParagraphSeparator, notTextInsertion, doNotAllowExecutionWhenDisabled} },
+        { "Delete", {11, executeDelete, supported, enabledDelete, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteBackward", {12, executeDeleteBackward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteBackwardByDecomposingPreviousCharacter", {13, executeDeleteBackwardByDecomposingPreviousCharacter, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteForward", {14, executeDeleteForward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteToBeginningOfLine", {15, executeDeleteToBeginningOfLine, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteToBeginningOfParagraph", {16, executeDeleteToBeginningOfParagraph, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteToEndOfLine", {17, executeDeleteToEndOfLine, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteToEndOfParagraph", {18, executeDeleteToEndOfParagraph, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteToMark", {19, executeDeleteToMark, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteWordBackward", {20, executeDeleteWordBackward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "DeleteWordForward", {21, executeDeleteWordForward, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "FindString", {22, executeFindString, supported, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "FontName", {23, executeFontName, supported, enabledInEditableText, stateNone, valueFontName, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "FontSize", {24, executeFontSize, supported, enabledInEditableText, stateNone, valueFontSize, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "FontSizeDelta", {25, executeFontSizeDelta, supported, enabledInEditableText, stateNone, valueFontSizeDelta, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ForeColor", {26, executeForeColor, supported, enabledInRichlyEditableText, stateNone, valueForeColor, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "FormatBlock", {27, executeFormatBlock, supported, enabledInRichlyEditableText, stateNone, valueFormatBlock, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ForwardDelete", {28, executeForwardDelete, supported, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "HiliteColor", {29, executeBackColor, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "IgnoreSpelling", {30, executeIgnoreSpelling, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Indent", {31, executeIndent, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertBacktab", {32, executeInsertBacktab, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertHTML", {33, executeInsertHTML, supported, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertHorizontalRule", {34, executeInsertHorizontalRule, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertImage", {35, executeInsertImage, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertLineBreak", {36, executeInsertLineBreak, supported, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertNewline", {37, executeInsertNewline, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertNewlineInQuotedContent", {38, executeInsertNewlineInQuotedContent, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertOrderedList", {39, executeInsertOrderedList, supported, enabledInRichlyEditableText, stateOrderedList, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertParagraph", {40, executeInsertParagraph, supported, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertTab", {41, executeInsertTab, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertText", {42, executeInsertText, supported, enabledInEditableText, stateNone, valueNull, isTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "InsertUnorderedList", {43, executeInsertUnorderedList, supported, enabledInRichlyEditableText, stateUnorderedList, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Italic", {44, executeToggleItalic, supported, enabledInRichlyEditableText, stateItalic, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "JustifyCenter", {45, executeJustifyCenter, supported, enabledInRichlyEditableText, stateJustifyCenter, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "JustifyFull", {46, executeJustifyFull, supported, enabledInRichlyEditableText, stateJustifyFull, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "JustifyLeft", {47, executeJustifyLeft, supported, enabledInRichlyEditableText, stateJustifyLeft, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "JustifyNone", {48, executeJustifyLeft, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "JustifyRight", {49, executeJustifyRight, supported, enabledInRichlyEditableText, stateJustifyRight, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MakeTextWritingDirectionLeftToRight", {50, executeMakeTextWritingDirectionLeftToRight, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateTextWritingDirectionLeftToRight, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MakeTextWritingDirectionNatural", {51, executeMakeTextWritingDirectionNatural, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateTextWritingDirectionNatural, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MakeTextWritingDirectionRightToLeft", {52, executeMakeTextWritingDirectionRightToLeft, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateTextWritingDirectionRightToLeft, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveBackward", {53, executeMoveBackward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveBackwardAndModifySelection", {54, executeMoveBackwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveDown", {55, executeMoveDown, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveDownAndModifySelection", {56, executeMoveDownAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveForward", {57, executeMoveForward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveForwardAndModifySelection", {58, executeMoveForwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveLeft", {59, executeMoveLeft, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveLeftAndModifySelection", {60, executeMoveLeftAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MovePageDown", {61, executeMovePageDown, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MovePageDownAndModifySelection", {62, executeMovePageDownAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MovePageUp", {63, executeMovePageUp, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MovePageUpAndModifySelection", {64, executeMovePageUpAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveParagraphBackward", {65, executeMoveParagraphBackward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveParagraphBackwardAndModifySelection", {66, executeMoveParagraphBackwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveParagraphForward", {67, executeMoveParagraphForward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveParagraphForwardAndModifySelection", {68, executeMoveParagraphForwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveRight", {69, executeMoveRight, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveRightAndModifySelection", {70, executeMoveRightAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToBeginningOfDocument", {71, executeMoveToBeginningOfDocument, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToBeginningOfDocumentAndModifySelection", {72, executeMoveToBeginningOfDocumentAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToBeginningOfLine", {73, executeMoveToBeginningOfLine, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToBeginningOfLineAndModifySelection", {74, executeMoveToBeginningOfLineAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToBeginningOfParagraph", {75, executeMoveToBeginningOfParagraph, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToBeginningOfParagraphAndModifySelection", {76, executeMoveToBeginningOfParagraphAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToBeginningOfSentence", {77, executeMoveToBeginningOfSentence, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToBeginningOfSentenceAndModifySelection", {78, executeMoveToBeginningOfSentenceAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToEndOfDocument", {79, executeMoveToEndOfDocument, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToEndOfDocumentAndModifySelection", {80, executeMoveToEndOfDocumentAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToEndOfLine", {81, executeMoveToEndOfLine, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToEndOfLineAndModifySelection", {82, executeMoveToEndOfLineAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToEndOfParagraph", {83, executeMoveToEndOfParagraph, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToEndOfParagraphAndModifySelection", {84, executeMoveToEndOfParagraphAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToEndOfSentence", {85, executeMoveToEndOfSentence, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToEndOfSentenceAndModifySelection", {86, executeMoveToEndOfSentenceAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToLeftEndOfLine", {87, executeMoveToLeftEndOfLine, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToLeftEndOfLineAndModifySelection", {88, executeMoveToLeftEndOfLineAndModifySelection, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToRightEndOfLine", {89, executeMoveToRightEndOfLine, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveToRightEndOfLineAndModifySelection", {90, executeMoveToRightEndOfLineAndModifySelection, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveUp", {91, executeMoveUp, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveUpAndModifySelection", {92, executeMoveUpAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveWordBackward", {93, executeMoveWordBackward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveWordBackwardAndModifySelection", {94, executeMoveWordBackwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveWordForward", {95, executeMoveWordForward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveWordForwardAndModifySelection", {96, executeMoveWordForwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveWordLeft", {97, executeMoveWordLeft, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveWordLeftAndModifySelection", {98, executeMoveWordLeftAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveWordRight", {99, executeMoveWordRight, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveWordRightAndModifySelection", {100, executeMoveWordRightAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Outdent", {101, executeOutdent, supported, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "OverWrite", {102, executeToggleOverwrite, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Paste", {103, executePaste, supportedPaste, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
+        { "PasteAndMatchStyle", {104, executePasteAndMatchStyle, supportedPaste, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
+        { "PasteGlobalSelection", {105, executePasteGlobalSelection, supportedFromMenuOrKeyBinding, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
+        { "Print", {106, executePrint, supported, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Redo", {107, executeRedo, supported, enabledRedo, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "RemoveFormat", {108, executeRemoveFormat, supported, enabledRangeInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ScrollPageBackward", {109, executeScrollPageBackward, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ScrollPageForward", {110, executeScrollPageForward, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ScrollLineUp", {111, executeScrollLineUp, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ScrollLineDown", {112, executeScrollLineDown, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ScrollToBeginningOfDocument", {113, executeScrollToBeginningOfDocument, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ScrollToEndOfDocument", {114, executeScrollToEndOfDocument, supportedFromMenuOrKeyBinding, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "SelectAll", {115, executeSelectAll, supported, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "SelectLine", {116, executeSelectLine, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "SelectParagraph", {117, executeSelectParagraph, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "SelectSentence", {118, executeSelectSentence, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "SelectToMark", {119, executeSelectToMark, supportedFromMenuOrKeyBinding, enabledVisibleSelectionAndMark, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "SelectWord", {120, executeSelectWord, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "SetMark", {121, executeSetMark, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Strikethrough", {122, executeStrikethrough, supported, enabledInRichlyEditableText, stateStrikethrough, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "StyleWithCSS", {123, executeStyleWithCSS, supported, enabled, stateStyleWithCSS, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Subscript", {124, executeSubscript, supported, enabledInRichlyEditableText, stateSubscript, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Superscript", {125, executeSuperscript, supported, enabledInRichlyEditableText, stateSuperscript, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "SwapWithMark", {126, executeSwapWithMark, supportedFromMenuOrKeyBinding, enabledVisibleSelectionAndMark, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ToggleBold", {127, executeToggleBold, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateBold, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ToggleItalic", {128, executeToggleItalic, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateItalic, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "ToggleUnderline", {129, executeUnderline, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateUnderline, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Transpose", {130, executeTranspose, supported, enableCaretInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Underline", {131, executeUnderline, supported, enabledInRichlyEditableText, stateUnderline, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Undo", {132, executeUndo, supported, enabledUndo, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Unlink", {133, executeUnlink, supported, enabledRangeInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Unscript", {134, executeUnscript, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Unselect", {135, executeUnselect, supported, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "UseCSS", {136, executeUseCSS, supported, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "Yank", {137, executeYank, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "YankAndSelect", {138, executeYankAndSelect, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
     };
 
     // These unsupported commands are listed here since they appear in the Microsoft
@@ -1623,10 +1627,17 @@
     // Unbookmark (not supported)
 
     CommandMap& commandMap = *new CommandMap;
-
+#if !ASSERT_DISABLED
+    HashSet<int> idSet;
+#endif
     for (size_t i = 0; i < WTF_ARRAY_LENGTH(commands); ++i) {
-        ASSERT(!commandMap.get(commands[i].name));
-        commandMap.set(commands[i].name, &commands[i].command);
+        const CommandEntry& command = commands[i];
+        ASSERT(!commandMap.get(command.name));
+        commandMap.set(command.name, &command.command);
+#if !ASSERT_DISABLED
+        ASSERT(!idSet.contains(command.command.idForUserMetrics));
+        idSet.add(command.command.idForUserMetrics);
+#endif
     }
 
     return commandMap;
@@ -1648,11 +1659,6 @@
     return Command(internalCommand(commandName), source, &m_frame);
 }
 
-bool Editor::commandIsSupportedFromMenuOrKeyBinding(const String& commandName)
-{
-    return internalCommand(commandName);
-}
-
 Editor::Command::Command()
     : m_command(0)
 {
@@ -1678,6 +1684,7 @@
             return false;
     }
     m_frame->document()->updateLayoutIgnorePendingStylesheets();
+    blink::Platform::current()->histogramSparse("WebCore.Editing.Commands", m_command->idForUserMetrics);
     return m_command->execute(*m_frame, triggeringEvent, m_source, parameter);
 }
 
diff --git a/Source/core/editing/EditorKeyBindings.cpp b/Source/core/editing/EditorKeyBindings.cpp
index 48295ec..f39c047 100644
--- a/Source/core/editing/EditorKeyBindings.cpp
+++ b/Source/core/editing/EditorKeyBindings.cpp
@@ -30,199 +30,10 @@
 #include "core/events/KeyboardEvent.h"
 #include "core/frame/Frame.h"
 #include "core/page/EditorClient.h"
-#include "core/platform/chromium/KeyboardCodes.h"
 #include "platform/PlatformKeyboardEvent.h"
 
 namespace WebCore {
 
-//
-// The below code was adapted from the WebKit file webview.cpp
-//
-
-static const unsigned CtrlKey = 1 << 0;
-static const unsigned AltKey = 1 << 1;
-static const unsigned ShiftKey = 1 << 2;
-static const unsigned MetaKey = 1 << 3;
-#if OS(MACOSX)
-// Aliases for the generic key defintions to make kbd shortcuts definitions more
-// readable on OS X.
-static const unsigned OptionKey  = AltKey;
-
-// Do not use this constant for anything but cursor movement commands. Keys
-// with cmd set have their |isSystemKey| bit set, so chances are the shortcut
-// will not be executed. Another, less important, reason is that shortcuts
-// defined in the renderer do not blink the menu item that they triggered. See
-// http://crbug.com/25856 and the bugs linked from there for details.
-static const unsigned CommandKey = MetaKey;
-#endif
-
-// Keys with special meaning. These will be delegated to the editor using
-// the execCommand() method
-struct KeyDownEntry {
-    unsigned virtualKey;
-    unsigned modifiers;
-    const char* name;
-};
-
-struct KeyPressEntry {
-    unsigned charCode;
-    unsigned modifiers;
-    const char* name;
-};
-
-// Key bindings with command key on Mac and alt key on other platforms are
-// marked as system key events and will be ignored (with the exception
-// of Command-B and Command-I) so they shouldn't be added here.
-static const KeyDownEntry keyDownEntries[] = {
-    { VKEY_LEFT,   0,                  "MoveLeft"                             },
-    { VKEY_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"           },
-#if OS(MACOSX)
-    { VKEY_LEFT,   OptionKey,          "MoveWordLeft"                         },
-    { VKEY_LEFT,   OptionKey | ShiftKey,
-        "MoveWordLeftAndModifySelection"                                      },
-#else
-    { VKEY_LEFT,   CtrlKey,            "MoveWordLeft"                         },
-    { VKEY_LEFT,   CtrlKey | ShiftKey,
-        "MoveWordLeftAndModifySelection"                                      },
-#endif
-    { VKEY_RIGHT,  0,                  "MoveRight"                            },
-    { VKEY_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"          },
-#if OS(MACOSX)
-    { VKEY_RIGHT,  OptionKey,          "MoveWordRight"                        },
-    { VKEY_RIGHT,  OptionKey | ShiftKey, "MoveWordRightAndModifySelection"    },
-#else
-    { VKEY_RIGHT,  CtrlKey,            "MoveWordRight"                        },
-    { VKEY_RIGHT,  CtrlKey | ShiftKey, "MoveWordRightAndModifySelection"      },
-#endif
-    { VKEY_UP,     0,                  "MoveUp"                               },
-    { VKEY_UP,     ShiftKey,           "MoveUpAndModifySelection"             },
-    { VKEY_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"         },
-    { VKEY_DOWN,   0,                  "MoveDown"                             },
-    { VKEY_DOWN,   ShiftKey,           "MoveDownAndModifySelection"           },
-    { VKEY_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"       },
-#if !OS(MACOSX)
-    { VKEY_UP,     CtrlKey,            "MoveParagraphBackward"                },
-    { VKEY_UP,     CtrlKey | ShiftKey, "MoveParagraphBackwardAndModifySelection" },
-    { VKEY_DOWN,   CtrlKey,            "MoveParagraphForward"                },
-    { VKEY_DOWN,   CtrlKey | ShiftKey, "MoveParagraphForwardAndModifySelection" },
-    { VKEY_PRIOR,  0,                  "MovePageUp"                           },
-    { VKEY_NEXT,   0,                  "MovePageDown"                         },
-#endif
-    { VKEY_HOME,   0,                  "MoveToBeginningOfLine"                },
-    { VKEY_HOME,   ShiftKey,
-        "MoveToBeginningOfLineAndModifySelection"                             },
-#if OS(MACOSX)
-    { VKEY_PRIOR,  OptionKey,          "MovePageUp"                           },
-    { VKEY_NEXT,   OptionKey,          "MovePageDown"                         },
-#endif
-#if !OS(MACOSX)
-    { VKEY_HOME,   CtrlKey,            "MoveToBeginningOfDocument"            },
-    { VKEY_HOME,   CtrlKey | ShiftKey,
-        "MoveToBeginningOfDocumentAndModifySelection"                         },
-#endif
-    { VKEY_END,    0,                  "MoveToEndOfLine"                      },
-    { VKEY_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"    },
-#if !OS(MACOSX)
-    { VKEY_END,    CtrlKey,            "MoveToEndOfDocument"                  },
-    { VKEY_END,    CtrlKey | ShiftKey,
-        "MoveToEndOfDocumentAndModifySelection"                               },
-#endif
-    { VKEY_BACK,   0,                  "DeleteBackward"                       },
-    { VKEY_BACK,   ShiftKey,           "DeleteBackward"                       },
-    { VKEY_DELETE, 0,                  "DeleteForward"                        },
-#if OS(MACOSX)
-    { VKEY_BACK,   OptionKey,          "DeleteWordBackward"                   },
-    { VKEY_DELETE, OptionKey,          "DeleteWordForward"                    },
-#else
-    { VKEY_BACK,   CtrlKey,            "DeleteWordBackward"                   },
-    { VKEY_DELETE, CtrlKey,            "DeleteWordForward"                    },
-#endif
-#if OS(MACOSX)
-    { 'B',         CommandKey,         "ToggleBold"                           },
-    { 'I',         CommandKey,         "ToggleItalic"                         },
-#else
-    { 'B',         CtrlKey,            "ToggleBold"                           },
-    { 'I',         CtrlKey,            "ToggleItalic"                         },
-#endif
-    { 'U',         CtrlKey,            "ToggleUnderline"                      },
-    { VKEY_ESCAPE, 0,                  "Cancel"                               },
-    { VKEY_OEM_PERIOD, CtrlKey,        "Cancel"                               },
-    { VKEY_TAB,    0,                  "InsertTab"                            },
-    { VKEY_TAB,    ShiftKey,           "InsertBacktab"                        },
-    { VKEY_RETURN, 0,                  "InsertNewline"                        },
-    { VKEY_RETURN, CtrlKey,            "InsertNewline"                        },
-    { VKEY_RETURN, AltKey,             "InsertNewline"                        },
-    { VKEY_RETURN, AltKey | ShiftKey,  "InsertNewline"                        },
-    { VKEY_RETURN, ShiftKey,           "InsertLineBreak"                      },
-    { VKEY_INSERT, CtrlKey,            "Copy"                                 },
-    { VKEY_INSERT, ShiftKey,           "Paste"                                },
-    { VKEY_DELETE, ShiftKey,           "Cut"                                  },
-#if !OS(MACOSX)
-    // On OS X, we pipe these back to the browser, so that it can do menu item
-    // blinking.
-    { 'C',         CtrlKey,            "Copy"                                 },
-    { 'V',         CtrlKey,            "Paste"                                },
-    { 'V',         CtrlKey | ShiftKey, "PasteAndMatchStyle"                   },
-    { 'X',         CtrlKey,            "Cut"                                  },
-    { 'A',         CtrlKey,            "SelectAll"                            },
-    { 'Z',         CtrlKey,            "Undo"                                 },
-    { 'Z',         CtrlKey | ShiftKey, "Redo"                                 },
-    { 'Y',         CtrlKey,            "Redo"                                 },
-#endif
-    { VKEY_INSERT, 0,                  "OverWrite"                            },
-};
-
-static const KeyPressEntry keyPressEntries[] = {
-    { '\t',   0,                  "InsertTab"                                 },
-    { '\t',   ShiftKey,           "InsertBacktab"                             },
-    { '\r',   0,                  "InsertNewline"                             },
-    { '\r',   CtrlKey,            "InsertNewline"                             },
-    { '\r',   ShiftKey,           "InsertLineBreak"                           },
-    { '\r',   AltKey,             "InsertNewline"                             },
-    { '\r',   AltKey | ShiftKey,  "InsertNewline"                             },
-};
-
-const char* Editor::interpretKeyEvent(const KeyboardEvent* evt)
-{
-    const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
-    if (!keyEvent)
-        return "";
-
-    static HashMap<int, const char*>* keyDownCommandsMap = 0;
-    static HashMap<int, const char*>* keyPressCommandsMap = 0;
-
-    if (!keyDownCommandsMap) {
-        keyDownCommandsMap = new HashMap<int, const char*>;
-        keyPressCommandsMap = new HashMap<int, const char*>;
-
-        for (unsigned i = 0; i < arraysize(keyDownEntries); i++) {
-            keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
-        }
-
-        for (unsigned i = 0; i < arraysize(keyPressEntries); i++) {
-            keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
-        }
-    }
-
-    unsigned modifiers = 0;
-    if (keyEvent->shiftKey())
-        modifiers |= ShiftKey;
-    if (keyEvent->altKey())
-        modifiers |= AltKey;
-    if (keyEvent->ctrlKey())
-        modifiers |= CtrlKey;
-    if (keyEvent->metaKey())
-        modifiers |= MetaKey;
-
-    if (keyEvent->type() == PlatformEvent::RawKeyDown) {
-        int mapKey = modifiers << 16 | evt->keyCode();
-        return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
-    }
-
-    int mapKey = modifiers << 16 | evt->charCode();
-    return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
-}
-
 bool Editor::handleEditingKeyboardEvent(KeyboardEvent* evt)
 {
     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
@@ -230,7 +41,7 @@
     if (!keyEvent || keyEvent->isSystemKey())
         return false;
 
-    String commandName = interpretKeyEvent(evt);
+    String commandName = behavior().interpretKeyEvent(*evt);
     Command command = this->command(commandName);
 
     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
@@ -253,45 +64,7 @@
         return true;
     }
 
-    // Here we need to filter key events.
-    // On Gtk/Linux, it emits key events with ASCII text and ctrl on for ctrl-<x>.
-    // In Webkit, EditorClient::handleKeyboardEvent in
-    // WebKit/gtk/WebCoreSupport/EditorClientGtk.cpp drop such events.
-    // On Mac, it emits key events with ASCII text and meta on for Command-<x>.
-    // These key events should not emit text insert event.
-    // Alt key would be used to insert alternative character, so we should let
-    // through. Also note that Ctrl-Alt combination equals to AltGr key which is
-    // also used to insert alternative character.
-    // http://code.google.com/p/chromium/issues/detail?id=10846
-    // Windows sets both alt and meta are on when "Alt" key pressed.
-    // http://code.google.com/p/chromium/issues/detail?id=2215
-    // Also, we should not rely on an assumption that keyboards don't
-    // send ASCII characters when pressing a control key on Windows,
-    // which may be configured to do it so by user.
-    // See also http://en.wikipedia.org/wiki/Keyboard_Layout
-    // FIXME(ukai): investigate more detail for various keyboard layout.
-    if (evt->keyEvent()->text().length() == 1) {
-        UChar ch = evt->keyEvent()->text()[0U];
-
-        // Don't insert null or control characters as they can result in
-        // unexpected behaviour
-        if (ch < ' ')
-            return false;
-#if !OS(WIN)
-        // Don't insert ASCII character if ctrl w/o alt or meta is on.
-        // On Mac, we should ignore events when meta is on (Command-<x>).
-        if (ch < 0x80) {
-            if (evt->keyEvent()->ctrlKey() && !evt->keyEvent()->altKey())
-                return false;
-#if OS(MACOSX)
-            if (evt->keyEvent()->metaKey())
-            return false;
-#endif
-        }
-#endif
-    }
-
-    if (!canEdit())
+    if (!behavior().shouldInsertCharacter(*evt) || !canEdit())
         return false;
 
     return insertText(evt->keyEvent()->text(), evt);
diff --git a/Source/core/editing/FormatBlockCommand.h b/Source/core/editing/FormatBlockCommand.h
index da6add6..e18bbfa 100644
--- a/Source/core/editing/FormatBlockCommand.h
+++ b/Source/core/editing/FormatBlockCommand.h
@@ -38,14 +38,14 @@
 class Range;
 class VisiblePosition;
 
-class FormatBlockCommand : public ApplyBlockElementCommand {
+class FormatBlockCommand FINAL : public ApplyBlockElementCommand {
 public:
     static PassRefPtr<FormatBlockCommand> create(Document& document, const QualifiedName& tagName)
     {
         return adoptRef(new FormatBlockCommand(document, tagName));
     }
 
-    virtual bool preservesTypingStyle() const { return true; }
+    virtual bool preservesTypingStyle() const OVERRIDE { return true; }
 
     static Element* elementForFormatBlockCommand(Range*);
     bool didApply() const { return m_didApply; }
@@ -53,9 +53,9 @@
 private:
     FormatBlockCommand(Document&, const QualifiedName& tagName);
 
-    void formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection);
-    void formatRange(const Position& start, const Position& end, const Position& endOfSelection, RefPtr<Element>&);
-    EditAction editingAction() const { return EditActionFormatBlock; }
+    virtual void formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection) OVERRIDE;
+    virtual void formatRange(const Position& start, const Position& end, const Position& endOfSelection, RefPtr<Element>&) OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE { return EditActionFormatBlock; }
 
     bool m_didApply;
 };
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index b07ac8d..7f546b8 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -57,7 +57,7 @@
 #include "core/page/FrameTree.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/page/SpatialNavigation.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
@@ -115,7 +115,7 @@
         return selectionRoot;
 
     Node* node = m_selection.base().containerNode();
-    return node ? node->treeScope().rootNode() : 0;
+    return node ? &node->treeScope().rootNode() : 0;
 }
 
 void FrameSelection::moveTo(const VisiblePosition &pos, EUserTriggered userTriggered, CursorAlignOnScroll align)
@@ -137,20 +137,6 @@
     setSelection(VisibleSelection(pos, affinity, m_selection.isDirectional()), options);
 }
 
-void FrameSelection::moveTo(const Range *r, EAffinity affinity, EUserTriggered userTriggered)
-{
-    SetSelectionOptions options = CloseTyping | ClearTypingStyle | userTriggered;
-    VisibleSelection selection = r ? VisibleSelection(r->startPosition(), r->endPosition(), affinity) : VisibleSelection(Position(), Position(), affinity);
-    setSelection(selection, options);
-}
-
-void FrameSelection::moveTo(const Position &base, const Position &extent, EAffinity affinity, EUserTriggered userTriggered)
-{
-    const bool selectionHasDirection = true;
-    SetSelectionOptions options = CloseTyping | ClearTypingStyle | userTriggered;
-    setSelection(VisibleSelection(base, extent, affinity, selectionHasDirection), options);
-}
-
 static void adjustEndpointsAtBidiBoundary(VisiblePosition& visibleBase, VisiblePosition& visibleExtent)
 {
     RenderedPosition base(visibleBase);
@@ -1208,18 +1194,6 @@
     setSelection(VisibleSelection(m_selection.base(), pos.deepEquivalent(), pos.affinity(), selectionHasDirection), CloseTyping | ClearTypingStyle | userTriggered);
 }
 
-void FrameSelection::setBase(const Position &pos, EAffinity affinity, EUserTriggered userTriggered)
-{
-    const bool selectionHasDirection = true;
-    setSelection(VisibleSelection(pos, m_selection.extent(), affinity, selectionHasDirection), CloseTyping | ClearTypingStyle | userTriggered);
-}
-
-void FrameSelection::setExtent(const Position &pos, EAffinity affinity, EUserTriggered userTriggered)
-{
-    const bool selectionHasDirection = true;
-    setSelection(VisibleSelection(m_selection.base(), pos, affinity, selectionHasDirection), CloseTyping | ClearTypingStyle | userTriggered);
-}
-
 RenderObject* FrameSelection::caretRenderer() const
 {
     return CaretBase::caretRenderer(m_selection.start().deprecatedNode());
@@ -1253,11 +1227,7 @@
     if (!shouldUpdateCaretRect())
         return false;
 
-    if (!m_frame)
-        return false;
-
-    FrameView* v = m_frame->document()->view();
-    if (!v)
+    if (!m_frame || !m_frame->document()->view())
         return false;
 
     LayoutRect oldRect = localCaretRectWithoutUpdate();
@@ -1273,9 +1243,9 @@
         return false;
 
     if (RenderView* view = m_frame->document()->renderView()) {
-        Node* node = m_selection.start().deprecatedNode();
-        if (m_previousCaretNode)
+        if (m_previousCaretNode && shouldRepaintCaret(view, m_previousCaretNode->isContentEditable()))
             repaintCaretForLocalRect(m_previousCaretNode.get(), oldRect);
+        Node* node = m_selection.start().deprecatedNode();
         m_previousCaretNode = node;
         if (shouldRepaintCaret(view, isContentEditable()))
             repaintCaretForLocalRect(node, newRect);
@@ -1691,13 +1661,6 @@
         m_frame->page()->focusController().setFocusedElement(0, m_frame);
 }
 
-PassRefPtr<MutableStylePropertySet> FrameSelection::copyTypingStyle() const
-{
-    if (!m_typingStyle || !m_typingStyle->style())
-        return 0;
-    return m_typingStyle->style()->mutableCopy();
-}
-
 static String extractSelectedText(const FrameSelection& selection, TextIteratorBehavior behavior)
 {
     // We remove '\0' characters because they are not visibly rendered to the user.
@@ -1739,8 +1702,11 @@
     for (; element; element = ElementTraversal::next(*element)) {
         if (element->hasTagName(formTag))
             return toHTMLFormElement(element);
-        if (element->isHTMLElement() && toHTMLElement(element)->isFormControlElement())
-            return toHTMLFormControlElement(element)->form();
+        if (element->isHTMLElement()) {
+            HTMLFormElement* owner = toHTMLElement(element)->formOwner();
+            if (owner)
+                return owner;
+        }
         if (element->hasTagName(frameTag) || element->hasTagName(iframeTag)) {
             Node* childDocument = toHTMLFrameElementBase(element)->contentDocument();
             if (HTMLFormElement* frameResult = scanForForm(childDocument))
@@ -1763,8 +1729,11 @@
     for (node = start; node; node = node->parentNode()) {
         if (node->hasTagName(formTag))
             return toHTMLFormElement(node);
-        if (node->isHTMLElement() && toHTMLElement(node)->isFormControlElement())
-            return toHTMLFormControlElement(node)->form();
+        if (node->isHTMLElement()) {
+            HTMLFormElement* owner = toHTMLElement(node)->formOwner();
+            if (owner)
+                return owner;
+        }
     }
 
     // Try walking forward in the node tree to find a form element.
diff --git a/Source/core/editing/FrameSelection.h b/Source/core/editing/FrameSelection.h
index 04b6599..7e88d9f 100644
--- a/Source/core/editing/FrameSelection.h
+++ b/Source/core/editing/FrameSelection.h
@@ -30,7 +30,7 @@
 #include "core/editing/Caret.h"
 #include "core/editing/EditingStyle.h"
 #include "core/editing/VisibleSelection.h"
-#include "core/rendering/ScrollBehavior.h"
+#include "core/rendering/ScrollAlignment.h"
 #include "platform/Timer.h"
 #include "platform/geometry/IntRect.h"
 #include "platform/geometry/LayoutRect.h"
@@ -87,11 +87,9 @@
     bool isContentEditable() const { return m_selection.isContentEditable(); }
     bool isContentRichlyEditable() const { return m_selection.isContentRichlyEditable(); }
 
-    void moveTo(const Range*, EAffinity, EUserTriggered = NotUserTriggered);
     void moveTo(const VisiblePosition&, EUserTriggered = NotUserTriggered, CursorAlignOnScroll = AlignCursorOnScrollIfNeeded);
     void moveTo(const VisiblePosition&, const VisiblePosition&, EUserTriggered = NotUserTriggered);
     void moveTo(const Position&, EAffinity, EUserTriggered = NotUserTriggered);
-    void moveTo(const Position&, const Position&, EAffinity, EUserTriggered = NotUserTriggered);
 
     const VisibleSelection& selection() const { return m_selection; }
     void setSelection(const VisibleSelection&, SetSelectionOptions = CloseTyping | ClearTypingStyle, CursorAlignOnScroll = AlignCursorOnScrollIfNeeded, TextGranularity = CharacterGranularity);
@@ -120,9 +118,7 @@
     void setEnd(const VisiblePosition &, EUserTriggered = NotUserTriggered);
 
     void setBase(const VisiblePosition&, EUserTriggered = NotUserTriggered);
-    void setBase(const Position&, EAffinity, EUserTriggered = NotUserTriggered);
     void setExtent(const VisiblePosition&, EUserTriggered = NotUserTriggered);
-    void setExtent(const Position&, EAffinity, EUserTriggered = NotUserTriggered);
 
     Position base() const { return m_selection.base(); }
     Position extent() const { return m_selection.extent(); }
@@ -147,7 +143,6 @@
     bool isRange() const { return m_selection.isRange(); }
     bool isCaretOrRange() const { return m_selection.isCaretOrRange(); }
     bool isInPasswordField() const;
-    bool isAll(EditingBoundaryCrossingRule rule = CannotCrossEditingBoundary) const { return m_selection.isAll(rule); }
 
     PassRefPtr<Range> toNormalizedRange() const { return m_selection.toNormalizedRange(); }
 
@@ -186,10 +181,7 @@
     void setFocusedNodeIfNeeded();
     void notifyRendererOfSelectionChange(EUserTriggered);
 
-    void paintDragCaret(GraphicsContext*, const LayoutPoint&, const LayoutRect& clipRect) const;
-
     EditingStyle* typingStyle() const;
-    PassRefPtr<MutableStylePropertySet> copyTypingStyle() const;
     void setTypingStyle(PassRefPtr<EditingStyle>);
     void clearTypingStyle();
 
@@ -203,7 +195,6 @@
     void revealSelection(const ScrollAlignment& = ScrollAlignment::alignCenterIfNeeded, RevealExtentOption = DoNotRevealExtent);
     void setSelectionFromNone();
 
-    bool shouldShowBlockCursor() const { return m_shouldShowBlockCursor; }
     void setShouldShowBlockCursor(bool);
 
 private:
diff --git a/Source/core/editing/HTMLInterchange.cpp b/Source/core/editing/HTMLInterchange.cpp
index c63d98c..403ca00 100644
--- a/Source/core/editing/HTMLInterchange.cpp
+++ b/Source/core/editing/HTMLInterchange.cpp
@@ -34,10 +34,10 @@
 
 namespace WebCore {
 
-String convertHTMLTextToInterchangeFormat(const String& in, const Text* node)
+String convertHTMLTextToInterchangeFormat(const String& in, const Text& node)
 {
     // Assume all the text comes from node.
-    if (node->renderer() && node->renderer()->style()->preserveNewline())
+    if (node.renderer() && node.renderer()->style()->preserveNewline())
         return in;
 
     const char convertedSpaceString[] = "<span class=\"" AppleConvertedSpace "\">\xA0</span>";
diff --git a/Source/core/editing/HTMLInterchange.h b/Source/core/editing/HTMLInterchange.h
index b306437..a4d484c 100644
--- a/Source/core/editing/HTMLInterchange.h
+++ b/Source/core/editing/HTMLInterchange.h
@@ -40,7 +40,7 @@
 
 enum EAnnotateForInterchange { DoNotAnnotateForInterchange, AnnotateForInterchange };
 
-String convertHTMLTextToInterchangeFormat(const String&, const Text*);
+String convertHTMLTextToInterchangeFormat(const String&, const Text&);
 
 }
 
diff --git a/Source/core/editing/IndentOutdentCommand.cpp b/Source/core/editing/IndentOutdentCommand.cpp
index f882fe0..ba5cf29 100644
--- a/Source/core/editing/IndentOutdentCommand.cpp
+++ b/Source/core/editing/IndentOutdentCommand.cpp
@@ -28,6 +28,7 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/editing/InsertListCommand.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
@@ -43,10 +44,9 @@
     return node && (node->hasTagName(ulTag) || node->hasTagName(olTag) || node->hasTagName(blockquoteTag));
 }
 
-IndentOutdentCommand::IndentOutdentCommand(Document& document, EIndentType typeOfAction, int marginInPixels)
+IndentOutdentCommand::IndentOutdentCommand(Document& document, EIndentType typeOfAction)
     : ApplyBlockElementCommand(document, blockquoteTag, "margin: 0 0 0 40px; border: none; padding: 0px;")
     , m_typeOfAction(typeOfAction)
-    , m_marginInPixels(marginInPixels)
 {
 }
 
@@ -66,8 +66,8 @@
         return false;
 
     // FIXME: previousElementSibling does not ignore non-rendered content like <span></span>.  Should we?
-    RefPtr<Element> previousList = selectedListItem->previousElementSibling();
-    RefPtr<Element> nextList = selectedListItem->nextElementSibling();
+    RefPtr<Element> previousList = ElementTraversal::previousSibling(*selectedListItem);
+    RefPtr<Element> nextList = ElementTraversal::nextSibling(*selectedListItem);
 
     // We should calculate visible range in list item because inserting new
     // list element will change visibility of list item, e.g. :first-child
diff --git a/Source/core/editing/IndentOutdentCommand.h b/Source/core/editing/IndentOutdentCommand.h
index b90d8ec..2fe5d4f 100644
--- a/Source/core/editing/IndentOutdentCommand.h
+++ b/Source/core/editing/IndentOutdentCommand.h
@@ -31,32 +31,30 @@
 
 namespace WebCore {
 
-class IndentOutdentCommand : public ApplyBlockElementCommand {
+class IndentOutdentCommand FINAL : public ApplyBlockElementCommand {
 public:
     enum EIndentType { Indent, Outdent };
-    static PassRefPtr<IndentOutdentCommand> create(Document& document, EIndentType type, int marginInPixels = 0)
+    static PassRefPtr<IndentOutdentCommand> create(Document& document, EIndentType type)
     {
-        return adoptRef(new IndentOutdentCommand(document, type, marginInPixels));
+        return adoptRef(new IndentOutdentCommand(document, type));
     }
 
-    virtual bool preservesTypingStyle() const { return true; }
+    virtual bool preservesTypingStyle() const OVERRIDE { return true; }
 
 private:
-    IndentOutdentCommand(Document&, EIndentType, int marginInPixels);
+    IndentOutdentCommand(Document&, EIndentType);
 
-    virtual EditAction editingAction() const { return m_typeOfAction == Indent ? EditActionIndent : EditActionOutdent; }
+    virtual EditAction editingAction() const OVERRIDE { return m_typeOfAction == Indent ? EditActionIndent : EditActionOutdent; }
 
-    void indentRegion(const VisiblePosition&, const VisiblePosition&);
     void outdentRegion(const VisiblePosition&, const VisiblePosition&);
     void outdentParagraph();
     bool tryIndentingAsListItem(const Position&, const Position&);
     void indentIntoBlockquote(const Position&, const Position&, RefPtr<Element>&);
 
-    void formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection);
-    void formatRange(const Position& start, const Position& end, const Position& endOfSelection, RefPtr<Element>& blockquoteForNextIndent);
+    virtual void formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection) OVERRIDE;
+    virtual void formatRange(const Position& start, const Position& end, const Position& endOfSelection, RefPtr<Element>& blockquoteForNextIndent) OVERRIDE;
 
     EIndentType m_typeOfAction;
-    int m_marginInPixels;
 };
 
 } // namespace WebCore
diff --git a/Source/core/editing/InputMethodController.cpp b/Source/core/editing/InputMethodController.cpp
index 92eb55a..8e32f93 100644
--- a/Source/core/editing/InputMethodController.cpp
+++ b/Source/core/editing/InputMethodController.cpp
@@ -192,7 +192,15 @@
     // We should send this event before sending a TextEvent as written in Section 6.2.2 and 6.2.3 of
     // the DOM Event specification.
     if (Element* target = m_frame.document()->focusedElement()) {
-        RefPtr<CompositionEvent> event = CompositionEvent::create(EventTypeNames::compositionend, m_frame.domWindow(), text);
+        unsigned baseOffset = m_frame.selection().base().downstream().deprecatedEditingOffset();
+        Vector<CompositionUnderline> underlines;
+        for (size_t i = 0; i < m_customCompositionUnderlines.size(); ++i) {
+            CompositionUnderline underline = m_customCompositionUnderlines[i];
+            underline.startOffset -= baseOffset;
+            underline.endOffset -= baseOffset;
+            underlines.append(underline);
+        }
+        RefPtr<CompositionEvent> event = CompositionEvent::create(EventTypeNames::compositionend, m_frame.domWindow(), text, underlines);
         target->dispatchEvent(event, IGNORE_EXCEPTION);
     }
 
@@ -251,14 +259,14 @@
             // We should send a compositionstart event only when the given text is not empty because this
             // function doesn't create a composition node when the text is empty.
             if (!text.isEmpty()) {
-                target->dispatchEvent(CompositionEvent::create(EventTypeNames::compositionstart, m_frame.domWindow(), m_frame.selectedText()));
-                event = CompositionEvent::create(EventTypeNames::compositionupdate, m_frame.domWindow(), text);
+                target->dispatchEvent(CompositionEvent::create(EventTypeNames::compositionstart, m_frame.domWindow(), m_frame.selectedText(), underlines));
+                event = CompositionEvent::create(EventTypeNames::compositionupdate, m_frame.domWindow(), text, underlines);
             }
         } else {
             if (!text.isEmpty())
-                event = CompositionEvent::create(EventTypeNames::compositionupdate, m_frame.domWindow(), text);
+                event = CompositionEvent::create(EventTypeNames::compositionupdate, m_frame.domWindow(), text, underlines);
             else
-                event = CompositionEvent::create(EventTypeNames::compositionend, m_frame.domWindow(), text);
+                event = CompositionEvent::create(EventTypeNames::compositionend, m_frame.domWindow(), text, underlines);
         }
         if (event.get())
             target->dispatchEvent(event, IGNORE_EXCEPTION);
diff --git a/Source/core/editing/InsertIntoTextNodeCommand.cpp b/Source/core/editing/InsertIntoTextNodeCommand.cpp
index 906274b..43790d9 100644
--- a/Source/core/editing/InsertIntoTextNodeCommand.cpp
+++ b/Source/core/editing/InsertIntoTextNodeCommand.cpp
@@ -29,7 +29,7 @@
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Document.h"
 #include "core/dom/Text.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderText.h"
 
 namespace WebCore {
diff --git a/Source/core/editing/InsertIntoTextNodeCommand.h b/Source/core/editing/InsertIntoTextNodeCommand.h
index 9764aa8..17e0dac 100644
--- a/Source/core/editing/InsertIntoTextNodeCommand.h
+++ b/Source/core/editing/InsertIntoTextNodeCommand.h
@@ -32,7 +32,7 @@
 
 class Text;
 
-class InsertIntoTextNodeCommand : public SimpleEditCommand {
+class InsertIntoTextNodeCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<InsertIntoTextNodeCommand> create(PassRefPtr<Text> node, unsigned offset, const String& text)
     {
diff --git a/Source/core/editing/InsertLineBreakCommand.cpp b/Source/core/editing/InsertLineBreakCommand.cpp
index cb4ad37..6d8cf00 100644
--- a/Source/core/editing/InsertLineBreakCommand.cpp
+++ b/Source/core/editing/InsertLineBreakCommand.cpp
@@ -35,7 +35,6 @@
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/html/HTMLElement.h"
-#include "core/html/HTMLTableElement.h"
 #include "core/frame/Frame.h"
 #include "core/rendering/RenderObject.h"
 
@@ -53,30 +52,6 @@
     return true;
 }
 
-void InsertLineBreakCommand::insertNodeAfterPosition(Node* node, const Position& pos)
-{
-    // Insert the BR after the caret position. In the case the
-    // position is a block, do an append. We don't want to insert
-    // the BR *after* the block.
-    Element* cb = pos.deprecatedNode()->enclosingBlockFlowElement();
-    if (cb == pos.deprecatedNode())
-        appendNode(node, cb);
-    else
-        insertNodeAfter(node, pos.deprecatedNode());
-}
-
-void InsertLineBreakCommand::insertNodeBeforePosition(Node* node, const Position& pos)
-{
-    // Insert the BR after the caret position. In the case the
-    // position is a block, do an append. We don't want to insert
-    // the BR *before* the block.
-    Element* cb = pos.deprecatedNode()->enclosingBlockFlowElement();
-    if (cb == pos.deprecatedNode())
-        appendNode(node, cb);
-    else
-        insertNodeBefore(node, pos.deprecatedNode());
-}
-
 // Whether we should insert a break element or a '\n'.
 bool InsertLineBreakCommand::shouldUseBreakElement(const Position& insertionPos)
 {
@@ -115,7 +90,7 @@
     // FIXME: Need to merge text nodes when inserting just after or before text.
 
     if (isEndOfParagraph(caret) && !lineBreakExistsAtVisiblePosition(caret)) {
-        bool needExtraLineBreak = !pos.deprecatedNode()->hasTagName(hrTag) && !isHTMLTableElement(pos.deprecatedNode());
+        bool needExtraLineBreak = !pos.deprecatedNode()->hasTagName(hrTag) && !pos.deprecatedNode()->hasTagName(tableTag);
 
         insertNodeAt(nodeToInsert.get(), pos);
 
diff --git a/Source/core/editing/InsertLineBreakCommand.h b/Source/core/editing/InsertLineBreakCommand.h
index 6eee0e0..1d84f17 100644
--- a/Source/core/editing/InsertLineBreakCommand.h
+++ b/Source/core/editing/InsertLineBreakCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class InsertLineBreakCommand : public CompositeEditCommand {
+class InsertLineBreakCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<InsertLineBreakCommand> create(Document& document)
     {
@@ -40,12 +40,10 @@
 private:
     explicit InsertLineBreakCommand(Document&);
 
-    virtual void doApply();
+    virtual void doApply() OVERRIDE;
 
-    virtual bool preservesTypingStyle() const;
+    virtual bool preservesTypingStyle() const OVERRIDE;
 
-    void insertNodeAfterPosition(Node*, const Position&);
-    void insertNodeBeforePosition(Node*, const Position&);
     bool shouldUseBreakElement(const Position&);
 };
 
diff --git a/Source/core/editing/InsertListCommand.cpp b/Source/core/editing/InsertListCommand.cpp
index 9a70258..e5bedb0 100644
--- a/Source/core/editing/InsertListCommand.cpp
+++ b/Source/core/editing/InsertListCommand.cpp
@@ -29,6 +29,7 @@
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/editing/TextIterator.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
@@ -46,13 +47,6 @@
     return listChild;
 }
 
-PassRefPtr<HTMLElement> InsertListCommand::insertList(Document& document, Type type)
-{
-    RefPtr<InsertListCommand> insertCommand = create(document, type);
-    insertCommand->apply();
-    return insertCommand->m_listElement;
-}
-
 HTMLElement* InsertListCommand::fixOrphanedListChild(Node* node)
 {
     RefPtr<HTMLElement> listElement = createUnorderedListElement(document());
@@ -66,14 +60,18 @@
 PassRefPtr<HTMLElement> InsertListCommand::mergeWithNeighboringLists(PassRefPtr<HTMLElement> passedList)
 {
     RefPtr<HTMLElement> list = passedList;
-    Element* previousList = list->previousElementSibling();
+    Element* previousList = ElementTraversal::previousSibling(*list);
     if (canMergeLists(previousList, list.get()))
         mergeIdenticalElements(previousList, list);
 
-    if (!list || !list->nextElementSibling() || !list->nextElementSibling()->isHTMLElement())
+    if (!list)
+        return 0;
+
+    Element* nextSibling = ElementTraversal::nextSibling(*list);
+    if (!nextSibling || !nextSibling->isHTMLElement())
         return list.release();
 
-    RefPtr<HTMLElement> nextList = toHTMLElement(list->nextElementSibling());
+    RefPtr<HTMLElement> nextList = toHTMLElement(nextSibling);
     if (canMergeLists(list.get(), nextList.get())) {
         mergeIdenticalElements(list, nextList);
         return nextList.release();
@@ -134,6 +132,8 @@
         VisiblePosition startOfLastParagraph = startOfParagraph(endOfSelection, CanSkipOverEditingBoundary);
 
         if (startOfParagraph(startOfSelection, CanSkipOverEditingBoundary) != startOfLastParagraph) {
+            RefPtr<ContainerNode> scope;
+            int indexForEndOfSelection = indexForVisiblePosition(endOfSelection, scope);
             bool forceCreateList = !selectionHasListOfType(selection, listTag);
 
             RefPtr<Range> currentSelection = endingSelection().firstRange();
@@ -153,8 +153,6 @@
                 // FIXME: This is an inefficient way to keep selection alive because indexForVisiblePosition walks from
                 // the beginning of the document to the endOfSelection everytime this code is executed.
                 // But not using index is hard because there are so many ways we can lose selection inside doApplyForSingleParagraph.
-                RefPtr<ContainerNode> scope;
-                int indexForEndOfSelection = indexForVisiblePosition(endOfSelection, scope);
                 doApplyForSingleParagraph(forceCreateList, listTag, currentSelection.get());
                 if (endOfSelection.isNull() || endOfSelection.isOrphan() || startOfLastParagraph.isNull() || startOfLastParagraph.isOrphan()) {
                     endOfSelection = visiblePositionForIndex(indexForEndOfSelection, scope.get());
@@ -178,7 +176,11 @@
             setEndingSelection(endOfSelection);
             doApplyForSingleParagraph(forceCreateList, listTag, currentSelection.get());
             // Fetch the end of the selection, for the reason mentioned above.
-            endOfSelection = endingSelection().visibleEnd();
+            if (endOfSelection.isNull() || endOfSelection.isOrphan()) {
+                endOfSelection = visiblePositionForIndex(indexForEndOfSelection, scope.get());
+                if (endOfSelection.isNull())
+                    return;
+            }
             setEndingSelection(VisibleSelection(startOfSelection, endOfSelection, endingSelection().isDirectional()));
             return;
         }
diff --git a/Source/core/editing/InsertListCommand.h b/Source/core/editing/InsertListCommand.h
index 80933b2..fe1a5d5 100644
--- a/Source/core/editing/InsertListCommand.h
+++ b/Source/core/editing/InsertListCommand.h
@@ -32,7 +32,7 @@
 
 class HTMLElement;
 
-class InsertListCommand : public CompositeEditCommand {
+class InsertListCommand FINAL : public CompositeEditCommand {
 public:
     enum Type { OrderedList, UnorderedList };
 
@@ -41,15 +41,13 @@
         return adoptRef(new InsertListCommand(document, listType));
     }
 
-    static PassRefPtr<HTMLElement> insertList(Document&, Type);
-
-    virtual bool preservesTypingStyle() const { return true; }
+    virtual bool preservesTypingStyle() const OVERRIDE { return true; }
 
 private:
     InsertListCommand(Document&, Type);
 
-    virtual void doApply();
-    virtual EditAction editingAction() const { return EditActionInsertList; }
+    virtual void doApply() OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE { return EditActionInsertList; }
 
     HTMLElement* fixOrphanedListChild(Node*);
     bool selectionHasListOfType(const VisibleSelection& selection, const QualifiedName&);
diff --git a/Source/core/editing/InsertNodeBeforeCommand.h b/Source/core/editing/InsertNodeBeforeCommand.h
index 6fc3b3c..bdd1abd 100644
--- a/Source/core/editing/InsertNodeBeforeCommand.h
+++ b/Source/core/editing/InsertNodeBeforeCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class InsertNodeBeforeCommand : public SimpleEditCommand {
+class InsertNodeBeforeCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<InsertNodeBeforeCommand> create(PassRefPtr<Node> childToInsert, PassRefPtr<Node> childToInsertBefore,
         ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
diff --git a/Source/core/editing/InsertParagraphSeparatorCommand.h b/Source/core/editing/InsertParagraphSeparatorCommand.h
index 57f32b3..075e849 100644
--- a/Source/core/editing/InsertParagraphSeparatorCommand.h
+++ b/Source/core/editing/InsertParagraphSeparatorCommand.h
@@ -32,7 +32,7 @@
 
 class EditingStyle;
 
-class InsertParagraphSeparatorCommand : public CompositeEditCommand {
+class InsertParagraphSeparatorCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<InsertParagraphSeparatorCommand> create(Document& document, bool useDefaultParagraphElement = false, bool pasteBlockqutoeIntoUnquotedArea = false)
     {
@@ -42,7 +42,7 @@
 private:
     InsertParagraphSeparatorCommand(Document&, bool useDefaultParagraphElement, bool pasteBlockqutoeIntoUnquotedArea);
 
-    virtual void doApply();
+    virtual void doApply() OVERRIDE;
 
     void calculateStyleBeforeInsertion(const Position&);
     void applyStyleAfterInsertion(Node* originalEnclosingBlock);
@@ -51,7 +51,7 @@
 
     bool shouldUseDefaultParagraphElement(Node*) const;
 
-    virtual bool preservesTypingStyle() const;
+    virtual bool preservesTypingStyle() const OVERRIDE;
 
     RefPtr<EditingStyle> m_style;
 
diff --git a/Source/core/editing/InsertTextCommand.cpp b/Source/core/editing/InsertTextCommand.cpp
index 8a48940..213fc8d 100644
--- a/Source/core/editing/InsertTextCommand.cpp
+++ b/Source/core/editing/InsertTextCommand.cpp
@@ -44,15 +44,6 @@
 {
 }
 
-InsertTextCommand::InsertTextCommand(Document& document, const String& text, PassRefPtr<TextInsertionMarkerSupplier> markerSupplier)
-    : CompositeEditCommand(document)
-    , m_text(text)
-    , m_selectInsertedText(false)
-    , m_rebalanceType(RebalanceLeadingAndTrailingWhitespaces)
-    , m_markerSupplier(markerSupplier)
-{
-}
-
 Position InsertTextCommand::positionInsideTextNode(const Position& p)
 {
     Position pos = p;
@@ -139,7 +130,7 @@
     if (endingSelection().isRange()) {
         if (performTrivialReplace(m_text, m_selectInsertedText))
             return;
-        deleteSelection(false, true, true, false, false);
+        deleteSelection(false, true, false, false);
         // deleteSelection eventually makes a new endingSelection out of a Position. If that Position doesn't have
         // a renderer (e.g. it is on a <frameset> in the DOM), the VisibleSelection cannot be canonicalized to
         // anything other than NoSelection. The rest of this function requires a real endingSelection, so bail out.
@@ -202,8 +193,6 @@
 
         insertTextIntoNode(textNode, offset, m_text);
         endPosition = Position(textNode, offset + m_text.length());
-        if (m_markerSupplier)
-            m_markerSupplier->addMarkersToTextNode(textNode.get(), offset, m_text);
 
         if (m_rebalanceType == RebalanceLeadingAndTrailingWhitespaces) {
             // The insertion may require adjusting adjacent whitespace, if it is present.
diff --git a/Source/core/editing/InsertTextCommand.h b/Source/core/editing/InsertTextCommand.h
index 10c8d80..6356ff8 100644
--- a/Source/core/editing/InsertTextCommand.h
+++ b/Source/core/editing/InsertTextCommand.h
@@ -30,18 +30,7 @@
 
 namespace WebCore {
 
-class DocumentMarkerController;
-class Text;
-
-class TextInsertionMarkerSupplier : public RefCounted<TextInsertionMarkerSupplier> {
-public:
-    virtual ~TextInsertionMarkerSupplier() { }
-    virtual void addMarkersToTextNode(Text*, unsigned offsetOfInsertion, const String& textInserted) = 0;
-protected:
-    TextInsertionMarkerSupplier() { }
-};
-
-class InsertTextCommand : public CompositeEditCommand {
+class InsertTextCommand FINAL : public CompositeEditCommand {
 public:
     enum RebalanceType {
         RebalanceLeadingAndTrailingWhitespaces,
@@ -54,19 +43,10 @@
         return adoptRef(new InsertTextCommand(document, text, selectInsertedText, rebalanceType));
     }
 
-    static PassRefPtr<InsertTextCommand> createWithMarkerSupplier(Document& document, const String& text, PassRefPtr<TextInsertionMarkerSupplier> markerSupplier)
-    {
-        return adoptRef(new InsertTextCommand(document, text, markerSupplier));
-    }
-
 private:
-
     InsertTextCommand(Document&, const String& text, bool selectInsertedText, RebalanceType);
-    InsertTextCommand(Document&, const String& text, PassRefPtr<TextInsertionMarkerSupplier>);
 
-    void deleteCharacter();
-
-    virtual void doApply();
+    virtual void doApply() OVERRIDE;
 
     Position positionInsideTextNode(const Position&);
     Position insertTab(const Position&);
@@ -80,7 +60,6 @@
     String m_text;
     bool m_selectInsertedText;
     RebalanceType m_rebalanceType;
-    RefPtr<TextInsertionMarkerSupplier> m_markerSupplier;
 };
 
 } // namespace WebCore
diff --git a/Source/core/editing/MarkupAccumulator.cpp b/Source/core/editing/MarkupAccumulator.cpp
index 9d5b975..044e9ee 100644
--- a/Source/core/editing/MarkupAccumulator.cpp
+++ b/Source/core/editing/MarkupAccumulator.cpp
@@ -46,13 +46,37 @@
 
 using namespace HTMLNames;
 
+struct EntityDescription {
+    UChar entity;
+    const CString& reference;
+    EntityMask mask;
+};
+
+template <typename CharType>
+static inline void appendCharactersReplacingEntitiesInternal(StringBuilder& result, CharType* text, unsigned length, const EntityDescription entityMaps[], unsigned entityMapsCount, EntityMask entityMask)
+{
+    unsigned positionAfterLastEntity = 0;
+    for (unsigned i = 0; i < length; ++i) {
+        for (unsigned entityIndex = 0; entityIndex < entityMapsCount; ++entityIndex) {
+            if (text[i] == entityMaps[entityIndex].entity && entityMaps[entityIndex].mask & entityMask) {
+                result.append(text + positionAfterLastEntity, i - positionAfterLastEntity);
+                const CString& replacement = entityMaps[entityIndex].reference;
+                result.append(replacement.data(), replacement.length());
+                positionAfterLastEntity = i + 1;
+                break;
+            }
+        }
+    }
+    result.append(text + positionAfterLastEntity, length - positionAfterLastEntity);
+}
+
 void MarkupAccumulator::appendCharactersReplacingEntities(StringBuilder& result, const String& source, unsigned offset, unsigned length, EntityMask entityMask)
 {
-    DEFINE_STATIC_LOCAL(const String, ampReference, ("&amp;"));
-    DEFINE_STATIC_LOCAL(const String, ltReference, ("&lt;"));
-    DEFINE_STATIC_LOCAL(const String, gtReference, ("&gt;"));
-    DEFINE_STATIC_LOCAL(const String, quotReference, ("&quot;"));
-    DEFINE_STATIC_LOCAL(const String, nbspReference, ("&nbsp;"));
+    DEFINE_STATIC_LOCAL(const CString, ampReference, ("&amp;"));
+    DEFINE_STATIC_LOCAL(const CString, ltReference, ("&lt;"));
+    DEFINE_STATIC_LOCAL(const CString, gtReference, ("&gt;"));
+    DEFINE_STATIC_LOCAL(const CString, quotReference, ("&quot;"));
+    DEFINE_STATIC_LOCAL(const CString, nbspReference, ("&nbsp;"));
 
     static const EntityDescription entityMaps[] = {
         { '&', ampReference, EntityAmp },
@@ -66,38 +90,10 @@
         return;
 
     ASSERT(offset + length <= source.length());
-
-    if (source.is8Bit()) {
-        const LChar* text = source.characters8() + offset;
-
-        size_t positionAfterLastEntity = 0;
-        for (size_t i = 0; i < length; ++i) {
-            for (size_t entityIndex = 0; entityIndex < WTF_ARRAY_LENGTH(entityMaps); ++entityIndex) {
-                if (text[i] == entityMaps[entityIndex].entity && entityMaps[entityIndex].mask & entityMask) {
-                    result.append(text + positionAfterLastEntity, i - positionAfterLastEntity);
-                    result.append(entityMaps[entityIndex].reference);
-                    positionAfterLastEntity = i + 1;
-                    break;
-                }
-            }
-        }
-        result.append(text + positionAfterLastEntity, length - positionAfterLastEntity);
-    } else {
-        const UChar* text = source.characters16() + offset;
-
-        size_t positionAfterLastEntity = 0;
-        for (size_t i = 0; i < length; ++i) {
-            for (size_t entityIndex = 0; entityIndex < WTF_ARRAY_LENGTH(entityMaps); ++entityIndex) {
-                if (text[i] == entityMaps[entityIndex].entity && entityMaps[entityIndex].mask & entityMask) {
-                    result.append(text + positionAfterLastEntity, i - positionAfterLastEntity);
-                    result.append(entityMaps[entityIndex].reference);
-                    positionAfterLastEntity = i + 1;
-                    break;
-                }
-            }
-        }
-        result.append(text + positionAfterLastEntity, length - positionAfterLastEntity);
-    }
+    if (source.is8Bit())
+        appendCharactersReplacingEntitiesInternal(result, source.characters8() + offset, length, entityMaps, WTF_ARRAY_LENGTH(entityMaps), entityMask);
+    else
+        appendCharactersReplacingEntitiesInternal(result, source.characters16() + offset, length, entityMaps, WTF_ARRAY_LENGTH(entityMaps), entityMask);
 }
 
 MarkupAccumulator::MarkupAccumulator(Vector<Node*>* nodes, EAbsoluteURLs resolveUrlsMethod, const Range* range)
@@ -111,22 +107,17 @@
 {
 }
 
-String MarkupAccumulator::serializeNodes(Node* targetNode, EChildrenOnly childrenOnly)
-{
-    return serializeNodes(targetNode, childrenOnly, 0);
-}
-
-String MarkupAccumulator::serializeNodes(Node* targetNode, EChildrenOnly childrenOnly, Vector<QualifiedName>* tagNamesToSkip)
+String MarkupAccumulator::serializeNodes(Node& targetNode, EChildrenOnly childrenOnly, Vector<QualifiedName>* tagNamesToSkip)
 {
     serializeNodesWithNamespaces(targetNode, childrenOnly, 0, tagNamesToSkip);
     return m_markup.toString();
 }
 
-void MarkupAccumulator::serializeNodesWithNamespaces(Node* targetNode, EChildrenOnly childrenOnly, const Namespaces* namespaces, Vector<QualifiedName>* tagNamesToSkip)
+void MarkupAccumulator::serializeNodesWithNamespaces(Node& targetNode, EChildrenOnly childrenOnly, const Namespaces* namespaces, Vector<QualifiedName>* tagNamesToSkip)
 {
     if (tagNamesToSkip) {
         for (size_t i = 0; i < tagNamesToSkip->size(); ++i) {
-            if (targetNode->hasTagName(tagNamesToSkip->at(i)))
+            if (targetNode.hasTagName(tagNamesToSkip->at(i)))
                 return;
         }
     }
@@ -138,25 +129,25 @@
     if (!childrenOnly)
         appendStartTag(targetNode, &namespaceHash);
 
-    if (!(targetNode->document().isHTMLDocument() && elementCannotHaveEndTag(targetNode))) {
-        Node* current = targetNode->hasTagName(templateTag) ? toHTMLTemplateElement(targetNode)->content()->firstChild() : targetNode->firstChild();
+    if (!(targetNode.document().isHTMLDocument() && elementCannotHaveEndTag(targetNode))) {
+        Node* current = targetNode.hasTagName(templateTag) ? toHTMLTemplateElement(targetNode).content()->firstChild() : targetNode.firstChild();
         for ( ; current; current = current->nextSibling())
-            serializeNodesWithNamespaces(current, IncludeNode, &namespaceHash, tagNamesToSkip);
+            serializeNodesWithNamespaces(*current, IncludeNode, &namespaceHash, tagNamesToSkip);
     }
 
     if (!childrenOnly)
         appendEndTag(targetNode);
 }
 
-String MarkupAccumulator::resolveURLIfNeeded(const Element* element, const String& urlString) const
+String MarkupAccumulator::resolveURLIfNeeded(const Element& element, const String& urlString) const
 {
     switch (m_resolveURLsMethod) {
     case ResolveAllURLs:
-        return element->document().completeURL(urlString).string();
+        return element.document().completeURL(urlString).string();
 
     case ResolveNonLocalURLs:
-        if (!element->document().url().isLocalFile())
-            return element->document().completeURL(urlString).string();
+        if (!element.document().url().isLocalFile())
+            return element.document().completeURL(urlString).string();
         break;
 
     case DoNotResolveURLs:
@@ -170,14 +161,14 @@
     m_markup.append(string);
 }
 
-void MarkupAccumulator::appendStartTag(Node* node, Namespaces* namespaces)
+void MarkupAccumulator::appendStartTag(Node& node, Namespaces* namespaces)
 {
     appendStartMarkup(m_markup, node, namespaces);
     if (m_nodes)
-        m_nodes->append(node);
+        m_nodes->append(&node);
 }
 
-void MarkupAccumulator::appendEndTag(Node* node)
+void MarkupAccumulator::appendEndTag(const Node& node)
 {
     appendEndMarkup(m_markup, node);
 }
@@ -201,13 +192,13 @@
         documentIsHTML ? EntityMaskInHTMLAttributeValue : EntityMaskInAttributeValue);
 }
 
-void MarkupAccumulator::appendCustomAttributes(StringBuilder&, Element*, Namespaces*)
+void MarkupAccumulator::appendCustomAttributes(StringBuilder&, const Element&, Namespaces*)
 {
 }
 
-void MarkupAccumulator::appendQuotedURLAttributeValue(StringBuilder& result, const Element* element, const Attribute& attribute)
+void MarkupAccumulator::appendQuotedURLAttributeValue(StringBuilder& result, const Element& element, const Attribute& attribute)
 {
-    ASSERT(element->isURLAttribute(attribute));
+    ASSERT(element.isURLAttribute(attribute));
     const String resolvedURLString = resolveURLIfNeeded(element, attribute.value());
     UChar quoteChar = '"';
     String strippedURLString = resolvedURLString.stripWhiteSpace();
@@ -231,33 +222,15 @@
     result.append(quoteChar);
 }
 
-void MarkupAccumulator::appendNodeValue(StringBuilder& result, const Node* node, const Range* range, EntityMask entityMask)
-{
-    const String str = node->nodeValue();
-    unsigned length = str.length();
-    unsigned start = 0;
-
-    if (range) {
-        if (node == range->endContainer())
-            length = range->endOffset();
-        if (node == range->startContainer()) {
-            start = range->startOffset();
-            length -= start;
-        }
-    }
-
-    appendCharactersReplacingEntities(result, str, start, length, entityMask);
-}
-
-bool MarkupAccumulator::shouldAddNamespaceElement(const Element* element)
+bool MarkupAccumulator::shouldAddNamespaceElement(const Element& element)
 {
     // Don't add namespace attribute if it is already defined for this elem.
-    const AtomicString& prefix = element->prefix();
+    const AtomicString& prefix = element.prefix();
     if (prefix.isEmpty())
-        return !element->hasAttribute(xmlnsAtom);
+        return !element.hasAttribute(xmlnsAtom);
 
     DEFINE_STATIC_LOCAL(String, xmlnsWithColon, ("xmlns:"));
-    return !element->hasAttribute(xmlnsWithColon + prefix);
+    return !element.hasAttribute(xmlnsWithColon + prefix);
 }
 
 bool MarkupAccumulator::shouldAddNamespaceAttribute(const Attribute& attribute, Namespaces& namespaces)
@@ -294,30 +267,41 @@
             result.append(prefix);
         }
 
-        result.append('=');
-        result.append('"');
+        result.appendLiteral("=\"");
         appendAttributeValue(result, namespaceURI, false);
         result.append('"');
     }
 }
 
-EntityMask MarkupAccumulator::entityMaskForText(Text* text) const
+EntityMask MarkupAccumulator::entityMaskForText(const Text& text) const
 {
-    if (!text->document().isHTMLDocument())
+    if (!text.document().isHTMLDocument())
         return EntityMaskInPCDATA;
 
     const QualifiedName* parentName = 0;
-    if (text->parentElement())
-        parentName = &(text->parentElement())->tagQName();
+    if (text.parentElement())
+        parentName = &(text.parentElement())->tagQName();
 
     if (parentName && (*parentName == scriptTag || *parentName == styleTag || *parentName == xmpTag))
         return EntityMaskInCDATA;
     return EntityMaskInHTMLPCDATA;
 }
 
-void MarkupAccumulator::appendText(StringBuilder& result, Text* text)
+void MarkupAccumulator::appendText(StringBuilder& result, Text& text)
 {
-    appendNodeValue(result, text, m_range, entityMaskForText(text));
+    const String& str = text.data();
+    unsigned length = str.length();
+    unsigned start = 0;
+
+    if (m_range) {
+        if (text == m_range->endContainer())
+            length = m_range->endOffset();
+        if (text == m_range->startContainer()) {
+            start = m_range->startOffset();
+            length -= start;
+        }
+    }
+    appendCharactersReplacingEntities(result, str, start, length, entityMaskForText(text));
 }
 
 void MarkupAccumulator::appendComment(StringBuilder& result, const String& comment)
@@ -328,21 +312,21 @@
     result.appendLiteral("-->");
 }
 
-void MarkupAccumulator::appendXMLDeclaration(StringBuilder& result, const Document* document)
+void MarkupAccumulator::appendXMLDeclaration(StringBuilder& result, const Document& document)
 {
-    if (!document->hasXMLDeclaration())
+    if (!document.hasXMLDeclaration())
         return;
 
     result.appendLiteral("<?xml version=\"");
-    result.append(document->xmlVersion());
-    const String& encoding = document->xmlEncoding();
+    result.append(document.xmlVersion());
+    const String& encoding = document.xmlEncoding();
     if (!encoding.isEmpty()) {
         result.appendLiteral("\" encoding=\"");
         result.append(encoding);
     }
-    if (document->xmlStandaloneStatus() != Document::StandaloneUnspecified) {
+    if (document.xmlStandaloneStatus() != Document::StandaloneUnspecified) {
         result.appendLiteral("\" standalone=\"");
-        if (document->xmlStandalone())
+        if (document.xmlStandalone())
             result.appendLiteral("yes");
         else
             result.appendLiteral("no");
@@ -351,32 +335,30 @@
     result.appendLiteral("\"?>");
 }
 
-void MarkupAccumulator::appendDocumentType(StringBuilder& result, const DocumentType* n)
+void MarkupAccumulator::appendDocumentType(StringBuilder& result, const DocumentType& n)
 {
-    if (n->name().isEmpty())
+    if (n.name().isEmpty())
         return;
 
     result.appendLiteral("<!DOCTYPE ");
-    result.append(n->name());
-    if (!n->publicId().isEmpty()) {
+    result.append(n.name());
+    if (!n.publicId().isEmpty()) {
         result.appendLiteral(" PUBLIC \"");
-        result.append(n->publicId());
+        result.append(n.publicId());
         result.append('"');
-        if (!n->systemId().isEmpty()) {
-            result.append(' ');
-            result.append('"');
-            result.append(n->systemId());
+        if (!n.systemId().isEmpty()) {
+            result.appendLiteral(" \"");
+            result.append(n.systemId());
             result.append('"');
         }
-    } else if (!n->systemId().isEmpty()) {
+    } else if (!n.systemId().isEmpty()) {
         result.appendLiteral(" SYSTEM \"");
-        result.append(n->systemId());
+        result.append(n.systemId());
         result.append('"');
     }
-    if (!n->internalSubset().isEmpty()) {
-        result.append(' ');
-        result.append('[');
-        result.append(n->internalSubset());
+    if (!n.internalSubset().isEmpty()) {
+        result.appendLiteral(" [");
+        result.append(n.internalSubset());
         result.append(']');
     }
     result.append('>');
@@ -385,23 +367,21 @@
 void MarkupAccumulator::appendProcessingInstruction(StringBuilder& result, const String& target, const String& data)
 {
     // FIXME: PI data is not escaped, but XMLSerializer (and possibly other callers) this should raise an exception if it includes "?>".
-    result.append('<');
-    result.append('?');
+    result.appendLiteral("<?");
     result.append(target);
     result.append(' ');
     result.append(data);
-    result.append('?');
-    result.append('>');
+    result.appendLiteral("?>");
 }
 
-void MarkupAccumulator::appendElement(StringBuilder& result, Element* element, Namespaces* namespaces)
+void MarkupAccumulator::appendElement(StringBuilder& result, Element& element, Namespaces* namespaces)
 {
     appendOpenTag(result, element, namespaces);
 
-    if (element->hasAttributes()) {
-        unsigned length = element->attributeCount();
+    if (element.hasAttributes()) {
+        unsigned length = element.attributeCount();
         for (unsigned int i = 0; i < length; i++)
-            appendAttribute(result, element, *element->attributeItem(i), namespaces);
+            appendAttribute(result, element, *element.attributeItem(i), namespaces);
     }
 
     // Give an opportunity to subclasses to add their own attributes.
@@ -410,18 +390,23 @@
     appendCloseTag(result, element);
 }
 
-void MarkupAccumulator::appendOpenTag(StringBuilder& result, Element* element, Namespaces* namespaces)
+static String nodeNamePreservingCase(const Element& element)
 {
-    result.append('<');
-    result.append(element->nodeNamePreservingCase());
-    if (!element->document().isHTMLDocument() && namespaces && shouldAddNamespaceElement(element))
-        appendNamespace(result, element->prefix(), element->namespaceURI(), *namespaces);
+    return element.tagQName().toString();
 }
 
-void MarkupAccumulator::appendCloseTag(StringBuilder& result, Element* element)
+void MarkupAccumulator::appendOpenTag(StringBuilder& result, const Element& element, Namespaces* namespaces)
+{
+    result.append('<');
+    result.append(nodeNamePreservingCase(element));
+    if (!element.document().isHTMLDocument() && namespaces && shouldAddNamespaceElement(element))
+        appendNamespace(result, element.prefix(), element.namespaceURI(), *namespaces);
+}
+
+void MarkupAccumulator::appendCloseTag(StringBuilder& result, const Element& element)
 {
     if (shouldSelfClose(element)) {
-        if (element->isHTMLElement())
+        if (element.isHTMLElement())
             result.append(' '); // XHTML 1.0 <-> HTML compatibility.
         result.append('/');
     }
@@ -435,9 +420,9 @@
         || attribute.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
 }
 
-void MarkupAccumulator::appendAttribute(StringBuilder& result, Element* element, const Attribute& attribute, Namespaces* namespaces)
+void MarkupAccumulator::appendAttribute(StringBuilder& result, const Element& element, const Attribute& attribute, Namespaces* namespaces)
 {
-    bool documentIsHTML = element->document().isHTMLDocument();
+    bool documentIsHTML = element.document().isHTMLDocument();
 
     result.append(' ');
 
@@ -460,7 +445,7 @@
 
     result.append('=');
 
-    if (element->isURLAttribute(attribute))
+    if (element.isURLAttribute(attribute))
         appendQuotedURLAttributeValue(result, element, attribute);
     else {
         result.append('"');
@@ -480,14 +465,14 @@
     result.appendLiteral("]]>");
 }
 
-void MarkupAccumulator::appendStartMarkup(StringBuilder& result, const Node* node, Namespaces* namespaces)
+void MarkupAccumulator::appendStartMarkup(StringBuilder& result, Node& node, Namespaces* namespaces)
 {
-    switch (node->nodeType()) {
+    switch (node.nodeType()) {
     case Node::TEXT_NODE:
-        appendText(result, toText(const_cast<Node*>(node)));
+        appendText(result, toText(node));
         break;
     case Node::COMMENT_NODE:
-        appendComment(result, toComment(node)->data());
+        appendComment(result, toComment(node).data());
         break;
     case Node::DOCUMENT_NODE:
         appendXMLDeclaration(result, toDocument(node));
@@ -498,18 +483,15 @@
         appendDocumentType(result, toDocumentType(node));
         break;
     case Node::PROCESSING_INSTRUCTION_NODE:
-        appendProcessingInstruction(result, toProcessingInstruction(node)->target(), toProcessingInstruction(node)->data());
+        appendProcessingInstruction(result, toProcessingInstruction(node).target(), toProcessingInstruction(node).data());
         break;
     case Node::ELEMENT_NODE:
-        appendElement(result, toElement(const_cast<Node*>(node)), namespaces);
+        appendElement(result, toElement(node), namespaces);
         break;
     case Node::CDATA_SECTION_NODE:
-        appendCDATASection(result, toCDATASection(node)->data());
+        appendCDATASection(result, toCDATASection(node).data());
         break;
     case Node::ATTRIBUTE_NODE:
-    case Node::ENTITY_NODE:
-    case Node::NOTATION_NODE:
-    case Node::XPATH_NAMESPACE_NODE:
         ASSERT_NOT_REACHED();
         break;
     }
@@ -520,37 +502,36 @@
 // 2. Elements w/ children never self-close because they use a separate end tag.
 // 3. HTML elements which do not have a "forbidden" end tag will close with a separate end tag.
 // 4. Other elements self-close.
-bool MarkupAccumulator::shouldSelfClose(const Node* node)
+bool MarkupAccumulator::shouldSelfClose(const Node& node)
 {
-    if (node->document().isHTMLDocument())
+    if (node.document().isHTMLDocument())
         return false;
-    if (node->hasChildNodes())
+    if (node.hasChildNodes())
         return false;
-    if (node->isHTMLElement() && !elementCannotHaveEndTag(node))
+    if (node.isHTMLElement() && !elementCannotHaveEndTag(node))
         return false;
     return true;
 }
 
-bool MarkupAccumulator::elementCannotHaveEndTag(const Node* node)
+bool MarkupAccumulator::elementCannotHaveEndTag(const Node& node)
 {
-    if (!node->isHTMLElement())
+    if (!node.isHTMLElement())
         return false;
 
     // FIXME: ieForbidsInsertHTML may not be the right function to call here
     // ieForbidsInsertHTML is used to disallow setting innerHTML/outerHTML
     // or createContextualFragment.  It does not necessarily align with
     // which elements should be serialized w/o end tags.
-    return toHTMLElement(node)->ieForbidsInsertHTML();
+    return toHTMLElement(node).ieForbidsInsertHTML();
 }
 
-void MarkupAccumulator::appendEndMarkup(StringBuilder& result, const Node* node)
+void MarkupAccumulator::appendEndMarkup(StringBuilder& result, const Node& node)
 {
-    if (!node->isElementNode() || shouldSelfClose(node) || (!node->hasChildNodes() && elementCannotHaveEndTag(node)))
+    if (!node.isElementNode() || shouldSelfClose(node) || (!node.hasChildNodes() && elementCannotHaveEndTag(node)))
         return;
 
-    result.append('<');
-    result.append('/');
-    result.append(toElement(node)->nodeNamePreservingCase());
+    result.appendLiteral("</");
+    result.append(nodeNamePreservingCase(toElement(node)));
     result.append('>');
 }
 
diff --git a/Source/core/editing/MarkupAccumulator.h b/Source/core/editing/MarkupAccumulator.h
index a126567..f14d6ed 100644
--- a/Source/core/editing/MarkupAccumulator.h
+++ b/Source/core/editing/MarkupAccumulator.h
@@ -53,64 +53,57 @@
     EntityMaskInCDATA = 0,
     EntityMaskInPCDATA = EntityAmp | EntityLt | EntityGt,
     EntityMaskInHTMLPCDATA = EntityMaskInPCDATA | EntityNbsp,
-    EntityMaskInAttributeValue = EntityAmp | EntityLt | EntityGt | EntityQuot,
-    EntityMaskInHTMLAttributeValue = EntityMaskInAttributeValue | EntityNbsp,
+    EntityMaskInAttributeValue = EntityAmp | EntityQuot | EntityLt | EntityGt,
+    EntityMaskInHTMLAttributeValue = EntityAmp | EntityQuot | EntityNbsp,
 };
 
-struct EntityDescription {
-    UChar entity;
-    const String& reference;
-    EntityMask mask;
-};
-
-// FIXME: Noncopyable?
 class MarkupAccumulator {
+    WTF_MAKE_NONCOPYABLE(MarkupAccumulator);
+
 public:
     MarkupAccumulator(Vector<Node*>*, EAbsoluteURLs, const Range* = 0);
     virtual ~MarkupAccumulator();
 
-    String serializeNodes(Node* targetNode, EChildrenOnly);
-    String serializeNodes(Node* targetNode, EChildrenOnly, Vector<QualifiedName>* tagNamesToSkip);
+    String serializeNodes(Node& targetNode, EChildrenOnly, Vector<QualifiedName>* tagNamesToSkip = 0);
 
     static void appendComment(StringBuilder&, const String&);
 
     static void appendCharactersReplacingEntities(StringBuilder&, const String&, unsigned, unsigned, EntityMask);
 
 protected:
-    virtual void appendString(const String&);
-    void appendStartTag(Node*, Namespaces* = 0);
-    virtual void appendEndTag(Node*);
+    void appendString(const String&);
+    void appendStartTag(Node&, Namespaces* = 0);
+    virtual void appendEndTag(const Node&);
     static size_t totalLength(const Vector<String>&);
     size_t length() const { return m_markup.length(); }
     void concatenateMarkup(StringBuilder&);
     void appendAttributeValue(StringBuilder&, const String&, bool);
-    virtual void appendCustomAttributes(StringBuilder&, Element*, Namespaces*);
-    void appendNodeValue(StringBuilder&, const Node*, const Range*, EntityMask);
-    bool shouldAddNamespaceElement(const Element*);
+    virtual void appendCustomAttributes(StringBuilder&, const Element&, Namespaces*);
+    bool shouldAddNamespaceElement(const Element&);
     bool shouldAddNamespaceAttribute(const Attribute&, Namespaces&);
     void appendNamespace(StringBuilder&, const AtomicString& prefix, const AtomicString& namespaceURI, Namespaces&);
-    EntityMask entityMaskForText(Text*) const;
-    virtual void appendText(StringBuilder&, Text*);
-    void appendXMLDeclaration(StringBuilder&, const Document*);
-    void appendDocumentType(StringBuilder&, const DocumentType*);
+    EntityMask entityMaskForText(const Text&) const;
+    virtual void appendText(StringBuilder&, Text&);
+    void appendXMLDeclaration(StringBuilder&, const Document&);
+    void appendDocumentType(StringBuilder&, const DocumentType&);
     void appendProcessingInstruction(StringBuilder&, const String& target, const String& data);
-    virtual void appendElement(StringBuilder&, Element*, Namespaces*);
-    void appendOpenTag(StringBuilder&, Element*, Namespaces*);
-    void appendCloseTag(StringBuilder&, Element*);
-    void appendAttribute(StringBuilder&, Element*, const Attribute&, Namespaces*);
+    virtual void appendElement(StringBuilder&, Element&, Namespaces*);
+    void appendOpenTag(StringBuilder&, const Element&, Namespaces*);
+    void appendCloseTag(StringBuilder&, const Element&);
+    void appendAttribute(StringBuilder&, const Element&, const Attribute&, Namespaces*);
     void appendCDATASection(StringBuilder&, const String&);
-    void appendStartMarkup(StringBuilder&, const Node*, Namespaces*);
-    bool shouldSelfClose(const Node*);
-    bool elementCannotHaveEndTag(const Node*);
-    void appendEndMarkup(StringBuilder&, const Node*);
+    void appendStartMarkup(StringBuilder&, Node&, Namespaces*);
+    bool shouldSelfClose(const Node&);
+    bool elementCannotHaveEndTag(const Node&);
+    void appendEndMarkup(StringBuilder&, const Node&);
 
     Vector<Node*>* const m_nodes;
     const Range* const m_range;
 
 private:
-    String resolveURLIfNeeded(const Element*, const String&) const;
-    void appendQuotedURLAttributeValue(StringBuilder&, const Element*, const Attribute&);
-    void serializeNodesWithNamespaces(Node* targetNode, EChildrenOnly, const Namespaces*, Vector<QualifiedName>* tagNamesToSkip);
+    String resolveURLIfNeeded(const Element&, const String&) const;
+    void appendQuotedURLAttributeValue(StringBuilder&, const Element&, const Attribute&);
+    void serializeNodesWithNamespaces(Node& targetNode, EChildrenOnly, const Namespaces*, Vector<QualifiedName>* tagNamesToSkip);
 
     StringBuilder m_markup;
     const EAbsoluteURLs m_resolveURLsMethod;
diff --git a/Source/core/editing/MergeIdenticalElementsCommand.h b/Source/core/editing/MergeIdenticalElementsCommand.h
index 42dd8a8..7f82f7c 100644
--- a/Source/core/editing/MergeIdenticalElementsCommand.h
+++ b/Source/core/editing/MergeIdenticalElementsCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class MergeIdenticalElementsCommand : public SimpleEditCommand {
+class MergeIdenticalElementsCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<MergeIdenticalElementsCommand> create(PassRefPtr<Element> element1, PassRefPtr<Element> element2)
     {
diff --git a/Source/core/editing/ModifySelectionListLevel.cpp b/Source/core/editing/ModifySelectionListLevel.cpp
deleted file mode 100644
index e438eb2..0000000
--- a/Source/core/editing/ModifySelectionListLevel.cpp
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-#include "core/editing/ModifySelectionListLevel.h"
-
-#include "core/dom/Document.h"
-#include "core/editing/FrameSelection.h"
-#include "core/editing/htmlediting.h"
-#include "core/html/HTMLElement.h"
-#include "core/frame/Frame.h"
-#include "core/rendering/RenderObject.h"
-
-namespace WebCore {
-
-ModifySelectionListLevelCommand::ModifySelectionListLevelCommand(Document& document)
-    : CompositeEditCommand(document)
-{
-}
-
-bool ModifySelectionListLevelCommand::preservesTypingStyle() const
-{
-    return true;
-}
-
-// This needs to be static so it can be called by canIncreaseSelectionListLevel and canDecreaseSelectionListLevel
-static bool getStartEndListChildren(const VisibleSelection& selection, Node*& start, Node*& end)
-{
-    if (selection.isNone())
-        return false;
-
-    // start must be in a list child
-    Node* startListChild = enclosingListChild(selection.start().anchorNode());
-    if (!startListChild)
-        return false;
-
-    // end must be in a list child
-    Node* endListChild = selection.isRange() ? enclosingListChild(selection.end().anchorNode()) : startListChild;
-    if (!endListChild)
-        return false;
-
-    // For a range selection we want the following behavior:
-    //      - the start and end must be within the same overall list
-    //      - the start must be at or above the level of the rest of the range
-    //      - if the end is anywhere in a sublist lower than start, the whole sublist gets moved
-    // In terms of this function, this means:
-    //      - endListChild must start out being be a sibling of startListChild, or be in a
-    //         sublist of startListChild or a sibling
-    //      - if endListChild is in a sublist of startListChild or a sibling, it must be adjusted
-    //         to be the ancestor that is startListChild or its sibling
-    while (startListChild->parentNode() != endListChild->parentNode()) {
-        endListChild = endListChild->parentNode();
-        if (!endListChild)
-            return false;
-    }
-
-    // if the selection ends on a list item with a sublist, include the entire sublist
-    if (endListChild->renderer()->isListItem()) {
-        RenderObject* r = endListChild->renderer()->nextSibling();
-        if (r && isListElement(r->node()))
-            endListChild = r->node();
-    }
-
-    start = startListChild;
-    end = endListChild;
-    return true;
-}
-
-void ModifySelectionListLevelCommand::insertSiblingNodeRangeBefore(Node* startNode, Node* endNode, Node* refNode)
-{
-    Node* node = startNode;
-    while (1) {
-        Node* next = node->nextSibling();
-        removeNode(node);
-        insertNodeBefore(node, refNode);
-
-        if (node == endNode)
-            break;
-
-        node = next;
-    }
-}
-
-void ModifySelectionListLevelCommand::insertSiblingNodeRangeAfter(Node* startNode, Node* endNode, Node* refNode)
-{
-    Node* node = startNode;
-    while (1) {
-        Node* next = node->nextSibling();
-        removeNode(node);
-        insertNodeAfter(node, refNode);
-
-        if (node == endNode)
-            break;
-
-        refNode = node;
-        node = next;
-    }
-}
-
-void ModifySelectionListLevelCommand::appendSiblingNodeRange(Node* startNode, Node* endNode, Element* newParent)
-{
-    Node* node = startNode;
-    while (1) {
-        Node* next = node->nextSibling();
-        removeNode(node);
-        appendNode(node, newParent);
-
-        if (node == endNode)
-            break;
-
-        node = next;
-    }
-}
-
-IncreaseSelectionListLevelCommand::IncreaseSelectionListLevelCommand(Document& document, Type listType)
-    : ModifySelectionListLevelCommand(document)
-    , m_listType(listType)
-{
-}
-
-// This needs to be static so it can be called by canIncreaseSelectionListLevel
-static bool canIncreaseListLevel(const VisibleSelection& selection, Node*& start, Node*& end)
-{
-    if (!getStartEndListChildren(selection, start, end))
-        return false;
-
-    // start must not be the first child (because you need a prior one
-    // to increase relative to)
-    if (!start->renderer()->previousSibling())
-        return false;
-
-    return true;
-}
-
-// For the moment, this is SPI and the only client (Mail.app) is satisfied.
-// Here are two things to re-evaluate when making into API.
-// 1. Currently, InheritedListType uses clones whereas OrderedList and
-// UnorderedList create a new list node of the specified type.  That is
-// inconsistent wrt style.  If that is not OK, here are some alternatives:
-//  - new nodes always inherit style (probably the best choice)
-//  - new nodes have always have no style
-//  - new nodes of the same type inherit style
-// 2. Currently, the node we return may be either a pre-existing one or
-// a new one. Is it confusing to return the pre-existing one without
-// somehow indicating that it is not new?  If so, here are some alternatives:
-//  - only return the list node if we created it
-//  - indicate whether the list node is new or pre-existing
-//  - (silly) client specifies whether to return pre-existing list nodes
-void IncreaseSelectionListLevelCommand::doApply()
-{
-    Node* startListChild;
-    Node* endListChild;
-    if (!canIncreaseListLevel(endingSelection(), startListChild, endListChild))
-        return;
-
-    Node* previousItem = startListChild->renderer()->previousSibling()->node();
-    if (isListElement(previousItem)) {
-        // move nodes up into preceding list
-        appendSiblingNodeRange(startListChild, endListChild, toElement(previousItem));
-        m_listElement = previousItem;
-    } else {
-        // create a sublist for the preceding element and move nodes there
-        RefPtr<Element> newParent;
-        switch (m_listType) {
-            case InheritedListType:
-                newParent = startListChild->parentElement();
-                if (newParent)
-                    newParent = newParent->cloneElementWithoutChildren();
-                break;
-            case OrderedList:
-                newParent = createOrderedListElement(document());
-                break;
-            case UnorderedList:
-                newParent = createUnorderedListElement(document());
-                break;
-        }
-        insertNodeBefore(newParent, startListChild);
-        appendSiblingNodeRange(startListChild, endListChild, newParent.get());
-        m_listElement = newParent.release();
-    }
-}
-
-bool IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(Document& document)
-{
-    Node* startListChild;
-    Node* endListChild;
-    return canIncreaseListLevel(document.frame()->selection().selection(), startListChild, endListChild);
-}
-
-PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevel(Document& document, Type type)
-{
-    ASSERT(document.frame());
-    RefPtr<IncreaseSelectionListLevelCommand> command = create(document, type);
-    command->apply();
-    return command->m_listElement.release();
-}
-
-PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevel(Document& document)
-{
-    return increaseSelectionListLevel(document, InheritedListType);
-}
-
-PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(Document& document)
-{
-    return increaseSelectionListLevel(document, OrderedList);
-}
-
-PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(Document& document)
-{
-    return increaseSelectionListLevel(document, UnorderedList);
-}
-
-DecreaseSelectionListLevelCommand::DecreaseSelectionListLevelCommand(Document& document)
-    : ModifySelectionListLevelCommand(document)
-{
-}
-
-// This needs to be static so it can be called by canDecreaseSelectionListLevel
-static bool canDecreaseListLevel(const VisibleSelection& selection, Node*& start, Node*& end)
-{
-    if (!getStartEndListChildren(selection, start, end))
-        return false;
-
-    // there must be a destination list to move the items to
-    if (!isListElement(start->parentNode()->parentNode()))
-        return false;
-
-    return true;
-}
-
-void DecreaseSelectionListLevelCommand::doApply()
-{
-    Node* startListChild;
-    Node* endListChild;
-    if (!canDecreaseListLevel(endingSelection(), startListChild, endListChild))
-        return;
-
-    Node* previousItem = startListChild->renderer()->previousSibling() ? startListChild->renderer()->previousSibling()->node() : 0;
-    Node* nextItem = endListChild->renderer()->nextSibling() ? endListChild->renderer()->nextSibling()->node() : 0;
-    Element* listNode = startListChild->parentElement();
-
-    if (!previousItem) {
-        // at start of sublist, move the child(ren) to before the sublist
-        insertSiblingNodeRangeBefore(startListChild, endListChild, listNode);
-        // if that was the whole sublist we moved, remove the sublist node
-        if (!nextItem)
-            removeNode(listNode);
-    } else if (!nextItem) {
-        // at end of list, move the child(ren) to after the sublist
-        insertSiblingNodeRangeAfter(startListChild, endListChild, listNode);
-    } else if (listNode) {
-        // in the middle of list, split the list and move the children to the divide
-        splitElement(listNode, startListChild);
-        insertSiblingNodeRangeBefore(startListChild, endListChild, listNode);
-    }
-}
-
-bool DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(Document& document)
-{
-    Node* startListChild;
-    Node* endListChild;
-    return canDecreaseListLevel(document.frame()->selection().selection(), startListChild, endListChild);
-}
-
-void DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(Document& document)
-{
-    ASSERT(document.frame());
-    create(document)->apply();
-}
-
-}
diff --git a/Source/core/editing/ModifySelectionListLevel.h b/Source/core/editing/ModifySelectionListLevel.h
deleted file mode 100644
index b870728..0000000
--- a/Source/core/editing/ModifySelectionListLevel.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2006, 2010 Apple Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef ModifySelectionListLevel_h
-#define ModifySelectionListLevel_h
-
-#include "core/editing/CompositeEditCommand.h"
-
-namespace WebCore {
-
-// ModifySelectionListLevelCommand provides functions useful for both increasing and decreasing the list level.
-// It is the base class of IncreaseSelectionListLevelCommand and DecreaseSelectionListLevelCommand.
-// It is not used on its own.
-class ModifySelectionListLevelCommand : public CompositeEditCommand {
-protected:
-    explicit ModifySelectionListLevelCommand(Document&);
-
-    void appendSiblingNodeRange(Node* startNode, Node* endNode, Element* newParent);
-    void insertSiblingNodeRangeBefore(Node* startNode, Node* endNode, Node* refNode);
-    void insertSiblingNodeRangeAfter(Node* startNode, Node* endNode, Node* refNode);
-
-private:
-    virtual bool preservesTypingStyle() const;
-};
-
-// IncreaseSelectionListLevelCommand moves the selected list items one level deeper.
-class IncreaseSelectionListLevelCommand : public ModifySelectionListLevelCommand {
-public:
-    static bool canIncreaseSelectionListLevel(Document&);
-    static PassRefPtr<Node> increaseSelectionListLevel(Document&);
-    static PassRefPtr<Node> increaseSelectionListLevelOrdered(Document&);
-    static PassRefPtr<Node> increaseSelectionListLevelUnordered(Document&);
-
-private:
-    enum Type { InheritedListType, OrderedList, UnorderedList };
-    static PassRefPtr<Node> increaseSelectionListLevel(Document&, Type);
-
-    static PassRefPtr<IncreaseSelectionListLevelCommand> create(Document& document, Type type)
-    {
-        return adoptRef(new IncreaseSelectionListLevelCommand(document, type));
-    }
-
-    IncreaseSelectionListLevelCommand(Document&, Type);
-
-    virtual void doApply();
-
-    Type m_listType;
-    RefPtr<Node> m_listElement;
-};
-
-// DecreaseSelectionListLevelCommand moves the selected list items one level shallower.
-class DecreaseSelectionListLevelCommand : public ModifySelectionListLevelCommand {
-public:
-    static bool canDecreaseSelectionListLevel(Document&);
-    static void decreaseSelectionListLevel(Document&);
-
-private:
-    static PassRefPtr<DecreaseSelectionListLevelCommand> create(Document& document)
-    {
-        return adoptRef(new DecreaseSelectionListLevelCommand(document));
-    }
-
-    explicit DecreaseSelectionListLevelCommand(Document&);
-
-    virtual void doApply();
-};
-
-} // namespace WebCore
-
-#endif // ModifySelectionListLevel_h
diff --git a/Source/core/editing/MoveSelectionCommand.h b/Source/core/editing/MoveSelectionCommand.h
index f952d5f..746c145 100644
--- a/Source/core/editing/MoveSelectionCommand.h
+++ b/Source/core/editing/MoveSelectionCommand.h
@@ -32,7 +32,7 @@
 
 class DocumentFragment;
 
-class MoveSelectionCommand : public CompositeEditCommand {
+class MoveSelectionCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<MoveSelectionCommand> create(PassRefPtr<DocumentFragment> fragment, const Position& position, bool smartInsert = false, bool smartDelete = false)
     {
@@ -42,8 +42,8 @@
 private:
     MoveSelectionCommand(PassRefPtr<DocumentFragment>, const Position&, bool smartInsert, bool smartDelete);
 
-    virtual void doApply();
-    virtual EditAction editingAction() const;
+    virtual void doApply() OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE;
 
     RefPtr<DocumentFragment> m_fragment;
     Position m_position;
diff --git a/Source/core/editing/RemoveCSSPropertyCommand.cpp b/Source/core/editing/RemoveCSSPropertyCommand.cpp
index 6daa841..f7d463a 100644
--- a/Source/core/editing/RemoveCSSPropertyCommand.cpp
+++ b/Source/core/editing/RemoveCSSPropertyCommand.cpp
@@ -50,6 +50,9 @@
 void RemoveCSSPropertyCommand::doApply()
 {
     const StylePropertySet* style = m_element->inlineStyle();
+    if (!style)
+        return;
+
     m_oldValue = style->getPropertyValue(m_property);
     m_important = style->propertyIsImportant(m_property);
 
diff --git a/Source/core/editing/RemoveCSSPropertyCommand.h b/Source/core/editing/RemoveCSSPropertyCommand.h
index 85d6156..950181f 100644
--- a/Source/core/editing/RemoveCSSPropertyCommand.h
+++ b/Source/core/editing/RemoveCSSPropertyCommand.h
@@ -33,7 +33,7 @@
 
 class Element;
 
-class RemoveCSSPropertyCommand : public SimpleEditCommand {
+class RemoveCSSPropertyCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<RemoveCSSPropertyCommand> create(Document& document, PassRefPtr<Element> element, CSSPropertyID property)
     {
@@ -42,7 +42,7 @@
 
 private:
     RemoveCSSPropertyCommand(Document&, PassRefPtr<Element>, CSSPropertyID);
-    ~RemoveCSSPropertyCommand();
+    virtual ~RemoveCSSPropertyCommand();
 
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
diff --git a/Source/core/editing/RemoveFormatCommand.h b/Source/core/editing/RemoveFormatCommand.h
index f6d030d..f08a5a7 100644
--- a/Source/core/editing/RemoveFormatCommand.h
+++ b/Source/core/editing/RemoveFormatCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class RemoveFormatCommand : public CompositeEditCommand {
+class RemoveFormatCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<RemoveFormatCommand> create(Document& document)
     {
@@ -40,8 +40,8 @@
 private:
     explicit RemoveFormatCommand(Document&);
 
-    virtual void doApply();
-    virtual EditAction editingAction() const { return EditActionUnspecified; }
+    virtual void doApply() OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE { return EditActionUnspecified; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/editing/RemoveNodeCommand.h b/Source/core/editing/RemoveNodeCommand.h
index 5d15512..31e9fe3 100644
--- a/Source/core/editing/RemoveNodeCommand.h
+++ b/Source/core/editing/RemoveNodeCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class RemoveNodeCommand : public SimpleEditCommand {
+class RemoveNodeCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<RemoveNodeCommand> create(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
     {
diff --git a/Source/core/editing/RemoveNodePreservingChildrenCommand.h b/Source/core/editing/RemoveNodePreservingChildrenCommand.h
index 6c9fdc8..7ad1b9e 100644
--- a/Source/core/editing/RemoveNodePreservingChildrenCommand.h
+++ b/Source/core/editing/RemoveNodePreservingChildrenCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class RemoveNodePreservingChildrenCommand : public CompositeEditCommand {
+class RemoveNodePreservingChildrenCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<RemoveNodePreservingChildrenCommand> create(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
     {
@@ -40,7 +40,7 @@
 private:
     explicit RemoveNodePreservingChildrenCommand(PassRefPtr<Node>, ShouldAssumeContentIsAlwaysEditable);
 
-    virtual void doApply();
+    virtual void doApply() OVERRIDE;
 
     RefPtr<Node> m_node;
     ShouldAssumeContentIsAlwaysEditable m_shouldAssumeContentIsAlwaysEditable;
diff --git a/Source/core/editing/ReplaceNodeWithSpanCommand.h b/Source/core/editing/ReplaceNodeWithSpanCommand.h
index e9e8afe..8fb5c5b 100644
--- a/Source/core/editing/ReplaceNodeWithSpanCommand.h
+++ b/Source/core/editing/ReplaceNodeWithSpanCommand.h
@@ -38,7 +38,7 @@
 class HTMLElement;
 
 // More accurately, this is ReplaceElementWithSpanPreservingChildrenAndAttributesCommand
-class ReplaceNodeWithSpanCommand : public SimpleEditCommand {
+class ReplaceNodeWithSpanCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<ReplaceNodeWithSpanCommand> create(PassRefPtr<HTMLElement> element)
     {
diff --git a/Source/core/editing/ReplaceSelectionCommand.cpp b/Source/core/editing/ReplaceSelectionCommand.cpp
index 3c9a629..984c9e0 100644
--- a/Source/core/editing/ReplaceSelectionCommand.cpp
+++ b/Source/core/editing/ReplaceSelectionCommand.cpp
@@ -50,7 +50,6 @@
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLTitleElement.h"
 #include "core/frame/Frame.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderText.h"
@@ -513,8 +512,9 @@
                 continue;
             }
             removeNodeAttribute(element, styleAttr);
-        } else if (newInlineStyle->style()->propertyCount() != inlineStyle->propertyCount())
-            setNodeAttribute(element, styleAttr, newInlineStyle->style()->asText());
+        } else if (newInlineStyle->style()->propertyCount() != inlineStyle->propertyCount()) {
+            setNodeAttribute(element, styleAttr, AtomicString(newInlineStyle->style()->asText()));
+        }
 
         // FIXME: Tolerate differences in id, class, and style attributes.
         if (isNonTableCellHTMLBlockElement(element) && areIdenticalElements(element, element->parentNode())
@@ -665,12 +665,12 @@
 {
     document().updateLayoutIgnorePendingStylesheets();
 
-    Node& lastLeafInserted = insertedNodes.lastLeafInserted();
-    if (lastLeafInserted.isTextNode() && !nodeHasVisibleRenderText(toText(lastLeafInserted))
-        && !enclosingNodeWithTag(firstPositionInOrBeforeNode(&lastLeafInserted), selectTag)
-        && !enclosingNodeWithTag(firstPositionInOrBeforeNode(&lastLeafInserted), scriptTag)) {
-        insertedNodes.willRemoveNode(lastLeafInserted);
-        removeNode(&lastLeafInserted);
+    Node* lastLeafInserted = insertedNodes.lastLeafInserted();
+    if (lastLeafInserted && lastLeafInserted->isTextNode() && !nodeHasVisibleRenderText(toText(*lastLeafInserted))
+        && !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), selectTag)
+        && !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), scriptTag)) {
+        insertedNodes.willRemoveNode(*lastLeafInserted);
+        removeNode(lastLeafInserted);
     }
 
     // We don't have to make sure that firstNodeInserted isn't inside a select or script element, because
@@ -702,7 +702,7 @@
             || node->hasTagName(linkTag)
             || node->hasTagName(metaTag)
             || node->hasTagName(styleTag)
-            || isHTMLTitleElement(node)) {
+            || node->hasTagName(titleTag)) {
             next = NodeTraversal::nextSkippingChildren(*node);
             fragment.removeNode(node);
         } else {
@@ -788,8 +788,9 @@
     if (style->isEmpty() || !wrappingStyleSpan->firstChild()) {
         insertedNodes.willRemoveNodePreservingChildren(*wrappingStyleSpan);
         removeNodePreservingChildren(wrappingStyleSpan);
-    } else
-        setNodeAttribute(wrappingStyleSpan, styleAttr, style->style()->asText());
+    } else {
+        setNodeAttribute(wrappingStyleSpan, styleAttr, AtomicString(style->style()->asText()));
+    }
 }
 
 void ReplaceSelectionCommand::mergeEndIfNeeded()
@@ -930,7 +931,7 @@
         bool mergeBlocksAfterDelete = startIsInsideMailBlockquote || isEndOfParagraph(visibleEnd) || isStartOfBlock(visibleStart);
         // FIXME: We should only expand to include fully selected special elements if we are copying a
         // selection and pasting it on top of itself.
-        deleteSelection(false, mergeBlocksAfterDelete, true, false);
+        deleteSelection(false, mergeBlocksAfterDelete, false);
         visibleStart = endingSelection().visibleStart();
         if (fragment.hasInterchangeNewlineAtStart()) {
             if (isEndOfParagraph(visibleStart) && !isStartOfParagraph(visibleStart)) {
@@ -1123,7 +1124,7 @@
     if (insertionBlock && insertionPos.deprecatedNode() == insertionBlock->parentNode() && (unsigned)insertionPos.deprecatedEditingOffset() < insertionBlock->nodeIndex() && !isStartOfParagraph(startOfInsertedContent))
         insertNodeAt(createBreakElement(document()).get(), startOfInsertedContent.deepEquivalent());
 
-    if (endBR && (plainTextFragment || shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR))) {
+    if (endBR && (plainTextFragment || (shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR) && !(fragment.hasInterchangeNewlineAtEnd() && selectionIsPlainText)))) {
         RefPtr<Node> parent = endBR->parentNode();
         insertedNodes.willRemoveNode(*endBR);
         removeNode(endBR);
@@ -1142,7 +1143,7 @@
 
     // Setup m_startOfInsertedContent and m_endOfInsertedContent. This should be the last two lines of code that access insertedNodes.
     m_startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
-    m_endOfInsertedContent = lastPositionInOrAfterNode(&insertedNodes.lastLeafInserted());
+    m_endOfInsertedContent = lastPositionInOrAfterNode(insertedNodes.lastLeafInserted());
 
     // Determine whether or not we should merge the end of inserted content with what's after it before we do
     // the start merge so that the start merge doesn't effect our decision.
diff --git a/Source/core/editing/ReplaceSelectionCommand.h b/Source/core/editing/ReplaceSelectionCommand.h
index ee3879b..4173df5 100644
--- a/Source/core/editing/ReplaceSelectionCommand.h
+++ b/Source/core/editing/ReplaceSelectionCommand.h
@@ -34,7 +34,7 @@
 class DocumentFragment;
 class ReplacementFragment;
 
-class ReplaceSelectionCommand : public CompositeEditCommand {
+class ReplaceSelectionCommand FINAL : public CompositeEditCommand {
 public:
     enum CommandOption {
         SelectReplacement = 1 << 0,
@@ -55,8 +55,8 @@
 private:
     ReplaceSelectionCommand(Document&, PassRefPtr<DocumentFragment>, CommandOptions, EditAction);
 
-    virtual void doApply();
-    virtual EditAction editingAction() const;
+    virtual void doApply() OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE;
 
     class InsertedNodes {
     public:
@@ -66,8 +66,8 @@
         void didReplaceNode(Node&, Node& newNode);
 
         Node* firstNodeInserted() const { return m_firstNodeInserted.get(); }
-        Node& lastLeafInserted() const { ASSERT(m_lastNodeInserted); return m_lastNodeInserted->lastDescendant(); }
-        Node* pastLastLeaf() const { return m_lastNodeInserted ? NodeTraversal::next(lastLeafInserted()) : 0; }
+        Node* lastLeafInserted() const { return m_lastNodeInserted ? &m_lastNodeInserted->lastDescendant() : 0; }
+        Node* pastLastLeaf() const { return m_lastNodeInserted ? NodeTraversal::next(*lastLeafInserted()) : 0; }
 
     private:
         RefPtr<Node> m_firstNodeInserted;
@@ -91,7 +91,6 @@
     void makeInsertedContentRoundTrippableWithHTMLTreeBuilder(InsertedNodes&);
     void moveNodeOutOfAncestor(PassRefPtr<Node>, PassRefPtr<Node> ancestor);
     void handleStyleSpans(InsertedNodes&);
-    void handlePasteAsQuotationNode();
 
     VisiblePosition positionAtStartOfInsertedContent() const;
     VisiblePosition positionAtEndOfInsertedContent() const;
diff --git a/Source/core/editing/SetNodeAttributeCommand.h b/Source/core/editing/SetNodeAttributeCommand.h
index 5716b61..a69634c 100644
--- a/Source/core/editing/SetNodeAttributeCommand.h
+++ b/Source/core/editing/SetNodeAttributeCommand.h
@@ -31,7 +31,7 @@
 
 namespace WebCore {
 
-class SetNodeAttributeCommand : public SimpleEditCommand {
+class SetNodeAttributeCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<SetNodeAttributeCommand> create(PassRefPtr<Element> element, const QualifiedName& attribute, const AtomicString& value)
     {
diff --git a/Source/core/editing/SimplifyMarkupCommand.h b/Source/core/editing/SimplifyMarkupCommand.h
index 3da2a62..f519690 100644
--- a/Source/core/editing/SimplifyMarkupCommand.h
+++ b/Source/core/editing/SimplifyMarkupCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class SimplifyMarkupCommand : public CompositeEditCommand {
+class SimplifyMarkupCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<SimplifyMarkupCommand> create(Document& document, Node* firstNode, Node* nodeAfterLast)
     {
@@ -40,7 +40,7 @@
 private:
     SimplifyMarkupCommand(Document&, Node* firstNode, Node* nodeAfterLast);
 
-    virtual void doApply();
+    virtual void doApply() OVERRIDE;
     int pruneSubsequentAncestorsToRemove(Vector<RefPtr<Node> >& nodesToRemove, size_t startNodeIndex);
 
     RefPtr<Node> m_firstNode;
diff --git a/Source/core/editing/SpellCheckRequester.cpp b/Source/core/editing/SpellCheckRequester.cpp
index b8c948d..104f446 100644
--- a/Source/core/editing/SpellCheckRequester.cpp
+++ b/Source/core/editing/SpellCheckRequester.cpp
@@ -31,8 +31,7 @@
 #include "core/dom/Node.h"
 #include "core/editing/SpellChecker.h"
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/text/TextCheckerClient.h"
 
 namespace WebCore {
diff --git a/Source/core/editing/SpellCheckRequester.h b/Source/core/editing/SpellCheckRequester.h
index 6eefe8f..f3fd57f 100644
--- a/Source/core/editing/SpellCheckRequester.h
+++ b/Source/core/editing/SpellCheckRequester.h
@@ -43,7 +43,7 @@
 class SpellCheckRequester;
 class TextCheckerClient;
 
-class SpellCheckRequest : public TextCheckingRequest {
+class SpellCheckRequest FINAL : public TextCheckingRequest {
 public:
     static PassRefPtr<SpellCheckRequest> create(TextCheckingTypeMask, TextCheckingProcessType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange, int requestNumber = 0);
     virtual ~SpellCheckRequest();
@@ -54,7 +54,6 @@
 
     void setCheckerAndSequence(SpellCheckRequester*, int sequence);
     void requesterDestroyed();
-    bool isStarted() const { return m_requester; }
 
     virtual const TextCheckingRequestData& data() const OVERRIDE;
     virtual void didSucceed(const Vector<TextCheckingResult>&) OVERRIDE;
diff --git a/Source/core/editing/SpellChecker.cpp b/Source/core/editing/SpellChecker.cpp
index 3ebc4e3..f73f78a 100644
--- a/Source/core/editing/SpellChecker.cpp
+++ b/Source/core/editing/SpellChecker.cpp
@@ -41,7 +41,7 @@
 #include "core/html/HTMLInputElement.h"
 #include "core/loader/EmptyClients.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/page/SpellCheckerClient.h"
 #include "core/rendering/RenderTextControl.h"
 #include "platform/text/TextCheckerClient.h"
@@ -104,7 +104,7 @@
     if (isContinuousSpellCheckingEnabled())
         return;
     for (Frame* frame = m_frame.page()->mainFrame(); frame && frame->document(); frame = frame->tree().traverseNext()) {
-        for (Node* node = frame->document()->rootNode(); node; node = NodeTraversal::next(*node)) {
+        for (Node* node = &frame->document()->rootNode(); node; node = NodeTraversal::next(*node)) {
             node->setAlreadySpellChecked(false);
         }
     }
@@ -120,11 +120,11 @@
     if (isContinuousSpellCheckingEnabled() && unifiedTextCheckerEnabled()) {
         bool isTextField = false;
         HTMLTextFormControlElement* enclosingHTMLTextFormControlElement = 0;
-        if (!isHTMLTextFormControlElement(element))
+        if (!isHTMLTextFormControlElement(*element))
             enclosingHTMLTextFormControlElement = enclosingTextFormControl(firstPositionInNode(element));
         element = enclosingHTMLTextFormControlElement ? enclosingHTMLTextFormControlElement : element;
         Element* parent = element;
-        if (isHTMLTextFormControlElement(element)) {
+        if (isHTMLTextFormControlElement(*element)) {
             HTMLTextFormControlElement* textControl = toHTMLTextFormControlElement(element);
             parent = textControl;
             element = textControl->innerTextElement();
@@ -304,36 +304,6 @@
     }
 }
 
-String SpellChecker::misspelledWordAtCaretOrRange(Node* clickedNode) const
-{
-    if (!isContinuousSpellCheckingEnabled() || !clickedNode || !isSpellCheckingEnabledFor(clickedNode))
-        return String();
-
-    VisibleSelection selection = m_frame.selection().selection();
-    if (!selection.isContentEditable() || selection.isNone())
-        return String();
-
-    VisibleSelection wordSelection(selection.base());
-    wordSelection.expandUsingGranularity(WordGranularity);
-    RefPtr<Range> wordRange = wordSelection.toNormalizedRange();
-
-    // In compliance with GTK+ applications, additionally allow to provide suggestions when the current
-    // selection exactly match the word selection.
-    if (selection.isRange() && !areRangesEqual(wordRange.get(), selection.toNormalizedRange().get()))
-        return String();
-
-    String word = wordRange->text();
-    if (word.isEmpty())
-        return String();
-
-    int wordLength = word.length();
-    int misspellingLocation = -1;
-    int misspellingLength = 0;
-    textChecker().checkSpellingOfString(word, &misspellingLocation, &misspellingLength);
-
-    return misspellingLength == wordLength ? word : String();
-}
-
 void SpellChecker::showSpellingGuessPanel()
 {
     if (spellCheckerClient().spellingUIIsShowing()) {
@@ -807,7 +777,7 @@
     if (oldAdjacentWords  != newAdjacentWords) {
         if (isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled()) {
             VisibleSelection selectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
-            markMisspellingsAndBadGrammar(oldAdjacentWords, selectedSentence != newSelectedSentence, selectedSentence);
+            markMisspellingsAndBadGrammar(oldAdjacentWords, true, selectedSentence);
         } else {
             markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
         }
diff --git a/Source/core/editing/SpellChecker.h b/Source/core/editing/SpellChecker.h
index 009cca1..6a57063 100644
--- a/Source/core/editing/SpellChecker.h
+++ b/Source/core/editing/SpellChecker.h
@@ -26,7 +26,7 @@
 #ifndef SpellChecker_h
 #define SpellChecker_h
 
-#include "core/dom/ClipboardAccessPolicy.h"
+#include "core/clipboard/ClipboardAccessPolicy.h"
 #include "core/dom/DocumentMarker.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/VisibleSelection.h"
@@ -56,7 +56,6 @@
     void toggleContinuousSpellChecking();
     bool isGrammarCheckingEnabled();
     void ignoreSpelling();
-    String misspelledWordAtCaretOrRange(Node* clickedNode) const;
     bool isSpellCheckingEnabledInFocusedNode() const;
     bool isSpellCheckingEnabledFor(Node*) const;
     void markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping);
diff --git a/Source/core/editing/SpellingCorrectionCommand.cpp b/Source/core/editing/SpellingCorrectionCommand.cpp
deleted file mode 100644
index cc73001..0000000
--- a/Source/core/editing/SpellingCorrectionCommand.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-#include "core/editing/SpellingCorrectionCommand.h"
-
-#include "core/dom/Document.h"
-#include "core/editing/InsertTextCommand.h"
-#include "core/editing/SetSelectionCommand.h"
-#include "core/editing/TextIterator.h"
-#include "core/frame/Frame.h"
-
-namespace WebCore {
-
-SpellingCorrectionCommand::SpellingCorrectionCommand(PassRefPtr<Range> rangeToBeCorrected, const String& correction)
-    : CompositeEditCommand(rangeToBeCorrected->startContainer()->document())
-    , m_rangeToBeCorrected(rangeToBeCorrected)
-    , m_selectionToBeCorrected(m_rangeToBeCorrected.get())
-    , m_correction(correction)
-{
-}
-
-void SpellingCorrectionCommand::doApply()
-{
-    m_corrected = plainText(m_rangeToBeCorrected.get());
-    if (!m_corrected.length())
-        return;
-
-    applyCommandToComposite(SetSelectionCommand::create(m_selectionToBeCorrected, FrameSelection::SpellCorrectionTriggered | FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle));
-    applyCommandToComposite(InsertTextCommand::create(document(), m_correction));
-}
-
-bool SpellingCorrectionCommand::shouldRetainAutocorrectionIndicator() const
-{
-    return true;
-}
-
-} // namespace WebCore
diff --git a/Source/core/editing/SpellingCorrectionCommand.h b/Source/core/editing/SpellingCorrectionCommand.h
deleted file mode 100644
index ae4d15e..0000000
--- a/Source/core/editing/SpellingCorrectionCommand.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef SpellingCorrectionCommand_h
-#define SpellingCorrectionCommand_h
-
-#include "core/dom/Range.h"
-#include "core/editing/CompositeEditCommand.h"
-
-namespace WebCore {
-
-class SpellingCorrectionCommand : public CompositeEditCommand {
-public:
-    static PassRefPtr<SpellingCorrectionCommand> create(PassRefPtr<Range> rangeToBeCorrected, const String& correction)
-    {
-        return adoptRef(new SpellingCorrectionCommand(rangeToBeCorrected, correction));
-    }
-private:
-    SpellingCorrectionCommand(PassRefPtr<Range> rangeToBeCorrected, const String& correction);
-    virtual void doApply();
-    virtual bool shouldRetainAutocorrectionIndicator() const;
-
-    RefPtr<Range> m_rangeToBeCorrected;
-    VisibleSelection m_selectionToBeCorrected;
-    String m_corrected;
-    String m_correction;
-};
-
-} // namespace WebCore
-
-#endif // SpellingCorrectionCommand_h
diff --git a/Source/core/editing/SplitElementCommand.h b/Source/core/editing/SplitElementCommand.h
index a87b5a2..d7cac54 100644
--- a/Source/core/editing/SplitElementCommand.h
+++ b/Source/core/editing/SplitElementCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class SplitElementCommand : public SimpleEditCommand {
+class SplitElementCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<SplitElementCommand> create(PassRefPtr<Element> element, PassRefPtr<Node> splitPointChild)
     {
diff --git a/Source/core/editing/SplitTextNodeCommand.h b/Source/core/editing/SplitTextNodeCommand.h
index 27e0cb4..ff924a3 100644
--- a/Source/core/editing/SplitTextNodeCommand.h
+++ b/Source/core/editing/SplitTextNodeCommand.h
@@ -32,7 +32,7 @@
 
 class Text;
 
-class SplitTextNodeCommand : public SimpleEditCommand {
+class SplitTextNodeCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<SplitTextNodeCommand> create(PassRefPtr<Text> node, int offset)
     {
diff --git a/Source/core/editing/SplitTextNodeContainingElementCommand.h b/Source/core/editing/SplitTextNodeContainingElementCommand.h
index ba9da5b..4210ac0 100644
--- a/Source/core/editing/SplitTextNodeContainingElementCommand.h
+++ b/Source/core/editing/SplitTextNodeContainingElementCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class SplitTextNodeContainingElementCommand : public CompositeEditCommand {
+class SplitTextNodeContainingElementCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<SplitTextNodeContainingElementCommand> create(PassRefPtr<Text> node, int offset)
     {
@@ -40,7 +40,7 @@
 private:
     SplitTextNodeContainingElementCommand(PassRefPtr<Text>, int offset);
 
-    virtual void doApply();
+    virtual void doApply() OVERRIDE;
 
     RefPtr<Text> m_text;
     int m_offset;
diff --git a/Source/core/editing/TextCheckingHelper.cpp b/Source/core/editing/TextCheckingHelper.cpp
index 41247b0..091585a 100644
--- a/Source/core/editing/TextCheckingHelper.cpp
+++ b/Source/core/editing/TextCheckingHelper.cpp
@@ -36,7 +36,7 @@
 #include "core/editing/VisiblePosition.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/page/SpellCheckerClient.h"
 #include "platform/text/TextBreakIterator.h"
 #include "platform/text/TextCheckerClient.h"
diff --git a/Source/core/editing/TextIterator.cpp b/Source/core/editing/TextIterator.cpp
index b59a8fe..b85b148 100644
--- a/Source/core/editing/TextIterator.cpp
+++ b/Source/core/editing/TextIterator.cpp
@@ -43,9 +43,11 @@
 #include "core/rendering/RenderTableRow.h"
 #include "core/rendering/RenderTextControl.h"
 #include "core/rendering/RenderTextFragment.h"
+#include "platform/fonts/Character.h"
 #include "platform/fonts/Font.h"
 #include "platform/text/TextBoundaries.h"
 #include "platform/text/TextBreakIteratorInternalICU.h"
+#include "platform/text/UnicodeUtilities.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
 #include "wtf/unicode/CharacterNames.h"
@@ -237,7 +239,7 @@
 
 // --------
 
-TextIterator::TextIterator(const Range* r, TextIteratorBehavior behavior)
+TextIterator::TextIterator(const Range* range, TextIteratorBehaviorFlags behavior)
     : m_shadowDepth(0)
     , m_startContainer(0)
     , m_startOffset(0)
@@ -256,21 +258,22 @@
     , m_stopsOnFormControls(behavior & TextIteratorStopsOnFormControls)
     , m_shouldStop(false)
     , m_emitsImageAltText(behavior & TextIteratorEmitsImageAltText)
+    , m_entersAuthorShadowRoots(behavior & TextIteratorEntersAuthorShadowRoots)
 {
-    if (!r)
+    if (!range)
         return;
 
     // get and validate the range endpoints
-    Node* startContainer = r->startContainer();
+    Node* startContainer = range->startContainer();
     if (!startContainer)
         return;
-    int startOffset = r->startOffset();
-    Node* endContainer = r->endContainer();
-    int endOffset = r->endOffset();
+    int startOffset = range->startOffset();
+    Node* endContainer = range->endContainer();
+    int endOffset = range->endOffset();
 
     // Callers should be handing us well-formed ranges. If we discover that this isn't
     // the case, we could consider changing this assertion to an early return.
-    ASSERT(r->boundaryPointsValid());
+    ASSERT(range->boundaryPointsValid());
 
     // remember range - this does not change
     m_startContainer = startContainer;
@@ -279,7 +282,7 @@
     m_endOffset = endOffset;
 
     // set up the current node for processing
-    m_node = r->firstNode();
+    m_node = range->firstNode();
     if (!m_node)
         return;
     setUpFullyClippedStack(m_fullyClippedStack, m_node);
@@ -366,18 +369,32 @@
                 m_iterationProgress = HandledChildren;
             }
         } else {
-            // Enter user-agent shadow root, if necessary.
-            if (m_iterationProgress < HandledUserAgentShadowRoot) {
-                if (m_entersTextControls && renderer->isTextControl()) {
-                    m_node = toElement(m_node)->userAgentShadowRoot();
+            // Enter author shadow roots, from youngest, if any and if necessary.
+            if (m_iterationProgress < HandledAuthorShadowRoots) {
+                if (m_entersAuthorShadowRoots && m_node->isElementNode() && toElement(m_node)->hasAuthorShadowRoot()) {
+                    ShadowRoot* youngestShadowRoot = toElement(m_node)->shadowRoot();
+                    ASSERT(youngestShadowRoot->type() == ShadowRoot::AuthorShadowRoot);
+                    m_node = youngestShadowRoot;
                     m_iterationProgress = HandledNone;
-                    m_handledFirstLetter = false;
-                    m_firstLetterText = 0;
                     ++m_shadowDepth;
                     pushFullyClippedState(m_fullyClippedStack, m_node);
                     continue;
                 }
 
+                m_iterationProgress = HandledAuthorShadowRoots;
+            }
+
+            // Enter user-agent shadow root, if necessary.
+            if (m_iterationProgress < HandledUserAgentShadowRoot) {
+                if (m_entersTextControls && renderer->isTextControl()) {
+                    ShadowRoot* userAgentShadowRoot = toElement(m_node)->userAgentShadowRoot();
+                    ASSERT(userAgentShadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
+                    m_node = userAgentShadowRoot;
+                    m_iterationProgress = HandledNone;
+                    ++m_shadowDepth;
+                    pushFullyClippedState(m_fullyClippedStack, m_node);
+                    continue;
+                }
                 m_iterationProgress = HandledUserAgentShadowRoot;
             }
 
@@ -387,11 +404,11 @@
                 if (renderer->isText() && m_node->nodeType() == Node::TEXT_NODE) { // FIXME: What about CDATA_SECTION_NODE?
                     handledNode = handleTextNode();
                 } else if (renderer && (renderer->isImage() || renderer->isWidget()
-                    || (renderer->node() && renderer->node()->isElementNode()
-                    && (toElement(renderer->node())->isFormControlElement()
-                    || toElement(renderer->node())->hasTagName(legendTag)
-                    || toElement(renderer->node())->hasTagName(meterTag)
-                    || toElement(renderer->node())->hasTagName(progressTag))))) {
+                    || (m_node && m_node->isElementNode()
+                    && (toElement(m_node)->isFormControlElement()
+                    || toElement(m_node)->hasTagName(legendTag)
+                    || toElement(m_node)->hasTagName(meterTag)
+                    || toElement(m_node)->hasTagName(progressTag))))) {
                     handledNode = handleReplacedElement();
                 } else {
                     handledNode = handleNonTextNode();
@@ -433,16 +450,34 @@
                 }
 
                 if (!next && !parentNode && m_shadowDepth > 0) {
-                    // 4. Reached the top of a shadow root; go back to where we were.
+                    // 4. Reached the top of a shadow root. If it's created by author, then try to visit the next
+                    // sibling shadow root, if any.
                     ShadowRoot* shadowRoot = toShadowRoot(m_node);
-                    // For now, the root can only be a user-agent shadow root.
-                    ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
-                    m_node = shadowRoot->host();
-                    m_iterationProgress = HandledUserAgentShadowRoot;
+                    if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot) {
+                        ShadowRoot* nextShadowRoot = shadowRoot->olderShadowRoot();
+                        if (nextShadowRoot && nextShadowRoot->type() == ShadowRoot::AuthorShadowRoot) {
+                            m_fullyClippedStack.pop();
+                            m_node = nextShadowRoot;
+                            m_iterationProgress = HandledNone;
+                            // m_shadowDepth is unchanged since we exit from a shadow root and enter another.
+                            pushFullyClippedState(m_fullyClippedStack, m_node);
+                        } else {
+                            // We are the last shadow root; exit from here and go back to where we were.
+                            m_node = shadowRoot->host();
+                            m_iterationProgress = HandledAuthorShadowRoots;
+                            --m_shadowDepth;
+                            m_fullyClippedStack.pop();
+                        }
+                    } else {
+                        // If we are in a user-agent shadow root, then go back to the host.
+                        ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
+                        m_node = shadowRoot->host();
+                        m_iterationProgress = HandledUserAgentShadowRoot;
+                        --m_shadowDepth;
+                        m_fullyClippedStack.pop();
+                    }
                     m_handledFirstLetter = false;
                     m_firstLetterText = 0;
-                    --m_shadowDepth;
-                    m_fullyClippedStack.pop();
                     continue;
                 }
             }
@@ -1113,7 +1148,7 @@
 
 // --------
 
-SimplifiedBackwardsTextIterator::SimplifiedBackwardsTextIterator(const Range* r, TextIteratorBehavior behavior)
+SimplifiedBackwardsTextIterator::SimplifiedBackwardsTextIterator(const Range* r, TextIteratorBehaviorFlags behavior)
     : m_node(0)
     , m_offset(0)
     , m_handledNode(false)
@@ -1327,7 +1362,12 @@
 
     m_shouldHandleFirstLetter = false;
     offsetInNode = 0;
-    return firstRenderTextInFirstLetter(fragment->firstLetter());
+    RenderText* firstLetterRenderer = firstRenderTextInFirstLetter(fragment->firstLetter());
+
+    m_offset = firstLetterRenderer->caretMaxOffset();
+    m_offset += collapsedSpaceLength(firstLetterRenderer, m_offset);
+
+    return firstLetterRenderer;
 }
 
 bool SimplifiedBackwardsTextIterator::handleReplacedElement()
@@ -1395,7 +1435,7 @@
 
 // --------
 
-CharacterIterator::CharacterIterator(const Range* r, TextIteratorBehavior behavior)
+CharacterIterator::CharacterIterator(const Range* r, TextIteratorBehaviorFlags behavior)
     : m_offset(0)
     , m_runOffset(0)
     , m_atBreak(true)
@@ -1467,19 +1507,6 @@
     m_runOffset = 0;
 }
 
-String CharacterIterator::string(int numChars)
-{
-    StringBuilder result;
-    result.reserveCapacity(numChars);
-    while (numChars > 0 && !atEnd()) {
-        int runSize = min(numChars, length());
-        m_textIterator.appendTextToStringBuilder(result, m_runOffset, runSize);
-        numChars -= runSize;
-        advance(runSize);
-    }
-    return result.toString();
-}
-
 static PassRefPtr<Range> characterSubrange(CharacterIterator& it, int offset, int length)
 {
     it.advance(offset);
@@ -1494,7 +1521,7 @@
         end->endContainer(), end->endOffset());
 }
 
-BackwardsCharacterIterator::BackwardsCharacterIterator(const Range* range, TextIteratorBehavior behavior)
+BackwardsCharacterIterator::BackwardsCharacterIterator(const Range* range, TextIteratorBehaviorFlags behavior)
     : m_offset(0)
     , m_runOffset(0)
     , m_atBreak(true)
@@ -1640,32 +1667,6 @@
 
 // --------
 
-static inline UChar foldQuoteMarkOrSoftHyphen(UChar c)
-{
-    switch (c) {
-    case hebrewPunctuationGershayim:
-    case leftDoubleQuotationMark:
-    case rightDoubleQuotationMark:
-        return '"';
-    case hebrewPunctuationGeresh:
-    case leftSingleQuotationMark:
-    case rightSingleQuotationMark:
-        return '\'';
-    case softHyphen:
-        // Replace soft hyphen with an ignorable character so that their presence or absence will
-        // not affect string comparison.
-        return 0;
-    default:
-        return c;
-    }
-}
-
-static inline void foldQuoteMarksAndSoftHyphens(UChar* data, size_t length)
-{
-    for (size_t i = 0; i < length; ++i)
-        data[i] = foldQuoteMarkOrSoftHyphen(data[i]);
-}
-
 static const size_t minimumSearchBufferSize = 8192;
 
 #ifndef NDEBUG
@@ -1706,241 +1707,6 @@
 #endif
 }
 
-// ICU's search ignores the distinction between small kana letters and ones
-// that are not small, and also characters that differ only in the voicing
-// marks when considering only primary collation strength differences.
-// This is not helpful for end users, since these differences make words
-// distinct, so for our purposes we need these to be considered.
-// The Unicode folks do not think the collation algorithm should be
-// changed. To work around this, we would like to tailor the ICU searcher,
-// but we can't get that to work yet. So instead, we check for cases where
-// these differences occur, and skip those matches.
-
-// We refer to the above technique as the "kana workaround". The next few
-// functions are helper functinos for the kana workaround.
-
-static inline bool isKanaLetter(UChar character)
-{
-    // Hiragana letters.
-    if (character >= 0x3041 && character <= 0x3096)
-        return true;
-
-    // Katakana letters.
-    if (character >= 0x30A1 && character <= 0x30FA)
-        return true;
-    if (character >= 0x31F0 && character <= 0x31FF)
-        return true;
-
-    // Halfwidth katakana letters.
-    if (character >= 0xFF66 && character <= 0xFF9D && character != 0xFF70)
-        return true;
-
-    return false;
-}
-
-static inline bool isSmallKanaLetter(UChar character)
-{
-    ASSERT(isKanaLetter(character));
-
-    switch (character) {
-    case 0x3041: // HIRAGANA LETTER SMALL A
-    case 0x3043: // HIRAGANA LETTER SMALL I
-    case 0x3045: // HIRAGANA LETTER SMALL U
-    case 0x3047: // HIRAGANA LETTER SMALL E
-    case 0x3049: // HIRAGANA LETTER SMALL O
-    case 0x3063: // HIRAGANA LETTER SMALL TU
-    case 0x3083: // HIRAGANA LETTER SMALL YA
-    case 0x3085: // HIRAGANA LETTER SMALL YU
-    case 0x3087: // HIRAGANA LETTER SMALL YO
-    case 0x308E: // HIRAGANA LETTER SMALL WA
-    case 0x3095: // HIRAGANA LETTER SMALL KA
-    case 0x3096: // HIRAGANA LETTER SMALL KE
-    case 0x30A1: // KATAKANA LETTER SMALL A
-    case 0x30A3: // KATAKANA LETTER SMALL I
-    case 0x30A5: // KATAKANA LETTER SMALL U
-    case 0x30A7: // KATAKANA LETTER SMALL E
-    case 0x30A9: // KATAKANA LETTER SMALL O
-    case 0x30C3: // KATAKANA LETTER SMALL TU
-    case 0x30E3: // KATAKANA LETTER SMALL YA
-    case 0x30E5: // KATAKANA LETTER SMALL YU
-    case 0x30E7: // KATAKANA LETTER SMALL YO
-    case 0x30EE: // KATAKANA LETTER SMALL WA
-    case 0x30F5: // KATAKANA LETTER SMALL KA
-    case 0x30F6: // KATAKANA LETTER SMALL KE
-    case 0x31F0: // KATAKANA LETTER SMALL KU
-    case 0x31F1: // KATAKANA LETTER SMALL SI
-    case 0x31F2: // KATAKANA LETTER SMALL SU
-    case 0x31F3: // KATAKANA LETTER SMALL TO
-    case 0x31F4: // KATAKANA LETTER SMALL NU
-    case 0x31F5: // KATAKANA LETTER SMALL HA
-    case 0x31F6: // KATAKANA LETTER SMALL HI
-    case 0x31F7: // KATAKANA LETTER SMALL HU
-    case 0x31F8: // KATAKANA LETTER SMALL HE
-    case 0x31F9: // KATAKANA LETTER SMALL HO
-    case 0x31FA: // KATAKANA LETTER SMALL MU
-    case 0x31FB: // KATAKANA LETTER SMALL RA
-    case 0x31FC: // KATAKANA LETTER SMALL RI
-    case 0x31FD: // KATAKANA LETTER SMALL RU
-    case 0x31FE: // KATAKANA LETTER SMALL RE
-    case 0x31FF: // KATAKANA LETTER SMALL RO
-    case 0xFF67: // HALFWIDTH KATAKANA LETTER SMALL A
-    case 0xFF68: // HALFWIDTH KATAKANA LETTER SMALL I
-    case 0xFF69: // HALFWIDTH KATAKANA LETTER SMALL U
-    case 0xFF6A: // HALFWIDTH KATAKANA LETTER SMALL E
-    case 0xFF6B: // HALFWIDTH KATAKANA LETTER SMALL O
-    case 0xFF6C: // HALFWIDTH KATAKANA LETTER SMALL YA
-    case 0xFF6D: // HALFWIDTH KATAKANA LETTER SMALL YU
-    case 0xFF6E: // HALFWIDTH KATAKANA LETTER SMALL YO
-    case 0xFF6F: // HALFWIDTH KATAKANA LETTER SMALL TU
-        return true;
-    }
-    return false;
-}
-
-enum VoicedSoundMarkType { NoVoicedSoundMark, VoicedSoundMark, SemiVoicedSoundMark };
-
-static inline VoicedSoundMarkType composedVoicedSoundMark(UChar character)
-{
-    ASSERT(isKanaLetter(character));
-
-    switch (character) {
-    case 0x304C: // HIRAGANA LETTER GA
-    case 0x304E: // HIRAGANA LETTER GI
-    case 0x3050: // HIRAGANA LETTER GU
-    case 0x3052: // HIRAGANA LETTER GE
-    case 0x3054: // HIRAGANA LETTER GO
-    case 0x3056: // HIRAGANA LETTER ZA
-    case 0x3058: // HIRAGANA LETTER ZI
-    case 0x305A: // HIRAGANA LETTER ZU
-    case 0x305C: // HIRAGANA LETTER ZE
-    case 0x305E: // HIRAGANA LETTER ZO
-    case 0x3060: // HIRAGANA LETTER DA
-    case 0x3062: // HIRAGANA LETTER DI
-    case 0x3065: // HIRAGANA LETTER DU
-    case 0x3067: // HIRAGANA LETTER DE
-    case 0x3069: // HIRAGANA LETTER DO
-    case 0x3070: // HIRAGANA LETTER BA
-    case 0x3073: // HIRAGANA LETTER BI
-    case 0x3076: // HIRAGANA LETTER BU
-    case 0x3079: // HIRAGANA LETTER BE
-    case 0x307C: // HIRAGANA LETTER BO
-    case 0x3094: // HIRAGANA LETTER VU
-    case 0x30AC: // KATAKANA LETTER GA
-    case 0x30AE: // KATAKANA LETTER GI
-    case 0x30B0: // KATAKANA LETTER GU
-    case 0x30B2: // KATAKANA LETTER GE
-    case 0x30B4: // KATAKANA LETTER GO
-    case 0x30B6: // KATAKANA LETTER ZA
-    case 0x30B8: // KATAKANA LETTER ZI
-    case 0x30BA: // KATAKANA LETTER ZU
-    case 0x30BC: // KATAKANA LETTER ZE
-    case 0x30BE: // KATAKANA LETTER ZO
-    case 0x30C0: // KATAKANA LETTER DA
-    case 0x30C2: // KATAKANA LETTER DI
-    case 0x30C5: // KATAKANA LETTER DU
-    case 0x30C7: // KATAKANA LETTER DE
-    case 0x30C9: // KATAKANA LETTER DO
-    case 0x30D0: // KATAKANA LETTER BA
-    case 0x30D3: // KATAKANA LETTER BI
-    case 0x30D6: // KATAKANA LETTER BU
-    case 0x30D9: // KATAKANA LETTER BE
-    case 0x30DC: // KATAKANA LETTER BO
-    case 0x30F4: // KATAKANA LETTER VU
-    case 0x30F7: // KATAKANA LETTER VA
-    case 0x30F8: // KATAKANA LETTER VI
-    case 0x30F9: // KATAKANA LETTER VE
-    case 0x30FA: // KATAKANA LETTER VO
-        return VoicedSoundMark;
-    case 0x3071: // HIRAGANA LETTER PA
-    case 0x3074: // HIRAGANA LETTER PI
-    case 0x3077: // HIRAGANA LETTER PU
-    case 0x307A: // HIRAGANA LETTER PE
-    case 0x307D: // HIRAGANA LETTER PO
-    case 0x30D1: // KATAKANA LETTER PA
-    case 0x30D4: // KATAKANA LETTER PI
-    case 0x30D7: // KATAKANA LETTER PU
-    case 0x30DA: // KATAKANA LETTER PE
-    case 0x30DD: // KATAKANA LETTER PO
-        return SemiVoicedSoundMark;
-    }
-    return NoVoicedSoundMark;
-}
-
-static inline bool isCombiningVoicedSoundMark(UChar character)
-{
-    switch (character) {
-    case 0x3099: // COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
-    case 0x309A: // COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
-        return true;
-    }
-    return false;
-}
-
-static inline bool containsKanaLetters(const String& pattern)
-{
-    unsigned length = pattern.length();
-    for (unsigned i = 0; i < length; ++i) {
-        if (isKanaLetter(pattern[i]))
-            return true;
-    }
-    return false;
-}
-
-static void normalizeCharacters(const UChar* characters, unsigned length, Vector<UChar>& buffer)
-{
-    ASSERT(length);
-
-    buffer.resize(length);
-
-    UErrorCode status = U_ZERO_ERROR;
-    size_t bufferSize = unorm_normalize(characters, length, UNORM_NFC, 0, buffer.data(), length, &status);
-    ASSERT(status == U_ZERO_ERROR || status == U_STRING_NOT_TERMINATED_WARNING || status == U_BUFFER_OVERFLOW_ERROR);
-    ASSERT(bufferSize);
-
-    buffer.resize(bufferSize);
-
-    if (status == U_ZERO_ERROR || status == U_STRING_NOT_TERMINATED_WARNING)
-        return;
-
-    status = U_ZERO_ERROR;
-    unorm_normalize(characters, length, UNORM_NFC, 0, buffer.data(), bufferSize, &status);
-    ASSERT(status == U_STRING_NOT_TERMINATED_WARNING);
-}
-
-static bool isNonLatin1Separator(UChar32 character)
-{
-    ASSERT_ARG(character, character >= 256);
-
-    return U_GET_GC_MASK(character) & (U_GC_S_MASK | U_GC_P_MASK | U_GC_Z_MASK | U_GC_CF_MASK);
-}
-
-static inline bool isSeparator(UChar32 character)
-{
-    static const bool latin1SeparatorTable[256] = {
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // space ! " # $ % & ' ( ) * + , - . /
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, //                         : ; < = > ?
-        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //   @
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, //                         [ \ ] ^ _
-        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //   `
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, //                           { | } ~
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
-        1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0
-    };
-
-    if (character < 256)
-        return latin1SeparatorTable[character];
-
-    return isNonLatin1Separator(character);
-}
-
 inline SearchBuffer::SearchBuffer(const String& target, FindOptions options)
     : m_options(options)
     , m_prefixLength(0)
@@ -1992,7 +1758,7 @@
 
     // The kana workaround requires a normalized copy of the target string.
     if (m_targetRequiresKanaWorkaround)
-        normalizeCharacters(m_target.data(), m_target.size(), m_normalizedTarget);
+        normalizeCharactersIntoNFCForm(m_target.data(), m_target.size(), m_normalizedTarget);
 }
 
 inline SearchBuffer::~SearchBuffer()
@@ -2078,55 +1844,9 @@
 
     // Normalize into a match buffer. We reuse a single buffer rather than
     // creating a new one each time.
-    normalizeCharacters(match, matchLength, m_normalizedMatch);
+    normalizeCharactersIntoNFCForm(match, matchLength, m_normalizedMatch);
 
-    const UChar* a = m_normalizedTarget.begin();
-    const UChar* aEnd = m_normalizedTarget.end();
-
-    const UChar* b = m_normalizedMatch.begin();
-    const UChar* bEnd = m_normalizedMatch.end();
-
-    while (true) {
-        // Skip runs of non-kana-letter characters. This is necessary so we can
-        // correctly handle strings where the target and match have different-length
-        // runs of characters that match, while still double checking the correctness
-        // of matches of kana letters with other kana letters.
-        while (a != aEnd && !isKanaLetter(*a))
-            ++a;
-        while (b != bEnd && !isKanaLetter(*b))
-            ++b;
-
-        // If we reached the end of either the target or the match, we should have
-        // reached the end of both; both should have the same number of kana letters.
-        if (a == aEnd || b == bEnd) {
-            ASSERT(a == aEnd);
-            ASSERT(b == bEnd);
-            return false;
-        }
-
-        // Check for differences in the kana letter character itself.
-        if (isSmallKanaLetter(*a) != isSmallKanaLetter(*b))
-            return true;
-        if (composedVoicedSoundMark(*a) != composedVoicedSoundMark(*b))
-            return true;
-        ++a;
-        ++b;
-
-        // Check for differences in combining voiced sound marks found after the letter.
-        while (1) {
-            if (!(a != aEnd && isCombiningVoicedSoundMark(*a))) {
-                if (b != bEnd && isCombiningVoicedSoundMark(*b))
-                    return true;
-                break;
-            }
-            if (!(b != bEnd && isCombiningVoicedSoundMark(*b)))
-                return true;
-            if (*a != *b)
-                return true;
-            ++a;
-            ++b;
-        }
-    }
+    return !checkOnlyKanaLettersInStrings(m_normalizedTarget.begin(), m_normalizedTarget.size(), m_normalizedMatch.begin(), m_normalizedMatch.size());
 }
 
 inline bool SearchBuffer::isWordStartMatch(size_t start, size_t length) const
@@ -2175,7 +1895,7 @@
 
     // Chinese and Japanese lack word boundary marks, and there is no clear agreement on what constitutes
     // a word, so treat the position before any CJK character as a word start.
-    if (Font::isCJKIdeographOrSymbol(firstCharacter))
+    if (Character::isCJKIdeographOrSymbol(firstCharacter))
         return true;
 
     size_t wordBreakSearchStart = start + length;
@@ -2270,7 +1990,7 @@
 
 // --------
 
-String plainText(const Range* r, TextIteratorBehavior defaultBehavior)
+String plainText(const Range* r, TextIteratorBehaviorFlags behavior)
 {
     // The initial buffer size can be critical for performance: https://bugs.webkit.org/show_bug.cgi?id=81192
     static const unsigned initialCapacity = 1 << 15;
@@ -2279,7 +1999,7 @@
     StringBuilder builder;
     builder.reserveCapacity(initialCapacity);
 
-    for (TextIterator it(r, defaultBehavior); !it.atEnd(); it.advance()) {
+    for (TextIterator it(r, behavior); !it.atEnd(); it.advance()) {
         it.appendTextToStringBuilder(builder);
         bufferLength += it.length();
     }
@@ -2352,14 +2072,14 @@
     size_t matchStart;
     size_t matchLength;
     {
-        CharacterIterator findIterator(range, TextIteratorEntersTextControls);
+        CharacterIterator findIterator(range, TextIteratorEntersTextControls | TextIteratorEntersAuthorShadowRoots);
         matchLength = findPlainText(findIterator, target, options, matchStart);
         if (!matchLength)
             return collapsedToBoundary(range, !(options & Backwards));
     }
 
     // Then, find the document position of the start and the end of the text.
-    CharacterIterator computeRangeIterator(range, TextIteratorEntersTextControls);
+    CharacterIterator computeRangeIterator(range, TextIteratorEntersTextControls | TextIteratorEntersAuthorShadowRoots);
     return characterSubrange(computeRangeIterator, matchStart, matchLength);
 }
 
diff --git a/Source/core/editing/TextIterator.h b/Source/core/editing/TextIterator.h
index 2f364c2..9d73d8a 100644
--- a/Source/core/editing/TextIterator.h
+++ b/Source/core/editing/TextIterator.h
@@ -44,7 +44,9 @@
     TextIteratorEmitsOriginalText = 1 << 3,
     TextIteratorStopsOnFormControls = 1 << 4,
     TextIteratorEmitsImageAltText = 1 << 5,
+    TextIteratorEntersAuthorShadowRoots = 1 << 6
 };
+typedef unsigned TextIteratorBehaviorFlags;
 
 // FIXME: Can't really answer this question correctly without knowing the white-space mode.
 // FIXME: Move this somewhere else in the editing directory. It doesn't belong here.
@@ -59,7 +61,7 @@
     }
 }
 
-String plainText(const Range*, TextIteratorBehavior defaultBehavior = TextIteratorDefaultBehavior);
+String plainText(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
 PassRefPtr<Range> findPlainText(const Range*, const String&, FindOptions);
 
 class BitStack {
@@ -84,7 +86,7 @@
 
 class TextIterator {
 public:
-    explicit TextIterator(const Range*, TextIteratorBehavior = TextIteratorDefaultBehavior);
+    explicit TextIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
     ~TextIterator();
 
     bool atEnd() const { return !m_positionNode || m_shouldStop; }
@@ -120,6 +122,7 @@
 private:
     enum IterationProgress {
         HandledNone,
+        HandledAuthorShadowRoots,
         HandledUserAgentShadowRoot,
         HandledNode,
         HandledChildren
@@ -209,6 +212,8 @@
     bool m_shouldStop;
 
     bool m_emitsImageAltText;
+
+    bool m_entersAuthorShadowRoots;
 };
 
 // Iterates through the DOM range, returning all the text, and 0-length boundaries
@@ -216,7 +221,7 @@
 // chunks so as to optimize for performance of the iteration.
 class SimplifiedBackwardsTextIterator {
 public:
-    explicit SimplifiedBackwardsTextIterator(const Range*, TextIteratorBehavior = TextIteratorDefaultBehavior);
+    explicit SimplifiedBackwardsTextIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
 
     bool atEnd() const { return !m_positionNode || m_shouldStop; }
     void advance();
@@ -298,7 +303,7 @@
 // character at a time, or faster, as needed. Useful for searching.
 class CharacterIterator {
 public:
-    explicit CharacterIterator(const Range*, TextIteratorBehavior = TextIteratorDefaultBehavior);
+    explicit CharacterIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
 
     void advance(int numCharacters);
 
@@ -311,8 +316,6 @@
     template<typename BufferType>
     void appendTextTo(BufferType& output) { m_textIterator.appendTextTo(output, m_runOffset); }
 
-    String string(int numChars);
-
     int characterOffset() const { return m_offset; }
     PassRefPtr<Range> range() const;
 
@@ -326,7 +329,7 @@
 
 class BackwardsCharacterIterator {
 public:
-    explicit BackwardsCharacterIterator(const Range*, TextIteratorBehavior = TextIteratorDefaultBehavior);
+    explicit BackwardsCharacterIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
 
     void advance(int);
 
@@ -356,9 +359,6 @@
     UChar characterAt(unsigned index) const;
     int length() const;
 
-    // Range of the text we're currently returning
-    PassRefPtr<Range> range() const { return m_range; }
-
 private:
     Vector<UChar> m_buffer;
     // Did we have to look ahead in the textIterator to confirm the current chunk?
diff --git a/Source/core/editing/TextIteratorTest.cpp b/Source/core/editing/TextIteratorTest.cpp
index 13c6e8c..0692414 100644
--- a/Source/core/editing/TextIteratorTest.cpp
+++ b/Source/core/editing/TextIteratorTest.cpp
@@ -117,6 +117,13 @@
     return result;
 }
 
+PassRefPtr<ShadowRoot> createShadowRootForElementWithIDAndSetInnerHTML(TreeScope& scope, const char* hostElementID, const char* shadowRootContent)
+{
+    RefPtr<ShadowRoot> shadowRoot = scope.getElementById(AtomicString::fromUTF8(hostElementID))->createShadowRoot(ASSERT_NO_EXCEPTION);
+    shadowRoot->setInnerHTML(String::fromUTF8(shadowRootContent), ASSERT_NO_EXCEPTION);
+    return shadowRoot.release();
+}
+
 TEST_F(TextIteratorTest, BasicIteration)
 {
     static const char* input = "<p>Hello, \ntext</p><p>iterator.</p>";
@@ -193,8 +200,7 @@
     Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
 
     setBodyInnerHTML(bodyContent);
-    RefPtr<ShadowRoot> shadowRoot = document().getElementById(AtomicString::fromUTF8("input"))->createShadowRoot(ASSERT_NO_EXCEPTION);
-    shadowRoot->setInnerHTML(String::fromUTF8(shadowContent), ASSERT_NO_EXCEPTION);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "input", shadowContent);
 
     EXPECT_EQ(expectedTextChunks, iterate());
 }
@@ -210,8 +216,7 @@
     Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
 
     setBodyInnerHTML(bodyContent);
-    RefPtr<ShadowRoot> shadowRoot = document().getElementById(AtomicString::fromUTF8("host"))->createShadowRoot(ASSERT_NO_EXCEPTION);
-    shadowRoot->setInnerHTML(String::fromUTF8(shadowContent), ASSERT_NO_EXCEPTION);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
 
     EXPECT_EQ(expectedTextChunks, iterate());
 }
@@ -228,11 +233,8 @@
     Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
 
     setBodyInnerHTML(bodyContent);
-    Element& host = *document().getElementById(AtomicString::fromUTF8("host"));
-    RefPtr<ShadowRoot> shadowRoot1 = host.createShadowRoot(ASSERT_NO_EXCEPTION);
-    shadowRoot1->setInnerHTML(String::fromUTF8(shadowContent1), ASSERT_NO_EXCEPTION);
-    RefPtr<ShadowRoot> shadowRoot2 = host.createShadowRoot(ASSERT_NO_EXCEPTION);
-    shadowRoot2->setInnerHTML(String::fromUTF8(shadowContent2), ASSERT_NO_EXCEPTION);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent1);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent2);
 
     EXPECT_EQ(expectedTextChunks, iterate());
 }
@@ -249,12 +251,8 @@
     Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
 
     setBodyInnerHTML(bodyContent);
-    Element& hostInDocument = *document().getElementById(AtomicString::fromUTF8("host-in-document"));
-    RefPtr<ShadowRoot> shadowRoot1 = hostInDocument.createShadowRoot(ASSERT_NO_EXCEPTION);
-    shadowRoot1->setInnerHTML(String::fromUTF8(shadowContent1), ASSERT_NO_EXCEPTION);
-    Element& hostInShadow = *shadowRoot1->getElementById(AtomicString::fromUTF8("host-in-shadow"));
-    RefPtr<ShadowRoot> shadowRoot2 = hostInShadow.createShadowRoot(ASSERT_NO_EXCEPTION);
-    shadowRoot2->setInnerHTML(String::fromUTF8(shadowContent2), ASSERT_NO_EXCEPTION);
+    RefPtr<ShadowRoot> shadowRoot1 = createShadowRootForElementWithIDAndSetInnerHTML(document(), "host-in-document", shadowContent1);
+    createShadowRootForElementWithIDAndSetInnerHTML(*shadowRoot1, "host-in-shadow", shadowContent2);
 
     EXPECT_EQ(expectedTextChunks, iterate());
 }
@@ -271,11 +269,163 @@
     Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
 
     setBodyInnerHTML(bodyContent);
-    Element& host = *document().getElementById(AtomicString::fromUTF8("host"));
-    RefPtr<ShadowRoot> shadowRoot = host.createShadowRoot(ASSERT_NO_EXCEPTION);
-    shadowRoot->setInnerHTML(String::fromUTF8(shadowContent), ASSERT_NO_EXCEPTION);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
 
     EXPECT_EQ(expectedTextChunks, iterate());
 }
 
+TEST_F(TextIteratorTest, EnteringShadowTreeWithOption)
+{
+    static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+    static const char* shadowContent = "<span>shadow</span>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello, ",
+        "shadow", // TextIterator emits "shadow" since TextIteratorEntersAuthorShadowRoots is specified.
+        " iterator."
+    };
+    Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+    EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, EnteringShadowTreeWithMultipleShadowTreesWithOption)
+{
+    static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+    static const char* shadowContent1 = "<span>first shadow</span>";
+    static const char* shadowContent2 = "<span>second shadow</span>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello, ",
+        "second shadow", // The first isn't emitted because a renderer for the first is not created.
+        " iterator."
+    };
+    Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent1);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent2);
+
+    EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, EnteringShadowTreeWithNestedShadowTreesWithOption)
+{
+    static const char* bodyContent = "<div>Hello, <span id=\"host-in-document\">text</span> iterator.</div>";
+    static const char* shadowContent1 = "<span>first <span id=\"host-in-shadow\">shadow</span></span>";
+    static const char* shadowContent2 = "<span>second shadow</span>";
+    static const char* expectedTextChunksRawString[] = {
+        "Hello, ",
+        "first ",
+        "second shadow",
+        " iterator."
+    };
+    Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    RefPtr<ShadowRoot> shadowRoot1 = createShadowRootForElementWithIDAndSetInnerHTML(document(), "host-in-document", shadowContent1);
+    createShadowRootForElementWithIDAndSetInnerHTML(*shadowRoot1, "host-in-shadow", shadowContent2);
+
+    EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, EnteringShadowTreeWithContentInsertionPointWithOption)
+{
+    static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+    static const char* shadowContent = "<span><content>content</content> shadow</span>";
+    // In this case a renderer for "text" is created, and emitted AFTER any nodes in the shadow tree.
+    // This order does not match the order of the rendered texts, but at this moment it's the expected behavior.
+    // FIXME: Fix this. We probably need pure-renderer-based implementation of TextIterator to achieve this.
+    static const char* expectedTextChunksRawString[] = {
+        "Hello, ",
+        " shadow",
+        "text",
+        " iterator."
+    };
+    Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+    EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, FullyClipsContents)
+{
+    static const char* bodyContent =
+        "<div style=\"overflow: hidden; width: 200px; height: 0;\">"
+        "I'm invisible"
+        "</div>";
+    Vector<String> expectedTextChunks; // Empty.
+
+    setBodyInnerHTML(bodyContent);
+    EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, IgnoresContainerClip)
+{
+    static const char* bodyContent =
+        "<div style=\"overflow: hidden; width: 200px; height: 0;\">"
+        "<div>I'm not visible</div>"
+        "<div style=\"position: absolute; width: 200px; height: 200px; top: 0; right: 0;\">"
+        "but I am!"
+        "</div>"
+        "</div>";
+    static const char* expectedTextChunksRawString[] = {
+        "but I am!"
+    };
+    Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, FullyClippedContentsDistributed)
+{
+    static const char* bodyContent =
+        "<div id=\"host\">"
+        "<div>Am I visible?</div>"
+        "</div>";
+    static const char* shadowContent =
+        "<div style=\"overflow: hidden; width: 200px; height: 0;\">"
+        "<content></content>"
+        "</div>";
+    static const char* expectedTextChunksRawString[] = {
+        "\n",
+        // FIXME: The text below is actually invisible but TextIterator currently thinks it's visible.
+        "Am I visible?"
+    };
+    Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+    setBodyInnerHTML(bodyContent);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+    EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, IgnoresContainersClipDistributed)
+{
+    static const char* bodyContent =
+        "<div id=\"host\" style=\"overflow: hidden; width: 200px; height: 0;\">"
+        "<div>Nobody can find me!</div>"
+        "</div>";
+    static const char* shadowContent =
+        "<div style=\"position: absolute; width: 200px; height: 200px; top: 0; right: 0;\">"
+        "<content></content>"
+        "</div>";
+    // FIXME: The text below is actually visible but TextIterator currently thinks it's invisible.
+    // static const char* expectedTextChunksRawString[] = {
+    //     "\n",
+    //     "Nobody can find me!"
+    // };
+    // Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+    Vector<String> expectedTextChunks; // Empty.
+
+    setBodyInnerHTML(bodyContent);
+    createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+    EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
 }
diff --git a/Source/core/editing/TypingCommand.cpp b/Source/core/editing/TypingCommand.cpp
index 46e1e7d..709bb88 100644
--- a/Source/core/editing/TypingCommand.cpp
+++ b/Source/core/editing/TypingCommand.cpp
@@ -29,6 +29,7 @@
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/editing/BreakBlockquoteCommand.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
@@ -381,10 +382,13 @@
     if (!root || !root->firstChild())
         return false;
 
-    if (root->firstChild() == root->lastChild() && root->firstElementChild() && root->firstElementChild()->hasTagName(brTag)) {
-        // If there is a single child and it could be a placeholder, leave it alone.
-        if (root->renderer() && root->renderer()->isRenderBlockFlow())
-            return false;
+    if (root->firstChild() == root->lastChild()) {
+        Element* firstElementChild = ElementTraversal::firstWithin(*root);
+        if (firstElementChild && firstElementChild->hasTagName(brTag)) {
+            // If there is a single child and it could be a placeholder, leave it alone.
+            if (root->renderer() && root->renderer()->isRenderBlockFlow())
+                return false;
+        }
     }
 
     while (Node* child = root->firstChild())
@@ -426,20 +430,20 @@
         if (killRing && selection.isCaret() && granularity != CharacterGranularity)
             selection.modify(FrameSelection::AlterationExtend, DirectionBackward, CharacterGranularity);
 
-        if (endingSelection().visibleStart().previous(CannotCrossEditingBoundary).isNull()) {
+        VisiblePosition visibleStart(endingSelection().visibleStart());
+        if (visibleStart.previous(CannotCrossEditingBoundary).isNull()) {
             // When the caret is at the start of the editable area in an empty list item, break out of the list item.
             if (breakOutOfEmptyListItem()) {
                 typingAddedToOpenCommand(DeleteKey);
                 return;
             }
             // When there are no visible positions in the editing root, delete its entire contents.
-            if (endingSelection().visibleStart().next(CannotCrossEditingBoundary).isNull() && makeEditableRootEmpty()) {
+            if (visibleStart.next(CannotCrossEditingBoundary).isNull() && makeEditableRootEmpty()) {
                 typingAddedToOpenCommand(DeleteKey);
                 return;
             }
         }
 
-        VisiblePosition visibleStart(endingSelection().visibleStart());
         // If we have a caret selection at the beginning of a cell, we have nothing to do.
         Node* enclosingTableCell = enclosingNodeOfType(visibleStart.deepEquivalent(), &isTableCell);
         if (enclosingTableCell && visibleStart == firstPositionInNode(enclosingTableCell))
diff --git a/Source/core/editing/TypingCommand.h b/Source/core/editing/TypingCommand.h
index 05032ab..ea4612e 100644
--- a/Source/core/editing/TypingCommand.h
+++ b/Source/core/editing/TypingCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class TypingCommand : public TextInsertionBaseCommand {
+class TypingCommand FINAL : public TextInsertionBaseCommand {
 public:
     enum ETypingCommand {
         DeleteSelection,
@@ -90,24 +90,18 @@
 
     TypingCommand(Document&, ETypingCommand, const String& text, Options, TextGranularity, TextCompositionType);
 
-    bool smartDelete() const { return m_smartDelete; }
     void setSmartDelete(bool smartDelete) { m_smartDelete = smartDelete; }
     bool isOpenForMoreTyping() const { return m_openForMoreTyping; }
     void closeTyping() { m_openForMoreTyping = false; }
 
     static PassRefPtr<TypingCommand> lastTypingCommandIfStillOpenForTyping(Frame*);
 
-    virtual void doApply();
-    virtual EditAction editingAction() const;
-    virtual bool isTypingCommand() const;
-    virtual bool preservesTypingStyle() const { return m_preservesTypingStyle; }
-    virtual bool shouldRetainAutocorrectionIndicator() const
-    {
-        ASSERT(isTopLevelCommand());
-        return m_shouldRetainAutocorrectionIndicator;
-    }
-    virtual void setShouldRetainAutocorrectionIndicator(bool retain) { m_shouldRetainAutocorrectionIndicator = retain; }
-    virtual bool shouldStopCaretBlinking() const { return true; }
+    virtual void doApply() OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE;
+    virtual bool isTypingCommand() const OVERRIDE;
+    virtual bool preservesTypingStyle() const OVERRIDE { return m_preservesTypingStyle; }
+    virtual void setShouldRetainAutocorrectionIndicator(bool retain) OVERRIDE { m_shouldRetainAutocorrectionIndicator = retain; }
+    virtual bool shouldStopCaretBlinking() const OVERRIDE { return true; }
     void setShouldPreventSpellChecking(bool prevent) { m_shouldPreventSpellChecking = prevent; }
 
     static void updateSelectionIfDifferentFromCurrentSelection(TypingCommand*, Frame*);
diff --git a/Source/core/editing/UnlinkCommand.h b/Source/core/editing/UnlinkCommand.h
index d6b8d17..aebc5ab 100644
--- a/Source/core/editing/UnlinkCommand.h
+++ b/Source/core/editing/UnlinkCommand.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class UnlinkCommand : public CompositeEditCommand {
+class UnlinkCommand FINAL : public CompositeEditCommand {
 public:
     static PassRefPtr<UnlinkCommand> create(Document& document)
     {
@@ -40,8 +40,8 @@
 private:
     explicit UnlinkCommand(Document&);
 
-    virtual void doApply();
-    virtual EditAction editingAction() const { return EditActionUnlink; }
+    virtual void doApply() OVERRIDE;
+    virtual EditAction editingAction() const OVERRIDE { return EditActionUnlink; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/editing/VisiblePosition.cpp b/Source/core/editing/VisiblePosition.cpp
index b158125..71205fd 100644
--- a/Source/core/editing/VisiblePosition.cpp
+++ b/Source/core/editing/VisiblePosition.cpp
@@ -35,7 +35,6 @@
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/html/HTMLElement.h"
-#include "core/html/HTMLHtmlElement.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RootInlineBox.h"
 #include "platform/geometry/FloatQuad.h"
@@ -592,14 +591,14 @@
 
     // The new position must be in the same editable element. Enforce that first.
     // Unless the descent is from a non-editable html element to an editable body.
-    if (node && isHTMLHtmlElement(node) && !node->rendererIsEditable() && node->document().body() && node->document().body()->rendererIsEditable())
+    if (node && node->hasTagName(htmlTag) && !node->rendererIsEditable() && node->document().body() && node->document().body()->rendererIsEditable())
         return next.isNotNull() ? next : prev;
 
     Node* editingRoot = editableRootForPosition(position);
 
     // If the html element is editable, descending into its body will look like a descent
     // from non-editable to editable content since rootEditableElement() always stops at the body.
-    if ((editingRoot && isHTMLHtmlElement(editingRoot)) || position.deprecatedNode()->isDocumentNode())
+    if ((editingRoot && editingRoot->hasTagName(htmlTag)) || position.deprecatedNode()->isDocumentNode())
         return next.isNotNull() ? next : prev;
 
     bool prevIsInSameEditableElement = prevNode && editableRootForPosition(prev) == editingRoot;
@@ -739,11 +738,6 @@
     return VisiblePosition(r->startPosition(), affinity);
 }
 
-VisiblePosition endVisiblePosition(const Range *r, EAffinity affinity)
-{
-    return VisiblePosition(r->endPosition(), affinity);
-}
-
 bool setStart(Range *r, const VisiblePosition &visiblePosition)
 {
     if (!r)
diff --git a/Source/core/editing/VisiblePosition.h b/Source/core/editing/VisiblePosition.h
index f482450..bb684c3 100644
--- a/Source/core/editing/VisiblePosition.h
+++ b/Source/core/editing/VisiblePosition.h
@@ -90,11 +90,6 @@
         m_deepPosition.getInlineBoxAndOffset(m_affinity, inlineBox, caretOffset);
     }
 
-    void getInlineBoxAndOffset(TextDirection primaryDirection, InlineBox*& inlineBox, int& caretOffset) const
-    {
-        m_deepPosition.getInlineBoxAndOffset(m_affinity, primaryDirection, inlineBox, caretOffset);
-    }
-
     // Rect is local to the returned renderer
     LayoutRect localCaretRect(RenderObject*&) const;
     // Bounds of (possibly transformed) caret in absolute coords
@@ -135,7 +130,6 @@
 bool setStart(Range*, const VisiblePosition&);
 bool setEnd(Range*, const VisiblePosition&);
 VisiblePosition startVisiblePosition(const Range*, EAffinity);
-VisiblePosition endVisiblePosition(const Range*, EAffinity);
 
 Element* enclosingBlockFlowElement(const VisiblePosition&);
 
diff --git a/Source/core/editing/VisibleSelection.cpp b/Source/core/editing/VisibleSelection.cpp
index 418c103..2330625 100644
--- a/Source/core/editing/VisibleSelection.cpp
+++ b/Source/core/editing/VisibleSelection.cpp
@@ -230,11 +230,6 @@
     return searchRange.release();
 }
 
-bool VisibleSelection::isAll(EditingBoundaryCrossingRule rule) const
-{
-    return !nonBoundaryShadowTreeRootNode() && visibleStart().previous(rule).isNull() && visibleEnd().next(rule).isNull();
-}
-
 void VisibleSelection::appendTrailingWhitespace()
 {
     RefPtr<Range> searchRange = makeSearchRange(m_end);
@@ -479,7 +474,7 @@
         return positionBeforeNode(ancestor);
     }
 
-    if (Node* lastChild = treeScope.rootNode()->lastChild())
+    if (Node* lastChild = treeScope.rootNode().lastChild())
         return positionAfterNode(lastChild);
 
     return Position();
@@ -497,7 +492,7 @@
         return positionAfterNode(ancestor);
     }
 
-    if (Node* firstChild = treeScope.rootNode()->firstChild())
+    if (Node* firstChild = treeScope.rootNode().firstChild())
         return positionBeforeNode(firstChild);
 
     return Position();
diff --git a/Source/core/editing/VisibleSelection.h b/Source/core/editing/VisibleSelection.h
index e5e9dd0..dd97eb7 100644
--- a/Source/core/editing/VisibleSelection.h
+++ b/Source/core/editing/VisibleSelection.h
@@ -83,8 +83,6 @@
     bool isDirectional() const { return m_isDirectional; }
     void setIsDirectional(bool isDirectional) { m_isDirectional = isDirectional; }
 
-    bool isAll(EditingBoundaryCrossingRule) const;
-
     void appendTrailingWhitespace();
 
     bool expandUsingGranularity(TextGranularity granularity);
diff --git a/Source/core/editing/VisibleUnits.cpp b/Source/core/editing/VisibleUnits.cpp
index 1f39b48..49923bf 100644
--- a/Source/core/editing/VisibleUnits.cpp
+++ b/Source/core/editing/VisibleUnits.cpp
@@ -704,11 +704,6 @@
     return c.honorEditingBoundaryAtOrAfter(next);
 }
 
-bool isStartOfWord(const VisiblePosition& p)
-{
-    return p.isNotNull() && p == startOfWord(p, RightWordIfOnBoundary);
-}
-
 // ---------
 
 enum LineEndpointComputationMode { UseLogicalOrdering, UseInlineBoxOrdering };
@@ -1359,20 +1354,6 @@
     return endOfDocument(c.deepEquivalent().deprecatedNode());
 }
 
-bool inSameDocument(const VisiblePosition &a, const VisiblePosition &b)
-{
-    Position ap = a.deepEquivalent();
-    Node* an = ap.deprecatedNode();
-    if (!an)
-        return false;
-    Position bp = b.deepEquivalent();
-    Node* bn = bp.deprecatedNode();
-    if (an == bn)
-        return true;
-
-    return an->document() == bn->document();
-}
-
 bool isStartOfDocument(const VisiblePosition &p)
 {
     return p.isNotNull() && p.previous(CanCrossEditingBoundary).isNull();
diff --git a/Source/core/editing/VisibleUnits.h b/Source/core/editing/VisibleUnits.h
index 598990b..825c3aa 100644
--- a/Source/core/editing/VisibleUnits.h
+++ b/Source/core/editing/VisibleUnits.h
@@ -43,7 +43,6 @@
 VisiblePosition nextWordPosition(const VisiblePosition &);
 VisiblePosition rightWordPosition(const VisiblePosition&, bool skipsSpaceWhenMovingRight);
 VisiblePosition leftWordPosition(const VisiblePosition&, bool skipsSpaceWhenMovingRight);
-bool isStartOfWord(const VisiblePosition&);
 
 // sentences
 VisiblePosition startOfSentence(const VisiblePosition &);
@@ -86,7 +85,6 @@
 VisiblePosition endOfDocument(const Node*);
 VisiblePosition startOfDocument(const VisiblePosition &);
 VisiblePosition endOfDocument(const VisiblePosition &);
-bool inSameDocument(const VisiblePosition &, const VisiblePosition &);
 bool isStartOfDocument(const VisiblePosition &);
 bool isEndOfDocument(const VisiblePosition &);
 
diff --git a/Source/core/editing/WrapContentsInDummySpanCommand.h b/Source/core/editing/WrapContentsInDummySpanCommand.h
index be7f4b6..7cdcb2f 100644
--- a/Source/core/editing/WrapContentsInDummySpanCommand.h
+++ b/Source/core/editing/WrapContentsInDummySpanCommand.h
@@ -32,7 +32,7 @@
 
 class HTMLElement;
 
-class WrapContentsInDummySpanCommand : public SimpleEditCommand {
+class WrapContentsInDummySpanCommand FINAL : public SimpleEditCommand {
 public:
     static PassRefPtr<WrapContentsInDummySpanCommand> create(PassRefPtr<Element> element)
     {
diff --git a/Source/core/editing/htmlediting.cpp b/Source/core/editing/htmlediting.cpp
index 6c00bb5..7d8591f 100644
--- a/Source/core/editing/htmlediting.cpp
+++ b/Source/core/editing/htmlediting.cpp
@@ -48,7 +48,6 @@
 #include "core/html/HTMLLIElement.h"
 #include "core/html/HTMLOListElement.h"
 #include "core/html/HTMLParagraphElement.h"
-#include "core/html/HTMLTableElement.h"
 #include "core/html/HTMLUListElement.h"
 #include "core/frame/Frame.h"
 #include "core/rendering/RenderObject.h"
@@ -159,7 +158,7 @@
     else
         ASSERT(updateStyle == DoNotUpdateStyle);
 
-    if (isTableElement(node))
+    if (isRenderedTableElement(node))
         node = node->parentNode();
 
     return node->rendererIsEditable(editableType);
@@ -178,7 +177,7 @@
     if (!node)
         return false;
 
-    if (isTableElement(node))
+    if (isRenderedTableElement(node))
         node = node->parentNode();
 
     return node->rendererIsRichlyEditable(editableType);
@@ -190,7 +189,7 @@
     if (!node)
         return 0;
 
-    if (isTableElement(node))
+    if (isRenderedTableElement(node))
         node = node->parentNode();
 
     return node->rootEditableElement(editableType);
@@ -680,30 +679,6 @@
     return 0;
 }
 
-static HTMLElement* embeddedSublist(Node* listItem)
-{
-    // Check the DOM so that we'll find collapsed sublists without renderers.
-    for (Node* n = listItem->firstChild(); n; n = n->nextSibling()) {
-        if (isListElement(n))
-            return toHTMLElement(n);
-    }
-
-    return 0;
-}
-
-static Node* appendedSublist(Node* listItem)
-{
-    // Check the DOM so that we'll find collapsed sublists without renderers.
-    for (Node* n = listItem->nextSibling(); n; n = n->nextSibling()) {
-        if (isListElement(n))
-            return toHTMLElement(n);
-        if (isListItem(listItem))
-            return 0;
-    }
-
-    return 0;
-}
-
 // FIXME: This method should not need to call isStartOfParagraph/isEndOfParagraph
 Node* enclosingEmptyListItem(const VisiblePosition& visiblePos)
 {
@@ -718,9 +693,6 @@
     if (firstInListChild != visiblePos || lastInListChild != visiblePos)
         return 0;
 
-    if (embeddedSublist(listChildNode) || appendedSublist(listChildNode))
-        return 0;
-
     return listChildNode;
 }
 
@@ -751,12 +723,12 @@
     // Make sure there is no visible content between this li and the previous list
 }
 
-bool isTableElement(const Node* node)
+bool isRenderedTableElement(const Node* node)
 {
     if (!node || !node->isElementNode())
         return false;
 
-    return node->hasTagName(tableTag);
+    return node->renderer() && node->hasTagName(tableTag);
 }
 
 bool isRenderedTable(const Node* node)
@@ -868,20 +840,6 @@
     return isTabSpanTextNode(node) ? node->parentNode() : 0;
 }
 
-Position positionOutsideTabSpan(const Position& pos)
-{
-    Node* node = pos.containerNode();
-    if (isTabSpanTextNode(node))
-        node = tabSpanNode(node);
-    else if (!isTabSpanNode(node))
-        return pos;
-
-    if (node && VisiblePosition(pos) == lastPositionInNode(node))
-        return positionInParentAfterNode(node);
-
-    return positionInParentBeforeNode(node);
-}
-
 PassRefPtr<Element> createTabSpanElement(Document& document, PassRefPtr<Node> prpTabTextNode)
 {
     RefPtr<Node> tabTextNode = prpTabTextNode;
@@ -1131,7 +1089,7 @@
     return node->hasTagName(listingTag)
         || node->hasTagName(olTag)
         || node->hasTagName(preTag)
-        || isHTMLTableElement(node)
+        || node->hasTagName(tableTag)
         || node->hasTagName(ulTag)
         || node->hasTagName(xmpTag)
         || node->hasTagName(h1Tag)
diff --git a/Source/core/editing/htmlediting.h b/Source/core/editing/htmlediting.h
index 1d7e52c..5439bc0 100644
--- a/Source/core/editing/htmlediting.h
+++ b/Source/core/editing/htmlediting.h
@@ -102,7 +102,7 @@
 bool isTabSpanTextNode(const Node*);
 bool isMailBlockquote(const Node*);
 bool isRenderedTable(const Node*);
-bool isTableElement(const Node*);
+bool isRenderedTableElement(const Node*);
 bool isTableCell(const Node*);
 bool isEmptyTableCell(const Node*);
 bool isTableStructureNode(const Node*);
@@ -127,7 +127,6 @@
 Position nextVisuallyDistinctCandidate(const Position&);
 Position previousVisuallyDistinctCandidate(const Position&);
 
-Position positionOutsideTabSpan(const Position&);
 Position positionBeforeContainingSpecialElement(const Position&, Node** containingSpecialElement = 0);
 Position positionAfterContainingSpecialElement(const Position&, Node** containingSpecialElement = 0);
 
@@ -153,6 +152,10 @@
 // boolean functions on Position
 
 enum EUpdateStyle { UpdateStyle, DoNotUpdateStyle };
+// FIXME: Both isEditablePosition and isRichlyEditablePosition rely on up-to-date
+// style to give proper results. They shouldn't update style by default, but
+// should make it clear that that is the contract.
+// FIXME: isRichlyEditablePosition should also take EUpdateStyle.
 bool isEditablePosition(const Position&, EditableType = ContentIsEditable, EUpdateStyle = UpdateStyle);
 bool isRichlyEditablePosition(const Position&, EditableType = ContentIsEditable);
 bool lineBreakExistsAtPosition(const Position&);
diff --git a/Source/core/editing/markup.cpp b/Source/core/editing/markup.cpp
index 184ed05..ce74846 100644
--- a/Source/core/editing/markup.cpp
+++ b/Source/core/editing/markup.cpp
@@ -52,8 +52,6 @@
 #include "core/editing/htmlediting.h"
 #include "core/html/HTMLBodyElement.h"
 #include "core/html/HTMLElement.h"
-#include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLTableElement.h"
 #include "core/html/HTMLTextFormControlElement.h"
 #include "core/frame/Frame.h"
 #include "core/rendering/RenderObject.h"
@@ -114,33 +112,33 @@
         changes[i].apply();
 }
 
-class StyledMarkupAccumulator : public MarkupAccumulator {
+class StyledMarkupAccumulator FINAL : public MarkupAccumulator {
 public:
     enum RangeFullySelectsNode { DoesFullySelectNode, DoesNotFullySelectNode };
 
     StyledMarkupAccumulator(Vector<Node*>* nodes, EAbsoluteURLs, EAnnotateForInterchange, const Range*, Node* highestNodeToBeSerialized = 0);
     Node* serializeNodes(Node* startNode, Node* pastEnd);
-    virtual void appendString(const String& s) { return MarkupAccumulator::appendString(s); }
-    void wrapWithNode(Node*, bool convertBlocksToInlines = false, RangeFullySelectsNode = DoesFullySelectNode);
-    void wrapWithStyleNode(StylePropertySet*, Document*, bool isBlock = false);
+    void appendString(const String& s) { return MarkupAccumulator::appendString(s); }
+    void wrapWithNode(Node&, bool convertBlocksToInlines = false, RangeFullySelectsNode = DoesFullySelectNode);
+    void wrapWithStyleNode(StylePropertySet*, const Document&, bool isBlock = false);
     String takeResults();
 
 private:
-    void appendStyleNodeOpenTag(StringBuilder&, StylePropertySet*, Document*, bool isBlock = false);
+    void appendStyleNodeOpenTag(StringBuilder&, StylePropertySet*, const Document&, bool isBlock = false);
     const String& styleNodeCloseTag(bool isBlock = false);
-    virtual void appendText(StringBuilder& out, Text*);
-    String renderedText(const Node*, const Range*);
-    String stringValueForRange(const Node*, const Range*);
-    void appendElement(StringBuilder& out, Element*, bool addDisplayInline, RangeFullySelectsNode);
-    void appendElement(StringBuilder& out, Element* element, Namespaces*) { appendElement(out, element, false, DoesFullySelectNode); }
+    virtual void appendText(StringBuilder& out, Text&) OVERRIDE;
+    String renderedText(Node&, const Range*);
+    String stringValueForRange(const Node&, const Range*);
+    void appendElement(StringBuilder& out, Element&, bool addDisplayInline, RangeFullySelectsNode);
+    virtual void appendElement(StringBuilder& out, Element& element, Namespaces*) OVERRIDE { appendElement(out, element, false, DoesFullySelectNode); }
 
     enum NodeTraversalMode { EmitString, DoNotEmitString };
     Node* traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode);
 
     bool shouldAnnotate() { return m_shouldAnnotate == AnnotateForInterchange; }
-    bool shouldApplyWrappingStyle(Node* node) const
+    bool shouldApplyWrappingStyle(const Node& node) const
     {
-        return m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode() == node->parentNode()
+        return m_highestNodeToBeSerialized && m_highestNodeToBeSerialized->parentNode() == node.parentNode()
             && m_wrappingStyle && m_wrappingStyle->style();
     }
 
@@ -158,20 +156,20 @@
 {
 }
 
-void StyledMarkupAccumulator::wrapWithNode(Node* node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode)
+void StyledMarkupAccumulator::wrapWithNode(Node& node, bool convertBlocksToInlines, RangeFullySelectsNode rangeFullySelectsNode)
 {
     StringBuilder markup;
-    if (node->isElementNode())
-        appendElement(markup, toElement(node), convertBlocksToInlines && isBlock(const_cast<Node*>(node)), rangeFullySelectsNode);
+    if (node.isElementNode())
+        appendElement(markup, toElement(node), convertBlocksToInlines && isBlock(&node), rangeFullySelectsNode);
     else
         appendStartMarkup(markup, node, 0);
     m_reversedPrecedingMarkup.append(markup.toString());
     appendEndTag(node);
     if (m_nodes)
-        m_nodes->append(node);
+        m_nodes->append(&node);
 }
 
-void StyledMarkupAccumulator::wrapWithStyleNode(StylePropertySet* style, Document* document, bool isBlock)
+void StyledMarkupAccumulator::wrapWithStyleNode(StylePropertySet* style, const Document& document, bool isBlock)
 {
     StringBuilder openTag;
     appendStyleNodeOpenTag(openTag, style, document, isBlock);
@@ -179,7 +177,7 @@
     appendString(styleNodeCloseTag(isBlock));
 }
 
-void StyledMarkupAccumulator::appendStyleNodeOpenTag(StringBuilder& out, StylePropertySet* style, Document* document, bool isBlock)
+void StyledMarkupAccumulator::appendStyleNodeOpenTag(StringBuilder& out, StylePropertySet* style, const Document& document, bool isBlock)
 {
     // wrappingStyleForSerialization should have removed -webkit-text-decorations-in-effect
     ASSERT(propertyMissingOrEqualToNone(style, CSSPropertyWebkitTextDecorationsInEffect));
@@ -187,9 +185,8 @@
         out.appendLiteral("<div style=\"");
     else
         out.appendLiteral("<span style=\"");
-    appendAttributeValue(out, style->asText(), document->isHTMLDocument());
-    out.append('\"');
-    out.append('>');
+    appendAttributeValue(out, style->asText(), document.isHTMLDocument());
+    out.appendLiteral("\">");
 }
 
 const String& StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock)
@@ -213,9 +210,9 @@
     return result.toString().replace(0, "");
 }
 
-void StyledMarkupAccumulator::appendText(StringBuilder& out, Text* text)
+void StyledMarkupAccumulator::appendText(StringBuilder& out, Text& text)
 {
-    const bool parentIsTextarea = text->parentElement() && text->parentElement()->tagQName() == textareaTag;
+    const bool parentIsTextarea = text.parentElement() && text.parentElement()->tagQName() == textareaTag;
     const bool wrappingSpan = shouldApplyWrappingStyle(text) && !parentIsTextarea;
     if (wrappingSpan) {
         RefPtr<EditingStyle> wrappingStyle = m_wrappingStyle->copy();
@@ -225,13 +222,13 @@
         // FIXME: Should this be included in forceInline?
         wrappingStyle->style()->setProperty(CSSPropertyFloat, CSSValueNone);
 
-        appendStyleNodeOpenTag(out, wrappingStyle->style(), &text->document());
+        appendStyleNodeOpenTag(out, wrappingStyle->style(), text.document());
     }
 
     if (!shouldAnnotate() || parentIsTextarea)
         MarkupAccumulator::appendText(out, text);
     else {
-        const bool useRenderedText = !enclosingNodeWithTag(firstPositionInNode(text), selectTag);
+        const bool useRenderedText = !enclosingNodeWithTag(firstPositionInNode(&text), selectTag);
         String content = useRenderedText ? renderedText(text, m_range) : stringValueForRange(text, m_range);
         StringBuilder buffer;
         appendCharactersReplacingEntities(buffer, content, 0, content.length(), EntityMaskInPCDATA);
@@ -242,31 +239,31 @@
         out.append(styleNodeCloseTag());
 }
 
-String StyledMarkupAccumulator::renderedText(const Node* node, const Range* range)
+String StyledMarkupAccumulator::renderedText(Node& node, const Range* range)
 {
-    if (!node->isTextNode())
+    if (!node.isTextNode())
         return String();
 
-    const Text* textNode = toText(node);
+    const Text& textNode = toText(node);
     unsigned startOffset = 0;
-    unsigned endOffset = textNode->length();
+    unsigned endOffset = textNode.length();
 
     if (range && node == range->startContainer())
         startOffset = range->startOffset();
     if (range && node == range->endContainer())
         endOffset = range->endOffset();
 
-    Position start = createLegacyEditingPosition(const_cast<Node*>(node), startOffset);
-    Position end = createLegacyEditingPosition(const_cast<Node*>(node), endOffset);
-    return plainText(Range::create(node->document(), start, end).get());
+    Position start = createLegacyEditingPosition(&node, startOffset);
+    Position end = createLegacyEditingPosition(&node, endOffset);
+    return plainText(Range::create(node.document(), start, end).get());
 }
 
-String StyledMarkupAccumulator::stringValueForRange(const Node* node, const Range* range)
+String StyledMarkupAccumulator::stringValueForRange(const Node& node, const Range* range)
 {
     if (!range)
-        return node->nodeValue();
+        return node.nodeValue();
 
-    String str = node->nodeValue();
+    String str = node.nodeValue();
     if (node == range->endContainer())
         str.truncate(range->endOffset());
     if (node == range->startContainer())
@@ -274,16 +271,16 @@
     return str;
 }
 
-void StyledMarkupAccumulator::appendElement(StringBuilder& out, Element* element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
+void StyledMarkupAccumulator::appendElement(StringBuilder& out, Element& element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
 {
-    const bool documentIsHTML = element->document().isHTMLDocument();
+    const bool documentIsHTML = element.document().isHTMLDocument();
     appendOpenTag(out, element, 0);
 
-    const unsigned length = element->hasAttributes() ? element->attributeCount() : 0;
-    const bool shouldAnnotateOrForceInline = element->isHTMLElement() && (shouldAnnotate() || addDisplayInline);
+    const unsigned length = element.hasAttributes() ? element.attributeCount() : 0;
+    const bool shouldAnnotateOrForceInline = element.isHTMLElement() && (shouldAnnotate() || addDisplayInline);
     const bool shouldOverrideStyleAttr = shouldAnnotateOrForceInline || shouldApplyWrappingStyle(element);
     for (unsigned i = 0; i < length; ++i) {
-        const Attribute* attribute = element->attributeItem(i);
+        const Attribute* attribute = element.attributeItem(i);
         // We'll handle the style attribute separately, below.
         if (attribute->name() == styleAttr && shouldOverrideStyleAttr)
             continue;
@@ -295,17 +292,17 @@
 
         if (shouldApplyWrappingStyle(element)) {
             newInlineStyle = m_wrappingStyle->copy();
-            newInlineStyle->removePropertiesInElementDefaultStyle(element);
-            newInlineStyle->removeStyleConflictingWithStyleOfNode(element);
+            newInlineStyle->removePropertiesInElementDefaultStyle(&element);
+            newInlineStyle->removeStyleConflictingWithStyleOfNode(&element);
         } else
             newInlineStyle = EditingStyle::create();
 
-        if (element->isStyledElement() && element->inlineStyle())
-            newInlineStyle->overrideWithStyle(element->inlineStyle());
+        if (element.isStyledElement() && element.inlineStyle())
+            newInlineStyle->overrideWithStyle(element.inlineStyle());
 
         if (shouldAnnotateOrForceInline) {
             if (shouldAnnotate())
-                newInlineStyle->mergeStyleFromRulesForSerialization(toHTMLElement(element));
+                newInlineStyle->mergeStyleFromRulesForSerialization(&toHTMLElement(element));
 
             if (addDisplayInline)
                 newInlineStyle->forceInline();
@@ -369,12 +366,12 @@
         } else {
             // Add the node to the markup if we're not skipping the descendants
             if (shouldEmit)
-                appendStartTag(n);
+                appendStartTag(*n);
 
             // If node has no children, close the tag now.
             if (!n->childNodeCount()) {
                 if (shouldEmit)
-                    appendEndTag(n);
+                    appendEndTag(*n);
                 lastClosed = n;
             } else {
                 openedTag = true;
@@ -388,11 +385,12 @@
             // Close up the ancestors.
             while (!ancestorsToClose.isEmpty()) {
                 Node* ancestor = ancestorsToClose.last();
+                ASSERT(ancestor);
                 if (next != pastEnd && next->isDescendantOf(ancestor))
                     break;
                 // Not at the end of the range, close ancestors up to sibling of next node.
                 if (shouldEmit)
-                    appendEndTag(ancestor);
+                    appendEndTag(*ancestor);
                 lastClosed = ancestor;
                 ancestorsToClose.removeLast();
             }
@@ -408,7 +406,7 @@
                     // or b) ancestors that we never encountered during a pre-order traversal starting at startNode:
                     ASSERT(startNode->isDescendantOf(parent));
                     if (shouldEmit)
-                        wrapWithNode(parent);
+                        wrapWithNode(*parent);
                     lastClosed = parent;
                 }
             }
@@ -432,7 +430,7 @@
 
     if (commonAncestorBlock->hasTagName(tbodyTag) || commonAncestorBlock->hasTagName(trTag)) {
         ContainerNode* table = commonAncestorBlock->parentNode();
-        while (table && !isHTMLTableElement(table))
+        while (table && !table->hasTagName(tableTag))
             table = table->parentNode();
 
         return table;
@@ -603,18 +601,16 @@
                         fullySelectedRootStyle->style()->setProperty(CSSPropertyTextDecoration, CSSValueNone);
                     if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyWebkitTextDecorationsInEffect))
                         fullySelectedRootStyle->style()->setProperty(CSSPropertyWebkitTextDecorationsInEffect, CSSValueNone);
-                    accumulator.wrapWithStyleNode(fullySelectedRootStyle->style(), &document, true);
+                    accumulator.wrapWithStyleNode(fullySelectedRootStyle->style(), document, true);
                 }
             } else {
                 // Since this node and all the other ancestors are not in the selection we want to set RangeFullySelectsNode to DoesNotFullySelectNode
                 // so that styles that affect the exterior of the node are not included.
-                accumulator.wrapWithNode(ancestor, convertBlocksToInlines, StyledMarkupAccumulator::DoesNotFullySelectNode);
+                accumulator.wrapWithNode(*ancestor, convertBlocksToInlines, StyledMarkupAccumulator::DoesNotFullySelectNode);
             }
             if (nodes)
                 nodes->append(ancestor);
 
-            lastClosed = ancestor;
-
             if (ancestor == specialCommonAncestor)
                 break;
         }
@@ -743,7 +739,7 @@
         return "";
 
     MarkupAccumulator accumulator(nodes, shouldResolveURLs);
-    return accumulator.serializeNodes(const_cast<Node*>(node), childrenOnly, tagNamesToSkip);
+    return accumulator.serializeNodes(const_cast<Node&>(*node), childrenOnly, tagNamesToSkip);
 }
 
 static void fillContainerFromString(ContainerNode* paragraph, const String& string)
@@ -759,7 +755,7 @@
 
     Vector<String> tabList;
     string.split('\t', true, tabList);
-    String tabText = emptyString();
+    StringBuilder tabText;
     bool first = true;
     size_t numEntries = tabList.size();
     for (size_t i = 0; i < numEntries; ++i) {
@@ -768,8 +764,8 @@
         // append the non-tab textual part
         if (!s.isEmpty()) {
             if (!tabText.isEmpty()) {
-                paragraph->appendChild(createTabSpanElement(document, tabText));
-                tabText = emptyString();
+                paragraph->appendChild(createTabSpanElement(document, tabText.toString()));
+                tabText.clear();
             }
             RefPtr<Node> textNode = document.createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
             paragraph->appendChild(textNode.release());
@@ -780,7 +776,7 @@
         if (i + 1 != numEntries)
             tabText.append('\t');
         else if (!tabText.isEmpty())
-            paragraph->appendChild(createTabSpanElement(document, tabText));
+            paragraph->appendChild(createTabSpanElement(document, tabText.toString()));
 
         first = false;
     }
@@ -849,7 +845,7 @@
     bool useClonesOfEnclosingBlock = blockNode
         && blockNode->isElementNode()
         && !block->hasTagName(bodyTag)
-        && !isHTMLHtmlElement(block)
+        && !block->hasTagName(htmlTag)
         && block != editableRootForPosition(context->startPosition());
     bool useLineBreak = enclosingTextFormControl(context->startPosition());
 
@@ -879,23 +875,6 @@
     return fragment.release();
 }
 
-PassRefPtr<DocumentFragment> createFragmentFromNodes(Document *document, const Vector<Node*>& nodes)
-{
-    if (!document)
-        return 0;
-
-    RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
-
-    size_t size = nodes.size();
-    for (size_t i = 0; i < size; ++i) {
-        RefPtr<Element> element = createDefaultParagraphElement(*document);
-        element->appendChild(nodes[i]);
-        fragment->appendChild(element.release());
-    }
-
-    return fragment.release();
-}
-
 String createFullMarkup(const Node* node)
 {
     if (!node)
@@ -908,37 +887,20 @@
     // FIXME: This is never "for interchange". Is that right?
     String markupString = createMarkup(node, IncludeNode, 0);
     Node::NodeType nodeType = node->nodeType();
-    if (nodeType != Node::DOCUMENT_NODE && nodeType != Node::DOCUMENT_TYPE_NODE)
+    if (nodeType != Node::DOCUMENT_NODE && !node->isDocumentTypeNode())
         markupString = frame->documentTypeString() + markupString;
 
     return markupString;
 }
 
-String createFullMarkup(const Range* range)
-{
-    if (!range)
-        return String();
-
-    Node* node = range->startContainer();
-    if (!node)
-        return String();
-
-    Frame* frame = node->document().frame();
-    if (!frame)
-        return String();
-
-    // FIXME: This is always "for interchange". Is that right? See the previous method.
-    return frame->documentTypeString() + createMarkup(range, 0, AnnotateForInterchange);
-}
-
 String urlToMarkup(const KURL& url, const String& title)
 {
     StringBuilder markup;
-    markup.append("<a href=\"");
+    markup.appendLiteral("<a href=\"");
     markup.append(url.string());
-    markup.append("\">");
+    markup.appendLiteral("\">");
     MarkupAccumulator::appendCharactersReplacingEntities(markup, title, 0, title.length(), EntityMaskInPCDATA);
-    markup.append("</a>");
+    markup.appendLiteral("</a>");
     return markup.toString();
 }
 
@@ -1015,7 +977,7 @@
     RefPtr<Node> nextNode;
     for (RefPtr<Node> node = fragment->firstChild(); node; node = nextNode) {
         nextNode = node->nextSibling();
-        if (isHTMLHtmlElement(node.get()) || node->hasTagName(headTag) || node->hasTagName(bodyTag)) {
+        if (node->hasTagName(htmlTag) || node->hasTagName(headTag) || node->hasTagName(bodyTag)) {
             HTMLElement* element = toHTMLElement(node);
             if (Node* firstChild = element->firstChild())
                 nextNode = firstChild;
diff --git a/Source/core/editing/markup.h b/Source/core/editing/markup.h
index f122092..41dd3d6 100644
--- a/Source/core/editing/markup.h
+++ b/Source/core/editing/markup.h
@@ -50,7 +50,6 @@
 PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text);
 PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document&, const String& markup, const String& baseURL, ParserContentPolicy = AllowScriptingContent);
 PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document&, const String& markup, unsigned fragmentStart, unsigned fragmentEnd, const String& baseURL, ParserContentPolicy);
-PassRefPtr<DocumentFragment> createFragmentFromNodes(Document*, const Vector<Node*>&);
 PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String&, Element*, ParserContentPolicy, const char* method, ExceptionState&);
 PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String&, const String& sourceMIMEType, Document& outputDoc);
 PassRefPtr<DocumentFragment> createContextualFragment(const String&, HTMLElement*, ParserContentPolicy, ExceptionState&);
@@ -66,7 +65,6 @@
 String createMarkup(const Node*, EChildrenOnly = IncludeNode, Vector<Node*>* = 0, EAbsoluteURLs = DoNotResolveURLs, Vector<QualifiedName>* tagNamesToSkip = 0);
 
 String createFullMarkup(const Node*);
-String createFullMarkup(const Range*);
 
 String urlToMarkup(const KURL&, const String& title);
 void mergeWithNextTextNode(PassRefPtr<Node>, ExceptionState&);
diff --git a/Source/core/events/AutocompleteErrorEvent.h b/Source/core/events/AutocompleteErrorEvent.h
index 1eed01d..847f257 100644
--- a/Source/core/events/AutocompleteErrorEvent.h
+++ b/Source/core/events/AutocompleteErrorEvent.h
@@ -34,7 +34,7 @@
     String reason;
 };
 
-class AutocompleteErrorEvent : public Event {
+class AutocompleteErrorEvent FINAL : public Event {
 public:
     static PassRefPtr<AutocompleteErrorEvent> create()
     {
@@ -53,7 +53,7 @@
 
     const String& reason() const { return m_reason; }
 
-    virtual const AtomicString& interfaceName() const { return EventNames::AutocompleteErrorEvent; }
+    virtual const AtomicString& interfaceName() const OVERRIDE { return EventNames::AutocompleteErrorEvent; }
 
 private:
     AutocompleteErrorEvent()
diff --git a/Source/core/events/BeforeLoadEvent.h b/Source/core/events/BeforeLoadEvent.h
index f52c537..b7fc894 100644
--- a/Source/core/events/BeforeLoadEvent.h
+++ b/Source/core/events/BeforeLoadEvent.h
@@ -27,6 +27,7 @@
 #ifndef BeforeLoadEvent_h
 #define BeforeLoadEvent_h
 
+#include "RuntimeEnabledFeatures.h"
 #include "core/events/Event.h"
 #include "core/events/ThreadLocalEventNames.h"
 
@@ -40,7 +41,7 @@
     String url;
 };
 
-class BeforeLoadEvent : public Event {
+class BeforeLoadEvent FINAL : public Event {
 public:
     static PassRefPtr<BeforeLoadEvent> create()
     {
@@ -59,11 +60,12 @@
 
     const String& url() const { return m_url; }
 
-    virtual const AtomicString& interfaceName() const { return EventNames::BeforeLoadEvent; }
+    virtual const AtomicString& interfaceName() const OVERRIDE { return EventNames::BeforeLoadEvent; }
 
 private:
     BeforeLoadEvent()
     {
+        RELEASE_ASSERT(RuntimeEnabledFeatures::beforeLoadEnabled());
         ScriptWrappable::init(this);
     }
 
@@ -71,6 +73,7 @@
         : Event(EventTypeNames::beforeload, false, true)
         , m_url(url)
     {
+        RELEASE_ASSERT(RuntimeEnabledFeatures::beforeLoadEnabled());
         ScriptWrappable::init(this);
     }
 
@@ -78,6 +81,7 @@
         : Event(type, initializer)
         , m_url(initializer.url)
     {
+        RELEASE_ASSERT(RuntimeEnabledFeatures::beforeLoadEnabled());
         ScriptWrappable::init(this);
     }
 
diff --git a/Source/core/events/BeforeLoadEvent.idl b/Source/core/events/BeforeLoadEvent.idl
index 6f8eca6..b8758d7 100644
--- a/Source/core/events/BeforeLoadEvent.idl
+++ b/Source/core/events/BeforeLoadEvent.idl
@@ -25,6 +25,7 @@
  */
 
 [
+    RuntimeEnabled=BeforeLoad,
     EventConstructor,
 ] interface BeforeLoadEvent : Event {
     [InitializedByEventConstructor] readonly attribute DOMString url;
diff --git a/Source/core/events/BeforeTextInsertedEvent.h b/Source/core/events/BeforeTextInsertedEvent.h
index 546c4fb..44f0434 100644
--- a/Source/core/events/BeforeTextInsertedEvent.h
+++ b/Source/core/events/BeforeTextInsertedEvent.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class BeforeTextInsertedEvent : public Event {
+class BeforeTextInsertedEvent FINAL : public Event {
 public:
     virtual ~BeforeTextInsertedEvent();
 
@@ -39,8 +39,8 @@
         return adoptRef(new BeforeTextInsertedEvent(text));
     }
 
-    virtual const AtomicString& interfaceName() const;
-    virtual bool isBeforeTextInsertedEvent() const { return true; }
+    virtual const AtomicString& interfaceName() const OVERRIDE;
+    virtual bool isBeforeTextInsertedEvent() const OVERRIDE { return true; }
 
     const String& text() const { return m_text; }
     void setText(const String& s) { m_text = s; }
diff --git a/Source/core/events/BeforeUnloadEvent.h b/Source/core/events/BeforeUnloadEvent.h
index 57136f9..7f7e881 100644
--- a/Source/core/events/BeforeUnloadEvent.h
+++ b/Source/core/events/BeforeUnloadEvent.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class BeforeUnloadEvent : public Event {
+class BeforeUnloadEvent FINAL : public Event {
 public:
     virtual ~BeforeUnloadEvent();
 
diff --git a/Source/core/events/ClipboardEvent.cpp b/Source/core/events/ClipboardEvent.cpp
index a8fa4f9..849a64b 100644
--- a/Source/core/events/ClipboardEvent.cpp
+++ b/Source/core/events/ClipboardEvent.cpp
@@ -23,7 +23,7 @@
 #include "config.h"
 #include "core/events/ClipboardEvent.h"
 
-#include "core/dom/Clipboard.h"
+#include "core/clipboard/Clipboard.h"
 #include "core/events/ThreadLocalEventNames.h"
 
 namespace WebCore {
diff --git a/Source/core/events/ClipboardEvent.h b/Source/core/events/ClipboardEvent.h
index 671315b..d0d93c4 100644
--- a/Source/core/events/ClipboardEvent.h
+++ b/Source/core/events/ClipboardEvent.h
@@ -30,14 +30,10 @@
 
     class Clipboard;
 
-    class ClipboardEvent : public Event {
+    class ClipboardEvent FINAL : public Event {
     public:
         virtual ~ClipboardEvent();
 
-        static PassRefPtr<ClipboardEvent> create()
-        {
-            return adoptRef(new ClipboardEvent);
-        }
         static PassRefPtr<ClipboardEvent> create(const AtomicString& type, bool canBubbleArg, bool cancelableArg, PassRefPtr<Clipboard> clipboardArg)
         {
             return adoptRef(new ClipboardEvent(type, canBubbleArg, cancelableArg, clipboardArg));
diff --git a/Source/core/events/CompositionEvent.cpp b/Source/core/events/CompositionEvent.cpp
index f4ecff6..6281bdc 100644
--- a/Source/core/events/CompositionEvent.cpp
+++ b/Source/core/events/CompositionEvent.cpp
@@ -36,22 +36,31 @@
 }
 
 CompositionEvent::CompositionEvent()
+    : m_activeSegmentStart(0)
+    , m_activeSegmentEnd(0)
 {
     ScriptWrappable::init(this);
+    initializeSegments();
 }
 
-CompositionEvent::CompositionEvent(const AtomicString& type, PassRefPtr<AbstractView> view, const String& data)
+CompositionEvent::CompositionEvent(const AtomicString& type, PassRefPtr<AbstractView> view, const String& data, const Vector<CompositionUnderline>& underlines)
     : UIEvent(type, true, true, view, 0)
     , m_data(data)
+    , m_activeSegmentStart(0)
+    , m_activeSegmentEnd(0)
 {
     ScriptWrappable::init(this);
+    initializeSegments(&underlines);
 }
 
 CompositionEvent::CompositionEvent(const AtomicString& type, const CompositionEventInit& initializer)
     : UIEvent(type, initializer)
     , m_data(initializer.data)
+    , m_activeSegmentStart(0)
+    , m_activeSegmentEnd(0)
 {
     ScriptWrappable::init(this);
+    initializeSegments();
 }
 
 CompositionEvent::~CompositionEvent()
@@ -66,6 +75,29 @@
     initUIEvent(type, canBubble, cancelable, view, 0);
 
     m_data = data;
+    initializeSegments();
+}
+
+void CompositionEvent::initializeSegments(const Vector<CompositionUnderline>* underlines)
+{
+    m_activeSegmentStart = 0;
+    m_activeSegmentEnd = m_data.length();
+
+    if (!underlines || !underlines->size()) {
+        m_segments.append(0);
+        return;
+    }
+
+    for (size_t i = 0; i < underlines->size(); ++i) {
+        if (underlines->at(i).thick) {
+            m_activeSegmentStart = underlines->at(i).startOffset;
+            m_activeSegmentEnd = underlines->at(i).endOffset;
+            break;
+        }
+    }
+
+    for (size_t i = 0; i < underlines->size(); ++i)
+        m_segments.append(underlines->at(i).startOffset);
 }
 
 const AtomicString& CompositionEvent::interfaceName() const
diff --git a/Source/core/events/CompositionEvent.h b/Source/core/events/CompositionEvent.h
index c06da88..b3c1a74 100644
--- a/Source/core/events/CompositionEvent.h
+++ b/Source/core/events/CompositionEvent.h
@@ -27,6 +27,7 @@
 #ifndef CompositionEvent_h
 #define CompositionEvent_h
 
+#include "core/editing/CompositionUnderline.h"
 #include "core/events/UIEvent.h"
 
 namespace WebCore {
@@ -37,16 +38,16 @@
     String data;
 };
 
-class CompositionEvent : public UIEvent {
+class CompositionEvent FINAL : public UIEvent {
 public:
     static PassRefPtr<CompositionEvent> create()
     {
         return adoptRef(new CompositionEvent);
     }
 
-    static PassRefPtr<CompositionEvent> create(const AtomicString& type, PassRefPtr<AbstractView> view, const String& data)
+    static PassRefPtr<CompositionEvent> create(const AtomicString& type, PassRefPtr<AbstractView> view, const String& data, const Vector<CompositionUnderline>& underlines)
     {
-        return adoptRef(new CompositionEvent(type, view, data));
+        return adoptRef(new CompositionEvent(type, view, data, underlines));
     }
 
     static PassRefPtr<CompositionEvent> create(const AtomicString& type, const CompositionEventInit& initializer)
@@ -59,15 +60,22 @@
     void initCompositionEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, const String& data);
 
     String data() const { return m_data; }
+    int activeSegmentStart() const { return m_activeSegmentStart; }
+    int activeSegmentEnd() const { return m_activeSegmentEnd; }
+    const Vector<unsigned>& getSegments() const { return m_segments; }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     CompositionEvent();
-    CompositionEvent(const AtomicString& type, PassRefPtr<AbstractView>, const String&);
+    CompositionEvent(const AtomicString& type, PassRefPtr<AbstractView>, const String&, const Vector<CompositionUnderline>& underlines);
     CompositionEvent(const AtomicString& type, const CompositionEventInit&);
+    void initializeSegments(const Vector<CompositionUnderline>* = 0);
 
     String m_data;
+    int m_activeSegmentStart;
+    int m_activeSegmentEnd;
+    Vector<unsigned> m_segments;
 };
 
 } // namespace WebCore
diff --git a/Source/core/events/CompositionEvent.idl b/Source/core/events/CompositionEvent.idl
index 4e14a95..8b1d740 100644
--- a/Source/core/events/CompositionEvent.idl
+++ b/Source/core/events/CompositionEvent.idl
@@ -29,6 +29,10 @@
 
     [InitializedByEventConstructor] readonly attribute DOMString data;
 
+    [RuntimeEnabled=IMEAPI] readonly attribute long activeSegmentStart;
+    [RuntimeEnabled=IMEAPI] readonly attribute long activeSegmentEnd;
+    [RuntimeEnabled=IMEAPI] sequence<unsigned long> getSegments();
+
     void initCompositionEvent([Default=Undefined] optional DOMString typeArg,
                               [Default=Undefined] optional boolean canBubbleArg,
                               [Default=Undefined] optional boolean cancelableArg,
@@ -36,4 +40,3 @@
                               [Default=Undefined] optional DOMString dataArg);
 
 };
-
diff --git a/Source/core/events/CustomEvent.h b/Source/core/events/CustomEvent.h
index 9be0e11..8b855d7 100644
--- a/Source/core/events/CustomEvent.h
+++ b/Source/core/events/CustomEvent.h
@@ -34,7 +34,7 @@
 
 typedef EventInit CustomEventInit;
 
-class CustomEvent : public Event {
+class CustomEvent FINAL : public Event {
 public:
     virtual ~CustomEvent();
 
@@ -50,7 +50,7 @@
 
     void initCustomEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<SerializedScriptValue>);
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
     SerializedScriptValue* serializedDetail() { return m_serializedDetail.get(); }
 
diff --git a/Source/core/events/DOMWindowEventQueue.h b/Source/core/events/DOMWindowEventQueue.h
index f19e22b..23dbb93 100644
--- a/Source/core/events/DOMWindowEventQueue.h
+++ b/Source/core/events/DOMWindowEventQueue.h
@@ -41,7 +41,7 @@
 class Node;
 class ExecutionContext;
 
-class DOMWindowEventQueue : public RefCounted<DOMWindowEventQueue>, public EventQueue {
+class DOMWindowEventQueue FINAL : public RefCounted<DOMWindowEventQueue>, public EventQueue {
 public:
     static PassRefPtr<DOMWindowEventQueue> create(ExecutionContext*);
     virtual ~DOMWindowEventQueue();
diff --git a/Source/core/events/ErrorEvent.cpp b/Source/core/events/ErrorEvent.cpp
index 0bd32f4..5485e81 100644
--- a/Source/core/events/ErrorEvent.cpp
+++ b/Source/core/events/ErrorEvent.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/events/ErrorEvent.h"
 
+#include "bindings/v8/V8Binding.h"
 #include "core/events/ThreadLocalEventNames.h"
 
 namespace WebCore {
@@ -54,7 +55,7 @@
     , m_fileName(initializer.filename)
     , m_lineNumber(initializer.lineno)
     , m_columnNumber(initializer.colno)
-    , m_world(DOMWrapperWorld::current())
+    , m_world(DOMWrapperWorld::current(v8::Isolate::GetCurrent()))
 {
     ScriptWrappable::init(this);
 }
diff --git a/Source/core/events/ErrorEvent.h b/Source/core/events/ErrorEvent.h
index e0643e4..09912ec 100644
--- a/Source/core/events/ErrorEvent.h
+++ b/Source/core/events/ErrorEvent.h
@@ -47,7 +47,7 @@
     unsigned colno;
 };
 
-class ErrorEvent : public Event {
+class ErrorEvent FINAL : public Event {
 public:
     static PassRefPtr<ErrorEvent> create()
     {
@@ -76,7 +76,7 @@
     // 'messageForConsole' is not exposed to JavaScript, and prefers 'm_unsanitizedMessage'.
     const String& messageForConsole() const { return !m_unsanitizedMessage.isEmpty() ? m_unsanitizedMessage : m_sanitizedMessage; }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
     PassRefPtr<DOMWrapperWorld> world() const { return m_world; }
 
diff --git a/Source/core/events/ErrorEvent.idl b/Source/core/events/ErrorEvent.idl
index f8e8e51..ad12285 100644
--- a/Source/core/events/ErrorEvent.idl
+++ b/Source/core/events/ErrorEvent.idl
@@ -35,6 +35,6 @@
     [InitializedByEventConstructor] readonly attribute DOMString filename;
     [InitializedByEventConstructor] readonly attribute unsigned long lineno;
     [InitializedByEventConstructor] readonly attribute unsigned long colno;
-    [Custom=Getter, InitializedByEventConstructor, Unserializable] readonly attribute any error;
+    [Custom=Getter, InitializedByEventConstructor] readonly attribute any error;
 };
 
diff --git a/Source/core/events/Event.cpp b/Source/core/events/Event.cpp
index 4ec6012..ee384a5 100644
--- a/Source/core/events/Event.cpp
+++ b/Source/core/events/Event.cpp
@@ -48,7 +48,6 @@
     , m_eventPhase(0)
     , m_currentTarget(0)
     , m_createTime(convertSecondsToDOMTimeStamp(currentTime()))
-    , m_eventPath(this)
 {
     ScriptWrappable::init(this);
 }
@@ -65,7 +64,6 @@
     , m_eventPhase(0)
     , m_currentTarget(0)
     , m_createTime(convertSecondsToDOMTimeStamp(currentTime()))
-    , m_eventPath(this)
 {
     ScriptWrappable::init(this);
 }
@@ -82,7 +80,6 @@
     , m_eventPhase(0)
     , m_currentTarget(0)
     , m_createTime(convertSecondsToDOMTimeStamp(currentTime()))
-    , m_eventPath(this)
 {
     ScriptWrappable::init(this);
 }
@@ -193,16 +190,23 @@
     m_underlyingEvent = ue;
 }
 
+EventPath& Event::ensureEventPath()
+{
+    if (!m_eventPath)
+        m_eventPath = adoptPtr(new EventPath(this));
+    return *m_eventPath;
+}
+
 PassRefPtr<NodeList> Event::path() const
 {
     if (!m_currentTarget || !m_currentTarget->toNode())
         return StaticNodeList::createEmpty();
     Node* node = m_currentTarget->toNode();
-    size_t eventPathSize = m_eventPath.size();
+    size_t eventPathSize = m_eventPath->size();
     for (size_t i = 0; i < eventPathSize; ++i) {
-        if (node == m_eventPath[i].node()) {
-            ASSERT(m_eventPath[i].eventPath());
-            return m_eventPath[i].eventPath();
+        if (node == (*m_eventPath)[i].node()) {
+            ASSERT((*m_eventPath)[i].eventPath());
+            return (*m_eventPath)[i].eventPath();
         }
     }
     return StaticNodeList::createEmpty();
diff --git a/Source/core/events/Event.h b/Source/core/events/Event.h
index b28f7f1..fab6c95 100644
--- a/Source/core/events/Event.h
+++ b/Source/core/events/Event.h
@@ -26,14 +26,12 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/DOMTimeStamp.h"
-#include "core/events/EventContext.h"
 #include "core/events/EventPath.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
-class Clipboard;
 class EventTarget;
 class EventDispatcher;
 class HTMLIFrameElement;
@@ -132,8 +130,6 @@
     bool legacyReturnValue() const { return !defaultPrevented(); }
     void setLegacyReturnValue(bool returnValue) { setDefaultPrevented(!returnValue); }
 
-    Clipboard* clipboardData() const { return isClipboardEvent() ? clipboard() : 0; }
-
     virtual const AtomicString& interfaceName() const;
     bool hasInterface(const AtomicString&) const;
 
@@ -175,10 +171,10 @@
     Event* underlyingEvent() const { return m_underlyingEvent.get(); }
     void setUnderlyingEvent(PassRefPtr<Event>);
 
-    EventPath& eventPath() { return m_eventPath; }
-    PassRefPtr<NodeList> path() const;
+    EventPath& eventPath() { ASSERT(m_eventPath); return *m_eventPath; }
+    EventPath& ensureEventPath();
 
-    virtual Clipboard* clipboard() const { return 0; }
+    PassRefPtr<NodeList> path() const;
 
     bool isBeingDispatched() const { return eventPhase(); }
 
@@ -206,7 +202,7 @@
     RefPtr<EventTarget> m_target;
     DOMTimeStamp m_createTime;
     RefPtr<Event> m_underlyingEvent;
-    EventPath m_eventPath;
+    OwnPtr<EventPath> m_eventPath;
 };
 
 #define DEFINE_EVENT_TYPE_CASTS(typeName) \
diff --git a/Source/core/events/EventAliases.in b/Source/core/events/EventAliases.in
index 82b8e99..f5d9063 100644
--- a/Source/core/events/EventAliases.in
+++ b/Source/core/events/EventAliases.in
@@ -5,10 +5,10 @@
 KeyboardEvents ImplementedAs=KeyboardEvent
 MouseEvents ImplementedAs=MouseEvent
 MutationEvents ImplementedAs=MutationEvent
-OrientationEvent ImplementedAs=Event, Conditional=ORIENTATION_EVENTS
+OrientationEvent ImplementedAs=Event, RuntimeEnabled=OrientationEventEnabled
 SVGEvents ImplementedAs=Event
 SVGZoomEvents ImplementedAs=SVGZoomEvent
 UIEvents ImplementedAs=UIEvent
 WebKitTransitionEvent ImplementedAs=TransitionEvent
 
-core/dom/TouchEvent RuntimeEnabled=touchEnabled
+core/events/TouchEvent RuntimeEnabled=touchEnabled
diff --git a/Source/core/events/EventContext.cpp b/Source/core/events/EventContext.cpp
deleted file mode 100644
index 0adddcc..0000000
--- a/Source/core/events/EventContext.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- *
- */
-
-#include "config.h"
-#include "core/events/EventContext.h"
-
-#include "core/events/Event.h"
-#include "core/events/FocusEvent.h"
-#include "core/events/MouseEvent.h"
-#include "core/events/TouchEvent.h"
-#include "core/dom/TouchList.h"
-
-namespace WebCore {
-
-EventContext::EventContext(PassRefPtr<Node> node, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target)
-    : m_node(node)
-    , m_currentTarget(currentTarget)
-    , m_target(target)
-{
-    ASSERT(m_node);
-    ASSERT(!isUnreachableNode(m_target.get()));
-}
-
-EventContext::~EventContext()
-{
-}
-
-void EventContext::adoptEventPath(Vector<RefPtr<Node> >& nodes)
-{
-    m_eventPath = StaticNodeList::adopt(nodes);
-}
-
-void EventContext::handleLocalEvents(Event* event) const
-{
-    event->setTarget(m_target.get());
-    event->setCurrentTarget(m_currentTarget.get());
-    m_node->handleLocalEvents(event);
-}
-
-bool EventContext::isMouseOrFocusEventContext() const
-{
-    return false;
-}
-
-bool EventContext::isTouchEventContext() const
-{
-    return false;
-}
-
-MouseOrFocusEventContext::MouseOrFocusEventContext(PassRefPtr<Node> node, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target)
-    : EventContext(node, currentTarget, target)
-    , m_relatedTarget(0)
-{
-}
-
-MouseOrFocusEventContext::~MouseOrFocusEventContext()
-{
-}
-
-void MouseOrFocusEventContext::handleLocalEvents(Event* event) const
-{
-    ASSERT(event->isMouseEvent() || event->isFocusEvent());
-    if (m_relatedTarget.get() && event->isMouseEvent())
-        toMouseEvent(event)->setRelatedTarget(m_relatedTarget.get());
-    else if (m_relatedTarget.get() && event->isFocusEvent())
-        toFocusEvent(event)->setRelatedTarget(m_relatedTarget.get());
-    EventContext::handleLocalEvents(event);
-}
-
-bool MouseOrFocusEventContext::isMouseOrFocusEventContext() const
-{
-    return true;
-}
-
-TouchEventContext::TouchEventContext(PassRefPtr<Node> node, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target)
-    : EventContext(node, currentTarget, target)
-    , m_touches(TouchList::create())
-    , m_targetTouches(TouchList::create())
-    , m_changedTouches(TouchList::create())
-{
-}
-
-TouchEventContext::~TouchEventContext()
-{
-}
-
-void TouchEventContext::handleLocalEvents(Event* event) const
-{
-#ifndef NDEBUG
-    checkReachability(m_touches.get());
-    checkReachability(m_targetTouches.get());
-    checkReachability(m_changedTouches.get());
-#endif
-    ASSERT(event->isTouchEvent());
-    TouchEvent* touchEvent = toTouchEvent(event);
-    touchEvent->setTouches(m_touches);
-    touchEvent->setTargetTouches(m_targetTouches);
-    touchEvent->setChangedTouches(m_changedTouches);
-    EventContext::handleLocalEvents(event);
-}
-
-bool TouchEventContext::isTouchEventContext() const
-{
-    return true;
-}
-
-#ifndef NDEBUG
-void TouchEventContext::checkReachability(TouchList* touchList) const
-{
-    for (size_t i = 0; i < touchList->length(); ++i)
-        ASSERT(touchList->item(i)->target()->toNode()->treeScope().isInclusiveAncestorOf(m_node->treeScope()));
-}
-#endif
-
-}
diff --git a/Source/core/events/EventContext.h b/Source/core/events/EventContext.h
deleted file mode 100644
index 09d1097..0000000
--- a/Source/core/events/EventContext.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- *
- */
-
-#ifndef EventContext_h
-#define EventContext_h
-
-#include "core/events/EventTarget.h"
-#include "core/dom/Node.h"
-#include "core/dom/StaticNodeList.h"
-#include "core/dom/TreeScope.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class Event;
-class TouchList;
-
-class EventContext {
-public:
-    // FIXME: Use ContainerNode instead of Node.
-    EventContext(PassRefPtr<Node>, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target);
-    virtual ~EventContext();
-
-    Node* node() const { return m_node.get(); }
-    EventTarget* target() const { return m_target.get(); }
-    void setTarget(PassRefPtr<EventTarget> target) { m_target = target; }
-    PassRefPtr<NodeList> eventPath() const { return m_eventPath; }
-    void adoptEventPath(Vector<RefPtr<Node> >&);
-    void setEventPath(PassRefPtr<NodeList> nodeList) { m_eventPath = nodeList; }
-
-    bool currentTargetSameAsTarget() const { return m_currentTarget.get() == m_target.get(); }
-    virtual void handleLocalEvents(Event*) const;
-    virtual bool isMouseOrFocusEventContext() const;
-    virtual bool isTouchEventContext() const;
-
-protected:
-#ifndef NDEBUG
-    bool isUnreachableNode(EventTarget*);
-#endif
-    RefPtr<Node> m_node;
-    RefPtr<EventTarget> m_currentTarget;
-    RefPtr<EventTarget> m_target;
-    RefPtr<NodeList> m_eventPath;
-};
-
-class MouseOrFocusEventContext : public EventContext {
-public:
-    MouseOrFocusEventContext(PassRefPtr<Node>, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target);
-    virtual ~MouseOrFocusEventContext();
-    EventTarget* relatedTarget() const { return m_relatedTarget.get(); }
-    void setRelatedTarget(PassRefPtr<EventTarget>);
-    virtual void handleLocalEvents(Event*) const OVERRIDE;
-    virtual bool isMouseOrFocusEventContext() const OVERRIDE;
-
-private:
-    RefPtr<EventTarget> m_relatedTarget;
-};
-
-
-class TouchEventContext : public EventContext {
-public:
-    TouchEventContext(PassRefPtr<Node>, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target);
-    virtual ~TouchEventContext();
-
-    virtual void handleLocalEvents(Event*) const OVERRIDE;
-    virtual bool isTouchEventContext() const OVERRIDE;
-
-    TouchList* touches() { return m_touches.get(); }
-    TouchList* targetTouches() { return m_targetTouches.get(); }
-    TouchList* changedTouches() { return m_changedTouches.get(); }
-
-private:
-    RefPtr<TouchList> m_touches;
-    RefPtr<TouchList> m_targetTouches;
-    RefPtr<TouchList> m_changedTouches;
-#ifndef NDEBUG
-    void checkReachability(TouchList*) const;
-#endif
-};
-
-inline TouchEventContext& toTouchEventContext(EventContext& eventContext)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(eventContext.isTouchEventContext());
-    return static_cast<TouchEventContext&>(eventContext);
-}
-
-#ifndef NDEBUG
-inline bool EventContext::isUnreachableNode(EventTarget* target)
-{
-    // FIXME: Checks also for SVG elements.
-    return target && target->toNode() && !target->toNode()->isSVGElement() && !target->toNode()->treeScope().isInclusiveAncestorOf(m_node->treeScope());
-}
-#endif
-
-inline void MouseOrFocusEventContext::setRelatedTarget(PassRefPtr<EventTarget> relatedTarget)
-{
-    ASSERT(!isUnreachableNode(relatedTarget.get()));
-    m_relatedTarget = relatedTarget;
-}
-
-}
-
-#endif // EventContext_h
diff --git a/Source/core/events/EventDispatcher.cpp b/Source/core/events/EventDispatcher.cpp
index fa5698e..055273a 100644
--- a/Source/core/events/EventDispatcher.cpp
+++ b/Source/core/events/EventDispatcher.cpp
@@ -28,7 +28,6 @@
 
 #include "core/dom/ContainerNode.h"
 #include "core/events/EventDispatchMediator.h"
-#include "core/events/EventRetargeter.h"
 #include "core/events/MouseEvent.h"
 #include "core/events/ScopedEventQueue.h"
 #include "core/events/WindowEventContext.h"
@@ -60,7 +59,7 @@
     ASSERT(m_event.get());
     ASSERT(!m_event->type().isNull()); // JavaScript code can create an event with an empty name, but not null.
     m_view = node->document().view();
-    m_event->eventPath().resetWith(m_node.get());
+    m_event->ensureEventPath().resetWith(m_node.get());
 }
 
 void EventDispatcher::dispatchScopedEvent(Node* node, PassRefPtr<EventDispatchMediator> mediator)
@@ -109,7 +108,7 @@
     m_event->setTarget(EventPath::eventTargetRespectingTargetRules(m_node.get()));
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
     ASSERT(m_event->target());
-    WindowEventContext windowEventContext(m_event.get(), m_node.get(), topEventContext());
+    WindowEventContext windowEventContext(m_event.get(), m_node.get(), topNodeEventContext());
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEvent(&m_node->document(), *m_event, windowEventContext.window(), m_node.get(), m_event->eventPath());
 
     void* preDispatchEventHandlerResult;
@@ -144,7 +143,7 @@
         return DoneDispatching;
 
     for (size_t i = m_event->eventPath().size() - 1; i > 0; --i) {
-        const EventContext& eventContext = m_event->eventPath()[i];
+        const NodeEventContext& eventContext = m_event->eventPath()[i];
         if (eventContext.currentTargetSameAsTarget())
             continue;
         eventContext.handleLocalEvents(m_event.get());
@@ -167,7 +166,7 @@
     // Trigger bubbling event handlers, starting at the bottom and working our way up.
     size_t size = m_event->eventPath().size();
     for (size_t i = 1; i < size; ++i) {
-        const EventContext& eventContext = m_event->eventPath()[i];
+        const NodeEventContext& eventContext = m_event->eventPath()[i];
         if (eventContext.currentTargetSameAsTarget())
             m_event->setEventPhase(Event::AT_TARGET);
         else if (m_event->bubbles() && !m_event->cancelBubble())
@@ -218,7 +217,7 @@
     }
 }
 
-const EventContext* EventDispatcher::topEventContext()
+const NodeEventContext* EventDispatcher::topNodeEventContext()
 {
     return m_event->eventPath().isEmpty() ? 0 : &m_event->eventPath().last();
 }
diff --git a/Source/core/events/EventDispatcher.h b/Source/core/events/EventDispatcher.h
index aae65a2..9fac66f 100644
--- a/Source/core/events/EventDispatcher.h
+++ b/Source/core/events/EventDispatcher.h
@@ -26,22 +26,17 @@
 #ifndef EventDispatcher_h
 #define EventDispatcher_h
 
-#include "core/events/EventContext.h"
 #include "core/dom/SimulatedClickOptions.h"
-#include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
 class Event;
 class EventDispatchMediator;
-class EventTarget;
 class FrameView;
 class Node;
-class PlatformKeyboardEvent;
-class PlatformMouseEvent;
-class ShadowRoot;
-class TreeScope;
+class NodeEventContext;
 class WindowEventContext;
 
 enum EventDispatchContinuation {
@@ -62,7 +57,7 @@
 
 private:
     EventDispatcher(Node*, PassRefPtr<Event>);
-    const EventContext* topEventContext();
+    const NodeEventContext* topNodeEventContext();
 
     EventDispatchContinuation dispatchEventPreProcess(void*& preDispatchEventHandlerResult);
     EventDispatchContinuation dispatchEventAtCapturing(WindowEventContext&);
diff --git a/Source/core/events/EventListener.h b/Source/core/events/EventListener.h
index 7829104..ea8bc44 100644
--- a/Source/core/events/EventListener.h
+++ b/Source/core/events/EventListener.h
@@ -43,6 +43,7 @@
         virtual bool operator==(const EventListener&) = 0;
         virtual void handleEvent(ExecutionContext*, Event*) = 0;
         virtual bool wasCreatedFromMarkup() const { return false; }
+        virtual bool belongsToTheCurrentWorld() const { return false; }
         virtual DOMWrapperWorld* world() const { return 0; }
 
         bool isAttribute() const { return virtualisAttribute(); }
diff --git a/Source/core/events/EventPath.cpp b/Source/core/events/EventPath.cpp
index 954ef21..c35c575 100644
--- a/Source/core/events/EventPath.cpp
+++ b/Source/core/events/EventPath.cpp
@@ -31,10 +31,14 @@
 #include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "core/dom/FullscreenElementStack.h"
-#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/Touch.h"
+#include "core/dom/TouchList.h"
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/html/shadow/HTMLShadowElement.h"
+#include "core/events/FocusEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/TouchEvent.h"
+#include "core/events/TouchEventContext.h"
 #include "core/svg/SVGElementInstance.h"
 #include "core/svg/SVGUseElement.h"
 
@@ -58,8 +62,8 @@
 
     // Spec: The event handling for the non-exposed tree works as if the referenced element had been textually included
     // as a deeply cloned child of the 'use' element, except that events are dispatched to the SVGElementInstance objects.
-    Node* rootNode = referenceNode->treeScope().rootNode();
-    Element* shadowHostElement = rootNode->isShadowRoot() ? toShadowRoot(rootNode)->host() : 0;
+    Node& rootNode = referenceNode->treeScope().rootNode();
+    Element* shadowHostElement = rootNode.isShadowRoot() ? toShadowRoot(rootNode).host() : 0;
     // At this time, SVG nodes are not supported in non-<use> shadow trees.
     if (!shadowHostElement || !shadowHostElement->hasTagName(SVGNames::useTag))
         return referenceNode;
@@ -122,33 +126,26 @@
 {
     ASSERT(node);
     m_node = node;
-    m_eventContexts.clear();
+    m_nodeEventContexts.clear();
+    m_treeScopeEventContexts.clear();
     calculatePath();
     calculateAdjustedTargets();
-    calculateAdjustedEventPathForEachNode();
+    calculateAdjustedEventPath();
 }
 
-void EventPath::addEventContext(Node* node, bool isMouseOrFocusEvent, bool isTouchEvent)
+void EventPath::addNodeEventContext(Node* node)
 {
-    if (isMouseOrFocusEvent)
-        m_eventContexts.append(adoptPtr(new MouseOrFocusEventContext(node, eventTargetRespectingTargetRules(node), 0)));
-    else if (isTouchEvent)
-        m_eventContexts.append(adoptPtr(new TouchEventContext(node, eventTargetRespectingTargetRules(node), 0)));
-    else
-        m_eventContexts.append(adoptPtr(new EventContext(node, eventTargetRespectingTargetRules(node), 0)));
+    m_nodeEventContexts.append(NodeEventContext(node, eventTargetRespectingTargetRules(node)));
 }
 
 void EventPath::calculatePath()
 {
     ASSERT(m_node);
-    ASSERT(m_eventContexts.isEmpty());
+    ASSERT(m_nodeEventContexts.isEmpty());
     m_node->document().updateDistributionForNodeIfNeeded(const_cast<Node*>(m_node));
 
-    bool isMouseOrFocusEvent = m_event && (m_event->isMouseEvent() || m_event->isFocusEvent());
-    bool isTouchEvent = m_event && m_event->isTouchEvent();
-
     Node* current = m_node;
-    addEventContext(current, isMouseOrFocusEvent, isTouchEvent);
+    addNodeEventContext(current);
     if (!m_node->inDocument())
         return;
     while (current) {
@@ -163,102 +160,218 @@
                     ShadowRoot* containingShadowRoot = insertionPoint->containingShadowRoot();
                     ASSERT(containingShadowRoot);
                     if (!containingShadowRoot->isOldest())
-                        addEventContext(containingShadowRoot->olderShadowRoot(), isMouseOrFocusEvent, isTouchEvent);
+                        addNodeEventContext(containingShadowRoot->olderShadowRoot());
                 }
-                addEventContext(insertionPoint, isMouseOrFocusEvent, isTouchEvent);
+                addNodeEventContext(insertionPoint);
             }
             current = insertionPoints.last();
             continue;
         }
         if (current->isShadowRoot()) {
             current = current->shadowHost();
-            addEventContext(current, isMouseOrFocusEvent, isTouchEvent);
+            addNodeEventContext(current);
         } else {
             current = current->parentNode();
             if (current)
-                addEventContext(current, isMouseOrFocusEvent, isTouchEvent);
+                addNodeEventContext(current);
         }
     }
 }
 
-void EventPath::calculateAdjustedEventPathForEachNode()
+void EventPath::calculateAdjustedEventPath()
 {
     if (!RuntimeEnabledFeatures::shadowDOMEnabled())
         return;
-    TreeScope* lastScope = 0;
-    for (size_t i = 0; i < size(); ++i) {
-        TreeScope* currentScope = &at(i).node()->treeScope();
-        if (currentScope == lastScope) {
-            // Fast path.
-            at(i).setEventPath(at(i - 1).eventPath());
-            continue;
-        }
-        lastScope = currentScope;
+    for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
+        TreeScopeEventContext* treeScopeEventContext = m_treeScopeEventContexts[i].get();
         Vector<RefPtr<Node> > nodes;
-        for (size_t j = 0; j < size(); ++j) {
-            if (at(j).node()->treeScope().isInclusiveAncestorOf(*currentScope))
-                nodes.append(at(j).node());
+        nodes.reserveInitialCapacity(size());
+        for (size_t i = 0; i < size(); ++i) {
+            if (at(i).node()->treeScope().isInclusiveOlderSiblingShadowRootOrAncestorTreeScopeOf(treeScopeEventContext->treeScope())) {
+                ASSERT(!at(i).node()->containingShadowRoot()
+                    || at(i).node()->treeScope() == treeScopeEventContext->treeScope()
+                    || toShadowRoot(treeScopeEventContext->treeScope().rootNode()).type() == ShadowRoot::UserAgentShadowRoot
+                    || at(i).node()->containingShadowRoot()->type() != ShadowRoot::UserAgentShadowRoot);
+                nodes.append(at(i).node());
+            }
         }
-        at(i).adoptEventPath(nodes);
+        treeScopeEventContext->adoptEventPath(nodes);
     }
 }
 
-#ifndef NDEBUG
-static inline bool movedFromOlderToYounger(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
+TreeScopeEventContext* EventPath::ensureTreeScopeEventContext(Node* currentTarget, TreeScope* treeScope, TreeScopeEventContextMap& treeScopeEventContextMap)
 {
-    Node* rootNode = lastTreeScope.rootNode();
-    return rootNode->isShadowRoot() && toShadowRoot(rootNode)->youngerShadowRoot() == currentTreeScope.rootNode();
-}
-
-static inline bool movedFromYoungerToOlder(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
-{
-    Node* rootNode = lastTreeScope.rootNode();
-    return rootNode->isShadowRoot() && toShadowRoot(rootNode)->olderShadowRoot() == currentTreeScope.rootNode();
-}
-#endif
-
-static inline bool movedFromChildToParent(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
-{
-    return lastTreeScope.parentTreeScope() == &currentTreeScope;
-}
-
-static inline bool movedFromParentToChild(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
-{
-    return currentTreeScope.parentTreeScope() == &lastTreeScope;
+    if (!treeScope)
+        return 0;
+    TreeScopeEventContextMap::AddResult addResult = treeScopeEventContextMap.add(treeScope, TreeScopeEventContext::create(*treeScope));
+    TreeScopeEventContext* treeScopeEventContext = addResult.storedValue->value.get();
+    if (addResult.isNewEntry) {
+        TreeScopeEventContext* parentTreeScopeEventContext = ensureTreeScopeEventContext(0, treeScope->olderShadowRootOrParentTreeScope(), treeScopeEventContextMap);
+        if (parentTreeScopeEventContext && parentTreeScopeEventContext->target()) {
+            treeScopeEventContext->setTarget(parentTreeScopeEventContext->target());
+        } else if (currentTarget) {
+            treeScopeEventContext->setTarget(eventTargetRespectingTargetRules(currentTarget));
+        }
+    } else if (!treeScopeEventContext->target() && currentTarget) {
+        treeScopeEventContext->setTarget(eventTargetRespectingTargetRules(currentTarget));
+    }
+    return treeScopeEventContext;
 }
 
 void EventPath::calculateAdjustedTargets()
 {
-    Vector<Node*, 32> targetStack;
     const TreeScope* lastTreeScope = 0;
     bool isSVGElement = at(0).node()->isSVGElement();
 
+    TreeScopeEventContextMap treeScopeEventContextMap;
+    TreeScopeEventContext* lastTreeScopeEventContext = 0;
+
     for (size_t i = 0; i < size(); ++i) {
-        Node* current = at(i).node();
-        const TreeScope& currentTreeScope = current->treeScope();
-        if (targetStack.isEmpty()) {
-            targetStack.append(current);
-        } else if (*lastTreeScope != currentTreeScope && !isSVGElement) {
-            if (movedFromParentToChild(*lastTreeScope, currentTreeScope)) {
-                targetStack.append(targetStack.last());
-            } else if (movedFromChildToParent(*lastTreeScope, currentTreeScope)) {
-                ASSERT(!targetStack.isEmpty());
-                targetStack.removeLast();
-                if (targetStack.isEmpty())
-                    targetStack.append(current);
+        Node* currentNode = at(i).node();
+        TreeScope& currentTreeScope = currentNode->treeScope();
+        if (lastTreeScope != &currentTreeScope) {
+            if (!isSVGElement) {
+                lastTreeScopeEventContext = ensureTreeScopeEventContext(currentNode, &currentTreeScope, treeScopeEventContextMap);
             } else {
-                ASSERT(movedFromYoungerToOlder(*lastTreeScope, currentTreeScope) || movedFromOlderToYounger(*lastTreeScope, currentTreeScope));
-                ASSERT(!targetStack.isEmpty());
-                targetStack.removeLast();
-                if (targetStack.isEmpty())
-                    targetStack.append(current);
-                else
-                    targetStack.append(targetStack.last());
+                TreeScopeEventContextMap::AddResult addResult = treeScopeEventContextMap.add(&currentTreeScope, TreeScopeEventContext::create(currentTreeScope));
+                lastTreeScopeEventContext = addResult.storedValue->value.get();
+                if (addResult.isNewEntry) {
+                    // Don't adjust an event target for SVG.
+                    lastTreeScopeEventContext->setTarget(eventTargetRespectingTargetRules(at(0).node()));
+                }
             }
         }
-        at(i).setTarget(eventTargetRespectingTargetRules(targetStack.last()));
+        ASSERT(lastTreeScopeEventContext);
+        at(i).setTreeScopeEventContext(lastTreeScopeEventContext);
         lastTreeScope = &currentTreeScope;
     }
+    m_treeScopeEventContexts.appendRange(treeScopeEventContextMap.values().begin(), treeScopeEventContextMap.values().end());
 }
 
+void EventPath::buildRelatedNodeMap(const Node* relatedNode, RelatedTargetMap& relatedTargetMap)
+{
+    EventPath relatedTargetEventPath(const_cast<Node*>(relatedNode));
+    for (size_t i = 0; i < relatedTargetEventPath.m_treeScopeEventContexts.size(); ++i) {
+        TreeScopeEventContext* treeScopeEventContext = relatedTargetEventPath.m_treeScopeEventContexts[i].get();
+        relatedTargetMap.add(&treeScopeEventContext->treeScope(), treeScopeEventContext->target());
+    }
+}
+
+EventTarget* EventPath::findRelatedNode(TreeScope* scope, RelatedTargetMap& relatedTargetMap)
+{
+    Vector<TreeScope*, 32> parentTreeScopes;
+    EventTarget* relatedNode = 0;
+    while (scope) {
+        parentTreeScopes.append(scope);
+        RelatedTargetMap::const_iterator iter = relatedTargetMap.find(scope);
+        if (iter != relatedTargetMap.end() && iter->value) {
+            relatedNode = iter->value;
+            break;
+        }
+        scope = scope->olderShadowRootOrParentTreeScope();
+    }
+    ASSERT(relatedNode);
+    for (Vector<TreeScope*, 32>::iterator iter = parentTreeScopes.begin(); iter < parentTreeScopes.end(); ++iter)
+        relatedTargetMap.add(*iter, relatedNode);
+    return relatedNode;
+}
+
+void EventPath::adjustForRelatedTarget(Node* target, EventTarget* relatedTarget)
+{
+    if (!target)
+        return;
+    if (!relatedTarget)
+        return;
+    Node* relatedNode = relatedTarget->toNode();
+    if (!relatedNode)
+        return;
+    if (target->document() != relatedNode->document())
+        return;
+    if (!target->inDocument() || !relatedNode->inDocument())
+        return;
+
+    RelatedTargetMap relatedNodeMap;
+    buildRelatedNodeMap(relatedNode, relatedNodeMap);
+
+    for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
+        TreeScopeEventContext* treeScopeEventContext = m_treeScopeEventContexts[i].get();
+        EventTarget* adjustedRelatedTarget = findRelatedNode(&treeScopeEventContext->treeScope(), relatedNodeMap);
+        ASSERT(adjustedRelatedTarget);
+        treeScopeEventContext->setRelatedTarget(adjustedRelatedTarget);
+    }
+
+    shrinkIfNeeded(target, relatedTarget);
+}
+
+void EventPath::shrinkIfNeeded(const Node* target, const EventTarget* relatedTarget)
+{
+    // Synthetic mouse events can have a relatedTarget which is identical to the target.
+    bool targetIsIdenticalToToRelatedTarget = (target == relatedTarget);
+
+    for (size_t i = 0; i < size(); ++i) {
+        if (targetIsIdenticalToToRelatedTarget) {
+            if (target->treeScope().rootNode() == at(i).node()) {
+                shrink(i + 1);
+                break;
+            }
+        } else if (at(i).target() == at(i).relatedTarget()) {
+            // Event dispatching should be stopped here.
+            shrink(i);
+            break;
+        }
+    }
+}
+
+void EventPath::adjustForTouchEvent(Node* node, TouchEvent& touchEvent)
+{
+    Vector<TouchList*> adjustedTouches;
+    Vector<TouchList*> adjustedTargetTouches;
+    Vector<TouchList*> adjustedChangedTouches;
+    Vector<TreeScope*> treeScopes;
+
+    for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
+        TouchEventContext* touchEventContext = m_treeScopeEventContexts[i]->ensureTouchEventContext();
+        adjustedTouches.append(&touchEventContext->touches());
+        adjustedTargetTouches.append(&touchEventContext->targetTouches());
+        adjustedChangedTouches.append(&touchEventContext->changedTouches());
+        treeScopes.append(&m_treeScopeEventContexts[i]->treeScope());
+    }
+
+    adjustTouchList(node, touchEvent.touches(), adjustedTouches, treeScopes);
+    adjustTouchList(node, touchEvent.targetTouches(), adjustedTargetTouches, treeScopes);
+    adjustTouchList(node, touchEvent.changedTouches(), adjustedChangedTouches, treeScopes);
+
+#ifndef NDEBUG
+    for (size_t i = 0; i < m_treeScopeEventContexts.size(); ++i) {
+        TreeScope& treeScope = m_treeScopeEventContexts[i]->treeScope();
+        TouchEventContext* touchEventContext = m_treeScopeEventContexts[i]->touchEventContext();
+        checkReachability(treeScope, touchEventContext->touches());
+        checkReachability(treeScope, touchEventContext->targetTouches());
+        checkReachability(treeScope, touchEventContext->changedTouches());
+    }
+#endif
+}
+
+void EventPath::adjustTouchList(const Node* node, const TouchList* touchList, Vector<TouchList*> adjustedTouchList, const Vector<TreeScope*>& treeScopes)
+{
+    if (!touchList)
+        return;
+    for (size_t i = 0; i < touchList->length(); ++i) {
+        const Touch& touch = *touchList->item(i);
+        RelatedTargetMap relatedNodeMap;
+        buildRelatedNodeMap(touch.target()->toNode(), relatedNodeMap);
+        for (size_t j = 0; j < treeScopes.size(); ++j) {
+            adjustedTouchList[j]->append(touch.cloneWithNewTarget(findRelatedNode(treeScopes[j], relatedNodeMap)));
+        }
+    }
+}
+
+#ifndef NDEBUG
+void EventPath::checkReachability(TreeScope& treeScope, TouchList& touchList)
+{
+    for (size_t i = 0; i < touchList.length(); ++i)
+        ASSERT(touchList.item(i)->target()->toNode()->treeScope().isInclusiveOlderSiblingShadowRootOrAncestorTreeScopeOf(treeScope));
+}
+#endif
+
 } // namespace
diff --git a/Source/core/events/EventPath.h b/Source/core/events/EventPath.h
index 5df0d5d..b29f2b6 100644
--- a/Source/core/events/EventPath.h
+++ b/Source/core/events/EventPath.h
@@ -27,15 +27,20 @@
 #ifndef EventPath_h
 #define EventPath_h
 
-#include "wtf/OwnPtr.h"
+#include "core/events/NodeEventContext.h"
+#include "core/events/TreeScopeEventContext.h"
+
+#include "wtf/HashMap.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
 class Event;
-class EventContext;
 class EventTarget;
 class Node;
+class TouchEvent;
+class TouchList;
+class TreeScope;
 
 enum EventDispatchBehavior {
     RetargetEvent,
@@ -48,14 +53,15 @@
     explicit EventPath(Node*);
     void resetWith(Node*);
 
-    EventContext& operator[](size_t index) { return *m_eventContexts[index]; }
-    const EventContext& operator[](size_t index) const { return *m_eventContexts[index]; }
-    EventContext& last() const { return *m_eventContexts[size() - 1]; }
+    NodeEventContext& operator[](size_t index) { return m_nodeEventContexts[index]; }
+    const NodeEventContext& operator[](size_t index) const { return m_nodeEventContexts[index]; }
+    const NodeEventContext& last() const { return m_nodeEventContexts[size() - 1]; }
 
-    bool isEmpty() const { return m_eventContexts.isEmpty(); }
-    size_t size() const { return m_eventContexts.size(); }
+    bool isEmpty() const { return m_nodeEventContexts.isEmpty(); }
+    size_t size() const { return m_nodeEventContexts.size(); }
 
-    void shrink(size_t newSize) { m_eventContexts.shrink(newSize); }
+    void adjustForRelatedTarget(Node*, EventTarget* relatedTarget);
+    void adjustForTouchEvent(Node*, TouchEvent&);
 
     static Node* parent(Node*);
     static EventTarget* eventTargetRespectingTargetRules(Node*);
@@ -63,17 +69,35 @@
 private:
     EventPath();
 
-    EventContext& at(size_t index) { return *m_eventContexts[index]; }
+    NodeEventContext& at(size_t index) { return m_nodeEventContexts[index]; }
 
-    void addEventContext(Node*, bool isMouseOrFocusEvent, bool isTouchEvent);
+    void addNodeEventContext(Node*);
 
     void calculatePath();
     void calculateAdjustedTargets();
-    void calculateAdjustedEventPathForEachNode();
+    void calculateAdjustedEventPath();
 
-    Vector<OwnPtr<EventContext>, 32> m_eventContexts;
+    void shrink(size_t newSize) { m_nodeEventContexts.shrink(newSize); }
+    void shrinkIfNeeded(const Node* target, const EventTarget* relatedTarget);
+
+    void adjustTouchList(const Node*, const TouchList*, Vector<TouchList*> adjustedTouchList, const Vector<TreeScope*>& treeScopes);
+
+    typedef HashMap<TreeScope*, RefPtr<TreeScopeEventContext> > TreeScopeEventContextMap;
+    TreeScopeEventContext* ensureTreeScopeEventContext(Node* currentTarget, TreeScope*, TreeScopeEventContextMap&);
+
+    typedef HashMap<TreeScope*, EventTarget*> RelatedTargetMap;
+
+    static void buildRelatedNodeMap(const Node*, RelatedTargetMap&);
+    static EventTarget* findRelatedNode(TreeScope*, RelatedTargetMap&);
+
+#ifndef NDEBUG
+    static void checkReachability(TreeScope&, TouchList&);
+#endif
+
+    Vector<NodeEventContext, 64> m_nodeEventContexts;
     Node* m_node;
     Event* m_event;
+    Vector<RefPtr<TreeScopeEventContext> > m_treeScopeEventContexts;
 };
 
 } // namespace
diff --git a/Source/core/events/EventRetargeter.cpp b/Source/core/events/EventRetargeter.cpp
deleted file mode 100644
index 4281150..0000000
--- a/Source/core/events/EventRetargeter.cpp
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/events/EventRetargeter.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/dom/ContainerNode.h"
-#include "core/dom/FullscreenElementStack.h"
-#include "core/dom/Touch.h"
-#include "core/dom/TouchList.h"
-#include "core/dom/TreeScope.h"
-#include "core/dom/shadow/InsertionPoint.h"
-#include "core/dom/shadow/ShadowRoot.h"
-#include "core/events/EventContext.h"
-#include "core/events/EventPath.h"
-#include "core/events/FocusEvent.h"
-#include "core/events/MouseEvent.h"
-#include "core/events/TouchEvent.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-void EventRetargeter::adjustForMouseEvent(Node* node, MouseEvent& mouseEvent)
-{
-    adjustForRelatedTarget(node, mouseEvent.relatedTarget(), mouseEvent.eventPath());
-}
-
-void EventRetargeter::adjustForFocusEvent(Node* node, FocusEvent& focusEvent)
-{
-    adjustForRelatedTarget(node, focusEvent.relatedTarget(), focusEvent.eventPath());
-}
-
-void EventRetargeter::adjustForTouchEvent(Node* node, TouchEvent& touchEvent)
-{
-    EventPath& eventPath = touchEvent.eventPath();
-    size_t eventPathSize = eventPath.size();
-
-    EventPathTouchLists eventPathTouches(eventPathSize);
-    EventPathTouchLists eventPathTargetTouches(eventPathSize);
-    EventPathTouchLists eventPathChangedTouches(eventPathSize);
-
-    for (size_t i = 0; i < eventPathSize; ++i) {
-        ASSERT(eventPath[i].isTouchEventContext());
-        TouchEventContext& touchEventContext = toTouchEventContext(eventPath[i]);
-        eventPathTouches[i] = touchEventContext.touches();
-        eventPathTargetTouches[i] = touchEventContext.targetTouches();
-        eventPathChangedTouches[i] = touchEventContext.changedTouches();
-    }
-
-    adjustTouchList(node, touchEvent.touches(), eventPath, eventPathTouches);
-    adjustTouchList(node, touchEvent.targetTouches(), eventPath, eventPathTargetTouches);
-    adjustTouchList(node, touchEvent.changedTouches(), eventPath, eventPathChangedTouches);
-}
-
-void EventRetargeter::adjustTouchList(const Node* node, const TouchList* touchList, const EventPath& eventPath, EventPathTouchLists& eventPathTouchLists)
-{
-    if (!touchList)
-        return;
-    size_t eventPathSize = eventPath.size();
-    ASSERT(eventPathTouchLists.size() == eventPathSize);
-    for (size_t i = 0; i < touchList->length(); ++i) {
-        const Touch& touch = *touchList->item(i);
-        AdjustedTargets adjustedNodes;
-        calculateAdjustedNodes(node, touch.target()->toNode(), DoesNotStopAtBoundary, const_cast<EventPath&>(eventPath), adjustedNodes);
-        ASSERT(adjustedNodes.size() == eventPathSize);
-        for (size_t j = 0; j < eventPathSize; ++j)
-            eventPathTouchLists[j]->append(touch.cloneWithNewTarget(adjustedNodes[j].get()));
-    }
-}
-
-void EventRetargeter::adjustForRelatedTarget(const Node* node, EventTarget* relatedTarget, EventPath& eventPath)
-{
-    if (!node)
-        return;
-    if (!relatedTarget)
-        return;
-    Node* relatedNode = relatedTarget->toNode();
-    if (!relatedNode)
-        return;
-    AdjustedTargets adjustedNodes;
-    calculateAdjustedNodes(node, relatedNode, StopAtBoundaryIfNeeded, eventPath, adjustedNodes);
-    ASSERT(adjustedNodes.size() <= eventPath.size());
-    for (size_t i = 0; i < adjustedNodes.size(); ++i) {
-        ASSERT(eventPath[i].isMouseOrFocusEventContext());
-        MouseOrFocusEventContext& mouseOrFocusEventContext = static_cast<MouseOrFocusEventContext&>(eventPath[i]);
-        mouseOrFocusEventContext.setRelatedTarget(adjustedNodes[i]);
-    }
-}
-
-void EventRetargeter::calculateAdjustedNodes(const Node* node, const Node* relatedNode, EventWithRelatedTargetDispatchBehavior eventWithRelatedTargetDispatchBehavior, EventPath& eventPath, AdjustedTargets& adjustedTargets)
-{
-    RelatedTargetMap relatedNodeMap;
-    buildRelatedNodeMap(relatedNode, relatedNodeMap);
-
-    // Synthetic mouse events can have a relatedTarget which is identical to the target.
-    bool targetIsIdenticalToToRelatedTarget = (node == relatedNode);
-
-    TreeScope* lastTreeScope = 0;
-    EventTarget* adjustedTarget = 0;
-
-    for (size_t i = 0; i < eventPath.size(); ++i) {
-        TreeScope* scope = &eventPath[i].node()->treeScope();
-        if (scope == lastTreeScope) {
-            // Re-use the previous adjustedRelatedTarget if treeScope does not change. Just for the performance optimization.
-            adjustedTargets.append(adjustedTarget);
-        } else {
-            adjustedTarget = findRelatedNode(scope, relatedNodeMap);
-            adjustedTargets.append(adjustedTarget);
-        }
-        lastTreeScope = scope;
-        if (eventWithRelatedTargetDispatchBehavior == DoesNotStopAtBoundary)
-            continue;
-        if (targetIsIdenticalToToRelatedTarget) {
-            if (node->treeScope().rootNode() == eventPath[i].node()) {
-                eventPath.shrink(i + 1);
-                break;
-            }
-        } else if (eventPath[i].target() == adjustedTarget) {
-            // Event dispatching should be stopped here.
-            eventPath.shrink(i);
-            adjustedTargets.shrink(adjustedTargets.size() - 1);
-            break;
-        }
-    }
-}
-
-void EventRetargeter::buildRelatedNodeMap(const Node* relatedNode, RelatedTargetMap& relatedTargetMap)
-{
-    TreeScope* lastTreeScope = 0;
-    EventPath eventPath(const_cast<Node*>(relatedNode));
-    for (size_t i = 0; i < eventPath.size(); ++i) {
-        TreeScope* treeScope = &eventPath[i].node()->treeScope();
-        if (treeScope != lastTreeScope)
-            relatedTargetMap.add(treeScope, eventPath[i].target());
-        lastTreeScope = treeScope;
-    }
-}
-
-EventTarget* EventRetargeter::findRelatedNode(TreeScope* scope, RelatedTargetMap& relatedTargetMap)
-{
-    Vector<TreeScope*, 32> parentTreeScopes;
-    EventTarget* relatedNode = 0;
-    while (scope) {
-        parentTreeScopes.append(scope);
-        RelatedTargetMap::const_iterator found = relatedTargetMap.find(scope);
-        if (found != relatedTargetMap.end()) {
-            relatedNode = found->value;
-            break;
-        }
-        scope = scope->parentTreeScope();
-    }
-    for (Vector<TreeScope*, 32>::iterator iter = parentTreeScopes.begin(); iter < parentTreeScopes.end(); ++iter)
-        relatedTargetMap.add(*iter, relatedNode);
-    return relatedNode;
-}
-
-}
diff --git a/Source/core/events/EventRetargeter.h b/Source/core/events/EventRetargeter.h
deleted file mode 100644
index 4edcded..0000000
--- a/Source/core/events/EventRetargeter.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef EventRetargeter_h
-#define EventRetargeter_h
-
-#include "wtf/HashMap.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class EventPath;
-class EventTarget;
-class FocusEvent;
-class MouseEvent;
-class Node;
-class TouchEvent;
-class TouchList;
-class TreeScope;
-
-class EventRetargeter {
-public:
-    static void adjustForMouseEvent(Node*, MouseEvent&);
-    static void adjustForFocusEvent(Node*, FocusEvent&);
-    typedef Vector<RefPtr<TouchList> > EventPathTouchLists;
-    static void adjustForTouchEvent(Node*, TouchEvent&);
-
-private:
-    typedef Vector<RefPtr<EventTarget> > AdjustedTargets;
-    typedef HashMap<TreeScope*, EventTarget*> RelatedTargetMap;
-    enum EventWithRelatedTargetDispatchBehavior {
-        StopAtBoundaryIfNeeded,
-        DoesNotStopAtBoundary
-    };
-    static void adjustForRelatedTarget(const Node*, EventTarget* relatedTarget, EventPath&);
-    static void calculateAdjustedNodes(const Node*, const Node* relatedNode, EventWithRelatedTargetDispatchBehavior, EventPath&, AdjustedTargets&);
-    static void buildRelatedNodeMap(const Node*, RelatedTargetMap&);
-    static EventTarget* findRelatedNode(TreeScope*, RelatedTargetMap&);
-    static void adjustTouchList(const Node*, const TouchList*, const EventPath&, EventPathTouchLists&);
-};
-
-}
-
-#endif // EventRetargeter_h
diff --git a/Source/core/events/EventTarget.cpp b/Source/core/events/EventTarget.cpp
index 6e96b47..99ef922 100644
--- a/Source/core/events/EventTarget.cpp
+++ b/Source/core/events/EventTarget.cpp
@@ -33,7 +33,6 @@
 #include "core/events/EventTarget.h"
 
 #include "RuntimeEnabledFeatures.h"
-#include "bindings/v8/DOMWrapperWorld.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/events/Event.h"
 #include "core/dom/ExceptionCode.h"
@@ -83,7 +82,12 @@
 
 bool EventTarget::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
 {
-    return ensureEventTargetData().eventListenerMap.add(eventType, listener, useCapture);
+    EventListener* eventListener = listener.get();
+    if (ensureEventTargetData().eventListenerMap.add(eventType, listener, useCapture)) {
+        InspectorInstrumentation::didAddEventListener(this, eventType, eventListener, useCapture);
+        return true;
+    }
+    return false;
 }
 
 bool EventTarget::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
@@ -96,6 +100,7 @@
 
     if (!d->eventListenerMap.remove(eventType, listener, useCapture, indexOfRemovedListener))
         return false;
+    InspectorInstrumentation::didRemoveEventListener(this, eventType, listener, useCapture);
 
     // Notify firing events planning to invoke the listener at 'index' that
     // they have one less listener to invoke.
@@ -117,38 +122,28 @@
     return true;
 }
 
-bool EventTarget::setAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld)
+bool EventTarget::setAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
 {
-    clearAttributeEventListener(eventType, isolatedWorld);
+    clearAttributeEventListener(eventType);
     if (!listener)
         return false;
     return addEventListener(eventType, listener, false);
 }
 
-EventListener* EventTarget::getAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld)
+EventListener* EventTarget::getAttributeEventListener(const AtomicString& eventType)
 {
     const EventListenerVector& entry = getEventListeners(eventType);
     for (size_t i = 0; i < entry.size(); ++i) {
         EventListener* listener = entry[i].listener.get();
-        if (listener->isAttribute()) {
-            DOMWrapperWorld* listenerWorld = listener->world();
-            // Worker listener
-            if (!listenerWorld) {
-                ASSERT(!isolatedWorld);
-                return listener;
-            }
-            if (listenerWorld->isMainWorld() && !isolatedWorld)
-                return listener;
-            if (listenerWorld == isolatedWorld)
-                return listener;
-        }
+        if (listener->isAttribute() && listener->belongsToTheCurrentWorld())
+            return listener;
     }
     return 0;
 }
 
-bool EventTarget::clearAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld)
+bool EventTarget::clearAttributeEventListener(const AtomicString& eventType)
 {
-    EventListener* listener = getAttributeEventListener(eventType, isolatedWorld);
+    EventListener* listener = getAttributeEventListener(eventType);
     if (!listener)
         return false;
     return removeEventListener(eventType, listener, false);
@@ -189,7 +184,7 @@
 {
 }
 
-static AtomicString legacyType(const Event* event)
+static const AtomicString& legacyType(const Event* event)
 {
     if (event->type() == EventTypeNames::transitionend)
         return EventTypeNames::webkitTransitionEnd;
@@ -206,7 +201,7 @@
     if (event->type() == EventTypeNames::wheel)
         return EventTypeNames::mousewheel;
 
-    return emptyString();
+    return emptyAtom;
 }
 
 void EventTarget::countLegacyEvents(const AtomicString& legacyTypeName, EventListenerVector* listenersVector, EventListenerVector* legacyListenersVector)
@@ -242,11 +237,11 @@
         if (DOMWindow* executingWindow = this->executingWindow()) {
             if (legacyListenersVector) {
                 if (listenersVector)
-                    UseCounter::count(executingWindow, prefixedAndUnprefixedFeature);
+                    UseCounter::count(executingWindow->document(), prefixedAndUnprefixedFeature);
                 else
-                    UseCounter::count(executingWindow, prefixedFeature);
+                    UseCounter::count(executingWindow->document(), prefixedFeature);
             } else if (listenersVector) {
-                UseCounter::count(executingWindow, unprefixedFeature);
+                UseCounter::count(executingWindow->document(), unprefixedFeature);
             }
         }
     }
@@ -297,12 +292,12 @@
     if (event->type() == EventTypeNames::beforeunload) {
         if (DOMWindow* executingWindow = this->executingWindow()) {
             if (executingWindow->top())
-                UseCounter::count(executingWindow, UseCounter::SubFrameBeforeUnloadFired);
-            UseCounter::count(executingWindow, UseCounter::DocumentBeforeUnloadFired);
+                UseCounter::count(executingWindow->document(), UseCounter::SubFrameBeforeUnloadFired);
+            UseCounter::count(executingWindow->document(), UseCounter::DocumentBeforeUnloadFired);
         }
     } else if (event->type() == EventTypeNames::unload) {
         if (DOMWindow* executingWindow = this->executingWindow())
-            UseCounter::count(executingWindow, UseCounter::DocumentUnloadFired);
+            UseCounter::count(executingWindow->document(), UseCounter::DocumentUnloadFired);
     }
 
     bool userEventWasHandled = false;
@@ -327,7 +322,7 @@
         if (!context)
             break;
 
-        InspectorInstrumentationCookie cookie = InspectorInstrumentation::willHandleEvent(context, event);
+        InspectorInstrumentationCookie cookie = InspectorInstrumentation::willHandleEvent(this, event->type(), registeredListener.listener.get(), registeredListener.useCapture);
         // To match Mozilla, the AT_TARGET phase fires both capturing and bubbling
         // event listeners, even though that violates some versions of the DOM spec.
         registeredListener.listener->handleEvent(context, event);
@@ -357,12 +352,19 @@
     return *listenerVector;
 }
 
+Vector<AtomicString> EventTarget::eventTypes()
+{
+    EventTargetData* d = eventTargetData();
+    return d ? d->eventListenerMap.eventTypes() : Vector<AtomicString>();
+}
+
 void EventTarget::removeAllEventListeners()
 {
     EventTargetData* d = eventTargetData();
     if (!d)
         return;
     d->eventListenerMap.clear();
+    InspectorInstrumentation::didRemoveAllEventListeners(this);
 
     // Notify firing events planning to invoke the listener at 'index' that
     // they have one less listener to invoke.
diff --git a/Source/core/events/EventTarget.h b/Source/core/events/EventTarget.h
index fa21925..28f7545 100644
--- a/Source/core/events/EventTarget.h
+++ b/Source/core/events/EventTarget.h
@@ -57,7 +57,6 @@
 class MediaController;
 class MediaStream;
 class MessagePort;
-class NamedFlow;
 class Node;
 class Notification;
 class SVGElementInstance;
@@ -116,16 +115,16 @@
     virtual void uncaughtExceptionInEventHandler();
 
     // Used for legacy "onEvent" attribute APIs.
-    bool setAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, DOMWrapperWorld* isolatedWorld = 0);
-    EventListener* getAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld = 0);
+    bool setAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>);
+    EventListener* getAttributeEventListener(const AtomicString& eventType);
 
     bool hasEventListeners() const;
     bool hasEventListeners(const AtomicString& eventType) const;
     bool hasCapturingEventListeners(const AtomicString& eventType);
     const EventListenerVector& getEventListeners(const AtomicString& eventType);
+    Vector<AtomicString> eventTypes();
 
     bool fireEventListeners(Event*);
-    bool isFiringEventListeners();
 
 protected:
     virtual ~EventTarget();
@@ -143,7 +142,7 @@
     void fireEventListeners(Event*, EventTargetData*, EventListenerVector&);
     void countLegacyEvents(const AtomicString& legacyTypeName, EventListenerVector*, EventListenerVector*);
 
-    bool clearAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld);
+    bool clearAttributeEventListener(const AtomicString& eventType);
 
     friend class EventListenerIterator;
 };
@@ -159,57 +158,49 @@
 // FIXME: These macros should be split into separate DEFINE and DECLARE
 // macros to avoid causing so many header includes.
 #define DEFINE_ATTRIBUTE_EVENT_LISTENER(attribute) \
-    EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return getAttributeEventListener(EventTypeNames::attribute, isolatedWorld); } \
-    void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld = 0) { setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); } \
+    EventListener* on##attribute() { return getAttributeEventListener(EventTypeNames::attribute); } \
+    void setOn##attribute(PassRefPtr<EventListener> listener) { setAttributeEventListener(EventTypeNames::attribute, listener); } \
 
 #define DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(attribute) \
-    static EventListener* on##attribute(EventTarget* eventTarget, DOMWrapperWorld* isolatedWorld) { return eventTarget->getAttributeEventListener(EventTypeNames::attribute, isolatedWorld); } \
-    static void setOn##attribute(EventTarget* eventTarget, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld = 0) { eventTarget->setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); } \
+    static EventListener* on##attribute(EventTarget* eventTarget) { return eventTarget->getAttributeEventListener(EventTypeNames::attribute); } \
+    static void setOn##attribute(EventTarget* eventTarget, PassRefPtr<EventListener> listener) { eventTarget->setAttributeEventListener(EventTypeNames::attribute, listener); } \
 
 #define DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(attribute) \
-    EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return document().getWindowAttributeEventListener(EventTypeNames::attribute, isolatedWorld); } \
-    void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { document().setWindowAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); } \
+    EventListener* on##attribute() { return document().getWindowAttributeEventListener(EventTypeNames::attribute); } \
+    void setOn##attribute(PassRefPtr<EventListener> listener) { document().setWindowAttributeEventListener(EventTypeNames::attribute, listener); } \
 
 #define DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(attribute) \
-    static EventListener* on##attribute(EventTarget* eventTarget, DOMWrapperWorld* isolatedWorld) { \
+    static EventListener* on##attribute(EventTarget* eventTarget) { \
         if (Node* node = eventTarget->toNode()) \
-            return node->document().getWindowAttributeEventListener(EventTypeNames::attribute, isolatedWorld); \
+            return node->document().getWindowAttributeEventListener(EventTypeNames::attribute); \
         ASSERT(eventTarget->toDOMWindow()); \
-        return eventTarget->getAttributeEventListener(EventTypeNames::attribute, isolatedWorld); \
+        return eventTarget->getAttributeEventListener(EventTypeNames::attribute); \
     } \
-    static void setOn##attribute(EventTarget* eventTarget, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { \
+    static void setOn##attribute(EventTarget* eventTarget, PassRefPtr<EventListener> listener) { \
         if (Node* node = eventTarget->toNode()) \
-            node->document().setWindowAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); \
+            node->document().setWindowAttributeEventListener(EventTypeNames::attribute, listener); \
         else { \
             ASSERT(eventTarget->toDOMWindow()); \
-            eventTarget->setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); \
+            eventTarget->setAttributeEventListener(EventTypeNames::attribute, listener); \
         } \
     }
 
 #define DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(attribute, eventName) \
-    EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return getAttributeEventListener(EventTypeNames::eventName, isolatedWorld); } \
-    void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { setAttributeEventListener(EventTypeNames::eventName, listener, isolatedWorld); } \
+    EventListener* on##attribute() { return getAttributeEventListener(EventTypeNames::eventName); } \
+    void setOn##attribute(PassRefPtr<EventListener> listener) { setAttributeEventListener(EventTypeNames::eventName, listener); } \
 
 #define DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(recipient, attribute) \
-    EventListener* on##attribute(DOMWrapperWorld* isolatedWorld); \
-    void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld);
+    EventListener* on##attribute(); \
+    void setOn##attribute(PassRefPtr<EventListener> listener);
 
 #define DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(type, recipient, attribute) \
-    EventListener* type::on##attribute(DOMWrapperWorld* isolatedWorld) { return recipient ? recipient->getAttributeEventListener(EventTypeNames::attribute, isolatedWorld) : 0; } \
-    void type::setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) \
+    EventListener* type::on##attribute() { return recipient ? recipient->getAttributeEventListener(EventTypeNames::attribute) : 0; } \
+    void type::setOn##attribute(PassRefPtr<EventListener> listener) \
     { \
         if (recipient) \
-            recipient->setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); \
+            recipient->setAttributeEventListener(EventTypeNames::attribute, listener); \
     }
 
-inline bool EventTarget::isFiringEventListeners()
-{
-    EventTargetData* d = eventTargetData();
-    if (!d)
-        return false;
-    return d->firingEventIterators && !d->firingEventIterators->isEmpty();
-}
-
 inline bool EventTarget::hasEventListeners() const
 {
     // FIXME: We should have a const version of eventTargetData.
diff --git a/Source/core/events/EventTargetFactory.in b/Source/core/events/EventTargetFactory.in
index a3eb30b..69317cb 100644
--- a/Source/core/events/EventTargetFactory.in
+++ b/Source/core/events/EventTargetFactory.in
@@ -3,7 +3,6 @@
 core/css/FontFaceSet
 core/dom/MessagePort
 core/dom/Node
-core/dom/WebKitNamedFlow ImplementedAs=NamedFlow
 core/fileapi/FileReader
 core/html/MediaController
 core/html/ime/InputMethodContext
@@ -13,6 +12,7 @@
 core/loader/appcache/ApplicationCache
 core/page/EventSource
 core/timing/Performance
+core/frame/Screen
 core/frame/Window ImplementedAs=DOMWindow
 core/svg/SVGElementInstance
 core/workers/DedicatedWorkerGlobalScope
@@ -21,7 +21,7 @@
 core/workers/Worker
 core/xml/XMLHttpRequest
 core/xml/XMLHttpRequestUpload
-modules/encryptedmedia/MediaKeySession Conditional=ENCRYPTED_MEDIA_V2
+modules/encryptedmedia/MediaKeySession
 modules/filesystem/FileWriter
 modules/indexeddb/IDBDatabase
 modules/indexeddb/IDBOpenDBRequest
diff --git a/Source/core/events/EventTypeNames.in b/Source/core/events/EventTypeNames.in
index b814801..96d8286 100644
--- a/Source/core/events/EventTypeNames.in
+++ b/Source/core/events/EventTypeNames.in
@@ -119,6 +119,7 @@
 mouseup
 mousewheel
 mute
+needkey
 negotiationneeded
 nomatch
 noupdate
@@ -137,6 +138,7 @@
 popstate
 progress
 ratechange
+ready
 readystatechange
 removesourcebuffer
 removestream
@@ -214,8 +216,6 @@
 webkitprerenderload
 webkitprerenderstart
 webkitprerenderstop
-webkitregionlayoutupdate
-webkitregionoversetchange
 webkitremovesourcebuffer
 webkitresourcetimingbufferfull
 webkitsourceclose
diff --git a/Source/core/events/FocusEvent.cpp b/Source/core/events/FocusEvent.cpp
index e201de0..b69c74a 100644
--- a/Source/core/events/FocusEvent.cpp
+++ b/Source/core/events/FocusEvent.cpp
@@ -28,7 +28,6 @@
 
 #include "core/events/Event.h"
 #include "core/events/EventDispatcher.h"
-#include "core/events/EventRetargeter.h"
 #include "core/events/ThreadLocalEventNames.h"
 
 namespace WebCore {
@@ -79,7 +78,7 @@
 
 bool FocusEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
 {
-    EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
+    event()->eventPath().adjustForRelatedTarget(dispatcher->node(), event()->relatedTarget());
     return EventDispatchMediator::dispatchEvent(dispatcher);
 }
 
@@ -95,7 +94,7 @@
 
 bool BlurEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
 {
-    EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
+    event()->eventPath().adjustForRelatedTarget(dispatcher->node(), event()->relatedTarget());
     return EventDispatchMediator::dispatchEvent(dispatcher);
 }
 
@@ -111,7 +110,7 @@
 
 bool FocusInEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
 {
-    EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
+    event()->eventPath().adjustForRelatedTarget(dispatcher->node(), event()->relatedTarget());
     return EventDispatchMediator::dispatchEvent(dispatcher);
 }
 
@@ -127,7 +126,7 @@
 
 bool FocusOutEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
 {
-    EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
+    event()->eventPath().adjustForRelatedTarget(dispatcher->node(), event()->relatedTarget());
     return EventDispatchMediator::dispatchEvent(dispatcher);
 }
 
diff --git a/Source/core/events/FocusEvent.h b/Source/core/events/FocusEvent.h
index 20a9a28..517f71f 100644
--- a/Source/core/events/FocusEvent.h
+++ b/Source/core/events/FocusEvent.h
@@ -39,7 +39,7 @@
     RefPtr<EventTarget> relatedTarget;
 };
 
-class FocusEvent : public UIEvent {
+class FocusEvent FINAL : public UIEvent {
 public:
     static PassRefPtr<FocusEvent> create()
     {
@@ -60,8 +60,8 @@
     EventTarget* relatedTarget(bool& isNull) const { isNull = !m_relatedTarget; return m_relatedTarget.get(); }
     void setRelatedTarget(EventTarget* relatedTarget) { m_relatedTarget = relatedTarget; }
 
-    virtual const AtomicString& interfaceName() const;
-    virtual bool isFocusEvent() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
+    virtual bool isFocusEvent() const OVERRIDE;
 
 private:
     FocusEvent();
@@ -73,7 +73,7 @@
 
 DEFINE_EVENT_TYPE_CASTS(FocusEvent);
 
-class FocusEventDispatchMediator : public EventDispatchMediator {
+class FocusEventDispatchMediator FINAL : public EventDispatchMediator {
 public:
     static PassRefPtr<FocusEventDispatchMediator> create(PassRefPtr<FocusEvent>);
 private:
@@ -82,7 +82,7 @@
     virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
 };
 
-class BlurEventDispatchMediator : public EventDispatchMediator {
+class BlurEventDispatchMediator FINAL : public EventDispatchMediator {
 public:
     static PassRefPtr<BlurEventDispatchMediator> create(PassRefPtr<FocusEvent>);
 private:
@@ -91,7 +91,7 @@
     virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
 };
 
-class FocusInEventDispatchMediator : public EventDispatchMediator {
+class FocusInEventDispatchMediator FINAL : public EventDispatchMediator {
 public:
     static PassRefPtr<FocusInEventDispatchMediator> create(PassRefPtr<FocusEvent>);
 private:
@@ -100,7 +100,7 @@
     virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
 };
 
-class FocusOutEventDispatchMediator : public EventDispatchMediator {
+class FocusOutEventDispatchMediator FINAL : public EventDispatchMediator {
 public:
     static PassRefPtr<FocusOutEventDispatchMediator> create(PassRefPtr<FocusEvent>);
 private:
diff --git a/Source/core/events/GenericEventQueue.cpp b/Source/core/events/GenericEventQueue.cpp
index b35f85c..453eeba 100644
--- a/Source/core/events/GenericEventQueue.cpp
+++ b/Source/core/events/GenericEventQueue.cpp
@@ -56,7 +56,7 @@
     if (event->target() == m_owner)
         event->setTarget(0);
 
-    TRACE_EVENT_ASYNC_BEGIN1("event", "GenericEventQueue:enqueueEvent", event.get(), "type", event->type().string().ascii());
+    TRACE_EVENT_ASYNC_BEGIN1("event", "GenericEventQueue:enqueueEvent", event.get(), "type", event->type().ascii());
     m_pendingEvents.append(event);
 
     if (!m_timer.isActive())
@@ -71,7 +71,7 @@
 
     if (found) {
         m_pendingEvents.remove(m_pendingEvents.find(event));
-        TRACE_EVENT_ASYNC_END2("event", "GenericEventQueue:enqueueEvent", event, "type", event->type().string().ascii(), "status", "cancelled");
+        TRACE_EVENT_ASYNC_END2("event", "GenericEventQueue:enqueueEvent", event, "type", event->type().ascii(), "status", "cancelled");
     }
 
     if (m_pendingEvents.isEmpty())
@@ -92,7 +92,7 @@
     for (size_t i = 0; i < pendingEvents.size(); ++i) {
         Event* event = pendingEvents[i].get();
         EventTarget* target = event->target() ? event->target() : m_owner;
-        CString type(event->type().string().ascii());
+        CString type(event->type().ascii());
         TRACE_EVENT_ASYNC_STEP_INTO1("event", "GenericEventQueue:enqueueEvent", event, "dispatch", "type", type);
         target->dispatchEvent(pendingEvents[i].release());
         TRACE_EVENT_ASYNC_END1("event", "GenericEventQueue:enqueueEvent", event, "type", type);
@@ -111,7 +111,7 @@
 
     for (size_t i = 0; i < m_pendingEvents.size(); ++i) {
         Event* event = m_pendingEvents[i].get();
-        TRACE_EVENT_ASYNC_END2("event", "GenericEventQueue:enqueueEvent", event, "type", event->type().string().ascii(), "status", "cancelled");
+        TRACE_EVENT_ASYNC_END2("event", "GenericEventQueue:enqueueEvent", event, "type", event->type().ascii(), "status", "cancelled");
     }
     m_pendingEvents.clear();
 }
diff --git a/Source/core/events/GenericEventQueue.h b/Source/core/events/GenericEventQueue.h
index ab80f89..cf8e8a6 100644
--- a/Source/core/events/GenericEventQueue.h
+++ b/Source/core/events/GenericEventQueue.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class GenericEventQueue : public EventQueue {
+class GenericEventQueue FINAL : public EventQueue {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit GenericEventQueue(EventTarget*);
diff --git a/Source/core/events/GestureEvent.cpp b/Source/core/events/GestureEvent.cpp
index 13d5f6f..5c7e937 100644
--- a/Source/core/events/GestureEvent.cpp
+++ b/Source/core/events/GestureEvent.cpp
@@ -30,11 +30,6 @@
 
 namespace WebCore {
 
-PassRefPtr<GestureEvent> GestureEvent::create()
-{
-    return adoptRef(new GestureEvent);
-}
-
 PassRefPtr<GestureEvent> GestureEvent::create(PassRefPtr<AbstractView> view, const PlatformGestureEvent& event)
 {
     AtomicString eventType;
@@ -73,24 +68,6 @@
     return adoptRef(new GestureEvent(eventType, view, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(), event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(), deltaX, deltaY));
 }
 
-void GestureEvent::initGestureEvent(const AtomicString& type, PassRefPtr<AbstractView> view, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY)
-{
-    if (dispatched())
-        return;
-
-    initUIEvent(type, true, true, view, 0);
-    m_screenLocation = IntPoint(screenX, screenY);
-    m_ctrlKey = ctrlKey;
-    m_altKey = altKey;
-    m_shiftKey = shiftKey;
-    m_metaKey = metaKey;
-
-    m_deltaX = deltaX;
-    m_deltaY = deltaY;
-
-    initCoordinates(IntPoint(clientX, clientY));
-}
-
 const AtomicString& GestureEvent::interfaceName() const
 {
     // FIXME: when a GestureEvent.idl interface is defined, return the string "GestureEvent".
diff --git a/Source/core/events/GestureEvent.h b/Source/core/events/GestureEvent.h
index fe98200..a9696d2 100644
--- a/Source/core/events/GestureEvent.h
+++ b/Source/core/events/GestureEvent.h
@@ -32,18 +32,15 @@
 
 namespace WebCore {
 
-class GestureEvent : public MouseRelatedEvent {
+class GestureEvent FINAL : public MouseRelatedEvent {
 public:
     virtual ~GestureEvent() { }
 
-    static PassRefPtr<GestureEvent> create();
     static PassRefPtr<GestureEvent> create(PassRefPtr<AbstractView>, const PlatformGestureEvent&);
 
-    void initGestureEvent(const AtomicString& type, PassRefPtr<AbstractView>, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY);
-
     virtual bool isGestureEvent() const OVERRIDE;
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
     float deltaX() const { return m_deltaX; }
     float deltaY() const { return m_deltaY; }
@@ -56,7 +53,7 @@
     float m_deltaY;
 };
 
-class GestureEventDispatchMediator : public EventDispatchMediator {
+class GestureEventDispatchMediator FINAL : public EventDispatchMediator {
 public:
     static PassRefPtr<GestureEventDispatchMediator> create(PassRefPtr<GestureEvent> gestureEvent)
     {
diff --git a/Source/core/events/HashChangeEvent.h b/Source/core/events/HashChangeEvent.h
index e652df8..16d4f73 100644
--- a/Source/core/events/HashChangeEvent.h
+++ b/Source/core/events/HashChangeEvent.h
@@ -35,7 +35,7 @@
     String newURL;
 };
 
-class HashChangeEvent : public Event {
+class HashChangeEvent FINAL : public Event {
 public:
     static PassRefPtr<HashChangeEvent> create()
     {
@@ -66,7 +66,7 @@
     const String& oldURL() const { return m_oldURL; }
     const String& newURL() const { return m_newURL; }
 
-    virtual const AtomicString& interfaceName() const { return EventNames::HashChangeEvent; }
+    virtual const AtomicString& interfaceName() const OVERRIDE { return EventNames::HashChangeEvent; }
 
 private:
     HashChangeEvent()
diff --git a/Source/core/events/KeyboardEvent.cpp b/Source/core/events/KeyboardEvent.cpp
index c03712e..93034ad 100644
--- a/Source/core/events/KeyboardEvent.cpp
+++ b/Source/core/events/KeyboardEvent.cpp
@@ -217,15 +217,6 @@
     return keyCode();
 }
 
-KeyboardEvent* findKeyboardEvent(Event* event)
-{
-    for (Event* e = event; e; e = e->underlyingEvent()) {
-        if (e->isKeyboardEvent())
-            return toKeyboardEvent(e);
-    }
-    return 0;
-}
-
 PassRefPtr<KeyboardEventDispatchMediator> KeyboardEventDispatchMediator::create(PassRefPtr<KeyboardEvent> event)
 {
     return adoptRef(new KeyboardEventDispatchMediator(event));
diff --git a/Source/core/events/KeyboardEvent.h b/Source/core/events/KeyboardEvent.h
index e4d1e9e..671b1bf 100644
--- a/Source/core/events/KeyboardEvent.h
+++ b/Source/core/events/KeyboardEvent.h
@@ -45,7 +45,7 @@
     bool repeat;
 };
 
-class KeyboardEvent : public UIEventWithKeyState {
+class KeyboardEvent FINAL : public UIEventWithKeyState {
 public:
     enum KeyLocationCode {
         DOM_KEY_LOCATION_STANDARD   = 0x00,
@@ -92,13 +92,13 @@
 
     const PlatformKeyboardEvent* keyEvent() const { return m_keyEvent.get(); }
 
-    int keyCode() const; // key code for keydown and keyup, character for keypress
-    int charCode() const; // character code for keypress, 0 for keydown and keyup
+    virtual int keyCode() const OVERRIDE; // key code for keydown and keyup, character for keypress
+    virtual int charCode() const OVERRIDE; // character code for keypress, 0 for keydown and keyup
     bool repeat() const { return m_isAutoRepeat; }
 
-    virtual const AtomicString& interfaceName() const;
-    virtual bool isKeyboardEvent() const;
-    virtual int which() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
+    virtual bool isKeyboardEvent() const OVERRIDE;
+    virtual int which() const OVERRIDE;
 
 private:
     KeyboardEvent();
@@ -115,8 +115,6 @@
     bool m_isAutoRepeat : 1;
 };
 
-KeyboardEvent* findKeyboardEvent(Event*);
-
 class KeyboardEventDispatchMediator : public EventDispatchMediator {
 public:
     static PassRefPtr<KeyboardEventDispatchMediator> create(PassRefPtr<KeyboardEvent>);
diff --git a/Source/core/events/MessageEvent.h b/Source/core/events/MessageEvent.h
index 64df40f..1442bf4 100644
--- a/Source/core/events/MessageEvent.h
+++ b/Source/core/events/MessageEvent.h
@@ -47,7 +47,7 @@
     MessagePortArray ports;
 };
 
-class MessageEvent : public Event {
+class MessageEvent FINAL : public Event {
 public:
     static PassRefPtr<MessageEvent> create()
     {
@@ -90,7 +90,7 @@
     MessagePortArray ports() const { return m_ports ? *m_ports : MessagePortArray(); }
     MessagePortChannelArray* channels() const { return m_channels ? m_channels.get() : 0; }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
     enum DataType {
         DataTypeScriptValue,
diff --git a/Source/core/events/MessageEvent.idl b/Source/core/events/MessageEvent.idl
index c482b08..b830e16 100644
--- a/Source/core/events/MessageEvent.idl
+++ b/Source/core/events/MessageEvent.idl
@@ -29,28 +29,28 @@
     EventConstructor,
     GlobalContext=Window&WorkerGlobalScope,
     RaisesException=Constructor,
+    Custom=Wrap,
 ] interface MessageEvent : Event {
     [InitializedByEventConstructor] readonly attribute DOMString origin;
     [InitializedByEventConstructor] readonly attribute DOMString lastEventId;
     [InitializedByEventConstructor] readonly attribute EventTarget? source; // May be a Window or a MessagePort
     [InitializedByEventConstructor, Custom=Getter] readonly attribute any data;
     [InitializedByEventConstructor] readonly attribute MessagePort[] ports;
-    [Custom] void initMessageEvent([Default=Undefined] optional DOMString typeArg,
+    [Custom, MeasureAs=InitMessageEvent] void initMessageEvent([Default=Undefined] optional DOMString typeArg,
                                    [Default=Undefined] optional boolean canBubbleArg,
                                    [Default=Undefined] optional boolean cancelableArg,
                                    [Default=Undefined] optional any dataArg,
                                    [Default=Undefined] optional DOMString originArg,
                                    [Default=Undefined] optional DOMString lastEventIdArg,
                                    [Default=Undefined] optional Window sourceArg,
-                                   [Default=Undefined] optional Array messagePorts);
+                                   [Default=Undefined] optional MessagePort[] messagePorts);
 
-    [Custom] void webkitInitMessageEvent([Default=Undefined] optional DOMString typeArg,
+    [Custom, MeasureAs=PrefixedInitMessageEvent] void webkitInitMessageEvent([Default=Undefined] optional DOMString typeArg,
                                          [Default=Undefined] optional boolean canBubbleArg,
                                          [Default=Undefined] optional boolean cancelableArg,
                                          [Default=Undefined] optional any dataArg,
                                          [Default=Undefined] optional DOMString originArg,
                                          [Default=Undefined] optional DOMString lastEventIdArg,
                                          [Default=Undefined] optional Window sourceArg,
-                                         [Default=Undefined] optional Array transferables);
+                                         [Default=Undefined] optional MessagePort[] transferables);
 };
-
diff --git a/Source/core/events/MouseEvent.cpp b/Source/core/events/MouseEvent.cpp
index 1e6a697..8c3d2fa 100644
--- a/Source/core/events/MouseEvent.cpp
+++ b/Source/core/events/MouseEvent.cpp
@@ -23,10 +23,9 @@
 #include "config.h"
 #include "core/events/MouseEvent.h"
 
-#include "core/dom/Clipboard.h"
+#include "core/clipboard/Clipboard.h"
 #include "core/dom/Element.h"
 #include "core/events/EventDispatcher.h"
-#include "core/events/EventRetargeter.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "platform/PlatformMouseEvent.h"
 
@@ -70,19 +69,6 @@
     int detail, int screenX, int screenY, int pageX, int pageY,
     int movementX, int movementY,
     bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
-    PassRefPtr<EventTarget> relatedTarget)
-
-{
-    return MouseEvent::create(type, canBubble, cancelable, view,
-        detail, screenX, screenY, pageX, pageY,
-        movementX, movementY,
-        ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget, 0, false);
-}
-
-PassRefPtr<MouseEvent> MouseEvent::create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
-    int detail, int screenX, int screenY, int pageX, int pageY,
-    int movementX, int movementY,
-    bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
     PassRefPtr<EventTarget> relatedTarget, PassRefPtr<Clipboard> clipboard, bool isSimulated)
 {
     return adoptRef(new MouseEvent(type, canBubble, cancelable, view,
@@ -251,7 +237,7 @@
 bool MouseEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
 {
     if (isSyntheticMouseEvent()) {
-        EventRetargeter::adjustForMouseEvent(dispatcher->node(), *event());
+        event()->eventPath().adjustForRelatedTarget(dispatcher->node(), event()->relatedTarget());
         return dispatcher->dispatch();
     }
 
@@ -264,7 +250,7 @@
     ASSERT(!event()->target() || event()->target() != event()->relatedTarget());
 
     EventTarget* relatedTarget = event()->relatedTarget();
-    EventRetargeter::adjustForMouseEvent(dispatcher->node(), *event());
+    event()->eventPath().adjustForRelatedTarget(dispatcher->node(), relatedTarget);
 
     dispatcher->dispatch();
     bool swallowEvent = event()->defaultHandled() || event()->defaultPrevented();
diff --git a/Source/core/events/MouseEvent.h b/Source/core/events/MouseEvent.h
index 41ab261..a61c73e 100644
--- a/Source/core/events/MouseEvent.h
+++ b/Source/core/events/MouseEvent.h
@@ -59,12 +59,6 @@
         int detail, int screenX, int screenY, int pageX, int pageY,
         int movementX, int movementY,
         bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
-        PassRefPtr<EventTarget> relatedTarget);
-
-    static PassRefPtr<MouseEvent> create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
-        int detail, int screenX, int screenY, int pageX, int pageY,
-        int movementX, int movementY,
-        bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
         PassRefPtr<EventTarget> relatedTarget, PassRefPtr<Clipboard>, bool isSimulated = false);
 
     static PassRefPtr<MouseEvent> create(const AtomicString& eventType, PassRefPtr<AbstractView>, const PlatformMouseEvent&, int detail, PassRefPtr<Node> relatedTarget);
@@ -86,18 +80,16 @@
     EventTarget* relatedTarget(bool& isNull) const { isNull = !m_relatedTarget; return m_relatedTarget.get(); }
     void setRelatedTarget(PassRefPtr<EventTarget> relatedTarget) { m_relatedTarget = relatedTarget; }
 
-    Clipboard* clipboard() const { return m_clipboard.get(); }
-
     Node* toElement() const;
     Node* fromElement() const;
 
     Clipboard* dataTransfer() const { return isDragEvent() ? m_clipboard.get() : 0; }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
-    virtual bool isMouseEvent() const;
-    virtual bool isDragEvent() const;
-    virtual int which() const;
+    virtual bool isMouseEvent() const OVERRIDE;
+    virtual bool isDragEvent() const OVERRIDE FINAL;
+    virtual int which() const OVERRIDE FINAL;
 
 protected:
     MouseEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
@@ -117,7 +109,7 @@
     RefPtr<Clipboard> m_clipboard;
 };
 
-class SimulatedMouseEvent : public MouseEvent {
+class SimulatedMouseEvent FINAL : public MouseEvent {
 public:
     static PassRefPtr<SimulatedMouseEvent> create(const AtomicString& eventType, PassRefPtr<AbstractView>, PassRefPtr<Event> underlyingEvent);
     virtual ~SimulatedMouseEvent();
@@ -126,7 +118,7 @@
     SimulatedMouseEvent(const AtomicString& eventType, PassRefPtr<AbstractView>, PassRefPtr<Event> underlyingEvent);
 };
 
-class MouseEventDispatchMediator : public EventDispatchMediator {
+class MouseEventDispatchMediator FINAL : public EventDispatchMediator {
 public:
     enum MouseEventType { SyntheticMouseEvent, NonSyntheticMouseEvent};
     static PassRefPtr<MouseEventDispatchMediator> create(PassRefPtr<MouseEvent>, MouseEventType = NonSyntheticMouseEvent);
diff --git a/Source/core/events/MouseRelatedEvent.cpp b/Source/core/events/MouseRelatedEvent.cpp
index 4953243..f9df0d8 100644
--- a/Source/core/events/MouseRelatedEvent.cpp
+++ b/Source/core/events/MouseRelatedEvent.cpp
@@ -208,11 +208,6 @@
     return m_pageLocation.y();
 }
 
-const LayoutPoint& MouseRelatedEvent::pageLocation() const
-{
-    return m_pageLocation;
-}
-
 int MouseRelatedEvent::x() const
 {
     // FIXME: This is not correct.
diff --git a/Source/core/events/MouseRelatedEvent.h b/Source/core/events/MouseRelatedEvent.h
index fbaeb9c..ee70b84 100644
--- a/Source/core/events/MouseRelatedEvent.h
+++ b/Source/core/events/MouseRelatedEvent.h
@@ -42,14 +42,13 @@
         int webkitMovementX() const { return m_movementDelta.x(); }
         int webkitMovementY() const { return m_movementDelta.y(); }
         const LayoutPoint& clientLocation() const { return m_clientLocation; }
-        int layerX();
-        int layerY();
+        virtual int layerX() OVERRIDE FINAL;
+        virtual int layerY() OVERRIDE FINAL;
         int offsetX();
         int offsetY();
         bool isSimulated() const { return m_isSimulated; }
-        virtual int pageX() const;
-        virtual int pageY() const;
-        virtual const LayoutPoint& pageLocation() const;
+        virtual int pageX() const OVERRIDE FINAL;
+        virtual int pageY() const OVERRIDE FINAL;
         int x() const;
         int y() const;
 
@@ -67,7 +66,7 @@
 
         void initCoordinates();
         void initCoordinates(const LayoutPoint& clientLocation);
-        virtual void receivedTarget();
+        virtual void receivedTarget() OVERRIDE FINAL;
 
         void computePageLocation();
         void computeRelativePosition();
diff --git a/Source/core/events/MutationEvent.h b/Source/core/events/MutationEvent.h
index f0ef13e..e2e9f56 100644
--- a/Source/core/events/MutationEvent.h
+++ b/Source/core/events/MutationEvent.h
@@ -29,7 +29,7 @@
 
 namespace WebCore {
 
-    class MutationEvent : public Event {
+    class MutationEvent FINAL : public Event {
     public:
         virtual ~MutationEvent();
 
@@ -60,7 +60,7 @@
         String attrName() const { return m_attrName; }
         unsigned short attrChange() const { return m_attrChange; }
 
-        virtual const AtomicString& interfaceName() const;
+        virtual const AtomicString& interfaceName() const OVERRIDE;
 
     private:
         MutationEvent();
diff --git a/Source/core/events/NavigatorEvents.cpp b/Source/core/events/NavigatorEvents.cpp
index a9f9a26..a4285c2 100644
--- a/Source/core/events/NavigatorEvents.cpp
+++ b/Source/core/events/NavigatorEvents.cpp
@@ -33,24 +33,18 @@
 
 #include "core/frame/Frame.h"
 #include "core/frame/Navigator.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 
 namespace WebCore {
 
 long NavigatorEvents::maxTouchPoints(Navigator* navigator)
 {
     Frame* frame = navigator->frame();
-
     if (!frame)
         return 0;
-
-    Page* page = frame->page();
-
-    if (!page)
-        return 0;
-
-    return page->settings().maxTouchPoints();
+    if (Settings* settings = frame->settings())
+        return settings->maxTouchPoints();
+    return 0;
 }
 
 } // namespace WebCore
diff --git a/Source/core/events/NavigatorEvents.idl b/Source/core/events/NavigatorEvents.idl
index fe899fc..2b83961 100644
--- a/Source/core/events/NavigatorEvents.idl
+++ b/Source/core/events/NavigatorEvents.idl
@@ -29,6 +29,5 @@
  */
 
 partial interface Navigator {
-    [RuntimeEnabled=PointerEventsMaxTouchPoints]
-    readonly    attribute long    maxTouchPoints;
-};
\ No newline at end of file
+    [RuntimeEnabled=PointerEventsMaxTouchPoints] readonly attribute long maxTouchPoints;
+};
diff --git a/Source/core/events/NodeEventContext.cpp b/Source/core/events/NodeEventContext.cpp
new file mode 100644
index 0000000..e422cce
--- /dev/null
+++ b/Source/core/events/NodeEventContext.cpp
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2014 Google Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
+ *
+ */
+
+#include "config.h"
+#include "core/events/NodeEventContext.h"
+
+#include "core/dom/TouchList.h"
+#include "core/events/Event.h"
+#include "core/events/FocusEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/TouchEventContext.h"
+
+namespace WebCore {
+
+NodeEventContext::NodeEventContext(PassRefPtr<Node> node, PassRefPtr<EventTarget> currentTarget)
+    : m_node(node)
+    , m_currentTarget(currentTarget)
+{
+    ASSERT(m_node);
+}
+
+NodeEventContext::~NodeEventContext()
+{
+}
+
+void NodeEventContext::handleLocalEvents(Event* event) const
+{
+    if (touchEventContext()) {
+        touchEventContext()->handleLocalEvents(event);
+    } else if (relatedTarget()) {
+        if (event->isMouseEvent()) {
+            toMouseEvent(event)->setRelatedTarget(relatedTarget());
+        } else if (event->isFocusEvent()) {
+            toFocusEvent(event)->setRelatedTarget(relatedTarget());
+        }
+    }
+    event->setTarget(target());
+    event->setCurrentTarget(m_currentTarget.get());
+    m_node->handleLocalEvents(event);
+}
+
+}
diff --git a/Source/core/events/NodeEventContext.h b/Source/core/events/NodeEventContext.h
new file mode 100644
index 0000000..4a8cf0c
--- /dev/null
+++ b/Source/core/events/NodeEventContext.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2014 Google Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
+ *
+ */
+
+#ifndef NodeEventContext_h
+#define NodeEventContext_h
+
+#include "core/events/TreeScopeEventContext.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class EventTarget;
+class Node;
+class NodeList;
+class TouchEventContext;
+
+class NodeEventContext {
+public:
+    // FIXME: Use ContainerNode instead of Node.
+    NodeEventContext(PassRefPtr<Node>, PassRefPtr<EventTarget> currentTarget);
+    ~NodeEventContext();
+
+    Node* node() const { return m_node.get(); }
+
+    void setTreeScopeEventContext(PassRefPtr<TreeScopeEventContext> prpTreeScopeEventContext) { m_treeScopeEventContext = prpTreeScopeEventContext; }
+
+    EventTarget* target() const { return m_treeScopeEventContext->target(); }
+    EventTarget* relatedTarget() const { return m_treeScopeEventContext->relatedTarget(); }
+    TouchEventContext* touchEventContext() const { return m_treeScopeEventContext->touchEventContext(); }
+    PassRefPtr<NodeList> eventPath() const { return m_treeScopeEventContext->eventPath(); }
+
+    bool currentTargetSameAsTarget() const { return m_currentTarget.get() == target(); }
+    void handleLocalEvents(Event*) const;
+
+private:
+    RefPtr<Node> m_node;
+    RefPtr<EventTarget> m_currentTarget;
+    RefPtr<TreeScopeEventContext> m_treeScopeEventContext;
+};
+
+}
+
+#endif // NodeEventContext_h
diff --git a/Source/core/events/OverflowEvent.cpp b/Source/core/events/OverflowEvent.cpp
index c958ce6..376404d 100644
--- a/Source/core/events/OverflowEvent.cpp
+++ b/Source/core/events/OverflowEvent.cpp
@@ -76,14 +76,4 @@
     return EventNames::OverflowEvent;
 }
 
-void OverflowEvent::initOverflowEvent(unsigned short orient, bool horizontalOverflow, bool verticalOverflow)
-{
-    if (dispatched())
-        return;
-
-    m_orient = orient;
-    m_horizontalOverflow = horizontalOverflow;
-    m_verticalOverflow = verticalOverflow;
-}
-
 }
diff --git a/Source/core/events/OverflowEvent.h b/Source/core/events/OverflowEvent.h
index 96c220b..1f8e1a1 100644
--- a/Source/core/events/OverflowEvent.h
+++ b/Source/core/events/OverflowEvent.h
@@ -38,7 +38,7 @@
     bool verticalOverflow;
 };
 
-class OverflowEvent : public Event {
+class OverflowEvent FINAL : public Event {
 public:
     enum orientType {
         HORIZONTAL = 0,
@@ -59,13 +59,11 @@
         return adoptRef(new OverflowEvent(type, initializer));
     }
 
-    void initOverflowEvent(unsigned short orient, bool horizontalOverflow, bool verticalOverflow);
-
     unsigned short orient() const { return m_orient; }
     bool horizontalOverflow() const { return m_horizontalOverflow; }
     bool verticalOverflow() const { return m_verticalOverflow; }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     OverflowEvent();
diff --git a/Source/core/events/PageTransitionEvent.h b/Source/core/events/PageTransitionEvent.h
index 1002f55..cc79580 100644
--- a/Source/core/events/PageTransitionEvent.h
+++ b/Source/core/events/PageTransitionEvent.h
@@ -36,7 +36,7 @@
     bool persisted;
 };
 
-class PageTransitionEvent : public Event {
+class PageTransitionEvent FINAL : public Event {
 public:
     static PassRefPtr<PageTransitionEvent> create()
     {
@@ -53,7 +53,7 @@
 
     virtual ~PageTransitionEvent();
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
     bool persisted() const { return m_persisted; }
 
diff --git a/Source/core/events/PopStateEvent.h b/Source/core/events/PopStateEvent.h
index 5f874ea..889e5aaf 100644
--- a/Source/core/events/PopStateEvent.h
+++ b/Source/core/events/PopStateEvent.h
@@ -36,7 +36,7 @@
 
 typedef EventInit PopStateEventInit;
 
-class PopStateEvent : public Event {
+class PopStateEvent FINAL : public Event {
 public:
     virtual ~PopStateEvent();
     static PassRefPtr<PopStateEvent> create();
@@ -51,7 +51,7 @@
     }
     History* history() const { return m_history.get(); }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     PopStateEvent();
diff --git a/Source/core/events/ProgressEvent.h b/Source/core/events/ProgressEvent.h
index eb5edb7..76bc750 100644
--- a/Source/core/events/ProgressEvent.h
+++ b/Source/core/events/ProgressEvent.h
@@ -57,7 +57,7 @@
     unsigned long long loaded() const { return m_loaded; }
     unsigned long long total() const { return m_total; }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 protected:
     ProgressEvent();
diff --git a/Source/core/events/ResourceProgressEvent.h b/Source/core/events/ResourceProgressEvent.h
index 9c88b19..bb8ae58 100644
--- a/Source/core/events/ResourceProgressEvent.h
+++ b/Source/core/events/ResourceProgressEvent.h
@@ -42,7 +42,7 @@
 // (and translate in the case of PNaCl) multiple binary files. It is not
 // constructable by web content at all, and so does not provide the usual
 // EventInit pattern for Event construction.
-class ResourceProgressEvent : public ProgressEvent {
+class ResourceProgressEvent FINAL : public ProgressEvent {
 public:
     static PassRefPtr<ResourceProgressEvent> create()
     {
@@ -55,7 +55,7 @@
 
     const String& url() const;
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 protected:
     ResourceProgressEvent();
diff --git a/Source/core/events/SecurityPolicyViolationEvent.h b/Source/core/events/SecurityPolicyViolationEvent.h
index cc88d03..5c52cab 100644
--- a/Source/core/events/SecurityPolicyViolationEvent.h
+++ b/Source/core/events/SecurityPolicyViolationEvent.h
@@ -47,7 +47,7 @@
     int statusCode;
 };
 
-class SecurityPolicyViolationEvent : public Event {
+class SecurityPolicyViolationEvent FINAL : public Event {
 public:
     static PassRefPtr<SecurityPolicyViolationEvent> create()
     {
@@ -70,7 +70,7 @@
     int columnNumber() const { return m_columnNumber; }
     int statusCode() const { return m_statusCode; }
 
-    virtual const AtomicString& interfaceName() const { return EventNames::SecurityPolicyViolationEvent; }
+    virtual const AtomicString& interfaceName() const OVERRIDE { return EventNames::SecurityPolicyViolationEvent; }
 
 private:
     SecurityPolicyViolationEvent()
diff --git a/Source/core/events/TextEvent.h b/Source/core/events/TextEvent.h
index 6c2f256..782ed0d 100644
--- a/Source/core/events/TextEvent.h
+++ b/Source/core/events/TextEvent.h
@@ -35,7 +35,7 @@
 
     class DocumentFragment;
 
-    class TextEvent : public UIEvent {
+    class TextEvent FINAL : public UIEvent {
     public:
 
         static PassRefPtr<TextEvent> create();
@@ -50,11 +50,10 @@
 
         String data() const { return m_data; }
 
-        virtual const AtomicString& interfaceName() const;
+        virtual const AtomicString& interfaceName() const OVERRIDE;
 
         bool isLineBreak() const { return m_inputType == TextEventInputLineBreak; }
         bool isComposition() const { return m_inputType == TextEventInputComposition; }
-        bool isBackTab() const { return m_inputType == TextEventInputBackTab; }
         bool isPaste() const { return m_inputType == TextEventInputPaste; }
         bool isDrop() const { return m_inputType == TextEventInputDrop; }
 
diff --git a/Source/core/events/TouchEvent.cpp b/Source/core/events/TouchEvent.cpp
index f0527ed..68d8095 100644
--- a/Source/core/events/TouchEvent.cpp
+++ b/Source/core/events/TouchEvent.cpp
@@ -29,7 +29,6 @@
 #include "core/events/TouchEvent.h"
 
 #include "core/events/EventDispatcher.h"
-#include "core/events/EventRetargeter.h"
 #include "core/events/ThreadLocalEventNames.h"
 
 namespace WebCore {
@@ -106,7 +105,7 @@
 
 bool TouchEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
 {
-    EventRetargeter::adjustForTouchEvent(dispatcher->node(), *event());
+    event()->eventPath().adjustForTouchEvent(dispatcher->node(), *event());
     return dispatcher->dispatch();
 }
 
diff --git a/Source/core/events/TouchEvent.h b/Source/core/events/TouchEvent.h
index 25c6f61..0961817 100644
--- a/Source/core/events/TouchEvent.h
+++ b/Source/core/events/TouchEvent.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class TouchEvent : public MouseRelatedEvent {
+class TouchEvent FINAL : public MouseRelatedEvent {
 public:
     virtual ~TouchEvent();
 
@@ -68,7 +68,7 @@
 
     virtual bool isTouchEvent() const OVERRIDE;
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     TouchEvent();
@@ -83,7 +83,7 @@
     RefPtr<TouchList> m_changedTouches;
 };
 
-class TouchEventDispatchMediator : public EventDispatchMediator {
+class TouchEventDispatchMediator FINAL : public EventDispatchMediator {
 public:
     static PassRefPtr<TouchEventDispatchMediator> create(PassRefPtr<TouchEvent>);
 
diff --git a/Source/core/editing/SetSelectionCommand.cpp b/Source/core/events/TouchEventContext.cpp
similarity index 62%
rename from Source/core/editing/SetSelectionCommand.cpp
rename to Source/core/events/TouchEventContext.cpp
index dff5416..5bdd411 100644
--- a/Source/core/editing/SetSelectionCommand.cpp
+++ b/Source/core/events/TouchEventContext.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -21,34 +21,41 @@
  * 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.
+ *
  */
 
 #include "config.h"
-#include "core/editing/SetSelectionCommand.h"
+#include "core/events/TouchEventContext.h"
 
-#include "core/dom/Document.h"
-#include "core/frame/Frame.h"
+#include "core/dom/TouchList.h"
+#include "core/events/Event.h"
+#include "core/events/TouchEvent.h"
 
 namespace WebCore {
 
-SetSelectionCommand::SetSelectionCommand(const VisibleSelection& selection, FrameSelection::SetSelectionOptions options)
-    : SimpleEditCommand(*selection.base().document())
-    , m_options(options)
-    , m_selectionToSet(selection)
+PassRefPtr<TouchEventContext> TouchEventContext::create()
+{
+    return adoptRef(new TouchEventContext);
+}
+
+TouchEventContext::TouchEventContext()
+    : m_touches(TouchList::create())
+    , m_targetTouches(TouchList::create())
+    , m_changedTouches(TouchList::create())
 {
 }
 
-void SetSelectionCommand::doApply()
+TouchEventContext::~TouchEventContext()
 {
-    FrameSelection& selection = document().frame()->selection();
-    selection.setSelection(m_selectionToSet, m_options);
-    setEndingSelection(m_selectionToSet);
 }
 
-void SetSelectionCommand::doUnapply()
+void TouchEventContext::handleLocalEvents(Event* event) const
 {
-    FrameSelection& selection = document().frame()->selection();
-    selection.setSelection(startingSelection(), m_options);
+    ASSERT(event->isTouchEvent());
+    TouchEvent* touchEvent = toTouchEvent(event);
+    touchEvent->setTouches(m_touches);
+    touchEvent->setTargetTouches(m_targetTouches);
+    touchEvent->setChangedTouches(m_changedTouches);
 }
 
-} // namespace WebCore
+}
diff --git a/Source/core/editing/SetSelectionCommand.h b/Source/core/events/TouchEventContext.h
similarity index 63%
rename from Source/core/editing/SetSelectionCommand.h
rename to Source/core/events/TouchEventContext.h
index b4f09af..b6c0f1a 100644
--- a/Source/core/editing/SetSelectionCommand.h
+++ b/Source/core/events/TouchEventContext.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -21,33 +21,38 @@
  * 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.
+ *
  */
 
-#ifndef SetSelectionCommand_h
-#define SetSelectionCommand_h
+#ifndef TouchEventContext_h
+#define TouchEventContext_h
 
-#include "core/editing/EditCommand.h"
-#include "core/editing/FrameSelection.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
-class SetSelectionCommand : public SimpleEditCommand {
+class Event;
+class TouchList;
+
+class TouchEventContext : public RefCounted<TouchEventContext> {
 public:
-    static PassRefPtr<SetSelectionCommand> create(const VisibleSelection& selection, FrameSelection::SetSelectionOptions options)
-    {
-        return adoptRef(new SetSelectionCommand(selection, options));
-    }
+    static PassRefPtr<TouchEventContext> create();
+    ~TouchEventContext();
+    void handleLocalEvents(Event*) const;
+    TouchList& touches() { return *m_touches; }
+    TouchList& targetTouches() { return *m_targetTouches; }
+    TouchList& changedTouches() { return *m_changedTouches; }
 
 private:
-    SetSelectionCommand(const VisibleSelection&, FrameSelection::SetSelectionOptions);
+    TouchEventContext();
 
-    virtual void doApply() OVERRIDE;
-    virtual void doUnapply() OVERRIDE;
-
-    FrameSelection::SetSelectionOptions m_options;
-    VisibleSelection m_selectionToSet;
+    RefPtr<TouchList> m_touches;
+    RefPtr<TouchList> m_targetTouches;
+    RefPtr<TouchList> m_changedTouches;
 };
 
-} // namespace WebCore
+}
 
-#endif // SetSelectionCommand_h
+#endif // TouchEventContext_h
diff --git a/Source/core/events/TransitionEvent.h b/Source/core/events/TransitionEvent.h
index e1d5fa2..91bab0e 100644
--- a/Source/core/events/TransitionEvent.h
+++ b/Source/core/events/TransitionEvent.h
@@ -39,7 +39,7 @@
     String pseudoElement;
 };
 
-class TransitionEvent : public Event {
+class TransitionEvent FINAL : public Event {
 public:
     static PassRefPtr<TransitionEvent> create()
     {
@@ -60,7 +60,7 @@
     double elapsedTime() const;
     const String& pseudoElement() const;
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     TransitionEvent();
diff --git a/Source/core/editing/SetSelectionCommand.cpp b/Source/core/events/TreeScopeEventContext.cpp
similarity index 62%
copy from Source/core/editing/SetSelectionCommand.cpp
copy to Source/core/events/TreeScopeEventContext.cpp
index dff5416..98df539 100644
--- a/Source/core/editing/SetSelectionCommand.cpp
+++ b/Source/core/events/TreeScopeEventContext.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -21,34 +21,41 @@
  * 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.
+ *
  */
 
 #include "config.h"
-#include "core/editing/SetSelectionCommand.h"
+#include "core/events/TreeScopeEventContext.h"
 
-#include "core/dom/Document.h"
-#include "core/frame/Frame.h"
+#include "core/dom/StaticNodeList.h"
+#include "core/events/TouchEventContext.h"
 
 namespace WebCore {
 
-SetSelectionCommand::SetSelectionCommand(const VisibleSelection& selection, FrameSelection::SetSelectionOptions options)
-    : SimpleEditCommand(*selection.base().document())
-    , m_options(options)
-    , m_selectionToSet(selection)
+void TreeScopeEventContext::adoptEventPath(Vector<RefPtr<Node> >& nodes)
+{
+    m_eventPath = StaticNodeList::adopt(nodes);
+}
+
+TouchEventContext* TreeScopeEventContext::ensureTouchEventContext()
+{
+    if (!m_touchEventContext)
+        m_touchEventContext = TouchEventContext::create();
+    return m_touchEventContext.get();
+}
+
+PassRefPtr<TreeScopeEventContext> TreeScopeEventContext::create(TreeScope& treeScope)
+{
+    return adoptRef(new TreeScopeEventContext(treeScope));
+}
+
+TreeScopeEventContext::TreeScopeEventContext(TreeScope& treeScope)
+    : m_treeScope(treeScope)
 {
 }
 
-void SetSelectionCommand::doApply()
+TreeScopeEventContext::~TreeScopeEventContext()
 {
-    FrameSelection& selection = document().frame()->selection();
-    selection.setSelection(m_selectionToSet, m_options);
-    setEndingSelection(m_selectionToSet);
 }
 
-void SetSelectionCommand::doUnapply()
-{
-    FrameSelection& selection = document().frame()->selection();
-    selection.setSelection(startingSelection(), m_options);
 }
-
-} // namespace WebCore
diff --git a/Source/core/events/TreeScopeEventContext.h b/Source/core/events/TreeScopeEventContext.h
new file mode 100644
index 0000000..c697566
--- /dev/null
+++ b/Source/core/events/TreeScopeEventContext.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2014 Google Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
+ *
+ */
+
+#ifndef TreeScopeEventContext_h
+#define TreeScopeEventContext_h
+
+#include "core/dom/Node.h"
+#include "core/dom/NodeList.h"
+#include "core/dom/TreeScope.h"
+#include "core/events/EventTarget.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class EventTarget;
+class Node;
+class TouchEventContext;
+class TreeScope;
+
+class TreeScopeEventContext : public RefCounted<TreeScopeEventContext> {
+public:
+    static PassRefPtr<TreeScopeEventContext> create(TreeScope&);
+    ~TreeScopeEventContext();
+
+    TreeScope& treeScope() const { return m_treeScope; }
+
+    EventTarget* target() const { return m_target.get(); }
+    void setTarget(PassRefPtr<EventTarget>);
+
+    EventTarget* relatedTarget() const { return m_relatedTarget.get(); }
+    void setRelatedTarget(PassRefPtr<EventTarget>);
+
+    TouchEventContext* touchEventContext() const { return m_touchEventContext.get(); }
+    TouchEventContext* ensureTouchEventContext();
+
+    PassRefPtr<NodeList> eventPath() const { return m_eventPath; }
+    void adoptEventPath(Vector<RefPtr<Node> >&);
+
+private:
+    TreeScopeEventContext(TreeScope&);
+
+#ifndef NDEBUG
+    bool isUnreachableNode(EventTarget&);
+#endif
+
+    TreeScope& m_treeScope;
+    RefPtr<EventTarget> m_target;
+    RefPtr<EventTarget> m_relatedTarget;
+    RefPtr<NodeList> m_eventPath;
+    RefPtr<TouchEventContext> m_touchEventContext;
+};
+
+#ifndef NDEBUG
+inline bool TreeScopeEventContext::isUnreachableNode(EventTarget& target)
+{
+    // FIXME: Checks also for SVG elements.
+    return target.toNode() && !target.toNode()->isSVGElement() && !target.toNode()->treeScope().isInclusiveOlderSiblingShadowRootOrAncestorTreeScopeOf(m_treeScope);
+}
+#endif
+
+inline void TreeScopeEventContext::setTarget(PassRefPtr<EventTarget> target)
+{
+    ASSERT(target);
+    ASSERT(!isUnreachableNode(*target));
+    m_target = target;
+}
+
+inline void TreeScopeEventContext::setRelatedTarget(PassRefPtr<EventTarget> relatedTarget)
+{
+    ASSERT(relatedTarget);
+    ASSERT(!isUnreachableNode(*relatedTarget));
+    m_relatedTarget = relatedTarget;
+}
+
+}
+
+#endif // TreeScopeEventContext_h
diff --git a/Source/core/events/UIEvent.h b/Source/core/events/UIEvent.h
index 2750331..b0d3844 100644
--- a/Source/core/events/UIEvent.h
+++ b/Source/core/events/UIEvent.h
@@ -61,8 +61,8 @@
     AbstractView* view(bool& isNull) const { isNull = !m_view; return m_view.get(); }
     int detail() const { return m_detail; }
 
-    virtual const AtomicString& interfaceName() const;
-    virtual bool isUIEvent() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
+    virtual bool isUIEvent() const OVERRIDE FINAL;
 
     virtual int keyCode() const;
     virtual int charCode() const;
diff --git a/Source/core/events/WebKitAnimationEvent.h b/Source/core/events/WebKitAnimationEvent.h
index b91c980..731f45d 100644
--- a/Source/core/events/WebKitAnimationEvent.h
+++ b/Source/core/events/WebKitAnimationEvent.h
@@ -40,7 +40,7 @@
     double elapsedTime;
 };
 
-class WebKitAnimationEvent : public Event {
+class WebKitAnimationEvent FINAL : public Event {
 public:
     static PassRefPtr<WebKitAnimationEvent> create()
     {
@@ -60,7 +60,7 @@
     const String& animationName() const;
     double elapsedTime() const;
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     WebKitAnimationEvent();
diff --git a/Source/core/events/WheelEvent.cpp b/Source/core/events/WheelEvent.cpp
index 0c23299..37bf05b 100644
--- a/Source/core/events/WheelEvent.cpp
+++ b/Source/core/events/WheelEvent.cpp
@@ -24,7 +24,7 @@
 #include "config.h"
 #include "core/events/WheelEvent.h"
 
-#include "core/dom/Clipboard.h"
+#include "core/clipboard/Clipboard.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "platform/PlatformWheelEvent.h"
 
diff --git a/Source/core/events/WheelEvent.h b/Source/core/events/WheelEvent.h
index 6c8ea02..b527130 100644
--- a/Source/core/events/WheelEvent.h
+++ b/Source/core/events/WheelEvent.h
@@ -44,7 +44,7 @@
     unsigned deltaMode;
 };
 
-class WheelEvent : public MouseEvent {
+class WheelEvent FINAL : public MouseEvent {
 public:
     enum { TickMultiplier = 120 };
 
@@ -93,7 +93,7 @@
 
     bool webkitDirectionInvertedFromDevice() const { return m_directionInvertedFromDevice; }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual bool isMouseEvent() const OVERRIDE;
     virtual bool isWheelEvent() const OVERRIDE;
 
@@ -114,7 +114,7 @@
 
 DEFINE_EVENT_TYPE_CASTS(WheelEvent);
 
-class WheelEventDispatchMediator : public EventDispatchMediator {
+class WheelEventDispatchMediator FINAL : public EventDispatchMediator {
 public:
     static PassRefPtr<WheelEventDispatchMediator> create(const PlatformWheelEvent&, PassRefPtr<AbstractView>);
 private:
diff --git a/Source/core/events/WindowEventContext.cpp b/Source/core/events/WindowEventContext.cpp
index 673ef36..b788f04 100644
--- a/Source/core/events/WindowEventContext.cpp
+++ b/Source/core/events/WindowEventContext.cpp
@@ -28,26 +28,26 @@
 #include "core/events/WindowEventContext.h"
 
 #include "core/dom/Document.h"
-#include "core/events/Event.h"
-#include "core/events/EventContext.h"
 #include "core/dom/Node.h"
+#include "core/events/Event.h"
+#include "core/events/NodeEventContext.h"
 #include "core/frame/DOMWindow.h"
 
 namespace WebCore {
 
-WindowEventContext::WindowEventContext(Event* event, PassRefPtr<Node> node, const EventContext* topEventContext)
+WindowEventContext::WindowEventContext(Event* event, PassRefPtr<Node> node, const NodeEventContext* topNodeEventContext)
 {
     // We don't dispatch load events to the window. This quirk was originally
     // added because Mozilla doesn't propagate load events to the window object.
     if (event->type() == EventTypeNames::load)
         return;
 
-    Node* topLevelContainer = topEventContext ? topEventContext->node() : node.get();
+    Node* topLevelContainer = topNodeEventContext ? topNodeEventContext->node() : node.get();
     if (!topLevelContainer->isDocumentNode())
         return;
 
     m_window = toDocument(topLevelContainer)->domWindow();
-    m_target = topEventContext ? topEventContext->target() : node.get();
+    m_target = topNodeEventContext ? topNodeEventContext->target() : node.get();
 }
 
 bool WindowEventContext::handleLocalEvents(Event* event)
diff --git a/Source/core/events/WindowEventContext.h b/Source/core/events/WindowEventContext.h
index 25c5079..f7c2acd 100644
--- a/Source/core/events/WindowEventContext.h
+++ b/Source/core/events/WindowEventContext.h
@@ -33,13 +33,13 @@
 
 class DOMWindow;
 class EventTarget;
-class EventContext;
 class Event;
 class Node;
+class NodeEventContext;
 
 class WindowEventContext {
 public:
-    WindowEventContext(Event*, PassRefPtr<Node>, const EventContext*);
+    WindowEventContext(Event*, PassRefPtr<Node>, const NodeEventContext*);
 
     DOMWindow* window() const;
     EventTarget* target() const;
diff --git a/Source/core/fetch/CSSStyleSheetResource.cpp b/Source/core/fetch/CSSStyleSheetResource.cpp
index dd6fad0..0d431c8 100644
--- a/Source/core/fetch/CSSStyleSheetResource.cpp
+++ b/Source/core/fetch/CSSStyleSheetResource.cpp
@@ -30,7 +30,7 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/fetch/ResourceClientWalker.h"
 #include "core/fetch/StyleSheetResourceClient.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "platform/SharedBuffer.h"
 #include "platform/network/HTTPParsers.h"
 #include "wtf/CurrentTime.h"
@@ -39,7 +39,7 @@
 namespace WebCore {
 
 CSSStyleSheetResource::CSSStyleSheetResource(const ResourceRequest& resourceRequest, const String& charset)
-    : Resource(resourceRequest, CSSStyleSheet)
+    : StyleSheetResource(resourceRequest, CSSStyleSheet)
     , m_decoder(TextResourceDecoder::create("text/css", charset))
 {
     DEFINE_STATIC_LOCAL(const AtomicString, acceptCSS, ("text/css,*/*;q=0.1", AtomicString::ConstructFromLiteral));
@@ -89,7 +89,7 @@
 
     // Don't cache the decoded text, regenerating is cheap and it can use quite a bit of memory
     String sheetText = m_decoder->decode(m_data->data(), m_data->size());
-    sheetText.append(m_decoder->flush());
+    sheetText = sheetText + m_decoder->flush();
     return sheetText;
 }
 
@@ -98,7 +98,7 @@
     // Decode the data to find out the encoding and keep the sheet text around during checkNotify()
     if (m_data) {
         m_decodedSheetText = m_decoder->decode(m_data->data(), m_data->size());
-        m_decodedSheetText.append(m_decoder->flush());
+        m_decodedSheetText = m_decodedSheetText + m_decoder->flush();
     }
 
     ResourceClientWalker<StyleSheetResourceClient> w(m_clients);
@@ -108,6 +108,22 @@
     m_decodedSheetText = String();
 }
 
+bool CSSStyleSheetResource::isSafeToUnlock() const
+{
+    return m_parsedStyleSheetCache;
+}
+
+void CSSStyleSheetResource::destroyDecodedDataIfPossible()
+{
+    if (!isSafeToUnlock())
+        return;
+
+    m_parsedStyleSheetCache->removedFromMemoryCache();
+    m_parsedStyleSheetCache.clear();
+
+    setDecodedSize(0);
+}
+
 bool CSSStyleSheetResource::canUseSheet(bool enforceMIMEType, bool* hasValidMIMEType) const
 {
     if (errorOccurred())
@@ -132,20 +148,6 @@
     return typeOK;
 }
 
-void CSSStyleSheetResource::destroyDecodedData()
-{
-    if (!m_parsedStyleSheetCache)
-        return;
-
-    m_parsedStyleSheetCache->removedFromMemoryCache();
-    m_parsedStyleSheetCache.clear();
-
-    setDecodedSize(0);
-
-    if (isSafeToMakePurgeable())
-        makePurgeable(true);
-}
-
 PassRefPtr<StyleSheetContents> CSSStyleSheetResource::restoreParsedStyleSheet(const CSSParserContext& context)
 {
     if (!m_parsedStyleSheetCache)
diff --git a/Source/core/fetch/CSSStyleSheetResource.h b/Source/core/fetch/CSSStyleSheetResource.h
index 986e991..f2fea75 100644
--- a/Source/core/fetch/CSSStyleSheetResource.h
+++ b/Source/core/fetch/CSSStyleSheetResource.h
@@ -27,6 +27,7 @@
 #define CSSStyleSheetResource_h
 
 #include "core/fetch/ResourcePtr.h"
+#include "core/fetch/StyleSheetResource.h"
 
 namespace WebCore {
 
@@ -35,26 +36,27 @@
 class StyleSheetContents;
 class TextResourceDecoder;
 
-class CSSStyleSheetResource : public Resource {
+class CSSStyleSheetResource FINAL : public StyleSheetResource {
 public:
     CSSStyleSheetResource(const ResourceRequest&, const String& charset);
     virtual ~CSSStyleSheetResource();
 
     const String sheetText(bool enforceMIMEType = true, bool* hasValidMIMEType = 0) const;
 
-    virtual void didAddClient(ResourceClient*);
-    virtual void setEncoding(const String&);
-    virtual String encoding() const;
-    virtual void destroyDecodedData() OVERRIDE;
+    virtual void didAddClient(ResourceClient*) OVERRIDE;
+    virtual void setEncoding(const String&) OVERRIDE;
+    virtual String encoding() const OVERRIDE;
 
     PassRefPtr<StyleSheetContents> restoreParsedStyleSheet(const CSSParserContext&);
     void saveParsedStyleSheet(PassRefPtr<StyleSheetContents>);
 
+protected:
+    virtual bool isSafeToUnlock() const OVERRIDE;
+    virtual void destroyDecodedDataIfPossible() OVERRIDE;
+
 private:
     bool canUseSheet(bool enforceMIMEType, bool* hasValidMIMEType) const;
-
-protected:
-    virtual void checkNotify();
+    virtual void checkNotify() OVERRIDE;
 
     OwnPtr<TextResourceDecoder> m_decoder;
     String m_decodedSheetText;
diff --git a/Source/core/fetch/CachePolicy.h b/Source/core/fetch/CachePolicy.h
index bffddfe..0bb84a6 100644
--- a/Source/core/fetch/CachePolicy.h
+++ b/Source/core/fetch/CachePolicy.h
@@ -29,7 +29,6 @@
 namespace WebCore {
 
 enum CachePolicy {
-    CachePolicyCache,
     CachePolicyVerify,
     CachePolicyRevalidate,
     CachePolicyReload,
diff --git a/Source/core/fetch/CachingCorrectnessTest.cpp b/Source/core/fetch/CachingCorrectnessTest.cpp
new file mode 100644
index 0000000..1056506
--- /dev/null
+++ b/Source/core/fetch/CachingCorrectnessTest.cpp
@@ -0,0 +1,377 @@
+/*
+ * Copyright (c) 2014, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/html/HTMLDocument.h"
+#include "core/loader/DocumentLoader.h"
+#include "platform/network/ResourceRequest.h"
+#include "public/platform/Platform.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/RefPtr.h"
+
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+// An URL for the original request.
+const char kResourceURL[] = "http://resource.com/";
+
+// The origin time of our first request.
+const char kOriginalRequestDateAsString[] = "Thu, 25 May 1977 18:30:00 GMT";
+const double kOriginalRequestDateAsDouble = 233433000.;
+
+const char kOneDayBeforeOriginalRequest[] = "Wed, 24 May 1977 18:30:00 GMT";
+const char kOneDayAfterOriginalRequest[] = "Fri, 26 May 1977 18:30:00 GMT";
+
+const unsigned char kAConstUnsignedCharZero = 0;
+
+class CachingCorrectnessTest : public ::testing::Test {
+protected:
+    void advanceClock(double seconds)
+    {
+        m_proxyPlatform.advanceClock(seconds);
+    }
+
+    ResourcePtr<Resource> resourceFromResourceResponse(ResourceResponse response)
+    {
+        if (response.url().isNull())
+            response.setURL(KURL(ParsedURLString, kResourceURL));
+        ResourcePtr<Resource> resource =
+            new Resource(ResourceRequest(response.url()), Resource::Raw);
+        resource->setResponse(response);
+        memoryCache()->add(resource.get());
+
+        return resource;
+    }
+
+    ResourcePtr<Resource> fetch()
+    {
+        FetchRequest fetchRequest(ResourceRequest(KURL(ParsedURLString, kResourceURL)), FetchInitiatorInfo());
+        return m_fetcher->fetchSynchronously(fetchRequest);
+    }
+
+private:
+    // A simple platform that mocks out the clock, for cache freshness testing.
+    class ProxyPlatform : public blink::Platform {
+    public:
+        ProxyPlatform() : m_elapsedSeconds(0.) { }
+
+        void advanceClock(double seconds)
+        {
+            m_elapsedSeconds += seconds;
+        }
+
+    private:
+        // From blink::Platform:
+        virtual double currentTime()
+        {
+            return kOriginalRequestDateAsDouble + m_elapsedSeconds;
+        }
+
+        // These blink::Platform methods must be overriden to make a usable object.
+        virtual void cryptographicallyRandomValues(unsigned char* buffer, size_t length) { ASSERT_NOT_REACHED(); }
+        virtual const unsigned char* getTraceCategoryEnabledFlag(const char* categoryName)
+        {
+            return &kAConstUnsignedCharZero;
+        }
+
+        double m_elapsedSeconds;
+    };
+
+    virtual void SetUp()
+    {
+        m_savedPlatform = blink::Platform::current();
+        blink::Platform::initialize(&m_proxyPlatform);
+
+        // Save the global memory cache to restore it upon teardown.
+        m_globalMemoryCache = adoptPtr(memoryCache());
+        // Create the test memory cache instance and hook it in.
+        m_testingMemoryCache = adoptPtr(new MemoryCache());
+        setMemoryCacheForTesting(m_testingMemoryCache.leakPtr());
+
+        // Create a ResourceFetcher that has a real DocumentLoader and Document, but is not attached to a Frame.
+        const KURL kDocumentURL(ParsedURLString, "http://document.com/");
+        m_documentLoader = DocumentLoader::create(0, ResourceRequest(kDocumentURL), SubstituteData());
+        m_document = HTMLDocument::create();
+        m_fetcher = ResourceFetcher::create(m_documentLoader.get());
+        m_fetcher->setDocument(m_document.get());
+    }
+
+    virtual void TearDown()
+    {
+        memoryCache()->evictResources();
+
+        // Regain the ownership of testing memory cache, so that it will be
+        // destroyed.
+        m_testingMemoryCache = adoptPtr(memoryCache());
+
+        // Yield the ownership of the global memory cache back.
+        setMemoryCacheForTesting(m_globalMemoryCache.leakPtr());
+
+        blink::Platform::initialize(m_savedPlatform);
+    }
+
+    blink::Platform* m_savedPlatform;
+    ProxyPlatform m_proxyPlatform;
+
+    OwnPtr<MemoryCache> m_testingMemoryCache;
+    OwnPtr<MemoryCache> m_globalMemoryCache;
+
+    RefPtr<DocumentLoader> m_documentLoader;
+
+    RefPtr<HTMLDocument> m_document;
+    RefPtr<ResourceFetcher> m_fetcher;
+};
+
+TEST_F(CachingCorrectnessTest, FreshFromLastModified)
+{
+    ResourceResponse fresh200Response;
+    fresh200Response.setHTTPStatusCode(200);
+    fresh200Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    fresh200Response.setHTTPHeaderField("Last-Modified", kOneDayBeforeOriginalRequest);
+
+    ResourcePtr<Resource> fresh200 = resourceFromResourceResponse(fresh200Response);
+
+    // Advance the clock within the implicit freshness period of this resource before we make a request.
+    advanceClock(600.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_EQ(fresh200, fetched);
+}
+
+TEST_F(CachingCorrectnessTest, FreshFromExpires)
+{
+    ResourceResponse fresh200Response;
+    fresh200Response.setHTTPStatusCode(200);
+    fresh200Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    fresh200Response.setHTTPHeaderField("Expires", kOneDayAfterOriginalRequest);
+
+    ResourcePtr<Resource> fresh200 = resourceFromResourceResponse(fresh200Response);
+
+    // Advance the clock within the freshness period of this resource before we make a request.
+    advanceClock(24. * 60. * 60. - 15.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_EQ(fresh200, fetched);
+}
+
+TEST_F(CachingCorrectnessTest, FreshFromMaxAge)
+{
+    ResourceResponse fresh200Response;
+    fresh200Response.setHTTPStatusCode(200);
+    fresh200Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    fresh200Response.setHTTPHeaderField("Cache-Control", "max-age=600");
+
+    ResourcePtr<Resource> fresh200 = resourceFromResourceResponse(fresh200Response);
+
+    // Advance the clock within the freshness period of this resource before we make a request.
+    advanceClock(500.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_EQ(fresh200, fetched);
+}
+
+// The strong validator causes a revalidation to be launched, and the proxy and original resources leak because of their reference loop.
+TEST_F(CachingCorrectnessTest, DISABLED_ExpiredFromLastModified)
+{
+    ResourceResponse expired200Response;
+    expired200Response.setHTTPStatusCode(200);
+    expired200Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    expired200Response.setHTTPHeaderField("Last-Modified", kOneDayBeforeOriginalRequest);
+
+    ResourcePtr<Resource> expired200 = resourceFromResourceResponse(expired200Response);
+
+    // Advance the clock beyond the implicit freshness period.
+    advanceClock(24. * 60. * 60. * 0.2);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_NE(expired200, fetched);
+}
+
+TEST_F(CachingCorrectnessTest, ExpiredFromExpires)
+{
+    ResourceResponse expired200Response;
+    expired200Response.setHTTPStatusCode(200);
+    expired200Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    expired200Response.setHTTPHeaderField("Expires", kOneDayAfterOriginalRequest);
+
+    ResourcePtr<Resource> expired200 = resourceFromResourceResponse(expired200Response);
+
+    // Advance the clock within the expiredness period of this resource before we make a request.
+    advanceClock(24. * 60. * 60. + 15.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_NE(expired200, fetched);
+}
+
+TEST_F(CachingCorrectnessTest, ExpiredFromMaxAge)
+{
+    ResourceResponse expired200Response;
+    expired200Response.setHTTPStatusCode(200);
+    expired200Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    expired200Response.setHTTPHeaderField("Cache-Control", "max-age=600");
+
+    ResourcePtr<Resource> expired200 = resourceFromResourceResponse(expired200Response);
+
+    // Advance the clock within the expiredness period of this resource before we make a request.
+    advanceClock(700.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_NE(expired200, fetched);
+}
+
+TEST_F(CachingCorrectnessTest, FreshButNoCache)
+{
+    ResourceResponse fresh200NocacheResponse;
+    fresh200NocacheResponse.setHTTPStatusCode(200);
+    fresh200NocacheResponse.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    fresh200NocacheResponse.setHTTPHeaderField("Expires", kOneDayAfterOriginalRequest);
+    fresh200NocacheResponse.setHTTPHeaderField("Cache-Control", "no-cache");
+
+    ResourcePtr<Resource> fresh200Nocache = resourceFromResourceResponse(fresh200NocacheResponse);
+
+    // Advance the clock within the freshness period of this resource before we make a request.
+    advanceClock(24. * 60. * 60. - 15.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_NE(fresh200Nocache, fetched);
+}
+
+TEST_F(CachingCorrectnessTest, FreshButNoStore)
+{
+    ResourceResponse fresh200NostoreResponse;
+    fresh200NostoreResponse.setHTTPStatusCode(200);
+    fresh200NostoreResponse.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    fresh200NostoreResponse.setHTTPHeaderField("Expires", kOneDayAfterOriginalRequest);
+    fresh200NostoreResponse.setHTTPHeaderField("Cache-Control", "no-store");
+
+    ResourcePtr<Resource> fresh200Nostore = resourceFromResourceResponse(fresh200NostoreResponse);
+
+    // Advance the clock within the freshness period of this resource before we make a request.
+    advanceClock(24. * 60. * 60. - 15.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_NE(fresh200Nostore, fetched);
+}
+
+// FIXME: Determine if ignoring must-revalidate for blink is correct behaviour.
+// See crbug.com/340088 .
+TEST_F(CachingCorrectnessTest, DISABLED_FreshButMustRevalidate)
+{
+    ResourceResponse fresh200MustRevalidateResponse;
+    fresh200MustRevalidateResponse.setHTTPStatusCode(200);
+    fresh200MustRevalidateResponse.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    fresh200MustRevalidateResponse.setHTTPHeaderField("Expires", kOneDayAfterOriginalRequest);
+    fresh200MustRevalidateResponse.setHTTPHeaderField("Cache-Control", "must-revalidate");
+
+    ResourcePtr<Resource> fresh200MustRevalidate = resourceFromResourceResponse(fresh200MustRevalidateResponse);
+
+    // Advance the clock within the freshness period of this resource before we make a request.
+    advanceClock(24. * 60. * 60. - 15.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_NE(fresh200MustRevalidate, fetched);
+}
+
+TEST_F(CachingCorrectnessTest, FreshWithFreshRedirect)
+{
+    KURL redirectUrl(ParsedURLString, kResourceURL);
+    const char redirectTargetUrlString[] = "http://redirect-target.com";
+    KURL redirectTargetUrl(ParsedURLString, redirectTargetUrlString);
+
+    ResourcePtr<Resource> firstResource = new Resource(ResourceRequest(redirectUrl), Resource::Raw);
+
+    ResourceResponse fresh301Response;
+    fresh301Response.setURL(redirectUrl);
+    fresh301Response.setHTTPStatusCode(301);
+    fresh301Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    fresh301Response.setHTTPHeaderField("Location", redirectTargetUrlString);
+    fresh301Response.setHTTPHeaderField("Cache-Control", "max-age=600");
+
+    // Add the redirect to our request.
+    ResourceRequest redirectRequest = ResourceRequest(redirectTargetUrl);
+    firstResource->willSendRequest(redirectRequest, fresh301Response);
+
+    // Add the final response to our request.
+    ResourceResponse fresh200Response;
+    fresh200Response.setURL(redirectTargetUrl);
+    fresh200Response.setHTTPStatusCode(200);
+    fresh200Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    fresh200Response.setHTTPHeaderField("Expires", kOneDayAfterOriginalRequest);
+
+    firstResource->setResponse(fresh200Response);
+    memoryCache()->add(firstResource.get());
+
+    advanceClock(500.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_EQ(firstResource, fetched);
+}
+
+TEST_F(CachingCorrectnessTest, FreshWithStaleRedirect)
+{
+    KURL redirectUrl(ParsedURLString, kResourceURL);
+    const char redirectTargetUrlString[] = "http://redirect-target.com";
+    KURL redirectTargetUrl(ParsedURLString, redirectTargetUrlString);
+
+    ResourcePtr<Resource> firstResource = new Resource(ResourceRequest(redirectUrl), Resource::Raw);
+
+    ResourceResponse stale302Response;
+    stale302Response.setURL(redirectUrl);
+    stale302Response.setHTTPStatusCode(301);
+    stale302Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    stale302Response.setHTTPHeaderField("Location", redirectTargetUrlString);
+
+    // Add the redirect to our request.
+    ResourceRequest redirectRequest = ResourceRequest(redirectTargetUrl);
+    firstResource->willSendRequest(redirectRequest, stale302Response);
+
+    // Add the final response to our request.
+    ResourceResponse fresh200Response;
+    fresh200Response.setURL(redirectTargetUrl);
+    fresh200Response.setHTTPStatusCode(200);
+    fresh200Response.setHTTPHeaderField("Date", kOriginalRequestDateAsString);
+    fresh200Response.setHTTPHeaderField("Expires", kOneDayAfterOriginalRequest);
+
+    firstResource->setResponse(fresh200Response);
+    memoryCache()->add(firstResource.get());
+
+    advanceClock(500.);
+
+    ResourcePtr<Resource> fetched = fetch();
+    EXPECT_NE(firstResource, fetched);
+}
+
+} // namespace
diff --git a/Source/core/fetch/CrossOriginAccessControl.cpp b/Source/core/fetch/CrossOriginAccessControl.cpp
index f35116c..98d2b1a 100644
--- a/Source/core/fetch/CrossOriginAccessControl.cpp
+++ b/Source/core/fetch/CrossOriginAccessControl.cpp
@@ -27,8 +27,12 @@
 #include "config.h"
 #include "core/fetch/CrossOriginAccessControl.h"
 
+#include "core/fetch/Resource.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "platform/network/HTTPParsers.h"
+#include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/SchemeRegistry.h"
 #include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/Threading.h"
 #include "wtf/text/AtomicString.h"
@@ -102,7 +106,7 @@
     request.setAllowCookies(allowCredentials == AllowStoredCredentials);
 
     if (securityOrigin)
-        request.setHTTPOrigin(securityOrigin->toString());
+        request.setHTTPOrigin(securityOrigin->toAtomicString());
 }
 
 ResourceRequest createAccessControlPreflightRequest(const ResourceRequest& request, SecurityOrigin* securityOrigin)
@@ -127,7 +131,7 @@
             headerBuffer.append(it->key);
         }
 
-        preflightRequest.setHTTPHeaderField("Access-Control-Request-Headers", headerBuffer.toString().lower());
+        preflightRequest.setHTTPHeaderField("Access-Control-Request-Headers", AtomicString(headerBuffer.toString().lower()));
     }
 
     return preflightRequest;
@@ -143,13 +147,18 @@
     AtomicallyInitializedStatic(AtomicString&, accessControlAllowOrigin = *new AtomicString("access-control-allow-origin", AtomicString::ConstructFromLiteral));
     AtomicallyInitializedStatic(AtomicString&, accessControlAllowCredentials = *new AtomicString("access-control-allow-credentials", AtomicString::ConstructFromLiteral));
 
+    if (!response.httpStatusCode()) {
+        errorDescription = "Received an invalid response. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
+        return false;
+    }
+
     // A wildcard Access-Control-Allow-Origin can not be used if credentials are to be sent,
     // even with Access-Control-Allow-Credentials set to true.
     const AtomicString& accessControlOriginString = response.httpHeaderField(accessControlAllowOrigin);
     if (accessControlOriginString == starAtom && includeCredentials == DoNotAllowStoredCredentials)
         return true;
 
-    if (accessControlOriginString != securityOrigin->toString()) {
+    if (accessControlOriginString != securityOrigin->toAtomicString()) {
         if (accessControlOriginString == starAtom) {
             errorDescription = "A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
         } else if (accessControlOriginString.isEmpty()) {
@@ -198,4 +207,67 @@
     }
 }
 
+bool CrossOriginAccessControl::isLegalRedirectLocation(const KURL& requestURL, String& errorDescription)
+{
+    // CORS restrictions imposed on Location: URL -- http://www.w3.org/TR/cors/#redirect-steps (steps 2 + 3.)
+    if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(requestURL.protocol())) {
+        errorDescription = "The request was redirected to a URL ('" + requestURL.string() + "') which has a disallowed scheme for cross-origin requests.";
+        return false;
+    }
+
+    if (!(requestURL.user().isEmpty() && requestURL.pass().isEmpty())) {
+        errorDescription = "The request was redirected to a URL ('" + requestURL.string() + "') containing userinfo, which is disallowed for cross-origin requests.";
+        return false;
+    }
+
+    return true;
+}
+
+bool CrossOriginAccessControl::handleRedirect(Resource* resource, SecurityOrigin* securityOrigin, ResourceRequest& request, const ResourceResponse& redirectResponse, ResourceLoaderOptions& options, String& errorMessage)
+{
+    // http://www.w3.org/TR/cors/#redirect-steps terminology:
+    const KURL& originalURL = redirectResponse.url();
+    const KURL& requestURL = request.url();
+
+    bool redirectCrossOrigin = !securityOrigin->canRequest(requestURL);
+
+    // Same-origin request URLs that redirect are allowed without checking access.
+    if (!securityOrigin->canRequest(originalURL)) {
+        // Follow http://www.w3.org/TR/cors/#redirect-steps
+        String errorDescription;
+
+        // Steps 3 & 4 - check if scheme and other URL restrictions hold.
+        bool allowRedirect = isLegalRedirectLocation(requestURL, errorDescription);
+        if (allowRedirect) {
+            // Step 5: perform resource sharing access check.
+            StoredCredentials withCredentials = resource->resourceRequest().allowCookies() ? AllowStoredCredentials : DoNotAllowStoredCredentials;
+            allowRedirect = passesAccessControlCheck(redirectResponse, withCredentials, securityOrigin, errorDescription);
+            if (allowRedirect) {
+                RefPtr<SecurityOrigin> originalOrigin = SecurityOrigin::create(originalURL);
+                // Step 6: if the request URL origin is not same origin as the original URL's,
+                // set the source origin to a globally unique identifier.
+                if (!originalOrigin->canRequest(requestURL)) {
+                    options.securityOrigin = SecurityOrigin::createUnique();
+                    securityOrigin = options.securityOrigin.get();
+                }
+            }
+        }
+        if (!allowRedirect) {
+            const String& originalOrigin = SecurityOrigin::create(originalURL)->toString();
+            errorMessage = "Redirect at origin '" + originalOrigin + "' has been blocked from loading by Cross-Origin Resource Sharing policy: " + errorDescription;
+            return false;
+        }
+    }
+    if (redirectCrossOrigin) {
+        // If now to a different origin, update/set Origin:.
+        request.clearHTTPOrigin();
+        request.setHTTPOrigin(securityOrigin->toAtomicString());
+        // If the user didn't request credentials in the first place, update our
+        // state so we neither request them nor expect they must be allowed.
+        if (options.credentialsRequested == ClientDidNotRequestCredentials)
+            options.allowCredentials = DoNotAllowStoredCredentials;
+    }
+    return true;
+}
+
 } // namespace WebCore
diff --git a/Source/core/fetch/CrossOriginAccessControl.h b/Source/core/fetch/CrossOriginAccessControl.h
index 450c342..a96536f 100644
--- a/Source/core/fetch/CrossOriginAccessControl.h
+++ b/Source/core/fetch/CrossOriginAccessControl.h
@@ -37,6 +37,9 @@
 typedef HashSet<String, CaseFoldingHash> HTTPHeaderSet;
 
 class HTTPHeaderMap;
+class Resource;
+struct ResourceLoaderOptions;
+class ResourceRequest;
 class ResourceResponse;
 class SecurityOrigin;
 
@@ -45,6 +48,12 @@
     SharableCrossOrigin
 };
 
+class CrossOriginAccessControl {
+public:
+    static bool isLegalRedirectLocation(const KURL&, String& errorDescription);
+    static bool handleRedirect(Resource*, SecurityOrigin*, ResourceRequest&, const ResourceResponse&, ResourceLoaderOptions&, String&);
+};
+
 bool isSimpleCrossOriginAccessRequest(const String& method, const HTTPHeaderMap&);
 bool isOnAccessControlSimpleRequestMethodWhitelist(const String&);
 bool isOnAccessControlSimpleRequestHeaderWhitelist(const AtomicString& name, const AtomicString& value);
diff --git a/Source/core/fetch/DocumentResource.h b/Source/core/fetch/DocumentResource.h
index f05d171..b12dbfb 100644
--- a/Source/core/fetch/DocumentResource.h
+++ b/Source/core/fetch/DocumentResource.h
@@ -26,21 +26,23 @@
 #include "core/fetch/Resource.h"
 #include "core/fetch/ResourceClient.h"
 #include "core/fetch/ResourcePtr.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 
 namespace WebCore {
 
 class Document;
 
-class DocumentResource : public Resource {
+class DocumentResource FINAL : public Resource {
 public:
+    typedef ResourceClient ClientType;
+
     DocumentResource(const ResourceRequest&, Type);
     virtual ~DocumentResource();
 
     Document* document() const { return m_document.get(); }
 
-    virtual void setEncoding(const String&);
-    virtual String encoding() const;
+    virtual void setEncoding(const String&) OVERRIDE;
+    virtual String encoding() const OVERRIDE;
     virtual void checkNotify() OVERRIDE;
 
 private:
@@ -57,7 +59,7 @@
 public:
     virtual ~DocumentResourceClient() { }
     static ResourceClientType expectedType() { return DocumentType; }
-    virtual ResourceClientType resourceClientType() const { return expectedType(); }
+    virtual ResourceClientType resourceClientType() const OVERRIDE { return expectedType(); }
 };
 
 }
diff --git a/Source/core/fetch/DocumentResourceReference.h b/Source/core/fetch/DocumentResourceReference.h
index 9e84335..60f7448 100644
--- a/Source/core/fetch/DocumentResourceReference.h
+++ b/Source/core/fetch/DocumentResourceReference.h
@@ -31,7 +31,7 @@
 
 namespace WebCore {
 
-class DocumentResourceReference : public DocumentResourceClient {
+class DocumentResourceReference FINAL : public DocumentResourceClient {
 public:
     DocumentResourceReference(DocumentResource* document) : m_document(document) { m_document->addClient(this); }
     virtual ~DocumentResourceReference() { m_document->removeClient(this); }
diff --git a/Source/core/fetch/FetchContext.cpp b/Source/core/fetch/FetchContext.cpp
index bfc362a..226c894 100644
--- a/Source/core/fetch/FetchContext.cpp
+++ b/Source/core/fetch/FetchContext.cpp
@@ -48,11 +48,11 @@
 {
 }
 
-void FetchContext::addAdditionalRequestHeaders(Document&, ResourceRequest&, Resource::Type)
+void FetchContext::addAdditionalRequestHeaders(Document*, ResourceRequest&, FetchResourceType)
 {
 }
 
-CachePolicy FetchContext::cachePolicy(Resource::Type) const
+CachePolicy FetchContext::cachePolicy(Document*) const
 {
     return CachePolicyVerify;
 }
@@ -77,7 +77,7 @@
 {
 }
 
-void FetchContext::dispatchDidFinishLoading(DocumentLoader*, unsigned long, double)
+void FetchContext::dispatchDidFinishLoading(DocumentLoader*, unsigned long, double, int64_t)
 {
 }
 
diff --git a/Source/core/fetch/FetchContext.h b/Source/core/fetch/FetchContext.h
index 80efbae..9e40ac1 100644
--- a/Source/core/fetch/FetchContext.h
+++ b/Source/core/fetch/FetchContext.h
@@ -49,6 +49,11 @@
 class ResourceResponse;
 class ResourceRequest;
 
+enum FetchResourceType {
+    FetchMainResource,
+    FetchSubresource
+};
+
 class FetchContext {
     WTF_MAKE_NONCOPYABLE(FetchContext);
 public:
@@ -58,8 +63,8 @@
     virtual ~FetchContext() { }
 
     virtual void reportLocalLoadFailed(const KURL&);
-    virtual void addAdditionalRequestHeaders(Document&, ResourceRequest&, Resource::Type);
-    virtual CachePolicy cachePolicy(Resource::Type) const;
+    virtual void addAdditionalRequestHeaders(Document*, ResourceRequest&, FetchResourceType);
+    virtual CachePolicy cachePolicy(Document*) const;
 
     virtual void dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority);
     virtual void dispatchWillSendRequest(DocumentLoader*, unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& = FetchInitiatorInfo());
@@ -67,7 +72,7 @@
     virtual void dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse&, ResourceLoader* = 0);
     virtual void dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength);
     virtual void dispatchDidDownloadData(DocumentLoader*, unsigned long identifier, int dataLength, int encodedDataLength);
-    virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier, double finishTime);
+    virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier, double finishTime, int64_t encodedDataLength);
     virtual void dispatchDidFail(DocumentLoader*, unsigned long identifier, const ResourceError&);
     virtual void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, int dataLength);
 };
diff --git a/Source/core/fetch/FetchInitiatorTypeNames.in b/Source/core/fetch/FetchInitiatorTypeNames.in
index f0cf1b8..d296fc2 100644
--- a/Source/core/fetch/FetchInitiatorTypeNames.in
+++ b/Source/core/fetch/FetchInitiatorTypeNames.in
@@ -5,7 +5,9 @@
 icon
 internal
 link
+ping
 processinginstruction
 texttrack
+violationreport
 xml
 xmlhttprequest
diff --git a/Source/core/fetch/FetchRequest.cpp b/Source/core/fetch/FetchRequest.cpp
index 956ae96..4ec40cc 100644
--- a/Source/core/fetch/FetchRequest.cpp
+++ b/Source/core/fetch/FetchRequest.cpp
@@ -72,6 +72,14 @@
 void FetchRequest::setCrossOriginAccessControl(SecurityOrigin* origin, StoredCredentials allowCredentials)
 {
     updateRequestForAccessControl(m_resourceRequest, origin, allowCredentials);
+    m_options.corsEnabled = IsCORSEnabled;
+}
+
+void FetchRequest::setCrossOriginAccessControl(SecurityOrigin* origin, const AtomicString& crossOriginMode)
+{
+    StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
+    updateRequestForAccessControl(m_resourceRequest, origin, allowCredentials);
+    m_options.corsEnabled = IsCORSEnabled;
 }
 
 } // namespace WebCore
diff --git a/Source/core/fetch/FetchRequest.h b/Source/core/fetch/FetchRequest.h
index 1954ced..e9aa687 100644
--- a/Source/core/fetch/FetchRequest.h
+++ b/Source/core/fetch/FetchRequest.h
@@ -60,6 +60,7 @@
     void setDefer(DeferOption defer) { m_defer = defer; }
     void setContentSecurityCheck(ContentSecurityPolicyCheck contentSecurityPolicyOption) { m_options.contentSecurityPolicyOption = contentSecurityPolicyOption; }
     void setCrossOriginAccessControl(SecurityOrigin*, StoredCredentials);
+    void setCrossOriginAccessControl(SecurityOrigin*, const AtomicString& crossOriginMode);
     OriginRestriction originRestriction() const { return m_originRestriction; }
     void setOriginRestriction(OriginRestriction restriction) { m_originRestriction = restriction; }
 
diff --git a/Source/core/fetch/FontResource.cpp b/Source/core/fetch/FontResource.cpp
index 0fdbcc1..a3c8824 100644
--- a/Source/core/fetch/FontResource.cpp
+++ b/Source/core/fetch/FontResource.cpp
@@ -28,7 +28,7 @@
 #include "core/fetch/FontResource.h"
 
 #include "core/fetch/ResourceClientWalker.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "platform/SharedBuffer.h"
 #include "platform/fonts/FontCustomPlatformData.h"
 #include "platform/fonts/FontPlatformData.h"
@@ -37,7 +37,7 @@
 
 #if ENABLE(SVG_FONTS)
 #include "SVGNames.h"
-#include "core/dom/NodeList.h"
+#include "core/html/HTMLCollection.h"
 #include "core/svg/SVGDocument.h"
 #include "core/svg/SVGFontElement.h"
 #endif
@@ -111,7 +111,7 @@
 
             OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
             String svgSource = decoder->decode(m_data->data(), m_data->size());
-            svgSource.append(decoder->flush());
+            svgSource = svgSource + decoder->flush();
 
             m_externalSVGDocument->setContent(svgSource);
 
@@ -127,26 +127,26 @@
 
 SVGFontElement* FontResource::getSVGFontById(const String& fontName) const
 {
-    RefPtr<NodeList> list = m_externalSVGDocument->getElementsByTagNameNS(SVGNames::fontTag.namespaceURI(), SVGNames::fontTag.localName());
-    if (!list)
+    RefPtr<HTMLCollection> collection = m_externalSVGDocument->getElementsByTagNameNS(SVGNames::fontTag.namespaceURI(), SVGNames::fontTag.localName());
+    if (!collection)
         return 0;
 
-    unsigned listLength = list->length();
-    if (!listLength)
+    unsigned collectionLength = collection->length();
+    if (!collectionLength)
         return 0;
 
 #ifndef NDEBUG
-    for (unsigned i = 0; i < listLength; ++i) {
-        ASSERT(list->item(i));
-        ASSERT(list->item(i)->hasTagName(SVGNames::fontTag));
+    for (unsigned i = 0; i < collectionLength; ++i) {
+        ASSERT(collection->item(i));
+        ASSERT(collection->item(i)->hasTagName(SVGNames::fontTag));
     }
 #endif
 
     if (fontName.isEmpty())
-        return toSVGFontElement(list->item(0));
+        return toSVGFontElement(collection->item(0));
 
-    for (unsigned i = 0; i < listLength; ++i) {
-        SVGFontElement* element = toSVGFontElement(list->item(i));
+    for (unsigned i = 0; i < collectionLength; ++i) {
+        SVGFontElement* element = toSVGFontElement(collection->item(i));
         if (element->getIdAttribute() == fontName)
             return element;
     }
diff --git a/Source/core/fetch/FontResource.h b/Source/core/fetch/FontResource.h
index 8d700ba..306d204 100644
--- a/Source/core/fetch/FontResource.h
+++ b/Source/core/fetch/FontResource.h
@@ -40,18 +40,20 @@
 class SVGFontElement;
 class FontCustomPlatformData;
 
-class FontResource : public Resource {
+class FontResource FINAL : public Resource {
 public:
+    typedef ResourceClient ClientType;
+
     FontResource(const ResourceRequest&);
     virtual ~FontResource();
 
-    virtual void load(ResourceFetcher*, const ResourceLoaderOptions&);
+    virtual void load(ResourceFetcher*, const ResourceLoaderOptions&) OVERRIDE;
 
-    virtual void didAddClient(ResourceClient*);
+    virtual void didAddClient(ResourceClient*) OVERRIDE;
 
-    virtual void allClientsRemoved();
+    virtual void allClientsRemoved() OVERRIDE;
     void beginLoadIfNeeded(ResourceFetcher* dl);
-    bool stillNeedsLoad() const { return !m_loadInitiated; }
+    virtual bool stillNeedsLoad() const OVERRIDE { return !m_loadInitiated; }
 
     bool ensureCustomFontData();
     FontPlatformData platformDataFromCustomData(float size, bool bold, bool italic, FontOrientation = Horizontal, FontWidthVariant = RegularWidth);
@@ -62,7 +64,7 @@
 #endif
 
 private:
-    virtual void checkNotify();
+    virtual void checkNotify() OVERRIDE;
     OwnPtr<FontCustomPlatformData> m_fontData;
     bool m_loadInitiated;
 
@@ -79,7 +81,7 @@
 public:
     virtual ~FontResourceClient() { }
     static ResourceClientType expectedType() { return FontType; }
-    virtual ResourceClientType resourceClientType() const { return expectedType(); }
+    virtual ResourceClientType resourceClientType() const OVERRIDE FINAL { return expectedType(); }
     virtual void fontLoaded(FontResource*) { }
     virtual void didStartFontLoad(FontResource*) { }
 };
diff --git a/Source/core/fetch/ImageResource.cpp b/Source/core/fetch/ImageResource.cpp
index 598e616..543f392 100644
--- a/Source/core/fetch/ImageResource.cpp
+++ b/Source/core/fetch/ImageResource.cpp
@@ -39,8 +39,6 @@
 #include "wtf/StdLibExtras.h"
 #include "wtf/Vector.h"
 
-using namespace std;
-
 namespace WebCore {
 
 ImageResource::ImageResource(const ResourceRequest& resourceRequest)
@@ -63,6 +61,15 @@
     setCustomAcceptHeader();
 }
 
+ImageResource::ImageResource(const ResourceRequest& resourceRequest, WebCore::Image* image)
+    : Resource(resourceRequest, Image)
+    , m_image(image)
+{
+    setStatus(Cached);
+    setLoading(false);
+    setCustomAcceptHeader();
+}
+
 ImageResource::~ImageResource()
 {
     clearImage();
@@ -122,6 +129,21 @@
     Resource::switchClientsToRevalidatedResource();
 }
 
+bool ImageResource::isSafeToUnlock() const
+{
+    return !m_image || (m_image->hasOneRef() && m_image->isBitmapImage());
+}
+
+void ImageResource::destroyDecodedDataIfPossible()
+{
+    if (isSafeToUnlock() && !hasClients() && !isLoading()) {
+        m_image = 0;
+        setDecodedSize(0);
+    } else if (m_image && !errorOccurred()) {
+        m_image->destroyDecodedData(true);
+    }
+}
+
 void ImageResource::allClientsRemoved()
 {
     m_pendingContainerSizeRequests.clear();
@@ -272,7 +294,7 @@
 
 void ImageResource::clear()
 {
-    destroyDecodedData();
+    prune();
     clearImage();
     m_pendingContainerSizeRequests.clear();
     setEncodedSize(0);
@@ -390,20 +412,6 @@
     Resource::responseReceived(response);
 }
 
-void ImageResource::destroyDecodedData()
-{
-    bool canDeleteImage = !m_image || (m_image->hasOneRef() && m_image->isBitmapImage());
-    if (isSafeToMakePurgeable() && canDeleteImage && !isLoading()) {
-        // Image refs the data buffer so we should not make it purgeable while the image is alive.
-        // Invoking addClient() will reconstruct the image object.
-        m_image = 0;
-        setDecodedSize(0);
-        makePurgeable(true);
-    } else if (m_image && !errorOccurred()) {
-        m_image->destroyDecodedData(true);
-    }
-}
-
 void ImageResource::decodedSizeChanged(const WebCore::Image* image, int delta)
 {
     if (!image || image != m_image)
diff --git a/Source/core/fetch/ImageResource.h b/Source/core/fetch/ImageResource.h
index 01e0747..b4a244e 100644
--- a/Source/core/fetch/ImageResource.h
+++ b/Source/core/fetch/ImageResource.h
@@ -41,15 +41,19 @@
 class RenderObject;
 class SecurityOrigin;
 
-class ImageResource : public Resource, public ImageObserver {
+class ImageResource FINAL : public Resource, public ImageObserver {
     friend class MemoryCache;
 
 public:
+    typedef ImageResourceClient ClientType;
+
     ImageResource(const ResourceRequest&);
     ImageResource(WebCore::Image*);
+    // Exposed for testing
+    ImageResource(const ResourceRequest&, WebCore::Image*);
     virtual ~ImageResource();
 
-    virtual void load(ResourceFetcher*, const ResourceLoaderOptions&);
+    virtual void load(ResourceFetcher*, const ResourceLoaderOptions&) OVERRIDE;
 
     WebCore::Image* image(); // Returns the nullImage() if the image is not available yet.
     WebCore::Image* imageForRenderer(const RenderObject*); // Returns the nullImage() if the image is not available yet.
@@ -79,30 +83,33 @@
 
     bool isAccessAllowed(SecurityOrigin*);
 
-    virtual void didAddClient(ResourceClient*);
-    virtual void didRemoveClient(ResourceClient*);
+    virtual void didAddClient(ResourceClient*) OVERRIDE;
+    virtual void didRemoveClient(ResourceClient*) OVERRIDE;
 
-    virtual void allClientsRemoved();
-    virtual void destroyDecodedData();
+    virtual void allClientsRemoved() OVERRIDE;
 
     virtual void appendData(const char*, int) OVERRIDE;
-    virtual void error(Resource::Status);
-    virtual void responseReceived(const ResourceResponse&);
+    virtual void error(Resource::Status) OVERRIDE;
+    virtual void responseReceived(const ResourceResponse&) OVERRIDE;
     virtual void finishOnePart() OVERRIDE;
 
     // For compatibility, images keep loading even if there are HTTP errors.
-    virtual bool shouldIgnoreHTTPStatusCodeErrors() const { return true; }
+    virtual bool shouldIgnoreHTTPStatusCodeErrors() const OVERRIDE { return true; }
 
-    virtual bool isImage() const { return true; }
+    virtual bool isImage() const OVERRIDE { return true; }
     virtual bool stillNeedsLoad() const OVERRIDE { return !errorOccurred() && status() == Unknown && !isLoading(); }
 
     // ImageObserver
-    virtual void decodedSizeChanged(const WebCore::Image*, int delta);
-    virtual void didDraw(const WebCore::Image*);
+    virtual void decodedSizeChanged(const WebCore::Image*, int delta) OVERRIDE;
+    virtual void didDraw(const WebCore::Image*) OVERRIDE;
 
-    virtual bool shouldPauseAnimation(const WebCore::Image*);
-    virtual void animationAdvanced(const WebCore::Image*);
-    virtual void changedInRect(const WebCore::Image*, const IntRect&);
+    virtual bool shouldPauseAnimation(const WebCore::Image*) OVERRIDE;
+    virtual void animationAdvanced(const WebCore::Image*) OVERRIDE;
+    virtual void changedInRect(const WebCore::Image*, const IntRect&) OVERRIDE;
+
+protected:
+    virtual bool isSafeToUnlock() const OVERRIDE;
+    virtual void destroyDecodedDataIfPossible() OVERRIDE;
 
 private:
     void clear();
diff --git a/Source/core/fetch/ImageResourceClient.h b/Source/core/fetch/ImageResourceClient.h
index 900550e..b242fc8 100644
--- a/Source/core/fetch/ImageResourceClient.h
+++ b/Source/core/fetch/ImageResourceClient.h
@@ -34,7 +34,7 @@
 public:
     virtual ~ImageResourceClient() { }
     static ResourceClientType expectedType() { return ImageType; }
-    virtual ResourceClientType resourceClientType() const { return expectedType(); }
+    virtual ResourceClientType resourceClientType() const OVERRIDE FINAL { return expectedType(); }
 
     // Called whenever a frame of an image changes, either because we got more data from the network or
     // because we are animating. If not null, the IntRect is the changed rect of the image.
diff --git a/Source/core/fetch/ImageResourceTest.cpp b/Source/core/fetch/ImageResourceTest.cpp
index c54767e..4c723e2 100644
--- a/Source/core/fetch/ImageResourceTest.cpp
+++ b/Source/core/fetch/ImageResourceTest.cpp
@@ -58,7 +58,7 @@
     cachedImage->addClient(&client);
 
     // Send the multipart response. No image or data buffer is created.
-    cachedImage->responseReceived(ResourceResponse(KURL(), "multipart/x-mixed-replace", 0, String(), String()));
+    cachedImage->responseReceived(ResourceResponse(KURL(), "multipart/x-mixed-replace", 0, nullAtom, String()));
     ASSERT_FALSE(cachedImage->resourceBuffer());
     ASSERT_FALSE(cachedImage->hasImage());
     ASSERT_EQ(client.imageChangedCount(), 0);
@@ -67,7 +67,7 @@
     // Send the response for the first real part. No image or data buffer is created.
     const char* svgData = "<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'><rect width='1' height='1' fill='green'/></svg>";
     unsigned svgDataLength = strlen(svgData);
-    cachedImage->responseReceived(ResourceResponse(KURL(), "image/svg+xml", svgDataLength, String(), String()));
+    cachedImage->responseReceived(ResourceResponse(KURL(), "image/svg+xml", svgDataLength, nullAtom, String()));
     ASSERT_FALSE(cachedImage->resourceBuffer());
     ASSERT_FALSE(cachedImage->hasImage());
     ASSERT_EQ(client.imageChangedCount(), 0);
@@ -100,14 +100,12 @@
     blink::WebURLResponse response;
     response.initialize();
     response.setMIMEType("text/html");
-    WTF::String localPath = blink::Platform::current()->unitTestSupport()->webKitRootDir();
-    localPath.append("/Source/web/tests/data/cancelTest.html");
+    WTF::String localPath = String(blink::Platform::current()->unitTestSupport()->webKitRootDir()) + "/Source/web/tests/data/cancelTest.html";
     blink::Platform::current()->unitTestSupport()->registerMockedURL(testURL, response, localPath);
 
     // Create enough of a mocked world to get a functioning ResourceLoader.
     OwnPtr<DummyPageHolder> dummyPageHolder = DummyPageHolder::create();
-    RefPtr<DocumentLoader> documentLoader = DocumentLoader::create(ResourceRequest(testURL), SubstituteData());
-    documentLoader->setFrame(&dummyPageHolder->frame());
+    RefPtr<DocumentLoader> documentLoader = DocumentLoader::create(&dummyPageHolder->frame(), ResourceRequest(testURL), SubstituteData());
 
     // Emulate starting a real load.
     ResourcePtr<ImageResource> cachedImage = new ImageResource(ResourceRequest(testURL));
@@ -131,4 +129,61 @@
     blink::Platform::current()->unitTestSupport()->unregisterMockedURL(testURL);
 }
 
+TEST(ImageResourceTest, DecodedDataRemainsWhileHasClients)
+{
+    ResourcePtr<ImageResource> cachedImage = new ImageResource(ResourceRequest());
+    cachedImage->setLoading(true);
+
+    MockImageResourceClient client;
+    cachedImage->addClient(&client);
+
+    // Send the image response.
+    cachedImage->responseReceived(ResourceResponse(KURL(), "multipart/x-mixed-replace", 0, nullAtom, String()));
+    static const unsigned char jpegData[] = {
+        0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00,
+        0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x13, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65,
+        0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x47, 0x49, 0x4d, 0x50, 0xff, 0xdb, 0x00, 0x43,
+        0x00, 0x05, 0x03, 0x04, 0x04, 0x04, 0x03, 0x05, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x06,
+        0x07, 0x0c, 0x08, 0x07, 0x07, 0x07, 0x07, 0x0f, 0x0b, 0x0b, 0x09, 0x0c, 0x11, 0x0f, 0x12,
+        0x12, 0x11, 0x0f, 0x11, 0x11, 0x13, 0x16, 0x1c, 0x17, 0x13, 0x14, 0x1a, 0x15, 0x11, 0x11,
+        0x18, 0x21, 0x18, 0x1a, 0x1d, 0x1d, 0x1f, 0x1f, 0x1f, 0x13, 0x17, 0x22, 0x24, 0x22, 0x1e,
+        0x24, 0x1c, 0x1e, 0x1f, 0x1e, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x05, 0x05, 0x05, 0x07, 0x06,
+        0x07, 0x0e, 0x08, 0x08, 0x0e, 0x1e, 0x14, 0x11, 0x14, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
+        0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
+        0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e,
+        0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0xff,
+        0xc0, 0x00, 0x11, 0x08, 0x00, 0x01, 0x00, 0x01, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01,
+        0x03, 0x11, 0x01, 0xff, 0xc4, 0x00, 0x15, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0xff, 0xc4, 0x00, 0x14,
+        0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0x00, 0xff, 0xc4, 0x00, 0x14, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xc4, 0x00, 0x14, 0x11,
+        0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f,
+        0x00, 0xb2, 0xc0, 0x07, 0xff, 0xd9
+    };
+
+    unsigned jpegDataLength = sizeof(jpegData);
+    cachedImage->responseReceived(ResourceResponse(KURL(), "image/jpeg", jpegDataLength, nullAtom, String()));
+    cachedImage->appendData(reinterpret_cast<const char*>(jpegData), jpegDataLength);
+    cachedImage->finish();
+    ASSERT_FALSE(cachedImage->errorOccurred());
+    ASSERT_TRUE(cachedImage->hasImage());
+    ASSERT_FALSE(cachedImage->image()->isNull());
+    ASSERT_TRUE(client.notifyFinishedCalled());
+
+    // The prune comes when the ImageResource still has clients. The image should not be deleted.
+    cachedImage->prune();
+    ASSERT_TRUE(cachedImage->hasClients());
+    ASSERT_TRUE(cachedImage->hasImage());
+    ASSERT_FALSE(cachedImage->image()->isNull());
+
+    // The ImageResource no longer has clients. The image should be deleted by prune.
+    cachedImage->removeClient(&client);
+    cachedImage->prune();
+    ASSERT_FALSE(cachedImage->hasClients());
+    ASSERT_FALSE(cachedImage->hasImage());
+    ASSERT_TRUE(cachedImage->image()->isNull());
+}
+
 } // namespace
diff --git a/Source/core/fetch/MemoryCache.cpp b/Source/core/fetch/MemoryCache.cpp
index 53d06d9..0092519 100644
--- a/Source/core/fetch/MemoryCache.cpp
+++ b/Source/core/fetch/MemoryCache.cpp
@@ -41,8 +41,6 @@
 #include "wtf/TemporaryChange.h"
 #include "wtf/text/CString.h"
 
-using namespace std;
-
 namespace WebCore {
 
 static MemoryCache* gMemoryCache;
@@ -111,7 +109,8 @@
 void MemoryCache::add(Resource* resource)
 {
     ASSERT(WTF::isMainThread());
-    m_resources.set(resource->url(), resource);
+    ASSERT(!m_resources.contains(resource->url()));
+    m_resources.set(resource->url(), MemoryCacheEntry::create(resource));
     resource->setInCache(true);
     resource->updateForAccess();
 
@@ -121,8 +120,8 @@
 void MemoryCache::replace(Resource* newResource, Resource* oldResource)
 {
     evict(oldResource);
-    ASSERT(!m_resources.get(newResource->url()));
-    m_resources.set(newResource->url(), newResource);
+    ASSERT(!m_resources.contains(newResource->url()));
+    m_resources.set(newResource->url(), MemoryCacheEntry::create(newResource));
     newResource->setInCache(true);
     insertInLRUList(newResource);
     int delta = newResource->size();
@@ -136,25 +135,29 @@
 {
     ASSERT(WTF::isMainThread());
     KURL url = removeFragmentIdentifierIfNeeded(resourceURL);
-    Resource* resource = m_resources.get(url);
-    if (resource && !resource->makePurgeable(false)) {
+    MemoryCacheEntry* entry = m_resources.get(url);
+    if (!entry)
+        return 0;
+    Resource* resource = entry->m_resource.get();
+    if (resource && !resource->lock()) {
         ASSERT(!resource->hasClients());
-        evict(resource);
+        bool didEvict = evict(resource);
+        ASSERT_UNUSED(didEvict, didEvict);
         return 0;
     }
     return resource;
 }
 
-unsigned MemoryCache::deadCapacity() const
+size_t MemoryCache::deadCapacity() const
 {
     // Dead resource capacity is whatever space is not occupied by live resources, bounded by an independent minimum and maximum.
-    unsigned capacity = m_capacity - min(m_liveSize, m_capacity); // Start with available capacity.
-    capacity = max(capacity, m_minDeadCapacity); // Make sure it's above the minimum.
-    capacity = min(capacity, m_maxDeadCapacity); // Make sure it's below the maximum.
+    size_t capacity = m_capacity - std::min(m_liveSize, m_capacity); // Start with available capacity.
+    capacity = std::max(capacity, m_minDeadCapacity); // Make sure it's above the minimum.
+    capacity = std::min(capacity, m_maxDeadCapacity); // Make sure it's below the maximum.
     return capacity;
 }
 
-unsigned MemoryCache::liveCapacity() const
+size_t MemoryCache::liveCapacity() const
 {
     // Live resource capacity is whatever is left over after calculating dead resource capacity.
     return m_capacity - deadCapacity();
@@ -163,11 +166,11 @@
 void MemoryCache::pruneLiveResources()
 {
     ASSERT(!m_prunePending);
-    unsigned capacity = liveCapacity();
+    size_t capacity = liveCapacity();
     if (!m_liveSize || (capacity && m_liveSize <= capacity))
         return;
 
-    unsigned targetSize = static_cast<unsigned>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
+    size_t targetSize = static_cast<size_t>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
 
     // Destroy any decoded data in live objects that we can.
     // Start from the tail, since this is the lowest priority
@@ -181,50 +184,50 @@
 
     // Start pruning from the lowest priority list.
     for (int priority = Resource::CacheLiveResourcePriorityLow; priority <= Resource::CacheLiveResourcePriorityHigh; ++priority) {
-        Resource* current = m_liveDecodedResources[priority].m_tail;
+        MemoryCacheEntry* current = m_liveDecodedResources[priority].m_tail;
         while (current) {
-            Resource* prev = current->m_prevInLiveResourcesList;
-            ASSERT(current->hasClients());
-            if (current->isLoaded() && current->decodedSize()) {
+            MemoryCacheEntry* previous = current->m_previousInLiveResourcesList;
+            ASSERT(current->m_resource->hasClients());
+            if (current->m_resource->isLoaded() && current->m_resource->decodedSize()) {
                 // Check to see if the remaining resources are too new to prune.
-                double elapsedTime = m_pruneFrameTimeStamp - current->m_lastDecodedAccessTime;
+                double elapsedTime = m_pruneFrameTimeStamp - current->m_resource->m_lastDecodedAccessTime;
                 if (elapsedTime < m_delayBeforeLiveDecodedPrune)
                     return;
 
-                // Destroy our decoded data. This will remove us from
-                // m_liveDecodedResources, and possibly move us to a different LRU
-                // list in m_allResources.
-                current->destroyDecodedData();
+                // Destroy our decoded data if possible. This will remove us
+                // from m_liveDecodedResources, and possibly move us to a
+                // different LRU list in m_allResources.
+                current->m_resource->prune();
 
                 if (targetSize && m_liveSize <= targetSize)
                     return;
             }
-            current = prev;
+            current = previous;
         }
     }
 }
 
 void MemoryCache::pruneDeadResources()
 {
-    unsigned capacity = deadCapacity();
+    size_t capacity = deadCapacity();
     if (!m_deadSize || (capacity && m_deadSize <= capacity))
         return;
 
-    unsigned targetSize = static_cast<unsigned>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
+    size_t targetSize = static_cast<size_t>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
 
     int size = m_allResources.size();
 
     // See if we have any purged resources we can evict.
     for (int i = 0; i < size; i++) {
-        Resource* current = m_allResources[i].m_tail;
+        MemoryCacheEntry* current = m_allResources[i].m_tail;
         while (current) {
-            Resource* prev = current->m_prevInAllResourcesList;
-            if (current->wasPurged()) {
-                ASSERT(!current->hasClients());
-                ASSERT(!current->isPreloaded());
-                evict(current);
+            MemoryCacheEntry* previous = current->m_previousInAllResourcesList;
+            if (current->m_resource->wasPurged()) {
+                ASSERT(!current->m_resource->hasClients());
+                ASSERT(!current->m_resource->isPreloaded());
+                evict(current->m_resource.get());
             }
-            current = prev;
+            current = previous;
         }
     }
     if (targetSize && m_deadSize <= targetSize)
@@ -233,42 +236,42 @@
     bool canShrinkLRULists = true;
     for (int i = size - 1; i >= 0; i--) {
         // Remove from the tail, since this is the least frequently accessed of the objects.
-        Resource* current = m_allResources[i].m_tail;
+        MemoryCacheEntry* current = m_allResources[i].m_tail;
 
         // First flush all the decoded data in this queue.
         while (current) {
             // Protect 'previous' so it can't get deleted during destroyDecodedData().
-            ResourcePtr<Resource> previous = current->m_prevInAllResourcesList;
-            ASSERT(!previous || previous->inCache());
-            if (!current->hasClients() && !current->isPreloaded() && current->isLoaded()) {
+            MemoryCacheEntry* previous = current->m_previousInAllResourcesList;
+            ASSERT(!previous || previous->m_resource->inCache());
+            if (!current->m_resource->hasClients() && !current->m_resource->isPreloaded() && current->m_resource->isLoaded()) {
                 // Destroy our decoded data. This will remove us from
                 // m_liveDecodedResources, and possibly move us to a different
                 // LRU list in m_allResources.
-                current->destroyDecodedData();
+                current->m_resource->prune();
 
                 if (targetSize && m_deadSize <= targetSize)
                     return;
             }
             // Decoded data may reference other resources. Stop iterating if 'previous' somehow got
             // kicked out of cache during destroyDecodedData().
-            if (previous && !previous->inCache())
+            if (previous && !previous->m_resource->inCache())
                 break;
-            current = previous.get();
+            current = previous;
         }
 
         // Now evict objects from this queue.
         current = m_allResources[i].m_tail;
         while (current) {
-            ResourcePtr<Resource> previous = current->m_prevInAllResourcesList;
-            ASSERT(!previous || previous->inCache());
-            if (!current->hasClients() && !current->isPreloaded() && !current->isCacheValidator()) {
-                evict(current);
+            MemoryCacheEntry* previous = current->m_previousInAllResourcesList;
+            ASSERT(!previous || previous->m_resource->inCache());
+            if (!current->m_resource->hasClients() && !current->m_resource->isPreloaded() && !current->m_resource->isCacheValidator()) {
+                evict(current->m_resource.get());
                 if (targetSize && m_deadSize <= targetSize)
                     return;
             }
-            if (previous && !previous->inCache())
+            if (previous && !previous->m_resource->inCache())
                 break;
-            current = previous.get();
+            current = previous;
         }
 
         // Shrink the vector back down so we don't waste time inspecting
@@ -280,7 +283,7 @@
     }
 }
 
-void MemoryCache::setCapacities(unsigned minDeadBytes, unsigned maxDeadBytes, unsigned totalBytes)
+void MemoryCache::setCapacities(size_t minDeadBytes, size_t maxDeadBytes, size_t totalBytes)
 {
     ASSERT(minDeadBytes <= maxDeadBytes);
     ASSERT(maxDeadBytes <= totalBytes);
@@ -291,35 +294,32 @@
     prune();
 }
 
-void MemoryCache::evict(Resource* resource)
+bool MemoryCache::evict(Resource* resource)
 {
     ASSERT(WTF::isMainThread());
     WTF_LOG(ResourceLoading, "Evicting resource %p for '%s' from cache", resource, resource->url().string().latin1().data());
     // The resource may have already been removed by someone other than our caller,
     // who needed a fresh copy for a reload. See <http://bugs.webkit.org/show_bug.cgi?id=12479#c6>.
     if (resource->inCache()) {
-        // Remove from the resource map.
-        m_resources.remove(resource->url());
-        resource->setInCache(false);
-
         // Remove from the appropriate LRU list.
         removeFromLRUList(resource);
         removeFromLiveDecodedResourcesList(resource);
-        adjustSize(resource->hasClients(), -static_cast<int>(resource->size()));
+        adjustSize(resource->hasClients(), -static_cast<ptrdiff_t>(resource->size()));
+
+        // Remove from the resource map.
+        m_resources.remove(resource->url());
+        resource->setInCache(false);
     } else {
-        ASSERT(m_resources.get(resource->url()) != resource);
+        ASSERT(!m_resources.get(resource->url()) || m_resources.get(resource->url())->m_resource != resource);
     }
 
-    resource->deleteIfPossible();
+    return resource->deleteIfPossible();
 }
 
-MemoryCache::LRUList* MemoryCache::lruListFor(Resource* resource)
+MemoryCache::LRUList* MemoryCache::lruListFor(MemoryCacheEntry* entry)
 {
-    unsigned accessCount = max(resource->accessCount(), 1U);
-    unsigned queueIndex = WTF::fastLog2(resource->size() / accessCount);
-#ifndef NDEBUG
-    resource->m_lruIndex = queueIndex;
-#endif
+    unsigned accessCount = std::max(entry->m_resource->accessCount(), 1U);
+    unsigned queueIndex = WTF::fastLog2(entry->m_resource->size() / accessCount);
     if (m_allResources.size() <= queueIndex)
         m_allResources.grow(queueIndex + 1);
     return &m_allResources[queueIndex];
@@ -331,20 +331,14 @@
     if (!resource->accessCount())
         return;
 
-#if !ASSERT_DISABLED
-    unsigned oldListIndex = resource->m_lruIndex;
-#endif
-
-    LRUList* list = lruListFor(resource);
+    MemoryCacheEntry* entry = m_resources.get(resource->url());
+    LRUList* list = lruListFor(entry);
 
 #if !ASSERT_DISABLED
-    // Verify that the list we got is the list we want.
-    ASSERT(resource->m_lruIndex == oldListIndex);
-
     // Verify that we are in fact in this list.
     bool found = false;
-    for (Resource* current = list->m_head; current; current = current->m_nextInAllResourcesList) {
-        if (current == resource) {
+    for (MemoryCacheEntry* current = list->m_head; current; current = current->m_nextInAllResourcesList) {
+        if (current == entry) {
             found = true;
             break;
         }
@@ -352,72 +346,75 @@
     ASSERT(found);
 #endif
 
-    Resource* next = resource->m_nextInAllResourcesList;
-    Resource* prev = resource->m_prevInAllResourcesList;
+    MemoryCacheEntry* next = entry->m_nextInAllResourcesList;
+    MemoryCacheEntry* previous = entry->m_previousInAllResourcesList;
 
-    if (!next && !prev && list->m_head != resource)
+    if (!next && !previous && list->m_head != entry)
         return;
 
-    resource->m_nextInAllResourcesList = 0;
-    resource->m_prevInAllResourcesList = 0;
+    entry->m_nextInAllResourcesList = 0;
+    entry->m_previousInAllResourcesList = 0;
 
     if (next)
-        next->m_prevInAllResourcesList = prev;
-    else if (list->m_tail == resource)
-        list->m_tail = prev;
+        next->m_previousInAllResourcesList = previous;
+    else if (list->m_tail == entry)
+        list->m_tail = previous;
 
-    if (prev)
-        prev->m_nextInAllResourcesList = next;
-    else if (list->m_head == resource)
+    if (previous)
+        previous->m_nextInAllResourcesList = next;
+    else if (list->m_head == entry)
         list->m_head = next;
 }
 
 void MemoryCache::insertInLRUList(Resource* resource)
 {
+    MemoryCacheEntry* entry = m_resources.get(resource->url());
+
     // Make sure we aren't in some list already.
-    ASSERT(!resource->m_nextInAllResourcesList && !resource->m_prevInAllResourcesList);
+    ASSERT(!entry->m_nextInAllResourcesList && !entry->m_previousInAllResourcesList);
     ASSERT(resource->inCache());
     ASSERT(resource->accessCount() > 0);
 
-    LRUList* list = lruListFor(resource);
+    LRUList* list = lruListFor(entry);
 
-    resource->m_nextInAllResourcesList = list->m_head;
+    entry->m_nextInAllResourcesList = list->m_head;
     if (list->m_head)
-        list->m_head->m_prevInAllResourcesList = resource;
-    list->m_head = resource;
+        list->m_head->m_previousInAllResourcesList = entry;
+    list->m_head = entry;
 
-    if (!resource->m_nextInAllResourcesList)
-        list->m_tail = resource;
+    if (!entry->m_nextInAllResourcesList)
+        list->m_tail = entry;
 
 #if !ASSERT_DISABLED
     // Verify that we are in now in the list like we should be.
-    list = lruListFor(resource);
+    list = lruListFor(entry);
     bool found = false;
-    for (Resource* current = list->m_head; current; current = current->m_nextInAllResourcesList) {
-        if (current == resource) {
+    for (MemoryCacheEntry* current = list->m_head; current; current = current->m_nextInAllResourcesList) {
+        if (current == entry) {
             found = true;
             break;
         }
     }
     ASSERT(found);
 #endif
-
 }
 
 void MemoryCache::removeFromLiveDecodedResourcesList(Resource* resource)
 {
+    MemoryCacheEntry* entry = m_resources.get(resource->url());
+
     // If we've never been accessed, then we're brand new and not in any list.
-    if (!resource->m_inLiveDecodedResourcesList)
+    if (!entry->m_inLiveDecodedResourcesList)
         return;
-    resource->m_inLiveDecodedResourcesList = false;
+    entry->m_inLiveDecodedResourcesList = false;
 
     LRUList* list = &m_liveDecodedResources[resource->cacheLiveResourcePriority()];
 
 #if !ASSERT_DISABLED
     // Verify that we are in fact in this list.
     bool found = false;
-    for (Resource* current = list->m_head; current; current = current->m_nextInLiveResourcesList) {
-        if (current == resource) {
+    for (MemoryCacheEntry* current = list->m_head; current; current = current->m_nextInLiveResourcesList) {
+        if (current == entry) {
             found = true;
             break;
         }
@@ -425,74 +422,83 @@
     ASSERT(found);
 #endif
 
-    Resource* next = resource->m_nextInLiveResourcesList;
-    Resource* prev = resource->m_prevInLiveResourcesList;
+    MemoryCacheEntry* next = entry->m_nextInLiveResourcesList;
+    MemoryCacheEntry* previous = entry->m_previousInLiveResourcesList;
 
-    if (!next && !prev && list->m_head != resource)
+    if (!next && !previous && list->m_head != entry)
         return;
 
-    resource->m_nextInLiveResourcesList = 0;
-    resource->m_prevInLiveResourcesList = 0;
+    entry->m_nextInLiveResourcesList = 0;
+    entry->m_previousInLiveResourcesList = 0;
 
     if (next)
-        next->m_prevInLiveResourcesList = prev;
-    else if (list->m_tail == resource)
-        list->m_tail = prev;
+        next->m_previousInLiveResourcesList = previous;
+    else if (list->m_tail == entry)
+        list->m_tail = previous;
 
-    if (prev)
-        prev->m_nextInLiveResourcesList = next;
-    else if (list->m_head == resource)
+    if (previous)
+        previous->m_nextInLiveResourcesList = next;
+    else if (list->m_head == entry)
         list->m_head = next;
 }
 
 void MemoryCache::insertInLiveDecodedResourcesList(Resource* resource)
 {
+    MemoryCacheEntry* entry = m_resources.get(resource->url());
+
     // Make sure we aren't in the list already.
-    ASSERT(!resource->m_nextInLiveResourcesList && !resource->m_prevInLiveResourcesList && !resource->m_inLiveDecodedResourcesList);
-    resource->m_inLiveDecodedResourcesList = true;
+    ASSERT(!entry->m_nextInLiveResourcesList && !entry->m_previousInLiveResourcesList && !entry->m_inLiveDecodedResourcesList);
+    entry->m_inLiveDecodedResourcesList = true;
 
     LRUList* list = &m_liveDecodedResources[resource->cacheLiveResourcePriority()];
-    resource->m_nextInLiveResourcesList = list->m_head;
+    entry->m_nextInLiveResourcesList = list->m_head;
     if (list->m_head)
-        list->m_head->m_prevInLiveResourcesList = resource;
-    list->m_head = resource;
+        list->m_head->m_previousInLiveResourcesList = entry;
+    list->m_head = entry;
 
-    if (!resource->m_nextInLiveResourcesList)
-        list->m_tail = resource;
+    if (!entry->m_nextInLiveResourcesList)
+        list->m_tail = entry;
 
 #if !ASSERT_DISABLED
     // Verify that we are in now in the list like we should be.
     bool found = false;
-    for (Resource* current = list->m_head; current; current = current->m_nextInLiveResourcesList) {
-        if (current == resource) {
+    for (MemoryCacheEntry* current = list->m_head; current; current = current->m_nextInLiveResourcesList) {
+        if (current == entry) {
             found = true;
             break;
         }
     }
     ASSERT(found);
 #endif
+}
 
+bool MemoryCache::isInLiveDecodedResourcesList(Resource* resource)
+{
+    MemoryCacheEntry* entry = m_resources.get(resource->url());
+    return entry ? entry->m_inLiveDecodedResourcesList : false;
 }
 
 void MemoryCache::addToLiveResourcesSize(Resource* resource)
 {
+    ASSERT(m_deadSize >= resource->size());
     m_liveSize += resource->size();
     m_deadSize -= resource->size();
 }
 
 void MemoryCache::removeFromLiveResourcesSize(Resource* resource)
 {
+    ASSERT(m_liveSize >= resource->size());
     m_liveSize -= resource->size();
     m_deadSize += resource->size();
 }
 
-void MemoryCache::adjustSize(bool live, int delta)
+void MemoryCache::adjustSize(bool live, ptrdiff_t delta)
 {
     if (live) {
-        ASSERT(delta >= 0 || ((int)m_liveSize + delta >= 0));
+        ASSERT(delta >= 0 || m_liveSize >= static_cast<size_t>(-delta) );
         m_liveSize += delta;
     } else {
-        ASSERT(delta >= 0 || ((int)m_deadSize + delta >= 0));
+        ASSERT(delta >= 0 || m_deadSize >= static_cast<size_t>(-delta) );
         m_deadSize += delta;
     }
 }
@@ -517,7 +523,7 @@
 {
     bool purged = o->wasPurged();
     bool purgeable = o->isPurgeable() && !purged;
-    int pageSize = (o->encodedSize() + o->overheadSize() + 4095) & ~4095;
+    size_t pageSize = (o->encodedSize() + o->overheadSize() + 4095) & ~4095;
     count++;
     size += purged ? 0 : o->size();
     liveSize += o->hasClients() ? o->size() : 0;
@@ -533,7 +539,7 @@
     Statistics stats;
     ResourceMap::iterator e = m_resources.end();
     for (ResourceMap::iterator i = m_resources.begin(); i != e; ++i) {
-        Resource* resource = i->value;
+        Resource* resource = i->value->m_resource.get();
         switch (resource->type()) {
         case Resource::Image:
             stats.images.addResource(resource);
@@ -564,7 +570,7 @@
         ResourceMap::iterator i = m_resources.begin();
         if (i == m_resources.end())
             break;
-        evict(i->value);
+        evict(i->value->m_resource.get());
     }
 }
 
diff --git a/Source/core/fetch/MemoryCache.h b/Source/core/fetch/MemoryCache.h
index 178680c..0030afe 100644
--- a/Source/core/fetch/MemoryCache.h
+++ b/Source/core/fetch/MemoryCache.h
@@ -26,6 +26,7 @@
 #define MemoryCache_h
 
 #include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
 #include "public/platform/WebThread.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
@@ -59,17 +60,39 @@
 // Enable this macro to periodically log information about the memory cache.
 #undef MEMORY_CACHE_STATS
 
-class MemoryCache : public blink::WebThread::TaskObserver {
+class MemoryCache FINAL : public blink::WebThread::TaskObserver {
     WTF_MAKE_NONCOPYABLE(MemoryCache); WTF_MAKE_FAST_ALLOCATED;
 public:
     MemoryCache();
     virtual ~MemoryCache();
 
-    typedef HashMap<String, Resource*> ResourceMap;
+    class MemoryCacheEntry {
+    public:
+        static PassOwnPtr<MemoryCacheEntry> create(Resource* resource) { return adoptPtr(new MemoryCacheEntry(resource)); }
+
+        ResourcePtr<Resource> m_resource;
+        bool m_inLiveDecodedResourcesList;
+
+        MemoryCacheEntry* m_previousInLiveResourcesList;
+        MemoryCacheEntry* m_nextInLiveResourcesList;
+        MemoryCacheEntry* m_previousInAllResourcesList;
+        MemoryCacheEntry* m_nextInAllResourcesList;
+
+    private:
+        MemoryCacheEntry(Resource* resource)
+            : m_resource(resource)
+            , m_inLiveDecodedResourcesList(false)
+            , m_previousInLiveResourcesList(0)
+            , m_nextInLiveResourcesList(0)
+            , m_previousInAllResourcesList(0)
+            , m_nextInAllResourcesList(0)
+        {
+        }
+    };
 
     struct LRUList {
-        Resource* m_head;
-        Resource* m_tail;
+        MemoryCacheEntry* m_head;
+        MemoryCacheEntry* m_tail;
         LRUList() : m_head(0), m_tail(0) { }
     };
 
@@ -120,7 +143,7 @@
     //  - minDeadBytes: The maximum number of bytes that dead resources should consume when the cache is under pressure.
     //  - maxDeadBytes: The maximum number of bytes that dead resources should consume when the cache is not under pressure.
     //  - totalBytes: The maximum number of bytes that the cache should consume overall.
-    void setCapacities(unsigned minDeadBytes, unsigned maxDeadBytes, unsigned totalBytes);
+    void setCapacities(size_t minDeadBytes, size_t maxDeadBytes, size_t totalBytes);
     void setDelayBeforeLiveDecodedPrune(double seconds) { m_delayBeforeLiveDecodedPrune = seconds; }
     void setMaxPruneDeferralDelay(double seconds) { m_maxPruneDeferralDelay = seconds; }
 
@@ -133,11 +156,12 @@
     void removeFromLRUList(Resource*);
 
     // Called to adjust the cache totals when a resource changes size.
-    void adjustSize(bool live, int delta);
+    void adjustSize(bool live, ptrdiff_t delta);
 
     // Track decoded resources that are in the cache and referenced by a Web page.
     void insertInLiveDecodedResourcesList(Resource*);
     void removeFromLiveDecodedResourcesList(Resource*);
+    bool isInLiveDecodedResourcesList(Resource*);
 
     void addToLiveResourcesSize(Resource*);
     void removeFromLiveResourcesSize(Resource*);
@@ -146,26 +170,26 @@
 
     Statistics getStatistics();
 
-    unsigned minDeadCapacity() const { return m_minDeadCapacity; }
-    unsigned maxDeadCapacity() const { return m_maxDeadCapacity; }
-    unsigned capacity() const { return m_capacity; }
-    unsigned liveSize() const { return m_liveSize; }
-    unsigned deadSize() const { return m_deadSize; }
+    size_t minDeadCapacity() const { return m_minDeadCapacity; }
+    size_t maxDeadCapacity() const { return m_maxDeadCapacity; }
+    size_t capacity() const { return m_capacity; }
+    size_t liveSize() const { return m_liveSize; }
+    size_t deadSize() const { return m_deadSize; }
 
     // TaskObserver implementation
     virtual void willProcessTask() OVERRIDE;
     virtual void didProcessTask() OVERRIDE;
 
 private:
-    LRUList* lruListFor(Resource*);
+    LRUList* lruListFor(MemoryCacheEntry*);
 
 #ifdef MEMORY_CACHE_STATS
     void dumpStats(Timer<MemoryCache>*);
     void dumpLRULists(bool includeLive) const;
 #endif
 
-    unsigned liveCapacity() const;
-    unsigned deadCapacity() const;
+    size_t liveCapacity() const;
+    size_t deadCapacity() const;
 
     // pruneDeadResources() - Flush decoded and encoded data from resources not referenced by Web pages.
     // pruneLiveResources() - Flush decoded data from resources still referenced by Web pages.
@@ -173,26 +197,24 @@
     void pruneLiveResources();
     void pruneNow(double currentTime);
 
-    void evict(Resource*);
+    bool evict(Resource*);
 
     static void removeURLFromCacheInternal(ExecutionContext*, const KURL&);
 
     bool m_inPruneResources;
     bool m_prunePending;
-    bool m_prePainting;
     double m_maxPruneDeferralDelay;
     double m_pruneTimeStamp;
     double m_pruneFrameTimeStamp;
 
-    unsigned m_capacity;
-    unsigned m_minDeadCapacity;
-    unsigned m_maxDeadCapacity;
-    unsigned m_maxDeferredPruneDeadCapacity;
+    size_t m_capacity;
+    size_t m_minDeadCapacity;
+    size_t m_maxDeadCapacity;
+    size_t m_maxDeferredPruneDeadCapacity;
     double m_delayBeforeLiveDecodedPrune;
-    double m_deadDecodedDataDeletionInterval;
 
-    unsigned m_liveSize; // The number of bytes currently consumed by "live" resources in the cache.
-    unsigned m_deadSize; // The number of bytes currently consumed by "dead" resources in the cache.
+    size_t m_liveSize; // The number of bytes currently consumed by "live" resources in the cache.
+    size_t m_deadSize; // The number of bytes currently consumed by "dead" resources in the cache.
 
     // Size-adjusted and popularity-aware LRU list collection for cache objects. This collection can hold
     // more resources than the cached resource map, since it can also hold "stale" multiple versions of objects that are
@@ -205,7 +227,8 @@
 
     // A URL-based map of all resources that are in the cache (including the freshest version of objects that are currently being
     // referenced by a Web page).
-    HashMap<String, Resource*> m_resources;
+    typedef HashMap<String, OwnPtr<MemoryCacheEntry> > ResourceMap;
+    ResourceMap m_resources;
 
     friend class MemoryCacheTest;
 #ifdef MEMORY_CACHE_STATS
diff --git a/Source/core/fetch/MemoryCacheTest.cpp b/Source/core/fetch/MemoryCacheTest.cpp
index 21962b1..b59e513 100644
--- a/Source/core/fetch/MemoryCacheTest.cpp
+++ b/Source/core/fetch/MemoryCacheTest.cpp
@@ -57,12 +57,26 @@
             setDecodedSize(this->size());
         }
 
-        virtual void destroyDecodedData()
+    protected:
+        virtual void destroyDecodedDataIfPossible() OVERRIDE
         {
             setDecodedSize(0);
         }
     };
 
+    class FakeResource : public WebCore::Resource {
+    public:
+        FakeResource(const ResourceRequest& request, Type type)
+            : Resource(request, type)
+        {
+        }
+
+        void fakeEncodedSize(size_t size)
+        {
+            setEncodedSize(size);
+        }
+    };
+
 protected:
     virtual void SetUp()
     {
@@ -89,16 +103,45 @@
 // Verifies that setters and getters for cache capacities work correcty.
 TEST_F(MemoryCacheTest, CapacityAccounting)
 {
-    const unsigned totalCapacity = 100;
-    const unsigned minDeadCapacity = 10;
-    const unsigned maxDeadCapacity = 50;
+    const size_t sizeMax = ~static_cast<size_t>(0);
+    const size_t totalCapacity = sizeMax / 4;
+    const size_t minDeadCapacity = sizeMax / 16;
+    const size_t maxDeadCapacity = sizeMax / 8;
     memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
-
     ASSERT_EQ(totalCapacity, memoryCache()->capacity());
     ASSERT_EQ(minDeadCapacity, memoryCache()->minDeadCapacity());
     ASSERT_EQ(maxDeadCapacity, memoryCache()->maxDeadCapacity());
 }
 
+TEST_F(MemoryCacheTest, VeryLargeResourceAccounting)
+{
+    const size_t sizeMax = ~static_cast<size_t>(0);
+    const size_t totalCapacity = sizeMax / 4;
+    const size_t minDeadCapacity = sizeMax / 16;
+    const size_t maxDeadCapacity = sizeMax / 8;
+    const size_t resourceSize1 = sizeMax / 16;
+    const size_t resourceSize2 = sizeMax / 20;
+    memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
+    ResourcePtr<FakeResource> cachedResource =
+        new FakeResource(ResourceRequest(""), Resource::Raw);
+    cachedResource->fakeEncodedSize(resourceSize1);
+
+    ASSERT_EQ(0u, memoryCache()->deadSize());
+    ASSERT_EQ(0u, memoryCache()->liveSize());
+    memoryCache()->add(cachedResource.get());
+    ASSERT_EQ(cachedResource->size(), memoryCache()->deadSize());
+    ASSERT_EQ(0u, memoryCache()->liveSize());
+
+    MockImageResourceClient client;
+    cachedResource->addClient(&client);
+    ASSERT_EQ(0u, memoryCache()->deadSize());
+    ASSERT_EQ(cachedResource->size(), memoryCache()->liveSize());
+
+    cachedResource->fakeEncodedSize(resourceSize2);
+    ASSERT_EQ(0u, memoryCache()->deadSize());
+    ASSERT_EQ(cachedResource->size(), memoryCache()->liveSize());
+}
+
 // Verifies that dead resources that exceed dead resource capacity are evicted
 // from cache when pruning.
 TEST_F(MemoryCacheTest, DeadResourceEviction)
@@ -141,7 +184,7 @@
     memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
     const char data[6] = "abcde";
     ResourcePtr<Resource> cachedDeadResource =
-        new Resource(ResourceRequest(""), Resource::Raw);
+        new Resource(ResourceRequest("http://foo"), Resource::Raw);
     cachedDeadResource->appendData(data, 3);
     ResourcePtr<Resource> cachedLiveResource =
         new FakeDecodedResource(ResourceRequest(""), Resource::Raw);
@@ -213,7 +256,7 @@
 {
     const char data[6] = "abcde";
     ResourcePtr<Resource> resource1 =
-        new FakeDecodedResource(ResourceRequest(""), Resource::Raw);
+        new FakeDecodedResource(ResourceRequest("http://foo.com"), Resource::Raw);
     MockImageResourceClient client1;
     resource1->addClient(&client1);
     resource1->appendData(data, 4);
@@ -224,7 +267,7 @@
     resource2->appendData(data, 4);
 
     const unsigned minDeadCapacity = 0;
-    const unsigned maxDeadCapacity = resource1->size() - 1;
+    const unsigned maxDeadCapacity = ((resource1->size() + resource2->size()) / 2) - 1;
     const unsigned totalCapacity = maxDeadCapacity;
     memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
     memoryCache()->add(resource1.get());
@@ -265,7 +308,7 @@
     memoryCache()->setDelayBeforeLiveDecodedPrune(0);
     memoryCache()->setMaxPruneDeferralDelay(0);
     ResourcePtr<FakeDecodedResource> cachedImageLowPriority =
-        new FakeDecodedResource(ResourceRequest(""), Resource::Raw);
+        new FakeDecodedResource(ResourceRequest("http://foo.com"), Resource::Raw);
     ResourcePtr<FakeDecodedResource> cachedImageHighPriority =
         new FakeDecodedResource(ResourceRequest(""), Resource::Raw);
 
diff --git a/Source/core/fetch/MockImageResourceClient.h b/Source/core/fetch/MockImageResourceClient.h
index 4499396..be1867d 100644
--- a/Source/core/fetch/MockImageResourceClient.h
+++ b/Source/core/fetch/MockImageResourceClient.h
@@ -37,7 +37,7 @@
 
 namespace WebCore {
 
-class MockImageResourceClient : public WebCore::ImageResourceClient {
+class MockImageResourceClient FINAL : public WebCore::ImageResourceClient {
 public:
     MockImageResourceClient()
         : m_imageChangedCount(0)
@@ -46,12 +46,12 @@
     }
 
     virtual ~MockImageResourceClient() { }
-    virtual void imageChanged(ImageResource*, const IntRect*)
+    virtual void imageChanged(ImageResource*, const IntRect*) OVERRIDE
     {
         m_imageChangedCount++;
     }
 
-    virtual void notifyFinished(Resource*)
+    virtual void notifyFinished(Resource*) OVERRIDE
     {
         ASSERT_FALSE(m_notifyFinishedCalled);
         m_notifyFinishedCalled = true;
diff --git a/Source/core/fetch/RawResource.cpp b/Source/core/fetch/RawResource.cpp
index f910e7e..1d4fe56 100644
--- a/Source/core/fetch/RawResource.cpp
+++ b/Source/core/fetch/RawResource.cpp
@@ -57,15 +57,15 @@
     // so a protector is necessary.
     ResourcePtr<RawResource> protect(this);
     RawResourceClient* client = static_cast<RawResourceClient*>(c);
-    size_t redirectCount = m_redirectChain.size();
+    size_t redirectCount = redirectChain().size();
     for (size_t i = 0; i < redirectCount; i++) {
-        RedirectPair redirect = m_redirectChain[i];
+        RedirectPair redirect = redirectChain()[i];
         ResourceRequest request(redirect.m_request);
         client->redirectReceived(this, request, redirect.m_redirectResponse);
         if (!hasClient(c))
             return;
     }
-    ASSERT(redirectCount == m_redirectChain.size());
+    ASSERT(redirectCount == redirectChain().size());
 
     if (!m_response.isNull())
         client->responseReceived(this, m_response);
@@ -85,14 +85,21 @@
         ResourceClientWalker<RawResourceClient> w(m_clients);
         while (RawResourceClient* c = w.next())
             c->redirectReceived(this, request, response);
-        m_redirectChain.append(RedirectPair(request, response));
     }
     Resource::willSendRequest(request, response);
 }
 
-void RawResource::responseReceived(const ResourceResponse& response)
+void RawResource::updateRequest(const ResourceRequest& request)
 {
     ResourcePtr<RawResource> protect(this);
+    ResourceClientWalker<RawResourceClient> w(m_clients);
+    while (RawResourceClient* c = w.next())
+        c->updateRequest(this, request);
+}
+
+void RawResource::responseReceived(const ResourceResponse& response)
+{
+    InternalResourcePtr protect(this);
     Resource::responseReceived(response);
     ResourceClientWalker<RawResourceClient> w(m_clients);
     while (RawResourceClient* c = w.next())
@@ -119,12 +126,6 @@
         m_loader->setDefersLoading(defers);
 }
 
-void RawResource::setDataBufferingPolicy(DataBufferingPolicy dataBufferingPolicy)
-{
-    m_options.dataBufferingPolicy = dataBufferingPolicy;
-    clear();
-}
-
 static bool shouldIgnoreHeaderForCacheReuse(AtomicString headerName)
 {
     // FIXME: This list of headers that don't affect cache policy almost certainly isn't complete.
@@ -177,18 +178,7 @@
             return false;
     }
 
-    for (size_t i = 0; i < m_redirectChain.size(); i++) {
-        if (m_redirectChain[i].m_redirectResponse.cacheControlContainsNoStore())
-            return false;
-    }
-
     return true;
 }
 
-void RawResource::clear()
-{
-    m_data.clear();
-    setEncodedSize(0);
-}
-
 } // namespace WebCore
diff --git a/Source/core/fetch/RawResource.h b/Source/core/fetch/RawResource.h
index 1cdbddd..07405e9 100644
--- a/Source/core/fetch/RawResource.h
+++ b/Source/core/fetch/RawResource.h
@@ -30,45 +30,30 @@
 class RawResourceCallback;
 class RawResourceClient;
 
-class RawResource : public Resource {
+class RawResource FINAL : public Resource {
 public:
+    typedef RawResourceClient ClientType;
+
     RawResource(const ResourceRequest&, Type);
 
     // FIXME: AssociatedURLLoader shouldn't be a DocumentThreadableLoader and therefore shouldn't
     // use RawResource. However, it is, and it needs to be able to defer loading.
     // This can be fixed by splitting CORS preflighting out of DocumentThreacableLoader.
-    virtual void setDefersLoading(bool);
+    void setDefersLoading(bool);
 
-    virtual void setDataBufferingPolicy(DataBufferingPolicy);
-
-    void clear();
-
-    virtual bool canReuse(const ResourceRequest&) const;
+    virtual bool canReuse(const ResourceRequest&) const OVERRIDE;
 
 private:
-    virtual void didAddClient(ResourceClient*);
+    virtual void didAddClient(ResourceClient*) OVERRIDE;
     virtual void appendData(const char*, int) OVERRIDE;
 
-    virtual bool shouldIgnoreHTTPStatusCodeErrors() const { return true; }
+    virtual bool shouldIgnoreHTTPStatusCodeErrors() const OVERRIDE { return true; }
 
-    virtual void willSendRequest(ResourceRequest&, const ResourceResponse&);
-    virtual void responseReceived(const ResourceResponse&);
-    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
-    virtual void didDownloadData(int);
-
-    struct RedirectPair {
-    public:
-        explicit RedirectPair(const ResourceRequest& request, const ResourceResponse& redirectResponse)
-            : m_request(request)
-            , m_redirectResponse(redirectResponse)
-        {
-        }
-
-        const ResourceRequest m_request;
-        const ResourceResponse m_redirectResponse;
-    };
-
-    Vector<RedirectPair> m_redirectChain;
+    virtual void willSendRequest(ResourceRequest&, const ResourceResponse&) OVERRIDE;
+    virtual void updateRequest(const ResourceRequest&) OVERRIDE;
+    virtual void responseReceived(const ResourceResponse&) OVERRIDE;
+    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
+    virtual void didDownloadData(int) OVERRIDE;
 };
 
 #ifdef SECURITY_ASSERT_ENABLED
@@ -88,12 +73,13 @@
 public:
     virtual ~RawResourceClient() { }
     static ResourceClientType expectedType() { return RawResourceType; }
-    virtual ResourceClientType resourceClientType() const { return expectedType(); }
+    virtual ResourceClientType resourceClientType() const OVERRIDE FINAL { return expectedType(); }
 
     virtual void dataSent(Resource*, unsigned long long /* bytesSent */, unsigned long long /* totalBytesToBeSent */) { }
     virtual void responseReceived(Resource*, const ResourceResponse&) { }
     virtual void dataReceived(Resource*, const char* /* data */, int /* length */) { }
     virtual void redirectReceived(Resource*, ResourceRequest&, const ResourceResponse&) { }
+    virtual void updateRequest(Resource*, const ResourceRequest&) { }
     virtual void dataDownloaded(Resource*, int) { }
 };
 
diff --git a/Source/core/fetch/RawResourceTest.cpp b/Source/core/fetch/RawResourceTest.cpp
index b61c7e6..3c4d009 100644
--- a/Source/core/fetch/RawResourceTest.cpp
+++ b/Source/core/fetch/RawResourceTest.cpp
@@ -62,4 +62,28 @@
     ASSERT_FALSE(jpegResource.canReuse(pngRequest));
 }
 
+TEST(RawResourceTest, RevalidationSucceeded)
+{
+    // Create two RawResources and set one to revalidate the other.
+    RawResource* oldResourcePointer = new RawResource(ResourceRequest("data:text/html,"), Resource::Raw);
+    RawResource* newResourcePointer = new RawResource(ResourceRequest("data:text/html,"), Resource::Raw);
+    newResourcePointer->setResourceToRevalidate(oldResourcePointer);
+    ResourcePtr<Resource> oldResource = oldResourcePointer;
+    ResourcePtr<Resource> newResource = newResourcePointer;
+    memoryCache()->add(oldResource.get());
+    memoryCache()->remove(oldResource.get());
+    memoryCache()->add(newResource.get());
+
+    // Simulate a successful revalidation.
+    // The revalidated resource (oldResource) should now be in the cache, newResource
+    // should have been sliently switched to point to the revalidated resource, and
+    // we shouldn't hit any ASSERTs.
+    ResourceResponse response;
+    response.setHTTPStatusCode(304);
+    newResource->responseReceived(response);
+    EXPECT_EQ(memoryCache()->resourceForURL(KURL(ParsedURLString, "data:text/html,")), oldResource.get());
+    EXPECT_EQ(oldResource.get(), newResource.get());
+    EXPECT_NE(newResource.get(), newResourcePointer);
+}
+
 } // namespace
diff --git a/Source/core/fetch/Resource.cpp b/Source/core/fetch/Resource.cpp
index b5d07b3..c728f37 100644
--- a/Source/core/fetch/Resource.cpp
+++ b/Source/core/fetch/Resource.cpp
@@ -24,6 +24,7 @@
 #include "config.h"
 #include "core/fetch/Resource.h"
 
+#include "FetchInitiatorTypeNames.h"
 #include "core/fetch/CachedMetadata.h"
 #include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/MemoryCache.h"
@@ -105,23 +106,20 @@
     , m_accessCount(0)
     , m_handleCount(0)
     , m_preloadCount(0)
+    , m_protectorCount(0)
     , m_preloadResult(PreloadNotReferenced)
     , m_cacheLiveResourcePriority(CacheLiveResourcePriorityLow)
-    , m_inLiveDecodedResourcesList(false)
     , m_requestedFromNetworkingLayer(false)
     , m_inCache(false)
     , m_loading(false)
     , m_switchingClientsToRevalidatedResource(false)
     , m_type(type)
     , m_status(Pending)
+    , m_wasPurged(false)
+    , m_needsSynchronousCacheHit(false)
 #ifndef NDEBUG
     , m_deleted(false)
-    , m_lruIndex(0)
 #endif
-    , m_nextInAllResourcesList(0)
-    , m_prevInAllResourcesList(0)
-    , m_nextInLiveResourcesList(0)
-    , m_prevInLiveResourcesList(0)
     , m_resourceToRevalidate(0)
     , m_proxyResource(0)
 {
@@ -224,6 +222,13 @@
     setEncodedSize(m_data->size());
 }
 
+void Resource::setDataBufferingPolicy(DataBufferingPolicy dataBufferingPolicy)
+{
+    m_options.dataBufferingPolicy = dataBufferingPolicy;
+    m_data.clear();
+    setEncodedSize(0);
+}
+
 void Resource::error(Resource::Status status)
 {
     if (m_resourceToRevalidate)
@@ -267,54 +272,102 @@
     return WebCore::passesAccessControlCheck(m_response, resourceRequest().allowCookies() ? AllowStoredCredentials : DoNotAllowStoredCredentials, securityOrigin, errorDescription);
 }
 
-bool Resource::isExpired() const
-{
-    if (m_response.isNull())
-        return false;
-
-    return currentAge() > freshnessLifetime();
-}
-
-double Resource::currentAge() const
+static double currentAge(const ResourceResponse& response, double responseTimestamp)
 {
     // RFC2616 13.2.3
     // No compensation for latency as that is not terribly important in practice
-    double dateValue = m_response.date();
-    double apparentAge = std::isfinite(dateValue) ? std::max(0., m_responseTimestamp - dateValue) : 0;
-    double ageValue = m_response.age();
+    double dateValue = response.date();
+    double apparentAge = std::isfinite(dateValue) ? std::max(0., responseTimestamp - dateValue) : 0;
+    double ageValue = response.age();
     double correctedReceivedAge = std::isfinite(ageValue) ? std::max(apparentAge, ageValue) : apparentAge;
-    double residentTime = currentTime() - m_responseTimestamp;
+    double residentTime = currentTime() - responseTimestamp;
     return correctedReceivedAge + residentTime;
 }
 
-double Resource::freshnessLifetime() const
+static double freshnessLifetime(const ResourceResponse& response, double responseTimestamp)
 {
 #if !OS(ANDROID)
     // On desktop, local files should be reloaded in case they change.
-    if (m_response.url().isLocalFile())
+    if (response.url().isLocalFile())
         return 0;
 #endif
 
-    // Cache other non-http resources liberally.
-    if (!m_response.url().protocolIsInHTTPFamily())
+    // Cache other non-http / non-filesystem resources liberally.
+    if (!response.url().protocolIsInHTTPFamily()
+        && !response.url().protocolIs("filesystem"))
         return std::numeric_limits<double>::max();
 
     // RFC2616 13.2.4
-    double maxAgeValue = m_response.cacheControlMaxAge();
+    double maxAgeValue = response.cacheControlMaxAge();
     if (std::isfinite(maxAgeValue))
         return maxAgeValue;
-    double expiresValue = m_response.expires();
-    double dateValue = m_response.date();
-    double creationTime = std::isfinite(dateValue) ? dateValue : m_responseTimestamp;
+    double expiresValue = response.expires();
+    double dateValue = response.date();
+    double creationTime = std::isfinite(dateValue) ? dateValue : responseTimestamp;
     if (std::isfinite(expiresValue))
         return expiresValue - creationTime;
-    double lastModifiedValue = m_response.lastModified();
+    double lastModifiedValue = response.lastModified();
     if (std::isfinite(lastModifiedValue))
         return (creationTime - lastModifiedValue) * 0.1;
     // If no cache headers are present, the specification leaves the decision to the UA. Other browsers seem to opt for 0.
     return 0;
 }
 
+static bool canUseResponse(const ResourceResponse& response, double responseTimestamp)
+{
+    if (response.isNull())
+        return false;
+
+    // FIXME: Why isn't must-revalidate considered a reason we can't use the response?
+    if (response.cacheControlContainsNoCache() || response.cacheControlContainsNoStore())
+        return false;
+
+    if (response.httpStatusCode() == 303)  {
+        // Must not be cached.
+        return false;
+    }
+
+    if (response.httpStatusCode() == 302 || response.httpStatusCode() == 307) {
+        // Default to not cacheable.
+        // FIXME: Consider allowing these to be cached if they have headers permitting caching.
+        return false;
+    }
+
+    return currentAge(response, responseTimestamp) <= freshnessLifetime(response, responseTimestamp);
+}
+
+void Resource::willSendRequest(ResourceRequest& request, const ResourceResponse& response)
+{
+    m_redirectChain.append(RedirectPair(request, response));
+    m_requestedFromNetworkingLayer = true;
+}
+
+bool Resource::unlock()
+{
+    if (hasClients() || m_proxyResource || m_resourceToRevalidate || !m_loadFinishTime || !isSafeToUnlock())
+        return false;
+
+    if (m_purgeableData) {
+        ASSERT(!m_data);
+        return true;
+    }
+    if (!m_data)
+        return false;
+
+    // Should not make buffer purgeable if it has refs other than this since we don't want two copies.
+    if (!m_data->hasOneRef())
+        return false;
+
+    m_data->createPurgeableBuffer();
+    if (!m_data->hasPurgeableBuffer())
+        return false;
+
+    m_purgeableData = m_data->releasePurgeableBuffer();
+    m_purgeableData->unlock();
+    m_data.clear();
+    return true;
+}
+
 void Resource::responseReceived(const ResourceResponse& response)
 {
     setResponse(response);
@@ -363,7 +416,7 @@
 
 void Resource::setCacheLiveResourcePriority(CacheLiveResourcePriority priority)
 {
-    if (inCache() && m_inLiveDecodedResourcesList && cacheLiveResourcePriority() != static_cast<unsigned>(priority)) {
+    if (inCache() && memoryCache()->isInLiveDecodedResourcesList(this) && cacheLiveResourcePriority() != static_cast<unsigned>(priority)) {
         memoryCache()->removeFromLiveDecodedResourcesList(this);
         m_cacheLiveResourcePriority = priority;
         memoryCache()->insertInLiveDecodedResourcesList(this);
@@ -423,7 +476,7 @@
         memoryCache()->addToLiveResourcesSize(this);
 
     // If we have existing data to send to the new client and the resource type supprts it, send it asynchronously.
-    if (!m_response.isNull() && !m_proxyResource && !shouldSendCachedDataSynchronouslyForType(type())) {
+    if (!m_response.isNull() && !m_proxyResource && !shouldSendCachedDataSynchronouslyForType(type()) && !m_needsSynchronousCacheHit) {
         m_clientsAwaitingCallback.add(client);
         ResourceCallback::callbackHandler()->schedule(this);
         return false;
@@ -499,12 +552,12 @@
     return false;
 }
 
-void Resource::setDecodedSize(unsigned size)
+void Resource::setDecodedSize(size_t size)
 {
     if (size == m_decodedSize)
         return;
 
-    int delta = size - m_decodedSize;
+    ptrdiff_t delta = size - m_decodedSize;
 
     // The object must now be moved to a different queue, since its size has been changed.
     // We have to remove explicitly before updating m_decodedSize, so that we find the correct previous
@@ -525,9 +578,9 @@
         // violation of the invariant that the list is to be kept sorted
         // by access time. The weakening of the invariant does not pose
         // a problem. For more details please see: https://bugs.webkit.org/show_bug.cgi?id=30209
-        if (m_decodedSize && !m_inLiveDecodedResourcesList && hasClients())
+        if (m_decodedSize && !memoryCache()->isInLiveDecodedResourcesList(this) && hasClients())
             memoryCache()->insertInLiveDecodedResourcesList(this);
-        else if (!m_decodedSize && m_inLiveDecodedResourcesList)
+        else if (!m_decodedSize && memoryCache()->isInLiveDecodedResourcesList(this))
             memoryCache()->removeFromLiveDecodedResourcesList(this);
 
         // Update the cache's size totals.
@@ -535,12 +588,12 @@
     }
 }
 
-void Resource::setEncodedSize(unsigned size)
+void Resource::setEncodedSize(size_t size)
 {
     if (size == m_encodedSize)
         return;
 
-    int delta = size - m_encodedSize;
+    ptrdiff_t delta = size - m_encodedSize;
 
     // The object must now be moved to a different queue, since its size has been changed.
     // We have to remove explicitly before updating m_encodedSize, so that we find the correct previous
@@ -563,7 +616,7 @@
 {
     m_lastDecodedAccessTime = timeStamp;
     if (inCache()) {
-        if (m_inLiveDecodedResourcesList) {
+        if (memoryCache()->isInLiveDecodedResourcesList(this)) {
             memoryCache()->removeFromLiveDecodedResourcesList(this);
             memoryCache()->insertInLiveDecodedResourcesList(this);
         }
@@ -581,6 +634,12 @@
     }
 }
 
+void Resource::prune()
+{
+    destroyDecodedDataIfPossible();
+    unlock();
+}
+
 void Resource::setResourceToRevalidate(Resource* resource)
 {
     ASSERT(resource);
@@ -750,6 +809,20 @@
         deleteIfPossible();
 }
 
+bool Resource::canReuseRedirectChain() const
+{
+    for (size_t i = 0; i < m_redirectChain.size(); ++i) {
+        if (!canUseResponse(m_redirectChain[i].m_redirectResponse, m_responseTimestamp))
+            return false;
+    }
+    return true;
+}
+
+bool Resource::mustRevalidateDueToCacheHeaders() const
+{
+    return !canUseResponse(m_response, m_responseTimestamp);
+}
+
 bool Resource::canUseCacheValidator() const
 {
     if (m_loading || errorOccurred())
@@ -760,90 +833,34 @@
     return m_response.hasCacheValidatorFields();
 }
 
-bool Resource::mustRevalidateDueToCacheHeaders(CachePolicy cachePolicy) const
+bool Resource::isPurgeable() const
 {
-    ASSERT(cachePolicy == CachePolicyRevalidate || cachePolicy == CachePolicyCache || cachePolicy == CachePolicyVerify);
-
-    if (cachePolicy == CachePolicyRevalidate)
-        return true;
-
-    if (m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()) {
-        WTF_LOG(ResourceLoading, "Resource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
-        return true;
-    }
-
-    if (cachePolicy == CachePolicyCache) {
-        if (m_response.cacheControlContainsMustRevalidate() && isExpired()) {
-            WTF_LOG(ResourceLoading, "Resource %p mustRevalidate because of cachePolicy == CachePolicyCache and m_response.cacheControlContainsMustRevalidate() && isExpired()\n", this);
-            return true;
-        }
-        return false;
-    }
-
-    // CachePolicyVerify
-    if (isExpired()) {
-        WTF_LOG(ResourceLoading, "Resource %p mustRevalidate because of isExpired()\n", this);
-        return true;
-    }
-
-    return false;
+    return m_purgeableData && !m_purgeableData->isLocked();
 }
 
-bool Resource::isSafeToMakePurgeable() const
+bool Resource::wasPurged() const
 {
-    return !hasClients() && !m_proxyResource && !m_resourceToRevalidate;
+    return m_wasPurged;
 }
 
-bool Resource::makePurgeable(bool purgeable)
+bool Resource::lock()
 {
-    if (purgeable) {
-        ASSERT(isSafeToMakePurgeable());
-
-        if (m_purgeableData) {
-            ASSERT(!m_data);
-            return true;
-        }
-        if (!m_data)
-            return false;
-
-        // Should not make buffer purgeable if it has refs other than this since we don't want two copies.
-        if (!m_data->hasOneRef())
-            return false;
-
-        m_data->createPurgeableBuffer();
-        if (!m_data->hasPurgeableBuffer())
-            return false;
-
-        m_purgeableData = m_data->releasePurgeableBuffer();
-        m_purgeableData->unlock();
-        m_data.clear();
-        return true;
-    }
-
     if (!m_purgeableData)
         return true;
 
     ASSERT(!m_data);
     ASSERT(!hasClients());
 
-    if (!m_purgeableData->lock())
+    if (!m_purgeableData->lock()) {
+        m_wasPurged = true;
         return false;
+    }
 
     m_data = SharedBuffer::adoptPurgeableBuffer(m_purgeableData.release());
     return true;
 }
 
-bool Resource::isPurgeable() const
-{
-    return m_purgeableData && m_purgeableData->isPurgeable();
-}
-
-bool Resource::wasPurged() const
-{
-    return m_purgeableData && m_purgeableData->wasPurged();
-}
-
-unsigned Resource::overheadSize() const
+size_t Resource::overheadSize() const
 {
     static const int kAverageClientsHashMapSize = 384;
     return sizeof(Resource) + m_response.memoryUsage() + kAverageClientsHashMapSize + m_resourceRequest.url().string().length() * 2;
@@ -891,6 +908,64 @@
         resources[i]->finishPendingClients();
 }
 
+static const char* initatorTypeNameToString(const AtomicString& initiatorTypeName)
+{
+    if (initiatorTypeName == FetchInitiatorTypeNames::css)
+        return "CSS resource";
+    if (initiatorTypeName == FetchInitiatorTypeNames::document)
+        return "Document";
+    if (initiatorTypeName == FetchInitiatorTypeNames::icon)
+        return "Icon";
+    if (initiatorTypeName == FetchInitiatorTypeNames::internal)
+        return "Internal resource";
+    if (initiatorTypeName == FetchInitiatorTypeNames::link)
+        return "Link element resource";
+    if (initiatorTypeName == FetchInitiatorTypeNames::processinginstruction)
+        return "Processing instruction";
+    if (initiatorTypeName == FetchInitiatorTypeNames::texttrack)
+        return "Text track";
+    if (initiatorTypeName == FetchInitiatorTypeNames::xml)
+        return "XML resource";
+    if (initiatorTypeName == FetchInitiatorTypeNames::xmlhttprequest)
+        return "XMLHttpRequest";
+
+    return "Resource";
+}
+
+const char* Resource::resourceTypeToString(Type type, const FetchInitiatorInfo& initiatorInfo)
+{
+    switch (type) {
+    case Resource::MainResource:
+        return "Main resource";
+    case Resource::Image:
+        return "Image";
+    case Resource::CSSStyleSheet:
+        return "CSS stylesheet";
+    case Resource::Script:
+        return "Script";
+    case Resource::Font:
+        return "Font";
+    case Resource::Raw:
+        return initatorTypeNameToString(initiatorInfo.name);
+    case Resource::SVGDocument:
+        return "SVG document";
+    case Resource::XSLStyleSheet:
+        return "XSL stylesheet";
+    case Resource::LinkPrefetch:
+        return "Link prefetch resource";
+    case Resource::LinkSubresource:
+        return "Link subresource";
+    case Resource::TextTrack:
+        return "Text track";
+    case Resource::Shader:
+        return "Shader";
+    case Resource::ImportResource:
+        return "Imported resource";
+    }
+    ASSERT_NOT_REACHED();
+    return initatorTypeNameToString(initiatorInfo.name);
+}
+
 #if !LOG_DISABLED
 const char* ResourceTypeName(Resource::Type type)
 {
diff --git a/Source/core/fetch/Resource.h b/Source/core/fetch/Resource.h
index d5bbd7a..ed2a99a 100644
--- a/Source/core/fetch/Resource.h
+++ b/Source/core/fetch/Resource.h
@@ -23,7 +23,6 @@
 #ifndef Resource_h
 #define Resource_h
 
-#include "core/fetch/CachePolicy.h"
 #include "core/fetch/ResourceLoaderOptions.h"
 #include "platform/Timer.h"
 #include "platform/network/ResourceError.h"
@@ -37,6 +36,7 @@
 
 namespace WebCore {
 
+struct FetchInitiatorInfo;
 class MemoryCache;
 class CachedMetadata;
 class ResourceClient;
@@ -98,6 +98,8 @@
     virtual void appendData(const char*, int);
     virtual void error(Resource::Status);
 
+    void setNeedsSynchronousCacheHit(bool needsSynchronousCacheHit) { m_needsSynchronousCacheHit = needsSynchronousCacheHit; }
+
     void setResourceError(const ResourceError& error) { m_error = error; }
     const ResourceError& resourceError() const { return m_error; }
 
@@ -136,10 +138,10 @@
     Status status() const { return static_cast<Status>(m_status); }
     void setStatus(Status status) { m_status = status; }
 
-    unsigned size() const { return encodedSize() + decodedSize() + overheadSize(); }
-    unsigned encodedSize() const { return m_encodedSize; }
-    unsigned decodedSize() const { return m_decodedSize; }
-    unsigned overheadSize() const;
+    size_t size() const { return encodedSize() + decodedSize() + overheadSize(); }
+    size_t encodedSize() const { return m_encodedSize; }
+    size_t decodedSize() const { return m_decodedSize; }
+    size_t overheadSize() const;
 
     bool isLoaded() const { return !m_loading; } // FIXME. Method name is inaccurate. Loading might not have started yet.
 
@@ -178,14 +180,15 @@
 
     void setCacheLiveResourcePriority(CacheLiveResourcePriority);
     unsigned cacheLiveResourcePriority() const { return m_cacheLiveResourcePriority; }
-    bool inLiveDecodedResourcesList() { return m_inLiveDecodedResourcesList; }
 
     void clearLoader();
 
     SharedBuffer* resourceBuffer() const { ASSERT(!m_purgeableData); return m_data.get(); }
     void setResourceBuffer(PassRefPtr<SharedBuffer>);
 
-    virtual void willSendRequest(ResourceRequest&, const ResourceResponse&) { m_requestedFromNetworkingLayer = true; }
+    virtual void willSendRequest(ResourceRequest&, const ResourceResponse&);
+
+    virtual void updateRequest(const ResourceRequest&) { }
     virtual void responseReceived(const ResourceResponse&);
     void setResponse(const ResourceResponse& response) { m_response = response; }
     const ResourceResponse& response() const { return m_response; }
@@ -201,11 +204,9 @@
     // Returns cached metadata of the given type associated with this resource.
     CachedMetadata* cachedMetadata(unsigned dataTypeID) const;
 
-    bool canDelete() const { return !hasClients() && !m_loader && !m_preloadCount && !m_handleCount && !m_resourceToRevalidate && !m_proxyResource; }
+    bool canDelete() const { return !hasClients() && !m_loader && !m_preloadCount && !m_handleCount && !m_protectorCount && !m_resourceToRevalidate && !m_proxyResource; }
     bool hasOneHandle() const { return m_handleCount == 1; }
 
-    bool isExpired() const;
-
     // List of acceptable MIME types separated by ",".
     // A MIME type may contain a wildcard, e.g. "text/*".
     AtomicString accept() const { return m_accept; }
@@ -215,10 +216,8 @@
     bool errorOccurred() const { return m_status == LoadError || m_status == DecodeError; }
     bool loadFailedOrCanceled() { return !m_error.isNull(); }
 
-    bool shouldSendResourceLoadCallbacks() const { return m_options.sendLoadCallbacks == SendCallbacks; }
     DataBufferingPolicy dataBufferingPolicy() const { return m_options.dataBufferingPolicy; }
-
-    virtual void destroyDecodedData() { }
+    void setDataBufferingPolicy(DataBufferingPolicy);
 
     bool isPreloaded() const { return m_preloadCount; }
     void increasePreloadCount() { ++m_preloadCount; }
@@ -227,19 +226,16 @@
     void registerHandle(ResourcePtrBase* h);
     void unregisterHandle(ResourcePtrBase* h);
 
+    bool canReuseRedirectChain() const;
+    bool mustRevalidateDueToCacheHeaders() const;
     bool canUseCacheValidator() const;
-    bool mustRevalidateDueToCacheHeaders(CachePolicy) const;
     bool isCacheValidator() const { return m_resourceToRevalidate; }
     Resource* resourceToRevalidate() const { return m_resourceToRevalidate; }
     void setResourceToRevalidate(Resource*);
 
     bool isPurgeable() const;
     bool wasPurged() const;
-
-    // This is used by the archive machinery to get at a purged resource without
-    // triggering a load. We should make it protected again if we can find a
-    // better way to handle the archive case.
-    bool makePurgeable(bool purgeable);
+    bool lock();
 
     virtual void didSendData(unsigned long long /* bytesSent */, unsigned long long /* totalBytesToBeSent */) { }
     virtual void didDownloadData(int) { }
@@ -248,15 +244,43 @@
 
     virtual bool canReuse(const ResourceRequest&) const { return true; }
 
+    void prune();
+
+    static const char* resourceTypeToString(Type, const FetchInitiatorInfo&);
+
 protected:
     virtual void checkNotify();
     virtual void finishOnePart();
 
-    void setEncodedSize(unsigned);
-    void setDecodedSize(unsigned);
-    void didAccessDecodedData(double timeStamp);
+    // Normal resource pointers will silently switch what Resource* they reference when we
+    // successfully revalidated the resource. We need a way to guarantee that the Resource
+    // that received the 304 response survives long enough to switch everything over to the
+    // revalidatedresource. The normal mechanisms for keeping a Resource alive externally
+    // (ResourcePtrs and ResourceClients registering themselves) don't work in this case, so
+    // have a separate internal protector).
+    class InternalResourcePtr {
+    public:
+        explicit InternalResourcePtr(Resource* resource)
+            : m_resource(resource)
+        {
+            m_resource->incrementProtectorCount();
+        }
 
-    bool isSafeToMakePurgeable() const;
+        ~InternalResourcePtr()
+        {
+            m_resource->decrementProtectorCount();
+            m_resource->deleteIfPossible();
+        }
+    private:
+        Resource* m_resource;
+    };
+
+    void incrementProtectorCount() { m_protectorCount++; }
+    void decrementProtectorCount() { m_protectorCount--; }
+
+    void setEncodedSize(size_t);
+    void setDecodedSize(size_t);
+    void didAccessDecodedData(double timeStamp);
 
     virtual void switchClientsToRevalidatedResource();
     void clearResourceToRevalidate();
@@ -281,6 +305,22 @@
 
     bool hasClient(ResourceClient* client) { return m_clients.contains(client) || m_clientsAwaitingCallback.contains(client); }
 
+    struct RedirectPair {
+    public:
+        explicit RedirectPair(const ResourceRequest& request, const ResourceResponse& redirectResponse)
+            : m_request(request)
+            , m_redirectResponse(redirectResponse)
+        {
+        }
+
+        const ResourceRequest m_request;
+        const ResourceResponse m_redirectResponse;
+    };
+    const Vector<RedirectPair>& redirectChain() const { return m_redirectChain; }
+
+    virtual bool isSafeToUnlock() const { return false; }
+    virtual void destroyDecodedDataIfPossible() { }
+
     ResourceRequest m_resourceRequest;
     AtomicString m_accept;
     RefPtr<ResourceLoader> m_loader;
@@ -300,8 +340,7 @@
     void revalidationSucceeded(const ResourceResponse&);
     void revalidationFailed();
 
-    double currentAge() const;
-    double freshnessLifetime() const;
+    bool unlock();
 
     void failBeforeStarting();
 
@@ -316,15 +355,15 @@
 
     unsigned long m_identifier;
 
-    unsigned m_encodedSize;
-    unsigned m_decodedSize;
+    size_t m_encodedSize;
+    size_t m_decodedSize;
     unsigned m_accessCount;
     unsigned m_handleCount;
     unsigned m_preloadCount;
+    unsigned m_protectorCount;
 
     unsigned m_preloadResult : 2; // PreloadResult
     unsigned m_cacheLiveResourcePriority : 2; // CacheLiveResourcePriority
-    unsigned m_inLiveDecodedResourcesList : 1;
     unsigned m_requestedFromNetworkingLayer : 1;
 
     unsigned m_inCache : 1;
@@ -335,17 +374,14 @@
     unsigned m_type : 4; // Type
     unsigned m_status : 3; // Status
 
+    unsigned m_wasPurged : 1;
+
+    unsigned m_needsSynchronousCacheHit : 1;
+
 #ifndef NDEBUG
     bool m_deleted;
-    unsigned m_lruIndex;
 #endif
 
-    Resource* m_nextInAllResourcesList;
-    Resource* m_prevInAllResourcesList;
-
-    Resource* m_nextInLiveResourcesList;
-    Resource* m_prevInLiveResourcesList;
-
     // If this field is non-null we are using the resource as a proxy for checking whether an existing resource is still up to date
     // using HTTP If-Modified-Since/If-None-Match headers. If the response is 304 all clients of this resource are moved
     // to to be clients of m_resourceToRevalidate and the resource is deleted. If not, the field is zeroed and this
@@ -357,6 +393,9 @@
 
     // These handles will need to be updated to point to the m_resourceToRevalidate in case we get 304 response.
     HashSet<ResourcePtrBase*> m_handlesToRevalidate;
+
+    // Ordered list of all redirects followed while fetching this resource.
+    Vector<RedirectPair> m_redirectChain;
 };
 
 #if !LOG_DISABLED
diff --git a/Source/core/fetch/ResourceFetcher.cpp b/Source/core/fetch/ResourceFetcher.cpp
index 43fdecf..e41f648 100644
--- a/Source/core/fetch/ResourceFetcher.cpp
+++ b/Source/core/fetch/ResourceFetcher.cpp
@@ -31,6 +31,7 @@
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/Document.h"
 #include "core/fetch/CSSStyleSheetResource.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/DocumentResource.h"
 #include "core/fetch/FetchContext.h"
 #include "core/fetch/FontResource.h"
@@ -50,6 +51,7 @@
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/PingLoader.h"
+#include "core/loader/SubstituteData.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
 #include "core/frame/ContentSecurityPolicy.h"
@@ -57,7 +59,7 @@
 #include "core/frame/Frame.h"
 #include "core/timing/Performance.h"
 #include "core/timing/ResourceTimingInfo.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/Logging.h"
 #include "platform/TraceEvent.h"
 #include "platform/weborigin/SecurityOrigin.h"
@@ -157,23 +159,27 @@
     Resource* resource = createResource(Resource::Image, request, charset);
     resource->setOptions(resourceOptions);
     resource->responseReceived(response);
-    // FIXME: AppendData causes an unnecessary memcpy.
     if (data->size())
-        resource->appendData(data->data(), data->size());
+        resource->setResourceBuffer(data);
     resource->finish();
     return resource;
 }
 
-static void reportResourceTiming(ResourceTimingInfo* info, Resource* resource, double finishTime, Document* initiatorDocument, bool clearLoadTimings)
+static void populateResourceTiming(ResourceTimingInfo* info, Resource* resource, bool clearLoadTimings)
 {
-    if (resource->type() == Resource::MainResource)
-        initiatorDocument = initiatorDocument->parentDocument();
-    ASSERT(initiatorDocument);
     info->setInitialRequest(resource->resourceRequest());
     info->setFinalResponse(resource->response());
     if (clearLoadTimings)
         info->clearLoadTimings();
-    info->setLoadFinishTime(finishTime);
+    info->setLoadFinishTime(resource->loadFinishTime());
+}
+
+static void reportResourceTiming(ResourceTimingInfo* info, Document* initiatorDocument, bool isMainResource)
+{
+    if (initiatorDocument && isMainResource)
+        initiatorDocument = initiatorDocument->parentDocument();
+    if (!initiatorDocument || !initiatorDocument->loader())
+        return;
     if (DOMWindow* initiatorWindow = initiatorDocument->domWindow()) {
         if (Performance* performance = initiatorWindow->performance())
             performance->addResourceTiming(*info, initiatorDocument);
@@ -219,6 +225,7 @@
     , m_documentLoader(documentLoader)
     , m_requestCount(0)
     , m_garbageCollectDocumentResourcesTimer(this, &ResourceFetcher::garbageCollectDocumentResourcesTimerFired)
+    , m_resourceTimingReportTimer(this, &ResourceFetcher::resourceTimingReportTimerFired)
     , m_autoLoadImages(true)
     , m_imagesEnabled(true)
     , m_allowStaleResources(false)
@@ -236,12 +243,6 @@
     ASSERT(!m_requestCount);
 }
 
-Resource* ResourceFetcher::cachedResource(const String& resourceURL) const
-{
-    KURL url = m_document->completeURL(resourceURL);
-    return cachedResource(url);
-}
-
 Resource* ResourceFetcher::cachedResource(const KURL& resourceURL) const
 {
     KURL url = MemoryCache::removeFragmentIdentifierIfNeeded(resourceURL);
@@ -300,8 +301,10 @@
     if (memoryCache()->resourceForURL(url))
         return;
 
-    if (Resource* resource = resourceFromDataURIRequest(request.resourceRequest(), request.options()))
+    if (Resource* resource = resourceFromDataURIRequest(request.resourceRequest(), request.options())) {
         memoryCache()->add(resource);
+        scheduleDocumentResourcesGC();
+    }
 }
 
 ResourcePtr<FontResource> ResourceFetcher::fetchFont(FetchRequest& request)
@@ -334,7 +337,7 @@
         memoryCache()->remove(existing);
     }
 
-    request.setOptions(ResourceLoaderOptions(DoNotSendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, DocumentContext));
+    request.setOptions(ResourceLoaderOptions(SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, CheckContentSecurityPolicy, DocumentContext));
     return toCSSStyleSheetResource(requestResource(Resource::CSSStyleSheet, request));
 }
 
@@ -366,11 +369,31 @@
     return toRawResource(requestResource(Resource::Raw, request));
 }
 
-ResourcePtr<RawResource> ResourceFetcher::fetchMainResource(FetchRequest& request)
+ResourcePtr<RawResource> ResourceFetcher::fetchMainResource(FetchRequest& request, const SubstituteData& substituteData)
 {
+    if (substituteData.isValid())
+        preCacheSubstituteDataForMainResource(request, substituteData);
     return toRawResource(requestResource(Resource::MainResource, request));
 }
 
+void ResourceFetcher::preCacheSubstituteDataForMainResource(const FetchRequest& request, const SubstituteData& substituteData)
+{
+    const KURL& url = request.url();
+    if (Resource* oldResource = memoryCache()->resourceForURL(url))
+        memoryCache()->remove(oldResource);
+
+    ResourceResponse response(url, substituteData.mimeType(), substituteData.content()->size(), substituteData.textEncoding(), emptyString());
+    ResourcePtr<Resource> resource = createResource(Resource::MainResource, request.resourceRequest(), substituteData.textEncoding());
+    resource->setNeedsSynchronousCacheHit(substituteData.forceSynchronousLoad());
+    resource->setOptions(request.options());
+    resource->setDataBufferingPolicy(BufferData);
+    resource->responseReceived(response);
+    if (substituteData.content()->size())
+        resource->setResourceBuffer(substituteData.content());
+    resource->finish();
+    memoryCache()->add(resource.get());
+}
+
 bool ResourceFetcher::checkInsecureContent(Resource::Type type, const KURL& url, MixedContentBlockingTreatment treatment) const
 {
     if (treatment == TreatAsDefaultForType) {
@@ -423,7 +446,7 @@
     return true;
 }
 
-bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload, FetchRequest::OriginRestriction originRestriction)
+bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload, FetchRequest::OriginRestriction originRestriction) const
 {
     SecurityOrigin* securityOrigin = options.securityOrigin.get();
     if (!securityOrigin && document())
@@ -484,7 +507,7 @@
 
         if (frame()) {
             Settings* settings = frame()->settings();
-            if (!frame()->loader().client()->allowScriptFromSource(!settings || settings->isScriptEnabled(), url)) {
+            if (!frame()->loader().client()->allowScriptFromSource(!settings || settings->scriptEnabled(), url)) {
                 frame()->loader().client()->didNotAllowScript();
                 return false;
             }
@@ -528,42 +551,38 @@
     return true;
 }
 
-bool ResourceFetcher::canAccess(Resource* resource, CORSEnabled corsEnabled, FetchRequest::OriginRestriction originRestriction)
+bool ResourceFetcher::canAccessResource(Resource* resource, SecurityOrigin* sourceOrigin, const KURL& url) const
 {
     // Redirects can change the response URL different from one of request.
-    if (!canRequest(resource->type(), resource->response().url(), resource->options(), false, originRestriction))
+    if (!canRequest(resource->type(), url, resource->options(), false, FetchRequest::UseDefaultOriginRestrictionForType))
         return false;
 
-    String error;
-    switch (resource->type()) {
-    case Resource::Script:
-    case Resource::ImportResource:
-        if (corsEnabled == PotentiallyCORSEnabled
-            && !m_document->securityOrigin()->canRequest(resource->response().url())
-            && !resource->passesAccessControlCheck(m_document->securityOrigin(), error)) {
-            if (frame() && frame()->document())
-                frame()->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Script from origin '" + SecurityOrigin::create(resource->response().url())->toString() + "' has been blocked from loading by Cross-Origin Resource Sharing policy: " + error);
-            return false;
-        }
+    if (!sourceOrigin && document())
+        sourceOrigin = document()->securityOrigin();
 
-        break;
-    default:
-        ASSERT_NOT_REACHED(); // FIXME: generalize to non-script resources
+    if (sourceOrigin->canRequest(url))
+        return true;
+
+    String errorDescription;
+    if (!resource->passesAccessControlCheck(sourceOrigin, errorDescription)) {
+        if (frame() && frame()->document()) {
+            String resourceType = Resource::resourceTypeToString(resource->type(), resource->options().initiatorInfo);
+            frame()->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, resourceType + " from origin '" + SecurityOrigin::create(url)->toString() + "' has been blocked from loading by Cross-Origin Resource Sharing policy: " + errorDescription);
+        }
         return false;
     }
-
     return true;
 }
 
-bool ResourceFetcher::shouldLoadNewResource() const
+bool ResourceFetcher::shouldLoadNewResource(Resource::Type type) const
 {
     if (!frame())
         return false;
     if (!m_documentLoader)
         return true;
-    if (m_documentLoader == frame()->loader().activeDocumentLoader())
-        return true;
-    return document() && document()->pageDismissalEventBeingDispatched() != Document::NoDismissal;
+    if (type == Resource::MainResource)
+        return m_documentLoader == frame()->loader().provisionalDocumentLoader();
+    return m_documentLoader == frame()->loader().documentLoader();
 }
 
 bool ResourceFetcher::resourceNeedsLoad(Resource* resource, const FetchRequest& request, RevalidationPolicy policy)
@@ -600,7 +619,7 @@
     // See if we can use an existing resource from the cache.
     ResourcePtr<Resource> resource = memoryCache()->resourceForURL(url);
 
-    const RevalidationPolicy policy = determineRevalidationPolicy(type, request.mutableResourceRequest(), request.forPreload(), resource.get(), request.defer());
+    const RevalidationPolicy policy = determineRevalidationPolicy(type, request.mutableResourceRequest(), request.forPreload(), resource.get(), request.defer(), request.options());
     switch (policy) {
     case Reload:
         memoryCache()->remove(resource.get());
@@ -620,6 +639,9 @@
     if (!resource)
         return 0;
 
+    if (!resource->hasClients())
+        m_deadStatsRecorder.update(policy);
+
     if (policy != Use)
         resource->setIdentifier(createUniqueIdentifier());
 
@@ -632,7 +654,7 @@
     }
 
     if (resourceNeedsLoad(resource.get(), request, policy)) {
-        if (!shouldLoadNewResource()) {
+        if (!shouldLoadNewResource(type)) {
             if (resource->inCache())
                 memoryCache()->remove(resource.get());
             return 0;
@@ -662,18 +684,21 @@
     // Ensure main resources aren't preloaded, and other main resource loads
     // are removed from cache to prevent reuse.
     if (type == Resource::MainResource) {
-        ASSERT(policy != Use);
+        ASSERT(policy != Use || m_documentLoader->substituteData().isValid());
         ASSERT(policy != Revalidate);
         memoryCache()->remove(resource.get());
         if (request.forPreload())
             return 0;
     }
 
-    if (!request.resourceRequest().url().protocolIsData()) {
+    if (!request.resourceRequest().url().protocolIsData() && (!m_documentLoader || !m_documentLoader->substituteData().isValid())) {
         if (policy == Use && !m_validatedURLs.contains(request.resourceRequest().url())) {
             // Resources loaded from memory cache should be reported the first time they're used.
             RefPtr<ResourceTimingInfo> info = ResourceTimingInfo::create(request.options().initiatorInfo.name, monotonicallyIncreasingTime());
-            reportResourceTiming(info.get(), resource.get(), monotonicallyIncreasingTime(), document(), true);
+            populateResourceTiming(info.get(), resource.get(), true);
+            m_scheduledResourceTimingReports.add(info, resource->type() == Resource::MainResource);
+            if (!m_resourceTimingReportTimer.isActive())
+                m_resourceTimingReportTimer.startOneShot(0);
         }
 
         m_validatedURLs.add(request.resourceRequest().url());
@@ -684,6 +709,19 @@
     return resource;
 }
 
+void ResourceFetcher::resourceTimingReportTimerFired(Timer<ResourceFetcher>* timer)
+{
+    ASSERT_UNUSED(timer, timer == &m_resourceTimingReportTimer);
+    HashMap<RefPtr<ResourceTimingInfo>, bool> timingReports;
+    timingReports.swap(m_scheduledResourceTimingReports);
+    HashMap<RefPtr<ResourceTimingInfo>, bool>::iterator end = timingReports.end();
+    for (HashMap<RefPtr<ResourceTimingInfo>, bool>::iterator it = timingReports.begin(); it != end; ++it) {
+        RefPtr<ResourceTimingInfo> info = it->key;
+        bool isMainResource = it->value;
+        reportResourceTiming(info.get(), document(), isMainResource);
+    }
+}
+
 void ResourceFetcher::determineTargetType(ResourceRequest& request, Resource::Type type)
 {
     ResourceRequest::TargetType targetType = requestTargetType(this, request, type);
@@ -732,7 +770,7 @@
     if (type == Resource::LinkPrefetch || type == Resource::LinkSubresource)
         request.setHTTPHeaderField("Purpose", "prefetch");
 
-    context().addAdditionalRequestHeaders(*document(), request, type);
+    context().addAdditionalRequestHeaders(document(), request, (type == Resource::MainResource) ? FetchMainResource : FetchSubresource);
 }
 
 ResourcePtr<Resource> ResourceFetcher::revalidateResource(const FetchRequest& request, Resource* resource)
@@ -749,8 +787,8 @@
     const AtomicString& lastModified = resource->response().httpHeaderField("Last-Modified");
     const AtomicString& eTag = resource->response().httpHeaderField("ETag");
     if (!lastModified.isEmpty() || !eTag.isEmpty()) {
-        ASSERT(context().cachePolicy(resource->type()) != CachePolicyReload);
-        if (context().cachePolicy(resource->type()) == CachePolicyRevalidate)
+        ASSERT(context().cachePolicy(document()) != CachePolicyReload);
+        if (context().cachePolicy(document()) == CachePolicyRevalidate)
             revalidatingRequest.setHTTPHeaderField("Cache-Control", "max-age=0");
         if (!lastModified.isEmpty())
             revalidatingRequest.setHTTPHeaderField("If-Modified-Since", lastModified);
@@ -804,7 +842,7 @@
     }
 }
 
-ResourceFetcher::RevalidationPolicy ResourceFetcher::determineRevalidationPolicy(Resource::Type type, ResourceRequest& request, bool forPreload, Resource* existingResource, FetchRequest::DeferOption defer) const
+ResourceFetcher::RevalidationPolicy ResourceFetcher::determineRevalidationPolicy(Resource::Type type, ResourceRequest& request, bool forPreload, Resource* existingResource, FetchRequest::DeferOption defer, const ResourceLoaderOptions& options) const
 {
     if (!existingResource)
         return Load;
@@ -829,9 +867,17 @@
     if (type == Resource::Image && request.url().protocolIsData())
         return Use;
 
+    // If a main resource was populated from a SubstituteData load, use it.
+    if (type == Resource::MainResource && m_documentLoader->substituteData().isValid())
+        return Use;
+
     if (!existingResource->canReuse(request))
         return Reload;
 
+    // Never use cache entries for downloadToFile requests. The caller expects the resource in a file.
+    if (request.downloadToFile())
+        return Reload;
+
     // Certain requests (e.g., XHRs) might have manually set headers that require revalidation.
     // FIXME: In theory, this should be a Revalidate case. In practice, the MemoryCache revalidation path assumes a whole bunch
     // of things about how revalidation works that manual headers violate, so punt to Reload instead.
@@ -842,12 +888,13 @@
     if (m_allowStaleResources)
         return Use;
 
-    // Alwaus use preloads.
+    // Always use preloads.
     if (existingResource->isPreloaded())
         return Use;
 
     // CachePolicyHistoryBuffer uses the cache no matter what.
-    if (context().cachePolicy(type) == CachePolicyHistoryBuffer)
+    CachePolicy cachePolicy = context().cachePolicy(document());
+    if (cachePolicy == CachePolicyHistoryBuffer)
         return Use;
 
     // Don't reuse resources with Cache-control: no-store.
@@ -856,6 +903,10 @@
         return Reload;
     }
 
+    // If fetching a resource with a different 'CORS enabled' flag, reload.
+    if (type != Resource::MainResource && options.corsEnabled != existingResource->options().corsEnabled)
+        return Reload;
+
     // If credentials were sent with the previous request and won't be
     // with this one, or vice versa, re-fetch the resource.
     //
@@ -873,7 +924,7 @@
         return Use;
 
     // CachePolicyReload always reloads
-    if (context().cachePolicy(type) == CachePolicyReload) {
+    if (cachePolicy == CachePolicyReload) {
         WTF_LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to CachePolicyReload.");
         return Reload;
     }
@@ -888,8 +939,14 @@
     if (existingResource->isLoading())
         return Use;
 
+    // If any of the redirects in the chain to loading the resource were not cacheable, we cannot reuse our cached resource.
+    if (!existingResource->canReuseRedirectChain()) {
+        WTF_LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to an uncacheable redirect");
+        return Reload;
+    }
+
     // Check if the cache headers requires us to revalidate (cache expiration for example).
-    if (existingResource->mustRevalidateDueToCacheHeaders(context().cachePolicy(type))) {
+    if (cachePolicy == CachePolicyRevalidate || existingResource->mustRevalidateDueToCacheHeaders()) {
         // See if the resource has usable ETag or Last-modified headers.
         if (existingResource->canUseCacheValidator())
             return Revalidate;
@@ -982,14 +1039,18 @@
         if (it != m_resourceTimingInfoMap.end()) {
             RefPtr<ResourceTimingInfo> info = it->value;
             m_resourceTimingInfoMap.remove(it);
-            reportResourceTiming(info.get(), resource, resource->loadFinishTime(), document(), false);
+            populateResourceTiming(info.get(), resource, false);
+            reportResourceTiming(info.get(), document(), resource->type() == Resource::MainResource);
         }
     }
 
     if (frame())
         frame()->loader().loadDone();
-    performPostLoadActions();
+    scheduleDocumentResourcesGC();
+}
 
+void ResourceFetcher::scheduleDocumentResourcesGC()
+{
     if (!m_garbageCollectDocumentResourcesTimer.isActive())
         m_garbageCollectDocumentResourcesTimer.startOneShot(0);
 }
@@ -1020,23 +1081,16 @@
         m_documentResources.remove(*it);
 }
 
-void ResourceFetcher::performPostLoadActions()
-{
-    checkForPendingPreloads();
-}
-
 void ResourceFetcher::notifyLoadedFromMemoryCache(Resource* resource)
 {
     if (!frame() || !frame()->page() || resource->status() != Resource::Cached || m_validatedURLs.contains(resource->url()))
         return;
-    if (!resource->shouldSendResourceLoadCallbacks())
-        return;
 
     ResourceRequest request(resource->url());
     unsigned long identifier = createUniqueIdentifier();
     context().dispatchDidLoadResourceFromMemoryCache(request, resource->response());
     // FIXME: If willSendRequest changes the request, we don't respect it.
-    willSendRequest(identifier, request, ResourceResponse(), resource->options());
+    willSendRequest(identifier, request, ResourceResponse(), resource->options().initiatorInfo);
     InspectorInstrumentation::markResourceAsCached(frame()->page(), identifier);
     context().sendRemainingDelegateMessages(m_documentLoader, identifier, resource->response(), resource->encodedSize());
 }
@@ -1063,20 +1117,6 @@
     requestPreload(type, request, charset);
 }
 
-void ResourceFetcher::checkForPendingPreloads()
-{
-    // FIXME: It seems wrong to poke body()->renderer() here.
-    if (m_pendingPreloads.isEmpty() || !m_document->body() || !m_document->body()->renderer())
-        return;
-    while (!m_pendingPreloads.isEmpty()) {
-        PendingPreload preload = m_pendingPreloads.takeFirst();
-        // Don't request preload if the resource already loaded normally (this will result in double load if the page is being reloaded with cached results ignored).
-        if (!cachedResource(preload.m_request.resourceRequest().url()))
-            requestPreload(preload.m_type, preload.m_request, preload.m_charset);
-    }
-    m_pendingPreloads.clear();
-}
-
 void ResourceFetcher::requestPreload(Resource::Type type, FetchRequest& request, const String& charset)
 {
     String encoding;
@@ -1097,7 +1137,7 @@
     m_preloads->add(resource.get());
 
 #if PRELOAD_DEBUG
-    printf("PRELOADING %s\n",  resource->url().latin1().data());
+    printf("PRELOADING %s\n",  resource->url().string().latin1().data());
 #endif
 }
 
@@ -1114,12 +1154,6 @@
         }
     }
 
-    Deque<PendingPreload>::const_iterator dequeEnd = m_pendingPreloads.end();
-    for (Deque<PendingPreload>::const_iterator it = m_pendingPreloads.begin(); it != dequeEnd; ++it) {
-        PendingPreload pendingPreload = *it;
-        if (pendingPreload.m_request.resourceRequest().url() == url)
-            return true;
-    }
     return false;
 }
 
@@ -1142,17 +1176,10 @@
     m_preloads.clear();
 }
 
-void ResourceFetcher::clearPendingPreloads()
-{
-    m_pendingPreloads.clear();
-}
-
-void ResourceFetcher::didFinishLoading(const Resource* resource, double finishTime, const ResourceLoaderOptions& options)
+void ResourceFetcher::didFinishLoading(const Resource* resource, double finishTime, int64_t encodedDataLength)
 {
     TRACE_EVENT_ASYNC_END0("net", "Resource", resource);
-    if (options.sendLoadCallbacks != SendCallbacks)
-        return;
-    context().dispatchDidFinishLoading(m_documentLoader, resource->identifier(), finishTime);
+    context().dispatchDidFinishLoading(m_documentLoader, resource->identifier(), finishTime, encodedDataLength);
 }
 
 void ResourceFetcher::didChangeLoadingPriority(const Resource* resource, ResourceLoadPriority loadPriority)
@@ -1161,44 +1188,33 @@
     context().dispatchDidChangeResourcePriority(resource->identifier(), loadPriority);
 }
 
-void ResourceFetcher::didFailLoading(const Resource* resource, const ResourceError& error, const ResourceLoaderOptions& options)
+void ResourceFetcher::didFailLoading(const Resource* resource, const ResourceError& error)
 {
     TRACE_EVENT_ASYNC_END0("net", "Resource", resource);
-    if (options.sendLoadCallbacks != SendCallbacks)
-        return;
     context().dispatchDidFail(m_documentLoader, resource->identifier(), error);
 }
 
-void ResourceFetcher::willSendRequest(unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse, const ResourceLoaderOptions& options)
+void ResourceFetcher::willSendRequest(unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& initiatorInfo)
 {
-    if (options.sendLoadCallbacks == SendCallbacks)
-        context().dispatchWillSendRequest(m_documentLoader, identifier, request, redirectResponse, options.initiatorInfo);
-    else
-        InspectorInstrumentation::willSendRequest(frame(), identifier, m_documentLoader, request, redirectResponse, options.initiatorInfo);
+    context().dispatchWillSendRequest(m_documentLoader, identifier, request, redirectResponse, initiatorInfo);
 }
 
-void ResourceFetcher::didReceiveResponse(const Resource* resource, const ResourceResponse& response, const ResourceLoaderOptions& options)
+void ResourceFetcher::didReceiveResponse(const Resource* resource, const ResourceResponse& response)
 {
-    if (options.sendLoadCallbacks != SendCallbacks)
-        return;
     context().dispatchDidReceiveResponse(m_documentLoader, resource->identifier(), response, resource->loader());
 }
 
-void ResourceFetcher::didReceiveData(const Resource* resource, const char* data, int dataLength, int encodedDataLength, const ResourceLoaderOptions& options)
+void ResourceFetcher::didReceiveData(const Resource* resource, const char* data, int dataLength, int encodedDataLength)
 {
     // FIXME: use frame of master document for imported documents.
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceData(frame(), resource->identifier(), encodedDataLength);
-    if (options.sendLoadCallbacks != SendCallbacks)
-        return;
     context().dispatchDidReceiveData(m_documentLoader, resource->identifier(), data, dataLength, encodedDataLength);
     InspectorInstrumentation::didReceiveResourceData(cookie);
 }
 
-void ResourceFetcher::didDownloadData(const Resource* resource, int dataLength, int encodedDataLength, const ResourceLoaderOptions& options)
+void ResourceFetcher::didDownloadData(const Resource* resource, int dataLength, int encodedDataLength)
 {
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceData(frame(), resource->identifier(), encodedDataLength);
-    if (options.sendLoadCallbacks != SendCallbacks)
-        return;
     context().dispatchDidDownloadData(m_documentLoader, resource->identifier(), dataLength, encodedDataLength);
     InspectorInstrumentation::didReceiveResourceData(cookie);
 }
@@ -1269,10 +1285,22 @@
     return this == possibleOwner;
 }
 
-bool ResourceFetcher::shouldRequest(Resource* resource, const ResourceRequest& request, const ResourceLoaderOptions& options)
+bool ResourceFetcher::canAccessRedirect(Resource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse, ResourceLoaderOptions& options)
 {
     if (!canRequest(resource->type(), request.url(), options, false, FetchRequest::UseDefaultOriginRestrictionForType))
         return false;
+    if (options.corsEnabled == IsCORSEnabled) {
+        SecurityOrigin* sourceOrigin = options.securityOrigin.get();
+        if (!sourceOrigin && document())
+            sourceOrigin = document()->securityOrigin();
+
+        String errorMessage;
+        if (!CrossOriginAccessControl::handleRedirect(resource, sourceOrigin, request, redirectResponse, options, errorMessage)) {
+            if (frame() && frame()->document())
+                frame()->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, errorMessage);
+            return false;
+        }
+    }
     if (resource->type() == Resource::Image && shouldDeferImageLoad(request.url()))
         return false;
     return true;
@@ -1291,21 +1319,24 @@
 #if PRELOAD_DEBUG
 void ResourceFetcher::printPreloadStats()
 {
+    if (!m_preloads)
+        return;
+
     unsigned scripts = 0;
     unsigned scriptMisses = 0;
     unsigned stylesheets = 0;
     unsigned stylesheetMisses = 0;
     unsigned images = 0;
     unsigned imageMisses = 0;
-    ListHashSet<Resource*>::iterator end = m_preloads.end();
-    for (ListHashSet<Resource*>::iterator it = m_preloads.begin(); it != end; ++it) {
+    ListHashSet<Resource*>::iterator end = m_preloads->end();
+    for (ListHashSet<Resource*>::iterator it = m_preloads->begin(); it != end; ++it) {
         Resource* res = *it;
         if (res->preloadResult() == Resource::PreloadNotReferenced)
-            printf("!! UNREFERENCED PRELOAD %s\n", res->url().latin1().data());
+            printf("!! UNREFERENCED PRELOAD %s\n", res->url().string().latin1().data());
         else if (res->preloadResult() == Resource::PreloadReferencedWhileComplete)
-            printf("HIT COMPLETE PRELOAD %s\n", res->url().latin1().data());
+            printf("HIT COMPLETE PRELOAD %s\n", res->url().string().latin1().data());
         else if (res->preloadResult() == Resource::PreloadReferencedWhileLoading)
-            printf("HIT LOADING PRELOAD %s\n", res->url().latin1().data());
+            printf("HIT LOADING PRELOAD %s\n", res->url().string().latin1().data());
 
         if (res->type() == Resource::Script) {
             scripts++;
@@ -1339,8 +1370,41 @@
 
 const ResourceLoaderOptions& ResourceFetcher::defaultResourceOptions()
 {
-    DEFINE_STATIC_LOCAL(ResourceLoaderOptions, options, (SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, DoSecurityCheck, CheckContentSecurityPolicy, DocumentContext));
+    DEFINE_STATIC_LOCAL(ResourceLoaderOptions, options, (SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, CheckContentSecurityPolicy, DocumentContext));
     return options;
 }
 
+ResourceFetcher::DeadResourceStatsRecorder::DeadResourceStatsRecorder()
+    : m_useCount(0)
+    , m_revalidateCount(0)
+    , m_loadCount(0)
+{
+}
+
+ResourceFetcher::DeadResourceStatsRecorder::~DeadResourceStatsRecorder()
+{
+    blink::Platform::current()->histogramCustomCounts(
+        "WebCore.ResourceFetcher.HitCount", m_useCount, 0, 1000, 50);
+    blink::Platform::current()->histogramCustomCounts(
+        "WebCore.ResourceFetcher.RevalidateCount", m_revalidateCount, 0, 1000, 50);
+    blink::Platform::current()->histogramCustomCounts(
+        "WebCore.ResourceFetcher.LoadCount", m_loadCount, 0, 1000, 50);
+}
+
+void ResourceFetcher::DeadResourceStatsRecorder::update(RevalidationPolicy policy)
+{
+    switch (policy) {
+    case Reload:
+    case Load:
+        ++m_loadCount;
+        return;
+    case Revalidate:
+        ++m_revalidateCount;
+        return;
+    case Use:
+        ++m_useCount;
+        return;
+    }
+}
+
 }
diff --git a/Source/core/fetch/ResourceFetcher.h b/Source/core/fetch/ResourceFetcher.h
index 318e6ff..0a65fe8 100644
--- a/Source/core/fetch/ResourceFetcher.h
+++ b/Source/core/fetch/ResourceFetcher.h
@@ -50,6 +50,7 @@
 class RawResource;
 class ScriptResource;
 class ShaderResource;
+class SubstituteData;
 class XSLStyleSheetResource;
 class Document;
 class DocumentLoader;
@@ -60,11 +61,6 @@
 class ResourceTimingInfo;
 class ResourceLoaderSet;
 
-enum CORSEnabled {
-    NotCORSEnabled,
-    PotentiallyCORSEnabled // Indicates "potentially CORS-enabled fetch" in HTML standard.
-};
-
 // The ResourceFetcher provides a per-context interface to the MemoryCache
 // and enforces a bunch of security checks and rules for resource revalidation.
 // Its lifetime is roughly per-DocumentLoader, in that it is generally created
@@ -73,7 +69,7 @@
 // RefPtr<ResourceFetcher> for their lifetime (and will create one if they
 // are initialized without a Frame), so a Document can keep a ResourceFetcher
 // alive past detach if scripts still reference the Document.
-class ResourceFetcher : public RefCounted<ResourceFetcher>, public ResourceLoaderHost {
+class ResourceFetcher FINAL : public RefCounted<ResourceFetcher>, public ResourceLoaderHost {
     WTF_MAKE_NONCOPYABLE(ResourceFetcher); WTF_MAKE_FAST_ALLOCATED;
 friend class ImageLoader;
 friend class ResourceCacheValidationSuppressor;
@@ -92,7 +88,7 @@
     ResourcePtr<ScriptResource> fetchScript(FetchRequest&);
     ResourcePtr<FontResource> fetchFont(FetchRequest&);
     ResourcePtr<RawResource> fetchRawResource(FetchRequest&);
-    ResourcePtr<RawResource> fetchMainResource(FetchRequest&);
+    ResourcePtr<RawResource> fetchMainResource(FetchRequest&, const SubstituteData&);
     ResourcePtr<DocumentResource> fetchSVGDocument(FetchRequest&);
     ResourcePtr<XSLStyleSheetResource> fetchXSLStyleSheet(FetchRequest&);
     ResourcePtr<Resource> fetchLinkResource(Resource::Type, FetchRequest&);
@@ -102,7 +98,6 @@
     // Logs an access denied message to the console for the specified URL.
     void printAccessDeniedMessage(const KURL&) const;
 
-    Resource* cachedResource(const String& url) const;
     Resource* cachedResource(const KURL&) const;
 
     typedef HashMap<String, ResourcePtr<Resource> > DocumentResourceMap;
@@ -129,11 +124,8 @@
 
     bool isPreloaded(const String& urlString) const;
     void clearPreloads();
-    void clearPendingPreloads();
     void preload(Resource::Type, FetchRequest&, const String& charset);
-    void checkForPendingPreloads();
     void printPreloadStats();
-    bool canAccess(Resource*, CORSEnabled, FetchRequest::OriginRestriction = FetchRequest::UseDefaultOriginRestrictionForType);
 
     void setDefersLoading(bool);
     void stopFetching();
@@ -144,20 +136,22 @@
     virtual void decrementRequestCount(const Resource*) OVERRIDE;
     virtual void didLoadResource(Resource*) OVERRIDE;
     virtual void redirectReceived(Resource*, const ResourceResponse&) OVERRIDE;
-    virtual void didFinishLoading(const Resource*, double finishTime, const ResourceLoaderOptions&) OVERRIDE;
+    virtual void didFinishLoading(const Resource*, double finishTime, int64_t encodedDataLength) OVERRIDE;
     virtual void didChangeLoadingPriority(const Resource*, ResourceLoadPriority) OVERRIDE;
-    virtual void didFailLoading(const Resource*, const ResourceError&, const ResourceLoaderOptions&) OVERRIDE;
-    virtual void willSendRequest(unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const ResourceLoaderOptions&) OVERRIDE;
-    virtual void didReceiveResponse(const Resource*, const ResourceResponse&, const ResourceLoaderOptions&) OVERRIDE;
-    virtual void didReceiveData(const Resource*, const char* data, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) OVERRIDE;
-    virtual void didDownloadData(const Resource*, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) OVERRIDE;
+    virtual void didFailLoading(const Resource*, const ResourceError&) OVERRIDE;
+    virtual void willSendRequest(unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo&) OVERRIDE;
+    virtual void didReceiveResponse(const Resource*, const ResourceResponse&) OVERRIDE;
+    virtual void didReceiveData(const Resource*, const char* data, int dataLength, int encodedDataLength) OVERRIDE;
+    virtual void didDownloadData(const Resource*, int dataLength, int encodedDataLength) OVERRIDE;
     virtual void subresourceLoaderFinishedLoadingOnePart(ResourceLoader*) OVERRIDE;
     virtual void didInitializeResourceLoader(ResourceLoader*) OVERRIDE;
     virtual void willTerminateResourceLoader(ResourceLoader*) OVERRIDE;
     virtual void willStartLoadingResource(ResourceRequest&) OVERRIDE;
     virtual bool defersLoading() const OVERRIDE;
     virtual bool isLoadedBy(ResourceLoaderHost*) const OVERRIDE;
-    virtual bool shouldRequest(Resource*, const ResourceRequest&, const ResourceLoaderOptions&) OVERRIDE;
+    virtual bool canAccessRedirect(Resource*, ResourceRequest&, const ResourceResponse&, ResourceLoaderOptions&) OVERRIDE;
+    virtual bool canAccessResource(Resource*, SecurityOrigin*, const KURL&) const OVERRIDE;
+
     virtual void refResourceLoaderHost() OVERRIDE;
     virtual void derefResourceLoaderHost() OVERRIDE;
 
@@ -166,23 +160,24 @@
 
     explicit ResourceFetcher(DocumentLoader*);
 
-    bool shouldLoadNewResource() const;
+    bool shouldLoadNewResource(Resource::Type) const;
 
     ResourcePtr<Resource> requestResource(Resource::Type, FetchRequest&);
     ResourcePtr<Resource> revalidateResource(const FetchRequest&, Resource*);
     ResourcePtr<Resource> loadResource(Resource::Type, FetchRequest&, const String& charset);
     void preCacheDataURIImage(const FetchRequest&);
+    void preCacheSubstituteDataForMainResource(const FetchRequest&, const SubstituteData&);
     void storeResourceTimingInitiatorInformation(const ResourcePtr<Resource>&, const FetchRequest&);
     void requestPreload(Resource::Type, FetchRequest&, const String& charset);
 
     enum RevalidationPolicy { Use, Revalidate, Reload, Load };
-    RevalidationPolicy determineRevalidationPolicy(Resource::Type, ResourceRequest&, bool forPreload, Resource* existingResource, FetchRequest::DeferOption) const;
+    RevalidationPolicy determineRevalidationPolicy(Resource::Type, ResourceRequest&, bool forPreload, Resource* existingResource, FetchRequest::DeferOption, const ResourceLoaderOptions&) const;
 
     void determineTargetType(ResourceRequest&, Resource::Type);
     ResourceRequestCachePolicy resourceRequestCachePolicy(const ResourceRequest&, Resource::Type);
     void addAdditionalRequestHeaders(ResourceRequest&, Resource::Type);
 
-    bool canRequest(Resource::Type, const KURL&, const ResourceLoaderOptions&, bool forPreload, FetchRequest::OriginRestriction);
+    bool canRequest(Resource::Type, const KURL&, const ResourceLoaderOptions&, bool forPreload, FetchRequest::OriginRestriction) const;
     bool checkInsecureContent(Resource::Type, const KURL&, MixedContentBlockingTreatment) const;
 
     static bool resourceNeedsLoad(Resource*, const FetchRequest&, RevalidationPolicy);
@@ -190,7 +185,9 @@
     void notifyLoadedFromMemoryCache(Resource*);
 
     void garbageCollectDocumentResourcesTimerFired(Timer<ResourceFetcher>*);
-    void performPostLoadActions();
+    void scheduleDocumentResourcesGC();
+
+    void resourceTimingReportTimerFired(Timer<ResourceFetcher>*);
 
     bool clientDefersImage(const KURL&) const;
     void reloadImagesIfNotDeferred();
@@ -203,21 +200,33 @@
     int m_requestCount;
 
     OwnPtr<ListHashSet<Resource*> > m_preloads;
-    struct PendingPreload {
-        Resource::Type m_type;
-        FetchRequest m_request;
-        String m_charset;
-    };
-    Deque<PendingPreload> m_pendingPreloads;
 
     Timer<ResourceFetcher> m_garbageCollectDocumentResourcesTimer;
+    Timer<ResourceFetcher> m_resourceTimingReportTimer;
 
     typedef HashMap<Resource*, RefPtr<ResourceTimingInfo> > ResourceTimingInfoMap;
     ResourceTimingInfoMap m_resourceTimingInfoMap;
 
+    HashMap<RefPtr<ResourceTimingInfo>, bool> m_scheduledResourceTimingReports;
+
     OwnPtr<ResourceLoaderSet> m_loaders;
     OwnPtr<ResourceLoaderSet> m_multipartLoaders;
 
+    // Used in hit rate histograms.
+    class DeadResourceStatsRecorder {
+    public:
+        DeadResourceStatsRecorder();
+        ~DeadResourceStatsRecorder();
+
+        void update(RevalidationPolicy);
+
+    private:
+        int m_useCount;
+        int m_revalidateCount;
+        int m_loadCount;
+    };
+    DeadResourceStatsRecorder m_deadStatsRecorder;
+
     // 29 bits left
     bool m_autoLoadImages : 1;
     bool m_imagesEnabled : 1;
diff --git a/Source/core/fetch/ResourceFetcherTest.cpp b/Source/core/fetch/ResourceFetcherTest.cpp
index adc8b4b..e2a99ed 100644
--- a/Source/core/fetch/ResourceFetcherTest.cpp
+++ b/Source/core/fetch/ResourceFetcherTest.cpp
@@ -51,7 +51,7 @@
     // Create a ResourceFetcher that has a real DocumentLoader and Document, but is not attached to a Frame.
     // Technically, we're concerned about what happens after a Frame is detached (rather than before
     // any attach occurs), but ResourceFetcher can't tell the difference.
-    RefPtr<DocumentLoader> documentLoader = DocumentLoader::create(ResourceRequest(testURL), SubstituteData());
+    RefPtr<DocumentLoader> documentLoader = DocumentLoader::create(0, ResourceRequest(testURL), SubstituteData());
     RefPtr<HTMLDocument> document = HTMLDocument::create();
     RefPtr<ResourceFetcher> fetcher(documentLoader->fetcher());
     fetcher->setDocument(document.get());
diff --git a/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp b/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp
index 2988252..625a999 100644
--- a/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp
+++ b/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp
@@ -30,9 +30,18 @@
 
 #include "config.h"
 #include "core/fetch/ResourceLoadPriorityOptimizer.h"
+#include "core/rendering/RenderObject.h"
+
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
+ResourceLoadPriorityOptimizer* ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()
+{
+    DEFINE_STATIC_LOCAL(ResourceLoadPriorityOptimizer, s_renderLoadOptimizer, ());
+    return &s_renderLoadOptimizer;
+}
+
 ResourceLoadPriorityOptimizer::ResourceAndVisibility::ResourceAndVisibility(ImageResource* image, VisibilityStatus v)
     : imageResource(image)
     , status(v)
@@ -49,6 +58,37 @@
 
 ResourceLoadPriorityOptimizer::~ResourceLoadPriorityOptimizer()
 {
+}
+
+void ResourceLoadPriorityOptimizer::addRenderObject(RenderObject* renderer)
+{
+    m_objects.add(renderer);
+    renderer->setHasPendingResourceUpdate(true);
+}
+
+void ResourceLoadPriorityOptimizer::removeRenderObject(RenderObject* renderer)
+{
+    if (!renderer->hasPendingResourceUpdate())
+        return;
+    m_objects.remove(renderer);
+    renderer->setHasPendingResourceUpdate(false);
+}
+
+void ResourceLoadPriorityOptimizer::updateAllImageResourcePriorities()
+{
+    m_imageResources.clear();
+
+    Vector<RenderObject*> objectsToRemove;
+    for (RenderObjectSet::iterator it = m_objects.begin(); it != m_objects.end(); ++it) {
+        RenderObject* obj = *it;
+        if (!obj->updateImageLoadingPriorities()) {
+            objectsToRemove.append(obj);
+        }
+    }
+
+    for (Vector<RenderObject*>::iterator it = objectsToRemove.begin(); it != objectsToRemove.end(); ++it)
+        m_objects.remove(*it);
+
     updateImageResourcesWithLoadPriority();
 }
 
@@ -73,7 +113,7 @@
 
     ImageResourceMap::AddResult result = m_imageResources.add(img->identifier(), adoptPtr(new ResourceAndVisibility(img, status)));
     if (!result.isNewEntry && status == Visible)
-        result.iterator->value->status = status;
+        result.storedValue->value->status = status;
 }
 
 }
diff --git a/Source/core/fetch/ResourceLoadPriorityOptimizer.h b/Source/core/fetch/ResourceLoadPriorityOptimizer.h
index cb58320..c682ead 100644
--- a/Source/core/fetch/ResourceLoadPriorityOptimizer.h
+++ b/Source/core/fetch/ResourceLoadPriorityOptimizer.h
@@ -36,6 +36,7 @@
 #include "platform/geometry/LayoutRect.h"
 
 #include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
 
 namespace WebCore {
@@ -46,11 +47,17 @@
         NotVisible,
         Visible,
     };
-    ResourceLoadPriorityOptimizer();
-    ~ResourceLoadPriorityOptimizer();
     void notifyImageResourceVisibility(ImageResource*, VisibilityStatus);
+    void updateAllImageResourcePriorities();
+    void addRenderObject(RenderObject*);
+    void removeRenderObject(RenderObject*);
+
+    static ResourceLoadPriorityOptimizer* resourceLoadPriorityOptimizer();
 
 private:
+    ResourceLoadPriorityOptimizer();
+    ~ResourceLoadPriorityOptimizer();
+
     void updateImageResourcesWithLoadPriority();
 
     struct ResourceAndVisibility {
@@ -62,6 +69,9 @@
 
     typedef HashMap<unsigned long, OwnPtr<ResourceAndVisibility> > ImageResourceMap;
     ImageResourceMap m_imageResources;
+
+    typedef HashSet<RenderObject*> RenderObjectSet;
+    RenderObjectSet m_objects;
 };
 
 }
diff --git a/Source/core/fetch/ResourceLoader.cpp b/Source/core/fetch/ResourceLoader.cpp
index f1356b7..f371aba 100644
--- a/Source/core/fetch/ResourceLoader.cpp
+++ b/Source/core/fetch/ResourceLoader.cpp
@@ -87,6 +87,7 @@
 void ResourceLoader::releaseResources()
 {
     ASSERT(m_state != Terminated);
+    ASSERT(m_notifiedLoadComplete);
     m_requestCountTracker.clear();
     m_host->didLoadResource(m_resource);
     if (m_state == Terminated)
@@ -116,11 +117,12 @@
 void ResourceLoader::init(const ResourceRequest& passedRequest)
 {
     ResourceRequest request(passedRequest);
-    m_host->willSendRequest(m_resource->identifier(), request, ResourceResponse(), m_options);
+    m_host->willSendRequest(m_resource->identifier(), request, ResourceResponse(), m_options.initiatorInfo);
     request.setReportLoadTiming(true);
     ASSERT(m_state != Terminated);
     ASSERT(!request.isNull());
     m_originalRequest = m_request = request;
+    m_resource->updateRequest(request);
     m_host->didInitializeResourceLoader(this);
 }
 
@@ -182,11 +184,11 @@
 {
     RefPtr<ResourceLoader> protect(this);
     RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse);
-    m_host->didDownloadData(m_resource, length, encodedDataLength, m_options);
+    m_host->didDownloadData(m_resource, length, encodedDataLength);
     m_resource->didDownloadData(length);
 }
 
-void ResourceLoader::didFinishLoadingOnePart(double finishTime)
+void ResourceLoader::didFinishLoadingOnePart(double finishTime, int64 encodedDataLength)
 {
     // If load has been cancelled after finishing (which could happen with a
     // JavaScript that changes the window location), do nothing.
@@ -196,7 +198,7 @@
     if (m_notifiedLoadComplete)
         return;
     m_notifiedLoadComplete = true;
-    m_host->didFinishLoading(m_resource, finishTime, m_options);
+    m_host->didFinishLoading(m_resource, finishTime, encodedDataLength);
 }
 
 void ResourceLoader::didChangePriority(ResourceLoadPriority loadPriority)
@@ -246,7 +248,10 @@
         m_loader.clear();
     }
 
-    m_host->didFailLoading(m_resource, nonNullError, m_options);
+    if (!m_notifiedLoadComplete) {
+        m_notifiedLoadComplete = true;
+        m_host->didFailLoading(m_resource, nonNullError);
+    }
 
     if (m_state == Finishing)
         m_resource->error(Resource::LoadError);
@@ -262,18 +267,20 @@
     ASSERT(!request.isNull());
     const ResourceResponse& redirectResponse(passedRedirectResponse.toResourceResponse());
     ASSERT(!redirectResponse.isNull());
-    if (!m_host->shouldRequest(m_resource, request, m_options)) {
+    if (!m_host->canAccessRedirect(m_resource, request, redirectResponse, m_options)) {
         cancel();
         return;
     }
+
     m_host->redirectReceived(m_resource, redirectResponse);
     m_resource->willSendRequest(request, redirectResponse);
     if (request.isNull() || m_state == Terminated)
         return;
 
-    m_host->willSendRequest(m_resource->identifier(), request, redirectResponse, m_options);
+    m_host->willSendRequest(m_resource->identifier(), request, redirectResponse, m_options.initiatorInfo);
     request.setReportLoadTiming(true);
     ASSERT(!request.isNull());
+    m_resource->updateRequest(request);
     m_request = request;
 }
 
@@ -291,6 +298,12 @@
     m_resource->didSendData(bytesSent, totalBytesToBeSent);
 }
 
+bool ResourceLoader::responseNeedsAccessControlCheck() const
+{
+    // If the fetch was (potentially) CORS enabled, an access control check of the response is required.
+    return m_options.corsEnabled == IsCORSEnabled;
+}
+
 void ResourceLoader::didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse& response)
 {
     ASSERT(!response.isNull());
@@ -302,14 +315,31 @@
     RELEASE_ASSERT(isMultipartPayload || isValidStateTransition);
     m_connectionState = ConnectionStateReceivedResponse;
 
+    const ResourceResponse& resourceResponse = response.toResourceResponse();
+
+    if (responseNeedsAccessControlCheck()) {
+        // If the response successfully validated a cached resource, perform
+        // the access control with respect to it. Need to do this right here
+        // before the resource switches clients over to that validated resource.
+        Resource* resource = m_resource;
+        if (resource->isCacheValidator() && resourceResponse.httpStatusCode() == 304)
+            resource = m_resource->resourceToRevalidate();
+        else
+            m_resource->setResponse(resourceResponse);
+        if (!m_host->canAccessResource(resource, m_options.securityOrigin.get(), response.url())) {
+            cancel();
+            return;
+        }
+    }
+
     // Reference the object in this method since the additional processing can do
     // anything including removing the last reference to this object.
     RefPtr<ResourceLoader> protect(this);
-    m_resource->responseReceived(response.toResourceResponse());
+    m_resource->responseReceived(resourceResponse);
     if (m_state == Terminated)
         return;
 
-    m_host->didReceiveResponse(m_resource, response.toResourceResponse(), m_options);
+    m_host->didReceiveResponse(m_resource, resourceResponse);
 
     if (response.toResourceResponse().isMultipart()) {
         // We don't count multiParts in a ResourceFetcher's request count
@@ -322,12 +352,18 @@
         // Since a subresource loader does not load multipart sections progressively, data was delivered to the loader all at once.
         // After the first multipart section is complete, signal to delegates that this load is "finished"
         m_host->subresourceLoaderFinishedLoadingOnePart(this);
-        didFinishLoadingOnePart(0);
+        didFinishLoadingOnePart(0, blink::WebURLLoaderClient::kUnknownEncodedDataLength);
     }
 
     if (m_resource->response().httpStatusCode() < 400 || m_resource->shouldIgnoreHTTPStatusCodeErrors())
         return;
     m_state = Finishing;
+
+    if (!m_notifiedLoadComplete) {
+        m_notifiedLoadComplete = true;
+        m_host->didFailLoading(m_resource, ResourceError::cancelledError(m_request.url()));
+    }
+
     m_resource->error(Resource::LoadError);
     cancel();
 }
@@ -350,11 +386,11 @@
     // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
     // However, with today's computers and networking speeds, this won't happen in practice.
     // Could be an issue with a giant local file.
-    m_host->didReceiveData(m_resource, data, length, encodedDataLength, m_options);
+    m_host->didReceiveData(m_resource, data, length, encodedDataLength);
     m_resource->appendData(data, length);
 }
 
-void ResourceLoader::didFinishLoading(blink::WebURLLoader*, double finishTime)
+void ResourceLoader::didFinishLoading(blink::WebURLLoader*, double finishTime, int64 encodedDataLength)
 {
     RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse || m_connectionState == ConnectionStateReceivingData);
     m_connectionState = ConnectionStateFinishedLoading;
@@ -366,8 +402,8 @@
     RefPtr<ResourceLoader> protect(this);
     ResourcePtr<Resource> protectResource(m_resource);
     m_state = Finishing;
+    didFinishLoadingOnePart(finishTime, encodedDataLength);
     m_resource->finish(finishTime);
-    didFinishLoadingOnePart(finishTime);
 
     // If the load has been cancelled by a delegate in response to didFinishLoad(), do not release
     // the resources a second time, they have been released by cancel.
@@ -387,16 +423,17 @@
     ResourcePtr<Resource> protectResource(m_resource);
     m_state = Finishing;
     m_resource->setResourceError(error);
+
+    if (!m_notifiedLoadComplete) {
+        m_notifiedLoadComplete = true;
+        m_host->didFailLoading(m_resource, error);
+    }
+
     m_resource->error(Resource::LoadError);
 
     if (m_state == Terminated)
         return;
 
-    if (!m_notifiedLoadComplete) {
-        m_notifiedLoadComplete = true;
-        m_host->didFailLoading(m_resource, error, m_options);
-    }
-
     releaseResources();
 }
 
@@ -432,9 +469,10 @@
     if (m_state == Terminated)
         return;
     RefPtr<ResourceLoadInfo> resourceLoadInfo = responseOut.toResourceResponse().resourceLoadInfo();
-    m_host->didReceiveData(m_resource, dataOut.data(), dataOut.size(), resourceLoadInfo ? resourceLoadInfo->encodedDataLength : -1, m_options);
+    int64 encodedDataLength = resourceLoadInfo ? resourceLoadInfo->encodedDataLength : blink::WebURLLoaderClient::kUnknownEncodedDataLength;
+    m_host->didReceiveData(m_resource, dataOut.data(), dataOut.size(), encodedDataLength);
     m_resource->setResourceBuffer(dataOut);
-    didFinishLoading(0, monotonicallyIncreasingTime());
+    didFinishLoading(0, monotonicallyIncreasingTime(), encodedDataLength);
 }
 
 }
diff --git a/Source/core/fetch/ResourceLoader.h b/Source/core/fetch/ResourceLoader.h
index 814cecf..151adb0 100644
--- a/Source/core/fetch/ResourceLoader.h
+++ b/Source/core/fetch/ResourceLoader.h
@@ -44,7 +44,7 @@
 class ResourceResponse;
 class ResourceLoaderHost;
 
-class ResourceLoader : public RefCounted<ResourceLoader>, protected blink::WebURLLoaderClient {
+class ResourceLoader FINAL : public RefCounted<ResourceLoader>, protected blink::WebURLLoaderClient {
 public:
     static PassRefPtr<ResourceLoader> create(ResourceLoaderHost*, Resource*, const ResourceRequest&, const ResourceLoaderOptions&);
     virtual ~ResourceLoader();
@@ -72,12 +72,11 @@
     virtual void didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse&) OVERRIDE;
     virtual void didReceiveData(blink::WebURLLoader*, const char*, int, int encodedDataLength) OVERRIDE;
     virtual void didReceiveCachedMetadata(blink::WebURLLoader*, const char* data, int length) OVERRIDE;
-    virtual void didFinishLoading(blink::WebURLLoader*, double finishTime) OVERRIDE;
+    virtual void didFinishLoading(blink::WebURLLoader*, double finishTime, int64 encodedDataLength) OVERRIDE;
     virtual void didFail(blink::WebURLLoader*, const blink::WebURLError&) OVERRIDE;
     virtual void didDownloadData(blink::WebURLLoader*, int, int) OVERRIDE;
 
     const KURL& url() const { return m_request.url(); }
-    bool shouldSendResourceLoadCallbacks() const { return m_options.sendLoadCallbacks == SendCallbacks; }
     bool shouldSniffContent() const { return m_options.sniffContent == SniffContent; }
     bool isLoadedBy(ResourceLoaderHost*) const;
 
@@ -90,7 +89,9 @@
     void init(const ResourceRequest&);
     void requestSynchronously();
 
-    void didFinishLoadingOnePart(double finishTime);
+    void didFinishLoadingOnePart(double finishTime, int64_t encodedDataLength);
+
+    bool responseNeedsAccessControlCheck() const;
 
     OwnPtr<blink::WebURLLoader> m_loader;
     RefPtr<ResourceLoaderHost> m_host;
diff --git a/Source/core/fetch/ResourceLoaderHost.h b/Source/core/fetch/ResourceLoaderHost.h
index 6748276..270b379 100644
--- a/Source/core/fetch/ResourceLoaderHost.h
+++ b/Source/core/fetch/ResourceLoaderHost.h
@@ -44,7 +44,6 @@
 class ResourceResponse;
 
 struct FetchInitiatorInfo;
-struct ResourceLoaderOptions;
 
 class ResourceLoaderHost {
 public:
@@ -56,21 +55,22 @@
     virtual void didLoadResource(Resource*) = 0;
     virtual void redirectReceived(Resource*, const ResourceResponse&) = 0;
 
-    virtual void didFinishLoading(const Resource*, double finishTime, const ResourceLoaderOptions&) = 0;
+    virtual void didFinishLoading(const Resource*, double finishTime, int64_t encodedDataLength) = 0;
     virtual void didChangeLoadingPriority(const Resource*, ResourceLoadPriority) = 0;
-    virtual void didFailLoading(const Resource*, const ResourceError&, const ResourceLoaderOptions&) = 0;
+    virtual void didFailLoading(const Resource*, const ResourceError&) = 0;
 
-    virtual void willSendRequest(unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const ResourceLoaderOptions&) = 0;
-    virtual void didReceiveResponse(const Resource*, const ResourceResponse&, const ResourceLoaderOptions&) = 0;
-    virtual void didReceiveData(const Resource*, const char* data, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) = 0;
-    virtual void didDownloadData(const Resource*, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) = 0;
+    virtual void willSendRequest(unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo&) = 0;
+    virtual void didReceiveResponse(const Resource*, const ResourceResponse&) = 0;
+    virtual void didReceiveData(const Resource*, const char* data, int dataLength, int encodedDataLength) = 0;
+    virtual void didDownloadData(const Resource*, int dataLength, int encodedDataLength) = 0;
 
     virtual void subresourceLoaderFinishedLoadingOnePart(ResourceLoader*) = 0;
     virtual void didInitializeResourceLoader(ResourceLoader*) = 0;
     virtual void willTerminateResourceLoader(ResourceLoader*) = 0;
     virtual void willStartLoadingResource(ResourceRequest&) = 0;
 
-    virtual bool shouldRequest(Resource*, const ResourceRequest&, const ResourceLoaderOptions&) = 0;
+    virtual bool canAccessRedirect(Resource*, ResourceRequest&, const ResourceResponse&, ResourceLoaderOptions&) = 0;
+    virtual bool canAccessResource(Resource*, SecurityOrigin* sourceOrigin, const KURL&) const = 0;
     virtual bool defersLoading() const = 0;
     virtual bool isLoadedBy(ResourceLoaderHost*) const = 0;
 
diff --git a/Source/core/fetch/ResourceLoaderOptions.h b/Source/core/fetch/ResourceLoaderOptions.h
index 5913622..b183901 100644
--- a/Source/core/fetch/ResourceLoaderOptions.h
+++ b/Source/core/fetch/ResourceLoaderOptions.h
@@ -36,11 +36,6 @@
 
 namespace WebCore {
 
-enum SendCallbackPolicy {
-    SendCallbacks,
-    DoNotSendCallbacks
-};
-
 enum ContentSniffingPolicy {
     SniffContent,
     DoNotSniffContent
@@ -51,16 +46,6 @@
     DoNotBufferData
 };
 
-enum ClientCrossOriginCredentialPolicy {
-    AskClientForCrossOriginCredentials,
-    DoNotAskClientForCrossOriginCredentials
-};
-
-enum SecurityCheckPolicy {
-    SkipSecurityCheck,
-    DoSecurityCheck
-};
-
 enum ContentSecurityPolicyCheck {
     CheckContentSecurityPolicy,
     DoNotCheckContentSecurityPolicy
@@ -97,58 +82,56 @@
     RequestAsynchronously
 };
 
+// A resource fetch can be marked as being CORS enabled. The loader
+// must perform an access check upon seeing the response.
+enum CORSEnabled {
+    NotCORSEnabled,
+    IsCORSEnabled
+};
+
 struct ResourceLoaderOptions {
     ResourceLoaderOptions()
-        : sendLoadCallbacks(DoNotSendCallbacks)
-        , sniffContent(DoNotSniffContent)
+        : sniffContent(DoNotSniffContent)
         , dataBufferingPolicy(BufferData)
         , allowCredentials(DoNotAllowStoredCredentials)
         , credentialsRequested(ClientDidNotRequestCredentials)
-        , crossOriginCredentialPolicy(DoNotAskClientForCrossOriginCredentials)
-        , securityCheck(DoSecurityCheck)
         , contentSecurityPolicyOption(CheckContentSecurityPolicy)
         , requestInitiatorContext(DocumentContext)
         , mixedContentBlockingTreatment(TreatAsDefaultForType)
         , synchronousPolicy(RequestAsynchronously)
+        , corsEnabled(NotCORSEnabled)
     {
     }
 
     ResourceLoaderOptions(
-        SendCallbackPolicy sendLoadCallbacks,
         ContentSniffingPolicy sniffContent,
         DataBufferingPolicy dataBufferingPolicy,
         StoredCredentials allowCredentials,
         CredentialRequest credentialsRequested,
-        ClientCrossOriginCredentialPolicy crossOriginCredentialPolicy,
-        SecurityCheckPolicy securityCheck,
         ContentSecurityPolicyCheck contentSecurityPolicyOption,
         RequestInitiatorContext requestInitiatorContext)
-        : sendLoadCallbacks(sendLoadCallbacks)
-        , sniffContent(sniffContent)
+        : sniffContent(sniffContent)
         , dataBufferingPolicy(dataBufferingPolicy)
         , allowCredentials(allowCredentials)
         , credentialsRequested(credentialsRequested)
-        , crossOriginCredentialPolicy(crossOriginCredentialPolicy)
-        , securityCheck(securityCheck)
         , contentSecurityPolicyOption(contentSecurityPolicyOption)
         , requestInitiatorContext(requestInitiatorContext)
         , mixedContentBlockingTreatment(TreatAsDefaultForType)
         , synchronousPolicy(RequestAsynchronously)
+        , corsEnabled(NotCORSEnabled)
     {
     }
 
-    SendCallbackPolicy sendLoadCallbacks;
     ContentSniffingPolicy sniffContent;
     DataBufferingPolicy dataBufferingPolicy;
     StoredCredentials allowCredentials; // Whether HTTP credentials and cookies are sent with the request.
     CredentialRequest credentialsRequested; // Whether the client (e.g. XHR) wanted credentials in the first place.
-    ClientCrossOriginCredentialPolicy crossOriginCredentialPolicy; // Whether we will ask the client for credentials (if we allow credentials at all).
-    SecurityCheckPolicy securityCheck;
     ContentSecurityPolicyCheck contentSecurityPolicyOption;
     FetchInitiatorInfo initiatorInfo;
     RequestInitiatorContext requestInitiatorContext;
     MixedContentBlockingTreatment mixedContentBlockingTreatment;
     SynchronousPolicy synchronousPolicy;
+    CORSEnabled corsEnabled; // If the resource is loaded out-of-origin, whether or not to use CORS.
     RefPtr<SecurityOrigin> securityOrigin;
 };
 
diff --git a/Source/core/fetch/ResourceOwner.h b/Source/core/fetch/ResourceOwner.h
new file mode 100644
index 0000000..ebadbe9
--- /dev/null
+++ b/Source/core/fetch/ResourceOwner.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef ResourceOwner_h
+#define ResourceOwner_h
+
+#include "core/fetch/ResourcePtr.h"
+
+namespace WebCore {
+
+
+template<class R, class C = typename R::ClientType>
+class ResourceOwner : public C {
+public:
+    typedef R ResourceType;
+
+    virtual ~ResourceOwner();
+    ResourceType* resource() const { return m_resource.get(); }
+
+protected:
+    ResourceOwner();
+    ResourceOwner(const ResourceOwner& other) { setResource(other.resource()); }
+    explicit ResourceOwner(const ResourcePtr<ResourceType>&);
+
+    void setResource(const ResourcePtr<ResourceType>&);
+    void clearResource();
+
+    ResourceOwner& operator=(const ResourceOwner& other);
+
+private:
+    ResourcePtr<ResourceType> m_resource;
+};
+
+template<class R, class C>
+inline ResourceOwner<R, C>::ResourceOwner()
+{
+}
+
+template<class R, class C>
+inline ResourceOwner<R, C>::~ResourceOwner()
+{
+    clearResource();
+}
+
+template<class R, class C>
+inline ResourceOwner<R, C>::ResourceOwner(const ResourcePtr<R>& resource)
+    : m_resource(resource)
+{
+    if (m_resource)
+        m_resource->addClient(this);
+}
+
+template<class R, class C>
+inline void ResourceOwner<R, C>::setResource(const ResourcePtr<R>& newResource)
+{
+    if (newResource == m_resource)
+        return;
+
+    // Some ResourceClient implementations reenter this so
+    // we need to prevent double removal.
+    if (ResourcePtr<ResourceType> oldResource = m_resource) {
+        m_resource.clear();
+        oldResource->removeClient(this);
+    }
+
+    if (newResource) {
+        m_resource = newResource;
+        m_resource->addClient(this);
+    }
+}
+
+template<class R, class C>
+inline void ResourceOwner<R, C>::clearResource()
+{
+    setResource(0);
+}
+
+template<class R, class C>
+inline ResourceOwner<R, C>& ResourceOwner<R, C>::operator=(const ResourceOwner<R, C>& other)
+{
+    if (this == &other)
+        return *this;
+    setResource(other.resource());
+    return *this;
+}
+
+} // namespace WebCore
+
+#endif
diff --git a/Source/core/fetch/ResourcePtr.h b/Source/core/fetch/ResourcePtr.h
index a9bdd5f..f913365 100644
--- a/Source/core/fetch/ResourcePtr.h
+++ b/Source/core/fetch/ResourcePtr.h
@@ -36,6 +36,7 @@
 
     Resource* get() const { return m_resource; }
     bool operator!() const { return !m_resource; }
+    void clear() { setResource(0); }
 
     // This conversion operator allows implicit conversion to bool but not to other integer types.
     typedef Resource* ResourcePtrBase::*UnspecifiedBoolType;
diff --git a/Source/core/fetch/ScriptResource.cpp b/Source/core/fetch/ScriptResource.cpp
index 873ef33..f69c9f9 100644
--- a/Source/core/fetch/ScriptResource.cpp
+++ b/Source/core/fetch/ScriptResource.cpp
@@ -27,7 +27,7 @@
 #include "config.h"
 #include "core/fetch/ScriptResource.h"
 
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "platform/MIMETypeRegistry.h"
 #include "platform/SharedBuffer.h"
 #include "platform/network/HTTPParsers.h"
@@ -72,13 +72,13 @@
 
     if (!m_script && m_data) {
         String script = m_decoder->decode(m_data->data(), encodedSize());
-        script.append(m_decoder->flush());
+        script = script + m_decoder->flush();
         m_data.clear();
         // We lie a it here and claim that script counts as encoded data (even though it's really decoded data).
         // That's because the MemoryCache thinks that it can clear out decoded data by calling destroyDecodedData(),
         // but we can't destroy script in destroyDecodedData because that's our only copy of the data!
         setEncodedSize(script.sizeInBytes());
-        m_script = script;
+        m_script = AtomicString(script);
     }
 
     return m_script.string();
diff --git a/Source/core/fetch/ScriptResource.h b/Source/core/fetch/ScriptResource.h
index 9b89b76..28f6225 100644
--- a/Source/core/fetch/ScriptResource.h
+++ b/Source/core/fetch/ScriptResource.h
@@ -33,15 +33,17 @@
 class ResourceFetcher;
 class TextResourceDecoder;
 
-class ScriptResource : public Resource {
+class ScriptResource FINAL : public Resource {
 public:
+    typedef ResourceClient ClientType;
+
     ScriptResource(const ResourceRequest&, const String& charset);
     virtual ~ScriptResource();
 
     const String& script();
 
-    virtual void setEncoding(const String&);
-    virtual String encoding() const;
+    virtual void setEncoding(const String&) OVERRIDE;
+    virtual String encoding() const OVERRIDE;
     AtomicString mimeType() const;
 
     bool mimeTypeAllowedByNosniff() const;
diff --git a/Source/core/fetch/ShaderResource.cpp b/Source/core/fetch/ShaderResource.cpp
index da0fa7e..1b5ea42 100644
--- a/Source/core/fetch/ShaderResource.cpp
+++ b/Source/core/fetch/ShaderResource.cpp
@@ -30,7 +30,7 @@
 #include "config.h"
 #include "core/fetch/ShaderResource.h"
 
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "platform/SharedBuffer.h"
 #include "wtf/text/StringBuilder.h"
 
diff --git a/Source/core/fetch/ShaderResource.h b/Source/core/fetch/ShaderResource.h
index 0363c67..dc9a2d3 100644
--- a/Source/core/fetch/ShaderResource.h
+++ b/Source/core/fetch/ShaderResource.h
@@ -36,8 +36,10 @@
 
 class TextResourceDecoder;
 
-class ShaderResource : public Resource {
+class ShaderResource FINAL : public Resource {
 public:
+    typedef ResourceClient ClientType;
+
     ShaderResource(const ResourceRequest&);
     virtual ~ShaderResource();
 
diff --git a/Source/core/html/HTMLImportDataClient.h b/Source/core/fetch/StyleSheetResource.h
similarity index 82%
copy from Source/core/html/HTMLImportDataClient.h
copy to Source/core/fetch/StyleSheetResource.h
index 0c26a22..d714ac5 100644
--- a/Source/core/html/HTMLImportDataClient.h
+++ b/Source/core/fetch/StyleSheetResource.h
@@ -28,17 +28,24 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef HTMLImportDataClient_h
-#define HTMLImportDataClient_h
+#ifndef StyleSheetResource_h
+#define StyleSheetResource_h
+
+#include "core/fetch/Resource.h"
 
 namespace WebCore {
 
-class HTMLImportDataClient {
+class StyleSheetResourceClient;
+
+class StyleSheetResource : public Resource {
 public:
-    virtual ~HTMLImportDataClient() { }
-    virtual void didFinish() = 0;
+    typedef StyleSheetResourceClient ClientType;
+
+    StyleSheetResource(const ResourceRequest& request, Type type)
+        : Resource(request, type)
+    { }
 };
 
 }
 
-#endif // HTMLImportDataClient_h
+#endif
diff --git a/Source/core/fetch/StyleSheetResourceClient.h b/Source/core/fetch/StyleSheetResourceClient.h
index 4e46c2a..05a6a48 100644
--- a/Source/core/fetch/StyleSheetResourceClient.h
+++ b/Source/core/fetch/StyleSheetResourceClient.h
@@ -37,10 +37,11 @@
 public:
     virtual ~StyleSheetResourceClient() { }
     static ResourceClientType expectedType() { return StyleSheetType; }
-    virtual ResourceClientType resourceClientType() const { return expectedType(); }
+    virtual ResourceClientType resourceClientType() const OVERRIDE FINAL { return expectedType(); }
     virtual void setCSSStyleSheet(const String& /* href */, const KURL& /* baseURL */, const String& /* charset */, const CSSStyleSheetResource*) { }
     virtual void setXSLStyleSheet(const String& /* href */, const KURL& /* baseURL */, const String& /* sheet */) { }
 };
+
 }
 
 #endif // StyleSheetResourceClient_h
diff --git a/Source/core/fetch/XSLStyleSheetResource.cpp b/Source/core/fetch/XSLStyleSheetResource.cpp
index bb36fce..67950a9 100644
--- a/Source/core/fetch/XSLStyleSheetResource.cpp
+++ b/Source/core/fetch/XSLStyleSheetResource.cpp
@@ -30,14 +30,14 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/fetch/ResourceClientWalker.h"
 #include "core/fetch/StyleSheetResourceClient.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "platform/SharedBuffer.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
 XSLStyleSheetResource::XSLStyleSheetResource(const ResourceRequest& resourceRequest)
-    : Resource(resourceRequest, XSLStyleSheet)
+    : StyleSheetResource(resourceRequest, XSLStyleSheet)
     , m_decoder(TextResourceDecoder::create("text/xsl"))
 {
     ASSERT(RuntimeEnabledFeatures::xsltEnabled());
@@ -70,7 +70,7 @@
 {
     if (m_data.get()) {
         m_sheet = m_decoder->decode(m_data->data(), encodedSize());
-        m_sheet.append(m_decoder->flush());
+        m_sheet = m_sheet + m_decoder->flush();
     }
 
     ResourceClientWalker<StyleSheetResourceClient> w(m_clients);
diff --git a/Source/core/fetch/XSLStyleSheetResource.h b/Source/core/fetch/XSLStyleSheetResource.h
index 1dea634..8071297 100644
--- a/Source/core/fetch/XSLStyleSheetResource.h
+++ b/Source/core/fetch/XSLStyleSheetResource.h
@@ -27,24 +27,25 @@
 #define XSLStyleSheetResource_h
 
 #include "core/fetch/ResourcePtr.h"
+#include "core/fetch/StyleSheetResource.h"
 
 namespace WebCore {
 
 class ResourceFetcher;
 class TextResourceDecoder;
 
-class XSLStyleSheetResource : public Resource {
+class XSLStyleSheetResource FINAL : public StyleSheetResource {
 public:
     XSLStyleSheetResource(const ResourceRequest&);
 
     const String& sheet() const { return m_sheet; }
 
-    virtual void didAddClient(ResourceClient*);
-    virtual void setEncoding(const String&);
-    virtual String encoding() const;
+    virtual void didAddClient(ResourceClient*) OVERRIDE;
+    virtual void setEncoding(const String&) OVERRIDE;
+    virtual String encoding() const OVERRIDE;
 
 protected:
-    virtual void checkNotify();
+    virtual void checkNotify() OVERRIDE;
 
     String m_sheet;
     OwnPtr<TextResourceDecoder> m_decoder;
diff --git a/Source/core/fileapi/Blob.cpp b/Source/core/fileapi/Blob.cpp
index def1ae0..4fa8e1f 100644
--- a/Source/core/fileapi/Blob.cpp
+++ b/Source/core/fileapi/Blob.cpp
@@ -31,7 +31,6 @@
 #include "config.h"
 #include "core/fileapi/Blob.h"
 
-#include "core/fileapi/File.h"
 #include "platform/blob/BlobRegistry.h"
 #include "platform/blob/BlobURL.h"
 
@@ -39,7 +38,7 @@
 
 namespace {
 
-class BlobURLRegistry : public URLRegistry {
+class BlobURLRegistry FINAL : public URLRegistry {
 public:
     virtual void registerURL(SecurityOrigin*, const KURL&, URLRegistrable*) OVERRIDE;
     virtual void unregisterURL(const KURL&) OVERRIDE;
@@ -76,19 +75,9 @@
 {
 }
 
-PassRefPtr<Blob> Blob::slice(long long start, long long end, const String& contentType) const
+void Blob::clampSliceOffsets(long long size, long long& start, long long& end)
 {
-    // When we slice a file for the first time, we obtain a snapshot of the file by capturing its current size and modification time.
-    // The modification time will be used to verify if the file has been changed or not, when the underlying data are accessed.
-    long long size;
-    double modificationTime;
-    if (hasBackingFile()) {
-        // FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
-        toFile(this)->captureSnapshot(size, modificationTime);
-    } else {
-        size = this->size();
-        ASSERT(size != -1);
-    }
+    ASSERT(size != -1);
 
     // Convert the negative value that is used to select from the end.
     if (start < 0)
@@ -108,21 +97,25 @@
         end = start;
     else if (end > size)
         end = size;
+}
+
+PassRefPtr<Blob> Blob::slice(long long start, long long end, const String& contentType) const
+{
+    long long size = this->size();
+    clampSliceOffsets(size, start, end);
 
     long long length = end - start;
     OwnPtr<BlobData> blobData = BlobData::create();
     blobData->setContentType(contentType);
-    if (hasBackingFile()) {
-        if (!toFile(this)->fileSystemURL().isEmpty())
-            blobData->appendFileSystemURL(toFile(this)->fileSystemURL(), start, length, modificationTime);
-        else
-            blobData->appendFile(toFile(this)->path(), start, length, modificationTime);
-    } else {
-        blobData->appendBlob(m_blobDataHandle, start, length);
-    }
+    blobData->appendBlob(m_blobDataHandle, start, length);
     return Blob::create(BlobDataHandle::create(blobData.release(), length));
 }
 
+void Blob::appendTo(BlobData& blobData) const
+{
+    blobData.appendBlob(m_blobDataHandle, 0, m_blobDataHandle->size());
+}
+
 URLRegistry& Blob::registry() const
 {
     return BlobURLRegistry::registry();
diff --git a/Source/core/fileapi/Blob.h b/Source/core/fileapi/Blob.h
index 6a72155..e564a65 100644
--- a/Source/core/fileapi/Blob.h
+++ b/Source/core/fileapi/Blob.h
@@ -57,19 +57,24 @@
 
     virtual ~Blob();
 
-    String uuid() const { return m_blobDataHandle->uuid(); }
-    String type() const {  return m_blobDataHandle->type(); }
     virtual unsigned long long size() const { return m_blobDataHandle->size(); }
+    virtual PassRefPtr<Blob> slice(long long start = 0, long long end = std::numeric_limits<long long>::max(), const String& contentType = String()) const;
+
+    String type() const {  return m_blobDataHandle->type(); }
+    String uuid() const { return m_blobDataHandle->uuid(); }
+    PassRefPtr<BlobDataHandle> blobDataHandle() const { return m_blobDataHandle; }
     // True for all File instances, including the user-built ones.
     virtual bool isFile() const { return false; }
     // Only true for File instances that are backed by platform files.
     virtual bool hasBackingFile() const { return false; }
-    PassRefPtr<BlobDataHandle> blobDataHandle() const { return m_blobDataHandle; }
-    PassRefPtr<Blob> slice(long long start = 0, long long end = std::numeric_limits<long long>::max(), const String& contentType = String()) const;
+
+    // Used by the JavaScript Blob and File constructors.
+    virtual void appendTo(BlobData&) const;
 
     // URLRegistrable to support PublicURLs.
-    virtual URLRegistry& registry() const OVERRIDE;
+    virtual URLRegistry& registry() const OVERRIDE FINAL;
 
+    static void clampSliceOffsets(long long size, long long& start, long long& end);
 protected:
     explicit Blob(PassRefPtr<BlobDataHandle>);
 
diff --git a/Source/core/fileapi/Blob.idl b/Source/core/fileapi/Blob.idl
index 814a2fc..28fd1aa 100644
--- a/Source/core/fileapi/Blob.idl
+++ b/Source/core/fileapi/Blob.idl
@@ -29,10 +29,10 @@
  */
 
 [
+    CustomConstructor,
+    CustomConstructor(sequence<any> blobParts, optional BlobPropertyBag options),
     GlobalContext=Window&WorkerGlobalScope,
     SpecialWrapFor=File,
-    CustomConstructor,
-    CustomConstructor(sequence<any> blobParts, optional BlobPropertyBag options)
 ] interface Blob {
     readonly attribute unsigned long long size;
     readonly attribute DOMString type;
diff --git a/Source/core/fileapi/BlobBuilder.cpp b/Source/core/fileapi/BlobBuilder.cpp
deleted file mode 100644
index 70583af..0000000
--- a/Source/core/fileapi/BlobBuilder.cpp
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-
-#include "core/fileapi/BlobBuilder.h"
-
-#include "core/fileapi/Blob.h"
-#include "core/fileapi/File.h"
-#include "platform/text/LineEnding.h"
-#include "wtf/ArrayBuffer.h"
-#include "wtf/ArrayBufferView.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/TextEncoding.h"
-
-namespace WebCore {
-
-BlobBuilder::BlobBuilder()
-    : m_size(0)
-{
-}
-
-Vector<char>& BlobBuilder::getBuffer()
-{
-    // If the last item is not a data item, create one. Otherwise, we simply append the new string to the last data item.
-    if (m_items.isEmpty() || m_items[m_items.size() - 1].type != BlobDataItem::Data)
-        m_items.append(BlobDataItem(RawData::create()));
-
-    return *m_items[m_items.size() - 1].data->mutableData();
-}
-
-void BlobBuilder::append(const String& text, const String& endingType)
-{
-    CString utf8Text = UTF8Encoding().normalizeAndEncode(text, WTF::EntitiesForUnencodables);
-
-    Vector<char>& buffer = getBuffer();
-    size_t oldSize = buffer.size();
-
-    if (endingType == "native")
-        normalizeLineEndingsToNative(utf8Text, buffer);
-    else {
-        ASSERT(endingType == "transparent");
-        buffer.append(utf8Text.data(), utf8Text.length());
-    }
-    m_size += buffer.size() - oldSize;
-}
-
-void BlobBuilder::append(ArrayBuffer* arrayBuffer)
-{
-    if (!arrayBuffer)
-        return;
-
-    appendBytesData(arrayBuffer->data(), arrayBuffer->byteLength());
-}
-
-void BlobBuilder::append(ArrayBufferView* arrayBufferView)
-{
-    if (!arrayBufferView)
-        return;
-
-    appendBytesData(arrayBufferView->baseAddress(), arrayBufferView->byteLength());
-}
-
-void BlobBuilder::append(Blob* blob)
-{
-    if (!blob)
-        return;
-    if (blob->hasBackingFile()) {
-        File* file = toFile(blob);
-        // If the blob is file that is not snapshoted, capture the snapshot now.
-        // FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
-        long long snapshotSize;
-        double snapshotModificationTime;
-        file->captureSnapshot(snapshotSize, snapshotModificationTime);
-
-        m_size += snapshotSize;
-        if (!file->fileSystemURL().isEmpty())
-            m_items.append(BlobDataItem(file->fileSystemURL(), 0, snapshotSize, snapshotModificationTime));
-        else
-            m_items.append(BlobDataItem(file->path(), 0, snapshotSize, snapshotModificationTime));
-    } else {
-        long long blobSize = static_cast<long long>(blob->size());
-        m_size += blobSize;
-        m_items.append(BlobDataItem(blob->blobDataHandle(), 0, blobSize));
-    }
-}
-
-void BlobBuilder::appendBytesData(const void* data, size_t length)
-{
-    Vector<char>& buffer = getBuffer();
-    size_t oldSize = buffer.size();
-    buffer.append(static_cast<const char*>(data), length);
-    m_size += buffer.size() - oldSize;
-}
-
-PassRefPtr<Blob> BlobBuilder::createBlob(const String& contentType)
-{
-    OwnPtr<BlobData> blobData = BlobData::create();
-    blobData->setContentType(contentType);
-    blobData->swapItems(m_items);
-
-    RefPtr<Blob> blob = Blob::create(BlobDataHandle::create(blobData.release(), m_size));
-
-    // After creating a blob from the current blob data, we do not need to keep the data around any more.
-    // Instead, we only need to keep a reference to the blob data just created.
-    m_items.append(BlobDataItem(blob->blobDataHandle(), 0, m_size));
-
-    return blob.release();
-}
-
-PassRefPtr<File> BlobBuilder::createFile(const String& contentType, const String& fileName, double modificationTime)
-{
-    OwnPtr<BlobData> blobData = BlobData::create();
-    blobData->setContentType(contentType);
-    blobData->swapItems(m_items);
-
-    RefPtr<File> file = File::create(fileName, modificationTime, BlobDataHandle::create(blobData.release(), m_size));
-
-    // After creating a file from the current blob data, we do not need to keep the data around any more.
-    // Instead, we only need to keep a reference to the blob data just created.
-    m_items.append(BlobDataItem(file->blobDataHandle(), 0, m_size));
-
-    return file.release();
-}
-
-} // namespace WebCore
diff --git a/Source/core/fileapi/BlobBuilder.h b/Source/core/fileapi/BlobBuilder.h
deleted file mode 100644
index cdf3cc5..0000000
--- a/Source/core/fileapi/BlobBuilder.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef BlobBuilder_h
-#define BlobBuilder_h
-
-#include "platform/blob/BlobData.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class Blob;
-class File;
-
-class BlobBuilder {
-public:
-    BlobBuilder();
-
-    void append(Blob*);
-    void append(const String& text, const String& ending);
-    void append(ArrayBuffer*);
-    void append(ArrayBufferView*);
-
-    PassRefPtr<Blob> createBlob(const String& contentType);
-    PassRefPtr<File> createFile(const String& contentType, const String& fileName, double modificationTime);
-
-private:
-    void appendBytesData(const void*, size_t);
-
-    Vector<char>& getBuffer();
-
-    long long m_size;
-    BlobDataItemList m_items;
-};
-
-} // namespace WebCore
-
-#endif // BlobBuilder_h
diff --git a/Source/core/fileapi/File.cpp b/Source/core/fileapi/File.cpp
index 52c6277..de776d5 100644
--- a/Source/core/fileapi/File.cpp
+++ b/Source/core/fileapi/File.cpp
@@ -113,18 +113,16 @@
     ScriptWrappable::init(this);
 }
 
-File::File(const String& path, PassRefPtr<BlobDataHandle> blobDataHandle)
+File::File(const String& path, const String& name, const String& relativePath, bool hasSnaphotData, uint64_t size, double lastModified, PassRefPtr<BlobDataHandle> blobDataHandle)
     : Blob(blobDataHandle)
-    , m_hasBackingFile(true)
+    , m_hasBackingFile(!path.isEmpty() || !relativePath.isEmpty())
     , m_path(path)
-    , m_name(blink::Platform::current()->fileUtilities()->baseName(path))
-    , m_snapshotSize(-1)
-    , m_snapshotModificationTime(invalidFileTime())
+    , m_name(name)
+    , m_snapshotSize(hasSnaphotData ? static_cast<long long>(size) : -1)
+    , m_snapshotModificationTime(hasSnaphotData ? lastModified : invalidFileTime())
+    , m_relativePath(relativePath)
 {
     ScriptWrappable::init(this);
-    // FIXME: File object serialization/deserialization does not include
-    // newer file object data members: m_name and m_relativePath.
-    // See SerializedScriptValue.cpp.
 }
 
 File::File(const String& name, double modificationTime, PassRefPtr<BlobDataHandle> blobDataHandle)
@@ -183,6 +181,29 @@
     return static_cast<unsigned long long>(size);
 }
 
+PassRefPtr<Blob> File::slice(long long start, long long end, const String& contentType) const
+{
+    if (!m_hasBackingFile)
+        return Blob::slice(start, end, contentType);
+
+    // FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
+    long long size;
+    double modificationTime;
+    captureSnapshot(size, modificationTime);
+    clampSliceOffsets(size, start, end);
+
+    long long length = end - start;
+    OwnPtr<BlobData> blobData = BlobData::create();
+    blobData->setContentType(contentType);
+    if (!m_fileSystemURL.isEmpty()) {
+        blobData->appendFileSystemURL(m_fileSystemURL, start, length, modificationTime);
+    } else {
+        ASSERT(!m_path.isEmpty());
+        blobData->appendFile(m_path, start, length, modificationTime);
+    }
+    return Blob::create(BlobDataHandle::create(blobData.release(), length));
+}
+
 void File::captureSnapshot(long long& snapshotSize, double& snapshotModificationTime) const
 {
     if (hasValidSnapshotMetadata()) {
@@ -204,4 +225,23 @@
     snapshotModificationTime = metadata.modificationTime;
 }
 
+void File::appendTo(BlobData& blobData) const
+{
+    if (!m_hasBackingFile) {
+        Blob::appendTo(blobData);
+        return;
+    }
+
+    // FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
+    long long size;
+    double modificationTime;
+    captureSnapshot(size, modificationTime);
+    if (!m_fileSystemURL.isEmpty()) {
+        blobData.appendFileSystemURL(m_fileSystemURL, 0, size, modificationTime);
+        return;
+    }
+    ASSERT(!m_path.isEmpty());
+    blobData.appendFile(m_path, 0, size, modificationTime);
+}
+
 } // namespace WebCore
diff --git a/Source/core/fileapi/File.h b/Source/core/fileapi/File.h
index f9c87b4..6c5dd1a 100644
--- a/Source/core/fileapi/File.h
+++ b/Source/core/fileapi/File.h
@@ -35,7 +35,7 @@
 struct FileMetadata;
 class KURL;
 
-class File : public Blob {
+class File FINAL : public Blob {
 public:
     // AllContentTypes should only be used when the full path/name are trusted; otherwise, it could
     // allow arbitrary pages to determine what applications an user has installed.
@@ -55,9 +55,9 @@
     }
 
     // For deserialization.
-    static PassRefPtr<File> create(const String& path, PassRefPtr<BlobDataHandle> blobDataHandle)
+    static PassRefPtr<File> create(const String& path, const String& name, const String& relativePath, bool hasSnaphotData, uint64_t size, double lastModified, PassRefPtr<BlobDataHandle> blobDataHandle)
     {
-        return adoptRef(new File(path, blobDataHandle));
+        return adoptRef(new File(path, name, relativePath, hasSnaphotData, size, lastModified, blobDataHandle));
     }
 
     static PassRefPtr<File> createWithRelativePath(const String& path, const String& relativePath);
@@ -86,9 +86,13 @@
     }
 
     virtual unsigned long long size() const OVERRIDE;
+    virtual PassRefPtr<Blob> slice(long long start = 0, long long end = std::numeric_limits<long long>::max(), const String& contentType = String()) const OVERRIDE;
+
     virtual bool isFile() const OVERRIDE { return true; }
     virtual bool hasBackingFile() const OVERRIDE { return m_hasBackingFile; }
 
+    virtual void appendTo(BlobData&) const OVERRIDE;
+
     const String& path() const { ASSERT(m_hasBackingFile); return m_path; }
     const String& name() const { return m_name; }
 
@@ -101,17 +105,17 @@
     // Note that this involves synchronous file operation. Think twice before calling this function.
     void captureSnapshot(long long& snapshotSize, double& snapshotModificationTime) const;
 
+    // Returns true if this has a valid snapshot metadata (i.e. m_snapshotSize >= 0).
+    bool hasValidSnapshotMetadata() const { return m_snapshotSize >= 0; }
+
 private:
     File(const String& path, ContentTypeLookupPolicy);
     File(const String& path, const String& name, ContentTypeLookupPolicy);
-    File(const String& path, PassRefPtr<BlobDataHandle>);
+    File(const String& path, const String& name, const String& relativePath, bool hasSnaphotData, uint64_t size, double lastModified, PassRefPtr<BlobDataHandle>);
     File(const String& name, double modificationTime, PassRefPtr<BlobDataHandle>);
     File(const String& name, const FileMetadata&);
     File(const KURL& fileSystemURL, const FileMetadata&);
 
-    // Returns true if this has a valid snapshot metadata (i.e. m_snapshotSize >= 0).
-    bool hasValidSnapshotMetadata() const { return m_snapshotSize >= 0; }
-
     bool m_hasBackingFile;
     String m_path;
     String m_name;
@@ -126,17 +130,7 @@
     String m_relativePath;
 };
 
-inline File* toFile(Blob* blob)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!blob || blob->isFile());
-    return static_cast<File*>(blob);
-}
-
-inline const File* toFile(const Blob* blob)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!blob || blob->isFile());
-    return static_cast<const File*>(blob);
-}
+DEFINE_TYPE_CASTS(File, Blob, blob, blob->isFile(), blob.isFile());
 
 } // namespace WebCore
 
diff --git a/Source/core/fileapi/File.idl b/Source/core/fileapi/File.idl
index 2a7fff4..4640ad3 100644
--- a/Source/core/fileapi/File.idl
+++ b/Source/core/fileapi/File.idl
@@ -24,11 +24,11 @@
  */
 
 [
+    CustomConstructor(sequence<any> blobParts, DOMString fileName, optional BlobPropertyBag options),
     GlobalContext=Window&WorkerGlobalScope,
-    CustomConstructor(sequence<any> blobParts, DOMString fileName, optional BlobPropertyBag options)
 ] interface File : Blob {
     readonly attribute DOMString name;
     [Custom=Getter, MeasureAs=FileGetLastModifiedDate] readonly attribute Date lastModifiedDate;
     [Custom=Getter, RuntimeEnabled=FileConstructor] readonly attribute long long lastModified;
-    [RuntimeEnabled=DirectoryUpload] readonly attribute DOMString webkitRelativePath;
+    readonly attribute DOMString webkitRelativePath;
 };
diff --git a/Source/core/fileapi/FileReader.cpp b/Source/core/fileapi/FileReader.cpp
index ed36fe5..c94eadb 100644
--- a/Source/core/fileapi/FileReader.cpp
+++ b/Source/core/fileapi/FileReader.cpp
@@ -160,8 +160,10 @@
 
 void FileReader::readAsArrayBuffer(Blob* blob, ExceptionState& exceptionState)
 {
-    if (!blob)
+    if (!blob) {
+        exceptionState.throwTypeError("The argument is not a Blob.");
         return;
+    }
 
     WTF_LOG(FileAPI, "FileReader: reading as array buffer: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
 
@@ -170,8 +172,10 @@
 
 void FileReader::readAsBinaryString(Blob* blob, ExceptionState& exceptionState)
 {
-    if (!blob)
+    if (!blob) {
+        exceptionState.throwTypeError("The argument is not a Blob.");
         return;
+    }
 
     WTF_LOG(FileAPI, "FileReader: reading as binary: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
 
@@ -180,8 +184,10 @@
 
 void FileReader::readAsText(Blob* blob, const String& encoding, ExceptionState& exceptionState)
 {
-    if (!blob)
+    if (!blob) {
+        exceptionState.throwTypeError("The argument is not a Blob.");
         return;
+    }
 
     WTF_LOG(FileAPI, "FileReader: reading as text: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
 
@@ -196,8 +202,10 @@
 
 void FileReader::readAsDataURL(Blob* blob, ExceptionState& exceptionState)
 {
-    if (!blob)
+    if (!blob) {
+        exceptionState.throwTypeError("The argument is not a Blob.");
         return;
+    }
 
     WTF_LOG(FileAPI, "FileReader: reading as data URL: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
 
@@ -208,7 +216,7 @@
 {
     // If multiple concurrent read methods are called on the same FileReader, InvalidStateError should be thrown when the state is LOADING.
     if (m_state == LOADING) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "The object is already busy reading Blobs.");
         return;
     }
 
diff --git a/Source/core/fileapi/FileReader.h b/Source/core/fileapi/FileReader.h
index 65fd97a..a4d46df 100644
--- a/Source/core/fileapi/FileReader.h
+++ b/Source/core/fileapi/FileReader.h
@@ -48,7 +48,7 @@
 class ExceptionState;
 class ExecutionContext;
 
-class FileReader : public RefCounted<FileReader>, public ScriptWrappable, public ActiveDOMObject, public EventTargetWithInlineData, public FileReaderLoaderClient {
+class FileReader FINAL : public RefCounted<FileReader>, public ScriptWrappable, public ActiveDOMObject, public EventTargetWithInlineData, public FileReaderLoaderClient {
     REFCOUNTED_EVENT_TARGET(FileReader);
 public:
     static PassRefPtr<FileReader> create(ExecutionContext*);
@@ -77,17 +77,17 @@
     String stringResult();
 
     // ActiveDOMObject
-    virtual void stop();
+    virtual void stop() OVERRIDE;
 
     // EventTarget
     virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual ExecutionContext* executionContext() const OVERRIDE { return ActiveDOMObject::executionContext(); }
 
     // FileReaderLoaderClient
-    virtual void didStartLoading();
-    virtual void didReceiveData();
-    virtual void didFinishLoading();
-    virtual void didFail(FileError::ErrorCode);
+    virtual void didStartLoading() OVERRIDE;
+    virtual void didReceiveData() OVERRIDE;
+    virtual void didFinishLoading() OVERRIDE;
+    virtual void didFail(FileError::ErrorCode) OVERRIDE;
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
diff --git a/Source/core/fileapi/FileReaderLoader.cpp b/Source/core/fileapi/FileReaderLoader.cpp
index 29827a4..3b133e4 100644
--- a/Source/core/fileapi/FileReaderLoader.cpp
+++ b/Source/core/fileapi/FileReaderLoader.cpp
@@ -34,10 +34,10 @@
 
 #include "FetchInitiatorTypeNames.h"
 #include "core/dom/ExecutionContext.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/fileapi/Blob.h"
 #include "core/fileapi/FileReaderLoaderClient.h"
 #include "core/fileapi/Stream.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/loader/ThreadableLoader.h"
 #include "platform/blob/BlobRegistry.h"
 #include "platform/blob/BlobURL.h"
@@ -102,10 +102,9 @@
     ResourceRequest request(m_urlForReading);
     request.setHTTPMethod("GET");
     if (m_hasRange)
-        request.setHTTPHeaderField("Range", String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd));
+        request.setHTTPHeaderField("Range", AtomicString(String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd)));
 
     ThreadableLoaderOptions options;
-    options.sendLoadCallbacks = SendCallbacks;
     options.sniffContent = DoNotSniffContent;
     options.preflightPolicy = ConsiderPreflight;
     options.allowCredentials = AllowStoredCredentials;
diff --git a/Source/core/fileapi/FileReaderLoader.h b/Source/core/fileapi/FileReaderLoader.h
index 6bb4459..238ee7b 100644
--- a/Source/core/fileapi/FileReaderLoader.h
+++ b/Source/core/fileapi/FileReaderLoader.h
@@ -50,7 +50,7 @@
 class TextResourceDecoder;
 class ThreadableLoader;
 
-class FileReaderLoader : public ThreadableLoaderClient {
+class FileReaderLoader FINAL : public ThreadableLoaderClient {
 public:
     enum ReadType {
         ReadAsArrayBuffer,
@@ -63,17 +63,17 @@
 
     // If client is given, do the loading asynchronously. Otherwise, load synchronously.
     FileReaderLoader(ReadType, FileReaderLoaderClient*);
-    ~FileReaderLoader();
+    virtual ~FileReaderLoader();
 
     void start(ExecutionContext*, PassRefPtr<BlobDataHandle>);
     void start(ExecutionContext*, const Stream&, unsigned readSize);
     void cancel();
 
     // ThreadableLoaderClient
-    virtual void didReceiveResponse(unsigned long, const ResourceResponse&);
-    virtual void didReceiveData(const char*, int);
-    virtual void didFinishLoading(unsigned long, double);
-    virtual void didFail(const ResourceError&);
+    virtual void didReceiveResponse(unsigned long, const ResourceResponse&) OVERRIDE;
+    virtual void didReceiveData(const char*, int) OVERRIDE;
+    virtual void didFinishLoading(unsigned long, double) OVERRIDE;
+    virtual void didFail(const ResourceError&) OVERRIDE;
 
     String stringResult();
     PassRefPtr<ArrayBuffer> arrayBufferResult() const;
diff --git a/Source/core/fileapi/FileReaderSync.h b/Source/core/fileapi/FileReaderSync.h
index 060633e..227a591 100644
--- a/Source/core/fileapi/FileReaderSync.h
+++ b/Source/core/fileapi/FileReaderSync.h
@@ -43,14 +43,14 @@
 class FileReaderLoader;
 class ExecutionContext;
 
-class FileReaderSync : public RefCounted<FileReaderSync>, public ScriptWrappable {
+class FileReaderSync FINAL : public RefCounted<FileReaderSync>, public ScriptWrappable {
 public:
     static PassRefPtr<FileReaderSync> create()
     {
         return adoptRef(new FileReaderSync());
     }
 
-    virtual ~FileReaderSync() { }
+    ~FileReaderSync() { }
 
     PassRefPtr<ArrayBuffer> readAsArrayBuffer(ExecutionContext*, Blob*, ExceptionState&);
     String readAsBinaryString(ExecutionContext*, Blob*, ExceptionState&);
diff --git a/Source/core/fileapi/Stream.h b/Source/core/fileapi/Stream.h
index 3e9b3e0..d3287ba 100644
--- a/Source/core/fileapi/Stream.h
+++ b/Source/core/fileapi/Stream.h
@@ -42,7 +42,7 @@
 
 class ExecutionContext;
 
-class Stream : public ScriptWrappable, public ActiveDOMObject, public RefCounted<Stream> {
+class Stream FINAL : public ScriptWrappable, public ActiveDOMObject, public RefCounted<Stream> {
 public:
     static PassRefPtr<Stream> create(ExecutionContext* context, const String& mediaType)
     {
diff --git a/Source/core/frame/AdjustViewSizeOrNot.h b/Source/core/frame/AdjustViewSizeOrNot.h
deleted file mode 100644
index 0137ad9..0000000
--- a/Source/core/frame/AdjustViewSizeOrNot.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-#ifndef AdjustViewSizeOrNot_h
-#define AdjustViewSizeOrNot_h
-
-namespace WebCore {
-
-enum AdjustViewSizeOrNot {
-    DoNotAdjustViewSize,
-    AdjustViewSize
-};
-
-} // namespace WebCore
-
-#endif // AdjustViewSizeOrNot_h
diff --git a/Source/core/frame/BarProp.cpp b/Source/core/frame/BarProp.cpp
index cc98718..2caccb1 100644
--- a/Source/core/frame/BarProp.cpp
+++ b/Source/core/frame/BarProp.cpp
@@ -31,7 +31,7 @@
 
 #include "core/page/Chrome.h"
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
+#include "core/frame/FrameHost.h"
 
 namespace WebCore {
 
@@ -42,30 +42,26 @@
     ScriptWrappable::init(this);
 }
 
-BarProp::Type BarProp::type() const
-{
-    return m_type;
-}
-
 bool BarProp::visible() const
 {
+    ASSERT(m_frame);
     if (!m_frame)
         return false;
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return false;
 
     switch (m_type) {
     case Locationbar:
     case Personalbar:
     case Toolbar:
-        return page->chrome().toolbarsVisible();
+        return host->chrome().toolbarsVisible();
     case Menubar:
-        return page->chrome().menubarVisible();
+        return host->chrome().menubarVisible();
     case Scrollbars:
-        return page->chrome().scrollbarsVisible();
+        return host->chrome().scrollbarsVisible();
     case Statusbar:
-        return page->chrome().statusbarVisible();
+        return host->chrome().statusbarVisible();
     }
 
     ASSERT_NOT_REACHED();
diff --git a/Source/core/frame/BarProp.h b/Source/core/frame/BarProp.h
index 1d188e1..55ba5d6 100644
--- a/Source/core/frame/BarProp.h
+++ b/Source/core/frame/BarProp.h
@@ -44,7 +44,6 @@
 
         static PassRefPtr<BarProp> create(Frame* frame, Type type) { return adoptRef(new BarProp(frame, type)); }
 
-        Type type() const;
         bool visible() const;
 
     private:
diff --git a/Source/core/frame/Console.cpp b/Source/core/frame/Console.cpp
index 530c6c5..7aaa7b2 100644
--- a/Source/core/frame/Console.cpp
+++ b/Source/core/frame/Console.cpp
@@ -30,24 +30,20 @@
 #include "core/frame/Console.h"
 
 #include "bindings/v8/ScriptCallStackFactory.h"
-#include "bindings/v8/ScriptProfiler.h"
 #include "core/frame/ConsoleTypes.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/PageConsole.h"
 #include "core/inspector/ConsoleAPITypes.h"
-#include "core/inspector/InspectorConsoleInstrumentation.h"
 #include "core/inspector/ScriptArguments.h"
 #include "core/inspector/ScriptCallStack.h"
-#include "core/inspector/ScriptProfile.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/frame/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/PageConsole.h"
 #include "core/timing/MemoryInfo.h"
+#include "platform/TraceEvent.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/WTFString.h"
 
-#include "platform/TraceEvent.h"
-
 namespace WebCore {
 
 Console::Console(Frame* frame)
@@ -69,20 +65,15 @@
 
 void Console::reportMessageToClient(MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack)
 {
-    if (!m_frame || !m_frame->page() || !callStack.get())
+    if (!m_frame || !m_frame->host() || !callStack.get())
         return;
 
     String stackTrace;
-    if (m_frame->page()->chrome().client().shouldReportDetailedMessageForSource(callStack->at(0).sourceURL())) {
+    if (m_frame->host()->chrome().client().shouldReportDetailedMessageForSource(callStack->at(0).sourceURL())) {
         RefPtr<ScriptCallStack> fullStack = createScriptCallStack(ScriptCallStack::maxCallStackSizeToCapture);
         stackTrace = PageConsole::formatStackTraceString(message, fullStack);
     }
-    m_frame->page()->chrome().client().addMessageToConsole(ConsoleAPIMessageSource, level, message, callStack->at(0).lineNumber(), callStack->at(0).sourceURL(), stackTrace);
-}
-
-bool Console::profilerEnabled()
-{
-    return InspectorInstrumentation::profilerEnabled(m_frame->page());
+    m_frame->host()->chrome().client().addMessageToConsole(ConsoleAPIMessageSource, level, message, callStack->at(0).lineNumber(), callStack->at(0).sourceURL(), stackTrace);
 }
 
 PassRefPtr<MemoryInfo> Console::memory() const
diff --git a/Source/core/frame/Console.h b/Source/core/frame/Console.h
index 128bf82..3b65af9 100644
--- a/Source/core/frame/Console.h
+++ b/Source/core/frame/Console.h
@@ -44,7 +44,7 @@
 class Page;
 class ScriptArguments;
 
-class Console : public RefCounted<Console>, public ConsoleBase, public ScriptWrappable, public DOMWindowProperty {
+class Console FINAL : public RefCounted<Console>, public ConsoleBase, public ScriptWrappable, public DOMWindowProperty {
 public:
     using RefCounted<Console>::ref;
     using RefCounted<Console>::deref;
@@ -55,16 +55,14 @@
     PassRefPtr<MemoryInfo> memory() const;
 
 protected:
-    virtual ExecutionContext* context();
+    virtual ExecutionContext* context() OVERRIDE;
     virtual void reportMessageToClient(MessageLevel, const String& message, PassRefPtr<ScriptCallStack>) OVERRIDE;
-    virtual bool profilerEnabled();
 
 private:
     explicit Console(Frame*);
-    inline Page* page() const;
 
-    virtual void refConsole() { ref(); }
-    virtual void derefConsole() { deref(); }
+    virtual void refConsole() OVERRIDE { ref(); }
+    virtual void derefConsole() OVERRIDE { deref(); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/frame/ConsoleBase.cpp b/Source/core/frame/ConsoleBase.cpp
index c4bab4e..8f54d86 100644
--- a/Source/core/frame/ConsoleBase.cpp
+++ b/Source/core/frame/ConsoleBase.cpp
@@ -30,11 +30,9 @@
 #include "core/frame/Console.h"
 
 #include "bindings/v8/ScriptCallStackFactory.h"
-#include "bindings/v8/ScriptProfiler.h"
 #include "core/dom/Document.h"
 #include "core/inspector/InspectorConsoleInstrumentation.h"
 #include "core/inspector/ScriptArguments.h"
-#include "core/inspector/ScriptProfile.h"
 #include "platform/TraceEvent.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/WTFString.h"
@@ -115,37 +113,12 @@
 
 void ConsoleBase::profile(ScriptState* state, const String& title)
 {
-    ExecutionContext* context = this->context();
-    if (!context)
-        return;
-
-    // FIXME: log a console message when profiling is disabled.
-    if (!profilerEnabled())
-        return;
-
-    String resolvedTitle = title;
-    if (title.isNull()) // no title so give it the next user initiated profile title.
-        resolvedTitle = InspectorInstrumentation::getCurrentUserInitiatedProfileName(context, true);
-
-    ScriptProfiler::start(resolvedTitle);
-    InspectorInstrumentation::addMessageToConsole(context, ConsoleAPIMessageSource, ProfileMessageType, DebugMessageLevel, resolvedTitle, String(), 0, 0, state);
+    InspectorInstrumentation::consoleProfile(context(), title, state);
 }
 
 void ConsoleBase::profileEnd(ScriptState* state, const String& title)
 {
-    ExecutionContext* context = this->context();
-    if (!context)
-        return;
-
-    if (!profilerEnabled())
-        return;
-
-    RefPtr<ScriptProfile> profile = ScriptProfiler::stop(title);
-    if (!profile)
-        return;
-
-    RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(1));
-    InspectorInstrumentation::addProfile(context, profile, callStack);
+    InspectorInstrumentation::consoleProfileEnd(context(), title);
 }
 
 void ConsoleBase::time(const String& title)
diff --git a/Source/core/frame/ConsoleBase.h b/Source/core/frame/ConsoleBase.h
index 37d95ec..30858d0 100644
--- a/Source/core/frame/ConsoleBase.h
+++ b/Source/core/frame/ConsoleBase.h
@@ -77,7 +77,6 @@
     virtual ~ConsoleBase();
     virtual ExecutionContext* context() = 0;
     virtual void reportMessageToClient(MessageLevel, const String& message, PassRefPtr<ScriptCallStack>) = 0;
-    virtual bool profilerEnabled() = 0;
 
 private:
     virtual void refConsole() = 0;
diff --git a/Source/core/frame/ContentSecurityPolicy.cpp b/Source/core/frame/ContentSecurityPolicy.cpp
index 4c3cbe4..5414ba7 100644
--- a/Source/core/frame/ContentSecurityPolicy.cpp
+++ b/Source/core/frame/ContentSecurityPolicy.cpp
@@ -148,9 +148,12 @@
 
 // CSP 1.1 Directives
 static const char baseURI[] = "base-uri";
+static const char childSrc[] = "child-src";
 static const char formAction[] = "form-action";
+static const char frameAncestors[] = "frame-ancestors";
 static const char pluginTypes[] = "plugin-types";
 static const char reflectedXSS[] = "reflected-xss";
+static const char referrer[] = "referrer";
 
 bool isDirectiveName(const String& name)
 {
@@ -166,9 +169,12 @@
         || equalIgnoringCase(name, scriptSrc)
         || equalIgnoringCase(name, styleSrc)
         || equalIgnoringCase(name, baseURI)
+        || equalIgnoringCase(name, childSrc)
         || equalIgnoringCase(name, formAction)
+        || equalIgnoringCase(name, frameAncestors)
         || equalIgnoringCase(name, pluginTypes)
         || equalIgnoringCase(name, reflectedXSS)
+        || equalIgnoringCase(name, referrer)
     );
 }
 
@@ -186,6 +192,13 @@
 
 } // namespace
 
+static ReferrerPolicy mergeReferrerPolicies(ReferrerPolicy a, ReferrerPolicy b)
+{
+    if (a != b)
+        return ReferrerPolicyNever;
+    return a;
+}
+
 static bool isSourceListNone(const UChar* begin, const UChar* end)
 {
     skipWhile<UChar, isASCIISpace>(begin, end);
@@ -297,11 +310,13 @@
 
     bool matches(const KURL&);
     bool allowInline() const { return m_allowInline; }
-    bool allowEval() const { return m_allowEval; }
+    bool allowScriptEval() const { return m_allowScriptEval; }
     bool allowNonce(const String& nonce) const { return !nonce.isNull() && m_nonces.contains(nonce); }
     bool allowHash(const SourceHashValue& hashValue) const { return m_hashes.contains(hashValue); }
     uint8_t hashAlgorithmsUsed() const { return m_hashAlgorithmsUsed; }
 
+    bool isHashOrNoncePresent() const { return !m_nonces.isEmpty() || m_hashAlgorithmsUsed != ContentSecurityPolicy::HashAlgorithmsNone; }
+
 private:
     bool parseSource(const UChar* begin, const UChar* end, String& scheme, String& host, int& port, String& path, bool& hostHasWildcard, bool& portHasWildcard);
     bool parseScheme(const UChar* begin, const UChar* end, String& scheme);
@@ -323,7 +338,7 @@
     String m_directiveName;
     bool m_allowStar;
     bool m_allowInline;
-    bool m_allowEval;
+    bool m_allowScriptEval;
     HashSet<String> m_nonces;
     HashSet<SourceHashValue> m_hashes;
     uint8_t m_hashAlgorithmsUsed;
@@ -334,7 +349,7 @@
     , m_directiveName(directiveName)
     , m_allowStar(false)
     , m_allowInline(false)
-    , m_allowEval(false)
+    , m_allowScriptEval(false)
     , m_hashAlgorithmsUsed(0)
 {
 }
@@ -715,7 +730,7 @@
 
 void CSPSourceList::addSourceUnsafeEval()
 {
-    m_allowEval = true;
+    m_allowScriptEval = true;
 }
 
 void CSPSourceList::addSourceNonce(const String& nonce)
@@ -843,9 +858,10 @@
     }
 
     bool allowInline() const { return m_sourceList.allowInline(); }
-    bool allowEval() const { return m_sourceList.allowEval(); }
+    bool allowScriptEval() const { return m_sourceList.allowScriptEval(); }
     bool allowNonce(const String& nonce) const { return m_sourceList.allowNonce(nonce.stripWhiteSpace()); }
     bool allowHash(const SourceHashValue& hashValue) const { return m_sourceList.allowHash(hashValue); }
+    bool isHashOrNoncePresent() const { return m_sourceList.isHashOrNoncePresent(); }
 
     uint8_t hashAlgorithmsUsed() const { return m_sourceList.hashAlgorithmsUsed(); }
 
@@ -856,18 +872,20 @@
 class CSPDirectiveList {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<CSPDirectiveList> create(ContentSecurityPolicy*, const UChar* begin, const UChar* end, ContentSecurityPolicy::HeaderType);
+    static PassOwnPtr<CSPDirectiveList> create(ContentSecurityPolicy*, const UChar* begin, const UChar* end, ContentSecurityPolicy::HeaderType, ContentSecurityPolicy::HeaderSource);
 
     void parse(const UChar* begin, const UChar* end);
 
     const String& header() const { return m_header; }
     ContentSecurityPolicy::HeaderType headerType() const { return m_headerType; }
+    ContentSecurityPolicy::HeaderSource headerSource() const { return m_headerSource; }
 
     bool allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
     bool allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
     bool allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
     bool allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
-    bool allowEval(ScriptState*, ContentSecurityPolicy::ReportingStatus) const;
+    bool allowScriptEval(ScriptState*, ContentSecurityPolicy::ReportingStatus) const;
+    bool allowStyleEval(ScriptState*, ContentSecurityPolicy::ReportingStatus) const;
     bool allowPluginType(const String& type, const String& typeAttribute, const KURL&, ContentSecurityPolicy::ReportingStatus) const;
 
     bool allowScriptFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
@@ -880,23 +898,29 @@
     bool allowConnectToSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
     bool allowFormAction(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
     bool allowBaseURI(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+    bool allowAncestors(Frame*, ContentSecurityPolicy::ReportingStatus) const;
+    bool allowChildContextFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
     bool allowScriptNonce(const String&) const;
     bool allowStyleNonce(const String&) const;
     bool allowScriptHash(const SourceHashValue&) const;
+    bool allowStyleHash(const SourceHashValue&) const;
 
-    void gatherReportURIs(DOMStringList&) const;
     const String& evalDisabledErrorMessage() const { return m_evalDisabledErrorMessage; }
+    const String& styleEvalDisabledErrorMessage() const { return m_styleEvalDisabledErrorMessage; }
     ReflectedXSSDisposition reflectedXSSDisposition() const { return m_reflectedXSSDisposition; }
+    ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
+    bool didSetReferrerPolicy() const { return m_didSetReferrerPolicy; }
     bool isReportOnly() const { return m_reportOnly; }
     const Vector<KURL>& reportURIs() const { return m_reportURIs; }
 
 private:
-    CSPDirectiveList(ContentSecurityPolicy*, ContentSecurityPolicy::HeaderType);
+    CSPDirectiveList(ContentSecurityPolicy*, ContentSecurityPolicy::HeaderType, ContentSecurityPolicy::HeaderSource);
 
     bool parseDirective(const UChar* begin, const UChar* end, String& name, String& value);
     void parseReportURI(const String& name, const String& value);
     void parsePluginTypes(const String& name, const String& value);
     void parseReflectedXSS(const String& name, const String& value);
+    void parseReferrer(const String& name, const String& value);
     void addDirective(const String& name, const String& value);
     void applySandboxPolicy(const String& name, const String& sandboxPolicy);
 
@@ -904,6 +928,7 @@
     void setCSPDirective(const String& name, const String& value, OwnPtr<CSPDirectiveType>&);
 
     SourceListDirective* operativeDirective(SourceListDirective*) const;
+    SourceListDirective* operativeDirective(SourceListDirective*, SourceListDirective* override) const;
     void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL) const;
     void reportViolationWithLocation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const String& contextURL, const WTF::OrdinalNumber& contextLine) const;
     void reportViolationWithState(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, ScriptState*) const;
@@ -914,14 +939,17 @@
     bool checkHash(SourceListDirective*, const SourceHashValue&) const;
     bool checkSource(SourceListDirective*, const KURL&) const;
     bool checkMediaType(MediaListDirective*, const String& type, const String& typeAttribute) const;
+    bool checkAncestors(SourceListDirective*, Frame*) const;
 
     void setEvalDisabledErrorMessage(const String& errorMessage) { m_evalDisabledErrorMessage = errorMessage; }
+    void setStyleEvalDisabledErrorMessage(const String& errorMessage) { m_styleEvalDisabledErrorMessage = errorMessage; }
 
     bool checkEvalAndReportViolation(SourceListDirective*, const String& consoleMessage, ScriptState*) const;
     bool checkInlineAndReportViolation(SourceListDirective*, const String& consoleMessage, const String& contextURL, const WTF::OrdinalNumber& contextLine, bool isScript) const;
 
     bool checkSourceAndReportViolation(SourceListDirective*, const KURL&, const String& effectiveDirective) const;
     bool checkMediaTypeAndReportViolation(MediaListDirective*, const String& type, const String& typeAttribute, const String& consoleMessage) const;
+    bool checkAncestorsAndReportViolation(SourceListDirective*, Frame*) const;
 
     bool denyIfEnforcingPolicy() const { return m_reportOnly; }
 
@@ -929,17 +957,23 @@
 
     String m_header;
     ContentSecurityPolicy::HeaderType m_headerType;
+    ContentSecurityPolicy::HeaderSource m_headerSource;
 
     bool m_reportOnly;
     bool m_haveSandboxPolicy;
     ReflectedXSSDisposition m_reflectedXSSDisposition;
 
+    bool m_didSetReferrerPolicy;
+    ReferrerPolicy m_referrerPolicy;
+
     OwnPtr<MediaListDirective> m_pluginTypes;
     OwnPtr<SourceListDirective> m_baseURI;
+    OwnPtr<SourceListDirective> m_childSrc;
     OwnPtr<SourceListDirective> m_connectSrc;
     OwnPtr<SourceListDirective> m_defaultSrc;
     OwnPtr<SourceListDirective> m_fontSrc;
     OwnPtr<SourceListDirective> m_formAction;
+    OwnPtr<SourceListDirective> m_frameAncestors;
     OwnPtr<SourceListDirective> m_frameSrc;
     OwnPtr<SourceListDirective> m_imgSrc;
     OwnPtr<SourceListDirective> m_mediaSrc;
@@ -950,27 +984,31 @@
     Vector<KURL> m_reportURIs;
 
     String m_evalDisabledErrorMessage;
+    String m_styleEvalDisabledErrorMessage;
 };
 
-CSPDirectiveList::CSPDirectiveList(ContentSecurityPolicy* policy, ContentSecurityPolicy::HeaderType type)
+CSPDirectiveList::CSPDirectiveList(ContentSecurityPolicy* policy, ContentSecurityPolicy::HeaderType type, ContentSecurityPolicy::HeaderSource source)
     : m_policy(policy)
     , m_headerType(type)
+    , m_headerSource(source)
     , m_reportOnly(false)
     , m_haveSandboxPolicy(false)
     , m_reflectedXSSDisposition(ReflectedXSSUnset)
+    , m_didSetReferrerPolicy(false)
+    , m_referrerPolicy(ReferrerPolicyDefault)
 {
     m_reportOnly = type == ContentSecurityPolicy::Report;
 }
 
-PassOwnPtr<CSPDirectiveList> CSPDirectiveList::create(ContentSecurityPolicy* policy, const UChar* begin, const UChar* end, ContentSecurityPolicy::HeaderType type)
+PassOwnPtr<CSPDirectiveList> CSPDirectiveList::create(ContentSecurityPolicy* policy, const UChar* begin, const UChar* end, ContentSecurityPolicy::HeaderType type, ContentSecurityPolicy::HeaderSource source)
 {
-    OwnPtr<CSPDirectiveList> directives = adoptPtr(new CSPDirectiveList(policy, type));
+    OwnPtr<CSPDirectiveList> directives = adoptPtr(new CSPDirectiveList(policy, type, source));
     directives->parse(begin, end);
 
-    if (!directives->checkEval(directives->operativeDirective(directives->m_scriptSrc.get()))) {
-        String message = "Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: \"" + directives->operativeDirective(directives->m_scriptSrc.get())->text() + "\".\n";
-        directives->setEvalDisabledErrorMessage(message);
-    }
+    if (!directives->checkEval(directives->operativeDirective(directives->m_scriptSrc.get())))
+        directives->setEvalDisabledErrorMessage("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: \"" + directives->operativeDirective(directives->m_scriptSrc.get())->text() + "\".\n");
+    if (!directives->checkEval(directives->operativeDirective(directives->m_styleSrc.get())))
+        directives->setStyleEvalDisabledErrorMessage("Refused to evaluate a string as CSS because 'unsafe-eval' is not an allowed source of style in the following Content Security Policy directive: \"" + directives->operativeDirective(directives->m_styleSrc.get())->text() + "\".\n");
 
     if (directives->isReportOnly() && directives->reportURIs().isEmpty())
         policy->reportMissingReportURI(String(begin, end - begin));
@@ -1001,12 +1039,12 @@
 
 bool CSPDirectiveList::checkEval(SourceListDirective* directive) const
 {
-    return !directive || directive->allowEval();
+    return !directive || directive->allowScriptEval();
 }
 
 bool CSPDirectiveList::checkInline(SourceListDirective* directive) const
 {
-    return !directive || directive->allowInline();
+    return !directive || (directive->allowInline() && !directive->isHashOrNoncePresent());
 }
 
 bool CSPDirectiveList::checkNonce(SourceListDirective* directive, const String& nonce) const
@@ -1024,6 +1062,18 @@
     return !directive || directive->allows(url);
 }
 
+bool CSPDirectiveList::checkAncestors(SourceListDirective* directive, Frame* frame) const
+{
+    if (!frame || !directive)
+        return true;
+
+    for (Frame* current = frame->tree().parent(); current; current = current->tree().parent()) {
+        if (!directive->allows(current->document()->url()))
+            return false;
+    }
+    return true;
+}
+
 bool CSPDirectiveList::checkMediaType(MediaListDirective* directive, const String& type, const String& typeAttribute) const
 {
     if (!directive)
@@ -1038,6 +1088,11 @@
     return directive ? directive : m_defaultSrc.get();
 }
 
+SourceListDirective* CSPDirectiveList::operativeDirective(SourceListDirective* directive, SourceListDirective* override) const
+{
+    return directive ? directive : override;
+}
+
 bool CSPDirectiveList::checkEvalAndReportViolation(SourceListDirective* directive, const String& consoleMessage, ScriptState* state) const
 {
     if (checkEval(directive))
@@ -1074,8 +1129,14 @@
         return true;
 
     String suffix = String();
-    if (directive == m_defaultSrc)
-        suffix = " Note that '" + String(isScript ? "script" : "style") + "-src' was not explicitly set, so 'default-src' is used as a fallback.";
+    if (directive->allowInline() && directive->isHashOrNoncePresent()) {
+        // If inline is allowed, but a hash or nonce is present, we ignore 'unsafe-inline'. Throw a reasonable error.
+        suffix = " Note that 'unsafe-inline' is ignored if either a hash or nonce value is present in the source list.";
+    } else {
+        suffix = " Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.";
+        if (directive == m_defaultSrc)
+            suffix = suffix + " Note also that '" + String(isScript ? "script" : "style") + "-src' was not explicitly set, so 'default-src' is used as a fallback.";
+    }
 
     reportViolationWithLocation(directive->text(), isScript ? scriptSrc : styleSrc, consoleMessage + "\"" + directive->text() + "\"." + suffix + "\n", KURL(), contextURL, contextLine);
 
@@ -1095,6 +1156,8 @@
     String prefix;
     if (baseURI == effectiveDirective)
         prefix = "Refused to set the document's base URI to '";
+    else if (childSrc == effectiveDirective)
+        prefix = "Refused to create a child context containing '";
     else if (connectSrc == effectiveDirective)
         prefix = "Refused to connect to '";
     else if (fontSrc == effectiveDirective)
@@ -1122,6 +1185,15 @@
     return denyIfEnforcingPolicy();
 }
 
+bool CSPDirectiveList::checkAncestorsAndReportViolation(SourceListDirective* directive, Frame* frame) const
+{
+    if (checkAncestors(directive, frame))
+        return true;
+
+    reportViolation(directive->text(), "frame-ancestors", "Refused to display '" + frame->document()->url().elidedString() + " in a frame because an ancestor violates the following Content Security Policy directive: \"" + directive->text() + "\".", frame->document()->url());
+    return denyIfEnforcingPolicy();
+}
+
 bool CSPDirectiveList::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
     DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute JavaScript URL because it violates the following Content Security Policy directive: "));
@@ -1155,7 +1227,7 @@
         checkInline(operativeDirective(m_styleSrc.get()));
 }
 
-bool CSPDirectiveList::allowEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+bool CSPDirectiveList::allowScriptEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
     DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "));
 
@@ -1164,6 +1236,15 @@
         checkEval(operativeDirective(m_scriptSrc.get()));
 }
 
+bool CSPDirectiveList::allowStyleEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+    DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to evaluate a string as CSS because 'unsafe-eval' is not an allowed source of style in the following Content Security Policy directive: "));
+
+    return reportingStatus == ContentSecurityPolicy::SendReport ?
+        checkEvalAndReportViolation(operativeDirective(m_styleSrc.get()), consoleMessage, state) :
+        checkEval(operativeDirective(m_styleSrc.get()));
+}
+
 bool CSPDirectiveList::allowPluginType(const String& type, const String& typeAttribute, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
     return reportingStatus == ContentSecurityPolicy::SendReport ?
@@ -1191,9 +1272,21 @@
 {
     if (url.isBlankURL())
         return true;
+
+    // 'frame-src' is the only directive which overrides something other than the default sources.
+    // It overrides 'child-src', which overrides the default sources. So, we do this nested set
+    // of calls to 'operativeDirective()' to grab 'frame-src' if it exists, 'child-src' if it
+    // doesn't, and 'defaut-src' if neither are available.
+    //
+    // All of this only applies, of course, if we're in CSP 1.1. In CSP 1.0, 'frame-src'
+    // overrides 'default-src' directly.
+    SourceListDirective* whichDirective = m_policy->experimentalFeaturesEnabled() ?
+        operativeDirective(m_frameSrc.get(), operativeDirective(m_childSrc.get())) :
+        operativeDirective(m_frameSrc.get());
+
     return reportingStatus == ContentSecurityPolicy::SendReport ?
-        checkSourceAndReportViolation(operativeDirective(m_frameSrc.get()), url, frameSrc) :
-        checkSource(operativeDirective(m_frameSrc.get()), url);
+        checkSourceAndReportViolation(whichDirective, url, frameSrc) :
+        checkSource(whichDirective, url);
 }
 
 bool CSPDirectiveList::allowImageFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
@@ -1231,12 +1324,6 @@
         checkSource(operativeDirective(m_connectSrc.get()), url);
 }
 
-void CSPDirectiveList::gatherReportURIs(DOMStringList& list) const
-{
-    for (size_t i = 0; i < m_reportURIs.size(); ++i)
-        list.append(m_reportURIs[i].string());
-}
-
 bool CSPDirectiveList::allowFormAction(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
     return reportingStatus == ContentSecurityPolicy::SendReport ?
@@ -1251,6 +1338,20 @@
         checkSource(m_baseURI.get(), url);
 }
 
+bool CSPDirectiveList::allowAncestors(Frame* frame, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+    return reportingStatus == ContentSecurityPolicy::SendReport ?
+        checkAncestorsAndReportViolation(m_frameAncestors.get(), frame) :
+        checkAncestors(m_frameAncestors.get(), frame);
+}
+
+bool CSPDirectiveList::allowChildContextFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+    return reportingStatus == ContentSecurityPolicy::SendReport ?
+        checkSourceAndReportViolation(operativeDirective(m_childSrc.get()), url, childSrc) :
+        checkSource(operativeDirective(m_childSrc.get()), url);
+}
+
 bool CSPDirectiveList::allowScriptNonce(const String& nonce) const
 {
     return checkNonce(operativeDirective(m_scriptSrc.get()), nonce);
@@ -1266,6 +1367,11 @@
     return checkHash(operativeDirective(m_scriptSrc.get()), hashValue);
 }
 
+bool CSPDirectiveList::allowStyleHash(const SourceHashValue& hashValue) const
+{
+    return checkHash(operativeDirective(m_styleSrc.get()), hashValue);
+}
+
 // policy            = directive-list
 // directive-list    = [ directive *( ";" [ directive ] ) ]
 //
@@ -1386,6 +1492,10 @@
 
 void CSPDirectiveList::applySandboxPolicy(const String& name, const String& sandboxPolicy)
 {
+    if (m_reportOnly) {
+        m_policy->reportInvalidInReportOnly(name);
+        return;
+    }
     if (m_haveSandboxPolicy) {
         m_policy->reportDuplicateDirective(name);
         return;
@@ -1445,6 +1555,59 @@
     m_policy->reportInvalidReflectedXSS(value);
 }
 
+void CSPDirectiveList::parseReferrer(const String& name, const String& value)
+{
+    if (m_didSetReferrerPolicy) {
+        m_policy->reportDuplicateDirective(name);
+        m_referrerPolicy = ReferrerPolicyNever;
+        return;
+    }
+
+    m_didSetReferrerPolicy = true;
+
+    if (value.isEmpty()) {
+        m_policy->reportInvalidReferrer(value);
+        m_referrerPolicy = ReferrerPolicyNever;
+        return;
+    }
+
+    Vector<UChar> characters;
+    value.appendTo(characters);
+
+    const UChar* position = characters.data();
+    const UChar* end = position + characters.size();
+
+    skipWhile<UChar, isASCIISpace>(position, end);
+    const UChar* begin = position;
+    skipWhile<UChar, isNotASCIISpace>(position, end);
+
+    // value1
+    //       ^
+    if (equalIgnoringCase("always", begin, position - begin)) {
+        m_referrerPolicy = ReferrerPolicyAlways;
+    } else if (equalIgnoringCase("default", begin, position - begin)) {
+        m_referrerPolicy = ReferrerPolicyDefault;
+    } else if (equalIgnoringCase("never", begin, position - begin)) {
+        m_referrerPolicy = ReferrerPolicyNever;
+    } else if (equalIgnoringCase("origin", begin, position - begin)) {
+        m_referrerPolicy = ReferrerPolicyOrigin;
+    } else {
+        m_referrerPolicy = ReferrerPolicyNever;
+        m_policy->reportInvalidReferrer(value);
+        return;
+    }
+
+    skipWhile<UChar, isASCIISpace>(position, end);
+    if (position == end)
+        return;
+
+    // value1 value2
+    //        ^
+    m_referrerPolicy = ReferrerPolicyNever;
+    m_policy->reportInvalidReferrer(value);
+
+}
+
 void CSPDirectiveList::addDirective(const String& name, const String& value)
 {
     ASSERT(!name.isEmpty());
@@ -1462,6 +1625,7 @@
         setCSPDirective<SourceListDirective>(name, value, m_imgSrc);
     } else if (equalIgnoringCase(name, styleSrc)) {
         setCSPDirective<SourceListDirective>(name, value, m_styleSrc);
+        m_policy->usesStyleHashAlgorithms(m_styleSrc->hashAlgorithmsUsed());
     } else if (equalIgnoringCase(name, fontSrc)) {
         setCSPDirective<SourceListDirective>(name, value, m_fontSrc);
     } else if (equalIgnoringCase(name, mediaSrc)) {
@@ -1475,12 +1639,18 @@
     } else if (m_policy->experimentalFeaturesEnabled()) {
         if (equalIgnoringCase(name, baseURI))
             setCSPDirective<SourceListDirective>(name, value, m_baseURI);
+        else if (equalIgnoringCase(name, childSrc))
+            setCSPDirective<SourceListDirective>(name, value, m_childSrc);
         else if (equalIgnoringCase(name, formAction))
             setCSPDirective<SourceListDirective>(name, value, m_formAction);
+        else if (equalIgnoringCase(name, frameAncestors))
+            setCSPDirective<SourceListDirective>(name, value, m_frameAncestors);
         else if (equalIgnoringCase(name, pluginTypes))
             setCSPDirective<MediaListDirective>(name, value, m_pluginTypes);
         else if (equalIgnoringCase(name, reflectedXSS))
             parseReflectedXSS(name, value);
+        else if (equalIgnoringCase(name, referrer))
+            parseReferrer(name, value);
         else
             m_policy->reportUnsupportedDirective(name);
     } else {
@@ -1491,7 +1661,8 @@
 ContentSecurityPolicy::ContentSecurityPolicy(ExecutionContextClient* client)
     : m_client(client)
     , m_overrideInlineStyleAllowed(false)
-    , m_sourceHashAlgorithmsUsed(HashAlgorithmsNone)
+    , m_scriptHashAlgorithmsUsed(HashAlgorithmsNone)
+    , m_styleHashAlgorithmsUsed(HashAlgorithmsNone)
 {
 }
 
@@ -1503,38 +1674,39 @@
 {
     ASSERT(m_policies.isEmpty());
     for (CSPDirectiveListVector::const_iterator iter = other->m_policies.begin(); iter != other->m_policies.end(); ++iter)
-        addPolicyFromHeaderValue((*iter)->header(), (*iter)->headerType());
+        addPolicyFromHeaderValue((*iter)->header(), (*iter)->headerType(), (*iter)->headerSource());
 }
 
 void ContentSecurityPolicy::didReceiveHeaders(const ContentSecurityPolicyResponseHeaders& headers)
 {
     if (!headers.contentSecurityPolicy().isEmpty())
-        didReceiveHeader(headers.contentSecurityPolicy(), ContentSecurityPolicy::Enforce);
+        didReceiveHeader(headers.contentSecurityPolicy(), ContentSecurityPolicy::Enforce, ContentSecurityPolicy::HeaderSourceHTTP);
     if (!headers.contentSecurityPolicyReportOnly().isEmpty())
-        didReceiveHeader(headers.contentSecurityPolicyReportOnly(), ContentSecurityPolicy::Report);
-
-    // FIXME: Remove this reporting (and the 'xWebKitCSP*' methods) after the next release branch.
-    if (m_client->isDocument()) {
-        Document* document = static_cast<Document*>(m_client);
-        if (!headers.xWebKitCSP().isEmpty())
-            UseCounter::countDeprecation(*document, UseCounter::PrefixedContentSecurityPolicy);
-        if (!headers.xWebKitCSPReportOnly().isEmpty())
-            UseCounter::countDeprecation(*document, UseCounter::PrefixedContentSecurityPolicyReportOnly);
-    }
+        didReceiveHeader(headers.contentSecurityPolicyReportOnly(), ContentSecurityPolicy::Report, ContentSecurityPolicy::HeaderSourceHTTP);
 }
 
-void ContentSecurityPolicy::didReceiveHeader(const String& header, HeaderType type)
+void ContentSecurityPolicy::didReceiveHeader(const String& header, HeaderType type, HeaderSource source)
 {
-    addPolicyFromHeaderValue(header, type);
+    addPolicyFromHeaderValue(header, type, source);
 }
 
-void ContentSecurityPolicy::addPolicyFromHeaderValue(const String& header, HeaderType type)
+void ContentSecurityPolicy::addPolicyFromHeaderValue(const String& header, HeaderType type, HeaderSource source)
 {
-    if (m_client->isDocument()) {
-        Document* document = static_cast<Document*>(m_client);
+    Document* document = this->document();
+    if (document) {
         UseCounter::count(*document, getUseCounterType(type));
+
+        // CSP 1.1 defines report-only in a <meta> element as invalid. Measure for now, disable in experimental mode.
+        if (source == ContentSecurityPolicy::HeaderSourceMeta && type == ContentSecurityPolicy::Report) {
+            UseCounter::count(*document, UseCounter::ContentSecurityPolicyReportOnlyInMeta);
+            if (experimentalFeaturesEnabled()) {
+                reportReportOnlyInMeta(header);
+                return;
+            }
+        }
     }
 
+
     Vector<UChar> characters;
     header.appendTo(characters);
 
@@ -1550,10 +1722,10 @@
 
         // header1,header2 OR header1
         //        ^                  ^
-        OwnPtr<CSPDirectiveList> policy = CSPDirectiveList::create(this, begin, position, type);
+        OwnPtr<CSPDirectiveList> policy = CSPDirectiveList::create(this, begin, position, type, source);
 
         // We disable 'eval()' even in the case of report-only policies, and rely on the check in the V8Initializer::codeGenerationCheckCallbackInMainThread callback to determine whether the call should execute or not.
-        if (!policy->allowEval(0, SuppressReport))
+        if (!policy->allowScriptEval(0, SuppressReport))
             m_client->disableEval(policy->evalDisabledErrorMessage());
 
         m_policies.append(policy.release());
@@ -1563,6 +1735,9 @@
         skipExactly<UChar>(position, end, ',');
         begin = position;
     }
+
+    if (document && type != Report && didSetReferrerPolicy())
+        document->setReferrerPolicy(referrerPolicy());
 }
 
 void ContentSecurityPolicy::setOverrideAllowInlineStyle(bool value)
@@ -1643,6 +1818,16 @@
     return true;
 }
 
+template<bool (CSPDirectiveList::*allowed)(Frame*, ContentSecurityPolicy::ReportingStatus) const>
+bool isAllowedByAllWithFrame(const CSPDirectiveListVector& policies, Frame* frame, ContentSecurityPolicy::ReportingStatus reportingStatus)
+{
+    for (size_t i = 0; i < policies.size(); ++i) {
+        if (!(policies[i].get()->*allowed)(frame, reportingStatus))
+            return false;
+    }
+    return true;
+}
+
 bool ContentSecurityPolicy::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
     return isAllowedByAllWithContext<&CSPDirectiveList::allowJavaScriptURLs>(m_policies, contextURL, contextLine, reportingStatus);
@@ -1665,20 +1850,39 @@
     return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineStyle>(m_policies, contextURL, contextLine, reportingStatus);
 }
 
-bool ContentSecurityPolicy::allowEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+bool ContentSecurityPolicy::allowScriptEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
-    return isAllowedByAllWithState<&CSPDirectiveList::allowEval>(m_policies, state, reportingStatus);
+    return isAllowedByAllWithState<&CSPDirectiveList::allowScriptEval>(m_policies, state, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowStyleEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+    if (!experimentalFeaturesEnabled()) {
+        if (Document* document = this->document())
+            UseCounter::count(*document, UseCounter::UnsafeEvalBlocksCSSOM);
+        return true;
+    }
+    return isAllowedByAllWithState<&CSPDirectiveList::allowStyleEval>(m_policies, state, reportingStatus);
 }
 
 String ContentSecurityPolicy::evalDisabledErrorMessage() const
 {
     for (size_t i = 0; i < m_policies.size(); ++i) {
-        if (!m_policies[i]->allowEval(0, SuppressReport))
+        if (!m_policies[i]->allowScriptEval(0, SuppressReport))
             return m_policies[i]->evalDisabledErrorMessage();
     }
     return String();
 }
 
+String ContentSecurityPolicy::styleEvalDisabledErrorMessage() const
+{
+    for (size_t i = 0; i < m_policies.size(); ++i) {
+        if (!m_policies[i]->allowStyleEval(0, SuppressReport))
+            return m_policies[i]->styleEvalDisabledErrorMessage();
+    }
+    return String();
+}
+
 bool ContentSecurityPolicy::allowPluginType(const String& type, const String& typeAttribute, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
 {
     for (size_t i = 0; i < m_policies.size(); ++i) {
@@ -1703,11 +1907,12 @@
     return isAllowedByAllWithNonce<&CSPDirectiveList::allowStyleNonce>(m_policies, nonce);
 }
 
+// TODO(jww) We don't currently have a WTF SHA256 implementation. Once we
+// have that, we should implement a proper check for sha256 hash values in
+// both allowScriptHash and allowStyleHash.
 bool ContentSecurityPolicy::allowScriptHash(const String& source) const
 {
-    // TODO(jww) We don't currently have a WTF SHA256 implementation. Once we
-    // have that, we should implement a proper check for sha256 hash values here.
-    if (HashAlgorithmsSha1 & m_sourceHashAlgorithmsUsed) {
+    if (HashAlgorithmsSha1 & m_scriptHashAlgorithmsUsed) {
         Vector<uint8_t, 20> digest;
         SHA1 sourceSha1;
         sourceSha1.addBytes(UTF8Encoding().normalizeAndEncode(source, WTF::EntitiesForUnencodables));
@@ -1720,9 +1925,29 @@
     return false;
 }
 
+bool ContentSecurityPolicy::allowStyleHash(const String& source) const
+{
+    if (HashAlgorithmsSha1 & m_styleHashAlgorithmsUsed) {
+        Vector<uint8_t, 20> digest;
+        SHA1 sourceSha1;
+        sourceSha1.addBytes(UTF8Encoding().normalizeAndEncode(source, WTF::EntitiesForUnencodables));
+        sourceSha1.computeHash(digest);
+
+        if (isAllowedByAllWithHash<&CSPDirectiveList::allowStyleHash>(m_policies, SourceHashValue(HashAlgorithmsSha1, Vector<uint8_t>(digest))))
+            return true;
+    }
+
+    return false;
+}
+
 void ContentSecurityPolicy::usesScriptHashAlgorithms(uint8_t algorithms)
 {
-    m_sourceHashAlgorithmsUsed |= algorithms;
+    m_scriptHashAlgorithmsUsed |= algorithms;
+}
+
+void ContentSecurityPolicy::usesStyleHashAlgorithms(uint8_t algorithms)
+{
+    m_styleHashAlgorithmsUsed |= algorithms;
 }
 
 bool ContentSecurityPolicy::allowObjectFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
@@ -1770,6 +1995,31 @@
     return isAllowedByAllWithURL<&CSPDirectiveList::allowBaseURI>(m_policies, url, reportingStatus);
 }
 
+bool ContentSecurityPolicy::allowAncestors(Frame* frame, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+    return isAllowedByAllWithFrame<&CSPDirectiveList::allowAncestors>(m_policies, frame, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowChildContextFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+    return isAllowedByAllWithURL<&CSPDirectiveList::allowChildContextFromSource>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowWorkerContextFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+    // CSP 1.1 moves workers from 'script-src' to the new 'child-src'. Measure the impact of this backwards-incompatible change.
+    if (m_client->isDocument()) {
+        Document* document = static_cast<Document*>(m_client);
+        UseCounter::count(*document, UseCounter::WorkerSubjectToCSP);
+        if (isAllowedByAllWithURL<&CSPDirectiveList::allowChildContextFromSource>(m_policies, url, SuppressReport) && !isAllowedByAllWithURL<&CSPDirectiveList::allowScriptFromSource>(m_policies, url, SuppressReport))
+            UseCounter::count(*document, UseCounter::WorkerAllowedByChildBlockedByScript);
+    }
+
+    return experimentalFeaturesEnabled() ?
+        isAllowedByAllWithURL<&CSPDirectiveList::allowChildContextFromSource>(m_policies, url, reportingStatus) :
+        isAllowedByAllWithURL<&CSPDirectiveList::allowScriptFromSource>(m_policies, url, reportingStatus);
+}
+
 bool ContentSecurityPolicy::isActive() const
 {
     return !m_policies.isEmpty();
@@ -1785,10 +2035,28 @@
     return disposition;
 }
 
-void ContentSecurityPolicy::gatherReportURIs(DOMStringList& list) const
+ReferrerPolicy ContentSecurityPolicy::referrerPolicy() const
 {
-    for (size_t i = 0; i < m_policies.size(); ++i)
-        m_policies[i]->gatherReportURIs(list);
+    ReferrerPolicy policy = ReferrerPolicyDefault;
+    bool first = true;
+    for (size_t i = 0; i < m_policies.size(); ++i) {
+        if (m_policies[i]->didSetReferrerPolicy()) {
+            if (first)
+                policy = m_policies[i]->referrerPolicy();
+            else
+                policy = mergeReferrerPolicies(policy, m_policies[i]->referrerPolicy());
+        }
+    }
+    return policy;
+}
+
+bool ContentSecurityPolicy::didSetReferrerPolicy() const
+{
+    for (size_t i = 0; i < m_policies.size(); ++i) {
+        if (m_policies[i]->didSetReferrerPolicy())
+            return true;
+    }
+    return false;
 }
 
 SecurityOrigin* ContentSecurityPolicy::securityOrigin() const
@@ -1808,8 +2076,8 @@
 
 void ContentSecurityPolicy::enforceSandboxFlags(SandboxFlags mask) const
 {
-    if (m_client->isDocument())
-        static_cast<Document*>(m_client)->enforceSandboxFlags(mask);
+    if (Document* document = this->document())
+        document->enforceSandboxFlags(mask);
 }
 
 static String stripURLForUseInReport(Document* document, const KURL& url)
@@ -1857,7 +2125,7 @@
     if (!m_client->isDocument())
         return;
 
-    Document* document = static_cast<Document*>(m_client);
+    Document* document = this->document();
     Frame* frame = document->frame();
     if (!frame)
         return;
@@ -1911,6 +2179,26 @@
     didSendViolationReport(stringifiedReport);
 }
 
+void ContentSecurityPolicy::reportInvalidReferrer(const String& invalidValue) const
+{
+    logToConsole("The 'referrer' Content Security Policy directive has the invalid value \"" + invalidValue + "\". Valid values are \"always\", \"default\", \"never\", and \"origin\".");
+}
+
+void ContentSecurityPolicy::reportReportOnlyInMeta(const String& header) const
+{
+    logToConsole("The report-only Content Security Policy '" + header + "' was delivered via a <meta> element, which is disallowed. The policy has been ignored.");
+}
+
+void ContentSecurityPolicy::reportMetaOutsideHead(const String& header) const
+{
+    logToConsole("The Content Security Policy '" + header + "' was delivered via a <meta> element outside the document's <head>, which is disallowed. The policy has been ignored.");
+}
+
+void ContentSecurityPolicy::reportInvalidInReportOnly(const String& name) const
+{
+    logToConsole("The Content Security Policy directive '" + name + "' is ignored when delivered in a report-only policy.");
+}
+
 void ContentSecurityPolicy::reportUnsupportedDirective(const String& name) const
 {
     DEFINE_STATIC_LOCAL(String, allow, ("allow"));
diff --git a/Source/core/frame/ContentSecurityPolicy.h b/Source/core/frame/ContentSecurityPolicy.h
index 0720123..6cf0205 100644
--- a/Source/core/frame/ContentSecurityPolicy.h
+++ b/Source/core/frame/ContentSecurityPolicy.h
@@ -27,7 +27,9 @@
 #define ContentSecurityPolicy_h
 
 #include "bindings/v8/ScriptState.h"
+#include "core/dom/Document.h"
 #include "platform/network/HTTPParsers.h"
+#include "platform/weborigin/ReferrerPolicy.h"
 #include "wtf/HashSet.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
@@ -68,6 +70,11 @@
         Enforce,
     };
 
+    enum HeaderSource {
+        HeaderSourceHTTP,
+        HeaderSourceMeta
+    };
+
     enum ReportingStatus {
         SendReport,
         SuppressReport
@@ -80,7 +87,7 @@
     };
 
     void didReceiveHeaders(const ContentSecurityPolicyResponseHeaders&);
-    void didReceiveHeader(const String&, HeaderType);
+    void didReceiveHeader(const String&, HeaderType, HeaderSource);
 
     // These functions are wrong because they assume that there is only one header.
     // FIXME: Replace them with functions that return vectors.
@@ -91,7 +98,8 @@
     bool allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
     bool allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
     bool allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
-    bool allowEval(ScriptState* = 0, ReportingStatus = SendReport) const;
+    bool allowScriptEval(ScriptState* = 0, ReportingStatus = SendReport) const;
+    bool allowStyleEval(ScriptState* = 0, ReportingStatus = SendReport) const;
     bool allowPluginType(const String& type, const String& typeAttribute, const KURL&, ReportingStatus = SendReport) const;
 
     bool allowScriptFromSource(const KURL&, ReportingStatus = SendReport) const;
@@ -104,20 +112,28 @@
     bool allowConnectToSource(const KURL&, ReportingStatus = SendReport) const;
     bool allowFormAction(const KURL&, ReportingStatus = SendReport) const;
     bool allowBaseURI(const KURL&, ReportingStatus = SendReport) const;
+    bool allowAncestors(Frame*, ReportingStatus = SendReport) const;
+    bool allowChildContextFromSource(const KURL&, ReportingStatus = SendReport) const;
+    bool allowWorkerContextFromSource(const KURL&, ReportingStatus = SendReport) const;
+
     // The nonce and hash allow functions are guaranteed to not have any side
     // effects, including reporting.
     bool allowScriptNonce(const String& nonce) const;
     bool allowStyleNonce(const String& nonce) const;
     bool allowScriptHash(const String& source) const;
+    bool allowStyleHash(const String& source) const;
 
     void usesScriptHashAlgorithms(uint8_t HashAlgorithms);
+    void usesStyleHashAlgorithms(uint8_t HashAlgorithms);
 
     ReflectedXSSDisposition reflectedXSSDisposition() const;
 
+    ReferrerPolicy referrerPolicy() const;
+    bool didSetReferrerPolicy() const;
+
     void setOverrideAllowInlineStyle(bool);
 
     bool isActive() const;
-    void gatherReportURIs(DOMStringList&) const;
 
     void reportDirectiveAsSourceExpression(const String& directiveName, const String& sourceExpression) const;
     void reportDuplicateDirective(const String&) const;
@@ -129,6 +145,10 @@
     void reportInvalidReflectedXSS(const String&) const;
     void reportMissingReportURI(const String&) const;
     void reportUnsupportedDirective(const String&) const;
+    void reportInvalidInReportOnly(const String&) const;
+    void reportInvalidReferrer(const String&) const;
+    void reportReportOnlyInMeta(const String&) const;
+    void reportMetaOutsideHead(const String&) const;
     void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header);
 
     void reportBlockedScriptExecutionToInspector(const String& directiveText) const;
@@ -138,18 +158,20 @@
     SecurityOrigin* securityOrigin() const;
     void enforceSandboxFlags(SandboxFlags) const;
     String evalDisabledErrorMessage() const;
+    String styleEvalDisabledErrorMessage() const;
 
     bool experimentalFeaturesEnabled() const;
 
     static bool shouldBypassMainWorld(ExecutionContext*);
 
-    ExecutionContextClient* client() { return m_client; }
+    ExecutionContextClient* client() const { return m_client; }
+    Document* document() const { return client()->isDocument() ? toDocument(client()) : 0; }
 
 private:
     explicit ContentSecurityPolicy(ExecutionContextClient*);
 
     void logToConsole(const String& message) const;
-    void addPolicyFromHeaderValue(const String&, HeaderType);
+    void addPolicyFromHeaderValue(const String&, HeaderType, HeaderSource);
 
     bool shouldSendViolationReport(const String&) const;
     void didSendViolationReport(const String&);
@@ -161,9 +183,10 @@
     HashSet<unsigned, AlreadyHashed> m_violationReportsSent;
 
     // We put the hash functions used on the policy object so that we only need
-    // to calculate a script hash once and then distribute it to all of the
-    // directives for validation.
-    uint8_t m_sourceHashAlgorithmsUsed;
+    // to calculate a hash once and then distribute it to all of the directives
+    // for validation.
+    uint8_t m_scriptHashAlgorithmsUsed;
+    uint8_t m_styleHashAlgorithmsUsed;
 };
 
 }
diff --git a/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp b/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp
index 1b58eac..0cd8808 100644
--- a/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp
+++ b/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp
@@ -33,8 +33,6 @@
 ContentSecurityPolicyResponseHeaders::ContentSecurityPolicyResponseHeaders(const ResourceResponse& response)
     : m_contentSecurityPolicy(response.httpHeaderField("Content-Security-Policy"))
     , m_contentSecurityPolicyReportOnly(response.httpHeaderField("Content-Security-Policy-Report-Only"))
-    , m_xWebKitCSP(response.httpHeaderField("X-WebKit-CSP"))
-    , m_xWebKitCSPReportOnly(response.httpHeaderField("X-WebKit-CSP-Report-Only"))
 {
 }
 
diff --git a/Source/core/frame/ContentSecurityPolicyResponseHeaders.h b/Source/core/frame/ContentSecurityPolicyResponseHeaders.h
index d5076d4..404fb38 100644
--- a/Source/core/frame/ContentSecurityPolicyResponseHeaders.h
+++ b/Source/core/frame/ContentSecurityPolicyResponseHeaders.h
@@ -39,14 +39,10 @@
 
     const String& contentSecurityPolicy() const { return m_contentSecurityPolicy; }
     const String& contentSecurityPolicyReportOnly() const { return m_contentSecurityPolicyReportOnly; }
-    const String& xWebKitCSP() const { return m_xWebKitCSP; }
-    const String& xWebKitCSPReportOnly() const { return m_xWebKitCSPReportOnly; }
 
 private:
     String m_contentSecurityPolicy;
     String m_contentSecurityPolicyReportOnly;
-    String m_xWebKitCSP;
-    String m_xWebKitCSPReportOnly;
 };
 
 }
diff --git a/Source/core/frame/DOMSecurityPolicy.cpp b/Source/core/frame/DOMSecurityPolicy.cpp
deleted file mode 100644
index c60cdad..0000000
--- a/Source/core/frame/DOMSecurityPolicy.cpp
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2012 Google, Inc. 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 GOOGLE INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-#include "core/frame/DOMSecurityPolicy.h"
-
-#include "core/dom/DOMStringList.h"
-#include "core/dom/ExecutionContext.h"
-#include "core/frame/ContentSecurityPolicy.h"
-#include "wtf/text/TextPosition.h"
-
-namespace WebCore {
-
-namespace {
-
-bool isPolicyActiveInContext(ExecutionContext* context)
-{
-    // If the ExecutionContext has been destroyed, there's no active policy.
-    if (!context)
-        return false;
-
-    return context->contentSecurityPolicy()->isActive();
-}
-
-template<bool (ContentSecurityPolicy::*allowWithType)(const String&, const String&, const KURL&, ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowedWithType(ExecutionContext* context, const String& type)
-{
-    if (!isPolicyActiveInContext(context))
-        return true;
-
-    return (context->contentSecurityPolicy()->*allowWithType)(type, type, KURL(), ContentSecurityPolicy::SuppressReport);
-}
-
-template<bool (ContentSecurityPolicy::*allowWithURL)(const KURL&, ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowedWithURL(ExecutionContext* context, const String& url)
-{
-    if (!isPolicyActiveInContext(context))
-        return true;
-
-    KURL parsedURL = context->completeURL(url);
-    if (!parsedURL.isValid())
-        return false; // FIXME: Figure out how to throw a JavaScript error.
-
-    return (context->contentSecurityPolicy()->*allowWithURL)(parsedURL, ContentSecurityPolicy::SuppressReport);
-}
-
-template<bool (ContentSecurityPolicy::*allowWithContext)(const String&, const WTF::OrdinalNumber&, ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowed(ExecutionContext* context)
-{
-    if (!isPolicyActiveInContext(context))
-        return true;
-
-    return (context->contentSecurityPolicy()->*allowWithContext)(String(), WTF::OrdinalNumber::beforeFirst(), ContentSecurityPolicy::SuppressReport);
-}
-
-} // namespace
-
-DOMSecurityPolicy::DOMSecurityPolicy(ExecutionContext* context)
-    : ContextLifecycleObserver(context)
-{
-    ScriptWrappable::init(this);
-}
-
-DOMSecurityPolicy::~DOMSecurityPolicy()
-{
-}
-
-bool DOMSecurityPolicy::isActive() const
-{
-    return isPolicyActiveInContext(executionContext());
-}
-
-PassRefPtr<DOMStringList> DOMSecurityPolicy::reportURIs() const
-{
-    RefPtr<DOMStringList> result = DOMStringList::create();
-
-    if (isActive())
-        executionContext()->contentSecurityPolicy()->gatherReportURIs(*result.get());
-
-    return result.release();
-}
-
-bool DOMSecurityPolicy::allowsInlineScript() const
-{
-    return isAllowed<&ContentSecurityPolicy::allowInlineScript>(executionContext());
-}
-
-bool DOMSecurityPolicy::allowsInlineStyle() const
-{
-    return isAllowed<&ContentSecurityPolicy::allowInlineStyle>(executionContext());
-}
-
-bool DOMSecurityPolicy::allowsEval() const
-{
-    if (!isActive())
-        return true;
-
-    return executionContext()->contentSecurityPolicy()->allowEval(0, ContentSecurityPolicy::SuppressReport);
-}
-
-
-bool DOMSecurityPolicy::allowsConnectionTo(const String& url) const
-{
-    return isAllowedWithURL<&ContentSecurityPolicy::allowConnectToSource>(executionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsFontFrom(const String& url) const
-{
-    return isAllowedWithURL<&ContentSecurityPolicy::allowFontFromSource>(executionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsFormAction(const String& url) const
-{
-    return isAllowedWithURL<&ContentSecurityPolicy::allowFormAction>(executionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsFrameFrom(const String& url) const
-{
-    return isAllowedWithURL<&ContentSecurityPolicy::allowChildFrameFromSource>(executionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsImageFrom(const String& url) const
-{
-    return isAllowedWithURL<&ContentSecurityPolicy::allowImageFromSource>(executionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsMediaFrom(const String& url) const
-{
-    return isAllowedWithURL<&ContentSecurityPolicy::allowMediaFromSource>(executionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsObjectFrom(const String& url) const
-{
-    return isAllowedWithURL<&ContentSecurityPolicy::allowObjectFromSource>(executionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsPluginType(const String& type) const
-{
-    return isAllowedWithType<&ContentSecurityPolicy::allowPluginType>(executionContext(), type);
-}
-
-bool DOMSecurityPolicy::allowsScriptFrom(const String& url) const
-{
-    return isAllowedWithURL<&ContentSecurityPolicy::allowScriptFromSource>(executionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsStyleFrom(const String& url) const
-{
-    return isAllowedWithURL<&ContentSecurityPolicy::allowStyleFromSource>(executionContext(), url);
-}
-
-} // namespace WebCore
diff --git a/Source/core/frame/DOMSecurityPolicy.h b/Source/core/frame/DOMSecurityPolicy.h
deleted file mode 100644
index 7881301..0000000
--- a/Source/core/frame/DOMSecurityPolicy.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2011 Google, Inc. 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 GOOGLE INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef DOMSecurityPolicy_h
-#define DOMSecurityPolicy_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ContextLifecycleObserver.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class ContentSecurityPolicy;
-class DOMStringList;
-class Frame;
-
-class DOMSecurityPolicy : public RefCounted<DOMSecurityPolicy>, public ScriptWrappable, public ContextLifecycleObserver {
-public:
-    static PassRefPtr<DOMSecurityPolicy> create(ExecutionContext* context)
-    {
-        return adoptRef(new DOMSecurityPolicy(context));
-    }
-    ~DOMSecurityPolicy();
-
-    bool isActive() const;
-    PassRefPtr<DOMStringList> reportURIs() const;
-
-    bool allowsInlineScript() const;
-    bool allowsInlineStyle() const;
-    bool allowsEval() const;
-
-    bool allowsConnectionTo(const String& url) const;
-    bool allowsFontFrom(const String& url) const;
-    bool allowsFormAction(const String& url) const;
-    bool allowsFrameFrom(const String& url) const;
-    bool allowsImageFrom(const String& url) const;
-    bool allowsMediaFrom(const String& url) const;
-    bool allowsObjectFrom(const String& url) const;
-    bool allowsPluginType(const String& type) const;
-    bool allowsScriptFrom(const String& url) const;
-    bool allowsStyleFrom(const String& url) const;
-
-private:
-    explicit DOMSecurityPolicy(ExecutionContext*);
-};
-
-}
-
-#endif
diff --git a/Source/core/frame/DOMTimer.h b/Source/core/frame/DOMTimer.h
index 95c094b..19c22d2 100644
--- a/Source/core/frame/DOMTimer.h
+++ b/Source/core/frame/DOMTimer.h
@@ -38,7 +38,7 @@
 
 class ExecutionContext;
 
-class DOMTimer : public SuspendableTimer {
+class DOMTimer FINAL : public SuspendableTimer {
 public:
     // Creates a new timer owned by the ExecutionContext, starts it and returns its ID.
     static int install(ExecutionContext*, PassOwnPtr<ScheduledAction>, int timeout, bool singleShot);
@@ -66,10 +66,10 @@
     }
 
     DOMTimer(ExecutionContext*, PassOwnPtr<ScheduledAction>, int interval, bool singleShot, int timeoutID);
-    virtual void fired();
+    virtual void fired() OVERRIDE;
 
     // Retuns timer fire time rounded to the next multiple of timer alignment interval.
-    virtual double alignedFireTime(double) const;
+    virtual double alignedFireTime(double) const OVERRIDE;
 
     int m_timeoutID;
     int m_nestingLevel;
diff --git a/Source/core/frame/DOMWindow.cpp b/Source/core/frame/DOMWindow.cpp
index c2eae6c..abf4901 100644
--- a/Source/core/frame/DOMWindow.cpp
+++ b/Source/core/frame/DOMWindow.cpp
@@ -27,7 +27,6 @@
 #include "config.h"
 #include "core/frame/DOMWindow.h"
 
-#include <algorithm>
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
@@ -57,13 +56,19 @@
 #include "core/events/PageTransitionEvent.h"
 #include "core/events/PopStateEvent.h"
 #include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/BarProp.h"
 #include "core/frame/Console.h"
 #include "core/frame/DOMPoint.h"
+#include "core/frame/DOMWindowLifecycleNotifier.h"
 #include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/FrameView.h"
 #include "core/frame/History.h"
 #include "core/frame/Location.h"
 #include "core/frame/Navigator.h"
+#include "core/frame/PageConsole.h"
 #include "core/frame/Screen.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/inspector/ScriptCallStack.h"
@@ -73,19 +78,14 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/SinkDocument.h"
 #include "core/loader/appcache/ApplicationCache.h"
-#include "core/frame/BarProp.h"
 #include "core/page/BackForwardClient.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/CreateWindow.h"
-#include "core/frame/DOMWindowLifecycleNotifier.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FrameTree.h"
-#include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/PageConsole.h"
 #include "core/page/PageGroup.h"
-#include "core/page/Settings.h"
 #include "core/page/WindowFeatures.h"
 #include "core/page/WindowFocusAllowedIndicator.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
@@ -104,13 +104,14 @@
 #include "wtf/MainThread.h"
 #include "wtf/MathExtras.h"
 #include "wtf/text/WTFString.h"
+#include <algorithm>
 
 using std::min;
 using std::max;
 
 namespace WebCore {
 
-class PostMessageTimer : public TimerBase {
+class PostMessageTimer FINAL : public TimerBase {
 public:
     PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin, PassRefPtr<ScriptCallStack> stackTrace)
         : m_window(window)
@@ -132,7 +133,7 @@
     ScriptCallStack* stackTrace() const { return m_stackTrace.get(); }
 
 private:
-    virtual void fired()
+    virtual void fired() OVERRIDE
     {
         m_window->postMessageTimerFired(adoptPtr(this));
         // This object is deleted now.
@@ -251,12 +252,14 @@
 // 3) Constrains the window rect to within the top and left boundaries of the available screen rect.
 // 4) Constrains the window rect to within the bottom and right boundaries of the available screen rect.
 // 5) Translate the window rect coordinates to be within the coordinate space of the screen.
-FloatRect DOMWindow::adjustWindowRect(Page* page, const FloatRect& pendingChanges)
+FloatRect DOMWindow::adjustWindowRect(Frame* frame, const FloatRect& pendingChanges)
 {
-    ASSERT(page);
+    ASSERT(frame);
+    FrameHost* host = frame->host();
+    ASSERT(host);
 
-    FloatRect screen = screenAvailableRect(page->mainFrame()->view());
-    FloatRect window = page->chrome().windowRect();
+    FloatRect screen = screenAvailableRect(frame->view());
+    FloatRect window = host->chrome().windowRect();
 
     // Make sure we're in a valid state before adjusting dimensions.
     ASSERT(std::isfinite(screen.x()));
@@ -278,7 +281,7 @@
     if (!std::isnan(pendingChanges.height()))
         window.setHeight(pendingChanges.height());
 
-    FloatSize minimumSize = page->chrome().client().minimumWindowSize();
+    FloatSize minimumSize = host->chrome().client().minimumWindowSize();
     // Let size 0 pass through, since that indicates default size, not minimum size.
     if (window.width())
         window.setWidth(min(max(minimumSize.width(), window.width()), screen.width()));
@@ -312,20 +315,20 @@
 {
     if (!frame)
         return false;
-    Page* page = frame->page();
-    if (!page)
+    FrameHost* host = frame->host();
+    if (!host)
         return false;
-    return page->chrome().canRunModal();
+    return host->chrome().canRunModal();
 }
 
 bool DOMWindow::canShowModalDialogNow(const Frame* frame)
 {
     if (!frame)
         return false;
-    Page* page = frame->page();
-    if (!page)
+    FrameHost* host = frame->host();
+    if (!host)
         return false;
-    return page->chrome().canRunModalNow();
+    return host->chrome().canRunModalNow();
 }
 
 DOMWindow::DOMWindow(Frame* frame)
@@ -408,9 +411,9 @@
     m_frame->selection().updateSecureKeyboardEntryIfActive();
 
     if (m_frame->isMainFrame()) {
-        m_frame->page()->mainFrame()->notifyChromeClientWheelEventHandlerCountChanged();
+        m_frame->notifyChromeClientWheelEventHandlerCountChanged();
         if (m_document->hasTouchEventHandlers())
-            m_frame->page()->chrome().client().needTouchEvents(true);
+            m_frame->host()->chrome().client().needTouchEvents(true);
     }
 
     return m_document;
@@ -447,7 +450,8 @@
 {
     dispatchWindowLoadEvent();
     enqueuePageshowEvent(PageshowEventNotPersisted);
-    enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
+    if (m_pendingStateObject)
+        enqueuePopstateEvent(m_pendingStateObject.release());
 }
 
 void DOMWindow::enqueuePageshowEvent(PageshowEventPersistence persisted)
@@ -541,7 +545,7 @@
     reset();
 }
 
-void DOMWindow::willDetachPage()
+void DOMWindow::willDetachFrameHost()
 {
     InspectorInstrumentation::frameWindowDiscarded(m_frame, this);
 }
@@ -609,15 +613,15 @@
     return m_frame && m_frame->domWindow() == this;
 }
 
-#if ENABLE(ORIENTATION_EVENTS)
 int DOMWindow::orientation() const
 {
+    ASSERT(RuntimeEnabledFeatures::orientationEventEnabled());
+
     if (!m_frame)
         return 0;
 
     return m_frame->orientation();
 }
-#endif
 
 Screen* DOMWindow::screen() const
 {
@@ -639,7 +643,7 @@
 
 BarProp* DOMWindow::locationbar() const
 {
-    UseCounter::count(this, UseCounter::BarPropLocationbar);
+    UseCounter::count(document(), UseCounter::BarPropLocationbar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_locationbar)
@@ -649,7 +653,7 @@
 
 BarProp* DOMWindow::menubar() const
 {
-    UseCounter::count(this, UseCounter::BarPropMenubar);
+    UseCounter::count(document(), UseCounter::BarPropMenubar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_menubar)
@@ -659,7 +663,7 @@
 
 BarProp* DOMWindow::personalbar() const
 {
-    UseCounter::count(this, UseCounter::BarPropPersonalbar);
+    UseCounter::count(document(), UseCounter::BarPropPersonalbar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_personalbar)
@@ -669,7 +673,7 @@
 
 BarProp* DOMWindow::scrollbars() const
 {
-    UseCounter::count(this, UseCounter::BarPropScrollbars);
+    UseCounter::count(document(), UseCounter::BarPropScrollbars);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_scrollbars)
@@ -679,7 +683,7 @@
 
 BarProp* DOMWindow::statusbar() const
 {
-    UseCounter::count(this, UseCounter::BarPropStatusbar);
+    UseCounter::count(document(), UseCounter::BarPropStatusbar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_statusbar)
@@ -689,7 +693,7 @@
 
 BarProp* DOMWindow::toolbar() const
 {
-    UseCounter::count(this, UseCounter::BarPropToolbar);
+    UseCounter::count(document(), UseCounter::BarPropToolbar);
     if (!isCurrentlyDisplayedInFrame())
         return 0;
     if (!m_toolbar)
@@ -710,7 +714,7 @@
 {
     if (!isCurrentlyDisplayedInFrame())
         return 0;
-    return m_frame->page() ? &m_frame->page()->console() : 0;
+    return m_frame->host() ? &m_frame->host()->console() : 0;
 }
 
 ApplicationCache* DOMWindow::applicationCache() const
@@ -781,7 +785,7 @@
     if (!page)
         return 0;
 
-    OwnPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
+    OwnPtrWillBeRawPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
     if (!storageArea->canAccessStorage(m_frame)) {
         exceptionState.throwSecurityError(accessDeniedMessage);
         return 0;
@@ -819,14 +823,12 @@
         return m_localStorage.get();
     }
 
-    Page* page = document->page();
-    if (!page)
+    // FIXME: Seems this check should be much higher?
+    FrameHost* host = document->frameHost();
+    if (!host || !host->settings().localStorageEnabled())
         return 0;
 
-    if (!page->settings().localStorageEnabled())
-        return 0;
-
-    OwnPtr<StorageArea> storageArea = StorageNamespace::localStorageArea(document->securityOrigin());
+    OwnPtrWillBeRawPtr<StorageArea> storageArea = StorageNamespace::localStorageArea(document->securityOrigin());
     if (!storageArea->canAccessStorage(m_frame)) {
         exceptionState.throwSecurityError(accessDeniedMessage);
         return 0;
@@ -884,7 +886,10 @@
 {
     OwnPtr<PostMessageTimer> timer(t);
 
-    if (!document() || !isCurrentlyDisplayedInFrame())
+    // FIXME: The frame()->host() check really does not belong here. We should
+    // move it up into isCurrentlyDisplayedInFrame(); however, doing so breaks a
+    // number of window properties like window.toolbar.
+    if (!isCurrentlyDisplayedInFrame() || !frame()->host())
         return;
 
     RefPtr<MessageEvent> event = timer->event();
@@ -934,8 +939,8 @@
     if (!m_frame)
         return;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return;
 
     bool allowFocus = WindowFocusAllowedIndicator::windowFocusAllowed();
@@ -948,7 +953,7 @@
 
     // If we're a top level window, bring the window to the front.
     if (m_frame->isMainFrame() && allowFocus)
-        page->chrome().focus();
+        host->chrome().focus();
 
     if (!m_frame)
         return;
@@ -962,16 +967,13 @@
 
 void DOMWindow::close(ExecutionContext* context)
 {
-    if (!m_frame)
+    if (!m_frame || !m_frame->isMainFrame())
         return;
 
     Page* page = m_frame->page();
     if (!page)
         return;
 
-    if (m_frame != page->mainFrame())
-        return;
-
     if (context) {
         ASSERT(isMainThread());
         Document* activeDocument = toDocument(context);
@@ -1001,16 +1003,16 @@
     if (!m_frame)
         return;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return;
 
-    if (m_frame->loader().activeDocumentLoader()->isLoading()) {
+    if (m_frame->loader().documentLoader()->isLoading()) {
         m_shouldPrintWhenFinishedLoading = true;
         return;
     }
     m_shouldPrintWhenFinishedLoading = false;
-    page->chrome().print(m_frame);
+    host->chrome().print(m_frame);
 }
 
 void DOMWindow::stop()
@@ -1027,11 +1029,11 @@
 
     m_frame->document()->updateStyleIfNeeded();
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return;
 
-    page->chrome().runJavaScriptAlert(m_frame, message);
+    host->chrome().runJavaScriptAlert(m_frame, message);
 }
 
 bool DOMWindow::confirm(const String& message)
@@ -1041,11 +1043,11 @@
 
     m_frame->document()->updateStyleIfNeeded();
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return false;
 
-    return page->chrome().runJavaScriptConfirm(m_frame, message);
+    return host->chrome().runJavaScriptConfirm(m_frame, message);
 }
 
 String DOMWindow::prompt(const String& message, const String& defaultValue)
@@ -1055,12 +1057,12 @@
 
     m_frame->document()->updateStyleIfNeeded();
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return String();
 
     String returnValue;
-    if (page->chrome().runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
+    if (host->chrome().runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
         return returnValue;
 
     return String();
@@ -1071,6 +1073,10 @@
     if (!isCurrentlyDisplayedInFrame())
         return false;
 
+    // |m_frame| can be destructed during |Editor::findString()| via
+    // |Document::updateLayou()|, e.g. event handler removes a frame.
+    RefPtr<Frame> protectFrame(m_frame);
+
     // FIXME (13016): Support wholeWord, searchInFrames and showDialog
     return m_frame->editor().findString(string, !backwards, caseSensitive, wrap, false);
 }
@@ -1085,13 +1091,13 @@
     if (!m_frame)
         return 0;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return 0;
 
-    if (page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(page->chrome().windowRect().height() * page->deviceScaleFactor());
-    return static_cast<int>(page->chrome().windowRect().height());
+    if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(host->chrome().windowRect().height() * host->deviceScaleFactor());
+    return static_cast<int>(host->chrome().windowRect().height());
 }
 
 int DOMWindow::outerWidth() const
@@ -1099,13 +1105,13 @@
     if (!m_frame)
         return 0;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return 0;
 
-    if (page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(page->chrome().windowRect().width() * page->deviceScaleFactor());
-    return static_cast<int>(page->chrome().windowRect().width());
+    if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(host->chrome().windowRect().width() * host->deviceScaleFactor());
+    return static_cast<int>(host->chrome().windowRect().width());
 }
 
 int DOMWindow::innerHeight() const
@@ -1145,13 +1151,13 @@
     if (!m_frame)
         return 0;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return 0;
 
-    if (page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(page->chrome().windowRect().x() * page->deviceScaleFactor());
-    return static_cast<int>(page->chrome().windowRect().x());
+    if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(host->chrome().windowRect().x() * host->deviceScaleFactor());
+    return static_cast<int>(host->chrome().windowRect().x());
 }
 
 int DOMWindow::screenY() const
@@ -1159,13 +1165,13 @@
     if (!m_frame)
         return 0;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return 0;
 
-    if (page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(page->chrome().windowRect().y() * page->deviceScaleFactor());
-    return static_cast<int>(page->chrome().windowRect().y());
+    if (host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(host->chrome().windowRect().y() * host->deviceScaleFactor());
+    return static_cast<int>(host->chrome().windowRect().y());
 }
 
 int DOMWindow::scrollX() const
@@ -1233,12 +1239,12 @@
     if (!m_frame)
         return;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return;
 
     ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
-    page->chrome().setStatusbarText(m_frame, m_status);
+    host->chrome().setStatusbarText(m_frame, m_status);
 }
 
 void DOMWindow::setDefaultStatus(const String& string)
@@ -1248,12 +1254,12 @@
     if (!m_frame)
         return;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return;
 
     ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
-    page->chrome().setStatusbarText(m_frame, m_defaultStatus);
+    host->chrome().setStatusbarText(m_frame, m_defaultStatus);
 }
 
 DOMWindow* DOMWindow::self() const
@@ -1322,9 +1328,9 @@
     return CSSComputedStyleDeclaration::create(elt, false, pseudoElt);
 }
 
-PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* element, const String& pseudoElement, bool authorOnly) const
+PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* element, const String& pseudoElement) const
 {
-    UseCounter::count(this, UseCounter::GetMatchedCSSRules);
+    UseCounter::count(document(), UseCounter::GetMatchedCSSRules);
     if (!element)
         return 0;
 
@@ -1337,11 +1343,7 @@
         return 0;
 
     unsigned rulesToInclude = StyleResolver::AuthorCSSRules;
-    if (!authorOnly)
-        rulesToInclude |= StyleResolver::UAAndUserCSSRules;
-
     PseudoId pseudoId = CSSSelector::pseudoId(pseudoType);
-
     return m_frame->document()->ensureStyleResolver().pseudoCSSRulesForElement(element, pseudoId, rulesToInclude);
 }
 
@@ -1383,8 +1385,27 @@
     return m_frame->devicePixelRatio();
 }
 
-void DOMWindow::scrollBy(int x, int y) const
+static bool scrollBehaviorFromScrollOptions(const Dictionary& scrollOptions, ScrollBehavior& scrollBehavior, ExceptionState& exceptionState)
 {
+    String scrollBehaviorString;
+    if (!scrollOptions.get("behavior", scrollBehaviorString)) {
+        scrollBehavior = ScrollBehaviorAuto;
+        return true;
+    }
+
+    if (ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior))
+        return true;
+
+    exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
+    return false;
+}
+
+void DOMWindow::scrollBy(int x, int y, const Dictionary& scrollOptions, ExceptionState &exceptionState) const
+{
+    ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
+    if (RuntimeEnabledFeatures::cssomSmoothScrollEnabled() && !scrollBehaviorFromScrollOptions(scrollOptions, scrollBehavior, exceptionState))
+        return;
+
     if (!isCurrentlyDisplayedInFrame())
         return;
 
@@ -1394,13 +1415,17 @@
     if (!view)
         return;
 
-
     IntSize scaledOffset(x * m_frame->pageZoomFactor(), y * m_frame->pageZoomFactor());
+    // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
     view->scrollBy(scaledOffset);
 }
 
-void DOMWindow::scrollTo(int x, int y) const
+void DOMWindow::scrollTo(int x, int y, const Dictionary& scrollOptions, ExceptionState& exceptionState) const
 {
+    ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
+    if (RuntimeEnabledFeatures::cssomSmoothScrollEnabled() && !scrollBehaviorFromScrollOptions(scrollOptions, scrollBehavior, exceptionState))
+        return;
+
     if (!isCurrentlyDisplayedInFrame())
         return;
 
@@ -1411,80 +1436,68 @@
         return;
 
     IntPoint layoutPos(x * m_frame->pageZoomFactor(), y * m_frame->pageZoomFactor());
+    // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
     view->setScrollPosition(layoutPos);
 }
 
 void DOMWindow::moveBy(float x, float y) const
 {
-    if (!m_frame)
+    if (!m_frame || !m_frame->isMainFrame())
         return;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return;
 
-    if (m_frame != page->mainFrame())
-        return;
-
-    FloatRect fr = page->chrome().windowRect();
-    FloatRect update = fr;
-    update.move(x, y);
+    FloatRect windowRect = host->chrome().windowRect();
+    windowRect.move(x, y);
     // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
-    page->chrome().setWindowRect(adjustWindowRect(page, update));
+    host->chrome().setWindowRect(adjustWindowRect(m_frame, windowRect));
 }
 
 void DOMWindow::moveTo(float x, float y) const
 {
-    if (!m_frame)
+    if (!m_frame || !m_frame->isMainFrame())
         return;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return;
 
-    if (m_frame != page->mainFrame())
-        return;
-
-    FloatRect update = page->chrome().windowRect();
-    update.setLocation(FloatPoint(x, y));
+    FloatRect windowRect = host->chrome().windowRect();
+    windowRect.setLocation(FloatPoint(x, y));
     // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
-    page->chrome().setWindowRect(adjustWindowRect(page, update));
+    host->chrome().setWindowRect(adjustWindowRect(m_frame, windowRect));
 }
 
 void DOMWindow::resizeBy(float x, float y) const
 {
-    if (!m_frame)
+    if (!m_frame || !m_frame->isMainFrame())
         return;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return;
 
-    if (m_frame != page->mainFrame())
-        return;
-
-    FloatRect fr = page->chrome().windowRect();
+    FloatRect fr = host->chrome().windowRect();
     FloatSize dest = fr.size() + FloatSize(x, y);
     FloatRect update(fr.location(), dest);
-    page->chrome().setWindowRect(adjustWindowRect(page, update));
+    host->chrome().setWindowRect(adjustWindowRect(m_frame, update));
 }
 
 void DOMWindow::resizeTo(float width, float height) const
 {
-    if (!m_frame)
+    if (!m_frame || !m_frame->isMainFrame())
         return;
 
-    Page* page = m_frame->page();
-    if (!page)
+    FrameHost* host = m_frame->host();
+    if (!host)
         return;
 
-    if (m_frame != page->mainFrame())
-        return;
-
-    FloatRect fr = page->chrome().windowRect();
+    FloatRect fr = host->chrome().windowRect();
     FloatSize dest = FloatSize(width, height);
     FloatRect update(fr.location(), dest);
-    page->chrome().setWindowRect(adjustWindowRect(page, update));
+    host->chrome().setWindowRect(adjustWindowRect(m_frame, update));
 }
 
 int DOMWindow::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
@@ -1542,10 +1555,10 @@
     lifecycleNotifier().notifyAddEventListener(this, eventType);
 
     if (eventType == EventTypeNames::unload) {
-        UseCounter::count(this, UseCounter::DocumentUnloadRegistered);
+        UseCounter::count(document(), UseCounter::DocumentUnloadRegistered);
         addUnloadEventListener(this);
     } else if (eventType == EventTypeNames::beforeunload) {
-        UseCounter::count(this, UseCounter::DocumentBeforeUnloadRegistered);
+        UseCounter::count(document(), UseCounter::DocumentBeforeUnloadRegistered);
         if (allowsBeforeUnloadListeners(this)) {
             // This is confusingly named. It doesn't actually add the listener. It just increments a count
             // so that we know we have listeners registered for the purposes of determining if we can
@@ -1553,7 +1566,7 @@
             addBeforeUnloadEventListener(this);
         } else {
             // Subframes return false from allowsBeforeUnloadListeners.
-            UseCounter::count(this, UseCounter::SubFrameBeforeUnloadRegistered);
+            UseCounter::count(document(), UseCounter::SubFrameBeforeUnloadRegistered);
         }
     }
 
@@ -1632,7 +1645,7 @@
     lifecycleNotifier().notifyRemoveAllEventListeners(this);
 
     if (Document* document = this->document())
-        document->didRemoveEventTargetNode(document);
+        document->didClearTouchEventHandlers(document);
 
     removeAllUnloadEventListeners(this);
     removeAllBeforeUnloadEventListeners(this);
@@ -1670,9 +1683,9 @@
         return;
 
     // We want a new history item if we are processing a user gesture.
-    m_frame->navigationScheduler().scheduleLocationChange(activeDocument->securityOrigin(),
+    m_frame->navigationScheduler().scheduleLocationChange(activeDocument,
         // FIXME: What if activeDocument()->frame() is 0?
-        completedURL, activeDocument->frame()->loader().outgoingReferrer(),
+        completedURL, Referrer(activeDocument->outgoingReferrer(), activeDocument->referrerPolicy()),
         locking != LockHistoryBasedOnGestureState);
 }
 
@@ -1821,9 +1834,9 @@
         // For whatever reason, Firefox uses the first window rather than the active window to
         // determine the outgoing referrer. We replicate that behavior here.
         targetFrame->navigationScheduler().scheduleLocationChange(
-            activeDocument->securityOrigin(),
+            activeDocument,
             completedURL,
-            firstFrame->loader().outgoingReferrer(),
+            Referrer(firstFrame->document()->outgoingReferrer(), firstFrame->document()->referrerPolicy()),
             false);
         return targetFrame->domWindow();
     }
@@ -1856,7 +1869,7 @@
     if (!dialogFrame)
         return;
     UserGestureIndicatorDisabler disabler;
-    dialogFrame->page()->chrome().runModal();
+    dialogFrame->host()->chrome().runModal();
 }
 
 DOMWindow* DOMWindow::anonymousIndexedGetter(uint32_t index)
diff --git a/Source/core/frame/DOMWindow.h b/Source/core/frame/DOMWindow.h
index f459057..b0a1580 100644
--- a/Source/core/frame/DOMWindow.h
+++ b/Source/core/frame/DOMWindow.h
@@ -27,6 +27,7 @@
 #ifndef DOMWindow_h
 #define DOMWindow_h
 
+#include "bindings/v8/Dictionary.h"
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/events/EventTarget.h"
 #include "core/frame/FrameDestructionObserver.h"
@@ -89,7 +90,7 @@
 
     enum SetLocationLocking { LockHistoryBasedOnGestureState, LockHistoryAndBackForwardList };
 
-    class DOMWindow : public RefCounted<DOMWindow>, public ScriptWrappable, public EventTargetWithInlineData, public FrameDestructionObserver, public Supplementable<DOMWindow>, public LifecycleContext<DOMWindow> {
+    class DOMWindow FINAL : public RefCounted<DOMWindow>, public ScriptWrappable, public EventTargetWithInlineData, public FrameDestructionObserver, public Supplementable<DOMWindow>, public LifecycleContext<DOMWindow> {
         REFCOUNTED_EVENT_TARGET(DOMWindow);
     public:
         static PassRefPtr<Document> createDocument(const String& mimeType, const DocumentInit&, bool forceXHTML);
@@ -101,7 +102,7 @@
         virtual const AtomicString& interfaceName() const OVERRIDE;
         virtual ExecutionContext* executionContext() const OVERRIDE;
 
-        virtual DOMWindow* toDOMWindow();
+        virtual DOMWindow* toDOMWindow() OVERRIDE;
 
         void registerProperty(DOMWindowProperty*);
         void unregisterProperty(DOMWindowProperty*);
@@ -112,7 +113,7 @@
 
         unsigned pendingUnloadEventListeners() const;
 
-        static FloatRect adjustWindowRect(Page*, const FloatRect& pendingChanges);
+        static FloatRect adjustWindowRect(Frame*, const FloatRect& pendingChanges);
 
         bool allowPopUp(); // Call on first window, not target window.
         static bool allowPopUp(Frame* firstFrame);
@@ -210,7 +211,7 @@
 
         // WebKit extensions
 
-        PassRefPtr<CSSRuleList> getMatchedCSSRules(Element*, const String& pseudoElt, bool authorOnly = true) const;
+        PassRefPtr<CSSRuleList> getMatchedCSSRules(Element*, const String& pseudoElt) const;
         double devicePixelRatio() const;
 
         PassRefPtr<DOMPoint> webkitConvertPointFromPageToNode(Node*, const DOMPoint*) const;
@@ -227,9 +228,9 @@
         void postMessageTimerFired(PassOwnPtr<PostMessageTimer>);
         void dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtr<Event>, PassRefPtr<ScriptCallStack>);
 
-        void scrollBy(int x, int y) const;
-        void scrollTo(int x, int y) const;
-        void scroll(int x, int y) const { scrollTo(x, y); }
+        void scrollBy(int x, int y, const Dictionary& scrollOptions, ExceptionState&) const;
+        void scrollTo(int x, int y, const Dictionary& scrollOptions, ExceptionState&) const;
+        void scroll(int x, int y, const Dictionary& scrollOptions, ExceptionState& exceptionState) const { scrollTo(x, y, scrollOptions, exceptionState); }
 
         void moveBy(float x, float y) const;
         void moveTo(float x, float y) const;
@@ -284,15 +285,12 @@
         ApplicationCache* applicationCache() const;
         ApplicationCache* optionalApplicationCache() const { return m_applicationCache.get(); }
 
-#if ENABLE(ORIENTATION_EVENTS)
         // This is the interface orientation in degrees. Some examples are:
         //  0 is straight up; -90 is when the device is rotated 90 clockwise;
         //  90 is when rotated counter clockwise.
         int orientation() const;
 
         DEFINE_ATTRIBUTE_EVENT_LISTENER(orientationchange);
-#endif
-
         DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
@@ -335,7 +333,7 @@
         Page* page();
 
         virtual void frameDestroyed() OVERRIDE;
-        virtual void willDetachPage() OVERRIDE;
+        virtual void willDetachFrameHost() OVERRIDE;
 
         void clearDocument();
         void resetDOMWindowProperties();
@@ -363,8 +361,8 @@
         String m_status;
         String m_defaultStatus;
 
-        mutable RefPtr<Storage> m_sessionStorage;
-        mutable RefPtr<Storage> m_localStorage;
+        mutable RefPtrWillBePersistent<Storage> m_sessionStorage;
+        mutable RefPtrWillBePersistent<Storage> m_localStorage;
         mutable RefPtr<ApplicationCache> m_applicationCache;
 
         mutable RefPtr<Performance> m_performance;
diff --git a/Source/core/frame/DOMWindowEventHandlers.h b/Source/core/frame/DOMWindowEventHandlers.h
index bf89771..96f97e2 100644
--- a/Source/core/frame/DOMWindowEventHandlers.h
+++ b/Source/core/frame/DOMWindowEventHandlers.h
@@ -43,7 +43,6 @@
 DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(pagehide);
 DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(pageshow);
 DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(popstate);
-DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
 DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(storage);
 DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(unload);
 }
diff --git a/Source/core/frame/DOMWindowLifecycleNotifier.h b/Source/core/frame/DOMWindowLifecycleNotifier.h
index 7db4859..8946a68 100644
--- a/Source/core/frame/DOMWindowLifecycleNotifier.h
+++ b/Source/core/frame/DOMWindowLifecycleNotifier.h
@@ -36,7 +36,7 @@
 
 class DOMWindow;
 
-class DOMWindowLifecycleNotifier : public LifecycleNotifier<DOMWindow> {
+class DOMWindowLifecycleNotifier FINAL : public LifecycleNotifier<DOMWindow> {
 public:
     static PassOwnPtr<DOMWindowLifecycleNotifier> create(DOMWindow*);
 
diff --git a/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp b/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp
new file mode 100644
index 0000000..daaec3a
--- /dev/null
+++ b/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp
@@ -0,0 +1,31 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.h"
+
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+DeprecatedScheduleStyleRecalcDuringCompositingUpdate::DeprecatedScheduleStyleRecalcDuringCompositingUpdate(DocumentLifecycle& lifecycle)
+    : m_lifecycle(lifecycle)
+    , m_deprecatedTransition(lifecycle.state(), DocumentLifecycle::StyleRecalcPending)
+    , m_originalState(lifecycle.state())
+{
+}
+
+DeprecatedScheduleStyleRecalcDuringCompositingUpdate::~DeprecatedScheduleStyleRecalcDuringCompositingUpdate()
+{
+    if (m_originalState != DocumentLifecycle::InStyleRecalc
+        && m_originalState != DocumentLifecycle::AfterPerformLayout
+        && m_originalState != DocumentLifecycle::InCompositingUpdate)
+        return;
+    if (m_lifecycle.state() != m_originalState) {
+        ASSERT(m_lifecycle.state() == DocumentLifecycle::StyleRecalcPending);
+        m_lifecycle.advanceTo(m_originalState);
+    }
+}
+
+}
diff --git a/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.h b/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.h
new file mode 100644
index 0000000..8059765
--- /dev/null
+++ b/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.h
@@ -0,0 +1,26 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef DeprecatedScheduleStyleRecalcDuringCompositingUpdate_h
+#define DeprecatedScheduleStyleRecalcDuringCompositingUpdate_h
+
+#include "core/dom/DocumentLifecycle.h"
+
+namespace WebCore {
+
+class DeprecatedScheduleStyleRecalcDuringCompositingUpdate {
+    WTF_MAKE_NONCOPYABLE(DeprecatedScheduleStyleRecalcDuringCompositingUpdate);
+public:
+    explicit DeprecatedScheduleStyleRecalcDuringCompositingUpdate(DocumentLifecycle&);
+    ~DeprecatedScheduleStyleRecalcDuringCompositingUpdate();
+
+private:
+    DocumentLifecycle& m_lifecycle;
+    DocumentLifecycle::DeprecatedTransition m_deprecatedTransition;
+    DocumentLifecycle::State m_originalState;
+};
+
+}
+
+#endif
diff --git a/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp b/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp
new file mode 100644
index 0000000..94367d8
--- /dev/null
+++ b/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp
@@ -0,0 +1,29 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/frame/DeprecatedScheduleStyleRecalcDuringLayout.h"
+
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+DeprecatedScheduleStyleRecalcDuringLayout::DeprecatedScheduleStyleRecalcDuringLayout(DocumentLifecycle& lifecycle)
+    : m_lifecycle(lifecycle)
+    , m_deprecatedTransition(DocumentLifecycle::InPerformLayout, DocumentLifecycle::StyleRecalcPending)
+    , m_wasInPerformLayout(lifecycle.state() == DocumentLifecycle::InPerformLayout)
+{
+}
+
+DeprecatedScheduleStyleRecalcDuringLayout::~DeprecatedScheduleStyleRecalcDuringLayout()
+{
+    // This block of code is intended to restore the state machine to the
+    // proper state. The style recalc will still have been schedule, however.
+    if (m_wasInPerformLayout && m_lifecycle.state() != DocumentLifecycle::InPerformLayout) {
+        ASSERT(m_lifecycle.state() == DocumentLifecycle::StyleRecalcPending);
+        m_lifecycle.advanceTo(DocumentLifecycle::InPerformLayout);
+    }
+}
+
+}
diff --git a/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.h b/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.h
new file mode 100644
index 0000000..90b9223
--- /dev/null
+++ b/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.h
@@ -0,0 +1,26 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef DeprecatedScheduleStyleRecalcDuringLayout_h
+#define DeprecatedScheduleStyleRecalcDuringLayout_h
+
+#include "core/dom/DocumentLifecycle.h"
+
+namespace WebCore {
+
+class DeprecatedScheduleStyleRecalcDuringLayout {
+    WTF_MAKE_NONCOPYABLE(DeprecatedScheduleStyleRecalcDuringLayout);
+public:
+    explicit DeprecatedScheduleStyleRecalcDuringLayout(DocumentLifecycle&);
+    ~DeprecatedScheduleStyleRecalcDuringLayout();
+
+private:
+    DocumentLifecycle& m_lifecycle;
+    DocumentLifecycle::DeprecatedTransition m_deprecatedTransition;
+    bool m_wasInPerformLayout;
+};
+
+}
+
+#endif
diff --git a/Source/core/frame/Frame.cpp b/Source/core/frame/Frame.cpp
index 98c1b17..a39b74c 100644
--- a/Source/core/frame/Frame.cpp
+++ b/Source/core/frame/Frame.cpp
@@ -33,7 +33,6 @@
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/DocumentType.h"
-#include "core/events/Event.h"
 #include "core/dom/WheelController.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
@@ -41,30 +40,33 @@
 #include "core/editing/SpellChecker.h"
 #include "core/editing/htmlediting.h"
 #include "core/editing/markup.h"
+#include "core/events/Event.h"
 #include "core/fetch/ResourceFetcher.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/FrameDestructionObserver.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/EmptyClients.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/frame/DOMWindow.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FocusController.h"
-#include "core/frame/FrameDestructionObserver.h"
-#include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/frame/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/DragImage.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderPart.h"
 #include "core/rendering/RenderView.h"
 #include "core/svg/SVGDocument.h"
+#include "platform/DragImage.h"
 #include "platform/graphics/GraphicsContext.h"
 #include "platform/graphics/ImageBuffer.h"
+#include "public/platform/WebLayer.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefCountedLeakCounter.h"
 #include "wtf/StdLibExtras.h"
@@ -77,13 +79,6 @@
 
 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, frameCounter, ("Frame"));
 
-static inline Frame* parentFromOwnerElement(HTMLFrameOwnerElement* ownerElement)
-{
-    if (!ownerElement)
-        return 0;
-    return ownerElement->document().frame();
-}
-
 static inline float parentPageZoomFactor(Frame* frame)
 {
     Frame* parent = frame->tree().parent();
@@ -101,8 +96,8 @@
 }
 
 inline Frame::Frame(PassRefPtr<FrameInit> frameInit)
-    : m_page(frameInit->page())
-    , m_treeNode(this, parentFromOwnerElement(frameInit->ownerElement()))
+    : m_host(frameInit->frameHost())
+    , m_treeNode(this)
     , m_loader(this, frameInit->frameLoaderClient())
     , m_navigationScheduler(this)
     , m_script(adoptPtr(new ScriptController(this)))
@@ -110,20 +105,18 @@
     , m_spellChecker(SpellChecker::create(*this))
     , m_selection(adoptPtr(new FrameSelection(this)))
     , m_eventHandler(adoptPtr(new EventHandler(this)))
-    , m_animationController(adoptPtr(new AnimationController(this)))
     , m_inputMethodController(InputMethodController::create(*this))
     , m_frameInit(frameInit)
     , m_pageZoomFactor(parentPageZoomFactor(this))
     , m_textZoomFactor(parentTextZoomFactor(this))
-#if ENABLE(ORIENTATION_EVENTS)
     , m_orientation(0)
-#endif
     , m_inViewSourceMode(false)
+    , m_remotePlatformLayer(0)
 {
-    ASSERT(m_page);
+    ASSERT(page());
 
     if (ownerElement()) {
-        m_page->incrementSubframeCount();
+        page()->incrementSubframeCount();
         ownerElement()->setContentFrame(*this);
     }
 
@@ -144,7 +137,8 @@
 Frame::~Frame()
 {
     setView(0);
-    loader().clear(ClearScriptObjects | ClearWindowObject);
+    loader().clear();
+    setDOMWindow(0);
 
     // FIXME: We should not be doing all this work inside the destructor
 
@@ -197,32 +191,44 @@
         document()->prepareForDestruction();
     }
 
-    if (m_view)
-        m_view->unscheduleRelayout();
-
     eventHandler().clear();
 
     m_view = view;
 
     if (m_view && isMainFrame())
-        m_view->setVisibleContentScaleFactor(m_page->pageScaleFactor());
+        m_view->setVisibleContentScaleFactor(page()->pageScaleFactor());
 }
 
-#if ENABLE(ORIENTATION_EVENTS)
 void Frame::sendOrientationChangeEvent(int orientation)
 {
+    if (!RuntimeEnabledFeatures::orientationEventEnabled())
+        return;
+
     m_orientation = orientation;
     if (DOMWindow* window = domWindow())
         window->dispatchEvent(Event::create(EventTypeNames::orientationchange));
 }
-#endif // ENABLE(ORIENTATION_EVENTS)
+
+FrameHost* Frame::host() const
+{
+    return m_host;
+}
+
+Page* Frame::page() const
+{
+    if (m_host)
+        return &m_host->page();
+    return 0;
+}
 
 Settings* Frame::settings() const
 {
-    return m_page ? &m_page->settings() : 0;
+    if (m_host)
+        return &m_host->settings();
+    return 0;
 }
 
-void Frame::setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot shouldAdjustViewSize)
+void Frame::setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio)
 {
     // In setting printing, we should not validate resources already cached for the document.
     // See https://bugs.webkit.org/show_bug.cgi?id=43704
@@ -233,16 +239,15 @@
 
     document()->styleResolverChanged(RecalcStyleImmediately);
     if (shouldUsePrintingLayout()) {
-        view()->forceLayoutForPagination(pageSize, originalPageSize, maximumShrinkRatio, shouldAdjustViewSize);
+        view()->forceLayoutForPagination(pageSize, originalPageSize, maximumShrinkRatio);
     } else {
         view()->forceLayout();
-        if (shouldAdjustViewSize == AdjustViewSize)
-            view()->adjustViewSize();
+        view()->adjustViewSize();
     }
 
     // Subframes of the one we're printing don't lay out to the page size.
     for (RefPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling())
-        child->setPrinting(printing, FloatSize(), FloatSize(), 0, shouldAdjustViewSize);
+        child->setPrinting(printing, FloatSize(), FloatSize(), 0);
 }
 
 bool Frame::shouldUsePrintingLayout() const
@@ -274,6 +279,11 @@
 
 void Frame::setDOMWindow(PassRefPtr<DOMWindow> domWindow)
 {
+    InspectorInstrumentation::frameWindowDiscarded(this, m_domWindow.get());
+    if (m_domWindow)
+        m_domWindow->reset();
+    if (domWindow)
+        script().clearWindowShell();
     m_domWindow = domWindow;
 }
 
@@ -316,31 +326,32 @@
     return toRenderPart(object);
 }
 
-void Frame::dispatchVisibilityStateChangeEvent()
+void Frame::didChangeVisibilityState()
 {
     if (document())
-        document()->dispatchVisibilityStateChangeEvent();
+        document()->didChangeVisibilityState();
 
     Vector<RefPtr<Frame> > childFrames;
     for (Frame* child = tree().firstChild(); child; child = child->tree().nextSibling())
         childFrames.append(child);
 
     for (size_t i = 0; i < childFrames.size(); ++i)
-        childFrames[i]->dispatchVisibilityStateChangeEvent();
+        childFrames[i]->didChangeVisibilityState();
 }
 
-void Frame::willDetachPage()
+void Frame::willDetachFrameHost()
 {
     // We should never be detatching the page during a Layout.
-    RELEASE_ASSERT(!m_view || !m_view->isInLayout());
+    RELEASE_ASSERT(!m_view || !m_view->isInPerformLayout());
 
     if (Frame* parent = tree().parent())
         parent->loader().checkLoadComplete();
 
     HashSet<FrameDestructionObserver*>::iterator stop = m_destructionObservers.end();
     for (HashSet<FrameDestructionObserver*>::iterator it = m_destructionObservers.begin(); it != stop; ++it)
-        (*it)->willDetachPage();
+        (*it)->willDetachFrameHost();
 
+    // FIXME: Page should take care of updating focus/scrolling instead of Frame.
     // FIXME: It's unclear as to why this is called more than once, but it is,
     // so page() could be NULL.
     if (page() && page()->focusController().focusedFrame() == this)
@@ -352,11 +363,11 @@
     script().clearScriptObjects();
 }
 
-void Frame::detachFromPage()
+void Frame::detachFromFrameHost()
 {
     // We should never be detatching the page during a Layout.
-    RELEASE_ASSERT(!m_view || !m_view->isInLayout());
-    m_page = 0;
+    RELEASE_ASSERT(!m_view || !m_view->isInPerformLayout());
+    m_host = 0;
 }
 
 void Frame::disconnectOwnerElement()
@@ -365,15 +376,16 @@
         if (Document* doc = document())
             doc->topDocument()->clearAXObjectCache();
         ownerElement()->clearContentFrame();
-        if (m_page)
-            m_page->decrementSubframeCount();
+        if (page())
+            page()->decrementSubframeCount();
     }
     m_frameInit->setOwnerElement(0);
 }
 
 bool Frame::isMainFrame() const
 {
-    return m_page && this == m_page->mainFrame();
+    Page* page = this->page();
+    return page && this == page->mainFrame();
 }
 
 String Frame::documentTypeString() const
@@ -451,7 +463,7 @@
     ScrollbarMode verticalScrollbarMode, bool verticalLock)
 {
     ASSERT(this);
-    ASSERT(m_page);
+    ASSERT(page());
 
     bool isMainFrame = this->isMainFrame();
 
@@ -473,7 +485,7 @@
 
     setView(frameView);
 
-    if (backgroundColor.isValid())
+    if (backgroundColor.alpha())
         frameView->updateBackgroundRecursively(backgroundColor, transparent);
 
     if (isMainFrame)
@@ -486,6 +498,26 @@
         view()->setCanHaveScrollbars(owner->scrollingMode() != ScrollbarAlwaysOff);
 }
 
+
+void Frame::countObjectsNeedingLayout(unsigned& needsLayoutObjects, unsigned& totalObjects, bool& isPartial)
+{
+    RenderObject* root = view()->layoutRoot();
+    isPartial = true;
+    if (!root) {
+        isPartial = false;
+        root = contentRenderer();
+    }
+
+    needsLayoutObjects = 0;
+    totalObjects = 0;
+
+    for (RenderObject* o = root; o; o = o->nextInPreOrder(root)) {
+        ++totalObjects;
+        if (o->needsLayout())
+            ++needsLayoutObjects;
+    }
+}
+
 String Frame::layerTreeAsText(unsigned flags) const
 {
     document()->updateLayout();
@@ -545,15 +577,11 @@
     m_pageZoomFactor = pageZoomFactor;
     m_textZoomFactor = textZoomFactor;
 
-    document->recalcStyle(Force);
-
     for (RefPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling())
         child->setPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor);
 
-    if (FrameView* view = this->view()) {
-        if (document->renderer() && document->renderer()->needsLayout() && view->didFirstLayout())
-            view->layout();
-    }
+    document->setNeedsStyleRecalc(SubtreeStyleChange);
+    document->updateLayoutIgnorePendingStylesheets();
 }
 
 void Frame::deviceOrPageScaleFactorChanged()
@@ -574,14 +602,14 @@
             count += WheelController::from(frame->document())->wheelEventHandlerCount();
     }
 
-    m_page->chrome().client().numWheelEventHandlersChanged(count);
+    m_host->chrome().client().numWheelEventHandlersChanged(count);
 }
 
 bool Frame::isURLAllowed(const KURL& url) const
 {
     // We allow one level of self-reference because some sites depend on that,
     // but we don't allow more than one.
-    if (m_page->subframeCount() >= Page::maxNumberOfFrames)
+    if (page()->subframeCount() >= Page::maxNumberOfFrames)
         return false;
     bool foundSelfReference = false;
     for (const Frame* frame = this; frame; frame = frame->tree().parent()) {
@@ -643,9 +671,8 @@
     LayoutRect topLevelRect;
     IntRect paintingRect = pixelSnappedIntRect(renderer->paintingRootRect(topLevelRect));
 
-    float deviceScaleFactor = 1;
-    if (m_page)
-        deviceScaleFactor = m_page->deviceScaleFactor();
+    ASSERT(document()->isActive());
+    float deviceScaleFactor = m_host->deviceScaleFactor();
     paintingRect.setWidth(paintingRect.width() * deviceScaleFactor);
     paintingRect.setHeight(paintingRect.height() * deviceScaleFactor);
 
@@ -656,10 +683,12 @@
     buffer->context()->translate(-paintingRect.x(), -paintingRect.y());
     buffer->context()->clip(FloatRect(0, 0, paintingRect.maxX(), paintingRect.maxY()));
 
+    // https://code.google.com/p/chromium/issues/detail?id=343755
+    DisableCompositingQueryAsserts disabler;
     m_view->paintContents(buffer->context(), paintingRect);
 
     RefPtr<Image> image = buffer->copyImage();
-    return DragImage::create(image.get(), renderer->shouldRespectImageOrientation());
+    return DragImage::create(image.get(), renderer->shouldRespectImageOrientation(), deviceScaleFactor);
 }
 
 PassOwnPtr<DragImage> Frame::dragImageForSelection()
@@ -673,9 +702,8 @@
 
     IntRect paintingRect = enclosingIntRect(selection().bounds());
 
-    float deviceScaleFactor = 1;
-    if (m_page)
-        deviceScaleFactor = m_page->deviceScaleFactor();
+    ASSERT(document()->isActive());
+    float deviceScaleFactor = m_host->deviceScaleFactor();
     paintingRect.setWidth(paintingRect.width() * deviceScaleFactor);
     paintingRect.setHeight(paintingRect.height() * deviceScaleFactor);
 
@@ -689,17 +717,16 @@
     m_view->paintContents(buffer->context(), paintingRect);
 
     RefPtr<Image> image = buffer->copyImage();
-    return DragImage::create(image.get());
+    return DragImage::create(image.get(), DoNotRespectImageOrientation, deviceScaleFactor);
 }
 
 double Frame::devicePixelRatio() const
 {
-    if (!m_page)
+    if (!m_host)
         return 0;
 
-    double ratio = m_page->deviceScaleFactor();
-    if (RuntimeEnabledFeatures::devicePixelRatioIncludesZoomEnabled())
-        ratio *= pageZoomFactor();
+    double ratio = m_host->deviceScaleFactor();
+    ratio *= pageZoomFactor();
     return ratio;
 }
 
diff --git a/Source/core/frame/Frame.h b/Source/core/frame/Frame.h
index 6c38bce..62276ad 100644
--- a/Source/core/frame/Frame.h
+++ b/Source/core/frame/Frame.h
@@ -30,16 +30,18 @@
 
 #include "core/loader/FrameLoader.h"
 #include "core/loader/NavigationScheduler.h"
-#include "core/frame/AdjustViewSizeOrNot.h"
 #include "core/page/FrameTree.h"
 #include "platform/geometry/IntSize.h"
 #include "platform/scroll/ScrollTypes.h"
 #include "wtf/Forward.h"
 #include "wtf/RefCounted.h"
 
+namespace blink {
+class WebLayer;
+}
+
 namespace WebCore {
 
-    class AnimationController;
     class ChromeClient;
     class Color;
     class DOMWindow;
@@ -51,6 +53,7 @@
     class FetchContext;
     class FloatSize;
     class FrameDestructionObserver;
+    class FrameHost;
     class FrameSelection;
     class FrameView;
     class HTMLFrameOwnerElement;
@@ -58,6 +61,7 @@
     class InputMethodController;
     class IntPoint;
     class Node;
+    class Page;
     class Range;
     class RenderPart;
     class RenderView;
@@ -72,27 +76,27 @@
     class FrameInit : public RefCounted<FrameInit> {
     public:
         // For creating a dummy Frame
-        static PassRefPtr<FrameInit> create(int64_t frameID, Page* page, FrameLoaderClient* client)
+        static PassRefPtr<FrameInit> create(int64_t frameID, FrameHost* host, FrameLoaderClient* client)
         {
-            return adoptRef(new FrameInit(frameID, page, client));
+            return adoptRef(new FrameInit(frameID, host, client));
         }
 
-        void setFrameLoaderClient(FrameLoaderClient* client) { m_client = client; }
-        FrameLoaderClient* frameLoaderClient() const { return m_client; }
-
         int64_t frameID() const { return m_frameID; }
 
-        void setPage(Page* page) { m_page = page; }
-        Page* page() const { return m_page; }
+        void setFrameHost(FrameHost* host) { m_frameHost = host; }
+        FrameHost* frameHost() const { return m_frameHost; }
+
+        void setFrameLoaderClient(FrameLoaderClient* client) { m_client = client; }
+        FrameLoaderClient* frameLoaderClient() const { return m_client; }
 
         void setOwnerElement(HTMLFrameOwnerElement* ownerElement) { m_ownerElement = ownerElement; }
         HTMLFrameOwnerElement* ownerElement() const { return m_ownerElement; }
 
     protected:
-        FrameInit(int64_t frameID, Page* page = 0, FrameLoaderClient* client = 0)
+        FrameInit(int64_t frameID, FrameHost* host = 0, FrameLoaderClient* client = 0)
             : m_frameID(frameID)
             , m_client(client)
-            , m_page(page)
+            , m_frameHost(host)
             , m_ownerElement(0)
         {
         }
@@ -100,7 +104,7 @@
     private:
         int64_t m_frameID;
         FrameLoaderClient* m_client;
-        Page* m_page;
+        FrameHost* m_frameHost;
         HTMLFrameOwnerElement* m_ownerElement;
     };
 
@@ -119,11 +123,16 @@
         void addDestructionObserver(FrameDestructionObserver*);
         void removeDestructionObserver(FrameDestructionObserver*);
 
-        void willDetachPage();
-        void detachFromPage();
+        void willDetachFrameHost();
+        void detachFromFrameHost();
         void disconnectOwnerElement();
 
+        // NOTE: Page is moving out of Blink up into the browser process as
+        // part of the site-isolation (out of process iframes) work.
+        // FrameHost should be used instead where possible.
         Page* page() const;
+        FrameHost* host() const; // Null when the frame is detached.
+
         HTMLFrameOwnerElement* ownerElement() const;
         bool isMainFrame() const;
 
@@ -139,7 +148,6 @@
         NavigationScheduler& navigationScheduler() const;
         FrameSelection& selection() const;
         FrameTree& tree() const;
-        AnimationController& animation() const;
         InputMethodController& inputMethodController() const;
         FetchContext& fetchContext() const { return loader().fetchContext(); }
         ScriptController& script();
@@ -148,21 +156,28 @@
         RenderView* contentRenderer() const; // Root of the render tree for the document contained in this frame.
         RenderPart* ownerRenderer() const; // Renderer for the element that contains this frame.
 
-        void dispatchVisibilityStateChangeEvent();
+        void didChangeVisibilityState();
 
         int64_t frameID() const { return m_frameInit->frameID(); }
 
+        // FIXME: These should move to RemoteFrame once that exists.
+        // RemotePlatformLayer is only ever set for Frames which exist in another process.
+        void setRemotePlatformLayer(blink::WebLayer* remotePlatformLayer) { m_remotePlatformLayer = remotePlatformLayer; }
+        blink::WebLayer* remotePlatformLayer() const { return m_remotePlatformLayer; }
+
     // ======== All public functions below this point are candidates to move out of Frame into another class. ========
 
         bool inScope(TreeScope*) const;
 
+        void countObjectsNeedingLayout(unsigned& needsLayoutObjects, unsigned& totalObjects, bool& isPartial);
+
         // See GraphicsLayerClient.h for accepted flags.
         String layerTreeAsText(unsigned flags = 0) const;
         String trackedRepaintRectsAsText() const;
 
         Settings* settings() const; // can be NULL
 
-        void setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot);
+        void setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio);
         bool shouldUsePrintingLayout() const;
         FloatSize resizePageRectsKeepingRatio(const FloatSize& originalSize, const FloatSize& expectedSize);
 
@@ -178,13 +193,11 @@
         void deviceOrPageScaleFactorChanged();
         double devicePixelRatio() const;
 
-#if ENABLE(ORIENTATION_EVENTS)
         // Orientation is the interface orientation in degrees. Some examples are:
         //  0 is straight up; -90 is when the device is rotated 90 clockwise;
         //  90 is when rotated counter clockwise.
         void sendOrientationChangeEvent(int orientation);
         int orientation() const { return m_orientation; }
-#endif
 
         String documentTypeString() const;
 
@@ -210,7 +223,7 @@
 
         HashSet<FrameDestructionObserver*> m_destructionObservers;
 
-        Page* m_page;
+        FrameHost* m_host;
         mutable FrameTree m_treeNode;
         mutable FrameLoader m_loader;
         mutable NavigationScheduler m_navigationScheduler;
@@ -223,7 +236,6 @@
         const OwnPtr<SpellChecker> m_spellChecker;
         const OwnPtr<FrameSelection> m_selection;
         const OwnPtr<EventHandler> m_eventHandler;
-        OwnPtr<AnimationController> m_animationController;
         OwnPtr<InputMethodController> m_inputMethodController;
 
         RefPtr<FrameInit> m_frameInit;
@@ -231,11 +243,11 @@
         float m_pageZoomFactor;
         float m_textZoomFactor;
 
-#if ENABLE(ORIENTATION_EVENTS)
         int m_orientation;
-#endif
 
         bool m_inViewSourceMode;
+
+        blink::WebLayer* m_remotePlatformLayer;
     };
 
     inline void Frame::init()
@@ -283,11 +295,6 @@
         return *m_spellChecker;
     }
 
-    inline AnimationController& Frame::animation() const
-    {
-        return *m_animationController;
-    }
-
     inline InputMethodController& Frame::inputMethodController() const
     {
         return *m_inputMethodController;
@@ -313,11 +320,6 @@
         return m_treeNode;
     }
 
-    inline Page* Frame::page() const
-    {
-        return m_page;
-    }
-
     inline EventHandler& Frame::eventHandler() const
     {
         ASSERT(m_eventHandler);
diff --git a/Source/core/frame/FrameDestructionObserver.cpp b/Source/core/frame/FrameDestructionObserver.cpp
index ea3923e..2c41712 100644
--- a/Source/core/frame/FrameDestructionObserver.cpp
+++ b/Source/core/frame/FrameDestructionObserver.cpp
@@ -58,7 +58,7 @@
     m_frame = 0;
 }
 
-void FrameDestructionObserver::willDetachPage()
+void FrameDestructionObserver::willDetachFrameHost()
 {
     // Subclasses should override this function to handle this notification.
 }
diff --git a/Source/core/frame/FrameDestructionObserver.h b/Source/core/frame/FrameDestructionObserver.h
index 8989e4a..ed75a2f 100644
--- a/Source/core/frame/FrameDestructionObserver.h
+++ b/Source/core/frame/FrameDestructionObserver.h
@@ -35,7 +35,7 @@
     explicit FrameDestructionObserver(Frame*);
 
     virtual void frameDestroyed();
-    virtual void willDetachPage();
+    virtual void willDetachFrameHost();
 
     Frame* frame() const { return m_frame; }
 
diff --git a/Source/core/html/HTMLImportResourceOwner.cpp b/Source/core/frame/FrameHost.cpp
similarity index 68%
copy from Source/core/html/HTMLImportResourceOwner.cpp
copy to Source/core/frame/FrameHost.cpp
index 3a3109c..8e7ac5d 100644
--- a/Source/core/html/HTMLImportResourceOwner.cpp
+++ b/Source/core/frame/FrameHost.cpp
@@ -29,32 +29,52 @@
  */
 
 #include "config.h"
-#include "core/html/HTMLImportResourceOwner.h"
+#include "core/frame/FrameHost.h"
+
+#include "core/frame/PageConsole.h"
+#include "core/page/Page.h"
 
 namespace WebCore {
 
-HTMLImportResourceOwner::HTMLImportResourceOwner()
+PassOwnPtr<FrameHost> FrameHost::create(Page& page)
+{
+    return adoptPtr(new FrameHost(page));
+}
+
+FrameHost::FrameHost(Page& page)
+    : m_page(page)
+    , m_console(PageConsole::create(*this))
 {
 }
 
-HTMLImportResourceOwner::~HTMLImportResourceOwner()
+// Explicitly in the .cpp to avoid default constructor in .h
+FrameHost::~FrameHost()
 {
-    clearResource();
 }
 
-void HTMLImportResourceOwner::setResource(const ResourcePtr<RawResource>& resource)
+Settings& FrameHost::settings() const
 {
-    ASSERT(!hasResource());
-    m_resource = resource;
-    m_resource->addClient(this);
+    return m_page.settings();
 }
 
-void HTMLImportResourceOwner::clearResource()
+Chrome& FrameHost::chrome() const
 {
-    if (!hasResource())
-        return;
-    m_resource->removeClient(this);
-    m_resource = 0;
+    return m_page.chrome();
 }
 
-} // namespace WebCore
+PageConsole& FrameHost::console() const
+{
+    return *m_console;
+}
+
+UseCounter& FrameHost::useCounter() const
+{
+    return m_page.useCounter();
+}
+
+float FrameHost::deviceScaleFactor() const
+{
+    return m_page.deviceScaleFactor();
+}
+
+}
diff --git a/Source/core/frame/FrameHost.h b/Source/core/frame/FrameHost.h
new file mode 100644
index 0000000..0438b4c
--- /dev/null
+++ b/Source/core/frame/FrameHost.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef FrameHost_h
+#define FrameHost_h
+
+#include "wtf/FastAllocBase.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class Page;
+class PageConsole;
+class Chrome;
+class Settings;
+class UseCounter;
+
+// FrameHost is the set of global data shared between multiple frames
+// and is provided by the embedder to each frame when created.
+// FrameHost currently corresponds to the Page object in core/page
+// however the concept of a Page is moving up out of Blink.
+// In an out-of-process iframe world, a single Page may have
+// multiple frames in different process, thus Page becomes a
+// browser-level concept and Blink core/ only knows about its Frame (and FrameHost).
+// Separating Page from the rest of core/ through this indirection
+// allows us to slowly refactor Page without breaking the rest of core.
+class FrameHost {
+    WTF_MAKE_NONCOPYABLE(FrameHost); WTF_MAKE_FAST_ALLOCATED;
+public:
+    static PassOwnPtr<FrameHost> create(Page&);
+    ~FrameHost();
+
+    // Careful: This function will eventually be removed.
+    Page& page() const { return m_page; }
+
+    Settings& settings() const;
+    Chrome& chrome() const;
+    PageConsole& console() const;
+    UseCounter& useCounter() const;
+
+    // Corresponds to pixel density of the device where this Page is
+    // being displayed. In multi-monitor setups this can vary between pages.
+    // This value does not account for Page zoom, use Frame::devicePixelRatio instead.
+    float deviceScaleFactor() const;
+
+private:
+    explicit FrameHost(Page&);
+
+    Page& m_page;
+    const OwnPtr<PageConsole> m_console;
+};
+
+}
+
+#endif // FrameHost_h
diff --git a/Source/core/frame/FrameView.cpp b/Source/core/frame/FrameView.cpp
index 0022af4..421f8fa 100644
--- a/Source/core/frame/FrameView.cpp
+++ b/Source/core/frame/FrameView.cpp
@@ -38,10 +38,11 @@
 #include "core/events/OverflowEvent.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/ResourceLoadPriorityOptimizer.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLFrameElement.h"
-#include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLPlugInElement.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
@@ -49,39 +50,37 @@
 #include "core/page/ChromeClient.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FocusController.h"
-#include "core/frame/Frame.h"
-#include "core/frame/GraphicsLayerDebugInfo.h"
 #include "core/page/FrameTree.h"
-#include "core/page/Settings.h"
-#include "core/frame/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/rendering/CompositedLayerMapping.h"
-#include "core/rendering/LayoutIndicator.h"
+#include "core/rendering/FastTextAutosizer.h"
 #include "core/rendering/RenderCounter.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderListBox.h"
 #include "core/rendering/RenderPart.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderScrollbarPart.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/RenderWidget.h"
 #include "core/rendering/TextAutosizer.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/svg/RenderSVGRoot.h"
 #include "core/svg/SVGDocument.h"
 #include "core/svg/SVGSVGElement.h"
+#include "platform/TraceEvent.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/GraphicsLayerDebugInfo.h"
 #include "platform/scroll/ScrollAnimator.h"
 #include "platform/scroll/ScrollbarTheme.h"
 #include "platform/text/TextStream.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/TemporaryChange.h"
 
-#include "platform/TraceEvent.h"
-
 namespace WebCore {
 
 using namespace HTMLNames;
@@ -89,30 +88,9 @@
 double FrameView::s_currentFrameTimeStamp = 0.0;
 bool FrameView::s_inPaintContents = false;
 
-
-// REPAINT_THROTTLING now chooses default values for throttling parameters.
-// Should be removed when applications start using runtime configuration.
-#if ENABLE(REPAINT_THROTTLING)
-// Normal delay
-double FrameView::s_normalDeferredRepaintDelay = 0.016;
-// Negative value would mean that first few repaints happen without a delay
-double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
-// The delay grows on each repaint to this maximum value
-double FrameView::s_maxDeferredRepaintDelayDuringLoading = 2.5;
-// On each repaint the delay increses by this amount
-double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0.5;
-#else
-// FIXME: Repaint throttling could be good to have on all platform.
-// The balance between CPU use and repaint frequency will need some tuning for desktop.
-// More hooks may be needed to reset the delay on things like GIF and CSS animations.
-double FrameView::s_normalDeferredRepaintDelay = 0;
-double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
-double FrameView::s_maxDeferredRepaintDelayDuringLoading = 0;
-double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0;
-#endif
-
 // The maximum number of updateWidgets iterations that should be done before returning.
 static const unsigned maxUpdateWidgetsIterations = 2;
+static const double resourcePriorityUpdateDelayAfterScroll = 0.250;
 
 static RenderLayer::UpdateLayerPositionsFlags updateLayerPositionFlags(RenderLayer* layer, bool isRelayoutingSubtree, bool didFullRepaint)
 {
@@ -127,50 +105,12 @@
     return flags;
 }
 
-Pagination::Mode paginationModeForRenderStyle(RenderStyle* style)
-{
-    EOverflow overflow = style->overflowY();
-    if (overflow != OPAGEDX && overflow != OPAGEDY)
-        return Pagination::Unpaginated;
-
-    bool isHorizontalWritingMode = style->isHorizontalWritingMode();
-    TextDirection textDirection = style->direction();
-    WritingMode writingMode = style->writingMode();
-
-    // paged-x always corresponds to LeftToRightPaginated or RightToLeftPaginated. If the WritingMode
-    // is horizontal, then we use TextDirection to choose between those options. If the WritingMode
-    // is vertical, then the direction of the verticality dictates the choice.
-    if (overflow == OPAGEDX) {
-        if ((isHorizontalWritingMode && textDirection == LTR) || writingMode == LeftToRightWritingMode)
-            return Pagination::LeftToRightPaginated;
-        return Pagination::RightToLeftPaginated;
-    }
-
-    // paged-y always corresponds to TopToBottomPaginated or BottomToTopPaginated. If the WritingMode
-    // is horizontal, then the direction of the horizontality dictates the choice. If the WritingMode
-    // is vertical, then we use TextDirection to choose between those options.
-    if (writingMode == TopToBottomWritingMode || (!isHorizontalWritingMode && textDirection == RTL))
-        return Pagination::TopToBottomPaginated;
-    return Pagination::BottomToTopPaginated;
-}
-
-FrameView::DeferredRepaintScope::DeferredRepaintScope(FrameView& view)
-    : m_view(&view)
-{
-    m_view->beginDeferredRepaints();
-}
-
-FrameView::DeferredRepaintScope::~DeferredRepaintScope()
-{
-    m_view->endDeferredRepaints();
-}
-
 FrameView::FrameView(Frame* frame)
     : m_frame(frame)
     , m_canHaveScrollbars(true)
     , m_slowRepaintObjectCount(0)
-    , m_layoutTimer(this, &FrameView::layoutTimerFired)
-    , m_layoutRoot(0)
+    , m_hasPendingLayout(false)
+    , m_layoutSubtreeRoot(0)
     , m_inSynchronousPostLayout(false)
     , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
     , m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired)
@@ -182,18 +122,18 @@
     , m_wasScrolledByUser(false)
     , m_inProgrammaticScroll(false)
     , m_safeToPropagateScrollToParent(true)
-    , m_deferredRepaintTimer(this, &FrameView::deferredRepaintTimerFired)
     , m_isTrackingRepaints(false)
-    , m_shouldUpdateWhileOffscreen(true)
     , m_scrollCorner(0)
     , m_shouldAutoSize(false)
     , m_inAutoSize(false)
     , m_didRunAutosize(false)
     , m_hasSoftwareFilters(false)
+    , m_servicingAnimations(false)
     , m_visibleContentScaleFactor(1)
     , m_inputEventsScaleFactorForEmulation(1)
     , m_partialLayout()
     , m_layoutSizeFixedToFrameSize(true)
+    , m_didScrollTimer(this, &FrameView::didScrollTimerFired)
 {
     ASSERT(m_frame);
     init();
@@ -227,6 +167,9 @@
     if (m_postLayoutTasksTimer.isActive())
         m_postLayoutTasksTimer.stop();
 
+    if (m_didScrollTimer.isActive())
+        m_didScrollTimer.stop();
+
     removeFromAXObjectCache();
     resetScrollbars();
 
@@ -251,14 +194,12 @@
     m_cannotBlitToWindow = false;
     m_isOverlapped = false;
     m_contentIsOpaque = false;
-    m_borderX = 30;
-    m_borderY = 30;
-    m_layoutTimer.stop();
-    m_layoutRoot = 0;
-    m_delayedLayout = false;
-    m_doFullRepaint = true;
+    m_hasPendingLayout = false;
+    m_layoutSubtreeRoot = 0;
+    m_doFullRepaint = false;
     m_layoutSchedulingEnabled = true;
-    m_inLayout = false;
+    m_inPerformLayout = false;
+    m_canRepaintDuringPerformLayout = false;
     m_doingPreLayoutStyleUpdate = false;
     m_inSynchronousPostLayout = false;
     m_layoutCount = 0;
@@ -271,11 +212,6 @@
     m_safeToPropagateScrollToParent = true;
     m_lastViewportSize = IntSize();
     m_lastZoomFactor = 1.0f;
-    m_deferringRepaints = 0;
-    m_repaintCount = 0;
-    m_repaintRects.clear();
-    m_deferredRepaintDelay = s_initialDeferredRepaintDelayDuringLoading;
-    m_deferredRepaintTimer.stop();
     m_isTrackingRepaints = false;
     m_trackedRepaintRects.clear();
     m_lastPaintTime = 0;
@@ -312,7 +248,6 @@
 {
     reset();
 
-    m_margins = LayoutSize(-1, -1); // undefined
     m_size = LayoutSize();
 
     // Propagate the marginwidth/height and scrolling modes to the view.
@@ -321,18 +256,12 @@
         HTMLFrameElementBase* frameElt = toHTMLFrameElementBase(ownerElement);
         if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
             setCanHaveScrollbars(false);
-        LayoutUnit marginWidth = frameElt->marginWidth();
-        LayoutUnit marginHeight = frameElt->marginHeight();
-        if (marginWidth != -1)
-            setMarginWidth(marginWidth);
-        if (marginHeight != -1)
-            setMarginHeight(marginHeight);
     }
 }
 
 void FrameView::prepareForDetach()
 {
-    RELEASE_ASSERT(!isInLayout());
+    RELEASE_ASSERT(!isInPerformLayout());
 
     if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
         scrollAnimator->cancelAnimations();
@@ -370,15 +299,13 @@
     ScrollbarOverlayStyle overlayStyle = ScrollbarOverlayStyleDefault;
 
     Color backgroundColor = documentBackgroundColor();
-    if (backgroundColor.isValid()) {
-        // Reduce the background color from RGB to a lightness value
-        // and determine which scrollbar style to use based on a lightness
-        // heuristic.
-        double hue, saturation, lightness;
-        backgroundColor.getHSL(hue, saturation, lightness);
-        if (lightness <= .5)
-            overlayStyle = ScrollbarOverlayStyleLight;
-    }
+    // Reduce the background color from RGB to a lightness value
+    // and determine which scrollbar style to use based on a lightness
+    // heuristic.
+    double hue, saturation, lightness;
+    backgroundColor.getHSL(hue, saturation, lightness);
+    if (lightness <= .5)
+        overlayStyle = ScrollbarOverlayStyleLight;
 
     if (oldOverlayStyle != overlayStyle)
         setScrollbarOverlayStyle(overlayStyle);
@@ -390,9 +317,6 @@
 
     reset();
 
-    if (RenderPart* renderer = m_frame->ownerRenderer())
-        renderer->viewCleared();
-
     setScrollbarsSuppressed(true);
 }
 
@@ -422,17 +346,22 @@
 void FrameView::setFrameRect(const IntRect& newRect)
 {
     IntRect oldRect = frameRect();
-    if (newRect == oldRect)
+    bool widthChanged = oldRect.width() != newRect.width();
+    bool heightChanged = oldRect.height() != newRect.height();
+    if (!widthChanged && !heightChanged)
         return;
 
     // Autosized font sizes depend on the width of the viewing area.
-    if (newRect.width() != oldRect.width()) {
-        Page* page = m_frame->page();
-        if (isMainFrame() && page->settings().textAutosizingEnabled()) {
-            TextAutosizer* textAutosizer = m_frame->document()->textAutosizer();
-            if (textAutosizer) {
-                for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
-                    textAutosizer->recalculateMultipliers();
+    if (widthChanged) {
+        if (isMainFrame()) {
+            Page* page = m_frame->page();
+            bool textAutosizingEnabled = m_frame->settings()->textAutosizingEnabled();
+            if (textAutosizingEnabled) {
+                TextAutosizer* textAutosizer = m_frame->document()->textAutosizer();
+                if (textAutosizer) {
+                    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
+                        textAutosizer->recalculateMultipliers();
+                }
             }
         }
     }
@@ -445,6 +374,8 @@
         if (renderView->usesCompositing())
             renderView->compositor()->frameViewDidChangeSize();
     }
+
+    viewportConstrainedVisibleContentRectChanged(widthChanged, heightChanged);
 }
 
 bool FrameView::scheduleAnimation()
@@ -461,40 +392,20 @@
     return frame().contentRenderer();
 }
 
-void FrameView::setMarginWidth(LayoutUnit w)
-{
-    // make it update the rendering area when set
-    m_margins.setWidth(w);
-}
-
-void FrameView::setMarginHeight(LayoutUnit h)
-{
-    // make it update the rendering area when set
-    m_margins.setHeight(h);
-}
-
 void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
 {
     m_canHaveScrollbars = canHaveScrollbars;
     ScrollView::setCanHaveScrollbars(canHaveScrollbars);
 }
 
-void FrameView::updateCanHaveScrollbars()
+bool FrameView::shouldUseCustomScrollbars(Element*& customScrollbarElement, Frame*& customScrollbarFrame)
 {
-    ScrollbarMode hMode;
-    ScrollbarMode vMode;
-    scrollbarModes(hMode, vMode);
-    if (hMode == ScrollbarAlwaysOff && vMode == ScrollbarAlwaysOff)
-        setCanHaveScrollbars(false);
-    else
-        setCanHaveScrollbars(true);
-}
+    customScrollbarElement = 0;
+    customScrollbarFrame = 0;
 
-PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
-{
     if (Settings* settings = m_frame->settings()) {
         if (!settings->allowCustomScrollbarInMainFrame() && isMainFrame())
-            return ScrollView::createScrollbar(orientation);
+            return false;
     }
 
     // FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
@@ -502,18 +413,34 @@
 
     // Try the <body> element first as a scrollbar source.
     Element* body = doc ? doc->body() : 0;
-    if (body && body->renderer() && body->renderer()->style()->hasPseudoStyle(SCROLLBAR))
-        return RenderScrollbar::createCustomScrollbar(this, orientation, body);
+    if (body && body->renderer() && body->renderer()->style()->hasPseudoStyle(SCROLLBAR)) {
+        customScrollbarElement = body;
+        return true;
+    }
 
     // If the <body> didn't have a custom style, then the root element might.
     Element* docElement = doc ? doc->documentElement() : 0;
-    if (docElement && docElement->renderer() && docElement->renderer()->style()->hasPseudoStyle(SCROLLBAR))
-        return RenderScrollbar::createCustomScrollbar(this, orientation, docElement);
+    if (docElement && docElement->renderer() && docElement->renderer()->style()->hasPseudoStyle(SCROLLBAR)) {
+        customScrollbarElement = docElement;
+        return true;
+    }
 
     // If we have an owning ipage/Frame element, then it can set the custom scrollbar also.
     RenderPart* frameRenderer = m_frame->ownerRenderer();
-    if (frameRenderer && frameRenderer->style()->hasPseudoStyle(SCROLLBAR))
-        return RenderScrollbar::createCustomScrollbar(this, orientation, 0, m_frame.get());
+    if (frameRenderer && frameRenderer->style()->hasPseudoStyle(SCROLLBAR)) {
+        customScrollbarFrame = m_frame.get();
+        return true;
+    }
+
+    return false;
+}
+
+PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
+{
+    Element* customScrollbarElement = 0;
+    Frame* customScrollbarFrame = 0;
+    if (shouldUseCustomScrollbars(customScrollbarElement, customScrollbarFrame))
+        return RenderScrollbar::createCustomScrollbar(this, orientation, customScrollbarElement, customScrollbarFrame);
 
     // Nobody set a custom style, so we just use a native scrollbar.
     return ScrollView::createScrollbar(orientation);
@@ -551,7 +478,7 @@
     setContentsSize(size);
 }
 
-void FrameView::applyOverflowToViewport(RenderObject* o, ScrollbarMode& hMode, ScrollbarMode& vMode)
+void FrameView::applyOverflowToViewportAndSetRenderer(RenderObject* o, ScrollbarMode& hMode, ScrollbarMode& vMode)
 {
     // Handle the overflow:hidden/scroll case for the body/html elements.  WinIE treats
     // overflow:hidden and overflow:scroll on <body> as applying to the document's
@@ -601,42 +528,14 @@
             vMode = ScrollbarAuto;
             break;
         default:
-            // Don't set it at all. Values of OPAGEDX and OPAGEDY are handled by applyPaginationToViewPort().
+            // Don't set it at all.
             ;
     }
 
     m_viewportRenderer = o;
 }
 
-void FrameView::applyPaginationToViewport()
-{
-    Document* document = m_frame->document();
-    Node* documentElement = document->documentElement();
-    RenderObject* documentRenderer = documentElement ? documentElement->renderer() : 0;
-    RenderObject* documentOrBodyRenderer = documentRenderer;
-    Node* body = document->body();
-    if (body && body->renderer()) {
-        if (body->hasTagName(bodyTag))
-            documentOrBodyRenderer = documentRenderer->style()->overflowX() == OVISIBLE && isHTMLHtmlElement(documentElement) ? body->renderer() : documentRenderer;
-    }
-
-    Pagination pagination;
-
-    if (!documentOrBodyRenderer) {
-        setPagination(pagination);
-        return;
-    }
-
-    EOverflow overflowY = documentOrBodyRenderer->style()->overflowY();
-    if (overflowY == OPAGEDX || overflowY == OPAGEDY) {
-        pagination.mode = WebCore::paginationModeForRenderStyle(documentOrBodyRenderer->style());
-        pagination.gap = static_cast<unsigned>(documentOrBodyRenderer->style()->columnGap());
-    }
-
-    setPagination(pagination);
-}
-
-void FrameView::calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
+void FrameView::calculateScrollbarModesForLayoutAndSetViewportRenderer(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
 {
     m_viewportRenderer = 0;
 
@@ -649,34 +548,24 @@
 
     if (m_canHaveScrollbars || strategy == RulesFromWebContentOnly) {
         hMode = ScrollbarAuto;
-        // Seamless documents begin with heights of 0; we special case that here
-        // to correctly render documents that don't need scrollbars.
-        IntSize fullVisibleSize = visibleContentRect(IncludeScrollbars).size();
-        bool isSeamlessDocument = frame().document() && frame().document()->shouldDisplaySeamlesslyWithParent();
-        vMode = (isSeamlessDocument && !fullVisibleSize.height()) ? ScrollbarAlwaysOff : ScrollbarAuto;
+        vMode = ScrollbarAuto;
     } else {
         hMode = ScrollbarAlwaysOff;
         vMode = ScrollbarAlwaysOff;
     }
 
-    if (!m_layoutRoot) {
+    if (!isSubtreeLayout()) {
         Document* document = m_frame->document();
-        Node* documentElement = document->documentElement();
-        RenderObject* rootRenderer = documentElement ? documentElement->renderer() : 0;
         Node* body = document->body();
-        if (body && body->renderer()) {
-            if (body->hasTagName(framesetTag)) {
-                vMode = ScrollbarAlwaysOff;
-                hMode = ScrollbarAlwaysOff;
-            } else if (body->hasTagName(bodyTag)) {
-                // It's sufficient to just check the X overflow,
-                // since it's illegal to have visible in only one direction.
-                RenderObject* o = rootRenderer->style()->overflowX() == OVISIBLE && isHTMLHtmlElement(document->documentElement()) ? body->renderer() : rootRenderer;
-                if (o->style())
-                    applyOverflowToViewport(o, hMode, vMode);
+        if (body && body->renderer() && body->hasTagName(framesetTag)) {
+            vMode = ScrollbarAlwaysOff;
+            hMode = ScrollbarAlwaysOff;
+        } else if (Element* viewportElement = document->viewportDefiningElement()) {
+            if (RenderObject* viewportRenderer = viewportElement->renderer()) {
+                if (viewportRenderer->style())
+                    applyOverflowToViewportAndSetRenderer(viewportRenderer, hMode, vMode);
             }
-        } else if (rootRenderer)
-            applyOverflowToViewport(rootRenderer, hMode, vMode);
+        }
     }
 }
 
@@ -691,6 +580,10 @@
     if (m_doingPreLayoutStyleUpdate || layoutPending() || renderView->needsLayout())
         return;
 
+    // FIXME: Remove incremental compositing updates after fixing the chicken/egg issues
+    // https://code.google.com/p/chromium/issues/detail?id=343756
+    DisableCompositingQueryAsserts disabler;
+
     // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
     renderView->compositor()->cacheAcceleratedCompositingFlags();
 
@@ -700,7 +593,7 @@
     if (!needsLayout())
         renderView->compositor()->updateCompositingRequirementsState();
 
-    renderView->compositor()->updateCompositingLayers(CompositingUpdateAfterStyleChange);
+    renderView->compositor()->setNeedsCompositingUpdate(CompositingUpdateAfterStyleChange);
 }
 
 void FrameView::updateCompositingLayersAfterLayout()
@@ -710,10 +603,14 @@
     if (!renderView)
         return;
 
+    // FIXME: Remove incremental compositing updates after fixing the chicken/egg issues
+    // https://code.google.com/p/chromium/issues/detail?id=343756
+    DisableCompositingQueryAsserts disabler;
+
     // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
     renderView->compositor()->cacheAcceleratedCompositingFlags();
     renderView->compositor()->updateCompositingRequirementsState();
-    renderView->compositor()->updateCompositingLayers(CompositingUpdateAfterLayout);
+    renderView->compositor()->setNeedsCompositingUpdate(CompositingUpdateAfterLayout);
 }
 
 bool FrameView::usesCompositedScrolling() const
@@ -785,20 +682,7 @@
 
 RenderObject* FrameView::layoutRoot(bool onlyDuringLayout) const
 {
-    return onlyDuringLayout && layoutPending() ? 0 : m_layoutRoot;
-}
-
-static inline void collectFrameViewChildren(FrameView* frameView, Vector<RefPtr<FrameView> >& frameViews)
-{
-    const HashSet<RefPtr<Widget> >* viewChildren = frameView->children();
-    ASSERT(viewChildren);
-
-    const HashSet<RefPtr<Widget> >::iterator end = viewChildren->end();
-    for (HashSet<RefPtr<Widget> >::iterator current = viewChildren->begin(); current != end; ++current) {
-        Widget* widget = (*current).get();
-        if (widget->isFrameView())
-            frameViews.append(toFrameView(widget));
-    }
+    return onlyDuringLayout && layoutPending() ? 0 : m_layoutSubtreeRoot;
 }
 
 inline void FrameView::forceLayoutParentViewIfNeeded()
@@ -834,19 +718,24 @@
 
 void FrameView::performPreLayoutTasks()
 {
+    TRACE_EVENT0("webkit", "FrameView::performPreLayoutTasks");
+    lifecycle().advanceTo(DocumentLifecycle::InPreLayout);
+
     // Don't schedule more layouts, we're in one.
     TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
 
-    if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !frame().document()->shouldDisplaySeamlesslyWithParent()) {
+    if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive()) {
         // This is a new top-level layout. If there are any remaining tasks from the previous layout, finish them now.
         m_inSynchronousPostLayout = true;
         performPostLayoutTasks();
         m_inSynchronousPostLayout = false;
     }
 
-    // Viewport-dependent media queries may cause us to need completely different style information.
     Document* document = m_frame->document();
-    if (!document->styleResolver() || document->styleResolver()->affectedByViewportChange()) {
+    document->notifyResizeForViewportUnits();
+
+    // Viewport-dependent media queries may cause us to need completely different style information.
+    if (!document->styleResolver() || document->styleResolver()->mediaQueryAffectedByViewportChange()) {
         document->styleResolverChanged(RecalcStyleDeferred);
         document->mediaQueryAffectingValueChanged();
 
@@ -857,22 +746,25 @@
         document->evaluateMediaQueryList();
     }
 
-    // If there is any pagination to apply, it will affect the RenderView's style, so we should
-    // take care of that now.
-    applyPaginationToViewport();
-
     // Always ensure our style info is up-to-date. This can happen in situations where
     // the layout beats any sort of style recalc update that needs to occur.
     TemporaryChange<bool> changeDoingPreLayoutStyleUpdate(m_doingPreLayoutStyleUpdate, true);
     document->updateStyleIfNeeded();
+    lifecycle().advanceTo(DocumentLifecycle::StyleClean);
 }
 
 void FrameView::performLayout(RenderObject* rootForThisLayout, bool inSubtreeLayout)
 {
+    TRACE_EVENT0("webkit", "FrameView::performLayout");
+
+    ASSERT(!isInPerformLayout());
+    lifecycle().advanceTo(DocumentLifecycle::InPerformLayout);
+
+    TemporaryChange<bool> changeInPerformLayout(m_inPerformLayout, true);
+
     // performLayout is the actual guts of layout().
     // FIXME: The 300 other lines in layout() probably belong in other helper functions
     // so that a single human could understand what layout() is actually doing.
-    FrameView::DeferredRepaintScope deferRepaints(*this);
 
     {
         bool disableLayoutState = false;
@@ -883,39 +775,30 @@
         }
         LayoutStateDisabler layoutStateDisabler(disableLayoutState ? rootForThisLayout->view() : 0);
 
-        m_inLayout = true;
-
         forceLayoutParentViewIfNeeded();
 
         // Text Autosizing requires two-pass layout which is incompatible with partial layout.
         // If enabled, only do partial layout for the second layout.
         // FIXME (crbug.com/256657): Do not do two layouts for text autosizing.
         PartialLayoutDisabler partialLayoutDisabler(partialLayout(), m_frame->settings() && m_frame->settings()->textAutosizingEnabled());
-
-        LayoutIndicator layoutIndicator;
         rootForThisLayout->layout();
         gatherDebugLayoutRects(rootForThisLayout);
 
-        ResourceLoadPriorityOptimizer modifier;
-        rootForThisLayout->didLayout(modifier);
+        ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->updateAllImageResourcePriorities();
     }
 
     TextAutosizer* textAutosizer = frame().document()->textAutosizer();
     bool autosized = textAutosizer && textAutosizer->processSubtree(rootForThisLayout);
     if (autosized && rootForThisLayout->needsLayout()) {
         TRACE_EVENT0("webkit", "2nd layout due to Text Autosizing");
-        LayoutIndicator layoutIndicator;
         rootForThisLayout->layout();
         gatherDebugLayoutRects(rootForThisLayout);
-
-        ResourceLoadPriorityOptimizer modifier;
-        rootForThisLayout->didLayout(modifier);
     }
 
-    m_inLayout = false;
-
     if (inSubtreeLayout)
         rootForThisLayout->view()->popLayoutState(rootForThisLayout);
+
+    lifecycle().advanceTo(DocumentLifecycle::AfterPerformLayout);
 }
 
 void FrameView::scheduleOrPerformPostLayoutTasks()
@@ -927,18 +810,13 @@
     ASSERT(!(m_inSynchronousPostLayout && partialLayout().isStopping()));
 
     if (!m_inSynchronousPostLayout) {
-        if (frame().document()->shouldDisplaySeamlesslyWithParent()) {
-            if (RenderView* renderView = this->renderView())
-                renderView->updateWidgetPositions();
-        } else {
-            m_inSynchronousPostLayout = true;
-            // Calls resumeScheduledEvents()
-            performPostLayoutTasks();
-            m_inSynchronousPostLayout = false;
-        }
+        m_inSynchronousPostLayout = true;
+        // Calls resumeScheduledEvents()
+        performPostLayoutTasks();
+        m_inSynchronousPostLayout = false;
     }
 
-    if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || frame().document()->shouldDisplaySeamlesslyWithParent())) {
+    if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout)) {
         // If we need layout or are already in a synchronous call to postLayoutTasks(),
         // defer widget updates and event dispatch until after we return. postLayoutTasks()
         // can make us need to update again, and we can get stuck in a nasty cycle unless
@@ -956,7 +834,7 @@
     ASSERT(m_frame->view() == this);
     ASSERT(m_frame->page());
 
-    if (m_inLayout)
+    if (isInPerformLayout() || !m_frame->document()->isActive())
         return;
 
     ASSERT(!partialLayout().isStopping());
@@ -970,13 +848,10 @@
     // Every scroll that happens during layout is programmatic.
     TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
 
-    m_layoutTimer.stop();
-    m_delayedLayout = false;
+    m_hasPendingLayout = false;
+    DocumentLifecycle::Scope lifecycleScope(lifecycle(), DocumentLifecycle::LayoutClean);
 
-    // we shouldn't enter layout() while painting
-    ASSERT(!isPainting());
-    if (isPainting())
-        return;
+    RELEASE_ASSERT(!isPainting());
 
     // Store the current maximal outline size to use when computing the old/new
     // outline rects for repainting.
@@ -984,9 +859,9 @@
 
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willLayout(m_frame.get());
 
-    if (!allowSubtree && m_layoutRoot) {
-        m_layoutRoot->markContainingBlocksForLayout(false);
-        m_layoutRoot = 0;
+    if (!allowSubtree && isSubtreeLayout()) {
+        m_layoutSubtreeRoot->markContainingBlocksForLayout(false);
+        m_layoutSubtreeRoot = 0;
     }
 
     performPreLayoutTasks();
@@ -997,8 +872,8 @@
         return;
 
     Document* document = m_frame->document();
-    bool inSubtreeLayout = m_layoutRoot;
-    RenderObject* rootForThisLayout = inSubtreeLayout ? m_layoutRoot : document->renderer();
+    bool inSubtreeLayout = isSubtreeLayout();
+    RenderObject* rootForThisLayout = inSubtreeLayout ? m_layoutSubtreeRoot : document->renderer();
     if (!rootForThisLayout) {
         // FIXME: Do we need to set m_size here?
         ASSERT_NOT_REACHED();
@@ -1007,13 +882,17 @@
 
     bool isPartialLayout = partialLayout().isPartialLayout();
 
+    if (isPartialLayout)
+        lifecycleScope.setFinalState(DocumentLifecycle::StyleClean);
+
+    bool shouldDoFullLayout = false;
     FontCachePurgePreventer fontCachePurgePreventer;
     RenderLayer* layer;
     {
         TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
 
         m_nestedLayoutCount++;
-        if (!m_layoutRoot) {
+        if (!inSubtreeLayout) {
             Document* document = m_frame->document();
             Node* body = document->body();
             if (body && body->renderer()) {
@@ -1030,9 +909,9 @@
 
         ScrollbarMode hMode;
         ScrollbarMode vMode;
-        calculateScrollbarModesForLayout(hMode, vMode);
+        calculateScrollbarModesForLayoutAndSetViewportRenderer(hMode, vMode);
 
-        m_doFullRepaint = !inSubtreeLayout && !isPartialLayout && (m_firstLayout || toRenderView(rootForThisLayout)->document().printing());
+        shouldDoFullLayout = !inSubtreeLayout && !isPartialLayout && (m_firstLayout || toRenderView(rootForThisLayout)->document().printing());
 
         if (!inSubtreeLayout && !isPartialLayout) {
             // Now set our scrollbar state for the layout.
@@ -1066,7 +945,7 @@
             m_size = LayoutSize(layoutSize().width(), layoutSize().height());
 
             if (oldSize != m_size) {
-                m_doFullRepaint = true;
+                shouldDoFullLayout = true;
                 if (!m_firstLayout) {
                     RenderBox* rootRenderer = document->documentElement() ? document->documentElement()->renderBox() : 0;
                     RenderBox* bodyRenderer = rootRenderer && document->body() ? document->body()->renderBox() : 0;
@@ -1080,37 +959,20 @@
 
         layer = rootForThisLayout->enclosingLayer();
 
+        // We need to set m_doFullRepaint before triggering layout as RenderObject::checkForRepaint
+        // checks the boolean to disable local repaints.
+        m_doFullRepaint |= shouldDoFullLayout;
+
         performLayout(rootForThisLayout, inSubtreeLayout);
 
-        m_layoutRoot = 0;
+        m_layoutSubtreeRoot = 0;
     } // Reset m_layoutSchedulingEnabled to its previous value.
 
-    bool neededFullRepaint = m_doFullRepaint;
-
     if (!inSubtreeLayout && !isPartialLayout && !toRenderView(rootForThisLayout)->document().printing())
         adjustViewSize();
 
-    m_doFullRepaint = neededFullRepaint;
+    layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, inSubtreeLayout, m_doFullRepaint));
 
-    {
-        // FIXME: Can this scope just encompass this entire function?
-        FrameView::DeferredRepaintScope deferRepaints(*this);
-
-        if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
-            if (m_doFullRepaint)
-                renderView()->setShouldDoFullRepaintAfterLayout(true);
-
-            if (m_doFullRepaint || !partialLayout().isStopping())
-                repaintTree(rootForThisLayout);
-
-        } else if (m_doFullRepaint) {
-            // FIXME: This isn't really right, since the RenderView doesn't fully encompass
-            // the visibleContentRect(). It just happens to work out most of the time,
-            // since first layouts and printing don't have you scrolled anywhere.
-            renderView()->repaint();
-        }
-        layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, inSubtreeLayout, m_doFullRepaint));
-    }
     updateCompositingLayersAfterLayout();
 
     m_layoutCount++;
@@ -1134,6 +996,22 @@
     if (m_nestedLayoutCount)
         return;
 
+    if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+        if (m_doFullRepaint)
+            renderView()->setShouldDoFullRepaintAfterLayout(true);
+
+        if (m_doFullRepaint || !partialLayout().isStopping())
+            repaintTree(rootForThisLayout);
+
+    } else if (m_doFullRepaint) {
+        // FIXME: This isn't really right, since the RenderView doesn't fully encompass
+        // the visibleContentRect(). It just happens to work out most of the time,
+        // since first layouts and printing don't have you scrolled anywhere.
+        renderView()->repaint();
+    }
+
+    m_doFullRepaint = false;
+
     if (partialLayout().isStopping())
         return;
 
@@ -1143,7 +1021,7 @@
 #endif
 
     // FIXME: It should be not possible to remove the FrameView from the frame/page during layout
-    // however m_inLayout is not set for most of this function, so none of our RELEASE_ASSERTS
+    // however m_inPerformLayout is not set for most of this function, so none of our RELEASE_ASSERTS
     // in Frame/Page will fire. One of the post-layout tasks is disconnecting the Frame from
     // the page in fast/frames/crash-remove-iframe-during-object-beforeload-2.html
     // necessitating this check here.
@@ -1160,8 +1038,19 @@
 {
     ASSERT(RuntimeEnabledFeatures::repaintAfterLayoutEnabled());
     ASSERT(!root->needsLayout());
+    // We should only repaint for the outer most layout. This works as
+    // we continue to track repaint rects until this function is called.
+    ASSERT(!m_nestedLayoutCount);
+
+    // FIXME: really, we're in the repaint phase here, and the compositing queries are legal.
+    // Until those states are fully fledged, I'll just disable the ASSERTS.
+    DisableCompositingQueryAsserts disabler;
 
     for (RenderObject* renderer = root; renderer; renderer = renderer->nextInPreOrder()) {
+        // The repaint rectangles stored on the RenderObjects should all match
+        // the current repaint rectangles for the renderers.
+        ASSERT(renderer->clippedOverflowRectForRepaint(renderer->containerForRepaint()) == renderer->newRepaintRect());
+
         const LayoutRect& oldRepaintRect = renderer->oldRepaintRect();
         const LayoutRect& newRepaintRect = renderer->newRepaintRect();
 
@@ -1183,15 +1072,46 @@
                 }
 
             } else {
-                didFullRepaint = renderer->repaintAfterLayoutIfNeeded(renderer->containerForRepaint(), renderer->shouldDoFullRepaintAfterLayout(),
-                    oldRepaintRect, oldOutlineRect, &newRepaintRect, &newOutlineRect);
+                didFullRepaint = renderer->repaintAfterLayoutIfNeeded(renderer->containerForRepaint(),
+                    renderer->shouldDoFullRepaintAfterLayout(), oldRepaintRect, oldOutlineRect,
+                    &newRepaintRect, &newOutlineRect);
             }
         }
+
         if (!didFullRepaint && renderer->shouldRepaintOverflowIfNeeded())
             renderer->repaintOverflow();
+
+        // Repaint any scrollbars if there is a scrollable area for this renderer.
+        if (renderer->enclosingLayer()) {
+            if (RenderLayerScrollableArea* area = renderer->enclosingLayer()->scrollableArea()) {
+                if (area->hasVerticalBarDamage())
+                    renderer->repaintRectangle(area->verticalBarDamage());
+                if (area->hasHorizontalBarDamage())
+                    renderer->repaintRectangle(area->horizontalBarDamage());
+                area->resetScrollbarDamage();
+            }
+        }
+        // The list box has a verticalScrollbar we may need to repaint.
+        if (renderer->isListBox()) {
+            RenderListBox* listBox = static_cast<RenderListBox*>(renderer);
+            listBox->repaintScrollbarIfNeeded();
+        }
+
         renderer->clearRepaintRects();
     }
     renderView()->setOldMaximalOutlineSize(0);
+
+    // Repaint the frameviews scrollbars if needed
+    if (hasVerticalBarDamage())
+        invalidateRect(verticalBarDamage());
+    if (hasHorizontalBarDamage())
+        invalidateRect(horizontalBarDamage());
+    resetScrollbarDamage();
+}
+
+DocumentLifecycle& FrameView::lifecycle() const
+{
+    return m_frame->document()->lifecycle();
 }
 
 void FrameView::gatherDebugLayoutRects(RenderObject* layoutRoot)
@@ -1206,19 +1126,19 @@
     if (!graphicsLayer)
         return;
 
-    GraphicsLayerDebugInfo* debugInfo = new GraphicsLayerDebugInfo();
+    GraphicsLayerDebugInfo& debugInfo = graphicsLayer->debugInfo();
+
+    debugInfo.currentLayoutRects().clear();
     for (RenderObject* renderer = layoutRoot; renderer; renderer = renderer->nextInPreOrder()) {
         if (renderer->layoutDidGetCalled()) {
-            LayoutRect rect = renderer->newRepaintRect();
-            debugInfo->m_currentLayoutRects.append(rect);
+            FloatQuad quad = renderer->localToAbsoluteQuad(FloatQuad(renderer->newRepaintRect()));
+            LayoutRect rect = quad.enclosingBoundingBox();
+            debugInfo.currentLayoutRects().append(rect);
             renderer->setLayoutDidGetCalled(false);
         }
     }
-
-    graphicsLayer->setDebugInfo(debugInfo);
 }
 
-
 RenderBox* FrameView::embeddedContentBox() const
 {
     RenderView* renderView = this->renderView();
@@ -1236,6 +1156,31 @@
     return 0;
 }
 
+
+void FrameView::addWidget(RenderWidget* object)
+{
+    m_widgets.add(object);
+}
+
+void FrameView::removeWidget(RenderWidget* object)
+{
+    m_widgets.remove(object);
+}
+
+void FrameView::updateWidgetPositions()
+{
+    Vector<RefPtr<RenderWidget> > widgets;
+    copyToVector(m_widgets, widgets);
+
+    // Script or plugins could detach the frame so abort processing if that happens.
+
+    for (size_t i = 0; i < widgets.size() && renderView(); ++i)
+        widgets[i]->updateWidgetPosition();
+
+    for (size_t i = 0; i < widgets.size() && renderView(); ++i)
+        widgets[i]->widgetPositionsUpdated();
+}
+
 void FrameView::addWidgetToUpdate(RenderEmbeddedObject& object)
 {
     // Tell the DOM element that it needs a widget update.
@@ -1259,7 +1204,7 @@
     String overrideType;
     InspectorInstrumentation::applyEmulatedMedia(m_frame.get(), &overrideType);
     if (!overrideType.isNull())
-        return overrideType;
+        return AtomicString(overrideType);
     return m_mediaType;
 }
 
@@ -1306,6 +1251,11 @@
 
 void FrameView::updateCanBlitOnScrollRecursively()
 {
+    // FIXME: useSlowRepaints reads compositing state in nested frames. Compositing state on the nested
+    // frames is not necessarily up to date.
+    // https://code.google.com/p/chromium/issues/detail?id=343766
+    DisableCompositingQueryAsserts disabler;
+
     for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
         if (FrameView* view = frame->view())
             view->setCanBlitOnScroll(!view->useSlowRepaints());
@@ -1394,6 +1344,32 @@
     return viewportRect;
 }
 
+void FrameView::viewportConstrainedVisibleContentRectChanged(bool widthChanged, bool heightChanged)
+{
+    // If viewport is not enabled, frameRect change will cause layout size change and then layout.
+    // Otherwise, viewport constrained objects need their layout flags set separately to ensure
+    // they are positioned correctly.
+    if ((m_frame->settings() && !m_frame->settings()->viewportEnabled()) || !hasViewportConstrainedObjects())
+        return;
+
+    ViewportConstrainedObjectSet::const_iterator end = m_viewportConstrainedObjects->end();
+    for (ViewportConstrainedObjectSet::const_iterator it = m_viewportConstrainedObjects->begin(); it != end; ++it) {
+        RenderObject* renderer = *it;
+        RenderStyle* style = renderer->style();
+        if (widthChanged) {
+            if (style->width().isFixed() && (style->left().isAuto() || style->right().isAuto()))
+                renderer->setNeedsPositionedMovementLayout();
+            else
+                renderer->setNeedsLayout();
+        }
+        if (heightChanged) {
+            if (style->height().isFixed() && (style->top().isAuto() || style->bottom().isAuto()))
+                renderer->setNeedsPositionedMovementLayout();
+            else
+                renderer->setNeedsLayout();
+        }
+    }
+}
 
 IntSize FrameView::scrollOffsetForFixedPosition() const
 {
@@ -1418,6 +1394,8 @@
         return true;
     }
 
+    // https://code.google.com/p/chromium/issues/detail?id=343767
+    DisableCompositingQueryAsserts disabler;
     const bool isCompositedContentLayer = contentsInCompositedLayer();
 
     // Get the rects of the fixed objects visible in the rectToScroll
@@ -1452,7 +1430,7 @@
 
         IntRect updateRect = pixelSnappedIntRect(layer->repainter().repaintRectIncludingNonCompositingDescendants());
 
-        RenderLayer* enclosingCompositingLayer = layer->enclosingCompositingLayer(false);
+        RenderLayer* enclosingCompositingLayer = layer->enclosingCompositingLayer(ExcludeSelf);
         if (enclosingCompositingLayer && !enclosingCompositingLayer->renderer()->isRenderView()) {
             // If the fixed-position layer is contained by a composited layer that is not its containing block,
             // then we have to invlidate that enclosing layer, not the RenderView.
@@ -1498,6 +1476,11 @@
 
 void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
 {
+    // FIXME: This is called when JS calls scrollTo, at which point there's no guarantee that
+    // compositing state is up to date.
+    // https://code.google.com/p/chromium/issues/detail?id=343767
+    DisableCompositingQueryAsserts disabler;
+
     if (contentsInCompositedLayer()) {
         IntRect updateRect = visibleContentRect();
         ASSERT(renderView());
@@ -1526,19 +1509,6 @@
     updateCanBlitOnScrollRecursively();
 }
 
-bool FrameView::isOverlappedIncludingAncestors() const
-{
-    if (isOverlapped())
-        return true;
-
-    if (FrameView* parentView = parentFrameView()) {
-        if (parentView->isOverlapped())
-            return true;
-    }
-
-    return false;
-}
-
 void FrameView::setContentIsOpaque(bool contentIsOpaque)
 {
     if (contentIsOpaque == m_contentIsOpaque)
@@ -1661,18 +1631,6 @@
     notifyScrollPositionChanged(newScrollPosition);
 }
 
-void FrameView::setViewportConstrainedObjectsNeedLayout()
-{
-    if (!hasViewportConstrainedObjects())
-        return;
-
-    ViewportConstrainedObjectSet::const_iterator end = m_viewportConstrainedObjects->end();
-    for (ViewportConstrainedObjectSet::const_iterator it = m_viewportConstrainedObjects->begin(); it != end; ++it) {
-        RenderObject* renderer = *it;
-        renderer->setNeedsLayout();
-    }
-}
-
 IntSize FrameView::layoutSize(IncludeScrollbarsInRect scrollbarInclusion) const
 {
     return scrollbarInclusion == ExcludeScrollbars ? excludeScrollbars(m_layoutSize) : m_layoutSize;
@@ -1687,29 +1645,42 @@
 
 void FrameView::scrollPositionChanged()
 {
-    m_frame->eventHandler().sendScrollEvent();
+    setWasScrolledByUser(true);
+
+    Document* document = m_frame->document();
+    document->enqueueScrollEventForNode(document);
+
     m_frame->eventHandler().dispatchFakeMouseMoveEventSoon();
 
-    if (RenderView* renderView = this->renderView()) {
-        if (renderView->usesCompositing())
+    if (RenderView* renderView = document->renderView()) {
+        if (renderView->usesCompositing()) {
+            // https://code.google.com/p/chromium/issues/detail?id=343767
+            DisableCompositingQueryAsserts disabler;
             renderView->compositor()->frameViewDidScroll();
+        }
     }
 
+    if (m_didScrollTimer.isActive())
+        m_didScrollTimer.stop();
+    m_didScrollTimer.startOneShot(resourcePriorityUpdateDelayAfterScroll);
+}
+
+void FrameView::didScrollTimerFired(Timer<FrameView>*)
+{
     if (m_frame->document() && m_frame->document()->renderer()) {
-        ResourceLoadPriorityOptimizer modifier;
-        m_frame->document()->renderer()->didScroll(modifier);
+        ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->updateAllImageResourcePriorities();
     }
 }
 
 void FrameView::repaintFixedElementsAfterScrolling()
 {
+    RefPtr<FrameView> protect(this);
     // For fixed position elements, update widget positions and compositing layers after scrolling,
     // but only if we're not inside of layout.
     if (!m_nestedLayoutCount && hasViewportConstrainedObjects()) {
-        if (RenderView* renderView = this->renderView()) {
-            renderView->updateWidgetPositions();
+        updateWidgetPositions();
+        if (RenderView* renderView = this->renderView())
             renderView->layer()->updateLayerPositionsAfterDocumentScroll();
-        }
     }
 }
 
@@ -1717,7 +1688,7 @@
 {
     if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
         if (RenderView* renderView = this->renderView())
-            renderView->compositor()->updateCompositingLayers(CompositingUpdateOnScroll);
+            renderView->compositor()->setNeedsCompositingUpdate(CompositingUpdateOnScroll);
     }
 }
 
@@ -1750,10 +1721,9 @@
     return &page->chrome();
 }
 
-const unsigned cRepaintRectUnionThreshold = 25;
-
 void FrameView::repaintContentRectangle(const IntRect& r)
 {
+    ASSERT(repaintAllowed());
     ASSERT(!m_frame->ownerElement());
 
     if (m_isTrackingRepaints) {
@@ -1762,35 +1732,6 @@
         m_trackedRepaintRects.append(repaintRect);
     }
 
-    double delay = m_deferringRepaints ? 0 : adjustedDeferredRepaintDelay();
-    if (m_deferringRepaints || m_deferredRepaintTimer.isActive() || delay) {
-        IntRect paintRect = r;
-        if (clipsRepaints() && !paintsEntireContents())
-            paintRect.intersect(visibleContentRect());
-        if (paintRect.isEmpty())
-            return;
-        if (m_repaintCount == cRepaintRectUnionThreshold) {
-            IntRect unionedRect;
-            for (unsigned i = 0; i < cRepaintRectUnionThreshold; ++i)
-                unionedRect.unite(pixelSnappedIntRect(m_repaintRects[i]));
-            m_repaintRects.clear();
-            m_repaintRects.append(unionedRect);
-        }
-        if (m_repaintCount < cRepaintRectUnionThreshold)
-            m_repaintRects.append(paintRect);
-        else
-            m_repaintRects[0].unite(paintRect);
-        m_repaintCount++;
-
-        if (!m_deferringRepaints)
-            startDeferredRepaintTimer(delay);
-
-        return;
-    }
-
-    if (!shouldUpdate())
-        return;
-
     ScrollView::repaintContentRectangle(r);
 }
 
@@ -1809,11 +1750,20 @@
     if (!frame().view())
         return;
 
+    // Note that simply having overlay scrollbars is not sufficient to be
+    // certain that scrollbars' presence does not impact layout. This should
+    // also check if custom scrollbars (as reported by shouldUseCustomScrollbars)
+    // are in use as well.
+    // http://crbug.com/269692
     bool useOverlayScrollbars = ScrollbarTheme::theme()->usesOverlayScrollbars();
 
     if (!useOverlayScrollbars && needsLayout())
         layout();
 
+    // FIXME: Rather than updating this state synchronously, we should set some dirty bits
+    // and clean them out when updating compositing.
+    // https://code.google.com/p/chromium/issues/detail?id=343756
+    DisableCompositingQueryAsserts disabler;
     if (renderView() && renderView()->usesCompositing()) {
         renderView()->compositor()->frameViewScrollbarsExistenceDidChange();
 
@@ -1822,151 +1772,20 @@
     }
 }
 
-void FrameView::beginDeferredRepaints()
-{
-    Page* page = m_frame->page();
-    ASSERT(page);
-
-    if (!isMainFrame()) {
-        page->mainFrame()->view()->beginDeferredRepaints();
-        return;
-    }
-
-    m_deferringRepaints++;
-}
-
-void FrameView::endDeferredRepaints()
-{
-    Page* page = m_frame->page();
-    ASSERT(page);
-
-    if (!isMainFrame()) {
-        page->mainFrame()->view()->endDeferredRepaints();
-        return;
-    }
-
-    ASSERT(m_deferringRepaints > 0);
-
-    if (--m_deferringRepaints)
-        return;
-
-    if (m_deferredRepaintTimer.isActive())
-        return;
-
-    if (double delay = adjustedDeferredRepaintDelay()) {
-        startDeferredRepaintTimer(delay);
-        return;
-    }
-
-    doDeferredRepaints();
-}
-
-void FrameView::startDeferredRepaintTimer(double delay)
-{
-    if (m_deferredRepaintTimer.isActive())
-        return;
-
-    m_deferredRepaintTimer.startOneShot(delay);
-}
-
 void FrameView::handleLoadCompleted()
 {
     // Once loading has completed, allow autoSize one last opportunity to
     // reduce the size of the frame.
     autoSizeIfEnabled();
-    if (shouldUseLoadTimeDeferredRepaintDelay())
-        return;
-    m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
-    flushDeferredRepaints();
-}
-
-void FrameView::flushDeferredRepaints()
-{
-    if (!m_deferredRepaintTimer.isActive())
-        return;
-    m_deferredRepaintTimer.stop();
-    doDeferredRepaints();
-}
-
-void FrameView::doDeferredRepaints()
-{
-    ASSERT(!m_deferringRepaints);
-    if (!shouldUpdate()) {
-        m_repaintRects.clear();
-        m_repaintCount = 0;
-        return;
-    }
-    unsigned size = m_repaintRects.size();
-    for (unsigned i = 0; i < size; i++) {
-        ScrollView::repaintContentRectangle(pixelSnappedIntRect(m_repaintRects[i]));
-    }
-    m_repaintRects.clear();
-    m_repaintCount = 0;
-
-    updateDeferredRepaintDelayAfterRepaint();
-}
-
-bool FrameView::shouldUseLoadTimeDeferredRepaintDelay() const
-{
-    // Don't defer after the initial load of the page has been completed.
-    if (m_frame->tree().top()->document()->loadEventFinished())
-        return false;
-    Document* document = m_frame->document();
-    if (!document)
-        return false;
-    if (document->parsing())
-        return true;
-    if (document->fetcher()->requestCount())
-        return true;
-    return false;
-}
-
-void FrameView::updateDeferredRepaintDelayAfterRepaint()
-{
-    if (!shouldUseLoadTimeDeferredRepaintDelay()) {
-        m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
-        return;
-    }
-    double incrementedRepaintDelay = m_deferredRepaintDelay + s_deferredRepaintDelayIncrementDuringLoading;
-    m_deferredRepaintDelay = std::min(incrementedRepaintDelay, s_maxDeferredRepaintDelayDuringLoading);
-}
-
-void FrameView::resetDeferredRepaintDelay()
-{
-    m_deferredRepaintDelay = 0;
-    if (m_deferredRepaintTimer.isActive()) {
-        m_deferredRepaintTimer.stop();
-        if (!m_deferringRepaints)
-            doDeferredRepaints();
-    }
-}
-
-double FrameView::adjustedDeferredRepaintDelay() const
-{
-    ASSERT(!m_deferringRepaints);
-    if (!m_deferredRepaintDelay)
-        return 0;
-    double timeSinceLastPaint = currentTime() - m_lastPaintTime;
-    return max(0., m_deferredRepaintDelay - timeSinceLastPaint);
-}
-
-void FrameView::deferredRepaintTimerFired(Timer<FrameView>*)
-{
-    doDeferredRepaints();
-}
-
-void FrameView::layoutTimerFired(Timer<FrameView>*)
-{
-    layout();
 }
 
 void FrameView::scheduleRelayout()
 {
     ASSERT(m_frame->view() == this);
 
-    if (m_layoutRoot) {
-        m_layoutRoot->markContainingBlocksForLayout(false);
-        m_layoutRoot = 0;
+    if (isSubtreeLayout()) {
+        m_layoutSubtreeRoot->markContainingBlocksForLayout(false);
+        m_layoutSubtreeRoot = 0;
     }
     if (!m_layoutSchedulingEnabled)
         return;
@@ -1976,19 +1795,11 @@
         return;
     InspectorInstrumentation::didInvalidateLayout(m_frame.get());
 
-    // When frame seamless is enabled, the contents of the frame could affect the layout of the parent frames.
-    // Also invalidate parent frame starting from the owner element of this frame.
-    if (m_frame->ownerRenderer() && m_frame->document()->shouldDisplaySeamlesslyWithParent())
-        m_frame->ownerRenderer()->setNeedsLayout();
-
-    int delay = m_frame->document()->minimumLayoutDelay();
-    if (m_layoutTimer.isActive() && m_delayedLayout && !delay)
-        unscheduleRelayout();
-    if (m_layoutTimer.isActive())
+    if (m_hasPendingLayout)
         return;
-
-    m_delayedLayout = delay != 0;
-    m_layoutTimer.startOneShot(delay * 0.001);
+    m_hasPendingLayout = true;
+    if (!isServicingAnimations())
+        scheduleAnimation();
 }
 
 static bool isObjectAncestorContainerOf(RenderObject* ancestor, RenderObject* descendant)
@@ -2012,39 +1823,45 @@
     }
 
     if (layoutPending() || !m_layoutSchedulingEnabled) {
-        if (m_layoutRoot != relayoutRoot) {
-            if (isObjectAncestorContainerOf(m_layoutRoot, relayoutRoot)) {
+        if (m_layoutSubtreeRoot != relayoutRoot) {
+            if (isObjectAncestorContainerOf(m_layoutSubtreeRoot, relayoutRoot)) {
                 // Keep the current root
-                relayoutRoot->markContainingBlocksForLayout(false, m_layoutRoot);
-                ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
-            } else if (m_layoutRoot && isObjectAncestorContainerOf(relayoutRoot, m_layoutRoot)) {
+                relayoutRoot->markContainingBlocksForLayout(false, m_layoutSubtreeRoot);
+                ASSERT(!m_layoutSubtreeRoot->container() || !m_layoutSubtreeRoot->container()->needsLayout());
+            } else if (isSubtreeLayout() && isObjectAncestorContainerOf(relayoutRoot, m_layoutSubtreeRoot)) {
                 // Re-root at relayoutRoot
-                m_layoutRoot->markContainingBlocksForLayout(false, relayoutRoot);
-                m_layoutRoot = relayoutRoot;
-                ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
+                m_layoutSubtreeRoot->markContainingBlocksForLayout(false, relayoutRoot);
+                m_layoutSubtreeRoot = relayoutRoot;
+                ASSERT(!m_layoutSubtreeRoot->container() || !m_layoutSubtreeRoot->container()->needsLayout());
                 InspectorInstrumentation::didInvalidateLayout(m_frame.get());
             } else {
                 // Just do a full relayout
-                if (m_layoutRoot)
-                    m_layoutRoot->markContainingBlocksForLayout(false);
-                m_layoutRoot = 0;
+                if (isSubtreeLayout())
+                    m_layoutSubtreeRoot->markContainingBlocksForLayout(false);
+                m_layoutSubtreeRoot = 0;
                 relayoutRoot->markContainingBlocksForLayout(false);
                 InspectorInstrumentation::didInvalidateLayout(m_frame.get());
             }
         }
     } else if (m_layoutSchedulingEnabled) {
-        int delay = m_frame->document()->minimumLayoutDelay();
-        m_layoutRoot = relayoutRoot;
-        ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
+        m_layoutSubtreeRoot = relayoutRoot;
+        ASSERT(!m_layoutSubtreeRoot->container() || !m_layoutSubtreeRoot->container()->needsLayout());
         InspectorInstrumentation::didInvalidateLayout(m_frame.get());
-        m_delayedLayout = delay != 0;
-        m_layoutTimer.startOneShot(delay * 0.001);
+        m_hasPendingLayout = true;
+        if (!isServicingAnimations())
+            scheduleAnimation();
     }
 }
 
 bool FrameView::layoutPending() const
 {
-    return m_layoutTimer.isActive();
+    return m_hasPendingLayout;
+}
+
+bool FrameView::isInPerformLayout() const
+{
+    ASSERT(m_inPerformLayout == (lifecycle().state() == DocumentLifecycle::InPerformLayout));
+    return m_inPerformLayout;
 }
 
 bool FrameView::needsLayout() const
@@ -2056,7 +1873,7 @@
     RenderView* renderView = this->renderView();
     return layoutPending()
         || (renderView && renderView->needsLayout())
-        || m_layoutRoot;
+        || isSubtreeLayout();
 }
 
 void FrameView::setNeedsLayout()
@@ -2065,22 +1882,12 @@
         renderView->setNeedsLayout();
 }
 
-void FrameView::unscheduleRelayout()
-{
-    if (!m_layoutTimer.isActive())
-        return;
-
-    m_layoutTimer.stop();
-    m_delayedLayout = false;
-}
-
 void FrameView::serviceScriptedAnimations(double monotonicAnimationStartTime)
 {
+    TemporaryChange<bool> servicing(m_servicingAnimations, true);
+
     for (RefPtr<Frame> frame = m_frame; frame; frame = frame->tree().traverseNext()) {
         frame->view()->serviceScrollAnimations();
-        if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-            frame->animation().serviceAnimations();
-
         DocumentAnimations::serviceOnAnimationFrame(*frame->document(), monotonicAnimationStartTime);
     }
 
@@ -2116,10 +1923,7 @@
 
 void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
 {
-    if (!backgroundColor.isValid())
-        m_baseBackgroundColor = Color::white;
-    else
-        m_baseBackgroundColor = backgroundColor;
+    m_baseBackgroundColor = backgroundColor;
 
     if (renderView() && renderView()->layer()->hasCompositedLayerMapping()) {
         CompositedLayerMappingPtr compositedLayerMapping = renderView()->layer()->compositedLayerMapping();
@@ -2140,23 +1944,6 @@
     }
 }
 
-bool FrameView::shouldUpdateWhileOffscreen() const
-{
-    return m_shouldUpdateWhileOffscreen;
-}
-
-void FrameView::setShouldUpdateWhileOffscreen(bool shouldUpdateWhileOffscreen)
-{
-    m_shouldUpdateWhileOffscreen = shouldUpdateWhileOffscreen;
-}
-
-bool FrameView::shouldUpdate() const
-{
-    if (isOffscreen() && !shouldUpdateWhileOffscreen())
-        return false;
-    return true;
-}
-
 void FrameView::scrollToAnchor()
 {
     RefPtr<Node> anchorNode = m_maintainScrollPositionAnchor;
@@ -2264,9 +2051,11 @@
 
     FontFaceSet::didLayout(m_frame->document());
 
-    RenderView* renderView = this->renderView();
-    if (renderView)
-        renderView->updateWidgetPositions();
+    updateWidgetPositions();
+
+    // Plugins could have torn down the page inside updateWidgetPositions().
+    if (!renderView())
+        return;
 
     if (!m_updateWidgetsTimer.isActive())
         m_updateWidgetsTimer.startOneShot(0);
@@ -2336,16 +2125,11 @@
     TemporaryChange<bool> changeInAutoSize(m_inAutoSize, true);
 
     Document* document = frame().document();
-    if (!document)
+    if (!document || !document->isActive())
         return;
 
-    RenderView* documentView = document->renderView();
     Element* documentElement = document->documentElement();
-    if (!documentView || !documentElement)
-        return;
-
-    RenderBox* documentRenderBox = documentElement->renderBox();
-    if (!documentRenderBox)
+    if (!documentElement)
         return;
 
     // If this is the first time we run autosize, start from small height and
@@ -2360,7 +2144,17 @@
     for (int i = 0; i < 2; i++) {
         // Update various sizes including contentsSize, scrollHeight, etc.
         document->updateLayoutIgnorePendingStylesheets();
-        int width = documentView->minPreferredLogicalWidth();
+
+        RenderView* renderView = document->renderView();
+        if (!renderView)
+            return;
+
+        int width = renderView->minPreferredLogicalWidth();
+
+        RenderBox* documentRenderBox = documentElement->renderBox();
+        if (!documentRenderBox)
+            return;
+
         int height = documentRenderBox->scrollHeight();
         IntSize newSize(width, height);
 
@@ -2448,27 +2242,6 @@
 
 }
 
-const Pagination& FrameView::pagination() const
-{
-    if (m_pagination != Pagination())
-        return m_pagination;
-
-    if (isMainFrame())
-        return m_frame->page()->pagination();
-
-    return m_pagination;
-}
-
-void FrameView::setPagination(const Pagination& pagination)
-{
-    if (m_pagination == pagination)
-        return;
-
-    m_pagination = pagination;
-
-    m_frame->document()->styleResolverChanged(RecalcStyleDeferred);
-}
-
 IntRect FrameView::windowClipRect(bool clipToContents) const
 {
     ASSERT(m_frame->view() == this);
@@ -2503,10 +2276,14 @@
 
     // Apply the clip from the layer.
     IntRect clipRect;
-    if (clipToLayerContents)
-        clipRect = pixelSnappedIntRect(enclosingLayer->childrenClipRect());
-    else
-        clipRect = pixelSnappedIntRect(enclosingLayer->selfClipRect());
+    if (clipToLayerContents) {
+        // FIXME: childrenClipRect relies on compositingState, which is not necessarily up to date.
+        // https://code.google.com/p/chromium/issues/detail?id=343769
+        DisableCompositingQueryAsserts disabler;
+        clipRect = pixelSnappedIntRect(enclosingLayer->clipper().childrenClipRect());
+    } else {
+        clipRect = pixelSnappedIntRect(enclosingLayer->clipper().selfClipRect());
+    }
     clipRect = contentsToWindow(clipRect);
     return intersection(clipRect, windowClipRect());
 }
@@ -2531,7 +2308,18 @@
     // Add in our offset within the FrameView.
     IntRect dirtyRect = rect;
     dirtyRect.moveBy(scrollbar->location());
-    invalidateRect(dirtyRect);
+
+    if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && isInPerformLayout()) {
+        if (scrollbar == verticalScrollbar()) {
+            m_verticalBarDamage = dirtyRect;
+            m_hasVerticalBarDamage = true;
+        } else {
+            m_horizontalBarDamage = dirtyRect;
+            m_hasHorizontalBarDamage = true;
+        }
+    } else {
+        invalidateRect(dirtyRect);
+    }
 }
 
 void FrameView::getTickmarks(Vector<IntRect>& tickmarks) const
@@ -2617,7 +2405,7 @@
     // Cover #3 and #4.
     ScrollbarMode horizontalMode;
     ScrollbarMode verticalMode;
-    calculateScrollbarModesForLayout(horizontalMode, verticalMode, RulesFromWebContentOnly);
+    calculateScrollbarModesForLayoutAndSetViewportRenderer(horizontalMode, verticalMode, RulesFromWebContentOnly);
     if (horizontalMode == ScrollbarAlwaysOff && verticalMode == ScrollbarAlwaysOff)
         return false;
 
@@ -2653,26 +2441,6 @@
         ScrollView::scrollbarStyleChanged(newStyle, forceUpdate);
 }
 
-void FrameView::setAnimatorsAreActive()
-{
-    Page* page = m_frame->page();
-    if (!page)
-        return;
-
-    if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
-        scrollAnimator->setIsActive();
-
-    if (!m_scrollableAreas)
-        return;
-
-    for (HashSet<ScrollableArea*>::const_iterator it = m_scrollableAreas->begin(), end = m_scrollableAreas->end(); it != end; ++it) {
-        ScrollableArea* scrollableArea = *it;
-
-        ASSERT(scrollableArea->scrollbarsCanBeActive());
-        scrollableArea->scrollAnimator()->setIsActive();
-    }
-}
-
 void FrameView::notifyPageThatContentAreaWillPaint() const
 {
     Page* page = m_frame->page();
@@ -2792,30 +2560,13 @@
     // the document and the body against the base background color of the frame view.
     // Background images are unfortunately impractical to include.
 
-    // Return invalid Color objects whenever there is insufficient information.
+    Color result = baseBackgroundColor();
     if (!frame().document())
-        return Color();
+        return result;
 
     Element* htmlElement = frame().document()->documentElement();
     Element* bodyElement = frame().document()->body();
 
-    // Start with invalid colors.
-    Color htmlBackgroundColor;
-    Color bodyBackgroundColor;
-    if (htmlElement && htmlElement->renderer())
-        htmlBackgroundColor = htmlElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
-    if (bodyElement && bodyElement->renderer())
-        bodyBackgroundColor = bodyElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
-
-    if (!bodyBackgroundColor.isValid()) {
-        if (!htmlBackgroundColor.isValid())
-            return Color();
-        return baseBackgroundColor().blend(htmlBackgroundColor);
-    }
-
-    if (!htmlBackgroundColor.isValid())
-        return baseBackgroundColor().blend(bodyBackgroundColor);
-
     // We take the aggregate of the base background color
     // the <html> background color, and the <body>
     // background color to find the document color. The
@@ -2823,7 +2574,12 @@
     // technically part of the document background, but it
     // otherwise poses problems when the aggregate is not
     // fully opaque.
-    return baseBackgroundColor().blend(htmlBackgroundColor).blend(bodyBackgroundColor);
+    if (htmlElement && htmlElement->renderer())
+        result = result.blend(htmlElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor));
+    if (bodyElement && bodyElement->renderer())
+        result = result.blend(bodyElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor));
+
+    return result;
 }
 
 bool FrameView::hasCustomScrollbars() const
@@ -2867,12 +2623,12 @@
     if (m_frame->document()->url().isEmpty())
         return;
 
-    if (RenderTheme::theme().supportsControlTints() || hasCustomScrollbars())
-        paintControlTints();
-}
+    // FIXME: Why do we need this for hasCustomScrollbars?
+    // FIXME: supportsControlTints is currently true for a bunch of platforms.
+    // It should only be for Mac 10.6.
+    if (!RenderTheme::theme().supportsControlTints() && !hasCustomScrollbars())
+        return;
 
-void FrameView::paintControlTints()
-{
     if (needsLayout())
         layout();
     // FIXME: The use of paint seems like overkill: crbug.com/236892
@@ -3036,22 +2792,18 @@
     if (needsLayout())
         layout();
 
-    // Grab a copy of the children() set, as it may be mutated by the following updateLayoutAndStyleIfNeededRecursive
-    // calls, as they can potentially re-enter a layout of the parent frame view, which may add/remove scrollbars
-    // and thus mutates the children() set.
+    // FIXME: Calling layout() shouldn't trigger scripe execution or have any
+    // observable effects on the frame tree but we're not quite there yet.
     Vector<RefPtr<FrameView> > frameViews;
-    collectFrameViewChildren(this, frameViews);
+    for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
+        if (FrameView* view = child->view())
+            frameViews.append(view);
+    }
 
     const Vector<RefPtr<FrameView> >::iterator end = frameViews.end();
     for (Vector<RefPtr<FrameView> >::iterator it = frameViews.begin(); it != end; ++it)
         (*it)->updateLayoutAndStyleIfNeededRecursive();
 
-    // updateLayoutAndStyleIfNeededRecursive is called when we need to make sure style and layout are up-to-date before
-    // painting, so we need to flush out any deferred repaints too.
-    flushDeferredRepaints();
-
-    // When seamless is on, child frame can mark parent frame dirty. In such case, child frame
-    // needs to call layout on parent frame recursively.
     // This assert ensures that parent frames are clean, when child frames finished updating layout and style.
     ASSERT(!needsLayout());
 }
@@ -3088,7 +2840,7 @@
     layout(allowSubtree);
 }
 
-void FrameView::forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor, AdjustViewSizeOrNot shouldAdjustViewSize)
+void FrameView::forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor)
 {
     // Dumping externalRepresentation(m_frame->renderer()).ascii() is a good trick to see
     // the state of things before and after the layout
@@ -3140,8 +2892,7 @@
         }
     }
 
-    if (shouldAdjustViewSize)
-        adjustViewSize();
+    adjustViewSize();
 }
 
 IntRect FrameView::convertFromRenderer(const RenderObject* renderer, const IntRect& rendererRect) const
@@ -3282,30 +3033,6 @@
     return parentPoint;
 }
 
-// Normal delay
-void FrameView::setRepaintThrottlingDeferredRepaintDelay(double p)
-{
-    s_normalDeferredRepaintDelay = p;
-}
-
-// Negative value would mean that first few repaints happen without a delay
-void FrameView::setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(double p)
-{
-    s_initialDeferredRepaintDelayDuringLoading = p;
-}
-
-// The delay grows on each repaint to this maximum value
-void FrameView::setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(double p)
-{
-    s_maxDeferredRepaintDelayDuringLoading = p;
-}
-
-// On each repaint the delay increases by this amount
-void FrameView::setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(double p)
-{
-    s_deferredRepaintDelayIncrementDuringLoading = p;
-}
-
 void FrameView::setTracksRepaints(bool trackRepaints)
 {
     if (trackRepaints == m_isTrackingRepaints)
diff --git a/Source/core/frame/FrameView.h b/Source/core/frame/FrameView.h
index 084317c..0217810 100644
--- a/Source/core/frame/FrameView.h
+++ b/Source/core/frame/FrameView.h
@@ -25,8 +25,6 @@
 #ifndef FrameView_h
 #define FrameView_h
 
-#include "core/frame/AdjustViewSizeOrNot.h"
-#include "core/rendering/Pagination.h"
 #include "core/rendering/PaintPhase.h"
 #include "core/rendering/PartialLayoutState.h"
 #include "platform/geometry/LayoutRect.h"
@@ -50,12 +48,11 @@
 class RenderObject;
 class RenderScrollbarPart;
 class RenderStyle;
-
-Pagination::Mode paginationModeForRenderStyle(RenderStyle*);
+class RenderWidget;
 
 typedef unsigned long long DOMTimeStamp;
 
-class FrameView : public ScrollView {
+class FrameView FINAL : public ScrollView {
 public:
     friend class RenderView;
     friend class Internals;
@@ -65,45 +62,39 @@
 
     virtual ~FrameView();
 
-    virtual HostWindow* hostWindow() const;
+    virtual HostWindow* hostWindow() const OVERRIDE;
 
-    virtual void invalidateRect(const IntRect&);
-    virtual void setFrameRect(const IntRect&);
+    virtual void invalidateRect(const IntRect&) OVERRIDE;
+    virtual void setFrameRect(const IntRect&) OVERRIDE;
 
-    virtual bool scheduleAnimation();
+    virtual bool scheduleAnimation() OVERRIDE;
 
     Frame& frame() const { return *m_frame; }
 
     RenderView* renderView() const;
 
-    LayoutUnit marginWidth() const { return m_margins.width(); } // -1 means default
-    LayoutUnit marginHeight() const { return m_margins.height(); } // -1 means default
-    void setMarginWidth(LayoutUnit);
-    void setMarginHeight(LayoutUnit);
+    virtual void setCanHaveScrollbars(bool) OVERRIDE;
 
-    virtual void setCanHaveScrollbars(bool);
-    void updateCanHaveScrollbars();
+    virtual PassRefPtr<Scrollbar> createScrollbar(ScrollbarOrientation) OVERRIDE;
 
-    virtual PassRefPtr<Scrollbar> createScrollbar(ScrollbarOrientation);
-
-    virtual void setContentsSize(const IntSize&);
+    virtual void setContentsSize(const IntSize&) OVERRIDE;
 
     void layout(bool allowSubtree = true);
     bool didFirstLayout() const;
-    void layoutTimerFired(Timer<FrameView>*);
     void scheduleRelayout();
     void scheduleRelayoutOfSubtree(RenderObject*);
-    void unscheduleRelayout();
     bool layoutPending() const;
-    bool isInLayout() const { return m_inLayout; }
+    bool isInPerformLayout() const;
+
+    void setCanRepaintDuringPerformLayout(bool b) { m_canRepaintDuringPerformLayout = b; }
+    bool canRepaintDuringPerformLayout() const { return m_canRepaintDuringPerformLayout; }
 
     RenderObject* layoutRoot(bool onlyDuringLayout = false) const;
-    void clearLayoutRoot() { m_layoutRoot = 0; }
+    void clearLayoutSubtreeRoot() { m_layoutSubtreeRoot = 0; }
     int layoutCount() const { return m_layoutCount; }
 
     bool needsLayout() const;
     void setNeedsLayout();
-    void setViewportConstrainedObjectsNeedLayout();
 
     // Methods for getting/setting the size Blink should use to layout the contents.
     IntSize layoutSize(IncludeScrollbarsInRect = ExcludeScrollbars) const;
@@ -145,16 +136,12 @@
     void setBaseBackgroundColor(const Color&);
     void updateBackgroundRecursively(const Color&, bool);
 
-    bool shouldUpdateWhileOffscreen() const;
-    void setShouldUpdateWhileOffscreen(bool);
-    bool shouldUpdate() const;
-
     void adjustViewSize();
 
-    virtual IntRect windowClipRect(bool clipToContents = true) const;
+    virtual IntRect windowClipRect(bool clipToContents = true) const OVERRIDE;
     IntRect windowClipRectForFrameOwner(const HTMLFrameOwnerElement*, bool clipToLayerContents) const;
 
-    virtual IntRect windowResizerRect() const;
+    virtual IntRect windowResizerRect() const OVERRIDE;
 
     virtual float visibleContentScaleFactor() const OVERRIDE { return m_visibleContentScaleFactor; }
     void setVisibleContentScaleFactor(float);
@@ -164,15 +151,16 @@
     void setInputEventsTransformForEmulation(const IntSize&, float);
 
     virtual void setScrollPosition(const IntPoint&) OVERRIDE;
-    virtual void repaintFixedElementsAfterScrolling();
-    virtual void updateFixedElementsAfterScrolling();
-    virtual bool shouldRubberBandInDirection(ScrollDirection) const;
+    virtual void repaintFixedElementsAfterScrolling() OVERRIDE;
+    virtual void updateFixedElementsAfterScrolling() OVERRIDE;
+    virtual bool shouldRubberBandInDirection(ScrollDirection) const OVERRIDE;
     virtual bool isRubberBandInProgress() const OVERRIDE;
     void setScrollPositionNonProgrammatically(const IntPoint&);
 
     // This is different than visibleContentRect() in that it ignores negative (or overly positive)
     // offsets from rubber-banding, and it takes zooming into account.
     LayoutRect viewportConstrainedVisibleContentRect() const;
+    void viewportConstrainedVisibleContentRectChanged(bool viewportWidthChanged, bool viewportHeightChanged);
 
     AtomicString mediaType() const;
     void setMediaType(const AtomicString&);
@@ -181,7 +169,6 @@
     void setCannotBlitToWindow();
     void setIsOverlapped(bool);
     bool isOverlapped() const { return m_isOverlapped; }
-    bool isOverlappedIncludingAncestors() const;
     void setContentIsOpaque(bool);
 
     void addSlowRepaintObject();
@@ -196,7 +183,6 @@
     bool hasViewportConstrainedObjects() const { return m_viewportConstrainedObjects && m_viewportConstrainedObjects->size() > 0; }
 
     void handleLoadCompleted();
-    void resetDeferredRepaintDelay();
 
     void updateAnnotatedRegions();
     void updateControlTints();
@@ -211,18 +197,23 @@
     bool safeToPropagateScrollToParent() const { return m_safeToPropagateScrollToParent; }
     void setSafeToPropagateScrollToParent(bool isSafe) { m_safeToPropagateScrollToParent = isSafe; }
 
+    void addWidget(RenderWidget*);
+    void removeWidget(RenderWidget*);
+    void updateWidgetPositions();
+
     void addWidgetToUpdate(RenderEmbeddedObject&);
 
-    virtual void paintContents(GraphicsContext*, const IntRect& damageRect);
+    virtual void paintContents(GraphicsContext*, const IntRect& damageRect) OVERRIDE;
     void setPaintBehavior(PaintBehavior);
     PaintBehavior paintBehavior() const;
     bool isPainting() const;
     bool hasEverPainted() const { return m_lastPaintTime; }
-    void setLastPaintTime(double lastPaintTime) { m_lastPaintTime = lastPaintTime; }
     void setNodeToDraw(Node*);
 
-    virtual void paintOverhangAreas(GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect);
-    virtual void paintScrollCorner(GraphicsContext*, const IntRect& cornerRect);
+    bool isServicingAnimations() const { return m_servicingAnimations; }
+
+    virtual void paintOverhangAreas(GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect) OVERRIDE;
+    virtual void paintScrollCorner(GraphicsContext*, const IntRect& cornerRect) OVERRIDE;
     virtual void paintScrollbar(GraphicsContext*, Scrollbar*, const IntRect&) OVERRIDE;
 
     Color documentBackgroundColor() const;
@@ -234,11 +225,10 @@
     void incrementVisuallyNonEmptyCharacterCount(unsigned);
     void incrementVisuallyNonEmptyPixelCount(const IntSize&);
     void setIsVisuallyNonEmpty() { m_isVisuallyNonEmpty = true; }
-    bool isVisuallyNonEmpty() const { return m_isVisuallyNonEmpty; }
     void enableAutoSizeMode(bool enable, const IntSize& minSize, const IntSize& maxSize);
 
     void forceLayout(bool allowSubtree = false);
-    void forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor, AdjustViewSizeOrNot);
+    void forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor);
 
     bool scrollToFragment(const KURL&);
     bool scrollToAnchor(const String&);
@@ -246,28 +236,19 @@
     void scrollElementToRect(Element*, const IntRect&);
 
     // Methods to convert points and rects between the coordinate space of the renderer, and this view.
-    virtual IntRect convertFromRenderer(const RenderObject*, const IntRect&) const;
-    virtual IntRect convertToRenderer(const RenderObject*, const IntRect&) const;
-    virtual IntPoint convertFromRenderer(const RenderObject*, const IntPoint&) const;
-    virtual IntPoint convertToRenderer(const RenderObject*, const IntPoint&) const;
+    IntRect convertFromRenderer(const RenderObject*, const IntRect&) const;
+    IntRect convertToRenderer(const RenderObject*, const IntRect&) const;
+    IntPoint convertFromRenderer(const RenderObject*, const IntPoint&) const;
+    IntPoint convertToRenderer(const RenderObject*, const IntPoint&) const;
 
     bool isFrameViewScrollCorner(RenderScrollbarPart* scrollCorner) const { return m_scrollCorner == scrollCorner; }
 
     bool isScrollable();
 
     enum ScrollbarModesCalculationStrategy { RulesFromWebContentOnly, AnyRule };
-    void calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy = AnyRule);
+    void calculateScrollbarModesForLayoutAndSetViewportRenderer(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy = AnyRule);
 
-    // Normal delay
-    static void setRepaintThrottlingDeferredRepaintDelay(double);
-    // Negative value would mean that first few repaints happen without a delay
-    static void setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(double);
-    // The delay grows on each repaint to this maximum value
-    static void setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(double);
-    // On each repaint the delay increses by this amount
-    static void setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(double);
-
-    virtual IntPoint lastKnownMousePosition() const;
+    virtual IntPoint lastKnownMousePosition() const OVERRIDE;
     bool shouldSetCursor() const;
 
     void setCursor(const Cursor&);
@@ -277,17 +258,14 @@
     // FIXME: Remove this method once plugin loading is decoupled from layout.
     void flushAnyPendingPostLayoutTasks();
 
-    virtual bool shouldSuspendScrollAnimations() const;
-    virtual void scrollbarStyleChanged(int newStyle, bool forceUpdate);
-
-    void setAnimatorsAreActive();
+    virtual bool shouldSuspendScrollAnimations() const OVERRIDE;
+    virtual void scrollbarStyleChanged(int newStyle, bool forceUpdate) OVERRIDE;
 
     RenderBox* embeddedContentBox() const;
 
     void setTracksRepaints(bool);
     bool isTrackingRepaints() const { return m_isTrackingRepaints; }
     void resetTrackedRepaints();
-    const Vector<IntRect>& trackedRepaintRects() const { return m_trackedRepaintRects; }
     String trackedRepaintRectsAsText() const;
 
     typedef HashSet<ScrollableArea*> ScrollableAreaSet;
@@ -313,15 +291,6 @@
     // we need this function in order to do the scroll ourselves.
     bool wheelEvent(const PlatformWheelEvent&);
 
-    // Page and FrameView both store a Pagination value. Page::pagination() is set only by API,
-    // and FrameView::pagination() is set only by CSS. Page::pagination() will affect all
-    // FrameViews in the page cache, but FrameView::pagination() only affects the current
-    // FrameView. FrameView::pagination() will return m_pagination if it has been set. Otherwise,
-    // it will return Page::pagination() since currently there are no callers that need to
-    // distinguish between the two.
-    const Pagination& pagination() const;
-    void setPagination(const Pagination&);
-
     bool inProgrammaticScroll() const { return m_inProgrammaticScroll; }
     void setInProgrammaticScroll(bool programmaticScroll) { m_inProgrammaticScroll = programmaticScroll; }
 
@@ -339,33 +308,20 @@
     virtual void didAddScrollbar(Scrollbar*, ScrollbarOrientation) OVERRIDE;
     virtual void willRemoveScrollbar(Scrollbar*, ScrollbarOrientation) OVERRIDE;
 
-    class DeferredRepaintScope {
-    public:
-        DeferredRepaintScope(FrameView&);
-        ~DeferredRepaintScope();
-    private:
-        RefPtr<FrameView> m_view;
-    };
-
 protected:
-    virtual bool scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect);
-    virtual void scrollContentsSlowPath(const IntRect& updateRect);
+    virtual bool scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect) OVERRIDE;
+    virtual void scrollContentsSlowPath(const IntRect& updateRect) OVERRIDE;
 
-    virtual bool isVerticalDocument() const;
-    virtual bool isFlippedDocument() const;
+    virtual bool isVerticalDocument() const OVERRIDE;
+    virtual bool isFlippedDocument() const OVERRIDE;
 
 private:
     explicit FrameView(Frame*);
 
-    void beginDeferredRepaints();
-    void endDeferredRepaints();
-    void flushDeferredRepaints();
-    void startDeferredRepaintTimer(double delay);
-
     void reset();
     void init();
 
-    virtual void frameRectsChanged();
+    virtual void frameRectsChanged() OVERRIDE;
     virtual bool isFrameView() const OVERRIDE { return true; }
 
     friend class RenderWidget;
@@ -374,13 +330,9 @@
     void updateCanBlitOnScrollRecursively();
     bool contentsInCompositedLayer() const;
 
-    void applyOverflowToViewport(RenderObject*, ScrollbarMode& hMode, ScrollbarMode& vMode);
-    void applyPaginationToViewport();
-
+    void applyOverflowToViewportAndSetRenderer(RenderObject*, ScrollbarMode& hMode, ScrollbarMode& vMode);
     void updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow);
 
-    void paintControlTints();
-
     void updateCounters();
     void autoSizeIfEnabled();
     void forceLayoutParentViewIfNeeded();
@@ -391,11 +343,13 @@
 
     void repaintTree(RenderObject* root);
 
-    virtual void gatherDebugLayoutRects(RenderObject* layoutRoot);
+    void gatherDebugLayoutRects(RenderObject* layoutRoot);
 
-    virtual void repaintContentRectangle(const IntRect&);
+    DocumentLifecycle& lifecycle() const;
+
+    virtual void repaintContentRectangle(const IntRect&) OVERRIDE;
     virtual void contentsResized() OVERRIDE;
-    virtual void scrollbarExistenceDidChange();
+    virtual void scrollbarExistenceDidChange() OVERRIDE;
 
     // Override ScrollView methods to do point conversion via renderers, in order to
     // take transforms into account.
@@ -421,42 +375,49 @@
 
     void updateScrollableAreaSet();
 
-    virtual void notifyPageThatContentAreaWillPaint() const;
-
-    bool shouldUseLoadTimeDeferredRepaintDelay() const;
-    void deferredRepaintTimerFired(Timer<FrameView>*);
-    void doDeferredRepaints();
-    void updateDeferredRepaintDelayAfterRepaint();
-    double adjustedDeferredRepaintDelay() const;
+    virtual void notifyPageThatContentAreaWillPaint() const OVERRIDE;
 
     void updateWidgetsTimerFired(Timer<FrameView>*);
     bool updateWidgets();
 
     void scrollToAnchor();
     void scrollPositionChanged();
+    void didScrollTimerFired(Timer<FrameView>*);
 
     bool hasCustomScrollbars() const;
+    bool shouldUseCustomScrollbars(Element*& customScrollbarElement, Frame*& customScrollbarFrame);
 
-    virtual void updateScrollCorner();
+    virtual void updateScrollCorner() OVERRIDE;
 
     FrameView* parentFrameView() const;
 
-    virtual AXObjectCache* axObjectCache() const;
+    AXObjectCache* axObjectCache() const;
     void removeFromAXObjectCache();
 
     bool isMainFrame() const;
 
     void setLayoutSizeInternal(const IntSize&);
 
+    bool isSubtreeLayout() const { return !!m_layoutSubtreeRoot; }
+    bool repaintAllowed() const
+    {
+        if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+            return true;
+
+        return !isInPerformLayout() || canRepaintDuringPerformLayout();
+    }
+
     static double s_currentFrameTimeStamp; // used for detecting decoded resource thrash in the cache
     static bool s_inPaintContents;
 
     LayoutSize m_size;
-    LayoutSize m_margins;
 
     typedef HashSet<RefPtr<RenderEmbeddedObject> > EmbeddedObjectSet;
     EmbeddedObjectSet m_widgetUpdateSet;
 
+    // FIXME: These are just "children" of the FrameView and should be RefPtr<Widget> instead.
+    HashSet<RefPtr<RenderWidget> > m_widgets;
+
     RefPtr<Frame> m_frame;
 
     bool m_doFullRepaint;
@@ -466,15 +427,13 @@
     bool m_isOverlapped;
     bool m_contentIsOpaque;
     unsigned m_slowRepaintObjectCount;
-    int m_borderX;
-    int m_borderY;
 
-    Timer<FrameView> m_layoutTimer;
-    bool m_delayedLayout;
-    RenderObject* m_layoutRoot;
+    bool m_hasPendingLayout;
+    RenderObject* m_layoutSubtreeRoot;
 
     bool m_layoutSchedulingEnabled;
-    bool m_inLayout;
+    bool m_inPerformLayout;
+    bool m_canRepaintDuringPerformLayout;
     bool m_doingPreLayoutStyleUpdate;
     bool m_inSynchronousPostLayout;
     int m_layoutCount;
@@ -497,24 +456,15 @@
     bool m_verticalOverflow;
     RenderObject* m_viewportRenderer;
 
-    Pagination m_pagination;
-
     bool m_wasScrolledByUser;
     bool m_inProgrammaticScroll;
     bool m_safeToPropagateScrollToParent;
 
-    unsigned m_deferringRepaints;
-    unsigned m_repaintCount;
-    Vector<LayoutRect> m_repaintRects;
-    Timer<FrameView> m_deferredRepaintTimer;
-    double m_deferredRepaintDelay;
     double m_lastPaintTime;
 
     bool m_isTrackingRepaints; // Used for testing.
     Vector<IntRect> m_trackedRepaintRects;
 
-    bool m_shouldUpdateWhileOffscreen;
-
     RefPtr<Node> m_nodeToDraw;
     PaintBehavior m_paintBehavior;
     bool m_isPainting;
@@ -543,13 +493,10 @@
     OwnPtr<ResizerAreaSet> m_resizerAreas;
     OwnPtr<ViewportConstrainedObjectSet> m_viewportConstrainedObjects;
 
-    static double s_normalDeferredRepaintDelay;
-    static double s_initialDeferredRepaintDelayDuringLoading;
-    static double s_maxDeferredRepaintDelayDuringLoading;
-    static double s_deferredRepaintDelayIncrementDuringLoading;
-
     bool m_hasSoftwareFilters;
 
+    bool m_servicingAnimations;
+
     float m_visibleContentScaleFactor;
     IntSize m_inputEventsOffsetForEmulation;
     float m_inputEventsScaleFactorForEmulation;
@@ -557,6 +504,8 @@
     PartialLayoutState m_partialLayout;
     IntSize m_layoutSize;
     bool m_layoutSizeFixedToFrameSize;
+
+    Timer<FrameView> m_didScrollTimer;
 };
 
 inline void FrameView::incrementVisuallyNonEmptyCharacterCount(unsigned count)
@@ -582,20 +531,31 @@
         setIsVisuallyNonEmpty();
 }
 
-inline FrameView* toFrameView(Widget* widget)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isFrameView());
-    return static_cast<FrameView*>(widget);
-}
+DEFINE_TYPE_CASTS(FrameView, Widget, widget, widget->isFrameView(), widget.isFrameView());
 
-inline const FrameView* toFrameView(const Widget* widget)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isFrameView());
-    return static_cast<const FrameView*>(widget);
-}
+class AllowRepaintScope {
+public:
+    explicit AllowRepaintScope(FrameView* view)
+        : m_view(view)
+        , m_originalValue(view ? view->canRepaintDuringPerformLayout() : false)
+    {
+        if (!m_view)
+            return;
 
-// This will catch anyone doing an unnecessary cast.
-void toFrameView(const FrameView*);
+        m_view->setCanRepaintDuringPerformLayout(true);
+    }
+
+    ~AllowRepaintScope()
+    {
+        if (!m_view)
+            return;
+
+        m_view->setCanRepaintDuringPerformLayout(m_originalValue);
+    }
+private:
+    FrameView* m_view;
+    bool m_originalValue;
+};
 
 } // namespace WebCore
 
diff --git a/Source/core/frame/GraphicsLayerDebugInfo.cpp b/Source/core/frame/GraphicsLayerDebugInfo.cpp
deleted file mode 100644
index 51470a2..0000000
--- a/Source/core/frame/GraphicsLayerDebugInfo.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/frame/GraphicsLayerDebugInfo.h"
-
-#include "platform/JSONValues.h"
-#include "wtf/text/CString.h"
-
-namespace WebCore {
-
-void GraphicsLayerDebugInfo::appendAsTraceFormat(blink::WebString* out) const
-{
-    RefPtr<JSONArray> jsonArray = JSONArray::create();
-    for (size_t i = 0; i < m_currentLayoutRects.size(); i++) {
-        const LayoutRect& rect = m_currentLayoutRects[i];
-        RefPtr<JSONObject> rectContainer = JSONObject::create();
-        RefPtr<JSONArray> rectArray = JSONArray::create();
-        rectArray->pushNumber(rect.x().toFloat());
-        rectArray->pushNumber(rect.y().toFloat());
-        rectArray->pushNumber(rect.maxX().toFloat());
-        rectArray->pushNumber(rect.maxY().toFloat());
-        rectContainer->setArray("geometry_rect", rectArray);
-        jsonArray->pushObject(rectContainer);
-    }
-    *out = jsonArray->toJSONString();
-}
-
-} // namespace WebCore
diff --git a/Source/core/frame/History.cpp b/Source/core/frame/History.cpp
index 863c936..1ee748d 100644
--- a/Source/core/frame/History.cpp
+++ b/Source/core/frame/History.cpp
@@ -29,11 +29,11 @@
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/history/HistoryItem.h"
+#include "core/frame/Frame.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/frame/Frame.h"
+#include "core/loader/HistoryItem.h"
 #include "core/page/BackForwardClient.h"
 #include "core/page/Page.h"
 #include "platform/weborigin/KURL.h"
@@ -123,7 +123,7 @@
     return KURL(document->baseURL(), urlString);
 }
 
-void History::stateObjectAdded(PassRefPtr<SerializedScriptValue> data, const String& /* title */, const String& urlString, SameDocumentNavigationSource sameDocumentNavigationSource, ExceptionState& exceptionState)
+void History::stateObjectAdded(PassRefPtr<SerializedScriptValue> data, const String& /* title */, const String& urlString, UpdateBackForwardListPolicy updateBackForwardListPolicy, ExceptionState& exceptionState)
 {
     if (!m_frame || !m_frame->page())
         return;
@@ -134,7 +134,7 @@
         exceptionState.throwSecurityError("A history state object with URL '" + fullURL.elidedString() + "' cannot be created in a document with origin '" + m_frame->document()->securityOrigin()->toString() + "'.");
         return;
     }
-    m_frame->loader().updateForSameDocumentNavigation(fullURL, sameDocumentNavigationSource, data, FrameLoader::DoNotUpdateBackForwardList);
+    m_frame->loader().updateForSameDocumentNavigation(fullURL, SameDocumentNavigationHistoryApi, data, updateBackForwardListPolicy);
 }
 
 } // namespace WebCore
diff --git a/Source/core/frame/History.h b/Source/core/frame/History.h
index 42ec345..40abf0d 100644
--- a/Source/core/frame/History.h
+++ b/Source/core/frame/History.h
@@ -41,7 +41,7 @@
 class ExecutionContext;
 class ExceptionState;
 
-class History : public ScriptWrappable, public RefCounted<History>, public DOMWindowProperty {
+class History FINAL : public ScriptWrappable, public RefCounted<History>, public DOMWindowProperty {
 public:
     static PassRefPtr<History> create(Frame* frame) { return adoptRef(new History(frame)); }
 
@@ -55,7 +55,7 @@
     bool stateChanged() const;
     bool isSameAsCurrentState(SerializedScriptValue*) const;
 
-    void stateObjectAdded(PassRefPtr<SerializedScriptValue>, const String& title, const String& url, SameDocumentNavigationSource, ExceptionState&);
+    void stateObjectAdded(PassRefPtr<SerializedScriptValue>, const String& title, const String& url, UpdateBackForwardListPolicy, ExceptionState&);
 
 private:
     explicit History(Frame*);
diff --git a/Source/core/frame/ImageBitmap.h b/Source/core/frame/ImageBitmap.h
index 8c9229d..7f62bda 100644
--- a/Source/core/frame/ImageBitmap.h
+++ b/Source/core/frame/ImageBitmap.h
@@ -18,7 +18,7 @@
 class HTMLVideoElement;
 class ImageData;
 
-class ImageBitmap : public RefCounted<ImageBitmap>, public ScriptWrappable, public ImageLoaderClient {
+class ImageBitmap FINAL : public RefCounted<ImageBitmap>, public ScriptWrappable, public ImageLoaderClient {
 
 public:
     static PassRefPtr<ImageBitmap> create(HTMLImageElement*, const IntRect&);
@@ -49,8 +49,8 @@
     ImageBitmap(Image*, const IntRect&);
 
     // ImageLoaderClient
-    virtual void notifyImageSourceChanged();
-    virtual bool requestsHighLiveResourceCachePriority() { return true; }
+    virtual void notifyImageSourceChanged() OVERRIDE;
+    virtual bool requestsHighLiveResourceCachePriority() OVERRIDE { return true; }
 
     // ImageBitmaps constructed from HTMLImageElements hold a reference to the HTMLImageElement until
     // the image source changes.
diff --git a/Source/core/frame/ImageBitmapTest.cpp b/Source/core/frame/ImageBitmapTest.cpp
index 6a6626a..6e48156 100644
--- a/Source/core/frame/ImageBitmapTest.cpp
+++ b/Source/core/frame/ImageBitmapTest.cpp
@@ -106,19 +106,19 @@
 TEST_F(ImageBitmapTest, ImageBitmapLiveResourcePriority)
 {
     RefPtr<HTMLImageElement> imageNoCrop = HTMLImageElement::create(*Document::create().get());
-    ResourcePtr<ImageResource> cachedImageNoCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+    ResourcePtr<ImageResource> cachedImageNoCrop = new ImageResource(ResourceRequest("http://foo.com/1"), BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
     imageNoCrop->setImageResource(cachedImageNoCrop.get());
 
     RefPtr<HTMLImageElement> imageInteriorCrop = HTMLImageElement::create(*Document::create().get());
-    ResourcePtr<ImageResource> cachedImageInteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+    ResourcePtr<ImageResource> cachedImageInteriorCrop = new ImageResource(ResourceRequest("http://foo.com/2"), BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
     imageInteriorCrop->setImageResource(cachedImageInteriorCrop.get());
 
     RefPtr<HTMLImageElement> imageExteriorCrop = HTMLImageElement::create(*Document::create().get());
-    ResourcePtr<ImageResource> cachedImageExteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+    ResourcePtr<ImageResource> cachedImageExteriorCrop = new ImageResource(ResourceRequest("http://foo.com/3"), BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
     imageExteriorCrop->setImageResource(cachedImageExteriorCrop.get());
 
     RefPtr<HTMLImageElement> imageOutsideCrop = HTMLImageElement::create(*Document::create().get());
-    ResourcePtr<ImageResource> cachedImageOutsideCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+    ResourcePtr<ImageResource> cachedImageOutsideCrop = new ImageResource(ResourceRequest("http://foo.com/4"), BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
     imageOutsideCrop->setImageResource(cachedImageOutsideCrop.get());
 
     MockImageResourceClient mockClient1, mockClient2, mockClient3, mockClient4;
diff --git a/Source/core/frame/Location.cpp b/Source/core/frame/Location.cpp
index e38b2fd..7f60ae2 100644
--- a/Source/core/frame/Location.cpp
+++ b/Source/core/frame/Location.cpp
@@ -242,8 +242,7 @@
 void Location::setLocation(const String& url, DOMWindow* activeWindow, DOMWindow* firstWindow)
 {
     ASSERT(m_frame);
-    // We call findFrameForNavigation to handle the case of a seamless iframe correctly.
-    Frame* frame = m_frame->loader().findFrameForNavigation(String(), activeWindow->document());
+    Frame* frame = m_frame->loader().findFrameForNavigation(nullAtom, activeWindow->document());
     if (!frame)
         return;
     frame->domWindow()->setLocation(url, activeWindow, firstWindow);
diff --git a/Source/core/frame/Location.h b/Source/core/frame/Location.h
index 50b4b23..4acb1e2 100644
--- a/Source/core/frame/Location.h
+++ b/Source/core/frame/Location.h
@@ -43,7 +43,7 @@
 class Frame;
 class KURL;
 
-class Location : public ScriptWrappable, public RefCounted<Location>, public DOMWindowProperty {
+class Location FINAL : public ScriptWrappable, public RefCounted<Location>, public DOMWindowProperty {
 public:
     static PassRefPtr<Location> create(Frame* frame) { return adoptRef(new Location(frame)); }
 
diff --git a/Source/core/frame/Location.idl b/Source/core/frame/Location.idl
index da81ecf..5ce2990 100644
--- a/Source/core/frame/Location.idl
+++ b/Source/core/frame/Location.idl
@@ -36,8 +36,8 @@
     // problem, since that allows tracking navigation.
     [SetterCallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity=Setter, Unforgeable] attribute DOMString href;
 
-    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void assign([Default=Undefined] optional DOMString url);
-    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void replace([Default=Undefined] optional DOMString url);
+    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void assign(DOMString url);
+    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void replace(DOMString url);
     [CallWith=ActiveWindow, Unforgeable, ReadOnly] void reload();
 
     // URI decomposition attributes
diff --git a/Source/core/frame/Navigator.cpp b/Source/core/frame/Navigator.cpp
index 0d5d778..5debf1d 100644
--- a/Source/core/frame/Navigator.cpp
+++ b/Source/core/frame/Navigator.cpp
@@ -29,8 +29,7 @@
 #include "core/loader/CookieJar.h"
 #include "core/loader/FrameLoader.h"
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/plugins/DOMMimeTypeArray.h"
 #include "core/plugins/DOMPluginArray.h"
 #include "platform/Language.h"
@@ -59,34 +58,7 @@
 {
 }
 
-// If this function returns true, we need to hide the substring "4." that would otherwise
-// appear in the appVersion string. This is to avoid problems with old versions of a
-// library called OpenCube QuickMenu, which as of this writing is still being used on
-// sites such as nwa.com -- the library thinks Safari is Netscape 4 if we don't do this!
-static bool shouldHideFourDot(Frame* frame)
-{
-    const String* sourceURL = frame->script().sourceURL();
-    if (!sourceURL)
-        return false;
-    if (!(sourceURL->endsWith("/dqm_script.js") || sourceURL->endsWith("/dqm_loader.js") || sourceURL->endsWith("/tdqm_loader.js")))
-        return false;
-    Settings* settings = frame->settings();
-    if (!settings)
-        return false;
-    return settings->needsSiteSpecificQuirks();
-}
-
-String Navigator::appVersion() const
-{
-    if (!m_frame)
-        return String();
-    String appVersion = NavigatorID::appVersion(this);
-    if (shouldHideFourDot(m_frame))
-        appVersion.replace("4.", "4_");
-    return appVersion;
-}
-
-String Navigator::language() const
+AtomicString Navigator::language() const
 {
     return defaultLanguage();
 }
@@ -108,12 +80,8 @@
 
 String Navigator::userAgent() const
 {
-    if (!m_frame)
-        return String();
-
-    // If the frame is already detached, FrameLoader::userAgent may malfunction, because it calls a client method
-    // that uses frame's WebView (at least, in Mac WebKit).
-    if (!m_frame->page())
+    // If the frame is already detached it no longer has a meaningful useragent.
+    if (!m_frame || !m_frame->page())
         return String();
 
     return m_frame->loader().userAgent(m_frame->document()->url());
@@ -138,7 +106,8 @@
     if (!m_frame)
         return false;
 
-    if (m_frame->page() && !m_frame->page()->settings().cookieEnabled())
+    Settings* settings = m_frame->settings();
+    if (!settings || !settings->cookieEnabled())
         return false;
 
     return cookiesEnabled(m_frame->document());
@@ -149,7 +118,7 @@
     if (!m_frame || !m_frame->settings())
         return false;
 
-    if (!m_frame->settings()->isJavaEnabled())
+    if (!m_frame->settings()->javaEnabled())
         return false;
 
     return true;
diff --git a/Source/core/frame/Navigator.h b/Source/core/frame/Navigator.h
index 0f289b3..2de28ab 100644
--- a/Source/core/frame/Navigator.h
+++ b/Source/core/frame/Navigator.h
@@ -23,6 +23,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/frame/DOMWindowProperty.h"
 #include "core/frame/NavigatorBase.h"
+#include "heap/Handle.h"
 #include "platform/Supplementable.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
@@ -38,13 +39,12 @@
 
 typedef int ExceptionCode;
 
-class Navigator : public NavigatorBase, public ScriptWrappable, public RefCounted<Navigator>, public DOMWindowProperty, public Supplementable<Navigator> {
+class Navigator FINAL : public NavigatorBase, public ScriptWrappable, public RefCounted<Navigator>, public DOMWindowProperty, public Supplementable<Navigator> {
 public:
     static PassRefPtr<Navigator> create(Frame* frame) { return adoptRef(new Navigator(frame)); }
     virtual ~Navigator();
 
-    String appVersion() const;
-    String language() const;
+    AtomicString language() const;
     DOMPluginArray* plugins() const;
     DOMMimeTypeArray* mimeTypes() const;
     bool cookieEnabled() const;
@@ -62,8 +62,8 @@
 private:
     explicit Navigator(Frame*);
 
-    mutable RefPtr<DOMPluginArray> m_plugins;
-    mutable RefPtr<DOMMimeTypeArray> m_mimeTypes;
+    mutable RefPtrWillBePersistent<DOMPluginArray> m_plugins;
+    mutable RefPtrWillBePersistent<DOMMimeTypeArray> m_mimeTypes;
 };
 
 }
diff --git a/Source/core/page/PageConsole.cpp b/Source/core/frame/PageConsole.cpp
similarity index 87%
rename from Source/core/page/PageConsole.cpp
rename to Source/core/frame/PageConsole.cpp
index 763910a..dde7232 100644
--- a/Source/core/page/PageConsole.cpp
+++ b/Source/core/frame/PageConsole.cpp
@@ -27,18 +27,16 @@
  */
 
 #include "config.h"
-#include "core/page/PageConsole.h"
+#include "core/frame/PageConsole.h"
 
 #include "core/dom/Document.h"
-#include "core/dom/ScriptableDocumentParser.h"
+#include "core/frame/FrameHost.h"
 #include "core/inspector/ConsoleAPITypes.h"
 #include "core/inspector/InspectorConsoleInstrumentation.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/frame/ConsoleBase.h"
 #include "core/page/Page.h"
 #include "wtf/text/StringBuilder.h"
-#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -48,8 +46,8 @@
 
 }
 
-PageConsole::PageConsole(Page* page)
-    : m_page(page)
+PageConsole::PageConsole(FrameHost& frameHost)
+    : m_frameHost(frameHost)
 {
 }
 
@@ -68,7 +66,9 @@
     if (muteCount && source != ConsoleAPIMessageSource)
         return;
 
-    ExecutionContext* context = m_page->mainFrame()->document();
+    // FIXME: This should not need to reach for the main-frame.
+    // Inspector code should just take the current frame and know how to walk itself.
+    ExecutionContext* context = m_frameHost.page().mainFrame()->document();
     if (!context)
         return;
 
@@ -85,10 +85,10 @@
         return;
 
     String stackTrace;
-    if (callStack && m_page->chrome().client().shouldReportDetailedMessageForSource(messageURL))
+    if (callStack && m_frameHost.chrome().client().shouldReportDetailedMessageForSource(messageURL))
         stackTrace = PageConsole::formatStackTraceString(message, callStack);
 
-    m_page->chrome().client().addMessageToConsole(source, level, message, lineNumber, messageURL, stackTrace);
+    m_frameHost.chrome().client().addMessageToConsole(source, level, message, lineNumber, messageURL, stackTrace);
 }
 
 String PageConsole::formatStackTraceString(const String& originalMessage, PassRefPtr<ScriptCallStack> callStack)
diff --git a/Source/core/page/PageConsole.h b/Source/core/frame/PageConsole.h
similarity index 84%
rename from Source/core/page/PageConsole.h
rename to Source/core/frame/PageConsole.h
index b62d192..b76447f 100644
--- a/Source/core/page/PageConsole.h
+++ b/Source/core/frame/PageConsole.h
@@ -30,18 +30,24 @@
 #define PageConsole_h
 
 #include "bindings/v8/ScriptState.h"
-#include "core/inspector/ScriptCallStack.h"
 #include "core/frame/ConsoleTypes.h"
+#include "core/inspector/ScriptCallStack.h"
 #include "wtf/Forward.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
-class Page;
+class FrameHost;
+
+// PageConsole (bad name) takes per-frame/per-document
+// console messages and routes them up through the
+// FrameHost to the ChromeClient and Inspector.
+// It's meant as an abstraction around ChromeClient calls
+// and the way that Blink core/ can add messages to the console.
 
 class PageConsole FINAL {
 public:
-    static PassOwnPtr<PageConsole> create(Page* page) { return adoptPtr(new PageConsole(page)); }
+    static PassOwnPtr<PageConsole> create(FrameHost& host) { return adoptPtr(new PageConsole(host)); }
 
     void addMessage(MessageSource, MessageLevel, const String& message);
     void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber = 0, PassRefPtr<ScriptCallStack> = 0, ScriptState* = 0, unsigned long requestIdentifier = 0);
@@ -52,9 +58,9 @@
     static void unmute();
 
 private:
-    explicit PageConsole(Page*);
+    explicit PageConsole(FrameHost&);
 
-    Page* m_page;
+    FrameHost& m_frameHost;
 };
 
 } // namespace WebCore
diff --git a/Source/core/frame/Screen.cpp b/Source/core/frame/Screen.cpp
index 678d750..67283ac 100644
--- a/Source/core/frame/Screen.cpp
+++ b/Source/core/frame/Screen.cpp
@@ -30,11 +30,11 @@
 #include "config.h"
 #include "core/frame/Screen.h"
 
-#include "core/inspector/InspectorInstrumentation.h"
 #include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "platform/PlatformScreen.h"
 #include "platform/geometry/FloatRect.h"
 
@@ -50,9 +50,9 @@
 {
     if (!m_frame)
         return 0;
-    Page* page = m_frame->page();
-    if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(screenRect(m_frame->view()).height() * page->deviceScaleFactor());
+    FrameHost* host = m_frame->host();
+    if (host && host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(screenRect(m_frame->view()).height() * host->deviceScaleFactor());
     return static_cast<unsigned>(screenRect(m_frame->view()).height());
 }
 
@@ -60,9 +60,9 @@
 {
     if (!m_frame)
         return 0;
-    Page* page = m_frame->page();
-    if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(screenRect(m_frame->view()).width() * page->deviceScaleFactor());
+    FrameHost* host = m_frame->host();
+    if (host && host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(screenRect(m_frame->view()).width() * host->deviceScaleFactor());
     return static_cast<unsigned>(screenRect(m_frame->view()).width());
 }
 
@@ -84,9 +84,9 @@
 {
     if (!m_frame)
         return 0;
-    Page* page = m_frame->page();
-    if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(screenAvailableRect(m_frame->view()).x() * page->deviceScaleFactor());
+    FrameHost* host = m_frame->host();
+    if (host && host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(screenAvailableRect(m_frame->view()).x() * host->deviceScaleFactor());
     return static_cast<int>(screenAvailableRect(m_frame->view()).x());
 }
 
@@ -94,9 +94,9 @@
 {
     if (!m_frame)
         return 0;
-    Page* page = m_frame->page();
-    if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(screenAvailableRect(m_frame->view()).y() * page->deviceScaleFactor());
+    FrameHost* host = m_frame->host();
+    if (host && host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(screenAvailableRect(m_frame->view()).y() * host->deviceScaleFactor());
     return static_cast<int>(screenAvailableRect(m_frame->view()).y());
 }
 
@@ -104,9 +104,9 @@
 {
     if (!m_frame)
         return 0;
-    Page* page = m_frame->page();
-    if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(screenAvailableRect(m_frame->view()).height() * page->deviceScaleFactor());
+    FrameHost* host = m_frame->host();
+    if (host && host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(screenAvailableRect(m_frame->view()).height() * host->deviceScaleFactor());
     return static_cast<unsigned>(screenAvailableRect(m_frame->view()).height());
 }
 
@@ -114,10 +114,22 @@
 {
     if (!m_frame)
         return 0;
-    Page* page = m_frame->page();
-    if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
-        return lroundf(screenAvailableRect(m_frame->view()).width() * page->deviceScaleFactor());
+    FrameHost* host = m_frame->host();
+    if (host && host->settings().reportScreenSizeInPhysicalPixelsQuirk())
+        return lroundf(screenAvailableRect(m_frame->view()).width() * host->deviceScaleFactor());
     return static_cast<unsigned>(screenAvailableRect(m_frame->view()).width());
 }
 
+const AtomicString& Screen::interfaceName() const
+{
+    return EventTargetNames::Screen;
+}
+
+ExecutionContext* Screen::executionContext() const
+{
+    if (!m_frame)
+        return 0;
+    return m_frame->document();
+}
+
 } // namespace WebCore
diff --git a/Source/core/frame/Screen.h b/Source/core/frame/Screen.h
index 7b2036b..df9e6e5 100644
--- a/Source/core/frame/Screen.h
+++ b/Source/core/frame/Screen.h
@@ -31,7 +31,9 @@
 #define Screen_h
 
 #include "bindings/v8/ScriptWrappable.h"
+#include "core/events/EventTarget.h"
 #include "core/frame/DOMWindowProperty.h"
+#include "platform/Supplementable.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 
@@ -39,9 +41,10 @@
 
     class Frame;
 
-    class Screen : public ScriptWrappable, public RefCounted<Screen>, public DOMWindowProperty {
+    class Screen FINAL : public ScriptWrappable, public RefCounted<Screen>, public EventTargetWithInlineData, public DOMWindowProperty, public Supplementable<Screen> {
+        REFCOUNTED_EVENT_TARGET(Screen);
     public:
-        static PassRefPtr<Screen> create(Frame *frame) { return adoptRef(new Screen(frame)); }
+        static PassRefPtr<Screen> create(Frame* frame) { return adoptRef(new Screen(frame)); }
 
         unsigned height() const;
         unsigned width() const;
@@ -52,6 +55,10 @@
         unsigned availHeight() const;
         unsigned availWidth() const;
 
+        // EventTarget.
+        virtual const AtomicString& interfaceName() const OVERRIDE;
+        virtual ExecutionContext* executionContext() const OVERRIDE;
+
     private:
         explicit Screen(Frame*);
     };
diff --git a/Source/core/frame/Screen.idl b/Source/core/frame/Screen.idl
index 184a863..8eeca83 100644
--- a/Source/core/frame/Screen.idl
+++ b/Source/core/frame/Screen.idl
@@ -27,7 +27,7 @@
  */
 
 
-interface Screen {
+interface Screen : EventTarget {
     readonly attribute unsigned long height;
     readonly attribute unsigned long width;
     readonly attribute unsigned long colorDepth;
diff --git a/Source/core/frame/SecurityPolicy.idl b/Source/core/frame/SecurityPolicy.idl
deleted file mode 100644
index f5651da..0000000
--- a/Source/core/frame/SecurityPolicy.idl
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-[
-    ImplementedAs=DOMSecurityPolicy
-] interface SecurityPolicy {
-    readonly attribute boolean allowsEval;
-    readonly attribute boolean allowsInlineScript;
-    readonly attribute boolean allowsInlineStyle;
-    readonly attribute boolean isActive;
-
-    readonly attribute DOMStringList reportURIs;
-
-    boolean allowsConnectionTo(DOMString url);
-    boolean allowsFontFrom(DOMString url);
-    boolean allowsFormAction(DOMString url);
-    boolean allowsFrameFrom(DOMString url);
-    boolean allowsImageFrom(DOMString url);
-    boolean allowsMediaFrom(DOMString url);
-    boolean allowsObjectFrom(DOMString url);
-    boolean allowsPluginType(DOMString type);
-    boolean allowsScriptFrom(DOMString url);
-    boolean allowsStyleFrom(DOMString url);
-};
diff --git a/Source/core/frame/Settings.cpp b/Source/core/frame/Settings.cpp
new file mode 100644
index 0000000..dc2bcaa
--- /dev/null
+++ b/Source/core/frame/Settings.cpp
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
+ */
+
+#include "config.h"
+#include "core/frame/Settings.h"
+
+#include "platform/scroll/ScrollbarTheme.h"
+
+namespace WebCore {
+
+// NOTEs
+//  1) EditingMacBehavior comprises builds on Mac;
+//  2) EditingWindowsBehavior comprises builds on Windows;
+//  3) EditingUnixBehavior comprises all unix-based systems, but Darwin/MacOS/Android (and then abusing the terminology);
+//  4) EditingAndroidBehavior comprises Android builds.
+// 99) MacEditingBehavior is used a fallback.
+static EditingBehaviorType editingBehaviorTypeForPlatform()
+{
+    return
+#if OS(MACOSX)
+    EditingMacBehavior
+#elif OS(WIN)
+    EditingWindowsBehavior
+#elif OS(ANDROID)
+    EditingAndroidBehavior
+#else // Rest of the UNIX-like systems
+    EditingUnixBehavior
+#endif
+    ;
+}
+
+static const bool defaultUnifiedTextCheckerEnabled = false;
+#if OS(MACOSX)
+static const bool defaultSmartInsertDeleteEnabled = true;
+#else
+static const bool defaultSmartInsertDeleteEnabled = false;
+#endif
+#if OS(WIN)
+static const bool defaultSelectTrailingWhitespaceEnabled = true;
+#else
+static const bool defaultSelectTrailingWhitespaceEnabled = false;
+#endif
+
+Settings::Settings()
+    : m_openGLMultisamplingEnabled(false)
+#if HACK_FORCE_TEXT_AUTOSIZING_ON_DESKTOP
+    , m_textAutosizingWindowSizeOverride(320, 480)
+    , m_textAutosizingEnabled(true)
+#else
+    , m_textAutosizingEnabled(false)
+#endif
+    SETTINGS_INITIALIZER_LIST
+{
+}
+
+PassOwnPtr<Settings> Settings::create()
+{
+    return adoptPtr(new Settings);
+}
+
+SETTINGS_SETTER_BODIES
+
+void Settings::setDelegate(SettingsDelegate* delegate)
+{
+    m_delegate = delegate;
+}
+
+void Settings::invalidate(SettingsDelegate::ChangeType changeType)
+{
+    if (m_delegate)
+        m_delegate->settingsChanged(changeType);
+}
+
+void Settings::setTextAutosizingEnabled(bool textAutosizingEnabled)
+{
+    if (m_textAutosizingEnabled == textAutosizingEnabled)
+        return;
+
+    m_textAutosizingEnabled = textAutosizingEnabled;
+    invalidate(SettingsDelegate::TextAutosizingChange);
+}
+
+// FIXME: Move to Settings.in once make_settings can understand IntSize.
+void Settings::setTextAutosizingWindowSizeOverride(const IntSize& textAutosizingWindowSizeOverride)
+{
+    if (m_textAutosizingWindowSizeOverride == textAutosizingWindowSizeOverride)
+        return;
+
+    m_textAutosizingWindowSizeOverride = textAutosizingWindowSizeOverride;
+    invalidate(SettingsDelegate::TextAutosizingChange);
+}
+
+void Settings::setMockScrollbarsEnabled(bool flag)
+{
+    ScrollbarTheme::setMockScrollbarsEnabled(flag);
+}
+
+bool Settings::mockScrollbarsEnabled()
+{
+    return ScrollbarTheme::mockScrollbarsEnabled();
+}
+
+void Settings::setOpenGLMultisamplingEnabled(bool flag)
+{
+    if (m_openGLMultisamplingEnabled == flag)
+        return;
+
+    m_openGLMultisamplingEnabled = flag;
+    invalidate(SettingsDelegate::MultisamplingChange);
+}
+
+} // namespace WebCore
diff --git a/Source/core/frame/Settings.h b/Source/core/frame/Settings.h
new file mode 100644
index 0000000..b6b7737
--- /dev/null
+++ b/Source/core/frame/Settings.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2003, 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
+ *           (C) 2006 Graham Dennis (graham.dennis@gmail.com)
+ *
+ * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
+ */
+
+#ifndef Settings_h
+#define Settings_h
+
+#include "SettingsMacros.h"
+#include "core/editing/EditingBehaviorTypes.h"
+#include "core/frame/SettingsDelegate.h"
+#include "platform/Timer.h"
+#include "platform/fonts/GenericFontFamilySettings.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/HashSet.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+enum EditableLinkBehavior {
+    EditableLinkDefaultBehavior,
+    EditableLinkAlwaysLive,
+    EditableLinkOnlyLiveWithShiftKey,
+    EditableLinkLiveWhenNotFocused,
+    EditableLinkNeverLive
+};
+
+class Settings {
+    WTF_MAKE_NONCOPYABLE(Settings); WTF_MAKE_FAST_ALLOCATED;
+public:
+    static PassOwnPtr<Settings> create();
+
+    GenericFontFamilySettings& genericFontFamilySettings() { return m_genericFontFamilySettings; }
+    void notifyGenericFontFamilyChange() { invalidate(SettingsDelegate::FontFamilyChange); }
+
+    void setTextAutosizingEnabled(bool);
+    bool textAutosizingEnabled() const { return m_textAutosizingEnabled; }
+
+    // Only set by Layout Tests, and only used if textAutosizingEnabled() returns true.
+    void setTextAutosizingWindowSizeOverride(const IntSize&);
+    const IntSize& textAutosizingWindowSizeOverride() const { return m_textAutosizingWindowSizeOverride; }
+
+    SETTINGS_GETTERS_AND_SETTERS
+
+    // FIXME: This does not belong here.
+    static void setMockScrollbarsEnabled(bool flag);
+    static bool mockScrollbarsEnabled();
+
+    // FIXME: naming_utilities.py isn't smart enough to handle OpenGL yet.
+    // It could handle "GL", but that seems a bit overly broad.
+    void setOpenGLMultisamplingEnabled(bool flag);
+    bool openGLMultisamplingEnabled() { return m_openGLMultisamplingEnabled; }
+
+    void setDelegate(SettingsDelegate*);
+
+private:
+    Settings();
+
+    void invalidate(SettingsDelegate::ChangeType);
+
+    SettingsDelegate* m_delegate;
+
+    GenericFontFamilySettings m_genericFontFamilySettings;
+    bool m_openGLMultisamplingEnabled : 1;
+    IntSize m_textAutosizingWindowSizeOverride;
+    bool m_textAutosizingEnabled : 1;
+
+    SETTINGS_MEMBER_VARIABLES
+};
+
+} // namespace WebCore
+
+#endif // Settings_h
diff --git a/Source/core/page/Settings.in b/Source/core/frame/Settings.in
similarity index 81%
rename from Source/core/page/Settings.in
rename to Source/core/frame/Settings.in
index 4d21a27..5dbb12a 100644
--- a/Source/core/page/Settings.in
+++ b/Source/core/frame/Settings.in
@@ -55,10 +55,10 @@
 # FIXME: This should get the value from the @viewport UA sheet instead.
 layoutFallbackWidth type=int, initial=980
 
-minimumFontSize type=int, initial=0, setNeedsStyleRecalcInAllFrames=1
-minimumLogicalFontSize type=int, initial=0, setNeedsStyleRecalcInAllFrames=1
-defaultFontSize type=int, initial=0, setNeedsStyleRecalcInAllFrames=1
-defaultFixedFontSize type=int, initial=0, setNeedsStyleRecalcInAllFrames=1
+minimumFontSize type=int, initial=0, invalidate=Style
+minimumLogicalFontSize type=int, initial=0, invalidate=Style
+defaultFontSize type=int, initial=0, invalidate=Style
+defaultFixedFontSize type=int, initial=0, invalidate=Style
 
 editingBehaviorType type=EditingBehaviorType, initial=editingBehaviorTypeForPlatform()
 
@@ -70,12 +70,13 @@
 supportsMultipleWindows initial=true
 javaScriptCanAccessClipboard initial=false
 shouldPrintBackgrounds initial=false
+shouldClearDocumentBackground initial=true
 
-textAreasAreResizable initial=false, setNeedsStyleRecalcInAllFrames=1
-acceleratedCompositingEnabled initial=true, setNeedsStyleRecalcInAllFrames=1
+textAreasAreResizable initial=false, invalidate=Style
+acceleratedCompositingEnabled initial=true, invalidate=Style
 
 # Debugging feature used for accelerated compositing layers.
-showRepaintCounter initial=false, setNeedsStyleRecalcInAllFrames=1
+showRepaintCounter initial=false, invalidate=Style
 
 shrinksStandaloneImagesToFit initial=true
 
@@ -87,6 +88,7 @@
 usesEncodingDetector initial=false
 allowScriptsToCloseWindows initial=false
 acceleratedFiltersEnabled initial=false
+deferredFiltersEnabled initial=false
 regionBasedColumnsEnabled initial=false
 
 # FIXME: This should really be disabled by default as it makes platforms that
@@ -180,8 +182,6 @@
 threadedHTMLParser initial=false
 useThreadedHTMLParserForDataURLs initial=false
 
-applyPageScaleFactorInCompositor initial=false
-
 allowCustomScrollbarInMainFrame initial=true
 webSecurityEnabled initial=true
 
@@ -249,3 +249,50 @@
 # Enable decoration shadow nodes to test password genration feature
 # crbug.com/114092. This flag should not be enabled for production.
 passwordGenerationDecorationEnabled initial=false
+
+
+# Presumably used by LayoutTests?  Unclear.
+useWideViewport initial=true, invalidate=ViewportDescription
+loadWithOverviewMode initial=true, invalidate=ViewportDescription
+
+
+# Font scale factor for accessibility, applied as part of text autosizing.
+accessibilityFontScaleFactor type=double, initial=1.0, invalidate=TextAutosizing
+
+
+# Only set by Layout Tests.
+mediaTypeOverride type=String, initial="screen", invalidate=MediaType
+
+# loadsImagesAutomatically only suppresses the network load of
+# the image URL. A cached image will still be rendered if requested.
+loadsImagesAutomatically initial=false, invalidate=ImageLoading
+imagesEnabled initial=true, invalidate=ImageLoading
+
+javaEnabled initial=false
+pluginsEnabled initial=false
+
+viewportEnabled initial=false, invalidate=ViewportDescription
+viewportMetaEnabled initial=false
+
+dnsPrefetchingEnabled initial=false, invalidate=DNSPrefetching
+
+touchEventEmulationEnabled initial=false
+
+
+# FIXME: This is a temporary flag and should be removed once
+# accelerated overflow scroll is ready (crbug.com/254111).
+compositorDrivenAcceleratedScrollingEnabled initial=false
+
+# FIXME: This is a temporary flag and should be removed
+# when squashing is ready. (crbug.com/261605)
+layerSquashingEnabled initial=false
+
+# Clients that execute script should call ScriptController::canExecuteScripts()
+# instead of this function. ScriptController::canExecuteScripts() checks the
+# HTML sandbox, plug-in sandboxing, and other important details.
+scriptEnabled initial=false, invalidate=ScriptEnable
+
+# Compensates for poor text legibility on mobile devices. This value is
+# multiplied by the font scale factor when performing text autosizing of
+# websites that do not set an explicit viewport description.
+deviceScaleAdjustment type=double, initial=1.0, invalidate=TextAutosizing
diff --git a/Source/core/rendering/LayoutIndicator.cpp b/Source/core/frame/SettingsDelegate.cpp
similarity index 81%
copy from Source/core/rendering/LayoutIndicator.cpp
copy to Source/core/frame/SettingsDelegate.cpp
index a57c53c..47c5ce5 100644
--- a/Source/core/rendering/LayoutIndicator.cpp
+++ b/Source/core/frame/SettingsDelegate.cpp
@@ -29,14 +29,23 @@
  */
 
 #include "config.h"
-#include "core/rendering/LayoutIndicator.h"
+#include "core/frame/SettingsDelegate.h"
+
+#include "core/frame/Settings.h"
 
 namespace WebCore {
 
-#ifndef NDEBUG
-
-size_t LayoutIndicator::s_inLayout = 0;
-
-#endif
-
+SettingsDelegate::SettingsDelegate(PassOwnPtr<Settings> settings)
+    : m_settings(settings)
+{
+    if (m_settings)
+        m_settings->setDelegate(this);
 }
+
+SettingsDelegate::~SettingsDelegate()
+{
+    if (m_settings)
+        m_settings->setDelegate(0);
+}
+
+} // namespace WebCore
diff --git a/Source/core/html/ime/Composition.h b/Source/core/frame/SettingsDelegate.h
similarity index 66%
rename from Source/core/html/ime/Composition.h
rename to Source/core/frame/SettingsDelegate.h
index 4305466..6d2778c 100644
--- a/Source/core/html/ime/Composition.h
+++ b/Source/core/frame/SettingsDelegate.h
@@ -28,36 +28,44 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef Composition_h
-#define Composition_h
+#ifndef SettingsDelegate_h
+#define SettingsDelegate_h
 
-#include "bindings/v8/ScriptWrappable.h"
+#include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-class InputMethodContext;
+class Page;
+class Settings;
 
-class Composition : public ScriptWrappable {
+class SettingsDelegate {
 public:
-    static PassOwnPtr<Composition> create(InputMethodContext*);
-    ~Composition();
+    explicit SettingsDelegate(PassOwnPtr<Settings>);
+    virtual ~SettingsDelegate();
 
-    void ref();
-    void deref();
+    Settings* settings() const { return m_settings.get(); }
 
-    String text() const;
-    int selectionStart() const;
-    int selectionEnd() const;
-    const Vector<unsigned>& getSegments() const;
+    // We currently use an enum instead of individual invalidation
+    // functions to make generating Settings.in slightly easier.
+    enum ChangeType {
+        StyleChange,
+        ViewportDescriptionChange,
+        MediaTypeChange,
+        DNSPrefetchingChange,
+        MultisamplingChange,
+        ImageLoadingChange,
+        TextAutosizingChange,
+        ScriptEnableChange,
+        FontFamilyChange,
+    };
 
-private:
-    explicit Composition(InputMethodContext*);
+    virtual void settingsChanged(ChangeType) = 0;
 
-    InputMethodContext* m_inputMethodContext;
+protected:
+    OwnPtr<Settings> const m_settings;
 };
 
 } // namespace WebCore
 
-#endif // Composition_h
+#endif // SettingsDelegate_h
diff --git a/Source/core/frame/SmartClip.cpp b/Source/core/frame/SmartClip.cpp
new file mode 100644
index 0000000..52f9b03
--- /dev/null
+++ b/Source/core/frame/SmartClip.cpp
@@ -0,0 +1,294 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/frame/SmartClip.h"
+
+#include "core/dom/ContainerNode.h"
+#include "core/dom/Document.h"
+#include "core/dom/NodeTraversal.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/FrameView.h"
+#include "core/html/HTMLFrameOwnerElement.h"
+#include "core/page/Page.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+static IntRect applyScaleWithoutCollapsingToZero(const IntRect& rect, float scale)
+{
+    IntRect result = rect;
+    result.scale(scale);
+    if (rect.width() > 0 && !result.width())
+        result.setWidth(1);
+    if (rect.height() > 0 && !result.height())
+        result.setHeight(1);
+    return result;
+}
+
+static Node* nodeInsideFrame(Node* node)
+{
+    if (node->isFrameOwnerElement())
+        return toHTMLFrameOwnerElement(node)->contentDocument();
+    return 0;
+}
+
+// FIXME: SmartClipData is eventually returned via
+// SLookSmartClip.DataExtractionListener:
+// http://img-developer.samsung.com/onlinedocs/sms/com/samsung/android/sdk/look/...
+// however the original author of this change chose to use a string-serialization
+// format (presumably to make IPC easy?).
+// If we're going to use this as a Pickle format, we should at least have the
+// read/write code in one place!
+String SmartClipData::toString()
+{
+    if (!m_node)
+        return emptyString();
+
+    const UChar fieldSeparator = 0xFFFE;
+    const UChar rowSeparator = 0xFFFF;
+
+    StringBuilder result;
+    result.append(String::number(m_rect.x()));
+    result.append(fieldSeparator);
+    result.append(String::number(m_rect.y()));
+    result.append(fieldSeparator);
+    result.append(String::number(m_rect.width()));
+    result.append(fieldSeparator);
+    result.append(String::number(m_rect.height()));
+    result.append(fieldSeparator);
+    result.append(m_string);
+    result.append(rowSeparator);
+    return result.toString();
+}
+
+SmartClip::SmartClip(PassRefPtr<Frame> frame)
+    : m_frame(frame)
+{
+}
+
+SmartClipData SmartClip::dataForRect(const IntRect& cropRect)
+{
+    IntRect resizedCropRect = applyScaleWithoutCollapsingToZero(cropRect, 1 / pageScaleFactor());
+
+    Node* bestNode = findBestOverlappingNode(m_frame->document(), resizedCropRect);
+    if (!bestNode)
+        return SmartClipData();
+
+    if (Node* nodeFromFrame = nodeInsideFrame(bestNode)) {
+        // FIXME: This code only hit-tests a single iframe. It seems like we ought support nested frames.
+        if (Node* bestNodeInFrame = findBestOverlappingNode(nodeFromFrame, resizedCropRect))
+            bestNode = bestNodeInFrame;
+    }
+
+    Vector<Node*> hitNodes;
+    collectOverlappingChildNodes(bestNode, resizedCropRect, hitNodes);
+
+    if (hitNodes.isEmpty() || hitNodes.size() == bestNode->childNodeCount()) {
+        hitNodes.clear();
+        hitNodes.append(bestNode);
+    }
+
+    // Unite won't work with the empty rect, so we initialize to the first rect.
+    IntRect unitedRects = hitNodes[0]->pixelSnappedBoundingBox();
+    StringBuilder collectedText;
+    for (size_t i = 0; i < hitNodes.size(); ++i) {
+        collectedText.append(extractTextFromNode(hitNodes[i]));
+        unitedRects.unite(hitNodes[i]->pixelSnappedBoundingBox());
+    }
+
+    return SmartClipData(bestNode, convertRectToWindow(unitedRects), collectedText.toString());
+}
+
+float SmartClip::pageScaleFactor()
+{
+    return m_frame->page()->pageScaleFactor();
+}
+
+// This function is a bit of a mystery. If you understand what it does, please
+// consider adding a more descriptive name.
+Node* SmartClip::minNodeContainsNodes(Node* minNode, Node* newNode)
+{
+    if (!newNode)
+        return minNode;
+    if (!minNode)
+        return newNode;
+
+    IntRect minNodeRect = minNode->pixelSnappedBoundingBox();
+    IntRect newNodeRect = newNode->pixelSnappedBoundingBox();
+
+    Node* parentMinNode = minNode->parentNode();
+    Node* parentNewNode = newNode->parentNode();
+
+    if (minNodeRect.contains(newNodeRect)) {
+        if (parentMinNode && parentNewNode && parentNewNode->parentNode() == parentMinNode)
+            return parentMinNode;
+        return minNode;
+    }
+
+    if (newNodeRect.contains(minNodeRect)) {
+        if (parentMinNode && parentNewNode && parentMinNode->parentNode() == parentNewNode)
+            return parentNewNode;
+        return newNode;
+    }
+
+    // This loop appears to find the nearest ancestor of minNode (in DOM order)
+    // that contains the newNodeRect. It's very unclear to me why that's an
+    // interesting node to find. Presumably this loop will often just return
+    // the documentElement.
+    Node* node = minNode;
+    while (node) {
+        if (node->renderer()) {
+            IntRect nodeRect = node->pixelSnappedBoundingBox();
+            if (nodeRect.contains(newNodeRect)) {
+                return node;
+            }
+        }
+        node = node->parentNode();
+    }
+
+    return 0;
+}
+
+Node* SmartClip::findBestOverlappingNode(Node* rootNode, const IntRect& cropRect)
+{
+    if (!rootNode)
+        return 0;
+
+    IntRect resizedCropRect = rootNode->document().view()->windowToContents(cropRect);
+
+    Node* node = rootNode;
+    Node* minNode = 0;
+
+    while (node) {
+        IntRect nodeRect = node->pixelSnappedBoundingBox();
+
+        if (node->isElementNode() && equalIgnoringCase(toElement(node)->fastGetAttribute(HTMLNames::aria_hiddenAttr), "true")) {
+            node = NodeTraversal::nextSkippingChildren(*node, rootNode);
+            continue;
+        }
+
+        RenderObject* renderer = node->renderer();
+        if (renderer && !nodeRect.isEmpty()) {
+            if (renderer->isText()
+                || renderer->isRenderImage()
+                || node->isFrameOwnerElement()
+                || (renderer->style()->hasBackgroundImage() && !shouldSkipBackgroundImage(node))) {
+                if (resizedCropRect.intersects(nodeRect)) {
+                    minNode = minNodeContainsNodes(minNode, node);
+                } else {
+                    node = NodeTraversal::nextSkippingChildren(*node, rootNode);
+                    continue;
+                }
+            }
+        }
+        node = NodeTraversal::next(*node, rootNode);
+    }
+
+    return minNode;
+}
+
+// This function appears to heuristically guess whether to include a background
+// image in the smart clip. It seems to want to include sprites created from
+// CSS background images but to skip actual backgrounds.
+bool SmartClip::shouldSkipBackgroundImage(Node* node)
+{
+    // Apparently we're only interested in background images on spans and divs.
+    if (!node->hasTagName(HTMLNames::spanTag) && !node->hasTagName(HTMLNames::divTag))
+        return true;
+
+    // This check actually makes a bit of sense. If you're going to sprite an
+    // image out of a CSS background, you're probably going to specify a height
+    // or a width. On the other hand, if we've got a legit background image,
+    // it's very likely the height or the width will be set to auto.
+    RenderObject* renderer = node->renderer();
+    if (renderer && (renderer->style()->logicalHeight().isAuto() || renderer->style()->logicalWidth().isAuto()))
+        return true;
+
+    return false;
+}
+
+void SmartClip::collectOverlappingChildNodes(Node* parentNode, const IntRect& cropRect, Vector<Node*>& hitNodes)
+{
+    if (!parentNode)
+        return;
+    IntRect resizedCropRect = parentNode->document().view()->windowToContents(cropRect);
+    for (Node* child = parentNode->firstChild(); child; child = child->nextSibling()) {
+        IntRect childRect = child->pixelSnappedBoundingBox();
+        if (resizedCropRect.intersects(childRect))
+            hitNodes.append(child);
+    }
+}
+
+IntRect SmartClip::convertRectToWindow(const IntRect& nodeRect)
+{
+    IntRect result = m_frame->document()->view()->contentsToWindow(nodeRect);
+    result.scale(pageScaleFactor());
+    return result;
+}
+
+String SmartClip::extractTextFromNode(Node* node)
+{
+    // Science has proven that no text nodes are ever positioned at y == -99999.
+    int prevYPos = -99999;
+
+    StringBuilder result;
+    for (Node* currentNode = node; currentNode; currentNode = NodeTraversal::next(*currentNode, node)) {
+        RenderStyle* style = currentNode->computedStyle();
+        if (style && style->userSelect() == SELECT_NONE)
+            continue;
+
+        if (Node* nodeFromFrame = nodeInsideFrame(currentNode))
+            result.append(extractTextFromNode(nodeFromFrame));
+
+        IntRect nodeRect = currentNode->pixelSnappedBoundingBox();
+        if (currentNode->renderer() && !nodeRect.isEmpty()) {
+            if (currentNode->isTextNode()) {
+                String nodeValue = currentNode->nodeValue();
+
+                // It's unclear why we blacklist solitary "\n" node values.
+                // Maybe we're trying to ignore <br> tags somehow?
+                if (nodeValue == "\n")
+                    nodeValue = "";
+
+                if (nodeRect.y() != prevYPos) {
+                    prevYPos = nodeRect.y();
+                    result.append('\n');
+                }
+
+                result.append(nodeValue);
+            }
+        }
+    }
+
+    return result.toString();
+}
+
+} // namespace WebCore
diff --git a/Source/core/frame/SmartClip.h b/Source/core/frame/SmartClip.h
new file mode 100644
index 0000000..7481b2a
--- /dev/null
+++ b/Source/core/frame/SmartClip.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SmartClip_h
+#define SmartClip_h
+
+#include "core/dom/Node.h"
+#include "core/frame/Frame.h"
+
+namespace WebCore {
+
+class SmartClipData {
+public:
+    SmartClipData()
+    {
+    }
+
+    SmartClipData(Node* node, IntRect rect, String string)
+        : m_node(node)
+        , m_rect(rect)
+        , m_string(string)
+    {
+    }
+
+    String toString();
+
+private:
+    RefPtr<Node> m_node;
+    IntRect m_rect;
+    String m_string;
+};
+
+// SmartClip implements support for the copy operation
+// with an S-Pen on Samsung devices. The behavior of this
+// class is quirky and poorly tested. It's approximately
+// trying to do a poor-mans implementation of columnar
+// selection followed by a copy operation.
+class SmartClip {
+public:
+    explicit SmartClip(PassRefPtr<Frame>);
+
+    SmartClipData dataForRect(const IntRect&);
+
+private:
+    float pageScaleFactor();
+
+    Node* minNodeContainsNodes(Node* minNode, Node* newNode);
+    Node* findBestOverlappingNode(Node*, const IntRect& cropRect);
+    bool shouldSkipBackgroundImage(Node*);
+    void collectOverlappingChildNodes(Node* parentNode, const IntRect& cropRect, Vector<Node*>& overlappingNodeInfoTable);
+    IntRect convertRectToWindow(const IntRect& nodeRect);
+    String extractTextFromNode(Node*);
+
+    RefPtr<Frame> m_frame;
+};
+
+} // namespace WebCore
+
+#endif // SmartClip_h
diff --git a/Source/core/frame/SuspendableTimer.h b/Source/core/frame/SuspendableTimer.h
index 3981ab7..c07f0d7 100644
--- a/Source/core/frame/SuspendableTimer.h
+++ b/Source/core/frame/SuspendableTimer.h
@@ -38,10 +38,10 @@
     virtual ~SuspendableTimer();
 
     // ActiveDOMObject
-    virtual bool hasPendingActivity() const;
-    virtual void stop();
-    virtual void suspend();
-    virtual void resume();
+    virtual bool hasPendingActivity() const OVERRIDE FINAL;
+    virtual void stop() OVERRIDE;
+    virtual void suspend() OVERRIDE FINAL;
+    virtual void resume() OVERRIDE FINAL;
 
 private:
     virtual void fired() = 0;
diff --git a/Source/core/frame/UseCounter.cpp b/Source/core/frame/UseCounter.cpp
index 520e121..1051e36 100644
--- a/Source/core/frame/UseCounter.cpp
+++ b/Source/core/frame/UseCounter.cpp
@@ -32,8 +32,8 @@
 #include "core/dom/Document.h"
 #include "core/dom/ExecutionContext.h"
 #include "core/frame/DOMWindow.h"
-#include "core/page/Page.h"
-#include "core/page/PageConsole.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/PageConsole.h"
 #include "public/platform/Platform.h"
 
 namespace WebCore {
@@ -64,7 +64,7 @@
     case CSSPropertyWebkitFontFeatureSettings: return 12;
     case CSSPropertyFontKerning: return 13;
     case CSSPropertyWebkitFontSmoothing: return 14;
-    case CSSPropertyWebkitFontVariantLigatures: return 15;
+    case CSSPropertyFontVariantLigatures: return 15;
     case CSSPropertyWebkitLocale: return 16;
     case CSSPropertyWebkitTextOrientation: return 17;
     case CSSPropertyWebkitWritingMode: return 18;
@@ -294,8 +294,8 @@
     case CSSPropertyFlexWrap: return 239;
     case CSSPropertyJustifyContent: return 240;
     case CSSPropertyWebkitFontSizeDelta: return 241;
-    case CSSPropertyGridDefinitionColumns: return 242;
-    case CSSPropertyGridDefinitionRows: return 243;
+    case CSSPropertyGridTemplateColumns: return 242;
+    case CSSPropertyGridTemplateRows: return 243;
     case CSSPropertyGridColumnStart: return 244;
     case CSSPropertyGridColumnEnd: return 245;
     case CSSPropertyGridRowStart: return 246;
@@ -306,11 +306,11 @@
     case CSSPropertyWebkitHighlight: return 251;
     case CSSPropertyWebkitHyphenateCharacter: return 252;
     case CSSPropertyWebkitLineBoxContain: return 257;
-    case CSSPropertyWebkitLineAlign: return 258;
+    // case CSSPropertyWebkitLineAlign: return 258;
     case CSSPropertyWebkitLineBreak: return 259;
     case CSSPropertyWebkitLineClamp: return 260;
-    case CSSPropertyWebkitLineGrid: return 261;
-    case CSSPropertyWebkitLineSnap: return 262;
+    // case CSSPropertyWebkitLineGrid: return 261;
+    // case CSSPropertyWebkitLineSnap: return 262;
     case CSSPropertyWebkitLogicalWidth: return 263;
     case CSSPropertyWebkitLogicalHeight: return 264;
     case CSSPropertyWebkitMarginAfterCollapse: return 265;
@@ -384,12 +384,12 @@
     case CSSPropertyWebkitUserDrag: return 337;
     case CSSPropertyWebkitUserModify: return 338;
     case CSSPropertyWebkitUserSelect: return 339;
-    case CSSPropertyWebkitFlowInto: return 340;
-    case CSSPropertyWebkitFlowFrom: return 341;
-    case CSSPropertyWebkitRegionFragment: return 342;
-    case CSSPropertyWebkitRegionBreakAfter: return 343;
-    case CSSPropertyWebkitRegionBreakBefore: return 344;
-    case CSSPropertyWebkitRegionBreakInside: return 345;
+    // case CSSPropertyWebkitFlowInto: return 340;
+    // case CSSPropertyWebkitFlowFrom: return 341;
+    // case CSSPropertyWebkitRegionFragment: return 342;
+    // case CSSPropertyWebkitRegionBreakAfter: return 343;
+    // case CSSPropertyWebkitRegionBreakBefore: return 344;
+    // case CSSPropertyWebkitRegionBreakInside: return 345;
     case CSSPropertyShapeInside: return 346;
     case CSSPropertyShapeOutside: return 347;
     case CSSPropertyShapeMargin: return 348;
@@ -475,7 +475,7 @@
     case CSSPropertyMixBlendMode: return 420;
     case CSSPropertyTouchAction: return 421;
     case CSSPropertyGridArea: return 422;
-    case CSSPropertyGridTemplate: return 423;
+    case CSSPropertyGridTemplateAreas: return 423;
     case CSSPropertyAnimation: return 424;
     case CSSPropertyAnimationDelay: return 425;
     case CSSPropertyAnimationDirection: return 426;
@@ -495,6 +495,8 @@
     case CSSPropertyColumnFill: return 440;
     case CSSPropertyTextJustify: return 441;
     case CSSPropertyTouchActionDelay: return 442;
+    case CSSPropertyJustifySelf: return 443;
+    case CSSPropertyScrollBehavior: return 444;
 
     // Add new features above this line (don't change the assigned numbers of the existing
     // items) and update maximumCSSSampleId() with the new maximum value.
@@ -506,7 +508,6 @@
     case CSSPropertyInternalMarqueeSpeed:
     case CSSPropertyInternalMarqueeStyle:
     case CSSPropertyInvalid:
-    case CSSPropertyVariable:
         ASSERT_NOT_REACHED();
         return 0;
     }
@@ -515,7 +516,7 @@
     return 0;
 }
 
-static int maximumCSSSampleId() { return 442; }
+static int maximumCSSSampleId() { return 444; }
 
 UseCounter::UseCounter()
 {
@@ -569,20 +570,19 @@
 
 void UseCounter::count(const Document& document, Feature feature)
 {
-    Page* page = document.page();
-    if (!page)
+    FrameHost* host = document.frameHost();
+    if (!host)
         return;
 
-    ASSERT(page->useCounter().deprecationMessage(feature).isEmpty());
-    page->useCounter().recordMeasurement(feature);
+    ASSERT(host->useCounter().deprecationMessage(feature).isEmpty());
+    host->useCounter().recordMeasurement(feature);
 }
 
-void UseCounter::count(const DOMWindow* domWindow, Feature feature)
+void UseCounter::count(const ExecutionContext* context, Feature feature)
 {
-    ASSERT(domWindow);
-    if (!domWindow->document())
+    if (!context || !context->isDocument())
         return;
-    count(*domWindow->document(), feature);
+    count(*toDocument(context), feature);
 }
 
 void UseCounter::countDeprecation(ExecutionContext* context, Feature feature)
@@ -601,53 +601,33 @@
 
 void UseCounter::countDeprecation(const Document& document, Feature feature)
 {
-    Page* page = document.page();
-    if (!page)
+    FrameHost* host = document.frameHost();
+    if (!host)
         return;
 
-    if (page->useCounter().recordMeasurement(feature)) {
-        ASSERT(!page->useCounter().deprecationMessage(feature).isEmpty());
-        page->console().addMessage(DeprecationMessageSource, WarningMessageLevel, page->useCounter().deprecationMessage(feature));
+    if (host->useCounter().recordMeasurement(feature)) {
+        ASSERT(!host->useCounter().deprecationMessage(feature).isEmpty());
+        host->console().addMessage(DeprecationMessageSource, WarningMessageLevel, host->useCounter().deprecationMessage(feature));
     }
 }
 
 String UseCounter::deprecationMessage(Feature feature)
 {
     switch (feature) {
-    // Content Security Policy
-    case PrefixedContentSecurityPolicy:
-    case PrefixedContentSecurityPolicyReportOnly:
-        return "The 'X-WebKit-CSP' headers are no longer supported. Please consider using the canonical 'Content-Security-Policy' header instead.";
-
-    // HTMLMediaElement
-    case PrefixedMediaGenerateKeyRequest:
-        return "'HTMLMediaElement.webkitGenerateKeyRequest()' is deprecated. Please use 'MediaKeys.createSession()' instead.";
-
     // Quota
-    case StorageInfo:
+    case PrefixedStorageInfo:
         return "'window.webkitStorageInfo' is deprecated. Please use 'navigator.webkitTemporaryStorage' or 'navigator.webkitPersistentStorage' instead.";
 
     // Performance
     case PrefixedPerformanceTimeline:
         return "'window.performance.webkitGet*' methods have been deprecated. Please use the unprefixed 'performance.get*' methods instead.";
-    case PrefixedUserTiming:
-        return "'window.performance.webkit*' methods have been deprecated. Please use the unprefixed 'window.performance.*' methods instead.";
-
-    // Web Audio
-    case WebAudioLooping:
-        return "AudioBufferSourceNode 'looping' attribute is deprecated.  Use 'loop' instead.";
 
     case DocumentClear:
         return "document.clear() is deprecated. This method doesn't do anything.";
 
-    case PrefixedTransitionMediaFeature:
-        return "The '(-webkit-transition)' media query feature is deprecated; please consider using the more exact conditional \"@supports('(transition-property: prop_name)')\" instead.";
-
     // Web Components
     case HTMLShadowElementOlderShadowRoot:
         return "HTMLShadowElement.olderShadowRoot is deprecated.";
-    case PrefixedDocumentRegister:
-        return "The document.webkitRegister method is deprecated. Use the document.register method instead.";
 
     // HTML Media Capture
     case CaptureAttributeAsEnum:
@@ -655,7 +635,7 @@
 
     // Keyboard Event (DOM Level 3)
     case KeyboardEventKeyLocation:
-        return "'KeyboardEvent.keyLocation'' is deprecated. Please use 'KeyboardEvent.location' instead.";
+        return "'KeyboardEvent.keyLocation' is deprecated. Please use 'KeyboardEvent.location' instead.";
 
     case CaptureEvents:
         return "captureEvents() is deprecated. This method doesn't do anything.";
@@ -684,6 +664,57 @@
     case CSSStyleSheetInsertRuleOptionalArg:
         return "Calling CSSStyleSheet.insertRule() with one argument is deprecated. Please pass the index argument as well: insertRule(x, 0).";
 
+    case AttributeSpecified:
+        return "Attr.specified is deprecated. Its value is always true.";
+
+    case SVGElementGetPresentationAttribute:
+        return "CSSValue and SVGElement.getPresentationAttribute are deprecated. Please use getPropertyValue and parse the return value instead.";
+
+    case TextTrackCueConstructor:
+        return "The 'TextTrackCue' constructor is deprecated. Please use 'VTTCue' instead.";
+
+    case PrefixedVideoSupportsFullscreen:
+        return "'HTMLVideoElement.webkitSupportsFullscreen' is deprecated. Its value is true if the video is loaded.";
+
+    case PrefixedVideoDisplayingFullscreen:
+        return "'HTMLVideoElement.webkitDisplayingFullscreen' is deprecated. Please use the 'fullscreenchange' and 'webkitfullscreenchange' events instead.";
+
+    case PrefixedVideoEnterFullscreen:
+        return "'HTMLVideoElement.webkitEnterFullscreen()' is deprecated. Please use 'Element.requestFullscreen()' and 'Element.webkitRequestFullscreen()' instead.";
+
+    case PrefixedVideoExitFullscreen:
+        return "'HTMLVideoElement.webkitExitFullscreen()' is deprecated. Please use 'Document.exitFullscreen()' and 'Document.webkitExitFullscreen()' instead.";
+
+    case PrefixedVideoEnterFullScreen:
+        return "'HTMLVideoElement.webkitEnterFullScreen()' is deprecated. Please use 'Element.requestFullscreen()' and 'Element.webkitRequestFullscreen()' instead.";
+
+    case PrefixedVideoExitFullScreen:
+        return "'HTMLVideoElement.webkitExitFullScreen()' is deprecated. Please use 'Document.exitFullscreen()' and 'Document.webkitExitFullscreen()' instead.";
+
+    case PrefixedMediaSourceOpen:
+        return "'WebKitMediaSource' is deprecated. Please use 'MediaSource' instead.";
+
+    case DOMImplementationCreateCSSStyleSheet:
+        return "'DOMImplementation.createCSSStyleSheet()' is deprecated.";
+
+    case MediaErrorEncrypted:
+        return "'MediaError.MEDIA_ERR_ENCRYPTED' is deprecated. This error code is never used.";
+
+    case HTMLSourceElementMedia:
+        return "'HTMLSourceElement.media' is deprecated. This attribute doesn't do anything.";
+
+    case PrefixedGetImageDataHD:
+        return "'CanvasRenderingContext2D.webkitGetImageDataHD' is deprecated. Please use getImageData instead.";
+
+    case PrefixedPutImageDataHD:
+        return "'CanvasRenderingContext2D.webkitPutImageDataHD' is deprecated. Please use putImageData instead.";
+
+    case ShadowRootApplyAuthorStyles:
+        return "'ShadowRoot.applyAuthorStyles' is deprecated.";
+
+    case PrefixedSpeechAttribute:
+        return "The 'x-webkit-speech' input field attribute is deprecated. Please use the JavaScript API instead.";
+
     // Features that aren't deprecated don't have a deprecation message.
     default:
         return String();
@@ -710,8 +741,8 @@
 
 UseCounter* UseCounter::getFrom(const Document* document)
 {
-    if (document && document->page())
-        return &document->page()->useCounter();
+    if (document && document->frameHost())
+        return &document->frameHost()->useCounter();
     return 0;
 }
 
diff --git a/Source/core/frame/UseCounter.h b/Source/core/frame/UseCounter.h
index b5692a5..994e91e 100644
--- a/Source/core/frame/UseCounter.h
+++ b/Source/core/frame/UseCounter.h
@@ -59,233 +59,267 @@
     ~UseCounter();
 
     enum Feature {
-        PageDestruction,
-        LegacyNotifications,
-        MultipartMainResource,
-        PrefixedIndexedDB,
-        WorkerStart,
-        SharedWorkerStart,
-        LegacyWebAudio,
-        WebAudioStart,
-        PrefixedContentSecurityPolicy,
-        UnprefixedIndexedDB,
-        OpenWebDatabase,
-        UnusedSlot01, // Prior to 7/2013, we used this slot for LegacyHTMLNotifications.
-        LegacyTextNotifications,
-        UnprefixedRequestAnimationFrame,
-        PrefixedRequestAnimationFrame,
-        ContentSecurityPolicy,
-        ContentSecurityPolicyReportOnly,
-        PrefixedContentSecurityPolicyReportOnly,
-        PrefixedTransitionEndEvent,
-        UnprefixedTransitionEndEvent,
-        PrefixedAndUnprefixedTransitionEndEvent,
-        AutoFocusAttribute,
-        UnusedSlot02, // Prior to 4/2013, we used this slot for AutoSaveAttribute.
-        DataListElement,
-        FormAttribute,
-        IncrementalAttribute,
-        InputTypeColor,
-        InputTypeDate,
-        InputTypeDateTime,
-        InputTypeDateTimeFallback,
-        InputTypeDateTimeLocal,
-        InputTypeEmail,
-        InputTypeMonth,
-        InputTypeNumber,
-        InputTypeRange,
-        InputTypeSearch,
-        InputTypeTel,
-        InputTypeTime,
-        InputTypeURL,
-        InputTypeWeek,
-        InputTypeWeekFallback,
-        ListAttribute,
-        MaxAttribute,
-        MinAttribute,
-        PatternAttribute,
-        PlaceholderAttribute,
-        PrecisionAttribute,
-        PrefixedDirectoryAttribute,
-        PrefixedSpeechAttribute,
-        RequiredAttribute,
-        ResultsAttribute,
-        StepAttribute,
-        PageVisits,
-        HTMLMarqueeElement,
-        UnusedSlot03, // Removed, was tracking overflow: -webkit-marquee.
-        Reflection,
-        CursorVisibility, // Removed, was -webkit-cursor-visibility.
-        StorageInfo,
-        XFrameOptions,
-        XFrameOptionsSameOrigin,
-        XFrameOptionsSameOriginWithBadAncestorChain,
-        DeprecatedFlexboxWebContent,
-        DeprecatedFlexboxChrome,
-        DeprecatedFlexboxChromeExtension,
-        UnusedSlot04,
-        UnprefixedPerformanceTimeline,
-        PrefixedPerformanceTimeline,
-        UnprefixedUserTiming,
-        PrefixedUserTiming,
-        WindowEvent,
-        ContentSecurityPolicyWithBaseElement,
-        PrefixedMediaAddKey,
-        PrefixedMediaGenerateKeyRequest,
-        WebAudioLooping,
-        DocumentClear,
-        PrefixedTransitionMediaFeature,
-        SVGFontElement,
-        XMLDocument,
-        XSLProcessingInstruction,
-        XSLTProcessor,
-        SVGSwitchElement,
-        PrefixedDocumentRegister,
-        HTMLShadowElementOlderShadowRoot,
-        DocumentAll,
-        FormElement,
-        DemotedFormElement,
-        CaptureAttributeAsEnum,
-        ShadowDOMPrefixedPseudo,
-        ShadowDOMPrefixedCreateShadowRoot,
-        ShadowDOMPrefixedShadowRoot,
-        SVGAnimationElement,
-        KeyboardEventKeyLocation,
-        CaptureEvents,
-        ReleaseEvents,
-        CSSDisplayRunIn,
-        CSSDisplayCompact,
-        LineClamp,
-        SubFrameBeforeUnloadRegistered,
-        SubFrameBeforeUnloadFired,
-        CSSPseudoElementPrefixedDistributed,
-        TextReplaceWholeText,
-        PrefixedShadowRootConstructor,
-        ConsoleMarkTimeline,
-        CSSPseudoElementUserAgentCustomPseudo,
-        DocumentTypeEntities, // Removed from DOM4.
-        DocumentTypeInternalSubset, // Removed from DOM4.
-        DocumentTypeNotations, // Removed from DOM4.
-        ElementGetAttributeNode, // Removed from DOM4.
-        ElementSetAttributeNode, // Removed from DOM4.
-        ElementRemoveAttributeNode, // Removed from DOM4.
-        ElementGetAttributeNodeNS, // Removed from DOM4.
-        DocumentCreateAttribute, // Removed from DOM4.
-        DocumentCreateAttributeNS, // Removed from DOM4.
-        DocumentCreateCDATASection, // Removed from DOM4.
-        DocumentInputEncoding, // Removed from DOM4.
-        DocumentXMLEncoding, // Removed from DOM4.
-        DocumentXMLStandalone, // Removed from DOM4.
-        DocumentXMLVersion, // Removed from DOM4.
-        NodeIsSameNode, // Removed from DOM4.
-        NodeIsSupported, // Removed from DOM4.
-        NodeNamespaceURI, // Removed from DOM4.
-        NodePrefix, // Removed from DOM4.
-        NodeLocalName, // Removed from DOM4.
-        NavigatorProductSub,
-        NavigatorVendor,
-        NavigatorVendorSub,
-        FileError,
-        DocumentCharset, // Documented as IE extensions, from KHTML days.
-        PrefixedAnimationEndEvent,
-        UnprefixedAnimationEndEvent,
-        PrefixedAndUnprefixedAnimationEndEvent,
-        PrefixedAnimationStartEvent,
-        UnprefixedAnimationStartEvent,
-        PrefixedAndUnprefixedAnimationStartEvent,
-        PrefixedAnimationIterationEvent,
-        UnprefixedAnimationIterationEvent,
-        PrefixedAndUnprefixedAnimationIterationEvent,
-        EventReturnValue, // Legacy IE extension.
-        SVGSVGElement,
-        SVGAnimateColorElement,
-        InsertAdjacentText,
-        InsertAdjacentElement,
-        HasAttributes, // Removed from DOM4.
-        DOMSubtreeModifiedEvent,
-        DOMNodeInsertedEvent,
-        DOMNodeRemovedEvent,
-        DOMNodeRemovedFromDocumentEvent,
-        DOMNodeInsertedIntoDocumentEvent,
-        DOMCharacterDataModifiedEvent,
-        DocumentAllTags,
-        DocumentAllLegacyCall,
-        HTMLAppletElementLegacyCall,
-        HTMLEmbedElementLegacyCall,
-        HTMLObjectElementLegacyCall,
-        BeforeLoadEvent,
-        GetMatchedCSSRules,
-        SVGFontInCSS,
-        ScrollTopBodyNotQuirksMode,
-        ScrollLeftBodyNotQuirksMode,
-        AttributeIsId, // Removed in DOM4.
-        AttributeOwnerElement, // Removed in DOM4.
-        AttributeSetPrefix, // Attribute prefix is readonly in DOM4.
-        AttributeSpecified, // Removed in DOM4.
-        BeforeLoadEventInIsolatedWorld,
-        PrefixedAudioDecodedByteCount,
-        PrefixedVideoDecodedByteCount,
-        PrefixedVideoSupportsFullscreen,
-        PrefixedVideoDisplayingFullscreen,
-        PrefixedVideoEnterFullscreen,
-        PrefixedVideoExitFullscreen,
-        PrefixedVideoEnterFullScreen,
-        PrefixedVideoExitFullScreen,
-        PrefixedVideoDecodedFrameCount,
-        PrefixedVideoDroppedFrameCount,
-        SourceElementCandidate,
-        SourceElementNonMatchingMedia,
-        PrefixedElementRequestFullscreen,
-        PrefixedElementRequestFullScreen,
-        BarPropLocationbar,
-        BarPropMenubar,
-        BarPropPersonalbar,
-        BarPropScrollbars,
-        BarPropStatusbar,
-        BarPropToolbar,
-        InputTypeEmailMultiple,
-        InputTypeEmailMaxLength,
-        InputTypeEmailMultipleMaxLength,
-        TextTrackCueConstructor,
-        CSSStyleDeclarationPropertyName, // Removed in CSSOM.
-        CSSStyleDeclarationFloatPropertyName, // Pending removal in CSSOM.
-        InputTypeText,
-        InputTypeTextMaxLength,
-        InputTypePassword,
-        InputTypePasswordMaxLength,
-        SVGInstanceRoot,
-        ShowModalDialog,
-        PrefixedPageVisibility,
-        HTMLFrameElementLocation,
-        CSSStyleSheetInsertRuleOptionalArg, // Inconsistent with the specification and other browsers.
-        CSSWebkitRegionAtRule, // @region rule changed to ::region()
-        DocumentBeforeUnloadRegistered,
-        DocumentBeforeUnloadFired,
-        DocumentUnloadRegistered,
-        DocumentUnloadFired,
-        SVGLocatableNearestViewportElement,
-        SVGLocatableFarthestViewportElement,
-        IsIndexElement,
-        HTMLHeadElementProfile,
-        OverflowChangedEvent,
-        SVGPointMatrixTransform,
-        HTMLHtmlElementManifest,
-        DOMFocusInOutEvent,
-        FileGetLastModifiedDate,
-        HTMLElementInnerText,
-        HTMLElementOuterText,
-        ReplaceDocumentViaJavaScriptURL,
-        ElementSetAttributeNodeNS, // Removed from DOM4.
-        ElementPrefixedMatchesSelector,
-        DOMImplementationCreateCSSStyleSheet,
+        // Do not change assigned numbers of existing items: add new features
+        // to the end of the list.
+        PageDestruction = 0,
+        LegacyNotifications = 1,
+        MultipartMainResource = 2,
+        PrefixedIndexedDB = 3,
+        WorkerStart = 4,
+        SharedWorkerStart = 5,
+        LegacyWebAudio = 6,
+        WebAudioStart = 7,
+        UnprefixedIndexedDB = 9,
+        OpenWebDatabase = 10,
+        LegacyTextNotifications = 12,
+        UnprefixedRequestAnimationFrame = 13,
+        PrefixedRequestAnimationFrame = 14,
+        ContentSecurityPolicy = 15,
+        ContentSecurityPolicyReportOnly = 16,
+        PrefixedTransitionEndEvent = 18,
+        UnprefixedTransitionEndEvent = 19,
+        PrefixedAndUnprefixedTransitionEndEvent = 20,
+        AutoFocusAttribute = 21,
+        DataListElement = 23,
+        FormAttribute = 24,
+        IncrementalAttribute = 25,
+        InputTypeColor = 26,
+        InputTypeDate = 27,
+        InputTypeDateTime = 28,
+        InputTypeDateTimeFallback = 29,
+        InputTypeDateTimeLocal = 30,
+        InputTypeEmail = 31,
+        InputTypeMonth = 32,
+        InputTypeNumber = 33,
+        InputTypeRange = 34,
+        InputTypeSearch = 35,
+        InputTypeTel = 36,
+        InputTypeTime = 37,
+        InputTypeURL = 38,
+        InputTypeWeek = 39,
+        InputTypeWeekFallback = 40,
+        ListAttribute = 41,
+        MaxAttribute = 42,
+        MinAttribute = 43,
+        PatternAttribute = 44,
+        PlaceholderAttribute = 45,
+        PrecisionAttribute = 46,
+        PrefixedDirectoryAttribute = 47,
+        PrefixedSpeechAttribute = 48,
+        RequiredAttribute = 49,
+        ResultsAttribute = 50,
+        StepAttribute = 51,
+        PageVisits = 52,
+        HTMLMarqueeElement = 53,
+        Reflection = 55,
+        PrefixedStorageInfo = 57,
+        XFrameOptions = 58,
+        XFrameOptionsSameOrigin = 59,
+        XFrameOptionsSameOriginWithBadAncestorChain = 60,
+        DeprecatedFlexboxWebContent = 61,
+        DeprecatedFlexboxChrome = 62,
+        DeprecatedFlexboxChromeExtension = 63,
+        UnprefixedPerformanceTimeline = 65,
+        PrefixedPerformanceTimeline = 66,
+        UnprefixedUserTiming = 67,
+        WindowEvent = 69,
+        ContentSecurityPolicyWithBaseElement = 70,
+        PrefixedMediaAddKey = 71,
+        PrefixedMediaGenerateKeyRequest = 72,
+        DocumentClear = 74,
+        SVGFontElement = 76,
+        XMLDocument = 77,
+        XSLProcessingInstruction = 78,
+        XSLTProcessor = 79,
+        SVGSwitchElement = 80,
+        HTMLShadowElementOlderShadowRoot = 82,
+        DocumentAll = 83,
+        FormElement = 84,
+        DemotedFormElement = 85,
+        CaptureAttributeAsEnum = 86,
+        ShadowDOMPrefixedPseudo = 87,
+        ShadowDOMPrefixedCreateShadowRoot = 88,
+        ShadowDOMPrefixedShadowRoot = 89,
+        SVGAnimationElement = 90,
+        KeyboardEventKeyLocation = 91,
+        CaptureEvents = 92,
+        ReleaseEvents = 93,
+        CSSDisplayRunIn = 94,
+        CSSDisplayCompact = 95,
+        LineClamp = 96,
+        SubFrameBeforeUnloadRegistered = 97,
+        SubFrameBeforeUnloadFired = 98,
+        CSSPseudoElementPrefixedDistributed = 99,
+        TextReplaceWholeText = 100,
+        PrefixedShadowRootConstructor = 101,
+        ConsoleMarkTimeline = 102,
+        CSSPseudoElementUserAgentCustomPseudo = 103,
+        DocumentTypeEntities = 104, // Removed from DOM4.
+        DocumentTypeInternalSubset = 105, // Removed from DOM4.
+        DocumentTypeNotations = 106, // Removed from DOM4.
+        ElementGetAttributeNode = 107, // Removed from DOM4.
+        ElementSetAttributeNode = 108, // Removed from DOM4.
+        ElementRemoveAttributeNode = 109, // Removed from DOM4.
+        ElementGetAttributeNodeNS = 110, // Removed from DOM4.
+        DocumentCreateAttribute = 111, // Removed from DOM4.
+        DocumentCreateCDATASection = 113, // Removed from DOM4.
+        DocumentInputEncoding = 114, // Removed from DOM4.
+        DocumentXMLEncoding = 115, // Removed from DOM4.
+        DocumentXMLStandalone = 116, // Removed from DOM4.
+        DocumentXMLVersion = 117, // Removed from DOM4.
+        NodeIsSameNode = 118, // Removed from DOM4.
+        NodeIsSupported = 119, // Removed from DOM4.
+        NodeNamespaceURI = 120, // Removed from DOM4.
+        NodeLocalName = 122, // Removed from DOM4.
+        NavigatorProductSub = 123,
+        NavigatorVendor = 124,
+        NavigatorVendorSub = 125,
+        FileError = 126,
+        DocumentCharset = 127, // Documented as IE extensions = 0, from KHTML days.
+        PrefixedAnimationEndEvent = 128,
+        UnprefixedAnimationEndEvent = 129,
+        PrefixedAndUnprefixedAnimationEndEvent = 130,
+        PrefixedAnimationStartEvent = 131,
+        UnprefixedAnimationStartEvent = 132,
+        PrefixedAndUnprefixedAnimationStartEvent = 133,
+        PrefixedAnimationIterationEvent = 134,
+        UnprefixedAnimationIterationEvent = 135,
+        PrefixedAndUnprefixedAnimationIterationEvent = 136,
+        EventReturnValue = 137, // Legacy IE extension.
+        SVGSVGElement = 138,
+        SVGAnimateColorElement = 139,
+        InsertAdjacentText = 140,
+        InsertAdjacentElement = 141,
+        HasAttributes = 142, // Removed from DOM4.
+        DOMSubtreeModifiedEvent = 143,
+        DOMNodeInsertedEvent = 144,
+        DOMNodeRemovedEvent = 145,
+        DOMNodeRemovedFromDocumentEvent = 146,
+        DOMNodeInsertedIntoDocumentEvent = 147,
+        DOMCharacterDataModifiedEvent = 148,
+        DocumentAllLegacyCall = 150,
+        HTMLAppletElementLegacyCall = 151,
+        HTMLEmbedElementLegacyCall = 152,
+        HTMLObjectElementLegacyCall = 153,
+        BeforeLoadEvent = 154,
+        GetMatchedCSSRules = 155,
+        SVGFontInCSS = 156,
+        ScrollTopBodyNotQuirksMode = 157,
+        ScrollLeftBodyNotQuirksMode = 158,
+        AttributeSpecified = 162, // Removed in DOM4.
+        BeforeLoadEventInIsolatedWorld = 163,
+        PrefixedAudioDecodedByteCount = 164,
+        PrefixedVideoDecodedByteCount = 165,
+        PrefixedVideoSupportsFullscreen = 166,
+        PrefixedVideoDisplayingFullscreen = 167,
+        PrefixedVideoEnterFullscreen = 168,
+        PrefixedVideoExitFullscreen = 169,
+        PrefixedVideoEnterFullScreen = 170,
+        PrefixedVideoExitFullScreen = 171,
+        PrefixedVideoDecodedFrameCount = 172,
+        PrefixedVideoDroppedFrameCount = 173,
+        PrefixedElementRequestFullscreen = 176,
+        PrefixedElementRequestFullScreen = 177,
+        BarPropLocationbar = 178,
+        BarPropMenubar = 179,
+        BarPropPersonalbar = 180,
+        BarPropScrollbars = 181,
+        BarPropStatusbar = 182,
+        BarPropToolbar = 183,
+        InputTypeEmailMultiple = 184,
+        InputTypeEmailMaxLength = 185,
+        InputTypeEmailMultipleMaxLength = 186,
+        TextTrackCueConstructor = 187,
+        CSSStyleDeclarationPropertyName = 188, // Removed in CSSOM.
+        CSSStyleDeclarationFloatPropertyName = 189, // Pending removal in CSSOM.
+        InputTypeText = 190,
+        InputTypeTextMaxLength = 191,
+        InputTypePassword = 192,
+        InputTypePasswordMaxLength = 193,
+        SVGInstanceRoot = 194,
+        ShowModalDialog = 195,
+        PrefixedPageVisibility = 196,
+        HTMLFrameElementLocation = 197,
+        CSSStyleSheetInsertRuleOptionalArg = 198, // Inconsistent with the specification and other browsers.
+        DocumentBeforeUnloadRegistered = 200,
+        DocumentBeforeUnloadFired = 201,
+        DocumentUnloadRegistered = 202,
+        DocumentUnloadFired = 203,
+        SVGLocatableNearestViewportElement = 204,
+        SVGLocatableFarthestViewportElement = 205,
+        IsIndexElement = 206,
+        HTMLHeadElementProfile = 207,
+        OverflowChangedEvent = 208,
+        SVGPointMatrixTransform = 209,
+        HTMLHtmlElementManifest = 210,
+        DOMFocusInOutEvent = 211,
+        FileGetLastModifiedDate = 212,
+        HTMLElementInnerText = 213,
+        HTMLElementOuterText = 214,
+        ReplaceDocumentViaJavaScriptURL = 215,
+        ElementPrefixedMatchesSelector = 217,
+        DOMImplementationCreateCSSStyleSheet = 218,
+        CSSStyleSheetRules = 219,
+        CSSStyleSheetAddRule = 220,
+        CSSStyleSheetRemoveRule = 221,
+        InitMessageEvent = 222,
+        PrefixedInitMessageEvent = 223,
+        ElementSetPrefix = 224, // Element.prefix is readonly in DOM4.
+        CSSStyleDeclarationGetPropertyCSSValue = 225,
+        SVGElementGetPresentationAttribute = 226,
+        PrefixedMediaCancelKeyRequest = 229,
+        DOMImplementationHasFeature = 230,
+        DOMImplementationHasFeatureReturnFalse = 231,
+        CanPlayTypeKeySystem = 232,
+        PrefixedDevicePixelRatioMediaFeature = 233,
+        PrefixedMaxDevicePixelRatioMediaFeature = 234,
+        PrefixedMinDevicePixelRatioMediaFeature = 235,
+        PrefixedTransform2dMediaFeature = 236,
+        PrefixedTransform3dMediaFeature = 237,
+        PrefixedAnimationMediaFeature = 238,
+        PrefixedViewModeMediaFeature = 239,
+        PrefixedStorageQuota = 240,
+        ContentSecurityPolicyReportOnlyInMeta = 241,
+        PrefixedMediaSourceOpen = 242,
+        ResetReferrerPolicy = 243,
+        CaseInsensitiveAttrSelectorMatch = 244, // Case-insensitivity dropped from specification.
+        CaptureAttributeAsBoolean = 245,
+        FormNameAccessForImageElement = 246,
+        FormNameAccessForPastNamesMap = 247,
+        FormAssociationByParser = 248,
+        HTMLSourceElementMedia = 249,
+        SVGSVGElementInDocument = 250,
+        SVGDocumentRootElement = 251,
+        DocumentCreateEventOptionalArgument = 252,
+        MediaErrorEncrypted = 253,
+        EventSourceURL = 254,
+        WebSocketURL = 255,
+        UnsafeEvalBlocksCSSOM = 256,
+        WorkerSubjectToCSP = 257,
+        WorkerAllowedByChildBlockedByScript = 258,
+        HTMLMediaElementControllerNotNull = 259,
+        DeprecatedWebKitGradient = 260,
+        DeprecatedWebKitLinearGradient = 261,
+        DeprecatedWebKitRepeatingLinearGradient = 262,
+        DeprecatedWebKitRadialGradient = 263,
+        DeprecatedWebKitRepeatingRadialGradient = 264,
+        PrefixedGetImageDataHD = 265,
+        PrefixedPutImageDataHD = 266,
+        PrefixedImageSmoothingEnabled = 267,
+        UnprefixedImageSmoothingEnabled = 268,
+        ShadowRootApplyAuthorStyles = 269,
+        PromiseConstructor = 270,
+        PromiseCast = 271,
+        PromiseReject = 272,
+        PromiseResolve = 273,
         // Add new features immediately above this line. Don't change assigned
-        // numbers of each items, and don't reuse unused slots.
+        // numbers of any item, and don't reuse removed slots.
         NumberOfFeatures, // This enum value must be last.
     };
 
     // "count" sets the bit for this feature to 1. Repeated calls are ignored.
     static void count(const Document&, Feature);
-    static void count(const DOMWindow*, Feature);
+    static void count(const ExecutionContext*, Feature);
     void count(CSSParserContext, CSSPropertyID);
     void count(Feature);
 
diff --git a/Source/core/frame/WebKitPoint.idl b/Source/core/frame/WebKitPoint.idl
index 4e3637a..88b4be2 100644
--- a/Source/core/frame/WebKitPoint.idl
+++ b/Source/core/frame/WebKitPoint.idl
@@ -26,7 +26,7 @@
 [
     CustomConstructor,
     CustomConstructor(float x, float y),
-    ImplementedAs=DOMPoint
+    ImplementedAs=DOMPoint,
 ] interface WebKitPoint {
     attribute float x;
     attribute float y;
diff --git a/Source/core/frame/Window.idl b/Source/core/frame/Window.idl
index 632e3a2..c418b52 100644
--- a/Source/core/frame/Window.idl
+++ b/Source/core/frame/Window.idl
@@ -65,10 +65,10 @@
                                        optional any dialogArgs,
                                        optional DOMString featureArgs);
 
-    void alert([Default=Undefined] optional DOMString message);
-    boolean confirm([Default=Undefined] optional DOMString message);
-    [TreatReturnedNullStringAs=Null] DOMString prompt([Default=Undefined] optional DOMString message,
-                                                [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString defaultValue);
+    void alert([Default=NullString] optional DOMString message);
+    boolean confirm([Default=NullString] optional DOMString message);
+    [TreatReturnedNullStringAs=Null] DOMString prompt([Default=NullString] optional DOMString message,
+                                                      [Default=NullString] optional DOMString defaultValue);
 
     boolean find([Default=Undefined] optional DOMString string,
                  [Default=Undefined] optional boolean caseSensitive,
@@ -93,9 +93,17 @@
     readonly attribute long pageXOffset;
     readonly attribute long pageYOffset;
 
-    void scrollBy(long x, long y);
-    void scrollTo(long x, long y);
-    void scroll(long x, long y);
+    // FIXME: should be:
+    // void scrollBy(long x, long y);
+    // [RuntimeEnabled=CSSOMSmoothScroll, RaisesException] void scrollBy(long x, long y, optional Dictionary scrollOptions);
+    // void scrollTo(long x, long y);
+    // [RuntimeEnabled=CSSOMSmoothScroll, RaisesException] void scrollTo(long x, long y, optional Dictionary scrollOptions);
+    // void scroll(long x, long y);
+    // [RuntimeEnabled=CSSOMSmoothScroll, RaisesException] void scroll(long x, long y, optional Dictionary scrollOptions);
+    // http://crbug.com/339000
+    [RaisesException] void scrollBy(long x, long y, optional Dictionary scrollOptions);
+    [RaisesException] void scrollTo(long x, long y, optional Dictionary scrollOptions);
+    [RaisesException] void scroll(long x, long y, optional Dictionary scrollOptions);
     void moveBy([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
     void moveTo([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
     void resizeBy([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
@@ -153,12 +161,12 @@
     // This is the interface orientation in degrees. Some examples are:
     //  0 is straight up; -90 is when the device is rotated 90 clockwise;
     //  90 is when rotated counter clockwise.
-    [Conditional=ORIENTATION_EVENTS] readonly attribute long orientation;
+    [RuntimeEnabled=OrientationEvent] readonly attribute long orientation;
 
     [Replaceable] readonly attribute Console console;
 
     // cross-document messaging
-    [DoNotCheckSecurity, Custom, RaisesException] void postMessage(SerializedScriptValue message, DOMString targetOrigin, optional Array messagePorts);
+    [DoNotCheckSecurity, Custom, RaisesException] void postMessage(SerializedScriptValue message, DOMString targetOrigin, optional MessagePort[] messagePorts);
 
     [Replaceable] readonly attribute Performance performance;
 
@@ -176,7 +184,7 @@
     [RuntimeEnabled=CSSAnimationUnprefixed] attribute EventHandler onanimationstart;
     [RuntimeEnabled=DeviceMotion] attribute EventHandler ondevicemotion;
     [RuntimeEnabled=DeviceOrientation] attribute EventHandler ondeviceorientation;
-    [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
+    [RuntimeEnabled=OrientationEvent] attribute EventHandler onorientationchange;
     attribute EventHandler onsearch;
     [RuntimeEnabled=Touch] attribute EventHandler ontouchcancel;
     [RuntimeEnabled=Touch] attribute EventHandler ontouchend;
@@ -195,9 +203,6 @@
     // Additional constructors.
     attribute TransitionEventConstructor WebKitTransitionEvent;
     [RuntimeEnabled=CSSAnimationUnprefixed] attribute WebKitAnimationEventConstructor AnimationEvent;
-    // Mozilla has a separate XMLDocument object for XML documents.
-    // We just use Document for this.
-    attribute DocumentConstructor XMLDocument;
     attribute URLConstructor webkitURL; // FIXME: deprecate this.
     attribute MutationObserverConstructor WebKitMutationObserver; // FIXME: Add metrics to determine when we can remove this.
     attribute IDBCursorConstructor webkitIDBCursor;
@@ -232,7 +237,7 @@
     // window.toString() requires special handling in V8
     [DoNotCheckSignature, DoNotCheckSecurity, Custom, NotEnumerable] DOMString toString();
 
-    [ImplementedAs=anonymousIndexedGetter, NotEnumerable] getter Window(unsigned long index);
+    [NotEnumerable] getter Window (unsigned long index);
     [Custom, NotEnumerable] getter Window (DOMString name);
 };
 
diff --git a/Source/core/frame/WindowEventHandlers.idl b/Source/core/frame/WindowEventHandlers.idl
index b7634ae..c268557 100644
--- a/Source/core/frame/WindowEventHandlers.idl
+++ b/Source/core/frame/WindowEventHandlers.idl
@@ -41,7 +41,6 @@
     attribute EventHandler onpagehide;
     attribute EventHandler onpageshow;
     attribute EventHandler onpopstate;
-    attribute EventHandler onresize;
     attribute EventHandler onstorage;
     attribute EventHandler onunload;
 };
diff --git a/Source/core/frame/animation/AnimationBase.cpp b/Source/core/frame/animation/AnimationBase.cpp
deleted file mode 100644
index 5dafb2d..0000000
--- a/Source/core/frame/animation/AnimationBase.cpp
+++ /dev/null
@@ -1,585 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-#include "core/frame/animation/AnimationBase.h"
-
-#include "core/frame/animation/AnimationControllerPrivate.h"
-#include "core/frame/animation/CompositeAnimation.h"
-#include "core/platform/animation/TimingFunction.h"
-#include "core/rendering/RenderBox.h"
-#include "platform/animation/AnimationUtilities.h"
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-AnimationBase::AnimationBase(const CSSAnimationData* transition, RenderObject& renderer, CompositeAnimation* compAnim)
-    : m_animState(AnimationStateNew)
-    , m_isAccelerated(false)
-    , m_transformFunctionListValid(false)
-    , m_filterFunctionListsMatch(false)
-    , m_startTime(0)
-    , m_pauseTime(-1)
-    , m_requestedStartTime(0)
-    , m_totalDuration(-1)
-    , m_nextIterationDuration(-1)
-    , m_object(&renderer)
-    , m_animation(const_cast<CSSAnimationData*>(transition))
-    , m_compAnim(compAnim)
-{
-    // Compute the total duration
-    if (m_animation->iterationCount() > 0)
-        m_totalDuration = m_animation->duration() * m_animation->iterationCount();
-}
-
-void AnimationBase::setNeedsStyleRecalc(Node* node)
-{
-    if (node)
-        node->setNeedsStyleRecalc(LocalStyleChange);
-}
-
-double AnimationBase::duration() const
-{
-    return m_animation->duration();
-}
-
-bool AnimationBase::playStatePlaying() const
-{
-    return m_animation->playState() == AnimPlayStatePlaying;
-}
-
-void AnimationBase::updateStateMachine(AnimStateInput input, double param)
-{
-    if (!m_compAnim)
-        return;
-
-    // If we get AnimationStateInputRestartAnimation then we force a new animation, regardless of state.
-    if (input == AnimationStateInputMakeNew) {
-        if (m_animState == AnimationStateStartWaitStyleAvailable)
-            m_compAnim->animationController()->removeFromAnimationsWaitingForStyle(this);
-        m_animState = AnimationStateNew;
-        m_startTime = 0;
-        m_pauseTime = -1;
-        m_requestedStartTime = 0;
-        m_nextIterationDuration = -1;
-        endAnimation();
-        return;
-    }
-
-    if (input == AnimationStateInputRestartAnimation) {
-        if (m_animState == AnimationStateStartWaitStyleAvailable)
-            m_compAnim->animationController()->removeFromAnimationsWaitingForStyle(this);
-        m_animState = AnimationStateNew;
-        m_startTime = 0;
-        m_pauseTime = -1;
-        m_requestedStartTime = 0;
-        m_nextIterationDuration = -1;
-        endAnimation();
-
-        if (!paused())
-            updateStateMachine(AnimationStateInputStartAnimation, -1);
-        return;
-    }
-
-    if (input == AnimationStateInputEndAnimation) {
-        if (m_animState == AnimationStateStartWaitStyleAvailable)
-            m_compAnim->animationController()->removeFromAnimationsWaitingForStyle(this);
-        m_animState = AnimationStateDone;
-        endAnimation();
-        return;
-    }
-
-    if (input == AnimationStateInputPauseOverride) {
-        if (m_animState == AnimationStateStartWaitResponse) {
-            // If we are in AnimationStateStartWaitResponse, the animation will get canceled before
-            // we get a response, so move to the next state.
-            endAnimation();
-            updateStateMachine(AnimationStateInputStartTimeSet, beginAnimationUpdateTime());
-        }
-        return;
-    }
-
-    if (input == AnimationStateInputResumeOverride) {
-        if (m_animState == AnimationStateLooping || m_animState == AnimationStateEnding) {
-            // Start the animation
-            startAnimation(beginAnimationUpdateTime() - m_startTime);
-        }
-        return;
-    }
-
-    // Execute state machine
-    switch (m_animState) {
-        case AnimationStateNew:
-            ASSERT(input == AnimationStateInputStartAnimation || input == AnimationStateInputPlayStateRunning || input == AnimationStateInputPlayStatePaused);
-            if (input == AnimationStateInputStartAnimation || input == AnimationStateInputPlayStateRunning) {
-                m_requestedStartTime = beginAnimationUpdateTime();
-                m_animState = AnimationStateStartWaitTimer;
-            }
-            break;
-        case AnimationStateStartWaitTimer:
-            ASSERT(input == AnimationStateInputStartTimerFired || input == AnimationStateInputPlayStatePaused);
-
-            if (input == AnimationStateInputStartTimerFired) {
-                ASSERT(param >= 0);
-                // Start timer has fired, tell the animation to start and wait for it to respond with start time
-                m_animState = AnimationStateStartWaitStyleAvailable;
-                m_compAnim->animationController()->addToAnimationsWaitingForStyle(this);
-
-                // Trigger a render so we can start the animation
-                if (m_object)
-                    m_compAnim->animationController()->addNodeChangeToDispatch(m_object->node());
-            } else {
-                ASSERT(!paused());
-                // We're waiting for the start timer to fire and we got a pause. Cancel the timer, pause and wait
-                m_pauseTime = beginAnimationUpdateTime();
-                m_animState = AnimationStatePausedWaitTimer;
-            }
-            break;
-        case AnimationStateStartWaitStyleAvailable:
-            ASSERT(input == AnimationStateInputStyleAvailable || input == AnimationStateInputPlayStatePaused);
-
-            if (input == AnimationStateInputStyleAvailable) {
-                // Start timer has fired, tell the animation to start and wait for it to respond with start time
-                m_animState = AnimationStateStartWaitResponse;
-
-                overrideAnimations();
-
-                // Start the animation
-                if (overridden()) {
-                    m_animState = AnimationStateStartWaitResponse;
-                    updateStateMachine(AnimationStateInputStartTimeSet, beginAnimationUpdateTime());
-                } else {
-                    double timeOffset = 0;
-                    // If the value for 'animation-delay' is negative then the animation appears to have started in the past.
-                    if (m_animation->delay() < 0)
-                        timeOffset = -m_animation->delay();
-                    startAnimation(timeOffset);
-                    m_compAnim->animationController()->addToAnimationsWaitingForStartTimeResponse(this, isAccelerated());
-                }
-            } else {
-                // We're waiting for the style to be available and we got a pause. Pause and wait
-                m_pauseTime = beginAnimationUpdateTime();
-                m_animState = AnimationStatePausedWaitStyleAvailable;
-            }
-            break;
-        case AnimationStateStartWaitResponse:
-            ASSERT(input == AnimationStateInputStartTimeSet || input == AnimationStateInputPlayStatePaused);
-
-            if (input == AnimationStateInputStartTimeSet) {
-                ASSERT(param >= 0);
-                // We have a start time, set it, unless the startTime is already set
-                if (m_startTime <= 0) {
-                    m_startTime = param;
-                    // If the value for 'animation-delay' is negative then the animation appears to have started in the past.
-                    if (m_animation->delay() < 0)
-                        m_startTime += m_animation->delay();
-                }
-
-                // Now that we know the start time, fire the start event.
-                onAnimationStart(0); // The elapsedTime is 0.
-
-                // Decide whether to go into looping or ending state
-                goIntoEndingOrLoopingState();
-
-                // Dispatch updateStyleIfNeeded so we can start the animation
-                if (m_object)
-                    m_compAnim->animationController()->addNodeChangeToDispatch(m_object->node());
-            } else {
-                // We are pausing while waiting for a start response. Cancel the animation and wait. When
-                // we unpause, we will act as though the start timer just fired
-                m_pauseTime = beginAnimationUpdateTime();
-                pauseAnimation(beginAnimationUpdateTime() - m_startTime);
-                m_animState = AnimationStatePausedWaitResponse;
-            }
-            break;
-        case AnimationStateLooping:
-            ASSERT(input == AnimationStateInputLoopTimerFired || input == AnimationStateInputPlayStatePaused);
-
-            if (input == AnimationStateInputLoopTimerFired) {
-                ASSERT(param >= 0);
-                // Loop timer fired, loop again or end.
-                onAnimationIteration(param);
-
-                // Decide whether to go into looping or ending state
-                goIntoEndingOrLoopingState();
-            } else {
-                // We are pausing while running. Cancel the animation and wait
-                m_pauseTime = beginAnimationUpdateTime();
-                pauseAnimation(beginAnimationUpdateTime() - m_startTime);
-                m_animState = AnimationStatePausedRun;
-            }
-            break;
-        case AnimationStateEnding:
-#if !LOG_DISABLED
-            if (input != AnimationStateInputEndTimerFired && input != AnimationStateInputPlayStatePaused)
-                WTF_LOG_ERROR("State is AnimationStateEnding, but input is not AnimationStateInputEndTimerFired or AnimationStateInputPlayStatePaused. It is %d.", input);
-#endif
-            if (input == AnimationStateInputEndTimerFired) {
-
-                ASSERT(param >= 0);
-                // End timer fired, finish up
-                onAnimationEnd(param);
-
-                m_animState = AnimationStateDone;
-
-                if (m_object) {
-                    if (m_animation->fillsForwards())
-                        m_animState = AnimationStateFillingForwards;
-                    else
-                        resumeOverriddenAnimations();
-
-                    // Fire off another style change so we can set the final value
-                    m_compAnim->animationController()->addNodeChangeToDispatch(m_object->node());
-                }
-            } else {
-                // We are pausing while running. Cancel the animation and wait
-                m_pauseTime = beginAnimationUpdateTime();
-                pauseAnimation(beginAnimationUpdateTime() - m_startTime);
-                m_animState = AnimationStatePausedRun;
-            }
-            // |this| may be deleted here
-            break;
-        case AnimationStatePausedWaitTimer:
-            ASSERT(input == AnimationStateInputPlayStateRunning);
-            ASSERT(paused());
-            // Update the times
-            m_startTime += beginAnimationUpdateTime() - m_pauseTime;
-            m_pauseTime = -1;
-
-            // we were waiting for the start timer to fire, go back and wait again
-            m_animState = AnimationStateNew;
-            updateStateMachine(AnimationStateInputStartAnimation, 0);
-            break;
-        case AnimationStatePausedWaitResponse:
-        case AnimationStatePausedWaitStyleAvailable:
-        case AnimationStatePausedRun:
-            // We treat these two cases the same. The only difference is that, when we are in
-            // AnimationStatePausedWaitResponse, we don't yet have a valid startTime, so we send 0 to startAnimation.
-            // When the AnimationStateInputStartTimeSet comes in and we were in AnimationStatePausedRun, we will notice
-            // that we have already set the startTime and will ignore it.
-            ASSERT(input == AnimationStateInputPlayStateRunning || input == AnimationStateInputStartTimeSet || input == AnimationStateInputStyleAvailable);
-            ASSERT(paused());
-
-            if (input == AnimationStateInputPlayStateRunning) {
-                // Update the times
-                if (m_animState == AnimationStatePausedRun)
-                    m_startTime += beginAnimationUpdateTime() - m_pauseTime;
-                else
-                    m_startTime = 0;
-                m_pauseTime = -1;
-
-                if (m_animState == AnimationStatePausedWaitStyleAvailable)
-                    m_animState = AnimationStateStartWaitStyleAvailable;
-                else {
-                    // We were either running or waiting for a begin time response from the animation.
-                    // Either way we need to restart the animation (possibly with an offset if we
-                    // had already been running) and wait for it to start.
-                    m_animState = AnimationStateStartWaitResponse;
-
-                    // Start the animation
-                    if (overridden()) {
-                        updateStateMachine(AnimationStateInputStartTimeSet, beginAnimationUpdateTime());
-                    } else {
-                        startAnimation(beginAnimationUpdateTime() - m_startTime);
-                        m_compAnim->animationController()->addToAnimationsWaitingForStartTimeResponse(this, isAccelerated());
-                    }
-                }
-                break;
-            }
-
-            if (input == AnimationStateInputStartTimeSet) {
-                ASSERT(m_animState == AnimationStatePausedWaitResponse);
-
-                // We are paused but we got the callback that notifies us that an accelerated animation started.
-                // We ignore the start time and just move into the paused-run state.
-                m_animState = AnimationStatePausedRun;
-                ASSERT(m_startTime == 0);
-                m_startTime = param;
-                m_pauseTime += m_startTime;
-                break;
-            }
-
-            ASSERT(m_animState == AnimationStatePausedWaitStyleAvailable);
-            // We are paused but we got the callback that notifies us that style has been updated.
-            // We move to the AnimationStatePausedWaitResponse state
-            m_animState = AnimationStatePausedWaitResponse;
-            overrideAnimations();
-            break;
-        case AnimationStateFillingForwards:
-        case AnimationStateDone:
-            // We're done. Stay in this state until we are deleted
-            break;
-    }
-}
-
-void AnimationBase::fireAnimationEventsIfNeeded()
-{
-    if (!m_compAnim)
-        return;
-
-    // If we are waiting for the delay time to expire and it has, go to the next state
-    if (m_animState != AnimationStateStartWaitTimer && m_animState != AnimationStateLooping && m_animState != AnimationStateEnding)
-        return;
-
-    // We have to make sure to keep a ref to the this pointer, because it could get destroyed
-    // during an animation callback that might get called. Since the owner is a CompositeAnimation
-    // and it ref counts this object, we will keep a ref to that instead. That way the AnimationBase
-    // can still access the resources of its CompositeAnimation as needed.
-    RefPtr<AnimationBase> protector(this);
-    RefPtr<CompositeAnimation> compProtector(m_compAnim);
-
-    // Check for start timeout
-    if (m_animState == AnimationStateStartWaitTimer) {
-        if (beginAnimationUpdateTime() - m_requestedStartTime >= m_animation->delay())
-            updateStateMachine(AnimationStateInputStartTimerFired, 0);
-        return;
-    }
-
-    double elapsedDuration = getElapsedTime();
-
-    // Check for end timeout
-    if (m_totalDuration >= 0 && elapsedDuration >= m_totalDuration) {
-        // We may still be in AnimationStateLooping if we've managed to skip a
-        // whole iteration, in which case we should jump to the end state.
-        m_animState = AnimationStateEnding;
-
-        // Fire an end event
-        updateStateMachine(AnimationStateInputEndTimerFired, m_totalDuration);
-    } else {
-        // Check for iteration timeout
-        if (m_nextIterationDuration < 0) {
-            // Hasn't been set yet, set it
-            double durationLeft = m_animation->duration() - fmod(elapsedDuration, m_animation->duration());
-            m_nextIterationDuration = elapsedDuration + durationLeft;
-        }
-
-        if (elapsedDuration >= m_nextIterationDuration) {
-            // Set to the next iteration
-            double previous = m_nextIterationDuration;
-            double durationLeft = m_animation->duration() - fmod(elapsedDuration, m_animation->duration());
-            m_nextIterationDuration = elapsedDuration + durationLeft;
-
-            // Send the event
-            updateStateMachine(AnimationStateInputLoopTimerFired, previous);
-        }
-    }
-}
-
-void AnimationBase::updatePlayState(EAnimPlayState playState)
-{
-    if (!m_compAnim)
-        return;
-
-    // Set the state machine to the desired state.
-    bool pause = playState == AnimPlayStatePaused;
-
-    if (pause == paused() && !isNew())
-        return;
-
-    updateStateMachine(pause ?  AnimationStateInputPlayStatePaused : AnimationStateInputPlayStateRunning, -1);
-}
-
-double AnimationBase::timeToNextService()
-{
-    // Returns the time at which next service is required. -1 means no service is required. 0 means
-    // service is required now, and > 0 means service is required that many seconds in the future.
-    if (paused() || isNew() || m_animState == AnimationStateFillingForwards)
-        return -1;
-
-    if (m_animState == AnimationStateStartWaitTimer) {
-        double timeFromNow = m_animation->delay() - (beginAnimationUpdateTime() - m_requestedStartTime);
-        return max(timeFromNow, 0.0);
-    }
-
-    fireAnimationEventsIfNeeded();
-
-    // In all other cases, we need service right away.
-    return 0;
-}
-
-// Compute the fractional time, taking into account direction.
-// There is no need to worry about iterations, we assume that we would have
-// short circuited above if we were done.
-
-double AnimationBase::fractionalTime(double scale, double elapsedTime, double offset) const
-{
-    double fractionalTime = m_animation->duration() ? (elapsedTime / m_animation->duration()) : 1;
-    // FIXME: startTime can be before the current animation "frame" time. This is to sync with the frame time
-    // concept in AnimationTimeController. So we need to somehow sync the two. Until then, the possible
-    // error is small and will probably not be noticeable. Until we fix this, remove the assert.
-    // https://bugs.webkit.org/show_bug.cgi?id=52037
-    // ASSERT(fractionalTime >= 0);
-    if (fractionalTime < 0)
-        fractionalTime = 0;
-
-    int integralTime = static_cast<int>(fractionalTime);
-    const int integralIterationCount = static_cast<int>(m_animation->iterationCount());
-    const bool iterationCountHasFractional = m_animation->iterationCount() - integralIterationCount;
-    if (m_animation->iterationCount() != CSSAnimationData::IterationCountInfinite && !iterationCountHasFractional)
-        integralTime = min(integralTime, integralIterationCount - 1);
-
-    fractionalTime -= integralTime;
-
-    // Thie method can be called with an elapsedTime which very slightly
-    // exceeds the end of the animation. In this case, clamp the
-    // fractionalTime.
-    if (fractionalTime > 1)
-        fractionalTime = 1;
-    ASSERT(fractionalTime >= 0 && fractionalTime <= 1);
-
-    if (((m_animation->direction() == CSSAnimationData::AnimationDirectionAlternate) && (integralTime & 1))
-        || ((m_animation->direction() == CSSAnimationData::AnimationDirectionAlternateReverse) && !(integralTime & 1))
-        || m_animation->direction() == CSSAnimationData::AnimationDirectionReverse)
-        fractionalTime = 1 - fractionalTime;
-
-    fractionalTime -= offset;
-    // Note that if fractionalTime == 0 here, scale may be infinity, but in
-    // this case we don't need to apply scale anyway.
-    if (scale != 1.0 && fractionalTime) {
-        ASSERT(scale >= 0 && !std::isinf(scale));
-        fractionalTime *= scale;
-    }
-
-    ASSERT(fractionalTime >= 0 && fractionalTime <= 1);
-    return fractionalTime;
-}
-
-double AnimationBase::progress(double scale, double offset, const TimingFunction* timingFunction) const
-{
-    if (preActive())
-        return 0;
-
-    double dur = m_animation->duration();
-    if (m_animation->iterationCount() > 0)
-        dur *= m_animation->iterationCount();
-
-    if (postActive() || !m_animation->duration())
-        return 1.0;
-
-    double elapsedTime = getElapsedTime();
-    if (m_animation->iterationCount() > 0 && elapsedTime >= dur) {
-        const int integralIterationCount = static_cast<int>(m_animation->iterationCount());
-        const bool iterationCountHasFractional = m_animation->iterationCount() - integralIterationCount;
-        return (integralIterationCount % 2 || iterationCountHasFractional) ? 1.0 : 0.0;
-    }
-
-    const double fractionalTime = this->fractionalTime(scale, elapsedTime, offset);
-
-    if (!timingFunction)
-        timingFunction = m_animation->timingFunction();
-
-    return timingFunction->evaluate(fractionalTime, accuracyForDuration(m_animation->duration()));
-}
-
-void AnimationBase::getTimeToNextEvent(double& time, bool& isLooping) const
-{
-    if (postActive()) {
-        time = -1;
-        isLooping = false;
-        return;
-    }
-
-    // Decide when the end or loop event needs to fire
-    const double elapsedDuration = getElapsedTime();
-    double durationLeft = 0;
-    double nextIterationTime = m_totalDuration;
-
-    if (m_totalDuration < 0 || elapsedDuration < m_totalDuration) {
-        durationLeft = m_animation->duration() > 0 ? (m_animation->duration() - fmod(elapsedDuration, m_animation->duration())) : 0;
-        nextIterationTime = elapsedDuration + durationLeft;
-    }
-
-    if (m_totalDuration < 0 || nextIterationTime < m_totalDuration) {
-        // We are not at the end yet
-        ASSERT(m_totalDuration < 0 || nextIterationTime > 0);
-        isLooping = true;
-    } else {
-        // We are at the end
-        isLooping = false;
-    }
-
-    time = durationLeft;
-}
-
-void AnimationBase::goIntoEndingOrLoopingState()
-{
-    double t;
-    bool isLooping;
-    getTimeToNextEvent(t, isLooping);
-    m_animState = isLooping ? AnimationStateLooping : AnimationStateEnding;
-}
-
-void AnimationBase::freezeAtTime(double t)
-{
-    if (!m_compAnim)
-        return;
-
-    if (!m_startTime) {
-        // If we haven't started yet, make it as if we started.
-        m_animState = AnimationStateStartWaitResponse;
-        onAnimationStartResponse(beginAnimationUpdateTime());
-    }
-
-    ASSERT(m_startTime);        // if m_startTime is zero, we haven't started yet, so we'll get a bad pause time.
-    if (t <= m_animation->delay())
-        m_pauseTime = m_startTime;
-    else
-        m_pauseTime = m_startTime + t - m_animation->delay();
-
-    // It is possible that m_isAccelerated is true and m_object->compositingState() is NotComposited, because of style change.
-    // So, both conditions need to be checked.
-    if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
-        pauseAnimation(t);
-}
-
-double AnimationBase::beginAnimationUpdateTime() const
-{
-    if (!m_compAnim)
-        return 0;
-
-    return m_compAnim->animationController()->beginAnimationUpdateTime();
-}
-
-double AnimationBase::getElapsedTime() const
-{
-    ASSERT(!postActive());
-    if (paused())
-        return m_pauseTime - m_startTime;
-    if (m_startTime <= 0)
-        return 0;
-
-    double elapsedTime = beginAnimationUpdateTime() - m_startTime;
-    // It's possible for the start time to be ahead of the last update time
-    // if the compositor has just sent notification for the start of an
-    // accelerated animation.
-    return max(elapsedTime, 0.0);
-}
-
-} // namespace WebCore
diff --git a/Source/core/frame/animation/AnimationBase.h b/Source/core/frame/animation/AnimationBase.h
deleted file mode 100644
index 6ab1d58..0000000
--- a/Source/core/frame/animation/AnimationBase.h
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef AnimationBase_h
-#define AnimationBase_h
-
-#include "CSSPropertyNames.h"
-#include "core/platform/animation/CSSAnimationData.h"
-#include "core/rendering/style/RenderStyleConstants.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class AnimationBase;
-class AnimationController;
-class CompositeAnimation;
-class Element;
-class Node;
-class RenderObject;
-class RenderStyle;
-class TimingFunction;
-
-class AnimationBase : public RefCounted<AnimationBase> {
-    friend class CompositeAnimation;
-    friend class CSSPropertyAnimation;
-
-public:
-    AnimationBase(const CSSAnimationData* transition, RenderObject& renderer, CompositeAnimation* compAnim);
-    virtual ~AnimationBase() { }
-
-    RenderObject* renderer() const { return m_object; }
-    void clear()
-    {
-      endAnimation();
-      m_object = 0;
-      m_compAnim = 0;
-    }
-
-    double duration() const;
-
-    // Animations and Transitions go through the states below. When entering the STARTED state
-    // the animation is started. This may or may not require deferred response from the animator.
-    // If so, we stay in this state until that response is received (and it returns the start time).
-    // Otherwise, we use the current time as the start time and go immediately to AnimationStateLooping
-    // or AnimationStateEnding.
-    enum AnimState {
-        AnimationStateNew,                  // animation just created, animation not running yet
-        AnimationStateStartWaitTimer,       // start timer running, waiting for fire
-        AnimationStateStartWaitStyleAvailable,   // waiting for style setup so we can start animations
-        AnimationStateStartWaitResponse,    // animation started, waiting for response
-        AnimationStateLooping,              // response received, animation running, loop timer running, waiting for fire
-        AnimationStateEnding,               // received, animation running, end timer running, waiting for fire
-        AnimationStatePausedWaitTimer,      // in pause mode when animation started
-        AnimationStatePausedWaitStyleAvailable, // in pause mode when waiting for style setup
-        AnimationStatePausedWaitResponse,   // animation paused when in STARTING state
-        AnimationStatePausedRun,            // animation paused when in LOOPING or ENDING state
-        AnimationStateDone,                 // end timer fired, animation finished and removed
-        AnimationStateFillingForwards       // animation has ended and is retaining its final value
-    };
-
-    enum AnimStateInput {
-        AnimationStateInputMakeNew,           // reset back to new from any state
-        AnimationStateInputStartAnimation,    // animation requests a start
-        AnimationStateInputRestartAnimation,  // force a restart from any state
-        AnimationStateInputStartTimerFired,   // start timer fired
-        AnimationStateInputStyleAvailable,    // style is setup, ready to start animating
-        AnimationStateInputStartTimeSet,      // m_startTime was set
-        AnimationStateInputLoopTimerFired,    // loop timer fired
-        AnimationStateInputEndTimerFired,     // end timer fired
-        AnimationStateInputPauseOverride,     // pause an animation due to override
-        AnimationStateInputResumeOverride,    // resume an overridden animation
-        AnimationStateInputPlayStateRunning,  // play state paused -> running
-        AnimationStateInputPlayStatePaused,   // play state running -> paused
-        AnimationStateInputEndAnimation       // force an end from any state
-    };
-
-    // Called when animation is in AnimationStateNew to start animation
-    void updateStateMachine(AnimStateInput, double param);
-
-    // Animation has actually started, at passed time
-    void onAnimationStartResponse(double startTime)
-    {
-        updateStateMachine(AnimationBase::AnimationStateInputStartTimeSet, startTime);
-    }
-
-    // Called to change to or from paused state
-    void updatePlayState(EAnimPlayState);
-    bool playStatePlaying() const;
-
-    bool waitingToStart() const { return m_animState == AnimationStateNew || m_animState == AnimationStateStartWaitTimer; }
-    bool preActive() const
-    {
-        return m_animState == AnimationStateNew || m_animState == AnimationStateStartWaitTimer || m_animState == AnimationStateStartWaitStyleAvailable || m_animState == AnimationStateStartWaitResponse;
-    }
-
-    bool postActive() const { return m_animState == AnimationStateDone; }
-    bool active() const { return !postActive() && !preActive(); }
-    bool running() const { return !isNew() && !postActive(); }
-    bool paused() const { return m_pauseTime >= 0; }
-    bool isNew() const { return m_animState == AnimationStateNew; }
-    bool waitingForStartTime() const { return m_animState == AnimationStateStartWaitResponse; }
-    bool waitingForStyleAvailable() const { return m_animState == AnimationStateStartWaitStyleAvailable; }
-
-    virtual double timeToNextService();
-
-    double progress(double scale, double offset, const TimingFunction*) const;
-
-    virtual void animate(CompositeAnimation*, RenderObject*, const RenderStyle* /*currentStyle*/, RenderStyle* /*targetStyle*/, RefPtr<RenderStyle>& /*animatedStyle*/) = 0;
-    virtual void getAnimatedStyle(RefPtr<RenderStyle>& /*animatedStyle*/) = 0;
-
-    virtual bool shouldFireEvents() const { return false; }
-
-    void fireAnimationEventsIfNeeded();
-
-    void setAnimation(const CSSAnimationData* anim) { m_animation = const_cast<CSSAnimationData*>(anim); }
-
-    // Return true if this animation is overridden. This will only be the case for
-    // ImplicitAnimations and is used to determine whether or not we should force
-    // set the start time. If an animation is overridden, it will probably not get
-    // back the AnimationStateInputStartTimeSet input.
-    virtual bool overridden() const { return false; }
-
-    // Does this animation/transition involve the given property?
-    virtual bool affectsProperty(CSSPropertyID /*property*/) const { return false; }
-
-    bool isAnimatingProperty(CSSPropertyID property, bool acceleratedOnly, bool isRunningNow) const
-    {
-        if (acceleratedOnly && !m_isAccelerated)
-            return false;
-
-        if (isRunningNow)
-            return (!waitingToStart() && !postActive()) && affectsProperty(property);
-
-        return !postActive() && affectsProperty(property);
-    }
-
-    // FIXME: rename this using the "lists match" terminology.
-    bool isTransformFunctionListValid() const { return m_transformFunctionListValid; }
-    bool filterFunctionListsMatch() const { return m_filterFunctionListsMatch; }
-
-    // Freeze the animation; used by DumpRenderTree.
-    void freezeAtTime(double t);
-
-    double beginAnimationUpdateTime() const;
-
-    double getElapsedTime() const;
-
-    void styleAvailable()
-    {
-        ASSERT(waitingForStyleAvailable());
-        updateStateMachine(AnimationBase::AnimationStateInputStyleAvailable, -1);
-    }
-
-    const CSSAnimationData* animation() const { return m_animation.get(); }
-
-protected:
-    virtual void overrideAnimations() { }
-    virtual void resumeOverriddenAnimations() { }
-
-    CompositeAnimation* compositeAnimation() { return m_compAnim; }
-
-    // These are called when the corresponding timer fires so subclasses can do any extra work
-    virtual void onAnimationStart(double /*elapsedTime*/) { }
-    virtual void onAnimationIteration(double /*elapsedTime*/) { }
-    virtual void onAnimationEnd(double /*elapsedTime*/) { }
-
-    // timeOffset is an offset from the current time when the animation should start. Negative values are OK.
-    virtual void startAnimation(double /*timeOffset*/) { }
-    // timeOffset is the time at which the animation is being paused.
-    virtual void pauseAnimation(double /*timeOffset*/) { }
-    virtual void endAnimation() { }
-
-    void goIntoEndingOrLoopingState();
-
-    bool isAccelerated() const { return m_isAccelerated; }
-
-    static void setNeedsStyleRecalc(Node*);
-
-    void getTimeToNextEvent(double& time, bool& isLooping) const;
-
-    double fractionalTime(double scale, double elapsedTime, double offset) const;
-
-    AnimState m_animState;
-
-    bool m_isAccelerated;
-    bool m_transformFunctionListValid;
-    bool m_filterFunctionListsMatch;
-    double m_startTime;
-    double m_pauseTime;
-    double m_requestedStartTime;
-
-    double m_totalDuration;
-    double m_nextIterationDuration;
-
-    RenderObject* m_object;
-
-    RefPtr<CSSAnimationData> m_animation;
-    CompositeAnimation* m_compAnim;
-};
-
-} // namespace WebCore
-
-#endif // AnimationBase_h
diff --git a/Source/core/frame/animation/AnimationController.cpp b/Source/core/frame/animation/AnimationController.cpp
deleted file mode 100644
index 8521e13..0000000
--- a/Source/core/frame/animation/AnimationController.cpp
+++ /dev/null
@@ -1,542 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-#include "core/frame/animation/AnimationController.h"
-
-#include "core/dom/PseudoElement.h"
-#include "core/events/ThreadLocalEventNames.h"
-#include "core/events/TransitionEvent.h"
-#include "core/events/WebKitAnimationEvent.h"
-#include "core/frame/Frame.h"
-#include "core/frame/FrameView.h"
-#include "core/page/Page.h"
-#include "core/frame/animation/AnimationBase.h"
-#include "core/frame/animation/AnimationControllerPrivate.h"
-#include "core/frame/animation/CSSPropertyAnimation.h"
-#include "core/frame/animation/CompositeAnimation.h"
-#include "core/rendering/RenderView.h"
-#include "wtf/CurrentTime.h"
-
-namespace WebCore {
-
-static const double cBeginAnimationUpdateTimeNotSet = -1;
-
-AnimationControllerPrivate::AnimationControllerPrivate(Frame* frame)
-    : m_animationTimer(this, &AnimationControllerPrivate::animationTimerFired)
-    , m_updateStyleIfNeededDispatcher(this, &AnimationControllerPrivate::updateStyleIfNeededDispatcherFired)
-    , m_frame(frame)
-    , m_beginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet)
-    , m_animationsWaitingForStyle()
-    , m_animationsWaitingForStartTimeResponse()
-    , m_animationsWaitingForAsyncStartNotification()
-{
-}
-
-AnimationControllerPrivate::~AnimationControllerPrivate()
-{
-}
-
-PassRefPtr<CompositeAnimation> AnimationControllerPrivate::accessCompositeAnimation(RenderObject& renderer)
-{
-    RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(&renderer);
-    if (!animation) {
-        animation = CompositeAnimation::create(this);
-        m_compositeAnimations.set(&renderer, animation);
-    }
-    return animation;
-}
-
-bool AnimationControllerPrivate::clear(RenderObject* renderer)
-{
-    // Return false if we didn't do anything.
-    PassRefPtr<CompositeAnimation> animation = m_compositeAnimations.take(renderer);
-    if (!animation)
-        return false;
-    animation->clearRenderer();
-    return true;
-}
-
-void AnimationControllerPrivate::updateAnimations(double& timeToNextService, double& timeToNextEvent, SetNeedsStyleRecalc callSetNeedsStyleRecalc/* = DoNotCallSetNeedsStyleRecalc*/)
-{
-    double minTimeToNextService = -1;
-    double minTimeToNextEvent = -1;
-    bool updateStyleNeeded = false;
-
-    RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
-    for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
-        CompositeAnimation* compAnim = it->value.get();
-        if (compAnim->hasAnimations()) {
-            double t = compAnim->timeToNextService();
-            if (t != -1 && (t < minTimeToNextService || minTimeToNextService == -1))
-                minTimeToNextService = t;
-            double nextEvent = compAnim->timeToNextEvent();
-            if (nextEvent != -1 && (nextEvent < minTimeToNextEvent || minTimeToNextEvent == -1))
-                minTimeToNextEvent = nextEvent;
-            if (callSetNeedsStyleRecalc == CallSetNeedsStyleRecalc) {
-                if (!t) {
-                    Node* node = it->key->node();
-                    node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
-                    updateStyleNeeded = true;
-                }
-            } else if (!minTimeToNextService && !minTimeToNextEvent) {
-                // Found the minimum values and do not need to mark for style recalc.
-                break;
-            }
-        }
-    }
-
-    if (updateStyleNeeded)
-        m_frame->document()->updateStyleIfNeeded();
-
-    timeToNextService = minTimeToNextService;
-    timeToNextEvent = minTimeToNextEvent;
-}
-
-void AnimationControllerPrivate::scheduleServiceForRenderer(RenderObject& renderer)
-{
-    double timeToNextService = -1;
-    double timeToNextEvent = -1;
-
-    RefPtr<CompositeAnimation> compAnim = m_compositeAnimations.get(&renderer);
-    if (compAnim->hasAnimations()) {
-        timeToNextService = compAnim->timeToNextService();
-        timeToNextEvent = compAnim->timeToNextEvent();
-    }
-
-    if (timeToNextService >= 0)
-        scheduleService(timeToNextService, timeToNextEvent);
-}
-
-void AnimationControllerPrivate::scheduleService()
-{
-    double timeToNextService = -1;
-    double timeToNextEvent = -1;
-    updateAnimations(timeToNextService, timeToNextEvent, DoNotCallSetNeedsStyleRecalc);
-    scheduleService(timeToNextService, timeToNextEvent);
-}
-
-void AnimationControllerPrivate::scheduleService(double timeToNextService, double timeToNextEvent)
-{
-    if (!m_frame->page())
-        return;
-
-    bool visible = m_frame->page()->visibilityState() == WebCore::PageVisibilityStateVisible;
-
-    // This std::max to 1 second limits how often we service animations on background tabs.
-    // Without this, plus and gmail were recalculating style as every 200ms or even more
-    // often, burning CPU needlessly for background tabs.
-    // FIXME: Do we want to fire events at all on background tabs?
-    if (!visible)
-        timeToNextService = std::max(timeToNextEvent, 1.0);
-
-    if (visible && !timeToNextService) {
-        m_frame->document()->view()->scheduleAnimation();
-        if (m_animationTimer.isActive())
-            m_animationTimer.stop();
-        return;
-    }
-
-    if (timeToNextService < 0) {
-        if (m_animationTimer.isActive())
-            m_animationTimer.stop();
-        return;
-    }
-
-    if (m_animationTimer.isActive() && m_animationTimer.nextFireInterval() <= timeToNextService)
-        return;
-
-    m_animationTimer.startOneShot(timeToNextService);
-}
-
-void AnimationControllerPrivate::updateStyleIfNeededDispatcherFired(Timer<AnimationControllerPrivate>*)
-{
-    fireEventsAndUpdateStyle();
-}
-
-void AnimationControllerPrivate::fireEventsAndUpdateStyle()
-{
-    // Protect the frame from getting destroyed in the event handler
-    RefPtr<Frame> protector = m_frame;
-
-    bool updateStyle = !m_eventsToDispatch.isEmpty() || !m_nodeChangesToDispatch.isEmpty();
-
-    // fire all the events
-    Vector<EventToDispatch> eventsToDispatch = m_eventsToDispatch;
-    m_eventsToDispatch.clear();
-    Vector<EventToDispatch>::const_iterator eventsToDispatchEnd = eventsToDispatch.end();
-    for (Vector<EventToDispatch>::const_iterator it = eventsToDispatch.begin(); it != eventsToDispatchEnd; ++it) {
-        Element* element = it->element.get();
-        if (it->eventType == EventTypeNames::transitionend)
-            element->dispatchEvent(TransitionEvent::create(it->eventType, it->name, it->elapsedTime, PseudoElement::pseudoElementNameForEvents(element->pseudoId())));
-        else
-            element->dispatchEvent(WebKitAnimationEvent::create(it->eventType, it->name, it->elapsedTime));
-    }
-
-    // call setChanged on all the elements
-    Vector<RefPtr<Node> >::const_iterator nodeChangesToDispatchEnd = m_nodeChangesToDispatch.end();
-    for (Vector<RefPtr<Node> >::const_iterator it = m_nodeChangesToDispatch.begin(); it != nodeChangesToDispatchEnd; ++it)
-        (*it)->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
-
-    m_nodeChangesToDispatch.clear();
-
-    if (updateStyle && m_frame)
-        m_frame->document()->updateStyleIfNeeded();
-}
-
-void AnimationControllerPrivate::startUpdateStyleIfNeededDispatcher()
-{
-    if (!m_updateStyleIfNeededDispatcher.isActive())
-        m_updateStyleIfNeededDispatcher.startOneShot(0);
-}
-
-void AnimationControllerPrivate::addEventToDispatch(PassRefPtr<Element> element, const AtomicString& eventType, const String& name, double elapsedTime)
-{
-    m_eventsToDispatch.grow(m_eventsToDispatch.size()+1);
-    EventToDispatch& event = m_eventsToDispatch[m_eventsToDispatch.size()-1];
-    event.element = element;
-    event.eventType = eventType;
-    event.name = name;
-    event.elapsedTime = elapsedTime;
-
-    startUpdateStyleIfNeededDispatcher();
-}
-
-void AnimationControllerPrivate::addNodeChangeToDispatch(PassRefPtr<Node> node)
-{
-    if (!node)
-        return;
-
-    m_nodeChangesToDispatch.append(node);
-    startUpdateStyleIfNeededDispatcher();
-}
-
-void AnimationControllerPrivate::serviceAnimations()
-{
-    double timeToNextService = -1;
-    double timeToNextEvent = -1;
-    updateAnimations(timeToNextService, timeToNextEvent, CallSetNeedsStyleRecalc);
-    scheduleService(timeToNextService, timeToNextEvent);
-
-    // Fire events right away, to avoid a flash of unanimated style after an animation completes, and before
-    // the 'end' event fires.
-    fireEventsAndUpdateStyle();
-}
-
-void AnimationControllerPrivate::animationTimerFired(Timer<AnimationControllerPrivate>*)
-{
-    // Make sure animationUpdateTime is updated, so that it is current even if no
-    // styleChange has happened (e.g. accelerated animations)
-    setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
-    serviceAnimations();
-}
-
-bool AnimationControllerPrivate::isRunningAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
-{
-    RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
-    if (!animation)
-        return false;
-
-    return animation->isAnimatingProperty(property, false, isRunningNow);
-}
-
-bool AnimationControllerPrivate::isRunningAcceleratableAnimationOnRenderer(RenderObject *renderer) const
-{
-    RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
-    if (!animation)
-        return false;
-
-    bool acceleratedOnly = false;
-    bool isRunningNow = true;
-    return animation->isAnimatingProperty(CSSPropertyOpacity, acceleratedOnly, isRunningNow)
-        || animation->isAnimatingProperty(CSSPropertyWebkitTransform, acceleratedOnly, isRunningNow)
-        || animation->isAnimatingProperty(CSSPropertyWebkitFilter, acceleratedOnly, isRunningNow);
-}
-
-bool AnimationControllerPrivate::isRunningAcceleratedAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
-{
-    RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
-    if (!animation)
-        return false;
-
-    return animation->isAnimatingProperty(property, true, isRunningNow);
-}
-
-void AnimationControllerPrivate::pauseAnimationsForTesting(double t)
-{
-    RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
-    for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
-        it->value->pauseAnimationsForTesting(t);
-        it->key->node()->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
-    }
-}
-
-double AnimationControllerPrivate::beginAnimationUpdateTime()
-{
-    if (m_beginAnimationUpdateTime == cBeginAnimationUpdateTimeNotSet)
-        m_beginAnimationUpdateTime = currentTime();
-    return m_beginAnimationUpdateTime;
-}
-
-void AnimationControllerPrivate::endAnimationUpdate()
-{
-    styleAvailable();
-    if (m_animationsWaitingForAsyncStartNotification.isEmpty())
-        startTimeResponse(beginAnimationUpdateTime());
-}
-
-void AnimationControllerPrivate::receivedStartTimeResponse(double time)
-{
-    startTimeResponse(time);
-}
-
-PassRefPtr<RenderStyle> AnimationControllerPrivate::getAnimatedStyleForRenderer(RenderObject* renderer)
-{
-    if (!renderer)
-        return 0;
-
-    RefPtr<CompositeAnimation> rendererAnimations = m_compositeAnimations.get(renderer);
-    if (!rendererAnimations)
-        return renderer->style();
-
-    RefPtr<RenderStyle> animatingStyle = rendererAnimations->getAnimatedStyle();
-    if (!animatingStyle)
-        animatingStyle = renderer->style();
-
-    return animatingStyle.release();
-}
-
-unsigned AnimationControllerPrivate::numberOfActiveAnimations(Document* document) const
-{
-    unsigned count = 0;
-
-    RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
-    for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
-        RenderObject* renderer = it->key;
-        CompositeAnimation* compAnim = it->value.get();
-        if (renderer->document() == document)
-            count += compAnim->numberOfActiveAnimations();
-    }
-
-    return count;
-}
-
-void AnimationControllerPrivate::addToAnimationsWaitingForStyle(AnimationBase* animation)
-{
-    // Make sure this animation is not in the start time waiters
-    m_animationsWaitingForStartTimeResponse.remove(animation);
-    m_animationsWaitingForAsyncStartNotification.remove(animation);
-
-    m_animationsWaitingForStyle.add(animation);
-}
-
-void AnimationControllerPrivate::removeFromAnimationsWaitingForStyle(AnimationBase* animationToRemove)
-{
-    m_animationsWaitingForStyle.remove(animationToRemove);
-}
-
-void AnimationControllerPrivate::styleAvailable()
-{
-    // Go through list of waiters and send them on their way
-    WaitingAnimationsSet::const_iterator it = m_animationsWaitingForStyle.begin();
-    WaitingAnimationsSet::const_iterator end = m_animationsWaitingForStyle.end();
-    for (; it != end; ++it)
-        (*it)->styleAvailable();
-
-    m_animationsWaitingForStyle.clear();
-}
-
-void AnimationControllerPrivate::addToAnimationsWaitingForStartTimeResponse(AnimationBase* animation, bool willGetResponse)
-{
-    // If willGetResponse is true, it means this animation is actually waiting for a response
-    // (which will come in as a call to notifyAnimationStarted()).
-    // In that case we don't need to add it to this list. We just set a waitingForAResponse flag
-    // which says we are waiting for the response. If willGetResponse is false, this animation
-    // is not waiting for a response for itself, but rather for a notifyXXXStarted() call for
-    // another animation to which it will sync.
-    //
-    // When endAnimationUpdate() is called we check to see if the waitingForAResponse flag is
-    // true. If so, we just return and will do our work when the first notifyXXXStarted() call
-    // comes in. If it is false, we will not be getting a notifyXXXStarted() call, so we will
-    // do our work right away. In both cases we call the onAnimationStartResponse() method
-    // on each animation. In the first case we send in the time we got from notifyXXXStarted().
-    // In the second case, we just pass in the beginAnimationUpdateTime().
-    //
-    // This will synchronize all software and accelerated animations started in the same
-    // updateStyleIfNeeded cycle.
-    //
-
-    if (willGetResponse)
-        m_animationsWaitingForAsyncStartNotification.add(animation);
-
-    m_animationsWaitingForStartTimeResponse.add(animation);
-}
-
-void AnimationControllerPrivate::removeFromAnimationsWaitingForStartTimeResponse(AnimationBase* animationToRemove)
-{
-    m_animationsWaitingForStartTimeResponse.remove(animationToRemove);
-    m_animationsWaitingForAsyncStartNotification.remove(animationToRemove);
-}
-
-void AnimationControllerPrivate::startTimeResponse(double time)
-{
-    // Go through list of waiters and send them on their way
-
-    WaitingAnimationsSet::const_iterator it = m_animationsWaitingForStartTimeResponse.begin();
-    WaitingAnimationsSet::const_iterator end = m_animationsWaitingForStartTimeResponse.end();
-    for (; it != end; ++it)
-        (*it)->onAnimationStartResponse(time);
-
-    m_animationsWaitingForStartTimeResponse.clear();
-    m_animationsWaitingForAsyncStartNotification.clear();
-}
-
-void AnimationControllerPrivate::animationWillBeRemoved(AnimationBase* animation)
-{
-    removeFromAnimationsWaitingForStyle(animation);
-    removeFromAnimationsWaitingForStartTimeResponse(animation);
-}
-
-AnimationController::AnimationController(Frame* frame)
-    : m_data(adoptPtr(new AnimationControllerPrivate(frame)))
-    , m_beginAnimationUpdateCount(0)
-{
-}
-
-AnimationController::~AnimationController()
-{
-}
-
-void AnimationController::cancelAnimations(RenderObject* renderer)
-{
-    if (!m_data->hasAnimations())
-        return;
-
-    if (m_data->clear(renderer)) {
-        if (Node* node = renderer->node())
-            node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
-    }
-}
-
-PassRefPtr<RenderStyle> AnimationController::updateAnimations(RenderObject& renderer, RenderStyle& newStyle)
-{
-    RenderStyle* oldStyle = renderer.style();
-
-    if ((!oldStyle || (!oldStyle->animations() && !oldStyle->transitions())) && (!newStyle.animations() && !newStyle.transitions()))
-        return PassRefPtr<RenderStyle>(newStyle);
-
-    // Don't run transitions when printing.
-    if (renderer.view()->document().printing())
-        return PassRefPtr<RenderStyle>(newStyle);
-
-    // Fetch our current set of implicit animations from a hashtable.  We then compare them
-    // against the animations in the style and make sure we're in sync.  If destination values
-    // have changed, we reset the animation.  We then do a blend to get new values and we return
-    // a new style.
-
-    // We don't support anonymous pseudo elements like :first-line or :first-letter.
-    ASSERT(renderer.node());
-
-    RefPtr<CompositeAnimation> rendererAnimations = m_data->accessCompositeAnimation(renderer);
-    RefPtr<RenderStyle> blendedStyle = rendererAnimations->animate(renderer, oldStyle, newStyle);
-
-    if (renderer.parent() || newStyle.animations() || (oldStyle && oldStyle->animations())) {
-        m_data->scheduleServiceForRenderer(renderer);
-    }
-
-    if (blendedStyle != &newStyle) {
-        // If the animations/transitions change opacity or transform, we need to update
-        // the style to impose the stacking rules. Note that this is also
-        // done in StyleResolver::adjustRenderStyle().
-        if (blendedStyle->hasAutoZIndex() && (blendedStyle->opacity() < 1.0f || blendedStyle->hasTransform()))
-            blendedStyle->setZIndex(0);
-    }
-    return blendedStyle.release();
-}
-
-PassRefPtr<RenderStyle> AnimationController::getAnimatedStyleForRenderer(RenderObject* renderer)
-{
-    return m_data->getAnimatedStyleForRenderer(renderer);
-}
-
-void AnimationController::notifyAnimationStarted(RenderObject*, double startTime)
-{
-    m_data->receivedStartTimeResponse(startTime);
-}
-
-void AnimationController::pauseAnimationsForTesting(double t)
-{
-    m_data->pauseAnimationsForTesting(t);
-}
-
-unsigned AnimationController::numberOfActiveAnimations(Document* document) const
-{
-    return m_data->numberOfActiveAnimations(document);
-}
-
-bool AnimationController::isRunningAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
-{
-    return m_data->isRunningAnimationOnRenderer(renderer, property, isRunningNow);
-}
-
-bool AnimationController::isRunningAcceleratableAnimationOnRenderer(RenderObject* renderer) const
-{
-    return m_data->isRunningAcceleratableAnimationOnRenderer(renderer);
-}
-
-bool AnimationController::isRunningAcceleratedAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
-{
-    return m_data->isRunningAcceleratedAnimationOnRenderer(renderer, property, isRunningNow);
-}
-
-void AnimationController::serviceAnimations()
-{
-    m_data->serviceAnimations();
-}
-
-void AnimationController::beginAnimationUpdate()
-{
-    if (!m_beginAnimationUpdateCount)
-        m_data->setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
-    ++m_beginAnimationUpdateCount;
-}
-
-void AnimationController::endAnimationUpdate()
-{
-    ASSERT(m_beginAnimationUpdateCount > 0);
-    --m_beginAnimationUpdateCount;
-    if (!m_beginAnimationUpdateCount)
-        m_data->endAnimationUpdate();
-}
-
-bool AnimationController::supportsAcceleratedAnimationOfProperty(CSSPropertyID property)
-{
-    return CSSPropertyAnimation::animationOfPropertyIsAccelerated(property);
-}
-
-} // namespace WebCore
diff --git a/Source/core/frame/animation/AnimationController.h b/Source/core/frame/animation/AnimationController.h
deleted file mode 100644
index 01cf326..0000000
--- a/Source/core/frame/animation/AnimationController.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef AnimationController_h
-#define AnimationController_h
-
-#include "CSSPropertyNames.h"
-#include "wtf/Forward.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-class AnimationBase;
-class AnimationControllerPrivate;
-class Document;
-class Element;
-class Frame;
-class Node;
-class RenderObject;
-class RenderStyle;
-
-class AnimationController {
-public:
-    AnimationController(Frame*);
-    ~AnimationController();
-
-    void cancelAnimations(RenderObject*);
-    PassRefPtr<RenderStyle> updateAnimations(RenderObject&, RenderStyle& newStyle);
-    PassRefPtr<RenderStyle> getAnimatedStyleForRenderer(RenderObject*);
-
-    // This is called when an accelerated animation or transition has actually started to animate.
-    void notifyAnimationStarted(RenderObject*, double startTime);
-
-    void pauseAnimationsForTesting(double t);
-    unsigned numberOfActiveAnimations(Document*) const; // To be used only for testing
-
-    bool isRunningAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow = true) const;
-    bool isRunningAcceleratableAnimationOnRenderer(RenderObject*) const;
-    bool isRunningAcceleratedAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow = true) const;
-
-    void serviceAnimations();
-
-    void beginAnimationUpdate();
-    void endAnimationUpdate();
-
-    static bool supportsAcceleratedAnimationOfProperty(CSSPropertyID);
-
-private:
-    OwnPtr<AnimationControllerPrivate> m_data;
-    int m_beginAnimationUpdateCount;
-};
-
-class AnimationUpdateBlock {
-public:
-    explicit AnimationUpdateBlock(AnimationController* animationController)
-        : m_animationController(animationController)
-    {
-        if (m_animationController)
-            m_animationController->beginAnimationUpdate();
-    }
-
-    explicit AnimationUpdateBlock(AnimationController& animationController)
-        : m_animationController(&animationController)
-    {
-        m_animationController->beginAnimationUpdate();
-    }
-
-    ~AnimationUpdateBlock()
-    {
-        if (m_animationController)
-            m_animationController->endAnimationUpdate();
-    }
-
-    AnimationController* m_animationController;
-};
-
-} // namespace WebCore
-
-#endif // AnimationController_h
diff --git a/Source/core/frame/animation/AnimationControllerPrivate.h b/Source/core/frame/animation/AnimationControllerPrivate.h
deleted file mode 100644
index 671ec89..0000000
--- a/Source/core/frame/animation/AnimationControllerPrivate.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef AnimationControllerPrivate_h
-#define AnimationControllerPrivate_h
-
-#include "CSSPropertyNames.h"
-#include "platform/Timer.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class AnimationBase;
-class CompositeAnimation;
-class Document;
-class Element;
-class Frame;
-class Node;
-class RenderObject;
-class RenderStyle;
-
-enum SetNeedsStyleRecalc {
-    DoNotCallSetNeedsStyleRecalc = 0,
-    CallSetNeedsStyleRecalc = 1
-};
-
-class AnimationControllerPrivate {
-    WTF_MAKE_NONCOPYABLE(AnimationControllerPrivate); WTF_MAKE_FAST_ALLOCATED;
-public:
-    AnimationControllerPrivate(Frame*);
-    ~AnimationControllerPrivate();
-
-    void updateAnimations(double& timeToNextService, double& timeToNextEvent, SetNeedsStyleRecalc callSetNeedsStyleRecalc = DoNotCallSetNeedsStyleRecalc);
-    void scheduleService();
-
-    PassRefPtr<CompositeAnimation> accessCompositeAnimation(RenderObject&);
-    bool clear(RenderObject*);
-
-    void updateStyleIfNeededDispatcherFired(Timer<AnimationControllerPrivate>*);
-    void startUpdateStyleIfNeededDispatcher();
-    void addEventToDispatch(PassRefPtr<Element> element, const AtomicString& eventType, const String& name, double elapsedTime);
-    void addNodeChangeToDispatch(PassRefPtr<Node>);
-
-    bool hasAnimations() const { return !m_compositeAnimations.isEmpty(); }
-
-    void serviceAnimations();
-
-    bool isRunningAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow) const;
-    bool isRunningAcceleratableAnimationOnRenderer(RenderObject*) const;
-    bool isRunningAcceleratedAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow) const;
-
-    void pauseAnimationsForTesting(double t);
-    unsigned numberOfActiveAnimations(Document*) const;
-
-    PassRefPtr<RenderStyle> getAnimatedStyleForRenderer(RenderObject* renderer);
-
-    double beginAnimationUpdateTime();
-    void setBeginAnimationUpdateTime(double t) { m_beginAnimationUpdateTime = t; }
-    void endAnimationUpdate();
-    void receivedStartTimeResponse(double);
-
-    void addToAnimationsWaitingForStyle(AnimationBase*);
-    void removeFromAnimationsWaitingForStyle(AnimationBase*);
-
-    void addToAnimationsWaitingForStartTimeResponse(AnimationBase*, bool willGetResponse);
-    void removeFromAnimationsWaitingForStartTimeResponse(AnimationBase*);
-
-    void animationWillBeRemoved(AnimationBase*);
-
-    void scheduleServiceForRenderer(RenderObject&);
-
-private:
-    void animationTimerFired(Timer<AnimationControllerPrivate>*);
-
-    void scheduleService(double timeToNextService, double timeToNextEvent);
-
-    void styleAvailable();
-    void fireEventsAndUpdateStyle();
-    void startTimeResponse(double t);
-
-    typedef HashMap<RenderObject*, RefPtr<CompositeAnimation> > RenderObjectAnimationMap;
-
-    RenderObjectAnimationMap m_compositeAnimations;
-    Timer<AnimationControllerPrivate> m_animationTimer;
-    Timer<AnimationControllerPrivate> m_updateStyleIfNeededDispatcher;
-    Frame* m_frame;
-
-    class EventToDispatch {
-    public:
-        RefPtr<Element> element;
-        AtomicString eventType;
-        String name;
-        double elapsedTime;
-    };
-
-    Vector<EventToDispatch> m_eventsToDispatch;
-    Vector<RefPtr<Node> > m_nodeChangesToDispatch;
-
-    double m_beginAnimationUpdateTime;
-
-    typedef HashSet<RefPtr<AnimationBase> > WaitingAnimationsSet;
-    WaitingAnimationsSet m_animationsWaitingForStyle;
-    WaitingAnimationsSet m_animationsWaitingForStartTimeResponse;
-    WaitingAnimationsSet m_animationsWaitingForAsyncStartNotification;
-};
-
-} // namespace WebCore
-
-#endif // AnimationControllerPrivate_h
diff --git a/Source/core/frame/animation/CSSPropertyAnimation.cpp b/Source/core/frame/animation/CSSPropertyAnimation.cpp
deleted file mode 100644
index 4d07ebf..0000000
--- a/Source/core/frame/animation/CSSPropertyAnimation.cpp
+++ /dev/null
@@ -1,1153 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2012 Adobe Systems Incorporated. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-#include "core/frame/animation/CSSPropertyAnimation.h"
-
-#include <algorithm>
-#include "StylePropertyShorthand.h"
-#include "core/animation/css/CSSAnimations.h"
-#include "core/css/CSSCrossfadeValue.h"
-#include "core/css/CSSImageValue.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/fetch/ImageResource.h"
-#include "core/frame/animation/AnimationBase.h"
-#include "core/rendering/ClipPathOperation.h"
-#include "core/rendering/RenderBox.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/ShadowList.h"
-#include "core/rendering/style/StyleFetchedImage.h"
-#include "core/rendering/style/StyleGeneratedImage.h"
-#include "platform/FloatConversion.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-template <typename T>
-static inline T blendFunc(const AnimationBase*, T from, T to, double progress)
-{
-    return blend(from, to, progress);
-}
-
-static inline float blendFunc(const AnimationBase*, float from, float to, double progress)
-{
-    return narrowPrecisionToFloat(from + (to - from) * progress);
-}
-
-static inline Color blendFunc(const AnimationBase*, const Color& from, const Color& to, double progress)
-{
-    return blend(from, to, progress);
-}
-
-static inline Length blendFunc(const AnimationBase*, const Length& from, const Length& to, double progress)
-{
-    return to.blend(from, progress, ValueRangeAll);
-}
-
-static inline BorderImageLength blendFunc(const AnimationBase* anim, const BorderImageLength& from, const BorderImageLength& to, double progress)
-{
-    if (from.isNumber() && to.isNumber())
-        return BorderImageLength(blendFunc(anim, from.number(), to.number(), progress));
-
-    if (from.isLength() && to.isLength())
-        return BorderImageLength(blendFunc(anim, from.length(), to.length(), progress));
-
-    // FIXME: Converting numbers to lengths using the computed border
-    // width would make it possible to interpolate between numbers and
-    // lengths.
-    // https://code.google.com/p/chromium/issues/detail?id=316164
-    return to;
-}
-
-static inline BorderImageLengthBox blendFunc(const AnimationBase* anim, const BorderImageLengthBox& from,
-    const BorderImageLengthBox& to, double progress)
-{
-    return BorderImageLengthBox(blendFunc(anim, from.top(), to.top(), progress),
-        blendFunc(anim, from.right(), to.right(), progress),
-        blendFunc(anim, from.bottom(), to.bottom(), progress),
-        blendFunc(anim, from.left(), to.left(), progress));
-}
-
-static inline LengthSize blendFunc(const AnimationBase* anim, const LengthSize& from, const LengthSize& to, double progress)
-{
-    return LengthSize(blendFunc(anim, from.width(), to.width(), progress),
-        blendFunc(anim, from.height(), to.height(), progress));
-}
-
-static inline LengthPoint blendFunc(const AnimationBase* anim, const LengthPoint& from, const LengthPoint& to, double progress)
-{
-    return LengthPoint(blendFunc(anim, from.x(), to.x(), progress), blendFunc(anim, from.y(), to.y(), progress));
-}
-
-static inline TransformOperations blendFunc(const AnimationBase* anim, const TransformOperations& from, const TransformOperations& to, double progress)
-{
-    if (anim->isTransformFunctionListValid())
-        return to.blendByMatchingOperations(from, progress);
-    return to.blendByUsingMatrixInterpolation(from, progress);
-}
-
-static inline PassRefPtr<ClipPathOperation> blendFunc(const AnimationBase*, ClipPathOperation* from, ClipPathOperation* to, double progress)
-{
-    // Other clip-path operations than BasicShapes can not be animated.
-    if (!from || !to || from->type() != ClipPathOperation::SHAPE || to->type() != ClipPathOperation::SHAPE)
-        return to;
-
-    const BasicShape* fromShape = toShapeClipPathOperation(from)->basicShape();
-    const BasicShape* toShape = toShapeClipPathOperation(to)->basicShape();
-
-    if (!fromShape->canBlend(toShape))
-        return to;
-
-    return ShapeClipPathOperation::create(toShape->blend(fromShape, progress));
-}
-
-static inline PassRefPtr<ShapeValue> blendFunc(const AnimationBase*, ShapeValue* from, ShapeValue* to, double progress)
-{
-    // FIXME Bug 102723: Shape-inside should be able to animate a value of 'outside-shape' when shape-outside is set to a BasicShape
-    if (!from || !to || from->type() != ShapeValue::Shape || to->type() != ShapeValue::Shape)
-        return to;
-
-    const BasicShape* fromShape = from->shape();
-    const BasicShape* toShape = to->shape();
-
-    if (!fromShape->canBlend(toShape))
-        return to;
-
-    return ShapeValue::createShapeValue(toShape->blend(fromShape, progress));
-}
-
-static inline FilterOperations blendFunc(const AnimationBase* anim, const FilterOperations& from, const FilterOperations& to, double progress)
-{
-    FilterOperations result;
-
-    // If we have a filter function list, use that to do a per-function animation.
-    if (anim->filterFunctionListsMatch()) {
-        size_t fromSize = from.operations().size();
-        size_t toSize = to.operations().size();
-        size_t size = max(fromSize, toSize);
-        for (size_t i = 0; i < size; i++) {
-            const FilterOperation* fromOp = (i < fromSize) ? from.operations()[i].get() : 0;
-            const FilterOperation* toOp = (i < toSize) ? to.operations()[i].get() : 0;
-            RefPtr<FilterOperation> blendedOp = FilterOperation::blend(fromOp, toOp, progress);
-            if (blendedOp)
-                result.operations().append(blendedOp);
-            else
-                ASSERT_NOT_REACHED();
-        }
-    } else {
-        // If the filter function lists don't match, we could try to cross-fade, but don't yet have a way to represent that in CSS.
-        // For now we'll just fail to animate.
-        result = to;
-    }
-
-    return result;
-}
-
-static inline EVisibility blendFunc(const AnimationBase* anim, EVisibility from, EVisibility to, double progress)
-{
-    // Any non-zero result means we consider the object to be visible. Only at 0 do we consider the object to be
-    // invisible. The invisible value we use (HIDDEN vs. COLLAPSE) depends on the specified from/to values.
-    double fromVal = from == VISIBLE ? 1. : 0.;
-    double toVal = to == VISIBLE ? 1. : 0.;
-    if (fromVal == toVal)
-        return to;
-    double result = blendFunc(anim, fromVal, toVal, progress);
-    return result > 0. ? VISIBLE : (to != VISIBLE ? to : from);
-}
-
-static inline LengthBox blendFunc(const AnimationBase* anim, const LengthBox& from, const LengthBox& to, double progress)
-{
-    // Length types have to match to animate
-    if (from.top().type() != to.top().type()
-        || from.right().type() != to.right().type()
-        || from.bottom().type() != to.bottom().type()
-        || from.left().type() != to.left().type())
-        return to;
-
-    LengthBox result(blendFunc(anim, from.top(), to.top(), progress),
-                     blendFunc(anim, from.right(), to.right(), progress),
-                     blendFunc(anim, from.bottom(), to.bottom(), progress),
-                     blendFunc(anim, from.left(), to.left(), progress));
-    return result;
-}
-
-static inline SVGLength blendFunc(const AnimationBase*, const SVGLength& from, const SVGLength& to, double progress)
-{
-    return to.blend(from, narrowPrecisionToFloat(progress));
-}
-
-static inline Vector<SVGLength> blendFunc(const AnimationBase*, const Vector<SVGLength>& from, const Vector<SVGLength>& to, double progress)
-{
-    size_t fromLength = from.size();
-    size_t toLength = to.size();
-    if (!fromLength)
-        return !progress ? from : to;
-    if (!toLength)
-        return progress == 1 ? from : to;
-
-    size_t resultLength = fromLength;
-    if (fromLength != toLength) {
-        if (!(fromLength % toLength))
-            resultLength = fromLength;
-        else if (!(toLength % fromLength))
-            resultLength = toLength;
-        else
-            resultLength = fromLength * toLength;
-    }
-    Vector<SVGLength> result(resultLength);
-    for (size_t i = 0; i < resultLength; ++i)
-        result[i] = to[i % toLength].blend(from[i % fromLength], narrowPrecisionToFloat(progress));
-    return result;
-}
-
-static inline PassRefPtr<StyleImage> crossfadeBlend(const AnimationBase*, StyleFetchedImage* fromStyleImage, StyleFetchedImage* toStyleImage, double progress)
-{
-    // If progress is at one of the extremes, we want getComputedStyle to show the image,
-    // not a completed cross-fade, so we hand back one of the existing images.
-    if (!progress)
-        return fromStyleImage;
-    if (progress == 1)
-        return toStyleImage;
-
-    ImageResource* fromImageResource = static_cast<ImageResource*>(fromStyleImage->data());
-    ImageResource* toImageResource = static_cast<ImageResource*>(toStyleImage->data());
-
-    RefPtr<CSSImageValue> fromImageValue = CSSImageValue::create(fromImageResource->url(), fromStyleImage);
-    RefPtr<CSSImageValue> toImageValue = CSSImageValue::create(toImageResource->url(), toStyleImage);
-    RefPtr<CSSCrossfadeValue> crossfadeValue = CSSCrossfadeValue::create(fromImageValue, toImageValue);
-
-    crossfadeValue->setPercentage(CSSPrimitiveValue::create(progress, CSSPrimitiveValue::CSS_NUMBER));
-
-    return StyleGeneratedImage::create(crossfadeValue.get());
-}
-
-static inline PassRefPtr<StyleImage> blendFunc(const AnimationBase* anim, StyleImage* from, StyleImage* to, double progress)
-{
-    if (!from || !to)
-        return to;
-
-    if (from->isImageResource() && to->isImageResource())
-        return crossfadeBlend(anim, toStyleFetchedImage(from), toStyleFetchedImage(to), progress);
-
-    // FIXME: Support transitioning generated images as well. (gradients, etc.)
-
-    return to;
-}
-
-class AnimationPropertyWrapperBase {
-    WTF_MAKE_NONCOPYABLE(AnimationPropertyWrapperBase);
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    AnimationPropertyWrapperBase(CSSPropertyID prop)
-        : m_prop(prop)
-    {
-    }
-
-    virtual ~AnimationPropertyWrapperBase() { }
-
-    virtual bool isShorthandWrapper() const { return false; }
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const = 0;
-    virtual void blend(const AnimationBase*, RenderStyle*, const RenderStyle*, const RenderStyle*, double) const = 0;
-
-    CSSPropertyID property() const { return m_prop; }
-
-    virtual bool animationIsAccelerated() const { return false; }
-
-private:
-    CSSPropertyID m_prop;
-};
-
-static int gPropertyWrapperMap[numCSSProperties];
-static const int cInvalidPropertyWrapperIndex = -1;
-static Vector<AnimationPropertyWrapperBase*>* gPropertyWrappers = 0;
-
-static void addPropertyWrapper(CSSPropertyID propertyID, AnimationPropertyWrapperBase* wrapper)
-{
-    int propIndex = propertyID - firstCSSProperty;
-
-    ASSERT(gPropertyWrapperMap[propIndex] == cInvalidPropertyWrapperIndex);
-
-    unsigned wrapperIndex = gPropertyWrappers->size();
-    gPropertyWrappers->append(wrapper);
-    gPropertyWrapperMap[propIndex] = wrapperIndex;
-}
-
-static AnimationPropertyWrapperBase* wrapperForProperty(CSSPropertyID propertyID)
-{
-    int propIndex = propertyID - firstCSSProperty;
-    if (propIndex >= 0 && propIndex < numCSSProperties) {
-        int wrapperIndex = gPropertyWrapperMap[propIndex];
-        if (wrapperIndex >= 0)
-            return (*gPropertyWrappers)[wrapperIndex];
-    }
-    return 0;
-}
-
-template <typename T>
-class PropertyWrapperGetter : public AnimationPropertyWrapperBase {
-public:
-    PropertyWrapperGetter(CSSPropertyID prop, T (RenderStyle::*getter)() const)
-        : AnimationPropertyWrapperBase(prop)
-        , m_getter(getter)
-    {
-    }
-
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
-    {
-        // If the style pointers are the same, don't bother doing the test.
-        // If either is null, return false. If both are null, return true.
-        if ((!a && !b) || a == b)
-            return true;
-        if (!a || !b)
-            return false;
-        return (a->*m_getter)() == (b->*m_getter)();
-    }
-
-protected:
-    T (RenderStyle::*m_getter)() const;
-};
-
-template <typename T>
-class PropertyWrapper : public PropertyWrapperGetter<T> {
-public:
-    PropertyWrapper(CSSPropertyID prop, T (RenderStyle::*getter)() const, void (RenderStyle::*setter)(T))
-        : PropertyWrapperGetter<T>(prop, getter)
-        , m_setter(setter)
-    {
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<T>::m_getter)(), (b->*PropertyWrapperGetter<T>::m_getter)(), progress));
-    }
-
-protected:
-    void (RenderStyle::*m_setter)(T);
-};
-
-class NonNegativeLengthWrapper : public PropertyWrapper<Length> {
-public:
-    NonNegativeLengthWrapper(CSSPropertyID prop, Length (RenderStyle::*getter)() const, void (RenderStyle::*setter)(Length))
-    : PropertyWrapper<Length>(prop, getter, setter)
-    {
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        Length from = (a->*PropertyWrapperGetter<Length>::m_getter)();
-        Length to = (b->*PropertyWrapperGetter<Length>::m_getter)();
-        (dst->*PropertyWrapper<Length>::m_setter)(to.blend(from, progress, ValueRangeNonNegative));
-    }
-};
-
-template <typename T>
-class RefCountedPropertyWrapper : public PropertyWrapperGetter<T*> {
-public:
-    RefCountedPropertyWrapper(CSSPropertyID prop, T* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<T>))
-        : PropertyWrapperGetter<T*>(prop, getter)
-        , m_setter(setter)
-    {
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<T*>::m_getter)(), (b->*PropertyWrapperGetter<T*>::m_getter)(), progress));
-    }
-
-protected:
-    void (RenderStyle::*m_setter)(PassRefPtr<T>);
-};
-
-
-class PropertyWrapperClipPath : public RefCountedPropertyWrapper<ClipPathOperation> {
-public:
-    PropertyWrapperClipPath(CSSPropertyID prop, ClipPathOperation* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ClipPathOperation>))
-        : RefCountedPropertyWrapper<ClipPathOperation>(prop, getter, setter)
-    {
-    }
-};
-
-class PropertyWrapperShape : public RefCountedPropertyWrapper<ShapeValue> {
-public:
-    PropertyWrapperShape(CSSPropertyID prop, ShapeValue* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ShapeValue>))
-        : RefCountedPropertyWrapper<ShapeValue>(prop, getter, setter)
-    {
-    }
-};
-
-class StyleImagePropertyWrapper : public RefCountedPropertyWrapper<StyleImage> {
-public:
-    StyleImagePropertyWrapper(CSSPropertyID prop, StyleImage* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<StyleImage>))
-        : RefCountedPropertyWrapper<StyleImage>(prop, getter, setter)
-    {
-    }
-
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
-    {
-       // If the style pointers are the same, don't bother doing the test.
-       // If either is null, return false. If both are null, return true.
-       if (a == b)
-           return true;
-       if (!a || !b)
-            return false;
-
-        StyleImage* imageA = (a->*m_getter)();
-        StyleImage* imageB = (b->*m_getter)();
-        return StyleImage::imagesEquivalent(imageA, imageB);
-    }
-};
-
-class PropertyWrapperColor : public PropertyWrapperGetter<Color> {
-public:
-    PropertyWrapperColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
-        : PropertyWrapperGetter<Color>(prop, getter)
-        , m_setter(setter)
-    {
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<Color>::m_getter)(), (b->*PropertyWrapperGetter<Color>::m_getter)(), progress));
-    }
-
-protected:
-    void (RenderStyle::*m_setter)(const Color&);
-};
-
-class PropertyWrapperAcceleratedOpacity : public PropertyWrapper<float> {
-public:
-    PropertyWrapperAcceleratedOpacity()
-        : PropertyWrapper<float>(CSSPropertyOpacity, &RenderStyle::opacity, &RenderStyle::setOpacity)
-    {
-    }
-
-    virtual bool animationIsAccelerated() const { return true; }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        float fromOpacity = a->opacity();
-
-        // This makes sure we put the object being animated into a RenderLayer during the animation
-        dst->setOpacity(blendFunc(anim, (fromOpacity == 1) ? 0.999999f : fromOpacity, b->opacity(), progress));
-    }
-};
-
-class PropertyWrapperAcceleratedTransform : public PropertyWrapper<const TransformOperations&> {
-public:
-    PropertyWrapperAcceleratedTransform()
-        : PropertyWrapper<const TransformOperations&>(CSSPropertyWebkitTransform, &RenderStyle::transform, &RenderStyle::setTransform)
-    {
-    }
-
-    virtual bool animationIsAccelerated() const { return true; }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        dst->setTransform(blendFunc(anim, a->transform(), b->transform(), progress));
-    }
-};
-
-class PropertyWrapperAcceleratedFilter : public PropertyWrapper<const FilterOperations&> {
-public:
-    PropertyWrapperAcceleratedFilter()
-        : PropertyWrapper<const FilterOperations&>(CSSPropertyWebkitFilter, &RenderStyle::filter, &RenderStyle::setFilter)
-    {
-    }
-
-    virtual bool animationIsAccelerated() const { return true; }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        dst->setFilter(blendFunc(anim, a->filter(), b->filter(), progress));
-    }
-};
-
-class PropertyWrapperShadow : public AnimationPropertyWrapperBase {
-public:
-    PropertyWrapperShadow(CSSPropertyID prop, ShadowList* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ShadowList>))
-        : AnimationPropertyWrapperBase(prop)
-        , m_getter(getter)
-        , m_setter(setter)
-    {
-    }
-
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
-    {
-        const ShadowList* shadowA = (a->*m_getter)();
-        const ShadowList* shadowB = (b->*m_getter)();
-        if (shadowA == shadowB)
-            return true;
-        if (shadowA && shadowB)
-            return *shadowA == *shadowB;
-        return false;
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        (dst->*m_setter)(ShadowList::blend((a->*m_getter)(), (b->*m_getter)(), progress));
-    }
-
-    ShadowList* (RenderStyle::*m_getter)() const;
-    void (RenderStyle::*m_setter)(PassRefPtr<ShadowList>);
-};
-
-class PropertyWrapperMaybeInvalidColor : public AnimationPropertyWrapperBase {
-public:
-    PropertyWrapperMaybeInvalidColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
-        : AnimationPropertyWrapperBase(prop)
-        , m_getter(getter)
-        , m_setter(setter)
-    {
-    }
-
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
-    {
-        Color fromColor = (a->*m_getter)();
-        Color toColor = (b->*m_getter)();
-
-        if (!fromColor.isValid() && !toColor.isValid())
-            return true;
-
-        if (!fromColor.isValid())
-            fromColor = a->color();
-        if (!toColor.isValid())
-            toColor = b->color();
-
-        return fromColor == toColor;
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        Color fromColor = (a->*m_getter)();
-        Color toColor = (b->*m_getter)();
-
-        if (!fromColor.isValid() && !toColor.isValid())
-            return;
-
-        if (!fromColor.isValid())
-            fromColor = a->color();
-        if (!toColor.isValid())
-            toColor = b->color();
-        (dst->*m_setter)(blendFunc(anim, fromColor, toColor, progress));
-    }
-
-private:
-    Color (RenderStyle::*m_getter)() const;
-    void (RenderStyle::*m_setter)(const Color&);
-};
-
-
-enum MaybeInvalidColorTag { MaybeInvalidColor };
-class PropertyWrapperVisitedAffectedColor : public AnimationPropertyWrapperBase {
-public:
-    PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&),
-        Color (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const Color&))
-        : AnimationPropertyWrapperBase(prop)
-        , m_wrapper(adoptPtr(new PropertyWrapperColor(prop, getter, setter)))
-        , m_visitedWrapper(adoptPtr(new PropertyWrapperColor(prop, visitedGetter, visitedSetter)))
-    {
-    }
-    PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, MaybeInvalidColorTag, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&),
-        Color (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const Color&))
-        : AnimationPropertyWrapperBase(prop)
-        , m_wrapper(adoptPtr(new PropertyWrapperMaybeInvalidColor(prop, getter, setter)))
-        , m_visitedWrapper(adoptPtr(new PropertyWrapperMaybeInvalidColor(prop, visitedGetter, visitedSetter)))
-    {
-    }
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
-    {
-        return m_wrapper->equals(a, b) && m_visitedWrapper->equals(a, b);
-    }
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        m_wrapper->blend(anim, dst, a, b, progress);
-        m_visitedWrapper->blend(anim, dst, a, b, progress);
-    }
-
-private:
-    OwnPtr<AnimationPropertyWrapperBase> m_wrapper;
-    OwnPtr<AnimationPropertyWrapperBase> m_visitedWrapper;
-};
-
-// Wrapper base class for an animatable property in a FillLayer
-class FillLayerAnimationPropertyWrapperBase {
-public:
-    FillLayerAnimationPropertyWrapperBase()
-    {
-    }
-
-    virtual ~FillLayerAnimationPropertyWrapperBase() { }
-
-    virtual bool equals(const FillLayer*, const FillLayer*) const = 0;
-    virtual void blend(const AnimationBase*, FillLayer*, const FillLayer*, const FillLayer*, double) const = 0;
-};
-
-template <typename T>
-class FillLayerPropertyWrapperGetter : public FillLayerAnimationPropertyWrapperBase {
-    WTF_MAKE_NONCOPYABLE(FillLayerPropertyWrapperGetter);
-public:
-    FillLayerPropertyWrapperGetter(T (FillLayer::*getter)() const)
-        : m_getter(getter)
-    {
-    }
-
-    virtual bool equals(const FillLayer* a, const FillLayer* b) const
-    {
-       // If the style pointers are the same, don't bother doing the test.
-       // If either is null, return false. If both are null, return true.
-       if ((!a && !b) || a == b)
-           return true;
-       if (!a || !b)
-            return false;
-        return (a->*m_getter)() == (b->*m_getter)();
-    }
-
-protected:
-    T (FillLayer::*m_getter)() const;
-};
-
-template <typename T>
-class FillLayerPropertyWrapper : public FillLayerPropertyWrapperGetter<T> {
-public:
-    FillLayerPropertyWrapper(T (FillLayer::*getter)() const, void (FillLayer::*setter)(T))
-        : FillLayerPropertyWrapperGetter<T>(getter)
-        , m_setter(setter)
-    {
-    }
-
-    virtual void blend(const AnimationBase* anim, FillLayer* dst, const FillLayer* a, const FillLayer* b, double progress) const
-    {
-        (dst->*m_setter)(blendFunc(anim, (a->*FillLayerPropertyWrapperGetter<T>::m_getter)(), (b->*FillLayerPropertyWrapperGetter<T>::m_getter)(), progress));
-    }
-
-protected:
-    void (FillLayer::*m_setter)(T);
-};
-
-template <typename T>
-class FillLayerRefCountedPropertyWrapper : public FillLayerPropertyWrapperGetter<T*> {
-public:
-    FillLayerRefCountedPropertyWrapper(T* (FillLayer::*getter)() const, void (FillLayer::*setter)(PassRefPtr<T>))
-        : FillLayerPropertyWrapperGetter<T*>(getter)
-        , m_setter(setter)
-    {
-    }
-
-    virtual void blend(const AnimationBase* anim, FillLayer* dst, const FillLayer* a, const FillLayer* b, double progress) const
-    {
-        (dst->*m_setter)(blendFunc(anim, (a->*FillLayerPropertyWrapperGetter<T*>::m_getter)(), (b->*FillLayerPropertyWrapperGetter<T*>::m_getter)(), progress));
-    }
-
-protected:
-    void (FillLayer::*m_setter)(PassRefPtr<T>);
-};
-
-class FillLayerStyleImagePropertyWrapper : public FillLayerRefCountedPropertyWrapper<StyleImage> {
-public:
-    FillLayerStyleImagePropertyWrapper(StyleImage* (FillLayer::*getter)() const, void (FillLayer::*setter)(PassRefPtr<StyleImage>))
-        : FillLayerRefCountedPropertyWrapper<StyleImage>(getter, setter)
-    {
-    }
-
-    virtual bool equals(const FillLayer* a, const FillLayer* b) const
-    {
-       // If the style pointers are the same, don't bother doing the test.
-       // If either is null, return false. If both are null, return true.
-       if (a == b)
-           return true;
-       if (!a || !b)
-            return false;
-
-        StyleImage* imageA = (a->*m_getter)();
-        StyleImage* imageB = (b->*m_getter)();
-        return StyleImage::imagesEquivalent(imageA, imageB);
-    }
-};
-
-
-class FillLayersPropertyWrapper : public AnimationPropertyWrapperBase {
-public:
-    typedef const FillLayer* (RenderStyle::*LayersGetter)() const;
-    typedef FillLayer* (RenderStyle::*LayersAccessor)();
-
-    FillLayersPropertyWrapper(CSSPropertyID prop, LayersGetter getter, LayersAccessor accessor)
-        : AnimationPropertyWrapperBase(prop)
-        , m_layersGetter(getter)
-        , m_layersAccessor(accessor)
-    {
-        switch (prop) {
-        case CSSPropertyBackgroundPositionX:
-        case CSSPropertyWebkitMaskPositionX:
-            m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<Length>(&FillLayer::xPosition, &FillLayer::setXPosition);
-            break;
-        case CSSPropertyBackgroundPositionY:
-        case CSSPropertyWebkitMaskPositionY:
-            m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<Length>(&FillLayer::yPosition, &FillLayer::setYPosition);
-            break;
-        case CSSPropertyBackgroundSize:
-        case CSSPropertyWebkitBackgroundSize:
-        case CSSPropertyWebkitMaskSize:
-            m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<LengthSize>(&FillLayer::sizeLength, &FillLayer::setSizeLength);
-            break;
-        case CSSPropertyBackgroundImage:
-            m_fillLayerPropertyWrapper = new FillLayerStyleImagePropertyWrapper(&FillLayer::image, &FillLayer::setImage);
-            break;
-        default:
-            break;
-        }
-    }
-
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
-    {
-        const FillLayer* fromLayer = (a->*m_layersGetter)();
-        const FillLayer* toLayer = (b->*m_layersGetter)();
-
-        while (fromLayer && toLayer) {
-            if (!m_fillLayerPropertyWrapper->equals(fromLayer, toLayer))
-                return false;
-
-            fromLayer = fromLayer->next();
-            toLayer = toLayer->next();
-        }
-
-        return true;
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        const FillLayer* aLayer = (a->*m_layersGetter)();
-        const FillLayer* bLayer = (b->*m_layersGetter)();
-        FillLayer* dstLayer = (dst->*m_layersAccessor)();
-
-        while (aLayer && bLayer && dstLayer) {
-            m_fillLayerPropertyWrapper->blend(anim, dstLayer, aLayer, bLayer, progress);
-            aLayer = aLayer->next();
-            bLayer = bLayer->next();
-            dstLayer = dstLayer->next();
-        }
-    }
-
-private:
-    FillLayerAnimationPropertyWrapperBase* m_fillLayerPropertyWrapper;
-
-    LayersGetter m_layersGetter;
-    LayersAccessor m_layersAccessor;
-};
-
-class ShorthandPropertyWrapper : public AnimationPropertyWrapperBase {
-public:
-    ShorthandPropertyWrapper(CSSPropertyID property, const StylePropertyShorthand& shorthand)
-        : AnimationPropertyWrapperBase(property)
-    {
-        for (unsigned i = 0; i < shorthand.length(); ++i) {
-            AnimationPropertyWrapperBase* wrapper = wrapperForProperty(shorthand.properties()[i]);
-            if (wrapper)
-                m_propertyWrappers.append(wrapper);
-        }
-    }
-
-    virtual bool isShorthandWrapper() const { return true; }
-
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
-    {
-        Vector<AnimationPropertyWrapperBase*>::const_iterator end = m_propertyWrappers.end();
-        for (Vector<AnimationPropertyWrapperBase*>::const_iterator it = m_propertyWrappers.begin(); it != end; ++it) {
-            if (!(*it)->equals(a, b))
-                return false;
-        }
-        return true;
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        Vector<AnimationPropertyWrapperBase*>::const_iterator end = m_propertyWrappers.end();
-        for (Vector<AnimationPropertyWrapperBase*>::const_iterator it = m_propertyWrappers.begin(); it != end; ++it)
-            (*it)->blend(anim, dst, a, b, progress);
-    }
-
-    const Vector<AnimationPropertyWrapperBase*> propertyWrappers() const { return m_propertyWrappers; }
-
-private:
-    Vector<AnimationPropertyWrapperBase*> m_propertyWrappers;
-};
-
-class PropertyWrapperFlex : public AnimationPropertyWrapperBase {
-public:
-    PropertyWrapperFlex()
-        : AnimationPropertyWrapperBase(CSSPropertyFlex)
-    {
-    }
-
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
-    {
-        // If the style pointers are the same, don't bother doing the test.
-        // If either is null, return false. If both are null, return true.
-        if ((!a && !b) || a == b)
-            return true;
-        if (!a || !b)
-            return false;
-
-        return a->flexBasis() == b->flexBasis() && a->flexGrow() == b->flexGrow() && a->flexShrink() == b->flexShrink();
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        dst->setFlexBasis(blendFunc(anim, a->flexBasis(), b->flexBasis(), progress));
-        dst->setFlexGrow(blendFunc(anim, a->flexGrow(), b->flexGrow(), progress));
-        dst->setFlexShrink(blendFunc(anim, a->flexShrink(), b->flexShrink(), progress));
-    }
-};
-
-class PropertyWrapperSVGPaint : public AnimationPropertyWrapperBase {
-public:
-    PropertyWrapperSVGPaint(CSSPropertyID prop, const SVGPaint::SVGPaintType& (RenderStyle::*paintTypeGetter)() const, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
-        : AnimationPropertyWrapperBase(prop)
-        , m_paintTypeGetter(paintTypeGetter)
-        , m_getter(getter)
-        , m_setter(setter)
-    {
-    }
-
-    virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
-    {
-        if ((a->*m_paintTypeGetter)() != (b->*m_paintTypeGetter)())
-            return false;
-
-        // We only support animations between SVGPaints that are pure Color values.
-        // For everything else we must return true for this method, otherwise
-        // we will try to animate between values forever.
-        if ((a->*m_paintTypeGetter)() == SVGPaint::SVG_PAINTTYPE_RGBCOLOR) {
-            Color fromColor = (a->*m_getter)();
-            Color toColor = (b->*m_getter)();
-
-            if (!fromColor.isValid() && !toColor.isValid())
-                return true;
-
-            if (!fromColor.isValid())
-                fromColor = Color();
-            if (!toColor.isValid())
-                toColor = Color();
-
-            return fromColor == toColor;
-        }
-        return true;
-    }
-
-    virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
-    {
-        if ((a->*m_paintTypeGetter)() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR
-            || (b->*m_paintTypeGetter)() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR)
-            return;
-
-        Color fromColor = (a->*m_getter)();
-        Color toColor = (b->*m_getter)();
-
-        if (!fromColor.isValid() && !toColor.isValid())
-            return;
-
-        if (!fromColor.isValid())
-            fromColor = Color();
-        if (!toColor.isValid())
-            toColor = Color();
-        (dst->*m_setter)(blendFunc(anim, fromColor, toColor, progress));
-    }
-
-private:
-    const SVGPaint::SVGPaintType& (RenderStyle::*m_paintTypeGetter)() const;
-    Color (RenderStyle::*m_getter)() const;
-    void (RenderStyle::*m_setter)(const Color&);
-};
-
-static void addShorthandProperties()
-{
-    static const CSSPropertyID animatableShorthandProperties[] = {
-        CSSPropertyBackground, // for background-color, background-position, background-image
-        CSSPropertyBackgroundPosition,
-        CSSPropertyFont, // for font-size, font-weight
-        CSSPropertyWebkitMask, // for mask-position
-        CSSPropertyWebkitMaskPosition,
-        CSSPropertyBorderTop, CSSPropertyBorderRight, CSSPropertyBorderBottom, CSSPropertyBorderLeft,
-        CSSPropertyBorderColor,
-        CSSPropertyBorderRadius,
-        CSSPropertyBorderWidth,
-        CSSPropertyBorder,
-        CSSPropertyBorderImage,
-        CSSPropertyBorderSpacing,
-        CSSPropertyListStyle, // for list-style-image
-        CSSPropertyMargin,
-        CSSPropertyOutline,
-        CSSPropertyPadding,
-        CSSPropertyWebkitTextStroke,
-        CSSPropertyWebkitColumnRule,
-        CSSPropertyWebkitBorderRadius,
-        CSSPropertyWebkitTransformOrigin
-    };
-
-    for (size_t i = 0; i < WTF_ARRAY_LENGTH(animatableShorthandProperties); ++i) {
-        CSSPropertyID propertyID = animatableShorthandProperties[i];
-        StylePropertyShorthand shorthand = shorthandForProperty(propertyID);
-        if (shorthand.length() > 0)
-            addPropertyWrapper(propertyID, new ShorthandPropertyWrapper(propertyID, shorthand));
-    }
-}
-
-void CSSPropertyAnimation::ensurePropertyMap()
-{
-    // FIXME: This data is never destroyed. Maybe we should ref count it and toss it when the last AnimationController is destroyed?
-    if (gPropertyWrappers)
-        return;
-
-    gPropertyWrappers = new Vector<AnimationPropertyWrapperBase*>();
-
-    // build the list of property wrappers to do the comparisons and blends
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyLeft, &RenderStyle::left, &RenderStyle::setLeft));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyRight, &RenderStyle::right, &RenderStyle::setRight));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyTop, &RenderStyle::top, &RenderStyle::setTop));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyBottom, &RenderStyle::bottom, &RenderStyle::setBottom));
-
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWidth, &RenderStyle::width, &RenderStyle::setWidth));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMinWidth, &RenderStyle::minWidth, &RenderStyle::setMinWidth));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMaxWidth, &RenderStyle::maxWidth, &RenderStyle::setMaxWidth));
-
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyHeight, &RenderStyle::height, &RenderStyle::setHeight));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMinHeight, &RenderStyle::minHeight, &RenderStyle::setMinHeight));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMaxHeight, &RenderStyle::maxHeight, &RenderStyle::setMaxHeight));
-
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-        gPropertyWrappers->append(new PropertyWrapperFlex());
-
-    gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderLeftWidth, &RenderStyle::borderLeftWidth, &RenderStyle::setBorderLeftWidth));
-    gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderRightWidth, &RenderStyle::borderRightWidth, &RenderStyle::setBorderRightWidth));
-    gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderTopWidth, &RenderStyle::borderTopWidth, &RenderStyle::setBorderTopWidth));
-    gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderBottomWidth, &RenderStyle::borderBottomWidth, &RenderStyle::setBorderBottomWidth));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginLeft, &RenderStyle::marginLeft, &RenderStyle::setMarginLeft));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginRight, &RenderStyle::marginRight, &RenderStyle::setMarginRight));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginTop, &RenderStyle::marginTop, &RenderStyle::setMarginTop));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginBottom, &RenderStyle::marginBottom, &RenderStyle::setMarginBottom));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingLeft, &RenderStyle::paddingLeft, &RenderStyle::setPaddingLeft));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingRight, &RenderStyle::paddingRight, &RenderStyle::setPaddingRight));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingTop, &RenderStyle::paddingTop, &RenderStyle::setPaddingTop));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingBottom, &RenderStyle::paddingBottom, &RenderStyle::setPaddingBottom));
-    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyColor, &RenderStyle::color, &RenderStyle::setColor, &RenderStyle::visitedLinkColor, &RenderStyle::setVisitedLinkColor));
-
-    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBackgroundColor, &RenderStyle::backgroundColor, &RenderStyle::setBackgroundColor, &RenderStyle::visitedLinkBackgroundColor, &RenderStyle::setVisitedLinkBackgroundColor));
-
-    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundImage, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
-    gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyListStyleImage, &RenderStyle::listStyleImage, &RenderStyle::setListStyleImage));
-    gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyWebkitMaskImage, &RenderStyle::maskImage, &RenderStyle::setMaskImage));
-
-    gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyBorderImageSource, &RenderStyle::borderImageSource, &RenderStyle::setBorderImageSource));
-    gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyBorderImageSlice, &RenderStyle::borderImageSlices, &RenderStyle::setBorderImageSlices));
-    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyBorderImageWidth, &RenderStyle::borderImageWidth, &RenderStyle::setBorderImageWidth));
-    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyBorderImageOutset, &RenderStyle::borderImageOutset, &RenderStyle::setBorderImageOutset));
-
-    gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyWebkitMaskBoxImageSource, &RenderStyle::maskBoxImageSource, &RenderStyle::setMaskBoxImageSource));
-    gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyWebkitMaskBoxImageSlice, &RenderStyle::maskBoxImageSlices, &RenderStyle::setMaskBoxImageSlices));
-    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyWebkitMaskBoxImageWidth, &RenderStyle::maskBoxImageWidth, &RenderStyle::setMaskBoxImageWidth));
-    gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyWebkitMaskBoxImageOutset, &RenderStyle::maskBoxImageOutset, &RenderStyle::setMaskBoxImageOutset));
-
-    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionX, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
-    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionY, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
-    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundSize, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
-    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitBackgroundSize, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
-
-    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskPositionX, &RenderStyle::maskLayers, &RenderStyle::accessMaskLayers));
-    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskPositionY, &RenderStyle::maskLayers, &RenderStyle::accessMaskLayers));
-    gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskSize, &RenderStyle::maskLayers, &RenderStyle::accessMaskLayers));
-
-    gPropertyWrappers->append(new PropertyWrapper<LengthPoint>(CSSPropertyObjectPosition, &RenderStyle::objectPosition, &RenderStyle::setObjectPosition));
-
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFontSize,
-        // Must pass a specified size to setFontSize if Text Autosizing is enabled, but a computed size
-        // if text zoom is enabled (if neither is enabled it's irrelevant as they're probably the same).
-        // FIXME: Should we introduce an option to pass the computed font size here, allowing consumers to
-        // enable text zoom rather than Text Autosizing? See http://crbug.com/227545.
-        &RenderStyle::specifiedFontSize,
-        &RenderStyle::setFontSize));
-    gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyWebkitColumnRuleWidth, &RenderStyle::columnRuleWidth, &RenderStyle::setColumnRuleWidth));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitColumnGap, &RenderStyle::columnGap, &RenderStyle::setColumnGap));
-    gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyWebkitColumnCount, &RenderStyle::columnCount, &RenderStyle::setColumnCount));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitColumnWidth, &RenderStyle::columnWidth, &RenderStyle::setColumnWidth));
-    gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWebkitBorderHorizontalSpacing, &RenderStyle::horizontalBorderSpacing, &RenderStyle::setHorizontalBorderSpacing));
-    gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWebkitBorderVerticalSpacing, &RenderStyle::verticalBorderSpacing, &RenderStyle::setVerticalBorderSpacing));
-    gPropertyWrappers->append(new PropertyWrapper<int>(CSSPropertyZIndex, &RenderStyle::zIndex, &RenderStyle::setZIndex));
-    gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyOrphans, &RenderStyle::orphans, &RenderStyle::setOrphans));
-    gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWidows, &RenderStyle::widows, &RenderStyle::setWidows));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyLineHeight, &RenderStyle::specifiedLineHeight, &RenderStyle::setLineHeight));
-    gPropertyWrappers->append(new PropertyWrapper<int>(CSSPropertyOutlineOffset, &RenderStyle::outlineOffset, &RenderStyle::setOutlineOffset));
-    gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyOutlineWidth, &RenderStyle::outlineWidth, &RenderStyle::setOutlineWidth));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyLetterSpacing, &RenderStyle::letterSpacing, &RenderStyle::setLetterSpacing));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWordSpacing, &RenderStyle::wordSpacing, &RenderStyle::setWordSpacing));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyTextIndent, &RenderStyle::textIndent, &RenderStyle::setTextIndent));
-
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitPerspective, &RenderStyle::perspective, &RenderStyle::setPerspective));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitPerspectiveOriginX, &RenderStyle::perspectiveOriginX, &RenderStyle::setPerspectiveOriginX));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitPerspectiveOriginY, &RenderStyle::perspectiveOriginY, &RenderStyle::setPerspectiveOriginY));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitTransformOriginX, &RenderStyle::transformOriginX, &RenderStyle::setTransformOriginX));
-    gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitTransformOriginY, &RenderStyle::transformOriginY, &RenderStyle::setTransformOriginY));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitTransformOriginZ, &RenderStyle::transformOriginZ, &RenderStyle::setTransformOriginZ));
-    gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderTopLeftRadius, &RenderStyle::borderTopLeftRadius, &RenderStyle::setBorderTopLeftRadius));
-    gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderTopRightRadius, &RenderStyle::borderTopRightRadius, &RenderStyle::setBorderTopRightRadius));
-    gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderBottomLeftRadius, &RenderStyle::borderBottomLeftRadius, &RenderStyle::setBorderBottomLeftRadius));
-    gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderBottomRightRadius, &RenderStyle::borderBottomRightRadius, &RenderStyle::setBorderBottomRightRadius));
-    gPropertyWrappers->append(new PropertyWrapper<EVisibility>(CSSPropertyVisibility, &RenderStyle::visibility, &RenderStyle::setVisibility));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyZoom, &RenderStyle::zoom, &RenderStyle::setZoomWithoutReturnValue));
-
-    gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyClip, &RenderStyle::clip, &RenderStyle::setClip));
-
-    gPropertyWrappers->append(new PropertyWrapperAcceleratedOpacity());
-    gPropertyWrappers->append(new PropertyWrapperAcceleratedTransform());
-    gPropertyWrappers->append(new PropertyWrapperAcceleratedFilter());
-
-    gPropertyWrappers->append(new PropertyWrapperClipPath(CSSPropertyWebkitClipPath, &RenderStyle::clipPath, &RenderStyle::setClipPath));
-
-    gPropertyWrappers->append(new PropertyWrapperShape(CSSPropertyShapeInside, &RenderStyle::shapeInside, &RenderStyle::setShapeInside));
-    gPropertyWrappers->append(new PropertyWrapperShape(CSSPropertyShapeOutside, &RenderStyle::shapeOutside, &RenderStyle::setShapeOutside));
-    gPropertyWrappers->append(new NonNegativeLengthWrapper(CSSPropertyShapeMargin, &RenderStyle::shapeMargin, &RenderStyle::setShapeMargin));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyShapeImageThreshold, &RenderStyle::shapeImageThreshold, &RenderStyle::setShapeImageThreshold));
-
-    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitColumnRuleColor, MaybeInvalidColor, &RenderStyle::columnRuleColor, &RenderStyle::setColumnRuleColor, &RenderStyle::visitedLinkColumnRuleColor, &RenderStyle::setVisitedLinkColumnRuleColor));
-    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitTextStrokeColor, MaybeInvalidColor, &RenderStyle::textStrokeColor, &RenderStyle::setTextStrokeColor, &RenderStyle::visitedLinkTextStrokeColor, &RenderStyle::setVisitedLinkTextStrokeColor));
-    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderLeftColor, MaybeInvalidColor, &RenderStyle::borderLeftColor, &RenderStyle::setBorderLeftColor, &RenderStyle::visitedLinkBorderLeftColor, &RenderStyle::setVisitedLinkBorderLeftColor));
-    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderRightColor, MaybeInvalidColor, &RenderStyle::borderRightColor, &RenderStyle::setBorderRightColor, &RenderStyle::visitedLinkBorderRightColor, &RenderStyle::setVisitedLinkBorderRightColor));
-    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderTopColor, MaybeInvalidColor, &RenderStyle::borderTopColor, &RenderStyle::setBorderTopColor, &RenderStyle::visitedLinkBorderTopColor, &RenderStyle::setVisitedLinkBorderTopColor));
-    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderBottomColor, MaybeInvalidColor, &RenderStyle::borderBottomColor, &RenderStyle::setBorderBottomColor, &RenderStyle::visitedLinkBorderBottomColor, &RenderStyle::setVisitedLinkBorderBottomColor));
-    gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyOutlineColor, MaybeInvalidColor, &RenderStyle::outlineColor, &RenderStyle::setOutlineColor, &RenderStyle::visitedLinkOutlineColor, &RenderStyle::setVisitedLinkOutlineColor));
-
-    gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyBoxShadow, &RenderStyle::boxShadow, &RenderStyle::setBoxShadow));
-    gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyWebkitBoxShadow, &RenderStyle::boxShadow, &RenderStyle::setBoxShadow));
-    gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyTextShadow, &RenderStyle::textShadow, &RenderStyle::setTextShadow));
-
-    gPropertyWrappers->append(new PropertyWrapperSVGPaint(CSSPropertyFill, &RenderStyle::fillPaintType, &RenderStyle::fillPaintColor, &RenderStyle::setFillPaintColor));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFillOpacity, &RenderStyle::fillOpacity, &RenderStyle::setFillOpacity));
-
-    gPropertyWrappers->append(new PropertyWrapperSVGPaint(CSSPropertyStroke, &RenderStyle::strokePaintType, &RenderStyle::strokePaintColor, &RenderStyle::setStrokePaintColor));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeOpacity, &RenderStyle::strokeOpacity, &RenderStyle::setStrokeOpacity));
-    gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyStrokeWidth, &RenderStyle::strokeWidth, &RenderStyle::setStrokeWidth));
-    gPropertyWrappers->append(new PropertyWrapper< Vector<SVGLength> >(CSSPropertyStrokeDasharray, &RenderStyle::strokeDashArray, &RenderStyle::setStrokeDashArray));
-    gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyStrokeDashoffset, &RenderStyle::strokeDashOffset, &RenderStyle::setStrokeDashOffset));
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeMiterlimit, &RenderStyle::strokeMiterLimit, &RenderStyle::setStrokeMiterLimit));
-
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFloodOpacity, &RenderStyle::floodOpacity, &RenderStyle::setFloodOpacity));
-    gPropertyWrappers->append(new PropertyWrapperMaybeInvalidColor(CSSPropertyFloodColor, &RenderStyle::floodColor, &RenderStyle::setFloodColor));
-
-    gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStopOpacity, &RenderStyle::stopOpacity, &RenderStyle::setStopOpacity));
-    gPropertyWrappers->append(new PropertyWrapperMaybeInvalidColor(CSSPropertyStopColor, &RenderStyle::stopColor, &RenderStyle::setStopColor));
-
-    gPropertyWrappers->append(new PropertyWrapperMaybeInvalidColor(CSSPropertyLightingColor, &RenderStyle::lightingColor, &RenderStyle::setLightingColor));
-
-    gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyBaselineShift, &RenderStyle::baselineShiftValue, &RenderStyle::setBaselineShiftValue));
-    gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyKerning, &RenderStyle::kerning, &RenderStyle::setKerning));
-
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
-        gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFlexGrow, &RenderStyle::flexGrow, &RenderStyle::setFlexGrow));
-        gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFlexShrink, &RenderStyle::flexShrink, &RenderStyle::setFlexShrink));
-        gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyFlexBasis, &RenderStyle::flexBasis, &RenderStyle::setFlexBasis));
-    }
-
-    // TODO:
-    //
-    //  CSSPropertyVerticalAlign
-    //
-    // Compound properties that have components that should be animatable:
-    //
-    //  CSSPropertyWebkitColumns
-    //  CSSPropertyWebkitBoxReflect
-
-    // Make sure unused slots have a value
-    for (unsigned int i = 0; i < static_cast<unsigned int>(numCSSProperties); ++i)
-        gPropertyWrapperMap[i] = cInvalidPropertyWrapperIndex;
-
-    // First we put the non-shorthand property wrappers into the map, so the shorthand-building
-    // code can find them.
-    size_t n = gPropertyWrappers->size();
-    for (unsigned int i = 0; i < n; ++i) {
-        CSSPropertyID property = (*gPropertyWrappers)[i]->property();
-        ASSERT_WITH_MESSAGE(RuntimeEnabledFeatures::webAnimationsCSSEnabled() || CSSAnimations::isAnimatableProperty(property), "%s is not whitelisted for animation", getPropertyNameString(property).utf8().data());
-        ASSERT(property - firstCSSProperty < numCSSProperties);
-        gPropertyWrapperMap[property - firstCSSProperty] = i;
-    }
-
-    // Now add the shorthand wrappers.
-    addShorthandProperties();
-}
-
-// Returns true if we need to start animation timers
-bool CSSPropertyAnimation::blendProperties(const AnimationBase* anim, CSSPropertyID prop, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress)
-{
-    ASSERT(prop != CSSPropertyInvalid);
-
-    ensurePropertyMap();
-
-    AnimationPropertyWrapperBase* wrapper = wrapperForProperty(prop);
-    if (wrapper) {
-        wrapper->blend(anim, dst, a, b, progress);
-        return !wrapper->animationIsAccelerated() || !anim->isAccelerated();
-    }
-
-    return false;
-}
-
-bool CSSPropertyAnimation::animationOfPropertyIsAccelerated(CSSPropertyID prop)
-{
-    ensurePropertyMap();
-    AnimationPropertyWrapperBase* wrapper = wrapperForProperty(prop);
-    return wrapper ? wrapper->animationIsAccelerated() : false;
-}
-
-bool CSSPropertyAnimation::propertiesEqual(CSSPropertyID prop, const RenderStyle* a, const RenderStyle* b)
-{
-    ensurePropertyMap();
-
-    AnimationPropertyWrapperBase* wrapper = wrapperForProperty(prop);
-    if (wrapper)
-        return wrapper->equals(a, b);
-    return true;
-}
-
-CSSPropertyID CSSPropertyAnimation::getPropertyAtIndex(int i, bool& isShorthand)
-{
-    ensurePropertyMap();
-
-    if (i < 0 || i >= getNumProperties())
-        return CSSPropertyInvalid;
-
-    AnimationPropertyWrapperBase* wrapper = (*gPropertyWrappers)[i];
-    isShorthand = wrapper->isShorthandWrapper();
-    return wrapper->property();
-}
-
-int CSSPropertyAnimation::getNumProperties()
-{
-    ensurePropertyMap();
-
-    return gPropertyWrappers->size();
-}
-
-}
diff --git a/Source/core/frame/animation/CompositeAnimation.cpp b/Source/core/frame/animation/CompositeAnimation.cpp
deleted file mode 100644
index f20f685..0000000
--- a/Source/core/frame/animation/CompositeAnimation.cpp
+++ /dev/null
@@ -1,510 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-#include "core/frame/animation/CompositeAnimation.h"
-
-#include "CSSPropertyNames.h"
-#include "core/frame/animation/AnimationControllerPrivate.h"
-#include "core/frame/animation/CSSPropertyAnimation.h"
-#include "core/rendering/style/RenderStyle.h"
-
-namespace WebCore {
-
-CompositeAnimation::~CompositeAnimation()
-{
-    // Toss the refs to all animations, but make sure we remove them from
-    // any waiting lists first.
-
-    clearRenderer();
-    m_transitions.clear();
-    m_keyframeAnimations.clear();
-}
-
-void CompositeAnimation::clearRenderer()
-{
-    if (!m_transitions.isEmpty()) {
-        // Clear the renderers from all running animations, in case we are in the middle of
-        // an animation callback (see https://bugs.webkit.org/show_bug.cgi?id=22052)
-        CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
-        for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
-            ImplicitAnimation* transition = it->value.get();
-            animationController()->animationWillBeRemoved(transition);
-            transition->clear();
-        }
-    }
-    if (!m_keyframeAnimations.isEmpty()) {
-        AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
-        for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
-            KeyframeAnimation* anim = it->value.get();
-            animationController()->animationWillBeRemoved(anim);
-            anim->clear();
-        }
-    }
-}
-
-void CompositeAnimation::updateTransitions(RenderObject& renderer, RenderStyle* currentStyle, RenderStyle& targetStyle)
-{
-    // If currentStyle is null or there are no old or new transitions, just skip it
-    if (!currentStyle || (!targetStyle.transitions() && m_transitions.isEmpty()))
-        return;
-
-    // Mark all existing transitions as no longer active. We will mark the still active ones
-    // in the next loop and then toss the ones that didn't get marked.
-    CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
-    for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it)
-        it->value->setActive(false);
-
-    RefPtr<RenderStyle> modifiedCurrentStyle;
-
-    // Check to see if we need to update the active transitions
-    if (targetStyle.transitions()) {
-        for (size_t i = 0; i < targetStyle.transitions()->size(); ++i) {
-            const CSSAnimationData* anim = targetStyle.transitions()->animation(i);
-            bool isActiveTransition = anim->duration() || anim->delay() > 0;
-
-            CSSAnimationData::AnimationMode mode = anim->animationMode();
-            if (mode == CSSAnimationData::AnimateNone)
-                continue;
-
-            CSSPropertyID prop = anim->property();
-
-            bool all = mode == CSSAnimationData::AnimateAll;
-
-            // Handle both the 'all' and single property cases. For the single prop case, we make only one pass
-            // through the loop.
-            for (int propertyIndex = 0; propertyIndex < CSSPropertyAnimation::getNumProperties(); ++propertyIndex) {
-                if (all) {
-                    // Get the next property which is not a shorthand.
-                    bool isShorthand;
-                    prop = CSSPropertyAnimation::getPropertyAtIndex(propertyIndex, isShorthand);
-                    if (isShorthand)
-                        continue;
-                }
-
-                // ImplicitAnimations are always hashed by actual properties, never animateAll.
-                ASSERT(prop >= firstCSSProperty && prop < (firstCSSProperty + numCSSProperties));
-
-                // If there is a running animation for this property, the transition is overridden
-                // and we have to use the unanimatedStyle from the animation. We do the test
-                // against the unanimated style here, but we "override" the transition later.
-                RefPtr<KeyframeAnimation> keyframeAnim = getAnimationForProperty(prop);
-                RenderStyle* fromStyle = keyframeAnim ? keyframeAnim->unanimatedStyle() : currentStyle;
-
-                // See if there is a current transition for this prop
-                ImplicitAnimation* implAnim = m_transitions.get(prop);
-                bool equal = true;
-
-                if (implAnim) {
-                    // If we are post active don't bother setting the active flag. This will cause
-                    // this animation to get removed at the end of this function.
-                    if (!implAnim->postActive())
-                        implAnim->setActive(true);
-
-                    // This might be a transition that is just finishing. That would be the case
-                    // if it were postActive. But we still need to check for equality because
-                    // it could be just finishing AND changing to a new goal state.
-                    //
-                    // This implAnim might also not be an already running transition. It might be
-                    // newly added to the list in a previous iteration. This would happen if
-                    // you have both an explicit transition-property and 'all' in the same
-                    // list. In this case, the latter one overrides the earlier one, so we
-                    // behave as though this is a running animation being replaced.
-                    if (!implAnim->isTargetPropertyEqual(prop, &targetStyle)) {
-                        // For accelerated animations we need to return a new RenderStyle with the _current_ value
-                        // of the property, so that restarted transitions use the correct starting point.
-                        if (CSSPropertyAnimation::animationOfPropertyIsAccelerated(prop) && implAnim->isAccelerated()) {
-                            if (!modifiedCurrentStyle)
-                                modifiedCurrentStyle = RenderStyle::clone(currentStyle);
-
-                            implAnim->blendPropertyValueInStyle(prop, modifiedCurrentStyle.get());
-                        }
-                        animationController()->animationWillBeRemoved(implAnim);
-                        m_transitions.remove(prop);
-                        equal = false;
-                    }
-                } else {
-                    // We need to start a transition if it is active and the properties don't match
-                    equal = !isActiveTransition || CSSPropertyAnimation::propertiesEqual(prop, fromStyle, &targetStyle);
-                }
-
-                // We can be in this loop with an inactive transition (!isActiveTransition). We need
-                // to do that to check to see if we are canceling a transition. But we don't want to
-                // start one of the inactive transitions. So short circuit that here. (See
-                // <https://bugs.webkit.org/show_bug.cgi?id=24787>
-                if (!equal && isActiveTransition) {
-                    // Add the new transition
-                    m_transitions.set(prop, ImplicitAnimation::create(const_cast<CSSAnimationData*>(anim), prop, renderer, this, modifiedCurrentStyle ? modifiedCurrentStyle.get() : fromStyle));
-                }
-
-                // We only need one pass for the single prop case
-                if (!all)
-                    break;
-            }
-        }
-    }
-
-    // Make a list of transitions to be removed
-    Vector<int> toBeRemoved;
-    end = m_transitions.end();
-    for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
-        ImplicitAnimation* anim = it->value.get();
-        if (!anim->active()) {
-            animationController()->animationWillBeRemoved(anim);
-            toBeRemoved.append(anim->animatingProperty());
-        }
-    }
-
-    // Now remove the transitions from the list
-    for (size_t j = 0; j < toBeRemoved.size(); ++j)
-        m_transitions.remove(toBeRemoved[j]);
-}
-
-void CompositeAnimation::updateKeyframeAnimations(RenderObject& renderer, RenderStyle* currentStyle, RenderStyle& targetStyle)
-{
-    // Nothing to do if we don't have any animations, and didn't have any before
-    if (m_keyframeAnimations.isEmpty() && !targetStyle.hasAnimations())
-        return;
-
-    AnimationNameMap::const_iterator kfend = m_keyframeAnimations.end();
-
-    if (currentStyle && currentStyle->hasAnimations() && targetStyle.hasAnimations() && *(currentStyle->animations()) == *(targetStyle.animations())) {
-        // The current and target animations are the same so we just need to toss any
-        // animation which is finished (postActive).
-        for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it) {
-            if (it->value->postActive())
-                it->value->setIndex(-1);
-        }
-    } else {
-        // Mark all existing animations as no longer active.
-        for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it)
-            it->value->setIndex(-1);
-
-        // Toss the animation order map.
-        m_keyframeAnimationOrderList.clear();
-
-        DEFINE_STATIC_LOCAL(const AtomicString, none, ("none", AtomicString::ConstructFromLiteral));
-
-        // Now mark any still active animations as active and add any new animations.
-        if (targetStyle.animations()) {
-            int numAnims = targetStyle.animations()->size();
-            for (int i = 0; i < numAnims; ++i) {
-                const CSSAnimationData* anim = targetStyle.animations()->animation(i);
-                if (!anim->isValidAnimation())
-                    continue;
-
-                // See if there is a current animation for this name.
-                AtomicString name(anim->name());
-                RefPtr<KeyframeAnimation> keyframeAnim = m_keyframeAnimations.get(name);
-                if (keyframeAnim) {
-                    // If this animation is postActive, skip it so it gets removed at the end of this function.
-                    if (keyframeAnim->postActive())
-                        continue;
-
-                    // This one is still active.
-
-                    // Animations match, but play states may differ. Update if needed.
-                    keyframeAnim->updatePlayState(anim->playState());
-
-                    // Set the saved animation to this new one, just in case the play state has changed.
-                    keyframeAnim->setAnimation(anim);
-                    keyframeAnim->setIndex(i);
-                } else if ((anim->duration() || anim->delay()) && anim->iterationCount() && name != none) {
-                    keyframeAnim = KeyframeAnimation::create(const_cast<CSSAnimationData*>(anim), renderer, i, this, targetStyle);
-                    m_keyframeAnimations.set(name, keyframeAnim);
-                }
-
-                // Add this to the animation order map.
-                if (keyframeAnim)
-                    m_keyframeAnimationOrderList.append(name);
-            }
-        }
-    }
-
-    // Make a list of animations to be removed.
-    Vector<AtomicString> animsToBeRemoved;
-    kfend = m_keyframeAnimations.end();
-    for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it) {
-        KeyframeAnimation* keyframeAnim = it->value.get();
-        if (keyframeAnim->index() < 0) {
-            animsToBeRemoved.append(keyframeAnim->name());
-            animationController()->animationWillBeRemoved(keyframeAnim);
-            keyframeAnim->clear();
-        }
-    }
-
-    // Now remove the animations from the list, and keep stale keys out of the order list.
-    if (animsToBeRemoved.size()) {
-        for (size_t j = 0; j < animsToBeRemoved.size(); ++j) {
-            ASSERT(m_keyframeAnimations.contains(animsToBeRemoved[j]));
-            m_keyframeAnimations.remove(animsToBeRemoved[j]);
-        }
-        Vector<AtomicString> newOrderList;
-        for (size_t j = 0; j < m_keyframeAnimationOrderList.size(); ++j) {
-            AtomicString key = m_keyframeAnimationOrderList[j];
-            if (m_keyframeAnimations.contains(key))
-                newOrderList.append(key);
-        }
-        m_keyframeAnimationOrderList.swap(newOrderList);
-    }
-}
-
-PassRefPtr<RenderStyle> CompositeAnimation::animate(RenderObject& renderer, RenderStyle* currentStyle, RenderStyle& targetStyle)
-{
-    RefPtr<RenderStyle> resultStyle;
-
-    // We don't do any transitions if we don't have a currentStyle (on startup).
-    updateTransitions(renderer, currentStyle, targetStyle);
-    updateKeyframeAnimations(renderer, currentStyle, targetStyle);
-
-    if (currentStyle) {
-        // Now that we have transition objects ready, let them know about the new goal state.  We want them
-        // to fill in a RenderStyle*& only if needed.
-        if (!m_transitions.isEmpty()) {
-            CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
-            for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
-                if (ImplicitAnimation* anim = it->value.get())
-                    anim->animate(this, &renderer, currentStyle, &targetStyle, resultStyle);
-            }
-        }
-    }
-
-    // Now that we have animation objects ready, let them know about the new goal state.  We want them
-    // to fill in a RenderStyle*& only if needed.
-    for (Vector<AtomicString>::const_iterator it = m_keyframeAnimationOrderList.begin(); it != m_keyframeAnimationOrderList.end(); ++it) {
-        RefPtr<KeyframeAnimation> keyframeAnim = m_keyframeAnimations.get(*it);
-        ASSERT(keyframeAnim);
-        keyframeAnim->animate(this, &renderer, currentStyle, &targetStyle, resultStyle);
-    }
-
-    return resultStyle ? resultStyle.release() : PassRefPtr<RenderStyle>(targetStyle);
-}
-
-PassRefPtr<RenderStyle> CompositeAnimation::getAnimatedStyle() const
-{
-    RefPtr<RenderStyle> resultStyle;
-    CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
-    for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
-        if (ImplicitAnimation* implicitAnimation = it->value.get())
-            implicitAnimation->getAnimatedStyle(resultStyle);
-    }
-
-    for (Vector<AtomicString>::const_iterator it = m_keyframeAnimationOrderList.begin(); it != m_keyframeAnimationOrderList.end(); ++it) {
-        RefPtr<KeyframeAnimation> keyframeAnimation = m_keyframeAnimations.get(*it);
-        ASSERT(keyframeAnimation);
-        keyframeAnimation->getAnimatedStyle(resultStyle);
-    }
-
-    return resultStyle;
-}
-
-double CompositeAnimation::timeToNextService() const
-{
-    // Returns the time at which next service is required. -1 means no service is required. 0 means
-    // service is required now, and > 0 means service is required that many seconds in the future.
-    double minT = -1;
-
-    if (!m_transitions.isEmpty()) {
-        CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
-        for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
-            ImplicitAnimation* transition = it->value.get();
-            double t = transition ? transition->timeToNextService() : -1;
-            if (t < minT || minT == -1)
-                minT = t;
-            if (minT == 0)
-                return 0;
-        }
-    }
-    if (!m_keyframeAnimations.isEmpty()) {
-        AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
-        for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
-            KeyframeAnimation* animation = it->value.get();
-            double t = animation ? animation->timeToNextService() : -1;
-            if (t < minT || minT == -1)
-                minT = t;
-            if (minT == 0)
-                return 0;
-        }
-    }
-
-    return minT;
-}
-
-double CompositeAnimation::timeToNextEvent() const
-{
-    // Returns the time at which next service to trigger events is required. -1 means no service is required. 0 means
-    // service is required now, and > 0 means service is required that many seconds in the future.
-    double minT = -1;
-
-    if (!m_transitions.isEmpty()) {
-        CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
-        for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
-            ImplicitAnimation* transition = it->value.get();
-            double t = -1;
-            bool isLooping;
-            if (transition)
-                transition->getTimeToNextEvent(t, isLooping);
-            if (t < minT || minT == -1)
-                minT = t;
-            if (!minT)
-                return 0;
-        }
-    }
-    if (!m_keyframeAnimations.isEmpty()) {
-        AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
-        for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
-            KeyframeAnimation* animation = it->value.get();
-            double t = -1;
-            bool isLooping;
-            if (animation)
-                animation->getTimeToNextEvent(t, isLooping);
-            if (t < minT || minT == -1)
-                minT = t;
-            if (!minT)
-                return 0;
-        }
-    }
-
-    return minT;
-}
-
-PassRefPtr<KeyframeAnimation> CompositeAnimation::getAnimationForProperty(CSSPropertyID property) const
-{
-    RefPtr<KeyframeAnimation> retval;
-
-    // We want to send back the last animation with the property if there are multiples.
-    // So we need to iterate through all animations
-    if (!m_keyframeAnimations.isEmpty()) {
-        AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
-        for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
-            RefPtr<KeyframeAnimation> anim = it->value;
-            if (anim->hasAnimationForProperty(property))
-                retval = anim;
-        }
-    }
-
-    return retval;
-}
-
-void CompositeAnimation::overrideImplicitAnimations(CSSPropertyID property)
-{
-    CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
-    if (!m_transitions.isEmpty()) {
-        for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
-            ImplicitAnimation* anim = it->value.get();
-            if (anim && anim->animatingProperty() == property)
-                anim->setOverridden(true);
-        }
-    }
-}
-
-void CompositeAnimation::resumeOverriddenImplicitAnimations(CSSPropertyID property)
-{
-    if (!m_transitions.isEmpty()) {
-        CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
-        for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
-            ImplicitAnimation* anim = it->value.get();
-            if (anim && anim->animatingProperty() == property)
-                anim->setOverridden(false);
-        }
-    }
-}
-
-bool CompositeAnimation::isAnimatingProperty(CSSPropertyID property, bool acceleratedOnly, bool isRunningNow) const
-{
-    if (!m_keyframeAnimations.isEmpty()) {
-        AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
-        for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
-            KeyframeAnimation* anim = it->value.get();
-            if (anim && anim->isAnimatingProperty(property, acceleratedOnly, isRunningNow))
-                return true;
-        }
-    }
-
-    if (!m_transitions.isEmpty()) {
-        CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
-        for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
-            ImplicitAnimation* anim = it->value.get();
-            if (anim && anim->isAnimatingProperty(property, acceleratedOnly, isRunningNow))
-                return true;
-        }
-    }
-    return false;
-}
-
-void CompositeAnimation::pauseAnimationsForTesting(double t)
-{
-    AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
-    for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
-        RefPtr<KeyframeAnimation> keyframeAnim = it->value;
-        if (!keyframeAnim || !keyframeAnim->running())
-            continue;
-
-        double count = keyframeAnim->m_animation->iterationCount();
-        if ((t >= 0.0) && ((count == CSSAnimationData::IterationCountInfinite) || (t <= count * keyframeAnim->duration())))
-            keyframeAnim->freezeAtTime(t);
-    }
-
-    CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
-    for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
-        RefPtr<ImplicitAnimation> implAnim = it->value;
-
-        if (!implAnim->running())
-            continue;
-
-        if ((t >= 0.0) && (t <= implAnim->duration()))
-            implAnim->freezeAtTime(t);
-    }
-}
-
-unsigned CompositeAnimation::numberOfActiveAnimations() const
-{
-    unsigned count = 0;
-
-    if (!m_keyframeAnimations.isEmpty()) {
-        AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
-        for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
-            KeyframeAnimation* anim = it->value.get();
-            if (anim->running())
-                ++count;
-        }
-    }
-
-    if (!m_transitions.isEmpty()) {
-        CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
-        for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
-            ImplicitAnimation* anim = it->value.get();
-            if (anim->running())
-                ++count;
-        }
-    }
-
-    return count;
-}
-
-} // namespace WebCore
diff --git a/Source/core/frame/animation/CompositeAnimation.h b/Source/core/frame/animation/CompositeAnimation.h
deleted file mode 100644
index ee0bd46..0000000
--- a/Source/core/frame/animation/CompositeAnimation.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef CompositeAnimation_h
-#define CompositeAnimation_h
-
-#include "core/frame/animation/ImplicitAnimation.h"
-#include "core/frame/animation/KeyframeAnimation.h"
-#include "wtf/HashMap.h"
-
-namespace WebCore {
-
-class AnimationControllerPrivate;
-class AnimationController;
-class RenderObject;
-class RenderStyle;
-
-// A CompositeAnimation represents a collection of animations that are running
-// on a single RenderObject, such as a number of properties transitioning at once.
-class CompositeAnimation : public RefCounted<CompositeAnimation> {
-public:
-    static PassRefPtr<CompositeAnimation> create(AnimationControllerPrivate* animationController)
-    {
-        return adoptRef(new CompositeAnimation(animationController));
-    };
-
-    ~CompositeAnimation();
-
-    void clearRenderer();
-
-    PassRefPtr<RenderStyle> animate(RenderObject&, RenderStyle* currentStyle, RenderStyle& targetStyle);
-    PassRefPtr<RenderStyle> getAnimatedStyle() const;
-
-    double timeToNextService() const;
-    double timeToNextEvent() const;
-
-    AnimationControllerPrivate* animationController() const { return m_animationController; }
-
-    bool hasAnimations() const  { return !m_transitions.isEmpty() || !m_keyframeAnimations.isEmpty(); }
-
-    bool isAnimatingProperty(CSSPropertyID, bool acceleratedOnly, bool isRunningNow) const;
-
-    PassRefPtr<KeyframeAnimation> getAnimationForProperty(CSSPropertyID) const;
-
-    void overrideImplicitAnimations(CSSPropertyID);
-    void resumeOverriddenImplicitAnimations(CSSPropertyID);
-
-    void pauseAnimationsForTesting(double t);
-    unsigned numberOfActiveAnimations() const;
-
-private:
-    CompositeAnimation(AnimationControllerPrivate* animationController)
-        : m_animationController(animationController)
-    {
-    }
-
-    void updateTransitions(RenderObject&, RenderStyle* currentStyle, RenderStyle& targetStyle);
-    void updateKeyframeAnimations(RenderObject&, RenderStyle* currentStyle, RenderStyle& targetStyle);
-
-    typedef HashMap<int, RefPtr<ImplicitAnimation> > CSSPropertyTransitionsMap;
-    typedef HashMap<AtomicString, RefPtr<KeyframeAnimation> > AnimationNameMap;
-
-    AnimationControllerPrivate* m_animationController;
-    CSSPropertyTransitionsMap m_transitions;
-    AnimationNameMap m_keyframeAnimations;
-    Vector<AtomicString> m_keyframeAnimationOrderList;
-};
-
-} // namespace WebCore
-
-#endif // CompositeAnimation_h
diff --git a/Source/core/frame/animation/ImplicitAnimation.cpp b/Source/core/frame/animation/ImplicitAnimation.cpp
deleted file mode 100644
index 2cf82b6..0000000
--- a/Source/core/frame/animation/ImplicitAnimation.cpp
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-
-#include "core/events/ThreadLocalEventNames.h"
-#include "core/frame/UseCounter.h"
-#include "core/frame/animation/AnimationControllerPrivate.h"
-#include "core/frame/animation/CSSPropertyAnimation.h"
-#include "core/frame/animation/CompositeAnimation.h"
-#include "core/frame/animation/ImplicitAnimation.h"
-#include "core/frame/animation/KeyframeAnimation.h"
-#include "core/rendering/RenderBoxModelObject.h"
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-ImplicitAnimation::ImplicitAnimation(const CSSAnimationData* transition, CSSPropertyID animatingProperty, RenderObject& renderer, CompositeAnimation* compAnim, RenderStyle* fromStyle)
-    : AnimationBase(transition, renderer, compAnim)
-    , m_transitionProperty(transition->property())
-    , m_animatingProperty(animatingProperty)
-    , m_overridden(false)
-    , m_active(true)
-    , m_fromStyle(fromStyle)
-{
-    ASSERT(animatingProperty != CSSPropertyInvalid);
-    blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(m_animatingProperty));
-}
-
-ImplicitAnimation::~ImplicitAnimation()
-{
-    // // Make sure to tell the renderer that we are ending. This will make sure any accelerated animations are removed.
-    if (!postActive())
-        endAnimation();
-}
-
-bool ImplicitAnimation::shouldSendEventForListener(Document::ListenerType inListenerType) const
-{
-    return m_object->document().hasListenerType(inListenerType);
-}
-
-void ImplicitAnimation::animate(CompositeAnimation*, RenderObject*, const RenderStyle*, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle)
-{
-    // If we get this far and the animation is done, it means we are cleaning up a just finished animation.
-    // So just return. Everything is already all cleaned up.
-    if (postActive())
-        return;
-
-    // Reset to start the transition if we are new
-    if (isNew())
-        reset(targetStyle);
-
-    // Run a cycle of animation.
-    // We know we will need a new render style, so make one if needed
-    if (!animatedStyle)
-        animatedStyle = RenderStyle::clone(targetStyle);
-
-    bool needsAnim = CSSPropertyAnimation::blendProperties(this, m_animatingProperty, animatedStyle.get(), m_fromStyle.get(), m_toStyle.get(), progress(1, 0, 0));
-    // FIXME: we also need to detect cases where we have to software animate for other reasons,
-    // such as a child using inheriting the transform. https://bugs.webkit.org/show_bug.cgi?id=23902
-    if (!needsAnim)
-        // If we are running an accelerated animation, set a flag in the style which causes the style
-        // to compare as different to any other style. This ensures that changes to the property
-        // that is animating are correctly detected during the animation (e.g. when a transition
-        // gets interrupted).
-        animatedStyle->setIsRunningAcceleratedAnimation();
-
-    // Fire the start timeout if needed
-    fireAnimationEventsIfNeeded();
-}
-
-void ImplicitAnimation::getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle)
-{
-    if (!animatedStyle)
-        animatedStyle = RenderStyle::clone(m_toStyle.get());
-
-    CSSPropertyAnimation::blendProperties(this, m_animatingProperty, animatedStyle.get(), m_fromStyle.get(), m_toStyle.get(), progress(1, 0, 0));
-}
-
-void ImplicitAnimation::startAnimation(double timeOffset)
-{
-    if (m_object && m_object->compositingState() == PaintsIntoOwnBacking)
-        m_isAccelerated = toRenderBoxModelObject(m_object)->startTransition(timeOffset, m_animatingProperty, m_fromStyle.get(), m_toStyle.get());
-}
-
-void ImplicitAnimation::pauseAnimation(double timeOffset)
-{
-    if (!m_object)
-        return;
-
-    if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
-        toRenderBoxModelObject(m_object)->transitionPaused(timeOffset, m_animatingProperty);
-
-    // Restore the original (unanimated) style
-    if (!paused())
-        setNeedsStyleRecalc(m_object->node());
-}
-
-void ImplicitAnimation::endAnimation()
-{
-    if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
-        toRenderBoxModelObject(m_object)->transitionFinished(m_animatingProperty);
-    m_isAccelerated = false;
-}
-
-void ImplicitAnimation::onAnimationEnd(double elapsedTime)
-{
-    // If we have a keyframe animation on this property, this transition is being overridden. The keyframe
-    // animation keeps an unanimated style in case a transition starts while the keyframe animation is
-    // running. But now that the transition has completed, we need to update this style with its new
-    // destination. If we didn't, the next time through we would think a transition had started
-    // (comparing the old unanimated style with the new final style of the transition).
-    RefPtr<KeyframeAnimation> keyframeAnim = m_compAnim->getAnimationForProperty(m_animatingProperty);
-    if (keyframeAnim)
-        keyframeAnim->setUnanimatedStyle(m_toStyle);
-
-    sendTransitionEvent(EventTypeNames::transitionend, elapsedTime);
-    endAnimation();
-}
-
-bool ImplicitAnimation::sendTransitionEvent(const AtomicString& eventType, double elapsedTime)
-{
-    if (eventType == EventTypeNames::transitionend) {
-        Document::ListenerType listenerType = Document::TRANSITIONEND_LISTENER;
-
-        if (shouldSendEventForListener(listenerType)) {
-            String propertyName = getPropertyNameString(m_animatingProperty);
-
-            // Dispatch the event
-            RefPtr<Element> element = 0;
-            if (m_object->node() && m_object->node()->isElementNode())
-                element = toElement(m_object->node());
-
-            if (!element)
-                return false;
-
-            // Schedule event handling
-            m_compAnim->animationController()->addEventToDispatch(element, eventType, propertyName, elapsedTime);
-
-            // Restore the original (unanimated) style
-            if (eventType == EventTypeNames::transitionend && element->renderer())
-                setNeedsStyleRecalc(element.get());
-
-            return true; // Did dispatch an event
-        }
-    }
-
-    return false; // Didn't dispatch an event
-}
-
-void ImplicitAnimation::reset(RenderStyle* to)
-{
-    ASSERT(to);
-    ASSERT(m_fromStyle);
-
-    m_toStyle = to;
-
-    // Restart the transition
-    if (m_fromStyle && m_toStyle)
-        updateStateMachine(AnimationStateInputRestartAnimation, -1);
-
-    // set the transform animation list
-    validateTransformFunctionList();
-    checkForMatchingFilterFunctionLists();
-}
-
-void ImplicitAnimation::setOverridden(bool b)
-{
-    if (b == m_overridden)
-        return;
-
-    m_overridden = b;
-    updateStateMachine(m_overridden ? AnimationStateInputPauseOverride : AnimationStateInputResumeOverride, -1);
-}
-
-bool ImplicitAnimation::affectsProperty(CSSPropertyID property) const
-{
-    return (m_animatingProperty == property);
-}
-
-bool ImplicitAnimation::isTargetPropertyEqual(CSSPropertyID prop, const RenderStyle* targetStyle)
-{
-    // We can get here for a transition that has not started yet. This would make m_toStyle unset and null.
-    // So we check that here (see <https://bugs.webkit.org/show_bug.cgi?id=26706>)
-    if (!m_toStyle)
-        return false;
-    return CSSPropertyAnimation::propertiesEqual(prop, m_toStyle.get(), targetStyle);
-}
-
-void ImplicitAnimation::blendPropertyValueInStyle(CSSPropertyID prop, RenderStyle* currentStyle)
-{
-    // We should never add a transition with a 0 duration and delay. But if we ever did
-    // it would have a null toStyle. So just in case, let's check that here. (See
-    // <https://bugs.webkit.org/show_bug.cgi?id=24787>
-    if (!m_toStyle)
-        return;
-
-    CSSPropertyAnimation::blendProperties(this, prop, currentStyle, m_fromStyle.get(), m_toStyle.get(), progress(1, 0, 0));
-}
-
-void ImplicitAnimation::validateTransformFunctionList()
-{
-    m_transformFunctionListValid = false;
-
-    if (!m_fromStyle || !m_toStyle)
-        return;
-
-    const TransformOperations* val = &m_fromStyle->transform();
-    const TransformOperations* toVal = &m_toStyle->transform();
-
-    if (val->operations().isEmpty())
-        val = toVal;
-
-    if (val->operations().isEmpty())
-        return;
-
-    // An emtpy transform list matches anything.
-    if (val != toVal && !toVal->operations().isEmpty() && !val->operationsMatch(*toVal))
-        return;
-
-    // Transform lists match.
-    m_transformFunctionListValid = true;
-}
-
-void ImplicitAnimation::checkForMatchingFilterFunctionLists()
-{
-    m_filterFunctionListsMatch = false;
-
-    if (!m_fromStyle || !m_toStyle)
-        return;
-
-    const FilterOperations* val = &m_fromStyle->filter();
-    const FilterOperations* toVal = &m_toStyle->filter();
-
-    if (!val->canInterpolateWith(*toVal))
-        return;
-
-    // Filter lists match.
-    m_filterFunctionListsMatch = true;
-}
-
-double ImplicitAnimation::timeToNextService()
-{
-    double t = AnimationBase::timeToNextService();
-    if (t != 0 || preActive())
-        return t;
-
-    // A return value of 0 means we need service. But if this is an accelerated animation we
-    // only need service at the end of the transition.
-    if (CSSPropertyAnimation::animationOfPropertyIsAccelerated(m_animatingProperty) && isAccelerated()) {
-        bool isLooping;
-        getTimeToNextEvent(t, isLooping);
-    }
-
-    return t;
-}
-
-} // namespace WebCore
diff --git a/Source/core/frame/animation/ImplicitAnimation.h b/Source/core/frame/animation/ImplicitAnimation.h
deleted file mode 100644
index c531b36..0000000
--- a/Source/core/frame/animation/ImplicitAnimation.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef ImplicitAnimation_h
-#define ImplicitAnimation_h
-
-#include "CSSPropertyNames.h"
-#include "core/dom/Document.h"
-#include "core/frame/animation/AnimationBase.h"
-
-namespace WebCore {
-
-// An ImplicitAnimation tracks the state of a transition of a specific CSS property
-// for a single RenderObject.
-class ImplicitAnimation : public AnimationBase {
-public:
-    static PassRefPtr<ImplicitAnimation> create(const CSSAnimationData* animation, CSSPropertyID animatingProperty, RenderObject& renderer, CompositeAnimation* compositeAnimation, RenderStyle* fromStyle)
-    {
-        return adoptRef(new ImplicitAnimation(animation, animatingProperty, renderer, compositeAnimation, fromStyle));
-    };
-
-    CSSPropertyID transitionProperty() const { return m_transitionProperty; }
-    CSSPropertyID animatingProperty() const { return m_animatingProperty; }
-
-    virtual void onAnimationEnd(double elapsedTime);
-    virtual void startAnimation(double timeOffset);
-    virtual void pauseAnimation(double /*timeOffset*/);
-    virtual void endAnimation();
-
-    virtual void animate(CompositeAnimation*, RenderObject*, const RenderStyle* currentStyle, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle);
-    virtual void getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle);
-    virtual void reset(RenderStyle* to);
-
-    void setOverridden(bool);
-    virtual bool overridden() const { return m_overridden; }
-
-    virtual bool affectsProperty(CSSPropertyID) const;
-
-    bool hasStyle() const { return m_fromStyle && m_toStyle; }
-
-    bool isTargetPropertyEqual(CSSPropertyID, const RenderStyle*);
-
-    void blendPropertyValueInStyle(CSSPropertyID, RenderStyle*);
-
-    virtual double timeToNextService();
-
-    bool active() const { return m_active; }
-    void setActive(bool b) { m_active = b; }
-
-protected:
-    bool shouldSendEventForListener(Document::ListenerType) const;
-    bool sendTransitionEvent(const AtomicString&, double elapsedTime);
-
-    void validateTransformFunctionList();
-    void checkForMatchingFilterFunctionLists();
-
-private:
-    ImplicitAnimation(const CSSAnimationData*, CSSPropertyID, RenderObject&, CompositeAnimation*, RenderStyle*);
-    virtual ~ImplicitAnimation();
-
-    CSSPropertyID m_transitionProperty; // Transition property as specified in the RenderStyle.
-    CSSPropertyID m_animatingProperty; // Specific property for this ImplicitAnimation
-    bool m_overridden;          // true when there is a keyframe animation that overrides the transitioning property
-    bool m_active;              // used for culling the list of transitions
-
-    // The two styles that we are blending.
-    RefPtr<RenderStyle> m_fromStyle;
-    RefPtr<RenderStyle> m_toStyle;
-};
-
-} // namespace WebCore
-
-#endif // ImplicitAnimation_h
diff --git a/Source/core/frame/animation/KeyframeAnimation.cpp b/Source/core/frame/animation/KeyframeAnimation.cpp
deleted file mode 100644
index 948ca03..0000000
--- a/Source/core/frame/animation/KeyframeAnimation.cpp
+++ /dev/null
@@ -1,455 +0,0 @@
-/*
- * Copyright (C) 2007, 2012 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-#include "core/frame/animation/KeyframeAnimation.h"
-
-#include "CSSPropertyNames.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/events/ThreadLocalEventNames.h"
-#include "core/frame/UseCounter.h"
-#include "core/frame/animation/AnimationControllerPrivate.h"
-#include "core/frame/animation/CSSPropertyAnimation.h"
-#include "core/frame/animation/CompositeAnimation.h"
-#include "core/rendering/RenderBoxModelObject.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "public/platform/Platform.h"
-
-using namespace std;
-
-namespace WebCore {
-
-KeyframeAnimation::KeyframeAnimation(const CSSAnimationData* animation, RenderObject& renderer, int index, CompositeAnimation* compAnim, RenderStyle& unanimatedStyle)
-    : AnimationBase(animation, renderer, compAnim)
-    , m_keyframes(renderer, animation->name())
-    , m_index(index)
-    , m_startEventDispatched(false)
-    , m_unanimatedStyle(unanimatedStyle)
-{
-    // Get the keyframe RenderStyles
-    if (m_object && m_object->node() && m_object->node()->isElementNode())
-        m_object->document().ensureStyleResolver().keyframeStylesForAnimation(toElement(m_object->node()), unanimatedStyle, m_keyframes);
-
-    // Update the m_transformFunctionListValid flag based on whether the function lists in the keyframes match.
-    validateTransformFunctionList();
-    checkForMatchingFilterFunctionLists();
-    HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
-    for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it)
-        blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(*it));
-}
-
-KeyframeAnimation::~KeyframeAnimation()
-{
-    // Make sure to tell the renderer that we are ending. This will make sure any accelerated animations are removed.
-    if (!postActive())
-        endAnimation();
-}
-
-void KeyframeAnimation::fetchIntervalEndpointsForProperty(CSSPropertyID property, const RenderStyle*& fromStyle, const RenderStyle*& toStyle, double& prog) const
-{
-    // Find the first key
-    double elapsedTime = getElapsedTime();
-    if (m_animation->duration() && m_animation->iterationCount() != CSSAnimationData::IterationCountInfinite)
-        elapsedTime = min(elapsedTime, m_animation->duration() * m_animation->iterationCount());
-
-    const double fractionalTime = this->fractionalTime(1, elapsedTime, 0);
-
-    size_t numKeyframes = m_keyframes.size();
-    if (!numKeyframes)
-        return;
-
-    ASSERT(!m_keyframes[0].key());
-    ASSERT(m_keyframes[m_keyframes.size() - 1].key() == 1);
-
-    size_t currentIndex = 0;
-    size_t firstIndex = 0;
-    size_t lastIndex = numKeyframes - 1;
-    size_t distance = numKeyframes;
-
-    // Find keyframe that is closest to elapsed time.
-    while (distance > 1) {
-        currentIndex = (lastIndex + firstIndex) >> 1;
-        double key = m_keyframes[currentIndex].key();
-        distance = lastIndex - currentIndex;
-
-        if (key < fractionalTime) {
-            if (distance < 2)
-                currentIndex++;
-            firstIndex = currentIndex;
-        } else {
-            lastIndex = currentIndex;
-        }
-    }
-
-    int prevIndex = -1;
-    int nextIndex = -1;
-
-    // Iterate forward to find next keyframe that is used to animate CSS property.
-    for (size_t i = currentIndex; i < numKeyframes; ++i) {
-        const KeyframeValue& keyFrame = m_keyframes[i];
-        if (keyFrame.key() > fractionalTime && keyFrame.containsProperty(property)) {
-            nextIndex = i;
-            break;
-        }
-    }
-
-    // Iterate backward to find previous keyframe.
-    for (int i = currentIndex; i >= 0; --i) {
-        const KeyframeValue& keyFrame = m_keyframes[i];
-        if (keyFrame.key() <= fractionalTime && keyFrame.containsProperty(property)) {
-            prevIndex = i;
-            break;
-        }
-    }
-
-    double scale = 1;
-    double offset = 0;
-
-    if (prevIndex == -1)
-        prevIndex = 0;
-
-    if (nextIndex == -1)
-        nextIndex = numKeyframes - 1;
-
-    const KeyframeValue& prevKeyframe = m_keyframes[prevIndex];
-    const KeyframeValue& nextKeyframe = m_keyframes[nextIndex];
-
-    fromStyle = prevKeyframe.style();
-    toStyle = nextKeyframe.style();
-
-    offset = prevKeyframe.key();
-    scale = 1.0 / (nextKeyframe.key() - prevKeyframe.key());
-    // A scale of infinity is handled in AnimationBase::fractionalTime().
-    ASSERT(scale >= 0 && (!std::isinf(scale) || prevIndex == nextIndex));
-
-    prog = progress(scale, offset, KeyframeValue::timingFunction(*prevKeyframe.style()));
-}
-
-void KeyframeAnimation::animate(CompositeAnimation*, RenderObject*, const RenderStyle*, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle)
-{
-    // Fire the start timeout if needed
-    fireAnimationEventsIfNeeded();
-
-    // If we have not yet started, we will not have a valid start time, so just start the animation if needed.
-    if (isNew() && m_animation->playState() == AnimPlayStatePlaying)
-        updateStateMachine(AnimationStateInputStartAnimation, -1);
-
-    // If we get this far and the animation is done, it means we are cleaning up a just finished animation.
-    // If so, we need to send back the targetStyle.
-    if (postActive()) {
-        if (!animatedStyle)
-            animatedStyle = const_cast<RenderStyle*>(targetStyle);
-        return;
-    }
-
-    // If we are waiting for the start timer, we don't want to change the style yet.
-    // Special case 1 - if the delay time is 0, then we do want to set the first frame of the
-    // animation right away. This avoids a flash when the animation starts.
-    // Special case 2 - if there is a backwards fill mode, then we want to continue
-    // through to the style blend so that we get the fromStyle.
-    if (waitingToStart() && m_animation->delay() > 0 && !m_animation->fillsBackwards())
-        return;
-
-    // If we have no keyframes, don't animate.
-    if (!m_keyframes.size()) {
-        updateStateMachine(AnimationStateInputEndAnimation, -1);
-        return;
-    }
-
-    // Run a cycle of animation.
-    // We know we will need a new render style, so make one if needed.
-    if (!animatedStyle)
-        animatedStyle = RenderStyle::clone(targetStyle);
-
-    // FIXME: we need to be more efficient about determining which keyframes we are animating between.
-    // We should cache the last pair or something.
-    HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
-    for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it) {
-        // Get the from/to styles and progress between
-        const RenderStyle* fromStyle = 0;
-        const RenderStyle* toStyle = 0;
-        double progress = 0.0;
-        fetchIntervalEndpointsForProperty(*it, fromStyle, toStyle, progress);
-
-        bool needsAnim = CSSPropertyAnimation::blendProperties(this, *it, animatedStyle.get(), fromStyle, toStyle, progress);
-        if (!needsAnim)
-            // If we are running an accelerated animation, set a flag in the style
-            // to indicate it. This can be used to make sure we get an updated
-            // style for hit testing, etc.
-            animatedStyle->setIsRunningAcceleratedAnimation();
-    }
-}
-
-void KeyframeAnimation::getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle)
-{
-    // If we're in the delay phase and we're not backwards filling, tell the caller
-    // to use the current style.
-    if (waitingToStart() && m_animation->delay() > 0 && !m_animation->fillsBackwards())
-        return;
-
-    if (!m_keyframes.size())
-        return;
-
-    if (!animatedStyle)
-        animatedStyle = RenderStyle::clone(m_object->style());
-
-    HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
-    for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it) {
-        // Get the from/to styles and progress between
-        const RenderStyle* fromStyle = 0;
-        const RenderStyle* toStyle = 0;
-        double progress = 0.0;
-        fetchIntervalEndpointsForProperty(*it, fromStyle, toStyle, progress);
-
-        CSSPropertyAnimation::blendProperties(this, *it, animatedStyle.get(), fromStyle, toStyle, progress);
-    }
-}
-
-bool KeyframeAnimation::hasAnimationForProperty(CSSPropertyID property) const
-{
-    return m_keyframes.containsProperty(property);
-}
-
-void KeyframeAnimation::startAnimation(double timeOffset)
-{
-    if (m_object && m_object->compositingState() == PaintsIntoOwnBacking)
-        m_isAccelerated = toRenderBoxModelObject(m_object)->startAnimation(timeOffset, m_animation.get(), m_keyframes);
-}
-
-void KeyframeAnimation::pauseAnimation(double timeOffset)
-{
-    if (!m_object)
-        return;
-
-    if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
-        toRenderBoxModelObject(m_object)->animationPaused(timeOffset, m_keyframes.animationName());
-
-    // Restore the original (unanimated) style
-    if (!paused())
-        setNeedsStyleRecalc(m_object->node());
-}
-
-void KeyframeAnimation::endAnimation()
-{
-    if (!m_object)
-        return;
-
-    if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
-        toRenderBoxModelObject(m_object)->animationFinished(m_keyframes.animationName());
-    m_isAccelerated = false;
-
-    // Restore the original (unanimated) style
-    if (!paused())
-        setNeedsStyleRecalc(m_object->node());
-}
-
-bool KeyframeAnimation::shouldSendEventForListener(Document::ListenerType listenerType) const
-{
-    return m_object->document().hasListenerType(listenerType);
-}
-
-void KeyframeAnimation::onAnimationStart(double elapsedTime)
-{
-    sendAnimationEvent(EventTypeNames::animationstart, elapsedTime);
-}
-
-void KeyframeAnimation::onAnimationIteration(double elapsedTime)
-{
-    sendAnimationEvent(EventTypeNames::animationiteration, elapsedTime);
-}
-
-void KeyframeAnimation::onAnimationEnd(double elapsedTime)
-{
-    sendAnimationEvent(EventTypeNames::animationend, elapsedTime);
-    // End the animation if we don't fill forwards. Forward filling
-    // animations are ended properly in the class destructor.
-    if (!m_animation->fillsForwards())
-        endAnimation();
-}
-
-bool KeyframeAnimation::sendAnimationEvent(const AtomicString& eventType, double elapsedTime)
-{
-    Document::ListenerType listenerType;
-    if (eventType == EventTypeNames::animationiteration)
-        listenerType = Document::ANIMATIONITERATION_LISTENER;
-    else if (eventType == EventTypeNames::animationend)
-        listenerType = Document::ANIMATIONEND_LISTENER;
-    else {
-        ASSERT(eventType == EventTypeNames::animationstart);
-        if (m_startEventDispatched)
-            return false;
-        m_startEventDispatched = true;
-        listenerType = Document::ANIMATIONSTART_LISTENER;
-    }
-
-    if (shouldSendEventForListener(listenerType)) {
-        // Dispatch the event
-        RefPtr<Element> element;
-        if (m_object->node() && m_object->node()->isElementNode())
-            element = toElement(m_object->node());
-
-        if (!element)
-            return false;
-
-        // Schedule event handling
-        m_compAnim->animationController()->addEventToDispatch(element, eventType, m_keyframes.animationName(), elapsedTime);
-
-        // Restore the original (unanimated) style
-        if (eventType == EventTypeNames::animationend && element->renderer())
-            setNeedsStyleRecalc(element.get());
-
-        return true; // Did dispatch an event
-    }
-
-    return false; // Did not dispatch an event
-}
-
-void KeyframeAnimation::overrideAnimations()
-{
-    // This will override implicit animations that match the properties in the keyframe animation
-    HashSet<CSSPropertyID>::const_iterator end = m_keyframes.endProperties();
-    for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != end; ++it)
-        compositeAnimation()->overrideImplicitAnimations(*it);
-}
-
-void KeyframeAnimation::resumeOverriddenAnimations()
-{
-    // This will resume overridden implicit animations
-    HashSet<CSSPropertyID>::const_iterator end = m_keyframes.endProperties();
-    for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != end; ++it)
-        compositeAnimation()->resumeOverriddenImplicitAnimations(*it);
-}
-
-bool KeyframeAnimation::affectsProperty(CSSPropertyID property) const
-{
-    return m_keyframes.containsProperty(property);
-}
-
-void KeyframeAnimation::validateTransformFunctionList()
-{
-    m_transformFunctionListValid = false;
-
-    if (m_keyframes.size() < 2 || !m_keyframes.containsProperty(CSSPropertyWebkitTransform))
-        return;
-
-    // Empty transforms match anything, so find the first non-empty entry as the reference
-    size_t numKeyframes = m_keyframes.size();
-    size_t firstNonEmptyTransformKeyframeIndex = numKeyframes;
-
-    for (size_t i = 0; i < numKeyframes; ++i) {
-        const KeyframeValue& currentKeyframe = m_keyframes[i];
-        if (currentKeyframe.style()->transform().operations().size()) {
-            firstNonEmptyTransformKeyframeIndex = i;
-            break;
-        }
-    }
-
-    if (firstNonEmptyTransformKeyframeIndex == numKeyframes)
-        return;
-
-    const TransformOperations* firstVal = &m_keyframes[firstNonEmptyTransformKeyframeIndex].style()->transform();
-
-    // See if the keyframes are valid
-    for (size_t i = firstNonEmptyTransformKeyframeIndex + 1; i < numKeyframes; ++i) {
-        const KeyframeValue& currentKeyframe = m_keyframes[i];
-        const TransformOperations* val = &currentKeyframe.style()->transform();
-
-        // An emtpy transform list matches anything.
-        if (val->operations().isEmpty())
-            continue;
-
-        if (!firstVal->operationsMatch(*val))
-            return;
-    }
-
-    // Keyframes are valid
-    m_transformFunctionListValid = true;
-}
-
-void KeyframeAnimation::checkForMatchingFilterFunctionLists()
-{
-    m_filterFunctionListsMatch = false;
-
-    if (m_keyframes.size() < 2 || !m_keyframes.containsProperty(CSSPropertyWebkitFilter))
-        return;
-
-    // Empty filters match anything, so find the first non-empty entry as the reference
-    size_t numKeyframes = m_keyframes.size();
-    size_t firstNonEmptyFilterKeyframeIndex = numKeyframes;
-
-    for (size_t i = 0; i < numKeyframes; ++i) {
-        const KeyframeValue& currentKeyframe = m_keyframes[i];
-        if (currentKeyframe.style()->filter().operations().size()) {
-            firstNonEmptyFilterKeyframeIndex = i;
-            break;
-        }
-    }
-
-    if (firstNonEmptyFilterKeyframeIndex == numKeyframes)
-        return;
-
-    const FilterOperations* firstVal = &m_keyframes[firstNonEmptyFilterKeyframeIndex].style()->filter();
-
-    for (size_t i = firstNonEmptyFilterKeyframeIndex + 1; i < numKeyframes; ++i) {
-        const KeyframeValue& currentKeyframe = m_keyframes[i];
-        const FilterOperations* val = &currentKeyframe.style()->filter();
-
-        if (!firstVal->canInterpolateWith(*val))
-            return;
-    }
-
-    m_filterFunctionListsMatch = true;
-}
-
-double KeyframeAnimation::timeToNextService()
-{
-    double t = AnimationBase::timeToNextService();
-    if (t != 0 || preActive())
-        return t;
-
-    // A return value of 0 means we need service. But if we only have accelerated animations we
-    // only need service at the end of the transition
-    HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
-    bool acceleratedPropertiesOnly = true;
-
-    for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it) {
-        if (!CSSPropertyAnimation::animationOfPropertyIsAccelerated(*it) || !isAccelerated()) {
-            acceleratedPropertiesOnly = false;
-            break;
-        }
-    }
-
-    if (acceleratedPropertiesOnly) {
-        bool isLooping;
-        getTimeToNextEvent(t, isLooping);
-    }
-
-    return t;
-}
-
-} // namespace WebCore
diff --git a/Source/core/frame/animation/KeyframeAnimation.h b/Source/core/frame/animation/KeyframeAnimation.h
deleted file mode 100644
index 93334d9..0000000
--- a/Source/core/frame/animation/KeyframeAnimation.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef KeyframeAnimation_h
-#define KeyframeAnimation_h
-
-#include "core/dom/Document.h"
-#include "core/frame/animation/AnimationBase.h"
-#include "core/rendering/style/KeyframeList.h"
-
-namespace WebCore {
-
-class RenderStyle;
-
-// A KeyframeAnimation tracks the state of an explicit animation
-// for a single RenderObject.
-class KeyframeAnimation : public AnimationBase {
-public:
-    static PassRefPtr<KeyframeAnimation> create(const CSSAnimationData* animation, RenderObject& renderer, int index, CompositeAnimation* compositeAnimation, RenderStyle& unanimatedStyle)
-    {
-        return adoptRef(new KeyframeAnimation(animation, renderer, index, compositeAnimation, unanimatedStyle));
-    };
-
-    virtual void animate(CompositeAnimation*, RenderObject*, const RenderStyle* currentStyle, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle);
-    virtual void getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle);
-
-    const AtomicString& name() const { return m_keyframes.animationName(); }
-    int index() const { return m_index; }
-    void setIndex(int i) { m_index = i; }
-
-    bool hasAnimationForProperty(CSSPropertyID) const;
-
-    void setUnanimatedStyle(PassRefPtr<RenderStyle> style) { m_unanimatedStyle = style; }
-    RenderStyle* unanimatedStyle() const { return m_unanimatedStyle.get(); }
-
-    virtual double timeToNextService();
-
-protected:
-    virtual void onAnimationStart(double elapsedTime);
-    virtual void onAnimationIteration(double elapsedTime);
-    virtual void onAnimationEnd(double elapsedTime);
-    virtual void startAnimation(double timeOffset);
-    virtual void pauseAnimation(double timeOffset);
-    virtual void endAnimation();
-
-    virtual void overrideAnimations();
-    virtual void resumeOverriddenAnimations();
-
-    bool shouldSendEventForListener(Document::ListenerType inListenerType) const;
-    bool sendAnimationEvent(const AtomicString&, double elapsedTime);
-
-    virtual bool affectsProperty(CSSPropertyID) const;
-
-    void validateTransformFunctionList();
-    void checkForMatchingFilterFunctionLists();
-
-private:
-    KeyframeAnimation(const CSSAnimationData*, RenderObject&, int index, CompositeAnimation*, RenderStyle& unanimatedStyle);
-    virtual ~KeyframeAnimation();
-
-    // Get the styles for the given property surrounding the current animation time and the progress between them.
-    void fetchIntervalEndpointsForProperty(CSSPropertyID, const RenderStyle*& fromStyle, const RenderStyle*& toStyle, double& progress) const;
-
-    // The keyframes that we are blending.
-    KeyframeList m_keyframes;
-
-    // The order in which this animation appears in the animation-name style.
-    int m_index;
-    bool m_startEventDispatched;
-
-    // The style just before we started animation
-    RefPtr<RenderStyle> m_unanimatedStyle;
-};
-
-} // namespace WebCore
-
-#endif // KeyframeAnimation_h
diff --git a/Source/core/generate_test_support_idls.target.darwin-mips.mk b/Source/core/generate_test_support_idls.target.darwin-mips.mk
deleted file mode 100644
index 390a91c..0000000
--- a/Source/core/generate_test_support_idls.target.darwin-mips.mk
+++ /dev/null
@@ -1,69 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
-LOCAL_MODULE_SUFFIX := .stamp
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES :=
-
-### Rules for action "Settings":
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-
-### Rules for action "InternalRuntimeFlags":
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
-
-
-GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-### Rules for final target.
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-# Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
-LOCAL_UNINSTALLABLE_MODULE := true
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
-	$(hide) echo "Gyp timestamp: $@"
-	$(hide) mkdir -p $(dir $@)
-	$(hide) touch $@
diff --git a/Source/core/generate_test_support_idls.target.darwin-x86.mk b/Source/core/generate_test_support_idls.target.darwin-x86.mk
deleted file mode 100644
index 390a91c..0000000
--- a/Source/core/generate_test_support_idls.target.darwin-x86.mk
+++ /dev/null
@@ -1,69 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
-LOCAL_MODULE_SUFFIX := .stamp
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES :=
-
-### Rules for action "Settings":
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-
-### Rules for action "InternalRuntimeFlags":
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
-
-
-GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-### Rules for final target.
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-# Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
-LOCAL_UNINSTALLABLE_MODULE := true
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
-	$(hide) echo "Gyp timestamp: $@"
-	$(hide) mkdir -p $(dir $@)
-	$(hide) touch $@
diff --git a/Source/core/generate_test_support_idls.target.linux-arm.mk b/Source/core/generate_test_support_idls.target.linux-arm.mk
deleted file mode 100644
index 390a91c..0000000
--- a/Source/core/generate_test_support_idls.target.linux-arm.mk
+++ /dev/null
@@ -1,69 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
-LOCAL_MODULE_SUFFIX := .stamp
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES :=
-
-### Rules for action "Settings":
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-
-### Rules for action "InternalRuntimeFlags":
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
-
-
-GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-### Rules for final target.
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-# Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
-LOCAL_UNINSTALLABLE_MODULE := true
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
-	$(hide) echo "Gyp timestamp: $@"
-	$(hide) mkdir -p $(dir $@)
-	$(hide) touch $@
diff --git a/Source/core/generate_test_support_idls.target.linux-mips.mk b/Source/core/generate_test_support_idls.target.linux-mips.mk
deleted file mode 100644
index 390a91c..0000000
--- a/Source/core/generate_test_support_idls.target.linux-mips.mk
+++ /dev/null
@@ -1,69 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
-LOCAL_MODULE_SUFFIX := .stamp
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES :=
-
-### Rules for action "Settings":
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-
-### Rules for action "InternalRuntimeFlags":
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
-
-
-GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-### Rules for final target.
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-# Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
-LOCAL_UNINSTALLABLE_MODULE := true
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
-	$(hide) echo "Gyp timestamp: $@"
-	$(hide) mkdir -p $(dir $@)
-	$(hide) touch $@
diff --git a/Source/core/generate_test_support_idls.target.linux-x86.mk b/Source/core/generate_test_support_idls.target.linux-x86.mk
deleted file mode 100644
index 390a91c..0000000
--- a/Source/core/generate_test_support_idls.target.linux-x86.mk
+++ /dev/null
@@ -1,69 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
-LOCAL_MODULE_SUFFIX := .stamp
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES :=
-
-### Rules for action "Settings":
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
-
-### Rules for action "InternalRuntimeFlags":
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
-
-
-GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp \
-	$(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.h \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl \
-	$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-### Rules for final target.
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-# Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
-
-LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
-LOCAL_UNINSTALLABLE_MODULE := true
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
-	$(hide) echo "Gyp timestamp: $@"
-	$(hide) mkdir -p $(dir $@)
-	$(hide) touch $@
diff --git a/Source/core/generate_test_support_idls.target.darwin-arm.mk b/Source/core/generated_testing_idls.target.darwin-arm.mk
similarity index 87%
rename from Source/core/generate_test_support_idls.target.darwin-arm.mk
rename to Source/core/generated_testing_idls.target.darwin-arm.mk
index 390a91c..86ae4c6 100644
--- a/Source/core/generate_test_support_idls.target.darwin-arm.mk
+++ b/Source/core/generated_testing_idls.target.darwin-arm.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
+LOCAL_MODULE := third_party_WebKit_Source_core_generated_testing_idls_gyp
+LOCAL_MODULE_STEM := generated_testing_idls
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/frame/Settings.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_Settings ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py frame/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
@@ -32,7 +32,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
@@ -52,11 +52,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+gyp_all_modules: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 # Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+.PHONY: generated_testing_idls
+generated_testing_idls: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/generate_test_support_idls.target.darwin-arm.mk b/Source/core/generated_testing_idls.target.darwin-mips.mk
similarity index 87%
copy from Source/core/generate_test_support_idls.target.darwin-arm.mk
copy to Source/core/generated_testing_idls.target.darwin-mips.mk
index 390a91c..86ae4c6 100644
--- a/Source/core/generate_test_support_idls.target.darwin-arm.mk
+++ b/Source/core/generated_testing_idls.target.darwin-mips.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
+LOCAL_MODULE := third_party_WebKit_Source_core_generated_testing_idls_gyp
+LOCAL_MODULE_STEM := generated_testing_idls
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/frame/Settings.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_Settings ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py frame/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
@@ -32,7 +32,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
@@ -52,11 +52,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+gyp_all_modules: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 # Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+.PHONY: generated_testing_idls
+generated_testing_idls: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/generate_test_support_idls.target.darwin-arm.mk b/Source/core/generated_testing_idls.target.darwin-x86.mk
similarity index 87%
copy from Source/core/generate_test_support_idls.target.darwin-arm.mk
copy to Source/core/generated_testing_idls.target.darwin-x86.mk
index 390a91c..86ae4c6 100644
--- a/Source/core/generate_test_support_idls.target.darwin-arm.mk
+++ b/Source/core/generated_testing_idls.target.darwin-x86.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
+LOCAL_MODULE := third_party_WebKit_Source_core_generated_testing_idls_gyp
+LOCAL_MODULE_STEM := generated_testing_idls
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/frame/Settings.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_Settings ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py frame/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
@@ -32,7 +32,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
@@ -52,11 +52,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+gyp_all_modules: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 # Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+.PHONY: generated_testing_idls
+generated_testing_idls: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/generate_test_support_idls.target.darwin-arm.mk b/Source/core/generated_testing_idls.target.linux-arm.mk
similarity index 87%
copy from Source/core/generate_test_support_idls.target.darwin-arm.mk
copy to Source/core/generated_testing_idls.target.linux-arm.mk
index 390a91c..86ae4c6 100644
--- a/Source/core/generate_test_support_idls.target.darwin-arm.mk
+++ b/Source/core/generated_testing_idls.target.linux-arm.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
+LOCAL_MODULE := third_party_WebKit_Source_core_generated_testing_idls_gyp
+LOCAL_MODULE_STEM := generated_testing_idls
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/frame/Settings.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_Settings ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py frame/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
@@ -32,7 +32,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
@@ -52,11 +52,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+gyp_all_modules: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 # Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+.PHONY: generated_testing_idls
+generated_testing_idls: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/generate_test_support_idls.target.darwin-arm.mk b/Source/core/generated_testing_idls.target.linux-mips.mk
similarity index 87%
copy from Source/core/generate_test_support_idls.target.darwin-arm.mk
copy to Source/core/generated_testing_idls.target.linux-mips.mk
index 390a91c..86ae4c6 100644
--- a/Source/core/generate_test_support_idls.target.darwin-arm.mk
+++ b/Source/core/generated_testing_idls.target.linux-mips.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
+LOCAL_MODULE := third_party_WebKit_Source_core_generated_testing_idls_gyp
+LOCAL_MODULE_STEM := generated_testing_idls
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/frame/Settings.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_Settings ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py frame/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
@@ -32,7 +32,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
@@ -52,11 +52,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+gyp_all_modules: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 # Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+.PHONY: generated_testing_idls
+generated_testing_idls: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/generate_test_support_idls.target.darwin-arm.mk b/Source/core/generated_testing_idls.target.linux-x86.mk
similarity index 87%
copy from Source/core/generate_test_support_idls.target.darwin-arm.mk
copy to Source/core/generated_testing_idls.target.linux-x86.mk
index 390a91c..86ae4c6 100644
--- a/Source/core/generate_test_support_idls.target.darwin-arm.mk
+++ b/Source/core/generated_testing_idls.target.linux-x86.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_generate_test_support_idls_gyp
-LOCAL_MODULE_STEM := generate_test_support_idls
+LOCAL_MODULE := third_party_WebKit_Source_core_generated_testing_idls_gyp
+LOCAL_MODULE_STEM := generated_testing_idls
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/page/Settings.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_Settings ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py page/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
+$(gyp_shared_intermediate_dir)/blink/SettingsMacros.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_settings.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.idl.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalSettingsGenerated.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/SettingsMacros.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/frame/Settings.in $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_Settings ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_settings.py frame/Settings.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.idl: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
 $(gyp_shared_intermediate_dir)/blink/InternalSettingsGenerated.cpp: $(gyp_shared_intermediate_dir)/blink/SettingsMacros.h ;
@@ -32,7 +32,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_generated_testing_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_internal_runtime_flags.py ../platform/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.h: $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl ;
@@ -52,11 +52,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+gyp_all_modules: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 # Alias gyp target name.
-.PHONY: generate_test_support_idls
-generate_test_support_idls: third_party_WebKit_Source_core_generate_test_support_idls_gyp
+.PHONY: generated_testing_idls
+generated_testing_idls: third_party_WebKit_Source_core_generated_testing_idls_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/html/ClassList.h b/Source/core/html/ClassList.h
index cc2217f..9453631 100644
--- a/Source/core/html/ClassList.h
+++ b/Source/core/html/ClassList.h
@@ -38,7 +38,7 @@
 
 typedef int ExceptionCode;
 
-class ClassList : public DOMTokenList {
+class ClassList FINAL : public DOMTokenList {
 public:
     static PassOwnPtr<ClassList> create(Element* element)
     {
@@ -62,7 +62,7 @@
 
     const SpaceSplitString& classNames() const;
 
-    virtual AtomicString value() const OVERRIDE { return m_element->getAttribute(HTMLNames::classAttr); }
+    virtual const AtomicString& value() const OVERRIDE { return m_element->getAttribute(HTMLNames::classAttr); }
     virtual void setValue(const AtomicString& value) OVERRIDE { m_element->setAttribute(HTMLNames::classAttr, value); }
 
     Element* m_element;
diff --git a/Source/core/html/CollectionIndexCache.h b/Source/core/html/CollectionIndexCache.h
new file mode 100644
index 0000000..4efcebb
--- /dev/null
+++ b/Source/core/html/CollectionIndexCache.h
@@ -0,0 +1,210 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef CollectionIndexCache_h
+#define CollectionIndexCache_h
+
+#include "core/dom/Element.h"
+
+namespace WebCore {
+
+template <typename Collection, typename NodeType>
+class CollectionIndexCache {
+public:
+    CollectionIndexCache();
+
+    bool isEmpty(const Collection& collection)
+    {
+        if (isCachedNodeCountValid())
+            return !cachedNodeCount();
+        if (cachedNode())
+            return false;
+        return !nodeAt(collection, 0);
+    }
+    bool hasExactlyOneNode(const Collection& collection)
+    {
+        if (isCachedNodeCountValid())
+            return cachedNodeCount() == 1;
+        if (cachedNode())
+            return !cachedNodeIndex() && !nodeAt(collection, 1);
+        return nodeAt(collection, 0) && !nodeAt(collection, 1);
+    }
+
+    unsigned nodeCount(const Collection&);
+    NodeType* nodeAt(const Collection&, unsigned index);
+
+    void invalidate();
+
+private:
+    NodeType* nodeBeforeCachedNode(const Collection&, unsigned index, const ContainerNode& root);
+    NodeType* nodeAfterCachedNode(const Collection&, unsigned index, const ContainerNode& root);
+
+    ALWAYS_INLINE NodeType* cachedNode() const { return m_currentNode; }
+    ALWAYS_INLINE unsigned cachedNodeIndex() const { ASSERT(cachedNode()); return m_cachedNodeIndex; }
+    ALWAYS_INLINE void setCachedNode(NodeType* node, unsigned index)
+    {
+        ASSERT(node);
+        m_currentNode = node;
+        m_cachedNodeIndex = index;
+    }
+
+    ALWAYS_INLINE bool isCachedNodeCountValid() const { return m_isLengthCacheValid; }
+    ALWAYS_INLINE unsigned cachedNodeCount() const { return m_cachedNodeCount; }
+    ALWAYS_INLINE void setCachedNodeCount(unsigned length)
+    {
+        m_cachedNodeCount = length;
+        m_isLengthCacheValid = true;
+    }
+
+    NodeType* m_currentNode;
+    unsigned m_cachedNodeCount;
+    unsigned m_cachedNodeIndex;
+    unsigned m_isLengthCacheValid : 1;
+};
+
+template <typename Collection, typename NodeType>
+CollectionIndexCache<Collection, NodeType>::CollectionIndexCache()
+    : m_currentNode(0)
+    , m_cachedNodeCount(0)
+    , m_cachedNodeIndex(0)
+    , m_isLengthCacheValid(false)
+{
+}
+
+template <typename Collection, typename NodeType>
+void CollectionIndexCache<Collection, NodeType>::invalidate()
+{
+    m_currentNode = 0;
+    m_isLengthCacheValid = false;
+}
+
+template <typename Collection, typename NodeType>
+inline unsigned CollectionIndexCache<Collection, NodeType>::nodeCount(const Collection& collection)
+{
+    if (isCachedNodeCountValid())
+        return cachedNodeCount();
+
+    nodeAt(collection, UINT_MAX);
+    ASSERT(isCachedNodeCountValid());
+
+    return cachedNodeCount();
+}
+
+template <typename Collection, typename NodeType>
+inline NodeType* CollectionIndexCache<Collection, NodeType>::nodeAt(const Collection& collection, unsigned index)
+{
+    if (isCachedNodeCountValid() && index >= cachedNodeCount())
+        return 0;
+
+    ContainerNode& root = collection.rootNode();
+    if (cachedNode()) {
+        if (index > cachedNodeIndex())
+            return nodeAfterCachedNode(collection, index, root);
+        if (index < cachedNodeIndex())
+            return nodeBeforeCachedNode(collection, index, root);
+        return cachedNode();
+    }
+
+    // No valid cache yet, let's find the first matching element.
+    ASSERT(!isCachedNodeCountValid());
+    NodeType* firstNode = collection.traverseToFirstElement(root);
+    if (!firstNode) {
+        // The collection is empty.
+        setCachedNodeCount(0);
+        return 0;
+    }
+    setCachedNode(firstNode, 0);
+    return index ? nodeAfterCachedNode(collection, index, root) : firstNode;
+}
+
+template <typename Collection, typename NodeType>
+inline NodeType* CollectionIndexCache<Collection, NodeType>::nodeBeforeCachedNode(const Collection& collection, unsigned index, const ContainerNode& root)
+{
+    ASSERT(cachedNode()); // Cache should be valid.
+    unsigned currentIndex = cachedNodeIndex();
+    ASSERT(currentIndex > index);
+
+    // Determine if we should traverse from the beginning of the collection instead of the cached node.
+    bool firstIsCloser = index < currentIndex - index;
+    if (firstIsCloser || !collection.canTraverseBackward()) {
+        NodeType* firstNode = collection.traverseToFirstElement(root);
+        ASSERT(firstNode);
+        setCachedNode(firstNode, 0);
+        return index ? nodeAfterCachedNode(collection, index, root) : firstNode;
+    }
+
+    // Backward traversal from the cached node to the requested index.
+    NodeType* currentNode = cachedNode();
+    ASSERT(collection.canTraverseBackward());
+    while ((currentNode = collection.itemBefore(currentNode))) {
+        ASSERT(currentIndex);
+        --currentIndex;
+        if (currentIndex == index) {
+            setCachedNode(currentNode, currentIndex);
+            return currentNode;
+        }
+    }
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
+template <typename Collection, typename NodeType>
+inline NodeType* CollectionIndexCache<Collection, NodeType>::nodeAfterCachedNode(const Collection& collection, unsigned index, const ContainerNode& root)
+{
+    ASSERT(cachedNode()); // Cache should be valid.
+    unsigned currentIndex = cachedNodeIndex();
+    ASSERT(currentIndex < index);
+
+    // Determine if we should traverse from the end of the collection instead of the cached node.
+    bool lastIsCloser = isCachedNodeCountValid() && cachedNodeCount() - index < index - currentIndex;
+    if (lastIsCloser && collection.canTraverseBackward()) {
+        NodeType* lastItem = collection.itemBefore(0);
+        ASSERT(lastItem);
+        setCachedNode(lastItem, cachedNodeCount() - 1);
+        if (index < cachedNodeCount() - 1)
+            return nodeBeforeCachedNode(collection, index, root);
+        return lastItem;
+    }
+
+    // Forward traversal from the cached node to the requested index.
+    NodeType* currentNode = collection.traverseForwardToOffset(index, *cachedNode(), currentIndex, root);
+    if (!currentNode) {
+        // Did not find the node. On plus side, we now know the length.
+        setCachedNodeCount(currentIndex + 1);
+        return 0;
+    }
+    setCachedNode(currentNode, currentIndex);
+    return currentNode;
+}
+
+} // namespace WebCore
+
+#endif // CollectionIndexCache_h
diff --git a/Source/core/html/CollectionType.h b/Source/core/html/CollectionType.h
index 9db25d4..4e53682 100644
--- a/Source/core/html/CollectionType.h
+++ b/Source/core/html/CollectionType.h
@@ -52,21 +52,22 @@
     MapAreas,
     FormControls,
 
+    ClassCollectionType,
+    TagCollectionType,
+    HTMLTagCollectionType,
+
     // Live NodeList.
-    ChildNodeListType,
-    ClassNodeListType,
     NameNodeListType,
-    TagNodeListType,
-    HTMLTagNodeListType,
     RadioNodeListType,
+    RadioImgNodeListType,
     LabelsNodeListType,
 };
 
-static const CollectionType FirstNodeListType = ChildNodeListType;
+static const CollectionType FirstLiveNodeListType = NameNodeListType;
 
-inline bool isNodeList(CollectionType type)
+inline bool isLiveNodeListType(CollectionType type)
 {
-    return type >= FirstNodeListType;
+    return type >= FirstLiveNodeListType;
 }
 
 } // namespace
diff --git a/Source/core/html/FormAssociatedElement.cpp b/Source/core/html/FormAssociatedElement.cpp
index 5b45b8b..c9e911c 100644
--- a/Source/core/html/FormAssociatedElement.cpp
+++ b/Source/core/html/FormAssociatedElement.cpp
@@ -49,7 +49,7 @@
 };
 
 FormAssociatedElement::FormAssociatedElement()
-    : m_form(0)
+    : m_formWasSetByParser(false)
 {
 }
 
@@ -75,10 +75,9 @@
 
 void FormAssociatedElement::insertedInto(ContainerNode* insertionPoint)
 {
-    if (m_form && insertionPoint->highestAncestor() != m_form->highestAncestor())
-        setForm(0);
+    if (!m_formWasSetByParser || insertionPoint->highestAncestor() != m_form->highestAncestor())
+        resetFormOwner();
 
-    resetFormOwner();
     if (!insertionPoint->inDocument())
         return;
 
@@ -95,47 +94,62 @@
     // If the form and element are both in the same tree, preserve the connection to the form.
     // Otherwise, null out our form and remove ourselves from the form's list of elements.
     if (m_form && element->highestAncestor() != m_form->highestAncestor())
-        setForm(0);
+        resetFormOwner();
 }
 
-HTMLFormElement* FormAssociatedElement::findAssociatedForm(const HTMLElement* element, HTMLFormElement* currentAssociatedForm)
+HTMLFormElement* FormAssociatedElement::findAssociatedForm(const HTMLElement* element)
 {
     const AtomicString& formId(element->fastGetAttribute(formAttr));
+    // 3. If the element is reassociateable, has a form content attribute, and
+    // is itself in a Document, then run these substeps:
     if (!formId.isNull() && element->inDocument()) {
-        // The HTML5 spec says that the element should be associated with
-        // the first element in the document to have an ID that equal to
-        // the value of form attribute, so we put the result of
-        // treeScope()->getElementById() over the given element.
+        // 3.1. If the first element in the Document to have an ID that is
+        // case-sensitively equal to the element's form content attribute's
+        // value is a form element, then associate the form-associated element
+        // with that form element.
+        // 3.2. Abort the "reset the form owner" steps.
         HTMLFormElement* newForm = 0;
         Element* newFormCandidate = element->treeScope().getElementById(formId);
         if (newFormCandidate && newFormCandidate->hasTagName(formTag))
             newForm = toHTMLFormElement(newFormCandidate);
         return newForm;
     }
-
-    if (!currentAssociatedForm)
-        return element->findFormAncestor();
-
-    return currentAssociatedForm;
+    // 4. Otherwise, if the form-associated element in question has an ancestor
+    // form element, then associate the form-associated element with the nearest
+    // such ancestor form element.
+    return element->findFormAncestor();
 }
 
 void FormAssociatedElement::formRemovedFromTree(const Node* formRoot)
 {
     ASSERT(m_form);
-    if (toHTMLElement(this)->highestAncestor() != formRoot)
-        setForm(0);
+    if (toHTMLElement(this)->highestAncestor() == formRoot)
+        return;
+    resetFormOwner();
+}
+
+void FormAssociatedElement::associateByParser(HTMLFormElement* form)
+{
+    if (form && form->inDocument()) {
+        m_formWasSetByParser = true;
+        setForm(form);
+        form->didAssociateByParser();
+    }
 }
 
 void FormAssociatedElement::setForm(HTMLFormElement* newForm)
 {
-    if (m_form == newForm)
+    if (m_form.get() == newForm)
         return;
     willChangeForm();
     if (m_form)
-        m_form->removeFormElement(this);
-    m_form = newForm;
-    if (m_form)
-        m_form->registerFormElement(*this);
+        m_form->disassociate(*this);
+    if (newForm) {
+        m_form = newForm->createWeakPtr();
+        m_form->associate(*this);
+    } else {
+        m_form = WeakPtr<HTMLFormElement>();
+    }
     didChangeForm();
 }
 
@@ -147,41 +161,31 @@
 {
 }
 
-void FormAssociatedElement::formWillBeDestroyed()
-{
-    ASSERT(m_form);
-    if (!m_form)
-        return;
-    willChangeForm();
-    m_form = 0;
-    didChangeForm();
-}
-
 void FormAssociatedElement::resetFormOwner()
 {
-    HTMLFormElement* originalForm = m_form;
-    setForm(findAssociatedForm(toHTMLElement(this), m_form));
+    m_formWasSetByParser = false;
     HTMLElement* element = toHTMLElement(this);
-    if (m_form && m_form != originalForm && m_form->inDocument())
+    const AtomicString& formId(element->fastGetAttribute(formAttr));
+    HTMLFormElement* nearestForm = element->findFormAncestor();
+    // 1. If the element's form owner is not null, and either the element is not
+    // reassociateable or its form content attribute is not present, and the
+    // element's form owner is its nearest form element ancestor after the
+    // change to the ancestor chain, then do nothing, and abort these steps.
+    if (m_form && formId.isNull() && m_form.get() == nearestForm)
+        return;
+
+    HTMLFormElement* originalForm = m_form.get();
+    setForm(findAssociatedForm(element));
+    // FIXME: Move didAssociateFormControl call to didChangeForm or
+    // HTMLFormElement::associate.
+    if (m_form && m_form.get() != originalForm && m_form->inDocument())
         element->document().didAssociateFormControl(element);
 }
 
 void FormAssociatedElement::formAttributeChanged()
 {
-    HTMLElement* element = toHTMLElement(this);
-    if (!element->fastHasAttribute(formAttr)) {
-        // The form attribute removed. We need to reset form owner here.
-        HTMLFormElement* originalForm = m_form;
-        setForm(element->findFormAncestor());
-        HTMLElement* element = toHTMLElement(this);
-        if (m_form && m_form != originalForm && m_form->inDocument())
-            element->document().didAssociateFormControl(element);
-        m_formAttributeTargetObserver = nullptr;
-    } else {
-        resetFormOwner();
-        if (element->inDocument())
-            resetFormAttributeTargetObserver();
-    }
+    resetFormOwner();
+    resetFormAttributeTargetObserver();
 }
 
 bool FormAssociatedElement::customError() const
@@ -254,8 +258,12 @@
 
 void FormAssociatedElement::resetFormAttributeTargetObserver()
 {
-    ASSERT(toHTMLElement(this)->inDocument());
-    m_formAttributeTargetObserver = FormAttributeTargetObserver::create(toHTMLElement(this)->fastGetAttribute(formAttr), this);
+    HTMLElement* element = toHTMLElement(this);
+    const AtomicString& formId(element->fastGetAttribute(formAttr));
+    if (!formId.isNull() && element->inDocument())
+        m_formAttributeTargetObserver = FormAttributeTargetObserver::create(formId, this);
+    else
+        m_formAttributeTargetObserver = nullptr;
 }
 
 void FormAssociatedElement::formAttributeTargetChanged()
diff --git a/Source/core/html/FormAssociatedElement.h b/Source/core/html/FormAssociatedElement.h
index 15f2fa1..70101f5 100644
--- a/Source/core/html/FormAssociatedElement.h
+++ b/Source/core/html/FormAssociatedElement.h
@@ -24,6 +24,7 @@
 #ifndef FormAssociatedElement_h
 #define FormAssociatedElement_h
 
+#include "wtf/WeakPtr.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -46,8 +47,8 @@
     void ref() { refFormAssociatedElement(); }
     void deref() { derefFormAssociatedElement(); }
 
-    static HTMLFormElement* findAssociatedForm(const HTMLElement*, HTMLFormElement*);
-    HTMLFormElement* form() const { return m_form; }
+    static HTMLFormElement* findAssociatedForm(const HTMLElement*);
+    HTMLFormElement* form() const { return m_form.get(); }
     ValidityState* validity();
 
     virtual bool isFormControlElement() const = 0;
@@ -63,8 +64,6 @@
     // Return true for a successful control (see HTML4-17.13.2).
     virtual bool appendFormData(FormDataList&, bool) { return false; }
 
-    void formWillBeDestroyed();
-
     void resetFormOwner();
 
     void formRemovedFromTree(const Node* formRoot);
@@ -95,7 +94,10 @@
     void removedFrom(ContainerNode*);
     void didMoveToNewDocument(Document& oldDocument);
 
+    // FIXME: Remove usage of setForm. resetFormOwner should be enough, and
+    // setForm is confusing.
     void setForm(HTMLFormElement*);
+    void associateByParser(HTMLFormElement*);
     void formAttributeChanged();
 
     // If you add an override of willChangeForm() or didChangeForm() to a class
@@ -113,9 +115,11 @@
     void resetFormAttributeTargetObserver();
 
     OwnPtr<FormAttributeTargetObserver> m_formAttributeTargetObserver;
-    HTMLFormElement* m_form;
+    // m_form should be a strong reference in Oilpan.
+    WeakPtr<HTMLFormElement> m_form;
     OwnPtr<ValidityState> m_validityState;
     String m_customValidationMessage;
+    bool m_formWasSetByParser;
 };
 
 HTMLElement* toHTMLElement(FormAssociatedElement*);
diff --git a/Source/core/html/HTMLAllCollection.cpp b/Source/core/html/HTMLAllCollection.cpp
index 5fc4b8b..5e38017 100644
--- a/Source/core/html/HTMLAllCollection.cpp
+++ b/Source/core/html/HTMLAllCollection.cpp
@@ -31,12 +31,12 @@
 
 namespace WebCore {
 
-PassRefPtr<HTMLAllCollection> HTMLAllCollection::create(Node* node, CollectionType type)
+PassRefPtr<HTMLAllCollection> HTMLAllCollection::create(ContainerNode* node, CollectionType type)
 {
     return adoptRef(new HTMLAllCollection(node, type));
 }
 
-HTMLAllCollection::HTMLAllCollection(Node* node, CollectionType type)
+HTMLAllCollection::HTMLAllCollection(ContainerNode* node, CollectionType type)
     : HTMLCollection(node, type, DoesNotOverrideItemAfter)
 {
     ScriptWrappable::init(this);
@@ -46,9 +46,9 @@
 {
 }
 
-Node* HTMLAllCollection::namedItemWithIndex(const AtomicString& name, unsigned index) const
+Element* HTMLAllCollection::namedItemWithIndex(const AtomicString& name, unsigned index) const
 {
-    updateNameCache();
+    updateIdNameCache();
 
     if (Vector<Element*>* cache = idCache(name)) {
         if (index < cache->size())
@@ -64,9 +64,9 @@
     return 0;
 }
 
-void HTMLAllCollection::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<NodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Node>& returnValue1)
+void HTMLAllCollection::namedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<NodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Element>& returnValue1)
 {
-    Vector<RefPtr<Node> > namedItems;
+    Vector<RefPtr<Element> > namedItems;
     this->namedItems(name, namedItems);
 
     if (!namedItems.size())
@@ -84,9 +84,4 @@
     returnValue0 = NamedNodesCollection::create(namedItems);
 }
 
-PassRefPtr<NodeList> HTMLAllCollection::tags(const String& name)
-{
-    return ownerNode()->getElementsByTagName(name);
-}
-
 } // namespace WebCore
diff --git a/Source/core/html/HTMLAllCollection.h b/Source/core/html/HTMLAllCollection.h
index d5f1106..010a44b 100644
--- a/Source/core/html/HTMLAllCollection.h
+++ b/Source/core/html/HTMLAllCollection.h
@@ -32,15 +32,14 @@
 
 class HTMLAllCollection FINAL : public HTMLCollection {
 public:
-    static PassRefPtr<HTMLAllCollection> create(Node*, CollectionType);
+    static PassRefPtr<HTMLAllCollection> create(ContainerNode*, CollectionType);
     virtual ~HTMLAllCollection();
 
-    Node* namedItemWithIndex(const AtomicString& name, unsigned index) const;
-    void anonymousNamedGetter(const AtomicString& name, bool&, RefPtr<NodeList>&, bool&, RefPtr<Node>&);
-    PassRefPtr<NodeList> tags(const String&);
+    Element* namedItemWithIndex(const AtomicString& name, unsigned index) const;
+    void namedGetter(const AtomicString& name, bool&, RefPtr<NodeList>&, bool&, RefPtr<Element>&);
 
 private:
-    HTMLAllCollection(Node*, CollectionType);
+    HTMLAllCollection(ContainerNode*, CollectionType);
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLAllCollection.idl b/Source/core/html/HTMLAllCollection.idl
index 3508f8b..5ca9c6b 100644
--- a/Source/core/html/HTMLAllCollection.idl
+++ b/Source/core/html/HTMLAllCollection.idl
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,17 +24,15 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+// FIXME: This interface should inherit HTMLCollection.
 [
     Custom=LegacyCallAsFunction,
     DependentLifetime,
-    GenerateVisitDOMWrapper=ownerNode,
+    SetWrapperReferenceFrom=ownerNode,
 ] interface HTMLAllCollection {
     readonly attribute unsigned long length;
-    [ImplementedAs=item] getter Node (unsigned long index);
-    [Custom] Node item([Default=Undefined] optional unsigned long index);
-    [ImplementedAs=anonymousNamedGetter, NotEnumerable] getter (NodeList or Node)(DOMString name);
-    [Custom] Node namedItem(DOMString name);
-    // FIXME: This should return an HTMLAllCollection.
-    [MeasureAs=DocumentAllTags] NodeList tags(DOMString name);
+    [ImplementedAs=item] getter Element (unsigned long index);
+    [Custom] Element item([Default=Undefined] optional unsigned long index);
+    // FIXME: This should return an (HTMLCollection or Element) union.
+    [ImplementedAs=namedGetter] getter (NodeList or Element) namedItem(DOMString name);
 };
-
diff --git a/Source/core/html/HTMLAnchorElement.cpp b/Source/core/html/HTMLAnchorElement.cpp
index d1687ce..47990fa 100644
--- a/Source/core/html/HTMLAnchorElement.cpp
+++ b/Source/core/html/HTMLAnchorElement.cpp
@@ -30,6 +30,8 @@
 #include "core/events/MouseEvent.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
@@ -40,8 +42,6 @@
 #include "core/loader/PingLoader.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
 #include "core/rendering/RenderImage.h"
 #include "core/svg/graphics/SVGImage.h"
 #include "platform/PlatformMouseEvent.h"
@@ -152,16 +152,13 @@
 
 bool HTMLAnchorElement::isKeyboardFocusable() const
 {
+    ASSERT(document().isActive());
+
     if (isFocusable() && Element::supportsFocus())
         return HTMLElement::isKeyboardFocusable();
 
-    if (isLink()) {
-        Page* page = document().page();
-        if (!page)
-            return false;
-        if (!page->chrome().client().tabsToLinks())
-            return false;
-    }
+    if (isLink() && !document().frameHost()->chrome().client().tabsToLinks())
+        return false;
     return HTMLElement::isKeyboardFocusable();
 }
 
@@ -349,7 +346,7 @@
 
 void HTMLAnchorElement::setInput(const String& value)
 {
-    setHref(value);
+    setHref(AtomicString(value));
 }
 
 bool HTMLAnchorElement::hasRel(uint32_t relation) const
@@ -357,7 +354,7 @@
     return m_linkRelations & relation;
 }
 
-void HTMLAnchorElement::setRel(const String& value)
+void HTMLAnchorElement::setRel(const AtomicString& value)
 {
     m_linkRelations = 0;
     SpaceSplitString newLinkRelations(value, true);
@@ -377,7 +374,7 @@
     return Element::tabIndex();
 }
 
-String HTMLAnchorElement::target() const
+AtomicString HTMLAnchorElement::target() const
 {
     return getAttribute(targetAttr);
 }
@@ -425,14 +422,14 @@
         frame->loader().client()->dispatchWillRequestAfterPreconnect(request);
     if (hasAttribute(downloadAttr)) {
         if (!hasRel(RelationNoReferrer)) {
-            String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), completedURL, frame->loader().outgoingReferrer());
+            String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), completedURL, document().outgoingReferrer());
             if (!referrer.isEmpty())
-                request.setHTTPReferrer(referrer);
+                request.setHTTPReferrer(Referrer(referrer, document().referrerPolicy()));
         }
 
         frame->loader().client()->loadURLExternally(request, NavigationPolicyDownload, fastGetAttribute(downloadAttr));
     } else {
-        FrameLoadRequest frameRequest(document().securityOrigin(), request, target());
+        FrameLoadRequest frameRequest(&document(), request, target());
         frameRequest.setTriggeringEvent(event);
         if (hasRel(RelationNoReferrer))
             frameRequest.setShouldSendReferrer(NeverSendReferrer);
@@ -695,7 +692,7 @@
 
 bool HTMLAnchorElement::isInteractiveContent() const
 {
-    return true;
+    return isLink();
 }
 
 }
diff --git a/Source/core/html/HTMLAnchorElement.h b/Source/core/html/HTMLAnchorElement.h
index bfb0d63..9907b8e 100644
--- a/Source/core/html/HTMLAnchorElement.h
+++ b/Source/core/html/HTMLAnchorElement.h
@@ -66,20 +66,20 @@
 
     const AtomicString& name() const;
 
-    virtual KURL url() const OVERRIDE;
-    virtual void setURL(const KURL&) OVERRIDE;
+    virtual KURL url() const OVERRIDE FINAL;
+    virtual void setURL(const KURL&) OVERRIDE FINAL;
 
-    virtual String input() const OVERRIDE;
-    virtual void setInput(const String&) OVERRIDE;
+    virtual String input() const OVERRIDE FINAL;
+    virtual void setInput(const String&) OVERRIDE FINAL;
 
     String text();
 
     bool isLiveLink() const;
 
-    virtual bool willRespondToMouseClickEvents() OVERRIDE;
+    virtual bool willRespondToMouseClickEvents() OVERRIDE FINAL;
 
     bool hasRel(uint32_t relation) const;
-    void setRel(const String&);
+    void setRel(const AtomicString&);
 
     LinkHash visitedLinkHash() const;
     void invalidateCachedVisitedLinkHash() { m_cachedVisitedLinkHash = 0; }
@@ -90,21 +90,20 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
 private:
-    virtual bool supportsFocus() const;
-    virtual bool isMouseFocusable() const;
+    virtual bool supportsFocus() const OVERRIDE;
+    virtual bool isMouseFocusable() const OVERRIDE;
     virtual bool isKeyboardFocusable() const OVERRIDE;
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE FINAL;
     virtual void setActive(bool = true) OVERRIDE FINAL;
-    virtual void accessKeyAction(bool sendMouseEvents);
-    virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
-    virtual bool canStartSelection() const;
-    virtual String target() const;
-    virtual short tabIndex() const;
-    virtual bool draggable() const;
-    virtual bool isInteractiveContent() const OVERRIDE;
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE FINAL;
+    virtual bool isURLAttribute(const Attribute&) const OVERRIDE FINAL;
+    virtual bool canStartSelection() const OVERRIDE FINAL;
+    virtual short tabIndex() const OVERRIDE FINAL;
+    virtual bool draggable() const OVERRIDE FINAL;
+    virtual bool isInteractiveContent() const OVERRIDE FINAL;
 
     void sendPings(const KURL& destinationURL);
-
+    AtomicString target() const;
     void handleClick(Event*);
 
     enum EventType {
@@ -141,21 +140,6 @@
 bool isEnterKeyKeydownEvent(Event*);
 bool isLinkClick(Event*);
 
-inline bool isHTMLAnchorElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::aTag);
-}
-
-inline bool isHTMLAnchorElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::aTag);
-}
-
-inline bool isHTMLAnchorElement(const Element& element)
-{
-    return element.hasTagName(HTMLNames::aTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLAnchorElement, hasTagName(HTMLNames::aTag));
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLAnchorElement.idl b/Source/core/html/HTMLAnchorElement.idl
index 525c307..57519bd 100644
--- a/Source/core/html/HTMLAnchorElement.idl
+++ b/Source/core/html/HTMLAnchorElement.idl
@@ -34,5 +34,4 @@
     readonly attribute DOMString text;
 };
 
-// force rebuild: crbug.com/307023
 HTMLAnchorElement implements URLUtils;
diff --git a/Source/core/html/HTMLAppletElement.cpp b/Source/core/html/HTMLAppletElement.cpp
index 66d1e58..242e2ea 100644
--- a/Source/core/html/HTMLAppletElement.cpp
+++ b/Source/core/html/HTMLAppletElement.cpp
@@ -31,7 +31,7 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderApplet.h"
 #include "platform/Widget.h"
 #include "platform/weborigin/KURL.h"
@@ -206,7 +206,7 @@
     if (!settings)
         return false;
 
-    if (!settings->isJavaEnabled())
+    if (!settings->javaEnabled())
         return false;
 
     return true;
diff --git a/Source/core/html/HTMLAreaElement.cpp b/Source/core/html/HTMLAreaElement.cpp
index 73cd5fb..4c1ce23 100644
--- a/Source/core/html/HTMLAreaElement.cpp
+++ b/Source/core/html/HTMLAreaElement.cpp
@@ -28,6 +28,7 @@
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderView.h"
+#include "platform/LengthFunctions.h"
 #include "platform/graphics/Path.h"
 #include "platform/transforms/AffineTransform.h"
 
@@ -141,30 +142,29 @@
     }
 
     Path path;
-    RenderView* renderView = document().renderView();
     switch (shape) {
         case Poly:
             if (m_coords.size() >= 6) {
                 int numPoints = m_coords.size() / 2;
-                path.moveTo(FloatPoint(minimumValueForLength(m_coords[0], width, renderView), minimumValueForLength(m_coords[1], height, renderView)));
+                path.moveTo(FloatPoint(minimumValueForLength(m_coords[0], width), minimumValueForLength(m_coords[1], height)));
                 for (int i = 1; i < numPoints; ++i)
-                    path.addLineTo(FloatPoint(minimumValueForLength(m_coords[i * 2], width, renderView), minimumValueForLength(m_coords[i * 2 + 1], height, renderView)));
+                    path.addLineTo(FloatPoint(minimumValueForLength(m_coords[i * 2], width), minimumValueForLength(m_coords[i * 2 + 1], height)));
                 path.closeSubpath();
             }
             break;
         case Circle:
             if (m_coords.size() >= 3) {
                 Length radius = m_coords[2];
-                int r = min(minimumValueForLength(radius, width, renderView), minimumValueForLength(radius, height, renderView));
-                path.addEllipse(FloatRect(minimumValueForLength(m_coords[0], width, renderView) - r, minimumValueForLength(m_coords[1], height, renderView) - r, 2 * r, 2 * r));
+                int r = min(minimumValueForLength(radius, width), minimumValueForLength(radius, height));
+                path.addEllipse(FloatRect(minimumValueForLength(m_coords[0], width) - r, minimumValueForLength(m_coords[1], height) - r, 2 * r, 2 * r));
             }
             break;
         case Rect:
             if (m_coords.size() >= 4) {
-                int x0 = minimumValueForLength(m_coords[0], width, renderView);
-                int y0 = minimumValueForLength(m_coords[1], height, renderView);
-                int x1 = minimumValueForLength(m_coords[2], width, renderView);
-                int y1 = minimumValueForLength(m_coords[3], height, renderView);
+                int x0 = minimumValueForLength(m_coords[0], width);
+                int y0 = minimumValueForLength(m_coords[1], height);
+                int x1 = minimumValueForLength(m_coords[2], width);
+                int y1 = minimumValueForLength(m_coords[3], height);
                 path.addRect(FloatRect(x0, y0, x1 - x0, y1 - y0));
             }
             break;
@@ -246,9 +246,4 @@
     return isLink();
 }
 
-String HTMLAreaElement::target() const
-{
-    return getAttribute(targetAttr);
-}
-
 }
diff --git a/Source/core/html/HTMLAreaElement.h b/Source/core/html/HTMLAreaElement.h
index 35f3438..0029fb9 100644
--- a/Source/core/html/HTMLAreaElement.h
+++ b/Source/core/html/HTMLAreaElement.h
@@ -50,12 +50,11 @@
     explicit HTMLAreaElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool supportsFocus() const;
-    virtual String target() const;
+    virtual bool supportsFocus() const OVERRIDE;
     virtual bool isKeyboardFocusable() const OVERRIDE;
-    virtual bool isMouseFocusable() const;
+    virtual bool isMouseFocusable() const OVERRIDE;
     virtual bool rendererIsFocusable() const OVERRIDE;
-    virtual void updateFocusAppearance(bool /*restorePreviousSelection*/);
+    virtual void updateFocusAppearance(bool /*restorePreviousSelection*/) OVERRIDE;
     virtual void setFocus(bool) OVERRIDE;
 
     enum Shape { Default, Poly, Rect, Circle, Unknown };
@@ -68,16 +67,6 @@
     Shape m_shape;
 };
 
-inline bool isHTMLAreaElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::areaTag);
-}
-
-inline bool isHTMLAreaElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::areaTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLAreaElement, hasTagName(HTMLNames::areaTag));
 
 } //namespace
diff --git a/Source/core/html/HTMLAreaElement.idl b/Source/core/html/HTMLAreaElement.idl
index 1ad7233..471e583 100644
--- a/Source/core/html/HTMLAreaElement.idl
+++ b/Source/core/html/HTMLAreaElement.idl
@@ -27,5 +27,4 @@
     [Reflect] attribute DOMString target;
 };
 
-// force rebuild: crbug.com/307023
 HTMLAreaElement implements URLUtils;
diff --git a/Source/core/html/HTMLAttributeNames.in b/Source/core/html/HTMLAttributeNames.in
index 4ae7745..4686e8e 100644
--- a/Source/core/html/HTMLAttributeNames.in
+++ b/Source/core/html/HTMLAttributeNames.in
@@ -307,7 +307,6 @@
 scrollamount
 scrolldelay
 scrolling
-seamless
 select
 selected
 shape
diff --git a/Source/core/html/HTMLAudioElement.cpp b/Source/core/html/HTMLAudioElement.cpp
index bdc0d9f..30764e5 100644
--- a/Source/core/html/HTMLAudioElement.cpp
+++ b/Source/core/html/HTMLAudioElement.cpp
@@ -32,23 +32,23 @@
 
 using namespace HTMLNames;
 
-HTMLAudioElement::HTMLAudioElement(Document& document, bool createdByParser)
-    : HTMLMediaElement(audioTag, document, createdByParser)
+HTMLAudioElement::HTMLAudioElement(Document& document)
+    : HTMLMediaElement(audioTag, document)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLAudioElement> HTMLAudioElement::create(Document& document, bool createdByParser)
+PassRefPtr<HTMLAudioElement> HTMLAudioElement::create(Document& document)
 {
-    RefPtr<HTMLAudioElement> audioElement(adoptRef(new HTMLAudioElement(document, createdByParser)));
+    RefPtr<HTMLAudioElement> audioElement(adoptRef(new HTMLAudioElement(document)));
     audioElement->suspendIfNeeded();
     return audioElement.release();
 }
 
 PassRefPtr<HTMLAudioElement> HTMLAudioElement::createForJSConstructor(Document& document, const AtomicString& src)
 {
-    RefPtr<HTMLAudioElement> audio = adoptRef(new HTMLAudioElement(document, false));
-    audio->setPreload("auto");
+    RefPtr<HTMLAudioElement> audio = adoptRef(new HTMLAudioElement(document));
+    audio->setPreload(AtomicString("auto", AtomicString::ConstructFromLiteral));
     if (!src.isNull())
         audio->setSrc(src);
     audio->suspendIfNeeded();
diff --git a/Source/core/html/HTMLAudioElement.h b/Source/core/html/HTMLAudioElement.h
index c69a305..d05c907 100644
--- a/Source/core/html/HTMLAudioElement.h
+++ b/Source/core/html/HTMLAudioElement.h
@@ -35,11 +35,11 @@
 
 class HTMLAudioElement FINAL : public HTMLMediaElement {
 public:
-    static PassRefPtr<HTMLAudioElement> create(Document&, bool);
+    static PassRefPtr<HTMLAudioElement> create(Document&);
     static PassRefPtr<HTMLAudioElement> createForJSConstructor(Document&, const AtomicString& src);
 
 private:
-    HTMLAudioElement(Document&, bool);
+    HTMLAudioElement(Document&);
 
     virtual bool isVideo() const OVERRIDE { return false; }
 };
diff --git a/Source/core/html/HTMLBRElement.h b/Source/core/html/HTMLBRElement.h
index 0188c71..483e5cd 100644
--- a/Source/core/html/HTMLBRElement.h
+++ b/Source/core/html/HTMLBRElement.h
@@ -32,7 +32,7 @@
 public:
     static PassRefPtr<HTMLBRElement> create(Document&);
 
-    virtual bool canContainRangeEndPoint() const { return false; }
+    virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
 
 private:
     explicit HTMLBRElement(Document&);
@@ -40,7 +40,7 @@
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 };
 
 } // namespace
diff --git a/Source/core/html/HTMLBaseElement.cpp b/Source/core/html/HTMLBaseElement.cpp
index 6ec6654..2e7d353 100644
--- a/Source/core/html/HTMLBaseElement.cpp
+++ b/Source/core/html/HTMLBaseElement.cpp
@@ -26,8 +26,8 @@
 #include "HTMLNames.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/Document.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/html/parser/HTMLParserIdioms.h"
+#include "core/html/parser/TextResourceDecoder.h"
 
 namespace WebCore {
 
@@ -72,11 +72,6 @@
     return attribute.name().localName() == hrefAttr || HTMLElement::isURLAttribute(attribute);
 }
 
-String HTMLBaseElement::target() const
-{
-    return fastGetAttribute(targetAttr);
-}
-
 KURL HTMLBaseElement::href() const
 {
     // This does not use the getURLAttribute function because that will resolve relative to the document's base URL;
diff --git a/Source/core/html/HTMLBaseElement.h b/Source/core/html/HTMLBaseElement.h
index 39c8bfe..1c511de 100644
--- a/Source/core/html/HTMLBaseElement.h
+++ b/Source/core/html/HTMLBaseElement.h
@@ -37,7 +37,6 @@
 private:
     explicit HTMLBaseElement(Document&);
 
-    virtual String target() const;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
diff --git a/Source/core/html/HTMLBodyElement.cpp b/Source/core/html/HTMLBodyElement.cpp
index 44a1572..a0024d2 100644
--- a/Source/core/html/HTMLBodyElement.cpp
+++ b/Source/core/html/HTMLBodyElement.cpp
@@ -28,7 +28,7 @@
 #include "HTMLNames.h"
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/css/CSSImageValue.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/Attribute.h"
 #include "core/events/ThreadLocalEventNames.h"
@@ -36,6 +36,7 @@
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
+#include "core/rendering/RenderBox.h"
 
 namespace WebCore {
 
@@ -68,7 +69,7 @@
     if (name == backgroundAttr) {
         String url = stripLeadingAndTrailingHTMLSpaces(value);
         if (!url.isEmpty()) {
-            RefPtr<CSSImageValue> imageValue = CSSImageValue::create(document().completeURL(url).string());
+            RefPtrWillBeRawPtr<CSSImageValue> imageValue = CSSImageValue::create(document().completeURL(url));
             imageValue->setInitiator(localName());
             style->setProperty(CSSProperty(CSSPropertyBackgroundImage, imageValue.release()));
         }
@@ -101,7 +102,7 @@
                 document().textLinkColors().resetActiveLinkColor();
         } else {
             RGBA32 color;
-            if (CSSParser::parseColor(color, value, !document().inQuirksMode())) {
+            if (BisonCSSParser::parseColor(color, value, !document().inQuirksMode())) {
                 if (name == linkAttr)
                     document().textLinkColors().setLinkColor(color);
                 else if (name == vlinkAttr)
@@ -111,7 +112,7 @@
             }
         }
 
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
     } else if (name == onloadAttr)
         document().setWindowAttributeEventListener(EventTypeNames::load, createAttributeEventListener(document().frame(), name, value));
     else if (name == onbeforeunloadAttr)
@@ -130,10 +131,8 @@
         document().setWindowAttributeEventListener(EventTypeNames::error, createAttributeEventListener(document().frame(), name, value));
     else if (name == onfocusAttr)
         document().setWindowAttributeEventListener(EventTypeNames::focus, createAttributeEventListener(document().frame(), name, value));
-#if ENABLE(ORIENTATION_EVENTS)
-    else if (name == onorientationchangeAttr)
+    else if (RuntimeEnabledFeatures::orientationEventEnabled() && name == onorientationchangeAttr)
         document().setWindowAttributeEventListener(EventTypeNames::orientationchange, createAttributeEventListener(document().frame(), name, value));
-#endif
     else if (name == onhashchangeAttr)
         document().setWindowAttributeEventListener(EventTypeNames::hashchange, createAttributeEventListener(document().frame(), name, value));
     else if (name == onmessageAttr)
@@ -199,17 +198,28 @@
     return static_cast<int>(value / zoomFactor);
 }
 
-// FIXME: There are cases where body.scrollLeft is allowed to return
-// non-zero values in both quirks and strict mode. It happens when
-// <body> has an overflow that is not the Frame overflow.
-// http://dev.w3.org/csswg/cssom-view/#dom-element-scrollleft
-// http://code.google.com/p/chromium/issues/detail?id=312435
+// Blink, Gecko and Presto's quirks mode implementations of overflow set to the
+// body element differ from IE's: the formers can create a scrollable area for the
+// body element that is not the same as the root elements's one. On IE's quirks mode
+// though, as body is the root element, body's and the root element's scrollable areas,
+// if any, are the same.
+// In order words, a <body> will only have an overflow clip (that differs from
+// documentElement's) if  both html and body nodes have its overflow set to either hidden,
+// auto or scroll.
+// That said, Blink's {set}scroll{Top,Left} behaviors match Gecko's: even if there is a non-overflown
+// scrollable area, scrolling should not get propagated to the viewport in neither strict
+// or quirks modes.
 int HTMLBodyElement::scrollLeft()
 {
     Document& document = this->document();
     document.updateLayoutIgnorePendingStylesheets();
 
     if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+        RenderBox* render = renderBox();
+        if (!render)
+            return 0;
+        if (render->hasOverflowClip())
+            return adjustForAbsoluteZoom(render->scrollLeft(), render);
         if (!document.inQuirksMode())
             return 0;
     }
@@ -224,6 +234,14 @@
     document.updateLayoutIgnorePendingStylesheets();
 
     if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+        RenderBox* render = renderBox();
+        if (!render)
+            return;
+        if (render->hasOverflowClip()) {
+            // FIXME: Investigate how are other browsers casting to int (rounding, ceiling, ...).
+            render->setScrollLeft(static_cast<int>(scrollLeft * render->style()->effectiveZoom()));
+            return;
+        }
         if (!document.inQuirksMode())
             return;
     }
@@ -243,6 +261,11 @@
     document.updateLayoutIgnorePendingStylesheets();
 
     if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+        RenderBox* render = renderBox();
+        if (!render)
+            return 0;
+        if (render->hasOverflowClip())
+            return adjustForAbsoluteZoom(render->scrollTop(), render);
         if (!document.inQuirksMode())
             return 0;
     }
@@ -257,6 +280,14 @@
     document.updateLayoutIgnorePendingStylesheets();
 
     if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+        RenderBox* render = renderBox();
+        if (!render)
+            return;
+        if (render->hasOverflowClip()) {
+            // FIXME: Investigate how are other browsers casting to int (rounding, ceiling, ...).
+            render->setScrollTop(static_cast<int>(scrollTop * render->style()->effectiveZoom()));
+            return;
+        }
         if (!document.inQuirksMode())
             return;
     }
@@ -288,11 +319,4 @@
     return view ? adjustForZoom(view->contentsWidth(), &document) : 0;
 }
 
-void HTMLBodyElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, document().completeURL(getAttribute(backgroundAttr)));
-}
-
 } // namespace WebCore
diff --git a/Source/core/html/HTMLBodyElement.h b/Source/core/html/HTMLBodyElement.h
index d7a5c45..fa247ff 100644
--- a/Source/core/html/HTMLBodyElement.h
+++ b/Source/core/html/HTMLBodyElement.h
@@ -39,11 +39,9 @@
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load);
+    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll);
-
-#if ENABLE(ORIENTATION_EVENTS)
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange);
-#endif
 
 private:
     explicit HTMLBodyElement(Document&);
@@ -56,18 +54,16 @@
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 
-    virtual bool supportsFocus() const;
+    virtual bool supportsFocus() const OVERRIDE;
 
-    virtual int scrollLeft();
-    virtual void setScrollLeft(int scrollLeft);
+    virtual int scrollLeft() OVERRIDE;
+    virtual void setScrollLeft(int) OVERRIDE;
 
-    virtual int scrollTop();
-    virtual void setScrollTop(int scrollTop);
+    virtual int scrollTop() OVERRIDE;
+    virtual void setScrollTop(int) OVERRIDE;
 
-    virtual int scrollHeight();
-    virtual int scrollWidth();
-
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
+    virtual int scrollHeight() OVERRIDE;
+    virtual int scrollWidth() OVERRIDE;
 };
 
 DEFINE_NODE_TYPE_CASTS(HTMLBodyElement, hasTagName(HTMLNames::bodyTag));
diff --git a/Source/core/html/HTMLBodyElement.idl b/Source/core/html/HTMLBodyElement.idl
index 139b34a..6f454c6 100644
--- a/Source/core/html/HTMLBodyElement.idl
+++ b/Source/core/html/HTMLBodyElement.idl
@@ -26,13 +26,14 @@
     [Reflect, TreatNullAs=NullString] attribute DOMString text;
     [Reflect, TreatNullAs=NullString] attribute DOMString vLink;
 
-    [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
+    [RuntimeEnabled=OrientationEvent] attribute EventHandler onorientationchange;
 
     // Overrides of GlobalEventHandler attributes
     attribute EventHandler onblur;
     attribute EventHandler onerror;
     attribute EventHandler onfocus;
     attribute EventHandler onload;
+    attribute EventHandler onresize;
     attribute EventHandler onscroll;
 };
 
diff --git a/Source/core/html/HTMLButtonElement.cpp b/Source/core/html/HTMLButtonElement.cpp
index 4b3c235..8e9ad8c 100644
--- a/Source/core/html/HTMLButtonElement.cpp
+++ b/Source/core/html/HTMLButtonElement.cpp
@@ -209,4 +209,9 @@
     return true;
 }
 
+bool HTMLButtonElement::supportsAutofocus() const
+{
+    return true;
+}
+
 } // namespace
diff --git a/Source/core/html/HTMLButtonElement.h b/Source/core/html/HTMLButtonElement.h
index 5032c38..a2328e7 100644
--- a/Source/core/html/HTMLButtonElement.h
+++ b/Source/core/html/HTMLButtonElement.h
@@ -43,34 +43,35 @@
 
     enum Type { SUBMIT, RESET, BUTTON };
 
-    virtual const AtomicString& formControlType() const;
+    virtual const AtomicString& formControlType() const OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     // HTMLFormControlElement always creates one, but buttons don't need it.
     virtual bool alwaysCreateUserAgentShadowRoot() const OVERRIDE { return false; }
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
 
-    virtual bool appendFormData(FormDataList&, bool);
+    virtual bool appendFormData(FormDataList&, bool) OVERRIDE;
 
-    virtual bool isEnumeratable() const { return true; }
+    virtual bool isEnumeratable() const OVERRIDE { return true; }
     virtual bool supportLabels() const OVERRIDE { return true; }
     virtual bool isInteractiveContent() const OVERRIDE;
+    virtual bool supportsAutofocus() const OVERRIDE;
 
     virtual bool canBeSuccessfulSubmitButton() const OVERRIDE;
-    virtual bool isActivatedSubmit() const;
-    virtual void setActivatedSubmit(bool flag);
+    virtual bool isActivatedSubmit() const OVERRIDE;
+    virtual void setActivatedSubmit(bool flag) OVERRIDE;
 
-    virtual void accessKeyAction(bool sendMouseEvents);
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 
-    virtual bool canStartSelection() const { return false; }
+    virtual bool canStartSelection() const OVERRIDE { return false; }
 
-    virtual bool isOptionalFormControl() const { return true; }
-    virtual bool recalcWillValidate() const;
+    virtual bool isOptionalFormControl() const OVERRIDE { return true; }
+    virtual bool recalcWillValidate() const OVERRIDE;
 
     Type m_type;
     bool m_isActivatedSubmit;
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index 8541dbb..c07e0d3 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -42,7 +42,7 @@
 #include "core/html/canvas/WebGLContextAttributes.h"
 #include "core/html/canvas/WebGLRenderingContext.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderHTMLCanvas.h"
 #include "platform/MIMETypeRegistry.h"
 #include "platform/graphics/Canvas2DImageBufferSurface.h"
@@ -50,6 +50,7 @@
 #include "platform/graphics/ImageBuffer.h"
 #include "platform/graphics/UnacceleratedImageBufferSurface.h"
 #include "platform/graphics/gpu/WebGLImageBufferSurface.h"
+#include "platform/transforms/AffineTransform.h"
 #include "public/platform/Platform.h"
 
 namespace WebCore {
@@ -70,6 +71,7 @@
 
 HTMLCanvasElement::HTMLCanvasElement(Document& document)
     : HTMLElement(canvasTag, document)
+    , DocumentVisibilityObserver(document)
     , m_size(DefaultWidth, DefaultHeight)
     , m_rendererIsCanvas(false)
     , m_ignoreReset(false)
@@ -350,8 +352,7 @@
 {
     m_size = size;
     m_didFailToCreateImageBuffer = false;
-    m_contextStateSaver.clear();
-    m_imageBuffer.clear();
+    discardImageBuffer();
     setExternallyAllocatedMemory(0);
     clearCopiedImage();
 }
@@ -447,6 +448,7 @@
 void HTMLCanvasElement::createImageBuffer()
 {
     ASSERT(!m_imageBuffer);
+    ASSERT(!m_contextStateSaver);
 
     m_didFailToCreateImageBuffer = true;
     m_didClearImageBuffer = true;
@@ -473,7 +475,6 @@
 
     if (is3D()) {
         // Early out for WebGL canvases
-        m_contextStateSaver.clear();
         return;
     }
 
@@ -523,6 +524,16 @@
     return m_imageBuffer.get();
 }
 
+void HTMLCanvasElement::ensureUnacceleratedImageBuffer()
+{
+    if ((hasImageBuffer() && !m_imageBuffer->isAccelerated()) || m_didFailToCreateImageBuffer)
+        return;
+    discardImageBuffer();
+    OpacityMode opacityMode = !m_context || m_context->hasAlpha() ? NonOpaque : Opaque;
+    m_imageBuffer = ImageBuffer::create(size(), opacityMode);
+    m_didFailToCreateImageBuffer = !m_imageBuffer;
+}
+
 Image* HTMLCanvasElement::copiedImage() const
 {
     if (!m_copiedImage && buffer()) {
@@ -548,6 +559,12 @@
     }
 }
 
+void HTMLCanvasElement::discardImageBuffer()
+{
+    m_contextStateSaver.clear(); // uses context owned by m_imageBuffer
+    m_imageBuffer.clear();
+}
+
 void HTMLCanvasElement::clearCopiedImage()
 {
     m_copiedImage.clear();
@@ -560,4 +577,26 @@
     return m_imageBuffer->baseTransform();
 }
 
+void HTMLCanvasElement::didChangeVisibilityState(PageVisibilityState visibility)
+{
+    if (hasImageBuffer()) {
+        bool hidden = visibility != PageVisibilityStateVisible;
+        if (hidden) {
+            clearCopiedImage();
+            if (is3D()) {
+                discardImageBuffer();
+            }
+        }
+        if (hasImageBuffer()) {
+            m_imageBuffer->setIsHidden(hidden);
+        }
+    }
+}
+
+void HTMLCanvasElement::didMoveToNewDocument(Document& oldDocument)
+{
+    setObservedDocument(document());
+    HTMLElement::didMoveToNewDocument(oldDocument);
+}
+
 }
diff --git a/Source/core/html/HTMLCanvasElement.h b/Source/core/html/HTMLCanvasElement.h
index fa7ad1e..e5e6723 100644
--- a/Source/core/html/HTMLCanvasElement.h
+++ b/Source/core/html/HTMLCanvasElement.h
@@ -31,12 +31,14 @@
 #include "core/html/HTMLElement.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/geometry/IntSize.h"
+#include "platform/graphics/Canvas2DLayerBridge.h"
 #include "wtf/Forward.h"
 
 #define DefaultInterpolationQuality InterpolationMedium
 
 namespace WebCore {
 
+class AffineTransform;
 class CanvasContextAttributes;
 class CanvasRenderingContext;
 class GraphicsContext;
@@ -57,7 +59,7 @@
     virtual void canvasDestroyed(HTMLCanvasElement*) = 0;
 };
 
-class HTMLCanvasElement FINAL : public HTMLElement {
+class HTMLCanvasElement FINAL : public HTMLElement, public DocumentVisibilityObserver {
 public:
     static PassRefPtr<HTMLCanvasElement> create(Document&);
     virtual ~HTMLCanvasElement();
@@ -104,6 +106,7 @@
 
     CanvasRenderingContext* renderingContext() const { return m_context.get(); }
 
+    void ensureUnacceleratedImageBuffer();
     ImageBuffer* buffer() const;
     Image* copiedImage() const;
     void clearCopiedImage();
@@ -123,13 +126,19 @@
 
     bool shouldAccelerate(const IntSize&) const;
 
-    InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
+    virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
+
+    // DocumentVisibilityObserver implementation
+    virtual void didChangeVisibilityState(PageVisibilityState) OVERRIDE;
+
+protected:
+    virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
 
 private:
     explicit HTMLCanvasElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
 
     void reset();
@@ -137,6 +146,7 @@
     PassOwnPtr<ImageBufferSurface> createImageBufferSurface(const IntSize& deviceSize, int* msaaSampleCount);
     void createImageBuffer();
     void clearImageBuffer();
+    void discardImageBuffer();
 
     void setSurfaceSize(const IntSize&);
 
diff --git a/Source/core/html/HTMLCollection.cpp b/Source/core/html/HTMLCollection.cpp
index a0edbbc..e332fb7 100644
--- a/Source/core/html/HTMLCollection.cpp
+++ b/Source/core/html/HTMLCollection.cpp
@@ -2,6 +2,7 @@
  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -24,7 +25,7 @@
 #include "core/html/HTMLCollection.h"
 
 #include "HTMLNames.h"
-#include "core/dom/ClassNodeList.h"
+#include "core/dom/ClassCollection.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/NodeList.h"
 #include "core/dom/NodeRareData.h"
@@ -32,14 +33,18 @@
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/HTMLOptionElement.h"
+#include "wtf/HashSet.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
-static bool shouldOnlyIncludeDirectChildren(CollectionType type)
+static bool shouldTypeOnlyIncludeDirectChildren(CollectionType type)
 {
     switch (type) {
+    case ClassCollectionType:
+    case TagCollectionType:
+    case HTMLTagCollectionType:
     case DocAll:
     case DocAnchors:
     case DocApplets:
@@ -62,12 +67,9 @@
     case TSectionRows:
     case TableTBodies:
         return true;
-    case ChildNodeListType:
-    case ClassNodeListType:
     case NameNodeListType:
-    case TagNodeListType:
-    case HTMLTagNodeListType:
     case RadioNodeListType:
+    case RadioImgNodeListType:
     case LabelsNodeListType:
         break;
     }
@@ -90,6 +92,9 @@
     case DocumentNamedItems:
     case FormControls:
         return NodeListIsRootedAtDocument;
+    case ClassCollectionType:
+    case TagCollectionType:
+    case HTMLTagCollectionType:
     case NodeChildren:
     case TableTBodies:
     case TSectionRows:
@@ -100,12 +105,9 @@
     case DataListOptions:
     case MapAreas:
         return NodeListIsRootedAtNode;
-    case ChildNodeListType:
-    case ClassNodeListType:
     case NameNodeListType:
-    case TagNodeListType:
-    case HTMLTagNodeListType:
     case RadioNodeListType:
+    case RadioImgNodeListType:
     case LabelsNodeListType:
         break;
     }
@@ -116,6 +118,8 @@
 static NodeListInvalidationType invalidationTypeExcludingIdAndNameAttributes(CollectionType type)
 {
     switch (type) {
+    case TagCollectionType:
+    case HTMLTagCollectionType:
     case DocImages:
     case DocEmbeds:
     case DocForms:
@@ -144,12 +148,11 @@
         return InvalidateOnIdNameAttrChange;
     case FormControls:
         return InvalidateForFormControls;
-    case ChildNodeListType:
-    case ClassNodeListType:
+    case ClassCollectionType:
+        return InvalidateOnClassAttrChange;
     case NameNodeListType:
-    case TagNodeListType:
-    case HTMLTagNodeListType:
     case RadioNodeListType:
+    case RadioImgNodeListType:
     case LabelsNodeListType:
         break;
     }
@@ -157,171 +160,203 @@
     return DoNotInvalidateOnAttributeChanges;
 }
 
-HTMLCollection::HTMLCollection(Node* ownerNode, CollectionType type, ItemAfterOverrideType itemAfterOverrideType)
-    : LiveNodeListBase(ownerNode, rootTypeFromCollectionType(type), invalidationTypeExcludingIdAndNameAttributes(type),
-        WebCore::shouldOnlyIncludeDirectChildren(type), type, itemAfterOverrideType)
+HTMLCollection::HTMLCollection(ContainerNode* ownerNode, CollectionType type, ItemAfterOverrideType itemAfterOverrideType)
+    : LiveNodeListBase(ownerNode, rootTypeFromCollectionType(type), invalidationTypeExcludingIdAndNameAttributes(type), type)
+    , m_overridesItemAfter(itemAfterOverrideType == OverridesItemAfter)
+    , m_shouldOnlyIncludeDirectChildren(shouldTypeOnlyIncludeDirectChildren(type))
+    , m_hasValidIdNameCache(false)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLCollection> HTMLCollection::create(Node* base, CollectionType type)
+PassRefPtr<HTMLCollection> HTMLCollection::create(ContainerNode* base, CollectionType type)
 {
     return adoptRef(new HTMLCollection(base, type, DoesNotOverrideItemAfter));
 }
 
 HTMLCollection::~HTMLCollection()
 {
-    // HTMLNameCollection removes cache by itself.
-    if (type() != WindowNamedItems && type() != DocumentNamedItems)
-        ownerNode()->nodeLists()->removeCacheWithAtomicName(this, type());
+    if (hasValidIdNameCache())
+        unregisterIdNameCacheFromDocument(document());
+    // HTMLNameCollection, ClassCollection and TagCollection remove cache by themselves.
+    if (type() != WindowNamedItems && type() != DocumentNamedItems && type() != ClassCollectionType
+        && type() != HTMLTagCollectionType && type() != TagCollectionType) {
+        ownerNode()->nodeLists()->removeCache(this, type());
+    }
+}
+
+void HTMLCollection::invalidateCache(Document* oldDocument) const
+{
+    m_collectionIndexCache.invalidate();
+    invalidateIdNameCacheMaps(oldDocument);
 }
 
 template <class NodeListType>
-inline bool isMatchingElement(const NodeListType*, Element*);
+inline bool isMatchingElement(const NodeListType&, const Element&);
 
-template <> inline bool isMatchingElement(const HTMLCollection* htmlCollection, Element* element)
+template <> inline bool isMatchingElement(const HTMLCollection& htmlCollection, const Element& element)
 {
-    CollectionType type = htmlCollection->type();
-    if (!element->isHTMLElement() && !(type == DocAll || type == NodeChildren || type == WindowNamedItems))
+    CollectionType type = htmlCollection.type();
+
+    // These collections apply to any kind of Elements, not just HTMLElements.
+    switch (type) {
+    case DocAll:
+    case NodeChildren:
+        return true;
+    case ClassCollectionType:
+        return static_cast<const ClassCollection&>(htmlCollection).elementMatches(element);
+    case TagCollectionType:
+        return static_cast<const TagCollection&>(htmlCollection).elementMatches(element);
+    case HTMLTagCollectionType:
+        return static_cast<const HTMLTagCollection&>(htmlCollection).elementMatches(element);
+    default:
+        break;
+    }
+
+    // The following only applies to HTMLElements.
+    if (!element.isHTMLElement())
         return false;
 
     switch (type) {
     case DocImages:
-        return element->hasLocalName(imgTag);
+        return element.hasLocalName(imgTag);
     case DocScripts:
-        return element->hasLocalName(scriptTag);
+        return element.hasLocalName(scriptTag);
     case DocForms:
-        return element->hasLocalName(formTag);
+        return element.hasLocalName(formTag);
     case TableTBodies:
-        return element->hasLocalName(tbodyTag);
+        return element.hasLocalName(tbodyTag);
     case TRCells:
-        return element->hasLocalName(tdTag) || element->hasLocalName(thTag);
+        return element.hasLocalName(tdTag) || element.hasLocalName(thTag);
     case TSectionRows:
-        return element->hasLocalName(trTag);
+        return element.hasLocalName(trTag);
     case SelectOptions:
-        return element->hasLocalName(optionTag);
+        return element.hasLocalName(optionTag);
     case SelectedOptions:
-        return element->hasLocalName(optionTag) && toHTMLOptionElement(element)->selected();
+        return element.hasLocalName(optionTag) && toHTMLOptionElement(element).selected();
     case DataListOptions:
-        if (element->hasLocalName(optionTag)) {
-            HTMLOptionElement* option = toHTMLOptionElement(element);
-            if (!option->isDisabledFormControl() && !option->value().isEmpty())
+        if (element.hasLocalName(optionTag)) {
+            const HTMLOptionElement& option = toHTMLOptionElement(element);
+            if (!option.isDisabledFormControl() && !option.value().isEmpty())
                 return true;
         }
         return false;
     case MapAreas:
-        return element->hasLocalName(areaTag);
+        return element.hasLocalName(areaTag);
     case DocApplets:
-        return element->hasLocalName(appletTag) || (element->hasLocalName(objectTag) && toHTMLObjectElement(element)->containsJavaApplet());
+        return element.hasLocalName(appletTag) || (element.hasLocalName(objectTag) && toHTMLObjectElement(element).containsJavaApplet());
     case DocEmbeds:
-        return element->hasLocalName(embedTag);
+        return element.hasLocalName(embedTag);
     case DocLinks:
-        return (element->hasLocalName(aTag) || element->hasLocalName(areaTag)) && element->fastHasAttribute(hrefAttr);
+        return (element.hasLocalName(aTag) || element.hasLocalName(areaTag)) && element.fastHasAttribute(hrefAttr);
     case DocAnchors:
-        return element->hasLocalName(aTag) && element->fastHasAttribute(nameAttr);
+        return element.hasLocalName(aTag) && element.fastHasAttribute(nameAttr);
+    case ClassCollectionType:
+    case TagCollectionType:
+    case HTMLTagCollectionType:
     case DocAll:
     case NodeChildren:
-        return true;
     case FormControls:
     case DocumentNamedItems:
     case TableRows:
     case WindowNamedItems:
-    case ChildNodeListType:
-    case ClassNodeListType:
     case NameNodeListType:
-    case TagNodeListType:
-    case HTMLTagNodeListType:
     case RadioNodeListType:
+    case RadioImgNodeListType:
     case LabelsNodeListType:
         ASSERT_NOT_REACHED();
     }
     return false;
 }
 
-template <> inline bool isMatchingElement(const LiveNodeList* nodeList, Element* element)
+template <> inline bool isMatchingElement(const ClassCollection& collection, const Element& element)
 {
-    return nodeList->nodeMatches(element);
+    return collection.elementMatches(element);
 }
 
-template <> inline bool isMatchingElement(const HTMLTagNodeList* nodeList, Element* element)
+template <> inline bool isMatchingElement(const HTMLTagCollection& collection, const Element& element)
 {
-    return nodeList->nodeMatchesInlined(element);
+    return collection.elementMatches(element);
 }
 
-template <> inline bool isMatchingElement(const ClassNodeList* nodeList, Element* element)
+template <> inline bool isMatchingElement(const LiveNodeList& nodeList, const Element& element)
 {
-    return nodeList->nodeMatchesInlined(element);
+    return nodeList.nodeMatches(element);
 }
 
-static Node* previousNode(Node& base, Node& previous, bool onlyIncludeDirectChildren)
+static Node* previousNode(const ContainerNode& base, const Node& previous, bool onlyIncludeDirectChildren)
 {
     return onlyIncludeDirectChildren ? previous.previousSibling() : NodeTraversal::previous(previous, &base);
 }
 
-static inline Node* lastDescendent(Node& node)
+static inline Node* lastDescendant(const ContainerNode& node)
 {
-    Node* descendent = node.lastChild();
-    for (Node* current = descendent; current; current = current->lastChild())
-        descendent = current;
-    return descendent;
+    Node* descendant = node.lastChild();
+    for (Node* current = descendant; current; current = current->lastChild())
+        descendant = current;
+    return descendant;
 }
 
-static Node* lastNode(Node& rootNode, bool onlyIncludeDirectChildren)
+static Node* lastNode(const ContainerNode& rootNode, bool onlyIncludeDirectChildren)
 {
-    return onlyIncludeDirectChildren ? rootNode.lastChild() : lastDescendent(rootNode);
+    return onlyIncludeDirectChildren ? rootNode.lastChild() : lastDescendant(rootNode);
 }
 
-ALWAYS_INLINE Node* LiveNodeListBase::iterateForPreviousNode(Node* current) const
+template <typename Collection>
+ALWAYS_INLINE Element* LiveNodeListBase::iterateForPreviousNode(const Collection& collection, Node* current)
 {
-    bool onlyIncludeDirectChildren = shouldOnlyIncludeDirectChildren();
-    CollectionType collectionType = type();
-    Node& rootNode = this->rootNode();
+    bool onlyIncludeDirectChildren = collection.shouldOnlyIncludeDirectChildren();
+    ContainerNode& rootNode = collection.rootNode();
     for (; current; current = previousNode(rootNode, *current, onlyIncludeDirectChildren)) {
-        if (isNodeList(collectionType)) {
-            if (current->isElementNode() && isMatchingElement(static_cast<const LiveNodeList*>(this), toElement(current)))
-                return toElement(current);
-        } else {
-            if (current->isElementNode() && isMatchingElement(static_cast<const HTMLCollection*>(this), toElement(current)))
-                return toElement(current);
-        }
+        if (current->isElementNode() && isMatchingElement(collection, toElement(*current)))
+            return toElement(current);
     }
     return 0;
 }
 
-ALWAYS_INLINE Node* LiveNodeListBase::itemBefore(Node* previous) const
+template <typename Collection>
+Element* LiveNodeListBase::itemBefore(const Collection& collection, const Element* previous)
 {
     Node* current;
     if (LIKELY(!!previous)) // Without this LIKELY, length() and item() can be 10% slower.
-        current = previousNode(rootNode(), *previous, shouldOnlyIncludeDirectChildren());
+        current = previousNode(collection.rootNode(), *previous, collection.shouldOnlyIncludeDirectChildren());
     else
-        current = lastNode(rootNode(), shouldOnlyIncludeDirectChildren());
+        current = lastNode(collection.rootNode(), collection.shouldOnlyIncludeDirectChildren());
 
-    if (type() == ChildNodeListType)
-        return current;
-    return iterateForPreviousNode(current);
+    return iterateForPreviousNode(collection, current);
+}
+
+Element* LiveNodeList::itemBefore(const Element* previous) const
+{
+    return LiveNodeListBase::itemBefore(*this, previous);
+}
+
+Element* HTMLCollection::itemBefore(const Element* previous) const
+{
+    return LiveNodeListBase::itemBefore(*this, previous);
 }
 
 template <class NodeListType>
-inline Element* firstMatchingElement(const NodeListType* nodeList, ContainerNode& root)
+inline Element* firstMatchingElement(const NodeListType& nodeList, const ContainerNode& root)
 {
     Element* element = ElementTraversal::firstWithin(root);
-    while (element && !isMatchingElement(nodeList, element))
+    while (element && !isMatchingElement(nodeList, *element))
         element = ElementTraversal::next(*element, &root);
     return element;
 }
 
 template <class NodeListType>
-inline Element* nextMatchingElement(const NodeListType* nodeList, Element& current, ContainerNode* root)
+inline Element* nextMatchingElement(const NodeListType& nodeList, Element& current, const ContainerNode& root)
 {
     Element* next = &current;
     do {
-        next = ElementTraversal::next(*next, root);
-    } while (next && !isMatchingElement(nodeList, next));
+        next = ElementTraversal::next(*next, &root);
+    } while (next && !isMatchingElement(nodeList, *next));
     return next;
 }
 
 template <class NodeListType>
-inline Element* traverseMatchingElementsForwardToOffset(const NodeListType* nodeList, unsigned offset, Element& currentElement, unsigned& currentOffset, ContainerNode* root)
+inline Element* traverseMatchingElementsForwardToOffset(const NodeListType& nodeList, unsigned offset, Element& currentElement, unsigned& currentOffset, const ContainerNode& root)
 {
     ASSERT(currentOffset < offset);
     Element* next = &currentElement;
@@ -332,344 +367,203 @@
     return 0;
 }
 
-// FIXME: This should be in ChildNodeList
-inline Node* LiveNodeListBase::traverseChildNodeListForwardToOffset(unsigned offset, Node* currentNode, unsigned& currentOffset) const
+// FIXME: This should be in LiveNodeList.cpp but it needs to stay here until firstMatchingElement()
+// and others are moved to a separate header.
+Element* LiveNodeList::traverseToFirstElement(const ContainerNode& root) const
 {
-    ASSERT(type() == ChildNodeListType);
-    ASSERT(currentOffset < offset);
-    while ((currentNode = currentNode->nextSibling())) {
-        if (++currentOffset == offset)
-            return currentNode;
-    }
-    return 0;
+    return firstMatchingElement(*this, root);
 }
 
-// FIXME: This should be in LiveNodeList
-inline Element* LiveNodeListBase::traverseLiveNodeListFirstElement(ContainerNode& root) const
+// FIXME: This should be in LiveNodeList.cpp but it needs to stay here until traverseMatchingElementsForwardToOffset()
+// and others are moved to a separate header.
+Element* LiveNodeList::traverseForwardToOffset(unsigned offset, Element& currentNode, unsigned& currentOffset, const ContainerNode& root) const
 {
-    ASSERT(isNodeList(type()));
-    ASSERT(type() != ChildNodeListType);
-    if (type() == HTMLTagNodeListType)
-        return firstMatchingElement(static_cast<const HTMLTagNodeList*>(this), root);
-    if (type() == ClassNodeListType)
-        return firstMatchingElement(static_cast<const ClassNodeList*>(this), root);
-    return firstMatchingElement(static_cast<const LiveNodeList*>(this), root);
+    return traverseMatchingElementsForwardToOffset(*this, offset, currentNode, currentOffset, root);
 }
 
-// FIXME: This should be in LiveNodeList
-inline Element* LiveNodeListBase::traverseLiveNodeListForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, ContainerNode* root) const
-{
-    ASSERT(isNodeList(type()));
-    ASSERT(type() != ChildNodeListType);
-    if (type() == HTMLTagNodeListType)
-        return traverseMatchingElementsForwardToOffset(static_cast<const HTMLTagNodeList*>(this), offset, currentElement, currentOffset, root);
-    if (type() == ClassNodeListType)
-        return traverseMatchingElementsForwardToOffset(static_cast<const ClassNodeList*>(this), offset, currentElement, currentOffset, root);
-    return traverseMatchingElementsForwardToOffset(static_cast<const LiveNodeList*>(this), offset, currentElement, currentOffset, root);
-}
-
-bool ALWAYS_INLINE LiveNodeListBase::isLastItemCloserThanLastOrCachedItem(unsigned offset) const
-{
-    ASSERT(isLengthCacheValid());
-    unsigned distanceFromLastItem = cachedLength() - offset;
-    if (!isItemCacheValid())
-        return distanceFromLastItem < offset;
-
-    return cachedItemOffset() < offset && distanceFromLastItem < offset - cachedItemOffset();
-}
-
-bool ALWAYS_INLINE LiveNodeListBase::isFirstItemCloserThanCachedItem(unsigned offset) const
-{
-    ASSERT(isItemCacheValid());
-    if (cachedItemOffset() < offset)
-        return false;
-
-    unsigned distanceFromCachedItem = cachedItemOffset() - offset;
-    return offset < distanceFromCachedItem;
-}
-
-ALWAYS_INLINE void LiveNodeListBase::setItemCache(Node* item, unsigned offset, unsigned elementsArrayOffset) const
-{
-    setItemCache(item, offset);
-    if (overridesItemAfter()) {
-        ASSERT_WITH_SECURITY_IMPLICATION(item->isElementNode());
-        static_cast<const HTMLCollection*>(this)->m_cachedElementsArrayOffset = elementsArrayOffset;
-    } else
-        ASSERT(!elementsArrayOffset);
-}
-
-unsigned LiveNodeListBase::length() const
-{
-    if (isLengthCacheValid())
-        return cachedLength();
-
-    item(UINT_MAX);
-    ASSERT(isLengthCacheValid());
-
-    return cachedLength();
-}
-
-// FIXME: It is silly that these functions are in HTMLCollection.cpp.
-Node* LiveNodeListBase::item(unsigned offset) const
-{
-    if (isItemCacheValid() && cachedItemOffset() == offset)
-        return cachedItem();
-
-    if (isLengthCacheValid() && cachedLength() <= offset)
-        return 0;
-
-    ContainerNode* root = rootContainerNode();
-    if (!root) {
-        // FIMXE: In someTextNode.childNodes case the root is Text. We shouldn't even make a LiveNodeList for that.
-        setLengthCache(0);
-        return 0;
-    }
-
-    if (isLengthCacheValid() && !overridesItemAfter() && isLastItemCloserThanLastOrCachedItem(offset)) {
-        Node* lastItem = itemBefore(0);
-        ASSERT(lastItem);
-        setItemCache(lastItem, cachedLength() - 1, 0);
-    } else if (!isItemCacheValid() || isFirstItemCloserThanCachedItem(offset) || (overridesItemAfter() && offset < cachedItemOffset())) {
-        unsigned offsetInArray = 0;
-        Node* firstItem;
-        if (type() == ChildNodeListType)
-            firstItem = root->firstChild();
-        else if (isNodeList(type()))
-            firstItem = traverseLiveNodeListFirstElement(*root);
-        else
-            firstItem = static_cast<const HTMLCollection*>(this)->traverseFirstElement(offsetInArray, *root);
-
-        if (!firstItem) {
-            setLengthCache(0);
-            return 0;
-        }
-        setItemCache(firstItem, 0, offsetInArray);
-        ASSERT(!cachedItemOffset());
-    }
-
-    if (cachedItemOffset() == offset)
-        return cachedItem();
-
-    return itemBeforeOrAfterCachedItem(offset, root);
-}
-
-inline Node* LiveNodeListBase::itemBeforeOrAfterCachedItem(unsigned offset, ContainerNode* root) const
-{
-    unsigned currentOffset = cachedItemOffset();
-    Node* currentItem = cachedItem();
-    ASSERT(currentItem);
-    ASSERT(currentOffset != offset);
-
-    if (offset < cachedItemOffset()) {
-        ASSERT(!overridesItemAfter());
-        while ((currentItem = itemBefore(currentItem))) {
-            ASSERT(currentOffset);
-            currentOffset--;
-            if (currentOffset == offset) {
-                setItemCache(currentItem, currentOffset, 0);
-                return currentItem;
-            }
-        }
-        ASSERT_NOT_REACHED();
-        return 0;
-    }
-
-    unsigned offsetInArray = 0;
-    if (type() == ChildNodeListType)
-        currentItem = traverseChildNodeListForwardToOffset(offset, currentItem, currentOffset);
-    else if (isNodeList(type()))
-        currentItem = traverseLiveNodeListForwardToOffset(offset, toElement(*currentItem), currentOffset, root);
-    else
-        currentItem = static_cast<const HTMLCollection*>(this)->traverseForwardToOffset(offset, toElement(*currentItem), currentOffset, offsetInArray, root);
-
-    if (!currentItem) {
-        // Did not find the item. On plus side, we now know the length.
-        setLengthCache(currentOffset + 1);
-        return 0;
-    }
-    setItemCache(currentItem, currentOffset, offsetInArray);
-    return currentItem;
-}
-
-Element* HTMLCollection::virtualItemAfter(unsigned&, Element*) const
+Element* HTMLCollection::virtualItemAfter(Element*) const
 {
     ASSERT_NOT_REACHED();
     return 0;
 }
 
-static inline bool nameShouldBeVisibleInDocumentAll(HTMLElement* element)
+static inline bool nameShouldBeVisibleInDocumentAll(const HTMLElement& element)
 {
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#dom-htmlallcollection-nameditem:
     // The document.all collection returns only certain types of elements by name,
     // although it returns any type of element by id.
-    return element->hasLocalName(appletTag)
-        || element->hasLocalName(embedTag)
-        || element->hasLocalName(formTag)
-        || element->hasLocalName(imgTag)
-        || element->hasLocalName(inputTag)
-        || element->hasLocalName(objectTag)
-        || element->hasLocalName(selectTag);
+    return element.hasLocalName(aTag)
+        || element.hasLocalName(appletTag)
+        || element.hasLocalName(areaTag)
+        || element.hasLocalName(embedTag)
+        || element.hasLocalName(formTag)
+        || element.hasLocalName(frameTag)
+        || element.hasLocalName(framesetTag)
+        || element.hasLocalName(iframeTag)
+        || element.hasLocalName(imgTag)
+        || element.hasLocalName(inputTag)
+        || element.hasLocalName(objectTag)
+        || element.hasLocalName(selectTag);
 }
 
-bool HTMLCollection::checkForNameMatch(Element* element, bool checkName, const AtomicString& name) const
-{
-    if (!element->isHTMLElement())
-        return false;
-
-    HTMLElement* e = toHTMLElement(element);
-    if (!checkName)
-        return e->getIdAttribute() == name;
-
-    if (type() == DocAll && !nameShouldBeVisibleInDocumentAll(e))
-        return false;
-
-    return e->getNameAttribute() == name && e->getIdAttribute() != name;
-}
-
-inline Element* firstMatchingChildElement(const HTMLCollection* nodeList, ContainerNode& root)
+inline Element* firstMatchingChildElement(const HTMLCollection& nodeList, const ContainerNode& root)
 {
     Element* element = ElementTraversal::firstWithin(root);
-    while (element && !isMatchingElement(nodeList, element))
+    while (element && !isMatchingElement(nodeList, *element))
         element = ElementTraversal::nextSkippingChildren(*element, &root);
     return element;
 }
 
-inline Element* nextMatchingChildElement(const HTMLCollection* nodeList, Element& current, ContainerNode* root)
+inline Element* nextMatchingChildElement(const HTMLCollection& nodeList, Element& current, const ContainerNode& root)
 {
     Element* next = &current;
     do {
-        next = ElementTraversal::nextSkippingChildren(*next, root);
-    } while (next && !isMatchingElement(nodeList, next));
+        next = ElementTraversal::nextSkippingChildren(*next, &root);
+    } while (next && !isMatchingElement(nodeList, *next));
     return next;
 }
 
-inline Element* HTMLCollection::traverseFirstElement(unsigned& offsetInArray, ContainerNode& root) const
+Element* HTMLCollection::traverseToFirstElement(const ContainerNode& root) const
 {
-    if (overridesItemAfter())
-        return virtualItemAfter(offsetInArray, 0);
-    ASSERT(!offsetInArray);
-    if (shouldOnlyIncludeDirectChildren())
-        return firstMatchingChildElement(static_cast<const HTMLCollection*>(this), root);
-    return firstMatchingElement(static_cast<const HTMLCollection*>(this), root);
+    switch (type()) {
+    case HTMLTagCollectionType:
+        return firstMatchingElement(static_cast<const HTMLTagCollection&>(*this), root);
+    case ClassCollectionType:
+        return firstMatchingElement(static_cast<const ClassCollection&>(*this), root);
+    default:
+        if (overridesItemAfter())
+            return virtualItemAfter(0);
+        if (shouldOnlyIncludeDirectChildren())
+            return firstMatchingChildElement(*this, root);
+        return firstMatchingElement(*this, root);
+    }
 }
 
-inline Element* HTMLCollection::traverseNextElement(unsigned& offsetInArray, Element& previous, ContainerNode* root) const
+inline Element* HTMLCollection::traverseNextElement(Element& previous, const ContainerNode& root) const
 {
     if (overridesItemAfter())
-        return virtualItemAfter(offsetInArray, &previous);
-    ASSERT(!offsetInArray);
+        return virtualItemAfter(&previous);
     if (shouldOnlyIncludeDirectChildren())
-        return nextMatchingChildElement(this, previous, root);
-    return nextMatchingElement(this, previous, root);
+        return nextMatchingChildElement(*this, previous, root);
+    return nextMatchingElement(*this, previous, root);
 }
 
-inline Element* HTMLCollection::traverseForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const
+Element* HTMLCollection::traverseForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, const ContainerNode& root) const
 {
     ASSERT(currentOffset < offset);
-    if (overridesItemAfter()) {
-        offsetInArray = m_cachedElementsArrayOffset;
-        Element* next = &currentElement;
-        while ((next = virtualItemAfter(offsetInArray, next))) {
-            if (++currentOffset == offset)
-                return next;
+    switch (type()) {
+    case HTMLTagCollectionType:
+        return traverseMatchingElementsForwardToOffset(static_cast<const HTMLTagCollection&>(*this), offset, currentElement, currentOffset, root);
+    case ClassCollectionType:
+        return traverseMatchingElementsForwardToOffset(static_cast<const ClassCollection&>(*this), offset, currentElement, currentOffset, root);
+    default:
+        if (overridesItemAfter()) {
+            Element* next = &currentElement;
+            while ((next = virtualItemAfter(next))) {
+                if (++currentOffset == offset)
+                    return next;
+            }
+            return 0;
         }
-        return 0;
-    }
-    if (shouldOnlyIncludeDirectChildren()) {
-        Element* next = &currentElement;
-        while ((next = nextMatchingChildElement(this, *next, root))) {
-            if (++currentOffset == offset)
-                return next;
+        if (shouldOnlyIncludeDirectChildren()) {
+            Element* next = &currentElement;
+            while ((next = nextMatchingChildElement(*this, *next, root))) {
+                if (++currentOffset == offset)
+                    return next;
+            }
+            return 0;
         }
-        return 0;
+        return traverseMatchingElementsForwardToOffset(*this, offset, currentElement, currentOffset, root);
     }
-    return traverseMatchingElementsForwardToOffset(this, offset, currentElement, currentOffset, root);
 }
 
-Node* HTMLCollection::namedItem(const AtomicString& name) const
+Element* HTMLCollection::namedItem(const AtomicString& name) const
 {
     // http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/nameditem.asp
     // This method first searches for an object with a matching id
     // attribute. If a match is not found, the method then searches for an
     // object with a matching name attribute, but only on those elements
     // that are allowed a name attribute.
+    updateIdNameCache();
 
-    ContainerNode* root = rootContainerNode();
-    if (!root)
-        return 0;
+    Vector<Element*>* idResults = idCache(name);
+    if (idResults && !idResults->isEmpty())
+        return idResults->first();
 
-    unsigned arrayOffset = 0;
-    unsigned i = 0;
-    for (Element* element = traverseFirstElement(arrayOffset, *root); element; element = traverseNextElement(arrayOffset, *element, root)) {
-        if (checkForNameMatch(element, /* checkName */ false, name)) {
-            setItemCache(element, i, arrayOffset);
-            return element;
-        }
-        i++;
-    }
-
-    i = 0;
-    for (Element* element = traverseFirstElement(arrayOffset, *root); element; element = traverseNextElement(arrayOffset, *element, root)) {
-        if (checkForNameMatch(element, /* checkName */ true, name)) {
-            setItemCache(element, i, arrayOffset);
-            return element;
-        }
-        i++;
-    }
+    Vector<Element*>* nameResults = nameCache(name);
+    if (nameResults && !nameResults->isEmpty())
+        return nameResults->first();
 
     return 0;
 }
 
-void HTMLCollection::updateNameCache() const
+bool HTMLCollection::namedPropertyQuery(const AtomicString& name, ExceptionState&)
 {
-    if (hasNameCache())
+    return namedItem(name);
+}
+
+void HTMLCollection::supportedPropertyNames(Vector<String>& names)
+{
+    // As per the specification (http://dom.spec.whatwg.org/#htmlcollection):
+    // The supported property names are the values from the list returned by these steps:
+    // 1. Let result be an empty list.
+    // 2. For each element represented by the collection, in tree order, run these substeps:
+    //   1. If element has an ID which is neither the empty string nor is in result, append element's ID to result.
+    //   2. If element is in the HTML namespace and has a name attribute whose value is neither the empty string
+    //      nor is in result, append element's name attribute value to result.
+    // 3. Return result.
+    HashSet<AtomicString> existingNames;
+    ContainerNode& root = rootNode();
+    for (Element* element = traverseToFirstElement(root); element; element = traverseNextElement(*element, root)) {
+        const AtomicString& idAttribute = element->getIdAttribute();
+        if (!idAttribute.isEmpty()) {
+            HashSet<AtomicString>::AddResult addResult = existingNames.add(idAttribute);
+            if (addResult.isNewEntry)
+                names.append(idAttribute);
+        }
+        if (!element->isHTMLElement())
+            continue;
+        const AtomicString& nameAttribute = element->getNameAttribute();
+        if (!nameAttribute.isEmpty() && (type() != DocAll || nameShouldBeVisibleInDocumentAll(toHTMLElement(*element)))) {
+            HashSet<AtomicString>::AddResult addResult = existingNames.add(nameAttribute);
+            if (addResult.isNewEntry)
+                names.append(nameAttribute);
+        }
+    }
+}
+
+void HTMLCollection::namedPropertyEnumerator(Vector<String>& names, ExceptionState&)
+{
+    supportedPropertyNames(names);
+}
+
+void HTMLCollection::updateIdNameCache() const
+{
+    if (hasValidIdNameCache())
         return;
 
-    ContainerNode* root = rootContainerNode();
-    if (!root)
-        return;
-
-    unsigned arrayOffset = 0;
-    for (Element* element = traverseFirstElement(arrayOffset, *root); element; element = traverseNextElement(arrayOffset, *element, root)) {
+    ContainerNode& root = rootNode();
+    for (Element* element = traverseToFirstElement(root); element; element = traverseNextElement(*element, root)) {
         const AtomicString& idAttrVal = element->getIdAttribute();
         if (!idAttrVal.isEmpty())
             appendIdCache(idAttrVal, element);
         if (!element->isHTMLElement())
             continue;
         const AtomicString& nameAttrVal = element->getNameAttribute();
-        if (!nameAttrVal.isEmpty() && idAttrVal != nameAttrVal && (type() != DocAll || nameShouldBeVisibleInDocumentAll(toHTMLElement(element))))
+        if (!nameAttrVal.isEmpty() && idAttrVal != nameAttrVal && (type() != DocAll || nameShouldBeVisibleInDocumentAll(toHTMLElement(*element))))
             appendNameCache(nameAttrVal, element);
     }
 
-    setHasNameCache();
+    setHasValidIdNameCache();
 }
 
-bool HTMLCollection::hasNamedItem(const AtomicString& name) const
-{
-    if (name.isEmpty())
-        return false;
-
-    updateNameCache();
-
-    if (Vector<Element*>* cache = idCache(name)) {
-        if (!cache->isEmpty())
-            return true;
-    }
-
-    if (Vector<Element*>* cache = nameCache(name)) {
-        if (!cache->isEmpty())
-            return true;
-    }
-
-    return false;
-}
-
-void HTMLCollection::namedItems(const AtomicString& name, Vector<RefPtr<Node> >& result) const
+void HTMLCollection::namedItems(const AtomicString& name, Vector<RefPtr<Element> >& result) const
 {
     ASSERT(result.isEmpty());
     if (name.isEmpty())
         return;
 
-    updateNameCache();
+    updateIdNameCache();
 
     Vector<Element*>* idResults = idCache(name);
     Vector<Element*>* nameResults = nameCache(name);
@@ -683,7 +577,7 @@
 
 void HTMLCollection::append(NodeCacheMap& map, const AtomicString& key, Element* element)
 {
-    OwnPtr<Vector<Element*> >& vector = map.add(key.impl(), nullptr).iterator->value;
+    OwnPtr<Vector<Element*> >& vector = map.add(key.impl(), nullptr).storedValue->value;
     if (!vector)
         vector = adoptPtr(new Vector<Element*>);
     vector->append(element);
diff --git a/Source/core/html/HTMLCollection.h b/Source/core/html/HTMLCollection.h
index 967b247..29f039e 100644
--- a/Source/core/html/HTMLCollection.h
+++ b/Source/core/html/HTMLCollection.h
@@ -2,6 +2,7 @@
  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -31,43 +32,51 @@
 
 namespace WebCore {
 
-class HTMLCollection : public LiveNodeListBase {
+class HTMLCollection : public ScriptWrappable, public RefCounted<HTMLCollection>, public LiveNodeListBase {
 public:
-    static PassRefPtr<HTMLCollection> create(Node* base, CollectionType);
+    enum ItemAfterOverrideType {
+        OverridesItemAfter,
+        DoesNotOverrideItemAfter,
+    };
+
+    static PassRefPtr<HTMLCollection> create(ContainerNode* base, CollectionType);
     virtual ~HTMLCollection();
+    virtual void invalidateCache(Document* oldDocument = 0) const OVERRIDE;
 
     // DOM API
-    virtual Node* namedItem(const AtomicString& name) const;
+    unsigned length() const { return m_collectionIndexCache.nodeCount(*this); }
+    Element* item(unsigned offset) const { return m_collectionIndexCache.nodeAt(*this, offset); }
+    virtual Element* namedItem(const AtomicString& name) const;
+    bool namedPropertyQuery(const AtomicString&, ExceptionState&);
+    void namedPropertyEnumerator(Vector<String>& names, ExceptionState&);
 
     // Non-DOM API
-    virtual bool hasNamedItem(const AtomicString& name) const;
-    void namedItems(const AtomicString& name, Vector<RefPtr<Node> >&) const;
-    bool isEmpty() const
-    {
-        if (isLengthCacheValid())
-            return !cachedLength();
-        if (isItemCacheValid())
-            return !cachedItem();
-        return !item(0);
-    }
-    bool hasExactlyOneItem() const
-    {
-        if (isLengthCacheValid())
-            return cachedLength() == 1;
-        if (isItemCacheValid())
-            return cachedItem() && !cachedItemOffset() && !item(1);
-        return item(0) && !item(1);
-    }
+    void namedItems(const AtomicString& name, Vector<RefPtr<Element> >&) const;
+    bool isEmpty() const { return m_collectionIndexCache.isEmpty(*this); }
+    bool hasExactlyOneItem() const { return m_collectionIndexCache.hasExactlyOneNode(*this); }
 
-    virtual Element* virtualItemAfter(unsigned& offsetInArray, Element*) const;
-
-    Element* traverseFirstElement(unsigned& offsetInArray, ContainerNode& root) const;
-    Element* traverseForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const;
+    // CollectionIndexCache API.
+    bool canTraverseBackward() const { return !overridesItemAfter(); }
+    Element* itemBefore(const Element* previousItem) const;
+    Element* traverseToFirstElement(const ContainerNode& root) const;
+    Element* traverseForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, const ContainerNode& root) const;
 
 protected:
-    HTMLCollection(Node* base, CollectionType, ItemAfterOverrideType);
+    HTMLCollection(ContainerNode* base, CollectionType, ItemAfterOverrideType);
 
-    virtual void updateNameCache() const;
+    bool overridesItemAfter() const { return m_overridesItemAfter; }
+    virtual Element* virtualItemAfter(Element*) const;
+    bool shouldOnlyIncludeDirectChildren() const { return m_shouldOnlyIncludeDirectChildren; }
+    virtual void supportedPropertyNames(Vector<String>& names);
+
+    virtual void updateIdNameCache() const;
+    bool hasValidIdNameCache() const { return m_hasValidIdNameCache; }
+    void setHasValidIdNameCache() const
+    {
+        ASSERT(!m_hasValidIdNameCache);
+        m_hasValidIdNameCache = true;
+        document().incrementNodeListWithIdNameCacheCount();
+    }
 
     typedef HashMap<StringImpl*, OwnPtr<Vector<Element*> > > NodeCacheMap;
     Vector<Element*>* idCache(const AtomicString& name) const { return m_idCache.get(name.impl()); }
@@ -76,16 +85,36 @@
     void appendNameCache(const AtomicString& name, Element* element) const { append(m_nameCache, name, element); }
 
 private:
-    bool checkForNameMatch(Element*, bool checkName, const AtomicString& name) const;
-    Element* traverseNextElement(unsigned& offsetInArray, Element& previous, ContainerNode* root) const;
-
-    virtual bool isLiveNodeList() const OVERRIDE { ASSERT_NOT_REACHED(); return true; }
+    Element* traverseNextElement(Element& previous, const ContainerNode& root) const;
 
     static void append(NodeCacheMap&, const AtomicString&, Element*);
+    void invalidateIdNameCacheMaps(Document* oldDocument = 0) const
+    {
+        if (!m_hasValidIdNameCache)
+            return;
 
+        // Make sure we decrement the NodeListWithIdNameCache count from
+        // the old document instead of the new one in the case the collection
+        // is moved to a new document.
+        unregisterIdNameCacheFromDocument(oldDocument ? *oldDocument : document());
+
+        m_idCache.clear();
+        m_nameCache.clear();
+        m_hasValidIdNameCache = false;
+    }
+
+    void unregisterIdNameCacheFromDocument(Document& document) const
+    {
+        ASSERT(m_hasValidIdNameCache);
+        document.decrementNodeListWithIdNameCacheCount();
+    }
+
+    const unsigned m_overridesItemAfter : 1;
+    const unsigned m_shouldOnlyIncludeDirectChildren : 1;
+    mutable unsigned m_hasValidIdNameCache : 1;
     mutable NodeCacheMap m_idCache;
     mutable NodeCacheMap m_nameCache;
-    mutable unsigned m_cachedElementsArrayOffset;
+    mutable CollectionIndexCache<HTMLCollection, Element> m_collectionIndexCache;
 
     friend class LiveNodeListBase;
 };
diff --git a/Source/core/html/HTMLCollection.idl b/Source/core/html/HTMLCollection.idl
index 0198742..337cfea 100644
--- a/Source/core/html/HTMLCollection.idl
+++ b/Source/core/html/HTMLCollection.idl
@@ -1,6 +1,7 @@
 /*
  * Copyright (C) 2006, 2007, 2009 Apple Inc. All rights reserved.
  * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -21,11 +22,10 @@
 [
     Custom=Wrap,
     DependentLifetime,
-    GenerateVisitDOMWrapper=ownerNode,
+    SetWrapperReferenceFrom=ownerNode,
 ] interface HTMLCollection {
     readonly attribute unsigned long length;
-    getter Node item([Default=Undefined] optional unsigned long index);
-    Node namedItem([Default=Undefined] optional DOMString name);
-    [NotEnumerable, ImplementedAs=namedItem] getter Node ([Default=Undefined] optional DOMString name);
+    getter Element item([Default=Undefined] optional unsigned long index);
+    getter Element namedItem(DOMString name);
 };
 
diff --git a/Source/core/html/HTMLDataListElement.cpp b/Source/core/html/HTMLDataListElement.cpp
index fbac9e9..d8666e8 100644
--- a/Source/core/html/HTMLDataListElement.cpp
+++ b/Source/core/html/HTMLDataListElement.cpp
@@ -55,6 +55,18 @@
     return ensureCachedHTMLCollection(DataListOptions);
 }
 
+void HTMLDataListElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
+{
+    HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
+    if (!changedByParser)
+        treeScope().idTargetObserverRegistry().notifyObservers(getIdAttribute());
+}
+
+void HTMLDataListElement::finishParsingChildren()
+{
+    treeScope().idTargetObserverRegistry().notifyObservers(getIdAttribute());
+}
+
 void HTMLDataListElement::optionElementChildrenChanged()
 {
     treeScope().idTargetObserverRegistry().notifyObservers(getIdAttribute());
diff --git a/Source/core/html/HTMLDataListElement.h b/Source/core/html/HTMLDataListElement.h
index e41a0e8..e19686b 100644
--- a/Source/core/html/HTMLDataListElement.h
+++ b/Source/core/html/HTMLDataListElement.h
@@ -47,6 +47,8 @@
 
 private:
     HTMLDataListElement(Document&);
+    virtual void childrenChanged(bool, Node*, Node*, int) OVERRIDE;
+    virtual void finishParsingChildren() OVERRIDE;
 };
 
 DEFINE_NODE_TYPE_CASTS(HTMLDataListElement, hasTagName(HTMLNames::datalistTag));
diff --git a/Source/core/html/HTMLDataListElement.idl b/Source/core/html/HTMLDataListElement.idl
index 93c8663..4dd3654 100644
--- a/Source/core/html/HTMLDataListElement.idl
+++ b/Source/core/html/HTMLDataListElement.idl
@@ -28,8 +28,6 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-[
-    RuntimeEnabled=DataListElement
-] interface HTMLDataListElement : HTMLElement {
+interface HTMLDataListElement : HTMLElement {
     readonly attribute HTMLCollection options;
 };
diff --git a/Source/core/html/HTMLDetailsElement.cpp b/Source/core/html/HTMLDetailsElement.cpp
index 28c6bbe..9546f30 100644
--- a/Source/core/html/HTMLDetailsElement.cpp
+++ b/Source/core/html/HTMLDetailsElement.cpp
@@ -21,12 +21,16 @@
 #include "config.h"
 #include "core/html/HTMLDetailsElement.h"
 
+#include "CSSPropertyNames.h"
+#include "CSSValueKeywords.h"
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ShadowRoot.h"
+#include "core/html/HTMLDivElement.h"
 #include "core/html/HTMLSummaryElement.h"
 #include "core/html/shadow/HTMLContentElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/rendering/RenderBlockFlow.h"
 #include "platform/text/PlatformLocale.h"
 
@@ -60,12 +64,17 @@
     RefPtr<HTMLSummaryElement> defaultSummary = HTMLSummaryElement::create(document());
     defaultSummary->appendChild(Text::create(document(), locale().queryString(blink::WebLocalizedString::DetailsLabel)));
 
-    RefPtr<HTMLContentElement> content = HTMLContentElement::create(document());
-    content->setAttribute(selectAttr, summarySelector);
-    content->appendChild(defaultSummary);
+    RefPtr<HTMLContentElement> summary = HTMLContentElement::create(document());
+    summary->setIdAttribute(ShadowElementNames::detailsSummary());
+    summary->setAttribute(selectAttr, summarySelector);
+    summary->appendChild(defaultSummary);
+    root.appendChild(summary.release());
 
-    root.appendChild(content);
-    root.appendChild(HTMLContentElement::create(document()));
+    RefPtr<HTMLDivElement> content = HTMLDivElement::create(document());
+    content->setIdAttribute(ShadowElementNames::detailsContent());
+    content->appendChild(HTMLContentElement::create(document()));
+    content->setInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
+    root.appendChild(content.release());
 }
 
 Element* HTMLDetailsElement::findMainSummary() const
@@ -85,20 +94,23 @@
     if (name == openAttr) {
         bool oldValue = m_isOpen;
         m_isOpen = !value.isNull();
-        if (oldValue != m_isOpen)
-            lazyReattachIfAttached();
-    } else
-        HTMLElement::parseAttribute(name, value);
-}
-
-bool HTMLDetailsElement::childShouldCreateRenderer(const Node& child) const
-{
-    // FIXME: These checks do not look correct, we should just use insertion points instead.
-    if (m_isOpen)
-        return HTMLElement::childShouldCreateRenderer(child);
-    if (!child.hasTagName(summaryTag))
-        return false;
-    return child == findMainSummary() && HTMLElement::childShouldCreateRenderer(child);
+        if (m_isOpen == oldValue)
+            return;
+        Element* content = ensureUserAgentShadowRoot().getElementById(ShadowElementNames::detailsContent());
+        ASSERT(content);
+        if (m_isOpen)
+            content->removeInlineStyleProperty(CSSPropertyDisplay);
+        else
+            content->setInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
+        Element* summary = ensureUserAgentShadowRoot().getElementById(ShadowElementNames::detailsSummary());
+        ASSERT(summary);
+        // FIXME: DetailsMarkerControl's RenderDetailsMarker has no concept of being updated
+        // without recreating it causing a repaint. Instead we should change it so we can tell
+        // it to toggle the open/closed triangle state and avoid reattaching the entire summary.
+        summary->lazyReattachIfAttached();
+        return;
+    }
+    HTMLElement::parseAttribute(name, value);
 }
 
 void HTMLDetailsElement::toggleOpen()
diff --git a/Source/core/html/HTMLDetailsElement.h b/Source/core/html/HTMLDetailsElement.h
index d5a6b4a..1bcf1d2 100644
--- a/Source/core/html/HTMLDetailsElement.h
+++ b/Source/core/html/HTMLDetailsElement.h
@@ -35,8 +35,7 @@
 private:
     explicit HTMLDetailsElement(Document&);
 
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
     virtual bool isInteractiveContent() const OVERRIDE;
@@ -44,16 +43,6 @@
     bool m_isOpen;
 };
 
-inline bool isHTMLDetailsElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::detailsTag);
-}
-
-inline bool isHTMLDetailsElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::detailsTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLDetailsElement, hasTagName(HTMLNames::detailsTag));
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLDialogElement.cpp b/Source/core/html/HTMLDialogElement.cpp
index 4113b30..6ba713b 100644
--- a/Source/core/html/HTMLDialogElement.cpp
+++ b/Source/core/html/HTMLDialogElement.cpp
@@ -39,23 +39,42 @@
 
 using namespace HTMLNames;
 
-static void runAutofocus(HTMLDialogElement* dialog)
+// This function chooses the focused element when showModal() is invoked, as described in the spec for showModal().
+static void setFocusForModalDialog(HTMLDialogElement* dialog)
 {
+    Element* focusableDescendant = 0;
     Node* next = 0;
     for (Node* node = dialog->firstChild(); node; node = next) {
-        if (node->isElementNode() && toElement(node)->isFormControlElement()) {
-            HTMLFormControlElement* control = toHTMLFormControlElement(node);
-            if (control->isAutofocusable()) {
-                control->focus();
-                control->setAutofocused();
-                return;
-            }
-        }
         if (node->hasTagName(dialogTag))
             next = NodeTraversal::nextSkippingChildren(*node, dialog);
         else
             next = NodeTraversal::next(*node, dialog);
+
+        if (!node->isElementNode())
+            continue;
+        Element* element = toElement(node);
+        if (element->isFormControlElement()) {
+            HTMLFormControlElement* control = toHTMLFormControlElement(node);
+            if (control->isAutofocusable()) {
+                control->focus();
+                return;
+            }
+        }
+        if (!focusableDescendant && element->isFocusable())
+            focusableDescendant = element;
     }
+
+    if (focusableDescendant) {
+        focusableDescendant->focus();
+        return;
+    }
+
+    if (dialog->isFocusable()) {
+        dialog->focus();
+        return;
+    }
+
+    dialog->document().setFocusedElement(0);
 }
 
 static void inertSubtreesChanged(Document& document)
@@ -72,7 +91,7 @@
 
 HTMLDialogElement::HTMLDialogElement(Document& document)
     : HTMLElement(dialogTag, document)
-    , m_centeringMode(Uninitialized)
+    , m_centeringMode(NotCentered)
     , m_centeredPosition(0)
     , m_returnValue("")
 {
@@ -112,10 +131,10 @@
 
 void HTMLDialogElement::forceLayoutForCentering()
 {
-    m_centeringMode = Uninitialized;
+    m_centeringMode = NeedsCentering;
     document().updateLayoutIgnorePendingStylesheets();
-    if (m_centeringMode == Uninitialized)
-        m_centeringMode = NotCentered;
+    if (m_centeringMode == NeedsCentering)
+        setNotCentered();
 }
 
 void HTMLDialogElement::show()
@@ -123,7 +142,6 @@
     if (fastHasAttribute(openAttr))
         return;
     setBooleanAttribute(openAttr, true);
-    forceLayoutForCentering();
 }
 
 void HTMLDialogElement::showModal(ExceptionState& exceptionState)
@@ -140,21 +158,30 @@
     document().addToTopLayer(this);
     setBooleanAttribute(openAttr, true);
 
-    runAutofocus(this);
-    forceLayoutForCentering();
+    // Throw away the AX cache first, so the subsequent steps don't have a chance of queuing up
+    // AX events on objects that would be invalidated when the cache is thrown away.
     inertSubtreesChanged(document());
+
+    forceLayoutForCentering();
+    setFocusForModalDialog(this);
+}
+
+void HTMLDialogElement::removedFrom(ContainerNode* insertionPoint)
+{
+    HTMLElement::removedFrom(insertionPoint);
+    setNotCentered();
+    // FIXME: We should call inertSubtreesChanged() here.
 }
 
 void HTMLDialogElement::setCentered(LayoutUnit centeredPosition)
 {
-    ASSERT(m_centeringMode == Uninitialized);
+    ASSERT(m_centeringMode == NeedsCentering);
     m_centeredPosition = centeredPosition;
     m_centeringMode = Centered;
 }
 
 void HTMLDialogElement::setNotCentered()
 {
-    ASSERT(m_centeringMode == Uninitialized);
     m_centeringMode = NotCentered;
 }
 
@@ -178,11 +205,4 @@
     HTMLElement::defaultEventHandler(event);
 }
 
-bool HTMLDialogElement::shouldBeReparentedUnderRenderView(const RenderStyle* style) const
-{
-    if (style && style->position() == AbsolutePosition)
-        return true;
-    return Element::shouldBeReparentedUnderRenderView(style);
-}
-
 } // namespace WebCore
diff --git a/Source/core/html/HTMLDialogElement.h b/Source/core/html/HTMLDialogElement.h
index 248044e..26d88cd 100644
--- a/Source/core/html/HTMLDialogElement.h
+++ b/Source/core/html/HTMLDialogElement.h
@@ -43,8 +43,12 @@
     void closeDialog(const String& returnValue = String());
     void show();
     void showModal(ExceptionState&);
+    virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    enum CenteringMode { Uninitialized, Centered, NotCentered };
+    // NotCentered means do not center the dialog. Centered means the dialog has
+    // been centered and centeredPosition() is set. NeedsCentering means attempt
+    // to center on the next layout, then set to Centered or NotCentered.
+    enum CenteringMode { NotCentered, Centered, NeedsCentering };
     CenteringMode centeringMode() const { return m_centeringMode; }
     LayoutUnit centeredPosition() const
     {
@@ -62,7 +66,6 @@
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
-    virtual bool shouldBeReparentedUnderRenderView(const RenderStyle*) const OVERRIDE;
 
     void forceLayoutForCentering();
 
@@ -71,13 +74,14 @@
     String m_returnValue;
 };
 
-inline HTMLDialogElement* toHTMLDialogElement(Node* node)
+inline bool isHTMLDialogElement(const Node& node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::dialogTag));
     ASSERT_WITH_SECURITY_IMPLICATION(RuntimeEnabledFeatures::dialogElementEnabled());
-    return static_cast<HTMLDialogElement*>(node);
+    return node.hasTagName(HTMLNames::dialogTag);
 }
 
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLDialogElement);
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/html/HTMLDivElement.cpp b/Source/core/html/HTMLDivElement.cpp
index af3d893..9882a75 100644
--- a/Source/core/html/HTMLDivElement.cpp
+++ b/Source/core/html/HTMLDivElement.cpp
@@ -42,13 +42,6 @@
     return adoptRef(new HTMLDivElement(document));
 }
 
-bool HTMLDivElement::isPresentationAttribute(const QualifiedName& name) const
-{
-    if (name == alignAttr)
-        return true;
-    return HTMLElement::isPresentationAttribute(name);
-}
-
 void HTMLDivElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
 {
     if (name == alignAttr) {
diff --git a/Source/core/html/HTMLDivElement.h b/Source/core/html/HTMLDivElement.h
index 12e2300..f810ce4 100644
--- a/Source/core/html/HTMLDivElement.h
+++ b/Source/core/html/HTMLDivElement.h
@@ -35,7 +35,6 @@
     explicit HTMLDivElement(Document&);
 
 private:
-    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 };
 
diff --git a/Source/core/html/HTMLDocument.cpp b/Source/core/html/HTMLDocument.cpp
index 761a6e3..eee2118 100644
--- a/Source/core/html/HTMLDocument.cpp
+++ b/Source/core/html/HTMLDocument.cpp
@@ -111,27 +111,6 @@
     Document::setDesignMode(mode);
 }
 
-Element* HTMLDocument::activeElement()
-{
-    if (Element* element = treeScope().adjustedFocusedElement())
-        return element;
-    return body();
-}
-
-bool HTMLDocument::hasFocus()
-{
-    Page* page = this->page();
-    if (!page)
-        return false;
-    if (!page->focusController().isActive() || !page->focusController().isFocused())
-        return false;
-    if (Frame* focusedFrame = page->focusController().focusedFrame()) {
-        if (focusedFrame->tree().isDescendantOf(frame()))
-            return true;
-    }
-    return false;
-}
-
 HTMLBodyElement* HTMLDocument::htmlBodyElement() const
 {
     HTMLElement* body = this->body();
diff --git a/Source/core/html/HTMLDocument.h b/Source/core/html/HTMLDocument.h
index aa52f77..a0c6220 100644
--- a/Source/core/html/HTMLDocument.h
+++ b/Source/core/html/HTMLDocument.h
@@ -47,9 +47,6 @@
     String designMode() const;
     void setDesignMode(const String&);
 
-    Element* activeElement();
-    bool hasFocus();
-
     const AtomicString& bgColor() const;
     void setBgColor(const AtomicString&);
     const AtomicString& fgColor() const;
diff --git a/Source/core/html/HTMLDocument.idl b/Source/core/html/HTMLDocument.idl
index 84328c8..2b2eb03 100644
--- a/Source/core/html/HTMLDocument.idl
+++ b/Source/core/html/HTMLDocument.idl
@@ -45,9 +45,6 @@
     [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString designMode;
     readonly attribute DOMString compatMode;
 
-    readonly attribute Element activeElement;
-    boolean hasFocus();
-
     // Deprecated attributes
     [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString bgColor;
     [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString fgColor;
diff --git a/Source/core/html/HTMLElement.cpp b/Source/core/html/HTMLElement.cpp
index 18f80f1..79c7fa1 100644
--- a/Source/core/html/HTMLElement.cpp
+++ b/Source/core/html/HTMLElement.cpp
@@ -30,9 +30,8 @@
 #include "HTMLNames.h"
 #include "XMLNames.h"
 #include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ScriptController.h"
 #include "bindings/v8/ScriptEventListener.h"
-#include "core/css/CSSParser.h"
+#include "core/css/CSSMarkup.h"
 #include "core/css/CSSValuePool.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/DocumentFragment.h"
@@ -43,17 +42,16 @@
 #include "core/events/EventListener.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLBRElement.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLTemplateElement.h"
 #include "core/html/HTMLTextFormControlElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/FrameLoader.h"
-#include "core/frame/Frame.h"
-#include "core/page/Settings.h"
-#include "core/rendering/RenderWordBreak.h"
+#include "core/rendering/RenderObject.h"
 #include "platform/text/BidiResolver.h"
+#include "platform/text/BidiTextRun.h"
 #include "platform/text/TextRunIterator.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/CString.h"
@@ -204,7 +202,7 @@
         Element::collectStyleForPresentationAttribute(name, value, style);
 }
 
-const AtomicString& HTMLElement::eventNameForAttributeName(const QualifiedName& attrName) const
+const AtomicString& HTMLElement::eventNameForAttributeName(const QualifiedName& attrName)
 {
     if (!attrName.namespaceURI().isNull())
         return nullAtom;
@@ -283,6 +281,7 @@
         attributeNameToEventNameMap.set(onprogressAttr.localName(), EventTypeNames::progress);
         attributeNameToEventNameMap.set(onratechangeAttr.localName(), EventTypeNames::ratechange);
         attributeNameToEventNameMap.set(onresetAttr.localName(), EventTypeNames::reset);
+        attributeNameToEventNameMap.set(onresizeAttr.localName(), EventTypeNames::resize);
         attributeNameToEventNameMap.set(onseekedAttr.localName(), EventTypeNames::seeked);
         attributeNameToEventNameMap.set(onseekingAttr.localName(), EventTypeNames::seeking);
         attributeNameToEventNameMap.set(onselectAttr.localName(), EventTypeNames::select);
@@ -452,24 +451,6 @@
         mergeWithNextTextNode(prev.release(), exceptionState);
 }
 
-Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& exceptionState)
-{
-    if (!newChild) {
-        // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
-        exceptionState.throwTypeError("The node provided is null.");
-        return 0;
-    }
-
-    Node* returnValue = insertAdjacent(where, newChild, exceptionState);
-    return toElement(returnValue);
-}
-
-void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionState& exceptionState)
-{
-    RefPtr<Text> textNode = document().createTextNode(text);
-    insertAdjacent(where, textNode.get(), exceptionState);
-}
-
 void HTMLElement::applyAlignmentAttributeToStyle(const AtomicString& alignment, MutableStylePropertySet* style)
 {
     // Vertical alignment with respect to the current baseline of the text
@@ -600,7 +581,7 @@
 
 String HTMLElement::title() const
 {
-    return getAttribute(titleAttr);
+    return fastGetAttribute(titleAttr);
 }
 
 short HTMLElement::tabIndex() const
@@ -650,27 +631,6 @@
     setAttribute(translateAttr, enable ? "yes" : "no");
 }
 
-bool HTMLElement::rendererIsNeeded(const RenderStyle& style)
-{
-    if (hasLocalName(noscriptTag)) {
-        Frame* frame = document().frame();
-        if (frame && frame->script().canExecuteScripts(NotAboutToExecuteScript))
-            return false;
-    } else if (hasLocalName(noembedTag)) {
-        Frame* frame = document().frame();
-        if (frame && frame->loader().allowPlugins(NotAboutToInstantiatePlugin))
-            return false;
-    }
-    return Element::rendererIsNeeded(style);
-}
-
-RenderObject* HTMLElement::createRenderer(RenderStyle* style)
-{
-    if (hasLocalName(wbrTag))
-        return new RenderWordBreak(this);
-    return RenderObject::createObject(this, style);
-}
-
 HTMLFormElement* HTMLElement::findFormAncestor() const
 {
     for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
@@ -680,11 +640,6 @@
     return 0;
 }
 
-HTMLFormElement* HTMLElement::virtualForm() const
-{
-    return findFormAncestor();
-}
-
 static inline bool elementAffectsDirectionality(const Node* node)
 {
     return node->isHTMLElement() && (node->hasTagName(bdiTag) || toHTMLElement(node)->hasAttribute(dirAttr));
@@ -736,15 +691,6 @@
     return directionality();
 }
 
-static TextDirection determineDirectionality(const String& value, bool& hasStrongDirectionality)
-{
-    TextRun run(value);
-    BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver;
-    bidiResolver.setStatus(BidiStatus(run.direction(), run.directionalOverride()));
-    bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&run, 0));
-    return bidiResolver.determineParagraphDirectionality(&hasStrongDirectionality);
-}
-
 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
 {
     if (hasTagName(inputTag)) {
@@ -811,7 +757,7 @@
         Element* elementToAdjust = this;
         for (; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
             if (elementAffectsDirectionality(elementToAdjust)) {
-                elementToAdjust->setNeedsStyleRecalc();
+                elementToAdjust->setNeedsStyleRecalc(SubtreeStyleChange);
                 return;
             }
         }
@@ -824,7 +770,7 @@
     TextDirection textDirection = directionality(&strongDirectionalityTextNode);
     setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
     if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection)
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
@@ -960,8 +906,8 @@
         return;
 
     // If the string is a named CSS color or a 3/6-digit hex color, use that.
-    Color parsedColor(colorString);
-    if (!parsedColor.isValid())
+    Color parsedColor;
+    if (!parsedColor.setFromString(colorString))
         parsedColor.setRGB(parseColorStringWithCrazyLegacyRules(colorString));
 
     style->setProperty(propertyID, cssValuePool().createColorValue(parsedColor.rgb()));
diff --git a/Source/core/html/HTMLElement.h b/Source/core/html/HTMLElement.h
index 6e28733..9d94c24 100644
--- a/Source/core/html/HTMLElement.h
+++ b/Source/core/html/HTMLElement.h
@@ -44,17 +44,14 @@
 
     virtual String title() const OVERRIDE FINAL;
 
-    virtual short tabIndex() const;
+    virtual short tabIndex() const OVERRIDE;
     void setTabIndex(int);
 
     void setInnerText(const String&, ExceptionState&);
     void setOuterText(const String&, ExceptionState&);
 
-    Element* insertAdjacentElement(const String& where, Element* newChild, ExceptionState&);
-    void insertAdjacentText(const String& where, const String& text, ExceptionState&);
-
     virtual bool hasCustomFocusLogic() const;
-    virtual bool supportsFocus() const;
+    virtual bool supportsFocus() const OVERRIDE;
 
     String contentEditable() const;
     void setContentEditable(const String&, ExceptionState&);
@@ -70,14 +67,11 @@
 
     void click();
 
-    virtual void accessKeyAction(bool sendMouseEvents);
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
 
     bool ieForbidsInsertHTML() const;
 
-    virtual bool rendererIsNeeded(const RenderStyle&);
-    virtual RenderObject* createRenderer(RenderStyle*);
-
-    HTMLFormElement* formOwner() const { return virtualForm(); }
+    virtual HTMLFormElement* formOwner() const { return 0; }
 
     HTMLFormElement* findFormAncestor() const;
 
@@ -91,6 +85,8 @@
     virtual bool isInteractiveContent() const;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
+    static const AtomicString& eventNameForAttributeName(const QualifiedName& attrName);
+
 protected:
     HTMLElement(const QualifiedName& tagName, Document&, ConstructionType);
 
@@ -105,7 +101,7 @@
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
     unsigned parseBorderWidthAttribute(const AtomicString&) const;
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
     void calculateAndAdjustDirectionality();
 
 private:
@@ -113,8 +109,6 @@
 
     void mapLanguageAttributeToLocale(const AtomicString&, MutableStylePropertySet*);
 
-    virtual HTMLFormElement* virtualForm() const;
-
     PassRefPtr<DocumentFragment> textToFragment(const String&, ExceptionState&);
 
     void dirAttributeChanged(const AtomicString&);
@@ -124,8 +118,6 @@
 
     TranslateAttributeMode translateAttributeMode() const;
 
-    const AtomicString& eventNameForAttributeName(const QualifiedName& attrName) const;
-
     void handleKeypressEvent(KeyboardEvent*);
     bool supportsSpatialNavigationFocus() const;
 };
diff --git a/Source/core/html/HTMLElement.idl b/Source/core/html/HTMLElement.idl
index 5d06568..cfcab73 100644
--- a/Source/core/html/HTMLElement.idl
+++ b/Source/core/html/HTMLElement.idl
@@ -36,11 +36,6 @@
     [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter, MeasureAs=HTMLElementInnerText] attribute DOMString innerText;
     [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter, MeasureAs=HTMLElementOuterText] attribute DOMString outerText;
 
-    [RaisesException, CustomElementCallbacks, MeasureAs=InsertAdjacentElement] Element insertAdjacentElement([Default=Undefined] optional DOMString where,
-                                  [Default=Undefined] optional Element element);
-    [RaisesException, MeasureAs=InsertAdjacentText] void insertAdjacentText([Default=Undefined] optional DOMString where,
-                            [Default=Undefined] optional DOMString text);
-
     [RuntimeEnabled=IMEAPI] readonly attribute InputMethodContext inputMethodContext;
 
     [CustomElementCallbacks, RaisesException=Setter] attribute DOMString contentEditable;
@@ -52,3 +47,4 @@
 };
 
 HTMLElement implements GlobalEventHandlers;
+
diff --git a/Source/core/html/HTMLEmbedElement.cpp b/Source/core/html/HTMLEmbedElement.cpp
index c6bde01..10dcf7a 100644
--- a/Source/core/html/HTMLEmbedElement.cpp
+++ b/Source/core/html/HTMLEmbedElement.cpp
@@ -193,13 +193,6 @@
     return getAttribute(srcAttr);
 }
 
-void HTMLEmbedElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLPlugInElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, document().completeURL(getAttribute(srcAttr)));
-}
-
 bool HTMLEmbedElement::isInteractiveContent() const
 {
     return true;
diff --git a/Source/core/html/HTMLEmbedElement.h b/Source/core/html/HTMLEmbedElement.h
index 8107fd1..b5a8956 100644
--- a/Source/core/html/HTMLEmbedElement.h
+++ b/Source/core/html/HTMLEmbedElement.h
@@ -40,7 +40,7 @@
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
     virtual const AtomicString imageSourceURL() const OVERRIDE;
@@ -49,8 +49,6 @@
 
     virtual void updateWidgetInternal() OVERRIDE;
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-
     void parametersForPlugin(Vector<String>& paramNames, Vector<String>& paramValues);
 
     virtual bool shouldRegisterAsNamedItem() const OVERRIDE { return true; }
diff --git a/Source/core/html/HTMLEmbedElement.idl b/Source/core/html/HTMLEmbedElement.idl
index 74524f3..ef32573 100644
--- a/Source/core/html/HTMLEmbedElement.idl
+++ b/Source/core/html/HTMLEmbedElement.idl
@@ -32,5 +32,5 @@
     [Custom, NotEnumerable] getter Node (DOMString name);
     [Custom] setter Node (DOMString name, Node value);
 
-    [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
+    [CheckSecurity=Node, RaisesException] Document getSVGDocument();
 };
diff --git a/Source/core/html/HTMLFieldSetElement.cpp b/Source/core/html/HTMLFieldSetElement.cpp
index bf568d1..65640c6 100644
--- a/Source/core/html/HTMLFieldSetElement.cpp
+++ b/Source/core/html/HTMLFieldSetElement.cpp
@@ -132,14 +132,4 @@
     return m_associatedElements;
 }
 
-unsigned HTMLFieldSetElement::length() const
-{
-    refreshElementsIfNeeded();
-    unsigned len = 0;
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i)
-        if (m_associatedElements[i]->isEnumeratable())
-            ++len;
-    return len;
-}
-
 } // namespace
diff --git a/Source/core/html/HTMLFieldSetElement.h b/Source/core/html/HTMLFieldSetElement.h
index e083544..b8c3a8d 100644
--- a/Source/core/html/HTMLFieldSetElement.h
+++ b/Source/core/html/HTMLFieldSetElement.h
@@ -39,7 +39,6 @@
     PassRefPtr<HTMLCollection> elements();
 
     const Vector<FormAssociatedElement*>& associatedElements() const;
-    unsigned length() const;
 
 protected:
     virtual void disabledAttributeChanged() OVERRIDE;
@@ -47,11 +46,11 @@
 private:
     HTMLFieldSetElement(Document&, HTMLFormElement*);
 
-    virtual bool isEnumeratable() const { return true; }
-    virtual bool supportsFocus() const;
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual const AtomicString& formControlType() const;
-    virtual bool recalcWillValidate() const { return false; }
+    virtual bool isEnumeratable() const OVERRIDE { return true; }
+    virtual bool supportsFocus() const OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual const AtomicString& formControlType() const OVERRIDE;
+    virtual bool recalcWillValidate() const OVERRIDE { return false; }
     virtual void childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) OVERRIDE;
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
 
diff --git a/Source/core/html/HTMLFontElement.cpp b/Source/core/html/HTMLFontElement.cpp
index 853eae4..5972e6f 100644
--- a/Source/core/html/HTMLFontElement.cpp
+++ b/Source/core/html/HTMLFontElement.cpp
@@ -193,7 +193,7 @@
     } else if (name == colorAttr)
         addHTMLColorToStyle(style, CSSPropertyColor, value);
     else if (name == faceAttr) {
-        if (RefPtr<CSSValueList> fontFaceValue = cssValuePool().createFontFaceValue(value))
+        if (RefPtrWillBeRawPtr<CSSValueList> fontFaceValue = cssValuePool().createFontFaceValue(value))
             style->setProperty(CSSProperty(CSSPropertyFontFamily, fontFaceValue.release()));
     } else
         HTMLElement::collectStyleForPresentationAttribute(name, value, style);
diff --git a/Source/core/html/HTMLFormControlElement.cpp b/Source/core/html/HTMLFormControlElement.cpp
index 4e361a6..5efd66f 100644
--- a/Source/core/html/HTMLFormControlElement.cpp
+++ b/Source/core/html/HTMLFormControlElement.cpp
@@ -32,7 +32,6 @@
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLLegendElement.h"
-#include "core/html/HTMLTextAreaElement.h"
 #include "core/html/ValidityState.h"
 #include "core/html/forms/ValidationMessage.h"
 #include "core/frame/UseCounter.h"
@@ -59,10 +58,9 @@
     , m_isValid(true)
     , m_wasChangedSinceLastFormControlChangeEvent(false)
     , m_wasFocusedByMouse(false)
-    , m_hasAutofocused(false)
 {
-    setForm(form ? form : findFormAncestor());
     setHasCustomStyleCallbacks();
+    associateByParser(form);
 }
 
 HTMLFormControlElement::~HTMLFormControlElement()
@@ -143,7 +141,7 @@
         m_isReadOnly = !value.isNull();
         if (wasReadOnly != m_isReadOnly) {
             setNeedsWillValidateCheck();
-            setNeedsStyleRecalc();
+            setNeedsStyleRecalc(SubtreeStyleChange);
             if (renderer() && renderer()->style()->hasAppearance())
                 RenderTheme::theme().stateChanged(renderer(), ReadOnlyState);
         }
@@ -178,33 +176,17 @@
     setNeedsValidityCheck();
     // Style recalculation is needed because style selectors may include
     // :required and :optional pseudo-classes.
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
-static void focusPostAttach(Node* element)
+bool HTMLFormControlElement::supportsAutofocus() const
 {
-    toElement(element)->focus();
-    element->deref();
+    return false;
 }
 
 bool HTMLFormControlElement::isAutofocusable() const
 {
-    if (!fastHasAttribute(autofocusAttr))
-        return false;
-
-    // FIXME: Should this set of hasTagName checks be replaced by a
-    // virtual member function?
-    if (hasTagName(inputTag))
-        return !toHTMLInputElement(this)->isInputTypeHidden();
-    if (hasTagName(selectTag))
-        return true;
-    if (hasTagName(keygenTag))
-        return true;
-    if (hasTagName(buttonTag))
-        return true;
-    if (isHTMLTextAreaElement(this))
-        return true;
-    return false;
+    return fastHasAttribute(autofocusAttr) && supportsAutofocus();
 }
 
 void HTMLFormControlElement::setAutofilled(bool autofilled)
@@ -213,15 +195,13 @@
         return;
 
     m_isAutofilled = autofilled;
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 static bool shouldAutofocusOnAttach(const HTMLFormControlElement* element)
 {
     if (!element->isAutofocusable())
         return false;
-    if (element->hasAutofocused())
-        return false;
     if (element->document().isSandboxed(SandboxAutomaticFeatures)) {
         // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
         element->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked autofocusing on a form control because the form's frame is sandboxed and the 'allow-scripts' permission is not set.");
@@ -243,11 +223,10 @@
     // on the renderer.
     renderer()->updateFromElement();
 
-    if (shouldAutofocusOnAttach(this)) {
-        setAutofocused();
-        ref();
-        PostAttachCallbacks::queueCallback(focusPostAttach, this);
-    }
+    // FIXME: Autofocus handling should be moved to insertedInto according to
+    // the standard.
+    if (shouldAutofocusOnAttach(this))
+        document().setAutofocusElement(this);
 }
 
 void HTMLFormControlElement::didMoveToNewDocument(Document& oldDocument)
@@ -275,19 +254,19 @@
     FormAssociatedElement::removedFrom(insertionPoint);
 }
 
-bool HTMLFormControlElement::wasChangedSinceLastFormControlChangeEvent() const
-{
-    return m_wasChangedSinceLastFormControlChangeEvent;
-}
-
 void HTMLFormControlElement::setChangedSinceLastFormControlChangeEvent(bool changed)
 {
     m_wasChangedSinceLastFormControlChangeEvent = changed;
 }
 
+void HTMLFormControlElement::dispatchChangeEvent()
+{
+    dispatchScopedEvent(Event::createBubble(EventTypeNames::change));
+}
+
 void HTMLFormControlElement::dispatchFormControlChangeEvent()
 {
-    HTMLElement::dispatchChangeEvent();
+    dispatchChangeEvent();
     setChangedSinceLastFormControlChangeEvent(false);
 }
 
@@ -297,6 +276,11 @@
     HTMLElement::dispatchInputEvent();
 }
 
+HTMLFormElement* HTMLFormControlElement::formOwner() const
+{
+    return FormAssociatedElement::form();
+}
+
 bool HTMLFormControlElement::isDisabledFormControl() const
 {
     if (m_disabled)
@@ -317,20 +301,10 @@
     return fastGetAttribute(valueAttr);
 }
 
-static void updateFromElementCallback(Node* node)
-{
-    ASSERT_ARG(node, node->isElementNode());
-    ASSERT_ARG(node, toElement(node)->isFormControlElement());
-    if (RenderObject* renderer = node->renderer())
-        renderer->updateFromElement();
-}
-
 void HTMLFormControlElement::didRecalcStyle(StyleRecalcChange)
 {
-    // updateFromElement() can cause the selection to change, and in turn
-    // trigger synchronous layout, so it must not be called during style recalc.
-    if (renderer())
-        PostAttachCallbacks::queueCallback(updateFromElementCallback, this);
+    if (RenderObject* renderer = this->renderer())
+        renderer->updateFromElement();
 }
 
 bool HTMLFormControlElement::supportsFocus() const
@@ -349,11 +323,11 @@
     return false;
 }
 
-void HTMLFormControlElement::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection direction)
+void HTMLFormControlElement::dispatchFocusEvent(Element* oldFocusedElement, FocusType type)
 {
-    if (direction != FocusDirectionPage)
-        m_wasFocusedByMouse = direction == FocusDirectionMouse;
-    HTMLElement::dispatchFocusEvent(oldFocusedElement, direction);
+    if (type != FocusTypePage)
+        m_wasFocusedByMouse = type == FocusTypeMouse;
+    HTMLElement::dispatchFocusEvent(oldFocusedElement, type);
 }
 
 bool HTMLFormControlElement::shouldHaveFocusAppearance() const
@@ -422,7 +396,7 @@
     m_willValidateInitialized = true;
     m_willValidate = newWillValidate;
     setNeedsValidityCheck();
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
     if (!m_willValidate)
         hideVisibleValidationMessage();
 }
@@ -474,11 +448,11 @@
     bool newIsValid = valid();
     if (willValidate() && newIsValid != m_isValid) {
         // Update style for pseudo classes such as :valid :invalid.
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
     }
     m_isValid = newIsValid;
 
-    // Updates only if this control already has a validtion message.
+    // Updates only if this control already has a validation message.
     if (m_validationMessage && m_validationMessage->isVisible()) {
         // Calls updateVisibleValidationMessage() even if m_isValid is not
         // changed because a validation message can be chagned.
@@ -498,11 +472,6 @@
     hideVisibleValidationMessage();
 }
 
-HTMLFormElement* HTMLFormControlElement::virtualForm() const
-{
-    return FormAssociatedElement::form();
-}
-
 bool HTMLFormControlElement::isSuccessfulSubmitButton() const
 {
     return canBeSuccessfulSubmitButton() && !isDisabledFormControl();
@@ -533,4 +502,12 @@
     return trimmedName;
 }
 
+void HTMLFormControlElement::setFocus(bool flag)
+{
+    LabelableElement::setFocus(flag);
+
+    if (!flag && wasChangedSinceLastFormControlChangeEvent())
+        dispatchFormControlChangeEvent();
+}
+
 } // namespace Webcore
diff --git a/Source/core/html/HTMLFormControlElement.h b/Source/core/html/HTMLFormControlElement.h
index f2699a0..44d3315 100644
--- a/Source/core/html/HTMLFormControlElement.h
+++ b/Source/core/html/HTMLFormControlElement.h
@@ -56,27 +56,30 @@
     virtual bool formControlValueMatchesRenderer() const { return m_valueMatchesRenderer; }
     virtual void setFormControlValueMatchesRenderer(bool b) { m_valueMatchesRenderer = b; }
 
-    virtual bool wasChangedSinceLastFormControlChangeEvent() const;
-    virtual void setChangedSinceLastFormControlChangeEvent(bool);
+    bool wasChangedSinceLastFormControlChangeEvent() const { return m_wasChangedSinceLastFormControlChangeEvent; }
+    void setChangedSinceLastFormControlChangeEvent(bool);
 
     virtual void dispatchFormControlChangeEvent();
-    virtual void dispatchFormControlInputEvent();
+    void dispatchChangeEvent();
+    void dispatchFormControlInputEvent();
+
+    virtual HTMLFormElement* formOwner() const OVERRIDE FINAL;
 
     virtual bool isDisabledFormControl() const OVERRIDE;
 
-    virtual bool isEnumeratable() const { return false; }
+    virtual bool isEnumeratable() const OVERRIDE { return false; }
 
     bool isRequired() const;
 
     const AtomicString& type() const { return formControlType(); }
 
-    virtual const AtomicString& formControlType() const OVERRIDE = 0;
+    virtual const AtomicString& formControlType() const = 0;
 
     virtual bool canTriggerImplicitSubmission() const { return false; }
 
     // Override in derived classes to get the encoded name=value pair for submitting.
     // Return true for a successful control (see HTML4-17.13.2).
-    virtual bool appendFormData(FormDataList&, bool) { return false; }
+    virtual bool appendFormData(FormDataList&, bool) OVERRIDE { return false; }
     virtual String resultForDialogSubmit();
 
     virtual bool canBeSuccessfulSubmitButton() const { return false; }
@@ -86,19 +89,17 @@
 
     enum CheckValidityDispatchEvents { CheckValidityDispatchEventsAllowed, CheckValidityDispatchEventsNone };
 
-    virtual bool willValidate() const;
+    virtual bool willValidate() const OVERRIDE;
     void updateVisibleValidationMessage();
     void hideVisibleValidationMessage();
     bool checkValidity(Vector<RefPtr<FormAssociatedElement> >* unhandledInvalidControls = 0, CheckValidityDispatchEvents = CheckValidityDispatchEventsAllowed);
     // This must be called when a validation constraint or control value is changed.
     void setNeedsValidityCheck();
-    virtual void setCustomValidity(const String&) OVERRIDE;
+    virtual void setCustomValidity(const String&) OVERRIDE FINAL;
 
     bool isReadOnly() const { return m_isReadOnly; }
     bool isDisabledOrReadOnly() const { return isDisabledFormControl() || m_isReadOnly; }
 
-    bool hasAutofocused() const { return m_hasAutofocused; }
-    void setAutofocused() { m_hasAutofocused = true; }
     bool isAutofocusable() const;
 
     bool isAutofilled() const { return m_isAutofilled; }
@@ -108,6 +109,8 @@
 
     String nameForAutofill() const;
 
+    virtual void setFocus(bool flag) OVERRIDE;
+
     using Node::ref;
     using Node::deref;
 
@@ -125,31 +128,31 @@
     virtual bool supportsFocus() const OVERRIDE;
     virtual bool isKeyboardFocusable() const OVERRIDE;
     virtual bool shouldShowFocusRingOnMouseFocus() const;
-    virtual bool shouldHaveFocusAppearance() const OVERRIDE;
-    virtual void dispatchFocusEvent(Element* oldFocusedElement, FocusDirection) OVERRIDE;
+    virtual bool shouldHaveFocusAppearance() const OVERRIDE FINAL;
+    virtual void dispatchFocusEvent(Element* oldFocusedElement, FocusType) OVERRIDE;
     virtual void dispatchBlurEvent(Element* newFocusedElement) OVERRIDE;
-    virtual void willCallDefaultEventHandler(const Event&) OVERRIDE;
+    virtual void willCallDefaultEventHandler(const Event&) OVERRIDE FINAL;
 
-    virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE;
+    virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE FINAL;
 
     // This must be called any time the result of willValidate() has changed.
     void setNeedsWillValidateCheck();
     virtual bool recalcWillValidate() const;
 
     virtual void resetImpl() { }
+    virtual bool supportsAutofocus() const;
 
 private:
-    virtual void refFormAssociatedElement() { ref(); }
-    virtual void derefFormAssociatedElement() { deref(); }
+    virtual void refFormAssociatedElement() OVERRIDE FINAL { ref(); }
+    virtual void derefFormAssociatedElement() OVERRIDE FINAL { deref(); }
 
-    virtual bool isFormControlElement() const { return true; }
+    virtual bool isFormControlElement() const OVERRIDE FINAL { return true; }
     virtual bool alwaysCreateUserAgentShadowRoot() const OVERRIDE { return true; }
 
-    virtual short tabIndex() const;
+    virtual short tabIndex() const OVERRIDE FINAL;
 
-    virtual HTMLFormElement* virtualForm() const;
-    virtual bool isDefaultButtonForForm() const;
-    virtual bool isValidFormControlElement();
+    virtual bool isDefaultButtonForForm() const OVERRIDE FINAL;
+    virtual bool isValidFormControlElement() OVERRIDE FINAL;
     void updateAncestorDisabledState() const;
 
     OwnPtr<ValidationMessage> m_validationMessage;
@@ -176,7 +179,6 @@
 
     bool m_wasChangedSinceLastFormControlChangeEvent : 1;
     bool m_wasFocusedByMouse : 1;
-    bool m_hasAutofocused : 1;
 };
 
 inline bool isHTMLFormControlElement(const Node& node)
@@ -185,30 +187,7 @@
 }
 
 DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLFormControlElement);
-
-inline HTMLFormControlElement* toHTMLFormControlElement(FormAssociatedElement* control)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!control || control->isFormControlElement());
-    return static_cast<HTMLFormControlElement*>(control);
-}
-
-inline HTMLFormControlElement& toHTMLFormControlElement(FormAssociatedElement& control)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(control.isFormControlElement());
-    return static_cast<HTMLFormControlElement&>(control);
-}
-
-inline const HTMLFormControlElement* toHTMLFormControlElement(const FormAssociatedElement* control)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!control || control->isFormControlElement());
-    return static_cast<const HTMLFormControlElement*>(control);
-}
-
-inline const HTMLFormControlElement& toHTMLFormControlElement(const FormAssociatedElement& control)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(control.isFormControlElement());
-    return static_cast<const HTMLFormControlElement&>(control);
-}
+DEFINE_TYPE_CASTS(HTMLFormControlElement, FormAssociatedElement, control, control->isFormControlElement(), control.isFormControlElement());
 
 } // namespace
 
diff --git a/Source/core/html/HTMLFormControlElementWithState.cpp b/Source/core/html/HTMLFormControlElementWithState.cpp
index 1508d79..3c9b9c5 100644
--- a/Source/core/html/HTMLFormControlElementWithState.cpp
+++ b/Source/core/html/HTMLFormControlElementWithState.cpp
@@ -25,12 +25,12 @@
 #include "config.h"
 #include "core/html/HTMLFormControlElementWithState.h"
 
+#include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/forms/FormController.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/frame/Frame.h"
-#include "core/page/Page.h"
 
 namespace WebCore {
 
@@ -46,14 +46,14 @@
 Node::InsertionNotificationRequest HTMLFormControlElementWithState::insertedInto(ContainerNode* insertionPoint)
 {
     if (insertionPoint->inDocument() && !containingShadowRoot())
-        document().formController()->registerFormElementWithState(this);
+        document().formController()->registerStatefulFormControl(*this);
     return HTMLFormControlElement::insertedInto(insertionPoint);
 }
 
 void HTMLFormControlElementWithState::removedFrom(ContainerNode* insertionPoint)
 {
     if (insertionPoint->inDocument() && !containingShadowRoot() && !insertionPoint->containingShadowRoot())
-        document().formController()->unregisterFormElementWithState(this);
+        document().formController()->unregisterStatefulFormControl(*this);
     HTMLFormControlElement::removedFrom(insertionPoint);
 }
 
@@ -66,12 +66,11 @@
 
 void HTMLFormControlElementWithState::notifyFormStateChanged()
 {
-    Frame* frame = document().frame();
-    if (!frame)
+    // This can be called during fragment parsing as a result of option
+    // selection before the document is active (or even in a frame).
+    if (!document().isActive())
         return;
-
-    if (Page* page = frame->page())
-        page->chrome().client().formStateDidChange(this);
+    document().frame()->host()->chrome().client().formStateDidChange(this);
 }
 
 bool HTMLFormControlElementWithState::shouldSaveAndRestoreFormControlState() const
diff --git a/Source/core/html/HTMLFormControlElementWithState.h b/Source/core/html/HTMLFormControlElementWithState.h
index 57bd66a..f6f7867 100644
--- a/Source/core/html/HTMLFormControlElementWithState.h
+++ b/Source/core/html/HTMLFormControlElementWithState.h
@@ -34,7 +34,7 @@
 public:
     virtual ~HTMLFormControlElementWithState();
 
-    virtual bool canContainRangeEndPoint() const { return false; }
+    virtual bool canContainRangeEndPoint() const OVERRIDE FINAL { return false; }
 
     virtual bool shouldSaveAndRestoreFormControlState() const;
     virtual FormControlState saveFormControlState() const;
@@ -46,17 +46,13 @@
     HTMLFormControlElementWithState(const QualifiedName& tagName, Document&, HTMLFormElement*);
 
     virtual bool shouldAutocomplete() const;
-    virtual void finishParsingChildren();
+    virtual void finishParsingChildren() OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual bool isFormControlElementWithState() const OVERRIDE;
+    virtual bool isFormControlElementWithState() const OVERRIDE FINAL;
 };
 
-inline HTMLFormControlElementWithState* toHTMLFormControlElementWithState(FormAssociatedElement* element)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isFormControlElementWithState());
-    return static_cast<HTMLFormControlElementWithState*>(element);
-}
+DEFINE_TYPE_CASTS(HTMLFormControlElementWithState, FormAssociatedElement, control, control->isFormControlElementWithState(), control.isFormControlElementWithState());
 
 } // namespace
 
diff --git a/Source/core/html/HTMLFormControlsCollection.cpp b/Source/core/html/HTMLFormControlsCollection.cpp
index 972bb75..6b2a290 100644
--- a/Source/core/html/HTMLFormControlsCollection.cpp
+++ b/Source/core/html/HTMLFormControlsCollection.cpp
@@ -2,6 +2,7 @@
  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -24,9 +25,11 @@
 #include "core/html/HTMLFormControlsCollection.h"
 
 #include "HTMLNames.h"
+#include "core/frame/UseCounter.h"
 #include "core/html/HTMLFieldSetElement.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLImageElement.h"
+#include "wtf/HashSet.h"
 
 namespace WebCore {
 
@@ -35,14 +38,16 @@
 // Since the collections are to be "live", we have to do the
 // calculation every time if anything has changed.
 
-HTMLFormControlsCollection::HTMLFormControlsCollection(Node* ownerNode)
+HTMLFormControlsCollection::HTMLFormControlsCollection(ContainerNode* ownerNode)
     : HTMLCollection(ownerNode, FormControls, OverridesItemAfter)
+    , m_cachedElement(0)
+    , m_cachedElementOffsetInArray(0)
 {
     ASSERT(ownerNode->hasTagName(formTag) || ownerNode->hasTagName(fieldsetTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLFormControlsCollection> HTMLFormControlsCollection::create(Node* ownerNode, CollectionType)
+PassRefPtr<HTMLFormControlsCollection> HTMLFormControlsCollection::create(ContainerNode* ownerNode, CollectionType)
 {
     return adoptRef(new HTMLFormControlsCollection(ownerNode));
 }
@@ -66,20 +71,46 @@
     return toHTMLFormElement(ownerNode())->imageElements();
 }
 
-Element* HTMLFormControlsCollection::virtualItemAfter(unsigned& offset, Element* previousItem) const
+static unsigned findFormAssociatedElement(const Vector<FormAssociatedElement*>& associatedElements, Element* element)
 {
-    const Vector<FormAssociatedElement*>& elementsArray = formControlElements();
-    if (previousItem)
-        offset++;
-    while (offset < elementsArray.size()) {
-        FormAssociatedElement* element = elementsArray[offset];
-        if (element->isEnumeratable())
-            return toHTMLElement(element);
-        offset++;
+    unsigned i = 0;
+    for (; i < associatedElements.size(); ++i) {
+        FormAssociatedElement* associatedElement = associatedElements[i];
+        if (associatedElement->isEnumeratable() && toHTMLElement(associatedElement) == element)
+            break;
+    }
+    return i;
+}
+
+Element* HTMLFormControlsCollection::virtualItemAfter(Element* previous) const
+{
+    const Vector<FormAssociatedElement*>& associatedElements = formControlElements();
+    unsigned offset;
+    if (!previous)
+        offset = 0;
+    else if (m_cachedElement == previous)
+        offset = m_cachedElementOffsetInArray + 1;
+    else
+        offset = findFormAssociatedElement(associatedElements, previous) + 1;
+
+    for (unsigned i = offset; i < associatedElements.size(); ++i) {
+        FormAssociatedElement* associatedElement = associatedElements[i];
+        if (associatedElement->isEnumeratable()) {
+            m_cachedElement = toHTMLElement(associatedElement);
+            m_cachedElementOffsetInArray = i;
+            return m_cachedElement;
+        }
     }
     return 0;
 }
 
+void HTMLFormControlsCollection::invalidateCache(Document* oldDocument) const
+{
+    HTMLCollection::invalidateCache(oldDocument);
+    m_cachedElement = 0;
+    m_cachedElementOffsetInArray = 0;
+}
+
 static HTMLElement* firstNamedItem(const Vector<FormAssociatedElement*>& elementsArray,
     const Vector<HTMLImageElement*>* imageElementsArray, const QualifiedName& attrName, const String& name)
 {
@@ -96,14 +127,16 @@
 
     for (unsigned i = 0; i < imageElementsArray->size(); ++i) {
         HTMLImageElement* element = (*imageElementsArray)[i];
-        if (element->fastGetAttribute(attrName) == name)
+        if (element->fastGetAttribute(attrName) == name) {
+            UseCounter::count(element->document(), UseCounter::FormNameAccessForImageElement);
             return element;
+        }
     }
 
     return 0;
 }
 
-Node* HTMLFormControlsCollection::namedItem(const AtomicString& name) const
+Element* HTMLFormControlsCollection::namedItem(const AtomicString& name) const
 {
     // http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/nameditem.asp
     // This method first searches for an object with a matching id
@@ -117,9 +150,9 @@
     return firstNamedItem(formControlElements(), imagesElements, nameAttr, name);
 }
 
-void HTMLFormControlsCollection::updateNameCache() const
+void HTMLFormControlsCollection::updateIdNameCache() const
 {
-    if (hasNameCache())
+    if (hasValidIdNameCache())
         return;
 
     HashSet<StringImpl*> foundInputElements;
@@ -156,25 +189,52 @@
         }
     }
 
-    setHasNameCache();
+    setHasValidIdNameCache();
 }
 
-void HTMLFormControlsCollection::namedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<RadioNodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Node>& returnValue1)
+void HTMLFormControlsCollection::namedGetter(const AtomicString& name, bool& radioNodeListEnabled, RefPtr<RadioNodeList>& radioNodeList, bool& elementEnabled, RefPtr<Element>& element)
 {
-    Vector<RefPtr<Node> > namedItems;
+    Vector<RefPtr<Element> > namedItems;
     this->namedItems(name, namedItems);
 
-    if (!namedItems.size())
+    if (namedItems.isEmpty())
         return;
 
     if (namedItems.size() == 1) {
-        returnValue1Enabled = true;
-        returnValue1 = namedItems.at(0);
+        elementEnabled = true;
+        element = namedItems.first();
         return;
     }
 
-    returnValue0Enabled = true;
-    returnValue0 = this->ownerNode()->radioNodeList(name);
+    radioNodeListEnabled = true;
+    radioNodeList = ownerNode()->radioNodeList(name);
+}
+
+void HTMLFormControlsCollection::supportedPropertyNames(Vector<String>& names)
+{
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#htmlformcontrolscollection-0:
+    // The supported property names consist of the non-empty values of all the id and name attributes
+    // of all the elements represented by the collection, in tree order, ignoring later duplicates,
+    // with the id of an element preceding its name if it contributes both, they differ from each
+    // other, and neither is the duplicate of an earlier entry.
+    HashSet<AtomicString> existingNames;
+    unsigned length = this->length();
+    for (unsigned i = 0; i < length; ++i) {
+        Element* element = item(i);
+        ASSERT(element);
+        const AtomicString& idAttribute = element->getIdAttribute();
+        if (!idAttribute.isEmpty()) {
+            HashSet<AtomicString>::AddResult addResult = existingNames.add(idAttribute);
+            if (addResult.isNewEntry)
+                names.append(idAttribute);
+        }
+        const AtomicString& nameAttribute = element->getNameAttribute();
+        if (!nameAttribute.isEmpty()) {
+            HashSet<AtomicString>::AddResult addResult = existingNames.add(nameAttribute);
+            if (addResult.isNewEntry)
+                names.append(nameAttribute);
+        }
+    }
 }
 
 }
diff --git a/Source/core/html/HTMLFormControlsCollection.h b/Source/core/html/HTMLFormControlsCollection.h
index 45b286c..d5d7029 100644
--- a/Source/core/html/HTMLFormControlsCollection.h
+++ b/Source/core/html/HTMLFormControlsCollection.h
@@ -2,6 +2,7 @@
  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -38,21 +39,26 @@
 
 class HTMLFormControlsCollection FINAL : public HTMLCollection {
 public:
-    static PassRefPtr<HTMLFormControlsCollection> create(Node*, CollectionType);
+    static PassRefPtr<HTMLFormControlsCollection> create(ContainerNode*, CollectionType);
 
     virtual ~HTMLFormControlsCollection();
 
-    virtual Node* namedItem(const AtomicString& name) const;
-    void namedGetter(const AtomicString& name, bool&, RefPtr<RadioNodeList>&, bool&, RefPtr<Node>&);
+    virtual Element* namedItem(const AtomicString& name) const OVERRIDE;
+    void namedGetter(const AtomicString& name, bool& radioNodeListEnabled, RefPtr<RadioNodeList>&, bool& elementEnabled, RefPtr<Element>&);
 
 private:
-    explicit HTMLFormControlsCollection(Node*);
+    explicit HTMLFormControlsCollection(ContainerNode*);
 
-    virtual void updateNameCache() const OVERRIDE;
+    virtual void updateIdNameCache() const OVERRIDE;
+    virtual void supportedPropertyNames(Vector<String>& names) OVERRIDE;
 
     const Vector<FormAssociatedElement*>& formControlElements() const;
     const Vector<HTMLImageElement*>& formImageElements() const;
-    virtual Element* virtualItemAfter(unsigned& offsetInArray, Element*) const OVERRIDE;
+    virtual Element* virtualItemAfter(Element*) const OVERRIDE;
+    virtual void invalidateCache(Document* oldDocument = 0) const OVERRIDE;
+
+    mutable Element* m_cachedElement;
+    mutable unsigned m_cachedElementOffsetInArray;
 };
 
 } // namespace
diff --git a/Source/core/html/HTMLFormControlsCollection.idl b/Source/core/html/HTMLFormControlsCollection.idl
index f483a67..5ed779f 100644
--- a/Source/core/html/HTMLFormControlsCollection.idl
+++ b/Source/core/html/HTMLFormControlsCollection.idl
@@ -1,6 +1,7 @@
 /*
  * Copyright (C) 2006, 2007, 2012 Apple Inc. All rights reserved.
  * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -20,9 +21,8 @@
 
 [
     DependentLifetime,
-    GenerateVisitDOMWrapper=ownerNode,
+    SetWrapperReferenceFrom=ownerNode,
 ] interface HTMLFormControlsCollection : HTMLCollection {
-    [ImplementedAs=item] getter Node(unsigned long index);
-    [Custom] Node namedItem([Default=Undefined] optional DOMString name);
-    [ImplementedAs=namedGetter, NotEnumerable] getter (RadioNodeList or Node)(DOMString name);
+    [ImplementedAs=item] getter Node (unsigned long index);
+    [ImplementedAs=namedGetter] getter (RadioNodeList or Element) namedItem(DOMString name); // shadows inherited namedItem()
 };
diff --git a/Source/core/html/HTMLFormElement.cpp b/Source/core/html/HTMLFormElement.cpp
index aa4888b..7e5a785 100644
--- a/Source/core/html/HTMLFormElement.cpp
+++ b/Source/core/html/HTMLFormElement.cpp
@@ -32,7 +32,7 @@
 #include "core/dom/Attribute.h"
 #include "core/dom/Document.h"
 #include "core/dom/ElementTraversal.h"
-#include "core/dom/NamedNodesCollection.h"
+#include "core/dom/IdTargetObserverRegistry.h"
 #include "core/events/AutocompleteErrorEvent.h"
 #include "core/events/Event.h"
 #include "core/events/ScopedEventQueue.h"
@@ -42,7 +42,7 @@
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLObjectElement.h"
-#include "core/html/HTMLTableElement.h"
+#include "core/html/RadioNodeList.h"
 #include "core/html/forms/FormController.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
@@ -61,8 +61,11 @@
 
 HTMLFormElement::HTMLFormElement(Document& document)
     : HTMLElement(formTag, document)
-    , m_associatedElementsBeforeIndex(0)
-    , m_associatedElementsAfterIndex(0)
+    , m_weakPtrFactory(this)
+    , m_associatedElementsAreDirty(false)
+    , m_imageElementsAreDirty(false)
+    , m_hasElementsAssociatedByParser(false)
+    , m_didFinishParsingChildren(false)
     , m_wasUserSubmitted(false)
     , m_isSubmittingOrPreparingForSubmission(false)
     , m_shouldSubmit(false)
@@ -82,16 +85,6 @@
 HTMLFormElement::~HTMLFormElement()
 {
     document().formController()->willDeleteForm(this);
-
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i)
-        m_associatedElements[i]->formWillBeDestroyed();
-    for (unsigned i = 0; i < m_imageElements.size(); ++i)
-        m_imageElements[i]->m_form = 0;
-}
-
-bool HTMLFormElement::formWouldHaveSecureSubmission(const String& url)
-{
-    return document().completeURL(url).protocolIs("https");
 }
 
 bool HTMLFormElement::rendererIsNeeded(const RenderStyle& style)
@@ -103,7 +96,7 @@
     RenderObject* parentRenderer = node->renderer();
     // FIXME: Shouldn't we also check for table caption (see |formIsTablePart| below).
     // FIXME: This check is not correct for Shadow DOM.
-    bool parentIsTableElementPart = (parentRenderer->isTable() && isHTMLTableElement(node))
+    bool parentIsTableElementPart = (parentRenderer->isTable() && node->hasTagName(tableTag))
         || (parentRenderer->isTableRow() && node->hasTagName(trTag))
         || (parentRenderer->isTableSection() && node->hasTagName(tbodyTag))
         || (parentRenderer->isRenderTableCol() && node->hasTagName(colTag))
@@ -129,20 +122,43 @@
     return InsertionDone;
 }
 
-static inline Node* findRoot(Node* n)
+template<class T>
+void notifyFormRemovedFromTree(const Vector<T*>& elements, Node* root)
 {
-    Node* root = n;
-    for (; n; n = n->parentNode())
-        root = n;
-    return root;
+    size_t size = elements.size();
+    for (size_t i = 0; i < size; ++i)
+        elements[i]->formRemovedFromTree(root);
+    ASSERT(elements.size() == size);
 }
 
 void HTMLFormElement::removedFrom(ContainerNode* insertionPoint)
 {
-    Node* root = findRoot(this);
-    Vector<FormAssociatedElement*> associatedElements(m_associatedElements);
-    for (unsigned i = 0; i < associatedElements.size(); ++i)
-        associatedElements[i]->formRemovedFromTree(root);
+    // We don't need to take care of form association by 'form' content
+    // attribute becuse IdTargetObserver handles it.
+    if (m_hasElementsAssociatedByParser) {
+        Node* root = highestAncestor();
+        if (!m_associatedElementsAreDirty) {
+            Vector<FormAssociatedElement*> elements(associatedElements());
+            notifyFormRemovedFromTree(elements, root);
+        } else {
+            Vector<FormAssociatedElement*> elements;
+            collectAssociatedElements(insertionPoint->highestAncestor(), elements);
+            notifyFormRemovedFromTree(elements, root);
+            collectAssociatedElements(root, elements);
+            notifyFormRemovedFromTree(elements, root);
+        }
+
+        if (!m_imageElementsAreDirty) {
+            Vector<HTMLImageElement*> images(imageElements());
+            notifyFormRemovedFromTree(images, root);
+        } else {
+            Vector<HTMLImageElement*> images;
+            collectImageElements(insertionPoint->highestAncestor(), images);
+            notifyFormRemovedFromTree(images, root);
+            collectImageElements(root, images);
+            notifyFormRemovedFromTree(images, root);
+        }
+    }
     HTMLElement::removedFrom(insertionPoint);
 }
 
@@ -158,14 +174,16 @@
 
 unsigned HTMLFormElement::length() const
 {
+    const Vector<FormAssociatedElement*>& elements = associatedElements();
     unsigned len = 0;
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i)
-        if (m_associatedElements[i]->isEnumeratable())
+    for (unsigned i = 0; i < elements.size(); ++i) {
+        if (elements[i]->isEnumeratable())
             ++len;
+    }
     return len;
 }
 
-Node* HTMLFormElement::item(unsigned index)
+Element* HTMLFormElement::item(unsigned index)
 {
     return elements()->item(index);
 }
@@ -174,8 +192,9 @@
 {
     int submissionTriggerCount = 0;
     bool seenDefaultButton = false;
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
-        FormAssociatedElement* formAssociatedElement = m_associatedElements[i];
+    const Vector<FormAssociatedElement*>& elements = associatedElements();
+    for (unsigned i = 0; i < elements.size(); ++i) {
+        FormAssociatedElement* formAssociatedElement = elements[i];
         if (!formAssociatedElement->isFormControlElement())
             continue;
         HTMLFormControlElement* control = toHTMLFormControlElement(formAssociatedElement);
@@ -219,9 +238,10 @@
     if (submitElement && submitElement->formNoValidate())
         return true;
 
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
-        if (m_associatedElements[i]->isFormControlElement())
-            toHTMLFormControlElement(m_associatedElements[i])->hideVisibleValidationMessage();
+    const Vector<FormAssociatedElement*>& elements = associatedElements();
+    for (unsigned i = 0; i < elements.size(); ++i) {
+        if (elements[i]->isFormControlElement())
+            toHTMLFormControlElement(elements[i])->hideVisibleValidationMessage();
     }
 
     Vector<RefPtr<FormAssociatedElement> > unhandledInvalidControls;
@@ -308,9 +328,10 @@
 {
     ASSERT_ARG(fieldNamesAndValues, fieldNamesAndValues.isEmpty());
 
-    fieldNamesAndValues.reserveCapacity(m_associatedElements.size());
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
-        FormAssociatedElement* control = m_associatedElements[i];
+    const Vector<FormAssociatedElement*>& elements = associatedElements();
+    fieldNamesAndValues.reserveCapacity(elements.size());
+    for (unsigned i = 0; i < elements.size(); ++i) {
+        FormAssociatedElement* control = elements[i];
         HTMLElement* element = toHTMLElement(control);
         if (!element->hasTagName(inputTag))
             continue;
@@ -351,8 +372,9 @@
     RefPtr<HTMLFormControlElement> firstSuccessfulSubmitButton;
     bool needButtonActivation = activateSubmitButton; // do we need to activate a submit button?
 
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
-        FormAssociatedElement* associatedElement = m_associatedElements[i];
+    const Vector<FormAssociatedElement*>& elements = associatedElements();
+    for (unsigned i = 0; i < elements.size(); ++i) {
+        FormAssociatedElement* associatedElement = elements[i];
         if (!associatedElement->isFormControlElement())
             continue;
         if (needButtonActivation) {
@@ -412,8 +434,8 @@
     if (!targetFrame->page())
         return;
 
-    submission->setReferrer(document().frame()->loader().outgoingReferrer());
-    submission->setOrigin(document().frame()->loader().outgoingOrigin());
+    submission->setReferrer(Referrer(document().outgoingReferrer(), document().referrerPolicy()));
+    submission->setOrigin(document().outgoingOrigin());
 
     targetFrame->navigationScheduler().scheduleFormSubmission(submission);
 }
@@ -431,9 +453,10 @@
         return;
     }
 
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
-        if (m_associatedElements[i]->isFormControlElement())
-            toHTMLFormControlElement(m_associatedElements[i])->reset();
+    const Vector<FormAssociatedElement*>& elements = associatedElements();
+    for (unsigned i = 0; i < elements.size(); ++i) {
+        if (elements[i]->isFormControlElement())
+            toHTMLFormControlElement(elements[i])->reset();
     }
 
     m_isInResetFunction = false;
@@ -504,105 +527,17 @@
         HTMLElement::parseAttribute(name, value);
 }
 
-template<class T, size_t n> static void removeFromVector(Vector<T*, n> & vec, T* item)
+void HTMLFormElement::associate(FormAssociatedElement& e)
 {
-    size_t size = vec.size();
-    for (size_t i = 0; i != size; ++i)
-        if (vec[i] == item) {
-            vec.remove(i);
-            break;
-        }
+    m_associatedElementsAreDirty = true;
+    m_associatedElements.clear();
 }
 
-unsigned HTMLFormElement::formElementIndexWithFormAttribute(Element* element, unsigned rangeStart, unsigned rangeEnd)
+void HTMLFormElement::disassociate(FormAssociatedElement& e)
 {
-    if (m_associatedElements.isEmpty())
-        return 0;
-
-    ASSERT(rangeStart <= rangeEnd);
-
-    if (rangeStart == rangeEnd)
-        return rangeStart;
-
-    unsigned left = rangeStart;
-    unsigned right = rangeEnd - 1;
-    unsigned short position;
-
-    // Does binary search on m_associatedElements in order to find the index
-    // to be inserted.
-    while (left != right) {
-        unsigned middle = left + ((right - left) / 2);
-        ASSERT(middle < m_associatedElementsBeforeIndex || middle >= m_associatedElementsAfterIndex);
-        position = element->compareDocumentPosition(toHTMLElement(m_associatedElements[middle]));
-        if (position & DOCUMENT_POSITION_FOLLOWING)
-            right = middle;
-        else
-            left = middle + 1;
-    }
-
-    ASSERT(left < m_associatedElementsBeforeIndex || left >= m_associatedElementsAfterIndex);
-    position = element->compareDocumentPosition(toHTMLElement(m_associatedElements[left]));
-    if (position & DOCUMENT_POSITION_FOLLOWING)
-        return left;
-    return left + 1;
-}
-
-unsigned HTMLFormElement::formElementIndex(FormAssociatedElement& associatedElement)
-{
-    HTMLElement& associatedHTMLElement = toHTMLElement(associatedElement);
-    // Treats separately the case where this element has the form attribute
-    // for performance consideration.
-    if (associatedHTMLElement.fastHasAttribute(formAttr)) {
-        unsigned short position = compareDocumentPosition(&associatedHTMLElement);
-        if (position & DOCUMENT_POSITION_PRECEDING) {
-            ++m_associatedElementsBeforeIndex;
-            ++m_associatedElementsAfterIndex;
-            return HTMLFormElement::formElementIndexWithFormAttribute(&associatedHTMLElement, 0, m_associatedElementsBeforeIndex - 1);
-        }
-        if (position & DOCUMENT_POSITION_FOLLOWING && !(position & DOCUMENT_POSITION_CONTAINED_BY))
-            return HTMLFormElement::formElementIndexWithFormAttribute(&associatedHTMLElement, m_associatedElementsAfterIndex, m_associatedElements.size());
-    }
-
-    // Check for the special case where this element is the very last thing in
-    // the form's tree of children; we don't want to walk the entire tree in that
-    // common case that occurs during parsing; instead we'll just return a value
-    // that says "add this form element to the end of the array".
-    if (ElementTraversal::next(associatedHTMLElement, this)) {
-        unsigned i = m_associatedElementsBeforeIndex;
-        for (Element* element = this; element; element = ElementTraversal::next(*element, this)) {
-            if (element == associatedHTMLElement) {
-                ++m_associatedElementsAfterIndex;
-                return i;
-            }
-            if (!element->isFormControlElement() && !element->hasTagName(objectTag))
-                continue;
-            if (!element->isHTMLElement() || toHTMLElement(element)->formOwner() != this)
-                continue;
-            ++i;
-        }
-    }
-    return m_associatedElementsAfterIndex++;
-}
-
-void HTMLFormElement::registerFormElement(FormAssociatedElement& e)
-{
-    m_associatedElements.insert(formElementIndex(e), &e);
-}
-
-void HTMLFormElement::removeFormElement(FormAssociatedElement* e)
-{
-    unsigned index;
-    for (index = 0; index < m_associatedElements.size(); ++index) {
-        if (m_associatedElements[index] == e)
-            break;
-    }
-    ASSERT_WITH_SECURITY_IMPLICATION(index < m_associatedElements.size());
-    if (index < m_associatedElementsBeforeIndex)
-        --m_associatedElementsBeforeIndex;
-    if (index < m_associatedElementsAfterIndex)
-        --m_associatedElementsAfterIndex;
-    removeFromPastNamesMap(*toHTMLElement(e));
-    removeFromVector(m_associatedElements, e);
+    m_associatedElementsAreDirty = true;
+    m_associatedElements.clear();
+    removeFromPastNamesMap(toHTMLElement(e));
 }
 
 bool HTMLFormElement::isURLAttribute(const Attribute& attribute) const
@@ -610,17 +545,30 @@
     return attribute.name() == actionAttr || HTMLElement::isURLAttribute(attribute);
 }
 
-void HTMLFormElement::registerImgElement(HTMLImageElement* e)
+void HTMLFormElement::associate(HTMLImageElement& e)
 {
-    ASSERT(m_imageElements.find(e) == kNotFound);
-    m_imageElements.append(e);
+    m_imageElementsAreDirty = true;
+    m_imageElements.clear();
 }
 
-void HTMLFormElement::removeImgElement(HTMLImageElement* e)
+void HTMLFormElement::disassociate(HTMLImageElement& e)
 {
-    ASSERT(m_imageElements.find(e) != kNotFound);
-    removeFromPastNamesMap(*e);
-    removeFromVector(m_imageElements, e);
+    m_imageElementsAreDirty = true;
+    m_imageElements.clear();
+    removeFromPastNamesMap(e);
+}
+
+WeakPtr<HTMLFormElement> HTMLFormElement::createWeakPtr()
+{
+    return m_weakPtrFactory.createWeakPtr();
+}
+
+void HTMLFormElement::didAssociateByParser()
+{
+    if (!m_didFinishParsingChildren)
+        return;
+    m_hasElementsAssociatedByParser = true;
+    UseCounter::count(document(), UseCounter::FormAssociationByParser);
 }
 
 PassRefPtr<HTMLCollection> HTMLFormElement::elements()
@@ -628,6 +576,59 @@
     return ensureCachedHTMLCollection(FormControls);
 }
 
+void HTMLFormElement::collectAssociatedElements(Node* root, Vector<FormAssociatedElement*>& elements) const
+{
+    elements.clear();
+    for (Node* node = root; node; node = NodeTraversal::next(*node)) {
+        if (!node->isHTMLElement())
+            continue;
+        FormAssociatedElement* element = 0;
+        if (toElement(node)->isFormControlElement())
+            element = toHTMLFormControlElement(node);
+        else if (node->hasTagName(objectTag))
+            element = toHTMLObjectElement(node);
+        else
+            continue;
+        if (element->form()== this)
+            elements.append(element);
+    }
+}
+
+// This function should be const conceptually. However we update some fields
+// because of lazy evaluation.
+const Vector<FormAssociatedElement*>& HTMLFormElement::associatedElements() const
+{
+    if (!m_associatedElementsAreDirty)
+        return m_associatedElements;
+    HTMLFormElement* mutableThis = const_cast<HTMLFormElement*>(this);
+    Node* scope = mutableThis;
+    if (m_hasElementsAssociatedByParser)
+        scope = highestAncestor();
+    if (inDocument() && treeScope().idTargetObserverRegistry().hasObservers(fastGetAttribute(idAttr)))
+        scope = &treeScope().rootNode();
+    collectAssociatedElements(scope, mutableThis->m_associatedElements);
+    mutableThis->m_associatedElementsAreDirty = false;
+    return m_associatedElements;
+}
+
+void HTMLFormElement::collectImageElements(Node* root, Vector<HTMLImageElement*>& elements)
+{
+    elements.clear();
+    for (Node* node = root; node; node = NodeTraversal::next(*node)) {
+        if (node->isHTMLElement() && node->hasTagName(imgTag) && toHTMLElement(node)->formOwner() == this)
+            elements.append(toHTMLImageElement(node));
+    }
+}
+
+const Vector<HTMLImageElement*>& HTMLFormElement::imageElements()
+{
+    if (!m_imageElementsAreDirty)
+        return m_imageElements;
+    collectImageElements(m_hasElementsAssociatedByParser ? highestAncestor() : this, m_imageElements);
+    m_imageElementsAreDirty = false;
+    return m_imageElements;
+}
+
 String HTMLFormElement::name() const
 {
     return getNameAttribute();
@@ -646,11 +647,6 @@
     return getAttribute(actionAttr);
 }
 
-void HTMLFormElement::setAction(const AtomicString& value)
-{
-    setAttribute(actionAttr, value);
-}
-
 void HTMLFormElement::setEnctype(const AtomicString& value)
 {
     setAttribute(enctypeAttr, value);
@@ -666,11 +662,6 @@
     setAttribute(methodAttr, value);
 }
 
-String HTMLFormElement::target() const
-{
-    return getAttribute(targetAttr);
-}
-
 bool HTMLFormElement::wasUserSubmitted() const
 {
     return m_wasUserSubmitted;
@@ -678,10 +669,11 @@
 
 HTMLFormControlElement* HTMLFormElement::defaultButton() const
 {
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
-        if (!m_associatedElements[i]->isFormControlElement())
+    const Vector<FormAssociatedElement*>& elements = associatedElements();
+    for (unsigned i = 0; i < elements.size(); ++i) {
+        if (!elements[i]->isFormControlElement())
             continue;
-        HTMLFormControlElement* control = toHTMLFormControlElement(m_associatedElements[i]);
+        HTMLFormControlElement* control = toHTMLFormControlElement(elements[i]);
         if (control->isSuccessfulSubmitButton())
             return control;
     }
@@ -703,12 +695,13 @@
 bool HTMLFormElement::checkInvalidControlsAndCollectUnhandled(Vector<RefPtr<FormAssociatedElement> >* unhandledInvalidControls, HTMLFormControlElement::CheckValidityDispatchEvents dispatchEvents)
 {
     RefPtr<HTMLFormElement> protector(this);
-    // Copy m_associatedElements because event handlers called from
-    // HTMLFormControlElement::checkValidity() might change m_associatedElements.
+    // Copy associatedElements because event handlers called from
+    // HTMLFormControlElement::checkValidity() might change associatedElements.
+    const Vector<FormAssociatedElement*>& associatedElements = this->associatedElements();
     Vector<RefPtr<FormAssociatedElement> > elements;
-    elements.reserveCapacity(m_associatedElements.size());
-    for (unsigned i = 0; i < m_associatedElements.size(); ++i)
-        elements.append(m_associatedElements[i]);
+    elements.reserveCapacity(associatedElements.size());
+    for (unsigned i = 0; i < associatedElements.size(); ++i)
+        elements.append(associatedElements[i]);
     bool hasInvalidControls = false;
     for (unsigned i = 0; i < elements.size(); ++i) {
         if (elements[i]->form() == this && elements[i]->isFormControlElement()) {
@@ -720,27 +713,27 @@
     return hasInvalidControls;
 }
 
-Node* HTMLFormElement::elementFromPastNamesMap(const AtomicString& pastName) const
+Element* HTMLFormElement::elementFromPastNamesMap(const AtomicString& pastName)
 {
     if (pastName.isEmpty() || !m_pastNamesMap)
         return 0;
-    Node* node = m_pastNamesMap->get(pastName);
+    Element* element = m_pastNamesMap->get(pastName);
 #if !ASSERT_DISABLED
-    if (!node)
+    if (!element)
         return 0;
-    ASSERT_WITH_SECURITY_IMPLICATION(toHTMLElement(node)->formOwner() == this);
-    if (node->hasTagName(imgTag)) {
-        ASSERT_WITH_SECURITY_IMPLICATION(m_imageElements.find(node) != kNotFound);
-    } else if (node->hasTagName(objectTag)) {
-        ASSERT_WITH_SECURITY_IMPLICATION(m_associatedElements.find(toHTMLObjectElement(node)) != kNotFound);
+    ASSERT_WITH_SECURITY_IMPLICATION(toHTMLElement(element)->formOwner() == this);
+    if (element->hasTagName(imgTag)) {
+        ASSERT_WITH_SECURITY_IMPLICATION(imageElements().find(element) != kNotFound);
+    } else if (element->hasTagName(objectTag)) {
+        ASSERT_WITH_SECURITY_IMPLICATION(associatedElements().find(toHTMLObjectElement(element)) != kNotFound);
     } else {
-        ASSERT_WITH_SECURITY_IMPLICATION(m_associatedElements.find(toHTMLFormControlElement(node)) != kNotFound);
+        ASSERT_WITH_SECURITY_IMPLICATION(associatedElements().find(toHTMLFormControlElement(element)) != kNotFound);
     }
 #endif
-    return node;
+    return element;
 }
 
-void HTMLFormElement::addToPastNamesMap(Node* element, const AtomicString& pastName)
+void HTMLFormElement::addToPastNamesMap(Element* element, const AtomicString& pastName)
 {
     if (pastName.isEmpty())
         return;
@@ -755,23 +748,25 @@
         return;
     PastNamesMap::iterator end = m_pastNamesMap->end();
     for (PastNamesMap::iterator it = m_pastNamesMap->begin(); it != end; ++it) {
-        if (it->value.get() == &element) {
+        if (it->value == &element) {
             it->value = 0;
             // Keep looping. Single element can have multiple names.
         }
     }
 }
 
-void HTMLFormElement::getNamedElements(const AtomicString& name, Vector<RefPtr<Node> >& namedItems)
+void HTMLFormElement::getNamedElements(const AtomicString& name, Vector<RefPtr<Element> >& namedItems)
 {
     // http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#dom-form-nameditem
     elements()->namedItems(name, namedItems);
 
-    Node* elementFromPast = elementFromPastNamesMap(name);
-    if (namedItems.size() && namedItems.first() != elementFromPast)
+    Element* elementFromPast = elementFromPastNamesMap(name);
+    if (namedItems.size() && namedItems.first() != elementFromPast) {
         addToPastNamesMap(namedItems.first().get(), name);
-    else if (elementFromPast && namedItems.isEmpty())
+    } else if (elementFromPast && namedItems.isEmpty()) {
         namedItems.append(elementFromPast);
+        UseCounter::count(document(), UseCounter::FormNameAccessForPastNamesMap);
+    }
 }
 
 bool HTMLFormElement::shouldAutocomplete() const
@@ -783,6 +778,7 @@
 {
     HTMLElement::finishParsingChildren();
     document().formController()->restoreControlStateIn(*this);
+    m_didFinishParsingChildren = true;
 }
 
 void HTMLFormElement::copyNonAttributePropertiesFromElement(const Element& source)
@@ -791,13 +787,13 @@
     HTMLElement::copyNonAttributePropertiesFromElement(source);
 }
 
-void HTMLFormElement::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<NodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Node>& returnValue1)
+void HTMLFormElement::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<RadioNodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Element>& returnValue1)
 {
     // Call getNamedElements twice, first time check if it has a value
     // and let HTMLFormElement update its cache.
     // See issue: 867404
     {
-        Vector<RefPtr<Node> > elements;
+        Vector<RefPtr<Element> > elements;
         getNamedElements(name, elements);
         if (elements.isEmpty())
             return;
@@ -805,7 +801,7 @@
 
     // Second call may return different results from the first call,
     // but if the first the size cannot be zero.
-    Vector<RefPtr<Node> > elements;
+    Vector<RefPtr<Element> > elements;
     getNamedElements(name, elements);
     ASSERT(!elements.isEmpty());
 
@@ -815,8 +811,9 @@
         return;
     }
 
+    bool onlyMatchImg = elements.size() && elements.at(0)->hasTagName(imgTag);
     returnValue0Enabled = true;
-    returnValue0 = NamedNodesCollection::create(elements);
+    returnValue0 = radioNodeList(name, onlyMatchImg);
 }
 
 void HTMLFormElement::setDemoted(bool demoted)
diff --git a/Source/core/html/HTMLFormElement.h b/Source/core/html/HTMLFormElement.h
index a71bd81..0c3c890 100644
--- a/Source/core/html/HTMLFormElement.h
+++ b/Source/core/html/HTMLFormElement.h
@@ -26,10 +26,11 @@
 
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLFormControlElement.h"
-#include "core/html/forms/CheckedRadioButtons.h"
+#include "core/html/forms/RadioButtonGroupScope.h"
 #include "core/loader/FormState.h"
 #include "core/loader/FormSubmission.h"
 #include "wtf/OwnPtr.h"
+#include "wtf/WeakPtr.h"
 
 namespace WTF{
 class TextEncoding;
@@ -50,10 +51,10 @@
     virtual ~HTMLFormElement();
 
     PassRefPtr<HTMLCollection> elements();
-    void getNamedElements(const AtomicString&, Vector<RefPtr<Node> >&);
+    void getNamedElements(const AtomicString&, Vector<RefPtr<Element> >&);
 
     unsigned length() const;
-    Node* item(unsigned index);
+    Element* item(unsigned index);
 
     String enctype() const { return m_attributes.encodingType(); }
     void setEnctype(const AtomicString&);
@@ -63,12 +64,12 @@
 
     bool shouldAutocomplete() const;
 
-    // FIXME: Should rename these two functions to say "form control" or "form-associated element" instead of "form element".
-    void registerFormElement(FormAssociatedElement&);
-    void removeFormElement(FormAssociatedElement*);
-
-    void registerImgElement(HTMLImageElement*);
-    void removeImgElement(HTMLImageElement*);
+    void associate(FormAssociatedElement&);
+    void disassociate(FormAssociatedElement&);
+    void associate(HTMLImageElement&);
+    void disassociate(HTMLImageElement&);
+    WeakPtr<HTMLFormElement> createWeakPtr();
+    void didAssociateByParser();
 
     bool prepareForSubmission(Event*);
     void submit();
@@ -78,20 +79,16 @@
     void setDemoted(bool);
 
     void submitImplicitly(Event*, bool fromImplicitSubmissionTrigger);
-    bool formWouldHaveSecureSubmission(const String& url);
 
     String name() const;
 
     bool noValidate() const;
 
     const AtomicString& action() const;
-    void setAction(const AtomicString&);
 
     String method() const;
     void setMethod(const AtomicString&);
 
-    virtual String target() const;
-
     bool wasUserSubmitted() const;
 
     HTMLFormControlElement* defaultButton() const;
@@ -112,23 +109,23 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(autocomplete);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(autocompleteerror);
 
-    CheckedRadioButtons& checkedRadioButtons() { return m_checkedRadioButtons; }
+    RadioButtonGroupScope& radioButtonGroupScope() { return m_radioButtonGroupScope; }
 
-    const Vector<FormAssociatedElement*>& associatedElements() const { return m_associatedElements; }
-    const Vector<HTMLImageElement*>& imageElements() const { return m_imageElements; }
+    const Vector<FormAssociatedElement*>& associatedElements() const;
+    const Vector<HTMLImageElement*>& imageElements();
 
     void getTextFieldValues(StringPairVector& fieldNamesAndValues) const;
-    void anonymousNamedGetter(const AtomicString& name, bool&, RefPtr<NodeList>&, bool&, RefPtr<Node>&);
+    void anonymousNamedGetter(const AtomicString& name, bool&, RefPtr<RadioNodeList>&, bool&, RefPtr<Element>&);
 
 private:
     explicit HTMLFormElement(Document&);
 
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void finishParsingChildren() OVERRIDE;
 
-    virtual void handleLocalEvents(Event*);
+    virtual void handleLocalEvents(Event*) OVERRIDE;
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
@@ -142,8 +139,8 @@
 
     void scheduleFormSubmission(PassRefPtr<FormSubmission>);
 
-    unsigned formElementIndexWithFormAttribute(Element*, unsigned rangeStart, unsigned rangeEnd);
-    unsigned formElementIndex(FormAssociatedElement&);
+    void collectAssociatedElements(Node* root, Vector<FormAssociatedElement*>&) const;
+    void collectImageElements(Node* root, Vector<HTMLImageElement*>&);
 
     // Returns true if the submission should proceed.
     bool validateInteractively(Event*);
@@ -153,21 +150,26 @@
     // are any invalid controls in this form.
     bool checkInvalidControlsAndCollectUnhandled(Vector<RefPtr<FormAssociatedElement> >*, HTMLFormControlElement::CheckValidityDispatchEvents = HTMLFormControlElement::CheckValidityDispatchEventsAllowed);
 
-    Node* elementFromPastNamesMap(const AtomicString&) const;
-    void addToPastNamesMap(Node*, const AtomicString& pastName);
+    Element* elementFromPastNamesMap(const AtomicString&);
+    void addToPastNamesMap(Element*, const AtomicString& pastName);
     void removeFromPastNamesMap(HTMLElement&);
 
-    typedef HashMap<AtomicString, RefPtr<Node> > PastNamesMap;
+    typedef HashMap<AtomicString, Element*> PastNamesMap;
 
     FormSubmission::Attributes m_attributes;
     OwnPtr<PastNamesMap> m_pastNamesMap;
 
-    CheckedRadioButtons m_checkedRadioButtons;
+    RadioButtonGroupScope m_radioButtonGroupScope;
 
-    unsigned m_associatedElementsBeforeIndex;
-    unsigned m_associatedElementsAfterIndex;
+    // Do not access m_associatedElements directly. Use associatedElements() instead.
     Vector<FormAssociatedElement*> m_associatedElements;
+    // Do not access m_imageElements directly. Use imageElements() instead.
     Vector<HTMLImageElement*> m_imageElements;
+    WeakPtrFactory<HTMLFormElement> m_weakPtrFactory;
+    bool m_associatedElementsAreDirty;
+    bool m_imageElementsAreDirty;
+    bool m_hasElementsAssociatedByParser;
+    bool m_didFinishParsingChildren;
 
     bool m_wasUserSubmitted;
     bool m_isSubmittingOrPreparingForSubmission;
diff --git a/Source/core/html/HTMLFormElement.idl b/Source/core/html/HTMLFormElement.idl
index 6ba5f41..912f73e 100644
--- a/Source/core/html/HTMLFormElement.idl
+++ b/Source/core/html/HTMLFormElement.idl
@@ -18,10 +18,12 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface HTMLFormElement : HTMLElement {
+[
+    OverrideBuiltins,
+] interface HTMLFormElement : HTMLElement {
     [Reflect=accept_charset] attribute DOMString acceptCharset;
     [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString action;
-    [Reflect] attribute DOMString autocomplete;
+    [Reflect, ReflectOnly="on"|"off", ReflectMissing="on", ReflectInvalid="on"] attribute DOMString autocomplete;
     [CustomElementCallbacks] attribute DOMString enctype;
     [CustomElementCallbacks] attribute DOMString encoding;
     [CustomElementCallbacks] attribute DOMString method;
@@ -31,10 +33,10 @@
 
     readonly attribute HTMLCollection elements;
     readonly attribute long length;
-    [ImplementedAs=item] getter Node(unsigned long index);
-    [ImplementedAs=anonymousNamedGetter, OverrideBuiltins, NotEnumerable] getter (NodeList or Node)(DOMString name);
+    [ImplementedAs=item] getter Element (unsigned long index);
+    [NotEnumerable] getter (RadioNodeList or Element) (DOMString name);
 
-    [ImplementedAs=submitFromJavaScript, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] void submit();
+    [ImplementedAs=submitFromJavaScript, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void submit();
     [CustomElementCallbacks] void reset();
     boolean checkValidity();
 
diff --git a/Source/core/html/HTMLFrameElement.h b/Source/core/html/HTMLFrameElement.h
index 72ca103..1605626 100644
--- a/Source/core/html/HTMLFrameElement.h
+++ b/Source/core/html/HTMLFrameElement.h
@@ -41,13 +41,11 @@
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&);
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
-    virtual bool allowFullScreen() const { return false; }
-
     bool m_frameBorder;
     bool m_frameBorderSet;
 };
diff --git a/Source/core/html/HTMLFrameElement.idl b/Source/core/html/HTMLFrameElement.idl
index 1ab494c..82cb3b2 100644
--- a/Source/core/html/HTMLFrameElement.idl
+++ b/Source/core/html/HTMLFrameElement.idl
@@ -35,7 +35,7 @@
     // Extensions
     readonly attribute Window contentWindow;
 
-    [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
+    [CheckSecurity=Node, RaisesException] Document getSVGDocument();
 
     [TreatNullAs=NullString, Custom=Setter, MeasureAs=HTMLFrameElementLocation] attribute DOMString location;
 
diff --git a/Source/core/html/HTMLFrameElementBase.cpp b/Source/core/html/HTMLFrameElementBase.cpp
index fc6bfb9..afc9ec5 100644
--- a/Source/core/html/HTMLFrameElementBase.cpp
+++ b/Source/core/html/HTMLFrameElementBase.cpp
@@ -76,7 +76,7 @@
         return;
 
     if (m_URL.isEmpty())
-        m_URL = blankURL().string();
+        m_URL = AtomicString(blankURL().string());
 
     Frame* parentFrame = document().frame();
     if (!parentFrame)
diff --git a/Source/core/html/HTMLFrameElementBase.h b/Source/core/html/HTMLFrameElementBase.h
index 9352e4e..300cdf4 100644
--- a/Source/core/html/HTMLFrameElementBase.h
+++ b/Source/core/html/HTMLFrameElementBase.h
@@ -34,7 +34,7 @@
     KURL location() const;
     void setLocation(const String&);
 
-    virtual ScrollbarMode scrollingMode() const { return m_scrolling; }
+    virtual ScrollbarMode scrollingMode() const OVERRIDE FINAL { return m_scrolling; }
 
     int marginWidth() const { return m_marginWidth; }
     int marginHeight() const { return m_marginHeight; }
@@ -42,7 +42,7 @@
     int width();
     int height();
 
-    virtual bool canContainRangeEndPoint() const { return false; }
+    virtual bool canContainRangeEndPoint() const OVERRIDE FINAL { return false; }
 
 protected:
     HTMLFrameElementBase(const QualifiedName&, Document&);
@@ -51,19 +51,19 @@
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
+    virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE FINAL;
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
 
 private:
-    virtual bool supportsFocus() const;
-    virtual void setFocus(bool) OVERRIDE;
+    virtual bool supportsFocus() const OVERRIDE FINAL;
+    virtual void setFocus(bool) OVERRIDE FINAL;
 
-    virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
-    virtual bool isHTMLContentAttribute(const Attribute&) const OVERRIDE;
+    virtual bool isURLAttribute(const Attribute&) const OVERRIDE FINAL;
+    virtual bool isHTMLContentAttribute(const Attribute&) const OVERRIDE FINAL;
 
-    virtual bool isFrameElementBase() const { return true; }
+    virtual bool isFrameElementBase() const OVERRIDE FINAL { return true; }
 
-    virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
+    virtual bool areAuthorShadowsAllowed() const OVERRIDE FINAL { return false; }
 
     void setNameAndOpenURL();
     void openURL(bool lockBackForwardList = true);
diff --git a/Source/core/html/HTMLFrameOwnerElement.cpp b/Source/core/html/HTMLFrameOwnerElement.cpp
index 20774db..53868b0 100644
--- a/Source/core/html/HTMLFrameOwnerElement.cpp
+++ b/Source/core/html/HTMLFrameOwnerElement.cpp
@@ -125,7 +125,7 @@
 {
     RefPtr<Frame> parentFrame = document().frame();
     if (contentFrame()) {
-        contentFrame()->navigationScheduler().scheduleLocationChange(document().securityOrigin(), url.string(), parentFrame->loader().outgoingReferrer(), lockBackForwardList);
+        contentFrame()->navigationScheduler().scheduleLocationChange(&document(), url.string(), Referrer(document().outgoingReferrer(), document().referrerPolicy()), lockBackForwardList);
         return true;
     }
 
@@ -137,8 +137,8 @@
     if (!SubframeLoadingDisabler::canLoadFrame(*this))
         return false;
 
-    String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), url, parentFrame->loader().outgoingReferrer());
-    RefPtr<Frame> childFrame = parentFrame->loader().client()->createFrame(url, frameName, referrer, this);
+    String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), url, document().outgoingReferrer());
+    RefPtr<Frame> childFrame = parentFrame->loader().client()->createFrame(url, frameName, Referrer(referrer, document().referrerPolicy()), this);
 
     if (!childFrame)  {
         parentFrame->loader().checkCompleted();
diff --git a/Source/core/html/HTMLFrameOwnerElement.h b/Source/core/html/HTMLFrameOwnerElement.h
index 834ac12..572788c 100644
--- a/Source/core/html/HTMLFrameOwnerElement.h
+++ b/Source/core/html/HTMLFrameOwnerElement.h
@@ -22,6 +22,7 @@
 #define HTMLFrameOwnerElement_h
 
 #include "core/html/HTMLElement.h"
+#include "core/svg/SVGDocument.h"
 #include "wtf/HashCountedSet.h"
 
 namespace WebCore {
@@ -30,7 +31,6 @@
 class ExceptionState;
 class Frame;
 class RenderPart;
-class SVGDocument;
 
 class HTMLFrameOwnerElement : public HTMLElement {
 public:
@@ -71,7 +71,7 @@
 
 private:
     virtual bool isKeyboardFocusable() const OVERRIDE;
-    virtual bool isFrameOwnerElement() const OVERRIDE { return true; }
+    virtual bool isFrameOwnerElement() const OVERRIDE FINAL { return true; }
 
     Frame* m_contentFrame;
     SandboxFlags m_sandboxFlags;
@@ -94,6 +94,8 @@
 
     static bool canLoadFrame(HTMLFrameOwnerElement& owner)
     {
+        if (owner.document().unloadStarted())
+            return false;
         for (Node* node = &owner; node; node = node->parentOrShadowHostNode()) {
             if (disabledSubtreeRoots().contains(node))
                 return false;
diff --git a/Source/core/html/HTMLFrameSetElement.cpp b/Source/core/html/HTMLFrameSetElement.cpp
index cfa4134..6bad8f9 100644
--- a/Source/core/html/HTMLFrameSetElement.cpp
+++ b/Source/core/html/HTMLFrameSetElement.cpp
@@ -79,12 +79,12 @@
     if (name == rowsAttr) {
         if (!value.isNull()) {
             m_rowLengths = parseListOfDimensions(value.string());
-            setNeedsStyleRecalc();
+            setNeedsStyleRecalc(SubtreeStyleChange);
         }
     } else if (name == colsAttr) {
         if (!value.isNull()) {
             m_colLengths = parseListOfDimensions(value.string());
-            setNeedsStyleRecalc();
+            setNeedsStyleRecalc(SubtreeStyleChange);
         }
     } else if (name == frameborderAttr) {
         if (!value.isNull()) {
@@ -128,10 +128,8 @@
         document().setWindowAttributeEventListener(EventTypeNames::focusin, createAttributeEventListener(document().frame(), name, value));
     else if (name == onfocusoutAttr)
         document().setWindowAttributeEventListener(EventTypeNames::focusout, createAttributeEventListener(document().frame(), name, value));
-#if ENABLE(ORIENTATION_EVENTS)
-    else if (name == onorientationchangeAttr)
+    else if (RuntimeEnabledFeatures::orientationEventEnabled() && name == onorientationchangeAttr)
         document().setWindowAttributeEventListener(EventTypeNames::orientationchange, createAttributeEventListener(document().frame(), name, value));
-#endif
     else if (name == onhashchangeAttr)
         document().setWindowAttributeEventListener(EventTypeNames::hashchange, createAttributeEventListener(document().frame(), name, value));
     else if (name == onmessageAttr)
@@ -221,10 +219,10 @@
 
 DOMWindow* HTMLFrameSetElement::anonymousNamedGetter(const AtomicString& name)
 {
-    Node* frameNode = children()->namedItem(name);
-    if (!frameNode || !frameNode->hasTagName(HTMLNames::frameTag))
+    Element* frameElement = children()->namedItem(name);
+    if (!frameElement || !frameElement->hasTagName(HTMLNames::frameTag))
         return 0;
-    Document* document = toHTMLFrameElement(frameNode)->contentDocument();
+    Document* document = toHTMLFrameElement(frameElement)->contentDocument();
     if (!document || !document->frame())
         return 0;
     return document->domWindow();
diff --git a/Source/core/html/HTMLFrameSetElement.h b/Source/core/html/HTMLFrameSetElement.h
index 3138495..09648e7 100644
--- a/Source/core/html/HTMLFrameSetElement.h
+++ b/Source/core/html/HTMLFrameSetElement.h
@@ -51,11 +51,9 @@
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load);
+    DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll);
-
-#if ENABLE(ORIENTATION_EVENTS)
     DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange);
-#endif
 
 private:
     explicit HTMLFrameSetElement(Document&);
@@ -65,10 +63,10 @@
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual bool rendererIsNeeded(const RenderStyle&);
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
diff --git a/Source/core/html/HTMLFrameSetElement.idl b/Source/core/html/HTMLFrameSetElement.idl
index 38a5f21..e7c6a24 100644
--- a/Source/core/html/HTMLFrameSetElement.idl
+++ b/Source/core/html/HTMLFrameSetElement.idl
@@ -18,18 +18,21 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface HTMLFrameSetElement : HTMLElement {
-    [ImplementedAs=anonymousNamedGetter, OverrideBuiltins, NotEnumerable] getter Window (DOMString name);
+[
+    OverrideBuiltins,
+] interface HTMLFrameSetElement : HTMLElement {
+    [NotEnumerable] getter Window (DOMString name);
     [Reflect] attribute DOMString cols;
     [Reflect] attribute DOMString rows;
 
-    [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
+    [RuntimeEnabled=OrientationEvent] attribute EventHandler onorientationchange;
 
     // Overrides of GlobalEventHandler attributes
     attribute EventHandler onblur;
     attribute EventHandler onerror;
     attribute EventHandler onfocus;
     attribute EventHandler onload;
+    attribute EventHandler onresize;
     attribute EventHandler onscroll;
 };
 
diff --git a/Source/core/html/HTMLHRElement.cpp b/Source/core/html/HTMLHRElement.cpp
index 7a6edf8..e8a35a1 100644
--- a/Source/core/html/HTMLHRElement.cpp
+++ b/Source/core/html/HTMLHRElement.cpp
@@ -78,7 +78,7 @@
     } else if (name == noshadeAttr) {
         addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderStyle, CSSValueSolid);
 
-        RefPtr<CSSPrimitiveValue> darkGrayValue = cssValuePool().createColorValue(Color::darkGray);
+        RefPtrWillBeRawPtr<CSSPrimitiveValue> darkGrayValue = cssValuePool().createColorValue(Color::darkGray);
         style->setProperty(CSSPropertyBorderColor, darkGrayValue);
         style->setProperty(CSSPropertyBackgroundColor, darkGrayValue);
     } else if (name == sizeAttr) {
diff --git a/Source/core/html/HTMLHRElement.h b/Source/core/html/HTMLHRElement.h
index ec5bcb0..0b06bbe 100644
--- a/Source/core/html/HTMLHRElement.h
+++ b/Source/core/html/HTMLHRElement.h
@@ -31,7 +31,7 @@
 public:
     static PassRefPtr<HTMLHRElement> create(Document&);
 
-    virtual bool canContainRangeEndPoint() const { return hasChildNodes(); }
+    virtual bool canContainRangeEndPoint() const OVERRIDE { return hasChildNodes(); }
 
 private:
     explicit HTMLHRElement(Document&);
diff --git a/Source/core/html/HTMLHtmlElement.cpp b/Source/core/html/HTMLHtmlElement.cpp
index e4a56c9..c089bba 100644
--- a/Source/core/html/HTMLHtmlElement.cpp
+++ b/Source/core/html/HTMLHtmlElement.cpp
@@ -65,7 +65,7 @@
     if (!documentLoader)
         return;
 
-    const AtomicString& manifest = getAttribute(manifestAttr);
+    const AtomicString& manifest = fastGetAttribute(manifestAttr);
     if (manifest.isEmpty())
         documentLoader->applicationCacheHost()->selectCacheWithoutManifest();
     else
diff --git a/Source/core/html/HTMLHtmlElement.h b/Source/core/html/HTMLHtmlElement.h
index 4976aac..cad8d8d 100644
--- a/Source/core/html/HTMLHtmlElement.h
+++ b/Source/core/html/HTMLHtmlElement.h
@@ -40,16 +40,6 @@
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 };
 
-inline bool isHTMLHtmlElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::htmlTag);
-}
-
-inline bool isHTMLHtmlElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::htmlTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLHtmlElement, hasTagName(HTMLNames::htmlTag));
 
 } // namespace
diff --git a/Source/core/html/HTMLIFrameElement.cpp b/Source/core/html/HTMLIFrameElement.cpp
index 016fba4..a4bc0ff 100644
--- a/Source/core/html/HTMLIFrameElement.cpp
+++ b/Source/core/html/HTMLIFrameElement.cpp
@@ -39,7 +39,6 @@
     , m_didLoadNonEmptyDocument(false)
 {
     ScriptWrappable::init(this);
-    setHasCustomStyleCallbacks();
 }
 
 PassRefPtr<HTMLIFrameElement> HTMLIFrameElement::create(Document& document)
@@ -49,7 +48,7 @@
 
 bool HTMLIFrameElement::isPresentationAttribute(const QualifiedName& name) const
 {
-    if (name == widthAttr || name == heightAttr || name == alignAttr || name == frameborderAttr || name == seamlessAttr)
+    if (name == widthAttr || name == heightAttr || name == alignAttr || name == frameborderAttr)
         return true;
     return HTMLFrameElementBase::isPresentationAttribute(name);
 }
@@ -87,12 +86,9 @@
         setSandboxFlags(value.isNull() ? SandboxNone : parseSandboxPolicy(value, invalidTokens));
         if (!invalidTokens.isNull())
             document().addConsoleMessage(OtherMessageSource, ErrorMessageLevel, "Error while parsing the 'sandbox' attribute: " + invalidTokens);
-    } else if (name == seamlessAttr) {
-        // If we're adding or removing the seamless attribute, we need to force the content document to recalculate its StyleResolver.
-        if (contentDocument())
-            contentDocument()->styleResolverChanged(RecalcStyleDeferred);
-    } else
+    } else {
         HTMLFrameElementBase::parseAttribute(name, value);
+    }
 }
 
 bool HTMLIFrameElement::rendererIsNeeded(const RenderStyle& style)
@@ -120,20 +116,6 @@
         toHTMLDocument(document()).removeExtraNamedItem(m_name);
 }
 
-bool HTMLIFrameElement::shouldDisplaySeamlessly() const
-{
-    return contentDocument() && contentDocument()->shouldDisplaySeamlesslyWithParent();
-}
-
-void HTMLIFrameElement::didRecalcStyle(StyleRecalcChange styleChange)
-{
-    if (!shouldDisplaySeamlessly())
-        return;
-    Document* childDocument = contentDocument();
-    if (shouldRecalcStyle(styleChange, childDocument))
-        contentDocument()->recalcStyle(styleChange);
-}
-
 bool HTMLIFrameElement::isInteractiveContent() const
 {
     return true;
diff --git a/Source/core/html/HTMLIFrameElement.h b/Source/core/html/HTMLIFrameElement.h
index eab2678..e2c2f77 100644
--- a/Source/core/html/HTMLIFrameElement.h
+++ b/Source/core/html/HTMLIFrameElement.h
@@ -32,8 +32,6 @@
 public:
     static PassRefPtr<HTMLIFrameElement> create(Document&);
 
-    bool shouldDisplaySeamlessly() const;
-
 private:
     explicit HTMLIFrameElement(Document&);
 
@@ -44,10 +42,8 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&);
-    virtual RenderObject* createRenderer(RenderStyle*);
-
-    virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     virtual bool loadedNonEmptyDocument() const OVERRIDE { return m_didLoadNonEmptyDocument; }
     virtual void didLoadNonEmptyDocument() OVERRIDE { m_didLoadNonEmptyDocument = true; }
diff --git a/Source/core/html/HTMLIFrameElement.idl b/Source/core/html/HTMLIFrameElement.idl
index d8a8a8e..7b864ca 100644
--- a/Source/core/html/HTMLIFrameElement.idl
+++ b/Source/core/html/HTMLIFrameElement.idl
@@ -27,7 +27,6 @@
     [Reflect, TreatNullAs=NullString] attribute DOMString marginWidth;
     [Reflect] attribute DOMString name;
     [Reflect, TreatNullAs=NullString] attribute DOMString sandbox;
-    [Reflect, RuntimeEnabled=SeamlessIFrames] attribute boolean seamless;
     [Reflect] attribute DOMString scrolling;
     [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
     [Reflect] attribute DOMString srcdoc;
@@ -39,5 +38,5 @@
     // Extensions
     readonly attribute Window contentWindow;
 
-    [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
+    [CheckSecurity=Node, RaisesException] Document getSVGDocument();
 };
diff --git a/Source/core/html/HTMLImageElement.cpp b/Source/core/html/HTMLImageElement.cpp
index 1145fea..bed556d 100644
--- a/Source/core/html/HTMLImageElement.cpp
+++ b/Source/core/html/HTMLImageElement.cpp
@@ -45,13 +45,17 @@
 HTMLImageElement::HTMLImageElement(Document& document, HTMLFormElement* form)
     : HTMLElement(imgTag, document)
     , m_imageLoader(this)
-    , m_form(form)
     , m_compositeOperator(CompositeSourceOver)
     , m_imageDevicePixelRatio(1.0f)
+    , m_formWasSetByParser(false)
 {
     ScriptWrappable::init(this);
-    if (form)
-        form->registerImgElement(this);
+    if (form && form->inDocument()) {
+        m_form = form->createWeakPtr();
+        m_formWasSetByParser = true;
+        m_form->associate(*this);
+        m_form->didAssociateByParser();
+    }
 }
 
 PassRefPtr<HTMLImageElement> HTMLImageElement::create(Document& document)
@@ -67,7 +71,7 @@
 HTMLImageElement::~HTMLImageElement()
 {
     if (m_form)
-        m_form->removeImgElement(this);
+        m_form->disassociate(*this);
 }
 
 PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document& document, int width, int height)
@@ -114,6 +118,35 @@
     return m_bestFitImageURL.isNull() ? fastGetAttribute(srcAttr) : m_bestFitImageURL;
 }
 
+HTMLFormElement* HTMLImageElement::formOwner() const
+{
+    return m_form.get();
+}
+
+void HTMLImageElement::formRemovedFromTree(const Node* formRoot)
+{
+    ASSERT(m_form);
+    if (highestAncestor() != formRoot)
+        resetFormOwner();
+}
+
+void HTMLImageElement::resetFormOwner()
+{
+    m_formWasSetByParser = false;
+    HTMLFormElement* nearestForm = findFormAncestor();
+    if (m_form) {
+        if (nearestForm == m_form.get())
+            return;
+        m_form->disassociate(*this);
+    }
+    if (nearestForm) {
+        m_form = nearestForm->createWeakPtr();
+        m_form->associate(*this);
+    } else {
+        m_form = WeakPtr<HTMLFormElement>();
+    }
+}
+
 void HTMLImageElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (name == altAttr) {
@@ -122,7 +155,7 @@
     } else if (name == srcAttr || name == srcsetAttr) {
         if (RuntimeEnabledFeatures::srcsetEnabled()) {
             ImageCandidate candidate = bestFitSourceForImageAttributes(document().devicePixelRatio(), fastGetAttribute(srcAttr), fastGetAttribute(srcsetAttr));
-            m_bestFitImageURL = candidate.toString();
+            m_bestFitImageURL = candidate.toAtomicString();
             float candidateScaleFactor = candidate.scaleFactor();
             if (candidateScaleFactor > 0)
                 m_imageDevicePixelRatio = 1 / candidateScaleFactor;
@@ -149,10 +182,11 @@
     // lets figure out the alt text.. magic stuff
     // http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
     // also heavily discussed by Hixie on bugzilla
-    if (!getAttribute(altAttr).isNull())
-        return getAttribute(altAttr);
+    const AtomicString& alt = fastGetAttribute(altAttr);
+    if (!alt.isNull())
+        return alt;
     // fall back to title attribute
-    return getAttribute(titleAttr);
+    return fastGetAttribute(titleAttr);
 }
 
 RenderObject* HTMLImageElement::createRenderer(RenderStyle* style)
@@ -196,17 +230,8 @@
 
 Node::InsertionNotificationRequest HTMLImageElement::insertedInto(ContainerNode* insertionPoint)
 {
-    // m_form can be non-null if it was set in constructor.
-    if (m_form && insertionPoint->highestAncestor() != m_form->highestAncestor()) {
-        m_form->removeImgElement(this);
-        m_form = 0;
-    }
-
-    if (!m_form) {
-        m_form = findFormAncestor();
-        if (m_form)
-            m_form->registerImgElement(this);
-    }
+    if (!m_formWasSetByParser || insertionPoint->highestAncestor() != m_form->highestAncestor())
+        resetFormOwner();
 
     // If we have been inserted from a renderer-less document,
     // our loader may have not fetched the image, so do it now.
@@ -218,9 +243,8 @@
 
 void HTMLImageElement::removedFrom(ContainerNode* insertionPoint)
 {
-    if (m_form)
-        m_form->removeImgElement(this);
-    m_form = 0;
+    if (!m_form || m_form->highestAncestor() != highestAncestor())
+        resetFormOwner();
     HTMLElement::removedFrom(insertionPoint);
 }
 
@@ -297,7 +321,7 @@
 
 const AtomicString& HTMLImageElement::alt() const
 {
-    return getAttribute(altAttr);
+    return fastGetAttribute(altAttr);
 }
 
 bool HTMLImageElement::draggable() const
@@ -353,15 +377,6 @@
     return m_imageLoader.imageComplete();
 }
 
-void HTMLImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, src());
-    // FIXME: What about when the usemap attribute begins with "#"?
-    addSubresourceURL(urls, document().completeURL(getAttribute(usemapAttr)));
-}
-
 void HTMLImageElement::didMoveToNewDocument(Document& oldDocument)
 {
     m_imageLoader.elementDidMoveToNewDocument();
diff --git a/Source/core/html/HTMLImageElement.h b/Source/core/html/HTMLImageElement.h
index f621384..54ea125 100644
--- a/Source/core/html/HTMLImageElement.h
+++ b/Source/core/html/HTMLImageElement.h
@@ -27,13 +27,13 @@
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLImageLoader.h"
 #include "platform/graphics/GraphicsTypes.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
 class HTMLFormElement;
 
 class HTMLImageElement FINAL : public HTMLElement {
-    friend class HTMLFormElement;
 public:
     static PassRefPtr<HTMLImageElement> create(Document&);
     static PassRefPtr<HTMLImageElement> create(Document&, HTMLFormElement*);
@@ -74,13 +74,16 @@
 
     bool hasPendingActivity() const { return m_imageLoader.hasPendingActivity(); }
 
-    virtual bool canContainRangeEndPoint() const { return false; }
+    virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
 
     void addClient(ImageLoaderClient* client) { m_imageLoader.addClient(client); }
     void removeClient(ImageLoaderClient* client) { m_imageLoader.removeClient(client); }
 
     virtual const AtomicString imageSourceURL() const OVERRIDE;
 
+    virtual HTMLFormElement* formOwner() const OVERRIDE;
+    void formRemovedFromTree(const Node* formRoot);
+
 protected:
     explicit HTMLImageElement(Document&, HTMLFormElement* = 0);
 
@@ -94,15 +97,13 @@
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
-    virtual bool canStartSelection() const;
+    virtual bool canStartSelection() const OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 
-    virtual bool draggable() const;
-
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
+    virtual bool draggable() const OVERRIDE;
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -111,11 +112,15 @@
     virtual bool isInteractiveContent() const OVERRIDE;
     virtual Image* imageContents() OVERRIDE;
 
+    void resetFormOwner();
+
     HTMLImageLoader m_imageLoader;
-    HTMLFormElement* m_form;
+    // m_form should be a strong reference in Oilpan.
+    WeakPtr<HTMLFormElement> m_form;
     CompositeOperator m_compositeOperator;
     AtomicString m_bestFitImageURL;
     float m_imageDevicePixelRatio;
+    bool m_formWasSetByParser;
 };
 
 DEFINE_NODE_TYPE_CASTS(HTMLImageElement, hasTagName(HTMLNames::imgTag));
diff --git a/Source/core/html/HTMLImageElement.idl b/Source/core/html/HTMLImageElement.idl
index a548023..809b785 100644
--- a/Source/core/html/HTMLImageElement.idl
+++ b/Source/core/html/HTMLImageElement.idl
@@ -27,7 +27,7 @@
     [Reflect] attribute DOMString alt;
     [Reflect, TreatNullAs=NullString] attribute DOMString border;
     readonly attribute boolean complete;
-    [Reflect] attribute DOMString crossOrigin;
+    [Reflect, ReflectOnly="anonymous"|"use-credentials", ReflectEmpty="anonymous", ReflectInvalid="anonymous"] attribute DOMString crossOrigin;
     attribute long height;
     [Reflect] attribute long hspace;
     [Reflect] attribute boolean isMap;
diff --git a/Source/core/html/HTMLImageLoader.cpp b/Source/core/html/HTMLImageLoader.cpp
index 9a50c5f..c884f3c 100644
--- a/Source/core/html/HTMLImageLoader.cpp
+++ b/Source/core/html/HTMLImageLoader.cpp
@@ -28,7 +28,6 @@
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/fetch/ImageResource.h"
 #include "core/html/HTMLObjectElement.h"
-#include "core/html/HTMLVideoElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 
 namespace WebCore {
@@ -45,7 +44,7 @@
 void HTMLImageLoader::dispatchLoadEvent()
 {
     // HTMLVideoElement uses this class to load the poster image, but it should not fire events for loading or failure.
-    if (isHTMLVideoElement(element()))
+    if (element()->hasTagName(HTMLNames::videoTag))
         return;
 
     bool errorOccurred = image()->errorOccurred();
diff --git a/Source/core/html/HTMLImageLoader.h b/Source/core/html/HTMLImageLoader.h
index 4ee2d8e..71c5365 100644
--- a/Source/core/html/HTMLImageLoader.h
+++ b/Source/core/html/HTMLImageLoader.h
@@ -27,15 +27,15 @@
 
 namespace WebCore {
 
-class HTMLImageLoader : public ImageLoader {
+class HTMLImageLoader FINAL : public ImageLoader {
 public:
     HTMLImageLoader(Element*);
     virtual ~HTMLImageLoader();
 
-    virtual void dispatchLoadEvent();
-    virtual String sourceURI(const AtomicString&) const;
+    virtual void dispatchLoadEvent() OVERRIDE;
+    virtual String sourceURI(const AtomicString&) const OVERRIDE;
 
-    virtual void notifyFinished(Resource*);
+    virtual void notifyFinished(Resource*) OVERRIDE;
 };
 
 }
diff --git a/Source/core/html/HTMLImport.cpp b/Source/core/html/HTMLImport.cpp
index 8ac2d7d..154ef04 100644
--- a/Source/core/html/HTMLImport.cpp
+++ b/Source/core/html/HTMLImport.cpp
@@ -32,6 +32,7 @@
 #include "core/html/HTMLImport.h"
 
 #include "core/dom/Document.h"
+#include "core/html/HTMLImportStateResolver.h"
 
 namespace WebCore {
 
@@ -52,132 +53,60 @@
 
 void HTMLImport::appendChild(HTMLImport* child)
 {
-    if (isScriptBlocked())
-        child->blockScript();
-    if (lastChild() && !lastChild()->isDone())
-        child->blockDocument();
     TreeNode<HTMLImport>::appendChild(child);
-    blockAfter(child);
+
+    // This prevents HTML parser from going beyond the
+    // blockage line before the precise state is computed by recalcState().
+    if (child->isCreatedByParser())
+        m_state = HTMLImportState::blockedState();
+
+    stateWillChange();
 }
 
-bool HTMLImport::areChilrenLoaded() const
+void HTMLImport::stateDidChange()
 {
-    for (HTMLImport* child = firstChild(); child; child = child->next()) {
-        if (!child->isLoaded())
-            return false;
+    if (!state().shouldBlockScriptExecution()) {
+        if (Document* document = this->document())
+            document->didLoadAllImports();
+    }
+}
+
+void HTMLImport::stateWillChange()
+{
+    root()->scheduleRecalcState();
+}
+
+void HTMLImport::recalcTreeState(HTMLImport* root)
+{
+    ASSERT(root == root->root());
+
+    HashMap<HTMLImport*, HTMLImportState> snapshot;
+    Vector<HTMLImport*> updated;
+
+    for (HTMLImport* i = root; i; i = traverseNext(i)) {
+        snapshot.add(i, i->state());
+        i->m_state = HTMLImportState::invalidState();
     }
 
-    return true;
-}
+    // The post-visit DFS order matters here because
+    // HTMLImportStateResolver in recalcState() Depends on
+    // |m_state| of its children and precedents of ancestors.
+    // Accidental cycle dependency of state computation is prevented
+    // by invalidateCachedState() and isStateCacheValid() check.
+    for (HTMLImport* i = traverseFirstPostOrder(root); i; i = traverseNextPostOrder(i)) {
+        ASSERT(!i->m_state.isValid());
+        i->m_state = HTMLImportStateResolver(i).resolve();
 
-bool HTMLImport::arePredecessorsLoaded() const
-{
-    HTMLImport* parent = this->parent();
-    if (!parent)
-        return true;
-
-    for (HTMLImport* sibling = parent->firstChild(); sibling; sibling = sibling->next()) {
-        if (sibling == this)
-            break;
-        if (!sibling->isLoaded())
-            return false;
+        HTMLImportState newState = i->state();
+        HTMLImportState oldState = snapshot.get(i);
+        // Once the state reaches Ready, it shouldn't go back.
+        ASSERT(!oldState.isReady() || oldState <= newState);
+        if (newState != oldState)
+            updated.append(i);
     }
 
-    return true;
-}
-
-void HTMLImport::blockScript()
-{
-    m_scriptBlocked = true;
-}
-
-void HTMLImport::unblockScript()
-{
-    bool wasBlocked = m_scriptBlocked;
-    m_scriptBlocked = false;
-    if (wasBlocked)
-        didUnblockScript();
-}
-
-void HTMLImport::didUnblockScript()
-{
-    ASSERT(!isDocumentBlocked());
-    ASSERT(!isScriptBlocked());
-
-    if (!isProcessing())
-        return;
-
-    if (Document* document = this->document())
-        document->didLoadAllImports();
-}
-
-
-void HTMLImport::blockDocument()
-{
-    m_documentBlocked = true;
-}
-
-void HTMLImport::unblockDocument()
-{
-    bool wasBlocked = m_documentBlocked;
-    m_documentBlocked = false;
-    if (wasBlocked)
-        didUnblockDocument();
-}
-
-void HTMLImport::didUnblockDocument()
-{
-    ASSERT(!isDocumentBlocked());
-    ASSERT(isScriptBlocked());
-}
-
-inline bool HTMLImport::needsBlockingDocument() const
-{
-    ASSERT(isDocumentBlocked());
-    HTMLImport* elder = previous();
-    return (elder && !elder->isDone());
-}
-
-bool HTMLImport::unblock(HTMLImport* import)
-{
-    ASSERT(import->arePredecessorsLoaded());
-    ASSERT(import->isScriptBlocked() || import->areChilrenLoaded());
-
-    if (import->isDocumentBlocked() && import->needsBlockingDocument())
-        return false;
-    import->unblockDocument();
-
-    if (import->isScriptBlocked()) {
-        for (HTMLImport* child = import->firstChild(); child; child = child->next()) {
-            if (!unblock(child))
-                return false;
-        }
-    }
-
-    import->unblockScript();
-    return import->isLoaded();
-}
-
-void HTMLImport::block(HTMLImport* import)
-{
-    for (HTMLImport* child = import; child; child = traverseNext(child, import))
-        child->blockScript();
-}
-
-void HTMLImport::blockAfter(HTMLImport* child)
-{
-    ASSERT(child->parent() == this);
-
-    for (HTMLImport* sibling = lastChild(); sibling; sibling = sibling->previous()) {
-        if (sibling == child)
-            break;
-        HTMLImport::block(sibling);
-    }
-
-    this->blockScript();
-
-    if (HTMLImport* parent = this->parent())
-        parent->blockAfter(this);
+    for (size_t i = 0; i < updated.size(); ++i)
+        updated[i]->stateDidChange();
 }
 
 bool HTMLImport::isMaster(Document* document)
@@ -187,4 +116,28 @@
     return (document->import()->master() == document);
 }
 
+#if !defined(NDEBUG)
+void HTMLImport::show()
+{
+    root()->showTree(this, 0);
+}
+
+void HTMLImport::showTree(HTMLImport* highlight, unsigned depth)
+{
+    for (unsigned i = 0; i < depth*4; ++i)
+        fprintf(stderr, " ");
+
+    fprintf(stderr, "%s", this == highlight ? "*" : " ");
+    showThis();
+    fprintf(stderr, "\n");
+    for (HTMLImport* child = firstChild(); child; child = child->next())
+        child->showTree(highlight, depth + 1);
+}
+
+void HTMLImport::showThis()
+{
+    fprintf(stderr, "%p state=%d", this, m_state.peekValueForDebug());
+}
+#endif
+
 } // namespace WebCore
diff --git a/Source/core/html/HTMLImport.h b/Source/core/html/HTMLImport.h
index ea9ac93..0e4f5c1 100644
--- a/Source/core/html/HTMLImport.h
+++ b/Source/core/html/HTMLImport.h
@@ -31,12 +31,13 @@
 #ifndef HTMLImport_h
 #define HTMLImport_h
 
+#include "core/html/HTMLImportState.h"
 #include "wtf/TreeNode.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
 
-class Frame;
+class CustomElementMicrotaskImportStep;
 class Document;
 class Frame;
 class HTMLImportChild;
@@ -72,66 +73,34 @@
 //               <|-                    HTMLImportChild <- LinkStyle <- HTMLLinkElement
 //
 //
-// # Import Sharing and HTMLImportData
+// # Import Sharing and HTMLImportLoader
 //
 // The HTML Imports spec calls for de-dup mechanism to share already loaded imports.
 // To implement this, the actual loading machinery is split out from HTMLImportChild to
-// HTMLImportData (FIXME: rename HTMLImportChild),
-// and each loader shares HTMLImportData with other loader if the URL is same.
+// HTMLImportLoader, and each loader shares HTMLImportLoader with other loader if the URL is same.
 // Check around HTMLImportsController::findLink() for more detail.
 //
-// Note that HTMLImportData provides HTMLImportDataClient to hook it up.
-// As it can be shared, HTMLImportData supports multiple clients.
+// Note that HTMLImportLoader provides HTMLImportLoaderClient to hook it up.
+// As it can be shared, HTMLImportLoader supports multiple clients.
 //
-//    HTMLImportChild (1)-->(*) HTMLImportData
+//    HTMLImportChild (1)-->(*) HTMLImportLoader
 //
 //
 // # Script Blocking
 //
-// The HTML parser blocks on <script> when preceding <link>s aren't finish loading imports.
-// Each HTMLImport instance tracks such a blocking state, that is called "script-blocked"
-// or HTMLImport::isScriptBlocked().
+// - An import blocks the HTML parser of its own imported document from running <script>
+//   until all of its children are loaded.
+//   Note that dynamically added import won't block the parser.
 //
-// ## Blocking Imports
-//
-// Each imports can become being script-blocked when new imports are added to the import tree.
-// For example, the parser of a parent import is blocked when new child import is given.
-// See HTMLImport::appendChild() to see how it is handled. Note that this blocking-ness is
-// transitive. HTMLImport::blockAfter() flips the flags iteratively to fullfill this transitivity.
-//
-// ## Unblocking Imports
-//
-// The blocking state can change when one of the imports finish loading. The Document notices it through
-// HTMLImportRoot::blockerGone(). The blockerGone() triggers HTMLImport::unblockScript(), which traverses
-// whole import tree and find unblock-able imports and unblock them.
-// Unblocked imported documents are notified through Document::didLoadAllImports() so that
-// it can resume its parser.
-//
-// # Document Blocking
-//
-// There is another type of blocking state that is called
-// "document-blocked". If the import is document-blocked, it cannot
-// create its own document object because sharable imported document
-// can appear later. The spec defines the loading order of the
-// import: The earlier one in the import-tree order should win and
-// later ones should share earlier one.
-//
-// The "document-blocked" state keeps the tree node from loading its
-// import until all preceding imports are ready t respect the
-// order. Note that the node may fetch the bytes from the URL
-// speculatively, even though it doesn't process it.
-//
-// The node is "document-unblocked" when there are unfinished,
-// preceeding import loading. Unblocking attempt for
-// "document-blocked" happens at the same timing as unblocking
-// "script-blocked".
+// - An import under loading also blocks imported documents that follow from being created.
+//   This is because an import can include another import that has same URLs of following ones.
+//   In such case, the preceding import should be loaded and following ones should be de-duped.
 //
 
 // The superclass of HTMLImportsController and HTMLImportChild
 // This represents the import tree data structure.
 class HTMLImport : public TreeNode<HTMLImport> {
 public:
-    static bool unblock(HTMLImport*);
     static bool isMaster(Document*);
 
     virtual ~HTMLImport() { }
@@ -139,52 +108,50 @@
     Frame* frame();
     Document* master();
     HTMLImportsController* controller();
-
-    bool isLoaded() const { return !isScriptBlocked() && !isProcessing(); }
-    bool isScriptBlocked() const { return m_scriptBlocked; }
-    bool isDocumentBlocked() const { return m_documentBlocked; }
-    bool isBlocked() const { return m_scriptBlocked || m_documentBlocked; }
+    bool isRoot() const { return !isChild(); }
+    bool isCreatedByParser() const { return m_createdByParser; }
+    const HTMLImportState& state() const { return m_state; }
 
     void appendChild(HTMLImport*);
 
+    virtual bool isChild() const { return false; }
     virtual HTMLImportRoot* root() = 0;
     virtual Document* document() const = 0;
     virtual void wasDetachedFromDocument() = 0;
-    virtual void didFinishParsing() = 0;
-    virtual bool isProcessing() const = 0;
-    virtual bool isDone() const = 0;
+    virtual void didFinishParsing() { };
+    virtual bool isDone() const = 0; // FIXME: Should be renamed to haveFinishedLoading()
+    virtual bool hasLoader() const = 0;
+    virtual bool ownsLoader() const { return false; }
+    virtual CustomElementMicrotaskImportStep* customElementMicrotaskStep() const { return 0; }
+    virtual void stateDidChange();
 
 protected:
-    HTMLImport()
-        : m_scriptBlocked(false)
-        , m_documentBlocked(false)
+    // Stating from most conservative state.
+    // It will be corrected through state update flow.
+    explicit HTMLImport(bool createdByParser = false)
+        : m_createdByParser(createdByParser)
     { }
 
-    virtual void didUnblockDocument();
+    void stateWillChange();
+    static void recalcTreeState(HTMLImport* root);
+
+#if !defined(NDEBUG)
+    void show();
+    void showTree(HTMLImport* highlight, unsigned depth);
+    virtual void showThis();
+#endif
 
 private:
-    static void block(HTMLImport*);
-
-    void blockAfter(HTMLImport* child);
-    void blockScript();
-    void unblockScript();
-    void didUnblockScript();
-
-    void blockDocument();
-    void unblockDocument();
-
-    bool needsBlockingDocument() const;
-    bool arePredecessorsLoaded() const;
-    bool areChilrenLoaded() const;
-
-    bool m_scriptBlocked; // If any of decendants or predecessors is in processing, the parser blocks on <script>.
-    bool m_documentBlocked; // If its predecessor is not done yet, the document creation is blocked.
+    HTMLImportState m_state;
+    bool m_createdByParser : 1;
 };
 
 // An abstract class to decouple its sublcass HTMLImportsController.
 class HTMLImportRoot : public HTMLImport {
 public:
-    virtual void blockerGone() = 0;
+    HTMLImportRoot() { }
+
+    virtual void scheduleRecalcState() = 0;
     virtual HTMLImportsController* toController() = 0;
     virtual HTMLImportChild* findLinkFor(const KURL&, HTMLImport* excluding = 0) const = 0;
 };
diff --git a/Source/core/html/HTMLImportChild.cpp b/Source/core/html/HTMLImportChild.cpp
index d0b9868..3a80baf 100644
--- a/Source/core/html/HTMLImportChild.cpp
+++ b/Source/core/html/HTMLImportChild.cpp
@@ -32,70 +32,97 @@
 #include "core/html/HTMLImportChild.h"
 
 #include "core/dom/Document.h"
+#include "core/dom/custom/CustomElement.h"
+#include "core/dom/custom/CustomElementMicrotaskImportStep.h"
 #include "core/html/HTMLImportChildClient.h"
-#include "core/html/HTMLImportData.h"
+#include "core/html/HTMLImportLoader.h"
 
 namespace WebCore {
 
-HTMLImportChild::HTMLImportChild(const KURL& url, HTMLImportChildClient* client)
-    : m_url(url)
-    , m_client(client)
+HTMLImportChild::HTMLImportChild(const KURL& url, bool createdByParser)
+    : HTMLImport(createdByParser)
+    , m_url(url)
+    , m_customElementMicrotaskStep(0)
+    , m_client(0)
 {
 }
 
 HTMLImportChild::~HTMLImportChild()
 {
     // importDestroyed() should be called before the destruction.
-    ASSERT(!m_data);
+    ASSERT(!m_loader);
+
+    if (m_customElementMicrotaskStep) {
+        // if Custom Elements were blocked, must unblock them before death
+        m_customElementMicrotaskStep->importDidFinish();
+        m_customElementMicrotaskStep = 0;
+    }
+
+    if (m_client)
+        m_client->importChildWasDestroyed(this);
 }
 
-void HTMLImportChild::wasAlreadyLoadedAs(HTMLImportChild* found)
+void HTMLImportChild::wasAlreadyLoaded()
 {
-    ASSERT(!m_data);
+    ASSERT(!m_loader);
     ASSERT(m_client);
-    shareData(found);
+    stateWillChange();
 }
 
 void HTMLImportChild::startLoading(const ResourcePtr<RawResource>& resource)
 {
-    ASSERT(!hasResource());
-    ASSERT(!m_data);
+    ASSERT(!this->resource());
+    ASSERT(!m_loader);
 
-    HTMLImportResourceOwner::setResource(resource);
+    if (isCreatedByParser()) {
+        ASSERT(!m_customElementMicrotaskStep);
+        m_customElementMicrotaskStep = CustomElement::didCreateImport(this);
+    }
 
-    // If the node is "document blocked", it cannot create HTMLImportData
+    setResource(resource);
+
+    // If the node is "document blocked", it cannot create HTMLImportLoader
     // even if there is no sharable one found, as there is possibility that
     // preceding imports load the sharable imports.
     // In that case preceding one should win because it comes first in the tree order.
-    // See also didUnblockDocument().
-    if (isDocumentBlocked())
+    // See also didUnblockFromCreatingDocument().
+    if (state().shouldBlockDocumentCreation())
         return;
 
-    createData();
+    ensureLoader();
 }
 
 void HTMLImportChild::didFinish()
 {
     if (m_client)
         m_client->didFinish();
+
+    if (m_customElementMicrotaskStep) {
+        m_customElementMicrotaskStep->importDidFinish();
+        m_customElementMicrotaskStep = 0;
+    }
+}
+
+void HTMLImportChild::didFinishLoading()
+{
     clearResource();
-    root()->blockerGone();
+    stateWillChange();
 }
 
 Document* HTMLImportChild::importedDocument() const
 {
-    if (!m_data)
+    if (!m_loader)
         return 0;
-    return m_data->importedDocument();
+    return m_loader->importedDocument();
 }
 
 void HTMLImportChild::importDestroyed()
 {
     if (parent())
         parent()->removeChild(this);
-    if (m_data) {
-        m_data->removeClient(this);
-        m_data.clear();
+    if (m_loader) {
+        m_loader->removeClient(this);
+        m_loader.clear();
     }
 }
 
@@ -106,7 +133,7 @@
 
 Document* HTMLImportChild::document() const
 {
-    return (m_data && m_data->isOwnedBy(this)) ? m_data->document() : 0;
+    return (m_loader && m_loader->isOwnedBy(this)) ? m_loader->document() : 0;
 }
 
 void HTMLImportChild::wasDetachedFromDocument()
@@ -118,57 +145,103 @@
 
 void HTMLImportChild::didFinishParsing()
 {
-    ASSERT(m_data->isOwnedBy(this));
-    m_data->didFinishParsing();
+    ASSERT(m_loader->isOwnedBy(this));
+    m_loader->didFinishParsing();
 }
 
-// Once all preceding imports are loaded and "document blocking" ends,
-// HTMLImportChild can decide whether it should load the import by itself
-// or it can share existing one.
-void HTMLImportChild::didUnblockDocument()
+void HTMLImportChild::stateDidChange()
 {
-    HTMLImport::didUnblockDocument();
-    ASSERT(!isDocumentBlocked());
-    ASSERT(!m_data || !m_data->isOwnedBy(this));
+    HTMLImport::stateDidChange();
 
-    if (m_data)
+    // Once all preceding imports are loaded,
+    // HTMLImportChild can decide whether it should load the import by itself
+    // or it can share existing one.
+    if (!state().shouldBlockDocumentCreation())
+        ensureLoader();
+    if (state().isReady())
+        didFinish();
+}
+
+void HTMLImportChild::ensureLoader()
+{
+    if (m_loader)
         return;
+
     if (HTMLImportChild* found = root()->findLinkFor(m_url, this))
-        shareData(found);
+        shareLoader(found);
     else
-        createData();
+        createLoader();
 }
 
-void HTMLImportChild::createData()
+void HTMLImportChild::createLoader()
 {
-    ASSERT(!isDocumentBlocked());
-    ASSERT(!m_data);
-    m_data = HTMLImportData::create(this, parent()->document()->fetcher());
-    m_data->addClient(this);
-    m_data->startLoading(resource());
+    ASSERT(!state().shouldBlockDocumentCreation());
+    ASSERT(!m_loader);
+    m_loader = HTMLImportLoader::create(this);
+    m_loader->addClient(this);
+    m_loader->startLoading(resource());
 }
 
-void HTMLImportChild::shareData(HTMLImportChild* loader)
+void HTMLImportChild::shareLoader(HTMLImportChild* loader)
 {
-    ASSERT(!m_data);
-    m_data = loader->m_data;
-    m_data->addClient(this);
-    root()->blockerGone();
-}
-
-bool HTMLImportChild::isProcessing() const
-{
-    return m_data && m_data->isOwnedBy(this) && m_data->isProcessing();
+    ASSERT(!m_loader);
+    m_loader = loader->m_loader;
+    m_loader->addClient(this);
+    stateWillChange();
 }
 
 bool HTMLImportChild::isDone() const
 {
-    return m_data && m_data->isDone();
+    return m_loader && m_loader->isDone();
 }
 
-bool HTMLImportChild::isLoaded() const
+bool HTMLImportChild::hasLoader() const
 {
-    return m_data->isLoaded();
+    return m_loader;
 }
 
+bool HTMLImportChild::ownsLoader() const
+{
+    return m_loader && m_loader->isOwnedBy(this);
+}
+
+bool HTMLImportChild::loaderHasError() const
+{
+    return m_loader && m_loader->hasError();
+}
+
+
+void HTMLImportChild::setClient(HTMLImportChildClient* client)
+{
+    ASSERT(client);
+    ASSERT(!m_client);
+    m_client = client;
+}
+
+void HTMLImportChild::clearClient()
+{
+    // Doesn't check m_client nullity because we allow
+    // clearClient() to reenter.
+    m_client = 0;
+}
+
+HTMLLinkElement* HTMLImportChild::link() const
+{
+    if (!m_client)
+        return 0;
+    return m_client->link();
+}
+
+#if !defined(NDEBUG)
+void HTMLImportChild::showThis()
+{
+    HTMLImport::showThis();
+    fprintf(stderr, " loader=%p own=%s async=%s url=%s",
+        m_loader.get(),
+        hasLoader() && ownsLoader() ? "Y" : "N",
+        isCreatedByParser() ? "Y" : "N",
+        url().string().utf8().data());
+}
+#endif
+
 } // namespace WebCore
diff --git a/Source/core/html/HTMLImportChild.h b/Source/core/html/HTMLImportChild.h
index eaf2b32..6a1a19b 100644
--- a/Source/core/html/HTMLImportChild.h
+++ b/Source/core/html/HTMLImportChild.h
@@ -31,48 +31,61 @@
 #ifndef HTMLImportChild_h
 #define HTMLImportChild_h
 
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ResourceOwner.h"
 #include "core/html/HTMLImport.h"
-#include "core/html/HTMLImportDataClient.h"
-#include "core/html/HTMLImportResourceOwner.h"
+#include "core/html/HTMLImportLoaderClient.h"
 #include "platform/weborigin/KURL.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
-class HTMLImportData;
+class CustomElementMicrotaskImportStep;
+class HTMLImportLoader;
 class HTMLImportChildClient;
+class HTMLLinkElement;
 
 //
 // An import tree node subclas to encapsulate imported document
 // lifecycle. This class is owned by LinkStyle. The actual loading
-// is done by HTMLImportData, which can be shared among multiple
+// is done by HTMLImportLoader, which can be shared among multiple
 // HTMLImportChild of same link URL.
 //
-// HTMLImportChild implements ResourceClient through HTMLImportResourceOwner
+// HTMLImportChild implements ResourceClient through ResourceOwner
 // so that it can speculatively request linked resources while it is unblocked.
 //
-class HTMLImportChild : public HTMLImport, public HTMLImportDataClient, public HTMLImportResourceOwner {
+class HTMLImportChild FINAL : public HTMLImport, public HTMLImportLoaderClient, public ResourceOwner<RawResource> {
 public:
-    HTMLImportChild(const KURL&, HTMLImportChildClient*);
+    HTMLImportChild(const KURL&, bool createdByParser);
     virtual ~HTMLImportChild();
 
+    HTMLLinkElement* link() const;
     Document* importedDocument() const;
     const KURL& url() const { return m_url; }
 
-    void wasAlreadyLoadedAs(HTMLImportChild* found);
+    void wasAlreadyLoaded();
     void startLoading(const ResourcePtr<RawResource>&);
     void importDestroyed();
-    bool isLoaded() const;
 
     // HTMLImport
+    virtual bool isChild() const OVERRIDE { return true; }
     virtual HTMLImportRoot* root() OVERRIDE;
     virtual Document* document() const OVERRIDE;
     virtual void wasDetachedFromDocument() OVERRIDE;
     virtual void didFinishParsing() OVERRIDE;
-    virtual bool isProcessing() const OVERRIDE;
     virtual bool isDone() const OVERRIDE;
-    virtual void didUnblockDocument() OVERRIDE;
+    virtual bool hasLoader() const OVERRIDE;
+    virtual bool ownsLoader() const OVERRIDE;
+    virtual CustomElementMicrotaskImportStep* customElementMicrotaskStep() const OVERRIDE FINAL { return m_customElementMicrotaskStep; }
+    virtual void stateDidChange() OVERRIDE;
 
-    void clearClient() { m_client = 0; }
+#if !defined(NDEBUG)
+    virtual void showThis() OVERRIDE;
+#endif
+
+    void setClient(HTMLImportChildClient*);
+    void clearClient();
+    bool loaderHasError() const;
 
 private:
     // RawResourceOwner doing nothing.
@@ -81,17 +94,26 @@
     virtual void dataReceived(Resource*, const char*, int) OVERRIDE { }
     virtual void notifyFinished(Resource*) OVERRIDE { }
 
-    // HTMLImportDataClient
-    virtual void didFinish() OVERRIDE;
+    // HTMLImportLoaderClient
+    virtual void didFinishLoading() OVERRIDE;
 
-    void createData();
-    void shareData(HTMLImportChild*);
+    void didFinish();
+    void createLoader();
+    void shareLoader(HTMLImportChild*);
+    void ensureLoader();
 
     KURL m_url;
+    CustomElementMicrotaskImportStep* m_customElementMicrotaskStep;
+    RefPtr<HTMLImportLoader> m_loader;
     HTMLImportChildClient* m_client;
-    RefPtr<HTMLImportData> m_data;
 };
 
+inline HTMLImportChild* toHTMLImportChild(HTMLImport* import)
+{
+    ASSERT(!import || import->isChild());
+    return static_cast<HTMLImportChild*>(import);
+}
+
 } // namespace WebCore
 
 #endif // HTMLImportChild_h
diff --git a/Source/core/html/HTMLImportChildClient.h b/Source/core/html/HTMLImportChildClient.h
index 62866e8..be3177d 100644
--- a/Source/core/html/HTMLImportChildClient.h
+++ b/Source/core/html/HTMLImportChildClient.h
@@ -33,11 +33,16 @@
 
 namespace WebCore {
 
+class HTMLImportChild;
+class HTMLLinkElement;
+
 class HTMLImportChildClient {
 public:
     virtual ~HTMLImportChildClient() { }
     virtual void didFinish() = 0;
-    virtual void loaderWillBeDestroyed() = 0;
+    virtual void importChildWasDestroyed(HTMLImportChild*) = 0;
+    virtual bool isCreatedByParser() const = 0;
+    virtual HTMLLinkElement* link() = 0;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLImportData.cpp b/Source/core/html/HTMLImportLoader.cpp
similarity index 70%
rename from Source/core/html/HTMLImportData.cpp
rename to Source/core/html/HTMLImportLoader.cpp
index ebbd812..e0a0c00 100644
--- a/Source/core/html/HTMLImportData.cpp
+++ b/Source/core/html/HTMLImportLoader.cpp
@@ -29,62 +29,54 @@
  */
 
 #include "config.h"
-#include "core/html/HTMLImportData.h"
+#include "core/html/HTMLImportLoader.h"
 
 #include "core/dom/Document.h"
-#include "core/dom/custom/CustomElementRegistrationContext.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/frame/ContentSecurityPolicyResponseHeaders.h"
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLImport.h"
-#include "core/html/HTMLImportDataClient.h"
+#include "core/html/HTMLImportLoaderClient.h"
 #include "core/loader/DocumentWriter.h"
 
 
 namespace WebCore {
 
-PassRefPtr<HTMLImportData> HTMLImportData::create(HTMLImport* import, ResourceFetcher* fetcher)
-{
-    RefPtr<HTMLImportData> self = adoptRef(new HTMLImportData(import, fetcher));
-    return self.release();
-}
-
-HTMLImportData::HTMLImportData(HTMLImport* import, ResourceFetcher* fetcher)
+HTMLImportLoader::HTMLImportLoader(HTMLImport* import)
     : m_import(import)
-    , m_fetcher(fetcher)
     , m_state(StateLoading)
 {
 }
 
-HTMLImportData::~HTMLImportData()
+HTMLImportLoader::~HTMLImportLoader()
 {
     if (m_importedDocument)
         m_importedDocument->setImport(0);
 }
 
-void HTMLImportData::startLoading(const ResourcePtr<RawResource>& resource)
+void HTMLImportLoader::startLoading(const ResourcePtr<RawResource>& resource)
 {
     setResource(resource);
 }
 
-void HTMLImportData::responseReceived(Resource* resource, const ResourceResponse& response)
+void HTMLImportLoader::responseReceived(Resource* resource, const ResourceResponse& response)
 {
-    // Current canAccess() implementation isn't sufficient for catching cross-domain redirects: http://crbug.com/256976
-    if (!m_fetcher->canAccess(resource, PotentiallyCORSEnabled)) {
+    // Resource may already have been loaded with the import loader
+    // being added as a client later & now being notified. Fail early.
+    if (resource->loadFailedOrCanceled() || response.httpStatusCode() >= 400) {
         setState(StateError);
         return;
     }
-
     setState(startWritingAndParsing(response));
 }
 
-void HTMLImportData::dataReceived(Resource*, const char* data, int length)
+void HTMLImportLoader::dataReceived(Resource*, const char* data, int length)
 {
     RefPtr<DocumentWriter> protectingWriter(m_writer);
     m_writer->addData(data, length);
 }
 
-void HTMLImportData::notifyFinished(Resource* resource)
+void HTMLImportLoader::notifyFinished(Resource* resource)
 {
     // The writer instance indicates that a part of the document can be already loaded.
     // We don't take such a case as an error because the partially-loaded document has been visible from script at this point.
@@ -96,7 +88,7 @@
     setState(finishWriting());
 }
 
-HTMLImportData::State HTMLImportData::startWritingAndParsing(const ResourceResponse& response)
+HTMLImportLoader::State HTMLImportLoader::startWritingAndParsing(const ResourceResponse& response)
 {
     DocumentInit init = DocumentInit(response.url(), 0, m_import->master()->contextDocument(), m_import)
         .withRegistrationContext(m_import->master()->registrationContext());
@@ -107,17 +99,17 @@
     return StateLoading;
 }
 
-HTMLImportData::State HTMLImportData::finishWriting()
+HTMLImportLoader::State HTMLImportLoader::finishWriting()
 {
     return StateWritten;
 }
 
-HTMLImportData::State HTMLImportData::finishParsing()
+HTMLImportLoader::State HTMLImportLoader::finishParsing()
 {
     return StateReady;
 }
 
-void HTMLImportData::setState(State state)
+void HTMLImportLoader::setState(State state)
 {
     if (m_state == state)
         return;
@@ -134,48 +126,40 @@
         didFinish();
 }
 
-void HTMLImportData::didFinishParsing()
+void HTMLImportLoader::didFinishParsing()
 {
     setState(finishParsing());
 }
 
-Document* HTMLImportData::importedDocument() const
+Document* HTMLImportLoader::importedDocument() const
 {
     if (m_state == StateError)
         return 0;
     return m_importedDocument.get();
 }
 
-bool HTMLImportData::isProcessing() const
-{
-    if (!m_importedDocument)
-        return !isDone();
-    return m_importedDocument->parsing();
-}
-
-void HTMLImportData::didFinish()
+void HTMLImportLoader::didFinish()
 {
     for (size_t i = 0; i < m_clients.size(); ++i)
-        m_clients[i]->didFinish();
+        m_clients[i]->didFinishLoading();
 
     clearResource();
 
     ASSERT(!m_importedDocument || !m_importedDocument->parsing());
 }
 
-void HTMLImportData::addClient(HTMLImportDataClient* client)
+void HTMLImportLoader::addClient(HTMLImportLoaderClient* client)
 {
     ASSERT(kNotFound == m_clients.find(client));
     m_clients.append(client);
     if (isDone())
-        client->didFinish();
+        client->didFinishLoading();
 }
 
-void HTMLImportData::removeClient(HTMLImportDataClient* client)
+void HTMLImportLoader::removeClient(HTMLImportLoaderClient* client)
 {
     ASSERT(kNotFound != m_clients.find(client));
     m_clients.remove(m_clients.find(client));
 }
 
-
 } // namespace WebCore
diff --git a/Source/core/html/HTMLImportData.h b/Source/core/html/HTMLImportLoader.h
similarity index 77%
rename from Source/core/html/HTMLImportData.h
rename to Source/core/html/HTMLImportLoader.h
index 92e3f76..a09f658 100644
--- a/Source/core/html/HTMLImportData.h
+++ b/Source/core/html/HTMLImportLoader.h
@@ -28,10 +28,11 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef HTMLImportData_h
-#define HTMLImportData_h
+#ifndef HTMLImportLoader_h
+#define HTMLImportLoader_h
 
-#include "core/html/HTMLImportResourceOwner.h"
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ResourceOwner.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
@@ -39,16 +40,15 @@
 class Document;
 class DocumentWriter;
 class HTMLImport;
-class HTMLImportDataClient;
+class HTMLImportLoaderClient;
 
 //
-// Owning imported Document lifetime. It also implements ResourceClient through HTMLImportResourceOwner
+// Owning imported Document lifetime. It also implements ResourceClient through ResourceOwner
 // to feed fetched bytes to the DocumentWriter of the imported document.
-// HTMLImportData is owned by and shared between HTMLImportChild.
+// HTMLImportLoader is owned by and shared between HTMLImportChild.
 //
-// FIXME: Should be renamed to HTMLImportLoader
 //
-class HTMLImportData : public RefCounted<HTMLImportData>, public HTMLImportResourceOwner {
+class HTMLImportLoader FINAL : public RefCounted<HTMLImportLoader>, public ResourceOwner<RawResource> {
 public:
     enum State {
         StateLoading,
@@ -57,25 +57,27 @@
         StateReady
     };
 
-    static PassRefPtr<HTMLImportData> create(HTMLImport*, ResourceFetcher*);
+    static PassRefPtr<HTMLImportLoader> create(HTMLImport* import)
+    {
+        return adoptRef(new HTMLImportLoader(import));
+    }
 
-    virtual ~HTMLImportData();
+    virtual ~HTMLImportLoader();
 
     Document* document() const { return m_importedDocument.get(); }
     Document* importedDocument() const;
-    void addClient(HTMLImportDataClient*);
-    void removeClient(HTMLImportDataClient*);
+    void addClient(HTMLImportLoaderClient*);
+    void removeClient(HTMLImportLoaderClient*);
 
     bool isDone() const { return m_state == StateReady || m_state == StateError; }
-    bool isLoaded() const { return m_state == StateReady; }
-    bool isProcessing() const;
+    bool hasError() const { return m_state == StateError; }
 
     void startLoading(const ResourcePtr<RawResource>&);
     void didFinishParsing();
     bool isOwnedBy(const HTMLImport* import) const { return m_import == import; }
 
 private:
-    HTMLImportData(HTMLImport*, ResourceFetcher*);
+    HTMLImportLoader(HTMLImport*);
 
     // RawResourceClient
     virtual void responseReceived(Resource*, const ResourceResponse&) OVERRIDE;
@@ -90,8 +92,7 @@
     void didFinish();
 
     HTMLImport* m_import;
-    ResourceFetcher* m_fetcher;
-    Vector<HTMLImportDataClient*> m_clients;
+    Vector<HTMLImportLoaderClient*> m_clients;
     State m_state;
     RefPtr<Document> m_importedDocument;
     RefPtr<DocumentWriter> m_writer;
@@ -99,4 +100,4 @@
 
 } // namespace WebCore
 
-#endif // HTMLImportData_h
+#endif // HTMLImportLoader_h
diff --git a/Source/core/html/HTMLImportDataClient.h b/Source/core/html/HTMLImportLoaderClient.h
similarity index 87%
rename from Source/core/html/HTMLImportDataClient.h
rename to Source/core/html/HTMLImportLoaderClient.h
index 0c26a22..4586661 100644
--- a/Source/core/html/HTMLImportDataClient.h
+++ b/Source/core/html/HTMLImportLoaderClient.h
@@ -28,17 +28,17 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef HTMLImportDataClient_h
-#define HTMLImportDataClient_h
+#ifndef HTMLImportLoaderClient_h
+#define HTMLImportLoaderClient_h
 
 namespace WebCore {
 
-class HTMLImportDataClient {
+class HTMLImportLoaderClient {
 public:
-    virtual ~HTMLImportDataClient() { }
-    virtual void didFinish() = 0;
+    virtual ~HTMLImportLoaderClient() { }
+    virtual void didFinishLoading() = 0;
 };
 
 }
 
-#endif // HTMLImportDataClient_h
+#endif // HTMLImportLoaderClient_h
diff --git a/Source/core/html/HTMLImportResourceOwner.h b/Source/core/html/HTMLImportResourceOwner.h
deleted file mode 100644
index a8f5c52..0000000
--- a/Source/core/html/HTMLImportResourceOwner.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef HTMLImportResourceOwner_h
-#define HTMLImportResourceOwner_h
-
-#include "core/fetch/RawResource.h"
-#include "core/fetch/ResourcePtr.h"
-
-namespace WebCore {
-
-// A RawResourceClient implenetation which is responsible for
-// owning RawResource object and adding/removing itself as a client
-// according to its lifetime.
-//
-// FIXME: This could be geneeric ResouceOwner<ResourceType> once it is
-// found that this class is broadly useful even outside HTMLImports module.
-//
-class HTMLImportResourceOwner : public RawResourceClient {
-public:
-    HTMLImportResourceOwner();
-    virtual ~HTMLImportResourceOwner();
-
-protected:
-    const ResourcePtr<RawResource>& resource() const { return m_resource; }
-
-    void setResource(const ResourcePtr<RawResource>&);
-    void clearResource();
-    bool hasResource() const { return m_resource.get(); }
-
-private:
-    ResourcePtr<RawResource> m_resource;
-};
-
-} // namespace WebCore
-
-#endif // HTMLImportResourceOwner_h
diff --git a/Source/core/html/HTMLImportState.h b/Source/core/html/HTMLImportState.h
new file mode 100644
index 0000000..6c3c140
--- /dev/null
+++ b/Source/core/html/HTMLImportState.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef HTMLImportState_h
+#define HTMLImportState_h
+
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+class HTMLImportState {
+public:
+    enum Value {
+        BlockingDocumentCreation = 0,
+        BlockingScriptExecution,
+        Active,
+        Ready,
+        Invalid
+    };
+
+    explicit HTMLImportState(Value value = BlockingDocumentCreation)
+        : m_value(value)
+    { }
+
+    bool shouldBlockScriptExecution() const { return checkedValue() <= BlockingScriptExecution; }
+    bool shouldBlockDocumentCreation() const { return checkedValue() <= BlockingDocumentCreation; }
+    bool isReady() const { return checkedValue() == Ready; }
+    bool isValid() const { return m_value != Invalid; }
+    bool operator==(const HTMLImportState& other) const { return m_value == other.m_value; }
+    bool operator!=(const HTMLImportState& other) const { return !(*this == other); }
+    bool operator<=(const HTMLImportState& other) const { return m_value <= other.m_value; }
+
+#if !defined(NDEBUG)
+    Value peekValueForDebug() const { return m_value; }
+#endif
+
+    static HTMLImportState invalidState() { return HTMLImportState(Invalid); }
+    static HTMLImportState blockedState() { return HTMLImportState(BlockingDocumentCreation); }
+private:
+    Value checkedValue() const;
+    Value m_value;
+};
+
+inline HTMLImportState::Value HTMLImportState::checkedValue() const
+{
+    ASSERT(isValid());
+    return m_value;
+}
+
+}
+
+#endif
diff --git a/Source/core/html/HTMLImportStateResolver.cpp b/Source/core/html/HTMLImportStateResolver.cpp
new file mode 100644
index 0000000..90650e8
--- /dev/null
+++ b/Source/core/html/HTMLImportStateResolver.cpp
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/html/HTMLImportStateResolver.h"
+
+#include "core/html/HTMLImport.h"
+
+namespace WebCore {
+
+inline bool HTMLImportStateResolver::isBlockingFollowers(HTMLImport* import)
+{
+    if (!import->hasLoader())
+        return true;
+    if (!import->ownsLoader())
+        return false;
+    return !import->state().isReady();
+}
+
+inline bool HTMLImportStateResolver::shouldBlockDocumentCreation() const
+{
+    // If any of its preceeding imports isn't ready, this import
+    // cannot start loading because such preceeding onces can include
+    // duplicating import that should wins over this.
+    for (const HTMLImport* ancestor = m_import; ancestor; ancestor = ancestor->parent()) {
+        if (ancestor->previous() && isBlockingFollowers(ancestor->previous()))
+            return true;
+    }
+
+    return false;
+}
+
+inline bool HTMLImportStateResolver::shouldBlockScriptExecution() const
+{
+    for (HTMLImport* child = m_import->firstChild(); child; child = child->next()) {
+        if (child->isCreatedByParser() && isBlockingFollowers(child))
+            return true;
+    }
+
+    return false;
+}
+
+inline bool HTMLImportStateResolver::isActive() const
+{
+    return !m_import->isDone();
+}
+
+HTMLImportState HTMLImportStateResolver::resolve() const
+{
+    if (shouldBlockDocumentCreation())
+        return HTMLImportState(HTMLImportState::BlockingDocumentCreation);
+    if (shouldBlockScriptExecution())
+        return HTMLImportState(HTMLImportState::BlockingScriptExecution);
+    if (isActive())
+        return HTMLImportState(HTMLImportState::Active);
+    return HTMLImportState(HTMLImportState::Ready);
+}
+
+}
+
diff --git a/Source/core/html/HTMLImportDataClient.h b/Source/core/html/HTMLImportStateResolver.h
similarity index 72%
copy from Source/core/html/HTMLImportDataClient.h
copy to Source/core/html/HTMLImportStateResolver.h
index 0c26a22..417680c 100644
--- a/Source/core/html/HTMLImportDataClient.h
+++ b/Source/core/html/HTMLImportStateResolver.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,17 +28,34 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef HTMLImportDataClient_h
-#define HTMLImportDataClient_h
+#ifndef HTMLImportStateResolver_h
+#define HTMLImportStateResolver_h
+
+#include "core/html/HTMLImportState.h"
 
 namespace WebCore {
 
-class HTMLImportDataClient {
+class HTMLImport;
+
+class HTMLImportStateResolver {
 public:
-    virtual ~HTMLImportDataClient() { }
-    virtual void didFinish() = 0;
+    explicit HTMLImportStateResolver(HTMLImport* import)
+        : m_import(import)
+    { }
+
+    HTMLImportState resolve() const;
+
+private:
+    static bool isBlockingFollowers(HTMLImport*);
+
+    bool shouldBlockDocumentCreation() const;
+    bool shouldBlockScriptExecution() const;
+    bool isActive() const;
+
+    HTMLImport* m_import;
 };
 
 }
 
-#endif // HTMLImportDataClient_h
+#endif // HTMLImportStateResolver_h
+
diff --git a/Source/core/html/HTMLImportsController.cpp b/Source/core/html/HTMLImportsController.cpp
index bc057d5..7baf599 100644
--- a/Source/core/html/HTMLImportsController.cpp
+++ b/Source/core/html/HTMLImportsController.cpp
@@ -48,8 +48,9 @@
 
 HTMLImportsController::HTMLImportsController(Document* master)
     : m_master(master)
-    , m_unblockTimer(this, &HTMLImportsController::unblockTimerFired)
+    , m_recalcTimer(this, &HTMLImportsController::recalcTimerFired)
 {
+    recalcTreeState(this); // This recomputes initial state.
 }
 
 HTMLImportsController::~HTMLImportsController()
@@ -68,7 +69,8 @@
 
 HTMLImportChild* HTMLImportsController::createChild(const KURL& url, HTMLImport* parent, HTMLImportChildClient* client)
 {
-    OwnPtr<HTMLImportChild> loader = adoptPtr(new HTMLImportChild(url, client));
+    OwnPtr<HTMLImportChild> loader = adoptPtr(new HTMLImportChild(url, client->isCreatedByParser()));
+    loader->setClient(client);
     parent->appendChild(loader.get());
     m_imports.append(loader.release());
     return m_imports.last().get();
@@ -78,9 +80,9 @@
 {
     ASSERT(!request.url().isEmpty() && request.url().isValid());
 
-    if (HTMLImportChild* found = findLinkFor(request.url())) {
+    if (findLinkFor(request.url())) {
         HTMLImportChild* child = createChild(request.url(), parent, client);
-        child->wasAlreadyLoadedAs(found);
+        child->wasAlreadyLoaded();
         return child;
     }
 
@@ -106,7 +108,7 @@
 {
     for (size_t i = 0; i < m_imports.size(); ++i) {
         HTMLImportChild* candidate = m_imports[i].get();
-        if (candidate != excluding && equalIgnoringFragmentIdentifier(candidate->url(), url) && !candidate->isDocumentBlocked())
+        if (candidate != excluding && equalIgnoringFragmentIdentifier(candidate->url(), url) && candidate->hasLoader())
             return candidate;
     }
 
@@ -138,13 +140,9 @@
     clear();
 }
 
-void HTMLImportsController::didFinishParsing()
+bool HTMLImportsController::hasLoader() const
 {
-}
-
-bool HTMLImportsController::isProcessing() const
-{
-    return m_master->parsing();
+    return true;
 }
 
 bool HTMLImportsController::isDone() const
@@ -152,24 +150,19 @@
     return !m_master->parsing();
 }
 
-void HTMLImportsController::blockerGone()
+void HTMLImportsController::scheduleRecalcState()
 {
-    scheduleUnblock();
-}
-
-void HTMLImportsController::scheduleUnblock()
-{
-    if (m_unblockTimer.isActive())
+    if (m_recalcTimer.isActive())
         return;
-    m_unblockTimer.startOneShot(0);
+    m_recalcTimer.startOneShot(0);
 }
 
-void HTMLImportsController::unblockTimerFired(Timer<HTMLImportsController>*)
+void HTMLImportsController::recalcTimerFired(Timer<HTMLImportsController>*)
 {
     do {
-        m_unblockTimer.stop();
-        HTMLImport::unblock(this);
-    } while (m_unblockTimer.isActive());
+        m_recalcTimer.stop();
+        HTMLImport::recalcTreeState(this);
+    } while (m_recalcTimer.isActive());
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLImportsController.h b/Source/core/html/HTMLImportsController.h
index 7cc1b92..1d62bde 100644
--- a/Source/core/html/HTMLImportsController.h
+++ b/Source/core/html/HTMLImportsController.h
@@ -48,7 +48,7 @@
 class HTMLImportChild;
 class HTMLImportChildClient;
 
-class HTMLImportsController : public HTMLImportRoot, public DocumentSupplement {
+class HTMLImportsController FINAL : public HTMLImportRoot, public DocumentSupplement {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static void provideTo(Document*);
@@ -60,12 +60,11 @@
     virtual HTMLImportRoot* root() OVERRIDE;
     virtual Document* document() const OVERRIDE;
     virtual void wasDetachedFromDocument() OVERRIDE;
-    virtual void didFinishParsing() OVERRIDE;
-    virtual bool isProcessing() const OVERRIDE;
     virtual bool isDone() const OVERRIDE;
+    virtual bool hasLoader() const OVERRIDE;
 
     // HTMLImportRoot
-    virtual void blockerGone() OVERRIDE;
+    virtual void scheduleRecalcState() OVERRIDE;
     virtual HTMLImportsController* toController() OVERRIDE { return this; }
     virtual HTMLImportChild* findLinkFor(const KURL&, HTMLImport* excluding = 0) const OVERRIDE;
 
@@ -75,15 +74,14 @@
     SecurityOrigin* securityOrigin() const;
     ResourceFetcher* fetcher() const;
 
-    void scheduleUnblock();
-    void unblockTimerFired(Timer<HTMLImportsController>*);
+    void recalcTimerFired(Timer<HTMLImportsController>*);
 
 private:
     HTMLImportChild* createChild(const KURL&, HTMLImport* parent, HTMLImportChildClient*);
     void clear();
 
     Document* m_master;
-    Timer<HTMLImportsController> m_unblockTimer;
+    Timer<HTMLImportsController> m_recalcTimer;
 
     // List of import which has been loaded or being loaded.
     typedef Vector<OwnPtr<HTMLImportChild> > ImportList;
diff --git a/Source/core/html/HTMLInputElement.cpp b/Source/core/html/HTMLInputElement.cpp
index 723a5e6..32ca5d5 100644
--- a/Source/core/html/HTMLInputElement.cpp
+++ b/Source/core/html/HTMLInputElement.cpp
@@ -52,7 +52,9 @@
 #include "core/events/TouchEvent.h"
 #include "core/fileapi/FileList.h"
 #include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
 #include "core/frame/FrameView.h"
+#include "core/frame/UseCounter.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLDataListElement.h"
 #include "core/html/HTMLFormElement.h"
@@ -65,10 +67,8 @@
 #include "core/html/forms/SearchInputType.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/ShadowElementNames.h"
-#include "core/frame/UseCounter.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/page/Page.h"
 #include "core/rendering/RenderTextControlSingleLine.h"
 #include "core/rendering/RenderTheme.h"
 #include "platform/DateTimeChooser.h"
@@ -120,6 +120,7 @@
     , m_valueAttributeWasUpdatedAfterParsing(false)
     , m_canReceiveDroppedFiles(false)
     , m_hasTouchEventHandler(false)
+    , m_shouldRevealPassword(false)
     , m_inputType(InputType::createText(*this))
     , m_inputTypeView(m_inputType)
 {
@@ -165,9 +166,9 @@
     // setForm(0) may register this to a document-level radio button group.
     // We should unregister it to avoid accessing a deleted object.
     if (isRadioButton())
-        document().formController()->checkedRadioButtons().removeButton(this);
+        document().formController()->radioButtonGroupScope().removeButton(this);
     if (m_hasTouchEventHandler)
-        document().didRemoveEventTargetNode(this);
+        document().didRemoveTouchEventHandler(this);
 }
 
 const AtomicString& HTMLInputElement::name() const
@@ -351,23 +352,28 @@
 
 void HTMLInputElement::beginEditing()
 {
+    ASSERT(document().isActive());
+    if (!document().isActive())
+        return;
+
     if (!isTextField())
         return;
 
-    if (Frame* frame = document().frame())
-        frame->spellChecker().didBeginEditing(this);
+    document().frame()->spellChecker().didBeginEditing(this);
 }
 
 void HTMLInputElement::endEditing()
 {
+    ASSERT(document().isActive());
+    if (!document().isActive())
+        return;
+
     if (!isTextField())
         return;
 
-    if (Frame* frame = document().frame()) {
-        frame->spellChecker().didEndEditingOnTextField(this);
-        if (Page* page = frame->page())
-            page->chrome().client().didEndEditingOnTextField(*this);
-    }
+    Frame* frame = document().frame();
+    frame->spellChecker().didEndEditingOnTextField(this);
+    frame->host()->chrome().client().didEndEditingOnTextField(*this);
 }
 
 bool HTMLInputElement::shouldUseInputMethod()
@@ -375,9 +381,9 @@
     return m_inputType->shouldUseInputMethod();
 }
 
-void HTMLInputElement::handleFocusEvent(Element* oldFocusedElement, FocusDirection direction)
+void HTMLInputElement::handleFocusEvent(Element* oldFocusedElement, FocusType type)
 {
-    m_inputTypeView->handleFocusEvent(oldFocusedElement, direction);
+    m_inputTypeView->handleFocusEvent(oldFocusedElement, type);
     m_inputType->enableSecureTextInput();
 }
 
@@ -389,14 +395,7 @@
 
 void HTMLInputElement::setType(const AtomicString& type)
 {
-    // FIXME: This should just call setAttribute. No reason to handle the empty string specially.
-    // We should write a test case to show that setting to the empty string does not remove the
-    // attribute in other browsers and then fix this. Note that setting to null *does* remove
-    // the attribute and setAttribute implements that.
-    if (type.isEmpty())
-        removeAttribute(typeAttr);
-    else
-        setAttribute(typeAttr, type);
+    setAttribute(typeAttr, type);
 }
 
 void HTMLInputElement::updateType()
@@ -514,14 +513,9 @@
     return HTMLTextFormControlElement::canStartSelection();
 }
 
-bool HTMLInputElement::canHaveSelection() const
-{
-    return isTextField();
-}
-
 int HTMLInputElement::selectionStartForBinding(ExceptionState& exceptionState) const
 {
-    if (!canHaveSelection()) {
+    if (!m_inputType->supportsSelectionAPI()) {
         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
         return 0;
     }
@@ -530,8 +524,8 @@
 
 int HTMLInputElement::selectionEndForBinding(ExceptionState& exceptionState) const
 {
-    if (!canHaveSelection()) {
-        exceptionState.throwDOMException(InvalidStateError,  "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
+    if (!m_inputType->supportsSelectionAPI()) {
+        exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
         return 0;
     }
     return HTMLTextFormControlElement::selectionEnd();
@@ -539,7 +533,7 @@
 
 String HTMLInputElement::selectionDirectionForBinding(ExceptionState& exceptionState) const
 {
-    if (!canHaveSelection()) {
+    if (!m_inputType->supportsSelectionAPI()) {
         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
         return String();
     }
@@ -548,7 +542,7 @@
 
 void HTMLInputElement::setSelectionStartForBinding(int start, ExceptionState& exceptionState)
 {
-    if (!canHaveSelection()) {
+    if (!m_inputType->supportsSelectionAPI()) {
         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
         return;
     }
@@ -557,7 +551,7 @@
 
 void HTMLInputElement::setSelectionEndForBinding(int end, ExceptionState& exceptionState)
 {
-    if (!canHaveSelection()) {
+    if (!m_inputType->supportsSelectionAPI()) {
         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
         return;
     }
@@ -566,7 +560,7 @@
 
 void HTMLInputElement::setSelectionDirectionForBinding(const String& direction, ExceptionState& exceptionState)
 {
-    if (!canHaveSelection()) {
+    if (!m_inputType->supportsSelectionAPI()) {
         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
         return;
     }
@@ -575,7 +569,7 @@
 
 void HTMLInputElement::setSelectionRangeForBinding(int start, int end, ExceptionState& exceptionState)
 {
-    if (!canHaveSelection()) {
+    if (!m_inputType->supportsSelectionAPI()) {
         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
         return;
     }
@@ -584,7 +578,7 @@
 
 void HTMLInputElement::setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionState& exceptionState)
 {
-    if (!canHaveSelection()) {
+    if (!m_inputType->supportsSelectionAPI()) {
         exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
         return;
     }
@@ -648,7 +642,7 @@
         // We only need to setChanged if the form is looking at the default value right now.
         if (!hasDirtyValue()) {
             updatePlaceholderVisibility(false);
-            setNeedsStyleRecalc();
+            setNeedsStyleRecalc(SubtreeStyleChange);
         }
         setFormControlValueMatchesRenderer(false);
         setNeedsValidityCheck();
@@ -687,10 +681,10 @@
         // time to relayout for this change.
         if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0))
             lazyReattachIfAttached();
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
         UseCounter::count(document(), UseCounter::ResultsAttribute);
     } else if (name == incrementalAttr) {
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
         UseCounter::count(document(), UseCounter::IncrementalAttribute);
     } else if (name == minAttr) {
         m_inputTypeView->minOrMaxAttributeChanged();
@@ -740,7 +734,7 @@
             m_inputTypeView->createShadowSubtree();
             setFormControlValueMatchesRenderer(false);
         }
-        UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute);
+        UseCounter::countDeprecation(document(), UseCounter::PrefixedSpeechAttribute);
     } else if (name == onwebkitspeechchangeAttr)
         setAttributeEventListener(EventTypeNames::webkitspeechchange, createAttributeEventListener(this, name, value));
 #endif
@@ -804,9 +798,9 @@
     String alt = fastGetAttribute(altAttr);
     // fall back to title attribute
     if (alt.isNull())
-        alt = getAttribute(titleAttr);
+        alt = fastGetAttribute(titleAttr);
     if (alt.isNull())
-        alt = getAttribute(valueAttr);
+        alt = fastGetAttribute(valueAttr);
     if (alt.isEmpty())
         alt = locale().queryString(blink::WebLocalizedString::InputElementAltText);
     return alt;
@@ -839,8 +833,10 @@
 
 void HTMLInputElement::resetImpl()
 {
-    if (m_inputType->storesValueSeparateFromAttribute())
+    if (m_inputType->storesValueSeparateFromAttribute()) {
         setValue(String());
+        setNeedsValidityCheck();
+    }
 
     setChecked(hasAttribute(checkedAttr));
     m_reflectsCheckedAttribute = true;
@@ -863,10 +859,10 @@
 
     m_reflectsCheckedAttribute = false;
     m_isChecked = nowChecked;
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
 
-    if (CheckedRadioButtons* buttons = checkedRadioButtons())
-            buttons->updateCheckedState(this);
+    if (RadioButtonGroupScope* scope = radioButtonGroupScope())
+        scope->updateCheckedState(this);
     if (renderer() && renderer()->style()->hasAppearance())
         RenderTheme::theme().stateChanged(renderer(), CheckedState);
 
@@ -975,7 +971,7 @@
         return;
     setFormControlValueMatchesRenderer(false);
     m_suggestedValue = sanitizeValue(value);
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
     m_inputTypeView->updateView();
 }
 
@@ -998,7 +994,7 @@
 void HTMLInputElement::setValue(const String& value, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
 {
     if (isFileUpload() && !value.isEmpty()) {
-        exceptionState.throwDOMException(InvalidStateError, "This input element accepts a filename, which may only be programatically set to the empty string.");
+        exceptionState.throwDOMException(InvalidStateError, "This input element accepts a filename, which may only be programmatically set to the empty string.");
         return;
     }
     setValue(value, eventBehavior);
@@ -1052,8 +1048,8 @@
 
 void HTMLInputElement::setValueAsNumber(double newValue, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
 {
-    if (!std::isfinite(newValue)) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(newValue));
+    if (std::isinf(newValue)) {
+        exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(newValue));
         return;
     }
     m_inputType->setValueAsDouble(newValue, eventBehavior, exceptionState);
@@ -1114,7 +1110,7 @@
             return;
     }
 
-    if (evt->isTouchEvent()) {
+    if (evt->isTouchEvent() && m_inputTypeView->hasTouchEventHandler()) {
         m_inputTypeView->handleTouchEvent(toTouchEvent(evt));
         if (evt->defaultHandled())
             return;
@@ -1269,11 +1265,6 @@
     return parseAcceptAttribute(fastGetAttribute(acceptAttr), isValidFileExtension);
 }
 
-const AtomicString& HTMLInputElement::accept() const
-{
-    return fastGetAttribute(acceptAttr);
-}
-
 const AtomicString& HTMLInputElement::alt() const
 {
     return fastGetAttribute(altAttr);
@@ -1349,11 +1340,6 @@
         renderer()->updateFromElement();
 }
 
-String HTMLInputElement::visibleValue() const
-{
-    return m_inputType->visibleValue();
-}
-
 String HTMLInputElement::sanitizeValue(const String& proposedValue) const
 {
     if (proposedValue.isNull())
@@ -1442,9 +1428,9 @@
         imageLoader()->elementDidMoveToNewDocument();
 
     if (isRadioButton())
-        oldDocument.formController()->checkedRadioButtons().removeButton(this);
+        oldDocument.formController()->radioButtonGroupScope().removeButton(this);
     if (m_hasTouchEventHandler)
-        oldDocument.didRemoveEventTargetNode(this);
+        oldDocument.didRemoveTouchEventHandler(this);
 
     if (m_hasTouchEventHandler)
         document().didAddTouchEventHandler(this);
@@ -1452,11 +1438,10 @@
     HTMLTextFormControlElement::didMoveToNewDocument(oldDocument);
 }
 
-void HTMLInputElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
+void HTMLInputElement::removeAllEventListeners()
 {
-    HTMLTextFormControlElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, src());
+    HTMLTextFormControlElement::removeAllEventListeners();
+    m_hasTouchEventHandler = false;
 }
 
 bool HTMLInputElement::recalcWillValidate() const
@@ -1467,8 +1452,8 @@
 void HTMLInputElement::requiredAttributeChanged()
 {
     HTMLTextFormControlElement::requiredAttributeChanged();
-    if (CheckedRadioButtons* buttons = checkedRadioButtons())
-        buttons->requiredAttributeChanged(this);
+    if (RadioButtonGroupScope* scope = radioButtonGroupScope())
+        scope->requiredAttributeChanged(this);
     m_inputTypeView->requiredAttributeChanged();
 }
 
@@ -1501,6 +1486,19 @@
     return toHTMLDataListElement(element);
 }
 
+bool HTMLInputElement::hasValidDataListOptions() const
+{
+    HTMLDataListElement* dataList = this->dataList();
+    if (!dataList)
+        return false;
+    RefPtr<HTMLCollection> options = dataList->options();
+    for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
+        if (isValidValue(option->value()))
+            return true;
+    }
+    return false;
+}
+
 void HTMLInputElement::resetListAttributeTargetObserver()
 {
     if (inDocument())
@@ -1564,11 +1562,6 @@
     return m_inputType->isRangeControl();
 }
 
-bool HTMLInputElement::isColorControl() const
-{
-    return m_inputType->isColorControl();
-}
-
 bool HTMLInputElement::isText() const
 {
     return m_inputType->isTextType();
@@ -1594,11 +1587,6 @@
     return m_inputType->isNumberField();
 }
 
-bool HTMLInputElement::isSubmitButton() const
-{
-    return m_inputType->isSubmitButton();
-}
-
 bool HTMLInputElement::isTelephoneField() const
 {
     return m_inputType->isTelephoneField();
@@ -1670,7 +1658,7 @@
     m_maxLength = maxLength;
     if (oldMaxLength != maxLength)
         updateValueIfNeeded();
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
     setNeedsValidityCheck();
 }
 
@@ -1701,11 +1689,11 @@
     // As per crbug.com/240252, emit a deprecation warning when the "capture"
     // attribute is used as an enum. The spec has been updated and "capture" is
     // supposed to be used as a boolean.
-    bool hasDeprecatedUsage = !fastGetAttribute(captureAttr).isNull();
+    bool hasDeprecatedUsage = !fastGetAttribute(captureAttr).isEmpty();
     if (hasDeprecatedUsage)
         UseCounter::countDeprecation(document(), UseCounter::CaptureAttributeAsEnum);
     else
-        UseCounter::count(document(), UseCounter::CaptureAttributeAsEnum);
+        UseCounter::count(document(), UseCounter::CaptureAttributeAsBoolean);
 
     return true;
 }
@@ -1714,39 +1702,39 @@
 bool HTMLInputElement::isInRequiredRadioButtonGroup()
 {
     ASSERT(isRadioButton());
-    if (CheckedRadioButtons* buttons = checkedRadioButtons())
-        return buttons->isInRequiredGroup(this);
+    if (RadioButtonGroupScope* scope = radioButtonGroupScope())
+        return scope->isInRequiredGroup(this);
     return false;
 }
 
 HTMLInputElement* HTMLInputElement::checkedRadioButtonForGroup() const
 {
-    if (CheckedRadioButtons* buttons = checkedRadioButtons())
-        return buttons->checkedButtonForGroup(name());
+    if (RadioButtonGroupScope* scope = radioButtonGroupScope())
+        return scope->checkedButtonForGroup(name());
     return 0;
 }
 
-CheckedRadioButtons* HTMLInputElement::checkedRadioButtons() const
+RadioButtonGroupScope* HTMLInputElement::radioButtonGroupScope() const
 {
     if (!isRadioButton())
         return 0;
     if (HTMLFormElement* formElement = form())
-        return &formElement->checkedRadioButtons();
+        return &formElement->radioButtonGroupScope();
     if (inDocument())
-        return &document().formController()->checkedRadioButtons();
+        return &document().formController()->radioButtonGroupScope();
     return 0;
 }
 
 inline void HTMLInputElement::addToRadioButtonGroup()
 {
-    if (CheckedRadioButtons* buttons = checkedRadioButtons())
-        buttons->addButton(this);
+    if (RadioButtonGroupScope* scope = radioButtonGroupScope())
+        scope->addButton(this);
 }
 
 inline void HTMLInputElement::removeFromRadioButtonGroup()
 {
-    if (CheckedRadioButtons* buttons = checkedRadioButtons())
-        buttons->removeButton(this);
+    if (RadioButtonGroupScope* scope = radioButtonGroupScope())
+        scope->removeButton(this);
 }
 
 unsigned HTMLInputElement::height() const
@@ -1818,7 +1806,7 @@
         parameters.locale = defaultLanguage();
     else {
         AtomicString computedLocale = computeInheritedLanguage();
-        parameters.locale = computedLocale.isEmpty() ? AtomicString(defaultLanguage()) : computedLocale;
+        parameters.locale = computedLocale.isEmpty() ? defaultLanguage() : computedLocale;
     }
 
     StepRange stepRange = createStepRange(RejectAny);
@@ -1834,20 +1822,18 @@
     parameters.currentValue = value();
     parameters.doubleValue = m_inputType->valueAsDouble();
     parameters.isAnchorElementRTL = computedStyle()->direction() == RTL;
-    if (RuntimeEnabledFeatures::dataListElementEnabled()) {
-        if (HTMLDataListElement* dataList = this->dataList()) {
-            RefPtr<HTMLCollection> options = dataList->options();
-            for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
-                if (!isValidValue(option->value()))
-                    continue;
-                DateTimeSuggestion suggestion;
-                suggestion.value = m_inputType->parseToNumber(option->value(), Decimal::nan()).toDouble();
-                if (std::isnan(suggestion.value))
-                    continue;
-                suggestion.localizedValue = localizeValue(option->value());
-                suggestion.label = option->value() == option->label() ? String() : option->label();
-                parameters.suggestions.append(suggestion);
-            }
+    if (HTMLDataListElement* dataList = this->dataList()) {
+        RefPtr<HTMLCollection> options = dataList->options();
+        for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
+            if (!isValidValue(option->value()))
+                continue;
+            DateTimeSuggestion suggestion;
+            suggestion.value = m_inputType->parseToNumber(option->value(), Decimal::nan()).toDouble();
+            if (std::isnan(suggestion.value))
+                continue;
+            suggestion.localizedValue = localizeValue(option->value());
+            suggestion.label = option->value() == option->label() ? String() : option->label();
+            parameters.suggestions.append(suggestion);
         }
     }
     return true;
@@ -1858,11 +1844,24 @@
     return m_inputType->supportsInputModeAttribute();
 }
 
+void HTMLInputElement::setShouldRevealPassword(bool value)
+{
+    if (m_shouldRevealPassword == value)
+        return;
+    m_shouldRevealPassword = value;
+    lazyReattachIfAttached();
+}
+
 bool HTMLInputElement::isInteractiveContent() const
 {
     return m_inputType->isInteractiveContent();
 }
 
+bool HTMLInputElement::supportsAutofocus() const
+{
+    return m_inputType->isInteractiveContent();
+}
+
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
 PassRefPtr<RenderStyle> HTMLInputElement::customStyleForRenderer()
 {
diff --git a/Source/core/html/HTMLInputElement.h b/Source/core/html/HTMLInputElement.h
index 04452ab..0181231 100644
--- a/Source/core/html/HTMLInputElement.h
+++ b/Source/core/html/HTMLInputElement.h
@@ -31,18 +31,17 @@
 
 namespace WebCore {
 
-class CheckedRadioButtons;
 class DragData;
 class ExceptionState;
 class FileList;
 class HTMLDataListElement;
 class HTMLImageLoader;
 class HTMLOptionElement;
-class Icon;
 class InputType;
 class InputTypeView;
 class KURL;
 class ListAttributeTargetObserver;
+class RadioButtonGroupScope;
 struct DateTimeChooserParameters;
 
 class HTMLInputElement : public HTMLTextFormControlElement {
@@ -52,18 +51,18 @@
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitspeechchange);
 
-    virtual bool shouldAutocomplete() const;
+    virtual bool shouldAutocomplete() const OVERRIDE FINAL;
 
     // For ValidityState
-    virtual bool hasBadInput() const OVERRIDE;
-    virtual bool patternMismatch() const OVERRIDE;
-    virtual bool rangeUnderflow() const OVERRIDE;
-    virtual bool rangeOverflow() const;
-    virtual bool stepMismatch() const OVERRIDE;
-    virtual bool tooLong() const OVERRIDE;
-    virtual bool typeMismatch() const OVERRIDE;
-    virtual bool valueMissing() const OVERRIDE;
-    virtual String validationMessage() const OVERRIDE;
+    virtual bool hasBadInput() const OVERRIDE FINAL;
+    virtual bool patternMismatch() const OVERRIDE FINAL;
+    virtual bool rangeUnderflow() const OVERRIDE FINAL;
+    virtual bool rangeOverflow() const OVERRIDE FINAL;
+    virtual bool stepMismatch() const OVERRIDE FINAL;
+    virtual bool tooLong() const OVERRIDE FINAL;
+    virtual bool typeMismatch() const OVERRIDE FINAL;
+    virtual bool valueMissing() const OVERRIDE FINAL;
+    virtual String validationMessage() const OVERRIDE FINAL;
 
     // Returns the minimum value for type=date, number, or range.  Don't call this for other types.
     double minimum() const;
@@ -94,7 +93,6 @@
     bool isPasswordField() const;
     bool isCheckbox() const;
     bool isRangeControl() const;
-    bool isColorControl() const;
 
     // FIXME: It's highly likely that any call site calling this function should instead
     // be using a different one. Many input elements behave like text fields, and in addition
@@ -106,7 +104,6 @@
     bool isFileUpload() const;
     bool isImageButton() const;
     bool isNumberField() const;
-    bool isSubmitButton() const;
     bool isTelephoneField() const;
     bool isURLField() const;
     bool isDateField() const;
@@ -136,7 +133,7 @@
 
     void setType(const AtomicString&);
 
-    String value() const;
+    virtual String value() const OVERRIDE;
     void setValue(const String&, ExceptionState&, TextFieldEventBehavior = DispatchNoEvent);
     void setValue(const String&, TextFieldEventBehavior = DispatchNoEvent);
     void setValueForUser(const String&);
@@ -149,9 +146,6 @@
 
     String localizeValue(const String&) const;
 
-    // The value which is drawn by a renderer.
-    String visibleValue() const;
-
     const String& suggestedValue() const;
     void setSuggestedValue(const String&);
 
@@ -176,15 +170,15 @@
     void setSelectionRangeForBinding(int start, int end, ExceptionState&);
     void setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionState&);
 
-    virtual bool rendererIsNeeded(const RenderStyle&);
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE FINAL;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual void detach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
 
     // FIXME: For isActivatedSubmit and setActivatedSubmit, we should use the NVI-idiom here by making
     // it private virtual in all classes and expose a public method in HTMLFormControlElement to call
     // the private virtual method.
-    virtual bool isActivatedSubmit() const;
-    virtual void setActivatedSubmit(bool flag);
+    virtual bool isActivatedSubmit() const OVERRIDE FINAL;
+    virtual void setActivatedSubmit(bool flag) OVERRIDE FINAL;
 
     String altText() const;
 
@@ -195,7 +189,6 @@
 
     Vector<String> acceptMIMETypes();
     Vector<String> acceptFileExtensions();
-    const AtomicString& accept() const;
     const AtomicString& alt() const;
 
     void setSize(unsigned);
@@ -203,7 +196,7 @@
 
     KURL src() const;
 
-    virtual int maxLength() const;
+    int maxLength() const;
     void setMaxLength(int, ExceptionState&);
 
     bool multiple() const;
@@ -216,7 +209,6 @@
 
     String droppedFileSystemId();
 
-    Icon* icon() const;
     // These functions are used for rendering the input active during a
     // drag-and-drop operation.
     bool canReceiveDroppedFiles() const;
@@ -230,6 +222,7 @@
 
     HTMLElement* list() const;
     HTMLDataListElement* dataList() const;
+    bool hasValidDataListOptions() const;
     void listAttributeTargetChanged();
 
     HTMLInputElement* checkedRadioButtonForGroup() const;
@@ -257,20 +250,20 @@
     void setHeight(unsigned);
     void setWidth(unsigned);
 
-    virtual void blur() OVERRIDE;
+    virtual void blur() OVERRIDE FINAL;
     void defaultBlur();
 
-    virtual const AtomicString& name() const OVERRIDE;
+    virtual const AtomicString& name() const OVERRIDE FINAL;
 
     void beginEditing();
     void endEditing();
 
     static Vector<FileChooserFileInfo> filesFromFileInputFormControlState(const FormControlState&);
 
-    virtual bool matchesReadOnlyPseudoClass() const OVERRIDE;
-    virtual bool matchesReadWritePseudoClass() const OVERRIDE;
-    virtual void setRangeText(const String& replacement, ExceptionState&) OVERRIDE;
-    virtual void setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState&) OVERRIDE;
+    virtual bool matchesReadOnlyPseudoClass() const OVERRIDE FINAL;
+    virtual bool matchesReadWritePseudoClass() const OVERRIDE FINAL;
+    virtual void setRangeText(const String& replacement, ExceptionState&) OVERRIDE FINAL;
+    virtual void setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState&) OVERRIDE FINAL;
 
     bool hasImageLoader() const { return m_imageLoader; }
     HTMLImageLoader* imageLoader();
@@ -279,99 +272,99 @@
 
     bool supportsInputModeAttribute() const;
 
+    void setShouldRevealPassword(bool value);
+    bool shouldRevealPassword() const { return m_shouldRevealPassword; }
+
 protected:
     HTMLInputElement(Document&, HTMLFormElement*, bool createdByParser);
 
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
 
 private:
     enum AutoCompleteSetting { Uninitialized, On, Off };
 
-    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
-    virtual void didAddShadowRoot(ShadowRoot&) OVERRIDE;
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE FINAL;
+    virtual void didAddShadowRoot(ShadowRoot&) OVERRIDE FINAL;
 
-    virtual void willChangeForm() OVERRIDE;
-    virtual void didChangeForm() OVERRIDE;
+    virtual void willChangeForm() OVERRIDE FINAL;
+    virtual void didChangeForm() OVERRIDE FINAL;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
+    virtual void removedFrom(ContainerNode*) OVERRIDE FINAL;
+    virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE FINAL;
+    virtual void removeAllEventListeners() OVERRIDE FINAL;
 
-    virtual bool hasCustomFocusLogic() const OVERRIDE;
-    virtual bool isKeyboardFocusable() const OVERRIDE;
-    virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
-    virtual bool isEnumeratable() const;
-    virtual bool isInteractiveContent() const OVERRIDE;
-    virtual bool supportLabels() const OVERRIDE;
-    virtual void updateFocusAppearance(bool restorePreviousSelection);
-    virtual bool shouldUseInputMethod();
+    virtual bool hasCustomFocusLogic() const OVERRIDE FINAL;
+    virtual bool isKeyboardFocusable() const OVERRIDE FINAL;
+    virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE FINAL;
+    virtual bool isEnumeratable() const OVERRIDE FINAL;
+    virtual bool isInteractiveContent() const OVERRIDE FINAL;
+    virtual bool supportLabels() const OVERRIDE FINAL;
+    virtual void updateFocusAppearance(bool restorePreviousSelection) OVERRIDE FINAL;
+    virtual bool shouldUseInputMethod() OVERRIDE FINAL;
 
-    virtual bool isTextFormControl() const { return isTextField(); }
+    virtual bool isTextFormControl() const OVERRIDE FINAL { return isTextField(); }
 
-    virtual bool canTriggerImplicitSubmission() const { return isTextField(); }
+    virtual bool canTriggerImplicitSubmission() const OVERRIDE FINAL { return isTextField(); }
 
-    virtual const AtomicString& formControlType() const;
+    virtual const AtomicString& formControlType() const OVERRIDE FINAL;
 
-    virtual bool shouldSaveAndRestoreFormControlState() const OVERRIDE;
-    virtual FormControlState saveFormControlState() const OVERRIDE;
-    virtual void restoreFormControlState(const FormControlState&) OVERRIDE;
+    virtual bool shouldSaveAndRestoreFormControlState() const OVERRIDE FINAL;
+    virtual FormControlState saveFormControlState() const OVERRIDE FINAL;
+    virtual void restoreFormControlState(const FormControlState&) OVERRIDE FINAL;
 
-    virtual bool canStartSelection() const;
+    virtual bool canStartSelection() const OVERRIDE FINAL;
 
-    virtual void accessKeyAction(bool sendMouseEvents);
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE FINAL;
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
-    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
-    virtual void finishParsingChildren();
+    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE FINAL;
+    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE FINAL;
+    virtual void finishParsingChildren() OVERRIDE FINAL;
 
-    virtual void copyNonAttributePropertiesFromElement(const Element&);
+    virtual void copyNonAttributePropertiesFromElement(const Element&) OVERRIDE FINAL;
 
-    virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
+    virtual void attach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
 
-    virtual bool appendFormData(FormDataList&, bool) OVERRIDE;
-    virtual String resultForDialogSubmit() OVERRIDE;
+    virtual bool appendFormData(FormDataList&, bool) OVERRIDE FINAL;
+    virtual String resultForDialogSubmit() OVERRIDE FINAL;
 
-    virtual bool canBeSuccessfulSubmitButton() const OVERRIDE;
+    virtual bool canBeSuccessfulSubmitButton() const OVERRIDE FINAL;
 
-    virtual void resetImpl() OVERRIDE;
+    virtual void resetImpl() OVERRIDE FINAL;
+    virtual bool supportsAutofocus() const OVERRIDE FINAL;
 
-    virtual void* preDispatchEventHandler(Event*);
-    virtual void postDispatchEventHandler(Event*, void* dataFromPreDispatch);
+    virtual void* preDispatchEventHandler(Event*) OVERRIDE FINAL;
+    virtual void postDispatchEventHandler(Event*, void* dataFromPreDispatch) OVERRIDE FINAL;
 
-    virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
-    virtual bool isInRange() const;
-    virtual bool isOutOfRange() const;
+    virtual bool isURLAttribute(const Attribute&) const OVERRIDE FINAL;
+    virtual bool isInRange() const OVERRIDE FINAL;
+    virtual bool isOutOfRange() const OVERRIDE FINAL;
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-
-    bool supportsMaxLength() const { return isTextType(); }
     bool isTextType() const;
     bool tooLong(const String&, NeedsToCheckDirtyFlag) const;
 
-    virtual bool supportsPlaceholder() const;
-    virtual void updatePlaceholderText();
-    virtual bool isEmptyValue() const OVERRIDE { return innerTextValue().isEmpty(); }
-    virtual bool isEmptySuggestedValue() const { return suggestedValue().isEmpty(); }
-    virtual void handleFocusEvent(Element* oldFocusedElement, FocusDirection) OVERRIDE;
-    virtual void handleBlurEvent();
+    virtual bool supportsPlaceholder() const OVERRIDE FINAL;
+    virtual void updatePlaceholderText() OVERRIDE FINAL;
+    virtual bool isEmptyValue() const OVERRIDE FINAL { return innerTextValue().isEmpty(); }
+    virtual bool isEmptySuggestedValue() const OVERRIDE FINAL { return suggestedValue().isEmpty(); }
+    virtual void handleFocusEvent(Element* oldFocusedElement, FocusType) OVERRIDE FINAL;
+    virtual void handleBlurEvent() OVERRIDE FINAL;
 
-    virtual bool isOptionalFormControl() const { return !isRequiredFormControl(); }
-    virtual bool isRequiredFormControl() const;
-    virtual bool recalcWillValidate() const;
-    virtual void requiredAttributeChanged() OVERRIDE;
+    virtual bool isOptionalFormControl() const OVERRIDE FINAL { return !isRequiredFormControl(); }
+    virtual bool isRequiredFormControl() const OVERRIDE FINAL;
+    virtual bool recalcWillValidate() const OVERRIDE FINAL;
+    virtual void requiredAttributeChanged() OVERRIDE FINAL;
 
     void updateType();
 
-    virtual void subtreeHasChanged();
+    virtual void subtreeHasChanged() OVERRIDE FINAL;
 
     void resetListAttributeTargetObserver();
     void parseMaxLengthAttribute(const AtomicString&);
     void updateValueIfNeeded();
 
-    bool canHaveSelection() const;
-
     // Returns null if this isn't associated with any radio button group.
-    CheckedRadioButtons* checkedRadioButtons() const;
+    RadioButtonGroupScope* radioButtonGroupScope() const;
     void addToRadioButtonGroup();
     void removeFromRadioButtonGroup();
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
@@ -396,6 +389,7 @@
     bool m_valueAttributeWasUpdatedAfterParsing : 1;
     bool m_canReceiveDroppedFiles : 1;
     bool m_hasTouchEventHandler : 1;
+    bool m_shouldRevealPassword : 1;
     RefPtr<InputType> m_inputType;
     RefPtr<InputTypeView> m_inputTypeView;
     // The ImageLoader must be owned by this element because the loader code assumes
diff --git a/Source/core/html/HTMLInputElement.idl b/Source/core/html/HTMLInputElement.idl
index 6c2fa4e..37a919d 100644
--- a/Source/core/html/HTMLInputElement.idl
+++ b/Source/core/html/HTMLInputElement.idl
@@ -41,7 +41,7 @@
     [CustomElementCallbacks] attribute unsigned long height;
     attribute boolean indeterminate;
     [RuntimeEnabled=InputModeAttribute, Reflect] attribute DOMString inputMode;
-    [RuntimeEnabled=DataListElement] readonly attribute HTMLElement list;
+    readonly attribute HTMLElement list;
     [Reflect] attribute DOMString max;
     [RaisesException=Setter, CustomElementCallbacks] attribute long maxLength;
     [Reflect] attribute DOMString min;
@@ -91,7 +91,7 @@
                            optional DOMString direction);
 
     // Non-standard attributes
-    [Reflect, RuntimeEnabled=DirectoryUpload] attribute boolean webkitdirectory;
+    [Reflect] attribute boolean webkitdirectory;
     [Reflect] attribute boolean incremental;
     [Conditional=INPUT_SPEECH, Reflect, RuntimeEnabled=SpeechInput] attribute boolean webkitSpeech;
     [Conditional=INPUT_SPEECH, Reflect, RuntimeEnabled=SpeechInput] attribute boolean webkitGrammar;
diff --git a/Source/core/html/HTMLKeygenElement.cpp b/Source/core/html/HTMLKeygenElement.cpp
index e6c80d0..0fb9dc1 100644
--- a/Source/core/html/HTMLKeygenElement.cpp
+++ b/Source/core/html/HTMLKeygenElement.cpp
@@ -58,7 +58,7 @@
 
     // Create a select element with one option element for each key size.
     RefPtr<HTMLSelectElement> select = HTMLSelectElement::create(document());
-    select->setPseudo(keygenSelectPseudoId);
+    select->setShadowPseudoId(keygenSelectPseudoId);
     for (size_t i = 0; i < keys.size(); ++i) {
         RefPtr<HTMLOptionElement> option = HTMLOptionElement::create(document());
         option->appendChild(Text::create(document(), keys[i]));
@@ -112,4 +112,9 @@
     return true;
 }
 
+bool HTMLKeygenElement::supportsAutofocus() const
+{
+    return true;
+}
+
 } // namespace
diff --git a/Source/core/html/HTMLKeygenElement.h b/Source/core/html/HTMLKeygenElement.h
index 292a78e..f561605 100644
--- a/Source/core/html/HTMLKeygenElement.h
+++ b/Source/core/html/HTMLKeygenElement.h
@@ -54,6 +54,7 @@
 
     virtual bool isEnumeratable() const OVERRIDE { return true; }
     virtual bool isInteractiveContent() const OVERRIDE;
+    virtual bool supportsAutofocus() const OVERRIDE;
     virtual bool supportLabels() const OVERRIDE { return true; }
 
     virtual void resetImpl() OVERRIDE;
diff --git a/Source/core/html/HTMLKeygenElement.idl b/Source/core/html/HTMLKeygenElement.idl
index 59af638..4484e2b 100644
--- a/Source/core/html/HTMLKeygenElement.idl
+++ b/Source/core/html/HTMLKeygenElement.idl
@@ -33,7 +33,7 @@
     [Reflect] attribute DOMString challenge;
     [Reflect] attribute boolean disabled;
     [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
-    [Reflect] attribute DOMString keytype;
+    [Reflect, ReflectOnly="rsa", ReflectMissing="rsa"] attribute DOMString keytype;
     [Reflect] attribute DOMString name;
 
     readonly attribute DOMString type;
diff --git a/Source/core/html/HTMLLIElement.cpp b/Source/core/html/HTMLLIElement.cpp
index d5a7896..aba2007 100644
--- a/Source/core/html/HTMLLIElement.cpp
+++ b/Source/core/html/HTMLLIElement.cpp
@@ -98,8 +98,10 @@
 
         // If we are not in a list, tell the renderer so it can position us inside.
         // We don't want to change our style to say "inside" since that would affect nested nodes.
-        if (!listNode)
+        if (!listNode) {
             listItemRenderer->setNotInList(true);
+            listItemRenderer->updateMarkerLocation();
+        }
 
         parseValue(fastGetAttribute(valueAttr));
     }
diff --git a/Source/core/html/HTMLLabelElement.cpp b/Source/core/html/HTMLLabelElement.cpp
index 67cf619..bb9bace 100644
--- a/Source/core/html/HTMLLabelElement.cpp
+++ b/Source/core/html/HTMLLabelElement.cpp
@@ -35,13 +35,13 @@
 
 using namespace HTMLNames;
 
-static bool supportsLabels(Element* element)
+static bool supportsLabels(const Element& element)
 {
-    if (!element || !element->isHTMLElement())
+    if (!element.isHTMLElement())
         return false;
-    if (!toHTMLElement(element)->isLabelable())
+    if (!toHTMLElement(element).isLabelable())
         return false;
-    return toLabelableElement(element)->supportLabels();
+    return toLabelableElement(element).supportLabels();
 }
 
 inline HTMLLabelElement::HTMLLabelElement(Document& document)
@@ -61,16 +61,15 @@
     return that->isContentEditable();
 }
 
-LabelableElement* HTMLLabelElement::control()
+LabelableElement* HTMLLabelElement::control() const
 {
     const AtomicString& controlId = getAttribute(forAttr);
     if (controlId.isNull()) {
         // Search the children and descendants of the label element for a form element.
         // per http://dev.w3.org/html5/spec/Overview.html#the-label-element
         // the form element must be "labelable form-associated element".
-        Element* element = this;
-        while ((element = ElementTraversal::next(*element, this))) {
-            if (!supportsLabels(element))
+        for (Element* element = ElementTraversal::next(*this, this); element; element = ElementTraversal::next(*element, this)) {
+            if (!supportsLabels(*element))
                 continue;
             return toLabelableElement(element);
         }
@@ -78,16 +77,16 @@
     }
 
     if (Element* element = treeScope().getElementById(controlId)) {
-        if (supportsLabels(element))
+        if (supportsLabels(*element))
             return toLabelableElement(element);
     }
 
     return 0;
 }
 
-HTMLFormElement* HTMLLabelElement::form() const
+HTMLFormElement* HTMLLabelElement::formOwner() const
 {
-    return FormAssociatedElement::findAssociatedForm(this, 0);
+    return FormAssociatedElement::findAssociatedForm(this);
 }
 
 void HTMLLabelElement::setActive(bool down)
@@ -152,7 +151,7 @@
 
         document().updateLayoutIgnorePendingStylesheets();
         if (element->isMouseFocusable())
-            element->focus(true, FocusDirectionMouse);
+            element->focus(true, FocusTypeMouse);
 
         // Click the corresponding control.
         element->dispatchSimulatedClick(evt);
@@ -173,13 +172,13 @@
     return HTMLElement::willRespondToMouseClickEvents();
 }
 
-void HTMLLabelElement::focus(bool, FocusDirection direction)
+void HTMLLabelElement::focus(bool, FocusType type)
 {
     // to match other browsers, always restore previous selection
     if (HTMLElement* element = control())
-        element->focus(true, direction);
+        element->focus(true, type);
     if (isFocusable())
-        HTMLElement::focus(true, direction);
+        HTMLElement::focus(true, type);
 }
 
 void HTMLLabelElement::accessKeyAction(bool sendMouseEvents)
diff --git a/Source/core/html/HTMLLabelElement.h b/Source/core/html/HTMLLabelElement.h
index 275b077..a735ce2 100644
--- a/Source/core/html/HTMLLabelElement.h
+++ b/Source/core/html/HTMLLabelElement.h
@@ -33,39 +33,30 @@
 public:
     static PassRefPtr<HTMLLabelElement> create(Document&);
 
-    LabelableElement* control();
-    HTMLFormElement* form() const;
+    LabelableElement* control() const;
 
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
+    virtual HTMLFormElement* formOwner() const OVERRIDE;
+
 private:
     explicit HTMLLabelElement(Document&);
     bool isInInteractiveContent(Node*) const;
 
     virtual bool rendererIsFocusable() const OVERRIDE;
     virtual bool isInteractiveContent() const OVERRIDE;
-    virtual void accessKeyAction(bool sendMouseEvents);
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
 
     // Overridden to update the hover/active state of the corresponding control.
     virtual void setActive(bool = true) OVERRIDE;
     virtual void setHovered(bool = true) OVERRIDE;
 
     // Overridden to either click() or focus() the corresponding control.
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
 
-    virtual void focus(bool restorePreviousSelection, FocusDirection) OVERRIDE;
+    virtual void focus(bool restorePreviousSelection, FocusType) OVERRIDE;
 };
 
-inline bool isHTMLLabelElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::labelTag);
-}
-
-inline bool isHTMLLabelElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::labelTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLLabelElement, hasTagName(HTMLNames::labelTag));
 
 } //namespace
diff --git a/Source/core/html/HTMLLabelElement.idl b/Source/core/html/HTMLLabelElement.idl
index d1e72b4..0f73764 100644
--- a/Source/core/html/HTMLLabelElement.idl
+++ b/Source/core/html/HTMLLabelElement.idl
@@ -19,7 +19,7 @@
  */
 
 interface HTMLLabelElement : HTMLElement {
-    readonly attribute HTMLFormElement form;
+    [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
     [Reflect=for] attribute DOMString htmlFor;
     readonly attribute HTMLElement control;
 };
diff --git a/Source/core/html/HTMLLegendElement.cpp b/Source/core/html/HTMLLegendElement.cpp
index f15aed3..20a6e8f 100644
--- a/Source/core/html/HTMLLegendElement.cpp
+++ b/Source/core/html/HTMLLegendElement.cpp
@@ -66,14 +66,14 @@
     return 0;
 }
 
-void HTMLLegendElement::focus(bool, FocusDirection direction)
+void HTMLLegendElement::focus(bool, FocusType type)
 {
     if (isFocusable())
-        Element::focus(true, direction);
+        Element::focus(true, type);
 
     // To match other browsers' behavior, never restore previous selection.
     if (HTMLFormControlElement* control = associatedControl())
-        control->focus(false, direction);
+        control->focus(false, type);
 }
 
 void HTMLLegendElement::accessKeyAction(bool sendMouseEvents)
diff --git a/Source/core/html/HTMLLegendElement.h b/Source/core/html/HTMLLegendElement.h
index 74290a8..a2e8849 100644
--- a/Source/core/html/HTMLLegendElement.h
+++ b/Source/core/html/HTMLLegendElement.h
@@ -42,8 +42,8 @@
     // Control in the legend's fieldset that gets focus and access key.
     HTMLFormControlElement* associatedControl();
 
-    virtual void accessKeyAction(bool sendMouseEvents);
-    virtual void focus(bool restorePreviousSelection, FocusDirection) OVERRIDE;
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
+    virtual void focus(bool restorePreviousSelection, FocusType) OVERRIDE;
 };
 
 DEFINE_NODE_TYPE_CASTS(HTMLLegendElement, hasTagName(HTMLNames::legendTag));
diff --git a/Source/core/html/HTMLLinkElement.cpp b/Source/core/html/HTMLLinkElement.cpp
index 7290ad7..c34f02e 100644
--- a/Source/core/html/HTMLLinkElement.cpp
+++ b/Source/core/html/HTMLLinkElement.cpp
@@ -138,6 +138,11 @@
     return continueLoad;
 }
 
+bool HTMLLinkElement::loadLink(const String& type, const KURL& url)
+{
+    return m_linkLoader.loadLink(m_relAttribute, fastGetAttribute(HTMLNames::crossoriginAttr), type, url, document());
+}
+
 LinkResource* HTMLLinkElement::linkResourceToProcess()
 {
     bool visible = inDocument() && !m_isInShadowTree;
@@ -174,6 +179,14 @@
     return static_cast<LinkImport*>(m_link.get());
 }
 
+bool HTMLLinkElement::importOwnsLoader() const
+{
+    LinkImport* import = linkImport();
+    if (!import)
+        return false;
+    return import->ownsLoader();
+}
+
 Document* HTMLLinkElement::import() const
 {
     if (LinkImport* link = linkImport())
@@ -287,6 +300,11 @@
 {
     ASSERT_UNUSED(eventSender, eventSender == &linkLoadEventSender());
     ASSERT(m_link);
+    dispatchEventImmediately();
+}
+
+void HTMLLinkElement::dispatchEventImmediately()
+{
     if (m_link->hasLoaded())
         linkLoaded();
     else
@@ -319,11 +337,6 @@
     return getAttribute(relAttr);
 }
 
-String HTMLLinkElement::target() const
-{
-    return getAttribute(targetAttr);
-}
-
 const AtomicString& HTMLLinkElement::type() const
 {
     return getAttribute(typeAttr);
@@ -334,30 +347,11 @@
     return m_relAttribute.iconType();
 }
 
-String HTMLLinkElement::iconSizes() const
+const AtomicString& HTMLLinkElement::iconSizes() const
 {
     return m_sizes->toString();
 }
 
-void HTMLLinkElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLElement::addSubresourceAttributeURLs(urls);
-
-    // Favicons are handled by a special case in LegacyWebArchive::create()
-    if (m_relAttribute.iconType() != InvalidIcon)
-        return;
-
-    if (!m_relAttribute.isStyleSheet())
-        return;
-
-    // Append the URL of this link element.
-    addSubresourceURL(urls, href());
-
-    // Walk the URLs linked by the linked-to stylesheet.
-    if (CSSStyleSheet* styleSheet = const_cast<HTMLLinkElement*>(this)->sheet())
-        styleSheet->contents()->addSubresourceStyleURLs(urls);
-}
-
 DOMSettableTokenList* HTMLLinkElement::sizes() const
 {
     return m_sizes.get();
@@ -382,9 +376,6 @@
 {
     if (m_sheet)
         m_sheet->clearOwnerNode();
-
-    if (m_resource)
-        m_resource->removeClient(this);
 }
 
 Document& LinkStyle::document()
@@ -402,7 +393,7 @@
     // Completing the sheet load may cause scripts to execute.
     RefPtr<Node> protector(m_owner);
 
-    CSSParserContext parserContext(m_owner->document(), baseURL, charset);
+    CSSParserContext parserContext(m_owner->document(), 0, baseURL, charset);
 
     if (RefPtr<StyleSheetContents> restoredSheet = const_cast<CSSStyleSheetResource*>(cachedStyleSheet)->restoreParsedStyleSheet(parserContext)) {
         ASSERT(restoredSheet->isCacheable());
@@ -415,8 +406,7 @@
         m_sheet->setTitle(m_owner->title());
 
         m_loading = false;
-        sheetLoaded();
-        notifyLoadedSheetAndAllCriticalSubresources(false);
+        restoredSheet->checkLoaded();
         return;
     }
 
@@ -579,24 +569,25 @@
     if ((m_disabledState != Disabled) && m_owner->relAttribute().isStyleSheet()
         && shouldLoadResource() && builder.url().isValid()) {
 
-        if (m_resource) {
+        if (resource()) {
             removePendingSheet();
-            m_resource->removeClient(this);
-            m_resource = 0;
+            clearResource();
         }
 
         if (!m_owner->shouldLoadLink())
             return;
 
-        Frame* frame = loadingFrame();
         m_loading = true;
 
         bool mediaQueryMatches = true;
         if (!m_owner->media().isEmpty()) {
-            RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(document());
-            RefPtr<MediaQuerySet> media = MediaQuerySet::create(m_owner->media());
-            MediaQueryEvaluator evaluator(frame->view()->mediaType(), frame, documentStyle.get());
-            mediaQueryMatches = evaluator.eval(media.get());
+            Frame* frame = loadingFrame();
+            if (Document* document = loadingFrame()->document()) {
+                RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*document);
+                RefPtr<MediaQuerySet> media = MediaQuerySet::create(m_owner->media());
+                MediaQueryEvaluator evaluator(frame->view()->mediaType(), frame, documentStyle.get());
+                mediaQueryMatches = evaluator.eval(media.get());
+            }
         }
 
         // Don't hold up render tree construction and script execution on stylesheets
@@ -606,11 +597,14 @@
 
         // Load stylesheets that are not needed for the rendering immediately with low priority.
         FetchRequest request = builder.build(blocking);
-        m_resource = document().fetcher()->fetchCSSStyleSheet(request);
+        AtomicString crossOriginMode = m_owner->fastGetAttribute(HTMLNames::crossoriginAttr);
+        if (!crossOriginMode.isNull()) {
+            StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
+            request.setCrossOriginAccessControl(document().securityOrigin(), allowCredentials);
+        }
+        setResource(document().fetcher()->fetchCSSStyleSheet(request));
 
-        if (m_resource)
-            m_resource->addClient(this);
-        else {
+        if (!resource()) {
             // The request may have been denied if (for example) the stylesheet is local and the document is remote.
             m_loading = false;
             removePendingSheet();
diff --git a/Source/core/html/HTMLLinkElement.h b/Source/core/html/HTMLLinkElement.h
index 2cab7b5..f2285f8 100644
--- a/Source/core/html/HTMLLinkElement.h
+++ b/Source/core/html/HTMLLinkElement.h
@@ -27,7 +27,8 @@
 #include "core/css/CSSStyleSheet.h"
 #include "core/dom/DOMSettableTokenList.h"
 #include "core/dom/IconURL.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
+#include "core/fetch/StyleSheetResource.h"
 #include "core/fetch/StyleSheetResourceClient.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/LinkRelAttribute.h"
@@ -54,7 +55,7 @@
 // changing @rel makes it harder to move such a design so we are
 // sticking current way so far.
 //
-class LinkStyle FINAL : public LinkResource, StyleSheetResourceClient {
+class LinkStyle FINAL : public LinkResource, ResourceOwner<StyleSheetResource> {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassOwnPtr<LinkStyle> create(HTMLLinkElement* owner);
@@ -83,8 +84,8 @@
     CSSStyleSheet* sheet() const { return m_sheet.get(); }
 
 private:
-    // From ResourceClient
-    virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*);
+    // From StyleSheetResourceClient
+    virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*) OVERRIDE;
 
     enum DisabledState {
         Unset,
@@ -108,7 +109,6 @@
     void removePendingSheet(RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
     Document& document();
 
-    ResourcePtr<CSSStyleSheetResource> m_resource;
     RefPtr<CSSStyleSheet> m_sheet;
     DisabledState m_disabledState;
     PendingSheetType m_pendingSheetType;
@@ -129,35 +129,37 @@
     String typeValue() const { return m_type; }
     const LinkRelAttribute& relAttribute() const { return m_relAttribute; }
 
-    virtual String target() const;
-
     const AtomicString& type() const;
 
     IconType iconType() const;
 
     // the icon size string as parsed from the HTML attribute
-    String iconSizes() const;
+    const AtomicString& iconSizes() const;
 
     CSSStyleSheet* sheet() const { return linkStyle() ? linkStyle()->sheet() : 0; }
     Document* import() const;
 
     bool styleSheetIsLoading() const;
 
+    bool isImport() const { return linkImport(); }
+    bool importOwnsLoader() const;
     bool isDisabled() const { return linkStyle() && linkStyle()->isDisabled(); }
     bool isEnabledViaScript() const { return linkStyle() && linkStyle()->isEnabledViaScript(); }
     DOMSettableTokenList* sizes() const;
 
     void dispatchPendingEvent(LinkEventSender*);
     void scheduleEvent();
+    void dispatchEventImmediately();
     static void dispatchPendingLoadEvents();
 
     // From LinkLoaderClient
     virtual bool shouldLoadLink() OVERRIDE;
 
     // For LinkStyle
-    bool loadLink(const String& type, const KURL& url) { return m_linkLoader.loadLink(m_relAttribute, type, url, document()); }
+    bool loadLink(const String& type, const KURL&);
     bool isAlternate() const { return linkStyle()->isUnset() && m_relAttribute.isAlternate(); }
     bool shouldProcessStyle() { return linkResourceToProcess() && linkStyle(); }
+    bool isCreatedByParser() const { return m_createdByParser; }
 
 private:
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -176,8 +178,7 @@
     virtual bool sheetLoaded() OVERRIDE;
     virtual void notifyLoadedSheetAndAllCriticalSubresources(bool errorOccurred) OVERRIDE;
     virtual void startLoadingDynamicSheet() OVERRIDE;
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const OVERRIDE;
-    virtual void finishParsingChildren();
+    virtual void finishParsingChildren() OVERRIDE;
 
     // From LinkLoaderClient
     virtual void linkLoaded() OVERRIDE;
diff --git a/Source/core/html/HTMLLinkElement.idl b/Source/core/html/HTMLLinkElement.idl
index 73c2426..92e5d19 100644
--- a/Source/core/html/HTMLLinkElement.idl
+++ b/Source/core/html/HTMLLinkElement.idl
@@ -23,6 +23,7 @@
     [Reflect] attribute boolean disabled;
     [Reflect] attribute DOMString charset;
     [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString href;
+    [Reflect, ReflectOnly="anonymous"|"use-credentials", ReflectEmpty="anonymous", ReflectInvalid="anonymous"] attribute DOMString crossOrigin;
     [Reflect] attribute DOMString hreflang;
     [Reflect] attribute DOMString media;
     [Reflect] attribute DOMString rel;
diff --git a/Source/core/html/HTMLMapElement.cpp b/Source/core/html/HTMLMapElement.cpp
index d1f055a..00f7032 100644
--- a/Source/core/html/HTMLMapElement.cpp
+++ b/Source/core/html/HTMLMapElement.cpp
@@ -56,7 +56,7 @@
     HTMLAreaElement* defaultArea = 0;
     Element* element = this;
     while ((element = ElementTraversal::next(*element, this))) {
-        if (isHTMLAreaElement(element)) {
+        if (element->hasTagName(areaTag)) {
             HTMLAreaElement* areaElt = toHTMLAreaElement(element);
             if (areaElt->isDefault()) {
                 if (!defaultArea)
@@ -76,7 +76,7 @@
 HTMLImageElement* HTMLMapElement::imageElement()
 {
     RefPtr<HTMLCollection> images = document().images();
-    for (unsigned i = 0; Node* curr = images->item(i); i++) {
+    for (unsigned i = 0; Element* curr = images->item(i); i++) {
         if (!curr->hasTagName(imgTag))
             continue;
 
@@ -108,7 +108,7 @@
         String mapName = value;
         if (mapName[0] == '#')
             mapName = mapName.substring(1);
-        m_name = document().isHTMLDocument() ? mapName.lower() : mapName;
+        m_name = AtomicString(document().isHTMLDocument() ? mapName.lower() : mapName);
         if (inDocument())
             treeScope().addImageMap(this);
 
diff --git a/Source/core/html/HTMLMarqueeElement.cpp b/Source/core/html/HTMLMarqueeElement.cpp
index 8628e6a..882cb06 100644
--- a/Source/core/html/HTMLMarqueeElement.cpp
+++ b/Source/core/html/HTMLMarqueeElement.cpp
@@ -189,4 +189,16 @@
     return new RenderMarquee(this);
 }
 
+void HTMLMarqueeElement::timerFired(Timer<HTMLMarqueeElement>*)
+{
+    if (!renderer())
+        return;
+
+    document().updateLayout();
+
+    // The updateLayout() could have destroyed renderer(), so this re-check is very important.
+    if (renderer())
+        toRenderMarquee(renderer())->timerFired();
+}
+
 } // namespace WebCore
diff --git a/Source/core/html/HTMLMarqueeElement.h b/Source/core/html/HTMLMarqueeElement.h
index 0a58595..4c7b14a 100644
--- a/Source/core/html/HTMLMarqueeElement.h
+++ b/Source/core/html/HTMLMarqueeElement.h
@@ -40,7 +40,7 @@
     // DOM Functions
 
     void start();
-    void stop();
+    virtual void stop() OVERRIDE;
 
     int scrollAmount() const;
     void setScrollAmount(int, ExceptionState&);
@@ -51,6 +51,8 @@
     int loop() const;
     void setLoop(int, ExceptionState&);
 
+    void timerFired(Timer<HTMLMarqueeElement>*);
+
 private:
     explicit HTMLMarqueeElement(Document&);
 
@@ -58,10 +60,10 @@
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 
     // ActiveDOMObject
-    virtual void suspend();
-    virtual void resume();
+    virtual void suspend() OVERRIDE;
+    virtual void resume() OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE FINAL;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     RenderMarquee* renderMarquee() const;
 };
diff --git a/Source/core/html/HTMLMediaElement.cpp b/Source/core/html/HTMLMediaElement.cpp
index aab7c24..c1c66cc 100644
--- a/Source/core/html/HTMLMediaElement.cpp
+++ b/Source/core/html/HTMLMediaElement.cpp
@@ -34,13 +34,16 @@
 #include "bindings/v8/ScriptController.h"
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/css/MediaList.h"
-#include "core/css/MediaQueryEvaluator.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/FullscreenElementStack.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/events/Event.h"
 #include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "core/frame/UseCounter.h"
 #include "core/html/HTMLMediaSource.h"
 #include "core/html/HTMLSourceElement.h"
 #include "core/html/HTMLTrackElement.h"
@@ -55,14 +58,12 @@
 #include "core/html/track/TextTrackCueList.h"
 #include "core/html/track/TextTrackList.h"
 #include "core/loader/FrameLoader.h"
-#include "core/frame/ContentSecurityPolicy.h"
-#include "core/frame/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderVideo.h"
 #include "core/rendering/RenderView.h"
-#include "modules/mediastream/MediaStreamRegistry.h"
+// FIXME: Remove dependency on modules/encryptedmedia (http://crbug.com/242754).
+#include "modules/encryptedmedia/MediaKeyNeededEvent.h"
+#include "modules/encryptedmedia/MediaKeys.h"
 #include "platform/ContentType.h"
 #include "platform/Language.h"
 #include "platform/Logging.h"
@@ -73,6 +74,7 @@
 #include "platform/graphics/GraphicsLayer.h"
 #include "platform/weborigin/SecurityOrigin.h"
 #include "public/platform/Platform.h"
+#include "public/platform/WebContentDecryptionModule.h"
 #include "public/platform/WebInbandTextTrack.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/MathExtras.h"
@@ -85,12 +87,6 @@
 #include "modules/webaudio/MediaElementAudioSourceNode.h"
 #endif
 
-#if ENABLE(ENCRYPTED_MEDIA_V2)
-// FIXME: Remove dependency on modules/encryptedmedia (http://crbug.com/242754).
-#include "modules/encryptedmedia/MediaKeyNeededEvent.h"
-#include "modules/encryptedmedia/MediaKeys.h"
-#endif
-
 using namespace std;
 using blink::WebInbandTextTrack;
 using blink::WebMimeRegistry;
@@ -244,7 +240,20 @@
     return blink::Platform::current()->mimeRegistry()->supportsMediaMIMEType(type, typeCodecs, system);
 }
 
-HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& document, bool createdByParser)
+URLRegistry* HTMLMediaElement::s_mediaStreamRegistry = 0;
+
+void HTMLMediaElement::setMediaStreamRegistry(URLRegistry* registry)
+{
+    ASSERT(!s_mediaStreamRegistry);
+    s_mediaStreamRegistry = registry;
+}
+
+bool HTMLMediaElement::isMediaStreamURL(const String& url)
+{
+    return s_mediaStreamRegistry ? s_mediaStreamRegistry->contains(url) : false;
+}
+
+HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , ActiveDOMObject(&document)
     , m_loadTimer(this, &HTMLMediaElement::loadTimerFired)
@@ -266,7 +275,7 @@
     , m_loadState(WaitingForSource)
     , m_webLayer(0)
     , m_opaque(false)
-    , m_restrictions(RequirePageConsentToLoadMediaRestriction)
+    , m_restrictions(NoRestrictions)
     , m_preload(MediaPlayer::Auto)
     , m_displayMode(Unknown)
     , m_cachedTime(MediaPlayer::invalidTime())
@@ -287,10 +296,8 @@
     , m_sentEndEvent(false)
     , m_pausedInternal(false)
     , m_closedCaptionsVisible(false)
-    , m_loadInitiatedByUserGesture(false)
     , m_completelyLoaded(false)
     , m_havePreparedToPlay(false)
-    , m_parsingInProgress(createdByParser)
     , m_tracksAreReady(true)
     , m_haveVisibleTextTrack(false)
     , m_processingPreferenceChange(false)
@@ -300,6 +307,7 @@
 #if ENABLE(WEB_AUDIO)
     , m_audioSourceNode(0)
 #endif
+    , m_emeMode(EmeModeNotSelected)
 {
     ASSERT(RuntimeEnabledFeatures::mediaEnabled());
 
@@ -307,18 +315,17 @@
     ScriptWrappable::init(this);
 
     if (document.settings()) {
-        if (document.settings()->mediaPlaybackRequiresUserGesture()) {
-            addBehaviorRestriction(RequireUserGestureForRateChangeRestriction);
-            addBehaviorRestriction(RequireUserGestureForLoadRestriction);
-        }
-        if (document.settings()->mediaFullscreenRequiresUserGesture()) {
+        if (document.settings()->mediaPlaybackRequiresUserGesture())
+            addBehaviorRestriction(RequireUserGestureForPlayRestriction);
+        if (document.settings()->mediaFullscreenRequiresUserGesture())
             addBehaviorRestriction(RequireUserGestureForFullscreenRestriction);
-        }
     }
 
+    // We must always have a ShadowRoot so children like <source> will not render
+    // as they never have an insertion point.
+    ensureUserAgentShadowRoot();
     setHasCustomStyleCallbacks();
     addElementToDocumentMap(this, &document);
-
 }
 
 HTMLMediaElement::~HTMLMediaElement()
@@ -342,9 +349,7 @@
 
     closeMediaSource();
 
-#if ENABLE(ENCRYPTED_MEDIA_V2)
-    setMediaKeys(0);
-#endif
+    setMediaKeysInternal(0);
 
     removeElementFromDocumentMap(this, &document());
 
@@ -455,7 +460,6 @@
 void HTMLMediaElement::finishParsingChildren()
 {
     HTMLElement::finishParsingChildren();
-    m_parsingInProgress = false;
 
     if (!RuntimeEnabledFeatures::videoTrackEnabled())
         return;
@@ -478,11 +482,6 @@
     return new RenderMedia(this);
 }
 
-bool HTMLMediaElement::childShouldCreateRenderer(const Node& child) const
-{
-    return hasMediaControls() && HTMLElement::childShouldCreateRenderer(child);
-}
-
 Node::InsertionNotificationRequest HTMLMediaElement::insertedInto(ContainerNode* insertionPoint)
 {
     WTF_LOG(Media, "HTMLMediaElement::insertedInto");
@@ -553,7 +552,7 @@
 void HTMLMediaElement::scheduleEvent(const AtomicString& eventName)
 {
 #if LOG_MEDIA_EVENTS
-    WTF_LOG(Media, "HTMLMediaElement::scheduleEvent - scheduling '%s'", eventName.string().ascii().data());
+    WTF_LOG(Media, "HTMLMediaElement::scheduleEvent - scheduling '%s'", eventName.ascii().data());
 #endif
     m_asyncEventQueue->enqueueEvent(Event::createCancelable(eventName));
 }
@@ -590,8 +589,11 @@
     return m_networkState;
 }
 
-String HTMLMediaElement::canPlayType(const String& mimeType, const String& keySystem, const KURL& url) const
+String HTMLMediaElement::canPlayType(const String& mimeType, const String& keySystem) const
 {
+    if (!keySystem.isNull())
+        UseCounter::count(document(), UseCounter::CanPlayTypeKeySystem);
+
     WebMimeRegistry::SupportsType support = supportsType(ContentType(mimeType), keySystem);
     String canPlay;
 
@@ -609,7 +611,7 @@
             break;
     }
 
-    WTF_LOG(Media, "HTMLMediaElement::canPlayType(%s, %s, %s) -> %s", mimeType.utf8().data(), keySystem.utf8().data(), url.elidedString().utf8().data(), canPlay.utf8().data());
+    WTF_LOG(Media, "HTMLMediaElement::canPlayType(%s, %s) -> %s", mimeType.utf8().data(), keySystem.utf8().data(), canPlay.utf8().data());
 
     return canPlay;
 }
@@ -623,12 +625,9 @@
     if (document().settings() && !document().settings()->mediaEnabled())
         return;
 
-    if (userGestureRequiredForLoad() && !UserGestureIndicator::processingUserGesture())
-        return;
-
-    m_loadInitiatedByUserGesture = UserGestureIndicator::processingUserGesture();
-    if (m_loadInitiatedByUserGesture)
+    if (UserGestureIndicator::processingUserGesture())
         removeBehaviorsRestrictionsAfterFirstUserGesture();
+
     prepareForLoad();
     loadInternal();
     prepareToPlay();
@@ -716,11 +715,6 @@
     // trigger the event.
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
 
-    // Once the page has allowed an element to load media, it is free to load at will. This allows a
-    // playlist that starts in a foreground tab to continue automatically if the tab is subsequently
-    // put in the the background.
-    removeBehaviorRestriction(RequirePageConsentToLoadMediaRestriction);
-
     // HTMLMediaElement::textTracksAreReady will need "... the text tracks whose mode was not in the
     // disabled state when the element's resource selection algorithm last started".
     if (RuntimeEnabledFeatures::videoTrackEnabled()) {
@@ -848,8 +842,7 @@
 
     WTF_LOG(Media, "HTMLMediaElement::loadResource - m_currentSrc -> %s", urlForLoggingMedia(m_currentSrc).utf8().data());
 
-    if (MediaStreamRegistry::registry().lookupMediaStreamDescriptor(url.string()))
-      removeBehaviorRestriction(RequireUserGestureForRateChangeRestriction);
+    blink::WebMediaPlayer::LoadType loadType = blink::WebMediaPlayer::LoadTypeURL;
 
     startProgressEventTimer();
 
@@ -865,20 +858,30 @@
 
     ASSERT(!m_mediaSource);
 
-    if (url.protocolIs(mediaSourceBlobProtocol))
-        m_mediaSource = HTMLMediaSource::lookup(url.string());
+    bool attemptLoad = true;
 
-    if (m_mediaSource) {
-        if (m_mediaSource->attachToElement(this)) {
-            m_player->load(url, m_mediaSource);
+    if (url.protocolIs(mediaSourceBlobProtocol)) {
+        if (isMediaStreamURL(url.string())) {
+            loadType = blink::WebMediaPlayer::LoadTypeMediaStream;
+            removeBehaviorRestriction(RequireUserGestureForPlayRestriction);
         } else {
-            // Forget our reference to the MediaSource, so we leave it alone
-            // while processing remainder of load failure.
-            m_mediaSource = 0;
-            mediaLoadingFailed(MediaPlayer::FormatError);
+            m_mediaSource = HTMLMediaSource::lookup(url.string());
+
+            if (m_mediaSource) {
+                loadType = blink::WebMediaPlayer::LoadTypeMediaSource;
+
+                if (!m_mediaSource->attachToElement(this)) {
+                    // Forget our reference to the MediaSource, so we leave it alone
+                    // while processing remainder of load failure.
+                    m_mediaSource = 0;
+                    attemptLoad = false;
+                }
+            }
         }
-    } else if (canLoadURL(url, contentType, keySystem)) {
-        m_player->load(url);
+    }
+
+    if (attemptLoad && canLoadURL(url, contentType, keySystem)) {
+        m_player->load(loadType, url);
     } else {
         mediaLoadingFailed(MediaPlayer::FormatError);
     }
@@ -928,8 +931,6 @@
     if (ignoreTrackDisplayUpdateRequests())
         return;
 
-    WTF_LOG(Media, "HTMLMediaElement::updateActiveTextTrackCues");
-
     // 1 - Let current cues be a list of cues, initialized to contain all the
     // cues of all the hidden, showing, or showing by default text tracks of the
     // media element (not the disabled ones) whose start times are less than or
@@ -1464,10 +1465,8 @@
         noneSupported();
 
     updateDisplayState();
-    if (hasMediaControls()) {
+    if (hasMediaControls())
         mediaControls()->reset();
-        mediaControls()->reportedError();
-    }
 }
 
 void HTMLMediaElement::setNetworkState(MediaPlayer::NetworkState state)
@@ -1505,9 +1504,6 @@
             changeNetworkStateFromLoadingToIdle();
         m_completelyLoaded = true;
     }
-
-    if (hasMediaControls())
-        mediaControls()->updateStatusDisplay();
 }
 
 void HTMLMediaElement::changeNetworkStateFromLoadingToIdle()
@@ -1583,9 +1579,11 @@
     if (m_readyState >= HAVE_METADATA && oldState < HAVE_METADATA) {
         prepareMediaFragmentURI();
         scheduleEvent(EventTypeNames::durationchange);
+        if (isVideo())
+            scheduleEvent(EventTypeNames::resize);
         scheduleEvent(EventTypeNames::loadedmetadata);
         if (hasMediaControls())
-            mediaControls()->loadedMetadata();
+            mediaControls()->reset();
         if (renderer())
             renderer()->updateFromElement();
     }
@@ -1617,7 +1615,7 @@
         if (isPotentiallyPlaying && oldState <= HAVE_CURRENT_DATA)
             scheduleEvent(EventTypeNames::playing);
 
-        if (m_autoplaying && m_paused && autoplay() && !document().isSandboxed(SandboxAutomaticFeatures) && !userGestureRequiredForRateChange()) {
+        if (m_autoplaying && m_paused && autoplay() && !document().isSandboxed(SandboxAutomaticFeatures) && !userGestureRequiredForPlay()) {
             m_paused = false;
             invalidateCachedTime();
             scheduleEvent(EventTypeNames::play);
@@ -1629,10 +1627,8 @@
 
     if (shouldUpdateDisplayState) {
         updateDisplayState();
-        if (hasMediaControls()) {
+        if (hasMediaControls())
             mediaControls()->refreshClosedCaptionsButtonVisibility();
-            mediaControls()->updateStatusDisplay();
-        }
     }
 
     updatePlayState();
@@ -1643,6 +1639,8 @@
 
 void HTMLMediaElement::mediaPlayerKeyAdded(const String& keySystem, const String& sessionId)
 {
+    WTF_LOG(Media, "HTMLMediaElement::mediaPlayerKeyAdded");
+
     MediaKeyEventInit initializer;
     initializer.keySystem = keySystem;
     initializer.sessionId = sessionId;
@@ -1656,6 +1654,8 @@
 
 void HTMLMediaElement::mediaPlayerKeyError(const String& keySystem, const String& sessionId, MediaPlayerClient::MediaKeyErrorCode errorCode, unsigned short systemCode)
 {
+    WTF_LOG(Media, "HTMLMediaElement::mediaPlayerKeyError: sessionID=%s, errorCode=%d, systemCode=%d", sessionId.utf8().data(), errorCode, systemCode);
+
     MediaKeyError::Code mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_UNKNOWN;
     switch (errorCode) {
     case MediaPlayerClient::UnknownError:
@@ -1693,6 +1693,8 @@
 
 void HTMLMediaElement::mediaPlayerKeyMessage(const String& keySystem, const String& sessionId, const unsigned char* message, unsigned messageLength, const KURL& defaultURL)
 {
+    WTF_LOG(Media, "HTMLMediaElement::mediaPlayerKeyMessage: sessionID=%s", sessionId.utf8().data());
+
     MediaKeyEventInit initializer;
     initializer.keySystem = keySystem;
     initializer.sessionId = sessionId;
@@ -1706,60 +1708,93 @@
     m_asyncEventQueue->enqueueEvent(event.release());
 }
 
-bool HTMLMediaElement::mediaPlayerKeyNeeded(const String& keySystem, const String& sessionId, const unsigned char* initData, unsigned initDataLength)
+// Create a MediaKeyNeededEvent for WD EME.
+static PassRefPtr<Event> createNeedKeyEvent(const String& contentType, const unsigned char* initData, unsigned initDataLength)
 {
-    if (!hasEventListeners(EventTypeNames::webkitneedkey)) {
-        m_error = MediaError::create(MediaError::MEDIA_ERR_ENCRYPTED);
-        scheduleEvent(EventTypeNames::error);
-        return false;
-    }
-
-    MediaKeyEventInit initializer;
-    initializer.keySystem = keySystem;
-    initializer.sessionId = sessionId;
+    MediaKeyNeededEventInit initializer;
+    initializer.contentType = contentType;
     initializer.initData = Uint8Array::create(initData, initDataLength);
     initializer.bubbles = false;
     initializer.cancelable = false;
 
-    RefPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitneedkey, initializer);
-    event->setTarget(this);
-    m_asyncEventQueue->enqueueEvent(event.release());
-    return true;
+    return MediaKeyNeededEvent::create(EventTypeNames::needkey, initializer);
 }
 
-#if ENABLE(ENCRYPTED_MEDIA_V2)
-bool HTMLMediaElement::mediaPlayerKeyNeeded(Uint8Array* initData)
+// Create a 'needkey' MediaKeyEvent for v0.1b EME.
+static PassRefPtr<Event> createWebkitNeedKeyEvent(const String& contentType, const unsigned char* initData, unsigned initDataLength)
 {
-    if (!hasEventListeners("webkitneedkey")) {
-        m_error = MediaError::create(MediaError::MEDIA_ERR_ENCRYPTED);
-        scheduleEvent(EventTypeNames::error);
-        return false;
+    MediaKeyEventInit webkitInitializer;
+    webkitInitializer.keySystem = String();
+    webkitInitializer.sessionId = String();
+    webkitInitializer.initData = Uint8Array::create(initData, initDataLength);
+    webkitInitializer.bubbles = false;
+    webkitInitializer.cancelable = false;
+
+    return MediaKeyEvent::create(EventTypeNames::webkitneedkey, webkitInitializer);
+}
+
+bool HTMLMediaElement::mediaPlayerKeyNeeded(const String& contentType, const unsigned char* initData, unsigned initDataLength)
+{
+    WTF_LOG(Media, "HTMLMediaElement::mediaPlayerKeyNeeded: contentType=%s", contentType.utf8().data());
+
+    if (RuntimeEnabledFeatures::encryptedMediaEnabled()) {
+        // Send event for WD EME.
+        RefPtr<Event> event = createNeedKeyEvent(contentType, initData, initDataLength);
+        event->setTarget(this);
+        m_asyncEventQueue->enqueueEvent(event.release());
     }
 
-    MediaKeyNeededEventInit initializer;
-    initializer.initData = initData;
-    initializer.bubbles = false;
-    initializer.cancelable = false;
-
-    RefPtr<Event> event = MediaKeyNeededEvent::create(EventTypeNames::webkitneedkey, initializer);
-    event->setTarget(this);
-    m_asyncEventQueue->enqueueEvent(event.release());
+    if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
+        // Send event for v0.1b EME.
+        RefPtr<Event> event = createWebkitNeedKeyEvent(contentType, initData, initDataLength);
+        event->setTarget(this);
+        m_asyncEventQueue->enqueueEvent(event.release());
+    }
 
     return true;
 }
 
-void HTMLMediaElement::setMediaKeys(MediaKeys* mediaKeys)
+bool HTMLMediaElement::setEmeMode(EmeMode emeMode, ExceptionState& exceptionState)
 {
+    if (m_emeMode != EmeModeNotSelected && m_emeMode != emeMode) {
+        exceptionState.throwDOMException(InvalidStateError, "Mixed use of EME prefixed and unprefixed API not allowed.");
+        return false;
+    }
+    m_emeMode = emeMode;
+    return true;
+}
+
+blink::WebContentDecryptionModule* HTMLMediaElement::contentDecryptionModule()
+{
+    return m_mediaKeys ? m_mediaKeys->contentDecryptionModule() : 0;
+}
+
+void HTMLMediaElement::setMediaKeysInternal(MediaKeys* mediaKeys)
+{
+    WTF_LOG(Media, "HTMLMediaElement::setMediaKeys");
     if (m_mediaKeys == mediaKeys)
         return;
 
+    ASSERT(m_emeMode = EmeModeUnprefixed);
+
     if (m_mediaKeys)
         m_mediaKeys->setMediaElement(0);
     m_mediaKeys = mediaKeys;
     if (m_mediaKeys)
         m_mediaKeys->setMediaElement(this);
+
+    // If a player is connected, tell it that the CDM has changed.
+    if (m_player)
+        m_player->setContentDecryptionModule(contentDecryptionModule());
 }
-#endif
+
+void HTMLMediaElement::setMediaKeys(MediaKeys* mediaKeys, ExceptionState& exceptionState)
+{
+    if (!setEmeMode(EmeModeUnprefixed, exceptionState))
+        return;
+
+    setMediaKeysInternal(mediaKeys);
+}
 
 void HTMLMediaElement::progressEventTimerFired(Timer<HTMLMediaElement>*)
 {
@@ -1815,7 +1850,7 @@
 
     // 1 - If the media element's readyState is HAVE_NOTHING, then raise an InvalidStateError exception.
     if (m_readyState == HAVE_NOTHING || !m_player) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "The element's readyState is HAVE_NOTHING.");
         return;
     }
 
@@ -1984,7 +2019,7 @@
 void HTMLMediaElement::setCurrentTime(double time, ExceptionState& exceptionState)
 {
     if (m_mediaController) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "No media controller is available.");
         return;
     }
     seek(time, exceptionState);
@@ -2086,7 +2121,7 @@
     return String();
 }
 
-void HTMLMediaElement::setPreload(const String& preload)
+void HTMLMediaElement::setPreload(const AtomicString& preload)
 {
     WTF_LOG(Media, "HTMLMediaElement::setPreload(%s)", preload.utf8().data());
     setAttribute(preloadAttr, preload);
@@ -2096,7 +2131,7 @@
 {
     WTF_LOG(Media, "HTMLMediaElement::play()");
 
-    if (userGestureRequiredForRateChange() && !UserGestureIndicator::processingUserGesture())
+    if (userGestureRequiredForPlay() && !UserGestureIndicator::processingUserGesture())
         return;
     if (UserGestureIndicator::processingUserGesture())
         removeBehaviorsRestrictionsAfterFirstUserGesture();
@@ -2138,18 +2173,6 @@
 {
     WTF_LOG(Media, "HTMLMediaElement::pause()");
 
-    if (userGestureRequiredForRateChange() && !UserGestureIndicator::processingUserGesture())
-        return;
-
-    pauseInternal();
-}
-
-
-void HTMLMediaElement::pauseInternal()
-{
-    WTF_LOG(Media, "HTMLMediaElement::pauseInternal");
-
-    // 4.8.10.9. Playing the media resource
     if (!m_player || m_networkState == NETWORK_EMPTY)
         scheduleDelayedAction(LoadMediaResource);
 
@@ -2175,13 +2198,18 @@
 
 void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState& exceptionState)
 {
+    WTF_LOG(Media, "HTMLMediaElement::webkitGenerateKeyRequest");
+
+    if (!setEmeMode(EmeModePrefixed, exceptionState))
+        return;
+
     if (keySystem.isEmpty()) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The key system provided is empty.");
         return;
     }
 
     if (!m_player) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "No player is available.");
         return;
     }
 
@@ -2203,23 +2231,28 @@
 
 void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState& exceptionState)
 {
+    WTF_LOG(Media, "HTMLMediaElement::webkitAddKey");
+
+    if (!setEmeMode(EmeModePrefixed, exceptionState))
+        return;
+
     if (keySystem.isEmpty()) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The key system provided is empty.");
         return;
     }
 
     if (!key) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The key provided is invalid.");
         return;
     }
 
     if (!key->length()) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The key provided is invalid.");
         return;
     }
 
     if (!m_player) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "No player is available.");
         return;
     }
 
@@ -2241,13 +2274,18 @@
 
 void HTMLMediaElement::webkitCancelKeyRequest(const String& keySystem, const String& sessionId, ExceptionState& exceptionState)
 {
+    WTF_LOG(Media, "HTMLMediaElement::webkitCancelKeyRequest");
+
+    if (!setEmeMode(EmeModePrefixed, exceptionState))
+        return;
+
     if (keySystem.isEmpty()) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The key system provided is empty.");
         return;
     }
 
     if (!m_player) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "No player is available.");
         return;
     }
 
@@ -2297,7 +2335,7 @@
     WTF_LOG(Media, "HTMLMediaElement::setVolume(%f)", vol);
 
     if (vol < 0.0f || vol > 1.0f) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexOutsideRange("volume", vol, 0.0f, ExceptionMessages::ExclusiveBound, 1.0f, ExceptionMessages::ExclusiveBound));
         return;
     }
 
@@ -2328,19 +2366,6 @@
     }
 }
 
-void HTMLMediaElement::togglePlayState()
-{
-    WTF_LOG(Media, "HTMLMediaElement::togglePlayState - canPlay() is %s", boolString(canPlay()));
-
-    // We can safely call the internal play/pause methods, which don't check restrictions, because
-    // this method is only called from the built-in media controller
-    if (canPlay()) {
-        updatePlaybackRate();
-        playInternal();
-    } else
-        pauseInternal();
-}
-
 void HTMLMediaElement::beginScrubbing()
 {
     WTF_LOG(Media, "HTMLMediaElement::beginScrubbing - paused() is %s", boolString(paused()));
@@ -2389,7 +2414,7 @@
         m_fragmentEndTime = MediaPlayer::invalidTime();
         if (!m_mediaController && !m_paused) {
             // changes paused to true and fires a simple event named pause at the media element.
-            pauseInternal();
+            pause();
         }
     }
 
@@ -2430,25 +2455,6 @@
     return paused() || ended() || m_readyState < HAVE_METADATA;
 }
 
-double HTMLMediaElement::percentLoaded() const
-{
-    if (!m_player)
-        return 0;
-    double duration = m_player->duration();
-
-    if (!duration || std::isinf(duration))
-        return 0;
-
-    double buffered = 0;
-    RefPtr<TimeRanges> timeRanges = m_player->buffered();
-    for (unsigned i = 0; i < timeRanges->length(); ++i) {
-        double start = timeRanges->start(i, IGNORE_EXCEPTION);
-        double end = timeRanges->end(i, IGNORE_EXCEPTION);
-        buffered += end - start;
-    }
-    return buffered / duration;
-}
-
 void HTMLMediaElement::mediaPlayerDidAddTrack(WebInbandTextTrack* webTrack)
 {
     if (!RuntimeEnabledFeatures::videoTrackEnabled())
@@ -2539,7 +2545,7 @@
     }
 }
 
-PassRefPtr<TextTrack> HTMLMediaElement::addTextTrack(const String& kind, const String& label, const String& language, ExceptionState& exceptionState)
+PassRefPtr<TextTrack> HTMLMediaElement::addTextTrack(const AtomicString& kind, const AtomicString& label, const AtomicString& language, ExceptionState& exceptionState)
 {
     ASSERT(RuntimeEnabledFeatures::videoTrackEnabled());
 
@@ -2548,7 +2554,7 @@
 
     // 1. If kind is not one of the following strings, then throw a SyntaxError exception and abort these steps
     if (!TextTrack::isValidKindKeyword(kind)) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The 'kind' provided ('" + kind + "') is invalid.");
         return 0;
     }
 
@@ -2604,7 +2610,7 @@
 
     // Do not schedule the track loading until parsing finishes so we don't start before all tracks
     // in the markup have been added.
-    if (!m_parsingInProgress)
+    if (isFinishedParsingChildren())
         scheduleDelayedAction(LoadTextTrackResource);
 
     if (hasMediaControls())
@@ -2650,7 +2656,7 @@
     if (track.language().isEmpty())
         return 0;
 
-    Vector<String> languages = userPreferredLanguages();
+    Vector<AtomicString> languages = userPreferredLanguages();
     size_t languageMatchIndex = indexOfBestMatchingLanguageInList(track.language(), languages);
     if (languageMatchIndex >= languages.size())
         return 0;
@@ -2684,8 +2690,7 @@
 
     WTF_LOG(Media, "HTMLMediaElement::configureTextTrackGroup(%d)", group.kind);
 
-    Page* page = document().page();
-    Settings* settings = page ? &page->settings() : 0;
+    Settings* settings = document().settings();
 
     // First, find the track in the group that should be enabled (if any).
     Vector<RefPtr<TextTrack> > currentlyEnabledTracks;
@@ -2868,7 +2873,6 @@
         if (node->parentNode() != this)
             continue;
 
-        UseCounter::count(document(), UseCounter::SourceElementCandidate);
         source = toHTMLSourceElement(node);
 
         // If candidate does not have a src attribute, or if its src attribute's value is the empty string ... jump down to the failed step below
@@ -2880,19 +2884,6 @@
         if (mediaURL.isEmpty())
             goto check_again;
 
-        if (source->fastHasAttribute(mediaAttr)) {
-            MediaQueryEvaluator screenEval("screen", document().frame(), renderer() ? renderer()->style() : 0);
-            RefPtr<MediaQuerySet> media = MediaQuerySet::create(source->media());
-#if !LOG_DISABLED
-            if (shouldLog)
-                WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'media' is %s", source->media().string().utf8().data());
-#endif
-            if (!screenEval.eval(media.get())) {
-                UseCounter::count(document(), UseCounter::SourceElementNonMatchingMedia);
-                goto check_again;
-            }
-        }
-
         type = source->type();
         // FIXME(82965): Add support for keySystem in <source> and set system from source.
         if (type.isEmpty() && mediaURL.protocolIsData())
@@ -3109,7 +3100,7 @@
         return;
 
     if (m_player->paused())
-        pauseInternal();
+        pause();
     else
         playInternal();
 }
@@ -3145,6 +3136,10 @@
 {
     WTF_LOG(Media, "HTMLMediaElement::mediaPlayerSizeChanged");
 
+    ASSERT(hasVideo()); // "resize" makes no sense absent video.
+    if (m_readyState > HAVE_NOTHING && isVideo())
+        scheduleEvent(EventTypeNames::resize);
+
     if (renderer())
         renderer()->updateFromElement();
 }
@@ -3406,6 +3401,8 @@
 
     closeMediaSource();
 
+    setMediaKeysInternal(0);
+
     clearMediaPlayerAndAudioSourceProviderClient();
 
     stopPeriodicTimers();
@@ -3704,6 +3701,9 @@
 
     m_player = MediaPlayer::create(this);
 
+    if (m_emeMode == EmeModeUnprefixed && m_player)
+        m_player->setContentDecryptionModule(contentDecryptionModule());
+
 #if ENABLE(WEB_AUDIO)
     if (m_audioSourceNode) {
         // When creating the player, make sure its AudioSourceProvider knows about the MediaElementAudioSourceNode.
@@ -3797,8 +3797,10 @@
 
     m_mediaController = controller;
 
-    if (m_mediaController)
+    if (m_mediaController) {
+        UseCounter::count(document(), UseCounter::HTMLMediaElementControllerNotNull);
         m_mediaController->addMediaElement(this);
+    }
 
     if (hasMediaControls())
         mediaControls()->setMediaController(m_mediaController ? m_mediaController.get() : static_cast<MediaControllerInterface*>(this));
@@ -3876,9 +3878,10 @@
 
 MediaPlayerClient::CORSMode HTMLMediaElement::mediaPlayerCORSMode() const
 {
-    if (!fastHasAttribute(crossoriginAttr))
+    const AtomicString& crossOriginMode = fastGetAttribute(crossoriginAttr);
+    if (crossOriginMode.isNull())
         return Unspecified;
-    if (equalIgnoringCase(fastGetAttribute(crossoriginAttr), "use-credentials"))
+    if (equalIgnoringCase(crossOriginMode, "use-credentials"))
         return UseCredentials;
     return Anonymous;
 }
@@ -3913,6 +3916,11 @@
         m_webLayer->setOpaque(m_opaque);
 }
 
+void HTMLMediaElement::mediaPlayerMediaSourceOpened(blink::WebMediaSource* webMediaSource)
+{
+    m_mediaSource->setWebMediaSourceAndOpen(adoptPtr(webMediaSource));
+}
+
 bool HTMLMediaElement::isInteractiveContent() const
 {
     return fastHasAttribute(controlsAttr);
diff --git a/Source/core/html/HTMLMediaElement.h b/Source/core/html/HTMLMediaElement.h
index 78b69dd..05df584 100644
--- a/Source/core/html/HTMLMediaElement.h
+++ b/Source/core/html/HTMLMediaElement.h
@@ -38,6 +38,7 @@
 #include "public/platform/WebMimeRegistry.h"
 
 namespace blink {
+class WebContentDecryptionModule;
 class WebInbandTextTrack;
 class WebLayer;
 }
@@ -57,12 +58,11 @@
 class MediaController;
 class MediaControls;
 class MediaError;
+class MediaKeys;
 class HTMLMediaSource;
 class TextTrackList;
 class TimeRanges;
-#if ENABLE(ENCRYPTED_MEDIA_V2)
-class MediaKeys;
-#endif
+class URLRegistry;
 
 typedef PODIntervalTree<double, TextTrackCue*> CueIntervalTree;
 typedef CueIntervalTree::IntervalType CueInterval;
@@ -78,14 +78,14 @@
 public:
     static blink::WebMimeRegistry::SupportsType supportsType(const ContentType&, const String& keySystem = String());
 
+    static void setMediaStreamRegistry(URLRegistry*);
+    static bool isMediaStreamURL(const String& url);
+
     MediaPlayer* player() const { return m_player.get(); }
 
     virtual bool isVideo() const = 0;
     virtual bool hasVideo() const OVERRIDE { return false; }
-    virtual bool hasAudio() const OVERRIDE;
-
-    // Eventually overloaded in HTMLVideoElement
-    virtual bool supportsFullscreen() const OVERRIDE { return false; };
+    virtual bool hasAudio() const OVERRIDE FINAL;
 
     bool supportsSave() const;
 
@@ -111,21 +111,22 @@
     NetworkState networkState() const;
 
     String preload() const;
-    void setPreload(const String&);
+    void setPreload(const AtomicString&);
 
     PassRefPtr<TimeRanges> buffered() const;
     void load();
-    String canPlayType(const String& mimeType, const String& keySystem = String(), const KURL& = KURL()) const;
+    String canPlayType(const String& mimeType, const String& keySystem = String()) const;
 
     // ready state
+    enum ReadyState { HAVE_NOTHING, HAVE_METADATA, HAVE_CURRENT_DATA, HAVE_FUTURE_DATA, HAVE_ENOUGH_DATA };
     ReadyState readyState() const;
     bool seeking() const;
 
     // playback state
-    double currentTime() const;
-    void setCurrentTime(double, ExceptionState&);
-    double duration() const;
-    bool paused() const;
+    virtual double currentTime() const OVERRIDE FINAL;
+    virtual void setCurrentTime(double, ExceptionState&) OVERRIDE FINAL;
+    virtual double duration() const OVERRIDE FINAL;
+    virtual bool paused() const OVERRIDE FINAL;
     double defaultPlaybackRate() const;
     void setDefaultPlaybackRate(double);
     double playbackRate() const;
@@ -137,8 +138,8 @@
     bool autoplay() const;
     bool loop() const;
     void setLoop(bool b);
-    void play();
-    void pause();
+    virtual void play() OVERRIDE FINAL;
+    virtual void pause() OVERRIDE FINAL;
 
     // statistics
     unsigned webkitAudioDecodedByteCount() const;
@@ -148,7 +149,7 @@
     void closeMediaSource();
     void durationChanged(double duration);
 
-    // encrypted media extensions
+    // encrypted media extensions (v0.1b)
     void webkitGenerateKeyRequest(const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState&);
     void webkitGenerateKeyRequest(const String& keySystem, ExceptionState&);
     void webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState&);
@@ -160,30 +161,27 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitkeymessage);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitneedkey);
 
-#if ENABLE(ENCRYPTED_MEDIA_V2)
+    // encrypted media extensions (WD)
     MediaKeys* mediaKeys() const { return m_mediaKeys.get(); }
-    void setMediaKeys(MediaKeys*);
-#endif
+    void setMediaKeys(MediaKeys*, ExceptionState&);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(needkey);
 
     // controls
     bool controls() const;
     void setControls(bool);
-    double volume() const;
-    void setVolume(double, ExceptionState&);
-    bool muted() const;
-    void setMuted(bool);
+    virtual double volume() const OVERRIDE FINAL;
+    virtual void setVolume(double, ExceptionState&) OVERRIDE FINAL;
+    virtual bool muted() const OVERRIDE FINAL;
+    virtual void setMuted(bool) OVERRIDE FINAL;
 
-    void togglePlayState();
-    void beginScrubbing();
-    void endScrubbing();
+    virtual void beginScrubbing() OVERRIDE FINAL;
+    virtual void endScrubbing() OVERRIDE FINAL;
 
-    bool canPlay() const;
+    virtual bool canPlay() const OVERRIDE FINAL;
 
-    double percentLoaded() const;
-
-    PassRefPtr<TextTrack> addTextTrack(const String& kind, const String& label, const String& language, ExceptionState&);
-    PassRefPtr<TextTrack> addTextTrack(const String& kind, const String& label, ExceptionState& exceptionState) { return addTextTrack(kind, label, emptyString(), exceptionState); }
-    PassRefPtr<TextTrack> addTextTrack(const String& kind, ExceptionState& exceptionState) { return addTextTrack(kind, emptyString(), emptyString(), exceptionState); }
+    PassRefPtr<TextTrack> addTextTrack(const AtomicString& kind, const AtomicString& label, const AtomicString& language, ExceptionState&);
+    PassRefPtr<TextTrack> addTextTrack(const AtomicString& kind, const AtomicString& label, ExceptionState& exceptionState) { return addTextTrack(kind, label, emptyAtom, exceptionState); }
+    PassRefPtr<TextTrack> addTextTrack(const AtomicString& kind, ExceptionState& exceptionState) { return addTextTrack(kind, emptyAtom, emptyAtom, exceptionState); }
 
     TextTrackList* textTracks();
     CueList currentlyActiveCues() const { return m_currentlyActiveCues; }
@@ -197,8 +195,10 @@
     void didAddTrack(HTMLTrackElement*);
     void didRemoveTrack(HTMLTrackElement*);
 
-    virtual void mediaPlayerDidAddTrack(blink::WebInbandTextTrack*) OVERRIDE;
-    virtual void mediaPlayerDidRemoveTrack(blink::WebInbandTextTrack*) OVERRIDE;
+    virtual void mediaPlayerDidAddTrack(blink::WebInbandTextTrack*) OVERRIDE FINAL;
+    virtual void mediaPlayerDidRemoveTrack(blink::WebInbandTextTrack*) OVERRIDE FINAL;
+    // FIXME: Remove this when WebMediaPlayerClientImpl::loadInternal does not depend on it.
+    virtual KURL mediaPlayerPosterURL() OVERRIDE { return KURL(); }
 
     struct TrackGroup {
         enum GroupKind { CaptionsAndSubtitles, Description, Chapter, Metadata, Other };
@@ -232,29 +232,29 @@
     void textTrackReadyStateChanged(TextTrack*);
 
     // TextTrackClient
-    virtual void textTrackKindChanged(TextTrack*) OVERRIDE;
-    virtual void textTrackModeChanged(TextTrack*) OVERRIDE;
-    virtual void textTrackAddCues(TextTrack*, const TextTrackCueList*) OVERRIDE;
-    virtual void textTrackRemoveCues(TextTrack*, const TextTrackCueList*) OVERRIDE;
-    virtual void textTrackAddCue(TextTrack*, PassRefPtr<TextTrackCue>) OVERRIDE;
-    virtual void textTrackRemoveCue(TextTrack*, PassRefPtr<TextTrackCue>) OVERRIDE;
+    virtual void textTrackKindChanged(TextTrack*) OVERRIDE FINAL;
+    virtual void textTrackModeChanged(TextTrack*) OVERRIDE FINAL;
+    virtual void textTrackAddCues(TextTrack*, const TextTrackCueList*) OVERRIDE FINAL;
+    virtual void textTrackRemoveCues(TextTrack*, const TextTrackCueList*) OVERRIDE FINAL;
+    virtual void textTrackAddCue(TextTrack*, PassRefPtr<TextTrackCue>) OVERRIDE FINAL;
+    virtual void textTrackRemoveCue(TextTrack*, PassRefPtr<TextTrackCue>) OVERRIDE FINAL;
 
     // EventTarget function.
     // Both Node (via HTMLElement) and ActiveDOMObject define this method, which
     // causes an ambiguity error at compile time. This class's constructor
     // ensures that both implementations return document, so return the result
     // of one of them here.
-    virtual ExecutionContext* executionContext() const OVERRIDE { return HTMLElement::executionContext(); }
+    virtual ExecutionContext* executionContext() const OVERRIDE FINAL { return HTMLElement::executionContext(); }
 
     bool hasSingleSecurityOrigin() const { return !m_player || m_player->hasSingleSecurityOrigin(); }
 
     bool isFullscreen() const;
-    void enterFullscreen();
+    virtual void enterFullscreen() OVERRIDE FINAL;
     void exitFullscreen();
 
-    bool hasClosedCaptions() const;
-    bool closedCaptionsVisible() const;
-    void setClosedCaptionsVisible(bool);
+    virtual bool hasClosedCaptions() const OVERRIDE FINAL;
+    virtual bool closedCaptionsVisible() const OVERRIDE FINAL;
+    virtual void setClosedCaptionsVisible(bool) OVERRIDE FINAL;
 
     MediaControls* mediaControls() const;
 
@@ -264,8 +264,8 @@
     bool isPlaying() const { return m_playing; }
 
     // ActiveDOMObject functions.
-    virtual bool hasPendingActivity() const OVERRIDE;
-    virtual void contextDestroyed() OVERRIDE;
+    virtual bool hasPendingActivity() const OVERRIDE FINAL;
+    virtual void contextDestroyed() OVERRIDE FINAL;
 
 #if ENABLE(WEB_AUDIO)
     MediaElementAudioSourceNode* audioSourceNode() { return m_audioSourceNode; }
@@ -281,38 +281,34 @@
     void setController(PassRefPtr<MediaController>); // Resets the MediaGroup and sets the MediaController.
 
 protected:
-    HTMLMediaElement(const QualifiedName&, Document&, bool);
+    HTMLMediaElement(const QualifiedName&, Document&);
     virtual ~HTMLMediaElement();
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void finishParsingChildren() OVERRIDE;
+    virtual void finishParsingChildren() OVERRIDE FINAL;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
 
     virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
 
-    enum DisplayMode { Unknown, None, Poster, PosterWaitingForVideo, Video };
+    enum DisplayMode { Unknown, Poster, PosterWaitingForVideo, Video };
     DisplayMode displayMode() const { return m_displayMode; }
     virtual void setDisplayMode(DisplayMode mode) { m_displayMode = mode; }
 
-    virtual bool isMediaElement() const OVERRIDE { return true; }
+    virtual bool isMediaElement() const OVERRIDE FINAL { return true; }
 
     void setControllerInternal(PassRefPtr<MediaController>);
 
     // Restrictions to change default behaviors.
     enum BehaviorRestrictionFlags {
         NoRestrictions = 0,
-        RequireUserGestureForLoadRestriction = 1 << 0,
-        RequireUserGestureForRateChangeRestriction = 1 << 1,
-        RequireUserGestureForFullscreenRestriction = 1 << 2,
-        RequirePageConsentToLoadMediaRestriction = 1 << 3,
+        RequireUserGestureForPlayRestriction = 1 << 0,
+        RequireUserGestureForFullscreenRestriction = 1 << 1,
     };
     typedef unsigned BehaviorRestrictions;
 
-    bool userGestureRequiredForLoad() const { return m_restrictions & RequireUserGestureForLoadRestriction; }
-    bool userGestureRequiredForRateChange() const { return m_restrictions & RequireUserGestureForRateChangeRestriction; }
+    bool userGestureRequiredForPlay() const { return m_restrictions & RequireUserGestureForPlayRestriction; }
     bool userGestureRequiredForFullscreen() const { return m_restrictions & RequireUserGestureForFullscreenRestriction; }
-    bool pageConsentRequiredForLoad() const { return m_restrictions & RequirePageConsentToLoadMediaRestriction; }
 
     void addBehaviorRestriction(BehaviorRestrictions restriction) { m_restrictions |= restriction; }
     void removeBehaviorRestriction(BehaviorRestrictions restriction) { m_restrictions &= ~restriction; }
@@ -324,54 +320,50 @@
 private:
     void createMediaPlayer();
 
-    virtual bool alwaysCreateUserAgentShadowRoot() const OVERRIDE { return true; }
-    virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
+    virtual bool alwaysCreateUserAgentShadowRoot() const OVERRIDE FINAL { return true; }
+    virtual bool areAuthorShadowsAllowed() const OVERRIDE FINAL { return false; }
 
-    virtual bool hasCustomFocusLogic() const OVERRIDE;
-    virtual bool supportsFocus() const OVERRIDE;
-    virtual bool isMouseFocusable() const OVERRIDE;
+    virtual bool hasCustomFocusLogic() const OVERRIDE FINAL;
+    virtual bool supportsFocus() const OVERRIDE FINAL;
+    virtual bool isMouseFocusable() const OVERRIDE FINAL;
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
-    virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE;
+    virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE FINAL;
+    virtual void removedFrom(ContainerNode*) OVERRIDE FINAL;
+    virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE FINAL;
 
-    virtual void didBecomeFullscreenElement() OVERRIDE;
-    virtual void willStopBeingFullscreenElement() OVERRIDE;
-    virtual bool isInteractiveContent() const OVERRIDE;
+    virtual void didBecomeFullscreenElement() OVERRIDE FINAL;
+    virtual void willStopBeingFullscreenElement() OVERRIDE FINAL;
+    virtual bool isInteractiveContent() const OVERRIDE FINAL;
 
     // ActiveDOMObject functions.
-    virtual void stop() OVERRIDE;
+    virtual void stop() OVERRIDE FINAL;
 
     virtual void updateDisplayState() { }
 
     void setReadyState(MediaPlayer::ReadyState);
     void setNetworkState(MediaPlayer::NetworkState);
 
-    virtual void mediaPlayerNetworkStateChanged() OVERRIDE;
-    virtual void mediaPlayerReadyStateChanged() OVERRIDE;
-    virtual void mediaPlayerTimeChanged() OVERRIDE;
-    virtual void mediaPlayerDurationChanged() OVERRIDE;
-    virtual void mediaPlayerPlaybackStateChanged() OVERRIDE;
-    virtual void mediaPlayerRequestFullscreen() OVERRIDE;
-    virtual void mediaPlayerRequestSeek(double) OVERRIDE;
-    virtual void mediaPlayerRepaint() OVERRIDE;
-    virtual void mediaPlayerSizeChanged() OVERRIDE;
+    virtual void mediaPlayerNetworkStateChanged() OVERRIDE FINAL;
+    virtual void mediaPlayerReadyStateChanged() OVERRIDE FINAL;
+    virtual void mediaPlayerTimeChanged() OVERRIDE FINAL;
+    virtual void mediaPlayerDurationChanged() OVERRIDE FINAL;
+    virtual void mediaPlayerPlaybackStateChanged() OVERRIDE FINAL;
+    virtual void mediaPlayerRequestFullscreen() OVERRIDE FINAL;
+    virtual void mediaPlayerRequestSeek(double) OVERRIDE FINAL;
+    virtual void mediaPlayerRepaint() OVERRIDE FINAL;
+    virtual void mediaPlayerSizeChanged() OVERRIDE FINAL;
 
-    virtual void mediaPlayerKeyAdded(const String& keySystem, const String& sessionId) OVERRIDE;
-    virtual void mediaPlayerKeyError(const String& keySystem, const String& sessionId, MediaPlayerClient::MediaKeyErrorCode, unsigned short systemCode) OVERRIDE;
-    virtual void mediaPlayerKeyMessage(const String& keySystem, const String& sessionId, const unsigned char* message, unsigned messageLength, const KURL& defaultURL) OVERRIDE;
-    virtual bool mediaPlayerKeyNeeded(const String& keySystem, const String& sessionId, const unsigned char* initData, unsigned initDataLength) OVERRIDE;
+    virtual void mediaPlayerKeyAdded(const String& keySystem, const String& sessionId) OVERRIDE FINAL;
+    virtual void mediaPlayerKeyError(const String& keySystem, const String& sessionId, MediaPlayerClient::MediaKeyErrorCode, unsigned short systemCode) OVERRIDE FINAL;
+    virtual void mediaPlayerKeyMessage(const String& keySystem, const String& sessionId, const unsigned char* message, unsigned messageLength, const KURL& defaultURL) OVERRIDE FINAL;
+    virtual bool mediaPlayerKeyNeeded(const String& contentType, const unsigned char* initData, unsigned initDataLength) OVERRIDE FINAL;
 
-#if ENABLE(ENCRYPTED_MEDIA_V2)
-    virtual bool mediaPlayerKeyNeeded(Uint8Array*) OVERRIDE;
-#endif
+    virtual CORSMode mediaPlayerCORSMode() const OVERRIDE FINAL;
 
-    virtual CORSMode mediaPlayerCORSMode() const OVERRIDE;
-
-    virtual void mediaPlayerSetWebLayer(blink::WebLayer*) OVERRIDE;
-    virtual void mediaPlayerSetOpaque(bool) OVERRIDE;
+    virtual void mediaPlayerSetWebLayer(blink::WebLayer*) OVERRIDE FINAL;
+    virtual void mediaPlayerSetOpaque(bool) OVERRIDE FINAL;
+    virtual void mediaPlayerMediaSourceOpened(blink::WebMediaSource*) OVERRIDE FINAL;
 
     void loadTimerFired(Timer<HTMLMediaElement>*);
     void progressEventTimerFired(Timer<HTMLMediaElement>*);
@@ -389,6 +381,8 @@
     void scheduleEvent(const AtomicString& eventName);
 
     // loading
+    void prepareForLoad();
+    void loadInternal();
     void selectMediaResource();
     void loadResource(const KURL&, ContentType&, const String& keySystem);
     void scheduleNextSourceChild();
@@ -412,12 +406,9 @@
 
     void markCaptionAndSubtitleTracksAsUnconfigured();
 
-    // These "internal" functions do not check user gesture restrictions.
-    void loadInternal();
+    // This does not check user gesture restrictions.
     void playInternal();
-    void pauseInternal();
 
-    void prepareForLoad();
     void allowVideoRendering();
 
     void updateVolume();
@@ -444,7 +435,7 @@
     void prepareMediaFragmentURI();
     void applyMediaFragmentURI();
 
-    virtual void* preDispatchEventHandler(Event*) OVERRIDE;
+    virtual void* preDispatchEventHandler(Event*) OVERRIDE FINAL;
 
     void changeNetworkStateFromLoadingToIdle();
 
@@ -455,9 +446,21 @@
     void updateMediaController();
     bool isBlocked() const;
     bool isBlockedOnMediaController() const;
-    bool hasCurrentSrc() const { return !m_currentSrc.isEmpty(); }
     bool isAutoplaying() const { return m_autoplaying; }
 
+    // Currently we have both EME v0.1b and EME WD implemented in media element.
+    // But we do not want to support both at the same time. The one used first
+    // will be supported. Use |m_emeMode| to track this selection.
+    // FIXME: Remove EmeMode once EME v0.1b support is removed. See crbug.com/249976.
+    enum EmeMode { EmeModeNotSelected, EmeModePrefixed, EmeModeUnprefixed };
+
+    // check (and set if necessary) the encrypted media extensions (EME) mode
+    // (v0.1b or WD). Returns whether the mode is allowed and successfully set.
+    bool setEmeMode(EmeMode, ExceptionState&);
+
+    blink::WebContentDecryptionModule* contentDecryptionModule();
+    void setMediaKeysInternal(MediaKeys*);
+
     Timer<HTMLMediaElement> m_loadTimer;
     Timer<HTMLMediaElement> m_progressEventTimer;
     Timer<HTMLMediaElement> m_playbackProgressTimer;
@@ -476,7 +479,6 @@
     double m_volume;
     double m_lastSeekTime;
 
-    unsigned m_previousProgress;
     double m_previousProgressTime;
 
     // Cached duration to suppress duplicate events if duration unchanged.
@@ -536,10 +538,8 @@
 
     bool m_closedCaptionsVisible : 1;
 
-    bool m_loadInitiatedByUserGesture : 1;
     bool m_completelyLoaded : 1;
     bool m_havePreparedToPlay : 1;
-    bool m_parsingInProgress : 1;
 
     bool m_tracksAreReady : 1;
     bool m_haveVisibleTextTrack : 1;
@@ -566,9 +566,11 @@
 
     friend class TrackDisplayUpdateScope;
 
-#if ENABLE(ENCRYPTED_MEDIA_V2)
-    RefPtr<MediaKeys> m_mediaKeys;
-#endif
+    EmeMode m_emeMode;
+
+    RefPtrWillBePersistent<MediaKeys> m_mediaKeys;
+
+    static URLRegistry* s_mediaStreamRegistry;
 };
 
 #ifndef NDEBUG
@@ -590,11 +592,6 @@
 };
 #endif
 
-inline bool isHTMLMediaElement(Node* node)
-{
-    return node && node->isElementNode() && toElement(node)->isMediaElement();
-}
-
 inline bool isHTMLMediaElement(const Node& node)
 {
     return node.isElementNode() && toElement(node).isMediaElement();
diff --git a/Source/core/html/HTMLMediaElement.idl b/Source/core/html/HTMLMediaElement.idl
index a868b53..977066a 100644
--- a/Source/core/html/HTMLMediaElement.idl
+++ b/Source/core/html/HTMLMediaElement.idl
@@ -24,8 +24,8 @@
  */
 
 [
+    ActiveDOMObject,
     RuntimeEnabled=Media,
-    ActiveDOMObject
 ] interface HTMLMediaElement : HTMLElement {
 
     // error state
@@ -34,7 +34,7 @@
     // network state
     [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
     [URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] readonly attribute DOMString currentSrc;
-    [Reflect] attribute DOMString crossOrigin;
+    [Reflect, ReflectOnly="anonymous"|"use-credentials", ReflectEmpty="anonymous", ReflectInvalid="anonymous"] attribute DOMString crossOrigin;
 
     const unsigned short NETWORK_EMPTY = 0;
     const unsigned short NETWORK_IDLE = 1;
@@ -45,7 +45,7 @@
 
     readonly attribute TimeRanges buffered;
     void load();
-    DOMString canPlayType([Default=Undefined] optional DOMString type, [Default=Undefined, TreatNullAs=NullString, TreatUndefinedAs=NullString] optional DOMString keySystem);
+    DOMString canPlayType(DOMString type, [Default=Undefined, TreatNullAs=NullString, TreatUndefinedAs=NullString] optional DOMString keySystem);
 
     // ready state
     const unsigned short HAVE_NOTHING = 0;
@@ -90,15 +90,16 @@
     [MeasureAs=PrefixedAudioDecodedByteCount] readonly attribute unsigned long webkitAudioDecodedByteCount;
     [MeasureAs=PrefixedVideoDecodedByteCount] readonly attribute unsigned long webkitVideoDecodedByteCount;
 
-    // FIXME: add DeprecateAs=PrefixedMediaGenerateKeyRequest when MediaKeys is ready.
-    [RuntimeEnabled=PrefixedEncryptedMedia, RaisesException] void webkitGenerateKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, optional Uint8Array initData);
-    [RuntimeEnabled=PrefixedEncryptedMedia, RaisesException] void webkitAddKey([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, Uint8Array key, optional Uint8Array initData, [Default=NullString] optional DOMString sessionId);
-    [RuntimeEnabled=PrefixedEncryptedMedia, RaisesException] void webkitCancelKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, [Default=NullString] optional DOMString sessionId);
+    [RuntimeEnabled=PrefixedEncryptedMedia, RaisesException, MeasureAs=PrefixedMediaGenerateKeyRequest] void webkitGenerateKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, optional Uint8Array initData);
+    [RuntimeEnabled=PrefixedEncryptedMedia, RaisesException, MeasureAs=PrefixedMediaAddKey] void webkitAddKey([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, Uint8Array key, optional Uint8Array initData, [Default=NullString] optional DOMString sessionId);
+    [RuntimeEnabled=PrefixedEncryptedMedia, RaisesException, MeasureAs=PrefixedMediaCancelKeyRequest] void webkitCancelKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, [Default=NullString] optional DOMString sessionId);
 
     [RuntimeEnabled=PrefixedEncryptedMedia] attribute EventHandler onwebkitkeyadded;
     [RuntimeEnabled=PrefixedEncryptedMedia] attribute EventHandler onwebkitkeyerror;
     [RuntimeEnabled=PrefixedEncryptedMedia] attribute EventHandler onwebkitkeymessage;
     [RuntimeEnabled=PrefixedEncryptedMedia] attribute EventHandler onwebkitneedkey;
 
-    [RuntimeEnabled=EncryptedMedia, Conditional=ENCRYPTED_MEDIA_V2] attribute MediaKeys mediaKeys;
+    [RuntimeEnabled=EncryptedMedia] readonly attribute MediaKeys mediaKeys;
+    [RuntimeEnabled=EncryptedMedia, RaisesException] void setMediaKeys(MediaKeys mediaKeys);
+    [RuntimeEnabled=EncryptedMedia] attribute EventHandler onneedkey;
 };
diff --git a/Source/core/html/HTMLMetaElement-in.cpp b/Source/core/html/HTMLMetaElement-in.cpp
index c6347df..f63a6f8 100644
--- a/Source/core/html/HTMLMetaElement-in.cpp
+++ b/Source/core/html/HTMLMetaElement-in.cpp
@@ -25,7 +25,7 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 
 namespace WebCore {
 
@@ -177,10 +177,10 @@
     DEFINE_ARRAY_FOR_MATCHING(characters, valueString, 13);
     SWITCH(characters, length) {
         CASE("device-width") {
-            return Length(100, ViewportPercentageWidth);
+            return Length(DeviceWidth);
         }
         CASE("device-height") {
-            return Length(100, ViewportPercentageHeight);
+            return Length(DeviceHeight);
         }
     }
 
@@ -333,6 +333,10 @@
             reportViewportWarning(TargetDensityDpiUnsupported, String(), String());
             return;
         }
+        CASE("minimal-ui") {
+            // Ignore vendor-specific argument.
+            return;
+        }
     }
     reportViewportWarning(UnrecognizedViewportArgumentKeyError, keyString, String());
 }
@@ -355,11 +359,10 @@
     switch (errorCode) {
     case TruncatedViewportArgumentValueError:
     case TargetDensityDpiUnsupported:
-        return WarningMessageLevel;
     case UnrecognizedViewportArgumentKeyError:
     case UnrecognizedViewportArgumentValueError:
     case MaximumScaleTooLargeError:
-        return ErrorMessageLevel;
+        return WarningMessageLevel;
     }
 
     ASSERT_NOT_REACHED();
@@ -440,6 +443,18 @@
     return InsertionDone;
 }
 
+static bool inDocumentHead(HTMLMetaElement* element)
+{
+    if (!element->inDocument())
+        return false;
+
+    for (Element* current = element; current; current = current->parentElement()) {
+        if (current->hasTagName(HTMLNames::headTag))
+            return true;
+    }
+    return false;
+}
+
 void HTMLMetaElement::process()
 {
     if (!inDocument())
@@ -451,24 +466,24 @@
         return;
 
     const AtomicString& nameValue = fastGetAttribute(nameAttr);
-    if (nameValue.isNull()) {
-        // Get the document to process the tag, but only if we're actually part of DOM
-        // tree (changing a meta tag while it's not in the tree shouldn't have any effect
-        // on the document).
-        const AtomicString& httpEquivValue = fastGetAttribute(http_equivAttr);
-        if (!httpEquivValue.isNull())
-            document().processHttpEquiv(httpEquivValue, contentValue);
-        return;
+    if (!nameValue.isEmpty()) {
+        if (equalIgnoringCase(nameValue, "viewport"))
+            processViewportContentAttribute(contentValue, ViewportDescription::ViewportMeta);
+        else if (equalIgnoringCase(nameValue, "referrer"))
+            document().processReferrerPolicy(contentValue);
+        else if (equalIgnoringCase(nameValue, "handheldfriendly") && equalIgnoringCase(contentValue, "true"))
+            processViewportContentAttribute("width=device-width", ViewportDescription::HandheldFriendlyMeta);
+        else if (equalIgnoringCase(nameValue, "mobileoptimized"))
+            processViewportContentAttribute("width=device-width, initial-scale=1", ViewportDescription::MobileOptimizedMeta);
     }
 
-    if (equalIgnoringCase(nameValue, "viewport"))
-        processViewportContentAttribute(contentValue, ViewportDescription::ViewportMeta);
-    else if (equalIgnoringCase(nameValue, "referrer"))
-        document().processReferrerPolicy(contentValue);
-    else if (equalIgnoringCase(nameValue, "handheldfriendly") && equalIgnoringCase(contentValue, "true"))
-        processViewportContentAttribute("width=device-width", ViewportDescription::HandheldFriendlyMeta);
-    else if (equalIgnoringCase(nameValue, "mobileoptimized"))
-        processViewportContentAttribute("width=device-width, initial-scale=1", ViewportDescription::MobileOptimizedMeta);
+    // Get the document to process the tag, but only if we're actually part of DOM
+    // tree (changing a meta tag while it's not in the tree shouldn't have any effect
+    // on the document).
+
+    const AtomicString& httpEquivValue = fastGetAttribute(http_equivAttr);
+    if (!httpEquivValue.isEmpty())
+        document().processHttpEquiv(httpEquivValue, contentValue, inDocumentHead(this));
 }
 
 const AtomicString& HTMLMetaElement::content() const
diff --git a/Source/core/html/HTMLMeterElement.cpp b/Source/core/html/HTMLMeterElement.cpp
index 39b3126..aabfb42 100644
--- a/Source/core/html/HTMLMeterElement.cpp
+++ b/Source/core/html/HTMLMeterElement.cpp
@@ -30,7 +30,6 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/MeterShadowElement.h"
-#include "core/page/Page.h"
 #include "core/rendering/RenderMeter.h"
 #include "core/rendering/RenderTheme.h"
 
@@ -79,7 +78,7 @@
 void HTMLMeterElement::setMin(double min, ExceptionState& exceptionState)
 {
     if (!std::isfinite(min)) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(min));
+        exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(min));
         return;
     }
     setFloatingPointAttribute(minAttr, min);
@@ -93,7 +92,7 @@
 void HTMLMeterElement::setMax(double max, ExceptionState& exceptionState)
 {
     if (!std::isfinite(max)) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(max));
+        exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(max));
         return;
     }
     setFloatingPointAttribute(maxAttr, max);
@@ -108,7 +107,7 @@
 void HTMLMeterElement::setValue(double value, ExceptionState& exceptionState)
 {
     if (!std::isfinite(value)) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(value));
+        exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(value));
         return;
     }
     setFloatingPointAttribute(valueAttr, value);
@@ -123,7 +122,7 @@
 void HTMLMeterElement::setLow(double low, ExceptionState& exceptionState)
 {
     if (!std::isfinite(low)) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(low));
+        exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(low));
         return;
     }
     setFloatingPointAttribute(lowAttr, low);
@@ -138,7 +137,7 @@
 void HTMLMeterElement::setHigh(double high, ExceptionState& exceptionState)
 {
     if (!std::isfinite(high)) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(high));
+        exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(high));
         return;
     }
     setFloatingPointAttribute(highAttr, high);
@@ -153,7 +152,7 @@
 void HTMLMeterElement::setOptimum(double optimum, ExceptionState& exceptionState)
 {
     if (!std::isfinite(optimum)) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(optimum));
+        exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(optimum));
         return;
     }
     setFloatingPointAttribute(optimumAttr, optimum);
diff --git a/Source/core/html/HTMLMeterElement.h b/Source/core/html/HTMLMeterElement.h
index e815e60..670ec81 100644
--- a/Source/core/html/HTMLMeterElement.h
+++ b/Source/core/html/HTMLMeterElement.h
@@ -60,7 +60,7 @@
     double valueRatio() const;
     GaugeRegion gaugeRegion() const;
 
-    bool canContainRangeEndPoint() const { return false; }
+    virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
 
 private:
     explicit HTMLMeterElement(Document&);
@@ -71,8 +71,7 @@
 
     virtual bool supportLabels() const OVERRIDE { return true; }
 
-    virtual bool recalcWillValidate() const { return false; }
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
     void didElementStateChange();
@@ -81,11 +80,6 @@
     RefPtr<MeterValueElement> m_value;
 };
 
-inline bool isHTMLMeterElement(Node* node)
-{
-    return node->hasTagName(HTMLNames::meterTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLMeterElement, hasTagName(HTMLNames::meterTag));
 
 } // namespace
diff --git a/Source/core/html/HTMLNameCollection.cpp b/Source/core/html/HTMLNameCollection.cpp
index 9941f55..47f681d 100644
--- a/Source/core/html/HTMLNameCollection.cpp
+++ b/Source/core/html/HTMLNameCollection.cpp
@@ -34,7 +34,7 @@
 
 using namespace HTMLNames;
 
-HTMLNameCollection::HTMLNameCollection(Node* document, CollectionType type, const AtomicString& name)
+HTMLNameCollection::HTMLNameCollection(ContainerNode* document, CollectionType type, const AtomicString& name)
     : HTMLCollection(document, type, OverridesItemAfter)
     , m_name(name)
 {
@@ -46,12 +46,11 @@
     ASSERT(ownerNode()->isDocumentNode());
     ASSERT(type() == WindowNamedItems || type() == DocumentNamedItems);
 
-    ownerNode()->nodeLists()->removeCacheWithAtomicName(this, type(), m_name);
+    ownerNode()->nodeLists()->removeCache(this, type(), m_name);
 }
 
-Element* HTMLNameCollection::virtualItemAfter(unsigned& offsetInArray, Element* previous) const
+Element* HTMLNameCollection::virtualItemAfter(Element* previous) const
 {
-    ASSERT_UNUSED(offsetInArray, !offsetInArray);
     ASSERT(previous != ownerNode());
 
     Element* current;
diff --git a/Source/core/html/HTMLNameCollection.h b/Source/core/html/HTMLNameCollection.h
index 435d439..afb3019 100644
--- a/Source/core/html/HTMLNameCollection.h
+++ b/Source/core/html/HTMLNameCollection.h
@@ -33,7 +33,7 @@
 
 class HTMLNameCollection FINAL : public HTMLCollection {
 public:
-    static PassRefPtr<HTMLNameCollection> create(Node* document, CollectionType type, const AtomicString& name)
+    static PassRefPtr<HTMLNameCollection> create(ContainerNode* document, CollectionType type, const AtomicString& name)
     {
         return adoptRef(new HTMLNameCollection(document, type, name));
     }
@@ -41,9 +41,9 @@
     ~HTMLNameCollection();
 
 private:
-    HTMLNameCollection(Node*, CollectionType, const AtomicString& name);
+    HTMLNameCollection(ContainerNode*, CollectionType, const AtomicString& name);
 
-    virtual Element* virtualItemAfter(unsigned& offsetInArray, Element*) const OVERRIDE;
+    virtual Element* virtualItemAfter(Element*) const OVERRIDE;
 
     AtomicString m_name;
 };
diff --git a/Source/core/html/HTMLImportResourceOwner.cpp b/Source/core/html/HTMLNoEmbedElement.cpp
similarity index 70%
copy from Source/core/html/HTMLImportResourceOwner.cpp
copy to Source/core/html/HTMLNoEmbedElement.cpp
index 3a3109c..d9e268c 100644
--- a/Source/core/html/HTMLImportResourceOwner.cpp
+++ b/Source/core/html/HTMLNoEmbedElement.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,32 +29,31 @@
  */
 
 #include "config.h"
-#include "core/html/HTMLImportResourceOwner.h"
+#include "core/html/HTMLNoEmbedElement.h"
+
+#include "HTMLNames.h"
+#include "core/frame/Frame.h"
+#include "core/loader/FrameLoader.h"
 
 namespace WebCore {
 
-HTMLImportResourceOwner::HTMLImportResourceOwner()
+using namespace HTMLNames;
+
+HTMLNoEmbedElement::HTMLNoEmbedElement(Document& document)
+    : HTMLElement(noembedTag, document)
 {
 }
 
-HTMLImportResourceOwner::~HTMLImportResourceOwner()
+PassRefPtr<HTMLNoEmbedElement> HTMLNoEmbedElement::create(Document& document)
 {
-    clearResource();
+    return adoptRef(new HTMLNoEmbedElement(document));
 }
 
-void HTMLImportResourceOwner::setResource(const ResourcePtr<RawResource>& resource)
+bool HTMLNoEmbedElement::rendererIsNeeded(const RenderStyle& style)
 {
-    ASSERT(!hasResource());
-    m_resource = resource;
-    m_resource->addClient(this);
+    if (document().frame()->loader().allowPlugins(NotAboutToInstantiatePlugin))
+        return false;
+    return Element::rendererIsNeeded(style);
 }
 
-void HTMLImportResourceOwner::clearResource()
-{
-    if (!hasResource())
-        return;
-    m_resource->removeClient(this);
-    m_resource = 0;
 }
-
-} // namespace WebCore
diff --git a/Source/core/rendering/LayoutIndicator.h b/Source/core/html/HTMLNoEmbedElement.h
similarity index 74%
rename from Source/core/rendering/LayoutIndicator.h
rename to Source/core/html/HTMLNoEmbedElement.h
index 6337da9..9c5ae7f 100644
--- a/Source/core/rendering/LayoutIndicator.h
+++ b/Source/core/html/HTMLNoEmbedElement.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,36 +28,25 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef LayoutIndicator_h
-#define LayoutIndicator_h
+#ifndef HTMLNoEmbedElement_h
+#define HTMLNoEmbedElement_h
 
-#include "wtf/Assertions.h"
+#include "core/html/HTMLElement.h"
 
 namespace WebCore {
 
-#ifndef NDEBUG
-
-class LayoutIndicator {
+// <noembed> is an HTMLElement in script, but we use a separate interface here
+// so HTMLElement's rendererIsNeeded doesn't need to know about it.
+class HTMLNoEmbedElement FINAL : public HTMLElement {
 public:
-    LayoutIndicator() { ++s_inLayout; }
-    ~LayoutIndicator() { --s_inLayout; }
-
-    static bool inLayout() { return s_inLayout; }
+    static PassRefPtr<HTMLNoEmbedElement> create(Document&);
 
 private:
-    static size_t s_inLayout;
+    explicit HTMLNoEmbedElement(Document&);
+
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 };
 
-#else
-
-class LayoutIndicator {
-public:
-    LayoutIndicator() { }
-    ~LayoutIndicator() { }
-};
+} // namespace
 
 #endif
-
-}
-
-#endif // LayoutIndicator_h
diff --git a/Source/core/html/HTMLImportResourceOwner.cpp b/Source/core/html/HTMLNoScriptElement.cpp
similarity index 69%
copy from Source/core/html/HTMLImportResourceOwner.cpp
copy to Source/core/html/HTMLNoScriptElement.cpp
index 3a3109c..65f1c1b 100644
--- a/Source/core/html/HTMLImportResourceOwner.cpp
+++ b/Source/core/html/HTMLNoScriptElement.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,32 +29,32 @@
  */
 
 #include "config.h"
-#include "core/html/HTMLImportResourceOwner.h"
+#include "core/html/HTMLNoScriptElement.h"
+
+#include "HTMLNames.h"
+#include "bindings/v8/ScriptController.h"
+#include "core/frame/Frame.h"
 
 namespace WebCore {
 
-HTMLImportResourceOwner::HTMLImportResourceOwner()
+using namespace HTMLNames;
+
+HTMLNoScriptElement::HTMLNoScriptElement(Document& document)
+    : HTMLElement(noscriptTag, document)
 {
 }
 
-HTMLImportResourceOwner::~HTMLImportResourceOwner()
+PassRefPtr<HTMLNoScriptElement> HTMLNoScriptElement::create(Document& document)
 {
-    clearResource();
+    return adoptRef(new HTMLNoScriptElement(document));
 }
 
-void HTMLImportResourceOwner::setResource(const ResourcePtr<RawResource>& resource)
+bool HTMLNoScriptElement::rendererIsNeeded(const RenderStyle& style)
 {
-    ASSERT(!hasResource());
-    m_resource = resource;
-    m_resource->addClient(this);
+    if (document().frame()->script().canExecuteScripts(NotAboutToExecuteScript))
+        return false;
+    return Element::rendererIsNeeded(style);
+
 }
 
-void HTMLImportResourceOwner::clearResource()
-{
-    if (!hasResource())
-        return;
-    m_resource->removeClient(this);
-    m_resource = 0;
 }
-
-} // namespace WebCore
diff --git a/Source/core/html/HTMLImportDataClient.h b/Source/core/html/HTMLNoScriptElement.h
similarity index 73%
copy from Source/core/html/HTMLImportDataClient.h
copy to Source/core/html/HTMLNoScriptElement.h
index 0c26a22..cbf8e75 100644
--- a/Source/core/html/HTMLImportDataClient.h
+++ b/Source/core/html/HTMLNoScriptElement.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,17 +28,25 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef HTMLImportDataClient_h
-#define HTMLImportDataClient_h
+#ifndef HTMLNoScriptElement_h
+#define HTMLNoScriptElement_h
+
+#include "core/html/HTMLElement.h"
 
 namespace WebCore {
 
-class HTMLImportDataClient {
+// <noscript> is an HTMLElement in script, but we use a separate interface here
+// so HTMLElement's rendererIsNeeded doesn't need to know about it.
+class HTMLNoScriptElement FINAL : public HTMLElement {
 public:
-    virtual ~HTMLImportDataClient() { }
-    virtual void didFinish() = 0;
+    static PassRefPtr<HTMLNoScriptElement> create(Document&);
+
+private:
+    explicit HTMLNoScriptElement(Document&);
+
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 };
 
-}
+} // namespace
 
-#endif // HTMLImportDataClient_h
+#endif
diff --git a/Source/core/html/HTMLObjectElement.cpp b/Source/core/html/HTMLObjectElement.cpp
index c4cc033..2879919 100644
--- a/Source/core/html/HTMLObjectElement.cpp
+++ b/Source/core/html/HTMLObjectElement.cpp
@@ -28,18 +28,18 @@
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/ElementTraversal.h"
-#include "core/dom/NodeList.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/fetch/ImageResource.h"
 #include "core/html/FormDataList.h"
+#include "core/html/HTMLCollection.h"
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLImageLoader.h"
 #include "core/html/HTMLMetaElement.h"
 #include "core/html/HTMLParamElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 #include "platform/MIMETypeRegistry.h"
@@ -53,8 +53,8 @@
     : HTMLPlugInElement(objectTag, document, createdByParser, ShouldNotPreferPlugInsForImages)
     , m_useFallbackContent(false)
 {
-    setForm(form ? form : findFormAncestor());
     ScriptWrappable::init(this);
+    associateByParser(form);
 }
 
 inline HTMLObjectElement::~HTMLObjectElement()
@@ -98,22 +98,20 @@
         size_t pos = m_serviceType.find(";");
         if (pos != kNotFound)
             m_serviceType = m_serviceType.left(pos);
-        if (renderer())
-            setNeedsWidgetUpdate(true);
+        reloadPluginOnAttributeChange(name);
     } else if (name == dataAttr) {
         m_url = stripLeadingAndTrailingHTMLSpaces(value);
-        if (renderer()) {
+        if (renderer() && isImageType()) {
             setNeedsWidgetUpdate(true);
-            if (isImageType()) {
-                if (!m_imageLoader)
-                    m_imageLoader = adoptPtr(new HTMLImageLoader(this));
-                m_imageLoader->updateFromElementIgnoringPreviousError();
-            }
+            if (!m_imageLoader)
+                m_imageLoader = adoptPtr(new HTMLImageLoader(this));
+            m_imageLoader->updateFromElementIgnoringPreviousError();
+        } else {
+            reloadPluginOnAttributeChange(name);
         }
     } else if (name == classidAttr) {
         m_classId = value;
-        if (renderer())
-            setNeedsWidgetUpdate(true);
+        reloadPluginOnAttributeChange(name);
     } else if (name == onbeforeloadAttr) {
         setAttributeEventListener(EventTypeNames::beforeload, createAttributeEventListener(this, name, value));
     } else {
@@ -237,7 +235,7 @@
         || !equalIgnoringCase(classId(), "clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"))
         return false;
 
-    RefPtr<NodeList> metaElements = document().getElementsByTagName(HTMLNames::metaTag.localName());
+    RefPtr<HTMLCollection> metaElements = document().getElementsByTagName(HTMLNames::metaTag.localName());
     unsigned length = metaElements->length();
     for (unsigned i = 0; i < length; ++i) {
         ASSERT(metaElements->item(i)->isHTMLElement());
@@ -262,6 +260,30 @@
     return classId().isEmpty();
 }
 
+void HTMLObjectElement::reloadPluginOnAttributeChange(const QualifiedName& name)
+{
+    // Following,
+    //   http://www.whatwg.org/specs/web-apps/current-work/#the-object-element
+    //   (Enumerated list below "Whenever one of the following conditions occur:")
+    //
+    // the updating of certain attributes should bring about "redetermination"
+    // of what the element contains.
+    bool needsInvalidation;
+    if (name == typeAttr) {
+        needsInvalidation = !fastHasAttribute(classidAttr) && !fastHasAttribute(dataAttr);
+    } else if (name == dataAttr) {
+        needsInvalidation = !fastHasAttribute(classidAttr);
+    } else if (name == classidAttr) {
+        needsInvalidation = true;
+    } else {
+        ASSERT_NOT_REACHED();
+        needsInvalidation = false;
+    }
+    setNeedsWidgetUpdate(true);
+    if (needsInvalidation)
+        setNeedsStyleRecalc(SubtreeStyleChange);
+}
+
 // FIXME: This should be unified with HTMLEmbedElement::updateWidget and
 // moved down into HTMLPluginElement.cpp
 void HTMLObjectElement::updateWidgetInternal()
@@ -270,14 +292,18 @@
     ASSERT(needsWidgetUpdate());
     setNeedsWidgetUpdate(false);
     // FIXME: This should ASSERT isFinishedParsingChildren() instead.
-    if (!isFinishedParsingChildren())
+    if (!isFinishedParsingChildren()) {
+        dispatchErrorEvent();
         return;
+    }
 
     // FIXME: I'm not sure it's ever possible to get into updateWidget during a
     // removal, but just in case we should avoid loading the frame to prevent
     // security bugs.
-    if (!SubframeLoadingDisabler::canLoadFrame(*this))
+    if (!SubframeLoadingDisabler::canLoadFrame(*this)) {
+        dispatchErrorEvent();
         return;
+    }
 
     String url = this->url();
     String serviceType = m_serviceType;
@@ -288,8 +314,10 @@
     parametersForPlugin(paramNames, paramValues, url, serviceType);
 
     // Note: url is modified above by parametersForPlugin.
-    if (!allowedToLoadFrameURL(url))
+    if (!allowedToLoadFrameURL(url)) {
+        dispatchErrorEvent();
         return;
+    }
 
     bool fallbackContent = hasFallbackContent();
     renderEmbeddedObject()->setHasFallbackContent(fallbackContent);
@@ -299,9 +327,12 @@
     if (!renderer()) // Do not load the plugin if beforeload removed this element or its renderer.
         return;
 
-    bool success = beforeLoadAllowedLoad && hasValidClassId() && requestObject(url, serviceType, paramNames, paramValues);
-    if (!success && fallbackContent)
-        renderFallbackContent();
+    if (!beforeLoadAllowedLoad || !hasValidClassId() || !requestObject(url, serviceType, paramNames, paramValues)) {
+        if (!url.isEmpty())
+            dispatchErrorEvent();
+        if (fallbackContent)
+            renderFallbackContent();
+    }
 }
 
 bool HTMLObjectElement::rendererIsNeeded(const RenderStyle& style)
@@ -329,7 +360,7 @@
 {
     if (inDocument() && !useFallbackContent()) {
         setNeedsWidgetUpdate(true);
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
     }
     HTMLPlugInElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
 }
@@ -415,19 +446,6 @@
     return false;
 }
 
-void HTMLObjectElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLPlugInElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, document().completeURL(getAttribute(dataAttr)));
-
-    // FIXME: Passing a string that starts with "#" to the completeURL function does
-    // not seem like it would work. The image element has similar but not identical code.
-    const AtomicString& useMap = getAttribute(usemapAttr);
-    if (useMap.startsWith('#'))
-        addSubresourceURL(urls, document().completeURL(useMap));
-}
-
 void HTMLObjectElement::didMoveToNewDocument(Document& oldDocument)
 {
     FormAssociatedElement::didMoveToNewDocument(oldDocument);
@@ -449,7 +467,7 @@
     return true;
 }
 
-HTMLFormElement* HTMLObjectElement::virtualForm() const
+HTMLFormElement* HTMLObjectElement::formOwner() const
 {
     return FormAssociatedElement::form();
 }
diff --git a/Source/core/html/HTMLObjectElement.h b/Source/core/html/HTMLObjectElement.h
index 9c0bb8c..347ed79 100644
--- a/Source/core/html/HTMLObjectElement.h
+++ b/Source/core/html/HTMLObjectElement.h
@@ -37,16 +37,18 @@
 
     const String& classId() const { return m_classId; }
 
+    virtual HTMLFormElement* formOwner() const OVERRIDE;
+
     bool containsJavaApplet() const;
 
     virtual bool useFallbackContent() const OVERRIDE;
     virtual void renderFallbackContent() OVERRIDE;
 
-    virtual bool isFormControlElement() const { return false; }
+    virtual bool isFormControlElement() const OVERRIDE { return false; }
 
-    virtual bool isEnumeratable() const { return true; }
+    virtual bool isEnumeratable() const OVERRIDE { return true; }
     virtual bool isInteractiveContent() const OVERRIDE;
-    virtual bool appendFormData(FormDataList&, bool);
+    virtual bool appendFormData(FormDataList&, bool) OVERRIDE;
 
     virtual bool isObjectElement() const OVERRIDE { return true; }
 
@@ -59,7 +61,7 @@
     using Node::ref;
     using Node::deref;
 
-    virtual bool canContainRangeEndPoint() const { return useFallbackContent(); }
+    virtual bool canContainRangeEndPoint() const OVERRIDE { return useFallbackContent(); }
 
     bool isExposed() const;
 
@@ -73,18 +75,16 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
     virtual const AtomicString imageSourceURL() const OVERRIDE;
 
     virtual RenderWidget* existingRenderWidget() const OVERRIDE;
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-
     virtual void updateWidgetInternal() OVERRIDE;
     void updateDocNamedItem();
 
@@ -99,9 +99,10 @@
     bool shouldAllowQuickTimeClassIdQuirk();
     bool hasValidClassId();
 
-    virtual void refFormAssociatedElement() { ref(); }
-    virtual void derefFormAssociatedElement() { deref(); }
-    virtual HTMLFormElement* virtualForm() const;
+    void reloadPluginOnAttributeChange(const QualifiedName&);
+
+    virtual void refFormAssociatedElement() OVERRIDE { ref(); }
+    virtual void derefFormAssociatedElement() OVERRIDE { deref(); }
 
     virtual bool shouldRegisterAsNamedItem() const OVERRIDE { return true; }
     virtual bool shouldRegisterAsExtraNamedItem() const OVERRIDE { return true; }
diff --git a/Source/core/html/HTMLObjectElement.idl b/Source/core/html/HTMLObjectElement.idl
index 2393f05..f01b7e8 100644
--- a/Source/core/html/HTMLObjectElement.idl
+++ b/Source/core/html/HTMLObjectElement.idl
@@ -51,5 +51,5 @@
     [Custom, NotEnumerable] getter Node (DOMString name);
     [Custom] setter Node (DOMString name, Node value);
 
-    [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
+    [CheckSecurity=Node, RaisesException] Document getSVGDocument();
 };
diff --git a/Source/core/html/HTMLOptGroupElement.cpp b/Source/core/html/HTMLOptGroupElement.cpp
index c9963b0..1f1a413 100644
--- a/Source/core/html/HTMLOptGroupElement.cpp
+++ b/Source/core/html/HTMLOptGroupElement.cpp
@@ -58,12 +58,6 @@
     return renderStyle() && renderStyle()->display() != NONE;
 }
 
-const AtomicString& HTMLOptGroupElement::formControlType() const
-{
-    DEFINE_STATIC_LOCAL(const AtomicString, optgroup, ("optgroup", AtomicString::ConstructFromLiteral));
-    return optgroup;
-}
-
 void HTMLOptGroupElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
     recalcSelectOptions();
@@ -90,12 +84,8 @@
 
 void HTMLOptGroupElement::attach(const AttachContext& context)
 {
+    updateNonRenderStyle();
     HTMLElement::attach(context);
-    // If after attaching nothing called styleForRenderer() on this node we
-    // manually cache the value. This happens if our parent doesn't have a
-    // renderer like <optgroup> or if it doesn't allow children like <select>.
-    if (!m_style && parentNode()->renderStyle())
-        updateNonRenderStyle();
 }
 
 void HTMLOptGroupElement::detach(const AttachContext& context)
@@ -116,12 +106,15 @@
 
 PassRefPtr<RenderStyle> HTMLOptGroupElement::customStyleForRenderer()
 {
-    // styleForRenderer is called whenever a new style should be associated
-    // with an Element so now is a good time to update our cached style.
-    updateNonRenderStyle();
     return m_style;
 }
 
+void HTMLOptGroupElement::willRecalcStyle(StyleRecalcChange change)
+{
+    if (!needsAttach() && (needsStyleRecalc() || change >= Inherit))
+        updateNonRenderStyle();
+}
+
 String HTMLOptGroupElement::groupLabelText() const
 {
     String itemText = getAttribute(labelAttr);
diff --git a/Source/core/html/HTMLOptGroupElement.h b/Source/core/html/HTMLOptGroupElement.h
index 54ed7b5..841fb5f 100644
--- a/Source/core/html/HTMLOptGroupElement.h
+++ b/Source/core/html/HTMLOptGroupElement.h
@@ -42,16 +42,16 @@
 private:
     explicit HTMLOptGroupElement(Document&);
 
-    virtual const AtomicString& formControlType() const;
     virtual bool rendererIsFocusable() const OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
+    virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual void accessKeyAction(bool sendMouseEvents);
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
 
     // <optgroup> never has a renderer so we manually manage a cached style.
     void updateNonRenderStyle();
@@ -63,21 +63,6 @@
     RefPtr<RenderStyle> m_style;
 };
 
-inline bool isHTMLOptGroupElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::optgroupTag);
-}
-
-inline bool isHTMLOptGroupElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::optgroupTag);
-}
-
-inline bool isHTMLOptGroupElement(const Element& element)
-{
-    return element.hasTagName(HTMLNames::optgroupTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLOptGroupElement, hasTagName(HTMLNames::optgroupTag));
 
 } //namespace
diff --git a/Source/core/html/HTMLOptionElement.cpp b/Source/core/html/HTMLOptionElement.cpp
index d2f6453..7b5bc1f 100644
--- a/Source/core/html/HTMLOptionElement.cpp
+++ b/Source/core/html/HTMLOptionElement.cpp
@@ -35,7 +35,6 @@
 #include "core/dom/ScriptLoader.h"
 #include "core/dom/Text.h"
 #include "core/html/HTMLDataListElement.h"
-#include "core/html/HTMLOptGroupElement.h"
 #include "core/html/HTMLSelectElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/rendering/RenderTheme.h"
@@ -82,12 +81,8 @@
 
 void HTMLOptionElement::attach(const AttachContext& context)
 {
+    updateNonRenderStyle();
     HTMLElement::attach(context);
-    // If after attaching nothing called styleForRenderer() on this node we
-    // manually cache the value. This happens if our parent doesn't have a
-    // renderer like <optgroup> or if it doesn't allow children like <select>.
-    if (!m_style && parentNode()->renderStyle())
-        updateNonRenderStyle();
 }
 
 void HTMLOptionElement::detach(const AttachContext& context)
@@ -146,8 +141,7 @@
 
 void HTMLOptionElement::accessKeyAction(bool)
 {
-    HTMLSelectElement* select = ownerSelectElement();
-    if (select)
+    if (HTMLSelectElement* select = ownerSelectElement())
         select->accessKeySetSelectedIndex(index());
 }
 
@@ -207,17 +201,17 @@
     setAttribute(valueAttr, value);
 }
 
-bool HTMLOptionElement::selected()
+bool HTMLOptionElement::selected() const
 {
     if (HTMLSelectElement* select = ownerSelectElement()) {
         // If a stylesheet contains option:checked selectors, this function is
         // called during parsing. updateListItemSelectedStates() is O(N) where N
         // is the number of option elements, so the <select> parsing would be
-        // O(N^2) without isParsingInProgress check. Also,
+        // O(N^2) without the isFinishedParsingChildren check. Also,
         // updateListItemSelectedStates() determines default selection, and we'd
         // like to avoid to determine default selection with incomplete option
         // list.
-        if (select->isParsingInProgress())
+        if (!select->isFinishedParsingChildren())
             return m_isSelected;
         select->updateListItemSelectedStates();
     }
@@ -302,12 +296,15 @@
 
 PassRefPtr<RenderStyle> HTMLOptionElement::customStyleForRenderer()
 {
-    // styleForRenderer is called whenever a new style should be associated
-    // with an Element so now is a good time to update our cached style.
-    updateNonRenderStyle();
     return m_style;
 }
 
+void HTMLOptionElement::willRecalcStyle(StyleRecalcChange change)
+{
+    if (!needsAttach() && (needsStyleRecalc() || change >= Inherit))
+        updateNonRenderStyle();
+}
+
 void HTMLOptionElement::didRecalcStyle(StyleRecalcChange)
 {
     // FIXME: This is nasty, we ask our owner select to repaint even if the new
@@ -321,7 +318,7 @@
 String HTMLOptionElement::textIndentedToRespectGroupLabel() const
 {
     ContainerNode* parent = parentNode();
-    if (parent && isHTMLOptGroupElement(parent))
+    if (parent && parent->hasTagName(optgroupTag))
         return "    " + text();
     return text();
 }
@@ -331,7 +328,7 @@
     if (ownElementDisabled())
         return true;
     if (Element* parent = parentElement())
-        return isHTMLOptGroupElement(parent) && parent->isDisabledFormControl();
+        return parent->hasTagName(optgroupTag) && parent->isDisabledFormControl();
     return false;
 }
 
@@ -366,4 +363,12 @@
     return text.toString();
 }
 
+HTMLFormElement* HTMLOptionElement::form() const
+{
+    if (HTMLSelectElement* selectElement = ownerSelectElement())
+        return selectElement->formOwner();
+
+    return 0;
+}
+
 } // namespace WebCore
diff --git a/Source/core/html/HTMLOptionElement.h b/Source/core/html/HTMLOptionElement.h
index f7103f8..6dc4c9d 100644
--- a/Source/core/html/HTMLOptionElement.h
+++ b/Source/core/html/HTMLOptionElement.h
@@ -39,7 +39,7 @@
     static PassRefPtr<HTMLOptionElement> createForJSConstructor(Document&, const String& data, const AtomicString& value,
         bool defaultSelected, bool selected, ExceptionState&);
 
-    virtual String text() const;
+    String text() const;
     void setText(const String&, ExceptionState&);
 
     int index() const;
@@ -47,7 +47,7 @@
     String value() const;
     void setValue(const AtomicString&);
 
-    bool selected();
+    bool selected() const;
     void setSelected(bool);
 
     HTMLDataListElement* ownerDataListElement() const;
@@ -64,27 +64,30 @@
 
     void setSelectedState(bool);
 
+    HTMLFormElement* form() const;
+
 private:
     explicit HTMLOptionElement(Document&);
 
     virtual bool rendererIsFocusable() const OVERRIDE;
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    virtual void accessKeyAction(bool);
+    virtual void accessKeyAction(bool) OVERRIDE;
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
     // <option> never has a renderer so we manually manage a cached style.
     void updateNonRenderStyle();
     virtual RenderStyle* nonRendererStyle() const OVERRIDE;
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
 
-    void didRecalcStyle(StyleRecalcChange) OVERRIDE;
+    virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE;
+    virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
 
     String collectOptionInnerText() const;
 
diff --git a/Source/core/html/HTMLOptionElement.idl b/Source/core/html/HTMLOptionElement.idl
index 2a1bf9d..41c6592 100644
--- a/Source/core/html/HTMLOptionElement.idl
+++ b/Source/core/html/HTMLOptionElement.idl
@@ -23,7 +23,7 @@
     RaisesException=Constructor
 ] interface HTMLOptionElement : HTMLElement {
     [Reflect] attribute boolean disabled;
-    [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
+    readonly attribute HTMLFormElement form;
     attribute DOMString label;
     [Reflect=selected] attribute boolean defaultSelected;
     attribute boolean selected;
diff --git a/Source/core/html/HTMLOptionsCollection.cpp b/Source/core/html/HTMLOptionsCollection.cpp
index aae87b0..f99e5f4 100644
--- a/Source/core/html/HTMLOptionsCollection.cpp
+++ b/Source/core/html/HTMLOptionsCollection.cpp
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2006, 2011, 2012 Apple Computer, Inc.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -30,14 +31,40 @@
 
 namespace WebCore {
 
-HTMLOptionsCollection::HTMLOptionsCollection(Node* select)
+HTMLOptionsCollection::HTMLOptionsCollection(ContainerNode* select)
     : HTMLCollection(select, SelectOptions, DoesNotOverrideItemAfter)
 {
     ASSERT(select->hasTagName(HTMLNames::selectTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLOptionsCollection> HTMLOptionsCollection::create(Node* select, CollectionType)
+void HTMLOptionsCollection::supportedPropertyNames(Vector<String>& names)
+{
+    // As per http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#htmloptionscollection:
+    // The supported property names consist of the non-empty values of all the id and name attributes of all the elements
+    // represented by the collection, in tree order, ignoring later duplicates, with the id of an element preceding its
+    // name if it contributes both, they differ from each other, and neither is the duplicate of an earlier entry.
+    HashSet<AtomicString> existingNames;
+    unsigned length = this->length();
+    for (unsigned i = 0; i < length; ++i) {
+        Element* element = item(i);
+        ASSERT(element);
+        const AtomicString& idAttribute = element->getIdAttribute();
+        if (!idAttribute.isEmpty()) {
+            HashSet<AtomicString>::AddResult addResult = existingNames.add(idAttribute);
+            if (addResult.isNewEntry)
+                names.append(idAttribute);
+        }
+        const AtomicString& nameAttribute = element->getNameAttribute();
+        if (!nameAttribute.isEmpty()) {
+            HashSet<AtomicString>::AddResult addResult = existingNames.add(nameAttribute);
+            if (addResult.isNewEntry)
+                names.append(nameAttribute);
+        }
+    }
+}
+
+PassRefPtr<HTMLOptionsCollection> HTMLOptionsCollection::create(ContainerNode* select, CollectionType)
 {
     return adoptRef(new HTMLOptionsCollection(select));
 }
@@ -96,9 +123,9 @@
     toHTMLSelectElement(ownerNode())->setLength(length, exceptionState);
 }
 
-void HTMLOptionsCollection::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<NodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Node>& returnValue1)
+void HTMLOptionsCollection::namedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<NodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Element>& returnValue1)
 {
-    Vector<RefPtr<Node> > namedItems;
+    Vector<RefPtr<Element> > namedItems;
     this->namedItems(name, namedItems);
 
     if (!namedItems.size())
@@ -110,22 +137,16 @@
         return;
     }
 
+    // FIXME: The spec and Firefox do not return a NodeList. They always return the first matching Element.
     returnValue0Enabled = true;
     returnValue0 = NamedNodesCollection::create(namedItems);
 }
 
-bool HTMLOptionsCollection::anonymousIndexedSetterRemove(unsigned index, ExceptionState& exceptionState)
-{
-    HTMLSelectElement* base = toHTMLSelectElement(ownerNode());
-    base->remove(index);
-    return true;
-}
-
 bool HTMLOptionsCollection::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& exceptionState)
 {
     HTMLSelectElement* base = toHTMLSelectElement(ownerNode());
-    if (!value) {
-        exceptionState.throwTypeError(ExceptionMessages::failedToSet(String::number(index), "HTMLOptionsCollection", "The element provided was not an HTMLOptionElement."));
+    if (!value) { // undefined or null
+        base->remove(index);
         return true;
     }
     base->setOption(index, value.get(), exceptionState);
diff --git a/Source/core/html/HTMLOptionsCollection.h b/Source/core/html/HTMLOptionsCollection.h
index fe5ad5d..55a591c 100644
--- a/Source/core/html/HTMLOptionsCollection.h
+++ b/Source/core/html/HTMLOptionsCollection.h
@@ -34,7 +34,7 @@
 
 class HTMLOptionsCollection FINAL : public HTMLCollection {
 public:
-    static PassRefPtr<HTMLOptionsCollection> create(Node*, CollectionType);
+    static PassRefPtr<HTMLOptionsCollection> create(ContainerNode*, CollectionType);
 
     void add(PassRefPtr<HTMLOptionElement>, ExceptionState&);
     void add(PassRefPtr<HTMLOptionElement>, int index, ExceptionState&);
@@ -45,12 +45,13 @@
     void setSelectedIndex(int);
 
     void setLength(unsigned, ExceptionState&);
-    void anonymousNamedGetter(const AtomicString& name, bool&, RefPtr<NodeList>&, bool&, RefPtr<Node>&);
+    void namedGetter(const AtomicString& name, bool&, RefPtr<NodeList>&, bool&, RefPtr<Element>&);
     bool anonymousIndexedSetter(unsigned, PassRefPtr<HTMLOptionElement>, ExceptionState&);
-    bool anonymousIndexedSetterRemove(unsigned, ExceptionState&);
 
 private:
-    explicit HTMLOptionsCollection(Node*);
+    explicit HTMLOptionsCollection(ContainerNode*);
+
+    virtual void supportedPropertyNames(Vector<String>& names) OVERRIDE;
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLOptionsCollection.idl b/Source/core/html/HTMLOptionsCollection.idl
index 32c4147..11d7673 100644
--- a/Source/core/html/HTMLOptionsCollection.idl
+++ b/Source/core/html/HTMLOptionsCollection.idl
@@ -1,7 +1,7 @@
 /*
  * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
  * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ * Copyright (C) 2013, 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -21,19 +21,17 @@
 
 [
     DependentLifetime,
-    GenerateVisitDOMWrapper=ownerNode,
+    SetWrapperReferenceFrom=ownerNode,
 ] interface HTMLOptionsCollection : HTMLCollection {
     attribute long selectedIndex;
     [Custom=Setter, RaisesException=Setter] attribute unsigned long length;
-    [ImplementedAs=item] getter Node(unsigned long index);
-    [ImplementedAs=anonymousIndexedSetter, RaisesException] setter HTMLOptionElement (unsigned long index, [TreatNullAs=anonymousIndexedSetterRemove, TreatUndefinedAs=anonymousIndexedSetterRemove] HTMLOptionElement value);
-    [ImplementedAs=anonymousNamedGetter, NotEnumerable] getter (NodeList or Node)(DOMString name);
+    [ImplementedAs=item] getter Node (unsigned long index);
+    [RaisesException, StrictTypeChecking] setter HTMLOptionElement (unsigned long index, HTMLOptionElement? value);
 
-    [Custom] Node namedItem([Default=Undefined] optional DOMString name);
+    // FIXME: The spec and firefox return an Element (the first matching Element).
+    [ImplementedAs=namedGetter] getter (NodeList or Element) namedItem(DOMString name);
 
-    [Custom, RaisesException] void add([Default=Undefined] optional HTMLOptionElement option,
-                      optional unsigned long index);
+    [Custom, RaisesException] void add([Default=Undefined] optional HTMLOptionElement option, optional unsigned long index);
     void remove(unsigned long index);
-    void remove(HTMLOptionElement option); // Non standard.
+    void remove(HTMLOptionElement option);  // non-standard
 };
-
diff --git a/Source/core/html/HTMLOutputElement.cpp b/Source/core/html/HTMLOutputElement.cpp
index 00d0435..6751780 100644
--- a/Source/core/html/HTMLOutputElement.cpp
+++ b/Source/core/html/HTMLOutputElement.cpp
@@ -75,7 +75,7 @@
     return m_tokens.get();
 }
 
-void HTMLOutputElement::setFor(const String& value)
+void HTMLOutputElement::setFor(const AtomicString& value)
 {
     m_tokens->setValue(value);
 }
diff --git a/Source/core/html/HTMLOutputElement.h b/Source/core/html/HTMLOutputElement.h
index bf1e469..92ad652 100644
--- a/Source/core/html/HTMLOutputElement.h
+++ b/Source/core/html/HTMLOutputElement.h
@@ -40,26 +40,26 @@
 public:
     static PassRefPtr<HTMLOutputElement> create(Document&, HTMLFormElement*);
 
-    virtual bool willValidate() const { return false; }
+    virtual bool willValidate() const OVERRIDE { return false; }
 
     String value() const;
     void setValue(const String&);
     String defaultValue() const;
     void setDefaultValue(const String&);
-    void setFor(const String&);
+    void setFor(const AtomicString&);
     DOMSettableTokenList* htmlFor() const;
 
-    virtual bool canContainRangeEndPoint() const { return false; }
+    virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
 
 private:
     HTMLOutputElement(Document&, HTMLFormElement*);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual const AtomicString& formControlType() const;
-    virtual bool isEnumeratable() const { return true; }
+    virtual const AtomicString& formControlType() const OVERRIDE;
+    virtual bool isEnumeratable() const OVERRIDE { return true; }
     virtual bool supportLabels() const OVERRIDE { return true; }
-    virtual bool supportsFocus() const;
-    virtual void childrenChanged(bool createdByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual bool supportsFocus() const OVERRIDE;
+    virtual void childrenChanged(bool createdByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
     virtual void resetImpl() OVERRIDE;
 
     void setTextContentInternal(const String&);
diff --git a/Source/core/html/HTMLParagraphElement.cpp b/Source/core/html/HTMLParagraphElement.cpp
index 4598008..6c6e643 100644
--- a/Source/core/html/HTMLParagraphElement.cpp
+++ b/Source/core/html/HTMLParagraphElement.cpp
@@ -42,13 +42,6 @@
     return adoptRef(new HTMLParagraphElement(document));
 }
 
-bool HTMLParagraphElement::isPresentationAttribute(const QualifiedName& name) const
-{
-    if (name == alignAttr)
-        return true;
-    return HTMLElement::isPresentationAttribute(name);
-}
-
 void HTMLParagraphElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
 {
     if (name == alignAttr) {
diff --git a/Source/core/html/HTMLParagraphElement.h b/Source/core/html/HTMLParagraphElement.h
index 4bfbbf6..ac83f03 100644
--- a/Source/core/html/HTMLParagraphElement.h
+++ b/Source/core/html/HTMLParagraphElement.h
@@ -34,7 +34,6 @@
 private:
     explicit HTMLParagraphElement(Document&);
 
-    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 };
 
diff --git a/Source/core/html/HTMLParamElement.cpp b/Source/core/html/HTMLParamElement.cpp
index 982d53d..a16e5cd 100644
--- a/Source/core/html/HTMLParamElement.cpp
+++ b/Source/core/html/HTMLParamElement.cpp
@@ -66,14 +66,4 @@
     return HTMLElement::isURLAttribute(attribute);
 }
 
-void HTMLParamElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLElement::addSubresourceAttributeURLs(urls);
-
-    if (!isURLParameter(name()))
-        return;
-
-    addSubresourceURL(urls, document().completeURL(value()));
-}
-
 }
diff --git a/Source/core/html/HTMLParamElement.h b/Source/core/html/HTMLParamElement.h
index 991e959..e7a709c 100644
--- a/Source/core/html/HTMLParamElement.h
+++ b/Source/core/html/HTMLParamElement.h
@@ -40,8 +40,6 @@
     explicit HTMLParamElement(Document&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
-
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
 };
 
 DEFINE_NODE_TYPE_CASTS(HTMLParamElement, hasTagName(HTMLNames::paramTag));
diff --git a/Source/core/html/HTMLPlugInElement.cpp b/Source/core/html/HTMLPlugInElement.cpp
index 7c29fdd..b3eb176 100644
--- a/Source/core/html/HTMLPlugInElement.cpp
+++ b/Source/core/html/HTMLPlugInElement.cpp
@@ -28,6 +28,7 @@
 #include "bindings/v8/ScriptController.h"
 #include "bindings/v8/npruntime_impl.h"
 #include "core/dom/Document.h"
+#include "core/dom/Node.h"
 #include "core/dom/PostAttachCallbacks.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/events/Event.h"
@@ -39,7 +40,7 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 #include "core/rendering/RenderImage.h"
@@ -128,6 +129,7 @@
         && !m_isDelayingLoadEvent) {
         m_isDelayingLoadEvent = true;
         document().incrementLoadEventDelayCount();
+        document().loadPluginsSoon();
     }
 }
 
@@ -200,7 +202,7 @@
 
     setNeedsWidgetUpdate(true);
     if (inDocument())
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 void HTMLPlugInElement::resetInstance()
@@ -318,11 +320,16 @@
 
 bool HTMLPlugInElement::isKeyboardFocusable() const
 {
-    if (!document().page())
+    if (!document().isActive())
         return false;
     return pluginWidget() && pluginWidget()->isPluginView() && toPluginView(pluginWidget())->supportsKeyboardFocus();
 }
 
+bool HTMLPlugInElement::hasCustomFocusLogic() const
+{
+    return !hasAuthorShadowRoot();
+}
+
 bool HTMLPlugInElement::isPluginElement() const
 {
     return true;
@@ -410,6 +417,8 @@
         return false;
 
     KURL completedURL = document().completeURL(url);
+    if (!pluginIsLoadable(completedURL, mimeType))
+        return false;
 
     bool useFallback;
     if (shouldUsePlugin(completedURL, mimeType, renderer->hasFallbackContent(), useFallback))
@@ -429,9 +438,6 @@
     if (!frame->loader().allowPlugins(AboutToInstantiatePlugin))
         return false;
 
-    if (!pluginIsLoadable(url, mimeType))
-        return false;
-
     RenderEmbeddedObject* renderer = renderEmbeddedObject();
     // FIXME: This code should not depend on renderer!
     if (!renderer || useFallback)
@@ -477,6 +483,14 @@
 
 }
 
+void HTMLPlugInElement::dispatchErrorEvent()
+{
+    if (document().isPluginDocument() && document().ownerElement())
+        document().ownerElement()->dispatchEvent(Event::create(EventTypeNames::error));
+    else
+        dispatchEvent(Event::create(EventTypeNames::error));
+}
+
 bool HTMLPlugInElement::pluginIsLoadable(const KURL& url, const String& mimeType)
 {
     Frame* frame = document().frame();
@@ -484,7 +498,7 @@
     if (!settings)
         return false;
 
-    if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType) && !settings->isJavaEnabled())
+    if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType) && !settings->javaEnabled())
         return false;
 
     if (document().isSandboxed(SandboxPlugins))
diff --git a/Source/core/html/HTMLPlugInElement.h b/Source/core/html/HTMLPlugInElement.h
index 33a69a0..c9b8fc9 100644
--- a/Source/core/html/HTMLPlugInElement.h
+++ b/Source/core/html/HTMLPlugInElement.h
@@ -61,7 +61,7 @@
 
     // Node functions:
     virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
-    virtual bool dispatchBeforeLoadEvent(const String& sourceURL) OVERRIDE;
+    virtual bool dispatchBeforeLoadEvent(const String& sourceURL) OVERRIDE FINAL;
 
     // Element functions:
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -79,6 +79,8 @@
     bool requestObject(const String& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues);
     bool shouldUsePlugin(const KURL&, const String& mimeType, bool hasFallback, bool& useFallback);
 
+    void dispatchErrorEvent();
+
     String m_serviceType;
     String m_url;
     KURL m_loadedUrl;
@@ -91,21 +93,24 @@
 
     // Node functions:
     virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
-    virtual bool willRespondToMouseClickEvents() OVERRIDE;
-    virtual void defaultEventHandler(Event*) OVERRIDE;
-    virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual void finishParsingChildren() OVERRIDE;
-    virtual bool isPluginElement() const OVERRIDE;
+    virtual bool willRespondToMouseClickEvents() OVERRIDE FINAL;
+    virtual void defaultEventHandler(Event*) OVERRIDE FINAL;
+    virtual void attach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
+    virtual void detach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
+    virtual void finishParsingChildren() OVERRIDE FINAL;
+    virtual bool isPluginElement() const OVERRIDE FINAL;
 
     // Element functions:
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE FINAL;
-    virtual bool supportsFocus() const OVERRIDE { return true; };
-    virtual bool rendererIsFocusable() const OVERRIDE;
-    virtual bool isKeyboardFocusable() const OVERRIDE;
-    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
-    virtual void didAddShadowRoot(ShadowRoot&) OVERRIDE;
+    virtual bool supportsFocus() const OVERRIDE FINAL { return true; }
+    virtual bool rendererIsFocusable() const OVERRIDE FINAL;
+    virtual bool isKeyboardFocusable() const OVERRIDE FINAL;
+    virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE FINAL;
+    virtual void didAddShadowRoot(ShadowRoot&) OVERRIDE FINAL;
+
+    // HTMLElement function:
+    virtual bool hasCustomFocusLogic() const OVERRIDE;
 
     // Return any existing RenderWidget without triggering relayout, or 0 if it
     // doesn't yet exist.
diff --git a/Source/core/html/HTMLProgressElement.cpp b/Source/core/html/HTMLProgressElement.cpp
index 3baeb65..e99cc86 100644
--- a/Source/core/html/HTMLProgressElement.cpp
+++ b/Source/core/html/HTMLProgressElement.cpp
@@ -101,7 +101,7 @@
 void HTMLProgressElement::setValue(double value, ExceptionState& exceptionState)
 {
     if (!std::isfinite(value)) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(value));
+        exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(value));
         return;
     }
     setFloatingPointAttribute(valueAttr, std::max(value, 0.));
@@ -116,7 +116,7 @@
 void HTMLProgressElement::setMax(double max, ExceptionState& exceptionState)
 {
     if (!std::isfinite(max)) {
-        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(max));
+        exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(max));
         return;
     }
     // FIXME: The specification says we should ignore the input value if it is inferior or equal to 0.
@@ -151,14 +151,14 @@
     ASSERT(!m_value);
 
     RefPtr<ProgressInnerElement> inner = ProgressInnerElement::create(document());
-    inner->setPseudo(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
+    inner->setShadowPseudoId(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
     root.appendChild(inner);
 
     RefPtr<ProgressBarElement> bar = ProgressBarElement::create(document());
-    bar->setPseudo(AtomicString("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
+    bar->setShadowPseudoId(AtomicString("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
     RefPtr<ProgressValueElement> value = ProgressValueElement::create(document());
     m_value = value.get();
-    m_value->setPseudo(AtomicString("-webkit-progress-value", AtomicString::ConstructFromLiteral));
+    m_value->setShadowPseudoId(AtomicString("-webkit-progress-value", AtomicString::ConstructFromLiteral));
     m_value->setWidthPercentage(HTMLProgressElement::IndeterminatePosition * 100);
     bar->appendChild(m_value);
 
diff --git a/Source/core/html/HTMLProgressElement.h b/Source/core/html/HTMLProgressElement.h
index 6162ded..4f33d24 100644
--- a/Source/core/html/HTMLProgressElement.h
+++ b/Source/core/html/HTMLProgressElement.h
@@ -44,7 +44,7 @@
 
     double position() const;
 
-    virtual bool canContainRangeEndPoint() const { return false; }
+    virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
 
 private:
     explicit HTMLProgressElement(Document&);
@@ -54,7 +54,7 @@
     virtual bool shouldAppearIndeterminate() const OVERRIDE;
     virtual bool supportLabels() const OVERRIDE { return true; }
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     RenderProgress* renderProgress() const;
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -68,12 +68,6 @@
     ProgressValueElement* m_value;
 };
 
-inline bool isHTMLProgressElement(Node* node)
-{
-    ASSERT(node);
-    return node->hasTagName(HTMLNames::progressTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLProgressElement, hasTagName(HTMLNames::progressTag));
 
 } // namespace
diff --git a/Source/core/html/HTMLRTElement.cpp b/Source/core/html/HTMLRTElement.cpp
new file mode 100644
index 0000000..4dcfb7d
--- /dev/null
+++ b/Source/core/html/HTMLRTElement.cpp
@@ -0,0 +1,32 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/html/HTMLRTElement.h"
+
+#include "HTMLNames.h"
+#include "core/rendering/RenderRubyText.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+HTMLRTElement::HTMLRTElement(Document& document)
+    : HTMLElement(rtTag, document)
+{
+}
+
+PassRefPtr<HTMLRTElement> HTMLRTElement::create(Document& document)
+{
+    return adoptRef(new HTMLRTElement(document));
+}
+
+RenderObject* HTMLRTElement::createRenderer(RenderStyle* style)
+{
+    if (style->display() == BLOCK)
+        return new RenderRubyText(this);
+    return RenderObject::createObject(this, style);
+}
+
+}
diff --git a/Source/core/html/HTMLRTElement.h b/Source/core/html/HTMLRTElement.h
new file mode 100644
index 0000000..55efc9a
--- /dev/null
+++ b/Source/core/html/HTMLRTElement.h
@@ -0,0 +1,26 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef HTMLRTElement_h
+#define HTMLRTElement_h
+
+#include "core/html/HTMLElement.h"
+
+namespace WebCore {
+
+// <rt> is an HTMLElement in script, but we use a separate interface here
+// so HTMLElement's createRenderer doesn't need to know about it.
+class HTMLRTElement FINAL : public HTMLElement {
+public:
+    static PassRefPtr<HTMLRTElement> create(Document&);
+
+private:
+    explicit HTMLRTElement(Document&);
+
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+};
+
+} // namespace
+
+#endif
diff --git a/Source/core/html/HTMLRubyElement.cpp b/Source/core/html/HTMLRubyElement.cpp
new file mode 100644
index 0000000..96eb941
--- /dev/null
+++ b/Source/core/html/HTMLRubyElement.cpp
@@ -0,0 +1,34 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/html/HTMLRubyElement.h"
+
+#include "HTMLNames.h"
+#include "core/rendering/RenderRuby.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+HTMLRubyElement::HTMLRubyElement(Document& document)
+    : HTMLElement(rubyTag, document)
+{
+}
+
+PassRefPtr<HTMLRubyElement> HTMLRubyElement::create(Document& document)
+{
+    return adoptRef(new HTMLRubyElement(document));
+}
+
+RenderObject* HTMLRubyElement::createRenderer(RenderStyle* style)
+{
+    if (style->display() == INLINE)
+        return new RenderRubyAsInline(this);
+    if (style->display() == BLOCK)
+        return new RenderRubyAsBlock(this);
+    return RenderObject::createObject(this, style);
+}
+
+}
diff --git a/Source/core/html/HTMLRubyElement.h b/Source/core/html/HTMLRubyElement.h
new file mode 100644
index 0000000..d7af56e
--- /dev/null
+++ b/Source/core/html/HTMLRubyElement.h
@@ -0,0 +1,26 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef HTMLRubyElement_h
+#define HTMLRubyElement_h
+
+#include "core/html/HTMLElement.h"
+
+namespace WebCore {
+
+// <ruby> is an HTMLElement in script, but we use a separate interface here
+// so HTMLElement's createRenderer doesn't need to know about it.
+class HTMLRubyElement FINAL : public HTMLElement {
+public:
+    static PassRefPtr<HTMLRubyElement> create(Document&);
+
+private:
+    explicit HTMLRubyElement(Document&);
+
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+};
+
+} // namespace
+
+#endif
diff --git a/Source/core/html/HTMLScriptElement.cpp b/Source/core/html/HTMLScriptElement.cpp
index fd54cc2..50afbd1 100644
--- a/Source/core/html/HTMLScriptElement.cpp
+++ b/Source/core/html/HTMLScriptElement.cpp
@@ -112,13 +112,6 @@
     return document().completeURL(sourceAttributeValue());
 }
 
-void HTMLScriptElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, src());
-}
-
 String HTMLScriptElement::sourceAttributeValue() const
 {
     return getAttribute(srcAttr).string();
diff --git a/Source/core/html/HTMLScriptElement.h b/Source/core/html/HTMLScriptElement.h
index d4e0efd..f02d51f 100644
--- a/Source/core/html/HTMLScriptElement.h
+++ b/Source/core/html/HTMLScriptElement.h
@@ -51,25 +51,23 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
+    virtual String sourceAttributeValue() const OVERRIDE;
+    virtual String charsetAttributeValue() const OVERRIDE;
+    virtual String typeAttributeValue() const OVERRIDE;
+    virtual String languageAttributeValue() const OVERRIDE;
+    virtual String forAttributeValue() const OVERRIDE;
+    virtual String eventAttributeValue() const OVERRIDE;
+    virtual bool asyncAttributeValue() const OVERRIDE;
+    virtual bool deferAttributeValue() const OVERRIDE;
+    virtual bool hasSourceAttribute() const OVERRIDE;
 
-    virtual String sourceAttributeValue() const;
-    virtual String charsetAttributeValue() const;
-    virtual String typeAttributeValue() const;
-    virtual String languageAttributeValue() const;
-    virtual String forAttributeValue() const;
-    virtual String eventAttributeValue() const;
-    virtual bool asyncAttributeValue() const;
-    virtual bool deferAttributeValue() const;
-    virtual bool hasSourceAttribute() const;
+    virtual void dispatchLoadEvent() OVERRIDE;
 
-    virtual void dispatchLoadEvent();
-
-    virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren();
+    virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren() OVERRIDE;
 
     OwnPtr<ScriptLoader> m_loader;
 };
diff --git a/Source/core/html/HTMLScriptElement.idl b/Source/core/html/HTMLScriptElement.idl
index 1f1e260..b8c367a 100644
--- a/Source/core/html/HTMLScriptElement.idl
+++ b/Source/core/html/HTMLScriptElement.idl
@@ -26,6 +26,6 @@
     [Reflect] attribute boolean defer;
     [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
     [Reflect] attribute DOMString type;
-    [Reflect] attribute DOMString crossOrigin;
+    [Reflect, ReflectOnly="anonymous"|"use-credentials", ReflectEmpty="anonymous", ReflectInvalid="anonymous"] attribute DOMString crossOrigin;
     [Reflect, RuntimeEnabled=ExperimentalContentSecurityPolicyFeatures] attribute DOMString nonce;
 };
diff --git a/Source/core/html/HTMLSelectElement.cpp b/Source/core/html/HTMLSelectElement.cpp
index 92cc401..1f74f02 100644
--- a/Source/core/html/HTMLSelectElement.cpp
+++ b/Source/core/html/HTMLSelectElement.cpp
@@ -41,12 +41,10 @@
 #include "core/events/ThreadLocalEventNames.h"
 #include "core/html/FormDataList.h"
 #include "core/html/HTMLFormElement.h"
-#include "core/html/HTMLOptGroupElement.h"
 #include "core/html/HTMLOptionElement.h"
 #include "core/html/forms/FormController.h"
 #include "core/page/EventHandler.h"
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
 #include "core/page/SpatialNavigation.h"
 #include "core/rendering/RenderListBox.h"
 #include "core/rendering/RenderMenuList.h"
@@ -64,7 +62,7 @@
 // Upper limit agreed upon with representatives of Opera and Mozilla.
 static const unsigned maxSelectItems = 10000;
 
-HTMLSelectElement::HTMLSelectElement(Document& document, HTMLFormElement* form, bool createdByParser)
+HTMLSelectElement::HTMLSelectElement(Document& document, HTMLFormElement* form)
     : HTMLFormControlElementWithState(selectTag, document, form)
     , m_typeAhead(this)
     , m_size(0)
@@ -75,19 +73,18 @@
     , m_multiple(false)
     , m_activeSelectionState(false)
     , m_shouldRecalcListItems(false)
-    , m_isParsingInProgress(createdByParser)
 {
     ScriptWrappable::init(this);
 }
 
 PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(Document& document)
 {
-    return adoptRef(new HTMLSelectElement(document, 0, false));
+    return adoptRef(new HTMLSelectElement(document, 0));
 }
 
-PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(Document& document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(Document& document, HTMLFormElement* form)
 {
-    return adoptRef(new HTMLSelectElement(document, form, createdByParser));
+    return adoptRef(new HTMLSelectElement(document, form));
 }
 
 const AtomicString& HTMLSelectElement::formControlType() const
@@ -97,12 +94,6 @@
     return m_multiple ? selectMultiple : selectOne;
 }
 
-void HTMLSelectElement::deselectItems(HTMLOptionElement* excludeElement)
-{
-    deselectItemsWithoutValidation(excludeElement);
-    setNeedsValidityCheck();
-}
-
 void HTMLSelectElement::optionSelectedByUser(int optionIndex, bool fireOnChangeNow, bool allowMultipleSelection)
 {
     // User interaction such as mousedown events can cause list box select elements to send change events.
@@ -332,15 +323,6 @@
     return new RenderListBox(this);
 }
 
-bool HTMLSelectElement::childShouldCreateRenderer(const Node& child) const
-{
-    if (!HTMLFormControlElementWithState::childShouldCreateRenderer(child))
-        return false;
-    if (!usesMenuList())
-        return child.hasTagName(HTMLNames::optionTag) || isHTMLOptGroupElement(&child);
-    return false;
-}
-
 PassRefPtr<HTMLCollection> HTMLSelectElement::selectedOptions()
 {
     updateListItemSelectedStates();
@@ -403,12 +385,12 @@
     setIntegralAttribute(sizeAttr, size);
 }
 
-Node* HTMLSelectElement::namedItem(const AtomicString& name)
+Element* HTMLSelectElement::namedItem(const AtomicString& name)
 {
     return options()->namedItem(name);
 }
 
-Node* HTMLSelectElement::item(unsigned index)
+Element* HTMLSelectElement::item(unsigned index)
 {
     return options()->item(index);
 }
@@ -712,7 +694,7 @@
     // Manual selection anchor is reset when manipulating the select programmatically.
     m_activeSelectionAnchorIndex = -1;
     setOptionsChangedOnRenderer();
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
     if (!inDocument()) {
         if (HTMLCollection* collection = cachedHTMLCollection(SelectOptions))
             collection->invalidateCache();
@@ -744,7 +726,7 @@
         // optgroup tags may not nest. However, both FireFox and IE will
         // flatten the tree automatically, so we follow suit.
         // (http://www.w3.org/TR/html401/interact/forms.html#h-17.6)
-        if (isHTMLOptGroupElement(current)) {
+        if (current.hasTagName(optgroupTag)) {
             m_listItems.append(&current);
             if (Element* nextElement = ElementTraversal::firstWithin(current)) {
                 currentElement = nextElement;
@@ -899,13 +881,13 @@
     return optionIndex;
 }
 
-void HTMLSelectElement::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection direction)
+void HTMLSelectElement::dispatchFocusEvent(Element* oldFocusedElement, FocusType type)
 {
     // Save the selection so it can be compared to the new selection when
     // dispatching change events during blur event dispatch.
     if (usesMenuList())
         saveLastSelection();
-    HTMLFormControlElementWithState::dispatchFocusEvent(oldFocusedElement, direction);
+    HTMLFormControlElementWithState::dispatchFocusEvent(oldFocusedElement, type);
 }
 
 void HTMLSelectElement::dispatchBlurEvent(Element* newFocusedElement)
@@ -1055,7 +1037,7 @@
         firstOption->setSelectedState(true);
 
     setOptionsChangedOnRenderer();
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
     setNeedsValidityCheck();
 }
 
@@ -1279,7 +1261,7 @@
 void HTMLSelectElement::listBoxDefaultEventHandler(Event* event)
 {
     const Vector<HTMLElement*>& listItems = this->listItems();
-
+    bool dragSelection = false;
     if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         focus();
         // Calling focus() may cause us to lose our renderer, in which case do not want to handle the event.
@@ -1325,7 +1307,7 @@
                     updateListBoxSelection(true);
                 }
             }
-            event->setDefaultHandled();
+            dragSelection = true;
         }
     } else if (event->type() == EventTypeNames::mouseup && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton && renderer() && !toRenderBox(renderer())->autoscrollInProgress()) {
         // We didn't start this click/drag on any options.
@@ -1334,7 +1316,9 @@
         // This makes sure we fire dispatchFormControlChangeEvent for a single
         // click. For drag selection, onChange will fire when the autoscroll
         // timer stops.
-        listBoxOnChange();
+        if (!dragSelection) {
+            listBoxOnChange();
+        }
     } else if (event->type() == EventTypeNames::keydown) {
         if (!event->isKeyboardEvent())
             return;
@@ -1559,27 +1543,25 @@
 void HTMLSelectElement::finishParsingChildren()
 {
     HTMLFormControlElementWithState::finishParsingChildren();
-    m_isParsingInProgress = false;
     updateListItemSelectedStates();
 }
 
 bool HTMLSelectElement::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& exceptionState)
 {
-    if (!value) {
-        exceptionState.throwTypeError(ExceptionMessages::failedToSet(String::number(index), "HTMLSelectElement", "The value provided was not an HTMLOptionElement."));
-        return false;
+    if (!value) { // undefined or null
+        remove(index);
+        return true;
     }
     setOption(index, value.get(), exceptionState);
     return true;
 }
 
-bool HTMLSelectElement::anonymousIndexedSetterRemove(unsigned index, ExceptionState& exceptionState)
+bool HTMLSelectElement::isInteractiveContent() const
 {
-    remove(index);
     return true;
 }
 
-bool HTMLSelectElement::isInteractiveContent() const
+bool HTMLSelectElement::supportsAutofocus() const
 {
     return true;
 }
diff --git a/Source/core/html/HTMLSelectElement.h b/Source/core/html/HTMLSelectElement.h
index 7564360..f4c205e 100644
--- a/Source/core/html/HTMLSelectElement.h
+++ b/Source/core/html/HTMLSelectElement.h
@@ -40,7 +40,7 @@
 class HTMLSelectElement FINAL : public HTMLFormControlElementWithState, public TypeAheadDataSource {
 public:
     static PassRefPtr<HTMLSelectElement> create(Document&);
-    static PassRefPtr<HTMLSelectElement> create(Document&, HTMLFormElement*, bool createdByParser);
+    static PassRefPtr<HTMLSelectElement> create(Document&, HTMLFormElement*);
 
     int selectedIndex() const;
     void setSelectedIndex(int);
@@ -80,7 +80,7 @@
 
     const Vector<HTMLElement*>& listItems() const;
 
-    virtual void accessKeyAction(bool sendMouseEvents);
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
     void accessKeySetSelectedIndex(int);
 
     void setMultiple(bool);
@@ -90,8 +90,8 @@
     void setOption(unsigned index, HTMLOptionElement*, ExceptionState&);
     void setLength(unsigned, ExceptionState&);
 
-    Node* namedItem(const AtomicString& name);
-    Node* item(unsigned index);
+    Element* namedItem(const AtomicString& name);
+    Element* item(unsigned index);
 
     void scrollToSelection();
 
@@ -110,25 +110,24 @@
 
     // For use in the implementation of HTMLOptionElement.
     void optionSelectionStateChanged(HTMLOptionElement*, bool optionIsSelected);
-    bool isParsingInProgress() const { return m_isParsingInProgress; }
     bool anonymousIndexedSetter(unsigned, PassRefPtr<HTMLOptionElement>, ExceptionState&);
-    bool anonymousIndexedSetterRemove(unsigned, ExceptionState&);
 
 protected:
-    HTMLSelectElement(Document&, HTMLFormElement*, bool createdByParser);
+    HTMLSelectElement(Document&, HTMLFormElement*);
 
 private:
-    virtual const AtomicString& formControlType() const;
+    virtual const AtomicString& formControlType() const OVERRIDE;
 
     virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
 
-    virtual void dispatchFocusEvent(Element* oldFocusedElement, FocusDirection) OVERRIDE;
+    virtual void dispatchFocusEvent(Element* oldFocusedElement, FocusType) OVERRIDE;
     virtual void dispatchBlurEvent(Element* newFocusedElemnet) OVERRIDE;
 
-    virtual bool canStartSelection() const { return false; }
+    virtual bool canStartSelection() const OVERRIDE { return false; }
 
-    virtual bool isEnumeratable() const { return true; }
+    virtual bool isEnumeratable() const OVERRIDE { return true; }
     virtual bool isInteractiveContent() const OVERRIDE;
+    virtual bool supportsAutofocus() const OVERRIDE;
     virtual bool supportLabels() const OVERRIDE { return true; }
 
     virtual FormControlState saveFormControlState() const OVERRIDE;
@@ -137,24 +136,22 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
 
-    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
-    virtual RenderObject* createRenderer(RenderStyle *);
-    virtual bool appendFormData(FormDataList&, bool);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual bool appendFormData(FormDataList&, bool) OVERRIDE;
 
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
 
     void dispatchChangeEventForMenuList();
 
     void recalcListItems(bool updateSelectedStates = true) const;
 
-    void deselectItems(HTMLOptionElement* excludeElement = 0);
     void typeAheadFind(KeyboardEvent*);
     void saveLastSelection();
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
 
-    virtual bool isOptionalFormControl() const { return !isRequiredFormControl(); }
-    virtual bool isRequiredFormControl() const;
+    virtual bool isOptionalFormControl() const OVERRIDE { return !isRequiredFormControl(); }
+    virtual bool isRequiredFormControl() const OVERRIDE;
 
     bool hasPlaceholderLabelOption() const;
 
@@ -186,7 +183,7 @@
     int lastSelectableListIndex() const;
     int nextSelectableListIndexPageAway(int startIndex, SkipDirection) const;
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
     virtual void finishParsingChildren() OVERRIDE;
 
@@ -208,7 +205,6 @@
     bool m_multiple;
     bool m_activeSelectionState;
     mutable bool m_shouldRecalcListItems;
-    bool m_isParsingInProgress;
 };
 
 DEFINE_NODE_TYPE_CASTS(HTMLSelectElement, hasTagName(HTMLNames::selectTag));
diff --git a/Source/core/html/HTMLSelectElement.idl b/Source/core/html/HTMLSelectElement.idl
index b61f512..3104a3f 100644
--- a/Source/core/html/HTMLSelectElement.idl
+++ b/Source/core/html/HTMLSelectElement.idl
@@ -33,13 +33,13 @@
     readonly attribute HTMLOptionsCollection options;
     [RaisesException=Setter] attribute unsigned long length;
 
-    getter Node item(unsigned long index);
-    [ImplementedAs=anonymousIndexedSetter, RaisesException] setter HTMLOptionElement (unsigned long index, [TreatNullAs=anonymousIndexedSetterRemove, TreatUndefinedAs=anonymousIndexedSetterRemove] HTMLOptionElement value);
-    Node namedItem([Default=Undefined] optional DOMString name);
-     [RaisesException] void add([Default=Undefined] optional HTMLElement element,
-                            [Default=Undefined] optional HTMLElement before);
+    getter Element item(unsigned long index);
+    [RaisesException, StrictTypeChecking] setter HTMLOptionElement (unsigned long index, HTMLOptionElement? value);
+    Element namedItem([Default=Undefined] optional DOMString name);
+    [RaisesException] void add([Default=Undefined] optional HTMLElement element,
+                               [Default=Undefined] optional HTMLElement before);
     void remove(long index);
-    void remove(HTMLOptionElement option); // Non standard.
+    void remove(HTMLOptionElement option);  // non-standard
     [RaisesException] void remove();
     readonly attribute HTMLCollection selectedOptions;
     attribute long selectedIndex;
diff --git a/Source/core/html/HTMLSourceElement.idl b/Source/core/html/HTMLSourceElement.idl
index 4e10349..9d86da4 100644
--- a/Source/core/html/HTMLSourceElement.idl
+++ b/Source/core/html/HTMLSourceElement.idl
@@ -28,5 +28,5 @@
 ] interface HTMLSourceElement : HTMLElement {
     [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
     attribute DOMString type;
-    attribute DOMString media;
+    [DeprecateAs=HTMLSourceElementMedia] attribute DOMString media;
 };
diff --git a/Source/core/html/HTMLStyleElement.cpp b/Source/core/html/HTMLStyleElement.cpp
index c3d7e1c..ff66523 100644
--- a/Source/core/html/HTMLStyleElement.cpp
+++ b/Source/core/html/HTMLStyleElement.cpp
@@ -270,14 +270,6 @@
     m_firedLoad = true;
 }
 
-void HTMLStyleElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLElement::addSubresourceAttributeURLs(urls);
-
-    if (CSSStyleSheet* styleSheet = const_cast<HTMLStyleElement*>(this)->sheet())
-        styleSheet->contents()->addSubresourceStyleURLs(urls);
-}
-
 bool HTMLStyleElement::disabled() const
 {
     if (!m_sheet)
diff --git a/Source/core/html/HTMLStyleElement.h b/Source/core/html/HTMLStyleElement.h
index 3ab95c6..01a10e4 100644
--- a/Source/core/html/HTMLStyleElement.h
+++ b/Source/core/html/HTMLStyleElement.h
@@ -74,19 +74,16 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual void finishParsingChildren();
+    virtual void finishParsingChildren() OVERRIDE;
 
-    virtual bool isLoading() const { return StyleElement::isLoading(); }
-    virtual bool sheetLoaded() { return StyleElement::sheetLoaded(document()); }
-    virtual void notifyLoadedSheetAndAllCriticalSubresources(bool errorOccurred);
-    virtual void startLoadingDynamicSheet() { StyleElement::startLoadingDynamicSheet(document()); }
+    virtual bool sheetLoaded() OVERRIDE { return StyleElement::sheetLoaded(document()); }
+    virtual void notifyLoadedSheetAndAllCriticalSubresources(bool errorOccurred) OVERRIDE;
+    virtual void startLoadingDynamicSheet() OVERRIDE { StyleElement::startLoadingDynamicSheet(document()); }
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-
-    virtual const AtomicString& media() const;
-    virtual const AtomicString& type() const;
+    virtual const AtomicString& media() const OVERRIDE;
+    virtual const AtomicString& type() const OVERRIDE;
 
     void scopedAttributeChanged(bool);
     void registerWithScopingNode(bool);
@@ -103,12 +100,6 @@
     ScopedStyleRegistrationState m_scopedStyleRegistrationState;
 };
 
-inline bool isHTMLStyleElement(Node* node)
-{
-    ASSERT(node);
-    return node->hasTagName(HTMLNames::styleTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLStyleElement, hasTagName(HTMLNames::styleTag));
 
 } //namespace
diff --git a/Source/core/html/HTMLSummaryElement.cpp b/Source/core/html/HTMLSummaryElement.cpp
index 7f13462..7c19001 100644
--- a/Source/core/html/HTMLSummaryElement.cpp
+++ b/Source/core/html/HTMLSummaryElement.cpp
@@ -61,7 +61,7 @@
 HTMLDetailsElement* HTMLSummaryElement::detailsElement() const
 {
     Node* parent = NodeRenderingTraversal::parent(this);
-    if (parent && isHTMLDetailsElement(parent))
+    if (parent && parent->hasTagName(detailsTag))
         return toHTMLDetailsElement(parent);
     return 0;
 }
diff --git a/Source/core/html/HTMLSummaryElement.h b/Source/core/html/HTMLSummaryElement.h
index 45f1463..1eebc5b 100644
--- a/Source/core/html/HTMLSummaryElement.h
+++ b/Source/core/html/HTMLSummaryElement.h
@@ -36,12 +36,12 @@
 private:
     explicit HTMLSummaryElement(Document&);
 
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual void defaultEventHandler(Event*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual void defaultEventHandler(Event*) OVERRIDE;
     virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
     HTMLDetailsElement* detailsElement() const;
 
-    bool supportsFocus() const OVERRIDE;
+    virtual bool supportsFocus() const OVERRIDE;
 };
 
 DEFINE_NODE_TYPE_CASTS(HTMLSummaryElement, hasTagName(HTMLNames::summaryTag));
diff --git a/Source/core/html/HTMLTableCaptionElement.cpp b/Source/core/html/HTMLTableCaptionElement.cpp
index 0212e32..bea0640 100644
--- a/Source/core/html/HTMLTableCaptionElement.cpp
+++ b/Source/core/html/HTMLTableCaptionElement.cpp
@@ -43,13 +43,6 @@
     return adoptRef(new HTMLTableCaptionElement(document));
 }
 
-bool HTMLTableCaptionElement::isPresentationAttribute(const QualifiedName& name) const
-{
-    if (name == alignAttr)
-        return true;
-    return HTMLElement::isPresentationAttribute(name);
-}
-
 void HTMLTableCaptionElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
 {
     if (name == alignAttr) {
diff --git a/Source/core/html/HTMLTableCaptionElement.h b/Source/core/html/HTMLTableCaptionElement.h
index 33315ac..bd3bdf4 100644
--- a/Source/core/html/HTMLTableCaptionElement.h
+++ b/Source/core/html/HTMLTableCaptionElement.h
@@ -37,7 +37,6 @@
 private:
     HTMLTableCaptionElement(Document&);
 
-    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 };
 
diff --git a/Source/core/html/HTMLTableCellElement.cpp b/Source/core/html/HTMLTableCellElement.cpp
index 01b7125..8331963 100644
--- a/Source/core/html/HTMLTableCellElement.cpp
+++ b/Source/core/html/HTMLTableCellElement.cpp
@@ -132,12 +132,12 @@
 
 const AtomicString& HTMLTableCellElement::abbr() const
 {
-    return getAttribute(abbrAttr);
+    return fastGetAttribute(abbrAttr);
 }
 
 const AtomicString& HTMLTableCellElement::axis() const
 {
-    return getAttribute(axisAttr);
+    return fastGetAttribute(axisAttr);
 }
 
 void HTMLTableCellElement::setColSpan(int n)
@@ -147,7 +147,7 @@
 
 const AtomicString& HTMLTableCellElement::headers() const
 {
-    return getAttribute(headersAttr);
+    return fastGetAttribute(headersAttr);
 }
 
 void HTMLTableCellElement::setRowSpan(int n)
@@ -157,14 +157,7 @@
 
 const AtomicString& HTMLTableCellElement::scope() const
 {
-    return getAttribute(scopeAttr);
-}
-
-void HTMLTableCellElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLTablePartElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, document().completeURL(getAttribute(backgroundAttr)));
+    return fastGetAttribute(scopeAttr);
 }
 
 HTMLTableCellElement* HTMLTableCellElement::cellAbove() const
diff --git a/Source/core/html/HTMLTableCellElement.h b/Source/core/html/HTMLTableCellElement.h
index 8c22ccc..0ccc3ed 100644
--- a/Source/core/html/HTMLTableCellElement.h
+++ b/Source/core/html/HTMLTableCellElement.h
@@ -59,8 +59,6 @@
     virtual const StylePropertySet* additionalPresentationAttributeStyle() OVERRIDE;
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
-
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
 };
 
 inline bool isHTMLTableCellElement(const Node& node)
diff --git a/Source/core/html/HTMLTableElement.cpp b/Source/core/html/HTMLTableElement.cpp
index c963c1f..e1c9014 100644
--- a/Source/core/html/HTMLTableElement.cpp
+++ b/Source/core/html/HTMLTableElement.cpp
@@ -271,7 +271,7 @@
     }
 
     if (cellChanged)
-       n->setNeedsStyleRecalc();
+        n->setNeedsStyleRecalc(SubtreeStyleChange);
 
     return cellChanged;
 }
@@ -318,7 +318,7 @@
     else if (name == backgroundAttr) {
         String url = stripLeadingAndTrailingHTMLSpaces(value);
         if (!url.isEmpty())
-            style->setProperty(CSSProperty(CSSPropertyBackgroundImage, CSSImageValue::create(document().completeURL(url).string())));
+            style->setProperty(CSSProperty(CSSPropertyBackgroundImage, CSSImageValue::create(document().completeURL(url))));
     } else if (name == valignAttr) {
         if (!value.isEmpty())
             addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, value);
@@ -411,7 +411,7 @@
         for (Node* child = firstChild(); child; child = child->nextSibling())
             cellChanged |= setTableCellsChanged(child);
         if (cellChanged)
-            setNeedsStyleRecalc();
+            setNeedsStyleRecalc(SubtreeStyleChange);
     }
 }
 
@@ -573,11 +573,4 @@
     return getAttribute(summaryAttr);
 }
 
-void HTMLTableElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    HTMLElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, document().completeURL(getAttribute(backgroundAttr)));
-}
-
 }
diff --git a/Source/core/html/HTMLTableElement.h b/Source/core/html/HTMLTableElement.h
index d25a23c..7b5dd49 100644
--- a/Source/core/html/HTMLTableElement.h
+++ b/Source/core/html/HTMLTableElement.h
@@ -79,8 +79,6 @@
     // Used to obtain either a solid or outset border decl and to deal with the frame and rules attributes.
     virtual const StylePropertySet* additionalPresentationAttributeStyle() OVERRIDE;
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-
     enum TableRules { UnsetRules, NoneRules, GroupsRules, RowsRules, ColsRules, AllRules };
     enum CellBorders { NoBorders, SolidBorders, InsetBorders, SolidBordersColsOnly, SolidBordersRowsOnly };
 
@@ -100,16 +98,6 @@
     RefPtr<StylePropertySet> m_sharedCellStyle;
 };
 
-inline bool isHTMLTableElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::tableTag);
-}
-
-inline bool isHTMLTableElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::tableTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLTableElement, hasTagName(HTMLNames::tableTag));
 
 } //namespace
diff --git a/Source/core/html/HTMLTablePartElement.cpp b/Source/core/html/HTMLTablePartElement.cpp
index 79b2b6c..06d86f7 100644
--- a/Source/core/html/HTMLTablePartElement.cpp
+++ b/Source/core/html/HTMLTablePartElement.cpp
@@ -53,7 +53,7 @@
     else if (name == backgroundAttr) {
         String url = stripLeadingAndTrailingHTMLSpaces(value);
         if (!url.isEmpty())
-            style->setProperty(CSSProperty(CSSPropertyBackgroundImage, CSSImageValue::create(document().completeURL(url).string())));
+            style->setProperty(CSSProperty(CSSPropertyBackgroundImage, CSSImageValue::create(document().completeURL(url))));
     } else if (name == valignAttr) {
         if (equalIgnoringCase(value, "top"))
             addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, CSSValueTop);
@@ -86,7 +86,7 @@
 HTMLTableElement* HTMLTablePartElement::findParentTable() const
 {
     ContainerNode* parent = NodeRenderingTraversal::parent(this);
-    while (parent && !isHTMLTableElement(parent))
+    while (parent && !parent->hasTagName(tableTag))
         parent = NodeRenderingTraversal::parent(parent);
     return toHTMLTableElement(parent);
 }
diff --git a/Source/core/html/HTMLTableRowElement.cpp b/Source/core/html/HTMLTableRowElement.cpp
index b643924..c54defc 100644
--- a/Source/core/html/HTMLTableRowElement.cpp
+++ b/Source/core/html/HTMLTableRowElement.cpp
@@ -54,7 +54,7 @@
     if (!table)
         return -1;
     table = table->parentNode();
-    if (!table || !isHTMLTableElement(table))
+    if (!table || !table->hasTagName(tableTag))
         return -1;
 
     // To match Firefox, the row indices work like this:
@@ -142,7 +142,7 @@
     if (index == -1)
         index = numCells-1;
     if (index >= 0 && index < numCells) {
-        RefPtr<Node> cell = children->item(index);
+        RefPtr<Element> cell = children->item(index);
         HTMLElement::removeChild(cell.get(), exceptionState);
     } else {
         exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(index) + ") is outside the range [0, " + String::number(numCells) + ").");
diff --git a/Source/core/html/HTMLTableRowElement.h b/Source/core/html/HTMLTableRowElement.h
index 1fe3867..9bd824c 100644
--- a/Source/core/html/HTMLTableRowElement.h
+++ b/Source/core/html/HTMLTableRowElement.h
@@ -49,11 +49,6 @@
     explicit HTMLTableRowElement(Document&);
 };
 
-inline bool isHTMLTableRowElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::trTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLTableRowElement, hasTagName(HTMLNames::trTag));
 
 } // namespace
diff --git a/Source/core/html/HTMLTableRowsCollection.cpp b/Source/core/html/HTMLTableRowsCollection.cpp
index 3037aff..ae67c03 100644
--- a/Source/core/html/HTMLTableRowsCollection.cpp
+++ b/Source/core/html/HTMLTableRowsCollection.cpp
@@ -30,6 +30,7 @@
 #include "core/html/HTMLTableRowsCollection.h"
 
 #include "HTMLNames.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/html/HTMLTableElement.h"
 #include "core/html/HTMLTableRowElement.h"
 
@@ -52,62 +53,65 @@
     return row->parentNode() && toElement(row->parentNode())->hasLocalName(tfootTag);
 }
 
+static inline HTMLTableRowElement* findTableRowElementInChildren(Element& current)
+{
+    for (Element* child = ElementTraversal::firstWithin(current); child; child = ElementTraversal::nextSibling(*child)) {
+        if (child->hasTagName(trTag))
+            return toHTMLTableRowElement(child);
+    }
+    return 0;
+}
+
 HTMLTableRowElement* HTMLTableRowsCollection::rowAfter(HTMLTableElement* table, HTMLTableRowElement* previous)
 {
-    Node* child = 0;
+    Element* child = 0;
 
     // Start by looking for the next row in this section.
     // Continue only if there is none.
     if (previous && previous->parentNode() != table) {
-        for (child = previous->nextSibling(); child; child = child->nextSibling()) {
-            if (isHTMLTableRowElement(child))
+        for (child = ElementTraversal::nextSibling(*previous); child; child = ElementTraversal::nextSibling(*child)) {
+            if (child->hasTagName(trTag))
                 return toHTMLTableRowElement(child);
         }
     }
 
     // If still looking at head sections, find the first row in the next head section.
     if (!previous)
-        child = table->firstChild();
+        child = ElementTraversal::firstWithin(*table);
     else if (isInHead(previous))
-        child = previous->parentNode()->nextSibling();
-    for (; child; child = child->nextSibling()) {
+        child = ElementTraversal::nextSibling(*previous->parentNode());
+    for (; child; child = ElementTraversal::nextSibling(*child)) {
         if (child->hasTagName(theadTag)) {
-            for (Node* grandchild = child->firstChild(); grandchild; grandchild = grandchild->nextSibling()) {
-                if (isHTMLTableRowElement(grandchild))
-                    return toHTMLTableRowElement(grandchild);
-            }
+            if (HTMLTableRowElement* row = findTableRowElementInChildren(*child))
+                return row;
         }
     }
 
     // If still looking at top level and bodies, find the next row in top level or the first in the next body section.
     if (!previous || isInHead(previous))
-        child = table->firstChild();
+        child = ElementTraversal::firstWithin(*table);
     else if (previous->parentNode() == table)
-        child = previous->nextSibling();
+        child = ElementTraversal::nextSibling(*previous);
     else if (isInBody(previous))
-        child = previous->parentNode()->nextSibling();
-    for (; child; child = child->nextSibling()) {
-        if (isHTMLTableRowElement(child))
+        child = ElementTraversal::nextSibling(*previous->parentNode());
+    for (; child; child = ElementTraversal::nextSibling(*child)) {
+        if (child->hasTagName(trTag))
             return toHTMLTableRowElement(child);
         if (child->hasTagName(tbodyTag)) {
-            for (Node* grandchild = child->firstChild(); grandchild; grandchild = grandchild->nextSibling()) {
-                if (isHTMLTableRowElement(grandchild))
-                    return toHTMLTableRowElement(grandchild);
-            }
+            if (HTMLTableRowElement* row = findTableRowElementInChildren(*child))
+                return row;
         }
     }
 
     // Find the first row in the next foot section.
     if (!previous || !isInFoot(previous))
-        child = table->firstChild();
+        child = ElementTraversal::firstWithin(*table);
     else
-        child = previous->parentNode()->nextSibling();
-    for (; child; child = child->nextSibling()) {
+        child = ElementTraversal::nextSibling(*previous->parentNode());
+    for (; child; child = ElementTraversal::nextSibling(*child)) {
         if (child->hasTagName(tfootTag)) {
-            for (Node* grandchild = child->firstChild(); grandchild; grandchild = grandchild->nextSibling()) {
-                if (isHTMLTableRowElement(grandchild))
-                    return toHTMLTableRowElement(grandchild);
-            }
+            if (HTMLTableRowElement* row = findTableRowElementInChildren(*child))
+                return row;
         }
     }
 
@@ -119,18 +123,18 @@
     for (Node* child = table->lastChild(); child; child = child->previousSibling()) {
         if (child->hasTagName(tfootTag)) {
             for (Node* grandchild = child->lastChild(); grandchild; grandchild = grandchild->previousSibling()) {
-                if (isHTMLTableRowElement(grandchild))
+                if (grandchild->hasTagName(trTag))
                     return toHTMLTableRowElement(grandchild);
             }
         }
     }
 
     for (Node* child = table->lastChild(); child; child = child->previousSibling()) {
-        if (isHTMLTableRowElement(child))
+        if (child->hasTagName(trTag))
             return toHTMLTableRowElement(child);
         if (child->hasTagName(tbodyTag)) {
             for (Node* grandchild = child->lastChild(); grandchild; grandchild = grandchild->previousSibling()) {
-                if (isHTMLTableRowElement(grandchild))
+                if (grandchild->hasTagName(trTag))
                     return toHTMLTableRowElement(grandchild);
             }
         }
@@ -139,7 +143,7 @@
     for (Node* child = table->lastChild(); child; child = child->previousSibling()) {
         if (child->hasTagName(theadTag)) {
             for (Node* grandchild = child->lastChild(); grandchild; grandchild = grandchild->previousSibling()) {
-                if (isHTMLTableRowElement(grandchild))
+                if (grandchild->hasTagName(trTag))
                     return toHTMLTableRowElement(grandchild);
             }
         }
@@ -151,20 +155,19 @@
 // Must call get() on the table in case that argument is compiled before dereferencing the
 // table to get at the collection cache. Order of argument evaluation is undefined and can
 // differ between compilers.
-HTMLTableRowsCollection::HTMLTableRowsCollection(Node* table)
+HTMLTableRowsCollection::HTMLTableRowsCollection(ContainerNode* table)
     : HTMLCollection(table, TableRows, OverridesItemAfter)
 {
-    ASSERT(isHTMLTableElement(table));
+    ASSERT(table->hasTagName(tableTag));
 }
 
-PassRefPtr<HTMLTableRowsCollection> HTMLTableRowsCollection::create(Node* table, CollectionType)
+PassRefPtr<HTMLTableRowsCollection> HTMLTableRowsCollection::create(ContainerNode* table, CollectionType)
 {
     return adoptRef(new HTMLTableRowsCollection(table));
 }
 
-Element* HTMLTableRowsCollection::virtualItemAfter(unsigned& offsetInArray, Element* previous) const
+Element* HTMLTableRowsCollection::virtualItemAfter(Element* previous) const
 {
-    ASSERT_UNUSED(offsetInArray, !offsetInArray);
     return rowAfter(toHTMLTableElement(ownerNode()), toHTMLTableRowElement(previous));
 }
 
diff --git a/Source/core/html/HTMLTableRowsCollection.h b/Source/core/html/HTMLTableRowsCollection.h
index d643d43..e7324b2 100644
--- a/Source/core/html/HTMLTableRowsCollection.h
+++ b/Source/core/html/HTMLTableRowsCollection.h
@@ -38,15 +38,15 @@
 
 class HTMLTableRowsCollection FINAL : public HTMLCollection {
 public:
-    static PassRefPtr<HTMLTableRowsCollection> create(Node*, CollectionType);
+    static PassRefPtr<HTMLTableRowsCollection> create(ContainerNode*, CollectionType);
 
     static HTMLTableRowElement* rowAfter(HTMLTableElement*, HTMLTableRowElement*);
     static HTMLTableRowElement* lastRow(HTMLTableElement*);
 
 private:
-    explicit HTMLTableRowsCollection(Node*);
+    explicit HTMLTableRowsCollection(ContainerNode*);
 
-    virtual Element* virtualItemAfter(unsigned& offsetInArray, Element*) const OVERRIDE;
+    virtual Element* virtualItemAfter(Element*) const OVERRIDE;
 };
 
 } // namespace
diff --git a/Source/core/html/HTMLTableSectionElement.cpp b/Source/core/html/HTMLTableSectionElement.cpp
index 01ec777..bf796d6 100644
--- a/Source/core/html/HTMLTableSectionElement.cpp
+++ b/Source/core/html/HTMLTableSectionElement.cpp
@@ -61,9 +61,9 @@
     RefPtr<HTMLTableRowElement> row;
     RefPtr<HTMLCollection> children = rows();
     int numRows = children ? (int)children->length() : 0;
-    if (index < -1 || index > numRows)
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError); // per the DOM
-    else {
+    if (index < -1 || index > numRows) {
+        exceptionState.throwDOMException(IndexSizeError, "The provided index (" + String::number(index) + " is outside the range [-1, " + String::number(numRows) + "].");
+    } else {
         row = HTMLTableRowElement::create(document());
         if (numRows == index || index == -1)
             appendChild(row, exceptionState);
@@ -86,10 +86,10 @@
     if (index == -1)
         index = numRows - 1;
     if (index >= 0 && index < numRows) {
-        RefPtr<Node> row = children->item(index);
+        RefPtr<Element> row = children->item(index);
         HTMLElement::removeChild(row.get(), exceptionState);
     } else {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, "The provided index (" + String::number(index) + " is outside the range [-1, " + String::number(numRows) + "].");
     }
 }
 
@@ -106,46 +106,6 @@
     return rows;
 }
 
-const AtomicString& HTMLTableSectionElement::align() const
-{
-    return getAttribute(alignAttr);
-}
-
-void HTMLTableSectionElement::setAlign(const AtomicString& value)
-{
-    setAttribute(alignAttr, value);
-}
-
-const AtomicString& HTMLTableSectionElement::ch() const
-{
-    return getAttribute(charAttr);
-}
-
-void HTMLTableSectionElement::setCh(const AtomicString& value)
-{
-    setAttribute(charAttr, value);
-}
-
-const AtomicString& HTMLTableSectionElement::chOff() const
-{
-    return getAttribute(charoffAttr);
-}
-
-void HTMLTableSectionElement::setChOff(const AtomicString& value)
-{
-    setAttribute(charoffAttr, value);
-}
-
-const AtomicString& HTMLTableSectionElement::vAlign() const
-{
-    return getAttribute(valignAttr);
-}
-
-void HTMLTableSectionElement::setVAlign(const AtomicString& value)
-{
-    setAttribute(valignAttr, value);
-}
-
 PassRefPtr<HTMLCollection> HTMLTableSectionElement::rows()
 {
     return ensureCachedHTMLCollection(TSectionRows);
diff --git a/Source/core/html/HTMLTableSectionElement.h b/Source/core/html/HTMLTableSectionElement.h
index 02d5516..2a72821 100644
--- a/Source/core/html/HTMLTableSectionElement.h
+++ b/Source/core/html/HTMLTableSectionElement.h
@@ -41,18 +41,6 @@
 
     int numRows() const;
 
-    const AtomicString& align() const;
-    void setAlign(const AtomicString&);
-
-    const AtomicString& ch() const;
-    void setCh(const AtomicString&);
-
-    const AtomicString& chOff() const;
-    void setChOff(const AtomicString&);
-
-    const AtomicString& vAlign() const;
-    void setVAlign(const AtomicString&);
-
     PassRefPtr<HTMLCollection> rows();
 
 private:
diff --git a/Source/core/html/HTMLTagNames.in b/Source/core/html/HTMLTagNames.in
index ee8c92f..1014edd 100644
--- a/Source/core/html/HTMLTagNames.in
+++ b/Source/core/html/HTMLTagNames.in
@@ -11,7 +11,7 @@
 area
 article interfaceName=HTMLElement
 aside interfaceName=HTMLElement
-audio runtimeEnabled=media, constructorNeedsCreatedByParser
+audio runtimeEnabled=media
 b interfaceName=HTMLElement
 base
 basefont interfaceName=HTMLElement
@@ -87,7 +87,7 @@
 meter interfaceName=HTMLMeterElement
 nav interfaceName=HTMLElement
 nobr interfaceName=HTMLElement
-noembed interfaceName=HTMLElement
+noembed interfaceName=HTMLNoEmbedElement, JSInterfaceName=HTMLElement
 noframes interfaceName=HTMLElement
 nolayer interfaceName=HTMLElement
 object constructorNeedsFormElement, constructorNeedsCreatedByParser
@@ -103,13 +103,13 @@
 progress interfaceName=HTMLProgressElement
 q interfaceName=HTMLQuoteElement
 rp interfaceName=HTMLElement
-rt interfaceName=HTMLElement
-ruby interfaceName=HTMLElement
+rt interfaceName=HTMLRTElement, JSInterfaceName=HTMLElement
+ruby interfaceName=HTMLRubyElement, JSInterfaceName=HTMLElement
 s interfaceName=HTMLElement
 samp interfaceName=HTMLElement
 script constructorNeedsCreatedByParser
 section interfaceName=HTMLElement
-select constructorNeedsFormElement, constructorNeedsCreatedByParser
+select constructorNeedsFormElement
 small interfaceName=HTMLElement
 source runtimeEnabled=media
 span
@@ -134,7 +134,7 @@
 u interfaceName=HTMLElement
 ul interfaceName=HTMLUListElement
 var interfaceName=HTMLElement
-video runtimeEnabled=media, constructorNeedsCreatedByParser
-wbr interfaceName=HTMLElement
+video runtimeEnabled=media
+wbr interfaceName=HTMLWBRElement, JSInterfaceName=HTMLElement
 xmp interfaceName=HTMLPreElement
-noscript interfaceName=HTMLElement
+noscript interfaceName=HTMLNoScriptElement, JSInterfaceName=HTMLElement
diff --git a/Source/core/html/HTMLTemplateElement.h b/Source/core/html/HTMLTemplateElement.h
index 6b2ebd6..b27958d 100644
--- a/Source/core/html/HTMLTemplateElement.h
+++ b/Source/core/html/HTMLTemplateElement.h
@@ -54,17 +54,7 @@
     mutable RefPtr<TemplateContentDocumentFragment> m_content;
 };
 
-inline HTMLTemplateElement* toHTMLTemplateElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && node->hasTagName(HTMLNames::templateTag)));
-    return static_cast<HTMLTemplateElement*>(node);
-}
-
-inline const HTMLTemplateElement* toHTMLTemplateElement(const Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && node->hasTagName(HTMLNames::templateTag)));
-    return static_cast<const HTMLTemplateElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTemplateElement, hasTagName(HTMLNames::templateTag));
 
 } // namespace WebCore
 
diff --git a/Source/core/html/HTMLTextAreaElement.cpp b/Source/core/html/HTMLTextAreaElement.cpp
index ca7494e..7ea7aa6 100644
--- a/Source/core/html/HTMLTextAreaElement.cpp
+++ b/Source/core/html/HTMLTextAreaElement.cpp
@@ -260,7 +260,7 @@
     HTMLTextFormControlElement::defaultEventHandler(event);
 }
 
-void HTMLTextAreaElement::handleFocusEvent(Element*, FocusDirection)
+void HTMLTextAreaElement::handleFocusEvent(Element*, FocusType)
 {
     if (Frame* frame = document().frame())
         frame->spellChecker().didBeginEditing(this);
@@ -312,11 +312,6 @@
     return proposedValue.left(maxLength);
 }
 
-void HTMLTextAreaElement::rendererWillBeDestroyed()
-{
-    updateValue();
-}
-
 void HTMLTextAreaElement::updateValue() const
 {
     if (formControlValueMatchesRenderer())
@@ -367,8 +362,9 @@
     setInnerTextValue(m_value);
     setLastChangeWasNotUserEdit();
     updatePlaceholderVisibility(false);
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
     setFormControlValueMatchesRenderer(true);
+    m_suggestedValue = String();
 
     // Set the caret to the end of the text value.
     if (document().focusedElement() == this) {
@@ -433,6 +429,20 @@
         setIntegralAttribute(maxlengthAttr, newValue);
 }
 
+String HTMLTextAreaElement::suggestedValue() const
+{
+    return m_suggestedValue;
+}
+
+void HTMLTextAreaElement::setSuggestedValue(const String& value)
+{
+    m_suggestedValue = value;
+    setInnerTextValue(m_suggestedValue);
+    updatePlaceholderVisibility(false);
+    setNeedsStyleRecalc(SubtreeStyleChange);
+    setFormControlValueMatchesRenderer(true);
+}
+
 String HTMLTextAreaElement::validationMessage() const
 {
     if (!willValidate())
@@ -520,7 +530,7 @@
     if (!placeholder) {
         RefPtr<HTMLDivElement> newElement = HTMLDivElement::create(document());
         placeholder = newElement.get();
-        placeholder->setPseudo(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+        placeholder->setShadowPseudoId(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
         placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
         userAgentShadowRoot()->insertBefore(placeholder, innerTextElement()->nextSibling());
     }
@@ -532,4 +542,9 @@
     return true;
 }
 
+bool HTMLTextAreaElement::supportsAutofocus() const
+{
+    return true;
+}
+
 }
diff --git a/Source/core/html/HTMLTextAreaElement.h b/Source/core/html/HTMLTextAreaElement.h
index a569334..00eb301 100644
--- a/Source/core/html/HTMLTextAreaElement.h
+++ b/Source/core/html/HTMLTextAreaElement.h
@@ -41,21 +41,23 @@
 
     bool shouldWrapText() const { return m_wrap != NoWrap; }
 
-    virtual String value() const;
+    virtual String value() const OVERRIDE;
     void setValue(const String&);
     String defaultValue() const;
     void setDefaultValue(const String&);
     int textLength() const { return value().length(); }
-    virtual int maxLength() const;
+    int maxLength() const;
     void setMaxLength(int, ExceptionState&);
+
+    String suggestedValue() const;
+    void setSuggestedValue(const String&);
+
     // For ValidityState
     virtual String validationMessage() const OVERRIDE;
     virtual bool valueMissing() const OVERRIDE;
     virtual bool tooLong() const OVERRIDE;
     bool isValidValue(const String&) const;
 
-    void rendererWillBeDestroyed();
-
     void setCols(int);
     void setRows(int);
 
@@ -75,44 +77,45 @@
     void setNonDirtyValue(const String&);
     void setValueCommon(const String&);
 
-    virtual bool supportsPlaceholder() const { return true; }
-    virtual void updatePlaceholderText();
-    virtual bool isEmptyValue() const { return value().isEmpty(); }
+    virtual bool supportsPlaceholder() const OVERRIDE { return true; }
+    virtual void updatePlaceholderText() OVERRIDE;
+    virtual bool isEmptyValue() const OVERRIDE { return value().isEmpty(); }
 
-    virtual bool isOptionalFormControl() const { return !isRequiredFormControl(); }
-    virtual bool isRequiredFormControl() const { return isRequired(); }
+    virtual bool isOptionalFormControl() const OVERRIDE { return !isRequiredFormControl(); }
+    virtual bool isRequiredFormControl() const OVERRIDE { return isRequired(); }
 
-    virtual void defaultEventHandler(Event*);
-    virtual void handleFocusEvent(Element* oldFocusedNode, FocusDirection) OVERRIDE;
+    virtual void defaultEventHandler(Event*) OVERRIDE;
+    virtual void handleFocusEvent(Element* oldFocusedNode, FocusType) OVERRIDE;
 
-    virtual void subtreeHasChanged();
+    virtual void subtreeHasChanged() OVERRIDE;
 
-    virtual bool isEnumeratable() const { return true; }
+    virtual bool isEnumeratable() const OVERRIDE { return true; }
     virtual bool isInteractiveContent() const OVERRIDE;
+    virtual bool supportsAutofocus() const OVERRIDE;
     virtual bool supportLabels() const OVERRIDE { return true; }
 
-    virtual const AtomicString& formControlType() const;
+    virtual const AtomicString& formControlType() const OVERRIDE;
 
     virtual FormControlState saveFormControlState() const OVERRIDE;
     virtual void restoreFormControlState(const FormControlState&) OVERRIDE;
 
-    virtual bool isTextFormControl() const { return true; }
+    virtual bool isTextFormControl() const OVERRIDE { return true; }
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool appendFormData(FormDataList&, bool);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual bool appendFormData(FormDataList&, bool) OVERRIDE;
     virtual void resetImpl() OVERRIDE;
     virtual bool hasCustomFocusLogic() const OVERRIDE;
     virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
     virtual bool isKeyboardFocusable() const OVERRIDE;
-    virtual void updateFocusAppearance(bool restorePreviousSelection);
+    virtual void updateFocusAppearance(bool restorePreviousSelection) OVERRIDE;
 
-    virtual void accessKeyAction(bool sendMouseEvents);
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
 
-    virtual bool shouldUseInputMethod();
+    virtual bool shouldUseInputMethod() OVERRIDE;
     virtual bool matchesReadOnlyPseudoClass() const OVERRIDE;
     virtual bool matchesReadWritePseudoClass() const OVERRIDE;
 
@@ -124,18 +127,9 @@
     WrapMethod m_wrap;
     mutable String m_value;
     mutable bool m_isDirty;
+    String m_suggestedValue;
 };
 
-inline bool isHTMLTextAreaElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::textareaTag);
-}
-
-inline bool isHTMLTextAreaElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::textareaTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLTextAreaElement, hasTagName(HTMLNames::textareaTag));
 
 } //namespace
diff --git a/Source/core/html/HTMLTextFormControlElement.cpp b/Source/core/html/HTMLTextFormControlElement.cpp
index 23a658b..a8ef2bf 100644
--- a/Source/core/html/HTMLTextFormControlElement.cpp
+++ b/Source/core/html/HTMLTextFormControlElement.cpp
@@ -73,12 +73,12 @@
     return InsertionDone;
 }
 
-void HTMLTextFormControlElement::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection direction)
+void HTMLTextFormControlElement::dispatchFocusEvent(Element* oldFocusedElement, FocusType type)
 {
     if (supportsPlaceholder())
         updatePlaceholderVisibility(false);
-    handleFocusEvent(oldFocusedElement, direction);
-    HTMLFormControlElementWithState::dispatchFocusEvent(oldFocusedElement, direction);
+    handleFocusEvent(oldFocusedElement, type);
+    HTMLFormControlElementWithState::dispatchFocusEvent(oldFocusedElement, type);
 }
 
 void HTMLTextFormControlElement::dispatchBlurEvent(Element* newFocusedElement)
@@ -182,17 +182,10 @@
     setSelectionRange(0, numeric_limits<int>::max(), SelectionHasNoDirection);
 }
 
-String HTMLTextFormControlElement::selectedText() const
-{
-    if (!isTextFormControl())
-        return String();
-    return value().substring(selectionStart(), selectionEnd() - selectionStart());
-}
-
 void HTMLTextFormControlElement::dispatchFormControlChangeEvent()
 {
     if (m_textAsOfLastFormControlChangeEvent != value()) {
-        HTMLElement::dispatchChangeEvent();
+        dispatchChangeEvent();
         setTextAsOfLastFormControlChangeEvent(value());
     }
     setChangedSinceLastFormControlChangeEvent(false);
@@ -618,22 +611,22 @@
     if (!container)
         return 0;
     Element* ancestor = container->shadowHost();
-    return ancestor && isHTMLTextFormControlElement(ancestor) ? toHTMLTextFormControlElement(ancestor) : 0;
+    return ancestor && isHTMLTextFormControlElement(*ancestor) ? toHTMLTextFormControlElement(ancestor) : 0;
 }
 
-static const Element* parentHTMLElement(const Element* element)
+static const HTMLElement* parentHTMLElement(const Element* element)
 {
     while (element) {
         element = element->parentElement();
         if (element && element->isHTMLElement())
-            return element;
+            return toHTMLElement(element);
     }
     return 0;
 }
 
 String HTMLTextFormControlElement::directionForFormData() const
 {
-    for (const Element* element = this; element; element = parentHTMLElement(element)) {
+    for (const HTMLElement* element = this; element; element = parentHTMLElement(element)) {
         const AtomicString& dirAttributeValue = element->fastGetAttribute(dirAttr);
         if (dirAttributeValue.isNull())
             continue;
@@ -643,7 +636,7 @@
 
         if (equalIgnoringCase(dirAttributeValue, "auto")) {
             bool isAuto;
-            TextDirection textDirection = static_cast<const HTMLElement*>(element)->directionalityIfhasDirAutoAttribute(isAuto);
+            TextDirection textDirection = element->directionalityIfhasDirAutoAttribute(isAuto);
             return textDirection == RTL ? "rtl" : "ltr";
         }
     }
diff --git a/Source/core/html/HTMLTextFormControlElement.h b/Source/core/html/HTMLTextFormControlElement.h
index 2c7a9bf..a8675d9 100644
--- a/Source/core/html/HTMLTextFormControlElement.h
+++ b/Source/core/html/HTMLTextFormControlElement.h
@@ -70,11 +70,9 @@
     void setSelectionRange(int start, int end, const String& direction);
     void setSelectionRange(int start, int end, TextFieldSelectionDirection = SelectionHasNoDirection);
     PassRefPtr<Range> selection() const;
-    String selectedText() const;
 
-    virtual void dispatchFormControlChangeEvent();
+    virtual void dispatchFormControlChangeEvent() OVERRIDE FINAL;
 
-    virtual int maxLength() const = 0;
     virtual String value() const = 0;
 
     HTMLElement* innerTextElement() const;
@@ -105,7 +103,7 @@
     void restoreCachedSelection();
     bool hasCachedSelection() const { return m_cachedSelectionStart >= 0; }
 
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
     virtual void subtreeHasChanged() = 0;
 
     void setLastChangeWasNotUserEdit() { m_lastChangeWasUserEdit = false; }
@@ -117,15 +115,15 @@
     int computeSelectionEnd() const;
     TextFieldSelectionDirection computeSelectionDirection() const;
 
-    virtual void dispatchFocusEvent(Element* oldFocusedElement, FocusDirection) OVERRIDE;
-    virtual void dispatchBlurEvent(Element* newFocusedElement) OVERRIDE;
+    virtual void dispatchFocusEvent(Element* oldFocusedElement, FocusType) OVERRIDE FINAL;
+    virtual void dispatchBlurEvent(Element* newFocusedElement) OVERRIDE FINAL;
 
     // Returns true if user-editable value is empty. Used to check placeholder visibility.
     virtual bool isEmptyValue() const = 0;
     // Returns true if suggested value is empty. Used to check placeholder visibility.
     virtual bool isEmptySuggestedValue() const { return true; }
     // Called in dispatchFocusEvent(), after placeholder process, before calling parent's dispatchFocusEvent().
-    virtual void handleFocusEvent(Element* /* oldFocusedNode */, FocusDirection) { }
+    virtual void handleFocusEvent(Element* /* oldFocusedNode */, FocusType) { }
     // Called in dispatchBlurEvent(), after placeholder process, before calling parent's dispatchBlurEvent().
     virtual void handleBlurEvent() { }
 
@@ -137,11 +135,6 @@
     TextFieldSelectionDirection m_cachedSelectionDirection;
 };
 
-inline bool isHTMLTextFormControlElement(const Node* node)
-{
-    return node->isElementNode() && toElement(node)->isTextFormControl();
-}
-
 inline bool isHTMLTextFormControlElement(const Node& node)
 {
     return node.isElementNode() && toElement(node).isTextFormControl();
diff --git a/Source/core/html/HTMLTitleElement.cpp b/Source/core/html/HTMLTitleElement.cpp
index c9fdaed..ed8a83c 100644
--- a/Source/core/html/HTMLTitleElement.cpp
+++ b/Source/core/html/HTMLTitleElement.cpp
@@ -25,6 +25,7 @@
 
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/ChildListMutationScope.h"
 #include "core/dom/Document.h"
 #include "core/dom/Text.h"
 #include "core/rendering/style/RenderStyle.h"
@@ -37,6 +38,7 @@
 
 inline HTMLTitleElement::HTMLTitleElement(Document& document)
     : HTMLElement(titleTag, document)
+    , m_ignoreTitleUpdatesWhenChildrenChange(false)
 {
     setHasCustomStyleCallbacks();
     ScriptWrappable::init(this);
@@ -65,7 +67,7 @@
 void HTMLTitleElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
     HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
-    if (inDocument() && !isInShadowTree())
+    if (inDocument() && !isInShadowTree() && !m_ignoreTitleUpdatesWhenChildrenChange)
         document().setTitleElement(text(), this);
 }
 
@@ -84,22 +86,15 @@
 void HTMLTitleElement::setText(const String &value)
 {
     RefPtr<Node> protectFromMutationEvents(this);
+    ChildListMutationScope mutation(*this);
 
-    int numChildren = childNodeCount();
+    // Avoid calling Document::setTitleElement() during intermediate steps.
+    m_ignoreTitleUpdatesWhenChildrenChange = !value.isEmpty();
+    removeChildren();
+    m_ignoreTitleUpdatesWhenChildrenChange = false;
 
-    if (numChildren == 1 && firstChild()->isTextNode())
-        toText(firstChild())->setData(value);
-    else {
-        // We make a copy here because entity of "value" argument can be Document::m_title,
-        // which goes empty during removeChildren() invocation below,
-        // which causes HTMLTitleElement::childrenChanged(), which ends up Document::setTitle().
-        String valueCopy(value);
-
-        if (numChildren > 0)
-            removeChildren();
-
-        appendChild(document().createTextNode(valueCopy.impl()), IGNORE_EXCEPTION);
-    }
+    if (!value.isEmpty())
+        appendChild(document().createTextNode(value.impl()), IGNORE_EXCEPTION);
 }
 
 }
diff --git a/Source/core/html/HTMLTitleElement.h b/Source/core/html/HTMLTitleElement.h
index 988f77a..129c03e 100644
--- a/Source/core/html/HTMLTitleElement.h
+++ b/Source/core/html/HTMLTitleElement.h
@@ -38,19 +38,11 @@
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
+
+    bool m_ignoreTitleUpdatesWhenChildrenChange;
 };
 
-inline bool isHTMLTitleElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::titleTag);
-}
-
-inline bool isHTMLTitleElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::titleTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLTitleElement, hasTagName(HTMLNames::titleTag));
 
 } //namespace
diff --git a/Source/core/html/HTMLTrackElement.cpp b/Source/core/html/HTMLTrackElement.cpp
index 0182bce..1ca3479 100644
--- a/Source/core/html/HTMLTrackElement.cpp
+++ b/Source/core/html/HTMLTrackElement.cpp
@@ -85,7 +85,7 @@
 
 void HTMLTrackElement::removedFrom(ContainerNode* insertionPoint)
 {
-    if (!parentNode() && isHTMLMediaElement(insertionPoint))
+    if (!parentNode() && isHTMLMediaElement(*insertionPoint))
         toHTMLMediaElement(insertionPoint)->didRemoveTrack(this);
     HTMLElement::removedFrom(insertionPoint);
 }
diff --git a/Source/core/html/HTMLVideoElement.cpp b/Source/core/html/HTMLVideoElement.cpp
index 214c470..5dacbac 100644
--- a/Source/core/html/HTMLVideoElement.cpp
+++ b/Source/core/html/HTMLVideoElement.cpp
@@ -34,7 +34,7 @@
 #include "core/dom/ExceptionCode.h"
 #include "core/html/HTMLImageLoader.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderVideo.h"
 #include "platform/UserGestureIndicator.h"
@@ -43,17 +43,17 @@
 
 using namespace HTMLNames;
 
-inline HTMLVideoElement::HTMLVideoElement(Document& document, bool createdByParser)
-    : HTMLMediaElement(videoTag, document, createdByParser)
+inline HTMLVideoElement::HTMLVideoElement(Document& document)
+    : HTMLMediaElement(videoTag, document)
 {
     ScriptWrappable::init(this);
     if (document.settings())
-        m_defaultPosterURL = document.settings()->defaultVideoPosterURL();
+        m_defaultPosterURL = AtomicString(document.settings()->defaultVideoPosterURL());
 }
 
-PassRefPtr<HTMLVideoElement> HTMLVideoElement::create(Document& document, bool createdByParser)
+PassRefPtr<HTMLVideoElement> HTMLVideoElement::create(Document& document)
 {
-    RefPtr<HTMLVideoElement> videoElement(adoptRef(new HTMLVideoElement(document, createdByParser)));
+    RefPtr<HTMLVideoElement> videoElement(adoptRef(new HTMLVideoElement(document)));
     videoElement->suspendIfNeeded();
     return videoElement.release();
 }
@@ -113,6 +113,9 @@
             if (renderer())
                 toRenderImage(renderer())->imageResource()->setImageResource(0);
         }
+        // Notify the player when the poster image URL changes.
+        if (player())
+            player()->setPoster(posterImageURL());
     } else
         HTMLMediaElement::parseAttribute(name, value);
 }
@@ -122,7 +125,7 @@
     if (!document().page())
         return false;
 
-    if (!player() || !player()->supportsFullscreen())
+    if (!player())
         return false;
 
     return true;
@@ -189,7 +192,7 @@
     player->paint(context, destRect);
 }
 
-bool HTMLVideoElement::copyVideoTextureToPlatformTexture(GraphicsContext3D* context, Platform3DObject texture, GC3Dint level, GC3Denum type, GC3Denum internalFormat, bool premultiplyAlpha, bool flipY)
+bool HTMLVideoElement::copyVideoTextureToPlatformTexture(blink::WebGraphicsContext3D* context, Platform3DObject texture, GLint level, GLenum type, GLenum internalFormat, bool premultiplyAlpha, bool flipY)
 {
     if (!player())
         return false;
@@ -270,4 +273,9 @@
     return document().completeURL(url);
 }
 
+KURL HTMLVideoElement::mediaPlayerPosterURL()
+{
+    return posterImageURL();
+}
+
 }
diff --git a/Source/core/html/HTMLVideoElement.h b/Source/core/html/HTMLVideoElement.h
index 4d729f3..13122fd 100644
--- a/Source/core/html/HTMLVideoElement.h
+++ b/Source/core/html/HTMLVideoElement.h
@@ -28,6 +28,10 @@
 
 #include "core/html/HTMLMediaElement.h"
 
+namespace blink {
+class WebGraphicsContext3D;
+}
+
 namespace WebCore {
 
 class ExceptionState;
@@ -35,7 +39,7 @@
 
 class HTMLVideoElement FINAL : public HTMLMediaElement {
 public:
-    static PassRefPtr<HTMLVideoElement> create(Document&, bool createdByParser = false);
+    static PassRefPtr<HTMLVideoElement> create(Document&);
 
     unsigned videoWidth() const;
     unsigned videoHeight() const;
@@ -55,14 +59,17 @@
 
     // Used by WebGL to do GPU-GPU textures copy if possible.
     // See more details at MediaPlayer::copyVideoTextureToPlatformTexture() defined in Source/WebCore/platform/graphics/MediaPlayer.h.
-    bool copyVideoTextureToPlatformTexture(GraphicsContext3D*, Platform3DObject texture, GC3Dint level, GC3Denum type, GC3Denum internalFormat, bool premultiplyAlpha, bool flipY);
+    bool copyVideoTextureToPlatformTexture(blink::WebGraphicsContext3D*, Platform3DObject texture, GC3Dint level, GC3Denum type, GC3Denum internalFormat, bool premultiplyAlpha, bool flipY);
 
     bool shouldDisplayPosterImage() const { return displayMode() == Poster || displayMode() == PosterWaitingForVideo; }
 
     KURL posterImageURL() const;
 
+    // FIXME: Remove this when WebMediaPlayerClientImpl::loadInternal does not depend on it.
+    virtual KURL mediaPlayerPosterURL() OVERRIDE;
+
 private:
-    HTMLVideoElement(Document&, bool);
+    HTMLVideoElement(Document&);
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
@@ -72,7 +79,7 @@
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
     virtual bool isVideo() const OVERRIDE { return true; }
     virtual bool hasVideo() const OVERRIDE { return player() && player()->hasVideo(); }
-    virtual bool supportsFullscreen() const OVERRIDE;
+    bool supportsFullscreen() const;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
     virtual const AtomicString imageSourceURL() const OVERRIDE;
 
@@ -86,16 +93,6 @@
     AtomicString m_defaultPosterURL;
 };
 
-inline bool isHTMLVideoElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::videoTag);
-}
-
-inline bool isHTMLVideoElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::videoTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLVideoElement, hasTagName(HTMLNames::videoTag));
 
 } //namespace
diff --git a/Source/core/html/HTMLVideoElement.idl b/Source/core/html/HTMLVideoElement.idl
index 4448cd2..b68a7db 100644
--- a/Source/core/html/HTMLVideoElement.idl
+++ b/Source/core/html/HTMLVideoElement.idl
@@ -32,15 +32,15 @@
     readonly attribute unsigned long videoHeight;
     [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString poster;
 
-    [MeasureAs=PrefixedVideoSupportsFullscreen] readonly attribute boolean webkitSupportsFullscreen;
-    [MeasureAs=PrefixedVideoDisplayingFullscreen] readonly attribute boolean webkitDisplayingFullscreen;
+    [DeprecateAs=PrefixedVideoSupportsFullscreen] readonly attribute boolean webkitSupportsFullscreen;
+    [DeprecateAs=PrefixedVideoDisplayingFullscreen] readonly attribute boolean webkitDisplayingFullscreen;
 
-    [MeasureAs=PrefixedVideoEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=ForAllWorlds] void webkitEnterFullscreen();
-    [MeasureAs=PrefixedVideoExitFullscreen] void webkitExitFullscreen();
+    [DeprecateAs=PrefixedVideoEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=ForAllWorlds] void webkitEnterFullscreen();
+    [DeprecateAs=PrefixedVideoExitFullscreen] void webkitExitFullscreen();
 
     // Note the different capitalization of the "S" in FullScreen.
-    [MeasureAs=PrefixedVideoEnterFullScreen, ImplementedAs=webkitEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=ForAllWorlds] void webkitEnterFullScreen();
-    [MeasureAs=PrefixedVideoExitFullScreen, ImplementedAs=webkitExitFullscreen] void webkitExitFullScreen();
+    [DeprecateAs=PrefixedVideoEnterFullScreen, ImplementedAs=webkitEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=ForAllWorlds] void webkitEnterFullScreen();
+    [DeprecateAs=PrefixedVideoExitFullScreen, ImplementedAs=webkitExitFullscreen] void webkitExitFullScreen();
 
     // The number of frames that have been decoded and made available for
     // playback.
diff --git a/Source/core/html/HTMLViewSourceDocument.cpp b/Source/core/html/HTMLViewSourceDocument.cpp
index 4a55226..b47a8b8 100644
--- a/Source/core/html/HTMLViewSourceDocument.cpp
+++ b/Source/core/html/HTMLViewSourceDocument.cpp
@@ -139,21 +139,21 @@
     while (index < source.length()) {
         if (iter == token.attributes().end()) {
             // We want to show the remaining characters in the token.
-            index = addRange(source, index, source.length(), "");
+            index = addRange(source, index, source.length(), emptyAtom);
             ASSERT(index == source.length());
             break;
         }
 
         AtomicString name(iter->name);
-        String value = StringImpl::create8BitIfPossible(iter->value);
+        AtomicString value(StringImpl::create8BitIfPossible(iter->value));
 
-        index = addRange(source, index, iter->nameRange.start - token.startIndex(), "");
+        index = addRange(source, index, iter->nameRange.start - token.startIndex(), emptyAtom);
         index = addRange(source, index, iter->nameRange.end - token.startIndex(), "webkit-html-attribute-name");
 
         if (tagName == baseTag && name == hrefAttr)
             addBase(value);
 
-        index = addRange(source, index, iter->valueRange.start - token.startIndex(), "");
+        index = addRange(source, index, iter->valueRange.start - token.startIndex(), emptyAtom);
 
         bool isLink = name == srcAttr || name == hrefAttr;
         index = addRange(source, index, iter->valueRange.end - token.startIndex(), "webkit-html-attribute-value", isLink, tagName == aTag, value);
@@ -249,7 +249,7 @@
     }
 }
 
-int HTMLViewSourceDocument::addRange(const String& source, int start, int end, const String& className, bool isLink, bool isAnchor, const String& link)
+int HTMLViewSourceDocument::addRange(const String& source, int start, int end, const AtomicString& className, bool isLink, bool isAnchor, const AtomicString& link)
 {
     ASSERT(start <= end);
     if (start == end)
diff --git a/Source/core/html/HTMLViewSourceDocument.h b/Source/core/html/HTMLViewSourceDocument.h
index a1988cc..8c2608a 100644
--- a/Source/core/html/HTMLViewSourceDocument.h
+++ b/Source/core/html/HTMLViewSourceDocument.h
@@ -58,7 +58,7 @@
     void addLine(const AtomicString& className);
     void finishLine();
     void addText(const String& text, const AtomicString& className);
-    int addRange(const String& source, int start, int end, const String& className, bool isLink = false, bool isAnchor = false, const String& link = String());
+    int addRange(const String& source, int start, int end, const AtomicString& className, bool isLink = false, bool isAnchor = false, const AtomicString& link = nullAtom);
     PassRefPtr<Element> addLink(const AtomicString& url, bool isAnchor);
     PassRefPtr<Element> addBase(const AtomicString& href);
 
diff --git a/Source/core/rendering/LayoutIndicator.cpp b/Source/core/html/HTMLWBRElement.cpp
similarity index 74%
copy from Source/core/rendering/LayoutIndicator.cpp
copy to Source/core/html/HTMLWBRElement.cpp
index a57c53c..80a7e2a 100644
--- a/Source/core/rendering/LayoutIndicator.cpp
+++ b/Source/core/html/HTMLWBRElement.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,14 +29,28 @@
  */
 
 #include "config.h"
-#include "core/rendering/LayoutIndicator.h"
+#include "core/html/HTMLWBRElement.h"
+
+#include "HTMLNames.h"
+#include "core/rendering/RenderWordBreak.h"
 
 namespace WebCore {
 
-#ifndef NDEBUG
+using namespace HTMLNames;
 
-size_t LayoutIndicator::s_inLayout = 0;
+HTMLWBRElement::HTMLWBRElement(Document& document)
+    : HTMLElement(wbrTag, document)
+{
+}
 
-#endif
+PassRefPtr<HTMLWBRElement> HTMLWBRElement::create(Document& document)
+{
+    return adoptRef(new HTMLWBRElement(document));
+}
+
+RenderObject* HTMLWBRElement::createRenderer(RenderStyle* style)
+{
+    return new RenderWordBreak(this);
+}
 
 }
diff --git a/Source/core/html/HTMLImportDataClient.h b/Source/core/html/HTMLWBRElement.h
similarity index 74%
copy from Source/core/html/HTMLImportDataClient.h
copy to Source/core/html/HTMLWBRElement.h
index 0c26a22..4695281 100644
--- a/Source/core/html/HTMLImportDataClient.h
+++ b/Source/core/html/HTMLWBRElement.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,17 +28,25 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef HTMLImportDataClient_h
-#define HTMLImportDataClient_h
+#ifndef HTMLWBRElement_h
+#define HTMLWBRElement_h
+
+#include "core/html/HTMLElement.h"
 
 namespace WebCore {
 
-class HTMLImportDataClient {
+// <wbr> is an HTMLElement in script, but we use a separate interface here
+// so HTMLElement's createRenderer doesn't need to know about it.
+class HTMLWBRElement FINAL : public HTMLElement {
 public:
-    virtual ~HTMLImportDataClient() { }
-    virtual void didFinish() = 0;
+    static PassRefPtr<HTMLWBRElement> create(Document&);
+
+private:
+    explicit HTMLWBRElement(Document&);
+
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 };
 
-}
+} // namespace
 
-#endif // HTMLImportDataClient_h
+#endif
diff --git a/Source/core/html/ImageDocument.cpp b/Source/core/html/ImageDocument.cpp
index 350fa9e..d5d8eb2 100644
--- a/Source/core/html/ImageDocument.cpp
+++ b/Source/core/html/ImageDocument.cpp
@@ -42,8 +42,7 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "wtf/text/StringBuilder.h"
 
 using std::min;
@@ -127,7 +126,7 @@
 
     Frame* frame = document()->frame();
     Settings* settings = frame->settings();
-    if (!frame->loader().client()->allowImage(!settings || settings->areImagesEnabled(), document()->url()))
+    if (!frame->loader().client()->allowImage(!settings || settings->imagesEnabled(), document()->url()))
         return;
 
     document()->cachedImage()->appendData(data, length);
@@ -189,7 +188,7 @@
     RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(*this);
     RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(*this);
     meta->setAttribute(nameAttr, "viewport");
-    meta->setAttribute(contentAttr, "width=device-width");
+    meta->setAttribute(contentAttr, "width=device-width, minimum-scale=0.1");
     head->appendChild(meta);
 
     RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(*this);
diff --git a/Source/core/html/LabelableElement.cpp b/Source/core/html/LabelableElement.cpp
index ad30251..8e522cc 100644
--- a/Source/core/html/LabelableElement.cpp
+++ b/Source/core/html/LabelableElement.cpp
@@ -44,7 +44,7 @@
     if (!supportLabels())
         return 0;
 
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<LabelsNodeList>(this, LabelsNodeListType, starAtom);
+    return ensureRareData().ensureNodeLists().addCache<LabelsNodeList>(this, LabelsNodeListType);
 }
 
 } // namespace Webcore
diff --git a/Source/core/html/LabelableElement.h b/Source/core/html/LabelableElement.h
index 259285c..f3d2188 100644
--- a/Source/core/html/LabelableElement.h
+++ b/Source/core/html/LabelableElement.h
@@ -50,12 +50,13 @@
     virtual bool isLabelable() const OVERRIDE FINAL { return true; }
 };
 
-inline LabelableElement* toLabelableElement(Node* node)
+inline bool isLabelableElement(const Node& node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && toHTMLElement(node)->isLabelable()));
-    return static_cast<LabelableElement*>(node);
+    return node.isHTMLElement() && toHTMLElement(node).isLabelable();
 }
 
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(LabelableElement);
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/html/LabelsNodeList.cpp b/Source/core/html/LabelsNodeList.cpp
index a3a6579..e4934cc 100644
--- a/Source/core/html/LabelsNodeList.cpp
+++ b/Source/core/html/LabelsNodeList.cpp
@@ -33,19 +33,19 @@
 
 using namespace HTMLNames;
 
-LabelsNodeList::LabelsNodeList(Node* ownerNode)
+LabelsNodeList::LabelsNodeList(ContainerNode* ownerNode)
     : LiveNodeList(ownerNode, LabelsNodeListType, InvalidateOnForAttrChange, NodeListIsRootedAtDocument)
 {
 }
 
 LabelsNodeList::~LabelsNodeList()
 {
-    ownerNode()->nodeLists()->removeCacheWithAtomicName(this, LabelsNodeListType, starAtom);
+    ownerNode()->nodeLists()->removeCache(this, LabelsNodeListType);
 }
 
-bool LabelsNodeList::nodeMatches(Element* testNode) const
+bool LabelsNodeList::nodeMatches(const Element& testNode) const
 {
-    return isHTMLLabelElement(testNode) && toHTMLLabelElement(testNode)->control() == ownerNode();
+    return testNode.hasTagName(labelTag) && toHTMLLabelElement(testNode).control() == ownerNode();
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/LabelsNodeList.h b/Source/core/html/LabelsNodeList.h
index 0e5b125..919edb1 100644
--- a/Source/core/html/LabelsNodeList.h
+++ b/Source/core/html/LabelsNodeList.h
@@ -32,7 +32,7 @@
 
 class LabelsNodeList FINAL : public LiveNodeList {
 public:
-    static PassRefPtr<LabelsNodeList> create(Node* ownerNode, CollectionType type, const AtomicString&)
+    static PassRefPtr<LabelsNodeList> create(ContainerNode* ownerNode, CollectionType type)
     {
         ASSERT_UNUSED(type, type == LabelsNodeListType);
         return adoptRef(new LabelsNodeList(ownerNode));
@@ -41,9 +41,9 @@
     virtual ~LabelsNodeList();
 
 protected:
-    explicit LabelsNodeList(Node*);
+    explicit LabelsNodeList(ContainerNode*);
 
-    virtual bool nodeMatches(Element*) const;
+    virtual bool nodeMatches(const Element&) const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/LinkImport.cpp b/Source/core/html/LinkImport.cpp
index 18e5d4a..dd61de4 100644
--- a/Source/core/html/LinkImport.cpp
+++ b/Source/core/html/LinkImport.cpp
@@ -47,7 +47,7 @@
 
 LinkImport::LinkImport(HTMLLinkElement* owner)
     : LinkResource(owner)
-    , m_loader(0)
+    , m_child(0)
 {
 }
 
@@ -58,14 +58,14 @@
 
 Document* LinkImport::importedDocument() const
 {
-    if (!m_loader)
+    if (!m_child)
         return 0;
-    return m_loader->importedDocument();
+    return m_child->importedDocument();
 }
 
 void LinkImport::process()
 {
-    if (m_loader)
+    if (m_child)
         return;
     if (!m_owner)
         return;
@@ -85,8 +85,8 @@
 
     HTMLImport* parent = m_owner->document().import();
     HTMLImportsController* controller = parent->controller();
-    m_loader = controller->load(parent, this, builder.build(true));
-    if (!m_loader) {
+    m_child = controller->load(parent, this, builder.build(true));
+    if (!m_child) {
         didFinish();
         return;
     }
@@ -95,9 +95,9 @@
 void LinkImport::clear()
 {
     m_owner = 0;
-    if (m_loader) {
-        m_loader->clearClient();
-        m_loader = 0;
+    if (m_child) {
+        m_child->clearClient();
+        m_child = 0;
     }
 }
 
@@ -110,17 +110,36 @@
 {
     if (!m_owner)
         return;
-    m_owner->scheduleEvent();
+    // Because didFinish() is called from import's own scheduler in HTMLImportsController,
+    // we don't need to scheduleEvent() here.
+    m_owner->dispatchEventImmediately();
 }
 
-void LinkImport::loaderWillBeDestroyed()
+void LinkImport::importChildWasDestroyed(HTMLImportChild* child)
 {
+    ASSERT(m_child == child);
+    m_child = 0;
     clear();
 }
 
+bool LinkImport::isCreatedByParser() const
+{
+    return m_owner && m_owner->isCreatedByParser();
+}
+
+HTMLLinkElement* LinkImport::link()
+{
+    return m_owner;
+}
+
 bool LinkImport::hasLoaded() const
 {
-    return m_loader && m_loader->isLoaded();
+    return m_child && m_child->isDone() && !m_child->loaderHasError();
+}
+
+bool LinkImport::ownsLoader() const
+{
+    return m_child && m_child->hasLoader() && m_child->ownsLoader();
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/LinkImport.h b/Source/core/html/LinkImport.h
index bc2ec95..5d84870 100644
--- a/Source/core/html/LinkImport.h
+++ b/Source/core/html/LinkImport.h
@@ -45,7 +45,7 @@
 //
 // A LinkResource subclasss used for @rel=import.
 //
-class LinkImport : public LinkResource, public HTMLImportChildClient {
+class LinkImport FINAL : public LinkResource, public HTMLImportChildClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
 
@@ -62,14 +62,17 @@
 
     // HTMLImportChildClient
     virtual void didFinish() OVERRIDE;
-    virtual void loaderWillBeDestroyed() OVERRIDE;
+    virtual void importChildWasDestroyed(HTMLImportChild*) OVERRIDE;
+    virtual bool isCreatedByParser() const OVERRIDE;
+    virtual HTMLLinkElement* link() OVERRIDE;
 
     Document* importedDocument() const;
+    bool ownsLoader() const;
 
 private:
     void clear();
 
-    HTMLImportChild* m_loader;
+    HTMLImportChild* m_child;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/LinkRelAttribute.cpp b/Source/core/html/LinkRelAttribute.cpp
index 0c2f32b..91ba040 100644
--- a/Source/core/html/LinkRelAttribute.cpp
+++ b/Source/core/html/LinkRelAttribute.cpp
@@ -32,6 +32,7 @@
 #include "config.h"
 #include "core/html/LinkRelAttribute.h"
 
+#include "RuntimeEnabledFeatures.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -44,6 +45,7 @@
     , m_isLinkPrefetch(false)
     , m_isLinkSubresource(false)
     , m_isLinkPrerender(false)
+    , m_isLinkNext(false)
     , m_isImport(false)
 {
 }
@@ -56,25 +58,28 @@
     , m_isLinkPrefetch(false)
     , m_isLinkSubresource(false)
     , m_isLinkPrerender(false)
+    , m_isLinkNext(false)
     , m_isImport(false)
 {
-    if (equalIgnoringCase(rel, "stylesheet"))
+    if (equalIgnoringCase(rel, "stylesheet")) {
         m_isStyleSheet = true;
-    else if (equalIgnoringCase(rel, "icon") || equalIgnoringCase(rel, "shortcut icon"))
+    } else if (equalIgnoringCase(rel, "icon") || equalIgnoringCase(rel, "shortcut icon")) {
         m_iconType = Favicon;
-#if ENABLE(TOUCH_ICON_LOADING)
-    else if (equalIgnoringCase(rel, "apple-touch-icon"))
-        m_iconType = TouchIcon;
-    else if (equalIgnoringCase(rel, "apple-touch-icon-precomposed"))
-        m_iconType = TouchPrecomposedIcon;
-#endif
-    else if (equalIgnoringCase(rel, "dns-prefetch"))
+    } else if (equalIgnoringCase(rel, "dns-prefetch")) {
         m_isDNSPrefetch = true;
-    else if (equalIgnoringCase(rel, "alternate stylesheet") || equalIgnoringCase(rel, "stylesheet alternate")) {
+    } else if (equalIgnoringCase(rel, "alternate stylesheet") || equalIgnoringCase(rel, "stylesheet alternate")) {
         m_isStyleSheet = true;
         m_isAlternate = true;
     } else if (equalIgnoringCase(rel, "import")) {
         m_isImport = true;
+    } else if (equalIgnoringCase(rel, "apple-touch-icon")) {
+        if (RuntimeEnabledFeatures::touchIconLoadingEnabled()) {
+            m_iconType = TouchIcon;
+        }
+    } else if (equalIgnoringCase(rel, "apple-touch-icon-precomposed")) {
+        if (RuntimeEnabledFeatures::touchIconLoadingEnabled()) {
+            m_iconType = TouchPrecomposedIcon;
+        }
     } else {
         // Tokenize the rel attribute and set bits based on specific keywords that we find.
         String relCopy = rel;
@@ -83,24 +88,29 @@
         relCopy.split(' ', list);
         Vector<String>::const_iterator end = list.end();
         for (Vector<String>::const_iterator it = list.begin(); it != end; ++it) {
-            if (equalIgnoringCase(*it, "stylesheet"))
+            if (equalIgnoringCase(*it, "stylesheet")) {
                 m_isStyleSheet = true;
-            else if (equalIgnoringCase(*it, "alternate"))
+            } else if (equalIgnoringCase(*it, "alternate")) {
                 m_isAlternate = true;
-            else if (equalIgnoringCase(*it, "icon"))
+            } else if (equalIgnoringCase(*it, "icon")) {
                 m_iconType = Favicon;
-#if ENABLE(TOUCH_ICON_LOADING)
-            else if (equalIgnoringCase(*it, "apple-touch-icon"))
-                m_iconType = TouchIcon;
-            else if (equalIgnoringCase(*it, "apple-touch-icon-precomposed"))
-                m_iconType = TouchPrecomposedIcon;
-#endif
-            else if (equalIgnoringCase(*it, "prefetch"))
-              m_isLinkPrefetch = true;
-            else if (equalIgnoringCase(*it, "subresource"))
-              m_isLinkSubresource = true;
-            else if (equalIgnoringCase(*it, "prerender"))
-              m_isLinkPrerender = true;
+            } else if (equalIgnoringCase(*it, "prefetch")) {
+                m_isLinkPrefetch = true;
+            } else if (equalIgnoringCase(*it, "subresource")) {
+                m_isLinkSubresource = true;
+            } else if (equalIgnoringCase(*it, "prerender")) {
+                m_isLinkPrerender = true;
+            } else if (equalIgnoringCase(*it, "next")) {
+                m_isLinkNext = true;
+            } else if (equalIgnoringCase(*it, "apple-touch-icon")) {
+                if (RuntimeEnabledFeatures::touchIconLoadingEnabled()) {
+                    m_iconType = TouchIcon;
+                }
+            } else if (equalIgnoringCase(*it, "apple-touch-icon-precomposed")) {
+                if (RuntimeEnabledFeatures::touchIconLoadingEnabled()) {
+                    m_iconType = TouchPrecomposedIcon;
+                }
+            }
         }
     }
 }
diff --git a/Source/core/html/LinkRelAttribute.h b/Source/core/html/LinkRelAttribute.h
index a124012..9c2a147 100644
--- a/Source/core/html/LinkRelAttribute.h
+++ b/Source/core/html/LinkRelAttribute.h
@@ -52,6 +52,7 @@
     bool isLinkPrefetch() const { return m_isLinkPrefetch; }
     bool isLinkSubresource() const { return m_isLinkSubresource; }
     bool isLinkPrerender() const { return m_isLinkPrerender; }
+    bool isLinkNext() const { return m_isLinkNext; }
     bool isImport() const { return m_isImport; }
 
 private:
@@ -62,6 +63,7 @@
     bool m_isLinkPrefetch : 1;
     bool m_isLinkSubresource : 1;
     bool m_isLinkPrerender : 1;
+    bool m_isLinkNext : 1;
     bool m_isImport : 1;
 };
 
diff --git a/Source/core/html/LinkRelAttributeTest.cpp b/Source/core/html/LinkRelAttributeTest.cpp
index beac0e6..aecfe9d 100644
--- a/Source/core/html/LinkRelAttributeTest.cpp
+++ b/Source/core/html/LinkRelAttributeTest.cpp
@@ -30,6 +30,7 @@
 
 #include "config.h"
 #include "core/html/LinkRelAttribute.h"
+#include "RuntimeEnabledFeatures.h"
 
 #include "wtf/text/CString.h"
 #include <gtest/gtest.h>
@@ -38,6 +39,22 @@
 
 namespace {
 
+class LinkRelAttributeTest : public testing::Test {
+protected:
+    virtual void SetUp()
+    {
+        m_touchIconLoadingEnabled = RuntimeEnabledFeatures::touchIconLoadingEnabled();
+    }
+
+    virtual void TearDown()
+    {
+        RuntimeEnabledFeatures::setTouchIconLoadingEnabled(m_touchIconLoadingEnabled);
+    }
+
+private:
+    bool m_touchIconLoadingEnabled;
+};
+
 static inline void testLinkRelAttribute(String value, bool isStyleSheet, IconType iconType, bool isAlternate, bool isDNSPrefetch, bool isLinkSubresource, bool isLinkPrerender, bool isImport = false)
 {
     LinkRelAttribute linkRelAttribute(value);
@@ -50,8 +67,10 @@
     ASSERT_EQ(isImport, linkRelAttribute.isImport()) << value.utf8().data();
 }
 
-TEST(CoreLinkRelAttribute, Constructor)
+TEST_F(LinkRelAttributeTest, Constructor)
 {
+    RuntimeEnabledFeatures::setTouchIconLoadingEnabled(false);
+
     testLinkRelAttribute("stylesheet", true, InvalidIcon, false, false, false, false);
     testLinkRelAttribute("sTyLeShEeT", true, InvalidIcon, false, false, false, false);
 
@@ -60,17 +79,48 @@
     testLinkRelAttribute("shortcut icon", false, Favicon, false, false, false, false);
     testLinkRelAttribute("sHoRtCuT iCoN", false, Favicon, false, false, false, false);
 
-#if ENABLE(TOUCH_ICON_LOADING)
-    testLinkRelAttribute("apple-touch-icon", false, TouchIcon, false, false, false, false);
-    testLinkRelAttribute("aPpLe-tOuCh-IcOn", false, TouchIcon, false, false, false, false);
+    testLinkRelAttribute("dns-prefetch", false, InvalidIcon, false, true, false, false);
+    testLinkRelAttribute("dNs-pReFeTcH", false, InvalidIcon, false, true, false, false);
 
-    testLinkRelAttribute("apple-touch-icon-precomposed", false, TouchPrecomposedIcon, false, false, false, false);
-    testLinkRelAttribute("aPpLe-tOuCh-IcOn-pReCoMpOsEd", false, TouchPrecomposedIcon, false, false, false, false);
-#endif
+    testLinkRelAttribute("apple-touch-icon", false, InvalidIcon, false, false, false, false);
+    testLinkRelAttribute("aPpLe-tOuCh-IcOn", false, InvalidIcon, false, false, false, false);
+    testLinkRelAttribute("apple-touch-icon-precomposed", false, InvalidIcon, false, false, false, false);
+    testLinkRelAttribute("aPpLe-tOuCh-IcOn-pReCoMpOsEd", false, InvalidIcon, false, false, false, false);
+
+    testLinkRelAttribute("alternate stylesheet", true, InvalidIcon, true, false, false, false);
+    testLinkRelAttribute("stylesheet alternate", true, InvalidIcon, true, false, false, false);
+    testLinkRelAttribute("aLtErNaTe sTyLeShEeT", true, InvalidIcon, true, false, false, false);
+    testLinkRelAttribute("sTyLeShEeT aLtErNaTe", true, InvalidIcon, true, false, false, false);
+
+    testLinkRelAttribute("stylesheet icon prerender aLtErNaTe", true, Favicon, true, false, false, true);
+    testLinkRelAttribute("alternate subresource", false, InvalidIcon, true, false, true, false);
+    testLinkRelAttribute("alternate icon stylesheet", true, Favicon, true, false, false, false);
+
+    testLinkRelAttribute("import", false, InvalidIcon, false, false, false, false, true);
+    // "import" is mutually exclusive and "stylesheet" wins when they conflict.
+    testLinkRelAttribute("stylesheet import", true, InvalidIcon, false, false, false, false, false);
+}
+
+TEST_F(LinkRelAttributeTest, ConstructorTouchIconLoadingEnabled)
+{
+    RuntimeEnabledFeatures::setTouchIconLoadingEnabled(true);
+
+    testLinkRelAttribute("stylesheet", true, InvalidIcon, false, false, false, false);
+    testLinkRelAttribute("sTyLeShEeT", true, InvalidIcon, false, false, false, false);
+
+    testLinkRelAttribute("icon", false, Favicon, false, false, false, false);
+    testLinkRelAttribute("iCoN", false, Favicon, false, false, false, false);
+    testLinkRelAttribute("shortcut icon", false, Favicon, false, false, false, false);
+    testLinkRelAttribute("sHoRtCuT iCoN", false, Favicon, false, false, false, false);
 
     testLinkRelAttribute("dns-prefetch", false, InvalidIcon, false, true, false, false);
     testLinkRelAttribute("dNs-pReFeTcH", false, InvalidIcon, false, true, false, false);
 
+    testLinkRelAttribute("apple-touch-icon", false, TouchIcon, false, false, false, false);
+    testLinkRelAttribute("aPpLe-tOuCh-IcOn", false, TouchIcon, false, false, false, false);
+    testLinkRelAttribute("apple-touch-icon-precomposed", false, TouchPrecomposedIcon, false, false, false, false);
+    testLinkRelAttribute("aPpLe-tOuCh-IcOn-pReCoMpOsEd", false, TouchPrecomposedIcon, false, false, false, false);
+
     testLinkRelAttribute("alternate stylesheet", true, InvalidIcon, true, false, false, false);
     testLinkRelAttribute("stylesheet alternate", true, InvalidIcon, true, false, false, false);
     testLinkRelAttribute("aLtErNaTe sTyLeShEeT", true, InvalidIcon, true, false, false, false);
diff --git a/Source/core/html/LinkResource.cpp b/Source/core/html/LinkResource.cpp
index ef23952..d12d5de 100644
--- a/Source/core/html/LinkResource.cpp
+++ b/Source/core/html/LinkResource.cpp
@@ -58,7 +58,7 @@
     HTMLImport* import = m_owner->document().import();
     if (!import)
         return m_owner->document().frame();
-    return import->master()->document().frame();
+    return import->master()->frame();
 }
 
 LinkRequestBuilder::LinkRequestBuilder(HTMLLinkElement* owner)
diff --git a/Source/core/html/MediaController.cpp b/Source/core/html/MediaController.cpp
index e93bbc1..4493fe5 100644
--- a/Source/core/html/MediaController.cpp
+++ b/Source/core/html/MediaController.cpp
@@ -51,7 +51,7 @@
     , m_volume(1)
     , m_position(MediaPlayer::invalidTime())
     , m_muted(false)
-    , m_readyState(HAVE_NOTHING)
+    , m_readyState(HTMLMediaElement::HAVE_NOTHING)
     , m_playbackState(WAITING)
     , m_asyncEventTimer(this, &MediaController::asyncEventTimerFired)
     , m_clearPositionTimer(this, &MediaController::clearPositionTimerFired)
@@ -331,18 +331,18 @@
     updatePlaybackState();
 }
 
-static AtomicString eventNameForReadyState(MediaControllerInterface::ReadyState state)
+static const AtomicString& eventNameForReadyState(HTMLMediaElement::ReadyState state)
 {
     switch (state) {
-    case MediaControllerInterface::HAVE_NOTHING:
+    case HTMLMediaElement::HAVE_NOTHING:
         return EventTypeNames::emptied;
-    case MediaControllerInterface::HAVE_METADATA:
+    case HTMLMediaElement::HAVE_METADATA:
         return EventTypeNames::loadedmetadata;
-    case MediaControllerInterface::HAVE_CURRENT_DATA:
+    case HTMLMediaElement::HAVE_CURRENT_DATA:
         return EventTypeNames::loadeddata;
-    case MediaControllerInterface::HAVE_FUTURE_DATA:
+    case HTMLMediaElement::HAVE_FUTURE_DATA:
         return EventTypeNames::canplay;
-    case MediaControllerInterface::HAVE_ENOUGH_DATA:
+    case HTMLMediaElement::HAVE_ENOUGH_DATA:
         return EventTypeNames::canplaythrough;
     default:
         ASSERT_NOT_REACHED();
@@ -357,7 +357,7 @@
 
     if (m_mediaElements.isEmpty()) {
         // If the MediaController has no slaved media elements, let new readiness state be 0.
-        newReadyState = HAVE_NOTHING;
+        newReadyState = HTMLMediaElement::HAVE_NOTHING;
     } else {
         // Otherwise, let it have the lowest value of the readyState IDL attributes of all of its
         // slaved media elements.
@@ -619,15 +619,6 @@
     return true;
 }
 
-bool MediaController::hasCurrentSrc() const
-{
-    for (size_t index = 0; index < m_mediaElements.size(); ++index) {
-        if (!m_mediaElements[index]->hasCurrentSrc())
-            return false;
-    }
-    return true;
-}
-
 const AtomicString& MediaController::interfaceName() const
 {
     return EventTargetNames::MediaController;
diff --git a/Source/core/html/MediaController.h b/Source/core/html/MediaController.h
index 5b31cc2..deee58c 100644
--- a/Source/core/html/MediaController.h
+++ b/Source/core/html/MediaController.h
@@ -29,6 +29,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/events/Event.h"
 #include "core/events/EventTarget.h"
+#include "core/html/HTMLMediaElement.h"
 #include "core/html/MediaControllerInterface.h"
 #include "platform/Timer.h"
 #include "wtf/PassRefPtr.h"
@@ -43,7 +44,7 @@
 class HTMLMediaElement;
 class ExecutionContext;
 
-class MediaController : public RefCounted<MediaController>, public ScriptWrappable, public MediaControllerInterface, public EventTargetWithInlineData {
+class MediaController FINAL : public RefCounted<MediaController>, public ScriptWrappable, public MediaControllerInterface, public EventTargetWithInlineData {
     REFCOUNTED_EVENT_TARGET(MediaController);
 public:
     static PassRefPtr<MediaController> create(ExecutionContext*);
@@ -53,54 +54,49 @@
     void removeMediaElement(HTMLMediaElement*);
     bool containsMediaElement(HTMLMediaElement*) const;
 
-    const String& mediaGroup() const { return m_mediaGroup; }
+    PassRefPtr<TimeRanges> buffered() const;
+    PassRefPtr<TimeRanges> seekable() const;
+    PassRefPtr<TimeRanges> played();
 
-    virtual PassRefPtr<TimeRanges> buffered() const;
-    virtual PassRefPtr<TimeRanges> seekable() const;
-    virtual PassRefPtr<TimeRanges> played();
+    virtual double duration() const OVERRIDE;
+    virtual double currentTime() const OVERRIDE;
+    virtual void setCurrentTime(double, ExceptionState&) OVERRIDE;
 
-    virtual double duration() const;
-    virtual double currentTime() const;
-    virtual void setCurrentTime(double, ExceptionState&);
-
-    virtual bool paused() const { return m_paused; }
-    virtual void play();
-    virtual void pause();
+    virtual bool paused() const OVERRIDE { return m_paused; }
+    virtual void play() OVERRIDE;
+    virtual void pause() OVERRIDE;
     void unpause();
 
-    virtual double defaultPlaybackRate() const { return m_defaultPlaybackRate; }
-    virtual void setDefaultPlaybackRate(double);
+    double defaultPlaybackRate() const { return m_defaultPlaybackRate; }
+    void setDefaultPlaybackRate(double);
 
-    virtual double playbackRate() const;
-    virtual void setPlaybackRate(double);
+    double playbackRate() const;
+    void setPlaybackRate(double);
 
-    virtual double volume() const { return m_volume; }
-    virtual void setVolume(double, ExceptionState&);
+    virtual double volume() const OVERRIDE { return m_volume; }
+    virtual void setVolume(double, ExceptionState&) OVERRIDE;
 
-    virtual bool muted() const { return m_muted; }
-    virtual void setMuted(bool);
+    virtual bool muted() const OVERRIDE { return m_muted; }
+    virtual void setMuted(bool) OVERRIDE;
 
-    virtual ReadyState readyState() const { return m_readyState; }
+    typedef HTMLMediaElement::ReadyState ReadyState;
+    ReadyState readyState() const { return m_readyState; }
 
     enum PlaybackState { WAITING, PLAYING, ENDED };
     const AtomicString& playbackState() const;
 
-    virtual bool supportsFullscreen() const { return false; }
-    virtual bool isFullscreen() const { return false; }
-    virtual void enterFullscreen() { }
+    virtual void enterFullscreen() OVERRIDE { }
 
-    virtual bool hasAudio() const;
-    virtual bool hasVideo() const;
-    virtual bool hasClosedCaptions() const;
-    virtual void setClosedCaptionsVisible(bool);
-    virtual bool closedCaptionsVisible() const { return m_closedCaptionsVisible; }
+    virtual bool hasAudio() const OVERRIDE;
+    virtual bool hasVideo() const OVERRIDE;
+    virtual bool hasClosedCaptions() const OVERRIDE;
+    virtual void setClosedCaptionsVisible(bool) OVERRIDE;
+    virtual bool closedCaptionsVisible() const OVERRIDE { return m_closedCaptionsVisible; }
 
-    virtual void beginScrubbing();
-    virtual void endScrubbing();
+    virtual void beginScrubbing() OVERRIDE;
+    virtual void endScrubbing() OVERRIDE;
 
-    virtual bool canPlay() const;
-
-    virtual bool hasCurrentSrc() const;
+    virtual bool canPlay() const OVERRIDE;
 
     bool isBlocked() const;
 
@@ -138,7 +134,6 @@
     Vector<RefPtr<Event> > m_pendingEvents;
     Timer<MediaController> m_asyncEventTimer;
     mutable Timer<MediaController> m_clearPositionTimer;
-    String m_mediaGroup;
     bool m_closedCaptionsVisible;
     OwnPtr<Clock> m_clock;
     ExecutionContext* m_executionContext;
diff --git a/Source/core/html/MediaControllerInterface.h b/Source/core/html/MediaControllerInterface.h
index 9f8f704..481d6bd 100644
--- a/Source/core/html/MediaControllerInterface.h
+++ b/Source/core/html/MediaControllerInterface.h
@@ -26,22 +26,15 @@
 #ifndef MediaControllerInterface_h
 #define MediaControllerInterface_h
 
-#include "wtf/PassRefPtr.h"
-
 namespace WebCore {
 
 class ExceptionState;
-class TimeRanges;
 
 class MediaControllerInterface {
 public:
     virtual ~MediaControllerInterface() { };
 
-    // MediaController IDL:
-    virtual PassRefPtr<TimeRanges> buffered() const = 0;
-    virtual PassRefPtr<TimeRanges> seekable() const = 0;
-    virtual PassRefPtr<TimeRanges> played() = 0;
-
+    // MediaControlElements:
     virtual double duration() const = 0;
     virtual double currentTime() const = 0;
     virtual void setCurrentTime(double, ExceptionState&) = 0;
@@ -50,24 +43,12 @@
     virtual void play() = 0;
     virtual void pause() = 0;
 
-    virtual double defaultPlaybackRate() const = 0;
-    virtual void setDefaultPlaybackRate(double) = 0;
-
-    virtual double playbackRate() const = 0;
-    virtual void setPlaybackRate(double) = 0;
-
     virtual double volume() const = 0;
     virtual void setVolume(double, ExceptionState&) = 0;
 
     virtual bool muted() const = 0;
     virtual void setMuted(bool) = 0;
 
-    enum ReadyState { HAVE_NOTHING, HAVE_METADATA, HAVE_CURRENT_DATA, HAVE_FUTURE_DATA, HAVE_ENOUGH_DATA };
-    virtual ReadyState readyState() const = 0;
-
-    // MediaControlElements:
-    virtual bool supportsFullscreen() const = 0;
-    virtual bool isFullscreen() const = 0;
     virtual void enterFullscreen() = 0;
 
     virtual bool hasAudio() const = 0;
@@ -80,8 +61,6 @@
     virtual void endScrubbing() = 0;
 
     virtual bool canPlay() const = 0;
-
-    virtual bool hasCurrentSrc() const = 0;
 };
 
 }
diff --git a/Source/core/html/MediaDocument.cpp b/Source/core/html/MediaDocument.cpp
index 65af26d..b5c820b 100644
--- a/Source/core/html/MediaDocument.cpp
+++ b/Source/core/html/MediaDocument.cpp
@@ -42,7 +42,7 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/frame/Frame.h"
-#include "core/platform/chromium/KeyboardCodes.h"
+#include "platform/KeyboardCodes.h"
 
 namespace WebCore {
 
@@ -134,7 +134,7 @@
     ASSERT(root);
 
     for (Node* node = root; node; node = NodeTraversal::next(*node, root)) {
-        if (isHTMLVideoElement(node))
+        if (node->hasTagName(videoTag))
             return toHTMLVideoElement(node);
     }
 
diff --git a/Source/core/html/MediaError.idl b/Source/core/html/MediaError.idl
index 4cf13ed..58b94d8 100644
--- a/Source/core/html/MediaError.idl
+++ b/Source/core/html/MediaError.idl
@@ -30,6 +30,6 @@
     const unsigned short MEDIA_ERR_NETWORK = 2;
     const unsigned short MEDIA_ERR_DECODE = 3;
     const unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
-    [RuntimeEnabled=EncryptedMediaAnyVersion] const unsigned short MEDIA_ERR_ENCRYPTED = 5;
+    [RuntimeEnabled=EncryptedMediaAnyVersion, DeprecateAs=MediaErrorEncrypted] const unsigned short MEDIA_ERR_ENCRYPTED = 5;
     readonly attribute unsigned short code;
 };
diff --git a/Source/core/html/MediaFragmentURIParser.cpp b/Source/core/html/MediaFragmentURIParser.cpp
index f887a05..70cd27f 100644
--- a/Source/core/html/MediaFragmentURIParser.cpp
+++ b/Source/core/html/MediaFragmentURIParser.cpp
@@ -134,11 +134,11 @@
         //     name or value are not valid UTF-8 strings, then remove the name-value pair from the list.
         bool validUTF8 = true;
         if (!name.isEmpty()) {
-            name = name.utf8(String::StrictConversion).data();
+            name = name.utf8(StrictUTF8Conversion).data();
             validUTF8 = !name.isEmpty();
         }
         if (validUTF8 && !value.isEmpty()) {
-            value = value.utf8(String::StrictConversion).data();
+            value = value.utf8(StrictUTF8Conversion).data();
             validUTF8 = !value.isEmpty();
         }
 
diff --git a/Source/core/html/MediaKeyError.idl b/Source/core/html/MediaKeyError.idl
index 58fddc8..d746c4c 100644
--- a/Source/core/html/MediaKeyError.idl
+++ b/Source/core/html/MediaKeyError.idl
@@ -33,5 +33,5 @@
     const unsigned short MEDIA_KEYERR_HARDWARECHANGE = 5;
     const unsigned short MEDIA_KEYERR_DOMAIN = 6;
     readonly attribute unsigned short code;
-    [Conditional=ENCRYPTED_MEDIA_V2, RuntimeEnabled=EncryptedMedia] readonly attribute unsigned long systemCode;
+    [RuntimeEnabled=EncryptedMedia] readonly attribute unsigned long systemCode;
 };
diff --git a/Source/core/html/MediaKeyEvent.h b/Source/core/html/MediaKeyEvent.h
index 370abaf..f6726a2 100644
--- a/Source/core/html/MediaKeyEvent.h
+++ b/Source/core/html/MediaKeyEvent.h
@@ -43,7 +43,7 @@
     unsigned short systemCode;
 };
 
-class MediaKeyEvent : public Event {
+class MediaKeyEvent FINAL : public Event {
 public:
     virtual ~MediaKeyEvent();
 
@@ -57,7 +57,7 @@
         return adoptRef(new MediaKeyEvent(type, initializer));
     }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
     String keySystem() const { return m_keySystem; }
     String sessionId() const { return m_sessionId; }
diff --git a/Source/core/html/PluginDocument.cpp b/Source/core/html/PluginDocument.cpp
index 366ee64..59451bf 100644
--- a/Source/core/html/PluginDocument.cpp
+++ b/Source/core/html/PluginDocument.cpp
@@ -189,7 +189,7 @@
     if (!shouldLoadPluginManually())
         return;
 
-    DocumentLoader* documentLoader = frame()->loader().activeDocumentLoader();
+    DocumentLoader* documentLoader = frame()->loader().documentLoader();
     documentLoader->cancelMainResourceLoad(ResourceError::cancelledError(documentLoader->request().url()));
     setShouldLoadPluginManually(false);
 }
diff --git a/Source/core/html/PublicURLManager.cpp b/Source/core/html/PublicURLManager.cpp
index 09157de..ce41a3f 100644
--- a/Source/core/html/PublicURLManager.cpp
+++ b/Source/core/html/PublicURLManager.cpp
@@ -51,7 +51,7 @@
     if (m_isStopped)
         return;
 
-    RegistryURLMap::iterator found = m_registryToURL.add(&registrable->registry(), URLSet()).iterator;
+    RegistryURLMap::ValueType* found = m_registryToURL.add(&registrable->registry(), URLSet()).storedValue;
     found->key->registerURL(origin, url, registrable);
     found->value.add(url.string());
 }
diff --git a/Source/core/html/PublicURLManager.h b/Source/core/html/PublicURLManager.h
index 0884877..02ae77d 100644
--- a/Source/core/html/PublicURLManager.h
+++ b/Source/core/html/PublicURLManager.h
@@ -40,7 +40,7 @@
 class URLRegistry;
 class URLRegistrable;
 
-class PublicURLManager : public ActiveDOMObject {
+class PublicURLManager FINAL : public ActiveDOMObject {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassOwnPtr<PublicURLManager> create(ExecutionContext*);
diff --git a/Source/core/html/RadioNodeList.cpp b/Source/core/html/RadioNodeList.cpp
index 0522f12..d2c9f29 100644
--- a/Source/core/html/RadioNodeList.cpp
+++ b/Source/core/html/RadioNodeList.cpp
@@ -37,16 +37,17 @@
 
 using namespace HTMLNames;
 
-RadioNodeList::RadioNodeList(Node* rootNode, const AtomicString& name)
-    : LiveNodeList(rootNode, RadioNodeListType, InvalidateForFormControls, rootNode->hasTagName(formTag) ? NodeListIsRootedAtDocument : NodeListIsRootedAtNode)
+RadioNodeList::RadioNodeList(ContainerNode* rootNode, const AtomicString& name, CollectionType type)
+    : LiveNodeList(rootNode, type, InvalidateForFormControls, rootNode->hasTagName(formTag) ? NodeListIsRootedAtDocument : NodeListIsRootedAtNode)
     , m_name(name)
+    , m_onlyMatchImgElements(type == RadioImgNodeListType)
 {
     ScriptWrappable::init(this);
 }
 
 RadioNodeList::~RadioNodeList()
 {
-    ownerNode()->nodeLists()->removeCacheWithAtomicName(this, RadioNodeListType, m_name);
+    ownerNode()->nodeLists()->removeCache(this, m_onlyMatchImgElements ? RadioImgNodeListType : RadioNodeListType, m_name);
 }
 
 static inline HTMLInputElement* toRadioButtonInputElement(Node* node)
@@ -62,6 +63,8 @@
 
 String RadioNodeList::value() const
 {
+    if (m_onlyMatchImgElements)
+        return String();
     for (unsigned i = 0; i < length(); ++i) {
         Node* node = item(i);
         const HTMLInputElement* inputElement = toRadioButtonInputElement(node);
@@ -74,6 +77,8 @@
 
 void RadioNodeList::setValue(const String& value)
 {
+    if (m_onlyMatchImgElements)
+        return;
     for (unsigned i = 0; i < length(); ++i) {
         Node* node = item(i);
         HTMLInputElement* inputElement = toRadioButtonInputElement(node);
@@ -84,32 +89,32 @@
     }
 }
 
-bool RadioNodeList::checkElementMatchesRadioNodeListFilter(Element* testElement) const
+bool RadioNodeList::checkElementMatchesRadioNodeListFilter(const Element& testElement) const
 {
-    ASSERT(testElement->hasTagName(objectTag) || testElement->isFormControlElement());
+    ASSERT(!m_onlyMatchImgElements);
+    ASSERT(testElement.hasTagName(objectTag) || testElement.isFormControlElement());
     if (ownerNode()->hasTagName(formTag)) {
-        HTMLFormElement* formElement = 0;
-        if (testElement->hasTagName(objectTag))
-            formElement = toHTMLObjectElement(testElement)->form();
-        else
-            formElement = toHTMLFormControlElement(testElement)->form();
+        HTMLFormElement* formElement = toHTMLElement(testElement).formOwner();
         if (!formElement || formElement != ownerNode())
             return false;
     }
 
-    return testElement->getIdAttribute() == m_name || testElement->getNameAttribute() == m_name;
+    return testElement.getIdAttribute() == m_name || testElement.getNameAttribute() == m_name;
 }
 
-bool RadioNodeList::nodeMatches(Element* testElement) const
+bool RadioNodeList::nodeMatches(const Element& testElement) const
 {
-    if (!testElement->hasTagName(objectTag) && !testElement->isFormControlElement())
+    if (m_onlyMatchImgElements)
+        return testElement.hasTagName(imgTag);
+
+    if (!testElement.hasTagName(objectTag) && !testElement.isFormControlElement())
         return false;
 
-    if (testElement->hasTagName(inputTag) && toHTMLInputElement(testElement)->isImageButton())
+    if (testElement.hasTagName(inputTag) && toHTMLInputElement(testElement).isImageButton())
         return false;
 
     return checkElementMatchesRadioNodeListFilter(testElement);
 }
 
-} // namspace
+} // namespace
 
diff --git a/Source/core/html/RadioNodeList.h b/Source/core/html/RadioNodeList.h
index b735b0c..df7d708 100644
--- a/Source/core/html/RadioNodeList.h
+++ b/Source/core/html/RadioNodeList.h
@@ -34,10 +34,10 @@
 
 class RadioNodeList FINAL : public LiveNodeList {
 public:
-    static PassRefPtr<RadioNodeList> create(Node* ownerNode, CollectionType type, const AtomicString& name)
+    static PassRefPtr<RadioNodeList> create(ContainerNode* ownerNode, CollectionType type, const AtomicString& name)
     {
-        ASSERT_UNUSED(type, type == RadioNodeListType);
-        return adoptRef(new RadioNodeList(ownerNode, name));
+        ASSERT_UNUSED(type, type == RadioNodeListType || type == RadioImgNodeListType);
+        return adoptRef(new RadioNodeList(ownerNode, name, type));
     }
 
     virtual ~RadioNodeList();
@@ -46,15 +46,17 @@
     void setValue(const String&);
 
 private:
-    RadioNodeList(Node*, const AtomicString& name);
-    bool checkElementMatchesRadioNodeListFilter(Element*) const;
+    RadioNodeList(ContainerNode*, const AtomicString& name, CollectionType);
 
-    virtual bool nodeMatches(Element*) const OVERRIDE;
+    bool checkElementMatchesRadioNodeListFilter(const Element&) const;
+
+    virtual bool nodeMatches(const Element&) const OVERRIDE;
 
     AtomicString m_name;
+    const bool m_onlyMatchImgElements;
 };
 
-} // namepsace
+} // namespace
 
 #endif
 
diff --git a/Source/core/html/RadioNodeList.idl b/Source/core/html/RadioNodeList.idl
index 47beea0..057ad06 100644
--- a/Source/core/html/RadioNodeList.idl
+++ b/Source/core/html/RadioNodeList.idl
@@ -24,8 +24,8 @@
  */
 
 [
-    NoInterfaceObject
+    NoInterfaceObject,
 ] interface RadioNodeList : NodeList {
     attribute DOMString value;
-    [ImplementedAs=item] getter Node(unsigned long index);
+    [ImplementedAs=item] getter Node (unsigned long index);
 };
diff --git a/Source/core/html/TextDocument.h b/Source/core/html/TextDocument.h
index a36617d..d554135 100644
--- a/Source/core/html/TextDocument.h
+++ b/Source/core/html/TextDocument.h
@@ -39,7 +39,7 @@
 private:
     TextDocument(const DocumentInit&);
 
-    virtual PassRefPtr<DocumentParser> createParser();
+    virtual PassRefPtr<DocumentParser> createParser() OVERRIDE;
 };
 
 }
diff --git a/Source/core/html/URLRegistry.h b/Source/core/html/URLRegistry.h
index 660acb9..f6f2c3b 100644
--- a/Source/core/html/URLRegistry.h
+++ b/Source/core/html/URLRegistry.h
@@ -52,8 +52,9 @@
     virtual void registerURL(SecurityOrigin*, const KURL&, URLRegistrable*) = 0;
     virtual void unregisterURL(const KURL&) = 0;
 
-    // This is an optional API
+    // These are optional APIs
     virtual URLRegistrable* lookup(const String&) { ASSERT_NOT_REACHED(); return 0; }
+    virtual bool contains(const String&) { ASSERT_NOT_REACHED(); return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/VoidCallback.h b/Source/core/html/VoidCallback.h
index cda64e5..8fdf709 100644
--- a/Source/core/html/VoidCallback.h
+++ b/Source/core/html/VoidCallback.h
@@ -31,7 +31,7 @@
 class VoidCallback {
 public:
     virtual ~VoidCallback() { }
-    virtual bool handleEvent() = 0;
+    virtual void handleEvent() = 0;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/VoidCallback.idl b/Source/core/html/VoidCallback.idl
index d403ecc..970113b 100644
--- a/Source/core/html/VoidCallback.idl
+++ b/Source/core/html/VoidCallback.idl
@@ -24,5 +24,5 @@
  */
 
 callback interface VoidCallback {
-    boolean handleEvent();
+    void handleEvent();
 };
diff --git a/Source/core/html/canvas/ANGLEInstancedArrays.cpp b/Source/core/html/canvas/ANGLEInstancedArrays.cpp
index c7e5c93..adaa8ef 100644
--- a/Source/core/html/canvas/ANGLEInstancedArrays.cpp
+++ b/Source/core/html/canvas/ANGLEInstancedArrays.cpp
@@ -33,7 +33,6 @@
 #include "core/html/canvas/ANGLEInstancedArrays.h"
 
 #include "core/html/canvas/WebGLRenderingContext.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -41,7 +40,7 @@
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_ANGLE_instanced_arrays");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_ANGLE_instanced_arrays");
 }
 
 ANGLEInstancedArrays::~ANGLEInstancedArrays()
@@ -60,8 +59,7 @@
 
 bool ANGLEInstancedArrays::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_ANGLE_instanced_arrays");
+    return context->extensionsUtil()->supportsExtension("GL_ANGLE_instanced_arrays");
 }
 
 const char* ANGLEInstancedArrays::extensionName()
@@ -69,7 +67,7 @@
     return "ANGLE_instanced_arrays";
 }
 
-void ANGLEInstancedArrays::drawArraysInstancedANGLE(GC3Denum mode, GC3Dint first, GC3Dsizei count, GC3Dsizei primcount)
+void ANGLEInstancedArrays::drawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
 {
     if (isLost())
         return;
@@ -77,7 +75,7 @@
     m_context->drawArraysInstancedANGLE(mode, first, count, primcount);
 }
 
-void ANGLEInstancedArrays::drawElementsInstancedANGLE(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset, GC3Dsizei primcount)
+void ANGLEInstancedArrays::drawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, GLintptr offset, GLsizei primcount)
 {
     if (isLost())
         return;
@@ -85,7 +83,7 @@
     m_context->drawElementsInstancedANGLE(mode, count, type, offset, primcount);
 }
 
-void ANGLEInstancedArrays::vertexAttribDivisorANGLE(GC3Duint index, GC3Duint divisor)
+void ANGLEInstancedArrays::vertexAttribDivisorANGLE(GLuint index, GLuint divisor)
 {
     if (isLost())
         return;
diff --git a/Source/core/html/canvas/ANGLEInstancedArrays.h b/Source/core/html/canvas/ANGLEInstancedArrays.h
index 0b9f531..5004ec2 100644
--- a/Source/core/html/canvas/ANGLEInstancedArrays.h
+++ b/Source/core/html/canvas/ANGLEInstancedArrays.h
@@ -32,25 +32,24 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLExtension.h"
-#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
 class WebGLRenderingContext;
 
-class ANGLEInstancedArrays : public WebGLExtension, public ScriptWrappable {
+class ANGLEInstancedArrays FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<ANGLEInstancedArrays> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~ANGLEInstancedArrays();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
-    void drawArraysInstancedANGLE(GC3Denum mode, GC3Dint first, GC3Dsizei count, GC3Dsizei primcount);
-    void drawElementsInstancedANGLE(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset, GC3Dsizei primcount);
-    void vertexAttribDivisorANGLE(GC3Duint index, GC3Duint divisor);
+    void drawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+    void drawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, GLintptr offset, GLsizei primcount);
+    void vertexAttribDivisorANGLE(GLuint index, GLuint divisor);
 
 private:
     ANGLEInstancedArrays(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/ANGLEInstancedArrays.idl b/Source/core/html/canvas/ANGLEInstancedArrays.idl
index 2d257cc..3a7593e 100644
--- a/Source/core/html/canvas/ANGLEInstancedArrays.idl
+++ b/Source/core/html/canvas/ANGLEInstancedArrays.idl
@@ -29,12 +29,13 @@
  */
 
 [
+    DoNotCheckConstants,
     NoInterfaceObject,
-    DoNotCheckConstants
+    StrictTypeChecking,
 ] interface ANGLEInstancedArrays {
     const unsigned long VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88FE;
 
-    [StrictTypeChecking] void drawArraysInstancedANGLE(unsigned long mode, long first, long count, long primcount);
-    [StrictTypeChecking] void drawElementsInstancedANGLE(unsigned long mode, long count, unsigned long type, long long offset, long primcount);
-    [StrictTypeChecking] void vertexAttribDivisorANGLE(unsigned long index, long divisor);
+    void drawArraysInstancedANGLE(unsigned long mode, long first, long count, long primcount);
+    void drawElementsInstancedANGLE(unsigned long mode, long count, unsigned long type, long long offset, long primcount);
+    void vertexAttribDivisorANGLE(unsigned long index, long divisor);
 };
diff --git a/Source/core/html/canvas/CanvasGradient.cpp b/Source/core/html/canvas/CanvasGradient.cpp
index 07e62a0..c63aa7d 100644
--- a/Source/core/html/canvas/CanvasGradient.cpp
+++ b/Source/core/html/canvas/CanvasGradient.cpp
@@ -49,13 +49,13 @@
 void CanvasGradient::addColorStop(float value, const String& color, ExceptionState& exceptionState)
 {
     if (!(value >= 0 && value <= 1.0f)) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, "The provided value (" + String::number(value) + ") is outside the range (0.0, 1.0).");
         return;
     }
 
     RGBA32 rgba = 0;
     if (!parseColorOrCurrentColor(rgba, color, 0 /*canvas*/)) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The value provided ('" + color + "') could not be parsed as a color.");
         return;
     }
 
diff --git a/Source/core/html/canvas/CanvasPathMethods.cpp b/Source/core/html/canvas/CanvasPathMethods.cpp
index 9d76556..4db53ac 100644
--- a/Source/core/html/canvas/CanvasPathMethods.cpp
+++ b/Source/core/html/canvas/CanvasPathMethods.cpp
@@ -113,7 +113,7 @@
         return;
 
     if (r < 0) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, "The radius provided (" + String::number(r) + ") is negative.");
         return;
     }
 
@@ -140,12 +140,13 @@
     /* http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-arc
      * If the anticlockwise argument is false and endAngle-startAngle is equal to or greater than 2pi, or,
      * if the anticlockwise argument is true and startAngle-endAngle is equal to or greater than 2pi,
-     * then the arc is the whole circumference of this ellipse.
+     * then the arc is the whole circumference of this ellipse, and the point at startAngle along this circle's circumference,
+     * measured in radians clockwise from the ellipse's semi-major axis, acts as both the start point and the end point.
      */
     if (!anticlockwise && endAngle - startAngle >= twoPi)
-        newEndAngle = startAngle + twoPi + fmodf(endAngle - startAngle, twoPi);
+        newEndAngle = startAngle + twoPi;
     else if (anticlockwise && startAngle - endAngle >= twoPi)
-        newEndAngle = startAngle - twoPi - fmodf(startAngle - endAngle, twoPi);
+        newEndAngle = startAngle - twoPi;
 
     /*
      * Otherwise, the arc is the path along the circumference of this ellipse from the start point to the end point,
@@ -162,7 +163,7 @@
     else if (anticlockwise && startAngle < endAngle)
         newEndAngle = startAngle - (twoPi - fmodf(endAngle - startAngle, twoPi));
 
-    ASSERT(std::abs(newEndAngle - startAngle) < 4 * piFloat);
+    ASSERT(ellipseIsRenderable(startAngle, newEndAngle));
     return newEndAngle;
 }
 
@@ -221,11 +222,11 @@
  * Angles for P are 0 and Pi in the ellipse coordinates.
  *
  * To handle both cases, degenerateEllipse() lines to start angle, local maximum points(every 0.5Pi), and end angle.
- * NOTE: Before ellipse() calls this function, adjustEndAngle() is called, so endAngle - startAngle must be less than 4Pi.
+ * NOTE: Before ellipse() calls this function, adjustEndAngle() is called, so endAngle - startAngle must be equal to or less than 2Pi.
  */
 void degenerateEllipse(CanvasPathMethods* path, float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise)
 {
-    ASSERT(std::abs(endAngle - startAngle) < 4 * piFloat);
+    ASSERT(ellipseIsRenderable(startAngle, endAngle));
     ASSERT(startAngle >= 0 && startAngle < 2 * piFloat);
     ASSERT((anticlockwise && (startAngle - endAngle) >= 0) || (!anticlockwise && (endAngle - startAngle) >= 0));
 
@@ -259,7 +260,7 @@
         return;
 
     if (radius < 0) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, "The radius provided (" + String::number(radius) + ") is negative.");
         return;
     }
 
@@ -282,8 +283,12 @@
     if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radiusX) || !std::isfinite(radiusY) || !std::isfinite(rotation) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
         return;
 
-    if (radiusX < 0 || radiusY < 0) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+    if (radiusX < 0) {
+        exceptionState.throwDOMException(IndexSizeError, "The major-axis radius provided (" + String::number(radiusX) + ") is negative.");
+        return;
+    }
+    if (radiusY < 0) {
+        exceptionState.throwDOMException(IndexSizeError, "The minor-axis radius provided (" + String::number(radiusY) + ") is negative.");
         return;
     }
 
diff --git a/Source/core/html/canvas/CanvasPattern.cpp b/Source/core/html/canvas/CanvasPattern.cpp
index f7ee0da..e011ff0 100644
--- a/Source/core/html/canvas/CanvasPattern.cpp
+++ b/Source/core/html/canvas/CanvasPattern.cpp
@@ -54,7 +54,7 @@
         repeatY = true;
         return;
     }
-    exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+    exceptionState.throwDOMException(SyntaxError, "The provided type ('" + type + "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'.");
 }
 
 CanvasPattern::CanvasPattern(PassRefPtr<Image> image, bool repeatX, bool repeatY, bool originClean)
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index 68f213b..eca1634 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -34,11 +34,12 @@
 #include "core/html/canvas/CanvasRenderingContext2D.h"
 
 #include "CSSPropertyNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/css/CSSFontSelector.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ExceptionCode.h"
@@ -80,7 +81,6 @@
 CanvasRenderingContext2D::CanvasRenderingContext2D(HTMLCanvasElement* canvas, const Canvas2DContextAttributes* attrs, bool usesCSSCompatibilityParseMode)
     : CanvasRenderingContext(canvas)
     , m_stateStack(1)
-    , m_unrealizedSaveCount(0)
     , m_usesCSSCompatibilityParseMode(usesCSSCompatibilityParseMode)
     , m_hasAlpha(!attrs || attrs->alpha())
 {
@@ -121,7 +121,6 @@
     m_stateStack.resize(1);
     m_stateStack.first() = State();
     m_path.clear();
-    m_unrealizedSaveCount = 0;
 }
 
 // Important: Several of these properties are also stored in GraphicsContext's
@@ -129,7 +128,8 @@
 // that the canvas 2d spec specifies. Make sure to sync the initial state of the
 // GraphicsContext in HTMLCanvasElement::createImageBuffer()!
 CanvasRenderingContext2D::State::State()
-    : m_strokeStyle(CanvasStyle::createFromRGBA(Color::black))
+    : m_unrealizedSaveCount(0)
+    , m_strokeStyle(CanvasStyle::createFromRGBA(Color::black))
     , m_fillStyle(CanvasStyle::createFromRGBA(Color::black))
     , m_lineWidth(1)
     , m_lineCap(ButtCap)
@@ -151,7 +151,8 @@
 }
 
 CanvasRenderingContext2D::State::State(const State& other)
-    : FontSelectorClient()
+    : CSSFontSelectorClient()
+    , m_unrealizedSaveCount(other.m_unrealizedSaveCount)
     , m_unparsedStrokeColor(other.m_unparsedStrokeColor)
     , m_unparsedFillColor(other.m_unparsedFillColor)
     , m_strokeStyle(other.m_strokeStyle)
@@ -177,7 +178,7 @@
     , m_realizedFont(other.m_realizedFont)
 {
     if (m_realizedFont)
-        m_font.fontSelector()->registerForInvalidationCallbacks(this);
+        static_cast<CSSFontSelector*>(m_font.fontSelector())->registerForInvalidationCallbacks(this);
 }
 
 CanvasRenderingContext2D::State& CanvasRenderingContext2D::State::operator=(const State& other)
@@ -186,8 +187,9 @@
         return *this;
 
     if (m_realizedFont)
-        m_font.fontSelector()->unregisterForInvalidationCallbacks(this);
+        static_cast<CSSFontSelector*>(m_font.fontSelector())->unregisterForInvalidationCallbacks(this);
 
+    m_unrealizedSaveCount = other.m_unrealizedSaveCount;
     m_unparsedStrokeColor = other.m_unparsedStrokeColor;
     m_unparsedFillColor = other.m_unparsedFillColor;
     m_strokeStyle = other.m_strokeStyle;
@@ -212,7 +214,7 @@
     m_realizedFont = other.m_realizedFont;
 
     if (m_realizedFont)
-        m_font.fontSelector()->registerForInvalidationCallbacks(this);
+        static_cast<CSSFontSelector*>(m_font.fontSelector())->registerForInvalidationCallbacks(this);
 
     return *this;
 }
@@ -220,10 +222,10 @@
 CanvasRenderingContext2D::State::~State()
 {
     if (m_realizedFont)
-        m_font.fontSelector()->unregisterForInvalidationCallbacks(this);
+        static_cast<CSSFontSelector*>(m_font.fontSelector())->unregisterForInvalidationCallbacks(this);
 }
 
-void CanvasRenderingContext2D::State::fontsNeedUpdate(FontSelector* fontSelector)
+void CanvasRenderingContext2D::State::fontsNeedUpdate(CSSFontSelector* fontSelector)
 {
     ASSERT_ARG(fontSelector, fontSelector == m_font.fontSelector());
     ASSERT(m_realizedFont);
@@ -231,22 +233,30 @@
     m_font.update(fontSelector);
 }
 
-void CanvasRenderingContext2D::realizeSavesLoop()
+void CanvasRenderingContext2D::realizeSaves()
 {
-    ASSERT(m_unrealizedSaveCount);
-    ASSERT(m_stateStack.size() >= 1);
-    GraphicsContext* context = drawingContext();
-    do {
+    if (state().m_unrealizedSaveCount) {
+        ASSERT(m_stateStack.size() >= 1);
+        // Reduce the current state's unrealized count by one now,
+        // to reflect the fact we are saving one state.
+        m_stateStack.last().m_unrealizedSaveCount--;
         m_stateStack.append(state());
+        // Set the new state's unrealized count to 0, because it has no outstanding saves.
+        // We need to do this explicitly because the copy constructor and operator= used
+        // by the Vector operations copy the unrealized count from the previous state (in
+        // turn necessary to support correct resizing and unwinding of the stack).
+        m_stateStack.last().m_unrealizedSaveCount = 0;
+        GraphicsContext* context = drawingContext();
         if (context)
             context->save();
-    } while (--m_unrealizedSaveCount);
+    }
 }
 
 void CanvasRenderingContext2D::restore()
 {
-    if (m_unrealizedSaveCount) {
-        --m_unrealizedSaveCount;
+    if (state().m_unrealizedSaveCount) {
+        // We never realized the save, so just record that it was unnecessary.
+        --m_stateStack.last().m_unrealizedSaveCount;
         return;
     }
     ASSERT(m_stateStack.size() >= 1);
@@ -256,9 +266,8 @@
     m_stateStack.removeLast();
     m_path.transform(state().m_transform.inverse());
     GraphicsContext* c = drawingContext();
-    if (!c)
-        return;
-    c->restore();
+    if (c)
+        c->restore();
 }
 
 CanvasStyle* CanvasRenderingContext2D::strokeStyle() const
@@ -497,17 +506,6 @@
     applyLineDash();
 }
 
-void CanvasRenderingContext2D::setWebkitLineDash(const Vector<float>& dash)
-{
-    if (!lineDashSequenceIsValid(dash))
-        return;
-
-    realizeSaves();
-    modifiableState().m_lineDash = dash;
-
-    applyLineDash();
-}
-
 float CanvasRenderingContext2D::lineDashOffset() const
 {
     return state().m_lineDashOffset;
@@ -523,16 +521,6 @@
     applyLineDash();
 }
 
-float CanvasRenderingContext2D::webkitLineDashOffset() const
-{
-    return lineDashOffset();
-}
-
-void CanvasRenderingContext2D::setWebkitLineDashOffset(float offset)
-{
-    setLineDashOffset(offset);
-}
-
 void CanvasRenderingContext2D::applyLineDash() const
 {
     GraphicsContext* c = drawingContext();
@@ -1289,7 +1277,7 @@
 void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap, float x, float y, ExceptionState& exceptionState)
 {
     if (!bitmap) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The element provided is invalid.");
         return;
     }
     drawImage(bitmap, x, y, bitmap->width(), bitmap->height(), exceptionState);
@@ -1299,7 +1287,7 @@
     float x, float y, float width, float height, ExceptionState& exceptionState)
 {
     if (!bitmap) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The element provided is invalid.");
         return;
     }
     if (!bitmap->bitmapRect().width() || !bitmap->bitmapRect().height())
@@ -1313,7 +1301,7 @@
     float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
 {
     if (!bitmap) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The element provided is invalid.");
         return;
     }
 
@@ -1325,12 +1313,8 @@
         || !std::isfinite(srcRect.x()) || !std::isfinite(srcRect.y()) || !std::isfinite(srcRect.width()) || !std::isfinite(srcRect.height()))
         return;
 
-    if (!dstRect.width() || !dstRect.height())
+    if (!dstRect.width() || !dstRect.height() || !srcRect.width() || !srcRect.height())
         return;
-    if (!srcRect.width() || !srcRect.height()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
 
     ASSERT(bitmap->height() && bitmap->width());
     FloatRect normalizedSrcRect = normalizeRect(srcRect);
@@ -1364,7 +1348,7 @@
 void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, float x, float y, ExceptionState& exceptionState)
 {
     if (!image) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The image element provided is invalid.");
         return;
     }
     LayoutSize destRectSize = sizeFor(image, ImageSizeAfterDevicePixelRatio);
@@ -1375,7 +1359,7 @@
     float x, float y, float width, float height, ExceptionState& exceptionState)
 {
     if (!image) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The image element provided is invalid.");
         return;
     }
     LayoutSize sourceRectSize = sizeFor(image, ImageSizeBeforeDevicePixelRatio);
@@ -1397,7 +1381,7 @@
 void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator& op, const blink::WebBlendMode& blendMode, ExceptionState& exceptionState)
 {
     if (!image) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The image element provided is invalid.");
         return;
     }
 
@@ -1410,22 +1394,13 @@
         return;
 
     LayoutSize size = sizeFor(image, ImageSizeBeforeDevicePixelRatio);
-    if (!size.width() || !size.height()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
-        return;
-    }
-
-    if (!dstRect.width() || !dstRect.height())
+    if (!size.width() || !size.height() || !dstRect.width() || !dstRect.height() || !srcRect.width() || !srcRect.height())
         return;
 
     FloatRect normalizedSrcRect = normalizeRect(srcRect);
     FloatRect normalizedDstRect = normalizeRect(dstRect);
 
     FloatRect imageRect = FloatRect(FloatPoint(), size);
-    if (!srcRect.width() || !srcRect.height()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
     if (!imageRect.intersects(normalizedSrcRect))
         return;
 
@@ -1466,21 +1441,14 @@
     const FloatRect& dstRect, ExceptionState& exceptionState)
 {
     if (!sourceCanvas) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The canvas element provided is invalid.");
         return;
     }
 
     FloatRect srcCanvasRect = FloatRect(FloatPoint(), sourceCanvas->size());
 
-    if (!srcCanvasRect.width() || !srcCanvasRect.height()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+    if (!srcCanvasRect.width() || !srcCanvasRect.height() || !srcRect.width() || !srcRect.height())
         return;
-    }
-
-    if (!srcRect.width() || !srcRect.height()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
 
     FloatRect normalizedSrcRect = normalizeRect(srcRect);
     FloatRect normalizedDstRect = normalizeRect(dstRect);
@@ -1540,7 +1508,7 @@
 void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, float x, float y, ExceptionState& exceptionState)
 {
     if (!video) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The video element provided is invalid.");
         return;
     }
     IntSize size = sizeFor(video);
@@ -1551,7 +1519,7 @@
     float x, float y, float width, float height, ExceptionState& exceptionState)
 {
     if (!video) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The video element provided is invalid.");
         return;
     }
     IntSize size = sizeFor(video);
@@ -1568,18 +1536,16 @@
 void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState& exceptionState)
 {
     if (!video) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The video element provided is invalid.");
         return;
     }
 
     if (video->readyState() == HTMLMediaElement::HAVE_NOTHING || video->readyState() == HTMLMediaElement::HAVE_METADATA)
         return;
+    if (!srcRect.width() || !srcRect.height())
+        return;
 
     FloatRect videoRect = FloatRect(FloatPoint(), sizeFor(video));
-    if (!srcRect.width() || !srcRect.height()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return;
-    }
 
     FloatRect normalizedSrcRect = normalizeRect(srcRect);
     FloatRect normalizedDstRect = normalizeRect(dstRect);
@@ -1700,10 +1666,17 @@
 
 PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1, ExceptionState& exceptionState)
 {
-    if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(x1) || !std::isfinite(y1)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+    if (!std::isfinite(x0))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(x0, "x0"));
+    else if (!std::isfinite(y0))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(y0, "y0"));
+    else if (!std::isfinite(x1))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(x1, "x1"));
+    else if (!std::isfinite(y1))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(y1, "y1"));
+
+    if (exceptionState.hadException())
         return 0;
-    }
 
     RefPtr<CanvasGradient> gradient = CanvasGradient::create(FloatPoint(x0, y0), FloatPoint(x1, y1));
     return gradient.release();
@@ -1711,15 +1684,23 @@
 
 PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1, ExceptionState& exceptionState)
 {
-    if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(r0) || !std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(r1)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
+    if (!std::isfinite(x0))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(x0, "x0"));
+    else if (!std::isfinite(y0))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(y0, "y0"));
+    else if (!std::isfinite(r0))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(r0, "r0"));
+    else if (!std::isfinite(x1))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(x1, "x1"));
+    else if (!std::isfinite(y1))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(y1, "y1"));
+    else if (!std::isfinite(r1))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(r1, "r1"));
+    else if (r0 < 0 || r1 < 0)
+        exceptionState.throwDOMException(IndexSizeError, String::format("The %s provided is less than 0.", r0 < 0 ? "r0" : "r1"));
 
-    if (r0 < 0 || r1 < 0) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+    if (exceptionState.hadException())
         return 0;
-    }
 
     RefPtr<CanvasGradient> gradient = CanvasGradient::create(FloatPoint(x0, y0), r0, FloatPoint(x1, y1), r1);
     return gradient.release();
@@ -1729,7 +1710,7 @@
     const String& repetitionType, ExceptionState& exceptionState)
 {
     if (!image) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The image element provided is invalid.");
         return 0;
     }
     bool repeatX, repeatY;
@@ -1756,14 +1737,13 @@
 PassRefPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(HTMLCanvasElement* canvas,
     const String& repetitionType, ExceptionState& exceptionState)
 {
-    if (!canvas) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+    if (!canvas)
+        exceptionState.throwDOMException(TypeMismatchError, "The canvas element provided is invalid.");
+    else if (!canvas->width() || !canvas->height())
+        exceptionState.throwDOMException(InvalidStateError, String::format("The canvas %s is 0.", canvas->width() ? "height" : "width"));
+
+    if (exceptionState.hadException())
         return 0;
-    }
-    if (!canvas->width() || !canvas->height()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
-        return 0;
-    }
 
     bool repeatX, repeatY;
     CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, exceptionState);
@@ -1841,7 +1821,7 @@
 PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(PassRefPtr<ImageData> imageData, ExceptionState& exceptionState) const
 {
     if (!imageData) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The ImageData provided is invalid.");
         return 0;
     }
 
@@ -1850,14 +1830,15 @@
 
 PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float sh, ExceptionState& exceptionState) const
 {
-    if (!sw || !sh) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+    if (!sw || !sh)
+        exceptionState.throwDOMException(IndexSizeError, String::format("The source %s is 0.", sw ? "height" : "width"));
+    else if (!std::isfinite(sw))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(sw, "source width"));
+    else if (!std::isfinite(sh))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(sh, "source height"));
+
+    if (exceptionState.hadException())
         return 0;
-    }
-    if (!std::isfinite(sw) || !std::isfinite(sh)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
 
     FloatSize logicalSize(fabs(sw), fabs(sh));
     if (!logicalSize.isExpressibleAsIntSize())
@@ -1879,19 +1860,21 @@
 
 PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(float sx, float sy, float sw, float sh, ExceptionState& exceptionState) const
 {
-    if (!canvas()->originClean()) {
+    if (!canvas()->originClean())
         exceptionState.throwSecurityError("The canvas has been tainted by cross-origin data.");
-        return 0;
-    }
+    else if (!sw || !sh)
+        exceptionState.throwDOMException(IndexSizeError, String::format("The source %s is 0.", sw ? "height" : "width"));
+    else if (!std::isfinite(sx))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(sx, "source X"));
+    else if (!std::isfinite(sy))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(sy, "source Y"));
+    else if (!std::isfinite(sw))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(sw, "source width"));
+    else if (!std::isfinite(sh))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(sh, "source height"));
 
-    if (!sw || !sh) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+    if (exceptionState.hadException())
         return 0;
-    }
-    if (!std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return 0;
-    }
 
     if (sw < 0) {
         sx += sw;
@@ -1925,7 +1908,7 @@
 void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, ExceptionState& exceptionState)
 {
     if (!data) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+        exceptionState.throwDOMException(TypeMismatchError, "The ImageData provided is invalid.");
         return;
     }
     putImageData(data, dx, dy, 0, 0, data->width(), data->height(), exceptionState);
@@ -1934,14 +1917,23 @@
 void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, float dirtyX, float dirtyY,
     float dirtyWidth, float dirtyHeight, ExceptionState& exceptionState)
 {
-    if (!data) {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
+    if (!data)
+        exceptionState.throwDOMException(TypeMismatchError, "The ImageData provided is invalid.");
+    else if (!std::isfinite(dx))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(dx, "dx"));
+    else if (!std::isfinite(dy))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(dy, "dy"));
+    else if (!std::isfinite(dirtyX))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(dirtyX, "dirtyX"));
+    else if (!std::isfinite(dirtyY))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(dirtyY, "dirtyY"));
+    else if (!std::isfinite(dirtyWidth))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(dirtyWidth, "dirtyWidth"));
+    else if (!std::isfinite(dirtyHeight))
+        exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(dirtyHeight, "dirtyHeight"));
+
+    if (exceptionState.hadException())
         return;
-    }
-    if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dirtyX) || !std::isfinite(dirtyY) || !std::isfinite(dirtyWidth) || !std::isfinite(dirtyHeight)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return;
-    }
 
     ImageBuffer* buffer = canvas()->buffer();
     if (!buffer)
@@ -2018,7 +2010,7 @@
     if (!parsedStyle) {
         parsedStyle = MutableStylePropertySet::create();
         CSSParserMode mode = m_usesCSSCompatibilityParseMode ? HTMLQuirksMode : HTMLStandardMode;
-        CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, newFont, true, mode, 0);
+        BisonCSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, newFont, true, mode, 0);
         m_fetchedFonts.add(newFont, parsedStyle);
     }
     if (parsedStyle->isEmpty())
@@ -2069,7 +2061,7 @@
     styleResolver.applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), newStyle.get());
 
     if (state().m_realizedFont)
-        state().m_font.fontSelector()->unregisterForInvalidationCallbacks(&modifiableState());
+        static_cast<CSSFontSelector*>(state().m_font.fontSelector())->unregisterForInvalidationCallbacks(&modifiableState());
     modifiableState().m_font = newStyle->font();
     modifiableState().m_font.update(canvas()->document().styleEngine()->fontSelector());
     modifiableState().m_realizedFont = true;
@@ -2396,7 +2388,7 @@
     c->setCompositeOperation(CompositeSourceOver, blink::WebBlendModeNormal);
 
     // These should match the style defined in html.css.
-    Color focusRingColor = RenderTheme::focusRingColor();
+    Color focusRingColor = RenderTheme::theme().focusRingColor();
     const int focusRingWidth = 5;
     const int focusRingOutline = 0;
     c->drawFocusRing(path, focusRingWidth, focusRingOutline, focusRingColor);
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.h b/Source/core/html/canvas/CanvasRenderingContext2D.h
index 8493b10..90b1fc7 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.h
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.h
@@ -26,6 +26,7 @@
 #ifndef CanvasRenderingContext2D_h
 #define CanvasRenderingContext2D_h
 
+#include "core/css/CSSFontSelectorClient.h"
 #include "core/html/canvas/Canvas2DContextAttributes.h"
 #include "core/html/canvas/CanvasPathMethods.h"
 #include "core/html/canvas/CanvasRenderingContext.h"
@@ -62,7 +63,7 @@
 
 typedef HashMap<String, RefPtr<MutableStylePropertySet> > MutableStylePropertyMap;
 
-class CanvasRenderingContext2D : public CanvasRenderingContext, public CanvasPathMethods {
+class CanvasRenderingContext2D FINAL : public CanvasRenderingContext, public CanvasPathMethods {
 public:
     static PassOwnPtr<CanvasRenderingContext2D> create(HTMLCanvasElement* canvas, const Canvas2DContextAttributes* attrs, bool usesCSSCompatibilityParseMode)
     {
@@ -90,12 +91,9 @@
 
     const Vector<float>& getLineDash() const;
     void setLineDash(const Vector<float>&);
-    void setWebkitLineDash(const Vector<float>&);
 
     float lineDashOffset() const;
     void setLineDashOffset(float);
-    float webkitLineDashOffset() const;
-    void setWebkitLineDashOffset(float);
 
     float shadowOffsetX() const;
     void setShadowOffsetX(float);
@@ -115,7 +113,7 @@
     String globalCompositeOperation() const;
     void setGlobalCompositeOperation(const String&);
 
-    void save() { ++m_unrealizedSaveCount; }
+    void save() { ++m_stateStack.last().m_unrealizedSaveCount; }
     void restore();
 
     SVGMatrix currentTransform() const
@@ -240,14 +238,17 @@
     bool drawCustomFocusRing(Element*);
 
 private:
-    struct State : FontSelectorClient {
+    struct State FINAL : CSSFontSelectorClient {
         State();
         virtual ~State();
 
         State(const State&);
         State& operator=(const State&);
 
-        virtual void fontsNeedUpdate(FontSelector*) OVERRIDE;
+        // CSSFontSelectorClient implementation
+        virtual void fontsNeedUpdate(CSSFontSelector*) OVERRIDE;
+
+        unsigned m_unrealizedSaveCount;
 
         String m_unparsedStrokeColor;
         String m_unparsedFillColor;
@@ -280,7 +281,7 @@
 
     CanvasRenderingContext2D(HTMLCanvasElement*, const Canvas2DContextAttributes* attrs, bool usesCSSCompatibilityParseMode);
 
-    State& modifiableState() { ASSERT(!m_unrealizedSaveCount); return m_stateStack.last(); }
+    State& modifiableState() { ASSERT(!state().m_unrealizedSaveCount); return m_stateStack.last(); }
     const State& state() const { return m_stateStack.last(); }
 
     void applyLineDash() const;
@@ -296,12 +297,7 @@
     GraphicsContext* drawingContext() const;
 
     void unwindStateStack();
-    void realizeSaves()
-    {
-        if (m_unrealizedSaveCount)
-            realizeSavesLoop();
-    }
-    void realizeSavesLoop();
+    void realizeSaves();
 
     void applyStrokePattern();
     void applyFillPattern();
@@ -326,12 +322,11 @@
     virtual bool isAccelerated() const OVERRIDE;
     virtual bool hasAlpha() const OVERRIDE { return m_hasAlpha; }
 
-    virtual bool isTransformInvertible() const { return state().m_invertibleCTM; }
+    virtual bool isTransformInvertible() const OVERRIDE { return state().m_invertibleCTM; }
 
     virtual blink::WebLayer* platformLayer() const OVERRIDE;
 
     Vector<State, 1> m_stateStack;
-    unsigned m_unrealizedSaveCount;
     bool m_usesCSSCompatibilityParseMode;
     bool m_hasAlpha;
     MutableStylePropertyMap m_fetchedFonts;
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.idl b/Source/core/html/canvas/CanvasRenderingContext2D.idl
index 1c243a6..d99a6a0 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.idl
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.idl
@@ -58,10 +58,6 @@
     sequence<float> getLineDash();
     attribute float lineDashOffset;
 
-    // FIXME: These attributes should be implemented.
-    // [Custom] attribute Array webkitLineDash;
-    // attribute float webkitLineDashOffset;
-
     void clearRect(float x, float y, float width, float height);
     void fillRect(float x, float y, float width, float height);
 
@@ -78,7 +74,7 @@
     [RaisesException] void arcTo(float x1, float y1, float x2, float y2, float radius);
     void rect(float x, float y, float width, float height);
     [RaisesException] void arc(float x, float y, float radius, float startAngle, float endAngle, [Default=Undefined] optional boolean anticlockwise);
-    [RaisesException] void ellipse(float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, boolean anticlockwise);
+    [RaisesException] void ellipse(float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, [Default=Undefined] optional boolean anticlockwise);
 
     void fill(optional CanvasWindingRule winding);
     void stroke();
@@ -146,8 +142,8 @@
     [RaisesException] void putImageData(ImageData? imagedata, float dx, float dy);
     [RaisesException] void putImageData(ImageData? imagedata, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight);
 
-    [RaisesException] void webkitPutImageDataHD(ImageData? imagedata, float dx, float dy);
-    [RaisesException] void webkitPutImageDataHD(ImageData? imagedata, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight);
+    [RaisesException, DeprecateAs=PrefixedPutImageDataHD] void webkitPutImageDataHD(ImageData? imagedata, float dx, float dy);
+    [RaisesException, DeprecateAs=PrefixedPutImageDataHD] void webkitPutImageDataHD(ImageData? imagedata, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight);
 
     [RaisesException] CanvasPattern createPattern(HTMLCanvasElement? canvas, [TreatNullAs=NullString] DOMString repetitionType);
     [RaisesException] CanvasPattern createPattern(HTMLImageElement? image, [TreatNullAs=NullString] DOMString repetitionType);
@@ -160,7 +156,7 @@
     // pixel manipulation
     [RaisesException] ImageData getImageData(float sx, float sy, float sw, float sh);
 
-    [RaisesException] ImageData webkitGetImageDataHD(float sx, float sy, float sw, float sh);
+    [RaisesException, DeprecateAs=PrefixedGetImageDataHD] ImageData webkitGetImageDataHD(float sx, float sy, float sw, float sh);
 
     // Focus rings
     [RuntimeEnabled=ExperimentalCanvasFeatures] void drawSystemFocusRing(Element element);
@@ -168,8 +164,8 @@
 
     readonly attribute float webkitBackingStorePixelRatio;
 
-    [ImplementedAs=imageSmoothingEnabled] attribute boolean webkitImageSmoothingEnabled;
-    attribute boolean imageSmoothingEnabled;
+    [ImplementedAs=imageSmoothingEnabled, MeasureAs=PrefixedImageSmoothingEnabled] attribute boolean webkitImageSmoothingEnabled;
+    [MeasureAs=UnprefixedImageSmoothingEnabled] attribute boolean imageSmoothingEnabled;
 
     Canvas2DContextAttributes getContextAttributes();
 };
diff --git a/Source/core/html/canvas/CanvasStyle.cpp b/Source/core/html/canvas/CanvasStyle.cpp
index b68421a..d722986 100644
--- a/Source/core/html/canvas/CanvasStyle.cpp
+++ b/Source/core/html/canvas/CanvasStyle.cpp
@@ -30,7 +30,7 @@
 #include "core/html/canvas/CanvasStyle.h"
 
 #include "CSSPropertyNames.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/StylePropertySet.h"
 #include "core/html/HTMLCanvasElement.h"
 #include "core/html/canvas/CanvasGradient.h"
@@ -46,9 +46,9 @@
 {
     if (equalIgnoringCase(colorString, "currentcolor"))
         return ParsedCurrentColor;
-    if (CSSParser::parseColor(parsedColor, colorString))
+    if (BisonCSSParser::parseColor(parsedColor, colorString))
         return ParsedRGBA;
-    if (CSSParser::parseSystemColor(parsedColor, colorString, document))
+    if (BisonCSSParser::parseSystemColor(parsedColor, colorString, document))
         return ParsedSystemColor;
     return ParseFailed;
 }
@@ -58,7 +58,7 @@
     if (!canvas || !canvas->inDocument() || !canvas->inlineStyle())
         return Color::black;
     RGBA32 rgba = Color::black;
-    CSSParser::parseColor(rgba, canvas->inlineStyle()->getPropertyValue(CSSPropertyColor));
+    BisonCSSParser::parseColor(rgba, canvas->inlineStyle()->getPropertyValue(CSSPropertyColor));
     return rgba;
 }
 
diff --git a/Source/core/html/canvas/DOMPath.h b/Source/core/html/canvas/DOMPath.h
index 9ce2cba..abb01a6 100644
--- a/Source/core/html/canvas/DOMPath.h
+++ b/Source/core/html/canvas/DOMPath.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class DOMPath : public RefCounted<DOMPath>, public CanvasPathMethods, public ScriptWrappable {
+class DOMPath FINAL : public RefCounted<DOMPath>, public CanvasPathMethods, public ScriptWrappable {
     WTF_MAKE_NONCOPYABLE(DOMPath); WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassRefPtr<DOMPath> create() { return adoptRef(new DOMPath); }
diff --git a/Source/core/html/canvas/DataView.cpp b/Source/core/html/canvas/DataView.cpp
index 5a28161..7399476 100644
--- a/Source/core/html/canvas/DataView.cpp
+++ b/Source/core/html/canvas/DataView.cpp
@@ -133,7 +133,7 @@
 T DataView::getData(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState) const
 {
     if (beyondRange<T>(byteOffset)) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, "The provided offset (" + String::number(byteOffset) + ") is outside the allowed range.");
         return 0;
     }
 
@@ -148,7 +148,7 @@
 void DataView::setData(unsigned byteOffset, T value, bool littleEndian, ExceptionState& exceptionState)
 {
     if (beyondRange<T>(byteOffset)) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, "The provided offset (" + String::number(byteOffset) + ") is outside the allowed range.");
         return;
     }
 
diff --git a/Source/core/html/canvas/DataView.h b/Source/core/html/canvas/DataView.h
index 4a9728d..d497eae 100644
--- a/Source/core/html/canvas/DataView.h
+++ b/Source/core/html/canvas/DataView.h
@@ -34,14 +34,12 @@
 
 class ExceptionState;
 
-class DataView : public ArrayBufferView, public ScriptWrappable {
+class DataView FINAL : public ArrayBufferView, public ScriptWrappable {
 public:
     static PassRefPtr<DataView> create(unsigned length);
     static PassRefPtr<DataView> create(PassRefPtr<ArrayBuffer>, unsigned byteOffset, unsigned byteLength);
 
-    virtual unsigned length() const { return m_byteLength; }
-    virtual unsigned byteLength() const { return m_byteLength; }
-    virtual PassRefPtr<ArrayBufferView> slice(int, int) const { return 0; }
+    virtual unsigned byteLength() const OVERRIDE { return m_byteLength; }
 
     int8_t getInt8(unsigned byteOffset, ExceptionState&);
     uint8_t getUint8(unsigned byteOffset, ExceptionState&);
@@ -73,13 +71,13 @@
     void setFloat64(unsigned byteOffset, double value, ExceptionState& ec) { setFloat64(byteOffset, value, false, ec); }
     void setFloat64(unsigned byteOffset, double value, bool littleEndian, ExceptionState&);
 
-    virtual ViewType getType() const
+    virtual ViewType type() const OVERRIDE
     {
         return TypeDataView;
     }
 
 protected:
-    virtual void neuter();
+    virtual void neuter() OVERRIDE;
 
 private:
     DataView(PassRefPtr<ArrayBuffer>, unsigned byteOffset, unsigned byteLength);
diff --git a/Source/core/html/canvas/DataView.idl b/Source/core/html/canvas/DataView.idl
index a9b9fac..972a6ff 100644
--- a/Source/core/html/canvas/DataView.idl
+++ b/Source/core/html/canvas/DataView.idl
@@ -27,29 +27,29 @@
     Custom=Wrap,
     CustomConstructor(ArrayBuffer buffer, optional unsigned long byteOffset, optional unsigned long byteLength),
     GlobalContext=Window&WorkerGlobalScope,
+    StrictTypeChecking,
 ] interface DataView : ArrayBufferView {
     // All these methods raise an exception if they would read or write beyond the end of the view.
 
     [RaisesException] byte getInt8(unsigned long byteOffset);
     [RaisesException] octet getUint8(unsigned long byteOffset);
 
-    [StrictTypeChecking, RaisesException] short getInt16(unsigned long byteOffset, optional boolean littleEndian);
-    [StrictTypeChecking, RaisesException] unsigned short getUint16(unsigned long byteOffset, optional boolean littleEndian);
-    [StrictTypeChecking, RaisesException] long getInt32(unsigned long byteOffset, optional boolean littleEndian);
-    [StrictTypeChecking, RaisesException] unsigned long getUint32(unsigned long byteOffset, optional boolean littleEndian);
+    [RaisesException] short getInt16(unsigned long byteOffset, optional boolean littleEndian);
+    [RaisesException] unsigned short getUint16(unsigned long byteOffset, optional boolean littleEndian);
+    [RaisesException] long getInt32(unsigned long byteOffset, optional boolean littleEndian);
+    [RaisesException] unsigned long getUint32(unsigned long byteOffset, optional boolean littleEndian);
 
     // Use custom code to handle NaN case for JSC.
-    [StrictTypeChecking, RaisesException] float getFloat32(unsigned long byteOffset, optional boolean littleEndian);
-    [StrictTypeChecking, RaisesException] double getFloat64(unsigned long byteOffset, optional boolean littleEndian);
+    [RaisesException] float getFloat32(unsigned long byteOffset, optional boolean littleEndian);
+    [RaisesException] double getFloat64(unsigned long byteOffset, optional boolean littleEndian);
 
     [RaisesException] void setInt8(unsigned long byteOffset, byte value);
     [RaisesException] void setUint8(unsigned long byteOffset, octet value);
 
-    [StrictTypeChecking, RaisesException] void setInt16(unsigned long byteOffset, short value, optional boolean littleEndian);
-    [StrictTypeChecking, RaisesException] void setUint16(unsigned long byteOffset, unsigned short value, optional boolean littleEndian);
-    [StrictTypeChecking, RaisesException] void setInt32(unsigned long byteOffset, long value, optional boolean littleEndian);
-    [StrictTypeChecking, RaisesException] void setUint32(unsigned long byteOffset, unsigned long value, optional boolean littleEndian);
-    [StrictTypeChecking, RaisesException] void setFloat32(unsigned long byteOffset, float value, optional boolean littleEndian);
-    [StrictTypeChecking, RaisesException] void setFloat64(unsigned long byteOffset, double value, optional boolean littleEndian);
+    [RaisesException] void setInt16(unsigned long byteOffset, short value, optional boolean littleEndian);
+    [RaisesException] void setUint16(unsigned long byteOffset, unsigned short value, optional boolean littleEndian);
+    [RaisesException] void setInt32(unsigned long byteOffset, long value, optional boolean littleEndian);
+    [RaisesException] void setUint32(unsigned long byteOffset, unsigned long value, optional boolean littleEndian);
+    [RaisesException] void setFloat32(unsigned long byteOffset, float value, optional boolean littleEndian);
+    [RaisesException] void setFloat64(unsigned long byteOffset, double value, optional boolean littleEndian);
 };
-
diff --git a/Source/core/html/canvas/EXTFragDepth.cpp b/Source/core/html/canvas/EXTFragDepth.cpp
index a2484d2..16c7622 100644
--- a/Source/core/html/canvas/EXTFragDepth.cpp
+++ b/Source/core/html/canvas/EXTFragDepth.cpp
@@ -27,15 +27,13 @@
 
 #include "core/html/canvas/EXTFragDepth.h"
 
-#include "platform/graphics/Extensions3D.h"
-
 namespace WebCore {
 
 EXTFragDepth::EXTFragDepth(WebGLRenderingContext* context)
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_EXT_frag_depth");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_EXT_frag_depth");
 }
 
 EXTFragDepth::~EXTFragDepth()
@@ -54,8 +52,7 @@
 
 bool EXTFragDepth::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_EXT_frag_depth");
+    return context->extensionsUtil()->supportsExtension("GL_EXT_frag_depth");
 }
 
 const char* EXTFragDepth::extensionName()
diff --git a/Source/core/html/canvas/EXTFragDepth.h b/Source/core/html/canvas/EXTFragDepth.h
index fc8a9fa..3c0563e 100644
--- a/Source/core/html/canvas/EXTFragDepth.h
+++ b/Source/core/html/canvas/EXTFragDepth.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class EXTFragDepth : public WebGLExtension, public ScriptWrappable {
+class EXTFragDepth FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<EXTFragDepth> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~EXTFragDepth();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     explicit EXTFragDepth(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/EXTTextureFilterAnisotropic.cpp b/Source/core/html/canvas/EXTTextureFilterAnisotropic.cpp
index 231c3c5..cf8775d 100644
--- a/Source/core/html/canvas/EXTTextureFilterAnisotropic.cpp
+++ b/Source/core/html/canvas/EXTTextureFilterAnisotropic.cpp
@@ -26,7 +26,6 @@
 #include "config.h"
 
 #include "core/html/canvas/EXTTextureFilterAnisotropic.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -34,7 +33,7 @@
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_EXT_texture_filter_anisotropic");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_EXT_texture_filter_anisotropic");
 }
 
 EXTTextureFilterAnisotropic::~EXTTextureFilterAnisotropic()
@@ -53,8 +52,7 @@
 
 bool EXTTextureFilterAnisotropic::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_EXT_texture_filter_anisotropic");
+    return context->extensionsUtil()->supportsExtension("GL_EXT_texture_filter_anisotropic");
 }
 
 const char* EXTTextureFilterAnisotropic::extensionName()
diff --git a/Source/core/html/canvas/EXTTextureFilterAnisotropic.h b/Source/core/html/canvas/EXTTextureFilterAnisotropic.h
index 727f00e..de1e77a 100644
--- a/Source/core/html/canvas/EXTTextureFilterAnisotropic.h
+++ b/Source/core/html/canvas/EXTTextureFilterAnisotropic.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class EXTTextureFilterAnisotropic : public WebGLExtension, public ScriptWrappable {
+class EXTTextureFilterAnisotropic FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<EXTTextureFilterAnisotropic> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~EXTTextureFilterAnisotropic();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     EXTTextureFilterAnisotropic(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/OESElementIndexUint.cpp b/Source/core/html/canvas/OESElementIndexUint.cpp
index a4b0e29..b8b872a 100644
--- a/Source/core/html/canvas/OESElementIndexUint.cpp
+++ b/Source/core/html/canvas/OESElementIndexUint.cpp
@@ -26,7 +26,6 @@
 #include "config.h"
 
 #include "core/html/canvas/OESElementIndexUint.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -34,7 +33,7 @@
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_OES_element_index_uint");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_OES_element_index_uint");
 }
 
 OESElementIndexUint::~OESElementIndexUint()
@@ -53,8 +52,7 @@
 
 bool OESElementIndexUint::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_OES_element_index_uint");
+    return context->extensionsUtil()->supportsExtension("GL_OES_element_index_uint");
 }
 
 const char* OESElementIndexUint::extensionName()
diff --git a/Source/core/html/canvas/OESElementIndexUint.h b/Source/core/html/canvas/OESElementIndexUint.h
index 0116c1d..cd050a4 100644
--- a/Source/core/html/canvas/OESElementIndexUint.h
+++ b/Source/core/html/canvas/OESElementIndexUint.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class OESElementIndexUint : public WebGLExtension, public ScriptWrappable {
+class OESElementIndexUint FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<OESElementIndexUint> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~OESElementIndexUint();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     OESElementIndexUint(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/OESStandardDerivatives.cpp b/Source/core/html/canvas/OESStandardDerivatives.cpp
index aec473b..251396c 100644
--- a/Source/core/html/canvas/OESStandardDerivatives.cpp
+++ b/Source/core/html/canvas/OESStandardDerivatives.cpp
@@ -26,7 +26,6 @@
 #include "config.h"
 
 #include "core/html/canvas/OESStandardDerivatives.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -34,7 +33,7 @@
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_OES_standard_derivatives");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_OES_standard_derivatives");
 }
 
 OESStandardDerivatives::~OESStandardDerivatives()
@@ -53,8 +52,7 @@
 
 bool OESStandardDerivatives::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_OES_standard_derivatives");
+    return context->extensionsUtil()->supportsExtension("GL_OES_standard_derivatives");
 }
 
 const char* OESStandardDerivatives::extensionName()
diff --git a/Source/core/html/canvas/OESStandardDerivatives.h b/Source/core/html/canvas/OESStandardDerivatives.h
index 327a152..e47e9c3 100644
--- a/Source/core/html/canvas/OESStandardDerivatives.h
+++ b/Source/core/html/canvas/OESStandardDerivatives.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class OESStandardDerivatives : public WebGLExtension, public ScriptWrappable {
+class OESStandardDerivatives FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<OESStandardDerivatives> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~OESStandardDerivatives();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     OESStandardDerivatives(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/OESTextureFloat.cpp b/Source/core/html/canvas/OESTextureFloat.cpp
index 99d1387..bc71c70 100644
--- a/Source/core/html/canvas/OESTextureFloat.cpp
+++ b/Source/core/html/canvas/OESTextureFloat.cpp
@@ -26,7 +26,6 @@
 #include "config.h"
 
 #include "core/html/canvas/OESTextureFloat.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -34,7 +33,11 @@
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_OES_texture_float");
+    if (context->extensionsUtil()->ensureExtensionEnabled("GL_OES_texture_float")) {
+        // Implicitly enable rendering to float textures
+        context->extensionsUtil()->ensureExtensionEnabled("GL_CHROMIUM_color_buffer_float_rgba");
+        context->extensionsUtil()->ensureExtensionEnabled("GL_CHROMIUM_color_buffer_float_rgb");
+    }
 }
 
 OESTextureFloat::~OESTextureFloat()
@@ -53,8 +56,7 @@
 
 bool OESTextureFloat::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_OES_texture_float");
+    return context->extensionsUtil()->supportsExtension("GL_OES_texture_float");
 }
 
 const char* OESTextureFloat::extensionName()
diff --git a/Source/core/html/canvas/OESTextureFloat.h b/Source/core/html/canvas/OESTextureFloat.h
index 255c674..29b7fcc 100644
--- a/Source/core/html/canvas/OESTextureFloat.h
+++ b/Source/core/html/canvas/OESTextureFloat.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class OESTextureFloat : public WebGLExtension, public ScriptWrappable {
+class OESTextureFloat FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<OESTextureFloat> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~OESTextureFloat();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     OESTextureFloat(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/OESTextureFloatLinear.cpp b/Source/core/html/canvas/OESTextureFloatLinear.cpp
index 1e8518d..29bd839 100644
--- a/Source/core/html/canvas/OESTextureFloatLinear.cpp
+++ b/Source/core/html/canvas/OESTextureFloatLinear.cpp
@@ -27,15 +27,13 @@
 
 #include "core/html/canvas/OESTextureFloatLinear.h"
 
-#include "platform/graphics/Extensions3D.h"
-
 namespace WebCore {
 
 OESTextureFloatLinear::OESTextureFloatLinear(WebGLRenderingContext* context)
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_OES_texture_float_linear");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_OES_texture_float_linear");
 }
 
 OESTextureFloatLinear::~OESTextureFloatLinear()
@@ -54,8 +52,7 @@
 
 bool OESTextureFloatLinear::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_OES_texture_float_linear");
+    return context->extensionsUtil()->supportsExtension("GL_OES_texture_float_linear");
 }
 
 const char* OESTextureFloatLinear::extensionName()
diff --git a/Source/core/html/canvas/OESTextureFloatLinear.h b/Source/core/html/canvas/OESTextureFloatLinear.h
index 4d7f8d1..0219b09 100644
--- a/Source/core/html/canvas/OESTextureFloatLinear.h
+++ b/Source/core/html/canvas/OESTextureFloatLinear.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class OESTextureFloatLinear : public WebGLExtension, public ScriptWrappable {
+class OESTextureFloatLinear FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<OESTextureFloatLinear> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~OESTextureFloatLinear();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     OESTextureFloatLinear(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/OESTextureHalfFloat.cpp b/Source/core/html/canvas/OESTextureHalfFloat.cpp
index 7253837..6d792b6 100644
--- a/Source/core/html/canvas/OESTextureHalfFloat.cpp
+++ b/Source/core/html/canvas/OESTextureHalfFloat.cpp
@@ -26,7 +26,6 @@
 #include "config.h"
 
 #include "core/html/canvas/OESTextureHalfFloat.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -34,7 +33,7 @@
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_OES_texture_half_float");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_OES_texture_half_float");
 }
 
 OESTextureHalfFloat::~OESTextureHalfFloat()
@@ -53,8 +52,7 @@
 
 bool OESTextureHalfFloat::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_OES_texture_half_float");
+    return context->extensionsUtil()->supportsExtension("GL_OES_texture_half_float");
 }
 
 const char* OESTextureHalfFloat::extensionName()
diff --git a/Source/core/html/canvas/OESTextureHalfFloat.h b/Source/core/html/canvas/OESTextureHalfFloat.h
index 953d311..811f47c 100644
--- a/Source/core/html/canvas/OESTextureHalfFloat.h
+++ b/Source/core/html/canvas/OESTextureHalfFloat.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class OESTextureHalfFloat : public WebGLExtension, public ScriptWrappable {
+class OESTextureHalfFloat FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<OESTextureHalfFloat> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~OESTextureHalfFloat();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     OESTextureHalfFloat(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/OESTextureHalfFloatLinear.cpp b/Source/core/html/canvas/OESTextureHalfFloatLinear.cpp
index c7da9bd..7f758d8 100644
--- a/Source/core/html/canvas/OESTextureHalfFloatLinear.cpp
+++ b/Source/core/html/canvas/OESTextureHalfFloatLinear.cpp
@@ -27,15 +27,13 @@
 
 #include "core/html/canvas/OESTextureHalfFloatLinear.h"
 
-#include "platform/graphics/Extensions3D.h"
-
 namespace WebCore {
 
 OESTextureHalfFloatLinear::OESTextureHalfFloatLinear(WebGLRenderingContext* context)
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_OES_texture_half_float_linear");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_OES_texture_half_float_linear");
 }
 
 OESTextureHalfFloatLinear::~OESTextureHalfFloatLinear()
@@ -54,8 +52,7 @@
 
 bool OESTextureHalfFloatLinear::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_OES_texture_half_float_linear");
+    return context->extensionsUtil()->supportsExtension("GL_OES_texture_half_float_linear");
 }
 
 const char* OESTextureHalfFloatLinear::extensionName()
diff --git a/Source/core/html/canvas/OESTextureHalfFloatLinear.h b/Source/core/html/canvas/OESTextureHalfFloatLinear.h
index 1753203..c817d7b 100644
--- a/Source/core/html/canvas/OESTextureHalfFloatLinear.h
+++ b/Source/core/html/canvas/OESTextureHalfFloatLinear.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class OESTextureHalfFloatLinear : public WebGLExtension, public ScriptWrappable {
+class OESTextureHalfFloatLinear FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<OESTextureHalfFloatLinear> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~OESTextureHalfFloatLinear();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     OESTextureHalfFloatLinear(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/OESVertexArrayObject.cpp b/Source/core/html/canvas/OESVertexArrayObject.cpp
index 9f75534..834b07c 100644
--- a/Source/core/html/canvas/OESVertexArrayObject.cpp
+++ b/Source/core/html/canvas/OESVertexArrayObject.cpp
@@ -30,7 +30,6 @@
 #include "bindings/v8/ExceptionState.h"
 #include "core/html/canvas/WebGLRenderingContext.h"
 #include "core/html/canvas/WebGLVertexArrayObjectOES.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -38,7 +37,7 @@
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_OES_vertex_array_object");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_OES_vertex_array_object");
 }
 
 OESVertexArrayObject::~OESVertexArrayObject()
@@ -73,10 +72,10 @@
     if (!arrayObject->isDefaultObject() && arrayObject == m_context->m_boundVertexArrayObject)
         m_context->setBoundVertexArrayObject(0);
 
-    arrayObject->deleteObject(m_context->graphicsContext3D());
+    arrayObject->deleteObject(m_context->webGraphicsContext3D());
 }
 
-GC3Dboolean OESVertexArrayObject::isVertexArrayOES(WebGLVertexArrayObjectOES* arrayObject)
+GLboolean OESVertexArrayObject::isVertexArrayOES(WebGLVertexArrayObjectOES* arrayObject)
 {
     if (!arrayObject || isLost())
         return 0;
@@ -84,8 +83,7 @@
     if (!arrayObject->hasEverBeenBound())
         return 0;
 
-    Extensions3D* extensions = m_context->graphicsContext3D()->extensions();
-    return extensions->isVertexArrayOES(arrayObject->object());
+    return m_context->webGraphicsContext3D()->isVertexArrayOES(arrayObject->object());
 }
 
 void OESVertexArrayObject::bindVertexArrayOES(WebGLVertexArrayObjectOES* arrayObject)
@@ -94,26 +92,24 @@
         return;
 
     if (arrayObject && (arrayObject->isDeleted() || !arrayObject->validate(0, context()))) {
-        m_context->graphicsContext3D()->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION);
+        m_context->webGraphicsContext3D()->synthesizeGLError(GL_INVALID_OPERATION);
         return;
     }
 
-    Extensions3D* extensions = m_context->graphicsContext3D()->extensions();
     if (arrayObject && !arrayObject->isDefaultObject() && arrayObject->object()) {
-        extensions->bindVertexArrayOES(arrayObject->object());
+        m_context->webGraphicsContext3D()->bindVertexArrayOES(arrayObject->object());
 
         arrayObject->setHasEverBeenBound();
         m_context->setBoundVertexArrayObject(arrayObject);
     } else {
-        extensions->bindVertexArrayOES(0);
+        m_context->webGraphicsContext3D()->bindVertexArrayOES(0);
         m_context->setBoundVertexArrayObject(0);
     }
 }
 
 bool OESVertexArrayObject::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_OES_vertex_array_object");
+    return context->extensionsUtil()->supportsExtension("GL_OES_vertex_array_object");
 }
 
 const char* OESVertexArrayObject::extensionName()
diff --git a/Source/core/html/canvas/OESVertexArrayObject.h b/Source/core/html/canvas/OESVertexArrayObject.h
index 2fd0735..d790bc0 100644
--- a/Source/core/html/canvas/OESVertexArrayObject.h
+++ b/Source/core/html/canvas/OESVertexArrayObject.h
@@ -28,7 +28,6 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLExtension.h"
-#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
@@ -36,18 +35,18 @@
 class WebGLRenderingContext;
 class WebGLVertexArrayObjectOES;
 
-class OESVertexArrayObject : public WebGLExtension, public ScriptWrappable {
+class OESVertexArrayObject FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<OESVertexArrayObject> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~OESVertexArrayObject();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
     PassRefPtr<WebGLVertexArrayObjectOES> createVertexArrayOES();
     void deleteVertexArrayOES(WebGLVertexArrayObjectOES*);
-    GC3Dboolean isVertexArrayOES(WebGLVertexArrayObjectOES*);
+    GLboolean isVertexArrayOES(WebGLVertexArrayObjectOES*);
     void bindVertexArrayOES(WebGLVertexArrayObjectOES*);
 
 private:
diff --git a/Source/core/html/canvas/OESVertexArrayObject.idl b/Source/core/html/canvas/OESVertexArrayObject.idl
index aa9a16d..e7cc9f7 100644
--- a/Source/core/html/canvas/OESVertexArrayObject.idl
+++ b/Source/core/html/canvas/OESVertexArrayObject.idl
@@ -24,13 +24,14 @@
  */
 
 [
+    DoNotCheckConstants,
     NoInterfaceObject,
-    DoNotCheckConstants
+    StrictTypeChecking,
 ] interface OESVertexArrayObject {
     const unsigned long VERTEX_ARRAY_BINDING_OES = 0x85B5;
 
-    [StrictTypeChecking] WebGLVertexArrayObjectOES createVertexArrayOES();
-    [StrictTypeChecking] void         deleteVertexArrayOES([Default=Undefined] optional WebGLVertexArrayObjectOES arrayObject);
-    [StrictTypeChecking] boolean      isVertexArrayOES([Default=Undefined] optional WebGLVertexArrayObjectOES arrayObject);
-    [StrictTypeChecking] void         bindVertexArrayOES([Default=Undefined] optional WebGLVertexArrayObjectOES arrayObject);
+    WebGLVertexArrayObjectOES createVertexArrayOES();
+    void deleteVertexArrayOES([Default=Undefined] optional WebGLVertexArrayObjectOES? arrayObject);
+    boolean isVertexArrayOES([Default=Undefined] optional WebGLVertexArrayObjectOES? arrayObject);
+    void bindVertexArrayOES([Default=Undefined] optional WebGLVertexArrayObjectOES? arrayObject);
 };
diff --git a/Source/core/html/canvas/WebGLActiveInfo.h b/Source/core/html/canvas/WebGLActiveInfo.h
index 7571e36..b1c9834 100644
--- a/Source/core/html/canvas/WebGLActiveInfo.h
+++ b/Source/core/html/canvas/WebGLActiveInfo.h
@@ -27,7 +27,7 @@
 #define WebGLActiveInfo_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "platform/graphics/GraphicsContext3D.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
@@ -36,16 +36,16 @@
 
 class WebGLActiveInfo : public RefCounted<WebGLActiveInfo>, public ScriptWrappable {
 public:
-    static PassRefPtr<WebGLActiveInfo> create(const String& name, GC3Denum type, GC3Dint size)
+    static PassRefPtr<WebGLActiveInfo> create(const String& name, GLenum type, GLint size)
     {
         return adoptRef(new WebGLActiveInfo(name, type, size));
     }
     String name() const { return m_name; }
-    GC3Denum type() const { return m_type; }
-    GC3Dint size() const { return m_size; }
+    GLenum type() const { return m_type; }
+    GLint size() const { return m_size; }
 
 private:
-    WebGLActiveInfo(const String& name, GC3Denum type, GC3Dint size)
+    WebGLActiveInfo(const String& name, GLenum type, GLint size)
         : m_name(name)
         , m_type(type)
         , m_size(size)
@@ -56,8 +56,8 @@
         ScriptWrappable::init(this);
     }
     String m_name;
-    GC3Denum m_type;
-    GC3Dint m_size;
+    GLenum m_type;
+    GLint m_size;
 };
 
 }
diff --git a/Source/core/html/canvas/WebGLBuffer.cpp b/Source/core/html/canvas/WebGLBuffer.cpp
index 34fb7bb..b821654 100644
--- a/Source/core/html/canvas/WebGLBuffer.cpp
+++ b/Source/core/html/canvas/WebGLBuffer.cpp
@@ -41,7 +41,7 @@
     , m_target(0)
 {
     ScriptWrappable::init(this);
-    setObject(ctx->graphicsContext3D()->createBuffer());
+    setObject(ctx->webGraphicsContext3D()->createBuffer());
 }
 
 WebGLBuffer::~WebGLBuffer()
@@ -49,17 +49,17 @@
     deleteObject(0);
 }
 
-void WebGLBuffer::deleteObjectImpl(GraphicsContext3D* context3d, Platform3DObject object)
+void WebGLBuffer::deleteObjectImpl(blink::WebGraphicsContext3D* context3d, Platform3DObject object)
 {
       context3d->deleteBuffer(object);
 }
 
-void WebGLBuffer::setTarget(GC3Denum target)
+void WebGLBuffer::setTarget(GLenum target)
 {
     // In WebGL, a buffer is bound to one target in its lifetime
     if (m_target)
         return;
-    if (target == GraphicsContext3D::ARRAY_BUFFER || target == GraphicsContext3D::ELEMENT_ARRAY_BUFFER)
+    if (target == GL_ARRAY_BUFFER || target == GL_ELEMENT_ARRAY_BUFFER)
         m_target = target;
 }
 
diff --git a/Source/core/html/canvas/WebGLBuffer.h b/Source/core/html/canvas/WebGLBuffer.h
index 8483685..56870e3 100644
--- a/Source/core/html/canvas/WebGLBuffer.h
+++ b/Source/core/html/canvas/WebGLBuffer.h
@@ -33,26 +33,26 @@
 
 namespace WebCore {
 
-class WebGLBuffer : public WebGLSharedObject, public ScriptWrappable {
+class WebGLBuffer FINAL : public WebGLSharedObject, public ScriptWrappable {
 public:
     virtual ~WebGLBuffer();
 
     static PassRefPtr<WebGLBuffer> create(WebGLRenderingContext*);
 
-    GC3Denum getTarget() const { return m_target; }
-    void setTarget(GC3Denum);
+    GLenum getTarget() const { return m_target; }
+    void setTarget(GLenum);
 
     bool hasEverBeenBound() const { return object() && m_target; }
 
 protected:
     WebGLBuffer(WebGLRenderingContext*);
 
-    virtual void deleteObjectImpl(GraphicsContext3D*, Platform3DObject);
+    virtual void deleteObjectImpl(blink::WebGraphicsContext3D*, Platform3DObject) OVERRIDE;
 
 private:
-    virtual bool isBuffer() const { return true; }
+    virtual bool isBuffer() const OVERRIDE { return true; }
 
-    GC3Denum m_target;
+    GLenum m_target;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/canvas/WebGLCompressedTextureATC.cpp b/Source/core/html/canvas/WebGLCompressedTextureATC.cpp
index dad7ff4..0049bee 100644
--- a/Source/core/html/canvas/WebGLCompressedTextureATC.cpp
+++ b/Source/core/html/canvas/WebGLCompressedTextureATC.cpp
@@ -27,17 +27,15 @@
 
 #include "core/html/canvas/WebGLCompressedTextureATC.h"
 
-#include "platform/graphics/Extensions3D.h"
-
 namespace WebCore {
 
 WebGLCompressedTextureATC::WebGLCompressedTextureATC(WebGLRenderingContext* context)
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_ATC_RGB_AMD);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_ATC_RGBA_EXPLICIT_ALPHA_AMD);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_ATC_RGBA_INTERPOLATED_ALPHA_AMD);
+    context->addCompressedTextureFormat(GC3D_COMPRESSED_ATC_RGB_AMD);
+    context->addCompressedTextureFormat(GC3D_COMPRESSED_ATC_RGBA_EXPLICIT_ALPHA_AMD);
+    context->addCompressedTextureFormat(GC3D_COMPRESSED_ATC_RGBA_INTERPOLATED_ALPHA_AMD);
 }
 
 WebGLCompressedTextureATC::~WebGLCompressedTextureATC()
@@ -56,8 +54,7 @@
 
 bool WebGLCompressedTextureATC::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_AMD_compressed_ATC_texture");
+    return context->extensionsUtil()->supportsExtension("GL_AMD_compressed_ATC_texture");
 }
 
 const char* WebGLCompressedTextureATC::extensionName()
diff --git a/Source/core/html/canvas/WebGLCompressedTextureATC.h b/Source/core/html/canvas/WebGLCompressedTextureATC.h
index eb49bc4..500b31b 100644
--- a/Source/core/html/canvas/WebGLCompressedTextureATC.h
+++ b/Source/core/html/canvas/WebGLCompressedTextureATC.h
@@ -34,14 +34,14 @@
 
 class WebGLTexture;
 
-class WebGLCompressedTextureATC : public WebGLExtension, public ScriptWrappable {
+class WebGLCompressedTextureATC FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<WebGLCompressedTextureATC> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~WebGLCompressedTextureATC();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     WebGLCompressedTextureATC(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/WebGLCompressedTexturePVRTC.cpp b/Source/core/html/canvas/WebGLCompressedTexturePVRTC.cpp
index 8ae4acd..db35168 100644
--- a/Source/core/html/canvas/WebGLCompressedTexturePVRTC.cpp
+++ b/Source/core/html/canvas/WebGLCompressedTexturePVRTC.cpp
@@ -28,7 +28,6 @@
 #include "core/html/canvas/WebGLCompressedTexturePVRTC.h"
 
 #include "core/html/canvas/WebGLRenderingContext.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -36,10 +35,10 @@
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_RGB_PVRTC_4BPPV1_IMG);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_RGB_PVRTC_2BPPV1_IMG);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_RGBA_PVRTC_4BPPV1_IMG);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_RGBA_PVRTC_2BPPV1_IMG);
+    context->addCompressedTextureFormat(GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG);
+    context->addCompressedTextureFormat(GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG);
+    context->addCompressedTextureFormat(GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG);
+    context->addCompressedTextureFormat(GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG);
 }
 
 WebGLCompressedTexturePVRTC::~WebGLCompressedTexturePVRTC()
@@ -58,8 +57,7 @@
 
 bool WebGLCompressedTexturePVRTC::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_IMG_texture_compression_pvrtc");
+    return context->extensionsUtil()->supportsExtension("GL_IMG_texture_compression_pvrtc");
 }
 
 const char* WebGLCompressedTexturePVRTC::extensionName()
diff --git a/Source/core/html/canvas/WebGLCompressedTexturePVRTC.h b/Source/core/html/canvas/WebGLCompressedTexturePVRTC.h
index dc28e5f..786c821 100644
--- a/Source/core/html/canvas/WebGLCompressedTexturePVRTC.h
+++ b/Source/core/html/canvas/WebGLCompressedTexturePVRTC.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class WebGLCompressedTexturePVRTC : public WebGLExtension, public ScriptWrappable {
+class WebGLCompressedTexturePVRTC FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<WebGLCompressedTexturePVRTC> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~WebGLCompressedTexturePVRTC();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     WebGLCompressedTexturePVRTC(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp b/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp
index 9d3f254..6db69fb 100644
--- a/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp
+++ b/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp
@@ -28,7 +28,6 @@
 #include "core/html/canvas/WebGLCompressedTextureS3TC.h"
 
 #include "core/html/canvas/WebGLRenderingContext.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -36,10 +35,10 @@
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_RGB_S3TC_DXT1_EXT);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_RGBA_S3TC_DXT1_EXT);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_RGBA_S3TC_DXT3_EXT);
-    context->addCompressedTextureFormat(Extensions3D::COMPRESSED_RGBA_S3TC_DXT5_EXT);
+    context->addCompressedTextureFormat(GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
+    context->addCompressedTextureFormat(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT);
+    context->addCompressedTextureFormat(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT);
+    context->addCompressedTextureFormat(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT);
 }
 
 WebGLCompressedTextureS3TC::~WebGLCompressedTextureS3TC()
@@ -58,11 +57,11 @@
 
 bool WebGLCompressedTextureS3TC::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_EXT_texture_compression_s3tc")
-        || (extensions->supports("GL_EXT_texture_compression_dxt1")
-            && extensions->supports("GL_CHROMIUM_texture_compression_dxt3")
-            && extensions->supports("GL_CHROMIUM_texture_compression_dxt5"));
+    Extensions3DUtil* extensionsUtil = context->extensionsUtil();
+    return extensionsUtil->supportsExtension("GL_EXT_texture_compression_s3tc")
+        || (extensionsUtil->supportsExtension("GL_EXT_texture_compression_dxt1")
+            && extensionsUtil->supportsExtension("GL_CHROMIUM_texture_compression_dxt3")
+            && extensionsUtil->supportsExtension("GL_CHROMIUM_texture_compression_dxt5"));
 }
 
 const char* WebGLCompressedTextureS3TC::extensionName()
diff --git a/Source/core/html/canvas/WebGLCompressedTextureS3TC.h b/Source/core/html/canvas/WebGLCompressedTextureS3TC.h
index 615f4f5..b43b565 100644
--- a/Source/core/html/canvas/WebGLCompressedTextureS3TC.h
+++ b/Source/core/html/canvas/WebGLCompressedTextureS3TC.h
@@ -34,14 +34,14 @@
 
 class WebGLTexture;
 
-class WebGLCompressedTextureS3TC : public WebGLExtension, public ScriptWrappable {
+class WebGLCompressedTextureS3TC FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<WebGLCompressedTextureS3TC> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~WebGLCompressedTextureS3TC();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     WebGLCompressedTextureS3TC(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/WebGLContextAttributes.cpp b/Source/core/html/canvas/WebGLContextAttributes.cpp
index cb26556..4d63bb6 100644
--- a/Source/core/html/canvas/WebGLContextAttributes.cpp
+++ b/Source/core/html/canvas/WebGLContextAttributes.cpp
@@ -28,6 +28,8 @@
 
 #include "core/html/canvas/WebGLContextAttributes.h"
 
+#include "core/frame/Settings.h"
+
 namespace WebCore {
 
 PassRefPtr<WebGLContextAttributes> WebGLContextAttributes::create()
@@ -35,20 +37,28 @@
     return adoptRef(new WebGLContextAttributes());
 }
 
-PassRefPtr<WebGLContextAttributes> WebGLContextAttributes::create(GraphicsContext3D::Attributes attributes)
-{
-    return adoptRef(new WebGLContextAttributes(attributes));
-}
-
 WebGLContextAttributes::WebGLContextAttributes()
     : CanvasContextAttributes()
+    , m_alpha(true)
+    , m_depth(true)
+    , m_stencil(false)
+    , m_antialias(true)
+    , m_premultipliedAlpha(true)
+    , m_preserveDrawingBuffer(false)
+    , m_failIfMajorPerformanceCaveat(false)
 {
     ScriptWrappable::init(this);
 }
 
-WebGLContextAttributes::WebGLContextAttributes(GraphicsContext3D::Attributes attributes)
+WebGLContextAttributes::WebGLContextAttributes(const WebGLContextAttributes& attrs)
     : CanvasContextAttributes()
-    , m_attrs(attributes)
+    , m_alpha(attrs.m_alpha)
+    , m_depth(attrs.m_depth)
+    , m_stencil(attrs.m_stencil)
+    , m_antialias(attrs.m_antialias)
+    , m_premultipliedAlpha(attrs.m_premultipliedAlpha)
+    , m_preserveDrawingBuffer(attrs.m_preserveDrawingBuffer)
+    , m_failIfMajorPerformanceCaveat(attrs.m_failIfMajorPerformanceCaveat)
 {
     ScriptWrappable::init(this);
 }
@@ -57,79 +67,104 @@
 {
 }
 
+PassRefPtr<WebGLContextAttributes> WebGLContextAttributes::clone() const
+{
+    return adoptRef(new WebGLContextAttributes(*this));
+}
+
 bool WebGLContextAttributes::alpha() const
 {
-    return m_attrs.alpha;
+    return m_alpha;
 }
 
 void WebGLContextAttributes::setAlpha(bool alpha)
 {
-    m_attrs.alpha = alpha;
+    m_alpha = alpha;
 }
 
 bool WebGLContextAttributes::depth() const
 {
-    return m_attrs.depth;
+    return m_depth;
 }
 
 void WebGLContextAttributes::setDepth(bool depth)
 {
-    m_attrs.depth = depth;
+    m_depth = depth;
 }
 
 bool WebGLContextAttributes::stencil() const
 {
-    return m_attrs.stencil;
+    return m_stencil;
 }
 
 void WebGLContextAttributes::setStencil(bool stencil)
 {
-    m_attrs.stencil = stencil;
+    m_stencil = stencil;
 }
 
 bool WebGLContextAttributes::antialias() const
 {
-    return m_attrs.antialias;
+    return m_antialias;
 }
 
 void WebGLContextAttributes::setAntialias(bool antialias)
 {
-    m_attrs.antialias = antialias;
+    m_antialias = antialias;
 }
 
 bool WebGLContextAttributes::premultipliedAlpha() const
 {
-    return m_attrs.premultipliedAlpha;
+    return m_premultipliedAlpha;
 }
 
 void WebGLContextAttributes::setPremultipliedAlpha(bool premultipliedAlpha)
 {
-    m_attrs.premultipliedAlpha = premultipliedAlpha;
+    m_premultipliedAlpha = premultipliedAlpha;
 }
 
 bool WebGLContextAttributes::preserveDrawingBuffer() const
 {
-    return m_attrs.preserveDrawingBuffer;
+    return m_preserveDrawingBuffer;
 }
 
 void WebGLContextAttributes::setPreserveDrawingBuffer(bool preserveDrawingBuffer)
 {
-    m_attrs.preserveDrawingBuffer = preserveDrawingBuffer;
+    m_preserveDrawingBuffer = preserveDrawingBuffer;
 }
 
 bool WebGLContextAttributes::failIfMajorPerformanceCaveat() const
 {
-    return m_attrs.failIfMajorPerformanceCaveat;
+    return m_failIfMajorPerformanceCaveat;
 }
 
 void WebGLContextAttributes::setFailIfMajorPerformanceCaveat(bool failIfMajorPerformanceCaveat)
 {
-    m_attrs.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat;
+    m_failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat;
 }
 
-GraphicsContext3D::Attributes WebGLContextAttributes::attributes() const
+blink::WebGraphicsContext3D::Attributes WebGLContextAttributes::attributes(
+    const blink::WebString& topDocumentURL, Settings* settings) const
 {
-    return m_attrs;
+    blink::WebGraphicsContext3D::Attributes attrs;
+
+    attrs.alpha = m_alpha;
+    attrs.depth = m_depth;
+    attrs.stencil = m_stencil;
+    attrs.antialias = m_antialias;
+    if (m_antialias) {
+        if (settings && !settings->openGLMultisamplingEnabled())
+            attrs.antialias = false;
+    }
+    attrs.premultipliedAlpha = m_premultipliedAlpha;
+    attrs.failIfMajorPerformanceCaveat = m_failIfMajorPerformanceCaveat;
+
+    attrs.noExtensions = true;
+    attrs.shareResources = true;
+    attrs.preferDiscreteGPU = true;
+
+    attrs.topDocumentURL = topDocumentURL;
+
+    return attrs;
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/canvas/WebGLContextAttributes.h b/Source/core/html/canvas/WebGLContextAttributes.h
index 62a576e..eeee443 100644
--- a/Source/core/html/canvas/WebGLContextAttributes.h
+++ b/Source/core/html/canvas/WebGLContextAttributes.h
@@ -29,42 +29,44 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/CanvasContextAttributes.h"
-#include "platform/graphics/GraphicsContext3D.h"
+#include "public/platform/WebGraphicsContext3D.h"
 #include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
-class WebGLContextAttributes : public CanvasContextAttributes, public ScriptWrappable {
+class Settings;
+
+class WebGLContextAttributes FINAL : public CanvasContextAttributes, public ScriptWrappable {
 public:
     virtual ~WebGLContextAttributes();
 
     // Create a new attributes object
     static PassRefPtr<WebGLContextAttributes> create();
 
-    // Create a new attributes object initialized with preexisting attributes
-    static PassRefPtr<WebGLContextAttributes> create(GraphicsContext3D::Attributes attributes);
+    // Create a copy of this object.
+    PassRefPtr<WebGLContextAttributes> clone() const;
 
     // Whether or not the drawing buffer has an alpha channel; default=true
     bool alpha() const;
-    void setAlpha(bool alpha);
+    void setAlpha(bool);
 
     // Whether or not the drawing buffer has a depth buffer; default=true
     bool depth() const;
-    void setDepth(bool depth);
+    void setDepth(bool);
 
-    // Whether or not the drawing buffer has a stencil buffer; default=true
+    // Whether or not the drawing buffer has a stencil buffer; default=false
     bool stencil() const;
-    void setStencil(bool stencil);
+    void setStencil(bool);
 
     // Whether or not the drawing buffer is antialiased; default=true
     bool antialias() const;
-    void setAntialias(bool antialias);
+    void setAntialias(bool);
 
     // Whether or not to treat the values in the drawing buffer as
     // though their alpha channel has already been multiplied into the
     // color channels; default=true
     bool premultipliedAlpha() const;
-    void setPremultipliedAlpha(bool premultipliedAlpha);
+    void setPremultipliedAlpha(bool);
 
     // Whether or not to preserve the drawing buffer after presentation to the
     // screen; default=false
@@ -76,16 +78,23 @@
     bool failIfMajorPerformanceCaveat() const;
     void setFailIfMajorPerformanceCaveat(bool);
 
-    // Fetches a copy of the attributes stored in this object in a
-    // form that can be used to initialize a GraphicsContext3D.
-    GraphicsContext3D::Attributes attributes() const;
+    // Set up the attributes that can be used to initialize a WebGraphicsContext3D.
+    // It's mostly based on WebGLContextAttributes, but would be adjusted based
+    // on settings.
+    blink::WebGraphicsContext3D::Attributes attributes(const blink::WebString&, Settings*) const;
 
 protected:
     WebGLContextAttributes();
-    WebGLContextAttributes(GraphicsContext3D::Attributes attributes);
+    WebGLContextAttributes(const WebGLContextAttributes&);
 
 private:
-    GraphicsContext3D::Attributes m_attrs;
+    bool m_alpha;
+    bool m_depth;
+    bool m_stencil;
+    bool m_antialias;
+    bool m_premultipliedAlpha;
+    bool m_preserveDrawingBuffer;
+    bool m_failIfMajorPerformanceCaveat;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/canvas/WebGLContextEvent.h b/Source/core/html/canvas/WebGLContextEvent.h
index 18f4a48..acba861 100644
--- a/Source/core/html/canvas/WebGLContextEvent.h
+++ b/Source/core/html/canvas/WebGLContextEvent.h
@@ -36,7 +36,7 @@
     String statusMessage;
 };
 
-class WebGLContextEvent : public Event {
+class WebGLContextEvent FINAL : public Event {
 public:
     static PassRefPtr<WebGLContextEvent> create()
     {
@@ -54,7 +54,7 @@
 
     const String& statusMessage() const { return m_statusMessage; }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     WebGLContextEvent();
diff --git a/Source/core/html/canvas/WebGLContextGroup.cpp b/Source/core/html/canvas/WebGLContextGroup.cpp
index 93ff6f4..d82ec98 100644
--- a/Source/core/html/canvas/WebGLContextGroup.cpp
+++ b/Source/core/html/canvas/WebGLContextGroup.cpp
@@ -46,11 +46,11 @@
     detachAndRemoveAllObjects();
 }
 
-GraphicsContext3D* WebGLContextGroup::getAGraphicsContext3D()
+blink::WebGraphicsContext3D* WebGLContextGroup::getAWebGraphicsContext3D()
 {
     ASSERT(!m_contexts.isEmpty());
     HashSet<WebGLRenderingContext*>::iterator it = m_contexts.begin();
-    return (*it)->graphicsContext3D();
+    return (*it)->webGraphicsContext3D();
 }
 
 void WebGLContextGroup::addContext(WebGLRenderingContext* context)
diff --git a/Source/core/html/canvas/WebGLContextGroup.h b/Source/core/html/canvas/WebGLContextGroup.h
index b1fece9..9358690 100644
--- a/Source/core/html/canvas/WebGLContextGroup.h
+++ b/Source/core/html/canvas/WebGLContextGroup.h
@@ -31,9 +31,12 @@
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 
+namespace blink {
+class WebGraphicsContext3D;
+}
+
 namespace WebCore {
 
-class GraphicsContext3D;
 class WebGLExtension;
 class WebGLSharedObject;
 class WebGLRenderingContext;
@@ -51,7 +54,7 @@
     void addObject(WebGLSharedObject*);
     void removeObject(WebGLSharedObject*);
 
-    GraphicsContext3D* getAGraphicsContext3D();
+    blink::WebGraphicsContext3D* getAWebGraphicsContext3D();
 
     void loseContextGroup(WebGLRenderingContext::LostContextMode);
 
diff --git a/Source/core/html/canvas/WebGLContextObject.cpp b/Source/core/html/canvas/WebGLContextObject.cpp
index ea718c5..0b1c980 100644
--- a/Source/core/html/canvas/WebGLContextObject.cpp
+++ b/Source/core/html/canvas/WebGLContextObject.cpp
@@ -47,15 +47,15 @@
 {
     detach();
     if (m_context) {
-        deleteObject(m_context->graphicsContext3D());
+        deleteObject(m_context->webGraphicsContext3D());
         m_context->removeContextObject(this);
         m_context = 0;
     }
 }
 
-GraphicsContext3D* WebGLContextObject::getAGraphicsContext3D() const
+blink::WebGraphicsContext3D* WebGLContextObject::getAWebGraphicsContext3D() const
 {
-    return m_context ? m_context->graphicsContext3D() : 0;
+    return m_context ? m_context->webGraphicsContext3D() : 0;
 }
 
 }
diff --git a/Source/core/html/canvas/WebGLContextObject.h b/Source/core/html/canvas/WebGLContextObject.h
index 1e4d296..99e56a4 100644
--- a/Source/core/html/canvas/WebGLContextObject.h
+++ b/Source/core/html/canvas/WebGLContextObject.h
@@ -28,9 +28,12 @@
 
 #include "core/html/canvas/WebGLObject.h"
 
+namespace blink {
+class WebGraphicsContext3D;
+}
+
 namespace WebCore {
 
-class GraphicsContext3D;
 class WebGLRenderingContext;
 
 // WebGLContextObject the base class for objects that are owned by a specific
@@ -41,7 +44,7 @@
 
     WebGLRenderingContext* context() const { return m_context; }
 
-    virtual bool validate(const WebGLContextGroup*, const WebGLRenderingContext* context) const
+    virtual bool validate(const WebGLContextGroup*, const WebGLRenderingContext* context) const OVERRIDE FINAL
     {
         return context == m_context;
     }
@@ -51,12 +54,12 @@
 protected:
     WebGLContextObject(WebGLRenderingContext*);
 
-    virtual bool hasGroupOrContext() const
+    virtual bool hasGroupOrContext() const OVERRIDE FINAL
     {
         return m_context;
     }
 
-    virtual GraphicsContext3D* getAGraphicsContext3D() const;
+    virtual blink::WebGraphicsContext3D* getAWebGraphicsContext3D() const OVERRIDE FINAL;
 
 private:
     WebGLRenderingContext* m_context;
diff --git a/Source/core/html/canvas/WebGLDebugRendererInfo.h b/Source/core/html/canvas/WebGLDebugRendererInfo.h
index 2baa7ab..221edb4 100644
--- a/Source/core/html/canvas/WebGLDebugRendererInfo.h
+++ b/Source/core/html/canvas/WebGLDebugRendererInfo.h
@@ -32,7 +32,7 @@
 
 namespace WebCore {
 
-class WebGLDebugRendererInfo : public WebGLExtension, public ScriptWrappable {
+class WebGLDebugRendererInfo FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     enum EnumType {
         UNMASKED_VENDOR_WEBGL = 0x9245,
@@ -44,7 +44,7 @@
     static const char* extensionName();
 
     virtual ~WebGLDebugRendererInfo();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     WebGLDebugRendererInfo(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/WebGLDebugShaders.cpp b/Source/core/html/canvas/WebGLDebugShaders.cpp
index 8ecb093..20669e8 100644
--- a/Source/core/html/canvas/WebGLDebugShaders.cpp
+++ b/Source/core/html/canvas/WebGLDebugShaders.cpp
@@ -29,7 +29,6 @@
 #include "bindings/v8/ExceptionState.h"
 #include "core/html/canvas/WebGLRenderingContext.h"
 #include "core/html/canvas/WebGLShader.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -59,13 +58,12 @@
         return String();
     if (!m_context->validateWebGLObject("getTranslatedShaderSource", shader))
         return "";
-    return m_context->graphicsContext3D()->extensions()->getTranslatedShaderSourceANGLE(shader->object());
+    return m_context->webGraphicsContext3D()->getTranslatedShaderSourceANGLE(shader->object());
 }
 
 bool WebGLDebugShaders::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return extensions->supports("GL_ANGLE_translated_shader_source");
+    return context->extensionsUtil()->supportsExtension("GL_ANGLE_translated_shader_source");
 }
 
 const char* WebGLDebugShaders::extensionName()
diff --git a/Source/core/html/canvas/WebGLDebugShaders.h b/Source/core/html/canvas/WebGLDebugShaders.h
index 1adbd30..2631050 100644
--- a/Source/core/html/canvas/WebGLDebugShaders.h
+++ b/Source/core/html/canvas/WebGLDebugShaders.h
@@ -34,14 +34,14 @@
 
 class WebGLShader;
 
-class WebGLDebugShaders : public WebGLExtension, public ScriptWrappable {
+class WebGLDebugShaders FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<WebGLDebugShaders> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~WebGLDebugShaders();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
     String getTranslatedShaderSource(WebGLShader*);
 
diff --git a/Source/core/html/canvas/WebGLDebugShaders.idl b/Source/core/html/canvas/WebGLDebugShaders.idl
index 55a6f3c..4948d0e 100644
--- a/Source/core/html/canvas/WebGLDebugShaders.idl
+++ b/Source/core/html/canvas/WebGLDebugShaders.idl
@@ -24,7 +24,8 @@
  */
 
 [
-    NoInterfaceObject
+    NoInterfaceObject,
+    StrictTypeChecking,
 ] interface WebGLDebugShaders {
-    [StrictTypeChecking, TreatReturnedNullStringAs=Null] DOMString getTranslatedShaderSource(WebGLShader shader);
+    [TreatReturnedNullStringAs=Null] DOMString getTranslatedShaderSource(WebGLShader? shader);
 };
diff --git a/Source/core/html/canvas/WebGLDepthTexture.cpp b/Source/core/html/canvas/WebGLDepthTexture.cpp
index d42019f..f3c5c65 100644
--- a/Source/core/html/canvas/WebGLDepthTexture.cpp
+++ b/Source/core/html/canvas/WebGLDepthTexture.cpp
@@ -27,15 +27,13 @@
 
 #include "core/html/canvas/WebGLDepthTexture.h"
 
-#include "platform/graphics/Extensions3D.h"
-
 namespace WebCore {
 
 WebGLDepthTexture::WebGLDepthTexture(WebGLRenderingContext* context)
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_CHROMIUM_depth_texture");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_CHROMIUM_depth_texture");
 }
 
 WebGLDepthTexture::~WebGLDepthTexture()
@@ -54,15 +52,15 @@
 
 bool WebGLDepthTexture::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
+    Extensions3DUtil* extensionsUtil = context->extensionsUtil();
     // Emulating the UNSIGNED_INT_24_8_WEBGL texture internal format in terms
     // of two separate texture objects is too difficult, so disable depth
     // textures unless a packed depth/stencil format is available.
-    if (!extensions->supports("GL_OES_packed_depth_stencil"))
+    if (!extensionsUtil->supportsExtension("GL_OES_packed_depth_stencil"))
         return false;
-    return extensions->supports("GL_CHROMIUM_depth_texture")
-        || extensions->supports("GL_OES_depth_texture")
-        || extensions->supports("GL_ARB_depth_texture");
+    return extensionsUtil->supportsExtension("GL_CHROMIUM_depth_texture")
+        || extensionsUtil->supportsExtension("GL_OES_depth_texture")
+        || extensionsUtil->supportsExtension("GL_ARB_depth_texture");
 }
 
 const char* WebGLDepthTexture::extensionName()
diff --git a/Source/core/html/canvas/WebGLDepthTexture.h b/Source/core/html/canvas/WebGLDepthTexture.h
index 34b0525..a0d3925 100644
--- a/Source/core/html/canvas/WebGLDepthTexture.h
+++ b/Source/core/html/canvas/WebGLDepthTexture.h
@@ -32,14 +32,14 @@
 
 namespace WebCore {
 
-class WebGLDepthTexture : public WebGLExtension, public ScriptWrappable {
+class WebGLDepthTexture FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<WebGLDepthTexture> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~WebGLDepthTexture();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
 private:
     WebGLDepthTexture(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/WebGLDrawBuffers.cpp b/Source/core/html/canvas/WebGLDrawBuffers.cpp
index a7bad1a..d1aa3a7 100644
--- a/Source/core/html/canvas/WebGLDrawBuffers.cpp
+++ b/Source/core/html/canvas/WebGLDrawBuffers.cpp
@@ -27,15 +27,13 @@
 
 #include "core/html/canvas/WebGLDrawBuffers.h"
 
-#include "platform/graphics/Extensions3D.h"
-
 namespace WebCore {
 
 WebGLDrawBuffers::WebGLDrawBuffers(WebGLRenderingContext* context)
     : WebGLExtension(context)
 {
     ScriptWrappable::init(this);
-    context->graphicsContext3D()->extensions()->ensureEnabled("GL_EXT_draw_buffers");
+    context->extensionsUtil()->ensureExtensionEnabled("GL_EXT_draw_buffers");
 }
 
 WebGLDrawBuffers::~WebGLDrawBuffers()
@@ -55,8 +53,7 @@
 // static
 bool WebGLDrawBuffers::supported(WebGLRenderingContext* context)
 {
-    Extensions3D* extensions = context->graphicsContext3D()->extensions();
-    return (extensions->supports("GL_EXT_draw_buffers")
+    return (context->extensionsUtil()->supportsExtension("GL_EXT_draw_buffers")
         && satisfiesWebGLRequirements(context));
 }
 
@@ -65,33 +62,33 @@
     return "WEBGL_draw_buffers";
 }
 
-void WebGLDrawBuffers::drawBuffersWEBGL(const Vector<GC3Denum>& buffers)
+void WebGLDrawBuffers::drawBuffersWEBGL(const Vector<GLenum>& buffers)
 {
     if (isLost())
         return;
-    GC3Dsizei n = buffers.size();
-    const GC3Denum* bufs = buffers.data();
+    GLsizei n = buffers.size();
+    const GLenum* bufs = buffers.data();
     if (!m_context->m_framebufferBinding) {
         if (n != 1) {
-            m_context->synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "drawBuffersWEBGL", "more than one buffer");
+            m_context->synthesizeGLError(GL_INVALID_VALUE, "drawBuffersWEBGL", "more than one buffer");
             return;
         }
-        if (bufs[0] != GraphicsContext3D::BACK && bufs[0] != GraphicsContext3D::NONE) {
-            m_context->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "drawBuffersWEBGL", "BACK or NONE");
+        if (bufs[0] != GL_BACK && bufs[0] != GL_NONE) {
+            m_context->synthesizeGLError(GL_INVALID_OPERATION, "drawBuffersWEBGL", "BACK or NONE");
             return;
         }
         // Because the backbuffer is simulated on all current WebKit ports, we need to change BACK to COLOR_ATTACHMENT0.
-        GC3Denum value = (bufs[0] == GraphicsContext3D::BACK) ? GraphicsContext3D::COLOR_ATTACHMENT0 : GraphicsContext3D::NONE;
-        m_context->graphicsContext3D()->extensions()->drawBuffersEXT(1, &value);
+        GLenum value = (bufs[0] == GL_BACK) ? GL_COLOR_ATTACHMENT0 : GL_NONE;
+        m_context->webGraphicsContext3D()->drawBuffersEXT(1, &value);
         m_context->setBackDrawBuffer(bufs[0]);
     } else {
         if (n > m_context->maxDrawBuffers()) {
-            m_context->synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "drawBuffersWEBGL", "more than max draw buffers");
+            m_context->synthesizeGLError(GL_INVALID_VALUE, "drawBuffersWEBGL", "more than max draw buffers");
             return;
         }
-        for (GC3Dsizei i = 0; i < n; ++i) {
-            if (bufs[i] != GraphicsContext3D::NONE && bufs[i] != static_cast<GC3Denum>(Extensions3D::COLOR_ATTACHMENT0_EXT + i)) {
-                m_context->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "drawBuffersWEBGL", "COLOR_ATTACHMENTi_EXT or NONE");
+        for (GLsizei i = 0; i < n; ++i) {
+            if (bufs[i] != GL_NONE && bufs[i] != static_cast<GLenum>(GL_COLOR_ATTACHMENT0_EXT + i)) {
+                m_context->synthesizeGLError(GL_INVALID_OPERATION, "drawBuffersWEBGL", "COLOR_ATTACHMENTi_EXT or NONE");
                 return;
             }
         }
@@ -102,68 +99,69 @@
 // static
 bool WebGLDrawBuffers::satisfiesWebGLRequirements(WebGLRenderingContext* webglContext)
 {
-    GraphicsContext3D* context = webglContext->graphicsContext3D();
+    blink::WebGraphicsContext3D* context = webglContext->webGraphicsContext3D();
+    Extensions3DUtil* extensionsUtil = webglContext->extensionsUtil();
 
     // This is called after we make sure GL_EXT_draw_buffers is supported.
-    GC3Dint maxDrawBuffers = 0;
-    GC3Dint maxColorAttachments = 0;
-    context->getIntegerv(Extensions3D::MAX_DRAW_BUFFERS_EXT, &maxDrawBuffers);
-    context->getIntegerv(Extensions3D::MAX_COLOR_ATTACHMENTS_EXT, &maxColorAttachments);
+    GLint maxDrawBuffers = 0;
+    GLint maxColorAttachments = 0;
+    context->getIntegerv(GL_MAX_DRAW_BUFFERS_EXT, &maxDrawBuffers);
+    context->getIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &maxColorAttachments);
     if (maxDrawBuffers < 4 || maxColorAttachments < 4)
         return false;
 
     Platform3DObject fbo = context->createFramebuffer();
-    context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, fbo);
+    context->bindFramebuffer(GL_FRAMEBUFFER, fbo);
 
     const unsigned char* buffer = 0; // Chromium doesn't allow init data for depth/stencil tetxures.
-    bool supportsDepth = (context->extensions()->supports("GL_CHROMIUM_depth_texture")
-        || context->extensions()->supports("GL_OES_depth_texture")
-        || context->extensions()->supports("GL_ARB_depth_texture"));
-    bool supportsDepthStencil = (context->extensions()->supports("GL_EXT_packed_depth_stencil")
-        || context->extensions()->supports("GL_OES_packed_depth_stencil"));
+    bool supportsDepth = (extensionsUtil->supportsExtension("GL_CHROMIUM_depth_texture")
+        || extensionsUtil->supportsExtension("GL_OES_depth_texture")
+        || extensionsUtil->supportsExtension("GL_ARB_depth_texture"));
+    bool supportsDepthStencil = (extensionsUtil->supportsExtension("GL_EXT_packed_depth_stencil")
+        || extensionsUtil->supportsExtension("GL_OES_packed_depth_stencil"));
     Platform3DObject depthStencil = 0;
     if (supportsDepthStencil) {
         depthStencil = context->createTexture();
-        context->bindTexture(GraphicsContext3D::TEXTURE_2D, depthStencil);
-        context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::DEPTH_STENCIL, 1, 1, 0, GraphicsContext3D::DEPTH_STENCIL, GraphicsContext3D::UNSIGNED_INT_24_8, buffer);
+        context->bindTexture(GL_TEXTURE_2D, depthStencil);
+        context->texImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL_OES, 1, 1, 0, GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, buffer);
     }
     Platform3DObject depth = 0;
     if (supportsDepth) {
         depth = context->createTexture();
-        context->bindTexture(GraphicsContext3D::TEXTURE_2D, depth);
-        context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::DEPTH_COMPONENT, 1, 1, 0, GraphicsContext3D::DEPTH_COMPONENT, GraphicsContext3D::UNSIGNED_INT, buffer);
+        context->bindTexture(GL_TEXTURE_2D, depth);
+        context->texImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1, 1, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, buffer);
     }
 
     Vector<Platform3DObject> colors;
     bool ok = true;
-    GC3Dint maxAllowedBuffers = std::min(maxDrawBuffers, maxColorAttachments);
-    for (GC3Dint i = 0; i < maxAllowedBuffers; ++i) {
+    GLint maxAllowedBuffers = std::min(maxDrawBuffers, maxColorAttachments);
+    for (GLint i = 0; i < maxAllowedBuffers; ++i) {
         Platform3DObject color = context->createTexture();
         colors.append(color);
-        context->bindTexture(GraphicsContext3D::TEXTURE_2D, color);
-        context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, 1, 1, 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, buffer);
-        context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0 + i, GraphicsContext3D::TEXTURE_2D, color, 0);
-        if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
+        context->bindTexture(GL_TEXTURE_2D, color);
+        context->texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
+        context->framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, color, 0);
+        if (context->checkFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
             ok = false;
             break;
         }
         if (supportsDepth) {
-            context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depth, 0);
-            if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
+            context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0);
+            if (context->checkFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
                 ok = false;
                 break;
             }
-            context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);
+            context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
         }
         if (supportsDepthStencil) {
-            context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depthStencil, 0);
-            context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depthStencil, 0);
-            if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
+            context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthStencil, 0);
+            context->framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthStencil, 0);
+            if (context->checkFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
                 ok = false;
                 break;
             }
-            context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);
-            context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);
+            context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
+            context->framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
         }
     }
 
diff --git a/Source/core/html/canvas/WebGLDrawBuffers.h b/Source/core/html/canvas/WebGLDrawBuffers.h
index 58e14f1..7b8c044 100644
--- a/Source/core/html/canvas/WebGLDrawBuffers.h
+++ b/Source/core/html/canvas/WebGLDrawBuffers.h
@@ -32,16 +32,16 @@
 
 namespace WebCore {
 
-class WebGLDrawBuffers : public WebGLExtension, public ScriptWrappable {
+class WebGLDrawBuffers FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<WebGLDrawBuffers> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~WebGLDrawBuffers();
-    virtual ExtensionName name() const;
+    virtual ExtensionName name() const OVERRIDE;
 
-    void drawBuffersWEBGL(const Vector<GC3Denum>& buffers);
+    void drawBuffersWEBGL(const Vector<GLenum>& buffers);
 
 private:
     WebGLDrawBuffers(WebGLRenderingContext*);
diff --git a/Source/core/html/canvas/WebGLFramebuffer.cpp b/Source/core/html/canvas/WebGLFramebuffer.cpp
index 73614b5..0522c46 100644
--- a/Source/core/html/canvas/WebGLFramebuffer.cpp
+++ b/Source/core/html/canvas/WebGLFramebuffer.cpp
@@ -29,7 +29,6 @@
 
 #include "core/html/canvas/WebGLRenderingContext.h"
 #include "platform/NotImplemented.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -40,24 +39,22 @@
         return object ? object->object() : 0;
     }
 
-    class WebGLRenderbufferAttachment : public WebGLFramebuffer::WebGLAttachment {
+    class WebGLRenderbufferAttachment FINAL : public WebGLFramebuffer::WebGLAttachment {
     public:
         static PassRefPtr<WebGLFramebuffer::WebGLAttachment> create(WebGLRenderbuffer*);
 
     private:
         WebGLRenderbufferAttachment(WebGLRenderbuffer*);
-        virtual GC3Dsizei width() const;
-        virtual GC3Dsizei height() const;
-        virtual GC3Denum format() const;
-        virtual GC3Denum type() const;
-        virtual WebGLSharedObject* object() const;
-        virtual bool isSharedObject(WebGLSharedObject*) const;
-        virtual bool valid() const;
-        virtual bool initialized() const;
-        virtual void setInitialized();
-        virtual void onDetached(GraphicsContext3D*);
-        virtual void attach(GraphicsContext3D*, GC3Denum attachment);
-        virtual void unattach(GraphicsContext3D*, GC3Denum attachment);
+        virtual GLsizei width() const OVERRIDE;
+        virtual GLsizei height() const OVERRIDE;
+        virtual GLenum format() const OVERRIDE;
+        virtual GLenum type() const OVERRIDE;
+        virtual WebGLSharedObject* object() const OVERRIDE;
+        virtual bool isSharedObject(WebGLSharedObject*) const OVERRIDE;
+        virtual bool valid() const OVERRIDE;
+        virtual void onDetached(blink::WebGraphicsContext3D*) OVERRIDE;
+        virtual void attach(blink::WebGraphicsContext3D*, GLenum attachment) OVERRIDE;
+        virtual void unattach(blink::WebGraphicsContext3D*, GLenum attachment) OVERRIDE;
 
         WebGLRenderbufferAttachment() { };
 
@@ -74,22 +71,22 @@
     {
     }
 
-    GC3Dsizei WebGLRenderbufferAttachment::width() const
+    GLsizei WebGLRenderbufferAttachment::width() const
     {
         return m_renderbuffer->width();
     }
 
-    GC3Dsizei WebGLRenderbufferAttachment::height() const
+    GLsizei WebGLRenderbufferAttachment::height() const
     {
         return m_renderbuffer->height();
     }
 
-    GC3Denum WebGLRenderbufferAttachment::format() const
+    GLenum WebGLRenderbufferAttachment::format() const
     {
-        GC3Denum format = m_renderbuffer->internalFormat();
-        if (format == GraphicsContext3D::DEPTH_STENCIL
+        GLenum format = m_renderbuffer->internalFormat();
+        if (format == GL_DEPTH_STENCIL_OES
             && m_renderbuffer->emulatedStencilBuffer()
-            && m_renderbuffer->emulatedStencilBuffer()->internalFormat() != GraphicsContext3D::STENCIL_INDEX8) {
+            && m_renderbuffer->emulatedStencilBuffer()->internalFormat() != GL_STENCIL_INDEX8) {
             return 0;
         }
         return format;
@@ -110,97 +107,85 @@
         return m_renderbuffer->object();
     }
 
-    bool WebGLRenderbufferAttachment::initialized() const
-    {
-        return m_renderbuffer->object() && m_renderbuffer->initialized();
-    }
-
-    void WebGLRenderbufferAttachment::setInitialized()
-    {
-        if (m_renderbuffer->object())
-            m_renderbuffer->setInitialized();
-    }
-
-    void WebGLRenderbufferAttachment::onDetached(GraphicsContext3D* context)
+    void WebGLRenderbufferAttachment::onDetached(blink::WebGraphicsContext3D* context)
     {
         m_renderbuffer->onDetached(context);
     }
 
-    void WebGLRenderbufferAttachment::attach(GraphicsContext3D* context, GC3Denum attachment)
+    void WebGLRenderbufferAttachment::attach(blink::WebGraphicsContext3D* context, GLenum attachment)
     {
         Platform3DObject object = objectOrZero(m_renderbuffer.get());
-        if (attachment == GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT && m_renderbuffer->emulatedStencilBuffer()) {
-            context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, object);
-            context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, objectOrZero(m_renderbuffer->emulatedStencilBuffer()));
+        if (attachment == GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL && m_renderbuffer->emulatedStencilBuffer()) {
+            context->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, object);
+            context->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, objectOrZero(m_renderbuffer->emulatedStencilBuffer()));
         } else {
-            context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, attachment, GraphicsContext3D::RENDERBUFFER, object);
+            context->framebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, object);
         }
     }
 
-    void WebGLRenderbufferAttachment::unattach(GraphicsContext3D* context, GC3Denum attachment)
+    void WebGLRenderbufferAttachment::unattach(blink::WebGraphicsContext3D* context, GLenum attachment)
     {
-        if (attachment == GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT) {
-            context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, 0);
-            context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, 0);
-        } else
-            context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, attachment, GraphicsContext3D::RENDERBUFFER, 0);
+        if (attachment == GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL) {
+            context->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
+            context->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
+        } else {
+            context->framebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, 0);
+        }
     }
 
-    GC3Denum WebGLRenderbufferAttachment::type() const
+    GLenum WebGLRenderbufferAttachment::type() const
     {
         notImplemented();
         return 0;
     }
 
-    class WebGLTextureAttachment : public WebGLFramebuffer::WebGLAttachment {
+    class WebGLTextureAttachment FINAL : public WebGLFramebuffer::WebGLAttachment {
     public:
-        static PassRefPtr<WebGLFramebuffer::WebGLAttachment> create(WebGLTexture*, GC3Denum target, GC3Dint level);
+        static PassRefPtr<WebGLFramebuffer::WebGLAttachment> create(WebGLTexture*, GLenum target, GLint level);
 
     private:
-        WebGLTextureAttachment(WebGLTexture*, GC3Denum target, GC3Dint level);
-        virtual GC3Dsizei width() const;
-        virtual GC3Dsizei height() const;
-        virtual GC3Denum format() const;
-        virtual GC3Denum type() const;
-        virtual WebGLSharedObject* object() const;
-        virtual bool isSharedObject(WebGLSharedObject*) const;
-        virtual bool valid() const;
-        virtual bool initialized() const;
-        virtual void setInitialized();
-        virtual void onDetached(GraphicsContext3D*);
-        virtual void attach(GraphicsContext3D*, GC3Denum attachment);
-        virtual void unattach(GraphicsContext3D*, GC3Denum attachment);
+        WebGLTextureAttachment(WebGLTexture*, GLenum target, GLint level);
+        virtual GLsizei width() const OVERRIDE;
+        virtual GLsizei height() const OVERRIDE;
+        virtual GLenum format() const OVERRIDE;
+        virtual GLenum type() const OVERRIDE;
+        virtual WebGLSharedObject* object() const OVERRIDE;
+        virtual bool isSharedObject(WebGLSharedObject*) const OVERRIDE;
+        virtual bool valid() const OVERRIDE;
+        virtual void onDetached(blink::WebGraphicsContext3D*) OVERRIDE;
+        virtual void attach(blink::WebGraphicsContext3D*, GLenum attachment) OVERRIDE;
+        virtual void unattach(blink::WebGraphicsContext3D*, GLenum attachment) OVERRIDE;
 
         WebGLTextureAttachment() { };
 
         RefPtr<WebGLTexture> m_texture;
-        GC3Denum m_target;
-        GC3Dint m_level;
+        GLenum m_target;
+        GLint m_level;
     };
 
-    PassRefPtr<WebGLFramebuffer::WebGLAttachment> WebGLTextureAttachment::create(WebGLTexture* texture, GC3Denum target, GC3Dint level)
+    PassRefPtr<WebGLFramebuffer::WebGLAttachment> WebGLTextureAttachment::create(WebGLTexture* texture, GLenum target, GLint level)
     {
         return adoptRef(new WebGLTextureAttachment(texture, target, level));
     }
 
-    WebGLTextureAttachment::WebGLTextureAttachment(WebGLTexture* texture, GC3Denum target, GC3Dint level)
+    WebGLTextureAttachment::WebGLTextureAttachment(WebGLTexture* texture, GLenum target, GLint level)
         : m_texture(texture)
         , m_target(target)
         , m_level(level)
     {
     }
 
-    GC3Dsizei WebGLTextureAttachment::width() const
+    GLsizei WebGLTextureAttachment::width() const
     {
         return m_texture->getWidth(m_target, m_level);
     }
 
-    GC3Dsizei WebGLTextureAttachment::height() const
+    GLsizei WebGLTextureAttachment::height() const
     {
         return m_texture->getHeight(m_target, m_level);
     }
 
-    GC3Denum WebGLTextureAttachment::format() const
+    GLenum WebGLTextureAttachment::format() const
     {
         return m_texture->getInternalFormat(m_target, m_level);
     }
@@ -220,48 +205,38 @@
         return m_texture->object();
     }
 
-    bool WebGLTextureAttachment::initialized() const
-    {
-        // Textures are assumed to be initialized.
-        return true;
-    }
-
-    void WebGLTextureAttachment::setInitialized()
-    {
-        // Textures are assumed to be initialized.
-    }
-
-    void WebGLTextureAttachment::onDetached(GraphicsContext3D* context)
+    void WebGLTextureAttachment::onDetached(blink::WebGraphicsContext3D* context)
     {
         m_texture->onDetached(context);
     }
 
-    void WebGLTextureAttachment::attach(GraphicsContext3D* context, GC3Denum attachment)
+    void WebGLTextureAttachment::attach(blink::WebGraphicsContext3D* context, GLenum attachment)
     {
         Platform3DObject object = objectOrZero(m_texture.get());
-        context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, attachment, m_target, object, m_level);
+        context->framebufferTexture2D(GL_FRAMEBUFFER, attachment, m_target, object, m_level);
     }
 
-    void WebGLTextureAttachment::unattach(GraphicsContext3D* context, GC3Denum attachment)
+    void WebGLTextureAttachment::unattach(blink::WebGraphicsContext3D* context, GLenum attachment)
     {
-        if (attachment == GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT) {
-            context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, m_target, 0, m_level);
-            context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, m_target, 0, m_level);
-        } else
-            context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, attachment, m_target, 0, m_level);
+        if (attachment == GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL) {
+            context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_target, 0, m_level);
+            context->framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, m_target, 0, m_level);
+        } else {
+            context->framebufferTexture2D(GL_FRAMEBUFFER, attachment, m_target, 0, m_level);
+        }
     }
 
-    GC3Denum WebGLTextureAttachment::type() const
+    GLenum WebGLTextureAttachment::type() const
     {
         return m_texture->getType(m_target, m_level);
     }
 
-    bool isColorRenderable(GC3Denum internalformat)
+    bool isColorRenderable(GLenum internalformat)
     {
         switch (internalformat) {
-        case GraphicsContext3D::RGBA4:
-        case GraphicsContext3D::RGB5_A1:
-        case GraphicsContext3D::RGB565:
+        case GL_RGBA4:
+        case GL_RGB5_A1:
+        case GL_RGB565:
             return true;
         default:
             return false;
@@ -288,7 +263,7 @@
     , m_hasEverBeenBound(false)
 {
     ScriptWrappable::init(this);
-    setObject(ctx->graphicsContext3D()->createFramebuffer());
+    setObject(ctx->webGraphicsContext3D()->createFramebuffer());
 }
 
 WebGLFramebuffer::~WebGLFramebuffer()
@@ -296,7 +271,7 @@
     deleteObject(0);
 }
 
-void WebGLFramebuffer::setAttachmentForBoundFramebuffer(GC3Denum attachment, GC3Denum texTarget, WebGLTexture* texture, GC3Dint level)
+void WebGLFramebuffer::setAttachmentForBoundFramebuffer(GLenum attachment, GLenum texTarget, WebGLTexture* texture, GLint level)
 {
     ASSERT(isBound());
     removeAttachmentFromBoundFramebuffer(attachment);
@@ -309,7 +284,7 @@
     }
 }
 
-void WebGLFramebuffer::setAttachmentForBoundFramebuffer(GC3Denum attachment, WebGLRenderbuffer* renderbuffer)
+void WebGLFramebuffer::setAttachmentForBoundFramebuffer(GLenum attachment, WebGLRenderbuffer* renderbuffer)
 {
     ASSERT(isBound());
     removeAttachmentFromBoundFramebuffer(attachment);
@@ -322,15 +297,15 @@
     }
 }
 
-void WebGLFramebuffer::attach(GC3Denum attachment, GC3Denum attachmentPoint)
+void WebGLFramebuffer::attach(GLenum attachment, GLenum attachmentPoint)
 {
     ASSERT(isBound());
     WebGLAttachment* attachmentObject = getAttachment(attachment);
     if (attachmentObject)
-        attachmentObject->attach(context()->graphicsContext3D(), attachmentPoint);
+        attachmentObject->attach(context()->webGraphicsContext3D(), attachmentPoint);
 }
 
-WebGLSharedObject* WebGLFramebuffer::getAttachmentObject(GC3Denum attachment) const
+WebGLSharedObject* WebGLFramebuffer::getAttachmentObject(GLenum attachment) const
 {
     if (!object())
         return 0;
@@ -338,63 +313,63 @@
     return attachmentObject ? attachmentObject->object() : 0;
 }
 
-bool WebGLFramebuffer::isAttachmentComplete(WebGLAttachment* attachedObject, GC3Denum attachment, const char** reason) const
+bool WebGLFramebuffer::isAttachmentComplete(WebGLAttachment* attachedObject, GLenum attachment, const char** reason) const
 {
     ASSERT(attachedObject && attachedObject->valid());
     ASSERT(reason);
 
-    GC3Denum internalformat = attachedObject->format();
+    GLenum internalformat = attachedObject->format();
     WebGLSharedObject* object = attachedObject->object();
     ASSERT(object && (object->isTexture() || object->isRenderbuffer()));
 
-    if (attachment == GraphicsContext3D::DEPTH_ATTACHMENT) {
+    if (attachment == GL_DEPTH_ATTACHMENT) {
         if (object->isRenderbuffer()) {
-            if (internalformat != GraphicsContext3D::DEPTH_COMPONENT16) {
+            if (internalformat != GL_DEPTH_COMPONENT16) {
                 *reason = "the internalformat of the attached renderbuffer is not DEPTH_COMPONENT16";
                 return false;
             }
         } else if (object->isTexture()) {
-            GC3Denum type = attachedObject->type();
-            if (!(context()->m_webglDepthTexture && internalformat == GraphicsContext3D::DEPTH_COMPONENT
-                && (type == GraphicsContext3D::UNSIGNED_SHORT || type == GraphicsContext3D::UNSIGNED_INT))) {
+            GLenum type = attachedObject->type();
+            if (!(context()->m_webglDepthTexture && internalformat == GL_DEPTH_COMPONENT
+                && (type == GL_UNSIGNED_SHORT || type == GL_UNSIGNED_INT))) {
                 *reason = "the attached texture is not a depth texture";
                 return false;
             }
         }
-    } else if (attachment == GraphicsContext3D::STENCIL_ATTACHMENT) {
+    } else if (attachment == GL_STENCIL_ATTACHMENT) {
         // Depend on the underlying GL drivers to check stencil textures
         // and check renderbuffer type here only.
         if (object->isRenderbuffer()) {
-            if (internalformat != GraphicsContext3D::STENCIL_INDEX8) {
+            if (internalformat != GL_STENCIL_INDEX8) {
                 *reason = "the internalformat of the attached renderbuffer is not STENCIL_INDEX8";
                 return false;
             }
         }
-    } else if (attachment == GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT) {
+    } else if (attachment == GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL) {
         if (object->isRenderbuffer()) {
-            if (internalformat != GraphicsContext3D::DEPTH_STENCIL) {
+            if (internalformat != GL_DEPTH_STENCIL_OES) {
                 *reason = "the internalformat of the attached renderbuffer is not DEPTH_STENCIL";
                 return false;
             }
         } else if (object->isTexture()) {
-            GC3Denum type = attachedObject->type();
-            if (!(context()->m_webglDepthTexture && internalformat == GraphicsContext3D::DEPTH_STENCIL
-                && type == GraphicsContext3D::UNSIGNED_INT_24_8)) {
+            GLenum type = attachedObject->type();
+            if (!(context()->m_webglDepthTexture && internalformat == GL_DEPTH_STENCIL_OES
+                && type == GL_UNSIGNED_INT_24_8_OES)) {
                 *reason = "the attached texture is not a DEPTH_STENCIL texture";
                 return false;
             }
         }
-    } else if (attachment == GraphicsContext3D::COLOR_ATTACHMENT0
-        || (context()->m_webglDrawBuffers && attachment > GraphicsContext3D::COLOR_ATTACHMENT0
-            && attachment < static_cast<GC3Denum>(GraphicsContext3D::COLOR_ATTACHMENT0 + context()->maxColorAttachments()))) {
+    } else if (attachment == GL_COLOR_ATTACHMENT0
+        || (context()->m_webglDrawBuffers && attachment > GL_COLOR_ATTACHMENT0
+            && attachment < static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + context()->maxColorAttachments()))) {
         if (object->isRenderbuffer()) {
             if (!isColorRenderable(internalformat)) {
                 *reason = "the internalformat of the attached renderbuffer is not color-renderable";
                 return false;
             }
         } else if (object->isTexture()) {
-            GC3Denum type = attachedObject->type();
-            if (internalformat != GraphicsContext3D::RGBA && internalformat != GraphicsContext3D::RGB) {
+            GLenum type = attachedObject->type();
+            if (internalformat != GL_RGBA && internalformat != GL_RGB) {
                 *reason = "the internalformat of the attached texture is not color-renderable";
                 return false;
             }
@@ -402,12 +377,12 @@
             // WebGL yet. It would be better to depend on the underlying GL drivers to check on rendering to floating point textures
             // and add the check back to WebGL when above two extensions are implemented.
             // Assume UNSIGNED_BYTE is renderable here without the need to explicitly check if GL_OES_rgb8_rgba8 extension is supported.
-            if (type != GraphicsContext3D::UNSIGNED_BYTE
-                && type != GraphicsContext3D::UNSIGNED_SHORT_5_6_5
-                && type != GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4
-                && type != GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1
-                && !(type == GraphicsContext3D::FLOAT && context()->m_oesTextureFloat)
-                && !(type == GraphicsContext3D::HALF_FLOAT_OES && context()->m_oesTextureHalfFloat)) {
+            if (type != GL_UNSIGNED_BYTE
+                && type != GL_UNSIGNED_SHORT_5_6_5
+                && type != GL_UNSIGNED_SHORT_4_4_4_4
+                && type != GL_UNSIGNED_SHORT_5_5_5_1
+                && !(type == GL_FLOAT && context()->m_oesTextureFloat)
+                && !(type == GL_HALF_FLOAT_OES && context()->m_oesTextureHalfFloat)) {
                 *reason = "unsupported type: The attached texture is not supported to be rendered to";
                 return false;
             }
@@ -424,13 +399,13 @@
     return true;
 }
 
-WebGLFramebuffer::WebGLAttachment* WebGLFramebuffer::getAttachment(GC3Denum attachment) const
+WebGLFramebuffer::WebGLAttachment* WebGLFramebuffer::getAttachment(GLenum attachment) const
 {
     const AttachmentMap::const_iterator it = m_attachments.find(attachment);
     return (it != m_attachments.end()) ? it->value.get() : 0;
 }
 
-void WebGLFramebuffer::removeAttachmentFromBoundFramebuffer(GC3Denum attachment)
+void WebGLFramebuffer::removeAttachmentFromBoundFramebuffer(GLenum attachment)
 {
     ASSERT(isBound());
     if (!object())
@@ -438,19 +413,19 @@
 
     WebGLAttachment* attachmentObject = getAttachment(attachment);
     if (attachmentObject) {
-        attachmentObject->onDetached(context()->graphicsContext3D());
+        attachmentObject->onDetached(context()->webGraphicsContext3D());
         m_attachments.remove(attachment);
         drawBuffersIfNecessary(false);
         switch (attachment) {
-        case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
-            attach(GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::DEPTH_ATTACHMENT);
-            attach(GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::STENCIL_ATTACHMENT);
+        case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
+            attach(GL_DEPTH_ATTACHMENT, GL_DEPTH_ATTACHMENT);
+            attach(GL_STENCIL_ATTACHMENT, GL_STENCIL_ATTACHMENT);
             break;
-        case GraphicsContext3D::DEPTH_ATTACHMENT:
-            attach(GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT, GraphicsContext3D::DEPTH_ATTACHMENT);
+        case GL_DEPTH_ATTACHMENT:
+            attach(GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL, GL_DEPTH_ATTACHMENT);
             break;
-        case GraphicsContext3D::STENCIL_ATTACHMENT:
-            attach(GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT, GraphicsContext3D::STENCIL_ATTACHMENT);
+        case GL_STENCIL_ATTACHMENT:
+            attach(GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL, GL_STENCIL_ATTACHMENT);
             break;
         }
     }
@@ -470,8 +445,8 @@
         for (AttachmentMap::iterator it = m_attachments.begin(); it != m_attachments.end(); ++it) {
             WebGLAttachment* attachmentObject = it->value.get();
             if (attachmentObject->isSharedObject(attachment)) {
-                GC3Denum attachmentType = it->key;
-                attachmentObject->unattach(context()->graphicsContext3D(), attachmentType);
+                GLenum attachmentType = it->key;
+                attachmentObject->unattach(context()->webGraphicsContext3D(), attachmentType);
                 removeAttachmentFromBoundFramebuffer(attachmentType);
                 checkMore = true;
                 break;
@@ -480,65 +455,65 @@
     }
 }
 
-GC3Dsizei WebGLFramebuffer::colorBufferWidth() const
+GLsizei WebGLFramebuffer::colorBufferWidth() const
 {
     if (!object())
         return 0;
-    WebGLAttachment* attachment = getAttachment(GraphicsContext3D::COLOR_ATTACHMENT0);
+    WebGLAttachment* attachment = getAttachment(GL_COLOR_ATTACHMENT0);
     if (!attachment)
         return 0;
 
     return attachment->width();
 }
 
-GC3Dsizei WebGLFramebuffer::colorBufferHeight() const
+GLsizei WebGLFramebuffer::colorBufferHeight() const
 {
     if (!object())
         return 0;
-    WebGLAttachment* attachment = getAttachment(GraphicsContext3D::COLOR_ATTACHMENT0);
+    WebGLAttachment* attachment = getAttachment(GL_COLOR_ATTACHMENT0);
     if (!attachment)
         return 0;
 
     return attachment->height();
 }
 
-GC3Denum WebGLFramebuffer::colorBufferFormat() const
+GLenum WebGLFramebuffer::colorBufferFormat() const
 {
     if (!object())
         return 0;
-    WebGLAttachment* attachment = getAttachment(GraphicsContext3D::COLOR_ATTACHMENT0);
+    WebGLAttachment* attachment = getAttachment(GL_COLOR_ATTACHMENT0);
     if (!attachment)
         return 0;
     return attachment->format();
 }
 
-GC3Denum WebGLFramebuffer::checkStatus(const char** reason) const
+GLenum WebGLFramebuffer::checkStatus(const char** reason) const
 {
     unsigned int count = 0;
-    GC3Dsizei width = 0, height = 0;
+    GLsizei width = 0, height = 0;
     bool haveDepth = false;
     bool haveStencil = false;
     bool haveDepthStencil = false;
     for (AttachmentMap::const_iterator it = m_attachments.begin(); it != m_attachments.end(); ++it) {
         WebGLAttachment* attachment = it->value.get();
         if (!isAttachmentComplete(attachment, it->key, reason))
-            return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
+            return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
         if (!attachment->valid()) {
             *reason = "attachment is not valid";
-            return GraphicsContext3D::FRAMEBUFFER_UNSUPPORTED;
+            return GL_FRAMEBUFFER_UNSUPPORTED;
         }
         if (!attachment->format()) {
             *reason = "attachment is an unsupported format";
-            return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
+            return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
         }
         switch (it->key) {
-        case GraphicsContext3D::DEPTH_ATTACHMENT:
+        case GL_DEPTH_ATTACHMENT:
             haveDepth = true;
             break;
-        case GraphicsContext3D::STENCIL_ATTACHMENT:
+        case GL_STENCIL_ATTACHMENT:
             haveStencil = true;
             break;
-        case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
+        case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
             haveDepthStencil = true;
             break;
         }
@@ -548,43 +523,43 @@
         } else {
             if (width != attachment->width() || height != attachment->height()) {
                 *reason = "attachments do not have the same dimensions";
-                return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
+                return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
             }
         }
         ++count;
     }
     if (!count) {
         *reason = "no attachments";
-        return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
+        return GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
     }
     if (!width || !height) {
         *reason = "framebuffer has a 0 dimension";
-        return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
+        return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
     }
     // WebGL specific: no conflicting DEPTH/STENCIL/DEPTH_STENCIL attachments.
     if ((haveDepthStencil && (haveDepth || haveStencil)) || (haveDepth && haveStencil)) {
         *reason = "conflicting DEPTH/STENCIL/DEPTH_STENCIL attachments";
-        return GraphicsContext3D::FRAMEBUFFER_UNSUPPORTED;
+        return GL_FRAMEBUFFER_UNSUPPORTED;
     }
-    return GraphicsContext3D::FRAMEBUFFER_COMPLETE;
+    return GL_FRAMEBUFFER_COMPLETE;
 }
 
-bool WebGLFramebuffer::onAccess(GraphicsContext3D* context3d, const char** reason)
+bool WebGLFramebuffer::onAccess(blink::WebGraphicsContext3D* context3d, const char** reason)
 {
-    if (checkStatus(reason) != GraphicsContext3D::FRAMEBUFFER_COMPLETE)
+    if (checkStatus(reason) != GL_FRAMEBUFFER_COMPLETE)
         return false;
     return true;
 }
 
 bool WebGLFramebuffer::hasStencilBuffer() const
 {
-    WebGLAttachment* attachment = getAttachment(GraphicsContext3D::STENCIL_ATTACHMENT);
+    WebGLAttachment* attachment = getAttachment(GL_STENCIL_ATTACHMENT);
     if (!attachment)
-        attachment = getAttachment(GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT);
+        attachment = getAttachment(GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL);
     return attachment && attachment->valid();
 }
 
-void WebGLFramebuffer::deleteObjectImpl(GraphicsContext3D* context3d, Platform3DObject object)
+void WebGLFramebuffer::deleteObjectImpl(blink::WebGraphicsContext3D* context3d, Platform3DObject object)
 {
     for (AttachmentMap::iterator it = m_attachments.begin(); it != m_attachments.end(); ++it)
         it->value->onDetached(context3d);
@@ -597,12 +572,12 @@
     return (context()->m_framebufferBinding.get() == this);
 }
 
-void WebGLFramebuffer::drawBuffers(const Vector<GC3Denum>& bufs)
+void WebGLFramebuffer::drawBuffers(const Vector<GLenum>& bufs)
 {
     m_drawBuffers = bufs;
     m_filteredDrawBuffers.resize(m_drawBuffers.size());
     for (size_t i = 0; i < m_filteredDrawBuffers.size(); ++i)
-        m_filteredDrawBuffers[i] = GraphicsContext3D::NONE;
+        m_filteredDrawBuffers[i] = GL_NONE;
     drawBuffersIfNecessary(true);
 }
 
@@ -613,33 +588,33 @@
     bool reset = force;
     // This filtering works around graphics driver bugs on Mac OS X.
     for (size_t i = 0; i < m_drawBuffers.size(); ++i) {
-        if (m_drawBuffers[i] != GraphicsContext3D::NONE && getAttachment(m_drawBuffers[i])) {
+        if (m_drawBuffers[i] != GL_NONE && getAttachment(m_drawBuffers[i])) {
             if (m_filteredDrawBuffers[i] != m_drawBuffers[i]) {
                 m_filteredDrawBuffers[i] = m_drawBuffers[i];
                 reset = true;
             }
         } else {
-            if (m_filteredDrawBuffers[i] != GraphicsContext3D::NONE) {
-                m_filteredDrawBuffers[i] = GraphicsContext3D::NONE;
+            if (m_filteredDrawBuffers[i] != GL_NONE) {
+                m_filteredDrawBuffers[i] = GL_NONE;
                 reset = true;
             }
         }
     }
     if (reset) {
-        context()->graphicsContext3D()->extensions()->drawBuffersEXT(
+        context()->webGraphicsContext3D()->drawBuffersEXT(
             m_filteredDrawBuffers.size(), m_filteredDrawBuffers.data());
     }
 }
 
-GC3Denum WebGLFramebuffer::getDrawBuffer(GC3Denum drawBuffer)
+GLenum WebGLFramebuffer::getDrawBuffer(GLenum drawBuffer)
 {
-    int index = static_cast<int>(drawBuffer - Extensions3D::DRAW_BUFFER0_EXT);
+    int index = static_cast<int>(drawBuffer - GL_DRAW_BUFFER0_EXT);
     ASSERT(index >= 0);
     if (index < static_cast<int>(m_drawBuffers.size()))
         return m_drawBuffers[index];
-    if (drawBuffer == Extensions3D::DRAW_BUFFER0_EXT)
-        return GraphicsContext3D::COLOR_ATTACHMENT0;
-    return GraphicsContext3D::NONE;
+    if (drawBuffer == GL_DRAW_BUFFER0_EXT)
+        return GL_COLOR_ATTACHMENT0;
+    return GL_NONE;
 }
 
 }
diff --git a/Source/core/html/canvas/WebGLFramebuffer.h b/Source/core/html/canvas/WebGLFramebuffer.h
index 86e2aeb..2e3e0f7 100644
--- a/Source/core/html/canvas/WebGLFramebuffer.h
+++ b/Source/core/html/canvas/WebGLFramebuffer.h
@@ -37,28 +37,26 @@
 class WebGLRenderbuffer;
 class WebGLTexture;
 
-class WebGLFramebuffer : public WebGLContextObject, public ScriptWrappable {
+class WebGLFramebuffer FINAL : public WebGLContextObject, public ScriptWrappable {
 public:
     class WebGLAttachment : public RefCounted<WebGLAttachment> {
     public:
         virtual ~WebGLAttachment();
 
-        virtual GC3Dsizei width() const = 0;
-        virtual GC3Dsizei height() const = 0;
-        virtual GC3Denum format() const = 0;
+        virtual GLsizei width() const = 0;
+        virtual GLsizei height() const = 0;
+        virtual GLenum format() const = 0;
         // For texture attachment, type() returns the type of the attached texture.
         // For renderbuffer attachment, the type of the renderbuffer may vary with GL implementation.
         // To avoid confusion, it would be better to not implement type() for renderbuffer attachment and
         // we should always use the internalformat of the renderbuffer and avoid using type() API.
-        virtual GC3Denum type() const = 0;
+        virtual GLenum type() const = 0;
         virtual WebGLSharedObject* object() const = 0;
         virtual bool isSharedObject(WebGLSharedObject*) const = 0;
         virtual bool valid() const = 0;
-        virtual bool initialized() const = 0;
-        virtual void setInitialized() = 0;
-        virtual void onDetached(GraphicsContext3D*) = 0;
-        virtual void attach(GraphicsContext3D*, GC3Denum attachment) = 0;
-        virtual void unattach(GraphicsContext3D*, GC3Denum attachment) = 0;
+        virtual void onDetached(blink::WebGraphicsContext3D*) = 0;
+        virtual void attach(blink::WebGraphicsContext3D*, GLenum attachment) = 0;
+        virtual void unattach(blink::WebGraphicsContext3D*, GLenum attachment) = 0;
 
     protected:
         WebGLAttachment();
@@ -68,31 +66,29 @@
 
     static PassRefPtr<WebGLFramebuffer> create(WebGLRenderingContext*);
 
-    void setAttachmentForBoundFramebuffer(GC3Denum attachment, GC3Denum texTarget, WebGLTexture*, GC3Dint level);
-    void setAttachmentForBoundFramebuffer(GC3Denum attachment, WebGLRenderbuffer*);
+    void setAttachmentForBoundFramebuffer(GLenum attachment, GLenum texTarget, WebGLTexture*, GLint level);
+    void setAttachmentForBoundFramebuffer(GLenum attachment, WebGLRenderbuffer*);
     // If an object is attached to the currently bound framebuffer, remove it.
     void removeAttachmentFromBoundFramebuffer(WebGLSharedObject*);
     // If a given attachment point for the currently bound framebuffer is not null, remove the attached object.
-    void removeAttachmentFromBoundFramebuffer(GC3Denum);
-    WebGLSharedObject* getAttachmentObject(GC3Denum) const;
+    void removeAttachmentFromBoundFramebuffer(GLenum);
+    WebGLSharedObject* getAttachmentObject(GLenum) const;
 
-    GC3Denum colorBufferFormat() const;
-    GC3Dsizei colorBufferWidth() const;
-    GC3Dsizei colorBufferHeight() const;
+    GLenum colorBufferFormat() const;
+    GLsizei colorBufferWidth() const;
+    GLsizei colorBufferHeight() const;
 
     // This should always be called before drawArray, drawElements, clear,
     // readPixels, copyTexImage2D, copyTexSubImage2D if this framebuffer is
     // currently bound.
-    // Return false if the framebuffer is incomplete; otherwise initialize
-    // the buffers if they haven't been initialized and
-    // needToInitializeAttachments is true.
-    bool onAccess(GraphicsContext3D*, const char** reason);
+    // Return false if the framebuffer is incomplete.
+    bool onAccess(blink::WebGraphicsContext3D*, const char** reason);
 
     // Software version of glCheckFramebufferStatus(), except that when
     // FRAMEBUFFER_COMPLETE is returned, it is still possible for
     // glCheckFramebufferStatus() to return FRAMEBUFFER_UNSUPPORTED,
     // depending on hardware implementation.
-    GC3Denum checkStatus(const char** reason) const;
+    GLenum checkStatus(const char** reason) const;
 
     bool hasEverBeenBound() const { return object() && m_hasEverBeenBound; }
 
@@ -101,38 +97,36 @@
     bool hasStencilBuffer() const;
 
     // Wrapper for drawBuffersEXT/drawBuffersARB to work around a driver bug.
-    void drawBuffers(const Vector<GC3Denum>& bufs);
+    void drawBuffers(const Vector<GLenum>& bufs);
 
-    GC3Denum getDrawBuffer(GC3Denum);
+    GLenum getDrawBuffer(GLenum);
 
 protected:
     WebGLFramebuffer(WebGLRenderingContext*);
 
-    virtual void deleteObjectImpl(GraphicsContext3D*, Platform3DObject);
+    virtual void deleteObjectImpl(blink::WebGraphicsContext3D*, Platform3DObject) OVERRIDE;
 
 private:
-    virtual bool isFramebuffer() const { return true; }
-
-    WebGLAttachment* getAttachment(GC3Denum) const;
-    bool isAttachmentComplete(WebGLAttachment* attachedObject, GC3Denum attachment, const char** reason) const;
+    WebGLAttachment* getAttachment(GLenum) const;
+    bool isAttachmentComplete(WebGLAttachment* attachedObject, GLenum attachment, const char** reason) const;
 
     // Check if the framebuffer is currently bound.
     bool isBound() const;
 
     // attach 'attachment' at 'attachmentPoint'.
-    void attach(GC3Denum attachment, GC3Denum attachmentPoint);
+    void attach(GLenum attachment, GLenum attachmentPoint);
 
     // Check if a new drawBuffers call should be issued. This is called when we add or remove an attachment.
     void drawBuffersIfNecessary(bool force);
 
-    typedef WTF::HashMap<GC3Denum, RefPtr<WebGLAttachment> > AttachmentMap;
+    typedef WTF::HashMap<GLenum, RefPtr<WebGLAttachment> > AttachmentMap;
 
     AttachmentMap m_attachments;
 
     bool m_hasEverBeenBound;
 
-    Vector<GC3Denum> m_drawBuffers;
-    Vector<GC3Denum> m_filteredDrawBuffers;
+    Vector<GLenum> m_drawBuffers;
+    Vector<GLenum> m_filteredDrawBuffers;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/canvas/WebGLLoseContext.h b/Source/core/html/canvas/WebGLLoseContext.h
index 23140d6..e2a1141 100644
--- a/Source/core/html/canvas/WebGLLoseContext.h
+++ b/Source/core/html/canvas/WebGLLoseContext.h
@@ -34,15 +34,15 @@
 
 class WebGLRenderingContext;
 
-class WebGLLoseContext : public WebGLExtension, public ScriptWrappable {
+class WebGLLoseContext FINAL : public WebGLExtension, public ScriptWrappable {
 public:
     static PassRefPtr<WebGLLoseContext> create(WebGLRenderingContext*);
     static bool supported(WebGLRenderingContext*);
     static const char* extensionName();
 
     virtual ~WebGLLoseContext();
-    virtual ExtensionName name() const;
-    virtual void lose(bool);
+    virtual ExtensionName name() const OVERRIDE;
+    virtual void lose(bool) OVERRIDE;
 
     void loseContext();
     void restoreContext();
diff --git a/Source/core/html/canvas/WebGLLoseContext.idl b/Source/core/html/canvas/WebGLLoseContext.idl
index 1ac288f..2b45e1a 100644
--- a/Source/core/html/canvas/WebGLLoseContext.idl
+++ b/Source/core/html/canvas/WebGLLoseContext.idl
@@ -24,8 +24,9 @@
  */
 
 [
-    NoInterfaceObject
+    NoInterfaceObject,
+    StrictTypeChecking,
 ] interface WebGLLoseContext {
-    [StrictTypeChecking] void loseContext();
-    [StrictTypeChecking] void restoreContext();
+    void loseContext();
+    void restoreContext();
 };
diff --git a/Source/core/html/canvas/WebGLObject.cpp b/Source/core/html/canvas/WebGLObject.cpp
index 3ffddaa..e7c348a 100644
--- a/Source/core/html/canvas/WebGLObject.cpp
+++ b/Source/core/html/canvas/WebGLObject.cpp
@@ -47,7 +47,7 @@
     m_object = object;
 }
 
-void WebGLObject::deleteObject(GraphicsContext3D* context3d)
+void WebGLObject::deleteObject(blink::WebGraphicsContext3D* context3d)
 {
     m_deleted = true;
     if (!m_object)
@@ -58,7 +58,7 @@
 
     if (!m_attachmentCount) {
         if (!context3d)
-            context3d = getAGraphicsContext3D();
+            context3d = getAWebGraphicsContext3D();
 
         if (context3d)
             deleteObjectImpl(context3d, m_object);
@@ -73,7 +73,7 @@
     }
 
 
-void WebGLObject::onDetached(GraphicsContext3D* context3d)
+void WebGLObject::onDetached(blink::WebGraphicsContext3D* context3d)
 {
     if (m_attachmentCount)
         --m_attachmentCount;
diff --git a/Source/core/html/canvas/WebGLObject.h b/Source/core/html/canvas/WebGLObject.h
index f1f1afd..159ef68 100644
--- a/Source/core/html/canvas/WebGLObject.h
+++ b/Source/core/html/canvas/WebGLObject.h
@@ -26,13 +26,15 @@
 #ifndef WebGLObject_h
 #define WebGLObject_h
 
-#include "platform/graphics/GraphicsContext3D.h"
-
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/RefCounted.h"
 
+namespace blink {
+class WebGraphicsContext3D;
+}
+
 namespace WebCore {
 
-class GraphicsContext3D;
 class WebGLContextGroup;
 class WebGLRenderingContext;
 
@@ -45,10 +47,10 @@
     // deleteObject may not always delete the OpenGL resource.  For programs and
     // shaders, deletion is delayed until they are no longer attached.
     // FIXME: revisit this when resource sharing between contexts are implemented.
-    void deleteObject(GraphicsContext3D*);
+    void deleteObject(blink::WebGraphicsContext3D*);
 
     void onAttached() { ++m_attachmentCount; }
-    void onDetached(GraphicsContext3D*);
+    void onDetached(blink::WebGraphicsContext3D*);
 
     // This indicates whether the client side issue a delete call already, not
     // whether the OpenGL resource is deleted.
@@ -65,13 +67,13 @@
     void setObject(Platform3DObject);
 
     // deleteObjectImpl should be only called once to delete the OpenGL resource.
-    virtual void deleteObjectImpl(GraphicsContext3D*, Platform3DObject) = 0;
+    virtual void deleteObjectImpl(blink::WebGraphicsContext3D*, Platform3DObject) = 0;
 
     virtual bool hasGroupOrContext() const = 0;
 
     virtual void detach();
 
-    virtual GraphicsContext3D* getAGraphicsContext3D() const = 0;
+    virtual blink::WebGraphicsContext3D* getAWebGraphicsContext3D() const = 0;
 
 private:
     Platform3DObject m_object;
diff --git a/Source/core/html/canvas/WebGLProgram.cpp b/Source/core/html/canvas/WebGLProgram.cpp
index f3001c5..9977889 100644
--- a/Source/core/html/canvas/WebGLProgram.cpp
+++ b/Source/core/html/canvas/WebGLProgram.cpp
@@ -43,7 +43,7 @@
     , m_infoValid(true)
 {
     ScriptWrappable::init(this);
-    setObject(ctx->graphicsContext3D()->createProgram());
+    setObject(ctx->webGraphicsContext3D()->createProgram());
 }
 
 WebGLProgram::~WebGLProgram()
@@ -51,7 +51,7 @@
     deleteObject(0);
 }
 
-void WebGLProgram::deleteObjectImpl(GraphicsContext3D* context3d, Platform3DObject obj)
+void WebGLProgram::deleteObjectImpl(blink::WebGraphicsContext3D* context3d, Platform3DObject obj)
 {
     context3d->deleteProgram(obj);
     if (m_vertexShader) {
@@ -70,7 +70,7 @@
     return m_activeAttribLocations.size();
 }
 
-GC3Dint WebGLProgram::getActiveAttribLocation(GC3Duint index)
+GLint WebGLProgram::getActiveAttribLocation(GLuint index)
 {
     cacheInfoIfNeeded();
     if (index >= numActiveAttribLocations())
@@ -106,12 +106,12 @@
     m_infoValid = false;
 }
 
-WebGLShader* WebGLProgram::getAttachedShader(GC3Denum type)
+WebGLShader* WebGLProgram::getAttachedShader(GLenum type)
 {
     switch (type) {
-    case GraphicsContext3D::VERTEX_SHADER:
+    case GL_VERTEX_SHADER:
         return m_vertexShader.get();
-    case GraphicsContext3D::FRAGMENT_SHADER:
+    case GL_FRAGMENT_SHADER:
         return m_fragmentShader.get();
     default:
         return 0;
@@ -123,12 +123,12 @@
     if (!shader || !shader->object())
         return false;
     switch (shader->type()) {
-    case GraphicsContext3D::VERTEX_SHADER:
+    case GL_VERTEX_SHADER:
         if (m_vertexShader)
             return false;
         m_vertexShader = shader;
         return true;
-    case GraphicsContext3D::FRAGMENT_SHADER:
+    case GL_FRAGMENT_SHADER:
         if (m_fragmentShader)
             return false;
         m_fragmentShader = shader;
@@ -143,12 +143,12 @@
     if (!shader || !shader->object())
         return false;
     switch (shader->type()) {
-    case GraphicsContext3D::VERTEX_SHADER:
+    case GL_VERTEX_SHADER:
         if (m_vertexShader != shader)
             return false;
         m_vertexShader = 0;
         return true;
-    case GraphicsContext3D::FRAGMENT_SHADER:
+    case GL_FRAGMENT_SHADER:
         if (m_fragmentShader != shader)
             return false;
         m_fragmentShader = 0;
@@ -158,17 +158,17 @@
     }
 }
 
-void WebGLProgram::cacheActiveAttribLocations(GraphicsContext3D* context3d)
+void WebGLProgram::cacheActiveAttribLocations(blink::WebGraphicsContext3D* context3d)
 {
     m_activeAttribLocations.clear();
 
-    GC3Dint numAttribs = 0;
-    context3d->getProgramiv(object(), GraphicsContext3D::ACTIVE_ATTRIBUTES, &numAttribs);
+    GLint numAttribs = 0;
+    context3d->getProgramiv(object(), GL_ACTIVE_ATTRIBUTES, &numAttribs);
     m_activeAttribLocations.resize(static_cast<size_t>(numAttribs));
     for (int i = 0; i < numAttribs; ++i) {
-        ActiveInfo info;
+        blink::WebGraphicsContext3D::ActiveInfo info;
         context3d->getActiveAttrib(object(), i, info);
-        m_activeAttribLocations[i] = context3d->getAttribLocation(object(), info.name);
+        m_activeAttribLocations[i] = context3d->getAttribLocation(object(), info.name.utf8().data());
     }
 }
 
@@ -180,11 +180,11 @@
     if (!object())
         return;
 
-    GraphicsContext3D* context = getAGraphicsContext3D();
+    blink::WebGraphicsContext3D* context = getAWebGraphicsContext3D();
     if (!context)
         return;
-    GC3Dint linkStatus = 0;
-    context->getProgramiv(object(), GraphicsContext3D::LINK_STATUS, &linkStatus);
+    GLint linkStatus = 0;
+    context->getProgramiv(object(), GL_LINK_STATUS, &linkStatus);
     m_linkStatus = linkStatus;
     if (m_linkStatus)
         cacheActiveAttribLocations(context);
diff --git a/Source/core/html/canvas/WebGLProgram.h b/Source/core/html/canvas/WebGLProgram.h
index 5ba00e7..5827afe 100644
--- a/Source/core/html/canvas/WebGLProgram.h
+++ b/Source/core/html/canvas/WebGLProgram.h
@@ -34,14 +34,14 @@
 
 namespace WebCore {
 
-class WebGLProgram : public WebGLSharedObject, public ScriptWrappable {
+class WebGLProgram FINAL : public WebGLSharedObject, public ScriptWrappable {
 public:
     virtual ~WebGLProgram();
 
     static PassRefPtr<WebGLProgram> create(WebGLRenderingContext*);
 
     unsigned numActiveAttribLocations();
-    GC3Dint getActiveAttribLocation(GC3Duint index);
+    GLint getActiveAttribLocation(GLuint index);
 
     bool isUsingVertexAttrib0();
 
@@ -56,24 +56,24 @@
     // Also, we invalidate the cached program info.
     void increaseLinkCount();
 
-    WebGLShader* getAttachedShader(GC3Denum);
+    WebGLShader* getAttachedShader(GLenum);
     bool attachShader(WebGLShader*);
     bool detachShader(WebGLShader*);
 
 protected:
     WebGLProgram(WebGLRenderingContext*);
 
-    virtual void deleteObjectImpl(GraphicsContext3D*, Platform3DObject);
+    virtual void deleteObjectImpl(blink::WebGraphicsContext3D*, Platform3DObject) OVERRIDE;
 
 private:
-    virtual bool isProgram() const { return true; }
+    virtual bool isProgram() const OVERRIDE { return true; }
 
-    void cacheActiveAttribLocations(GraphicsContext3D*);
+    void cacheActiveAttribLocations(blink::WebGraphicsContext3D*);
     void cacheInfoIfNeeded();
 
-    Vector<GC3Dint> m_activeAttribLocations;
+    Vector<GLint> m_activeAttribLocations;
 
-    GC3Dint m_linkStatus;
+    GLint m_linkStatus;
 
     // This is used to track whether a WebGLUniformLocation belongs to this
     // program or not.
diff --git a/Source/core/html/canvas/WebGLRenderbuffer.cpp b/Source/core/html/canvas/WebGLRenderbuffer.cpp
index 68b3ae2..d5c517f 100644
--- a/Source/core/html/canvas/WebGLRenderbuffer.cpp
+++ b/Source/core/html/canvas/WebGLRenderbuffer.cpp
@@ -43,23 +43,22 @@
 
 WebGLRenderbuffer::WebGLRenderbuffer(WebGLRenderingContext* ctx)
     : WebGLSharedObject(ctx)
-    , m_internalFormat(GraphicsContext3D::RGBA4)
-    , m_initialized(false)
+    , m_internalFormat(GL_RGBA4)
     , m_width(0)
     , m_height(0)
     , m_hasEverBeenBound(false)
 {
     ScriptWrappable::init(this);
-    setObject(ctx->graphicsContext3D()->createRenderbuffer());
+    setObject(ctx->webGraphicsContext3D()->createRenderbuffer());
 }
 
-void WebGLRenderbuffer::deleteObjectImpl(GraphicsContext3D* context3d, Platform3DObject object)
+void WebGLRenderbuffer::deleteObjectImpl(blink::WebGraphicsContext3D* context3d, Platform3DObject object)
 {
     context3d->deleteRenderbuffer(object);
     deleteEmulatedStencilBuffer(context3d);
 }
 
-void WebGLRenderbuffer::deleteEmulatedStencilBuffer(GraphicsContext3D* context3d)
+void WebGLRenderbuffer::deleteEmulatedStencilBuffer(blink::WebGraphicsContext3D* context3d)
 {
     if (!m_emulatedStencilBuffer)
         return;
diff --git a/Source/core/html/canvas/WebGLRenderbuffer.h b/Source/core/html/canvas/WebGLRenderbuffer.h
index 95688a2..8af0755 100644
--- a/Source/core/html/canvas/WebGLRenderbuffer.h
+++ b/Source/core/html/canvas/WebGLRenderbuffer.h
@@ -32,29 +32,25 @@
 
 namespace WebCore {
 
-class WebGLRenderbuffer : public WebGLSharedObject, public ScriptWrappable {
+class WebGLRenderbuffer FINAL : public WebGLSharedObject, public ScriptWrappable {
 public:
     virtual ~WebGLRenderbuffer();
 
     static PassRefPtr<WebGLRenderbuffer> create(WebGLRenderingContext*);
 
-    void setInternalFormat(GC3Denum internalformat)
+    void setInternalFormat(GLenum internalformat)
     {
         m_internalFormat = internalformat;
-        m_initialized = false;
     }
-    GC3Denum internalFormat() const { return m_internalFormat; }
+    GLenum internalFormat() const { return m_internalFormat; }
 
-    void setSize(GC3Dsizei width, GC3Dsizei height)
+    void setSize(GLsizei width, GLsizei height)
     {
         m_width = width;
         m_height = height;
     }
-    GC3Dsizei width() const { return m_width; }
-    GC3Dsizei height() const { return m_height; }
-
-    bool initialized() const { return m_initialized; }
-    void setInitialized() { m_initialized = true; }
+    GLsizei width() const { return m_width; }
+    GLsizei height() const { return m_height; }
 
     bool hasEverBeenBound() const { return object() && m_hasEverBeenBound; }
 
@@ -62,19 +58,18 @@
 
     void setEmulatedStencilBuffer(PassRefPtr<WebGLRenderbuffer> buffer) { m_emulatedStencilBuffer = buffer; }
     WebGLRenderbuffer* emulatedStencilBuffer() const { return m_emulatedStencilBuffer.get(); }
-    void deleteEmulatedStencilBuffer(GraphicsContext3D* context3d);
+    void deleteEmulatedStencilBuffer(blink::WebGraphicsContext3D* context3d);
 
 protected:
     WebGLRenderbuffer(WebGLRenderingContext*);
 
-    virtual void deleteObjectImpl(GraphicsContext3D*, Platform3DObject);
+    virtual void deleteObjectImpl(blink::WebGraphicsContext3D*, Platform3DObject) OVERRIDE;
 
 private:
-    virtual bool isRenderbuffer() const { return true; }
+    virtual bool isRenderbuffer() const OVERRIDE { return true; }
 
-    GC3Denum m_internalFormat;
-    bool m_initialized;
-    GC3Dsizei m_width, m_height;
+    GLenum m_internalFormat;
+    GLsizei m_width, m_height;
 
     bool m_hasEverBeenBound;
 
diff --git a/Source/core/html/canvas/WebGLRenderingContext.cpp b/Source/core/html/canvas/WebGLRenderingContext.cpp
index b8b9220..02a321e 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -69,13 +69,14 @@
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderBox.h"
+#include "platform/CheckedInt.h"
 #include "platform/NotImplemented.h"
 #include "platform/geometry/IntSize.h"
-#include "platform/graphics/Extensions3D.h"
 #include "platform/graphics/UnacceleratedImageBufferSurface.h"
 #include "platform/graphics/gpu/DrawingBuffer.h"
+#include "public/platform/Platform.h"
 
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Uint32Array.h"
@@ -125,7 +126,7 @@
     size_t candidateID = 0;
     for (size_t ii = 1; ii < activeContexts().size(); ++ii) {
         WebGLRenderingContext* context = activeContexts()[ii];
-        if (context->graphicsContext3D() && candidate->graphicsContext3D() && context->graphicsContext3D()->lastFlushID() < candidate->graphicsContext3D()->lastFlushID()) {
+        if (context->webGraphicsContext3D() && candidate->webGraphicsContext3D() && context->webGraphicsContext3D()->lastFlushID() < candidate->webGraphicsContext3D()->lastFlushID()) {
             candidate = context;
             candidateID = ii;
         }
@@ -238,7 +239,7 @@
         return object ? object->object() : 0;
     }
 
-    GC3Dint clamp(GC3Dint value, GC3Dint min, GC3Dint max)
+    GLint clamp(GLint value, GLint min, GLint max)
     {
         if (value < min)
             value = min;
@@ -452,20 +453,9 @@
             break;
         }
     }
-
-    GraphicsContext3D::Attributes adjustAttributes(const GraphicsContext3D::Attributes& attributes, Settings* settings)
-    {
-        GraphicsContext3D::Attributes adjustedAttributes = attributes;
-        if (adjustedAttributes.antialias) {
-            if (settings && !settings->openGLMultisamplingEnabled())
-                adjustedAttributes.antialias = false;
-        }
-
-        return adjustedAttributes;
-    }
 } // namespace anonymous
 
-class WebGLRenderingContextLostCallback : public GraphicsContext3D::ContextLostCallback {
+class WebGLRenderingContextLostCallback : public blink::WebGraphicsContext3D::WebGraphicsContextLostCallback {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit WebGLRenderingContextLostCallback(WebGLRenderingContext* cb) : m_context(cb) { }
@@ -475,11 +465,11 @@
     WebGLRenderingContext* m_context;
 };
 
-class WebGLRenderingContextErrorMessageCallback : public GraphicsContext3D::ErrorMessageCallback {
+class WebGLRenderingContextErrorMessageCallback : public blink::WebGraphicsContext3D::WebGraphicsErrorMessageCallback {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit WebGLRenderingContextErrorMessageCallback(WebGLRenderingContext* cb) : m_context(cb) { }
-    virtual void onErrorMessage(const String& message, GC3Dint)
+    virtual void onErrorMessage(const blink::WebString& message, blink::WGC3Dint)
     {
         if (m_context->m_synthesizedErrorsToConsole)
             m_context->printGLErrorToConsole(message);
@@ -505,26 +495,24 @@
         return nullptr;
     }
 
-    GraphicsContext3D::Attributes requestedAttributes = attrs ? attrs->attributes() : GraphicsContext3D::Attributes();
-    requestedAttributes.noExtensions = true;
-    requestedAttributes.shareResources = true;
-    requestedAttributes.preferDiscreteGPU = true;
-    requestedAttributes.topDocumentURL = document.topDocument()->url();
-
-    GraphicsContext3D::Attributes attributes = adjustAttributes(requestedAttributes, settings);
-
-    RefPtr<GraphicsContext3D> context(GraphicsContext3D::create(attributes));
-
+    // The only situation that attrs is null is through Document::getCSSCanvasContext().
+    RefPtr<WebGLContextAttributes> defaultAttrs;
+    if (!attrs) {
+        defaultAttrs = WebGLContextAttributes::create();
+        attrs = defaultAttrs.get();
+    }
+    blink::WebGraphicsContext3D::Attributes attributes = attrs->attributes(document.topDocument()->url().string(), settings);
+    OwnPtr<blink::WebGraphicsContext3D> context = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(attributes));
     if (!context || !context->makeContextCurrent()) {
         canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Could not create a WebGL context."));
         return nullptr;
     }
 
-    Extensions3D* extensions = context->extensions();
-    if (extensions->supports("GL_EXT_debug_marker"))
-        extensions->pushGroupMarkerEXT("WebGLRenderingContext");
+    Extensions3DUtil extensionsUtil(context.get());
+    if (extensionsUtil.supportsExtension("GL_EXT_debug_marker"))
+        context->pushGroupMarkerEXT("WebGLRenderingContext");
 
-    OwnPtr<WebGLRenderingContext> renderingContext = adoptPtr(new WebGLRenderingContext(canvas, context, attributes, requestedAttributes));
+    OwnPtr<WebGLRenderingContext> renderingContext = adoptPtr(new WebGLRenderingContext(canvas, context.release(), attrs));
     renderingContext->suspendIfNeeded();
 
     if (renderingContext->m_drawingBuffer->isZeroSized()) {
@@ -535,7 +523,7 @@
     return renderingContext.release();
 }
 
-WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, PassRefPtr<GraphicsContext3D> context, GraphicsContext3D::Attributes attributes, GraphicsContext3D::Attributes requestedAttributes)
+WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, PassOwnPtr<blink::WebGraphicsContext3D> context, WebGLContextAttributes* requestedAttributes)
     : CanvasRenderingContext(passedCanvas)
     , ActiveDOMObject(&passedCanvas->document())
     , m_context(context)
@@ -546,8 +534,7 @@
     , m_generatedImageCache(4)
     , m_contextLost(false)
     , m_contextLostMode(SyntheticLostContext)
-    , m_attributes(attributes)
-    , m_requestedAttributes(requestedAttributes)
+    , m_requestedAttributes(requestedAttributes->clone())
     , m_synthesizedErrorsToConsole(true)
     , m_numGLErrorsToConsoleAllowed(maxGLErrorsAllowedToConsole)
     , m_multisamplingAllowed(false)
@@ -562,12 +549,12 @@
     m_contextGroup->addContext(this);
 
     m_maxViewportDims[0] = m_maxViewportDims[1] = 0;
-    m_context->getIntegerv(GraphicsContext3D::MAX_VIEWPORT_DIMS, m_maxViewportDims);
+    m_context->getIntegerv(GL_MAX_VIEWPORT_DIMS, m_maxViewportDims);
 
     RefPtr<WebGLRenderingContextEvictionManager> contextEvictionManager = adoptRef(new WebGLRenderingContextEvictionManager());
 
     // Create the DrawingBuffer and initialize the platform layer.
-    DrawingBuffer::PreserveDrawingBuffer preserve = m_attributes.preserveDrawingBuffer ? DrawingBuffer::Preserve : DrawingBuffer::Discard;
+    DrawingBuffer::PreserveDrawingBuffer preserve = requestedAttributes->preserveDrawingBuffer() ? DrawingBuffer::Preserve : DrawingBuffer::Discard;
     m_drawingBuffer = DrawingBuffer::create(m_context.get(), clampedCanvasSize(), preserve, contextEvictionManager.release());
 
     if (!m_drawingBuffer->isZeroSized()) {
@@ -581,7 +568,7 @@
     static const char* const bothPrefixes[] = { "", "WEBKIT_", 0, };
 
     registerExtension<ANGLEInstancedArrays>(m_angleInstancedArrays);
-    registerExtension<EXTTextureFilterAnisotropic>(m_extTextureFilterAnisotropic, PrefixedExtension, webkitPrefix);
+    registerExtension<EXTTextureFilterAnisotropic>(m_extTextureFilterAnisotropic, ApprovedExtension, bothPrefixes);
     registerExtension<OESElementIndexUint>(m_oesElementIndexUint);
     registerExtension<OESStandardDerivatives>(m_oesStandardDerivatives);
     registerExtension<OESTextureFloat>(m_oesTextureFloat);
@@ -591,8 +578,8 @@
     registerExtension<OESVertexArrayObject>(m_oesVertexArrayObject);
     registerExtension<WebGLCompressedTextureATC>(m_webglCompressedTextureATC, PrefixedExtension, webkitPrefix);
     registerExtension<WebGLCompressedTexturePVRTC>(m_webglCompressedTexturePVRTC, PrefixedExtension, webkitPrefix);
-    registerExtension<WebGLCompressedTextureS3TC>(m_webglCompressedTextureS3TC, PrefixedExtension, bothPrefixes);
-    registerExtension<WebGLDepthTexture>(m_webglDepthTexture, PrefixedExtension, bothPrefixes);
+    registerExtension<WebGLCompressedTextureS3TC>(m_webglCompressedTextureS3TC, ApprovedExtension, bothPrefixes);
+    registerExtension<WebGLDepthTexture>(m_webglDepthTexture, ApprovedExtension, bothPrefixes);
     registerExtension<WebGLDrawBuffers>(m_webglDrawBuffers);
     registerExtension<WebGLLoseContext>(m_webglLoseContext, ApprovedExtension, bothPrefixes);
 
@@ -614,7 +601,7 @@
     m_unpackAlignment = 4;
     m_unpackFlipY = false;
     m_unpackPremultiplyAlpha = false;
-    m_unpackColorspaceConversion = GraphicsContext3D::BROWSER_DEFAULT_WEBGL;
+    m_unpackColorspaceConversion = GC3D_BROWSER_DEFAULT_WEBGL;
     m_boundArrayBuffer = 0;
     m_currentProgram = 0;
     m_framebufferBinding = 0;
@@ -636,29 +623,29 @@
     m_clearStencil = 0;
     m_colorMask[0] = m_colorMask[1] = m_colorMask[2] = m_colorMask[3] = true;
 
-    GC3Dint numCombinedTextureImageUnits = 0;
-    m_context->getIntegerv(GraphicsContext3D::MAX_COMBINED_TEXTURE_IMAGE_UNITS, &numCombinedTextureImageUnits);
+    GLint numCombinedTextureImageUnits = 0;
+    m_context->getIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &numCombinedTextureImageUnits);
     m_textureUnits.clear();
     m_textureUnits.resize(numCombinedTextureImageUnits);
 
-    GC3Dint numVertexAttribs = 0;
-    m_context->getIntegerv(GraphicsContext3D::MAX_VERTEX_ATTRIBS, &numVertexAttribs);
+    GLint numVertexAttribs = 0;
+    m_context->getIntegerv(GL_MAX_VERTEX_ATTRIBS, &numVertexAttribs);
     m_maxVertexAttribs = numVertexAttribs;
 
     m_maxTextureSize = 0;
-    m_context->getIntegerv(GraphicsContext3D::MAX_TEXTURE_SIZE, &m_maxTextureSize);
+    m_context->getIntegerv(GL_MAX_TEXTURE_SIZE, &m_maxTextureSize);
     m_maxTextureLevel = WebGLTexture::computeLevelCount(m_maxTextureSize, m_maxTextureSize);
     m_maxCubeMapTextureSize = 0;
-    m_context->getIntegerv(GraphicsContext3D::MAX_CUBE_MAP_TEXTURE_SIZE, &m_maxCubeMapTextureSize);
+    m_context->getIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &m_maxCubeMapTextureSize);
     m_maxCubeMapTextureLevel = WebGLTexture::computeLevelCount(m_maxCubeMapTextureSize, m_maxCubeMapTextureSize);
     m_maxRenderbufferSize = 0;
-    m_context->getIntegerv(GraphicsContext3D::MAX_RENDERBUFFER_SIZE, &m_maxRenderbufferSize);
+    m_context->getIntegerv(GL_MAX_RENDERBUFFER_SIZE, &m_maxRenderbufferSize);
 
     // These two values from EXT_draw_buffers are lazily queried.
     m_maxDrawBuffers = 0;
     m_maxColorAttachments = 0;
 
-    m_backDrawBuffer = GraphicsContext3D::BACK;
+    m_backDrawBuffer = GL_BACK;
 
     m_defaultVertexArrayObject = WebGLVertexArrayObjectOES::create(this, WebGLVertexArrayObjectOES::VaoTypeDefault);
     addContextObject(m_defaultVertexArrayObject.get());
@@ -674,8 +661,11 @@
     m_context->viewport(0, 0, canvasSize.width(), canvasSize.height());
     m_context->scissor(0, 0, canvasSize.width(), canvasSize.height());
 
-    m_context->setContextLostCallback(adoptPtr(new WebGLRenderingContextLostCallback(this)));
-    m_context->setErrorMessageCallback(adoptPtr(new WebGLRenderingContextErrorMessageCallback(this)));
+    m_contextLostCallbackAdapter = adoptPtr(new WebGLRenderingContextLostCallback(this));
+    m_errorMessageCallbackAdapter = adoptPtr(new WebGLRenderingContextErrorMessageCallback(this));
+
+    m_context->setContextLostCallback(m_contextLostCallbackAdapter.get());
+    m_context->setErrorMessageCallback(m_errorMessageCallbackAdapter.get());
 
     // This ensures that the context has a valid "lastFlushID" and won't be mistakenly identified as the "least recently used" context.
     m_context->flush();
@@ -689,15 +679,15 @@
     if (Page* p = canvas()->document().page()) {
         m_synthesizedErrorsToConsole = p->settings().webGLErrorsToConsoleEnabled();
 
-        if (!m_multisamplingObserverRegistered && m_requestedAttributes.antialias) {
+        if (!m_multisamplingObserverRegistered && m_requestedAttributes->antialias()) {
             m_multisamplingAllowed = m_drawingBuffer->multisample();
             p->addMultisamplingChangedObserver(this);
             m_multisamplingObserverRegistered = true;
         }
     }
 
-    m_isGLES2NPOTStrict = !m_context->extensions()->isEnabled("GL_OES_texture_npot");
-    m_isDepthStencilSupported = m_context->extensions()->isEnabled("GL_OES_packed_depth_stencil");
+    m_isGLES2NPOTStrict = !extensionsUtil()->isExtensionEnabled("GL_OES_texture_npot");
+    m_isDepthStencilSupported = extensionsUtil()->isExtensionEnabled("GL_OES_packed_depth_stencil");
 }
 
 bool WebGLRenderingContext::allowPrivilegedExtensions() const
@@ -709,13 +699,10 @@
 
 bool WebGLRenderingContext::allowWebGLDebugRendererInfo() const
 {
-    if (allowPrivilegedExtensions())
-        return true;
-    Frame* frame = canvas()->document().frame();
-    return frame && frame->loader().client()->allowWebGLDebugRendererInfo();
+    return true;
 }
 
-void WebGLRenderingContext::addCompressedTextureFormat(GC3Denum format)
+void WebGLRenderingContext::addCompressedTextureFormat(GLenum format)
 {
     if (!m_compressedTextureFormats.contains(format))
         m_compressedTextureFormats.append(format);
@@ -753,10 +740,10 @@
         delete m_extensions[i];
 
     // Context must be removed from the group prior to the destruction of the
-    // GraphicsContext3D, otherwise shared objects may not be properly deleted.
+    // WebGraphicsContext3D, otherwise shared objects may not be properly deleted.
     m_contextGroup->removeContext(this);
 
-    destroyGraphicsContext3D();
+    destroyContext();
 
     if (m_multisamplingObserverRegistered) {
         Page* page = canvas()->document().page();
@@ -767,7 +754,7 @@
     willDestroyContext(this);
 }
 
-void WebGLRenderingContext::destroyGraphicsContext3D()
+void WebGLRenderingContext::destroyContext()
 {
     m_contextLost = true;
 
@@ -775,9 +762,11 @@
     // in order for the context to be released.
     m_drawingBuffer->releaseResources();
 
+    m_extensionsUtil.clear();
+
     if (m_context) {
-        m_context->setContextLostCallback(nullptr);
-        m_context->setErrorMessageCallback(nullptr);
+        m_context->setContextLostCallback(0);
+        m_context->setErrorMessageCallback(0);
         m_context.clear();
     }
 }
@@ -787,7 +776,6 @@
     if (m_framebufferBinding || isContextLost())
         return;
 
-    m_context->markContextChanged();
     m_drawingBuffer->markContentsChanged();
 
     m_layerCleared = false;
@@ -804,13 +792,13 @@
     }
 }
 
-bool WebGLRenderingContext::clearIfComposited(GC3Dbitfield mask)
+bool WebGLRenderingContext::clearIfComposited(GLbitfield mask)
 {
     if (isContextLost())
         return false;
 
-    if (!m_context->layerComposited() || m_layerCleared
-        || m_attributes.preserveDrawingBuffer || (mask && m_framebufferBinding))
+    if (!m_drawingBuffer->layerComposited() || m_layerCleared
+        || m_requestedAttributes->preserveDrawingBuffer() || (mask && m_framebufferBinding))
         return false;
 
     RefPtr<WebGLContextAttributes> contextAttributes = getContextAttributes();
@@ -818,8 +806,8 @@
     // Determine if it's possible to combine the clear the user asked for and this clear.
     bool combinedClear = mask && !m_scissorEnabled;
 
-    m_context->disable(GraphicsContext3D::SCISSOR_TEST);
-    if (combinedClear && (mask & GraphicsContext3D::COLOR_BUFFER_BIT))
+    m_context->disable(GL_SCISSOR_TEST);
+    if (combinedClear && (mask & GL_COLOR_BUFFER_BIT))
         m_context->clearColor(m_colorMask[0] ? m_clearColor[0] : 0,
                               m_colorMask[1] ? m_clearColor[1] : 0,
                               m_colorMask[2] ? m_clearColor[2] : 0,
@@ -827,27 +815,27 @@
     else
         m_context->clearColor(0, 0, 0, 0);
     m_context->colorMask(true, true, true, true);
-    GC3Dbitfield clearMask = GraphicsContext3D::COLOR_BUFFER_BIT;
+    GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
     if (contextAttributes->depth()) {
-        if (!combinedClear || !m_depthMask || !(mask & GraphicsContext3D::DEPTH_BUFFER_BIT))
+        if (!combinedClear || !m_depthMask || !(mask & GL_DEPTH_BUFFER_BIT))
             m_context->clearDepth(1.0f);
-        clearMask |= GraphicsContext3D::DEPTH_BUFFER_BIT;
+        clearMask |= GL_DEPTH_BUFFER_BIT;
         m_context->depthMask(true);
     }
     if (contextAttributes->stencil()) {
-        if (combinedClear && (mask & GraphicsContext3D::STENCIL_BUFFER_BIT))
+        if (combinedClear && (mask & GL_STENCIL_BUFFER_BIT))
             m_context->clearStencil(m_clearStencil & m_stencilMask);
         else
             m_context->clearStencil(0);
-        clearMask |= GraphicsContext3D::STENCIL_BUFFER_BIT;
-        m_context->stencilMaskSeparate(GraphicsContext3D::FRONT, 0xFFFFFFFF);
+        clearMask |= GL_STENCIL_BUFFER_BIT;
+        m_context->stencilMaskSeparate(GL_FRONT, 0xFFFFFFFF);
     }
 
     m_drawingBuffer->clearFramebuffers(clearMask);
 
     restoreStateAfterClear();
     if (m_framebufferBinding)
-        m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
+        m_context->bindFramebuffer(GL_FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
     m_layerCleared = true;
 
     return combinedClear;
@@ -860,21 +848,21 @@
 
     // Restore the state that the context set.
     if (m_scissorEnabled)
-        m_context->enable(GraphicsContext3D::SCISSOR_TEST);
+        m_context->enable(GL_SCISSOR_TEST);
     m_context->clearColor(m_clearColor[0], m_clearColor[1],
                           m_clearColor[2], m_clearColor[3]);
     m_context->colorMask(m_colorMask[0], m_colorMask[1],
                          m_colorMask[2], m_colorMask[3]);
     m_context->clearDepth(m_clearDepth);
     m_context->clearStencil(m_clearStencil);
-    m_context->stencilMaskSeparate(GraphicsContext3D::FRONT, m_stencilMask);
+    m_context->stencilMaskSeparate(GL_FRONT, m_stencilMask);
     m_context->depthMask(m_depthMask);
 }
 
 void WebGLRenderingContext::markLayerComposited()
 {
     if (!isContextLost())
-        m_context->markLayerComposited();
+        m_drawingBuffer->markLayerComposited();
 }
 
 void WebGLRenderingContext::paintRenderingResultsToCanvas()
@@ -889,7 +877,7 @@
 
     // Until the canvas is written to by the application, the clear that
     // happened after it was composited should be ignored by the compositor.
-    if (m_context->layerComposited() && !m_attributes.preserveDrawingBuffer) {
+    if (m_drawingBuffer->layerComposited() && !m_requestedAttributes->preserveDrawingBuffer()) {
         m_drawingBuffer->paintCompositedResultsToCanvas(canvas()->buffer());
 
         canvas()->makePresentationCopy();
@@ -904,11 +892,14 @@
     m_markedCanvasDirty = false;
 
     m_drawingBuffer->commit();
-    if (!(canvas()->buffer())->copyRenderingResultsFromDrawingBuffer(m_drawingBuffer.get()))
-        m_context->paintRenderingResultsToCanvas(canvas()->buffer(), m_drawingBuffer.get());
+    if (!(canvas()->buffer())->copyRenderingResultsFromDrawingBuffer(m_drawingBuffer.get())) {
+        canvas()->ensureUnacceleratedImageBuffer();
+        if (canvas()->hasImageBuffer())
+            m_drawingBuffer->paintRenderingResultsToCanvas(canvas()->buffer());
+    }
 
     if (m_framebufferBinding)
-        m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
+        m_context->bindFramebuffer(GL_FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
     else
         m_drawingBuffer->bind();
 }
@@ -921,12 +912,12 @@
     clearIfComposited();
     m_drawingBuffer->commit();
     int width, height;
-    RefPtr<Uint8ClampedArray> imageDataPixels = m_context->paintRenderingResultsToImageData(m_drawingBuffer.get(), width, height);
+    RefPtr<Uint8ClampedArray> imageDataPixels = m_drawingBuffer->paintRenderingResultsToImageData(width, height);
     if (!imageDataPixels)
         return 0;
 
     if (m_framebufferBinding)
-        m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
+        m_context->bindFramebuffer(GL_FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
     else
         m_drawingBuffer->bind();
 
@@ -940,12 +931,12 @@
 
     // This is an approximation because at WebGLRenderingContext level we don't
     // know if the underlying FBO uses textures or renderbuffers.
-    GC3Dint maxSize = std::min(m_maxTextureSize, m_maxRenderbufferSize);
+    GLint maxSize = std::min(m_maxTextureSize, m_maxRenderbufferSize);
     // Limit drawing buffer size to 4k to avoid memory exhaustion.
     const int sizeUpperLimit = 4096;
     maxSize = std::min(maxSize, sizeUpperLimit);
-    GC3Dint maxWidth = std::min(maxSize, m_maxViewportDims[0]);
-    GC3Dint maxHeight = std::min(maxSize, m_maxViewportDims[1]);
+    GLint maxWidth = std::min(maxSize, m_maxViewportDims[0]);
+    GLint maxHeight = std::min(maxSize, m_maxViewportDims[1]);
     width = clamp(width, 1, maxWidth);
     height = clamp(height, 1, maxHeight);
 
@@ -961,10 +952,10 @@
     m_drawingBuffer->reset(IntSize(width, height));
     restoreStateAfterClear();
 
-    m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, objectOrZero(m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get()));
-    m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, objectOrZero(m_renderbufferBinding.get()));
+    m_context->bindTexture(GL_TEXTURE_2D, objectOrZero(m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get()));
+    m_context->bindRenderbuffer(GL_RENDERBUFFER, objectOrZero(m_renderbufferBinding.get()));
     if (m_framebufferBinding)
-      m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
+        m_context->bindFramebuffer(GL_FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
 }
 
 int WebGLRenderingContext::drawingBufferWidth() const
@@ -977,37 +968,37 @@
     return m_drawingBuffer->size().height();
 }
 
-unsigned int WebGLRenderingContext::sizeInBytes(GC3Denum type)
+unsigned WebGLRenderingContext::sizeInBytes(GLenum type)
 {
     switch (type) {
-    case GraphicsContext3D::BYTE:
-        return sizeof(GC3Dbyte);
-    case GraphicsContext3D::UNSIGNED_BYTE:
-        return sizeof(GC3Dubyte);
-    case GraphicsContext3D::SHORT:
-        return sizeof(GC3Dshort);
-    case GraphicsContext3D::UNSIGNED_SHORT:
-        return sizeof(GC3Dushort);
-    case GraphicsContext3D::INT:
-        return sizeof(GC3Dint);
-    case GraphicsContext3D::UNSIGNED_INT:
-        return sizeof(GC3Duint);
-    case GraphicsContext3D::FLOAT:
-        return sizeof(GC3Dfloat);
+    case GL_BYTE:
+        return sizeof(GLbyte);
+    case GL_UNSIGNED_BYTE:
+        return sizeof(GLubyte);
+    case GL_SHORT:
+        return sizeof(GLshort);
+    case GL_UNSIGNED_SHORT:
+        return sizeof(GLushort);
+    case GL_INT:
+        return sizeof(GLint);
+    case GL_UNSIGNED_INT:
+        return sizeof(GLuint);
+    case GL_FLOAT:
+        return sizeof(GLfloat);
     }
     ASSERT_NOT_REACHED();
     return 0;
 }
 
-void WebGLRenderingContext::activeTexture(GC3Denum texture)
+void WebGLRenderingContext::activeTexture(GLenum texture)
 {
     if (isContextLost())
         return;
-    if (texture - GraphicsContext3D::TEXTURE0 >= m_textureUnits.size()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "activeTexture", "texture unit out of range");
+    if (texture - GL_TEXTURE0 >= m_textureUnits.size()) {
+        synthesizeGLError(GL_INVALID_ENUM, "activeTexture", "texture unit out of range");
         return;
     }
-    m_activeTextureUnit = texture - GraphicsContext3D::TEXTURE0;
+    m_activeTextureUnit = texture - GL_TEXTURE0;
     m_context->activeTexture(texture);
 
     m_drawingBuffer->setActiveTextureUnit(texture);
@@ -1019,14 +1010,14 @@
     if (isContextLost() || !validateWebGLObject("attachShader", program) || !validateWebGLObject("attachShader", shader))
         return;
     if (!program->attachShader(shader)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "attachShader", "shader attachment already has shader");
+        synthesizeGLError(GL_INVALID_OPERATION, "attachShader", "shader attachment already has shader");
         return;
     }
     m_context->attachShader(objectOrZero(program), objectOrZero(shader));
     shader->onAttached();
 }
 
-void WebGLRenderingContext::bindAttribLocation(WebGLProgram* program, GC3Duint index, const String& name)
+void WebGLRenderingContext::bindAttribLocation(WebGLProgram* program, GLuint index, const String& name)
 {
     if (isContextLost() || !validateWebGLObject("bindAttribLocation", program))
         return;
@@ -1035,14 +1026,14 @@
     if (!validateString("bindAttribLocation", name))
         return;
     if (isPrefixReserved(name)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "bindAttribLocation", "reserved prefix");
+        synthesizeGLError(GL_INVALID_OPERATION, "bindAttribLocation", "reserved prefix");
         return;
     }
     if (index >= m_maxVertexAttribs) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bindAttribLocation", "index out of range");
+        synthesizeGLError(GL_INVALID_VALUE, "bindAttribLocation", "index out of range");
         return;
     }
-    m_context->bindAttribLocation(objectOrZero(program), index, name);
+    m_context->bindAttribLocation(objectOrZero(program), index, name.utf8().data());
 }
 
 bool WebGLRenderingContext::checkObjectToBeBound(const char* functionName, WebGLObject* object, bool& deleted)
@@ -1052,7 +1043,7 @@
         return false;
     if (object) {
         if (!object->validate(contextGroup(), this)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "object not from this context");
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "object not from this context");
             return false;
         }
         deleted = !object->object();
@@ -1060,7 +1051,7 @@
     return true;
 }
 
-void WebGLRenderingContext::bindBuffer(GC3Denum target, WebGLBuffer* buffer)
+void WebGLRenderingContext::bindBuffer(GLenum target, WebGLBuffer* buffer)
 {
     bool deleted;
     if (!checkObjectToBeBound("bindBuffer", buffer, deleted))
@@ -1068,15 +1059,15 @@
     if (deleted)
         buffer = 0;
     if (buffer && buffer->getTarget() && buffer->getTarget() != target) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "bindBuffer", "buffers can not be used with multiple targets");
+        synthesizeGLError(GL_INVALID_OPERATION, "bindBuffer", "buffers can not be used with multiple targets");
         return;
     }
-    if (target == GraphicsContext3D::ARRAY_BUFFER)
+    if (target == GL_ARRAY_BUFFER)
         m_boundArrayBuffer = buffer;
-    else if (target == GraphicsContext3D::ELEMENT_ARRAY_BUFFER)
+    else if (target == GL_ELEMENT_ARRAY_BUFFER)
         m_boundVertexArrayObject->setElementArrayBuffer(buffer);
     else {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "bindBuffer", "invalid target");
+        synthesizeGLError(GL_INVALID_ENUM, "bindBuffer", "invalid target");
         return;
     }
 
@@ -1085,15 +1076,15 @@
         buffer->setTarget(target);
 }
 
-void WebGLRenderingContext::bindFramebuffer(GC3Denum target, WebGLFramebuffer* buffer)
+void WebGLRenderingContext::bindFramebuffer(GLenum target, WebGLFramebuffer* buffer)
 {
     bool deleted;
     if (!checkObjectToBeBound("bindFramebuffer", buffer, deleted))
         return;
     if (deleted)
         buffer = 0;
-    if (target != GraphicsContext3D::FRAMEBUFFER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "bindFramebuffer", "invalid target");
+    if (target != GL_FRAMEBUFFER) {
+        synthesizeGLError(GL_INVALID_ENUM, "bindFramebuffer", "invalid target");
         return;
     }
     m_framebufferBinding = buffer;
@@ -1108,15 +1099,15 @@
     applyStencilTest();
 }
 
-void WebGLRenderingContext::bindRenderbuffer(GC3Denum target, WebGLRenderbuffer* renderBuffer)
+void WebGLRenderingContext::bindRenderbuffer(GLenum target, WebGLRenderbuffer* renderBuffer)
 {
     bool deleted;
     if (!checkObjectToBeBound("bindRenderbuffer", renderBuffer, deleted))
         return;
     if (deleted)
         renderBuffer = 0;
-    if (target != GraphicsContext3D::RENDERBUFFER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "bindRenderbuffer", "invalid target");
+    if (target != GL_RENDERBUFFER) {
+        synthesizeGLError(GL_INVALID_ENUM, "bindRenderbuffer", "invalid target");
         return;
     }
     m_renderbufferBinding = renderBuffer;
@@ -1125,7 +1116,7 @@
         renderBuffer->setHasEverBeenBound();
 }
 
-void WebGLRenderingContext::bindTexture(GC3Denum target, WebGLTexture* texture)
+void WebGLRenderingContext::bindTexture(GLenum target, WebGLTexture* texture)
 {
     bool deleted;
     if (!checkObjectToBeBound("bindTexture", texture, deleted))
@@ -1133,22 +1124,22 @@
     if (deleted)
         texture = 0;
     if (texture && texture->getTarget() && texture->getTarget() != target) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "bindTexture", "textures can not be used with multiple targets");
+        synthesizeGLError(GL_INVALID_OPERATION, "bindTexture", "textures can not be used with multiple targets");
         return;
     }
-    GC3Dint maxLevel = 0;
-    if (target == GraphicsContext3D::TEXTURE_2D) {
+    GLint maxLevel = 0;
+    if (target == GL_TEXTURE_2D) {
         m_textureUnits[m_activeTextureUnit].m_texture2DBinding = texture;
         maxLevel = m_maxTextureLevel;
 
         if (!m_activeTextureUnit)
             m_drawingBuffer->setTexture2DBinding(objectOrZero(texture));
 
-    } else if (target == GraphicsContext3D::TEXTURE_CUBE_MAP) {
+    } else if (target == GL_TEXTURE_CUBE_MAP) {
         m_textureUnits[m_activeTextureUnit].m_textureCubeMapBinding = texture;
         maxLevel = m_maxCubeMapTextureLevel;
     } else {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "bindTexture", "invalid target");
+        synthesizeGLError(GL_INVALID_ENUM, "bindTexture", "invalid target");
         return;
     }
 
@@ -1174,21 +1165,21 @@
 
 }
 
-void WebGLRenderingContext::blendColor(GC3Dfloat red, GC3Dfloat green, GC3Dfloat blue, GC3Dfloat alpha)
+void WebGLRenderingContext::blendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
 {
     if (isContextLost())
         return;
     m_context->blendColor(red, green, blue, alpha);
 }
 
-void WebGLRenderingContext::blendEquation(GC3Denum mode)
+void WebGLRenderingContext::blendEquation(GLenum mode)
 {
     if (isContextLost() || !validateBlendEquation("blendEquation", mode))
         return;
     m_context->blendEquation(mode);
 }
 
-void WebGLRenderingContext::blendEquationSeparate(GC3Denum modeRGB, GC3Denum modeAlpha)
+void WebGLRenderingContext::blendEquationSeparate(GLenum modeRGB, GLenum modeAlpha)
 {
     if (isContextLost() || !validateBlendEquation("blendEquationSeparate", modeRGB) || !validateBlendEquation("blendEquationSeparate", modeAlpha))
         return;
@@ -1196,14 +1187,14 @@
 }
 
 
-void WebGLRenderingContext::blendFunc(GC3Denum sfactor, GC3Denum dfactor)
+void WebGLRenderingContext::blendFunc(GLenum sfactor, GLenum dfactor)
 {
     if (isContextLost() || !validateBlendFuncFactors("blendFunc", sfactor, dfactor))
         return;
     m_context->blendFunc(sfactor, dfactor);
 }
 
-void WebGLRenderingContext::blendFuncSeparate(GC3Denum srcRGB, GC3Denum dstRGB, GC3Denum srcAlpha, GC3Denum dstAlpha)
+void WebGLRenderingContext::blendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
 {
     // Note: Alpha does not have the same restrictions as RGB.
     if (isContextLost() || !validateBlendFuncFactors("blendFuncSeparate", srcRGB, dstRGB))
@@ -1211,7 +1202,7 @@
     m_context->blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
 }
 
-void WebGLRenderingContext::bufferData(GC3Denum target, long long size, GC3Denum usage)
+void WebGLRenderingContext::bufferData(GLenum target, long long size, GLenum usage)
 {
     if (isContextLost())
         return;
@@ -1219,18 +1210,18 @@
     if (!buffer)
         return;
     if (size < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferData", "size < 0");
+        synthesizeGLError(GL_INVALID_VALUE, "bufferData", "size < 0");
         return;
     }
     if (!size) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferData", "size == 0");
+        synthesizeGLError(GL_INVALID_VALUE, "bufferData", "size == 0");
         return;
     }
 
-    m_context->bufferData(target, static_cast<GC3Dsizeiptr>(size), usage);
+    m_context->bufferData(target, static_cast<GLsizeiptr>(size), 0, usage);
 }
 
-void WebGLRenderingContext::bufferData(GC3Denum target, ArrayBuffer* data, GC3Denum usage)
+void WebGLRenderingContext::bufferData(GLenum target, ArrayBuffer* data, GLenum usage)
 {
     if (isContextLost())
         return;
@@ -1238,13 +1229,13 @@
     if (!buffer)
         return;
     if (!data) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferData", "no data");
+        synthesizeGLError(GL_INVALID_VALUE, "bufferData", "no data");
         return;
     }
     m_context->bufferData(target, data->byteLength(), data->data(), usage);
 }
 
-void WebGLRenderingContext::bufferData(GC3Denum target, ArrayBufferView* data, GC3Denum usage)
+void WebGLRenderingContext::bufferData(GLenum target, ArrayBufferView* data, GLenum usage)
 {
     if (isContextLost())
         return;
@@ -1252,60 +1243,60 @@
     if (!buffer)
         return;
     if (!data) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferData", "no data");
+        synthesizeGLError(GL_INVALID_VALUE, "bufferData", "no data");
         return;
     }
 
     m_context->bufferData(target, data->byteLength(), data->baseAddress(), usage);
 }
 
-void WebGLRenderingContext::bufferSubData(GC3Denum target, long long offset, ArrayBuffer* data)
+void WebGLRenderingContext::bufferSubData(GLenum target, long long offset, ArrayBuffer* data)
 {
     if (isContextLost())
         return;
-    WebGLBuffer* buffer = validateBufferDataParameters("bufferSubData", target, GraphicsContext3D::STATIC_DRAW);
+    WebGLBuffer* buffer = validateBufferDataParameters("bufferSubData", target, GL_STATIC_DRAW);
     if (!buffer)
         return;
     if (offset < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferSubData", "offset < 0");
+        synthesizeGLError(GL_INVALID_VALUE, "bufferSubData", "offset < 0");
         return;
     }
     if (!data)
         return;
 
-    m_context->bufferSubData(target, static_cast<GC3Dintptr>(offset), data->byteLength(), data->data());
+    m_context->bufferSubData(target, static_cast<GLintptr>(offset), data->byteLength(), data->data());
 }
 
-void WebGLRenderingContext::bufferSubData(GC3Denum target, long long offset, ArrayBufferView* data)
+void WebGLRenderingContext::bufferSubData(GLenum target, long long offset, ArrayBufferView* data)
 {
     if (isContextLost())
         return;
-    WebGLBuffer* buffer = validateBufferDataParameters("bufferSubData", target, GraphicsContext3D::STATIC_DRAW);
+    WebGLBuffer* buffer = validateBufferDataParameters("bufferSubData", target, GL_STATIC_DRAW);
     if (!buffer)
         return;
     if (offset < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferSubData", "offset < 0");
+        synthesizeGLError(GL_INVALID_VALUE, "bufferSubData", "offset < 0");
         return;
     }
     if (!data)
         return;
 
-    m_context->bufferSubData(target, static_cast<GC3Dintptr>(offset), data->byteLength(), data->baseAddress());
+    m_context->bufferSubData(target, static_cast<GLintptr>(offset), data->byteLength(), data->baseAddress());
 }
 
-GC3Denum WebGLRenderingContext::checkFramebufferStatus(GC3Denum target)
+GLenum WebGLRenderingContext::checkFramebufferStatus(GLenum target)
 {
     if (isContextLost())
-        return GraphicsContext3D::FRAMEBUFFER_UNSUPPORTED;
-    if (target != GraphicsContext3D::FRAMEBUFFER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "checkFramebufferStatus", "invalid target");
+        return GL_FRAMEBUFFER_UNSUPPORTED;
+    if (target != GL_FRAMEBUFFER) {
+        synthesizeGLError(GL_INVALID_ENUM, "checkFramebufferStatus", "invalid target");
         return 0;
     }
     if (!m_framebufferBinding || !m_framebufferBinding->object())
-        return GraphicsContext3D::FRAMEBUFFER_COMPLETE;
+        return GL_FRAMEBUFFER_COMPLETE;
     const char* reason = "framebuffer incomplete";
-    GC3Denum result = m_framebufferBinding->checkStatus(&reason);
-    if (result != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
+    GLenum result = m_framebufferBinding->checkStatus(&reason);
+    if (result != GL_FRAMEBUFFER_COMPLETE) {
         emitGLWarning("checkFramebufferStatus", reason);
         return result;
     }
@@ -1313,17 +1304,17 @@
     return result;
 }
 
-void WebGLRenderingContext::clear(GC3Dbitfield mask)
+void WebGLRenderingContext::clear(GLbitfield mask)
 {
     if (isContextLost())
         return;
-    if (mask & ~(GraphicsContext3D::COLOR_BUFFER_BIT | GraphicsContext3D::DEPTH_BUFFER_BIT | GraphicsContext3D::STENCIL_BUFFER_BIT)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "clear", "invalid mask");
+    if (mask & ~(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)) {
+        synthesizeGLError(GL_INVALID_VALUE, "clear", "invalid mask");
         return;
     }
     const char* reason = "framebuffer incomplete";
-    if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, "clear", reason);
+    if (m_framebufferBinding && !m_framebufferBinding->onAccess(m_context.get(), &reason)) {
+        synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, "clear", reason);
         return;
     }
     if (!clearIfComposited(mask))
@@ -1331,7 +1322,7 @@
     markContextChanged();
 }
 
-void WebGLRenderingContext::clearColor(GC3Dfloat r, GC3Dfloat g, GC3Dfloat b, GC3Dfloat a)
+void WebGLRenderingContext::clearColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a)
 {
     if (isContextLost())
         return;
@@ -1350,7 +1341,7 @@
     m_context->clearColor(r, g, b, a);
 }
 
-void WebGLRenderingContext::clearDepth(GC3Dfloat depth)
+void WebGLRenderingContext::clearDepth(GLfloat depth)
 {
     if (isContextLost())
         return;
@@ -1358,7 +1349,7 @@
     m_context->clearDepth(depth);
 }
 
-void WebGLRenderingContext::clearStencil(GC3Dint s)
+void WebGLRenderingContext::clearStencil(GLint s)
 {
     if (isContextLost())
         return;
@@ -1366,7 +1357,7 @@
     m_context->clearStencil(s);
 }
 
-void WebGLRenderingContext::colorMask(GC3Dboolean red, GC3Dboolean green, GC3Dboolean blue, GC3Dboolean alpha)
+void WebGLRenderingContext::colorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
 {
     if (isContextLost())
         return;
@@ -1384,8 +1375,7 @@
     m_context->compileShader(objectOrZero(shader));
 }
 
-void WebGLRenderingContext::compressedTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width,
-                                                 GC3Dsizei height, GC3Dint border, ArrayBufferView* data)
+void WebGLRenderingContext::compressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, ArrayBufferView* data)
 {
     if (isContextLost())
         return;
@@ -1393,11 +1383,11 @@
         return;
 
     if (!validateCompressedTexFormat(internalformat)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "compressedTexImage2D", "invalid internalformat");
+        synthesizeGLError(GL_INVALID_ENUM, "compressedTexImage2D", "invalid internalformat");
         return;
     }
     if (border) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "compressedTexImage2D", "border not 0");
+        synthesizeGLError(GL_INVALID_VALUE, "compressedTexImage2D", "border not 0");
         return;
     }
     if (!validateCompressedTexDimensions("compressedTexImage2D", NotTexSubImage2D, target, level, width, height, internalformat))
@@ -1410,24 +1400,23 @@
         return;
     if (!isGLES2NPOTStrict()) {
         if (level && WebGLTexture::isNPOT(width, height)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "compressedTexImage2D", "level > 0 not power of 2");
+            synthesizeGLError(GL_INVALID_VALUE, "compressedTexImage2D", "level > 0 not power of 2");
             return;
         }
     }
-    graphicsContext3D()->compressedTexImage2D(target, level, internalformat, width, height,
+    m_context->compressedTexImage2D(target, level, internalformat, width, height,
                                               border, data->byteLength(), data->baseAddress());
-    tex->setLevelInfo(target, level, internalformat, width, height, GraphicsContext3D::UNSIGNED_BYTE);
+    tex->setLevelInfo(target, level, internalformat, width, height, GL_UNSIGNED_BYTE);
 }
 
-void WebGLRenderingContext::compressedTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-                                                    GC3Dsizei width, GC3Dsizei height, GC3Denum format, ArrayBufferView* data)
+void WebGLRenderingContext::compressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, ArrayBufferView* data)
 {
     if (isContextLost())
         return;
     if (!validateTexFuncLevel("compressedTexSubImage2D", target, level))
         return;
     if (!validateCompressedTexFormat(format)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "compressedTexSubImage2D", "invalid format");
+        synthesizeGLError(GL_INVALID_ENUM, "compressedTexSubImage2D", "invalid format");
         return;
     }
     if (!validateCompressedTexFuncData("compressedTexSubImage2D", width, height, format, data))
@@ -1438,31 +1427,31 @@
         return;
 
     if (format != tex->getInternalFormat(target, level)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "compressedTexSubImage2D", "format does not match texture format");
+        synthesizeGLError(GL_INVALID_OPERATION, "compressedTexSubImage2D", "format does not match texture format");
         return;
     }
 
     if (!validateCompressedTexSubDimensions("compressedTexSubImage2D", target, level, xoffset, yoffset, width, height, format, tex))
         return;
 
-    graphicsContext3D()->compressedTexSubImage2D(target, level, xoffset, yoffset,
+    m_context->compressedTexSubImage2D(target, level, xoffset, yoffset,
                                                  width, height, format, data->byteLength(), data->baseAddress());
 }
 
-bool WebGLRenderingContext::validateSettableTexFormat(const char* functionName, GC3Denum format)
+bool WebGLRenderingContext::validateSettableTexFormat(const char* functionName, GLenum format)
 {
-    if (GraphicsContext3D::getClearBitsByFormat(format) & (GraphicsContext3D::DEPTH_BUFFER_BIT | GraphicsContext3D::STENCIL_BUFFER_BIT)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "format can not be set, only rendered to");
+    if (WebGLImageConversion::getClearBitsByFormat(format) & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)) {
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "format can not be set, only rendered to");
         return false;
     }
     return true;
 }
 
-void WebGLRenderingContext::copyTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Dint border)
+void WebGLRenderingContext::copyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
 {
     if (isContextLost())
         return;
-    if (!validateTexFuncParameters("copyTexImage2D", NotTexSubImage2D, target, level, internalformat, width, height, border, internalformat, GraphicsContext3D::UNSIGNED_BYTE))
+    if (!validateTexFuncParameters("copyTexImage2D", NotTexSubImage2D, target, level, internalformat, width, height, border, internalformat, GL_UNSIGNED_BYTE))
         return;
     if (!validateSettableTexFormat("copyTexImage2D", internalformat))
         return;
@@ -1470,26 +1459,26 @@
     if (!tex)
         return;
     if (!isTexInternalFormatColorBufferCombinationValid(internalformat, boundFramebufferColorFormat())) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "copyTexImage2D", "framebuffer is incompatible format");
+        synthesizeGLError(GL_INVALID_OPERATION, "copyTexImage2D", "framebuffer is incompatible format");
         return;
     }
     if (!isGLES2NPOTStrict() && level && WebGLTexture::isNPOT(width, height)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "copyTexImage2D", "level > 0 not power of 2");
+        synthesizeGLError(GL_INVALID_VALUE, "copyTexImage2D", "level > 0 not power of 2");
         return;
     }
     const char* reason = "framebuffer incomplete";
-    if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, "copyTexImage2D", reason);
+    if (m_framebufferBinding && !m_framebufferBinding->onAccess(m_context.get(), &reason)) {
+        synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, "copyTexImage2D", reason);
         return;
     }
     clearIfComposited();
     ScopedDrawingBufferBinder binder(m_drawingBuffer.get(), m_framebufferBinding.get());
     m_context->copyTexImage2D(target, level, internalformat, x, y, width, height, border);
     // FIXME: if the framebuffer is not complete, none of the below should be executed.
-    tex->setLevelInfo(target, level, internalformat, width, height, GraphicsContext3D::UNSIGNED_BYTE);
+    tex->setLevelInfo(target, level, internalformat, width, height, GL_UNSIGNED_BYTE);
 }
 
-void WebGLRenderingContext::copyTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height)
+void WebGLRenderingContext::copyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
 {
     if (isContextLost())
         return;
@@ -1501,24 +1490,28 @@
     if (!validateSize("copyTexSubImage2D", xoffset, yoffset) || !validateSize("copyTexSubImage2D", width, height))
         return;
     // Before checking if it is in the range, check if overflow happens first.
-    if (xoffset + width < 0 || yoffset + height < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "copyTexSubImage2D", "bad dimensions");
+    Checked<GLint, RecordOverflow> maxX = xoffset;
+    maxX += width;
+    Checked<GLint, RecordOverflow> maxY = yoffset;
+    maxY += height;
+    if (maxX.hasOverflowed() || maxY.hasOverflowed()) {
+        synthesizeGLError(GL_INVALID_VALUE, "copyTexSubImage2D", "bad dimensions");
         return;
     }
-    if (xoffset + width > tex->getWidth(target, level) || yoffset + height > tex->getHeight(target, level)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "copyTexSubImage2D", "rectangle out of range");
+    if (maxX.unsafeGet() > tex->getWidth(target, level) || maxY.unsafeGet() > tex->getHeight(target, level)) {
+        synthesizeGLError(GL_INVALID_VALUE, "copyTexSubImage2D", "rectangle out of range");
         return;
     }
-    GC3Denum internalformat = tex->getInternalFormat(target, level);
+    GLenum internalformat = tex->getInternalFormat(target, level);
     if (!validateSettableTexFormat("copyTexSubImage2D", internalformat))
         return;
     if (!isTexInternalFormatColorBufferCombinationValid(internalformat, boundFramebufferColorFormat())) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "copyTexSubImage2D", "framebuffer is incompatible format");
+        synthesizeGLError(GL_INVALID_OPERATION, "copyTexSubImage2D", "framebuffer is incompatible format");
         return;
     }
     const char* reason = "framebuffer incomplete";
-    if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, "copyTexSubImage2D", reason);
+    if (m_framebufferBinding && !m_framebufferBinding->onAccess(m_context.get(), &reason)) {
+        synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, "copyTexSubImage2D", reason);
         return;
     }
     clearIfComposited();
@@ -1571,7 +1564,7 @@
     return o;
 }
 
-WebGLRenderbuffer* WebGLRenderingContext::ensureEmulatedStencilBuffer(GC3Denum target, WebGLRenderbuffer* renderbuffer)
+WebGLRenderbuffer* WebGLRenderingContext::ensureEmulatedStencilBuffer(GLenum target, WebGLRenderbuffer* renderbuffer)
 {
     if (isContextLost())
         return 0;
@@ -1583,12 +1576,12 @@
     return renderbuffer->emulatedStencilBuffer();
 }
 
-PassRefPtr<WebGLShader> WebGLRenderingContext::createShader(GC3Denum type)
+PassRefPtr<WebGLShader> WebGLRenderingContext::createShader(GLenum type)
 {
     if (isContextLost())
         return 0;
-    if (type != GraphicsContext3D::VERTEX_SHADER && type != GraphicsContext3D::FRAGMENT_SHADER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "createShader", "invalid shader type");
+    if (type != GL_VERTEX_SHADER && type != GL_FRAGMENT_SHADER) {
+        synthesizeGLError(GL_INVALID_ENUM, "createShader", "invalid shader type");
         return 0;
     }
 
@@ -1597,17 +1590,17 @@
     return o;
 }
 
-void WebGLRenderingContext::cullFace(GC3Denum mode)
+void WebGLRenderingContext::cullFace(GLenum mode)
 {
     if (isContextLost())
         return;
     switch (mode) {
-    case GraphicsContext3D::FRONT_AND_BACK:
-    case GraphicsContext3D::FRONT:
-    case GraphicsContext3D::BACK:
+    case GL_FRONT_AND_BACK:
+    case GL_FRONT:
+    case GL_BACK:
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "cullFace", "invalid mode");
+        synthesizeGLError(GL_INVALID_ENUM, "cullFace", "invalid mode");
         return;
     }
     m_context->cullFace(mode);
@@ -1618,13 +1611,14 @@
     if (isContextLost() || !object)
         return false;
     if (!object->validate(contextGroup(), this)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "delete", "object does not belong to this context");
+        synthesizeGLError(GL_INVALID_OPERATION, "delete", "object does not belong to this context");
         return false;
     }
-    if (object->object())
+    if (object->object()) {
         // We need to pass in context here because we want
         // things in this context unbound.
-        object->deleteObject(graphicsContext3D());
+        object->deleteObject(m_context.get());
+    }
     return true;
 }
 
@@ -1699,7 +1693,7 @@
     }
 }
 
-void WebGLRenderingContext::depthFunc(GC3Denum func)
+void WebGLRenderingContext::depthFunc(GLenum func)
 {
     if (isContextLost())
         return;
@@ -1708,7 +1702,7 @@
     m_context->depthFunc(func);
 }
 
-void WebGLRenderingContext::depthMask(GC3Dboolean flag)
+void WebGLRenderingContext::depthMask(GLboolean flag)
 {
     if (isContextLost())
         return;
@@ -1716,12 +1710,12 @@
     m_context->depthMask(flag);
 }
 
-void WebGLRenderingContext::depthRange(GC3Dfloat zNear, GC3Dfloat zFar)
+void WebGLRenderingContext::depthRange(GLfloat zNear, GLfloat zFar)
 {
     if (isContextLost())
         return;
     if (zNear > zFar) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "depthRange", "zNear > zFar");
+        synthesizeGLError(GL_INVALID_OPERATION, "depthRange", "zNear > zFar");
         return;
     }
     m_context->depthRange(zNear, zFar);
@@ -1732,35 +1726,35 @@
     if (isContextLost() || !validateWebGLObject("detachShader", program) || !validateWebGLObject("detachShader", shader))
         return;
     if (!program->detachShader(shader)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "detachShader", "shader not attached");
+        synthesizeGLError(GL_INVALID_OPERATION, "detachShader", "shader not attached");
         return;
     }
     m_context->detachShader(objectOrZero(program), objectOrZero(shader));
-    shader->onDetached(graphicsContext3D());
+    shader->onDetached(m_context.get());
 }
 
-void WebGLRenderingContext::disable(GC3Denum cap)
+void WebGLRenderingContext::disable(GLenum cap)
 {
     if (isContextLost() || !validateCapability("disable", cap))
         return;
-    if (cap == GraphicsContext3D::STENCIL_TEST) {
+    if (cap == GL_STENCIL_TEST) {
         m_stencilEnabled = false;
         applyStencilTest();
         return;
     }
-    if (cap == GraphicsContext3D::SCISSOR_TEST) {
+    if (cap == GL_SCISSOR_TEST) {
         m_scissorEnabled = false;
         m_drawingBuffer->setScissorEnabled(m_scissorEnabled);
     }
     m_context->disable(cap);
 }
 
-void WebGLRenderingContext::disableVertexAttribArray(GC3Duint index)
+void WebGLRenderingContext::disableVertexAttribArray(GLuint index)
 {
     if (isContextLost())
         return;
     if (index >= m_maxVertexAttribs) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "disableVertexAttribArray", "index out of range");
+        synthesizeGLError(GL_INVALID_VALUE, "disableVertexAttribArray", "index out of range");
         return;
     }
 
@@ -1775,17 +1769,21 @@
     m_context->disableVertexAttribArray(index);
 }
 
-bool WebGLRenderingContext::validateRenderingState()
+bool WebGLRenderingContext::validateRenderingState(const char* functionName)
 {
-    if (!m_currentProgram)
+    if (!m_currentProgram) {
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "no valid shader program in use");
         return false;
+    }
 
     // Look in each enabled vertex attrib and check if they've been bound to a buffer.
     for (unsigned i = 0; i < m_onePlusMaxEnabledAttribIndex; ++i) {
         const WebGLVertexArrayObjectOES::VertexAttribState& state = m_boundVertexArrayObject->getVertexAttribState(i);
         if (state.enabled
-            && (!state.bufferBinding || !state.bufferBinding->object()))
+            && (!state.bufferBinding || !state.bufferBinding->object())) {
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, String::format("attribute %d is enabled but has no buffer bound", i).utf8().data());
             return false;
+        }
     }
 
     return true;
@@ -1794,17 +1792,17 @@
 bool WebGLRenderingContext::validateWebGLObject(const char* functionName, WebGLObject* object)
 {
     if (!object || !object->object()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no object or object deleted");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no object or object deleted");
         return false;
     }
     if (!object->validate(contextGroup(), this)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "object does not belong to this context");
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "object does not belong to this context");
         return false;
     }
     return true;
 }
 
-void WebGLRenderingContext::drawArrays(GC3Denum mode, GC3Dint first, GC3Dsizei count)
+void WebGLRenderingContext::drawArrays(GLenum mode, GLint first, GLsizei count)
 {
     if (!validateDrawArrays("drawArrays", mode, first, count))
         return;
@@ -1817,7 +1815,7 @@
     markContextChanged();
 }
 
-void WebGLRenderingContext::drawElements(GC3Denum mode, GC3Dsizei count, GC3Denum type, long long offset)
+void WebGLRenderingContext::drawElements(GLenum mode, GLsizei count, GLenum type, long long offset)
 {
     if (!validateDrawElements("drawElements", mode, count, type, offset))
         return;
@@ -1825,12 +1823,12 @@
     clearIfComposited();
 
     handleTextureCompleteness("drawElements", true);
-    m_context->drawElements(mode, count, type, static_cast<GC3Dintptr>(offset));
+    m_context->drawElements(mode, count, type, static_cast<GLintptr>(offset));
     handleTextureCompleteness("drawElements", false);
     markContextChanged();
 }
 
-void WebGLRenderingContext::drawArraysInstancedANGLE(GC3Denum mode, GC3Dint first, GC3Dsizei count, GC3Dsizei primcount)
+void WebGLRenderingContext::drawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
 {
     if (!validateDrawArrays("drawArraysInstancedANGLE", mode, first, count))
         return;
@@ -1841,12 +1839,12 @@
     clearIfComposited();
 
     handleTextureCompleteness("drawArraysInstancedANGLE", true);
-    m_context->extensions()->drawArraysInstancedANGLE(mode, first, count, primcount);
+    m_context->drawArraysInstancedANGLE(mode, first, count, primcount);
     handleTextureCompleteness("drawArraysInstancedANGLE", false);
     markContextChanged();
 }
 
-void WebGLRenderingContext::drawElementsInstancedANGLE(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset, GC3Dsizei primcount)
+void WebGLRenderingContext::drawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, GLintptr offset, GLsizei primcount)
 {
     if (!validateDrawElements("drawElementsInstancedANGLE", mode, count, type, offset))
         return;
@@ -1857,33 +1855,33 @@
     clearIfComposited();
 
     handleTextureCompleteness("drawElementsInstancedANGLE", true);
-    m_context->extensions()->drawElementsInstancedANGLE(mode, count, type, static_cast<GC3Dintptr>(offset), primcount);
+    m_context->drawElementsInstancedANGLE(mode, count, type, static_cast<GLintptr>(offset), primcount);
     handleTextureCompleteness("drawElementsInstancedANGLE", false);
     markContextChanged();
 }
 
-void WebGLRenderingContext::enable(GC3Denum cap)
+void WebGLRenderingContext::enable(GLenum cap)
 {
     if (isContextLost() || !validateCapability("enable", cap))
         return;
-    if (cap == GraphicsContext3D::STENCIL_TEST) {
+    if (cap == GL_STENCIL_TEST) {
         m_stencilEnabled = true;
         applyStencilTest();
         return;
     }
-    if (cap == GraphicsContext3D::SCISSOR_TEST) {
+    if (cap == GL_SCISSOR_TEST) {
         m_scissorEnabled = true;
         m_drawingBuffer->setScissorEnabled(m_scissorEnabled);
     }
     m_context->enable(cap);
 }
 
-void WebGLRenderingContext::enableVertexAttribArray(GC3Duint index)
+void WebGLRenderingContext::enableVertexAttribArray(GLuint index)
 {
     if (isContextLost())
         return;
     if (index >= m_maxVertexAttribs) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "enableVertexAttribArray", "index out of range");
+        synthesizeGLError(GL_INVALID_VALUE, "enableVertexAttribArray", "index out of range");
         return;
     }
 
@@ -1909,39 +1907,39 @@
     m_context->flush();
 }
 
-void WebGLRenderingContext::framebufferRenderbuffer(GC3Denum target, GC3Denum attachment, GC3Denum renderbuffertarget, WebGLRenderbuffer* buffer)
+void WebGLRenderingContext::framebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, WebGLRenderbuffer* buffer)
 {
     if (isContextLost() || !validateFramebufferFuncParameters("framebufferRenderbuffer", target, attachment))
         return;
-    if (renderbuffertarget != GraphicsContext3D::RENDERBUFFER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "framebufferRenderbuffer", "invalid target");
+    if (renderbuffertarget != GL_RENDERBUFFER) {
+        synthesizeGLError(GL_INVALID_ENUM, "framebufferRenderbuffer", "invalid target");
         return;
     }
     if (buffer && !buffer->validate(contextGroup(), this)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "framebufferRenderbuffer", "no buffer or buffer not from this context");
+        synthesizeGLError(GL_INVALID_OPERATION, "framebufferRenderbuffer", "no buffer or buffer not from this context");
         return;
     }
     // Don't allow the default framebuffer to be mutated; all current
     // implementations use an FBO internally in place of the default
     // FBO.
     if (!m_framebufferBinding || !m_framebufferBinding->object()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "framebufferRenderbuffer", "no framebuffer bound");
+        synthesizeGLError(GL_INVALID_OPERATION, "framebufferRenderbuffer", "no framebuffer bound");
         return;
     }
     Platform3DObject bufferObject = objectOrZero(buffer);
     switch (attachment) {
-    case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
+    case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
         if (isDepthStencilSupported() || !buffer) {
-            m_context->framebufferRenderbuffer(target, GraphicsContext3D::DEPTH_ATTACHMENT, renderbuffertarget, bufferObject);
-            m_context->framebufferRenderbuffer(target, GraphicsContext3D::STENCIL_ATTACHMENT, renderbuffertarget, bufferObject);
+            m_context->framebufferRenderbuffer(target, GL_DEPTH_ATTACHMENT, renderbuffertarget, bufferObject);
+            m_context->framebufferRenderbuffer(target, GL_STENCIL_ATTACHMENT, renderbuffertarget, bufferObject);
         } else {
             WebGLRenderbuffer* emulatedStencilBuffer = ensureEmulatedStencilBuffer(renderbuffertarget, buffer);
             if (!emulatedStencilBuffer) {
-                synthesizeGLError(GraphicsContext3D::OUT_OF_MEMORY, "framebufferRenderbuffer", "out of memory");
+                synthesizeGLError(GL_OUT_OF_MEMORY, "framebufferRenderbuffer", "out of memory");
                 return;
             }
-            m_context->framebufferRenderbuffer(target, GraphicsContext3D::DEPTH_ATTACHMENT, renderbuffertarget, bufferObject);
-            m_context->framebufferRenderbuffer(target, GraphicsContext3D::STENCIL_ATTACHMENT, renderbuffertarget, objectOrZero(emulatedStencilBuffer));
+            m_context->framebufferRenderbuffer(target, GL_DEPTH_ATTACHMENT, renderbuffertarget, bufferObject);
+            m_context->framebufferRenderbuffer(target, GL_STENCIL_ATTACHMENT, renderbuffertarget, objectOrZero(emulatedStencilBuffer));
         }
         break;
     default:
@@ -1951,35 +1949,35 @@
     applyStencilTest();
 }
 
-void WebGLRenderingContext::framebufferTexture2D(GC3Denum target, GC3Denum attachment, GC3Denum textarget, WebGLTexture* texture, GC3Dint level)
+void WebGLRenderingContext::framebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, WebGLTexture* texture, GLint level)
 {
     if (isContextLost() || !validateFramebufferFuncParameters("framebufferTexture2D", target, attachment))
         return;
     if (level) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "framebufferTexture2D", "level not 0");
+        synthesizeGLError(GL_INVALID_VALUE, "framebufferTexture2D", "level not 0");
         return;
     }
     if (texture && !texture->validate(contextGroup(), this)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "framebufferTexture2D", "no texture or texture not from this context");
+        synthesizeGLError(GL_INVALID_OPERATION, "framebufferTexture2D", "no texture or texture not from this context");
         return;
     }
     // Don't allow the default framebuffer to be mutated; all current
     // implementations use an FBO internally in place of the default
     // FBO.
     if (!m_framebufferBinding || !m_framebufferBinding->object()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "framebufferTexture2D", "no framebuffer bound");
+        synthesizeGLError(GL_INVALID_OPERATION, "framebufferTexture2D", "no framebuffer bound");
         return;
     }
     Platform3DObject textureObject = objectOrZero(texture);
     switch (attachment) {
-    case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
-        m_context->framebufferTexture2D(target, GraphicsContext3D::DEPTH_ATTACHMENT, textarget, textureObject, level);
-        m_context->framebufferTexture2D(target, GraphicsContext3D::STENCIL_ATTACHMENT, textarget, textureObject, level);
+    case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
+        m_context->framebufferTexture2D(target, GL_DEPTH_ATTACHMENT, textarget, textureObject, level);
+        m_context->framebufferTexture2D(target, GL_STENCIL_ATTACHMENT, textarget, textureObject, level);
         break;
-    case GraphicsContext3D::DEPTH_ATTACHMENT:
+    case GL_DEPTH_ATTACHMENT:
         m_context->framebufferTexture2D(target, attachment, textarget, textureObject, level);
         break;
-    case GraphicsContext3D::STENCIL_ATTACHMENT:
+    case GL_STENCIL_ATTACHMENT:
         m_context->framebufferTexture2D(target, attachment, textarget, textureObject, level);
         break;
     default:
@@ -1989,22 +1987,22 @@
     applyStencilTest();
 }
 
-void WebGLRenderingContext::frontFace(GC3Denum mode)
+void WebGLRenderingContext::frontFace(GLenum mode)
 {
     if (isContextLost())
         return;
     switch (mode) {
-    case GraphicsContext3D::CW:
-    case GraphicsContext3D::CCW:
+    case GL_CW:
+    case GL_CCW:
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "frontFace", "invalid mode");
+        synthesizeGLError(GL_INVALID_ENUM, "frontFace", "invalid mode");
         return;
     }
     m_context->frontFace(mode);
 }
 
-void WebGLRenderingContext::generateMipmap(GC3Denum target)
+void WebGLRenderingContext::generateMipmap(GLenum target)
 {
     if (isContextLost())
         return;
@@ -2012,7 +2010,7 @@
     if (!tex)
         return;
     if (!tex->canGenerateMipmaps()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "generateMipmap", "level 0 not power of 2 or not all the same size");
+        synthesizeGLError(GL_INVALID_OPERATION, "generateMipmap", "level 0 not power of 2 or not all the same size");
         return;
     }
     if (!validateSettableTexFormat("generateMipmap", tex->getInternalFormat(target, 0)))
@@ -2022,34 +2020,34 @@
     // on Mac.  Remove the hack once this driver bug is fixed.
 #if OS(MACOSX)
     bool needToResetMinFilter = false;
-    if (tex->getMinFilter() != GraphicsContext3D::NEAREST_MIPMAP_LINEAR) {
-        m_context->texParameteri(target, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::NEAREST_MIPMAP_LINEAR);
+    if (tex->getMinFilter() != GL_NEAREST_MIPMAP_LINEAR) {
+        m_context->texParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
         needToResetMinFilter = true;
     }
 #endif
     m_context->generateMipmap(target);
 #if OS(MACOSX)
     if (needToResetMinFilter)
-        m_context->texParameteri(target, GraphicsContext3D::TEXTURE_MIN_FILTER, tex->getMinFilter());
+        m_context->texParameteri(target, GL_TEXTURE_MIN_FILTER, tex->getMinFilter());
 #endif
     tex->generateMipmapLevelInfo();
 }
 
-PassRefPtr<WebGLActiveInfo> WebGLRenderingContext::getActiveAttrib(WebGLProgram* program, GC3Duint index)
+PassRefPtr<WebGLActiveInfo> WebGLRenderingContext::getActiveAttrib(WebGLProgram* program, GLuint index)
 {
     if (isContextLost() || !validateWebGLObject("getActiveAttrib", program))
         return 0;
-    ActiveInfo info;
+    blink::WebGraphicsContext3D::ActiveInfo info;
     if (!m_context->getActiveAttrib(objectOrZero(program), index, info))
         return 0;
     return WebGLActiveInfo::create(info.name, info.type, info.size);
 }
 
-PassRefPtr<WebGLActiveInfo> WebGLRenderingContext::getActiveUniform(WebGLProgram* program, GC3Duint index)
+PassRefPtr<WebGLActiveInfo> WebGLRenderingContext::getActiveUniform(WebGLProgram* program, GLuint index)
 {
     if (isContextLost() || !validateWebGLObject("getActiveUniform", program))
         return 0;
-    ActiveInfo info;
+    blink::WebGraphicsContext3D::ActiveInfo info;
     if (!m_context->getActiveUniform(objectOrZero(program), index, info))
         return 0;
     return WebGLActiveInfo::create(info.name, info.type, info.size);
@@ -2061,11 +2059,11 @@
     if (isContextLost() || !validateWebGLObject("getAttachedShaders", program))
         return false;
 
-    const GC3Denum shaderType[] = {
-        GraphicsContext3D::VERTEX_SHADER,
-        GraphicsContext3D::FRAGMENT_SHADER
+    const GLenum shaderType[] = {
+        GL_VERTEX_SHADER,
+        GL_FRAGMENT_SHADER
     };
-    for (unsigned i = 0; i < sizeof(shaderType) / sizeof(GC3Denum); ++i) {
+    for (unsigned i = 0; i < sizeof(shaderType) / sizeof(GLenum); ++i) {
         WebGLShader* shader = program->getAttachedShader(shaderType[i]);
         if (shader)
             shaderObjects.append(shader);
@@ -2073,7 +2071,7 @@
     return true;
 }
 
-GC3Dint WebGLRenderingContext::getAttribLocation(WebGLProgram* program, const String& name)
+GLint WebGLRenderingContext::getAttribLocation(WebGLProgram* program, const String& name)
 {
     if (isContextLost() || !validateWebGLObject("getAttribLocation", program))
         return -1;
@@ -2084,31 +2082,31 @@
     if (isPrefixReserved(name))
         return -1;
     if (!program->linkStatus()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getAttribLocation", "program not linked");
+        synthesizeGLError(GL_INVALID_OPERATION, "getAttribLocation", "program not linked");
         return 0;
     }
-    return m_context->getAttribLocation(objectOrZero(program), name);
+    return m_context->getAttribLocation(objectOrZero(program), name.utf8().data());
 }
 
-WebGLGetInfo WebGLRenderingContext::getBufferParameter(GC3Denum target, GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getBufferParameter(GLenum target, GLenum pname)
 {
     if (isContextLost())
         return WebGLGetInfo();
-    if (target != GraphicsContext3D::ARRAY_BUFFER && target != GraphicsContext3D::ELEMENT_ARRAY_BUFFER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getBufferParameter", "invalid target");
+    if (target != GL_ARRAY_BUFFER && target != GL_ELEMENT_ARRAY_BUFFER) {
+        synthesizeGLError(GL_INVALID_ENUM, "getBufferParameter", "invalid target");
         return WebGLGetInfo();
     }
 
-    if (pname != GraphicsContext3D::BUFFER_SIZE && pname != GraphicsContext3D::BUFFER_USAGE) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getBufferParameter", "invalid parameter name");
+    if (pname != GL_BUFFER_SIZE && pname != GL_BUFFER_USAGE) {
+        synthesizeGLError(GL_INVALID_ENUM, "getBufferParameter", "invalid parameter name");
         return WebGLGetInfo();
     }
 
-    GC3Dint value = 0;
+    GLint value = 0;
     m_context->getBufferParameteriv(target, pname, &value);
-    if (pname == GraphicsContext3D::BUFFER_SIZE)
+    if (pname == GL_BUFFER_SIZE)
         return WebGLGetInfo(value);
-    return WebGLGetInfo(static_cast<unsigned int>(value));
+    return WebGLGetInfo(static_cast<unsigned>(value));
 }
 
 PassRefPtr<WebGLContextAttributes> WebGLRenderingContext::getContextAttributes()
@@ -2117,31 +2115,28 @@
         return 0;
     // We always need to return a new WebGLContextAttributes object to
     // prevent the user from mutating any cached version.
-
-    // Also, we need to enforce requested values of "false" for depth
-    // and stencil, regardless of the properties of the underlying
-    // GraphicsContext3D or DrawingBuffer.
-    RefPtr<WebGLContextAttributes> attributes = WebGLContextAttributes::create(m_context->getContextAttributes());
-    if (!m_attributes.depth)
+    blink::WebGraphicsContext3D::Attributes attrs = m_context->getContextAttributes();
+    RefPtr<WebGLContextAttributes> attributes = m_requestedAttributes->clone();
+    // Some requested attributes may not be honored, so we need to query the underlying
+    // context/drawing buffer and adjust accordingly.
+    if (m_requestedAttributes->depth() && !attrs.depth)
         attributes->setDepth(false);
-    if (!m_attributes.stencil)
+    if (m_requestedAttributes->stencil() && !attrs.stencil)
         attributes->setStencil(false);
-    // The DrawingBuffer obtains its parameters from GraphicsContext3D::getContextAttributes(),
-    // but it makes its own determination of whether multisampling is supported.
     attributes->setAntialias(m_drawingBuffer->multisample());
     return attributes.release();
 }
 
-GC3Denum WebGLRenderingContext::getError()
+GLenum WebGLRenderingContext::getError()
 {
-    if (lost_context_errors_.size()) {
-        GC3Denum err = lost_context_errors_.first();
-        lost_context_errors_.remove(0);
+    if (m_lostContextErrors.size()) {
+        GLenum err = m_lostContextErrors.first();
+        m_lostContextErrors.remove(0);
         return err;
     }
 
     if (isContextLost())
-        return GraphicsContext3D::NO_ERROR;
+        return GL_NO_ERROR;
 
     return m_context->getError();
 }
@@ -2183,315 +2178,315 @@
     return 0;
 }
 
-WebGLGetInfo WebGLRenderingContext::getFramebufferAttachmentParameter(GC3Denum target, GC3Denum attachment, GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getFramebufferAttachmentParameter(GLenum target, GLenum attachment, GLenum pname)
 {
     if (isContextLost() || !validateFramebufferFuncParameters("getFramebufferAttachmentParameter", target, attachment))
         return WebGLGetInfo();
 
     if (!m_framebufferBinding || !m_framebufferBinding->object()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getFramebufferAttachmentParameter", "no framebuffer bound");
+        synthesizeGLError(GL_INVALID_OPERATION, "getFramebufferAttachmentParameter", "no framebuffer bound");
         return WebGLGetInfo();
     }
 
     WebGLSharedObject* object = m_framebufferBinding->getAttachmentObject(attachment);
     if (!object) {
-        if (pname == GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)
-            return WebGLGetInfo(GraphicsContext3D::NONE);
+        if (pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)
+            return WebGLGetInfo(GL_NONE);
         // OpenGL ES 2.0 specifies INVALID_ENUM in this case, while desktop GL
         // specifies INVALID_OPERATION.
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name");
+        synthesizeGLError(GL_INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name");
         return WebGLGetInfo();
     }
 
     ASSERT(object->isTexture() || object->isRenderbuffer());
     if (object->isTexture()) {
         switch (pname) {
-        case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
-            return WebGLGetInfo(GraphicsContext3D::TEXTURE);
-        case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
+        case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
+            return WebGLGetInfo(GL_TEXTURE);
+        case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
             return WebGLGetInfo(PassRefPtr<WebGLTexture>(static_cast<WebGLTexture*>(object)));
-        case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:
-        case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:
+        case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:
+        case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:
             {
-                GC3Dint value = 0;
+                GLint value = 0;
                 m_context->getFramebufferAttachmentParameteriv(target, attachment, pname, &value);
                 return WebGLGetInfo(value);
             }
         default:
-            synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name for texture attachment");
+            synthesizeGLError(GL_INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name for texture attachment");
             return WebGLGetInfo();
         }
     } else {
         switch (pname) {
-        case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
-            return WebGLGetInfo(GraphicsContext3D::RENDERBUFFER);
-        case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
+        case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
+            return WebGLGetInfo(GL_RENDERBUFFER);
+        case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
             return WebGLGetInfo(PassRefPtr<WebGLRenderbuffer>(static_cast<WebGLRenderbuffer*>(object)));
         default:
-            synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name for renderbuffer attachment");
+            synthesizeGLError(GL_INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name for renderbuffer attachment");
             return WebGLGetInfo();
         }
     }
 }
 
-WebGLGetInfo WebGLRenderingContext::getParameter(GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getParameter(GLenum pname)
 {
     if (isContextLost())
         return WebGLGetInfo();
     const int intZero = 0;
     switch (pname) {
-    case GraphicsContext3D::ACTIVE_TEXTURE:
+    case GL_ACTIVE_TEXTURE:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::ALIASED_LINE_WIDTH_RANGE:
+    case GL_ALIASED_LINE_WIDTH_RANGE:
         return getWebGLFloatArrayParameter(pname);
-    case GraphicsContext3D::ALIASED_POINT_SIZE_RANGE:
+    case GL_ALIASED_POINT_SIZE_RANGE:
         return getWebGLFloatArrayParameter(pname);
-    case GraphicsContext3D::ALPHA_BITS:
+    case GL_ALPHA_BITS:
         return getIntParameter(pname);
-    case GraphicsContext3D::ARRAY_BUFFER_BINDING:
+    case GL_ARRAY_BUFFER_BINDING:
         return WebGLGetInfo(PassRefPtr<WebGLBuffer>(m_boundArrayBuffer));
-    case GraphicsContext3D::BLEND:
+    case GL_BLEND:
         return getBooleanParameter(pname);
-    case GraphicsContext3D::BLEND_COLOR:
+    case GL_BLEND_COLOR:
         return getWebGLFloatArrayParameter(pname);
-    case GraphicsContext3D::BLEND_DST_ALPHA:
+    case GL_BLEND_DST_ALPHA:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::BLEND_DST_RGB:
+    case GL_BLEND_DST_RGB:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::BLEND_EQUATION_ALPHA:
+    case GL_BLEND_EQUATION_ALPHA:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::BLEND_EQUATION_RGB:
+    case GL_BLEND_EQUATION_RGB:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::BLEND_SRC_ALPHA:
+    case GL_BLEND_SRC_ALPHA:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::BLEND_SRC_RGB:
+    case GL_BLEND_SRC_RGB:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::BLUE_BITS:
+    case GL_BLUE_BITS:
         return getIntParameter(pname);
-    case GraphicsContext3D::COLOR_CLEAR_VALUE:
+    case GL_COLOR_CLEAR_VALUE:
         return getWebGLFloatArrayParameter(pname);
-    case GraphicsContext3D::COLOR_WRITEMASK:
+    case GL_COLOR_WRITEMASK:
         return getBooleanArrayParameter(pname);
-    case GraphicsContext3D::COMPRESSED_TEXTURE_FORMATS:
+    case GL_COMPRESSED_TEXTURE_FORMATS:
         return WebGLGetInfo(Uint32Array::create(m_compressedTextureFormats.data(), m_compressedTextureFormats.size()));
-    case GraphicsContext3D::CULL_FACE:
+    case GL_CULL_FACE:
         return getBooleanParameter(pname);
-    case GraphicsContext3D::CULL_FACE_MODE:
+    case GL_CULL_FACE_MODE:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::CURRENT_PROGRAM:
+    case GL_CURRENT_PROGRAM:
         return WebGLGetInfo(PassRefPtr<WebGLProgram>(m_currentProgram));
-    case GraphicsContext3D::DEPTH_BITS:
-        if (!m_framebufferBinding && !m_attributes.depth)
+    case GL_DEPTH_BITS:
+        if (!m_framebufferBinding && !m_requestedAttributes->depth())
             return WebGLGetInfo(intZero);
         return getIntParameter(pname);
-    case GraphicsContext3D::DEPTH_CLEAR_VALUE:
+    case GL_DEPTH_CLEAR_VALUE:
         return getFloatParameter(pname);
-    case GraphicsContext3D::DEPTH_FUNC:
+    case GL_DEPTH_FUNC:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::DEPTH_RANGE:
+    case GL_DEPTH_RANGE:
         return getWebGLFloatArrayParameter(pname);
-    case GraphicsContext3D::DEPTH_TEST:
+    case GL_DEPTH_TEST:
         return getBooleanParameter(pname);
-    case GraphicsContext3D::DEPTH_WRITEMASK:
+    case GL_DEPTH_WRITEMASK:
         return getBooleanParameter(pname);
-    case GraphicsContext3D::DITHER:
+    case GL_DITHER:
         return getBooleanParameter(pname);
-    case GraphicsContext3D::ELEMENT_ARRAY_BUFFER_BINDING:
+    case GL_ELEMENT_ARRAY_BUFFER_BINDING:
         return WebGLGetInfo(PassRefPtr<WebGLBuffer>(m_boundVertexArrayObject->boundElementArrayBuffer()));
-    case GraphicsContext3D::FRAMEBUFFER_BINDING:
+    case GL_FRAMEBUFFER_BINDING:
         return WebGLGetInfo(PassRefPtr<WebGLFramebuffer>(m_framebufferBinding));
-    case GraphicsContext3D::FRONT_FACE:
+    case GL_FRONT_FACE:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::GENERATE_MIPMAP_HINT:
+    case GL_GENERATE_MIPMAP_HINT:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::GREEN_BITS:
+    case GL_GREEN_BITS:
         return getIntParameter(pname);
-    case GraphicsContext3D::LINE_WIDTH:
+    case GL_LINE_WIDTH:
         return getFloatParameter(pname);
-    case GraphicsContext3D::MAX_COMBINED_TEXTURE_IMAGE_UNITS:
+    case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_CUBE_MAP_TEXTURE_SIZE:
+    case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_FRAGMENT_UNIFORM_VECTORS:
+    case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_RENDERBUFFER_SIZE:
+    case GL_MAX_RENDERBUFFER_SIZE:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_TEXTURE_IMAGE_UNITS:
+    case GL_MAX_TEXTURE_IMAGE_UNITS:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_TEXTURE_SIZE:
+    case GL_MAX_TEXTURE_SIZE:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_VARYING_VECTORS:
+    case GL_MAX_VARYING_VECTORS:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_VERTEX_ATTRIBS:
+    case GL_MAX_VERTEX_ATTRIBS:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_VERTEX_TEXTURE_IMAGE_UNITS:
+    case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_VERTEX_UNIFORM_VECTORS:
+    case GL_MAX_VERTEX_UNIFORM_VECTORS:
         return getIntParameter(pname);
-    case GraphicsContext3D::MAX_VIEWPORT_DIMS:
+    case GL_MAX_VIEWPORT_DIMS:
         return getWebGLIntArrayParameter(pname);
-    case GraphicsContext3D::NUM_SHADER_BINARY_FORMATS:
+    case GL_NUM_SHADER_BINARY_FORMATS:
         // FIXME: should we always return 0 for this?
         return getIntParameter(pname);
-    case GraphicsContext3D::PACK_ALIGNMENT:
+    case GL_PACK_ALIGNMENT:
         return getIntParameter(pname);
-    case GraphicsContext3D::POLYGON_OFFSET_FACTOR:
+    case GL_POLYGON_OFFSET_FACTOR:
         return getFloatParameter(pname);
-    case GraphicsContext3D::POLYGON_OFFSET_FILL:
+    case GL_POLYGON_OFFSET_FILL:
         return getBooleanParameter(pname);
-    case GraphicsContext3D::POLYGON_OFFSET_UNITS:
+    case GL_POLYGON_OFFSET_UNITS:
         return getFloatParameter(pname);
-    case GraphicsContext3D::RED_BITS:
+    case GL_RED_BITS:
         return getIntParameter(pname);
-    case GraphicsContext3D::RENDERBUFFER_BINDING:
+    case GL_RENDERBUFFER_BINDING:
         return WebGLGetInfo(PassRefPtr<WebGLRenderbuffer>(m_renderbufferBinding));
-    case GraphicsContext3D::RENDERER:
+    case GL_RENDERER:
         return WebGLGetInfo(String("WebKit WebGL"));
-    case GraphicsContext3D::SAMPLE_BUFFERS:
+    case GL_SAMPLE_BUFFERS:
         return getIntParameter(pname);
-    case GraphicsContext3D::SAMPLE_COVERAGE_INVERT:
+    case GL_SAMPLE_COVERAGE_INVERT:
         return getBooleanParameter(pname);
-    case GraphicsContext3D::SAMPLE_COVERAGE_VALUE:
+    case GL_SAMPLE_COVERAGE_VALUE:
         return getFloatParameter(pname);
-    case GraphicsContext3D::SAMPLES:
+    case GL_SAMPLES:
         return getIntParameter(pname);
-    case GraphicsContext3D::SCISSOR_BOX:
+    case GL_SCISSOR_BOX:
         return getWebGLIntArrayParameter(pname);
-    case GraphicsContext3D::SCISSOR_TEST:
+    case GL_SCISSOR_TEST:
         return getBooleanParameter(pname);
-    case GraphicsContext3D::SHADING_LANGUAGE_VERSION:
-        return WebGLGetInfo("WebGL GLSL ES 1.0 (" + m_context->getString(GraphicsContext3D::SHADING_LANGUAGE_VERSION) + ")");
-    case GraphicsContext3D::STENCIL_BACK_FAIL:
+    case GL_SHADING_LANGUAGE_VERSION:
+        return WebGLGetInfo("WebGL GLSL ES 1.0 (" + String(m_context->getString(GL_SHADING_LANGUAGE_VERSION)) + ")");
+    case GL_STENCIL_BACK_FAIL:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_BACK_FUNC:
+    case GL_STENCIL_BACK_FUNC:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_BACK_PASS_DEPTH_FAIL:
+    case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_BACK_PASS_DEPTH_PASS:
+    case GL_STENCIL_BACK_PASS_DEPTH_PASS:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_BACK_REF:
+    case GL_STENCIL_BACK_REF:
         return getIntParameter(pname);
-    case GraphicsContext3D::STENCIL_BACK_VALUE_MASK:
+    case GL_STENCIL_BACK_VALUE_MASK:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_BACK_WRITEMASK:
+    case GL_STENCIL_BACK_WRITEMASK:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_BITS:
-        if (!m_framebufferBinding && !m_attributes.stencil)
+    case GL_STENCIL_BITS:
+        if (!m_framebufferBinding && !m_requestedAttributes->stencil())
             return WebGLGetInfo(intZero);
         return getIntParameter(pname);
-    case GraphicsContext3D::STENCIL_CLEAR_VALUE:
+    case GL_STENCIL_CLEAR_VALUE:
         return getIntParameter(pname);
-    case GraphicsContext3D::STENCIL_FAIL:
+    case GL_STENCIL_FAIL:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_FUNC:
+    case GL_STENCIL_FUNC:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_PASS_DEPTH_FAIL:
+    case GL_STENCIL_PASS_DEPTH_FAIL:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_PASS_DEPTH_PASS:
+    case GL_STENCIL_PASS_DEPTH_PASS:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_REF:
+    case GL_STENCIL_REF:
         return getIntParameter(pname);
-    case GraphicsContext3D::STENCIL_TEST:
+    case GL_STENCIL_TEST:
         return getBooleanParameter(pname);
-    case GraphicsContext3D::STENCIL_VALUE_MASK:
+    case GL_STENCIL_VALUE_MASK:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::STENCIL_WRITEMASK:
+    case GL_STENCIL_WRITEMASK:
         return getUnsignedIntParameter(pname);
-    case GraphicsContext3D::SUBPIXEL_BITS:
+    case GL_SUBPIXEL_BITS:
         return getIntParameter(pname);
-    case GraphicsContext3D::TEXTURE_BINDING_2D:
+    case GL_TEXTURE_BINDING_2D:
         return WebGLGetInfo(PassRefPtr<WebGLTexture>(m_textureUnits[m_activeTextureUnit].m_texture2DBinding));
-    case GraphicsContext3D::TEXTURE_BINDING_CUBE_MAP:
+    case GL_TEXTURE_BINDING_CUBE_MAP:
         return WebGLGetInfo(PassRefPtr<WebGLTexture>(m_textureUnits[m_activeTextureUnit].m_textureCubeMapBinding));
-    case GraphicsContext3D::UNPACK_ALIGNMENT:
+    case GL_UNPACK_ALIGNMENT:
         return getIntParameter(pname);
-    case GraphicsContext3D::UNPACK_FLIP_Y_WEBGL:
+    case GC3D_UNPACK_FLIP_Y_WEBGL:
         return WebGLGetInfo(m_unpackFlipY);
-    case GraphicsContext3D::UNPACK_PREMULTIPLY_ALPHA_WEBGL:
+    case GC3D_UNPACK_PREMULTIPLY_ALPHA_WEBGL:
         return WebGLGetInfo(m_unpackPremultiplyAlpha);
-    case GraphicsContext3D::UNPACK_COLORSPACE_CONVERSION_WEBGL:
+    case GC3D_UNPACK_COLORSPACE_CONVERSION_WEBGL:
         return WebGLGetInfo(m_unpackColorspaceConversion);
-    case GraphicsContext3D::VENDOR:
+    case GL_VENDOR:
         return WebGLGetInfo(String("WebKit"));
-    case GraphicsContext3D::VERSION:
-        return WebGLGetInfo("WebGL 1.0 (" + m_context->getString(GraphicsContext3D::VERSION) + ")");
-    case GraphicsContext3D::VIEWPORT:
+    case GL_VERSION:
+        return WebGLGetInfo("WebGL 1.0 (" + String(m_context->getString(GL_VERSION)) + ")");
+    case GL_VIEWPORT:
         return getWebGLIntArrayParameter(pname);
-    case Extensions3D::FRAGMENT_SHADER_DERIVATIVE_HINT_OES: // OES_standard_derivatives
+    case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: // OES_standard_derivatives
         if (m_oesStandardDerivatives)
-            return getUnsignedIntParameter(Extensions3D::FRAGMENT_SHADER_DERIVATIVE_HINT_OES);
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, OES_standard_derivatives not enabled");
+            return getUnsignedIntParameter(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES);
+        synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, OES_standard_derivatives not enabled");
         return WebGLGetInfo();
     case WebGLDebugRendererInfo::UNMASKED_RENDERER_WEBGL:
         if (m_webglDebugRendererInfo)
-            return WebGLGetInfo(m_context->getString(GraphicsContext3D::RENDERER));
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_debug_renderer_info not enabled");
+            return WebGLGetInfo(m_context->getString(GL_RENDERER));
+        synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_debug_renderer_info not enabled");
         return WebGLGetInfo();
     case WebGLDebugRendererInfo::UNMASKED_VENDOR_WEBGL:
         if (m_webglDebugRendererInfo)
-            return WebGLGetInfo(m_context->getString(GraphicsContext3D::VENDOR));
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_debug_renderer_info not enabled");
+            return WebGLGetInfo(m_context->getString(GL_VENDOR));
+        synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_debug_renderer_info not enabled");
         return WebGLGetInfo();
-    case Extensions3D::VERTEX_ARRAY_BINDING_OES: // OES_vertex_array_object
+    case GL_VERTEX_ARRAY_BINDING_OES: // OES_vertex_array_object
         if (m_oesVertexArrayObject) {
             if (!m_boundVertexArrayObject->isDefaultObject())
                 return WebGLGetInfo(PassRefPtr<WebGLVertexArrayObjectOES>(m_boundVertexArrayObject));
             return WebGLGetInfo();
         }
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, OES_vertex_array_object not enabled");
+        synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, OES_vertex_array_object not enabled");
         return WebGLGetInfo();
-    case Extensions3D::MAX_TEXTURE_MAX_ANISOTROPY_EXT: // EXT_texture_filter_anisotropic
+    case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT: // EXT_texture_filter_anisotropic
         if (m_extTextureFilterAnisotropic)
-            return getUnsignedIntParameter(Extensions3D::MAX_TEXTURE_MAX_ANISOTROPY_EXT);
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, EXT_texture_filter_anisotropic not enabled");
+            return getUnsignedIntParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT);
+        synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, EXT_texture_filter_anisotropic not enabled");
         return WebGLGetInfo();
-    case Extensions3D::MAX_COLOR_ATTACHMENTS_EXT: // EXT_draw_buffers BEGIN
+    case GL_MAX_COLOR_ATTACHMENTS_EXT: // EXT_draw_buffers BEGIN
         if (m_webglDrawBuffers)
             return WebGLGetInfo(maxColorAttachments());
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_draw_buffers not enabled");
+        synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_draw_buffers not enabled");
         return WebGLGetInfo();
-    case Extensions3D::MAX_DRAW_BUFFERS_EXT:
+    case GL_MAX_DRAW_BUFFERS_EXT:
         if (m_webglDrawBuffers)
             return WebGLGetInfo(maxDrawBuffers());
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_draw_buffers not enabled");
+        synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_draw_buffers not enabled");
         return WebGLGetInfo();
     default:
         if (m_webglDrawBuffers
-            && pname >= Extensions3D::DRAW_BUFFER0_EXT
-            && pname < static_cast<GC3Denum>(Extensions3D::DRAW_BUFFER0_EXT + maxDrawBuffers())) {
-            GC3Dint value = GraphicsContext3D::NONE;
+            && pname >= GL_DRAW_BUFFER0_EXT
+            && pname < static_cast<GLenum>(GL_DRAW_BUFFER0_EXT + maxDrawBuffers())) {
+            GLint value = GL_NONE;
             if (m_framebufferBinding)
                 value = m_framebufferBinding->getDrawBuffer(pname);
             else // emulated backbuffer
                 value = m_backDrawBuffer;
             return WebGLGetInfo(value);
         }
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name");
+        synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name");
         return WebGLGetInfo();
     }
 }
 
-WebGLGetInfo WebGLRenderingContext::getProgramParameter(WebGLProgram* program, GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getProgramParameter(WebGLProgram* program, GLenum pname)
 {
     if (isContextLost() || !validateWebGLObject("getProgramParameter", program))
         return WebGLGetInfo();
 
-    GC3Dint value = 0;
+    GLint value = 0;
     switch (pname) {
-    case GraphicsContext3D::DELETE_STATUS:
+    case GL_DELETE_STATUS:
         return WebGLGetInfo(program->isDeleted());
-    case GraphicsContext3D::VALIDATE_STATUS:
+    case GL_VALIDATE_STATUS:
         m_context->getProgramiv(objectOrZero(program), pname, &value);
         return WebGLGetInfo(static_cast<bool>(value));
-    case GraphicsContext3D::LINK_STATUS:
+    case GL_LINK_STATUS:
         return WebGLGetInfo(program->linkStatus());
-    case GraphicsContext3D::ATTACHED_SHADERS:
-    case GraphicsContext3D::ACTIVE_ATTRIBUTES:
-    case GraphicsContext3D::ACTIVE_UNIFORMS:
+    case GL_ATTACHED_SHADERS:
+    case GL_ACTIVE_ATTRIBUTES:
+    case GL_ACTIVE_UNIFORMS:
         m_context->getProgramiv(objectOrZero(program), pname, &value);
         return WebGLGetInfo(value);
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getProgramParameter", "invalid parameter name");
+        synthesizeGLError(GL_INVALID_ENUM, "getProgramParameter", "invalid parameter name");
         return WebGLGetInfo();
     }
 }
@@ -2505,31 +2500,31 @@
     return ensureNotNull(m_context->getProgramInfoLog(objectOrZero(program)));
 }
 
-WebGLGetInfo WebGLRenderingContext::getRenderbufferParameter(GC3Denum target, GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getRenderbufferParameter(GLenum target, GLenum pname)
 {
     if (isContextLost())
         return WebGLGetInfo();
-    if (target != GraphicsContext3D::RENDERBUFFER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getRenderbufferParameter", "invalid target");
+    if (target != GL_RENDERBUFFER) {
+        synthesizeGLError(GL_INVALID_ENUM, "getRenderbufferParameter", "invalid target");
         return WebGLGetInfo();
     }
     if (!m_renderbufferBinding || !m_renderbufferBinding->object()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getRenderbufferParameter", "no renderbuffer bound");
+        synthesizeGLError(GL_INVALID_OPERATION, "getRenderbufferParameter", "no renderbuffer bound");
         return WebGLGetInfo();
     }
 
-    GC3Dint value = 0;
+    GLint value = 0;
     switch (pname) {
-    case GraphicsContext3D::RENDERBUFFER_WIDTH:
-    case GraphicsContext3D::RENDERBUFFER_HEIGHT:
-    case GraphicsContext3D::RENDERBUFFER_RED_SIZE:
-    case GraphicsContext3D::RENDERBUFFER_GREEN_SIZE:
-    case GraphicsContext3D::RENDERBUFFER_BLUE_SIZE:
-    case GraphicsContext3D::RENDERBUFFER_ALPHA_SIZE:
-    case GraphicsContext3D::RENDERBUFFER_DEPTH_SIZE:
+    case GL_RENDERBUFFER_WIDTH:
+    case GL_RENDERBUFFER_HEIGHT:
+    case GL_RENDERBUFFER_RED_SIZE:
+    case GL_RENDERBUFFER_GREEN_SIZE:
+    case GL_RENDERBUFFER_BLUE_SIZE:
+    case GL_RENDERBUFFER_ALPHA_SIZE:
+    case GL_RENDERBUFFER_DEPTH_SIZE:
         m_context->getRenderbufferParameteriv(target, pname, &value);
         return WebGLGetInfo(value);
-    case GraphicsContext3D::RENDERBUFFER_STENCIL_SIZE:
+    case GL_RENDERBUFFER_STENCIL_SIZE:
         if (m_renderbufferBinding->emulatedStencilBuffer()) {
             m_context->bindRenderbuffer(target, objectOrZero(m_renderbufferBinding->emulatedStencilBuffer()));
             m_context->getRenderbufferParameteriv(target, pname, &value);
@@ -2538,30 +2533,30 @@
             m_context->getRenderbufferParameteriv(target, pname, &value);
         }
         return WebGLGetInfo(value);
-    case GraphicsContext3D::RENDERBUFFER_INTERNAL_FORMAT:
+    case GL_RENDERBUFFER_INTERNAL_FORMAT:
         return WebGLGetInfo(m_renderbufferBinding->internalFormat());
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getRenderbufferParameter", "invalid parameter name");
+        synthesizeGLError(GL_INVALID_ENUM, "getRenderbufferParameter", "invalid parameter name");
         return WebGLGetInfo();
     }
 }
 
-WebGLGetInfo WebGLRenderingContext::getShaderParameter(WebGLShader* shader, GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getShaderParameter(WebGLShader* shader, GLenum pname)
 {
     if (isContextLost() || !validateWebGLObject("getShaderParameter", shader))
         return WebGLGetInfo();
-    GC3Dint value = 0;
+    GLint value = 0;
     switch (pname) {
-    case GraphicsContext3D::DELETE_STATUS:
+    case GL_DELETE_STATUS:
         return WebGLGetInfo(shader->isDeleted());
-    case GraphicsContext3D::COMPILE_STATUS:
+    case GL_COMPILE_STATUS:
         m_context->getShaderiv(objectOrZero(shader), pname, &value);
         return WebGLGetInfo(static_cast<bool>(value));
-    case GraphicsContext3D::SHADER_TYPE:
+    case GL_SHADER_TYPE:
         m_context->getShaderiv(objectOrZero(shader), pname, &value);
-        return WebGLGetInfo(static_cast<unsigned int>(value));
+        return WebGLGetInfo(static_cast<unsigned>(value));
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getShaderParameter", "invalid parameter name");
+        synthesizeGLError(GL_INVALID_ENUM, "getShaderParameter", "invalid parameter name");
         return WebGLGetInfo();
     }
 }
@@ -2575,33 +2570,33 @@
     return ensureNotNull(m_context->getShaderInfoLog(objectOrZero(shader)));
 }
 
-PassRefPtr<WebGLShaderPrecisionFormat> WebGLRenderingContext::getShaderPrecisionFormat(GC3Denum shaderType, GC3Denum precisionType)
+PassRefPtr<WebGLShaderPrecisionFormat> WebGLRenderingContext::getShaderPrecisionFormat(GLenum shaderType, GLenum precisionType)
 {
     if (isContextLost())
         return 0;
     switch (shaderType) {
-    case GraphicsContext3D::VERTEX_SHADER:
-    case GraphicsContext3D::FRAGMENT_SHADER:
+    case GL_VERTEX_SHADER:
+    case GL_FRAGMENT_SHADER:
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getShaderPrecisionFormat", "invalid shader type");
+        synthesizeGLError(GL_INVALID_ENUM, "getShaderPrecisionFormat", "invalid shader type");
         return 0;
     }
     switch (precisionType) {
-    case GraphicsContext3D::LOW_FLOAT:
-    case GraphicsContext3D::MEDIUM_FLOAT:
-    case GraphicsContext3D::HIGH_FLOAT:
-    case GraphicsContext3D::LOW_INT:
-    case GraphicsContext3D::MEDIUM_INT:
-    case GraphicsContext3D::HIGH_INT:
+    case GL_LOW_FLOAT:
+    case GL_MEDIUM_FLOAT:
+    case GL_HIGH_FLOAT:
+    case GL_LOW_INT:
+    case GL_MEDIUM_INT:
+    case GL_HIGH_INT:
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getShaderPrecisionFormat", "invalid precision type");
+        synthesizeGLError(GL_INVALID_ENUM, "getShaderPrecisionFormat", "invalid precision type");
         return 0;
     }
 
-    GC3Dint range[2] = {0, 0};
-    GC3Dint precision = 0;
+    GLint range[2] = {0, 0};
+    GLint precision = 0;
     m_context->getShaderPrecisionFormat(shaderType, precisionType, range, &precision);
     return WebGLShaderPrecisionFormat::create(range[0], range[1], precision);
 }
@@ -2636,30 +2631,30 @@
     return result;
 }
 
-WebGLGetInfo WebGLRenderingContext::getTexParameter(GC3Denum target, GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getTexParameter(GLenum target, GLenum pname)
 {
     if (isContextLost())
         return WebGLGetInfo();
     WebGLTexture* tex = validateTextureBinding("getTexParameter", target, false);
     if (!tex)
         return WebGLGetInfo();
-    GC3Dint value = 0;
+    GLint value = 0;
     switch (pname) {
-    case GraphicsContext3D::TEXTURE_MAG_FILTER:
-    case GraphicsContext3D::TEXTURE_MIN_FILTER:
-    case GraphicsContext3D::TEXTURE_WRAP_S:
-    case GraphicsContext3D::TEXTURE_WRAP_T:
+    case GL_TEXTURE_MAG_FILTER:
+    case GL_TEXTURE_MIN_FILTER:
+    case GL_TEXTURE_WRAP_S:
+    case GL_TEXTURE_WRAP_T:
         m_context->getTexParameteriv(target, pname, &value);
-        return WebGLGetInfo(static_cast<unsigned int>(value));
-    case Extensions3D::TEXTURE_MAX_ANISOTROPY_EXT: // EXT_texture_filter_anisotropic
+        return WebGLGetInfo(static_cast<unsigned>(value));
+    case GL_TEXTURE_MAX_ANISOTROPY_EXT: // EXT_texture_filter_anisotropic
         if (m_extTextureFilterAnisotropic) {
             m_context->getTexParameteriv(target, pname, &value);
-            return WebGLGetInfo(static_cast<unsigned int>(value));
+            return WebGLGetInfo(static_cast<unsigned>(value));
         }
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getTexParameter", "invalid parameter name, EXT_texture_filter_anisotropic not enabled");
+        synthesizeGLError(GL_INVALID_ENUM, "getTexParameter", "invalid parameter name, EXT_texture_filter_anisotropic not enabled");
         return WebGLGetInfo();
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getTexParameter", "invalid parameter name");
+        synthesizeGLError(GL_INVALID_ENUM, "getTexParameter", "invalid parameter name");
         return WebGLGetInfo();
     }
 }
@@ -2669,123 +2664,126 @@
     if (isContextLost() || !validateWebGLObject("getUniform", program))
         return WebGLGetInfo();
     if (!uniformLocation || uniformLocation->program() != program) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getUniform", "no uniformlocation or not valid for this program");
+        synthesizeGLError(GL_INVALID_OPERATION, "getUniform", "no uniformlocation or not valid for this program");
         return WebGLGetInfo();
     }
-    GC3Dint location = uniformLocation->location();
+    GLint location = uniformLocation->location();
 
     // FIXME: make this more efficient using WebGLUniformLocation and caching types in it
-    GC3Dint activeUniforms = 0;
-    m_context->getProgramiv(objectOrZero(program), GraphicsContext3D::ACTIVE_UNIFORMS, &activeUniforms);
-    for (GC3Dint i = 0; i < activeUniforms; i++) {
-        ActiveInfo info;
+    GLint activeUniforms = 0;
+    m_context->getProgramiv(objectOrZero(program), GL_ACTIVE_UNIFORMS, &activeUniforms);
+    for (GLint i = 0; i < activeUniforms; i++) {
+        blink::WebGraphicsContext3D::ActiveInfo info;
         if (!m_context->getActiveUniform(objectOrZero(program), i, info))
             return WebGLGetInfo();
+        String name = info.name;
+        StringBuilder nameBuilder;
         // Strip "[0]" from the name if it's an array.
-        if (info.size > 1 && info.name.endsWith("[0]"))
-            info.name = info.name.left(info.name.length() - 3);
+        if (info.size > 1 && name.endsWith("[0]"))
+            info.name = name.left(name.length() - 3);
         // If it's an array, we need to iterate through each element, appending "[index]" to the name.
-        for (GC3Dint index = 0; index < info.size; ++index) {
-            String name = info.name;
+        for (GLint index = 0; index < info.size; ++index) {
+            nameBuilder.clear();
+            nameBuilder.append(info.name);
             if (info.size > 1 && index >= 1) {
-                name.append('[');
-                name.append(String::number(index));
-                name.append(']');
+                nameBuilder.append('[');
+                nameBuilder.append(String::number(index));
+                nameBuilder.append(']');
             }
             // Now need to look this up by name again to find its location
-            GC3Dint loc = m_context->getUniformLocation(objectOrZero(program), name);
+            GLint loc = m_context->getUniformLocation(objectOrZero(program), nameBuilder.toString().utf8().data());
             if (loc == location) {
                 // Found it. Use the type in the ActiveInfo to determine the return type.
-                GC3Denum baseType;
-                unsigned int length;
+                GLenum baseType;
+                unsigned length;
                 switch (info.type) {
-                case GraphicsContext3D::BOOL:
-                    baseType = GraphicsContext3D::BOOL;
+                case GL_BOOL:
+                    baseType = GL_BOOL;
                     length = 1;
                     break;
-                case GraphicsContext3D::BOOL_VEC2:
-                    baseType = GraphicsContext3D::BOOL;
+                case GL_BOOL_VEC2:
+                    baseType = GL_BOOL;
                     length = 2;
                     break;
-                case GraphicsContext3D::BOOL_VEC3:
-                    baseType = GraphicsContext3D::BOOL;
+                case GL_BOOL_VEC3:
+                    baseType = GL_BOOL;
                     length = 3;
                     break;
-                case GraphicsContext3D::BOOL_VEC4:
-                    baseType = GraphicsContext3D::BOOL;
+                case GL_BOOL_VEC4:
+                    baseType = GL_BOOL;
                     length = 4;
                     break;
-                case GraphicsContext3D::INT:
-                    baseType = GraphicsContext3D::INT;
+                case GL_INT:
+                    baseType = GL_INT;
                     length = 1;
                     break;
-                case GraphicsContext3D::INT_VEC2:
-                    baseType = GraphicsContext3D::INT;
+                case GL_INT_VEC2:
+                    baseType = GL_INT;
                     length = 2;
                     break;
-                case GraphicsContext3D::INT_VEC3:
-                    baseType = GraphicsContext3D::INT;
+                case GL_INT_VEC3:
+                    baseType = GL_INT;
                     length = 3;
                     break;
-                case GraphicsContext3D::INT_VEC4:
-                    baseType = GraphicsContext3D::INT;
+                case GL_INT_VEC4:
+                    baseType = GL_INT;
                     length = 4;
                     break;
-                case GraphicsContext3D::FLOAT:
-                    baseType = GraphicsContext3D::FLOAT;
+                case GL_FLOAT:
+                    baseType = GL_FLOAT;
                     length = 1;
                     break;
-                case GraphicsContext3D::FLOAT_VEC2:
-                    baseType = GraphicsContext3D::FLOAT;
+                case GL_FLOAT_VEC2:
+                    baseType = GL_FLOAT;
                     length = 2;
                     break;
-                case GraphicsContext3D::FLOAT_VEC3:
-                    baseType = GraphicsContext3D::FLOAT;
+                case GL_FLOAT_VEC3:
+                    baseType = GL_FLOAT;
                     length = 3;
                     break;
-                case GraphicsContext3D::FLOAT_VEC4:
-                    baseType = GraphicsContext3D::FLOAT;
+                case GL_FLOAT_VEC4:
+                    baseType = GL_FLOAT;
                     length = 4;
                     break;
-                case GraphicsContext3D::FLOAT_MAT2:
-                    baseType = GraphicsContext3D::FLOAT;
+                case GL_FLOAT_MAT2:
+                    baseType = GL_FLOAT;
                     length = 4;
                     break;
-                case GraphicsContext3D::FLOAT_MAT3:
-                    baseType = GraphicsContext3D::FLOAT;
+                case GL_FLOAT_MAT3:
+                    baseType = GL_FLOAT;
                     length = 9;
                     break;
-                case GraphicsContext3D::FLOAT_MAT4:
-                    baseType = GraphicsContext3D::FLOAT;
+                case GL_FLOAT_MAT4:
+                    baseType = GL_FLOAT;
                     length = 16;
                     break;
-                case GraphicsContext3D::SAMPLER_2D:
-                case GraphicsContext3D::SAMPLER_CUBE:
-                    baseType = GraphicsContext3D::INT;
+                case GL_SAMPLER_2D:
+                case GL_SAMPLER_CUBE:
+                    baseType = GL_INT;
                     length = 1;
                     break;
                 default:
                     // Can't handle this type
-                    synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "getUniform", "unhandled type");
+                    synthesizeGLError(GL_INVALID_VALUE, "getUniform", "unhandled type");
                     return WebGLGetInfo();
                 }
                 switch (baseType) {
-                case GraphicsContext3D::FLOAT: {
-                    GC3Dfloat value[16] = {0};
+                case GL_FLOAT: {
+                    GLfloat value[16] = {0};
                     m_context->getUniformfv(objectOrZero(program), location, value);
                     if (length == 1)
                         return WebGLGetInfo(value[0]);
                     return WebGLGetInfo(Float32Array::create(value, length));
                 }
-                case GraphicsContext3D::INT: {
-                    GC3Dint value[4] = {0};
+                case GL_INT: {
+                    GLint value[4] = {0};
                     m_context->getUniformiv(objectOrZero(program), location, value);
                     if (length == 1)
                         return WebGLGetInfo(value[0]);
                     return WebGLGetInfo(Int32Array::create(value, length));
                 }
-                case GraphicsContext3D::BOOL: {
-                    GC3Dint value[4] = {0};
+                case GL_BOOL: {
+                    GLint value[4] = {0};
                     m_context->getUniformiv(objectOrZero(program), location, value);
                     if (length > 1) {
                         bool boolValue[16] = {0};
@@ -2802,7 +2800,7 @@
         }
     }
     // If we get here, something went wrong in our unfortunately complex logic above
-    synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "getUniform", "unknown error");
+    synthesizeGLError(GL_INVALID_VALUE, "getUniform", "unknown error");
     return WebGLGetInfo();
 }
 
@@ -2817,85 +2815,85 @@
     if (isPrefixReserved(name))
         return 0;
     if (!program->linkStatus()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getUniformLocation", "program not linked");
+        synthesizeGLError(GL_INVALID_OPERATION, "getUniformLocation", "program not linked");
         return 0;
     }
-    GC3Dint uniformLocation = m_context->getUniformLocation(objectOrZero(program), name);
+    GLint uniformLocation = m_context->getUniformLocation(objectOrZero(program), name.utf8().data());
     if (uniformLocation == -1)
         return 0;
     return WebGLUniformLocation::create(program, uniformLocation);
 }
 
-WebGLGetInfo WebGLRenderingContext::getVertexAttrib(GC3Duint index, GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getVertexAttrib(GLuint index, GLenum pname)
 {
     if (isContextLost())
         return WebGLGetInfo();
     if (index >= m_maxVertexAttribs) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "getVertexAttrib", "index out of range");
+        synthesizeGLError(GL_INVALID_VALUE, "getVertexAttrib", "index out of range");
         return WebGLGetInfo();
     }
     const WebGLVertexArrayObjectOES::VertexAttribState& state = m_boundVertexArrayObject->getVertexAttribState(index);
 
-    if (m_angleInstancedArrays && pname == Extensions3D::VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE)
+    if (m_angleInstancedArrays && pname == GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE)
         return WebGLGetInfo(state.divisor);
 
     switch (pname) {
-    case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
+    case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
         if (!state.bufferBinding || !state.bufferBinding->object())
             return WebGLGetInfo();
         return WebGLGetInfo(PassRefPtr<WebGLBuffer>(state.bufferBinding));
-    case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_ENABLED:
+    case GL_VERTEX_ATTRIB_ARRAY_ENABLED:
         return WebGLGetInfo(state.enabled);
-    case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_NORMALIZED:
+    case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED:
         return WebGLGetInfo(state.normalized);
-    case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_SIZE:
+    case GL_VERTEX_ATTRIB_ARRAY_SIZE:
         return WebGLGetInfo(state.size);
-    case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_STRIDE:
+    case GL_VERTEX_ATTRIB_ARRAY_STRIDE:
         return WebGLGetInfo(state.originalStride);
-    case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_TYPE:
+    case GL_VERTEX_ATTRIB_ARRAY_TYPE:
         return WebGLGetInfo(state.type);
-    case GraphicsContext3D::CURRENT_VERTEX_ATTRIB:
+    case GL_CURRENT_VERTEX_ATTRIB:
         return WebGLGetInfo(Float32Array::create(m_vertexAttribValue[index].value, 4));
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getVertexAttrib", "invalid parameter name");
+        synthesizeGLError(GL_INVALID_ENUM, "getVertexAttrib", "invalid parameter name");
         return WebGLGetInfo();
     }
 }
 
-long long WebGLRenderingContext::getVertexAttribOffset(GC3Duint index, GC3Denum pname)
+long long WebGLRenderingContext::getVertexAttribOffset(GLuint index, GLenum pname)
 {
     if (isContextLost())
         return 0;
-    if (pname != GraphicsContext3D::VERTEX_ATTRIB_ARRAY_POINTER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getVertexAttribOffset", "invalid parameter name");
+    if (pname != GL_VERTEX_ATTRIB_ARRAY_POINTER) {
+        synthesizeGLError(GL_INVALID_ENUM, "getVertexAttribOffset", "invalid parameter name");
         return 0;
     }
-    GC3Dsizeiptr result = m_context->getVertexAttribOffset(index, pname);
+    GLsizeiptr result = m_context->getVertexAttribOffset(index, pname);
     return static_cast<long long>(result);
 }
 
-void WebGLRenderingContext::hint(GC3Denum target, GC3Denum mode)
+void WebGLRenderingContext::hint(GLenum target, GLenum mode)
 {
     if (isContextLost())
         return;
     bool isValid = false;
     switch (target) {
-    case GraphicsContext3D::GENERATE_MIPMAP_HINT:
+    case GL_GENERATE_MIPMAP_HINT:
         isValid = true;
         break;
-    case Extensions3D::FRAGMENT_SHADER_DERIVATIVE_HINT_OES: // OES_standard_derivatives
+    case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: // OES_standard_derivatives
         if (m_oesStandardDerivatives)
             isValid = true;
         break;
     }
     if (!isValid) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "hint", "invalid target");
+        synthesizeGLError(GL_INVALID_ENUM, "hint", "invalid target");
         return;
     }
     m_context->hint(target, mode);
 }
 
-GC3Dboolean WebGLRenderingContext::isBuffer(WebGLBuffer* buffer)
+GLboolean WebGLRenderingContext::isBuffer(WebGLBuffer* buffer)
 {
     if (!buffer || isContextLost())
         return 0;
@@ -2911,16 +2909,16 @@
     return m_contextLost;
 }
 
-GC3Dboolean WebGLRenderingContext::isEnabled(GC3Denum cap)
+GLboolean WebGLRenderingContext::isEnabled(GLenum cap)
 {
     if (isContextLost() || !validateCapability("isEnabled", cap))
         return 0;
-    if (cap == GraphicsContext3D::STENCIL_TEST)
+    if (cap == GL_STENCIL_TEST)
         return m_stencilEnabled;
     return m_context->isEnabled(cap);
 }
 
-GC3Dboolean WebGLRenderingContext::isFramebuffer(WebGLFramebuffer* framebuffer)
+GLboolean WebGLRenderingContext::isFramebuffer(WebGLFramebuffer* framebuffer)
 {
     if (!framebuffer || isContextLost())
         return 0;
@@ -2931,7 +2929,7 @@
     return m_context->isFramebuffer(framebuffer->object());
 }
 
-GC3Dboolean WebGLRenderingContext::isProgram(WebGLProgram* program)
+GLboolean WebGLRenderingContext::isProgram(WebGLProgram* program)
 {
     if (!program || isContextLost())
         return 0;
@@ -2939,7 +2937,7 @@
     return m_context->isProgram(program->object());
 }
 
-GC3Dboolean WebGLRenderingContext::isRenderbuffer(WebGLRenderbuffer* renderbuffer)
+GLboolean WebGLRenderingContext::isRenderbuffer(WebGLRenderbuffer* renderbuffer)
 {
     if (!renderbuffer || isContextLost())
         return 0;
@@ -2950,7 +2948,7 @@
     return m_context->isRenderbuffer(renderbuffer->object());
 }
 
-GC3Dboolean WebGLRenderingContext::isShader(WebGLShader* shader)
+GLboolean WebGLRenderingContext::isShader(WebGLShader* shader)
 {
     if (!shader || isContextLost())
         return 0;
@@ -2958,7 +2956,7 @@
     return m_context->isShader(shader->object());
 }
 
-GC3Dboolean WebGLRenderingContext::isTexture(WebGLTexture* texture)
+GLboolean WebGLRenderingContext::isTexture(WebGLTexture* texture)
 {
     if (!texture || isContextLost())
         return 0;
@@ -2969,7 +2967,7 @@
     return m_context->isTexture(texture->object());
 }
 
-void WebGLRenderingContext::lineWidth(GC3Dfloat width)
+void WebGLRenderingContext::lineWidth(GLfloat width)
 {
     if (isContextLost())
         return;
@@ -2985,52 +2983,54 @@
     program->increaseLinkCount();
 }
 
-void WebGLRenderingContext::pixelStorei(GC3Denum pname, GC3Dint param)
+void WebGLRenderingContext::pixelStorei(GLenum pname, GLint param)
 {
     if (isContextLost())
         return;
     switch (pname) {
-    case GraphicsContext3D::UNPACK_FLIP_Y_WEBGL:
+    case GC3D_UNPACK_FLIP_Y_WEBGL:
         m_unpackFlipY = param;
         break;
-    case GraphicsContext3D::UNPACK_PREMULTIPLY_ALPHA_WEBGL:
+    case GC3D_UNPACK_PREMULTIPLY_ALPHA_WEBGL:
         m_unpackPremultiplyAlpha = param;
         break;
-    case GraphicsContext3D::UNPACK_COLORSPACE_CONVERSION_WEBGL:
-        if (param == GraphicsContext3D::BROWSER_DEFAULT_WEBGL || param == GraphicsContext3D::NONE)
-            m_unpackColorspaceConversion = static_cast<GC3Denum>(param);
-        else {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "pixelStorei", "invalid parameter for UNPACK_COLORSPACE_CONVERSION_WEBGL");
+    case GC3D_UNPACK_COLORSPACE_CONVERSION_WEBGL:
+        if (static_cast<GLenum>(param) == GC3D_BROWSER_DEFAULT_WEBGL || param == GL_NONE) {
+            m_unpackColorspaceConversion = static_cast<GLenum>(param);
+        } else {
+            synthesizeGLError(GL_INVALID_VALUE, "pixelStorei", "invalid parameter for UNPACK_COLORSPACE_CONVERSION_WEBGL");
             return;
         }
         break;
-    case GraphicsContext3D::PACK_ALIGNMENT:
-    case GraphicsContext3D::UNPACK_ALIGNMENT:
+    case GL_PACK_ALIGNMENT:
+    case GL_UNPACK_ALIGNMENT:
         if (param == 1 || param == 2 || param == 4 || param == 8) {
-            if (pname == GraphicsContext3D::PACK_ALIGNMENT)
+            if (pname == GL_PACK_ALIGNMENT) {
                 m_packAlignment = param;
-            else // GraphicsContext3D::UNPACK_ALIGNMENT:
+                m_drawingBuffer->setPackAlignment(param);
+            } else { // GL_UNPACK_ALIGNMENT:
                 m_unpackAlignment = param;
+            }
             m_context->pixelStorei(pname, param);
         } else {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "pixelStorei", "invalid parameter for alignment");
+            synthesizeGLError(GL_INVALID_VALUE, "pixelStorei", "invalid parameter for alignment");
             return;
         }
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "pixelStorei", "invalid parameter name");
+        synthesizeGLError(GL_INVALID_ENUM, "pixelStorei", "invalid parameter name");
         return;
     }
 }
 
-void WebGLRenderingContext::polygonOffset(GC3Dfloat factor, GC3Dfloat units)
+void WebGLRenderingContext::polygonOffset(GLfloat factor, GLfloat units)
 {
     if (isContextLost())
         return;
     m_context->polygonOffset(factor, units);
 }
 
-void WebGLRenderingContext::readPixels(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, ArrayBufferView* pixels)
+void WebGLRenderingContext::readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, ArrayBufferView* pixels)
 {
     if (isContextLost())
         return;
@@ -3039,52 +3039,52 @@
     ASSERT(canvas()->originClean());
     // Validate input parameters.
     if (!pixels) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "readPixels", "no destination ArrayBufferView");
+        synthesizeGLError(GL_INVALID_VALUE, "readPixels", "no destination ArrayBufferView");
         return;
     }
     switch (format) {
-    case GraphicsContext3D::ALPHA:
-    case GraphicsContext3D::RGB:
-    case GraphicsContext3D::RGBA:
+    case GL_ALPHA:
+    case GL_RGB:
+    case GL_RGBA:
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "readPixels", "invalid format");
+        synthesizeGLError(GL_INVALID_ENUM, "readPixels", "invalid format");
         return;
     }
     switch (type) {
-    case GraphicsContext3D::UNSIGNED_BYTE:
-    case GraphicsContext3D::UNSIGNED_SHORT_5_6_5:
-    case GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4:
-    case GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1:
+    case GL_UNSIGNED_BYTE:
+    case GL_UNSIGNED_SHORT_5_6_5:
+    case GL_UNSIGNED_SHORT_4_4_4_4:
+    case GL_UNSIGNED_SHORT_5_5_5_1:
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "readPixels", "invalid type");
+        synthesizeGLError(GL_INVALID_ENUM, "readPixels", "invalid type");
         return;
     }
-    if (format != GraphicsContext3D::RGBA || type != GraphicsContext3D::UNSIGNED_BYTE) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "readPixels", "format not RGBA or type not UNSIGNED_BYTE");
+    if (format != GL_RGBA || type != GL_UNSIGNED_BYTE) {
+        synthesizeGLError(GL_INVALID_OPERATION, "readPixels", "format not RGBA or type not UNSIGNED_BYTE");
         return;
     }
     // Validate array type against pixel type.
-    if (pixels->getType() != ArrayBufferView::TypeUint8) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "readPixels", "ArrayBufferView not Uint8Array");
+    if (pixels->type() != ArrayBufferView::TypeUint8) {
+        synthesizeGLError(GL_INVALID_OPERATION, "readPixels", "ArrayBufferView not Uint8Array");
         return;
     }
     const char* reason = "framebuffer incomplete";
-    if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, "readPixels", reason);
+    if (m_framebufferBinding && !m_framebufferBinding->onAccess(m_context.get(), &reason)) {
+        synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, "readPixels", reason);
         return;
     }
     // Calculate array size, taking into consideration of PACK_ALIGNMENT.
-    unsigned int totalBytesRequired = 0;
-    unsigned int padding = 0;
-    GC3Denum error = m_context->computeImageSizeInBytes(format, type, width, height, m_packAlignment, &totalBytesRequired, &padding);
-    if (error != GraphicsContext3D::NO_ERROR) {
+    unsigned totalBytesRequired = 0;
+    unsigned padding = 0;
+    GLenum error = WebGLImageConversion::computeImageSizeInBytes(format, type, width, height, m_packAlignment, &totalBytesRequired, &padding);
+    if (error != GL_NO_ERROR) {
         synthesizeGLError(error, "readPixels", "invalid dimensions");
         return;
     }
     if (pixels->byteLength() < totalBytesRequired) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "readPixels", "ArrayBufferView not large enough for dimensions");
+        synthesizeGLError(GL_INVALID_OPERATION, "readPixels", "ArrayBufferView not large enough for dimensions");
         return;
     }
 
@@ -3101,8 +3101,8 @@
     // when alpha is off, readPixels should set alpha to 255 instead of 0.
     if (!m_framebufferBinding && !m_context->getContextAttributes().alpha) {
         unsigned char* pixels = reinterpret_cast<unsigned char*>(data);
-        for (GC3Dsizei iy = 0; iy < height; ++iy) {
-            for (GC3Dsizei ix = 0; ix < width; ++ix) {
+        for (GLsizei iy = 0; iy < height; ++iy) {
+            for (GLsizei ix = 0; ix < width; ++ix) {
                 pixels[3] = 255;
                 pixels += 4;
             }
@@ -3112,65 +3112,65 @@
 #endif
 }
 
-void WebGLRenderingContext::renderbufferStorage(GC3Denum target, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height)
+void WebGLRenderingContext::renderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
 {
     if (isContextLost())
         return;
-    if (target != GraphicsContext3D::RENDERBUFFER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "renderbufferStorage", "invalid target");
+    if (target != GL_RENDERBUFFER) {
+        synthesizeGLError(GL_INVALID_ENUM, "renderbufferStorage", "invalid target");
         return;
     }
     if (!m_renderbufferBinding || !m_renderbufferBinding->object()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "renderbufferStorage", "no bound renderbuffer");
+        synthesizeGLError(GL_INVALID_OPERATION, "renderbufferStorage", "no bound renderbuffer");
         return;
     }
     if (!validateSize("renderbufferStorage", width, height))
         return;
     switch (internalformat) {
-    case GraphicsContext3D::DEPTH_COMPONENT16:
-    case GraphicsContext3D::RGBA4:
-    case GraphicsContext3D::RGB5_A1:
-    case GraphicsContext3D::RGB565:
-    case GraphicsContext3D::STENCIL_INDEX8:
+    case GL_DEPTH_COMPONENT16:
+    case GL_RGBA4:
+    case GL_RGB5_A1:
+    case GL_RGB565:
+    case GL_STENCIL_INDEX8:
         m_context->renderbufferStorage(target, internalformat, width, height);
         m_renderbufferBinding->setInternalFormat(internalformat);
         m_renderbufferBinding->setSize(width, height);
         m_renderbufferBinding->deleteEmulatedStencilBuffer(m_context.get());
         break;
-    case GraphicsContext3D::DEPTH_STENCIL:
+    case GL_DEPTH_STENCIL_OES:
         if (isDepthStencilSupported()) {
-            m_context->renderbufferStorage(target, Extensions3D::DEPTH24_STENCIL8, width, height);
+            m_context->renderbufferStorage(target, GL_DEPTH24_STENCIL8_OES, width, height);
         } else {
             WebGLRenderbuffer* emulatedStencilBuffer = ensureEmulatedStencilBuffer(target, m_renderbufferBinding.get());
             if (!emulatedStencilBuffer) {
-                synthesizeGLError(GraphicsContext3D::OUT_OF_MEMORY, "renderbufferStorage", "out of memory");
+                synthesizeGLError(GL_OUT_OF_MEMORY, "renderbufferStorage", "out of memory");
                 return;
             }
-            m_context->renderbufferStorage(target, GraphicsContext3D::DEPTH_COMPONENT16, width, height);
+            m_context->renderbufferStorage(target, GL_DEPTH_COMPONENT16, width, height);
             m_context->bindRenderbuffer(target, objectOrZero(emulatedStencilBuffer));
-            m_context->renderbufferStorage(target, GraphicsContext3D::STENCIL_INDEX8, width, height);
+            m_context->renderbufferStorage(target, GL_STENCIL_INDEX8, width, height);
             m_context->bindRenderbuffer(target, objectOrZero(m_renderbufferBinding.get()));
             emulatedStencilBuffer->setSize(width, height);
-            emulatedStencilBuffer->setInternalFormat(GraphicsContext3D::STENCIL_INDEX8);
+            emulatedStencilBuffer->setInternalFormat(GL_STENCIL_INDEX8);
         }
         m_renderbufferBinding->setSize(width, height);
         m_renderbufferBinding->setInternalFormat(internalformat);
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "renderbufferStorage", "invalid internalformat");
+        synthesizeGLError(GL_INVALID_ENUM, "renderbufferStorage", "invalid internalformat");
         return;
     }
     applyStencilTest();
 }
 
-void WebGLRenderingContext::sampleCoverage(GC3Dfloat value, GC3Dboolean invert)
+void WebGLRenderingContext::sampleCoverage(GLfloat value, GLboolean invert)
 {
     if (isContextLost())
         return;
     m_context->sampleCoverage(value, invert);
 }
 
-void WebGLRenderingContext::scissor(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height)
+void WebGLRenderingContext::scissor(GLint x, GLint y, GLsizei width, GLsizei height)
 {
     if (isContextLost())
         return;
@@ -3187,10 +3187,10 @@
     if (!validateString("shaderSource", stringWithoutComments))
         return;
     shader->setSource(string);
-    m_context->shaderSource(objectOrZero(shader), stringWithoutComments);
+    m_context->shaderSource(objectOrZero(shader), stringWithoutComments.utf8().data());
 }
 
-void WebGLRenderingContext::stencilFunc(GC3Denum func, GC3Dint ref, GC3Duint mask)
+void WebGLRenderingContext::stencilFunc(GLenum func, GLint ref, GLuint mask)
 {
     if (isContextLost())
         return;
@@ -3203,35 +3203,35 @@
     m_context->stencilFunc(func, ref, mask);
 }
 
-void WebGLRenderingContext::stencilFuncSeparate(GC3Denum face, GC3Denum func, GC3Dint ref, GC3Duint mask)
+void WebGLRenderingContext::stencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
 {
     if (isContextLost())
         return;
     if (!validateStencilOrDepthFunc("stencilFuncSeparate", func))
         return;
     switch (face) {
-    case GraphicsContext3D::FRONT_AND_BACK:
+    case GL_FRONT_AND_BACK:
         m_stencilFuncRef = ref;
         m_stencilFuncRefBack = ref;
         m_stencilFuncMask = mask;
         m_stencilFuncMaskBack = mask;
         break;
-    case GraphicsContext3D::FRONT:
+    case GL_FRONT:
         m_stencilFuncRef = ref;
         m_stencilFuncMask = mask;
         break;
-    case GraphicsContext3D::BACK:
+    case GL_BACK:
         m_stencilFuncRefBack = ref;
         m_stencilFuncMaskBack = mask;
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "stencilFuncSeparate", "invalid face");
+        synthesizeGLError(GL_INVALID_ENUM, "stencilFuncSeparate", "invalid face");
         return;
     }
     m_context->stencilFuncSeparate(face, func, ref, mask);
 }
 
-void WebGLRenderingContext::stencilMask(GC3Duint mask)
+void WebGLRenderingContext::stencilMask(GLuint mask)
 {
     if (isContextLost())
         return;
@@ -3240,43 +3240,55 @@
     m_context->stencilMask(mask);
 }
 
-void WebGLRenderingContext::stencilMaskSeparate(GC3Denum face, GC3Duint mask)
+void WebGLRenderingContext::stencilMaskSeparate(GLenum face, GLuint mask)
 {
     if (isContextLost())
         return;
     switch (face) {
-    case GraphicsContext3D::FRONT_AND_BACK:
+    case GL_FRONT_AND_BACK:
         m_stencilMask = mask;
         m_stencilMaskBack = mask;
         break;
-    case GraphicsContext3D::FRONT:
+    case GL_FRONT:
         m_stencilMask = mask;
         break;
-    case GraphicsContext3D::BACK:
+    case GL_BACK:
         m_stencilMaskBack = mask;
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "stencilMaskSeparate", "invalid face");
+        synthesizeGLError(GL_INVALID_ENUM, "stencilMaskSeparate", "invalid face");
         return;
     }
     m_context->stencilMaskSeparate(face, mask);
 }
 
-void WebGLRenderingContext::stencilOp(GC3Denum fail, GC3Denum zfail, GC3Denum zpass)
+void WebGLRenderingContext::stencilOp(GLenum fail, GLenum zfail, GLenum zpass)
 {
     if (isContextLost())
         return;
     m_context->stencilOp(fail, zfail, zpass);
 }
 
-void WebGLRenderingContext::stencilOpSeparate(GC3Denum face, GC3Denum fail, GC3Denum zfail, GC3Denum zpass)
+void WebGLRenderingContext::stencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
 {
     if (isContextLost())
         return;
     m_context->stencilOpSeparate(face, fail, zfail, zpass);
 }
 
-void WebGLRenderingContext::texImage2DBase(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& exceptionState)
+GLenum WebGLRenderingContext::convertTexInternalFormat(GLenum internalformat, GLenum type)
+{
+    // Convert to sized internal formats that are renderable with GL_CHROMIUM_color_buffer_float_rgb(a).
+    if (type == GL_FLOAT && internalformat == GL_RGBA
+        && extensionsUtil()->isExtensionEnabled("GL_CHROMIUM_color_buffer_float_rgba"))
+        return GL_RGBA32F_EXT;
+    if (type == GL_FLOAT && internalformat == GL_RGB
+        && extensionsUtil()->isExtensionEnabled("GL_CHROMIUM_color_buffer_float_rgb"))
+        return GL_RGB32F_EXT;
+    return internalformat;
+}
+
+void WebGLRenderingContext::texImage2DBase(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels, ExceptionState& exceptionState)
 {
     // All calling functions check isContextLost, so a duplicate check is not needed here.
     // FIXME: Handle errors.
@@ -3285,42 +3297,41 @@
     ASSERT(tex);
     ASSERT(!level || !WebGLTexture::isNPOT(width, height));
     ASSERT(!pixels || validateSettableTexFormat("texImage2D", internalformat));
-    m_context->texImage2D(target, level, internalformat, width, height,
-                          border, format, type, pixels);
+    m_context->texImage2D(target, level, convertTexInternalFormat(internalformat, type), width, height, border, format, type, pixels);
     tex->setLevelInfo(target, level, internalformat, width, height, type);
 }
 
-void WebGLRenderingContext::texImage2DImpl(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& exceptionState)
+void WebGLRenderingContext::texImage2DImpl(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, Image* image, WebGLImageConversion::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& exceptionState)
 {
     // All calling functions check isContextLost, so a duplicate check is not needed here.
     Vector<uint8_t> data;
-    GraphicsContext3D::ImageExtractor imageExtractor(image, domSource, premultiplyAlpha, m_unpackColorspaceConversion == GraphicsContext3D::NONE);
+    WebGLImageConversion::ImageExtractor imageExtractor(image, domSource, premultiplyAlpha, m_unpackColorspaceConversion == GL_NONE);
     if (!imageExtractor.extractSucceeded()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texImage2D", "bad image data");
+        synthesizeGLError(GL_INVALID_VALUE, "texImage2D", "bad image data");
         return;
     }
-    GraphicsContext3D::DataFormat sourceDataFormat = imageExtractor.imageSourceFormat();
-    GraphicsContext3D::AlphaOp alphaOp = imageExtractor.imageAlphaOp();
+    WebGLImageConversion::DataFormat sourceDataFormat = imageExtractor.imageSourceFormat();
+    WebGLImageConversion::AlphaOp alphaOp = imageExtractor.imageAlphaOp();
     const void* imagePixelData = imageExtractor.imagePixelData();
 
     bool needConversion = true;
-    if (type == GraphicsContext3D::UNSIGNED_BYTE && sourceDataFormat == GraphicsContext3D::DataFormatRGBA8 && format == GraphicsContext3D::RGBA && alphaOp == GraphicsContext3D::AlphaDoNothing && !flipY)
+    if (type == GL_UNSIGNED_BYTE && sourceDataFormat == WebGLImageConversion::DataFormatRGBA8 && format == GL_RGBA && alphaOp == WebGLImageConversion::AlphaDoNothing && !flipY)
         needConversion = false;
     else {
-        if (!m_context->packImageData(image, imagePixelData, format, type, flipY, alphaOp, sourceDataFormat, imageExtractor.imageWidth(), imageExtractor.imageHeight(), imageExtractor.imageSourceUnpackAlignment(), data)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texImage2D", "packImage error");
+        if (!WebGLImageConversion::packImageData(image, imagePixelData, format, type, flipY, alphaOp, sourceDataFormat, imageExtractor.imageWidth(), imageExtractor.imageHeight(), imageExtractor.imageSourceUnpackAlignment(), data)) {
+            synthesizeGLError(GL_INVALID_VALUE, "texImage2D", "packImage error");
             return;
         }
     }
 
     if (m_unpackAlignment != 1)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
     texImage2DBase(target, level, internalformat, image->width(), image->height(), 0, format, type, needConversion ? data.data() : imagePixelData, exceptionState);
     if (m_unpackAlignment != 1)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
-bool WebGLRenderingContext::validateTexFunc(const char* functionName, TexFuncValidationFunctionType functionType, TexFuncValidationSourceType sourceType, GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, GC3Dint xoffset, GC3Dint yoffset)
+bool WebGLRenderingContext::validateTexFunc(const char* functionName, TexFuncValidationFunctionType functionType, TexFuncValidationSourceType sourceType, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, GLint xoffset, GLint yoffset)
 {
     if (!validateTexFuncParameters(functionName, functionType, target, level, internalformat, width, height, border, format, type))
         return false;
@@ -3331,7 +3342,7 @@
 
     if (functionType == NotTexSubImage2D) {
         if (level && WebGLTexture::isNPOT(width, height)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level > 0 not power of 2");
+            synthesizeGLError(GL_INVALID_VALUE, functionName, "level > 0 not power of 2");
             return false;
         }
         // For SourceArrayBufferView, function validateTexFuncData() would handle whether to validate the SettableTexFormat
@@ -3347,15 +3358,15 @@
             return false;
         // Before checking if it is in the range, check if overflow happens first.
         if (xoffset + width < 0 || yoffset + height < 0) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "bad dimensions");
+            synthesizeGLError(GL_INVALID_VALUE, functionName, "bad dimensions");
             return false;
         }
         if (xoffset + width > texture->getWidth(target, level) || yoffset + height > texture->getHeight(target, level)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "dimensions out of range");
+            synthesizeGLError(GL_INVALID_VALUE, functionName, "dimensions out of range");
             return false;
         }
         if (texture->getInternalFormat(target, level) != format || texture->getType(target, level) != type) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type and format do not match texture");
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "type and format do not match texture");
             return false;
         }
     }
@@ -3368,7 +3379,7 @@
     IntSize size(width, height);
     ImageBuffer* buf = m_generatedImageCache.imageBuffer(size);
     if (!buf) {
-        synthesizeGLError(GraphicsContext3D::OUT_OF_MEMORY, "texImage2D", "out of memory");
+        synthesizeGLError(GL_OUT_OF_MEMORY, "texImage2D", "out of memory");
         return 0;
     }
 
@@ -3378,9 +3389,9 @@
     return buf->copyImage(ImageBuffer::fastCopyImageMode());
 }
 
-void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-    GC3Dsizei width, GC3Dsizei height, GC3Dint border,
-    GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& exceptionState)
+void WebGLRenderingContext::texImage2D(GLenum target, GLint level, GLenum internalformat,
+    GLsizei width, GLsizei height, GLint border,
+    GLenum format, GLenum type, ArrayBufferView* pixels, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateTexFuncData("texImage2D", level, width, height, format, type, pixels, NullAllowed)
         || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceArrayBufferView, target, level, internalformat, width, height, border, format, type, 0, 0))
@@ -3389,24 +3400,20 @@
     Vector<uint8_t> tempData;
     bool changeUnpackAlignment = false;
     if (data && (m_unpackFlipY || m_unpackPremultiplyAlpha)) {
-        if (!m_context->extractTextureData(width, height, format, type,
-                                           m_unpackAlignment,
-                                           m_unpackFlipY, m_unpackPremultiplyAlpha,
-                                           data,
-                                           tempData))
+        if (!WebGLImageConversion::extractTextureData(width, height, format, type, m_unpackAlignment, m_unpackFlipY, m_unpackPremultiplyAlpha, data, tempData))
             return;
         data = tempData.data();
         changeUnpackAlignment = true;
     }
     if (changeUnpackAlignment)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
     texImage2DBase(target, level, internalformat, width, height, border, format, type, data, exceptionState);
     if (changeUnpackAlignment)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
-void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-    GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& exceptionState)
+void WebGLRenderingContext::texImage2D(GLenum target, GLint level, GLenum internalformat,
+    GLenum format, GLenum type, ImageData* pixels, ExceptionState& exceptionState)
 {
     if (isContextLost() || !pixels || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceImageData, target, level, internalformat, pixels->width(), pixels->height(), 0, format, type, 0, 0))
         return;
@@ -3414,23 +3421,23 @@
     bool needConversion = true;
     // The data from ImageData is always of format RGBA8.
     // No conversion is needed if destination format is RGBA and type is USIGNED_BYTE and no Flip or Premultiply operation is required.
-    if (!m_unpackFlipY && !m_unpackPremultiplyAlpha && format == GraphicsContext3D::RGBA && type == GraphicsContext3D::UNSIGNED_BYTE)
+    if (!m_unpackFlipY && !m_unpackPremultiplyAlpha && format == GL_RGBA && type == GL_UNSIGNED_BYTE)
         needConversion = false;
     else {
-        if (!m_context->extractImageData(pixels->data()->data(), pixels->size(), format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texImage2D", "bad image data");
+        if (!WebGLImageConversion::extractImageData(pixels->data()->data(), pixels->size(), format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
+            synthesizeGLError(GL_INVALID_VALUE, "texImage2D", "bad image data");
             return;
         }
     }
     if (m_unpackAlignment != 1)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
     texImage2DBase(target, level, internalformat, pixels->width(), pixels->height(), 0, format, type, needConversion ? data.data() : pixels->data()->data(), exceptionState);
     if (m_unpackAlignment != 1)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
-void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-    GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& exceptionState)
+void WebGLRenderingContext::texImage2D(GLenum target, GLint level, GLenum internalformat,
+    GLenum format, GLenum type, HTMLImageElement* image, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateHTMLImageElement("texImage2D", image, exceptionState))
         return;
@@ -3442,11 +3449,11 @@
     if (!imageForRender || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLImageElement, target, level, internalformat, imageForRender->width(), imageForRender->height(), 0, format, type, 0, 0))
         return;
 
-    texImage2DImpl(target, level, internalformat, format, type, imageForRender.get(), GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
+    texImage2DImpl(target, level, internalformat, format, type, imageForRender.get(), WebGLImageConversion::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
-void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-    GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
+void WebGLRenderingContext::texImage2D(GLenum target, GLint level, GLenum internalformat,
+    GLenum format, GLenum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateHTMLCanvasElement("texImage2D", canvas, exceptionState) || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLCanvasElement, target, level, internalformat, canvas->width(), canvas->height(), 0, format, type, 0, 0))
         return;
@@ -3454,17 +3461,17 @@
     WebGLTexture* texture = validateTextureBinding("texImage2D", target, true);
     // If possible, copy from the canvas element directly to the texture
     // via the GPU, without a read-back to system memory.
-    if (GraphicsContext3D::TEXTURE_2D == target && texture) {
+    if (GL_TEXTURE_2D == target && texture) {
         if (!canvas->is3D()) {
             ImageBuffer* buffer = canvas->buffer();
-            if (buffer && buffer->copyToPlatformTexture(*m_context.get(), texture->object(), internalformat, type,
+            if (buffer && buffer->copyToPlatformTexture(m_context.get(), texture->object(), internalformat, type,
                 level, m_unpackPremultiplyAlpha, m_unpackFlipY)) {
                 texture->setLevelInfo(target, level, internalformat, canvas->width(), canvas->height(), type);
                 return;
             }
         } else {
             WebGLRenderingContext* gl = toWebGLRenderingContext(canvas->renderingContext());
-            if (gl && gl->m_drawingBuffer->copyToPlatformTexture(*m_context.get(), texture->object(), internalformat, type,
+            if (gl && gl->m_drawingBuffer->copyToPlatformTexture(m_context.get(), texture->object(), internalformat, type,
                 level, m_unpackPremultiplyAlpha, m_unpackFlipY)) {
                 texture->setLevelInfo(target, level, internalformat, canvas->width(), canvas->height(), type);
                 return;
@@ -3476,7 +3483,7 @@
     if (imageData)
         texImage2D(target, level, internalformat, format, type, imageData.get(), exceptionState);
     else
-        texImage2DImpl(target, level, internalformat, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
+        texImage2DImpl(target, level, internalformat, format, type, canvas->copiedImage(), WebGLImageConversion::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
 PassRefPtr<Image> WebGLRenderingContext::videoFrameToImage(HTMLVideoElement* video, BackingStoreCopy backingStoreCopy)
@@ -3484,7 +3491,7 @@
     IntSize size(video->videoWidth(), video->videoHeight());
     ImageBuffer* buf = m_generatedImageCache.imageBuffer(size);
     if (!buf) {
-        synthesizeGLError(GraphicsContext3D::OUT_OF_MEMORY, "texImage2D", "out of memory");
+        synthesizeGLError(GL_OUT_OF_MEMORY, "texImage2D", "out of memory");
         return 0;
     }
     IntRect destRect(0, 0, size.width(), size.height());
@@ -3493,8 +3500,8 @@
     return buf->copyImage(backingStoreCopy);
 }
 
-void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-    GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& exceptionState)
+void WebGLRenderingContext::texImage2D(GLenum target, GLint level, GLenum internalformat,
+    GLenum format, GLenum type, HTMLVideoElement* video, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateHTMLVideoElement("texImage2D", video, exceptionState)
         || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLVideoElement, target, level, internalformat, video->videoWidth(), video->videoHeight(), 0, format, type, 0, 0))
@@ -3503,7 +3510,7 @@
     // Go through the fast path doing a GPU-GPU textures copy without a readback to system memory if possible.
     // Otherwise, it will fall back to the normal SW path.
     WebGLTexture* texture = validateTextureBinding("texImage2D", target, true);
-    if (GraphicsContext3D::TEXTURE_2D == target && texture) {
+    if (GL_TEXTURE_2D == target && texture) {
         if (video->copyVideoTextureToPlatformTexture(m_context.get(), texture->object(), level, type, internalformat, m_unpackPremultiplyAlpha, m_unpackFlipY)) {
             texture->setLevelInfo(target, level, internalformat, video->videoWidth(), video->videoHeight(), type);
             return;
@@ -3514,10 +3521,10 @@
     RefPtr<Image> image = videoFrameToImage(video, ImageBuffer::fastCopyImageMode());
     if (!image)
         return;
-    texImage2DImpl(target, level, internalformat, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
+    texImage2DImpl(target, level, internalformat, format, type, image.get(), WebGLImageConversion::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
-void WebGLRenderingContext::texParameter(GC3Denum target, GC3Denum pname, GC3Dfloat paramf, GC3Dint parami, bool isFloat)
+void WebGLRenderingContext::texParameter(GLenum target, GLenum pname, GLfloat paramf, GLint parami, bool isFloat)
 {
     if (isContextLost())
         return;
@@ -3525,25 +3532,25 @@
     if (!tex)
         return;
     switch (pname) {
-    case GraphicsContext3D::TEXTURE_MIN_FILTER:
-    case GraphicsContext3D::TEXTURE_MAG_FILTER:
+    case GL_TEXTURE_MIN_FILTER:
+    case GL_TEXTURE_MAG_FILTER:
         break;
-    case GraphicsContext3D::TEXTURE_WRAP_S:
-    case GraphicsContext3D::TEXTURE_WRAP_T:
-        if ((isFloat && paramf != GraphicsContext3D::CLAMP_TO_EDGE && paramf != GraphicsContext3D::MIRRORED_REPEAT && paramf != GraphicsContext3D::REPEAT)
-            || (!isFloat && parami != GraphicsContext3D::CLAMP_TO_EDGE && parami != GraphicsContext3D::MIRRORED_REPEAT && parami != GraphicsContext3D::REPEAT)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "texParameter", "invalid parameter");
+    case GL_TEXTURE_WRAP_S:
+    case GL_TEXTURE_WRAP_T:
+        if ((isFloat && paramf != GL_CLAMP_TO_EDGE && paramf != GL_MIRRORED_REPEAT && paramf != GL_REPEAT)
+            || (!isFloat && parami != GL_CLAMP_TO_EDGE && parami != GL_MIRRORED_REPEAT && parami != GL_REPEAT)) {
+            synthesizeGLError(GL_INVALID_ENUM, "texParameter", "invalid parameter");
             return;
         }
         break;
-    case Extensions3D::TEXTURE_MAX_ANISOTROPY_EXT: // EXT_texture_filter_anisotropic
+    case GL_TEXTURE_MAX_ANISOTROPY_EXT: // EXT_texture_filter_anisotropic
         if (!m_extTextureFilterAnisotropic) {
-            synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "texParameter", "invalid parameter, EXT_texture_filter_anisotropic not enabled");
+            synthesizeGLError(GL_INVALID_ENUM, "texParameter", "invalid parameter, EXT_texture_filter_anisotropic not enabled");
             return;
         }
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "texParameter", "invalid parameter name");
+        synthesizeGLError(GL_INVALID_ENUM, "texParameter", "invalid parameter name");
         return;
     }
     if (isFloat) {
@@ -3555,17 +3562,17 @@
     }
 }
 
-void WebGLRenderingContext::texParameterf(GC3Denum target, GC3Denum pname, GC3Dfloat param)
+void WebGLRenderingContext::texParameterf(GLenum target, GLenum pname, GLfloat param)
 {
     texParameter(target, pname, param, 0, true);
 }
 
-void WebGLRenderingContext::texParameteri(GC3Denum target, GC3Denum pname, GC3Dint param)
+void WebGLRenderingContext::texParameteri(GLenum target, GLenum pname, GLint param)
 {
     texParameter(target, pname, 0, param, false);
 }
 
-void WebGLRenderingContext::texSubImage2DBase(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& exceptionState)
+void WebGLRenderingContext::texSubImage2DBase(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels, ExceptionState& exceptionState)
 {
     // FIXME: Handle errors.
     ASSERT(!isContextLost());
@@ -3586,39 +3593,39 @@
     m_context->texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
 }
 
-void WebGLRenderingContext::texSubImage2DImpl(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& exceptionState)
+void WebGLRenderingContext::texSubImage2DImpl(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, Image* image, WebGLImageConversion::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& exceptionState)
 {
     // All calling functions check isContextLost, so a duplicate check is not needed here.
     Vector<uint8_t> data;
-    GraphicsContext3D::ImageExtractor imageExtractor(image, domSource, premultiplyAlpha, m_unpackColorspaceConversion == GraphicsContext3D::NONE);
+    WebGLImageConversion::ImageExtractor imageExtractor(image, domSource, premultiplyAlpha, m_unpackColorspaceConversion == GL_NONE);
     if (!imageExtractor.extractSucceeded()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texSubImage2D", "bad image");
+        synthesizeGLError(GL_INVALID_VALUE, "texSubImage2D", "bad image");
         return;
     }
-    GraphicsContext3D::DataFormat sourceDataFormat = imageExtractor.imageSourceFormat();
-    GraphicsContext3D::AlphaOp alphaOp = imageExtractor.imageAlphaOp();
+    WebGLImageConversion::DataFormat sourceDataFormat = imageExtractor.imageSourceFormat();
+    WebGLImageConversion::AlphaOp alphaOp = imageExtractor.imageAlphaOp();
     const void* imagePixelData = imageExtractor.imagePixelData();
 
     bool needConversion = true;
-    if (type == GraphicsContext3D::UNSIGNED_BYTE && sourceDataFormat == GraphicsContext3D::DataFormatRGBA8 && format == GraphicsContext3D::RGBA && alphaOp == GraphicsContext3D::AlphaDoNothing && !flipY)
+    if (type == GL_UNSIGNED_BYTE && sourceDataFormat == WebGLImageConversion::DataFormatRGBA8 && format == GL_RGBA && alphaOp == WebGLImageConversion::AlphaDoNothing && !flipY)
         needConversion = false;
     else {
-        if (!m_context->packImageData(image, imagePixelData, format, type, flipY, alphaOp, sourceDataFormat, imageExtractor.imageWidth(), imageExtractor.imageHeight(), imageExtractor.imageSourceUnpackAlignment(), data)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texImage2D", "bad image data");
+        if (!WebGLImageConversion::packImageData(image, imagePixelData, format, type, flipY, alphaOp, sourceDataFormat, imageExtractor.imageWidth(), imageExtractor.imageHeight(), imageExtractor.imageSourceUnpackAlignment(), data)) {
+            synthesizeGLError(GL_INVALID_VALUE, "texImage2D", "bad image data");
             return;
         }
     }
 
     if (m_unpackAlignment != 1)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
     texSubImage2DBase(target, level, xoffset, yoffset, image->width(), image->height(), format, type,  needConversion ? data.data() : imagePixelData, exceptionState);
     if (m_unpackAlignment != 1)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
-void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-    GC3Dsizei width, GC3Dsizei height,
-    GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& exceptionState)
+void WebGLRenderingContext::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+    GLsizei width, GLsizei height,
+    GLenum format, GLenum type, ArrayBufferView* pixels, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateTexFuncData("texSubImage2D", level, width, height, format, type, pixels, NullNotAllowed)
         || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceArrayBufferView, target, level, format, width, height, 0, format, type, xoffset, yoffset))
@@ -3627,7 +3634,7 @@
     Vector<uint8_t> tempData;
     bool changeUnpackAlignment = false;
     if (data && (m_unpackFlipY || m_unpackPremultiplyAlpha)) {
-        if (!m_context->extractTextureData(width, height, format, type,
+        if (!WebGLImageConversion::extractTextureData(width, height, format, type,
                                            m_unpackAlignment,
                                            m_unpackFlipY, m_unpackPremultiplyAlpha,
                                            data,
@@ -3637,14 +3644,14 @@
         changeUnpackAlignment = true;
     }
     if (changeUnpackAlignment)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
     texSubImage2DBase(target, level, xoffset, yoffset, width, height, format, type, data, exceptionState);
     if (changeUnpackAlignment)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
-void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-    GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& exceptionState)
+void WebGLRenderingContext::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+    GLenum format, GLenum type, ImageData* pixels, ExceptionState& exceptionState)
 {
     if (isContextLost() || !pixels || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceImageData, target, level, format,  pixels->width(), pixels->height(), 0, format, type, xoffset, yoffset))
         return;
@@ -3653,23 +3660,23 @@
     bool needConversion = true;
     // The data from ImageData is always of format RGBA8.
     // No conversion is needed if destination format is RGBA and type is USIGNED_BYTE and no Flip or Premultiply operation is required.
-    if (format == GraphicsContext3D::RGBA && type == GraphicsContext3D::UNSIGNED_BYTE && !m_unpackFlipY && !m_unpackPremultiplyAlpha)
+    if (format == GL_RGBA && type == GL_UNSIGNED_BYTE && !m_unpackFlipY && !m_unpackPremultiplyAlpha)
         needConversion = false;
     else {
-        if (!m_context->extractImageData(pixels->data()->data(), pixels->size(), format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texSubImage2D", "bad image data");
+        if (!WebGLImageConversion::extractImageData(pixels->data()->data(), pixels->size(), format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
+            synthesizeGLError(GL_INVALID_VALUE, "texSubImage2D", "bad image data");
             return;
         }
     }
     if (m_unpackAlignment != 1)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
     texSubImage2DBase(target, level, xoffset, yoffset, pixels->width(), pixels->height(), format, type, needConversion ? data.data() : pixels->data()->data(), exceptionState);
     if (m_unpackAlignment != 1)
-        m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+        m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
 }
 
-void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-    GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& exceptionState)
+void WebGLRenderingContext::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+    GLenum format, GLenum type, HTMLImageElement* image, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateHTMLImageElement("texSubImage2D", image, exceptionState))
         return;
@@ -3681,11 +3688,11 @@
     if (!imageForRender || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLImageElement, target, level, format, imageForRender->width(), imageForRender->height(), 0, format, type, xoffset, yoffset))
         return;
 
-    texSubImage2DImpl(target, level, xoffset, yoffset, format, type, imageForRender.get(), GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
+    texSubImage2DImpl(target, level, xoffset, yoffset, format, type, imageForRender.get(), WebGLImageConversion::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
-void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-    GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
+void WebGLRenderingContext::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+    GLenum format, GLenum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateHTMLCanvasElement("texSubImage2D", canvas, exceptionState)
         || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLCanvasElement, target, level, format, canvas->width(), canvas->height(), 0, format, type, xoffset, yoffset))
@@ -3695,11 +3702,11 @@
     if (imageData)
         texSubImage2D(target, level, xoffset, yoffset, format, type, imageData.get(), exceptionState);
     else
-        texSubImage2DImpl(target, level, xoffset, yoffset, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
+        texSubImage2DImpl(target, level, xoffset, yoffset, format, type, canvas->copiedImage(), WebGLImageConversion::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
-void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-    GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& exceptionState)
+void WebGLRenderingContext::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+    GLenum format, GLenum type, HTMLVideoElement* video, ExceptionState& exceptionState)
 {
     if (isContextLost() || !validateHTMLVideoElement("texSubImage2D", video, exceptionState)
         || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLVideoElement, target, level, format, video->videoWidth(), video->videoHeight(), 0, format, type, xoffset, yoffset))
@@ -3708,16 +3715,16 @@
     RefPtr<Image> image = videoFrameToImage(video, ImageBuffer::fastCopyImageMode());
     if (!image)
         return;
-    texSubImage2DImpl(target, level, xoffset, yoffset, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
+    texSubImage2DImpl(target, level, xoffset, yoffset, format, type, image.get(), WebGLImageConversion::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
 }
 
-void WebGLRenderingContext::uniform1f(const WebGLUniformLocation* location, GC3Dfloat x)
+void WebGLRenderingContext::uniform1f(const WebGLUniformLocation* location, GLfloat x)
 {
     if (isContextLost() || !location)
         return;
 
     if (location->program() != m_currentProgram) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform1f", "location not for current program");
+        synthesizeGLError(GL_INVALID_OPERATION, "uniform1f", "location not for current program");
         return;
     }
 
@@ -3732,7 +3739,7 @@
     m_context->uniform1fv(location->location(), v->length(), v->data());
 }
 
-void WebGLRenderingContext::uniform1fv(const WebGLUniformLocation* location, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::uniform1fv(const WebGLUniformLocation* location, GLfloat* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformParameters("uniform1fv", location, v, size, 1))
         return;
@@ -3740,13 +3747,13 @@
     m_context->uniform1fv(location->location(), size, v);
 }
 
-void WebGLRenderingContext::uniform1i(const WebGLUniformLocation* location, GC3Dint x)
+void WebGLRenderingContext::uniform1i(const WebGLUniformLocation* location, GLint x)
 {
     if (isContextLost() || !location)
         return;
 
     if (location->program() != m_currentProgram) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform1i", "location not for current program");
+        synthesizeGLError(GL_INVALID_OPERATION, "uniform1i", "location not for current program");
         return;
     }
 
@@ -3761,7 +3768,7 @@
     m_context->uniform1iv(location->location(), v->length(), v->data());
 }
 
-void WebGLRenderingContext::uniform1iv(const WebGLUniformLocation* location, GC3Dint* v, GC3Dsizei size)
+void WebGLRenderingContext::uniform1iv(const WebGLUniformLocation* location, GLint* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformParameters("uniform1iv", location, v, size, 1))
         return;
@@ -3769,13 +3776,13 @@
     m_context->uniform1iv(location->location(), size, v);
 }
 
-void WebGLRenderingContext::uniform2f(const WebGLUniformLocation* location, GC3Dfloat x, GC3Dfloat y)
+void WebGLRenderingContext::uniform2f(const WebGLUniformLocation* location, GLfloat x, GLfloat y)
 {
     if (isContextLost() || !location)
         return;
 
     if (location->program() != m_currentProgram) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform2f", "location not for current program");
+        synthesizeGLError(GL_INVALID_OPERATION, "uniform2f", "location not for current program");
         return;
     }
 
@@ -3790,7 +3797,7 @@
     m_context->uniform2fv(location->location(), v->length() / 2, v->data());
 }
 
-void WebGLRenderingContext::uniform2fv(const WebGLUniformLocation* location, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::uniform2fv(const WebGLUniformLocation* location, GLfloat* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformParameters("uniform2fv", location, v, size, 2))
         return;
@@ -3798,13 +3805,13 @@
     m_context->uniform2fv(location->location(), size / 2, v);
 }
 
-void WebGLRenderingContext::uniform2i(const WebGLUniformLocation* location, GC3Dint x, GC3Dint y)
+void WebGLRenderingContext::uniform2i(const WebGLUniformLocation* location, GLint x, GLint y)
 {
     if (isContextLost() || !location)
         return;
 
     if (location->program() != m_currentProgram) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform2i", "location not for current program");
+        synthesizeGLError(GL_INVALID_OPERATION, "uniform2i", "location not for current program");
         return;
     }
 
@@ -3819,7 +3826,7 @@
     m_context->uniform2iv(location->location(), v->length() / 2, v->data());
 }
 
-void WebGLRenderingContext::uniform2iv(const WebGLUniformLocation* location, GC3Dint* v, GC3Dsizei size)
+void WebGLRenderingContext::uniform2iv(const WebGLUniformLocation* location, GLint* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformParameters("uniform2iv", location, v, size, 2))
         return;
@@ -3827,13 +3834,13 @@
     m_context->uniform2iv(location->location(), size / 2, v);
 }
 
-void WebGLRenderingContext::uniform3f(const WebGLUniformLocation* location, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z)
+void WebGLRenderingContext::uniform3f(const WebGLUniformLocation* location, GLfloat x, GLfloat y, GLfloat z)
 {
     if (isContextLost() || !location)
         return;
 
     if (location->program() != m_currentProgram) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform3f", "location not for current program");
+        synthesizeGLError(GL_INVALID_OPERATION, "uniform3f", "location not for current program");
         return;
     }
 
@@ -3848,7 +3855,7 @@
     m_context->uniform3fv(location->location(), v->length() / 3, v->data());
 }
 
-void WebGLRenderingContext::uniform3fv(const WebGLUniformLocation* location, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::uniform3fv(const WebGLUniformLocation* location, GLfloat* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformParameters("uniform3fv", location, v, size, 3))
         return;
@@ -3856,13 +3863,13 @@
     m_context->uniform3fv(location->location(), size / 3, v);
 }
 
-void WebGLRenderingContext::uniform3i(const WebGLUniformLocation* location, GC3Dint x, GC3Dint y, GC3Dint z)
+void WebGLRenderingContext::uniform3i(const WebGLUniformLocation* location, GLint x, GLint y, GLint z)
 {
     if (isContextLost() || !location)
         return;
 
     if (location->program() != m_currentProgram) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform3i", "location not for current program");
+        synthesizeGLError(GL_INVALID_OPERATION, "uniform3i", "location not for current program");
         return;
     }
 
@@ -3877,7 +3884,7 @@
     m_context->uniform3iv(location->location(), v->length() / 3, v->data());
 }
 
-void WebGLRenderingContext::uniform3iv(const WebGLUniformLocation* location, GC3Dint* v, GC3Dsizei size)
+void WebGLRenderingContext::uniform3iv(const WebGLUniformLocation* location, GLint* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformParameters("uniform3iv", location, v, size, 3))
         return;
@@ -3885,13 +3892,13 @@
     m_context->uniform3iv(location->location(), size / 3, v);
 }
 
-void WebGLRenderingContext::uniform4f(const WebGLUniformLocation* location, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z, GC3Dfloat w)
+void WebGLRenderingContext::uniform4f(const WebGLUniformLocation* location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
 {
     if (isContextLost() || !location)
         return;
 
     if (location->program() != m_currentProgram) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform4f", "location not for current program");
+        synthesizeGLError(GL_INVALID_OPERATION, "uniform4f", "location not for current program");
         return;
     }
 
@@ -3906,7 +3913,7 @@
     m_context->uniform4fv(location->location(), v->length() / 4, v->data());
 }
 
-void WebGLRenderingContext::uniform4fv(const WebGLUniformLocation* location, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::uniform4fv(const WebGLUniformLocation* location, GLfloat* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformParameters("uniform4fv", location, v, size, 4))
         return;
@@ -3914,13 +3921,13 @@
     m_context->uniform4fv(location->location(), size / 4, v);
 }
 
-void WebGLRenderingContext::uniform4i(const WebGLUniformLocation* location, GC3Dint x, GC3Dint y, GC3Dint z, GC3Dint w)
+void WebGLRenderingContext::uniform4i(const WebGLUniformLocation* location, GLint x, GLint y, GLint z, GLint w)
 {
     if (isContextLost() || !location)
         return;
 
     if (location->program() != m_currentProgram) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform4i", "location not for current program");
+        synthesizeGLError(GL_INVALID_OPERATION, "uniform4i", "location not for current program");
         return;
     }
 
@@ -3935,7 +3942,7 @@
     m_context->uniform4iv(location->location(), v->length() / 4, v->data());
 }
 
-void WebGLRenderingContext::uniform4iv(const WebGLUniformLocation* location, GC3Dint* v, GC3Dsizei size)
+void WebGLRenderingContext::uniform4iv(const WebGLUniformLocation* location, GLint* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformParameters("uniform4iv", location, v, size, 4))
         return;
@@ -3943,42 +3950,42 @@
     m_context->uniform4iv(location->location(), size / 4, v);
 }
 
-void WebGLRenderingContext::uniformMatrix2fv(const WebGLUniformLocation* location, GC3Dboolean transpose, Float32Array* v)
+void WebGLRenderingContext::uniformMatrix2fv(const WebGLUniformLocation* location, GLboolean transpose, Float32Array* v)
 {
     if (isContextLost() || !validateUniformMatrixParameters("uniformMatrix2fv", location, transpose, v, 4))
         return;
     m_context->uniformMatrix2fv(location->location(), v->length() / 4, transpose, v->data());
 }
 
-void WebGLRenderingContext::uniformMatrix2fv(const WebGLUniformLocation* location, GC3Dboolean transpose, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::uniformMatrix2fv(const WebGLUniformLocation* location, GLboolean transpose, GLfloat* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformMatrixParameters("uniformMatrix2fv", location, transpose, v, size, 4))
         return;
     m_context->uniformMatrix2fv(location->location(), size / 4, transpose, v);
 }
 
-void WebGLRenderingContext::uniformMatrix3fv(const WebGLUniformLocation* location, GC3Dboolean transpose, Float32Array* v)
+void WebGLRenderingContext::uniformMatrix3fv(const WebGLUniformLocation* location, GLboolean transpose, Float32Array* v)
 {
     if (isContextLost() || !validateUniformMatrixParameters("uniformMatrix3fv", location, transpose, v, 9))
         return;
     m_context->uniformMatrix3fv(location->location(), v->length() / 9, transpose, v->data());
 }
 
-void WebGLRenderingContext::uniformMatrix3fv(const WebGLUniformLocation* location, GC3Dboolean transpose, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::uniformMatrix3fv(const WebGLUniformLocation* location, GLboolean transpose, GLfloat* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformMatrixParameters("uniformMatrix3fv", location, transpose, v, size, 9))
         return;
     m_context->uniformMatrix3fv(location->location(), size / 9, transpose, v);
 }
 
-void WebGLRenderingContext::uniformMatrix4fv(const WebGLUniformLocation* location, GC3Dboolean transpose, Float32Array* v)
+void WebGLRenderingContext::uniformMatrix4fv(const WebGLUniformLocation* location, GLboolean transpose, Float32Array* v)
 {
     if (isContextLost() || !validateUniformMatrixParameters("uniformMatrix4fv", location, transpose, v, 16))
         return;
     m_context->uniformMatrix4fv(location->location(), v->length() / 16, transpose, v->data());
 }
 
-void WebGLRenderingContext::uniformMatrix4fv(const WebGLUniformLocation* location, GC3Dboolean transpose, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::uniformMatrix4fv(const WebGLUniformLocation* location, GLboolean transpose, GLfloat* v, GLsizei size)
 {
     if (isContextLost() || !validateUniformMatrixParameters("uniformMatrix4fv", location, transpose, v, size, 16))
         return;
@@ -3993,12 +4000,12 @@
     if (deleted)
         program = 0;
     if (program && !program->linkStatus()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "useProgram", "program not valid");
+        synthesizeGLError(GL_INVALID_OPERATION, "useProgram", "program not valid");
         return;
     }
     if (m_currentProgram != program) {
         if (m_currentProgram)
-            m_currentProgram->onDetached(graphicsContext3D());
+            m_currentProgram->onDetached(m_context.get());
         m_currentProgram = program;
         m_context->useProgram(objectOrZero(program));
         if (program)
@@ -4013,124 +4020,124 @@
     m_context->validateProgram(objectOrZero(program));
 }
 
-void WebGLRenderingContext::vertexAttrib1f(GC3Duint index, GC3Dfloat v0)
+void WebGLRenderingContext::vertexAttrib1f(GLuint index, GLfloat v0)
 {
     vertexAttribfImpl("vertexAttrib1f", index, 1, v0, 0.0f, 0.0f, 1.0f);
 }
 
-void WebGLRenderingContext::vertexAttrib1fv(GC3Duint index, Float32Array* v)
+void WebGLRenderingContext::vertexAttrib1fv(GLuint index, Float32Array* v)
 {
     vertexAttribfvImpl("vertexAttrib1fv", index, v, 1);
 }
 
-void WebGLRenderingContext::vertexAttrib1fv(GC3Duint index, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::vertexAttrib1fv(GLuint index, GLfloat* v, GLsizei size)
 {
     vertexAttribfvImpl("vertexAttrib1fv", index, v, size, 1);
 }
 
-void WebGLRenderingContext::vertexAttrib2f(GC3Duint index, GC3Dfloat v0, GC3Dfloat v1)
+void WebGLRenderingContext::vertexAttrib2f(GLuint index, GLfloat v0, GLfloat v1)
 {
     vertexAttribfImpl("vertexAttrib2f", index, 2, v0, v1, 0.0f, 1.0f);
 }
 
-void WebGLRenderingContext::vertexAttrib2fv(GC3Duint index, Float32Array* v)
+void WebGLRenderingContext::vertexAttrib2fv(GLuint index, Float32Array* v)
 {
     vertexAttribfvImpl("vertexAttrib2fv", index, v, 2);
 }
 
-void WebGLRenderingContext::vertexAttrib2fv(GC3Duint index, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::vertexAttrib2fv(GLuint index, GLfloat* v, GLsizei size)
 {
     vertexAttribfvImpl("vertexAttrib2fv", index, v, size, 2);
 }
 
-void WebGLRenderingContext::vertexAttrib3f(GC3Duint index, GC3Dfloat v0, GC3Dfloat v1, GC3Dfloat v2)
+void WebGLRenderingContext::vertexAttrib3f(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2)
 {
     vertexAttribfImpl("vertexAttrib3f", index, 3, v0, v1, v2, 1.0f);
 }
 
-void WebGLRenderingContext::vertexAttrib3fv(GC3Duint index, Float32Array* v)
+void WebGLRenderingContext::vertexAttrib3fv(GLuint index, Float32Array* v)
 {
     vertexAttribfvImpl("vertexAttrib3fv", index, v, 3);
 }
 
-void WebGLRenderingContext::vertexAttrib3fv(GC3Duint index, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::vertexAttrib3fv(GLuint index, GLfloat* v, GLsizei size)
 {
     vertexAttribfvImpl("vertexAttrib3fv", index, v, size, 3);
 }
 
-void WebGLRenderingContext::vertexAttrib4f(GC3Duint index, GC3Dfloat v0, GC3Dfloat v1, GC3Dfloat v2, GC3Dfloat v3)
+void WebGLRenderingContext::vertexAttrib4f(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3)
 {
     vertexAttribfImpl("vertexAttrib4f", index, 4, v0, v1, v2, v3);
 }
 
-void WebGLRenderingContext::vertexAttrib4fv(GC3Duint index, Float32Array* v)
+void WebGLRenderingContext::vertexAttrib4fv(GLuint index, Float32Array* v)
 {
     vertexAttribfvImpl("vertexAttrib4fv", index, v, 4);
 }
 
-void WebGLRenderingContext::vertexAttrib4fv(GC3Duint index, GC3Dfloat* v, GC3Dsizei size)
+void WebGLRenderingContext::vertexAttrib4fv(GLuint index, GLfloat* v, GLsizei size)
 {
     vertexAttribfvImpl("vertexAttrib4fv", index, v, size, 4);
 }
 
-void WebGLRenderingContext::vertexAttribPointer(GC3Duint index, GC3Dint size, GC3Denum type, GC3Dboolean normalized, GC3Dsizei stride, long long offset)
+void WebGLRenderingContext::vertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, long long offset)
 {
     if (isContextLost())
         return;
     switch (type) {
-    case GraphicsContext3D::BYTE:
-    case GraphicsContext3D::UNSIGNED_BYTE:
-    case GraphicsContext3D::SHORT:
-    case GraphicsContext3D::UNSIGNED_SHORT:
-    case GraphicsContext3D::FLOAT:
+    case GL_BYTE:
+    case GL_UNSIGNED_BYTE:
+    case GL_SHORT:
+    case GL_UNSIGNED_SHORT:
+    case GL_FLOAT:
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "vertexAttribPointer", "invalid type");
+        synthesizeGLError(GL_INVALID_ENUM, "vertexAttribPointer", "invalid type");
         return;
     }
     if (index >= m_maxVertexAttribs) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "vertexAttribPointer", "index out of range");
+        synthesizeGLError(GL_INVALID_VALUE, "vertexAttribPointer", "index out of range");
         return;
     }
     if (size < 1 || size > 4 || stride < 0 || stride > 255 || offset < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "vertexAttribPointer", "bad size, stride or offset");
+        synthesizeGLError(GL_INVALID_VALUE, "vertexAttribPointer", "bad size, stride or offset");
         return;
     }
     if (!m_boundArrayBuffer) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "vertexAttribPointer", "no bound ARRAY_BUFFER");
+        synthesizeGLError(GL_INVALID_OPERATION, "vertexAttribPointer", "no bound ARRAY_BUFFER");
         return;
     }
     // Determine the number of elements the bound buffer can hold, given the offset, size, type and stride
-    unsigned int typeSize = sizeInBytes(type);
+    unsigned typeSize = sizeInBytes(type);
     if (!typeSize) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "vertexAttribPointer", "invalid type");
+        synthesizeGLError(GL_INVALID_ENUM, "vertexAttribPointer", "invalid type");
         return;
     }
-    if ((stride % typeSize) || (static_cast<GC3Dintptr>(offset) % typeSize)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "vertexAttribPointer", "stride or offset not valid for type");
+    if ((stride % typeSize) || (static_cast<GLintptr>(offset) % typeSize)) {
+        synthesizeGLError(GL_INVALID_OPERATION, "vertexAttribPointer", "stride or offset not valid for type");
         return;
     }
-    GC3Dsizei bytesPerElement = size * typeSize;
+    GLsizei bytesPerElement = size * typeSize;
 
-    m_boundVertexArrayObject->setVertexAttribState(index, bytesPerElement, size, type, normalized, stride, static_cast<GC3Dintptr>(offset), m_boundArrayBuffer);
-    m_context->vertexAttribPointer(index, size, type, normalized, stride, static_cast<GC3Dintptr>(offset));
+    m_boundVertexArrayObject->setVertexAttribState(index, bytesPerElement, size, type, normalized, stride, static_cast<GLintptr>(offset), m_boundArrayBuffer);
+    m_context->vertexAttribPointer(index, size, type, normalized, stride, static_cast<GLintptr>(offset));
 }
 
-void WebGLRenderingContext::vertexAttribDivisorANGLE(GC3Duint index, GC3Duint divisor)
+void WebGLRenderingContext::vertexAttribDivisorANGLE(GLuint index, GLuint divisor)
 {
     if (isContextLost())
         return;
 
     if (index >= m_maxVertexAttribs) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "vertexAttribDivisorANGLE", "index out of range");
+        synthesizeGLError(GL_INVALID_VALUE, "vertexAttribDivisorANGLE", "index out of range");
         return;
     }
 
     m_boundVertexArrayObject->setVertexAttribDivisor(index, divisor);
-    m_context->extensions()->vertexAttribDivisorANGLE(index, divisor);
+    m_context->vertexAttribDivisorANGLE(index, divisor);
 }
 
-void WebGLRenderingContext::viewport(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height)
+void WebGLRenderingContext::viewport(GLint x, GLint y, GLsizei width, GLsizei height)
 {
     if (isContextLost())
         return;
@@ -4142,7 +4149,7 @@
 void WebGLRenderingContext::forceLostContext(WebGLRenderingContext::LostContextMode mode)
 {
     if (isContextLost()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "loseContext", "context already lost");
+        synthesizeGLError(GL_INVALID_OPERATION, "loseContext", "context already lost");
         return;
     }
 
@@ -4161,7 +4168,7 @@
         // Inform the embedder that a lost context was received. In response, the embedder might
         // decide to take action such as asking the user for permission to use WebGL again.
         if (Frame* frame = canvas()->document().frame())
-            frame->loader().client()->didLoseWebGLContext(m_context->extensions()->getGraphicsResetStatusARB());
+            frame->loader().client()->didLoseWebGLContext(m_context->getGraphicsResetStatusARB());
     }
 
     // Make absolutely sure we do not refer to an already-deleted texture or framebuffer.
@@ -4179,10 +4186,10 @@
     removeAllCompressedTextureFormats();
 
     if (mode != RealLostContext)
-        destroyGraphicsContext3D();
+        destroyContext();
 
     ConsoleDisplayPreference display = (mode == RealLostContext) ? DisplayInConsole: DontDisplayInConsole;
-    synthesizeGLError(GraphicsContext3D::CONTEXT_LOST_WEBGL, "loseContext", "context lost", display);
+    synthesizeGLError(GC3D_CONTEXT_LOST_WEBGL, "loseContext", "context lost", display);
 
     // Don't allow restoration unless the context lost event has both been
     // dispatched and its default behavior prevented.
@@ -4196,13 +4203,13 @@
 void WebGLRenderingContext::forceRestoreContext()
 {
     if (!isContextLost()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "restoreContext", "context not lost");
+        synthesizeGLError(GL_INVALID_OPERATION, "restoreContext", "context not lost");
         return;
     }
 
     if (!m_restoreAllowed) {
         if (m_contextLostMode == SyntheticLostContext)
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "restoreContext", "context restoration not allowed");
+            synthesizeGLError(GL_INVALID_OPERATION, "restoreContext", "context restoration not allowed");
         return;
     }
 
@@ -4215,6 +4222,13 @@
     return m_drawingBuffer->platformLayer();
 }
 
+Extensions3DUtil* WebGLRenderingContext::extensionsUtil()
+{
+    if (!m_extensionsUtil)
+        m_extensionsUtil = adoptPtr(new Extensions3DUtil(m_context.get()));
+    return m_extensionsUtil.get();
+}
+
 void WebGLRenderingContext::removeSharedObject(WebGLSharedObject* object)
 {
     m_contextGroup->removeObject(object);
@@ -4254,25 +4268,25 @@
 {
     if (!isContextLost()) {
         forceLostContext(SyntheticLostContext);
-        destroyGraphicsContext3D();
+        destroyContext();
     }
 }
 
-WebGLGetInfo WebGLRenderingContext::getBooleanParameter(GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getBooleanParameter(GLenum pname)
 {
-    GC3Dboolean value = 0;
+    GLboolean value = 0;
     if (!isContextLost())
         m_context->getBooleanv(pname, &value);
     return WebGLGetInfo(static_cast<bool>(value));
 }
 
-WebGLGetInfo WebGLRenderingContext::getBooleanArrayParameter(GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getBooleanArrayParameter(GLenum pname)
 {
-    if (pname != GraphicsContext3D::COLOR_WRITEMASK) {
+    if (pname != GL_COLOR_WRITEMASK) {
         notImplemented();
         return WebGLGetInfo(0, 0);
     }
-    GC3Dboolean value[4] = {0};
+    GLboolean value[4] = {0};
     if (!isContextLost())
         m_context->getBooleanv(pname, value);
     bool boolValue[4];
@@ -4281,44 +4295,44 @@
     return WebGLGetInfo(boolValue, 4);
 }
 
-WebGLGetInfo WebGLRenderingContext::getFloatParameter(GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getFloatParameter(GLenum pname)
 {
-    GC3Dfloat value = 0;
+    GLfloat value = 0;
     if (!isContextLost())
         m_context->getFloatv(pname, &value);
     return WebGLGetInfo(value);
 }
 
-WebGLGetInfo WebGLRenderingContext::getIntParameter(GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getIntParameter(GLenum pname)
 {
-    GC3Dint value = 0;
+    GLint value = 0;
     if (!isContextLost())
         m_context->getIntegerv(pname, &value);
     return WebGLGetInfo(value);
 }
 
-WebGLGetInfo WebGLRenderingContext::getUnsignedIntParameter(GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getUnsignedIntParameter(GLenum pname)
 {
-    GC3Dint value = 0;
+    GLint value = 0;
     if (!isContextLost())
         m_context->getIntegerv(pname, &value);
-    return WebGLGetInfo(static_cast<unsigned int>(value));
+    return WebGLGetInfo(static_cast<unsigned>(value));
 }
 
-WebGLGetInfo WebGLRenderingContext::getWebGLFloatArrayParameter(GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getWebGLFloatArrayParameter(GLenum pname)
 {
-    GC3Dfloat value[4] = {0};
+    GLfloat value[4] = {0};
     if (!isContextLost())
         m_context->getFloatv(pname, value);
     unsigned length = 0;
     switch (pname) {
-    case GraphicsContext3D::ALIASED_POINT_SIZE_RANGE:
-    case GraphicsContext3D::ALIASED_LINE_WIDTH_RANGE:
-    case GraphicsContext3D::DEPTH_RANGE:
+    case GL_ALIASED_POINT_SIZE_RANGE:
+    case GL_ALIASED_LINE_WIDTH_RANGE:
+    case GL_DEPTH_RANGE:
         length = 2;
         break;
-    case GraphicsContext3D::BLEND_COLOR:
-    case GraphicsContext3D::COLOR_CLEAR_VALUE:
+    case GL_BLEND_COLOR:
+    case GL_COLOR_CLEAR_VALUE:
         length = 4;
         break;
     default:
@@ -4327,18 +4341,18 @@
     return WebGLGetInfo(Float32Array::create(value, length));
 }
 
-WebGLGetInfo WebGLRenderingContext::getWebGLIntArrayParameter(GC3Denum pname)
+WebGLGetInfo WebGLRenderingContext::getWebGLIntArrayParameter(GLenum pname)
 {
-    GC3Dint value[4] = {0};
+    GLint value[4] = {0};
     if (!isContextLost())
         m_context->getIntegerv(pname, value);
     unsigned length = 0;
     switch (pname) {
-    case GraphicsContext3D::MAX_VIEWPORT_DIMS:
+    case GL_MAX_VIEWPORT_DIMS:
         length = 2;
         break;
-    case GraphicsContext3D::SCISSOR_BOX:
-    case GraphicsContext3D::VIEWPORT:
+    case GL_SCISSOR_BOX:
+    case GL_VIEWPORT:
         length = 4;
         break;
     default:
@@ -4377,9 +4391,9 @@
                 texCubeMap = m_textureUnits[ii].m_textureCubeMapBinding.get();
             }
             if (m_textureUnits[ii].m_texture2DBinding && m_textureUnits[ii].m_texture2DBinding->needToUseBlackTexture(flag))
-                m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, objectOrZero(tex2D));
+                m_context->bindTexture(GL_TEXTURE_2D, objectOrZero(tex2D));
             if (m_textureUnits[ii].m_textureCubeMapBinding && m_textureUnits[ii].m_textureCubeMapBinding->needToUseBlackTexture(flag))
-                m_context->bindTexture(GraphicsContext3D::TEXTURE_CUBE_MAP, objectOrZero(texCubeMap));
+                m_context->bindTexture(GL_TEXTURE_CUBE_MAP, objectOrZero(texCubeMap));
         }
     }
     if (resetActiveUnit)
@@ -4391,42 +4405,41 @@
     // All calling functions check isContextLost, so a duplicate check is not needed here.
     unsigned char black[] = {0, 0, 0, 255};
     m_blackTexture2D = createTexture();
-    m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, m_blackTexture2D->object());
-    m_context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, 1, 1,
-                          0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
-    m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, 0);
+    m_context->bindTexture(GL_TEXTURE_2D, m_blackTexture2D->object());
+    m_context->texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1,
+        0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+    m_context->bindTexture(GL_TEXTURE_2D, 0);
     m_blackTextureCubeMap = createTexture();
-    m_context->bindTexture(GraphicsContext3D::TEXTURE_CUBE_MAP, m_blackTextureCubeMap->object());
-    m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X, 0, GraphicsContext3D::RGBA, 1, 1,
-                          0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
-    m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GraphicsContext3D::RGBA, 1, 1,
-                          0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
-    m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GraphicsContext3D::RGBA, 1, 1,
-                          0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
-    m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GraphicsContext3D::RGBA, 1, 1,
-                          0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
-    m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GraphicsContext3D::RGBA, 1, 1,
-                          0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
-    m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GraphicsContext3D::RGBA, 1, 1,
-                          0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
-    m_context->bindTexture(GraphicsContext3D::TEXTURE_CUBE_MAP, 0);
+    m_context->bindTexture(GL_TEXTURE_CUBE_MAP, m_blackTextureCubeMap->object());
+    m_context->texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, 1, 1,
+        0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+    m_context->texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGBA, 1, 1,
+        0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+    m_context->texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGBA, 1, 1,
+        0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+    m_context->texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGBA, 1, 1,
+        0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+    m_context->texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGBA, 1, 1,
+        0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+    m_context->texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGBA, 1, 1,
+        0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+    m_context->bindTexture(GL_TEXTURE_CUBE_MAP, 0);
 }
 
-bool WebGLRenderingContext::isTexInternalFormatColorBufferCombinationValid(GC3Denum texInternalFormat,
-                                                                           GC3Denum colorBufferFormat)
+bool WebGLRenderingContext::isTexInternalFormatColorBufferCombinationValid(GLenum texInternalFormat, GLenum colorBufferFormat)
 {
-    unsigned need = GraphicsContext3D::getChannelBitsByFormat(texInternalFormat);
-    unsigned have = GraphicsContext3D::getChannelBitsByFormat(colorBufferFormat);
+    unsigned need = WebGLImageConversion::getChannelBitsByFormat(texInternalFormat);
+    unsigned have = WebGLImageConversion::getChannelBitsByFormat(colorBufferFormat);
     return (need & have) == need;
 }
 
-GC3Denum WebGLRenderingContext::boundFramebufferColorFormat()
+GLenum WebGLRenderingContext::boundFramebufferColorFormat()
 {
     if (m_framebufferBinding && m_framebufferBinding->object())
         return m_framebufferBinding->colorBufferFormat();
-    if (m_attributes.alpha)
-        return GraphicsContext3D::RGBA;
-    return GraphicsContext3D::RGB;
+    if (m_requestedAttributes->alpha())
+        return GL_RGBA;
+    return GL_RGB;
 }
 
 int WebGLRenderingContext::boundFramebufferWidth()
@@ -4443,38 +4456,38 @@
     return m_drawingBuffer->size().height();
 }
 
-WebGLTexture* WebGLRenderingContext::validateTextureBinding(const char* functionName, GC3Denum target, bool useSixEnumsForCubeMap)
+WebGLTexture* WebGLRenderingContext::validateTextureBinding(const char* functionName, GLenum target, bool useSixEnumsForCubeMap)
 {
     WebGLTexture* tex = 0;
     switch (target) {
-    case GraphicsContext3D::TEXTURE_2D:
+    case GL_TEXTURE_2D:
         tex = m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get();
         break;
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z:
+    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
         if (!useSixEnumsForCubeMap) {
-            synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture target");
+            synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture target");
             return 0;
         }
         tex = m_textureUnits[m_activeTextureUnit].m_textureCubeMapBinding.get();
         break;
-    case GraphicsContext3D::TEXTURE_CUBE_MAP:
+    case GL_TEXTURE_CUBE_MAP:
         if (useSixEnumsForCubeMap) {
-            synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture target");
+            synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture target");
             return 0;
         }
         tex = m_textureUnits[m_activeTextureUnit].m_textureCubeMapBinding.get();
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture target");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture target");
         return 0;
     }
     if (!tex)
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "no texture");
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "no texture");
     return tex;
 }
 
@@ -4482,16 +4495,16 @@
 {
     const unsigned maxWebGLLocationLength = 256;
     if (string.length() > maxWebGLLocationLength) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "location length > 256");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "location length > 256");
         return false;
     }
     return true;
 }
 
-bool WebGLRenderingContext::validateSize(const char* functionName, GC3Dint x, GC3Dint y)
+bool WebGLRenderingContext::validateSize(const char* functionName, GLint x, GLint y)
 {
     if (x < 0 || y < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "size < 0");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "size < 0");
         return false;
     }
     return true;
@@ -4501,119 +4514,119 @@
 {
     for (size_t i = 0; i < string.length(); ++i) {
         if (!validateCharacter(string[i])) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "string not ASCII");
+            synthesizeGLError(GL_INVALID_VALUE, functionName, "string not ASCII");
             return false;
         }
     }
     return true;
 }
 
-bool WebGLRenderingContext::validateTexFuncFormatAndType(const char* functionName, GC3Denum format, GC3Denum type, GC3Dint level)
+bool WebGLRenderingContext::validateTexFuncFormatAndType(const char* functionName, GLenum format, GLenum type, GLint level)
 {
     switch (format) {
-    case GraphicsContext3D::ALPHA:
-    case GraphicsContext3D::LUMINANCE:
-    case GraphicsContext3D::LUMINANCE_ALPHA:
-    case GraphicsContext3D::RGB:
-    case GraphicsContext3D::RGBA:
+    case GL_ALPHA:
+    case GL_LUMINANCE:
+    case GL_LUMINANCE_ALPHA:
+    case GL_RGB:
+    case GL_RGBA:
         break;
-    case GraphicsContext3D::DEPTH_STENCIL:
-    case GraphicsContext3D::DEPTH_COMPONENT:
+    case GL_DEPTH_STENCIL_OES:
+    case GL_DEPTH_COMPONENT:
         if (m_webglDepthTexture)
             break;
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "depth texture formats not enabled");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "depth texture formats not enabled");
         return false;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture format");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture format");
         return false;
     }
 
     switch (type) {
-    case GraphicsContext3D::UNSIGNED_BYTE:
-    case GraphicsContext3D::UNSIGNED_SHORT_5_6_5:
-    case GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4:
-    case GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1:
+    case GL_UNSIGNED_BYTE:
+    case GL_UNSIGNED_SHORT_5_6_5:
+    case GL_UNSIGNED_SHORT_4_4_4_4:
+    case GL_UNSIGNED_SHORT_5_5_5_1:
         break;
-    case GraphicsContext3D::FLOAT:
+    case GL_FLOAT:
         if (m_oesTextureFloat)
             break;
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture type");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture type");
         return false;
-    case GraphicsContext3D::HALF_FLOAT_OES:
+    case GL_HALF_FLOAT_OES:
         if (m_oesTextureHalfFloat)
             break;
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture type");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture type");
         return false;
-    case GraphicsContext3D::UNSIGNED_INT:
-    case GraphicsContext3D::UNSIGNED_INT_24_8:
-    case GraphicsContext3D::UNSIGNED_SHORT:
+    case GL_UNSIGNED_INT:
+    case GL_UNSIGNED_INT_24_8_OES:
+    case GL_UNSIGNED_SHORT:
         if (m_webglDepthTexture)
             break;
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture type");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture type");
         return false;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture type");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture type");
         return false;
     }
 
     // Verify that the combination of format and type is supported.
     switch (format) {
-    case GraphicsContext3D::ALPHA:
-    case GraphicsContext3D::LUMINANCE:
-    case GraphicsContext3D::LUMINANCE_ALPHA:
-        if (type != GraphicsContext3D::UNSIGNED_BYTE
-            && type != GraphicsContext3D::FLOAT
-            && type != GraphicsContext3D::HALF_FLOAT_OES) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for format");
+    case GL_ALPHA:
+    case GL_LUMINANCE:
+    case GL_LUMINANCE_ALPHA:
+        if (type != GL_UNSIGNED_BYTE
+            && type != GL_FLOAT
+            && type != GL_HALF_FLOAT_OES) {
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for format");
             return false;
         }
         break;
-    case GraphicsContext3D::RGB:
-        if (type != GraphicsContext3D::UNSIGNED_BYTE
-            && type != GraphicsContext3D::UNSIGNED_SHORT_5_6_5
-            && type != GraphicsContext3D::FLOAT
-            && type != GraphicsContext3D::HALF_FLOAT_OES) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for RGB format");
+    case GL_RGB:
+        if (type != GL_UNSIGNED_BYTE
+            && type != GL_UNSIGNED_SHORT_5_6_5
+            && type != GL_FLOAT
+            && type != GL_HALF_FLOAT_OES) {
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for RGB format");
             return false;
         }
         break;
-    case GraphicsContext3D::RGBA:
-        if (type != GraphicsContext3D::UNSIGNED_BYTE
-            && type != GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4
-            && type != GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1
-            && type != GraphicsContext3D::FLOAT
-            && type != GraphicsContext3D::HALF_FLOAT_OES) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for RGBA format");
+    case GL_RGBA:
+        if (type != GL_UNSIGNED_BYTE
+            && type != GL_UNSIGNED_SHORT_4_4_4_4
+            && type != GL_UNSIGNED_SHORT_5_5_5_1
+            && type != GL_FLOAT
+            && type != GL_HALF_FLOAT_OES) {
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for RGBA format");
             return false;
         }
         break;
-    case GraphicsContext3D::DEPTH_COMPONENT:
+    case GL_DEPTH_COMPONENT:
         if (!m_webglDepthTexture) {
-            synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid format. DEPTH_COMPONENT not enabled");
+            synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid format. DEPTH_COMPONENT not enabled");
             return false;
         }
-        if (type != GraphicsContext3D::UNSIGNED_SHORT
-            && type != GraphicsContext3D::UNSIGNED_INT) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for DEPTH_COMPONENT format");
+        if (type != GL_UNSIGNED_SHORT
+            && type != GL_UNSIGNED_INT) {
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for DEPTH_COMPONENT format");
             return false;
         }
         if (level > 0) {
-          synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "level must be 0 for DEPTH_COMPONENT format");
-          return false;
-        }
-        break;
-    case GraphicsContext3D::DEPTH_STENCIL:
-        if (!m_webglDepthTexture) {
-            synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid format. DEPTH_STENCIL not enabled");
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "level must be 0 for DEPTH_COMPONENT format");
             return false;
         }
-        if (type != GraphicsContext3D::UNSIGNED_INT_24_8) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for DEPTH_STENCIL format");
+        break;
+    case GL_DEPTH_STENCIL_OES:
+        if (!m_webglDepthTexture) {
+            synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid format. DEPTH_STENCIL not enabled");
+            return false;
+        }
+        if (type != GL_UNSIGNED_INT_24_8_OES) {
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for DEPTH_STENCIL format");
             return false;
         }
         if (level > 0) {
-          synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "level must be 0 for DEPTH_STENCIL format");
-          return false;
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "level must be 0 for DEPTH_STENCIL format");
+            return false;
         }
         break;
     default:
@@ -4623,27 +4636,27 @@
     return true;
 }
 
-bool WebGLRenderingContext::validateTexFuncLevel(const char* functionName, GC3Denum target, GC3Dint level)
+bool WebGLRenderingContext::validateTexFuncLevel(const char* functionName, GLenum target, GLint level)
 {
     if (level < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level < 0");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "level < 0");
         return false;
     }
     switch (target) {
-    case GraphicsContext3D::TEXTURE_2D:
+    case GL_TEXTURE_2D:
         if (level >= m_maxTextureLevel) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level out of range");
+            synthesizeGLError(GL_INVALID_VALUE, functionName, "level out of range");
             return false;
         }
         break;
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z:
+    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
         if (level >= m_maxCubeMapTextureLevel) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level out of range");
+            synthesizeGLError(GL_INVALID_VALUE, functionName, "level out of range");
             return false;
         }
         break;
@@ -4654,46 +4667,46 @@
 }
 
 bool WebGLRenderingContext::validateTexFuncDimensions(const char* functionName, TexFuncValidationFunctionType functionType,
-    GC3Denum target, GC3Dint level, GC3Dsizei width, GC3Dsizei height)
+    GLenum target, GLint level, GLsizei width, GLsizei height)
 {
     if (width < 0 || height < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height < 0");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "width or height < 0");
         return false;
     }
 
     switch (target) {
-    case GraphicsContext3D::TEXTURE_2D:
+    case GL_TEXTURE_2D:
         if (width > (m_maxTextureSize >> level) || height > (m_maxTextureSize >> level)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height out of range");
+            synthesizeGLError(GL_INVALID_VALUE, functionName, "width or height out of range");
             return false;
         }
         break;
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z:
-    case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z:
+    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
         if (functionType != TexSubImage2D && width != height) {
-          synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width != height for cube map");
-          return false;
+            synthesizeGLError(GL_INVALID_VALUE, functionName, "width != height for cube map");
+            return false;
         }
         // No need to check height here. For texImage width == height.
         // For texSubImage that will be checked when checking yoffset + height is in range.
         if (width > (m_maxCubeMapTextureSize >> level)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height out of range for cube map");
+            synthesizeGLError(GL_INVALID_VALUE, functionName, "width or height out of range for cube map");
             return false;
         }
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid target");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid target");
         return false;
     }
     return true;
 }
 
-bool WebGLRenderingContext::validateTexFuncParameters(const char* functionName, TexFuncValidationFunctionType functionType, GC3Denum target,
-    GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type)
+bool WebGLRenderingContext::validateTexFuncParameters(const char* functionName, TexFuncValidationFunctionType functionType, GLenum target,
+    GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type)
 {
     // We absolutely have to validate the format and type combination.
     // The texImage2D entry points taking HTMLImage, etc. will produce
@@ -4705,29 +4718,25 @@
         return false;
 
     if (format != internalformat) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "format != internalformat");
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "format != internalformat");
         return false;
     }
 
     if (border) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "border != 0");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "border != 0");
         return false;
     }
 
     return true;
 }
 
-bool WebGLRenderingContext::validateTexFuncData(const char* functionName, GC3Dint level,
-                                                GC3Dsizei width, GC3Dsizei height,
-                                                GC3Denum format, GC3Denum type,
-                                                ArrayBufferView* pixels,
-                                                NullDisposition disposition)
+bool WebGLRenderingContext::validateTexFuncData(const char* functionName, GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, ArrayBufferView* pixels, NullDisposition disposition)
 {
     // All calling functions check isContextLost, so a duplicate check is not needed here.
     if (!pixels) {
         if (disposition == NullAllowed)
             return true;
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no pixels");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no pixels");
         return false;
     }
 
@@ -4737,31 +4746,31 @@
         return false;
 
     switch (type) {
-    case GraphicsContext3D::UNSIGNED_BYTE:
-        if (pixels->getType() != ArrayBufferView::TypeUint8) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type UNSIGNED_BYTE but ArrayBufferView not Uint8Array");
+    case GL_UNSIGNED_BYTE:
+        if (pixels->type() != ArrayBufferView::TypeUint8) {
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "type UNSIGNED_BYTE but ArrayBufferView not Uint8Array");
             return false;
         }
         break;
-    case GraphicsContext3D::UNSIGNED_SHORT_5_6_5:
-    case GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4:
-    case GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1:
-        if (pixels->getType() != ArrayBufferView::TypeUint16) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type UNSIGNED_SHORT but ArrayBufferView not Uint16Array");
+    case GL_UNSIGNED_SHORT_5_6_5:
+    case GL_UNSIGNED_SHORT_4_4_4_4:
+    case GL_UNSIGNED_SHORT_5_5_5_1:
+        if (pixels->type() != ArrayBufferView::TypeUint16) {
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "type UNSIGNED_SHORT but ArrayBufferView not Uint16Array");
             return false;
         }
         break;
-    case GraphicsContext3D::FLOAT: // OES_texture_float
-        if (pixels->getType() != ArrayBufferView::TypeFloat32) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type FLOAT but ArrayBufferView not Float32Array");
+    case GL_FLOAT: // OES_texture_float
+        if (pixels->type() != ArrayBufferView::TypeFloat32) {
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "type FLOAT but ArrayBufferView not Float32Array");
             return false;
         }
         break;
-    case GraphicsContext3D::HALF_FLOAT_OES: // OES_texture_half_float
+    case GL_HALF_FLOAT_OES: // OES_texture_half_float
         // As per the specification, ArrayBufferView should be null when
         // OES_texture_half_float is enabled.
         if (pixels) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type HALF_FLOAT_OES but ArrayBufferView is not NULL");
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "type HALF_FLOAT_OES but ArrayBufferView is not NULL");
             return false;
         }
         break;
@@ -4769,49 +4778,47 @@
         ASSERT_NOT_REACHED();
     }
 
-    unsigned int totalBytesRequired;
-    GC3Denum error = m_context->computeImageSizeInBytes(format, type, width, height, m_unpackAlignment, &totalBytesRequired, 0);
-    if (error != GraphicsContext3D::NO_ERROR) {
+    unsigned totalBytesRequired;
+    GLenum error = WebGLImageConversion::computeImageSizeInBytes(format, type, width, height, m_unpackAlignment, &totalBytesRequired, 0);
+    if (error != GL_NO_ERROR) {
         synthesizeGLError(error, functionName, "invalid texture dimensions");
         return false;
     }
     if (pixels->byteLength() < totalBytesRequired) {
         if (m_unpackAlignment != 1) {
-          error = m_context->computeImageSizeInBytes(format, type, width, height, 1, &totalBytesRequired, 0);
-          if (pixels->byteLength() == totalBytesRequired) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "ArrayBufferView not big enough for request with UNPACK_ALIGNMENT > 1");
-            return false;
-          }
+            error = WebGLImageConversion::computeImageSizeInBytes(format, type, width, height, 1, &totalBytesRequired, 0);
+            if (pixels->byteLength() == totalBytesRequired) {
+                synthesizeGLError(GL_INVALID_OPERATION, functionName, "ArrayBufferView not big enough for request with UNPACK_ALIGNMENT > 1");
+                return false;
+            }
         }
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "ArrayBufferView not big enough for request");
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "ArrayBufferView not big enough for request");
         return false;
     }
     return true;
 }
 
-bool WebGLRenderingContext::validateCompressedTexFormat(GC3Denum format)
+bool WebGLRenderingContext::validateCompressedTexFormat(GLenum format)
 {
     return m_compressedTextureFormats.contains(format);
 }
 
-bool WebGLRenderingContext::validateCompressedTexFuncData(const char* functionName,
-                                                          GC3Dsizei width, GC3Dsizei height,
-                                                          GC3Denum format, ArrayBufferView* pixels)
+bool WebGLRenderingContext::validateCompressedTexFuncData(const char* functionName, GLsizei width, GLsizei height, GLenum format, ArrayBufferView* pixels)
 {
     if (!pixels) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no pixels");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no pixels");
         return false;
     }
     if (width < 0 || height < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height < 0");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "width or height < 0");
         return false;
     }
 
-    unsigned int bytesRequired = 0;
+    unsigned bytesRequired = 0;
 
     switch (format) {
-    case Extensions3D::COMPRESSED_RGB_S3TC_DXT1_EXT:
-    case Extensions3D::COMPRESSED_RGBA_S3TC_DXT1_EXT:
+    case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
+    case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
         {
             const int kBlockWidth = 4;
             const int kBlockHeight = 4;
@@ -4822,8 +4829,8 @@
             bytesRequired = numBlocks * kBlockSize;
         }
         break;
-    case Extensions3D::COMPRESSED_RGBA_S3TC_DXT3_EXT:
-    case Extensions3D::COMPRESSED_RGBA_S3TC_DXT5_EXT:
+    case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
+    case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
         {
             const int kBlockWidth = 4;
             const int kBlockHeight = 4;
@@ -4834,58 +4841,59 @@
             bytesRequired = numBlocks * kBlockSize;
         }
         break;
-    case Extensions3D::COMPRESSED_ATC_RGB_AMD:
+    case GC3D_COMPRESSED_ATC_RGB_AMD:
         {
             bytesRequired = floor(static_cast<double>((width + 3) / 4)) * floor(static_cast<double>((height + 3) / 4)) * 8;
         }
         break;
-    case Extensions3D::COMPRESSED_ATC_RGBA_EXPLICIT_ALPHA_AMD:
-    case Extensions3D::COMPRESSED_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
+    case GC3D_COMPRESSED_ATC_RGBA_EXPLICIT_ALPHA_AMD:
+    case GC3D_COMPRESSED_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
         {
             bytesRequired = floor(static_cast<double>((width + 3) / 4)) * floor(static_cast<double>((height + 3) / 4)) * 16;
         }
-    case Extensions3D::COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
-    case Extensions3D::COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
+        break;
+    case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
+    case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
         {
             bytesRequired = max(width, 8) * max(height, 8) / 2;
         }
         break;
-    case Extensions3D::COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
-    case Extensions3D::COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
+    case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
+    case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
         {
             bytesRequired = max(width, 8) * max(height, 8) / 4;
         }
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid format");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid format");
         return false;
     }
 
     if (pixels->byteLength() != bytesRequired) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "length of ArrayBufferView is not correct for dimensions");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "length of ArrayBufferView is not correct for dimensions");
         return false;
     }
 
     return true;
 }
 
-bool WebGLRenderingContext::validateCompressedTexDimensions(const char* functionName, TexFuncValidationFunctionType functionType, GC3Denum target, GC3Dint level, GC3Dsizei width, GC3Dsizei height, GC3Denum format)
+bool WebGLRenderingContext::validateCompressedTexDimensions(const char* functionName, TexFuncValidationFunctionType functionType, GLenum target, GLint level, GLsizei width, GLsizei height, GLenum format)
 {
     if (!validateTexFuncDimensions(functionName, functionType, target, level, width, height))
         return false;
 
     switch (format) {
-    case Extensions3D::COMPRESSED_RGB_S3TC_DXT1_EXT:
-    case Extensions3D::COMPRESSED_RGBA_S3TC_DXT1_EXT:
-    case Extensions3D::COMPRESSED_RGBA_S3TC_DXT3_EXT:
-    case Extensions3D::COMPRESSED_RGBA_S3TC_DXT5_EXT: {
+    case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
+    case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
+    case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
+    case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: {
         const int kBlockWidth = 4;
         const int kBlockHeight = 4;
         bool widthValid = (level && width == 1) || (level && width == 2) || !(width % kBlockWidth);
         bool heightValid = (level && height == 1) || (level && height == 2) || !(height % kBlockHeight);
         if (!widthValid || !heightValid) {
-          synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "width or height invalid for level");
-          return false;
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "width or height invalid for level");
+            return false;
         }
         return true;
     }
@@ -4894,28 +4902,27 @@
     }
 }
 
-bool WebGLRenderingContext::validateCompressedTexSubDimensions(const char* functionName, GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-                                                               GC3Dsizei width, GC3Dsizei height, GC3Denum format, WebGLTexture* tex)
+bool WebGLRenderingContext::validateCompressedTexSubDimensions(const char* functionName, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, WebGLTexture* tex)
 {
     if (xoffset < 0 || yoffset < 0) {
-      synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "xoffset or yoffset < 0");
-      return false;
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "xoffset or yoffset < 0");
+        return false;
     }
 
     switch (format) {
-    case Extensions3D::COMPRESSED_RGB_S3TC_DXT1_EXT:
-    case Extensions3D::COMPRESSED_RGBA_S3TC_DXT1_EXT:
-    case Extensions3D::COMPRESSED_RGBA_S3TC_DXT3_EXT:
-    case Extensions3D::COMPRESSED_RGBA_S3TC_DXT5_EXT: {
+    case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
+    case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
+    case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
+    case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: {
         const int kBlockWidth = 4;
         const int kBlockHeight = 4;
         if ((xoffset % kBlockWidth) || (yoffset % kBlockHeight)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "xoffset or yoffset not multiple of 4");
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "xoffset or yoffset not multiple of 4");
             return false;
         }
         if (width - xoffset > tex->getWidth(target, level)
             || height - yoffset > tex->getHeight(target, level)) {
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "dimensions out of range");
+            synthesizeGLError(GL_INVALID_OPERATION, functionName, "dimensions out of range");
             return false;
         }
         return validateCompressedTexDimensions(functionName, TexSubImage2D, target, level, width, height, format);
@@ -4925,19 +4932,19 @@
     }
 }
 
-bool WebGLRenderingContext::validateDrawMode(const char* functionName, GC3Denum mode)
+bool WebGLRenderingContext::validateDrawMode(const char* functionName, GLenum mode)
 {
     switch (mode) {
-    case GraphicsContext3D::POINTS:
-    case GraphicsContext3D::LINE_STRIP:
-    case GraphicsContext3D::LINE_LOOP:
-    case GraphicsContext3D::LINES:
-    case GraphicsContext3D::TRIANGLE_STRIP:
-    case GraphicsContext3D::TRIANGLE_FAN:
-    case GraphicsContext3D::TRIANGLES:
+    case GL_POINTS:
+    case GL_LINE_STRIP:
+    case GL_LINE_LOOP:
+    case GL_LINES:
+    case GL_TRIANGLE_STRIP:
+    case GL_TRIANGLE_FAN:
+    case GL_TRIANGLES:
         return true;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid draw mode");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid draw mode");
         return false;
     }
 }
@@ -4945,26 +4952,26 @@
 bool WebGLRenderingContext::validateStencilSettings(const char* functionName)
 {
     if (m_stencilMask != m_stencilMaskBack || m_stencilFuncRef != m_stencilFuncRefBack || m_stencilFuncMask != m_stencilFuncMaskBack) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "front and back stencils settings do not match");
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "front and back stencils settings do not match");
         return false;
     }
     return true;
 }
 
-bool WebGLRenderingContext::validateStencilOrDepthFunc(const char* functionName, GC3Denum func)
+bool WebGLRenderingContext::validateStencilOrDepthFunc(const char* functionName, GLenum func)
 {
     switch (func) {
-    case GraphicsContext3D::NEVER:
-    case GraphicsContext3D::LESS:
-    case GraphicsContext3D::LEQUAL:
-    case GraphicsContext3D::GREATER:
-    case GraphicsContext3D::GEQUAL:
-    case GraphicsContext3D::EQUAL:
-    case GraphicsContext3D::NOTEQUAL:
-    case GraphicsContext3D::ALWAYS:
+    case GL_NEVER:
+    case GL_LESS:
+    case GL_LEQUAL:
+    case GL_GREATER:
+    case GL_GEQUAL:
+    case GL_EQUAL:
+    case GL_NOTEQUAL:
+    case GL_ALWAYS:
         return true;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid function");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid function");
         return false;
     }
 }
@@ -4990,165 +4997,165 @@
     canvas()->document().addConsoleMessage(RenderingMessageSource, WarningMessageLevel, message);
 }
 
-bool WebGLRenderingContext::validateFramebufferFuncParameters(const char* functionName, GC3Denum target, GC3Denum attachment)
+bool WebGLRenderingContext::validateFramebufferFuncParameters(const char* functionName, GLenum target, GLenum attachment)
 {
-    if (target != GraphicsContext3D::FRAMEBUFFER) {
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid target");
+    if (target != GL_FRAMEBUFFER) {
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid target");
         return false;
     }
     switch (attachment) {
-    case GraphicsContext3D::COLOR_ATTACHMENT0:
-    case GraphicsContext3D::DEPTH_ATTACHMENT:
-    case GraphicsContext3D::STENCIL_ATTACHMENT:
-    case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
+    case GL_COLOR_ATTACHMENT0:
+    case GL_DEPTH_ATTACHMENT:
+    case GL_STENCIL_ATTACHMENT:
+    case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
         break;
     default:
         if (m_webglDrawBuffers
-            && attachment > GraphicsContext3D::COLOR_ATTACHMENT0
-            && attachment < static_cast<GC3Denum>(GraphicsContext3D::COLOR_ATTACHMENT0 + maxColorAttachments()))
+            && attachment > GL_COLOR_ATTACHMENT0
+            && attachment < static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + maxColorAttachments()))
             break;
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid attachment");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid attachment");
         return false;
     }
     return true;
 }
 
-bool WebGLRenderingContext::validateBlendEquation(const char* functionName, GC3Denum mode)
+bool WebGLRenderingContext::validateBlendEquation(const char* functionName, GLenum mode)
 {
     switch (mode) {
-    case GraphicsContext3D::FUNC_ADD:
-    case GraphicsContext3D::FUNC_SUBTRACT:
-    case GraphicsContext3D::FUNC_REVERSE_SUBTRACT:
+    case GL_FUNC_ADD:
+    case GL_FUNC_SUBTRACT:
+    case GL_FUNC_REVERSE_SUBTRACT:
         return true;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid mode");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid mode");
         return false;
     }
 }
 
-bool WebGLRenderingContext::validateBlendFuncFactors(const char* functionName, GC3Denum src, GC3Denum dst)
+bool WebGLRenderingContext::validateBlendFuncFactors(const char* functionName, GLenum src, GLenum dst)
 {
-    if (((src == GraphicsContext3D::CONSTANT_COLOR || src == GraphicsContext3D::ONE_MINUS_CONSTANT_COLOR)
-         && (dst == GraphicsContext3D::CONSTANT_ALPHA || dst == GraphicsContext3D::ONE_MINUS_CONSTANT_ALPHA))
-        || ((dst == GraphicsContext3D::CONSTANT_COLOR || dst == GraphicsContext3D::ONE_MINUS_CONSTANT_COLOR)
-            && (src == GraphicsContext3D::CONSTANT_ALPHA || src == GraphicsContext3D::ONE_MINUS_CONSTANT_ALPHA))) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "incompatible src and dst");
+    if (((src == GL_CONSTANT_COLOR || src == GL_ONE_MINUS_CONSTANT_COLOR)
+        && (dst == GL_CONSTANT_ALPHA || dst == GL_ONE_MINUS_CONSTANT_ALPHA))
+        || ((dst == GL_CONSTANT_COLOR || dst == GL_ONE_MINUS_CONSTANT_COLOR)
+        && (src == GL_CONSTANT_ALPHA || src == GL_ONE_MINUS_CONSTANT_ALPHA))) {
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "incompatible src and dst");
         return false;
     }
     return true;
 }
 
-bool WebGLRenderingContext::validateCapability(const char* functionName, GC3Denum cap)
+bool WebGLRenderingContext::validateCapability(const char* functionName, GLenum cap)
 {
     switch (cap) {
-    case GraphicsContext3D::BLEND:
-    case GraphicsContext3D::CULL_FACE:
-    case GraphicsContext3D::DEPTH_TEST:
-    case GraphicsContext3D::DITHER:
-    case GraphicsContext3D::POLYGON_OFFSET_FILL:
-    case GraphicsContext3D::SAMPLE_ALPHA_TO_COVERAGE:
-    case GraphicsContext3D::SAMPLE_COVERAGE:
-    case GraphicsContext3D::SCISSOR_TEST:
-    case GraphicsContext3D::STENCIL_TEST:
+    case GL_BLEND:
+    case GL_CULL_FACE:
+    case GL_DEPTH_TEST:
+    case GL_DITHER:
+    case GL_POLYGON_OFFSET_FILL:
+    case GL_SAMPLE_ALPHA_TO_COVERAGE:
+    case GL_SAMPLE_COVERAGE:
+    case GL_SCISSOR_TEST:
+    case GL_STENCIL_TEST:
         return true;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid capability");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid capability");
         return false;
     }
 }
 
-bool WebGLRenderingContext::validateUniformParameters(const char* functionName, const WebGLUniformLocation* location, Float32Array* v, GC3Dsizei requiredMinSize)
+bool WebGLRenderingContext::validateUniformParameters(const char* functionName, const WebGLUniformLocation* location, Float32Array* v, GLsizei requiredMinSize)
 {
     if (!v) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
         return false;
     }
     return validateUniformMatrixParameters(functionName, location, false, v->data(), v->length(), requiredMinSize);
 }
 
-bool WebGLRenderingContext::validateUniformParameters(const char* functionName, const WebGLUniformLocation* location, Int32Array* v, GC3Dsizei requiredMinSize)
+bool WebGLRenderingContext::validateUniformParameters(const char* functionName, const WebGLUniformLocation* location, Int32Array* v, GLsizei requiredMinSize)
 {
     if (!v) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
         return false;
     }
     return validateUniformMatrixParameters(functionName, location, false, v->data(), v->length(), requiredMinSize);
 }
 
-bool WebGLRenderingContext::validateUniformParameters(const char* functionName, const WebGLUniformLocation* location, void* v, GC3Dsizei size, GC3Dsizei requiredMinSize)
+bool WebGLRenderingContext::validateUniformParameters(const char* functionName, const WebGLUniformLocation* location, void* v, GLsizei size, GLsizei requiredMinSize)
 {
     return validateUniformMatrixParameters(functionName, location, false, v, size, requiredMinSize);
 }
 
-bool WebGLRenderingContext::validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation* location, GC3Dboolean transpose, Float32Array* v, GC3Dsizei requiredMinSize)
+bool WebGLRenderingContext::validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation* location, GLboolean transpose, Float32Array* v, GLsizei requiredMinSize)
 {
     if (!v) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
         return false;
     }
     return validateUniformMatrixParameters(functionName, location, transpose, v->data(), v->length(), requiredMinSize);
 }
 
-bool WebGLRenderingContext::validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation* location, GC3Dboolean transpose, void* v, GC3Dsizei size, GC3Dsizei requiredMinSize)
+bool WebGLRenderingContext::validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation* location, GLboolean transpose, void* v, GLsizei size, GLsizei requiredMinSize)
 {
     if (!location)
         return false;
     if (location->program() != m_currentProgram) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "location is not from current program");
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "location is not from current program");
         return false;
     }
     if (!v) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
         return false;
     }
     if (transpose) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "transpose not FALSE");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "transpose not FALSE");
         return false;
     }
     if (size < requiredMinSize || (size % requiredMinSize)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "invalid size");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "invalid size");
         return false;
     }
     return true;
 }
 
-WebGLBuffer* WebGLRenderingContext::validateBufferDataParameters(const char* functionName, GC3Denum target, GC3Denum usage)
+WebGLBuffer* WebGLRenderingContext::validateBufferDataParameters(const char* functionName, GLenum target, GLenum usage)
 {
     WebGLBuffer* buffer = 0;
     switch (target) {
-    case GraphicsContext3D::ELEMENT_ARRAY_BUFFER:
+    case GL_ELEMENT_ARRAY_BUFFER:
         buffer = m_boundVertexArrayObject->boundElementArrayBuffer().get();
         break;
-    case GraphicsContext3D::ARRAY_BUFFER:
+    case GL_ARRAY_BUFFER:
         buffer = m_boundArrayBuffer.get();
         break;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid target");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid target");
         return 0;
     }
     if (!buffer) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "no buffer");
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "no buffer");
         return 0;
     }
     switch (usage) {
-    case GraphicsContext3D::STREAM_DRAW:
-    case GraphicsContext3D::STATIC_DRAW:
-    case GraphicsContext3D::DYNAMIC_DRAW:
+    case GL_STREAM_DRAW:
+    case GL_STATIC_DRAW:
+    case GL_DYNAMIC_DRAW:
         return buffer;
     }
-    synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid usage");
+    synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid usage");
     return 0;
 }
 
 bool WebGLRenderingContext::validateHTMLImageElement(const char* functionName, HTMLImageElement* image, ExceptionState& exceptionState)
 {
     if (!image || !image->cachedImage()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no image");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no image");
         return false;
     }
     const KURL& url = image->cachedImage()->response().url();
     if (url.isNull() || url.isEmpty() || !url.isValid()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "invalid image");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "invalid image");
         return false;
     }
     if (wouldTaintOrigin(image)) {
@@ -5161,7 +5168,7 @@
 bool WebGLRenderingContext::validateHTMLCanvasElement(const char* functionName, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
 {
     if (!canvas || !canvas->buffer()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no canvas");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no canvas");
         return false;
     }
     if (wouldTaintOrigin(canvas)) {
@@ -5174,7 +5181,7 @@
 bool WebGLRenderingContext::validateHTMLVideoElement(const char* functionName, HTMLVideoElement* video, ExceptionState& exceptionState)
 {
     if (!video || !video->videoWidth() || !video->videoHeight()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no video");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no video");
         return false;
     }
     if (wouldTaintOrigin(video)) {
@@ -5184,7 +5191,7 @@
     return true;
 }
 
-bool WebGLRenderingContext::validateDrawArrays(const char* functionName, GC3Denum mode, GC3Dint first, GC3Dsizei count)
+bool WebGLRenderingContext::validateDrawArrays(const char* functionName, GLenum mode, GLint first, GLsizei count)
 {
     if (isContextLost() || !validateDrawMode(functionName, mode))
         return false;
@@ -5193,7 +5200,7 @@
         return false;
 
     if (first < 0 || count < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "first or count < 0");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "first or count < 0");
         return false;
     }
 
@@ -5202,21 +5209,20 @@
         return false;
     }
 
-    if (!validateRenderingState()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "attribs not setup correctly");
+    if (!validateRenderingState(functionName)) {
         return false;
     }
 
     const char* reason = "framebuffer incomplete";
-    if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, functionName, reason);
+    if (m_framebufferBinding && !m_framebufferBinding->onAccess(m_context.get(), &reason)) {
+        synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, functionName, reason);
         return false;
     }
 
     return true;
 }
 
-bool WebGLRenderingContext::validateDrawElements(const char* functionName, GC3Denum mode, GC3Dsizei count, GC3Denum type, long long offset)
+bool WebGLRenderingContext::validateDrawElements(const char* functionName, GLenum mode, GLsizei count, GLenum type, long long offset)
 {
     if (isContextLost() || !validateDrawMode(functionName, mode))
         return false;
@@ -5225,21 +5231,21 @@
         return false;
 
     switch (type) {
-    case GraphicsContext3D::UNSIGNED_BYTE:
-    case GraphicsContext3D::UNSIGNED_SHORT:
+    case GL_UNSIGNED_BYTE:
+    case GL_UNSIGNED_SHORT:
         break;
-    case GraphicsContext3D::UNSIGNED_INT:
+    case GL_UNSIGNED_INT:
         if (m_oesElementIndexUint)
             break;
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid type");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid type");
         return false;
     default:
-        synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid type");
+        synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid type");
         return false;
     }
 
     if (count < 0 || offset < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "count or offset < 0");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "count or offset < 0");
         return false;
     }
 
@@ -5249,18 +5255,17 @@
     }
 
     if (!m_boundVertexArrayObject->boundElementArrayBuffer()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "no ELEMENT_ARRAY_BUFFER bound");
+        synthesizeGLError(GL_INVALID_OPERATION, functionName, "no ELEMENT_ARRAY_BUFFER bound");
         return false;
     }
 
-    if (!validateRenderingState()) {
-        synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "attribs not setup correctly");
+    if (!validateRenderingState(functionName)) {
         return false;
     }
 
     const char* reason = "framebuffer incomplete";
-    if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
-        synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, functionName, reason);
+    if (m_framebufferBinding && !m_framebufferBinding->onAccess(m_context.get(), &reason)) {
+        synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, functionName, reason);
         return false;
     }
 
@@ -5268,10 +5273,10 @@
 }
 
 // Helper function to validate draw*Instanced calls
-bool WebGLRenderingContext::validateDrawInstanced(const char* functionName, GC3Dsizei primcount)
+bool WebGLRenderingContext::validateDrawInstanced(const char* functionName, GLsizei primcount)
 {
     if (primcount < 0) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "primcount < 0");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "primcount < 0");
         return false;
     }
 
@@ -5282,16 +5287,16 @@
             return true;
     }
 
-    synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "at least one enabled attribute must have a divisor of 0");
+    synthesizeGLError(GL_INVALID_OPERATION, functionName, "at least one enabled attribute must have a divisor of 0");
     return false;
 }
 
-void WebGLRenderingContext::vertexAttribfImpl(const char* functionName, GC3Duint index, GC3Dsizei expectedSize, GC3Dfloat v0, GC3Dfloat v1, GC3Dfloat v2, GC3Dfloat v3)
+void WebGLRenderingContext::vertexAttribfImpl(const char* functionName, GLuint index, GLsizei expectedSize, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3)
 {
     if (isContextLost())
         return;
     if (index >= m_maxVertexAttribs) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "index out of range");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "index out of range");
         return;
     }
     // In GL, we skip setting vertexAttrib0 values.
@@ -5316,31 +5321,31 @@
     attribValue.value[3] = v3;
 }
 
-void WebGLRenderingContext::vertexAttribfvImpl(const char* functionName, GC3Duint index, Float32Array* v, GC3Dsizei expectedSize)
+void WebGLRenderingContext::vertexAttribfvImpl(const char* functionName, GLuint index, Float32Array* v, GLsizei expectedSize)
 {
     if (isContextLost())
         return;
     if (!v) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
         return;
     }
     vertexAttribfvImpl(functionName, index, v->data(), v->length(), expectedSize);
 }
 
-void WebGLRenderingContext::vertexAttribfvImpl(const char* functionName, GC3Duint index, GC3Dfloat* v, GC3Dsizei size, GC3Dsizei expectedSize)
+void WebGLRenderingContext::vertexAttribfvImpl(const char* functionName, GLuint index, GLfloat* v, GLsizei size, GLsizei expectedSize)
 {
     if (isContextLost())
         return;
     if (!v) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
         return;
     }
     if (size < expectedSize) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "invalid size");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "invalid size");
         return;
     }
     if (index >= m_maxVertexAttribs) {
-        synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "index out of range");
+        synthesizeGLError(GL_INVALID_VALUE, functionName, "index out of range");
         return;
     }
     // In GL, we skip setting vertexAttrib0 values.
@@ -5396,25 +5401,23 @@
     if (!frame->loader().client()->allowWebGL(settings && settings->webGLEnabled()))
         return;
 
-    // Reset the context attributes back to the requested attributes and re-apply restrictions
-    m_attributes = adjustAttributes(m_requestedAttributes, settings);
-
-    RefPtr<GraphicsContext3D> context(GraphicsContext3D::create(m_attributes));
-
+    blink::WebGraphicsContext3D::Attributes attributes = m_requestedAttributes->attributes(canvas()->document().topDocument()->url().string(), settings);
+    OwnPtr<blink::WebGraphicsContext3D> context = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(attributes));
     if (!context) {
-        if (m_contextLostMode == RealLostContext)
+        if (m_contextLostMode == RealLostContext) {
             m_restoreTimer.startOneShot(secondsBetweenRestoreAttempts);
-        else
+        } else {
             // This likely shouldn't happen but is the best way to report it to the WebGL app.
-            synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "", "error restoring context");
+            synthesizeGLError(GL_INVALID_OPERATION, "", "error restoring context");
+        }
         return;
     }
 
     RefPtr<WebGLRenderingContextEvictionManager> contextEvictionManager = adoptRef(new WebGLRenderingContextEvictionManager());
 
-    // Construct a new drawing buffer with the new GraphicsContext3D.
+    // Construct a new drawing buffer with the new WebGraphicsContext3D.
     m_drawingBuffer->releaseResources();
-    DrawingBuffer::PreserveDrawingBuffer preserve = m_attributes.preserveDrawingBuffer ? DrawingBuffer::Preserve : DrawingBuffer::Discard;
+    DrawingBuffer::PreserveDrawingBuffer preserve = m_requestedAttributes->preserveDrawingBuffer() ? DrawingBuffer::Preserve : DrawingBuffer::Discard;
     m_drawingBuffer = DrawingBuffer::create(context.get(), clampedCanvasSize(), preserve, contextEvictionManager.release());
 
     if (m_drawingBuffer->isZeroSized())
@@ -5422,9 +5425,9 @@
 
     m_drawingBuffer->bind();
 
-    lost_context_errors_.clear();
+    m_lostContextErrors.clear();
 
-    m_context = context;
+    m_context = context.release();
     m_contextLost = false;
 
     setupFlags();
@@ -5477,20 +5480,20 @@
 
 namespace {
 
-    String GetErrorString(GC3Denum error)
+    String GetErrorString(GLenum error)
     {
         switch (error) {
-        case GraphicsContext3D::INVALID_ENUM:
+        case GL_INVALID_ENUM:
             return "INVALID_ENUM";
-        case GraphicsContext3D::INVALID_VALUE:
+        case GL_INVALID_VALUE:
             return "INVALID_VALUE";
-        case GraphicsContext3D::INVALID_OPERATION:
+        case GL_INVALID_OPERATION:
             return "INVALID_OPERATION";
-        case GraphicsContext3D::OUT_OF_MEMORY:
+        case GL_OUT_OF_MEMORY:
             return "OUT_OF_MEMORY";
-        case GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION:
+        case GL_INVALID_FRAMEBUFFER_OPERATION:
             return "INVALID_FRAMEBUFFER_OPERATION";
-        case GraphicsContext3D::CONTEXT_LOST_WEBGL:
+        case GC3D_CONTEXT_LOST_WEBGL:
             return "CONTEXT_LOST_WEBGL";
         default:
             return String::format("WebGL ERROR(0x%04X)", error);
@@ -5499,7 +5502,7 @@
 
 } // namespace anonymous
 
-void WebGLRenderingContext::synthesizeGLError(GC3Denum error, const char* functionName, const char* description, ConsoleDisplayPreference display)
+void WebGLRenderingContext::synthesizeGLError(GLenum error, const char* functionName, const char* description, ConsoleDisplayPreference display)
 {
     String errorType = GetErrorString(error);
     if (m_synthesizedErrorsToConsole && display == DisplayInConsole) {
@@ -5509,8 +5512,8 @@
     if (!isContextLost())
         m_context->synthesizeGLError(error);
     else {
-        if (lost_context_errors_.find(error) == WTF::kNotFound)
-            lost_context_errors_.append(error);
+        if (m_lostContextErrors.find(error) == WTF::kNotFound)
+            m_lostContextErrors.append(error);
     }
     InspectorInstrumentation::didFireWebGLError(canvas(), errorType);
 }
@@ -5534,11 +5537,11 @@
         RefPtr<WebGLContextAttributes> attributes = getContextAttributes();
         haveStencilBuffer = attributes->stencil();
     }
-    enableOrDisable(GraphicsContext3D::STENCIL_TEST,
+    enableOrDisable(GL_STENCIL_TEST,
                     m_stencilEnabled && haveStencilBuffer);
 }
 
-void WebGLRenderingContext::enableOrDisable(GC3Denum capability, bool enable)
+void WebGLRenderingContext::enableOrDisable(GLenum capability, bool enable)
 {
     if (isContextLost())
         return;
@@ -5554,40 +5557,40 @@
                    clamp(canvas()->height(), 1, m_maxViewportDims[1]));
 }
 
-GC3Dint WebGLRenderingContext::maxDrawBuffers()
+GLint WebGLRenderingContext::maxDrawBuffers()
 {
     if (isContextLost() || !m_webglDrawBuffers)
         return 0;
     if (!m_maxDrawBuffers)
-        m_context->getIntegerv(Extensions3D::MAX_DRAW_BUFFERS_EXT, &m_maxDrawBuffers);
+        m_context->getIntegerv(GL_MAX_DRAW_BUFFERS_EXT, &m_maxDrawBuffers);
     if (!m_maxColorAttachments)
-        m_context->getIntegerv(Extensions3D::MAX_COLOR_ATTACHMENTS_EXT, &m_maxColorAttachments);
+        m_context->getIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &m_maxColorAttachments);
     // WEBGL_draw_buffers requires MAX_COLOR_ATTACHMENTS >= MAX_DRAW_BUFFERS.
     return std::min(m_maxDrawBuffers, m_maxColorAttachments);
 }
 
-GC3Dint WebGLRenderingContext::maxColorAttachments()
+GLint WebGLRenderingContext::maxColorAttachments()
 {
     if (isContextLost() || !m_webglDrawBuffers)
         return 0;
     if (!m_maxColorAttachments)
-        m_context->getIntegerv(Extensions3D::MAX_COLOR_ATTACHMENTS_EXT, &m_maxColorAttachments);
+        m_context->getIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &m_maxColorAttachments);
     return m_maxColorAttachments;
 }
 
-void WebGLRenderingContext::setBackDrawBuffer(GC3Denum buf)
+void WebGLRenderingContext::setBackDrawBuffer(GLenum buf)
 {
     m_backDrawBuffer = buf;
 }
 
 void WebGLRenderingContext::restoreCurrentFramebuffer()
 {
-    bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_framebufferBinding.get());
+    bindFramebuffer(GL_FRAMEBUFFER, m_framebufferBinding.get());
 }
 
 void WebGLRenderingContext::restoreCurrentTexture2D()
 {
-    bindTexture(GraphicsContext3D::TEXTURE_2D, m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get());
+    bindTexture(GL_TEXTURE_2D, m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get());
 }
 
 void WebGLRenderingContext::multisamplingChanged(bool enabled)
diff --git a/Source/core/html/canvas/WebGLRenderingContext.h b/Source/core/html/canvas/WebGLRenderingContext.h
index e1e3911..04c7c95 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.h
+++ b/Source/core/html/canvas/WebGLRenderingContext.h
@@ -31,15 +31,19 @@
 #include "core/html/canvas/WebGLGetInfo.h"
 #include "core/page/Page.h"
 #include "platform/Timer.h"
-#include "platform/graphics/GraphicsContext3D.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "platform/graphics/ImageBuffer.h"
-
+#include "platform/graphics/gpu/Extensions3DUtil.h"
+#include "platform/graphics/gpu/WebGLImageConversion.h"
+#include "public/platform/WebGraphicsContext3D.h"
 #include "wtf/Float32Array.h"
 #include "wtf/Int32Array.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/text/WTFString.h"
 
-namespace blink { class WebLayer; }
+namespace blink {
+class WebLayer;
+}
 
 namespace WebCore {
 
@@ -85,60 +89,61 @@
 class WebGLUniformLocation;
 class WebGLVertexArrayObjectOES;
 
-class WebGLRenderingContext : public CanvasRenderingContext, public ActiveDOMObject, private Page::MultisamplingChangedObserver {
+class WebGLRenderingContextLostCallback;
+class WebGLRenderingContextErrorMessageCallback;
+
+class WebGLRenderingContext FINAL : public CanvasRenderingContext, public ActiveDOMObject, private Page::MultisamplingChangedObserver {
 public:
     static PassOwnPtr<WebGLRenderingContext> create(HTMLCanvasElement*, WebGLContextAttributes*);
     virtual ~WebGLRenderingContext();
 
-    virtual bool is3d() const { return true; }
-    virtual bool isAccelerated() const { return true; }
+    virtual bool is3d() const OVERRIDE { return true; }
+    virtual bool isAccelerated() const OVERRIDE { return true; }
 
     int drawingBufferWidth() const;
     int drawingBufferHeight() const;
 
-    void activeTexture(GC3Denum texture);
+    void activeTexture(GLenum texture);
     void attachShader(WebGLProgram*, WebGLShader*);
-    void bindAttribLocation(WebGLProgram*, GC3Duint index, const String& name);
-    void bindBuffer(GC3Denum target, WebGLBuffer*);
-    void bindFramebuffer(GC3Denum target, WebGLFramebuffer*);
-    void bindRenderbuffer(GC3Denum target, WebGLRenderbuffer*);
-    void bindTexture(GC3Denum target, WebGLTexture*);
-    void blendColor(GC3Dfloat red, GC3Dfloat green, GC3Dfloat blue, GC3Dfloat alpha);
-    void blendEquation(GC3Denum mode);
-    void blendEquationSeparate(GC3Denum modeRGB, GC3Denum modeAlpha);
-    void blendFunc(GC3Denum sfactor, GC3Denum dfactor);
-    void blendFuncSeparate(GC3Denum srcRGB, GC3Denum dstRGB, GC3Denum srcAlpha, GC3Denum dstAlpha);
+    void bindAttribLocation(WebGLProgram*, GLuint index, const String& name);
+    void bindBuffer(GLenum target, WebGLBuffer*);
+    void bindFramebuffer(GLenum target, WebGLFramebuffer*);
+    void bindRenderbuffer(GLenum target, WebGLRenderbuffer*);
+    void bindTexture(GLenum target, WebGLTexture*);
+    void blendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+    void blendEquation(GLenum mode);
+    void blendEquationSeparate(GLenum modeRGB, GLenum modeAlpha);
+    void blendFunc(GLenum sfactor, GLenum dfactor);
+    void blendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
 
-    void bufferData(GC3Denum target, long long size, GC3Denum usage);
-    void bufferData(GC3Denum target, ArrayBuffer* data, GC3Denum usage);
-    void bufferData(GC3Denum target, ArrayBufferView* data, GC3Denum usage);
-    void bufferSubData(GC3Denum target, long long offset, ArrayBuffer* data);
-    void bufferSubData(GC3Denum target, long long offset, ArrayBufferView* data);
+    void bufferData(GLenum target, long long size, GLenum usage);
+    void bufferData(GLenum target, ArrayBuffer* data, GLenum usage);
+    void bufferData(GLenum target, ArrayBufferView* data, GLenum usage);
+    void bufferSubData(GLenum target, long long offset, ArrayBuffer* data);
+    void bufferSubData(GLenum target, long long offset, ArrayBufferView* data);
 
-    GC3Denum checkFramebufferStatus(GC3Denum target);
-    void clear(GC3Dbitfield mask);
-    void clearColor(GC3Dfloat red, GC3Dfloat green, GC3Dfloat blue, GC3Dfloat alpha);
-    void clearDepth(GC3Dfloat);
-    void clearStencil(GC3Dint);
-    void colorMask(GC3Dboolean red, GC3Dboolean green, GC3Dboolean blue, GC3Dboolean alpha);
+    GLenum checkFramebufferStatus(GLenum target);
+    void clear(GLbitfield mask);
+    void clearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+    void clearDepth(GLfloat);
+    void clearStencil(GLint);
+    void colorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
     void compileShader(WebGLShader*);
 
-    void compressedTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width,
-                              GC3Dsizei height, GC3Dint border, ArrayBufferView* data);
-    void compressedTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-                                 GC3Dsizei width, GC3Dsizei height, GC3Denum format, ArrayBufferView* data);
+    void compressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, ArrayBufferView* data);
+    void compressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, ArrayBufferView* data);
 
-    void copyTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Dint border);
-    void copyTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height);
+    void copyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+    void copyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
 
     PassRefPtr<WebGLBuffer> createBuffer();
     PassRefPtr<WebGLFramebuffer> createFramebuffer();
     PassRefPtr<WebGLProgram> createProgram();
     PassRefPtr<WebGLRenderbuffer> createRenderbuffer();
-    PassRefPtr<WebGLShader> createShader(GC3Denum type);
+    PassRefPtr<WebGLShader> createShader(GLenum type);
     PassRefPtr<WebGLTexture> createTexture();
 
-    void cullFace(GC3Denum mode);
+    void cullFace(GLenum mode);
 
     void deleteBuffer(WebGLBuffer*);
     void deleteFramebuffer(WebGLFramebuffer*);
@@ -147,156 +152,156 @@
     void deleteShader(WebGLShader*);
     void deleteTexture(WebGLTexture*);
 
-    void depthFunc(GC3Denum);
-    void depthMask(GC3Dboolean);
-    void depthRange(GC3Dfloat zNear, GC3Dfloat zFar);
+    void depthFunc(GLenum);
+    void depthMask(GLboolean);
+    void depthRange(GLfloat zNear, GLfloat zFar);
     void detachShader(WebGLProgram*, WebGLShader*);
-    void disable(GC3Denum cap);
-    void disableVertexAttribArray(GC3Duint index);
-    void drawArrays(GC3Denum mode, GC3Dint first, GC3Dsizei count);
-    void drawElements(GC3Denum mode, GC3Dsizei count, GC3Denum type, long long offset);
+    void disable(GLenum cap);
+    void disableVertexAttribArray(GLuint index);
+    void drawArrays(GLenum mode, GLint first, GLsizei count);
+    void drawElements(GLenum mode, GLsizei count, GLenum type, long long offset);
 
-    void drawArraysInstancedANGLE(GC3Denum mode, GC3Dint first, GC3Dsizei count, GC3Dsizei primcount);
-    void drawElementsInstancedANGLE(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset, GC3Dsizei primcount);
+    void drawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+    void drawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, GLintptr offset, GLsizei primcount);
 
-    void enable(GC3Denum cap);
-    void enableVertexAttribArray(GC3Duint index);
+    void enable(GLenum cap);
+    void enableVertexAttribArray(GLuint index);
     void finish();
     void flush();
-    void framebufferRenderbuffer(GC3Denum target, GC3Denum attachment, GC3Denum renderbuffertarget, WebGLRenderbuffer*);
-    void framebufferTexture2D(GC3Denum target, GC3Denum attachment, GC3Denum textarget, WebGLTexture*, GC3Dint level);
-    void frontFace(GC3Denum mode);
-    void generateMipmap(GC3Denum target);
+    void framebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, WebGLRenderbuffer*);
+    void framebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, WebGLTexture*, GLint level);
+    void frontFace(GLenum mode);
+    void generateMipmap(GLenum target);
 
-    PassRefPtr<WebGLActiveInfo> getActiveAttrib(WebGLProgram*, GC3Duint index);
-    PassRefPtr<WebGLActiveInfo> getActiveUniform(WebGLProgram*, GC3Duint index);
+    PassRefPtr<WebGLActiveInfo> getActiveAttrib(WebGLProgram*, GLuint index);
+    PassRefPtr<WebGLActiveInfo> getActiveUniform(WebGLProgram*, GLuint index);
     bool getAttachedShaders(WebGLProgram*, Vector<RefPtr<WebGLShader> >&);
-    GC3Dint getAttribLocation(WebGLProgram*, const String& name);
-    WebGLGetInfo getBufferParameter(GC3Denum target, GC3Denum pname);
+    GLint getAttribLocation(WebGLProgram*, const String& name);
+    WebGLGetInfo getBufferParameter(GLenum target, GLenum pname);
     PassRefPtr<WebGLContextAttributes> getContextAttributes();
-    GC3Denum getError();
+    GLenum getError();
     PassRefPtr<WebGLExtension> getExtension(const String& name);
-    WebGLGetInfo getFramebufferAttachmentParameter(GC3Denum target, GC3Denum attachment, GC3Denum pname);
-    WebGLGetInfo getParameter(GC3Denum pname);
-    WebGLGetInfo getProgramParameter(WebGLProgram*, GC3Denum pname);
+    WebGLGetInfo getFramebufferAttachmentParameter(GLenum target, GLenum attachment, GLenum pname);
+    WebGLGetInfo getParameter(GLenum pname);
+    WebGLGetInfo getProgramParameter(WebGLProgram*, GLenum pname);
     String getProgramInfoLog(WebGLProgram*);
-    WebGLGetInfo getRenderbufferParameter(GC3Denum target, GC3Denum pname);
-    WebGLGetInfo getShaderParameter(WebGLShader*, GC3Denum pname);
+    WebGLGetInfo getRenderbufferParameter(GLenum target, GLenum pname);
+    WebGLGetInfo getShaderParameter(WebGLShader*, GLenum pname);
     String getShaderInfoLog(WebGLShader*);
-    PassRefPtr<WebGLShaderPrecisionFormat> getShaderPrecisionFormat(GC3Denum shaderType, GC3Denum precisionType);
+    PassRefPtr<WebGLShaderPrecisionFormat> getShaderPrecisionFormat(GLenum shaderType, GLenum precisionType);
     String getShaderSource(WebGLShader*);
     Vector<String> getSupportedExtensions();
-    WebGLGetInfo getTexParameter(GC3Denum target, GC3Denum pname);
+    WebGLGetInfo getTexParameter(GLenum target, GLenum pname);
     WebGLGetInfo getUniform(WebGLProgram*, const WebGLUniformLocation*);
     PassRefPtr<WebGLUniformLocation> getUniformLocation(WebGLProgram*, const String&);
-    WebGLGetInfo getVertexAttrib(GC3Duint index, GC3Denum pname);
-    long long getVertexAttribOffset(GC3Duint index, GC3Denum pname);
+    WebGLGetInfo getVertexAttrib(GLuint index, GLenum pname);
+    long long getVertexAttribOffset(GLuint index, GLenum pname);
 
-    void hint(GC3Denum target, GC3Denum mode);
-    GC3Dboolean isBuffer(WebGLBuffer*);
+    void hint(GLenum target, GLenum mode);
+    GLboolean isBuffer(WebGLBuffer*);
     bool isContextLost();
-    GC3Dboolean isEnabled(GC3Denum cap);
-    GC3Dboolean isFramebuffer(WebGLFramebuffer*);
-    GC3Dboolean isProgram(WebGLProgram*);
-    GC3Dboolean isRenderbuffer(WebGLRenderbuffer*);
-    GC3Dboolean isShader(WebGLShader*);
-    GC3Dboolean isTexture(WebGLTexture*);
+    GLboolean isEnabled(GLenum cap);
+    GLboolean isFramebuffer(WebGLFramebuffer*);
+    GLboolean isProgram(WebGLProgram*);
+    GLboolean isRenderbuffer(WebGLRenderbuffer*);
+    GLboolean isShader(WebGLShader*);
+    GLboolean isTexture(WebGLTexture*);
 
-    void lineWidth(GC3Dfloat);
+    void lineWidth(GLfloat);
     void linkProgram(WebGLProgram*);
-    void pixelStorei(GC3Denum pname, GC3Dint param);
-    void polygonOffset(GC3Dfloat factor, GC3Dfloat units);
-    void readPixels(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, ArrayBufferView* pixels);
-    void renderbufferStorage(GC3Denum target, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height);
-    void sampleCoverage(GC3Dfloat value, GC3Dboolean invert);
-    void scissor(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height);
+    void pixelStorei(GLenum pname, GLint param);
+    void polygonOffset(GLfloat factor, GLfloat units);
+    void readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, ArrayBufferView* pixels);
+    void renderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+    void sampleCoverage(GLfloat value, GLboolean invert);
+    void scissor(GLint x, GLint y, GLsizei width, GLsizei height);
     void shaderSource(WebGLShader*, const String&);
-    void stencilFunc(GC3Denum func, GC3Dint ref, GC3Duint mask);
-    void stencilFuncSeparate(GC3Denum face, GC3Denum func, GC3Dint ref, GC3Duint mask);
-    void stencilMask(GC3Duint);
-    void stencilMaskSeparate(GC3Denum face, GC3Duint mask);
-    void stencilOp(GC3Denum fail, GC3Denum zfail, GC3Denum zpass);
-    void stencilOpSeparate(GC3Denum face, GC3Denum fail, GC3Denum zfail, GC3Denum zpass);
+    void stencilFunc(GLenum func, GLint ref, GLuint mask);
+    void stencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask);
+    void stencilMask(GLuint);
+    void stencilMaskSeparate(GLenum face, GLuint mask);
+    void stencilOp(GLenum fail, GLenum zfail, GLenum zpass);
+    void stencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
 
-    void texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-        GC3Dsizei width, GC3Dsizei height, GC3Dint border,
-        GC3Denum format, GC3Denum type, ArrayBufferView*, ExceptionState&);
-    void texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-        GC3Denum format, GC3Denum type, ImageData*, ExceptionState&);
-    void texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-        GC3Denum format, GC3Denum type, HTMLImageElement*, ExceptionState&);
-    void texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-        GC3Denum format, GC3Denum type, HTMLCanvasElement*, ExceptionState&);
-    void texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
-        GC3Denum format, GC3Denum type, HTMLVideoElement*, ExceptionState&);
+    void texImage2D(GLenum target, GLint level, GLenum internalformat,
+        GLsizei width, GLsizei height, GLint border,
+        GLenum format, GLenum type, ArrayBufferView*, ExceptionState&);
+    void texImage2D(GLenum target, GLint level, GLenum internalformat,
+        GLenum format, GLenum type, ImageData*, ExceptionState&);
+    void texImage2D(GLenum target, GLint level, GLenum internalformat,
+        GLenum format, GLenum type, HTMLImageElement*, ExceptionState&);
+    void texImage2D(GLenum target, GLint level, GLenum internalformat,
+        GLenum format, GLenum type, HTMLCanvasElement*, ExceptionState&);
+    void texImage2D(GLenum target, GLint level, GLenum internalformat,
+        GLenum format, GLenum type, HTMLVideoElement*, ExceptionState&);
 
-    void texParameterf(GC3Denum target, GC3Denum pname, GC3Dfloat param);
-    void texParameteri(GC3Denum target, GC3Denum pname, GC3Dint param);
+    void texParameterf(GLenum target, GLenum pname, GLfloat param);
+    void texParameteri(GLenum target, GLenum pname, GLint param);
 
-    void texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-        GC3Dsizei width, GC3Dsizei height,
-        GC3Denum format, GC3Denum type, ArrayBufferView*, ExceptionState&);
-    void texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-        GC3Denum format, GC3Denum type, ImageData*, ExceptionState&);
-    void texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-        GC3Denum format, GC3Denum type, HTMLImageElement*, ExceptionState&);
-    void texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-        GC3Denum format, GC3Denum type, HTMLCanvasElement*, ExceptionState&);
-    void texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-        GC3Denum format, GC3Denum type, HTMLVideoElement*, ExceptionState&);
+    void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLsizei width, GLsizei height,
+        GLenum format, GLenum type, ArrayBufferView*, ExceptionState&);
+    void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLenum format, GLenum type, ImageData*, ExceptionState&);
+    void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLenum format, GLenum type, HTMLImageElement*, ExceptionState&);
+    void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLenum format, GLenum type, HTMLCanvasElement*, ExceptionState&);
+    void texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLenum format, GLenum type, HTMLVideoElement*, ExceptionState&);
 
-    void uniform1f(const WebGLUniformLocation*, GC3Dfloat x);
+    void uniform1f(const WebGLUniformLocation*, GLfloat x);
     void uniform1fv(const WebGLUniformLocation*, Float32Array* v);
-    void uniform1fv(const WebGLUniformLocation*, GC3Dfloat* v, GC3Dsizei);
-    void uniform1i(const WebGLUniformLocation*, GC3Dint x);
+    void uniform1fv(const WebGLUniformLocation*, GLfloat* v, GLsizei);
+    void uniform1i(const WebGLUniformLocation*, GLint x);
     void uniform1iv(const WebGLUniformLocation*, Int32Array* v);
-    void uniform1iv(const WebGLUniformLocation*, GC3Dint* v, GC3Dsizei);
-    void uniform2f(const WebGLUniformLocation*, GC3Dfloat x, GC3Dfloat y);
+    void uniform1iv(const WebGLUniformLocation*, GLint* v, GLsizei);
+    void uniform2f(const WebGLUniformLocation*, GLfloat x, GLfloat y);
     void uniform2fv(const WebGLUniformLocation*, Float32Array* v);
-    void uniform2fv(const WebGLUniformLocation*, GC3Dfloat* v, GC3Dsizei);
-    void uniform2i(const WebGLUniformLocation*, GC3Dint x, GC3Dint y);
+    void uniform2fv(const WebGLUniformLocation*, GLfloat* v, GLsizei);
+    void uniform2i(const WebGLUniformLocation*, GLint x, GLint y);
     void uniform2iv(const WebGLUniformLocation*, Int32Array* v);
-    void uniform2iv(const WebGLUniformLocation*, GC3Dint* v, GC3Dsizei);
-    void uniform3f(const WebGLUniformLocation*, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z);
+    void uniform2iv(const WebGLUniformLocation*, GLint* v, GLsizei);
+    void uniform3f(const WebGLUniformLocation*, GLfloat x, GLfloat y, GLfloat z);
     void uniform3fv(const WebGLUniformLocation*, Float32Array* v);
-    void uniform3fv(const WebGLUniformLocation*, GC3Dfloat* v, GC3Dsizei);
-    void uniform3i(const WebGLUniformLocation*, GC3Dint x, GC3Dint y, GC3Dint z);
+    void uniform3fv(const WebGLUniformLocation*, GLfloat* v, GLsizei);
+    void uniform3i(const WebGLUniformLocation*, GLint x, GLint y, GLint z);
     void uniform3iv(const WebGLUniformLocation*, Int32Array* v);
-    void uniform3iv(const WebGLUniformLocation*, GC3Dint* v, GC3Dsizei);
-    void uniform4f(const WebGLUniformLocation*, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z, GC3Dfloat w);
+    void uniform3iv(const WebGLUniformLocation*, GLint* v, GLsizei);
+    void uniform4f(const WebGLUniformLocation*, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
     void uniform4fv(const WebGLUniformLocation*, Float32Array* v);
-    void uniform4fv(const WebGLUniformLocation*, GC3Dfloat* v, GC3Dsizei);
-    void uniform4i(const WebGLUniformLocation*, GC3Dint x, GC3Dint y, GC3Dint z, GC3Dint w);
+    void uniform4fv(const WebGLUniformLocation*, GLfloat* v, GLsizei);
+    void uniform4i(const WebGLUniformLocation*, GLint x, GLint y, GLint z, GLint w);
     void uniform4iv(const WebGLUniformLocation*, Int32Array* v);
-    void uniform4iv(const WebGLUniformLocation*, GC3Dint* v, GC3Dsizei);
-    void uniformMatrix2fv(const WebGLUniformLocation*, GC3Dboolean transpose, Float32Array* value);
-    void uniformMatrix2fv(const WebGLUniformLocation*, GC3Dboolean transpose, GC3Dfloat* value, GC3Dsizei);
-    void uniformMatrix3fv(const WebGLUniformLocation*, GC3Dboolean transpose, Float32Array* value);
-    void uniformMatrix3fv(const WebGLUniformLocation*, GC3Dboolean transpose, GC3Dfloat* value, GC3Dsizei);
-    void uniformMatrix4fv(const WebGLUniformLocation*, GC3Dboolean transpose, Float32Array* value);
-    void uniformMatrix4fv(const WebGLUniformLocation*, GC3Dboolean transpose, GC3Dfloat* value, GC3Dsizei);
+    void uniform4iv(const WebGLUniformLocation*, GLint* v, GLsizei);
+    void uniformMatrix2fv(const WebGLUniformLocation*, GLboolean transpose, Float32Array* value);
+    void uniformMatrix2fv(const WebGLUniformLocation*, GLboolean transpose, GLfloat* value, GLsizei);
+    void uniformMatrix3fv(const WebGLUniformLocation*, GLboolean transpose, Float32Array* value);
+    void uniformMatrix3fv(const WebGLUniformLocation*, GLboolean transpose, GLfloat* value, GLsizei);
+    void uniformMatrix4fv(const WebGLUniformLocation*, GLboolean transpose, Float32Array* value);
+    void uniformMatrix4fv(const WebGLUniformLocation*, GLboolean transpose, GLfloat* value, GLsizei);
 
     void useProgram(WebGLProgram*);
     void validateProgram(WebGLProgram*);
 
-    void vertexAttrib1f(GC3Duint index, GC3Dfloat x);
-    void vertexAttrib1fv(GC3Duint index, Float32Array* values);
-    void vertexAttrib1fv(GC3Duint index, GC3Dfloat* values, GC3Dsizei);
-    void vertexAttrib2f(GC3Duint index, GC3Dfloat x, GC3Dfloat y);
-    void vertexAttrib2fv(GC3Duint index, Float32Array* values);
-    void vertexAttrib2fv(GC3Duint index, GC3Dfloat* values, GC3Dsizei);
-    void vertexAttrib3f(GC3Duint index, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z);
-    void vertexAttrib3fv(GC3Duint index, Float32Array* values);
-    void vertexAttrib3fv(GC3Duint index, GC3Dfloat* values, GC3Dsizei);
-    void vertexAttrib4f(GC3Duint index, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z, GC3Dfloat w);
-    void vertexAttrib4fv(GC3Duint index, Float32Array* values);
-    void vertexAttrib4fv(GC3Duint index, GC3Dfloat* values, GC3Dsizei);
-    void vertexAttribPointer(GC3Duint index, GC3Dint size, GC3Denum type, GC3Dboolean normalized,
-        GC3Dsizei stride, long long offset);
+    void vertexAttrib1f(GLuint index, GLfloat x);
+    void vertexAttrib1fv(GLuint index, Float32Array* values);
+    void vertexAttrib1fv(GLuint index, GLfloat* values, GLsizei);
+    void vertexAttrib2f(GLuint index, GLfloat x, GLfloat y);
+    void vertexAttrib2fv(GLuint index, Float32Array* values);
+    void vertexAttrib2fv(GLuint index, GLfloat* values, GLsizei);
+    void vertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z);
+    void vertexAttrib3fv(GLuint index, Float32Array* values);
+    void vertexAttrib3fv(GLuint index, GLfloat* values, GLsizei);
+    void vertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+    void vertexAttrib4fv(GLuint index, Float32Array* values);
+    void vertexAttrib4fv(GLuint index, GLfloat* values, GLsizei);
+    void vertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized,
+        GLsizei stride, long long offset);
 
-    void vertexAttribDivisorANGLE(GC3Duint index, GC3Duint divisor);
+    void vertexAttribDivisorANGLE(GLuint index, GLuint divisor);
 
-    void viewport(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height);
+    void viewport(GLint x, GLint y, GLsizei width, GLsizei height);
 
     // WEBKIT_lose_context support
     enum LostContextMode {
@@ -313,15 +318,16 @@
     void forceRestoreContext();
     void loseContextImpl(LostContextMode);
 
-    GraphicsContext3D* graphicsContext3D() const { return m_context.get(); }
+    blink::WebGraphicsContext3D* webGraphicsContext3D() const { return m_context.get(); }
     WebGLContextGroup* contextGroup() const { return m_contextGroup.get(); }
-    virtual blink::WebLayer* platformLayer() const;
+    virtual blink::WebLayer* platformLayer() const OVERRIDE;
+    Extensions3DUtil* extensionsUtil();
 
     void reshape(int width, int height);
 
     void markLayerComposited();
-    virtual void paintRenderingResultsToCanvas();
-    virtual PassRefPtr<ImageData> paintRenderingResultsToImageData();
+    virtual void paintRenderingResultsToCanvas() OVERRIDE;
+    PassRefPtr<ImageData> paintRenderingResultsToImageData();
 
     void removeSharedObject(WebGLSharedObject*);
     void removeContextObject(WebGLContextObject*);
@@ -329,8 +335,8 @@
     unsigned maxVertexAttribs() const { return m_maxVertexAttribs; }
 
     // ActiveDOMObject notifications
-    virtual bool hasPendingActivity() const;
-    virtual void stop();
+    virtual bool hasPendingActivity() const OVERRIDE;
+    virtual void stop() OVERRIDE;
 
   private:
     friend class WebGLDrawBuffers;
@@ -344,7 +350,7 @@
     friend class WebGLRenderingContextErrorMessageCallback;
     friend class WebGLVertexArrayObjectOES;
 
-    WebGLRenderingContext(HTMLCanvasElement*, PassRefPtr<GraphicsContext3D>, GraphicsContext3D::Attributes, GraphicsContext3D::Attributes);
+    WebGLRenderingContext(HTMLCanvasElement*, PassOwnPtr<blink::WebGraphicsContext3D>, WebGLContextAttributes*);
     void initializeNewContext();
     void setupFlags();
 
@@ -352,7 +358,7 @@
     void addContextObject(WebGLContextObject*);
     void detachAndRemoveAllObjects();
 
-    void destroyGraphicsContext3D();
+    void destroyContext();
     void markContextChanged();
 
     // Query if the GL implementation is NPOT strict.
@@ -362,24 +368,24 @@
 
     // Helper to return the size in bytes of OpenGL data types
     // like GL_FLOAT, GL_INT, etc.
-    unsigned int sizeInBytes(GC3Denum type);
+    unsigned sizeInBytes(GLenum type);
 
     // Check if each enabled vertex attribute is bound to a buffer.
-    bool validateRenderingState();
+    bool validateRenderingState(const char*);
 
     bool validateWebGLObject(const char*, WebGLObject*);
 
     // Adds a compressed texture format.
-    void addCompressedTextureFormat(GC3Denum);
+    void addCompressedTextureFormat(GLenum);
     void removeAllCompressedTextureFormats();
 
     PassRefPtr<Image> drawImageIntoBuffer(Image*, int width, int height);
 
     PassRefPtr<Image> videoFrameToImage(HTMLVideoElement*, BackingStoreCopy);
 
-    WebGLRenderbuffer* ensureEmulatedStencilBuffer(GC3Denum target, WebGLRenderbuffer*);
+    WebGLRenderbuffer* ensureEmulatedStencilBuffer(GLenum target, WebGLRenderbuffer*);
 
-    RefPtr<GraphicsContext3D> m_context;
+    OwnPtr<blink::WebGraphicsContext3D> m_context;
     RefPtr<WebGLContextGroup> m_contextGroup;
 
     // Structure for rendering to a DrawingBuffer, instead of directly
@@ -399,6 +405,9 @@
     bool m_markedCanvasDirty;
     HashSet<WebGLContextObject*> m_contextObjects;
 
+    OwnPtr<WebGLRenderingContextLostCallback> m_contextLostCallbackAdapter;
+    OwnPtr<WebGLRenderingContextErrorMessageCallback> m_errorMessageCallbackAdapter;
+
     // List of bound VBO's. Used to maintain info about sizes for ARRAY_BUFFER and stored values for ELEMENT_ARRAY_BUFFER
     RefPtr<WebGLBuffer> m_boundArrayBuffer;
 
@@ -427,13 +436,13 @@
             value[3] = 1.0f;
         }
 
-        GC3Dfloat value[4];
+        GLfloat value[4];
     };
     Vector<VertexAttribValue> m_vertexAttribValue;
     unsigned m_maxVertexAttribs;
     RefPtr<WebGLBuffer> m_vertexAttrib0Buffer;
     long m_vertexAttrib0BufferSize;
-    GC3Dfloat m_vertexAttrib0BufferValue[4];
+    GLfloat m_vertexAttrib0BufferValue[4];
     bool m_forceAttrib0BufferRefill;
     bool m_vertexAttrib0UsedBefore;
 
@@ -451,7 +460,7 @@
     RefPtr<WebGLTexture> m_blackTexture2D;
     RefPtr<WebGLTexture> m_blackTextureCubeMap;
 
-    Vector<GC3Denum> m_compressedTextureFormats;
+    Vector<GLenum> m_compressedTextureFormats;
 
     // Fixed-size cache of reusable image buffers for video texImage2D calls.
     class LRUImageBufferCache {
@@ -466,41 +475,40 @@
     };
     LRUImageBufferCache m_generatedImageCache;
 
-    GC3Dint m_maxTextureSize;
-    GC3Dint m_maxCubeMapTextureSize;
-    GC3Dint m_maxRenderbufferSize;
-    GC3Dint m_maxViewportDims[2];
-    GC3Dint m_maxTextureLevel;
-    GC3Dint m_maxCubeMapTextureLevel;
+    GLint m_maxTextureSize;
+    GLint m_maxCubeMapTextureSize;
+    GLint m_maxRenderbufferSize;
+    GLint m_maxViewportDims[2];
+    GLint m_maxTextureLevel;
+    GLint m_maxCubeMapTextureLevel;
 
-    GC3Dint m_maxDrawBuffers;
-    GC3Dint m_maxColorAttachments;
-    GC3Denum m_backDrawBuffer;
+    GLint m_maxDrawBuffers;
+    GLint m_maxColorAttachments;
+    GLenum m_backDrawBuffer;
     bool m_drawBuffersWebGLRequirementsChecked;
     bool m_drawBuffersSupported;
 
-    GC3Dint m_packAlignment;
-    GC3Dint m_unpackAlignment;
+    GLint m_packAlignment;
+    GLint m_unpackAlignment;
     bool m_unpackFlipY;
     bool m_unpackPremultiplyAlpha;
-    GC3Denum m_unpackColorspaceConversion;
+    GLenum m_unpackColorspaceConversion;
     bool m_contextLost;
     LostContextMode m_contextLostMode;
-    GraphicsContext3D::Attributes m_attributes;
-    GraphicsContext3D::Attributes m_requestedAttributes;
+    RefPtr<WebGLContextAttributes> m_requestedAttributes;
 
     bool m_layerCleared;
-    GC3Dfloat m_clearColor[4];
+    GLfloat m_clearColor[4];
     bool m_scissorEnabled;
-    GC3Dfloat m_clearDepth;
-    GC3Dint m_clearStencil;
-    GC3Dboolean m_colorMask[4];
-    GC3Dboolean m_depthMask;
+    GLfloat m_clearDepth;
+    GLint m_clearStencil;
+    GLboolean m_colorMask[4];
+    GLboolean m_depthMask;
 
     bool m_stencilEnabled;
-    GC3Duint m_stencilMask, m_stencilMaskBack;
-    GC3Dint m_stencilFuncRef, m_stencilFuncRefBack; // Note that these are the user specified values, not the internal clamped value.
-    GC3Duint m_stencilFuncMask, m_stencilFuncMaskBack;
+    GLuint m_stencilMask, m_stencilMaskBack;
+    GLint m_stencilFuncRef, m_stencilFuncRefBack; // Note that these are the user specified values, not the internal clamped value.
+    GLuint m_stencilFuncMask, m_stencilFuncMaskBack;
 
     bool m_isGLES2NPOTStrict;
     bool m_isDepthStencilSupported;
@@ -511,9 +519,12 @@
     bool m_multisamplingAllowed;
     bool m_multisamplingObserverRegistered;
 
-    GC3Duint m_onePlusMaxEnabledAttribIndex;
+    GLuint m_onePlusMaxEnabledAttribIndex;
     unsigned long m_onePlusMaxNonDefaultTextureUnit;
 
+    bool m_preserveDrawingBuffer;
+    OwnPtr<Extensions3DUtil> m_extensionsUtil;
+
     // Enabled extension objects.
     RefPtr<ANGLEInstancedArrays> m_angleInstancedArrays;
     RefPtr<EXTFragDepth> m_extFragDepth;
@@ -593,7 +604,7 @@
     };
 
     template <typename T>
-    class TypedExtensionTracker : public ExtensionTracker {
+    class TypedExtensionTracker FINAL : public ExtensionTracker {
     public:
         TypedExtensionTracker(RefPtr<T>& extensionField, ExtensionFlags flags, const char* const* prefixes)
             : ExtensionTracker(flags, prefixes)
@@ -609,7 +620,7 @@
             }
         }
 
-        virtual PassRefPtr<WebGLExtension> getExtension(WebGLRenderingContext* context) const
+        virtual PassRefPtr<WebGLExtension> getExtension(WebGLRenderingContext* context) const OVERRIDE
         {
             if (!m_extensionField)
                 m_extensionField = T::create(context);
@@ -617,17 +628,17 @@
             return m_extensionField;
         }
 
-        virtual bool supported(WebGLRenderingContext* context) const
+        virtual bool supported(WebGLRenderingContext* context) const OVERRIDE
         {
             return T::supported(context);
         }
 
-        virtual const char* extensionName() const
+        virtual const char* extensionName() const OVERRIDE
         {
             return T::extensionName();
         }
 
-        virtual void loseExtension()
+        virtual void loseExtension() OVERRIDE
         {
             if (m_extensionField) {
                 m_extensionField->lose(false);
@@ -649,29 +660,32 @@
     }
 
     // Errors raised by synthesizeGLError() while the context is lost.
-    Vector<GC3Denum> lost_context_errors_;
+    Vector<GLenum> m_lostContextErrors;
 
     // Helpers for getParameter and others
-    WebGLGetInfo getBooleanParameter(GC3Denum);
-    WebGLGetInfo getBooleanArrayParameter(GC3Denum);
-    WebGLGetInfo getFloatParameter(GC3Denum);
-    WebGLGetInfo getIntParameter(GC3Denum);
-    WebGLGetInfo getUnsignedIntParameter(GC3Denum);
-    WebGLGetInfo getWebGLFloatArrayParameter(GC3Denum);
-    WebGLGetInfo getWebGLIntArrayParameter(GC3Denum);
+    WebGLGetInfo getBooleanParameter(GLenum);
+    WebGLGetInfo getBooleanArrayParameter(GLenum);
+    WebGLGetInfo getFloatParameter(GLenum);
+    WebGLGetInfo getIntParameter(GLenum);
+    WebGLGetInfo getUnsignedIntParameter(GLenum);
+    WebGLGetInfo getWebGLFloatArrayParameter(GLenum);
+    WebGLGetInfo getWebGLIntArrayParameter(GLenum);
 
     // Clear the backbuffer if it was composited since the last operation.
     // clearMask is set to the bitfield of any clear that would happen anyway at this time
     // and the function returns true if that clear is now unnecessary.
-    bool clearIfComposited(GC3Dbitfield clearMask = 0);
+    bool clearIfComposited(GLbitfield clearMask = 0);
 
     // Helper to restore state that clearing the framebuffer may destroy.
     void restoreStateAfterClear();
 
-    void texImage2DBase(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState&);
-    void texImage2DImpl(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Denum format, GC3Denum type, Image*, GraphicsContext3D::ImageHtmlDomSource, bool flipY, bool premultiplyAlpha, ExceptionState&);
-    void texSubImage2DBase(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState&);
-    void texSubImage2DImpl(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Denum format, GC3Denum type, Image*, GraphicsContext3D::ImageHtmlDomSource, bool flipY, bool premultiplyAlpha, ExceptionState&);
+    // Convert texture internal format.
+    GLenum convertTexInternalFormat(GLenum internalformat, GLenum type);
+
+    void texImage2DBase(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels, ExceptionState&);
+    void texImage2DImpl(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, Image*, WebGLImageConversion::ImageHtmlDomSource, bool flipY, bool premultiplyAlpha, ExceptionState&);
+    void texSubImage2DBase(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels, ExceptionState&);
+    void texSubImage2DImpl(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, Image*, WebGLImageConversion::ImageHtmlDomSource, bool flipY, bool premultiplyAlpha, ExceptionState&);
 
     void handleTextureCompleteness(const char*, bool);
     void createFallbackBlackTextures1x1();
@@ -679,11 +693,10 @@
     // Helper function for copyTex{Sub}Image, check whether the internalformat
     // and the color buffer format of the current bound framebuffer combination
     // is valid.
-    bool isTexInternalFormatColorBufferCombinationValid(GC3Denum texInternalFormat,
-                                                        GC3Denum colorBufferFormat);
+    bool isTexInternalFormatColorBufferCombinationValid(GLenum texInternalFormat, GLenum colorBufferFormat);
 
     // Helper function to get the bound framebuffer's color buffer format.
-    GC3Denum boundFramebufferColorFormat();
+    GLenum boundFramebufferColorFormat();
 
     // Helper function to get the bound framebuffer's width.
     int boundFramebufferWidth();
@@ -696,7 +709,7 @@
 
     // Helper function to check if size is non-negative.
     // Generate GL error and return false for negative inputs; otherwise, return true.
-    bool validateSize(const char* functionName, GC3Dint x, GC3Dint y);
+    bool validateSize(const char* functionName, GLint x, GLint y);
 
     // Helper function to check if all characters in the string belong to the
     // ASCII subset as defined in GLSL ES 1.0 spec section 3.1.
@@ -705,15 +718,15 @@
     // Helper function to check target and texture bound to the target.
     // Generate GL errors and return 0 if target is invalid or texture bound is
     // null.  Otherwise, return the texture bound to the target.
-    WebGLTexture* validateTextureBinding(const char* functionName, GC3Denum target, bool useSixEnumsForCubeMap);
+    WebGLTexture* validateTextureBinding(const char* functionName, GLenum target, bool useSixEnumsForCubeMap);
 
     // Helper function to check input format/type for functions {copy}Tex{Sub}Image.
     // Generates GL error and returns false if parameters are invalid.
-    bool validateTexFuncFormatAndType(const char* functionName, GC3Denum format, GC3Denum type, GC3Dint level);
+    bool validateTexFuncFormatAndType(const char* functionName, GLenum format, GLenum type, GLint level);
 
     // Helper function to check input level for functions {copy}Tex{Sub}Image.
     // Generates GL error and returns false if level is invalid.
-    bool validateTexFuncLevel(const char* functionName, GC3Denum target, GC3Dint level);
+    bool validateTexFuncLevel(const char* functionName, GLenum target, GLint level);
 
     enum TexFuncValidationFunctionType {
         NotTexSubImage2D,
@@ -730,22 +743,16 @@
 
     // Helper function for tex{Sub}Image2D to check if the input format/type/level/target/width/height/border/xoffset/yoffset are valid.
     // Otherwise, it would return quickly without doing other work.
-    bool validateTexFunc(const char* functionName, TexFuncValidationFunctionType, TexFuncValidationSourceType, GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width,
-        GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, GC3Dint xoffset, GC3Dint yoffset);
+    bool validateTexFunc(const char* functionName, TexFuncValidationFunctionType, TexFuncValidationSourceType, GLenum target, GLint level, GLenum internalformat, GLsizei width,
+        GLsizei height, GLint border, GLenum format, GLenum type, GLint xoffset, GLint yoffset);
 
     // Helper function to check input width and height for functions {copy, compressed}Tex{Sub}Image.
     // Generates GL error and returns false if width or height is invalid.
-    bool validateTexFuncDimensions(const char* functionName, TexFuncValidationFunctionType,
-        GC3Denum target, GC3Dint level, GC3Dsizei width, GC3Dsizei height);
+    bool validateTexFuncDimensions(const char* functionName, TexFuncValidationFunctionType, GLenum target, GLint level, GLsizei width, GLsizei height);
 
     // Helper function to check input parameters for functions {copy}Tex{Sub}Image.
     // Generates GL error and returns false if parameters are invalid.
-    bool validateTexFuncParameters(const char* functionName,
-                                   TexFuncValidationFunctionType,
-                                   GC3Denum target, GC3Dint level,
-                                   GC3Denum internalformat,
-                                   GC3Dsizei width, GC3Dsizei height, GC3Dint border,
-                                   GC3Denum format, GC3Denum type);
+    bool validateTexFuncParameters(const char* functionName, TexFuncValidationFunctionType, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type);
 
     enum NullDisposition {
         NullAllowed,
@@ -755,47 +762,40 @@
     // Helper function to validate that the given ArrayBufferView
     // is of the correct type and contains enough data for the texImage call.
     // Generates GL error and returns false if parameters are invalid.
-    bool validateTexFuncData(const char* functionName, GC3Dint level,
-                             GC3Dsizei width, GC3Dsizei height,
-                             GC3Denum format, GC3Denum type,
-                             ArrayBufferView* pixels,
-                             NullDisposition);
+    bool validateTexFuncData(const char* functionName, GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, ArrayBufferView* pixels, NullDisposition);
 
     // Helper function to validate a given texture format is settable as in
     // you can supply data to texImage2D, or call texImage2D, copyTexImage2D and
     // copyTexSubImage2D.
     // Generates GL error and returns false if the format is not settable.
-    bool validateSettableTexFormat(const char* functionName, GC3Denum format);
+    bool validateSettableTexFormat(const char* functionName, GLenum format);
 
     // Helper function to validate compressed texture data is correct size
     // for the given format and dimensions.
-    bool validateCompressedTexFuncData(const char* functionName,
-                                       GC3Dsizei width, GC3Dsizei height,
-                                       GC3Denum format, ArrayBufferView* pixels);
+    bool validateCompressedTexFuncData(const char* functionName, GLsizei width, GLsizei height, GLenum format, ArrayBufferView* pixels);
 
     // Helper function for validating compressed texture formats.
-    bool validateCompressedTexFormat(GC3Denum format);
+    bool validateCompressedTexFormat(GLenum format);
 
     // Helper function to validate compressed texture dimensions are valid for
     // the given format.
-    bool validateCompressedTexDimensions(const char* functionName, TexFuncValidationFunctionType, GC3Denum target, GC3Dint level, GC3Dsizei width, GC3Dsizei height, GC3Denum format);
+    bool validateCompressedTexDimensions(const char* functionName, TexFuncValidationFunctionType, GLenum target, GLint level, GLsizei width, GLsizei height, GLenum format);
 
     // Helper function to validate compressed texture dimensions are valid for
     // the given format.
-    bool validateCompressedTexSubDimensions(const char* functionName, GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
-                                            GC3Dsizei width, GC3Dsizei height, GC3Denum format, WebGLTexture*);
+    bool validateCompressedTexSubDimensions(const char* functionName, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, WebGLTexture*);
 
     // Helper function to validate mode for draw{Arrays/Elements}.
-    bool validateDrawMode(const char* functionName, GC3Denum);
+    bool validateDrawMode(const char* functionName, GLenum);
 
     // Helper function to validate if front/back stencilMask and stencilFunc settings are the same.
     bool validateStencilSettings(const char* functionName);
 
     // Helper function to validate stencil or depth func.
-    bool validateStencilOrDepthFunc(const char* functionName, GC3Denum);
+    bool validateStencilOrDepthFunc(const char* functionName, GLenum);
 
     // Helper function for texParameterf and texParameteri.
-    void texParameter(GC3Denum target, GC3Denum pname, GC3Dfloat parami, GC3Dint paramf, bool isFloat);
+    void texParameter(GLenum target, GLenum pname, GLfloat parami, GLint paramf, bool isFloat);
 
     // Helper function to print GL errors to console.
     void printGLErrorToConsole(const String&);
@@ -806,27 +806,27 @@
 
     // Helper function to validate input parameters for framebuffer functions.
     // Generate GL error if parameters are illegal.
-    bool validateFramebufferFuncParameters(const char* functionName, GC3Denum target, GC3Denum attachment);
+    bool validateFramebufferFuncParameters(const char* functionName, GLenum target, GLenum attachment);
 
     // Helper function to validate blend equation mode.
-    bool validateBlendEquation(const char* functionName, GC3Denum);
+    bool validateBlendEquation(const char* functionName, GLenum);
 
     // Helper function to validate blend func factors.
-    bool validateBlendFuncFactors(const char* functionName, GC3Denum src, GC3Denum dst);
+    bool validateBlendFuncFactors(const char* functionName, GLenum src, GLenum dst);
 
     // Helper function to validate a GL capability.
-    bool validateCapability(const char* functionName, GC3Denum);
+    bool validateCapability(const char* functionName, GLenum);
 
     // Helper function to validate input parameters for uniform functions.
-    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation*, Float32Array*, GC3Dsizei mod);
-    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation*, Int32Array*, GC3Dsizei mod);
-    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation*, void*, GC3Dsizei, GC3Dsizei mod);
-    bool validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation*, GC3Dboolean transpose, Float32Array*, GC3Dsizei mod);
-    bool validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation*, GC3Dboolean transpose, void*, GC3Dsizei, GC3Dsizei mod);
+    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation*, Float32Array*, GLsizei mod);
+    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation*, Int32Array*, GLsizei mod);
+    bool validateUniformParameters(const char* functionName, const WebGLUniformLocation*, void*, GLsizei, GLsizei mod);
+    bool validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation*, GLboolean transpose, Float32Array*, GLsizei mod);
+    bool validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation*, GLboolean transpose, void*, GLsizei, GLsizei mod);
 
     // Helper function to validate parameters for bufferData.
     // Return the current bound buffer to target, or 0 if parameters are invalid.
-    WebGLBuffer* validateBufferDataParameters(const char* functionName, GC3Denum target, GC3Denum usage);
+    WebGLBuffer* validateBufferDataParameters(const char* functionName, GLenum target, GLenum usage);
 
     // Helper function for tex{Sub}Image2D to make sure image is ready and wouldn't taint Origin.
     bool validateHTMLImageElement(const char* functionName, HTMLImageElement*, ExceptionState&);
@@ -838,18 +838,18 @@
     bool validateHTMLVideoElement(const char* functionName, HTMLVideoElement*, ExceptionState&);
 
     // Helper function to validate drawArrays(Instanced) calls
-    bool validateDrawArrays(const char* functionName, GC3Denum mode, GC3Dint first, GC3Dsizei count);
+    bool validateDrawArrays(const char* functionName, GLenum mode, GLint first, GLsizei count);
 
     // Helper function to validate drawElements(Instanced) calls
-    bool validateDrawElements(const char* functionName, GC3Denum mode, GC3Dsizei count, GC3Denum type, long long offset);
+    bool validateDrawElements(const char* functionName, GLenum mode, GLsizei count, GLenum type, long long offset);
 
     // Helper function to validate draw*Instanced calls
-    bool validateDrawInstanced(const char* functionName, GC3Dsizei primcount);
+    bool validateDrawInstanced(const char* functionName, GLsizei primcount);
 
     // Helper functions for vertexAttribNf{v}.
-    void vertexAttribfImpl(const char* functionName, GC3Duint index, GC3Dsizei expectedSize, GC3Dfloat, GC3Dfloat, GC3Dfloat, GC3Dfloat);
-    void vertexAttribfvImpl(const char* functionName, GC3Duint index, Float32Array*, GC3Dsizei expectedSize);
-    void vertexAttribfvImpl(const char* functionName, GC3Duint index, GC3Dfloat*, GC3Dsizei, GC3Dsizei expectedSize);
+    void vertexAttribfImpl(const char* functionName, GLuint index, GLsizei expectedSize, GLfloat, GLfloat, GLfloat, GLfloat);
+    void vertexAttribfvImpl(const char* functionName, GLuint index, Float32Array*, GLsizei expectedSize);
+    void vertexAttribfvImpl(const char* functionName, GLuint index, GLfloat*, GLsizei, GLsizei expectedSize);
 
     // Helper function for delete* (deleteBuffer, deleteProgram, etc) functions.
     // Return false if caller should return without further processing.
@@ -878,9 +878,9 @@
         DontDisplayInConsole
     };
 
-    // Wrapper for GraphicsContext3D::synthesizeGLError that sends a message
+    // Wrapper for WebGraphicsContext3D::synthesizeGLError that sends a message
     // to the JavaScript console.
-    void synthesizeGLError(GC3Denum, const char* functionName, const char* description, ConsoleDisplayPreference = DisplayInConsole);
+    void synthesizeGLError(GLenum, const char* functionName, const char* description, ConsoleDisplayPreference = DisplayInConsole);
     void emitGLWarning(const char* function, const char* reason);
 
     String ensureNotNull(const String&) const;
@@ -890,22 +890,22 @@
     void applyStencilTest();
 
     // Helper for enabling or disabling a capability.
-    void enableOrDisable(GC3Denum capability, bool enable);
+    void enableOrDisable(GLenum capability, bool enable);
 
     // Clamp the width and height to GL_MAX_VIEWPORT_DIMS.
     IntSize clampedCanvasSize();
 
     // First time called, if EXT_draw_buffers is supported, query the value; otherwise return 0.
     // Later, return the cached value.
-    GC3Dint maxDrawBuffers();
-    GC3Dint maxColorAttachments();
+    GLint maxDrawBuffers();
+    GLint maxColorAttachments();
 
-    void setBackDrawBuffer(GC3Denum);
+    void setBackDrawBuffer(GLenum);
 
     void restoreCurrentFramebuffer();
     void restoreCurrentTexture2D();
 
-    virtual void multisamplingChanged(bool);
+    virtual void multisamplingChanged(bool) OVERRIDE;
 
     void findNewMaxEnabledAttribIndex();
     void findNewMaxNonDefaultTextureUnit();
diff --git a/Source/core/html/canvas/WebGLRenderingContext.idl b/Source/core/html/canvas/WebGLRenderingContext.idl
index a006bae..ef8746e 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.idl
+++ b/Source/core/html/canvas/WebGLRenderingContext.idl
@@ -39,7 +39,8 @@
 typedef /*unrestricted*/ float GLclampf;
 
 [
-    DoNotCheckConstants
+    DoNotCheckConstants,
+    StrictTypeChecking,
 ] interface WebGLRenderingContext : CanvasRenderingContext {
 
     /* ClearBufferMask */
@@ -460,203 +461,214 @@
     readonly attribute GLsizei drawingBufferWidth;
     readonly attribute GLsizei drawingBufferHeight;
 
-    [StrictTypeChecking] void         activeTexture(GLenum texture);
-    [StrictTypeChecking] void         attachShader(WebGLProgram program, WebGLShader shader);
-    [StrictTypeChecking] void         bindAttribLocation(WebGLProgram program, GLuint index, DOMString name);
-    [StrictTypeChecking] void         bindBuffer(GLenum target, WebGLBuffer buffer);
-    [StrictTypeChecking] void         bindFramebuffer(GLenum target, WebGLFramebuffer framebuffer);
-    [StrictTypeChecking] void         bindRenderbuffer(GLenum target, WebGLRenderbuffer renderbuffer);
-    [StrictTypeChecking] void         bindTexture(GLenum target, WebGLTexture texture);
-    [StrictTypeChecking] void         blendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
-    [StrictTypeChecking] void         blendEquation(GLenum mode);
-    [StrictTypeChecking] void         blendEquationSeparate(GLenum modeRGB, GLenum modeAlpha);
-    [StrictTypeChecking] void         blendFunc(GLenum sfactor, GLenum dfactor);
-    [StrictTypeChecking] void         blendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
-    [StrictTypeChecking] void         bufferData(GLenum target, ArrayBuffer? data, GLenum usage);
-    [StrictTypeChecking] void         bufferData(GLenum target, ArrayBufferView? data, GLenum usage);
-    [StrictTypeChecking] void         bufferData(GLenum target, GLsizeiptr size, GLenum usage);
-    [StrictTypeChecking] void         bufferSubData(GLenum target, GLintptr offset, ArrayBuffer? data);
-    [StrictTypeChecking] void         bufferSubData(GLenum target, GLintptr offset, ArrayBufferView? data);
+    void activeTexture(GLenum texture);
+    void attachShader(WebGLProgram? program, WebGLShader? shader);
+    void bindAttribLocation(WebGLProgram? program, GLuint index, DOMString name);
+    void bindBuffer(GLenum target, WebGLBuffer? buffer);
+    void bindFramebuffer(GLenum target, WebGLFramebuffer? framebuffer);
+    void bindRenderbuffer(GLenum target, WebGLRenderbuffer? renderbuffer);
+    void bindTexture(GLenum target, WebGLTexture? texture);
+    void blendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+    void blendEquation(GLenum mode);
+    void blendEquationSeparate(GLenum modeRGB, GLenum modeAlpha);
+    void blendFunc(GLenum sfactor, GLenum dfactor);
+    void blendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+    void bufferData(GLenum target, ArrayBuffer? data, GLenum usage);
+    void bufferData(GLenum target, ArrayBufferView? data, GLenum usage);
+    void bufferData(GLenum target, GLsizeiptr size, GLenum usage);
+    void bufferSubData(GLenum target, GLintptr offset, ArrayBuffer? data);
+    void bufferSubData(GLenum target, GLintptr offset, ArrayBufferView? data);
 
-    [StrictTypeChecking] GLenum       checkFramebufferStatus(GLenum target);
-    [StrictTypeChecking] void         clear(GLbitfield mask);
-    [StrictTypeChecking] void         clearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
-    [StrictTypeChecking] void         clearDepth(GLclampf depth);
-    [StrictTypeChecking] void         clearStencil(GLint s);
-    [StrictTypeChecking] void         colorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
-    [StrictTypeChecking] void         compileShader(WebGLShader shader);
+    GLenum checkFramebufferStatus(GLenum target);
+    void clear(GLbitfield mask);
+    void clearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+    void clearDepth(GLclampf depth);
+    void clearStencil(GLint s);
+    void colorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+    void compileShader(WebGLShader? shader);
 
-    [StrictTypeChecking] void         compressedTexImage2D(GLenum target, GLint level, GLenum internalformat,
-                                                           GLsizei width, GLsizei height, GLint border, ArrayBufferView data);
-    [StrictTypeChecking] void         compressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
-                                                              GLsizei width, GLsizei height, GLenum format, ArrayBufferView data);
+    void compressedTexImage2D(GLenum target, GLint level, GLenum internalformat,
+                              GLsizei width, GLsizei height, GLint border, ArrayBufferView? data);
+    void compressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
+                                 GLsizei width, GLsizei height, GLenum format, ArrayBufferView? data);
 
-    [StrictTypeChecking] void         copyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
-    [StrictTypeChecking] void         copyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+    void copyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+    void copyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
 
-    [StrictTypeChecking] WebGLBuffer createBuffer();
-    [StrictTypeChecking] WebGLFramebuffer createFramebuffer();
-    [StrictTypeChecking] WebGLProgram createProgram();
-    [StrictTypeChecking] WebGLRenderbuffer createRenderbuffer();
-    [StrictTypeChecking] WebGLShader createShader(GLenum type);
-    [StrictTypeChecking] WebGLTexture createTexture();
+    WebGLBuffer createBuffer();
+    WebGLFramebuffer createFramebuffer();
+    WebGLProgram createProgram();
+    WebGLRenderbuffer createRenderbuffer();
+    WebGLShader createShader(GLenum type);
+    WebGLTexture createTexture();
 
-    [StrictTypeChecking] void         cullFace(GLenum mode);
+    void cullFace(GLenum mode);
 
-    [StrictTypeChecking] void         deleteBuffer(WebGLBuffer buffer);
-    [StrictTypeChecking] void         deleteFramebuffer(WebGLFramebuffer framebuffer);
-    [StrictTypeChecking] void         deleteProgram(WebGLProgram program);
-    [StrictTypeChecking] void         deleteRenderbuffer(WebGLRenderbuffer renderbuffer);
-    [StrictTypeChecking] void         deleteShader(WebGLShader shader);
-    [StrictTypeChecking] void         deleteTexture(WebGLTexture texture);
+    void deleteBuffer(WebGLBuffer? buffer);
+    void deleteFramebuffer(WebGLFramebuffer? framebuffer);
+    void deleteProgram(WebGLProgram? program);
+    void deleteRenderbuffer(WebGLRenderbuffer? renderbuffer);
+    void deleteShader(WebGLShader? shader);
+    void deleteTexture(WebGLTexture? texture);
 
-    [StrictTypeChecking] void         depthFunc(GLenum func);
-    [StrictTypeChecking] void         depthMask(GLboolean flag);
-    [StrictTypeChecking] void         depthRange(GLclampf zNear, GLclampf zFar);
-    [StrictTypeChecking] void         detachShader(WebGLProgram program, WebGLShader shader);
-    [StrictTypeChecking] void         disable(GLenum cap);
-    [StrictTypeChecking] void         disableVertexAttribArray(GLuint index);
-    [StrictTypeChecking] void         drawArrays(GLenum mode, GLint first, GLsizei count);
-    [StrictTypeChecking] void         drawElements(GLenum mode, GLsizei count, GLenum type, GLintptr offset);
+    void depthFunc(GLenum func);
+    void depthMask(GLboolean flag);
+    void depthRange(GLclampf zNear, GLclampf zFar);
+    void detachShader(WebGLProgram? program, WebGLShader? shader);
+    void disable(GLenum cap);
+    void disableVertexAttribArray(GLuint index);
+    void drawArrays(GLenum mode, GLint first, GLsizei count);
+    void drawElements(GLenum mode, GLsizei count, GLenum type, GLintptr offset);
 
-    [StrictTypeChecking] void         enable(GLenum cap);
-    [StrictTypeChecking] void         enableVertexAttribArray(GLuint index);
-    [StrictTypeChecking] void         finish();
-    [StrictTypeChecking] void         flush();
-    [StrictTypeChecking] void         framebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, WebGLRenderbuffer renderbuffer);
-    [StrictTypeChecking] void         framebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, WebGLTexture texture, GLint level);
-    [StrictTypeChecking] void         frontFace(GLenum mode);
-    [StrictTypeChecking] void         generateMipmap(GLenum target);
+    void enable(GLenum cap);
+    void enableVertexAttribArray(GLuint index);
+    void finish();
+    void flush();
+    void framebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, WebGLRenderbuffer? renderbuffer);
+    void framebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, WebGLTexture? texture, GLint level);
+    void frontFace(GLenum mode);
+    void generateMipmap(GLenum target);
 
-    [StrictTypeChecking] WebGLActiveInfo getActiveAttrib(WebGLProgram program, GLuint index);
-    [StrictTypeChecking] WebGLActiveInfo getActiveUniform(WebGLProgram program, GLuint index);
+    WebGLActiveInfo getActiveAttrib(WebGLProgram? program, GLuint index);
+    WebGLActiveInfo getActiveUniform(WebGLProgram? program, GLuint index);
 
-    [StrictTypeChecking, Custom] void getAttachedShaders(WebGLProgram program);
+    [Custom] void getAttachedShaders(WebGLProgram? program);
 
-    [StrictTypeChecking] GLint        getAttribLocation(WebGLProgram program, DOMString name);
+    GLint getAttribLocation(WebGLProgram? program, DOMString name);
 
-    [StrictTypeChecking, Custom] any getBufferParameter(GLenum target, GLenum pname);
+    [Custom] any getBufferParameter(GLenum target, GLenum pname);
 
-    [StrictTypeChecking] WebGLContextAttributes getContextAttributes();
+    WebGLContextAttributes getContextAttributes();
 
-    [StrictTypeChecking] GLenum getError();
+    GLenum getError();
 
     // object getExtension(DOMString name);
-    [StrictTypeChecking, Custom] any getExtension(DOMString name);
+    [Custom] any getExtension(DOMString name);
 
-    [StrictTypeChecking, Custom] any getFramebufferAttachmentParameter(GLenum target, GLenum attachment, GLenum pname);
-    [StrictTypeChecking, Custom] any getParameter(GLenum pname);
-    [StrictTypeChecking, Custom] any getProgramParameter(WebGLProgram program, GLenum pname);
-    [StrictTypeChecking, TreatReturnedNullStringAs=Null] DOMString getProgramInfoLog(WebGLProgram program);
-    [StrictTypeChecking, Custom] any getRenderbufferParameter(GLenum target, GLenum pname);
-    [StrictTypeChecking, Custom] any getShaderParameter(WebGLShader shader, GLenum pname);
+    [Custom] any getFramebufferAttachmentParameter(GLenum target, GLenum attachment, GLenum pname);
+    [Custom] any getParameter(GLenum pname);
+    [Custom] any getProgramParameter(WebGLProgram? program, GLenum pname);
+    [TreatReturnedNullStringAs=Null] DOMString getProgramInfoLog(WebGLProgram? program);
+    [Custom] any getRenderbufferParameter(GLenum target, GLenum pname);
+    [Custom] any getShaderParameter(WebGLShader? shader, GLenum pname);
 
-    [StrictTypeChecking, TreatReturnedNullStringAs=Null] DOMString    getShaderInfoLog(WebGLShader shader);
+    [TreatReturnedNullStringAs=Null] DOMString    getShaderInfoLog(WebGLShader? shader);
 
-    [StrictTypeChecking] WebGLShaderPrecisionFormat getShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype);
+    WebGLShaderPrecisionFormat getShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype);
 
-    [StrictTypeChecking, TreatReturnedNullStringAs=Null] DOMString    getShaderSource(WebGLShader shader);
+    [TreatReturnedNullStringAs=Null] DOMString    getShaderSource(WebGLShader? shader);
 
-    [StrictTypeChecking, Custom] sequence<DOMString> getSupportedExtensions();
+    [Custom] sequence<DOMString> getSupportedExtensions();
 
-    [StrictTypeChecking, Custom] any getTexParameter(GLenum target, GLenum pname);
+    [Custom] any getTexParameter(GLenum target, GLenum pname);
 
-    [StrictTypeChecking, Custom] any getUniform(WebGLProgram program, WebGLUniformLocation location);
+    [Custom] any getUniform(WebGLProgram? program, WebGLUniformLocation location);
 
-    [StrictTypeChecking] WebGLUniformLocation getUniformLocation(WebGLProgram program, DOMString name);
+    WebGLUniformLocation getUniformLocation(WebGLProgram? program, DOMString name);
 
-    [StrictTypeChecking, Custom] any getVertexAttrib(GLuint index, GLenum pname);
+    [Custom] any getVertexAttrib(GLuint index, GLenum pname);
 
-    [StrictTypeChecking] GLsizeiptr getVertexAttribOffset(GLuint index, GLenum pname);
+    GLsizeiptr getVertexAttribOffset(GLuint index, GLenum pname);
 
-    [StrictTypeChecking] void         hint(GLenum target, GLenum mode);
-    [StrictTypeChecking] GLboolean    isBuffer(WebGLBuffer buffer);
-    [StrictTypeChecking] GLboolean    isContextLost();
-    [StrictTypeChecking] GLboolean    isEnabled(GLenum cap);
-    [StrictTypeChecking] GLboolean    isFramebuffer(WebGLFramebuffer framebuffer);
-    [StrictTypeChecking] GLboolean    isProgram(WebGLProgram program);
-    [StrictTypeChecking] GLboolean    isRenderbuffer(WebGLRenderbuffer renderbuffer);
-    [StrictTypeChecking] GLboolean    isShader(WebGLShader shader);
-    [StrictTypeChecking] GLboolean    isTexture(WebGLTexture texture);
-    [StrictTypeChecking] void         lineWidth(GLfloat width);
-    [StrictTypeChecking] void         linkProgram(WebGLProgram program);
-    [StrictTypeChecking] void         pixelStorei(GLenum pname, GLint param);
-    [StrictTypeChecking] void         polygonOffset(GLfloat factor, GLfloat units);
+    void hint(GLenum target, GLenum mode);
+    GLboolean isBuffer(WebGLBuffer? buffer);
+    GLboolean isContextLost();
+    GLboolean isEnabled(GLenum cap);
+    GLboolean isFramebuffer(WebGLFramebuffer? framebuffer);
+    GLboolean isProgram(WebGLProgram? program);
+    GLboolean isRenderbuffer(WebGLRenderbuffer? renderbuffer);
+    GLboolean isShader(WebGLShader? shader);
+    GLboolean isTexture(WebGLTexture? texture);
+    void lineWidth(GLfloat width);
+    void linkProgram(WebGLProgram? program);
+    void pixelStorei(GLenum pname, GLint param);
+    void polygonOffset(GLfloat factor, GLfloat units);
 
-    [StrictTypeChecking] void         readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, ArrayBufferView pixels);
+    void readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, ArrayBufferView? pixels);
 
-    [StrictTypeChecking] void         renderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
-    [StrictTypeChecking] void         sampleCoverage(GLclampf value, GLboolean invert);
-    [StrictTypeChecking] void         scissor(GLint x, GLint y, GLsizei width, GLsizei height);
-    [StrictTypeChecking] void         shaderSource(WebGLShader shader, DOMString string);
-    [StrictTypeChecking] void         stencilFunc(GLenum func, GLint ref, GLuint mask);
-    [StrictTypeChecking] void         stencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask);
-    [StrictTypeChecking] void         stencilMask(GLuint mask);
-    [StrictTypeChecking] void         stencilMaskSeparate(GLenum face, GLuint mask);
-    [StrictTypeChecking] void         stencilOp(GLenum fail, GLenum zfail, GLenum zpass);
-    [StrictTypeChecking] void         stencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
+    void renderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+    void sampleCoverage(GLclampf value, GLboolean invert);
+    void scissor(GLint x, GLint y, GLsizei width, GLsizei height);
+    void shaderSource(WebGLShader? shader, DOMString string);
+    void stencilFunc(GLenum func, GLint ref, GLuint mask);
+    void stencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask);
+    void stencilMask(GLuint mask);
+    void stencilMaskSeparate(GLenum face, GLuint mask);
+    void stencilOp(GLenum fail, GLenum zfail, GLenum zpass);
+    void stencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
 
-    [StrictTypeChecking] void         texParameterf(GLenum target, GLenum pname, GLfloat param);
-    [StrictTypeChecking] void         texParameteri(GLenum target, GLenum pname, GLint param);
+    void texParameterf(GLenum target, GLenum pname, GLfloat param);
+    void texParameteri(GLenum target, GLenum pname, GLint param);
 
     // Supported forms:
-    [StrictTypeChecking, RaisesException] void         texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height,
-                                                 GLint border, GLenum format, GLenum type, ArrayBufferView? pixels);
-    [StrictTypeChecking, RaisesException] void         texImage2D(GLenum target, GLint level, GLenum internalformat,
-                                                 GLenum format, GLenum type, ImageData? pixels);
-    [StrictTypeChecking, RaisesException] void         texImage2D(GLenum target, GLint level, GLenum internalformat,
-                                                 GLenum format, GLenum type, HTMLImageElement? image);
-    [StrictTypeChecking, RaisesException] void         texImage2D(GLenum target, GLint level, GLenum internalformat,
-                                                 GLenum format, GLenum type, HTMLCanvasElement? canvas);
-    [StrictTypeChecking, RaisesException] void         texImage2D(GLenum target, GLint level, GLenum internalformat,
-                                                 GLenum format, GLenum type, HTMLVideoElement? video);
+    [RaisesException] void texImage2D(
+        GLenum target, GLint level, GLenum internalformat,
+        GLsizei width, GLsizei height, GLint border,
+        GLenum format, GLenum type, ArrayBufferView? pixels);
+    [RaisesException] void texImage2D(
+        GLenum target, GLint level, GLenum internalformat,
+        GLenum format, GLenum type, ImageData? pixels);
+    [RaisesException] void texImage2D(
+        GLenum target, GLint level, GLenum internalformat,
+        GLenum format, GLenum type, HTMLImageElement? image);
+    [RaisesException] void texImage2D(
+        GLenum target, GLint level, GLenum internalformat,
+        GLenum format, GLenum type, HTMLCanvasElement? canvas);
+    [RaisesException] void texImage2D(
+        GLenum target, GLint level, GLenum internalformat,
+        GLenum format, GLenum type, HTMLVideoElement? video);
 
-    [StrictTypeChecking, RaisesException] void         texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
-                                                    GLsizei width, GLsizei height,
-                                                    GLenum format, GLenum type, ArrayBufferView? pixels);
-    [StrictTypeChecking, RaisesException] void         texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
-                                                    GLenum format, GLenum type, ImageData? pixels);
-    [StrictTypeChecking, RaisesException] void         texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
-                                                    GLenum format, GLenum type, HTMLImageElement? image);
-    [StrictTypeChecking, RaisesException] void         texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
-                                                    GLenum format, GLenum type, HTMLCanvasElement? canvas);
-    [StrictTypeChecking, RaisesException] void         texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
-                                                    GLenum format, GLenum type, HTMLVideoElement? video);
+    [RaisesException] void texSubImage2D(
+        GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLsizei width, GLsizei height,
+        GLenum format, GLenum type, ArrayBufferView? pixels);
+    [RaisesException] void texSubImage2D(
+        GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLenum format, GLenum type, ImageData? pixels);
+    [RaisesException] void texSubImage2D(
+        GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLenum format, GLenum type, HTMLImageElement? image);
+    [RaisesException] void texSubImage2D(
+        GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLenum format, GLenum type, HTMLCanvasElement? canvas);
+    [RaisesException] void texSubImage2D(
+        GLenum target, GLint level, GLint xoffset, GLint yoffset,
+        GLenum format, GLenum type, HTMLVideoElement? video);
 
-    [StrictTypeChecking] void uniform1f(WebGLUniformLocation location, GLfloat x);
-    [StrictTypeChecking, Custom] void uniform1fv(WebGLUniformLocation location, Float32Array v);
-    [StrictTypeChecking] void uniform1i(WebGLUniformLocation location, GLint x);
-    [StrictTypeChecking, Custom] void uniform1iv(WebGLUniformLocation location, Int32Array v);
-    [StrictTypeChecking] void uniform2f(WebGLUniformLocation location, GLfloat x, GLfloat y);
-    [StrictTypeChecking, Custom] void uniform2fv(WebGLUniformLocation location, Float32Array v);
-    [StrictTypeChecking] void uniform2i(WebGLUniformLocation location, GLint x, GLint y);
-    [StrictTypeChecking, Custom] void uniform2iv(WebGLUniformLocation location, Int32Array v);
-    [StrictTypeChecking] void uniform3f(WebGLUniformLocation location, GLfloat x, GLfloat y, GLfloat z);
-    [StrictTypeChecking, Custom] void uniform3fv(WebGLUniformLocation location, Float32Array v);
-    [StrictTypeChecking] void uniform3i(WebGLUniformLocation location, GLint x, GLint y, GLint z);
-    [StrictTypeChecking, Custom] void uniform3iv(WebGLUniformLocation location, Int32Array v);
-    [StrictTypeChecking] void uniform4f(WebGLUniformLocation location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-    [StrictTypeChecking, Custom] void uniform4fv(WebGLUniformLocation location, Float32Array v);
-    [StrictTypeChecking] void uniform4i(WebGLUniformLocation location, GLint x, GLint y, GLint z, GLint w);
-    [StrictTypeChecking, Custom] void uniform4iv(WebGLUniformLocation location, Int32Array v);
+    void uniform1f(WebGLUniformLocation? location, GLfloat x);
+    [Custom] void uniform1fv(WebGLUniformLocation? location, Float32Array v);
+    void uniform1i(WebGLUniformLocation? location, GLint x);
+    [Custom] void uniform1iv(WebGLUniformLocation? location, Int32Array v);
+    void uniform2f(WebGLUniformLocation? location, GLfloat x, GLfloat y);
+    [Custom] void uniform2fv(WebGLUniformLocation? location, Float32Array v);
+    void uniform2i(WebGLUniformLocation? location, GLint x, GLint y);
+    [Custom] void uniform2iv(WebGLUniformLocation? location, Int32Array v);
+    void uniform3f(WebGLUniformLocation? location, GLfloat x, GLfloat y, GLfloat z);
+    [Custom] void uniform3fv(WebGLUniformLocation? location, Float32Array v);
+    void uniform3i(WebGLUniformLocation? location, GLint x, GLint y, GLint z);
+    [Custom] void uniform3iv(WebGLUniformLocation? location, Int32Array v);
+    void uniform4f(WebGLUniformLocation? location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+    [Custom] void uniform4fv(WebGLUniformLocation? location, Float32Array v);
+    void uniform4i(WebGLUniformLocation? location, GLint x, GLint y, GLint z, GLint w);
+    [Custom] void uniform4iv(WebGLUniformLocation? location, Int32Array v);
 
-    [StrictTypeChecking, Custom] void uniformMatrix2fv(WebGLUniformLocation location, GLboolean transpose, Float32Array array);
-    [StrictTypeChecking, Custom] void uniformMatrix3fv(WebGLUniformLocation location, GLboolean transpose, Float32Array array);
-    [StrictTypeChecking, Custom] void uniformMatrix4fv(WebGLUniformLocation location, GLboolean transpose, Float32Array array);
+    [Custom] void uniformMatrix2fv(WebGLUniformLocation? location, GLboolean transpose, Float32Array array);
+    [Custom] void uniformMatrix3fv(WebGLUniformLocation? location, GLboolean transpose, Float32Array array);
+    [Custom] void uniformMatrix4fv(WebGLUniformLocation? location, GLboolean transpose, Float32Array array);
 
-    [StrictTypeChecking] void         useProgram(WebGLProgram program);
-    [StrictTypeChecking] void         validateProgram(WebGLProgram program);
+    void useProgram(WebGLProgram? program);
+    void validateProgram(WebGLProgram? program);
 
-    [StrictTypeChecking] void         vertexAttrib1f(GLuint indx, GLfloat x);
-    [StrictTypeChecking, Custom] void vertexAttrib1fv(GLuint indx, Float32Array values);
-    [StrictTypeChecking] void         vertexAttrib2f(GLuint indx, GLfloat x, GLfloat y);
-    [StrictTypeChecking, Custom] void vertexAttrib2fv(GLuint indx, Float32Array values);
-    [StrictTypeChecking] void         vertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z);
-    [StrictTypeChecking, Custom] void vertexAttrib3fv(GLuint indx, Float32Array values);
-    [StrictTypeChecking] void         vertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-    [StrictTypeChecking, Custom] void vertexAttrib4fv(GLuint indx, Float32Array values);
-    [StrictTypeChecking] void         vertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized,
-                                                          GLsizei stride, GLintptr offset);
+    void vertexAttrib1f(GLuint indx, GLfloat x);
+    [Custom] void vertexAttrib1fv(GLuint indx, Float32Array values);
+    void vertexAttrib2f(GLuint indx, GLfloat x, GLfloat y);
+    [Custom] void vertexAttrib2fv(GLuint indx, Float32Array values);
+    void vertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z);
+    [Custom] void vertexAttrib3fv(GLuint indx, Float32Array values);
+    void vertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+    [Custom] void vertexAttrib4fv(GLuint indx, Float32Array values);
+    void vertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized,
+                             GLsizei stride, GLintptr offset);
 
-    [StrictTypeChecking] void         viewport(GLint x, GLint y, GLsizei width, GLsizei height);
+    void viewport(GLint x, GLint y, GLsizei width, GLsizei height);
 };
diff --git a/Source/core/html/canvas/WebGLShader.cpp b/Source/core/html/canvas/WebGLShader.cpp
index 0920fc9..009347d 100644
--- a/Source/core/html/canvas/WebGLShader.cpp
+++ b/Source/core/html/canvas/WebGLShader.cpp
@@ -31,18 +31,18 @@
 
 namespace WebCore {
 
-PassRefPtr<WebGLShader> WebGLShader::create(WebGLRenderingContext* ctx, GC3Denum type)
+PassRefPtr<WebGLShader> WebGLShader::create(WebGLRenderingContext* ctx, GLenum type)
 {
     return adoptRef(new WebGLShader(ctx, type));
 }
 
-WebGLShader::WebGLShader(WebGLRenderingContext* ctx, GC3Denum type)
+WebGLShader::WebGLShader(WebGLRenderingContext* ctx, GLenum type)
     : WebGLSharedObject(ctx)
     , m_type(type)
     , m_source("")
 {
     ScriptWrappable::init(this);
-    setObject(ctx->graphicsContext3D()->createShader(type));
+    setObject(ctx->webGraphicsContext3D()->createShader(type));
 }
 
 WebGLShader::~WebGLShader()
@@ -50,7 +50,7 @@
     deleteObject(0);
 }
 
-void WebGLShader::deleteObjectImpl(GraphicsContext3D* context3d, Platform3DObject object)
+void WebGLShader::deleteObjectImpl(blink::WebGraphicsContext3D* context3d, Platform3DObject object)
 {
     context3d->deleteShader(object);
 }
diff --git a/Source/core/html/canvas/WebGLShader.h b/Source/core/html/canvas/WebGLShader.h
index 6c776af..940231f 100644
--- a/Source/core/html/canvas/WebGLShader.h
+++ b/Source/core/html/canvas/WebGLShader.h
@@ -29,28 +29,29 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLSharedObject.h"
 #include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-class WebGLShader : public WebGLSharedObject, public ScriptWrappable {
+class WebGLShader FINAL : public WebGLSharedObject, public ScriptWrappable {
 public:
     virtual ~WebGLShader();
 
-    static PassRefPtr<WebGLShader> create(WebGLRenderingContext*, GC3Denum);
+    static PassRefPtr<WebGLShader> create(WebGLRenderingContext*, GLenum);
 
-    GC3Denum type() const { return m_type; }
+    GLenum type() const { return m_type; }
     const String& source() const { return m_source; }
 
     void setSource(const String& source) { m_source = source; }
 
 private:
-    WebGLShader(WebGLRenderingContext*, GC3Denum);
+    WebGLShader(WebGLRenderingContext*, GLenum);
 
-    virtual void deleteObjectImpl(GraphicsContext3D*, Platform3DObject);
+    virtual void deleteObjectImpl(blink::WebGraphicsContext3D*, Platform3DObject) OVERRIDE;
 
-    virtual bool isShader() const { return true; }
+    virtual bool isShader() const OVERRIDE { return true; }
 
-    GC3Denum m_type;
+    GLenum m_type;
     String m_source;
 };
 
diff --git a/Source/core/html/canvas/WebGLShaderPrecisionFormat.cpp b/Source/core/html/canvas/WebGLShaderPrecisionFormat.cpp
index 288468f..8fb4bb1 100644
--- a/Source/core/html/canvas/WebGLShaderPrecisionFormat.cpp
+++ b/Source/core/html/canvas/WebGLShaderPrecisionFormat.cpp
@@ -31,27 +31,27 @@
 namespace WebCore {
 
 // static
-PassRefPtr<WebGLShaderPrecisionFormat> WebGLShaderPrecisionFormat::create(GC3Dint rangeMin, GC3Dint rangeMax, GC3Dint precision)
+PassRefPtr<WebGLShaderPrecisionFormat> WebGLShaderPrecisionFormat::create(GLint rangeMin, GLint rangeMax, GLint precision)
 {
     return adoptRef(new WebGLShaderPrecisionFormat(rangeMin, rangeMax, precision));
 }
 
-GC3Dint WebGLShaderPrecisionFormat::rangeMin() const
+GLint WebGLShaderPrecisionFormat::rangeMin() const
 {
     return m_rangeMin;
 }
 
-GC3Dint WebGLShaderPrecisionFormat::rangeMax() const
+GLint WebGLShaderPrecisionFormat::rangeMax() const
 {
     return m_rangeMax;
 }
 
-GC3Dint WebGLShaderPrecisionFormat::precision() const
+GLint WebGLShaderPrecisionFormat::precision() const
 {
     return m_precision;
 }
 
-WebGLShaderPrecisionFormat::WebGLShaderPrecisionFormat(GC3Dint rangeMin, GC3Dint rangeMax, GC3Dint precision)
+WebGLShaderPrecisionFormat::WebGLShaderPrecisionFormat(GLint rangeMin, GLint rangeMax, GLint precision)
     : m_rangeMin(rangeMin)
     , m_rangeMax(rangeMax)
     , m_precision(precision)
diff --git a/Source/core/html/canvas/WebGLShaderPrecisionFormat.h b/Source/core/html/canvas/WebGLShaderPrecisionFormat.h
index b59acc0..bd363bb 100644
--- a/Source/core/html/canvas/WebGLShaderPrecisionFormat.h
+++ b/Source/core/html/canvas/WebGLShaderPrecisionFormat.h
@@ -28,7 +28,7 @@
 #define WebGLShaderPrecisionFormat_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "platform/graphics/GraphicsContext3D.h"
+#include "platform/graphics/GraphicsTypes3D.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 
@@ -36,18 +36,18 @@
 
 class WebGLShaderPrecisionFormat : public RefCounted<WebGLShaderPrecisionFormat>, public ScriptWrappable {
 public:
-    static PassRefPtr<WebGLShaderPrecisionFormat> create(GC3Dint rangeMin, GC3Dint rangeMax, GC3Dint precision);
+    static PassRefPtr<WebGLShaderPrecisionFormat> create(GLint rangeMin, GLint rangeMax, GLint precision);
 
-    GC3Dint rangeMin() const;
-    GC3Dint rangeMax() const;
-    GC3Dint precision() const;
+    GLint rangeMin() const;
+    GLint rangeMax() const;
+    GLint precision() const;
 
 private:
-    WebGLShaderPrecisionFormat(GC3Dint rangeMin, GC3Dint rangeMax, GC3Dint precision);
+    WebGLShaderPrecisionFormat(GLint rangeMin, GLint rangeMax, GLint precision);
 
-    GC3Dint m_rangeMin;
-    GC3Dint m_rangeMax;
-    GC3Dint m_precision;
+    GLint m_rangeMin;
+    GLint m_rangeMax;
+    GLint m_precision;
 };
 
 }
diff --git a/Source/core/html/canvas/WebGLSharedObject.cpp b/Source/core/html/canvas/WebGLSharedObject.cpp
index f5d6365..42cc599 100644
--- a/Source/core/html/canvas/WebGLSharedObject.cpp
+++ b/Source/core/html/canvas/WebGLSharedObject.cpp
@@ -54,9 +54,9 @@
     }
 }
 
-GraphicsContext3D* WebGLSharedObject::getAGraphicsContext3D() const
+blink::WebGraphicsContext3D* WebGLSharedObject::getAWebGraphicsContext3D() const
 {
-    return m_contextGroup ? m_contextGroup->getAGraphicsContext3D() : 0;
+    return m_contextGroup ? m_contextGroup->getAWebGraphicsContext3D() : 0;
 }
 
 }
diff --git a/Source/core/html/canvas/WebGLSharedObject.h b/Source/core/html/canvas/WebGLSharedObject.h
index 6c33471..025b960 100644
--- a/Source/core/html/canvas/WebGLSharedObject.h
+++ b/Source/core/html/canvas/WebGLSharedObject.h
@@ -30,7 +30,6 @@
 
 namespace WebCore {
 
-class GraphicsContext3D;
 class WebGLContextGroup;
 class WebGLRenderingContext;
 
@@ -43,13 +42,12 @@
     WebGLContextGroup* contextGroup() const { return m_contextGroup; }
 
     virtual bool isBuffer() const { return false; }
-    virtual bool isFramebuffer() const { return false; }
     virtual bool isProgram() const { return false; }
     virtual bool isRenderbuffer() const { return false; }
     virtual bool isShader() const { return false; }
     virtual bool isTexture() const { return false; }
 
-    virtual bool validate(const WebGLContextGroup* contextGroup, const WebGLRenderingContext*) const
+    virtual bool validate(const WebGLContextGroup* contextGroup, const WebGLRenderingContext*) const OVERRIDE FINAL
     {
         return contextGroup == m_contextGroup;
     }
@@ -59,12 +57,12 @@
 protected:
     WebGLSharedObject(WebGLRenderingContext*);
 
-    virtual bool hasGroupOrContext() const
+    virtual bool hasGroupOrContext() const OVERRIDE FINAL
     {
         return m_contextGroup;
     }
 
-    virtual GraphicsContext3D* getAGraphicsContext3D() const;
+    virtual blink::WebGraphicsContext3D* getAWebGraphicsContext3D() const OVERRIDE FINAL;
 
 private:
     WebGLContextGroup* m_contextGroup;
diff --git a/Source/core/html/canvas/WebGLTexture.cpp b/Source/core/html/canvas/WebGLTexture.cpp
index d01bf83..c9b3d6c 100644
--- a/Source/core/html/canvas/WebGLTexture.cpp
+++ b/Source/core/html/canvas/WebGLTexture.cpp
@@ -39,10 +39,10 @@
 WebGLTexture::WebGLTexture(WebGLRenderingContext* ctx)
     : WebGLSharedObject(ctx)
     , m_target(0)
-    , m_minFilter(GraphicsContext3D::NEAREST_MIPMAP_LINEAR)
-    , m_magFilter(GraphicsContext3D::LINEAR)
-    , m_wrapS(GraphicsContext3D::REPEAT)
-    , m_wrapT(GraphicsContext3D::REPEAT)
+    , m_minFilter(GL_NEAREST_MIPMAP_LINEAR)
+    , m_magFilter(GL_LINEAR)
+    , m_wrapS(GL_REPEAT)
+    , m_wrapT(GL_REPEAT)
     , m_isNPOT(false)
     , m_isCubeComplete(false)
     , m_isComplete(false)
@@ -51,7 +51,7 @@
     , m_isHalfFloatType(false)
 {
     ScriptWrappable::init(this);
-    setObject(ctx->graphicsContext3D()->createTexture());
+    setObject(ctx->webGraphicsContext3D()->createTexture());
 }
 
 WebGLTexture::~WebGLTexture()
@@ -59,7 +59,7 @@
     deleteObject(0);
 }
 
-void WebGLTexture::setTarget(GC3Denum target, GC3Dint maxLevel)
+void WebGLTexture::setTarget(GLenum target, GLint maxLevel)
 {
     if (!object())
         return;
@@ -67,12 +67,12 @@
     if (m_target)
         return;
     switch (target) {
-    case GraphicsContext3D::TEXTURE_2D:
+    case GL_TEXTURE_2D:
         m_target = target;
         m_info.resize(1);
         m_info[0].resize(maxLevel);
         break;
-    case GraphicsContext3D::TEXTURE_CUBE_MAP:
+    case GL_TEXTURE_CUBE_MAP:
         m_target = target;
         m_info.resize(6);
         for (int ii = 0; ii < 6; ++ii)
@@ -81,45 +81,45 @@
     }
 }
 
-void WebGLTexture::setParameteri(GC3Denum pname, GC3Dint param)
+void WebGLTexture::setParameteri(GLenum pname, GLint param)
 {
     if (!object() || !m_target)
         return;
     switch (pname) {
-    case GraphicsContext3D::TEXTURE_MIN_FILTER:
+    case GL_TEXTURE_MIN_FILTER:
         switch (param) {
-        case GraphicsContext3D::NEAREST:
-        case GraphicsContext3D::LINEAR:
-        case GraphicsContext3D::NEAREST_MIPMAP_NEAREST:
-        case GraphicsContext3D::LINEAR_MIPMAP_NEAREST:
-        case GraphicsContext3D::NEAREST_MIPMAP_LINEAR:
-        case GraphicsContext3D::LINEAR_MIPMAP_LINEAR:
+        case GL_NEAREST:
+        case GL_LINEAR:
+        case GL_NEAREST_MIPMAP_NEAREST:
+        case GL_LINEAR_MIPMAP_NEAREST:
+        case GL_NEAREST_MIPMAP_LINEAR:
+        case GL_LINEAR_MIPMAP_LINEAR:
             m_minFilter = param;
             break;
         }
         break;
-    case GraphicsContext3D::TEXTURE_MAG_FILTER:
+    case GL_TEXTURE_MAG_FILTER:
         switch (param) {
-        case GraphicsContext3D::NEAREST:
-        case GraphicsContext3D::LINEAR:
+        case GL_NEAREST:
+        case GL_LINEAR:
             m_magFilter = param;
             break;
         }
         break;
-    case GraphicsContext3D::TEXTURE_WRAP_S:
+    case GL_TEXTURE_WRAP_S:
         switch (param) {
-        case GraphicsContext3D::CLAMP_TO_EDGE:
-        case GraphicsContext3D::MIRRORED_REPEAT:
-        case GraphicsContext3D::REPEAT:
+        case GL_CLAMP_TO_EDGE:
+        case GL_MIRRORED_REPEAT:
+        case GL_REPEAT:
             m_wrapS = param;
             break;
         }
         break;
-    case GraphicsContext3D::TEXTURE_WRAP_T:
+    case GL_TEXTURE_WRAP_T:
         switch (param) {
-        case GraphicsContext3D::CLAMP_TO_EDGE:
-        case GraphicsContext3D::MIRRORED_REPEAT:
-        case GraphicsContext3D::REPEAT:
+        case GL_CLAMP_TO_EDGE:
+        case GL_MIRRORED_REPEAT:
+        case GL_REPEAT:
             m_wrapT = param;
             break;
         }
@@ -130,15 +130,15 @@
     update();
 }
 
-void WebGLTexture::setParameterf(GC3Denum pname, GC3Dfloat param)
+void WebGLTexture::setParameterf(GLenum pname, GLfloat param)
 {
     if (!object() || !m_target)
         return;
-    GC3Dint iparam = static_cast<GC3Dint>(param);
+    GLint iparam = static_cast<GLint>(param);
     setParameteri(pname, iparam);
 }
 
-void WebGLTexture::setLevelInfo(GC3Denum target, GC3Dint level, GC3Denum internalFormat, GC3Dsizei width, GC3Dsizei height, GC3Denum type)
+void WebGLTexture::setLevelInfo(GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLenum type)
 {
     if (!object() || !m_target)
         return;
@@ -160,10 +160,10 @@
     if (!m_isComplete) {
         for (size_t ii = 0; ii < m_info.size(); ++ii) {
             const LevelInfo& info0 = m_info[ii][0];
-            GC3Dsizei width = info0.width;
-            GC3Dsizei height = info0.height;
-            GC3Dint levelCount = computeLevelCount(width, height);
-            for (GC3Dint level = 1; level < levelCount; ++level) {
+            GLsizei width = info0.width;
+            GLsizei height = info0.height;
+            GLint levelCount = computeLevelCount(width, height);
+            for (GLint level = 1; level < levelCount; ++level) {
                 width = std::max(1, width >> 1);
                 height = std::max(1, height >> 1);
                 LevelInfo& info = m_info[ii][level];
@@ -175,7 +175,7 @@
     m_needToUseBlackTexture = false;
 }
 
-GC3Denum WebGLTexture::getInternalFormat(GC3Denum target, GC3Dint level) const
+GLenum WebGLTexture::getInternalFormat(GLenum target, GLint level) const
 {
     const LevelInfo* info = getLevelInfo(target, level);
     if (!info)
@@ -183,7 +183,7 @@
     return info->internalFormat;
 }
 
-GC3Denum WebGLTexture::getType(GC3Denum target, GC3Dint level) const
+GLenum WebGLTexture::getType(GLenum target, GLint level) const
 {
     const LevelInfo* info = getLevelInfo(target, level);
     if (!info)
@@ -191,7 +191,7 @@
     return info->type;
 }
 
-GC3Dsizei WebGLTexture::getWidth(GC3Denum target, GC3Dint level) const
+GLsizei WebGLTexture::getWidth(GLenum target, GLint level) const
 {
     const LevelInfo* info = getLevelInfo(target, level);
     if (!info)
@@ -199,7 +199,7 @@
     return info->width;
 }
 
-GC3Dsizei WebGLTexture::getHeight(GC3Denum target, GC3Dint level) const
+GLsizei WebGLTexture::getHeight(GLenum target, GLint level) const
 {
     const LevelInfo* info = getLevelInfo(target, level);
     if (!info)
@@ -207,7 +207,7 @@
     return info->height;
 }
 
-bool WebGLTexture::isValid(GC3Denum target, GC3Dint level) const
+bool WebGLTexture::isValid(GLenum target, GLint level) const
 {
     const LevelInfo* info = getLevelInfo(target, level);
     if (!info)
@@ -215,7 +215,7 @@
     return info->valid;
 }
 
-bool WebGLTexture::isNPOT(GC3Dsizei width, GC3Dsizei height)
+bool WebGLTexture::isNPOT(GLsizei width, GLsizei height)
 {
     ASSERT(width >= 0 && height >= 0);
     if (!width || !height)
@@ -239,35 +239,35 @@
     if (m_needToUseBlackTexture)
         return true;
     if ((m_isFloatType && !(flag & TextureFloatLinearExtensionEnabled)) || (m_isHalfFloatType && !(flag && TextureHalfFloatLinearExtensionEnabled))) {
-        if (m_magFilter != GraphicsContext3D::NEAREST || (m_minFilter != GraphicsContext3D::NEAREST && m_minFilter != GraphicsContext3D::NEAREST_MIPMAP_NEAREST))
+        if (m_magFilter != GL_NEAREST || (m_minFilter != GL_NEAREST && m_minFilter != GL_NEAREST_MIPMAP_NEAREST))
             return true;
     }
     return false;
 }
 
-void WebGLTexture::deleteObjectImpl(GraphicsContext3D* context3d, Platform3DObject object)
+void WebGLTexture::deleteObjectImpl(blink::WebGraphicsContext3D* context3d, Platform3DObject object)
 {
     context3d->deleteTexture(object);
 }
 
-int WebGLTexture::mapTargetToIndex(GC3Denum target) const
+int WebGLTexture::mapTargetToIndex(GLenum target) const
 {
-    if (m_target == GraphicsContext3D::TEXTURE_2D) {
-        if (target == GraphicsContext3D::TEXTURE_2D)
+    if (m_target == GL_TEXTURE_2D) {
+        if (target == GL_TEXTURE_2D)
             return 0;
-    } else if (m_target == GraphicsContext3D::TEXTURE_CUBE_MAP) {
+    } else if (m_target == GL_TEXTURE_CUBE_MAP) {
         switch (target) {
-        case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X:
+        case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
             return 0;
-        case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X:
+        case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
             return 1;
-        case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y:
+        case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
             return 2;
-        case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y:
+        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
             return 3;
-        case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z:
+        case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
             return 4;
-        case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z:
+        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
             return 5;
         }
     }
@@ -290,17 +290,17 @@
     return true;
 }
 
-GC3Dint WebGLTexture::computeLevelCount(GC3Dsizei width, GC3Dsizei height)
+GLint WebGLTexture::computeLevelCount(GLsizei width, GLsizei height)
 {
     // return 1 + log2Floor(std::max(width, height));
-    GC3Dsizei n = std::max(width, height);
+    GLsizei n = std::max(width, height);
     if (n <= 0)
         return 0;
-    GC3Dint log = 0;
-    GC3Dsizei value = n;
+    GLint log = 0;
+    GLsizei value = n;
     for (int ii = 4; ii >= 0; --ii) {
         int shift = (1 << ii);
-        GC3Dsizei x = (value >> shift);
+        GLsizei x = (value >> shift);
         if (x) {
             value = x;
             log += shift;
@@ -322,7 +322,7 @@
     m_isComplete = true;
     m_isCubeComplete = true;
     const LevelInfo& first = m_info[0][0];
-    GC3Dint levelCount = computeLevelCount(first.width, first.height);
+    GLint levelCount = computeLevelCount(first.width, first.height);
     if (levelCount < 1)
         m_isComplete = false;
     else {
@@ -337,9 +337,9 @@
                 m_isComplete = false;
                 break;
             }
-            GC3Dsizei width = info0.width;
-            GC3Dsizei height = info0.height;
-            for (GC3Dint level = 1; level < levelCount; ++level) {
+            GLsizei width = info0.width;
+            GLsizei height = info0.height;
+            for (GLint level = 1; level < levelCount; ++level) {
                 width = std::max(1, width >> 1);
                 height = std::max(1, height >> 1);
                 const LevelInfo& info = m_info[ii][level];
@@ -353,30 +353,30 @@
             }
         }
     }
-    m_isFloatType = m_info[0][0].type == GraphicsContext3D::FLOAT;
-    m_isHalfFloatType = m_info[0][0].type == GraphicsContext3D::HALF_FLOAT_OES;
+    m_isFloatType = m_info[0][0].type == GL_FLOAT;
+    m_isHalfFloatType = m_info[0][0].type == GL_HALF_FLOAT_OES;
 
     m_needToUseBlackTexture = false;
     // NPOT
-    if (m_isNPOT && ((m_minFilter != GraphicsContext3D::NEAREST && m_minFilter != GraphicsContext3D::LINEAR)
-                     || m_wrapS != GraphicsContext3D::CLAMP_TO_EDGE || m_wrapT != GraphicsContext3D::CLAMP_TO_EDGE))
+    if (m_isNPOT && ((m_minFilter != GL_NEAREST && m_minFilter != GL_LINEAR)
+        || m_wrapS != GL_CLAMP_TO_EDGE || m_wrapT != GL_CLAMP_TO_EDGE))
         m_needToUseBlackTexture = true;
     // If it is a Cube texture, check Cube Completeness first
     if (m_info.size() > 1 && !m_isCubeComplete)
         m_needToUseBlackTexture = true;
     // Completeness
-    if (!m_isComplete && m_minFilter != GraphicsContext3D::NEAREST && m_minFilter != GraphicsContext3D::LINEAR)
+    if (!m_isComplete && m_minFilter != GL_NEAREST && m_minFilter != GL_LINEAR)
         m_needToUseBlackTexture = true;
 }
 
-const WebGLTexture::LevelInfo* WebGLTexture::getLevelInfo(GC3Denum target, GC3Dint level) const
+const WebGLTexture::LevelInfo* WebGLTexture::getLevelInfo(GLenum target, GLint level) const
 {
     if (!object() || !m_target)
         return 0;
     int targetIndex = mapTargetToIndex(target);
     if (targetIndex < 0 || targetIndex >= static_cast<int>(m_info.size()))
         return 0;
-    if (level < 0 || level >= static_cast<GC3Dint>(m_info[targetIndex].size()))
+    if (level < 0 || level >= static_cast<GLint>(m_info[targetIndex].size()))
         return 0;
     return &(m_info[targetIndex][level]);
 }
diff --git a/Source/core/html/canvas/WebGLTexture.h b/Source/core/html/canvas/WebGLTexture.h
index 67f1fdc..a23ab4c 100644
--- a/Source/core/html/canvas/WebGLTexture.h
+++ b/Source/core/html/canvas/WebGLTexture.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class WebGLTexture : public WebGLSharedObject, public ScriptWrappable {
+class WebGLTexture FINAL : public WebGLSharedObject, public ScriptWrappable {
 public:
     enum TextureExtensionFlag {
         NoTextureExtensionEnabled = 0,
@@ -44,28 +44,28 @@
 
     static PassRefPtr<WebGLTexture> create(WebGLRenderingContext*);
 
-    void setTarget(GC3Denum target, GC3Dint maxLevel);
-    void setParameteri(GC3Denum pname, GC3Dint param);
-    void setParameterf(GC3Denum pname, GC3Dfloat param);
+    void setTarget(GLenum target, GLint maxLevel);
+    void setParameteri(GLenum pname, GLint param);
+    void setParameterf(GLenum pname, GLfloat param);
 
-    GC3Denum getTarget() const { return m_target; }
+    GLenum getTarget() const { return m_target; }
 
     int getMinFilter() const { return m_minFilter; }
 
-    void setLevelInfo(GC3Denum target, GC3Dint level, GC3Denum internalFormat, GC3Dsizei width, GC3Dsizei height, GC3Denum type);
+    void setLevelInfo(GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLenum type);
 
     bool canGenerateMipmaps();
     // Generate all level information.
     void generateMipmapLevelInfo();
 
-    GC3Denum getInternalFormat(GC3Denum target, GC3Dint level) const;
-    GC3Denum getType(GC3Denum target, GC3Dint level) const;
-    GC3Dsizei getWidth(GC3Denum target, GC3Dint level) const;
-    GC3Dsizei getHeight(GC3Denum target, GC3Dint level) const;
-    bool isValid(GC3Denum target, GC3Dint level) const;
+    GLenum getInternalFormat(GLenum target, GLint level) const;
+    GLenum getType(GLenum target, GLint level) const;
+    GLsizei getWidth(GLenum target, GLint level) const;
+    GLsizei getHeight(GLenum target, GLint level) const;
+    bool isValid(GLenum target, GLint level) const;
 
     // Whether width/height is NotPowerOfTwo.
-    static bool isNPOT(GC3Dsizei, GC3Dsizei);
+    static bool isNPOT(GLsizei, GLsizei);
 
     bool isNPOT() const;
     // Determine if texture sampling should always return [0, 0, 0, 1] (OpenGL ES 2.0 Sec 3.8.2).
@@ -73,12 +73,12 @@
 
     bool hasEverBeenBound() const { return object() && m_target; }
 
-    static GC3Dint computeLevelCount(GC3Dsizei width, GC3Dsizei height);
+    static GLint computeLevelCount(GLsizei width, GLsizei height);
 
 protected:
     WebGLTexture(WebGLRenderingContext*);
 
-    virtual void deleteObjectImpl(GraphicsContext3D*, Platform3DObject);
+    virtual void deleteObjectImpl(blink::WebGraphicsContext3D*, Platform3DObject) OVERRIDE;
 
 private:
     class LevelInfo {
@@ -92,7 +92,7 @@
         {
         }
 
-        void setInfo(GC3Denum internalFmt, GC3Dsizei w, GC3Dsizei h, GC3Denum tp)
+        void setInfo(GLenum internalFmt, GLsizei w, GLsizei h, GLenum tp)
         {
             valid = true;
             internalFormat = internalFmt;
@@ -102,26 +102,26 @@
         }
 
         bool valid;
-        GC3Denum internalFormat;
-        GC3Dsizei width;
-        GC3Dsizei height;
-        GC3Denum type;
+        GLenum internalFormat;
+        GLsizei width;
+        GLsizei height;
+        GLenum type;
     };
 
-    virtual bool isTexture() const { return true; }
+    virtual bool isTexture() const OVERRIDE { return true; }
 
     void update();
 
-    int mapTargetToIndex(GC3Denum) const;
+    int mapTargetToIndex(GLenum) const;
 
-    const LevelInfo* getLevelInfo(GC3Denum target, GC3Dint level) const;
+    const LevelInfo* getLevelInfo(GLenum target, GLint level) const;
 
-    GC3Denum m_target;
+    GLenum m_target;
 
-    GC3Denum m_minFilter;
-    GC3Denum m_magFilter;
-    GC3Denum m_wrapS;
-    GC3Denum m_wrapT;
+    GLenum m_minFilter;
+    GLenum m_magFilter;
+    GLenum m_wrapS;
+    GLenum m_wrapT;
 
     Vector<Vector<LevelInfo> > m_info;
 
diff --git a/Source/core/html/canvas/WebGLUniformLocation.cpp b/Source/core/html/canvas/WebGLUniformLocation.cpp
index 2790c7e..cd1eb95 100644
--- a/Source/core/html/canvas/WebGLUniformLocation.cpp
+++ b/Source/core/html/canvas/WebGLUniformLocation.cpp
@@ -30,12 +30,12 @@
 
 namespace WebCore {
 
-PassRefPtr<WebGLUniformLocation> WebGLUniformLocation::create(WebGLProgram* program, GC3Dint location)
+PassRefPtr<WebGLUniformLocation> WebGLUniformLocation::create(WebGLProgram* program, GLint location)
 {
     return adoptRef(new WebGLUniformLocation(program, location));
 }
 
-WebGLUniformLocation::WebGLUniformLocation(WebGLProgram* program, GC3Dint location)
+WebGLUniformLocation::WebGLUniformLocation(WebGLProgram* program, GLint location)
     : m_program(program)
     , m_location(location)
 {
@@ -53,7 +53,7 @@
     return m_program.get();
 }
 
-GC3Dint WebGLUniformLocation::location() const
+GLint WebGLUniformLocation::location() const
 {
     // If the program has been linked again, then this UniformLocation is no
     // longer valid.
diff --git a/Source/core/html/canvas/WebGLUniformLocation.h b/Source/core/html/canvas/WebGLUniformLocation.h
index 34e0480..76e98b3 100644
--- a/Source/core/html/canvas/WebGLUniformLocation.h
+++ b/Source/core/html/canvas/WebGLUniformLocation.h
@@ -36,18 +36,18 @@
 
 class WebGLUniformLocation FINAL : public RefCounted<WebGLUniformLocation>, public ScriptWrappable {
 public:
-    static PassRefPtr<WebGLUniformLocation> create(WebGLProgram*, GC3Dint location);
+    static PassRefPtr<WebGLUniformLocation> create(WebGLProgram*, GLint location);
 
     WebGLProgram* program() const;
 
-    GC3Dint location() const;
+    GLint location() const;
 
 protected:
-    WebGLUniformLocation(WebGLProgram*, GC3Dint location);
+    WebGLUniformLocation(WebGLProgram*, GLint location);
 
 private:
     RefPtr<WebGLProgram> m_program;
-    GC3Dint m_location;
+    GLint m_location;
     unsigned m_linkCount;
 };
 
diff --git a/Source/core/html/canvas/WebGLVertexArrayObjectOES.cpp b/Source/core/html/canvas/WebGLVertexArrayObjectOES.cpp
index 1d54886..dcb7e53 100644
--- a/Source/core/html/canvas/WebGLVertexArrayObjectOES.cpp
+++ b/Source/core/html/canvas/WebGLVertexArrayObjectOES.cpp
@@ -28,7 +28,6 @@
 #include "core/html/canvas/WebGLVertexArrayObjectOES.h"
 
 #include "core/html/canvas/WebGLRenderingContext.h"
-#include "platform/graphics/Extensions3D.h"
 
 namespace WebCore {
 
@@ -46,12 +45,11 @@
     ScriptWrappable::init(this);
     m_vertexAttribState.resize(ctx->maxVertexAttribs());
 
-    Extensions3D* extensions = context()->graphicsContext3D()->extensions();
     switch (m_type) {
     case VaoTypeDefault:
         break;
     default:
-        setObject(extensions->createVertexArrayOES());
+        setObject(context()->webGraphicsContext3D()->createVertexArrayOES());
         break;
     }
 }
@@ -61,14 +59,13 @@
     deleteObject(0);
 }
 
-void WebGLVertexArrayObjectOES::deleteObjectImpl(GraphicsContext3D* context3d, Platform3DObject object)
+void WebGLVertexArrayObjectOES::deleteObjectImpl(blink::WebGraphicsContext3D* context3d, Platform3DObject object)
 {
-    Extensions3D* extensions = context3d->extensions();
     switch (m_type) {
     case VaoTypeDefault:
         break;
     default:
-        extensions->deleteVertexArrayOES(object);
+        context()->webGraphicsContext3D()->deleteVertexArrayOES(object);
         break;
     }
 
@@ -87,22 +84,22 @@
     if (buffer)
         buffer->onAttached();
     if (m_boundElementArrayBuffer)
-        m_boundElementArrayBuffer->onDetached(context()->graphicsContext3D());
+        m_boundElementArrayBuffer->onDetached(context()->webGraphicsContext3D());
     m_boundElementArrayBuffer = buffer;
 
 }
 
 void WebGLVertexArrayObjectOES::setVertexAttribState(
-    GC3Duint index, GC3Dsizei bytesPerElement, GC3Dint size, GC3Denum type, GC3Dboolean normalized, GC3Dsizei stride, GC3Dintptr offset, PassRefPtr<WebGLBuffer> buffer)
+    GLuint index, GLsizei bytesPerElement, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset, PassRefPtr<WebGLBuffer> buffer)
 {
-    GC3Dsizei validatedStride = stride ? stride : bytesPerElement;
+    GLsizei validatedStride = stride ? stride : bytesPerElement;
 
     VertexAttribState& state = m_vertexAttribState[index];
 
     if (buffer)
         buffer->onAttached();
     if (state.bufferBinding)
-        state.bufferBinding->onDetached(context()->graphicsContext3D());
+        state.bufferBinding->onDetached(context()->webGraphicsContext3D());
 
     state.bufferBinding = buffer;
     state.bytesPerElement = bytesPerElement;
@@ -117,20 +114,20 @@
 void WebGLVertexArrayObjectOES::unbindBuffer(PassRefPtr<WebGLBuffer> buffer)
 {
     if (m_boundElementArrayBuffer == buffer) {
-        m_boundElementArrayBuffer->onDetached(context()->graphicsContext3D());
+        m_boundElementArrayBuffer->onDetached(context()->webGraphicsContext3D());
         m_boundElementArrayBuffer = 0;
     }
 
     for (size_t i = 0; i < m_vertexAttribState.size(); ++i) {
         VertexAttribState& state = m_vertexAttribState[i];
         if (state.bufferBinding == buffer) {
-            buffer->onDetached(context()->graphicsContext3D());
+            buffer->onDetached(context()->webGraphicsContext3D());
             state.bufferBinding = 0;
         }
     }
 }
 
-void WebGLVertexArrayObjectOES::setVertexAttribDivisor(GC3Duint index, GC3Duint divisor)
+void WebGLVertexArrayObjectOES::setVertexAttribDivisor(GLuint index, GLuint divisor)
 {
     VertexAttribState& state = m_vertexAttribState[index];
     state.divisor = divisor;
diff --git a/Source/core/html/canvas/WebGLVertexArrayObjectOES.h b/Source/core/html/canvas/WebGLVertexArrayObjectOES.h
index 2d7fe01..8b1c11d 100644
--- a/Source/core/html/canvas/WebGLVertexArrayObjectOES.h
+++ b/Source/core/html/canvas/WebGLVertexArrayObjectOES.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class WebGLVertexArrayObjectOES : public WebGLContextObject, public ScriptWrappable {
+class WebGLVertexArrayObjectOES FINAL : public WebGLContextObject, public ScriptWrappable {
 public:
     enum VaoType {
         VaoTypeDefault,
@@ -50,7 +50,7 @@
             : enabled(false)
             , bytesPerElement(0)
             , size(4)
-            , type(GraphicsContext3D::FLOAT)
+            , type(GL_FLOAT)
             , normalized(false)
             , stride(16)
             , originalStride(0)
@@ -61,14 +61,14 @@
 
         bool enabled;
         RefPtr<WebGLBuffer> bufferBinding;
-        GC3Dsizei bytesPerElement;
-        GC3Dint size;
-        GC3Denum type;
+        GLsizei bytesPerElement;
+        GLint size;
+        GLenum type;
         bool normalized;
-        GC3Dsizei stride;
-        GC3Dsizei originalStride;
-        GC3Dintptr offset;
-        GC3Duint divisor;
+        GLsizei stride;
+        GLsizei originalStride;
+        GLintptr offset;
+        GLuint divisor;
     };
 
     bool isDefaultObject() const { return m_type == VaoTypeDefault; }
@@ -80,16 +80,14 @@
     void setElementArrayBuffer(PassRefPtr<WebGLBuffer>);
 
     VertexAttribState& getVertexAttribState(int index) { return m_vertexAttribState[index]; }
-    void setVertexAttribState(GC3Duint, GC3Dsizei, GC3Dint, GC3Denum, GC3Dboolean, GC3Dsizei, GC3Dintptr, PassRefPtr<WebGLBuffer>);
+    void setVertexAttribState(GLuint, GLsizei, GLint, GLenum, GLboolean, GLsizei, GLintptr, PassRefPtr<WebGLBuffer>);
     void unbindBuffer(PassRefPtr<WebGLBuffer>);
-    void setVertexAttribDivisor(GC3Duint index, GC3Duint divisor);
+    void setVertexAttribDivisor(GLuint index, GLuint divisor);
 
 private:
     WebGLVertexArrayObjectOES(WebGLRenderingContext*, VaoType);
 
-    virtual void deleteObjectImpl(GraphicsContext3D*, Platform3DObject);
-
-    virtual bool isVertexArray() const { return true; }
+    virtual void deleteObjectImpl(blink::WebGraphicsContext3D*, Platform3DObject) OVERRIDE;
 
     VaoType m_type;
     bool m_hasEverBeenBound;
diff --git a/Source/core/html/forms/BaseCheckableInputType.h b/Source/core/html/forms/BaseCheckableInputType.h
index fdb2fa0..1e8a665 100644
--- a/Source/core/html/forms/BaseCheckableInputType.h
+++ b/Source/core/html/forms/BaseCheckableInputType.h
@@ -42,16 +42,16 @@
     virtual void handleKeydownEvent(KeyboardEvent*);
 
 private:
-    virtual FormControlState saveFormControlState() const OVERRIDE;
-    virtual void restoreFormControlState(const FormControlState&) OVERRIDE;
-    virtual bool appendFormData(FormDataList&, bool) const OVERRIDE;
-    virtual void handleKeypressEvent(KeyboardEvent*) OVERRIDE;
-    virtual bool canSetStringValue() const OVERRIDE;
-    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
-    virtual String fallbackValue() const OVERRIDE;
-    virtual bool storesValueSeparateFromAttribute() OVERRIDE;
-    virtual void setValue(const String&, bool, TextFieldEventBehavior) OVERRIDE;
-    virtual bool isCheckable() OVERRIDE;
+    virtual FormControlState saveFormControlState() const OVERRIDE FINAL;
+    virtual void restoreFormControlState(const FormControlState&) OVERRIDE FINAL;
+    virtual bool appendFormData(FormDataList&, bool) const OVERRIDE FINAL;
+    virtual void handleKeypressEvent(KeyboardEvent*) OVERRIDE FINAL;
+    virtual bool canSetStringValue() const OVERRIDE FINAL;
+    virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE FINAL;
+    virtual String fallbackValue() const OVERRIDE FINAL;
+    virtual bool storesValueSeparateFromAttribute() OVERRIDE FINAL;
+    virtual void setValue(const String&, bool, TextFieldEventBehavior) OVERRIDE FINAL;
+    virtual bool isCheckable() OVERRIDE FINAL;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp b/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
index 5ed613d..4fbb511 100644
--- a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
+++ b/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
@@ -29,10 +29,10 @@
 
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/shadow/ShadowRoot.h"
+#include "core/frame/FrameHost.h"
 #include "core/html/HTMLDivElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/page/Chrome.h"
-#include "core/page/Page.h"
 #include "platform/UserGestureIndicator.h"
 
 namespace WebCore {
@@ -49,12 +49,12 @@
 
     if (m_dateTimeChooser)
         return;
-    if (!element().document().page())
+    if (!element().document().isActive())
         return;
     DateTimeChooserParameters parameters;
     if (!element().setupDateTimeChooserParameters(parameters))
         return;
-    m_dateTimeChooser = element().document().page()->chrome().openDateTimeChooser(this, parameters);
+    m_dateTimeChooser = element().document().frameHost()->chrome().openDateTimeChooser(this, parameters);
 }
 
 void BaseChooserOnlyDateAndTimeInputType::createShadowSubtree()
@@ -62,7 +62,7 @@
     DEFINE_STATIC_LOCAL(AtomicString, valueContainerPseudo, ("-webkit-date-and-time-value", AtomicString::ConstructFromLiteral));
 
     RefPtr<HTMLDivElement> valueContainer = HTMLDivElement::create(element().document());
-    valueContainer->setPseudo(valueContainerPseudo);
+    valueContainer->setShadowPseudoId(valueContainerPseudo);
     element().userAgentShadowRoot()->appendChild(valueContainer.get());
     updateAppearance();
 }
diff --git a/Source/core/html/forms/BaseDateAndTimeInputType.cpp b/Source/core/html/forms/BaseDateAndTimeInputType.cpp
index bf87e94..6868f8a 100644
--- a/Source/core/html/forms/BaseDateAndTimeInputType.cpp
+++ b/Source/core/html/forms/BaseDateAndTimeInputType.cpp
@@ -64,9 +64,9 @@
     return value.isFinite() ? value.toDouble() : DateComponents::invalidMilliseconds();
 }
 
-void BaseDateAndTimeInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState&) const
+void BaseDateAndTimeInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
 {
-    element().setValue(serialize(newValue), eventBehavior);
+    setValueAsDecimal(Decimal::fromDouble(newValue), eventBehavior, exceptionState);
 }
 
 bool BaseDateAndTimeInputType::typeMismatchFor(const String& value) const
diff --git a/Source/core/html/forms/BaseDateAndTimeInputType.h b/Source/core/html/forms/BaseDateAndTimeInputType.h
index 0ce2d09..bf5c8bf 100644
--- a/Source/core/html/forms/BaseDateAndTimeInputType.h
+++ b/Source/core/html/forms/BaseDateAndTimeInputType.h
@@ -43,7 +43,11 @@
 protected:
     BaseDateAndTimeInputType(HTMLInputElement& element) : InputType(element) { }
     virtual Decimal parseToNumber(const String&, const Decimal&) const OVERRIDE;
-    virtual bool parseToDateComponents(const String&, DateComponents*) const OVERRIDE;
+    // Parses the specified string for this InputType, and returns true if it
+    // is successfully parsed. An instance pointed by the DateComponents*
+    // parameter will have parsed values and be modified even if the parsing
+    // fails. The DateComponents* parameter may be 0.
+    bool parseToDateComponents(const String&, DateComponents*) const;
     virtual String sanitizeValue(const String&) const OVERRIDE;
     virtual String serialize(const Decimal&) const OVERRIDE;
     String serializeWithComponents(const DateComponents&) const;
@@ -52,11 +56,10 @@
 
 private:
     virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const = 0;
-    virtual DateComponents::Type dateType() const = 0;
     virtual double valueAsDate() const OVERRIDE;
     virtual void setValueAsDate(double, ExceptionState&) const OVERRIDE;
     virtual double valueAsDouble() const OVERRIDE;
-    virtual void setValueAsDecimal(const Decimal&, TextFieldEventBehavior, ExceptionState&) const OVERRIDE;
+    virtual void setValueAsDouble(double, TextFieldEventBehavior, ExceptionState&) const OVERRIDE;
     virtual bool typeMismatchFor(const String&) const OVERRIDE;
     virtual bool typeMismatch() const OVERRIDE;
     virtual bool valueMissing(const String&) const OVERRIDE;
diff --git a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
index 9758338..447ae22 100644
--- a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
+++ b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
@@ -185,7 +185,7 @@
         input->setNeedsValidityCheck();
     } else {
         input->setValueInternal(newValue, DispatchNoEvent);
-        input->setNeedsStyleRecalc();
+        input->setNeedsStyleRecalc(SubtreeStyleChange);
         input->dispatchFormControlInputEvent();
         input->dispatchFormControlChangeEvent();
     }
@@ -379,15 +379,15 @@
     m_isDestroyingShadowSubtree = false;
 }
 
-void BaseMultipleFieldsDateAndTimeInputType::handleFocusEvent(Element* oldFocusedElement, FocusDirection direction)
+void BaseMultipleFieldsDateAndTimeInputType::handleFocusEvent(Element* oldFocusedElement, FocusType type)
 {
     DateTimeEditElement* edit = dateTimeEditElement();
     if (!edit || m_isDestroyingShadowSubtree)
         return;
-    if (direction == FocusDirectionBackward) {
+    if (type == FocusTypeBackward) {
         if (element().document().page())
-            element().document().page()->focusController().advanceFocus(direction);
-    } else if (direction == FocusDirectionNone || direction == FocusDirectionMouse || direction == FocusDirectionPage) {
+            element().document().page()->focusController().advanceFocus(type);
+    } else if (type == FocusTypeNone || type == FocusTypeMouse || type == FocusTypePage) {
         edit->focusByOwner(oldFocusedElement);
     } else {
         edit->focusByOwner();
@@ -540,18 +540,10 @@
         showPickerIndicator();
         return;
     }
-    if (RuntimeEnabledFeatures::dataListElementEnabled()) {
-        if (HTMLDataListElement* dataList = element().dataList()) {
-            RefPtr<HTMLCollection> options = dataList->options();
-            for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
-                if (element().isValidValue(option->value())) {
-                    showPickerIndicator();
-                    return;
-                }
-            }
-        }
+    if (element().hasValidDataListOptions())
+        showPickerIndicator();
+    else
         hidePickerIndicator();
-    }
 }
 
 void BaseMultipleFieldsDateAndTimeInputType::hidePickerIndicator()
@@ -603,10 +595,13 @@
     if (!clearButton)
         return;
 
-    if (element().isRequired() || !dateTimeEditElement()->anyEditableFieldsHaveValues())
-        clearButton->setInlineStyleProperty(CSSPropertyVisibility, CSSValueHidden);
-    else
-        clearButton->removeInlineStyleProperty(CSSPropertyVisibility);
+    if (element().isRequired() || !dateTimeEditElement()->anyEditableFieldsHaveValues()) {
+        clearButton->setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
+        clearButton->setInlineStyleProperty(CSSPropertyPointerEvents, CSSValueNone);
+    } else {
+        clearButton->removeInlineStyleProperty(CSSPropertyOpacity);
+        clearButton->removeInlineStyleProperty(CSSPropertyPointerEvents);
+    }
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h
index 14a0a2c..af8f2c0 100644
--- a/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h
+++ b/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h
@@ -94,7 +94,7 @@
     virtual void destroyShadowSubtree() OVERRIDE FINAL;
     virtual void disabledAttributeChanged() OVERRIDE FINAL;
     virtual void forwardEvent(Event*) OVERRIDE FINAL;
-    virtual void handleFocusEvent(Element* oldFocusedElement, FocusDirection) OVERRIDE;
+    virtual void handleFocusEvent(Element* oldFocusedElement, FocusType) OVERRIDE;
     virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE FINAL;
     virtual bool hasBadInput() const OVERRIDE;
     virtual bool hasCustomFocusLogic() const OVERRIDE FINAL;
diff --git a/Source/core/html/forms/BaseTextInputType.h b/Source/core/html/forms/BaseTextInputType.h
index 8c917a0..c274368 100644
--- a/Source/core/html/forms/BaseTextInputType.h
+++ b/Source/core/html/forms/BaseTextInputType.h
@@ -42,9 +42,9 @@
     BaseTextInputType(HTMLInputElement& element) : TextFieldInputType(element) { }
 
 private:
-    virtual bool isTextType() const OVERRIDE;
-    virtual bool patternMismatch(const String&) const OVERRIDE;
-    virtual bool supportsPlaceholder() const OVERRIDE;
+    virtual bool isTextType() const OVERRIDE FINAL;
+    virtual bool patternMismatch(const String&) const OVERRIDE FINAL;
+    virtual bool supportsPlaceholder() const OVERRIDE FINAL;
     virtual bool supportsSelectionAPI() const OVERRIDE;
 };
 
diff --git a/Source/core/html/forms/ButtonInputType.h b/Source/core/html/forms/ButtonInputType.h
index aa31135..68e2f28 100644
--- a/Source/core/html/forms/ButtonInputType.h
+++ b/Source/core/html/forms/ButtonInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class ButtonInputType : public BaseButtonInputType {
+class ButtonInputType FINAL : public BaseButtonInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/CheckboxInputType.h b/Source/core/html/forms/CheckboxInputType.h
index 9299018..e6d15d7 100644
--- a/Source/core/html/forms/CheckboxInputType.h
+++ b/Source/core/html/forms/CheckboxInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class CheckboxInputType : public BaseCheckableInputType {
+class CheckboxInputType FINAL : public BaseCheckableInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/ColorInputType.cpp b/Source/core/html/forms/ColorInputType.cpp
index 304504b..9adbc54 100644
--- a/Source/core/html/forms/ColorInputType.cpp
+++ b/Source/core/html/forms/ColorInputType.cpp
@@ -68,8 +68,8 @@
     // We don't accept #rgb and #aarrggbb formats.
     if (value.length() != 7)
         return false;
-    Color color(value);
-    return color.isValid() && !color.hasAlpha();
+    Color color;
+    return color.setFromString(value) && !color.hasAlpha();
 }
 
 PassRefPtr<InputType> ColorInputType::create(HTMLInputElement& element)
@@ -117,7 +117,10 @@
 
 Color ColorInputType::valueAsColor() const
 {
-    return Color(element().value());
+    Color color;
+    bool success = color.setFromString(element().value());
+    ASSERT_UNUSED(success, success);
+    return color;
 }
 
 void ColorInputType::createShadowSubtree()
@@ -126,9 +129,9 @@
 
     Document& document = element().document();
     RefPtr<HTMLDivElement> wrapperElement = HTMLDivElement::create(document);
-    wrapperElement->setPseudo(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
+    wrapperElement->setShadowPseudoId(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
     RefPtr<HTMLDivElement> colorSwatch = HTMLDivElement::create(document);
-    colorSwatch->setPseudo(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
+    colorSwatch->setShadowPseudoId(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
     wrapperElement->appendChild(colorSwatch.release());
     element().userAgentShadowRoot()->appendChild(wrapperElement.release());
 
@@ -224,30 +227,25 @@
 
 bool ColorInputType::shouldShowSuggestions() const
 {
-    if (RuntimeEnabledFeatures::dataListElementEnabled())
-        return element().fastHasAttribute(listAttr);
-
-    return false;
+    return element().fastHasAttribute(listAttr);
 }
 
 Vector<ColorSuggestion> ColorInputType::suggestions() const
 {
     Vector<ColorSuggestion> suggestions;
-    if (RuntimeEnabledFeatures::dataListElementEnabled()) {
-        HTMLDataListElement* dataList = element().dataList();
-        if (dataList) {
-            RefPtr<HTMLCollection> options = dataList->options();
-            for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); i++) {
-                if (!element().isValidValue(option->value()))
-                    continue;
-                Color color(option->value());
-                if (!color.isValid())
-                    continue;
-                ColorSuggestion suggestion(color, option->label().left(maxSuggestionLabelLength));
-                suggestions.append(suggestion);
-                if (suggestions.size() >= maxSuggestions)
-                    break;
-            }
+    HTMLDataListElement* dataList = element().dataList();
+    if (dataList) {
+        RefPtr<HTMLCollection> options = dataList->options();
+        for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); i++) {
+            if (!element().isValidValue(option->value()))
+                continue;
+            Color color;
+            if (!color.setFromString(option->value()))
+                continue;
+            ColorSuggestion suggestion(color, option->label().left(maxSuggestionLabelLength));
+            suggestions.append(suggestion);
+            if (suggestions.size() >= maxSuggestions)
+                break;
         }
     }
     return suggestions;
diff --git a/Source/core/html/forms/ColorInputType.h b/Source/core/html/forms/ColorInputType.h
index b0f7ba3..b28246a 100644
--- a/Source/core/html/forms/ColorInputType.h
+++ b/Source/core/html/forms/ColorInputType.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class ColorInputType : public BaseClickableWithKeyInputType, public ColorChooserClient {
+class ColorInputType FINAL : public BaseClickableWithKeyInputType, public ColorChooserClient {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
     virtual ~ColorInputType();
diff --git a/Source/core/html/forms/DateInputType.cpp b/Source/core/html/forms/DateInputType.cpp
index c76e4be..148881e 100644
--- a/Source/core/html/forms/DateInputType.cpp
+++ b/Source/core/html/forms/DateInputType.cpp
@@ -68,20 +68,11 @@
     return InputTypeNames::date;
 }
 
-DateComponents::Type DateInputType::dateType() const
-{
-    return DateComponents::Date;
-}
-
 StepRange DateInputType::createStepRange(AnyStepHandling anyStepHandling) const
 {
     DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (dateDefaultStep, dateDefaultStepBase, dateStepScaleFactor, StepRange::ParsedStepValueShouldBeInteger));
 
-    const Decimal stepBase = findStepBase(0);
-    const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumDate()));
-    const Decimal maximum = parseToNumber(element().fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumDate()));
-    const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
-    return StepRange(stepBase, minimum, maximum, step, stepDescription);
+    return InputType::createStepRange(anyStepHandling, dateDefaultStepBase, Decimal::fromDouble(DateComponents::minimumDate()), Decimal::fromDouble(DateComponents::maximumDate()), stepDescription);
 }
 
 bool DateInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
diff --git a/Source/core/html/forms/DateInputType.h b/Source/core/html/forms/DateInputType.h
index aa13e43..0e5abec 100644
--- a/Source/core/html/forms/DateInputType.h
+++ b/Source/core/html/forms/DateInputType.h
@@ -44,7 +44,7 @@
 typedef BaseChooserOnlyDateAndTimeInputType BaseDateInputType;
 #endif
 
-class DateInputType : public BaseDateInputType {
+class DateInputType FINAL : public BaseDateInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
@@ -52,7 +52,6 @@
     DateInputType(HTMLInputElement&);
     virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
-    virtual DateComponents::Type dateType() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
     virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
     virtual bool setMillisecondToDateComponents(double, DateComponents*) const OVERRIDE;
@@ -62,7 +61,7 @@
     // BaseMultipleFieldsDateAndTimeInputType functions
     virtual String formatDateTimeFieldsState(const DateTimeFieldsState&) const OVERRIDE;
     virtual void setupLayoutParameters(DateTimeEditElement::LayoutParameters&, const DateComponents&) const OVERRIDE;
-    virtual bool isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const;
+    virtual bool isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const OVERRIDE;
 #endif
 };
 
diff --git a/Source/core/html/forms/DateTimeLocalInputType.cpp b/Source/core/html/forms/DateTimeLocalInputType.cpp
index 9ad29fa..ae901a1 100644
--- a/Source/core/html/forms/DateTimeLocalInputType.cpp
+++ b/Source/core/html/forms/DateTimeLocalInputType.cpp
@@ -65,11 +65,6 @@
     return InputTypeNames::datetime_local;
 }
 
-DateComponents::Type DateTimeLocalInputType::dateType() const
-{
-    return DateComponents::DateTimeLocal;
-}
-
 double DateTimeLocalInputType::valueAsDate() const
 {
     // valueAsDate doesn't work for the datetime-local type according to the standard.
@@ -86,11 +81,7 @@
 {
     DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (dateTimeLocalDefaultStep, dateTimeLocalDefaultStepBase, dateTimeLocalStepScaleFactor, StepRange::ScaledStepValueShouldBeInteger));
 
-    const Decimal stepBase = findStepBase(0);
-    const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumDateTime()));
-    const Decimal maximum = parseToNumber(element().fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumDateTime()));
-    const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
-    return StepRange(stepBase, minimum, maximum, step, stepDescription);
+    return InputType::createStepRange(anyStepHandling, dateTimeLocalDefaultStepBase, Decimal::fromDouble(DateComponents::minimumDateTime()), Decimal::fromDouble(DateComponents::maximumDateTime()), stepDescription);
 }
 
 bool DateTimeLocalInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
diff --git a/Source/core/html/forms/DateTimeLocalInputType.h b/Source/core/html/forms/DateTimeLocalInputType.h
index eca7d02..f3fc386 100644
--- a/Source/core/html/forms/DateTimeLocalInputType.h
+++ b/Source/core/html/forms/DateTimeLocalInputType.h
@@ -44,7 +44,7 @@
 typedef BaseChooserOnlyDateAndTimeInputType BaseDateTimeLocalInputType;
 #endif
 
-class DateTimeLocalInputType : public BaseDateTimeLocalInputType {
+class DateTimeLocalInputType FINAL : public BaseDateTimeLocalInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
@@ -52,7 +52,6 @@
     DateTimeLocalInputType(HTMLInputElement& element) : BaseDateTimeLocalInputType(element) { }
     virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
-    virtual DateComponents::Type dateType() const OVERRIDE;
     virtual double valueAsDate() const OVERRIDE;
     virtual void setValueAsDate(double, ExceptionState&) const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const;
diff --git a/Source/core/html/forms/EmailInputType.cpp b/Source/core/html/forms/EmailInputType.cpp
index 20db60b..968df8c 100644
--- a/Source/core/html/forms/EmailInputType.cpp
+++ b/Source/core/html/forms/EmailInputType.cpp
@@ -45,7 +45,8 @@
 static const char emailPattern[] =
     "[a-z0-9!#$%&'*+/=?^_`{|}~.-]+" // local part
     "@"
-    "[a-z0-9-]+(\\.[a-z0-9-]+)*"; // domain part
+    "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?" // domain part
+    "(?:\\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*";
 
 // RFC5321 says the maximum total length of a domain name is 255 octets.
 static const size_t maximumDomainNameLength = 255;
diff --git a/Source/core/html/forms/EmailInputType.h b/Source/core/html/forms/EmailInputType.h
index 82bd153..1cfc7f9 100644
--- a/Source/core/html/forms/EmailInputType.h
+++ b/Source/core/html/forms/EmailInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class EmailInputType : public BaseTextInputType {
+class EmailInputType FINAL : public BaseTextInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/FileInputType.cpp b/Source/core/html/forms/FileInputType.cpp
index 64338a6..e0ceace 100644
--- a/Source/core/html/forms/FileInputType.cpp
+++ b/Source/core/html/forms/FileInputType.cpp
@@ -146,7 +146,7 @@
     if (Chrome* chrome = this->chrome()) {
         FileChooserSettings settings;
         HTMLInputElement& input = element();
-        settings.allowsDirectoryUpload = RuntimeEnabledFeatures::directoryUploadEnabled() && input.fastHasAttribute(webkitdirectoryAttr);
+        settings.allowsDirectoryUpload = input.fastHasAttribute(webkitdirectoryAttr);
         settings.allowsMultipleFiles = settings.allowsDirectoryUpload || input.fastHasAttribute(multipleAttr);
         settings.acceptMIMETypes = input.acceptMIMETypes();
         settings.acceptFileExtensions = input.acceptFileExtensions();
@@ -200,10 +200,14 @@
     return true;
 }
 
-void FileInputType::setValue(const String&, bool, TextFieldEventBehavior)
+void FileInputType::setValue(const String&, bool valueChanged, TextFieldEventBehavior)
 {
+    if (!valueChanged)
+        return;
+
     m_fileList->clear();
-    element().setNeedsStyleRecalc();
+    element().setNeedsStyleRecalc(SubtreeStyleChange);
+    element().setNeedsValidityCheck();
 }
 
 PassRefPtr<FileList> FileInputType::createFileList(const Vector<FileChooserFileInfo>& files) const
@@ -214,7 +218,7 @@
     // If a directory is being selected, the UI allows a directory to be chosen
     // and the paths provided here share a root directory somewhere up the tree;
     // we want to store only the relative paths from that point.
-    if (size && element().fastHasAttribute(webkitdirectoryAttr) && RuntimeEnabledFeatures::directoryUploadEnabled()) {
+    if (size && element().fastHasAttribute(webkitdirectoryAttr)) {
         // Find the common root path.
         String rootPath = directoryName(files[0].path);
         for (size_t i = 1; i < size; i++) {
@@ -249,8 +253,8 @@
     ASSERT(element().shadow());
     RefPtr<HTMLInputElement> button = HTMLInputElement::create(element().document(), 0, false);
     button->setType(InputTypeNames::button);
-    button->setAttribute(valueAttr, locale().queryString(element().multiple() ? WebLocalizedString::FileButtonChooseMultipleFilesLabel : WebLocalizedString::FileButtonChooseFileLabel));
-    button->setPseudo(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
+    button->setAttribute(valueAttr, AtomicString(locale().queryString(element().multiple() ? WebLocalizedString::FileButtonChooseMultipleFilesLabel : WebLocalizedString::FileButtonChooseFileLabel)));
+    button->setShadowPseudoId(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
     element().userAgentShadowRoot()->appendChild(button.release());
 }
 
@@ -265,7 +269,7 @@
 {
     ASSERT(element().shadow());
     if (Element* button = toElement(element().userAgentShadowRoot()->firstChild()))
-        button->setAttribute(valueAttr, locale().queryString(element().multiple() ? WebLocalizedString::FileButtonChooseMultipleFilesLabel : WebLocalizedString::FileButtonChooseFileLabel));
+        button->setAttribute(valueAttr, AtomicString(locale().queryString(element().multiple() ? WebLocalizedString::FileButtonChooseMultipleFilesLabel : WebLocalizedString::FileButtonChooseFileLabel)));
 }
 
 void FileInputType::setFiles(PassRefPtr<FileList> files)
@@ -303,7 +307,7 @@
     if (pathsChanged) {
         // This call may cause destruction of this instance.
         // input instance is safe since it is ref-counted.
-        input->HTMLElement::dispatchChangeEvent();
+        input->dispatchChangeEvent();
     }
     input->setChangedSinceLastFormControlChangeEvent(false);
 }
@@ -335,7 +339,7 @@
         return false;
 
     HTMLInputElement& input = element();
-    if (input.fastHasAttribute(webkitdirectoryAttr) && RuntimeEnabledFeatures::directoryUploadEnabled()) {
+    if (input.fastHasAttribute(webkitdirectoryAttr)) {
         receiveDropForDirectoryUpload(paths);
         return true;
     }
diff --git a/Source/core/html/forms/FileInputType.h b/Source/core/html/forms/FileInputType.h
index a91ba75..a675ec9 100644
--- a/Source/core/html/forms/FileInputType.h
+++ b/Source/core/html/forms/FileInputType.h
@@ -41,7 +41,7 @@
 class DragData;
 class FileList;
 
-class FileInputType : public BaseClickableWithKeyInputType, private FileChooserClient {
+class FileInputType FINAL : public BaseClickableWithKeyInputType, private FileChooserClient {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
     static Vector<FileChooserFileInfo> filesFromFormControlState(const FormControlState&);
diff --git a/Source/core/html/forms/FormController.cpp b/Source/core/html/forms/FormController.cpp
index a3cd9b0..09f2b0e 100644
--- a/Source/core/html/forms/FormController.cpp
+++ b/Source/core/html/forms/FormController.cpp
@@ -221,7 +221,7 @@
         FormControlState state = FormControlState::deserialize(stateVector, index);
         if (type.isEmpty() || type.find(isNotFormControlTypeCharacter) != kNotFound || state.isFailure())
             return nullptr;
-        savedFormState->appendControlState(name, type, state);
+        savedFormState->appendControlState(AtomicString(name), AtomicString(type), state);
     }
     return savedFormState.release();
 }
@@ -356,14 +356,14 @@
     String signature = formSignature(*form);
     ASSERT(!signature.isNull());
     FormSignatureToNextIndexMap::AddResult result = m_formSignatureToNextIndexMap.add(signature, 0);
-    unsigned nextIndex = result.iterator->value++;
+    unsigned nextIndex = result.storedValue->value++;
 
     StringBuilder formKeyBuilder;
     formKeyBuilder.append(signature);
     formKeyBuilder.appendLiteral(" #");
     formKeyBuilder.appendNumber(nextIndex);
     FormToKeyMap::AddResult addFormKeyresult = m_formToKeyMap.add(form, formKeyBuilder.toAtomicString());
-    return addFormKeyresult.iterator->value;
+    return addFormKeyresult.storedValue->value;
 }
 
 void FormKeyGenerator::willDeleteForm(HTMLFormElement* form)
@@ -402,17 +402,17 @@
             continue;
         SavedFormStateMap::AddResult result = stateMap->add(keyGenerator->formKey(*control), nullptr);
         if (result.isNewEntry)
-            result.iterator->value = SavedFormState::create();
-        result.iterator->value->appendControlState(control->name(), control->type(), control->saveFormControlState());
+            result.storedValue->value = SavedFormState::create();
+        result.storedValue->value->appendControlState(control->name(), control->type(), control->saveFormControlState());
     }
     return stateMap.release();
 }
 
 Vector<String> FormController::formElementsState() const
 {
-    OwnPtr<SavedFormStateMap> stateMap = createSavedFormStateMap(m_formElementsWithState);
+    OwnPtr<SavedFormStateMap> stateMap = createSavedFormStateMap(m_formControls);
     Vector<String> stateVector;
-    stateVector.reserveInitialCapacity(m_formElementsWithState.size() * 4);
+    stateVector.reserveInitialCapacity(m_formControls.size() * 4);
     stateVector.append(formStateSignature());
     for (SavedFormStateMap::const_iterator it = stateMap->begin(); it != stateMap->end(); ++it) {
         stateVector.append(it->key);
@@ -453,7 +453,7 @@
         return;
 
     while (i + 1 < stateVector.size()) {
-        AtomicString formKey = stateVector[i++];
+        AtomicString formKey = AtomicString(stateVector[i++]);
         OwnPtr<SavedFormState> state = SavedFormState::deserialize(stateVector, i);
         if (!state) {
             i = 0;
@@ -512,16 +512,16 @@
     return toReturn;
 }
 
-void FormController::registerFormElementWithState(HTMLFormControlElementWithState* control)
+void FormController::registerStatefulFormControl(HTMLFormControlElementWithState& control)
 {
-    ASSERT(!m_formElementsWithState.contains(control));
-    m_formElementsWithState.add(control);
+    ASSERT(!m_formControls.contains(&control));
+    m_formControls.add(&control);
 }
 
-void FormController::unregisterFormElementWithState(HTMLFormControlElementWithState* control)
+void FormController::unregisterStatefulFormControl(HTMLFormControlElementWithState& control)
 {
-    RELEASE_ASSERT(m_formElementsWithState.contains(control));
-    m_formElementsWithState.remove(control);
+    RELEASE_ASSERT(m_formControls.contains(&control));
+    m_formControls.remove(&control);
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/forms/FormController.h b/Source/core/html/forms/FormController.h
index 4079935..21d5860 100644
--- a/Source/core/html/forms/FormController.h
+++ b/Source/core/html/forms/FormController.h
@@ -22,7 +22,7 @@
 #ifndef FormController_h
 #define FormController_h
 
-#include "core/html/forms/CheckedRadioButtons.h"
+#include "core/html/forms/RadioButtonGroupScope.h"
 #include "wtf/Forward.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/Vector.h"
@@ -80,10 +80,10 @@
     }
     ~FormController();
 
-    CheckedRadioButtons& checkedRadioButtons() { return m_checkedRadioButtons; }
+    RadioButtonGroupScope& radioButtonGroupScope() { return m_radioButtonGroupScope; }
 
-    void registerFormElementWithState(HTMLFormControlElementWithState*);
-    void unregisterFormElementWithState(HTMLFormControlElementWithState*);
+    void registerStatefulFormControl(HTMLFormControlElementWithState&);
+    void unregisterStatefulFormControl(HTMLFormControlElementWithState&);
     // This should be callled only by Document::formElementsState().
     Vector<String> formElementsState() const;
     // This should be callled only by Document::setStateForNewFormElements().
@@ -103,8 +103,8 @@
     FormControlState takeStateForFormElement(const HTMLFormControlElementWithState&);
     static void formStatesFromStateVector(const Vector<String>&, SavedFormStateMap&);
 
-    CheckedRadioButtons m_checkedRadioButtons;
-    FormElementListHashSet m_formElementsWithState;
+    RadioButtonGroupScope m_radioButtonGroupScope;
+    FormElementListHashSet m_formControls;
     SavedFormStateMap m_savedFormStateMap;
     OwnPtr<FormKeyGenerator> m_formKeyGenerator;
 };
diff --git a/Source/core/html/forms/HiddenInputType.h b/Source/core/html/forms/HiddenInputType.h
index a93b5c3..4670459 100644
--- a/Source/core/html/forms/HiddenInputType.h
+++ b/Source/core/html/forms/HiddenInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class HiddenInputType : public InputType {
+class HiddenInputType FINAL : public InputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/ImageInputType.h b/Source/core/html/forms/ImageInputType.h
index d033e2a..c871974 100644
--- a/Source/core/html/forms/ImageInputType.h
+++ b/Source/core/html/forms/ImageInputType.h
@@ -38,7 +38,7 @@
 
 namespace WebCore {
 
-class ImageInputType : public BaseButtonInputType {
+class ImageInputType FINAL : public BaseButtonInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/InputType.cpp b/Source/core/html/forms/InputType.cpp
index 65ba6ea..53ad643 100644
--- a/Source/core/html/forms/InputType.cpp
+++ b/Source/core/html/forms/InputType.cpp
@@ -30,11 +30,14 @@
 
 #include "InputTypeNames.h"
 #include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionState.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/events/ScopedEventQueue.h"
 #include "core/fileapi/FileList.h"
+#include "core/frame/FrameHost.h"
 #include "core/html/FormDataList.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/ButtonInputType.h"
@@ -62,7 +65,6 @@
 #include "core/html/forms/WeekInputType.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/HTMLShadowElement.h"
-#include "core/page/Page.h"
 #include "core/rendering/RenderTheme.h"
 #include "platform/text/PlatformLocale.h"
 #include "platform/text/TextBreakIterator.h"
@@ -81,8 +83,7 @@
     OwnPtr<InputTypeFactoryMap> map = adoptPtr(new InputTypeFactoryMap);
     map->add(InputTypeNames::button, ButtonInputType::create);
     map->add(InputTypeNames::checkbox, CheckboxInputType::create);
-    if (RuntimeEnabledFeatures::inputTypeColorEnabled())
-        map->add(InputTypeNames::color, ColorInputType::create);
+    map->add(InputTypeNames::color, ColorInputType::create);
     map->add(InputTypeNames::date, DateInputType::create);
     map->add(InputTypeNames::datetime_local, DateTimeLocalInputType::create);
     map->add(InputTypeNames::email, EmailInputType::create);
@@ -100,8 +101,7 @@
     map->add(InputTypeNames::tel, TelephoneInputType::create);
     map->add(InputTypeNames::time, TimeInputType::create);
     map->add(InputTypeNames::url, URLInputType::create);
-    if (RuntimeEnabledFeatures::inputTypeWeekEnabled())
-        map->add(InputTypeNames::week, WeekInputType::create);
+    map->add(InputTypeNames::week, WeekInputType::create);
     // No need to register "text" because it is the default type.
     return map.release();
 }
@@ -210,7 +210,7 @@
 
 void InputType::setValueAsDate(double, ExceptionState& exceptionState) const
 {
-    exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+    exceptionState.throwDOMException(InvalidStateError, "This input element does not support Date values.");
 }
 
 double InputType::valueAsDouble() const
@@ -220,12 +220,12 @@
 
 void InputType::setValueAsDouble(double doubleValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
 {
-    setValueAsDecimal(Decimal::fromDouble(doubleValue), eventBehavior, exceptionState);
+    exceptionState.throwDOMException(InvalidStateError, "This input element does not support Number values.");
 }
 
-void InputType::setValueAsDecimal(const Decimal&, TextFieldEventBehavior, ExceptionState& exceptionState) const
+void InputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState&) const
 {
-    exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+    element().setValue(serialize(newValue), eventBehavior);
 }
 
 bool InputType::supportsValidation() const
@@ -437,12 +437,6 @@
     return parseToNumber(string, Decimal::nan());
 }
 
-bool InputType::parseToDateComponents(const String&, DateComponents*) const
-{
-    ASSERT_NOT_REACHED();
-    return false;
-}
-
 String InputType::serialize(const Decimal&) const
 {
     ASSERT_NOT_REACHED();
@@ -458,8 +452,8 @@
 
 Chrome* InputType::chrome() const
 {
-    if (Page* page = element().document().page())
-        return &page->chrome();
+    if (FrameHost* host = element().document().frameHost())
+        return &host->chrome();
     return 0;
 }
 
@@ -571,7 +565,7 @@
 void InputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
 {
     element().setValueInternal(sanitizedValue, eventBehavior);
-    element().setNeedsStyleRecalc();
+    element().setNeedsStyleRecalc(SubtreeStyleChange);
     if (!valueChanged)
         return;
     switch (eventBehavior) {
@@ -619,11 +613,6 @@
     return String();
 }
 
-bool InputType::shouldResetOnDocumentActivation()
-{
-    return false;
-}
-
 bool InputType::shouldRespectListAttribute()
 {
     return false;
@@ -689,11 +678,6 @@
     return false;
 }
 
-bool InputType::isSubmitButton() const
-{
-    return false;
-}
-
 bool InputType::isTelephoneField() const
 {
     return false;
@@ -808,46 +792,64 @@
     return 0;
 }
 
-void InputType::applyStep(int count, AnyStepHandling anyStepHandling, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState)
+void InputType::applyStep(const Decimal& current, int count, AnyStepHandling anyStepHandling, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState)
 {
     StepRange stepRange(createStepRange(anyStepHandling));
     if (!stepRange.hasStep()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "This form element does not have an allowed value step.");
         return;
     }
 
-    const Decimal current = parseToNumberOrNaN(element().value());
-    if (!current.isFinite()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
-        return;
-    }
-    Decimal newValue = current + stepRange.step() * count;
-    if (!newValue.isFinite()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
-        return;
-    }
-
-    const Decimal acceptableErrorValue = stepRange.acceptableError();
-    if (newValue - stepRange.minimum() < -acceptableErrorValue) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
-        return;
-    }
-    if (newValue < stepRange.minimum())
-        newValue = stepRange.minimum();
+    EventQueueScope scope;
+    const Decimal step = stepRange.step();
 
     const AtomicString& stepString = element().fastGetAttribute(stepAttr);
-    if (!equalIgnoringCase(stepString, "any"))
-        newValue = stepRange.alignValueForStep(current, newValue);
+    if (!equalIgnoringCase(stepString, "any") && stepRange.stepMismatch(current)) {
+        // Snap-to-step / clamping steps
+        // If the current value is not matched to step value:
+        // - The value should be the larger matched value nearest to 0 if count > 0
+        //   e.g. <input type=number value=3 min=-100 step=3> -> 5
+        // - The value should be the smaller matched value nearest to 0 if count < 0
+        //   e.g. <input type=number value=3 min=-100 step=3> -> 2
+        //
 
-    if (newValue - stepRange.maximum() > acceptableErrorValue) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
-        return;
+        ASSERT(!step.isZero());
+        Decimal newValue;
+        const Decimal base = stepRange.stepBase();
+        if (count < 0)
+            newValue = base + ((current - base) / step).floor() * step;
+        else if (count > 0)
+            newValue = base + ((current - base) / step).ceiling() * step;
+        else
+            newValue = current;
+
+        if (newValue < stepRange.minimum())
+            newValue = stepRange.minimum();
+        if (newValue > stepRange.maximum())
+            newValue = stepRange.maximum();
+
+        setValueAsDecimal(newValue, count == 1 || count == -1 ? DispatchChangeEvent : DispatchNoEvent, IGNORE_EXCEPTION);
+        if (count > 1) {
+            applyStep(newValue, count - 1, AnyIsDefaultStep, DispatchChangeEvent, IGNORE_EXCEPTION);
+            return;
+        }
+        if (count < -1) {
+            applyStep(newValue, count + 1, AnyIsDefaultStep, DispatchChangeEvent, IGNORE_EXCEPTION);
+            return;
+        }
+    } else {
+        Decimal newValue = current + stepRange.step() * count;
+
+        if (!equalIgnoringCase(stepString, "any"))
+            newValue = stepRange.alignValueForStep(current, newValue);
+
+        if (newValue > stepRange.maximum())
+            newValue = newValue - stepRange.step();
+        else if (newValue < stepRange.minimum())
+            newValue = newValue + stepRange.step();
+
+        setValueAsDecimal(newValue, eventBehavior, exceptionState);
     }
-    if (newValue > stepRange.maximum())
-        newValue = stepRange.maximum();
-
-    setValueAsDecimal(newValue, eventBehavior, exceptionState);
-
     if (AXObjectCache* cache = element().document().existingAXObjectCache())
         cache->postNotification(&element(), AXObjectCache::AXValueChanged, true);
 }
@@ -868,17 +870,18 @@
 void InputType::stepUp(int n, ExceptionState& exceptionState)
 {
     if (!isSteppable()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+        exceptionState.throwDOMException(InvalidStateError, "This form element is not steppable.");
         return;
     }
-    applyStep(n, RejectAny, DispatchNoEvent, exceptionState);
+    const Decimal current = parseToNumber(element().value(), 0);
+    applyStep(current, n, RejectAny, DispatchNoEvent, exceptionState);
 }
 
 void InputType::stepUpFromRenderer(int n)
 {
-    // The differences from stepUp()/stepDown():
+    // The only difference from stepUp()/stepDown() is the extra treatment
+    // of the current value before applying the step:
     //
-    // Difference 1: the current value
     // If the current value is not a number, including empty, the current value is assumed as 0.
     //   * If 0 is in-range, and matches to step value
     //     - The value should be the +step if n > 0
@@ -902,13 +905,6 @@
     //  - The value should be the maximum value if n < 0
     //  - Nothing should happen if n > 0
     //
-    // Difference 2: clamping steps
-    // If the current value is not matched to step value:
-    // - The value should be the larger matched value nearest to 0 if n > 0
-    //   e.g. <input type=number value=3 min=-100 step=3> -> 5
-    // - The value should be the smaler matched value nearest to 0 if n < 0
-    //   e.g. <input type=number value=3 min=-100 step=3> -> 2
-    //
     // n is assumed as -n if step < 0.
 
     ASSERT(isSteppable());
@@ -936,8 +932,7 @@
     else
         sign = 0;
 
-    String currentStringValue = element().value();
-    Decimal current = parseToNumberOrNaN(currentStringValue);
+    Decimal current = parseToNumberOrNaN(element().value());
     if (!current.isFinite()) {
         current = defaultValueForStepUp();
         const Decimal nextDiff = step * n;
@@ -949,32 +944,9 @@
     }
     if ((sign > 0 && current < stepRange.minimum()) || (sign < 0 && current > stepRange.maximum())) {
         setValueAsDecimal(sign > 0 ? stepRange.minimum() : stepRange.maximum(), DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
-    } else {
-        if (stepMismatch(element().value())) {
-            ASSERT(!step.isZero());
-            const Decimal base = stepRange.stepBase();
-            Decimal newValue;
-            if (sign < 0)
-                newValue = base + ((current - base) / step).floor() * step;
-            else if (sign > 0)
-                newValue = base + ((current - base) / step).ceiling() * step;
-            else
-                newValue = current;
-
-            if (newValue < stepRange.minimum())
-                newValue = stepRange.minimum();
-            if (newValue > stepRange.maximum())
-                newValue = stepRange.maximum();
-
-            setValueAsDecimal(newValue, n == 1 || n == -1 ? DispatchInputAndChangeEvent : DispatchNoEvent, IGNORE_EXCEPTION);
-            if (n > 1)
-                applyStep(n - 1, AnyIsDefaultStep, DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
-            else if (n < -1)
-                applyStep(n + 1, AnyIsDefaultStep, DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
-        } else {
-            applyStep(n, AnyIsDefaultStep, DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
-        }
+        return;
     }
+    applyStep(current, n, AnyIsDefaultStep, DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
 }
 
 void InputType::countUsageIfVisible(UseCounter::Feature feature) const
@@ -993,4 +965,13 @@
     return stepBase;
 }
 
+StepRange InputType::createStepRange(AnyStepHandling anyStepHandling, const Decimal& stepBaseDefault, const Decimal& minimumDefault, const Decimal& maximumDefault, const StepRange::StepDescription& stepDescription) const
+{
+    const Decimal stepBase = findStepBase(stepBaseDefault);
+    const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), minimumDefault);
+    const Decimal maximum = parseToNumber(element().fastGetAttribute(maxAttr), maximumDefault);
+    const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
+    return StepRange(stepBase, minimum, maximum, step, stepDescription);
+}
+
 } // namespace WebCore
diff --git a/Source/core/html/forms/InputType.h b/Source/core/html/forms/InputType.h
index ad43aef..1e83ecd 100644
--- a/Source/core/html/forms/InputType.h
+++ b/Source/core/html/forms/InputType.h
@@ -92,7 +92,6 @@
     virtual bool isRadioButton() const;
     virtual bool isRangeControl() const;
     virtual bool isSearchField() const;
-    virtual bool isSubmitButton() const;
     virtual bool isTelephoneField() const;
     virtual bool isTextButton() const;
     virtual bool isTextField() const;
@@ -182,7 +181,6 @@
     virtual bool canSetValue(const String&);
     virtual bool storesValueSeparateFromAttribute();
     virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior);
-    virtual bool shouldResetOnDocumentActivation();
     virtual bool shouldRespectListAttribute();
     virtual bool shouldRespectSpeechAttribute();
     virtual bool isEnumeratable();
@@ -202,12 +200,6 @@
     // return NaN or Infinity only if defaultValue is NaN or Infinity.
     virtual Decimal parseToNumber(const String&, const Decimal& defaultValue) const;
 
-    // Parses the specified string for this InputType, and returns true if it
-    // is successfully parsed. An instance pointed by the DateComponents*
-    // parameter will have parsed values and be modified even if the parsing
-    // fails. The DateComponents* parameter may be 0.
-    virtual bool parseToDateComponents(const String&, DateComponents*) const;
-
     // Create a string representation of the specified Decimal value for the
     // input type. If NaN or Infinity is specified, this returns an empty
     // string. This should not be called for types without valueAsNumber.
@@ -240,9 +232,11 @@
     // Derive the step base, following the HTML algorithm steps.
     Decimal findStepBase(const Decimal&) const;
 
+    StepRange createStepRange(AnyStepHandling, const Decimal& stepBaseDefault, const Decimal& minimumDefault, const Decimal& maximumDefault, const StepRange::StepDescription&) const;
+
 private:
     // Helper for stepUp()/stepDown(). Adds step value * count to the current value.
-    void applyStep(int count, AnyStepHandling, TextFieldEventBehavior, ExceptionState&);
+    void applyStep(const Decimal&, int count, AnyStepHandling, TextFieldEventBehavior, ExceptionState&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/forms/InputTypeView.cpp b/Source/core/html/forms/InputTypeView.cpp
index d8c4939..1ae57e2 100644
--- a/Source/core/html/forms/InputTypeView.cpp
+++ b/Source/core/html/forms/InputTypeView.cpp
@@ -112,7 +112,7 @@
     return false;
 }
 
-void InputTypeView::handleFocusEvent(Element*, FocusDirection)
+void InputTypeView::handleFocusEvent(Element*, FocusType)
 {
 }
 
diff --git a/Source/core/html/forms/InputTypeView.h b/Source/core/html/forms/InputTypeView.h
index 1e4aec4..20b7210 100644
--- a/Source/core/html/forms/InputTypeView.h
+++ b/Source/core/html/forms/InputTypeView.h
@@ -33,7 +33,7 @@
 #ifndef InputTypeView_h
 #define InputTypeView_h
 
-#include "core/page/FocusDirection.h"
+#include "core/page/FocusType.h"
 #include "wtf/FastAllocBase.h"
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
@@ -87,7 +87,7 @@
     virtual bool shouldSubmitImplicitly(Event*);
     virtual PassRefPtr<HTMLFormElement> formForSubmission() const;
     virtual bool hasCustomFocusLogic() const;
-    virtual void handleFocusEvent(Element* oldFocusedElement, FocusDirection);
+    virtual void handleFocusEvent(Element* oldFocusedElement, FocusType);
     virtual void handleBlurEvent();
     virtual void subtreeHasChanged();
     virtual bool hasTouchEventHandler() const;
diff --git a/Source/core/html/forms/MonthInputType.cpp b/Source/core/html/forms/MonthInputType.cpp
index 5aed90b..647ac35 100644
--- a/Source/core/html/forms/MonthInputType.cpp
+++ b/Source/core/html/forms/MonthInputType.cpp
@@ -66,11 +66,6 @@
     return InputTypeNames::month;
 }
 
-DateComponents::Type MonthInputType::dateType() const
-{
-    return DateComponents::Month;
-}
-
 double MonthInputType::valueAsDate() const
 {
     DateComponents date;
@@ -108,11 +103,7 @@
 {
     DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (monthDefaultStep, monthDefaultStepBase, monthStepScaleFactor, StepRange::ParsedStepValueShouldBeInteger));
 
-    const Decimal stepBase = findStepBase(Decimal::fromDouble(monthDefaultStepBase));
-    const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumMonth()));
-    const Decimal maximum = parseToNumber(element().fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumMonth()));
-    const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
-    return StepRange(stepBase, minimum, maximum, step, stepDescription);
+    return InputType::createStepRange(anyStepHandling, Decimal::fromDouble(monthDefaultStepBase), Decimal::fromDouble(DateComponents::minimumMonth()), Decimal::fromDouble(DateComponents::maximumMonth()), stepDescription);
 }
 
 Decimal MonthInputType::parseToNumber(const String& src, const Decimal& defaultValue) const
diff --git a/Source/core/html/forms/MonthInputType.h b/Source/core/html/forms/MonthInputType.h
index c440d32..9baf95c 100644
--- a/Source/core/html/forms/MonthInputType.h
+++ b/Source/core/html/forms/MonthInputType.h
@@ -42,7 +42,7 @@
 typedef BaseChooserOnlyDateAndTimeInputType BaseMonthInputType;
 #endif
 
-class MonthInputType : public BaseMonthInputType {
+class MonthInputType FINAL : public BaseMonthInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
@@ -50,7 +50,6 @@
     MonthInputType(HTMLInputElement& element) : BaseMonthInputType(element) { }
     virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
-    virtual DateComponents::Type dateType() const OVERRIDE;
     virtual double valueAsDate() const OVERRIDE;
     virtual String serializeWithMilliseconds(double) const OVERRIDE;
     virtual Decimal parseToNumber(const String&, const Decimal&) const OVERRIDE;
@@ -62,9 +61,9 @@
 
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
     // BaseMultipleFieldsDateAndTimeInputType functions
-    virtual String formatDateTimeFieldsState(const DateTimeFieldsState&) const OVERRIDE FINAL;
-    virtual void setupLayoutParameters(DateTimeEditElement::LayoutParameters&, const DateComponents&) const OVERRIDE FINAL;
-    virtual bool isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const;
+    virtual String formatDateTimeFieldsState(const DateTimeFieldsState&) const OVERRIDE;
+    virtual void setupLayoutParameters(DateTimeEditElement::LayoutParameters&, const DateComponents&) const OVERRIDE;
+    virtual bool isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const OVERRIDE;
 #endif
 };
 
diff --git a/Source/core/html/forms/NumberInputType.cpp b/Source/core/html/forms/NumberInputType.cpp
index 2466ec4..53cc2b5 100644
--- a/Source/core/html/forms/NumberInputType.cpp
+++ b/Source/core/html/forms/NumberInputType.cpp
@@ -124,6 +124,7 @@
 void NumberInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
 {
     // FIXME: We should use numeric_limits<double>::max for number input type.
+    // (NOTE: the range check will not be true for NaN.)
     const double floatMax = numeric_limits<float>::max();
     if (newValue < -floatMax || newValue > floatMax) {
         exceptionState.throwDOMException(InvalidStateError, "The value provided (" + String::number(newValue) + ") is outside the range (" + String::number(-floatMax) + ", " + String::number(floatMax) + ").");
@@ -157,13 +158,10 @@
 StepRange NumberInputType::createStepRange(AnyStepHandling anyStepHandling) const
 {
     DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (numberDefaultStep, numberDefaultStepBase, numberStepScaleFactor));
-    const Decimal stepBase = findStepBase(numberDefaultStepBase);
+
     // FIXME: We should use numeric_limits<double>::max for number input type.
     const Decimal floatMax = Decimal::fromDouble(numeric_limits<float>::max());
-    const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), -floatMax);
-    const Decimal maximum = parseToNumber(element().fastGetAttribute(maxAttr), floatMax);
-    const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
-    return StepRange(stepBase, minimum, maximum, step, stepDescription);
+    return InputType::createStepRange(anyStepHandling, numberDefaultStepBase, -floatMax, floatMax, stepDescription);
 }
 
 bool NumberInputType::sizeShouldIncludeDecoration(int defaultSize, int& preferredSize) const
@@ -305,4 +303,9 @@
         element().renderer()->setNeedsLayoutAndPrefWidthsRecalc();
 }
 
+bool NumberInputType::supportsSelectionAPI() const
+{
+    return false;
+}
+
 } // namespace WebCore
diff --git a/Source/core/html/forms/NumberInputType.h b/Source/core/html/forms/NumberInputType.h
index ca7d971..cb60adc 100644
--- a/Source/core/html/forms/NumberInputType.h
+++ b/Source/core/html/forms/NumberInputType.h
@@ -37,7 +37,7 @@
 
 class ExceptionState;
 
-class NumberInputType : public TextFieldInputType {
+class NumberInputType FINAL : public TextFieldInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
@@ -70,6 +70,7 @@
     virtual bool isNumberField() const OVERRIDE;
     virtual void minOrMaxAttributeChanged() OVERRIDE;
     virtual void stepAttributeChanged() OVERRIDE;
+    virtual bool supportsSelectionAPI() const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/forms/PasswordInputType.cpp b/Source/core/html/forms/PasswordInputType.cpp
index 7350aa8..9c448f3 100644
--- a/Source/core/html/forms/PasswordInputType.cpp
+++ b/Source/core/html/forms/PasswordInputType.cpp
@@ -36,12 +36,12 @@
 #include "CSSValueKeywords.h"
 #include "InputTypeNames.h"
 #include "core/dom/shadow/ShadowRoot.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/forms/FormController.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
 #include "wtf/Assertions.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -63,15 +63,15 @@
 {
     if (isPasswordGenerationDecorationEnabled())
         return true;
-    if (Page* page = element().document().page())
-        return page->chrome().client().isPasswordGenerationEnabled();
+    if (FrameHost* host = element().document().frameHost())
+        return host->chrome().client().isPasswordGenerationEnabled();
     return false;
 }
 
 bool PasswordInputType::isPasswordGenerationDecorationEnabled() const
 {
-    if (Page* page = element().document().page())
-        return page->settings().passwordGenerationDecorationEnabled();
+    if (Settings* settings = element().document().settings())
+        return settings->passwordGenerationDecorationEnabled();
     return false;
 }
 
@@ -121,11 +121,6 @@
     return false;
 }
 
-bool PasswordInputType::shouldResetOnDocumentActivation()
-{
-    return true;
-}
-
 bool PasswordInputType::shouldRespectListAttribute()
 {
     return false;
diff --git a/Source/core/html/forms/PasswordInputType.h b/Source/core/html/forms/PasswordInputType.h
index 50f3669..ed9cdfa 100644
--- a/Source/core/html/forms/PasswordInputType.h
+++ b/Source/core/html/forms/PasswordInputType.h
@@ -50,7 +50,6 @@
     virtual FormControlState saveFormControlState() const OVERRIDE;
     virtual void restoreFormControlState(const FormControlState&) OVERRIDE;
     virtual bool shouldUseInputMethod() const OVERRIDE;
-    virtual bool shouldResetOnDocumentActivation() OVERRIDE;
     virtual bool shouldRespectListAttribute() OVERRIDE;
     virtual bool shouldRespectSpeechAttribute() OVERRIDE;
     virtual bool isPasswordField() const OVERRIDE;
diff --git a/Source/core/html/forms/CheckedRadioButtons.cpp b/Source/core/html/forms/RadioButtonGroupScope.cpp
similarity index 83%
rename from Source/core/html/forms/CheckedRadioButtons.cpp
rename to Source/core/html/forms/RadioButtonGroupScope.cpp
index 58850fb..f0913ab 100644
--- a/Source/core/html/forms/CheckedRadioButtons.cpp
+++ b/Source/core/html/forms/RadioButtonGroupScope.cpp
@@ -19,7 +19,7 @@
  */
 
 #include "config.h"
-#include "core/html/forms/CheckedRadioButtons.h"
+#include "core/html/forms/RadioButtonGroupScope.h"
 
 #include "core/html/HTMLInputElement.h"
 #include "wtf/HashSet.h"
@@ -176,15 +176,15 @@
 // Explicity define empty constructor and destructor in order to prevent the
 // compiler from generating them as inlines. So we don't need to to define
 // RadioButtonGroup in the header.
-CheckedRadioButtons::CheckedRadioButtons()
+RadioButtonGroupScope::RadioButtonGroupScope()
 {
 }
 
-CheckedRadioButtons::~CheckedRadioButtons()
+RadioButtonGroupScope::~RadioButtonGroupScope()
 {
 }
 
-void CheckedRadioButtons::addButton(HTMLInputElement* element)
+void RadioButtonGroupScope::addButton(HTMLInputElement* element)
 {
     ASSERT(element->isRadioButton());
     if (element->name().isEmpty())
@@ -193,13 +193,13 @@
     if (!m_nameToGroupMap)
         m_nameToGroupMap = adoptPtr(new NameToGroupMap);
 
-    OwnPtr<RadioButtonGroup>& group = m_nameToGroupMap->add(element->name().impl(), PassOwnPtr<RadioButtonGroup>()).iterator->value;
+    OwnPtr<RadioButtonGroup>& group = m_nameToGroupMap->add(element->name(), PassOwnPtr<RadioButtonGroup>()).storedValue->value;
     if (!group)
         group = RadioButtonGroup::create();
     group->add(element);
 }
 
-void CheckedRadioButtons::updateCheckedState(HTMLInputElement* element)
+void RadioButtonGroupScope::updateCheckedState(HTMLInputElement* element)
 {
     ASSERT(element->isRadioButton());
     if (element->name().isEmpty())
@@ -207,12 +207,12 @@
     ASSERT(m_nameToGroupMap);
     if (!m_nameToGroupMap)
         return;
-    RadioButtonGroup* group = m_nameToGroupMap->get(element->name().impl());
+    RadioButtonGroup* group = m_nameToGroupMap->get(element->name());
     ASSERT(group);
     group->updateCheckedState(element);
 }
 
-void CheckedRadioButtons::requiredAttributeChanged(HTMLInputElement* element)
+void RadioButtonGroupScope::requiredAttributeChanged(HTMLInputElement* element)
 {
     ASSERT(element->isRadioButton());
     if (element->name().isEmpty())
@@ -220,31 +220,31 @@
     ASSERT(m_nameToGroupMap);
     if (!m_nameToGroupMap)
         return;
-    RadioButtonGroup* group = m_nameToGroupMap->get(element->name().impl());
+    RadioButtonGroup* group = m_nameToGroupMap->get(element->name());
     ASSERT(group);
     group->requiredAttributeChanged(element);
 }
 
-HTMLInputElement* CheckedRadioButtons::checkedButtonForGroup(const AtomicString& name) const
+HTMLInputElement* RadioButtonGroupScope::checkedButtonForGroup(const AtomicString& name) const
 {
     if (!m_nameToGroupMap)
         return 0;
-    RadioButtonGroup* group = m_nameToGroupMap->get(name.impl());
+    RadioButtonGroup* group = m_nameToGroupMap->get(name);
     return group ? group->checkedButton() : 0;
 }
 
-bool CheckedRadioButtons::isInRequiredGroup(HTMLInputElement* element) const
+bool RadioButtonGroupScope::isInRequiredGroup(HTMLInputElement* element) const
 {
     ASSERT(element->isRadioButton());
     if (element->name().isEmpty())
         return false;
     if (!m_nameToGroupMap)
         return false;
-    RadioButtonGroup* group = m_nameToGroupMap->get(element->name().impl());
+    RadioButtonGroup* group = m_nameToGroupMap->get(element->name());
     return group && group->isRequired() && group->contains(element);
 }
 
-void CheckedRadioButtons::removeButton(HTMLInputElement* element)
+void RadioButtonGroupScope::removeButton(HTMLInputElement* element)
 {
     ASSERT(element->isRadioButton());
     if (element->name().isEmpty())
@@ -252,17 +252,15 @@
     if (!m_nameToGroupMap)
         return;
 
-    NameToGroupMap::iterator it = m_nameToGroupMap->find(element->name().impl());
-    if (it == m_nameToGroupMap->end())
+    RadioButtonGroup* group = m_nameToGroupMap->get(element->name());
+    if (!group)
         return;
-    it->value->remove(element);
-    if (it->value->isEmpty()) {
-        // FIXME: We may skip deallocating the empty RadioButtonGroup for
-        // performance improvement. If we do so, we need to change the key type
-        // of m_nameToGroupMap from StringImpl* to AtomicString.
-        m_nameToGroupMap->remove(it);
-        if (m_nameToGroupMap->isEmpty())
-            m_nameToGroupMap.clear();
+    group->remove(element);
+    if (group->isEmpty()) {
+        // We don't remove an empty RadioButtonGroup from m_nameToGroupMap for
+        // better performance.
+        ASSERT(!group->isRequired());
+        ASSERT_WITH_SECURITY_IMPLICATION(!group->checkedButton());
     }
 }
 
diff --git a/Source/core/html/forms/CheckedRadioButtons.h b/Source/core/html/forms/RadioButtonGroupScope.h
similarity index 78%
rename from Source/core/html/forms/CheckedRadioButtons.h
rename to Source/core/html/forms/RadioButtonGroupScope.h
index 6a1585b..cd440b6 100644
--- a/Source/core/html/forms/CheckedRadioButtons.h
+++ b/Source/core/html/forms/RadioButtonGroupScope.h
@@ -18,8 +18,8 @@
  *
  */
 
-#ifndef CheckedRadioButtons_h
-#define CheckedRadioButtons_h
+#ifndef RadioButtonGroupScope_h
+#define RadioButtonGroupScope_h
 
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
@@ -31,12 +31,10 @@
 class HTMLInputElement;
 class RadioButtonGroup;
 
-// FIXME: Rename the class. The class was a simple map from a name to a checked
-// radio button. It manages RadioButtonGroup objects now.
-class CheckedRadioButtons {
+class RadioButtonGroupScope {
 public:
-    CheckedRadioButtons();
-    ~CheckedRadioButtons();
+    RadioButtonGroupScope();
+    ~RadioButtonGroupScope();
     void addButton(HTMLInputElement*);
     void updateCheckedState(HTMLInputElement*);
     void requiredAttributeChanged(HTMLInputElement*);
@@ -45,10 +43,10 @@
     bool isInRequiredGroup(HTMLInputElement*) const;
 
 private:
-    typedef HashMap<StringImpl*, OwnPtr<RadioButtonGroup> > NameToGroupMap;
+    typedef HashMap<AtomicString, OwnPtr<RadioButtonGroup>, CaseFoldingHash> NameToGroupMap;
     OwnPtr<NameToGroupMap> m_nameToGroupMap;
 };
 
 } // namespace WebCore
 
-#endif // CheckedRadioButtons_h
+#endif // RadioButtonGroupScope_h
diff --git a/Source/core/html/forms/RadioInputType.h b/Source/core/html/forms/RadioInputType.h
index 09788e2..14a1386 100644
--- a/Source/core/html/forms/RadioInputType.h
+++ b/Source/core/html/forms/RadioInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class RadioInputType : public BaseCheckableInputType {
+class RadioInputType FINAL : public BaseCheckableInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/RangeInputType.cpp b/Source/core/html/forms/RangeInputType.cpp
index 561a650..55a9915 100644
--- a/Source/core/html/forms/RangeInputType.cpp
+++ b/Source/core/html/forms/RangeInputType.cpp
@@ -105,9 +105,9 @@
     return parseToDoubleForNumberType(element().value());
 }
 
-void RangeInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState&) const
+void RangeInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
 {
-    element().setValue(serialize(newValue), eventBehavior);
+    setValueAsDecimal(Decimal::fromDouble(newValue), eventBehavior, exceptionState);
 }
 
 bool RangeInputType::typeMismatchFor(const String& value) const
@@ -124,17 +124,18 @@
 {
     DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (rangeDefaultStep, rangeDefaultStepBase, rangeStepScaleFactor));
 
+    const Decimal stepBase = findStepBase(rangeDefaultStepBase);
     const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), rangeDefaultMinimum);
     const Decimal maximum = ensureMaximum(parseToNumber(element().fastGetAttribute(maxAttr), rangeDefaultMaximum), minimum, rangeDefaultMaximum);
 
     const AtomicString& precisionValue = element().fastGetAttribute(precisionAttr);
     if (!precisionValue.isNull()) {
         const Decimal step = equalIgnoringCase(precisionValue, "float") ? Decimal::nan() : 1;
-        return StepRange(minimum, minimum, maximum, step, stepDescription);
+        return StepRange(stepBase, minimum, maximum, step, stepDescription);
     }
 
     const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
-    return StepRange(minimum, minimum, maximum, step, stepDescription);
+    return StepRange(stepBase, minimum, maximum, step, stepDescription);
 }
 
 bool RangeInputType::isSteppable() const
@@ -246,7 +247,7 @@
 
     Document& document = element().document();
     RefPtr<HTMLDivElement> track = HTMLDivElement::create(document);
-    track->setPseudo(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
+    track->setShadowPseudoId(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
     track->setAttribute(idAttr, ShadowElementNames::sliderTrack());
     track->appendChild(SliderThumbElement::create(document));
     RefPtr<HTMLElement> container = SliderContainerElement::create(document);
@@ -355,10 +356,10 @@
     RefPtr<HTMLCollection> options = dataList->options();
     m_tickMarkValues.reserveCapacity(options->length());
     for (unsigned i = 0; i < options->length(); ++i) {
-        Node* node = options->item(i);
-        HTMLOptionElement* optionElement = toHTMLOptionElement(node);
+        Element* element = options->item(i);
+        HTMLOptionElement* optionElement = toHTMLOptionElement(element);
         String optionValue = optionElement->value();
-        if (!element().isValidValue(optionValue))
+        if (!this->element().isValidValue(optionValue))
             continue;
         m_tickMarkValues.append(parseToNumber(optionValue, Decimal::nan()));
     }
diff --git a/Source/core/html/forms/RangeInputType.h b/Source/core/html/forms/RangeInputType.h
index cb10f78..498e129 100644
--- a/Source/core/html/forms/RangeInputType.h
+++ b/Source/core/html/forms/RangeInputType.h
@@ -38,7 +38,7 @@
 class ExceptionState;
 class SliderThumbElement;
 
-class RangeInputType : public InputType {
+class RangeInputType FINAL : public InputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
@@ -48,7 +48,7 @@
     virtual bool isRangeControl() const OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual double valueAsDouble() const OVERRIDE;
-    virtual void setValueAsDecimal(const Decimal&, TextFieldEventBehavior, ExceptionState&) const OVERRIDE;
+    virtual void setValueAsDouble(double, TextFieldEventBehavior, ExceptionState&) const OVERRIDE;
     virtual bool typeMismatchFor(const String&) const OVERRIDE;
     virtual bool supportsRequired() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
diff --git a/Source/core/html/forms/ResetInputType.h b/Source/core/html/forms/ResetInputType.h
index 8837400..1e5c0d0 100644
--- a/Source/core/html/forms/ResetInputType.h
+++ b/Source/core/html/forms/ResetInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class ResetInputType : public BaseButtonInputType {
+class ResetInputType FINAL : public BaseButtonInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/SearchInputType.h b/Source/core/html/forms/SearchInputType.h
index d13c0f9..2bcf4c5 100644
--- a/Source/core/html/forms/SearchInputType.h
+++ b/Source/core/html/forms/SearchInputType.h
@@ -39,7 +39,7 @@
 class SearchFieldCancelButtonElement;
 class SearchFieldDecorationElement;
 
-class SearchInputType : public BaseTextInputType {
+class SearchInputType FINAL : public BaseTextInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/StepRange.cpp b/Source/core/html/forms/StepRange.cpp
index 0e10a5f..62a3afa 100644
--- a/Source/core/html/forms/StepRange.cpp
+++ b/Source/core/html/forms/StepRange.cpp
@@ -87,9 +87,9 @@
     const Decimal inRangeValue = max(m_minimum, min(value, m_maximum));
     if (!m_hasStep)
         return inRangeValue;
-    // Rounds inRangeValue to minimum + N * step.
-    const Decimal roundedValue = roundByStep(inRangeValue, m_minimum);
-    const Decimal clampedValue = roundedValue > m_maximum ? roundedValue - m_step : roundedValue;
+    // Rounds inRangeValue to stepBase + N * step.
+    const Decimal roundedValue = roundByStep(inRangeValue, m_stepBase);
+    const Decimal clampedValue = roundedValue > m_maximum ? roundedValue - m_step : (roundedValue < m_minimum ? roundedValue + m_step : roundedValue);
     ASSERT(clampedValue >= m_minimum);
     ASSERT(clampedValue <= m_maximum);
     return clampedValue;
@@ -161,7 +161,7 @@
     // ... that number subtracted from the step base is not an integral multiple
     // of the allowed value step, the element is suffering from a step mismatch.
     const Decimal remainder = (value - m_step * (value / m_step).round()).abs();
-    // Accepts erros in lower fractional part which IEEE 754 single-precision
+    // Accepts errors in lower fractional part which IEEE 754 single-precision
     // can't represent.
     const Decimal computedAcceptableError = acceptableError();
     return computedAcceptableError < remainder && remainder < (m_step - computedAcceptableError);
diff --git a/Source/core/html/forms/StepRange.h b/Source/core/html/forms/StepRange.h
index a31e264..f2fdbb2 100644
--- a/Source/core/html/forms/StepRange.h
+++ b/Source/core/html/forms/StepRange.h
@@ -71,7 +71,6 @@
     StepRange();
     StepRange(const StepRange&);
     StepRange(const Decimal& stepBase, const Decimal& minimum, const Decimal& maximum, const Decimal& step, const StepDescription&);
-    Decimal acceptableError() const;
     Decimal alignValueForStep(const Decimal& currentValue, const Decimal& newValue) const;
     Decimal clampValue(const Decimal& value) const;
     bool hasStep() const { return m_hasStep; }
@@ -80,7 +79,6 @@
     static Decimal parseStep(AnyStepHandling, const StepDescription&, const String&);
     Decimal step() const { return m_step; }
     Decimal stepBase() const { return m_stepBase; }
-    int stepScaleFactor() const { return m_stepDescription.stepScaleFactor; }
     bool stepMismatch(const Decimal&) const;
 
     // Clamp the middle value according to the step
@@ -106,6 +104,7 @@
 
 private:
     StepRange& operator =(const StepRange&);
+    Decimal acceptableError() const;
     Decimal roundByStep(const Decimal& value, const Decimal& base) const;
 
     const Decimal m_maximum; // maximum must be >= minimum.
diff --git a/Source/core/html/forms/SubmitInputType.cpp b/Source/core/html/forms/SubmitInputType.cpp
index 3b25b46..e89d809 100644
--- a/Source/core/html/forms/SubmitInputType.cpp
+++ b/Source/core/html/forms/SubmitInputType.cpp
@@ -86,11 +86,6 @@
     return locale().queryString(blink::WebLocalizedString::SubmitButtonDefaultLabel);
 }
 
-bool SubmitInputType::isSubmitButton() const
-{
-    return true;
-}
-
 bool SubmitInputType::isTextButton() const
 {
     return true;
diff --git a/Source/core/html/forms/SubmitInputType.h b/Source/core/html/forms/SubmitInputType.h
index ea88704..77d86ca 100644
--- a/Source/core/html/forms/SubmitInputType.h
+++ b/Source/core/html/forms/SubmitInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class SubmitInputType : public BaseButtonInputType {
+class SubmitInputType FINAL : public BaseButtonInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
@@ -47,7 +47,6 @@
     virtual void handleDOMActivateEvent(Event*) OVERRIDE;
     virtual bool canBeSuccessfulSubmitButton() OVERRIDE;
     virtual String defaultValue() const OVERRIDE;
-    virtual bool isSubmitButton() const OVERRIDE;
     virtual bool isTextButton() const OVERRIDE;
 };
 
diff --git a/Source/core/html/forms/TelephoneInputType.h b/Source/core/html/forms/TelephoneInputType.h
index d636ee2..8ec46d7 100644
--- a/Source/core/html/forms/TelephoneInputType.h
+++ b/Source/core/html/forms/TelephoneInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class TelephoneInputType : public BaseTextInputType {
+class TelephoneInputType FINAL : public BaseTextInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/TextFieldInputType.cpp b/Source/core/html/forms/TextFieldInputType.cpp
index f7e3a4d..c89f07c 100644
--- a/Source/core/html/forms/TextFieldInputType.cpp
+++ b/Source/core/html/forms/TextFieldInputType.cpp
@@ -34,22 +34,22 @@
 
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/events/BeforeTextInsertedEvent.h"
-#include "core/events/KeyboardEvent.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/events/TextEvent.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/TextIterator.h"
+#include "core/events/BeforeTextInsertedEvent.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/TextEvent.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
 #include "core/html/FormDataList.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/TextControlInnerElements.h"
-#include "core/frame/Frame.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/rendering/RenderDetailsMarker.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderTextControlSingleLine.h"
 #include "core/rendering/RenderTheme.h"
@@ -59,6 +59,55 @@
 
 using namespace HTMLNames;
 
+class DataListIndicatorElement FINAL : public HTMLDivElement {
+private:
+    inline DataListIndicatorElement(Document& document) : HTMLDivElement(document) { }
+    inline HTMLInputElement* hostInput() const { return toHTMLInputElement(shadowHost()); }
+
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE
+    {
+        return new RenderDetailsMarker(this);
+    }
+
+    virtual void* preDispatchEventHandler(Event* event) OVERRIDE
+    {
+        // Chromium opens autofill popup in a mousedown event listener
+        // associated to the document. We don't want to open it in this case
+        // because we opens a datalist chooser later.
+        // FIXME: We should dispatch mousedown events even in such case.
+        if (event->type() == EventTypeNames::mousedown)
+            event->stopPropagation();
+        return 0;
+    }
+
+    virtual void defaultEventHandler(Event* event) OVERRIDE
+    {
+        ASSERT(document().isActive());
+        if (event->type() != EventTypeNames::click)
+            return;
+        HTMLInputElement* host = hostInput();
+        if (host && !host->isDisabledOrReadOnly()) {
+            document().frameHost()->chrome().openTextDataListChooser(*host);
+            event->setDefaultHandled();
+        }
+    }
+
+    virtual bool willRespondToMouseClickEvents() OVERRIDE
+    {
+        return hostInput() && !hostInput()->isDisabledOrReadOnly() && document().isActive();
+    }
+
+public:
+    static PassRefPtr<DataListIndicatorElement> create(Document& document)
+    {
+        RefPtr<DataListIndicatorElement> element = adoptRef(new DataListIndicatorElement(document));
+        element->setShadowPseudoId(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
+        element->setAttribute(idAttr, ShadowElementNames::pickerIndicator());
+        return element.release();
+    }
+
+};
+
 TextFieldInputType::TextFieldInputType(HTMLInputElement& element)
     : InputType(element)
 {
@@ -85,18 +134,9 @@
     return true;
 }
 
-static inline bool shouldIgnoreRequiredAttribute(const HTMLInputElement& input)
-{
-    if (!input.document().settings() || !input.document().settings()->needsSiteSpecificQuirks())
-        return false;
-    if (!equalIgnoringCase(input.document().url().host(), "egov.uscis.gov"))
-        return false;
-    return input.fastGetAttribute(requiredAttr) == "no";
-}
-
 bool TextFieldInputType::valueMissing(const String& value) const
 {
-    return !shouldIgnoreRequiredAttribute(element()) && element().isRequired() && value.isEmpty();
+    return element().isRequired() && value.isEmpty();
 }
 
 bool TextFieldInputType::canSetSuggestedValue()
@@ -204,9 +244,9 @@
     }
 }
 
-void TextFieldInputType::handleFocusEvent(Element* oldFocusedNode, FocusDirection focusDirection)
+void TextFieldInputType::handleFocusEvent(Element* oldFocusedNode, FocusType focusType)
 {
-    InputType::handleFocusEvent(oldFocusedNode, focusDirection);
+    InputType::handleFocusEvent(oldFocusedNode, focusType);
     element().beginEditing();
 }
 
@@ -248,7 +288,8 @@
 
     Document& document = element().document();
     bool shouldHaveSpinButton = this->shouldHaveSpinButton();
-    bool createsContainer = shouldHaveSpinButton || needsContainer();
+    bool shouldHaveDataListIndicator = element().hasValidDataListOptions();
+    bool createsContainer = shouldHaveSpinButton || shouldHaveDataListIndicator || needsContainer();
 
     RefPtr<TextControlInnerTextElement> innerEditor = TextControlInnerTextElement::create(document);
     if (!createsContainer) {
@@ -257,7 +298,7 @@
     }
 
     RefPtr<TextControlInnerContainer> container = TextControlInnerContainer::create(document);
-    container->setPseudo(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
+    container->setShadowPseudoId(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
     shadowRoot->appendChild(container);
 
     RefPtr<EditingViewPortElement> editingViewPort = EditingViewPortElement::create(document);
@@ -269,8 +310,15 @@
         container->appendChild(InputFieldSpeechButtonElement::create(document));
 #endif
 
+    if (shouldHaveDataListIndicator)
+        container->appendChild(DataListIndicatorElement::create(document));
+    // FIXME: Because of a special handling for a spin button in
+    // RenderTextControlSingleLine, we need to put it to the last position. It's
+    // inconsistent with multiple-fields date/time types.
     if (shouldHaveSpinButton)
         container->appendChild(SpinButtonElement::create(document, *this));
+
+    // See listAttributeTargetChanged too.
 }
 
 Element* TextFieldInputType::containerElement() const
@@ -285,6 +333,35 @@
         spinButton->removeSpinButtonOwner();
 }
 
+void TextFieldInputType::listAttributeTargetChanged()
+{
+    Element* picker = element().userAgentShadowRoot()->getElementById(ShadowElementNames::pickerIndicator());
+    bool didHavePickerIndicator = picker;
+    bool willHavePickerIndicator = element().hasValidDataListOptions();
+    if (didHavePickerIndicator == willHavePickerIndicator)
+        return;
+    if (willHavePickerIndicator) {
+        Document& document = element().document();
+        if (Element* container = containerElement()) {
+            container->insertBefore(DataListIndicatorElement::create(document), spinButtonElement());
+        } else {
+            // FIXME: The following code is similar to createShadowSubtree(),
+            // but they are different. We should simplify the code by making
+            // containerElement mandatory.
+            RefPtr<Element> rpContainer = TextControlInnerContainer::create(document);
+            rpContainer->setShadowPseudoId(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
+            RefPtr<Element> innerEditor = element().innerTextElement();
+            innerEditor->parentNode()->replaceChild(rpContainer.get(), innerEditor.get());
+            RefPtr<Element> editingViewPort = EditingViewPortElement::create(document);
+            editingViewPort->appendChild(innerEditor.release());
+            rpContainer->appendChild(editingViewPort.release());
+            rpContainer->appendChild(DataListIndicatorElement::create(document));
+        }
+    } else {
+        picker->remove(ASSERT_NO_EXCEPTION);
+    }
+}
+
 void TextFieldInputType::attributeChanged()
 {
     // FIXME: Updating on any attribute update should be unnecessary. We should
@@ -397,7 +474,7 @@
     if (!placeholder) {
         RefPtr<HTMLElement> newElement = HTMLDivElement::create(element().document());
         placeholder = newElement.get();
-        placeholder->setPseudo(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+        placeholder->setShadowPseudoId(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
         placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
         Element* container = containerElement();
         Node* previous = container ? container : element().innerTextElement();
@@ -435,7 +512,7 @@
     element().setValueFromRenderer(sanitizeValue(convertFromVisibleValue(element().innerTextValue())));
     element().updatePlaceholderVisibility(false);
     // Recalc for :invalid change.
-    element().setNeedsStyleRecalc();
+    element().setNeedsStyleRecalc(SubtreeStyleChange);
 
     didSetValueByUserEdit(wasChanged ? ValueChangeStateChanged : ValueChangeStateNone);
 }
diff --git a/Source/core/html/forms/TextFieldInputType.h b/Source/core/html/forms/TextFieldInputType.h
index a124ea1..2ff1362 100644
--- a/Source/core/html/forms/TextFieldInputType.h
+++ b/Source/core/html/forms/TextFieldInputType.h
@@ -50,15 +50,15 @@
 
 protected:
     virtual bool needsContainer() const;
-    virtual bool shouldHaveSpinButton() const;
+    bool shouldHaveSpinButton() const;
     virtual void createShadowSubtree() OVERRIDE;
     virtual void destroyShadowSubtree() OVERRIDE;
     virtual void attributeChanged() OVERRIDE;
     virtual void disabledAttributeChanged() OVERRIDE;
     virtual void readonlyAttributeChanged() OVERRIDE;
     virtual bool supportsReadOnly() const OVERRIDE;
-    virtual void handleFocusEvent(Element* oldFocusedNode, FocusDirection) OVERRIDE;
-    virtual void handleBlurEvent() OVERRIDE;
+    virtual void handleFocusEvent(Element* oldFocusedNode, FocusType) OVERRIDE FINAL;
+    virtual void handleBlurEvent() OVERRIDE FINAL;
     virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
     virtual void updateView() OVERRIDE;
 
@@ -72,26 +72,27 @@
     Element* containerElement() const;
 
 private:
-    virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
-    virtual bool isTextField() const OVERRIDE;
+    virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE FINAL;
+    virtual bool isTextField() const OVERRIDE FINAL;
     virtual bool valueMissing(const String&) const OVERRIDE;
     virtual void handleBeforeTextInsertedEvent(BeforeTextInsertedEvent*) OVERRIDE;
-    virtual void forwardEvent(Event*) OVERRIDE;
-    virtual bool shouldSubmitImplicitly(Event*) OVERRIDE;
+    virtual void forwardEvent(Event*) OVERRIDE FINAL;
+    virtual bool shouldSubmitImplicitly(Event*) OVERRIDE FINAL;
     virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual bool shouldUseInputMethod() const OVERRIDE;
     virtual String sanitizeValue(const String&) const OVERRIDE;
     virtual bool shouldRespectListAttribute() OVERRIDE;
-    virtual void updatePlaceholderText() OVERRIDE;
+    virtual void listAttributeTargetChanged() OVERRIDE;
+    virtual void updatePlaceholderText() OVERRIDE FINAL;
     virtual bool appendFormData(FormDataList&, bool multipart) const OVERRIDE;
-    virtual void subtreeHasChanged() OVERRIDE;
+    virtual void subtreeHasChanged() OVERRIDE FINAL;
 
     // SpinButtonElement::SpinButtonOwner functions.
-    virtual void focusAndSelectSpinButtonOwner() OVERRIDE;
-    virtual bool shouldSpinButtonRespondToMouseEvents() OVERRIDE;
-    virtual bool shouldSpinButtonRespondToWheelEvents() OVERRIDE;
-    virtual void spinButtonStepDown() OVERRIDE;
-    virtual void spinButtonStepUp() OVERRIDE;
+    virtual void focusAndSelectSpinButtonOwner() OVERRIDE FINAL;
+    virtual bool shouldSpinButtonRespondToMouseEvents() OVERRIDE FINAL;
+    virtual bool shouldSpinButtonRespondToWheelEvents() OVERRIDE FINAL;
+    virtual void spinButtonStepDown() OVERRIDE FINAL;
+    virtual void spinButtonStepUp() OVERRIDE FINAL;
 
     SpinButtonElement* spinButtonElement() const;
 };
diff --git a/Source/core/html/forms/TextInputType.h b/Source/core/html/forms/TextInputType.h
index 8fb1e8c..d74cdbc 100644
--- a/Source/core/html/forms/TextInputType.h
+++ b/Source/core/html/forms/TextInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class TextInputType : public BaseTextInputType {
+class TextInputType FINAL : public BaseTextInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/TimeInputType.cpp b/Source/core/html/forms/TimeInputType.cpp
index c3eccd7..c8ab269 100644
--- a/Source/core/html/forms/TimeInputType.cpp
+++ b/Source/core/html/forms/TimeInputType.cpp
@@ -71,11 +71,6 @@
     return InputTypeNames::time;
 }
 
-DateComponents::Type TimeInputType::dateType() const
-{
-    return DateComponents::Time;
-}
-
 Decimal TimeInputType::defaultValueForStepUp() const
 {
     double current = currentTimeMS();
@@ -95,11 +90,7 @@
 {
     DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (timeDefaultStep, timeDefaultStepBase, timeStepScaleFactor, StepRange::ScaledStepValueShouldBeInteger));
 
-    const Decimal stepBase = findStepBase(0);
-    const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumTime()));
-    const Decimal maximum = parseToNumber(element().fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumTime()));
-    const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
-    return StepRange(stepBase, minimum, maximum, step, stepDescription);
+    return InputType::createStepRange(anyStepHandling, timeDefaultStepBase, Decimal::fromDouble(DateComponents::minimumTime()), Decimal::fromDouble(DateComponents::maximumTime()), stepDescription);
 }
 
 bool TimeInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
diff --git a/Source/core/html/forms/TimeInputType.h b/Source/core/html/forms/TimeInputType.h
index 57af1f1..99de035 100644
--- a/Source/core/html/forms/TimeInputType.h
+++ b/Source/core/html/forms/TimeInputType.h
@@ -42,7 +42,7 @@
 typedef BaseChooserOnlyDateAndTimeInputType BaseTimeInputType;
 #endif
 
-class TimeInputType : public BaseTimeInputType {
+class TimeInputType FINAL : public BaseTimeInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
@@ -50,7 +50,6 @@
     TimeInputType(HTMLInputElement&);
     virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
-    virtual DateComponents::Type dateType() const OVERRIDE;
     virtual Decimal defaultValueForStepUp() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
     virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
@@ -60,9 +59,9 @@
     virtual String localizeValue(const String&) const OVERRIDE;
 
     // BaseMultipleFieldsDateAndTimeInputType functions
-    virtual String formatDateTimeFieldsState(const DateTimeFieldsState&) const OVERRIDE FINAL;
-    virtual void setupLayoutParameters(DateTimeEditElement::LayoutParameters&, const DateComponents&) const OVERRIDE FINAL;
-    virtual bool isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const;
+    virtual String formatDateTimeFieldsState(const DateTimeFieldsState&) const OVERRIDE;
+    virtual void setupLayoutParameters(DateTimeEditElement::LayoutParameters&, const DateComponents&) const OVERRIDE;
+    virtual bool isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const OVERRIDE;
 #endif
 };
 
diff --git a/Source/core/html/forms/TypeAhead.cpp b/Source/core/html/forms/TypeAhead.cpp
index e9a0052..673b889 100644
--- a/Source/core/html/forms/TypeAhead.cpp
+++ b/Source/core/html/forms/TypeAhead.cpp
@@ -50,7 +50,7 @@
 
     unsigned i;
     for (i = 0; i < length; ++i) {
-        if (string[i] != noBreakSpace && (string[i] <= 0x7F ? !isASCIISpace(string[i]) : (direction(string[i]) != WhiteSpaceNeutral)))
+        if (string[i] != noBreakSpace && !isSpaceOrNewline(string[i]))
             break;
     }
 
diff --git a/Source/core/html/forms/URLInputType.h b/Source/core/html/forms/URLInputType.h
index 98f53f2..9ec1e30 100644
--- a/Source/core/html/forms/URLInputType.h
+++ b/Source/core/html/forms/URLInputType.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class URLInputType : public BaseTextInputType {
+class URLInputType FINAL : public BaseTextInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
diff --git a/Source/core/html/forms/WeekInputType.cpp b/Source/core/html/forms/WeekInputType.cpp
index 62acb74..419b160 100644
--- a/Source/core/html/forms/WeekInputType.cpp
+++ b/Source/core/html/forms/WeekInputType.cpp
@@ -63,20 +63,11 @@
     return InputTypeNames::week;
 }
 
-DateComponents::Type WeekInputType::dateType() const
-{
-    return DateComponents::Week;
-}
-
 StepRange WeekInputType::createStepRange(AnyStepHandling anyStepHandling) const
 {
     DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (weekDefaultStep, weekDefaultStepBase, weekStepScaleFactor, StepRange::ParsedStepValueShouldBeInteger));
 
-    const Decimal stepBase = findStepBase(weekDefaultStepBase);
-    const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumWeek()));
-    const Decimal maximum = parseToNumber(element().fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumWeek()));
-    const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
-    return StepRange(stepBase, minimum, maximum, step, stepDescription);
+    return InputType::createStepRange(anyStepHandling, weekDefaultStepBase, Decimal::fromDouble(DateComponents::minimumWeek()), Decimal::fromDouble(DateComponents::maximumWeek()), stepDescription);
 }
 
 bool WeekInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
diff --git a/Source/core/html/forms/WeekInputType.h b/Source/core/html/forms/WeekInputType.h
index 89130b0..7254f12 100644
--- a/Source/core/html/forms/WeekInputType.h
+++ b/Source/core/html/forms/WeekInputType.h
@@ -42,7 +42,7 @@
 typedef BaseChooserOnlyDateAndTimeInputType BaseWeekInputType;
 #endif
 
-class WeekInputType : public BaseWeekInputType {
+class WeekInputType FINAL : public BaseWeekInputType {
 public:
     static PassRefPtr<InputType> create(HTMLInputElement&);
 
@@ -50,7 +50,6 @@
     WeekInputType(HTMLInputElement& element) : BaseWeekInputType(element) { }
     virtual void countUsage() OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
-    virtual DateComponents::Type dateType() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
     virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
     virtual bool setMillisecondToDateComponents(double, DateComponents*) const OVERRIDE;
@@ -58,9 +57,9 @@
 
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
     // BaseMultipleFieldsDateAndTimeInputType functions
-    virtual String formatDateTimeFieldsState(const DateTimeFieldsState&) const OVERRIDE FINAL;
-    virtual void setupLayoutParameters(DateTimeEditElement::LayoutParameters&, const DateComponents&) const OVERRIDE FINAL;
-    virtual bool isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const;
+    virtual String formatDateTimeFieldsState(const DateTimeFieldsState&) const OVERRIDE;
+    virtual void setupLayoutParameters(DateTimeEditElement::LayoutParameters&, const DateComponents&) const OVERRIDE;
+    virtual bool isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const OVERRIDE;
 #endif
 };
 
diff --git a/Source/core/html/ime/Composition.cpp b/Source/core/html/ime/Composition.cpp
deleted file mode 100644
index 17250b3..0000000
--- a/Source/core/html/ime/Composition.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/html/ime/Composition.h"
-
-#include "core/html/ime/InputMethodContext.h"
-
-namespace WebCore {
-
-Composition::~Composition()
-{
-}
-
-void Composition::ref()
-{
-    m_inputMethodContext->ref();
-}
-
-void Composition::deref()
-{
-    m_inputMethodContext->deref();
-}
-
-PassOwnPtr<Composition> Composition::create(InputMethodContext* context)
-{
-    return adoptPtr(new Composition(context));
-}
-
-Composition::Composition(InputMethodContext* context)
-    : m_inputMethodContext(context)
-{
-    ScriptWrappable::init(this);
-}
-
-String Composition::text() const
-{
-    return m_inputMethodContext->compositionText();
-}
-
-int Composition::selectionStart() const
-{
-    return m_inputMethodContext->selectionStart();
-}
-
-int Composition::selectionEnd() const
-{
-    return m_inputMethodContext->selectionEnd();
-}
-
-const Vector<unsigned>& Composition::getSegments() const
-{
-    return m_inputMethodContext->segments();
-}
-
-} // namespace WebCore
diff --git a/Source/core/html/ime/InputMethodContext.cpp b/Source/core/html/ime/InputMethodContext.cpp
index ef02973..40f2aab 100644
--- a/Source/core/html/ime/InputMethodContext.cpp
+++ b/Source/core/html/ime/InputMethodContext.cpp
@@ -33,7 +33,6 @@
 
 #include "core/dom/Text.h"
 #include "core/editing/InputMethodController.h"
-#include "core/html/ime/Composition.h"
 #include "core/frame/Frame.h"
 
 namespace WebCore {
@@ -53,13 +52,6 @@
 {
 }
 
-Composition* InputMethodContext::composition()
-{
-    if (!m_composition)
-        m_composition = Composition::create(this);
-    return m_composition.get();
-}
-
 String InputMethodContext::locale() const
 {
     // FIXME: Implement this.
@@ -71,6 +63,20 @@
     return m_element;
 }
 
+unsigned InputMethodContext::compositionStartOffset()
+{
+    if (hasFocus())
+        return inputMethodController().compositionStart();
+    return 0;
+}
+
+unsigned InputMethodContext::compositionEndOffset()
+{
+    if (hasFocus())
+        return inputMethodController().compositionEnd();
+    return 0;
+}
+
 void InputMethodContext::confirmComposition()
 {
     if (hasFocus())
diff --git a/Source/core/html/ime/InputMethodContext.h b/Source/core/html/ime/InputMethodContext.h
index 851d80a..2aeea39 100644
--- a/Source/core/html/ime/InputMethodContext.h
+++ b/Source/core/html/ime/InputMethodContext.h
@@ -42,22 +42,22 @@
 
 namespace WebCore {
 
-class Composition;
 class ExecutionContext;
 class InputMethodController;
 class Node;
 
-class InputMethodContext : public ScriptWrappable, public EventTargetWithInlineData {
+class InputMethodContext FINAL : public ScriptWrappable, public EventTargetWithInlineData {
 public:
     static PassOwnPtr<InputMethodContext> create(HTMLElement*);
-    ~InputMethodContext();
+    virtual ~InputMethodContext();
 
     void ref() { m_element->ref(); }
     void deref() { m_element->deref(); }
 
-    Composition* composition();
     String locale() const;
     HTMLElement* target() const;
+    unsigned compositionStartOffset();
+    unsigned compositionEndOffset();
     void confirmComposition();
 
     String compositionText() const;
@@ -86,7 +86,6 @@
     virtual void derefEventTarget() OVERRIDE { deref(); }
 
     HTMLElement* m_element;
-    OwnPtr<Composition> m_composition;
     Vector<unsigned> m_segments;
 };
 
diff --git a/Source/core/html/ime/InputMethodContext.idl b/Source/core/html/ime/InputMethodContext.idl
index e8437a6..043feed 100644
--- a/Source/core/html/ime/InputMethodContext.idl
+++ b/Source/core/html/ime/InputMethodContext.idl
@@ -30,9 +30,11 @@
 
 // http://www.w3.org/TR/ime-api/
 interface InputMethodContext : EventTarget {
-    readonly attribute Composition composition;
     readonly attribute DOMString locale;
     readonly attribute HTMLElement target;
+    readonly attribute unsigned long compositionStartOffset;
+    readonly attribute unsigned long compositionEndOffset;
+
     void confirmComposition();
 
     attribute EventHandler oncandidatewindowshow;
diff --git a/Source/core/html/parser/AtomicHTMLToken.h b/Source/core/html/parser/AtomicHTMLToken.h
index 4bc8aa4..886fd54 100644
--- a/Source/core/html/parser/AtomicHTMLToken.h
+++ b/Source/core/html/parser/AtomicHTMLToken.h
@@ -150,10 +150,10 @@
             ASSERT_NOT_REACHED();
             break;
         case HTMLToken::DOCTYPE:
-            m_name = token.data().asString();
+            m_name = AtomicString(token.data());
             m_doctypeData = adoptPtr(new DoctypeData());
             m_doctypeData->m_hasPublicIdentifier = true;
-            append(m_doctypeData->m_publicIdentifier, token.publicIdentifier().asString());
+            append(m_doctypeData->m_publicIdentifier, token.publicIdentifier());
             m_doctypeData->m_hasSystemIdentifier = true;
             append(m_doctypeData->m_systemIdentifier, token.systemIdentifier());
             m_doctypeData->m_forceQuirks = token.doctypeForcesQuirks();
@@ -163,19 +163,19 @@
         case HTMLToken::StartTag:
             m_attributes.reserveInitialCapacity(token.attributes().size());
             for (Vector<CompactHTMLToken::Attribute>::const_iterator it = token.attributes().begin(); it != token.attributes().end(); ++it) {
-                QualifiedName name(nullAtom, it->name.asString(), nullAtom);
+                QualifiedName name(nullAtom, AtomicString(it->name), nullAtom);
                 // FIXME: This is N^2 for the number of attributes.
                 if (!findAttributeInVector(m_attributes, name))
-                    m_attributes.append(Attribute(name, it->value));
+                    m_attributes.append(Attribute(name, AtomicString(it->value)));
             }
             // Fall through!
         case HTMLToken::EndTag:
             m_selfClosing = token.selfClosing();
-            m_name = token.data().asString();
+            m_name = AtomicString(token.data());
             break;
         case HTMLToken::Character:
         case HTMLToken::Comment:
-            m_data = token.data().asString();
+            m_data = token.data();
             break;
         }
     }
diff --git a/Source/core/html/parser/BackgroundHTMLParser.cpp b/Source/core/html/parser/BackgroundHTMLParser.cpp
index b91dafd..77d1154 100644
--- a/Source/core/html/parser/BackgroundHTMLParser.cpp
+++ b/Source/core/html/parser/BackgroundHTMLParser.cpp
@@ -28,6 +28,7 @@
 
 #include "core/html/parser/HTMLDocumentParser.h"
 #include "core/html/parser/HTMLParserThread.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/html/parser/XSSAuditor.h"
 #include "wtf/MainThread.h"
 #include "wtf/text/TextPosition.h"
@@ -76,6 +77,12 @@
 
 #endif
 
+void BackgroundHTMLParser::start(PassRefPtr<WeakReference<BackgroundHTMLParser> > reference, PassOwnPtr<Configuration> config)
+{
+    new BackgroundHTMLParser(reference, config);
+    // Caller must free by calling stop().
+}
+
 BackgroundHTMLParser::BackgroundHTMLParser(PassRefPtr<WeakReference<BackgroundHTMLParser> > reference, PassOwnPtr<Configuration> config)
     : m_weakFactory(reference, this)
     , m_token(adoptPtr(new HTMLToken))
@@ -86,6 +93,11 @@
     , m_pendingTokens(adoptPtr(new CompactHTMLTokenStream))
     , m_xssAuditor(config->xssAuditor.release())
     , m_preloadScanner(config->preloadScanner.release())
+    , m_decoder(config->decoder.release())
+{
+}
+
+BackgroundHTMLParser::~BackgroundHTMLParser()
 {
 }
 
@@ -96,6 +108,38 @@
     pumpTokenizer();
 }
 
+void BackgroundHTMLParser::appendBytes(PassOwnPtr<Vector<char> > buffer)
+{
+    updateDocument(m_decoder->decode(buffer->data(), buffer->size()));
+}
+
+void BackgroundHTMLParser::setDecoder(PassOwnPtr<TextResourceDecoder> decoder)
+{
+    m_decoder = decoder;
+}
+
+void BackgroundHTMLParser::flush()
+{
+    updateDocument(m_decoder->flush());
+}
+
+void BackgroundHTMLParser::updateDocument(const String& decodedData)
+{
+    DocumentEncodingData encodingData(*m_decoder.get());
+
+    if (encodingData != m_lastSeenEncodingData) {
+        m_lastSeenEncodingData = encodingData;
+
+        m_xssAuditor->setEncoding(encodingData.encoding());
+        callOnMainThread(bind(&HTMLDocumentParser::didReceiveEncodingDataFromBackgroundParser, m_parser, encodingData));
+    }
+
+    if (decodedData.isEmpty())
+        return;
+
+    append(decodedData);
+}
+
 void BackgroundHTMLParser::resumeFrom(PassOwnPtr<Checkpoint> checkpoint)
 {
     m_parser = checkpoint->parser;
diff --git a/Source/core/html/parser/BackgroundHTMLParser.h b/Source/core/html/parser/BackgroundHTMLParser.h
index b9b5a51..f1a76fd 100644
--- a/Source/core/html/parser/BackgroundHTMLParser.h
+++ b/Source/core/html/parser/BackgroundHTMLParser.h
@@ -31,8 +31,6 @@
 #include "core/html/parser/HTMLParserOptions.h"
 #include "core/html/parser/HTMLPreloadScanner.h"
 #include "core/html/parser/HTMLSourceTracker.h"
-#include "core/html/parser/HTMLToken.h"
-#include "core/html/parser/HTMLTokenizer.h"
 #include "core/html/parser/HTMLTreeBuilderSimulator.h"
 #include "core/html/parser/XSSAuditorDelegate.h"
 #include "wtf/PassOwnPtr.h"
@@ -41,6 +39,7 @@
 namespace WebCore {
 
 class HTMLDocumentParser;
+class SharedBuffer;
 class XSSAuditor;
 
 class BackgroundHTMLParser {
@@ -51,13 +50,10 @@
         WeakPtr<HTMLDocumentParser> parser;
         OwnPtr<XSSAuditor> xssAuditor;
         OwnPtr<TokenPreloadScanner> preloadScanner;
+        OwnPtr<TextResourceDecoder> decoder;
     };
 
-    static void create(PassRefPtr<WeakReference<BackgroundHTMLParser> > reference, PassOwnPtr<Configuration> config)
-    {
-        new BackgroundHTMLParser(reference, config);
-        // Caller must free by calling stop().
-    }
+    static void start(PassRefPtr<WeakReference<BackgroundHTMLParser> >, PassOwnPtr<Configuration>);
 
     struct Checkpoint {
         WeakPtr<HTMLDocumentParser> parser;
@@ -69,7 +65,9 @@
         String unparsedInput;
     };
 
-    void append(const String&);
+    void appendBytes(PassOwnPtr<Vector<char> >);
+    void setDecoder(PassOwnPtr<TextResourceDecoder>);
+    void flush();
     void resumeFrom(PassOwnPtr<Checkpoint>);
     void startedChunkWithCheckpoint(HTMLInputCheckpoint);
     void finish();
@@ -79,10 +77,13 @@
 
 private:
     BackgroundHTMLParser(PassRefPtr<WeakReference<BackgroundHTMLParser> >, PassOwnPtr<Configuration>);
+    ~BackgroundHTMLParser();
 
+    void append(const String&);
     void markEndOfFile();
     void pumpTokenizer();
     void sendTokensToMainThread();
+    void updateDocument(const String& decodedData);
 
     WeakPtrFactory<BackgroundHTMLParser> m_weakFactory;
     BackgroundHTMLInputStream m_input;
@@ -99,6 +100,8 @@
 
     OwnPtr<XSSAuditor> m_xssAuditor;
     OwnPtr<TokenPreloadScanner> m_preloadScanner;
+    OwnPtr<TextResourceDecoder> m_decoder;
+    DocumentEncodingData m_lastSeenEncodingData;
 };
 
 }
diff --git a/Source/core/html/parser/CSSPreloadScanner.cpp b/Source/core/html/parser/CSSPreloadScanner.cpp
index b3f1454..b1eea27 100644
--- a/Source/core/html/parser/CSSPreloadScanner.cpp
+++ b/Source/core/html/parser/CSSPreloadScanner.cpp
@@ -29,7 +29,6 @@
 #include "core/html/parser/CSSPreloadScanner.h"
 
 #include "FetchInitiatorTypeNames.h"
-#include "core/html/parser/HTMLIdentifier.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "platform/text/SegmentedString.h"
 
@@ -66,16 +65,15 @@
     scanCommon(data.data(), data.data() + data.size(), source, requests);
 }
 
-void CSSPreloadScanner::scan(const HTMLIdentifier& identifier,  const SegmentedString& source, PreloadRequestStream& requests)
+void CSSPreloadScanner::scan(const String& tagName,  const SegmentedString& source, PreloadRequestStream& requests)
 {
-    const StringImpl* data = identifier.asStringImpl();
-    if (data->is8Bit()) {
-        const LChar* begin = data->characters8();
-        scanCommon(begin, begin + data->length(), source, requests);
+    if (tagName.is8Bit()) {
+        const LChar* begin = tagName.characters8();
+        scanCommon(begin, begin + tagName.length(), source, requests);
         return;
     }
-    const UChar* begin = data->characters16();
-    scanCommon(begin, begin + data->length(), source, requests);
+    const UChar* begin = tagName.characters16();
+    scanCommon(begin, begin + tagName.length(), source, requests);
 }
 
 inline void CSSPreloadScanner::tokenize(UChar c, const SegmentedString& source)
diff --git a/Source/core/html/parser/CSSPreloadScanner.h b/Source/core/html/parser/CSSPreloadScanner.h
index 07e3b17..8c32899 100644
--- a/Source/core/html/parser/CSSPreloadScanner.h
+++ b/Source/core/html/parser/CSSPreloadScanner.h
@@ -33,7 +33,6 @@
 
 namespace WebCore {
 
-class HTMLIdentifier;
 class SegmentedString;
 
 class CSSPreloadScanner {
@@ -45,7 +44,7 @@
     void reset();
 
     void scan(const HTMLToken::DataVector&, const SegmentedString&, PreloadRequestStream&);
-    void scan(const HTMLIdentifier&, const SegmentedString&, PreloadRequestStream&);
+    void scan(const String&, const SegmentedString&, PreloadRequestStream&);
 
 private:
     enum State {
diff --git a/Source/core/html/parser/CompactHTMLToken.cpp b/Source/core/html/parser/CompactHTMLToken.cpp
index fd4026b..4a826e8 100644
--- a/Source/core/html/parser/CompactHTMLToken.cpp
+++ b/Source/core/html/parser/CompactHTMLToken.cpp
@@ -33,7 +33,7 @@
 
 struct SameSizeAsCompactHTMLToken  {
     unsigned bitfields;
-    HTMLIdentifier data;
+    String data;
     Vector<Attribute> vector;
     TextPosition textPosition;
 };
@@ -51,10 +51,11 @@
         ASSERT_NOT_REACHED();
         break;
     case HTMLToken::DOCTYPE: {
-        m_data = HTMLIdentifier(token->name(), Likely8Bit);
+        m_data = attemptStaticStringCreation(token->name(), Likely8Bit);
+
         // There is only 1 DOCTYPE token per document, so to avoid increasing the
         // size of CompactHTMLToken, we just use the m_attributes vector.
-        m_attributes.append(Attribute(HTMLIdentifier(token->publicIdentifier(), Likely8Bit), String(token->systemIdentifier())));
+        m_attributes.append(Attribute(attemptStaticStringCreation(token->publicIdentifier(), Likely8Bit), String(token->systemIdentifier())));
         m_doctypeForcesQuirks = token->forceQuirks();
         break;
     }
@@ -63,7 +64,7 @@
     case HTMLToken::StartTag:
         m_attributes.reserveInitialCapacity(token->attributes().size());
         for (Vector<HTMLToken::Attribute>::const_iterator it = token->attributes().begin(); it != token->attributes().end(); ++it)
-            m_attributes.append(Attribute(HTMLIdentifier(it->name, Likely8Bit), StringImpl::create8BitIfPossible(it->value)));
+            m_attributes.append(Attribute(attemptStaticStringCreation(it->name, Likely8Bit), StringImpl::create8BitIfPossible(it->value)));
         // Fall through!
     case HTMLToken::EndTag:
         m_selfClosing = token->selfClosing();
@@ -71,7 +72,7 @@
     case HTMLToken::Comment:
     case HTMLToken::Character: {
         m_isAll8BitData = token->isAll8BitData();
-        m_data = HTMLIdentifier(token->data(), token->isAll8BitData() ? Force8Bit : Force16Bit);
+        m_data = attemptStaticStringCreation(token->data(), token->isAll8BitData() ? Force8Bit : Force16Bit);
         break;
     }
     default:
diff --git a/Source/core/html/parser/CompactHTMLToken.h b/Source/core/html/parser/CompactHTMLToken.h
index 89ef4ca..3858e03 100644
--- a/Source/core/html/parser/CompactHTMLToken.h
+++ b/Source/core/html/parser/CompactHTMLToken.h
@@ -26,7 +26,6 @@
 #ifndef CompactHTMLToken_h
 #define CompactHTMLToken_h
 
-#include "core/html/parser/HTMLIdentifier.h"
 #include "core/html/parser/HTMLToken.h"
 #include "wtf/Vector.h"
 #include "wtf/text/TextPosition.h"
@@ -39,13 +38,13 @@
 class CompactHTMLToken {
 public:
     struct Attribute {
-        Attribute(const HTMLIdentifier& name, const String& value)
+        Attribute(const String& name, const String& value)
             : name(name)
             , value(value)
         {
         }
 
-        HTMLIdentifier name;
+        String name;
         String value;
     };
 
@@ -54,7 +53,7 @@
     bool isSafeToSendToAnotherThread() const;
 
     HTMLToken::Type type() const { return static_cast<HTMLToken::Type>(m_type); }
-    const HTMLIdentifier& data() const { return m_data; }
+    const String& data() const { return m_data; }
     bool selfClosing() const { return m_selfClosing; }
     bool isAll8BitData() const { return m_isAll8BitData; }
     const Vector<Attribute>& attributes() const { return m_attributes; }
@@ -63,7 +62,7 @@
 
     // There is only 1 DOCTYPE token per document, so to avoid increasing the
     // size of CompactHTMLToken, we just use the m_attributes vector.
-    const HTMLIdentifier& publicIdentifier() const { return m_attributes[0].name; }
+    const String& publicIdentifier() const { return m_attributes[0].name; }
     const String& systemIdentifier() const { return m_attributes[0].value; }
     bool doctypeForcesQuirks() const { return m_doctypeForcesQuirks; }
 
@@ -73,7 +72,7 @@
     unsigned m_isAll8BitData : 1;
     unsigned m_doctypeForcesQuirks: 1;
 
-    HTMLIdentifier m_data; // "name", "characters", or "data" depending on m_type
+    String m_data; // "name", "characters", or "data" depending on m_type
     Vector<Attribute> m_attributes;
     TextPosition m_textPosition;
 };
diff --git a/Source/core/html/parser/HTMLConstructionSite.cpp b/Source/core/html/parser/HTMLConstructionSite.cpp
index 96dc248..84f1d38 100644
--- a/Source/core/html/parser/HTMLConstructionSite.cpp
+++ b/Source/core/html/parser/HTMLConstructionSite.cpp
@@ -37,7 +37,6 @@
 #include "core/dom/Text.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLOptGroupElement.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/HTMLTemplateElement.h"
 #include "core/html/parser/AtomicHTMLToken.h"
@@ -70,7 +69,7 @@
         || item->hasTagName(dtTag)
         || item->hasTagName(liTag)
         || item->hasTagName(optionTag)
-        || isHTMLOptGroupElement(item->node())
+        || item->hasTagName(optgroupTag)
         || item->hasTagName(pTag)
         || item->hasTagName(rpTag)
         || item->hasTagName(rtTag);
@@ -113,10 +112,12 @@
 
     insert(task);
 
-    task.child->beginParsingChildren();
-
-    if (task.selfClosing)
-        task.child->finishParsingChildren();
+    if (task.child->isElementNode()) {
+        Element& child = toElement(*task.child);
+        child.beginParsingChildren();
+        if (task.selfClosing)
+            child.finishParsingChildren();
+    }
 }
 
 static inline void executeInsertTextTask(HTMLConstructionSiteTask& task)
diff --git a/Source/core/html/parser/HTMLConstructionSite.h b/Source/core/html/parser/HTMLConstructionSite.h
index d4d812e..7a1b2aa 100644
--- a/Source/core/html/parser/HTMLConstructionSite.h
+++ b/Source/core/html/parser/HTMLConstructionSite.h
@@ -71,7 +71,7 @@
 } // namespace WebCore
 
 namespace WTF {
-template<> struct VectorTraits<WebCore::HTMLConstructionSiteTask> : SimpleClassVectorTraits { };
+template<> struct VectorTraits<WebCore::HTMLConstructionSiteTask> : SimpleClassVectorTraits<WebCore::HTMLConstructionSiteTask> { };
 } // namespace WTF
 
 namespace WebCore {
diff --git a/Source/core/html/parser/HTMLDocumentParser.cpp b/Source/core/html/parser/HTMLDocumentParser.cpp
index 2c2633b..84c9197 100644
--- a/Source/core/html/parser/HTMLDocumentParser.cpp
+++ b/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -32,13 +32,13 @@
 #include "core/html/HTMLDocument.h"
 #include "core/html/parser/AtomicHTMLToken.h"
 #include "core/html/parser/BackgroundHTMLParser.h"
-#include "core/html/parser/HTMLIdentifier.h"
 #include "core/html/parser/HTMLParserScheduler.h"
 #include "core/html/parser/HTMLParserThread.h"
 #include "core/html/parser/HTMLScriptRunner.h"
 #include "core/html/parser/HTMLTreeBuilder.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/frame/Frame.h"
+#include "platform/SharedBuffer.h"
 #include "platform/TraceEvent.h"
 #include "wtf/Functional.h"
 
@@ -317,6 +317,11 @@
     pumpPendingSpeculations();
 }
 
+void HTMLDocumentParser::didReceiveEncodingDataFromBackgroundParser(const DocumentEncodingData& data)
+{
+    document()->setEncodingData(data);
+}
+
 void HTMLDocumentParser::validateSpeculations(PassOwnPtr<ParsedChunk> chunk)
 {
     ASSERT(chunk);
@@ -654,12 +659,11 @@
 
 void HTMLDocumentParser::startBackgroundParser()
 {
+    ASSERT(!isStopped());
     ASSERT(shouldUseThreading());
     ASSERT(!m_haveBackgroundParser);
     m_haveBackgroundParser = true;
 
-    HTMLIdentifier::init();
-
     RefPtr<WeakReference<BackgroundHTMLParser> > reference = WeakReference<BackgroundHTMLParser>::createUnbound();
     m_backgroundParser = WeakPtr<BackgroundHTMLParser>(reference);
 
@@ -669,10 +673,11 @@
     config->xssAuditor = adoptPtr(new XSSAuditor);
     config->xssAuditor->init(document(), &m_xssAuditorDelegate);
     config->preloadScanner = adoptPtr(new TokenPreloadScanner(document()->url().copy(), document()->devicePixelRatio()));
+    config->decoder = takeDecoder();
 
     ASSERT(config->xssAuditor->isSafeToSendToAnotherThread());
     ASSERT(config->preloadScanner->isSafeToSendToAnotherThread());
-    HTMLParserThread::shared()->postTask(bind(&BackgroundHTMLParser::create, reference.release(), config.release()));
+    HTMLParserThread::shared()->postTask(bind(&BackgroundHTMLParser::start, reference.release(), config.release()));
 }
 
 void HTMLDocumentParser::stopBackgroundParser()
@@ -690,19 +695,9 @@
     if (isStopped())
         return;
 
-    if (shouldUseThreading()) {
-        if (!m_haveBackgroundParser)
-            startBackgroundParser();
-
-        ASSERT(inputSource->hasOneRef());
-        TRACE_EVENT1("net", "HTMLDocumentParser::append", "size", inputSource->length());
-        // NOTE: Important that the String temporary is destroyed before we post the task
-        // otherwise the String could call deref() on a StringImpl now owned by the background parser.
-        // We would like to ASSERT(closure.arg3()->hasOneRef()) but sadly the args are private.
-        Closure closure = bind(&BackgroundHTMLParser::append, m_backgroundParser, String(inputSource));
-        HTMLParserThread::shared()->postTask(closure);
-        return;
-    }
+    // We should never reach this point if we're using a parser thread,
+    // as appendBytes() will directly ship the data to the thread.
+    ASSERT(!shouldUseThreading());
 
     // pumpTokenizer can cause this parser to be detached from the Document,
     // but we need to ensure it isn't deleted yet.
@@ -968,4 +963,45 @@
         m_parserScheduler->resume();
 }
 
+void HTMLDocumentParser::appendBytes(const char* data, size_t length)
+{
+    if (!length || isStopped())
+        return;
+
+    if (shouldUseThreading()) {
+        if (!m_haveBackgroundParser)
+            startBackgroundParser();
+
+        OwnPtr<Vector<char> > buffer = adoptPtr(new Vector<char>(length));
+        memcpy(buffer->data(), data, length);
+        TRACE_EVENT1("net", "HTMLDocumentParser::appendBytes", "size", (unsigned)length);
+
+        HTMLParserThread::shared()->postTask(bind(&BackgroundHTMLParser::appendBytes, m_backgroundParser, buffer.release()));
+        return;
+    }
+
+    DecodedDataDocumentParser::appendBytes(data, length);
+}
+
+void HTMLDocumentParser::flush()
+{
+    // If we've got no decoder, we never received any data.
+    if (isDetached() || needsDecoder())
+        return;
+
+    if (m_haveBackgroundParser)
+        HTMLParserThread::shared()->postTask(bind(&BackgroundHTMLParser::flush, m_backgroundParser));
+    else
+        DecodedDataDocumentParser::flush();
+}
+
+void HTMLDocumentParser::setDecoder(PassOwnPtr<TextResourceDecoder> decoder)
+{
+    ASSERT(decoder);
+    DecodedDataDocumentParser::setDecoder(decoder);
+
+    if (m_haveBackgroundParser)
+        HTMLParserThread::shared()->postTask(bind(&BackgroundHTMLParser::setDecoder, m_backgroundParser, takeDecoder()));
+}
+
 }
diff --git a/Source/core/html/parser/HTMLDocumentParser.h b/Source/core/html/parser/HTMLDocumentParser.h
index 4077956..b07a16c 100644
--- a/Source/core/html/parser/HTMLDocumentParser.h
+++ b/Source/core/html/parser/HTMLDocumentParser.h
@@ -40,6 +40,7 @@
 #include "core/html/parser/HTMLToken.h"
 #include "core/html/parser/HTMLTokenizer.h"
 #include "core/html/parser/HTMLTreeBuilderSimulator.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/html/parser/XSSAuditor.h"
 #include "core/html/parser/XSSAuditorDelegate.h"
 #include "platform/text/SegmentedString.h"
@@ -80,11 +81,11 @@
 
     HTMLTokenizer* tokenizer() const { return m_tokenizer.get(); }
 
-    virtual TextPosition textPosition() const;
-    virtual OrdinalNumber lineNumber() const;
+    virtual TextPosition textPosition() const OVERRIDE FINAL;
+    virtual OrdinalNumber lineNumber() const OVERRIDE FINAL;
 
-    virtual void suspendScheduledTasks();
-    virtual void resumeScheduledTasks();
+    virtual void suspendScheduledTasks() OVERRIDE FINAL;
+    virtual void resumeScheduledTasks() OVERRIDE FINAL;
 
     struct ParsedChunk {
         OwnPtr<CompactHTMLTokenStream> tokens;
@@ -96,13 +97,18 @@
         TokenPreloadScannerCheckpoint preloadScannerCheckpoint;
     };
     void didReceiveParsedChunkFromBackgroundParser(PassOwnPtr<ParsedChunk>);
+    void didReceiveEncodingDataFromBackgroundParser(const DocumentEncodingData&);
+
+    virtual void appendBytes(const char* bytes, size_t length) OVERRIDE;
+    virtual void flush() OVERRIDE FINAL;
+    virtual void setDecoder(PassOwnPtr<TextResourceDecoder>) OVERRIDE FINAL;
 
     UseCounter* useCounter() { return UseCounter::getFrom(contextForParsingSession()); }
 
 protected:
-    virtual void insert(const SegmentedString&) OVERRIDE;
+    virtual void insert(const SegmentedString&) OVERRIDE FINAL;
     virtual void append(PassRefPtr<StringImpl>) OVERRIDE;
-    virtual void finish() OVERRIDE;
+    virtual void finish() OVERRIDE FINAL;
 
     HTMLDocumentParser(HTMLDocument*, bool reportErrors);
     HTMLDocumentParser(DocumentFragment*, Element* contextElement, ParserContentPolicy);
@@ -118,25 +124,25 @@
     }
 
     // DocumentParser
-    virtual void pinToMainThread() OVERRIDE;
-    virtual void detach() OVERRIDE;
-    virtual bool hasInsertionPoint() OVERRIDE;
-    virtual bool processingData() const OVERRIDE;
-    virtual void prepareToStopParsing() OVERRIDE;
-    virtual void stopParsing() OVERRIDE;
-    virtual bool isWaitingForScripts() const OVERRIDE;
-    virtual bool isExecutingScript() const OVERRIDE;
-    virtual void executeScriptsWaitingForResources() OVERRIDE;
+    virtual void pinToMainThread() OVERRIDE FINAL;
+    virtual void detach() OVERRIDE FINAL;
+    virtual bool hasInsertionPoint() OVERRIDE FINAL;
+    virtual bool processingData() const OVERRIDE FINAL;
+    virtual void prepareToStopParsing() OVERRIDE FINAL;
+    virtual void stopParsing() OVERRIDE FINAL;
+    virtual bool isWaitingForScripts() const OVERRIDE FINAL;
+    virtual bool isExecutingScript() const OVERRIDE FINAL;
+    virtual void executeScriptsWaitingForResources() OVERRIDE FINAL;
 
     // HTMLScriptRunnerHost
-    virtual void watchForLoad(Resource*) OVERRIDE;
-    virtual void stopWatchingForLoad(Resource*) OVERRIDE;
-    virtual HTMLInputStream& inputStream() { return m_input; }
-    virtual bool hasPreloadScanner() const { return m_preloadScanner.get() && !shouldUseThreading(); }
-    virtual void appendCurrentInputStreamToPreloadScannerAndScan() OVERRIDE;
+    virtual void watchForLoad(Resource*) OVERRIDE FINAL;
+    virtual void stopWatchingForLoad(Resource*) OVERRIDE FINAL;
+    virtual HTMLInputStream& inputStream() OVERRIDE FINAL { return m_input; }
+    virtual bool hasPreloadScanner() const OVERRIDE FINAL { return m_preloadScanner.get() && !shouldUseThreading(); }
+    virtual void appendCurrentInputStreamToPreloadScannerAndScan() OVERRIDE FINAL;
 
     // ResourceClient
-    virtual void notifyFinished(Resource*);
+    virtual void notifyFinished(Resource*) OVERRIDE FINAL;
 
     void startBackgroundParser();
     void stopBackgroundParser();
diff --git a/Source/core/html/parser/HTMLElementStack.cpp b/Source/core/html/parser/HTMLElementStack.cpp
index 9adfdf1..5bf3a14 100644
--- a/Source/core/html/parser/HTMLElementStack.cpp
+++ b/Source/core/html/parser/HTMLElementStack.cpp
@@ -31,9 +31,6 @@
 #include "MathMLNames.h"
 #include "SVGNames.h"
 #include "core/dom/Element.h"
-#include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLOptGroupElement.h"
-#include "core/html/HTMLTableElement.h"
 
 namespace WebCore {
 
@@ -45,7 +42,7 @@
 inline bool isRootNode(HTMLStackItem* item)
 {
     return item->isDocumentFragmentNode()
-        || isHTMLHtmlElement(item->node());
+        || item->hasTagName(htmlTag);
 }
 
 inline bool isScopeMarker(HTMLStackItem* item)
@@ -54,7 +51,7 @@
         || item->hasTagName(captionTag)
         || item->hasTagName(marqueeTag)
         || item->hasTagName(objectTag)
-        || isHTMLTableElement(item->node())
+        || item->hasTagName(tableTag)
         || item->hasTagName(tdTag)
         || item->hasTagName(thTag)
         || item->hasTagName(MathMLNames::miTag)
@@ -79,7 +76,7 @@
 
 inline bool isTableScopeMarker(HTMLStackItem* item)
 {
-    return isHTMLTableElement(item->node())
+    return item->hasTagName(tableTag)
         || item->hasTagName(templateTag)
         || isRootNode(item);
 }
@@ -115,7 +112,7 @@
 
 inline bool isSelectScopeMarker(HTMLStackItem* item)
 {
-    return !isHTMLOptGroupElement(item->node())
+    return !item->hasTagName(optgroupTag)
         && !item->hasTagName(optionTag);
 }
 
@@ -199,7 +196,9 @@
     m_bodyElement = 0;
     m_stackDepth = 0;
     while (m_top) {
-        topNode()->finishParsingChildren();
+        Node& node = *topNode();
+        if (node.isElementNode())
+            toElement(node).finishParsingChildren();
         m_top = m_top->releaseNext();
     }
 }
@@ -309,7 +308,7 @@
 
 void HTMLElementStack::pushHTMLHtmlElement(PassRefPtr<HTMLStackItem> item)
 {
-    ASSERT(isHTMLHtmlElement(item->node()));
+    ASSERT(item->hasTagName(htmlTag));
     pushRootNodeCommon(item);
 }
 
@@ -339,9 +338,9 @@
 
 void HTMLElementStack::push(PassRefPtr<HTMLStackItem> item)
 {
-    ASSERT(!isHTMLHtmlElement(item->node()));
-    ASSERT(!item->hasTagName(HTMLNames::headTag));
-    ASSERT(!item->hasTagName(HTMLNames::bodyTag));
+    ASSERT(!item->hasTagName(htmlTag));
+    ASSERT(!item->hasTagName(headTag));
+    ASSERT(!item->hasTagName(bodyTag));
     ASSERT(m_rootNode);
     pushCommon(item);
 }
@@ -351,9 +350,9 @@
     ASSERT(item);
     ASSERT(recordBelow);
     ASSERT(m_top);
-    ASSERT(!isHTMLHtmlElement(item->node()));
-    ASSERT(!item->hasTagName(HTMLNames::headTag));
-    ASSERT(!item->hasTagName(HTMLNames::bodyTag));
+    ASSERT(!item->hasTagName(htmlTag));
+    ASSERT(!item->hasTagName(headTag));
+    ASSERT(!item->hasTagName(bodyTag));
     ASSERT(m_rootNode);
     if (recordBelow == m_top) {
         push(item);
@@ -566,9 +565,9 @@
 
 void HTMLElementStack::popCommon()
 {
-    ASSERT(!isHTMLHtmlElement(topStackItem()->node()));
-    ASSERT(!topStackItem()->hasTagName(HTMLNames::headTag) || !m_headElement);
-    ASSERT(!topStackItem()->hasTagName(HTMLNames::bodyTag) || !m_bodyElement);
+    ASSERT(!topStackItem()->hasTagName(htmlTag));
+    ASSERT(!topStackItem()->hasTagName(headTag) || !m_headElement);
+    ASSERT(!topStackItem()->hasTagName(bodyTag) || !m_bodyElement);
     top()->finishParsingChildren();
     m_top = m_top->releaseNext();
 
@@ -577,8 +576,8 @@
 
 void HTMLElementStack::removeNonTopCommon(Element* element)
 {
-    ASSERT(!isHTMLHtmlElement(element));
-    ASSERT(!element->hasTagName(HTMLNames::bodyTag));
+    ASSERT(!element->hasTagName(htmlTag));
+    ASSERT(!element->hasTagName(bodyTag));
     ASSERT(top() != element);
     for (ElementRecord* pos = m_top.get(); pos; pos = pos->next()) {
         if (pos->next()->element() == element) {
diff --git a/Source/core/html/parser/HTMLEntityParser.cpp b/Source/core/html/parser/HTMLEntityParser.cpp
index 97cebee..7c1cdde 100644
--- a/Source/core/html/parser/HTMLEntityParser.cpp
+++ b/Source/core/html/parser/HTMLEntityParser.cpp
@@ -131,7 +131,7 @@
         unconsumeCharacters(source, consumedCharacters);
         consumedCharacters.clear();
         const int length = entitySearch.mostRecentMatch()->length;
-        const UChar* reference = entitySearch.mostRecentMatch()->entity;
+        const LChar* reference = entitySearch.mostRecentMatch()->entity;
         for (int i = 0; i < length; ++i) {
             cc = source.currentChar();
             ASSERT_UNUSED(reference, cc == *reference++);
diff --git a/Source/core/html/parser/HTMLEntityTable.h b/Source/core/html/parser/HTMLEntityTable.h
index f0d775e..b5cd6c4 100644
--- a/Source/core/html/parser/HTMLEntityTable.h
+++ b/Source/core/html/parser/HTMLEntityTable.h
@@ -31,9 +31,9 @@
 namespace WebCore {
 
 struct HTMLEntityTableEntry {
-    UChar lastCharacter() const { return entity[length - 1]; }
+    LChar lastCharacter() const { return entity[length - 1]; }
 
-    const UChar* entity;
+    const LChar* entity;
     int length;
     UChar32 firstValue;
     UChar32 secondValue;
diff --git a/Source/core/html/parser/HTMLIdentifier.cpp b/Source/core/html/parser/HTMLIdentifier.cpp
deleted file mode 100644
index 9b91cfc..0000000
--- a/Source/core/html/parser/HTMLIdentifier.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2013 Google, Inc. 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 GOOGLE INC. ``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 GOOGLE INC. 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.
- */
-
-#include "config.h"
-#include "core/html/parser/HTMLIdentifier.h"
-
-#include "HTMLNames.h"
-#include "wtf/HashMap.h"
-#include "wtf/MainThread.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-typedef HashMap<unsigned, StringImpl*, AlreadyHashed> IdentifierTable;
-
-unsigned HTMLIdentifier::maxNameLength = 0;
-
-static IdentifierTable& identifierTable()
-{
-    DEFINE_STATIC_LOCAL(IdentifierTable, table, ());
-    ASSERT(isMainThread() || !table.isEmpty());
-    return table;
-}
-
-#ifndef NDEBUG
-bool HTMLIdentifier::isKnown(const StringImpl* string)
-{
-    const IdentifierTable& table = identifierTable();
-    return table.contains(string->hash());
-}
-#endif
-
-StringImpl* HTMLIdentifier::findIfKnown(const UChar* characters, unsigned length)
-{
-    // We don't need to try hashing if we know the string is too long.
-    if (length > maxNameLength)
-        return 0;
-    // computeHashAndMaskTop8Bits is the function StringImpl::hash() uses.
-    unsigned hash = StringHasher::computeHashAndMaskTop8Bits(characters, length);
-    const IdentifierTable& table = identifierTable();
-    ASSERT(!table.isEmpty());
-
-    IdentifierTable::const_iterator it = table.find(hash);
-    if (it == table.end())
-        return 0;
-    // It's possible to have hash collisions between arbitrary strings and
-    // known identifiers (e.g. "bvvfg" collides with "script").
-    // However ASSERTs in addNames() guard against there ever being collisions
-    // between known identifiers.
-    if (!equal(it->value, characters, length))
-        return 0;
-    return it->value;
-}
-
-const String& HTMLIdentifier::asString() const
-{
-    ASSERT(isMainThread());
-    return m_string;
-}
-
-const StringImpl* HTMLIdentifier::asStringImpl() const
-{
-    return m_string.impl();
-}
-
-void HTMLIdentifier::addNames(const QualifiedName* const* names, unsigned namesCount)
-{
-    IdentifierTable& table = identifierTable();
-    for (unsigned i = 0; i < namesCount; ++i) {
-        StringImpl* name = names[i]->localName().impl();
-        unsigned hash = name->hash();
-        IdentifierTable::AddResult addResult = table.add(hash, name);
-        maxNameLength = std::max(maxNameLength, name->length());
-        // Ensure we're using the same hashing algorithm to get and set.
-        ASSERT_UNUSED(addResult, !addResult.isNewEntry || HTMLIdentifier::findIfKnown(String(name).charactersWithNullTermination().data(), name->length()) == name);
-        // We expect some hash collisions, but only for identical strings.
-        // Since all of these names are AtomicStrings pointers should be equal.
-        // Note: If you hit this ASSERT, then we had a hash collision among
-        // HTMLNames strings, and we need to re-design how we use this hash!
-        ASSERT_UNUSED(addResult, !addResult.isNewEntry || name == addResult.iterator->value);
-    }
-}
-
-void HTMLIdentifier::init()
-{
-    ASSERT(isMainThread()); // Not technically necessary, but this is our current expected usage.
-    static bool isInitialized = false;
-    if (isInitialized)
-        return;
-    isInitialized = true;
-
-    // FIXME: We should atomize small whitespace (\n, \n\n, etc.)
-    addNames(getHTMLTags(), HTMLTagsCount);
-    addNames(getHTMLAttrs(), HTMLAttrsCount);
-}
-
-}
diff --git a/Source/core/html/parser/HTMLIdentifier.h b/Source/core/html/parser/HTMLIdentifier.h
deleted file mode 100644
index 0034013..0000000
--- a/Source/core/html/parser/HTMLIdentifier.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2013 Google, Inc. 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 GOOGLE INC. ``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 GOOGLE INC. 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.
- */
-
-#ifndef HTMLIdentifier_h
-#define HTMLIdentifier_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class QualifiedName;
-
-enum CharacterWidth {
-    Likely8Bit,
-    Force8Bit,
-    Force16Bit
-};
-
-class HTMLIdentifier {
-public:
-    HTMLIdentifier() { }
-
-    template<size_t inlineCapacity>
-    HTMLIdentifier(const Vector<UChar, inlineCapacity>& vector, CharacterWidth width)
-        : m_string(findIfKnown(vector.data(), vector.size()))
-    {
-        if (m_string.impl())
-            return;
-        if (width == Likely8Bit)
-            m_string = StringImpl::create8BitIfPossible(vector);
-        else if (width == Force8Bit)
-            m_string = String::make8BitFrom16BitSource(vector);
-        else
-            m_string = String(vector);
-    }
-
-    // asString should only be used on the main thread.
-    const String& asString() const;
-    // asStringImpl() is safe to call from any thread.
-    const StringImpl* asStringImpl() const;
-
-    static void init();
-
-    bool isSafeToSendToAnotherThread() const { return m_string.isSafeToSendToAnotherThread(); }
-
-#ifndef NDEBUG
-    static bool isKnown(const StringImpl*);
-#endif
-
-private:
-    static unsigned maxNameLength;
-    static StringImpl* findIfKnown(const UChar* characters, unsigned length);
-    static void addNames(const QualifiedName* const* names, unsigned namesCount);
-
-    String m_string;
-};
-
-}
-
-#endif
diff --git a/Source/core/html/parser/HTMLMetaCharsetParser.cpp b/Source/core/html/parser/HTMLMetaCharsetParser.cpp
index 038c8a1..7947846 100644
--- a/Source/core/html/parser/HTMLMetaCharsetParser.cpp
+++ b/Source/core/html/parser/HTMLMetaCharsetParser.cpp
@@ -51,61 +51,12 @@
 {
 }
 
-static const char charsetString[] = "charset";
-static const size_t charsetLength = sizeof("charset") - 1;
-
-String HTMLMetaCharsetParser::extractCharset(const String& value)
-{
-    size_t pos = 0;
-    unsigned length = value.length();
-
-    while (pos < length) {
-        pos = value.find(charsetString, pos, false);
-        if (pos == kNotFound)
-            break;
-
-        pos += charsetLength;
-
-        // Skip whitespace.
-        while (pos < length && value[pos] <= ' ')
-            ++pos;
-
-        if (value[pos] != '=')
-            continue;
-
-        ++pos;
-
-        while (pos < length && value[pos] <= ' ')
-            ++pos;
-
-        char quoteMark = 0;
-        if (pos < length && (value[pos] == '"' || value[pos] == '\'')) {
-            quoteMark = static_cast<char>(value[pos++]);
-            ASSERT(!(quoteMark & 0x80));
-        }
-
-        if (pos == length)
-            break;
-
-        unsigned end = pos;
-        while (end < length && ((quoteMark && value[end] != quoteMark) || (!quoteMark && value[end] > ' ' && value[end] != '"' && value[end] != '\'' && value[end] != ';')))
-            ++end;
-
-        if (quoteMark && (end == length))
-            break; // Close quote not found.
-
-        return value.substring(pos, end - pos);
-    }
-
-    return "";
-}
-
 bool HTMLMetaCharsetParser::processMeta()
 {
     const HTMLToken::AttributeList& tokenAttributes = m_token.attributes();
-    AttributeList attributes;
+    HTMLAttributeList attributes;
     for (HTMLToken::AttributeList::const_iterator iter = tokenAttributes.begin(); iter != tokenAttributes.end(); ++iter) {
-        String attributeName = StringImpl::create8BitIfPossible(iter->name);
+        String attributeName = attemptStaticStringCreation(iter->name, Likely8Bit);
         String attributeValue = StringImpl::create8BitIfPossible(iter->value);
         attributes.append(std::make_pair(attributeName, attributeValue));
     }
@@ -114,37 +65,6 @@
     return m_encoding.isValid();
 }
 
-WTF::TextEncoding HTMLMetaCharsetParser::encodingFromMetaAttributes(const AttributeList& attributes)
-{
-    bool gotPragma = false;
-    Mode mode = None;
-    String charset;
-
-    for (AttributeList::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter) {
-        const AtomicString& attributeName = iter->first;
-        const String& attributeValue = iter->second;
-
-        if (attributeName == http_equivAttr) {
-            if (equalIgnoringCase(attributeValue, "content-type"))
-                gotPragma = true;
-        } else if (charset.isEmpty()) {
-            if (attributeName == charsetAttr) {
-                charset = attributeValue;
-                mode = Charset;
-            } else if (attributeName == contentAttr) {
-                charset = extractCharset(attributeValue);
-                if (charset.length())
-                    mode = Pragma;
-            }
-        }
-    }
-
-    if (mode == Charset || (mode == Pragma && gotPragma))
-        return WTF::TextEncoding(stripLeadingAndTrailingHTMLSpaces(charset));
-
-    return WTF::TextEncoding();
-}
-
 static const int bytesToCheckUnconditionally = 1024; // That many input bytes will be checked for meta charset even if <head> section is over.
 
 bool HTMLMetaCharsetParser::checkForMetaCharset(const char* data, size_t length)
@@ -177,20 +97,20 @@
     while (m_tokenizer->nextToken(m_input, m_token)) {
         bool end = m_token.type() == HTMLToken::EndTag;
         if (end || m_token.type() == HTMLToken::StartTag) {
-            AtomicString tagName(m_token.name());
+            String tagName = attemptStaticStringCreation(m_token.name(), Likely8Bit);
             if (!end) {
                 m_tokenizer->updateStateFor(tagName);
-                if (tagName == metaTag && processMeta()) {
+                if (threadSafeMatch(tagName, metaTag) && processMeta()) {
                     m_doneChecking = true;
                     return true;
                 }
             }
 
-            if (tagName != scriptTag && tagName != noscriptTag
-                && tagName != styleTag && tagName != linkTag
-                && tagName != metaTag && tagName != objectTag
-                && tagName != titleTag && tagName != baseTag
-                && (end || tagName != htmlTag) && (end || tagName != headTag)) {
+            if (!threadSafeMatch(tagName, scriptTag) && !threadSafeMatch(tagName, noscriptTag)
+                && !threadSafeMatch(tagName, styleTag) && !threadSafeMatch(tagName, linkTag)
+                && !threadSafeMatch(tagName, metaTag) && !threadSafeMatch(tagName, objectTag)
+                && !threadSafeMatch(tagName, titleTag) && !threadSafeMatch(tagName, baseTag)
+                && (end || !threadSafeMatch(tagName, htmlTag)) && (end || !threadSafeMatch(tagName, headTag))) {
                 m_inHeadSection = false;
             }
         }
diff --git a/Source/core/html/parser/HTMLMetaCharsetParser.h b/Source/core/html/parser/HTMLMetaCharsetParser.h
index 3393fca..65d9517 100644
--- a/Source/core/html/parser/HTMLMetaCharsetParser.h
+++ b/Source/core/html/parser/HTMLMetaCharsetParser.h
@@ -48,22 +48,10 @@
 
     const WTF::TextEncoding& encoding() { return m_encoding; }
 
-    typedef Vector<pair<String, String> > AttributeList;
-    // The returned encoding might not be valid.
-    static WTF::TextEncoding encodingFromMetaAttributes(const AttributeList&
-);
-
 private:
     HTMLMetaCharsetParser();
 
     bool processMeta();
-    static String extractCharset(const String&);
-
-    enum Mode {
-        None,
-        Charset,
-        Pragma,
-    };
 
     OwnPtr<HTMLTokenizer> m_tokenizer;
     OwnPtr<TextCodec> m_assumedCodec;
diff --git a/Source/core/html/parser/HTMLParserIdioms.cpp b/Source/core/html/parser/HTMLParserIdioms.cpp
index 2173ef5..e3b143a 100644
--- a/Source/core/html/parser/HTMLParserIdioms.cpp
+++ b/Source/core/html/parser/HTMLParserIdioms.cpp
@@ -25,13 +25,18 @@
 #include "config.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 
+#include "HTMLNames.h"
 #include <limits>
 #include "wtf/MathExtras.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/StringBuilder.h"
+#include "wtf/text/StringHash.h"
+#include "wtf/text/TextEncoding.h"
 
 namespace WebCore {
 
+using namespace HTMLNames;
+
 template <typename CharType>
 static String stripLeadingAndTrailingHTMLSpaces(String string, const CharType* characters, unsigned length)
 {
@@ -264,6 +269,92 @@
     return parseHTMLNonNegativeIntegerInternal(start, start + length, value);
 }
 
+static const char charsetString[] = "charset";
+static const size_t charsetLength = sizeof("charset") - 1;
+
+String extractCharset(const String& value)
+{
+    size_t pos = 0;
+    unsigned length = value.length();
+
+    while (pos < length) {
+        pos = value.find(charsetString, pos, false);
+        if (pos == kNotFound)
+            break;
+
+        pos += charsetLength;
+
+        // Skip whitespace.
+        while (pos < length && value[pos] <= ' ')
+            ++pos;
+
+        if (value[pos] != '=')
+            continue;
+
+        ++pos;
+
+        while (pos < length && value[pos] <= ' ')
+            ++pos;
+
+        char quoteMark = 0;
+        if (pos < length && (value[pos] == '"' || value[pos] == '\'')) {
+            quoteMark = static_cast<char>(value[pos++]);
+            ASSERT(!(quoteMark & 0x80));
+        }
+
+        if (pos == length)
+            break;
+
+        unsigned end = pos;
+        while (end < length && ((quoteMark && value[end] != quoteMark) || (!quoteMark && value[end] > ' ' && value[end] != '"' && value[end] != '\'' && value[end] != ';')))
+            ++end;
+
+        if (quoteMark && (end == length))
+            break; // Close quote not found.
+
+        return value.substring(pos, end - pos);
+    }
+
+    return "";
+}
+
+enum Mode {
+    None,
+    Charset,
+    Pragma,
+};
+
+WTF::TextEncoding encodingFromMetaAttributes(const HTMLAttributeList& attributes)
+{
+    bool gotPragma = false;
+    Mode mode = None;
+    String charset;
+
+    for (HTMLAttributeList::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter) {
+        const String& attributeName = iter->first;
+        const String& attributeValue = AtomicString(iter->second);
+
+        if (threadSafeMatch(attributeName, http_equivAttr)) {
+            if (equalIgnoringCase(attributeValue, "content-type"))
+                gotPragma = true;
+        } else if (charset.isEmpty()) {
+            if (threadSafeMatch(attributeName, charsetAttr)) {
+                charset = attributeValue;
+                mode = Charset;
+            } else if (threadSafeMatch(attributeName, contentAttr)) {
+                charset = extractCharset(attributeValue);
+                if (charset.length())
+                    mode = Pragma;
+            }
+        }
+    }
+
+    if (mode == Charset || (mode == Pragma && gotPragma))
+        return WTF::TextEncoding(stripLeadingAndTrailingHTMLSpaces(charset));
+
+    return WTF::TextEncoding();
+}
+
 static bool threadSafeEqual(const StringImpl* a, const StringImpl* b)
 {
     if (a == b)
@@ -278,9 +369,31 @@
     return threadSafeEqual(a.localName().impl(), b.localName().impl());
 }
 
-bool threadSafeMatch(const HTMLIdentifier& localName, const QualifiedName& qName)
+bool threadSafeMatch(const String& localName, const QualifiedName& qName)
 {
-    return threadSafeEqual(localName.asStringImpl(), qName.localName().impl());
+    return threadSafeEqual(localName.impl(), qName.localName().impl());
+}
+
+StringImpl* findStringIfStatic(const UChar* characters, unsigned length)
+{
+    // We don't need to try hashing if we know the string is too long.
+    if (length > StringImpl::highestStaticStringLength())
+        return 0;
+    // computeHashAndMaskTop8Bits is the function StringImpl::hash() uses.
+    unsigned hash = StringHasher::computeHashAndMaskTop8Bits(characters, length);
+    const WTF::StaticStringsTable& table = StringImpl::allStaticStrings();
+    ASSERT(!table.isEmpty());
+
+    WTF::StaticStringsTable::const_iterator it = table.find(hash);
+    if (it == table.end())
+        return 0;
+    // It's possible to have hash collisions between arbitrary strings and
+    // known identifiers (e.g. "bvvfg" collides with "script").
+    // However ASSERTs in StringImpl::createStatic guard against there ever being collisions
+    // between static strings.
+    if (!equal(it->value, characters, length))
+        return 0;
+    return it->value;
 }
 
 }
diff --git a/Source/core/html/parser/HTMLParserIdioms.h b/Source/core/html/parser/HTMLParserIdioms.h
index 903ca5a..49dbed3 100644
--- a/Source/core/html/parser/HTMLParserIdioms.h
+++ b/Source/core/html/parser/HTMLParserIdioms.h
@@ -26,11 +26,14 @@
 #define HTMLParserIdioms_h
 
 #include "core/dom/QualifiedName.h"
-#include "core/html/parser/HTMLIdentifier.h"
 #include "platform/Decimal.h"
 #include "wtf/Forward.h"
 #include "wtf/text/WTFString.h"
 
+namespace WTF {
+class TextEncoding;
+}
+
 namespace WebCore {
 
 // Space characters as defined by the HTML specification.
@@ -62,6 +65,10 @@
 // http://www.whatwg.org/specs/web-apps/current-work/#rules-for-parsing-non-negative-integers
 bool parseHTMLNonNegativeInteger(const String&, unsigned int&);
 
+typedef Vector<pair<String, String> > HTMLAttributeList;
+// The returned encoding might not be valid.
+WTF::TextEncoding encodingFromMetaAttributes(const HTMLAttributeList&);
+
 // Inline implementations of some of the functions declared above.
 
 template<typename CharType>
@@ -98,15 +105,31 @@
 }
 
 bool threadSafeMatch(const QualifiedName&, const QualifiedName&);
-bool threadSafeMatch(const HTMLIdentifier&, const QualifiedName&);
-inline bool threadSafeHTMLNamesMatch(const HTMLIdentifier& tagName, const QualifiedName& qName)
+bool threadSafeMatch(const String&, const QualifiedName&);
+
+StringImpl* findStringIfStatic(const UChar* characters, unsigned length);
+
+enum CharacterWidth {
+    Likely8Bit,
+    Force8Bit,
+    Force16Bit
+};
+
+template<size_t inlineCapacity>
+static String attemptStaticStringCreation(const Vector<UChar, inlineCapacity>& vector, CharacterWidth width)
 {
-    // When the QualifiedName is known to HTMLIdentifier,
-    // all we have to do is a pointer compare.
-    ASSERT(HTMLIdentifier::isKnown(qName.localName().impl()));
-    return tagName.asStringImpl() == qName.localName().impl();
+    String string(findStringIfStatic(vector.data(), vector.size()));
+    if (string.impl())
+        return string;
+    if (width == Likely8Bit)
+        string = StringImpl::create8BitIfPossible(vector);
+    else if (width == Force8Bit)
+        string = String::make8BitFrom16BitSource(vector);
+    else
+        string = String(vector);
+
+    return string;
 }
 
 }
-
 #endif
diff --git a/Source/core/html/parser/HTMLParserOptions.cpp b/Source/core/html/parser/HTMLParserOptions.cpp
index b101eac..98ceb68 100644
--- a/Source/core/html/parser/HTMLParserOptions.cpp
+++ b/Source/core/html/parser/HTMLParserOptions.cpp
@@ -30,7 +30,7 @@
 #include "core/dom/Document.h"
 #include "core/loader/FrameLoader.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLParserThread.cpp b/Source/core/html/parser/HTMLParserThread.cpp
index 5a0e30c..75c8e82 100644
--- a/Source/core/html/parser/HTMLParserThread.cpp
+++ b/Source/core/html/parser/HTMLParserThread.cpp
@@ -37,8 +37,9 @@
 
 namespace WebCore {
 
+static HTMLParserThread* s_sharedThread = 0;
+
 HTMLParserThread::HTMLParserThread()
-    : m_thread(adoptPtr(blink::Platform::current()->createThread("HTMLParserThread")))
 {
 }
 
@@ -46,17 +47,34 @@
 {
 }
 
+void HTMLParserThread::init()
+{
+    ASSERT(!s_sharedThread);
+    s_sharedThread = new HTMLParserThread;
+}
+
+void HTMLParserThread::shutdown()
+{
+    ASSERT(s_sharedThread);
+    delete s_sharedThread;
+    s_sharedThread = 0;
+}
+
 HTMLParserThread* HTMLParserThread::shared()
 {
-    static HTMLParserThread* thread;
-    if (!thread)
-        thread = new HTMLParserThread;
-    return thread;
+    return s_sharedThread;
+}
+
+blink::WebThread& HTMLParserThread::ensureThread()
+{
+    if (!m_thread)
+        m_thread = adoptPtr(blink::Platform::current()->createThread("HTMLParserThread"));
+    return *m_thread;
 }
 
 void HTMLParserThread::postTask(const Closure& closure)
 {
-    m_thread->postTask(new Task(closure));
+    ensureThread().postTask(new Task(closure));
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/parser/HTMLParserThread.h b/Source/core/html/parser/HTMLParserThread.h
index e0b85f9..a350c80 100644
--- a/Source/core/html/parser/HTMLParserThread.h
+++ b/Source/core/html/parser/HTMLParserThread.h
@@ -39,13 +39,20 @@
 
 class HTMLParserThread {
 public:
+    static void init();
+    static void shutdown();
+
+    // It is an error to call shared() before init() or after shutdown();
     static HTMLParserThread* shared();
+
     void postTask(const Closure&);
 
 private:
     HTMLParserThread();
     ~HTMLParserThread();
 
+    blink::WebThread& ensureThread();
+
     OwnPtr<blink::WebThread> m_thread;
 };
 
diff --git a/Source/core/html/parser/HTMLParserThreadTest.cpp b/Source/core/html/parser/HTMLParserThreadTest.cpp
new file mode 100644
index 0000000..8b742b8
--- /dev/null
+++ b/Source/core/html/parser/HTMLParserThreadTest.cpp
@@ -0,0 +1,26 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/html/parser/HTMLParserThread.h"
+
+#include <gtest/gtest.h>
+
+namespace {
+
+using namespace WebCore;
+
+TEST(HTMLParserThread, Init)
+{
+    // The harness has already run init() for us, so tear down the parser first.
+    ASSERT_TRUE(HTMLParserThread::shared());
+    HTMLParserThread::shutdown();
+
+    // Make sure starting the parser thread brings it back to life.
+    ASSERT_FALSE(HTMLParserThread::shared());
+    HTMLParserThread::init();
+    ASSERT_TRUE(HTMLParserThread::shared());
+}
+
+} // namespace
diff --git a/Source/core/html/parser/HTMLPreloadScanner.cpp b/Source/core/html/parser/HTMLPreloadScanner.cpp
index b925f1b..f9199cc 100644
--- a/Source/core/html/parser/HTMLPreloadScanner.cpp
+++ b/Source/core/html/parser/HTMLPreloadScanner.cpp
@@ -47,17 +47,17 @@
     return impl == qName.localName().impl();
 }
 
-static bool match(const HTMLIdentifier& name, const QualifiedName& qName)
-{
-    return match(name.asStringImpl(), qName);
-}
-
 static bool match(const AtomicString& name, const QualifiedName& qName)
 {
     ASSERT(isMainThread());
     return qName.localName() == name;
 }
 
+static bool match(const String& name, const QualifiedName& qName)
+{
+    return threadSafeMatch(name, qName);
+}
+
 static const StringImpl* tagImplFor(const HTMLToken::DataVector& data)
 {
     AtomicString tagName(data);
@@ -67,9 +67,9 @@
     return 0;
 }
 
-static const StringImpl* tagImplFor(const HTMLIdentifier& tagName)
+static const StringImpl* tagImplFor(const String& tagName)
 {
-    const StringImpl* result = tagName.asStringImpl();
+    const StringImpl* result = tagName.impl();
     if (result->isStatic())
         return result;
     return 0;
@@ -178,6 +178,8 @@
                 m_linkIsStyleSheet = relAttributeIsStyleSheet(attributeValue);
             else if (match(attributeName, mediaAttr))
                 m_mediaAttribute = attributeValue;
+            else if (match(attributeName, crossoriginAttr))
+                setCrossOriginAllowed(attributeValue);
         } else if (match(m_tagImpl, inputTag)) {
             if (match(attributeName, srcAttr))
                 setUrlToLoad(attributeValue, DisallowURLReplacement);
@@ -399,7 +401,7 @@
 
     while (m_tokenizer->nextToken(m_source, m_token)) {
         if (m_token.type() == HTMLToken::StartTag)
-            m_tokenizer->updateStateFor(AtomicString(m_token.name()));
+            m_tokenizer->updateStateFor(attemptStaticStringCreation(m_token.name(), Likely8Bit));
         m_scanner.scan(m_token, m_source, requests);
         m_token.clear();
     }
diff --git a/Source/core/html/parser/HTMLResourcePreloader.cpp b/Source/core/html/parser/HTMLResourcePreloader.cpp
index 08e70a6..b023fa9 100644
--- a/Source/core/html/parser/HTMLResourcePreloader.cpp
+++ b/Source/core/html/parser/HTMLResourcePreloader.cpp
@@ -48,14 +48,14 @@
 
 KURL PreloadRequest::completeURL(Document* document)
 {
-    return document->completeURL(m_resourceURL, m_baseURL.isEmpty() ? document->url() : m_baseURL);
+    return document->completeURLWithOverride(m_resourceURL, m_baseURL.isEmpty() ? document->url() : m_baseURL);
 }
 
 FetchRequest PreloadRequest::resourceRequest(Document* document)
 {
     ASSERT(isMainThread());
     FetchInitiatorInfo initiatorInfo;
-    initiatorInfo.name = m_initiatorName;
+    initiatorInfo.name = AtomicString(m_initiatorName);
     initiatorInfo.position = m_initiatorPosition;
     FetchRequest request(ResourceRequest(completeURL(document)), initiatorInfo);
 
diff --git a/Source/core/html/parser/HTMLScriptRunner.cpp b/Source/core/html/parser/HTMLScriptRunner.cpp
index 1cb6555..2d73cce 100644
--- a/Source/core/html/parser/HTMLScriptRunner.cpp
+++ b/Source/core/html/parser/HTMLScriptRunner.cpp
@@ -137,8 +137,8 @@
             scriptLoader->dispatchErrorEvent();
         else {
             ASSERT(isExecutingScript());
-            if (scriptLoader->executePotentiallyCrossOriginScript(sourceCode))
-                element->dispatchEvent(createScriptLoadEvent());
+            scriptLoader->executeScript(sourceCode);
+            element->dispatchEvent(createScriptLoadEvent());
         }
     }
     ASSERT(!isExecutingScript());
@@ -158,8 +158,9 @@
     pendingScript.setWatchingForLoad(false);
 }
 
-// This function should match 10.2.5.11 "An end tag whose tag name is 'script'"
-// Script handling lives outside the tree builder to keep the each class simple.
+// Implements the steps for 'An end tag whose tag name is "script"'
+// http://whatwg.org/html#scriptEndTag
+// Script handling lives outside the tree builder to keep each class simple.
 void HTMLScriptRunner::execute(PassRefPtr<Element> scriptElement, const TextPosition& scriptStartPosition)
 {
     ASSERT(scriptElement);
@@ -268,8 +269,8 @@
     return true;
 }
 
-// This method is meant to match the HTML5 definition of "running a script"
-// http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#running-a-script
+// Implements the initial steps for 'An end tag whose tag name is "script"'
+// http://whatwg.org/html#scriptEndTag
 void HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition)
 {
     ASSERT(m_document);
@@ -285,10 +286,8 @@
         if (!scriptLoader)
             return;
 
-        // FIXME: This may be too agressive as we always deliver mutations at
-        // every script element, even if it's not ready to execute yet. There's
-        // unfortuantely no obvious way to tell if prepareScript is going to
-        // execute the script from out here.
+        ASSERT(scriptLoader->isParserInserted());
+
         if (!isExecutingScript())
             Microtask::performCheckpoint();
 
diff --git a/Source/core/html/parser/HTMLSrcsetParser.h b/Source/core/html/parser/HTMLSrcsetParser.h
index 8964ffb..861df34 100644
--- a/Source/core/html/parser/HTMLSrcsetParser.h
+++ b/Source/core/html/parser/HTMLSrcsetParser.h
@@ -50,7 +50,12 @@
 
     String toString() const
     {
-        return m_string.toString();
+        return String(m_string.toString());
+    }
+
+    AtomicString toAtomicString() const
+    {
+        return AtomicString(m_string.toString());
     }
 
     inline float scaleFactor() const
diff --git a/Source/core/html/parser/HTMLTokenizer.cpp b/Source/core/html/parser/HTMLTokenizer.cpp
index ed8c954..43e50c7 100644
--- a/Source/core/html/parser/HTMLTokenizer.cpp
+++ b/Source/core/html/parser/HTMLTokenizer.cpp
@@ -30,6 +30,7 @@
 
 #include "HTMLNames.h"
 #include "core/html/parser/HTMLEntityParser.h"
+#include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/HTMLTreeBuilder.h"
 #include "platform/NotImplemented.h"
 #include "core/xml/parser/MarkupTokenizerInlines.h"
@@ -1596,20 +1597,20 @@
     return characters.toString();
 }
 
-void HTMLTokenizer::updateStateFor(const AtomicString& tagName)
+void HTMLTokenizer::updateStateFor(const String& tagName)
 {
-    if (tagName == textareaTag || tagName == titleTag)
+    if (threadSafeMatch(tagName, textareaTag) || threadSafeMatch(tagName, titleTag))
         setState(HTMLTokenizer::RCDATAState);
-    else if (tagName == plaintextTag)
+    else if (threadSafeMatch(tagName, plaintextTag))
         setState(HTMLTokenizer::PLAINTEXTState);
-    else if (tagName == scriptTag)
+    else if (threadSafeMatch(tagName, scriptTag))
         setState(HTMLTokenizer::ScriptDataState);
-    else if (tagName == styleTag
-        || tagName == iframeTag
-        || tagName == xmpTag
-        || (tagName == noembedTag && m_options.pluginsEnabled)
-        || tagName == noframesTag
-        || (tagName == noscriptTag && m_options.scriptEnabled))
+    else if (threadSafeMatch(tagName, styleTag)
+        || threadSafeMatch(tagName, iframeTag)
+        || threadSafeMatch(tagName, xmpTag)
+        || (threadSafeMatch(tagName, noembedTag) && m_options.pluginsEnabled)
+        || threadSafeMatch(tagName, noframesTag)
+        || (threadSafeMatch(tagName, noscriptTag) && m_options.scriptEnabled))
         setState(HTMLTokenizer::RAWTEXTState);
 }
 
diff --git a/Source/core/html/parser/HTMLTokenizer.h b/Source/core/html/parser/HTMLTokenizer.h
index aa7c059..3a4ca7f 100644
--- a/Source/core/html/parser/HTMLTokenizer.h
+++ b/Source/core/html/parser/HTMLTokenizer.h
@@ -126,7 +126,6 @@
         State state;
         UChar additionalAllowedCharacter;
         bool skipNextNewLine;
-        bool forceNullCharacterReplacement;
         bool shouldAllowCDATA;
 
         Checkpoint()
@@ -134,7 +133,6 @@
             , state()
             , additionalAllowedCharacter('\0')
             , skipNextNewLine(false)
-            , forceNullCharacterReplacement(false)
             , shouldAllowCDATA(false)
         {
         }
@@ -176,7 +174,7 @@
     //  * CDATA sections in foreign content will be tokenized as bogus comments
     //    instead of as character tokens.
     //
-    void updateStateFor(const AtomicString& tagName);
+    void updateStateFor(const String& tagName);
 
     bool forceNullCharacterReplacement() const { return m_forceNullCharacterReplacement; }
     void setForceNullCharacterReplacement(bool value) { m_forceNullCharacterReplacement = value; }
diff --git a/Source/core/html/parser/HTMLTreeBuilder.cpp b/Source/core/html/parser/HTMLTreeBuilder.cpp
index 4196cde..5997b21 100644
--- a/Source/core/html/parser/HTMLTreeBuilder.cpp
+++ b/Source/core/html/parser/HTMLTreeBuilder.cpp
@@ -37,9 +37,6 @@
 #include "core/dom/DocumentFragment.h"
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLFormElement.h"
-#include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLOptGroupElement.h"
-#include "core/html/HTMLTableElement.h"
 #include "core/html/parser/AtomicHTMLToken.h"
 #include "core/html/parser/HTMLDocumentParser.h"
 #include "core/html/parser/HTMLParserIdioms.h"
@@ -572,8 +569,8 @@
     static PrefixedNameToQualifiedNameMap* caseMap = 0;
     if (!caseMap) {
         caseMap = new PrefixedNameToQualifiedNameMap;
-        const QualifiedName* const* svgTags = SVGNames::getSVGTags();
-        mapLoweredLocalNameToName(caseMap, svgTags, SVGNames::SVGTagsCount);
+        OwnPtr<const QualifiedName*[]> svgTags = SVGNames::getSVGTags();
+        mapLoweredLocalNameToName(caseMap, svgTags.get(), SVGNames::SVGTagsCount);
     }
 
     const QualifiedName& casedName = caseMap->get(token->name());
@@ -582,14 +579,14 @@
     token->setName(casedName.localName());
 }
 
-template<const QualifiedName* const* getAttrs(), unsigned length>
+template<PassOwnPtr<const QualifiedName*[]> getAttrs(), unsigned length>
 static void adjustAttributes(AtomicHTMLToken* token)
 {
     static PrefixedNameToQualifiedNameMap* caseMap = 0;
     if (!caseMap) {
         caseMap = new PrefixedNameToQualifiedNameMap;
-        const QualifiedName* const* attrs = getAttrs();
-        mapLoweredLocalNameToName(caseMap, attrs, length);
+        OwnPtr<const QualifiedName*[]> attrs = getAttrs();
+        mapLoweredLocalNameToName(caseMap, attrs.get(), length);
     }
 
     for (unsigned i = 0; i < token->attributes().size(); ++i) {
@@ -627,11 +624,11 @@
     if (!map) {
         map = new PrefixedNameToQualifiedNameMap;
 
-        const QualifiedName* const* attrs = XLinkNames::getXLinkAttrs();
-        addNamesWithPrefix(map, xlinkAtom, attrs, XLinkNames::XLinkAttrsCount);
+        OwnPtr<const QualifiedName*[]> attrs = XLinkNames::getXLinkAttrs();
+        addNamesWithPrefix(map, xlinkAtom, attrs.get(), XLinkNames::XLinkAttrsCount);
 
-        attrs = XMLNames::getXMLAttrs();
-        addNamesWithPrefix(map, xmlAtom, attrs, XMLNames::XMLAttrsCount);
+        OwnPtr<const QualifiedName*[]> xmlAttrs = XMLNames::getXMLAttrs();
+        addNamesWithPrefix(map, xmlAtom, xmlAttrs.get(), XMLNames::XMLAttrsCount);
 
         map->add(WTF::xmlnsAtom, XMLNSNames::xmlnsAttr);
         map->add("xmlns:xlink", QualifiedName(xmlnsAtom, xlinkAtom, XMLNSNames::xmlnsNamespaceURI));
@@ -1396,7 +1393,7 @@
                 AtomicHTMLToken endOption(HTMLToken::EndTag, optionTag.localName());
                 processEndTag(&endOption);
             }
-            if (isHTMLOptGroupElement(m_tree.currentStackItem()->node())) {
+            if (m_tree.currentStackItem()->hasTagName(optgroupTag)) {
                 AtomicHTMLToken endOptgroup(HTMLToken::EndTag, optgroupTag.localName());
                 processEndTag(&endOptgroup);
             }
@@ -1636,7 +1633,7 @@
                 while (item->node() != m_tree.openElements()->rootNode() && !item->hasTagName(templateTag)) {
                     nodeRecord = nodeRecord->next();
                     item = nodeRecord->stackItem();
-                    if (isHTMLTableElement(item->node()))
+                    if (item->hasTagName(tableTag))
                         return setInsertionMode(InSelectInTableMode);
                 }
             }
@@ -1653,7 +1650,7 @@
         if (item->hasTagName(colgroupTag)) {
             return setInsertionMode(InColumnGroupMode);
         }
-        if (isHTMLTableElement(item->node()))
+        if (item->hasTagName(tableTag))
             return setInsertionMode(InTableMode);
         if (item->hasTagName(headTag)) {
             if (!m_fragmentContext.fragment() || m_fragmentContext.contextElement() != item->node())
@@ -1665,7 +1662,7 @@
         if (item->hasTagName(framesetTag)) {
             return setInsertionMode(InFramesetMode);
         }
-        if (isHTMLHtmlElement(item->node())) {
+        if (item->hasTagName(htmlTag)) {
             if (m_tree.headStackItem())
                 return setInsertionMode(AfterHeadMode);
 
@@ -2212,9 +2209,9 @@
     case InSelectMode:
         ASSERT(insertionMode() == InSelectMode || insertionMode() == InSelectInTableMode);
         if (token->name() == optgroupTag) {
-            if (m_tree.currentStackItem()->hasTagName(optionTag) && m_tree.oneBelowTop() && isHTMLOptGroupElement(m_tree.oneBelowTop()->node()))
+            if (m_tree.currentStackItem()->hasTagName(optionTag) && m_tree.oneBelowTop() && m_tree.oneBelowTop()->hasTagName(optgroupTag))
                 processFakeEndTag(optionTag);
-            if (isHTMLOptGroupElement(m_tree.currentStackItem()->node())) {
+            if (m_tree.currentStackItem()->hasTagName(optgroupTag)) {
                 m_tree.openElements()->pop();
                 return;
             }
@@ -2366,11 +2363,11 @@
         ASSERT(insertionMode() == InTableMode || insertionMode() == InTableBodyMode || insertionMode() == InRowMode);
         ASSERT(m_pendingTableCharacters.isEmpty());
         if (m_tree.currentStackItem()->isElementNode()
-            && (isHTMLTableElement(m_tree.currentStackItem()->node())
-                || m_tree.currentStackItem()->hasTagName(HTMLNames::tbodyTag)
-                || m_tree.currentStackItem()->hasTagName(HTMLNames::tfootTag)
-                || m_tree.currentStackItem()->hasTagName(HTMLNames::theadTag)
-                || m_tree.currentStackItem()->hasTagName(HTMLNames::trTag))) {
+            && (m_tree.currentStackItem()->hasTagName(tableTag)
+                || m_tree.currentStackItem()->hasTagName(tbodyTag)
+                || m_tree.currentStackItem()->hasTagName(tfootTag)
+                || m_tree.currentStackItem()->hasTagName(theadTag)
+                || m_tree.currentStackItem()->hasTagName(trTag))) {
             m_originalInsertionMode = m_insertionMode;
             setInsertionMode(InTableTextMode);
             // Note that we fall through to the InTableTextMode case below.
@@ -2407,7 +2404,6 @@
         // FIXME: parse error
         setInsertionMode(InBodyMode);
         goto ReprocessBuffer;
-        break;
     }
     case TextMode: {
         ASSERT(insertionMode() == TextMode);
@@ -2423,7 +2419,6 @@
             return;
         defaultForInHeadNoscript();
         goto ReprocessBuffer;
-        break;
     }
     case InFramesetMode:
     case AfterFramesetMode: {
diff --git a/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp b/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp
index 32ccaaf..37273cb 100644
--- a/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp
+++ b/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp
@@ -40,64 +40,64 @@
 static bool tokenExitsForeignContent(const CompactHTMLToken& token)
 {
     // FIXME: This is copied from HTMLTreeBuilder::processTokenInForeignContent and changed to use threadSafeHTMLNamesMatch.
-    const HTMLIdentifier& tagName = token.data();
-    return threadSafeHTMLNamesMatch(tagName, bTag)
-        || threadSafeHTMLNamesMatch(tagName, bigTag)
-        || threadSafeHTMLNamesMatch(tagName, blockquoteTag)
-        || threadSafeHTMLNamesMatch(tagName, bodyTag)
-        || threadSafeHTMLNamesMatch(tagName, brTag)
-        || threadSafeHTMLNamesMatch(tagName, centerTag)
-        || threadSafeHTMLNamesMatch(tagName, codeTag)
-        || threadSafeHTMLNamesMatch(tagName, ddTag)
-        || threadSafeHTMLNamesMatch(tagName, divTag)
-        || threadSafeHTMLNamesMatch(tagName, dlTag)
-        || threadSafeHTMLNamesMatch(tagName, dtTag)
-        || threadSafeHTMLNamesMatch(tagName, emTag)
-        || threadSafeHTMLNamesMatch(tagName, embedTag)
-        || threadSafeHTMLNamesMatch(tagName, h1Tag)
-        || threadSafeHTMLNamesMatch(tagName, h2Tag)
-        || threadSafeHTMLNamesMatch(tagName, h3Tag)
-        || threadSafeHTMLNamesMatch(tagName, h4Tag)
-        || threadSafeHTMLNamesMatch(tagName, h5Tag)
-        || threadSafeHTMLNamesMatch(tagName, h6Tag)
-        || threadSafeHTMLNamesMatch(tagName, headTag)
-        || threadSafeHTMLNamesMatch(tagName, hrTag)
-        || threadSafeHTMLNamesMatch(tagName, iTag)
-        || threadSafeHTMLNamesMatch(tagName, imgTag)
-        || threadSafeHTMLNamesMatch(tagName, liTag)
-        || threadSafeHTMLNamesMatch(tagName, listingTag)
-        || threadSafeHTMLNamesMatch(tagName, menuTag)
-        || threadSafeHTMLNamesMatch(tagName, metaTag)
-        || threadSafeHTMLNamesMatch(tagName, nobrTag)
-        || threadSafeHTMLNamesMatch(tagName, olTag)
-        || threadSafeHTMLNamesMatch(tagName, pTag)
-        || threadSafeHTMLNamesMatch(tagName, preTag)
-        || threadSafeHTMLNamesMatch(tagName, rubyTag)
-        || threadSafeHTMLNamesMatch(tagName, sTag)
-        || threadSafeHTMLNamesMatch(tagName, smallTag)
-        || threadSafeHTMLNamesMatch(tagName, spanTag)
-        || threadSafeHTMLNamesMatch(tagName, strongTag)
-        || threadSafeHTMLNamesMatch(tagName, strikeTag)
-        || threadSafeHTMLNamesMatch(tagName, subTag)
-        || threadSafeHTMLNamesMatch(tagName, supTag)
-        || threadSafeHTMLNamesMatch(tagName, tableTag)
-        || threadSafeHTMLNamesMatch(tagName, ttTag)
-        || threadSafeHTMLNamesMatch(tagName, uTag)
-        || threadSafeHTMLNamesMatch(tagName, ulTag)
-        || threadSafeHTMLNamesMatch(tagName, varTag)
-        || (threadSafeHTMLNamesMatch(tagName, fontTag) && (token.getAttributeItem(colorAttr) || token.getAttributeItem(faceAttr) || token.getAttributeItem(sizeAttr)));
+    const String& tagName = token.data();
+    return threadSafeMatch(tagName, bTag)
+        || threadSafeMatch(tagName, bigTag)
+        || threadSafeMatch(tagName, blockquoteTag)
+        || threadSafeMatch(tagName, bodyTag)
+        || threadSafeMatch(tagName, brTag)
+        || threadSafeMatch(tagName, centerTag)
+        || threadSafeMatch(tagName, codeTag)
+        || threadSafeMatch(tagName, ddTag)
+        || threadSafeMatch(tagName, divTag)
+        || threadSafeMatch(tagName, dlTag)
+        || threadSafeMatch(tagName, dtTag)
+        || threadSafeMatch(tagName, emTag)
+        || threadSafeMatch(tagName, embedTag)
+        || threadSafeMatch(tagName, h1Tag)
+        || threadSafeMatch(tagName, h2Tag)
+        || threadSafeMatch(tagName, h3Tag)
+        || threadSafeMatch(tagName, h4Tag)
+        || threadSafeMatch(tagName, h5Tag)
+        || threadSafeMatch(tagName, h6Tag)
+        || threadSafeMatch(tagName, headTag)
+        || threadSafeMatch(tagName, hrTag)
+        || threadSafeMatch(tagName, iTag)
+        || threadSafeMatch(tagName, imgTag)
+        || threadSafeMatch(tagName, liTag)
+        || threadSafeMatch(tagName, listingTag)
+        || threadSafeMatch(tagName, menuTag)
+        || threadSafeMatch(tagName, metaTag)
+        || threadSafeMatch(tagName, nobrTag)
+        || threadSafeMatch(tagName, olTag)
+        || threadSafeMatch(tagName, pTag)
+        || threadSafeMatch(tagName, preTag)
+        || threadSafeMatch(tagName, rubyTag)
+        || threadSafeMatch(tagName, sTag)
+        || threadSafeMatch(tagName, smallTag)
+        || threadSafeMatch(tagName, spanTag)
+        || threadSafeMatch(tagName, strongTag)
+        || threadSafeMatch(tagName, strikeTag)
+        || threadSafeMatch(tagName, subTag)
+        || threadSafeMatch(tagName, supTag)
+        || threadSafeMatch(tagName, tableTag)
+        || threadSafeMatch(tagName, ttTag)
+        || threadSafeMatch(tagName, uTag)
+        || threadSafeMatch(tagName, ulTag)
+        || threadSafeMatch(tagName, varTag)
+        || (threadSafeMatch(tagName, fontTag) && (token.getAttributeItem(colorAttr) || token.getAttributeItem(faceAttr) || token.getAttributeItem(sizeAttr)));
 }
 
 static bool tokenExitsSVG(const CompactHTMLToken& token)
 {
     // FIXME: It's very fragile that we special case foreignObject here to be case-insensitive.
-    return equalIgnoringCaseNonNull(token.data().asStringImpl(), SVGNames::foreignObjectTag.localName().impl());
+    return equalIgnoringCaseNonNull(token.data().impl(), SVGNames::foreignObjectTag.localName().impl());
 }
 
 static bool tokenExitsMath(const CompactHTMLToken& token)
 {
     // FIXME: This is copied from HTMLElementStack::isMathMLTextIntegrationPoint and changed to use threadSafeMatch.
-    const HTMLIdentifier& tagName = token.data();
+    const String& tagName = token.data();
     return threadSafeMatch(tagName, MathMLNames::miTag)
         || threadSafeMatch(tagName, MathMLNames::moTag)
         || threadSafeMatch(tagName, MathMLNames::mnTag)
@@ -132,7 +132,7 @@
 bool HTMLTreeBuilderSimulator::simulate(const CompactHTMLToken& token, HTMLTokenizer* tokenizer)
 {
     if (token.type() == HTMLToken::StartTag) {
-        const HTMLIdentifier& tagName = token.data();
+        const String& tagName = token.data();
         if (threadSafeMatch(tagName, SVGNames::svgTag))
             m_namespaceStack.append(SVG);
         if (threadSafeMatch(tagName, MathMLNames::mathTag))
@@ -144,30 +144,30 @@
             m_namespaceStack.append(HTML);
         if (!inForeignContent()) {
             // FIXME: This is just a copy of Tokenizer::updateStateFor which uses threadSafeMatches.
-            if (threadSafeHTMLNamesMatch(tagName, textareaTag) || threadSafeHTMLNamesMatch(tagName, titleTag))
+            if (threadSafeMatch(tagName, textareaTag) || threadSafeMatch(tagName, titleTag))
                 tokenizer->setState(HTMLTokenizer::RCDATAState);
-            else if (threadSafeHTMLNamesMatch(tagName, plaintextTag))
+            else if (threadSafeMatch(tagName, plaintextTag))
                 tokenizer->setState(HTMLTokenizer::PLAINTEXTState);
-            else if (threadSafeHTMLNamesMatch(tagName, scriptTag))
+            else if (threadSafeMatch(tagName, scriptTag))
                 tokenizer->setState(HTMLTokenizer::ScriptDataState);
-            else if (threadSafeHTMLNamesMatch(tagName, styleTag)
-                || threadSafeHTMLNamesMatch(tagName, iframeTag)
-                || threadSafeHTMLNamesMatch(tagName, xmpTag)
-                || (threadSafeHTMLNamesMatch(tagName, noembedTag) && m_options.pluginsEnabled)
-                || threadSafeHTMLNamesMatch(tagName, noframesTag)
-                || (threadSafeHTMLNamesMatch(tagName, noscriptTag) && m_options.scriptEnabled))
+            else if (threadSafeMatch(tagName, styleTag)
+                || threadSafeMatch(tagName, iframeTag)
+                || threadSafeMatch(tagName, xmpTag)
+                || (threadSafeMatch(tagName, noembedTag) && m_options.pluginsEnabled)
+                || threadSafeMatch(tagName, noframesTag)
+                || (threadSafeMatch(tagName, noscriptTag) && m_options.scriptEnabled))
                 tokenizer->setState(HTMLTokenizer::RAWTEXTState);
         }
     }
 
     if (token.type() == HTMLToken::EndTag) {
-        const HTMLIdentifier& tagName = token.data();
+        const String& tagName = token.data();
         if ((m_namespaceStack.last() == SVG && threadSafeMatch(tagName, SVGNames::svgTag))
             || (m_namespaceStack.last() == MathML && threadSafeMatch(tagName, MathMLNames::mathTag))
             || (m_namespaceStack.contains(SVG) && m_namespaceStack.last() == HTML && tokenExitsSVG(token))
             || (m_namespaceStack.contains(MathML) && m_namespaceStack.last() == HTML && tokenExitsMath(token)))
             m_namespaceStack.removeLast();
-        if (threadSafeHTMLNamesMatch(tagName, scriptTag)) {
+        if (threadSafeMatch(tagName, scriptTag)) {
             if (!inForeignContent())
                 tokenizer->setState(HTMLTokenizer::DataState);
             return false;
diff --git a/Source/core/html/parser/HTMLViewSourceParser.cpp b/Source/core/html/parser/HTMLViewSourceParser.cpp
index b46ff5a..55e860f 100644
--- a/Source/core/html/parser/HTMLViewSourceParser.cpp
+++ b/Source/core/html/parser/HTMLViewSourceParser.cpp
@@ -27,6 +27,7 @@
 #include "core/html/parser/HTMLViewSourceParser.h"
 
 #include "core/dom/DOMImplementation.h"
+#include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/HTMLParserOptions.h"
 #include "core/html/parser/HTMLToken.h"
 
@@ -52,7 +53,7 @@
 
         // FIXME: The tokenizer should do this work for us.
         if (m_token.type() == HTMLToken::StartTag)
-            m_tokenizer->updateStateFor(AtomicString(m_token.name()));
+            m_tokenizer->updateStateFor(attemptStaticStringCreation(m_token.name(), Likely8Bit));
         m_token.clear();
     }
 }
diff --git a/Source/core/html/parser/TextDocumentParser.cpp b/Source/core/html/parser/TextDocumentParser.cpp
index 38175a0..d29935a 100644
--- a/Source/core/html/parser/TextDocumentParser.cpp
+++ b/Source/core/html/parser/TextDocumentParser.cpp
@@ -42,11 +42,11 @@
 {
 }
 
-void TextDocumentParser::append(PassRefPtr<StringImpl> text)
+void TextDocumentParser::appendBytes(const char* data, size_t length)
 {
     if (!m_haveInsertedFakePreElement)
         insertFakePreElement();
-    HTMLDocumentParser::append(text);
+    HTMLDocumentParser::appendBytes(data, length);
 }
 
 void TextDocumentParser::insertFakePreElement()
diff --git a/Source/core/html/parser/TextDocumentParser.h b/Source/core/html/parser/TextDocumentParser.h
index 6b5bb9e..9134274 100644
--- a/Source/core/html/parser/TextDocumentParser.h
+++ b/Source/core/html/parser/TextDocumentParser.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class TextDocumentParser : public HTMLDocumentParser {
+class TextDocumentParser FINAL : public HTMLDocumentParser {
 public:
     static PassRefPtr<TextDocumentParser> create(HTMLDocument* document)
     {
@@ -41,7 +41,7 @@
 private:
     explicit TextDocumentParser(HTMLDocument*);
 
-    virtual void append(PassRefPtr<StringImpl>);
+    virtual void appendBytes(const char*, size_t) OVERRIDE;
     void insertFakePreElement();
 
     bool m_haveInsertedFakePreElement;
diff --git a/Source/core/fetch/TextResourceDecoder.cpp b/Source/core/html/parser/TextResourceDecoder.cpp
similarity index 94%
rename from Source/core/fetch/TextResourceDecoder.cpp
rename to Source/core/html/parser/TextResourceDecoder.cpp
index 5a21dd5..1f650d4 100644
--- a/Source/core/fetch/TextResourceDecoder.cpp
+++ b/Source/core/html/parser/TextResourceDecoder.cpp
@@ -21,7 +21,7 @@
 
 
 #include "config.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 
 #include "HTMLNames.h"
 #include "core/dom/DOMImplementation.h"
@@ -91,19 +91,19 @@
 TextResourceDecoder::ContentType TextResourceDecoder::determineContentType(const String& mimeType)
 {
     if (equalIgnoringCase(mimeType, "text/css"))
-        return CSS;
+        return CSSContent;
     if (equalIgnoringCase(mimeType, "text/html"))
-        return HTML;
+        return HTMLContent;
     if (DOMImplementation::isXMLMIMEType(mimeType))
-        return XML;
-    return PlainText;
+        return XMLContent;
+    return PlainTextContent;
 }
 
 const WTF::TextEncoding& TextResourceDecoder::defaultEncoding(ContentType contentType, const WTF::TextEncoding& specifiedDefaultEncoding)
 {
     // Despite 8.5 "Text/xml with Omitted Charset" of RFC 3023, we assume UTF-8 instead of US-ASCII
     // for text/xml. This matches Firefox.
-    if (contentType == XML)
+    if (contentType == XMLContent)
         return UTF8Encoding();
     if (!specifiedDefaultEncoding.isValid())
         return Latin1Encoding();
@@ -368,12 +368,12 @@
 
     bool movedDataToBuffer = false;
 
-    if (m_contentType == CSS && !m_checkedForCSSCharset) {
+    if (m_contentType == CSSContent && !m_checkedForCSSCharset) {
         if (!checkForCSSCharset(data, len, movedDataToBuffer))
             return emptyString();
     }
 
-    if ((m_contentType == HTML || m_contentType == XML) && !m_checkedForXMLCharset) {
+    if ((m_contentType == HTMLContent || m_contentType == XMLContent) && !m_checkedForXMLCharset) {
         if (!checkForXMLCharset(data, len, movedDataToBuffer))
             return emptyString();
     }
@@ -392,7 +392,7 @@
         lengthForDecode = m_buffer.size() - lengthOfBOM;
     }
 
-    if (m_contentType == HTML && !m_checkedForMetaCharset)
+    if (m_contentType == HTMLContent && !m_checkedForMetaCharset)
         checkForMetaCharset(dataForDecode, lengthForDecode);
 
     if (shouldAutoDetect()) {
@@ -406,7 +406,7 @@
     if (!m_codec)
         m_codec = newTextCodec(m_encoding);
 
-    String result = m_codec->decode(dataForDecode, lengthForDecode, false, m_contentType == XML && !m_useLenientXMLDecoding, m_sawError);
+    String result = m_codec->decode(dataForDecode, lengthForDecode, false, m_contentType == XMLContent && !m_useLenientXMLDecoding, m_sawError);
 
     m_buffer.clear();
     return result;
@@ -418,7 +418,7 @@
     // loaded, we need to detect the encoding if other conditions for
     // autodetection is satisfied.
     if (m_buffer.size() && shouldAutoDetect()
-        && ((!m_checkedForXMLCharset && (m_contentType == HTML || m_contentType == XML)) || (!m_checkedForCSSCharset && (m_contentType == CSS)))) {
+        && ((!m_checkedForXMLCharset && (m_contentType == HTMLContent || m_contentType == XMLContent)) || (!m_checkedForCSSCharset && (m_contentType == CSSContent)))) {
         WTF::TextEncoding detectedEncoding;
         if (detectTextEncoding(m_buffer.data(), m_buffer.size(), m_hintEncoding, &detectedEncoding))
             setEncoding(detectedEncoding, EncodingFromContentSniffing);
@@ -427,7 +427,7 @@
     if (!m_codec)
         m_codec = newTextCodec(m_encoding);
 
-    String result = m_codec->decode(m_buffer.data(), m_buffer.size(), true, m_contentType == XML && !m_useLenientXMLDecoding, m_sawError);
+    String result = m_codec->decode(m_buffer.data(), m_buffer.size(), true, m_contentType == XMLContent && !m_useLenientXMLDecoding, m_sawError);
     m_buffer.clear();
     m_codec.clear();
     m_checkedForBOM = false; // Skip BOM again when re-decoding.
diff --git a/Source/core/fetch/TextResourceDecoder.h b/Source/core/html/parser/TextResourceDecoder.h
similarity index 95%
rename from Source/core/fetch/TextResourceDecoder.h
rename to Source/core/html/parser/TextResourceDecoder.h
index 4c77347..5ad2ad5 100644
--- a/Source/core/fetch/TextResourceDecoder.h
+++ b/Source/core/html/parser/TextResourceDecoder.h
@@ -28,6 +28,7 @@
 
 namespace WebCore {
 
+class DocumentEncodingData;
 class HTMLMetaCharsetParser;
 
 class TextResourceDecoder {
@@ -72,7 +73,7 @@
 private:
     TextResourceDecoder(const String& mimeType, const WTF::TextEncoding& defaultEncoding, bool usesEncodingDetector);
 
-    enum ContentType { PlainText, HTML, XML, CSS }; // PlainText only checks for BOM.
+    enum ContentType { PlainTextContent, HTMLContent, XMLContent, CSSContent }; // PlainText only checks for BOM.
     static ContentType determineContentType(const String& mimeType);
     static const WTF::TextEncoding& defaultEncoding(ContentType, const WTF::TextEncoding& defaultEncoding);
 
diff --git a/Source/core/html/parser/XSSAuditor.cpp b/Source/core/html/parser/XSSAuditor.cpp
index 1fb6a0f..2e07967 100644
--- a/Source/core/html/parser/XSSAuditor.cpp
+++ b/Source/core/html/parser/XSSAuditor.cpp
@@ -31,20 +31,27 @@
 #include "SVGNames.h"
 #include "XLinkNames.h"
 #include "core/dom/Document.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/frame/Frame.h"
 #include "core/html/HTMLParamElement.h"
 #include "core/html/parser/HTMLDocumentParser.h"
 #include "core/html/parser/HTMLParserIdioms.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/html/parser/XSSAuditorDelegate.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/JSONValues.h"
 #include "platform/network/FormData.h"
 #include "platform/text/DecodeEscapeSequences.h"
 #include "wtf/MainThread.h"
 
+namespace {
+
+// SecurityOrigin::urlWithUniqueSecurityOrigin() can't be used cross-thread, or we'd use it instead.
+const char kURLWithUniqueOrigin[] = "data:,";
+
+} // namespace
+
 namespace WebCore {
 
 using namespace HTMLNames;
@@ -220,9 +227,6 @@
 
 void XSSAuditor::init(Document* document, XSSAuditorDelegate* auditorDelegate)
 {
-    const size_t miniumLengthForSuffixTree = 512; // FIXME: Tune this parameter.
-    const int suffixTreeDepth = 5;
-
     ASSERT(isMainThread());
     if (m_state != Uninitialized)
         return;
@@ -257,11 +261,6 @@
     if (document->encoding().isValid())
         m_encoding = document->encoding();
 
-    m_decodedURL = fullyDecodeString(m_documentURL.string(), m_encoding);
-    if (m_decodedURL.find(isRequiredForInjection) == kNotFound)
-        m_decodedURL = String();
-
-    String httpBodyAsString;
     if (DocumentLoader* documentLoader = document->frame()->loader().documentLoader()) {
         DEFINE_STATIC_LOCAL(const AtomicString, XSSProtectionHeader, ("X-XSS-Protection", AtomicString::ConstructFromLiteral));
         const AtomicString& headerValue = documentLoader->response().httpHeaderField(XSSProtectionHeader);
@@ -291,23 +290,40 @@
         // FIXME: Combine the two report URLs in some reasonable way.
         if (auditorDelegate)
             auditorDelegate->setReportURL(xssProtectionReportURL.copy());
-        FormData* httpBody = documentLoader->originalRequest().httpBody();
-        if (httpBody && !httpBody->isEmpty()) {
-            httpBodyAsString = httpBody->flattenToString();
-            if (!httpBodyAsString.isEmpty()) {
-                m_decodedHTTPBody = fullyDecodeString(httpBodyAsString, m_encoding);
-                if (m_decodedHTTPBody.find(isRequiredForInjection) == kNotFound)
-                    m_decodedHTTPBody = String();
-                if (m_decodedHTTPBody.length() >= miniumLengthForSuffixTree)
-                    m_decodedHTTPBodySuffixTree = adoptPtr(new SuffixTree<ASCIICodebook>(m_decodedHTTPBody, suffixTreeDepth));
-            }
-        }
+
+        FormData* httpBody = documentLoader->request().httpBody();
+        if (httpBody && !httpBody->isEmpty())
+            m_httpBodyAsString = httpBody->flattenToString();
     }
 
-    if (m_decodedURL.isEmpty() && m_decodedHTTPBody.isEmpty()) {
-        m_isEnabled = false;
+    setEncoding(m_encoding);
+}
+
+void XSSAuditor::setEncoding(const WTF::TextEncoding& encoding)
+{
+    const size_t miniumLengthForSuffixTree = 512; // FIXME: Tune this parameter.
+    const int suffixTreeDepth = 5;
+
+    if (!encoding.isValid())
         return;
+
+    m_encoding = encoding;
+
+    m_decodedURL = fullyDecodeString(m_documentURL.string(), m_encoding);
+    if (m_decodedURL.find(isRequiredForInjection) == kNotFound)
+        m_decodedURL = String();
+
+    if (!m_httpBodyAsString.isEmpty()) {
+        m_decodedHTTPBody = fullyDecodeString(m_httpBodyAsString, m_encoding);
+        m_httpBodyAsString = String();
+        if (m_decodedHTTPBody.find(isRequiredForInjection) == kNotFound)
+            m_decodedHTTPBody = String();
+            if (m_decodedHTTPBody.length() >= miniumLengthForSuffixTree)
+                m_decodedHTTPBodySuffixTree = adoptPtr(new SuffixTree<ASCIICodebook>(m_decodedHTTPBody, suffixTreeDepth));
     }
+
+    if (m_decodedURL.isEmpty() && m_decodedHTTPBody.isEmpty())
+        m_isEnabled = false;
 }
 
 PassOwnPtr<XSSInfo> XSSAuditor::filterToken(const FilterTokenRequest& request)
@@ -500,7 +516,7 @@
     ASSERT(request.token.type() == HTMLToken::StartTag);
     ASSERT(hasName(request.token, formTag));
 
-    return eraseAttributeIfInjected(request, actionAttr, blankURL().string());
+    return eraseAttributeIfInjected(request, actionAttr, kURLWithUniqueOrigin);
 }
 
 bool XSSAuditor::filterInputToken(const FilterTokenRequest& request)
@@ -508,7 +524,7 @@
     ASSERT(request.token.type() == HTMLToken::StartTag);
     ASSERT(hasName(request.token, inputTag));
 
-    return eraseAttributeIfInjected(request, formactionAttr, blankURL().string(), SrcLikeAttribute);
+    return eraseAttributeIfInjected(request, formactionAttr, kURLWithUniqueOrigin, SrcLikeAttribute);
 }
 
 bool XSSAuditor::filterButtonToken(const FilterTokenRequest& request)
@@ -516,7 +532,7 @@
     ASSERT(request.token.type() == HTMLToken::StartTag);
     ASSERT(hasName(request.token, buttonTag));
 
-    return eraseAttributeIfInjected(request, formactionAttr, blankURL().string(), SrcLikeAttribute);
+    return eraseAttributeIfInjected(request, formactionAttr, kURLWithUniqueOrigin, SrcLikeAttribute);
 }
 
 bool XSSAuditor::eraseDangerousAttributesIfInjected(const FilterTokenRequest& request)
@@ -725,7 +741,8 @@
 {
     return m_documentURL.isSafeToSendToAnotherThread()
         && m_decodedURL.isSafeToSendToAnotherThread()
-        && m_decodedHTTPBody.isSafeToSendToAnotherThread();
+        && m_decodedHTTPBody.isSafeToSendToAnotherThread()
+        && m_httpBodyAsString.isSafeToSendToAnotherThread();
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/parser/XSSAuditor.h b/Source/core/html/parser/XSSAuditor.h
index db2655f..37e463c 100644
--- a/Source/core/html/parser/XSSAuditor.h
+++ b/Source/core/html/parser/XSSAuditor.h
@@ -64,6 +64,8 @@
     PassOwnPtr<XSSInfo> filterToken(const FilterTokenRequest&);
     bool isSafeToSendToAnotherThread() const;
 
+    void setEncoding(const WTF::TextEncoding&);
+
 private:
     static const size_t kMaximumFragmentLengthTarget = 100;
 
@@ -115,6 +117,7 @@
 
     String m_decodedURL;
     String m_decodedHTTPBody;
+    String m_httpBodyAsString;
     OwnPtr<SuffixTree<ASCIICodebook> > m_decodedHTTPBodySuffixTree;
 
     State m_state;
diff --git a/Source/core/html/parser/XSSAuditorDelegate.cpp b/Source/core/html/parser/XSSAuditorDelegate.cpp
index f7f8bfd..8e3e0b9 100644
--- a/Source/core/html/parser/XSSAuditorDelegate.cpp
+++ b/Source/core/html/parser/XSSAuditorDelegate.cpp
@@ -116,7 +116,7 @@
     }
 
     if (xssInfo.m_didBlockEntirePage)
-        m_document->frame()->navigationScheduler().scheduleLocationChange(m_document->securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
+        m_document->frame()->navigationScheduler().scheduleLocationChange(m_document, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/parser/create-html-entity-table b/Source/core/html/parser/create-html-entity-table
index 8c408fe..3b9ca45 100755
--- a/Source/core/html/parser/create-html-entity-table
+++ b/Source/core/html/parser/create-html-entity-table
@@ -42,10 +42,6 @@
     return "%s%s" % (entity, postfix)
 
 
-def convert_entity_to_uchar_array(entity):
-    return "{'%s'}" % "', '".join(entity)
-
-
 def convert_value_to_int(value):
     if not value:
         return "0";
@@ -113,9 +109,7 @@
 """)
 
 for entry in entries:
-    output_file.write("static const UChar %s[] = %s;\n" % (
-        convert_entity_to_cpp_name(entry[ENTITY]),
-        convert_entity_to_uchar_array(entry[ENTITY])))
+    output_file.write("static const LChar %s[] = \"%s\";\n" % (convert_entity_to_cpp_name(entry[ENTITY]), entry[ENTITY]))
 
 output_file.write("""
 static const HTMLEntityTableEntry staticEntityTable[%s] = {\n""" % entity_count)
diff --git a/Source/core/html/shadow/ClearButtonElement.cpp b/Source/core/html/shadow/ClearButtonElement.cpp
index cb928e8..f3e0d1d 100644
--- a/Source/core/html/shadow/ClearButtonElement.cpp
+++ b/Source/core/html/shadow/ClearButtonElement.cpp
@@ -46,7 +46,7 @@
 PassRefPtr<ClearButtonElement> ClearButtonElement::create(Document& document, ClearButtonOwner& clearButtonOwner)
 {
     RefPtr<ClearButtonElement> element = adoptRef(new ClearButtonElement(document, clearButtonOwner));
-    element->setPseudo(AtomicString("-webkit-clear-button", AtomicString::ConstructFromLiteral));
+    element->setShadowPseudoId(AtomicString("-webkit-clear-button", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::clearButton());
     return element.release();
 }
diff --git a/Source/core/html/shadow/ClearButtonElement.h b/Source/core/html/shadow/ClearButtonElement.h
index 00bf5aa..6acf100 100644
--- a/Source/core/html/shadow/ClearButtonElement.h
+++ b/Source/core/html/shadow/ClearButtonElement.h
@@ -48,19 +48,15 @@
 private:
     ClearButtonElement(Document&, ClearButtonOwner&);
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual bool isMouseFocusable() const { return false; }
-    virtual void defaultEventHandler(Event*);
+    virtual bool isMouseFocusable() const OVERRIDE { return false; }
+    virtual void defaultEventHandler(Event*) OVERRIDE;
     virtual bool isClearButtonElement() const OVERRIDE;
 
     ClearButtonOwner* m_clearButtonOwner;
     bool m_capturing;
 };
 
-inline ClearButtonElement* toClearButtonElement(Element* element)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isClearButtonElement());
-    return static_cast<ClearButtonElement*>(element);
-}
+DEFINE_TYPE_CASTS(ClearButtonElement, Element, element, element->isClearButtonElement(), element.isClearButtonElement());
 
 } // namespace
 
diff --git a/Source/core/html/shadow/DateTimeEditElement.cpp b/Source/core/html/shadow/DateTimeEditElement.cpp
index eb3508e..d820a5e 100644
--- a/Source/core/html/shadow/DateTimeEditElement.cpp
+++ b/Source/core/html/shadow/DateTimeEditElement.cpp
@@ -402,7 +402,7 @@
     DEFINE_STATIC_LOCAL(AtomicString, textPseudoId, ("-webkit-datetime-edit-text", AtomicString::ConstructFromLiteral));
     ASSERT(text.length());
     RefPtr<HTMLDivElement> element = HTMLDivElement::create(m_editElement.document());
-    element->setPseudo(textPseudoId);
+    element->setShadowPseudoId(textPseudoId);
     if (m_parameters.locale.isRTL() && text.length()) {
         Direction dir = direction(text[0]);
         if (dir == SegmentSeparator || dir == WhiteSpaceNeutral || dir == OtherNeutral)
@@ -484,7 +484,7 @@
 PassRefPtr<DateTimeEditElement> DateTimeEditElement::create(Document& document, EditControlOwner& editControlOwner)
 {
     RefPtr<DateTimeEditElement> container = adoptRef(new DateTimeEditElement(document, editControlOwner));
-    container->setPseudo(AtomicString("-webkit-datetime-edit", AtomicString::ConstructFromLiteral));
+    container->setShadowPseudoId(AtomicString("-webkit-datetime-edit", AtomicString::ConstructFromLiteral));
     container->setAttribute(idAttr, ShadowElementNames::dateTimeEdit());
     return container.release();
 }
@@ -652,7 +652,7 @@
     DEFINE_STATIC_LOCAL(AtomicString, fieldsWrapperPseudoId, ("-webkit-datetime-edit-fields-wrapper", AtomicString::ConstructFromLiteral));
     if (!firstChild()) {
         RefPtr<HTMLDivElement> element = HTMLDivElement::create(document());
-        element->setPseudo(fieldsWrapperPseudoId);
+        element->setShadowPseudoId(fieldsWrapperPseudoId);
         appendChild(element.get());
     }
     Element* fieldsWrapper = fieldsWrapperElement();
@@ -685,7 +685,7 @@
             if (childNode == lastChildToBeRemoved)
                 break;
         }
-        setNeedsStyleRecalc();
+        setNeedsStyleRecalc(SubtreeStyleChange);
     }
 }
 
diff --git a/Source/core/html/shadow/DateTimeEditElement.h b/Source/core/html/shadow/DateTimeEditElement.h
index 70bf479..ede8764 100644
--- a/Source/core/html/shadow/DateTimeEditElement.h
+++ b/Source/core/html/shadow/DateTimeEditElement.h
@@ -136,24 +136,20 @@
     virtual bool isDateTimeEditElement() const OVERRIDE;
 
     // DateTimeFieldElement::FieldOwner functions.
-    virtual void didBlurFromField() OVERRIDE FINAL;
-    virtual void didFocusOnField() OVERRIDE FINAL;
-    virtual void fieldValueChanged() OVERRIDE FINAL;
-    virtual bool focusOnNextField(const DateTimeFieldElement&) OVERRIDE FINAL;
-    virtual bool focusOnPreviousField(const DateTimeFieldElement&) OVERRIDE FINAL;
-    virtual bool isFieldOwnerDisabled() const OVERRIDE FINAL;
-    virtual bool isFieldOwnerReadOnly() const OVERRIDE FINAL;
-    virtual AtomicString localeIdentifier() const OVERRIDE FINAL;
+    virtual void didBlurFromField() OVERRIDE;
+    virtual void didFocusOnField() OVERRIDE;
+    virtual void fieldValueChanged() OVERRIDE;
+    virtual bool focusOnNextField(const DateTimeFieldElement&) OVERRIDE;
+    virtual bool focusOnPreviousField(const DateTimeFieldElement&) OVERRIDE;
+    virtual bool isFieldOwnerDisabled() const OVERRIDE;
+    virtual bool isFieldOwnerReadOnly() const OVERRIDE;
+    virtual AtomicString localeIdentifier() const OVERRIDE;
 
     Vector<DateTimeFieldElement*, maximumNumberOfFields> m_fields;
     EditControlOwner* m_editControlOwner;
 };
 
-inline DateTimeEditElement* toDateTimeEditElement(Element* element)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isDateTimeEditElement());
-    return static_cast<DateTimeEditElement*>(element);
-}
+DEFINE_TYPE_CASTS(DateTimeEditElement, Element, element, element->isDateTimeEditElement(), element.isDateTimeEditElement());
 
 } // namespace WebCore
 
diff --git a/Source/core/html/shadow/DateTimeFieldElement.cpp b/Source/core/html/shadow/DateTimeFieldElement.cpp
index 31cdb06..1746b01 100644
--- a/Source/core/html/shadow/DateTimeFieldElement.cpp
+++ b/Source/core/html/shadow/DateTimeFieldElement.cpp
@@ -152,12 +152,12 @@
 {
     // On accessibility, DateTimeFieldElement acts like spin button.
     setAttribute(roleAttr, AtomicString("spinbutton", AtomicString::ConstructFromLiteral));
-    setAttribute(aria_valuetextAttr, emptyValueAXText());
-    setAttribute(aria_valueminAttr, String::number(axMinimum));
-    setAttribute(aria_valuemaxAttr, String::number(axMaximum));
+    setAttribute(aria_valuetextAttr, AtomicString(emptyValueAXText()));
+    setAttribute(aria_valueminAttr, AtomicString::number(axMinimum));
+    setAttribute(aria_valuemaxAttr, AtomicString::number(axMaximum));
 
-    setAttribute(aria_helpAttr, axHelpText);
-    setPseudo(pseudo);
+    setAttribute(aria_helpAttr, AtomicString(axHelpText));
+    setShadowPseudoId(pseudo);
     appendChild(Text::create(document(), visibleValue()));
 }
 
@@ -201,7 +201,7 @@
 {
     // Set HTML attribute disabled to change apperance.
     setBooleanAttribute(disabledAttr, true);
-    setNeedsStyleRecalc();
+    setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 bool DateTimeFieldElement::supportsFocus() const
@@ -220,10 +220,10 @@
 
     textNode->replaceWholeText(newVisibleValue);
     if (hasValue()) {
-        setAttribute(aria_valuetextAttr, newVisibleValue);
-        setAttribute(aria_valuenowAttr, String::number(valueForARIAValueNow()));
+        setAttribute(aria_valuetextAttr, AtomicString(newVisibleValue));
+        setAttribute(aria_valuenowAttr, AtomicString::number(valueForARIAValueNow()));
     } else {
-        setAttribute(aria_valuetextAttr, emptyValueAXText());
+        setAttribute(aria_valuetextAttr, AtomicString(emptyValueAXText()));
         removeAttribute(aria_valuenowAttr);
     }
 
diff --git a/Source/core/html/shadow/DateTimeFieldElement.h b/Source/core/html/shadow/DateTimeFieldElement.h
index a2e42a9..66ff3b7 100644
--- a/Source/core/html/shadow/DateTimeFieldElement.h
+++ b/Source/core/html/shadow/DateTimeFieldElement.h
@@ -92,7 +92,7 @@
 
 private:
     void defaultKeyboardEventHandler(KeyboardEvent*);
-    virtual bool isDateTimeFieldElement() const OVERRIDE;
+    virtual bool isDateTimeFieldElement() const OVERRIDE FINAL;
     bool isFieldOwnerDisabled() const;
     bool isFieldOwnerReadOnly() const;
     virtual bool supportsFocus() const OVERRIDE FINAL;
diff --git a/Source/core/html/shadow/DateTimeFieldElements.h b/Source/core/html/shadow/DateTimeFieldElements.h
index fb8ef52..d2a2da4 100644
--- a/Source/core/html/shadow/DateTimeFieldElements.h
+++ b/Source/core/html/shadow/DateTimeFieldElements.h
@@ -42,9 +42,9 @@
     DateTimeAMPMFieldElement(Document&, FieldOwner&, const Vector<String>&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 };
 
 class DateTimeDayFieldElement FINAL : public DateTimeNumericFieldElement {
@@ -57,9 +57,9 @@
     DateTimeDayFieldElement(Document&, FieldOwner&, const String& placeholder, const Range&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 };
 
 class DateTimeHourFieldElementBase : public DateTimeNumericFieldElement {
@@ -71,8 +71,8 @@
 
 private:
     // DateTimeFieldElement functions.
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 };
 
 class DateTimeHour11FieldElement FINAL : public DateTimeHourFieldElementBase {
@@ -85,8 +85,8 @@
     DateTimeHour11FieldElement(Document&, FieldOwner&, const Range& hour23Range, const Step&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsInteger(int, EventBehavior = DispatchNoEvent) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsInteger(int, EventBehavior = DispatchNoEvent) OVERRIDE;
 };
 
 class DateTimeHour12FieldElement FINAL : public DateTimeHourFieldElementBase {
@@ -99,8 +99,8 @@
     DateTimeHour12FieldElement(Document&, FieldOwner&, const Range& hour23Range, const Step&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsInteger(int, EventBehavior = DispatchNoEvent) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsInteger(int, EventBehavior = DispatchNoEvent) OVERRIDE;
 };
 
 class DateTimeHour23FieldElement FINAL : public DateTimeHourFieldElementBase {
@@ -113,8 +113,8 @@
     DateTimeHour23FieldElement(Document&, FieldOwner&, const Range& hour23Range, const Step&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsInteger(int, EventBehavior = DispatchNoEvent) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsInteger(int, EventBehavior = DispatchNoEvent) OVERRIDE;
 };
 
 class DateTimeHour24FieldElement FINAL : public DateTimeHourFieldElementBase {
@@ -127,8 +127,8 @@
     DateTimeHour24FieldElement(Document&, FieldOwner&, const Range& hour23Range, const Step&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsInteger(int, EventBehavior = DispatchNoEvent) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsInteger(int, EventBehavior = DispatchNoEvent) OVERRIDE;
 };
 
 class DateTimeMillisecondFieldElement FINAL : public DateTimeNumericFieldElement {
@@ -141,9 +141,9 @@
     DateTimeMillisecondFieldElement(Document&, FieldOwner&, const Range&, const Step&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 };
 
 class DateTimeMinuteFieldElement FINAL : public DateTimeNumericFieldElement {
@@ -156,9 +156,9 @@
     DateTimeMinuteFieldElement(Document&, FieldOwner&, const Range&, const Step&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 };
 
 class DateTimeMonthFieldElement FINAL : public DateTimeNumericFieldElement {
@@ -171,9 +171,9 @@
     DateTimeMonthFieldElement(Document&, FieldOwner&, const String& placeholder, const Range&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 };
 
 class DateTimeSecondFieldElement FINAL : public DateTimeNumericFieldElement {
@@ -186,9 +186,9 @@
     DateTimeSecondFieldElement(Document&, FieldOwner&, const Range&, const Step&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 };
 
 class DateTimeSymbolicMonthFieldElement FINAL : public DateTimeSymbolicFieldElement {
@@ -201,9 +201,9 @@
     DateTimeSymbolicMonthFieldElement(Document&, FieldOwner&, const Vector<String>&, int minimum, int maximum);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 };
 
 class DateTimeWeekFieldElement FINAL : public DateTimeNumericFieldElement {
@@ -216,9 +216,9 @@
     DateTimeWeekFieldElement(Document&, FieldOwner&, const Range&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 };
 
 class DateTimeYearFieldElement FINAL : public DateTimeNumericFieldElement {
@@ -247,13 +247,13 @@
     DateTimeYearFieldElement(Document&, FieldOwner&, const Parameters&);
 
     // DateTimeFieldElement functions.
-    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
-    virtual void setValueAsDate(const DateComponents&) OVERRIDE FINAL;
-    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE FINAL;
+    virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE;
+    virtual void setValueAsDate(const DateComponents&) OVERRIDE;
+    virtual void setValueAsDateTimeFieldsState(const DateTimeFieldsState&) OVERRIDE;
 
     // DateTimeNumericFieldElement functions.
-    virtual int defaultValueForStepDown() const OVERRIDE FINAL;
-    virtual int defaultValueForStepUp() const OVERRIDE FINAL;
+    virtual int defaultValueForStepDown() const OVERRIDE;
+    virtual int defaultValueForStepUp() const OVERRIDE;
 
     bool m_minIsSpecified;
     bool m_maxIsSpecified;
diff --git a/Source/core/html/shadow/DateTimeNumericFieldElement.cpp b/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
index 6c3f5ef..569d72e 100644
--- a/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
+++ b/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
@@ -37,8 +37,6 @@
 
 namespace WebCore {
 
-static const DOMTimeStamp typeAheadTimeout = 1000;
-
 int DateTimeNumericFieldElement::Range::clampValue(int value) const
 {
     return std::min(std::max(value, minimum), maximum);
@@ -53,7 +51,6 @@
 
 DateTimeNumericFieldElement::DateTimeNumericFieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Range& hardLimits, const String& placeholder, const DateTimeNumericFieldElement::Step& step)
     : DateTimeFieldElement(document, fieldOwner)
-    , m_lastDigitCharTime(0)
     , m_placeholder(placeholder)
     , m_range(range)
     , m_hardLimits(hardLimits)
@@ -125,13 +122,14 @@
     if (digit < 0 || digit > 9)
         return;
 
-    DOMTimeStamp delta = keyboardEvent->timeStamp() - m_lastDigitCharTime;
-    m_lastDigitCharTime = keyboardEvent->timeStamp();
-
-    if (delta > typeAheadTimeout)
+    unsigned maximumLength = DateTimeNumericFieldElement::formatValue(m_range.maximum).length();
+    if (m_typeAheadBuffer.length() >= maximumLength) {
+        String current = m_typeAheadBuffer.toString();
         m_typeAheadBuffer.clear();
+        unsigned desiredLength = maximumLength - 1;
+        m_typeAheadBuffer.append(current, current.length() - desiredLength, desiredLength);
+    }
     m_typeAheadBuffer.append(number);
-
     int newValue = typeAheadValue();
     if (newValue >= m_hardLimits.minimum)
         setValueAsInteger(newValue, DispatchEvent);
@@ -140,7 +138,7 @@
         updateVisibleValue(DispatchEvent);
     }
 
-    if (m_typeAheadBuffer.length() >= DateTimeNumericFieldElement::formatValue(m_range.maximum).length() || newValue * 10 > m_range.maximum)
+    if (m_typeAheadBuffer.length() >= maximumLength || newValue * 10 > m_range.maximum)
         focusOnNextField();
 
     keyboardEvent->setDefaultHandled();
diff --git a/Source/core/html/shadow/DateTimeNumericFieldElement.h b/Source/core/html/shadow/DateTimeNumericFieldElement.h
index e38e210..9b96fb5 100644
--- a/Source/core/html/shadow/DateTimeNumericFieldElement.h
+++ b/Source/core/html/shadow/DateTimeNumericFieldElement.h
@@ -92,7 +92,6 @@
     int roundDown(int) const;
     int typeAheadValue() const;
 
-    DOMTimeStamp m_lastDigitCharTime;
     const String m_placeholder;
     const Range m_range;
     const Range m_hardLimits;
diff --git a/Source/core/html/shadow/DetailsMarkerControl.h b/Source/core/html/shadow/DetailsMarkerControl.h
index 118063e..b89bb26 100644
--- a/Source/core/html/shadow/DetailsMarkerControl.h
+++ b/Source/core/html/shadow/DetailsMarkerControl.h
@@ -44,8 +44,8 @@
     static PassRefPtr<DetailsMarkerControl> create(Document&);
 
 private:
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
     HTMLSummaryElement* summaryElement();
 };
@@ -53,7 +53,7 @@
 inline PassRefPtr<DetailsMarkerControl> DetailsMarkerControl::create(Document& document)
 {
     RefPtr<DetailsMarkerControl> element = adoptRef(new DetailsMarkerControl(document));
-    element->setPseudo(AtomicString("-webkit-details-marker", AtomicString::ConstructFromLiteral));
+    element->setShadowPseudoId(AtomicString("-webkit-details-marker", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
diff --git a/Source/core/html/shadow/HTMLContentElement.cpp b/Source/core/html/shadow/HTMLContentElement.cpp
index 8169129..69faf7f 100644
--- a/Source/core/html/shadow/HTMLContentElement.cpp
+++ b/Source/core/html/shadow/HTMLContentElement.cpp
@@ -28,7 +28,7 @@
 #include "core/html/shadow/HTMLContentElement.h"
 
 #include "HTMLNames.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/SelectorChecker.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/dom/QualifiedName.h"
@@ -60,7 +60,7 @@
 {
     ASSERT(m_shouldParseSelect);
 
-    CSSParser parser(document());
+    BisonCSSParser parser(CSSParserContext(document(), 0));
     parser.parseSelector(m_select, m_selectorList);
     m_shouldParseSelect = false;
     m_isValidSelector = validateSelect();
@@ -91,7 +91,7 @@
     if (!m_selectorList.isValid())
         return false;
 
-    for (const CSSSelector* selector = m_selectorList.first(); selector; selector = m_selectorList.next(selector)) {
+    for (const CSSSelector* selector = m_selectorList.first(); selector; selector = m_selectorList.next(*selector)) {
         if (!selector->isCompound())
             return false;
     }
@@ -99,7 +99,7 @@
     return true;
 }
 
-static inline bool checkOneSelector(const CSSSelector* selector, const Vector<Node*, 32>& siblings, int nth)
+static inline bool checkOneSelector(const CSSSelector& selector, const Vector<Node*, 32>& siblings, int nth)
 {
     Element* element = toElement(siblings[nth]);
     SelectorChecker selectorChecker(element->document(), SelectorChecker::CollectingCSSRules);
@@ -110,8 +110,8 @@
 
 bool HTMLContentElement::matchSelector(const Vector<Node*, 32>& siblings, int nth) const
 {
-    for (const CSSSelector* selector = selectorList().first(); selector; selector = CSSSelectorList::next(selector)) {
-        if (checkOneSelector(selector, siblings, nth))
+    for (const CSSSelector* selector = selectorList().first(); selector; selector = CSSSelectorList::next(*selector)) {
+        if (checkOneSelector(*selector, siblings, nth))
             return true;
     }
     return false;
diff --git a/Source/core/html/shadow/HTMLContentElement.h b/Source/core/html/shadow/HTMLContentElement.h
index b8f0f4f..2b60b19 100644
--- a/Source/core/html/shadow/HTMLContentElement.h
+++ b/Source/core/html/shadow/HTMLContentElement.h
@@ -90,16 +90,6 @@
     return matchSelector(siblings, nth);
 }
 
-inline bool isHTMLContentElement(const Node* node)
-{
-    return node->hasTagName(HTMLNames::contentTag);
-}
-
-inline bool isHTMLContentElement(const Element* element)
-{
-    return element->hasTagName(HTMLNames::contentTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLContentElement, hasTagName(HTMLNames::contentTag));
 
 }
diff --git a/Source/core/html/shadow/HTMLShadowElement.h b/Source/core/html/shadow/HTMLShadowElement.h
index 77741ec..435a057 100644
--- a/Source/core/html/shadow/HTMLShadowElement.h
+++ b/Source/core/html/shadow/HTMLShadowElement.h
@@ -49,12 +49,6 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode* insertionPoint) OVERRIDE;
 };
 
-inline bool isHTMLShadowElement(const Node* node)
-{
-    ASSERT(node);
-    return node->hasTagName(HTMLNames::shadowTag);
-}
-
 DEFINE_NODE_TYPE_CASTS(HTMLShadowElement, hasTagName(HTMLNames::shadowTag));
 
 } // namespace WebCore
diff --git a/Source/core/html/shadow/HTMLShadowElement.idl b/Source/core/html/shadow/HTMLShadowElement.idl
index faceace..44bc357 100644
--- a/Source/core/html/shadow/HTMLShadowElement.idl
+++ b/Source/core/html/shadow/HTMLShadowElement.idl
@@ -30,6 +30,5 @@
 
 interface HTMLShadowElement : HTMLElement {
     attribute boolean resetStyleInheritance;
-    [DeprecateAs=HTMLShadowElementOlderShadowRoot] readonly attribute ShadowRoot olderShadowRoot;
     [RuntimeEnabled=ShadowDOM] NodeList getDistributedNodes();
 };
diff --git a/Source/core/html/shadow/MediaControlElementTypes.cpp b/Source/core/html/shadow/MediaControlElementTypes.cpp
index dc7f986..f8e0d5f 100644
--- a/Source/core/html/shadow/MediaControlElementTypes.cpp
+++ b/Source/core/html/shadow/MediaControlElementTypes.cpp
@@ -82,14 +82,6 @@
     m_element->removeInlineStyleProperty(CSSPropertyDisplay);
 }
 
-bool MediaControlElement::isShowing() const
-{
-    const StylePropertySet* propertySet = m_element->inlineStyle();
-    // Following the code from show() and hide() above, we only have
-    // to check for the presense of inline display.
-    return (!propertySet || !propertySet->getPropertyCSSValue(CSSPropertyDisplay));
-}
-
 void MediaControlElement::setDisplayType(MediaControlElementType displayType)
 {
     if (displayType == m_displayType)
diff --git a/Source/core/html/shadow/MediaControlElementTypes.h b/Source/core/html/shadow/MediaControlElementTypes.h
index 6293e6d..e80ee79 100644
--- a/Source/core/html/shadow/MediaControlElementTypes.h
+++ b/Source/core/html/shadow/MediaControlElementTypes.h
@@ -38,17 +38,12 @@
 
 namespace WebCore {
 
-// Must match WebKitSystemInterface.h
 enum MediaControlElementType {
     MediaEnterFullscreenButton = 0,
     MediaMuteButton,
     MediaPlayButton,
-    MediaSeekBackButton,
-    MediaSeekForwardButton,
     MediaSlider,
     MediaSliderThumb,
-    MediaRewindButton,
-    MediaReturnToRealtimeButton,
     MediaShowClosedCaptionsButton,
     MediaHideClosedCaptionsButton,
     MediaUnMuteButton,
@@ -63,7 +58,6 @@
     MediaVolumeSliderThumb,
     MediaFullScreenVolumeSlider,
     MediaFullScreenVolumeSliderThumb,
-    MediaVolumeSliderMuteButton,
     MediaTextTrackDisplayContainer,
     MediaTextTrackDisplay,
     MediaExitFullscreenButton,
@@ -79,22 +73,19 @@
 
 class MediaControlElement {
 public:
-    virtual void hide();
-    virtual void show();
-    virtual bool isShowing() const;
+    void hide();
+    void show();
 
-    virtual MediaControlElementType displayType() { return m_displayType; }
-    virtual const AtomicString& pseudo() const = 0;
+    MediaControlElementType displayType() { return m_displayType; }
 
-    virtual void setMediaController(MediaControllerInterface* controller) { m_mediaController = controller; }
-    virtual MediaControllerInterface* mediaController() const { return m_mediaController; }
+    void setMediaController(MediaControllerInterface* controller) { m_mediaController = controller; }
+    MediaControllerInterface* mediaController() const { return m_mediaController; }
 
 protected:
     explicit MediaControlElement(MediaControlElementType, HTMLElement*);
     ~MediaControlElement() { }
 
-    virtual void setDisplayType(MediaControlElementType);
-    virtual bool isMediaControlElement() const { return true; }
+    void setDisplayType(MediaControlElementType);
 
 private:
     MediaControllerInterface* m_mediaController;
@@ -106,7 +97,7 @@
 
 class MediaControlDivElement : public HTMLDivElement, public MediaControlElement {
 protected:
-    virtual bool isMediaControlElement() const OVERRIDE { return MediaControlElement::isMediaControlElement(); }
+    virtual bool isMediaControlElement() const OVERRIDE FINAL { return true; }
     explicit MediaControlDivElement(Document&, MediaControlElementType);
 };
 
@@ -114,7 +105,7 @@
 
 class MediaControlInputElement : public HTMLInputElement, public MediaControlElement {
 protected:
-    virtual bool isMediaControlElement() const OVERRIDE { return MediaControlElement::isMediaControlElement(); }
+    virtual bool isMediaControlElement() const OVERRIDE FINAL { return true; }
     explicit MediaControlInputElement(Document&, MediaControlElementType);
 
 private:
diff --git a/Source/core/html/shadow/MediaControlElements.cpp b/Source/core/html/shadow/MediaControlElements.cpp
index fb337df..2c1ad6e 100644
--- a/Source/core/html/shadow/MediaControlElements.cpp
+++ b/Source/core/html/shadow/MediaControlElements.cpp
@@ -43,8 +43,7 @@
 #include "core/html/track/vtt/VTTRegionList.h"
 #include "core/page/EventHandler.h"
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderMediaControlElements.h"
 #include "core/rendering/RenderSlider.h"
 #include "core/rendering/RenderTheme.h"
@@ -75,7 +74,7 @@
     return adoptRef(new MediaControlPanelElement(document));
 }
 
-const AtomicString& MediaControlPanelElement::pseudo() const
+const AtomicString& MediaControlPanelElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-panel", AtomicString::ConstructFromLiteral));
     return id;
@@ -258,7 +257,7 @@
     return adoptRef(new MediaControlPanelEnclosureElement(document));
 }
 
-const AtomicString& MediaControlPanelEnclosureElement::pseudo() const
+const AtomicString& MediaControlPanelEnclosureElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-enclosure", AtomicString::ConstructFromLiteral));
     return id;
@@ -277,7 +276,7 @@
     return adoptRef(new MediaControlOverlayEnclosureElement(document));
 }
 
-const AtomicString& MediaControlOverlayEnclosureElement::pseudo() const
+const AtomicString& MediaControlOverlayEnclosureElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-overlay-enclosure", AtomicString::ConstructFromLiteral));
     return id;
@@ -309,7 +308,7 @@
     MediaControlMuteButtonElement::defaultEventHandler(event);
 }
 
-const AtomicString& MediaControlPanelMuteButtonElement::pseudo() const
+const AtomicString& MediaControlPanelMuteButtonElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-mute-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -317,27 +316,6 @@
 
 // ----------------------------
 
-MediaControlVolumeSliderMuteButtonElement::MediaControlVolumeSliderMuteButtonElement(Document& document)
-    : MediaControlMuteButtonElement(document, MediaMuteButton)
-{
-}
-
-PassRefPtr<MediaControlVolumeSliderMuteButtonElement> MediaControlVolumeSliderMuteButtonElement::create(Document& document)
-{
-    RefPtr<MediaControlVolumeSliderMuteButtonElement> button = adoptRef(new MediaControlVolumeSliderMuteButtonElement(document));
-    button->ensureUserAgentShadowRoot();
-    button->setType("button");
-    return button.release();
-}
-
-const AtomicString& MediaControlVolumeSliderMuteButtonElement::pseudo() const
-{
-    DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-volume-slider-mute-button", AtomicString::ConstructFromLiteral));
-    return id;
-}
-
-// ----------------------------
-
 MediaControlPlayButtonElement::MediaControlPlayButtonElement(Document& document)
     : MediaControlInputElement(document, MediaPlayButton)
 {
@@ -369,7 +347,7 @@
     setDisplayType(mediaController()->canPlay() ? MediaPlayButton : MediaPauseButton);
 }
 
-const AtomicString& MediaControlPlayButtonElement::pseudo() const
+const AtomicString& MediaControlPlayButtonElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-play-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -408,7 +386,7 @@
         hide();
 }
 
-const AtomicString& MediaControlOverlayPlayButtonElement::pseudo() const
+const AtomicString& MediaControlOverlayPlayButtonElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-overlay-play-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -452,7 +430,7 @@
     HTMLInputElement::defaultEventHandler(event);
 }
 
-const AtomicString& MediaControlToggleClosedCaptionsButtonElement::pseudo() const
+const AtomicString& MediaControlToggleClosedCaptionsButtonElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-toggle-closed-captions-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -522,7 +500,7 @@
 }
 
 
-const AtomicString& MediaControlTimelineElement::pseudo() const
+const AtomicString& MediaControlTimelineElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-timeline", AtomicString::ConstructFromLiteral));
     return id;
@@ -545,7 +523,7 @@
     return slider.release();
 }
 
-const AtomicString& MediaControlPanelVolumeSliderElement::pseudo() const
+const AtomicString& MediaControlPanelVolumeSliderElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-volume-slider", AtomicString::ConstructFromLiteral));
     return id;
@@ -587,7 +565,7 @@
     HTMLInputElement::defaultEventHandler(event);
 }
 
-const AtomicString& MediaControlFullscreenButtonElement::pseudo() const
+const AtomicString& MediaControlFullscreenButtonElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-fullscreen-button", AtomicString::ConstructFromLiteral));
     return id;
@@ -616,7 +594,7 @@
     return id;
 }
 
-const AtomicString& MediaControlTimeRemainingDisplayElement::pseudo() const
+const AtomicString& MediaControlTimeRemainingDisplayElement::shadowPseudoId() const
 {
     return getMediaControlTimeRemainingDisplayElementShadowPseudoId();
 }
@@ -639,7 +617,7 @@
     return id;
 }
 
-const AtomicString& MediaControlCurrentTimeDisplayElement::pseudo() const
+const AtomicString& MediaControlCurrentTimeDisplayElement::shadowPseudoId() const
 {
     return getMediaControlCurrentTimeDisplayElementShadowPseudoId();
 }
@@ -670,7 +648,7 @@
     return id;
 }
 
-const AtomicString& MediaControlTextTrackContainerElement::pseudo() const
+const AtomicString& MediaControlTextTrackContainerElement::shadowPseudoId() const
 {
     return textTrackContainerElementShadowPseudoId();
 }
@@ -744,13 +722,13 @@
         hide();
 }
 
-void MediaControlTextTrackContainerElement::updateSizes(bool forceUpdate)
+void MediaControlTextTrackContainerElement::updateSizes()
 {
     HTMLMediaElement* mediaElement = toParentMediaElement(this);
     if (!mediaElement)
         return;
 
-    if (!document().page())
+    if (!document().isActive())
         return;
 
     IntRect videoBox;
@@ -759,7 +737,7 @@
         return;
     videoBox = toRenderVideo(mediaElement->renderer())->videoBox();
 
-    if (!forceUpdate && m_videoDisplaySize == videoBox)
+    if (m_videoDisplaySize == videoBox)
         return;
     m_videoDisplaySize = videoBox;
 
diff --git a/Source/core/html/shadow/MediaControlElements.h b/Source/core/html/shadow/MediaControlElements.h
index 3d631db..85d2bac 100644
--- a/Source/core/html/shadow/MediaControlElements.h
+++ b/Source/core/html/shadow/MediaControlElements.h
@@ -53,7 +53,7 @@
 private:
     explicit MediaControlPanelElement(Document&);
 
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
     void startDrag(const LayoutPoint& eventLocation);
@@ -84,7 +84,7 @@
 
 private:
     explicit MediaControlPanelEnclosureElement(Document&);
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
 };
 
 // ----------------------------
@@ -95,7 +95,7 @@
 
 private:
     explicit MediaControlOverlayEnclosureElement(Document&);
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
 };
 
 // ----------------------------
@@ -109,7 +109,7 @@
 private:
     explicit MediaControlPanelMuteButtonElement(Document&, MediaControls*);
 
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
     MediaControls* m_controls;
@@ -117,18 +117,6 @@
 
 // ----------------------------
 
-class MediaControlVolumeSliderMuteButtonElement FINAL : public MediaControlMuteButtonElement {
-public:
-    static PassRefPtr<MediaControlVolumeSliderMuteButtonElement> create(Document&);
-
-private:
-    explicit MediaControlVolumeSliderMuteButtonElement(Document&);
-    virtual const AtomicString& pseudo() const OVERRIDE;
-};
-
-
-// ----------------------------
-
 class MediaControlPlayButtonElement FINAL : public MediaControlInputElement {
 public:
     static PassRefPtr<MediaControlPlayButtonElement> create(Document&);
@@ -139,7 +127,7 @@
 private:
     explicit MediaControlPlayButtonElement(Document&);
 
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -154,7 +142,7 @@
 private:
     explicit MediaControlOverlayPlayButtonElement(Document&);
 
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -171,7 +159,7 @@
 private:
     explicit MediaControlToggleClosedCaptionsButtonElement(Document&, MediaControls*);
 
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -189,7 +177,7 @@
 private:
     explicit MediaControlTimelineElement(Document&, MediaControls*);
 
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
     MediaControls* m_controls;
@@ -203,12 +191,12 @@
 
     virtual bool willRespondToMouseClickEvents() OVERRIDE { return true; }
 
-    virtual void setIsFullscreen(bool);
+    void setIsFullscreen(bool);
 
 private:
     explicit MediaControlFullscreenButtonElement(Document&);
 
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
 };
 
@@ -220,7 +208,7 @@
 
 private:
     explicit MediaControlPanelVolumeSliderElement(Document&);
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
 };
 
 // ----------------------------
@@ -231,7 +219,7 @@
 
 private:
     explicit MediaControlTimeRemainingDisplayElement(Document&);
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
 };
 
 // ----------------------------
@@ -242,7 +230,7 @@
 
 private:
     explicit MediaControlCurrentTimeDisplayElement(Document&);
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
 };
 
 // ----------------------------
@@ -252,14 +240,14 @@
     static PassRefPtr<MediaControlTextTrackContainerElement> create(Document&);
 
     void updateDisplay();
-    void updateSizes(bool forceUpdate = false);
+    void updateSizes();
     static const AtomicString& textTrackContainerElementShadowPseudoId();
 
 private:
     explicit MediaControlTextTrackContainerElement(Document&);
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     IntRect m_videoDisplaySize;
     float m_fontSize;
diff --git a/Source/core/html/shadow/MediaControls.cpp b/Source/core/html/shadow/MediaControls.cpp
index 0e2fa81..bb3c8c2 100644
--- a/Source/core/html/shadow/MediaControls.cpp
+++ b/Source/core/html/shadow/MediaControls.cpp
@@ -28,6 +28,9 @@
 #include "core/html/shadow/MediaControls.h"
 
 #include "bindings/v8/ExceptionStatePlaceholder.h"
+#if OS(ANDROID)
+#include "core/html/shadow/MediaControlsAndroid.h"
+#endif
 
 namespace WebCore {
 
@@ -45,12 +48,104 @@
     , m_volumeSlider(0)
     , m_toggleClosedCaptionsButton(0)
     , m_fullScreenButton(0)
+    , m_durationDisplay(0)
+    , m_enclosure(0)
     , m_hideFullscreenControlsTimer(this, &MediaControls::hideFullscreenControlsTimerFired)
     , m_isFullscreen(false)
     , m_isMouseOverControls(false)
 {
 }
 
+PassRefPtr<MediaControls> MediaControls::create(Document& document)
+{
+    if (!document.page())
+        return 0;
+
+    RefPtr<MediaControls> controls;
+#if OS(ANDROID)
+    controls = adoptRef(new MediaControlsAndroid(document));
+#else
+    controls = adoptRef(new MediaControls(document));
+#endif
+
+    if (controls->initializeControls(document))
+        return controls.release();
+
+    return 0;
+}
+
+bool MediaControls::initializeControls(Document& document)
+{
+    // Create an enclosing element for the panel so we can visually offset the controls correctly.
+    RefPtr<MediaControlPanelEnclosureElement> enclosure = MediaControlPanelEnclosureElement::create(document);
+
+    RefPtr<MediaControlPanelElement> panel = MediaControlPanelElement::create(document);
+
+    TrackExceptionState exceptionState;
+
+    RefPtr<MediaControlPlayButtonElement> playButton = MediaControlPlayButtonElement::create(document);
+    m_playButton = playButton.get();
+    panel->appendChild(playButton.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    RefPtr<MediaControlTimelineElement> timeline = MediaControlTimelineElement::create(document, this);
+    m_timeline = timeline.get();
+    panel->appendChild(timeline.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    RefPtr<MediaControlCurrentTimeDisplayElement> currentTimeDisplay = MediaControlCurrentTimeDisplayElement::create(document);
+    m_currentTimeDisplay = currentTimeDisplay.get();
+    m_currentTimeDisplay->hide();
+    panel->appendChild(currentTimeDisplay.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    RefPtr<MediaControlTimeRemainingDisplayElement> durationDisplay = MediaControlTimeRemainingDisplayElement::create(document);
+    m_durationDisplay = durationDisplay.get();
+    panel->appendChild(durationDisplay.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    RefPtr<MediaControlPanelMuteButtonElement> panelMuteButton = MediaControlPanelMuteButtonElement::create(document, this);
+    m_panelMuteButton = panelMuteButton.get();
+    panel->appendChild(panelMuteButton.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    RefPtr<MediaControlPanelVolumeSliderElement> slider = MediaControlPanelVolumeSliderElement::create(document);
+    m_volumeSlider = slider.get();
+    m_volumeSlider->setClearMutedOnUserInteraction(true);
+    panel->appendChild(slider.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    RefPtr<MediaControlToggleClosedCaptionsButtonElement> toggleClosedCaptionsButton = MediaControlToggleClosedCaptionsButtonElement::create(document, this);
+    m_toggleClosedCaptionsButton = toggleClosedCaptionsButton.get();
+    panel->appendChild(toggleClosedCaptionsButton.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    RefPtr<MediaControlFullscreenButtonElement> fullscreenButton = MediaControlFullscreenButtonElement::create(document);
+    m_fullScreenButton = fullscreenButton.get();
+    panel->appendChild(fullscreenButton.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    m_panel = panel.get();
+    enclosure->appendChild(panel.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    m_enclosure = enclosure.get();
+    appendChild(enclosure.release(), exceptionState);
+    if (exceptionState.hadException())
+        return false;
+
+    return true;
+}
+
 void MediaControls::setMediaController(MediaControllerInterface* controller)
 {
     if (m_mediaController == controller)
@@ -75,6 +170,10 @@
         m_toggleClosedCaptionsButton->setMediaController(controller);
     if (m_fullScreenButton)
         m_fullScreenButton->setMediaController(controller);
+    if (m_durationDisplay)
+        m_durationDisplay->setMediaController(controller);
+    if (m_enclosure)
+        m_enclosure->setMediaController(controller);
 }
 
 void MediaControls::reset()
@@ -83,20 +182,18 @@
     if (!page)
         return;
 
+    double duration = m_mediaController->duration();
+    m_durationDisplay->setInnerText(RenderTheme::theme().formatMediaControlsTime(duration), ASSERT_NO_EXCEPTION);
+    m_durationDisplay->setCurrentValue(duration);
+
     m_playButton->updateDisplayType();
 
     updateCurrentTimeDisplay();
 
-    double duration = m_mediaController->duration();
-    if (std::isfinite(duration) || RenderTheme::theme().hasOwnDisabledStateHandlingFor(MediaSliderPart)) {
-        m_timeline->setDuration(duration);
-        m_timeline->setPosition(m_mediaController->currentTime());
-    }
+    m_timeline->setDuration(m_mediaController->duration());
+    m_timeline->setPosition(m_mediaController->currentTime());
 
-    if (m_mediaController->hasAudio() || RenderTheme::theme().hasOwnDisabledStateHandlingFor(MediaMuteButtonPart))
-        m_panelMuteButton->show();
-    else
-        m_panelMuteButton->hide();
+    m_panelMuteButton->show();
 
     if (m_volumeSlider) {
         if (!m_mediaController->hasAudio())
@@ -110,7 +207,7 @@
     refreshClosedCaptionsButtonVisibility();
 
     if (m_fullScreenButton) {
-        if (m_mediaController->supportsFullscreen() && m_mediaController->hasVideo())
+        if (m_mediaController->hasVideo())
             m_fullScreenButton->show();
         else
             m_fullScreenButton->hide();
@@ -119,29 +216,6 @@
     makeOpaque();
 }
 
-void MediaControls::reportedError()
-{
-    Page* page = document().page();
-    if (!page)
-        return;
-
-    if (!RenderTheme::theme().hasOwnDisabledStateHandlingFor(MediaMuteButtonPart)) {
-        m_panelMuteButton->hide();
-        m_volumeSlider->hide();
-    }
-
-    if (m_toggleClosedCaptionsButton && !RenderTheme::theme().hasOwnDisabledStateHandlingFor(MediaToggleClosedCaptionsButtonPart))
-        m_toggleClosedCaptionsButton->hide();
-
-    if (m_fullScreenButton && !RenderTheme::theme().hasOwnDisabledStateHandlingFor(MediaEnterFullscreenButtonPart))
-        m_fullScreenButton->hide();
-}
-
-void MediaControls::loadedMetadata()
-{
-    reset();
-}
-
 void MediaControls::show()
 {
     makeOpaque();
@@ -180,6 +254,9 @@
 
 void MediaControls::playbackStarted()
 {
+    m_currentTimeDisplay->show();
+    m_durationDisplay->hide();
+
     m_playButton->updateDisplayType();
     m_timeline->setPosition(m_mediaController->currentTime());
     updateCurrentTimeDisplay();
@@ -207,6 +284,26 @@
     stopHideFullscreenControlsTimer();
 }
 
+void MediaControls::updateCurrentTimeDisplay()
+{
+    double now = m_mediaController->currentTime();
+    double duration = m_mediaController->duration();
+
+    Page* page = document().page();
+    if (!page)
+        return;
+
+    // After seek, hide duration display and show current time.
+    if (now > 0) {
+        m_currentTimeDisplay->show();
+        m_durationDisplay->hide();
+    }
+
+    // Allow the theme to format the time.
+    m_currentTimeDisplay->setInnerText(RenderTheme::theme().formatMediaControlsCurrentTime(now, duration), IGNORE_EXCEPTION);
+    m_currentTimeDisplay->setCurrentValue(now);
+}
+
 void MediaControls::showVolumeSlider()
 {
     if (!m_mediaController->hasAudio())
@@ -218,6 +315,11 @@
 void MediaControls::changedMute()
 {
     m_panelMuteButton->changedMute();
+
+    if (m_mediaController->muted())
+        m_volumeSlider->setVolume(0);
+    else
+        m_volumeSlider->setVolume(m_mediaController->volume());
 }
 
 void MediaControls::changedVolume()
@@ -331,7 +433,7 @@
     m_hideFullscreenControlsTimer.stop();
 }
 
-const AtomicString& MediaControls::pseudo() const
+const AtomicString& MediaControls::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls"));
     return id;
@@ -358,8 +460,7 @@
     if (m_mediaController)
         m_textDisplayContainer->setMediaController(m_mediaController);
 
-    // Insert it before the first controller element so it always displays behind the controls.
-    insertBefore(textDisplayContainer.release(), m_panel, IGNORE_EXCEPTION);
+    insertTextTrackContainer(textDisplayContainer.release());
 }
 
 void MediaControls::showTextTrackDisplay()
@@ -384,4 +485,10 @@
     m_textDisplayContainer->updateDisplay();
 }
 
+void MediaControls::insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement> textTrackContainer)
+{
+    // Insert it before the first controller element so it always displays behind the controls.
+    insertBefore(textTrackContainer, m_enclosure);
+}
+
 }
diff --git a/Source/core/html/shadow/MediaControls.h b/Source/core/html/shadow/MediaControls.h
index d5b5884..c5e86af 100644
--- a/Source/core/html/shadow/MediaControls.h
+++ b/Source/core/html/shadow/MediaControls.h
@@ -30,76 +30,79 @@
 #include "core/events/MouseEvent.h"
 #include "core/html/HTMLDivElement.h"
 #include "core/html/shadow/MediaControlElements.h"
-#include "core/page/Page.h"
 #include "core/rendering/RenderTheme.h"
 
 namespace WebCore {
 
 class Document;
 class Event;
-class Page;
 class MediaPlayer;
 
 class RenderBox;
 class RenderMedia;
 
-// An abstract class with the media control elements that all ports support.
 class MediaControls : public HTMLDivElement {
-  public:
+public:
     virtual ~MediaControls() {}
 
-    // This function is to be implemented in your port-specific media
-    // controls implementation since it will return a child instance.
     static PassRefPtr<MediaControls> create(Document&);
 
     virtual void setMediaController(MediaControllerInterface*);
 
-    virtual void reset();
-    virtual void reportedError();
-    virtual void loadedMetadata();
+    void reset();
 
-    virtual void show();
-    virtual void hide();
-    virtual void makeOpaque();
-    virtual void makeTransparent();
-    virtual bool shouldHideControls();
+    void show();
+    void hide();
 
-    virtual void bufferingProgressed();
+    void bufferingProgressed();
     virtual void playbackStarted();
-    virtual void playbackProgressed();
+    void playbackProgressed();
     virtual void playbackStopped();
 
-    virtual void updateStatusDisplay() { };
-    virtual void updateCurrentTimeDisplay() = 0;
-    virtual void showVolumeSlider();
+    void updateCurrentTimeDisplay();
+    void showVolumeSlider();
 
-    virtual void changedMute();
-    virtual void changedVolume();
+    void changedMute();
+    void changedVolume();
 
-    virtual void changedClosedCaptionsVisibility();
-    virtual void refreshClosedCaptionsButtonVisibility();
-    virtual void closedCaptionTracksChanged();
+    void changedClosedCaptionsVisibility();
+    void refreshClosedCaptionsButtonVisibility();
+    void closedCaptionTracksChanged();
 
-    virtual void enteredFullscreen();
-    virtual void exitedFullscreen();
+    void enteredFullscreen();
+    void exitedFullscreen();
 
-    virtual bool willRespondToMouseMoveEvents() OVERRIDE { return true; }
-
-    virtual void hideFullscreenControlsTimerFired(Timer<MediaControls>*);
-    virtual void startHideFullscreenControlsTimer();
-    virtual void stopHideFullscreenControlsTimer();
-
-    virtual void createTextTrackDisplay();
-    virtual void showTextTrackDisplay();
-    virtual void hideTextTrackDisplay();
-    virtual void updateTextTrackDisplay();
+    void updateTextTrackDisplay();
 
 protected:
     explicit MediaControls(Document&);
 
-    virtual void defaultEventHandler(Event*);
+    virtual bool initializeControls(Document&);
 
-    virtual bool containsRelatedTarget(Event*);
+    virtual bool shouldHideControls();
+
+    virtual void insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement>);
+
+private:
+    void makeOpaque();
+    void makeTransparent();
+
+    void hideFullscreenControlsTimerFired(Timer<MediaControls>*);
+    void startHideFullscreenControlsTimer();
+    void stopHideFullscreenControlsTimer();
+
+    void createTextTrackDisplay();
+    void showTextTrackDisplay();
+    void hideTextTrackDisplay();
+
+    // Node
+    virtual bool isMediaControls() const OVERRIDE FINAL { return true; }
+    virtual bool willRespondToMouseMoveEvents() OVERRIDE { return true; }
+    virtual void defaultEventHandler(Event*) OVERRIDE;
+    bool containsRelatedTarget(Event*);
+
+    // Element
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
 
     MediaControllerInterface* m_mediaController;
 
@@ -117,25 +120,15 @@
     MediaControlPanelVolumeSliderElement* m_volumeSlider;
     MediaControlToggleClosedCaptionsButtonElement* m_toggleClosedCaptionsButton;
     MediaControlFullscreenButtonElement* m_fullScreenButton;
+    MediaControlTimeRemainingDisplayElement* m_durationDisplay;
+    MediaControlPanelEnclosureElement* m_enclosure;
 
     Timer<MediaControls> m_hideFullscreenControlsTimer;
     bool m_isFullscreen;
     bool m_isMouseOverControls;
-
-private:
-    virtual bool isMediaControls() const { return true; }
-
-    virtual const AtomicString& pseudo() const;
 };
 
-inline MediaControls* toMediaControls(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isMediaControls());
-    return static_cast<MediaControls*>(node);
-}
-
-// This will catch anyone doing an unneccessary cast.
-void toMediaControls(const MediaControls*);
+DEFINE_NODE_TYPE_CASTS(MediaControls, isMediaControls());
 
 }
 
diff --git a/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp b/Source/core/html/shadow/MediaControlsAndroid.cpp
similarity index 64%
rename from Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
rename to Source/core/html/shadow/MediaControlsAndroid.cpp
index f81c930..6943ae5 100644
--- a/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
+++ b/Source/core/html/shadow/MediaControlsAndroid.cpp
@@ -24,74 +24,61 @@
  */
 
 #include "config.h"
-#include "core/html/shadow/MediaControlsChromiumAndroid.h"
+#include "core/html/shadow/MediaControlsAndroid.h"
 
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 
 namespace WebCore {
 
-MediaControlsChromiumAndroid::MediaControlsChromiumAndroid(Document& document)
-    : MediaControlsChromium(document)
+MediaControlsAndroid::MediaControlsAndroid(Document& document)
+    : MediaControls(document)
     , m_overlayPlayButton(0)
     , m_overlayEnclosure(0)
 {
 }
 
-PassRefPtr<MediaControls> MediaControls::create(Document& document)
+bool MediaControlsAndroid::initializeControls(Document& document)
 {
-    return MediaControlsChromiumAndroid::createControls(document);
-}
-
-PassRefPtr<MediaControlsChromiumAndroid> MediaControlsChromiumAndroid::createControls(Document& document)
-{
-    if (!document.page())
-        return 0;
-
-    RefPtr<MediaControlsChromiumAndroid> controls = adoptRef(new MediaControlsChromiumAndroid(document));
-
     TrackExceptionState exceptionState;
 
     RefPtr<MediaControlOverlayEnclosureElement> overlayEnclosure = MediaControlOverlayEnclosureElement::create(document);
     RefPtr<MediaControlOverlayPlayButtonElement> overlayPlayButton = MediaControlOverlayPlayButtonElement::create(document);
-    controls->m_overlayPlayButton = overlayPlayButton.get();
+    m_overlayPlayButton = overlayPlayButton.get();
     overlayEnclosure->appendChild(overlayPlayButton.release(), exceptionState);
     if (exceptionState.hadException())
-        return 0;
+        return false;
 
-    controls->m_overlayEnclosure = overlayEnclosure.get();
-    controls->appendChild(overlayEnclosure.release(), exceptionState);
+    m_overlayEnclosure = overlayEnclosure.get();
+    appendChild(overlayEnclosure.release(), exceptionState);
     if (exceptionState.hadException())
-        return 0;
+        return false;
 
-    if (controls->initializeControls(document))
-        return controls.release();
-
-    return 0;
+    return MediaControls::initializeControls(document);
 }
 
-void MediaControlsChromiumAndroid::setMediaController(MediaControllerInterface* controller)
+void MediaControlsAndroid::setMediaController(MediaControllerInterface* controller)
 {
     if (m_overlayPlayButton)
         m_overlayPlayButton->setMediaController(controller);
     if (m_overlayEnclosure)
         m_overlayEnclosure->setMediaController(controller);
-    MediaControlsChromium::setMediaController(controller);
+    MediaControls::setMediaController(controller);
 }
 
-void MediaControlsChromiumAndroid::playbackStarted()
+void MediaControlsAndroid::playbackStarted()
 {
     m_overlayPlayButton->updateDisplayType();
-    MediaControlsChromium::playbackStarted();
+    MediaControls::playbackStarted();
 }
 
-void MediaControlsChromiumAndroid::playbackStopped()
+void MediaControlsAndroid::playbackStopped()
 {
     m_overlayPlayButton->updateDisplayType();
-    MediaControlsChromium::playbackStopped();
+    MediaControls::playbackStopped();
 }
 
-void MediaControlsChromiumAndroid::insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement> textTrackContainer)
+void MediaControlsAndroid::insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement> textTrackContainer)
 {
     // Insert it before the overlay play button so it always displays behind it.
     m_overlayEnclosure->insertBefore(textTrackContainer, m_overlayPlayButton);
diff --git a/Source/core/html/shadow/MediaControlsChromiumAndroid.h b/Source/core/html/shadow/MediaControlsAndroid.h
similarity index 80%
rename from Source/core/html/shadow/MediaControlsChromiumAndroid.h
rename to Source/core/html/shadow/MediaControlsAndroid.h
index 8b8a900..34240bc 100644
--- a/Source/core/html/shadow/MediaControlsChromiumAndroid.h
+++ b/Source/core/html/shadow/MediaControlsAndroid.h
@@ -23,27 +23,26 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef MediaControlsChromiumAndroid_h
-#define MediaControlsChromiumAndroid_h
+#ifndef MediaControlsAndroid_h
+#define MediaControlsAndroid_h
 
 #include "core/html/shadow/MediaControls.h"
-#include "core/html/shadow/MediaControlsChromium.h"
 
 namespace WebCore {
 
-class MediaControlsChromiumAndroid : public MediaControlsChromium {
+class MediaControlsAndroid FINAL : public MediaControls {
 public:
-    static PassRefPtr<MediaControlsChromiumAndroid> createControls(Document&);
+    explicit MediaControlsAndroid(Document&);
 
     virtual void setMediaController(MediaControllerInterface*) OVERRIDE;
     virtual void playbackStarted() OVERRIDE;
     virtual void playbackStopped() OVERRIDE;
     virtual bool shouldHideControls() OVERRIDE { return true; }
 
-    void insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement>) OVERRIDE;
+    virtual void insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement>) OVERRIDE;
 
 private:
-    explicit MediaControlsChromiumAndroid(Document&);
+    virtual bool initializeControls(Document&) OVERRIDE;
 
     MediaControlOverlayPlayButtonElement* m_overlayPlayButton;
     MediaControlOverlayEnclosureElement* m_overlayEnclosure;
diff --git a/Source/core/html/shadow/MediaControlsChromium.cpp b/Source/core/html/shadow/MediaControlsChromium.cpp
deleted file mode 100644
index d1d4ccb..0000000
--- a/Source/core/html/shadow/MediaControlsChromium.cpp
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2011, 2012 Google Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-#include "core/html/shadow/MediaControlsChromium.h"
-
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-
-using namespace std;
-
-namespace WebCore {
-
-MediaControlsChromium::MediaControlsChromium(Document& document)
-    : MediaControls(document)
-    , m_durationDisplay(0)
-    , m_enclosure(0)
-{
-}
-
-// MediaControls::create() for Android is defined in MediaControlsChromiumAndroid.cpp.
-#if !OS(ANDROID)
-PassRefPtr<MediaControls> MediaControls::create(Document& document)
-{
-    return MediaControlsChromium::createControls(document);
-}
-#endif
-
-PassRefPtr<MediaControlsChromium> MediaControlsChromium::createControls(Document& document)
-{
-    if (!document.page())
-        return 0;
-
-    RefPtr<MediaControlsChromium> controls = adoptRef(new MediaControlsChromium(document));
-
-    if (controls->initializeControls(document))
-        return controls.release();
-
-    return 0;
-}
-
-bool MediaControlsChromium::initializeControls(Document& document)
-{
-    // Create an enclosing element for the panel so we can visually offset the controls correctly.
-    RefPtr<MediaControlPanelEnclosureElement> enclosure = MediaControlPanelEnclosureElement::create(document);
-
-    RefPtr<MediaControlPanelElement> panel = MediaControlPanelElement::create(document);
-
-    TrackExceptionState exceptionState;
-
-    RefPtr<MediaControlPlayButtonElement> playButton = MediaControlPlayButtonElement::create(document);
-    m_playButton = playButton.get();
-    panel->appendChild(playButton.release(), exceptionState);
-    if (exceptionState.hadException())
-        return false;
-
-    RefPtr<MediaControlTimelineElement> timeline = MediaControlTimelineElement::create(document, this);
-    m_timeline = timeline.get();
-    panel->appendChild(timeline.release(), exceptionState);
-    if (exceptionState.hadException())
-        return false;
-
-    RefPtr<MediaControlCurrentTimeDisplayElement> currentTimeDisplay = MediaControlCurrentTimeDisplayElement::create(document);
-    m_currentTimeDisplay = currentTimeDisplay.get();
-    m_currentTimeDisplay->hide();
-    panel->appendChild(currentTimeDisplay.release(), exceptionState);
-    if (exceptionState.hadException())
-        return false;
-
-    RefPtr<MediaControlTimeRemainingDisplayElement> durationDisplay = MediaControlTimeRemainingDisplayElement::create(document);
-    m_durationDisplay = durationDisplay.get();
-    panel->appendChild(durationDisplay.release(), exceptionState);
-    if (exceptionState.hadException())
-        return false;
-
-    RefPtr<MediaControlPanelMuteButtonElement> panelMuteButton = MediaControlPanelMuteButtonElement::create(document, this);
-    m_panelMuteButton = panelMuteButton.get();
-    panel->appendChild(panelMuteButton.release(), exceptionState);
-    if (exceptionState.hadException())
-        return false;
-
-    RefPtr<MediaControlPanelVolumeSliderElement> slider = MediaControlPanelVolumeSliderElement::create(document);
-    m_volumeSlider = slider.get();
-    m_volumeSlider->setClearMutedOnUserInteraction(true);
-    panel->appendChild(slider.release(), exceptionState);
-    if (exceptionState.hadException())
-        return false;
-
-    if (RenderTheme::theme().supportsClosedCaptioning()) {
-        RefPtr<MediaControlToggleClosedCaptionsButtonElement> toggleClosedCaptionsButton = MediaControlToggleClosedCaptionsButtonElement::create(document, this);
-        m_toggleClosedCaptionsButton = toggleClosedCaptionsButton.get();
-        panel->appendChild(toggleClosedCaptionsButton.release(), exceptionState);
-        if (exceptionState.hadException())
-            return false;
-    }
-
-    RefPtr<MediaControlFullscreenButtonElement> fullscreenButton = MediaControlFullscreenButtonElement::create(document);
-    m_fullScreenButton = fullscreenButton.get();
-    panel->appendChild(fullscreenButton.release(), exceptionState);
-    if (exceptionState.hadException())
-        return false;
-
-    m_panel = panel.get();
-    enclosure->appendChild(panel.release(), exceptionState);
-    if (exceptionState.hadException())
-        return false;
-
-    m_enclosure = enclosure.get();
-    appendChild(enclosure.release(), exceptionState);
-    if (exceptionState.hadException())
-        return false;
-
-    return true;
-}
-
-void MediaControlsChromium::setMediaController(MediaControllerInterface* controller)
-{
-    if (m_mediaController == controller)
-        return;
-
-    MediaControls::setMediaController(controller);
-
-    if (m_durationDisplay)
-        m_durationDisplay->setMediaController(controller);
-    if (m_enclosure)
-        m_enclosure->setMediaController(controller);
-}
-
-void MediaControlsChromium::reset()
-{
-    Page* page = document().page();
-    if (!page)
-        return;
-
-    double duration = m_mediaController->duration();
-    m_durationDisplay->setInnerText(RenderTheme::theme().formatMediaControlsTime(duration), ASSERT_NO_EXCEPTION);
-    m_durationDisplay->setCurrentValue(duration);
-
-    MediaControls::reset();
-}
-
-void MediaControlsChromium::playbackStarted()
-{
-    m_currentTimeDisplay->show();
-    m_durationDisplay->hide();
-
-    MediaControls::playbackStarted();
-}
-
-void MediaControlsChromium::updateCurrentTimeDisplay()
-{
-    double now = m_mediaController->currentTime();
-    double duration = m_mediaController->duration();
-
-    Page* page = document().page();
-    if (!page)
-        return;
-
-    // After seek, hide duration display and show current time.
-    if (now > 0) {
-        m_currentTimeDisplay->show();
-        m_durationDisplay->hide();
-    }
-
-    // Allow the theme to format the time.
-    m_currentTimeDisplay->setInnerText(RenderTheme::theme().formatMediaControlsCurrentTime(now, duration), IGNORE_EXCEPTION);
-    m_currentTimeDisplay->setCurrentValue(now);
-}
-
-void MediaControlsChromium::changedMute()
-{
-    MediaControls::changedMute();
-
-    if (m_mediaController->muted())
-        m_volumeSlider->setVolume(0);
-    else
-        m_volumeSlider->setVolume(m_mediaController->volume());
-}
-
-void MediaControlsChromium::createTextTrackDisplay()
-{
-    if (m_textDisplayContainer)
-        return;
-
-    RefPtr<MediaControlTextTrackContainerElement> textDisplayContainer = MediaControlTextTrackContainerElement::create(document());
-    m_textDisplayContainer = textDisplayContainer.get();
-
-    if (m_mediaController)
-        m_textDisplayContainer->setMediaController(m_mediaController);
-
-    insertTextTrackContainer(textDisplayContainer.release());
-}
-
-void MediaControlsChromium::insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement> textTrackContainer)
-{
-    // Insert it before the first controller element so it always displays behind the controls.
-    // In the Chromium case, that's the enclosure element.
-    insertBefore(textTrackContainer, m_enclosure);
-}
-
-
-}
diff --git a/Source/core/html/shadow/MediaControlsChromium.h b/Source/core/html/shadow/MediaControlsChromium.h
deleted file mode 100644
index 5e3c55e..0000000
--- a/Source/core/html/shadow/MediaControlsChromium.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2011, 2012 Google Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef MediaControlsChromium_h
-#define MediaControlsChromium_h
-
-#include "core/html/shadow/MediaControls.h"
-
-namespace WebCore {
-
-class MediaControlsChromium : public MediaControls {
-public:
-    // Called from port-specific parent create function to create custom controls.
-    static PassRefPtr<MediaControlsChromium> createControls(Document&);
-
-    virtual void setMediaController(MediaControllerInterface*) OVERRIDE;
-
-    virtual void reset() OVERRIDE;
-
-    virtual void playbackStarted() OVERRIDE;
-
-    void changedMute() OVERRIDE;
-
-    virtual void updateCurrentTimeDisplay() OVERRIDE;
-
-    void createTextTrackDisplay() OVERRIDE;
-
-    virtual void insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement>);
-
-protected:
-    explicit MediaControlsChromium(Document&);
-
-    bool initializeControls(Document&);
-
-private:
-    MediaControlTimeRemainingDisplayElement* m_durationDisplay;
-    MediaControlPanelEnclosureElement* m_enclosure;
-};
-
-}
-
-#endif
diff --git a/Source/core/html/shadow/MeterShadowElement.cpp b/Source/core/html/shadow/MeterShadowElement.cpp
index a39c29c..47ced5d 100644
--- a/Source/core/html/shadow/MeterShadowElement.cpp
+++ b/Source/core/html/shadow/MeterShadowElement.cpp
@@ -66,7 +66,7 @@
 PassRefPtr<MeterInnerElement> MeterInnerElement::create(Document& document)
 {
     RefPtr<MeterInnerElement> element = adoptRef(new MeterInnerElement(document));
-    element->setPseudo(AtomicString("-webkit-meter-inner-element", AtomicString::ConstructFromLiteral));
+    element->setShadowPseudoId(AtomicString("-webkit-meter-inner-element", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
@@ -92,7 +92,7 @@
 PassRefPtr<MeterBarElement> MeterBarElement::create(Document& document)
 {
     RefPtr<MeterBarElement> element = adoptRef(new MeterBarElement(document));
-    element->setPseudo(AtomicString("-webkit-meter-bar", AtomicString::ConstructFromLiteral));
+    element->setShadowPseudoId(AtomicString("-webkit-meter-bar", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
diff --git a/Source/core/html/shadow/MeterShadowElement.h b/Source/core/html/shadow/MeterShadowElement.h
index c15bfdc..d065678 100644
--- a/Source/core/html/shadow/MeterShadowElement.h
+++ b/Source/core/html/shadow/MeterShadowElement.h
@@ -45,7 +45,7 @@
     HTMLMeterElement* meterElement() const;
 
 private:
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 };
 
 class MeterInnerElement FINAL : public MeterShadowElement {
@@ -70,7 +70,7 @@
 public:
     static PassRefPtr<MeterValueElement> create(Document&);
     void setWidthPercentage(double);
-    void updatePseudo() { setPseudo(valuePseudoId()); }
+    void updatePseudo() { setShadowPseudoId(valuePseudoId()); }
 
 private:
     MeterValueElement(Document&);
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
index 238c3f4..b2ac683 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
@@ -31,14 +31,14 @@
 #include "config.h"
 #include "core/html/shadow/PasswordGeneratorButtonElement.h"
 
-#include "core/events/Event.h"
 #include "core/dom/NodeRenderStyle.h"
+#include "core/events/Event.h"
 #include "core/fetch/ImageResource.h"
+#include "core/frame/FrameHost.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/shadow/ShadowElementNames.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/page/Page.h"
 #include "core/rendering/RenderImage.h"
 #include "platform/graphics/Image.h"
 
@@ -123,6 +123,7 @@
 
 void PasswordGeneratorButtonElement::defaultEventHandler(Event* event)
 {
+    ASSERT(document().isActive());
     RefPtr<HTMLInputElement> input = hostInput();
     if (!input || input->isDisabledOrReadOnly() || !event->isMouseEvent()) {
         if (!event->defaultHandled())
@@ -132,8 +133,7 @@
 
     RefPtr<PasswordGeneratorButtonElement> protector(this);
     if (event->type() == EventTypeNames::click) {
-        if (Page* page = document().page())
-            page->chrome().client().openPasswordGenerator(input.get());
+        document().frameHost()->chrome().client().openPasswordGenerator(input.get());
         event->setDefaultHandled();
     }
 
diff --git a/Source/core/html/shadow/PickerIndicatorElement.cpp b/Source/core/html/shadow/PickerIndicatorElement.cpp
index 40aec28..06452e6 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.cpp
+++ b/Source/core/html/shadow/PickerIndicatorElement.cpp
@@ -53,7 +53,7 @@
 PassRefPtr<PickerIndicatorElement> PickerIndicatorElement::create(Document& document, PickerIndicatorOwner& pickerIndicatorOwner)
 {
     RefPtr<PickerIndicatorElement> element = adoptRef(new PickerIndicatorElement(document, pickerIndicatorOwner));
-    element->setPseudo(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
+    element->setShadowPseudoId(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::pickerIndicator());
     return element.release();
 }
diff --git a/Source/core/html/shadow/PickerIndicatorElement.h b/Source/core/html/shadow/PickerIndicatorElement.h
index 4f42297..8b7a5e3 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.h
+++ b/Source/core/html/shadow/PickerIndicatorElement.h
@@ -80,11 +80,7 @@
     RefPtr<DateTimeChooser> m_chooser;
 };
 
-inline PickerIndicatorElement* toPickerIndicatorElement(Element* element)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isPickerIndicatorElement());
-    return static_cast<PickerIndicatorElement*>(element);
-}
+DEFINE_TYPE_CASTS(PickerIndicatorElement, Element, element, element->isPickerIndicatorElement(), element.isPickerIndicatorElement());
 
 }
 #endif
diff --git a/Source/core/html/shadow/ProgressShadowElement.h b/Source/core/html/shadow/ProgressShadowElement.h
index b375fcc..658b40f 100644
--- a/Source/core/html/shadow/ProgressShadowElement.h
+++ b/Source/core/html/shadow/ProgressShadowElement.h
@@ -45,7 +45,7 @@
     HTMLProgressElement* progressElement() const;
 
 protected:
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 };
 
 class ProgressInnerElement FINAL : public ProgressShadowElement {
@@ -56,7 +56,7 @@
     ProgressInnerElement(Document&);
 
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 };
 
 inline PassRefPtr<ProgressInnerElement> ProgressInnerElement::create(Document& document)
diff --git a/Source/core/html/shadow/ShadowElementNames.cpp b/Source/core/html/shadow/ShadowElementNames.cpp
index abe60e1..1023615 100644
--- a/Source/core/html/shadow/ShadowElementNames.cpp
+++ b/Source/core/html/shadow/ShadowElementNames.cpp
@@ -35,6 +35,18 @@
 
 namespace ShadowElementNames {
 
+const AtomicString& detailsContent()
+{
+    DEFINE_STATIC_LOCAL(AtomicString, name, ("details-content", AtomicString::ConstructFromLiteral));
+    return name;
+}
+
+const AtomicString& detailsSummary()
+{
+    DEFINE_STATIC_LOCAL(AtomicString, name, ("details-summary", AtomicString::ConstructFromLiteral));
+    return name;
+}
+
 const AtomicString& dateTimeEdit()
 {
     DEFINE_STATIC_LOCAL(AtomicString, name, ("date-time-edit", AtomicString::ConstructFromLiteral));
diff --git a/Source/core/html/shadow/ShadowElementNames.h b/Source/core/html/shadow/ShadowElementNames.h
index 46788a1..92426b2 100644
--- a/Source/core/html/shadow/ShadowElementNames.h
+++ b/Source/core/html/shadow/ShadowElementNames.h
@@ -37,6 +37,8 @@
 
 namespace ShadowElementNames {
 
+const AtomicString& detailsContent();
+const AtomicString& detailsSummary();
 const AtomicString& dateTimeEdit();
 const AtomicString& spinButton();
 const AtomicString& clearButton();
diff --git a/Source/core/html/shadow/SliderThumbElement.cpp b/Source/core/html/shadow/SliderThumbElement.cpp
index dc7d508..94dae01 100644
--- a/Source/core/html/shadow/SliderThumbElement.cpp
+++ b/Source/core/html/shadow/SliderThumbElement.cpp
@@ -64,9 +64,6 @@
     ASSERT(input->renderer());
     RenderStyle* sliderStyle = input->renderer()->style();
 
-    if (sliderStyle->appearance() == MediaVolumeSliderPart && RenderTheme::theme().usesVerticalVolumeSlider())
-        return true;
-
     return sliderStyle->appearance() == SliderVerticalPart;
 }
 
@@ -305,7 +302,6 @@
     input->setValueFromRenderer(valueString);
     if (renderer())
         renderer()->setNeedsLayout();
-    input->dispatchFormControlChangeEvent();
 }
 
 void SliderThumbElement::startDragging()
@@ -326,6 +322,7 @@
     m_inDragMode = false;
     if (renderer())
         renderer()->setNeedsLayout();
+    hostInput()->dispatchFormControlChangeEvent();
 }
 
 void SliderThumbElement::defaultEventHandler(Event* event)
@@ -412,7 +409,7 @@
     return mediaSliderThumb;
 }
 
-const AtomicString& SliderThumbElement::pseudo() const
+const AtomicString& SliderThumbElement::shadowPseudoId() const
 {
     HTMLInputElement* input = hostInput();
     if (!input)
@@ -449,7 +446,7 @@
     return new RenderSliderContainer(this);
 }
 
-const AtomicString& SliderContainerElement::pseudo() const
+const AtomicString& SliderContainerElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderContainer, ("-webkit-media-slider-container", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(const AtomicString, sliderContainer, ("-webkit-slider-container", AtomicString::ConstructFromLiteral));
diff --git a/Source/core/html/shadow/SliderThumbElement.h b/Source/core/html/shadow/SliderThumbElement.h
index a7af777..39bbe01 100644
--- a/Source/core/html/shadow/SliderThumbElement.h
+++ b/Source/core/html/shadow/SliderThumbElement.h
@@ -51,23 +51,23 @@
     void setPositionFromValue();
 
     void dragFrom(const LayoutPoint&);
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
     virtual bool willRespondToMouseMoveEvents() OVERRIDE;
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
     HTMLInputElement* hostInput() const;
     void setPositionFromPoint(const LayoutPoint&);
     void stopDragging();
 
 private:
     SliderThumbElement(Document&);
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren();
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren() OVERRIDE;
     virtual bool isDisabledFormControl() const OVERRIDE;
     virtual bool matchesReadOnlyPseudoClass() const OVERRIDE;
     virtual bool matchesReadWritePseudoClass() const OVERRIDE;
-    virtual Node* focusDelegate();
+    virtual Node* focusDelegate() OVERRIDE;
     void startDragging();
 
     bool m_inDragMode;
@@ -78,11 +78,8 @@
     return create(document());
 }
 
-inline SliderThumbElement* toSliderThumbElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isHTMLElement());
-    return static_cast<SliderThumbElement*>(node);
-}
+// FIXME: There are no ways to check if a node is a SliderThumbElement.
+DEFINE_NODE_TYPE_CASTS(SliderThumbElement, isHTMLElement());
 
 // --------------------------------
 
@@ -92,7 +89,7 @@
     void updateAppearance(RenderStyle* parentStyle);
 
 private:
-    virtual bool isSliderThumb() const;
+    virtual bool isSliderThumb() const OVERRIDE;
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 };
 
@@ -104,8 +101,8 @@
 
 private:
     SliderContainerElement(Document&);
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual const AtomicString& pseudo() const;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
 };
 
 }
diff --git a/Source/core/html/shadow/SpinButtonElement.cpp b/Source/core/html/shadow/SpinButtonElement.cpp
index 38303b5..e9cefa5 100644
--- a/Source/core/html/shadow/SpinButtonElement.cpp
+++ b/Source/core/html/shadow/SpinButtonElement.cpp
@@ -56,7 +56,7 @@
 PassRefPtr<SpinButtonElement> SpinButtonElement::create(Document& document, SpinButtonOwner& spinButtonOwner)
 {
     RefPtr<SpinButtonElement> element = adoptRef(new SpinButtonElement(document, spinButtonOwner));
-    element->setPseudo(AtomicString("-webkit-inner-spin-button", AtomicString::ConstructFromLiteral));
+    element->setShadowPseudoId(AtomicString("-webkit-inner-spin-button", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::spinButton());
     return element.release();
 }
@@ -111,9 +111,9 @@
             }
             event->setDefaultHandled();
         }
-    } else if (mouseEvent->type() == EventTypeNames::mouseup && mouseEvent->button() == LeftButton)
+    } else if (mouseEvent->type() == EventTypeNames::mouseup && mouseEvent->button() == LeftButton) {
         stopRepeatingTimer();
-    else if (event->type() == EventTypeNames::mousemove) {
+    } else if (event->type() == EventTypeNames::mousemove) {
         if (box->pixelSnappedBorderBoxRect().contains(local)) {
             if (!m_capturing) {
                 if (Frame* frame = document().frame()) {
diff --git a/Source/core/html/shadow/SpinButtonElement.h b/Source/core/html/shadow/SpinButtonElement.h
index 4cce722..8c3da22 100644
--- a/Source/core/html/shadow/SpinButtonElement.h
+++ b/Source/core/html/shadow/SpinButtonElement.h
@@ -56,7 +56,7 @@
     // implementation, e.g. during event handling.
     static PassRefPtr<SpinButtonElement> create(Document&, SpinButtonOwner&);
     UpDownState upDownState() const { return m_upDownState; }
-    virtual void releaseCapture();
+    void releaseCapture();
     void removeSpinButtonOwner() { m_spinButtonOwner = 0; }
 
     void step(int amount);
@@ -70,19 +70,19 @@
     SpinButtonElement(Document&, SpinButtonOwner&);
 
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual bool isSpinButtonElement() const { return true; }
+    virtual bool isSpinButtonElement() const OVERRIDE { return true; }
     virtual bool isDisabledFormControl() const OVERRIDE { return shadowHost() && shadowHost()->isDisabledFormControl(); }
     virtual bool matchesReadOnlyPseudoClass() const OVERRIDE;
     virtual bool matchesReadWritePseudoClass() const OVERRIDE;
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
     virtual void willOpenPopup() OVERRIDE;
     void doStepAction(int);
     void startRepeatingTimer();
     void stopRepeatingTimer();
     void repeatingTimerFired(Timer<SpinButtonElement>*);
-    virtual void setHovered(bool = true);
+    virtual void setHovered(bool = true) OVERRIDE;
     bool shouldRespondToMouseEvents();
-    virtual bool isMouseFocusable() const { return false; }
+    virtual bool isMouseFocusable() const OVERRIDE { return false; }
 
     SpinButtonOwner* m_spinButtonOwner;
     bool m_capturing;
@@ -91,25 +91,7 @@
     Timer<SpinButtonElement> m_repeatingTimer;
 };
 
-inline SpinButtonElement* toSpinButtonElement(Element* element)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isSpinButtonElement());
-    return static_cast<SpinButtonElement*>(element);
-}
-
-inline SpinButtonElement* toSpinButtonElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || toElement(node)->isSpinButtonElement());
-    return static_cast<SpinButtonElement*>(node);
-}
-
-inline const SpinButtonElement* toSpinButtonElement(const Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || toElement(node)->isSpinButtonElement());
-    return static_cast<const SpinButtonElement*>(node);
-}
-
-void toSpinButtonElement(const SpinButtonElement*);
+DEFINE_TYPE_CASTS(SpinButtonElement, Node, node, toElement(node)->isSpinButtonElement(), toElement(node).isSpinButtonElement());
 
 } // namespace
 
diff --git a/Source/core/html/shadow/TextControlInnerElements.cpp b/Source/core/html/shadow/TextControlInnerElements.cpp
index a19fef2..5570359 100644
--- a/Source/core/html/shadow/TextControlInnerElements.cpp
+++ b/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -164,7 +164,7 @@
     return element.release();
 }
 
-const AtomicString& SearchFieldDecorationElement::pseudo() const
+const AtomicString& SearchFieldDecorationElement::shadowPseudoId() const
 {
     DEFINE_STATIC_LOCAL(AtomicString, resultsDecorationId, ("-webkit-search-results-decoration", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, decorationId, ("-webkit-search-decoration", AtomicString::ConstructFromLiteral));
@@ -209,7 +209,7 @@
 PassRefPtr<SearchFieldCancelButtonElement> SearchFieldCancelButtonElement::create(Document& document)
 {
     RefPtr<SearchFieldCancelButtonElement> element = adoptRef(new SearchFieldCancelButtonElement(document));
-    element->setPseudo(AtomicString("-webkit-search-cancel-button", AtomicString::ConstructFromLiteral));
+    element->setShadowPseudoId(AtomicString("-webkit-search-cancel-button", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::clearButton());
     return element.release();
 }
@@ -298,7 +298,7 @@
 PassRefPtr<InputFieldSpeechButtonElement> InputFieldSpeechButtonElement::create(Document& document)
 {
     RefPtr<InputFieldSpeechButtonElement> element = adoptRef(new InputFieldSpeechButtonElement(document));
-    element->setPseudo(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
+    element->setShadowPseudoId(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
     element->setAttribute(idAttr, ShadowElementNames::speechButton());
     return element.release();
 }
diff --git a/Source/core/html/shadow/TextControlInnerElements.h b/Source/core/html/shadow/TextControlInnerElements.h
index 711f5ef..d18fd8c 100644
--- a/Source/core/html/shadow/TextControlInnerElements.h
+++ b/Source/core/html/shadow/TextControlInnerElements.h
@@ -40,7 +40,7 @@
     static PassRefPtr<TextControlInnerContainer> create(Document&);
 protected:
     TextControlInnerContainer(Document&);
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 };
 
 class EditingViewPortElement FINAL : public HTMLDivElement {
@@ -59,11 +59,11 @@
 public:
     static PassRefPtr<TextControlInnerTextElement> create(Document&);
 
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
 
 private:
     TextControlInnerTextElement(Document&);
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
     virtual bool supportsFocus() const OVERRIDE { return false; }
 };
@@ -72,12 +72,12 @@
 public:
     static PassRefPtr<SearchFieldDecorationElement> create(Document&);
 
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
     SearchFieldDecorationElement(Document&);
-    virtual const AtomicString& pseudo() const OVERRIDE;
+    virtual const AtomicString& shadowPseudoId() const OVERRIDE;
     virtual bool supportsFocus() const OVERRIDE { return false; }
 };
 
@@ -85,7 +85,7 @@
 public:
     static PassRefPtr<SearchFieldCancelButtonElement> create(Document&);
 
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
@@ -112,23 +112,23 @@
     virtual ~InputFieldSpeechButtonElement();
 
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual void defaultEventHandler(Event*);
-    virtual bool willRespondToMouseClickEvents();
-    virtual bool isInputFieldSpeechButtonElement() const { return true; }
+    virtual void defaultEventHandler(Event*) OVERRIDE;
+    virtual bool willRespondToMouseClickEvents() OVERRIDE;
+    virtual bool isInputFieldSpeechButtonElement() const OVERRIDE { return true; }
     SpeechInputState state() const { return m_state; }
     void startSpeechInput();
     void stopSpeechInput();
 
     // SpeechInputListener methods.
-    void didCompleteRecording(int);
-    void didCompleteRecognition(int);
-    void setRecognitionResult(int, const SpeechInputResultArray&);
+    virtual void didCompleteRecording(int) OVERRIDE;
+    virtual void didCompleteRecognition(int) OVERRIDE;
+    virtual void setRecognitionResult(int, const SpeechInputResultArray&) OVERRIDE;
 
 private:
     InputFieldSpeechButtonElement(Document&);
     SpeechInput* speechInput();
     void setState(SpeechInputState state);
-    virtual bool isMouseFocusable() const { return false; }
+    virtual bool isMouseFocusable() const OVERRIDE { return false; }
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
 
     bool m_capturing;
@@ -137,11 +137,7 @@
     SpeechInputResultArray m_results;
 };
 
-inline InputFieldSpeechButtonElement* toInputFieldSpeechButtonElement(Element* element)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isInputFieldSpeechButtonElement());
-    return static_cast<InputFieldSpeechButtonElement*>(element);
-}
+DEFINE_TYPE_CASTS(InputFieldSpeechButtonElement, Element, element, element->isInputFieldSpeechButtonElement(), element.isInputFieldSpeechButtonElement());
 
 #endif // ENABLE(INPUT_SPEECH)
 
diff --git a/Source/core/html/track/InbandTextTrack.h b/Source/core/html/track/InbandTextTrack.h
index 83948f0..70c1ada 100644
--- a/Source/core/html/track/InbandTextTrack.h
+++ b/Source/core/html/track/InbandTextTrack.h
@@ -41,7 +41,7 @@
 class MediaPlayer;
 class TextTrackCue;
 
-class InbandTextTrack : public TextTrack, public blink::WebInbandTextTrackClient {
+class InbandTextTrack FINAL : public TextTrack, public blink::WebInbandTextTrackClient {
 public:
     static PassRefPtr<InbandTextTrack> create(Document&, TextTrackClient*, blink::WebInbandTextTrack*);
     virtual ~InbandTextTrack();
diff --git a/Source/core/html/track/LoadableTextTrack.cpp b/Source/core/html/track/LoadableTextTrack.cpp
index 588c06c..012b360 100644
--- a/Source/core/html/track/LoadableTextTrack.cpp
+++ b/Source/core/html/track/LoadableTextTrack.cpp
@@ -32,6 +32,8 @@
 
 namespace WebCore {
 
+using namespace HTMLNames;
+
 LoadableTextTrack::LoadableTextTrack(HTMLTrackElement* track)
     : TextTrack(track->document(), track, emptyAtom, emptyAtom, emptyAtom, emptyAtom, TrackElement)
     , m_trackElement(track)
diff --git a/Source/core/html/track/LoadableTextTrack.h b/Source/core/html/track/LoadableTextTrack.h
index 487e7ca..b557645 100644
--- a/Source/core/html/track/LoadableTextTrack.h
+++ b/Source/core/html/track/LoadableTextTrack.h
@@ -35,7 +35,7 @@
 class HTMLTrackElement;
 class LoadableTextTrack;
 
-class LoadableTextTrack : public TextTrack, private TextTrackLoaderClient {
+class LoadableTextTrack FINAL : public TextTrack, private TextTrackLoaderClient {
 public:
     static PassRefPtr<LoadableTextTrack> create(HTMLTrackElement* track)
     {
diff --git a/Source/core/html/track/TextTrack.cpp b/Source/core/html/track/TextTrack.cpp
index 84dea3e..02b8753 100644
--- a/Source/core/html/track/TextTrack.cpp
+++ b/Source/core/html/track/TextTrack.cpp
@@ -96,14 +96,11 @@
 }
 
 TextTrack::TextTrack(Document& document, TextTrackClient* client, const AtomicString& kind, const AtomicString& label, const AtomicString& language, const AtomicString& id, TextTrackType type)
-    : TrackBase(TrackBase::TextTrack)
+    : TrackBase(TrackBase::TextTrack, label, language, id)
     , m_cues(0)
     , m_regions(0)
     , m_document(&document)
-    , m_mediaElement(0)
-    , m_label(label)
-    , m_language(language)
-    , m_id(id)
+    , m_trackList(0)
     , m_mode(disabledKeyword())
     , m_client(client)
     , m_trackType(type)
@@ -149,16 +146,12 @@
     return false;
 }
 
-void TextTrack::setKind(const AtomicString& kind)
+void TextTrack::setKind(const AtomicString& newKind)
 {
-    String oldKind = m_kind;
+    AtomicString oldKind = kind();
+    TrackBase::setKind(newKind);
 
-    if (isValidKindKeyword(kind))
-        m_kind = kind;
-    else
-        m_kind = subtitlesKeyword();
-
-    if (m_client && oldKind != m_kind)
+    if (m_client && oldKind != kind())
         m_client->textTrackKindChanged(this);
 }
 
@@ -376,10 +369,10 @@
 
 int TextTrack::trackIndex()
 {
-    ASSERT(m_mediaElement);
+    ASSERT(m_trackList);
 
     if (m_trackIndex == invalidTrackIndex)
-        m_trackIndex = m_mediaElement->textTracks()->getTrackIndex(this);
+        m_trackIndex = m_trackList->getTrackIndex(this);
 
     return m_trackIndex;
 }
@@ -392,7 +385,7 @@
 
 bool TextTrack::isRendered()
 {
-    if (m_kind != captionsKeyword() && m_kind != subtitlesKeyword())
+    if (kind() != captionsKeyword() && kind() != subtitlesKeyword())
         return false;
 
     if (m_mode != showingKeyword())
@@ -411,10 +404,10 @@
 
 int TextTrack::trackIndexRelativeToRenderedTracks()
 {
-    ASSERT(m_mediaElement);
+    ASSERT(m_trackList);
 
     if (m_renderedTrackIndex == invalidTrackIndex)
-        m_renderedTrackIndex = m_mediaElement->textTracks()->getTrackIndexRelativeToRenderedTracks(this);
+        m_renderedTrackIndex = m_trackList->getTrackIndexRelativeToRenderedTracks(this);
 
     return m_renderedTrackIndex;
 }
diff --git a/Source/core/html/track/TextTrack.h b/Source/core/html/track/TextTrack.h
index 721c555..c430c83 100644
--- a/Source/core/html/track/TextTrack.h
+++ b/Source/core/html/track/TextTrack.h
@@ -28,6 +28,7 @@
 #define TextTrack_h
 
 #include "bindings/v8/ScriptWrappable.h"
+#include "core/events/EventTarget.h"
 #include "core/html/track/TrackBase.h"
 #include "wtf/text/WTFString.h"
 
@@ -39,6 +40,7 @@
 class TextTrack;
 class TextTrackCue;
 class TextTrackCueList;
+class TextTrackList;
 class VTTRegion;
 class VTTRegionList;
 
@@ -53,7 +55,8 @@
     virtual void textTrackRemoveCue(TextTrack*, PassRefPtr<TextTrackCue>) = 0;
 };
 
-class TextTrack : public TrackBase, public ScriptWrappable {
+class TextTrack : public TrackBase, public ScriptWrappable, public EventTargetWithInlineData {
+    REFCOUNTED_EVENT_TARGET(TrackBase);
 public:
     static PassRefPtr<TextTrack> create(Document& document, TextTrackClient* client, const AtomicString& kind, const AtomicString& label, const AtomicString& language)
     {
@@ -61,11 +64,10 @@
     }
     virtual ~TextTrack();
 
-    void setMediaElement(HTMLMediaElement* element) { m_mediaElement = element; }
-    HTMLMediaElement* mediaElement() { return m_mediaElement; }
+    void setTrackList(TextTrackList* trackList) { m_trackList = trackList; }
+    TextTrackList* trackList() { return m_trackList; }
 
-    const AtomicString& kind() const { return m_kind; }
-    void setKind(const AtomicString&);
+    virtual void setKind(const AtomicString&) OVERRIDE;
 
     static const AtomicString& subtitlesKeyword();
     static const AtomicString& captionsKeyword();
@@ -74,15 +76,6 @@
     static const AtomicString& metadataKeyword();
     static bool isValidKindKeyword(const AtomicString&);
 
-    AtomicString label() const { return m_label; }
-    void setLabel(const AtomicString& label) { m_label = label; }
-
-    AtomicString language() const { return m_language; }
-    void setLanguage(const AtomicString& language) { m_language = language; }
-
-    AtomicString id() const { return m_id; }
-    void setId(const AtomicString& id) { m_id = id; }
-
     static const AtomicString& disabledKeyword();
     static const AtomicString& hiddenKeyword();
     static const AtomicString& showingKeyword();
@@ -138,6 +131,9 @@
 protected:
     TextTrack(Document&, TextTrackClient*, const AtomicString& kind, const AtomicString& label, const AtomicString& language, const AtomicString& id, TextTrackType);
 
+    virtual bool isValidKind(const AtomicString& kind) const OVERRIDE { return isValidKindKeyword(kind); }
+    virtual AtomicString defaultKind() const OVERRIDE { return subtitlesKeyword(); }
+
     RefPtr<TextTrackCueList> m_cues;
 
 private:
@@ -149,11 +145,7 @@
     // FIXME: Remove this pointer and get the Document from m_client
     Document* m_document;
 
-    HTMLMediaElement* m_mediaElement;
-    AtomicString m_kind;
-    AtomicString m_label;
-    AtomicString m_language;
-    AtomicString m_id;
+    TextTrackList* m_trackList;
     AtomicString m_mode;
     TextTrackClient* m_client;
     TextTrackType m_trackType;
diff --git a/Source/core/html/track/TextTrackCue.cpp b/Source/core/html/track/TextTrackCue.cpp
index cfb2eff..a89b462 100644
--- a/Source/core/html/track/TextTrackCue.cpp
+++ b/Source/core/html/track/TextTrackCue.cpp
@@ -83,7 +83,7 @@
     m_track = track;
 }
 
-void TextTrackCue::setId(const String& id)
+void TextTrackCue::setId(const AtomicString& id)
 {
     if (m_id == id)
         return;
diff --git a/Source/core/html/track/TextTrackCue.h b/Source/core/html/track/TextTrackCue.h
index 1779e37..6e9da46 100644
--- a/Source/core/html/track/TextTrackCue.h
+++ b/Source/core/html/track/TextTrackCue.h
@@ -56,8 +56,8 @@
     TextTrack* track() const;
     void setTrack(TextTrack*);
 
-    const String& id() const { return m_id; }
-    void setId(const String&);
+    const AtomicString& id() const { return m_id; }
+    void setId(const AtomicString&);
 
     double startTime() const { return m_startTime; }
     void setStartTime(double, ExceptionState&);
@@ -101,7 +101,7 @@
     virtual void cueDidChange();
 
 private:
-    String m_id;
+    AtomicString m_id;
     double m_startTime;
     double m_endTime;
     int m_cueIndex;
diff --git a/Source/core/html/track/TextTrackCueList.cpp b/Source/core/html/track/TextTrackCueList.cpp
index 43fa9b5..5e9b7c7 100644
--- a/Source/core/html/track/TextTrackCueList.cpp
+++ b/Source/core/html/track/TextTrackCueList.cpp
@@ -51,7 +51,7 @@
     return 0;
 }
 
-TextTrackCue* TextTrackCueList::getCueById(const String& id) const
+TextTrackCue* TextTrackCueList::getCueById(const AtomicString& id) const
 {
     for (size_t i = 0; i < m_list.size(); ++i) {
         if (m_list[i]->id() == id)
diff --git a/Source/core/html/track/TextTrackCueList.h b/Source/core/html/track/TextTrackCueList.h
index b209fcf..b59552b 100644
--- a/Source/core/html/track/TextTrackCueList.h
+++ b/Source/core/html/track/TextTrackCueList.h
@@ -47,7 +47,7 @@
     unsigned long getCueIndex(TextTrackCue*) const;
 
     TextTrackCue* item(unsigned index) const;
-    TextTrackCue* getCueById(const String&) const;
+    TextTrackCue* getCueById(const AtomicString&) const;
     TextTrackCueList* activeCues();
 
     bool add(PassRefPtr<TextTrackCue>);
diff --git a/Source/core/html/track/TextTrackList.cpp b/Source/core/html/track/TextTrackList.cpp
index 0d00ba3..ba8ca1a 100644
--- a/Source/core/html/track/TextTrackList.cpp
+++ b/Source/core/html/track/TextTrackList.cpp
@@ -192,8 +192,8 @@
 
     invalidateTrackIndexesAfterTrack(track.get());
 
-    ASSERT(!track->mediaElement() || track->mediaElement() == m_owner);
-    track->setMediaElement(m_owner);
+    ASSERT(!track->trackList());
+    track->setTrackList(this);
 
     scheduleAddTrackEvent(track.release());
 }
@@ -220,8 +220,8 @@
 
     invalidateTrackIndexesAfterTrack(track);
 
-    ASSERT(track->mediaElement() == m_owner);
-    track->setMediaElement(0);
+    ASSERT(track->trackList() == this);
+    track->setTrackList(0);
 
     tracks->remove(index);
 
diff --git a/Source/core/html/track/TextTrackList.h b/Source/core/html/track/TextTrackList.h
index 7c150b2..0d4c883 100644
--- a/Source/core/html/track/TextTrackList.h
+++ b/Source/core/html/track/TextTrackList.h
@@ -41,14 +41,14 @@
 class TextTrack;
 class TextTrackList;
 
-class TextTrackList : public RefCounted<TextTrackList>, public ScriptWrappable, public EventTargetWithInlineData {
+class TextTrackList FINAL : public RefCounted<TextTrackList>, public ScriptWrappable, public EventTargetWithInlineData {
     REFCOUNTED_EVENT_TARGET(TextTrackList);
 public:
     static PassRefPtr<TextTrackList> create(HTMLMediaElement* owner)
     {
         return adoptRef(new TextTrackList(owner));
     }
-    ~TextTrackList();
+    virtual ~TextTrackList();
 
     unsigned length() const;
     int getTrackIndex(TextTrack*);
diff --git a/Source/core/html/track/TextTrackList.idl b/Source/core/html/track/TextTrackList.idl
index bbcd2d9..f9d982d 100644
--- a/Source/core/html/track/TextTrackList.idl
+++ b/Source/core/html/track/TextTrackList.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    GenerateVisitDOMWrapper=owner,
+    SetWrapperReferenceFrom=owner,
     RuntimeEnabled=VideoTrack,
 ] interface TextTrackList : EventTarget {
     readonly attribute unsigned long length;
diff --git a/Source/core/rendering/LayoutIndicator.cpp b/Source/core/html/track/TrackBase.cpp
similarity index 75%
copy from Source/core/rendering/LayoutIndicator.cpp
copy to Source/core/html/track/TrackBase.cpp
index a57c53c..a11c065 100644
--- a/Source/core/rendering/LayoutIndicator.cpp
+++ b/Source/core/html/track/TrackBase.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,14 +29,29 @@
  */
 
 #include "config.h"
-#include "core/rendering/LayoutIndicator.h"
+#include "core/html/track/TrackBase.h"
 
 namespace WebCore {
 
-#ifndef NDEBUG
-
-size_t LayoutIndicator::s_inLayout = 0;
-
-#endif
-
+TrackBase::TrackBase(Type type, const AtomicString& label, const AtomicString& language, const AtomicString& id)
+    : m_type(type)
+    , m_label(label)
+    , m_language(language)
+    , m_id(id)
+{
 }
+
+TrackBase::~TrackBase()
+{
+}
+
+void TrackBase::setKind(const AtomicString& kind)
+{
+    if (isValidKind(kind))
+        m_kind = kind;
+    else
+        m_kind = defaultKind();
+}
+
+} // namespace WebCore
+
diff --git a/Source/core/html/track/TrackBase.h b/Source/core/html/track/TrackBase.h
index 38ead64..b291c68 100644
--- a/Source/core/html/track/TrackBase.h
+++ b/Source/core/html/track/TrackBase.h
@@ -26,24 +26,42 @@
 #ifndef TrackBase_h
 #define TrackBase_h
 
-#include "core/events/EventTarget.h"
 #include "wtf/RefCounted.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
-class TrackBase : public RefCounted<TrackBase>, public EventTargetWithInlineData {
-    REFCOUNTED_EVENT_TARGET(TrackBase);
+class TrackBase : public RefCounted<TrackBase> {
 public:
-    virtual ~TrackBase() { }
+    virtual ~TrackBase();
 
     enum Type { TextTrack, AudioTrack, VideoTrack };
     Type type() const { return m_type; }
 
+    const AtomicString& kind() const { return m_kind; }
+    virtual void setKind(const AtomicString&);
+
+    AtomicString label() const { return m_label; }
+    void setLabel(const AtomicString& label) { m_label = label; }
+
+    AtomicString language() const { return m_language; }
+    void setLanguage(const AtomicString& language) { m_language = language; }
+
+    AtomicString id() const { return m_id; }
+    void setId(const AtomicString& id) { m_id = id; }
+
 protected:
-    explicit TrackBase(Type type) : m_type(type) { }
+    TrackBase(Type, const AtomicString& label, const AtomicString& language, const AtomicString& id);
+
+    virtual bool isValidKind(const AtomicString&) const = 0;
+    virtual AtomicString defaultKind() const = 0;
 
 private:
     Type m_type;
+    AtomicString m_kind;
+    AtomicString m_label;
+    AtomicString m_language;
+    AtomicString m_id;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/track/TrackEvent.h b/Source/core/html/track/TrackEvent.h
index 606bc14..17fbf09 100644
--- a/Source/core/html/track/TrackEvent.h
+++ b/Source/core/html/track/TrackEvent.h
@@ -37,7 +37,7 @@
     RefPtr<TrackBase> track;
 };
 
-class TrackEvent : public Event {
+class TrackEvent FINAL : public Event {
 public:
     virtual ~TrackEvent();
 
@@ -51,7 +51,7 @@
         return adoptRef(new TrackEvent(type, initializer));
     }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
     TrackBase* track() const { return m_track.get(); }
 
diff --git a/Source/core/html/track/vtt/VTTCue.cpp b/Source/core/html/track/vtt/VTTCue.cpp
index ab185dc..f5a4c8c 100644
--- a/Source/core/html/track/vtt/VTTCue.cpp
+++ b/Source/core/html/track/vtt/VTTCue.cpp
@@ -44,6 +44,7 @@
 #include "core/html/track/vtt/VTTElement.h"
 #include "core/html/track/vtt/VTTParser.h"
 #include "core/html/track/vtt/VTTRegionList.h"
+#include "core/html/track/vtt/VTTScanner.h"
 #include "core/rendering/RenderVTTCue.h"
 #include "platform/text/BidiResolver.h"
 #include "platform/text/TextRunIterator.h"
@@ -53,6 +54,7 @@
 namespace WebCore {
 
 static const int undefinedPosition = -1;
+static const int undefinedSize = -1;
 
 static const CSSValueID displayWritingModeMap[] = {
     CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr
@@ -128,7 +130,7 @@
     : HTMLDivElement(document)
     , m_cue(cue)
 {
-    setPseudo(AtomicString("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
+    setShadowPseudoId(AtomicString("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
 }
 
 void VTTCueBox::applyCSSProperties(const IntSize&)
@@ -211,6 +213,7 @@
     , m_vttNodeTree(0)
     , m_cueBackgroundBox(HTMLDivElement::create(document))
     , m_displayDirection(CSSValueLtr)
+    , m_displaySize(undefinedSize)
     , m_snapToLines(true)
     , m_displayTreeShouldChange(true)
     , m_notifyRegion(true)
@@ -675,10 +678,8 @@
 
     for (Node* child = root->firstChild(); child; child = NodeTraversal::next(*child, root)) {
         if (child->nodeName() == timestampTag) {
-            unsigned position = 0;
-            String timestamp = child->nodeValue();
             double currentTimestamp;
-            bool check = VTTParser::collectTimeStamp(timestamp, &position, currentTimestamp);
+            bool check = VTTParser::collectTimeStamp(child->nodeValue(), currentTimestamp);
             ASSERT_UNUSED(check, check);
 
             if (currentTimestamp > movieTime)
@@ -732,7 +733,7 @@
     // background box.
 
     // Note: This is contained by default in m_cueBackgroundBox.
-    m_cueBackgroundBox->setPseudo(cueShadowPseudoId());
+    m_cueBackgroundBox->setShadowPseudoId(cueShadowPseudoId());
     displayTree->appendChild(m_cueBackgroundBox);
 
     // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not
@@ -833,42 +834,65 @@
     return coordinates;
 }
 
-VTTCue::CueSetting VTTCue::settingName(const String& name)
+VTTCue::CueSetting VTTCue::settingName(VTTScanner& input)
 {
-    DEFINE_STATIC_LOCAL(const String, verticalKeyword, ("vertical"));
-    DEFINE_STATIC_LOCAL(const String, lineKeyword, ("line"));
-    DEFINE_STATIC_LOCAL(const String, positionKeyword, ("position"));
-    DEFINE_STATIC_LOCAL(const String, sizeKeyword, ("size"));
-    DEFINE_STATIC_LOCAL(const String, alignKeyword, ("align"));
-    DEFINE_STATIC_LOCAL(const String, regionIdKeyword, ("region"));
-
-    if (name == verticalKeyword)
-        return Vertical;
-    if (name == lineKeyword)
-        return Line;
-    if (name == positionKeyword)
-        return Position;
-    if (name == sizeKeyword)
-        return Size;
-    if (name == alignKeyword)
-        return Align;
-    if (RuntimeEnabledFeatures::webVTTRegionsEnabled() && name == regionIdKeyword)
-        return RegionId;
-
+    CueSetting parsedSetting = None;
+    if (input.scan("vertical"))
+        parsedSetting = Vertical;
+    else if (input.scan("line"))
+        parsedSetting = Line;
+    else if (input.scan("position"))
+        parsedSetting = Position;
+    else if (input.scan("size"))
+        parsedSetting = Size;
+    else if (input.scan("align"))
+        parsedSetting = Align;
+    else if (RuntimeEnabledFeatures::webVTTRegionsEnabled() && input.scan("region"))
+        parsedSetting = RegionId;
+    // Verify that a ':' follows.
+    if (parsedSetting != None && input.scan(':'))
+        return parsedSetting;
     return None;
 }
 
-void VTTCue::parseSettings(const String& input)
+// Used for 'position' and 'size'.
+static bool scanPercentage(VTTScanner& input, const VTTScanner::Run& valueRun, int& number)
 {
-    unsigned position = 0;
+    // 1. If value contains any characters other than U+0025 PERCENT SIGN
+    //    characters (%) and characters in the range U+0030 DIGIT ZERO (0) to
+    //    U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
+    // 2. If value does not contain at least one character in the range U+0030
+    //    DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step
+    //    labeled next setting.
+    if (!input.scanDigits(number))
+        return false;
 
-    while (position < input.length()) {
+    // 3. If any character in value other than the last character is a U+0025
+    //    PERCENT SIGN character (%), then jump to the step labeled next
+    //    setting.
+    // 4. If the last character in value is not a U+0025 PERCENT SIGN character
+    //    (%), then jump to the step labeled next setting.
+    if (!input.scan('%') || !input.isAt(valueRun.end()))
+        return false;
+
+    // 5. Ignoring the trailing percent sign, interpret value as an integer,
+    //    and let number be that number.
+    // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step
+    //    labeled next setting.
+    return number >= 0 && number <= 100;
+}
+
+void VTTCue::parseSettings(const String& inputString)
+{
+    VTTScanner input(inputString);
+
+    while (!input.isAtEnd()) {
 
         // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order,
         // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
-        while (position < input.length() && VTTParser::isValidSettingDelimiter(input[position]))
-            position++;
-        if (position >= input.length())
+        input.skipWhile<VTTParser::isValidSettingDelimiter>();
+
+        if (input.isAtEnd())
             break;
 
         // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue,
@@ -877,48 +901,38 @@
         // 2. For each token setting in the list settings, run the following substeps:
         //    1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:)
         //       in setting is either the first or last character of setting, then jump to the step labeled next setting.
-        unsigned endOfSetting = position;
-        String setting = VTTParser::collectWord(input, &endOfSetting);
-        CueSetting name;
-        size_t colonOffset = setting.find(':', 1);
-        if (colonOffset == kNotFound || !colonOffset || colonOffset == setting.length() - 1)
-            goto NextSetting;
-
-        // 2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
-        name = settingName(setting.substring(0, colonOffset));
+        //    2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
+        CueSetting name = settingName(input);
 
         // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
-        position += colonOffset + 1;
-        if (position >= input.length())
-            break;
+        VTTScanner::Run valueRun = input.collectUntil<VTTParser::isValidSettingDelimiter>();
 
         // 4. Run the appropriate substeps that apply for the value of name, as follows:
         switch (name) {
-        case Vertical:
-            {
+        case Vertical: {
             // If name is a case-sensitive match for "vertical"
             // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction
             //    be vertical growing left.
-            String writingDirection = VTTParser::collectWord(input, &position);
-            if (writingDirection == verticalGrowingLeftKeyword())
+            if (input.scanRun(valueRun, verticalGrowingLeftKeyword()))
                 m_writingDirection = VerticalGrowingLeft;
 
             // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing
             //    direction be vertical growing right.
-            else if (writingDirection == verticalGrowingRightKeyword())
+            else if (input.scanRun(valueRun, verticalGrowingRightKeyword()))
                 m_writingDirection = VerticalGrowingRight;
-            }
             break;
-        case Line:
-            {
+        }
+        case Line: {
             // 1-2 - Collect chars that are either '-', '%', or a digit.
             // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN
             //    characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
             //    to the step labeled next setting.
-            StringBuilder linePositionBuilder;
-            while (position < input.length() && (input[position] == '-' || input[position] == '%' || isASCIIDigit(input[position])))
-                linePositionBuilder.append(input[position++]);
-            if (position < input.length() && !VTTParser::isValidSettingDelimiter(input[position]))
+            bool isNegative = input.scan('-');
+            int linePosition;
+            unsigned numDigits = input.scanDigits(linePosition);
+            bool isPercentage = input.scan('%');
+
+            if (!input.isAt(valueRun.end()))
                 break;
 
             // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
@@ -927,134 +941,83 @@
             //    jump to the step labeled next setting.
             // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
             //    jump to the step labeled next setting.
-            String linePosition = linePositionBuilder.toString();
-            if (linePosition.find('-', 1) != kNotFound || linePosition.reverseFind("%", linePosition.length() - 2) != kNotFound)
-                break;
 
             // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a
             //    U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
-            if (linePosition[0] == '-' && linePosition[linePosition.length() - 1] == '%')
+            if (!numDigits || (isPercentage && isNegative))
                 break;
 
             // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and
             //    let number be that number.
-            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
-            bool validNumber;
-            int number = linePosition.toInt(&validNumber);
-            if (!validNumber)
-                break;
-
             // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range
             //    0 ≤ number ≤ 100, then jump to the step labeled next setting.
             // 8. Let cue's text track cue line position be number.
             // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue
             //    snap-to-lines flag be false. Otherwise, let it be true.
-            if (linePosition[linePosition.length() - 1] == '%') {
-                if (number < 0 || number > 100)
+            if (isPercentage) {
+                if (linePosition < 0 || linePosition > 100)
                     break;
-
                 // 10 - If '%' then set snap-to-lines flag to false.
                 m_snapToLines = false;
+            } else {
+                if (isNegative)
+                    linePosition = -linePosition;
+                m_snapToLines = true;
             }
-
-            m_linePosition = number;
-            }
+            m_linePosition = linePosition;
             break;
-        case Position:
-            {
-            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the range
-            //    U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
-            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9),
-            //    then jump to the step labeled next setting.
+        }
+        case Position: {
             int number;
-            if (!VTTParser::collectDigitsToInt(input, &position, number))
-                break;
-            if (position >= input.length())
-                break;
-
-            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then jump
-            //    to the step labeled next setting.
-            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step labeled
-            //    next setting.
-            if (input[position++] != '%')
-                break;
-            if (position < input.length() && !VTTParser::isValidSettingDelimiter(input[position]))
-                break;
-
-            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
-            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
-            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
-            if (number < 0 || number > 100)
+            // Steps 1 - 6.
+            if (!scanPercentage(input, valueRun, number))
                 break;
 
             // 7. Let cue's text track cue text position be number.
             m_textPosition = number;
-            }
             break;
-        case Size:
-            {
-            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the
-            //    range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
-            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
-            //    NINE (9), then jump to the step labeled next setting.
+        }
+        case Size: {
             int number;
-            if (!VTTParser::collectDigitsToInt(input, &position, number))
-                break;
-            if (position >= input.length())
-                break;
-
-            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%),
-            //    then jump to the step labeled next setting.
-            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step
-            //    labeled next setting.
-            if (input[position++] != '%')
-                break;
-            if (position < input.length() && !VTTParser::isValidSettingDelimiter(input[position]))
-                break;
-
-            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
-            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
-            if (number < 0 || number > 100)
+            // Steps 1 - 6.
+            if (!scanPercentage(input, valueRun, number))
                 break;
 
             // 7. Let cue's text track cue size be number.
             m_cueSize = number;
-            }
             break;
-        case Align:
-            {
-            String cueAlignment = VTTParser::collectWord(input, &position);
-
+        }
+        case Align: {
             // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
-            if (cueAlignment == startKeyword())
+            if (input.scanRun(valueRun, startKeyword()))
                 m_cueAlignment = Start;
 
             // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
-            else if (cueAlignment == middleKeyword())
+            else if (input.scanRun(valueRun, middleKeyword()))
                 m_cueAlignment = Middle;
 
             // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
-            else if (cueAlignment == endKeyword())
+            else if (input.scanRun(valueRun, endKeyword()))
                 m_cueAlignment = End;
 
             // 4. If value is a case-sensitive match for the string "left", then let cue's text track cue alignment be left alignment.
-            else if (cueAlignment == leftKeyword())
+            else if (input.scanRun(valueRun, leftKeyword()))
                 m_cueAlignment = Left;
 
             // 5. If value is a case-sensitive match for the string "right", then let cue's text track cue alignment be right alignment.
-            else if (cueAlignment == rightKeyword())
+            else if (input.scanRun(valueRun, rightKeyword()))
                 m_cueAlignment = Right;
-            }
             break;
+        }
         case RegionId:
-            m_regionId = VTTParser::collectWord(input, &position);
+            m_regionId = input.extractString(valueRun);
             break;
         case None:
             break;
         }
 
-NextSetting:
-        position = endOfSetting;
+        // Make sure the entire run is consumed.
+        input.skipRun(valueRun);
     }
 
     // If cue's line position is not auto or cue's size is not 100 or cue's
@@ -1084,6 +1047,7 @@
 
 int VTTCue::getCSSSize() const
 {
+    ASSERT(m_displaySize != undefinedSize);
     return m_displaySize;
 }
 
diff --git a/Source/core/html/track/vtt/VTTCue.h b/Source/core/html/track/vtt/VTTCue.h
index 05e6f8e..5398005 100644
--- a/Source/core/html/track/vtt/VTTCue.h
+++ b/Source/core/html/track/vtt/VTTCue.h
@@ -38,6 +38,7 @@
 class Document;
 class ExecutionContext;
 class VTTCue;
+class VTTScanner;
 
 class VTTCueBox FINAL : public HTMLDivElement {
 public:
@@ -162,7 +163,7 @@
         Align,
         RegionId
     };
-    CueSetting settingName(const String&);
+    CueSetting settingName(VTTScanner&);
 
     String m_text;
     int m_linePosition;
@@ -186,11 +187,8 @@
     bool m_notifyRegion : 1;
 };
 
-inline VTTCue* toVTTCue(TextTrackCue* cue)
-{
-    // VTTCue is currently the only TextTrackCue subclass.
-    return static_cast<VTTCue*>(cue);
-}
+// VTTCue is currently the only TextTrackCue subclass.
+DEFINE_TYPE_CASTS(VTTCue, TextTrackCue, cue, true, true);
 
 } // namespace WebCore
 
diff --git a/Source/core/html/track/vtt/VTTParser.cpp b/Source/core/html/track/vtt/VTTParser.cpp
index e1b4b2a..6cb7c45 100644
--- a/Source/core/html/track/vtt/VTTParser.cpp
+++ b/Source/core/html/track/vtt/VTTParser.cpp
@@ -35,103 +35,44 @@
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/Text.h"
 #include "core/html/track/vtt/VTTElement.h"
+#include "core/html/track/vtt/VTTScanner.h"
 #include "platform/text/SegmentedString.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
+using namespace HTMLNames;
+
 const double secondsPerHour = 3600;
 const double secondsPerMinute = 60;
 const double secondsPerMillisecond = 0.001;
 const unsigned fileIdentifierLength = 6;
 
-static unsigned scanDigits(const String& input, unsigned* position)
+bool VTTParser::parseFloatPercentageValue(VTTScanner& valueScanner, float& percentage)
 {
-    unsigned startPosition = *position;
-    while (*position < input.length() && isASCIIDigit(input[*position]))
-        (*position)++;
-    return *position - startPosition;
-}
-
-unsigned VTTParser::collectDigitsToInt(const String& input, unsigned* position, int& number)
-{
-    unsigned startPosition = *position;
-    unsigned numDigits = scanDigits(input, position);
-    if (!numDigits) {
-        number = 0;
-        return 0;
-    }
-    bool validNumber;
-    if (input.is8Bit())
-        number = charactersToInt(input.characters8() + startPosition, numDigits, &validNumber);
-    else
-        number = charactersToInt(input.characters16() + startPosition, numDigits, &validNumber);
-
-    // Since we know that scanDigits only scanned valid (ASCII) digits (and
-    // hence that's what got passed to charactersToInt()), the remaining
-    // failure mode for charactersToInt() is overflow, so if |validNumber| is
-    // not true, then set |number| to the maximum int value.
-    if (!validNumber)
-        number = std::numeric_limits<int>::max();
-    return numDigits;
-}
-
-String VTTParser::collectWord(const String& input, unsigned* position)
-{
-    StringBuilder string;
-    while (*position < input.length() && !isASpace(input[*position]))
-        string.append(input[(*position)++]);
-    return string.toString();
-}
-
-void VTTParser::skipWhiteSpace(const String& line, unsigned* position)
-{
-    while (*position < line.length() && isASpace(line[*position]))
-        (*position)++;
-}
-
-bool VTTParser::parseFloatPercentageValue(const String& value, float& percentage)
-{
+    float number;
+    if (!valueScanner.scanFloat(number))
+        return false;
     // '%' must be present and at the end of the setting value.
-    if (value.isEmpty() || value[value.length() - 1] != '%')
+    if (!valueScanner.scan('%'))
         return false;
-
-    unsigned position = 0;
-    unsigned digitsBeforeDot = scanDigits(value, &position);
-    unsigned digitsAfterDot = 0;
-    if (value[position] == '.') {
-        position++;
-
-        digitsAfterDot = scanDigits(value, &position);
-    }
-
-    // At least one digit required.
-    if (!digitsBeforeDot && !digitsAfterDot)
-        return false;
-
-    float number = value.toFloat();
     if (number < 0 || number > 100)
         return false;
-
     percentage = number;
     return true;
 }
 
-bool VTTParser::parseFloatPercentageValuePair(const String& value, char delimiter, FloatPoint& valuePair)
+bool VTTParser::parseFloatPercentageValuePair(VTTScanner& valueScanner, char delimiter, FloatPoint& valuePair)
 {
-    // The delimiter can't be the first or second value because a pair of
-    // percentages (x%,y%) implies that at least the first two characters
-    // are the first percentage value.
-    size_t delimiterOffset = value.find(delimiter, 2);
-    if (delimiterOffset == kNotFound || delimiterOffset == value.length() - 1)
+    float firstCoord;
+    if (!parseFloatPercentageValue(valueScanner, firstCoord))
         return false;
 
-    float firstCoord;
-    if (!parseFloatPercentageValue(value.substring(0, delimiterOffset), firstCoord))
+    if (!valueScanner.scan(delimiter))
         return false;
 
     float secondCoord;
-    if (!parseFloatPercentageValue(value.substring(delimiterOffset + 1, value.length() - 1), secondCoord))
+    if (!parseFloatPercentageValue(valueScanner, secondCoord))
         return false;
 
     valuePair = FloatPoint(firstCoord, secondCoord);
@@ -301,41 +242,35 @@
 {
     if (line.contains("-->"))
         return collectTimingsAndSettings(line);
-    m_currentId = line;
+    m_currentId = AtomicString(line);
     return TimingsAndSettings;
 }
 
 VTTParser::ParseState VTTParser::collectTimingsAndSettings(const String& line)
 {
+    VTTScanner input(line);
+
     // Collect WebVTT cue timings and settings. (5.3 WebVTT cue timings and settings parsing.)
     // Steps 1 - 3 - Let input be the string being parsed and position be a pointer into input.
-    unsigned position = 0;
-    skipWhiteSpace(line, &position);
+    input.skipWhile<isASpace>();
 
     // Steps 4 - 5 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue start time be the collected time.
-    if (!collectTimeStamp(line, &position, m_currentStartTime))
+    if (!collectTimeStamp(input, m_currentStartTime))
         return BadCue;
-    if (position >= line.length())
-        return BadCue;
-
-    skipWhiteSpace(line, &position);
+    input.skipWhile<isASpace>();
 
     // Steps 6 - 9 - If the next three characters are not "-->", abort and return failure.
-    if (line.find("-->", position) == kNotFound)
+    if (!input.scan("-->"))
         return BadCue;
-    position += 3;
-    if (position >= line.length())
-        return BadCue;
-
-    skipWhiteSpace(line, &position);
+    input.skipWhile<isASpace>();
 
     // Steps 10 - 11 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue end time be the collected time.
-    if (!collectTimeStamp(line, &position, m_currentEndTime))
+    if (!collectTimeStamp(input, m_currentEndTime))
         return BadCue;
-    skipWhiteSpace(line, &position);
+    input.skipWhile<isASpace>();
 
     // Step 12 - Parse the WebVTT settings for the cue (conducted in TextTrackCue).
-    m_currentSettings = line.substring(position, line.length()-1);
+    m_currentSettings = input.restOfInputAsString();
     return CueText;
 }
 
@@ -439,7 +374,7 @@
 
 void VTTParser::resetCueValues()
 {
-    m_currentId = emptyString();
+    m_currentId = emptyAtom;
     m_currentSettings = emptyString();
     m_currentStartTime = 0;
     m_currentEndTime = 0;
@@ -468,7 +403,13 @@
     m_regionList.append(region);
 }
 
-bool VTTParser::collectTimeStamp(const String& line, unsigned* position, double& timeStamp)
+bool VTTParser::collectTimeStamp(const String& line, double& timeStamp)
+{
+    VTTScanner input(line);
+    return collectTimeStamp(input, timeStamp);
+}
+
+bool VTTParser::collectTimeStamp(VTTScanner& input, double& timeStamp)
 {
     // Collect a WebVTT timestamp (5.3 WebVTT cue timings and settings parsing.)
     // Steps 1 - 4 - Initial checks, let most significant units be minutes.
@@ -478,25 +419,21 @@
     // Steps 5 - 7 - Collect a sequence of characters that are 0-9.
     // If not 2 characters or value is greater than 59, interpret as hours.
     int value1;
-    unsigned value1Digits = collectDigitsToInt(line, position, value1);
+    unsigned value1Digits = input.scanDigits(value1);
     if (!value1Digits)
         return false;
     if (value1Digits != 2 || value1 > 59)
         mode = Hours;
 
     // Steps 8 - 11 - Collect the next sequence of 0-9 after ':' (must be 2 chars).
-    if (*position >= line.length() || line[(*position)++] != ':')
-        return false;
     int value2;
-    if (collectDigitsToInt(line, position, value2) != 2)
+    if (!input.scan(':') || input.scanDigits(value2) != 2)
         return false;
 
     // Step 12 - Detect whether this timestamp includes hours.
     int value3;
-    if (mode == Hours || (*position < line.length() && line[*position] == ':')) {
-        if (*position >= line.length() || line[(*position)++] != ':')
-            return false;
-        if (collectDigitsToInt(line, position, value3) != 2)
+    if (mode == Hours || input.match(':')) {
+        if (!input.scan(':') || input.scanDigits(value3) != 2)
             return false;
     } else {
         value3 = value2;
@@ -505,10 +442,8 @@
     }
 
     // Steps 13 - 17 - Collect next sequence of 0-9 after '.' (must be 3 chars).
-    if (*position >= line.length() || line[(*position)++] != '.')
-        return false;
     int value4;
-    if (collectDigitsToInt(line, position, value4) != 3)
+    if (!input.scan('.') || input.scanDigits(value4) != 3)
         return false;
     if (value2 > 59 || value3 > 59)
         return false;
@@ -611,10 +546,9 @@
         break;
     }
     case VTTTokenTypes::TimestampTag: {
-        unsigned position = 0;
         String charactersString = m_token.characters();
         double parsedTimeStamp;
-        if (VTTParser::collectTimeStamp(charactersString, &position, parsedTimeStamp))
+        if (VTTParser::collectTimeStamp(charactersString, parsedTimeStamp))
             m_currentNode->parserAppendChild(ProcessingInstruction::create(document, "timestamp", charactersString));
         break;
     }
diff --git a/Source/core/html/track/vtt/VTTParser.h b/Source/core/html/track/vtt/VTTParser.h
index df4e584..93170e1 100644
--- a/Source/core/html/track/vtt/VTTParser.h
+++ b/Source/core/html/track/vtt/VTTParser.h
@@ -34,7 +34,7 @@
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/DocumentFragment.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/html/track/vtt/BufferedLineReader.h"
 #include "core/html/track/vtt/VTTCue.h"
 #include "core/html/track/vtt/VTTRegion.h"
@@ -44,9 +44,8 @@
 
 namespace WebCore {
 
-using namespace HTMLNames;
-
 class Document;
+class VTTScanner;
 
 class VTTParserClient {
 public:
@@ -75,31 +74,28 @@
 
     static inline bool isRecognizedTag(const AtomicString& tagName)
     {
-        return tagName == iTag
-            || tagName == bTag
-            || tagName == uTag
-            || tagName == rubyTag
-            || tagName == rtTag;
+        return tagName == HTMLNames::iTag
+            || tagName == HTMLNames::bTag
+            || tagName == HTMLNames::uTag
+            || tagName == HTMLNames::rubyTag
+            || tagName == HTMLNames::rtTag;
     }
-
-    static inline bool isASpace(char c)
+    static inline bool isASpace(UChar c)
     {
         // WebVTT space characters are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), and U+000D CARRIAGE RETURN    (CR).
         return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r';
     }
-    static inline bool isValidSettingDelimiter(char c)
+    static inline bool isValidSettingDelimiter(UChar c)
     {
         // ... a WebVTT cue consists of zero or more of the following components, in any order, separated from each other by one or more
         // U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
         return c == ' ' || c == '\t';
     }
-    static unsigned collectDigitsToInt(const String& input, unsigned* position, int& number);
-    static String collectWord(const String&, unsigned*);
-    static bool collectTimeStamp(const String&, unsigned*, double& timeStamp);
+    static bool collectTimeStamp(const String&, double& timeStamp);
 
     // Useful functions for parsing percentage settings.
-    static bool parseFloatPercentageValue(const String&, float&);
-    static bool parseFloatPercentageValuePair(const String&, char, FloatPoint&);
+    static bool parseFloatPercentageValue(VTTScanner& valueScanner, float& percentage);
+    static bool parseFloatPercentageValuePair(VTTScanner&, char, FloatPoint&);
 
     // Create the DocumentFragment representation of the WebVTT cue text.
     static PassRefPtr<DocumentFragment> createDocumentFragmentFromCueText(Document&, const String&);
@@ -133,11 +129,11 @@
     void collectMetadataHeader(const String&);
     void createNewRegion(const String& headerValue);
 
-    static void skipWhiteSpace(const String&, unsigned*);
+    static bool collectTimeStamp(VTTScanner& input, double& timeStamp);
 
     BufferedLineReader m_lineReader;
     OwnPtr<TextResourceDecoder> m_decoder;
-    String m_currentId;
+    AtomicString m_currentId;
     double m_currentStartTime;
     double m_currentEndTime;
     StringBuilder m_currentContent;
diff --git a/Source/core/html/track/vtt/VTTRegion.cpp b/Source/core/html/track/vtt/VTTRegion.cpp
index 4f39fb5..dd7613e 100644
--- a/Source/core/html/track/vtt/VTTRegion.cpp
+++ b/Source/core/html/track/vtt/VTTRegion.cpp
@@ -37,6 +37,7 @@
 #include "core/dom/DOMTokenList.h"
 #include "core/html/HTMLDivElement.h"
 #include "core/html/track/vtt/VTTParser.h"
+#include "core/html/track/vtt/VTTScanner.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderObject.h"
 #include "platform/Logging.h"
@@ -190,83 +191,102 @@
     setScroll(region->scroll(), ASSERT_NO_EXCEPTION);
 }
 
-void VTTRegion::setRegionSettings(const String& input)
+void VTTRegion::setRegionSettings(const String& inputString)
 {
-    m_settings = input;
-    unsigned position = 0;
+    m_settings = inputString;
 
-    while (position < input.length()) {
-        while (position < input.length() && VTTParser::isValidSettingDelimiter(input[position]))
-            position++;
+    VTTScanner input(inputString);
 
-        if (position >= input.length())
+    while (!input.isAtEnd()) {
+        input.skipWhile<VTTParser::isValidSettingDelimiter>();
+
+        if (input.isAtEnd())
             break;
 
-        parseSetting(input, &position);
+        // Scan the name part.
+        RegionSetting name = scanSettingName(input);
+
+        // Verify that we're looking at a '='.
+        if (name == None || !input.scan('=')) {
+            input.skipUntil<VTTParser::isASpace>();
+            continue;
+        }
+
+        // Scan the value part.
+        parseSettingValue(name, input);
     }
 }
 
-VTTRegion::RegionSetting VTTRegion::getSettingFromString(const String& setting)
+VTTRegion::RegionSetting VTTRegion::scanSettingName(VTTScanner& input)
 {
-    DEFINE_STATIC_LOCAL(const AtomicString, idKeyword, ("id", AtomicString::ConstructFromLiteral));
-    DEFINE_STATIC_LOCAL(const AtomicString, heightKeyword, ("height", AtomicString::ConstructFromLiteral));
-    DEFINE_STATIC_LOCAL(const AtomicString, widthKeyword, ("width", AtomicString::ConstructFromLiteral));
-    DEFINE_STATIC_LOCAL(const AtomicString, regionAnchorKeyword, ("regionanchor", AtomicString::ConstructFromLiteral));
-    DEFINE_STATIC_LOCAL(const AtomicString, viewportAnchorKeyword, ("viewportanchor", AtomicString::ConstructFromLiteral));
-    DEFINE_STATIC_LOCAL(const AtomicString, scrollKeyword, ("scroll", AtomicString::ConstructFromLiteral));
-
-    if (setting == idKeyword)
+    if (input.scan("id"))
         return Id;
-    if (setting == heightKeyword)
+    if (input.scan("height"))
         return Height;
-    if (setting == widthKeyword)
+    if (input.scan("width"))
         return Width;
-    if (setting == viewportAnchorKeyword)
+    if (input.scan("viewportanchor"))
         return ViewportAnchor;
-    if (setting == regionAnchorKeyword)
+    if (input.scan("regionanchor"))
         return RegionAnchor;
-    if (setting == scrollKeyword)
+    if (input.scan("scroll"))
         return Scroll;
 
     return None;
 }
 
-void VTTRegion::parseSettingValue(RegionSetting setting, const String& value)
+static inline bool parsedEntireRun(const VTTScanner& input, const VTTScanner::Run& run)
+{
+    return input.isAt(run.end());
+}
+
+void VTTRegion::parseSettingValue(RegionSetting setting, VTTScanner& input)
 {
     DEFINE_STATIC_LOCAL(const AtomicString, scrollUpValueKeyword, ("up", AtomicString::ConstructFromLiteral));
 
+    VTTScanner::Run valueRun = input.collectUntil<VTTParser::isASpace>();
+
     switch (setting) {
-    case Id:
-        if (value.find("-->") == kNotFound)
-            m_id = value;
+    case Id: {
+        String stringValue = input.extractString(valueRun);
+        if (stringValue.find("-->") == kNotFound)
+            m_id = stringValue;
         break;
+    }
     case Width: {
         float floatWidth;
-        if (VTTParser::parseFloatPercentageValue(value, floatWidth))
+        if (VTTParser::parseFloatPercentageValue(input, floatWidth) && parsedEntireRun(input, valueRun))
             m_width = floatWidth;
         else
             WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid Width");
         break;
     }
     case Height: {
-        unsigned position = 0;
         int number;
-        if (VTTParser::collectDigitsToInt(value, &position, number) && position == value.length())
+        if (input.scanDigits(number) && parsedEntireRun(input, valueRun))
             m_heightInLines = number;
         else
             WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid Height");
         break;
     }
-    case RegionAnchor:
-        if (!VTTParser::parseFloatPercentageValuePair(value, ',', m_regionAnchor))
+    case RegionAnchor: {
+        FloatPoint anchor;
+        if (VTTParser::parseFloatPercentageValuePair(input, ',', anchor) && parsedEntireRun(input, valueRun))
+            m_regionAnchor = anchor;
+        else
             WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid RegionAnchor");
         break;
-    case ViewportAnchor:
-        if (!VTTParser::parseFloatPercentageValuePair(value, ',', m_viewportAnchor))
+    }
+    case ViewportAnchor: {
+        FloatPoint anchor;
+        if (VTTParser::parseFloatPercentageValuePair(input, ',', anchor) && parsedEntireRun(input, valueRun))
+            m_viewportAnchor = anchor;
+        else
             WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid ViewportAnchor");
         break;
+    }
     case Scroll:
-        if (value == scrollUpValueKeyword)
+        if (input.scanRun(valueRun, scrollUpValueKeyword))
             m_scroll = true;
         else
             WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid Scroll");
@@ -274,20 +294,8 @@
     case None:
         break;
     }
-}
 
-void VTTRegion::parseSetting(const String& input, unsigned* position)
-{
-    String setting = VTTParser::collectWord(input, position);
-
-    size_t equalOffset = setting.find('=', 1);
-    if (equalOffset == kNotFound || !equalOffset || equalOffset == setting.length() - 1)
-        return;
-
-    RegionSetting name = getSettingFromString(setting.substring(0, equalOffset));
-    String value = setting.substring(equalOffset + 1, setting.length() - 1);
-
-    parseSettingValue(name, value);
+    input.skipRun(valueRun);
 }
 
 const AtomicString& VTTRegion::textTrackCueContainerShadowPseudoId()
@@ -429,11 +437,11 @@
         0.0,
         CSSPrimitiveValue::CSS_PX);
 
-    m_cueContainer->setPseudo(textTrackCueContainerShadowPseudoId());
+    m_cueContainer->setShadowPseudoId(textTrackCueContainerShadowPseudoId());
     m_regionDisplayTree->appendChild(m_cueContainer);
 
     // 7.5 Every WebVTT region object is initialised with the following CSS
-    m_regionDisplayTree->setPseudo(textTrackRegionShadowPseudoId());
+    m_regionDisplayTree->setShadowPseudoId(textTrackRegionShadowPseudoId());
 }
 
 void VTTRegion::startTimer()
diff --git a/Source/core/html/track/vtt/VTTRegion.h b/Source/core/html/track/vtt/VTTRegion.h
index f9452c2..c160162 100644
--- a/Source/core/html/track/vtt/VTTRegion.h
+++ b/Source/core/html/track/vtt/VTTRegion.h
@@ -43,6 +43,7 @@
 class ExceptionState;
 class HTMLDivElement;
 class VTTCueBox;
+class VTTScanner;
 
 class VTTRegion : public RefCounted<VTTRegion> {
 public:
@@ -112,9 +113,8 @@
         ViewportAnchor,
         Scroll
     };
-    RegionSetting getSettingFromString(const String&);
-    void parseSettingValue(RegionSetting, const String&);
-    void parseSetting(const String&, unsigned*);
+    RegionSetting scanSettingName(VTTScanner&);
+    void parseSettingValue(RegionSetting, VTTScanner&);
 
     static const AtomicString& textTrackCueContainerShadowPseudoId();
     static const AtomicString& textTrackCueContainerScrollingClass();
diff --git a/Source/core/html/track/vtt/VTTRegion.idl b/Source/core/html/track/vtt/VTTRegion.idl
index b0348b4..398f740 100644
--- a/Source/core/html/track/vtt/VTTRegion.idl
+++ b/Source/core/html/track/vtt/VTTRegion.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    Constructor(),
+    Constructor,
     RuntimeEnabled=WebVTTRegions
 ] interface VTTRegion {
     readonly attribute TextTrack track;
diff --git a/Source/core/html/track/vtt/VTTScanner.cpp b/Source/core/html/track/vtt/VTTScanner.cpp
new file mode 100644
index 0000000..590178f
--- /dev/null
+++ b/Source/core/html/track/vtt/VTTScanner.cpp
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE
+ * COPYRIGHT HOLDER 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.
+ */
+
+#include "config.h"
+#include "core/html/track/vtt/VTTScanner.h"
+
+namespace WebCore {
+
+VTTScanner::VTTScanner(const String& line) : m_is8Bit(line.is8Bit())
+{
+    if (m_is8Bit) {
+        m_data.characters8 = line.characters8();
+        m_end.characters8 = m_data.characters8 + line.length();
+    } else {
+        m_data.characters16 = line.characters16();
+        m_end.characters16 = m_data.characters16 + line.length();
+    }
+}
+
+bool VTTScanner::scan(char c)
+{
+    if (!match(c))
+        return false;
+    advance();
+    return true;
+}
+
+bool VTTScanner::scan(const LChar* characters, size_t charactersCount)
+{
+    unsigned matchLength = m_is8Bit ? m_end.characters8 - m_data.characters8 : m_end.characters16 - m_data.characters16;
+    if (matchLength < charactersCount)
+        return false;
+    bool matched;
+    if (m_is8Bit)
+        matched = WTF::equal(m_data.characters8, characters, charactersCount);
+    else
+        matched = WTF::equal(m_data.characters16, characters, charactersCount);
+    if (matched)
+        advance(charactersCount);
+    return matched;
+}
+
+bool VTTScanner::scanRun(const Run& run, const String& toMatch)
+{
+    ASSERT(run.start() == position());
+    ASSERT(run.start() <= end());
+    ASSERT(run.end() >= run.start());
+    ASSERT(run.end() <= end());
+    size_t matchLength = run.length();
+    if (toMatch.length() > matchLength)
+        return false;
+    bool matched;
+    if (m_is8Bit)
+        matched = WTF::equal(toMatch.impl(), m_data.characters8, matchLength);
+    else
+        matched = WTF::equal(toMatch.impl(), m_data.characters16, matchLength);
+    if (matched)
+        seekTo(run.end());
+    return matched;
+}
+
+void VTTScanner::skipRun(const Run& run)
+{
+    ASSERT(run.start() <= end());
+    ASSERT(run.end() >= run.start());
+    ASSERT(run.end() <= end());
+    seekTo(run.end());
+}
+
+String VTTScanner::extractString(const Run& run)
+{
+    ASSERT(run.start() == position());
+    ASSERT(run.start() <= end());
+    ASSERT(run.end() >= run.start());
+    ASSERT(run.end() <= end());
+    String s;
+    if (m_is8Bit)
+        s = String(m_data.characters8, run.length());
+    else
+        s = String(m_data.characters16, run.length());
+    seekTo(run.end());
+    return s;
+}
+
+String VTTScanner::restOfInputAsString()
+{
+    Run rest(position(), end(), m_is8Bit);
+    return extractString(rest);
+}
+
+unsigned VTTScanner::scanDigits(int& number)
+{
+    Run runOfDigits = collectWhile<isASCIIDigit>();
+    if (runOfDigits.isEmpty()) {
+        number = 0;
+        return 0;
+    }
+    bool validNumber;
+    size_t numDigits = runOfDigits.length();
+    if (m_is8Bit)
+        number = charactersToInt(m_data.characters8, numDigits, &validNumber);
+    else
+        number = charactersToInt(m_data.characters16, numDigits, &validNumber);
+
+    // Since we know that scanDigits only scanned valid (ASCII) digits (and
+    // hence that's what got passed to charactersToInt()), the remaining
+    // failure mode for charactersToInt() is overflow, so if |validNumber| is
+    // not true, then set |number| to the maximum int value.
+    if (!validNumber)
+        number = std::numeric_limits<int>::max();
+    // Consume the digits.
+    seekTo(runOfDigits.end());
+    return numDigits;
+}
+
+bool VTTScanner::scanFloat(float& number)
+{
+    Run integerRun = collectWhile<isASCIIDigit>();
+    seekTo(integerRun.end());
+    Run decimalRun(position(), position(), m_is8Bit);
+    if (scan('.')) {
+        decimalRun = collectWhile<isASCIIDigit>();
+        seekTo(decimalRun.end());
+    }
+
+    // At least one digit required.
+    if (integerRun.isEmpty() && decimalRun.isEmpty()) {
+        // Restore to starting position.
+        seekTo(integerRun.start());
+        return false;
+    }
+
+    size_t lengthOfFloat = Run(integerRun.start(), position(), m_is8Bit).length();
+    bool validNumber;
+    if (m_is8Bit)
+        number = charactersToFloat(integerRun.start(), lengthOfFloat, &validNumber);
+    else
+        number = charactersToFloat(reinterpret_cast<const UChar*>(integerRun.start()), lengthOfFloat, &validNumber);
+
+    if (!validNumber)
+        number = std::numeric_limits<float>::max();
+    return true;
+}
+
+}
diff --git a/Source/core/html/track/vtt/VTTScanner.h b/Source/core/html/track/vtt/VTTScanner.h
new file mode 100644
index 0000000..aa097e7
--- /dev/null
+++ b/Source/core/html/track/vtt/VTTScanner.h
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE
+ * COPYRIGHT HOLDER 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.
+ */
+
+#ifndef VTTScanner_h
+#define VTTScanner_h
+
+#include "platform/ParsingUtilities.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+// Helper class for "scanning" an input string and performing parsing of
+// "micro-syntax"-like constructs.
+//
+// There's two primary operations: match and scan.
+//
+// The 'match' operation matches an explicitly or implicitly specified sequence
+// against the characters ahead of the current input pointer, and returns true
+// if the sequence can be matched.
+//
+// The 'scan' operation performs a 'match', and if the match is successful it
+// advance the input pointer past the matched sequence.
+class VTTScanner {
+    WTF_MAKE_NONCOPYABLE(VTTScanner);
+public:
+    explicit VTTScanner(const String& line);
+
+    typedef const LChar* Position;
+
+    class Run {
+    public:
+        Run(Position start, Position end, bool is8Bit)
+            : m_start(start), m_end(end), m_is8Bit(is8Bit) { }
+
+        Position start() const { return m_start; }
+        Position end() const { return m_end; }
+
+        bool isEmpty() const { return m_start == m_end; }
+        size_t length() const;
+
+    private:
+        Position m_start;
+        Position m_end;
+        bool m_is8Bit;
+    };
+
+    // Check if the input pointer points at the specified position.
+    bool isAt(Position checkPosition) const { return position() == checkPosition; }
+    // Check if the input pointer points at the end of the input.
+    bool isAtEnd() const { return position() == end(); }
+    // Match the character |c| against the character at the input pointer (~lookahead).
+    bool match(char c) const { return !isAtEnd() && currentChar() == c; }
+    // Scan the character |c|.
+    bool scan(char);
+    // Scan the first |charactersCount| characters of the string |characters|.
+    bool scan(const LChar* characters, size_t charactersCount);
+
+    // Scan the literal |characters|.
+    template<unsigned charactersCount>
+    bool scan(const char (&characters)[charactersCount]);
+
+    // Skip (advance the input pointer) as long as the specified
+    // |characterPredicate| returns true, and the input pointer is not passed
+    // the end of the input.
+    template<bool characterPredicate(UChar)>
+    void skipWhile();
+
+    // Like skipWhile, but using a negated predicate.
+    template<bool characterPredicate(UChar)>
+    void skipUntil();
+
+    // Return the run of characters for which the specified
+    // |characterPredicate| returns true. The start of the run will be the
+    // current input pointer.
+    template<bool characterPredicate(UChar)>
+    Run collectWhile();
+
+    // Like collectWhile, but using a negated predicate.
+    template<bool characterPredicate(UChar)>
+    Run collectUntil();
+
+    // Scan the string |toMatch|, using the specified |run| as the sequence to
+    // match against.
+    bool scanRun(const Run&, const String& toMatch);
+
+    // Skip to the end of the specified |run|.
+    void skipRun(const Run&);
+
+    // Return the String made up of the characters in |run|, and advance the
+    // input pointer to the end of the run.
+    String extractString(const Run&);
+
+    // Return a String constructed from the rest of the input (between input
+    // pointer and end of input), and advance the input pointer accordingly.
+    String restOfInputAsString();
+
+    // Scan a set of ASCII digits from the input. Return the number of digits
+    // scanned, and set |number| to the computed value. If the digits make up a
+    // number that does not fit the 'int' type, |number| is set to INT_MAX.
+    // Note: Does not handle sign.
+    unsigned scanDigits(int& number);
+
+    // Scan a floating point value on one of the forms: \d+\.? \d+\.\d+ \.\d+
+    bool scanFloat(float& number);
+
+protected:
+    Position position() const { return m_data.characters8; }
+    Position end() const { return m_end.characters8; }
+    void seekTo(Position);
+    UChar currentChar() const;
+    void advance(unsigned amount = 1);
+    // Adapt a UChar-predicate to an LChar-predicate.
+    // (For use with skipWhile/Until from ParsingUtilities.h).
+    template<bool characterPredicate(UChar)>
+    static inline bool LCharPredicateAdapter(LChar c) { return characterPredicate(c); }
+    union {
+        const LChar* characters8;
+        const UChar* characters16;
+    } m_data;
+    union {
+        const LChar* characters8;
+        const UChar* characters16;
+    } m_end;
+    bool m_is8Bit;
+};
+
+inline size_t VTTScanner::Run::length() const
+{
+    if (m_is8Bit)
+        return m_end - m_start;
+    return reinterpret_cast<const UChar*>(m_end) - reinterpret_cast<const UChar*>(m_start);
+}
+
+template<unsigned charactersCount>
+inline bool VTTScanner::scan(const char (&characters)[charactersCount])
+{
+    return scan(reinterpret_cast<const LChar*>(characters), charactersCount - 1);
+}
+
+template<bool characterPredicate(UChar)>
+inline void VTTScanner::skipWhile()
+{
+    if (m_is8Bit)
+        ::skipWhile<LChar, LCharPredicateAdapter<characterPredicate> >(m_data.characters8, m_end.characters8);
+    else
+        ::skipWhile<UChar, characterPredicate>(m_data.characters16, m_end.characters16);
+}
+
+template<bool characterPredicate(UChar)>
+inline void VTTScanner::skipUntil()
+{
+    if (m_is8Bit)
+        ::skipUntil<LChar, LCharPredicateAdapter<characterPredicate> >(m_data.characters8, m_end.characters8);
+    else
+        ::skipUntil<UChar, characterPredicate>(m_data.characters16, m_end.characters16);
+}
+
+template<bool characterPredicate(UChar)>
+inline VTTScanner::Run VTTScanner::collectWhile()
+{
+    if (m_is8Bit) {
+        const LChar* current = m_data.characters8;
+        ::skipWhile<LChar, LCharPredicateAdapter<characterPredicate> >(current, m_end.characters8);
+        return Run(position(), current, m_is8Bit);
+    }
+    const UChar* current = m_data.characters16;
+    ::skipWhile<UChar, characterPredicate>(current, m_end.characters16);
+    return Run(position(), reinterpret_cast<Position>(current), m_is8Bit);
+}
+
+template<bool characterPredicate(UChar)>
+inline VTTScanner::Run VTTScanner::collectUntil()
+{
+    if (m_is8Bit) {
+        const LChar* current = m_data.characters8;
+        ::skipUntil<LChar, LCharPredicateAdapter<characterPredicate> >(current, m_end.characters8);
+        return Run(position(), current, m_is8Bit);
+    }
+    const UChar* current = m_data.characters16;
+    ::skipUntil<UChar, characterPredicate>(current, m_end.characters16);
+    return Run(position(), reinterpret_cast<Position>(current), m_is8Bit);
+}
+
+inline void VTTScanner::seekTo(Position position)
+{
+    ASSERT(position <= end());
+    m_data.characters8 = position;
+}
+
+inline UChar VTTScanner::currentChar() const
+{
+    ASSERT(position() < end());
+    return m_is8Bit ? *m_data.characters8 : *m_data.characters16;
+}
+
+inline void VTTScanner::advance(unsigned amount)
+{
+    ASSERT(position() < end());
+    if (m_is8Bit)
+        m_data.characters8 += amount;
+    else
+        m_data.characters16 += amount;
+}
+
+}
+
+#endif
diff --git a/Source/core/html/track/vtt/VTTScannerTest.cpp b/Source/core/html/track/vtt/VTTScannerTest.cpp
new file mode 100644
index 0000000..d5bcfb8
--- /dev/null
+++ b/Source/core/html/track/vtt/VTTScannerTest.cpp
@@ -0,0 +1,352 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE
+ * COPYRIGHT HOLDER 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.
+ */
+
+#include "config.h"
+#include "core/html/track/vtt/VTTScanner.h"
+
+#include "wtf/text/WTFString.h"
+
+#include <gtest/gtest.h>
+
+using WebCore::VTTScanner;
+
+namespace {
+
+TEST(VTTScanner, Constructor)
+{
+    String data8("foo");
+    EXPECT_TRUE(data8.is8Bit());
+    VTTScanner scanner8(data8);
+    EXPECT_FALSE(scanner8.isAtEnd());
+
+    String data16(data8);
+    data16.ensure16Bit();
+    EXPECT_FALSE(data16.is8Bit());
+    VTTScanner scanner16(data16);
+    EXPECT_FALSE(scanner16.isAtEnd());
+
+    VTTScanner scannerEmpty(emptyString());
+    EXPECT_TRUE(scannerEmpty.isAtEnd());
+}
+
+void scanSequenceHelper1(const String& input)
+{
+    VTTScanner scanner(input);
+    EXPECT_FALSE(scanner.isAtEnd());
+    EXPECT_TRUE(scanner.match('f'));
+    EXPECT_FALSE(scanner.match('o'));
+
+    EXPECT_TRUE(scanner.scan('f'));
+    EXPECT_FALSE(scanner.match('f'));
+    EXPECT_TRUE(scanner.match('o'));
+
+    EXPECT_FALSE(scanner.scan('e'));
+    EXPECT_TRUE(scanner.scan('o'));
+
+    EXPECT_TRUE(scanner.scan('e'));
+    EXPECT_FALSE(scanner.match('e'));
+
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+// Run TESTFUNC with DATA in Latin and then UTF-16. (Requires DATA being Latin.)
+#define TEST_WITH(TESTFUNC, DATA) do {      \
+    String data8(DATA);                     \
+    EXPECT_TRUE(data8.is8Bit());            \
+    TESTFUNC(data8);                        \
+    \
+    String data16(data8);                   \
+    data16.ensure16Bit();                   \
+    EXPECT_FALSE(data16.is8Bit());          \
+    TESTFUNC(data16);                       \
+} while (false)
+
+
+// Exercises match(c) and scan(c).
+TEST(VTTScanner, BasicOperations1)
+{
+    TEST_WITH(scanSequenceHelper1, "foe");
+}
+
+void scanSequenceHelper2(const String& input)
+{
+    VTTScanner scanner(input);
+    EXPECT_FALSE(scanner.isAtEnd());
+    EXPECT_FALSE(scanner.scan("fe"));
+
+    EXPECT_TRUE(scanner.scan("fo"));
+    EXPECT_FALSE(scanner.isAtEnd());
+
+    EXPECT_FALSE(scanner.scan("ee"));
+
+    EXPECT_TRUE(scanner.scan('e'));
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+// Exercises scan(<literal>[, length]).
+TEST(VTTScanner, BasicOperations2)
+{
+    TEST_WITH(scanSequenceHelper2, "foe");
+}
+
+bool lowerCaseAlpha(UChar c)
+{
+    return c >= 'a' && c <= 'z';
+}
+
+void scanWithPredicate(const String& input)
+{
+    VTTScanner scanner(input);
+    EXPECT_FALSE(scanner.isAtEnd());
+    // Collect "bad".
+    VTTScanner::Run lcRun = scanner.collectWhile<lowerCaseAlpha>();
+    // collectWhile doesn't move the scan position.
+    EXPECT_TRUE(scanner.match('b'));
+    // Consume "bad".
+    scanner.skipWhile<lowerCaseAlpha>();
+    EXPECT_TRUE(scanner.match('A'));
+    EXPECT_TRUE(scanner.isAt(lcRun.end()));
+
+    // Consume "A".
+    EXPECT_TRUE(scanner.scan('A'));
+
+    // Collect "bing".
+    lcRun = scanner.collectWhile<lowerCaseAlpha>();
+    // collectWhile doesn't move the scan position.
+    EXPECT_FALSE(scanner.isAtEnd());
+    // Consume "bing".
+    scanner.skipWhile<lowerCaseAlpha>();
+    EXPECT_TRUE(scanner.isAt(lcRun.end()));
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+// Tests skipWhile() and collectWhile().
+TEST(VTTScanner, PredicateScanning)
+{
+    TEST_WITH(scanWithPredicate, "badAbing");
+}
+
+void scanWithInvPredicate(const String& input)
+{
+    VTTScanner scanner(input);
+    EXPECT_FALSE(scanner.isAtEnd());
+    // Collect "BAD".
+    VTTScanner::Run ucRun = scanner.collectUntil<lowerCaseAlpha>();
+    // collectUntil doesn't move the scan position.
+    EXPECT_TRUE(scanner.match('B'));
+    // Consume "BAD".
+    scanner.skipUntil<lowerCaseAlpha>();
+    EXPECT_TRUE(scanner.match('a'));
+    EXPECT_TRUE(scanner.isAt(ucRun.end()));
+
+    // Consume "a".
+    EXPECT_TRUE(scanner.scan('a'));
+
+    // Collect "BING".
+    ucRun = scanner.collectUntil<lowerCaseAlpha>();
+    // collectUntil doesn't move the scan position.
+    EXPECT_FALSE(scanner.isAtEnd());
+    // Consume "BING".
+    scanner.skipUntil<lowerCaseAlpha>();
+    EXPECT_TRUE(scanner.isAt(ucRun.end()));
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+// Tests skipUntil() and collectUntil().
+TEST(VTTScanner, InversePredicateScanning)
+{
+    TEST_WITH(scanWithInvPredicate, "BADaBING");
+}
+
+void scanRuns(const String& input)
+{
+    String fooString("foo");
+    String barString("bar");
+    VTTScanner scanner(input);
+    EXPECT_FALSE(scanner.isAtEnd());
+    VTTScanner::Run word = scanner.collectWhile<lowerCaseAlpha>();
+    EXPECT_FALSE(scanner.scanRun(word, barString));
+    EXPECT_TRUE(scanner.scanRun(word, fooString));
+
+    EXPECT_TRUE(scanner.match(':'));
+    EXPECT_TRUE(scanner.scan(':'));
+
+    // Skip 'baz'.
+    scanner.skipRun(scanner.collectWhile<lowerCaseAlpha>());
+
+    EXPECT_TRUE(scanner.match(':'));
+    EXPECT_TRUE(scanner.scan(':'));
+
+    word = scanner.collectWhile<lowerCaseAlpha>();
+    EXPECT_FALSE(scanner.scanRun(word, fooString));
+    EXPECT_TRUE(scanner.scanRun(word, barString));
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+// Tests scanRun/skipRun.
+TEST(VTTScanner, RunScanning)
+{
+    TEST_WITH(scanRuns, "foo:baz:bar");
+}
+
+void scanRunsToStrings(const String& input)
+{
+    VTTScanner scanner(input);
+    EXPECT_FALSE(scanner.isAtEnd());
+    VTTScanner::Run word = scanner.collectWhile<lowerCaseAlpha>();
+    String fooString = scanner.extractString(word);
+    EXPECT_EQ(fooString, "foo");
+    EXPECT_TRUE(scanner.isAt(word.end()));
+
+    EXPECT_TRUE(scanner.match(':'));
+    EXPECT_TRUE(scanner.scan(':'));
+
+    word = scanner.collectWhile<lowerCaseAlpha>();
+    String barString = scanner.extractString(word);
+    EXPECT_EQ(barString, "bar");
+    EXPECT_TRUE(scanner.isAt(word.end()));
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+// Tests extractString.
+TEST(VTTScanner, ExtractString)
+{
+    TEST_WITH(scanRunsToStrings, "foo:bar");
+}
+
+void tailStringExtract(const String& input)
+{
+    VTTScanner scanner(input);
+    EXPECT_TRUE(scanner.scan("foo"));
+    EXPECT_TRUE(scanner.scan(':'));
+    String barSuffix = scanner.restOfInputAsString();
+    EXPECT_EQ(barSuffix, "bar");
+
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+// Tests restOfInputAsString().
+TEST(VTTScanner, ExtractRestAsString)
+{
+    TEST_WITH(tailStringExtract, "foo:bar");
+}
+
+void scanDigits1(const String& input)
+{
+    VTTScanner scanner(input);
+    EXPECT_TRUE(scanner.scan("foo"));
+    int number;
+    EXPECT_EQ(scanner.scanDigits(number), 0u);
+    EXPECT_EQ(number, 0);
+    EXPECT_TRUE(scanner.scan(' '));
+    EXPECT_EQ(scanner.scanDigits(number), 3u);
+    EXPECT_TRUE(scanner.match(' '));
+    EXPECT_EQ(number, 123);
+
+    EXPECT_TRUE(scanner.scan(' '));
+    EXPECT_TRUE(scanner.scan("bar"));
+    EXPECT_TRUE(scanner.scan(' '));
+
+    EXPECT_EQ(scanner.scanDigits(number), 5u);
+    EXPECT_EQ(number, 45678);
+
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+void scanDigits2(const String& input)
+{
+    VTTScanner scanner(input);
+    int number;
+    EXPECT_EQ(scanner.scanDigits(number), 0u);
+    EXPECT_EQ(number, 0);
+    EXPECT_TRUE(scanner.scan('-'));
+    EXPECT_EQ(scanner.scanDigits(number), 3u);
+    EXPECT_EQ(number, 654);
+
+    EXPECT_TRUE(scanner.scan(' '));
+
+    EXPECT_EQ(scanner.scanDigits(number), 19u);
+    EXPECT_EQ(number, std::numeric_limits<int>::max());
+
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+// Tests scanDigits().
+TEST(VTTScanner, ScanDigits)
+{
+    TEST_WITH(scanDigits1, "foo 123 bar 45678");
+    TEST_WITH(scanDigits2, "-654 1000000000000000000");
+}
+
+void scanFloatValue(const String& input)
+{
+    VTTScanner scanner(input);
+    float value;
+    // "1."
+    EXPECT_TRUE(scanner.scanFloat(value));
+    EXPECT_EQ(value, 1.0f);
+    EXPECT_TRUE(scanner.scan(' '));
+
+    // "1.0"
+    EXPECT_TRUE(scanner.scanFloat(value));
+    EXPECT_EQ(value, 1.0f);
+    EXPECT_TRUE(scanner.scan(' '));
+
+    // ".0"
+    EXPECT_TRUE(scanner.scanFloat(value));
+    EXPECT_EQ(value, 0.0f);
+    EXPECT_TRUE(scanner.scan(' '));
+
+    // "." (invalid)
+    EXPECT_FALSE(scanner.scanFloat(value));
+    EXPECT_TRUE(scanner.match('.'));
+    EXPECT_TRUE(scanner.scan('.'));
+    EXPECT_TRUE(scanner.scan(' '));
+
+    // "1.0000"
+    EXPECT_TRUE(scanner.scanFloat(value));
+    EXPECT_EQ(value, 1.0f);
+    EXPECT_TRUE(scanner.scan(' '));
+
+    // "01.000"
+    EXPECT_TRUE(scanner.scanFloat(value));
+    EXPECT_EQ(value, 1.0f);
+
+    EXPECT_TRUE(scanner.isAtEnd());
+}
+
+// Tests scanFloat().
+TEST(VTTScanner, ScanFloat)
+{
+    TEST_WITH(scanFloatValue, "1. 1.0 .0 . 1.0000 01.000");
+}
+
+#undef TEST_WITH
+
+} // namespace
diff --git a/Source/core/inspector/AsyncCallStackTracker.cpp b/Source/core/inspector/AsyncCallStackTracker.cpp
index 1337385..a8761a9 100644
--- a/Source/core/inspector/AsyncCallStackTracker.cpp
+++ b/Source/core/inspector/AsyncCallStackTracker.cpp
@@ -31,14 +31,37 @@
 #include "config.h"
 #include "core/inspector/AsyncCallStackTracker.h"
 
+#include "bindings/v8/V8RecursionScope.h"
 #include "core/dom/ContextLifecycleObserver.h"
 #include "core/dom/ExecutionContext.h"
+#include "core/events/EventTarget.h"
+#include "core/events/RegisteredEventListener.h"
+#include "core/xml/XMLHttpRequest.h"
+#include "core/xml/XMLHttpRequestUpload.h"
+#include "wtf/text/AtomicStringHash.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace {
+
+static const char setTimeoutName[] = "setTimeout";
+static const char setIntervalName[] = "setInterval";
+static const char requestAnimationFrameName[] = "requestAnimationFrame";
+static const char xhrSendName[] = "XMLHttpRequest.send";
+static const char enqueueMutationRecordName[] = "Mutation";
+static const char promiseResolved[] = "Promise.resolve";
+static const char promiseRejected[] = "Promise.reject";
+
+}
 
 namespace WebCore {
 
-class AsyncCallStackTracker::ExecutionContextData : public ContextLifecycleObserver {
+class AsyncCallStackTracker::ExecutionContextData FINAL : public ContextLifecycleObserver {
     WTF_MAKE_FAST_ALLOCATED;
 public:
+    typedef std::pair<RegisteredEventListener, RefPtr<AsyncCallChain> > EventListenerAsyncCallChain;
+    typedef Vector<EventListenerAsyncCallChain, 1> EventListenerAsyncCallChainVector;
+    typedef HashMap<AtomicString, EventListenerAsyncCallChainVector> EventListenerAsyncCallChainVectorHashMap;
+
     ExecutionContextData(AsyncCallStackTracker* tracker, ExecutionContext* executionContext)
         : ContextLifecycleObserver(executionContext)
         , m_tracker(tracker)
@@ -47,18 +70,82 @@
 
     virtual void contextDestroyed() OVERRIDE
     {
+        ASSERT(executionContext());
+        ExecutionContextData* self = m_tracker->m_executionContextDataMap.take(executionContext());
+        ASSERT(self == this);
         ContextLifecycleObserver::contextDestroyed();
-        m_tracker->contextDestroyed(executionContext());
+        delete self;
     }
 
-private:
-    friend class AsyncCallStackTracker;
+    void addEventListenerData(EventTarget* eventTarget, const AtomicString& eventType, const EventListenerAsyncCallChain& item)
+    {
+        HashMap<EventTarget*, EventListenerAsyncCallChainVectorHashMap>::iterator it = m_eventTargetCallChains.find(eventTarget);
+        EventListenerAsyncCallChainVectorHashMap* mapPtr;
+        if (it == m_eventTargetCallChains.end())
+            mapPtr = &m_eventTargetCallChains.set(eventTarget, EventListenerAsyncCallChainVectorHashMap()).storedValue->value;
+        else
+            mapPtr = &it->value;
+        EventListenerAsyncCallChainVectorHashMap& map = *mapPtr;
+        EventListenerAsyncCallChainVectorHashMap::iterator it2 = map.find(eventType);
+        if (it2 == map.end())
+            map.set(eventType, EventListenerAsyncCallChainVector()).storedValue->value.append(item);
+        else
+            it2->value.append(item);
+    }
+
+    void removeEventListenerData(EventTarget* eventTarget, const AtomicString& eventType, const RegisteredEventListener& item)
+    {
+        findEventListenerData(eventTarget, eventType, item, true);
+    }
+
+    PassRefPtr<AsyncCallChain> findEventListenerData(EventTarget* eventTarget, const AtomicString& eventType, const RegisteredEventListener& item, bool remove = false)
+    {
+        HashMap<EventTarget*, EventListenerAsyncCallChainVectorHashMap>::iterator it = m_eventTargetCallChains.find(eventTarget);
+        if (it == m_eventTargetCallChains.end())
+            return 0;
+        EventListenerAsyncCallChainVectorHashMap& map = it->value;
+        EventListenerAsyncCallChainVectorHashMap::iterator it2 = map.find(eventType);
+        if (it2 == map.end())
+            return 0;
+        RefPtr<AsyncCallChain> result;
+        EventListenerAsyncCallChainVector& vector = it2->value;
+        for (size_t i = 0; i < vector.size(); ++i) {
+            if (vector[i].first == item) {
+                result = vector[i].second;
+                if (remove) {
+                    vector.remove(i);
+                    if (vector.isEmpty())
+                        map.remove(it2);
+                    if (map.isEmpty())
+                        m_eventTargetCallChains.remove(it);
+                }
+                break;
+            }
+        }
+        return result.release();
+    }
+
+public:
     AsyncCallStackTracker* m_tracker;
     HashSet<int> m_intervalTimerIds;
     HashMap<int, RefPtr<AsyncCallChain> > m_timerCallChains;
     HashMap<int, RefPtr<AsyncCallChain> > m_animationFrameCallChains;
+    HashMap<EventTarget*, EventListenerAsyncCallChainVectorHashMap> m_eventTargetCallChains;
+    HashMap<EventTarget*, RefPtr<AsyncCallChain> > m_xhrCallChains;
+    HashMap<MutationObserver*, RefPtr<AsyncCallChain> > m_mutationObserverCallChains;
+    HashMap<ExecutionContextTask*, RefPtr<AsyncCallChain> > m_promiseTaskCallChains;
 };
 
+static XMLHttpRequest* toXmlHttpRequest(EventTarget* eventTarget)
+{
+    const AtomicString& interfaceName = eventTarget->interfaceName();
+    if (interfaceName == EventTargetNames::XMLHttpRequest)
+        return static_cast<XMLHttpRequest*>(eventTarget);
+    if (interfaceName == EventTargetNames::XMLHttpRequestUpload)
+        return static_cast<XMLHttpRequestUpload*>(eventTarget)->xmlHttpRequest();
+    return 0;
+}
+
 AsyncCallStackTracker::AsyncCallStack::AsyncCallStack(const String& description, const ScriptValue& callFrames)
     : m_description(description)
     , m_callFrames(callFrames)
@@ -93,9 +180,7 @@
 
 void AsyncCallStackTracker::didInstallTimer(ExecutionContext* context, int timerId, bool singleShot, const ScriptValue& callFrames)
 {
-    DEFINE_STATIC_LOCAL(String, setTimeoutName, ("setTimeout"));
-    DEFINE_STATIC_LOCAL(String, setIntervalName, ("setInterval"));
-
+    ASSERT(context);
     ASSERT(isEnabled());
     if (!validateCallFrames(callFrames))
         return;
@@ -108,7 +193,9 @@
 
 void AsyncCallStackTracker::didRemoveTimer(ExecutionContext* context, int timerId)
 {
-    if (!isEnabled() || timerId <= 0)
+    ASSERT(context);
+    ASSERT(isEnabled());
+    if (timerId <= 0)
         return;
     ExecutionContextData* data = m_executionContextDataMap.get(context);
     if (!data)
@@ -119,23 +206,23 @@
 
 void AsyncCallStackTracker::willFireTimer(ExecutionContext* context, int timerId)
 {
-    if (!isEnabled())
-        return;
+    ASSERT(context);
+    ASSERT(isEnabled());
     ASSERT(timerId > 0);
     ASSERT(!m_currentAsyncCallChain);
-    ExecutionContextData* data = m_executionContextDataMap.get(context);
-    if (!data)
-        return;
-    if (data->m_intervalTimerIds.contains(timerId))
-        m_currentAsyncCallChain = data->m_timerCallChains.get(timerId);
-    else
-        m_currentAsyncCallChain = data->m_timerCallChains.take(timerId);
+    if (ExecutionContextData* data = m_executionContextDataMap.get(context)) {
+        if (data->m_intervalTimerIds.contains(timerId))
+            setCurrentAsyncCallChain(data->m_timerCallChains.get(timerId));
+        else
+            setCurrentAsyncCallChain(data->m_timerCallChains.take(timerId));
+    } else {
+        setCurrentAsyncCallChain(0);
+    }
 }
 
 void AsyncCallStackTracker::didRequestAnimationFrame(ExecutionContext* context, int callbackId, const ScriptValue& callFrames)
 {
-    DEFINE_STATIC_LOCAL(String, requestAnimationFrameName, ("requestAnimationFrame"));
-
+    ASSERT(context);
     ASSERT(isEnabled());
     if (!validateCallFrames(callFrames))
         return;
@@ -146,40 +233,200 @@
 
 void AsyncCallStackTracker::didCancelAnimationFrame(ExecutionContext* context, int callbackId)
 {
-    if (!isEnabled() || callbackId <= 0)
+    ASSERT(context);
+    ASSERT(isEnabled());
+    if (callbackId <= 0)
         return;
-    ExecutionContextData* data = m_executionContextDataMap.get(context);
-    if (!data)
-        return;
-    data->m_animationFrameCallChains.remove(callbackId);
+    if (ExecutionContextData* data = m_executionContextDataMap.get(context))
+        data->m_animationFrameCallChains.remove(callbackId);
 }
 
 void AsyncCallStackTracker::willFireAnimationFrame(ExecutionContext* context, int callbackId)
 {
-    if (!isEnabled())
-        return;
+    ASSERT(context);
+    ASSERT(isEnabled());
     ASSERT(callbackId > 0);
     ASSERT(!m_currentAsyncCallChain);
-    ExecutionContextData* data = m_executionContextDataMap.get(context);
-    if (!data)
+    if (ExecutionContextData* data = m_executionContextDataMap.get(context))
+        setCurrentAsyncCallChain(data->m_animationFrameCallChains.take(callbackId));
+    else
+        setCurrentAsyncCallChain(0);
+}
+
+void AsyncCallStackTracker::didAddEventListener(EventTarget* eventTarget, const AtomicString& eventType, EventListener* listener, bool useCapture, const ScriptValue& callFrames)
+{
+    ASSERT(eventTarget->executionContext());
+    ASSERT(isEnabled());
+    if (!validateCallFrames(callFrames) || toXmlHttpRequest(eventTarget))
         return;
-    m_currentAsyncCallChain = data->m_animationFrameCallChains.take(callbackId);
+
+    StringBuilder description;
+    description.append(eventTarget->interfaceName());
+    if (!description.isEmpty())
+        description.append(".");
+    if (listener->isAttribute()) {
+        description.append("on");
+        description.append(eventType);
+    } else {
+        description.append("addEventListener(\"");
+        description.append(eventType);
+        description.append("\")");
+    }
+
+    ExecutionContextData* data = createContextDataIfNeeded(eventTarget->executionContext());
+    data->addEventListenerData(eventTarget, eventType, std::make_pair(RegisteredEventListener(listener, useCapture), createAsyncCallChain(description.toString(), callFrames)));
+}
+
+void AsyncCallStackTracker::didRemoveEventListener(EventTarget* eventTarget, const AtomicString& eventType, EventListener* listener, bool useCapture)
+{
+    ASSERT(eventTarget->executionContext());
+    ASSERT(isEnabled());
+    if (ExecutionContextData* data = m_executionContextDataMap.get(eventTarget->executionContext()))
+        data->removeEventListenerData(eventTarget, eventType, RegisteredEventListener(listener, useCapture));
+}
+
+void AsyncCallStackTracker::didRemoveAllEventListeners(EventTarget* eventTarget)
+{
+    ASSERT(eventTarget->executionContext());
+    ASSERT(isEnabled());
+    if (ExecutionContextData* data = m_executionContextDataMap.get(eventTarget->executionContext()))
+        data->m_eventTargetCallChains.remove(eventTarget);
+}
+
+void AsyncCallStackTracker::willHandleEvent(EventTarget* eventTarget, const AtomicString& eventType, EventListener* listener, bool useCapture)
+{
+    ASSERT(eventTarget->executionContext());
+    ASSERT(isEnabled());
+    if (XMLHttpRequest* xhr = toXmlHttpRequest(eventTarget)) {
+        willHandleXHREvent(xhr, eventTarget, eventType);
+        return;
+    }
+    if (ExecutionContextData* data = m_executionContextDataMap.get(eventTarget->executionContext()))
+        setCurrentAsyncCallChain(data->findEventListenerData(eventTarget, eventType, RegisteredEventListener(listener, useCapture)));
+    else
+        setCurrentAsyncCallChain(0);
+}
+
+void AsyncCallStackTracker::willLoadXHR(XMLHttpRequest* xhr, const ScriptValue& callFrames)
+{
+    ASSERT(xhr->executionContext());
+    ASSERT(isEnabled());
+    if (!validateCallFrames(callFrames))
+        return;
+    ExecutionContextData* data = createContextDataIfNeeded(xhr->executionContext());
+    data->m_xhrCallChains.set(xhr, createAsyncCallChain(xhrSendName, callFrames));
+}
+
+void AsyncCallStackTracker::willHandleXHREvent(XMLHttpRequest* xhr, EventTarget* eventTarget, const AtomicString& eventType)
+{
+    ASSERT(xhr->executionContext());
+    ASSERT(isEnabled());
+    if (ExecutionContextData* data = m_executionContextDataMap.get(xhr->executionContext())) {
+        bool isXHRDownload = (xhr == eventTarget);
+        if (isXHRDownload && eventType == EventTypeNames::loadend)
+            setCurrentAsyncCallChain(data->m_xhrCallChains.take(xhr));
+        else
+            setCurrentAsyncCallChain(data->m_xhrCallChains.get(xhr));
+    } else {
+        setCurrentAsyncCallChain(0);
+    }
+}
+
+void AsyncCallStackTracker::didEnqueueMutationRecord(ExecutionContext* context, MutationObserver* observer, const ScriptValue& callFrames)
+{
+    ASSERT(context);
+    ASSERT(isEnabled());
+    if (!validateCallFrames(callFrames))
+        return;
+    ExecutionContextData* data = createContextDataIfNeeded(context);
+    data->m_mutationObserverCallChains.set(observer, createAsyncCallChain(enqueueMutationRecordName, callFrames));
+}
+
+bool AsyncCallStackTracker::hasEnqueuedMutationRecord(ExecutionContext* context, MutationObserver* observer)
+{
+    ASSERT(context);
+    ASSERT(isEnabled());
+    if (ExecutionContextData* data = m_executionContextDataMap.get(context))
+        return data->m_mutationObserverCallChains.contains(observer);
+    return false;
+}
+
+void AsyncCallStackTracker::didClearAllMutationRecords(ExecutionContext* context, MutationObserver* observer)
+{
+    ASSERT(context);
+    ASSERT(isEnabled());
+    if (ExecutionContextData* data = m_executionContextDataMap.get(context))
+        data->m_mutationObserverCallChains.remove(observer);
+}
+
+void AsyncCallStackTracker::willDeliverMutationRecords(ExecutionContext* context, MutationObserver* observer)
+{
+    ASSERT(context);
+    ASSERT(isEnabled());
+    if (ExecutionContextData* data = m_executionContextDataMap.get(context))
+        setCurrentAsyncCallChain(data->m_mutationObserverCallChains.take(observer));
+    else
+        setCurrentAsyncCallChain(0);
+}
+
+void AsyncCallStackTracker::didPostPromiseTask(ExecutionContext* context, ExecutionContextTask* task, bool isResolved, const ScriptValue& callFrames)
+{
+    ASSERT(context);
+    ASSERT(isEnabled());
+    if (validateCallFrames(callFrames)) {
+        ExecutionContextData* data = createContextDataIfNeeded(context);
+        data->m_promiseTaskCallChains.set(task, createAsyncCallChain(isResolved ? promiseResolved : promiseRejected, callFrames));
+    } else if (m_currentAsyncCallChain) {
+        // Propagate async call stack to the re-posted task to update a derived Promise.
+        ExecutionContextData* data = createContextDataIfNeeded(context);
+        data->m_promiseTaskCallChains.set(task, m_currentAsyncCallChain);
+    }
+}
+
+void AsyncCallStackTracker::willPerformPromiseTask(ExecutionContext* context, ExecutionContextTask* task)
+{
+    ASSERT(context);
+    ASSERT(isEnabled());
+    if (ExecutionContextData* data = m_executionContextDataMap.get(context))
+        setCurrentAsyncCallChain(data->m_promiseTaskCallChains.take(task));
+    else
+        setCurrentAsyncCallChain(0);
 }
 
 void AsyncCallStackTracker::didFireAsyncCall()
 {
-    m_currentAsyncCallChain = 0;
+    clearCurrentAsyncCallChain();
 }
 
 PassRefPtr<AsyncCallStackTracker::AsyncCallChain> AsyncCallStackTracker::createAsyncCallChain(const String& description, const ScriptValue& callFrames)
 {
-    ASSERT(isEnabled());
     RefPtr<AsyncCallChain> chain = adoptRef(m_currentAsyncCallChain ? new AsyncCallStackTracker::AsyncCallChain(*m_currentAsyncCallChain) : new AsyncCallStackTracker::AsyncCallChain());
     ensureMaxAsyncCallChainDepth(chain.get(), m_maxAsyncCallStackDepth - 1);
     chain->m_callStacks.prepend(adoptRef(new AsyncCallStackTracker::AsyncCallStack(description, callFrames)));
     return chain.release();
 }
 
+void AsyncCallStackTracker::setCurrentAsyncCallChain(PassRefPtr<AsyncCallChain> chain)
+{
+    if (V8RecursionScope::recursionLevel()) {
+        if (m_currentAsyncCallChain)
+            ++m_nestedAsyncCallCount;
+    } else {
+        // Current AsyncCallChain corresponds to the bottommost JS call frame.
+        m_currentAsyncCallChain = chain;
+        m_nestedAsyncCallCount = m_currentAsyncCallChain ? 1 : 0;
+    }
+}
+
+void AsyncCallStackTracker::clearCurrentAsyncCallChain()
+{
+    if (!m_nestedAsyncCallCount)
+        return;
+    --m_nestedAsyncCallCount;
+    if (!m_nestedAsyncCallCount)
+        m_currentAsyncCallChain.clear();
+}
+
 void AsyncCallStackTracker::ensureMaxAsyncCallChainDepth(AsyncCallChain* chain, unsigned maxDepth)
 {
     while (chain->m_callStacks.size() > maxDepth)
@@ -188,14 +435,7 @@
 
 bool AsyncCallStackTracker::validateCallFrames(const ScriptValue& callFrames)
 {
-    return !callFrames.hasNoValue() && callFrames.isObject();
-}
-
-void AsyncCallStackTracker::contextDestroyed(ExecutionContext* context)
-{
-    ExecutionContextData* data = m_executionContextDataMap.take(context);
-    if (data)
-        delete data;
+    return !callFrames.hasNoValue();
 }
 
 AsyncCallStackTracker::ExecutionContextData* AsyncCallStackTracker::createContextDataIfNeeded(ExecutionContext* context)
@@ -210,12 +450,12 @@
 
 void AsyncCallStackTracker::clear()
 {
-    m_currentAsyncCallChain = 0;
-    Vector<ExecutionContextData*> contextsData;
-    copyValuesToVector(m_executionContextDataMap, contextsData);
-    m_executionContextDataMap.clear();
-    for (Vector<ExecutionContextData*>::const_iterator it = contextsData.begin(); it != contextsData.end(); ++it)
-        delete *it;
+    m_currentAsyncCallChain.clear();
+    m_nestedAsyncCallCount = 0;
+    ExecutionContextDataMap copy;
+    m_executionContextDataMap.swap(copy);
+    for (ExecutionContextDataMap::const_iterator it = copy.begin(); it != copy.end(); ++it)
+        delete it->value;
 }
 
 } // namespace WebCore
diff --git a/Source/core/inspector/AsyncCallStackTracker.h b/Source/core/inspector/AsyncCallStackTracker.h
index e032134..2ccb4fb 100644
--- a/Source/core/inspector/AsyncCallStackTracker.h
+++ b/Source/core/inspector/AsyncCallStackTracker.h
@@ -41,7 +41,12 @@
 
 namespace WebCore {
 
+class EventListener;
+class EventTarget;
 class ExecutionContext;
+class ExecutionContextTask;
+class MutationObserver;
+class XMLHttpRequest;
 
 class AsyncCallStackTracker {
     WTF_MAKE_NONCOPYABLE(AsyncCallStackTracker);
@@ -83,21 +88,41 @@
     void didCancelAnimationFrame(ExecutionContext*, int callbackId);
     void willFireAnimationFrame(ExecutionContext*, int callbackId);
 
+    void didAddEventListener(EventTarget*, const AtomicString& eventType, EventListener*, bool useCapture, const ScriptValue& callFrames);
+    void didRemoveEventListener(EventTarget*, const AtomicString& eventType, EventListener*, bool useCapture);
+    void didRemoveAllEventListeners(EventTarget*);
+    void willHandleEvent(EventTarget*, const AtomicString& eventType, EventListener*, bool useCapture);
+
+    void willLoadXHR(XMLHttpRequest*, const ScriptValue& callFrames);
+
+    void didEnqueueMutationRecord(ExecutionContext*, MutationObserver*, const ScriptValue& callFrames);
+    bool hasEnqueuedMutationRecord(ExecutionContext*, MutationObserver*);
+    void didClearAllMutationRecords(ExecutionContext*, MutationObserver*);
+    void willDeliverMutationRecords(ExecutionContext*, MutationObserver*);
+
+    void didPostPromiseTask(ExecutionContext*, ExecutionContextTask*, bool isResolved, const ScriptValue& callFrames);
+    void willPerformPromiseTask(ExecutionContext*, ExecutionContextTask*);
+
     void didFireAsyncCall();
     void clear();
 
 private:
+    void willHandleXHREvent(XMLHttpRequest*, EventTarget*, const AtomicString& eventType);
+
     PassRefPtr<AsyncCallChain> createAsyncCallChain(const String& description, const ScriptValue& callFrames);
+    void setCurrentAsyncCallChain(PassRefPtr<AsyncCallChain>);
+    void clearCurrentAsyncCallChain();
     static void ensureMaxAsyncCallChainDepth(AsyncCallChain*, unsigned);
     static bool validateCallFrames(const ScriptValue& callFrames);
 
     class ExecutionContextData;
-    void contextDestroyed(ExecutionContext*);
     ExecutionContextData* createContextDataIfNeeded(ExecutionContext*);
 
     unsigned m_maxAsyncCallStackDepth;
     RefPtr<AsyncCallChain> m_currentAsyncCallChain;
-    HashMap<ExecutionContext*, ExecutionContextData*> m_executionContextDataMap;
+    unsigned m_nestedAsyncCallCount;
+    typedef HashMap<ExecutionContext*, ExecutionContextData*> ExecutionContextDataMap;
+    ExecutionContextDataMap m_executionContextDataMap;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/BindingVisitors.h b/Source/core/inspector/BindingVisitors.h
index c885703..9a51b0f 100644
--- a/Source/core/inspector/BindingVisitors.h
+++ b/Source/core/inspector/BindingVisitors.h
@@ -52,14 +52,6 @@
     virtual ~ExternalStringVisitor() { }
 };
 
-
-class ExternalArrayVisitor {
-public:
-    virtual void visitJSExternalArray(WTF::ArrayBufferView*) = 0;
-protected:
-    virtual ~ExternalArrayVisitor() { }
-};
-
 } // namespace WebCore
 
 #endif // BindingVisitors_h
diff --git a/Source/core/inspector/CodeGeneratorInspector.py b/Source/core/inspector/CodeGeneratorInspector.py
index 163ce99..342b5a2 100755
--- a/Source/core/inspector/CodeGeneratorInspector.py
+++ b/Source/core/inspector/CodeGeneratorInspector.py
@@ -49,11 +49,9 @@
 
 TYPES_WITH_RUNTIME_CAST_SET = frozenset(["Runtime.RemoteObject", "Runtime.PropertyDescriptor", "Runtime.InternalPropertyDescriptor",
                                          "Debugger.FunctionDetails", "Debugger.CallFrame", "Debugger.Location",
-                                         "Canvas.TraceLog", "Canvas.ResourceState",
-                                         # This should be a temporary hack. TimelineEvent should be created via generated C++ API.
-                                         "Timeline.TimelineEvent"])
+                                         "Canvas.TraceLog", "Canvas.ResourceState"])
 
-TYPES_WITH_OPEN_FIELD_LIST_SET = frozenset(["Timeline.TimelineEvent",
+TYPES_WITH_OPEN_FIELD_LIST_SET = frozenset([
                                             # InspectorStyleSheet not only creates this property but wants to read it and modify it.
                                             "CSS.CSSProperty",
                                             # InspectorResourceAgent needs to update mime-type.
@@ -1889,11 +1887,13 @@
         Generator.method_handler_list.append("            &InspectorBackendDispatcherImpl::%s_%s," % (domain_name, json_command_name))
         Generator.backend_method_declaration_list.append("    void %s_%s(long callId, JSONObject* requestMessageObject);" % (domain_name, json_command_name))
 
+        backend_agent_interface_list = [] if "redirect" in json_command else Generator.backend_agent_interface_list
+
         ad_hoc_type_output = []
-        Generator.backend_agent_interface_list.append(ad_hoc_type_output)
+        backend_agent_interface_list.append(ad_hoc_type_output)
         ad_hoc_type_writer = Writer(ad_hoc_type_output, "        ")
 
-        Generator.backend_agent_interface_list.append("        virtual void %s(ErrorString*" % json_command_name)
+        backend_agent_interface_list.append("        virtual void %s(ErrorString*" % json_command_name)
 
         method_in_code = ""
         method_out_code = ""
@@ -1908,7 +1908,7 @@
             error_type_model = error_type_binding.get_type_model().get_optional()
             error_annotated_type = error_type_model.get_command_return_pass_model().get_output_parameter_type()
             agent_call_param_list.append(", %serrorData" % error_type_model.get_command_return_pass_model().get_output_argument_prefix())
-            Generator.backend_agent_interface_list.append(", %s errorData" % error_annotated_type)
+            backend_agent_interface_list.append(", %s errorData" % error_annotated_type)
             method_in_code += "    %s errorData;\n" % error_type_model.get_command_return_pass_model().get_return_var_type()
 
             setter_argument = error_type_model.get_command_return_pass_model().get_output_to_raw_expression() % "errorData"
@@ -1962,7 +1962,7 @@
 
                 method_in_code += code
                 agent_call_param_list.append(param)
-                Generator.backend_agent_interface_list.append(", %s in_%s" % (formal_param_type_pattern % non_optional_type_model.get_command_return_pass_model().get_return_var_type(), json_param_name))
+                backend_agent_interface_list.append(", %s in_%s" % (formal_param_type_pattern % non_optional_type_model.get_command_return_pass_model().get_return_var_type(), json_param_name))
 
         if json_command.get("async") == True:
             callback_name = Capitalizer.lower_camel_case_to_upper(json_command_name) + "Callback"
@@ -2007,7 +2007,7 @@
             normal_response_cook_text += "        if (!error.length()) \n"
             normal_response_cook_text += "            return;\n"
             normal_response_cook_text += "        callback->disable();\n"
-            Generator.backend_agent_interface_list.append(", PassRefPtr<%s> callback" % callback_name)
+            backend_agent_interface_list.append(", PassRefPtr<%s> callback" % callback_name)
         else:
             if "returns" in json_command:
                 method_out_code += "\n"
@@ -2047,7 +2047,7 @@
                     if optional:
                         param_name = "opt_" + param_name
 
-                    Generator.backend_agent_interface_list.append(", %s %s" % (annotated_type, param_name))
+                    backend_agent_interface_list.append(", %s %s" % (annotated_type, param_name))
                     response_cook_list.append(cook)
 
                     method_out_code += code
@@ -2058,9 +2058,15 @@
                 if len(normal_response_cook_text) != 0:
                     normal_response_cook_text = "        if (!error.length()) {\n" + normal_response_cook_text + "        }"
 
+        # Redirect to another agent's implementation.
+        agent_field = "m_" + agent_field_name
+        if "redirect" in json_command:
+            domain_fixes = DomainNameFixes.get_fixed_data(json_command.get("redirect"))
+            agent_field = "m_" + domain_fixes.agent_field_name
+
         Generator.backend_method_implementation_list.append(Templates.backend_method.substitute(None,
             domainName=domain_name, methodName=json_command_name,
-            agentField="m_" + agent_field_name,
+            agentField=agent_field,
             methodInCode=method_in_code,
             methodOutCode=method_out_code,
             agentCallParams="".join(agent_call_param_list),
@@ -2073,7 +2079,7 @@
         Generator.backend_method_name_declaration_index_list.append("    %d," % Generator.backend_method_name_declaration_current_index)
         Generator.backend_method_name_declaration_current_index += len(declaration_command_name) - 1
 
-        Generator.backend_agent_interface_list.append(") = 0;\n")
+        backend_agent_interface_list.append(") = 0;\n")
 
     class CallbackMethodStructTemplate:
         @staticmethod
diff --git a/Source/core/inspector/CodeGeneratorInspectorStrings.py b/Source/core/inspector/CodeGeneratorInspectorStrings.py
index bc3bb73..94416e7 100644
--- a/Source/core/inspector/CodeGeneratorInspectorStrings.py
+++ b/Source/core/inspector/CodeGeneratorInspectorStrings.py
@@ -136,7 +136,6 @@
 
 namespace WebCore {
 
-class InspectorAgent;
 class JSONObject;
 class JSONArray;
 class InspectorFrontendChannel;
@@ -215,7 +214,6 @@
 #include "config.h"
 #include "InspectorBackendDispatcher.h"
 
-#include "core/inspector/InspectorAgent.h"
 #include "core/inspector/InspectorFrontendChannel.h"
 #include "core/inspector/JSONParser.h"
 #include "platform/JSONValues.h"
@@ -290,7 +288,7 @@
     long callId = 0;
 
     if (dispatchMap.isEmpty()) {
-        static CallHandler handlers[] = {
+        static const CallHandler handlers[] = {
 $messageHandlers
         };
         for (size_t i = 0; i < kMethodNamesEnumSize; ++i)
diff --git a/Source/core/inspector/CodeGeneratorInstrumentation.py b/Source/core/inspector/CodeGeneratorInstrumentation.py
index ce639eb..aa84d84 100644
--- a/Source/core/inspector/CodeGeneratorInstrumentation.py
+++ b/Source/core/inspector/CodeGeneratorInstrumentation.py
@@ -405,7 +405,7 @@
 
 
 def agent_class_name(agent):
-    custom_agent_names = ["Inspector", "PageDebugger", "PageRuntime", "WorkerRuntime"]
+    custom_agent_names = ["PageDebugger", "PageRuntime", "WorkerRuntime"]
     if agent in custom_agent_names:
         return "%sAgent" % agent
     return "Inspector%sAgent" % agent
diff --git a/Source/core/inspector/ConsoleAPITypes.h b/Source/core/inspector/ConsoleAPITypes.h
index b36cdfe..01a9fe9 100644
--- a/Source/core/inspector/ConsoleAPITypes.h
+++ b/Source/core/inspector/ConsoleAPITypes.h
@@ -37,9 +37,7 @@
     StartGroupCollapsedMessageType,
     EndGroupMessageType,
     ClearMessageType,
-    AssertMessageType,
-    ProfileMessageType,
-    ProfileEndMessageType
+    AssertMessageType
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/ConsoleMessage.cpp b/Source/core/inspector/ConsoleMessage.cpp
index b54e46b..4e1dabc 100644
--- a/Source/core/inspector/ConsoleMessage.cpp
+++ b/Source/core/inspector/ConsoleMessage.cpp
@@ -170,8 +170,6 @@
     case StartGroupCollapsedMessageType: return TypeBuilder::Console::ConsoleMessage::Type::StartGroupCollapsed;
     case EndGroupMessageType: return TypeBuilder::Console::ConsoleMessage::Type::EndGroup;
     case AssertMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Assert;
-    case ProfileMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Profile;
-    case ProfileEndMessageType: return TypeBuilder::Console::ConsoleMessage::Type::ProfileEnd;
     }
     return TypeBuilder::Console::ConsoleMessage::Type::Log;
 }
diff --git a/Source/core/inspector/ConsoleMessage.h b/Source/core/inspector/ConsoleMessage.h
index f487f74..430fe13 100644
--- a/Source/core/inspector/ConsoleMessage.h
+++ b/Source/core/inspector/ConsoleMessage.h
@@ -62,8 +62,6 @@
     void setTimestamp(double timestamp) { m_timestamp = timestamp; }
     bool isEqual(ConsoleMessage* msg) const;
 
-    MessageSource source() const { return m_source; }
-    const String& message() const { return m_message; }
     MessageType type() const { return m_type; }
 
     void windowCleared(DOMWindow*);
diff --git a/Source/core/inspector/DOMEditor.cpp b/Source/core/inspector/DOMEditor.cpp
index cd3a1f5..1f8956b 100644
--- a/Source/core/inspector/DOMEditor.cpp
+++ b/Source/core/inspector/DOMEditor.cpp
@@ -46,7 +46,7 @@
 
 namespace WebCore {
 
-class DOMEditor::RemoveChildAction : public InspectorHistory::Action {
+class DOMEditor::RemoveChildAction FINAL : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(RemoveChildAction);
 public:
     RemoveChildAction(Node* parentNode, Node* node)
@@ -56,19 +56,19 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         m_anchorNode = m_node->nextSibling();
         return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), exceptionState);
         return !exceptionState.hadException();
     }
 
-    virtual bool redo(ExceptionState& exceptionState)
+    virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
         m_parentNode->removeChild(m_node.get(), exceptionState);
         return !exceptionState.hadException();
@@ -80,7 +80,7 @@
     RefPtr<Node> m_anchorNode;
 };
 
-class DOMEditor::InsertBeforeAction : public InspectorHistory::Action {
+class DOMEditor::InsertBeforeAction FINAL : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(InsertBeforeAction);
 public:
     InsertBeforeAction(Node* parentNode, PassRefPtr<Node> node, Node* anchorNode)
@@ -91,7 +91,7 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         if (m_node->parentNode()) {
             m_removeChildAction = adoptPtr(new RemoveChildAction(m_node->parentNode(), m_node.get()));
@@ -102,7 +102,7 @@
         return !exceptionState.hadException();
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         m_parentNode->removeChild(m_node.get(), exceptionState);
         if (exceptionState.hadException())
@@ -112,7 +112,7 @@
         return true;
     }
 
-    virtual bool redo(ExceptionState& exceptionState)
+    virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
         if (m_removeChildAction && !m_removeChildAction->redo(exceptionState))
             return false;
@@ -127,7 +127,7 @@
     OwnPtr<RemoveChildAction> m_removeChildAction;
 };
 
-class DOMEditor::RemoveAttributeAction : public InspectorHistory::Action {
+class DOMEditor::RemoveAttributeAction FINAL : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(RemoveAttributeAction);
 public:
     RemoveAttributeAction(Element* element, const AtomicString& name)
@@ -137,19 +137,19 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         m_value = m_element->getAttribute(m_name);
         return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         m_element->setAttribute(m_name, m_value, exceptionState);
         return true;
     }
 
-    virtual bool redo(ExceptionState&)
+    virtual bool redo(ExceptionState&) OVERRIDE
     {
         m_element->removeAttribute(m_name);
         return true;
@@ -161,7 +161,7 @@
     AtomicString m_value;
 };
 
-class DOMEditor::SetAttributeAction : public InspectorHistory::Action {
+class DOMEditor::SetAttributeAction FINAL : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(SetAttributeAction);
 public:
     SetAttributeAction(Element* element, const AtomicString& name, const AtomicString& value)
@@ -173,7 +173,7 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         m_hadAttribute = m_element->hasAttribute(m_name);
         if (m_hadAttribute)
@@ -181,7 +181,7 @@
         return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         if (m_hadAttribute)
             m_element->setAttribute(m_name, m_oldValue, exceptionState);
@@ -190,7 +190,7 @@
         return true;
     }
 
-    virtual bool redo(ExceptionState& exceptionState)
+    virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
         m_element->setAttribute(m_name, m_value, exceptionState);
         return true;
@@ -204,7 +204,7 @@
     AtomicString m_oldValue;
 };
 
-class DOMEditor::SetOuterHTMLAction : public InspectorHistory::Action {
+class DOMEditor::SetOuterHTMLAction FINAL : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(SetOuterHTMLAction);
 public:
     SetOuterHTMLAction(Node* node, const String& html)
@@ -218,7 +218,7 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         m_oldHTML = createMarkup(m_node.get());
         ASSERT(m_node->ownerDocument());
@@ -227,12 +227,12 @@
         return !exceptionState.hadException();
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         return m_history->undo(exceptionState);
     }
 
-    virtual bool redo(ExceptionState& exceptionState)
+    virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
         return m_history->redo(exceptionState);
     }
@@ -252,7 +252,7 @@
     OwnPtr<DOMEditor> m_domEditor;
 };
 
-class DOMEditor::ReplaceWholeTextAction : public InspectorHistory::Action {
+class DOMEditor::ReplaceWholeTextAction FINAL : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(ReplaceWholeTextAction);
 public:
     ReplaceWholeTextAction(Text* textNode, const String& text)
@@ -262,19 +262,19 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         m_oldText = m_textNode->wholeText();
         return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState&)
+    virtual bool undo(ExceptionState&) OVERRIDE
     {
         m_textNode->replaceWholeText(m_oldText);
         return true;
     }
 
-    virtual bool redo(ExceptionState&)
+    virtual bool redo(ExceptionState&) OVERRIDE
     {
         m_textNode->replaceWholeText(m_text);
         return true;
@@ -286,7 +286,7 @@
     String m_oldText;
 };
 
-class DOMEditor::ReplaceChildNodeAction : public InspectorHistory::Action {
+class DOMEditor::ReplaceChildNodeAction FINAL : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(ReplaceChildNodeAction);
 public:
     ReplaceChildNodeAction(Node* parentNode, PassRefPtr<Node> newNode, Node* oldNode)
@@ -297,18 +297,18 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         m_parentNode->replaceChild(m_oldNode, m_newNode.get(), exceptionState);
         return !exceptionState.hadException();
     }
 
-    virtual bool redo(ExceptionState& exceptionState)
+    virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
         m_parentNode->replaceChild(m_newNode, m_oldNode.get(), exceptionState);
         return !exceptionState.hadException();
@@ -320,7 +320,7 @@
     RefPtr<Node> m_oldNode;
 };
 
-class DOMEditor::SetNodeValueAction : public InspectorHistory::Action {
+class DOMEditor::SetNodeValueAction FINAL : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(SetNodeValueAction);
 public:
     SetNodeValueAction(Node* node, const String& value)
@@ -330,19 +330,19 @@
     {
     }
 
-    virtual bool perform(ExceptionState&)
+    virtual bool perform(ExceptionState&) OVERRIDE
     {
         m_oldValue = m_node->nodeValue();
         return redo(IGNORE_EXCEPTION);
     }
 
-    virtual bool undo(ExceptionState&)
+    virtual bool undo(ExceptionState&) OVERRIDE
     {
         m_node->setNodeValue(m_oldValue);
         return true;
     }
 
-    virtual bool redo(ExceptionState&)
+    virtual bool redo(ExceptionState&) OVERRIDE
     {
         m_node->setNodeValue(m_value);
         return true;
@@ -370,12 +370,12 @@
 
 bool DOMEditor::setAttribute(Element* element, const String& name, const String& value, ExceptionState& exceptionState)
 {
-    return m_history->perform(adoptPtr(new SetAttributeAction(element, name, value)), exceptionState);
+    return m_history->perform(adoptPtr(new SetAttributeAction(element, AtomicString(name), AtomicString(value))), exceptionState);
 }
 
 bool DOMEditor::removeAttribute(Element* element, const String& name, ExceptionState& exceptionState)
 {
-    return m_history->perform(adoptPtr(new RemoveAttributeAction(element, name)), exceptionState);
+    return m_history->perform(adoptPtr(new RemoveAttributeAction(element, AtomicString(name))), exceptionState);
 }
 
 bool DOMEditor::setOuterHTML(Node* node, const String& html, Node** newNode, ExceptionState& exceptionState)
diff --git a/Source/core/inspector/DOMPatchSupport.cpp b/Source/core/inspector/DOMPatchSupport.cpp
index d5c7cd5..67c9718 100644
--- a/Source/core/inspector/DOMPatchSupport.cpp
+++ b/Source/core/inspector/DOMPatchSupport.cpp
@@ -39,6 +39,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/Node.h"
+#include "core/dom/XMLDocument.h"
 #include "core/html/HTMLDocument.h"
 #include "core/html/parser/HTMLDocumentParser.h"
 #include "core/inspector/DOMEditor.h"
@@ -88,9 +89,9 @@
     if (m_document.isHTMLDocument())
         newDocument = HTMLDocument::create();
     else if (m_document.isXHTMLDocument())
-        newDocument = HTMLDocument::createXHTML();
-    else if (m_document.isSVGDocument())
-        newDocument = Document::create();
+        newDocument = XMLDocument::createXHTML();
+    else if (m_document.isXMLDocument())
+        newDocument = XMLDocument::create();
 
     ASSERT(newDocument);
     newDocument->setContextFeatures(m_document.contextFeatures());
@@ -243,13 +244,11 @@
     DiffTable oldTable;
 
     for (size_t i = 0; i < newList.size(); ++i) {
-        DiffTable::iterator it = newTable.add(newList[i]->m_sha1, Vector<size_t>()).iterator;
-        it->value.append(i);
+        newTable.add(newList[i]->m_sha1, Vector<size_t>()).storedValue->value.append(i);
     }
 
     for (size_t i = 0; i < oldList.size(); ++i) {
-        DiffTable::iterator it = oldTable.add(oldList[i]->m_sha1, Vector<size_t>()).iterator;
-        it->value.append(i);
+        oldTable.add(oldList[i]->m_sha1, Vector<size_t>()).storedValue->value.append(i);
     }
 
     for (DiffTable::iterator newIt = newTable.begin(); newIt != newTable.end(); ++newIt) {
diff --git a/Source/core/inspector/InjectedScript.cpp b/Source/core/inspector/InjectedScript.cpp
index 9d46e69..d746427 100644
--- a/Source/core/inspector/InjectedScript.cpp
+++ b/Source/core/inspector/InjectedScript.cpp
@@ -79,10 +79,11 @@
     makeEvalCall(errorString, function, result, wasThrown);
 }
 
-void InjectedScript::evaluateOnCallFrame(ErrorString* errorString, const ScriptValue& callFrames, const String& callFrameId, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, RefPtr<RemoteObject>* result, TypeBuilder::OptOutput<bool>* wasThrown)
+void InjectedScript::evaluateOnCallFrame(ErrorString* errorString, const ScriptValue& callFrames, const Vector<ScriptValue>& asyncCallStacks, const String& callFrameId, const String& expression, const String& objectGroup, bool includeCommandLineAPI, bool returnByValue, bool generatePreview, RefPtr<RemoteObject>* result, TypeBuilder::OptOutput<bool>* wasThrown)
 {
     ScriptFunctionCall function(injectedScriptObject(), "evaluateOnCallFrame");
     function.appendArgument(callFrames);
+    function.appendArgument(asyncCallStacks);
     function.appendArgument(callFrameId);
     function.appendArgument(expression);
     function.appendArgument(objectGroup);
@@ -231,11 +232,12 @@
     makeCall(function, &result);
 }
 
-PassRefPtr<Array<CallFrame> > InjectedScript::wrapCallFrames(const ScriptValue& callFrames)
+PassRefPtr<Array<CallFrame> > InjectedScript::wrapCallFrames(const ScriptValue& callFrames, int asyncOrdinal)
 {
     ASSERT(!hasNoValue());
     ScriptFunctionCall function(injectedScriptObject(), "wrapCallFrames");
     function.appendArgument(callFrames);
+    function.appendArgument(asyncOrdinal);
     bool hadException = false;
     ScriptValue callFramesValue = callFunctionWithEvalEnabled(function, hadException);
     ASSERT(!hadException);
diff --git a/Source/core/inspector/InjectedScript.h b/Source/core/inspector/InjectedScript.h
index 05cfcf3..16ea58f 100644
--- a/Source/core/inspector/InjectedScript.h
+++ b/Source/core/inspector/InjectedScript.h
@@ -37,6 +37,7 @@
 #include "core/inspector/InjectedScriptManager.h"
 #include "core/inspector/ScriptArguments.h"
 #include "wtf/Forward.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -44,38 +45,41 @@
 class Node;
 class SerializedScriptValue;
 
-
-class InjectedScript : public InjectedScriptBase {
+class InjectedScript FINAL : public InjectedScriptBase {
 public:
     InjectedScript();
-    ~InjectedScript() { }
+    virtual ~InjectedScript() { }
 
-    void evaluate(ErrorString*,
-                  const String& expression,
-                  const String& objectGroup,
-                  bool includeCommandLineAPI,
-                  bool returnByValue,
-                  bool generatePreview,
-                  RefPtr<TypeBuilder::Runtime::RemoteObject>* result,
-                  TypeBuilder::OptOutput<bool>* wasThrown);
-    void callFunctionOn(ErrorString*,
-                        const String& objectId,
-                        const String& expression,
-                        const String& arguments,
-                        bool returnByValue,
-                        bool generatePreview,
-                        RefPtr<TypeBuilder::Runtime::RemoteObject>* result,
-                        TypeBuilder::OptOutput<bool>* wasThrown);
-    void evaluateOnCallFrame(ErrorString*,
-                             const ScriptValue& callFrames,
-                             const String& callFrameId,
-                             const String& expression,
-                             const String& objectGroup,
-                             bool includeCommandLineAPI,
-                             bool returnByValue,
-                             bool generatePreview,
-                             RefPtr<TypeBuilder::Runtime::RemoteObject>* result,
-                             TypeBuilder::OptOutput<bool>* wasThrown);
+    void evaluate(
+        ErrorString*,
+        const String& expression,
+        const String& objectGroup,
+        bool includeCommandLineAPI,
+        bool returnByValue,
+        bool generatePreview,
+        RefPtr<TypeBuilder::Runtime::RemoteObject>* result,
+        TypeBuilder::OptOutput<bool>* wasThrown);
+    void callFunctionOn(
+        ErrorString*,
+        const String& objectId,
+        const String& expression,
+        const String& arguments,
+        bool returnByValue,
+        bool generatePreview,
+        RefPtr<TypeBuilder::Runtime::RemoteObject>* result,
+        TypeBuilder::OptOutput<bool>* wasThrown);
+    void evaluateOnCallFrame(
+        ErrorString*,
+        const ScriptValue& callFrames,
+        const Vector<ScriptValue>& asyncCallStacks,
+        const String& callFrameId,
+        const String& expression,
+        const String& objectGroup,
+        bool includeCommandLineAPI,
+        bool returnByValue,
+        bool generatePreview,
+        RefPtr<TypeBuilder::Runtime::RemoteObject>* result,
+        TypeBuilder::OptOutput<bool>* wasThrown);
     void restartFrame(ErrorString*, const ScriptValue& callFrames, const String& callFrameId, RefPtr<JSONObject>* result);
     void getStepInPositions(ErrorString*, const ScriptValue& callFrames, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& positions);
     void setVariableValue(ErrorString*, const ScriptValue& callFrames, const String* callFrameIdOpt, const String* functionObjectIdOpt, int scopeNumber, const String& variableName, const String& newValueStr);
@@ -85,7 +89,7 @@
     Node* nodeForObjectId(const String& objectId);
     void releaseObject(const String& objectId);
 
-    PassRefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> > wrapCallFrames(const ScriptValue&);
+    PassRefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> > wrapCallFrames(const ScriptValue&, int asyncOrdinal);
 
     PassRefPtr<TypeBuilder::Runtime::RemoteObject> wrapObject(const ScriptValue&, const String& groupName, bool generatePreview = false) const;
     PassRefPtr<TypeBuilder::Runtime::RemoteObject> wrapTable(const ScriptValue& table, const ScriptValue& columns) const;
diff --git a/Source/core/inspector/InjectedScriptCanvasModule.h b/Source/core/inspector/InjectedScriptCanvasModule.h
index 9a675eb..fcbcc0c 100644
--- a/Source/core/inspector/InjectedScriptCanvasModule.h
+++ b/Source/core/inspector/InjectedScriptCanvasModule.h
@@ -41,11 +41,11 @@
 class ScriptObject;
 
 
-class InjectedScriptCanvasModule : public InjectedScriptModule {
+class InjectedScriptCanvasModule FINAL : public InjectedScriptModule {
 public:
     InjectedScriptCanvasModule();
 
-    virtual String source() const;
+    virtual String source() const OVERRIDE;
 
     static InjectedScriptCanvasModule moduleForState(InjectedScriptManager*, ScriptState*);
 
diff --git a/Source/core/inspector/InjectedScriptExterns.js b/Source/core/inspector/InjectedScriptExterns.js
index b7d83a2..59c7d56 100644
--- a/Source/core/inspector/InjectedScriptExterns.js
+++ b/Source/core/inspector/InjectedScriptExterns.js
@@ -157,8 +157,6 @@
     this.rawScopes;
 }
 
-var InspectorBackend = { };
-
 // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
 /**
  * @constructor
diff --git a/Source/core/inspector/InjectedScriptHost.cpp b/Source/core/inspector/InjectedScriptHost.cpp
index 8354958..c04a976 100644
--- a/Source/core/inspector/InjectedScriptHost.cpp
+++ b/Source/core/inspector/InjectedScriptHost.cpp
@@ -31,12 +31,10 @@
 #include "config.h"
 #include "core/inspector/InjectedScriptHost.h"
 
-#include "core/inspector/InspectorAgent.h"
 #include "core/inspector/InspectorConsoleAgent.h"
 #include "core/inspector/InspectorDOMAgent.h"
-#include "core/inspector/InspectorDOMStorageAgent.h"
-#include "core/inspector/InspectorDatabaseAgent.h"
 #include "core/inspector/InspectorDebuggerAgent.h"
+#include "core/inspector/InspectorInspectorAgent.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "platform/JSONValues.h"
 
@@ -72,15 +70,15 @@
 
 void InjectedScriptHost::inspectImpl(PassRefPtr<JSONValue> object, PassRefPtr<JSONValue> hints)
 {
-    if (InspectorAgent* inspectorAgent = m_instrumentingAgents ? m_instrumentingAgents->inspectorAgent() : 0) {
+    if (InspectorInspectorAgent* inspectorAgent = m_instrumentingAgents ? m_instrumentingAgents->inspectorInspectorAgent() : 0) {
         RefPtr<TypeBuilder::Runtime::RemoteObject> remoteObject = TypeBuilder::Runtime::RemoteObject::runtimeCast(object);
         inspectorAgent->inspect(remoteObject, hints->asObject());
     }
 }
 
-void InjectedScriptHost::getEventListenersImpl(Node* node, Vector<EventListenerInfo>& listenersArray)
+void InjectedScriptHost::getEventListenersImpl(EventTarget* target, Vector<EventListenerInfo>& listenersArray)
 {
-    InspectorDOMAgent::getEventListeners(node, listenersArray, false);
+    InspectorDOMAgent::getEventListeners(target, listenersArray, false);
 }
 
 void InjectedScriptHost::clearConsoleMessages()
@@ -115,20 +113,6 @@
     return m_inspectedObjects[num].get();
 }
 
-String InjectedScriptHost::databaseIdImpl(Database* database)
-{
-    if (InspectorDatabaseAgent* databaseAgent = m_instrumentingAgents ? m_instrumentingAgents->inspectorDatabaseAgent() : 0)
-        return databaseAgent->databaseId(database);
-    return String();
-}
-
-String InjectedScriptHost::storageIdImpl(Storage* storage)
-{
-    if (InspectorDOMStorageAgent* domStorageAgent = m_instrumentingAgents ? m_instrumentingAgents->inspectorDOMStorageAgent() : 0)
-        return domStorageAgent->storageId(storage);
-    return String();
-}
-
 void InjectedScriptHost::debugFunction(const String& scriptId, int lineNumber, int columnNumber)
 {
     if (InspectorDebuggerAgent* debuggerAgent = m_instrumentingAgents ? m_instrumentingAgents->inspectorDebuggerAgent() : 0)
diff --git a/Source/core/inspector/InjectedScriptHost.h b/Source/core/inspector/InjectedScriptHost.h
index 2a95c7a..046fe3b 100644
--- a/Source/core/inspector/InjectedScriptHost.h
+++ b/Source/core/inspector/InjectedScriptHost.h
@@ -38,6 +38,7 @@
 namespace WebCore {
 
 class Database;
+class EventTarget;
 class InjectedScript;
 class InstrumentingAgents;
 class JSONValue;
@@ -80,11 +81,9 @@
     InspectableObject* inspectedObject(unsigned int num);
 
     void inspectImpl(PassRefPtr<JSONValue> objectToInspect, PassRefPtr<JSONValue> hints);
-    void getEventListenersImpl(Node*, Vector<EventListenerInfo>& listenersArray);
+    void getEventListenersImpl(EventTarget*, Vector<EventListenerInfo>& listenersArray);
 
     void clearConsoleMessages();
-    String databaseIdImpl(Database*);
-    String storageIdImpl(Storage*);
     void debugFunction(const String& scriptId, int lineNumber, int columnNumber);
     void undebugFunction(const String& scriptId, int lineNumber, int columnNumber);
     void monitorFunction(const String& scriptId, int lineNumber, int columnNumber, const String& functionName);
diff --git a/Source/core/inspector/InjectedScriptHost.idl b/Source/core/inspector/InjectedScriptHost.idl
index 77e4cbe..da13730 100644
--- a/Source/core/inspector/InjectedScriptHost.idl
+++ b/Source/core/inspector/InjectedScriptHost.idl
@@ -41,16 +41,14 @@
     [Custom] boolean isHTMLAllCollection(any obj);
     [Custom] DOMString type(any obj);
     [Custom] any functionDetails(any obj);
-    [Custom] Array getInternalProperties(any obj);
-    [Custom] Array getEventListeners(Node node);
+    [Custom] any[] getInternalProperties(any obj);
+    [Custom] EventListener[] getEventListeners(EventTarget target);
     [Custom] any evaluate(DOMString text);
-    [Custom] DOMString databaseId(any database);
-    [Custom] DOMString storageId(any storage);
     [Custom] void debugFunction(any fn);
     [Custom] void undebugFunction(any fn);
     [Custom] void monitorFunction(any fn);
     [Custom] void unmonitorFunction(any fn);
 
     // Only declarative scope (local, with and catch) is accepted. Returns undefined.
-    [Custom] any setFunctionVariableValue(any functionObject, int scopeIndex, DOMString variableName, any newValue);
+    [Custom] any setFunctionVariableValue(any functionObject, long scopeIndex, DOMString variableName, any newValue);
 };
diff --git a/Source/core/inspector/InjectedScriptSource.js b/Source/core/inspector/InjectedScriptSource.js
index 64c39f7..efb9451 100644
--- a/Source/core/inspector/InjectedScriptSource.js
+++ b/Source/core/inspector/InjectedScriptSource.js
@@ -78,26 +78,39 @@
  * Please use this bind, not the one from Function.prototype
  * @param {function(...)} func
  * @param {Object} thisObject
- * @param {...number} var_args
+ * @param {...} var_args
  */
 function bind(func, thisObject, var_args)
 {
     var args = slice(arguments, 2);
 
     /**
-     * @param {...number} var_args
+     * @param {...} var_args
      */
     function bound(var_args)
     {
         return func.apply(thisObject, args.concat(slice(arguments)));
     }
-    bound.toString = function() {
+    bound.toString = function()
+    {
         return "bound: " + func;
     };
     return bound;
 }
 
 /**
+ * @param {T} obj
+ * @return {T}
+ * @template T
+ */
+function nullifyObjectProto(obj)
+{
+    if (obj && typeof obj === "object")
+        obj.__proto__ = null;
+    return obj;
+}
+
+/**
  * @constructor
  */
 var InjectedScript = function()
@@ -105,24 +118,25 @@
     /** @type {number} */
     this._lastBoundObjectId = 1;
     /** @type {!Object.<number, Object>} */
-    this._idToWrappedObject = {};
+    this._idToWrappedObject = { __proto__: null };
     /** @type {!Object.<number, string>} */
-    this._idToObjectGroupName = {};
+    this._idToObjectGroupName = { __proto__: null };
     /** @type {!Object.<string, Array.<number>>} */
-    this._objectGroups = {};
+    this._objectGroups = { __proto__: null };
     /** @type {!Object.<string, Object>} */
-    this._modules = {};
+    this._modules = { __proto__: null };
 }
 
 /**
- * @type {Object.<string, boolean>}
+ * @type {!Object.<string, boolean>}
  * @const
  */
 InjectedScript.primitiveTypes = {
-    undefined: true,
-    boolean: true,
-    number: true,
-    string: true
+    "undefined": true,
+    "boolean": true,
+    "number": true,
+    "string": true,
+    __proto__: null
 }
 
 InjectedScript.prototype = {
@@ -156,7 +170,7 @@
      */
     _fallbackWrapper: function(object)
     {
-        var result = {};
+        var result = { __proto__: null };
         result.type = typeof object;
         if (this.isPrimitiveValue(object))
             result.value = object;
@@ -204,20 +218,8 @@
             return;
 
         var objectId = this._wrapObject(object, "");
-        var hints = {};
+        var hints = { __proto__: null };
 
-        switch (injectedScript._describe(object)) {
-            case "Database":
-                var databaseId = InjectedScriptHost.databaseId(object)
-                if (databaseId)
-                    hints.databaseId = databaseId;
-                break;
-            case "Storage":
-                var storageId = InjectedScriptHost.storageId(object)
-                if (storageId)
-                    hints.domStorageId = InjectedScriptHost.evaluate("(" + storageId + ")");
-                break;
-        }
         InjectedScriptHost.inspect(objectId, hints);
         return object;
     },
@@ -271,11 +273,11 @@
 
     /**
      * @param {string} objectId
-     * @return {Object}
+     * @return {!Object}
      */
     _parseObjectId: function(objectId)
     {
-        return InjectedScriptHost.evaluate("(" + objectId + ")");
+        return nullifyObjectProto(InjectedScriptHost.evaluate("(" + objectId + ")"));
     },
 
     /**
@@ -358,7 +360,8 @@
                 var property = internalProperties[i];
                 var descriptor = {
                     name: property.name,
-                    value: this._wrapObject(property.value, objectGroupName)
+                    value: this._wrapObject(property.value, objectGroupName),
+                    __proto__: null
                 };
                 descriptors.push(descriptor);
             }
@@ -376,7 +379,7 @@
         var func = this._objectForId(parsedFunctionId);
         if (typeof func !== "function")
             return "Cannot resolve function by id.";
-        var details = InjectedScriptHost.functionDetails(func);
+        var details = nullifyObjectProto(InjectedScriptHost.functionDetails(func));
         if ("rawScopes" in details) {
             var objectGroupName = this._idToObjectGroupName[parsedFunctionId.id];
             var rawScopes = details.rawScopes;
@@ -431,7 +434,7 @@
 
                 try {
                     nameProcessed[name] = true;
-                    var descriptor = Object.getOwnPropertyDescriptor(/** @type {!Object} */ (o), name);
+                    var descriptor = nullifyObjectProto(Object.getOwnPropertyDescriptor(/** @type {!Object} */ (o), name));
                     if (descriptor) {
                         if (accessorPropertiesOnly && !("get" in descriptor || "set" in descriptor))
                             continue;
@@ -440,7 +443,7 @@
                         if (accessorPropertiesOnly)
                             continue;
                         try {
-                            descriptor = { name: name, value: o[name], writable: false, configurable: false, enumerable: false};
+                            descriptor = { name: name, value: o[name], writable: false, configurable: false, enumerable: false, __proto__: null };
                             if (o === object)
                                 descriptor.isOwn = true;
                             descriptors.push(descriptor);
@@ -452,7 +455,7 @@
                 } catch (e) {
                     if (accessorPropertiesOnly)
                         continue;
-                    var descriptor = {};
+                    var descriptor = { __proto__: null };
                     descriptor.value = e;
                     descriptor.wasThrown = true;
                 }
@@ -471,7 +474,7 @@
 
             if (ownProperties) {
                 if (object.__proto__ && !accessorPropertiesOnly)
-                    descriptors.push({ name: "__proto__", value: object.__proto__, writable: true, configurable: true, enumerable: false, isOwn: true});
+                    descriptors.push({ name: "__proto__", value: object.__proto__, writable: true, configurable: true, enumerable: false, isOwn: true, __proto__: null });
                 break;
             }
         }
@@ -496,7 +499,7 @@
      * @param {string} objectId
      * @param {string} expression
      * @param {boolean} returnByValue
-     * @return {Object|string}
+     * @return {!Object|string}
      */
     callFunctionOn: function(objectId, expression, args, returnByValue)
     {
@@ -526,7 +529,8 @@
                 return "Given expression does not evaluate to a function";
 
             return { wasThrown: false,
-                     result: this._wrapObject(func.apply(object, resolvedArgs), objectGroup, returnByValue) };
+                     result: this._wrapObject(func.apply(object, resolvedArgs), objectGroup, returnByValue),
+                     __proto__: null };
         } catch (e) {
             return this._createThrownValue(e, objectGroup);
         }
@@ -538,7 +542,9 @@
      * @return {*} resolved value
      * @throws {string} error message
      */
-    _resolveCallArgument: function(callArgumentJson) {
+    _resolveCallArgument: function(callArgumentJson)
+    {
+        callArgumentJson = nullifyObjectProto(callArgumentJson);
         var objectId = callArgumentJson.objectId;
         if (objectId) {
             var parsedArgId = this._parseObjectId(objectId);
@@ -564,13 +570,15 @@
      * @param {boolean} injectCommandLineAPI
      * @param {boolean} returnByValue
      * @param {boolean} generatePreview
-     * @return {*}
+     * @param {!Array.<!Object>=} scopeChain
+     * @return {!Object}
      */
-    _evaluateAndWrap: function(evalFunction, object, expression, objectGroup, isEvalOnCallFrame, injectCommandLineAPI, returnByValue, generatePreview)
+    _evaluateAndWrap: function(evalFunction, object, expression, objectGroup, isEvalOnCallFrame, injectCommandLineAPI, returnByValue, generatePreview, scopeChain)
     {
         try {
             return { wasThrown: false,
-                     result: this._wrapObject(this._evaluateOn(evalFunction, object, objectGroup, expression, isEvalOnCallFrame, injectCommandLineAPI), objectGroup, returnByValue, generatePreview) };
+                     result: this._wrapObject(this._evaluateOn(evalFunction, object, objectGroup, expression, isEvalOnCallFrame, injectCommandLineAPI, scopeChain), objectGroup, returnByValue, generatePreview),
+                     __proto__: null };
         } catch (e) {
             return this._createThrownValue(e, objectGroup);
         }
@@ -579,7 +587,7 @@
     /**
      * @param {*} value
      * @param {string} objectGroup
-     * @return {Object}
+     * @return {!Object}
      */
     _createThrownValue: function(value, objectGroup)
     {
@@ -587,7 +595,7 @@
         try {
             remoteObject.description = toStringDescription(value);
         } catch (e) {}
-        return { wasThrown: true, result: remoteObject };
+        return { wasThrown: true, result: remoteObject, __proto__: null };
     },
 
     /**
@@ -597,19 +605,38 @@
      * @param {string} expression
      * @param {boolean} isEvalOnCallFrame
      * @param {boolean} injectCommandLineAPI
+     * @param {!Array.<!Object>=} scopeChain
      * @return {*}
      */
-    _evaluateOn: function(evalFunction, object, objectGroup, expression, isEvalOnCallFrame, injectCommandLineAPI)
+    _evaluateOn: function(evalFunction, object, objectGroup, expression, isEvalOnCallFrame, injectCommandLineAPI, scopeChain)
     {
         // Only install command line api object for the time of evaluation.
         // Surround the expression in with statements to inject our command line API so that
         // the window object properties still take more precedent than our API functions.
 
+        var injectScopeChain = scopeChain && scopeChain.length;
+
         try {
+            var prefix = "";
+            var suffix = "";
             if (injectCommandLineAPI && inspectedWindow.console) {
                 inspectedWindow.console._commandLineAPI = new CommandLineAPI(this._commandLineAPIImpl, isEvalOnCallFrame ? object : null);
-                expression = "with ((console && console._commandLineAPI) || {}) {\n" + expression + "\n}";
+                prefix = "with ((console && console._commandLineAPI) || { __proto__: null }) {";
+                suffix = "}";
             }
+            if (injectScopeChain && inspectedWindow.console) {
+                inspectedWindow.console._scopeChainForEval = scopeChain;
+                for (var i = 0; i < scopeChain.length; ++i) {
+                    prefix = "with ((console && console._scopeChainForEval[" + i + "]) || { __proto__: null }) {" + (suffix ? " " : "") + prefix;
+                    if (suffix)
+                        suffix += " }";
+                    else
+                        suffix = "}";
+                }
+            }
+
+            if (prefix)
+                expression = prefix + "\n" + expression + "\n" + suffix;
             var result = evalFunction.call(object, expression);
             if (objectGroup === "console")
                 this._lastResult = result;
@@ -617,14 +644,17 @@
         } finally {
             if (injectCommandLineAPI && inspectedWindow.console)
                 delete inspectedWindow.console._commandLineAPI;
+            if (injectScopeChain && inspectedWindow.console)
+                delete inspectedWindow.console._scopeChainForEval;
         }
     },
 
     /**
-     * @param {Object} callFrame
-     * @return {!Array.<InjectedScript.CallFrameProxy>|boolean}
+     * @param {?Object} callFrame
+     * @param {number} asyncOrdinal
+     * @return {!Array.<!InjectedScript.CallFrameProxy>|boolean}
      */
-    wrapCallFrames: function(callFrame)
+    wrapCallFrames: function(callFrame, asyncOrdinal)
     {
         if (!callFrame)
             return false;
@@ -632,14 +662,15 @@
         var result = [];
         var depth = 0;
         do {
-            result.push(new InjectedScript.CallFrameProxy(depth++, callFrame));
+            result.push(new InjectedScript.CallFrameProxy(depth++, callFrame, asyncOrdinal));
             callFrame = callFrame.caller;
         } while (callFrame);
         return result;
     },
 
     /**
-     * @param {Object} topCallFrame
+     * @param {!Object} topCallFrame
+     * @param {!Array.<!Object>} asyncCallStacks
      * @param {string} callFrameId
      * @param {string} expression
      * @param {string} objectGroup
@@ -648,16 +679,19 @@
      * @param {boolean} generatePreview
      * @return {*}
      */
-    evaluateOnCallFrame: function(topCallFrame, callFrameId, expression, objectGroup, injectCommandLineAPI, returnByValue, generatePreview)
+    evaluateOnCallFrame: function(topCallFrame, asyncCallStacks, callFrameId, expression, objectGroup, injectCommandLineAPI, returnByValue, generatePreview)
     {
-        var callFrame = this.callFrameForId(topCallFrame, callFrameId);
+        var parsedCallFrameId = nullifyObjectProto(InjectedScriptHost.evaluate("(" + callFrameId + ")"));
+        var callFrame = this._callFrameForParsedId(topCallFrame, parsedCallFrameId, asyncCallStacks);
         if (!callFrame)
             return "Could not find call frame with given id";
+        if (parsedCallFrameId["asyncOrdinal"])
+            return this._evaluateAndWrap(InjectedScriptHost.evaluate, InjectedScriptHost, expression, objectGroup, false, injectCommandLineAPI, returnByValue, generatePreview, callFrame.scopeChain);
         return this._evaluateAndWrap(callFrame.evaluate, callFrame, expression, objectGroup, true, injectCommandLineAPI, returnByValue, generatePreview);
     },
 
     /**
-     * @param {Object} topCallFrame
+     * @param {!Object} topCallFrame
      * @param {string} callFrameId
      * @return {*}
      */
@@ -673,7 +707,7 @@
     },
 
     /**
-     * @param {Object} topCallFrame
+     * @param {!Object} topCallFrame
      * @param {string} callFrameId
      * @return {*} a stepIn position array ready for protocol JSON or a string error
      */
@@ -690,7 +724,7 @@
 
     /**
      * Either callFrameId or functionObjectId must be specified.
-     * @param {Object} topCallFrame
+     * @param {!Object} topCallFrame
      * @param {string|boolean} callFrameId or false
      * @param {string|boolean} functionObjectId or false
      * @param {number} scopeNumber
@@ -734,13 +768,27 @@
     },
 
     /**
-     * @param {Object} topCallFrame
+     * @param {!Object} topCallFrame
      * @param {string} callFrameId
-     * @return {Object}
+     * @return {?Object}
      */
     callFrameForId: function(topCallFrame, callFrameId)
     {
-        var parsedCallFrameId = InjectedScriptHost.evaluate("(" + callFrameId + ")");
+        var parsedCallFrameId = nullifyObjectProto(InjectedScriptHost.evaluate("(" + callFrameId + ")"));
+        return this._callFrameForParsedId(topCallFrame, parsedCallFrameId, []);
+    },
+
+    /**
+     * @param {!Object} topCallFrame
+     * @param {!Object} parsedCallFrameId
+     * @param {!Array.<!Object>} asyncCallStacks
+     * @return {?Object}
+     */
+    _callFrameForParsedId: function(topCallFrame, parsedCallFrameId, asyncCallStacks)
+    {
+        var asyncOrdinal = parsedCallFrameId["asyncOrdinal"]; // 1-based index
+        if (asyncOrdinal)
+            topCallFrame = asyncCallStacks[asyncOrdinal - 1];
         var ordinal = parsedCallFrameId["ordinal"];
         var callFrame = topCallFrame;
         while (--ordinal >= 0 && callFrame)
@@ -969,7 +1017,7 @@
      */
     _generatePreview: function(object, firstLevelKeys, secondLevelKeys, isTable, isTableRow)
     {
-        var preview = {};
+        var preview = { __proto__: null };
         preview.lossless = true;
         preview.overflow = false;
         preview.properties = [];
@@ -985,7 +1033,7 @@
             var descriptors = injectedScript._propertyDescriptors(object);
 
             if (firstLevelKeys) {
-                var nameToDescriptors = {};
+                var nameToDescriptors = { __proto__: null };
                 for (var i = 0; i < descriptors.length; ++i) {
                     var descriptor = descriptors[i];
                     nameToDescriptors["#" + descriptor.name] = descriptor;
@@ -1016,13 +1064,14 @@
                     continue;
 
                 if (!("value" in descriptor)) {
-                    this._appendPropertyPreview(preview, { name: name, type: "accessor" }, propertiesThreshold);
+                    preview.lossless = false;
+                    this._appendPropertyPreview(preview, { name: name, type: "accessor", __proto__: null }, propertiesThreshold);
                     continue;
                 }
 
                 var value = descriptor.value;
                 if (value === null) {
-                    this._appendPropertyPreview(preview, { name: name, type: "object", value: "null" }, propertiesThreshold);
+                    this._appendPropertyPreview(preview, { name: name, type: "object", value: "null", __proto__: null }, propertiesThreshold);
                     continue;
                 }
 
@@ -1038,13 +1087,13 @@
                         value = this._abbreviateString(value, maxLength, true);
                         preview.lossless = false;
                     }
-                    this._appendPropertyPreview(preview, { name: name, type: type, value: toStringDescription(value) }, propertiesThreshold);
+                    this._appendPropertyPreview(preview, { name: name, type: type, value: toStringDescription(value), __proto__: null }, propertiesThreshold);
                     continue;
                 }
 
                 if (secondLevelKeys === null || secondLevelKeys) {
                     var subPreview = this._generatePreview(value, secondLevelKeys || undefined, undefined, false, isTable);
-                    var property = { name: name, type: type, valuePreview: subPreview };
+                    var property = { name: name, type: type, valuePreview: subPreview, __proto__: null };
                     this._appendPropertyPreview(preview, property, propertiesThreshold);
                     if (!subPreview.lossless)
                         preview.lossless = false;
@@ -1060,7 +1109,7 @@
                 if (type !== "function")
                     description = this._abbreviateString(/** @type {string} */ (injectedScript._describe(value)), maxLength, subtype === "regexp");
 
-                var property = { name: name, type: type, value: description };
+                var property = { name: name, type: type, value: description, __proto__: null };
                 if (subtype)
                     property.subtype = subtype;
                 this._appendPropertyPreview(preview, property, propertiesThreshold);
@@ -1095,7 +1144,7 @@
      * @param {string} string
      * @param {number} maxLength
      * @param {boolean=} middle
-     * @returns
+     * @return {string}
      */
     _abbreviateString: function(string, maxLength, middle)
     {
@@ -1107,18 +1156,21 @@
             return string.substr(0, leftHalf) + "\u2026" + string.substr(string.length - rightHalf, rightHalf);
         }
         return string.substr(0, maxLength) + "\u2026";
-    }
+    },
+
+    __proto__: null
 }
 /**
  * @constructor
  * @param {number} ordinal
  * @param {!Object} callFrame
+ * @param {number} asyncOrdinal
  */
-InjectedScript.CallFrameProxy = function(ordinal, callFrame)
+InjectedScript.CallFrameProxy = function(ordinal, callFrame, asyncOrdinal)
 {
-    this.callFrameId = "{\"ordinal\":" + ordinal + ",\"injectedScriptId\":" + injectedScriptId + "}";
+    this.callFrameId = "{\"ordinal\":" + ordinal + ",\"injectedScriptId\":" + injectedScriptId + (asyncOrdinal ? ",\"asyncOrdinal\":" + asyncOrdinal : "") + "}";
     this.functionName = (callFrame.type === "function" ? callFrame.functionName : "");
-    this.location = { scriptId: toString(callFrame.sourceID), lineNumber: callFrame.line, columnNumber: callFrame.column };
+    this.location = { scriptId: toString(callFrame.sourceID), lineNumber: callFrame.line, columnNumber: callFrame.column, __proto__: null };
     this.scopeChain = this._wrapScopeChain(callFrame);
     this.this = injectedScript._wrapObject(callFrame.thisObject, "backtrace");
     if (callFrame.isAtReturn)
@@ -1139,7 +1191,9 @@
             scopeChainProxy.push(scope);
         }
         return scopeChainProxy;
-    }
+    },
+
+    __proto__: null
 }
 
 /**
@@ -1148,7 +1202,8 @@
  * @param {string} groupId
  * @return {!DebuggerAgent.Scope}
  */
-InjectedScript.CallFrameProxy._createScopeJson = function(scopeTypeCode, scopeObject, groupId) {
+InjectedScript.CallFrameProxy._createScopeJson = function(scopeTypeCode, scopeObject, groupId)
+{
     const GLOBAL_SCOPE = 0;
     const LOCAL_SCOPE = 1;
     const WITH_SCOPE = 2;
@@ -1156,7 +1211,7 @@
     const CATCH_SCOPE = 4;
 
     /** @type {!Object.<number, string>} */
-    var scopeTypeNames = {};
+    var scopeTypeNames = { __proto__: null };
     scopeTypeNames[GLOBAL_SCOPE] = "global";
     scopeTypeNames[LOCAL_SCOPE] = "local";
     scopeTypeNames[WITH_SCOPE] = "with";
@@ -1165,7 +1220,8 @@
 
     return {
         object: injectedScript._wrapObject(scopeObject, groupId),
-        type: /** @type {DebuggerAgent.ScopeType} */ (scopeTypeNames[scopeTypeCode])
+        type: /** @type {DebuggerAgent.ScopeType} */ (scopeTypeNames[scopeTypeCode]),
+        __proto__: null
     };
 }
 
@@ -1233,6 +1289,8 @@
     }
 
     this.$_ = injectedScript._lastResult;
+
+    this.__proto__ = null;
 }
 
 // NOTE: Please keep the list of API methods below snchronized to that in WebInspector.RuntimeModel!
@@ -1396,7 +1454,7 @@
             }
         }
 
-        var hints = { copyToClipboard: true };
+        var hints = { copyToClipboard: true, __proto__: null };
         var remoteObject = injectedScript._wrapObject(string, "")
         InjectedScriptHost.inspect(remoteObject, hints);
     },
@@ -1412,7 +1470,7 @@
      */
     getEventListeners: function(node)
     {
-        var result = InjectedScriptHost.getEventListeners(node);
+        var result = nullifyObjectProto(InjectedScriptHost.getEventListeners(node));
         if (!result)
             return result;
         /** @this {{type: string, listener: function(), useCapture: boolean}} */
@@ -1445,7 +1503,8 @@
         InjectedScriptHost.monitorFunction(fn);
     },
 
-    unmonitor: function(fn) {
+    unmonitor: function(fn)
+    {
         InjectedScriptHost.unmonitorFunction(fn);
     },
 
diff --git a/Source/core/inspector/InspectorApplicationCacheAgent.cpp b/Source/core/inspector/InspectorApplicationCacheAgent.cpp
index 954c28a..0e83a41 100644
--- a/Source/core/inspector/InspectorApplicationCacheAgent.cpp
+++ b/Source/core/inspector/InspectorApplicationCacheAgent.cpp
@@ -41,8 +41,8 @@
 static const char applicationCacheAgentEnabled[] = "applicationCacheAgentEnabled";
 }
 
-InspectorApplicationCacheAgent::InspectorApplicationCacheAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorPageAgent* pageAgent)
-    : InspectorBaseAgent<InspectorApplicationCacheAgent>("ApplicationCache", instrumentingAgents, state)
+InspectorApplicationCacheAgent::InspectorApplicationCacheAgent(InspectorPageAgent* pageAgent)
+    : InspectorBaseAgent<InspectorApplicationCacheAgent>("ApplicationCache")
     , m_pageAgent(pageAgent)
     , m_frontend(0)
 {
diff --git a/Source/core/inspector/InspectorApplicationCacheAgent.h b/Source/core/inspector/InspectorApplicationCacheAgent.h
index 8b9b9d5..2f22dec 100644
--- a/Source/core/inspector/InspectorApplicationCacheAgent.h
+++ b/Source/core/inspector/InspectorApplicationCacheAgent.h
@@ -40,32 +40,32 @@
 
 typedef String ErrorString;
 
-class InspectorApplicationCacheAgent : public InspectorBaseAgent<InspectorApplicationCacheAgent>, public InspectorBackendDispatcher::ApplicationCacheCommandHandler {
+class InspectorApplicationCacheAgent FINAL : public InspectorBaseAgent<InspectorApplicationCacheAgent>, public InspectorBackendDispatcher::ApplicationCacheCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorApplicationCacheAgent); WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<InspectorApplicationCacheAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorPageAgent* pageAgent)
+    static PassOwnPtr<InspectorApplicationCacheAgent> create(InspectorPageAgent* pageAgent)
     {
-        return adoptPtr(new InspectorApplicationCacheAgent(instrumentingAgents, state, pageAgent));
+        return adoptPtr(new InspectorApplicationCacheAgent(pageAgent));
     }
-    ~InspectorApplicationCacheAgent() { }
+    virtual ~InspectorApplicationCacheAgent() { }
 
     // InspectorBaseAgent
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
 
     // InspectorInstrumentation API
     void updateApplicationCacheStatus(Frame*);
     void networkStateChanged(bool online);
 
     // ApplicationCache API for InspectorFrontend
-    virtual void enable(ErrorString*);
-    virtual void getFramesWithManifests(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::ApplicationCache::FrameWithManifest> >& result);
-    virtual void getManifestForFrame(ErrorString*, const String& frameId, String* manifestURL);
-    virtual void getApplicationCacheForFrame(ErrorString*, const String& frameId, RefPtr<TypeBuilder::ApplicationCache::ApplicationCache>&);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void getFramesWithManifests(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::ApplicationCache::FrameWithManifest> >& result) OVERRIDE;
+    virtual void getManifestForFrame(ErrorString*, const String& frameId, String* manifestURL) OVERRIDE;
+    virtual void getApplicationCacheForFrame(ErrorString*, const String& frameId, RefPtr<TypeBuilder::ApplicationCache::ApplicationCache>&) OVERRIDE;
 
 private:
-    InspectorApplicationCacheAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorPageAgent*);
+    InspectorApplicationCacheAgent(InspectorPageAgent*);
     PassRefPtr<TypeBuilder::ApplicationCache::ApplicationCache> buildObjectForApplicationCache(const ApplicationCacheHost::ResourceInfoList&, const ApplicationCacheHost::CacheInfo&);
     PassRefPtr<TypeBuilder::Array<TypeBuilder::ApplicationCache::ApplicationCacheResource> > buildArrayForApplicationCacheResources(const ApplicationCacheHost::ResourceInfoList&);
     PassRefPtr<TypeBuilder::ApplicationCache::ApplicationCacheResource> buildObjectForApplicationCacheResource(const ApplicationCacheHost::ResourceInfo&);
diff --git a/Source/core/inspector/InspectorBaseAgent.cpp b/Source/core/inspector/InspectorBaseAgent.cpp
index dd63adb..5d93086 100644
--- a/Source/core/inspector/InspectorBaseAgent.cpp
+++ b/Source/core/inspector/InspectorBaseAgent.cpp
@@ -36,19 +36,31 @@
 
 namespace WebCore {
 
-InspectorBaseAgentInterface::InspectorBaseAgentInterface(const String& name, InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState)
+InspectorAgent::InspectorAgent(const String& name)
+    : m_name(name)
+{
+}
+
+InspectorAgent::~InspectorAgent()
+{
+}
+
+void InspectorAgent::appended(InstrumentingAgents* instrumentingAgents, InspectorState* inspectorState)
+{
+    m_instrumentingAgents = instrumentingAgents;
+    m_state = inspectorState;
+    init();
+}
+
+InspectorAgentRegistry::InspectorAgentRegistry(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState)
     : m_instrumentingAgents(instrumentingAgents)
-    , m_state(inspectorState->createAgentState(name))
-    , m_name(name)
+    , m_inspectorState(inspectorState)
 {
 }
 
-InspectorBaseAgentInterface::~InspectorBaseAgentInterface()
+void InspectorAgentRegistry::append(PassOwnPtr<InspectorAgent> agent)
 {
-}
-
-void InspectorAgentRegistry::append(PassOwnPtr<InspectorBaseAgentInterface> agent)
-{
+    agent->appended(m_instrumentingAgents, m_inspectorState->createAgentState(agent->name()));
     m_agents.append(agent);
 }
 
diff --git a/Source/core/inspector/InspectorBaseAgent.h b/Source/core/inspector/InspectorBaseAgent.h
index 0369e09..af1c670 100644
--- a/Source/core/inspector/InspectorBaseAgent.h
+++ b/Source/core/inspector/InspectorBaseAgent.h
@@ -43,18 +43,21 @@
 class InspectorState;
 class InstrumentingAgents;
 
-class InspectorBaseAgentInterface {
+class InspectorAgent {
 public:
-    InspectorBaseAgentInterface(const String&, InstrumentingAgents*, InspectorCompositeState*);
-    virtual ~InspectorBaseAgentInterface();
+    explicit InspectorAgent(const String&);
+    virtual ~InspectorAgent();
 
+    virtual void init() { }
     virtual void setFrontend(InspectorFrontend*) { }
     virtual void clearFrontend() { }
     virtual void restore() { }
     virtual void registerInDispatcher(InspectorBackendDispatcher*) = 0;
     virtual void discardAgent() { }
+    virtual void didCommitLoadForMainFrame() { }
 
     String name() { return m_name; }
+    void appended(InstrumentingAgents*, InspectorState*);
 
 protected:
     InstrumentingAgents* m_instrumentingAgents;
@@ -66,7 +69,8 @@
 
 class InspectorAgentRegistry {
 public:
-    void append(PassOwnPtr<InspectorBaseAgentInterface>);
+    InspectorAgentRegistry(InstrumentingAgents*, InspectorCompositeState*);
+    void append(PassOwnPtr<InspectorAgent>);
 
     void setFrontend(InspectorFrontend*);
     void clearFrontend();
@@ -75,22 +79,23 @@
     void discardAgents();
 
 private:
-    Vector<OwnPtr<InspectorBaseAgentInterface> > m_agents;
+    InstrumentingAgents* m_instrumentingAgents;
+    InspectorCompositeState* m_inspectorState;
+    Vector<OwnPtr<InspectorAgent> > m_agents;
 };
 
 template<typename T>
-class InspectorBaseAgent : public InspectorBaseAgentInterface {
+class InspectorBaseAgent : public InspectorAgent {
 public:
     virtual ~InspectorBaseAgent() { }
 
-    virtual void registerInDispatcher(InspectorBackendDispatcher* dispatcher)
+    virtual void registerInDispatcher(InspectorBackendDispatcher* dispatcher) OVERRIDE FINAL
     {
         dispatcher->registerAgent(static_cast<T*>(this));
     }
 
 protected:
-    InspectorBaseAgent(const String& name, InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState)
-        : InspectorBaseAgentInterface(name, instrumentingAgents, inspectorState)
+    InspectorBaseAgent(const String& name) : InspectorAgent(name)
     {
     }
 };
diff --git a/Source/core/inspector/InspectorCSSAgent.cpp b/Source/core/inspector/InspectorCSSAgent.cpp
index d4bafdf..c1767d7 100644
--- a/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/Source/core/inspector/InspectorCSSAgent.cpp
@@ -32,9 +32,9 @@
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/css/CSSComputedStyleDeclaration.h"
+#include "core/css/CSSDefaultStyleSheets.h"
 #include "core/css/CSSImportRule.h"
 #include "core/css/CSSMediaRule.h"
-#include "core/css/CSSParser.h"
 #include "core/css/CSSRule.h"
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSStyleRule.h"
@@ -46,8 +46,6 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/css/StyleSheetList.h"
 #include "core/css/resolver/StyleResolver.h"
-#include "core/dom/NamedFlow.h"
-#include "core/dom/NamedFlowCollection.h"
 #include "core/dom/Node.h"
 #include "core/dom/NodeList.h"
 #include "core/fetch/CSSStyleSheetResource.h"
@@ -65,7 +63,6 @@
 #include "core/page/Page.h"
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderObject.h"
-#include "core/rendering/RenderRegion.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/RenderTextFragment.h"
 #include "platform/fonts/Font.h"
@@ -92,28 +89,6 @@
     PseudoVisited = 1 << 3
 };
 
-class StyleSheetAppender {
-public:
-    StyleSheetAppender(Vector<CSSStyleSheet*>& result)
-        : m_result(result) { }
-
-    void run(CSSStyleSheet* styleSheet)
-    {
-        m_result.append(styleSheet);
-        for (unsigned i = 0, size = styleSheet->length(); i < size; ++i) {
-            CSSRule* rule = styleSheet->item(i);
-            if (rule->type() == CSSRule::IMPORT_RULE) {
-                CSSStyleSheet* importedStyleSheet = toCSSImportRule(rule)->styleSheet();
-                if (importedStyleSheet)
-                    run(importedStyleSheet);
-            }
-        }
-    }
-
-private:
-    Vector<CSSStyleSheet*>& m_result;
-};
-
 static unsigned computePseudoClassMask(JSONArray* pseudoClassArray)
 {
     DEFINE_STATIC_LOCAL(String, active, ("active"));
@@ -143,115 +118,6 @@
     return result;
 }
 
-class UpdateRegionLayoutTask {
-public:
-    UpdateRegionLayoutTask(InspectorCSSAgent*);
-    void scheduleFor(NamedFlow*, int documentNodeId);
-    void unschedule(NamedFlow*);
-    void reset();
-    void onTimer(Timer<UpdateRegionLayoutTask>*);
-
-private:
-    InspectorCSSAgent* m_cssAgent;
-    Timer<UpdateRegionLayoutTask> m_timer;
-    HashMap<NamedFlow*, int> m_namedFlows;
-};
-
-UpdateRegionLayoutTask::UpdateRegionLayoutTask(InspectorCSSAgent* cssAgent)
-    : m_cssAgent(cssAgent)
-    , m_timer(this, &UpdateRegionLayoutTask::onTimer)
-{
-}
-
-void UpdateRegionLayoutTask::scheduleFor(NamedFlow* namedFlow, int documentNodeId)
-{
-    m_namedFlows.add(namedFlow, documentNodeId);
-
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
-}
-
-void UpdateRegionLayoutTask::unschedule(NamedFlow* namedFlow)
-{
-    m_namedFlows.remove(namedFlow);
-}
-
-void UpdateRegionLayoutTask::reset()
-{
-    m_timer.stop();
-    m_namedFlows.clear();
-}
-
-void UpdateRegionLayoutTask::onTimer(Timer<UpdateRegionLayoutTask>*)
-{
-    // The timer is stopped on m_cssAgent destruction, so this method will never be called after m_cssAgent has been destroyed.
-    Vector<std::pair<NamedFlow*, int> > namedFlows;
-
-    for (HashMap<NamedFlow*, int>::iterator it = m_namedFlows.begin(), end = m_namedFlows.end(); it != end; ++it)
-        namedFlows.append(std::make_pair(it->key, it->value));
-
-    for (unsigned i = 0, size = namedFlows.size(); i < size; ++i) {
-        NamedFlow* namedFlow = namedFlows.at(i).first;
-        int documentNodeId = namedFlows.at(i).second;
-
-        if (m_namedFlows.contains(namedFlow)) {
-            m_cssAgent->regionLayoutUpdated(namedFlow, documentNodeId);
-            m_namedFlows.remove(namedFlow);
-        }
-    }
-
-    if (!m_namedFlows.isEmpty() && !m_timer.isActive())
-        m_timer.startOneShot(0);
-}
-
-class ChangeRegionOversetTask {
-public:
-    ChangeRegionOversetTask(InspectorCSSAgent*);
-    void scheduleFor(NamedFlow*, int documentNodeId);
-    void unschedule(NamedFlow*);
-    void reset();
-    void onTimer(Timer<ChangeRegionOversetTask>*);
-
-private:
-    InspectorCSSAgent* m_cssAgent;
-    Timer<ChangeRegionOversetTask> m_timer;
-    HashMap<NamedFlow*, int> m_namedFlows;
-};
-
-ChangeRegionOversetTask::ChangeRegionOversetTask(InspectorCSSAgent* cssAgent)
-    : m_cssAgent(cssAgent)
-    , m_timer(this, &ChangeRegionOversetTask::onTimer)
-{
-}
-
-void ChangeRegionOversetTask::scheduleFor(NamedFlow* namedFlow, int documentNodeId)
-{
-    m_namedFlows.add(namedFlow, documentNodeId);
-
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
-}
-
-void ChangeRegionOversetTask::unschedule(NamedFlow* namedFlow)
-{
-    m_namedFlows.remove(namedFlow);
-}
-
-void ChangeRegionOversetTask::reset()
-{
-    m_timer.stop();
-    m_namedFlows.clear();
-}
-
-void ChangeRegionOversetTask::onTimer(Timer<ChangeRegionOversetTask>*)
-{
-    // The timer is stopped on m_cssAgent destruction, so this method will never be called after m_cssAgent has been destroyed.
-    for (HashMap<NamedFlow*, int>::iterator it = m_namedFlows.begin(), end = m_namedFlows.end(); it != end; ++it)
-        m_cssAgent->regionOversetChanged(it->key, it->value);
-
-    m_namedFlows.clear();
-}
-
 class InspectorCSSAgent::StyleSheetAction : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(StyleSheetAction);
 public:
@@ -265,7 +131,7 @@
     RefPtr<InspectorStyleSheet> m_styleSheet;
 };
 
-class InspectorCSSAgent::EnableResourceClient : public StyleSheetResourceClient {
+class InspectorCSSAgent::EnableResourceClient FINAL : public StyleSheetResourceClient {
 public:
     EnableResourceClient(InspectorCSSAgent*, const Vector<InspectorStyleSheet*>&, PassRefPtr<EnableCallback>);
 
@@ -306,7 +172,7 @@
     delete this;
 }
 
-class InspectorCSSAgent::SetStyleSheetTextAction : public InspectorCSSAgent::StyleSheetAction {
+class InspectorCSSAgent::SetStyleSheetTextAction FINAL : public InspectorCSSAgent::StyleSheetAction {
     WTF_MAKE_NONCOPYABLE(SetStyleSheetTextAction);
 public:
     SetStyleSheetTextAction(InspectorStyleSheet* styleSheet, const String& text)
@@ -315,14 +181,14 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         if (!m_styleSheet->getText(&m_oldText))
             return false;
         return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         if (m_styleSheet->setText(m_oldText, exceptionState)) {
             m_styleSheet->reparseStyleSheet(m_oldText);
@@ -331,7 +197,7 @@
         return false;
     }
 
-    virtual bool redo(ExceptionState& exceptionState)
+    virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
         if (m_styleSheet->setText(m_text, exceptionState)) {
             m_styleSheet->reparseStyleSheet(m_text);
@@ -340,12 +206,12 @@
         return false;
     }
 
-    virtual String mergeId()
+    virtual String mergeId() OVERRIDE
     {
         return String::format("SetStyleSheetText %s", m_styleSheet->id().utf8().data());
     }
 
-    virtual void merge(PassOwnPtr<Action> action)
+    virtual void merge(PassOwnPtr<Action> action) OVERRIDE
     {
         ASSERT(action->mergeId() == mergeId());
 
@@ -358,57 +224,7 @@
     String m_oldText;
 };
 
-class InspectorCSSAgent::SetStyleTextAction : public InspectorCSSAgent::StyleSheetAction {
-    WTF_MAKE_NONCOPYABLE(SetStyleTextAction);
-public:
-    SetStyleTextAction(InspectorStyleSheet* styleSheet, const InspectorCSSId& cssId, const String& text)
-        : InspectorCSSAgent::StyleSheetAction("SetPropertyText", styleSheet)
-        , m_cssId(cssId)
-        , m_text(text)
-    {
-    }
-
-    virtual String toString()
-    {
-        return mergeId() + ": " + m_oldText + " -> " + m_text;
-    }
-
-    virtual bool perform(ExceptionState& exceptionState)
-    {
-        return redo(exceptionState);
-    }
-
-    virtual bool undo(ExceptionState& exceptionState)
-    {
-        String placeholder;
-        return m_styleSheet->setStyleText(m_cssId, m_oldText, &placeholder, exceptionState);
-    }
-
-    virtual bool redo(ExceptionState& exceptionState)
-    {
-        return m_styleSheet->setStyleText(m_cssId, m_text, &m_oldText, exceptionState);
-    }
-
-    virtual String mergeId()
-    {
-        return String::format("SetStyleText %s:%u", m_cssId.styleSheetId().utf8().data(), m_cssId.ordinal());
-    }
-
-    virtual void merge(PassOwnPtr<Action> action)
-    {
-        ASSERT(action->mergeId() == mergeId());
-
-        SetStyleTextAction* other = static_cast<SetStyleTextAction*>(action.get());
-        m_text = other->m_text;
-    }
-
-private:
-    InspectorCSSId m_cssId;
-    String m_text;
-    String m_oldText;
-};
-
-class InspectorCSSAgent::SetPropertyTextAction : public InspectorCSSAgent::StyleSheetAction {
+class InspectorCSSAgent::SetPropertyTextAction FINAL : public InspectorCSSAgent::StyleSheetAction {
     WTF_MAKE_NONCOPYABLE(SetPropertyTextAction);
 public:
     SetPropertyTextAction(InspectorStyleSheet* styleSheet, const InspectorCSSId& cssId, unsigned propertyIndex, const String& text, bool overwrite)
@@ -420,39 +236,36 @@
     {
     }
 
-    virtual String toString()
+    virtual String toString() OVERRIDE
     {
         return mergeId() + ": " + m_oldText + " -> " + m_text;
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         String placeholder;
         return m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_overwrite ? m_oldText : "", true, &placeholder, exceptionState);
     }
 
-    virtual bool redo(ExceptionState& exceptionState)
+    virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
         String oldText;
         bool result = m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_text, m_overwrite, &oldText, exceptionState);
         m_oldText = oldText.stripWhiteSpace();
-        // FIXME: remove this once the model handles this case.
-        if (!m_oldText.endsWith(';'))
-            m_oldText.append(';');
         return result;
     }
 
-    virtual String mergeId()
+    virtual String mergeId() OVERRIDE
     {
         return String::format("SetPropertyText %s:%u:%s", m_styleSheet->id().utf8().data(), m_propertyIndex, m_overwrite ? "true" : "false");
     }
 
-    virtual void merge(PassOwnPtr<Action> action)
+    virtual void merge(PassOwnPtr<Action> action) OVERRIDE
     {
         ASSERT(action->mergeId() == mergeId());
 
@@ -468,39 +281,7 @@
     bool m_overwrite;
 };
 
-class InspectorCSSAgent::TogglePropertyAction : public InspectorCSSAgent::StyleSheetAction {
-    WTF_MAKE_NONCOPYABLE(TogglePropertyAction);
-public:
-    TogglePropertyAction(InspectorStyleSheet* styleSheet, const InspectorCSSId& cssId, unsigned propertyIndex, bool disable)
-        : InspectorCSSAgent::StyleSheetAction("ToggleProperty", styleSheet)
-        , m_cssId(cssId)
-        , m_propertyIndex(propertyIndex)
-        , m_disable(disable)
-    {
-    }
-
-    virtual bool perform(ExceptionState& exceptionState)
-    {
-        return redo(exceptionState);
-    }
-
-    virtual bool undo(ExceptionState& exceptionState)
-    {
-        return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, !m_disable, exceptionState);
-    }
-
-    virtual bool redo(ExceptionState& exceptionState)
-    {
-        return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, m_disable, exceptionState);
-    }
-
-private:
-    InspectorCSSId m_cssId;
-    unsigned m_propertyIndex;
-    bool m_disable;
-};
-
-class InspectorCSSAgent::SetRuleSelectorAction : public InspectorCSSAgent::StyleSheetAction {
+class InspectorCSSAgent::SetRuleSelectorAction FINAL : public InspectorCSSAgent::StyleSheetAction {
     WTF_MAKE_NONCOPYABLE(SetRuleSelectorAction);
 public:
     SetRuleSelectorAction(InspectorStyleSheet* styleSheet, const InspectorCSSId& cssId, const String& selector)
@@ -510,7 +291,7 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         m_oldSelector = m_styleSheet->ruleSelector(m_cssId, exceptionState);
         if (exceptionState.hadException())
@@ -518,12 +299,12 @@
         return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         return m_styleSheet->setRuleSelector(m_cssId, m_oldSelector, exceptionState);
     }
 
-    virtual bool redo(ExceptionState& exceptionState)
+    virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
         return m_styleSheet->setRuleSelector(m_cssId, m_selector, exceptionState);
     }
@@ -534,7 +315,7 @@
     String m_oldSelector;
 };
 
-class InspectorCSSAgent::AddRuleAction : public InspectorCSSAgent::StyleSheetAction {
+class InspectorCSSAgent::AddRuleAction FINAL : public InspectorCSSAgent::StyleSheetAction {
     WTF_MAKE_NONCOPYABLE(AddRuleAction);
 public:
     AddRuleAction(InspectorStyleSheet* styleSheet, const String& selector)
@@ -543,17 +324,17 @@
     {
     }
 
-    virtual bool perform(ExceptionState& exceptionState)
+    virtual bool perform(ExceptionState& exceptionState) OVERRIDE
     {
         return redo(exceptionState);
     }
 
-    virtual bool undo(ExceptionState& exceptionState)
+    virtual bool undo(ExceptionState& exceptionState) OVERRIDE
     {
         return m_styleSheet->deleteRule(m_newId, exceptionState);
     }
 
-    virtual bool redo(ExceptionState& exceptionState)
+    virtual bool redo(ExceptionState& exceptionState) OVERRIDE
     {
         CSSStyleRule* cssStyleRule = m_styleSheet->addRule(m_selector, exceptionState);
         if (exceptionState.hadException())
@@ -604,8 +385,8 @@
     return 0;
 }
 
-InspectorCSSAgent::InspectorCSSAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorDOMAgent* domAgent, InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent)
-    : InspectorBaseAgent<InspectorCSSAgent>("CSS", instrumentingAgents, state)
+InspectorCSSAgent::InspectorCSSAgent(InspectorDOMAgent* domAgent, InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent)
+    : InspectorBaseAgent<InspectorCSSAgent>("CSS")
     , m_frontend(0)
     , m_domAgent(domAgent)
     , m_pageAgent(pageAgent)
@@ -654,18 +435,14 @@
 {
     m_idToInspectorStyleSheet.clear();
     m_cssStyleSheetToInspectorStyleSheet.clear();
+    m_frameToCSSStyleSheets.clear();
     m_nodeToInspectorStyleSheet.clear();
-    m_documentToInspectorStyleSheet.clear();
+    m_documentToViaInspectorStyleSheet.clear();
     resetNonPersistentData();
 }
 
 void InspectorCSSAgent::resetNonPersistentData()
 {
-    m_namedFlowCollectionsRequested.clear();
-    if (m_updateRegionLayoutTask)
-        m_updateRegionLayoutTask->reset();
-    if (m_changeRegionOversetTask)
-        m_changeRegionOversetTask->reset();
     resetPseudoStates();
 }
 
@@ -690,7 +467,7 @@
         Document* document = styleSheet->ownerDocument();
         if (!document)
             continue;
-        Resource* cachedResource = document->fetcher()->cachedResource(url);
+        Resource* cachedResource = document->fetcher()->cachedResource(document->completeURL(url));
         if (cachedResource)
             continue;
         urlsToFetch.add(styleSheet->finalURL());
@@ -711,16 +488,12 @@
         return;
     }
 
-    Vector<InspectorStyleSheet*> styleSheets;
-    collectAllStyleSheets(styleSheets);
-    for (size_t i = 0; i < styleSheets.size(); ++i)
-        m_frontend->styleSheetAdded(styleSheets.at(i)->buildObjectForStyleSheetInfo());
-
-    // More styleSheetAdded events will be generated below.
     m_instrumentingAgents->setInspectorCSSAgent(this);
     Vector<Document*> documents = m_domAgent->documents();
-    for (Vector<Document*>::iterator it = documents.begin(); it != documents.end(); ++it)
-        (*it)->styleEngine()->updateActiveStyleSheets(FullStyleUpdate);
+    for (Vector<Document*>::iterator it = documents.begin(); it != documents.end(); ++it) {
+        Document* document = *it;
+        updateActiveStyleSheetsForDocument(document, InitialFrontendLoad);
+    }
 
     if (callback)
         callback->sendSuccess();
@@ -734,10 +507,12 @@
 
 void InspectorCSSAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
 {
-    if (loader->frame() != frame->page()->mainFrame())
+    if (loader->frame() == frame->page()->mainFrame()) {
+        reset();
         return;
+    }
 
-    reset();
+    updateActiveStyleSheets(frame, Vector<CSSStyleSheet*>(), ExistingFrontendRefresh);
 }
 
 void InspectorCSSAgent::mediaQueryResultChanged()
@@ -746,28 +521,6 @@
         m_frontend->mediaQueryResultChanged();
 }
 
-void InspectorCSSAgent::didCreateNamedFlow(Document* document, NamedFlow* namedFlow)
-{
-    int documentNodeId = documentNodeWithRequestedFlowsId(document);
-    if (!documentNodeId)
-        return;
-
-    ErrorString errorString;
-    m_frontend->namedFlowCreated(buildObjectForNamedFlow(&errorString, namedFlow, documentNodeId));
-}
-
-void InspectorCSSAgent::willRemoveNamedFlow(Document* document, NamedFlow* namedFlow)
-{
-    int documentNodeId = documentNodeWithRequestedFlowsId(document);
-    if (!documentNodeId)
-        return;
-
-    if (m_updateRegionLayoutTask)
-        m_updateRegionLayoutTask->unschedule(namedFlow);
-
-    m_frontend->namedFlowRemoved(documentNodeId, namedFlow->name().string());
-}
-
 void InspectorCSSAgent::willMutateRules()
 {
     ++m_styleSheetsPendingMutation;
@@ -802,105 +555,81 @@
     }
 }
 
-void InspectorCSSAgent::didUpdateRegionLayout(Document* document, NamedFlow* namedFlow)
-{
-    int documentNodeId = documentNodeWithRequestedFlowsId(document);
-    if (!documentNodeId)
-        return;
-
-    if (!m_updateRegionLayoutTask)
-        m_updateRegionLayoutTask = adoptPtr(new UpdateRegionLayoutTask(this));
-    m_updateRegionLayoutTask->scheduleFor(namedFlow, documentNodeId);
-}
-
-void InspectorCSSAgent::regionLayoutUpdated(NamedFlow* namedFlow, int documentNodeId)
-{
-    if (namedFlow->flowState() == NamedFlow::FlowStateNull)
-        return;
-
-    ErrorString errorString;
-    RefPtr<NamedFlow> protector(namedFlow);
-
-    m_frontend->regionLayoutUpdated(buildObjectForNamedFlow(&errorString, namedFlow, documentNodeId));
-}
-
-void InspectorCSSAgent::didChangeRegionOverset(Document* document, NamedFlow* namedFlow)
-{
-    int documentNodeId = documentNodeWithRequestedFlowsId(document);
-    if (!documentNodeId)
-        return;
-
-    if (!m_changeRegionOversetTask)
-        m_changeRegionOversetTask = adoptPtr(new ChangeRegionOversetTask(this));
-    m_changeRegionOversetTask->scheduleFor(namedFlow, documentNodeId);
-}
-
-void InspectorCSSAgent::regionOversetChanged(NamedFlow* namedFlow, int documentNodeId)
-{
-    if (namedFlow->flowState() == NamedFlow::FlowStateNull)
-        return;
-
-    ErrorString errorString;
-    RefPtr<NamedFlow> protector(namedFlow);
-
-    m_frontend->regionOversetChanged(buildObjectForNamedFlow(&errorString, namedFlow, documentNodeId));
-}
-
-void InspectorCSSAgent::activeStyleSheetsUpdated(Document* document, const StyleSheetVector& newSheets)
+void InspectorCSSAgent::activeStyleSheetsUpdated(Document* document)
 {
     if (styleSheetEditInProgress())
         return;
+    updateActiveStyleSheetsForDocument(document, ExistingFrontendRefresh);
+}
 
-    HashSet<CSSStyleSheet*> removedSheets;
-    for (CSSStyleSheetToInspectorStyleSheet::iterator it = m_cssStyleSheetToInspectorStyleSheet.begin(); it != m_cssStyleSheetToInspectorStyleSheet.end(); ++it) {
-        if (it->value->canBind() && (!it->key->ownerDocument() || it->key->ownerDocument() == document))
-            removedSheets.add(it->key);
+void InspectorCSSAgent::updateActiveStyleSheetsForDocument(Document* document, StyleSheetsUpdateType styleSheetsUpdateType)
+{
+    Frame* frame = document->frame();
+    if (!frame)
+        return;
+    Vector<CSSStyleSheet*> newSheetsVector;
+    collectAllDocumentStyleSheets(document, newSheetsVector);
+    updateActiveStyleSheets(frame, newSheetsVector, styleSheetsUpdateType);
+}
+
+void InspectorCSSAgent::updateActiveStyleSheets(Frame* frame, const Vector<CSSStyleSheet*>& allSheetsVector, StyleSheetsUpdateType styleSheetsUpdateType)
+{
+    bool isInitialFrontendLoad = styleSheetsUpdateType == InitialFrontendLoad;
+
+    HashSet<CSSStyleSheet*>* frameCSSStyleSheets = m_frameToCSSStyleSheets.get(frame);
+    if (!frameCSSStyleSheets) {
+        frameCSSStyleSheets = new HashSet<CSSStyleSheet*>();
+        OwnPtr<HashSet<CSSStyleSheet*> > frameCSSStyleSheetsPtr = adoptPtr(frameCSSStyleSheets);
+        m_frameToCSSStyleSheets.set(frame, frameCSSStyleSheetsPtr.release());
     }
 
-    Vector<CSSStyleSheet*> newSheetsVector;
-    for (size_t i = 0, size = newSheets.size(); i < size; ++i) {
-        StyleSheet* newSheet = newSheets.at(i).get();
-        if (newSheet->isCSSStyleSheet()) {
-            StyleSheetAppender appender(newSheetsVector);
-            appender.run(toCSSStyleSheet(newSheet));
+    HashSet<CSSStyleSheet*> removedSheets;
+    for (HashSet<CSSStyleSheet*>::iterator it = frameCSSStyleSheets->begin(); it != frameCSSStyleSheets->end(); ++it)
+        removedSheets.add(*it);
+
+    HashSet<CSSStyleSheet*> addedSheets;
+    for (Vector<CSSStyleSheet*>::const_iterator it = allSheetsVector.begin(); it != allSheetsVector.end(); ++it) {
+        CSSStyleSheet* cssStyleSheet = *it;
+        if (removedSheets.contains(cssStyleSheet)) {
+            removedSheets.remove(cssStyleSheet);
+            if (isInitialFrontendLoad)
+                addedSheets.add(cssStyleSheet);
+        } else {
+            addedSheets.add(cssStyleSheet);
         }
     }
 
-    HashSet<CSSStyleSheet*> addedSheets;
-    for (size_t i = 0; i < newSheetsVector.size(); ++i) {
-        CSSStyleSheet* newCSSSheet = newSheetsVector.at(i);
-        if (removedSheets.contains(newCSSSheet))
-            removedSheets.remove(newCSSSheet);
-        else
-            addedSheets.add(newCSSSheet);
-    }
-
     for (HashSet<CSSStyleSheet*>::iterator it = removedSheets.begin(); it != removedSheets.end(); ++it) {
-        RefPtr<InspectorStyleSheet> inspectorStyleSheet = m_cssStyleSheetToInspectorStyleSheet.get(*it);
+        CSSStyleSheet* cssStyleSheet = *it;
+        RefPtr<InspectorStyleSheet> inspectorStyleSheet = m_cssStyleSheetToInspectorStyleSheet.get(cssStyleSheet);
         ASSERT(inspectorStyleSheet);
+
         if (m_idToInspectorStyleSheet.contains(inspectorStyleSheet->id())) {
             String id = unbindStyleSheet(inspectorStyleSheet.get());
-            if (m_frontend)
+            frameCSSStyleSheets->remove(cssStyleSheet);
+            if (m_frontend && !isInitialFrontendLoad)
                 m_frontend->styleSheetRemoved(id);
         }
     }
 
     for (HashSet<CSSStyleSheet*>::iterator it = addedSheets.begin(); it != addedSheets.end(); ++it) {
-        if (!m_cssStyleSheetToInspectorStyleSheet.contains(*it)) {
-            InspectorStyleSheet* newStyleSheet = bindStyleSheet(*it);
+        CSSStyleSheet* cssStyleSheet = *it;
+        bool isNew = isInitialFrontendLoad || !m_cssStyleSheetToInspectorStyleSheet.contains(cssStyleSheet);
+        if (isNew) {
+            InspectorStyleSheet* newStyleSheet = bindStyleSheet(cssStyleSheet);
+            frameCSSStyleSheets->add(cssStyleSheet);
             if (m_frontend)
                 m_frontend->styleSheetAdded(newStyleSheet->buildObjectForStyleSheetInfo());
         }
     }
+
+    if (frameCSSStyleSheets->isEmpty())
+        m_frameToCSSStyleSheets.remove(frame);
 }
 
 void InspectorCSSAgent::frameDetachedFromParent(Frame* frame)
 {
-    Document* document = frame->document();
-    if (!document)
-        return;
-    StyleSheetVector newSheets;
-    activeStyleSheetsUpdated(document, newSheets);
+    updateActiveStyleSheets(frame, Vector<CSSStyleSheet*>(), ExistingFrontendRefresh);
 }
 
 bool InspectorCSSAgent::forcePseudoState(Element* element, CSSSelector::PseudoType pseudoType)
@@ -953,19 +682,19 @@
 
     // Matched rules.
     StyleResolver& styleResolver = ownerDocument->ensureStyleResolver();
-    // FIXME: This code should not pass DoNotIncludeStyleSheetInCSSOMWrapper. All CSSOMWrappers should always have a parent sheet or rule.
-    RefPtr<CSSRuleList> matchedRules = styleResolver.pseudoCSSRulesForElement(element, elementPseudoId, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
-    matchedCSSRules = buildArrayForMatchedRuleList(matchedRules.get(), styleResolver, originalElement);
+
+    RefPtr<CSSRuleList> matchedRules = styleResolver.pseudoCSSRulesForElement(element, elementPseudoId, StyleResolver::AllCSSRules);
+    matchedCSSRules = buildArrayForMatchedRuleList(matchedRules.get(), originalElement);
 
     // Pseudo elements.
     if (!elementPseudoId && (!includePseudo || *includePseudo)) {
         RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PseudoIdMatches> > pseudoElements = TypeBuilder::Array<TypeBuilder::CSS::PseudoIdMatches>::create();
         for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; pseudoId < AFTER_LAST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
-            RefPtr<CSSRuleList> matchedRules = styleResolver.pseudoCSSRulesForElement(element, pseudoId, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
+            RefPtr<CSSRuleList> matchedRules = styleResolver.pseudoCSSRulesForElement(element, pseudoId, StyleResolver::AllCSSRules);
             if (matchedRules && matchedRules->length()) {
                 RefPtr<TypeBuilder::CSS::PseudoIdMatches> matches = TypeBuilder::CSS::PseudoIdMatches::create()
                     .setPseudoId(static_cast<int>(pseudoId))
-                    .setMatches(buildArrayForMatchedRuleList(matchedRules.get(), styleResolver, element));
+                    .setMatches(buildArrayForMatchedRuleList(matchedRules.get(), element));
                 pseudoElements->addItem(matches.release());
             }
         }
@@ -979,9 +708,9 @@
         Element* parentElement = element->parentElement();
         while (parentElement) {
             StyleResolver& parentStyleResolver = parentElement->ownerDocument()->ensureStyleResolver();
-            RefPtr<CSSRuleList> parentMatchedRules = parentStyleResolver.cssRulesForElement(parentElement, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
+            RefPtr<CSSRuleList> parentMatchedRules = parentStyleResolver.cssRulesForElement(parentElement, StyleResolver::AllCSSRules);
             RefPtr<TypeBuilder::CSS::InheritedStyleEntry> entry = TypeBuilder::CSS::InheritedStyleEntry::create()
-                .setMatchedCSSRules(buildArrayForMatchedRuleList(parentMatchedRules.get(), styleResolver, parentElement));
+                .setMatchedCSSRules(buildArrayForMatchedRuleList(parentMatchedRules.get(), parentElement));
             if (parentElement->style() && parentElement->style()->length()) {
                 InspectorStyleSheetForInlineStyle* styleSheet = asInspectorStyleSheet(parentElement);
                 if (styleSheet)
@@ -1086,15 +815,6 @@
     }
 }
 
-void InspectorCSSAgent::getAllStyleSheets(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSStyleSheetHeader> >& styleInfos)
-{
-    styleInfos = TypeBuilder::Array<TypeBuilder::CSS::CSSStyleSheetHeader>::create();
-    Vector<InspectorStyleSheet*> styleSheets;
-    collectAllStyleSheets(styleSheets);
-    for (size_t i = 0; i < styleSheets.size(); ++i)
-        styleInfos->addItem(styleSheets.at(i)->buildObjectForStyleSheetInfo());
-}
-
 void InspectorCSSAgent::getStyleSheet(ErrorString* errorString, const String& styleSheetId, RefPtr<TypeBuilder::CSS::CSSStyleSheetBody>& styleSheetObject)
 {
     InspectorStyleSheet* inspectorStyleSheet = assertStyleSheetForId(errorString, styleSheetId);
@@ -1106,8 +826,7 @@
         return;
 
     RefPtr<TypeBuilder::CSS::CSSStyleSheetBody> result = TypeBuilder::CSS::CSSStyleSheetBody::create()
-        .setStyleSheetId(styleSheetId)
-        .setRules(buildArrayForRuleList(inspectorStyleSheet->pageStyleSheet()->rules().get(), doc->ensureStyleResolver()));
+        .setRules(buildArrayForRuleList(inspectorStyleSheet->pageStyleSheet()->rules().get()));
 
     bool success = inspectorStyleSheet->fillObjectForStyleSheet(result);
     if (success)
@@ -1126,30 +845,16 @@
 void InspectorCSSAgent::setStyleSheetText(ErrorString* errorString, const String& styleSheetId, const String& text)
 {
     InspectorStyleSheet* inspectorStyleSheet = assertStyleSheetForId(errorString, styleSheetId);
-    if (!inspectorStyleSheet)
+    if (!inspectorStyleSheet) {
+        *errorString = "Style sheet with id " + styleSheetId + " not found.";
         return;
+    }
 
     TrackExceptionState exceptionState;
     m_domAgent->history()->perform(adoptPtr(new SetStyleSheetTextAction(inspectorStyleSheet, text)), exceptionState);
     *errorString = InspectorDOMAgent::toErrorString(exceptionState);
 }
 
-void InspectorCSSAgent::setStyleText(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, const String& text, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
-{
-    InspectorCSSId compoundId(fullStyleId);
-    ASSERT(!compoundId.isEmpty());
-
-    InspectorStyleSheet* inspectorStyleSheet = assertStyleSheetForId(errorString, compoundId.styleSheetId());
-    if (!inspectorStyleSheet)
-        return;
-
-    TrackExceptionState exceptionState;
-    m_domAgent->history()->perform(adoptPtr(new SetStyleTextAction(inspectorStyleSheet, compoundId, text)), exceptionState);
-    if (!exceptionState.hadException())
-        result = inspectorStyleSheet->buildObjectForStyle(inspectorStyleSheet->styleForId(compoundId));
-    *errorString = InspectorDOMAgent::toErrorString(exceptionState);
-}
-
 void InspectorCSSAgent::setPropertyText(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, int propertyIndex, const String& text, bool overwrite, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
 {
     InspectorCSSId compoundId(fullStyleId);
@@ -1166,22 +871,6 @@
     *errorString = InspectorDOMAgent::toErrorString(exceptionState);
 }
 
-void InspectorCSSAgent::toggleProperty(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, int propertyIndex, bool disable, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
-{
-    InspectorCSSId compoundId(fullStyleId);
-    ASSERT(!compoundId.isEmpty());
-
-    InspectorStyleSheet* inspectorStyleSheet = assertStyleSheetForId(errorString, compoundId.styleSheetId());
-    if (!inspectorStyleSheet)
-        return;
-
-    TrackExceptionState exceptionState;
-    bool success = m_domAgent->history()->perform(adoptPtr(new TogglePropertyAction(inspectorStyleSheet, compoundId, propertyIndex, disable)), exceptionState);
-    if (success)
-        result = inspectorStyleSheet->buildObjectForStyle(inspectorStyleSheet->styleForId(compoundId));
-    *errorString = InspectorDOMAgent::toErrorString(exceptionState);
-}
-
 void InspectorCSSAgent::setRuleSelector(ErrorString* errorString, const RefPtr<JSONObject>& fullRuleId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result)
 {
     InspectorCSSId compoundId(fullRuleId);
@@ -1227,30 +916,6 @@
     result = inspectorStyleSheet->buildObjectForRule(rule, buildMediaListChain(rule));
 }
 
-void InspectorCSSAgent::getSupportedCSSProperties(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSPropertyInfo> >& cssProperties)
-{
-    RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSPropertyInfo> > properties = TypeBuilder::Array<TypeBuilder::CSS::CSSPropertyInfo>::create();
-    for (int i = firstCSSProperty; i <= lastCSSProperty; ++i) {
-        CSSPropertyID id = convertToCSSPropertyID(i);
-        RefPtr<TypeBuilder::CSS::CSSPropertyInfo> property = TypeBuilder::CSS::CSSPropertyInfo::create()
-            .setName(getPropertyNameString(id));
-
-        const StylePropertyShorthand& shorthand = shorthandForProperty(id);
-        if (!shorthand.length()) {
-            properties->addItem(property.release());
-            continue;
-        }
-        RefPtr<TypeBuilder::Array<String> > longhands = TypeBuilder::Array<String>::create();
-        for (unsigned j = 0; j < shorthand.length(); ++j) {
-            CSSPropertyID longhandID = shorthand.properties()[j];
-            longhands->addItem(getPropertyNameString(longhandID));
-        }
-        property->setLonghands(longhands);
-        properties->addItem(property.release());
-    }
-    cssProperties = properties.release();
-}
-
 void InspectorCSSAgent::forcePseudoState(ErrorString* errorString, int nodeId, const RefPtr<JSONArray>& forcedPseudoClasses)
 {
     Element* element = m_domAgent->assertElement(errorString, nodeId);
@@ -1268,24 +933,7 @@
         m_nodeIdToForcedPseudoState.set(nodeId, forcedPseudoState);
     else
         m_nodeIdToForcedPseudoState.remove(nodeId);
-    element->ownerDocument()->setNeedsStyleRecalc();
-}
-
-void InspectorCSSAgent::getNamedFlowCollection(ErrorString* errorString, int documentNodeId, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::NamedFlow> >& result)
-{
-    Document* document = m_domAgent->assertDocument(errorString, documentNodeId);
-    if (!document)
-        return;
-
-    m_namedFlowCollectionsRequested.add(documentNodeId);
-
-    Vector<RefPtr<NamedFlow> > namedFlowsVector = document->namedFlows()->namedFlows();
-    RefPtr<TypeBuilder::Array<TypeBuilder::CSS::NamedFlow> > namedFlows = TypeBuilder::Array<TypeBuilder::CSS::NamedFlow>::create();
-
-    for (Vector<RefPtr<NamedFlow> >::iterator it = namedFlowsVector.begin(); it != namedFlowsVector.end(); ++it)
-        namedFlows->addItem(buildObjectForNamedFlow(errorString, it->get(), documentNodeId));
-
-    result = namedFlows.release();
+    element->ownerDocument()->setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 PassRefPtr<TypeBuilder::CSS::CSSMedia> InspectorCSSAgent::buildMediaObject(const MediaList* media, MediaListSource mediaListSource, const String& sourceURL, CSSStyleSheet* parentStyleSheet)
@@ -1425,32 +1073,29 @@
     return toElement(node);
 }
 
-int InspectorCSSAgent::documentNodeWithRequestedFlowsId(Document* document)
-{
-    int documentNodeId = m_domAgent->boundNodeId(document);
-    if (!documentNodeId || !m_namedFlowCollectionsRequested.contains(documentNodeId))
-        return 0;
-
-    return documentNodeId;
-}
-
 void InspectorCSSAgent::collectAllStyleSheets(Vector<InspectorStyleSheet*>& result)
 {
+    Vector<CSSStyleSheet*> cssStyleSheets;
     Vector<Document*> documents = m_domAgent->documents();
-    for (Vector<Document*>::iterator it = documents.begin(); it != documents.end(); ++it) {
-        StyleSheetList* list = (*it)->styleSheets();
-        for (unsigned i = 0; i < list->length(); ++i) {
-            StyleSheet* styleSheet = list->item(i);
-            if (styleSheet->isCSSStyleSheet())
-                collectStyleSheets(toCSSStyleSheet(styleSheet), result);
-        }
+    for (Vector<Document*>::iterator it = documents.begin(); it != documents.end(); ++it)
+        collectAllDocumentStyleSheets(*it, cssStyleSheets);
+    for (Vector<CSSStyleSheet*>::iterator it = cssStyleSheets.begin(); it != cssStyleSheets.end(); ++it)
+        result.append(bindStyleSheet(*it));
+}
+
+void InspectorCSSAgent::collectAllDocumentStyleSheets(Document* document, Vector<CSSStyleSheet*>& result)
+{
+    const Vector<RefPtr<StyleSheet> > activeStyleSheets = document->styleEngine()->activeStyleSheetsForInspector();
+    for (Vector<RefPtr<StyleSheet> >::const_iterator it = activeStyleSheets.begin(); it != activeStyleSheets.end(); ++it) {
+        StyleSheet* styleSheet = (*it).get();
+        if (styleSheet->isCSSStyleSheet())
+            collectStyleSheets(toCSSStyleSheet(styleSheet), result);
     }
 }
 
-void InspectorCSSAgent::collectStyleSheets(CSSStyleSheet* styleSheet, Vector<InspectorStyleSheet*>& result)
+void InspectorCSSAgent::collectStyleSheets(CSSStyleSheet* styleSheet, Vector<CSSStyleSheet*>& result)
 {
-    InspectorStyleSheet* inspectorStyleSheet = bindStyleSheet(styleSheet);
-    result.append(inspectorStyleSheet);
+    result.append(styleSheet);
     for (unsigned i = 0, size = styleSheet->length(); i < size; ++i) {
         CSSRule* rule = styleSheet->item(i);
         if (rule->type() == CSSRule::IMPORT_RULE) {
@@ -1471,7 +1116,7 @@
         m_idToInspectorStyleSheet.set(id, inspectorStyleSheet);
         m_cssStyleSheetToInspectorStyleSheet.set(styleSheet, inspectorStyleSheet);
         if (m_creatingViaInspectorStyleSheet)
-            m_documentToInspectorStyleSheet.add(document, inspectorStyleSheet);
+            m_documentToViaInspectorStyleSheet.add(document, inspectorStyleSheet);
     }
     return inspectorStyleSheet.get();
 }
@@ -1495,7 +1140,7 @@
     if (!document->isHTMLDocument() && !document->isSVGDocument())
         return 0;
 
-    RefPtr<InspectorStyleSheet> inspectorStyleSheet = m_documentToInspectorStyleSheet.get(document);
+    RefPtr<InspectorStyleSheet> inspectorStyleSheet = m_documentToViaInspectorStyleSheet.get(document);
     if (inspectorStyleSheet || !createIfAbsent)
         return inspectorStyleSheet.get();
 
@@ -1517,13 +1162,13 @@
         m_creatingViaInspectorStyleSheet = true;
         targetNode->appendChild(styleElement, exceptionState);
         // At this point the added stylesheet will get bound through the updateActiveStyleSheets() invocation.
-        // We just need to pick the respective InspectorStyleSheet from m_documentToInspectorStyleSheet.
+        // We just need to pick the respective InspectorStyleSheet from m_documentToViaInspectorStyleSheet.
         m_creatingViaInspectorStyleSheet = false;
     }
     if (exceptionState.hadException())
         return 0;
 
-    return m_documentToInspectorStyleSheet.get(document);
+    return m_documentToViaInspectorStyleSheet.get(document);
 }
 
 InspectorStyleSheet* InspectorCSSAgent::assertStyleSheetForId(ErrorString* errorString, const String& styleSheetId)
@@ -1544,7 +1189,7 @@
     TypeBuilder::CSS::StyleSheetOrigin::Enum origin = TypeBuilder::CSS::StyleSheetOrigin::Regular;
     if (pageStyleSheet && !pageStyleSheet->ownerNode() && pageStyleSheet->href().isEmpty())
         origin = TypeBuilder::CSS::StyleSheetOrigin::User_agent;
-    else if (pageStyleSheet && pageStyleSheet->ownerNode() && pageStyleSheet->ownerNode()->nodeName() == "#document")
+    else if (pageStyleSheet && pageStyleSheet->ownerNode() && pageStyleSheet->ownerNode()->isDocumentNode())
         origin = TypeBuilder::CSS::StyleSheetOrigin::User;
     else {
         InspectorStyleSheet* viaInspectorStyleSheetForOwner = viaInspectorStyleSheet(ownerDocument, false);
@@ -1554,23 +1199,22 @@
     return origin;
 }
 
-PassRefPtr<TypeBuilder::CSS::CSSRule> InspectorCSSAgent::buildObjectForRule(CSSStyleRule* rule, StyleResolver& styleResolver)
+PassRefPtr<TypeBuilder::CSS::CSSRule> InspectorCSSAgent::buildObjectForRule(CSSStyleRule* rule)
 {
     if (!rule)
         return 0;
 
-    // CSSRules returned by StyleResolver::cssRulesForElement lack parent pointers since that infomation is not cheaply available.
-    // Since the inspector wants to walk the parent chain, we construct the full wrappers here.
-    // FIXME: This could be factored better. StyleResolver::cssRulesForElement should return a StyleRule vector, not a CSSRuleList.
+    // CSSRules returned by StyleResolver::pseudoCSSRulesForElement lack parent pointers if they are coming from
+    // user agent stylesheets. To work around this issue, we use CSSOM wrapper created by inspector.
     if (!rule->parentStyleSheet()) {
-        rule = styleResolver.inspectorCSSOMWrappers().getWrapperForRuleInSheets(rule->styleRule(), styleResolver.document().styleEngine());
-        if (!rule)
-            return 0;
+        if (!m_inspectorUserAgentStyleSheet)
+            m_inspectorUserAgentStyleSheet = CSSStyleSheet::create(CSSDefaultStyleSheets::instance().defaultStyleSheet());
+        rule->setParentStyleSheet(m_inspectorUserAgentStyleSheet.get());
     }
     return bindStyleSheet(rule->parentStyleSheet())->buildObjectForRule(rule, buildMediaListChain(rule));
 }
 
-PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > InspectorCSSAgent::buildArrayForRuleList(CSSRuleList* ruleList, StyleResolver& styleResolver)
+PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > InspectorCSSAgent::buildArrayForRuleList(CSSRuleList* ruleList)
 {
     RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > result = TypeBuilder::Array<TypeBuilder::CSS::CSSRule>::create();
     if (!ruleList)
@@ -1584,7 +1228,7 @@
         CSSStyleRule* styleRule = asCSSStyleRule(rules.at(i).get());
         if (!styleRule)
             continue;
-        result->addItem(buildObjectForRule(styleRule, styleResolver));
+        result->addItem(buildObjectForRule(styleRule));
     }
 
     return result.release();
@@ -1602,7 +1246,7 @@
     return selectorPseudoId == elementPseudoId;
 }
 
-PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > InspectorCSSAgent::buildArrayForMatchedRuleList(CSSRuleList* ruleList, StyleResolver& styleResolver, Element* element)
+PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > InspectorCSSAgent::buildArrayForMatchedRuleList(CSSRuleList* ruleList, Element* element)
 {
     RefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > result = TypeBuilder::Array<TypeBuilder::CSS::RuleMatch>::create();
     if (!ruleList)
@@ -1610,19 +1254,19 @@
 
     for (unsigned i = 0, size = ruleList->length(); i < size; ++i) {
         CSSStyleRule* rule = asCSSStyleRule(ruleList->item(i));
-        RefPtr<TypeBuilder::CSS::CSSRule> ruleObject = buildObjectForRule(rule, styleResolver);
+        RefPtr<TypeBuilder::CSS::CSSRule> ruleObject = buildObjectForRule(rule);
         if (!ruleObject)
             continue;
         RefPtr<TypeBuilder::Array<int> > matchingSelectors = TypeBuilder::Array<int>::create();
         const CSSSelectorList& selectorList = rule->styleRule()->selectorList();
         long index = 0;
         PseudoId elementPseudoId = element->pseudoId();
-        for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector)) {
+        for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(*selector)) {
             const CSSSelector* firstTagHistorySelector = selector;
             bool matched = false;
             if (elementPseudoId)
                 matched = matchesPseudoElement(selector, elementPseudoId); // Modifies |selector|.
-            matched |= element->webkitMatchesSelector(firstTagHistorySelector->selectorText(), IGNORE_EXCEPTION);
+            matched |= element->matches(firstTagHistorySelector->selectorText(), IGNORE_EXCEPTION);
             if (matched)
                 matchingSelectors->addItem(index);
             ++index;
@@ -1652,65 +1296,10 @@
     return inspectorStyle->buildObjectForStyle();
 }
 
-PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::Region> > InspectorCSSAgent::buildArrayForRegions(ErrorString* errorString, PassRefPtr<NodeList> regionList, int documentNodeId)
-{
-    RefPtr<TypeBuilder::Array<TypeBuilder::CSS::Region> > regions = TypeBuilder::Array<TypeBuilder::CSS::Region>::create();
-
-    for (unsigned i = 0; i < regionList->length(); ++i) {
-        TypeBuilder::CSS::Region::RegionOverset::Enum regionOverset;
-
-        switch (toElement(regionList->item(i))->renderRegion()->regionOversetState()) {
-        case RegionFit:
-            regionOverset = TypeBuilder::CSS::Region::RegionOverset::Fit;
-            break;
-        case RegionEmpty:
-            regionOverset = TypeBuilder::CSS::Region::RegionOverset::Empty;
-            break;
-        case RegionOverset:
-            regionOverset = TypeBuilder::CSS::Region::RegionOverset::Overset;
-            break;
-        case RegionUndefined:
-            continue;
-        default:
-            ASSERT_NOT_REACHED();
-            continue;
-        }
-
-        RefPtr<TypeBuilder::CSS::Region> region = TypeBuilder::CSS::Region::create()
-            .setRegionOverset(regionOverset)
-            // documentNodeId was previously asserted
-            .setNodeId(m_domAgent->pushNodeToFrontend(errorString, documentNodeId, regionList->item(i)));
-
-        regions->addItem(region);
-    }
-
-    return regions.release();
-}
-
-PassRefPtr<TypeBuilder::CSS::NamedFlow> InspectorCSSAgent::buildObjectForNamedFlow(ErrorString* errorString, NamedFlow* webkitNamedFlow, int documentNodeId)
-{
-    RefPtr<NodeList> contentList = webkitNamedFlow->getContent();
-    RefPtr<TypeBuilder::Array<int> > content = TypeBuilder::Array<int>::create();
-
-    for (unsigned i = 0; i < contentList->length(); ++i) {
-        // documentNodeId was previously asserted
-        content->addItem(m_domAgent->pushNodeToFrontend(errorString, documentNodeId, contentList->item(i)));
-    }
-
-    RefPtr<TypeBuilder::CSS::NamedFlow> namedFlow = TypeBuilder::CSS::NamedFlow::create()
-        .setDocumentNodeId(documentNodeId)
-        .setName(webkitNamedFlow->name().string())
-        .setOverset(webkitNamedFlow->overset())
-        .setContent(content)
-        .setRegions(buildArrayForRegions(errorString, webkitNamedFlow->getRegions(), documentNodeId));
-
-    return namedFlow.release();
-}
-
 void InspectorCSSAgent::didRemoveDocument(Document* document)
 {
     if (document)
-        m_documentToInspectorStyleSheet.remove(document);
+        m_documentToViaInspectorStyleSheet.remove(document);
 }
 
 void InspectorCSSAgent::didRemoveDOMNode(Node* node)
@@ -1771,7 +1360,7 @@
 
     m_nodeIdToForcedPseudoState.clear();
     for (HashSet<Document*>::iterator it = documentsToChange.begin(), end = documentsToChange.end(); it != end; ++it)
-        (*it)->setNeedsStyleRecalc();
+        (*it)->setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorCSSAgent.h b/Source/core/inspector/InspectorCSSAgent.h
index aab8854..d213ba3 100644
--- a/Source/core/inspector/InspectorCSSAgent.h
+++ b/Source/core/inspector/InspectorCSSAgent.h
@@ -27,10 +27,10 @@
 
 #include "core/css/CSSSelector.h"
 #include "core/dom/SecurityContext.h"
+#include "core/frame/ContentSecurityPolicy.h"
 #include "core/inspector/InspectorBaseAgent.h"
 #include "core/inspector/InspectorDOMAgent.h"
 #include "core/inspector/InspectorStyleSheet.h"
-#include "core/frame/ContentSecurityPolicy.h"
 #include "platform/JSONValues.h"
 #include "wtf/HashCountedSet.h"
 #include "wtf/HashMap.h"
@@ -42,7 +42,6 @@
 
 namespace WebCore {
 
-class ChangeRegionOversetTask;
 struct CSSParserString;
 class CSSRule;
 class CSSRuleList;
@@ -59,12 +58,8 @@
 class PlatformFontUsage;
 class RenderText;
 class StyleResolver;
-class UpdateRegionLayoutTask;
 
-typedef HashMap<CSSStyleSheet*, RefPtr<InspectorStyleSheet> > CSSStyleSheetToInspectorStyleSheet;
-typedef Vector<RefPtr<StyleSheet> > StyleSheetVector;
-
-class InspectorCSSAgent
+class InspectorCSSAgent FINAL
     : public InspectorBaseAgent<InspectorCSSAgent>
     , public InspectorDOMAgent::DOMListener
     , public InspectorBackendDispatcher::CSSCommandHandler
@@ -78,6 +73,11 @@
         MediaListSourceImportRule
     };
 
+    enum StyleSheetsUpdateType {
+        InitialFrontendLoad = 0,
+        ExistingFrontendRefresh,
+    };
+
     class InlineStyleOverrideScope {
     public:
         InlineStyleOverrideScope(SecurityContext* context)
@@ -97,56 +97,42 @@
 
     static CSSStyleRule* asCSSStyleRule(CSSRule*);
 
-    static PassOwnPtr<InspectorCSSAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorDOMAgent* domAgent, InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent)
+    static PassOwnPtr<InspectorCSSAgent> create(InspectorDOMAgent* domAgent, InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent)
     {
-        return adoptPtr(new InspectorCSSAgent(instrumentingAgents, state, domAgent, pageAgent, resourceAgent));
+        return adoptPtr(new InspectorCSSAgent(domAgent, pageAgent, resourceAgent));
     }
-    ~InspectorCSSAgent();
+    virtual ~InspectorCSSAgent();
 
     bool forcePseudoState(Element*, CSSSelector::PseudoType);
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void discardAgent();
-    virtual void restore();
-    virtual void enable(ErrorString*, PassRefPtr<EnableCallback>);
-    virtual void disable(ErrorString*);
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void discardAgent() OVERRIDE;
+    virtual void restore() OVERRIDE;
+    virtual void enable(ErrorString*, PassRefPtr<EnableCallback>) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
     void reset();
     void didCommitLoad(Frame*, DocumentLoader*);
     void mediaQueryResultChanged();
-    void didCreateNamedFlow(Document*, NamedFlow*);
-    void willRemoveNamedFlow(Document*, NamedFlow*);
     void willMutateRules();
     void didMutateRules(CSSStyleSheet*);
     void willMutateStyle();
     void didMutateStyle(CSSStyleDeclaration*, bool);
 
-private:
-    void regionLayoutUpdated(NamedFlow*, int documentNodeId);
-    void regionOversetChanged(NamedFlow*, int documentNodeId);
-
 public:
-    void didUpdateRegionLayout(Document*, NamedFlow*);
-    void didChangeRegionOverset(Document*, NamedFlow*);
-
-    void activeStyleSheetsUpdated(Document*, const StyleSheetVector& newSheets);
+    void activeStyleSheetsUpdated(Document*);
     void frameDetachedFromParent(Frame*);
 
-    virtual void getComputedStyleForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSComputedStyleProperty> >&);
-    virtual void getPlatformFontsForNode(ErrorString*, int nodeId, String* cssFamilyName, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PlatformFontUsage> >&);
-    virtual void getInlineStylesForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::CSS::CSSStyle>& inlineStyle, RefPtr<TypeBuilder::CSS::CSSStyle>& attributes);
-    virtual void getMatchedStylesForNode(ErrorString*, int nodeId, const bool* includePseudo, const bool* includeInherited, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> >& matchedCSSRules, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PseudoIdMatches> >& pseudoIdMatches, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::InheritedStyleEntry> >& inheritedEntries);
-    virtual void getAllStyleSheets(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSStyleSheetHeader> >& styleSheetInfos);
-    virtual void getStyleSheet(ErrorString*, const String& styleSheetId, RefPtr<TypeBuilder::CSS::CSSStyleSheetBody>& result);
-    virtual void getStyleSheetText(ErrorString*, const String& styleSheetId, String* result);
-    virtual void setStyleSheetText(ErrorString*, const String& styleSheetId, const String& text);
-    virtual void setStyleText(ErrorString*, const RefPtr<JSONObject>& styleId, const String& text, RefPtr<TypeBuilder::CSS::CSSStyle>& result);
-    virtual void setPropertyText(ErrorString*, const RefPtr<JSONObject>& styleId, int propertyIndex, const String& text, bool overwrite, RefPtr<TypeBuilder::CSS::CSSStyle>& result);
-    virtual void toggleProperty(ErrorString*, const RefPtr<JSONObject>& styleId, int propertyIndex, bool disable, RefPtr<TypeBuilder::CSS::CSSStyle>& result);
-    virtual void setRuleSelector(ErrorString*, const RefPtr<JSONObject>& ruleId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result);
-    virtual void addRule(ErrorString*, int contextNodeId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result);
-    virtual void getSupportedCSSProperties(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSPropertyInfo> >& result);
-    virtual void forcePseudoState(ErrorString*, int nodeId, const RefPtr<JSONArray>& forcedPseudoClasses);
-    virtual void getNamedFlowCollection(ErrorString*, int documentNodeId, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::NamedFlow> >& result);
+    virtual void getComputedStyleForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSComputedStyleProperty> >&) OVERRIDE;
+    virtual void getPlatformFontsForNode(ErrorString*, int nodeId, String* cssFamilyName, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PlatformFontUsage> >&) OVERRIDE;
+    virtual void getInlineStylesForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::CSS::CSSStyle>& inlineStyle, RefPtr<TypeBuilder::CSS::CSSStyle>& attributes) OVERRIDE;
+    virtual void getMatchedStylesForNode(ErrorString*, int nodeId, const bool* includePseudo, const bool* includeInherited, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> >& matchedCSSRules, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PseudoIdMatches> >&, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::InheritedStyleEntry> >& inheritedEntries) OVERRIDE;
+    virtual void getStyleSheet(ErrorString*, const String& styleSheetId, RefPtr<TypeBuilder::CSS::CSSStyleSheetBody>& result) OVERRIDE;
+    virtual void getStyleSheetText(ErrorString*, const String& styleSheetId, String* result) OVERRIDE;
+    virtual void setStyleSheetText(ErrorString*, const String& styleSheetId, const String& text) OVERRIDE;
+    virtual void setPropertyText(ErrorString*, const RefPtr<JSONObject>& styleId, int propertyIndex, const String& text, bool overwrite, RefPtr<TypeBuilder::CSS::CSSStyle>& result) OVERRIDE;
+    virtual void setRuleSelector(ErrorString*, const RefPtr<JSONObject>& ruleId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result) OVERRIDE;
+    virtual void addRule(ErrorString*, int contextNodeId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result) OVERRIDE;
+    virtual void forcePseudoState(ErrorString*, int nodeId, const RefPtr<JSONArray>& forcedPseudoClasses) OVERRIDE;
 
     PassRefPtr<TypeBuilder::CSS::CSSMedia> buildMediaObject(const MediaList*, MediaListSource, const String&, CSSStyleSheet*);
     PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSMedia> > buildMediaListChain(CSSRule*);
@@ -154,27 +140,27 @@
 private:
     class StyleSheetAction;
     class SetStyleSheetTextAction;
-    class SetStyleTextAction;
     class SetPropertyTextAction;
-    class TogglePropertyAction;
     class SetRuleSelectorAction;
     class AddRuleAction;
     class EnableResourceClient;
 
-    InspectorCSSAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorDOMAgent*, InspectorPageAgent*, InspectorResourceAgent*);
+    InspectorCSSAgent(InspectorDOMAgent*, InspectorPageAgent*, InspectorResourceAgent*);
 
     typedef HashMap<String, RefPtr<InspectorStyleSheet> > IdToInspectorStyleSheet;
     typedef HashMap<Node*, RefPtr<InspectorStyleSheetForInlineStyle> > NodeToInspectorStyleSheet; // bogus "stylesheets" with elements' inline styles
-    typedef HashMap<RefPtr<Document>, RefPtr<InspectorStyleSheet> > DocumentToViaInspectorStyleSheet; // "via inspector" stylesheets
     typedef HashMap<int, unsigned> NodeIdToForcedPseudoState;
 
     void wasEnabled(PassRefPtr<EnableCallback>);
     void resetNonPersistentData();
     InspectorStyleSheetForInlineStyle* asInspectorStyleSheet(Element* element);
     Element* elementForId(ErrorString*, int nodeId);
-    int documentNodeWithRequestedFlowsId(Document*);
     void collectAllStyleSheets(Vector<InspectorStyleSheet*>&);
-    void collectStyleSheets(CSSStyleSheet*, Vector<InspectorStyleSheet*>&);
+    void collectAllDocumentStyleSheets(Document*, Vector<CSSStyleSheet*>&);
+    void collectStyleSheets(CSSStyleSheet*, Vector<CSSStyleSheet*>&);
+
+    void updateActiveStyleSheetsForDocument(Document*, StyleSheetsUpdateType);
+    void updateActiveStyleSheets(Frame*, const Vector<CSSStyleSheet*>&, StyleSheetsUpdateType);
 
     void collectPlatformFontsForRenderer(RenderText*, HashCountedSet<String>*);
 
@@ -185,17 +171,15 @@
     TypeBuilder::CSS::StyleSheetOrigin::Enum detectOrigin(CSSStyleSheet* pageStyleSheet, Document* ownerDocument);
     bool styleSheetEditInProgress() const { return m_styleSheetsPendingMutation || m_styleDeclarationPendingMutation || m_isSettingStyleSheetText; }
 
-    PassRefPtr<TypeBuilder::CSS::CSSRule> buildObjectForRule(CSSStyleRule*, StyleResolver&);
-    PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > buildArrayForRuleList(CSSRuleList*, StyleResolver&);
-    PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > buildArrayForMatchedRuleList(CSSRuleList*, StyleResolver&, Element*);
+    PassRefPtr<TypeBuilder::CSS::CSSRule> buildObjectForRule(CSSStyleRule*);
+    PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > buildArrayForRuleList(CSSRuleList*);
+    PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > buildArrayForMatchedRuleList(CSSRuleList*, Element*);
     PassRefPtr<TypeBuilder::CSS::CSSStyle> buildObjectForAttributesStyle(Element*);
-    PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::Region> > buildArrayForRegions(ErrorString*, PassRefPtr<NodeList>, int documentNodeId);
-    PassRefPtr<TypeBuilder::CSS::NamedFlow> buildObjectForNamedFlow(ErrorString*, NamedFlow*, int documentNodeId);
 
     // InspectorDOMAgent::DOMListener implementation
-    virtual void didRemoveDocument(Document*);
-    virtual void didRemoveDOMNode(Node*);
-    virtual void didModifyDOMAttr(Element*);
+    virtual void didRemoveDocument(Document*) OVERRIDE;
+    virtual void didRemoveDOMNode(Node*) OVERRIDE;
+    virtual void didModifyDOMAttr(Element*) OVERRIDE;
 
     // InspectorStyleSheet::Listener implementation
     virtual void styleSheetChanged(InspectorStyleSheet*) OVERRIDE;
@@ -210,13 +194,14 @@
     InspectorResourceAgent* m_resourceAgent;
 
     IdToInspectorStyleSheet m_idToInspectorStyleSheet;
-    CSSStyleSheetToInspectorStyleSheet m_cssStyleSheetToInspectorStyleSheet;
+    HashMap<CSSStyleSheet*, RefPtr<InspectorStyleSheet> > m_cssStyleSheetToInspectorStyleSheet;
+    HashMap<Frame*, OwnPtr<HashSet<CSSStyleSheet*> > > m_frameToCSSStyleSheets;
+
     NodeToInspectorStyleSheet m_nodeToInspectorStyleSheet;
-    DocumentToViaInspectorStyleSheet m_documentToInspectorStyleSheet;
+    HashMap<RefPtr<Document>, RefPtr<InspectorStyleSheet> > m_documentToViaInspectorStyleSheet; // "via inspector" stylesheets
     NodeIdToForcedPseudoState m_nodeIdToForcedPseudoState;
-    HashSet<int> m_namedFlowCollectionsRequested;
-    OwnPtr<UpdateRegionLayoutTask> m_updateRegionLayoutTask;
-    OwnPtr<ChangeRegionOversetTask> m_changeRegionOversetTask;
+
+    RefPtr<CSSStyleSheet> m_inspectorUserAgentStyleSheet;
 
     int m_lastStyleSheetId;
     int m_styleSheetsPendingMutation;
@@ -224,10 +209,8 @@
     bool m_creatingViaInspectorStyleSheet;
     bool m_isSettingStyleSheetText;
 
-    friend class ChangeRegionOversetTask;
     friend class EnableResourceClient;
     friend class StyleSheetBinder;
-    friend class UpdateRegionLayoutTask;
 };
 
 
diff --git a/Source/core/inspector/InspectorCanvasAgent.cpp b/Source/core/inspector/InspectorCanvasAgent.cpp
index 5a03d88..d4e8af3 100644
--- a/Source/core/inspector/InspectorCanvasAgent.cpp
+++ b/Source/core/inspector/InspectorCanvasAgent.cpp
@@ -60,8 +60,8 @@
 static const char canvasAgentEnabled[] = "canvasAgentEnabled";
 };
 
-InspectorCanvasAgent::InspectorCanvasAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager)
-    : InspectorBaseAgent<InspectorCanvasAgent>("Canvas", instrumentingAgents, state)
+InspectorCanvasAgent::InspectorCanvasAgent(InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager)
+    : InspectorBaseAgent<InspectorCanvasAgent>("Canvas")
     , m_pageAgent(pageAgent)
     , m_injectedScriptManager(injectedScriptManager)
     , m_frontend(0)
@@ -260,7 +260,7 @@
 
 void InspectorCanvasAgent::findFramesWithUninstrumentedCanvases()
 {
-    class NodeVisitor : public WrappedNodeVisitor {
+    class NodeVisitor FINAL : public WrappedNodeVisitor {
     public:
         NodeVisitor(Page* page, FramesWithUninstrumentedCanvases& result)
             : m_page(page)
diff --git a/Source/core/inspector/InspectorCanvasAgent.h b/Source/core/inspector/InspectorCanvasAgent.h
index 5d30d75..bc7bfa3 100644
--- a/Source/core/inspector/InspectorCanvasAgent.h
+++ b/Source/core/inspector/InspectorCanvasAgent.h
@@ -52,17 +52,17 @@
 
 typedef String ErrorString;
 
-class InspectorCanvasAgent : public InspectorBaseAgent<InspectorCanvasAgent>, public InspectorBackendDispatcher::CanvasCommandHandler {
+class InspectorCanvasAgent FINAL : public InspectorBaseAgent<InspectorCanvasAgent>, public InspectorBackendDispatcher::CanvasCommandHandler {
 public:
-    static PassOwnPtr<InspectorCanvasAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager)
+    static PassOwnPtr<InspectorCanvasAgent> create(InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager)
     {
-        return adoptPtr(new InspectorCanvasAgent(instrumentingAgents, state, pageAgent, injectedScriptManager));
+        return adoptPtr(new InspectorCanvasAgent(pageAgent, injectedScriptManager));
     }
-    ~InspectorCanvasAgent();
+    virtual ~InspectorCanvasAgent();
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
 
     void didCommitLoad(Frame*, DocumentLoader*);
     void frameDetachedFromParent(Frame*);
@@ -73,20 +73,20 @@
     ScriptObject wrapWebGLRenderingContextForInstrumentation(const ScriptObject&);
 
     // Called from the front-end.
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void dropTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&);
-    virtual void hasUninstrumentedCanvases(ErrorString*, bool*);
-    virtual void captureFrame(ErrorString*, const TypeBuilder::Page::FrameId*, TypeBuilder::Canvas::TraceLogId*);
-    virtual void startCapturing(ErrorString*, const TypeBuilder::Page::FrameId*, TypeBuilder::Canvas::TraceLogId*);
-    virtual void stopCapturing(ErrorString*, const TypeBuilder::Canvas::TraceLogId&);
-    virtual void getTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, const int*, const int*, RefPtr<TypeBuilder::Canvas::TraceLog>&);
-    virtual void replayTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, int, RefPtr<TypeBuilder::Canvas::ResourceState>&, double*);
-    virtual void getResourceState(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, const TypeBuilder::Canvas::ResourceId&, RefPtr<TypeBuilder::Canvas::ResourceState>&);
-    virtual void evaluateTraceLogCallArgument(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, int, int, const String*, RefPtr<TypeBuilder::Runtime::RemoteObject>&, RefPtr<TypeBuilder::Canvas::ResourceState>&);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void dropTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&) OVERRIDE;
+    virtual void hasUninstrumentedCanvases(ErrorString*, bool*) OVERRIDE;
+    virtual void captureFrame(ErrorString*, const TypeBuilder::Page::FrameId*, TypeBuilder::Canvas::TraceLogId*) OVERRIDE;
+    virtual void startCapturing(ErrorString*, const TypeBuilder::Page::FrameId*, TypeBuilder::Canvas::TraceLogId*) OVERRIDE;
+    virtual void stopCapturing(ErrorString*, const TypeBuilder::Canvas::TraceLogId&) OVERRIDE;
+    virtual void getTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, const int*, const int*, RefPtr<TypeBuilder::Canvas::TraceLog>&) OVERRIDE;
+    virtual void replayTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, int, RefPtr<TypeBuilder::Canvas::ResourceState>&, double*) OVERRIDE;
+    virtual void getResourceState(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, const TypeBuilder::Canvas::ResourceId&, RefPtr<TypeBuilder::Canvas::ResourceState>&) OVERRIDE;
+    virtual void evaluateTraceLogCallArgument(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, int, int, const String*, RefPtr<TypeBuilder::Runtime::RemoteObject>&, RefPtr<TypeBuilder::Canvas::ResourceState>&) OVERRIDE;
 
 private:
-    InspectorCanvasAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorPageAgent*, InjectedScriptManager*);
+    InspectorCanvasAgent(InspectorPageAgent*, InjectedScriptManager*);
 
     InjectedScriptCanvasModule injectedScriptCanvasModule(ErrorString*, ScriptState*);
     InjectedScriptCanvasModule injectedScriptCanvasModule(ErrorString*, const ScriptObject&);
diff --git a/Source/core/inspector/InspectorConsoleAgent.cpp b/Source/core/inspector/InspectorConsoleAgent.cpp
index 06f9e6a..a64d052 100644
--- a/Source/core/inspector/InspectorConsoleAgent.cpp
+++ b/Source/core/inspector/InspectorConsoleAgent.cpp
@@ -62,8 +62,8 @@
 
 int InspectorConsoleAgent::s_enabledAgentCount = 0;
 
-InspectorConsoleAgent::InspectorConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorTimelineAgent* timelineAgent, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
-    : InspectorBaseAgent<InspectorConsoleAgent>("Console", instrumentingAgents, state)
+InspectorConsoleAgent::InspectorConsoleAgent(InspectorTimelineAgent* timelineAgent, InjectedScriptManager* injectedScriptManager)
+    : InspectorBaseAgent<InspectorConsoleAgent>("Console")
     , m_timelineAgent(timelineAgent)
     , m_injectedScriptManager(injectedScriptManager)
     , m_frontend(0)
@@ -71,7 +71,6 @@
     , m_expiredConsoleMessageCount(0)
     , m_enabled(false)
 {
-    m_instrumentingAgents->setInspectorConsoleAgent(this);
 }
 
 InspectorConsoleAgent::~InspectorConsoleAgent()
@@ -82,6 +81,11 @@
     m_injectedScriptManager = 0;
 }
 
+void InspectorConsoleAgent::init()
+{
+    m_instrumentingAgents->setInspectorConsoleAgent(this);
+}
+
 void InspectorConsoleAgent::enable(ErrorString*)
 {
     if (m_enabled)
@@ -243,7 +247,7 @@
                                         : String(title + '@');
 
     HashCountedSet<String>::AddResult result = m_counts.add(identifier);
-    String message = title + ": " + String::number(result.iterator->value);
+    String message = title + ": " + String::number(result.storedValue->value);
     addMessageToConsole(ConsoleAPIMessageSource, LogMessageType, DebugMessageLevel, message, callStack);
 }
 
@@ -262,10 +266,10 @@
     reset();
 }
 
-void InspectorConsoleAgent::didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*, unsigned long requestIdentifier, ScriptString, const String& url, const String& sendURL, unsigned sendLineNumber)
+void InspectorConsoleAgent::didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*, unsigned long requestIdentifier, ScriptString, const AtomicString& method, const String& url, const String& sendURL, unsigned sendLineNumber)
 {
     if (m_frontend && m_state->getBoolean(ConsoleAgentState::monitoringXHR)) {
-        String message = "XHR finished loading: \"" + url + "\".";
+        String message = "XHR finished loading: " + method + " \"" + url + "\".";
         addMessageToConsole(NetworkMessageSource, LogMessageType, DebugMessageLevel, message, sendURL, sendLineNumber, 0, 0, requestIdentifier);
     }
 }
@@ -280,7 +284,7 @@
     }
 }
 
-void InspectorConsoleAgent::didFailLoading(unsigned long requestIdentifier, DocumentLoader*, const ResourceError& error)
+void InspectorConsoleAgent::didFailLoading(unsigned long requestIdentifier, const ResourceError& error)
 {
     if (error.isCancellation()) // Report failures only.
         return;
@@ -326,10 +330,10 @@
     }
 }
 
-class InspectableHeapObject : public InjectedScriptHost::InspectableObject {
+class InspectableHeapObject FINAL : public InjectedScriptHost::InspectableObject {
 public:
     explicit InspectableHeapObject(int heapObjectId) : m_heapObjectId(heapObjectId) { }
-    virtual ScriptValue get(ScriptState*)
+    virtual ScriptValue get(ScriptState*) OVERRIDE
     {
         return ScriptProfiler::objectByHeapObjectId(m_heapObjectId);
     }
diff --git a/Source/core/inspector/InspectorConsoleAgent.h b/Source/core/inspector/InspectorConsoleAgent.h
index 142728f..81c9b55 100644
--- a/Source/core/inspector/InspectorConsoleAgent.h
+++ b/Source/core/inspector/InspectorConsoleAgent.h
@@ -62,18 +62,19 @@
 class InspectorConsoleAgent : public InspectorBaseAgent<InspectorConsoleAgent>, public InspectorBackendDispatcher::ConsoleCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorConsoleAgent);
 public:
-    InspectorConsoleAgent(InstrumentingAgents*, InspectorTimelineAgent*, InspectorCompositeState*, InjectedScriptManager*);
+    InspectorConsoleAgent(InspectorTimelineAgent*, InjectedScriptManager*);
     virtual ~InspectorConsoleAgent();
 
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void clearMessages(ErrorString*);
+    virtual void init() OVERRIDE;
+    virtual void enable(ErrorString*) OVERRIDE FINAL;
+    virtual void disable(ErrorString*) OVERRIDE FINAL;
+    virtual void clearMessages(ErrorString*) OVERRIDE;
     bool enabled() { return m_enabled; }
     void reset();
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE FINAL;
+    virtual void clearFrontend() OVERRIDE FINAL;
+    virtual void restore() OVERRIDE FINAL;
 
     void addMessageToConsole(MessageSource, MessageType, MessageLevel, const String& message, ScriptState*, PassRefPtr<ScriptArguments>, unsigned long requestIdentifier = 0);
     void addMessageToConsole(MessageSource, MessageType, MessageLevel, const String& message, const String& scriptId, unsigned lineNumber, unsigned columnNumber = 0, ScriptState* = 0, unsigned long requestIdentifier = 0);
@@ -93,14 +94,14 @@
     void frameWindowDiscarded(DOMWindow*);
     void didCommitLoad(Frame*, DocumentLoader*);
 
-    void didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*, unsigned long requestIdentifier, ScriptString, const String& url, const String& sendURL, unsigned sendLineNumber);
+    void didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*, unsigned long requestIdentifier, ScriptString, const AtomicString& method, const String& url, const String& sendURL, unsigned sendLineNumber);
     void didReceiveResourceResponse(Frame*, unsigned long requestIdentifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
-    void didFailLoading(unsigned long requestIdentifier, DocumentLoader*, const ResourceError&);
+    void didFailLoading(unsigned long requestIdentifier, const ResourceError&);
     void addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile>, unsigned lineNumber, const String& sourceURL);
     void addStartProfilingMessageToConsole(const String& title, unsigned lineNumber, const String& sourceURL);
-    virtual void setMonitoringXHREnabled(ErrorString*, bool enabled);
+    virtual void setMonitoringXHREnabled(ErrorString*, bool enabled) OVERRIDE;
     virtual void addInspectedNode(ErrorString*, int nodeId) = 0;
-    virtual void addInspectedHeapObject(ErrorString*, int inspectedHeapObjectId);
+    virtual void addInspectedHeapObject(ErrorString*, int inspectedHeapObjectId) OVERRIDE;
 
     virtual bool isWorkerAgent() = 0;
 
diff --git a/Source/core/inspector/InspectorController.cpp b/Source/core/inspector/InspectorController.cpp
index 505fec3..b4364bf 100644
--- a/Source/core/inspector/InspectorController.cpp
+++ b/Source/core/inspector/InspectorController.cpp
@@ -37,7 +37,6 @@
 #include "core/inspector/IdentifiersFactory.h"
 #include "core/inspector/InjectedScriptHost.h"
 #include "core/inspector/InjectedScriptManager.h"
-#include "core/inspector/InspectorAgent.h"
 #include "core/inspector/InspectorApplicationCacheAgent.h"
 #include "core/inspector/InspectorCSSAgent.h"
 #include "core/inspector/InspectorCanvasAgent.h"
@@ -45,13 +44,11 @@
 #include "core/inspector/InspectorDOMAgent.h"
 #include "core/inspector/InspectorDOMDebuggerAgent.h"
 #include "core/inspector/InspectorDOMStorageAgent.h"
-#include "core/inspector/InspectorDatabaseAgent.h"
 #include "core/inspector/InspectorDebuggerAgent.h"
-#include "core/inspector/InspectorFileSystemAgent.h"
 #include "core/inspector/InspectorFrontendClient.h"
 #include "core/inspector/InspectorHeapProfilerAgent.h"
-#include "core/inspector/InspectorIndexedDBAgent.h"
 #include "core/inspector/InspectorInputAgent.h"
+#include "core/inspector/InspectorInspectorAgent.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/inspector/InspectorLayerTreeAgent.h"
 #include "core/inspector/InspectorMemoryAgent.h"
@@ -67,6 +64,7 @@
 #include "core/inspector/PageDebuggerAgent.h"
 #include "core/inspector/PageRuntimeAgent.h"
 #include "core/page/Page.h"
+#include "core/rendering/RenderLayer.h"
 #include "platform/PlatformMouseEvent.h"
 
 namespace WebCore {
@@ -78,69 +76,35 @@
     , m_overlay(InspectorOverlay::create(page, inspectorClient))
     , m_page(page)
     , m_inspectorClient(inspectorClient)
+    , m_agents(m_instrumentingAgents.get(), m_state.get())
     , m_isUnderTest(false)
+    , m_deferredAgentsInitialized(false)
 {
-    m_agents.append(InspectorAgent::create(page, m_injectedScriptManager.get(), m_instrumentingAgents.get(), m_state.get()));
+    InjectedScriptManager* injectedScriptManager = m_injectedScriptManager.get();
+    InspectorOverlay* overlay = m_overlay.get();
 
-    OwnPtr<InspectorPageAgent> pageAgentPtr(InspectorPageAgent::create(m_instrumentingAgents.get(), page, m_state.get(), m_injectedScriptManager.get(), inspectorClient, m_overlay.get()));
-    InspectorPageAgent* pageAgent = pageAgentPtr.get();
+    m_agents.append(InspectorInspectorAgent::create(m_page, injectedScriptManager));
+
+    OwnPtr<InspectorPageAgent> pageAgentPtr(InspectorPageAgent::create(m_page, injectedScriptManager, inspectorClient, overlay));
+    m_pageAgent = pageAgentPtr.get();
     m_agents.append(pageAgentPtr.release());
 
-    OwnPtr<InspectorDOMAgent> domAgentPtr(InspectorDOMAgent::create(m_instrumentingAgents.get(), pageAgent, m_state.get(), m_injectedScriptManager.get(), m_overlay.get(), inspectorClient));
-    InspectorDOMAgent* domAgent = domAgentPtr.get();
+    OwnPtr<InspectorDOMAgent> domAgentPtr(InspectorDOMAgent::create(m_pageAgent, injectedScriptManager, overlay));
+    m_domAgent = domAgentPtr.get();
     m_agents.append(domAgentPtr.release());
 
-    OwnPtr<InspectorResourceAgent> resourceAgentPtr(InspectorResourceAgent::create(m_instrumentingAgents.get(), pageAgent, inspectorClient, m_state.get()));
-    InspectorResourceAgent* resourceAgent = resourceAgentPtr.get();
-    m_agents.append(resourceAgentPtr.release());
-
-    m_agents.append(InspectorCSSAgent::create(m_instrumentingAgents.get(), m_state.get(), domAgent, pageAgent, resourceAgent));
-
-    m_agents.append(InspectorDatabaseAgent::create(m_instrumentingAgents.get(), m_state.get()));
-
-    m_agents.append(InspectorIndexedDBAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), pageAgent));
-
-    m_agents.append(InspectorFileSystemAgent::create(m_instrumentingAgents.get(), pageAgent, m_state.get()));
-
-    m_agents.append(InspectorDOMStorageAgent::create(m_instrumentingAgents.get(), pageAgent, m_state.get()));
-
-    OwnPtr<InspectorMemoryAgent> memoryAgentPtr(InspectorMemoryAgent::create(m_instrumentingAgents.get(), m_state.get()));
-    m_memoryAgent = memoryAgentPtr.get();
-    m_agents.append(memoryAgentPtr.release());
-
-    OwnPtr<InspectorTimelineAgent> timelineAgentPtr(InspectorTimelineAgent::create(m_instrumentingAgents.get(), pageAgent, m_memoryAgent, domAgent, m_overlay.get(), m_state.get(),
+    OwnPtr<InspectorTimelineAgent> timelineAgentPtr(InspectorTimelineAgent::create(m_pageAgent, m_domAgent, overlay,
         InspectorTimelineAgent::PageInspector, inspectorClient));
     m_timelineAgent = timelineAgentPtr.get();
     m_agents.append(timelineAgentPtr.release());
 
-    m_agents.append(InspectorApplicationCacheAgent::create(m_instrumentingAgents.get(), m_state.get(), pageAgent));
-
     PageScriptDebugServer* pageScriptDebugServer = &PageScriptDebugServer::shared();
 
-    m_agents.append(PageRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), pageScriptDebugServer, page, pageAgent));
+    m_agents.append(PageRuntimeAgent::create(injectedScriptManager, pageScriptDebugServer, m_page, m_pageAgent));
 
-    OwnPtr<InspectorConsoleAgent> consoleAgentPtr(PageConsoleAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), domAgent, m_timelineAgent));
-    InspectorConsoleAgent* consoleAgent = consoleAgentPtr.get();
-    m_agents.append(consoleAgentPtr.release());
+    m_agents.append(PageConsoleAgent::create(injectedScriptManager, m_domAgent, m_timelineAgent));
 
-    OwnPtr<InspectorDebuggerAgent> debuggerAgentPtr(PageDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), pageScriptDebugServer, pageAgent, m_injectedScriptManager.get(), m_overlay.get()));
-    InspectorDebuggerAgent* debuggerAgent = debuggerAgentPtr.get();
-    m_agents.append(debuggerAgentPtr.release());
-
-    m_agents.append(InspectorDOMDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), domAgent, debuggerAgent));
-
-    m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent, m_state.get(), m_injectedScriptManager.get(), m_overlay.get()));
-
-    m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()));
-
-
-    m_agents.append(InspectorWorkerAgent::create(m_instrumentingAgents.get(), m_state.get()));
-
-    m_agents.append(InspectorCanvasAgent::create(m_instrumentingAgents.get(), m_state.get(), pageAgent, m_injectedScriptManager.get()));
-
-    m_agents.append(InspectorInputAgent::create(m_instrumentingAgents.get(), m_state.get(), page, inspectorClient));
-
-    m_agents.append(InspectorLayerTreeAgent::create(m_instrumentingAgents.get(), m_state.get(), domAgent, page));
+    m_agents.append(InspectorWorkerAgent::create());
 
     ASSERT_ARG(inspectorClient, inspectorClient);
     m_injectedScriptManager->injectedScriptHost()->init(m_instrumentingAgents.get(), pageScriptDebugServer);
@@ -158,6 +122,56 @@
     return adoptPtr(new InspectorController(page, client));
 }
 
+void InspectorController::setTextAutosizingEnabled(bool enabled)
+{
+    m_pageAgent->setTextAutosizingEnabled(enabled);
+}
+
+void InspectorController::setDeviceScaleAdjustment(float deviceScaleAdjustment)
+{
+    m_pageAgent->setDeviceScaleAdjustment(deviceScaleAdjustment);
+}
+
+void InspectorController::initializeDeferredAgents()
+{
+    if (m_deferredAgentsInitialized)
+        return;
+    m_deferredAgentsInitialized = true;
+
+    InjectedScriptManager* injectedScriptManager = m_injectedScriptManager.get();
+    InspectorOverlay* overlay = m_overlay.get();
+
+    OwnPtr<InspectorResourceAgent> resourceAgentPtr(InspectorResourceAgent::create(m_pageAgent, m_inspectorClient));
+    InspectorResourceAgent* resourceAgent = resourceAgentPtr.get();
+    m_agents.append(resourceAgentPtr.release());
+
+    m_agents.append(InspectorCSSAgent::create(m_domAgent, m_pageAgent, resourceAgent));
+
+    m_agents.append(InspectorDOMStorageAgent::create(m_pageAgent));
+
+    m_agents.append(InspectorMemoryAgent::create());
+
+    m_agents.append(InspectorApplicationCacheAgent::create(m_pageAgent));
+
+    PageScriptDebugServer* pageScriptDebugServer = &PageScriptDebugServer::shared();
+
+    OwnPtr<InspectorDebuggerAgent> debuggerAgentPtr(PageDebuggerAgent::create(pageScriptDebugServer, m_pageAgent, injectedScriptManager, overlay));
+    InspectorDebuggerAgent* debuggerAgent = debuggerAgentPtr.get();
+    m_agents.append(debuggerAgentPtr.release());
+
+    m_agents.append(InspectorDOMDebuggerAgent::create(m_domAgent, debuggerAgent));
+
+    m_agents.append(InspectorProfilerAgent::create(injectedScriptManager, overlay));
+
+    m_agents.append(InspectorHeapProfilerAgent::create(injectedScriptManager));
+
+    m_agents.append(InspectorCanvasAgent::create(m_pageAgent, injectedScriptManager));
+
+    m_agents.append(InspectorInputAgent::create(m_page, m_inspectorClient));
+
+    m_agents.append(InspectorLayerTreeAgent::create(m_domAgent, m_page));
+}
+
 void InspectorController::inspectedPageDestroyed()
 {
     disconnectFrontend();
@@ -166,16 +180,19 @@
     m_page = 0;
 }
 
+void InspectorController::registerModuleAgent(PassOwnPtr<InspectorAgent> agent)
+{
+    m_moduleAgents.append(agent.get());
+    m_agents.append(agent);
+}
+
 void InspectorController::setInspectorFrontendClient(PassOwnPtr<InspectorFrontendClient> inspectorFrontendClient)
 {
     m_inspectorFrontendClient = inspectorFrontendClient;
 }
 
-void InspectorController::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world)
+void InspectorController::didClearWindowObjectInMainWorld(Frame* frame)
 {
-    if (world != mainThreadNormalWorld())
-        return;
-
     // If the page is supposed to serve as InspectorFrontend notify inspector frontend
     // client that it's cleared so that the client can expose inspector bindings.
     if (m_inspectorFrontendClient && frame == m_page->mainFrame())
@@ -186,6 +203,8 @@
 {
     ASSERT(frontendChannel);
 
+    initializeDeferredAgents();
+
     m_inspectorFrontend = adoptPtr(new InspectorFrontend(frontendChannel));
     // We can reconnect to existing front-end -> unmute state.
     m_state->unmute();
@@ -263,12 +282,14 @@
 void InspectorController::evaluateForTestInFrontend(long callId, const String& script)
 {
     m_isUnderTest = true;
-    if (InspectorAgent* inspectorAgent = m_instrumentingAgents->inspectorAgent())
+    if (InspectorInspectorAgent* inspectorAgent = m_instrumentingAgents->inspectorInspectorAgent())
         inspectorAgent->evaluateForTestInFrontend(callId, script);
 }
 
 void InspectorController::drawHighlight(GraphicsContext& context) const
 {
+    // https://code.google.com/p/chromium/issues/detail?id=343757
+    DisableCompositingQueryAsserts disabler;
     m_overlay->paint(context);
 }
 
@@ -299,7 +320,7 @@
 
 void InspectorController::setInjectedScriptForOrigin(const String& origin, const String& source)
 {
-    if (InspectorAgent* inspectorAgent = m_instrumentingAgents->inspectorAgent())
+    if (InspectorInspectorAgent* inspectorAgent = m_instrumentingAgents->inspectorInspectorAgent())
         inspectorAgent->setInjectedScriptForOrigin(origin, source);
 }
 
@@ -405,6 +426,13 @@
         domDebuggerAgent->didProcessTask();
 }
 
+void InspectorController::didCommitLoadForMainFrame()
+{
+    Vector<InspectorAgent*> agents = m_moduleAgents;
+    for (size_t i = 0; i < agents.size(); i++)
+        agents[i]->didCommitLoadForMainFrame();
+}
+
 void InspectorController::didBeginFrame(int frameId)
 {
     if (InspectorTimelineAgent* timelineAgent = m_instrumentingAgents->inspectorTimelineAgent())
@@ -437,4 +465,10 @@
         timelineAgent->processGPUEvent(InspectorTimelineAgent::GPUEvent(timestamp, phase, foreign, usedGPUMemoryBytes));
 }
 
+void InspectorController::scriptsEnabled(bool  enabled)
+{
+    if (InspectorPageAgent* pageAgent = m_instrumentingAgents->inspectorPageAgent())
+        pageAgent->scriptsEnabled(enabled);
+}
+
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorController.h b/Source/core/inspector/InspectorController.h
index f8e9af7..9540292 100644
--- a/Source/core/inspector/InspectorController.h
+++ b/Source/core/inspector/InspectorController.h
@@ -35,6 +35,7 @@
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
+#include "wtf/Vector.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -44,11 +45,13 @@
 class GraphicsContext;
 class InjectedScriptManager;
 class InspectorBackendDispatcher;
+class InspectorAgent;
 class InspectorClient;
+class InspectorDOMAgent;
 class InspectorFrontend;
 class InspectorFrontendChannel;
 class InspectorFrontendClient;
-class InspectorMemoryAgent;
+class InspectorPageAgent;
 class InspectorTimelineAgent;
 class InspectorOverlay;
 class InspectorState;
@@ -60,7 +63,6 @@
 class PlatformKeyboardEvent;
 class PlatformMouseEvent;
 class PlatformTouchEvent;
-class PostWorkerNotificationToFrontendTask;
 class Node;
 
 struct Highlight;
@@ -72,10 +74,16 @@
     ~InspectorController();
 
     static PassOwnPtr<InspectorController> create(Page*, InspectorClient*);
+
+    // Settings overrides.
+    void setTextAutosizingEnabled(bool);
+    void setDeviceScaleAdjustment(float);
+
     void inspectedPageDestroyed();
+    void registerModuleAgent(PassOwnPtr<InspectorAgent>);
 
     void setInspectorFrontendClient(PassOwnPtr<InspectorFrontendClient>);
-    void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
+    void didClearWindowObjectInMainWorld(Frame*);
     void setInjectedScriptForOrigin(const String& origin, const String& source);
 
     void dispatchMessageFromFrontend(const String& message);
@@ -112,6 +120,7 @@
     void willProcessTask();
     void didProcessTask();
 
+    void didCommitLoadForMainFrame();
     void didBeginFrame(int frameId);
     void didCancelFrame();
     void willComposite();
@@ -119,10 +128,13 @@
 
     void processGPUEvent(double timestamp, int phase, bool foreign, size_t usedGPUMemoryBytes);
 
+    void scriptsEnabled(bool);
+
 private:
     InspectorController(Page*, InspectorClient*);
 
-    friend class PostWorkerNotificationToFrontendTask;
+    void initializeDeferredAgents();
+
     friend InstrumentingAgents* instrumentationForPage(Page*);
 
     RefPtr<InstrumentingAgents> m_instrumentingAgents;
@@ -130,7 +142,8 @@
     OwnPtr<InspectorCompositeState> m_state;
     OwnPtr<InspectorOverlay> m_overlay;
 
-    InspectorMemoryAgent* m_memoryAgent;
+    InspectorDOMAgent* m_domAgent;
+    InspectorPageAgent* m_pageAgent;
     InspectorTimelineAgent* m_timelineAgent;
 
     RefPtr<InspectorBackendDispatcher> m_inspectorBackendDispatcher;
@@ -139,7 +152,9 @@
     Page* m_page;
     InspectorClient* m_inspectorClient;
     InspectorAgentRegistry m_agents;
+    Vector<InspectorAgent*> m_moduleAgents;
     bool m_isUnderTest;
+    bool m_deferredAgentsInitialized;
 };
 
 }
diff --git a/Source/core/inspector/InspectorDOMAgent.cpp b/Source/core/inspector/InspectorDOMAgent.cpp
index 8637e7a..4dd5f42 100644
--- a/Source/core/inspector/InspectorDOMAgent.cpp
+++ b/Source/core/inspector/InspectorDOMAgent.cpp
@@ -55,7 +55,9 @@
 #include "core/fileapi/File.h"
 #include "core/fileapi/FileList.h"
 #include "core/html/HTMLFrameOwnerElement.h"
+#include "core/html/HTMLImportChild.h"
 #include "core/html/HTMLInputElement.h"
+#include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLTemplateElement.h"
 #include "core/inspector/DOMEditor.h"
 #include "core/inspector/DOMPatchSupport.h"
@@ -222,12 +224,11 @@
     return "";
 }
 
-InspectorDOMAgent::InspectorDOMAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay, InspectorClient* client)
-    : InspectorBaseAgent<InspectorDOMAgent>("DOM", instrumentingAgents, inspectorState)
+InspectorDOMAgent::InspectorDOMAgent(InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
+    : InspectorBaseAgent<InspectorDOMAgent>("DOM")
     , m_pageAgent(pageAgent)
     , m_injectedScriptManager(injectedScriptManager)
     , m_overlay(overlay)
-    , m_client(client)
     , m_frontend(0)
     , m_domListener(0)
     , m_lastNodeId(1)
@@ -361,6 +362,12 @@
             unbind(element->pseudoElement(BEFORE), nodesMap);
         if (element->pseudoElement(AFTER))
             unbind(element->pseudoElement(AFTER), nodesMap);
+
+        if (element->hasTagName(HTMLNames::linkTag)) {
+            HTMLLinkElement* linkElement = toHTMLLinkElement(element);
+            if (linkElement->isImport() && linkElement->import())
+                unbind(linkElement->import(), nodesMap);
+        }
     }
 
     nodesMap->remove(node);
@@ -559,11 +566,11 @@
 {
     *elementId = 0;
     Node* node = assertNode(errorString, nodeId);
-    if (!node)
+    if (!node || !node->isContainerNode())
         return;
 
     TrackExceptionState exceptionState;
-    RefPtr<Element> element = node->querySelector(selectors, exceptionState);
+    RefPtr<Element> element = toContainerNode(node)->querySelector(AtomicString(selectors), exceptionState);
     if (exceptionState.hadException()) {
         *errorString = "DOM Error while querying";
         return;
@@ -576,11 +583,11 @@
 void InspectorDOMAgent::querySelectorAll(ErrorString* errorString, int nodeId, const String& selectors, RefPtr<TypeBuilder::Array<int> >& result)
 {
     Node* node = assertNode(errorString, nodeId);
-    if (!node)
+    if (!node || !node->isContainerNode())
         return;
 
     TrackExceptionState exceptionState;
-    RefPtr<NodeList> nodes = node->querySelectorAll(selectors, exceptionState);
+    RefPtr<NodeList> nodes = toContainerNode(node)->querySelectorAll(AtomicString(selectors), exceptionState);
     if (exceptionState.hadException()) {
         *errorString = "DOM Error while querying";
         return;
@@ -696,9 +703,9 @@
     bool shouldIgnoreCase = element->document().isHTMLDocument() && element->isHTMLElement();
     // Not all elements can represent the context (i.e. IFRAME), hence using document.body.
     if (shouldIgnoreCase && element->document().body())
-        fragment->parseHTML(markup, element->document().body(), DisallowScriptingContent);
+        fragment->parseHTML(markup, element->document().body(), AllowScriptingContent);
     else
-        fragment->parseXML(markup, 0, DisallowScriptingContent);
+        fragment->parseXML(markup, 0, AllowScriptingContent);
 
     Element* parsedElement = fragment->firstChild() && fragment->firstChild()->isElementNode() ? toElement(fragment->firstChild()) : 0;
     if (!parsedElement) {
@@ -763,7 +770,7 @@
         return;
 
     TrackExceptionState exceptionState;
-    RefPtr<Element> newElem = oldNode->document().createElement(tagName, exceptionState);
+    RefPtr<Element> newElem = oldNode->document().createElement(AtomicString(tagName), exceptionState);
     if (exceptionState.hadException())
         return;
 
@@ -812,7 +819,7 @@
         return;
 
     Document* document = node->isDocumentNode() ? toDocument(node) : node->ownerDocument();
-    if (!document || (!document->isHTMLDocument() && !document->isXHTMLDocument() && !document->isSVGDocument())) {
+    if (!document || (!document->isHTMLDocument() && !document->isXMLDocument())) {
         *errorString = "Not an HTML/XML document";
         return;
     }
@@ -863,8 +870,11 @@
         const EventListenerVector& vector = info.eventListenerVector;
         for (size_t j = 0; j < vector.size(); ++j) {
             const RegisteredEventListener& listener = vector[j];
-            if (listener.useCapture)
-                listenersArray->addItem(buildObjectForEventListener(listener, info.eventType, info.node, objectGroup));
+            if (listener.useCapture) {
+                RefPtr<TypeBuilder::DOM::EventListener> listenerObject = buildObjectForEventListener(listener, info.eventType, info.eventTarget->toNode(), objectGroup);
+                if (listenerObject)
+                    listenersArray->addItem(listenerObject);
+            }
         }
     }
 
@@ -874,31 +884,30 @@
         const EventListenerVector& vector = info.eventListenerVector;
         for (size_t j = 0; j < vector.size(); ++j) {
             const RegisteredEventListener& listener = vector[j];
-            if (!listener.useCapture)
-                listenersArray->addItem(buildObjectForEventListener(listener, info.eventType, info.node, objectGroup));
+            if (!listener.useCapture) {
+                RefPtr<TypeBuilder::DOM::EventListener> listenerObject = buildObjectForEventListener(listener, info.eventType, info.eventTarget->toNode(), objectGroup);
+                if (listenerObject)
+                    listenersArray->addItem(listenerObject);
+            }
         }
     }
 }
 
-void InspectorDOMAgent::getEventListeners(Node* node, Vector<EventListenerInfo>& eventInformation, bool includeAncestors)
+void InspectorDOMAgent::getEventListeners(EventTarget* target, Vector<EventListenerInfo>& eventInformation, bool includeAncestors)
 {
     // The Node's Ancestors including self.
-    Vector<Node*> ancestors;
-    // Push this node as the firs element.
-    ancestors.append(node);
+    Vector<EventTarget*> ancestors;
+    ancestors.append(target);
     if (includeAncestors) {
-        for (ContainerNode* ancestor = node->parentOrShadowHostNode(); ancestor; ancestor = ancestor->parentOrShadowHostNode())
+        Node* node = target->toNode();
+        for (ContainerNode* ancestor = node ? node->parentOrShadowHostNode() : 0; ancestor; ancestor = ancestor->parentOrShadowHostNode())
             ancestors.append(ancestor);
     }
 
     // Nodes and their Listeners for the concerned event types (order is top to bottom)
     for (size_t i = ancestors.size(); i; --i) {
-        Node* ancestor = ancestors[i - 1];
-        EventTargetData* d = ancestor->eventTargetData();
-        if (!d)
-            continue;
-        // Get the list of event types this Node is concerned with
-        Vector<AtomicString> eventTypes = d->eventListenerMap.eventTypes();
+        EventTarget* ancestor = ancestors[i - 1];
+        Vector<AtomicString> eventTypes = ancestor->eventTypes();
         for (size_t j = 0; j < eventTypes.size(); ++j) {
             AtomicString& type = eventTypes[j];
             const EventListenerVector& listeners = ancestor->getEventListeners(type);
@@ -1019,7 +1028,7 @@
         for (Vector<Document*>::iterator it = docs.begin(); it != docs.end(); ++it) {
             Document* document = *it;
             TrackExceptionState exceptionState;
-            RefPtr<NodeList> nodeList = document->querySelectorAll(whitespaceTrimmedQuery, exceptionState);
+            RefPtr<NodeList> nodeList = document->querySelectorAll(AtomicString(whitespaceTrimmedQuery), exceptionState);
             if (exceptionState.hadException() || !nodeList)
                 continue;
 
@@ -1030,12 +1039,12 @@
     }
 
     *searchId = IdentifiersFactory::createIdentifier();
-    SearchResults::iterator resultsIt = m_searchResults.add(*searchId, Vector<RefPtr<Node> >()).iterator;
+    Vector<RefPtr<Node> >* resultsIt = &m_searchResults.add(*searchId, Vector<RefPtr<Node> >()).storedValue->value;
 
     for (ListHashSet<Node*>::iterator it = resultCollector.begin(); it != resultCollector.end(); ++it)
-        resultsIt->value.append(*it);
+        resultsIt->append(*it);
 
-    *resultCount = resultsIt->value.size();
+    *resultCount = resultsIt->size();
 }
 
 void InspectorDOMAgent::getSearchResults(ErrorString* errorString, const String& searchId, int fromIndex, int toIndex, RefPtr<TypeBuilder::Array<int> >& nodeIds)
@@ -1299,6 +1308,8 @@
     Element* element = assertElement(errorString, nodeId);
     if (!element)
         return;
+
+    element->document().updateLayoutIgnorePendingStylesheets();
     if (!element->isFocusable()) {
         *errorString = "Element is not focusable";
         return;
@@ -1456,10 +1467,8 @@
     case Node::COMMENT_NODE:
     case Node::CDATA_SECTION_NODE:
         nodeValue = node->nodeValue();
-        if (nodeValue.length() > maxTextSize) {
-            nodeValue = nodeValue.left(maxTextSize);
-            nodeValue.append(ellipsisUChar);
-        }
+        if (nodeValue.length() > maxTextSize)
+            nodeValue = nodeValue.left(maxTextSize) + ellipsisUChar;
         break;
     case Node::ATTRIBUTE_NODE:
         localName = node->localName();
@@ -1484,6 +1493,7 @@
     if (node->isElementNode()) {
         Element* element = toElement(node);
         value->setAttributes(buildArrayForElementAttributes(element));
+
         if (node->isFrameOwnerElement()) {
             HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(node);
             if (Frame* frame = frameOwner->contentFrame())
@@ -1501,6 +1511,13 @@
             forcePushChildren = true;
         }
 
+        if (element->hasTagName(linkTag)) {
+            HTMLLinkElement* linkElement = toHTMLLinkElement(element);
+            if (linkElement->isImport() && linkElement->import() && innerParentNode(linkElement->import()) == linkElement)
+                value->setImportedDocument(buildObjectForNode(linkElement->import(), 0, nodesMap));
+            forcePushChildren = true;
+        }
+
         if (element->hasTagName(templateTag)) {
             value->setTemplateContent(buildObjectForNode(toHTMLTemplateElement(element)->content(), 0, nodesMap));
             forcePushChildren = true;
@@ -1527,7 +1544,7 @@
         value->setDocumentURL(documentURLString(document));
         value->setBaseURL(documentBaseURLString(document));
         value->setXmlVersion(document->xmlVersion());
-    } else if (node->nodeType() == Node::DOCUMENT_TYPE_NODE) {
+    } else if (node->isDocumentTypeNode()) {
         DocumentType* docType = toDocumentType(node);
         value->setPublicId(docType->publicId());
         value->setSystemId(docType->systemId());
@@ -1596,13 +1613,23 @@
 PassRefPtr<TypeBuilder::DOM::EventListener> InspectorDOMAgent::buildObjectForEventListener(const RegisteredEventListener& registeredEventListener, const AtomicString& eventType, Node* node, const String* objectGroupId)
 {
     RefPtr<EventListener> eventListener = registeredEventListener.listener;
+    String sourceName;
+    String scriptId;
+    int lineNumber;
+    if (!eventListenerHandlerLocation(&node->document(), eventListener.get(), sourceName, scriptId, lineNumber))
+        return 0;
+
     Document& document = node->document();
+    RefPtr<TypeBuilder::Debugger::Location> location = TypeBuilder::Debugger::Location::create()
+        .setScriptId(scriptId)
+        .setLineNumber(lineNumber);
     RefPtr<TypeBuilder::DOM::EventListener> value = TypeBuilder::DOM::EventListener::create()
         .setType(eventType)
         .setUseCapture(registeredEventListener.useCapture)
         .setIsAttribute(eventListener->isAttribute())
         .setNodeId(pushNodePathToFrontend(node))
-        .setHandlerBody(eventListenerHandlerBody(&document, eventListener.get()));
+        .setHandlerBody(eventListenerHandlerBody(&document, eventListener.get()))
+        .setLocation(location);
     if (objectGroupId) {
         ScriptValue functionValue = eventListenerHandler(&document, eventListener.get());
         if (!functionValue.hasNoValue()) {
@@ -1619,17 +1646,8 @@
             }
         }
     }
-    String sourceName;
-    String scriptId;
-    int lineNumber;
-    if (eventListenerHandlerLocation(&node->document(), eventListener.get(), sourceName, scriptId, lineNumber)) {
-        RefPtr<TypeBuilder::Debugger::Location> location = TypeBuilder::Debugger::Location::create()
-            .setScriptId(scriptId)
-            .setLineNumber(lineNumber);
-        value->setLocation(location);
-        if (!sourceName.isEmpty())
-            value->setSourceName(sourceName);
-    }
+    if (!sourceName.isEmpty())
+        value->setSourceName(sourceName);
     return value.release();
 }
 
@@ -1685,6 +1703,9 @@
 {
     if (node->isDocumentNode()) {
         Document* document = toDocument(node);
+        HTMLImportChild* importChild = toHTMLImportChild(document->import());
+        if (importChild)
+            return importChild->link();
         return document->ownerElement();
     }
     return node->parentOrShadowHostNode();
@@ -1698,7 +1719,7 @@
 
 void InspectorDOMAgent::domContentLoadedEventFired(Frame* frame)
 {
-    if (frame->page()->mainFrame() != frame)
+    if (!frame->isMainFrame())
         return;
 
     // Re-push document once it is loaded.
@@ -1730,6 +1751,9 @@
 
 void InspectorDOMAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
 {
+    // FIXME: If "frame" is always guarenteed to be in the same Page as loader->frame()
+    // then all we need to check here is loader->frame()->isMainFrame()
+    // and we don't need "frame" at all.
     Frame* mainFrame = frame->page()->mainFrame();
     if (loader->frame() != mainFrame) {
         invalidateFrameOwnerElement(loader->frame());
@@ -1935,17 +1959,6 @@
     m_frontend->pseudoElementRemoved(parentId, pseudoElementId);
 }
 
-void InspectorDOMAgent::pseudoStateChanged(Node* node)
-{
-    if (!node->isElementNode())
-        return;
-
-    int nodeId = m_documentNodeToIdMap.get(node);
-    if (!nodeId)
-        return;
-    m_frontend->pseudoStateChanged(nodeId);
-}
-
 Node* InspectorDOMAgent::nodeForPath(const String& path)
 {
     // The path is of form "1,HTML,2,BODY,1,DIV"
diff --git a/Source/core/inspector/InspectorDOMAgent.h b/Source/core/inspector/InspectorDOMAgent.h
index 860fdb3..a5cefac 100644
--- a/Source/core/inspector/InspectorDOMAgent.h
+++ b/Source/core/inspector/InspectorDOMAgent.h
@@ -51,8 +51,8 @@
 class DOMEditor;
 class Document;
 class Element;
+class EventTarget;
 class ExceptionState;
-class InspectorClient;
 class InspectorFrontend;
 class InspectorHistory;
 class InspectorOverlay;
@@ -72,19 +72,19 @@
 
 
 struct EventListenerInfo {
-    EventListenerInfo(Node* node, const AtomicString& eventType, const EventListenerVector& eventListenerVector)
-        : node(node)
+    EventListenerInfo(EventTarget* eventTarget, const AtomicString& eventType, const EventListenerVector& eventListenerVector)
+        : eventTarget(eventTarget)
         , eventType(eventType)
         , eventListenerVector(eventListenerVector)
     {
     }
 
-    Node* node;
+    EventTarget* eventTarget;
     const AtomicString eventType;
     const EventListenerVector eventListenerVector;
 };
 
-class InspectorDOMAgent : public InspectorBaseAgent<InspectorDOMAgent>, public InspectorBackendDispatcher::DOMCommandHandler {
+class InspectorDOMAgent FINAL : public InspectorBaseAgent<InspectorDOMAgent>, public InspectorBackendDispatcher::DOMCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorDOMAgent);
 public:
     struct DOMListener {
@@ -96,63 +96,63 @@
         virtual void didModifyDOMAttr(Element*) = 0;
     };
 
-    static PassOwnPtr<InspectorDOMAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay, InspectorClient* client)
+    static PassOwnPtr<InspectorDOMAgent> create(InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
     {
-        return adoptPtr(new InspectorDOMAgent(instrumentingAgents, pageAgent, inspectorState, injectedScriptManager, overlay, client));
+        return adoptPtr(new InspectorDOMAgent(pageAgent, injectedScriptManager, overlay));
     }
 
     static String toErrorString(ExceptionState&);
 
-    ~InspectorDOMAgent();
+    virtual ~InspectorDOMAgent();
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
 
     Vector<Document*> documents();
     void reset();
 
     // Methods called from the frontend for DOM nodes inspection.
-    virtual void querySelector(ErrorString*, int nodeId, const String& selectors, int* elementId);
-    virtual void querySelectorAll(ErrorString*, int nodeId, const String& selectors, RefPtr<TypeBuilder::Array<int> >& result);
-    virtual void getDocument(ErrorString*, RefPtr<TypeBuilder::DOM::Node>& root);
-    virtual void requestChildNodes(ErrorString*, int nodeId, const int* depth);
-    virtual void setAttributeValue(ErrorString*, int elementId, const String& name, const String& value);
-    virtual void setAttributesAsText(ErrorString*, int elementId, const String& text, const String* name);
-    virtual void removeAttribute(ErrorString*, int elementId, const String& name);
-    virtual void removeNode(ErrorString*, int nodeId);
-    virtual void setNodeName(ErrorString*, int nodeId, const String& name, int* newId);
-    virtual void getOuterHTML(ErrorString*, int nodeId, WTF::String* outerHTML);
-    virtual void setOuterHTML(ErrorString*, int nodeId, const String& outerHTML);
-    virtual void setNodeValue(ErrorString*, int nodeId, const String& value);
-    virtual void getEventListenersForNode(ErrorString*, int nodeId, const WTF::String* objectGroup, RefPtr<TypeBuilder::Array<TypeBuilder::DOM::EventListener> >& listenersArray);
-    virtual void performSearch(ErrorString*, const String& whitespaceTrimmedQuery, String* searchId, int* resultCount);
-    virtual void getSearchResults(ErrorString*, const String& searchId, int fromIndex, int toIndex, RefPtr<TypeBuilder::Array<int> >&);
-    virtual void discardSearchResults(ErrorString*, const String& searchId);
-    virtual void resolveNode(ErrorString*, int nodeId, const String* objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& result);
-    virtual void getAttributes(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<String> >& result);
-    virtual void setInspectModeEnabled(ErrorString*, bool enabled, const bool* inspectShadowDOM, const RefPtr<JSONObject>* highlightConfig);
-    virtual void requestNode(ErrorString*, const String& objectId, int* nodeId);
-    virtual void pushNodeByPathToFrontend(ErrorString*, const String& path, int* nodeId);
-    virtual void pushNodeByBackendIdToFrontend(ErrorString*, BackendNodeId, int* nodeId);
-    virtual void releaseBackendNodeIds(ErrorString*, const String& nodeGroup);
-    virtual void hideHighlight(ErrorString*);
-    virtual void highlightRect(ErrorString*, int x, int y, int width, int height, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor);
-    virtual void highlightQuad(ErrorString*, const RefPtr<JSONArray>& quad, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor);
-    virtual void highlightNode(ErrorString*, const RefPtr<JSONObject>& highlightConfig, const int* nodeId, const String* objectId);
-    virtual void highlightFrame(ErrorString*, const String& frameId, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor);
+    virtual void querySelector(ErrorString*, int nodeId, const String& selectors, int* elementId) OVERRIDE;
+    virtual void querySelectorAll(ErrorString*, int nodeId, const String& selectors, RefPtr<TypeBuilder::Array<int> >& result) OVERRIDE;
+    virtual void getDocument(ErrorString*, RefPtr<TypeBuilder::DOM::Node>& root) OVERRIDE;
+    virtual void requestChildNodes(ErrorString*, int nodeId, const int* depth) OVERRIDE;
+    virtual void setAttributeValue(ErrorString*, int elementId, const String& name, const String& value) OVERRIDE;
+    virtual void setAttributesAsText(ErrorString*, int elementId, const String& text, const String* name) OVERRIDE;
+    virtual void removeAttribute(ErrorString*, int elementId, const String& name) OVERRIDE;
+    virtual void removeNode(ErrorString*, int nodeId) OVERRIDE;
+    virtual void setNodeName(ErrorString*, int nodeId, const String& name, int* newId) OVERRIDE;
+    virtual void getOuterHTML(ErrorString*, int nodeId, WTF::String* outerHTML) OVERRIDE;
+    virtual void setOuterHTML(ErrorString*, int nodeId, const String& outerHTML) OVERRIDE;
+    virtual void setNodeValue(ErrorString*, int nodeId, const String& value) OVERRIDE;
+    virtual void getEventListenersForNode(ErrorString*, int nodeId, const WTF::String* objectGroup, RefPtr<TypeBuilder::Array<TypeBuilder::DOM::EventListener> >& listenersArray) OVERRIDE;
+    virtual void performSearch(ErrorString*, const String& whitespaceTrimmedQuery, String* searchId, int* resultCount) OVERRIDE;
+    virtual void getSearchResults(ErrorString*, const String& searchId, int fromIndex, int toIndex, RefPtr<TypeBuilder::Array<int> >&) OVERRIDE;
+    virtual void discardSearchResults(ErrorString*, const String& searchId) OVERRIDE;
+    virtual void resolveNode(ErrorString*, int nodeId, const String* objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& result) OVERRIDE;
+    virtual void getAttributes(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<String> >& result) OVERRIDE;
+    virtual void setInspectModeEnabled(ErrorString*, bool enabled, const bool* inspectShadowDOM, const RefPtr<JSONObject>* highlightConfig) OVERRIDE;
+    virtual void requestNode(ErrorString*, const String& objectId, int* nodeId) OVERRIDE;
+    virtual void pushNodeByPathToFrontend(ErrorString*, const String& path, int* nodeId) OVERRIDE;
+    virtual void pushNodeByBackendIdToFrontend(ErrorString*, BackendNodeId, int* nodeId) OVERRIDE;
+    virtual void releaseBackendNodeIds(ErrorString*, const String& nodeGroup) OVERRIDE;
+    virtual void hideHighlight(ErrorString*) OVERRIDE;
+    virtual void highlightRect(ErrorString*, int x, int y, int width, int height, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor) OVERRIDE;
+    virtual void highlightQuad(ErrorString*, const RefPtr<JSONArray>& quad, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor) OVERRIDE;
+    virtual void highlightNode(ErrorString*, const RefPtr<JSONObject>& highlightConfig, const int* nodeId, const String* objectId) OVERRIDE;
+    virtual void highlightFrame(ErrorString*, const String& frameId, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor) OVERRIDE;
 
-    virtual void moveTo(ErrorString*, int nodeId, int targetNodeId, const int* anchorNodeId, int* newNodeId);
-    virtual void undo(ErrorString*);
-    virtual void redo(ErrorString*);
-    virtual void markUndoableState(ErrorString*);
-    virtual void focus(ErrorString*, int nodeId);
-    virtual void setFileInputFiles(ErrorString*, int nodeId, const RefPtr<JSONArray>& files);
-    virtual void getBoxModel(ErrorString*, int nodeId, RefPtr<TypeBuilder::DOM::BoxModel>&);
-    virtual void getNodeForLocation(ErrorString*, int x, int y, int* nodeId);
-    virtual void getRelayoutBoundary(ErrorString*, int nodeId, int* relayoutBoundaryNodeId);
+    virtual void moveTo(ErrorString*, int nodeId, int targetNodeId, const int* anchorNodeId, int* newNodeId) OVERRIDE;
+    virtual void undo(ErrorString*) OVERRIDE;
+    virtual void redo(ErrorString*) OVERRIDE;
+    virtual void markUndoableState(ErrorString*) OVERRIDE;
+    virtual void focus(ErrorString*, int nodeId) OVERRIDE;
+    virtual void setFileInputFiles(ErrorString*, int nodeId, const RefPtr<JSONArray>& files) OVERRIDE;
+    virtual void getBoxModel(ErrorString*, int nodeId, RefPtr<TypeBuilder::DOM::BoxModel>&) OVERRIDE;
+    virtual void getNodeForLocation(ErrorString*, int x, int y, int* nodeId) OVERRIDE;
+    virtual void getRelayoutBoundary(ErrorString*, int nodeId, int* relayoutBoundaryNodeId) OVERRIDE;
 
-    static void getEventListeners(Node*, Vector<EventListenerInfo>& listenersArray, bool includeAncestors);
+    static void getEventListeners(EventTarget*, Vector<EventListenerInfo>& listenersArray, bool includeAncestors);
 
     // Methods called from the InspectorInstrumentation.
     void setDocument(Document*);
@@ -174,7 +174,6 @@
     void frameDocumentUpdated(Frame*);
     void pseudoElementCreated(PseudoElement*);
     void pseudoElementDestroyed(PseudoElement*);
-    void pseudoStateChanged(Node*);
 
     int pushNodeToFrontend(ErrorString*, int documentNodeId, Node*);
     Node* nodeForId(int nodeId);
@@ -208,7 +207,7 @@
 private:
     enum SearchMode { NotSearching, SearchingForNormal, SearchingForShadow };
 
-    InspectorDOMAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorCompositeState*, InjectedScriptManager*, InspectorOverlay*, InspectorClient*);
+    InspectorDOMAgent(InspectorPageAgent*, InjectedScriptManager*, InspectorOverlay*);
 
     void setSearchingForNode(ErrorString*, SearchMode, JSONObject* highlightConfig);
     PassOwnPtr<HighlightConfig> highlightConfigFromInspectorObject(ErrorString*, JSONObject* highlightInspectorObject);
@@ -250,7 +249,6 @@
     InspectorPageAgent* m_pageAgent;
     InjectedScriptManager* m_injectedScriptManager;
     InspectorOverlay* m_overlay;
-    InspectorClient* m_client;
     InspectorFrontend::DOM* m_frontend;
     DOMListener* m_domListener;
     NodeToIdMap m_documentNodeToIdMap;
diff --git a/Source/core/inspector/InspectorDOMDebuggerAgent.cpp b/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
index 1fe6918..b0fff77 100644
--- a/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
@@ -32,7 +32,6 @@
 #include "core/inspector/InspectorDOMDebuggerAgent.h"
 
 #include "InspectorFrontend.h"
-#include "core/events/Event.h"
 #include "core/inspector/InspectorDOMAgent.h"
 #include "core/inspector/InspectorState.h"
 #include "core/inspector/InstrumentingAgents.h"
@@ -63,6 +62,7 @@
 static const char setTimerEventName[] = "setTimer";
 static const char clearTimerEventName[] = "clearTimer";
 static const char timerFiredEventName[] = "timerFired";
+static const char customElementCallbackName[] = "customElementCallback";
 static const char webglErrorFiredEventName[] = "webglErrorFired";
 static const char webglWarningFiredEventName[] = "webglWarningFired";
 static const char webglErrorNameProperty[] = "webglErrorName";
@@ -73,13 +73,13 @@
 static const char xhrBreakpoints[] = "xhrBreakpoints";
 }
 
-PassOwnPtr<InspectorDOMDebuggerAgent> InspectorDOMDebuggerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, InspectorDOMAgent* domAgent, InspectorDebuggerAgent* debuggerAgent)
+PassOwnPtr<InspectorDOMDebuggerAgent> InspectorDOMDebuggerAgent::create(InspectorDOMAgent* domAgent, InspectorDebuggerAgent* debuggerAgent)
 {
-    return adoptPtr(new InspectorDOMDebuggerAgent(instrumentingAgents, inspectorState, domAgent, debuggerAgent));
+    return adoptPtr(new InspectorDOMDebuggerAgent(domAgent, debuggerAgent));
 }
 
-InspectorDOMDebuggerAgent::InspectorDOMDebuggerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, InspectorDOMAgent* domAgent, InspectorDebuggerAgent* debuggerAgent)
-    : InspectorBaseAgent<InspectorDOMDebuggerAgent>("DOMDebugger", instrumentingAgents, inspectorState)
+InspectorDOMDebuggerAgent::InspectorDOMDebuggerAgent(InspectorDOMAgent* domAgent, InspectorDebuggerAgent* debuggerAgent)
+    : InspectorBaseAgent<InspectorDOMDebuggerAgent>("DOMDebugger")
     , m_domAgent(domAgent)
     , m_debuggerAgent(debuggerAgent)
     , m_pauseInNextEventListener(false)
@@ -405,39 +405,44 @@
     return eventData.release();
 }
 
-void InspectorDOMDebuggerAgent::didInstallTimer(ExecutionContext* context, int timerId, int timeout, bool singleShot)
+void InspectorDOMDebuggerAgent::didInstallTimer(ExecutionContext*, int, int, bool)
 {
     pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, setTimerEventName), true);
 }
 
-void InspectorDOMDebuggerAgent::didRemoveTimer(ExecutionContext* context, int timerId)
+void InspectorDOMDebuggerAgent::didRemoveTimer(ExecutionContext*, int)
 {
     pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, clearTimerEventName), true);
 }
 
-void InspectorDOMDebuggerAgent::willFireTimer(ExecutionContext* context, int timerId)
+void InspectorDOMDebuggerAgent::willFireTimer(ExecutionContext*, int)
 {
     pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, timerFiredEventName), false);
 }
 
-void InspectorDOMDebuggerAgent::didRequestAnimationFrame(Document* document, int callbackId)
+void InspectorDOMDebuggerAgent::didRequestAnimationFrame(Document*, int)
 {
     pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, requestAnimationFrameEventName), true);
 }
 
-void InspectorDOMDebuggerAgent::didCancelAnimationFrame(Document* document, int callbackId)
+void InspectorDOMDebuggerAgent::didCancelAnimationFrame(Document*, int)
 {
     pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, cancelAnimationFrameEventName), true);
 }
 
-void InspectorDOMDebuggerAgent::willFireAnimationFrame(Document* document, int callbackId)
+void InspectorDOMDebuggerAgent::willFireAnimationFrame(Document*, int)
 {
     pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, animationFrameFiredEventName), false);
 }
 
-void InspectorDOMDebuggerAgent::willHandleEvent(Event* event)
+void InspectorDOMDebuggerAgent::willHandleEvent(EventTarget*, const AtomicString& eventType, EventListener*, bool)
 {
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(true, event->type()), false);
+    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(true, eventType), false);
+}
+
+void InspectorDOMDebuggerAgent::willExecuteCustomElementCallback(Element*)
+{
+    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, customElementCallbackName), false);
 }
 
 void InspectorDOMDebuggerAgent::didFireWebGLError(const String& errorName)
diff --git a/Source/core/inspector/InspectorDOMDebuggerAgent.h b/Source/core/inspector/InspectorDOMDebuggerAgent.h
index 2b0b87b..80363c3 100644
--- a/Source/core/inspector/InspectorDOMDebuggerAgent.h
+++ b/Source/core/inspector/InspectorDOMDebuggerAgent.h
@@ -42,7 +42,8 @@
 
 class Document;
 class Element;
-class Event;
+class EventListener;
+class EventTarget;
 class InspectorDOMAgent;
 class InspectorDebuggerAgent;
 class InspectorFrontend;
@@ -52,22 +53,22 @@
 
 typedef String ErrorString;
 
-class InspectorDOMDebuggerAgent : public InspectorBaseAgent<InspectorDOMDebuggerAgent>, public InspectorDebuggerAgent::Listener, public InspectorBackendDispatcher::DOMDebuggerCommandHandler {
+class InspectorDOMDebuggerAgent FINAL : public InspectorBaseAgent<InspectorDOMDebuggerAgent>, public InspectorDebuggerAgent::Listener, public InspectorBackendDispatcher::DOMDebuggerCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorDOMDebuggerAgent);
 public:
-    static PassOwnPtr<InspectorDOMDebuggerAgent> create(InstrumentingAgents*, InspectorCompositeState*, InspectorDOMAgent*, InspectorDebuggerAgent*);
+    static PassOwnPtr<InspectorDOMDebuggerAgent> create(InspectorDOMAgent*, InspectorDebuggerAgent*);
 
     virtual ~InspectorDOMDebuggerAgent();
 
     // DOMDebugger API for InspectorFrontend
-    virtual void setXHRBreakpoint(ErrorString*, const String& url);
-    virtual void removeXHRBreakpoint(ErrorString*, const String& url);
-    virtual void setEventListenerBreakpoint(ErrorString*, const String& eventName);
-    virtual void removeEventListenerBreakpoint(ErrorString*, const String& eventName);
-    virtual void setInstrumentationBreakpoint(ErrorString*, const String& eventName);
-    virtual void removeInstrumentationBreakpoint(ErrorString*, const String& eventName);
-    virtual void setDOMBreakpoint(ErrorString*, int nodeId, const String& type);
-    virtual void removeDOMBreakpoint(ErrorString*, int nodeId, const String& type);
+    virtual void setXHRBreakpoint(ErrorString*, const String& url) OVERRIDE;
+    virtual void removeXHRBreakpoint(ErrorString*, const String& url) OVERRIDE;
+    virtual void setEventListenerBreakpoint(ErrorString*, const String& eventName) OVERRIDE;
+    virtual void removeEventListenerBreakpoint(ErrorString*, const String& eventName) OVERRIDE;
+    virtual void setInstrumentationBreakpoint(ErrorString*, const String& eventName) OVERRIDE;
+    virtual void removeInstrumentationBreakpoint(ErrorString*, const String& eventName) OVERRIDE;
+    virtual void setDOMBreakpoint(ErrorString*, int nodeId, const String& type) OVERRIDE;
+    virtual void removeDOMBreakpoint(ErrorString*, int nodeId, const String& type) OVERRIDE;
 
     // InspectorInstrumentation API
     void willInsertDOMNode(Node* parent);
@@ -83,27 +84,28 @@
     void didRequestAnimationFrame(Document*, int callbackId);
     void didCancelAnimationFrame(Document*, int callbackId);
     void willFireAnimationFrame(Document*, int callbackId);
-    void willHandleEvent(Event*);
+    void willHandleEvent(EventTarget*, const AtomicString& eventType, EventListener*, bool useCapture);
     void didFireWebGLError(const String& errorName);
     void didFireWebGLWarning();
     void didFireWebGLErrorOrWarning(const String& message);
+    void willExecuteCustomElementCallback(Element*);
 
     void didProcessTask();
 
-    virtual void clearFrontend();
-    virtual void discardAgent();
+    virtual void clearFrontend() OVERRIDE;
+    virtual void discardAgent() OVERRIDE;
 
 private:
-    InspectorDOMDebuggerAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorDOMAgent*, InspectorDebuggerAgent*);
+    InspectorDOMDebuggerAgent(InspectorDOMAgent*, InspectorDebuggerAgent*);
 
     void pauseOnNativeEventIfNeeded(PassRefPtr<JSONObject> eventData, bool synchronous);
     PassRefPtr<JSONObject> preparePauseOnNativeEventData(bool isDOMEvent, const String& eventName);
 
     // InspectorDebuggerAgent::Listener implementation.
-    virtual void debuggerWasEnabled();
-    virtual void debuggerWasDisabled();
-    virtual void stepInto();
-    virtual void didPause();
+    virtual void debuggerWasEnabled() OVERRIDE;
+    virtual void debuggerWasDisabled() OVERRIDE;
+    virtual void stepInto() OVERRIDE;
+    virtual void didPause() OVERRIDE;
     void disable();
 
     void descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, JSONObject* description);
diff --git a/Source/core/inspector/InspectorDOMStorageAgent.cpp b/Source/core/inspector/InspectorDOMStorageAgent.cpp
index 19e11e8..5c79088 100644
--- a/Source/core/inspector/InspectorDOMStorageAgent.cpp
+++ b/Source/core/inspector/InspectorDOMStorageAgent.cpp
@@ -68,8 +68,8 @@
     }
 }
 
-InspectorDOMStorageAgent::InspectorDOMStorageAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorCompositeState* state)
-    : InspectorBaseAgent<InspectorDOMStorageAgent>("DOMStorage", instrumentingAgents, state)
+InspectorDOMStorageAgent::InspectorDOMStorageAgent(InspectorPageAgent* pageAgent)
+    : InspectorBaseAgent<InspectorDOMStorageAgent>("DOMStorage")
     , m_pageAgent(pageAgent)
     , m_frontend(0)
 {
@@ -110,7 +110,7 @@
 void InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, const RefPtr<JSONObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > >& items)
 {
     Frame* frame;
-    OwnPtr<StorageArea> storageArea = findStorageArea(errorString, storageId, frame);
+    OwnPtrWillBeRawPtr<StorageArea> storageArea = findStorageArea(errorString, storageId, frame);
     if (!storageArea)
         return;
 
@@ -142,7 +142,7 @@
 void InspectorDOMStorageAgent::setDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key, const String& value)
 {
     Frame* frame;
-    OwnPtr<StorageArea> storageArea = findStorageArea(0, storageId, frame);
+    OwnPtrWillBeRawPtr<StorageArea> storageArea = findStorageArea(0, storageId, frame);
     if (!storageArea) {
         *errorString = "Storage not found";
         return;
@@ -156,7 +156,7 @@
 void InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key)
 {
     Frame* frame;
-    OwnPtr<StorageArea> storageArea = findStorageArea(0, storageId, frame);
+    OwnPtrWillBeRawPtr<StorageArea> storageArea = findStorageArea(0, storageId, frame);
     if (!storageArea) {
         *errorString = "Storage not found";
         return;
@@ -167,18 +167,6 @@
     *errorString = toErrorString(exceptionState);
 }
 
-String InspectorDOMStorageAgent::storageId(Storage* storage)
-{
-    ASSERT(storage);
-    Document* document = storage->frame()->document();
-    ASSERT(document);
-    DOMWindow* window = document->domWindow();
-    ASSERT(window);
-    RefPtr<SecurityOrigin> securityOrigin = document->securityOrigin();
-    bool isLocalStorage = window->optionalLocalStorage() == storage;
-    return storageId(securityOrigin.get(), isLocalStorage)->toJSONString();
-}
-
 PassRefPtr<TypeBuilder::DOMStorage::StorageId> InspectorDOMStorageAgent::storageId(SecurityOrigin* securityOrigin, bool isLocalStorage)
 {
     return TypeBuilder::DOMStorage::StorageId::create()
@@ -203,7 +191,7 @@
         m_frontend->domstorage()->domStorageItemUpdated(id, key, oldValue, newValue);
 }
 
-PassOwnPtr<StorageArea> InspectorDOMStorageAgent::findStorageArea(ErrorString* errorString, const RefPtr<JSONObject>& storageId, Frame*& targetFrame)
+PassOwnPtrWillBeRawPtr<StorageArea> InspectorDOMStorageAgent::findStorageArea(ErrorString* errorString, const RefPtr<JSONObject>& storageId, Frame*& targetFrame)
 {
     String securityOrigin;
     bool isLocalStorage = false;
diff --git a/Source/core/inspector/InspectorDOMStorageAgent.h b/Source/core/inspector/InspectorDOMStorageAgent.h
index 4c79cef..1ab86df 100644
--- a/Source/core/inspector/InspectorDOMStorageAgent.h
+++ b/Source/core/inspector/InspectorDOMStorageAgent.h
@@ -46,37 +46,34 @@
 
 typedef String ErrorString;
 
-class InspectorDOMStorageAgent : public InspectorBaseAgent<InspectorDOMStorageAgent>, public InspectorBackendDispatcher::DOMStorageCommandHandler {
+class InspectorDOMStorageAgent FINAL : public InspectorBaseAgent<InspectorDOMStorageAgent>, public InspectorBackendDispatcher::DOMStorageCommandHandler {
 public:
-    static PassOwnPtr<InspectorDOMStorageAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorCompositeState* state)
+    static PassOwnPtr<InspectorDOMStorageAgent> create(InspectorPageAgent* pageAgent)
     {
-        return adoptPtr(new InspectorDOMStorageAgent(instrumentingAgents, pageAgent, state));
+        return adoptPtr(new InspectorDOMStorageAgent(pageAgent));
     }
-    ~InspectorDOMStorageAgent();
+    virtual ~InspectorDOMStorageAgent();
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
 
     // Called from the front-end.
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void getDOMStorageItems(ErrorString*, const RefPtr<JSONObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > >& items);
-    virtual void setDOMStorageItem(ErrorString*, const RefPtr<JSONObject>& storageId, const String& key, const String& value);
-    virtual void removeDOMStorageItem(ErrorString*, const RefPtr<JSONObject>& storageId, const String& key);
-
-    // Called from the injected script.
-    String storageId(Storage*);
-    PassRefPtr<TypeBuilder::DOMStorage::StorageId> storageId(SecurityOrigin*, bool isLocalStorage);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void getDOMStorageItems(ErrorString*, const RefPtr<JSONObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > >& items) OVERRIDE;
+    virtual void setDOMStorageItem(ErrorString*, const RefPtr<JSONObject>& storageId, const String& key, const String& value) OVERRIDE;
+    virtual void removeDOMStorageItem(ErrorString*, const RefPtr<JSONObject>& storageId, const String& key) OVERRIDE;
 
     // Called from InspectorInstrumentation
     void didDispatchDOMStorageEvent(const String& key, const String& oldValue, const String& newValue, StorageType, SecurityOrigin*);
 
 private:
 
-    InspectorDOMStorageAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorCompositeState*);
+    InspectorDOMStorageAgent(InspectorPageAgent*);
 
     bool isEnabled() const;
-    PassOwnPtr<StorageArea> findStorageArea(ErrorString*, const RefPtr<JSONObject>&, Frame*&);
+    PassOwnPtrWillBeRawPtr<StorageArea> findStorageArea(ErrorString*, const RefPtr<JSONObject>&, Frame*&);
+    PassRefPtr<TypeBuilder::DOMStorage::StorageId> storageId(SecurityOrigin*, bool isLocalStorage);
 
     InspectorPageAgent* m_pageAgent;
     InspectorFrontend* m_frontend;
diff --git a/Source/core/inspector/InspectorDatabaseAgent.cpp b/Source/core/inspector/InspectorDatabaseAgent.cpp
deleted file mode 100644
index d48e9a2..0000000
--- a/Source/core/inspector/InspectorDatabaseAgent.cpp
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-#include "core/inspector/InspectorDatabaseAgent.h"
-
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/inspector/InspectorDatabaseResource.h"
-#include "core/inspector/InspectorState.h"
-#include "core/inspector/InstrumentingAgents.h"
-#include "core/loader/DocumentLoader.h"
-#include "core/frame/Frame.h"
-#include "core/html/VoidCallback.h"
-#include "core/page/Page.h"
-#include "modules/webdatabase/Database.h"
-#include "modules/webdatabase/SQLError.h"
-#include "modules/webdatabase/SQLResultSet.h"
-#include "modules/webdatabase/SQLResultSetRowList.h"
-#include "modules/webdatabase/SQLStatementCallback.h"
-#include "modules/webdatabase/SQLStatementErrorCallback.h"
-#include "modules/webdatabase/SQLTransaction.h"
-#include "modules/webdatabase/SQLTransactionCallback.h"
-#include "modules/webdatabase/SQLTransactionErrorCallback.h"
-#include "modules/webdatabase/sqlite/SQLValue.h"
-#include "platform/JSONValues.h"
-#include "wtf/Vector.h"
-
-typedef WebCore::InspectorBackendDispatcher::DatabaseCommandHandler::ExecuteSQLCallback ExecuteSQLCallback;
-
-namespace WebCore {
-
-namespace DatabaseAgentState {
-static const char databaseAgentEnabled[] = "databaseAgentEnabled";
-};
-
-namespace {
-
-void reportTransactionFailed(ExecuteSQLCallback* requestCallback, SQLError* error)
-{
-    RefPtr<TypeBuilder::Database::Error> errorObject = TypeBuilder::Database::Error::create()
-        .setMessage(error->message())
-        .setCode(error->code());
-    requestCallback->sendSuccess(0, 0, errorObject.release());
-}
-
-class StatementCallback : public SQLStatementCallback {
-public:
-    static PassOwnPtr<StatementCallback> create(PassRefPtr<ExecuteSQLCallback> requestCallback)
-    {
-        return adoptPtr(new StatementCallback(requestCallback));
-    }
-
-    virtual ~StatementCallback() { }
-
-    virtual bool handleEvent(SQLTransaction*, SQLResultSet* resultSet)
-    {
-        SQLResultSetRowList* rowList = resultSet->rows();
-
-        RefPtr<TypeBuilder::Array<String> > columnNames = TypeBuilder::Array<String>::create();
-        const Vector<String>& columns = rowList->columnNames();
-        for (size_t i = 0; i < columns.size(); ++i)
-            columnNames->addItem(columns[i]);
-
-        RefPtr<TypeBuilder::Array<JSONValue> > values = TypeBuilder::Array<JSONValue>::create();
-        const Vector<SQLValue>& data = rowList->values();
-        for (size_t i = 0; i < data.size(); ++i) {
-            const SQLValue& value = rowList->values()[i];
-            switch (value.type()) {
-            case SQLValue::StringValue: values->addItem(JSONString::create(value.string())); break;
-            case SQLValue::NumberValue: values->addItem(JSONBasicValue::create(value.number())); break;
-            case SQLValue::NullValue: values->addItem(JSONValue::null()); break;
-            }
-        }
-        m_requestCallback->sendSuccess(columnNames.release(), values.release(), 0);
-        return true;
-    }
-
-private:
-    StatementCallback(PassRefPtr<ExecuteSQLCallback> requestCallback)
-        : m_requestCallback(requestCallback) { }
-    RefPtr<ExecuteSQLCallback> m_requestCallback;
-};
-
-class StatementErrorCallback : public SQLStatementErrorCallback {
-public:
-    static PassOwnPtr<StatementErrorCallback> create(PassRefPtr<ExecuteSQLCallback> requestCallback)
-    {
-        return adoptPtr(new StatementErrorCallback(requestCallback));
-    }
-
-    virtual ~StatementErrorCallback() { }
-
-    virtual bool handleEvent(SQLTransaction*, SQLError* error)
-    {
-        reportTransactionFailed(m_requestCallback.get(), error);
-        return true;
-    }
-
-private:
-    StatementErrorCallback(PassRefPtr<ExecuteSQLCallback> requestCallback)
-        : m_requestCallback(requestCallback) { }
-    RefPtr<ExecuteSQLCallback> m_requestCallback;
-};
-
-class TransactionCallback : public SQLTransactionCallback {
-public:
-    static PassOwnPtr<TransactionCallback> create(const String& sqlStatement, PassRefPtr<ExecuteSQLCallback> requestCallback)
-    {
-        return adoptPtr(new TransactionCallback(sqlStatement, requestCallback));
-    }
-
-    virtual ~TransactionCallback() { }
-
-    virtual bool handleEvent(SQLTransaction* transaction)
-    {
-        if (!m_requestCallback->isActive())
-            return true;
-
-        Vector<SQLValue> sqlValues;
-        OwnPtr<SQLStatementCallback> callback(StatementCallback::create(m_requestCallback.get()));
-        OwnPtr<SQLStatementErrorCallback> errorCallback(StatementErrorCallback::create(m_requestCallback.get()));
-        transaction->executeSQL(m_sqlStatement, sqlValues, callback.release(), errorCallback.release(), IGNORE_EXCEPTION);
-        return true;
-    }
-private:
-    TransactionCallback(const String& sqlStatement, PassRefPtr<ExecuteSQLCallback> requestCallback)
-        : m_sqlStatement(sqlStatement)
-        , m_requestCallback(requestCallback) { }
-    String m_sqlStatement;
-    RefPtr<ExecuteSQLCallback> m_requestCallback;
-};
-
-class TransactionErrorCallback : public SQLTransactionErrorCallback {
-public:
-    static PassOwnPtr<TransactionErrorCallback> create(PassRefPtr<ExecuteSQLCallback> requestCallback)
-    {
-        return adoptPtr(new TransactionErrorCallback(requestCallback));
-    }
-
-    virtual ~TransactionErrorCallback() { }
-
-    virtual bool handleEvent(SQLError* error)
-    {
-        reportTransactionFailed(m_requestCallback.get(), error);
-        return true;
-    }
-private:
-    TransactionErrorCallback(PassRefPtr<ExecuteSQLCallback> requestCallback)
-        : m_requestCallback(requestCallback) { }
-    RefPtr<ExecuteSQLCallback> m_requestCallback;
-};
-
-class TransactionSuccessCallback : public VoidCallback {
-public:
-    static PassOwnPtr<TransactionSuccessCallback> create()
-    {
-        return adoptPtr(new TransactionSuccessCallback());
-    }
-
-    virtual ~TransactionSuccessCallback() { }
-
-    virtual bool handleEvent() { return false; }
-
-private:
-    TransactionSuccessCallback() { }
-};
-
-} // namespace
-
-void InspectorDatabaseAgent::didOpenDatabase(PassRefPtr<Database> database, const String& domain, const String& name, const String& version)
-{
-    if (InspectorDatabaseResource* resource = findByFileName(database->fileName())) {
-        resource->setDatabase(database);
-        return;
-    }
-
-    RefPtr<InspectorDatabaseResource> resource = InspectorDatabaseResource::create(database, domain, name, version);
-    m_resources.set(resource->id(), resource);
-    // Resources are only bound while visible.
-    if (m_frontend && m_enabled)
-        resource->bind(m_frontend);
-}
-
-void InspectorDatabaseAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
-{
-    if (loader->frame() != frame->page()->mainFrame())
-        return;
-
-    m_resources.clear();
-}
-
-InspectorDatabaseAgent::InspectorDatabaseAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
-    : InspectorBaseAgent<InspectorDatabaseAgent>("Database", instrumentingAgents, state)
-    , m_frontend(0)
-    , m_enabled(false)
-{
-    m_instrumentingAgents->setInspectorDatabaseAgent(this);
-}
-
-InspectorDatabaseAgent::~InspectorDatabaseAgent()
-{
-    m_instrumentingAgents->setInspectorDatabaseAgent(0);
-}
-
-void InspectorDatabaseAgent::setFrontend(InspectorFrontend* frontend)
-{
-    m_frontend = frontend->database();
-}
-
-void InspectorDatabaseAgent::clearFrontend()
-{
-    m_frontend = 0;
-    disable(0);
-}
-
-void InspectorDatabaseAgent::enable(ErrorString*)
-{
-    if (m_enabled)
-        return;
-    m_enabled = true;
-    m_state->setBoolean(DatabaseAgentState::databaseAgentEnabled, m_enabled);
-
-    DatabaseResourcesMap::iterator databasesEnd = m_resources.end();
-    for (DatabaseResourcesMap::iterator it = m_resources.begin(); it != databasesEnd; ++it)
-        it->value->bind(m_frontend);
-}
-
-void InspectorDatabaseAgent::disable(ErrorString*)
-{
-    if (!m_enabled)
-        return;
-    m_enabled = false;
-    m_state->setBoolean(DatabaseAgentState::databaseAgentEnabled, m_enabled);
-}
-
-void InspectorDatabaseAgent::restore()
-{
-    m_enabled = m_state->getBoolean(DatabaseAgentState::databaseAgentEnabled);
-}
-
-void InspectorDatabaseAgent::getDatabaseTableNames(ErrorString* error, const String& databaseId, RefPtr<TypeBuilder::Array<String> >& names)
-{
-    if (!m_enabled) {
-        *error = "Database agent is not enabled";
-        return;
-    }
-
-    names = TypeBuilder::Array<String>::create();
-
-    Database* database = databaseForId(databaseId);
-    if (database) {
-        Vector<String> tableNames = database->tableNames();
-        unsigned length = tableNames.size();
-        for (unsigned i = 0; i < length; ++i)
-            names->addItem(tableNames[i]);
-    }
-}
-
-void InspectorDatabaseAgent::executeSQL(ErrorString*, const String& databaseId, const String& query, PassRefPtr<ExecuteSQLCallback> prpRequestCallback)
-{
-    RefPtr<ExecuteSQLCallback> requestCallback = prpRequestCallback;
-
-    if (!m_enabled) {
-        requestCallback->sendFailure("Database agent is not enabled");
-        return;
-    }
-
-    Database* database = databaseForId(databaseId);
-    if (!database) {
-        requestCallback->sendFailure("Database not found");
-        return;
-    }
-
-    OwnPtr<SQLTransactionCallback> callback(TransactionCallback::create(query, requestCallback.get()));
-    OwnPtr<SQLTransactionErrorCallback> errorCallback(TransactionErrorCallback::create(requestCallback.get()));
-    OwnPtr<VoidCallback> successCallback(TransactionSuccessCallback::create());
-    database->transaction(callback.release(), errorCallback.release(), successCallback.release());
-}
-
-String InspectorDatabaseAgent::databaseId(Database* database)
-{
-    for (DatabaseResourcesMap::iterator it = m_resources.begin(); it != m_resources.end(); ++it) {
-        if (it->value->database() == database)
-            return it->key;
-    }
-    return String();
-}
-
-InspectorDatabaseResource* InspectorDatabaseAgent::findByFileName(const String& fileName)
-{
-    for (DatabaseResourcesMap::iterator it = m_resources.begin(); it != m_resources.end(); ++it) {
-        if (it->value->database()->fileName() == fileName)
-            return it->value.get();
-    }
-    return 0;
-}
-
-Database* InspectorDatabaseAgent::databaseForId(const String& databaseId)
-{
-    DatabaseResourcesMap::iterator it = m_resources.find(databaseId);
-    if (it == m_resources.end())
-        return 0;
-    return it->value->database();
-}
-
-} // namespace WebCore
diff --git a/Source/core/inspector/InspectorDatabaseAgent.h b/Source/core/inspector/InspectorDatabaseAgent.h
deleted file mode 100644
index 1a937f9..0000000
--- a/Source/core/inspector/InspectorDatabaseAgent.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef InspectorDatabaseAgent_h
-#define InspectorDatabaseAgent_h
-
-#include "InspectorFrontend.h"
-#include "core/inspector/InspectorBaseAgent.h"
-#include "wtf/HashMap.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Database;
-class DocumentLoader;
-class Frame;
-class InspectorDatabaseResource;
-class InspectorFrontend;
-class InstrumentingAgents;
-
-typedef String ErrorString;
-
-class InspectorDatabaseAgent : public InspectorBaseAgent<InspectorDatabaseAgent>, public InspectorBackendDispatcher::DatabaseCommandHandler {
-public:
-    static PassOwnPtr<InspectorDatabaseAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
-    {
-        return adoptPtr(new InspectorDatabaseAgent(instrumentingAgents, state));
-    }
-    ~InspectorDatabaseAgent();
-
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
-
-    void didCommitLoad(Frame*, DocumentLoader*);
-
-    // Called from the front-end.
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void getDatabaseTableNames(ErrorString*, const String& databaseId, RefPtr<TypeBuilder::Array<String> >& names);
-    virtual void executeSQL(ErrorString*, const String& databaseId, const String& query, PassRefPtr<ExecuteSQLCallback>);
-
-    // Called from the injected script.
-    String databaseId(Database*);
-
-    void didOpenDatabase(PassRefPtr<Database>, const String& domain, const String& name, const String& version);
-private:
-    explicit InspectorDatabaseAgent(InstrumentingAgents*, InspectorCompositeState*);
-
-    Database* databaseForId(const String& databaseId);
-    InspectorDatabaseResource* findByFileName(const String& fileName);
-
-    InspectorFrontend::Database* m_frontend;
-    typedef HashMap<String, RefPtr<InspectorDatabaseResource> > DatabaseResourcesMap;
-    DatabaseResourcesMap m_resources;
-    bool m_enabled;
-};
-
-} // namespace WebCore
-
-#endif // !defined(InspectorDatabaseAgent_h)
diff --git a/Source/core/inspector/InspectorDatabaseInstrumentation.h b/Source/core/inspector/InspectorDatabaseInstrumentation.h
deleted file mode 100644
index 859cc6c..0000000
--- a/Source/core/inspector/InspectorDatabaseInstrumentation.h
+++ /dev/null
@@ -1 +0,0 @@
-#include "InspectorDatabaseInstrumentationInl.h"
diff --git a/Source/core/inspector/InspectorDatabaseResource.cpp b/Source/core/inspector/InspectorDatabaseResource.cpp
deleted file mode 100644
index d2196a0..0000000
--- a/Source/core/inspector/InspectorDatabaseResource.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
- * Copyright (C) 2009 Google Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-
-#include "core/inspector/InspectorDatabaseResource.h"
-
-#include "modules/webdatabase/Database.h"
-
-namespace WebCore {
-
-static int nextUnusedId = 1;
-
-PassRefPtr<InspectorDatabaseResource> InspectorDatabaseResource::create(PassRefPtr<Database> database, const String& domain, const String& name, const String& version)
-{
-    return adoptRef(new InspectorDatabaseResource(database, domain, name, version));
-}
-
-InspectorDatabaseResource::InspectorDatabaseResource(PassRefPtr<Database> database, const String& domain, const String& name, const String& version)
-    : m_database(database)
-    , m_id(String::number(nextUnusedId++))
-    , m_domain(domain)
-    , m_name(name)
-    , m_version(version)
-{
-}
-
-void InspectorDatabaseResource::bind(InspectorFrontend::Database* frontend)
-{
-    RefPtr<TypeBuilder::Database::Database> jsonObject = TypeBuilder::Database::Database::create()
-        .setId(m_id)
-        .setDomain(m_domain)
-        .setName(m_name)
-        .setVersion(m_version);
-    frontend->addDatabase(jsonObject);
-}
-
-} // namespace WebCore
diff --git a/Source/core/inspector/InspectorDatabaseResource.h b/Source/core/inspector/InspectorDatabaseResource.h
deleted file mode 100644
index 24c1fd8..0000000
--- a/Source/core/inspector/InspectorDatabaseResource.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
- * Copyright (C) 2009 Google Inc. 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef InspectorDatabaseResource_h
-#define InspectorDatabaseResource_h
-
-#include "InspectorFrontend.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-class Database;
-class InspectorFrontend;
-
-class InspectorDatabaseResource : public RefCounted<InspectorDatabaseResource> {
-public:
-    static PassRefPtr<InspectorDatabaseResource> create(PassRefPtr<Database> database, const String& domain, const String& name, const String& version);
-
-    void bind(InspectorFrontend::Database*);
-    Database* database() { return m_database.get(); }
-    void setDatabase(PassRefPtr<Database> database) { m_database = database; }
-    String id() const { return m_id; }
-
-private:
-    InspectorDatabaseResource(PassRefPtr<Database>, const String& domain, const String& name, const String& version);
-
-    RefPtr<Database> m_database;
-    String m_id;
-    String m_domain;
-    String m_name;
-    String m_version;
-};
-
-} // namespace WebCore
-
-#endif // InspectorDatabaseResource_h
diff --git a/Source/core/inspector/InspectorDebuggerAgent.cpp b/Source/core/inspector/InspectorDebuggerAgent.cpp
index 9e9f336..08edc7a 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -1,6 +1,6 @@
 /*
  * Copyright (C) 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2010-2011 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -61,6 +61,7 @@
 static const char debuggerEnabled[] = "debuggerEnabled";
 static const char javaScriptBreakpoints[] = "javaScriptBreakopints";
 static const char pauseOnExceptionsState[] = "pauseOnExceptionsState";
+static const char asyncCallStackDepth[] = "asyncCallStackDepth";
 
 // Breakpoint properties.
 static const char url[] = "url";
@@ -97,8 +98,8 @@
     return scriptId + ':' + String::number(lineNumber) + ':' + String::number(columnNumber) + breakpointIdSuffix(source);
 }
 
-InspectorDebuggerAgent::InspectorDebuggerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
-    : InspectorBaseAgent<InspectorDebuggerAgent>("Debugger", instrumentingAgents, inspectorState)
+InspectorDebuggerAgent::InspectorDebuggerAgent(InjectedScriptManager* injectedScriptManager)
+    : InspectorBaseAgent<InspectorDebuggerAgent>("Debugger")
     , m_injectedScriptManager(injectedScriptManager)
     , m_frontend(0)
     , m_pausedScriptState(0)
@@ -107,9 +108,6 @@
     , m_skipStepInCount(numberOfStepsBeforeStepOut)
     , m_skipAllPauses(false)
 {
-    // FIXME: make breakReason optional so that there was no need to init it with "other".
-    clearBreakDetails();
-    m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, ScriptDebugServer::DontPauseOnExceptions);
 }
 
 InspectorDebuggerAgent::~InspectorDebuggerAgent()
@@ -117,6 +115,13 @@
     ASSERT(!m_instrumentingAgents->inspectorDebuggerAgent());
 }
 
+void InspectorDebuggerAgent::init()
+{
+    // FIXME: make breakReason optional so that there was no need to init it with "other".
+    clearBreakDetails();
+    m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, ScriptDebugServer::DontPauseOnExceptions);
+}
+
 void InspectorDebuggerAgent::enable()
 {
     m_instrumentingAgents->setInspectorDebuggerAgent(this);
@@ -134,6 +139,7 @@
     m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, JSONObject::create());
     m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, ScriptDebugServer::DontPauseOnExceptions);
     m_state->setString(DebuggerAgentState::skipStackPattern, "");
+    m_state->setLong(DebuggerAgentState::asyncCallStackDepth, 0);
     m_instrumentingAgents->setInspectorDebuggerAgent(0);
 
     stopListeningScriptDebugServer();
@@ -196,6 +202,7 @@
             m_skipAllPauses = false;
             m_state->setBoolean(DebuggerAgentState::skipAllPauses, false);
         }
+        m_asyncCallStackTracker.setAsyncCallStackDepth(m_state->getLong(DebuggerAgentState::asyncCallStackDepth));
     }
 }
 
@@ -431,7 +438,7 @@
 
 void InspectorDebuggerAgent::getStepInPositions(ErrorString* errorString, const String& callFrameId, RefPtr<Array<TypeBuilder::Debugger::Location> >& positions)
 {
-    if (!isPaused() || m_currentCallStack.isNull()) {
+    if (!isPaused() || m_currentCallStack.hasNoValue()) {
         *errorString = "Attempt to access callframe when debugger is not on pause";
         return;
     }
@@ -561,8 +568,9 @@
 
     BreakpointIdToDebugServerBreakpointIdsMap::iterator debugServerBreakpointIdsIterator = m_breakpointIdToDebugServerBreakpointIds.find(breakpointId);
     if (debugServerBreakpointIdsIterator == m_breakpointIdToDebugServerBreakpointIds.end())
-        debugServerBreakpointIdsIterator = m_breakpointIdToDebugServerBreakpointIds.set(breakpointId, Vector<String>()).iterator;
-    debugServerBreakpointIdsIterator->value.append(debugServerBreakpointId);
+        m_breakpointIdToDebugServerBreakpointIds.set(breakpointId, Vector<String>()).storedValue->value.append(debugServerBreakpointId);
+    else
+        debugServerBreakpointIdsIterator->value.append(debugServerBreakpointId);
 
     RefPtr<TypeBuilder::Debugger::Location> location = TypeBuilder::Debugger::Location::create()
         .setScriptId(scriptId)
@@ -608,7 +616,7 @@
 
 void InspectorDebuggerAgent::restartFrame(ErrorString* errorString, const String& callFrameId, RefPtr<Array<CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<StackTrace>& asyncStackTrace)
 {
-    if (!isPaused() || m_currentCallStack.isNull()) {
+    if (!isPaused() || m_currentCallStack.hasNoValue()) {
         *errorString = "Attempt to access callframe when debugger is not on pause";
         return;
     }
@@ -668,18 +676,21 @@
 
 void InspectorDebuggerAgent::didRemoveTimer(ExecutionContext* context, int timerId)
 {
-    m_asyncCallStackTracker.didRemoveTimer(context, timerId);
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didRemoveTimer(context, timerId);
 }
 
 bool InspectorDebuggerAgent::willFireTimer(ExecutionContext* context, int timerId)
 {
-    m_asyncCallStackTracker.willFireTimer(context, timerId);
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.willFireTimer(context, timerId);
     return true;
 }
 
 void InspectorDebuggerAgent::didFireTimer()
 {
-    m_asyncCallStackTracker.didFireAsyncCall();
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didFireAsyncCall();
     cancelPauseOnNextStatement();
 }
 
@@ -691,25 +702,102 @@
 
 void InspectorDebuggerAgent::didCancelAnimationFrame(Document* document, int callbackId)
 {
-    m_asyncCallStackTracker.didCancelAnimationFrame(document, callbackId);
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didCancelAnimationFrame(document, callbackId);
 }
 
 bool InspectorDebuggerAgent::willFireAnimationFrame(Document* document, int callbackId)
 {
-    m_asyncCallStackTracker.willFireAnimationFrame(document, callbackId);
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.willFireAnimationFrame(document, callbackId);
     return true;
 }
 
 void InspectorDebuggerAgent::didFireAnimationFrame()
 {
-    m_asyncCallStackTracker.didFireAsyncCall();
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didFireAsyncCall();
+}
+
+void InspectorDebuggerAgent::didAddEventListener(EventTarget* eventTarget, const AtomicString& eventType, EventListener* listener, bool useCapture)
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didAddEventListener(eventTarget, eventType, listener, useCapture, scriptDebugServer().currentCallFrames());
+}
+
+void InspectorDebuggerAgent::didRemoveEventListener(EventTarget* eventTarget, const AtomicString& eventType, EventListener* listener, bool useCapture)
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didRemoveEventListener(eventTarget, eventType, listener, useCapture);
+}
+
+void InspectorDebuggerAgent::didRemoveAllEventListeners(EventTarget* eventTarget)
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didRemoveAllEventListeners(eventTarget);
+}
+
+void InspectorDebuggerAgent::willHandleEvent(EventTarget* eventTarget, const AtomicString& eventType, EventListener* listener, bool useCapture)
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.willHandleEvent(eventTarget, eventType, listener, useCapture);
 }
 
 void InspectorDebuggerAgent::didHandleEvent()
 {
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didFireAsyncCall();
     cancelPauseOnNextStatement();
 }
 
+void InspectorDebuggerAgent::willLoadXHR(XMLHttpRequest* xhr, ThreadableLoaderClient*, const AtomicString&, const KURL&, bool async, PassRefPtr<FormData>, const HTTPHeaderMap&, bool)
+{
+    if (m_asyncCallStackTracker.isEnabled() && async)
+        m_asyncCallStackTracker.willLoadXHR(xhr, scriptDebugServer().currentCallFrames());
+}
+
+void InspectorDebuggerAgent::didEnqueueMutationRecord(ExecutionContext* context, MutationObserver* observer)
+{
+    if (m_asyncCallStackTracker.isEnabled() && !m_asyncCallStackTracker.hasEnqueuedMutationRecord(context, observer))
+        m_asyncCallStackTracker.didEnqueueMutationRecord(context, observer, scriptDebugServer().currentCallFrames());
+}
+
+void InspectorDebuggerAgent::didClearAllMutationRecords(ExecutionContext* context, MutationObserver* observer)
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didClearAllMutationRecords(context, observer);
+}
+
+void InspectorDebuggerAgent::willDeliverMutationRecords(ExecutionContext* context, MutationObserver* observer)
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.willDeliverMutationRecords(context, observer);
+}
+
+void InspectorDebuggerAgent::didDeliverMutationRecords()
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didFireAsyncCall();
+}
+
+void InspectorDebuggerAgent::didPostPromiseTask(ExecutionContext* context, ExecutionContextTask* task, bool isResolved)
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didPostPromiseTask(context, task, isResolved, scriptDebugServer().currentCallFrames());
+}
+
+void InspectorDebuggerAgent::willPerformPromiseTask(ExecutionContext* context, ExecutionContextTask* task)
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.willPerformPromiseTask(context, task);
+}
+
+void InspectorDebuggerAgent::didPerformPromiseTask()
+{
+    if (m_asyncCallStackTracker.isEnabled())
+        m_asyncCallStackTracker.didFireAsyncCall();
+}
+
 void InspectorDebuggerAgent::pause(ErrorString*)
 {
     if (m_javaScriptPauseScheduled)
@@ -731,7 +819,7 @@
 {
     if (!callFrameId)
         return ScriptValue();
-    if (!isPaused() || m_currentCallStack.isNull()) {
+    if (!isPaused() || m_currentCallStack.hasNoValue()) {
         *errorString = "Attempt to access callframe when debugger is not on pause";
         return ScriptValue();
     }
@@ -802,7 +890,7 @@
 
 void InspectorDebuggerAgent::evaluateOnCallFrame(ErrorString* errorString, const String& callFrameId, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
 {
-    if (!isPaused() || m_currentCallStack.isNull()) {
+    if (!isPaused() || m_currentCallStack.hasNoValue()) {
         *errorString = "Attempt to access callframe when debugger is not on pause";
         return;
     }
@@ -819,7 +907,17 @@
         muteConsole();
     }
 
-    injectedScript.evaluateOnCallFrame(errorString, m_currentCallStack, callFrameId, expression, objectGroup ? *objectGroup : "", includeCommandLineAPI ? *includeCommandLineAPI : false, returnByValue ? *returnByValue : false, generatePreview ? *generatePreview : false, &result, wasThrown);
+    Vector<ScriptValue> asyncCallStacks;
+    const AsyncCallStackTracker::AsyncCallChain* asyncChain = m_asyncCallStackTracker.isEnabled() ? m_asyncCallStackTracker.currentAsyncCallChain() : 0;
+    if (asyncChain) {
+        const AsyncCallStackTracker::AsyncCallStackVector& callStacks = asyncChain->callStacks();
+        asyncCallStacks.resize(callStacks.size());
+        AsyncCallStackTracker::AsyncCallStackVector::const_iterator it = callStacks.begin();
+        for (size_t i = 0; it != callStacks.end(); ++it, ++i)
+            asyncCallStacks[i] = (*it)->callFrames();
+    }
+
+    injectedScript.evaluateOnCallFrame(errorString, m_currentCallStack, asyncCallStacks, callFrameId, expression, objectGroup ? *objectGroup : "", includeCommandLineAPI ? *includeCommandLineAPI : false, returnByValue ? *returnByValue : false, generatePreview ? *generatePreview : false, &result, wasThrown);
 
     if (doNotPauseOnExceptionsAndMuteConsole ? *doNotPauseOnExceptionsAndMuteConsole : false) {
         unmuteConsole();
@@ -890,7 +988,7 @@
 {
     InjectedScript injectedScript;
     if (callFrameId) {
-        if (!isPaused() || m_currentCallStack.isNull()) {
+        if (!isPaused() || m_currentCallStack.hasNoValue()) {
             *errorString = "Attempt to access callframe when debugger is not on pause";
             return;
         }
@@ -931,6 +1029,7 @@
 
 void InspectorDebuggerAgent::setAsyncCallStackDepth(ErrorString*, int depth)
 {
+    m_state->setLong(DebuggerAgentState::asyncCallStackDepth, depth);
     m_asyncCallStackTracker.setAsyncCallStackDepth(depth);
 }
 
@@ -945,14 +1044,14 @@
 
 PassRefPtr<Array<CallFrame> > InspectorDebuggerAgent::currentCallFrames()
 {
-    if (!m_pausedScriptState)
+    if (!m_pausedScriptState || m_currentCallStack.hasNoValue())
         return Array<CallFrame>::create();
     InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(m_pausedScriptState);
     if (injectedScript.hasNoValue()) {
         ASSERT_NOT_REACHED();
         return Array<CallFrame>::create();
     }
-    return injectedScript.wrapCallFrames(m_currentCallStack);
+    return injectedScript.wrapCallFrames(m_currentCallStack, 0);
 }
 
 PassRefPtr<StackTrace> InspectorDebuggerAgent::currentAsyncStackTrace()
@@ -971,9 +1070,10 @@
     if (callStacks.isEmpty())
         return 0;
     RefPtr<StackTrace> result;
+    int asyncOrdinal = callStacks.size();
     for (AsyncCallStackTracker::AsyncCallStackVector::const_reverse_iterator it = callStacks.rbegin(); it != callStacks.rend(); ++it) {
         RefPtr<StackTrace> next = StackTrace::create()
-            .setCallFrames(injectedScript.wrapCallFrames((*it)->callFrames()))
+            .setCallFrames(injectedScript.wrapCallFrames((*it)->callFrames(), asyncOrdinal--))
             .release();
         next->setDescription((*it)->description());
         if (result)
diff --git a/Source/core/inspector/InspectorDebuggerAgent.h b/Source/core/inspector/InspectorDebuggerAgent.h
index 718a0c2..f44abcc 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.h
+++ b/Source/core/inspector/InspectorDebuggerAgent.h
@@ -32,13 +32,13 @@
 
 #include "InspectorFrontend.h"
 #include "bindings/v8/ScriptState.h"
+#include "core/frame/ConsoleTypes.h"
 #include "core/inspector/AsyncCallStackTracker.h"
 #include "core/inspector/ConsoleAPITypes.h"
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InspectorBaseAgent.h"
 #include "core/inspector/ScriptBreakpoint.h"
 #include "core/inspector/ScriptDebugListener.h"
-#include "core/frame/ConsoleTypes.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/PassRefPtr.h"
@@ -48,16 +48,25 @@
 namespace WebCore {
 
 class Document;
+class EventListener;
+class EventTarget;
+class ExecutionContextTask;
+class FormData;
+class HTTPHeaderMap;
 class InjectedScriptManager;
 class InspectorFrontend;
 class InstrumentingAgents;
 class JSONObject;
+class KURL;
+class MutationObserver;
 class ScriptArguments;
 class ScriptCallStack;
 class ScriptDebugServer;
+class ScriptRegexp;
 class ScriptSourceCode;
 class ScriptValue;
-class ScriptRegexp;
+class ThreadableLoaderClient;
+class XMLHttpRequest;
 
 typedef String ErrorString;
 
@@ -74,11 +83,12 @@
 
     virtual ~InspectorDebuggerAgent();
 
-    virtual void canSetScriptSource(ErrorString*, bool* result) { *result = true; }
+    virtual void canSetScriptSource(ErrorString*, bool* result) OVERRIDE FINAL { *result = true; }
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void init() OVERRIDE FINAL;
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE FINAL;
+    virtual void clearFrontend() OVERRIDE FINAL;
+    virtual void restore() OVERRIDE FINAL;
 
     bool isPaused();
     bool runningNestedMessageLoop();
@@ -89,45 +99,45 @@
     PassOwnPtr<ScriptSourceCode> preprocess(Frame*, const ScriptSourceCode&);
 
     // Part of the protocol.
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void setBreakpointsActive(ErrorString*, bool active);
-    virtual void setSkipAllPauses(ErrorString*, bool skipped, const bool* untilReload);
+    virtual void enable(ErrorString*) OVERRIDE FINAL;
+    virtual void disable(ErrorString*) OVERRIDE FINAL;
+    virtual void setBreakpointsActive(ErrorString*, bool active) OVERRIDE FINAL;
+    virtual void setSkipAllPauses(ErrorString*, bool skipped, const bool* untilReload) OVERRIDE FINAL;
 
-    virtual void setBreakpointByUrl(ErrorString*, int lineNumber, const String* optionalURL, const String* optionalURLRegex, const int* optionalColumnNumber, const String* optionalCondition, const bool* isAntiBreakpoint, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& locations);
-    virtual void setBreakpoint(ErrorString*, const RefPtr<JSONObject>& location, const String* optionalCondition, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Debugger::Location>& actualLocation);
-    virtual void removeBreakpoint(ErrorString*, const String& breakpointId);
-    virtual void continueToLocation(ErrorString*, const RefPtr<JSONObject>& location, const bool* interstateLocationOpt);
-    virtual void getStepInPositions(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& positions);
-    virtual void getBacktrace(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >&, RefPtr<TypeBuilder::Debugger::StackTrace>&);
+    virtual void setBreakpointByUrl(ErrorString*, int lineNumber, const String* optionalURL, const String* optionalURLRegex, const int* optionalColumnNumber, const String* optionalCondition, const bool* isAntiBreakpoint, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& locations) OVERRIDE FINAL;
+    virtual void setBreakpoint(ErrorString*, const RefPtr<JSONObject>& location, const String* optionalCondition, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Debugger::Location>& actualLocation) OVERRIDE FINAL;
+    virtual void removeBreakpoint(ErrorString*, const String& breakpointId) OVERRIDE FINAL;
+    virtual void continueToLocation(ErrorString*, const RefPtr<JSONObject>& location, const bool* interstateLocationOpt) OVERRIDE FINAL;
+    virtual void getStepInPositions(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& positions) OVERRIDE FINAL;
+    virtual void getBacktrace(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >&, RefPtr<TypeBuilder::Debugger::StackTrace>&) OVERRIDE FINAL;
 
-    virtual void searchInContent(ErrorString*, const String& scriptId, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> >&);
-    virtual void setScriptSource(ErrorString*, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>&, const String& scriptId, const String& newContent, const bool* preview, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<TypeBuilder::Debugger::StackTrace>& asyncStackTrace);
-    virtual void restartFrame(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<TypeBuilder::Debugger::StackTrace>& asyncStackTrace);
-    virtual void getScriptSource(ErrorString*, const String& scriptId, String* scriptSource);
-    virtual void getFunctionDetails(ErrorString*, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>&);
-    virtual void pause(ErrorString*);
-    virtual void resume(ErrorString*);
-    virtual void stepOver(ErrorString*, const String* callFrameId);
-    virtual void stepInto(ErrorString*);
-    virtual void stepOut(ErrorString*, const String* callFrameId);
-    virtual void setPauseOnExceptions(ErrorString*, const String& pauseState);
+    virtual void searchInContent(ErrorString*, const String& scriptId, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> >&) OVERRIDE FINAL;
+    virtual void setScriptSource(ErrorString*, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>&, const String& scriptId, const String& newContent, const bool* preview, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<TypeBuilder::Debugger::StackTrace>& asyncStackTrace) OVERRIDE FINAL;
+    virtual void restartFrame(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<TypeBuilder::Debugger::StackTrace>& asyncStackTrace) OVERRIDE FINAL;
+    virtual void getScriptSource(ErrorString*, const String& scriptId, String* scriptSource) OVERRIDE FINAL;
+    virtual void getFunctionDetails(ErrorString*, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>&) OVERRIDE FINAL;
+    virtual void pause(ErrorString*) OVERRIDE FINAL;
+    virtual void resume(ErrorString*) OVERRIDE FINAL;
+    virtual void stepOver(ErrorString*, const String* callFrameId) OVERRIDE FINAL;
+    virtual void stepInto(ErrorString*) OVERRIDE FINAL;
+    virtual void stepOut(ErrorString*, const String* callFrameId) OVERRIDE FINAL;
+    virtual void setPauseOnExceptions(ErrorString*, const String& pauseState) OVERRIDE FINAL;
     virtual void evaluateOnCallFrame(ErrorString*,
-                             const String& callFrameId,
-                             const String& expression,
-                             const String* objectGroup,
-                             const bool* includeCommandLineAPI,
-                             const bool* doNotPauseOnExceptionsAndMuteConsole,
-                             const bool* returnByValue,
-                             const bool* generatePreview,
-                             RefPtr<TypeBuilder::Runtime::RemoteObject>& result,
-                             TypeBuilder::OptOutput<bool>* wasThrown);
-    void compileScript(ErrorString*, const String& expression, const String& sourceURL, TypeBuilder::OptOutput<TypeBuilder::Debugger::ScriptId>*, TypeBuilder::OptOutput<String>* syntaxErrorMessage);
-    void runScript(ErrorString*, const TypeBuilder::Debugger::ScriptId&, const int* executionContextId, const String* objectGroup, const bool* doNotPauseOnExceptionsAndMuteConsole, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown);
-    virtual void setOverlayMessage(ErrorString*, const String*);
-    virtual void setVariableValue(ErrorString*, int in_scopeNumber, const String& in_variableName, const RefPtr<JSONObject>& in_newValue, const String* in_callFrame, const String* in_functionObjectId);
-    virtual void skipStackFrames(ErrorString*, const String* pattern);
-    virtual void setAsyncCallStackDepth(ErrorString*, int depth);
+        const String& callFrameId,
+        const String& expression,
+        const String* objectGroup,
+        const bool* includeCommandLineAPI,
+        const bool* doNotPauseOnExceptionsAndMuteConsole,
+        const bool* returnByValue,
+        const bool* generatePreview,
+        RefPtr<TypeBuilder::Runtime::RemoteObject>& result,
+        TypeBuilder::OptOutput<bool>* wasThrown) OVERRIDE FINAL;
+    virtual void compileScript(ErrorString*, const String& expression, const String& sourceURL, TypeBuilder::OptOutput<TypeBuilder::Debugger::ScriptId>*, TypeBuilder::OptOutput<String>* syntaxErrorMessage) OVERRIDE;
+    virtual void runScript(ErrorString*, const TypeBuilder::Debugger::ScriptId&, const int* executionContextId, const String* objectGroup, const bool* doNotPauseOnExceptionsAndMuteConsole, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown) OVERRIDE;
+    virtual void setOverlayMessage(ErrorString*, const String*) OVERRIDE;
+    virtual void setVariableValue(ErrorString*, int in_scopeNumber, const String& in_variableName, const RefPtr<JSONObject>& in_newValue, const String* in_callFrame, const String* in_functionObjectId) OVERRIDE FINAL;
+    virtual void skipStackFrames(ErrorString*, const String* pattern) OVERRIDE FINAL;
+    virtual void setAsyncCallStackDepth(ErrorString*, int depth) OVERRIDE FINAL;
 
     void schedulePauseOnNextStatement(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data);
     void didInstallTimer(ExecutionContext*, int timerId, int timeout, bool singleShot);
@@ -138,10 +148,22 @@
     void didCancelAnimationFrame(Document*, int callbackId);
     bool willFireAnimationFrame(Document*, int callbackId);
     void didFireAnimationFrame();
+    void didAddEventListener(EventTarget*, const AtomicString& eventType, EventListener*, bool useCapture);
+    void didRemoveEventListener(EventTarget*, const AtomicString& eventType, EventListener*, bool useCapture);
+    void didRemoveAllEventListeners(EventTarget*);
+    void willHandleEvent(EventTarget*, const AtomicString& eventType, EventListener*, bool useCapture);
     void didHandleEvent();
+    void willLoadXHR(XMLHttpRequest*, ThreadableLoaderClient*, const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData> body, const HTTPHeaderMap& headers, bool includeCrendentials);
+    void didEnqueueMutationRecord(ExecutionContext*, MutationObserver*);
+    void didClearAllMutationRecords(ExecutionContext*, MutationObserver*);
+    void willDeliverMutationRecords(ExecutionContext*, MutationObserver*);
+    void didDeliverMutationRecords();
+    void didPostPromiseTask(ExecutionContext*, ExecutionContextTask*, bool isResolved);
+    void willPerformPromiseTask(ExecutionContext*, ExecutionContextTask*);
+    void didPerformPromiseTask();
     bool canBreakProgram();
     void breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data);
-    virtual void scriptExecutionBlockedByCSP(const String& directiveText);
+    void scriptExecutionBlockedByCSP(const String& directiveText);
 
     class Listener {
     public:
@@ -158,12 +180,12 @@
     void setBreakpoint(const String& scriptId, int lineNumber, int columnNumber, BreakpointSource, const String& condition = String());
     void removeBreakpoint(const String& scriptId, int lineNumber, int columnNumber, BreakpointSource);
 
-    SkipPauseRequest shouldSkipExceptionPause(RefPtr<JavaScriptCallFrame>& topFrame);
-    SkipPauseRequest shouldSkipBreakpointPause(RefPtr<JavaScriptCallFrame>& topFrame);
-    SkipPauseRequest shouldSkipStepPause(RefPtr<JavaScriptCallFrame>& topFrame);
+    virtual SkipPauseRequest shouldSkipExceptionPause(RefPtr<JavaScriptCallFrame>& topFrame) OVERRIDE FINAL;
+    virtual SkipPauseRequest shouldSkipBreakpointPause(RefPtr<JavaScriptCallFrame>& topFrame) OVERRIDE FINAL;
+    virtual SkipPauseRequest shouldSkipStepPause(RefPtr<JavaScriptCallFrame>& topFrame) OVERRIDE FINAL;
 
 protected:
-    InspectorDebuggerAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*);
+    explicit InspectorDebuggerAgent(InjectedScriptManager*);
 
     virtual void startListeningScriptDebugServer() = 0;
     virtual void stopListeningScriptDebugServer() = 0;
@@ -174,8 +196,8 @@
 
     virtual void enable();
     virtual void disable();
-    virtual void didPause(ScriptState*, const ScriptValue& callFrames, const ScriptValue& exception, const Vector<String>& hitBreakpoints);
-    virtual void didContinue();
+    virtual void didPause(ScriptState*, const ScriptValue& callFrames, const ScriptValue& exception, const Vector<String>& hitBreakpoints) OVERRIDE FINAL;
+    virtual void didContinue() OVERRIDE FINAL;
     void reset();
     void pageDidCommitLoad();
 
@@ -188,8 +210,8 @@
     PassRefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> > currentCallFrames();
     PassRefPtr<TypeBuilder::Debugger::StackTrace> currentAsyncStackTrace();
 
-    virtual void didParseSource(const String& scriptId, const Script&);
-    virtual void failedToParseSource(const String& url, const String& data, int firstLine, int errorLine, const String& errorMessage);
+    virtual void didParseSource(const String& scriptId, const Script&) OVERRIDE FINAL;
+    virtual void failedToParseSource(const String& url, const String& data, int firstLine, int errorLine, const String& errorMessage) OVERRIDE FINAL;
 
     void setPauseOnExceptionsImpl(ErrorString*, int);
 
diff --git a/Source/core/inspector/InspectorFileSystemAgent.cpp b/Source/core/inspector/InspectorFileSystemAgent.cpp
deleted file mode 100644
index e968a1b..0000000
--- a/Source/core/inspector/InspectorFileSystemAgent.cpp
+++ /dev/null
@@ -1,729 +0,0 @@
-/*
- * Copyright (C) 2011, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/inspector/InspectorFileSystemAgent.h"
-
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/DOMImplementation.h"
-#include "core/dom/Document.h"
-#include "core/events/Event.h"
-#include "core/fetch/TextResourceDecoder.h"
-#include "core/fileapi/File.h"
-#include "core/fileapi/FileError.h"
-#include "core/fileapi/FileReader.h"
-#include "core/frame/Frame.h"
-#include "core/html/VoidCallback.h"
-#include "core/inspector/InspectorPageAgent.h"
-#include "core/inspector/InspectorState.h"
-#include "modules/filesystem/DOMFileSystem.h"
-#include "modules/filesystem/DirectoryEntry.h"
-#include "modules/filesystem/DirectoryReader.h"
-#include "modules/filesystem/EntriesCallback.h"
-#include "modules/filesystem/Entry.h"
-#include "modules/filesystem/EntryCallback.h"
-#include "modules/filesystem/ErrorCallback.h"
-#include "modules/filesystem/FileCallback.h"
-#include "modules/filesystem/FileEntry.h"
-#include "modules/filesystem/FileSystemCallbacks.h"
-#include "modules/filesystem/LocalFileSystem.h"
-#include "modules/filesystem/Metadata.h"
-#include "modules/filesystem/MetadataCallback.h"
-#include "platform/MIMETypeRegistry.h"
-#include "platform/weborigin/KURL.h"
-#include "platform/weborigin/SecurityOrigin.h"
-#include "wtf/ArrayBuffer.h"
-#include "wtf/text/Base64.h"
-#include "wtf/text/TextEncoding.h"
-
-using WebCore::TypeBuilder::Array;
-
-typedef WebCore::InspectorBackendDispatcher::FileSystemCommandHandler::RequestFileSystemRootCallback RequestFileSystemRootCallback;
-typedef WebCore::InspectorBackendDispatcher::FileSystemCommandHandler::RequestDirectoryContentCallback RequestDirectoryContentCallback;
-typedef WebCore::InspectorBackendDispatcher::FileSystemCommandHandler::RequestMetadataCallback RequestMetadataCallback;
-typedef WebCore::InspectorBackendDispatcher::FileSystemCommandHandler::RequestFileContentCallback RequestFileContentCallback;
-typedef WebCore::InspectorBackendDispatcher::FileSystemCommandHandler::DeleteEntryCallback DeleteEntryCallback;
-
-namespace WebCore {
-
-namespace FileSystemAgentState {
-static const char fileSystemAgentEnabled[] = "fileSystemAgentEnabled";
-}
-
-namespace {
-
-template<typename BaseCallback, typename Handler, typename Argument>
-class CallbackDispatcher : public BaseCallback {
-public:
-    typedef bool (Handler::*HandlingMethod)(Argument);
-
-    static PassOwnPtr<CallbackDispatcher> create(PassRefPtr<Handler> handler, HandlingMethod handlingMethod)
-    {
-        return adoptPtr(new CallbackDispatcher(handler, handlingMethod));
-    }
-
-    virtual bool handleEvent(Argument argument) OVERRIDE
-    {
-        return (m_handler.get()->*m_handlingMethod)(argument);
-    }
-
-private:
-    CallbackDispatcher(PassRefPtr<Handler> handler, HandlingMethod handlingMethod)
-        : m_handler(handler)
-        , m_handlingMethod(handlingMethod) { }
-
-    RefPtr<Handler> m_handler;
-    HandlingMethod m_handlingMethod;
-};
-
-template<typename BaseCallback>
-class CallbackDispatcherFactory {
-public:
-    template<typename Handler, typename Argument>
-    static PassOwnPtr<CallbackDispatcher<BaseCallback, Handler, Argument> > create(Handler* handler, bool (Handler::*handlingMethod)(Argument))
-    {
-        return CallbackDispatcher<BaseCallback, Handler, Argument>::create(PassRefPtr<Handler>(handler), handlingMethod);
-    }
-};
-
-class FileSystemRootRequest : public RefCounted<FileSystemRootRequest> {
-    WTF_MAKE_NONCOPYABLE(FileSystemRootRequest);
-public:
-    static PassRefPtr<FileSystemRootRequest> create(PassRefPtr<RequestFileSystemRootCallback> requestCallback, const String& type)
-    {
-        return adoptRef(new FileSystemRootRequest(requestCallback, type));
-    }
-
-    void start(ExecutionContext*);
-
-private:
-    bool didHitError(FileError* error)
-    {
-        reportResult(error->code());
-        return true;
-    }
-
-    bool didGetEntry(Entry*);
-
-    void reportResult(FileError::ErrorCode errorCode, PassRefPtr<TypeBuilder::FileSystem::Entry> entry = 0)
-    {
-        m_requestCallback->sendSuccess(static_cast<int>(errorCode), entry);
-    }
-
-    FileSystemRootRequest(PassRefPtr<RequestFileSystemRootCallback> requestCallback, const String& type)
-        : m_requestCallback(requestCallback)
-        , m_type(type) { }
-
-    RefPtr<RequestFileSystemRootCallback> m_requestCallback;
-    String m_type;
-};
-
-void FileSystemRootRequest::start(ExecutionContext* executionContext)
-{
-    ASSERT(executionContext);
-
-    OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &FileSystemRootRequest::didHitError);
-
-    FileSystemType type;
-    if (!DOMFileSystemBase::pathPrefixToFileSystemType(m_type, type)) {
-        errorCallback->handleEvent(FileError::create(FileError::SYNTAX_ERR).get());
-        return;
-    }
-
-    KURL rootURL = DOMFileSystemBase::createFileSystemRootURL(executionContext->securityOrigin()->toString(), type);
-    if (!rootURL.isValid()) {
-        errorCallback->handleEvent(FileError::create(FileError::SYNTAX_ERR).get());
-        return;
-    }
-
-    OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &FileSystemRootRequest::didGetEntry);
-    OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
-    LocalFileSystem::from(executionContext)->resolveURL(executionContext, rootURL, fileSystemCallbacks.release());
-}
-
-bool FileSystemRootRequest::didGetEntry(Entry* entry)
-{
-    RefPtr<TypeBuilder::FileSystem::Entry> result = TypeBuilder::FileSystem::Entry::create()
-        .setUrl(entry->toURL())
-        .setName("/")
-        .setIsDirectory(true);
-    reportResult(static_cast<FileError::ErrorCode>(0), result);
-    return true;
-}
-
-class DirectoryContentRequest : public RefCounted<DirectoryContentRequest> {
-    WTF_MAKE_NONCOPYABLE(DirectoryContentRequest);
-public:
-    static PassRefPtr<DirectoryContentRequest> create(PassRefPtr<RequestDirectoryContentCallback> requestCallback, const String& url)
-    {
-        return adoptRef(new DirectoryContentRequest(requestCallback, url));
-    }
-
-    virtual ~DirectoryContentRequest()
-    {
-        reportResult(FileError::ABORT_ERR);
-    }
-
-    void start(ExecutionContext*);
-
-private:
-    bool didHitError(FileError* error)
-    {
-        reportResult(error->code());
-        return true;
-    }
-
-    bool didGetEntry(Entry*);
-    bool didReadDirectoryEntries(const EntryVector&);
-
-    void reportResult(FileError::ErrorCode errorCode, PassRefPtr<Array<TypeBuilder::FileSystem::Entry> > entries = 0)
-    {
-        m_requestCallback->sendSuccess(static_cast<int>(errorCode), entries);
-    }
-
-    DirectoryContentRequest(PassRefPtr<RequestDirectoryContentCallback> requestCallback, const String& url)
-        : m_requestCallback(requestCallback)
-        , m_url(ParsedURLString, url) { }
-
-    void readDirectoryEntries();
-
-    RefPtr<RequestDirectoryContentCallback> m_requestCallback;
-    KURL m_url;
-    RefPtr<Array<TypeBuilder::FileSystem::Entry> > m_entries;
-    RefPtr<DirectoryReader> m_directoryReader;
-};
-
-void DirectoryContentRequest::start(ExecutionContext* executionContext)
-{
-    ASSERT(executionContext);
-
-    OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DirectoryContentRequest::didHitError);
-    OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &DirectoryContentRequest::didGetEntry);
-
-    OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
-
-    LocalFileSystem::from(executionContext)->resolveURL(executionContext, m_url, fileSystemCallbacks.release());
-}
-
-bool DirectoryContentRequest::didGetEntry(Entry* entry)
-{
-    if (!entry->isDirectory()) {
-        reportResult(FileError::TYPE_MISMATCH_ERR);
-        return true;
-    }
-
-    m_directoryReader = static_cast<DirectoryEntry*>(entry)->createReader();
-    m_entries = Array<TypeBuilder::FileSystem::Entry>::create();
-    readDirectoryEntries();
-    return true;
-}
-
-void DirectoryContentRequest::readDirectoryEntries()
-{
-    if (!m_directoryReader->filesystem()->executionContext()) {
-        reportResult(FileError::ABORT_ERR);
-        return;
-    }
-
-    OwnPtr<EntriesCallback> successCallback = CallbackDispatcherFactory<EntriesCallback>::create(this, &DirectoryContentRequest::didReadDirectoryEntries);
-    OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DirectoryContentRequest::didHitError);
-    m_directoryReader->readEntries(successCallback.release(), errorCallback.release());
-}
-
-bool DirectoryContentRequest::didReadDirectoryEntries(const EntryVector& entries)
-{
-    if (entries.isEmpty()) {
-        reportResult(static_cast<FileError::ErrorCode>(0), m_entries);
-        return true;
-    }
-
-    for (size_t i = 0; i < entries.size(); ++i) {
-        RefPtr<Entry> entry = entries[i];
-        RefPtr<TypeBuilder::FileSystem::Entry> entryForFrontend = TypeBuilder::FileSystem::Entry::create()
-            .setUrl(entry->toURL())
-            .setName(entry->name())
-            .setIsDirectory(entry->isDirectory());
-
-        using TypeBuilder::Page::ResourceType;
-        if (!entry->isDirectory()) {
-            String mimeType = MIMETypeRegistry::getMIMETypeForPath(entry->name());
-            ResourceType::Enum resourceType;
-            if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType)) {
-                resourceType = ResourceType::Image;
-                entryForFrontend->setIsTextFile(false);
-            } else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType)) {
-                resourceType = ResourceType::Script;
-                entryForFrontend->setIsTextFile(true);
-            } else if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType)) {
-                resourceType = ResourceType::Document;
-                entryForFrontend->setIsTextFile(true);
-            } else {
-                resourceType = ResourceType::Other;
-                entryForFrontend->setIsTextFile(DOMImplementation::isXMLMIMEType(mimeType) || DOMImplementation::isTextMIMEType(mimeType));
-            }
-
-            entryForFrontend->setMimeType(mimeType);
-            entryForFrontend->setResourceType(resourceType);
-        }
-
-        m_entries->addItem(entryForFrontend);
-    }
-    readDirectoryEntries();
-    return true;
-}
-
-class MetadataRequest : public RefCounted<MetadataRequest> {
-    WTF_MAKE_NONCOPYABLE(MetadataRequest);
-public:
-    static PassRefPtr<MetadataRequest> create(PassRefPtr<RequestMetadataCallback> requestCallback, const String& url)
-    {
-        return adoptRef(new MetadataRequest(requestCallback, url));
-    }
-
-    virtual ~MetadataRequest()
-    {
-        reportResult(FileError::ABORT_ERR);
-    }
-
-    void start(ExecutionContext*);
-
-private:
-    bool didHitError(FileError* error)
-    {
-        reportResult(error->code());
-        return true;
-    }
-
-    bool didGetEntry(Entry*);
-    bool didGetMetadata(Metadata*);
-
-    void reportResult(FileError::ErrorCode errorCode, PassRefPtr<TypeBuilder::FileSystem::Metadata> metadata = 0)
-    {
-        m_requestCallback->sendSuccess(static_cast<int>(errorCode), metadata);
-    }
-
-    MetadataRequest(PassRefPtr<RequestMetadataCallback> requestCallback, const String& url)
-        : m_requestCallback(requestCallback)
-        , m_url(ParsedURLString, url) { }
-
-    RefPtr<RequestMetadataCallback> m_requestCallback;
-    KURL m_url;
-    bool m_isDirectory;
-};
-
-void MetadataRequest::start(ExecutionContext* executionContext)
-{
-    ASSERT(executionContext);
-
-    OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &MetadataRequest::didHitError);
-    OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &MetadataRequest::didGetEntry);
-    OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
-    LocalFileSystem::from(executionContext)->resolveURL(executionContext, m_url, fileSystemCallbacks.release());
-}
-
-bool MetadataRequest::didGetEntry(Entry* entry)
-{
-    if (!entry->filesystem()->executionContext()) {
-        reportResult(FileError::ABORT_ERR);
-        return true;
-    }
-
-    OwnPtr<MetadataCallback> successCallback = CallbackDispatcherFactory<MetadataCallback>::create(this, &MetadataRequest::didGetMetadata);
-    OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &MetadataRequest::didHitError);
-    entry->getMetadata(successCallback.release(), errorCallback.release());
-    m_isDirectory = entry->isDirectory();
-    return true;
-}
-
-bool MetadataRequest::didGetMetadata(Metadata* metadata)
-{
-    using TypeBuilder::FileSystem::Metadata;
-    RefPtr<Metadata> result = Metadata::create()
-        .setModificationTime(metadata->modificationTime())
-        .setSize(metadata->size());
-    reportResult(static_cast<FileError::ErrorCode>(0), result);
-    return true;
-}
-
-class FileContentRequest : public EventListener {
-    WTF_MAKE_NONCOPYABLE(FileContentRequest);
-public:
-    static PassRefPtr<FileContentRequest> create(PassRefPtr<RequestFileContentCallback> requestCallback, const String& url, bool readAsText, long long start, long long end, const String& charset)
-    {
-        return adoptRef(new FileContentRequest(requestCallback, url, readAsText, start, end, charset));
-    }
-
-    virtual ~FileContentRequest()
-    {
-        reportResult(FileError::ABORT_ERR);
-    }
-
-    void start(ExecutionContext*);
-
-    virtual bool operator==(const EventListener& other) OVERRIDE
-    {
-        return this == &other;
-    }
-
-    virtual void handleEvent(ExecutionContext*, Event* event) OVERRIDE
-    {
-        if (event->type() == EventTypeNames::load)
-            didRead();
-        else if (event->type() == EventTypeNames::error)
-            didHitError(m_reader->error().get());
-    }
-
-private:
-    bool didHitError(FileError* error)
-    {
-        reportResult(error->code());
-        return true;
-    }
-
-    bool didGetEntry(Entry*);
-    bool didGetFile(File*);
-    void didRead();
-
-    void reportResult(FileError::ErrorCode errorCode, const String* result = 0, const String* charset = 0)
-    {
-        m_requestCallback->sendSuccess(static_cast<int>(errorCode), result, charset);
-    }
-
-    FileContentRequest(PassRefPtr<RequestFileContentCallback> requestCallback, const String& url, bool readAsText, long long start, long long end, const String& charset)
-        : EventListener(EventListener::CPPEventListenerType)
-        , m_requestCallback(requestCallback)
-        , m_url(ParsedURLString, url)
-        , m_readAsText(readAsText)
-        , m_start(start)
-        , m_end(end)
-        , m_charset(charset) { }
-
-    RefPtr<RequestFileContentCallback> m_requestCallback;
-    KURL m_url;
-    bool m_readAsText;
-    int m_start;
-    long long m_end;
-    String m_mimeType;
-    String m_charset;
-
-    RefPtr<FileReader> m_reader;
-};
-
-void FileContentRequest::start(ExecutionContext* executionContext)
-{
-    ASSERT(executionContext);
-
-    OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &FileContentRequest::didHitError);
-    OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &FileContentRequest::didGetEntry);
-
-    OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
-    LocalFileSystem::from(executionContext)->resolveURL(executionContext, m_url, fileSystemCallbacks.release());
-}
-
-bool FileContentRequest::didGetEntry(Entry* entry)
-{
-    if (entry->isDirectory()) {
-        reportResult(FileError::TYPE_MISMATCH_ERR);
-        return true;
-    }
-
-    if (!entry->filesystem()->executionContext()) {
-        reportResult(FileError::ABORT_ERR);
-        return true;
-    }
-
-    OwnPtr<FileCallback> successCallback = CallbackDispatcherFactory<FileCallback>::create(this, &FileContentRequest::didGetFile);
-    OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &FileContentRequest::didHitError);
-    static_cast<FileEntry*>(entry)->file(successCallback.release(), errorCallback.release());
-
-    m_reader = FileReader::create(entry->filesystem()->executionContext());
-    m_mimeType = MIMETypeRegistry::getMIMETypeForPath(entry->name());
-
-    return true;
-}
-
-bool FileContentRequest::didGetFile(File* file)
-{
-    RefPtr<Blob> blob = file->slice(m_start, m_end);
-    m_reader->setOnload(this);
-    m_reader->setOnerror(this);
-
-    m_reader->readAsArrayBuffer(blob.get(), IGNORE_EXCEPTION);
-    return true;
-}
-
-void FileContentRequest::didRead()
-{
-    RefPtr<ArrayBuffer> buffer = m_reader->arrayBufferResult();
-
-    if (!m_readAsText) {
-        String result = base64Encode(static_cast<char*>(buffer->data()), buffer->byteLength());
-        reportResult(static_cast<FileError::ErrorCode>(0), &result, 0);
-        return;
-    }
-
-    OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create(m_mimeType, m_charset, true);
-    String result = decoder->decode(static_cast<char*>(buffer->data()), buffer->byteLength());
-    result.append(decoder->flush());
-    m_charset = decoder->encoding().name();
-    reportResult(static_cast<FileError::ErrorCode>(0), &result, &m_charset);
-}
-
-class DeleteEntryRequest : public RefCounted<DeleteEntryRequest> {
-public:
-    static PassRefPtr<DeleteEntryRequest> create(PassRefPtr<DeleteEntryCallback> requestCallback, const KURL& url)
-    {
-        return adoptRef(new DeleteEntryRequest(requestCallback, url));
-    }
-
-    virtual ~DeleteEntryRequest()
-    {
-        reportResult(FileError::ABORT_ERR);
-    }
-
-    void start(ExecutionContext*);
-
-private:
-    // CallbackDispatcherFactory doesn't handle 0-arg handleEvent methods
-    class VoidCallbackImpl : public VoidCallback {
-    public:
-        explicit VoidCallbackImpl(PassRefPtr<DeleteEntryRequest> handler)
-            : m_handler(handler)
-        {
-        }
-
-        virtual bool handleEvent() OVERRIDE
-        {
-            return m_handler->didDeleteEntry();
-        }
-
-    private:
-        RefPtr<DeleteEntryRequest> m_handler;
-    };
-
-    bool didHitError(FileError* error)
-    {
-        reportResult(error->code());
-        return true;
-    }
-
-    bool didGetEntry(Entry*);
-    bool didDeleteEntry();
-
-    void reportResult(FileError::ErrorCode errorCode)
-    {
-        m_requestCallback->sendSuccess(static_cast<int>(errorCode));
-    }
-
-    DeleteEntryRequest(PassRefPtr<DeleteEntryCallback> requestCallback, const KURL& url)
-        : m_requestCallback(requestCallback)
-        , m_url(url) { }
-
-    RefPtr<DeleteEntryCallback> m_requestCallback;
-    KURL m_url;
-};
-
-void DeleteEntryRequest::start(ExecutionContext* executionContext)
-{
-    ASSERT(executionContext);
-
-    OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DeleteEntryRequest::didHitError);
-
-    FileSystemType type;
-    String path;
-    if (!DOMFileSystemBase::crackFileSystemURL(m_url, type, path)) {
-        errorCallback->handleEvent(FileError::create(FileError::SYNTAX_ERR).get());
-        return;
-    }
-
-    if (path == "/") {
-        OwnPtr<VoidCallback> successCallback = adoptPtr(new VoidCallbackImpl(this));
-        OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = VoidCallbacks::create(successCallback.release(), errorCallback.release(), 0);
-        LocalFileSystem::from(executionContext)->deleteFileSystem(executionContext, type, fileSystemCallbacks.release());
-    } else {
-        OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &DeleteEntryRequest::didGetEntry);
-        OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
-        LocalFileSystem::from(executionContext)->resolveURL(executionContext, m_url, fileSystemCallbacks.release());
-    }
-}
-
-bool DeleteEntryRequest::didGetEntry(Entry* entry)
-{
-    OwnPtr<VoidCallback> successCallback = adoptPtr(new VoidCallbackImpl(this));
-    OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DeleteEntryRequest::didHitError);
-    if (entry->isDirectory()) {
-        DirectoryEntry* directoryEntry = static_cast<DirectoryEntry*>(entry);
-        directoryEntry->removeRecursively(successCallback.release(), errorCallback.release());
-    } else {
-        entry->remove(successCallback.release(), errorCallback.release());
-    }
-    return true;
-}
-
-bool DeleteEntryRequest::didDeleteEntry()
-{
-    reportResult(static_cast<FileError::ErrorCode>(0));
-    return true;
-}
-
-} // anonymous namespace
-
-// static
-PassOwnPtr<InspectorFileSystemAgent> InspectorFileSystemAgent::create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorCompositeState* state)
-{
-    return adoptPtr(new InspectorFileSystemAgent(instrumentingAgents, pageAgent, state));
-}
-
-InspectorFileSystemAgent::~InspectorFileSystemAgent()
-{
-}
-
-void InspectorFileSystemAgent::enable(ErrorString*)
-{
-    if (m_enabled)
-        return;
-    m_enabled = true;
-    m_state->setBoolean(FileSystemAgentState::fileSystemAgentEnabled, m_enabled);
-}
-
-void InspectorFileSystemAgent::disable(ErrorString*)
-{
-    if (!m_enabled)
-        return;
-    m_enabled = false;
-    m_state->setBoolean(FileSystemAgentState::fileSystemAgentEnabled, m_enabled);
-}
-
-void InspectorFileSystemAgent::requestFileSystemRoot(ErrorString* error, const String& origin, const String& type, PassRefPtr<RequestFileSystemRootCallback> requestCallback)
-{
-    if (!assertEnabled(error))
-        return;
-
-    ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::createFromString(origin).get());
-    if (!executionContext)
-        return;
-
-    FileSystemRootRequest::create(requestCallback, type)->start(executionContext);
-}
-
-void InspectorFileSystemAgent::requestDirectoryContent(ErrorString* error, const String& url, PassRefPtr<RequestDirectoryContentCallback> requestCallback)
-{
-    if (!assertEnabled(error))
-        return;
-
-    ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::createFromString(url).get());
-    if (!executionContext)
-        return;
-
-    DirectoryContentRequest::create(requestCallback, url)->start(executionContext);
-}
-
-void InspectorFileSystemAgent::requestMetadata(ErrorString* error, const String& url, PassRefPtr<RequestMetadataCallback> requestCallback)
-{
-    if (!assertEnabled(error))
-        return;
-
-    ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::createFromString(url).get());
-    if (!executionContext)
-        return;
-
-    MetadataRequest::create(requestCallback, url)->start(executionContext);
-}
-
-void InspectorFileSystemAgent::requestFileContent(ErrorString* error, const String& url, bool readAsText, const int* start, const int* end, const String* charset, PassRefPtr<RequestFileContentCallback> requestCallback)
-{
-    if (!assertEnabled(error))
-        return;
-
-    ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::createFromString(url).get());
-    if (!executionContext)
-        return;
-
-    long long startPosition = start ? *start : 0;
-    long long endPosition = end ? *end : std::numeric_limits<long long>::max();
-    FileContentRequest::create(requestCallback, url, readAsText, startPosition, endPosition, charset ? *charset : "")->start(executionContext);
-}
-
-void InspectorFileSystemAgent::deleteEntry(ErrorString* error, const String& urlString, PassRefPtr<DeleteEntryCallback> requestCallback)
-{
-    if (!assertEnabled(error))
-        return;
-
-    KURL url(ParsedURLString, urlString);
-
-    ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::create(url).get());
-    if (!executionContext)
-        return;
-
-    DeleteEntryRequest::create(requestCallback, url)->start(executionContext);
-}
-
-void InspectorFileSystemAgent::clearFrontend()
-{
-    m_enabled = false;
-    m_state->setBoolean(FileSystemAgentState::fileSystemAgentEnabled, m_enabled);
-}
-
-void InspectorFileSystemAgent::restore()
-{
-    m_enabled = m_state->getBoolean(FileSystemAgentState::fileSystemAgentEnabled);
-}
-
-InspectorFileSystemAgent::InspectorFileSystemAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorCompositeState* state)
-    : InspectorBaseAgent<InspectorFileSystemAgent>("FileSystem", instrumentingAgents, state)
-    , m_pageAgent(pageAgent)
-    , m_enabled(false)
-{
-    ASSERT(instrumentingAgents);
-    ASSERT(state);
-    ASSERT(m_pageAgent);
-}
-
-bool InspectorFileSystemAgent::assertEnabled(ErrorString* error)
-{
-    if (!m_enabled) {
-        *error = "FileSystem agent is not enabled.";
-        return false;
-    }
-    return true;
-}
-
-ExecutionContext* InspectorFileSystemAgent::assertExecutionContextForOrigin(ErrorString* error, SecurityOrigin* origin)
-{
-    for (Frame* frame = m_pageAgent->mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (frame->document() && frame->document()->securityOrigin()->isSameSchemeHostPort(origin))
-            return frame->document();
-    }
-
-    *error = "No frame is available for the request";
-    return 0;
-}
-
-} // namespace WebCore
diff --git a/Source/core/inspector/InspectorFileSystemAgent.h b/Source/core/inspector/InspectorFileSystemAgent.h
deleted file mode 100644
index 24e68ab..0000000
--- a/Source/core/inspector/InspectorFileSystemAgent.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2011, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef InspectorFileSystemAgent_h
-#define InspectorFileSystemAgent_h
-
-#include "core/inspector/InspectorBaseAgent.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-class InspectorPageAgent;
-class ExecutionContext;
-class SecurityOrigin;
-
-class InspectorFileSystemAgent : public InspectorBaseAgent<InspectorFileSystemAgent>, public InspectorBackendDispatcher::FileSystemCommandHandler {
-public:
-    static PassOwnPtr<InspectorFileSystemAgent> create(InstrumentingAgents*, InspectorPageAgent*, InspectorCompositeState*);
-    virtual ~InspectorFileSystemAgent();
-
-    virtual void enable(ErrorString*) OVERRIDE;
-    virtual void disable(ErrorString*) OVERRIDE;
-
-    virtual void requestFileSystemRoot(ErrorString*, const String& origin, const String& typeString, PassRefPtr<RequestFileSystemRootCallback>) OVERRIDE;
-    virtual void requestDirectoryContent(ErrorString*, const String& url, PassRefPtr<RequestDirectoryContentCallback>) OVERRIDE;
-    virtual void requestMetadata(ErrorString*, const String& url, PassRefPtr<RequestMetadataCallback>) OVERRIDE;
-    virtual void requestFileContent(ErrorString*, const String& url, bool readAsText, const int* start, const int* end, const String* charset, PassRefPtr<RequestFileContentCallback>) OVERRIDE;
-    virtual void deleteEntry(ErrorString*, const String& url, PassRefPtr<DeleteEntryCallback>) OVERRIDE;
-
-    virtual void clearFrontend() OVERRIDE;
-    virtual void restore() OVERRIDE;
-
-private:
-    InspectorFileSystemAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorCompositeState*);
-    bool assertEnabled(ErrorString*);
-    ExecutionContext* assertExecutionContextForOrigin(ErrorString*, SecurityOrigin*);
-
-    InspectorPageAgent* m_pageAgent;
-    bool m_enabled;
-};
-
-} // namespace WebCore
-
-#endif // InspectorFileSystemAgent_h
diff --git a/Source/core/inspector/InspectorFrontendHost.cpp b/Source/core/inspector/InspectorFrontendHost.cpp
index 20f2160..a6035e0 100644
--- a/Source/core/inspector/InspectorFrontendHost.cpp
+++ b/Source/core/inspector/InspectorFrontendHost.cpp
@@ -32,21 +32,19 @@
 
 #include "bindings/v8/ScriptFunctionCall.h"
 #include "bindings/v8/ScriptState.h"
+#include "core/clipboard/Pasteboard.h"
 #include "core/fetch/ResourceFetcher.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/frame/Frame.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorFrontendClient.h"
 #include "core/loader/FrameLoader.h"
 #include "core/page/ContextMenuController.h"
 #include "core/page/ContextMenuProvider.h"
 #include "core/page/Page.h"
-#include "core/platform/Pasteboard.h"
 #include "core/rendering/RenderTheme.h"
-#include "modules/filesystem/DOMFileSystem.h"
 #include "platform/ContextMenu.h"
 #include "platform/ContextMenuItem.h"
-#include "platform/JSONValues.h"
 #include "platform/SharedBuffer.h"
 #include "platform/UserGestureIndicator.h"
 #include "platform/network/ResourceError.h"
@@ -55,7 +53,7 @@
 
 namespace WebCore {
 
-class FrontendMenuProvider : public ContextMenuProvider {
+class FrontendMenuProvider FINAL : public ContextMenuProvider {
 public:
     static PassRefPtr<FrontendMenuProvider> create(InspectorFrontendHost* frontendHost, ScriptObject frontendApiObject, const Vector<ContextMenuItem>& items)
     {
@@ -81,13 +79,13 @@
         contextMenuCleared();
     }
 
-    virtual void populateContextMenu(ContextMenu* menu)
+    virtual void populateContextMenu(ContextMenu* menu) OVERRIDE
     {
         for (size_t i = 0; i < m_items.size(); ++i)
             menu->appendItem(m_items[i]);
     }
 
-    virtual void contextMenuItemSelected(const ContextMenuItem* item)
+    virtual void contextMenuItemSelected(const ContextMenuItem* item) OVERRIDE
     {
         if (m_frontendHost) {
             UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
@@ -99,7 +97,7 @@
         }
     }
 
-    virtual void contextMenuCleared()
+    virtual void contextMenuCleared() OVERRIDE
     {
         if (m_frontendHost) {
             ScriptFunctionCall function(m_frontendApiObject, "contextMenuCleared");
@@ -141,6 +139,11 @@
     m_frontendPage->mainFrame()->setPageAndTextZoomFactors(zoom, 1);
 }
 
+float InspectorFrontendHost::zoomFactor()
+{
+    return m_frontendPage->mainFrame()->pageZoomFactor();
+}
+
 void InspectorFrontendHost::inspectedURLChanged(const String& newURL)
 {
     if (m_client)
@@ -188,33 +191,12 @@
 
 String InspectorFrontendHost::getSelectionBackgroundColor()
 {
-    Color color = RenderTheme::theme().activeSelectionBackgroundColor();
-    return color.isValid() ? color.serialized() : "";
+    return RenderTheme::theme().activeSelectionBackgroundColor().serialized();
 }
 
 String InspectorFrontendHost::getSelectionForegroundColor()
 {
-    Color color = RenderTheme::theme().activeSelectionForegroundColor();
-    return color.isValid() ? color.serialized() : "";
-}
-
-PassRefPtr<DOMFileSystem> InspectorFrontendHost::isolatedFileSystem(const String& fileSystemName, const String& rootURL)
-{
-    ExecutionContext* context = m_frontendPage->mainFrame()->document();
-    return DOMFileSystem::create(context, fileSystemName, FileSystemTypeIsolated, KURL(ParsedURLString, rootURL));
-}
-
-void InspectorFrontendHost::upgradeDraggedFileSystemPermissions(DOMFileSystem* domFileSystem)
-{
-    if (!m_client)
-        return;
-    RefPtr<JSONObject> message = JSONObject::create();
-    message->setNumber("id", 0);
-    message->setString("method", "upgradeDraggedFileSystemPermissions");
-    RefPtr<JSONArray> params = JSONArray::create();
-    message->setArray("params", params);
-    params->pushString(domFileSystem->rootURL().string());
-    sendMessageToEmbedder(message->toJSONString());
+    return RenderTheme::theme().activeSelectionForegroundColor().serialized();
 }
 
 bool InspectorFrontendHost::isUnderTest()
diff --git a/Source/core/inspector/InspectorFrontendHost.h b/Source/core/inspector/InspectorFrontendHost.h
index 1bccdca..a6c7908 100644
--- a/Source/core/inspector/InspectorFrontendHost.h
+++ b/Source/core/inspector/InspectorFrontendHost.h
@@ -37,7 +37,6 @@
 namespace WebCore {
 
 class ContextMenuItem;
-class DOMFileSystem;
 class Event;
 class FrontendMenuProvider;
 class InspectorFrontendClient;
@@ -54,6 +53,7 @@
     void disconnectClient();
 
     void setZoomFactor(float);
+    float zoomFactor();
     void inspectedURLChanged(const String&);
 
     void setInjectedScriptForOrigin(const String& origin, const String& script);
@@ -68,11 +68,10 @@
     String getSelectionBackgroundColor();
     String getSelectionForegroundColor();
 
-    PassRefPtr<DOMFileSystem> isolatedFileSystem(const String& fileSystemName, const String& rootURL);
-    void upgradeDraggedFileSystemPermissions(DOMFileSystem*);
-
     bool isUnderTest();
 
+    Page* frontendPage() { return m_frontendPage; }
+
 private:
     friend class FrontendMenuProvider;
     InspectorFrontendHost(InspectorFrontendClient* client, Page* frontendPage);
diff --git a/Source/core/inspector/InspectorFrontendHost.idl b/Source/core/inspector/InspectorFrontendHost.idl
index 467e7aa..a9102bc 100644
--- a/Source/core/inspector/InspectorFrontendHost.idl
+++ b/Source/core/inspector/InspectorFrontendHost.idl
@@ -33,7 +33,9 @@
 [
     NoInterfaceObject
 ] interface InspectorFrontendHost {
+    // FIXME: setZoomFactor is here only for old frontends. Remove in M38.
     void setZoomFactor(float zoom);
+    float zoomFactor();
     void inspectedURLChanged(DOMString newURL);
 
     void setInjectedScriptForOrigin(DOMString origin, DOMString script);
@@ -53,8 +55,5 @@
     DOMString getSelectionBackgroundColor();
     DOMString getSelectionForegroundColor();
 
-    DOMFileSystem isolatedFileSystem(DOMString fileSystemId, DOMString registeredName);
-    void upgradeDraggedFileSystemPermissions(DOMFileSystem domFileSystem);
-
     boolean isUnderTest();
 };
diff --git a/Source/core/inspector/InspectorHeapProfilerAgent.cpp b/Source/core/inspector/InspectorHeapProfilerAgent.cpp
index fd67c24..28575a3 100644
--- a/Source/core/inspector/InspectorHeapProfilerAgent.cpp
+++ b/Source/core/inspector/InspectorHeapProfilerAgent.cpp
@@ -41,6 +41,8 @@
 
 namespace WebCore {
 
+typedef uint32_t SnapshotObjectId;
+
 namespace HeapProfilerAgentState {
 static const char heapProfilerEnabled[] = "heapProfilerEnabled";
 }
@@ -57,13 +59,13 @@
     Timer<HeapStatsUpdateTask> m_timer;
 };
 
-PassOwnPtr<InspectorHeapProfilerAgent> InspectorHeapProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
+PassOwnPtr<InspectorHeapProfilerAgent> InspectorHeapProfilerAgent::create(InjectedScriptManager* injectedScriptManager)
 {
-    return adoptPtr(new InspectorHeapProfilerAgent(instrumentingAgents, inspectorState, injectedScriptManager));
+    return adoptPtr(new InspectorHeapProfilerAgent(injectedScriptManager));
 }
 
-InspectorHeapProfilerAgent::InspectorHeapProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
-    : InspectorBaseAgent<InspectorHeapProfilerAgent>("HeapProfiler", instrumentingAgents, inspectorState)
+InspectorHeapProfilerAgent::InspectorHeapProfilerAgent(InjectedScriptManager* injectedScriptManager)
+    : InspectorBaseAgent<InspectorHeapProfilerAgent>("HeapProfiler")
     , m_injectedScriptManager(injectedScriptManager)
     , m_frontend(0)
     , m_nextUserInitiatedHeapSnapshotNumber(1)
@@ -74,25 +76,6 @@
 {
 }
 
-void InspectorHeapProfilerAgent::clearProfiles(ErrorString*)
-{
-    m_snapshots.clear();
-    m_nextUserInitiatedHeapSnapshotNumber = 1;
-    stopTrackingHeapObjectsInternal();
-    resetFrontendProfiles();
-    m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
-}
-
-void InspectorHeapProfilerAgent::resetFrontendProfiles()
-{
-    if (!m_frontend)
-        return;
-    if (!m_state->getBoolean(HeapProfilerAgentState::heapProfilerEnabled))
-        return;
-    if (m_snapshots.isEmpty())
-        m_frontend->resetProfiles();
-}
-
 void InspectorHeapProfilerAgent::setFrontend(InspectorFrontend* frontend)
 {
     m_frontend = frontend->heapprofiler();
@@ -101,14 +84,19 @@
 void InspectorHeapProfilerAgent::clearFrontend()
 {
     m_frontend = 0;
+
+    m_nextUserInitiatedHeapSnapshotNumber = 1;
+    stopTrackingHeapObjectsInternal();
+    m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
+
     ErrorString error;
-    clearProfiles(&error);
     disable(&error);
 }
 
 void InspectorHeapProfilerAgent::restore()
 {
-    resetFrontendProfiles();
+    if (m_state->getBoolean(HeapProfilerAgentState::heapProfilerEnabled))
+        m_frontend->resetProfiles();
 }
 
 void InspectorHeapProfilerAgent::collectGarbage(WebCore::ErrorString*)
@@ -116,15 +104,6 @@
     ScriptProfiler::collectGarbage();
 }
 
-PassRefPtr<TypeBuilder::HeapProfiler::ProfileHeader> InspectorHeapProfilerAgent::createSnapshotHeader(const ScriptHeapSnapshot& snapshot)
-{
-    RefPtr<TypeBuilder::HeapProfiler::ProfileHeader> header = TypeBuilder::HeapProfiler::ProfileHeader::create()
-        .setUid(snapshot.uid())
-        .setTitle(snapshot.title());
-    header->setMaxJSObjectId(snapshot.maxSnapshotJSObjectId());
-    return header.release();
-}
-
 InspectorHeapProfilerAgent::HeapStatsUpdateTask::HeapStatsUpdateTask(InspectorHeapProfilerAgent* heapProfilerAgent)
     : m_heapProfilerAgent(heapProfilerAgent)
     , m_timer(this, &HeapStatsUpdateTask::onTimer)
@@ -144,7 +123,7 @@
     m_timer.startRepeating(0.05);
 }
 
-class InspectorHeapProfilerAgent::HeapStatsStream : public ScriptProfiler::OutputStream {
+class InspectorHeapProfilerAgent::HeapStatsStream FINAL : public ScriptProfiler::OutputStream {
 public:
     HeapStatsStream(InspectorHeapProfilerAgent* heapProfilerAgent)
         : m_heapProfilerAgent(heapProfilerAgent)
@@ -161,11 +140,11 @@
     InspectorHeapProfilerAgent* m_heapProfilerAgent;
 };
 
-void InspectorHeapProfilerAgent::startTrackingHeapObjects(ErrorString*)
+void InspectorHeapProfilerAgent::startTrackingHeapObjects(ErrorString*, const bool* trackAllocations)
 {
     if (m_heapStatsUpdateTask)
         return;
-    ScriptProfiler::startTrackingHeapObjects();
+    ScriptProfiler::startTrackingHeapObjects(trackAllocations && *trackAllocations);
     m_heapStatsUpdateTask = adoptPtr(new HeapStatsUpdateTask(this));
     m_heapStatsUpdateTask->startTimer();
 }
@@ -217,59 +196,32 @@
 void InspectorHeapProfilerAgent::disable(ErrorString* error)
 {
     stopTrackingHeapObjectsInternal();
+    ScriptProfiler::clearHeapObjectIds();
     m_state->setBoolean(HeapProfilerAgentState::heapProfilerEnabled, false);
 }
 
-void InspectorHeapProfilerAgent::getHeapSnapshot(ErrorString* errorString, int rawUid)
+void InspectorHeapProfilerAgent::takeHeapSnapshot(ErrorString* errorString, const bool* reportProgress)
 {
-    class OutputStream : public ScriptHeapSnapshot::OutputStream {
-    public:
-        OutputStream(InspectorFrontend::HeapProfiler* frontend, unsigned uid)
-            : m_frontend(frontend), m_uid(uid) { }
-        void Write(const String& chunk) { m_frontend->addHeapSnapshotChunk(m_uid, chunk); }
-        void Close() { }
-    private:
-        InspectorFrontend::HeapProfiler* m_frontend;
-        int m_uid;
-    };
-
-    unsigned uid = static_cast<unsigned>(rawUid);
-    IdToHeapSnapshotMap::iterator it = m_snapshots.find(uid);
-    if (it == m_snapshots.end()) {
-        *errorString = "Profile wasn't found";
-        return;
-    }
-    RefPtr<ScriptHeapSnapshot> snapshot = it->value;
-    if (m_frontend) {
-        OutputStream stream(m_frontend, uid);
-        snapshot->writeJSON(&stream);
-    }
-}
-
-void InspectorHeapProfilerAgent::removeProfile(ErrorString*, int rawUid)
-{
-    unsigned uid = static_cast<unsigned>(rawUid);
-    if (m_snapshots.contains(uid))
-        m_snapshots.remove(uid);
-}
-
-void InspectorHeapProfilerAgent::takeHeapSnapshot(ErrorString*, const bool* reportProgress)
-{
-    class HeapSnapshotProgress: public ScriptProfiler::HeapSnapshotProgress {
+    class HeapSnapshotProgress FINAL : public ScriptProfiler::HeapSnapshotProgress {
     public:
         explicit HeapSnapshotProgress(InspectorFrontend::HeapProfiler* frontend)
             : m_frontend(frontend) { }
-        void Start(int totalWork)
+        virtual void Start(int totalWork) OVERRIDE
         {
             m_totalWork = totalWork;
         }
-        void Worked(int workDone)
+        virtual void Worked(int workDone) OVERRIDE
         {
             if (m_frontend)
-                m_frontend->reportHeapSnapshotProgress(workDone, m_totalWork);
+                m_frontend->reportHeapSnapshotProgress(workDone, m_totalWork, 0);
         }
-        void Done() { }
-        bool isCanceled() { return false; }
+        virtual void Done() OVERRIDE
+        {
+            const bool finished = true;
+            if (m_frontend)
+                m_frontend->reportHeapSnapshotProgress(m_totalWork, m_totalWork, &finished);
+        }
+        virtual bool isCanceled() OVERRIDE { return false; }
     private:
         InspectorFrontend::HeapProfiler* m_frontend;
         int m_totalWork;
@@ -278,10 +230,24 @@
     String title = "Snapshot " + String::number(m_nextUserInitiatedHeapSnapshotNumber++);
     HeapSnapshotProgress progress(reportProgress && *reportProgress ? m_frontend : 0);
     RefPtr<ScriptHeapSnapshot> snapshot = ScriptProfiler::takeHeapSnapshot(title, &progress);
-    if (snapshot) {
-        m_snapshots.add(snapshot->uid(), snapshot);
-        if (m_frontend)
-            m_frontend->addProfileHeader(createSnapshotHeader(*snapshot));
+    if (!snapshot) {
+        *errorString = "Failed to take heap snapshot";
+        return;
+    }
+
+    class OutputStream : public ScriptHeapSnapshot::OutputStream {
+    public:
+        explicit OutputStream(InspectorFrontend::HeapProfiler* frontend)
+            : m_frontend(frontend) { }
+        void Write(const String& chunk) { m_frontend->addHeapSnapshotChunk(chunk); }
+        void Close() { }
+    private:
+        InspectorFrontend::HeapProfiler* m_frontend;
+    };
+
+    if (m_frontend) {
+        OutputStream stream(m_frontend);
+        snapshot->writeJSON(&stream);
     }
 }
 
diff --git a/Source/core/inspector/InspectorHeapProfilerAgent.h b/Source/core/inspector/InspectorHeapProfilerAgent.h
index 65ea526..e9207a8 100644
--- a/Source/core/inspector/InspectorHeapProfilerAgent.h
+++ b/Source/core/inspector/InspectorHeapProfilerAgent.h
@@ -48,50 +48,42 @@
 
 typedef String ErrorString;
 
-class InspectorHeapProfilerAgent : public InspectorBaseAgent<InspectorHeapProfilerAgent>, public InspectorBackendDispatcher::HeapProfilerCommandHandler {
+class InspectorHeapProfilerAgent FINAL : public InspectorBaseAgent<InspectorHeapProfilerAgent>, public InspectorBackendDispatcher::HeapProfilerCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorHeapProfilerAgent); WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<InspectorHeapProfilerAgent> create(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*);
+    static PassOwnPtr<InspectorHeapProfilerAgent> create(InjectedScriptManager*);
     virtual ~InspectorHeapProfilerAgent();
 
-    virtual void collectGarbage(ErrorString*);
-    virtual void clearProfiles(ErrorString*);
+    virtual void collectGarbage(ErrorString*) OVERRIDE;
 
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void getHeapSnapshot(ErrorString*, int uid);
-    virtual void removeProfile(ErrorString*, int uid);
-    virtual void startTrackingHeapObjects(ErrorString*);
-    virtual void stopTrackingHeapObjects(ErrorString*, const bool* reportProgress);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void startTrackingHeapObjects(ErrorString*, const bool* trackAllocations) OVERRIDE;
+    virtual void stopTrackingHeapObjects(ErrorString*, const bool* reportProgress) OVERRIDE;
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
 
-    virtual void takeHeapSnapshot(ErrorString*, const bool* reportProgress);
+    virtual void takeHeapSnapshot(ErrorString*, const bool* reportProgress) OVERRIDE;
 
-    virtual void getObjectByHeapObjectId(ErrorString*, const String& heapSnapshotObjectId, const String* objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& result);
-    virtual void getHeapObjectId(ErrorString*, const String& objectId, String* heapSnapshotObjectId);
+    virtual void getObjectByHeapObjectId(ErrorString*, const String& heapSnapshotObjectId, const String* objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& result) OVERRIDE;
+    virtual void getHeapObjectId(ErrorString*, const String& objectId, String* heapSnapshotObjectId) OVERRIDE;
 
 private:
     class HeapStatsStream;
     class HeapStatsUpdateTask;
 
-    InspectorHeapProfilerAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*);
+    explicit InspectorHeapProfilerAgent(InjectedScriptManager*);
 
-    typedef HashMap<unsigned, RefPtr<ScriptHeapSnapshot> > IdToHeapSnapshotMap;
-
-    void resetFrontendProfiles();
     void requestHeapStatsUpdate();
     void pushHeapStatsUpdate(const uint32_t* const data, const int size);
 
-    PassRefPtr<TypeBuilder::HeapProfiler::ProfileHeader> createSnapshotHeader(const ScriptHeapSnapshot&);
     void stopTrackingHeapObjectsInternal();
 
     InjectedScriptManager* m_injectedScriptManager;
     InspectorFrontend::HeapProfiler* m_frontend;
     unsigned m_nextUserInitiatedHeapSnapshotNumber;
-    IdToHeapSnapshotMap m_snapshots;
     OwnPtr<HeapStatsUpdateTask> m_heapStatsUpdateTask;
 };
 
diff --git a/Source/core/inspector/InspectorHistory.cpp b/Source/core/inspector/InspectorHistory.cpp
index e882744..556d4bb 100644
--- a/Source/core/inspector/InspectorHistory.cpp
+++ b/Source/core/inspector/InspectorHistory.cpp
@@ -39,17 +39,17 @@
 
 namespace {
 
-class UndoableStateMark : public InspectorHistory::Action {
+class UndoableStateMark FINAL : public InspectorHistory::Action {
 public:
     UndoableStateMark() : InspectorHistory::Action("[UndoableState]") { }
 
-    virtual bool perform(ExceptionState&) { return true; }
+    virtual bool perform(ExceptionState&) OVERRIDE { return true; }
 
-    virtual bool undo(ExceptionState&) { return true; }
+    virtual bool undo(ExceptionState&) OVERRIDE { return true; }
 
-    virtual bool redo(ExceptionState&) { return true; }
+    virtual bool redo(ExceptionState&) OVERRIDE { return true; }
 
-    virtual bool isUndoableStateMark() { return true; }
+    virtual bool isUndoableStateMark() OVERRIDE { return true; }
 };
 
 }
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.cpp b/Source/core/inspector/InspectorIndexedDBAgent.cpp
deleted file mode 100644
index c271a57..0000000
--- a/Source/core/inspector/InspectorIndexedDBAgent.cpp
+++ /dev/null
@@ -1,773 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/inspector/InspectorIndexedDBAgent.h"
-
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "bindings/v8/ScriptController.h"
-#include "core/dom/DOMStringList.h"
-#include "core/dom/Document.h"
-#include "core/events/Event.h"
-#include "core/events/EventListener.h"
-#include "core/inspector/InjectedScript.h"
-#include "core/inspector/InspectorPageAgent.h"
-#include "core/inspector/InspectorState.h"
-#include "core/frame/Frame.h"
-#include "modules/indexeddb/DOMWindowIndexedDatabase.h"
-#include "modules/indexeddb/IDBCursor.h"
-#include "modules/indexeddb/IDBCursorWithValue.h"
-#include "modules/indexeddb/IDBDatabase.h"
-#include "modules/indexeddb/IDBFactory.h"
-#include "modules/indexeddb/IDBIndex.h"
-#include "modules/indexeddb/IDBKey.h"
-#include "modules/indexeddb/IDBKeyPath.h"
-#include "modules/indexeddb/IDBKeyRange.h"
-#include "modules/indexeddb/IDBMetadata.h"
-#include "modules/indexeddb/IDBObjectStore.h"
-#include "modules/indexeddb/IDBOpenDBRequest.h"
-#include "modules/indexeddb/IDBPendingTransactionMonitor.h"
-#include "modules/indexeddb/IDBRequest.h"
-#include "modules/indexeddb/IDBTransaction.h"
-#include "platform/JSONValues.h"
-#include "platform/weborigin/SecurityOrigin.h"
-#include "wtf/Vector.h"
-
-using WebCore::TypeBuilder::Array;
-using WebCore::TypeBuilder::IndexedDB::DatabaseWithObjectStores;
-using WebCore::TypeBuilder::IndexedDB::DataEntry;
-using WebCore::TypeBuilder::IndexedDB::Key;
-using WebCore::TypeBuilder::IndexedDB::KeyPath;
-using WebCore::TypeBuilder::IndexedDB::KeyRange;
-using WebCore::TypeBuilder::IndexedDB::ObjectStore;
-using WebCore::TypeBuilder::IndexedDB::ObjectStoreIndex;
-
-typedef WebCore::InspectorBackendDispatcher::IndexedDBCommandHandler::RequestDatabaseNamesCallback RequestDatabaseNamesCallback;
-typedef WebCore::InspectorBackendDispatcher::IndexedDBCommandHandler::RequestDatabaseCallback RequestDatabaseCallback;
-typedef WebCore::InspectorBackendDispatcher::IndexedDBCommandHandler::RequestDataCallback RequestDataCallback;
-typedef WebCore::InspectorBackendDispatcher::CallbackBase RequestCallback;
-typedef WebCore::InspectorBackendDispatcher::IndexedDBCommandHandler::ClearObjectStoreCallback ClearObjectStoreCallback;
-
-namespace WebCore {
-
-namespace IndexedDBAgentState {
-static const char indexedDBAgentEnabled[] = "indexedDBAgentEnabled";
-};
-
-namespace {
-
-class GetDatabaseNamesCallback : public EventListener {
-    WTF_MAKE_NONCOPYABLE(GetDatabaseNamesCallback);
-public:
-    static PassRefPtr<GetDatabaseNamesCallback> create(PassRefPtr<RequestDatabaseNamesCallback> requestCallback, const String& securityOrigin)
-    {
-        return adoptRef(new GetDatabaseNamesCallback(requestCallback, securityOrigin));
-    }
-
-    virtual ~GetDatabaseNamesCallback() { }
-
-    virtual bool operator==(const EventListener& other) OVERRIDE
-    {
-        return this == &other;
-    }
-
-    virtual void handleEvent(ExecutionContext*, Event* event) OVERRIDE
-    {
-        if (!m_requestCallback->isActive())
-            return;
-        if (event->type() != EventTypeNames::success) {
-            m_requestCallback->sendFailure("Unexpected event type.");
-            return;
-        }
-
-        IDBRequest* idbRequest = static_cast<IDBRequest*>(event->target());
-        RefPtr<IDBAny> requestResult = idbRequest->resultAsAny();
-        if (requestResult->type() != IDBAny::DOMStringListType) {
-            m_requestCallback->sendFailure("Unexpected result type.");
-            return;
-        }
-
-        RefPtr<DOMStringList> databaseNamesList = requestResult->domStringList();
-        RefPtr<TypeBuilder::Array<String> > databaseNames = TypeBuilder::Array<String>::create();
-        for (size_t i = 0; i < databaseNamesList->length(); ++i)
-            databaseNames->addItem(databaseNamesList->item(i));
-        m_requestCallback->sendSuccess(databaseNames.release());
-    }
-
-private:
-    GetDatabaseNamesCallback(PassRefPtr<RequestDatabaseNamesCallback> requestCallback, const String& securityOrigin)
-        : EventListener(EventListener::CPPEventListenerType)
-        , m_requestCallback(requestCallback)
-        , m_securityOrigin(securityOrigin) { }
-    RefPtr<RequestDatabaseNamesCallback> m_requestCallback;
-    String m_securityOrigin;
-};
-
-class ExecutableWithDatabase : public RefCounted<ExecutableWithDatabase> {
-public:
-    ExecutableWithDatabase(ExecutionContext* context)
-        : m_context(context) { }
-    virtual ~ExecutableWithDatabase() { };
-    void start(IDBFactory*, SecurityOrigin*, const String& databaseName);
-    virtual void execute(PassRefPtr<IDBDatabase>) = 0;
-    virtual RequestCallback* requestCallback() = 0;
-    ExecutionContext* context() { return m_context; };
-private:
-    ExecutionContext* m_context;
-};
-
-class OpenDatabaseCallback : public EventListener {
-public:
-    static PassRefPtr<OpenDatabaseCallback> create(ExecutableWithDatabase* executableWithDatabase)
-    {
-        return adoptRef(new OpenDatabaseCallback(executableWithDatabase));
-    }
-
-    virtual ~OpenDatabaseCallback() { }
-
-    virtual bool operator==(const EventListener& other) OVERRIDE
-    {
-        return this == &other;
-    }
-
-    virtual void handleEvent(ExecutionContext*, Event* event) OVERRIDE
-    {
-        if (event->type() != EventTypeNames::success) {
-            m_executableWithDatabase->requestCallback()->sendFailure("Unexpected event type.");
-            return;
-        }
-
-        IDBOpenDBRequest* idbOpenDBRequest = static_cast<IDBOpenDBRequest*>(event->target());
-        RefPtr<IDBAny> requestResult = idbOpenDBRequest->resultAsAny();
-        if (requestResult->type() != IDBAny::IDBDatabaseType) {
-            m_executableWithDatabase->requestCallback()->sendFailure("Unexpected result type.");
-            return;
-        }
-
-        RefPtr<IDBDatabase> idbDatabase = requestResult->idbDatabase();
-        m_executableWithDatabase->execute(idbDatabase);
-        IDBPendingTransactionMonitor::deactivateNewTransactions();
-        idbDatabase->close();
-    }
-
-private:
-    OpenDatabaseCallback(ExecutableWithDatabase* executableWithDatabase)
-        : EventListener(EventListener::CPPEventListenerType)
-        , m_executableWithDatabase(executableWithDatabase) { }
-    RefPtr<ExecutableWithDatabase> m_executableWithDatabase;
-};
-
-void ExecutableWithDatabase::start(IDBFactory* idbFactory, SecurityOrigin*, const String& databaseName)
-{
-    RefPtr<OpenDatabaseCallback> callback = OpenDatabaseCallback::create(this);
-    TrackExceptionState exceptionState;
-    RefPtr<IDBOpenDBRequest> idbOpenDBRequest = idbFactory->open(context(), databaseName, exceptionState);
-    if (exceptionState.hadException()) {
-        requestCallback()->sendFailure("Could not open database.");
-        return;
-    }
-    idbOpenDBRequest->addEventListener(EventTypeNames::success, callback, false);
-}
-
-static PassRefPtr<IDBTransaction> transactionForDatabase(ExecutionContext* executionContext, IDBDatabase* idbDatabase, const String& objectStoreName, const String& mode = IDBTransaction::modeReadOnly())
-{
-    TrackExceptionState exceptionState;
-    RefPtr<IDBTransaction> idbTransaction = idbDatabase->transaction(executionContext, objectStoreName, mode, exceptionState);
-    if (exceptionState.hadException())
-        return 0;
-    return idbTransaction;
-}
-
-static PassRefPtr<IDBObjectStore> objectStoreForTransaction(IDBTransaction* idbTransaction, const String& objectStoreName)
-{
-    TrackExceptionState exceptionState;
-    RefPtr<IDBObjectStore> idbObjectStore = idbTransaction->objectStore(objectStoreName, exceptionState);
-    if (exceptionState.hadException())
-        return 0;
-    return idbObjectStore;
-}
-
-static PassRefPtr<IDBIndex> indexForObjectStore(IDBObjectStore* idbObjectStore, const String& indexName)
-{
-    TrackExceptionState exceptionState;
-    RefPtr<IDBIndex> idbIndex = idbObjectStore->index(indexName, exceptionState);
-    if (exceptionState.hadException())
-        return 0;
-    return idbIndex;
-}
-
-static PassRefPtr<KeyPath> keyPathFromIDBKeyPath(const IDBKeyPath& idbKeyPath)
-{
-    RefPtr<KeyPath> keyPath;
-    switch (idbKeyPath.type()) {
-    case IDBKeyPath::NullType:
-        keyPath = KeyPath::create().setType(KeyPath::Type::Null);
-        break;
-    case IDBKeyPath::StringType:
-        keyPath = KeyPath::create().setType(KeyPath::Type::String);
-        keyPath->setString(idbKeyPath.string());
-        break;
-    case IDBKeyPath::ArrayType: {
-        keyPath = KeyPath::create().setType(KeyPath::Type::Array);
-        RefPtr<TypeBuilder::Array<String> > array = TypeBuilder::Array<String>::create();
-        const Vector<String>& stringArray = idbKeyPath.array();
-        for (size_t i = 0; i < stringArray.size(); ++i)
-            array->addItem(stringArray[i]);
-        keyPath->setArray(array);
-        break;
-    }
-    default:
-        ASSERT_NOT_REACHED();
-    }
-
-    return keyPath.release();
-}
-
-class DatabaseLoader : public ExecutableWithDatabase {
-public:
-    static PassRefPtr<DatabaseLoader> create(ExecutionContext* context, PassRefPtr<RequestDatabaseCallback> requestCallback)
-    {
-        return adoptRef(new DatabaseLoader(context, requestCallback));
-    }
-
-    virtual ~DatabaseLoader() { }
-
-    virtual void execute(PassRefPtr<IDBDatabase> prpDatabase)
-    {
-        RefPtr<IDBDatabase> idbDatabase = prpDatabase;
-        if (!requestCallback()->isActive())
-            return;
-
-        const IDBDatabaseMetadata databaseMetadata = idbDatabase->metadata();
-
-        RefPtr<TypeBuilder::Array<TypeBuilder::IndexedDB::ObjectStore> > objectStores = TypeBuilder::Array<TypeBuilder::IndexedDB::ObjectStore>::create();
-
-        for (IDBDatabaseMetadata::ObjectStoreMap::const_iterator it = databaseMetadata.objectStores.begin(); it != databaseMetadata.objectStores.end(); ++it) {
-            const IDBObjectStoreMetadata& objectStoreMetadata = it->value;
-
-            RefPtr<TypeBuilder::Array<TypeBuilder::IndexedDB::ObjectStoreIndex> > indexes = TypeBuilder::Array<TypeBuilder::IndexedDB::ObjectStoreIndex>::create();
-
-            for (IDBObjectStoreMetadata::IndexMap::const_iterator it = objectStoreMetadata.indexes.begin(); it != objectStoreMetadata.indexes.end(); ++it) {
-                const IDBIndexMetadata& indexMetadata = it->value;
-
-                RefPtr<ObjectStoreIndex> objectStoreIndex = ObjectStoreIndex::create()
-                    .setName(indexMetadata.name)
-                    .setKeyPath(keyPathFromIDBKeyPath(indexMetadata.keyPath))
-                    .setUnique(indexMetadata.unique)
-                    .setMultiEntry(indexMetadata.multiEntry);
-                indexes->addItem(objectStoreIndex);
-            }
-
-            RefPtr<ObjectStore> objectStore = ObjectStore::create()
-                .setName(objectStoreMetadata.name)
-                .setKeyPath(keyPathFromIDBKeyPath(objectStoreMetadata.keyPath))
-                .setAutoIncrement(objectStoreMetadata.autoIncrement)
-                .setIndexes(indexes);
-            objectStores->addItem(objectStore);
-        }
-        RefPtr<DatabaseWithObjectStores> result = DatabaseWithObjectStores::create()
-            .setName(databaseMetadata.name)
-            .setIntVersion(databaseMetadata.intVersion)
-            .setVersion(databaseMetadata.version)
-            .setObjectStores(objectStores);
-
-        m_requestCallback->sendSuccess(result);
-    }
-
-    virtual RequestCallback* requestCallback() { return m_requestCallback.get(); }
-private:
-    DatabaseLoader(ExecutionContext* context, PassRefPtr<RequestDatabaseCallback> requestCallback)
-        : ExecutableWithDatabase(context)
-        , m_requestCallback(requestCallback) { }
-    RefPtr<RequestDatabaseCallback> m_requestCallback;
-};
-
-static PassRefPtr<IDBKey> idbKeyFromInspectorObject(JSONObject* key)
-{
-    RefPtr<IDBKey> idbKey;
-
-    String type;
-    if (!key->getString("type", &type))
-        return 0;
-
-    DEFINE_STATIC_LOCAL(String, number, ("number"));
-    DEFINE_STATIC_LOCAL(String, string, ("string"));
-    DEFINE_STATIC_LOCAL(String, date, ("date"));
-    DEFINE_STATIC_LOCAL(String, array, ("array"));
-
-    if (type == number) {
-        double number;
-        if (!key->getNumber("number", &number))
-            return 0;
-        idbKey = IDBKey::createNumber(number);
-    } else if (type == string) {
-        String string;
-        if (!key->getString("string", &string))
-            return 0;
-        idbKey = IDBKey::createString(string);
-    } else if (type == date) {
-        double date;
-        if (!key->getNumber("date", &date))
-            return 0;
-        idbKey = IDBKey::createDate(date);
-    } else if (type == array) {
-        IDBKey::KeyArray keyArray;
-        RefPtr<JSONArray> array = key->getArray("array");
-        for (size_t i = 0; i < array->length(); ++i) {
-            RefPtr<JSONValue> value = array->get(i);
-            RefPtr<JSONObject> object;
-            if (!value->asObject(&object))
-                return 0;
-            keyArray.append(idbKeyFromInspectorObject(object.get()));
-        }
-        idbKey = IDBKey::createArray(keyArray);
-    } else
-        return 0;
-
-    return idbKey.release();
-}
-
-static PassRefPtr<IDBKeyRange> idbKeyRangeFromKeyRange(JSONObject* keyRange)
-{
-    RefPtr<JSONObject> lower = keyRange->getObject("lower");
-    RefPtr<IDBKey> idbLower = lower ? idbKeyFromInspectorObject(lower.get()) : 0;
-    if (lower && !idbLower)
-        return 0;
-
-    RefPtr<JSONObject> upper = keyRange->getObject("upper");
-    RefPtr<IDBKey> idbUpper = upper ? idbKeyFromInspectorObject(upper.get()) : 0;
-    if (upper && !idbUpper)
-        return 0;
-
-    bool lowerOpen;
-    if (!keyRange->getBoolean("lowerOpen", &lowerOpen))
-        return 0;
-    IDBKeyRange::LowerBoundType lowerBoundType = lowerOpen ? IDBKeyRange::LowerBoundOpen : IDBKeyRange::LowerBoundClosed;
-
-    bool upperOpen;
-    if (!keyRange->getBoolean("upperOpen", &upperOpen))
-        return 0;
-    IDBKeyRange::UpperBoundType upperBoundType = upperOpen ? IDBKeyRange::UpperBoundOpen : IDBKeyRange::UpperBoundClosed;
-
-    RefPtr<IDBKeyRange> idbKeyRange = IDBKeyRange::create(idbLower, idbUpper, lowerBoundType, upperBoundType);
-    return idbKeyRange.release();
-}
-
-class DataLoader;
-
-class OpenCursorCallback : public EventListener {
-public:
-    static PassRefPtr<OpenCursorCallback> create(InjectedScript injectedScript, PassRefPtr<RequestDataCallback> requestCallback, int skipCount, unsigned pageSize)
-    {
-        return adoptRef(new OpenCursorCallback(injectedScript, requestCallback, skipCount, pageSize));
-    }
-
-    virtual ~OpenCursorCallback() { }
-
-    virtual bool operator==(const EventListener& other) OVERRIDE
-    {
-        return this == &other;
-    }
-
-    virtual void handleEvent(ExecutionContext* context, Event* event) OVERRIDE
-    {
-        if (event->type() != EventTypeNames::success) {
-            m_requestCallback->sendFailure("Unexpected event type.");
-            return;
-        }
-
-        IDBRequest* idbRequest = static_cast<IDBRequest*>(event->target());
-        RefPtr<IDBAny> requestResult = idbRequest->resultAsAny();
-        if (requestResult->type() == IDBAny::BufferType) {
-            end(false);
-            return;
-        }
-        if (requestResult->type() != IDBAny::IDBCursorWithValueType) {
-            m_requestCallback->sendFailure("Unexpected result type.");
-            return;
-        }
-
-        RefPtr<IDBCursorWithValue> idbCursor = requestResult->idbCursorWithValue();
-
-        if (m_skipCount) {
-            TrackExceptionState exceptionState;
-            idbCursor->advance(m_skipCount, exceptionState);
-            if (exceptionState.hadException())
-                m_requestCallback->sendFailure("Could not advance cursor.");
-            m_skipCount = 0;
-            return;
-        }
-
-        if (m_result->length() == m_pageSize) {
-            end(true);
-            return;
-        }
-
-        // Continue cursor before making injected script calls, otherwise transaction might be finished.
-        TrackExceptionState exceptionState;
-        idbCursor->continueFunction(0, exceptionState);
-        if (exceptionState.hadException()) {
-            m_requestCallback->sendFailure("Could not continue cursor.");
-            return;
-        }
-
-        RefPtr<DataEntry> dataEntry = DataEntry::create()
-            .setKey(m_injectedScript.wrapObject(idbCursor->key(context), String()))
-            .setPrimaryKey(m_injectedScript.wrapObject(idbCursor->primaryKey(context), String()))
-            .setValue(m_injectedScript.wrapObject(idbCursor->value(context), String()));
-        m_result->addItem(dataEntry);
-
-    }
-
-    void end(bool hasMore)
-    {
-        if (!m_requestCallback->isActive())
-            return;
-        m_requestCallback->sendSuccess(m_result.release(), hasMore);
-    }
-
-private:
-    OpenCursorCallback(InjectedScript injectedScript, PassRefPtr<RequestDataCallback> requestCallback, int skipCount, unsigned pageSize)
-        : EventListener(EventListener::CPPEventListenerType)
-        , m_injectedScript(injectedScript)
-        , m_requestCallback(requestCallback)
-        , m_skipCount(skipCount)
-        , m_pageSize(pageSize)
-    {
-        m_result = Array<DataEntry>::create();
-    }
-    InjectedScript m_injectedScript;
-    RefPtr<RequestDataCallback> m_requestCallback;
-    int m_skipCount;
-    unsigned m_pageSize;
-    RefPtr<Array<DataEntry> > m_result;
-};
-
-class DataLoader : public ExecutableWithDatabase {
-public:
-    static PassRefPtr<DataLoader> create(ExecutionContext* context, PassRefPtr<RequestDataCallback> requestCallback, const InjectedScript& injectedScript, const String& objectStoreName, const String& indexName, PassRefPtr<IDBKeyRange> idbKeyRange, int skipCount, unsigned pageSize)
-    {
-        return adoptRef(new DataLoader(context, requestCallback, injectedScript, objectStoreName, indexName, idbKeyRange, skipCount, pageSize));
-    }
-
-    virtual ~DataLoader() { }
-
-    virtual void execute(PassRefPtr<IDBDatabase> prpDatabase)
-    {
-        RefPtr<IDBDatabase> idbDatabase = prpDatabase;
-        if (!requestCallback()->isActive())
-            return;
-        RefPtr<IDBTransaction> idbTransaction = transactionForDatabase(context(), idbDatabase.get(), m_objectStoreName);
-        if (!idbTransaction) {
-            m_requestCallback->sendFailure("Could not get transaction");
-            return;
-        }
-        RefPtr<IDBObjectStore> idbObjectStore = objectStoreForTransaction(idbTransaction.get(), m_objectStoreName);
-        if (!idbObjectStore) {
-            m_requestCallback->sendFailure("Could not get object store");
-            return;
-        }
-
-        RefPtr<OpenCursorCallback> openCursorCallback = OpenCursorCallback::create(m_injectedScript, m_requestCallback, m_skipCount, m_pageSize);
-
-        RefPtr<IDBRequest> idbRequest;
-        if (!m_indexName.isEmpty()) {
-            RefPtr<IDBIndex> idbIndex = indexForObjectStore(idbObjectStore.get(), m_indexName);
-            if (!idbIndex) {
-                m_requestCallback->sendFailure("Could not get index");
-                return;
-            }
-
-            idbRequest = idbIndex->openCursor(context(), PassRefPtr<IDBKeyRange>(m_idbKeyRange), IndexedDB::CursorNext);
-        } else {
-            idbRequest = idbObjectStore->openCursor(context(), PassRefPtr<IDBKeyRange>(m_idbKeyRange), IndexedDB::CursorNext);
-        }
-        idbRequest->addEventListener(EventTypeNames::success, openCursorCallback, false);
-    }
-
-    virtual RequestCallback* requestCallback() { return m_requestCallback.get(); }
-    DataLoader(ExecutionContext* executionContext, PassRefPtr<RequestDataCallback> requestCallback, const InjectedScript& injectedScript, const String& objectStoreName, const String& indexName, PassRefPtr<IDBKeyRange> idbKeyRange, int skipCount, unsigned pageSize)
-        : ExecutableWithDatabase(executionContext)
-        , m_requestCallback(requestCallback)
-        , m_injectedScript(injectedScript)
-        , m_objectStoreName(objectStoreName)
-        , m_indexName(indexName)
-        , m_idbKeyRange(idbKeyRange)
-        , m_skipCount(skipCount)
-        , m_pageSize(pageSize) { }
-    RefPtr<RequestDataCallback> m_requestCallback;
-    InjectedScript m_injectedScript;
-    String m_objectStoreName;
-    String m_indexName;
-    RefPtr<IDBKeyRange> m_idbKeyRange;
-    int m_skipCount;
-    unsigned m_pageSize;
-};
-
-} // namespace
-
-InspectorIndexedDBAgent::InspectorIndexedDBAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, InspectorPageAgent* pageAgent)
-    : InspectorBaseAgent<InspectorIndexedDBAgent>("IndexedDB", instrumentingAgents, state)
-    , m_injectedScriptManager(injectedScriptManager)
-    , m_pageAgent(pageAgent)
-{
-}
-
-InspectorIndexedDBAgent::~InspectorIndexedDBAgent()
-{
-}
-
-void InspectorIndexedDBAgent::clearFrontend()
-{
-    disable(0);
-}
-
-void InspectorIndexedDBAgent::restore()
-{
-    if (m_state->getBoolean(IndexedDBAgentState::indexedDBAgentEnabled)) {
-        ErrorString error;
-        enable(&error);
-    }
-}
-
-void InspectorIndexedDBAgent::enable(ErrorString*)
-{
-    m_state->setBoolean(IndexedDBAgentState::indexedDBAgentEnabled, true);
-}
-
-void InspectorIndexedDBAgent::disable(ErrorString*)
-{
-    m_state->setBoolean(IndexedDBAgentState::indexedDBAgentEnabled, false);
-}
-
-static Document* assertDocument(ErrorString* errorString, Frame* frame)
-{
-    Document* document = frame ? frame->document() : 0;
-
-    if (!document)
-        *errorString = "No document for given frame found";
-
-    return document;
-}
-
-static IDBFactory* assertIDBFactory(ErrorString* errorString, Document* document)
-{
-    DOMWindow* domWindow = document->domWindow();
-    if (!domWindow) {
-        *errorString = "No IndexedDB factory for given frame found";
-        return 0;
-    }
-    IDBFactory* idbFactory = DOMWindowIndexedDatabase::indexedDB(domWindow);
-
-    if (!idbFactory)
-        *errorString = "No IndexedDB factory for given frame found";
-
-    return idbFactory;
-}
-
-void InspectorIndexedDBAgent::requestDatabaseNames(ErrorString* errorString, const String& securityOrigin, PassRefPtr<RequestDatabaseNamesCallback> requestCallback)
-{
-    Frame* frame = m_pageAgent->findFrameWithSecurityOrigin(securityOrigin);
-    Document* document = assertDocument(errorString, frame);
-    if (!document)
-        return;
-    IDBFactory* idbFactory = assertIDBFactory(errorString, document);
-    if (!idbFactory)
-        return;
-
-    // FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
-    v8::HandleScope handleScope(toIsolate(frame));
-    v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
-    ASSERT(!context.IsEmpty());
-    v8::Context::Scope contextScope(context);
-
-    TrackExceptionState exceptionState;
-    RefPtr<IDBRequest> idbRequest = idbFactory->getDatabaseNames(document, exceptionState);
-    if (exceptionState.hadException()) {
-        requestCallback->sendFailure("Could not obtain database names.");
-        return;
-    }
-    idbRequest->addEventListener(EventTypeNames::success, GetDatabaseNamesCallback::create(requestCallback, document->securityOrigin()->toRawString()), false);
-}
-
-void InspectorIndexedDBAgent::requestDatabase(ErrorString* errorString, const String& securityOrigin, const String& databaseName, PassRefPtr<RequestDatabaseCallback> requestCallback)
-{
-    Frame* frame = m_pageAgent->findFrameWithSecurityOrigin(securityOrigin);
-    Document* document = assertDocument(errorString, frame);
-    if (!document)
-        return;
-    IDBFactory* idbFactory = assertIDBFactory(errorString, document);
-    if (!idbFactory)
-        return;
-
-    // FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
-    v8::HandleScope handleScope(toIsolate(frame));
-    v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
-    ASSERT(!context.IsEmpty());
-    v8::Context::Scope contextScope(context);
-
-    RefPtr<DatabaseLoader> databaseLoader = DatabaseLoader::create(document, requestCallback);
-    databaseLoader->start(idbFactory, document->securityOrigin(), databaseName);
-}
-
-void InspectorIndexedDBAgent::requestData(ErrorString* errorString, const String& securityOrigin, const String& databaseName, const String& objectStoreName, const String& indexName, int skipCount, int pageSize, const RefPtr<JSONObject>* keyRange, PassRefPtr<RequestDataCallback> requestCallback)
-{
-    Frame* frame = m_pageAgent->findFrameWithSecurityOrigin(securityOrigin);
-    Document* document = assertDocument(errorString, frame);
-    if (!document)
-        return;
-    IDBFactory* idbFactory = assertIDBFactory(errorString, document);
-    if (!idbFactory)
-        return;
-
-    InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(mainWorldScriptState(frame));
-
-    RefPtr<IDBKeyRange> idbKeyRange = keyRange ? idbKeyRangeFromKeyRange(keyRange->get()) : 0;
-    if (keyRange && !idbKeyRange) {
-        *errorString = "Can not parse key range.";
-        return;
-    }
-
-    // FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
-    v8::HandleScope handleScope(toIsolate(frame));
-    v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
-    ASSERT(!context.IsEmpty());
-    v8::Context::Scope contextScope(context);
-
-    RefPtr<DataLoader> dataLoader = DataLoader::create(document, requestCallback, injectedScript, objectStoreName, indexName, idbKeyRange, skipCount, pageSize);
-    dataLoader->start(idbFactory, document->securityOrigin(), databaseName);
-}
-
-class ClearObjectStoreListener : public EventListener {
-    WTF_MAKE_NONCOPYABLE(ClearObjectStoreListener);
-public:
-    static PassRefPtr<ClearObjectStoreListener> create(PassRefPtr<ClearObjectStoreCallback> requestCallback)
-    {
-        return adoptRef(new ClearObjectStoreListener(requestCallback));
-    }
-
-    virtual ~ClearObjectStoreListener() { }
-
-    virtual bool operator==(const EventListener& other) OVERRIDE
-    {
-        return this == &other;
-    }
-
-    virtual void handleEvent(ExecutionContext*, Event* event) OVERRIDE
-    {
-        if (!m_requestCallback->isActive())
-            return;
-        if (event->type() != EventTypeNames::complete) {
-            m_requestCallback->sendFailure("Unexpected event type.");
-            return;
-        }
-
-        m_requestCallback->sendSuccess();
-    }
-private:
-    ClearObjectStoreListener(PassRefPtr<ClearObjectStoreCallback> requestCallback)
-        : EventListener(EventListener::CPPEventListenerType)
-        , m_requestCallback(requestCallback)
-    {
-    }
-
-    RefPtr<ClearObjectStoreCallback> m_requestCallback;
-};
-
-
-class ClearObjectStore : public ExecutableWithDatabase {
-public:
-    static PassRefPtr<ClearObjectStore> create(ExecutionContext* context, const String& objectStoreName, PassRefPtr<ClearObjectStoreCallback> requestCallback)
-    {
-        return adoptRef(new ClearObjectStore(context, objectStoreName, requestCallback));
-    }
-
-    ClearObjectStore(ExecutionContext* context, const String& objectStoreName, PassRefPtr<ClearObjectStoreCallback> requestCallback)
-        : ExecutableWithDatabase(context)
-        , m_objectStoreName(objectStoreName)
-        , m_requestCallback(requestCallback)
-    {
-    }
-
-    virtual void execute(PassRefPtr<IDBDatabase> prpDatabase)
-    {
-        RefPtr<IDBDatabase> idbDatabase = prpDatabase;
-        if (!requestCallback()->isActive())
-            return;
-        RefPtr<IDBTransaction> idbTransaction = transactionForDatabase(context(), idbDatabase.get(), m_objectStoreName, IDBTransaction::modeReadWrite());
-        if (!idbTransaction) {
-            m_requestCallback->sendFailure("Could not get transaction");
-            return;
-        }
-        RefPtr<IDBObjectStore> idbObjectStore = objectStoreForTransaction(idbTransaction.get(), m_objectStoreName);
-        if (!idbObjectStore) {
-            m_requestCallback->sendFailure("Could not get object store");
-            return;
-        }
-
-        TrackExceptionState exceptionState;
-        RefPtr<IDBRequest> idbRequest = idbObjectStore->clear(context(), exceptionState);
-        ASSERT(!exceptionState.hadException());
-        if (exceptionState.hadException()) {
-            ExceptionCode ec = exceptionState.code();
-            m_requestCallback->sendFailure(String::format("Could not clear object store '%s': %d", m_objectStoreName.utf8().data(), ec));
-            return;
-        }
-        idbTransaction->addEventListener(EventTypeNames::complete, ClearObjectStoreListener::create(m_requestCallback), false);
-    }
-
-    virtual RequestCallback* requestCallback() { return m_requestCallback.get(); }
-private:
-    const String m_objectStoreName;
-    RefPtr<ClearObjectStoreCallback> m_requestCallback;
-};
-
-void InspectorIndexedDBAgent::clearObjectStore(ErrorString* errorString, const String& securityOrigin, const String& databaseName, const String& objectStoreName, PassRefPtr<ClearObjectStoreCallback> requestCallback)
-{
-    Frame* frame = m_pageAgent->findFrameWithSecurityOrigin(securityOrigin);
-    Document* document = assertDocument(errorString, frame);
-    if (!document)
-        return;
-    IDBFactory* idbFactory = assertIDBFactory(errorString, document);
-    if (!idbFactory)
-        return;
-
-    // FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
-    v8::HandleScope handleScope(toIsolate(frame));
-    v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
-    ASSERT(!context.IsEmpty());
-    v8::Context::Scope contextScope(context);
-
-    RefPtr<ClearObjectStore> clearObjectStore = ClearObjectStore::create(document, objectStoreName, requestCallback);
-    clearObjectStore->start(idbFactory, document->securityOrigin(), databaseName);
-}
-
-} // namespace WebCore
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.h b/Source/core/inspector/InspectorIndexedDBAgent.h
deleted file mode 100644
index 237af20..0000000
--- a/Source/core/inspector/InspectorIndexedDBAgent.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef InspectorIndexedDBAgent_h
-#define InspectorIndexedDBAgent_h
-
-#include "core/inspector/InspectorBaseAgent.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class InjectedScriptManager;
-class InspectorPageAgent;
-
-typedef String ErrorString;
-
-class InspectorIndexedDBAgent : public InspectorBaseAgent<InspectorIndexedDBAgent>, public InspectorBackendDispatcher::IndexedDBCommandHandler {
-public:
-    static PassOwnPtr<InspectorIndexedDBAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, InspectorPageAgent* pageAgent)
-    {
-        return adoptPtr(new InspectorIndexedDBAgent(instrumentingAgents, state, injectedScriptManager, pageAgent));
-    }
-    ~InspectorIndexedDBAgent();
-
-    virtual void clearFrontend();
-    virtual void restore();
-
-    // Called from the front-end.
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void requestDatabaseNames(ErrorString*, const String& securityOrigin, PassRefPtr<RequestDatabaseNamesCallback>);
-    virtual void requestDatabase(ErrorString*, const String& securityOrigin, const String& databaseName, PassRefPtr<RequestDatabaseCallback>);
-    virtual void requestData(ErrorString*, const String& securityOrigin, const String& databaseName, const String& objectStoreName, const String& indexName, int skipCount, int pageSize, const RefPtr<JSONObject>* keyRange, PassRefPtr<RequestDataCallback>);
-    virtual void clearObjectStore(ErrorString*, const String& in_securityOrigin, const String& in_databaseName, const String& in_objectStoreName, PassRefPtr<ClearObjectStoreCallback>);
-
-private:
-    InspectorIndexedDBAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, InspectorPageAgent*);
-
-    InjectedScriptManager* m_injectedScriptManager;
-    InspectorPageAgent* m_pageAgent;
-};
-
-} // namespace WebCore
-
-#endif // !defined(InspectorIndexedDBAgent_h)
diff --git a/Source/core/inspector/InspectorInputAgent.cpp b/Source/core/inspector/InspectorInputAgent.cpp
index 342f9ad..65888eb 100644
--- a/Source/core/inspector/InspectorInputAgent.cpp
+++ b/Source/core/inspector/InspectorInputAgent.cpp
@@ -89,8 +89,8 @@
 
 namespace WebCore {
 
-InspectorInputAgent::InspectorInputAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, Page* page, InspectorClient* client)
-    : InspectorBaseAgent<InspectorInputAgent>("Input", instrumentingAgents, inspectorState)
+InspectorInputAgent::InspectorInputAgent(Page* page, InspectorClient* client)
+    : InspectorBaseAgent<InspectorInputAgent>("Input")
     , m_page(page), m_client(client)
 {
 }
diff --git a/Source/core/inspector/InspectorInputAgent.h b/Source/core/inspector/InspectorInputAgent.h
index 4ae8753..830a72f 100644
--- a/Source/core/inspector/InspectorInputAgent.h
+++ b/Source/core/inspector/InspectorInputAgent.h
@@ -42,23 +42,23 @@
 
 typedef String ErrorString;
 
-class InspectorInputAgent : public InspectorBaseAgent<InspectorInputAgent>, public InspectorBackendDispatcher::InputCommandHandler {
+class InspectorInputAgent FINAL : public InspectorBaseAgent<InspectorInputAgent>, public InspectorBackendDispatcher::InputCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorInputAgent);
 public:
-    static PassOwnPtr<InspectorInputAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, Page* page, InspectorClient* client)
+    static PassOwnPtr<InspectorInputAgent> create(Page* page, InspectorClient* client)
     {
-        return adoptPtr(new InspectorInputAgent(instrumentingAgents, inspectorState, page, client));
+        return adoptPtr(new InspectorInputAgent(page, client));
     }
 
-    ~InspectorInputAgent();
+    virtual ~InspectorInputAgent();
 
     // Methods called from the frontend for simulating input.
-    virtual void dispatchKeyEvent(ErrorString*, const String& type, const int* modifiers, const double* timestamp, const String* text, const String* unmodifiedText, const String* keyIdentifier, const int* windowsVirtualKeyCode, const int* nativeVirtualKeyCode, const int* macCharCode, const bool* autoRepeat, const bool* isKeypad, const bool* isSystemKey);
-    virtual void dispatchMouseEvent(ErrorString*, const String& type, int x, int y, const int* modifiers, const double* timestamp, const String* button, const int* clickCount, const bool* deviceSpace);
-    virtual void dispatchTouchEvent(ErrorString*, const String& type, const RefPtr<JSONArray>& touchPoints, const int* modifiers, const double* timestamp);
-    virtual void dispatchGestureEvent(ErrorString*, const String& type, int x, int y, const double* timestamp, const int* deltaX, const int* deltaY, const double* scale);
+    virtual void dispatchKeyEvent(ErrorString*, const String& type, const int* modifiers, const double* timestamp, const String* text, const String* unmodifiedText, const String* keyIdentifier, const int* windowsVirtualKeyCode, const int* nativeVirtualKeyCode, const int* macCharCode, const bool* autoRepeat, const bool* isKeypad, const bool* isSystemKey) OVERRIDE;
+    virtual void dispatchMouseEvent(ErrorString*, const String& type, int x, int y, const int* modifiers, const double* timestamp, const String* button, const int* clickCount, const bool* deviceSpace) OVERRIDE;
+    virtual void dispatchTouchEvent(ErrorString*, const String& type, const RefPtr<JSONArray>& touchPoints, const int* modifiers, const double* timestamp) OVERRIDE;
+    virtual void dispatchGestureEvent(ErrorString*, const String& type, int x, int y, const double* timestamp, const int* deltaX, const int* deltaY, const double* scale) OVERRIDE;
 private:
-    InspectorInputAgent(InstrumentingAgents*, InspectorCompositeState*, Page*, InspectorClient*);
+    InspectorInputAgent(Page*, InspectorClient*);
 
     Page* m_page;
     InspectorClient* m_client;
diff --git a/Source/core/inspector/InspectorAgent.cpp b/Source/core/inspector/InspectorInspectorAgent.cpp
similarity index 79%
rename from Source/core/inspector/InspectorAgent.cpp
rename to Source/core/inspector/InspectorInspectorAgent.cpp
index 4ae9a66..95fc107 100644
--- a/Source/core/inspector/InspectorAgent.cpp
+++ b/Source/core/inspector/InspectorInspectorAgent.cpp
@@ -29,19 +29,19 @@
  */
 
 #include "config.h"
-#include "core/inspector/InspectorAgent.h"
+#include "core/inspector/InspectorInspectorAgent.h"
 
 #include "InspectorFrontend.h"
 #include "bindings/v8/DOMWrapperWorld.h"
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/Document.h"
+#include "core/frame/Frame.h"
 #include "core/inspector/InjectedScriptHost.h"
 #include "core/inspector/InjectedScriptManager.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorState.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/text/StringBuilder.h"
@@ -52,26 +52,22 @@
 static const char inspectorAgentEnabled[] = "inspectorAgentEnabled";
 }
 
-InspectorAgent::InspectorAgent(Page* page, InjectedScriptManager* injectedScriptManager, InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
-    : InspectorBaseAgent<InspectorAgent>("Inspector", instrumentingAgents, state)
+InspectorInspectorAgent::InspectorInspectorAgent(Page* page, InjectedScriptManager* injectedScriptManager)
+    : InspectorBaseAgent<InspectorInspectorAgent>("Inspector")
     , m_inspectedPage(page)
     , m_frontend(0)
     , m_injectedScriptManager(injectedScriptManager)
 {
     ASSERT_ARG(page, page);
-    m_instrumentingAgents->setInspectorAgent(this);
 }
 
-InspectorAgent::~InspectorAgent()
+InspectorInspectorAgent::~InspectorInspectorAgent()
 {
-    m_instrumentingAgents->setInspectorAgent(0);
+    m_instrumentingAgents->setInspectorInspectorAgent(0);
 }
 
-void InspectorAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world)
+void InspectorInspectorAgent::didClearWindowObjectInMainWorld(Frame* frame)
 {
-    if (world != mainThreadNormalWorld())
-        return;
-
     if (m_injectedScriptForOrigin.isEmpty())
         return;
 
@@ -88,12 +84,17 @@
     frame->script().executeScriptInMainWorld(scriptSource.toString());
 }
 
-void InspectorAgent::setFrontend(InspectorFrontend* inspectorFrontend)
+void InspectorInspectorAgent::init()
+{
+    m_instrumentingAgents->setInspectorInspectorAgent(this);
+}
+
+void InspectorInspectorAgent::setFrontend(InspectorFrontend* inspectorFrontend)
 {
     m_frontend = inspectorFrontend;
 }
 
-void InspectorAgent::clearFrontend()
+void InspectorInspectorAgent::clearFrontend()
 {
     m_pendingEvaluateTestCommands.clear();
     m_frontend = 0;
@@ -102,7 +103,7 @@
     disable(&error);
 }
 
-void InspectorAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
+void InspectorInspectorAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
 {
     if (loader->frame() != frame->page()->mainFrame())
         return;
@@ -110,7 +111,7 @@
     m_injectedScriptManager->discardInjectedScripts();
 }
 
-void InspectorAgent::enable(ErrorString*)
+void InspectorInspectorAgent::enable(ErrorString*)
 {
     m_state->setBoolean(InspectorAgentState::inspectorAgentEnabled, true);
 
@@ -122,17 +123,17 @@
     m_pendingEvaluateTestCommands.clear();
 }
 
-void InspectorAgent::disable(ErrorString*)
+void InspectorInspectorAgent::disable(ErrorString*)
 {
     m_state->setBoolean(InspectorAgentState::inspectorAgentEnabled, false);
 }
 
-void InspectorAgent::reset(ErrorString*)
+void InspectorInspectorAgent::reset(ErrorString*)
 {
     m_inspectedPage->inspectorController().reconnectFrontend();
 }
 
-void InspectorAgent::domContentLoadedEventFired(Frame* frame)
+void InspectorInspectorAgent::domContentLoadedEventFired(Frame* frame)
 {
     if (frame->page()->mainFrame() != frame)
         return;
@@ -140,7 +141,7 @@
     m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
 }
 
-void InspectorAgent::evaluateForTestInFrontend(long callId, const String& script)
+void InspectorInspectorAgent::evaluateForTestInFrontend(long callId, const String& script)
 {
     if (m_state->getBoolean(InspectorAgentState::inspectorAgentEnabled))
         m_frontend->inspector()->evaluateForTestInFrontend(static_cast<int>(callId), script);
@@ -148,12 +149,12 @@
         m_pendingEvaluateTestCommands.append(pair<long, String>(callId, script));
 }
 
-void InspectorAgent::setInjectedScriptForOrigin(const String& origin, const String& source)
+void InspectorInspectorAgent::setInjectedScriptForOrigin(const String& origin, const String& source)
 {
     m_injectedScriptForOrigin.set(origin, source);
 }
 
-void InspectorAgent::inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<JSONObject> hints)
+void InspectorInspectorAgent::inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<JSONObject> hints)
 {
     if (m_state->getBoolean(InspectorAgentState::inspectorAgentEnabled) && m_frontend) {
         m_frontend->inspector()->inspect(objectToInspect, hints);
@@ -166,4 +167,3 @@
 }
 
 } // namespace WebCore
-
diff --git a/Source/core/inspector/InspectorAgent.h b/Source/core/inspector/InspectorInspectorAgent.h
similarity index 75%
rename from Source/core/inspector/InspectorAgent.h
rename to Source/core/inspector/InspectorInspectorAgent.h
index 789e002..6302cff 100644
--- a/Source/core/inspector/InspectorAgent.h
+++ b/Source/core/inspector/InspectorInspectorAgent.h
@@ -27,8 +27,8 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef InspectorAgent_h
-#define InspectorAgent_h
+#ifndef InspectorInspectorAgent_h
+#define InspectorInspectorAgent_h
 
 #include "core/inspector/InspectorBaseAgent.h"
 #include "wtf/HashMap.h"
@@ -48,25 +48,26 @@
 
 typedef String ErrorString;
 
-class InspectorAgent : public InspectorBaseAgent<InspectorAgent>, public InspectorBackendDispatcher::InspectorCommandHandler {
-    WTF_MAKE_NONCOPYABLE(InspectorAgent);
+class InspectorInspectorAgent FINAL : public InspectorBaseAgent<InspectorInspectorAgent>, public InspectorBackendDispatcher::InspectorCommandHandler {
+    WTF_MAKE_NONCOPYABLE(InspectorInspectorAgent);
 public:
-    static PassOwnPtr<InspectorAgent> create(Page* page, InjectedScriptManager* injectedScriptManager, InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
+    static PassOwnPtr<InspectorInspectorAgent> create(Page* page, InjectedScriptManager* injectedScriptManager)
     {
-        return adoptPtr(new InspectorAgent(page, injectedScriptManager, instrumentingAgents, state));
+        return adoptPtr(new InspectorInspectorAgent(page, injectedScriptManager));
     }
 
-    virtual ~InspectorAgent();
+    virtual ~InspectorInspectorAgent();
 
     // Inspector front-end API.
-    void enable(ErrorString*);
-    void disable(ErrorString*);
-    void reset(ErrorString*);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void reset(ErrorString*) OVERRIDE;
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
+    virtual void init() OVERRIDE;
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
 
-    void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
+    void didClearWindowObjectInMainWorld(Frame*);
 
     void didCommitLoad(Frame*, DocumentLoader*);
     void domContentLoadedEventFired(Frame*);
@@ -81,7 +82,7 @@
     void inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<JSONObject> hints);
 
 private:
-    InspectorAgent(Page*, InjectedScriptManager*, InstrumentingAgents*, InspectorCompositeState*);
+    InspectorInspectorAgent(Page*, InjectedScriptManager*);
 
     Page* m_inspectedPage;
     InspectorFrontend* m_frontend;
@@ -95,4 +96,4 @@
 
 } // namespace WebCore
 
-#endif // !defined(InspectorAgent_h)
+#endif // !defined(InspectorInspectorAgent_h)
diff --git a/Source/core/inspector/InspectorInstrumentation.cpp b/Source/core/inspector/InspectorInstrumentation.cpp
index 9b135b5..dc54b8b 100644
--- a/Source/core/inspector/InspectorInstrumentation.cpp
+++ b/Source/core/inspector/InspectorInstrumentation.cpp
@@ -31,12 +31,13 @@
 #include "config.h"
 #include "core/inspector/InspectorInstrumentation.h"
 
+#include "core/events/EventTarget.h"
 #include "core/fetch/FetchInitiatorInfo.h"
-#include "core/inspector/InspectorAgent.h"
 #include "core/inspector/InspectorCSSAgent.h"
 #include "core/inspector/InspectorConsoleAgent.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorDebuggerAgent.h"
+#include "core/inspector/InspectorInspectorAgent.h"
 #include "core/inspector/InspectorProfilerAgent.h"
 #include "core/inspector/InspectorResourceAgent.h"
 #include "core/inspector/InspectorTimelineAgent.h"
@@ -94,11 +95,6 @@
     return false;
 }
 
-void continueAfterPingLoaderImpl(InstrumentingAgents* instrumentingAgents, unsigned long identifier, DocumentLoader* loader, ResourceRequest& request, const ResourceResponse& response)
-{
-    willSendRequestImpl(instrumentingAgents, identifier, loader, request, response, FetchInitiatorInfo());
-}
-
 void didReceiveResourceResponseButCanceledImpl(Frame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r)
 {
     didReceiveResourceResponse(frame, identifier, loader, r, 0);
@@ -131,16 +127,9 @@
     }
 }
 
-bool profilerEnabledImpl(InstrumentingAgents* instrumentingAgents)
-{
-    if (InspectorProfilerAgent* profilerAgent = instrumentingAgents->inspectorProfilerAgent())
-        return profilerAgent->enabled();
-    return false;
-}
-
 bool collectingHTMLParseErrorsImpl(InstrumentingAgents* instrumentingAgents)
 {
-    if (InspectorAgent* inspectorAgent = instrumentingAgents->inspectorAgent())
+    if (InspectorInspectorAgent* inspectorAgent = instrumentingAgents->inspectorInspectorAgent())
         return inspectorAgent->hasFrontend();
     return false;
 }
@@ -213,6 +202,13 @@
     return instrumentationForPage(page);
 }
 
+InstrumentingAgents* instrumentingAgentsFor(EventTarget* eventTarget)
+{
+    if (!eventTarget)
+        return 0;
+    return instrumentingAgentsFor(eventTarget->executionContext());
+}
+
 InstrumentingAgents* instrumentingAgentsFor(RenderObject* renderer)
 {
     return instrumentingAgentsFor(renderer->frame());
@@ -239,8 +235,10 @@
 const char RasterTask[] = "RasterTask";
 const char Paint[] = "Paint";
 const char Layer[] = "Layer";
+const char RequestMainThreadFrame[] = "RequestMainThreadFrame";
 const char BeginFrame[] = "BeginFrame";
 const char ActivateLayerTree[] = "ActivateLayerTree";
+const char DrawFrame[] = "DrawFrame";
 };
 
 namespace InstrumentationEventArguments {
diff --git a/Source/core/inspector/InspectorInstrumentation.h b/Source/core/inspector/InspectorInstrumentation.h
index 53fb806..570e516 100644
--- a/Source/core/inspector/InspectorInstrumentation.h
+++ b/Source/core/inspector/InspectorInstrumentation.h
@@ -38,14 +38,13 @@
 #include "core/dom/CharacterData.h"
 #include "core/dom/Element.h"
 #include "core/dom/ExecutionContext.h"
-#include "core/events/EventContext.h"
+#include "core/events/NodeEventContext.h"
 #include "core/frame/Frame.h"
 #include "core/inspector/ConsoleAPITypes.h"
 #include "core/page/Page.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderImage.h"
 #include "core/storage/StorageArea.h"
-#include "modules/websockets/WebSocketFrame.h"
 #include "platform/network/FormData.h"
 #include "platform/network/WebSocketHandshakeRequest.h"
 #include "platform/network/WebSocketHandshakeResponse.h"
@@ -56,14 +55,13 @@
 struct CSSParserString;
 class Document;
 class Element;
-class DeviceOrientationData;
-class GeolocationPosition;
+class EventTarget;
+class ExecutionContext;
 class GraphicsContext;
 class GraphicsLayer;
 class InspectorTimelineAgent;
 class InstrumentingAgents;
 class RenderLayer;
-class ExecutionContext;
 class ThreadableLoaderClient;
 class WorkerGlobalScope;
 class WorkerGlobalScopeProxy;
@@ -109,6 +107,7 @@
 // Called from generated instrumentation code.
 InstrumentingAgents* instrumentingAgentsFor(Page*);
 InstrumentingAgents* instrumentingAgentsFor(Frame*);
+InstrumentingAgents* instrumentingAgentsFor(EventTarget*);
 InstrumentingAgents* instrumentingAgentsFor(ExecutionContext*);
 InstrumentingAgents* instrumentingAgentsFor(Document&);
 InstrumentingAgents* instrumentingAgentsFor(Document*);
@@ -126,7 +125,9 @@
 extern const char RasterTask[];
 extern const char Paint[];
 extern const char Layer[];
+extern const char RequestMainThreadFrame[];
 extern const char BeginFrame[];
+extern const char DrawFrame[];
 extern const char ActivateLayerTree[];
 };
 
diff --git a/Source/core/inspector/InspectorInstrumentation.idl b/Source/core/inspector/InspectorInstrumentation.idl
index f76ecec..adda1e4 100644
--- a/Source/core/inspector/InspectorInstrumentation.idl
+++ b/Source/core/inspector/InspectorInstrumentation.idl
@@ -65,7 +65,7 @@
 #include "core/dom/PseudoElement.h"
 
     [Page, Inspector, PageDebugger, PageRuntime]
-    void didClearWindowObjectInWorld([Keep] Frame*, DOMWrapperWorld*);
+    void didClearWindowObjectInMainWorld([Keep] Frame*);
 
     [DOMDebugger, Inline=FastReturn]
     void willInsertDOMNode([Keep] Node* parent);
@@ -91,9 +91,6 @@
     [DOM, DOMDebugger, Inline=FastReturn]
     void didInvalidateStyleAttr([Keep] Node*);
 
-    [DOM, Inline=FastReturn]
-    void pseudoStateChanged([Keep] Node*);
-
     [CSS, Inline=FastReturn]
     void willMutateRules(CSSStyleSheet*);
 
@@ -107,7 +104,7 @@
     void didMutateStyle([Keep] CSSStyleDeclaration*, bool);
 
     [CSS, Inline=FastReturn]
-    void activeStyleSheetsUpdated([Keep] Document*, const Vector<RefPtr<StyleSheet> >& newSheets);
+    void activeStyleSheetsUpdated([Keep] Document*);
 
     [Console]
     void frameWindowDiscarded(Frame*, DOMWindow* domWindow);
@@ -121,18 +118,6 @@
     [DOM, Inline=FastReturn]
     void willPopShadowRoot([Keep] Element* host, ShadowRoot*);
 
-    [CSS, Inline=FastReturn]
-    void didCreateNamedFlow([Keep] Document*, NamedFlow*);
-
-    [CSS, Inline=FastReturn]
-    void willRemoveNamedFlow([Keep] Document*, NamedFlow*);
-
-    [CSS, Inline=FastReturn]
-    void didUpdateRegionLayout([Keep] Document*, NamedFlow*);
-
-    [CSS, Inline=FastReturn]
-    void didChangeRegionOverset([Keep] Document*, NamedFlow*);
-
     [DOMDebugger, Inline=FastReturn]
     void willSendXMLHttpRequest(ExecutionContext*, const String& url);
 
@@ -172,8 +157,17 @@
     [Timeline, Inline=FastReturn]
     void didDispatchEvent(const InspectorInstrumentationCookie&);
 
-    [DOMDebugger, Inline=FastReturn]
-    InspectorInstrumentationCookie willHandleEvent(ExecutionContext*, Event*);
+    [Debugger, Inline=FastReturn]
+    void didAddEventListener([Keep] EventTarget*, const AtomicString& eventType, EventListener* listener, bool useCapture);
+
+    [Debugger, Inline=FastReturn]
+    void didRemoveEventListener([Keep] EventTarget*, const AtomicString& eventType, EventListener* listener, bool useCapture);
+
+    [Debugger, Inline=FastReturn]
+    void didRemoveAllEventListeners([Keep] EventTarget*);
+
+    [Debugger, DOMDebugger, Inline=FastReturn]
+    InspectorInstrumentationCookie willHandleEvent([Keep] EventTarget*, const AtomicString& eventType, EventListener* listener, bool useCapture);
 
     [Debugger, Inline=FastReturn]
     void didHandleEvent(const InspectorInstrumentationCookie&);
@@ -184,15 +178,33 @@
     [Timeline, Inline=FastReturn]
     void didDispatchEventOnWindow(const InspectorInstrumentationCookie&);
 
+    [Debugger, Inline=FastReturn]
+    void didEnqueueMutationRecord([Keep] ExecutionContext*, MutationObserver*);
+
+    [Debugger, Inline=FastReturn]
+    void didClearAllMutationRecords([Keep] ExecutionContext*, MutationObserver*);
+
+    [Debugger, Inline=FastReturn]
+    void willDeliverMutationRecords([Keep] ExecutionContext*, MutationObserver*);
+
+    [Debugger, Inline=FastReturn]
+    void didDeliverMutationRecords(ExecutionContext*);
+
+    [Debugger, Inline=FastReturn]
+    void didPostPromiseTask([Keep] ExecutionContext*, ExecutionContextTask*, bool isResolved);
+
+    [Debugger, Inline=FastReturn]
+    InspectorInstrumentationCookie willPerformPromiseTask([Keep] ExecutionContext*, ExecutionContextTask*);
+
+    [Debugger, Inline=FastReturn]
+    void didPerformPromiseTask(const InspectorInstrumentationCookie&);
+
     [Timeline, Inline=FastReturn]
     InspectorInstrumentationCookie willEvaluateScript([Keep] Frame*, const String& url, int lineNumber);
 
     [Timeline, Inline=FastReturn]
     void didEvaluateScript(const InspectorInstrumentationCookie&);
 
-    [Page, Inline=FastReturn]
-    void scriptsEnabled(Page*, bool isEnabled);
-
     [PageRuntime, Inline=FastReturn]
     void didCreateIsolatedContext([Keep] Frame*, ScriptState*, SecurityOrigin*);
 
@@ -271,8 +283,6 @@
     [Timeline, Resource]
     void willSendRequest(Frame*, unsigned long identifier, DocumentLoader*, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo&);
 
-    void continueAfterPingLoader(Frame*, unsigned long identifier, DocumentLoader*, ResourceRequest&, const ResourceResponse&);
-
     [Resource]
     void markResourceAsCached(Page*, unsigned long identifier);
 
@@ -298,25 +308,25 @@
     void didReceiveData(Frame*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength);
 
     [Timeline, Resource]
-    void didFinishLoading(Frame* frame, unsigned long identifier, DocumentLoader*, double finishTime);
+    void didFinishLoading(Frame* frame, unsigned long identifier, DocumentLoader*, double finishTime, int64_t encodedDataLength);
 
     [Resource]
     void didReceiveCORSRedirectResponse([Keep] Frame*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
 
     [Timeline, Resource, Console] // Console should come AFTER Resource notification, front-end relies on this.
-    void didFailLoading(Frame* frame, unsigned long identifier, DocumentLoader*, const ResourceError&);
+    void didFailLoading(Frame* frame, unsigned long identifier, const ResourceError&);
 
     [Resource]
     void documentThreadableLoaderStartedLoadingForClient(ExecutionContext*, unsigned long identifier, ThreadableLoaderClient* client);
 
-    [Resource]
+    [Debugger, Resource]
     void willLoadXHR(ExecutionContext*, XMLHttpRequest* xhr, ThreadableLoaderClient* client, const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData>, const HTTPHeaderMap& headers, bool includeCredentials);
 
     [Resource]
     void didFailXHRLoading(ExecutionContext*, XMLHttpRequest* xhr, ThreadableLoaderClient* client);
 
     [Console, Resource]
-    void didFinishXHRLoading(ExecutionContext*, XMLHttpRequest* xhr, ThreadableLoaderClient* client, unsigned long identifier, ScriptString sourceString, const String& url, const String& sendURL, unsigned sendLineNumber);
+    void didFinishXHRLoading(ExecutionContext*, XMLHttpRequest* xhr, ThreadableLoaderClient* client, unsigned long identifier, ScriptString sourceString, const AtomicString& method, const String& url, const String& sendURL, unsigned sendLineNumber);
 
     [Resource]
     void scriptImported(ExecutionContext*, unsigned long identifier, const String& sourceString);
@@ -339,7 +349,7 @@
     [Canvas, Page, CSS]
     void frameDetachedFromParent([Keep] Frame*);
 
-    [Console, Resource, CSS, Database, DOM, Inspector, Canvas, Page, PageDebugger]
+    [Console, Resource, CSS, DOM, Inspector, Canvas, Page, PageDebugger]
     void didCommitLoad([Keep] Frame*, DocumentLoader*);
 
     [DOM, Inline=FastReturn]
@@ -424,10 +434,10 @@
     void didCloseWebSocket([Keep] Document*, unsigned long identifier);
 
     [Resource]
-    void didReceiveWebSocketFrame(Document*, unsigned long identifier, const WebSocketFrame& frame);
+    void didReceiveWebSocketFrame(Document*, unsigned long identifier, int opCode, bool masked, const char* payload, size_t payloadLength);
 
     [Resource]
-    void didSendWebSocketFrame(Document*, unsigned long identifier, const WebSocketFrame& frame);
+    void didSendWebSocketFrame(Document*, unsigned long identifier, int opCode, bool masked, const char* payload, size_t payloadLength);
 
     [Resource]
     void didReceiveWebSocketFrameError(Document*, unsigned long identifier, const String& errorMessage);
@@ -446,13 +456,15 @@
 
     [DOM, Inline=FastReturn]
     void pseudoElementDestroyed([Keep] PseudoElement*);
+
+    [DOMDebugger, Inline=FastReturn]
+    void willExecuteCustomElementCallback([Keep] Element*);
 }
 
 interface InspectorConsoleInstrumentation {
 
 #include "core/inspector/ScriptArguments.h"
 #include "core/inspector/ScriptCallStack.h"
-#include "core/inspector/ScriptProfile.h"
 
     // FIXME: Convert to ScriptArguments to match non-worker context.
     // Use the same implementation as above as a similar method dispatched on Page.
@@ -484,16 +496,11 @@
     [Console, Inline=FastReturn]
     void consoleTimelineEnd([Keep] ExecutionContext* context, const String& title, ScriptState* state);
 
-    [Profiler]
-    void addProfile(ExecutionContext* context, PassRefPtr<ScriptProfile> profile, PassRefPtr<ScriptCallStack> callStack);
-}
+    [Profiler, Inline=FastReturn]
+    void consoleProfile(ExecutionContext* context, const String& title, ScriptState* state);
 
-interface InspectorDatabaseInstrumentation {
-
-#include "modules/webdatabase/Database.h"
-
-    [Database]
-    void didOpenDatabase(ExecutionContext* context, PassRefPtr<Database> database, const String& domain, const String& name, const String& version);
+    [Profiler, Inline=FastReturn]
+    void consoleProfileEnd(ExecutionContext* context, const String& title);
 }
 
 interface InspectorOverrides {
@@ -502,18 +509,6 @@
 
     [Worker, Inline=FastReturn]
     bool shouldPauseDedicatedWorkerOnStart(ExecutionContext* context);
-
-    [Page, Inline=FastReturn]
-    GeolocationPosition* overrideGeolocationPosition(Page* page, [DefaultReturn] GeolocationPosition* position);
-
-    [Page, Inline=FastReturn]
-    float overrideFontScaleFactor(Page* page, [DefaultReturn] float fontScaleFactor);
-
-    [Page, Inline=FastReturn]
-    bool overrideTextAutosizing(Page* page, [DefaultReturn] bool textAutosizing);
-
-    [Profiler]
-    String getCurrentUserInitiatedProfileName(ExecutionContext* context, bool incrementProfileNumber);
 }
 
 
diff --git a/Source/core/inspector/InspectorInstrumentationCustomInl.h b/Source/core/inspector/InspectorInstrumentationCustomInl.h
index 8849062..2ff178d 100644
--- a/Source/core/inspector/InspectorInstrumentationCustomInl.h
+++ b/Source/core/inspector/InspectorInstrumentationCustomInl.h
@@ -35,7 +35,6 @@
 
 namespace InspectorInstrumentation {
 
-bool profilerEnabledImpl(InstrumentingAgents*);
 bool isDebuggerPausedImpl(InstrumentingAgents*);
 bool collectingHTMLParseErrorsImpl(InstrumentingAgents*);
 PassOwnPtr<ScriptSourceCode> preprocessImpl(InstrumentingAgents*, Frame*, const ScriptSourceCode&);
@@ -45,20 +44,6 @@
 bool consoleAgentEnabled(ExecutionContext*);
 bool timelineAgentEnabled(ExecutionContext*);
 
-inline bool profilerEnabled(WorkerGlobalScope* scope)
-{
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(scope))
-        return profilerEnabledImpl(instrumentingAgents);
-    return false;
-}
-
-inline bool profilerEnabled(Page* page)
-{
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(page))
-        return profilerEnabledImpl(instrumentingAgents);
-    return false;
-}
-
 inline bool isDebuggerPaused(Frame* frame)
 {
     FAST_RETURN_IF_NO_FRONTENDS(false);
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.cpp b/Source/core/inspector/InspectorLayerTreeAgent.cpp
index 0c138c1..68fa440 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.cpp
+++ b/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -44,9 +44,9 @@
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderView.h"
 #include "platform/geometry/IntRect.h"
+#include "platform/graphics/CompositingReasons.h"
 #include "platform/graphics/GraphicsContextRecorder.h"
 #include "platform/transforms/TransformationMatrix.h"
-#include "public/platform/WebCompositingReasons.h"
 #include "public/platform/WebLayer.h"
 
 namespace WebCore {
@@ -118,8 +118,8 @@
         gatherGraphicsLayers(root->children()[i], layerIdToNodeIdMap, layers);
 }
 
-InspectorLayerTreeAgent::InspectorLayerTreeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorDOMAgent* domAgent, Page* page)
-    : InspectorBaseAgent<InspectorLayerTreeAgent>("LayerTree", instrumentingAgents, state)
+InspectorLayerTreeAgent::InspectorLayerTreeAgent(InspectorDOMAgent* domAgent, Page* page)
+    : InspectorBaseAgent<InspectorLayerTreeAgent>("LayerTree")
     , m_frontend(0)
     , m_page(page)
     , m_domAgent(domAgent)
@@ -308,7 +308,7 @@
     const GraphicsLayer* graphicsLayer = layerById(errorString, layerId);
     if (!graphicsLayer)
         return;
-    blink::WebCompositingReasons reasonsBitmask = graphicsLayer->compositingReasons();
+    CompositingReasons reasonsBitmask = graphicsLayer->compositingReasons();
     reasonStrings = TypeBuilder::Array<String>::create();
     for (size_t i = 0; i < WTF_ARRAY_LENGTH(compositingReasonNames); ++i) {
         if (!(reasonsBitmask & compositingReasonNames[i].mask))
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.h b/Source/core/inspector/InspectorLayerTreeAgent.h
index ffaeb48..9414419 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.h
+++ b/Source/core/inspector/InspectorLayerTreeAgent.h
@@ -51,35 +51,35 @@
 
 typedef String ErrorString;
 
-class InspectorLayerTreeAgent : public InspectorBaseAgent<InspectorLayerTreeAgent>, public InspectorBackendDispatcher::LayerTreeCommandHandler {
+class InspectorLayerTreeAgent FINAL : public InspectorBaseAgent<InspectorLayerTreeAgent>, public InspectorBackendDispatcher::LayerTreeCommandHandler {
 public:
-    static PassOwnPtr<InspectorLayerTreeAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorDOMAgent* domAgent, Page* page)
+    static PassOwnPtr<InspectorLayerTreeAgent> create(InspectorDOMAgent* domAgent, Page* page)
     {
-        return adoptPtr(new InspectorLayerTreeAgent(instrumentingAgents, state, domAgent, page));
+        return adoptPtr(new InspectorLayerTreeAgent(domAgent, page));
     }
-    ~InspectorLayerTreeAgent();
+    virtual ~InspectorLayerTreeAgent();
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
 
     // Called from InspectorInstrumentation
     void layerTreeDidChange();
     void didPaint(RenderObject*, const GraphicsLayer*, GraphicsContext*, const LayoutRect&);
 
     // Called from the front-end.
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void compositingReasons(ErrorString*, const String& layerId, RefPtr<TypeBuilder::Array<String> >&);
-    virtual void makeSnapshot(ErrorString*, const String& layerId, String* snapshotId);
-    virtual void releaseSnapshot(ErrorString*, const String& snapshotId);
-    virtual void replaySnapshot(ErrorString*, const String& snapshotId, const int* fromStep, const int* toStep, String* dataURL);
-    virtual void profileSnapshot(ErrorString*, const String& snapshotId, const int* minRepeatCount, const double* minDuration, RefPtr<TypeBuilder::Array<TypeBuilder::Array<double> > >&);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void compositingReasons(ErrorString*, const String& layerId, RefPtr<TypeBuilder::Array<String> >&) OVERRIDE;
+    virtual void makeSnapshot(ErrorString*, const String& layerId, String* snapshotId) OVERRIDE;
+    virtual void releaseSnapshot(ErrorString*, const String& snapshotId) OVERRIDE;
+    virtual void replaySnapshot(ErrorString*, const String& snapshotId, const int* fromStep, const int* toStep, String* dataURL) OVERRIDE;
+    virtual void profileSnapshot(ErrorString*, const String& snapshotId, const int* minRepeatCount, const double* minDuration, RefPtr<TypeBuilder::Array<TypeBuilder::Array<double> > >&) OVERRIDE;
 
 private:
     static unsigned s_lastSnapshotId;
 
-    InspectorLayerTreeAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorDOMAgent*, Page*);
+    InspectorLayerTreeAgent(InspectorDOMAgent*, Page*);
 
     RenderLayerCompositor* renderLayerCompositor();
     GraphicsLayer* layerById(ErrorString*, const String& layerId);
diff --git a/Source/core/inspector/InspectorMemoryAgent.cpp b/Source/core/inspector/InspectorMemoryAgent.cpp
index c754aa0..404018f 100644
--- a/Source/core/inspector/InspectorMemoryAgent.cpp
+++ b/Source/core/inspector/InspectorMemoryAgent.cpp
@@ -47,8 +47,8 @@
     *jsEventListeners = InspectorCounters::counterValue(InspectorCounters::JSEventListenerCounter);
 }
 
-InspectorMemoryAgent::InspectorMemoryAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
-    : InspectorBaseAgent<InspectorMemoryAgent>("Memory", instrumentingAgents, state)
+InspectorMemoryAgent::InspectorMemoryAgent()
+    : InspectorBaseAgent<InspectorMemoryAgent>("Memory")
     , m_frontend(0)
 {
 }
diff --git a/Source/core/inspector/InspectorMemoryAgent.h b/Source/core/inspector/InspectorMemoryAgent.h
index 6b202a8..bea3779 100644
--- a/Source/core/inspector/InspectorMemoryAgent.h
+++ b/Source/core/inspector/InspectorMemoryAgent.h
@@ -41,22 +41,22 @@
 
 typedef String ErrorString;
 
-class InspectorMemoryAgent : public InspectorBaseAgent<InspectorMemoryAgent>, public InspectorBackendDispatcher::MemoryCommandHandler {
+class InspectorMemoryAgent FINAL : public InspectorBaseAgent<InspectorMemoryAgent>, public InspectorBackendDispatcher::MemoryCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorMemoryAgent);
 public:
-    static PassOwnPtr<InspectorMemoryAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
+    static PassOwnPtr<InspectorMemoryAgent> create()
     {
-        return adoptPtr(new InspectorMemoryAgent(instrumentingAgents, state));
+        return adoptPtr(new InspectorMemoryAgent());
     }
     virtual ~InspectorMemoryAgent();
 
-    virtual void getDOMCounters(ErrorString*, int* documents, int* nodes, int* jsEventListeners);
+    virtual void getDOMCounters(ErrorString*, int* documents, int* nodes, int* jsEventListeners) OVERRIDE;
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
 
 private:
-    InspectorMemoryAgent(InstrumentingAgents*, InspectorCompositeState*);
+    InspectorMemoryAgent();
 
     InspectorFrontend::Memory* m_frontend;
 };
diff --git a/Source/core/inspector/InspectorOverlay.cpp b/Source/core/inspector/InspectorOverlay.cpp
index da350df..b8bcaff 100644
--- a/Source/core/inspector/InspectorOverlay.cpp
+++ b/Source/core/inspector/InspectorOverlay.cpp
@@ -38,14 +38,14 @@
 #include "core/dom/PseudoElement.h"
 #include "core/inspector/InspectorClient.h"
 #include "core/inspector/InspectorOverlayHost.h"
-#include "core/loader/DocumentLoader.h"
 #include "core/loader/EmptyClients.h"
+#include "core/loader/FrameLoadRequest.h"
 #include "core/page/Chrome.h"
 #include "core/page/EventHandler.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderBoxModelObject.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderObject.h"
@@ -59,34 +59,29 @@
 
 namespace {
 
-class InspectorOverlayChromeClient: public EmptyChromeClient {
+class InspectorOverlayChromeClient FINAL: public EmptyChromeClient {
 public:
     InspectorOverlayChromeClient(ChromeClient& client, InspectorOverlay* overlay)
         : m_client(client)
         , m_overlay(overlay)
     { }
 
-    virtual void setCursor(const Cursor& cursor)
+    virtual void setCursor(const Cursor& cursor) OVERRIDE
     {
         m_client.setCursor(cursor);
     }
 
-    virtual void setToolTip(const String& tooltip, TextDirection direction)
+    virtual void setToolTip(const String& tooltip, TextDirection direction) OVERRIDE
     {
         m_client.setToolTip(tooltip, direction);
     }
 
-    virtual void invalidateRootView(const IntRect& rect)
+    virtual void invalidateContentsAndRootView(const IntRect&) OVERRIDE
     {
         m_overlay->invalidate();
     }
 
-    virtual void invalidateContentsAndRootView(const IntRect& rect)
-    {
-        m_overlay->invalidate();
-    }
-
-    virtual void invalidateContentsForSlowScroll(const IntRect& rect)
+    virtual void invalidateContentsForSlowScroll(const IntRect&) OVERRIDE
     {
         m_overlay->invalidate();
     }
@@ -416,13 +411,12 @@
     if (!view)
         return;
     IntRect viewRect = view->visibleContentRect();
-    FrameView* overlayView = overlayPage()->mainFrame()->view();
 
     // Include scrollbars to avoid masking them by the gutter.
     IntSize frameViewFullSize = view->visibleContentRect(ScrollableArea::IncludeScrollbars).size();
     IntSize size = m_size.isEmpty() ? frameViewFullSize : m_size;
     size.scale(m_page->pageScaleFactor());
-    overlayView->resize(size);
+    overlayPage()->mainFrame()->view()->resize(size);
 
     // Clear canvas and paint things.
     reset(size, m_size.isEmpty() ? IntSize() : frameViewFullSize, viewRect.x(), viewRect.y());
@@ -434,9 +428,8 @@
     drawViewSize();
 
     // Position DOM elements.
-    overlayPage()->mainFrame()->document()->recalcStyle(Force);
-    if (overlayView->needsLayout())
-        overlayView->layout();
+    overlayPage()->mainFrame()->document()->setNeedsStyleRecalc(SubtreeStyleChange);
+    overlayPage()->mainFrame()->document()->updateLayout();
 
     // Kick paint.
     m_client->highlight();
@@ -610,19 +603,19 @@
     overlaySettings.setPluginsEnabled(false);
     overlaySettings.setLoadsImagesAutomatically(true);
 
-    RefPtr<Frame> frame = Frame::create(FrameInit::create(0, m_overlayPage.get(), dummyFrameLoaderClient));
+    RefPtr<Frame> frame = Frame::create(FrameInit::create(0, &m_overlayPage->frameHost(), dummyFrameLoaderClient));
     frame->setView(FrameView::create(frame.get()));
     frame->init();
     FrameLoader& loader = frame->loader();
     frame->view()->setCanHaveScrollbars(false);
     frame->view()->setTransparent(true);
-    ASSERT(loader.activeDocumentLoader());
-    DocumentWriter* writer = loader.activeDocumentLoader()->beginWriting("text/html", "UTF-8");
-    writer->addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
-    loader.activeDocumentLoader()->endWriting(writer);
+
+    RefPtr<SharedBuffer> data = SharedBuffer::create(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
+    loader.load(FrameLoadRequest(0, blankURL(), SubstituteData(data, "text/html", "UTF-8", KURL(), ForceSynchronousLoad)));
     v8::Isolate* isolate = toIsolate(frame.get());
     v8::HandleScope handleScope(isolate);
-    v8::Handle<v8::Context> frameContext = frame->script().currentWorldContext();
+    v8::Handle<v8::Context> frameContext = toV8Context(isolate, frame.get(), DOMWrapperWorld::mainWorld());
+    ASSERT(!frameContext.IsEmpty());
     v8::Context::Scope contextScope(frameContext);
     v8::Handle<v8::Value> overlayHostObj = toV8(m_overlayHost.get(), v8::Handle<v8::Object>(), isolate);
     v8::Handle<v8::Object> global = frameContext->Global();
@@ -681,7 +674,12 @@
 
 void InspectorOverlay::freePage()
 {
-    m_overlayPage.clear();
+    if (m_overlayPage) {
+        // FIXME: This logic is duplicated in SVGImage and WebViewImpl. Perhaps it can be combined
+        // into Page's destructor.
+        m_overlayPage->mainFrame()->loader().frameDetached();
+        m_overlayPage.clear();
+    }
     m_overlayChromeClient.clear();
     m_timer.stop();
 }
diff --git a/Source/core/inspector/InspectorPageAgent.cpp b/Source/core/inspector/InspectorPageAgent.cpp
index 376f21e..1677e61 100644
--- a/Source/core/inspector/InspectorPageAgent.cpp
+++ b/Source/core/inspector/InspectorPageAgent.cpp
@@ -47,8 +47,14 @@
 #include "core/fetch/Resource.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/ScriptResource.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/PageConsole.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLFrameOwnerElement.h"
+#include "core/html/HTMLImport.h"
+#include "core/html/HTMLImportChild.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/inspector/ContentSearchUtils.h"
 #include "core/inspector/DOMPatchSupport.h"
 #include "core/inspector/IdentifiersFactory.h"
@@ -62,14 +68,7 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
-#include "core/frame/Frame.h"
-#include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/PageConsole.h"
-#include "core/page/Settings.h"
-#include "modules/device_orientation/DeviceOrientationController.h"
-#include "modules/device_orientation/DeviceOrientationData.h"
-#include "modules/geolocation/GeolocationController.h"
 #include "platform/Cookie.h"
 #include "platform/JSONValues.h"
 #include "platform/UserGestureIndicator.h"
@@ -149,7 +148,7 @@
         // FIXME: should we do something else in the case of a purged
         // resource that informs the user why there is no data in the
         // inspector?
-        if (!cachedResource->makePurgeable(false))
+        if (!cachedResource->lock())
             return false;
     }
 
@@ -166,7 +165,7 @@
 {
     if (!textEncodingName.isEmpty())
         return TextResourceDecoder::create("text/plain", textEncodingName);
-    if (DOMImplementation::isXMLMIMEType(mimeType.lower())) {
+    if (DOMImplementation::isXMLMIMEType(mimeType)) {
         OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
         decoder->useLenientXMLDecoding();
         return decoder.release();
@@ -242,9 +241,9 @@
     return decodeBuffer(data, size, textEncodingName, result);
 }
 
-PassOwnPtr<InspectorPageAgent> InspectorPageAgent::create(InstrumentingAgents* instrumentingAgents, Page* page, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, InspectorClient* client, InspectorOverlay* overlay)
+PassOwnPtr<InspectorPageAgent> InspectorPageAgent::create(Page* page, InjectedScriptManager* injectedScriptManager, InspectorClient* client, InspectorOverlay* overlay)
 {
-    return adoptPtr(new InspectorPageAgent(instrumentingAgents, page, state, injectedScriptManager, client, overlay));
+    return adoptPtr(new InspectorPageAgent(page, injectedScriptManager, client, overlay));
 }
 
 // static
@@ -303,6 +302,8 @@
         return InspectorPageAgent::ScriptResource;
     case Resource::Raw:
         return InspectorPageAgent::XHRResource;
+    case Resource::ImportResource:
+        // Fall through.
     case Resource::MainResource:
         return InspectorPageAgent::DocumentResource;
     default:
@@ -316,8 +317,8 @@
     return resourceTypeJson(cachedResourceType(cachedResource));
 }
 
-InspectorPageAgent::InspectorPageAgent(InstrumentingAgents* instrumentingAgents, Page* page, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorClient* client, InspectorOverlay* overlay)
-    : InspectorBaseAgent<InspectorPageAgent>("Page", instrumentingAgents, inspectorState)
+InspectorPageAgent::InspectorPageAgent(Page* page, InjectedScriptManager* injectedScriptManager, InspectorClient* client, InspectorOverlay* overlay)
+    : InspectorBaseAgent<InspectorPageAgent>("Page")
     , m_page(page)
     , m_injectedScriptManager(injectedScriptManager)
     , m_client(client)
@@ -325,13 +326,28 @@
     , m_overlay(overlay)
     , m_lastScriptIdentifier(0)
     , m_enabled(false)
-    , m_geolocationOverridden(false)
     , m_ignoreScriptsEnabledNotification(false)
     , m_deviceMetricsOverridden(false)
     , m_emulateViewportEnabled(false)
+    , m_embedderTextAutosizingEnabled(m_page->settings().textAutosizingEnabled())
+    , m_embedderFontScaleFactor(m_page->settings().deviceScaleAdjustment())
 {
 }
 
+void InspectorPageAgent::setTextAutosizingEnabled(bool enabled)
+{
+    m_embedderTextAutosizingEnabled = enabled;
+    if (!m_deviceMetricsOverridden)
+        m_page->settings().setTextAutosizingEnabled(enabled);
+}
+
+void InspectorPageAgent::setDeviceScaleAdjustment(float deviceScaleAdjustment)
+{
+    m_embedderFontScaleFactor = deviceScaleAdjustment;
+    if (!m_deviceMetricsOverridden)
+        m_page->settings().setDeviceScaleAdjustment(deviceScaleAdjustment);
+}
+
 void InspectorPageAgent::setFrontend(InspectorFrontend* frontend)
 {
     m_frontend = frontend->page();
@@ -370,7 +386,9 @@
         double currentDeviceScaleFactor = m_state->getDouble(PageAgentState::pageAgentDeviceScaleFactorOverride);
         bool currentEmulateViewport = m_state->getBoolean(PageAgentState::pageAgentEmulateViewport);
         bool currentFitWindow = m_state->getBoolean(PageAgentState::pageAgentFitWindow);
-        updateViewMetrics(currentWidth, currentHeight, currentDeviceScaleFactor, currentEmulateViewport, currentFitWindow);
+        bool currentTextAutosizingEnabled = m_state->getBoolean(PageAgentState::pageAgentTextAutosizingOverride);
+        double currentFontScaleFactor = m_state->getBoolean(PageAgentState::fontScaleFactor);
+        updateViewMetrics(currentWidth, currentHeight, currentDeviceScaleFactor, currentEmulateViewport, currentFitWindow, currentFontScaleFactor, currentTextAutosizingEnabled);
         updateTouchEventEmulationInPage(m_state->getBoolean(PageAgentState::touchEventEmulationEnabled));
     }
 }
@@ -409,7 +427,7 @@
         return;
 
     // When disabling the agent, reset the override values if necessary.
-    updateViewMetrics(0, 0, 1, false, false);
+    updateViewMetrics(0, 0, 1, false, false, m_embedderFontScaleFactor, m_embedderTextAutosizingEnabled);
     m_state->setLong(PageAgentState::pageAgentScreenWidthOverride, 0);
     m_state->setLong(PageAgentState::pageAgentScreenHeightOverride, 0);
     m_state->setDouble(PageAgentState::pageAgentDeviceScaleFactorOverride, 1);
@@ -458,7 +476,7 @@
 {
     UserGestureIndicator indicator(DefinitelyProcessingNewUserGesture);
     Frame* frame = m_page->mainFrame();
-    FrameLoadRequest request(frame->document()->securityOrigin(), ResourceRequest(frame->document()->completeURL(url)));
+    FrameLoadRequest request(frame->document(), ResourceRequest(frame->document()->completeURL(url)));
     frame->loader().load(request);
 }
 
@@ -495,11 +513,9 @@
     return cookies;
 }
 
-static Vector<Resource*> cachedResourcesForFrame(Frame* frame)
+static void cachedResourcesForDocument(Document* document, Vector<Resource*>& result)
 {
-    Vector<Resource*> result;
-
-    const ResourceFetcher::DocumentResourceMap& allResources = frame->document()->fetcher()->allResources();
+    const ResourceFetcher::DocumentResourceMap& allResources = document->fetcher()->allResources();
     ResourceFetcher::DocumentResourceMap::const_iterator end = allResources.end();
     for (ResourceFetcher::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it) {
         Resource* cachedResource = it->value.get();
@@ -522,6 +538,39 @@
 
         result.append(cachedResource);
     }
+}
+
+static Vector<Resource*> cachedResourcesForFrame(Frame* frame)
+{
+    Vector<Resource*> result;
+    Document* rootDocument = frame->document();
+
+    if (HTMLImport* rootImport = rootDocument->import()) {
+        for (HTMLImport* import = rootImport; import; import = traverseNext(import)) {
+            if (import->ownsLoader() || import->isRoot()) {
+                if (Document* document = import->document())
+                    cachedResourcesForDocument(document, result);
+            }
+        }
+    } else {
+        cachedResourcesForDocument(rootDocument, result);
+    }
+
+    return result;
+}
+
+static Vector<HTMLImportChild*> importsForFrame(Frame* frame)
+{
+    Vector<HTMLImportChild*> result;
+    Document* rootDocument = frame->document();
+
+    if (HTMLImport* rootImport = rootDocument->import()) {
+        // Skips root, that isn't a real import but just a placeholder.
+        for (HTMLImport* import = traverseNext(rootImport); import; import = traverseNext(import)) {
+            if (import->ownsLoader() && import->document())
+                result.append(toHTMLImportChild(import));
+        }
+    }
 
     return result;
 }
@@ -671,7 +720,6 @@
     if (!deviceMetricsChanged(width, height, deviceScaleFactor, emulateViewport, fitWindow, fontScaleFactor, textAutosizing))
         return;
 
-
     m_state->setLong(PageAgentState::pageAgentScreenWidthOverride, width);
     m_state->setLong(PageAgentState::pageAgentScreenHeightOverride, height);
     m_state->setDouble(PageAgentState::pageAgentDeviceScaleFactorOverride, deviceScaleFactor);
@@ -680,7 +728,7 @@
     m_state->setDouble(PageAgentState::fontScaleFactor, fontScaleFactor);
     m_state->setBoolean(PageAgentState::pageAgentTextAutosizingOverride, textAutosizing);
 
-    updateViewMetrics(width, height, deviceScaleFactor, emulateViewport, fitWindow);
+    updateViewMetrics(width, height, deviceScaleFactor, emulateViewport, fitWindow, fontScaleFactor, textAutosizing);
 }
 
 bool InspectorPageAgent::deviceMetricsChanged(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, double fontScaleFactor, bool textAutosizing)
@@ -747,7 +795,7 @@
     if (frame) {
         disabledByScriptController = !frame->script().canExecuteScripts(NotAboutToExecuteScript);
         if (frame->settings())
-            disabledInSettings = !frame->settings()->isScriptEnabled();
+            disabledInSettings = !frame->settings()->scriptEnabled();
     }
 
     if (!disabledByScriptController) {
@@ -775,11 +823,8 @@
     }
 }
 
-void InspectorPageAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world)
+void InspectorPageAgent::didClearWindowObjectInMainWorld(Frame* frame)
 {
-    if (world != mainThreadNormalWorld())
-        return;
-
     if (frame == m_page->mainFrame())
         m_injectedScriptManager->discardInjectedScripts();
 
@@ -801,21 +846,23 @@
 
 void InspectorPageAgent::domContentLoadedEventFired(Frame* frame)
 {
-    if (frame->page()->mainFrame() != frame)
+    if (!frame->isMainFrame())
         return;
-
     m_frontend->domContentEventFired(currentTime());
 }
 
 void InspectorPageAgent::loadEventFired(Frame* frame)
 {
-    if (frame->page()->mainFrame() != frame)
+    if (!frame->isMainFrame())
         return;
     m_frontend->loadEventFired(currentTime());
 }
 
 void InspectorPageAgent::didCommitLoad(Frame*, DocumentLoader* loader)
 {
+    // FIXME: If "frame" is always guarenteed to be in the same Page as loader->frame()
+    // then all we need to check here is loader->frame()->isMainFrame()
+    // and we don't need "frame" at all.
     if (loader->frame() == m_page->mainFrame()) {
         m_scriptToEvaluateOnLoadOnce = m_pendingScriptToEvaluateOnLoadOnce;
         m_scriptPreprocessorSource = m_pendingScriptPreprocessor;
@@ -976,9 +1023,9 @@
 
     static int colorSelector = 0;
     const Color colors[] = {
-        Color(0xFF, 0, 0, 0x3F),
-        Color(0xFF, 0, 0xFF, 0x3F),
-        Color(0, 0, 0xFF, 0x3F),
+        Color(0, 0x5F, 0, 0x3F),
+        Color(0, 0xAF, 0, 0x3F),
+        Color(0, 0xFF, 0, 0x3F),
     };
 
     LayoutRect inflatedRect(rect);
@@ -1001,8 +1048,10 @@
 
 void InspectorPageAgent::didResizeMainFrame()
 {
+#if !OS(ANDROID)
     if (m_enabled && m_state->getBoolean(PageAgentState::showSizeOnResize))
         m_overlay->showAndHideViewSize(m_state->getBoolean(PageAgentState::showGridOnResize));
+#endif
     m_frontend->frameResized();
 }
 
@@ -1063,6 +1112,16 @@
         subresources->addItem(resourceObject);
     }
 
+    Vector<HTMLImportChild*> allImports = importsForFrame(frame);
+    for (Vector<HTMLImportChild*>::const_iterator it = allImports.begin(); it != allImports.end(); ++it) {
+        HTMLImportChild* import = *it;
+        RefPtr<TypeBuilder::Page::FrameResourceTree::Resources> resourceObject = TypeBuilder::Page::FrameResourceTree::Resources::create()
+            .setUrl(urlWithoutFragment(import->url()).string())
+            .setType(resourceTypeJson(InspectorPageAgent::DocumentResource))
+            .setMimeType(import->document()->suggestedMIMEType());
+        subresources->addItem(resourceObject);
+    }
+
     RefPtr<TypeBuilder::Array<TypeBuilder::Page::FrameResourceTree> > childrenArray;
     for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
         if (!childrenArray) {
@@ -1074,7 +1133,7 @@
     return result;
 }
 
-void InspectorPageAgent::updateViewMetrics(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow)
+void InspectorPageAgent::updateViewMetrics(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, double fontScaleFactor, bool textAutosizingEnabled)
 {
     if (width && height && !m_page->settings().acceleratedCompositingEnabled())
         return;
@@ -1090,6 +1149,11 @@
     }
     InspectorInstrumentation::mediaQueryResultChanged(document);
 
+    if (m_deviceMetricsOverridden) {
+        m_page->settings().setTextAutosizingEnabled(textAutosizingEnabled);
+        m_page->settings().setDeviceScaleAdjustment(fontScaleFactor);
+    }
+
     // FIXME: allow metrics override, fps counter and continuous painting at the same time: crbug.com/299837.
     m_client->setShowFPSCounter(m_state->getBoolean(PageAgentState::pageAgentShowFPSCounter) && !m_deviceMetricsOverridden);
     m_client->setContinuousPaintingEnabled(m_state->getBoolean(PageAgentState::pageAgentContinuousPaintingEnabled) && !m_deviceMetricsOverridden);
@@ -1102,79 +1166,6 @@
         mainFrame()->settings()->setTouchEventEmulationEnabled(enabled);
 }
 
-void InspectorPageAgent::setGeolocationOverride(ErrorString* error, const double* latitude, const double* longitude, const double* accuracy)
-{
-    GeolocationController* controller = GeolocationController::from(m_page);
-    GeolocationPosition* position = 0;
-    if (!controller) {
-        *error = "Internal error: unable to override geolocation";
-        return;
-    }
-    position = controller->lastPosition();
-    if (!m_geolocationOverridden && position)
-        m_platformGeolocationPosition = position;
-
-    m_geolocationOverridden = true;
-    if (latitude && longitude && accuracy)
-        m_geolocationPosition = GeolocationPosition::create(currentTimeMS(), *latitude, *longitude, *accuracy);
-    else
-        m_geolocationPosition.clear();
-
-    controller->positionChanged(0); // Kick location update.
-}
-
-void InspectorPageAgent::clearGeolocationOverride(ErrorString*)
-{
-    if (!m_geolocationOverridden)
-        return;
-    m_geolocationOverridden = false;
-    m_geolocationPosition.clear();
-
-    GeolocationController* controller = GeolocationController::from(m_page);
-    if (controller && m_platformGeolocationPosition.get())
-        controller->positionChanged(m_platformGeolocationPosition.get());
-}
-
-GeolocationPosition* InspectorPageAgent::overrideGeolocationPosition(GeolocationPosition* position)
-{
-    if (m_geolocationOverridden) {
-        if (position)
-            m_platformGeolocationPosition = position;
-        return m_geolocationPosition.get();
-    }
-    return position;
-}
-
-void InspectorPageAgent::setDeviceOrientationOverride(ErrorString* error, double alpha, double beta, double gamma)
-{
-    DeviceOrientationController* controller = DeviceOrientationController::from(mainFrame()->document());
-    if (!controller) {
-        *error = "Internal error: unable to override device orientation";
-        return;
-    }
-
-    controller->didChangeDeviceOrientation(DeviceOrientationData::create(true, alpha, true, beta, true, gamma).get());
-}
-
-void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
-{
-    setDeviceOrientationOverride(error, 0, 0, 0);
-}
-
-bool InspectorPageAgent::overrideTextAutosizing(bool textAutosizing)
-{
-    if (!m_deviceMetricsOverridden)
-        return textAutosizing;
-    return m_state->getBoolean(PageAgentState::pageAgentTextAutosizingOverride);
-}
-
-float InspectorPageAgent::overrideFontScaleFactor(float fontScaleFactor)
-{
-    if (!m_deviceMetricsOverridden)
-        return fontScaleFactor;
-    return static_cast<float>(m_state->getDouble(PageAgentState::fontScaleFactor));
-}
-
 void InspectorPageAgent::setTouchEmulationEnabled(ErrorString*, bool enabled)
 {
     if (m_state->getBoolean(PageAgentState::touchEventEmulationEnabled) == enabled)
@@ -1204,7 +1195,7 @@
     if (!m_deviceMetricsOverridden || !m_emulateViewportEnabled)
         return false;
 
-    RefPtr<StyleSheetContents> styleSheet = StyleSheetContents::create(CSSParserContext(UASheetMode));
+    RefPtr<StyleSheetContents> styleSheet = StyleSheetContents::create(CSSParserContext(UASheetMode, 0));
     styleSheet->parseString(String(viewportAndroidUserAgentStyleSheet, sizeof(viewportAndroidUserAgentStyleSheet)));
     OwnPtr<RuleSet> ruleSet = RuleSet::create();
     ruleSet->addRulesFromSheet(styleSheet.get(), MediaQueryEvaluator("screen"));
diff --git a/Source/core/inspector/InspectorPageAgent.h b/Source/core/inspector/InspectorPageAgent.h
index 8a0dc8d..239573c 100644
--- a/Source/core/inspector/InspectorPageAgent.h
+++ b/Source/core/inspector/InspectorPageAgent.h
@@ -34,7 +34,6 @@
 
 #include "InspectorFrontend.h"
 #include "core/inspector/InspectorBaseAgent.h"
-#include "modules/geolocation/GeolocationPosition.h"
 #include "wtf/HashMap.h"
 #include "wtf/text/WTFString.h"
 
@@ -61,7 +60,7 @@
 
 typedef String ErrorString;
 
-class InspectorPageAgent : public InspectorBaseAgent<InspectorPageAgent>, public InspectorBackendDispatcher::PageCommandHandler {
+class InspectorPageAgent FINAL : public InspectorBaseAgent<InspectorPageAgent>, public InspectorBackendDispatcher::PageCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorPageAgent);
 public:
     enum ResourceType {
@@ -75,7 +74,11 @@
         OtherResource
     };
 
-    static PassOwnPtr<InspectorPageAgent> create(InstrumentingAgents*, Page*, InspectorCompositeState*, InjectedScriptManager*, InspectorClient*, InspectorOverlay*);
+    static PassOwnPtr<InspectorPageAgent> create(Page*, InjectedScriptManager*, InspectorClient*, InspectorOverlay*);
+
+    // Settings overrides.
+    void setTextAutosizingEnabled(bool);
+    void setDeviceScaleAdjustment(float);
 
     static bool cachedResourceContent(Resource*, String* result, bool* base64Encoded);
     static bool sharedBufferContent(PassRefPtr<SharedBuffer>, const String& textEncodingName, bool withBase64Encode, String* result);
@@ -87,52 +90,40 @@
     static TypeBuilder::Page::ResourceType::Enum cachedResourceTypeJson(const Resource&);
 
     // Page API for InspectorFrontend
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void addScriptToEvaluateOnLoad(ErrorString*, const String& source, String* result);
-    virtual void removeScriptToEvaluateOnLoad(ErrorString*, const String& identifier);
-    virtual void reload(ErrorString*, const bool* optionalIgnoreCache, const String* optionalScriptToEvaluateOnLoad, const String* optionalScriptPreprocessor);
-    virtual void navigate(ErrorString*, const String& url);
-    virtual void getNavigationHistory(ErrorString*, int*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::NavigationEntry> >&);
-    virtual void navigateToHistoryEntry(ErrorString*, int);
-    virtual void getCookies(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::Cookie> >& cookies);
-    virtual void deleteCookie(ErrorString*, const String& cookieName, const String& url);
-    virtual void getResourceTree(ErrorString*, RefPtr<TypeBuilder::Page::FrameResourceTree>&);
-    virtual void getResourceContent(ErrorString*, const String& frameId, const String& url, String* content, bool* base64Encoded);
-    virtual void searchInResource(ErrorString*, const String& frameId, const String& url, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> >&);
-    virtual void setDocumentContent(ErrorString*, const String& frameId, const String& html);
-    virtual void setDeviceMetricsOverride(ErrorString*, int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, const bool* optionalTextAutosizing, const double* optionalFontScaleFactor);
-    virtual void setShowPaintRects(ErrorString*, bool show);
-    virtual void setShowDebugBorders(ErrorString*, bool show);
-    virtual void setShowFPSCounter(ErrorString*, bool show);
-    virtual void setContinuousPaintingEnabled(ErrorString*, bool enabled);
-    virtual void setShowScrollBottleneckRects(ErrorString*, bool show);
-    virtual void getScriptExecutionStatus(ErrorString*, PageCommandHandler::Result::Enum*);
-    virtual void setScriptExecutionDisabled(ErrorString*, bool);
-    virtual void setGeolocationOverride(ErrorString*, const double*, const double*, const double*);
-    virtual void clearGeolocationOverride(ErrorString*);
-    virtual void setDeviceOrientationOverride(ErrorString*, double, double, double);
-    virtual void clearDeviceOrientationOverride(ErrorString*);
-    virtual void setTouchEmulationEnabled(ErrorString*, bool);
-    virtual void setEmulatedMedia(ErrorString*, const String&);
-    virtual void captureScreenshot(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight, String* data, RefPtr<TypeBuilder::Page::ScreencastFrameMetadata>& out_metadata);
-    virtual void canScreencast(ErrorString*, bool*);
-    virtual void startScreencast(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight);
-    virtual void stopScreencast(ErrorString*);
-    virtual void handleJavaScriptDialog(ErrorString*, bool accept, const String* promptText);
-    virtual void queryUsageAndQuota(WebCore::ErrorString*, const WTF::String&, WTF::RefPtr<WebCore::TypeBuilder::Page::Quota>&, WTF::RefPtr<WebCore::TypeBuilder::Page::Usage>&);
-    virtual void setShowViewportSizeOnResize(ErrorString*, bool show, const bool* showGrid);
-
-    // Geolocation override helper.
-    GeolocationPosition* overrideGeolocationPosition(GeolocationPosition*);
-
-    // Text autosizing override helpers.
-    bool overrideTextAutosizing(bool);
-    // Note: This is used by Settings::deviceScaleAdjustment to calculate the overridden device scale adjustment.
-    float overrideFontScaleFactor(float);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void addScriptToEvaluateOnLoad(ErrorString*, const String& source, String* result) OVERRIDE;
+    virtual void removeScriptToEvaluateOnLoad(ErrorString*, const String& identifier) OVERRIDE;
+    virtual void reload(ErrorString*, const bool* optionalIgnoreCache, const String* optionalScriptToEvaluateOnLoad, const String* optionalScriptPreprocessor) OVERRIDE;
+    virtual void navigate(ErrorString*, const String& url) OVERRIDE;
+    virtual void getNavigationHistory(ErrorString*, int*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::NavigationEntry> >&) OVERRIDE;
+    virtual void navigateToHistoryEntry(ErrorString*, int) OVERRIDE;
+    virtual void getCookies(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::Cookie> >& cookies) OVERRIDE;
+    virtual void deleteCookie(ErrorString*, const String& cookieName, const String& url) OVERRIDE;
+    virtual void getResourceTree(ErrorString*, RefPtr<TypeBuilder::Page::FrameResourceTree>&) OVERRIDE;
+    virtual void getResourceContent(ErrorString*, const String& frameId, const String& url, String* content, bool* base64Encoded) OVERRIDE;
+    virtual void searchInResource(ErrorString*, const String& frameId, const String& url, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> >&) OVERRIDE;
+    virtual void setDocumentContent(ErrorString*, const String& frameId, const String& html) OVERRIDE;
+    virtual void setDeviceMetricsOverride(ErrorString*, int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, const bool* optionalTextAutosizing, const double* optionalFontScaleFactor) OVERRIDE;
+    virtual void setShowPaintRects(ErrorString*, bool show) OVERRIDE;
+    virtual void setShowDebugBorders(ErrorString*, bool show) OVERRIDE;
+    virtual void setShowFPSCounter(ErrorString*, bool show) OVERRIDE;
+    virtual void setContinuousPaintingEnabled(ErrorString*, bool enabled) OVERRIDE;
+    virtual void setShowScrollBottleneckRects(ErrorString*, bool show) OVERRIDE;
+    virtual void getScriptExecutionStatus(ErrorString*, PageCommandHandler::Result::Enum*) OVERRIDE;
+    virtual void setScriptExecutionDisabled(ErrorString*, bool) OVERRIDE;
+    virtual void setTouchEmulationEnabled(ErrorString*, bool) OVERRIDE;
+    virtual void setEmulatedMedia(ErrorString*, const String&) OVERRIDE;
+    virtual void captureScreenshot(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight, String* data, RefPtr<TypeBuilder::Page::ScreencastFrameMetadata>& out_metadata) OVERRIDE;
+    virtual void canScreencast(ErrorString*, bool*) OVERRIDE;
+    virtual void startScreencast(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight) OVERRIDE;
+    virtual void stopScreencast(ErrorString*) OVERRIDE;
+    virtual void handleJavaScriptDialog(ErrorString*, bool accept, const String* promptText) OVERRIDE;
+    virtual void queryUsageAndQuota(WebCore::ErrorString*, const WTF::String&, WTF::RefPtr<WebCore::TypeBuilder::Page::Quota>&, WTF::RefPtr<WebCore::TypeBuilder::Page::Usage>&) OVERRIDE;
+    virtual void setShowViewportSizeOnResize(ErrorString*, bool show, const bool* showGrid) OVERRIDE;
 
     // InspectorInstrumentation API
-    void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
+    void didClearWindowObjectInMainWorld(Frame*);
     void domContentLoadedEventFired(Frame*);
     void loadEventFired(Frame*);
     void didCommitLoad(Frame*, DocumentLoader*);
@@ -155,9 +146,9 @@
     void scriptsEnabled(bool isEnabled);
 
     // Inspector Controller API
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
 
     void webViewResized(const IntSize&);
 
@@ -179,9 +170,9 @@
 private:
     static void resourceContent(ErrorString*, Frame*, const KURL&, String* result, bool* base64Encoded);
 
-    InspectorPageAgent(InstrumentingAgents*, Page*, InspectorCompositeState*, InjectedScriptManager*, InspectorClient*, InspectorOverlay*);
+    InspectorPageAgent(Page*, InjectedScriptManager*, InspectorClient*, InspectorOverlay*);
     bool deviceMetricsChanged(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, double fontScaleFactor, bool textAutosizing);
-    void updateViewMetrics(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow);
+    void updateViewMetrics(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, double fontScaleFactor, bool textAutosizingEnabled);
     void updateTouchEventEmulationInPage(bool);
     bool forceCompositingMode(ErrorString*);
 
@@ -203,12 +194,11 @@
     HashMap<String, Frame*> m_identifierToFrame;
     HashMap<DocumentLoader*, String> m_loaderToIdentifier;
     bool m_enabled;
-    bool m_geolocationOverridden;
     bool m_ignoreScriptsEnabledNotification;
     bool m_deviceMetricsOverridden;
     bool m_emulateViewportEnabled;
-    RefPtr<GeolocationPosition> m_geolocationPosition;
-    RefPtr<GeolocationPosition> m_platformGeolocationPosition;
+    bool m_embedderTextAutosizingEnabled;
+    double m_embedderFontScaleFactor;
 };
 
 
diff --git a/Source/core/inspector/InspectorProfilerAgent.cpp b/Source/core/inspector/InspectorProfilerAgent.cpp
index 0711c5a..b6d4247 100644
--- a/Source/core/inspector/InspectorProfilerAgent.cpp
+++ b/Source/core/inspector/InspectorProfilerAgent.cpp
@@ -30,11 +30,10 @@
 #include "config.h"
 #include "core/inspector/InspectorProfilerAgent.h"
 
+#include "bindings/v8/ScriptCallStackFactory.h"
 #include "bindings/v8/ScriptProfiler.h"
-#include "core/inspector/ConsoleAPITypes.h"
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InjectedScriptHost.h"
-#include "core/inspector/InspectorConsoleAgent.h"
 #include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InspectorState.h"
 #include "core/inspector/InstrumentingAgents.h"
@@ -50,21 +49,49 @@
 static const char samplingInterval[] = "samplingInterval";
 static const char userInitiatedProfiling[] = "userInitiatedProfiling";
 static const char profilerEnabled[] = "profilerEnabled";
+static const char nextProfileId[] = "nextProfileId";
 }
 
-PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
+static PassRefPtr<TypeBuilder::Profiler::CPUProfile> createCPUProfile(const ScriptProfile& scriptProfile)
 {
-    return adoptPtr(new InspectorProfilerAgent(instrumentingAgents, consoleAgent, inspectorState, injectedScriptManager, overlay));
+    RefPtr<TypeBuilder::Profiler::CPUProfile> profile = TypeBuilder::Profiler::CPUProfile::create()
+        .setHead(scriptProfile.buildInspectorObjectForHead())
+        .setStartTime(scriptProfile.startTime())
+        .setEndTime(scriptProfile.endTime());
+    profile->setSamples(scriptProfile.buildInspectorObjectForSamples());
+    return profile.release();
 }
 
-InspectorProfilerAgent::InspectorProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
-    : InspectorBaseAgent<InspectorProfilerAgent>("Profiler", instrumentingAgents, inspectorState)
-    , m_consoleAgent(consoleAgent)
+static PassRefPtr<TypeBuilder::Debugger::Location> currentDebugLocation()
+{
+    RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(1));
+    const ScriptCallFrame& lastCaller = callStack->at(0);
+    RefPtr<TypeBuilder::Debugger::Location> location = TypeBuilder::Debugger::Location::create()
+        .setScriptId(lastCaller.scriptId())
+        .setLineNumber(lastCaller.lineNumber());
+    location->setColumnNumber(lastCaller.columnNumber());
+    return location.release();
+}
+
+class InspectorProfilerAgent::ProfileDescriptor {
+public:
+    ProfileDescriptor(const String& id, const String& title)
+        : m_id(id)
+        , m_title(title) { }
+    String m_id;
+    String m_title;
+};
+
+PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
+{
+    return adoptPtr(new InspectorProfilerAgent(injectedScriptManager, overlay));
+}
+
+InspectorProfilerAgent::InspectorProfilerAgent(InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
+    : InspectorBaseAgent<InspectorProfilerAgent>("Profiler")
     , m_injectedScriptManager(injectedScriptManager)
     , m_frontend(0)
     , m_recordingCPUProfile(false)
-    , m_currentUserInitiatedProfileNumber(-1)
-    , m_nextUserInitiatedProfileNumber(1)
     , m_profileNameIdleTimeMap(ScriptProfiler::currentProfileNameIdleTimeMap())
     , m_idleStartTime(0.0)
     , m_overlay(overlay)
@@ -75,36 +102,44 @@
 {
 }
 
-void InspectorProfilerAgent::addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
+void InspectorProfilerAgent::consoleProfile(const String& title, ScriptState* state)
 {
-    RefPtr<ScriptProfile> profile = prpProfile;
-    m_profiles.add(profile->uid(), profile);
-    if (m_frontend && m_state->getBoolean(ProfilerAgentState::profilerEnabled))
-        m_frontend->addProfileHeader(createProfileHeader(*profile));
-    addProfileFinishedMessageToConsole(profile, lineNumber, sourceURL);
+    ASSERT(m_frontend && enabled());
+    String id = nextProfileId();
+    m_startedProfiles.append(ProfileDescriptor(id, title));
+    ScriptProfiler::start(id);
+    m_frontend->consoleProfileStarted(id, currentDebugLocation(), title.isNull() ? 0 : &title);
 }
 
-void InspectorProfilerAgent::addProfile(PassRefPtr<ScriptProfile> prpProfile, PassRefPtr<ScriptCallStack> callStack)
+void InspectorProfilerAgent::consoleProfileEnd(const String& title)
 {
-    const ScriptCallFrame& lastCaller = callStack->at(0);
-    addProfile(prpProfile, lastCaller.lineNumber(), lastCaller.sourceURL());
-}
-
-void InspectorProfilerAgent::addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
-{
-    if (!m_frontend)
+    ASSERT(m_frontend && enabled());
+    String id;
+    String resolvedTitle;
+    // Take last started profile if no title was passed.
+    if (title.isNull()) {
+        if (m_startedProfiles.isEmpty())
+            return;
+        id = m_startedProfiles.last().m_id;
+        resolvedTitle = m_startedProfiles.last().m_title;
+        m_startedProfiles.removeLast();
+    } else {
+        for (size_t i = 0; i < m_startedProfiles.size(); i++) {
+            if (m_startedProfiles[i].m_title == title) {
+                resolvedTitle = title;
+                id = m_startedProfiles[i].m_id;
+                m_startedProfiles.remove(i);
+                break;
+            }
+        }
+        if (id.isEmpty())
+            return;
+    }
+    RefPtr<ScriptProfile> profile = ScriptProfiler::stop(id);
+    if (!profile)
         return;
-    RefPtr<ScriptProfile> profile = prpProfile;
-    String message = profile->title() + "#" + String::number(profile->uid());
-    m_consoleAgent->addMessageToConsole(ConsoleAPIMessageSource, ProfileEndMessageType, DebugMessageLevel, message, sourceURL, lineNumber);
-}
-
-PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::createProfileHeader(const ScriptProfile& profile)
-{
-    return TypeBuilder::Profiler::ProfileHeader::create()
-        .setUid(profile.uid())
-        .setTitle(profile.title())
-        .release();
+    RefPtr<TypeBuilder::Debugger::Location> location = currentDebugLocation();
+    m_frontend->consoleProfileFinished(id, location, createCPUProfile(*profile), resolvedTitle.isNull() ? 0 : &resolvedTitle);
 }
 
 void InspectorProfilerAgent::enable(ErrorString*)
@@ -120,6 +155,11 @@
 
 void InspectorProfilerAgent::disable(ErrorString*)
 {
+    for (Vector<ProfileDescriptor>::reverse_iterator it = m_startedProfiles.rbegin(); it != m_startedProfiles.rend(); ++it)
+        ScriptProfiler::stop(it->m_id);
+    m_startedProfiles.clear();
+    stop(0, 0);
+
     m_instrumentingAgents->setInspectorProfilerAgent(0);
     m_state->setBoolean(ProfilerAgentState::profilerEnabled, false);
 }
@@ -139,58 +179,6 @@
     ScriptProfiler::setSamplingInterval(interval);
 }
 
-String InspectorProfilerAgent::getCurrentUserInitiatedProfileName(bool incrementProfileNumber)
-{
-    if (incrementProfileNumber)
-        m_currentUserInitiatedProfileNumber = m_nextUserInitiatedProfileNumber++;
-
-    return "Profile " + String::number(m_currentUserInitiatedProfileNumber);
-}
-
-void InspectorProfilerAgent::getCPUProfile(ErrorString* errorString, int rawUid, RefPtr<TypeBuilder::Profiler::CPUProfile>& profileObject)
-{
-    unsigned uid = static_cast<unsigned>(rawUid);
-    ProfilesMap::iterator it = m_profiles.find(uid);
-    if (it == m_profiles.end()) {
-        *errorString = "Profile wasn't found";
-        return;
-    }
-    profileObject = TypeBuilder::Profiler::CPUProfile::create()
-        .setHead(it->value->buildInspectorObjectForHead())
-        .setStartTime(it->value->startTime())
-        .setEndTime(it->value->endTime());
-    profileObject->setSamples(it->value->buildInspectorObjectForSamples());
-}
-
-void InspectorProfilerAgent::removeProfile(ErrorString* errorString, int rawUid)
-{
-    unsigned uid = static_cast<unsigned>(rawUid);
-    if (m_profiles.contains(uid))
-        m_profiles.remove(uid);
-    else
-        *errorString = "Profile not found";
-}
-
-void InspectorProfilerAgent::clearProfiles(ErrorString*)
-{
-    stop();
-    m_profiles.clear();
-    m_currentUserInitiatedProfileNumber = 1;
-    m_nextUserInitiatedProfileNumber = 1;
-    resetFrontendProfiles();
-    m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
-}
-
-void InspectorProfilerAgent::resetFrontendProfiles()
-{
-    if (!m_frontend)
-        return;
-    if (!m_state->getBoolean(ProfilerAgentState::profilerEnabled))
-        return;
-    if (m_profiles.isEmpty())
-        m_frontend->resetProfiles();
-}
-
 void InspectorProfilerAgent::setFrontend(InspectorFrontend* frontend)
 {
     m_frontend = frontend->profiler();
@@ -200,62 +188,67 @@
 {
     m_frontend = 0;
     ErrorString error;
-    clearProfiles(&error);
     disable(&error);
+    m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
 }
 
 void InspectorProfilerAgent::restore()
 {
     if (m_state->getBoolean(ProfilerAgentState::profilerEnabled))
         doEnable();
-    resetFrontendProfiles();
     if (long interval = m_state->getLong(ProfilerAgentState::samplingInterval, 0))
         ScriptProfiler::setSamplingInterval(interval);
-    if (m_state->getBoolean(ProfilerAgentState::userInitiatedProfiling))
-        start();
+    if (m_state->getBoolean(ProfilerAgentState::userInitiatedProfiling)) {
+        ErrorString error;
+        start(&error);
+    }
 }
 
-void InspectorProfilerAgent::start(ErrorString*)
+void InspectorProfilerAgent::start(ErrorString* error)
 {
     if (m_recordingCPUProfile)
         return;
     if (!enabled()) {
-        ErrorString error;
-        enable(&error);
+        *error = "Profiler is not enabled";
+        return;
     }
     m_recordingCPUProfile = true;
     if (m_overlay)
         m_overlay->startedRecordingProfile();
-    String title = getCurrentUserInitiatedProfileName(true);
-    ScriptProfiler::start(title);
+    m_frontendInitiatedProfileId = nextProfileId();
+    ScriptProfiler::start(m_frontendInitiatedProfileId);
     m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, true);
 }
 
-void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::ProfileHeader>& header)
+void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::CPUProfile>& profile)
 {
-    header = stop(errorString);
+    stop(errorString, &profile);
 }
 
-PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::stop(ErrorString* errorString)
+void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::CPUProfile>* profile)
 {
     if (!m_recordingCPUProfile) {
         if (errorString)
             *errorString = "No recording profiles found";
-        return 0;
+        return;
     }
     m_recordingCPUProfile = false;
     if (m_overlay)
         m_overlay->finishedRecordingProfile();
-    String title = getCurrentUserInitiatedProfileName();
-    RefPtr<ScriptProfile> profile = ScriptProfiler::stop(title);
-    RefPtr<TypeBuilder::Profiler::ProfileHeader> profileHeader;
-    if (profile) {
-        addProfile(profile, 0, String());
-        profileHeader = createProfileHeader(*profile);
-    } else if (errorString)
+    RefPtr<ScriptProfile> scriptProfile = ScriptProfiler::stop(m_frontendInitiatedProfileId);
+    m_frontendInitiatedProfileId = String();
+    if (scriptProfile && profile)
+        *profile = createCPUProfile(*scriptProfile);
+    else if (errorString)
         *errorString = "Profile wasn't found";
     m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, false);
-    return profileHeader;
+}
+
+String InspectorProfilerAgent::nextProfileId()
+{
+    long nextId = m_state->getLong(ProfilerAgentState::nextProfileId, 1);
+    m_state->setLong(ProfilerAgentState::nextProfileId, nextId + 1);
+    return String::number(nextId);
 }
 
 void InspectorProfilerAgent::idleFinished()
diff --git a/Source/core/inspector/InspectorProfilerAgent.h b/Source/core/inspector/InspectorProfilerAgent.h
index c8ca404..7b1a690 100644
--- a/Source/core/inspector/InspectorProfilerAgent.h
+++ b/Source/core/inspector/InspectorProfilerAgent.h
@@ -41,39 +41,33 @@
 namespace WebCore {
 
 class InjectedScriptManager;
-class InspectorConsoleAgent;
 class InspectorFrontend;
 class InspectorOverlay;
 class InstrumentingAgents;
 class ScriptCallStack;
 class ScriptProfile;
+class ScriptState;
 
 typedef String ErrorString;
 
-class InspectorProfilerAgent : public InspectorBaseAgent<InspectorProfilerAgent>, public InspectorBackendDispatcher::ProfilerCommandHandler {
+class InspectorProfilerAgent FINAL : public InspectorBaseAgent<InspectorProfilerAgent>, public InspectorBackendDispatcher::ProfilerCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorProfilerAgent); WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<InspectorProfilerAgent> create(InstrumentingAgents*, InspectorConsoleAgent*, InspectorCompositeState*, InjectedScriptManager*, InspectorOverlay*);
+    static PassOwnPtr<InspectorProfilerAgent> create(InjectedScriptManager*, InspectorOverlay*);
     virtual ~InspectorProfilerAgent();
 
-    void addProfile(PassRefPtr<ScriptProfile> prpProfile, PassRefPtr<ScriptCallStack>);
-    void addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile>, unsigned lineNumber, const String& sourceURL);
-    virtual void clearProfiles(ErrorString*);
+    void consoleProfile(const String& title, ScriptState*);
+    void consoleProfileEnd(const String& title);
 
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void setSamplingInterval(ErrorString*, int);
-    virtual void start(ErrorString* = 0);
-    virtual void stop(ErrorString*, RefPtr<TypeBuilder::Profiler::ProfileHeader>& header);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void setSamplingInterval(ErrorString*, int) OVERRIDE;
+    virtual void start(ErrorString*) OVERRIDE;
+    virtual void stop(ErrorString*, RefPtr<TypeBuilder::Profiler::CPUProfile>&) OVERRIDE;
 
-    bool enabled();
-    String getCurrentUserInitiatedProfileName(bool incrementProfileNumber = false);
-    virtual void getCPUProfile(ErrorString*, int uid, RefPtr<TypeBuilder::Profiler::CPUProfile>&);
-    virtual void removeProfile(ErrorString*, int uid);
-
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
 
     void willProcessTask();
     void didProcessTask();
@@ -81,25 +75,18 @@
     void didLeaveNestedRunLoop();
 
 private:
-    InspectorProfilerAgent(InstrumentingAgents*, InspectorConsoleAgent*, InspectorCompositeState*, InjectedScriptManager*, InspectorOverlay*);
-
+    InspectorProfilerAgent(InjectedScriptManager*, InspectorOverlay*);
+    bool enabled();
     void doEnable();
+    void stop(ErrorString*, RefPtr<TypeBuilder::Profiler::CPUProfile>*);
+    String nextProfileId();
 
-    void addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL);
-
-    void resetFrontendProfiles();
-    PassRefPtr<TypeBuilder::Profiler::ProfileHeader> stop(ErrorString* = 0);
-
-    PassRefPtr<TypeBuilder::Profiler::ProfileHeader> createProfileHeader(const ScriptProfile&);
-
-    InspectorConsoleAgent* m_consoleAgent;
     InjectedScriptManager* m_injectedScriptManager;
     InspectorFrontend::Profiler* m_frontend;
     bool m_recordingCPUProfile;
-    int m_currentUserInitiatedProfileNumber;
-    unsigned m_nextUserInitiatedProfileNumber;
-    typedef HashMap<unsigned, RefPtr<ScriptProfile> > ProfilesMap;
-    ProfilesMap m_profiles;
+    class ProfileDescriptor;
+    Vector<ProfileDescriptor> m_startedProfiles;
+    String m_frontendInitiatedProfileId;
 
     typedef HashMap<String, double> ProfileNameIdleTimeMap;
     ProfileNameIdleTimeMap* m_profileNameIdleTimeMap;
diff --git a/Source/core/inspector/InspectorResourceAgent.cpp b/Source/core/inspector/InspectorResourceAgent.cpp
index d0e29e9..d192d71 100644
--- a/Source/core/inspector/InspectorResourceAgent.cpp
+++ b/Source/core/inspector/InspectorResourceAgent.cpp
@@ -57,7 +57,6 @@
 #include "core/loader/ThreadableLoaderClient.h"
 #include "core/page/Page.h"
 #include "core/xml/XMLHttpRequest.h"
-#include "modules/websockets/WebSocketFrame.h"
 #include "platform/JSONValues.h"
 #include "platform/network/HTTPHeaderMap.h"
 #include "platform/network/ResourceError.h"
@@ -91,7 +90,7 @@
     return headersObject;
 }
 
-class InspectorThreadableLoaderClient : public ThreadableLoaderClient {
+class InspectorThreadableLoaderClient FINAL : public ThreadableLoaderClient {
     WTF_MAKE_NONCOPYABLE(InspectorThreadableLoaderClient);
 public:
     InspectorThreadableLoaderClient(PassRefPtr<LoadResourceForFrontendCallback> callback)
@@ -100,7 +99,7 @@
 
     virtual ~InspectorThreadableLoaderClient() { }
 
-    virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
+    virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse& response) OVERRIDE
     {
         WTF::TextEncoding textEncoding(response.textEncodingName());
         bool useDetector = false;
@@ -113,7 +112,7 @@
         m_responseHeaders = response.httpHeaderFields();
     }
 
-    virtual void didReceiveData(const char* data, int dataLength)
+    virtual void didReceiveData(const char* data, int dataLength) OVERRIDE
     {
         if (!dataLength)
             return;
@@ -124,7 +123,7 @@
         m_responseText = m_responseText.concatenateWith(m_decoder->decode(data, dataLength));
     }
 
-    virtual void didFinishLoading(unsigned long /*identifier*/, double /*finishTime*/)
+    virtual void didFinishLoading(unsigned long /*identifier*/, double /*finishTime*/) OVERRIDE
     {
         if (m_decoder)
             m_responseText = m_responseText.concatenateWith(m_decoder->flush());
@@ -132,13 +131,13 @@
         dispose();
     }
 
-    virtual void didFail(const ResourceError&)
+    virtual void didFail(const ResourceError&) OVERRIDE
     {
         m_callback->sendFailure("Loading resource for inspector failed");
         dispose();
     }
 
-    virtual void didFailRedirectCheck()
+    virtual void didFailRedirectCheck() OVERRIDE
     {
         m_callback->sendFailure("Loading resource for inspector failed redirect check");
         dispose();
@@ -250,6 +249,8 @@
     else
         headers = buildObjectForHeaders(response.httpHeaderFields());
 
+    int64_t encodedDataLength = response.resourceLoadInfo() ? response.resourceLoadInfo()->encodedDataLength : -1;
+
     RefPtr<TypeBuilder::Network::Response> responseObject = TypeBuilder::Network::Response::create()
         .setUrl(urlWithoutFragment(response.url()).string())
         .setStatus(status)
@@ -257,7 +258,8 @@
         .setHeaders(headers)
         .setMimeType(response.mimeType())
         .setConnectionReused(response.connectionReused())
-        .setConnectionId(response.connectionID());
+        .setConnectionId(response.connectionID())
+        .setEncodedDataLength(encodedDataLength);
 
     responseObject->setFromDiskCache(response.wasCached());
     if (response.resourceLoadTiming())
@@ -272,6 +274,12 @@
             responseObject->setRequestHeadersText(response.resourceLoadInfo()->requestHeadersText);
     }
 
+    AtomicString remoteIPAddress = response.remoteIPAddress();
+    if (!remoteIPAddress.isEmpty()) {
+        responseObject->setRemoteIPAddress(remoteIPAddress);
+        responseObject->setRemotePort(response.remotePort());
+    }
+
     return responseObject;
 }
 
@@ -299,7 +307,7 @@
         for (JSONObject::const_iterator it = headers->begin(); it != end; ++it) {
             String value;
             if (it->value->asString(&value))
-                request.setHTTPHeaderField(it->key, value);
+                request.setHTTPHeaderField(AtomicString(it->key), AtomicString(value));
         }
     }
 
@@ -387,7 +395,7 @@
     m_frontend->dataReceived(requestId, currentTime(), dataLength, encodedDataLength);
 }
 
-void InspectorResourceAgent::didFinishLoading(unsigned long identifier, DocumentLoader* loader, double monotonicFinishTime)
+void InspectorResourceAgent::didFinishLoading(unsigned long identifier, DocumentLoader* loader, double monotonicFinishTime, int64_t encodedDataLength)
 {
     double finishTime = 0.0;
     // FIXME: Expose all of the timing details to inspector and have it calculate finishTime.
@@ -398,17 +406,17 @@
     m_resourcesData->maybeDecodeDataToContent(requestId);
     if (!finishTime)
         finishTime = currentTime();
-    m_frontend->loadingFinished(requestId, finishTime);
+    m_frontend->loadingFinished(requestId, finishTime, encodedDataLength);
 }
 
 void InspectorResourceAgent::didReceiveCORSRedirectResponse(Frame* frame, unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
 {
     // Update the response and finish loading
     didReceiveResourceResponse(frame, identifier, loader, response, resourceLoader);
-    didFinishLoading(identifier, loader, 0);
+    didFinishLoading(identifier, loader, 0, blink::WebURLLoaderClient::kUnknownEncodedDataLength);
 }
 
-void InspectorResourceAgent::didFailLoading(unsigned long identifier, DocumentLoader* loader, const ResourceError& error)
+void InspectorResourceAgent::didFailLoading(unsigned long identifier, const ResourceError& error)
 {
     String requestId = IdentifiersFactory::requestId(identifier);
     bool canceled = error.isCancellation();
@@ -439,9 +447,10 @@
     m_resourcesData->setXHRReplayData(requestId, xhrReplayData);
 }
 
-void InspectorResourceAgent::willLoadXHR(XMLHttpRequest*, ThreadableLoaderClient* client, const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData> formData, const HTTPHeaderMap& headers, bool includeCredentials)
+void InspectorResourceAgent::willLoadXHR(XMLHttpRequest* xhr, ThreadableLoaderClient* client, const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData> formData, const HTTPHeaderMap& headers, bool includeCredentials)
 {
-    RefPtr<XHRReplayData> xhrReplayData = XHRReplayData::create(method, urlWithoutFragment(url), async, formData, includeCredentials);
+    ASSERT(xhr);
+    RefPtr<XHRReplayData> xhrReplayData = XHRReplayData::create(xhr->executionContext(), method, urlWithoutFragment(url), async, formData, includeCredentials);
     HTTPHeaderMap::const_iterator end = headers.end();
     for (HTTPHeaderMap::const_iterator it = headers.begin(); it!= end; ++it)
         xhrReplayData->addHeader(it->key, it->value);
@@ -453,7 +462,7 @@
     m_pendingXHRReplayData.remove(client);
 }
 
-void InspectorResourceAgent::didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient* client, unsigned long identifier, ScriptString sourceString, const String&, const String&, unsigned)
+void InspectorResourceAgent::didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient* client, unsigned long identifier, ScriptString sourceString, const AtomicString&, const String&, const String&, unsigned)
 {
     m_pendingXHRReplayData.remove(client);
 }
@@ -552,21 +561,21 @@
     m_frontend->webSocketClosed(IdentifiersFactory::requestId(identifier), currentTime());
 }
 
-void InspectorResourceAgent::didReceiveWebSocketFrame(unsigned long identifier, const WebSocketFrame& frame)
+void InspectorResourceAgent::didReceiveWebSocketFrame(unsigned long identifier, int opCode, bool masked, const char* payload, size_t payloadLength)
 {
     RefPtr<TypeBuilder::Network::WebSocketFrame> frameObject = TypeBuilder::Network::WebSocketFrame::create()
-        .setOpcode(frame.opCode)
-        .setMask(frame.masked)
-        .setPayloadData(String(frame.payload, frame.payloadLength));
+        .setOpcode(opCode)
+        .setMask(masked)
+        .setPayloadData(String(payload, payloadLength));
     m_frontend->webSocketFrameReceived(IdentifiersFactory::requestId(identifier), currentTime(), frameObject);
 }
 
-void InspectorResourceAgent::didSendWebSocketFrame(unsigned long identifier, const WebSocketFrame& frame)
+void InspectorResourceAgent::didSendWebSocketFrame(unsigned long identifier, int opCode, bool masked, const char* payload, size_t payloadLength)
 {
     RefPtr<TypeBuilder::Network::WebSocketFrame> frameObject = TypeBuilder::Network::WebSocketFrame::create()
-        .setOpcode(frame.opCode)
-        .setMask(frame.masked)
-        .setPayloadData(String(frame.payload, frame.payloadLength));
+        .setOpcode(opCode)
+        .setMask(masked)
+        .setPayloadData(String(payload, payloadLength));
     m_frontend->webSocketFrameSent(IdentifiersFactory::requestId(identifier), currentTime(), frameObject);
 }
 
@@ -647,13 +656,20 @@
 
 void InspectorResourceAgent::replayXHR(ErrorString*, const String& requestId)
 {
-    RefPtr<XMLHttpRequest> xhr = XMLHttpRequest::create(m_pageAgent->mainFrame()->document());
     String actualRequestId = requestId;
 
     XHRReplayData* xhrReplayData = m_resourcesData->xhrReplayData(requestId);
     if (!xhrReplayData)
         return;
 
+    ExecutionContext* executionContext = xhrReplayData->executionContext();
+    if (!executionContext) {
+        m_resourcesData->setXHRReplayData(requestId, 0);
+        return;
+    }
+
+    RefPtr<XMLHttpRequest> xhr = XMLHttpRequest::create(executionContext);
+
     Resource* cachedResource = memoryCache()->resourceForURL(xhrReplayData->url());
     if (cachedResource)
         memoryCache()->remove(cachedResource);
@@ -690,6 +706,8 @@
     m_state->setBoolean(ResourceAgentState::cacheDisabled, cacheDisabled);
     if (cacheDisabled)
         memoryCache()->evictResources();
+    for (Frame* frame = m_pageAgent->mainFrame(); frame; frame = frame->tree().traverseNext())
+        frame->document()->fetcher()->garbageCollectDocumentResources();
 }
 
 void InspectorResourceAgent::loadResourceForFrontend(ErrorString* errorString, const String& frameId, const String& url, const RefPtr<JSONObject>* requestHeaders, PassRefPtr<LoadResourceForFrontendCallback> prpCallback)
@@ -716,14 +734,13 @@
                 *errorString = "Request header \"" + it->key + "\" value is not a string";
                 return;
             }
-            request.addHTTPHeaderField(it->key, value);
+            request.addHTTPHeaderField(AtomicString(it->key), AtomicString(value));
         }
     }
 
     ThreadableLoaderOptions options;
     options.allowCredentials = AllowStoredCredentials;
     options.crossOriginRequestPolicy = AllowCrossOriginRequests;
-    options.sendLoadCallbacks = SendCallbacks;
 
     InspectorThreadableLoaderClient* inspectorThreadableLoaderClient = new InspectorThreadableLoaderClient(callback);
     RefPtr<DocumentThreadableLoader> loader = DocumentThreadableLoader::create(document, inspectorThreadableLoaderClient, request, options);
@@ -780,8 +797,8 @@
     return false;
 }
 
-InspectorResourceAgent::InspectorResourceAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state)
-    : InspectorBaseAgent<InspectorResourceAgent>("Network", instrumentingAgents, state)
+InspectorResourceAgent::InspectorResourceAgent(InspectorPageAgent* pageAgent, InspectorClient* client)
+    : InspectorBaseAgent<InspectorResourceAgent>("Network")
     , m_pageAgent(pageAgent)
     , m_client(client)
     , m_frontend(0)
diff --git a/Source/core/inspector/InspectorResourceAgent.h b/Source/core/inspector/InspectorResourceAgent.h
index e5eb8be..b46bbca 100644
--- a/Source/core/inspector/InspectorResourceAgent.h
+++ b/Source/core/inspector/InspectorResourceAgent.h
@@ -67,35 +67,32 @@
 class XHRReplayData;
 class XMLHttpRequest;
 
-struct WebSocketFrame;
 class WebSocketHandshakeRequest;
 class WebSocketHandshakeResponse;
 
 typedef String ErrorString;
 
-class InspectorResourceAgent : public InspectorBaseAgent<InspectorResourceAgent>, public InspectorBackendDispatcher::NetworkCommandHandler {
+class InspectorResourceAgent FINAL : public InspectorBaseAgent<InspectorResourceAgent>, public InspectorBackendDispatcher::NetworkCommandHandler {
 public:
-    static PassOwnPtr<InspectorResourceAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state)
+    static PassOwnPtr<InspectorResourceAgent> create(InspectorPageAgent* pageAgent, InspectorClient* client)
     {
-        return adoptPtr(new InspectorResourceAgent(instrumentingAgents, pageAgent, client, state));
+        return adoptPtr(new InspectorResourceAgent(pageAgent, client));
     }
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
 
-    static PassRefPtr<InspectorResourceAgent> restore(Page*, InspectorCompositeState*, InspectorFrontend*);
-
-    ~InspectorResourceAgent();
+    virtual ~InspectorResourceAgent();
 
     // Called from instrumentation.
     void willSendRequest(unsigned long identifier, DocumentLoader*, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo&);
     void markResourceAsCached(unsigned long identifier);
     void didReceiveResourceResponse(Frame*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
     void didReceiveData(unsigned long identifier, const char* data, int dataLength, int encodedDataLength);
-    void didFinishLoading(unsigned long identifier, DocumentLoader*, double monotonicFinishTime);
+    void didFinishLoading(unsigned long identifier, DocumentLoader*, double monotonicFinishTime, int64_t encodedDataLength);
     void didReceiveCORSRedirectResponse(Frame*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
-    void didFailLoading(unsigned long identifier, DocumentLoader*, const ResourceError&);
+    void didFailLoading(unsigned long identifier, const ResourceError&);
     void didCommitLoad(Frame*, DocumentLoader*);
     void scriptImported(unsigned long identifier, const String& sourceString);
     void didReceiveScriptResponse(unsigned long identifier);
@@ -103,7 +100,7 @@
     void documentThreadableLoaderStartedLoadingForClient(unsigned long identifier, ThreadableLoaderClient*);
     void willLoadXHR(XMLHttpRequest*, ThreadableLoaderClient*, const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData> body, const HTTPHeaderMap& headers, bool includeCrendentials);
     void didFailXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*);
-    void didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*, unsigned long identifier, ScriptString sourceString, const String&, const String&, unsigned);
+    void didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*, unsigned long identifier, ScriptString sourceString, const AtomicString&, const String&, const String&, unsigned);
 
     void willDestroyResource(Resource*);
 
@@ -123,35 +120,35 @@
     void willSendWebSocketHandshakeRequest(Document*, unsigned long identifier, const WebSocketHandshakeRequest&);
     void didReceiveWebSocketHandshakeResponse(Document*, unsigned long identifier, const WebSocketHandshakeResponse&);
     void didCloseWebSocket(Document*, unsigned long identifier);
-    void didReceiveWebSocketFrame(unsigned long identifier, const WebSocketFrame&);
-    void didSendWebSocketFrame(unsigned long identifier, const WebSocketFrame&);
+    void didReceiveWebSocketFrame(unsigned long identifier, int opCode, bool masked, const char* payload, size_t payloadLength);
+    void didSendWebSocketFrame(unsigned long identifier, int opCode, bool masked, const char* payload, size_t payloadLength);
     void didReceiveWebSocketFrameError(unsigned long identifier, const String&);
 
     // called from Internals for layout test purposes.
     void setResourcesDataSizeLimitsFromInternals(int maximumResourcesContentSize, int maximumSingleResourceContentSize);
 
     // Called from frontend
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void setUserAgentOverride(ErrorString*, const String& userAgent);
-    virtual void setExtraHTTPHeaders(ErrorString*, const RefPtr<JSONObject>&);
-    virtual void getResponseBody(ErrorString*, const String& requestId, String* content, bool* base64Encoded);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void setUserAgentOverride(ErrorString*, const String& userAgent) OVERRIDE;
+    virtual void setExtraHTTPHeaders(ErrorString*, const RefPtr<JSONObject>&) OVERRIDE;
+    virtual void getResponseBody(ErrorString*, const String& requestId, String* content, bool* base64Encoded) OVERRIDE;
 
-    virtual void replayXHR(ErrorString*, const String& requestId);
+    virtual void replayXHR(ErrorString*, const String& requestId) OVERRIDE;
 
-    virtual void canClearBrowserCache(ErrorString*, bool*);
-    virtual void clearBrowserCache(ErrorString*);
-    virtual void canClearBrowserCookies(ErrorString*, bool*);
-    virtual void clearBrowserCookies(ErrorString*);
-    virtual void setCacheDisabled(ErrorString*, bool cacheDisabled);
+    virtual void canClearBrowserCache(ErrorString*, bool*) OVERRIDE;
+    virtual void clearBrowserCache(ErrorString*) OVERRIDE;
+    virtual void canClearBrowserCookies(ErrorString*, bool*) OVERRIDE;
+    virtual void clearBrowserCookies(ErrorString*) OVERRIDE;
+    virtual void setCacheDisabled(ErrorString*, bool cacheDisabled) OVERRIDE;
 
-    virtual void loadResourceForFrontend(ErrorString*, const String& frameId, const String& url, const RefPtr<JSONObject>* requestHeaders, PassRefPtr<LoadResourceForFrontendCallback>);
+    virtual void loadResourceForFrontend(ErrorString*, const String& frameId, const String& url, const RefPtr<JSONObject>* requestHeaders, PassRefPtr<LoadResourceForFrontendCallback>) OVERRIDE;
 
     // Called from other agents.
     bool fetchResourceContent(Frame*, const KURL&, String* content, bool* base64Encoded);
 
 private:
-    InspectorResourceAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorClient*, InspectorCompositeState*);
+    InspectorResourceAgent(InspectorPageAgent*, InspectorClient*);
 
     void enable();
 
diff --git a/Source/core/inspector/InspectorRuntimeAgent.cpp b/Source/core/inspector/InspectorRuntimeAgent.cpp
index fcb3a27..094d11b 100644
--- a/Source/core/inspector/InspectorRuntimeAgent.cpp
+++ b/Source/core/inspector/InspectorRuntimeAgent.cpp
@@ -45,8 +45,8 @@
     return b ? *b : false;
 }
 
-InspectorRuntimeAgent::InspectorRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer)
-    : InspectorBaseAgent<InspectorRuntimeAgent>("Runtime", instrumentingAgents, state)
+InspectorRuntimeAgent::InspectorRuntimeAgent(InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer)
+    : InspectorBaseAgent<InspectorRuntimeAgent>("Runtime")
     , m_enabled(false)
     , m_injectedScriptManager(injectedScriptManager)
     , m_scriptDebugServer(scriptDebugServer)
diff --git a/Source/core/inspector/InspectorRuntimeAgent.h b/Source/core/inspector/InspectorRuntimeAgent.h
index f719291..9112fba 100644
--- a/Source/core/inspector/InspectorRuntimeAgent.h
+++ b/Source/core/inspector/InspectorRuntimeAgent.h
@@ -52,18 +52,18 @@
     virtual ~InspectorRuntimeAgent();
 
     // Part of the protocol.
-    virtual void enable(ErrorString*) { m_enabled = true; }
-    virtual void disable(ErrorString*) { m_enabled = false; }
+    virtual void enable(ErrorString*) OVERRIDE { m_enabled = true; }
+    virtual void disable(ErrorString*) OVERRIDE { m_enabled = false; }
     virtual void evaluate(ErrorString*,
-                  const String& expression,
-                  const String* objectGroup,
-                  const bool* includeCommandLineAPI,
-                  const bool* doNotPauseOnExceptionsAndMuteConsole,
-                  const int* executionContextId,
-                  const bool* returnByValue,
-                  const bool* generatePreview,
-                  RefPtr<TypeBuilder::Runtime::RemoteObject>& result,
-                  TypeBuilder::OptOutput<bool>* wasThrown);
+        const String& expression,
+        const String* objectGroup,
+        const bool* includeCommandLineAPI,
+        const bool* doNotPauseOnExceptionsAndMuteConsole,
+        const int* executionContextId,
+        const bool* returnByValue,
+        const bool* generatePreview,
+        RefPtr<TypeBuilder::Runtime::RemoteObject>& result,
+        TypeBuilder::OptOutput<bool>* wasThrown) OVERRIDE FINAL;
     virtual void callFunctionOn(ErrorString*,
                         const String& objectId,
                         const String& expression,
@@ -72,14 +72,14 @@
                         const bool* returnByValue,
                         const bool* generatePreview,
                         RefPtr<TypeBuilder::Runtime::RemoteObject>& result,
-                        TypeBuilder::OptOutput<bool>* wasThrown);
-    virtual void releaseObject(ErrorString*, const String& objectId);
-    virtual void getProperties(ErrorString*, const String& objectId, const bool* ownProperties, const bool* accessorPropertiesOnly, RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::PropertyDescriptor> >& result, RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::InternalPropertyDescriptor> >& internalProperties);
-    virtual void releaseObjectGroup(ErrorString*, const String& objectGroup);
-    virtual void run(ErrorString*);
+                        TypeBuilder::OptOutput<bool>* wasThrown) OVERRIDE FINAL;
+    virtual void releaseObject(ErrorString*, const String& objectId) OVERRIDE FINAL;
+    virtual void getProperties(ErrorString*, const String& objectId, const bool* ownProperties, const bool* accessorPropertiesOnly, RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::PropertyDescriptor> >& result, RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::InternalPropertyDescriptor> >& internalProperties) OVERRIDE FINAL;
+    virtual void releaseObjectGroup(ErrorString*, const String& objectGroup) OVERRIDE FINAL;
+    virtual void run(ErrorString*) OVERRIDE;
 
 protected:
-    InspectorRuntimeAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, ScriptDebugServer*);
+    InspectorRuntimeAgent(InjectedScriptManager*, ScriptDebugServer*);
     virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId) = 0;
 
     virtual void muteConsole() = 0;
diff --git a/Source/core/inspector/InspectorState.h b/Source/core/inspector/InspectorState.h
index d9faea7..353423e 100644
--- a/Source/core/inspector/InspectorState.h
+++ b/Source/core/inspector/InspectorState.h
@@ -84,7 +84,7 @@
     RefPtr<JSONObject> m_properties;
 };
 
-class InspectorCompositeState : public InspectorStateUpdateListener {
+class InspectorCompositeState FINAL : public InspectorStateUpdateListener {
 public:
     InspectorCompositeState(InspectorStateClient* inspectorClient)
         : m_client(inspectorClient)
@@ -104,7 +104,7 @@
     typedef HashMap<String, OwnPtr<InspectorState> > InspectorStateMap;
 
     // From InspectorStateUpdateListener.
-    virtual void inspectorStateUpdated();
+    virtual void inspectorStateUpdated() OVERRIDE;
 
     InspectorStateClient* m_client;
     RefPtr<JSONObject> m_stateObject;
diff --git a/Source/core/inspector/InspectorStyleSheet.cpp b/Source/core/inspector/InspectorStyleSheet.cpp
index 01f60ef..22c9cd4 100644
--- a/Source/core/inspector/InspectorStyleSheet.cpp
+++ b/Source/core/inspector/InspectorStyleSheet.cpp
@@ -33,8 +33,7 @@
 #include "bindings/v8/ScriptRegexp.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSMediaRule.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSRule.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSStyleRule.h"
 #include "core/css/CSSStyleSheet.h"
@@ -44,14 +43,12 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
-#include "core/dom/Node.h"
+#include "core/frame/PageConsole.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/inspector/ContentSearchUtils.h"
 #include "core/inspector/InspectorCSSAgent.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorResourceAgent.h"
-#include "core/page/Page.h"
-#include "core/page/PageConsole.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/text/StringBuilder.h"
@@ -120,7 +117,7 @@
     m_sourceData = adoptPtr(new RuleSourceDataList());
 
     // FIXME: This is a temporary solution to retain the original flat sourceData structure
-    // containing only style rules, even though CSSParser now provides the full rule source data tree.
+    // containing only style rules, even though BisonCSSParser now provides the full rule source data tree.
     // Normally, we should just assign m_sourceData = sourceData;
     flattenSourceData(sourceData.get());
 }
@@ -135,15 +132,14 @@
 
 namespace WebCore {
 
-static PassOwnPtr<CSSParser> createCSSParser(Document* document)
+static PassOwnPtr<BisonCSSParser> createCSSParser(Document* document)
 {
-    UseCounter* counter = 0;
-    return adoptPtr(new CSSParser(document ? CSSParserContext(*document) : strictCSSParserContext(), counter));
+    return adoptPtr(new BisonCSSParser(document ? CSSParserContext(*document, 0) : strictCSSParserContext()));
 }
 
 namespace {
 
-class StyleSheetHandler : public CSSParser::SourceDataHandler {
+class StyleSheetHandler FINAL : public CSSParserObserver {
 public:
     StyleSheetHandler(const String& parsedText, Document* document, StyleSheetContents* styleSheetContents, RuleSourceDataList* result)
         : m_parsedText(parsedText)
@@ -166,7 +162,7 @@
     virtual void endRuleBody(unsigned, bool) OVERRIDE;
     virtual void startEndUnknownRule() OVERRIDE { addNewRuleToSourceTree(CSSRuleSourceData::createUnknown()); }
     virtual void startProperty(unsigned) OVERRIDE;
-    virtual void endProperty(bool, bool, unsigned, CSSParser::ErrorType) OVERRIDE;
+    virtual void endProperty(bool, bool, unsigned, CSSParserError) OVERRIDE;
     virtual void startComment(unsigned) OVERRIDE;
     virtual void endComment(unsigned) OVERRIDE;
 
@@ -181,7 +177,7 @@
     RuleSourceDataList* m_result;
     RuleSourceDataList m_currentRuleDataStack;
     RefPtr<CSSRuleSourceData> m_currentRuleData;
-    OwnPtr<CSSParser> m_commentParser;
+    OwnPtr<BisonCSSParser> m_commentParser;
     unsigned m_propertyRangeStart;
     unsigned m_selectorRangeStart;
     unsigned m_commentRangeStart;
@@ -340,9 +336,10 @@
     m_propertyRangeStart = offset;
 }
 
-void StyleSheetHandler::endProperty(bool isImportant, bool isParsed, unsigned offset, CSSParser::ErrorType errorType)
+void StyleSheetHandler::endProperty(bool isImportant, bool isParsed, unsigned offset, CSSParserError errorType)
 {
-    if (errorType != CSSParser::NoError)
+    // FIXME: This is the only place CSSParserError is every read!?
+    if (errorType != NoCSSError)
         m_propertyRangeStart = UINT_MAX;
 
     if (m_propertyRangeStart == UINT_MAX || m_currentRuleDataStack.isEmpty() || !m_currentRuleDataStack.last()->styleSourceData)
@@ -411,7 +408,7 @@
         m_commentParser = createCSSParser(m_document);
     RuleSourceDataList sourceData;
 
-    // FIXME: Use another subclass of CSSParser::SourceDataHandler and assert that
+    // FIXME: Use another subclass of BisonCSSParser::SourceDataHandler and assert that
     // no comments are encountered (will not need m_document and m_styleSheetContents).
     StyleSheetHandler handler(commentText, m_document, m_styleSheetContents, &sourceData);
     RefPtr<MutableStylePropertySet> tempMutableStyle = MutableStylePropertySet::create();
@@ -505,9 +502,6 @@
     if (!m_styleId.isEmpty())
         result->setStyleId(m_styleId.asProtocolValue<TypeBuilder::CSS::CSSStyleId>());
 
-    result->setWidth(m_style->getPropertyValue("width"));
-    result->setHeight(m_style->getPropertyValue("height"));
-
     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
     if (sourceData)
         result->setRange(buildSourceRangeObject(sourceData->ruleBodyRange, m_parentStyleSheet->lineEndings().get()));
@@ -532,54 +526,55 @@
     return result.release();
 }
 
-// This method does the following preprocessing of |propertyText| with |overwrite| == false and |index| past the last active property:
-// - If the last property (if present) has no closing ";", the ";" is prepended to the current |propertyText| value.
-// - A heuristic formatting is attempted to retain the style structure.
-//
-// The propertyText (if not empty) is checked to be a valid style declaration (containing at least one property). If not,
-// the method returns false (denoting an error).
+bool InspectorStyle::verifyPropertyText(const String& propertyText, bool canOmitSemicolon)
+{
+    DEFINE_STATIC_LOCAL(String, bogusPropertyName, ("-webkit-boguz-propertee"));
+    RefPtr<MutableStylePropertySet> tempMutableStyle = MutableStylePropertySet::create();
+    RuleSourceDataList sourceData;
+    RefPtr<StyleSheetContents> styleSheetContents = StyleSheetContents::create(strictCSSParserContext());
+    String declarationText = propertyText + (canOmitSemicolon ? ";" : " ") + bogusPropertyName + ": none";
+    StyleSheetHandler handler(declarationText, ownerDocument(), styleSheetContents.get(), &sourceData);
+    createCSSParser(ownerDocument())->parseDeclaration(tempMutableStyle.get(), declarationText, &handler, styleSheetContents.get());
+    Vector<CSSPropertySourceData>& propertyData = sourceData.first()->styleSourceData->propertyData;
+    unsigned propertyCount = propertyData.size();
+
+    // At least one property + the bogus property added just above should be present.
+    if (propertyCount < 2)
+        return false;
+
+    // Check for the proper propertyText termination (the parser could at least restore to the PROPERTY_NAME state).
+    if (propertyData.at(propertyCount - 1).name != bogusPropertyName)
+        return false;
+
+    return true;
+}
+
 bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText, bool overwrite, String* oldText, ExceptionState& exceptionState)
 {
     ASSERT(m_parentStyleSheet);
-    DEFINE_STATIC_LOCAL(String, bogusPropertyName, ("-webkit-boguz-propertee"));
 
     if (!m_parentStyleSheet->ensureParsedDataReady()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The parent style sheet's data hasn't been processed.");
         return false;
     }
 
     if (!propertyText.stripWhiteSpace().isEmpty()) {
-        RefPtr<MutableStylePropertySet> tempMutableStyle = MutableStylePropertySet::create();
-        String declarationText = propertyText + " " + bogusPropertyName + ": none";
-        RuleSourceDataList sourceData;
-        StyleSheetHandler handler(declarationText, ownerDocument(), m_style->parentStyleSheet()->contents(), &sourceData);
-        createCSSParser(ownerDocument())->parseDeclaration(tempMutableStyle.get(), declarationText, &handler, m_style->parentStyleSheet()->contents());
-        Vector<CSSPropertySourceData>& propertyData = sourceData.first()->styleSourceData->propertyData;
-        unsigned propertyCount = propertyData.size();
-
-        // At least one property + the bogus property added just above should be present.
-        if (propertyCount < 2) {
-            exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
-            return false;
-        }
-
-        // Check for the proper propertyText termination (the parser could at least restore to the PROPERTY_NAME state).
-        if (propertyData.at(propertyCount - 1).name != bogusPropertyName) {
-            exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        if (!verifyPropertyText(propertyText, false) && !verifyPropertyText(propertyText, true)) {
+            exceptionState.throwDOMException(SyntaxError, "The property '" + propertyText + "' could not be set.");
             return false;
         }
     }
 
     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
     if (!sourceData) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The property '" + propertyText + "' could not be set.");
         return false;
     }
 
     String text;
     bool success = styleText(&text);
     if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The property '" + propertyText + "' could not be set.");
         return false;
     }
 
@@ -589,7 +584,7 @@
     InspectorStyleTextEditor editor(&allProperties, text, newLineAndWhitespaceDelimiters());
     if (overwrite) {
         if (index >= allProperties.size()) {
-            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is greater than or equal to the maximum bound (" + String::number(allProperties.size()) + ").");
             return false;
         }
         *oldText = allProperties.at(index).rawText;
@@ -600,47 +595,6 @@
     return applyStyleText(editor.styleText());
 }
 
-bool InspectorStyle::toggleProperty(unsigned index, bool disable, ExceptionState& exceptionState)
-{
-    ASSERT(m_parentStyleSheet);
-    if (!m_parentStyleSheet->ensureParsedDataReady()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
-        return false;
-    }
-
-    RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
-    if (!sourceData) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
-        return false;
-    }
-
-    String text;
-    bool success = styleText(&text);
-    if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
-        return false;
-    }
-
-    Vector<InspectorStyleProperty> allProperties;
-    populateAllProperties(allProperties);
-    if (index >= allProperties.size()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return false;
-    }
-
-    InspectorStyleProperty& property = allProperties.at(index);
-    if (property.sourceData.disabled == disable)
-        return true; // Idempotent operation.
-
-    InspectorStyleTextEditor editor(&allProperties, text, newLineAndWhitespaceDelimiters());
-    if (disable)
-        editor.disableProperty(index);
-    else
-        editor.enableProperty(index);
-
-    return applyStyleText(editor.styleText());
-}
-
 bool InspectorStyle::styleText(String* result) const
 {
     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
@@ -1036,7 +990,7 @@
 {
     CSSStyleRule* rule = ruleForId(id);
     if (!rule) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No rule was found for the given ID.");
         return "";
     }
     return rule->selectorText();
@@ -1048,19 +1002,19 @@
         return false;
     CSSStyleRule* rule = ruleForId(id);
     if (!rule) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No rule was found for the given ID.");
         return false;
     }
     CSSStyleSheet* styleSheet = rule->parentStyleSheet();
     if (!styleSheet || !ensureParsedDataReady()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No stylesheet could be found in which to set the selector.");
         return false;
     }
 
     rule->setSelectorText(selector);
     RefPtr<CSSRuleSourceData> sourceData = ruleSourceDataFor(rule->style());
     if (!sourceData) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The selector '" + selector + "' could not be set.");
         return false;
     }
 
@@ -1083,14 +1037,14 @@
     if (!checkPageStyleSheet(exceptionState))
         return 0;
     if (!checkStyleRuleSelector(m_pageStyleSheet->ownerDocument(), selector)) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The selector '" + selector + "' could not be added.");
         return 0;
     }
 
     String text;
     bool success = getText(&text);
     if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "The selector '" + selector + "' could not be added.");
         return 0;
     }
     StringBuilder styleSheetText;
@@ -1109,7 +1063,7 @@
         // What we just added has to be a CSSStyleRule - we cannot handle other types of rules yet.
         // If it is not a style rule, pretend we never touched the stylesheet.
         m_pageStyleSheet->deleteRule(lastRuleIndex, ASSERT_NO_EXCEPTION);
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The selector '" + selector + "' could not be added.");
         return 0;
     }
 
@@ -1132,18 +1086,18 @@
         return false;
     RefPtr<CSSStyleRule> rule = ruleForId(id);
     if (!rule) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No style rule could be found for the provided ID.");
         return false;
     }
     CSSStyleSheet* styleSheet = rule->parentStyleSheet();
     if (!styleSheet || !ensureParsedDataReady()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No parent stylesheet could be found.");
         return false;
     }
 
     RefPtr<CSSRuleSourceData> sourceData = ruleSourceDataFor(rule->style());
     if (!sourceData) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No style rule could be found for the provided ID.");
         return false;
     }
 
@@ -1252,7 +1206,7 @@
     else {
         selectors = TypeBuilder::Array<TypeBuilder::CSS::Selector>::create();
         const CSSSelectorList& selectorList = rule->styleRule()->selectorList();
-        for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector))
+        for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(*selector))
             selectors->addItem(TypeBuilder::CSS::Selector::create().setValue(selector->selectorText()).release());
     }
     RefPtr<TypeBuilder::CSS::SelectorList> result = TypeBuilder::CSS::SelectorList::create()
@@ -1283,8 +1237,6 @@
             result->setRuleId(id.asProtocolValue<TypeBuilder::CSS::CSSRuleId>());
     }
 
-    RefPtr<Array<TypeBuilder::CSS::CSSMedia> > mediaArray = Array<TypeBuilder::CSS::CSSMedia>::create();
-
     if (mediaStack)
         result->setMedia(mediaStack);
 
@@ -1299,10 +1251,10 @@
 
     InspectorCSSId id = ruleOrStyleId(style);
     if (id.isEmpty()) {
-        RefPtr<TypeBuilder::CSS::CSSStyle> bogusStyle = TypeBuilder::CSS::CSSStyle::create()
-            .setCssProperties(Array<TypeBuilder::CSS::CSSProperty>::create())
-            .setShorthandEntries(Array<TypeBuilder::CSS::ShorthandEntry>::create());
-        return bogusStyle.release();
+        // Any rule coming from User Agent and not from DefaultStyleSheet will not have id.
+        // See InspectorCSSAgent::buildObjectForRule for details.
+        RefPtr<InspectorStyle> inspectorStyle = InspectorStyle::create(id, style, this);
+        return inspectorStyle->buildObjectForStyle();
     }
     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
     RefPtr<TypeBuilder::CSS::CSSStyle> result = inspectorStyle->buildObjectForStyle();
@@ -1324,13 +1276,13 @@
 {
     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
     if (!inspectorStyle || !inspectorStyle->cssStyle()) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No property could be found for the given ID.");
         return false;
     }
 
     bool success = inspectorStyle->styleText(oldText);
     if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "Style text could not be read for the given property.");
         return false;
     }
 
@@ -1338,7 +1290,7 @@
     if (success)
         fireStyleSheetChanged();
     else
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The style text '" + text + "' is invalid.");
     return success;
 }
 
@@ -1346,7 +1298,7 @@
 {
     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
     if (!inspectorStyle) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
+        exceptionState.throwDOMException(NotFoundError, "No property could be found for the given ID.");
         return false;
     }
 
@@ -1356,20 +1308,6 @@
     return success;
 }
 
-bool InspectorStyleSheet::toggleProperty(const InspectorCSSId& id, unsigned propertyIndex, bool disable, ExceptionState& exceptionState)
-{
-    RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
-    if (!inspectorStyle) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
-        return false;
-    }
-
-    bool success = inspectorStyle->toggleProperty(propertyIndex, disable, exceptionState);
-    if (success)
-        fireStyleSheetChanged();
-    return success;
-}
-
 bool InspectorStyleSheet::getText(String* result) const
 {
     if (!ensureText())
@@ -1534,7 +1472,7 @@
 bool InspectorStyleSheet::checkPageStyleSheet(ExceptionState& exceptionState) const
 {
     if (!m_pageStyleSheet) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "No stylesheet is available.");
         return false;
     }
     return true;
@@ -1569,7 +1507,7 @@
     if (!m_parsedStyleSheet->hasText())
         return false;
 
-    RefPtr<StyleSheetContents> newStyleSheet = StyleSheetContents::create();
+    RefPtr<StyleSheetContents> newStyleSheet = StyleSheetContents::create(strictCSSParserContext());
     OwnPtr<RuleSourceDataList> result = adoptPtr(new RuleSourceDataList());
     StyleSheetHandler handler(m_parsedStyleSheet->text(), m_pageStyleSheet->ownerDocument(), newStyleSheet.get(), result.get());
     createCSSParser(m_pageStyleSheet->ownerDocument())->parseSheet(newStyleSheet.get(), m_parsedStyleSheet->text(), TextPosition::minimumPosition(), &handler);
@@ -1713,6 +1651,19 @@
     m_ruleSourceData.clear();
 }
 
+void InspectorStyleSheetForInlineStyle::reparseStyleSheet(const String& text)
+{
+    fireStyleSheetChanged();
+}
+
+bool InspectorStyleSheetForInlineStyle::setText(const String& text, ExceptionState& exceptionState)
+{
+    bool success = setStyleText(inlineStyle(), text);
+    if (!success)
+        exceptionState.throwDOMException(SyntaxError, "Style sheet text is invalid.");
+    return success;
+}
+
 bool InspectorStyleSheetForInlineStyle::getText(String* result) const
 {
     if (!m_isStyleTextValid) {
diff --git a/Source/core/inspector/InspectorStyleSheet.h b/Source/core/inspector/InspectorStyleSheet.h
index 56a0cca..8c3399d 100644
--- a/Source/core/inspector/InspectorStyleSheet.h
+++ b/Source/core/inspector/InspectorStyleSheet.h
@@ -137,12 +137,12 @@
     PassRefPtr<TypeBuilder::CSS::CSSStyle> buildObjectForStyle() const;
     PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSComputedStyleProperty> > buildArrayForComputedStyle() const;
     bool setPropertyText(unsigned index, const String& text, bool overwrite, String* oldText, ExceptionState&);
-    bool toggleProperty(unsigned index, bool disable, ExceptionState&);
     bool styleText(String* result) const;
 
 private:
     InspectorStyle(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheet* parentStyleSheet);
 
+    bool verifyPropertyText(const String& propertyText, bool canOmitSemicolon);
     void populateAllProperties(Vector<InspectorStyleProperty>& result) const;
     PassRefPtr<TypeBuilder::CSS::CSSStyle> styleWithProperties() const;
     PassRefPtr<CSSRuleSourceData> extractSourceData() const;
@@ -183,8 +183,8 @@
     virtual Document* ownerDocument() const;
     bool canBind() const { return m_origin != TypeBuilder::CSS::StyleSheetOrigin::User_agent && m_origin != TypeBuilder::CSS::StyleSheetOrigin::User; }
     CSSStyleSheet* pageStyleSheet() const { return m_pageStyleSheet.get(); }
-    void reparseStyleSheet(const String&);
-    bool setText(const String&, ExceptionState&);
+    virtual void reparseStyleSheet(const String&);
+    virtual bool setText(const String&, ExceptionState&);
     String ruleSelector(const InspectorCSSId&, ExceptionState&);
     bool setRuleSelector(const InspectorCSSId&, const String& selector, ExceptionState&);
     CSSStyleRule* addRule(const String& selector, ExceptionState&);
@@ -196,7 +196,6 @@
     PassRefPtr<TypeBuilder::CSS::CSSStyle> buildObjectForStyle(CSSStyleDeclaration*);
     bool setStyleText(const InspectorCSSId&, const String& text, String* oldText, ExceptionState&);
     bool setPropertyText(const InspectorCSSId&, unsigned propertyIndex, const String& text, bool overwrite, String* oldPropertyText, ExceptionState&);
-    bool toggleProperty(const InspectorCSSId&, unsigned propertyIndex, bool disable, ExceptionState&);
 
     virtual TypeBuilder::CSS::StyleSheetOrigin::Enum origin() const { return m_origin; }
     virtual bool getText(String* result) const;
@@ -254,29 +253,31 @@
     mutable String m_sourceURL;
 };
 
-class InspectorStyleSheetForInlineStyle : public InspectorStyleSheet {
+class InspectorStyleSheetForInlineStyle FINAL : public InspectorStyleSheet {
 public:
     static PassRefPtr<InspectorStyleSheetForInlineStyle> create(InspectorPageAgent*, InspectorResourceAgent*, const String& id, PassRefPtr<Element>, TypeBuilder::CSS::StyleSheetOrigin::Enum, Listener*);
 
     void didModifyElementAttribute();
-    virtual bool getText(String* result) const;
-    virtual CSSStyleDeclaration* styleForId(const InspectorCSSId& id) const { ASSERT_UNUSED(id, !id.ordinal()); return inlineStyle(); }
-    virtual TypeBuilder::CSS::StyleSheetOrigin::Enum origin() const { return TypeBuilder::CSS::StyleSheetOrigin::Regular; }
+    virtual void reparseStyleSheet(const String&) OVERRIDE;
+    virtual bool setText(const String&, ExceptionState&) OVERRIDE;
+    virtual bool getText(String* result) const OVERRIDE;
+    virtual CSSStyleDeclaration* styleForId(const InspectorCSSId& id) const OVERRIDE { ASSERT_UNUSED(id, !id.ordinal()); return inlineStyle(); }
+    virtual TypeBuilder::CSS::StyleSheetOrigin::Enum origin() const OVERRIDE { return TypeBuilder::CSS::StyleSheetOrigin::Regular; }
 
 protected:
     InspectorStyleSheetForInlineStyle(InspectorPageAgent*, InspectorResourceAgent*, const String& id, PassRefPtr<Element>, TypeBuilder::CSS::StyleSheetOrigin::Enum, Listener*);
 
-    virtual Document* ownerDocument() const;
-    virtual PassRefPtr<CSSRuleSourceData> ruleSourceDataFor(CSSStyleDeclaration* style) const { ASSERT_UNUSED(style, style == inlineStyle()); return m_ruleSourceData; }
-    virtual unsigned ruleIndexByStyle(CSSStyleDeclaration*) const { return 0; }
-    virtual bool ensureParsedDataReady();
-    virtual PassRefPtr<InspectorStyle> inspectorStyleForId(const InspectorCSSId&);
+    virtual Document* ownerDocument() const OVERRIDE;
+    virtual PassRefPtr<CSSRuleSourceData> ruleSourceDataFor(CSSStyleDeclaration* style) const OVERRIDE { ASSERT_UNUSED(style, style == inlineStyle()); return m_ruleSourceData; }
+    virtual unsigned ruleIndexByStyle(CSSStyleDeclaration*) const OVERRIDE { return 0; }
+    virtual bool ensureParsedDataReady() OVERRIDE;
+    virtual PassRefPtr<InspectorStyle> inspectorStyleForId(const InspectorCSSId&) OVERRIDE;
     virtual String sourceMapURL() const OVERRIDE { return String(); }
     virtual String sourceURL() const OVERRIDE { return String(); }
 
     // Also accessed by friend class InspectorStyle.
-    virtual bool setStyleText(CSSStyleDeclaration*, const String&);
-    virtual PassOwnPtr<Vector<unsigned> > lineEndings() const;
+    virtual bool setStyleText(CSSStyleDeclaration*, const String&) OVERRIDE;
+    virtual PassOwnPtr<Vector<unsigned> > lineEndings() const OVERRIDE;
 
 private:
     CSSStyleDeclaration* inlineStyle() const;
diff --git a/Source/core/inspector/InspectorStyleTextEditor.cpp b/Source/core/inspector/InspectorStyleTextEditor.cpp
index 1c538ea..af66f69 100644
--- a/Source/core/inspector/InspectorStyleTextEditor.cpp
+++ b/Source/core/inspector/InspectorStyleTextEditor.cpp
@@ -93,11 +93,11 @@
                 textToSet.insert(formatLineFeed, formattingPrependOffset);
         }
         if (!isHTMLLineBreak(m_styleText[propertyStart]))
-            textToSet.append(formatLineFeed);
+            textToSet = textToSet + formatLineFeed;
     } else {
         String fullPrefix = formatLineFeed + formatPropertyPrefix;
         long fullPrefixLength = fullPrefix.length();
-        textToSet.append(fullPrefix);
+        textToSet = textToSet + fullPrefix;
         if (insertFirstInSource && (propertyStart < fullPrefixLength || m_styleText.substring(propertyStart - fullPrefixLength, fullPrefixLength) != fullPrefix))
             textToSet.insert(fullPrefix, formattingPrependOffset);
     }
@@ -115,24 +115,6 @@
     replaceProperty(index, "");
 }
 
-void InspectorStyleTextEditor::enableProperty(unsigned index)
-{
-    InspectorStyleProperty& disabledProperty = m_allProperties->at(index);
-    ASSERT(disabledProperty.sourceData.disabled);
-    internalReplaceProperty(disabledProperty, disabledProperty.rawText.substring(2, disabledProperty.rawText.length() - 4).stripWhiteSpace());
-}
-
-void InspectorStyleTextEditor::disableProperty(unsigned index)
-{
-    ASSERT(!m_allProperties->at(index).sourceData.disabled);
-
-    InspectorStyleProperty& property = m_allProperties->at(index);
-    property.setRawTextFromStyleDeclaration(m_styleText);
-    property.sourceData.disabled = true;
-
-    internalReplaceProperty(property, "/* " + property.rawText + " */");
-}
-
 void InspectorStyleTextEditor::internalReplaceProperty(const InspectorStyleProperty& property, const String& newText)
 {
     const SourceRange& range = property.sourceData.range;
diff --git a/Source/core/inspector/InspectorStyleTextEditor.h b/Source/core/inspector/InspectorStyleTextEditor.h
index f5ac0ec..abad8c8 100644
--- a/Source/core/inspector/InspectorStyleTextEditor.h
+++ b/Source/core/inspector/InspectorStyleTextEditor.h
@@ -42,8 +42,6 @@
     void insertProperty(unsigned index, const String& propertyText, unsigned styleBodyLength);
     void replaceProperty(unsigned index, const String& newText);
     void removeProperty(unsigned index);
-    void enableProperty(unsigned index);
-    void disableProperty(unsigned index);
     const String& styleText() const { return m_styleText; }
 
 private:
diff --git a/Source/core/inspector/InspectorTimelineAgent.cpp b/Source/core/inspector/InspectorTimelineAgent.cpp
index 2e73ed1..1d6ba95 100644
--- a/Source/core/inspector/InspectorTimelineAgent.cpp
+++ b/Source/core/inspector/InspectorTimelineAgent.cpp
@@ -34,13 +34,13 @@
 #include "core/events/Event.h"
 #include "core/frame/DOMWindow.h"
 #include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
 #include "core/frame/FrameView.h"
 #include "core/inspector/IdentifiersFactory.h"
 #include "core/inspector/InspectorClient.h"
 #include "core/inspector/InspectorCounters.h"
 #include "core/inspector/InspectorDOMAgent.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/inspector/InspectorMemoryAgent.h"
 #include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
@@ -49,7 +49,8 @@
 #include "core/inspector/TimelineRecordFactory.h"
 #include "core/inspector/TraceEventDispatcher.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/page/PageConsole.h"
+#include "core/page/Page.h"
+#include "core/frame/PageConsole.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderView.h"
 #include "core/xml/XMLHttpRequest.h"
@@ -57,7 +58,6 @@
 #include "platform/graphics/DeferredImageDecoder.h"
 #include "platform/graphics/GraphicsLayer.h"
 #include "platform/network/ResourceRequest.h"
-
 #include "wtf/CurrentTime.h"
 
 namespace WebCore {
@@ -67,7 +67,7 @@
 static const char started[] = "started";
 static const char startedFromProtocol[] = "startedFromProtocol";
 static const char timelineMaxCallStackDepth[] = "timelineMaxCallStackDepth";
-static const char includeDomCounters[] = "includeDomCounters";
+static const char includeCounters[] = "includeCounters";
 static const char includeGPUEvents[] = "includeGPUEvents";
 static const char bufferEvents[] = "bufferEvents";
 }
@@ -124,27 +124,30 @@
 static const char WebSocketReceiveHandshakeResponse[] = "WebSocketReceiveHandshakeResponse";
 static const char WebSocketDestroy[] = "WebSocketDestroy";
 
-// Event names visible to other modules.
-const char ActivateLayerTree[] = "ActivateLayerTree";
-const char BeginFrame[] = "BeginFrame";
-const char DecodeImage[] = "DecodeImage";
-const char GPUTask[] = "GPUTask";
-const char Rasterize[] = "Rasterize";
-const char PaintSetup[] = "PaintSetup";
+static const char RequestMainThreadFrame[] = "RequestMainThreadFrame";
+static const char ActivateLayerTree[] = "ActivateLayerTree";
+static const char DrawFrame[] = "DrawFrame";
+static const char BeginFrame[] = "BeginFrame";
+static const char DecodeImage[] = "DecodeImage";
+static const char GPUTask[] = "GPUTask";
+static const char Rasterize[] = "Rasterize";
+static const char PaintSetup[] = "PaintSetup";
 }
 
 namespace {
 const char BackendNodeIdGroup[] = "timeline";
 }
 
+using TypeBuilder::Timeline::TimelineEvent;
+
 struct TimelineRecordEntry {
-    TimelineRecordEntry(PassRefPtr<JSONObject> record, PassRefPtr<JSONObject> data, PassRefPtr<JSONArray> children, const String& type, size_t usedHeapSizeAtStart)
+    TimelineRecordEntry(PassRefPtr<TimelineEvent> record, PassRefPtr<JSONObject> data, PassRefPtr<TypeBuilder::Array<TimelineEvent> > children, const String& type, size_t usedHeapSizeAtStart)
         : record(record), data(data), children(children), type(type), usedHeapSizeAtStart(usedHeapSizeAtStart)
     {
     }
-    RefPtr<JSONObject> record;
+    RefPtr<TimelineEvent> record;
     RefPtr<JSONObject> data;
-    RefPtr<JSONArray> children;
+    RefPtr<TypeBuilder::Array<TimelineEvent> > children;
     String type;
     size_t usedHeapSizeAtStart;
 };
@@ -152,23 +155,29 @@
 class TimelineRecordStack {
 private:
     struct Entry {
-        Entry(PassRefPtr<JSONObject> record)
+        Entry(PassRefPtr<TimelineEvent> record, const String& type)
             : record(record)
-            , children(JSONArray::create())
+            , children(TypeBuilder::Array<TimelineEvent>::create())
+#ifndef NDEBUG
+            , type(type)
+#endif
         {
         }
 
-        RefPtr<JSONObject> record;
-        RefPtr<JSONArray> children;
+        RefPtr<TimelineEvent> record;
+        RefPtr<TypeBuilder::Array<TimelineEvent> > children;
+#ifndef NDEBUG
+        String type;
+#endif
     };
 
 public:
     TimelineRecordStack() : m_timelineAgent(0) { }
     TimelineRecordStack(InspectorTimelineAgent*);
 
-    void addScopedRecord(PassRefPtr<JSONObject> record);
+    void addScopedRecord(PassRefPtr<TimelineEvent> record, const String& type);
     void closeScopedRecord(double endTime);
-    void addInstantRecord(PassRefPtr<JSONObject> record);
+    void addInstantRecord(PassRefPtr<TimelineEvent> record);
 
 #ifndef NDEBUG
     bool isOpenRecordOfType(const String& type);
@@ -251,9 +260,8 @@
     GCEvents events = m_gcEvents;
     m_gcEvents.clear();
     for (GCEvents::iterator i = events.begin(); i != events.end(); ++i) {
-        RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(m_timeConverter.fromMonotonicallyIncreasingTime(i->startTime), m_maxCallStackDepth, TimelineRecordType::GCEvent);
-        record->setObject("data", TimelineRecordFactory::createGCEventData(i->collectedBytes));
-        record->setNumber("endTime", m_timeConverter.fromMonotonicallyIncreasingTime(i->endTime));
+        RefPtr<TimelineEvent> record = TimelineRecordFactory::createGenericRecord(m_timeConverter.fromMonotonicallyIncreasingTime(i->startTime), m_maxCallStackDepth, TimelineRecordType::GCEvent, TimelineRecordFactory::createGCEventData(i->collectedBytes));
+        record->setEndTime(m_timeConverter.fromMonotonicallyIncreasingTime(i->endTime));
         addRecordToTimeline(record.release());
     }
 }
@@ -275,7 +283,7 @@
 void InspectorTimelineAgent::clearFrontend()
 {
     ErrorString error;
-    RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> > events;
+    RefPtr<TypeBuilder::Array<TimelineEvent> > events;
     stop(&error, events);
     disable(&error);
     releaseNodeIds();
@@ -286,7 +294,7 @@
 {
     if (m_state->getBoolean(TimelineAgentState::startedFromProtocol)) {
         if (m_state->getBoolean(TimelineAgentState::bufferEvents))
-            m_bufferedEvents = TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent>::create();
+            m_bufferedEvents = TypeBuilder::Array<TimelineEvent>::create();
         innerStart();
     } else if (isStarted()) {
         // Timeline was started from console.timeline, it is not restored.
@@ -307,7 +315,7 @@
     m_state->setBoolean(TimelineAgentState::enabled, false);
 }
 
-void InspectorTimelineAgent::start(ErrorString* errorString, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters, const bool* includeGPUEvents)
+void InspectorTimelineAgent::start(ErrorString* errorString, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeCounters, const bool* includeGPUEvents)
 {
     if (!m_frontend)
         return;
@@ -325,10 +333,10 @@
         m_maxCallStackDepth = 5;
 
     if (bufferEvents && *bufferEvents)
-        m_bufferedEvents = TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent>::create();
+        m_bufferedEvents = TypeBuilder::Array<TimelineEvent>::create();
 
     m_state->setLong(TimelineAgentState::timelineMaxCallStackDepth, m_maxCallStackDepth);
-    m_state->setBoolean(TimelineAgentState::includeDomCounters, includeDomCounters && *includeDomCounters);
+    m_state->setBoolean(TimelineAgentState::includeCounters, includeCounters && *includeCounters);
     m_state->setBoolean(TimelineAgentState::includeGPUEvents, includeGPUEvents && *includeGPUEvents);
     m_state->setBoolean(TimelineAgentState::bufferEvents, bufferEvents && *bufferEvents);
 
@@ -358,7 +366,9 @@
         dispatcher->addListener(InstrumentationEvents::RasterTask, TRACE_EVENT_PHASE_BEGIN, this, &InspectorTimelineAgent::onRasterTaskBegin, m_client);
         dispatcher->addListener(InstrumentationEvents::RasterTask, TRACE_EVENT_PHASE_END, this, &InspectorTimelineAgent::onRasterTaskEnd, m_client);
         dispatcher->addListener(InstrumentationEvents::Layer, TRACE_EVENT_PHASE_DELETE_OBJECT, this, &InspectorTimelineAgent::onLayerDeleted, m_client);
+        dispatcher->addListener(InstrumentationEvents::RequestMainThreadFrame, TRACE_EVENT_PHASE_INSTANT, this, &InspectorTimelineAgent::onRequestMainThreadFrame, m_client);
         dispatcher->addListener(InstrumentationEvents::ActivateLayerTree, TRACE_EVENT_PHASE_INSTANT, this, &InspectorTimelineAgent::onActivateLayerTree, m_client);
+        dispatcher->addListener(InstrumentationEvents::DrawFrame, TRACE_EVENT_PHASE_INSTANT, this, &InspectorTimelineAgent::onDrawFrame, m_client);
         dispatcher->addListener(PlatformInstrumentation::ImageDecodeEvent, TRACE_EVENT_PHASE_BEGIN, this, &InspectorTimelineAgent::onImageDecodeBegin, m_client);
         dispatcher->addListener(PlatformInstrumentation::ImageDecodeEvent, TRACE_EVENT_PHASE_END, this, &InspectorTimelineAgent::onImageDecodeEnd, m_client);
         dispatcher->addListener(PlatformInstrumentation::DrawLazyPixelRefEvent, TRACE_EVENT_PHASE_INSTANT, this, &InspectorTimelineAgent::onDrawLazyPixelRef, m_client);
@@ -373,7 +383,7 @@
     }
 }
 
-void InspectorTimelineAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> >& events)
+void InspectorTimelineAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Array<TimelineEvent> >& events)
 {
     m_state->setBoolean(TimelineAgentState::startedFromProtocol, false);
     m_state->setBoolean(TimelineAgentState::bufferEvents, false);
@@ -411,7 +421,7 @@
 
     for (size_t i = 0; i < m_consoleTimelines.size(); ++i) {
         String message = String::format("Timeline '%s' terminated.", m_consoleTimelines[i].utf8().data());
-        page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message);
+        frameHost()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message);
     }
     m_consoleTimelines.clear();
 
@@ -423,8 +433,7 @@
 void InspectorTimelineAgent::didBeginFrame(int frameId)
 {
     TraceEventDispatcher::instance()->processBackgroundEvents();
-    m_pendingFrameRecord = TimelineRecordFactory::createGenericRecord(timestamp(), 0, TimelineRecordType::BeginFrame);
-    m_pendingFrameRecord->setObject("data", TimelineRecordFactory::createFrameData(frameId));
+    m_pendingFrameRecord = TimelineRecordFactory::createGenericRecord(timestamp(), 0, TimelineRecordType::BeginFrame, TimelineRecordFactory::createFrameData(frameId));
 }
 
 void InspectorTimelineAgent::didCancelFrame()
@@ -477,20 +486,12 @@
 
 bool InspectorTimelineAgent::willLayout(Frame* frame)
 {
-    RenderObject* root = frame->view()->layoutRoot();
-    bool partialLayout = !!root;
+    bool isPartial;
+    unsigned needsLayoutObjects;
+    unsigned totalObjects;
+    frame->countObjectsNeedingLayout(needsLayoutObjects, totalObjects, isPartial);
 
-    if (!partialLayout)
-        root = frame->contentRenderer();
-
-    unsigned dirtyObjects = 0;
-    unsigned totalObjects = 0;
-    for (RenderObject* o = root; o; o = o->nextInPreOrder(root)) {
-        ++totalObjects;
-        if (o->needsLayout())
-            ++dirtyObjects;
-    }
-    pushCurrentRecord(TimelineRecordFactory::createLayoutData(dirtyObjects, totalObjects, partialLayout), TimelineRecordType::Layout, true, frame);
+    pushCurrentRecord(TimelineRecordFactory::createLayoutData(needsLayoutObjects, totalObjects, isPartial), TimelineRecordType::Layout, true, frame);
     return true;
 }
 
@@ -503,7 +504,7 @@
     Vector<FloatQuad> quads;
     root->absoluteQuads(quads);
     if (quads.size() >= 1)
-        TimelineRecordFactory::appendLayoutRoot(entry.data.get(), quads[0], nodeId(root));
+        TimelineRecordFactory::setLayoutRoot(entry.data.get(), quads[0], nodeId(root));
     else
         ASSERT_NOT_REACHED();
     didCompleteCurrentRecord(TimelineRecordType::Layout);
@@ -542,7 +543,7 @@
         return;
     TimelineRecordEntry& entry = m_recordStack.last();
     ASSERT(entry.type == TimelineRecordType::RecalculateStyles);
-    TimelineRecordFactory::appendStyleRecalcDetails(entry.data.get(), m_styleRecalcElementCounter);
+    TimelineRecordFactory::setStyleRecalcDetails(entry.data.get(), m_styleRecalcElementCounter);
     m_styleRecalcElementCounter = 0;
     didCompleteCurrentRecord(TimelineRecordType::RecalculateStyles);
 }
@@ -565,9 +566,8 @@
         ASSERT(layerIdentifier && nodeIdentifier);
         m_layerToNodeMap.set(layerIdentifier, nodeIdentifier);
         if (paintSetupStart) {
-            RefPtr<JSONObject> paintSetupRecord = TimelineRecordFactory::createGenericRecord(paintSetupStart, 0, TimelineRecordType::PaintSetup);
-            paintSetupRecord->setNumber("endTime", m_paintSetupEnd);
-            paintSetupRecord->setObject("data", TimelineRecordFactory::createLayerData(nodeIdentifier));
+            RefPtr<TimelineEvent> paintSetupRecord = TimelineRecordFactory::createGenericRecord(paintSetupStart, 0, TimelineRecordType::PaintSetup, TimelineRecordFactory::createLayerData(nodeIdentifier));
+            paintSetupRecord->setEndTime(m_paintSetupEnd);
             addRecordToTimeline(paintSetupRecord);
         }
     }
@@ -581,7 +581,7 @@
     FloatQuad quad;
     localToPageQuad(*renderer, clipRect, &quad);
     int graphicsLayerId = graphicsLayer ? graphicsLayer->platformLayer()->id() : 0;
-    entry.data = TimelineRecordFactory::createPaintData(quad, nodeId(renderer), graphicsLayerId);
+    TimelineRecordFactory::setPaintData(entry.data.get(), quad, nodeId(renderer), graphicsLayerId);
     didCompleteCurrentRecord(TimelineRecordType::Paint);
     if (m_mayEmitFirstPaint && !graphicsLayer) {
         m_mayEmitFirstPaint = false;
@@ -659,7 +659,7 @@
 void InspectorTimelineAgent::didWriteHTML(unsigned endLine)
 {
     if (!m_recordStack.isEmpty()) {
-        TimelineRecordEntry entry = m_recordStack.last();
+        TimelineRecordEntry& entry = m_recordStack.last();
         entry.data->setNumber("endLine", endLine);
         didCompleteCurrentRecord(TimelineRecordType::ParseHTML);
     }
@@ -749,27 +749,27 @@
 void InspectorTimelineAgent::didReceiveResourceResponse(Frame* frame, unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
 {
     String requestId = IdentifiersFactory::requestId(identifier);
-    appendRecord(TimelineRecordFactory::createResourceReceiveResponseData(requestId, response), TimelineRecordType::ResourceReceiveResponse, false, frame);
+    appendRecord(TimelineRecordFactory::createResourceReceiveResponseData(requestId, response), TimelineRecordType::ResourceReceiveResponse, false, 0);
 }
 
-void InspectorTimelineAgent::didFinishLoadingResource(unsigned long identifier, bool didFail, double finishTime, Frame* frame)
+void InspectorTimelineAgent::didFinishLoadingResource(unsigned long identifier, bool didFail, double finishTime)
 {
-    appendRecord(TimelineRecordFactory::createResourceFinishData(IdentifiersFactory::requestId(identifier), didFail, finishTime * 1000), TimelineRecordType::ResourceFinish, false, frame);
+    appendRecord(TimelineRecordFactory::createResourceFinishData(IdentifiersFactory::requestId(identifier), didFail, finishTime * 1000), TimelineRecordType::ResourceFinish, false, 0);
 }
 
-void InspectorTimelineAgent::didFinishLoading(unsigned long identifier, DocumentLoader* loader, double monotonicFinishTime)
+void InspectorTimelineAgent::didFinishLoading(unsigned long identifier, DocumentLoader* loader, double monotonicFinishTime, int64_t)
 {
     double finishTime = 0.0;
     // FIXME: Expose all of the timing details to inspector and have it calculate finishTime.
     if (monotonicFinishTime)
         finishTime = loader->timing()->monotonicTimeToPseudoWallTime(monotonicFinishTime);
 
-    didFinishLoadingResource(identifier, false, finishTime, loader->frame());
+    didFinishLoadingResource(identifier, false, finishTime);
 }
 
-void InspectorTimelineAgent::didFailLoading(unsigned long identifier, DocumentLoader* loader, const ResourceError& error)
+void InspectorTimelineAgent::didFailLoading(unsigned long identifier, const ResourceError& error)
 {
-    didFinishLoadingResource(identifier, true, 0, loader->frame());
+    didFinishLoadingResource(identifier, true, 0);
 }
 
 void InspectorTimelineAgent::consoleTimeStamp(ExecutionContext* context, const String& title)
@@ -793,7 +793,7 @@
         return;
 
     String message = String::format("Timeline '%s' started.", title.utf8().data());
-    page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
+    frameHost()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
     m_consoleTimelines.append(title);
     if (!isStarted()) {
         innerStart();
@@ -811,7 +811,7 @@
     size_t index = m_consoleTimelines.find(title);
     if (index == kNotFound) {
         String message = String::format("Timeline '%s' was not started.", title.utf8().data());
-        page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
+        frameHost()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
         return;
     }
 
@@ -822,7 +822,7 @@
         unwindRecordStack();
         innerStop(true);
     }
-    page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
+    frameHost()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
 }
 
 void InspectorTimelineAgent::domContentLoadedEventFired(Frame* frame)
@@ -901,7 +901,7 @@
     if (layerTreeId != m_layerTreeId)
         return;
     TimelineThreadState& state = threadState(event.threadIdentifier());
-    state.recordStack.addInstantRecord(createRecordForEvent(event, TimelineRecordType::BeginFrame));
+    state.recordStack.addInstantRecord(createRecordForEvent(event, TimelineRecordType::BeginFrame, JSONObject::create()));
 }
 
 void InspectorTimelineAgent::onPaintSetupBegin(const TraceEventDispatcher::TraceEvent& event)
@@ -925,10 +925,10 @@
         return;
     ASSERT(!state.inKnownLayerTask);
     state.inKnownLayerTask = true;
-    double timeestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
+    double timestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
     RefPtr<JSONObject> data = TimelineRecordFactory::createLayerData(m_layerToNodeMap.get(layerId));
-    RefPtr<JSONObject> record = TimelineRecordFactory::createBackgroundRecord(timeestamp, String::number(event.threadIdentifier()), TimelineRecordType::Rasterize, data);
-    state.recordStack.addScopedRecord(record);
+    RefPtr<TimelineEvent> record = TimelineRecordFactory::createBackgroundRecord(timestamp, String::number(event.threadIdentifier()), TimelineRecordType::Rasterize, data);
+    state.recordStack.addScopedRecord(record, TimelineRecordType::Rasterize);
 }
 
 void InspectorTimelineAgent::onRasterTaskEnd(const TraceEventDispatcher::TraceEvent& event)
@@ -955,9 +955,9 @@
             ASSERT_NOT_REACHED();
     }
     RefPtr<JSONObject> data = JSONObject::create();
-    TimelineRecordFactory::appendImageDetails(data.get(), imageInfo.backendNodeId, imageInfo.url);
+    TimelineRecordFactory::setImageDetails(data.get(), imageInfo.backendNodeId, imageInfo.url);
     double timeestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
-    state.recordStack.addScopedRecord(TimelineRecordFactory::createBackgroundRecord(timeestamp, String::number(event.threadIdentifier()), TimelineRecordType::DecodeImage, data));
+    state.recordStack.addScopedRecord(TimelineRecordFactory::createBackgroundRecord(timeestamp, String::number(event.threadIdentifier()), TimelineRecordType::DecodeImage, data), TimelineRecordType::DecodeImage);
 }
 
 void InspectorTimelineAgent::onImageDecodeEnd(const TraceEventDispatcher::TraceEvent& event)
@@ -969,6 +969,15 @@
     state.recordStack.closeScopedRecord(m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp()));
 }
 
+void InspectorTimelineAgent::onRequestMainThreadFrame(const TraceEventDispatcher::TraceEvent& event)
+{
+    unsigned long long layerTreeId = event.asUInt(InstrumentationEventArguments::LayerTreeId);
+    if (layerTreeId != m_layerTreeId)
+        return;
+    TimelineThreadState& state = threadState(event.threadIdentifier());
+    state.recordStack.addInstantRecord(createRecordForEvent(event, TimelineRecordType::RequestMainThreadFrame, JSONObject::create()));
+}
+
 void InspectorTimelineAgent::onActivateLayerTree(const TraceEventDispatcher::TraceEvent& event)
 {
     unsigned long long layerTreeId = event.asUInt(InstrumentationEventArguments::LayerTreeId);
@@ -979,6 +988,15 @@
     state.recordStack.addInstantRecord(createRecordForEvent(event, TimelineRecordType::ActivateLayerTree, TimelineRecordFactory::createFrameData(frameId)));
 }
 
+void InspectorTimelineAgent::onDrawFrame(const TraceEventDispatcher::TraceEvent& event)
+{
+    unsigned long long layerTreeId = event.asUInt(InstrumentationEventArguments::LayerTreeId);
+    if (layerTreeId != m_layerTreeId)
+        return;
+    TimelineThreadState& state = threadState(event.threadIdentifier());
+    state.recordStack.addInstantRecord(createRecordForEvent(event, TimelineRecordType::DrawFrame, JSONObject::create()));
+}
+
 void InspectorTimelineAgent::onLayerDeleted(const TraceEventDispatcher::TraceEvent& event)
 {
     unsigned long long id = event.id();
@@ -1022,28 +1040,33 @@
 {
     double timelineTimestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp);
     if (event.phase == GPUEvent::PhaseBegin) {
-        m_pendingGPURecord = TimelineRecordFactory::createBackgroundRecord(timelineTimestamp, "gpu", TimelineRecordType::GPUTask, TimelineRecordFactory::createGPUTaskData(event.foreign, event.usedGPUMemoryBytes));
+        m_pendingGPURecord = TimelineRecordFactory::createBackgroundRecord(timelineTimestamp, "gpu", TimelineRecordType::GPUTask, TimelineRecordFactory::createGPUTaskData(event.foreign));
     } else if (m_pendingGPURecord) {
-        m_pendingGPURecord->setNumber("endTime", timelineTimestamp);
+        m_pendingGPURecord->setEndTime(timelineTimestamp);
+        if (!event.foreign && m_state->getBoolean(TimelineAgentState::includeCounters)) {
+            RefPtr<TypeBuilder::Timeline::Counters> counters = TypeBuilder::Timeline::Counters::create();
+            counters->setGpuMemoryUsedKB(static_cast<double>(event.usedGPUMemoryBytes / 1024));
+            m_pendingGPURecord->setCounters(counters.release());
+        }
         sendEvent(m_pendingGPURecord.release());
     }
 }
 
-void InspectorTimelineAgent::addRecordToTimeline(PassRefPtr<JSONObject> record)
+void InspectorTimelineAgent::addRecordToTimeline(PassRefPtr<TimelineEvent> record)
 {
     commitFrameRecord();
     innerAddRecordToTimeline(record);
 }
 
-void InspectorTimelineAgent::innerAddRecordToTimeline(PassRefPtr<JSONObject> prpRecord)
+void InspectorTimelineAgent::innerAddRecordToTimeline(PassRefPtr<TimelineEvent> record)
 {
-    RefPtr<TypeBuilder::Timeline::TimelineEvent> record = TypeBuilder::Timeline::TimelineEvent::runtimeCast(prpRecord);
     if (m_recordStack.isEmpty()) {
-        sendEvent(record.release());
+        TraceEventDispatcher::instance()->processBackgroundEvents();
+        sendEvent(record);
     } else {
-        setDOMCounters(record.get());
-        TimelineRecordEntry parent = m_recordStack.last();
-        parent.children->pushObject(record.release());
+        setCounters(record.get());
+        TimelineRecordEntry& parent = m_recordStack.last();
+        parent.children->addItem(record);
     }
 }
 
@@ -1054,41 +1077,34 @@
     return info.usedJSHeapSize;
 }
 
-void InspectorTimelineAgent::setDOMCounters(TypeBuilder::Timeline::TimelineEvent* record)
+void InspectorTimelineAgent::setCounters(TimelineEvent* record)
 {
-    record->setUsedHeapSize(getUsedHeapSize());
-
-    if (m_state->getBoolean(TimelineAgentState::includeDomCounters)) {
-        int documentCount = 0;
-        int nodeCount = 0;
-        int listenerCount = 0;
-        if (m_inspectorType == PageInspector) {
-            documentCount = InspectorCounters::counterValue(InspectorCounters::DocumentCounter);
-            nodeCount = InspectorCounters::counterValue(InspectorCounters::NodeCounter);
-            listenerCount = InspectorCounters::counterValue(InspectorCounters::JSEventListenerCounter);
-        }
-        RefPtr<TypeBuilder::Timeline::DOMCounters> counters = TypeBuilder::Timeline::DOMCounters::create()
-            .setDocuments(documentCount)
-            .setNodes(nodeCount)
-            .setJsEventListeners(listenerCount);
-        record->setCounters(counters.release());
+    if (!m_state->getBoolean(TimelineAgentState::includeCounters))
+        return;
+    RefPtr<TypeBuilder::Timeline::Counters> counters = TypeBuilder::Timeline::Counters::create();
+    if (m_inspectorType == PageInspector) {
+        counters->setDocuments(InspectorCounters::counterValue(InspectorCounters::DocumentCounter));
+        counters->setNodes(InspectorCounters::counterValue(InspectorCounters::NodeCounter));
+        counters->setJsEventListeners(InspectorCounters::counterValue(InspectorCounters::JSEventListenerCounter));
     }
+    counters->setJsHeapSizeUsed(static_cast<double>(getUsedHeapSize()));
+    record->setCounters(counters.release());
 }
 
-void InspectorTimelineAgent::setFrameIdentifier(JSONObject* record, Frame* frame)
+void InspectorTimelineAgent::setFrameIdentifier(TimelineEvent* record, Frame* frame)
 {
     if (!frame || !m_pageAgent)
         return;
     String frameId;
     if (frame && m_pageAgent)
         frameId = m_pageAgent->frameId(frame);
-    record->setString("frameId", frameId);
+    record->setFrameId(frameId);
 }
 
 void InspectorTimelineAgent::populateImageDetails(JSONObject* data, const RenderImage& renderImage)
 {
     const ImageResource* resource = renderImage.cachedImage();
-    TimelineRecordFactory::appendImageDetails(data, nodeId(renderImage.generatingNode()), resource ? resource->url().string() : "");
+    TimelineRecordFactory::setImageDetails(data, nodeId(renderImage.generatingNode()), resource ? resource->url().string() : "");
 }
 
 void InspectorTimelineAgent::didCompleteCurrentRecord(const String& type)
@@ -1105,12 +1121,11 @@
         TimelineRecordEntry entry = m_recordStack.last();
         m_recordStack.removeLast();
         ASSERT(entry.type == type);
-        entry.record->setObject("data", entry.data);
-        entry.record->setArray("children", entry.children);
-        entry.record->setNumber("endTime", timestamp());
+        entry.record->setChildren(entry.children);
+        entry.record->setEndTime(timestamp());
         ptrdiff_t usedHeapSizeDelta = getUsedHeapSize() - entry.usedHeapSizeAtStart;
         if (usedHeapSizeDelta)
-            entry.record->setNumber("usedHeapSizeDelta", usedHeapSizeDelta);
+            entry.record->setUsedHeapSizeDelta(usedHeapSizeDelta);
         addRecordToTimeline(entry.record);
     }
 }
@@ -1123,10 +1138,9 @@
     }
 }
 
-InspectorTimelineAgent::InspectorTimelineAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorOverlay* overlay, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
-    : InspectorBaseAgent<InspectorTimelineAgent>("Timeline", instrumentingAgents, state)
+InspectorTimelineAgent::InspectorTimelineAgent(InspectorPageAgent* pageAgent, InspectorDOMAgent* domAgent, InspectorOverlay* overlay, InspectorType type, InspectorClient* client)
+    : InspectorBaseAgent<InspectorTimelineAgent>("Timeline")
     , m_pageAgent(pageAgent)
-    , m_memoryAgent(memoryAgent)
     , m_domAgent(domAgent)
     , m_frontend(0)
     , m_client(client)
@@ -1146,30 +1160,26 @@
 void InspectorTimelineAgent::appendRecord(PassRefPtr<JSONObject> data, const String& type, bool captureCallStack, Frame* frame)
 {
     pushGCEventRecords();
-    RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(timestamp(), captureCallStack ? m_maxCallStackDepth : 0, type);
-    record->setObject("data", data);
+    RefPtr<TimelineEvent> record = TimelineRecordFactory::createGenericRecord(timestamp(), captureCallStack ? m_maxCallStackDepth : 0, type, data);
     setFrameIdentifier(record.get(), frame);
     addRecordToTimeline(record.release());
 }
 
-void InspectorTimelineAgent::sendEvent(PassRefPtr<JSONObject> event)
+void InspectorTimelineAgent::sendEvent(PassRefPtr<TimelineEvent> record)
 {
-    // FIXME: runtimeCast is a hack. We do it because we can't build TimelineEvent directly now.
-    RefPtr<TypeBuilder::Timeline::TimelineEvent> recordChecked = TypeBuilder::Timeline::TimelineEvent::runtimeCast(event);
-    if (m_bufferedEvents) {
-        m_bufferedEvents->addItem(recordChecked.release());
-        return;
-    }
-    m_frontend->eventRecorded(recordChecked.release());
+    if (m_bufferedEvents)
+        m_bufferedEvents->addItem(record);
+    else
+        m_frontend->eventRecorded(record);
 }
 
 void InspectorTimelineAgent::pushCurrentRecord(PassRefPtr<JSONObject> data, const String& type, bool captureCallStack, Frame* frame, bool hasLowLevelDetails)
 {
     pushGCEventRecords();
     commitFrameRecord();
-    RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(timestamp(), captureCallStack ? m_maxCallStackDepth : 0, type);
+    RefPtr<TimelineEvent> record = TimelineRecordFactory::createGenericRecord(timestamp(), captureCallStack ? m_maxCallStackDepth : 0, type, data.get());
     setFrameIdentifier(record.get(), frame);
-    m_recordStack.append(TimelineRecordEntry(record.release(), data, JSONArray::create(), type, getUsedHeapSize()));
+    m_recordStack.append(TimelineRecordEntry(record.release(), data, TypeBuilder::Array<TimelineEvent>::create(), type, getUsedHeapSize()));
     if (hasLowLevelDetails && !m_platformInstrumentationClientInstalledAtStackDepth && !PlatformInstrumentation::hasClient()) {
         m_platformInstrumentationClientInstalledAtStackDepth = m_recordStack.size();
         PlatformInstrumentation::setClient(this);
@@ -1181,7 +1191,7 @@
     ThreadStateMap::iterator it = m_threadStates.find(thread);
     if (it != m_threadStates.end())
         return it->value;
-    return m_threadStates.add(thread, TimelineThreadState(this)).iterator->value;
+    return m_threadStates.add(thread, TimelineThreadState(this)).storedValue->value;
 }
 
 void InspectorTimelineAgent::commitFrameRecord()
@@ -1235,12 +1245,14 @@
     return m_timeConverter.fromMonotonicallyIncreasingTime(WTF::monotonicallyIncreasingTime());
 }
 
-Page* InspectorTimelineAgent::page()
+FrameHost* InspectorTimelineAgent::frameHost() const
 {
-    return m_pageAgent ? m_pageAgent->page() : 0;
+    if (!m_pageAgent || !m_pageAgent->page())
+        return 0;
+    return &m_pageAgent->page()->frameHost();
 }
 
-PassRefPtr<JSONObject> InspectorTimelineAgent::createRecordForEvent(const TraceEventDispatcher::TraceEvent& event, const String& type, PassRefPtr<JSONObject> data)
+PassRefPtr<TimelineEvent> InspectorTimelineAgent::createRecordForEvent(const TraceEventDispatcher::TraceEvent& event, const String& type, PassRefPtr<JSONObject> data)
 {
     double timeestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
     return TimelineRecordFactory::createBackgroundRecord(timeestamp, String::number(event.threadIdentifier()), type, data);
@@ -1251,9 +1263,9 @@
 {
 }
 
-void TimelineRecordStack::addScopedRecord(PassRefPtr<JSONObject> record)
+void TimelineRecordStack::addScopedRecord(PassRefPtr<TimelineEvent> record, const String& type)
 {
-    m_stack.append(Entry(record));
+    m_stack.append(Entry(record, type));
 }
 
 void TimelineRecordStack::closeScopedRecord(double endTime)
@@ -1262,25 +1274,24 @@
         return;
     Entry last = m_stack.last();
     m_stack.removeLast();
-    last.record->setNumber("endTime", endTime);
+    last.record->setEndTime(endTime);
     if (last.children->length())
-        last.record->setArray("children", last.children);
+        last.record->setChildren(last.children);
     addInstantRecord(last.record);
 }
 
-void TimelineRecordStack::addInstantRecord(PassRefPtr<JSONObject> record)
+void TimelineRecordStack::addInstantRecord(PassRefPtr<TimelineEvent> record)
 {
     if (m_stack.isEmpty())
         m_timelineAgent->sendEvent(record);
     else
-        m_stack.last().children->pushObject(record);
+        m_stack.last().children->addItem(record);
 }
 
 #ifndef NDEBUG
 bool TimelineRecordStack::isOpenRecordOfType(const String& type)
 {
-    String lastRecordType;
-    return m_stack.isEmpty() || (m_stack.last().record->getString("type", &lastRecordType) && type == lastRecordType);
+    return !m_stack.isEmpty() && m_stack.last().type == type;
 }
 #endif
 
diff --git a/Source/core/inspector/InspectorTimelineAgent.h b/Source/core/inspector/InspectorTimelineAgent.h
index 10b1d94..7f85231 100644
--- a/Source/core/inspector/InspectorTimelineAgent.h
+++ b/Source/core/inspector/InspectorTimelineAgent.h
@@ -33,6 +33,7 @@
 
 
 #include "InspectorFrontend.h"
+#include "InspectorTypeBuilder.h"
 #include "bindings/v8/ScriptGCEvent.h"
 #include "core/events/EventPath.h"
 #include "core/inspector/InspectorBaseAgent.h"
@@ -56,20 +57,20 @@
 class Document;
 class DocumentLoader;
 class Event;
+class ExecutionContext;
 class FloatQuad;
 class Frame;
+class FrameHost;
 class GraphicsContext;
 class GraphicsLayer;
 class InspectorClient;
 class InspectorDOMAgent;
 class InspectorFrontend;
-class InspectorMemoryAgent;
 class InspectorOverlay;
 class InspectorPageAgent;
 class InstrumentingAgents;
 class KURL;
 class Node;
-class Page;
 class RenderImage;
 class RenderObject;
 class ResourceError;
@@ -78,24 +79,14 @@
 class ResourceResponse;
 class ScriptArguments;
 class ScriptCallStack;
-class TimelineRecordStack;
-class ExecutionContext;
 class ScriptState;
+class TimelineRecordStack;
 class WebSocketHandshakeRequest;
 class WebSocketHandshakeResponse;
 class XMLHttpRequest;
 
 typedef String ErrorString;
 
-namespace TimelineRecordType {
-extern const char ActivateLayerTree[];
-extern const char BeginFrame[];
-extern const char DecodeImage[];
-extern const char GPUTask[];
-extern const char PaintSetup[];
-extern const char Rasterize[];
-};
-
 class TimelineTimeConverter {
 public:
     TimelineTimeConverter()
@@ -109,7 +100,7 @@
     double m_startOffset;
 };
 
-class InspectorTimelineAgent
+class InspectorTimelineAgent FINAL
     : public TraceEventTarget<InspectorTimelineAgent>
     , public InspectorBaseAgent<InspectorTimelineAgent>
     , public ScriptGCEventListener
@@ -133,21 +124,21 @@
         size_t usedGPUMemoryBytes;
     };
 
-    static PassOwnPtr<InspectorTimelineAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorOverlay* overlay, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
+    static PassOwnPtr<InspectorTimelineAgent> create(InspectorPageAgent* pageAgent, InspectorDOMAgent* domAgent, InspectorOverlay* overlay, InspectorType type, InspectorClient* client)
     {
-        return adoptPtr(new InspectorTimelineAgent(instrumentingAgents, pageAgent, memoryAgent, domAgent, overlay, state, type, client));
+        return adoptPtr(new InspectorTimelineAgent(pageAgent, domAgent, overlay, type, client));
     }
 
-    ~InspectorTimelineAgent();
+    virtual ~InspectorTimelineAgent();
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
 
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void start(ErrorString*, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters, const bool* includeGPUEvents);
-    virtual void stop(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> >& events);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void start(ErrorString*, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeCounters, const bool* includeGPUEvents) OVERRIDE;
+    virtual void stop(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> >& events) OVERRIDE;
 
     void setLayerTreeId(int layerTreeId) { m_layerTreeId = layerTreeId; }
     int id() const { return m_id; }
@@ -218,8 +209,8 @@
     void didScheduleResourceRequest(Document*, const String& url);
     void willSendRequest(unsigned long, DocumentLoader*, const ResourceRequest&, const ResourceResponse&, const FetchInitiatorInfo&);
     void didReceiveResourceResponse(Frame*, unsigned long, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
-    void didFinishLoading(unsigned long, DocumentLoader*, double monotonicFinishTime);
-    void didFailLoading(unsigned long identifier, DocumentLoader* loader, const ResourceError& error);
+    void didFinishLoading(unsigned long, DocumentLoader*, double monotonicFinishTime, int64_t);
+    void didFailLoading(unsigned long identifier, const ResourceError&);
     bool willReceiveResourceData(Frame*, unsigned long identifier, int length);
     void didReceiveResourceData();
 
@@ -239,7 +230,7 @@
     void processGPUEvent(const GPUEvent&);
 
     // ScriptGCEventListener methods.
-    virtual void didGC(double, double, size_t);
+    virtual void didGC(double, double, size_t) OVERRIDE;
 
     // PlatformInstrumentationClient methods.
     virtual void willDecodeImage(const String& imageType) OVERRIDE;
@@ -251,7 +242,7 @@
 
     friend class TimelineRecordStack;
 
-    InspectorTimelineAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorMemoryAgent*, InspectorDOMAgent*, InspectorOverlay*, InspectorCompositeState*, InspectorType, InspectorClient*);
+    InspectorTimelineAgent(InspectorPageAgent*, InspectorDOMAgent*, InspectorOverlay*, InspectorType, InspectorClient*);
 
     // Trace event handlers
     void onBeginImplSideFrame(const TraceEventDispatcher::TraceEvent&);
@@ -265,18 +256,20 @@
     void onDrawLazyPixelRef(const TraceEventDispatcher::TraceEvent&);
     void onDecodeLazyPixelRefBegin(const TraceEventDispatcher::TraceEvent&);
     void onDecodeLazyPixelRefEnd(const TraceEventDispatcher::TraceEvent&);
+    void onRequestMainThreadFrame(const TraceEventDispatcher::TraceEvent&);
     void onActivateLayerTree(const TraceEventDispatcher::TraceEvent&);
+    void onDrawFrame(const TraceEventDispatcher::TraceEvent&);
     void onLazyPixelRefDeleted(const TraceEventDispatcher::TraceEvent&);
 
-    void didFinishLoadingResource(unsigned long, bool didFail, double finishTime, Frame*);
+    void didFinishLoadingResource(unsigned long, bool didFail, double finishTime);
 
-    void sendEvent(PassRefPtr<JSONObject>);
+    void sendEvent(PassRefPtr<TypeBuilder::Timeline::TimelineEvent>);
     void appendRecord(PassRefPtr<JSONObject> data, const String& type, bool captureCallStack, Frame*);
-    void pushCurrentRecord(PassRefPtr<JSONObject>, const String& type, bool captureCallStack, Frame*, bool hasLowLevelDetails = false);
+    void pushCurrentRecord(PassRefPtr<JSONObject> data, const String& type, bool captureCallStack, Frame*, bool hasLowLevelDetails = false);
     TimelineThreadState& threadState(ThreadIdentifier);
 
-    void setDOMCounters(TypeBuilder::Timeline::TimelineEvent*);
-    void setFrameIdentifier(JSONObject* record, Frame*);
+    void setCounters(TypeBuilder::Timeline::TimelineEvent*);
+    void setFrameIdentifier(TypeBuilder::Timeline::TimelineEvent* record, Frame*);
     void populateImageDetails(JSONObject* data, const RenderImage&);
 
     void pushGCEventRecords();
@@ -286,10 +279,10 @@
 
     void commitFrameRecord();
 
-    void addRecordToTimeline(PassRefPtr<JSONObject>);
-    void innerAddRecordToTimeline(PassRefPtr<JSONObject>);
+    void addRecordToTimeline(PassRefPtr<TypeBuilder::Timeline::TimelineEvent>);
+    void innerAddRecordToTimeline(PassRefPtr<TypeBuilder::Timeline::TimelineEvent>);
     void clearRecordStack();
-    PassRefPtr<JSONObject> createRecordForEvent(const TraceEventDispatcher::TraceEvent&, const String& type, PassRefPtr<JSONObject> data = 0);
+    PassRefPtr<TypeBuilder::Timeline::TimelineEvent> createRecordForEvent(const TraceEventDispatcher::TraceEvent&, const String& type, PassRefPtr<JSONObject> data);
 
     void localToPageQuad(const RenderObject& renderer, const LayoutRect&, FloatQuad*);
     long long nodeId(Node*);
@@ -297,14 +290,14 @@
     void releaseNodeIds();
 
     double timestamp();
-    Page* page();
+
+    FrameHost* frameHost() const;
 
     bool isStarted();
     void innerStart();
     void innerStop(bool fromConsole);
 
     InspectorPageAgent* m_pageAgent;
-    InspectorMemoryAgent* m_memoryAgent;
     InspectorDOMAgent* m_domAgent;
     InspectorFrontend::Timeline* m_frontend;
     InspectorClient* m_client;
@@ -324,8 +317,8 @@
     typedef Vector<TimelineGCEvent> GCEvents;
     GCEvents m_gcEvents;
     unsigned m_platformInstrumentationClientInstalledAtStackDepth;
-    RefPtr<JSONObject> m_pendingFrameRecord;
-    RefPtr<JSONObject> m_pendingGPURecord;
+    RefPtr<TypeBuilder::Timeline::TimelineEvent> m_pendingFrameRecord;
+    RefPtr<TypeBuilder::Timeline::TimelineEvent> m_pendingGPURecord;
     typedef HashMap<unsigned long long, TimelineImageInfo> PixelRefToImageInfoMap;
     PixelRefToImageInfoMap m_pixelRefToImageInfo;
     RenderImage* m_imageBeingPainted;
diff --git a/Source/core/inspector/InspectorWorkerAgent.cpp b/Source/core/inspector/InspectorWorkerAgent.cpp
index c4b9191..3469d9f 100644
--- a/Source/core/inspector/InspectorWorkerAgent.cpp
+++ b/Source/core/inspector/InspectorWorkerAgent.cpp
@@ -49,7 +49,7 @@
 static const char autoconnectToWorkers[] = "autoconnectToWorkers";
 };
 
-class InspectorWorkerAgent::WorkerFrontendChannel : public WorkerGlobalScopeProxy::PageInspector {
+class InspectorWorkerAgent::WorkerFrontendChannel FINAL : public WorkerGlobalScopeProxy::PageInspector {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit WorkerFrontendChannel(InspectorFrontend* frontend, WorkerGlobalScopeProxy* proxy)
@@ -85,7 +85,7 @@
 
 private:
     // WorkerGlobalScopeProxy::PageInspector implementation
-    virtual void dispatchMessageFromWorker(const String& message)
+    virtual void dispatchMessageFromWorker(const String& message) OVERRIDE
     {
         RefPtr<JSONValue> value = parseJSON(message);
         if (!value)
@@ -105,16 +105,15 @@
 
 int InspectorWorkerAgent::WorkerFrontendChannel::s_nextId = 1;
 
-PassOwnPtr<InspectorWorkerAgent> InspectorWorkerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState)
+PassOwnPtr<InspectorWorkerAgent> InspectorWorkerAgent::create()
 {
-    return adoptPtr(new InspectorWorkerAgent(instrumentingAgents, inspectorState));
+    return adoptPtr(new InspectorWorkerAgent());
 }
 
-InspectorWorkerAgent::InspectorWorkerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState)
-    : InspectorBaseAgent<InspectorWorkerAgent>("Worker", instrumentingAgents, inspectorState)
+InspectorWorkerAgent::InspectorWorkerAgent()
+    : InspectorBaseAgent<InspectorWorkerAgent>("Worker")
     , m_inspectorFrontend(0)
 {
-    m_instrumentingAgents->setInspectorWorkerAgent(this);
 }
 
 InspectorWorkerAgent::~InspectorWorkerAgent()
@@ -122,6 +121,11 @@
     m_instrumentingAgents->setInspectorWorkerAgent(0);
 }
 
+void InspectorWorkerAgent::init()
+{
+    m_instrumentingAgents->setInspectorWorkerAgent(this);
+}
+
 void InspectorWorkerAgent::setFrontend(InspectorFrontend* frontend)
 {
     m_inspectorFrontend = frontend;
diff --git a/Source/core/inspector/InspectorWorkerAgent.h b/Source/core/inspector/InspectorWorkerAgent.h
index 316f854..986439e 100644
--- a/Source/core/inspector/InspectorWorkerAgent.h
+++ b/Source/core/inspector/InspectorWorkerAgent.h
@@ -44,14 +44,15 @@
 
 typedef String ErrorString;
 
-class InspectorWorkerAgent : public InspectorBaseAgent<InspectorWorkerAgent>, public InspectorBackendDispatcher::WorkerCommandHandler {
+class InspectorWorkerAgent FINAL : public InspectorBaseAgent<InspectorWorkerAgent>, public InspectorBackendDispatcher::WorkerCommandHandler {
 public:
-    static PassOwnPtr<InspectorWorkerAgent> create(InstrumentingAgents*, InspectorCompositeState*);
-    ~InspectorWorkerAgent();
+    static PassOwnPtr<InspectorWorkerAgent> create();
+    virtual ~InspectorWorkerAgent();
 
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void restore();
-    virtual void clearFrontend();
+    virtual void init() OVERRIDE;
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void restore() OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
 
     // Called from InspectorInstrumentation
     bool shouldPauseDedicatedWorkerOnStart();
@@ -59,16 +60,16 @@
     void workerGlobalScopeTerminated(WorkerGlobalScopeProxy*);
 
     // Called from InspectorBackendDispatcher
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
-    virtual void canInspectWorkers(ErrorString*, bool*);
-    virtual void connectToWorker(ErrorString*, int workerId);
-    virtual void disconnectFromWorker(ErrorString*, int workerId);
-    virtual void sendMessageToWorker(ErrorString*, int workerId, const RefPtr<JSONObject>& message);
-    virtual void setAutoconnectToWorkers(ErrorString*, bool value);
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
+    virtual void canInspectWorkers(ErrorString*, bool*) OVERRIDE;
+    virtual void connectToWorker(ErrorString*, int workerId) OVERRIDE;
+    virtual void disconnectFromWorker(ErrorString*, int workerId) OVERRIDE;
+    virtual void sendMessageToWorker(ErrorString*, int workerId, const RefPtr<JSONObject>& message) OVERRIDE;
+    virtual void setAutoconnectToWorkers(ErrorString*, bool value) OVERRIDE;
 
 private:
-    InspectorWorkerAgent(InstrumentingAgents*, InspectorCompositeState*);
+    InspectorWorkerAgent();
     void createWorkerFrontendChannelsForExistingWorkers();
     void createWorkerFrontendChannel(WorkerGlobalScopeProxy*, const String& url);
     void destroyWorkerFrontendChannels();
diff --git a/Source/core/inspector/JavaScriptCallFrame.cpp b/Source/core/inspector/JavaScriptCallFrame.cpp
index ae2d659..38032cc 100644
--- a/Source/core/inspector/JavaScriptCallFrame.cpp
+++ b/Source/core/inspector/JavaScriptCallFrame.cpp
@@ -97,7 +97,7 @@
     v8::HandleScope handleScope(m_isolate);
     v8::Context::Scope contextScope(m_debuggerContext.newLocal(m_isolate));
     v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "functionName"));
-    return toWebCoreStringWithUndefinedOrNullCheck(result);
+    return toCoreStringWithUndefinedOrNullCheck(result);
 }
 
 v8::Handle<v8::Value> JavaScriptCallFrame::scopeChain() const
@@ -125,7 +125,7 @@
     v8::Handle<v8::Object> callFrame = m_callFrame.newLocal(m_isolate);
     v8::Handle<v8::Function> stepInPositions = v8::Handle<v8::Function>::Cast(callFrame->Get(v8AtomicString(m_isolate, "stepInPositions")));
     v8::Handle<v8::Value> result = stepInPositions->Call(callFrame, 0, 0);
-    return toWebCoreStringWithUndefinedOrNullCheck(result);
+    return toCoreStringWithUndefinedOrNullCheck(result);
 }
 
 bool JavaScriptCallFrame::isAtReturn() const
@@ -171,7 +171,7 @@
     v8::Handle<v8::Object> callFrame = m_callFrame.newLocal(m_isolate);
     v8::Handle<v8::Function> setVariableValueFunction = v8::Handle<v8::Function>::Cast(callFrame->Get(v8AtomicString(m_isolate, "setVariableValue")));
     v8::Handle<v8::Value> argv[] = {
-        v8::Handle<v8::Value>(v8::Integer::New(scopeNumber, m_isolate)),
+        v8::Handle<v8::Value>(v8::Integer::New(m_isolate, scopeNumber)),
         v8String(m_isolate, variableName),
         newValue.v8Value()
     };
diff --git a/Source/core/inspector/NetworkResourcesData.cpp b/Source/core/inspector/NetworkResourcesData.cpp
index 3427421..aef2d8d 100644
--- a/Source/core/inspector/NetworkResourcesData.cpp
+++ b/Source/core/inspector/NetworkResourcesData.cpp
@@ -31,6 +31,7 @@
 
 #include "core/dom/DOMImplementation.h"
 #include "core/fetch/Resource.h"
+#include "platform/MIMETypeRegistry.h"
 #include "platform/SharedBuffer.h"
 #include "platform/network/ResourceResponse.h"
 
@@ -45,9 +46,9 @@
 namespace WebCore {
 
 
-PassRefPtr<XHRReplayData> XHRReplayData::create(const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData> formData, bool includeCredentials)
+PassRefPtr<XHRReplayData> XHRReplayData::create(ExecutionContext* executionContext, const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData> formData, bool includeCredentials)
 {
-    return adoptRef(new XHRReplayData(method, url, async, formData, includeCredentials));
+    return adoptRef(new XHRReplayData(executionContext, method, url, async, formData, includeCredentials));
 }
 
 void XHRReplayData::addHeader(const AtomicString& key, const AtomicString& value)
@@ -55,8 +56,9 @@
     m_headers.set(key, value);
 }
 
-XHRReplayData::XHRReplayData(const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData> formData, bool includeCredentials)
-    : m_method(method)
+XHRReplayData::XHRReplayData(ExecutionContext* executionContext, const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData> formData, bool includeCredentials)
+    : ContextLifecycleObserver(executionContext)
+    , m_method(method)
     , m_url(url)
     , m_async(async)
     , m_formData(formData)
@@ -130,7 +132,7 @@
     ASSERT(!hasContent());
     size_t dataLength = m_dataBuffer->size();
     m_content = m_decoder->decode(m_dataBuffer->data(), m_dataBuffer->size());
-    m_content.append(m_decoder->flush());
+    m_content = m_content + m_decoder->flush();
     m_dataBuffer = nullptr;
     return contentSizeInBytes(m_content) - dataLength;
 }
@@ -157,15 +159,18 @@
 static PassOwnPtr<TextResourceDecoder> createOtherResourceTextDecoder(const String& mimeType, const String& textEncodingName)
 {
     OwnPtr<TextResourceDecoder> decoder;
-    if (!textEncodingName.isEmpty())
+    if (!textEncodingName.isEmpty()) {
         decoder = TextResourceDecoder::create("text/plain", textEncodingName);
-    else if (DOMImplementation::isXMLMIMEType(mimeType.lower())) {
+    } else if (DOMImplementation::isXMLMIMEType(mimeType)) {
         decoder = TextResourceDecoder::create("application/xml");
         decoder->useLenientXMLDecoding();
-    } else if (equalIgnoringCase(mimeType, "text/html"))
+    } else if (equalIgnoringCase(mimeType, "text/html")) {
         decoder = TextResourceDecoder::create("text/html", "UTF-8");
-    else if (mimeType == "text/plain")
+    } else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType) || DOMImplementation::isJSONMIMEType(mimeType)) {
+        decoder = TextResourceDecoder::create("text/plain", "UTF-8");
+    } else if (DOMImplementation::isTextMIMEType(mimeType)) {
         decoder = TextResourceDecoder::create("text/plain", "ISO-8859-1");
+    }
     return decoder.release();
 }
 
diff --git a/Source/core/inspector/NetworkResourcesData.h b/Source/core/inspector/NetworkResourcesData.h
index 672f588..9b6dd1f 100644
--- a/Source/core/inspector/NetworkResourcesData.h
+++ b/Source/core/inspector/NetworkResourcesData.h
@@ -29,7 +29,8 @@
 #ifndef NetworkResourcesData_h
 #define NetworkResourcesData_h
 
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/dom/ContextLifecycleObserver.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "platform/network/HTTPHeaderMap.h"
 #include "platform/weborigin/KURL.h"
@@ -41,15 +42,18 @@
 
 namespace WebCore {
 
+class ExecutionContext;
 class Resource;
 class FormData;
 class ResourceResponse;
 class SharedBuffer;
 class TextResourceDecoder;
 
-class XHRReplayData : public RefCounted<XHRReplayData> {
+class XHRReplayData
+    : public RefCounted<XHRReplayData>
+    , public ContextLifecycleObserver {
 public:
-    static PassRefPtr<XHRReplayData> create(const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData>, bool includeCredentials);
+    static PassRefPtr<XHRReplayData> create(ExecutionContext*, const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData>, bool includeCredentials);
 
     void addHeader(const AtomicString& key, const AtomicString& value);
     const AtomicString& method() const { return m_method; }
@@ -60,7 +64,7 @@
     bool includeCredentials() const { return m_includeCredentials; }
 
 private:
-    XHRReplayData(const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData>, bool includeCredentials);
+    XHRReplayData(ExecutionContext*, const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData>, bool includeCredentials);
 
     AtomicString m_method;
     KURL m_url;
diff --git a/Source/core/inspector/PageConsoleAgent.cpp b/Source/core/inspector/PageConsoleAgent.cpp
index 8418b37..122b636 100644
--- a/Source/core/inspector/PageConsoleAgent.cpp
+++ b/Source/core/inspector/PageConsoleAgent.cpp
@@ -39,8 +39,8 @@
 
 namespace WebCore {
 
-PageConsoleAgent::PageConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, InspectorDOMAgent* domAgent, InspectorTimelineAgent* timelineAgent)
-    : InspectorConsoleAgent(instrumentingAgents, timelineAgent, state, injectedScriptManager)
+PageConsoleAgent::PageConsoleAgent(InjectedScriptManager* injectedScriptManager, InspectorDOMAgent* domAgent, InspectorTimelineAgent* timelineAgent)
+    : InspectorConsoleAgent(timelineAgent, injectedScriptManager)
     , m_inspectorDOMAgent(domAgent)
 {
 }
@@ -56,10 +56,10 @@
     InspectorConsoleAgent::clearMessages(errorString);
 }
 
-class InspectableNode : public InjectedScriptHost::InspectableObject {
+class InspectableNode FINAL : public InjectedScriptHost::InspectableObject {
 public:
     explicit InspectableNode(Node* node) : m_node(node) { }
-    virtual ScriptValue get(ScriptState* state)
+    virtual ScriptValue get(ScriptState* state) OVERRIDE
     {
         return InjectedScriptHost::nodeAsScriptValue(state, m_node);
     }
diff --git a/Source/core/inspector/PageConsoleAgent.h b/Source/core/inspector/PageConsoleAgent.h
index 4cca695..4dbf7f6 100644
--- a/Source/core/inspector/PageConsoleAgent.h
+++ b/Source/core/inspector/PageConsoleAgent.h
@@ -38,21 +38,21 @@
 
 class InspectorDOMAgent;
 
-class PageConsoleAgent : public InspectorConsoleAgent {
+class PageConsoleAgent FINAL : public InspectorConsoleAgent {
     WTF_MAKE_NONCOPYABLE(PageConsoleAgent);
 public:
-    static PassOwnPtr<PageConsoleAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, InspectorDOMAgent* domAgent, InspectorTimelineAgent* timelineAgent)
+    static PassOwnPtr<PageConsoleAgent> create(InjectedScriptManager* injectedScriptManager, InspectorDOMAgent* domAgent, InspectorTimelineAgent* timelineAgent)
     {
-        return adoptPtr(new PageConsoleAgent(instrumentingAgents, state, injectedScriptManager, domAgent, timelineAgent));
+        return adoptPtr(new PageConsoleAgent(injectedScriptManager, domAgent, timelineAgent));
     }
     virtual ~PageConsoleAgent();
 
     virtual bool isWorkerAgent() OVERRIDE { return false; }
 
 private:
-    PageConsoleAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, InspectorDOMAgent*, InspectorTimelineAgent*);
-    virtual void clearMessages(ErrorString*);
-    virtual void addInspectedNode(ErrorString*, int nodeId);
+    PageConsoleAgent(InjectedScriptManager*, InspectorDOMAgent*, InspectorTimelineAgent*);
+    virtual void clearMessages(ErrorString*) OVERRIDE;
+    virtual void addInspectedNode(ErrorString*, int nodeId) OVERRIDE;
 
     InspectorDOMAgent* m_inspectorDOMAgent;
 };
diff --git a/Source/core/inspector/PageDebuggerAgent.cpp b/Source/core/inspector/PageDebuggerAgent.cpp
index 5e9323b..1738b2b 100644
--- a/Source/core/inspector/PageDebuggerAgent.cpp
+++ b/Source/core/inspector/PageDebuggerAgent.cpp
@@ -34,23 +34,23 @@
 #include "bindings/v8/DOMWrapperWorld.h"
 #include "bindings/v8/ScriptController.h"
 #include "bindings/v8/ScriptSourceCode.h"
+#include "core/frame/Frame.h"
+#include "core/frame/PageConsole.h"
 #include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/page/PageConsole.h"
 
 namespace WebCore {
 
-PassOwnPtr<PageDebuggerAgent> PageDebuggerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, PageScriptDebugServer* pageScriptDebugServer, InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
+PassOwnPtr<PageDebuggerAgent> PageDebuggerAgent::create(PageScriptDebugServer* pageScriptDebugServer, InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
 {
-    return adoptPtr(new PageDebuggerAgent(instrumentingAgents, inspectorState, pageScriptDebugServer, pageAgent, injectedScriptManager, overlay));
+    return adoptPtr(new PageDebuggerAgent(pageScriptDebugServer, pageAgent, injectedScriptManager, overlay));
 }
 
-PageDebuggerAgent::PageDebuggerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, PageScriptDebugServer* pageScriptDebugServer, InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
-    : InspectorDebuggerAgent(instrumentingAgents, inspectorState, injectedScriptManager)
+PageDebuggerAgent::PageDebuggerAgent(PageScriptDebugServer* pageScriptDebugServer, InspectorPageAgent* pageAgent, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
+    : InspectorDebuggerAgent(injectedScriptManager)
     , m_pageScriptDebugServer(pageScriptDebugServer)
     , m_pageAgent(pageAgent)
     , m_overlay(overlay)
@@ -128,9 +128,9 @@
     m_overlay->setPausedInDebuggerMessage(message);
 }
 
-void PageDebuggerAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world)
+void PageDebuggerAgent::didClearWindowObjectInMainWorld(Frame* frame)
 {
-    if (world != mainThreadNormalWorld() || frame != m_pageAgent->mainFrame())
+    if (frame != m_pageAgent->mainFrame())
         return;
 
     reset();
diff --git a/Source/core/inspector/PageDebuggerAgent.h b/Source/core/inspector/PageDebuggerAgent.h
index fa66819..4316666 100644
--- a/Source/core/inspector/PageDebuggerAgent.h
+++ b/Source/core/inspector/PageDebuggerAgent.h
@@ -44,39 +44,39 @@
 class PageScriptDebugServer;
 class ScriptSourceCode;
 
-class PageDebuggerAgent :
+class PageDebuggerAgent FINAL :
     public InspectorDebuggerAgent,
     public InspectorOverlayHost::Listener {
     WTF_MAKE_NONCOPYABLE(PageDebuggerAgent);
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<PageDebuggerAgent> create(InstrumentingAgents*, InspectorCompositeState*, PageScriptDebugServer*, InspectorPageAgent*, InjectedScriptManager*, InspectorOverlay*);
+    static PassOwnPtr<PageDebuggerAgent> create(PageScriptDebugServer*, InspectorPageAgent*, InjectedScriptManager*, InspectorOverlay*);
     virtual ~PageDebuggerAgent();
 
-    void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
+    void didClearWindowObjectInMainWorld(Frame*);
     String preprocessEventListener(Frame*, const String& source, const String& url, const String& functionName);
     PassOwnPtr<ScriptSourceCode> preprocess(Frame*, const ScriptSourceCode&);
     void didCommitLoad(Frame*, DocumentLoader*);
 
 protected:
-    virtual void enable();
-    virtual void disable();
+    virtual void enable() OVERRIDE;
+    virtual void disable() OVERRIDE;
 
 private:
-    virtual void startListeningScriptDebugServer();
-    virtual void stopListeningScriptDebugServer();
-    virtual PageScriptDebugServer& scriptDebugServer();
-    virtual void muteConsole();
-    virtual void unmuteConsole();
+    virtual void startListeningScriptDebugServer() OVERRIDE;
+    virtual void stopListeningScriptDebugServer() OVERRIDE;
+    virtual PageScriptDebugServer& scriptDebugServer() OVERRIDE;
+    virtual void muteConsole() OVERRIDE;
+    virtual void unmuteConsole() OVERRIDE;
 
     // InspectorOverlayHost::Listener implementation.
-    virtual void overlayResumed();
-    virtual void overlaySteppedOver();
+    virtual void overlayResumed() OVERRIDE;
+    virtual void overlaySteppedOver() OVERRIDE;
 
-    virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId);
-    virtual void setOverlayMessage(ErrorString*, const String*);
+    virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId) OVERRIDE;
+    virtual void setOverlayMessage(ErrorString*, const String*) OVERRIDE;
 
-    PageDebuggerAgent(InstrumentingAgents*, InspectorCompositeState*, PageScriptDebugServer*, InspectorPageAgent*, InjectedScriptManager*, InspectorOverlay*);
+    PageDebuggerAgent(PageScriptDebugServer*, InspectorPageAgent*, InjectedScriptManager*, InspectorOverlay*);
     PageScriptDebugServer* m_pageScriptDebugServer;
     InspectorPageAgent* m_pageAgent;
     InspectorOverlay* m_overlay;
diff --git a/Source/core/inspector/PageRuntimeAgent.cpp b/Source/core/inspector/PageRuntimeAgent.cpp
index 78d2bbc..72102c7 100644
--- a/Source/core/inspector/PageRuntimeAgent.cpp
+++ b/Source/core/inspector/PageRuntimeAgent.cpp
@@ -33,14 +33,14 @@
 
 #include "bindings/v8/DOMWrapperWorld.h"
 #include "bindings/v8/ScriptController.h"
+#include "core/frame/Frame.h"
+#include "core/frame/PageConsole.h"
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InjectedScriptManager.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
 #include "core/inspector/InstrumentingAgents.h"
-#include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/page/PageConsole.h"
 #include "platform/weborigin/SecurityOrigin.h"
 
 using WebCore::TypeBuilder::Runtime::ExecutionContextDescription;
@@ -51,14 +51,13 @@
 static const char runtimeEnabled[] = "runtimeEnabled";
 };
 
-PageRuntimeAgent::PageRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, Page* page, InspectorPageAgent* pageAgent)
-    : InspectorRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer)
+PageRuntimeAgent::PageRuntimeAgent(InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, Page* page, InspectorPageAgent* pageAgent)
+    : InspectorRuntimeAgent(injectedScriptManager, scriptDebugServer)
     , m_inspectedPage(page)
     , m_pageAgent(pageAgent)
     , m_frontend(0)
     , m_mainWorldContextCreated(false)
 {
-    m_instrumentingAgents->setPageRuntimeAgent(this);
 }
 
 PageRuntimeAgent::~PageRuntimeAgent()
@@ -66,6 +65,11 @@
     m_instrumentingAgents->setPageRuntimeAgent(0);
 }
 
+void PageRuntimeAgent::init()
+{
+    m_instrumentingAgents->setPageRuntimeAgent(this);
+}
+
 void PageRuntimeAgent::setFrontend(InspectorFrontend* frontend)
 {
     m_frontend = frontend->runtime();
@@ -109,11 +113,8 @@
     m_state->setBoolean(PageRuntimeAgentState::runtimeEnabled, false);
 }
 
-void PageRuntimeAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world)
+void PageRuntimeAgent::didClearWindowObjectInMainWorld(Frame* frame)
 {
-    if (world != mainThreadNormalWorld())
-        return;
-
     m_mainWorldContextCreated = true;
 
     if (!m_enabled)
diff --git a/Source/core/inspector/PageRuntimeAgent.h b/Source/core/inspector/PageRuntimeAgent.h
index 27e635b..c78f418 100644
--- a/Source/core/inspector/PageRuntimeAgent.h
+++ b/Source/core/inspector/PageRuntimeAgent.h
@@ -42,28 +42,29 @@
 class Page;
 class SecurityOrigin;
 
-class PageRuntimeAgent : public InspectorRuntimeAgent {
+class PageRuntimeAgent FINAL : public InspectorRuntimeAgent {
 public:
-    static PassOwnPtr<PageRuntimeAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, Page* page, InspectorPageAgent* pageAgent)
+    static PassOwnPtr<PageRuntimeAgent> create(InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, Page* page, InspectorPageAgent* pageAgent)
     {
-        return adoptPtr(new PageRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer, page, pageAgent));
+        return adoptPtr(new PageRuntimeAgent(injectedScriptManager, scriptDebugServer, page, pageAgent));
     }
     virtual ~PageRuntimeAgent();
-    virtual void setFrontend(InspectorFrontend*);
-    virtual void clearFrontend();
-    virtual void restore();
-    virtual void enable(ErrorString*);
-    virtual void disable(ErrorString*);
+    virtual void init() OVERRIDE;
+    virtual void setFrontend(InspectorFrontend*) OVERRIDE;
+    virtual void clearFrontend() OVERRIDE;
+    virtual void restore() OVERRIDE;
+    virtual void enable(ErrorString*) OVERRIDE;
+    virtual void disable(ErrorString*) OVERRIDE;
 
-    void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
+    void didClearWindowObjectInMainWorld(Frame*);
     void didCreateIsolatedContext(Frame*, ScriptState*, SecurityOrigin*);
 
 private:
-    PageRuntimeAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, ScriptDebugServer*, Page*, InspectorPageAgent*);
+    PageRuntimeAgent(InjectedScriptManager*, ScriptDebugServer*, Page*, InspectorPageAgent*);
 
-    virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId);
-    virtual void muteConsole();
-    virtual void unmuteConsole();
+    virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId) OVERRIDE;
+    virtual void muteConsole() OVERRIDE;
+    virtual void unmuteConsole() OVERRIDE;
     void reportExecutionContextCreation();
     void notifyContextCreated(const String& frameId, ScriptState*, SecurityOrigin*, bool isPageContext);
 
diff --git a/Source/core/inspector/ScriptProfile.cpp b/Source/core/inspector/ScriptProfile.cpp
index e77883e..7313538 100644
--- a/Source/core/inspector/ScriptProfile.cpp
+++ b/Source/core/inspector/ScriptProfile.cpp
@@ -46,12 +46,7 @@
 String ScriptProfile::title() const
 {
     v8::HandleScope scope(v8::Isolate::GetCurrent());
-    return toWebCoreString(m_profile->GetTitle());
-}
-
-unsigned int ScriptProfile::uid() const
-{
-    return m_profile->GetUid();
+    return toCoreString(m_profile->GetTitle());
 }
 
 double ScriptProfile::idleTime() const
@@ -81,9 +76,9 @@
     }
 
     RefPtr<TypeBuilder::Profiler::CPUProfileNode> result = TypeBuilder::Profiler::CPUProfileNode::create()
-        .setFunctionName(toWebCoreString(node->GetFunctionName()))
+        .setFunctionName(toCoreString(node->GetFunctionName()))
         .setScriptId(String::number(node->GetScriptId()))
-        .setUrl(toWebCoreString(node->GetScriptResourceName()))
+        .setUrl(toCoreString(node->GetScriptResourceName()))
         .setLineNumber(node->GetLineNumber())
         .setColumnNumber(node->GetColumnNumber())
         .setHitCount(node->GetHitCount())
diff --git a/Source/core/inspector/ScriptProfile.h b/Source/core/inspector/ScriptProfile.h
index 0a99d89..162c0b8 100644
--- a/Source/core/inspector/ScriptProfile.h
+++ b/Source/core/inspector/ScriptProfile.h
@@ -50,7 +50,6 @@
     ~ScriptProfile();
 
     String title() const;
-    unsigned int uid() const;
     double idleTime() const;
 
     double startTime() const;
diff --git a/Source/core/inspector/TimelineRecordFactory.cpp b/Source/core/inspector/TimelineRecordFactory.cpp
index b0fd28a..9ea01aa 100644
--- a/Source/core/inspector/TimelineRecordFactory.cpp
+++ b/Source/core/inspector/TimelineRecordFactory.cpp
@@ -42,27 +42,31 @@
 
 namespace WebCore {
 
-PassRefPtr<JSONObject> TimelineRecordFactory::createGenericRecord(double startTime, int maxCallStackDepth, const String& type)
-{
-    RefPtr<JSONObject> record = JSONObject::create();
-    record->setNumber("startTime", startTime);
+using TypeBuilder::Timeline::TimelineEvent;
 
+PassRefPtr<TimelineEvent> TimelineRecordFactory::createGenericRecord(double startTime, int maxCallStackDepth, const String& type, PassRefPtr<JSONObject> data)
+{
+    ASSERT(data.get());
+    RefPtr<TimelineEvent> record = TimelineEvent::create()
+        .setType(type)
+        .setData(data)
+        .setStartTime(startTime);
     if (maxCallStackDepth) {
         RefPtr<ScriptCallStack> stackTrace = createScriptCallStack(maxCallStackDepth, true);
         if (stackTrace && stackTrace->size())
-            record->setValue("stackTrace", stackTrace->buildInspectorArray());
+            record->setStackTrace(stackTrace->buildInspectorArray());
     }
-    record->setString("type", type);
     return record.release();
 }
 
-PassRefPtr<JSONObject> TimelineRecordFactory::createBackgroundRecord(double startTime, const String& threadName, const String& type, PassRefPtr<JSONObject> data)
+PassRefPtr<TimelineEvent> TimelineRecordFactory::createBackgroundRecord(double startTime, const String& threadName, const String& type, PassRefPtr<JSONObject> data)
 {
-    RefPtr<JSONObject> record = JSONObject::create();
-    record->setNumber("startTime", startTime);
-    record->setString("thread", threadName);
-    record->setString("type", type);
-    record->setObject("data", data ? data : JSONObject::create());
+    ASSERT(data.get());
+    RefPtr<TimelineEvent> record = TimelineEvent::create()
+        .setType(type)
+        .setData(data)
+        .setStartTime(startTime);
+    record->setThread(threadName);
     return record.release();
 }
 
@@ -221,12 +225,10 @@
     return data.release();
 }
 
-PassRefPtr<JSONObject> TimelineRecordFactory::createGPUTaskData(bool foreign, size_t usedGPUMemoryBytes)
+PassRefPtr<JSONObject> TimelineRecordFactory::createGPUTaskData(bool foreign)
 {
     RefPtr<JSONObject> data = JSONObject::create();
     data->setBoolean("foreign", foreign);
-    if (!foreign)
-        data->setNumber("usedGPUMemoryBytes", usedGPUMemoryBytes);
     return data.release();
 }
 
@@ -247,8 +249,7 @@
 PassRefPtr<JSONObject> TimelineRecordFactory::createNodeData(long long nodeId)
 {
     RefPtr<JSONObject> data = JSONObject::create();
-    if (nodeId)
-        data->setNumber("rootNode", nodeId);
+    setNodeData(data.get(), nodeId);
     return data.release();
 }
 
@@ -257,12 +258,22 @@
     return createNodeData(rootNodeId);
 }
 
-PassRefPtr<JSONObject> TimelineRecordFactory::createPaintData(const FloatQuad& quad, long long layerRootNodeId, int graphicsLayerId)
+void TimelineRecordFactory::setNodeData(JSONObject* data, long long nodeId)
 {
-    RefPtr<JSONObject> data = TimelineRecordFactory::createLayerData(layerRootNodeId);
+    if (nodeId)
+        data->setNumber("rootNode", nodeId);
+}
+
+void TimelineRecordFactory::setLayerData(JSONObject* data, long long rootNodeId)
+{
+    setNodeData(data, rootNodeId);
+}
+
+void TimelineRecordFactory::setPaintData(JSONObject* data, const FloatQuad& quad, long long layerRootNodeId, int graphicsLayerId)
+{
+    setLayerData(data, layerRootNodeId);
     data->setArray("clip", createQuad(quad));
     data->setNumber("layerId", graphicsLayerId);
-    return data.release();
 }
 
 PassRefPtr<JSONObject> TimelineRecordFactory::createFrameData(int frameId)
@@ -272,19 +283,19 @@
     return data.release();
 }
 
-void TimelineRecordFactory::appendLayoutRoot(JSONObject* data, const FloatQuad& quad, long long rootNodeId)
+void TimelineRecordFactory::setLayoutRoot(JSONObject* data, const FloatQuad& quad, long long rootNodeId)
 {
     data->setArray("root", createQuad(quad));
     if (rootNodeId)
         data->setNumber("rootNode", rootNodeId);
 }
 
-void TimelineRecordFactory::appendStyleRecalcDetails(JSONObject* data, unsigned elementCount)
+void TimelineRecordFactory::setStyleRecalcDetails(JSONObject* data, unsigned elementCount)
 {
     data->setNumber("elementCount", elementCount);
 }
 
-void TimelineRecordFactory::appendImageDetails(JSONObject* data, long long imageElementId, const String& url)
+void TimelineRecordFactory::setImageDetails(JSONObject* data, long long imageElementId, const String& url)
 {
     if (imageElementId)
         data->setNumber("elementId", imageElementId);
diff --git a/Source/core/inspector/TimelineRecordFactory.h b/Source/core/inspector/TimelineRecordFactory.h
index 67ac43f..8f53206 100644
--- a/Source/core/inspector/TimelineRecordFactory.h
+++ b/Source/core/inspector/TimelineRecordFactory.h
@@ -31,6 +31,7 @@
 #ifndef TimelineRecordFactory_h
 #define TimelineRecordFactory_h
 
+#include "InspectorTypeBuilder.h"
 #include "platform/JSONValues.h"
 #include "platform/weborigin/KURL.h"
 #include "wtf/Forward.h"
@@ -38,93 +39,69 @@
 
 namespace WebCore {
 
-    class Event;
-    class FloatQuad;
-    class InspectorFrontend;
-    class IntRect;
-    class ResourceRequest;
-    class ResourceResponse;
+class Event;
+class FloatQuad;
+class InspectorFrontend;
+class IntRect;
+class ResourceRequest;
+class ResourceResponse;
 
-    class TimelineRecordFactory {
-    public:
-        static PassRefPtr<JSONObject> createGenericRecord(double startTime, int maxCallStackDepth, const String& type);
-        static PassRefPtr<JSONObject> createBackgroundRecord(double startTime, const String& thread, const String& type, PassRefPtr<JSONObject> data = 0);
+class TimelineRecordFactory {
+public:
+    static PassRefPtr<TypeBuilder::Timeline::TimelineEvent> createGenericRecord(double startTime, int maxCallStackDepth, const String& type, PassRefPtr<JSONObject> data);
+    static PassRefPtr<TypeBuilder::Timeline::TimelineEvent> createBackgroundRecord(double startTime, const String& thread, const String& type, PassRefPtr<JSONObject> data);
 
-        static PassRefPtr<JSONObject> createGCEventData(size_t usedHeapSizeDelta);
+    static PassRefPtr<JSONObject> createGCEventData(size_t usedHeapSizeDelta);
+    static PassRefPtr<JSONObject> createFunctionCallData(const String& scriptName, int scriptLine);
+    static PassRefPtr<JSONObject> createEventDispatchData(const Event&);
+    static PassRefPtr<JSONObject> createGenericTimerData(int timerId);
+    static PassRefPtr<JSONObject> createTimerInstallData(int timerId, int timeout, bool singleShot);
+    static PassRefPtr<JSONObject> createXHRReadyStateChangeData(const String& url, int readyState);
+    static PassRefPtr<JSONObject> createXHRLoadData(const String& url);
+    static PassRefPtr<JSONObject> createEvaluateScriptData(const String&, double lineNumber);
+    static PassRefPtr<JSONObject> createTimeStampData(const String&);
+    static PassRefPtr<JSONObject> createResourceSendRequestData(const String& requestId, const ResourceRequest&);
+    static PassRefPtr<JSONObject> createScheduleResourceRequestData(const String&);
+    static PassRefPtr<JSONObject> createResourceReceiveResponseData(const String& requestId, const ResourceResponse&);
+    static PassRefPtr<JSONObject> createReceiveResourceData(const String& requestId, int length);
+    static PassRefPtr<JSONObject> createResourceFinishData(const String& requestId, bool didFail, double finishTime);
+    static PassRefPtr<JSONObject> createLayoutData(unsigned dirtyObjects, unsigned totalObjects, bool partialLayout);
+    static PassRefPtr<JSONObject> createDecodeImageData(const String& imageType);
+    static PassRefPtr<JSONObject> createResizeImageData(bool shouldCache);
+    static PassRefPtr<JSONObject> createMarkData(bool isMainFrame);
+    static PassRefPtr<JSONObject> createParseHTMLData(unsigned startLine);
+    static PassRefPtr<JSONObject> createAnimationFrameData(int callbackId);
+    static PassRefPtr<JSONObject> createNodeData(long long nodeId);
+    static PassRefPtr<JSONObject> createLayerData(long long layerRootNodeId);
+    static PassRefPtr<JSONObject> createFrameData(int frameId);
+    static PassRefPtr<JSONObject> createGPUTaskData(bool foreign);
 
-        static PassRefPtr<JSONObject> createFunctionCallData(const String& scriptName, int scriptLine);
+    static void setNodeData(JSONObject* data, long long nodeId);
+    static void setLayerData(JSONObject* data, long long layerRootNodeId);
+    static void setPaintData(JSONObject* data, const FloatQuad&, long long layerRootNodeId, int graphicsLayerId);
+    static void setLayoutRoot(JSONObject* data, const FloatQuad&, long long rootNodeId);
+    static void setStyleRecalcDetails(JSONObject* data, unsigned elementCount);
+    static void setImageDetails(JSONObject* data, long long imageElementId, const String& url);
 
-        static PassRefPtr<JSONObject> createEventDispatchData(const Event&);
+    static inline PassRefPtr<JSONObject> createWebSocketCreateData(unsigned long identifier, const KURL& url, const String& protocol)
+    {
+        RefPtr<JSONObject> data = JSONObject::create();
+        data->setNumber("identifier", identifier);
+        data->setString("url", url.string());
+        if (!protocol.isNull())
+            data->setString("webSocketProtocol", protocol);
+        return data.release();
+    }
 
-        static PassRefPtr<JSONObject> createGenericTimerData(int timerId);
-
-        static PassRefPtr<JSONObject> createTimerInstallData(int timerId, int timeout, bool singleShot);
-
-        static PassRefPtr<JSONObject> createXHRReadyStateChangeData(const String& url, int readyState);
-
-        static PassRefPtr<JSONObject> createXHRLoadData(const String& url);
-
-        static PassRefPtr<JSONObject> createEvaluateScriptData(const String&, double lineNumber);
-
-        static PassRefPtr<JSONObject> createTimeStampData(const String&);
-
-        static PassRefPtr<JSONObject> createResourceSendRequestData(const String& requestId, const ResourceRequest&);
-
-        static PassRefPtr<JSONObject> createScheduleResourceRequestData(const String&);
-
-        static PassRefPtr<JSONObject> createResourceReceiveResponseData(const String& requestId, const ResourceResponse&);
-
-        static PassRefPtr<JSONObject> createReceiveResourceData(const String& requestId, int length);
-
-        static PassRefPtr<JSONObject> createResourceFinishData(const String& requestId, bool didFail, double finishTime);
-
-        static PassRefPtr<JSONObject> createLayoutData(unsigned dirtyObjects, unsigned totalObjects, bool partialLayout);
-
-        static PassRefPtr<JSONObject> createDecodeImageData(const String& imageType);
-
-        static PassRefPtr<JSONObject> createResizeImageData(bool shouldCache);
-
-        static PassRefPtr<JSONObject> createMarkData(bool isMainFrame);
-
-        static PassRefPtr<JSONObject> createParseHTMLData(unsigned startLine);
-
-        static PassRefPtr<JSONObject> createAnimationFrameData(int callbackId);
-
-        static PassRefPtr<JSONObject> createNodeData(long long nodeId);
-
-        static PassRefPtr<JSONObject> createLayerData(long long layerRootNodeId);
-
-        static PassRefPtr<JSONObject> createPaintData(const FloatQuad&, long long layerRootNodeId, int graphicsLayerId);
-
-        static PassRefPtr<JSONObject> createFrameData(int frameId);
-
-        static PassRefPtr<JSONObject> createGPUTaskData(bool foreign, size_t usedGPUMemoryBytes);
-
-        static void appendLayoutRoot(JSONObject* data, const FloatQuad&, long long rootNodeId);
-
-        static void appendStyleRecalcDetails(JSONObject* data, unsigned elementCount);
-
-        static void appendImageDetails(JSONObject* data, long long imageElementId, const String& url);
-
-        static inline PassRefPtr<JSONObject> createWebSocketCreateData(unsigned long identifier, const KURL& url, const String& protocol)
-        {
-            RefPtr<JSONObject> data = JSONObject::create();
-            data->setNumber("identifier", identifier);
-            data->setString("url", url.string());
-            if (!protocol.isNull())
-                data->setString("webSocketProtocol", protocol);
-            return data.release();
-        }
-
-        static inline PassRefPtr<JSONObject> createGenericWebSocketData(unsigned long identifier)
-        {
-            RefPtr<JSONObject> data = JSONObject::create();
-            data->setNumber("identifier", identifier);
-            return data.release();
-        }
-    private:
-        TimelineRecordFactory() { }
-    };
+    static inline PassRefPtr<JSONObject> createGenericWebSocketData(unsigned long identifier)
+    {
+        RefPtr<JSONObject> data = JSONObject::create();
+        data->setNumber("identifier", identifier);
+        return data.release();
+    }
+private:
+    TimelineRecordFactory() { }
+};
 
 } // namespace WebCore
 
diff --git a/Source/core/inspector/TraceEventDispatcher.cpp b/Source/core/inspector/TraceEventDispatcher.cpp
index bdfbea6..a75f4a4 100644
--- a/Source/core/inspector/TraceEventDispatcher.cpp
+++ b/Source/core/inspector/TraceEventDispatcher.cpp
@@ -106,8 +106,9 @@
         client->setTraceEventCallback(dispatchEventOnAnyThread);
     HandlersMap::iterator it = m_handlers.find(std::make_pair(name, phase));
     if (it == m_handlers.end())
-        it = m_handlers.add(std::make_pair(name, phase), Vector<BoundTraceEventHandler>()).iterator;
-    it->value.append(BoundTraceEventHandler(instance, method));
+        m_handlers.add(std::make_pair(name, phase), Vector<BoundTraceEventHandler>()).storedValue->value.append(BoundTraceEventHandler(instance, method));
+    else
+        it->value.append(BoundTraceEventHandler(instance, method));
 }
 
 void TraceEventDispatcher::removeAllListeners(TraceEventTargetBase* instance, InspectorClient* client)
diff --git a/Source/core/inspector/WorkerConsoleAgent.cpp b/Source/core/inspector/WorkerConsoleAgent.cpp
index f6b912a..754ddcf 100644
--- a/Source/core/inspector/WorkerConsoleAgent.cpp
+++ b/Source/core/inspector/WorkerConsoleAgent.cpp
@@ -34,8 +34,8 @@
 
 namespace WebCore {
 
-WorkerConsoleAgent::WorkerConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorTimelineAgent* timelineAgent, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
-    : InspectorConsoleAgent(instrumentingAgents, timelineAgent, state, injectedScriptManager)
+WorkerConsoleAgent::WorkerConsoleAgent(InspectorTimelineAgent* timelineAgent, InjectedScriptManager* injectedScriptManager)
+    : InspectorConsoleAgent(timelineAgent, injectedScriptManager)
 {
 }
 
diff --git a/Source/core/inspector/WorkerConsoleAgent.h b/Source/core/inspector/WorkerConsoleAgent.h
index e886da7..676a42a 100644
--- a/Source/core/inspector/WorkerConsoleAgent.h
+++ b/Source/core/inspector/WorkerConsoleAgent.h
@@ -36,20 +36,20 @@
 
 namespace WebCore {
 
-class WorkerConsoleAgent : public InspectorConsoleAgent {
+class WorkerConsoleAgent FINAL : public InspectorConsoleAgent {
     WTF_MAKE_NONCOPYABLE(WorkerConsoleAgent);
 public:
-    static PassOwnPtr<WorkerConsoleAgent> create(InstrumentingAgents* instrumentingAgents, InspectorTimelineAgent* timelineAgent, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
+    static PassOwnPtr<WorkerConsoleAgent> create(InspectorTimelineAgent* timelineAgent, InjectedScriptManager* injectedScriptManager)
     {
-        return adoptPtr(new WorkerConsoleAgent(instrumentingAgents, timelineAgent, state, injectedScriptManager));
+        return adoptPtr(new WorkerConsoleAgent(timelineAgent, injectedScriptManager));
     }
     virtual ~WorkerConsoleAgent();
 
     virtual bool isWorkerAgent() OVERRIDE { return true; }
 
 private:
-    WorkerConsoleAgent(InstrumentingAgents*, InspectorTimelineAgent*, InspectorCompositeState*, InjectedScriptManager*);
-    virtual void addInspectedNode(ErrorString*, int nodeId);
+    WorkerConsoleAgent(InspectorTimelineAgent*, InjectedScriptManager*);
+    virtual void addInspectedNode(ErrorString*, int nodeId) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/WorkerDebuggerAgent.cpp b/Source/core/inspector/WorkerDebuggerAgent.cpp
index 271c306..7eeec11 100644
--- a/Source/core/inspector/WorkerDebuggerAgent.cpp
+++ b/Source/core/inspector/WorkerDebuggerAgent.cpp
@@ -55,13 +55,13 @@
 }
 
 
-class RunInspectorCommandsTask : public ScriptDebugServer::Task {
+class RunInspectorCommandsTask FINAL : public ScriptDebugServer::Task {
 public:
     RunInspectorCommandsTask(WorkerThread* thread, WorkerGlobalScope* workerGlobalScope)
         : m_thread(thread)
         , m_workerGlobalScope(workerGlobalScope) { }
     virtual ~RunInspectorCommandsTask() { }
-    virtual void run()
+    virtual void run() OVERRIDE
     {
         // Process all queued debugger commands. It is safe to use m_workerGlobalScope here
         // because it is alive if RunWorkerLoop is not terminated, otherwise it will
@@ -78,13 +78,13 @@
 
 const char WorkerDebuggerAgent::debuggerTaskMode[] = "debugger";
 
-PassOwnPtr<WorkerDebuggerAgent> WorkerDebuggerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, WorkerScriptDebugServer* scriptDebugServer, WorkerGlobalScope* inspectedWorkerGlobalScope, InjectedScriptManager* injectedScriptManager)
+PassOwnPtr<WorkerDebuggerAgent> WorkerDebuggerAgent::create(WorkerScriptDebugServer* scriptDebugServer, WorkerGlobalScope* inspectedWorkerGlobalScope, InjectedScriptManager* injectedScriptManager)
 {
-    return adoptPtr(new WorkerDebuggerAgent(instrumentingAgents, inspectorState, scriptDebugServer, inspectedWorkerGlobalScope, injectedScriptManager));
+    return adoptPtr(new WorkerDebuggerAgent(scriptDebugServer, inspectedWorkerGlobalScope, injectedScriptManager));
 }
 
-WorkerDebuggerAgent::WorkerDebuggerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, WorkerScriptDebugServer* scriptDebugServer, WorkerGlobalScope* inspectedWorkerGlobalScope, InjectedScriptManager* injectedScriptManager)
-    : InspectorDebuggerAgent(instrumentingAgents, inspectorState, injectedScriptManager)
+WorkerDebuggerAgent::WorkerDebuggerAgent(WorkerScriptDebugServer* scriptDebugServer, WorkerGlobalScope* inspectedWorkerGlobalScope, InjectedScriptManager* injectedScriptManager)
+    : InspectorDebuggerAgent(injectedScriptManager)
     , m_scriptDebugServer(scriptDebugServer)
     , m_inspectedWorkerGlobalScope(inspectedWorkerGlobalScope)
 {
diff --git a/Source/core/inspector/WorkerDebuggerAgent.h b/Source/core/inspector/WorkerDebuggerAgent.h
index dee9dbf..e0ea4a7 100644
--- a/Source/core/inspector/WorkerDebuggerAgent.h
+++ b/Source/core/inspector/WorkerDebuggerAgent.h
@@ -39,25 +39,25 @@
 class WorkerGlobalScope;
 class WorkerThread;
 
-class WorkerDebuggerAgent : public InspectorDebuggerAgent {
+class WorkerDebuggerAgent FINAL : public InspectorDebuggerAgent {
     WTF_MAKE_NONCOPYABLE(WorkerDebuggerAgent);
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<WorkerDebuggerAgent> create(InstrumentingAgents*, InspectorCompositeState*, WorkerScriptDebugServer*, WorkerGlobalScope*, InjectedScriptManager*);
+    static PassOwnPtr<WorkerDebuggerAgent> create(WorkerScriptDebugServer*, WorkerGlobalScope*, InjectedScriptManager*);
     virtual ~WorkerDebuggerAgent();
 
     static const char debuggerTaskMode[];
     static void interruptAndDispatchInspectorCommands(WorkerThread*);
 
 private:
-    WorkerDebuggerAgent(InstrumentingAgents*, InspectorCompositeState*, WorkerScriptDebugServer*, WorkerGlobalScope*, InjectedScriptManager*);
+    WorkerDebuggerAgent(WorkerScriptDebugServer*, WorkerGlobalScope*, InjectedScriptManager*);
 
-    virtual void startListeningScriptDebugServer();
-    virtual void stopListeningScriptDebugServer();
-    virtual WorkerScriptDebugServer& scriptDebugServer();
-    virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId);
-    virtual void muteConsole();
-    virtual void unmuteConsole();
+    virtual void startListeningScriptDebugServer() OVERRIDE;
+    virtual void stopListeningScriptDebugServer() OVERRIDE;
+    virtual WorkerScriptDebugServer& scriptDebugServer() OVERRIDE;
+    virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId) OVERRIDE;
+    virtual void muteConsole() OVERRIDE;
+    virtual void unmuteConsole() OVERRIDE;
 
     WorkerScriptDebugServer* m_scriptDebugServer;
     WorkerGlobalScope* m_inspectedWorkerGlobalScope;
diff --git a/Source/core/inspector/WorkerInspectorController.cpp b/Source/core/inspector/WorkerInspectorController.cpp
index a33fb16..b569802 100644
--- a/Source/core/inspector/WorkerInspectorController.cpp
+++ b/Source/core/inspector/WorkerInspectorController.cpp
@@ -56,13 +56,13 @@
 
 namespace {
 
-class PageInspectorProxy : public InspectorFrontendChannel {
+class PageInspectorProxy FINAL : public InspectorFrontendChannel {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit PageInspectorProxy(WorkerGlobalScope* workerGlobalScope) : m_workerGlobalScope(workerGlobalScope) { }
     virtual ~PageInspectorProxy() { }
 private:
-    virtual bool sendMessageToFrontend(const String& message)
+    virtual bool sendMessageToFrontend(const String& message) OVERRIDE
     {
         m_workerGlobalScope->thread()->workerReportingProxy().postMessageToPageInspector(message);
         return true;
@@ -70,14 +70,14 @@
     WorkerGlobalScope* m_workerGlobalScope;
 };
 
-class WorkerStateClient : public InspectorStateClient {
+class WorkerStateClient FINAL : public InspectorStateClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     WorkerStateClient(WorkerGlobalScope* context) : m_workerGlobalScope(context) { }
     virtual ~WorkerStateClient() { }
 
 private:
-    virtual void updateInspectorStateCookie(const String& cookie)
+    virtual void updateInspectorStateCookie(const String& cookie) OVERRIDE
     {
         m_workerGlobalScope->thread()->workerReportingProxy().updateInspectorStateCookie(cookie);
     }
@@ -94,17 +94,17 @@
     , m_instrumentingAgents(InstrumentingAgents::create())
     , m_injectedScriptManager(InjectedScriptManager::createForWorker())
     , m_debugServer(adoptPtr(new WorkerScriptDebugServer(workerGlobalScope, WorkerDebuggerAgent::debuggerTaskMode)))
+    , m_agents(m_instrumentingAgents.get(), m_state.get())
 {
-    m_agents.append(WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), m_debugServer.get(), workerGlobalScope));
+    m_agents.append(WorkerRuntimeAgent::create(m_injectedScriptManager.get(), m_debugServer.get(), workerGlobalScope));
 
-    OwnPtr<InspectorTimelineAgent> timelineAgent = InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, 0, 0, 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0);
-    OwnPtr<InspectorConsoleAgent> consoleAgent = WorkerConsoleAgent::create(m_instrumentingAgents.get(), timelineAgent.get(), m_state.get(), m_injectedScriptManager.get());
-    m_agents.append(WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_debugServer.get(), workerGlobalScope, m_injectedScriptManager.get()));
+    OwnPtr<InspectorTimelineAgent> timelineAgent = InspectorTimelineAgent::create(0, 0, 0, InspectorTimelineAgent::WorkerInspector, 0);
+    m_agents.append(WorkerDebuggerAgent::create(m_debugServer.get(), workerGlobalScope, m_injectedScriptManager.get()));
 
-    m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent.get(), m_state.get(), m_injectedScriptManager.get(), 0));
-    m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()));
+    m_agents.append(InspectorProfilerAgent::create(m_injectedScriptManager.get(), 0));
+    m_agents.append(InspectorHeapProfilerAgent::create(m_injectedScriptManager.get()));
+    m_agents.append(WorkerConsoleAgent::create(timelineAgent.get(), m_injectedScriptManager.get()));
     m_agents.append(timelineAgent.release());
-    m_agents.append(consoleAgent.release());
 
     m_injectedScriptManager->injectedScriptHost()->init(m_instrumentingAgents.get(), m_debugServer.get());
 }
diff --git a/Source/core/inspector/WorkerRuntimeAgent.cpp b/Source/core/inspector/WorkerRuntimeAgent.cpp
index d3d0c3f..52ec387 100644
--- a/Source/core/inspector/WorkerRuntimeAgent.cpp
+++ b/Source/core/inspector/WorkerRuntimeAgent.cpp
@@ -42,12 +42,11 @@
 
 namespace WebCore {
 
-WorkerRuntimeAgent::WorkerRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, WorkerGlobalScope* workerGlobalScope)
-    : InspectorRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer)
+WorkerRuntimeAgent::WorkerRuntimeAgent(InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, WorkerGlobalScope* workerGlobalScope)
+    : InspectorRuntimeAgent(injectedScriptManager, scriptDebugServer)
     , m_workerGlobalScope(workerGlobalScope)
     , m_paused(false)
 {
-    m_instrumentingAgents->setWorkerRuntimeAgent(this);
 }
 
 WorkerRuntimeAgent::~WorkerRuntimeAgent()
@@ -55,6 +54,11 @@
     m_instrumentingAgents->setWorkerRuntimeAgent(0);
 }
 
+void WorkerRuntimeAgent::init()
+{
+    m_instrumentingAgents->setWorkerRuntimeAgent(this);
+}
+
 InjectedScript WorkerRuntimeAgent::injectedScriptForEval(ErrorString* error, const int* executionContextId)
 {
     if (executionContextId) {
diff --git a/Source/core/inspector/WorkerRuntimeAgent.h b/Source/core/inspector/WorkerRuntimeAgent.h
index 745baf2..65dba70 100644
--- a/Source/core/inspector/WorkerRuntimeAgent.h
+++ b/Source/core/inspector/WorkerRuntimeAgent.h
@@ -38,24 +38,26 @@
 
 class WorkerGlobalScope;
 
-class WorkerRuntimeAgent : public InspectorRuntimeAgent {
+class WorkerRuntimeAgent FINAL : public InspectorRuntimeAgent {
 public:
-    static PassOwnPtr<WorkerRuntimeAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, WorkerGlobalScope* context)
+    static PassOwnPtr<WorkerRuntimeAgent> create(InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, WorkerGlobalScope* context)
     {
-        return adoptPtr(new WorkerRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer, context));
+        return adoptPtr(new WorkerRuntimeAgent(injectedScriptManager, scriptDebugServer, context));
     }
     virtual ~WorkerRuntimeAgent();
 
+    virtual void init() OVERRIDE;
+
     // Protocol commands.
-    virtual void run(ErrorString*);
+    virtual void run(ErrorString*) OVERRIDE;
 
     void willEvaluateWorkerScript(WorkerGlobalScope*, int workerThreadStartMode);
 
 private:
-    WorkerRuntimeAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, ScriptDebugServer*, WorkerGlobalScope*);
-    virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId);
-    virtual void muteConsole();
-    virtual void unmuteConsole();
+    WorkerRuntimeAgent(InjectedScriptManager*, ScriptDebugServer*, WorkerGlobalScope*);
+    virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId) OVERRIDE;
+    virtual void muteConsole() OVERRIDE;
+    virtual void unmuteConsole() OVERRIDE;
     WorkerGlobalScope* m_workerGlobalScope;
     bool m_paused;
 };
diff --git a/Source/core/inspector/combine-javascript-resources.pl b/Source/core/inspector/combine-javascript-resources.pl
deleted file mode 100755
index 428b6b7..0000000
--- a/Source/core/inspector/combine-javascript-resources.pl
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/perl -w
-
-# Copyright (C) 2008 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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.
-
-# Script to combine multiple JavaScript files into one file, based on
-# the script tags in the head of an input HTML file.
-
-use strict;
-use Getopt::Long;
-use File::Basename;
-use File::Path;
-
-my $generatedScriptsDirectory;
-my $outputDirectory;
-my $scriptName;
-my $htmlFile;
-
-GetOptions('output-dir=s' => \$outputDirectory,
-           'output-script-name=s' => \$scriptName,
-           'generated-scripts-dir=s' => \$generatedScriptsDirectory,
-           'input-html=s' => \$htmlFile);
-
-unless (defined $htmlFile and defined $scriptName and defined $outputDirectory) {
-    print "Usage: $0 --input-html <path> --output-dir path --output-script-name <name>\n";
-    exit;
-}
-
-my $htmlDirectory = dirname($htmlFile);
-my $htmlContents;
-
-{
-    local $/;
-    open HTML, $htmlFile or die;
-    $htmlContents = <HTML>;
-    close HTML;
-}
-
-$htmlContents =~ m/<head>(.*)<\/head>/si;
-my $headContents = $1;
-
-mkpath $outputDirectory;
-open SCRIPT_OUT, ">", "$outputDirectory/$scriptName" or die "Can't open $outputDirectory/$scriptName: $!";
-
-while ($headContents =~ m/<script.*src="([^"]*)"[^>]*>/gi) {
-    local $/;
-    open SCRIPT_IN, "$generatedScriptsDirectory/$1" or open SCRIPT_IN, "$htmlDirectory/$1" or die "Can't open $htmlDirectory/$1: $!";
-    print SCRIPT_OUT "/* $1 */\n\n";
-    print SCRIPT_OUT <SCRIPT_IN>;
-    close SCRIPT_IN;
-}
-
-close SCRIPT_OUT;
-
-$headContents =~ s/<script.*src="[^"]*"[^>]*><\/script>\s*//gi;
-$headContents .= "<script type=\"text/javascript\" src=\"$scriptName\"></script>\n";
-$htmlContents =~ s/<head>.*<\/head>/<head>$headContents<\/head>/si;
-
-open HTML, ">", "$outputDirectory/" . basename($htmlFile) or die "Can't open $outputDirectory/" . basename($htmlFile) . ": $!";
-print HTML $htmlContents;
-close HTML;
diff --git a/Source/core/inspector_instrumentation_sources.target.darwin-arm.mk b/Source/core/inspector_instrumentation_sources.target.darwin-arm.mk
index 4930cde..f826e07 100644
--- a/Source/core/inspector_instrumentation_sources.target.darwin-arm.mk
+++ b/Source/core/inspector_instrumentation_sources.target.darwin-arm.mk
@@ -23,7 +23,6 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python inspector/CodeGeneratorInstrumentation.py inspector/InspectorInstrumentation.idl --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
-$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
@@ -33,7 +32,6 @@
 GYP_GENERATED_OUTPUTS := \
 	$(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h \
-	$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h \
diff --git a/Source/core/inspector_instrumentation_sources.target.darwin-mips.mk b/Source/core/inspector_instrumentation_sources.target.darwin-mips.mk
index 4930cde..f826e07 100644
--- a/Source/core/inspector_instrumentation_sources.target.darwin-mips.mk
+++ b/Source/core/inspector_instrumentation_sources.target.darwin-mips.mk
@@ -23,7 +23,6 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python inspector/CodeGeneratorInstrumentation.py inspector/InspectorInstrumentation.idl --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
-$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
@@ -33,7 +32,6 @@
 GYP_GENERATED_OUTPUTS := \
 	$(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h \
-	$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h \
diff --git a/Source/core/inspector_instrumentation_sources.target.darwin-x86.mk b/Source/core/inspector_instrumentation_sources.target.darwin-x86.mk
index 4930cde..f826e07 100644
--- a/Source/core/inspector_instrumentation_sources.target.darwin-x86.mk
+++ b/Source/core/inspector_instrumentation_sources.target.darwin-x86.mk
@@ -23,7 +23,6 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python inspector/CodeGeneratorInstrumentation.py inspector/InspectorInstrumentation.idl --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
-$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
@@ -33,7 +32,6 @@
 GYP_GENERATED_OUTPUTS := \
 	$(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h \
-	$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h \
diff --git a/Source/core/inspector_instrumentation_sources.target.linux-arm.mk b/Source/core/inspector_instrumentation_sources.target.linux-arm.mk
index 4930cde..f826e07 100644
--- a/Source/core/inspector_instrumentation_sources.target.linux-arm.mk
+++ b/Source/core/inspector_instrumentation_sources.target.linux-arm.mk
@@ -23,7 +23,6 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python inspector/CodeGeneratorInstrumentation.py inspector/InspectorInstrumentation.idl --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
-$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
@@ -33,7 +32,6 @@
 GYP_GENERATED_OUTPUTS := \
 	$(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h \
-	$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h \
diff --git a/Source/core/inspector_instrumentation_sources.target.linux-mips.mk b/Source/core/inspector_instrumentation_sources.target.linux-mips.mk
index 4930cde..f826e07 100644
--- a/Source/core/inspector_instrumentation_sources.target.linux-mips.mk
+++ b/Source/core/inspector_instrumentation_sources.target.linux-mips.mk
@@ -23,7 +23,6 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python inspector/CodeGeneratorInstrumentation.py inspector/InspectorInstrumentation.idl --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
-$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
@@ -33,7 +32,6 @@
 GYP_GENERATED_OUTPUTS := \
 	$(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h \
-	$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h \
diff --git a/Source/core/inspector_instrumentation_sources.target.linux-x86.mk b/Source/core/inspector_instrumentation_sources.target.linux-x86.mk
index 4930cde..f826e07 100644
--- a/Source/core/inspector_instrumentation_sources.target.linux-x86.mk
+++ b/Source/core/inspector_instrumentation_sources.target.linux-x86.mk
@@ -23,7 +23,6 @@
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python inspector/CodeGeneratorInstrumentation.py inspector/InspectorInstrumentation.idl --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
-$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
 $(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h: $(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h ;
@@ -33,7 +32,6 @@
 GYP_GENERATED_OUTPUTS := \
 	$(gyp_shared_intermediate_dir)/blink/InspectorCanvasInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorConsoleInstrumentationInl.h \
-	$(gyp_shared_intermediate_dir)/blink/InspectorDatabaseInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InspectorOverridesInl.h \
 	$(gyp_shared_intermediate_dir)/blink/InstrumentingAgentsInl.h \
diff --git a/Source/core/loader/CrossOriginPreflightResultCache.cpp b/Source/core/loader/CrossOriginPreflightResultCache.cpp
index 460e2e9..babd969 100644
--- a/Source/core/loader/CrossOriginPreflightResultCache.cpp
+++ b/Source/core/loader/CrossOriginPreflightResultCache.cpp
@@ -35,8 +35,6 @@
 
 namespace WebCore {
 
-using namespace std;
-
 // These values are at the discretion of the user agent.
 static const unsigned defaultPreflightCacheTimeoutSeconds = 5;
 static const unsigned maxPreflightCacheTimeoutSeconds = 600; // Should be short enough to minimize the risk of using a poisoned cache after switching to a secure network.
@@ -157,13 +155,13 @@
 void CrossOriginPreflightResultCache::appendEntry(const String& origin, const KURL& url, PassOwnPtr<CrossOriginPreflightResultCacheItem> preflightResult)
 {
     ASSERT(isMainThread());
-    m_preflightHashMap.set(make_pair(origin, url), preflightResult);
+    m_preflightHashMap.set(std::make_pair(origin, url), preflightResult);
 }
 
 bool CrossOriginPreflightResultCache::canSkipPreflight(const String& origin, const KURL& url, StoredCredentials includeCredentials, const String& method, const HTTPHeaderMap& requestHeaders)
 {
     ASSERT(isMainThread());
-    CrossOriginPreflightResultHashMap::iterator cacheIt = m_preflightHashMap.find(make_pair(origin, url));
+    CrossOriginPreflightResultHashMap::iterator cacheIt = m_preflightHashMap.find(std::make_pair(origin, url));
     if (cacheIt == m_preflightHashMap.end())
         return false;
 
diff --git a/Source/core/loader/DocumentLoader.cpp b/Source/core/loader/DocumentLoader.cpp
index 07ad2cb..ef8bf14 100644
--- a/Source/core/loader/DocumentLoader.cpp
+++ b/Source/core/loader/DocumentLoader.cpp
@@ -34,12 +34,11 @@
 #include "core/dom/Document.h"
 #include "core/dom/DocumentParser.h"
 #include "core/events/Event.h"
-#include "core/fetch/FetchContext.h"
 #include "core/fetch/MemoryCache.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/ResourceLoader.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/html/HTMLFrameOwnerElement.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
@@ -50,7 +49,7 @@
 #include "core/frame/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/Logging.h"
 #include "platform/UserGestureIndicator.h"
 #include "platform/mhtml/ArchiveResourceCollection.h"
@@ -70,21 +69,17 @@
     return mimeType == "multipart/related";
 }
 
-DocumentLoader::DocumentLoader(const ResourceRequest& req, const SubstituteData& substituteData)
-    : m_deferMainResourceDataLoad(true)
-    , m_frame(0)
+DocumentLoader::DocumentLoader(Frame* frame, const ResourceRequest& req, const SubstituteData& substituteData)
+    : m_frame(frame)
     , m_fetcher(ResourceFetcher::create(this))
     , m_originalRequest(req)
     , m_substituteData(substituteData)
-    , m_originalRequestCopy(req)
     , m_request(req)
     , m_committed(false)
     , m_isClientRedirect(false)
     , m_replacesCurrentHistoryItem(false)
     , m_loadingMainResource(false)
     , m_timeOfLastDataReceived(0.0)
-    , m_identifierForLoadWithoutResourceLoader(0)
-    , m_dataLoadTimer(this, &DocumentLoader::handleSubstituteDataLoadNow)
     , m_applicationCacheHost(adoptPtr(new ApplicationCacheHost(this)))
 {
 }
@@ -103,24 +98,14 @@
 
 DocumentLoader::~DocumentLoader()
 {
-    ASSERT(!m_frame || frameLoader()->activeDocumentLoader() != this || !isLoading());
+    ASSERT(!m_frame || !isLoading());
     m_fetcher->clearDocumentLoader();
     clearMainResourceHandle();
 }
 
-PassRefPtr<SharedBuffer> DocumentLoader::mainResourceData() const
-{
-    ASSERT(isArchiveMIMEType(m_response.mimeType()));
-    if (m_substituteData.isValid())
-        return m_substituteData.content()->copy();
-    if (m_mainResource)
-        return m_mainResource->resourceBuffer();
-    return 0;
-}
-
 unsigned long DocumentLoader::mainResourceIdentifier() const
 {
-    return m_mainResource ? m_mainResource->identifier() : m_identifierForLoadWithoutResourceLoader;
+    return m_mainResource ? m_mainResource->identifier() : 0;
 }
 
 Document* DocumentLoader::document() const
@@ -135,30 +120,20 @@
     return m_originalRequest;
 }
 
-const ResourceRequest& DocumentLoader::originalRequestCopy() const
-{
-    return m_originalRequestCopy;
-}
-
 const ResourceRequest& DocumentLoader::request() const
 {
     return m_request;
 }
 
-ResourceRequest& DocumentLoader::request()
-{
-    return m_request;
-}
-
 const KURL& DocumentLoader::url() const
 {
-    return request().url();
+    return m_request.url();
 }
 
 void DocumentLoader::updateForSameDocumentNavigation(const KURL& newURL)
 {
     KURL oldURL = m_request.url();
-    m_originalRequestCopy.setURL(newURL);
+    m_originalRequest.setURL(newURL);
     m_request.setURL(newURL);
     clearRedirectChain();
     if (m_isClientRedirect)
@@ -171,25 +146,6 @@
     return !originalRequest().url().isEmpty() || !unreachableURL().isEmpty();
 }
 
-void DocumentLoader::setRequest(const ResourceRequest& req)
-{
-    // Replacing an unreachable URL with alternate content looks like a server-side
-    // redirect at this point, but we can replace a committed dataSource.
-    bool handlingUnreachableURL = false;
-
-    handlingUnreachableURL = m_substituteData.isValid() && !m_substituteData.failingURL().isEmpty();
-
-    if (handlingUnreachableURL)
-        m_committed = false;
-
-    // We should never be getting a redirect callback after the data
-    // source is committed, except in the unreachable URL case. It
-    // would be a WebFoundation bug if it sent a redirect callback after commit.
-    ASSERT(!m_committed);
-
-    m_request = req;
-}
-
 void DocumentLoader::setMainDocumentError(const ResourceError& error)
 {
     m_mainDocumentError = error;
@@ -198,7 +154,7 @@
 void DocumentLoader::mainReceivedError(const ResourceError& error)
 {
     ASSERT(!error.isNull());
-    ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading());
+    ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame));
     m_applicationCacheHost->failedLoadingMainResource();
     if (!frameLoader())
         return;
@@ -236,7 +192,7 @@
     if (!loading)
         return;
 
-    if (isLoadingMainResource()) {
+    if (m_loadingMainResource) {
         // Stop the main resource loader and let it send the cancelled message.
         cancelMainResourceLoad(ResourceError::cancelledError(m_request.url()));
     } else if (m_fetcher->isFetching()) {
@@ -265,7 +221,7 @@
     if (document() && document()->hasActiveParser())
         return true;
 
-    return isLoadingMainResource() || m_fetcher->isFetching();
+    return m_loadingMainResource || m_fetcher->isFetching();
 }
 
 void DocumentLoader::notifyFinished(Resource* resource)
@@ -285,15 +241,10 @@
 
 void DocumentLoader::finishedLoading(double finishTime)
 {
-    ASSERT(!m_frame->page()->defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame));
+    ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame));
 
     RefPtr<DocumentLoader> protect(this);
 
-    if (m_identifierForLoadWithoutResourceLoader) {
-        m_frame->fetchContext().dispatchDidFinishLoading(this, m_identifierForLoadWithoutResourceLoader, finishTime);
-        m_identifierForLoadWithoutResourceLoader = 0;
-    }
-
     double responseEndTime = finishTime;
     if (!responseEndTime)
         responseEndTime = m_timeOfLastDataReceived;
@@ -305,9 +256,7 @@
     if (!frameLoader())
         return;
 
-    if (isArchiveMIMEType(m_response.mimeType())) {
-        createArchive();
-    } else {
+    if (!maybeCreateArchive()) {
         // If this is an empty document, it will not have actually been created yet. Commit dummy data so that
         // DocumentWriter::begin() gets called and creates the Document.
         if (!m_writer)
@@ -342,48 +291,25 @@
     return false;
 }
 
-void DocumentLoader::handleSubstituteDataLoadNow(DocumentLoaderTimer*)
-{
-    RefPtr<DocumentLoader> protect(this);
-    ResourceResponse response(m_request.url(), m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), emptyString());
-    responseReceived(0, response);
-    if (m_substituteData.content()->size())
-        dataReceived(0, m_substituteData.content()->data(), m_substituteData.content()->size());
-    if (isLoadingMainResource())
-        finishedLoading(0);
-}
-
-void DocumentLoader::startDataLoadTimer()
-{
-    m_dataLoadTimer.startOneShot(0);
-}
-
-void DocumentLoader::handleSubstituteDataLoadSoon()
-{
-    if (m_deferMainResourceDataLoad)
-        startDataLoadTimer();
-    else
-        handleSubstituteDataLoadNow(0);
-}
-
-bool DocumentLoader::shouldContinueForNavigationPolicy(const ResourceRequest& request, PolicyCheckLoadType policyCheckLoadType)
+bool DocumentLoader::shouldContinueForNavigationPolicy(const ResourceRequest& request)
 {
     // Don't ask if we are loading an empty URL.
-    if (request.url().isEmpty())
-        return true;
-
-    // We are always willing to show alternate content for unreachable URLs.
-    if (m_substituteData.isValid() && !m_substituteData.failingURL().isEmpty())
+    if (request.url().isEmpty() || m_substituteData.isValid())
         return true;
 
     // If we're loading content into a subframe, check against the parent's Content Security Policy
     // and kill the load if that check fails.
-    if (m_frame->ownerElement() && !m_frame->ownerElement()->document().contentSecurityPolicy()->allowChildFrameFromSource(request.url()))
+    if (m_frame->ownerElement() && !m_frame->ownerElement()->document().contentSecurityPolicy()->allowChildFrameFromSource(request.url())) {
+        // Fire a load event, as timing attacks would otherwise reveal that the
+        // frame was blocked. This way, it looks like every other cross-origin
+        // page load.
+        m_frame->document()->enforceSandboxFlags(SandboxOrigin);
+        m_frame->ownerElement()->dispatchEvent(Event::create(EventTypeNames::load));
         return false;
+    }
 
     NavigationPolicy policy = m_triggeringAction.policy();
-    if (policyCheckLoadType != PolicyCheckFragment)
-        policy = frameLoader()->client()->decidePolicyForNavigation(request, this, policy);
+    policy = frameLoader()->client()->decidePolicyForNavigation(request, this, policy);
     if (policy == NavigationPolicyCurrentTab)
         return true;
     if (policy == NavigationPolicyIgnore)
@@ -400,6 +326,12 @@
     willSendRequest(request, redirectResponse);
 }
 
+void DocumentLoader::updateRequest(Resource* resource, const ResourceRequest& request)
+{
+    ASSERT_UNUSED(resource, resource == m_mainResource);
+    m_request = request;
+}
+
 static bool isFormSubmission(NavigationType type)
 {
     return type == NavigationTypeFormSubmitted || type == NavigationTypeFormResubmitted;
@@ -441,22 +373,23 @@
     if (newRequest.cachePolicy() == UseProtocolCachePolicy && isRedirectAfterPost(newRequest, redirectResponse))
         newRequest.setCachePolicy(ReloadIgnoringCacheData);
 
-    Frame* parent = m_frame->tree().parent();
-    if (parent) {
-        if (!parent->loader().mixedContentChecker()->canRunInsecureContent(parent->document()->securityOrigin(), newRequest.url())) {
+    // If this is a sub-frame, check for mixed content blocking against the top frame.
+    if (m_frame->tree().parent()) {
+        Frame* top = m_frame->tree().top();
+        if (!top->loader().mixedContentChecker()->canRunInsecureContent(top->document()->securityOrigin(), newRequest.url())) {
             cancelMainResourceLoad(ResourceError::cancelledError(newRequest.url()));
             return;
         }
     }
 
-    setRequest(newRequest);
+    m_request = newRequest;
 
     if (redirectResponse.isNull())
         return;
 
     appendRedirect(newRequest.url());
     frameLoader()->client()->dispatchDidReceiveServerRedirectForProvisionalLoad();
-    if (!shouldContinueForNavigationPolicy(newRequest, PolicyCheckStandard))
+    if (!shouldContinueForNavigationPolicy(newRequest))
         cancelMainResourceLoad(ResourceError::cancelledError(m_request.url()));
 }
 
@@ -538,9 +471,6 @@
     if (isArchiveMIMEType(m_response.mimeType()) && m_mainResource->dataBufferingPolicy() != BufferData)
         m_mainResource->setDataBufferingPolicy(BufferData);
 
-    if (m_identifierForLoadWithoutResourceLoader)
-        m_frame->fetchContext().dispatchDidReceiveResponse(this, m_identifierForLoadWithoutResourceLoader, m_response, 0);
-
     if (!shouldContinueForResponse()) {
         InspectorInstrumentation::continueWithPolicyIgnore(m_frame, this, m_mainResource->identifier(), m_response);
         cancelMainResourceLoad(ResourceError::cancelledError(m_request.url()));
@@ -558,18 +488,13 @@
     }
 }
 
-void DocumentLoader::ensureWriter()
-{
-    ensureWriter(m_response.mimeType());
-}
-
 void DocumentLoader::ensureWriter(const AtomicString& mimeType, const KURL& overridingURL)
 {
     if (m_writer)
         return;
 
     const AtomicString& encoding = overrideEncoding().isNull() ? response().textEncodingName() : overrideEncoding();
-    m_writer = createWriterFor(m_frame, 0, requestURL(), mimeType, encoding, false, false);
+    m_writer = createWriterFor(m_frame, 0, url(), mimeType, encoding, false, false);
     m_writer->setDocumentWasLoadedAsPartOfNavigation();
     // This should be set before receivedFirstData().
     if (!overridingURL.isEmpty())
@@ -582,7 +507,7 @@
 
 void DocumentLoader::commitData(const char* bytes, size_t length)
 {
-    ensureWriter();
+    ensureWriter(m_response.mimeType());
     ASSERT(m_frame->document()->parsing());
     m_writer->addData(bytes, length);
 }
@@ -600,9 +525,6 @@
     RefPtr<Frame> protectFrame(m_frame);
     RefPtr<DocumentLoader> protectLoader(this);
 
-    if (m_identifierForLoadWithoutResourceLoader)
-        frame()->fetchContext().dispatchDidReceiveData(this, m_identifierForLoadWithoutResourceLoader, data, length, -1);
-
     m_applicationCacheHost->mainResourceDataReceived(data, length);
     m_timeOfLastDataReceived = monotonicallyIncreasingTime();
 
@@ -623,9 +545,6 @@
 {
     if (!m_frame || isLoading())
         return;
-    // FIXME: This ASSERT is always triggered.
-    // See https://bugs.webkit.org/show_bug.cgi?id=110937
-    // ASSERT(this == frameLoader()->activeDocumentLoader())
     m_frame->domWindow()->finishedLoading();
 }
 
@@ -639,15 +558,6 @@
     m_redirectChain.append(url);
 }
 
-void DocumentLoader::setFrame(Frame* frame)
-{
-    if (m_frame == frame)
-        return;
-    ASSERT(frame && !m_frame);
-    ASSERT(!m_writer);
-    m_frame = frame;
-}
-
 void DocumentLoader::detachFromFrame()
 {
     ASSERT(m_frame);
@@ -666,8 +576,7 @@
 void DocumentLoader::clearMainResourceLoader()
 {
     m_loadingMainResource = false;
-    if (this == frameLoader()->activeDocumentLoader())
-        checkLoadComplete();
+    checkLoadComplete();
 }
 
 void DocumentLoader::clearMainResourceHandle()
@@ -684,7 +593,7 @@
     // but we still need to consider subframes.
     if (frameLoader()->state() != FrameStateComplete) {
         Document* doc = m_frame->document();
-        if ((isLoadingMainResource() || !m_frame->document()->loadEventFinished()) && isLoading())
+        if ((m_loadingMainResource || !m_frame->document()->loadEventFinished()) && isLoading())
             return true;
         if (m_fetcher->requestCount())
             return true;
@@ -698,10 +607,19 @@
     return frameLoader()->subframeIsLoading();
 }
 
-void DocumentLoader::createArchive()
+bool DocumentLoader::maybeCreateArchive()
 {
-    m_archive = MHTMLArchive::create(m_response.url(), mainResourceData().get());
-    RELEASE_ASSERT(m_archive);
+    // Give the archive machinery a crack at this document. If the MIME type is not an archive type, it will return 0.
+    if (!isArchiveMIMEType(m_response.mimeType()))
+        return false;
+
+    ASSERT(m_mainResource);
+    m_archive = MHTMLArchive::create(m_response.url(), m_mainResource->resourceBuffer());
+    // Invalid MHTML.
+    if (!m_archive || !m_archive->mainResource()) {
+        m_archive.clear();
+        return false;
+    }
 
     addAllArchiveResources(m_archive.get());
     ArchiveResource* mainResource = m_archive->mainResource();
@@ -711,6 +629,7 @@
     ensureWriter(mainResource->mimeType(), m_archive->mainResource()->url());
 
     commitData(mainResource->data()->data(), mainResource->data()->size());
+    return true;
 }
 
 void DocumentLoader::addAllArchiveResources(MHTMLArchive* archive)
@@ -768,12 +687,7 @@
 
 const KURL& DocumentLoader::originalURL() const
 {
-    return m_originalRequestCopy.url();
-}
-
-const KURL& DocumentLoader::requestURL() const
-{
-    return request().url();
+    return m_originalRequest.url();
 }
 
 const AtomicString& DocumentLoader::responseMIMEType() const
@@ -834,20 +748,13 @@
     m_applicationCacheHost->willStartLoadingMainResource(m_request);
     prepareSubframeArchiveLoadIfNeeded();
 
-    if (m_substituteData.isValid()) {
-        m_identifierForLoadWithoutResourceLoader = createUniqueIdentifier();
-        frame()->fetchContext().dispatchWillSendRequest(this, m_identifierForLoadWithoutResourceLoader, m_request, ResourceResponse());
-        handleSubstituteDataLoadSoon();
-        return;
-    }
-
     ResourceRequest request(m_request);
     DEFINE_STATIC_LOCAL(ResourceLoaderOptions, mainResourceLoadOptions,
-        (SendCallbacks, SniffContent, DoNotBufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, DocumentContext));
+        (SniffContent, DoNotBufferData, AllowStoredCredentials, ClientRequestedCredentials, CheckContentSecurityPolicy, DocumentContext));
     FetchRequest cachedResourceRequest(request, FetchInitiatorTypeNames::document, mainResourceLoadOptions);
-    m_mainResource = m_fetcher->fetchMainResource(cachedResourceRequest);
+    m_mainResource = m_fetcher->fetchMainResource(cachedResourceRequest, m_substituteData);
     if (!m_mainResource) {
-        setRequest(ResourceRequest());
+        m_request = ResourceRequest();
         // If the load was aborted by clearing m_request, it's possible the ApplicationCacheHost
         // is now in a state where starting an empty load will be inconsistent. Replace it with
         // a new ApplicationCacheHost.
@@ -864,7 +771,7 @@
     // the fragment identifier, so add that back in.
     if (equalIgnoringFragmentIdentifier(m_request.url(), request.url()))
         request.setURL(m_request.url());
-    setRequest(request);
+    m_request = request;
 }
 
 void DocumentLoader::cancelMainResourceLoad(const ResourceError& resourceError)
@@ -872,19 +779,12 @@
     RefPtr<DocumentLoader> protect(this);
     ResourceError error = resourceError.isNull() ? ResourceError::cancelledError(m_request.url()) : resourceError;
 
-    m_dataLoadTimer.stop();
     if (mainResourceLoader())
         mainResourceLoader()->cancel(error);
 
     mainReceivedError(error);
 }
 
-DocumentWriter* DocumentLoader::beginWriting(const AtomicString& mimeType, const AtomicString& encoding, const KURL& url)
-{
-    m_writer = createWriterFor(m_frame, 0, url, mimeType, encoding, false, true);
-    return m_writer.get();
-}
-
 void DocumentLoader::endWriting(DocumentWriter* writer)
 {
     ASSERT_UNUSED(writer, m_writer == writer);
@@ -897,6 +797,7 @@
     // Create a new document before clearing the frame, because it may need to
     // inherit an aliased security context.
     DocumentInit init(url, frame);
+    init.withNewRegistrationContext();
 
     // In some rare cases, we'll re-used a DOMWindow for a new Document. For example,
     // when a script calls window.open("..."), the browser gives JavaScript a window
@@ -907,10 +808,7 @@
     // the network load. See also SecurityContext::isSecureTransitionTo.
     bool shouldReuseDefaultView = frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && frame->document()->isSecureTransitionTo(url);
 
-    ClearOptions options = 0;
-    if (!shouldReuseDefaultView)
-        options = ClearWindowProperties | ClearScriptObjects;
-    frame->loader().clear(options);
+    frame->loader().clear();
 
     if (frame->document())
         frame->document()->prepareForDestruction();
@@ -918,7 +816,6 @@
     if (!shouldReuseDefaultView)
         frame->setDOMWindow(DOMWindow::create(frame));
 
-    frame->loader().setOutgoingReferrer(url);
     RefPtr<Document> document = frame->domWindow()->installNewDocument(mimeType, init);
     if (ownerDocument) {
         document->setCookieURL(ownerDocument->cookieURL());
diff --git a/Source/core/loader/DocumentLoader.h b/Source/core/loader/DocumentLoader.h
index d9b30f8..a54d183 100644
--- a/Source/core/loader/DocumentLoader.h
+++ b/Source/core/loader/DocumentLoader.h
@@ -37,7 +37,6 @@
 #include "core/loader/DocumentWriter.h"
 #include "core/loader/NavigationAction.h"
 #include "core/loader/SubstituteData.h"
-#include "platform/Timer.h"
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
@@ -65,51 +64,41 @@
     class DocumentLoader : public RefCounted<DocumentLoader>, private RawResourceClient {
         WTF_MAKE_FAST_ALLOCATED;
     public:
-        static PassRefPtr<DocumentLoader> create(const ResourceRequest& request, const SubstituteData& data)
+        static PassRefPtr<DocumentLoader> create(Frame* frame, const ResourceRequest& request, const SubstituteData& data)
         {
-            return adoptRef(new DocumentLoader(request, data));
+            return adoptRef(new DocumentLoader(frame, request, data));
         }
         virtual ~DocumentLoader();
 
-        void setFrame(Frame*);
         Frame* frame() const { return m_frame; }
 
         void detachFromFrame();
 
-        FrameLoader* frameLoader() const;
-
         unsigned long mainResourceIdentifier() const;
 
         void replaceDocument(const String& source, Document*);
-        DocumentWriter* beginWriting(const AtomicString& mimeType, const AtomicString& encoding, const KURL& = KURL());
-        void endWriting(DocumentWriter*);
 
         const AtomicString& mimeType() const;
 
         void setUserChosenEncoding(const String& charset);
 
         const ResourceRequest& originalRequest() const;
-        const ResourceRequest& originalRequestCopy() const;
 
         const ResourceRequest& request() const;
-        ResourceRequest& request();
 
         ResourceFetcher* fetcher() const { return m_fetcher.get(); }
 
         const SubstituteData& substituteData() const { return m_substituteData; }
 
-        // FIXME: This is the same as requestURL(). We should remove one of them.
         const KURL& url() const;
         const KURL& unreachableURL() const;
         bool isURLValidForNewHistoryEntry() const;
 
         const KURL& originalURL() const;
-        const KURL& requestURL() const;
         const AtomicString& responseMIMEType() const;
 
         void updateForSameDocumentNavigation(const KURL&);
         void stopLoading();
-        void setCommitted(bool committed) { m_committed = committed; }
         bool isCommitted() const { return m_committed; }
         bool isLoading() const;
         const ResourceResponse& response() const { return m_response; }
@@ -122,13 +111,8 @@
         const AtomicString& overrideEncoding() const { return m_overrideEncoding; }
 
         bool scheduleArchiveLoad(Resource*, const ResourceRequest&);
-        void cancelPendingSubstituteLoad(ResourceLoader*);
 
-        enum PolicyCheckLoadType {
-            PolicyCheckStandard,
-            PolicyCheckFragment
-        };
-        bool shouldContinueForNavigationPolicy(const ResourceRequest&, PolicyCheckLoadType);
+        bool shouldContinueForNavigationPolicy(const ResourceRequest&);
         const NavigationAction& triggeringAction() const { return m_triggeringAction; }
         void setTriggeringAction(const NavigationAction& action) { m_triggeringAction = action; }
 
@@ -139,16 +123,7 @@
         void startLoadingMainResource();
         void cancelMainResourceLoad(const ResourceError&);
 
-        bool isLoadingMainResource() const { return m_loadingMainResource; }
-
-        void stopLoadingSubresources();
-
-        void subresourceLoaderFinishedLoadingOnePart(ResourceLoader*);
-
-        void setDeferMainResourceDataLoad(bool defer) { m_deferMainResourceDataLoad = defer; }
-
         DocumentLoadTiming* timing() { return &m_documentLoadTiming; }
-        void resetTiming() { m_documentLoadTiming = DocumentLoadTiming(); }
 
         ApplicationCacheHost* applicationCacheHost() const { return m_applicationCacheHost.get(); }
 
@@ -159,20 +134,18 @@
         void appendRedirect(const KURL&);
 
     protected:
-        DocumentLoader(const ResourceRequest&, const SubstituteData&);
+        DocumentLoader(Frame*, const ResourceRequest&, const SubstituteData&);
 
-        bool m_deferMainResourceDataLoad;
         Vector<KURL> m_redirectChain;
 
     private:
         static PassRefPtr<DocumentWriter> createWriterFor(Frame*, const Document* ownerDocument, const KURL&, const AtomicString& mimeType, const AtomicString& encoding, bool userChosen, bool dispatch);
 
-        void ensureWriter();
         void ensureWriter(const AtomicString& mimeType, const KURL& overridingURL = KURL());
+        void endWriting(DocumentWriter*);
 
         Document* document() const;
-
-        void setRequest(const ResourceRequest&);
+        FrameLoader* frameLoader() const;
 
         void commitIfReady();
         void commitData(const char* bytes, size_t length);
@@ -180,9 +153,8 @@
         void clearMainResourceLoader();
         ResourceLoader* mainResourceLoader() const;
         void clearMainResourceHandle();
-        PassRefPtr<SharedBuffer> mainResourceData() const;
 
-        void createArchive();
+        bool maybeCreateArchive();
         void clearArchiveResources();
 
         void prepareSubframeArchiveLoadIfNeeded();
@@ -191,10 +163,11 @@
         void willSendRequest(ResourceRequest&, const ResourceResponse&);
         void finishedLoading(double finishTime);
         void mainReceivedError(const ResourceError&);
-        virtual void redirectReceived(Resource*, ResourceRequest&, const ResourceResponse&) OVERRIDE;
-        virtual void responseReceived(Resource*, const ResourceResponse&) OVERRIDE;
-        virtual void dataReceived(Resource*, const char* data, int length) OVERRIDE;
-        virtual void notifyFinished(Resource*) OVERRIDE;
+        virtual void redirectReceived(Resource*, ResourceRequest&, const ResourceResponse&) OVERRIDE FINAL;
+        virtual void updateRequest(Resource*, const ResourceRequest&) OVERRIDE FINAL;
+        virtual void responseReceived(Resource*, const ResourceResponse&) OVERRIDE FINAL;
+        virtual void dataReceived(Resource*, const char* data, int length) OVERRIDE FINAL;
+        virtual void notifyFinished(Resource*) OVERRIDE FINAL;
 
         bool maybeLoadEmpty();
 
@@ -202,12 +175,6 @@
 
         bool shouldContinueForResponse() const;
 
-        typedef Timer<DocumentLoader> DocumentLoaderTimer;
-
-        void handleSubstituteDataLoadSoon();
-        void handleSubstituteDataLoadNow(DocumentLoaderTimer*);
-        void startDataLoadTimer();
-
         Frame* m_frame;
         RefPtr<ResourceFetcher> m_fetcher;
 
@@ -216,17 +183,12 @@
         RefPtr<DocumentWriter> m_writer;
 
         // A reference to actual request used to create the data source.
-        // This should only be used by the resourceLoadDelegate's
-        // identifierForInitialRequest:fromDatasource: method. It is
-        // not guaranteed to remain unchanged, as requests are mutable.
+        // The only part of this request that should change is the url, and
+        // that only in the case of a same-document navigation.
         ResourceRequest m_originalRequest;
 
         SubstituteData m_substituteData;
 
-        // A copy of the original request used to create the data source.
-        // We have to copy the request because requests are mutable.
-        ResourceRequest m_originalRequestCopy;
-
         // The 'working' request. It may be mutated
         // several times from the original request to include additional
         // headers, cookie information, canonicalization and redirects.
@@ -253,9 +215,6 @@
         DocumentLoadTiming m_documentLoadTiming;
 
         double m_timeOfLastDataReceived;
-        unsigned long m_identifierForLoadWithoutResourceLoader;
-
-        DocumentLoaderTimer m_dataLoadTimer;
 
         friend class ApplicationCacheHost;  // for substitute resource delivery
         OwnPtr<ApplicationCacheHost> m_applicationCacheHost;
diff --git a/Source/core/loader/DocumentThreadableLoader.cpp b/Source/core/loader/DocumentThreadableLoader.cpp
index f9d9e18..1888afb 100644
--- a/Source/core/loader/DocumentThreadableLoader.cpp
+++ b/Source/core/loader/DocumentThreadableLoader.cpp
@@ -62,7 +62,7 @@
 PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
 {
     RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options));
-    if (!loader->m_resource)
+    if (!loader->resource())
         loader = 0;
     return loader.release();
 }
@@ -82,7 +82,7 @@
     ASSERT(m_async || request.httpReferrer().isEmpty());
 
     if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) {
-        loadRequest(request, DoSecurityCheck);
+        loadRequest(request);
         return;
     }
 
@@ -127,19 +127,17 @@
         return;
     }
 
-    loadRequest(request, DoSecurityCheck);
+    loadRequest(request);
 }
 
 void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(const ResourceRequest& request)
 {
     ResourceRequest preflightRequest = createAccessControlPreflightRequest(request, securityOrigin());
-    loadRequest(preflightRequest, DoSecurityCheck);
+    loadRequest(preflightRequest);
 }
 
 DocumentThreadableLoader::~DocumentThreadableLoader()
 {
-    if (m_resource)
-        m_resource->removeClient(this);
 }
 
 void DocumentThreadableLoader::cancel()
@@ -152,14 +150,14 @@
     RefPtr<DocumentThreadableLoader> protect(this);
 
     // Cancel can re-enter and m_resource might be null here as a result.
-    if (m_client && m_resource) {
+    if (m_client && resource()) {
         ResourceError errorForCallback = error;
         if (errorForCallback.isNull()) {
             // FIXME: This error is sent to the client in didFail(), so it should not be an internal one. Use FrameLoaderClient::cancelledError() instead.
-            errorForCallback = ResourceError(errorDomainBlinkInternal, 0, m_resource->url().string(), "Load cancelled");
+            errorForCallback = ResourceError(errorDomainBlinkInternal, 0, resource()->url().string(), "Load cancelled");
             errorForCallback.setIsCancellation(true);
         }
-        didFail(m_resource->identifier(), errorForCallback);
+        m_client->didFail(errorForCallback);
     }
     clearResource();
     m_client = 0;
@@ -167,26 +165,14 @@
 
 void DocumentThreadableLoader::setDefersLoading(bool value)
 {
-    if (m_resource)
-        m_resource->setDefersLoading(value);
-}
-
-void DocumentThreadableLoader::clearResource()
-{
-    // Script can cancel and restart a request reentrantly within removeClient(),
-    // which could lead to calling Resource::removeClient() multiple times for
-    // this DocumentThreadableLoader. Save off a copy of m_resource and clear it to
-    // prevent the reentrancy.
-    if (ResourcePtr<RawResource> resource = m_resource) {
-        m_resource = 0;
-        resource->removeClient(this);
-    }
+    if (resource())
+        resource()->setDefersLoading(value);
 }
 
 void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse)
 {
     ASSERT(m_client);
-    ASSERT_UNUSED(resource, resource == m_resource);
+    ASSERT_UNUSED(resource, resource == this->resource());
 
     RefPtr<DocumentThreadableLoader> protect(this);
     if (!isAllowedByPolicy(request.url())) {
@@ -213,15 +199,16 @@
         String accessControlErrorDescription;
 
         if (m_simpleRequest) {
-            allowRedirect = checkCrossOriginAccessRedirectionUrl(request.url(), accessControlErrorDescription)
+            allowRedirect = CrossOriginAccessControl::isLegalRedirectLocation(request.url(), accessControlErrorDescription)
                             && (m_sameOriginRequest || passesAccessControlCheck(redirectResponse, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription));
         } else {
             accessControlErrorDescription = "The request was redirected to '"+ request.url().string() + "', which is disallowed for cross-origin requests that require preflight.";
         }
 
         if (allowRedirect) {
-            if (m_resource)
-                clearResource();
+            // FIXME: consider combining this with CORS redirect handling performed by
+            // CrossOriginAccessControl::handleRedirect().
+            clearResource();
 
             RefPtr<SecurityOrigin> originalOrigin = SecurityOrigin::create(redirectResponse.url());
             RefPtr<SecurityOrigin> requestOrigin = SecurityOrigin::create(request.url());
@@ -259,14 +246,14 @@
 void DocumentThreadableLoader::dataSent(Resource* resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
 {
     ASSERT(m_client);
-    ASSERT_UNUSED(resource, resource == m_resource);
+    ASSERT_UNUSED(resource, resource == this->resource());
     m_client->didSendData(bytesSent, totalBytesToBeSent);
 }
 
 void DocumentThreadableLoader::dataDownloaded(Resource* resource, int dataLength)
 {
     ASSERT(m_client);
-    ASSERT_UNUSED(resource, resource == m_resource);
+    ASSERT_UNUSED(resource, resource == this->resource());
     ASSERT(!m_actualRequest);
 
     m_client->didDownloadData(dataLength);
@@ -274,8 +261,8 @@
 
 void DocumentThreadableLoader::responseReceived(Resource* resource, const ResourceResponse& response)
 {
-    ASSERT_UNUSED(resource, resource == m_resource);
-    didReceiveResponse(m_resource->identifier(), response);
+    ASSERT_UNUSED(resource, resource == this->resource());
+    didReceiveResponse(resource->identifier(), response);
 }
 
 void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
@@ -284,16 +271,20 @@
 
     String accessControlErrorDescription;
     if (m_actualRequest) {
+        // Notifying the inspector here is necessary because a call to preflightFailure() might synchronously
+        // cause the underlying ResourceLoader to be cancelled before it tells the inspector about the response.
+        // In that case, if we don't tell the inspector about the response now, the resource type in the inspector
+        // will default to "other" instead of something more descriptive.
         DocumentLoader* loader = m_document->frame()->loader().documentLoader();
-        InspectorInstrumentation::didReceiveResourceResponse(m_document->frame(), identifier, loader, response, m_resource ? m_resource->loader() : 0);
+        InspectorInstrumentation::didReceiveResourceResponse(m_document->frame(), identifier, loader, response, resource() ? resource()->loader() : 0);
 
         if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
-            preflightFailure(identifier, response.url().string(), accessControlErrorDescription);
+            preflightFailure(response.url().string(), accessControlErrorDescription);
             return;
         }
 
         if (!passesPreflightStatusCheck(response, accessControlErrorDescription)) {
-            preflightFailure(identifier, response.url().string(), accessControlErrorDescription);
+            preflightFailure(response.url().string(), accessControlErrorDescription);
             return;
         }
 
@@ -301,7 +292,7 @@
         if (!preflightResult->parse(response, accessControlErrorDescription)
             || !preflightResult->allowsCrossOriginMethod(m_actualRequest->httpMethod(), accessControlErrorDescription)
             || !preflightResult->allowsCrossOriginHeaders(m_actualRequest->httpHeaderFields(), accessControlErrorDescription)) {
-            preflightFailure(identifier, response.url().string(), accessControlErrorDescription);
+            preflightFailure(response.url().string(), accessControlErrorDescription);
             return;
         }
 
@@ -320,40 +311,34 @@
 
 void DocumentThreadableLoader::dataReceived(Resource* resource, const char* data, int dataLength)
 {
-    ASSERT_UNUSED(resource, resource == m_resource);
-    didReceiveData(m_resource->identifier(), data, dataLength);
+    ASSERT_UNUSED(resource, resource == this->resource());
+    didReceiveData(data, dataLength);
 }
 
-void DocumentThreadableLoader::didReceiveData(unsigned long identifier, const char* data, int dataLength)
+void DocumentThreadableLoader::didReceiveData(const char* data, int dataLength)
 {
     ASSERT(m_client);
-
     // Preflight data should be invisible to clients.
-    if (m_actualRequest) {
-        InspectorInstrumentation::didReceiveData(m_document->frame(), identifier, 0, 0, dataLength);
-        return;
-    }
-
-    m_client->didReceiveData(data, dataLength);
+    if (!m_actualRequest)
+        m_client->didReceiveData(data, dataLength);
 }
 
 void DocumentThreadableLoader::notifyFinished(Resource* resource)
 {
     ASSERT(m_client);
-    ASSERT_UNUSED(resource, resource == m_resource);
+    ASSERT(resource == this->resource());
 
     m_timeoutTimer.stop();
 
-    if (m_resource->errorOccurred())
-        didFail(m_resource->identifier(), m_resource->resourceError());
+    if (resource->errorOccurred())
+        m_client->didFail(resource->resourceError());
     else
-        didFinishLoading(m_resource->identifier(), m_resource->loadFinishTime());
+        didFinishLoading(resource->identifier(), resource->loadFinishTime());
 }
 
 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
 {
     if (m_actualRequest) {
-        InspectorInstrumentation::didFinishLoading(m_document->frame(), identifier, m_document->frame()->loader().documentLoader(), finishTime);
         ASSERT(!m_sameOriginRequest);
         ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
         preflightSuccess();
@@ -361,14 +346,6 @@
         m_client->didFinishLoading(identifier, finishTime);
 }
 
-void DocumentThreadableLoader::didFail(unsigned long identifier, const ResourceError& error)
-{
-    if (m_actualRequest)
-        InspectorInstrumentation::didFailLoading(m_document->frame(), identifier, m_document->frame()->loader().documentLoader(), error);
-
-    m_client->didFail(error);
-}
-
 void DocumentThreadableLoader::didTimeout(Timer<DocumentThreadableLoader>* timer)
 {
     ASSERT_UNUSED(timer, timer == &m_timeoutTimer);
@@ -376,7 +353,7 @@
     // Using values from net/base/net_error_list.h ERR_TIMED_OUT,
     // Same as existing FIXME above - this error should be coming from FrameLoaderClient to be identifiable.
     static const int timeoutError = -7;
-    ResourceError error("net", timeoutError, m_resource->url(), String());
+    ResourceError error("net", timeoutError, resource()->url(), String());
     error.setIsTimeout(true);
     cancelWithError(error);
 }
@@ -386,39 +363,31 @@
     OwnPtr<ResourceRequest> actualRequest;
     actualRequest.swap(m_actualRequest);
 
-    actualRequest->setHTTPOrigin(securityOrigin()->toString());
+    actualRequest->setHTTPOrigin(securityOrigin()->toAtomicString());
 
     clearResource();
 
-    // It should be ok to skip the security check since we already asked about the preflight request.
-    loadRequest(*actualRequest, SkipSecurityCheck);
+    loadRequest(*actualRequest);
 }
 
-void DocumentThreadableLoader::preflightFailure(unsigned long identifier, const String& url, const String& errorDescription)
+void DocumentThreadableLoader::preflightFailure(const String& url, const String& errorDescription)
 {
     ResourceError error(errorDomainBlinkInternal, 0, url, errorDescription);
-    if (m_actualRequest)
-        InspectorInstrumentation::didFailLoading(m_document->frame(), identifier, m_document->frame()->loader().documentLoader(), error);
     m_actualRequest = nullptr; // Prevent didFinishLoading() from bypassing access check.
     m_client->didFailAccessControlCheck(error);
 }
 
-void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, SecurityCheckPolicy securityCheck)
+void DocumentThreadableLoader::loadRequest(const ResourceRequest& request)
 {
     // Any credential should have been removed from the cross-site requests.
     const KURL& requestURL = request.url();
-    m_options.securityCheck = securityCheck;
     ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
     ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
 
     ThreadableLoaderOptions options = m_options;
     if (m_async) {
-        options.crossOriginCredentialPolicy = DoNotAskClientForCrossOriginCredentials;
         if (m_actualRequest) {
-            // Don't sniff content or send load callbacks for the preflight request.
-            options.sendLoadCallbacks = DoNotSendCallbacks;
             options.sniffContent = DoNotSniffContent;
-            // Keep buffering the data for the preflight request.
             options.dataBufferingPolicy = BufferData;
         }
 
@@ -426,14 +395,11 @@
             m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0);
 
         FetchRequest newRequest(request, m_options.initiator, options);
-        ASSERT(!m_resource);
-        m_resource = m_document->fetcher()->fetchRawResource(newRequest);
-        if (m_resource) {
-            if (m_resource->loader()) {
-                unsigned long identifier = m_resource->identifier();
-                InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
-            }
-            m_resource->addClient(this);
+        ASSERT(!resource());
+        setResource(m_document->fetcher()->fetchRawResource(newRequest));
+        if (resource() && resource()->loader()) {
+            unsigned long identifier = resource()->identifier();
+            InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
         }
         return;
     }
@@ -470,7 +436,7 @@
 
     SharedBuffer* data = resource->resourceBuffer();
     if (data)
-        didReceiveData(identifier, data->data(), data->size());
+        didReceiveData(data->data(), data->size());
 
     didFinishLoading(identifier, 0.0);
 }
@@ -495,19 +461,4 @@
     return m_options.securityOrigin ? m_options.securityOrigin.get() : m_document->securityOrigin();
 }
 
-bool DocumentThreadableLoader::checkCrossOriginAccessRedirectionUrl(const KURL& requestUrl, String& errorDescription)
-{
-    if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(requestUrl.protocol())) {
-        errorDescription = "The request was redirected to a URL ('" + requestUrl.string() + "') which has a disallowed scheme for cross-origin requests.";
-        return false;
-    }
-
-    if (!(requestUrl.user().isEmpty() && requestUrl.pass().isEmpty())) {
-        errorDescription = "The request was redirected to a URL ('" + requestUrl.string() + "') containing userinfo, which is disallowed for cross-origin requests.";
-        return false;
-    }
-
-    return true;
-}
-
 } // namespace WebCore
diff --git a/Source/core/loader/DocumentThreadableLoader.h b/Source/core/loader/DocumentThreadableLoader.h
index 77139bd..2a32096 100644
--- a/Source/core/loader/DocumentThreadableLoader.h
+++ b/Source/core/loader/DocumentThreadableLoader.h
@@ -33,7 +33,7 @@
 #define DocumentThreadableLoader_h
 
 #include "core/fetch/RawResource.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
 #include "core/loader/ThreadableLoader.h"
 #include "platform/Timer.h"
 #include "platform/network/ResourceError.h"
@@ -51,22 +51,22 @@
 class SecurityOrigin;
 class ThreadableLoaderClient;
 
-class DocumentThreadableLoader : public RefCounted<DocumentThreadableLoader>, public ThreadableLoader, private RawResourceClient  {
+class DocumentThreadableLoader FINAL : public RefCounted<DocumentThreadableLoader>, public ThreadableLoader, private ResourceOwner<RawResource>  {
     WTF_MAKE_FAST_ALLOCATED;
     public:
         static void loadResourceSynchronously(Document*, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&);
         static PassRefPtr<DocumentThreadableLoader> create(Document*, ThreadableLoaderClient*, const ResourceRequest&, const ThreadableLoaderOptions&);
         virtual ~DocumentThreadableLoader();
 
-        virtual void cancel();
-        virtual void setDefersLoading(bool);
+        virtual void cancel() OVERRIDE;
+        void setDefersLoading(bool);
 
         using RefCounted<DocumentThreadableLoader>::ref;
         using RefCounted<DocumentThreadableLoader>::deref;
 
     protected:
-        virtual void refThreadableLoader() { ref(); }
-        virtual void derefThreadableLoader() { deref(); }
+        virtual void refThreadableLoader() OVERRIDE { ref(); }
+        virtual void derefThreadableLoader() OVERRIDE { deref(); }
 
     private:
         enum BlockingBehavior {
@@ -76,36 +76,31 @@
 
         DocumentThreadableLoader(Document*, ThreadableLoaderClient*, BlockingBehavior, const ResourceRequest&, const ThreadableLoaderOptions&);
 
-        void clearResource();
-
         // RawResourceClient
-        virtual void dataSent(Resource*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
-        virtual void responseReceived(Resource*, const ResourceResponse&);
-        virtual void dataReceived(Resource*, const char* data, int dataLength);
-        virtual void redirectReceived(Resource*, ResourceRequest&, const ResourceResponse&);
-        virtual void notifyFinished(Resource*);
-        virtual void dataDownloaded(Resource*, int);
+        virtual void dataSent(Resource*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
+        virtual void responseReceived(Resource*, const ResourceResponse&) OVERRIDE;
+        virtual void dataReceived(Resource*, const char* data, int dataLength) OVERRIDE;
+        virtual void redirectReceived(Resource*, ResourceRequest&, const ResourceResponse&) OVERRIDE;
+        virtual void notifyFinished(Resource*) OVERRIDE;
+        virtual void dataDownloaded(Resource*, int) OVERRIDE;
 
         void cancelWithError(const ResourceError&);
         void didReceiveResponse(unsigned long identifier, const ResourceResponse&);
-        void didReceiveData(unsigned long identifier, const char* data, int dataLength);
+        void didReceiveData(const char* data, int dataLength);
         void didFinishLoading(unsigned long identifier, double finishTime);
-        void didFail(unsigned long identifier, const ResourceError&);
         void didTimeout(Timer<DocumentThreadableLoader>*);
         void makeCrossOriginAccessRequest(const ResourceRequest&);
         void makeSimpleCrossOriginAccessRequest(const ResourceRequest&);
         void makeCrossOriginAccessRequestWithPreflight(const ResourceRequest&);
         void preflightSuccess();
-        void preflightFailure(unsigned long identifier, const String& url, const String& errorDescription);
+        void preflightFailure(const String& url, const String& errorDescription);
 
-        void loadRequest(const ResourceRequest&, SecurityCheckPolicy);
+        void loadRequest(const ResourceRequest&);
         bool isAllowedRedirect(const KURL&) const;
         bool isAllowedByPolicy(const KURL&) const;
 
         SecurityOrigin* securityOrigin() const;
-        bool checkCrossOriginAccessRedirectionUrl(const KURL&, String& errorDescription);
 
-        ResourcePtr<RawResource> m_resource;
         ThreadableLoaderClient* m_client;
         Document* m_document;
         ThreadableLoaderOptions m_options;
diff --git a/Source/core/loader/DocumentThreadableLoaderClient.h b/Source/core/loader/DocumentThreadableLoaderClient.h
index 325a841..d272a47 100644
--- a/Source/core/loader/DocumentThreadableLoaderClient.h
+++ b/Source/core/loader/DocumentThreadableLoaderClient.h
@@ -42,7 +42,7 @@
     WTF_MAKE_NONCOPYABLE(DocumentThreadableLoaderClient);
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    virtual bool isDocumentThreadableLoaderClient() { return true; }
+    virtual bool isDocumentThreadableLoaderClient()  OVERRIDE FINAL { return true; }
 
     virtual void willSendRequest(ResourceRequest& /*newRequest*/, const ResourceResponse& /*redirectResponse*/) { }
 
diff --git a/Source/core/loader/DocumentWriter.cpp b/Source/core/loader/DocumentWriter.cpp
index 9400517..8294fbd 100644
--- a/Source/core/loader/DocumentWriter.cpp
+++ b/Source/core/loader/DocumentWriter.cpp
@@ -31,13 +31,13 @@
 
 #include "core/dom/Document.h"
 #include "core/dom/ScriptableDocumentParser.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderStateMachine.h"
 #include "core/frame/DOMWindow.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/weborigin/KURL.h"
 #include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/PassOwnPtr.h"
@@ -78,7 +78,6 @@
         // Because we're pinned to the main thread we don't need to worry about
         // passing ownership of the source string.
         parser->append(source.impl());
-        parser->setHasAppendedData();
     }
 }
 
diff --git a/Source/core/loader/EmptyClients.cpp b/Source/core/loader/EmptyClients.cpp
index ea196a4..da1c28d 100644
--- a/Source/core/loader/EmptyClients.cpp
+++ b/Source/core/loader/EmptyClients.cpp
@@ -32,6 +32,7 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FormState.h"
 #include "core/frame/Frame.h"
+#include "core/storage/StorageNamespace.h"
 #include "platform/ColorChooser.h"
 #include "platform/DateTimeChooser.h"
 #include "platform/FileChooser.h"
@@ -62,6 +63,9 @@
 
     static SpellCheckerClient* dummySpellCheckerClient = adoptPtr(new EmptySpellCheckerClient).leakPtr();
     pageClients.spellCheckerClient = dummySpellCheckerClient;
+
+    static StorageClient* dummyStorageClient = adoptPtr(new EmptyStorageClient).leakPtr();
+    pageClients.storageClient = dummyStorageClient;
 }
 
 class EmptyPopupMenu : public PopupMenu {
@@ -87,6 +91,10 @@
     return PassRefPtr<DateTimeChooser>();
 }
 
+void EmptyChromeClient::openTextDataListChooser(HTMLInputElement&)
+{
+}
+
 void EmptyChromeClient::runOpenPanel(Frame*, PassRefPtr<FileChooser>)
 {
 }
@@ -109,12 +117,12 @@
 {
 }
 
-PassRefPtr<DocumentLoader> EmptyFrameLoaderClient::createDocumentLoader(const ResourceRequest& request, const SubstituteData& substituteData)
+PassRefPtr<DocumentLoader> EmptyFrameLoaderClient::createDocumentLoader(Frame* frame, const ResourceRequest& request, const SubstituteData& substituteData)
 {
-    return DocumentLoader::create(request, substituteData);
+    return DocumentLoader::create(frame, request, substituteData);
 }
 
-PassRefPtr<Frame> EmptyFrameLoaderClient::createFrame(const KURL&, const String&, const String&, HTMLFrameOwnerElement*)
+PassRefPtr<Frame> EmptyFrameLoaderClient::createFrame(const KURL&, const AtomicString&, const Referrer&, HTMLFrameOwnerElement*)
 {
     return 0;
 }
@@ -142,4 +150,9 @@
     return nullptr;
 }
 
+PassOwnPtr<StorageNamespace> EmptyStorageClient::createSessionStorageNamespace()
+{
+    return nullptr;
+}
+
 }
diff --git a/Source/core/loader/EmptyClients.h b/Source/core/loader/EmptyClients.h
index f80131c..f66e933 100644
--- a/Source/core/loader/EmptyClients.h
+++ b/Source/core/loader/EmptyClients.h
@@ -37,10 +37,11 @@
 #include "core/page/ContextMenuClient.h"
 #include "core/page/DragClient.h"
 #include "core/page/EditorClient.h"
-#include "core/page/FocusDirection.h"
+#include "core/page/FocusType.h"
 #include "core/page/Page.h"
 #include "core/page/SpellCheckerClient.h"
-#include "core/platform/DragImage.h"
+#include "core/page/StorageClient.h"
+#include "platform/DragImage.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/network/ResourceError.h"
 #include "platform/text/TextCheckerClient.h"
@@ -64,8 +65,6 @@
 
 namespace WebCore {
 
-class GraphicsContext3D;
-
 class EmptyChromeClient : public ChromeClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -79,10 +78,9 @@
     virtual FloatRect pageRect() OVERRIDE { return FloatRect(); }
 
     virtual void focus() OVERRIDE { }
-    virtual void unfocus() OVERRIDE { }
 
-    virtual bool canTakeFocus(FocusDirection) OVERRIDE { return false; }
-    virtual void takeFocus(FocusDirection) OVERRIDE { }
+    virtual bool canTakeFocus(FocusType) OVERRIDE { return false; }
+    virtual void takeFocus(FocusType) OVERRIDE { }
 
     virtual void focusedNodeChanged(Node*) OVERRIDE { }
     virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy, ShouldSendReferrer) OVERRIDE { return 0; }
@@ -119,8 +117,6 @@
 
     virtual bool hasOpenedPopup() const OVERRIDE { return false; }
     virtual PassRefPtr<PopupMenu> createPopupMenu(Frame&, PopupMenuClient*) const OVERRIDE;
-    virtual PagePopup* openPagePopup(PagePopupClient*, const IntRect&) OVERRIDE { return 0; }
-    virtual void closePagePopup(PagePopup*) OVERRIDE { }
     virtual void setPagePopupDriver(PagePopupDriver*) OVERRIDE { }
     virtual void resetPagePopupDriver() OVERRIDE { }
 
@@ -135,7 +131,8 @@
     virtual void scroll(const IntSize&, const IntRect&, const IntRect&) OVERRIDE { }
     virtual void scheduleAnimation() OVERRIDE { }
 
-    virtual IntPoint screenToRootView(const IntPoint& p) const OVERRIDE { return p; }
+    virtual bool isCompositorFramePending() const OVERRIDE { return false; }
+
     virtual IntRect rootViewToScreen(const IntRect& r) const OVERRIDE { return r; }
     virtual blink::WebScreenInfo screenInfo() const OVERRIDE { return blink::WebScreenInfo(); }
     virtual void contentsSizeChanged(Frame*, const IntSize&) const OVERRIDE { }
@@ -149,8 +146,8 @@
     virtual void enumerateChosenDirectory(FileChooser*) OVERRIDE { }
 
     virtual PassOwnPtr<ColorChooser> createColorChooser(ColorChooserClient*, const Color&) OVERRIDE;
-
     virtual PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) OVERRIDE;
+    virtual void openTextDataListChooser(HTMLInputElement&) OVERRIDE;
 
     virtual void runOpenPanel(Frame*, PassRefPtr<FileChooser>) OVERRIDE;
 
@@ -159,7 +156,6 @@
     virtual void setCursor(const Cursor&) OVERRIDE { }
 
     virtual void attachRootGraphicsLayer(Frame*, GraphicsLayer*) OVERRIDE { }
-    virtual void scheduleCompositingLayerFlush() OVERRIDE { }
 
     virtual void needTouchEvents(bool) OVERRIDE { }
     virtual void setTouchAction(TouchAction touchAction) OVERRIDE { };
@@ -168,28 +164,27 @@
 
     virtual bool shouldRubberBandInDirection(WebCore::ScrollDirection) const OVERRIDE { return false; }
 
-    virtual bool isEmptyChromeClient() const OVERRIDE { return true; }
-
     virtual void didAssociateFormControls(const Vector<RefPtr<Element> >&) OVERRIDE { }
 
-    virtual void popupOpened(PopupContainer* popupContainer, const IntRect& bounds,
-                             bool handleExternal) { }
-    virtual void popupClosed(PopupContainer* popupContainer) OVERRIDE { }
-
     virtual void annotatedRegionsChanged() OVERRIDE { }
     virtual bool paintCustomOverhangArea(GraphicsContext*, const IntRect&, const IntRect&, const IntRect&) OVERRIDE { return false; }
     virtual String acceptLanguages() OVERRIDE;
 };
 
-class EmptyFrameLoaderClient : public FrameLoaderClient {
+class EmptyFrameLoaderClient FINAL : public FrameLoaderClient {
     WTF_MAKE_NONCOPYABLE(EmptyFrameLoaderClient); WTF_MAKE_FAST_ALLOCATED;
 public:
     EmptyFrameLoaderClient() { }
     virtual ~EmptyFrameLoaderClient() {  }
-    virtual void frameLoaderDestroyed() OVERRIDE { }
 
     virtual bool hasWebView() const OVERRIDE { return true; } // mainly for assertions
 
+    virtual Frame* parent() const OVERRIDE { return 0; }
+    virtual Frame* top() const OVERRIDE { return 0; }
+    virtual Frame* previousSibling() const OVERRIDE { return 0; }
+    virtual Frame* nextSibling() const OVERRIDE { return 0; }
+    virtual Frame* firstChild() const OVERRIDE { return 0; }
+    virtual Frame* lastChild() const OVERRIDE { return 0; }
     virtual void detachedFromParent() OVERRIDE { }
 
     virtual void dispatchWillSendRequest(DocumentLoader*, unsigned long, ResourceRequest&, const ResourceResponse&) OVERRIDE { }
@@ -203,7 +198,7 @@
     virtual void dispatchDidStartProvisionalLoad() OVERRIDE { }
     virtual void dispatchDidReceiveTitle(const String&) OVERRIDE { }
     virtual void dispatchDidChangeIcons(IconType) OVERRIDE { }
-    virtual void dispatchDidCommitLoad(Frame*, HistoryItem*, NavigationHistoryPolicy) OVERRIDE { }
+    virtual void dispatchDidCommitLoad(Frame*, HistoryItem*, HistoryCommitType) OVERRIDE { }
     virtual void dispatchDidFailProvisionalLoad(const ResourceError&) OVERRIDE { }
     virtual void dispatchDidFailLoad(const ResourceError&) OVERRIDE { }
     virtual void dispatchDidFinishDocumentLoad() OVERRIDE { }
@@ -215,13 +210,13 @@
     virtual void dispatchWillSendSubmitEvent(PassRefPtr<FormState>) OVERRIDE;
     virtual void dispatchWillSubmitForm(PassRefPtr<FormState>) OVERRIDE;
 
-    virtual void postProgressStartedNotification() OVERRIDE { }
+    virtual void postProgressStartedNotification(LoadStartType) OVERRIDE { }
     virtual void postProgressEstimateChangedNotification() OVERRIDE { }
     virtual void postProgressFinishedNotification() OVERRIDE { }
 
     virtual void loadURLExternally(const ResourceRequest&, NavigationPolicy, const String& = String()) OVERRIDE { }
 
-    virtual PassRefPtr<DocumentLoader> createDocumentLoader(const ResourceRequest&, const SubstituteData&) OVERRIDE;
+    virtual PassRefPtr<DocumentLoader> createDocumentLoader(Frame*, const ResourceRequest&, const SubstituteData&) OVERRIDE;
 
     virtual String userAgent(const KURL&) OVERRIDE { return ""; }
 
@@ -235,7 +230,7 @@
     virtual void didDetectXSS(const KURL&, bool) OVERRIDE { }
     virtual void didDispatchPingLoader(const KURL&) OVERRIDE { }
     virtual void selectorMatchChanged(const Vector<String>&, const Vector<String>&) OVERRIDE { }
-    virtual PassRefPtr<Frame> createFrame(const KURL&, const String&, const String&, HTMLFrameOwnerElement*) OVERRIDE;
+    virtual PassRefPtr<Frame> createFrame(const KURL&, const AtomicString&, const Referrer&, HTMLFrameOwnerElement*) OVERRIDE;
     virtual PassRefPtr<Widget> createPlugin(const IntSize&, HTMLPlugInElement*, const KURL&, const Vector<String>&, const Vector<String>&, const String&, bool) OVERRIDE;
     virtual PassRefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement*, const KURL&, const Vector<String>&, const Vector<String>&) OVERRIDE;
 
@@ -248,13 +243,13 @@
     virtual void willReleaseScriptContext(v8::Handle<v8::Context>, int worldId) OVERRIDE { }
     virtual bool allowScriptExtension(const String& extensionName, int extensionGroup, int worldId) OVERRIDE { return false; }
 
-    virtual blink::WebCookieJar* cookieJar() const { return 0; }
+    virtual blink::WebCookieJar* cookieJar() const OVERRIDE { return 0; }
 
     virtual void didRequestAutocomplete(PassRefPtr<FormState>) OVERRIDE;
     virtual PassOwnPtr<blink::WebServiceWorkerProvider> createServiceWorkerProvider(PassOwnPtr<blink::WebServiceWorkerProviderClient>) OVERRIDE;
 };
 
-class EmptyTextCheckerClient : public TextCheckerClient {
+class EmptyTextCheckerClient FINAL : public TextCheckerClient {
 public:
     virtual bool shouldEraseMarkersAfterChangeSelection(TextCheckingType) const OVERRIDE { return true; }
     virtual void checkSpellingOfString(const String&, int*, int*) OVERRIDE { }
@@ -263,7 +258,7 @@
     virtual void requestCheckingOfString(PassRefPtr<TextCheckingRequest>) OVERRIDE;
 };
 
-class EmptySpellCheckerClient : public SpellCheckerClient {
+class EmptySpellCheckerClient FINAL : public SpellCheckerClient {
     WTF_MAKE_NONCOPYABLE(EmptySpellCheckerClient); WTF_MAKE_FAST_ALLOCATED;
 public:
     EmptySpellCheckerClient() { }
@@ -273,7 +268,7 @@
     virtual void toggleContinuousSpellChecking() OVERRIDE { }
     virtual bool isGrammarCheckingEnabled() OVERRIDE { return false; }
 
-    TextCheckerClient& textChecker() { return m_textCheckerClient; }
+    virtual TextCheckerClient& textChecker() OVERRIDE { return m_textCheckerClient; }
 
     virtual void updateSpellingUIWithMisspelledWord(const String&) OVERRIDE { }
     virtual void showSpellingUI(bool) OVERRIDE { }
@@ -283,7 +278,7 @@
     EmptyTextCheckerClient m_textCheckerClient;
 };
 
-class EmptyEditorClient : public EditorClient {
+class EmptyEditorClient FINAL : public EditorClient {
     WTF_MAKE_NONCOPYABLE(EmptyEditorClient); WTF_MAKE_FAST_ALLOCATED;
 public:
     EmptyEditorClient() { }
@@ -299,7 +294,7 @@
     virtual bool handleKeyboardEvent() OVERRIDE { return false; }
 };
 
-class EmptyContextMenuClient : public ContextMenuClient {
+class EmptyContextMenuClient FINAL : public ContextMenuClient {
     WTF_MAKE_NONCOPYABLE(EmptyContextMenuClient); WTF_MAKE_FAST_ALLOCATED;
 public:
     EmptyContextMenuClient() { }
@@ -308,7 +303,7 @@
     virtual void clearContextMenu() OVERRIDE { }
 };
 
-class EmptyDragClient : public DragClient {
+class EmptyDragClient FINAL : public DragClient {
     WTF_MAKE_NONCOPYABLE(EmptyDragClient); WTF_MAKE_FAST_ALLOCATED;
 public:
     EmptyDragClient() { }
@@ -317,7 +312,7 @@
     virtual void startDrag(DragImage*, const IntPoint&, const IntPoint&, Clipboard*, Frame*, bool) OVERRIDE { }
 };
 
-class EmptyInspectorClient : public InspectorClient {
+class EmptyInspectorClient FINAL : public InspectorClient {
     WTF_MAKE_NONCOPYABLE(EmptyInspectorClient); WTF_MAKE_FAST_ALLOCATED;
 public:
     EmptyInspectorClient() { }
@@ -327,13 +322,19 @@
     virtual void hideHighlight() OVERRIDE { }
 };
 
-class EmptyBackForwardClient : public BackForwardClient {
+class EmptyBackForwardClient FINAL : public BackForwardClient {
 public:
     virtual int backListCount() OVERRIDE { return 0; }
     virtual int forwardListCount() OVERRIDE { return 0; }
     virtual int backForwardListCount() OVERRIDE { return 0; }
 };
 
+class EmptyStorageClient FINAL : public StorageClient {
+public:
+    virtual PassOwnPtr<StorageNamespace> createSessionStorageNamespace() OVERRIDE;
+    virtual bool canAccessStorage(Frame*, StorageType) const OVERRIDE { return false; }
+};
+
 void fillWithEmptyClients(Page::PageClients&);
 
 }
diff --git a/Source/core/loader/FormSubmission.cpp b/Source/core/loader/FormSubmission.cpp
index 178a996..dea9f79 100644
--- a/Source/core/loader/FormSubmission.cpp
+++ b/Source/core/loader/FormSubmission.cpp
@@ -45,6 +45,7 @@
 #include "platform/network/FormData.h"
 #include "platform/network/FormDataBuilder.h"
 #include "wtf/CurrentTime.h"
+#include "wtf/text/StringBuilder.h"
 #include "wtf/text/TextEncoding.h"
 
 namespace WebCore {
@@ -73,11 +74,12 @@
     FormDataBuilder::encodeStringAsFormData(bodyData, body.utf8());
     body = String(bodyData.data(), bodyData.size()).replaceWithLiteral('+', "%20");
 
-    String query = url.query();
+    StringBuilder query;
+    query.append(url.query());
     if (!query.isEmpty())
         query.append('&');
     query.append(body);
-    url.setQuery(query);
+    url.setQuery(query.toString());
 }
 
 void FormSubmission::Attributes::parseAction(const String& action)
@@ -86,13 +88,13 @@
     m_action = stripLeadingAndTrailingHTMLSpaces(action);
 }
 
-String FormSubmission::Attributes::parseEncodingType(const String& type)
+AtomicString FormSubmission::Attributes::parseEncodingType(const String& type)
 {
     if (equalIgnoringCase(type, "multipart/form-data"))
-        return "multipart/form-data";
+        return AtomicString("multipart/form-data", AtomicString::ConstructFromLiteral);
     if (equalIgnoringCase(type, "text/plain"))
-        return "text/plain";
-    return "application/x-www-form-urlencoded";
+        return AtomicString("text/plain", AtomicString::ConstructFromLiteral);
+    return AtomicString("application/x-www-form-urlencoded", AtomicString::ConstructFromLiteral);
 }
 
 void FormSubmission::Attributes::updateEncodingType(const String& type)
@@ -140,7 +142,7 @@
     m_acceptCharset = other.m_acceptCharset;
 }
 
-inline FormSubmission::FormSubmission(Method method, const KURL& action, const String& target, const String& contentType, PassRefPtr<FormState> state, PassRefPtr<FormData> data, const String& boundary, PassRefPtr<Event> event)
+inline FormSubmission::FormSubmission(Method method, const KURL& action, const AtomicString& target, const AtomicString& contentType, PassRefPtr<FormState> state, PassRefPtr<FormData> data, const String& boundary, PassRefPtr<Event> event)
     : m_method(method)
     , m_action(action)
     , m_target(target)
@@ -175,7 +177,7 @@
     FormSubmission::Attributes copiedAttributes;
     copiedAttributes.copyFrom(attributes);
     if (submitButton) {
-        String attributeValue;
+        AtomicString attributeValue;
         if (!(attributeValue = submitButton->fastGetAttribute(formactionAttr)).isNull())
             copiedAttributes.parseAction(attributeValue);
         if (!(attributeValue = submitButton->fastGetAttribute(formenctypeAttr)).isNull())
@@ -193,12 +195,12 @@
     KURL actionURL = document.completeURL(copiedAttributes.action().isEmpty() ? document.url().string() : copiedAttributes.action());
     bool isMailtoForm = actionURL.protocolIs("mailto");
     bool isMultiPartForm = false;
-    String encodingType = copiedAttributes.encodingType();
+    AtomicString encodingType = copiedAttributes.encodingType();
 
     if (copiedAttributes.method() == PostMethod) {
         isMultiPartForm = copiedAttributes.isMultiPartForm();
         if (isMultiPartForm && isMailtoForm) {
-            encodingType = "application/x-www-form-urlencoded";
+            encodingType = AtomicString("application/x-www-form-urlencoded", AtomicString::ConstructFromLiteral);
             isMultiPartForm = false;
         }
     }
@@ -238,7 +240,7 @@
 
     formData->setIdentifier(generateFormDataIdentifier());
     formData->setContainsPasswordData(containsPasswordData);
-    String targetOrBaseTarget = copiedAttributes.target().isEmpty() ? document.baseTarget() : copiedAttributes.target();
+    AtomicString targetOrBaseTarget = copiedAttributes.target().isEmpty() ? document.baseTarget() : copiedAttributes.target();
     RefPtr<FormState> formState = FormState::create(form, formValues, &document, trigger);
     return adoptRef(new FormSubmission(copiedAttributes.method(), actionURL, targetOrBaseTarget, encodingType, formState.release(), formData.release(), boundary, event));
 }
@@ -258,7 +260,7 @@
     if (!m_target.isEmpty())
         frameRequest.setFrameName(m_target);
 
-    if (!m_referrer.isEmpty())
+    if (!m_referrer.referrer.isEmpty())
         frameRequest.resourceRequest().setHTTPReferrer(m_referrer);
 
     if (m_method == FormSubmission::PostMethod) {
@@ -273,7 +275,7 @@
     }
 
     frameRequest.resourceRequest().setURL(requestURL());
-    FrameLoader::addHTTPOriginIfNeeded(frameRequest.resourceRequest(), m_origin);
+    FrameLoader::addHTTPOriginIfNeeded(frameRequest.resourceRequest(), AtomicString(m_origin));
 }
 
 }
diff --git a/Source/core/loader/FormSubmission.h b/Source/core/loader/FormSubmission.h
index d53b2e6..65bdfe2 100644
--- a/Source/core/loader/FormSubmission.h
+++ b/Source/core/loader/FormSubmission.h
@@ -33,6 +33,7 @@
 
 #include "core/loader/FormState.h"
 #include "platform/weborigin/KURL.h"
+#include "platform/weborigin/Referrer.h"
 
 namespace WTF{
 class TextEncoding;
@@ -56,7 +57,7 @@
         Attributes()
             : m_method(GetMethod)
             , m_isMultiPartForm(false)
-            , m_encodingType("application/x-www-form-urlencoded")
+            , m_encodingType("application/x-www-form-urlencoded", AtomicString::ConstructFromLiteral)
         {
         }
 
@@ -68,11 +69,11 @@
         const String& action() const { return m_action; }
         void parseAction(const String&);
 
-        const String& target() const { return m_target; }
-        void setTarget(const String& target) { m_target = target; }
+        const AtomicString& target() const { return m_target; }
+        void setTarget(const AtomicString& target) { m_target = target; }
 
-        const String& encodingType() const { return m_encodingType; }
-        static String parseEncodingType(const String&);
+        const AtomicString& encodingType() const { return m_encodingType; }
+        static AtomicString parseEncodingType(const String&);
         void updateEncodingType(const String&);
         bool isMultiPartForm() const { return m_isMultiPartForm; }
 
@@ -86,8 +87,8 @@
         bool m_isMultiPartForm;
 
         String m_action;
-        String m_target;
-        String m_encodingType;
+        AtomicString m_target;
+        AtomicString m_encodingType;
         String m_acceptCharset;
     };
 
@@ -99,36 +100,36 @@
 
     Method method() const { return m_method; }
     const KURL& action() const { return m_action; }
-    const String& target() const { return m_target; }
-    void clearTarget() { m_target = String(); }
-    const String& contentType() const { return m_contentType; }
+    const AtomicString& target() const { return m_target; }
+    void clearTarget() { m_target = nullAtom; }
+    const AtomicString& contentType() const { return m_contentType; }
     FormState* state() const { return m_formState.get(); }
     FormData* data() const { return m_formData.get(); }
     const String boundary() const { return m_boundary; }
     Event* event() const { return m_event.get(); }
 
-    const String& referrer() const { return m_referrer; }
-    void setReferrer(const String& referrer) { m_referrer = referrer; }
+    const Referrer& referrer() const { return m_referrer; }
+    void setReferrer(const Referrer& referrer) { m_referrer = referrer; }
     const String& origin() const { return m_origin; }
     void setOrigin(const String& origin) { m_origin = origin; }
 
     const String& result() const { return m_result; }
 
 private:
-    FormSubmission(Method, const KURL& action, const String& target, const String& contentType, PassRefPtr<FormState>, PassRefPtr<FormData>, const String& boundary, PassRefPtr<Event>);
+    FormSubmission(Method, const KURL& action, const AtomicString& target, const AtomicString& contentType, PassRefPtr<FormState>, PassRefPtr<FormData>, const String& boundary, PassRefPtr<Event>);
     // FormSubmission for DialogMethod
     FormSubmission(const String& result);
 
     // FIXME: Hold an instance of Attributes instead of individual members.
     Method m_method;
     KURL m_action;
-    String m_target;
-    String m_contentType;
+    AtomicString m_target;
+    AtomicString m_contentType;
     RefPtr<FormState> m_formState;
     RefPtr<FormData> m_formData;
     String m_boundary;
     RefPtr<Event> m_event;
-    String m_referrer;
+    Referrer m_referrer;
     String m_origin;
     String m_result;
 };
diff --git a/Source/core/loader/FrameFetchContext.cpp b/Source/core/loader/FrameFetchContext.cpp
index ccbd9b6..c8ad61b 100644
--- a/Source/core/loader/FrameFetchContext.cpp
+++ b/Source/core/loader/FrameFetchContext.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/loader/FrameFetchContext.h"
 
+#include "core/dom/Document.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
@@ -38,11 +39,13 @@
 #include "core/loader/ProgressTracker.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/weborigin/SecurityPolicy.h"
 
 namespace WebCore {
 
+static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
+
 FrameFetchContext::FrameFetchContext(Frame* frame)
     : m_frame(frame)
 {
@@ -53,42 +56,77 @@
     FrameLoader::reportLocalLoadFailed(m_frame, url.elidedString());
 }
 
-void FrameFetchContext::addAdditionalRequestHeaders(Document& document, ResourceRequest& request, Resource::Type type)
+void FrameFetchContext::addAdditionalRequestHeaders(Document* document, ResourceRequest& request, FetchResourceType type)
 {
-    bool isMainResource = type == Resource::MainResource;
-
-    FrameLoader& frameLoader = m_frame->loader();
-
+    bool isMainResource = type == FetchMainResource;
     if (!isMainResource) {
         String outgoingReferrer;
         String outgoingOrigin;
         if (request.httpReferrer().isNull()) {
-            outgoingReferrer = frameLoader.outgoingReferrer();
-            outgoingOrigin = frameLoader.outgoingOrigin();
+            outgoingReferrer = document->outgoingReferrer();
+            outgoingOrigin = document->outgoingOrigin();
         } else {
             outgoingReferrer = request.httpReferrer();
             outgoingOrigin = SecurityOrigin::createFromString(outgoingReferrer)->toString();
         }
 
-        outgoingReferrer = SecurityPolicy::generateReferrerHeader(document.referrerPolicy(), request.url(), outgoingReferrer);
+        outgoingReferrer = SecurityPolicy::generateReferrerHeader(document->referrerPolicy(), request.url(), outgoingReferrer);
         if (outgoingReferrer.isEmpty())
             request.clearHTTPReferrer();
         else if (!request.httpReferrer())
-            request.setHTTPReferrer(outgoingReferrer);
+            request.setHTTPReferrer(Referrer(outgoingReferrer, document->referrerPolicy()));
 
-        FrameLoader::addHTTPOriginIfNeeded(request, outgoingOrigin);
+        FrameLoader::addHTTPOriginIfNeeded(request, AtomicString(outgoingOrigin));
     }
 
-    frameLoader.addExtraFieldsToRequest(request);
+    if (isMainResource && m_frame->isMainFrame())
+        request.setFirstPartyForCookies(request.url());
+    else
+        request.setFirstPartyForCookies(m_frame->tree().top()->document()->firstPartyForCookies());
+
+    // The remaining modifications are only necessary for HTTP and HTTPS.
+    if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
+        return;
+
+    m_frame->loader().applyUserAgent(request);
+
+    if (request.cachePolicy() == ReloadIgnoringCacheData) {
+        if (m_frame->loader().loadType() == FrameLoadTypeReload) {
+            request.setHTTPHeaderField("Cache-Control", "max-age=0");
+        } else if (m_frame->loader().loadType() == FrameLoadTypeReloadFromOrigin) {
+            request.setHTTPHeaderField("Cache-Control", "no-cache");
+            request.setHTTPHeaderField("Pragma", "no-cache");
+        }
+    }
+
+    if (isMainResource)
+        request.setHTTPAccept(defaultAcceptHeader);
+
+    // Default to sending an empty Origin header if one hasn't been set yet.
+    FrameLoader::addHTTPOriginIfNeeded(request, nullAtom);
 }
 
-CachePolicy FrameFetchContext::cachePolicy(Resource::Type type) const
+CachePolicy FrameFetchContext::cachePolicy(Document* document) const
 {
-    if (type != Resource::MainResource)
-        return m_frame->loader().subresourceCachePolicy();
+    if (document && document->loadEventFinished())
+        return CachePolicyVerify;
 
-    if (m_frame->loader().loadType() == FrameLoadTypeReloadFromOrigin || m_frame->loader().loadType() == FrameLoadTypeReload)
+    FrameLoadType loadType = m_frame->loader().loadType();
+    if (loadType == FrameLoadTypeReloadFromOrigin)
         return CachePolicyReload;
+
+    if (Frame* parentFrame = m_frame->tree().parent()) {
+        CachePolicy parentCachePolicy = parentFrame->loader().fetchContext().cachePolicy(parentFrame->document());
+        if (parentCachePolicy != CachePolicyVerify)
+            return parentCachePolicy;
+    }
+
+    if (loadType == FrameLoadTypeReload)
+        return CachePolicyRevalidate;
+
+    DocumentLoader* loader = document ? document->loader() : 0;
+    if (loader && loader->request().cachePolicy() == ReturnCacheDataElseLoad)
+        return CachePolicyHistoryBuffer;
     return CachePolicyVerify;
 
 }
@@ -99,7 +137,7 @@
 // cannot see imported documents.
 inline DocumentLoader* FrameFetchContext::ensureLoader(DocumentLoader* loader)
 {
-    return loader ? loader : m_frame->loader().activeDocumentLoader();
+    return loader ? loader : m_frame->loader().documentLoader();
 }
 
 void FrameFetchContext::dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority loadPriority)
@@ -141,20 +179,20 @@
     InspectorInstrumentation::didReceiveData(m_frame, identifier, 0, dataLength, encodedDataLength);
 }
 
-void FrameFetchContext::dispatchDidFinishLoading(DocumentLoader* loader, unsigned long identifier, double finishTime)
+void FrameFetchContext::dispatchDidFinishLoading(DocumentLoader* loader, unsigned long identifier, double finishTime, int64_t encodedDataLength)
 {
     if (Page* page = m_frame->page())
         page->progress().completeProgress(identifier);
     m_frame->loader().client()->dispatchDidFinishLoading(loader, identifier);
 
-    InspectorInstrumentation::didFinishLoading(m_frame, identifier, ensureLoader(loader), finishTime);
+    InspectorInstrumentation::didFinishLoading(m_frame, identifier, ensureLoader(loader), finishTime, encodedDataLength);
 }
 
 void FrameFetchContext::dispatchDidFail(DocumentLoader* loader, unsigned long identifier, const ResourceError& error)
 {
     if (Page* page = m_frame->page())
         page->progress().completeProgress(identifier);
-    InspectorInstrumentation::didFailLoading(m_frame, identifier, ensureLoader(loader), error);
+    InspectorInstrumentation::didFailLoading(m_frame, identifier, error);
 }
 
 void FrameFetchContext::sendRemainingDelegateMessages(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& response, int dataLength)
@@ -165,7 +203,7 @@
     if (dataLength > 0)
         dispatchDidReceiveData(ensureLoader(loader), identifier, 0, dataLength, 0);
 
-    dispatchDidFinishLoading(ensureLoader(loader), identifier, 0);
+    dispatchDidFinishLoading(ensureLoader(loader), identifier, 0, 0);
 }
 
 } // namespace WebCore
diff --git a/Source/core/loader/FrameFetchContext.h b/Source/core/loader/FrameFetchContext.h
index 2c66a17..8f6e554 100644
--- a/Source/core/loader/FrameFetchContext.h
+++ b/Source/core/loader/FrameFetchContext.h
@@ -37,6 +37,7 @@
 
 namespace WebCore {
 
+class Document;
 class DocumentLoader;
 class Frame;
 class Page;
@@ -45,20 +46,20 @@
 class ResourceResponse;
 class ResourceRequest;
 
-class FrameFetchContext  : public FetchContext {
+class FrameFetchContext FINAL : public FetchContext {
 public:
     static PassOwnPtr<FrameFetchContext> create(Frame* frame) { return adoptPtr(new FrameFetchContext(frame)); }
 
     virtual void reportLocalLoadFailed(const KURL&) OVERRIDE;
-    virtual void addAdditionalRequestHeaders(Document&, ResourceRequest&, Resource::Type) OVERRIDE;
-    virtual CachePolicy cachePolicy(Resource::Type) const OVERRIDE;
-    virtual void dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority);
+    virtual void addAdditionalRequestHeaders(Document*, ResourceRequest&, FetchResourceType) OVERRIDE;
+    virtual CachePolicy cachePolicy(Document*) const OVERRIDE;
+    virtual void dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority) OVERRIDE;
     virtual void dispatchWillSendRequest(DocumentLoader*, unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& = FetchInitiatorInfo()) OVERRIDE;
     virtual void dispatchDidLoadResourceFromMemoryCache(const ResourceRequest&, const ResourceResponse&) OVERRIDE;
     virtual void dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse&, ResourceLoader* = 0) OVERRIDE;
     virtual void dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength) OVERRIDE;
     virtual void dispatchDidDownloadData(DocumentLoader*, unsigned long identifier, int dataLength, int encodedDataLength)  OVERRIDE;
-    virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier, double finishTime) OVERRIDE;
+    virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier, double finishTime, int64_t encodedDataLength) OVERRIDE;
     virtual void dispatchDidFail(DocumentLoader*, unsigned long identifier, const ResourceError&) OVERRIDE;
     virtual void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, int dataLength) OVERRIDE;
 
diff --git a/Source/core/loader/FrameLoadRequest.h b/Source/core/loader/FrameLoadRequest.h
index fefdd1f..09d992a 100644
--- a/Source/core/loader/FrameLoadRequest.h
+++ b/Source/core/loader/FrameLoadRequest.h
@@ -26,28 +26,28 @@
 #ifndef FrameLoadRequest_h
 #define FrameLoadRequest_h
 
+#include "core/dom/Document.h"
 #include "core/events/Event.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/loader/FrameLoaderTypes.h"
 #include "core/loader/SubstituteData.h"
 #include "platform/network/ResourceRequest.h"
-#include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
 class Frame;
 
 struct FrameLoadRequest {
 public:
-    explicit FrameLoadRequest(SecurityOrigin* requester)
-        : m_requester(requester)
+    explicit FrameLoadRequest(Document* originDocument)
+        : m_originDocument(originDocument)
         , m_lockBackForwardList(false)
         , m_clientRedirect(NotClientRedirect)
         , m_shouldSendReferrer(MaybeSendReferrer)
     {
     }
 
-    FrameLoadRequest(SecurityOrigin* requester, const ResourceRequest& resourceRequest)
-        : m_requester(requester)
+    FrameLoadRequest(Document* originDocument, const ResourceRequest& resourceRequest)
+        : m_originDocument(originDocument)
         , m_resourceRequest(resourceRequest)
         , m_lockBackForwardList(false)
         , m_clientRedirect(NotClientRedirect)
@@ -55,8 +55,8 @@
     {
     }
 
-    FrameLoadRequest(SecurityOrigin* requester, const ResourceRequest& resourceRequest, const String& frameName)
-        : m_requester(requester)
+    FrameLoadRequest(Document* originDocument, const ResourceRequest& resourceRequest, const AtomicString& frameName)
+        : m_originDocument(originDocument)
         , m_resourceRequest(resourceRequest)
         , m_frameName(frameName)
         , m_lockBackForwardList(false)
@@ -65,8 +65,8 @@
     {
     }
 
-    FrameLoadRequest(SecurityOrigin* requester, const ResourceRequest& resourceRequest, const SubstituteData& substituteData)
-        : m_requester(requester)
+    FrameLoadRequest(Document* originDocument, const ResourceRequest& resourceRequest, const SubstituteData& substituteData)
+        : m_originDocument(originDocument)
         , m_resourceRequest(resourceRequest)
         , m_substituteData(substituteData)
         , m_lockBackForwardList(false)
@@ -75,13 +75,13 @@
     {
     }
 
-    const SecurityOrigin* requester() const { return m_requester.get(); }
+    Document* originDocument() const { return m_originDocument.get(); }
 
     ResourceRequest& resourceRequest() { return m_resourceRequest; }
     const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
 
-    const String& frameName() const { return m_frameName; }
-    void setFrameName(const String& frameName) { m_frameName = frameName; }
+    const AtomicString& frameName() const { return m_frameName; }
+    void setFrameName(const AtomicString& frameName) { m_frameName = frameName; }
 
     const SubstituteData& substituteData() const { return m_substituteData; }
 
@@ -101,9 +101,9 @@
     void setShouldSendReferrer(ShouldSendReferrer shouldSendReferrer) { m_shouldSendReferrer = shouldSendReferrer; }
 
 private:
-    RefPtr<SecurityOrigin> m_requester;
+    RefPtr<Document> m_originDocument;
     ResourceRequest m_resourceRequest;
-    String m_frameName;
+    AtomicString m_frameName;
     SubstituteData m_substituteData;
     bool m_lockBackForwardList;
     ClientRedirectPolicy m_clientRedirect;
diff --git a/Source/core/loader/FrameLoader.cpp b/Source/core/loader/FrameLoader.cpp
index 80ccf05..6887bdd 100644
--- a/Source/core/loader/FrameLoader.cpp
+++ b/Source/core/loader/FrameLoader.cpp
@@ -76,7 +76,7 @@
 #include "core/page/EventHandler.h"
 #include "core/page/FrameTree.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/page/WindowFeatures.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/xml/parser/XMLDocumentParser.h"
@@ -97,8 +97,6 @@
 
 using namespace HTMLNames;
 
-static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
-
 bool isBackForwardLoadType(FrameLoadType type)
 {
     return type == FrameLoadTypeBackForward;
@@ -145,6 +143,7 @@
     : m_frame(frame)
     , m_client(client)
     , m_mixedContentChecker(frame)
+    , m_progressTracker(FrameProgressTracker::create(m_frame))
     , m_state(FrameStateProvisional)
     , m_loadType(FrameLoadTypeStandard)
     , m_fetchContext(FrameFetchContext::create(frame))
@@ -161,24 +160,17 @@
 
 FrameLoader::~FrameLoader()
 {
-    setOpener(0);
-
     HashSet<Frame*>::iterator end = m_openedFrames.end();
     for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
         (*it)->loader().m_opener = 0;
-
-    m_client->frameLoaderDestroyed();
 }
 
 void FrameLoader::init()
 {
-    // This somewhat odd set of steps gives the frame an initial empty document.
-    m_provisionalDocumentLoader = m_client->createDocumentLoader(ResourceRequest(KURL(ParsedURLString, emptyString())), SubstituteData());
-    m_provisionalDocumentLoader->setFrame(m_frame);
+    m_provisionalDocumentLoader = m_client->createDocumentLoader(m_frame, ResourceRequest(KURL(ParsedURLString, emptyString())), SubstituteData());
     m_provisionalDocumentLoader->startLoadingMainResource();
     m_frame->document()->cancelParsing();
     m_stateMachine.advanceTo(FrameLoaderStateMachine::DisplayingInitialEmptyDocument);
-    m_progressTracker = FrameProgressTracker::create(m_frame);
 }
 
 void FrameLoader::setDefersLoading(bool defers)
@@ -246,11 +238,7 @@
 
 bool FrameLoader::closeURL()
 {
-    // This is done when a back/forward navigation begins (and the current item
-    // changes) in loadHistoryItem(). Saving now will save the state will save
-    // to the wrong item if the navigation is back/forward.
-    if (m_loadType != FrameLoadTypeBackForward)
-        saveDocumentAndScrollState();
+    saveDocumentAndScrollState();
 
     // Should only send the pagehide event here if the current document exists.
     if (m_frame->document())
@@ -277,7 +265,7 @@
     m_frame->navigationScheduler().cancel();
 }
 
-void FrameLoader::clear(ClearOptions options)
+void FrameLoader::clear()
 {
     if (m_stateMachine.creatingInitialEmptyDocument())
         return;
@@ -287,27 +275,11 @@
     m_frame->document()->prepareForDestruction();
     m_frame->document()->removeFocusedElementOfSubtree(m_frame->document());
 
-    // Do this after detaching the document so that the unload event works.
-    if (options & ClearWindowProperties) {
-        InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame->domWindow());
-        m_frame->domWindow()->reset();
-        m_frame->script().clearWindowShell();
-    }
-
     m_frame->selection().prepareForDestruction();
     m_frame->eventHandler().clear();
     if (m_frame->view())
         m_frame->view()->clear();
 
-    if (options & ClearWindowObject) {
-        // Do not drop the DOMWindow (and Document) before the ScriptController and view are cleared
-        // as some destructors might still try to access the document.
-        m_frame->setDOMWindow(0);
-    }
-
-    if (options & ClearScriptObjects)
-        m_frame->script().clearScriptObjects();
-
     m_frame->script().enableEval();
 
     m_frame->navigationScheduler().clear();
@@ -319,49 +291,74 @@
         m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
 }
 
-void FrameLoader::setHistoryItemStateForCommit(HistoryItemPolicy historyItemPolicy)
+void FrameLoader::setHistoryItemStateForCommit(HistoryCommitType historyCommitType, bool isPushOrReplaceState, PassRefPtr<SerializedScriptValue> stateObject)
 {
-    if (!m_currentItem || historyItemPolicy == CreateNewHistoryItem || m_currentItem->url() != m_documentLoader->url()) {
-        if (!m_currentItem || historyItemPolicy == CreateNewHistoryItem)
-            m_currentItem = HistoryItem::create();
-        else
-            m_currentItem->reset();
-        const KURL& unreachableURL = m_documentLoader->unreachableURL();
-        const KURL& url = unreachableURL.isEmpty() ? m_documentLoader->requestURL() : unreachableURL;
-        const KURL& originalURL = unreachableURL.isEmpty() ? m_documentLoader->originalURL() : unreachableURL;
-        m_currentItem->setURL(url);
-        m_currentItem->setTarget(m_frame->tree().uniqueName());
-        m_currentItem->setTargetFrameID(m_frame->frameID());
-        m_currentItem->setOriginalURLString(originalURL.string());
+    if (m_provisionalItem)
+        m_currentItem = m_provisionalItem.release();
+    if (!m_currentItem || historyCommitType == StandardCommit)
+        m_currentItem = HistoryItem::create();
+    else if (!isPushOrReplaceState && m_documentLoader->url() != m_currentItem->url())
+        m_currentItem->generateNewSequenceNumbers();
+    const KURL& unreachableURL = m_documentLoader->unreachableURL();
+    const KURL& url = unreachableURL.isEmpty() ? m_documentLoader->url() : unreachableURL;
+    const KURL& originalURL = unreachableURL.isEmpty() ? m_documentLoader->originalURL() : unreachableURL;
+    m_currentItem->setURL(url);
+    m_currentItem->setTarget(m_frame->tree().uniqueName());
+    m_currentItem->setTargetFrameID(m_frame->frameID());
+    m_currentItem->setOriginalURLString(originalURL.string());
+    if (isPushOrReplaceState)
+        m_currentItem->setStateObject(stateObject);
+    m_currentItem->setReferrer(Referrer(m_documentLoader->request().httpReferrer(), m_documentLoader->request().referrerPolicy()));
+    m_currentItem->setFormInfoFromRequest(isPushOrReplaceState ? ResourceRequest() : m_documentLoader->request());
+}
+
+static HistoryCommitType loadTypeToCommitType(FrameLoadType type, bool isValidHistoryURL)
+{
+    switch (type) {
+    case FrameLoadTypeStandard:
+        return isValidHistoryURL ? StandardCommit : HistoryInertCommit;
+    case FrameLoadTypeInitialInChildFrame:
+        return InitialCommitInChildFrame;
+    case FrameLoadTypeBackForward:
+        return BackForwardCommit;
+    default:
+        break;
     }
-    m_currentItem->setFormInfoFromRequest(m_documentLoader->request());
+    return HistoryInertCommit;
 }
 
 void FrameLoader::receivedFirstData()
 {
     if (m_stateMachine.creatingInitialEmptyDocument())
         return;
-    NavigationHistoryPolicy navigationHistoryPolicy = NavigationReusedHistoryEntry;
-    if (m_loadType == FrameLoadTypeStandard && m_documentLoader->isURLValidForNewHistoryEntry())
-        navigationHistoryPolicy = NavigationCreatedHistoryEntry;
-    HistoryItemPolicy historyItemPolicy = DoNotCreateNewHistoryItem;
-    if (m_loadType == FrameLoadTypeInitialInChildFrame || navigationHistoryPolicy == NavigationCreatedHistoryEntry)
-        historyItemPolicy = CreateNewHistoryItem;
-    setHistoryItemStateForCommit(historyItemPolicy);
 
-    if (!m_stateMachine.committedMultipleRealLoads() && navigationHistoryPolicy == NavigationCreatedHistoryEntry)
+    HistoryCommitType historyCommitType = loadTypeToCommitType(m_loadType, m_documentLoader->isURLValidForNewHistoryEntry());
+    setHistoryItemStateForCommit(historyCommitType);
+
+    if (!m_stateMachine.committedMultipleRealLoads() && m_loadType == FrameLoadTypeStandard)
         m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedMultipleRealLoads);
 
-    m_client->dispatchDidCommitLoad(m_frame, m_currentItem.get(), navigationHistoryPolicy);
+    m_client->dispatchDidCommitLoad(m_frame, m_currentItem.get(), historyCommitType);
 
     InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
     m_frame->page()->didCommitLoad(m_frame);
     dispatchDidClearWindowObjectsInAllWorlds();
 }
 
-void FrameLoader::setOutgoingReferrer(const KURL& url)
+static void didFailContentSecurityPolicyCheck(FrameLoader* loader)
 {
-    m_outgoingReferrer = url.strippedForUseAsReferrer();
+    // load event and stopAllLoaders can detach the Frame, so protect it.
+    RefPtr<Frame> frame(loader->frame());
+
+    // Move the page to a unique origin, and cancel the load.
+    frame->document()->enforceSandboxFlags(SandboxOrigin);
+    loader->stopAllLoaders();
+
+    // Fire a load event, as timing attacks would otherwise reveal that the
+    // frame was blocked. This way, it looks like every other cross-origin
+    // page.
+    if (HTMLFrameOwnerElement* ownerElement = frame->ownerElement())
+        ownerElement->dispatchEvent(Event::create(EventTypeNames::load));
 }
 
 void FrameLoader::didBeginDocument(bool dispatch)
@@ -369,17 +366,22 @@
     m_isComplete = false;
     m_frame->document()->setReadyState(Document::Loading);
 
-    if (m_currentItem && m_loadType == FrameLoadTypeBackForward)
-        m_frame->domWindow()->statePopped(m_currentItem->stateObject());
+    if (m_provisionalItem && m_loadType == FrameLoadTypeBackForward)
+        m_frame->domWindow()->statePopped(m_provisionalItem->stateObject());
 
     if (dispatch)
         dispatchDidClearWindowObjectsInAllWorlds();
 
     m_frame->document()->initContentSecurityPolicy(m_documentLoader ? ContentSecurityPolicyResponseHeaders(m_documentLoader->response()) : ContentSecurityPolicyResponseHeaders());
 
+    if (!m_frame->document()->contentSecurityPolicy()->allowAncestors(m_frame)) {
+        didFailContentSecurityPolicyCheck(this);
+        return;
+    }
+
     Settings* settings = m_frame->document()->settings();
     if (settings) {
-        m_frame->document()->fetcher()->setImagesEnabled(settings->areImagesEnabled());
+        m_frame->document()->fetcher()->setImagesEnabled(settings->imagesEnabled());
         m_frame->document()->fetcher()->setAutoLoadImages(settings->loadsImagesAutomatically());
     }
 
@@ -398,8 +400,8 @@
         }
     }
 
-    if (m_currentItem && m_loadType == FrameLoadTypeBackForward)
-        m_frame->document()->setStateForNewFormElements(m_currentItem->documentState());
+    if (m_provisionalItem && m_loadType == FrameLoadTypeBackForward)
+        m_frame->document()->setStateForNewFormElements(m_provisionalItem->documentState());
 }
 
 void FrameLoader::finishedParsing()
@@ -412,7 +414,8 @@
     // Null-checking the FrameView indicates whether or not we're in the destructor.
     RefPtr<Frame> protector = m_frame->view() ? m_frame : 0;
 
-    m_client->dispatchDidFinishDocumentLoad();
+    if (m_client)
+        m_client->dispatchDidFinishDocumentLoad();
 
     checkCompleted();
 
@@ -519,25 +522,6 @@
     startCheckCompleteTimer();
 }
 
-String FrameLoader::outgoingReferrer() const
-{
-    // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
-    // for why we walk the parent chain for srcdoc documents.
-    Frame* frame = m_frame;
-    while (frame->document()->isSrcdocDocument()) {
-        frame = frame->tree().parent();
-        // Srcdoc documents cannot be top-level documents, by definition,
-        // because they need to be contained in iframes with the srcdoc.
-        ASSERT(frame);
-    }
-    return frame->loader().m_outgoingReferrer;
-}
-
-String FrameLoader::outgoingOrigin() const
-{
-    return m_frame->document()->securityOrigin()->toString();
-}
-
 Frame* FrameLoader::opener()
 {
     return m_opener;
@@ -561,7 +545,7 @@
 bool FrameLoader::allowPlugins(ReasonForCallingAllowPlugins reason)
 {
     Settings* settings = m_frame->settings();
-    bool allowed = m_client->allowPlugins(settings && settings->arePluginsEnabled());
+    bool allowed = m_client->allowPlugins(settings && settings->pluginsEnabled());
     if (!allowed && reason == AboutToInstantiatePlugin)
         m_client->didNotAllowPlugins();
     return allowed;
@@ -571,40 +555,35 @@
 {
     // Update the data source's request with the new URL to fake the URL change
     m_frame->document()->setURL(newURL);
-    setOutgoingReferrer(newURL);
     documentLoader()->updateForSameDocumentNavigation(newURL);
 
     // Generate start and stop notifications only when loader is completed so that we
     // don't fire them for fragment redirection that happens in window.onload handler.
     // See https://bugs.webkit.org/show_bug.cgi?id=31838
     if (m_frame->document()->loadEventFinished())
-        m_client->postProgressStartedNotification();
+        m_client->postProgressStartedNotification(NavigationWithinSameDocument);
 
-    NavigationHistoryPolicy navigationHistoryPolicy = NavigationReusedHistoryEntry;
-    if (updateBackForwardList == UpdateBackForwardList || (sameDocumentNavigationSource == SameDocumentNavigationPushState && m_currentItem)) {
-        navigationHistoryPolicy = NavigationCreatedHistoryEntry;
-        setHistoryItemStateForCommit(CreateNewHistoryItem);
-    }
-    m_client->dispatchDidNavigateWithinPage(navigationHistoryPolicy, m_currentItem.get());
+    HistoryCommitType historyCommitType = updateBackForwardList == UpdateBackForwardList && m_currentItem ? StandardCommit : HistoryInertCommit;
+    setHistoryItemStateForCommit(historyCommitType, sameDocumentNavigationSource == SameDocumentNavigationHistoryApi, data);
+    m_client->dispatchDidNavigateWithinPage(m_currentItem.get(), historyCommitType);
     m_client->dispatchDidReceiveTitle(m_frame->document()->title());
-
-    if (m_currentItem) {
-        m_currentItem->setURL(newURL);
-        if (sameDocumentNavigationSource != SameDocumentNavigationDefault) {
-            m_currentItem->setStateObject(data);
-            m_currentItem->setFormData(0);
-            m_currentItem->setFormContentType(nullAtom);
-        }
-    }
-
     if (m_frame->document()->loadEventFinished())
         m_client->postProgressFinishedNotification();
 }
 
-void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation, ClientRedirectPolicy clientRedirect)
+void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, UpdateBackForwardListPolicy updateBackForwardList, ClientRedirectPolicy clientRedirect)
 {
     // If we have a state object, we cannot also be a new navigation.
-    ASSERT(!stateObject || (stateObject && !isNewNavigation));
+    ASSERT(!stateObject || updateBackForwardList == DoNotUpdateBackForwardList);
+
+    // If we have a provisional request for a different document, a fragment scroll should cancel it.
+    if (m_provisionalDocumentLoader) {
+        m_provisionalDocumentLoader->stopLoading();
+        if (m_provisionalDocumentLoader)
+            m_provisionalDocumentLoader->detachFromFrame();
+        m_provisionalDocumentLoader = 0;
+    }
+    saveDocumentAndScrollState();
 
     KURL oldURL = m_frame->document()->url();
     // If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
@@ -613,9 +592,8 @@
         m_frame->eventHandler().stopAutoscroll();
         m_frame->domWindow()->enqueueHashchangeEvent(oldURL, url);
     }
-    m_documentLoader->setIsClientRedirect((clientRedirect == ClientRedirect && !isNewNavigation) || !UserGestureIndicator::processingUserGesture());
-    m_documentLoader->setReplacesCurrentHistoryItem(!isNewNavigation);
-    UpdateBackForwardListPolicy updateBackForwardList = isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject ? UpdateBackForwardList : DoNotUpdateBackForwardList;
+    m_documentLoader->setIsClientRedirect(clientRedirect == ClientRedirect);
+    m_documentLoader->setReplacesCurrentHistoryItem(updateBackForwardList == DoNotUpdateBackForwardList);
     updateForSameDocumentNavigation(url, SameDocumentNavigationDefault, 0, updateBackForwardList);
 
     // It's important to model this as a load that starts and immediately finishes.
@@ -652,21 +630,24 @@
         frame->loader().m_isComplete = false;
 }
 
-void FrameLoader::setReferrerForFrameRequest(ResourceRequest& request, ShouldSendReferrer shouldSendReferrer)
+void FrameLoader::setReferrerForFrameRequest(ResourceRequest& request, ShouldSendReferrer shouldSendReferrer, Document* originDocument)
 {
     if (shouldSendReferrer == NeverSendReferrer) {
         request.clearHTTPReferrer();
         return;
     }
 
+    // Always use the initiating document to generate the referrer.
+    // We need to generateReferrerHeader(), because we might not have enforced ReferrerPolicy or https->http
+    // referrer suppression yet.
     String argsReferrer(request.httpReferrer());
     if (argsReferrer.isEmpty())
-        argsReferrer = outgoingReferrer();
-    String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), request.url(), argsReferrer);
+        argsReferrer = originDocument->outgoingReferrer();
+    String referrer = SecurityPolicy::generateReferrerHeader(originDocument->referrerPolicy(), request.url(), argsReferrer);
 
-    request.setHTTPReferrer(referrer);
+    request.setHTTPReferrer(Referrer(referrer, originDocument->referrerPolicy()));
     RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
-    addHTTPOriginIfNeeded(request, referrerOrigin->toString());
+    addHTTPOriginIfNeeded(request, referrerOrigin->toAtomicString());
 }
 
 bool FrameLoader::isScriptTriggeredFormSubmissionInChildFrame(const FrameLoadRequest& request) const
@@ -687,9 +668,11 @@
         return FrameLoadTypeStandard;
     if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
         return FrameLoadTypeReload;
+    if (m_provisionalDocumentLoader && request.substituteData().failingURL() == m_provisionalDocumentLoader->url() && m_loadType == FrameLoadTypeBackForward)
+        return FrameLoadTypeBackForward;
     if (request.lockBackForwardList() || isScriptTriggeredFormSubmissionInChildFrame(request))
         return FrameLoadTypeRedirectWithLockedBackForwardList;
-    if (!request.requester() && shouldTreatURLAsSameAsCurrent(request.resourceRequest().url()))
+    if (!request.originDocument() && shouldTreatURLAsSameAsCurrent(request.resourceRequest().url()))
         return FrameLoadTypeSame;
     if (shouldTreatURLAsSameAsCurrent(request.substituteData().failingURL()) && m_loadType == FrameLoadTypeReload)
         return FrameLoadTypeReload;
@@ -698,26 +681,23 @@
 
 bool FrameLoader::prepareRequestForThisFrame(FrameLoadRequest& request)
 {
-    // If no SecurityOrigin was specified, skip security checks and assume the caller has fully initialized the FrameLoadRequest.
-    if (!request.requester())
+    // If no origin Document* was specified, skip security checks and assume the caller has fully initialized the FrameLoadRequest.
+    if (!request.originDocument())
         return true;
 
     KURL url = request.resourceRequest().url();
     if (m_frame->script().executeScriptIfJavaScriptURL(url))
         return false;
 
-    if (!request.requester()->canDisplay(url)) {
+    if (!request.originDocument()->securityOrigin()->canDisplay(url)) {
         reportLocalLoadFailed(m_frame, url.elidedString());
         return false;
     }
 
-    if (request.requester() && !request.formState() && request.frameName().isEmpty())
+    if (!request.formState() && request.frameName().isEmpty())
         request.setFrameName(m_frame->document()->baseTarget());
 
-    // If the requesting SecurityOrigin is not this Frame's SecurityOrigin, the request was initiated by a different frame that should
-    // have already set the referrer.
-    if (request.requester() == m_frame->document()->securityOrigin())
-        setReferrerForFrameRequest(request.resourceRequest(), request.shouldSendReferrer());
+    setReferrerForFrameRequest(request.resourceRequest(), request.shouldSendReferrer(), request.originDocument());
     return true;
 }
 
@@ -735,7 +715,7 @@
     if (!prepareRequestForThisFrame(request))
         return;
 
-    RefPtr<Frame> targetFrame = request.formState() ? 0 : findFrameForNavigation(request.frameName(), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
+    RefPtr<Frame> targetFrame = request.formState() ? 0 : findFrameForNavigation(AtomicString(request.frameName()), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
     if (targetFrame && targetFrame != m_frame) {
         request.setFrameName("_self");
         targetFrame->loader().load(request);
@@ -754,11 +734,13 @@
         return;
     }
 
-    if (shouldPerformFragmentNavigation(request.formState(), request.resourceRequest().httpMethod(), newLoadType, request.resourceRequest().url())) {
-        checkNavigationPolicyAndContinueFragmentScroll(action, newLoadType != FrameLoadTypeRedirectWithLockedBackForwardList, request.clientRedirect());
+    const KURL& url = request.resourceRequest().url();
+    if (shouldPerformFragmentNavigation(request.formState(), request.resourceRequest().httpMethod(), newLoadType, url)) {
+        m_documentLoader->setTriggeringAction(action);
+        loadInSameDocument(url, 0, newLoadType == FrameLoadTypeStandard ? UpdateBackForwardList : DoNotUpdateBackForwardList, request.clientRedirect());
         return;
     }
-    bool sameURL = shouldTreatURLAsSameAsCurrent(request.resourceRequest().url());
+    bool sameURL = shouldTreatURLAsSameAsCurrent(url);
     loadWithNavigationAction(action, newLoadType, request.formState(), request.substituteData(), request.clientRedirect());
     // Example of this case are sites that reload the same URL with a different cookie
     // driving the generated content, or a master frame with links that drive a target
@@ -786,24 +768,34 @@
     frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Not allowed to load local resource: " + url);
 }
 
+static ResourceRequest requestFromHistoryItem(HistoryItem* item, ResourceRequestCachePolicy cachePolicy)
+{
+    RefPtr<FormData> formData = item->formData();
+    ResourceRequest request(item->url(), item->referrer());
+    request.setCachePolicy(cachePolicy);
+    if (formData) {
+        request.setHTTPMethod("POST");
+        request.setHTTPBody(formData);
+        request.setHTTPContentType(item->formContentType());
+        RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer().referrer);
+        FrameLoader::addHTTPOriginIfNeeded(request, securityOrigin->toAtomicString());
+    }
+    return request;
+}
+
 void FrameLoader::reload(ReloadPolicy reloadPolicy, const KURL& overrideURL, const AtomicString& overrideEncoding)
 {
-    DocumentLoader* documentLoader = activeDocumentLoader();
-    if (!documentLoader)
+    if (!m_currentItem)
         return;
 
-    ResourceRequest request = documentLoader->request();
-    // FIXME: We need to reset cache policy to prevent it from being incorrectly propagted to the reload.
-    // Do we need to propagate anything other than the url?
-    request.setCachePolicy(UseProtocolCachePolicy);
-    if (!overrideURL.isEmpty())
+    ResourceRequest request = requestFromHistoryItem(m_currentItem.get(), ReloadIgnoringCacheData);
+    if (!overrideURL.isEmpty()) {
         request.setURL(overrideURL);
-    else if (!documentLoader->unreachableURL().isEmpty())
-        request.setURL(documentLoader->unreachableURL());
+        request.clearHTTPReferrer();
+    }
 
     FrameLoadType type = reloadPolicy == EndToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload;
-    NavigationAction action(request, type, request.httpMethod() == "POST");
-    loadWithNavigationAction(action, type, 0, SubstituteData(), NotClientRedirect, overrideEncoding);
+    loadWithNavigationAction(NavigationAction(request, type), type, 0, SubstituteData(), NotClientRedirect, overrideEncoding);
 }
 
 void FrameLoader::stopAllLoaders()
@@ -836,14 +828,10 @@
 
     m_inStopAllLoaders = false;
 
-    m_client->didStopAllLoaders();
-}
-
-DocumentLoader* FrameLoader::activeDocumentLoader() const
-{
-    if (m_state == FrameStateProvisional)
-        return m_provisionalDocumentLoader.get();
-    return m_documentLoader.get();
+    // detachFromParent() can be called multiple times on same Frame, which
+    // means we may no longer have a FrameLoaderClient to talk to.
+    if (m_client)
+        m_client->didStopAllLoaders();
 }
 
 void FrameLoader::didAccessInitialDocument()
@@ -871,10 +859,9 @@
 
 bool FrameLoader::isLoading() const
 {
-    DocumentLoader* docLoader = activeDocumentLoader();
-    if (!docLoader)
-        return false;
-    return docLoader->isLoading();
+    if (m_provisionalDocumentLoader)
+        return true;
+    return m_documentLoader && m_documentLoader->isLoading();
 }
 
 void FrameLoader::commitProvisionalLoad()
@@ -884,8 +871,6 @@
     RefPtr<DocumentLoader> pdl = m_provisionalDocumentLoader;
     RefPtr<Frame> protect(m_frame);
 
-    closeOldDataSources();
-
     // Check if the destination page is allowed to access the previous page's timing information.
     if (m_frame->document()) {
         RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(pdl->request().url());
@@ -896,8 +881,10 @@
     // JavaScript. If the script initiates a new load, we need to abandon the current load,
     // or the two will stomp each other.
     // detachChildren will similarly trigger child frame unload event handlers.
-    if (m_documentLoader)
+    if (m_documentLoader) {
+        m_client->dispatchWillClose();
         closeURL();
+    }
     detachChildren();
     if (pdl != m_provisionalDocumentLoader)
         return;
@@ -924,18 +911,6 @@
     started();
 }
 
-void FrameLoader::closeOldDataSources()
-{
-    // FIXME: Is it important for this traversal to be postorder instead of preorder?
-    // If so, add helpers for postorder traversal, and use them. If not, then lets not
-    // use a recursive algorithm here.
-    for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
-        child->loader().closeOldDataSources();
-
-    if (m_documentLoader)
-        m_client->dispatchWillClose();
-}
-
 bool FrameLoader::isLoadingMainFrame() const
 {
     return m_frame->isMainFrame();
@@ -964,31 +939,6 @@
     return m_loadType;
 }
 
-CachePolicy FrameLoader::subresourceCachePolicy() const
-{
-    if (m_frame->document()->loadEventFinished())
-        return CachePolicyVerify;
-
-    if (m_loadType == FrameLoadTypeReloadFromOrigin)
-        return CachePolicyReload;
-
-    if (Frame* parentFrame = m_frame->tree().parent()) {
-        CachePolicy parentCachePolicy = parentFrame->loader().subresourceCachePolicy();
-        if (parentCachePolicy != CachePolicyVerify)
-            return parentCachePolicy;
-    }
-
-    if (m_loadType == FrameLoadTypeReload)
-        return CachePolicyRevalidate;
-
-    const ResourceRequest& request(documentLoader()->request());
-
-    if (request.cachePolicy() == ReturnCacheDataElseLoad)
-        return CachePolicyHistoryBuffer;
-
-    return CachePolicyVerify;
-}
-
 void FrameLoader::checkLoadCompleteForThisFrame()
 {
     ASSERT(m_client->hasWebView());
@@ -1078,21 +1028,17 @@
     for (Frame* child = m_frame->tree().lastChild(); child; child = child->tree().previousSibling())
         childrenToDetach.append(child);
     FrameVector::iterator end = childrenToDetach.end();
-    for (FrameVector::iterator it = childrenToDetach.begin(); it != end; it++)
+    for (FrameVector::iterator it = childrenToDetach.begin(); it != end; ++it)
         (*it)->loader().detachFromParent();
 }
 
 void FrameLoader::closeAndRemoveChild(Frame* child)
 {
-    child->tree().detachFromParent();
-
     child->setView(0);
     if (child->ownerElement() && child->page())
         child->page()->decrementSubframeCount();
-    child->willDetachPage();
-    child->detachFromPage();
-
-    m_frame->tree().removeChild(child);
+    child->willDetachFrameHost();
+    child->loader().detachClient();
 }
 
 // Called every time a resource is completely loaded or an error is received.
@@ -1162,49 +1108,38 @@
     if (m_documentLoader)
         m_documentLoader->detachFromFrame();
     m_documentLoader = 0;
-    m_client->detachedFromParent();
 
-    m_progressTracker.clear();
+    if (!m_client)
+        return;
 
+    // FIXME: All this code belongs up in Page.
     if (Frame* parent = m_frame->tree().parent()) {
         parent->loader().closeAndRemoveChild(m_frame);
         parent->loader().scheduleCheckCompleted();
     } else {
         m_frame->setView(0);
-        m_frame->willDetachPage();
-        m_frame->detachFromPage();
+        m_frame->willDetachFrameHost();
+        detachClient();
     }
+    m_frame->detachFromFrameHost();
+
 }
 
-void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request)
+void FrameLoader::detachClient()
 {
-    bool isMainResource = (request.targetType() == ResourceRequest::TargetIsMainFrame) || (request.targetType() == ResourceRequest::TargetIsSubframe);
+    ASSERT(m_client);
 
-    if (isMainResource && isLoadingMainFrame())
-        request.setFirstPartyForCookies(request.url());
-    else
-        request.setFirstPartyForCookies(m_frame->document()->firstPartyForCookies());
+    // Finish all cleanup work that might require talking to the embedder.
+    m_progressTracker.clear();
+    setOpener(0);
+    // Notify ScriptController that the frame is closing, since its cleanup ends up calling
+    // back to FrameLoaderClient via V8WindowShell.
+    m_frame->script().clearForClose();
 
-    // The remaining modifications are only necessary for HTTP and HTTPS.
-    if (!request.url().isEmpty() && !request.url().protocolIsInHTTPFamily())
-        return;
-
-    applyUserAgent(request);
-
-    if (request.cachePolicy() == ReloadIgnoringCacheData) {
-        if (m_loadType == FrameLoadTypeReload)
-            request.setHTTPHeaderField("Cache-Control", "max-age=0");
-        else if (m_loadType == FrameLoadTypeReloadFromOrigin) {
-            request.setHTTPHeaderField("Cache-Control", "no-cache");
-            request.setHTTPHeaderField("Pragma", "no-cache");
-        }
-    }
-
-    if (isMainResource)
-        request.setHTTPAccept(defaultAcceptHeader);
-
-    // Make sure we send the Origin header.
-    addHTTPOriginIfNeeded(request, nullAtom);
+    // After this, we must no longer talk to the client since this clears
+    // its owning reference back to our owning Frame.
+    m_client->detachedFromParent();
+    m_client = 0;
 }
 
 void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const AtomicString& origin)
@@ -1227,24 +1162,18 @@
     if (origin.isEmpty()) {
         // If we don't know what origin header to attach, we attach the value
         // for an empty origin.
-        request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
+        request.setHTTPOrigin(SecurityOrigin::createUnique()->toAtomicString());
         return;
     }
 
     request.setHTTPOrigin(origin);
 }
 
-const ResourceRequest& FrameLoader::originalRequest() const
-{
-    return activeDocumentLoader()->originalRequestCopy();
-}
-
 void FrameLoader::receivedMainResourceError(const ResourceError& error)
 {
     // Retain because the stop may release the last reference to it.
     RefPtr<Frame> protect(m_frame);
 
-    RefPtr<DocumentLoader> loader = activeDocumentLoader();
     if (m_frame->document()->parser())
         m_frame->document()->parser()->stopParsing();
 
@@ -1259,34 +1188,15 @@
         checkLoadComplete();
 }
 
-void FrameLoader::checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction& action, bool isNewNavigation, ClientRedirectPolicy clientRedirect)
-{
-    m_documentLoader->setTriggeringAction(action);
-
-    const ResourceRequest& request = action.resourceRequest();
-    if (!m_documentLoader->shouldContinueForNavigationPolicy(request, DocumentLoader::PolicyCheckFragment))
-        return;
-
-    // If we have a provisional request for a different document, a fragment scroll should cancel it.
-    if (m_provisionalDocumentLoader && !equalIgnoringFragmentIdentifier(m_provisionalDocumentLoader->request().url(), request.url())) {
-        m_provisionalDocumentLoader->stopLoading();
-        if (m_provisionalDocumentLoader)
-            m_provisionalDocumentLoader->detachFromFrame();
-        m_provisionalDocumentLoader = 0;
-    }
-    saveDocumentAndScrollState();
-    loadInSameDocument(request.url(), 0, isNewNavigation, clientRedirect);
-}
-
 bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
 {
-    ASSERT(loadType != FrameLoadTypeBackForward);
     ASSERT(loadType != FrameLoadTypeReloadFromOrigin);
     // We don't do this if we are submitting a form with method other than "GET", explicitly reloading,
     // currently displaying a frameset, or if the URL does not have a fragment.
     return (!isFormSubmission || equalIgnoringCase(httpMethod, "GET"))
         && loadType != FrameLoadTypeReload
         && loadType != FrameLoadTypeSame
+        && loadType != FrameLoadTypeBackForward
         && url.hasFragmentIdentifier()
         && equalIgnoringFragmentIdentifier(m_frame->document()->url(), url)
         // We don't want to just scroll if a link from within a
@@ -1357,6 +1267,10 @@
     if (!m_stateMachine.committedFirstRealDocumentLoad() && m_frame->ownerElement() && !m_frame->ownerElement()->dispatchBeforeLoadEvent(request.url().string()))
         return;
 
+    // Dispatching the beforeload event could have blown away the frame.
+    if (!m_client)
+        return;
+
     if (!m_stateMachine.startedFirstRealLoad())
         m_stateMachine.advanceTo(FrameLoaderStateMachine::StartedFirstRealLoad);
 
@@ -1368,8 +1282,7 @@
         replacesCurrentHistoryItem = true;
     }
 
-    m_policyDocumentLoader = m_client->createDocumentLoader(request, substituteData.isValid() ? substituteData : defaultSubstituteDataForURL(request.url()));
-    m_policyDocumentLoader->setFrame(m_frame);
+    m_policyDocumentLoader = m_client->createDocumentLoader(m_frame, request, substituteData.isValid() ? substituteData : defaultSubstituteDataForURL(request.url()));
     m_policyDocumentLoader->setTriggeringAction(action);
     m_policyDocumentLoader->setReplacesCurrentHistoryItem(replacesCurrentHistoryItem);
     m_policyDocumentLoader->setIsClientRedirect(clientRedirect == ClientRedirect);
@@ -1383,7 +1296,7 @@
 
     // stopAllLoaders can detach the Frame, so protect it.
     RefPtr<Frame> protect(m_frame);
-    if ((!m_policyDocumentLoader->shouldContinueForNavigationPolicy(request, DocumentLoader::PolicyCheckStandard) || !shouldClose()) && m_policyDocumentLoader) {
+    if ((!m_policyDocumentLoader->shouldContinueForNavigationPolicy(request) || !shouldClose()) && m_policyDocumentLoader) {
         m_policyDocumentLoader->detachFromFrame();
         m_policyDocumentLoader = 0;
         return;
@@ -1421,12 +1334,12 @@
 {
     String userAgent = this->userAgent(request.url());
     ASSERT(!userAgent.isNull());
-    request.setHTTPUserAgent(userAgent);
+    request.setHTTPUserAgent(AtomicString(userAgent));
 }
 
 bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url, unsigned long requestIdentifier)
 {
-    UseCounter::count(m_frame->domWindow(), UseCounter::XFrameOptions);
+    UseCounter::count(m_frame->domWindow()->document(), UseCounter::XFrameOptions);
 
     Frame* topFrame = m_frame->tree().top();
     if (m_frame == topFrame)
@@ -1436,13 +1349,13 @@
 
     switch (disposition) {
     case XFrameOptionsSameOrigin: {
-        UseCounter::count(m_frame->domWindow(), UseCounter::XFrameOptionsSameOrigin);
+        UseCounter::count(m_frame->domWindow()->document(), UseCounter::XFrameOptionsSameOrigin);
         RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
         if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin()))
             return true;
         for (Frame* frame = m_frame->tree().parent(); frame; frame = frame->tree().parent()) {
             if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin())) {
-                UseCounter::count(m_frame->domWindow(), UseCounter::XFrameOptionsSameOriginWithBadAncestorChain);
+                UseCounter::count(m_frame->domWindow()->document(), UseCounter::XFrameOptionsSameOriginWithBadAncestorChain);
                 break;
             }
         }
@@ -1487,53 +1400,20 @@
 {
     ASSERT(activeDocument);
     Frame* frame = m_frame->tree().find(name);
-
-    // From http://www.whatwg.org/specs/web-apps/current-work/#seamlessLinks:
-    //
-    // If the source browsing context is the same as the browsing context
-    // being navigated, and this browsing context has its seamless browsing
-    // context flag set, and the browsing context being navigated was not
-    // chosen using an explicit self-navigation override, then find the
-    // nearest ancestor browsing context that does not have its seamless
-    // browsing context flag set, and continue these steps as if that
-    // browsing context was the one that was going to be navigated instead.
-    if (frame == m_frame && name != "_self" && m_frame->document()->shouldDisplaySeamlesslyWithParent()) {
-        for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree().parent()) {
-            if (!ancestor->document()->shouldDisplaySeamlesslyWithParent()) {
-                frame = ancestor;
-                break;
-            }
-        }
-        ASSERT(frame != m_frame);
-    }
-
     if (!activeDocument->canNavigate(frame))
         return 0;
     return frame;
 }
 
-void FrameLoader::loadHistoryItem(HistoryItem* item, HistoryLoadType historyLoadType)
+void FrameLoader::loadHistoryItem(HistoryItem* item, HistoryLoadType historyLoadType, ResourceRequestCachePolicy cachePolicy)
 {
-    saveDocumentAndScrollState();
-    m_currentItem = item;
+    m_provisionalItem = item;
     if (historyLoadType == HistorySameDocumentLoad) {
-        loadInSameDocument(item->url(), item->stateObject(), false, NotClientRedirect);
+        loadInSameDocument(item->url(), item->stateObject(), DoNotUpdateBackForwardList, NotClientRedirect);
         restoreScrollPositionAndViewState(ForcedRestoreForSameDocumentHistoryNavigation);
         return;
     }
-
-    RefPtr<FormData> formData = item->formData();
-    ResourceRequest request(item->url());
-    request.setHTTPReferrer(item->referrer());
-    if (formData) {
-        request.setHTTPMethod("POST");
-        request.setHTTPBody(formData);
-        request.setHTTPContentType(item->formContentType());
-        RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::createFromString(item->referrer());
-        addHTTPOriginIfNeeded(request, securityOrigin->toString());
-    }
-
-    loadWithNavigationAction(NavigationAction(request, FrameLoadTypeBackForward, formData), FrameLoadTypeBackForward, 0, SubstituteData());
+    loadWithNavigationAction(NavigationAction(requestFromHistoryItem(item, cachePolicy), FrameLoadTypeBackForward), FrameLoadTypeBackForward, 0, SubstituteData());
 }
 
 void FrameLoader::dispatchDocumentElementAvailable()
@@ -1546,10 +1426,14 @@
     if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript))
         return;
 
+    if (Page* page = m_frame->page())
+        page->inspectorController().didClearWindowObjectInMainWorld(m_frame);
+    InspectorInstrumentation::didClearWindowObjectInMainWorld(m_frame);
+
     Vector<RefPtr<DOMWrapperWorld> > worlds;
-    DOMWrapperWorld::getAllWorlds(worlds);
+    DOMWrapperWorld::getAllWorldsInMainThread(worlds);
     for (size_t i = 0; i < worlds.size(); ++i)
-        dispatchDidClearWindowObjectInWorld(worlds[i].get());
+        m_client->dispatchDidClearWindowObjectInWorld(worlds[i].get());
 }
 
 void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
@@ -1558,11 +1442,6 @@
         return;
 
     m_client->dispatchDidClearWindowObjectInWorld(world);
-
-    if (Page* page = m_frame->page())
-        page->inspectorController().didClearWindowObjectInWorld(m_frame, world);
-
-    InspectorInstrumentation::didClearWindowObjectInWorld(m_frame, world);
 }
 
 SandboxFlags FrameLoader::effectiveSandboxFlags() const
diff --git a/Source/core/loader/FrameLoader.h b/Source/core/loader/FrameLoader.h
index 7bdef53..3454dec 100644
--- a/Source/core/loader/FrameLoader.h
+++ b/Source/core/loader/FrameLoader.h
@@ -35,13 +35,13 @@
 #include "core/dom/IconURL.h"
 #include "core/dom/SandboxFlags.h"
 #include "core/dom/SecurityContext.h"
-#include "core/fetch/CachePolicy.h"
 #include "core/fetch/ResourceLoaderOptions.h"
-#include "core/history/HistoryItem.h"
 #include "core/loader/FrameLoaderStateMachine.h"
 #include "core/loader/FrameLoaderTypes.h"
+#include "core/loader/HistoryItem.h"
 #include "core/loader/MixedContentChecker.h"
 #include "platform/Timer.h"
+#include "platform/network/ResourceRequest.h"
 #include "wtf/Forward.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
@@ -61,7 +61,6 @@
 class NavigationAction;
 class Page;
 class ResourceError;
-class ResourceRequest;
 class ResourceResponse;
 class SecurityOrigin;
 class SerializedScriptValue;
@@ -87,7 +86,7 @@
     // These functions start a load. All eventually call into loadWithNavigationAction() or loadInSameDocument().
     void load(const FrameLoadRequest&); // The entry point for non-reload, non-history loads.
     void reload(ReloadPolicy = NormalReload, const KURL& overrideURL = KURL(), const AtomicString& overrideEncoding = nullAtom);
-    void loadHistoryItem(HistoryItem*, HistoryLoadType = HistoryDifferentDocumentLoad); // The entry point for all back/forward loads
+    void loadHistoryItem(HistoryItem*, HistoryLoadType = HistoryDifferentDocumentLoad, ResourceRequestCachePolicy = UseProtocolCachePolicy); // The entry point for all back/forward loads
 
     static void reportLocalLoadFailed(Frame*, const String& url);
 
@@ -98,7 +97,7 @@
     void stopLoading();
     bool closeURL();
     // FIXME: clear() is trying to do too many things. We should break it down into smaller functions.
-    void clear(ClearOptions);
+    void clear();
 
     // Sets a timer to notify the client that the initial empty document has
     // been accessed, and thus it is no longer safe to show a provisional URL
@@ -113,17 +112,13 @@
     bool isLoading() const;
 
     int numPendingOrLoadingRequests(bool recurse) const;
-    String outgoingReferrer() const;
-    String outgoingOrigin() const;
 
-    DocumentLoader* activeDocumentLoader() const;
     DocumentLoader* documentLoader() const { return m_documentLoader.get(); }
     DocumentLoader* policyDocumentLoader() const { return m_policyDocumentLoader.get(); }
     DocumentLoader* provisionalDocumentLoader() const { return m_provisionalDocumentLoader.get(); }
     FrameState state() const { return m_state; }
     FetchContext& fetchContext() const { return *m_fetchContext; }
 
-    const ResourceRequest& originalRequest() const;
     void receivedMainResourceError(const ResourceError&);
 
     bool isLoadingMainFrame() const;
@@ -136,15 +131,10 @@
     FrameLoadType loadType() const;
     void setLoadType(FrameLoadType loadType) { m_loadType = loadType; }
 
-    CachePolicy subresourceCachePolicy() const;
-
     void didFirstLayout();
 
     void checkLoadComplete(DocumentLoader*);
     void checkLoadComplete();
-    void detachFromParent();
-
-    void addExtraFieldsToRequest(ResourceRequest&);
 
     static void addHTTPOriginIfNeeded(ResourceRequest&, const AtomicString& origin);
 
@@ -175,8 +165,6 @@
 
     void frameDetached();
 
-    void setOutgoingReferrer(const KURL&);
-
     void loadDone();
     void finishedParsing();
     void checkCompleted();
@@ -199,10 +187,6 @@
 
     bool allowPlugins(ReasonForCallingAllowPlugins);
 
-    enum UpdateBackForwardListPolicy {
-        UpdateBackForwardList,
-        DoNotUpdateBackForwardList
-    };
     void updateForSameDocumentNavigation(const KURL&, SameDocumentNavigationSource, PassRefPtr<SerializedScriptValue>, UpdateBackForwardListPolicy);
 
     HistoryItem* currentItem() const { return m_currentItem.get(); }
@@ -224,35 +208,29 @@
     void didAccessInitialDocumentTimerFired(Timer<FrameLoader>*);
 
     bool prepareRequestForThisFrame(FrameLoadRequest&);
-    void setReferrerForFrameRequest(ResourceRequest&, ShouldSendReferrer);
+    void setReferrerForFrameRequest(ResourceRequest&, ShouldSendReferrer, Document*);
     FrameLoadType determineFrameLoadType(const FrameLoadRequest&);
     bool isScriptTriggeredFormSubmissionInChildFrame(const FrameLoadRequest&) const;
 
     SubstituteData defaultSubstituteDataForURL(const KURL&);
 
-    void checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction&, bool isNewNavigation, ClientRedirectPolicy);
-
     bool shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType, const KURL&);
     void scrollToFragmentWithParentBoundary(const KURL&);
 
     void checkLoadCompleteForThisFrame();
 
-    void closeOldDataSources();
-
     // Calls continueLoadAfterNavigationPolicy
     void loadWithNavigationAction(const NavigationAction&, FrameLoadType, PassRefPtr<FormState>,
         const SubstituteData&, ClientRedirectPolicy = NotClientRedirect, const AtomicString& overrideEncoding = nullAtom);
 
+    void detachFromParent();
     void detachChildren();
     void closeAndRemoveChild(Frame*);
+    void detachClient();
 
-    enum HistoryItemPolicy {
-        CreateNewHistoryItem,
-        DoNotCreateNewHistoryItem
-    };
-    void setHistoryItemStateForCommit(HistoryItemPolicy);
+    void setHistoryItemStateForCommit(HistoryCommitType, bool isPushOrReplaceState = false, PassRefPtr<SerializedScriptValue> = 0);
 
-    void loadInSameDocument(const KURL&, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation, ClientRedirectPolicy);
+    void loadInSameDocument(const KURL&, PassRefPtr<SerializedScriptValue> stateObject, UpdateBackForwardListPolicy, ClientRedirectPolicy);
 
     void scheduleCheckCompleted();
     void startCheckCompleteTimer();
@@ -282,11 +260,10 @@
     OwnPtr<FetchContext> m_fetchContext;
 
     RefPtr<HistoryItem> m_currentItem;
+    RefPtr<HistoryItem> m_provisionalItem;
 
     bool m_inStopAllLoaders;
 
-    String m_outgoingReferrer;
-
     // FIXME: This is only used in checkCompleted(). Figure out a way to disentangle it.
     bool m_isComplete;
 
diff --git a/Source/core/loader/FrameLoaderClient.h b/Source/core/loader/FrameLoaderClient.h
index ec3ca3c..ac8c5ca 100644
--- a/Source/core/loader/FrameLoaderClient.h
+++ b/Source/core/loader/FrameLoaderClient.h
@@ -34,6 +34,7 @@
 #include "core/loader/FrameLoaderTypes.h"
 #include "core/loader/NavigationPolicy.h"
 #include "platform/network/ResourceLoadPriority.h"
+#include "platform/weborigin/Referrer.h"
 #include "wtf/Forward.h"
 #include "wtf/Vector.h"
 
@@ -46,6 +47,7 @@
 
 namespace blink {
 class WebCookieJar;
+class WebRTCPeerConnectionHandler;
 class WebServiceWorkerProvider;
 class WebServiceWorkerProviderClient;
 }
@@ -76,26 +78,25 @@
     class ResourceHandle;
     class ResourceRequest;
     class ResourceResponse;
-    class RTCPeerConnectionHandler;
     class SecurityOrigin;
     class SharedBuffer;
+    class SharedWorkerRepositoryClient;
     class SocketStreamHandle;
     class SubstituteData;
     class Widget;
 
-    enum NavigationHistoryPolicy {
-        NavigationCreatedHistoryEntry,
-        NavigationReusedHistoryEntry
-    };
-
     class FrameLoaderClient {
     public:
         virtual ~FrameLoaderClient() { }
 
-        virtual void frameLoaderDestroyed() = 0;
-
         virtual bool hasWebView() const = 0; // mainly for assertions
 
+        virtual Frame* parent() const = 0;
+        virtual Frame* top() const = 0;
+        virtual Frame* previousSibling() const = 0;
+        virtual Frame* nextSibling() const = 0;
+        virtual Frame* firstChild() const = 0;
+        virtual Frame* lastChild() const = 0;
         virtual void detachedFromParent() = 0;
 
         virtual void dispatchWillRequestAfterPreconnect(ResourceRequest&) { }
@@ -106,12 +107,12 @@
 
         virtual void dispatchDidHandleOnloadEvents() = 0;
         virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() = 0;
-        virtual void dispatchDidNavigateWithinPage(NavigationHistoryPolicy, HistoryItem*) { }
+        virtual void dispatchDidNavigateWithinPage(HistoryItem*, HistoryCommitType) { }
         virtual void dispatchWillClose() = 0;
         virtual void dispatchDidStartProvisionalLoad() = 0;
         virtual void dispatchDidReceiveTitle(const String&) = 0;
         virtual void dispatchDidChangeIcons(IconType) = 0;
-        virtual void dispatchDidCommitLoad(Frame*, HistoryItem*, NavigationHistoryPolicy) = 0;
+        virtual void dispatchDidCommitLoad(Frame*, HistoryItem*, HistoryCommitType) = 0;
         virtual void dispatchDidFailProvisionalLoad(const ResourceError&) = 0;
         virtual void dispatchDidFailLoad(const ResourceError&) = 0;
         virtual void dispatchDidFinishDocumentLoad() = 0;
@@ -126,7 +127,7 @@
         virtual void dispatchWillSubmitForm(PassRefPtr<FormState>) = 0;
 
         // Maybe these should go into a ProgressTrackerClient some day
-        virtual void postProgressStartedNotification() = 0;
+        virtual void postProgressStartedNotification(LoadStartType) = 0;
         virtual void postProgressEstimateChangedNotification() = 0;
         virtual void postProgressFinishedNotification() = 0;
 
@@ -159,7 +160,7 @@
         // that match any element on the frame.
         virtual void selectorMatchChanged(const Vector<String>& addedSelectors, const Vector<String>& removedSelectors) = 0;
 
-        virtual PassRefPtr<DocumentLoader> createDocumentLoader(const ResourceRequest&, const SubstituteData&) = 0;
+        virtual PassRefPtr<DocumentLoader> createDocumentLoader(Frame*, const ResourceRequest&, const SubstituteData&) = 0;
 
         virtual String userAgent(const KURL&) = 0;
 
@@ -167,7 +168,7 @@
 
         virtual void transitionToCommittedForNewPage() = 0;
 
-        virtual PassRefPtr<Frame> createFrame(const KURL&, const String& name, const String& referrer, HTMLFrameOwnerElement*) = 0;
+        virtual PassRefPtr<Frame> createFrame(const KURL&, const AtomicString& name, const Referrer&, HTMLFrameOwnerElement*) = 0;
         virtual PassRefPtr<Widget> createPlugin(const IntSize&, HTMLPlugInElement*, const KURL&, const Vector<String>&, const Vector<String>&, const String&, bool loadManually) = 0;
 
         virtual PassRefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement*, const KURL& baseURL, const Vector<String>& paramNames, const Vector<String>& paramValues) = 0;
@@ -210,7 +211,7 @@
 
         virtual void dispatchWillOpenSocketStream(SocketStreamHandle*) { }
 
-        virtual void dispatchWillStartUsingPeerConnectionHandler(RTCPeerConnectionHandler*) { }
+        virtual void dispatchWillStartUsingPeerConnectionHandler(blink::WebRTCPeerConnectionHandler*) { }
 
         virtual void didRequestAutocomplete(PassRefPtr<FormState>) = 0;
 
@@ -219,9 +220,6 @@
         // notification with the given GL_ARB_robustness guilt/innocence code (see Extensions3D.h).
         virtual void didLoseWebGLContext(int) { }
 
-        // Returns true if WebGL extension WEBGL_debug_renderer_info is allowed.
-        virtual bool allowWebGLDebugRendererInfo() { return false; }
-
         // If an HTML document is being loaded, informs the embedder that the document will have its <body> attached soon.
         virtual void dispatchWillInsertBody() { }
 
@@ -229,6 +227,8 @@
 
         virtual PassOwnPtr<blink::WebServiceWorkerProvider> createServiceWorkerProvider(PassOwnPtr<blink::WebServiceWorkerProviderClient>) = 0;
 
+        virtual SharedWorkerRepositoryClient* sharedWorkerRepositoryClient() { return 0; }
+
         virtual void didStopAllLoaders() { }
 
         virtual bool isFrameLoaderClientImpl() const { return false; }
diff --git a/Source/core/loader/FrameLoaderTypes.h b/Source/core/loader/FrameLoaderTypes.h
index 5fe5d36..b2af42f 100644
--- a/Source/core/loader/FrameLoaderTypes.h
+++ b/Source/core/loader/FrameLoaderTypes.h
@@ -66,13 +66,6 @@
     ObjectContentOtherPlugin
 };
 
-enum ClearOption {
-    ClearWindowProperties = 1 << 0,
-    ClearScriptObjects = 1 << 1,
-    ClearWindowObject = 1 << 2,
-};
-typedef int ClearOptions;
-
 enum ShouldSendReferrer {
     MaybeSendReferrer,
     NeverSendReferrer
@@ -88,10 +81,14 @@
     EndToEndReload
 };
 
+enum LoadStartType {
+    NavigationToDifferentDocument,
+    NavigationWithinSameDocument
+};
+
 enum SameDocumentNavigationSource {
     SameDocumentNavigationDefault,
-    SameDocumentNavigationPushState,
-    SameDocumentNavigationReplaceState
+    SameDocumentNavigationHistoryApi,
 };
 
 enum ClientRedirectPolicy {
@@ -104,6 +101,17 @@
     HistoryDifferentDocumentLoad
 };
 
+enum HistoryCommitType {
+    StandardCommit,
+    BackForwardCommit,
+    InitialCommitInChildFrame,
+    HistoryInertCommit
+};
+
+enum UpdateBackForwardListPolicy {
+    UpdateBackForwardList,
+    DoNotUpdateBackForwardList
+};
 }
 
 #endif
diff --git a/Source/core/history/HistoryItem.cpp b/Source/core/loader/HistoryItem.cpp
similarity index 92%
rename from Source/core/history/HistoryItem.cpp
rename to Source/core/loader/HistoryItem.cpp
index a26929a..e9600e9 100644
--- a/Source/core/history/HistoryItem.cpp
+++ b/Source/core/loader/HistoryItem.cpp
@@ -24,7 +24,7 @@
  */
 
 #include "config.h"
-#include "core/history/HistoryItem.h"
+#include "core/loader/HistoryItem.h"
 
 #include "core/dom/Document.h"
 #include "platform/network/ResourceRequest.h"
@@ -82,19 +82,10 @@
     return adoptRef(new HistoryItem(*this));
 }
 
-void HistoryItem::reset()
+void HistoryItem::generateNewSequenceNumbers()
 {
-    m_urlString = String();
-    m_originalURLString = String();
-    m_referrer = nullAtom;
-    m_target = String();
     m_itemSequenceNumber = generateSequenceNumber();
-    m_stateObject = 0;
     m_documentSequenceNumber = generateSequenceNumber();
-    m_targetFrameID = 0;
-    m_formData = 0;
-    m_formContentType = nullAtom;
-    clearChildren();
 }
 
 const String& HistoryItem::urlString() const
@@ -102,7 +93,7 @@
     return m_urlString;
 }
 
-// The first URL we loaded to get to where this history item points.  Includes both client
+// The first URL we loaded to get to where this history item points. Includes both client
 // and server redirects.
 const String& HistoryItem::originalURLString() const
 {
@@ -119,7 +110,7 @@
     return KURL(ParsedURLString, m_originalURLString);
 }
 
-const AtomicString& HistoryItem::referrer() const
+const Referrer& HistoryItem::referrer() const
 {
     return m_referrer;
 }
@@ -146,7 +137,7 @@
     m_originalURLString = urlString;
 }
 
-void HistoryItem::setReferrer(const AtomicString& referrer)
+void HistoryItem::setReferrer(const Referrer& referrer)
 {
     m_referrer = referrer;
 }
@@ -224,8 +215,6 @@
 
 void HistoryItem::setFormInfoFromRequest(const ResourceRequest& request)
 {
-    m_referrer = request.httpReferrer();
-
     if (equalIgnoringCase(request.httpMethod(), "POST")) {
         // FIXME: Eventually we have to make this smart enough to handle the case where
         // we have a stream for the body to handle the "data interspersed with files" feature.
diff --git a/Source/core/history/HistoryItem.h b/Source/core/loader/HistoryItem.h
similarity index 87%
rename from Source/core/history/HistoryItem.h
rename to Source/core/loader/HistoryItem.h
index e2fa91e..8a5677c 100644
--- a/Source/core/history/HistoryItem.h
+++ b/Source/core/loader/HistoryItem.h
@@ -29,6 +29,7 @@
 
 #include "bindings/v8/SerializedScriptValue.h"
 #include "platform/geometry/IntPoint.h"
+#include "platform/weborigin/Referrer.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
@@ -51,15 +52,16 @@
 
     PassRefPtr<HistoryItem> copy() const;
 
-    // Resets the HistoryItem to its initial state, as returned by create().
-    void reset();
+    // Used when the frame this item represents was navigated to a different
+    // url but a new item wasn't created.
+    void generateNewSequenceNumbers();
 
     const String& originalURLString() const;
     const String& urlString() const;
     KURL url() const;
     KURL originalURL() const;
 
-    const AtomicString& referrer() const;
+    const Referrer& referrer() const;
     const String& target() const;
 
     FormData* formData();
@@ -79,10 +81,10 @@
     void setURL(const KURL&);
     void setURLString(const String&);
     void setOriginalURLString(const String&);
-    void setReferrer(const AtomicString&);
+    void setReferrer(const Referrer&);
     void setTarget(const String&);
 
-    void setStateObject(PassRefPtr<SerializedScriptValue> object);
+    void setStateObject(PassRefPtr<SerializedScriptValue>);
     SerializedScriptValue* stateObject() const { return m_stateObject.get(); }
 
     void setItemSequenceNumber(long long number) { m_itemSequenceNumber = number; }
@@ -110,7 +112,7 @@
 
     String m_urlString;
     String m_originalURLString;
-    AtomicString m_referrer;
+    Referrer m_referrer;
     String m_target;
 
     IntPoint m_scrollPoint;
@@ -120,13 +122,13 @@
     HistoryItemVector m_children;
 
     // If two HistoryItems have the same item sequence number, then they are
-    // clones of one another.  Traversing history from one such HistoryItem to
-    // another is a no-op.  HistoryItem clones are created for parent and
+    // clones of one another. Traversing history from one such HistoryItem to
+    // another is a no-op. HistoryItem clones are created for parent and
     // sibling frames when only a subframe navigates.
     int64_t m_itemSequenceNumber;
 
     // If two HistoryItems have the same document sequence number, then they
-    // refer to the same instance of a document.  Traversing history from one
+    // refer to the same instance of a document. Traversing history from one
     // such HistoryItem to another preserves the document.
     int64_t m_documentSequenceNumber;
 
@@ -139,8 +141,8 @@
     RefPtr<FormData> m_formData;
     AtomicString m_formContentType;
 
-}; //class HistoryItem
+}; // class HistoryItem
 
-} //namespace WebCore
+} // namespace WebCore
 
 #endif // HISTORYITEM_H
diff --git a/Source/core/loader/ImageLoader.cpp b/Source/core/loader/ImageLoader.cpp
index a8177ba..1d99b40 100644
--- a/Source/core/loader/ImageLoader.cpp
+++ b/Source/core/loader/ImageLoader.cpp
@@ -158,10 +158,8 @@
         FetchRequest request(ResourceRequest(document.completeURL(sourceURI(attr))), element()->localName());
 
         AtomicString crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
-        if (!crossOriginMode.isNull()) {
-            StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
-            updateRequestForAccessControl(request.mutableResourceRequest(), document.securityOrigin(), allowCredentials);
-        }
+        if (!crossOriginMode.isNull())
+            request.setCrossOriginAccessControl(document.securityOrigin(), crossOriginMode);
 
         if (m_loadManually) {
             bool autoLoadOtherImages = document.fetcher()->autoLoadImages();
@@ -264,26 +262,18 @@
     if (!m_hasPendingLoadEvent)
         return;
 
-    if (m_element->fastHasAttribute(HTMLNames::crossoriginAttr)
-        && !m_element->document().securityOrigin()->canRequest(image()->response().url())
-        && !resource->passesAccessControlCheck(m_element->document().securityOrigin())) {
-
-        setImageWithoutConsideringPendingLoadEvent(0);
+    if (resource->errorOccurred()) {
+        loadEventSender().cancelEvent(this);
+        m_hasPendingLoadEvent = false;
 
         m_hasPendingErrorEvent = true;
         errorEventSender().dispatchEventSoon(this);
 
-        DEFINE_STATIC_LOCAL(String, consoleMessage, ("Cross-origin image load denied by Cross-Origin Resource Sharing policy."));
-        m_element->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
-
-        ASSERT(!m_hasPendingLoadEvent);
-
         // Only consider updating the protection ref-count of the Element immediately before returning
         // from this function as doing so might result in the destruction of this ImageLoader.
         updatedHasPendingEvent();
         return;
     }
-
     if (resource->wasCanceled()) {
         m_hasPendingLoadEvent = false;
         // Only consider updating the protection ref-count of the Element immediately before returning
@@ -291,7 +281,6 @@
         updatedHasPendingEvent();
         return;
     }
-
     loadEventSender().dispatchEventSoon(this);
 }
 
diff --git a/Source/core/loader/ImageLoader.h b/Source/core/loader/ImageLoader.h
index 6c1274f..ad0deb6 100644
--- a/Source/core/loader/ImageLoader.h
+++ b/Source/core/loader/ImageLoader.h
@@ -85,7 +85,7 @@
     void removeClient(ImageLoaderClient*);
 
 protected:
-    virtual void notifyFinished(Resource*);
+    virtual void notifyFinished(Resource*) OVERRIDE;
 
 private:
     virtual void dispatchLoadEvent() = 0;
diff --git a/Source/core/loader/LinkLoader.cpp b/Source/core/loader/LinkLoader.cpp
index f2441b5..adbc51e 100644
--- a/Source/core/loader/LinkLoader.cpp
+++ b/Source/core/loader/LinkLoader.cpp
@@ -36,13 +36,25 @@
 #include "core/dom/Document.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ResourceFetcher.h"
+#include "core/frame/Settings.h"
 #include "core/html/LinkRelAttribute.h"
 #include "core/loader/PrerenderHandle.h"
-#include "core/page/Settings.h"
+#include "platform/Prerender.h"
 #include "platform/network/DNS.h"
 
 namespace WebCore {
 
+static unsigned prerenderRelTypesFromRelAttribute(const LinkRelAttribute& relAttribute)
+{
+    unsigned result = 0;
+    if (relAttribute.isLinkPrerender())
+        result |= PrerenderRelTypePrerender;
+    if (relAttribute.isLinkNext())
+        result |= PrerenderRelTypeNext;
+
+    return result;
+}
+
 LinkLoader::LinkLoader(LinkLoaderClient* client)
     : m_client(client)
     , m_linkLoadTimer(this, &LinkLoader::linkLoadTimerFired)
@@ -52,8 +64,6 @@
 
 LinkLoader::~LinkLoader()
 {
-    if (m_cachedLinkResource)
-        m_cachedLinkResource->removeClient(this);
 }
 
 void LinkLoader::linkLoadTimerFired(Timer<LinkLoader>* timer)
@@ -70,15 +80,14 @@
 
 void LinkLoader::notifyFinished(Resource* resource)
 {
-    ASSERT_UNUSED(resource, m_cachedLinkResource.get() == resource);
+    ASSERT(this->resource() == resource);
 
-    if (m_cachedLinkResource->errorOccurred())
+    if (resource->errorOccurred())
         m_linkLoadingErrorTimer.startOneShot(0);
     else
         m_linkLoadTimer.startOneShot(0);
 
-    m_cachedLinkResource->removeClient(this);
-    m_cachedLinkResource = 0;
+    clearResource();
 }
 
 void LinkLoader::didStartPrerender()
@@ -101,7 +110,7 @@
     m_client->didSendDOMContentLoadedForLinkPrerender();
 }
 
-bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const String& type, const KURL& href, Document& document)
+bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const AtomicString& crossOriginMode, const String& type, const KURL& href, Document& document)
 {
     if (relAttribute.isDNSPrefetch()) {
         Settings* settings = document.settings();
@@ -117,22 +126,19 @@
             return false;
         Resource::Type type = relAttribute.isLinkSubresource() ?  Resource::LinkSubresource : Resource::LinkPrefetch;
         FetchRequest linkRequest(ResourceRequest(document.completeURL(href)), FetchInitiatorTypeNames::link);
-        if (m_cachedLinkResource) {
-            m_cachedLinkResource->removeClient(this);
-            m_cachedLinkResource = 0;
-        }
-        m_cachedLinkResource = document.fetcher()->fetchLinkResource(type, linkRequest);
-        if (m_cachedLinkResource)
-            m_cachedLinkResource->addClient(this);
+        if (!crossOriginMode.isNull())
+            linkRequest.setCrossOriginAccessControl(document.securityOrigin(), crossOriginMode);
+        setResource(document.fetcher()->fetchLinkResource(type, linkRequest));
     }
 
-    if (relAttribute.isLinkPrerender()) {
+    if (const unsigned prerenderRelTypes = prerenderRelTypesFromRelAttribute(relAttribute)) {
         if (!m_prerender) {
-            m_prerender = PrerenderHandle::create(document, this, href);
+            m_prerender = PrerenderHandle::create(document, this, href, prerenderRelTypes);
         } else if (m_prerender->url() != href) {
             m_prerender->cancel();
-            m_prerender = PrerenderHandle::create(document, this, href);
+            m_prerender = PrerenderHandle::create(document, this, href, prerenderRelTypes);
         }
+        // TODO(gavinp): Handle changes to rel types of existing prerenders.
     } else if (m_prerender) {
         m_prerender->cancel();
         m_prerender.clear();
diff --git a/Source/core/loader/LinkLoader.h b/Source/core/loader/LinkLoader.h
index 56e940a..978f5ad 100644
--- a/Source/core/loader/LinkLoader.h
+++ b/Source/core/loader/LinkLoader.h
@@ -33,7 +33,7 @@
 #define LinkLoader_h
 
 #include "core/fetch/ResourceClient.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
 #include "core/loader/LinkLoaderClient.h"
 #include "platform/PrerenderClient.h"
 #include "platform/Timer.h"
@@ -46,14 +46,14 @@
 class PrerenderHandle;
 
 // The LinkLoader can load link rel types icon, dns-prefetch, subresource, prefetch and prerender.
-class LinkLoader : public ResourceClient, public PrerenderClient {
+class LinkLoader FINAL : public ResourceOwner<Resource, ResourceClient>, public PrerenderClient {
 
 public:
     explicit LinkLoader(LinkLoaderClient*);
     virtual ~LinkLoader();
 
     // from ResourceClient
-    virtual void notifyFinished(Resource*);
+    virtual void notifyFinished(Resource*) OVERRIDE;
 
     // from PrerenderClient
     virtual void didStartPrerender() OVERRIDE;
@@ -62,7 +62,7 @@
     virtual void didSendDOMContentLoadedForPrerender() OVERRIDE;
 
     void released();
-    bool loadLink(const LinkRelAttribute&, const String& type, const KURL&, Document&);
+    bool loadLink(const LinkRelAttribute&, const AtomicString& crossOriginMode, const String& type, const KURL&, Document&);
 
 private:
     void linkLoadTimerFired(Timer<LinkLoader>*);
@@ -70,7 +70,6 @@
 
     LinkLoaderClient* m_client;
 
-    ResourcePtr<Resource> m_cachedLinkResource;
     Timer<LinkLoader> m_linkLoadTimer;
     Timer<LinkLoader> m_linkLoadingErrorTimer;
 
diff --git a/Source/core/loader/MixedContentChecker.cpp b/Source/core/loader/MixedContentChecker.cpp
index 8830a60..750f130 100644
--- a/Source/core/loader/MixedContentChecker.cpp
+++ b/Source/core/loader/MixedContentChecker.cpp
@@ -33,7 +33,7 @@
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
diff --git a/Source/core/loader/NavigationAction.cpp b/Source/core/loader/NavigationAction.cpp
index b0cffda..b27828e 100644
--- a/Source/core/loader/NavigationAction.cpp
+++ b/Source/core/loader/NavigationAction.cpp
@@ -57,7 +57,7 @@
 NavigationAction::NavigationAction(const ResourceRequest& resourceRequest, FrameLoadType frameLoadType,
         bool isFormSubmission, PassRefPtr<Event> event)
     : m_resourceRequest(resourceRequest)
-    , m_type(navigationType(frameLoadType, isFormSubmission, event))
+    , m_type(navigationType(frameLoadType, isFormSubmission || resourceRequest.httpBody(), event))
     , m_event(event)
 {
     const MouseEvent* mouseEvent = 0;
diff --git a/Source/core/loader/NavigationScheduler.cpp b/Source/core/loader/NavigationScheduler.cpp
index 5c2b2a4..295cdfc 100644
--- a/Source/core/loader/NavigationScheduler.cpp
+++ b/Source/core/loader/NavigationScheduler.cpp
@@ -96,47 +96,47 @@
 
 class ScheduledURLNavigation : public ScheduledNavigation {
 protected:
-    ScheduledURLNavigation(double delay, SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList, bool isLocationChange)
+    ScheduledURLNavigation(double delay, Document* originDocument, const String& url, const Referrer& referrer, bool lockBackForwardList, bool isLocationChange)
         : ScheduledNavigation(delay, lockBackForwardList, isLocationChange)
-        , m_securityOrigin(securityOrigin)
+        , m_originDocument(originDocument)
         , m_url(url)
         , m_referrer(referrer)
     {
     }
 
-    virtual void fire(Frame* frame)
+    virtual void fire(Frame* frame) OVERRIDE
     {
         OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
-        FrameLoadRequest request(m_securityOrigin.get(), ResourceRequest(KURL(ParsedURLString, m_url), m_referrer), "_self");
+        FrameLoadRequest request(m_originDocument.get(), ResourceRequest(KURL(ParsedURLString, m_url), m_referrer), "_self");
         request.setLockBackForwardList(lockBackForwardList());
         request.setClientRedirect(ClientRedirect);
         frame->loader().load(request);
     }
 
-    SecurityOrigin* securityOrigin() const { return m_securityOrigin.get(); }
+    Document* originDocument() const { return m_originDocument.get(); }
     String url() const { return m_url; }
-    String referrer() const { return m_referrer; }
+    const Referrer& referrer() const { return m_referrer; }
 
 private:
-    RefPtr<SecurityOrigin> m_securityOrigin;
+    RefPtr<Document> m_originDocument;
     String m_url;
-    String m_referrer;
+    Referrer m_referrer;
 };
 
-class ScheduledRedirect : public ScheduledURLNavigation {
+class ScheduledRedirect FINAL : public ScheduledURLNavigation {
 public:
-    ScheduledRedirect(double delay, SecurityOrigin* securityOrigin, const String& url, bool lockBackForwardList)
-        : ScheduledURLNavigation(delay, securityOrigin, url, String(), lockBackForwardList, false)
+    ScheduledRedirect(double delay, Document* originDocument, const String& url, bool lockBackForwardList)
+        : ScheduledURLNavigation(delay, originDocument, url, Referrer(), lockBackForwardList, false)
     {
         clearUserGesture();
     }
 
-    virtual bool shouldStartTimer(Frame* frame) { return frame->loader().allAncestorsAreComplete(); }
+    virtual bool shouldStartTimer(Frame* frame) OVERRIDE { return frame->loader().allAncestorsAreComplete(); }
 
-    virtual void fire(Frame* frame)
+    virtual void fire(Frame* frame) OVERRIDE
     {
         OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
-        FrameLoadRequest request(securityOrigin(), ResourceRequest(KURL(ParsedURLString, url()), referrer()), "_self");
+        FrameLoadRequest request(originDocument(), ResourceRequest(KURL(ParsedURLString, url()), referrer()), "_self");
         request.setLockBackForwardList(lockBackForwardList());
         if (equalIgnoringFragmentIdentifier(frame->document()->url(), request.resourceRequest().url()))
             request.resourceRequest().setCachePolicy(ReloadIgnoringCacheData);
@@ -145,30 +145,30 @@
     }
 };
 
-class ScheduledLocationChange : public ScheduledURLNavigation {
+class ScheduledLocationChange FINAL : public ScheduledURLNavigation {
 public:
-    ScheduledLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList)
-        : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, lockBackForwardList, true) { }
+    ScheduledLocationChange(Document* originDocument, const String& url, const Referrer& referrer, bool lockBackForwardList)
+        : ScheduledURLNavigation(0.0, originDocument, url, referrer, lockBackForwardList, true) { }
 };
 
-class ScheduledRefresh : public ScheduledURLNavigation {
+class ScheduledRefresh FINAL : public ScheduledURLNavigation {
 public:
-    ScheduledRefresh(SecurityOrigin* securityOrigin, const String& url, const String& referrer)
-        : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, true, true)
+    ScheduledRefresh(Document* originDocument, const String& url, const Referrer& referrer)
+        : ScheduledURLNavigation(0.0, originDocument, url, referrer, true, true)
     {
     }
 
-    virtual void fire(Frame* frame)
+    virtual void fire(Frame* frame) OVERRIDE
     {
         OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
-        FrameLoadRequest request(securityOrigin(), ResourceRequest(KURL(ParsedURLString, url()), referrer(), ReloadIgnoringCacheData), "_self");
+        FrameLoadRequest request(originDocument(), ResourceRequest(KURL(ParsedURLString, url()), referrer(), ReloadIgnoringCacheData), "_self");
         request.setLockBackForwardList(lockBackForwardList());
         request.setClientRedirect(ClientRedirect);
         frame->loader().load(request);
     }
 };
 
-class ScheduledHistoryNavigation : public ScheduledNavigation {
+class ScheduledHistoryNavigation FINAL : public ScheduledNavigation {
 public:
     explicit ScheduledHistoryNavigation(int historySteps)
         : ScheduledNavigation(0, false, true)
@@ -176,12 +176,12 @@
     {
     }
 
-    virtual void fire(Frame* frame)
+    virtual void fire(Frame* frame) OVERRIDE
     {
         OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
 
         if (!m_historySteps) {
-            FrameLoadRequest frameRequest(frame->document()->securityOrigin(), ResourceRequest(frame->document()->url()));
+            FrameLoadRequest frameRequest(frame->document(), ResourceRequest(frame->document()->url()));
             frameRequest.setLockBackForwardList(lockBackForwardList());
             // Special case for go(0) from a frame -> reload only the frame
             // To follow Firefox and IE's behavior, history reload can only navigate the self frame.
@@ -197,7 +197,7 @@
     int m_historySteps;
 };
 
-class ScheduledFormSubmission : public ScheduledNavigation {
+class ScheduledFormSubmission FINAL : public ScheduledNavigation {
 public:
     ScheduledFormSubmission(PassRefPtr<FormSubmission> submission, bool lockBackForwardList)
         : ScheduledNavigation(0, lockBackForwardList, true)
@@ -206,10 +206,10 @@
         ASSERT(m_submission->state());
     }
 
-    virtual void fire(Frame* frame)
+    virtual void fire(Frame* frame) OVERRIDE
     {
         OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
-        FrameLoadRequest frameRequest(m_submission->state()->sourceDocument()->securityOrigin());
+        FrameLoadRequest frameRequest(m_submission->state()->sourceDocument());
         m_submission->populateFrameLoadRequest(frameRequest);
         frameRequest.setLockBackForwardList(lockBackForwardList());
         frameRequest.setTriggeringEvent(m_submission->event());
@@ -217,7 +217,7 @@
         frame->loader().load(frameRequest);
     }
 
-    virtual bool isForm() const { return true; }
+    virtual bool isForm() const OVERRIDE { return true; }
     FormSubmission* submission() const { return m_submission.get(); }
 
 private:
@@ -268,7 +268,7 @@
 
     // We want a new back/forward list item if the refresh timeout is > 1 second.
     if (!m_redirect || delay <= m_redirect->delay())
-        schedule(adoptPtr(new ScheduledRedirect(delay, m_frame->document()->securityOrigin(), url, delay <= 1)));
+        schedule(adoptPtr(new ScheduledRedirect(delay, m_frame->document(), url, delay <= 1)));
 }
 
 bool NavigationScheduler::mustLockBackForwardList(Frame* targetFrame)
@@ -292,7 +292,7 @@
     return targetFrame->tree().parent() && !targetFrame->tree().parent()->loader().allAncestorsAreComplete();
 }
 
-void NavigationScheduler::scheduleLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList)
+void NavigationScheduler::scheduleLocationChange(Document* originDocument, const String& url, const Referrer& referrer, bool lockBackForwardList)
 {
     if (!shouldScheduleNavigation(url))
         return;
@@ -305,18 +305,19 @@
     // fragment part, we don't need to schedule the location change. We'll skip this
     // optimization for cross-origin navigations to minimize the navigator's ability to
     // execute timing attacks.
-    if (securityOrigin->canAccess(m_frame->document()->securityOrigin())) {
+    if (originDocument->securityOrigin()->canAccess(m_frame->document()->securityOrigin())) {
         KURL parsedURL(ParsedURLString, url);
         if (parsedURL.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(m_frame->document()->url(), parsedURL)) {
-            FrameLoadRequest request(securityOrigin, ResourceRequest(m_frame->document()->completeURL(url), referrer), "_self");
+            FrameLoadRequest request(originDocument, ResourceRequest(m_frame->document()->completeURL(url), referrer), "_self");
             request.setLockBackForwardList(lockBackForwardList);
-            request.setClientRedirect(ClientRedirect);
+            if (lockBackForwardList)
+                request.setClientRedirect(ClientRedirect);
             m_frame->loader().load(request);
             return;
         }
     }
 
-    schedule(adoptPtr(new ScheduledLocationChange(securityOrigin, url, referrer, lockBackForwardList)));
+    schedule(adoptPtr(new ScheduledLocationChange(originDocument, url, referrer, lockBackForwardList)));
 }
 
 void NavigationScheduler::scheduleFormSubmission(PassRefPtr<FormSubmission> submission)
@@ -333,7 +334,7 @@
     if (url.isEmpty())
         return;
 
-    schedule(adoptPtr(new ScheduledRefresh(m_frame->document()->securityOrigin(), url.string(), m_frame->loader().outgoingReferrer())));
+    schedule(adoptPtr(new ScheduledRefresh(m_frame->document(), url.string(), Referrer(m_frame->document()->outgoingReferrer(), m_frame->document()->referrerPolicy()))));
 }
 
 void NavigationScheduler::scheduleHistoryNavigation(int steps)
diff --git a/Source/core/loader/NavigationScheduler.h b/Source/core/loader/NavigationScheduler.h
index dbbee95..5d5fb01 100644
--- a/Source/core/loader/NavigationScheduler.h
+++ b/Source/core/loader/NavigationScheduler.h
@@ -32,6 +32,7 @@
 #define NavigationScheduler_h
 
 #include "platform/Timer.h"
+#include "platform/weborigin/Referrer.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
@@ -42,10 +43,10 @@
 
 namespace WebCore {
 
+class Document;
 class FormSubmission;
 class Frame;
 class ScheduledNavigation;
-class SecurityOrigin;
 
 class NavigationDisablerForBeforeUnload {
     WTF_MAKE_NONCOPYABLE(NavigationDisablerForBeforeUnload);
@@ -76,7 +77,7 @@
     bool locationChangePending();
 
     void scheduleRedirect(double delay, const String& url);
-    void scheduleLocationChange(SecurityOrigin*, const String& url, const String& referrer, bool lockBackForwardList = true);
+    void scheduleLocationChange(Document*, const String& url, const Referrer& referrer, bool lockBackForwardList = true);
     void scheduleFormSubmission(PassRefPtr<FormSubmission>);
     void scheduleRefresh();
     void scheduleHistoryNavigation(int steps);
diff --git a/Source/core/loader/PingLoader.cpp b/Source/core/loader/PingLoader.cpp
index 853b706..c629979 100644
--- a/Source/core/loader/PingLoader.cpp
+++ b/Source/core/loader/PingLoader.cpp
@@ -32,20 +32,25 @@
 #include "config.h"
 #include "core/loader/PingLoader.h"
 
+#include "FetchInitiatorTypeNames.h"
 #include "core/dom/Document.h"
+#include "core/fetch/FetchContext.h"
 #include "core/frame/Frame.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/UniqueIdentifier.h"
+#include "core/page/Page.h"
 #include "platform/exported/WrappedResourceRequest.h"
 #include "platform/network/FormData.h"
+#include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
 #include "platform/weborigin/SecurityOrigin.h"
 #include "platform/weborigin/SecurityPolicy.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebURLLoader.h"
+#include "public/platform/WebURLResponse.h"
 #include "wtf/OwnPtr.h"
 
 namespace WebCore {
@@ -60,14 +65,11 @@
     ResourceRequest request(url);
     request.setTargetType(ResourceRequest::TargetIsPing);
     request.setHTTPHeaderField("Cache-Control", "max-age=0");
-    String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), request.url(), frame->loader().outgoingReferrer());
-    if (!referrer.isEmpty())
-        request.setHTTPReferrer(referrer);
-    frame->loader().addExtraFieldsToRequest(request);
-    OwnPtr<PingLoader> pingLoader = adoptPtr(new PingLoader(frame, request));
+    frame->loader().fetchContext().addAdditionalRequestHeaders(frame->document(), request, FetchSubresource);
 
-    // Leak the ping loader, since it will kill itself as soon as it receives a response.
-    PingLoader* ALLOW_UNUSED leakedPingLoader = pingLoader.leakPtr();
+    FetchInitiatorInfo initiatorInfo;
+    initiatorInfo.name = FetchInitiatorTypeNames::ping;
+    PingLoader::start(frame, request, initiatorInfo);
 }
 
 // http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing
@@ -79,24 +81,24 @@
     request.setHTTPContentType("text/ping");
     request.setHTTPBody(FormData::create("PING"));
     request.setHTTPHeaderField("Cache-Control", "max-age=0");
-    frame->loader().addExtraFieldsToRequest(request);
+    frame->loader().fetchContext().addAdditionalRequestHeaders(frame->document(), request, FetchSubresource);
 
-    SecurityOrigin* sourceOrigin = frame->document()->securityOrigin();
     RefPtr<SecurityOrigin> pingOrigin = SecurityOrigin::create(pingURL);
-    FrameLoader::addHTTPOriginIfNeeded(request, sourceOrigin->toString());
-    request.setHTTPHeaderField("Ping-To", destinationURL.string());
-    if (!SecurityPolicy::shouldHideReferrer(pingURL, frame->loader().outgoingReferrer())) {
-        request.setHTTPHeaderField("Ping-From", frame->document()->url().string());
-        if (!sourceOrigin->isSameSchemeHostPort(pingOrigin.get())) {
-            String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), pingURL, frame->loader().outgoingReferrer());
-            if (!referrer.isEmpty())
-                request.setHTTPReferrer(referrer);
-        }
-    }
-    OwnPtr<PingLoader> pingLoader = adoptPtr(new PingLoader(frame, request));
+    // addAdditionalRequestHeaders() will have added a referrer for same origin requests,
+    // but the spec omits the referrer for same origin.
+    if (frame->document()->securityOrigin()->isSameSchemeHostPort(pingOrigin.get()))
+        request.clearHTTPReferrer();
 
-    // Leak the ping loader, since it will kill itself as soon as it receives a response.
-    PingLoader* ALLOW_UNUSED leakedPingLoader = pingLoader.leakPtr();
+    request.setHTTPHeaderField("Ping-To", AtomicString(destinationURL.string()));
+
+    // Ping-From follows the same rules as the default referrer beahavior for subresource requests.
+    // FIXME: Should Ping-From obey ReferrerPolicy?
+    if (!SecurityPolicy::shouldHideReferrer(pingURL, frame->document()->url().string()))
+        request.setHTTPHeaderField("Ping-From", AtomicString(frame->document()->url().string()));
+
+    FetchInitiatorInfo initiatorInfo;
+    initiatorInfo.name = FetchInitiatorTypeNames::ping;
+    PingLoader::start(frame, request, initiatorInfo);
 }
 
 void PingLoader::sendViolationReport(Frame* frame, const KURL& reportURL, PassRefPtr<FormData> report, ViolationReportType type)
@@ -106,30 +108,36 @@
     request.setHTTPMethod("POST");
     request.setHTTPContentType(type == ContentSecurityPolicyViolationReport ? "application/csp-report" : "application/json");
     request.setHTTPBody(report);
-    frame->loader().addExtraFieldsToRequest(request);
+    frame->loader().fetchContext().addAdditionalRequestHeaders(frame->document(), request, FetchSubresource);
 
-    String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), reportURL, frame->loader().outgoingReferrer());
-    if (!referrer.isEmpty())
-        request.setHTTPReferrer(referrer);
-    OwnPtr<PingLoader> pingLoader = adoptPtr(new PingLoader(frame, request, SecurityOrigin::create(reportURL)->isSameSchemeHostPort(frame->document()->securityOrigin()) ? AllowStoredCredentials : DoNotAllowStoredCredentials));
+    FetchInitiatorInfo initiatorInfo;
+    initiatorInfo.name = FetchInitiatorTypeNames::violationreport;
+    PingLoader::start(frame, request, initiatorInfo, SecurityOrigin::create(reportURL)->isSameSchemeHostPort(frame->document()->securityOrigin()) ? AllowStoredCredentials : DoNotAllowStoredCredentials);
+}
+
+void PingLoader::start(Frame* frame, ResourceRequest& request, const FetchInitiatorInfo& initiatorInfo, StoredCredentials credentialsAllowed)
+{
+    OwnPtr<PingLoader> pingLoader = adoptPtr(new PingLoader(frame, request, initiatorInfo, credentialsAllowed));
 
     // Leak the ping loader, since it will kill itself as soon as it receives a response.
     PingLoader* ALLOW_UNUSED leakedPingLoader = pingLoader.leakPtr();
 }
 
-PingLoader::PingLoader(Frame* frame, ResourceRequest& request, StoredCredentials credentialsAllowed)
-    : m_timeout(this, &PingLoader::timeout)
+PingLoader::PingLoader(Frame* frame, ResourceRequest& request, const FetchInitiatorInfo& initiatorInfo, StoredCredentials credentialsAllowed)
+    : PageLifecycleObserver(frame->page())
+    , m_timeout(this, &PingLoader::timeout)
+    , m_url(request.url())
+    , m_identifier(createUniqueIdentifier())
 {
     frame->loader().client()->didDispatchPingLoader(request.url());
 
-    unsigned long identifier = createUniqueIdentifier();
     m_loader = adoptPtr(blink::Platform::current()->createURLLoader());
     ASSERT(m_loader);
     blink::WrappedResourceRequest wrappedRequest(request);
     wrappedRequest.setAllowStoredCredentials(credentialsAllowed == AllowStoredCredentials);
     m_loader->loadAsynchronously(wrappedRequest, this);
 
-    InspectorInstrumentation::continueAfterPingLoader(frame, identifier, frame->loader().activeDocumentLoader(), request, ResourceResponse());
+    InspectorInstrumentation::willSendRequest(frame, m_identifier, frame->loader().documentLoader(), request, ResourceResponse(), initiatorInfo);
 
     // If the server never responds, FrameLoader won't be able to cancel this load and
     // we'll sit here waiting forever. Set a very generous timeout, just in case.
@@ -142,4 +150,39 @@
         m_loader->cancel();
 }
 
+void PingLoader::didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse&)
+{
+    if (Page* page = this->page())
+        InspectorInstrumentation::didFailLoading(page->mainFrame(), m_identifier, ResourceError::cancelledError(m_url));
+    delete this;
+}
+
+void PingLoader::didReceiveData(blink::WebURLLoader*, const char* data, int dataLength, int encodedDataLength)
+{
+    if (Page* page = this->page())
+        InspectorInstrumentation::didFailLoading(page->mainFrame(), m_identifier, ResourceError::cancelledError(m_url));
+    delete this;
+}
+
+void PingLoader::didFinishLoading(blink::WebURLLoader*, double, int64_t)
+{
+    if (Page* page = this->page())
+        InspectorInstrumentation::didFailLoading(page->mainFrame(), m_identifier, ResourceError::cancelledError(m_url));
+    delete this;
+}
+
+void PingLoader::didFail(blink::WebURLLoader*, const blink::WebURLError& resourceError)
+{
+    if (Page* page = this->page())
+        InspectorInstrumentation::didFailLoading(page->mainFrame(), m_identifier, ResourceError(resourceError));
+    delete this;
+}
+
+void PingLoader::timeout(Timer<PingLoader>*)
+{
+    if (Page* page = this->page())
+        InspectorInstrumentation::didFailLoading(page->mainFrame(), m_identifier, ResourceError::cancelledError(m_url));
+    delete this;
+}
+
 }
diff --git a/Source/core/loader/PingLoader.h b/Source/core/loader/PingLoader.h
index e22f84c..5651aa2 100644
--- a/Source/core/loader/PingLoader.h
+++ b/Source/core/loader/PingLoader.h
@@ -33,6 +33,7 @@
 #define PingLoader_h
 
 #include "core/fetch/ResourceLoaderOptions.h"
+#include "core/page/PageLifecycleObserver.h"
 #include "platform/Timer.h"
 #include "public/platform/WebURLLoaderClient.h"
 #include "wtf/Noncopyable.h"
@@ -53,7 +54,7 @@
 // to allow the load to live long enough to ensure the message was actually sent.
 // Therefore, as soon as a callback is received from the ResourceHandle, this class
 // will cancel the load and delete itself.
-class PingLoader : private blink::WebURLLoaderClient {
+class PingLoader FINAL : public PageLifecycleObserver, private blink::WebURLLoaderClient {
     WTF_MAKE_NONCOPYABLE(PingLoader); WTF_MAKE_FAST_ALLOCATED;
 public:
     enum ViolationReportType {
@@ -68,16 +69,21 @@
     virtual ~PingLoader();
 
 private:
-    PingLoader(Frame*, ResourceRequest&, StoredCredentials = AllowStoredCredentials);
+    PingLoader(Frame*, ResourceRequest&, const FetchInitiatorInfo&, StoredCredentials);
 
-    virtual void didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse&) OVERRIDE { delete this; }
-    virtual void didReceiveData(blink::WebURLLoader*, const char*, int, int) OVERRIDE { delete this; }
-    virtual void didFinishLoading(blink::WebURLLoader*, double) OVERRIDE { delete this; }
-    virtual void didFail(blink::WebURLLoader*, const blink::WebURLError&) OVERRIDE { delete this; }
-    void timeout(Timer<PingLoader>*) { delete this; }
+    static void start(Frame*, ResourceRequest&, const FetchInitiatorInfo&, StoredCredentials = AllowStoredCredentials);
+
+    virtual void didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse&) OVERRIDE;
+    virtual void didReceiveData(blink::WebURLLoader*, const char*, int, int) OVERRIDE;
+    virtual void didFinishLoading(blink::WebURLLoader*, double, int64_t) OVERRIDE;
+    virtual void didFail(blink::WebURLLoader*, const blink::WebURLError&) OVERRIDE;
+
+    void timeout(Timer<PingLoader>*);
 
     OwnPtr<blink::WebURLLoader> m_loader;
     Timer<PingLoader> m_timeout;
+    String m_url;
+    unsigned long m_identifier;
 };
 
 }
diff --git a/Source/core/loader/PrerenderHandle.cpp b/Source/core/loader/PrerenderHandle.cpp
index b00c785..e822ff5 100644
--- a/Source/core/loader/PrerenderHandle.cpp
+++ b/Source/core/loader/PrerenderHandle.cpp
@@ -42,7 +42,7 @@
 namespace WebCore {
 
 // static
-PassOwnPtr<PrerenderHandle> PrerenderHandle::create(Document& document, PrerenderClient* client, const KURL& url)
+PassOwnPtr<PrerenderHandle> PrerenderHandle::create(Document& document, PrerenderClient* client, const KURL& url, const unsigned prerenderRelTypes)
 {
     // Prerenders are unlike requests in most ways (for instance, they pass down fragments, and they don't return data),
     // but they do have referrers.
@@ -51,9 +51,9 @@
     if (!document.frame())
         return PassOwnPtr<PrerenderHandle>();
 
-    const String referrer = SecurityPolicy::generateReferrerHeader(referrerPolicy, url, document.frame()->loader().outgoingReferrer());
+    const String referrer = SecurityPolicy::generateReferrerHeader(referrerPolicy, url, document.outgoingReferrer());
 
-    RefPtr<Prerender> prerender = Prerender::create(client, url, referrer, referrerPolicy);
+    RefPtr<Prerender> prerender = Prerender::create(client, url, prerenderRelTypes, referrer, referrerPolicy);
 
     PrerendererClient* prerendererClient = PrerendererClient::from(document.page());
     if (prerendererClient)
diff --git a/Source/core/loader/PrerenderHandle.h b/Source/core/loader/PrerenderHandle.h
index 2adc058..6c484af 100644
--- a/Source/core/loader/PrerenderHandle.h
+++ b/Source/core/loader/PrerenderHandle.h
@@ -43,10 +43,10 @@
 class Prerender;
 class PrerenderClient;
 
-class PrerenderHandle : public DocumentLifecycleObserver {
+class PrerenderHandle FINAL : public DocumentLifecycleObserver {
     WTF_MAKE_NONCOPYABLE(PrerenderHandle);
 public:
-    static PassOwnPtr<PrerenderHandle> create(Document&, PrerenderClient*, const KURL&);
+    static PassOwnPtr<PrerenderHandle> create(Document&, PrerenderClient*, const KURL&, unsigned prerenderRelTypes);
 
     virtual ~PrerenderHandle();
 
diff --git a/Source/core/loader/ProgressTracker.cpp b/Source/core/loader/ProgressTracker.cpp
index df7477c..b96844a 100644
--- a/Source/core/loader/ProgressTracker.cpp
+++ b/Source/core/loader/ProgressTracker.cpp
@@ -104,14 +104,14 @@
 
 void ProgressTracker::progressStarted(Frame* frame)
 {
-    WTF_LOG(Progress, "Progress started (%p) - frame %p(\"%s\"), value %f, tracked frames %d, originating frame %p", this, frame, frame->tree().uniqueName().string().utf8().data(), m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
+    WTF_LOG(Progress, "Progress started (%p) - frame %p(\"%s\"), value %f, tracked frames %d, originating frame %p", this, frame, frame->tree().uniqueName().utf8().data(), m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
 
     if (m_numProgressTrackedFrames == 0 || m_originatingProgressFrame == frame) {
         reset();
         m_progressValue = initialProgressValue;
         m_originatingProgressFrame = frame;
 
-        m_originatingProgressFrame->loader().client()->postProgressStartedNotification();
+        m_originatingProgressFrame->loader().client()->postProgressStartedNotification(NavigationToDifferentDocument);
     }
     m_numProgressTrackedFrames++;
     InspectorInstrumentation::frameStartedLoading(frame);
@@ -119,7 +119,7 @@
 
 void ProgressTracker::progressCompleted(Frame* frame)
 {
-    WTF_LOG(Progress, "Progress completed (%p) - frame %p(\"%s\"), value %f, tracked frames %d, originating frame %p", this, frame, frame->tree().uniqueName().string().utf8().data(), m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
+    WTF_LOG(Progress, "Progress completed (%p) - frame %p(\"%s\"), value %f, tracked frames %d, originating frame %p", this, frame, frame->tree().uniqueName().utf8().data(), m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
 
     if (m_numProgressTrackedFrames <= 0)
         return;
diff --git a/Source/core/loader/ProgressTracker.h b/Source/core/loader/ProgressTracker.h
index f7516c7..c6d73af 100644
--- a/Source/core/loader/ProgressTracker.h
+++ b/Source/core/loader/ProgressTracker.h
@@ -26,6 +26,7 @@
 #ifndef ProgressTracker_h
 #define ProgressTracker_h
 
+#include "wtf/FastAllocBase.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
@@ -38,6 +39,9 @@
 class ResourceResponse;
 struct ProgressItem;
 
+// FIXME: This is only used on Android. Android is the only Chrome
+// browser which shows a progress bar during loading.
+// We should find a better way for Android to get this data and remove this!
 class ProgressTracker {
     WTF_MAKE_NONCOPYABLE(ProgressTracker); WTF_MAKE_FAST_ALLOCATED;
 public:
diff --git a/Source/core/loader/SinkDocument.h b/Source/core/loader/SinkDocument.h
index 3421775..7a0f0ec 100644
--- a/Source/core/loader/SinkDocument.h
+++ b/Source/core/loader/SinkDocument.h
@@ -40,7 +40,7 @@
 private:
     SinkDocument(const DocumentInit&);
 
-    virtual PassRefPtr<DocumentParser> createParser();
+    virtual PassRefPtr<DocumentParser> createParser() OVERRIDE;
 };
 
 
diff --git a/Source/core/loader/SubstituteData.h b/Source/core/loader/SubstituteData.h
index 48f1928..82a1398 100644
--- a/Source/core/loader/SubstituteData.h
+++ b/Source/core/loader/SubstituteData.h
@@ -33,32 +33,42 @@
 
 namespace WebCore {
 
-    class SubstituteData {
-    public:
-        SubstituteData() { }
+enum SubstituteDataLoadPolicy {
+    LoadNormally,
+    ForceSynchronousLoad
+};
 
-        SubstituteData(PassRefPtr<SharedBuffer> content, const AtomicString& mimeType, const AtomicString& textEncoding, const KURL& failingURL)
-            : m_content(content)
-            , m_mimeType(mimeType)
-            , m_textEncoding(textEncoding)
-            , m_failingURL(failingURL)
-        {
-        }
+class SubstituteData {
+public:
+    SubstituteData()
+        : m_substituteDataLoadPolicy(LoadNormally)
+    {
+    }
 
-        bool isValid() const { return m_content != 0; }
+    SubstituteData(PassRefPtr<SharedBuffer> content, const AtomicString& mimeType, const AtomicString& textEncoding, const KURL& failingURL, SubstituteDataLoadPolicy substituteDataLoadPolicy = LoadNormally)
+        : m_content(content)
+        , m_mimeType(mimeType)
+        , m_textEncoding(textEncoding)
+        , m_failingURL(failingURL)
+        , m_substituteDataLoadPolicy(substituteDataLoadPolicy)
+    {
+    }
 
-        const SharedBuffer* content() const { return m_content.get(); }
-        const AtomicString& mimeType() const { return m_mimeType; }
-        const AtomicString& textEncoding() const { return m_textEncoding; }
-        const KURL& failingURL() const { return m_failingURL; }
+    bool isValid() const { return m_content; }
 
-    private:
-        RefPtr<SharedBuffer> m_content;
-        AtomicString m_mimeType;
-        AtomicString m_textEncoding;
-        KURL m_failingURL;
-        KURL m_responseURL;
-    };
+    SharedBuffer* content() const { return m_content.get(); }
+    const AtomicString& mimeType() const { return m_mimeType; }
+    const AtomicString& textEncoding() const { return m_textEncoding; }
+    const KURL& failingURL() const { return m_failingURL; }
+    bool forceSynchronousLoad() const { return m_substituteDataLoadPolicy == ForceSynchronousLoad; }
+
+private:
+    RefPtr<SharedBuffer> m_content;
+    AtomicString m_mimeType;
+    AtomicString m_textEncoding;
+    KURL m_failingURL;
+    SubstituteDataLoadPolicy m_substituteDataLoadPolicy;
+};
 
 }
 
diff --git a/Source/core/loader/TextResourceDecoderBuilder.cpp b/Source/core/loader/TextResourceDecoderBuilder.cpp
index b1843b2..ff4002a 100644
--- a/Source/core/loader/TextResourceDecoderBuilder.cpp
+++ b/Source/core/loader/TextResourceDecoderBuilder.cpp
@@ -33,7 +33,7 @@
 
 #include "core/dom/Document.h"
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/weborigin/SecurityOrigin.h"
 
 namespace WebCore {
diff --git a/Source/core/loader/TextResourceDecoderBuilder.h b/Source/core/loader/TextResourceDecoderBuilder.h
index b6c27c7..8e89f3c 100644
--- a/Source/core/loader/TextResourceDecoderBuilder.h
+++ b/Source/core/loader/TextResourceDecoderBuilder.h
@@ -31,7 +31,7 @@
 #ifndef TextResourceDecoderBuilder_h
 #define TextResourceDecoderBuilder_h
 
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/loader/TextTrackLoader.cpp b/Source/core/loader/TextTrackLoader.cpp
index ce95150..a6691c2 100644
--- a/Source/core/loader/TextTrackLoader.cpp
+++ b/Source/core/loader/TextTrackLoader.cpp
@@ -49,8 +49,6 @@
 
 TextTrackLoader::~TextTrackLoader()
 {
-    if (m_resource)
-        m_resource->removeClient(this);
 }
 
 void TextTrackLoader::cueLoadTimerFired(Timer<TextTrackLoader>* timer)
@@ -68,15 +66,12 @@
 
 void TextTrackLoader::cancelLoad()
 {
-    if (m_resource) {
-        m_resource->removeClient(this);
-        m_resource = 0;
-    }
+    clearResource();
 }
 
 void TextTrackLoader::dataReceived(Resource* resource, const char* data, int length)
 {
-    ASSERT(m_resource == resource);
+    ASSERT(this->resource() == resource);
 
     if (m_state == Failed)
         return;
@@ -87,24 +82,16 @@
     m_cueParser->parseBytes(data, length);
 }
 
-void TextTrackLoader::corsPolicyPreventedLoad()
+void TextTrackLoader::corsPolicyPreventedLoad(SecurityOrigin* securityOrigin, const KURL& url)
 {
-    DEFINE_STATIC_LOCAL(String, consoleMessage, ("Cross-origin text track load denied by Cross-Origin Resource Sharing policy."));
+    String consoleMessage("Text track from origin '" + SecurityOrigin::create(url)->toString() + "' has been blocked from loading: Not at same origin as the document, and parent of track element does not have a 'crossorigin' attribute. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.");
     m_document.addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
     m_state = Failed;
 }
 
 void TextTrackLoader::notifyFinished(Resource* resource)
 {
-    ASSERT(m_resource == resource);
-
-    if (!m_crossOriginMode.isNull()
-        && !m_document.securityOrigin()->canRequest(resource->response().url())
-        && !resource->passesAccessControlCheck(m_document.securityOrigin())) {
-
-        corsPolicyPreventedLoad();
-    }
-
+    ASSERT(this->resource() == resource);
     if (m_state != Failed)
         m_state = resource->errorOccurred() ? Failed : Finished;
 
@@ -117,30 +104,23 @@
     cancelLoad();
 }
 
-bool TextTrackLoader::load(const KURL& url, const String& crossOriginMode)
+bool TextTrackLoader::load(const KURL& url, const AtomicString& crossOriginMode)
 {
     cancelLoad();
 
     FetchRequest cueRequest(ResourceRequest(m_document.completeURL(url)), FetchInitiatorTypeNames::texttrack);
 
     if (!crossOriginMode.isNull()) {
-        m_crossOriginMode = crossOriginMode;
-        StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
-        updateRequestForAccessControl(cueRequest.mutableResourceRequest(), m_document.securityOrigin(), allowCredentials);
-    } else {
-        // Cross-origin resources that are not suitably CORS-enabled may not load.
-        if (!m_document.securityOrigin()->canRequest(url)) {
-            corsPolicyPreventedLoad();
-            return false;
-        }
+        cueRequest.setCrossOriginAccessControl(m_document.securityOrigin(), crossOriginMode);
+    } else if (!m_document.securityOrigin()->canRequest(url)) {
+        // Text track elements without 'crossorigin' set on the parent are "No CORS"; report error if not same-origin.
+        corsPolicyPreventedLoad(m_document.securityOrigin(), url);
+        return false;
     }
 
     ResourceFetcher* fetcher = m_document.fetcher();
-    m_resource = fetcher->fetchRawResource(cueRequest);
-    if (!m_resource)
-        return false;
-    m_resource->addClient(this);
-    return true;
+    setResource(fetcher->fetchRawResource(cueRequest));
+    return resource();
 }
 
 void TextTrackLoader::newCuesParsed()
diff --git a/Source/core/loader/TextTrackLoader.h b/Source/core/loader/TextTrackLoader.h
index e9bcfcc..e2fcaed 100644
--- a/Source/core/loader/TextTrackLoader.h
+++ b/Source/core/loader/TextTrackLoader.h
@@ -27,7 +27,7 @@
 #define TextTrackLoader_h
 
 #include "core/fetch/RawResource.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
 #include "core/html/track/vtt/VTTParser.h"
 #include "platform/Timer.h"
 #include "wtf/OwnPtr.h"
@@ -37,7 +37,7 @@
 class Document;
 class TextTrackLoader;
 
-class TextTrackLoaderClient {
+class TextTrackLoaderClient : public ResourceOwner<RawResource> {
 public:
     virtual ~TextTrackLoaderClient() { }
 
@@ -46,7 +46,7 @@
     virtual void newRegionsAvailable(TextTrackLoader*) = 0;
 };
 
-class TextTrackLoader : public RawResourceClient, private VTTParserClient {
+class TextTrackLoader FINAL : public ResourceOwner<RawResource>, private VTTParserClient {
     WTF_MAKE_NONCOPYABLE(TextTrackLoader);
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -56,7 +56,7 @@
     }
     virtual ~TextTrackLoader();
 
-    bool load(const KURL&, const String& crossOriginMode);
+    bool load(const KURL&, const AtomicString& crossOriginMode);
     void cancelLoad();
 
     enum State { Idle, Loading, Finished, Failed };
@@ -78,15 +78,13 @@
     TextTrackLoader(TextTrackLoaderClient&, Document&);
 
     void cueLoadTimerFired(Timer<TextTrackLoader>*);
-    void corsPolicyPreventedLoad();
+    void corsPolicyPreventedLoad(SecurityOrigin*, const KURL&);
 
     TextTrackLoaderClient& m_client;
     OwnPtr<VTTParser> m_cueParser;
-    ResourcePtr<RawResource> m_resource;
     // FIXME: Remove this pointer and get the Document from m_client.
     Document& m_document;
     Timer<TextTrackLoader> m_cueLoadTimer;
-    String m_crossOriginMode;
     State m_state;
     bool m_newCuesAvailable;
 };
diff --git a/Source/core/loader/ThreadableLoader.cpp b/Source/core/loader/ThreadableLoader.cpp
index 476f915..1abd564 100644
--- a/Source/core/loader/ThreadableLoader.cpp
+++ b/Source/core/loader/ThreadableLoader.cpp
@@ -34,9 +34,12 @@
 #include "core/dom/Document.h"
 #include "core/dom/ExecutionContext.h"
 #include "core/loader/DocumentThreadableLoader.h"
+#include "core/loader/ThreadableLoaderClientWrapper.h"
+#include "core/loader/WorkerLoaderClientBridge.h"
 #include "core/loader/WorkerThreadableLoader.h"
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerRunLoop.h"
+#include "core/workers/WorkerThread.h"
 
 namespace WebCore {
 
@@ -45,8 +48,12 @@
     ASSERT(client);
     ASSERT(context);
 
-    if (context->isWorkerGlobalScope())
-        return WorkerThreadableLoader::create(toWorkerGlobalScope(context), client, WorkerRunLoop::defaultMode(), request, options);
+    if (context->isWorkerGlobalScope()) {
+        WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
+        RefPtr<ThreadableLoaderClientWrapper> clientWrapper(ThreadableLoaderClientWrapper::create(client));
+        OwnPtr<ThreadableLoaderClient> clientBridge(WorkerLoaderClientBridge::create(clientWrapper, workerGlobalScope->thread()->workerLoaderProxy()));
+        return WorkerThreadableLoader::create(workerGlobalScope, clientWrapper, clientBridge.release(), request, options);
+    }
 
     return DocumentThreadableLoader::create(toDocument(context), client, request, options);
 }
diff --git a/Source/core/loader/ThreadableLoaderClient.h b/Source/core/loader/ThreadableLoaderClient.h
index 152aa68..0604120 100644
--- a/Source/core/loader/ThreadableLoaderClient.h
+++ b/Source/core/loader/ThreadableLoaderClient.h
@@ -56,9 +56,10 @@
 
         virtual void didDownloadData(int /*dataLength*/) { }
 
+        virtual ~ThreadableLoaderClient() { }
+
     protected:
         ThreadableLoaderClient() { }
-        virtual ~ThreadableLoaderClient() { }
     };
 
 } // namespace WebCore
diff --git a/Source/core/loader/ThreadableLoaderClientWrapper.h b/Source/core/loader/ThreadableLoaderClientWrapper.h
index 22a7e99..56da8f8 100644
--- a/Source/core/loader/ThreadableLoaderClientWrapper.h
+++ b/Source/core/loader/ThreadableLoaderClientWrapper.h
@@ -34,6 +34,7 @@
 #include "core/loader/ThreadableLoaderClient.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/PassRefPtr.h"
+#include "wtf/ThreadSafeRefCounted.h"
 #include "wtf/Threading.h"
 
 namespace WebCore {
diff --git a/Source/core/loader/WorkerLoaderClientBridge.cpp b/Source/core/loader/WorkerLoaderClientBridge.cpp
new file mode 100644
index 0000000..c73d1e6
--- /dev/null
+++ b/Source/core/loader/WorkerLoaderClientBridge.cpp
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/loader/WorkerLoaderClientBridge.h"
+
+#include "core/dom/CrossThreadTask.h"
+#include "core/loader/ThreadableLoaderClientWrapper.h"
+#include "core/workers/WorkerGlobalScope.h"
+#include "core/workers/WorkerLoaderProxy.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+PassOwnPtr<ThreadableLoaderClient> WorkerLoaderClientBridge::create(PassRefPtr<ThreadableLoaderClientWrapper> client, WorkerLoaderProxy& loaderProxy)
+{
+    return adoptPtr(new WorkerLoaderClientBridge(client, loaderProxy));
+}
+
+WorkerLoaderClientBridge::~WorkerLoaderClientBridge()
+{
+}
+
+static void workerGlobalScopeDidSendData(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
+{
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+    workerClientWrapper->didSendData(bytesSent, totalBytesToBeSent);
+}
+
+void WorkerLoaderClientBridge::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
+{
+    m_loaderProxy.postTaskToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent));
+}
+
+static void workerGlobalScopeDidReceiveResponse(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
+{
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+    OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
+    workerClientWrapper->didReceiveResponse(identifier, *response);
+}
+
+void WorkerLoaderClientBridge::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
+{
+    m_loaderProxy.postTaskToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveResponse, m_workerClientWrapper, identifier, response));
+}
+
+static void workerGlobalScopeDidReceiveData(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
+{
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+    workerClientWrapper->didReceiveData(vectorData->data(), vectorData->size());
+}
+
+void WorkerLoaderClientBridge::didReceiveData(const char* data, int dataLength)
+{
+    OwnPtr<Vector<char> > vector = adoptPtr(new Vector<char>(dataLength)); // needs to be an OwnPtr for usage with createCallbackTask.
+    memcpy(vector->data(), data, dataLength);
+    m_loaderProxy.postTaskToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveData, m_workerClientWrapper, vector.release()));
+}
+
+static void workerGlobalScopeDidDownloadData(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, int dataLength)
+{
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+    workerClientWrapper->didDownloadData(dataLength);
+}
+
+void WorkerLoaderClientBridge::didDownloadData(int dataLength)
+{
+    m_loaderProxy.postTaskToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidDownloadData, m_workerClientWrapper, dataLength));
+}
+
+static void workerGlobalScopeDidReceiveCachedMetadata(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
+{
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+    workerClientWrapper->didReceiveCachedMetadata(vectorData->data(), vectorData->size());
+}
+
+void WorkerLoaderClientBridge::didReceiveCachedMetadata(const char* data, int dataLength)
+{
+    OwnPtr<Vector<char> > vector = adoptPtr(new Vector<char>(dataLength)); // needs to be an OwnPtr for usage with createCallbackTask.
+    memcpy(vector->data(), data, dataLength);
+    m_loaderProxy.postTaskToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveCachedMetadata, m_workerClientWrapper, vector.release()));
+}
+
+static void workerGlobalScopeDidFinishLoading(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, double finishTime)
+{
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+    workerClientWrapper->didFinishLoading(identifier, finishTime);
+}
+
+void WorkerLoaderClientBridge::didFinishLoading(unsigned long identifier, double finishTime)
+{
+    m_loaderProxy.postTaskToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFinishLoading, m_workerClientWrapper, identifier, finishTime));
+}
+
+static void workerGlobalScopeDidFail(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
+{
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+    workerClientWrapper->didFail(error);
+}
+
+void WorkerLoaderClientBridge::didFail(const ResourceError& error)
+{
+    m_loaderProxy.postTaskToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFail, m_workerClientWrapper, error));
+}
+
+static void workerGlobalScopeDidFailAccessControlCheck(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
+{
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+    workerClientWrapper->didFailAccessControlCheck(error);
+}
+
+void WorkerLoaderClientBridge::didFailAccessControlCheck(const ResourceError& error)
+{
+    m_loaderProxy.postTaskToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFailAccessControlCheck, m_workerClientWrapper, error));
+}
+
+static void workerGlobalScopeDidFailRedirectCheck(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper)
+{
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+    workerClientWrapper->didFailRedirectCheck();
+}
+
+void WorkerLoaderClientBridge::didFailRedirectCheck()
+{
+    m_loaderProxy.postTaskToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFailRedirectCheck, m_workerClientWrapper));
+}
+
+WorkerLoaderClientBridge::WorkerLoaderClientBridge(PassRefPtr<ThreadableLoaderClientWrapper> clientWrapper, WorkerLoaderProxy& loaderProxy)
+    : m_workerClientWrapper(clientWrapper)
+    , m_loaderProxy(loaderProxy)
+{
+}
+
+} // namespace WebCore
diff --git a/Source/core/loader/WorkerLoaderClientBridge.h b/Source/core/loader/WorkerLoaderClientBridge.h
new file mode 100644
index 0000000..50242f4
--- /dev/null
+++ b/Source/core/loader/WorkerLoaderClientBridge.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef WorkerLoaderClientBridge_h
+#define WorkerLoaderClientBridge_h
+
+#include "core/loader/ThreadableLoaderClient.h"
+#include "wtf/Forward.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class ThreadableLoaderClientWrapper;
+class WorkerLoaderProxy;
+
+// This bridge is created and destroyed on the worker thread, but is
+// passed to and used on the main thread. Each did* method relays the given
+// data to the client wrapper on the worker context thread.
+class WorkerLoaderClientBridge : public ThreadableLoaderClient {
+public:
+    static PassOwnPtr<ThreadableLoaderClient> create(PassRefPtr<ThreadableLoaderClientWrapper>, WorkerLoaderProxy&);
+    virtual ~WorkerLoaderClientBridge();
+
+    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
+    virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&) OVERRIDE;
+    virtual void didReceiveData(const char*, int dataLength) OVERRIDE;
+    virtual void didDownloadData(int dataLength) OVERRIDE;
+    virtual void didReceiveCachedMetadata(const char*, int dataLength) OVERRIDE;
+    virtual void didFinishLoading(unsigned long identifier, double finishTime) OVERRIDE;
+    virtual void didFail(const ResourceError&) OVERRIDE;
+    virtual void didFailAccessControlCheck(const ResourceError&) OVERRIDE;
+    virtual void didFailRedirectCheck() OVERRIDE;
+
+private:
+    WorkerLoaderClientBridge(PassRefPtr<ThreadableLoaderClientWrapper>, WorkerLoaderProxy&);
+
+    // Used on the worker context thread, while its refcounting is done on
+    // either thread.
+    RefPtr<ThreadableLoaderClientWrapper> m_workerClientWrapper;
+
+    WorkerLoaderProxy& m_loaderProxy;
+};
+
+} // namespace WebCore
+
+#endif // WorkerLoaderClientBridge_h
diff --git a/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.cpp b/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.cpp
new file mode 100644
index 0000000..451442a
--- /dev/null
+++ b/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.cpp
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/loader/WorkerLoaderClientBridgeSyncHelper.h"
+
+#include "core/workers/WorkerGlobalScope.h"
+#include "core/workers/WorkerLoaderProxy.h"
+#include "public/platform/WebWaitableEvent.h"
+#include "wtf/ArrayBuffer.h"
+#include "wtf/Functional.h"
+#include "wtf/MainThread.h"
+#include "wtf/OwnPtr.h"
+
+namespace WebCore {
+
+PassOwnPtr<WorkerLoaderClientBridgeSyncHelper> WorkerLoaderClientBridgeSyncHelper::create(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
+{
+    return adoptPtr(new WorkerLoaderClientBridgeSyncHelper(client, event));
+}
+
+WorkerLoaderClientBridgeSyncHelper::~WorkerLoaderClientBridgeSyncHelper()
+{
+    ASSERT(isMainThread());
+    for (size_t i = 0; i < m_receivedData.size(); ++i)
+        delete m_receivedData[i];
+}
+
+void WorkerLoaderClientBridgeSyncHelper::run()
+{
+    // This must be called only after m_event is signalled.
+    ASSERT(m_done);
+    for (size_t i = 0; i < m_clientTasks.size(); ++i)
+        m_clientTasks[i]();
+}
+
+void WorkerLoaderClientBridgeSyncHelper::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
+{
+    ASSERT(isMainThread());
+    m_clientTasks.append(bind(&ThreadableLoaderClient::didSendData, &m_client, bytesSent, totalBytesToBeSent));
+}
+
+static void didReceiveResponseAdapter(ThreadableLoaderClient* client, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
+{
+    OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
+    client->didReceiveResponse(identifier, *response);
+}
+
+void WorkerLoaderClientBridgeSyncHelper::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
+{
+    ASSERT(isMainThread());
+    m_clientTasks.append(bind(&didReceiveResponseAdapter, &m_client, identifier, response.copyData()));
+}
+
+void WorkerLoaderClientBridgeSyncHelper::didReceiveData(const char* data, int dataLength)
+{
+    ASSERT(isMainThread());
+    Vector<char>* buffer = new Vector<char>(dataLength);
+    memcpy(buffer->data(), data, dataLength);
+    m_receivedData.append(buffer);
+    m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveData, &m_client, static_cast<const char*>(buffer->data()), dataLength));
+}
+
+void WorkerLoaderClientBridgeSyncHelper::didDownloadData(int dataLength)
+{
+    ASSERT(isMainThread());
+    m_clientTasks.append(bind(&ThreadableLoaderClient::didDownloadData, &m_client, dataLength));
+}
+
+void WorkerLoaderClientBridgeSyncHelper::didReceiveCachedMetadata(const char* data, int dataLength)
+{
+    ASSERT(isMainThread());
+    Vector<char>* buffer = new Vector<char>(dataLength);
+    memcpy(buffer->data(), data, dataLength);
+    m_receivedData.append(buffer);
+    m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveCachedMetadata, &m_client, static_cast<const char*>(buffer->data()), dataLength));
+}
+
+void WorkerLoaderClientBridgeSyncHelper::didFinishLoading(unsigned long identifier, double finishTime)
+{
+    ASSERT(isMainThread());
+    m_clientTasks.append(bind(&ThreadableLoaderClient::didFinishLoading, &m_client, identifier, finishTime));
+    m_done = true;
+    m_event->signal();
+}
+
+void WorkerLoaderClientBridgeSyncHelper::didFail(const ResourceError& error)
+{
+    ASSERT(isMainThread());
+    m_clientTasks.append(bind(&ThreadableLoaderClient::didFail, &m_client, error));
+    m_done = true;
+    m_event->signal();
+}
+
+void WorkerLoaderClientBridgeSyncHelper::didFailAccessControlCheck(const ResourceError& error)
+{
+    ASSERT(isMainThread());
+    m_clientTasks.append(bind(&ThreadableLoaderClient::didFailAccessControlCheck, &m_client, error));
+    m_done = true;
+    m_event->signal();
+}
+
+void WorkerLoaderClientBridgeSyncHelper::didFailRedirectCheck()
+{
+    ASSERT(isMainThread());
+    m_clientTasks.append(bind(&ThreadableLoaderClient::didFailRedirectCheck, &m_client));
+    m_done = true;
+    m_event->signal();
+}
+
+WorkerLoaderClientBridgeSyncHelper::WorkerLoaderClientBridgeSyncHelper(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
+    : m_done(false)
+    , m_client(client)
+    , m_event(event)
+{
+    ASSERT(m_event);
+}
+
+} // namespace WebCore
diff --git a/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.h b/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.h
new file mode 100644
index 0000000..7ab1cf6
--- /dev/null
+++ b/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef WorkerLoaderClientBridgeSyncHelper_h
+#define WorkerLoaderClientBridgeSyncHelper_h
+
+#include "core/loader/ThreadableLoaderClient.h"
+#include "wtf/Forward.h"
+#include "wtf/Functional.h"
+#include "wtf/Vector.h"
+
+namespace blink {
+class WebWaitableEvent;
+}
+
+namespace WebCore {
+
+// This bridge is created and destroyed on the worker thread, but is
+// passed to and used on the main thread. Each did* method records the given
+// data so that they can be run on the worker thread later (by run()).
+class WorkerLoaderClientBridgeSyncHelper : public ThreadableLoaderClient {
+public:
+    static PassOwnPtr<WorkerLoaderClientBridgeSyncHelper> create(ThreadableLoaderClient&, PassOwnPtr<blink::WebWaitableEvent>);
+    virtual ~WorkerLoaderClientBridgeSyncHelper();
+
+    // Called on the worker context thread.
+    void run();
+
+    // Called on the main thread.
+    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
+    virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&) OVERRIDE;
+    virtual void didReceiveData(const char*, int dataLength) OVERRIDE;
+    virtual void didDownloadData(int dataLength) OVERRIDE;
+    virtual void didReceiveCachedMetadata(const char*, int dataLength) OVERRIDE;
+    virtual void didFinishLoading(unsigned long identifier, double finishTime) OVERRIDE;
+    virtual void didFail(const ResourceError&) OVERRIDE;
+    virtual void didFailAccessControlCheck(const ResourceError&) OVERRIDE;
+    virtual void didFailRedirectCheck() OVERRIDE;
+
+private:
+    WorkerLoaderClientBridgeSyncHelper(ThreadableLoaderClient&, PassOwnPtr<blink::WebWaitableEvent>);
+
+    bool m_done;
+    ThreadableLoaderClient& m_client;
+    OwnPtr<blink::WebWaitableEvent> m_event;
+    Vector<Vector<char>*> m_receivedData;
+    Vector<Closure> m_clientTasks;
+};
+
+} // namespace WebCore
+
+#endif // WorkerLoaderClientBridgeSyncHelper_h
diff --git a/Source/core/loader/WorkerThreadableLoader.cpp b/Source/core/loader/WorkerThreadableLoader.cpp
index ad16a0f..fd07cca 100644
--- a/Source/core/loader/WorkerThreadableLoader.cpp
+++ b/Source/core/loader/WorkerThreadableLoader.cpp
@@ -35,26 +35,26 @@
 #include "core/dom/CrossThreadTask.h"
 #include "core/dom/Document.h"
 #include "core/loader/DocumentThreadableLoader.h"
+#include "core/loader/WorkerLoaderClientBridgeSyncHelper.h"
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerLoaderProxy.h"
 #include "core/workers/WorkerThread.h"
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/Referrer.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebWaitableEvent.h"
 #include "wtf/MainThread.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/Vector.h"
 
-using namespace std;
-
 namespace WebCore {
 
-static const char loadResourceSynchronouslyMode[] = "loadResourceSynchronouslyMode";
-
-WorkerThreadableLoader::WorkerThreadableLoader(WorkerGlobalScope* workerGlobalScope, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, const ThreadableLoaderOptions& options)
+WorkerThreadableLoader::WorkerThreadableLoader(WorkerGlobalScope* workerGlobalScope, PassRefPtr<ThreadableLoaderClientWrapper> clientWrapper, PassOwnPtr<ThreadableLoaderClient> clientBridge, const ResourceRequest& request, const ThreadableLoaderOptions& options)
     : m_workerGlobalScope(workerGlobalScope)
-    , m_workerClientWrapper(ThreadableLoaderClientWrapper::create(client))
-    , m_bridge(*(new MainThreadBridge(m_workerClientWrapper, m_workerGlobalScope->thread()->workerLoaderProxy(), taskMode, request, options, workerGlobalScope->url().strippedForUseAsReferrer())))
+    , m_workerClientWrapper(clientWrapper)
+    , m_bridge(*(new MainThreadBridge(m_workerClientWrapper, clientBridge, m_workerGlobalScope->thread()->workerLoaderProxy(), request, options, workerGlobalScope->url().strippedForUseAsReferrer())))
 {
 }
 
@@ -65,19 +65,30 @@
 
 void WorkerThreadableLoader::loadResourceSynchronously(WorkerGlobalScope* workerGlobalScope, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
 {
-    WorkerRunLoop& runLoop = workerGlobalScope->thread()->runLoop();
+    blink::WebWaitableEvent* shutdownEvent =
+        workerGlobalScope->thread()->shutdownEvent();
+    OwnPtr<blink::WebWaitableEvent> loaderDone =
+        adoptPtr(blink::Platform::current()->createWaitableEvent());
 
-    // Create a unique mode just for this synchronous resource load.
-    String mode = loadResourceSynchronouslyMode;
-    mode.append(String::number(runLoop.createUniqueId()));
+    Vector<blink::WebWaitableEvent*> events;
+    events.append(shutdownEvent);
+    events.append(loaderDone.get());
 
-    RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerGlobalScope, &client, mode, request, options);
-    MessageQueueWaitResult result = MessageQueueMessageReceived;
-    while (!loader->done() && result != MessageQueueTerminated)
-        result = runLoop.runInMode(workerGlobalScope, mode);
+    RefPtr<ThreadableLoaderClientWrapper> clientWrapper(ThreadableLoaderClientWrapper::create(&client));
+    OwnPtr<WorkerLoaderClientBridgeSyncHelper> clientBridge(WorkerLoaderClientBridgeSyncHelper::create(client, loaderDone.release()));
 
-    if (!loader->done() && result == MessageQueueTerminated)
+    // This must be valid while loader is around.
+    WorkerLoaderClientBridgeSyncHelper* clientBridgePtr = clientBridge.get();
+
+    RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerGlobalScope, clientWrapper, clientBridge.release(), request, options);
+
+    blink::WebWaitableEvent* signalled = blink::Platform::current()->waitMultipleEvents(events);
+    if (signalled == shutdownEvent) {
         loader->cancel();
+        return;
+    }
+
+    clientBridgePtr->run();
 }
 
 void WorkerThreadableLoader::cancel()
@@ -85,13 +96,17 @@
     m_bridge.cancel();
 }
 
-WorkerThreadableLoader::MainThreadBridge::MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, WorkerLoaderProxy& loaderProxy, const String& taskMode,
-                                                           const ResourceRequest& request, const ThreadableLoaderOptions& options, const String& outgoingReferrer)
-    : m_workerClientWrapper(workerClientWrapper)
+WorkerThreadableLoader::MainThreadBridge::MainThreadBridge(
+    PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper,
+    PassOwnPtr<ThreadableLoaderClient> clientBridge,
+    WorkerLoaderProxy& loaderProxy,
+    const ResourceRequest& request, const ThreadableLoaderOptions& options, const String& outgoingReferrer)
+    : m_clientBridge(clientBridge)
+    , m_workerClientWrapper(workerClientWrapper)
     , m_loaderProxy(loaderProxy)
-    , m_taskMode(taskMode.isolatedCopy())
 {
     ASSERT(m_workerClientWrapper.get());
+    ASSERT(m_clientBridge.get());
     m_loaderProxy.postTaskToLoader(
         createCallbackTask(&MainThreadBridge::mainThreadCreateLoader,
                            AllowCrossThreadAccess(this), request, options, outgoingReferrer));
@@ -107,7 +122,7 @@
     Document* document = toDocument(context);
 
     OwnPtr<ResourceRequest> request(ResourceRequest::adopt(requestData));
-    request->setHTTPReferrer(outgoingReferrer);
+    request->setHTTPReferrer(Referrer(outgoingReferrer, ReferrerPolicyDefault));
     options.requestInitiatorContext = WorkerContext;
     thisPtr->m_mainThreadLoader = DocumentThreadableLoader::create(document, thisPtr, *request, options);
     if (!thisPtr->m_mainThreadLoader) {
@@ -164,108 +179,49 @@
     m_workerClientWrapper->clearClient();
 }
 
-static void workerGlobalScopeDidSendData(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
-{
-    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
-    workerClientWrapper->didSendData(bytesSent, totalBytesToBeSent);
-}
-
 void WorkerThreadableLoader::MainThreadBridge::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
 {
-    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent), m_taskMode);
-}
-
-static void workerGlobalScopeDidReceiveResponse(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
-{
-    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
-    OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
-    workerClientWrapper->didReceiveResponse(identifier, *response);
+    m_clientBridge->didSendData(bytesSent, totalBytesToBeSent);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
 {
-    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveResponse, m_workerClientWrapper, identifier, response), m_taskMode);
-}
-
-static void workerGlobalScopeDidReceiveData(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
-{
-    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
-    workerClientWrapper->didReceiveData(vectorData->data(), vectorData->size());
+    m_clientBridge->didReceiveResponse(identifier, response);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didReceiveData(const char* data, int dataLength)
 {
-    OwnPtr<Vector<char> > vector = adoptPtr(new Vector<char>(dataLength)); // needs to be an OwnPtr for usage with createCallbackTask.
-    memcpy(vector->data(), data, dataLength);
-    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveData, m_workerClientWrapper, vector.release()), m_taskMode);
-}
-
-static void workerGlobalScopeDidDownloadData(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, int dataLength)
-{
-    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
-    workerClientWrapper->didDownloadData(dataLength);
+    m_clientBridge->didReceiveData(data, dataLength);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didDownloadData(int dataLength)
 {
-    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidDownloadData, m_workerClientWrapper, dataLength), m_taskMode);
-}
-
-static void workerGlobalScopeDidReceiveCachedMetadata(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
-{
-    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
-    workerClientWrapper->didReceiveCachedMetadata(vectorData->data(), vectorData->size());
+    m_clientBridge->didDownloadData(dataLength);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didReceiveCachedMetadata(const char* data, int dataLength)
 {
-    OwnPtr<Vector<char> > vector = adoptPtr(new Vector<char>(dataLength)); // needs to be an OwnPtr for usage with createCallbackTask.
-    memcpy(vector->data(), data, dataLength);
-    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveCachedMetadata, m_workerClientWrapper, vector.release()), m_taskMode);
-}
-
-static void workerGlobalScopeDidFinishLoading(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, double finishTime)
-{
-    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
-    workerClientWrapper->didFinishLoading(identifier, finishTime);
+    m_clientBridge->didReceiveCachedMetadata(data, dataLength);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didFinishLoading(unsigned long identifier, double finishTime)
 {
-    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFinishLoading, m_workerClientWrapper, identifier, finishTime), m_taskMode);
-}
-
-static void workerGlobalScopeDidFail(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
-{
-    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
-    workerClientWrapper->didFail(error);
+    m_clientBridge->didFinishLoading(identifier, finishTime);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didFail(const ResourceError& error)
 {
-    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFail, m_workerClientWrapper, error), m_taskMode);
-}
-
-static void workerGlobalScopeDidFailAccessControlCheck(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
-{
-    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
-    workerClientWrapper->didFailAccessControlCheck(error);
+    m_clientBridge->didFail(error);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didFailAccessControlCheck(const ResourceError& error)
 {
-    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFailAccessControlCheck, m_workerClientWrapper, error), m_taskMode);
-}
-
-static void workerGlobalScopeDidFailRedirectCheck(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper)
-{
-    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
-    workerClientWrapper->didFailRedirectCheck();
+    m_clientBridge->didFailAccessControlCheck(error);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didFailRedirectCheck()
 {
-    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFailRedirectCheck, m_workerClientWrapper), m_taskMode);
+    m_clientBridge->didFailRedirectCheck();
 }
 
 } // namespace WebCore
diff --git a/Source/core/loader/WorkerThreadableLoader.h b/Source/core/loader/WorkerThreadableLoader.h
index 369babe..ec69fec 100644
--- a/Source/core/loader/WorkerThreadableLoader.h
+++ b/Source/core/loader/WorkerThreadableLoader.h
@@ -50,16 +50,16 @@
     struct CrossThreadResourceResponseData;
     struct CrossThreadResourceRequestData;
 
-    class WorkerThreadableLoader : public RefCounted<WorkerThreadableLoader>, public ThreadableLoader {
+    class WorkerThreadableLoader FINAL : public RefCounted<WorkerThreadableLoader>, public ThreadableLoader {
         WTF_MAKE_FAST_ALLOCATED;
     public:
         static void loadResourceSynchronously(WorkerGlobalScope*, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&);
-        static PassRefPtr<WorkerThreadableLoader> create(WorkerGlobalScope* workerGlobalScope, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, const ThreadableLoaderOptions& options)
+        static PassRefPtr<WorkerThreadableLoader> create(WorkerGlobalScope* workerGlobalScope, PassRefPtr<ThreadableLoaderClientWrapper> clientWrapper, PassOwnPtr<ThreadableLoaderClient> clientBridge, const ResourceRequest& request, const ThreadableLoaderOptions& options)
         {
-            return adoptRef(new WorkerThreadableLoader(workerGlobalScope, client, taskMode, request, options));
+            return adoptRef(new WorkerThreadableLoader(workerGlobalScope, clientWrapper, clientBridge, request, options));
         }
 
-        ~WorkerThreadableLoader();
+        virtual ~WorkerThreadableLoader();
 
         virtual void cancel() OVERRIDE;
 
@@ -92,10 +92,10 @@
         //    thread do "ThreadableLoaderClientWrapper::ref" (automatically inside of the cross thread copy
         //    done in createCallbackTask), so the ThreadableLoaderClientWrapper instance is there until all
         //    tasks are executed.
-        class MainThreadBridge : public ThreadableLoaderClient {
+        class MainThreadBridge FINAL : public ThreadableLoaderClient {
         public:
             // All executed on the worker context's thread.
-            MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper>, WorkerLoaderProxy&, const String& taskMode, const ResourceRequest&, const ThreadableLoaderOptions&, const String& outgoingReferrer);
+            MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper>, PassOwnPtr<ThreadableLoaderClient>, WorkerLoaderProxy&, const ResourceRequest&, const ThreadableLoaderOptions&, const String& outgoingReferrer);
             void cancel();
             void destroy();
 
@@ -105,7 +105,7 @@
 
             // All executed on the main thread.
             static void mainThreadDestroy(ExecutionContext*, MainThreadBridge*);
-            ~MainThreadBridge();
+            virtual ~MainThreadBridge();
 
             static void mainThreadCreateLoader(ExecutionContext*, MainThreadBridge*, PassOwnPtr<CrossThreadResourceRequestData>, ThreadableLoaderOptions, const String& outgoingReferrer);
             static void mainThreadCancel(ExecutionContext*, MainThreadBridge*);
@@ -121,19 +121,17 @@
 
             // Only to be used on the main thread.
             RefPtr<ThreadableLoader> m_mainThreadLoader;
+            OwnPtr<ThreadableLoaderClient> m_clientBridge;
 
             // ThreadableLoaderClientWrapper is to be used on the worker context thread.
             // The ref counting is done on either thread.
             RefPtr<ThreadableLoaderClientWrapper> m_workerClientWrapper;
 
-            // May be used on either thread.
+            // Used on the worker context thread.
             WorkerLoaderProxy& m_loaderProxy;
-
-            // For use on the main thread.
-            String m_taskMode;
         };
 
-        WorkerThreadableLoader(WorkerGlobalScope*, ThreadableLoaderClient*, const String& taskMode, const ResourceRequest&, const ThreadableLoaderOptions&);
+        WorkerThreadableLoader(WorkerGlobalScope*, PassRefPtr<ThreadableLoaderClientWrapper>, PassOwnPtr<ThreadableLoaderClient>, const ResourceRequest&, const ThreadableLoaderOptions&);
 
         RefPtr<WorkerGlobalScope> m_workerGlobalScope;
         RefPtr<ThreadableLoaderClientWrapper> m_workerClientWrapper;
diff --git a/Source/core/loader/appcache/ApplicationCache.h b/Source/core/loader/appcache/ApplicationCache.h
index 405ad35..ca0366f 100644
--- a/Source/core/loader/appcache/ApplicationCache.h
+++ b/Source/core/loader/appcache/ApplicationCache.h
@@ -41,11 +41,11 @@
 class Frame;
 class KURL;
 
-class ApplicationCache : public ScriptWrappable, public RefCounted<ApplicationCache>, public EventTargetWithInlineData, public DOMWindowProperty {
+class ApplicationCache FINAL : public ScriptWrappable, public RefCounted<ApplicationCache>, public EventTargetWithInlineData, public DOMWindowProperty {
     REFCOUNTED_EVENT_TARGET(ApplicationCache);
 public:
     static PassRefPtr<ApplicationCache> create(Frame* frame) { return adoptRef(new ApplicationCache(frame)); }
-    ~ApplicationCache() { ASSERT(!m_frame); }
+    virtual ~ApplicationCache() { ASSERT(!m_frame); }
 
     virtual void willDestroyGlobalObjectInFrame() OVERRIDE;
 
diff --git a/Source/core/make_core_derived_sources.target.linux-arm.mk b/Source/core/make_core_derived_sources.target.linux-arm.mk
deleted file mode 100644
index e3667ad..0000000
--- a/Source/core/make_core_derived_sources.target.linux-arm.mk
+++ /dev/null
@@ -1,598 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_make_core_derived_sources_gyp
-LOCAL_MODULE_STEM := make_core_derived_sources
-LOCAL_MODULE_SUFFIX := .stamp
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
-
-### Rules for action "generateV8ArrayBufferViewCustomScript":
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
-
-
-### Rules for action "generateXMLViewerCSS":
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerCSS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
-
-
-### Rules for action "generateXMLViewerJS":
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerJS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
-
-
-### Rules for action "HTMLEntityTable":
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/create-html-entity-table $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/HTMLEntityNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLEntityTable ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python html/parser/create-html-entity-table -o "$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp" html/parser/HTMLEntityNames.in
-
-
-### Rules for action "CSSPropertyNames":
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
-
-### Rules for action "StylePropertyShorthand":
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StylePropertyShorthand ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp ;
-
-### Rules for action "StyleBuilder":
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StyleBuilder ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
-$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
-
-### Rules for action "CSSValueKeywords":
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
-
-### Rules for action "HTMLElementFactory":
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py html/HTMLTagNames.in html/HTMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-
-### Rules for action "SVGNames":
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py svg/SVGTagNames.in svg/SVGAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-
-### Rules for action "EventFactory":
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventHeaders.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
-$(gyp_shared_intermediate_dir)/blink/EventInterfaces.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
-
-### Rules for action "EventNames":
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventNames.h: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp ;
-
-### Rules for action "EventTargetFactory":
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h ;
-
-### Rules for action "EventTargetNames":
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.h: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp ;
-
-### Rules for action "MathMLNames":
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
-
-### Rules for action "UserAgentStyleSheets":
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
-
-### Rules for action "FetchInitiatorTypeNames":
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_FetchInitiatorTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py fetch/FetchInitiatorTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
-
-### Rules for action "EventTypeNames":
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
-
-### Rules for action "InputTypeNames":
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
-
-### Rules for action "XLinkNames":
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py svg/xlinkattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
-
-### Rules for action "XMLNSNames":
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlnsattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
-
-### Rules for action "XMLNames":
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
-
-### Rules for action "MakeTokenMatcher":
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
-
-
-### Rules for action "MakeParser":
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
-
-
-### Rules for action "MakeTokenMatcherForViewport":
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcherForViewport ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
-
-
-### Rules for action "HTMLElementLookupTrie":
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
-
-
-
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
-# "{'msvs_cygwin_shell': '1', 'extension': 'y', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'rule_name': 'bison', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h'], 'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison']}":
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py css/CSSGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
-
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
-
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XPathGrammar.y $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py xml/XPathGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
-
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.h: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
-
-### Finished generating for all rules
-
-GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h \
-	$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h \
-	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp \
-	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h \
-	$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp \
-	$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h \
-	$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLNames.h \
-	$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.h \
-	$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/Event.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventHeaders.h \
-	$(gyp_shared_intermediate_dir)/blink/EventInterfaces.h \
-	$(gyp_shared_intermediate_dir)/blink/EventNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventNames.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetNames.h \
-	$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/MathMLNames.h \
-	$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h \
-	$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp \
-	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h \
-	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h \
-	$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XLinkNames.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
-	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
-	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h \
-	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.h
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-LOCAL_GENERATED_SOURCES := \
-	third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS :=
-
-LOCAL_SRC_FILES :=
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-fno-tree-sra \
-	-fuse-ld=gold \
-	-Wno-psabi \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-fno-tree-sra \
-	-fuse-ld=gold \
-	-Wno-psabi \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_make_core_derived_sources_gyp
-
-# Alias gyp target name.
-.PHONY: make_core_derived_sources
-make_core_derived_sources: third_party_WebKit_Source_core_make_core_derived_sources_gyp
-
-LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
-LOCAL_UNINSTALLABLE_MODULE := true
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
-	$(hide) echo "Gyp timestamp: $@"
-	$(hide) mkdir -p $(dir $@)
-	$(hide) touch $@
diff --git a/Source/core/make_core_derived_sources.target.linux-mips.mk b/Source/core/make_core_derived_sources.target.linux-mips.mk
deleted file mode 100644
index e24b046..0000000
--- a/Source/core/make_core_derived_sources.target.linux-mips.mk
+++ /dev/null
@@ -1,596 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_make_core_derived_sources_gyp
-LOCAL_MODULE_STEM := make_core_derived_sources
-LOCAL_MODULE_SUFFIX := .stamp
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
-
-### Rules for action "generateV8ArrayBufferViewCustomScript":
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
-
-
-### Rules for action "generateXMLViewerCSS":
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerCSS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
-
-
-### Rules for action "generateXMLViewerJS":
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerJS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
-
-
-### Rules for action "HTMLEntityTable":
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/create-html-entity-table $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/HTMLEntityNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLEntityTable ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python html/parser/create-html-entity-table -o "$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp" html/parser/HTMLEntityNames.in
-
-
-### Rules for action "CSSPropertyNames":
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
-
-### Rules for action "StylePropertyShorthand":
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StylePropertyShorthand ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp ;
-
-### Rules for action "StyleBuilder":
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StyleBuilder ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
-$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
-
-### Rules for action "CSSValueKeywords":
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
-
-### Rules for action "HTMLElementFactory":
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py html/HTMLTagNames.in html/HTMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-
-### Rules for action "SVGNames":
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py svg/SVGTagNames.in svg/SVGAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-
-### Rules for action "EventFactory":
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventHeaders.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
-$(gyp_shared_intermediate_dir)/blink/EventInterfaces.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
-
-### Rules for action "EventNames":
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventNames.h: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp ;
-
-### Rules for action "EventTargetFactory":
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h ;
-
-### Rules for action "EventTargetNames":
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.h: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp ;
-
-### Rules for action "MathMLNames":
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
-
-### Rules for action "UserAgentStyleSheets":
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
-
-### Rules for action "FetchInitiatorTypeNames":
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_FetchInitiatorTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py fetch/FetchInitiatorTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
-
-### Rules for action "EventTypeNames":
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
-
-### Rules for action "InputTypeNames":
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
-
-### Rules for action "XLinkNames":
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py svg/xlinkattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
-
-### Rules for action "XMLNSNames":
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlnsattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
-
-### Rules for action "XMLNames":
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
-
-### Rules for action "MakeTokenMatcher":
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
-
-
-### Rules for action "MakeParser":
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
-
-
-### Rules for action "MakeTokenMatcherForViewport":
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcherForViewport ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
-
-
-### Rules for action "HTMLElementLookupTrie":
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
-
-
-
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
-# "{'msvs_cygwin_shell': '1', 'extension': 'y', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'rule_name': 'bison', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h'], 'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison']}":
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py css/CSSGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
-
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
-
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XPathGrammar.y $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py xml/XPathGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
-
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.h: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
-
-### Finished generating for all rules
-
-GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h \
-	$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h \
-	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp \
-	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h \
-	$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp \
-	$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h \
-	$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLNames.h \
-	$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.h \
-	$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/Event.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventHeaders.h \
-	$(gyp_shared_intermediate_dir)/blink/EventInterfaces.h \
-	$(gyp_shared_intermediate_dir)/blink/EventNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventNames.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetNames.h \
-	$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/MathMLNames.h \
-	$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h \
-	$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp \
-	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h \
-	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h \
-	$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XLinkNames.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
-	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
-	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h \
-	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.h
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-LOCAL_GENERATED_SOURCES := \
-	third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS :=
-
-LOCAL_SRC_FILES :=
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-EL \
-	-mhard-float \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-EL \
-	-mhard-float \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_make_core_derived_sources_gyp
-
-# Alias gyp target name.
-.PHONY: make_core_derived_sources
-make_core_derived_sources: third_party_WebKit_Source_core_make_core_derived_sources_gyp
-
-LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
-LOCAL_UNINSTALLABLE_MODULE := true
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
-	$(hide) echo "Gyp timestamp: $@"
-	$(hide) mkdir -p $(dir $@)
-	$(hide) touch $@
diff --git a/Source/core/make_core_derived_sources.target.linux-x86.mk b/Source/core/make_core_derived_sources.target.linux-x86.mk
deleted file mode 100644
index 3e50140..0000000
--- a/Source/core/make_core_derived_sources.target.linux-x86.mk
+++ /dev/null
@@ -1,602 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_make_core_derived_sources_gyp
-LOCAL_MODULE_STEM := make_core_derived_sources
-LOCAL_MODULE_SUFFIX := .stamp
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
-
-### Rules for action "generateV8ArrayBufferViewCustomScript":
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
-
-
-### Rules for action "generateXMLViewerCSS":
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerCSS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
-
-
-### Rules for action "generateXMLViewerJS":
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerJS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
-
-
-### Rules for action "HTMLEntityTable":
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/create-html-entity-table $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/HTMLEntityNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLEntityTable ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python html/parser/create-html-entity-table -o "$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp" html/parser/HTMLEntityNames.in
-
-
-### Rules for action "CSSPropertyNames":
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
-
-### Rules for action "StylePropertyShorthand":
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StylePropertyShorthand ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp ;
-
-### Rules for action "StyleBuilder":
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StyleBuilder ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
-$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
-
-### Rules for action "CSSValueKeywords":
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
-
-### Rules for action "HTMLElementFactory":
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py html/HTMLTagNames.in html/HTMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
-
-### Rules for action "SVGNames":
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py svg/SVGTagNames.in svg/SVGAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
-
-### Rules for action "EventFactory":
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventHeaders.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
-$(gyp_shared_intermediate_dir)/blink/EventInterfaces.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
-
-### Rules for action "EventNames":
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventNames.h: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp ;
-
-### Rules for action "EventTargetFactory":
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h ;
-
-### Rules for action "EventTargetNames":
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventTargetNames.h: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp ;
-
-### Rules for action "MathMLNames":
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
-
-### Rules for action "UserAgentStyleSheets":
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
-
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
-
-### Rules for action "FetchInitiatorTypeNames":
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_FetchInitiatorTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py fetch/FetchInitiatorTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
-
-### Rules for action "EventTypeNames":
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
-
-### Rules for action "InputTypeNames":
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
-
-### Rules for action "XLinkNames":
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py svg/xlinkattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
-
-### Rules for action "XMLNSNames":
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlnsattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
-
-### Rules for action "XMLNames":
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
-
-### Rules for action "MakeTokenMatcher":
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
-
-
-### Rules for action "MakeParser":
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
-
-
-### Rules for action "MakeTokenMatcherForViewport":
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcherForViewport ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
-
-
-### Rules for action "HTMLElementLookupTrie":
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
-
-$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
-
-
-
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
-# "{'msvs_cygwin_shell': '1', 'extension': 'y', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'rule_name': 'bison', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h'], 'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison']}":
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py css/CSSGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
-
-$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
-
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XPathGrammar.y $(GYP_TARGET_DEPENDENCIES)
-	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py xml/XPathGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
-
-$(gyp_shared_intermediate_dir)/blink/XPathGrammar.h: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
-
-### Finished generating for all rules
-
-GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h \
-	$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h \
-	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp \
-	$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h \
-	$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp \
-	$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h \
-	$(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLNames.h \
-	$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/SVGNames.h \
-	$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp \
-	$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h \
-	$(gyp_shared_intermediate_dir)/blink/Event.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventHeaders.h \
-	$(gyp_shared_intermediate_dir)/blink/EventInterfaces.h \
-	$(gyp_shared_intermediate_dir)/blink/EventNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventNames.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventTargetNames.h \
-	$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/MathMLNames.h \
-	$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h \
-	$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp \
-	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h \
-	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/EventTypeNames.h \
-	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/InputTypeNames.h \
-	$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XLinkNames.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h \
-	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
-	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
-	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
-	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSGrammar.h \
-	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp \
-	$(gyp_shared_intermediate_dir)/blink/XPathGrammar.h
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-LOCAL_GENERATED_SOURCES := \
-	third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS :=
-
-LOCAL_SRC_FILES :=
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-m32 \
-	-mmmx \
-	-march=pentium4 \
-	-msse2 \
-	-mfpmath=sse \
-	-fuse-ld=gold \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-fno-stack-protector \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-m32 \
-	-mmmx \
-	-march=pentium4 \
-	-msse2 \
-	-mfpmath=sse \
-	-fuse-ld=gold \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-fno-stack-protector \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_make_core_derived_sources_gyp
-
-# Alias gyp target name.
-.PHONY: make_core_derived_sources
-make_core_derived_sources: third_party_WebKit_Source_core_make_core_derived_sources_gyp
-
-LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
-LOCAL_UNINSTALLABLE_MODULE := true
-
-include $(BUILD_SYSTEM)/base_rules.mk
-
-$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
-	$(hide) echo "Gyp timestamp: $@"
-	$(hide) mkdir -p $(dir $@)
-	$(hide) touch $@
diff --git a/Source/core/make_core_derived_sources.xml b/Source/core/make_core_derived_sources.xml
deleted file mode 100644
index a526384..0000000
--- a/Source/core/make_core_derived_sources.xml
+++ /dev/null
@@ -1,68 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>

-<ProjectSchemaDefinitions xmlns="clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:transformCallback="Microsoft.Cpp.Dev10.ConvertPropertyCallback" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

-  <Rule DisplayName="bison" Name="bison" Order="200" PageTemplate="tool">

-    <Rule.DataSource>

-      <DataSource ItemType="bison" Persistence="ProjectFile"/>

-    </Rule.DataSource>

-    <Rule.Categories>

-      <Category Name="General">

-        <Category.DisplayName>

-          <sys:String>General</sys:String>

-        </Category.DisplayName>

-      </Category>

-      <Category Name="Command Line" Subtype="CommandLine">

-        <Category.DisplayName>

-          <sys:String>Command Line</sys:String>

-        </Category.DisplayName>

-      </Category>

-    </Rule.Categories>

-    <StringListProperty Category="Command Line" IsRequired="true" Name="Inputs" Switch=" ">

-      <StringListProperty.DataSource>

-        <DataSource ItemType="bison" Persistence="ProjectFile" SourceType="Item"/>

-      </StringListProperty.DataSource>

-    </StringListProperty>

-    <StringProperty DisplayName="Command Line" IncludeInCommandLine="False" Name="CommandLineTemplate" Visible="False"/>

-    <DynamicEnumProperty Category="General" EnumProvider="Targets" IncludeInCommandLine="False" Name="bisonBeforeTargets">

-      <DynamicEnumProperty.DisplayName>

-        <sys:String>Execute Before</sys:String>

-      </DynamicEnumProperty.DisplayName>

-      <DynamicEnumProperty.Description>

-        <sys:String>Specifies the targets for the build customization to run before.</sys:String>

-      </DynamicEnumProperty.Description>

-      <DynamicEnumProperty.ProviderSettings>

-        <NameValuePair Name="Exclude" Value="^bisonBeforeTargets|^Compute"/>

-      </DynamicEnumProperty.ProviderSettings>

-      <DynamicEnumProperty.DataSource>

-        <DataSource HasConfigurationCondition="true" Persistence="ProjectFile"/>

-      </DynamicEnumProperty.DataSource>

-    </DynamicEnumProperty>

-    <DynamicEnumProperty Category="General" EnumProvider="Targets" IncludeInCommandLine="False" Name="bisonAfterTargets">

-      <DynamicEnumProperty.DisplayName>

-        <sys:String>Execute After</sys:String>

-      </DynamicEnumProperty.DisplayName>

-      <DynamicEnumProperty.Description>

-        <sys:String>Specifies the targets for the build customization to run after.</sys:String>

-      </DynamicEnumProperty.Description>

-      <DynamicEnumProperty.ProviderSettings>

-        <NameValuePair Name="Exclude" Value="^bisonAfterTargets|^Compute"/>

-      </DynamicEnumProperty.ProviderSettings>

-      <DynamicEnumProperty.DataSource>

-        <DataSource HasConfigurationCondition="true" ItemType="" Persistence="ProjectFile"/>

-      </DynamicEnumProperty.DataSource>

-    </DynamicEnumProperty>

-    <StringListProperty DisplayName="Outputs" IncludeInCommandLine="False" Name="Outputs" Visible="False"/>

-    <StringProperty DisplayName="Execution Description" IncludeInCommandLine="False" Name="ExecutionDescription" Visible="False"/>

-    <StringListProperty DisplayName="Additional Dependencies" IncludeInCommandLine="False" Name="AdditionalDependencies" Visible="false"/>

-    <StringProperty Category="Command Line" Name="AdditionalOptions" Subtype="AdditionalOptions">

-      <StringProperty.DisplayName>

-        <sys:String>Additional Options</sys:String>

-      </StringProperty.DisplayName>

-      <StringProperty.Description>

-        <sys:String>Additional Options</sys:String>

-      </StringProperty.Description>

-    </StringProperty>

-  </Rule>

-  <ItemType DisplayName="bison" Name="bison"/>

-  <FileExtension ContentType="bison" Name="*.y"/>

-  <ContentType DisplayName="" ItemType="bison" Name="bison"/>

-</ProjectSchemaDefinitions>

diff --git a/Source/core/make_core_derived_sources.target.darwin-arm.mk b/Source/core/make_core_generated.target.darwin-arm.mk
similarity index 85%
rename from Source/core/make_core_derived_sources.target.darwin-arm.mk
rename to Source/core/make_core_generated.target.darwin-arm.mk
index e3667ad..adffd5f 100644
--- a/Source/core/make_core_derived_sources.target.darwin-arm.mk
+++ b/Source/core/make_core_generated.target.darwin-arm.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_make_core_derived_sources_gyp
-LOCAL_MODULE_STEM := make_core_derived_sources
+LOCAL_MODULE := third_party_WebKit_Source_core_make_core_generated_gyp
+LOCAL_MODULE_STEM := make_core_generated
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,26 +12,16 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generated_testing_idls_gyp)/generated_testing_idls.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
-### Rules for action "generateV8ArrayBufferViewCustomScript":
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
-
-
 ### Rules for action "generateXMLViewerCSS":
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerCSS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerCSS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
@@ -41,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerJS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerJS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
@@ -51,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/create-html-entity-table $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/HTMLEntityNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLEntityTable ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLEntityTable ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python html/parser/create-html-entity-table -o "$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp" html/parser/HTMLEntityNames.in
 
 
@@ -61,8 +51,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSPropertyNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -72,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StylePropertyShorthand ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp ;
@@ -83,7 +73,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StyleBuilder ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
@@ -95,8 +85,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSValueKeywords ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -106,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py html/HTMLTagNames.in html/HTMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
@@ -121,7 +111,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_SVGNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_SVGNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py svg/SVGTagNames.in svg/SVGAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
@@ -136,7 +126,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventHeaders.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
@@ -148,7 +138,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventNames.h: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp ;
@@ -159,7 +149,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h ;
@@ -170,7 +160,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.h: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp ;
@@ -181,8 +171,8 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MathMLNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -192,8 +182,8 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -203,7 +193,7 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_FetchInitiatorTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_FetchInitiatorTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py fetch/FetchInitiatorTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
@@ -214,7 +204,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
@@ -225,7 +215,7 @@
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_InputTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
@@ -236,7 +226,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XLinkNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XLinkNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py svg/xlinkattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
@@ -247,7 +237,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNSNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNSNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlnsattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
@@ -258,7 +248,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
@@ -269,18 +259,18 @@
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
 
 
 ### Rules for action "MakeParser":
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/parser/BisonCSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeParser ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/parser/BisonCSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp"
 
 
 ### Rules for action "MakeTokenMatcherForViewport":
@@ -289,7 +279,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcherForViewport ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcherForViewport ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
@@ -299,15 +289,15 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementLookupTrie ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
 
 
 
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
-# "{'msvs_cygwin_shell': '1', 'extension': 'y', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'rule_name': 'bison', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h'], 'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison']}":
+### Generated for rule "third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_bison":
+# "{'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison'], 'rule_name': 'bison', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'extension': 'y', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h']}":
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
@@ -316,8 +306,8 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py css/CSSGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.h: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -327,13 +317,12 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py xml/XPathGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.h: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
 
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h \
 	$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp \
@@ -384,7 +373,7 @@
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
+	$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
@@ -397,7 +386,7 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
 LOCAL_GENERATED_SOURCES := \
-	third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
+	third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
 
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
@@ -431,14 +420,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -449,7 +439,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -484,7 +473,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -516,14 +504,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -534,7 +523,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -570,7 +558,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -581,11 +568,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+gyp_all_modules: third_party_WebKit_Source_core_make_core_generated_gyp
 
 # Alias gyp target name.
-.PHONY: make_core_derived_sources
-make_core_derived_sources: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+.PHONY: make_core_generated
+make_core_generated: third_party_WebKit_Source_core_make_core_generated_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/make_core_derived_sources.target.darwin-mips.mk b/Source/core/make_core_generated.target.darwin-mips.mk
similarity index 85%
rename from Source/core/make_core_derived_sources.target.darwin-mips.mk
rename to Source/core/make_core_generated.target.darwin-mips.mk
index e24b046..fc97fa2 100644
--- a/Source/core/make_core_derived_sources.target.darwin-mips.mk
+++ b/Source/core/make_core_generated.target.darwin-mips.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_make_core_derived_sources_gyp
-LOCAL_MODULE_STEM := make_core_derived_sources
+LOCAL_MODULE := third_party_WebKit_Source_core_make_core_generated_gyp
+LOCAL_MODULE_STEM := make_core_generated
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,26 +12,16 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generated_testing_idls_gyp)/generated_testing_idls.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
-### Rules for action "generateV8ArrayBufferViewCustomScript":
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
-
-
 ### Rules for action "generateXMLViewerCSS":
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerCSS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerCSS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
@@ -41,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerJS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerJS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
@@ -51,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/create-html-entity-table $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/HTMLEntityNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLEntityTable ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLEntityTable ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python html/parser/create-html-entity-table -o "$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp" html/parser/HTMLEntityNames.in
 
 
@@ -61,8 +51,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSPropertyNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -72,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StylePropertyShorthand ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp ;
@@ -83,7 +73,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StyleBuilder ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
@@ -95,8 +85,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSValueKeywords ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -106,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py html/HTMLTagNames.in html/HTMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
@@ -121,7 +111,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_SVGNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_SVGNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py svg/SVGTagNames.in svg/SVGAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
@@ -136,7 +126,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventHeaders.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
@@ -148,7 +138,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventNames.h: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp ;
@@ -159,7 +149,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h ;
@@ -170,7 +160,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.h: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp ;
@@ -181,8 +171,8 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MathMLNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -192,8 +182,8 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -203,7 +193,7 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_FetchInitiatorTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_FetchInitiatorTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py fetch/FetchInitiatorTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
@@ -214,7 +204,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
@@ -225,7 +215,7 @@
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_InputTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
@@ -236,7 +226,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XLinkNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XLinkNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py svg/xlinkattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
@@ -247,7 +237,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNSNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNSNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlnsattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
@@ -258,7 +248,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
@@ -269,18 +259,18 @@
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
 
 
 ### Rules for action "MakeParser":
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/parser/BisonCSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeParser ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/parser/BisonCSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp"
 
 
 ### Rules for action "MakeTokenMatcherForViewport":
@@ -289,7 +279,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcherForViewport ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcherForViewport ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
@@ -299,15 +289,15 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementLookupTrie ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
 
 
 
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
-# "{'msvs_cygwin_shell': '1', 'extension': 'y', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'rule_name': 'bison', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h'], 'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison']}":
+### Generated for rule "third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_bison":
+# "{'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison'], 'rule_name': 'bison', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'extension': 'y', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h']}":
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
@@ -316,8 +306,8 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py css/CSSGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.h: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -327,13 +317,12 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py xml/XPathGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.h: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
 
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h \
 	$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp \
@@ -384,7 +373,7 @@
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
+	$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
@@ -397,7 +386,7 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
 LOCAL_GENERATED_SOURCES := \
-	third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
+	third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
 
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
@@ -430,14 +419,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -448,7 +438,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -483,7 +472,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -514,14 +502,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -532,7 +521,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -568,7 +556,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -579,11 +566,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+gyp_all_modules: third_party_WebKit_Source_core_make_core_generated_gyp
 
 # Alias gyp target name.
-.PHONY: make_core_derived_sources
-make_core_derived_sources: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+.PHONY: make_core_generated
+make_core_generated: third_party_WebKit_Source_core_make_core_generated_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/make_core_derived_sources.target.darwin-x86.mk b/Source/core/make_core_generated.target.darwin-x86.mk
similarity index 85%
rename from Source/core/make_core_derived_sources.target.darwin-x86.mk
rename to Source/core/make_core_generated.target.darwin-x86.mk
index 3e50140..00c2b62 100644
--- a/Source/core/make_core_derived_sources.target.darwin-x86.mk
+++ b/Source/core/make_core_generated.target.darwin-x86.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_make_core_derived_sources_gyp
-LOCAL_MODULE_STEM := make_core_derived_sources
+LOCAL_MODULE := third_party_WebKit_Source_core_make_core_generated_gyp
+LOCAL_MODULE_STEM := make_core_generated
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,26 +12,16 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generated_testing_idls_gyp)/generated_testing_idls.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
-### Rules for action "generateV8ArrayBufferViewCustomScript":
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
-
-
 ### Rules for action "generateXMLViewerCSS":
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerCSS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerCSS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
@@ -41,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerJS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerJS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
@@ -51,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/create-html-entity-table $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/HTMLEntityNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLEntityTable ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLEntityTable ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python html/parser/create-html-entity-table -o "$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp" html/parser/HTMLEntityNames.in
 
 
@@ -61,8 +51,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSPropertyNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -72,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StylePropertyShorthand ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp ;
@@ -83,7 +73,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StyleBuilder ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
@@ -95,8 +85,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSValueKeywords ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -106,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py html/HTMLTagNames.in html/HTMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
@@ -121,7 +111,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_SVGNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_SVGNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py svg/SVGTagNames.in svg/SVGAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
@@ -136,7 +126,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventHeaders.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
@@ -148,7 +138,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventNames.h: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp ;
@@ -159,7 +149,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h ;
@@ -170,7 +160,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.h: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp ;
@@ -181,8 +171,8 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MathMLNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -192,8 +182,8 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -203,7 +193,7 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_FetchInitiatorTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_FetchInitiatorTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py fetch/FetchInitiatorTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
@@ -214,7 +204,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
@@ -225,7 +215,7 @@
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_InputTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
@@ -236,7 +226,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XLinkNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XLinkNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py svg/xlinkattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
@@ -247,7 +237,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNSNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNSNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlnsattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
@@ -258,7 +248,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
@@ -269,18 +259,18 @@
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
 
 
 ### Rules for action "MakeParser":
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/parser/BisonCSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeParser ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/parser/BisonCSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp"
 
 
 ### Rules for action "MakeTokenMatcherForViewport":
@@ -289,7 +279,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcherForViewport ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcherForViewport ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
@@ -299,15 +289,15 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementLookupTrie ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
 
 
 
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
-# "{'msvs_cygwin_shell': '1', 'extension': 'y', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'rule_name': 'bison', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h'], 'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison']}":
+### Generated for rule "third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_bison":
+# "{'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison'], 'rule_name': 'bison', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'extension': 'y', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h']}":
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
@@ -316,8 +306,8 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py css/CSSGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.h: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -327,13 +317,12 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py xml/XPathGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.h: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
 
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h \
 	$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp \
@@ -384,7 +373,7 @@
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
+	$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
@@ -397,7 +386,7 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
 LOCAL_GENERATED_SOURCES := \
-	third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
+	third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
 
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
@@ -432,15 +421,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -451,7 +441,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -485,7 +474,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -518,17 +506,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -539,7 +526,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -574,7 +560,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -585,11 +570,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+gyp_all_modules: third_party_WebKit_Source_core_make_core_generated_gyp
 
 # Alias gyp target name.
-.PHONY: make_core_derived_sources
-make_core_derived_sources: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+.PHONY: make_core_generated
+make_core_generated: third_party_WebKit_Source_core_make_core_generated_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/make_core_derived_sources.target.darwin-arm.mk b/Source/core/make_core_generated.target.linux-arm.mk
similarity index 85%
copy from Source/core/make_core_derived_sources.target.darwin-arm.mk
copy to Source/core/make_core_generated.target.linux-arm.mk
index e3667ad..adffd5f 100644
--- a/Source/core/make_core_derived_sources.target.darwin-arm.mk
+++ b/Source/core/make_core_generated.target.linux-arm.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_make_core_derived_sources_gyp
-LOCAL_MODULE_STEM := make_core_derived_sources
+LOCAL_MODULE := third_party_WebKit_Source_core_make_core_generated_gyp
+LOCAL_MODULE_STEM := make_core_generated
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,26 +12,16 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generated_testing_idls_gyp)/generated_testing_idls.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
-### Rules for action "generateV8ArrayBufferViewCustomScript":
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
-
-
 ### Rules for action "generateXMLViewerCSS":
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerCSS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerCSS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
@@ -41,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerJS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerJS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
@@ -51,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/create-html-entity-table $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/HTMLEntityNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLEntityTable ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLEntityTable ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python html/parser/create-html-entity-table -o "$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp" html/parser/HTMLEntityNames.in
 
 
@@ -61,8 +51,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSPropertyNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -72,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StylePropertyShorthand ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp ;
@@ -83,7 +73,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StyleBuilder ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
@@ -95,8 +85,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSValueKeywords ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -106,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py html/HTMLTagNames.in html/HTMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
@@ -121,7 +111,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_SVGNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_SVGNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py svg/SVGTagNames.in svg/SVGAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
@@ -136,7 +126,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventHeaders.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
@@ -148,7 +138,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventNames.h: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp ;
@@ -159,7 +149,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h ;
@@ -170,7 +160,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.h: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp ;
@@ -181,8 +171,8 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MathMLNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -192,8 +182,8 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -203,7 +193,7 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_FetchInitiatorTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_FetchInitiatorTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py fetch/FetchInitiatorTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
@@ -214,7 +204,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
@@ -225,7 +215,7 @@
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_InputTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
@@ -236,7 +226,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XLinkNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XLinkNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py svg/xlinkattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
@@ -247,7 +237,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNSNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNSNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlnsattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
@@ -258,7 +248,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
@@ -269,18 +259,18 @@
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
 
 
 ### Rules for action "MakeParser":
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/parser/BisonCSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeParser ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/parser/BisonCSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp"
 
 
 ### Rules for action "MakeTokenMatcherForViewport":
@@ -289,7 +279,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcherForViewport ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcherForViewport ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
@@ -299,15 +289,15 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementLookupTrie ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
 
 
 
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
-# "{'msvs_cygwin_shell': '1', 'extension': 'y', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'rule_name': 'bison', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h'], 'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison']}":
+### Generated for rule "third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_bison":
+# "{'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison'], 'rule_name': 'bison', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'extension': 'y', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h']}":
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
@@ -316,8 +306,8 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py css/CSSGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.h: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -327,13 +317,12 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py xml/XPathGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.h: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
 
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h \
 	$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp \
@@ -384,7 +373,7 @@
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
+	$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
@@ -397,7 +386,7 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
 LOCAL_GENERATED_SOURCES := \
-	third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
+	third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
 
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
@@ -431,14 +420,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -449,7 +439,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -484,7 +473,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -516,14 +504,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -534,7 +523,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -570,7 +558,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -581,11 +568,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+gyp_all_modules: third_party_WebKit_Source_core_make_core_generated_gyp
 
 # Alias gyp target name.
-.PHONY: make_core_derived_sources
-make_core_derived_sources: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+.PHONY: make_core_generated
+make_core_generated: third_party_WebKit_Source_core_make_core_generated_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/make_core_derived_sources.target.darwin-mips.mk b/Source/core/make_core_generated.target.linux-mips.mk
similarity index 85%
copy from Source/core/make_core_derived_sources.target.darwin-mips.mk
copy to Source/core/make_core_generated.target.linux-mips.mk
index e24b046..fc97fa2 100644
--- a/Source/core/make_core_derived_sources.target.darwin-mips.mk
+++ b/Source/core/make_core_generated.target.linux-mips.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_make_core_derived_sources_gyp
-LOCAL_MODULE_STEM := make_core_derived_sources
+LOCAL_MODULE := third_party_WebKit_Source_core_make_core_generated_gyp
+LOCAL_MODULE_STEM := make_core_generated
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,26 +12,16 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generated_testing_idls_gyp)/generated_testing_idls.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
-### Rules for action "generateV8ArrayBufferViewCustomScript":
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
-
-
 ### Rules for action "generateXMLViewerCSS":
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerCSS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerCSS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
@@ -41,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerJS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerJS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
@@ -51,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/create-html-entity-table $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/HTMLEntityNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLEntityTable ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLEntityTable ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python html/parser/create-html-entity-table -o "$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp" html/parser/HTMLEntityNames.in
 
 
@@ -61,8 +51,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSPropertyNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -72,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StylePropertyShorthand ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp ;
@@ -83,7 +73,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StyleBuilder ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
@@ -95,8 +85,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSValueKeywords ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -106,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py html/HTMLTagNames.in html/HTMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
@@ -121,7 +111,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_SVGNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_SVGNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py svg/SVGTagNames.in svg/SVGAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
@@ -136,7 +126,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventHeaders.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
@@ -148,7 +138,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventNames.h: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp ;
@@ -159,7 +149,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h ;
@@ -170,7 +160,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.h: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp ;
@@ -181,8 +171,8 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MathMLNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -192,8 +182,8 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -203,7 +193,7 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_FetchInitiatorTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_FetchInitiatorTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py fetch/FetchInitiatorTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
@@ -214,7 +204,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
@@ -225,7 +215,7 @@
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_InputTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
@@ -236,7 +226,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XLinkNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XLinkNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py svg/xlinkattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
@@ -247,7 +237,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNSNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNSNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlnsattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
@@ -258,7 +248,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
@@ -269,18 +259,18 @@
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
 
 
 ### Rules for action "MakeParser":
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/parser/BisonCSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeParser ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/parser/BisonCSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp"
 
 
 ### Rules for action "MakeTokenMatcherForViewport":
@@ -289,7 +279,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcherForViewport ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcherForViewport ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
@@ -299,15 +289,15 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementLookupTrie ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
 
 
 
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
-# "{'msvs_cygwin_shell': '1', 'extension': 'y', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'rule_name': 'bison', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h'], 'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison']}":
+### Generated for rule "third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_bison":
+# "{'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison'], 'rule_name': 'bison', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'extension': 'y', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h']}":
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
@@ -316,8 +306,8 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py css/CSSGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.h: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -327,13 +317,12 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py xml/XPathGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.h: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
 
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h \
 	$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp \
@@ -384,7 +373,7 @@
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
+	$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
@@ -397,7 +386,7 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
 LOCAL_GENERATED_SOURCES := \
-	third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
+	third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
 
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
@@ -430,14 +419,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -448,7 +438,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -483,7 +472,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -514,14 +502,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -532,7 +521,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -568,7 +556,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -579,11 +566,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+gyp_all_modules: third_party_WebKit_Source_core_make_core_generated_gyp
 
 # Alias gyp target name.
-.PHONY: make_core_derived_sources
-make_core_derived_sources: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+.PHONY: make_core_generated
+make_core_generated: third_party_WebKit_Source_core_make_core_generated_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/make_core_derived_sources.target.darwin-x86.mk b/Source/core/make_core_generated.target.linux-x86.mk
similarity index 85%
copy from Source/core/make_core_derived_sources.target.darwin-x86.mk
copy to Source/core/make_core_generated.target.linux-x86.mk
index 3e50140..00c2b62 100644
--- a/Source/core/make_core_derived_sources.target.darwin-x86.mk
+++ b/Source/core/make_core_generated.target.linux-x86.mk
@@ -3,8 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := GYP
-LOCAL_MODULE := third_party_WebKit_Source_core_make_core_derived_sources_gyp
-LOCAL_MODULE_STEM := make_core_derived_sources
+LOCAL_MODULE := third_party_WebKit_Source_core_make_core_generated_gyp
+LOCAL_MODULE_STEM := make_core_generated
 LOCAL_MODULE_SUFFIX := .stamp
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,26 +12,16 @@
 
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generate_test_support_idls_gyp)/generate_test_support_idls.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_generated_testing_idls_gyp)/generated_testing_idls.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp
 
-### Rules for action "generateV8ArrayBufferViewCustomScript":
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
-
-
 ### Rules for action "generateXMLViewerCSS":
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerCSS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerCSS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
@@ -41,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_generateXMLViewerJS ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_generateXMLViewerJS ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/xxd.py XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
@@ -51,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/create-html-entity-table $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/HTMLEntityNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLEntityTable ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLEntityTable ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python html/parser/create-html-entity-table -o "$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp" html/parser/HTMLEntityNames.in
 
 
@@ -61,8 +51,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSPropertyNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -72,7 +62,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StylePropertyShorthand ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.h: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp ;
@@ -83,7 +73,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_StyleBuilder ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.h: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp ;
@@ -95,8 +85,8 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_CSSValueKeywords ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --gperf gperf --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -106,7 +96,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py html/HTMLTagNames.in html/HTMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp ;
@@ -121,7 +111,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementWrapperFactory.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/SVGAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_SVGNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_SVGNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_factory.py svg/SVGTagNames.in svg/SVGAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp ;
@@ -136,7 +126,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" events/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventHeaders.h: $(gyp_shared_intermediate_dir)/blink/Event.cpp ;
@@ -148,7 +138,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventNames.h: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp ;
@@ -159,7 +149,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/EventFactory.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetFactory ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_event_factory.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h ;
@@ -170,7 +160,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTargetNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTargetNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTargetNames.h: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp ;
@@ -181,8 +171,8 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MathMLNames ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py html/parser/MathMLTagNames.in html/parser/MathMLAttributeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -192,8 +182,8 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/viewportAndroid.css $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"ENABLE_OPENTYPE_VERTICAL=1\""
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_UserAgentStyleSheets ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css css/viewportAndroid.css -- css/make-css-file-arrays.pl ../build/scripts/preprocessor.pm -- --defines "\"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=0\" \"ENABLE_HARFBUZZ_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_OPENTYPE_VERTICAL=1\"" --preprocessor "/usr/bin/gcc -E -P -x c++" --perl perl
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -203,7 +193,7 @@
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_FetchInitiatorTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_FetchInitiatorTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py fetch/FetchInitiatorTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.h: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp ;
@@ -214,7 +204,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/events/EventTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_EventTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_EventTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py events/EventTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/EventTypeNames.h: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp ;
@@ -225,7 +215,7 @@
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/forms/InputTypeNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_InputTypeNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_InputTypeNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_names.py html/forms/InputTypeNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/InputTypeNames.h: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp ;
@@ -236,7 +226,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XLinkNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XLinkNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py svg/xlinkattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
@@ -247,7 +237,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNSNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNSNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlnsattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
@@ -258,7 +248,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_qualified_names.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/MakeQualifiedNames.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_XMLNames ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_XMLNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_qualified_names.py xml/xmlattrs.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
@@ -269,18 +259,18 @@
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcher ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSTokenizer-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp"
 
 
 ### Rules for action "MakeParser":
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeParser ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_local_path := $(LOCAL_PATH)
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
+$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/parser/BisonCSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeParser ($@)"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/css/parser/BisonCSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp"
 
 
 ### Rules for action "MakeTokenMatcherForViewport":
@@ -289,7 +279,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_MakeTokenMatcherForViewport ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_MakeTokenMatcherForViewport ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_token_matcher.py ../core/html/HTMLMetaElement-in.cpp "$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp"
 
 
@@ -299,15 +289,15 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/hasher.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/make_element_lookup_trie.py $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/build/scripts/templates/ElementLookupTrie.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_HTMLElementLookupTrie ($@)"
+	@echo "Gyp action: third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_HTMLElementLookupTrie ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../build/scripts/make_element_lookup_trie.py html/HTMLTagNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
 $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp ;
 
 
 
-### Generated for rule "third_party_WebKit_Source_core_core_derived_sources_gyp_make_core_derived_sources_target_bison":
-# "{'msvs_cygwin_shell': '1', 'extension': 'y', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'rule_name': 'bison', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h'], 'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison']}":
+### Generated for rule "third_party_WebKit_Source_core_core_generated_gyp_make_core_generated_target_bison":
+# "{'action': ['python', '../build/scripts/rule_bison.py', '$(RULE_SOURCES)', '$(gyp_shared_intermediate_dir)/blink', 'bison'], 'rule_name': 'bison', 'rule_sources': ['css/CSSGrammar.y', 'xml/XPathGrammar.y'], 'extension': 'y', 'outputs': ['$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.cpp', '$(gyp_shared_intermediate_dir)/blink/%(INPUT_ROOT)s.h']}":
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
@@ -316,8 +306,8 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py css/CSSGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/CSSGrammar.h: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -327,13 +317,12 @@
 	mkdir -p $(gyp_shared_intermediate_dir)/blink; cd $(gyp_local_path)/third_party/WebKit/Source/core; python ../build/scripts/rule_bison.py xml/XPathGrammar.y "$(gyp_shared_intermediate_dir)/blink" bison
 
 $(gyp_shared_intermediate_dir)/blink/XPathGrammar.h: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp ;
-.PHONY: third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
-third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
+.PHONY: third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
+third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
 
 ### Finished generating for all rules
 
 GYP_GENERATED_OUTPUTS := \
-	$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h \
 	$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h \
 	$(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp \
@@ -384,7 +373,7 @@
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/blink/XMLNames.h \
 	$(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp \
-	$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp \
+	$(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp \
 	$(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.h \
@@ -397,7 +386,7 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
 LOCAL_GENERATED_SOURCES := \
-	third_party_WebKit_Source_core_make_core_derived_sources_gyp_rule_trigger
+	third_party_WebKit_Source_core_make_core_generated_gyp_rule_trigger
 
 GYP_COPIED_SOURCE_ORIGIN_DIRS :=
 
@@ -432,15 +421,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -451,7 +441,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -485,7 +474,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -518,17 +506,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -539,7 +526,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -574,7 +560,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -585,11 +570,11 @@
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+gyp_all_modules: third_party_WebKit_Source_core_make_core_generated_gyp
 
 # Alias gyp target name.
-.PHONY: make_core_derived_sources
-make_core_derived_sources: third_party_WebKit_Source_core_make_core_derived_sources_gyp
+.PHONY: make_core_generated
+make_core_generated: third_party_WebKit_Source_core_make_core_generated_gyp
 
 LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp
 LOCAL_UNINSTALLABLE_MODULE := true
diff --git a/Source/core/page/AutoscrollController.cpp b/Source/core/page/AutoscrollController.cpp
index 6c46028..281e16b 100644
--- a/Source/core/page/AutoscrollController.cpp
+++ b/Source/core/page/AutoscrollController.cpp
@@ -36,6 +36,7 @@
 #include "core/page/Page.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderBox.h"
+#include "core/rendering/RenderListBox.h"
 #include "wtf/CurrentTime.h"
 
 namespace WebCore {
@@ -73,6 +74,8 @@
         return;
     RenderBox* scrollable = RenderBox::findAutoscrollable(renderer);
     if (!scrollable)
+        scrollable = renderer->isListBox() ? toRenderListBox(renderer) : 0;
+    if (!scrollable)
         return;
     m_autoscrollType = AutoscrollForSelection;
     m_autoscrollRenderer = scrollable;
diff --git a/Source/core/page/Chrome.cpp b/Source/core/page/Chrome.cpp
index a7ae353..dc4774a 100644
--- a/Source/core/page/Chrome.cpp
+++ b/Source/core/page/Chrome.cpp
@@ -46,7 +46,6 @@
 namespace WebCore {
 
 using namespace HTMLNames;
-using namespace std;
 
 Chrome::Chrome(Page* page, ChromeClient* client)
     : m_page(page)
@@ -81,11 +80,6 @@
     InspectorInstrumentation::didScroll(m_page);
 }
 
-IntPoint Chrome::screenToRootView(const IntPoint& point) const
-{
-    return m_client->screenToRootView(point);
-}
-
 IntRect Chrome::rootViewToScreen(const IntRect& rect) const
 {
     return m_client->rootViewToScreen(rect);
@@ -101,11 +95,6 @@
     m_client->contentsSizeChanged(frame, size);
 }
 
-void Chrome::layoutUpdated(Frame* frame) const
-{
-    m_client->layoutUpdated(frame);
-}
-
 void Chrome::setWindowRect(const FloatRect& rect) const
 {
     m_client->setWindowRect(rect);
@@ -126,19 +115,14 @@
     m_client->focus();
 }
 
-void Chrome::unfocus() const
+bool Chrome::canTakeFocus(FocusType type) const
 {
-    m_client->unfocus();
+    return m_client->canTakeFocus(type);
 }
 
-bool Chrome::canTakeFocus(FocusDirection direction) const
+void Chrome::takeFocus(FocusType type) const
 {
-    return m_client->canTakeFocus(direction);
-}
-
-void Chrome::takeFocus(FocusDirection direction) const
-{
-    m_client->takeFocus(direction);
+    m_client->takeFocus(type);
 }
 
 void Chrome::focusedNodeChanged(Node* node) const
@@ -359,6 +343,12 @@
     return m_client->openDateTimeChooser(client, parameters);
 }
 
+void Chrome::openTextDataListChooser(HTMLInputElement& input)
+{
+    notifyPopupOpeningObservers();
+    m_client->openTextDataListChooser(input);
+}
+
 void Chrome::runOpenPanel(Frame* frame, PassRefPtr<FileChooser> fileChooser)
 {
     notifyPopupOpeningObservers();
diff --git a/Source/core/page/Chrome.h b/Source/core/page/Chrome.h
index d7536f3..ab2cf0c 100644
--- a/Source/core/page/Chrome.h
+++ b/Source/core/page/Chrome.h
@@ -23,7 +23,7 @@
 #define Chrome_h
 
 #include "core/loader/NavigationPolicy.h"
-#include "core/page/FocusDirection.h"
+#include "core/page/FocusType.h"
 #include "platform/Cursor.h"
 #include "platform/HostWindow.h"
 #include "wtf/Forward.h"
@@ -38,7 +38,7 @@
 class FileChooser;
 class FloatRect;
 class Frame;
-class Geolocation;
+class HTMLInputElement;
 class HitTestResult;
 class IntRect;
 class Node;
@@ -52,9 +52,9 @@
 struct ViewportDescription;
 struct WindowFeatures;
 
-class Chrome : public HostWindow {
+class Chrome FINAL : public HostWindow {
 public:
-    ~Chrome();
+    virtual ~Chrome();
 
     static PassOwnPtr<Chrome> create(Page*, ChromeClient*);
 
@@ -64,14 +64,12 @@
     virtual void invalidateContentsAndRootView(const IntRect&) OVERRIDE;
     virtual void invalidateContentsForSlowScroll(const IntRect&) OVERRIDE;
     virtual void scroll(const IntSize&, const IntRect&, const IntRect&) OVERRIDE;
-    virtual IntPoint screenToRootView(const IntPoint&) const OVERRIDE;
     virtual IntRect rootViewToScreen(const IntRect&) const OVERRIDE;
     virtual blink::WebScreenInfo screenInfo() const OVERRIDE;
 
     virtual void scheduleAnimation() OVERRIDE;
 
     void contentsSizeChanged(Frame*, const IntSize&) const;
-    void layoutUpdated(Frame*) const;
 
     void setCursor(const Cursor&);
 
@@ -81,10 +79,9 @@
     FloatRect pageRect() const;
 
     void focus() const;
-    void unfocus() const;
 
-    bool canTakeFocus(FocusDirection) const;
-    void takeFocus(FocusDirection) const;
+    bool canTakeFocus(FocusType) const;
+    void takeFocus(FocusType) const;
 
     void focusedNodeChanged(Node*) const;
 
@@ -121,6 +118,7 @@
 
     PassOwnPtr<ColorChooser> createColorChooser(ColorChooserClient*, const Color& initialColor);
     PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&);
+    void openTextDataListChooser(HTMLInputElement&);
 
     void runOpenPanel(Frame*, PassRefPtr<FileChooser>);
     void enumerateChosenDirectory(FileChooser*);
diff --git a/Source/core/page/ChromeClient.h b/Source/core/page/ChromeClient.h
index 5ab0c86..b92337b 100644
--- a/Source/core/page/ChromeClient.h
+++ b/Source/core/page/ChromeClient.h
@@ -27,13 +27,13 @@
 #include "core/loader/FrameLoader.h"
 #include "core/loader/NavigationPolicy.h"
 #include "core/frame/ConsoleTypes.h"
-#include "core/page/FocusDirection.h"
-#include "core/platform/PopupMenuClient.h"
+#include "core/page/FocusType.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "platform/Cursor.h"
 #include "platform/HostWindow.h"
 #include "platform/PopupMenu.h"
+#include "platform/PopupMenuClient.h"
 #include "platform/graphics/GraphicsContext.h"
 #include "platform/scroll/ScrollTypes.h"
 #include "wtf/Forward.h"
@@ -57,8 +57,6 @@
 class FileChooser;
 class FloatRect;
 class Frame;
-class Geolocation;
-class GraphicsContext3D;
 class GraphicsLayer;
 class GraphicsLayerFactory;
 class HitTestResult;
@@ -69,7 +67,6 @@
 class PagePopup;
 class PagePopupClient;
 class PagePopupDriver;
-class PopupContainer;
 class PopupMenuClient;
 class SecurityOrigin;
 class Widget;
@@ -90,10 +87,9 @@
     virtual FloatRect pageRect() = 0;
 
     virtual void focus() = 0;
-    virtual void unfocus() = 0;
 
-    virtual bool canTakeFocus(FocusDirection) = 0;
-    virtual void takeFocus(FocusDirection) = 0;
+    virtual bool canTakeFocus(FocusType) = 0;
+    virtual void takeFocus(FocusType) = 0;
 
     virtual void focusedNodeChanged(Node*) = 0;
 
@@ -145,13 +141,14 @@
     virtual void invalidateContentsAndRootView(const IntRect&) = 0;
     virtual void invalidateContentsForSlowScroll(const IntRect&) = 0;
     virtual void scroll(const IntSize&, const IntRect&, const IntRect&) = 0;
-    virtual IntPoint screenToRootView(const IntPoint&) const = 0;
     virtual IntRect rootViewToScreen(const IntRect&) const = 0;
     virtual blink::WebScreenInfo screenInfo() const = 0;
     virtual void setCursor(const Cursor&) = 0;
     virtual void scheduleAnimation() = 0;
     // End methods used by HostWindow.
 
+    virtual bool isCompositorFramePending() const = 0;
+
     virtual void dispatchViewportPropertiesDidChange(const ViewportDescription&) const { }
 
     virtual void contentsSizeChanged(Frame*, const IntSize&) const = 0;
@@ -179,6 +176,8 @@
     //    ENABLE(INPUT_MULTIPLE_FIELDS_UI)
     virtual PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) = 0;
 
+    virtual void openTextDataListChooser(HTMLInputElement&) = 0;
+
     virtual void runOpenPanel(Frame*, PassRefPtr<FileChooser>) = 0;
 
     // Asychronous request to enumerate all files in a directory chosen by the user.
@@ -193,12 +192,6 @@
 
     // Pass 0 as the GraphicsLayer to detatch the root layer.
     virtual void attachRootGraphicsLayer(Frame*, GraphicsLayer*) = 0;
-    // Sets a flag to specify that the view needs to be updated, so we need
-    // to do an eager layout before the drawing.
-    virtual void scheduleCompositingLayerFlush() = 0;
-    // Returns whether or not the client can render the composited layer,
-    // regardless of the settings.
-    virtual bool allowsAcceleratedCompositing() const { return true; }
 
     enum CompositingTrigger {
         ThreeDTransformTrigger = 1 << 0,
@@ -225,10 +218,6 @@
     // Checks if there is an opened popup, called by RenderMenuList::showPopup().
     virtual bool hasOpenedPopup() const = 0;
     virtual PassRefPtr<PopupMenu> createPopupMenu(Frame&, PopupMenuClient*) const = 0;
-    // Creates a PagePopup object, and shows it beside originBoundsInRootView.
-    // The return value can be 0.
-    virtual PagePopup* openPagePopup(PagePopupClient*, const IntRect& originBoundsInRootView) = 0;
-    virtual void closePagePopup(PagePopup*) = 0;
     // For testing.
     virtual void setPagePopupDriver(PagePopupDriver*) = 0;
     virtual void resetPagePopupDriver() = 0;
@@ -254,11 +243,9 @@
 
     virtual bool requestPointerLock() { return false; }
     virtual void requestPointerUnlock() { }
-    virtual bool isPointerLocked() { return false; }
 
     virtual FloatSize minimumWindowSize() const { return FloatSize(100, 100); };
 
-    virtual bool isEmptyChromeClient() const { return false; }
     virtual bool isChromeClientImpl() const { return false; }
 
     virtual void didAssociateFormControls(const Vector<RefPtr<Element> >&) { };
@@ -266,20 +253,14 @@
     virtual void didEndEditingOnTextField(HTMLInputElement&) { }
     virtual void handleKeyboardEventOnTextField(HTMLInputElement&, KeyboardEvent&) { }
 
+    // FIXME: Remove this method once we have input routing in the browser
+    // process. See http://crbug.com/339659.
+    virtual void forwardInputEvent(WebCore::Document*, WebCore::Event*) { }
+
     // Input mehtod editor related functions.
     virtual void didCancelCompositionOnSelectionChange() { }
     virtual void willSetInputMethodState() { }
 
-    // Notifies the client of a new popup widget.  The client should place
-    // and size the widget with the given bounds, relative to the screen.
-    // If handleExternal is true, then drawing and input handling for the
-    // popup will be handled by the external embedder.
-    virtual void popupOpened(PopupContainer* popupContainer, const IntRect& bounds,
-                             bool handleExternal) = 0;
-
-    // Notifies the client a popup was closed.
-    virtual void popupClosed(PopupContainer* popupContainer) = 0;
-
 protected:
     virtual ~ChromeClient() { }
 };
diff --git a/Source/core/page/CreateWindow.cpp b/Source/core/page/CreateWindow.cpp
index 1a76d57..2b6b5b8 100644
--- a/Source/core/page/CreateWindow.cpp
+++ b/Source/core/page/CreateWindow.cpp
@@ -29,11 +29,13 @@
 
 #include "core/dom/Document.h"
 #include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/Settings.h"
 #include "core/loader/FrameLoadRequest.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
+#include "core/page/FocusController.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
 #include "core/page/WindowFeatures.h"
 #include "platform/network/ResourceRequest.h"
 #include "platform/weborigin/KURL.h"
@@ -48,10 +50,8 @@
 
     if (!request.frameName().isEmpty() && request.frameName() != "_blank" && policy == NavigationPolicyIgnore) {
         if (Frame* frame = lookupFrame->loader().findFrameForNavigation(request.frameName(), openerFrame->document())) {
-            if (request.frameName() != "_self") {
-                if (Page* page = frame->page())
-                    page->chrome().focus();
-            }
+            if (request.frameName() != "_self")
+                frame->page()->focusController().setFocusedFrame(frame);
             created = false;
             return frame;
         }
@@ -76,6 +76,7 @@
     Page* page = oldPage->chrome().client().createWindow(openerFrame, request, features, policy, shouldSendReferrer);
     if (!page)
         return 0;
+    FrameHost* host = &page->frameHost();
 
     Frame* frame = page->mainFrame();
 
@@ -84,14 +85,14 @@
     if (request.frameName() != "_blank")
         frame->tree().setName(request.frameName());
 
-    page->chrome().setWindowFeatures(features);
+    host->chrome().setWindowFeatures(features);
 
     // 'x' and 'y' specify the location of the window, while 'width' and 'height'
     // specify the size of the viewport. We can only resize the window, so adjust
     // for the difference between the window size and the viewport size.
 
-    FloatRect windowRect = page->chrome().windowRect();
-    FloatSize viewportSize = page->chrome().pageRect().size();
+    FloatRect windowRect = host->chrome().windowRect();
+    FloatSize viewportSize = host->chrome().pageRect().size();
 
     if (features.xSet)
         windowRect.setX(features.x);
@@ -103,10 +104,10 @@
         windowRect.setHeight(features.height + (windowRect.height() - viewportSize.height()));
 
     // Ensure non-NaN values, minimum size as well as being within valid screen area.
-    FloatRect newWindowRect = DOMWindow::adjustWindowRect(page, windowRect);
+    FloatRect newWindowRect = DOMWindow::adjustWindowRect(frame, windowRect);
 
-    page->chrome().setWindowRect(newWindowRect);
-    page->chrome().show(policy);
+    host->chrome().setWindowRect(newWindowRect);
+    host->chrome().show(policy);
 
     created = true;
     return frame;
@@ -125,11 +126,11 @@
     }
 
     // For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
-    String referrer = SecurityPolicy::generateReferrerHeader(firstFrame->document()->referrerPolicy(), completedURL, firstFrame->loader().outgoingReferrer());
+    Referrer referrer(SecurityPolicy::generateReferrerHeader(firstFrame->document()->referrerPolicy(), completedURL, firstFrame->document()->outgoingReferrer()), firstFrame->document()->referrerPolicy());
 
     ResourceRequest request(completedURL, referrer);
-    FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader().outgoingOrigin());
-    FrameLoadRequest frameRequest(activeWindow->document()->securityOrigin(), request, frameName);
+    FrameLoader::addHTTPOriginIfNeeded(request, AtomicString(firstFrame->document()->outgoingOrigin()));
+    FrameLoadRequest frameRequest(activeWindow->document(), request, frameName);
 
     // We pass the opener frame for the lookupFrame in case the active frame is different from
     // the opener frame, and the name references a frame relative to the opener frame.
@@ -148,10 +149,10 @@
         function(newFrame->domWindow(), functionContext);
 
     if (created) {
-        FrameLoadRequest request(activeWindow->document()->securityOrigin(), ResourceRequest(completedURL, referrer));
+        FrameLoadRequest request(activeWindow->document(), ResourceRequest(completedURL, referrer));
         newFrame->loader().load(request);
     } else if (!urlString.isEmpty()) {
-        newFrame->navigationScheduler().scheduleLocationChange(activeWindow->document()->securityOrigin(), completedURL.string(), referrer, false);
+        newFrame->navigationScheduler().scheduleLocationChange(activeWindow->document(), completedURL.string(), referrer, false);
     }
     return newFrame;
 }
diff --git a/Source/core/page/DOMSelection.cpp b/Source/core/page/DOMSelection.cpp
index 4de89de..fb95fef 100644
--- a/Source/core/page/DOMSelection.cpp
+++ b/Source/core/page/DOMSelection.cpp
@@ -59,7 +59,7 @@
 }
 
 DOMSelection::DOMSelection(const TreeScope* treeScope)
-    : DOMWindowProperty(treeScope->rootNode()->document().frame())
+    : DOMWindowProperty(treeScope->rootNode().document().frame())
     , m_treeScope(treeScope)
 {
     ScriptWrappable::init(this);
@@ -272,22 +272,6 @@
     m_frame->selection().moveTo(visibleBase, visibleExtent);
 }
 
-void DOMSelection::setPosition(Node* node, int offset, ExceptionState& exceptionState)
-{
-    if (!m_frame)
-        return;
-    if (offset < 0) {
-        exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is not a valid offset.");
-        return;
-    }
-
-    if (!isValidForPosition(node))
-        return;
-
-    // FIXME: Eliminate legacy editing positions
-    m_frame->selection().moveTo(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
-}
-
 void DOMSelection::modify(const String& alterString, const String& directionString, const String& granularityString)
 {
     if (!m_frame)
diff --git a/Source/core/page/DOMSelection.h b/Source/core/page/DOMSelection.h
index 0b4adfe..693349b 100644
--- a/Source/core/page/DOMSelection.h
+++ b/Source/core/page/DOMSelection.h
@@ -47,7 +47,7 @@
 class TreeScope;
 class VisibleSelection;
 
-class DOMSelection : public RefCounted<DOMSelection>, public ScriptWrappable, public DOMWindowProperty {
+class DOMSelection FINAL : public RefCounted<DOMSelection>, public ScriptWrappable, public DOMWindowProperty {
 public:
     static PassRefPtr<DOMSelection> create(const TreeScope* treeScope) { return adoptRef(new DOMSelection(treeScope)); }
 
@@ -61,7 +61,6 @@
     int extentOffset() const;
     String type() const;
     void setBaseAndExtent(Node* baseNode, int baseOffset, Node* extentNode, int extentOffset, ExceptionState&);
-    void setPosition(Node*, int offset, ExceptionState&);
     void modify(const String& alter, const String& direction, const String& granularity);
 
     // Mozilla Selection Object API
diff --git a/Source/core/page/DOMWindowPagePopup.h b/Source/core/page/DOMWindowPagePopup.h
index aa401a4..0a2e8d8 100644
--- a/Source/core/page/DOMWindowPagePopup.h
+++ b/Source/core/page/DOMWindowPagePopup.h
@@ -39,12 +39,12 @@
 class PagePopupClient;
 class PagePopupController;
 
-class DOMWindowPagePopup : public Supplement<DOMWindow> {
+class DOMWindowPagePopup FINAL : public Supplement<DOMWindow> {
 public:
     static PagePopupController* pagePopupController(DOMWindow*);
     static void install(DOMWindow*, PagePopupClient*);
     static void uninstall(DOMWindow*);
-    ~DOMWindowPagePopup();
+    virtual ~DOMWindowPagePopup();
 
 private:
     explicit DOMWindowPagePopup(PagePopupClient*);
diff --git a/Source/core/page/DragController.cpp b/Source/core/page/DragController.cpp
index c943e8a..fe17aef 100644
--- a/Source/core/page/DragController.cpp
+++ b/Source/core/page/DragController.cpp
@@ -29,8 +29,9 @@
 
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/Clipboard.h"
-#include "core/dom/ClipboardAccessPolicy.h"
+#include "core/clipboard/Clipboard.h"
+#include "core/clipboard/ClipboardAccessPolicy.h"
+#include "core/clipboard/DataObject.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/Element.h"
@@ -60,14 +61,13 @@
 #include "core/page/DragState.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/DragImage.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
+#include "platform/DragImage.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/graphics/Image.h"
 #include "platform/graphics/ImageOrientation.h"
@@ -110,13 +110,11 @@
 
 static PlatformMouseEvent createMouseEvent(DragData* dragData)
 {
-    bool shiftKey, ctrlKey, altKey, metaKey;
-    shiftKey = ctrlKey = altKey = metaKey = false;
     int keyState = dragData->modifierKeyState();
-    shiftKey = static_cast<bool>(keyState & PlatformEvent::ShiftKey);
-    ctrlKey = static_cast<bool>(keyState & PlatformEvent::CtrlKey);
-    altKey = static_cast<bool>(keyState & PlatformEvent::AltKey);
-    metaKey = static_cast<bool>(keyState & PlatformEvent::MetaKey);
+    bool shiftKey = static_cast<bool>(keyState & PlatformEvent::ShiftKey);
+    bool ctrlKey = static_cast<bool>(keyState & PlatformEvent::CtrlKey);
+    bool altKey = static_cast<bool>(keyState & PlatformEvent::AltKey);
+    bool metaKey = static_cast<bool>(keyState & PlatformEvent::MetaKey);
 
     return PlatformMouseEvent(dragData->clientPosition(), dragData->globalPosition(),
                               LeftButton, PlatformEvent::MouseMoved, 0, shiftKey, ctrlKey, altKey,
@@ -166,7 +164,7 @@
             String url = dragData->asURL(DragData::DoNotConvertFilenames, &title);
             if (!url.isEmpty()) {
                 RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(document);
-                anchor->setHref(url);
+                anchor->setHref(AtomicString(url));
                 if (title.isEmpty()) {
                     // Try the plain text first because the url might be normalized or escaped.
                     if (dragData->containsPlainText())
@@ -656,8 +654,7 @@
                 return node;
             }
             // Other draggable elements are considered unselectable.
-            if (isHTMLAnchorElement(node)
-                && toHTMLAnchorElement(node)->isLiveLink()) {
+            if (node->hasTagName(HTMLNames::aTag) && toHTMLAnchorElement(node)->isLiveLink()) {
                 candidateDragType = DragSourceActionLink;
                 break;
             }
diff --git a/Source/core/page/DragData.cpp b/Source/core/page/DragData.cpp
index 79a2257..4e1a477 100644
--- a/Source/core/page/DragData.cpp
+++ b/Source/core/page/DragData.cpp
@@ -27,12 +27,12 @@
 #include "config.h"
 #include "core/page/DragData.h"
 
+#include "core/clipboard/DataObject.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/Range.h"
 #include "core/editing/markup.h"
 #include "core/frame/Frame.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
 #include "modules/filesystem/DraggedIsolatedFileSystem.h"
 #include "platform/FileMetadata.h"
 #include "platform/clipboard/ClipboardMimeTypes.h"
@@ -41,7 +41,7 @@
 
 namespace WebCore {
 
-DragData::DragData(ChromiumDataObject* data, const IntPoint& clientPosition, const IntPoint& globalPosition,
+DragData::DragData(DataObject* data, const IntPoint& clientPosition, const IntPoint& globalPosition,
     DragOperation sourceOperationMask, DragApplicationFlags flags)
     : m_clientPosition(clientPosition)
     , m_globalPosition(globalPosition)
@@ -61,7 +61,7 @@
 {
 }
 
-static bool containsHTML(const ChromiumDataObject* dropData)
+static bool containsHTML(const DataObject* dropData)
 {
     return dropData->types().contains(mimeTypeTextHTML);
 }
diff --git a/Source/core/page/DragData.h b/Source/core/page/DragData.h
index 33c108c..83a11b0 100644
--- a/Source/core/page/DragData.h
+++ b/Source/core/page/DragData.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class ChromiumDataObject;
+class DataObject;
 class DocumentFragment;
 class Frame;
 class KURL;
@@ -54,12 +54,12 @@
     enum FilenameConversionPolicy { DoNotConvertFilenames, ConvertFilenames };
 
     // clientPosition is taken to be the position of the drag event within the target window, with (0,0) at the top left
-    DragData(ChromiumDataObject*, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
+    DragData(DataObject*, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
     DragData(const String& dragStorageName, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
     const IntPoint& clientPosition() const { return m_clientPosition; }
     const IntPoint& globalPosition() const { return m_globalPosition; }
     DragApplicationFlags flags() const { return m_applicationFlags; }
-    ChromiumDataObject* platformData() const { return m_platformDragData; }
+    DataObject* platformData() const { return m_platformDragData; }
     DragOperation draggingSourceOperationMask() const { return m_draggingSourceOperationMask; }
     bool containsURL(FilenameConversionPolicy filenamePolicy = ConvertFilenames) const;
     bool containsPlainText() const;
@@ -78,7 +78,7 @@
 private:
     IntPoint m_clientPosition;
     IntPoint m_globalPosition;
-    ChromiumDataObject* m_platformDragData;
+    DataObject* m_platformDragData;
     DragOperation m_draggingSourceOperationMask;
     DragApplicationFlags m_applicationFlags;
 };
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index c0466e3..acc91dc 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -32,7 +32,8 @@
 #include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/Clipboard.h"
+#include "core/clipboard/Clipboard.h"
+#include "core/clipboard/DataObject.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentMarkerController.h"
 #include "core/dom/FullscreenElementStack.h"
@@ -72,15 +73,13 @@
 #include "core/inspector/InspectorController.h"
 #include "core/page/MouseEventWithHitTestResults.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/page/SpatialNavigation.h"
 #include "core/page/TouchAdjustment.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderRegion.h"
 #include "core/rendering/RenderTextControlSingleLine.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
@@ -255,69 +254,6 @@
     }
 }
 
-static inline bool scrollNodeLogically(float delta, ScrollGranularity granularity, ScrollLogicalDirection direction, Node* node, Node** stopNode)
-{
-    if (!delta)
-        return false;
-    if (!node->renderer())
-        return false;
-
-    RenderBox* curBox = node->renderer()->enclosingBox();
-
-    while (curBox && !curBox->isRenderView()) {
-        ScrollDirection physicalDirection =
-            logicalToPhysical(direction, curBox->isHorizontalWritingMode(), curBox->style()->isFlippedBlocksWritingMode());
-
-        if (curBox->scroll(physicalDirection, granularity, delta)) {
-            if (stopNode)
-                *stopNode = curBox->node();
-            return true;
-        }
-
-        if (stopNode && *stopNode && curBox->node() == *stopNode)
-            return true;
-
-        curBox = curBox->containingBlock();
-    }
-
-    return false;
-}
-
-static inline bool scrollNode(float delta, ScrollGranularity granularity, ScrollDirection positiveDirection, ScrollDirection negativeDirection, Node* node, Node** stopNode, IntPoint absolutePoint = IntPoint())
-{
-    if (!delta)
-        return false;
-    if (!node->renderer())
-        return false;
-
-    float absDelta = delta > 0 ? delta : -delta;
-    RenderBox* curBox = node->renderer()->enclosingBox();
-
-    while (curBox && !curBox->isRenderView()) {
-        if (curBox->scroll(delta < 0 ? negativeDirection : positiveDirection, granularity, absDelta)) {
-            if (stopNode)
-                *stopNode = curBox->node();
-            return true;
-        }
-
-        if (stopNode && *stopNode && curBox->node() == *stopNode)
-            return true;
-
-        // FIXME: This should probably move to a virtual method on RenderBox, something like RenderBox::scrollAncestor, and specialized for RenderFlowThread
-        curBox = curBox->containingBlock();
-        if (curBox && curBox->isRenderNamedFlowThread()) {
-            RenderBox* flowedBox = curBox;
-
-            if (RenderBox* startBox = node->renderBox())
-                flowedBox = startBox;
-
-            curBox = toRenderFlowThread(curBox)->regionFromAbsolutePointAndBox(absolutePoint, flowedBox);
-        }
-    }
-
-    return false;
-}
-
 // Refetch the event target node if it is removed or currently is the shadow node inside an <input> element.
 // If a mouse event handler changes the input element type to one that has a widget associated,
 // we'd like to EventHandler::handleMousePressEvent to pass the event to the widget and thus the
@@ -338,7 +274,6 @@
     , m_mouseDownMayStartDrag(false)
     , m_mouseDownWasSingleClickInSelection(false)
     , m_selectionInitiationState(HaveNotStartedSelection)
-    , m_panScrollButtonPressed(false)
     , m_hoverTimer(this, &EventHandler::hoverTimerFired)
     , m_cursorUpdateTimer(this, &EventHandler::cursorUpdateTimerFired)
     , m_mouseDownMayStartAutoscroll(false)
@@ -363,7 +298,6 @@
     , m_syntheticPageScaleFactor(0)
     , m_activeIntervalTimer(this, &EventHandler::activeIntervalTimerFired)
     , m_lastShowPressTimestamp(0)
-    , m_shouldKeepActiveForMinInterval(false)
 {
 }
 
@@ -420,7 +354,6 @@
     m_mouseDownMayStartSelect = false;
     m_mouseDownMayStartDrag = false;
     m_lastShowPressTimestamp = 0;
-    m_shouldKeepActiveForMinInterval = false;
     m_lastDeferredTapElement = 0;
 }
 
@@ -992,9 +925,12 @@
     return m_mousePressNode.get();
 }
 
-bool EventHandler::scrollOverflow(ScrollDirection direction, ScrollGranularity granularity, Node* startingNode)
+bool EventHandler::scroll(ScrollDirection direction, ScrollGranularity granularity, Node* startNode, Node** stopNode, float delta, IntPoint absolutePoint)
 {
-    Node* node = startingNode;
+    if (!delta)
+        return false;
+
+    Node* node = startNode;
 
     if (!node)
         node = m_frame->document()->focusedElement();
@@ -1002,55 +938,38 @@
     if (!node)
         node = m_mousePressNode.get();
 
-    // FIXME: Remove once scrollNode is refactored
-    ScrollDirection negative = ScrollUp;
-    if (direction == ScrollLeft)
-        negative = ScrollRight;
-    else if (direction == ScrollRight)
-        negative = ScrollLeft;
-    else if (direction == ScrollUp)
-        negative = ScrollDown;
-    else if (direction == ScrollDown)
-        negative = ScrollUp;
+    if (!node || !node->renderer())
+        return false;
 
-    if (node) {
-        RenderObject* r = node->renderer();
-        if (r && !r->isListBox() && scrollNode(1.0f, granularity, direction, negative, node, 0)) {
+    RenderBox* curBox = node->renderer()->enclosingBox();
+    while (curBox && !curBox->isRenderView()) {
+        ScrollDirection physicalDirection = toPhysicalDirection(
+            direction, curBox->isHorizontalWritingMode(), curBox->style()->isFlippedBlocksWritingMode());
+
+        // If we're at the stopNode, we should try to scroll it but we shouldn't bubble past it
+        bool shouldStopBubbling = stopNode && *stopNode && curBox->node() == *stopNode;
+        bool didScroll = curBox->scroll(physicalDirection, granularity, delta);
+
+        if (didScroll && stopNode)
+            *stopNode = curBox->node();
+
+        if (didScroll || shouldStopBubbling) {
             setFrameWasScrolledByUser();
             return true;
         }
+
+        curBox = curBox->containingBlock();
     }
 
     return false;
 }
 
-bool EventHandler::logicalScrollOverflow(ScrollLogicalDirection direction, ScrollGranularity granularity, Node* startingNode)
-{
-    Node* node = startingNode;
-
-    if (!node)
-        node = m_frame->document()->focusedElement();
-
-    if (!node)
-        node = m_mousePressNode.get();
-
-    if (node) {
-        RenderObject* r = node->renderer();
-        if (r && !r->isListBox() && scrollNodeLogically(1.0f, granularity, direction, node, 0)) {
-            setFrameWasScrolledByUser();
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool EventHandler::scrollRecursively(ScrollDirection direction, ScrollGranularity granularity, Node* startingNode)
+bool EventHandler::bubblingScroll(ScrollDirection direction, ScrollGranularity granularity, Node* startingNode)
 {
     // The layout needs to be up to date to determine if we can scroll. We may be
     // here because of an onLoad event, in which case the final layout hasn't been performed yet.
     m_frame->document()->updateLayoutIgnorePendingStylesheets();
-    if (scrollOverflow(direction, granularity, startingNode))
+    if (scroll(direction, granularity, startingNode))
         return true;
     Frame* frame = m_frame;
     FrameView* view = frame->view();
@@ -1059,31 +978,7 @@
     frame = frame->tree().parent();
     if (!frame)
         return false;
-    return frame->eventHandler().scrollRecursively(direction, granularity, m_frame->ownerElement());
-}
-
-bool EventHandler::logicalScrollRecursively(ScrollLogicalDirection direction, ScrollGranularity granularity, Node* startingNode)
-{
-    // The layout needs to be up to date to determine if we can scroll. We may be
-    // here because of an onLoad event, in which case the final layout hasn't been performed yet.
-    m_frame->document()->updateLayoutIgnorePendingStylesheets();
-    if (logicalScrollOverflow(direction, granularity, startingNode))
-        return true;
-    Frame* frame = m_frame;
-    FrameView* view = frame->view();
-
-    bool scrolled = false;
-    if (view && view->logicalScroll(direction, granularity))
-        scrolled = true;
-
-    if (scrolled)
-        return true;
-
-    frame = frame->tree().parent();
-    if (!frame)
-        return false;
-
-    return frame->eventHandler().logicalScrollRecursively(direction, granularity, m_frame->ownerElement());
+    return frame->eventHandler().bubblingScroll(direction, granularity, m_frame->ownerElement());
 }
 
 IntPoint EventHandler::lastKnownMousePosition() const
@@ -1409,7 +1304,10 @@
     }
     m_mouseDownWasInSubframe = false;
 
-    HitTestRequest request(HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+    HitTestRequest::HitTestRequestType hitType = HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
+    if (mouseEvent.fromTouch())
+        hitType |= HitTestRequest::ReadOnly;
+    HitTestRequest request(hitType);
     // Save the document point we generate in case the window coordinate is invalidated by what happens
     // when we dispatch the event.
     LayoutPoint documentPoint = documentPointForWindowPoint(m_frame, mouseEvent.position());
@@ -1612,6 +1510,9 @@
     }
 
     HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
+    if (mouseEvent.fromTouch())
+        hitType |= HitTestRequest::ReadOnly;
+
     if (m_mousePressed)
         hitType |= HitTestRequest::Active;
     else if (onlyUpdateScrollbars) {
@@ -1691,6 +1592,15 @@
     m_clickNode = 0;
 }
 
+static Node* parentForClickEvent(const Node& node)
+{
+    // IE doesn't dispatch click events for mousedown/mouseup events across form
+    // controls.
+    if (node.isHTMLElement() && toHTMLElement(node).isInteractiveContent())
+        return 0;
+    return node.parentOrShadowHostNode();
+}
+
 bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
 {
     RefPtr<FrameView> protector(m_frame->view());
@@ -1734,7 +1644,7 @@
     }
 
     HitTestRequest::HitTestRequestType hitType = HitTestRequest::Release | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
-    if (m_shouldKeepActiveForMinInterval)
+    if (mouseEvent.fromTouch())
         hitType |= HitTestRequest::ReadOnly;
     HitTestRequest request(hitType);
     MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseEvent);
@@ -1744,9 +1654,6 @@
     if (subframe && passMouseReleaseEventToSubframe(mev, subframe))
         return true;
 
-    if (m_shouldKeepActiveForMinInterval)
-        m_lastDeferredTapElement = mev.hitTestResult().innerElement();
-
     bool swallowMouseUpEvent = !dispatchMouseEvent(EventTypeNames::mouseup, mev.targetNode(), true, m_clickCount, mouseEvent, false);
 
     bool contextMenuEvent = mouseEvent.button() == RightButton;
@@ -1758,7 +1665,7 @@
 
     bool swallowClickEvent = false;
     if (m_clickCount > 0 && !contextMenuEvent && mev.targetNode() && m_clickNode) {
-        if (Node* clickTargetNode = mev.targetNode()->commonAncestorOverShadowBoundary(*m_clickNode))
+        if (Node* clickTargetNode = mev.targetNode()->commonAncestor(*m_clickNode, parentForClickEvent))
             swallowClickEvent = !dispatchMouseEvent(EventTypeNames::click, clickTargetNode, true, m_clickCount, mouseEvent, true);
     }
 
@@ -1816,7 +1723,6 @@
     if (!view)
         return false;
 
-    view->resetDeferredRepaintDelay();
     RefPtr<MouseEvent> me = MouseEvent::create(eventType,
         true, true, m_frame->document()->domWindow(),
         0, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(),
@@ -2110,9 +2016,6 @@
 
 bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targetNode, bool /*cancelable*/, int clickCount, const PlatformMouseEvent& mouseEvent, bool setUnder)
 {
-    if (FrameView* view = m_frame->view())
-        view->resetDeferredRepaintDelay();
-
     updateMouseEventTargetNode(targetNode, mouseEvent, setUnder);
 
     bool swallowEvent = false;
@@ -2164,7 +2067,7 @@
         // clear swallowEvent if the page already set it (e.g., by canceling
         // default behavior).
         if (element) {
-            if (!page->focusController().setFocusedElement(element, m_frame, FocusDirectionMouse))
+            if (!page->focusController().setFocusedElement(element, m_frame, FocusTypeMouse))
                 swallowEvent = true;
         } else {
             // We call setFocusedElement even with !element in order to blur
@@ -2296,10 +2199,10 @@
 
     // Break up into two scrolls if we need to.  Diagonal movement on
     // a MacBook pro is an example of a 2-dimensional mouse wheel event (where both deltaX and deltaY can be set).
-    if (scrollNode(wheelEvent->deltaX(), granularity, ScrollRight, ScrollLeft, startNode, &stopNode, roundedIntPoint(wheelEvent->absoluteLocation())))
+    if (scroll(ScrollRight, granularity, startNode, &stopNode, wheelEvent->deltaX(), roundedIntPoint(wheelEvent->absoluteLocation())))
         wheelEvent->setDefaultHandled();
 
-    if (scrollNode(wheelEvent->deltaY(), granularity, ScrollDown, ScrollUp, startNode, &stopNode, roundedIntPoint(wheelEvent->absoluteLocation())))
+    if (scroll(ScrollDown, granularity, startNode, &stopNode, wheelEvent->deltaY(), roundedIntPoint(wheelEvent->absoluteLocation())))
         wheelEvent->setDefaultHandled();
 
     if (!m_latchedWheelEventNode)
@@ -2336,6 +2239,7 @@
     case PlatformEvent::GestureScrollUpdate:
     case PlatformEvent::GestureScrollUpdateWithoutPropagation:
     case PlatformEvent::GestureScrollEnd:
+    case PlatformEvent::GestureFlingStart:
         // Handle directly in main frame
         break;
 
@@ -2364,24 +2268,31 @@
     Scrollbar* scrollbar = 0;
     if (gestureEvent.type() == PlatformEvent::GestureScrollEnd
         || gestureEvent.type() == PlatformEvent::GestureScrollUpdate
-        || gestureEvent.type() == PlatformEvent::GestureScrollUpdateWithoutPropagation) {
+        || gestureEvent.type() == PlatformEvent::GestureScrollUpdateWithoutPropagation
+        || gestureEvent.type() == PlatformEvent::GestureFlingStart) {
         scrollbar = m_scrollbarHandlingScrollGesture.get();
         eventTarget = m_scrollGestureHandlingNode.get();
     }
 
     HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent;
+    double activeInterval = 0;
+    bool shouldKeepActiveForMinInterval = false;
     if (gestureEvent.type() == PlatformEvent::GestureShowPress
         || gestureEvent.type() == PlatformEvent::GestureTapUnconfirmed) {
         hitType |= HitTestRequest::Active;
     } else if (gestureEvent.type() == PlatformEvent::GestureTapDownCancel) {
         hitType |= HitTestRequest::Release;
         // A TapDownCancel received when no element is active shouldn't really be changing hover state.
-        if (!m_frame->document()->activeElement())
+        if (!m_frame->document()->activeHoverElement())
             hitType |= HitTestRequest::ReadOnly;
     } else if (gestureEvent.type() == PlatformEvent::GestureTap) {
-        // The mouseup event synthesized for this gesture will clear the active state of the
-        // targeted node, so performing a ReadOnly hit test here is fine.
-        hitType |= HitTestRequest::ReadOnly;
+        hitType |= HitTestRequest::Release;
+        // If the Tap is received very shortly after ShowPress, we want to delay clearing
+        // of the active state so that it's visible to the user for at least one frame.
+        activeInterval = WTF::currentTime() - m_lastShowPressTimestamp;
+        shouldKeepActiveForMinInterval = m_lastShowPressTimestamp && activeInterval < minimumActiveInterval;
+        if (shouldKeepActiveForMinInterval)
+            hitType |= HitTestRequest::ReadOnly;
     }
     else
         hitType |= HitTestRequest::Active | HitTestRequest::ReadOnly;
@@ -2389,6 +2300,12 @@
     if ((!scrollbar && !eventTarget) || !(hitType & HitTestRequest::ReadOnly)) {
         IntPoint hitTestPoint = m_frame->view()->windowToContents(adjustedPoint);
         HitTestResult result = hitTestResultAtPoint(hitTestPoint, hitType | HitTestRequest::AllowFrameScrollbars);
+
+        if (shouldKeepActiveForMinInterval) {
+            m_lastDeferredTapElement = result.innerElement();
+            m_activeIntervalTimer.startOneShot(minimumActiveInterval - activeInterval);
+        }
+
         eventTarget = result.targetNode();
         if (!scrollbar) {
             FrameView* view = m_frame->view();
@@ -2400,10 +2317,13 @@
 
     if (scrollbar) {
         bool eventSwallowed = scrollbar->gestureEvent(gestureEvent);
-        if (gestureEvent.type() == PlatformEvent::GestureScrollBegin && eventSwallowed)
+        if (gestureEvent.type() == PlatformEvent::GestureTapDown && eventSwallowed) {
             m_scrollbarHandlingScrollGesture = scrollbar;
-        else if (gestureEvent.type() == PlatformEvent::GestureScrollEnd || !eventSwallowed)
+        } else if (gestureEvent.type() == PlatformEvent::GestureScrollEnd
+            || gestureEvent.type() == PlatformEvent::GestureFlingStart
+            || !eventSwallowed) {
             m_scrollbarHandlingScrollGesture = 0;
+        }
 
         if (eventSwallowed)
             return true;
@@ -2452,6 +2372,7 @@
     case PlatformEvent::GesturePinchUpdate:
     case PlatformEvent::GestureTapDownCancel:
     case PlatformEvent::GestureTapUnconfirmed:
+    case PlatformEvent::GestureFlingStart:
         break;
     default:
         ASSERT_NOT_REACHED();
@@ -2464,31 +2385,33 @@
 {
     // FIXME: Refactor this code to not hit test multiple times. We use the adjusted position to ensure that the correct node is targeted by the later redundant hit tests.
 
+    unsigned modifierFlags = 0;
+    if (gestureEvent.altKey())
+        modifierFlags |= PlatformEvent::AltKey;
+    if (gestureEvent.ctrlKey())
+        modifierFlags |= PlatformEvent::CtrlKey;
+    if (gestureEvent.metaKey())
+        modifierFlags |= PlatformEvent::MetaKey;
+    if (gestureEvent.shiftKey())
+        modifierFlags |= PlatformEvent::ShiftKey;
+    PlatformEvent::Modifiers modifiers = static_cast<PlatformEvent::Modifiers>(modifierFlags);
+
     PlatformMouseEvent fakeMouseMove(adjustedPoint, gestureEvent.globalPosition(),
         NoButton, PlatformEvent::MouseMoved, /* clickCount */ 0,
-        gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
+        modifiers, PlatformMouseEvent::FromTouch, gestureEvent.timestamp());
     handleMouseMoveEvent(fakeMouseMove);
 
     bool defaultPrevented = false;
     PlatformMouseEvent fakeMouseDown(adjustedPoint, gestureEvent.globalPosition(),
         LeftButton, PlatformEvent::MousePressed, gestureEvent.tapCount(),
-        gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
+        modifiers, PlatformMouseEvent::FromTouch,  gestureEvent.timestamp());
     defaultPrevented |= handleMousePressEvent(fakeMouseDown);
 
     PlatformMouseEvent fakeMouseUp(adjustedPoint, gestureEvent.globalPosition(),
         LeftButton, PlatformEvent::MouseReleased, gestureEvent.tapCount(),
-        gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
-
-    // If the Tap is received very shortly after ShowPress, we want to delay clearing
-    // of the active state so that it's visible to the user for at least one frame.
-    double activeInterval = WTF::currentTime() - m_lastShowPressTimestamp;
-    m_shouldKeepActiveForMinInterval = m_lastShowPressTimestamp && activeInterval < minimumActiveInterval;
+        modifiers, PlatformMouseEvent::FromTouch,  gestureEvent.timestamp());
     defaultPrevented |= handleMouseReleaseEvent(fakeMouseUp);
 
-    if (m_shouldKeepActiveForMinInterval)
-        m_activeIntervalTimer.startOneShot(minimumActiveInterval - activeInterval);
-    m_shouldKeepActiveForMinInterval = false;
-
     return defaultPrevented;
 }
 
@@ -2678,8 +2601,8 @@
 
     // First try to scroll the closest scrollable RenderBox ancestor of |node|.
     ScrollGranularity granularity = ScrollByPixel;
-    bool horizontalScroll = scrollNode(delta.width(), granularity, ScrollLeft, ScrollRight, node, &stopNode);
-    bool verticalScroll = scrollNode(delta.height(), granularity, ScrollUp, ScrollDown, node, &stopNode);
+    bool horizontalScroll = scroll(ScrollLeft, granularity, node, &stopNode, delta.width());
+    bool verticalScroll = scroll(ScrollUp, granularity, node, &stopNode, delta.height());
 
     if (scrollShouldNotPropagate)
         m_previousGestureScrolledNode = stopNode;
@@ -3074,9 +2997,10 @@
 
     if (m_frame
         && m_frame->document()
-        && m_lastDeferredTapElement
-        && m_lastDeferredTapElement.get() == m_frame->document()->activeElement()) {
-        HitTestRequest request(HitTestRequest::Release | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+        && m_lastDeferredTapElement) {
+        // FIXME: Enable condition when http://crbug.com/226842 lands
+        // m_lastDeferredTapElement.get() == m_frame->document()->activeElement()
+        HitTestRequest request(HitTestRequest::TouchEvent | HitTestRequest::Release);
         m_frame->document()->updateHoverActiveState(request, m_lastDeferredTapElement.get());
     }
     m_lastDeferredTapElement = 0;
@@ -3157,9 +3081,6 @@
 
     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
 
-    if (FrameView* view = m_frame->view())
-        view->resetDeferredRepaintDelay();
-
     // In IE, access keys are special, they are handled after default keydown processing, but cannot be canceled - this is hard to match.
     // On Mac OS X, we process them before dispatching keydown, as the default keydown handler implements Emacs key bindings, which may conflict
     // with access keys. Then we dispatch keydown, but suppress its default handling.
@@ -3214,23 +3135,23 @@
     return keydownResult || keypress->defaultPrevented() || keypress->defaultHandled();
 }
 
-static FocusDirection focusDirectionForKey(const AtomicString& keyIdentifier)
+static FocusType focusDirectionForKey(const AtomicString& keyIdentifier)
 {
     DEFINE_STATIC_LOCAL(AtomicString, Down, ("Down", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, Up, ("Up", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, Left, ("Left", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, Right, ("Right", AtomicString::ConstructFromLiteral));
 
-    FocusDirection retVal = FocusDirectionNone;
+    FocusType retVal = FocusTypeNone;
 
     if (keyIdentifier == Down)
-        retVal = FocusDirectionDown;
+        retVal = FocusTypeDown;
     else if (keyIdentifier == Up)
-        retVal = FocusDirectionUp;
+        retVal = FocusTypeUp;
     else if (keyIdentifier == Left)
-        retVal = FocusDirectionLeft;
+        retVal = FocusTypeLeft;
     else if (keyIdentifier == Right)
-        retVal = FocusDirectionRight;
+        retVal = FocusTypeRight;
 
     return retVal;
 }
@@ -3248,9 +3169,9 @@
         else if (event->keyIdentifier() == "U+001B")
             defaultEscapeEventHandler(event);
         else {
-            FocusDirection direction = focusDirectionForKey(event->keyIdentifier());
-            if (direction != FocusDirectionNone)
-                defaultArrowEventHandler(direction, event);
+            FocusType type = focusDirectionForKey(AtomicString(event->keyIdentifier()));
+            if (type != FocusTypeNone)
+                defaultArrowEventHandler(type, event);
         }
     }
     if (event->type() == EventTypeNames::keypress) {
@@ -3457,9 +3378,6 @@
     if (!target)
         return false;
 
-    if (FrameView* view = m_frame->view())
-        view->resetDeferredRepaintDelay();
-
     RefPtr<TextEvent> event = TextEvent::create(m_frame->domWindow(), text, inputType);
     event->setUnderlyingEvent(underlyingEvent);
 
@@ -3480,8 +3398,8 @@
     if (event->ctrlKey() || event->metaKey() || event->altKey() || event->altGraphKey())
         return;
 
-    ScrollLogicalDirection direction = event->shiftKey() ? ScrollBlockDirectionBackward : ScrollBlockDirectionForward;
-    if (logicalScrollOverflow(direction, ScrollByPage)) {
+    ScrollDirection direction = event->shiftKey() ? ScrollBlockDirectionBackward : ScrollBlockDirectionForward;
+    if (scroll(direction, ScrollByPage)) {
         event->setDefaultHandled();
         return;
     }
@@ -3490,7 +3408,7 @@
     if (!view)
         return;
 
-    if (view->logicalScroll(direction, ScrollByPage))
+    if (view->scroll(direction, ScrollByPage))
         event->setDefaultHandled();
 }
 
@@ -3512,7 +3430,7 @@
         event->setDefaultHandled();
 }
 
-void EventHandler::defaultArrowEventHandler(FocusDirection focusDirection, KeyboardEvent* event)
+void EventHandler::defaultArrowEventHandler(FocusType focusType, KeyboardEvent* event)
 {
     ASSERT(event->type() == EventTypeNames::keydown);
 
@@ -3531,7 +3449,7 @@
     if (m_frame->document()->inDesignMode())
         return;
 
-    if (page->focusController().advanceFocus(focusDirection))
+    if (page->focusController().advanceFocus(focusType))
         event->setDefaultHandled();
 }
 
@@ -3549,13 +3467,13 @@
     if (!page->tabKeyCyclesThroughElements())
         return;
 
-    FocusDirection focusDirection = event->shiftKey() ? FocusDirectionBackward : FocusDirectionForward;
+    FocusType focusType = event->shiftKey() ? FocusTypeBackward : FocusTypeForward;
 
     // Tabs can be used in design mode editing.
     if (m_frame->document()->inDesignMode())
         return;
 
-    if (page->focusController().advanceFocus(focusDirection))
+    if (page->focusController().advanceFocus(focusType))
         event->setDefaultHandled();
 }
 
@@ -3575,18 +3493,10 @@
     }
 }
 
-void EventHandler::sendScrollEvent()
-{
-    setFrameWasScrolledByUser();
-    if (m_frame->view() && m_frame->document())
-        m_frame->document()->enqueueScrollEventForNode(m_frame->document());
-}
-
 void EventHandler::setFrameWasScrolledByUser()
 {
-    FrameView* v = m_frame->view();
-    if (v)
-        v->setWasScrolledByUser(true);
+    if (FrameView* view = m_frame->view())
+        view->setWasScrolledByUser(true);
 }
 
 bool EventHandler::passMousePressEventToScrollbar(MouseEventWithHitTestResults& mev, Scrollbar* scrollbar)
@@ -3783,16 +3693,21 @@
 
         int adjustedPageX = lroundf(pagePoint.x() / scaleFactor);
         int adjustedPageY = lroundf(pagePoint.y() / scaleFactor);
+        int adjustedRadiusX = lroundf(point.radiusX() / scaleFactor);
+        int adjustedRadiusY = lroundf(point.radiusY() / scaleFactor);
 
         RefPtr<Touch> touch = Touch::create(targetFrame, touchTarget.get(), point.id(),
                                             point.screenPos().x(), point.screenPos().y(),
                                             adjustedPageX, adjustedPageY,
-                                            point.radiusX(), point.radiusY(), point.rotationAngle(), point.force());
+                                            adjustedRadiusX, adjustedRadiusY,
+                                            point.rotationAngle(), point.force());
 
         // Ensure this target's touch list exists, even if it ends up empty, so it can always be passed to TouchEvent::Create below.
         TargetTouchesMap::iterator targetTouchesIterator = touchesByTarget.find(touchTarget.get());
-        if (targetTouchesIterator == touchesByTarget.end())
-            targetTouchesIterator = touchesByTarget.set(touchTarget.get(), TouchList::create()).iterator;
+        if (targetTouchesIterator == touchesByTarget.end()) {
+            touchesByTarget.set(touchTarget.get(), TouchList::create());
+            targetTouchesIterator = touchesByTarget.find(touchTarget.get());
+        }
 
         // touches and targetTouches should only contain information about touches still on the screen, so if this point is
         // released or cancelled it will only appear in the changedTouches list.
@@ -3851,7 +3766,7 @@
 
 bool EventHandler::dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent& event)
 {
-    if (!m_frame || !m_frame->settings() || !m_frame->settings()->isTouchEventEmulationEnabled())
+    if (!m_frame || !m_frame->settings() || !m_frame->settings()->touchEventEmulationEnabled())
         return false;
 
     PlatformEvent::Type eventType = event.type();
@@ -3945,7 +3860,7 @@
 
 bool EventHandler::handleWheelEventAsEmulatedGesture(const PlatformWheelEvent& event)
 {
-    if (!m_frame || !m_frame->settings() || !m_frame->settings()->isTouchEventEmulationEnabled())
+    if (!m_frame || !m_frame->settings() || !m_frame->settings()->touchEventEmulationEnabled())
         return false;
 
     // Only convert vertical wheel w/ shift into pinch for touch-enabled device convenience.
@@ -3968,6 +3883,19 @@
     return true;
 }
 
+TouchAction EventHandler::intersectTouchAction(TouchAction action1, TouchAction action2)
+{
+    if (action1 == TouchActionNone || action2 == TouchActionNone)
+        return TouchActionNone;
+    if (action1 == TouchActionAuto)
+        return action2;
+    if (action2 == TouchActionAuto)
+        return action1;
+    if (!(action1 & action2))
+        return TouchActionNone;
+    return action1 & action2;
+}
+
 TouchAction EventHandler::computeEffectiveTouchAction(const Node& node)
 {
     // Optimization to minimize risk of this new feature (behavior should be identical
@@ -3979,13 +3907,16 @@
     // the target node up to the nearest scrollable ancestor and exclude any
     // prohibited actions. For now this is trivial, but when we add more types
     // of actions it'll get a little more complex.
+    TouchAction effectiveTouchAction = TouchActionAuto;
     for (const Node* curNode = &node; curNode; curNode = NodeRenderingTraversal::parent(curNode)) {
         // The spec says only block and SVG elements get touch-action.
         // FIXME(rbyers): Add correct support for SVG, crbug.com/247396.
         if (RenderObject* renderer = curNode->renderer()) {
             if (renderer->isRenderBlockFlow()) {
-                if (renderer->style()->touchAction() == TouchActionNone)
-                    return TouchActionNone;
+                TouchAction action = renderer->style()->touchAction();
+                effectiveTouchAction = intersectTouchAction(action, effectiveTouchAction);
+                if (effectiveTouchAction == TouchActionNone)
+                    break;
             }
 
             // If we've reached an ancestor that supports a touch action, search no further.
@@ -3993,7 +3924,7 @@
                 break;
         }
     }
-    return TouchActionAuto;
+    return effectiveTouchAction;
 }
 
 void EventHandler::setLastKnownMousePosition(const PlatformMouseEvent& event)
@@ -4060,7 +3991,7 @@
 
 PassRefPtr<Clipboard> EventHandler::createDraggingClipboard() const
 {
-    return Clipboard::create(Clipboard::DragAndDrop, ClipboardWritable, ChromiumDataObject::create());
+    return Clipboard::create(Clipboard::DragAndDrop, ClipboardWritable, DataObject::create());
 }
 
 void EventHandler::focusDocumentView()
diff --git a/Source/core/page/EventHandler.h b/Source/core/page/EventHandler.h
index 734f5ed..23316e2 100644
--- a/Source/core/page/EventHandler.h
+++ b/Source/core/page/EventHandler.h
@@ -29,7 +29,7 @@
 #include "core/editing/TextGranularity.h"
 #include "core/events/TextEventInputType.h"
 #include "core/page/DragActions.h"
-#include "core/page/FocusDirection.h"
+#include "core/page/FocusType.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "platform/Cursor.h"
@@ -129,9 +129,9 @@
     IntPoint lastKnownMousePosition() const;
     Cursor currentMouseCursor() const { return m_currentMouseCursor; }
 
-    bool scrollOverflow(ScrollDirection, ScrollGranularity, Node* startingNode = 0);
-    bool scrollRecursively(ScrollDirection, ScrollGranularity, Node* startingNode = 0);
-    bool logicalScrollRecursively(ScrollLogicalDirection, ScrollGranularity, Node* startingNode = 0);
+    // Attempts to scroll the DOM tree. If that fails, scrolls the view.
+    // If the view can't be scrolled either, recursively bubble to the parent frame.
+    bool bubblingScroll(ScrollDirection, ScrollGranularity, Node* startingNode = 0);
 
     bool handleMouseMoveEvent(const PlatformMouseEvent&);
     void handleMouseLeaveEvent(const PlatformMouseEvent&);
@@ -171,8 +171,6 @@
 
     void capsLockStateMayHaveChanged(); // Only called by FrameSelection
 
-    void sendScrollEvent(); // Only called in FrameView
-
     bool handleTouchEvent(const PlatformTouchEvent&);
 
     bool useHandCursor(Node*, bool isOverLink, bool shiftKey);
@@ -218,8 +216,6 @@
     void cursorUpdateTimerFired(Timer<EventHandler>*);
     void activeIntervalTimerFired(Timer<EventHandler>*);
 
-    bool logicalScrollOverflow(ScrollLogicalDirection, ScrollGranularity, Node* startingNode = 0);
-
     bool shouldTurnVerticalTicksIntoHorizontal(const HitTestResult&, const PlatformWheelEvent&) const;
     bool mouseDownMayStartSelect() const { return m_mouseDownMayStartSelect; }
 
@@ -232,7 +228,22 @@
 
     ScrollableArea* associatedScrollableArea(const RenderLayer*) const;
 
+    // Scrolls the elements of the DOM tree. Returns true if a node was scrolled.
+    // False if we reached the root and couldn't scroll anything.
+    // direction - The direction to scroll in. If this is a logicl direction, it will be
+    //             converted to the physical direction based on a node's writing mode.
+    // granularity - The units that the  scroll delta parameter is in.
+    // startNode - The node to start bubbling the scroll from. If a node can't scroll,
+    //             the scroll bubbles up to the containing block.
+    // stopNode - On input, if provided and non-null, the node at which we should stop bubbling on input.
+    //            On output, if provided and a node was scrolled stopNode will point to that node.
+    // delta - The delta to scroll by, in the units of the granularity parameter. (e.g. pixels, lines, pages, etc.)
+    // absolutePoint - For wheel scrolls - the location, in absolute coordinates, where the event occured.
+    bool scroll(ScrollDirection, ScrollGranularity, Node* startNode = 0, Node** stopNode = 0, float delta = 1.0f, IntPoint absolutePoint = IntPoint());
+
     bool dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent&);
+
+    TouchAction intersectTouchAction(const TouchAction, const TouchAction);
     TouchAction computeEffectiveTouchAction(const Node&);
 
     bool handleMouseEventAsEmulatedGesture(const PlatformMouseEvent&);
@@ -275,7 +286,7 @@
     void defaultBackspaceEventHandler(KeyboardEvent*);
     void defaultTabEventHandler(KeyboardEvent*);
     void defaultEscapeEventHandler(KeyboardEvent*);
-    void defaultArrowEventHandler(FocusDirection, KeyboardEvent*);
+    void defaultArrowEventHandler(FocusType, KeyboardEvent*);
 
     void updateSelectionForMouseDrag(const HitTestResult&);
 
@@ -314,8 +325,6 @@
 
     LayoutPoint m_dragStartPos;
 
-    bool m_panScrollButtonPressed;
-
     Timer<EventHandler> m_hoverTimer;
     Timer<EventHandler> m_cursorUpdateTimer;
 
@@ -385,7 +394,6 @@
 
     Timer<EventHandler> m_activeIntervalTimer;
     double m_lastShowPressTimestamp;
-    bool m_shouldKeepActiveForMinInterval;
     RefPtr<Element> m_lastDeferredTapElement;
 };
 
diff --git a/Source/core/page/EventSource.cpp b/Source/core/page/EventSource.cpp
index 6a9600c..6fae815 100644
--- a/Source/core/page/EventSource.cpp
+++ b/Source/core/page/EventSource.cpp
@@ -42,10 +42,10 @@
 #include "core/dom/ExecutionContext.h"
 #include "core/events/Event.h"
 #include "core/events/MessageEvent.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/frame/DOMWindow.h"
 #include "core/frame/Frame.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/loader/ThreadableLoader.h"
 #include "platform/network/ResourceError.h"
 #include "platform/network/ResourceRequest.h"
@@ -135,7 +135,6 @@
     SecurityOrigin* origin = executionContext()->securityOrigin();
 
     ThreadableLoaderOptions options;
-    options.sendLoadCallbacks = SendCallbacks;
     options.sniffContent = DoNotSniffContent;
     options.allowCredentials = (origin->canRequest(m_url) || m_withCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials;
     options.credentialsRequested = m_withCredentials ? ClientRequestedCredentials : ClientDidNotRequestCredentials;
@@ -282,8 +281,8 @@
         // Discard everything that has not been dispatched by now.
         m_receiveBuf.clear();
         m_data.clear();
-        m_eventName = "";
-        m_currentlyParsedEventId = String();
+        m_eventName = emptyAtom;
+        m_currentlyParsedEventId = nullAtom;
     }
     networkRequestEnded();
 }
@@ -377,13 +376,13 @@
         if (!m_data.isEmpty()) {
             m_data.removeLast();
             if (!m_currentlyParsedEventId.isNull()) {
-                m_lastEventId.swap(m_currentlyParsedEventId);
-                m_currentlyParsedEventId = String();
+                m_lastEventId = m_currentlyParsedEventId;
+                m_currentlyParsedEventId = nullAtom;
             }
             dispatchEvent(createMessageEvent());
         }
         if (!m_eventName.isEmpty())
-            m_eventName = "";
+            m_eventName = emptyAtom;
     } else if (fieldLength) {
         bool noValue = fieldLength < 0;
 
@@ -402,11 +401,11 @@
             if (valueLength)
                 m_data.append(&m_receiveBuf[bufPos], valueLength);
             m_data.append('\n');
-        } else if (field == "event")
-            m_eventName = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
-        else if (field == "id")
-            m_currentlyParsedEventId = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
-        else if (field == "retry") {
+        } else if (field == "event") {
+            m_eventName = valueLength ? AtomicString(&m_receiveBuf[bufPos], valueLength) : "";
+        } else if (field == "id") {
+            m_currentlyParsedEventId = valueLength ? AtomicString(&m_receiveBuf[bufPos], valueLength) : "";
+        } else if (field == "retry") {
             if (!valueLength)
                 m_reconnectDelay = defaultReconnectDelay;
             else {
@@ -428,7 +427,7 @@
 PassRefPtr<MessageEvent> EventSource::createMessageEvent()
 {
     RefPtr<MessageEvent> event = MessageEvent::create();
-    event->initMessageEvent(m_eventName.isEmpty() ? EventTypeNames::message : AtomicString(m_eventName), false, false, SerializedScriptValue::create(String(m_data)), m_eventStreamOrigin, m_lastEventId, 0, nullptr);
+    event->initMessageEvent(m_eventName.isEmpty() ? EventTypeNames::message : m_eventName, false, false, SerializedScriptValue::create(String(m_data)), m_eventStreamOrigin, m_lastEventId, 0, nullptr);
     m_data.clear();
     return event.release();
 }
diff --git a/Source/core/page/EventSource.h b/Source/core/page/EventSource.h
index 66ea83a..bf54cc4 100644
--- a/Source/core/page/EventSource.h
+++ b/Source/core/page/EventSource.h
@@ -50,7 +50,7 @@
 class TextResourceDecoder;
 class ThreadableLoader;
 
-class EventSource : public RefCounted<EventSource>, public ScriptWrappable, public EventTargetWithInlineData, private ThreadableLoaderClient, public ActiveDOMObject {
+class EventSource FINAL : public RefCounted<EventSource>, public ScriptWrappable, public EventTargetWithInlineData, private ThreadableLoaderClient, public ActiveDOMObject {
     WTF_MAKE_FAST_ALLOCATED;
     REFCOUNTED_EVENT_TARGET(EventSource);
 public:
@@ -89,12 +89,12 @@
 private:
     EventSource(ExecutionContext*, const KURL&, const Dictionary&);
 
-    virtual void didReceiveResponse(unsigned long, const ResourceResponse&);
-    virtual void didReceiveData(const char*, int);
-    virtual void didFinishLoading(unsigned long, double);
-    virtual void didFail(const ResourceError&);
-    virtual void didFailAccessControlCheck(const ResourceError&);
-    virtual void didFailRedirectCheck();
+    virtual void didReceiveResponse(unsigned long, const ResourceResponse&) OVERRIDE;
+    virtual void didReceiveData(const char*, int) OVERRIDE;
+    virtual void didFinishLoading(unsigned long, double) OVERRIDE;
+    virtual void didFail(const ResourceError&) OVERRIDE;
+    virtual void didFailAccessControlCheck(const ResourceError&) OVERRIDE;
+    virtual void didFailRedirectCheck() OVERRIDE;
 
     void scheduleInitialConnect();
     void connect();
@@ -117,10 +117,10 @@
     bool m_discardTrailingNewline;
     bool m_requestInFlight;
 
-    String m_eventName;
+    AtomicString m_eventName;
     Vector<UChar> m_data;
-    String m_currentlyParsedEventId;
-    String m_lastEventId;
+    AtomicString m_currentlyParsedEventId;
+    AtomicString m_lastEventId;
     unsigned long long m_reconnectDelay;
     String m_eventStreamOrigin;
 };
diff --git a/Source/core/page/EventSource.idl b/Source/core/page/EventSource.idl
index 3562791..5e3efa8 100644
--- a/Source/core/page/EventSource.idl
+++ b/Source/core/page/EventSource.idl
@@ -37,7 +37,7 @@
     RaisesException=Constructor,
 ] interface EventSource : EventTarget {
 
-    readonly attribute DOMString URL; // Lowercased .url is the one in the spec, but leaving .URL for compatibility reasons.
+    [MeasureAs=EventSourceURL] readonly attribute DOMString URL; // Lowercased .url is the one in the spec, but leaving .URL for compatibility reasons.
     readonly attribute DOMString url;
     readonly attribute boolean withCredentials;
 
diff --git a/Source/core/page/FocusController.cpp b/Source/core/page/FocusController.cpp
index be1d745..93a2193 100644
--- a/Source/core/page/FocusController.cpp
+++ b/Source/core/page/FocusController.cpp
@@ -47,21 +47,26 @@
 #include "core/frame/FrameView.h"
 #include "core/html/HTMLAreaElement.h"
 #include "core/html/HTMLImageElement.h"
-#include "core/html/HTMLTextAreaElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FrameTree.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/page/SpatialNavigation.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/RenderLayer.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
+static inline bool isShadowInsertionPointFocusScopeOwner(Node& node)
+{
+    return isActiveShadowInsertionPoint(node) && toHTMLShadowElement(node).olderShadowRoot();
+}
+
 // FIXME: Some of Node* return values and Node* arguments should be Element*.
 
 FocusNavigationScope::FocusNavigationScope(TreeScope* treeScope)
@@ -72,7 +77,7 @@
 
 Node* FocusNavigationScope::rootNode() const
 {
-    return m_rootTreeScope->rootNode();
+    return &m_rootTreeScope->rootNode();
 }
 
 Element* FocusNavigationScope::owner() const
@@ -103,7 +108,7 @@
     ASSERT(node);
     if (isShadowHost(node))
         return FocusNavigationScope::ownedByShadowHost(node);
-    ASSERT(isActiveShadowInsertionPoint(*node));
+    ASSERT(isShadowInsertionPointFocusScopeOwner(*node));
     return FocusNavigationScope::ownedByShadowInsertionPoint(toHTMLShadowElement(node));
 }
 
@@ -121,7 +126,7 @@
 
 FocusNavigationScope FocusNavigationScope::ownedByShadowInsertionPoint(HTMLShadowElement* shadowInsertionPoint)
 {
-    ASSERT(shadowInsertionPoint->isActive());
+    ASSERT(isShadowInsertionPointFocusScopeOwner(*shadowInsertionPoint));
     return FocusNavigationScope(shadowInsertionPoint->olderShadowRoot());
 }
 
@@ -151,7 +156,7 @@
         window->dispatchEvent(Event::create(focused ? EventTypeNames::focus : EventTypeNames::blur));
     if (focused && document->focusedElement()) {
         RefPtr<Element> focusedElement(document->focusedElement());
-        focusedElement->dispatchFocusEvent(0, FocusDirectionPage);
+        focusedElement->dispatchFocusEvent(0, FocusTypePage);
         if (focusedElement == document->focusedElement()) {
             document->focusedElement()->dispatchFocusInEvent(EventTypeNames::focusin, 0);
             if (focusedElement == document->focusedElement())
@@ -197,7 +202,7 @@
 static inline bool isNonFocusableFocusScopeOwner(Node* node)
 {
     ASSERT(node);
-    return isNonKeyboardFocusableShadowHost(node) || isActiveShadowInsertionPoint(*node);
+    return isNonKeyboardFocusableShadowHost(node) || isShadowInsertionPointFocusScopeOwner(*node);
 }
 
 static inline int adjustedTabIndex(Node* node)
@@ -279,7 +284,7 @@
     }
 }
 
-Node* FocusController::findFocusableNodeDecendingDownIntoFrameDocument(FocusDirection direction, Node* node)
+Node* FocusController::findFocusableNodeDecendingDownIntoFrameDocument(FocusType type, Node* node)
 {
     // The node we found might be a HTMLFrameOwnerElement, so descend down the tree until we find either:
     // 1) a focusable node, or
@@ -288,7 +293,7 @@
         HTMLFrameOwnerElement* owner = toHTMLFrameOwnerElement(node);
         if (!owner->contentFrame())
             break;
-        Node* foundNode = findFocusableNode(direction, FocusNavigationScope::ownedByIFrame(owner), 0);
+        Node* foundNode = findFocusableNode(type, FocusNavigationScope::ownedByIFrame(owner), 0);
         if (!foundNode)
             break;
         ASSERT(node != foundNode);
@@ -297,9 +302,9 @@
     return node;
 }
 
-bool FocusController::setInitialFocus(FocusDirection direction)
+bool FocusController::setInitialFocus(FocusType type)
 {
-    bool didAdvanceFocus = advanceFocus(direction, true);
+    bool didAdvanceFocus = advanceFocus(type, true);
 
     // If focus is being set initially, accessibility needs to be informed that system focus has moved
     // into the web area again, even if focus did not change within WebCore. PostNotification is called instead
@@ -310,17 +315,17 @@
     return didAdvanceFocus;
 }
 
-bool FocusController::advanceFocus(FocusDirection direction, bool initialFocus)
+bool FocusController::advanceFocus(FocusType type, bool initialFocus)
 {
-    switch (direction) {
-    case FocusDirectionForward:
-    case FocusDirectionBackward:
-        return advanceFocusInDocumentOrder(direction, initialFocus);
-    case FocusDirectionLeft:
-    case FocusDirectionRight:
-    case FocusDirectionUp:
-    case FocusDirectionDown:
-        return advanceFocusDirectionally(direction);
+    switch (type) {
+    case FocusTypeForward:
+    case FocusTypeBackward:
+        return advanceFocusInDocumentOrder(type, initialFocus);
+    case FocusTypeLeft:
+    case FocusTypeRight:
+    case FocusTypeUp:
+    case FocusTypeDown:
+        return advanceFocusDirectionally(type);
     default:
         ASSERT_NOT_REACHED();
     }
@@ -328,7 +333,7 @@
     return false;
 }
 
-bool FocusController::advanceFocusInDocumentOrder(FocusDirection direction, bool initialFocus)
+bool FocusController::advanceFocusInDocumentOrder(FocusType type, bool initialFocus)
 {
     Frame* frame = focusedOrMainFrame();
     ASSERT(frame);
@@ -343,20 +348,20 @@
 
     document->updateLayoutIgnorePendingStylesheets();
 
-    RefPtr<Node> node = findFocusableNodeAcrossFocusScope(direction, FocusNavigationScope::focusNavigationScopeOf(currentNode ? currentNode : document), currentNode);
+    RefPtr<Node> node = findFocusableNodeAcrossFocusScope(type, FocusNavigationScope::focusNavigationScopeOf(currentNode ? currentNode : document), currentNode);
 
     if (!node) {
         // We didn't find a node to focus, so we should try to pass focus to Chrome.
-        if (!initialFocus && m_page->chrome().canTakeFocus(direction)) {
+        if (!initialFocus && m_page->chrome().canTakeFocus(type)) {
             document->setFocusedElement(0);
             setFocusedFrame(0);
-            m_page->chrome().takeFocus(direction);
+            m_page->chrome().takeFocus(type);
             return true;
         }
 
         // Chrome doesn't want focus, so we should wrap focus.
-        node = findFocusableNodeRecursively(direction, FocusNavigationScope::focusNavigationScopeOf(m_page->mainFrame()->document()), 0);
-        node = findFocusableNodeDecendingDownIntoFrameDocument(direction, node.get());
+        node = findFocusableNodeRecursively(type, FocusNavigationScope::focusNavigationScopeOf(m_page->mainFrame()->document()), 0);
+        node = findFocusableNodeDecendingDownIntoFrameDocument(type, node.get());
 
         if (!node)
             return false;
@@ -403,19 +408,19 @@
         frame->selection().setSelection(newSelection);
     }
 
-    element->focus(false, direction);
+    element->focus(false, type);
     return true;
 }
 
-Node* FocusController::findFocusableNodeAcrossFocusScope(FocusDirection direction, FocusNavigationScope scope, Node* currentNode)
+Node* FocusController::findFocusableNodeAcrossFocusScope(FocusType type, FocusNavigationScope scope, Node* currentNode)
 {
     ASSERT(!currentNode || !isNonFocusableShadowHost(currentNode));
     Node* found;
-    if (currentNode && direction == FocusDirectionForward && isKeyboardFocusableShadowHost(currentNode)) {
-        Node* foundInInnerFocusScope = findFocusableNodeRecursively(direction, FocusNavigationScope::ownedByShadowHost(currentNode), 0);
-        found = foundInInnerFocusScope ? foundInInnerFocusScope : findFocusableNodeRecursively(direction, scope, currentNode);
+    if (currentNode && type == FocusTypeForward && isKeyboardFocusableShadowHost(currentNode)) {
+        Node* foundInInnerFocusScope = findFocusableNodeRecursively(type, FocusNavigationScope::ownedByShadowHost(currentNode), 0);
+        found = foundInInnerFocusScope ? foundInInnerFocusScope : findFocusableNodeRecursively(type, scope, currentNode);
     } else {
-        found = findFocusableNodeRecursively(direction, scope, currentNode);
+        found = findFocusableNodeRecursively(type, scope, currentNode);
     }
 
     // If there's no focusable node to advance to, move up the focus scopes until we find one.
@@ -424,51 +429,49 @@
         if (!owner)
             break;
         scope = FocusNavigationScope::focusNavigationScopeOf(owner);
-        if (direction == FocusDirectionBackward && isKeyboardFocusableShadowHost(owner)) {
+        if (type == FocusTypeBackward && isKeyboardFocusableShadowHost(owner)) {
             found = owner;
             break;
         }
-        found = findFocusableNodeRecursively(direction, scope, owner);
+        found = findFocusableNodeRecursively(type, scope, owner);
     }
-    found = findFocusableNodeDecendingDownIntoFrameDocument(direction, found);
+    found = findFocusableNodeDecendingDownIntoFrameDocument(type, found);
     return found;
 }
 
-Node* FocusController::findFocusableNodeRecursively(FocusDirection direction, FocusNavigationScope scope, Node* start)
+Node* FocusController::findFocusableNodeRecursively(FocusType type, FocusNavigationScope scope, Node* start)
 {
     // Starting node is exclusive.
-    Node* found = findFocusableNode(direction, scope, start);
+    Node* found = findFocusableNode(type, scope, start);
     if (!found)
         return 0;
-    if (direction == FocusDirectionForward) {
+    if (type == FocusTypeForward) {
         if (!isNonFocusableFocusScopeOwner(found))
             return found;
-        Node* foundInInnerFocusScope = findFocusableNodeRecursively(direction, FocusNavigationScope::ownedByNonFocusableFocusScopeOwner(found), 0);
-        return foundInInnerFocusScope ? foundInInnerFocusScope : findFocusableNodeRecursively(direction, scope, found);
+        Node* foundInInnerFocusScope = findFocusableNodeRecursively(type, FocusNavigationScope::ownedByNonFocusableFocusScopeOwner(found), 0);
+        return foundInInnerFocusScope ? foundInInnerFocusScope : findFocusableNodeRecursively(type, scope, found);
     }
-    ASSERT(direction == FocusDirectionBackward);
+    ASSERT(type == FocusTypeBackward);
     if (isKeyboardFocusableShadowHost(found)) {
-        Node* foundInInnerFocusScope = findFocusableNodeRecursively(direction, FocusNavigationScope::ownedByShadowHost(found), 0);
+        Node* foundInInnerFocusScope = findFocusableNodeRecursively(type, FocusNavigationScope::ownedByShadowHost(found), 0);
         return foundInInnerFocusScope ? foundInInnerFocusScope : found;
     }
     if (isNonFocusableFocusScopeOwner(found)) {
-        Node* foundInInnerFocusScope = findFocusableNodeRecursively(direction, FocusNavigationScope::ownedByNonFocusableFocusScopeOwner(found), 0);
-        return foundInInnerFocusScope ? foundInInnerFocusScope :findFocusableNodeRecursively(direction, scope, found);
+        Node* foundInInnerFocusScope = findFocusableNodeRecursively(type, FocusNavigationScope::ownedByNonFocusableFocusScopeOwner(found), 0);
+        return foundInInnerFocusScope ? foundInInnerFocusScope :findFocusableNodeRecursively(type, scope, found);
     }
     return found;
 }
 
-Node* FocusController::findFocusableNode(FocusDirection direction, FocusNavigationScope scope, Node* node)
+Node* FocusController::findFocusableNode(FocusType type, FocusNavigationScope scope, Node* node)
 {
-    return (direction == FocusDirectionForward)
-        ? nextFocusableNode(scope, node)
-        : previousFocusableNode(scope, node);
+    return type == FocusTypeForward ? nextFocusableNode(scope, node) : previousFocusableNode(scope, node);
 }
 
-Node* FocusController::findNodeWithExactTabIndex(Node* start, int tabIndex, FocusDirection direction)
+Node* FocusController::findNodeWithExactTabIndex(Node* start, int tabIndex, FocusType type)
 {
     // Search is inclusive of start
-    for (Node* node = start; node; node = direction == FocusDirectionForward ? NodeTraversal::next(*node) : NodeTraversal::previous(*node)) {
+    for (Node* node = start; node; node = type == FocusTypeForward ? NodeTraversal::next(*node) : NodeTraversal::previous(*node)) {
         if (shouldVisit(node) && adjustedTabIndex(node) == tabIndex)
             return node;
     }
@@ -518,7 +521,7 @@
         }
 
         // First try to find a node with the same tabindex as start that comes after start in the scope.
-        if (Node* winner = findNodeWithExactTabIndex(NodeTraversal::next(*start), tabIndex, FocusDirectionForward))
+        if (Node* winner = findNodeWithExactTabIndex(NodeTraversal::next(*start), tabIndex, FocusTypeForward))
             return winner;
 
         if (!tabIndex)
@@ -534,7 +537,7 @@
 
     // There are no nodes with a tabindex greater than start's tabindex,
     // so find the first node with a tabindex of 0.
-    return findNodeWithExactTabIndex(scope.rootNode(), 0, FocusDirectionForward);
+    return findNodeWithExactTabIndex(scope.rootNode(), 0, FocusTypeForward);
 }
 
 Node* FocusController::previousFocusableNode(FocusNavigationScope scope, Node* start)
@@ -564,7 +567,7 @@
         }
     }
 
-    if (Node* winner = findNodeWithExactTabIndex(startingNode, startingTabIndex, FocusDirectionBackward))
+    if (Node* winner = findNodeWithExactTabIndex(startingNode, startingTabIndex, FocusTypeBackward))
         return winner;
 
     // There are no nodes before start with the same tabindex as start, so look for a node that:
@@ -609,7 +612,7 @@
                 return;
 
             if (Node* shadowAncestorNode = root->deprecatedShadowAncestorNode()) {
-                if (!shadowAncestorNode->hasTagName(inputTag) && !isHTMLTextAreaElement(shadowAncestorNode))
+                if (!shadowAncestorNode->hasTagName(inputTag) && !shadowAncestorNode->hasTagName(textareaTag))
                     return;
             }
         }
@@ -618,7 +621,7 @@
     selection.clear();
 }
 
-bool FocusController::setFocusedElement(Element* element, PassRefPtr<Frame> newFocusedFrame, FocusDirection direction)
+bool FocusController::setFocusedElement(Element* element, PassRefPtr<Frame> newFocusedFrame, FocusType type)
 {
     RefPtr<Frame> oldFocusedFrame = focusedFrame();
     RefPtr<Document> oldDocument = oldFocusedFrame ? oldFocusedFrame->document() : 0;
@@ -639,7 +642,7 @@
     else if (newFocusedFrame)
         newDocument = newFocusedFrame->document();
 
-    if (newDocument && newDocument->focusedElement() == element)
+    if (newDocument && oldDocument == newDocument && newDocument->focusedElement() == element)
         return true;
 
     clearSelectionIfNeeded(oldFocusedFrame.get(), newFocusedFrame.get(), element);
@@ -656,7 +659,7 @@
     // Setting the focused node can result in losing our last reft to node when JS event handlers fire.
     RefPtr<Element> protect = element;
     if (newDocument) {
-        bool successfullyFocused = newDocument->setFocusedElement(element, direction);
+        bool successfullyFocused = newDocument->setFocusedElement(element, type);
         if (!successfullyFocused)
             return false;
     }
@@ -673,6 +676,8 @@
 
     if (FrameView* view = m_page->mainFrame()->view()) {
         view->updateLayoutAndStyleIfNeededRecursive();
+        // https://code.google.com/p/chromium/issues/detail?id=343758
+        DisableCompositingQueryAsserts disabler;
         view->updateControlTints();
     }
 
@@ -718,7 +723,7 @@
     }
 }
 
-static void updateFocusCandidateIfNeeded(FocusDirection direction, const FocusCandidate& current, FocusCandidate& candidate, FocusCandidate& closest)
+static void updateFocusCandidateIfNeeded(FocusType type, const FocusCandidate& current, FocusCandidate& candidate, FocusCandidate& closest)
 {
     ASSERT(candidate.visibleNode->isElementNode());
     ASSERT(candidate.visibleNode->renderer());
@@ -728,10 +733,10 @@
         return;
 
     // Ignore off screen child nodes of containers that do not scroll (overflow:hidden)
-    if (candidate.isOffscreen && !canBeScrolledIntoView(direction, candidate))
+    if (candidate.isOffscreen && !canBeScrolledIntoView(type, candidate))
         return;
 
-    distanceDataForNode(direction, current, candidate);
+    distanceDataForNode(type, current, candidate);
     if (candidate.distance == maxDistance())
         return;
 
@@ -767,7 +772,7 @@
         closest = candidate;
 }
 
-void FocusController::findFocusCandidateInContainer(Node& container, const LayoutRect& startingRect, FocusDirection direction, FocusCandidate& closest)
+void FocusController::findFocusCandidateInContainer(Node& container, const LayoutRect& startingRect, FocusType type, FocusCandidate& closest)
 {
     Element* focusedElement = (focusedFrame() && focusedFrame()->document()) ? focusedFrame()->document()->focusedElement() : 0;
 
@@ -777,25 +782,25 @@
     current.focusableNode = focusedElement;
     current.visibleNode = focusedElement;
 
-    for (; element; element = (element->isFrameOwnerElement() || canScrollInDirection(element, direction))
+    for (; element; element = (element->isFrameOwnerElement() || canScrollInDirection(element, type))
         ? ElementTraversal::nextSkippingChildren(*element, &container)
         : ElementTraversal::next(*element, &container)) {
         if (element == focusedElement)
             continue;
 
-        if (!element->isKeyboardFocusable() && !element->isFrameOwnerElement() && !canScrollInDirection(element, direction))
+        if (!element->isKeyboardFocusable() && !element->isFrameOwnerElement() && !canScrollInDirection(element, type))
             continue;
 
-        FocusCandidate candidate = FocusCandidate(element, direction);
+        FocusCandidate candidate = FocusCandidate(element, type);
         if (candidate.isNull())
             continue;
 
         candidate.enclosingScrollableBox = &container;
-        updateFocusCandidateIfNeeded(direction, current, candidate, closest);
+        updateFocusCandidateIfNeeded(type, current, candidate, closest);
     }
 }
 
-bool FocusController::advanceFocusDirectionallyInContainer(Node* container, const LayoutRect& startingRect, FocusDirection direction)
+bool FocusController::advanceFocusDirectionallyInContainer(Node* container, const LayoutRect& startingRect, FocusType type)
 {
     if (!container)
         return false;
@@ -803,17 +808,17 @@
     LayoutRect newStartingRect = startingRect;
 
     if (startingRect.isEmpty())
-        newStartingRect = virtualRectForDirection(direction, nodeRectInAbsoluteCoordinates(container));
+        newStartingRect = virtualRectForDirection(type, nodeRectInAbsoluteCoordinates(container));
 
     // Find the closest node within current container in the direction of the navigation.
     FocusCandidate focusCandidate;
-    findFocusCandidateInContainer(*container, newStartingRect, direction, focusCandidate);
+    findFocusCandidateInContainer(*container, newStartingRect, type, focusCandidate);
 
     if (focusCandidate.isNull()) {
         // Nothing to focus, scroll if possible.
         // NOTE: If no scrolling is performed (i.e. scrollInDirection returns false), the
         // spatial navigation algorithm will skip this container.
-        return scrollInDirection(container, direction);
+        return scrollInDirection(container, type);
     }
 
     if (HTMLFrameOwnerElement* frameElement = frameOwnerElement(focusCandidate)) {
@@ -823,7 +828,7 @@
         ASSERT(frameElement->contentFrame());
 
         if (focusCandidate.isOffscreenAfterScrolling) {
-            scrollInDirection(&focusCandidate.visibleNode->document(), direction);
+            scrollInDirection(&focusCandidate.visibleNode->document(), type);
             return true;
         }
         // Navigate into a new frame.
@@ -832,16 +837,16 @@
         if (focusedElement && !hasOffscreenRect(focusedElement))
             rect = nodeRectInAbsoluteCoordinates(focusedElement, true /* ignore border */);
         frameElement->contentFrame()->document()->updateLayoutIgnorePendingStylesheets();
-        if (!advanceFocusDirectionallyInContainer(frameElement->contentFrame()->document(), rect, direction)) {
+        if (!advanceFocusDirectionallyInContainer(frameElement->contentFrame()->document(), rect, type)) {
             // The new frame had nothing interesting, need to find another candidate.
-            return advanceFocusDirectionallyInContainer(container, nodeRectInAbsoluteCoordinates(focusCandidate.visibleNode, true), direction);
+            return advanceFocusDirectionallyInContainer(container, nodeRectInAbsoluteCoordinates(focusCandidate.visibleNode, true), type);
         }
         return true;
     }
 
-    if (canScrollInDirection(focusCandidate.visibleNode, direction)) {
+    if (canScrollInDirection(focusCandidate.visibleNode, type)) {
         if (focusCandidate.isOffscreenAfterScrolling) {
-            scrollInDirection(focusCandidate.visibleNode, direction);
+            scrollInDirection(focusCandidate.visibleNode, type);
             return true;
         }
         // Navigate into a new scrollable container.
@@ -849,11 +854,11 @@
         Element* focusedElement = focusedOrMainFrame()->document()->focusedElement();
         if (focusedElement && !hasOffscreenRect(focusedElement))
             startingRect = nodeRectInAbsoluteCoordinates(focusedElement, true);
-        return advanceFocusDirectionallyInContainer(focusCandidate.visibleNode, startingRect, direction);
+        return advanceFocusDirectionallyInContainer(focusCandidate.visibleNode, startingRect, type);
     }
     if (focusCandidate.isOffscreenAfterScrolling) {
         Node* container = focusCandidate.enclosingScrollableBox;
-        scrollInDirection(container, direction);
+        scrollInDirection(container, type);
         return true;
     }
 
@@ -861,11 +866,11 @@
     Element* element = toElement(focusCandidate.focusableNode);
     ASSERT(element);
 
-    element->focus(false, direction);
+    element->focus(false, type);
     return true;
 }
 
-bool FocusController::advanceFocusDirectionally(FocusDirection direction)
+bool FocusController::advanceFocusDirectionally(FocusType type)
 {
     Frame* curFrame = focusedOrMainFrame();
     ASSERT(curFrame);
@@ -884,20 +889,20 @@
     LayoutRect startingRect;
     if (focusedElement) {
         if (!hasOffscreenRect(focusedElement)) {
-            container = scrollableEnclosingBoxOrParentFrameForNodeInDirection(direction, focusedElement);
+            container = scrollableEnclosingBoxOrParentFrameForNodeInDirection(type, focusedElement);
             startingRect = nodeRectInAbsoluteCoordinates(focusedElement, true /* ignore border */);
-        } else if (isHTMLAreaElement(focusedElement)) {
+        } else if (focusedElement->hasTagName(areaTag)) {
             HTMLAreaElement* area = toHTMLAreaElement(focusedElement);
-            container = scrollableEnclosingBoxOrParentFrameForNodeInDirection(direction, area->imageElement());
-            startingRect = virtualRectForAreaElementAndDirection(area, direction);
+            container = scrollableEnclosingBoxOrParentFrameForNodeInDirection(type, area->imageElement());
+            startingRect = virtualRectForAreaElementAndDirection(area, type);
         }
     }
 
     bool consumed = false;
     do {
-        consumed = advanceFocusDirectionallyInContainer(container, startingRect, direction);
+        consumed = advanceFocusDirectionallyInContainer(container, startingRect, type);
         startingRect = nodeRectInAbsoluteCoordinates(container, true /* ignore border */);
-        container = scrollableEnclosingBoxOrParentFrameForNodeInDirection(direction, container);
+        container = scrollableEnclosingBoxOrParentFrameForNodeInDirection(type, container);
         if (container && container->isDocumentNode())
             toDocument(container)->updateLayoutIgnorePendingStylesheets();
     } while (!consumed && container);
diff --git a/Source/core/page/FocusController.h b/Source/core/page/FocusController.h
index 38069eb..0983fcd 100644
--- a/Source/core/page/FocusController.h
+++ b/Source/core/page/FocusController.h
@@ -26,7 +26,7 @@
 #ifndef FocusController_h
 #define FocusController_h
 
-#include "core/page/FocusDirection.h"
+#include "core/page/FocusType.h"
 #include "platform/geometry/LayoutRect.h"
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
@@ -70,10 +70,10 @@
     Frame* focusedFrame() const { return m_focusedFrame.get(); }
     Frame* focusedOrMainFrame() const;
 
-    bool setInitialFocus(FocusDirection);
-    bool advanceFocus(FocusDirection direction) { return advanceFocus(direction, false); }
+    bool setInitialFocus(FocusType);
+    bool advanceFocus(FocusType type) { return advanceFocus(type, false); }
 
-    bool setFocusedElement(Element*, PassRefPtr<Frame>, FocusDirection = FocusDirectionNone);
+    bool setFocusedElement(Element*, PassRefPtr<Frame>, FocusType = FocusTypeNone);
 
     void setActive(bool);
     bool isActive() const { return m_isActive; }
@@ -87,13 +87,13 @@
 private:
     explicit FocusController(Page*);
 
-    bool advanceFocus(FocusDirection, bool initialFocus);
-    bool advanceFocusDirectionally(FocusDirection);
-    bool advanceFocusInDocumentOrder(FocusDirection, bool initialFocus);
+    bool advanceFocus(FocusType, bool initialFocus);
+    bool advanceFocusDirectionally(FocusType);
+    bool advanceFocusInDocumentOrder(FocusType, bool initialFocus);
 
-    Node* findFocusableNodeAcrossFocusScope(FocusDirection, FocusNavigationScope startScope, Node* start);
-    Node* findFocusableNodeRecursively(FocusDirection, FocusNavigationScope, Node* start);
-    Node* findFocusableNodeDecendingDownIntoFrameDocument(FocusDirection, Node*);
+    Node* findFocusableNodeAcrossFocusScope(FocusType, FocusNavigationScope startScope, Node* start);
+    Node* findFocusableNodeRecursively(FocusType, FocusNavigationScope, Node* start);
+    Node* findFocusableNodeDecendingDownIntoFrameDocument(FocusType, Node*);
 
     // Searches through the given tree scope, starting from start node, for the next/previous selectable element that comes after/before start node.
     // The order followed is as specified in section 17.11.1 of the HTML4 spec, which is elements with tab indexes
@@ -104,15 +104,15 @@
     // @return The focus node that comes after/before start node.
     //
     // See http://www.w3.org/TR/html4/interact/forms.html#h-17.11.1
-    inline Node* findFocusableNode(FocusDirection, FocusNavigationScope, Node* start);
+    inline Node* findFocusableNode(FocusType, FocusNavigationScope, Node* start);
 
     Node* nextFocusableNode(FocusNavigationScope, Node* start);
     Node* previousFocusableNode(FocusNavigationScope, Node* start);
 
-    Node* findNodeWithExactTabIndex(Node* start, int tabIndex, FocusDirection);
+    Node* findNodeWithExactTabIndex(Node* start, int tabIndex, FocusType);
 
-    bool advanceFocusDirectionallyInContainer(Node* container, const LayoutRect& startingRect, FocusDirection);
-    void findFocusCandidateInContainer(Node& container, const LayoutRect& startingRect, FocusDirection, FocusCandidate& closest);
+    bool advanceFocusDirectionallyInContainer(Node* container, const LayoutRect& startingRect, FocusType);
+    void findFocusCandidateInContainer(Node& container, const LayoutRect& startingRect, FocusType, FocusCandidate& closest);
 
     Page* m_page;
     RefPtr<Frame> m_focusedFrame;
diff --git a/Source/core/page/FocusDirection.h b/Source/core/page/FocusType.h
similarity index 70%
rename from Source/core/page/FocusDirection.h
rename to Source/core/page/FocusType.h
index c972e11..ac2d81c 100644
--- a/Source/core/page/FocusDirection.h
+++ b/Source/core/page/FocusType.h
@@ -23,27 +23,28 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef FocusDirection_h
-#define FocusDirection_h
+#ifndef FocusType_h
+#define FocusType_h
 
 namespace WebCore {
-// FIXME: Rename FocusDirection to FocusType or something.
-    enum FocusDirection {
-        // Element::focus(), etc.
-        FocusDirectionNone = 0,
-        // TAB, or Shift + TAB
-        FocusDirectionForward,
-        FocusDirectionBackward,
-        // Spatial navigation.
-        FocusDirectionUp,
-        FocusDirectionDown,
-        FocusDirectionLeft,
-        FocusDirectionRight,
-        // Mouse press
-        FocusDirectionMouse,
-        // Re-focus by a page focus
-        FocusDirectionPage
-    };
+
+enum FocusType {
+    // Element::focus(), etc.
+    FocusTypeNone = 0,
+    // Sequential navigation with TAB, or Shift + TAB.
+    FocusTypeForward,
+    FocusTypeBackward,
+    // Spatial navigation.
+    FocusTypeUp,
+    FocusTypeDown,
+    FocusTypeLeft,
+    FocusTypeRight,
+    // Mouse press
+    FocusTypeMouse,
+    // Re-focus by a page focus
+    FocusTypePage
+};
+
 }
 
-#endif // FocusDirection_h
+#endif // FocusType_h
diff --git a/Source/core/page/FrameTree.cpp b/Source/core/page/FrameTree.cpp
index b7e7dc1..cc01cfb 100644
--- a/Source/core/page/FrameTree.cpp
+++ b/Source/core/page/FrameTree.cpp
@@ -24,6 +24,7 @@
 #include "core/dom/Document.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
+#include "core/loader/FrameLoaderClient.h"
 #include "core/page/Page.h"
 #include "core/page/PageGroup.h"
 #include "wtf/Vector.h"
@@ -34,8 +35,21 @@
 
 namespace WebCore {
 
+namespace {
+
+const unsigned invalidChildCount = ~0;
+
+} // namespace
+
+FrameTree::FrameTree(Frame* thisFrame)
+    : m_thisFrame(thisFrame)
+    , m_scopedChildCount(invalidChildCount)
+{
+}
+
 FrameTree::~FrameTree()
 {
+    // FIXME: Why is this here? Doesn't this parallel what we already do in ~Frame?
     for (Frame* child = firstChild(); child; child = child->tree().nextSibling())
         child->setView(0);
 }
@@ -53,45 +67,48 @@
 
 Frame* FrameTree::parent() const
 {
-    return m_parent;
+    if (!m_thisFrame->loader().client())
+        return 0;
+    return m_thisFrame->loader().client()->parent();
 }
 
-void FrameTree::appendChild(PassRefPtr<Frame> child)
+Frame* FrameTree::top() const
 {
-    ASSERT(child->page() == m_thisFrame->page());
-    child->tree().m_parent = m_thisFrame;
-    Frame* oldLast = m_lastChild;
-    m_lastChild = child.get();
-
-    if (oldLast) {
-        child->tree().m_previousSibling = oldLast;
-        oldLast->tree().m_nextSibling = child;
-    } else
-        m_firstChild = child;
-
-    m_scopedChildCount = invalidCount;
-
-    ASSERT(!m_lastChild->tree().m_nextSibling);
+    // FIXME: top() should never return null, so here are some hacks to deal
+    // with EmptyFrameLoaderClient and cases where the frame is detached
+    // already...
+    if (!m_thisFrame->loader().client())
+        return m_thisFrame;
+    Frame* candidate = m_thisFrame->loader().client()->top();
+    return candidate ? candidate : m_thisFrame;
 }
 
-void FrameTree::removeChild(Frame* child)
+Frame* FrameTree::previousSibling() const
 {
-    child->tree().m_parent = 0;
+    if (!m_thisFrame->loader().client())
+        return 0;
+    return m_thisFrame->loader().client()->previousSibling();
+}
 
-    // Slightly tricky way to prevent deleting the child until we are done with it, w/o
-    // extra refs. These swaps leave the child in a circular list by itself. Clearing its
-    // previous and next will then finally deref it.
+Frame* FrameTree::nextSibling() const
+{
+    if (!m_thisFrame->loader().client())
+        return 0;
+    return m_thisFrame->loader().client()->nextSibling();
+}
 
-    RefPtr<Frame>& newLocationForNext = m_firstChild == child ? m_firstChild : child->tree().m_previousSibling->tree().m_nextSibling;
-    Frame*& newLocationForPrevious = m_lastChild == child ? m_lastChild : child->tree().m_nextSibling->tree().m_previousSibling;
-    swap(newLocationForNext, child->tree().m_nextSibling);
-    // For some inexplicable reason, the following line does not compile without the explicit std:: namespace
-    std::swap(newLocationForPrevious, child->tree().m_previousSibling);
+Frame* FrameTree::firstChild() const
+{
+    if (!m_thisFrame->loader().client())
+        return 0;
+    return m_thisFrame->loader().client()->firstChild();
+}
 
-    child->tree().m_previousSibling = 0;
-    child->tree().m_nextSibling = 0;
-
-    m_scopedChildCount = invalidCount;
+Frame* FrameTree::lastChild() const
+{
+    if (!m_thisFrame->loader().client())
+        return 0;
+    return m_thisFrame->loader().client()->lastChild();
 }
 
 AtomicString FrameTree::uniqueChildName(const AtomicString& requestedName) const
@@ -131,7 +148,7 @@
     }
 
     name.appendLiteral("/<!--frame");
-    name.appendNumber(childCount());
+    name.appendNumber(childCount() - 1);
     name.appendLiteral("-->-->");
 
     return name.toAtomicString();
@@ -183,11 +200,16 @@
 
 unsigned FrameTree::scopedChildCount() const
 {
-    if (m_scopedChildCount == invalidCount)
+    if (m_scopedChildCount == invalidChildCount)
         m_scopedChildCount = scopedChildCount(m_thisFrame->document());
     return m_scopedChildCount;
 }
 
+void FrameTree::invalidateScopedChildCount()
+{
+    m_scopedChildCount = invalidChildCount;
+}
+
 unsigned FrameTree::childCount() const
 {
     unsigned count = 0;
@@ -336,14 +358,6 @@
     return result;
 }
 
-Frame* FrameTree::top() const
-{
-    Frame* frame = m_thisFrame;
-    for (Frame* parent = m_thisFrame; parent; parent = parent->tree().parent())
-        frame = parent;
-    return frame;
-}
-
 } // namespace WebCore
 
 #ifndef NDEBUG
@@ -371,7 +385,7 @@
     printIndent(indent);
     printf("  document=%p\n", frame->document());
     printIndent(indent);
-    printf("  uri=%s\n\n", frame->document()->documentURI().utf8().data());
+    printf("  uri=%s\n\n", frame->document()->url().string().utf8().data());
 
     for (WebCore::Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling())
         printFrames(child, targetFrame, indent + 1);
diff --git a/Source/core/page/FrameTree.h b/Source/core/page/FrameTree.h
index 9f7f842..0ac7be3 100644
--- a/Source/core/page/FrameTree.h
+++ b/Source/core/page/FrameTree.h
@@ -30,48 +30,33 @@
     class FrameTree {
         WTF_MAKE_NONCOPYABLE(FrameTree);
     public:
-        const static unsigned invalidCount = static_cast<unsigned>(-1);
-
-        FrameTree(Frame* thisFrame, Frame* parentFrame)
-            : m_thisFrame(thisFrame)
-            , m_parent(parentFrame)
-            , m_previousSibling(0)
-            , m_lastChild(0)
-            , m_scopedChildCount(invalidCount)
-        {
-        }
-
+        explicit FrameTree(Frame* thisFrame);
         ~FrameTree();
 
         const AtomicString& name() const { return m_name; }
         const AtomicString& uniqueName() const { return m_uniqueName; }
         void setName(const AtomicString&);
-        Frame* parent() const;
-        void setParent(Frame* parent) { m_parent = parent; }
 
-        Frame* nextSibling() const { return m_nextSibling.get(); }
-        Frame* previousSibling() const { return m_previousSibling; }
-        Frame* firstChild() const { return m_firstChild.get(); }
-        Frame* lastChild() const { return m_lastChild; }
+        Frame* parent() const;
+        Frame* top() const;
+        Frame* previousSibling() const;
+        Frame* nextSibling() const;
+        Frame* firstChild() const;
+        Frame* lastChild() const;
 
         bool isDescendantOf(const Frame* ancestor) const;
+        Frame* traversePreviousWithWrap(bool) const;
         Frame* traverseNext(const Frame* stayWithin = 0) const;
         Frame* traverseNextWithWrap(bool) const;
-        Frame* traversePreviousWithWrap(bool) const;
-
-        void appendChild(PassRefPtr<Frame>);
-        void detachFromParent() { m_parent = 0; }
-        void removeChild(Frame*);
 
         Frame* child(const AtomicString& name) const;
         Frame* find(const AtomicString& name) const;
         unsigned childCount() const;
 
-        Frame* top() const;
-
         Frame* scopedChild(unsigned index) const;
         Frame* scopedChild(const AtomicString& name) const;
         unsigned scopedChildCount() const;
+        void invalidateScopedChildCount();
 
     private:
         Frame* deepLastChild() const;
@@ -80,15 +65,9 @@
 
         Frame* m_thisFrame;
 
-        Frame* m_parent;
         AtomicString m_name; // The actual frame name (may be empty).
         AtomicString m_uniqueName;
 
-        // FIXME: use ListRefPtr?
-        RefPtr<Frame> m_nextSibling;
-        Frame* m_previousSibling;
-        RefPtr<Frame> m_firstChild;
-        Frame* m_lastChild;
         mutable unsigned m_scopedChildCount;
     };
 
diff --git a/Source/core/loader/HistoryController.cpp b/Source/core/page/HistoryController.cpp
similarity index 70%
rename from Source/core/loader/HistoryController.cpp
rename to Source/core/page/HistoryController.cpp
index fc3fbee..9b246ab 100644
--- a/Source/core/loader/HistoryController.cpp
+++ b/Source/core/page/HistoryController.cpp
@@ -29,10 +29,10 @@
  */
 
 #include "config.h"
-#include "core/loader/HistoryController.h"
+#include "core/page/HistoryController.h"
 
-#include "core/loader/FrameLoader.h"
 #include "core/frame/Frame.h"
+#include "core/loader/FrameLoader.h"
 #include "core/page/FrameTree.h"
 #include "core/page/Page.h"
 #include "wtf/Deque.h"
@@ -59,12 +59,9 @@
 
     if (!clipAtTarget || !isNodeBeingNavigated) {
         for (Frame* child = currentFrame->tree().firstChild(); child; child = child->tree().nextSibling()) {
-            HistoryNode* childHistoryNode = m_entry->m_framesToItems.get(child->frameID());
-            if (!childHistoryNode) {
-                if (targetFrame == child)
-                    newHistoryNode->m_children.append(create(newEntry, newItem));
+            HistoryNode* childHistoryNode = m_entry->historyNodeForFrame(child);
+            if (!childHistoryNode)
                 continue;
-            }
             newHistoryNode->m_children.append(childHistoryNode->cloneAndReplace(newEntry, newItem, clipAtTarget, targetFrame, child));
         }
     }
@@ -82,6 +79,26 @@
     m_entry->m_uniqueNamesToItems.add(target, this);
 }
 
+void HistoryNode::removeChildren()
+{
+    // FIXME: This is inefficient. Figure out a cleaner way to ensure this HistoryNode isn't cached anywhere.
+    for (unsigned i = 0; i < m_children.size(); i++) {
+        m_children[i]->removeChildren();
+
+        HashMap<uint64_t, HistoryNode*>::iterator framesEnd = m_entry->m_framesToItems.end();
+        HashMap<String, HistoryNode*>::iterator uniqueNamesEnd = m_entry->m_uniqueNamesToItems.end();
+        for (HashMap<uint64_t, HistoryNode*>::iterator it = m_entry->m_framesToItems.begin(); it != framesEnd; ++it) {
+            if (it->value == m_children[i])
+                m_entry->m_framesToItems.remove(it);
+        }
+        for (HashMap<String, HistoryNode*>::iterator it = m_entry->m_uniqueNamesToItems.begin(); it != uniqueNamesEnd; ++it) {
+            if (it->value == m_children[i])
+                m_entry->m_uniqueNamesToItems.remove(it);
+        }
+    }
+    m_children.clear();
+}
+
 HistoryEntry::HistoryEntry(HistoryItem* root)
 {
     m_root = HistoryNode::create(this, root);
@@ -119,6 +136,7 @@
 HistoryController::HistoryController(Page* page)
     : m_page(page)
     , m_defersLoading(false)
+    , m_deferredCachePolicy(UseProtocolCachePolicy)
 {
 }
 
@@ -128,59 +146,64 @@
 
 void HistoryController::updateBackForwardListForFragmentScroll(Frame* frame, HistoryItem* item)
 {
-    m_provisionalEntry.clear();
     createNewBackForwardItem(frame, item, false);
 }
 
-void HistoryController::goToEntry(PassOwnPtr<HistoryEntry> targetEntry)
+void HistoryController::goToEntry(PassOwnPtr<HistoryEntry> targetEntry, ResourceRequestCachePolicy cachePolicy)
 {
-    ASSERT(m_sameDocumentLoadsInProgress.isEmpty());
-    ASSERT(m_differentDocumentLoadsInProgress.isEmpty());
+    HistoryFrameLoadSet sameDocumentLoads;
+    HistoryFrameLoadSet differentDocumentLoads;
 
     m_provisionalEntry = targetEntry;
-    recursiveGoToEntry(m_page->mainFrame());
+    if (m_currentEntry)
+        recursiveGoToEntry(m_page->mainFrame(), sameDocumentLoads, differentDocumentLoads);
+    else
+        differentDocumentLoads.set(m_page->mainFrame(), m_provisionalEntry->root());
 
-    if (m_sameDocumentLoadsInProgress.isEmpty() && m_differentDocumentLoadsInProgress.isEmpty())
-        m_sameDocumentLoadsInProgress.set(m_page->mainFrame(), m_provisionalEntry->root());
+    if (sameDocumentLoads.isEmpty() && differentDocumentLoads.isEmpty())
+        sameDocumentLoads.set(m_page->mainFrame(), m_provisionalEntry->root());
 
-    if (m_differentDocumentLoadsInProgress.isEmpty()) {
+    if (differentDocumentLoads.isEmpty()) {
         m_previousEntry = m_currentEntry.release();
         m_currentEntry = m_provisionalEntry.release();
-    } else {
-        m_page->mainFrame()->loader().stopAllLoaders();
     }
 
-    for (HistoryFrameLoadSet::iterator it = m_sameDocumentLoadsInProgress.begin(); it != m_sameDocumentLoadsInProgress.end(); ++it)
-        it->key->loader().loadHistoryItem(it->value, HistorySameDocumentLoad);
-    for (HistoryFrameLoadSet::iterator it = m_differentDocumentLoadsInProgress.begin(); it != m_differentDocumentLoadsInProgress.end(); ++it)
-        it->key->loader().loadHistoryItem(it->value, HistoryDifferentDocumentLoad);
-    m_sameDocumentLoadsInProgress.clear();
-    m_differentDocumentLoadsInProgress.clear();
+    for (HistoryFrameLoadSet::iterator it = sameDocumentLoads.begin(); it != sameDocumentLoads.end(); ++it) {
+        if (it->key->host())
+            it->key->loader().loadHistoryItem(it->value.get(), HistorySameDocumentLoad, cachePolicy);
+    }
+    for (HistoryFrameLoadSet::iterator it = differentDocumentLoads.begin(); it != differentDocumentLoads.end(); ++it) {
+        if (it->key->host())
+            it->key->loader().loadHistoryItem(it->value.get(), HistoryDifferentDocumentLoad, cachePolicy);
+    }
 }
 
-void HistoryController::recursiveGoToEntry(Frame* frame)
+void HistoryController::recursiveGoToEntry(Frame* frame, HistoryFrameLoadSet& sameDocumentLoads, HistoryFrameLoadSet& differentDocumentLoads)
 {
+    ASSERT(m_provisionalEntry);
+    ASSERT(m_currentEntry);
     HistoryItem* newItem = m_provisionalEntry->itemForFrame(frame);
-    HistoryItem* oldItem = m_currentEntry ? m_currentEntry->itemForFrame(frame) : 0;
+    HistoryItem* oldItem = m_currentEntry->itemForFrame(frame);
     if (!newItem)
         return;
 
     if (!oldItem || (newItem != oldItem && newItem->itemSequenceNumber() != oldItem->itemSequenceNumber())) {
         if (oldItem && newItem->documentSequenceNumber() == oldItem->documentSequenceNumber())
-            m_sameDocumentLoadsInProgress.set(frame, newItem);
+            sameDocumentLoads.set(frame, newItem);
         else
-            m_differentDocumentLoadsInProgress.set(frame, newItem);
+            differentDocumentLoads.set(frame, newItem);
         return;
     }
 
     for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling())
-        recursiveGoToEntry(child);
+        recursiveGoToEntry(child, sameDocumentLoads, differentDocumentLoads);
 }
 
-void HistoryController::goToItem(HistoryItem* targetItem)
+void HistoryController::goToItem(HistoryItem* targetItem, ResourceRequestCachePolicy cachePolicy)
 {
     if (m_defersLoading) {
         m_deferredItem = targetItem;
+        m_deferredCachePolicy = cachePolicy;
         return;
     }
 
@@ -199,15 +222,16 @@
         }
         historyNode->value()->clearChildren();
     }
-    goToEntry(newEntry.release());
+    goToEntry(newEntry.release(), cachePolicy);
 }
 
 void HistoryController::setDefersLoading(bool defer)
 {
     m_defersLoading = defer;
     if (!defer && m_deferredItem) {
-        goToItem(m_deferredItem.get());
+        goToItem(m_deferredItem.get(), m_deferredCachePolicy);
         m_deferredItem = 0;
+        m_deferredCachePolicy = UseProtocolCachePolicy;
     }
 }
 
@@ -216,16 +240,17 @@
     ASSERT(frame->tree().parent());
     if (!m_currentEntry)
         return;
-    if (HistoryNode* existingChildHistoryNode = m_currentEntry->historyNodeForFrame(frame))
-        existingChildHistoryNode->updateValue(item);
+    if (HistoryNode* existingNode = m_currentEntry->historyNodeForFrame(frame))
+        existingNode->updateValue(item);
     else if (HistoryNode* parentHistoryNode = m_currentEntry->historyNodeForFrame(frame->tree().parent()))
         parentHistoryNode->addChild(item);
 }
 
-void HistoryController::updateForCommit(Frame* frame, HistoryItem* item)
+void HistoryController::updateForCommit(Frame* frame, HistoryItem* item, HistoryCommitType commitType)
 {
-    FrameLoadType type = frame->loader().loadType();
-    if (isBackForwardLoadType(type) && m_provisionalEntry) {
+    if (commitType == BackForwardCommit) {
+        if (!m_provisionalEntry)
+            return;
         // Once committed, we want to use current item for saving DocState, and
         // the provisional item for restoring state.
         // Note previousItem must be set before we close the URL, which will
@@ -233,18 +258,16 @@
         m_previousEntry = m_currentEntry.release();
         ASSERT(m_provisionalEntry);
         m_currentEntry = m_provisionalEntry.release();
-    } else if (type != FrameLoadTypeRedirectWithLockedBackForwardList) {
-        m_provisionalEntry.clear();
-    }
-
-    if (type == FrameLoadTypeStandard)
+    } else if (commitType == StandardCommit) {
         createNewBackForwardItem(frame, item, true);
-    else if (type == FrameLoadTypeInitialInChildFrame)
+    } else if (commitType == InitialCommitInChildFrame) {
         updateForInitialLoadInChildFrame(frame, item);
+    }
 }
 
 static PassRefPtr<HistoryItem> itemForExport(HistoryNode* historyNode)
 {
+    ASSERT(historyNode);
     RefPtr<HistoryItem> item = historyNode->value()->copy();
     const Vector<OwnPtr<HistoryNode> >& childEntries = historyNode->children();
     for (size_t i = 0; i < childEntries.size(); i++)
@@ -252,28 +275,18 @@
     return item;
 }
 
-PassRefPtr<HistoryItem> HistoryController::currentItemForExport(Frame* frame)
+PassRefPtr<HistoryItem> HistoryController::currentItemForExport()
 {
     if (!m_currentEntry)
         return 0;
-    HistoryNode* historyNode = m_currentEntry->historyNodeForFrame(frame);
-    return historyNode ? itemForExport(historyNode) : 0;
+    return itemForExport(m_currentEntry->rootHistoryNode());
 }
 
-PassRefPtr<HistoryItem> HistoryController::previousItemForExport(Frame* frame)
+PassRefPtr<HistoryItem> HistoryController::previousItemForExport()
 {
     if (!m_previousEntry)
         return 0;
-    HistoryNode* historyNode = m_previousEntry->historyNodeForFrame(frame);
-    return historyNode ? itemForExport(historyNode) : 0;
-}
-
-PassRefPtr<HistoryItem> HistoryController::provisionalItemForExport(Frame* frame)
-{
-    if (!m_provisionalEntry)
-        return 0;
-    HistoryNode* historyNode = m_provisionalEntry->historyNodeForFrame(frame);
-    return historyNode ? itemForExport(historyNode) : 0;
+    return itemForExport(m_previousEntry->rootHistoryNode());
 }
 
 HistoryItem* HistoryController::itemForNewChildFrame(Frame* frame) const
@@ -281,6 +294,14 @@
     return m_currentEntry ? m_currentEntry->itemForFrame(frame) : 0;
 }
 
+void HistoryController::removeChildrenForRedirect(Frame* frame)
+{
+    if (!m_provisionalEntry)
+        return;
+    if (HistoryNode* node = m_provisionalEntry->historyNodeForFrame(frame))
+        node->removeChildren();
+}
+
 void HistoryController::createNewBackForwardItem(Frame* targetFrame, HistoryItem* item, bool clipAtTarget)
 {
     RefPtr<HistoryItem> newItem = item;
diff --git a/Source/core/loader/HistoryController.h b/Source/core/page/HistoryController.h
similarity index 90%
rename from Source/core/loader/HistoryController.h
rename to Source/core/page/HistoryController.h
index d3e1155..433cea0 100644
--- a/Source/core/loader/HistoryController.h
+++ b/Source/core/page/HistoryController.h
@@ -30,8 +30,9 @@
 #ifndef HistoryController_h
 #define HistoryController_h
 
-#include "core/history/HistoryItem.h"
 #include "core/loader/FrameLoaderTypes.h"
+#include "core/loader/HistoryItem.h"
+#include "platform/network/ResourceRequest.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/RefPtr.h"
@@ -100,6 +101,7 @@
     HistoryItem* value() { return m_value.get(); }
     void updateValue(PassRefPtr<HistoryItem> item) { m_value = item; }
     const Vector<OwnPtr<HistoryNode> >& children() const { return m_children; }
+    void removeChildren();
 
 private:
     HistoryNode(HistoryEntry*, HistoryItem*);
@@ -107,6 +109,7 @@
     HistoryEntry* m_entry;
     Vector<OwnPtr<HistoryNode> > m_children;
     RefPtr<HistoryItem> m_value;
+
 };
 
 class HistoryEntry {
@@ -138,23 +141,22 @@
 
     // Should only be called by embedder. To request a back/forward
     // navigation, call FrameLoaderClient::navigateBackForward().
-    void goToItem(HistoryItem*);
+    void goToItem(HistoryItem*, ResourceRequestCachePolicy);
 
     void updateBackForwardListForFragmentScroll(Frame*, HistoryItem*);
-    void updateForCommit(Frame*, HistoryItem*);
+    void updateForCommit(Frame*, HistoryItem*, HistoryCommitType);
 
-    PassRefPtr<HistoryItem> currentItemForExport(Frame*);
-    PassRefPtr<HistoryItem> previousItemForExport(Frame*);
-    PassRefPtr<HistoryItem> provisionalItemForExport(Frame*);
+    PassRefPtr<HistoryItem> currentItemForExport();
+    PassRefPtr<HistoryItem> previousItemForExport();
     HistoryItem* itemForNewChildFrame(Frame*) const;
-
-    bool inSameDocumentLoad() const { return !m_sameDocumentLoadsInProgress.isEmpty() && m_differentDocumentLoadsInProgress.isEmpty(); }
+    void removeChildrenForRedirect(Frame*);
 
     void setDefersLoading(bool);
 
 private:
-    void goToEntry(PassOwnPtr<HistoryEntry>);
-    void recursiveGoToEntry(Frame*);
+    void goToEntry(PassOwnPtr<HistoryEntry>, ResourceRequestCachePolicy);
+    typedef HashMap<RefPtr<Frame>, RefPtr<HistoryItem> > HistoryFrameLoadSet;
+    void recursiveGoToEntry(Frame*, HistoryFrameLoadSet& sameDocumentLoads, HistoryFrameLoadSet& differentDocumentLoads);
 
     void updateForInitialLoadInChildFrame(Frame*, HistoryItem*);
     void createNewBackForwardItem(Frame*, HistoryItem*, bool doClip);
@@ -165,12 +167,9 @@
     OwnPtr<HistoryEntry> m_previousEntry;
     OwnPtr<HistoryEntry> m_provisionalEntry;
 
-    typedef HashMap<Frame*, HistoryItem*> HistoryFrameLoadSet;
-    HistoryFrameLoadSet m_sameDocumentLoadsInProgress;
-    HistoryFrameLoadSet m_differentDocumentLoadsInProgress;
-
     bool m_defersLoading;
     RefPtr<HistoryItem> m_deferredItem;
+    ResourceRequestCachePolicy m_deferredCachePolicy;
 };
 
 } // namespace WebCore
diff --git a/Source/core/page/InjectedStyleSheets.cpp b/Source/core/page/InjectedStyleSheets.cpp
new file mode 100644
index 0000000..561ecd6
--- /dev/null
+++ b/Source/core/page/InjectedStyleSheets.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright 2014 The Chromium Authors. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/page/InjectedStyleSheets.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/StyleEngine.h"
+#include "core/frame/Frame.h"
+#include "core/page/Page.h"
+#include "core/page/PageGroup.h"
+#include "wtf/HashSet.h"
+
+namespace WebCore {
+
+// static
+InjectedStyleSheets& InjectedStyleSheets::instance()
+{
+    DEFINE_STATIC_LOCAL(InjectedStyleSheets, instance, ());
+    return instance;
+}
+
+void InjectedStyleSheets::add(const String& source, const Vector<String>& whitelist, StyleInjectionTarget injectIn)
+{
+    m_entries.append(adoptPtr(new InjectedStyleSheetEntry(source, whitelist, injectIn)));
+    invalidateInjectedStyleSheetCacheInAllFrames();
+}
+
+void InjectedStyleSheets::removeAll()
+{
+    m_entries.clear();
+    invalidateInjectedStyleSheetCacheInAllFrames();
+}
+
+void InjectedStyleSheets::invalidateInjectedStyleSheetCacheInAllFrames()
+{
+    // Clear our cached sheets and have them just reparse.
+    const HashSet<Page*>& pages = PageGroup::sharedGroup()->pages();
+
+    HashSet<Page*>::const_iterator end = pages.end();
+    for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) {
+        for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
+            frame->document()->styleEngine()->invalidateInjectedStyleSheetCache();
+    }
+}
+
+} // namespace WebCore
diff --git a/Source/core/page/InjectedStyleSheet.h b/Source/core/page/InjectedStyleSheets.h
similarity index 71%
rename from Source/core/page/InjectedStyleSheet.h
rename to Source/core/page/InjectedStyleSheets.h
index cdee055..dbf728f 100644
--- a/Source/core/page/InjectedStyleSheet.h
+++ b/Source/core/page/InjectedStyleSheets.h
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2009 Apple Inc. All rights reserved.
+ * Copyright 2014 The Chromium Authors. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,8 +24,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef InjectedStyleSheet_h
-#define InjectedStyleSheet_h
+#ifndef InjectedStyleSheets_h
+#define InjectedStyleSheets_h
 
 #include "wtf/Vector.h"
 #include "wtf/text/WTFString.h"
@@ -33,10 +34,10 @@
 
 enum StyleInjectionTarget { InjectStyleInAllFrames, InjectStyleInTopFrameOnly };
 
-class InjectedStyleSheet {
+class InjectedStyleSheetEntry {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    InjectedStyleSheet(const String& source, const Vector<String>& whitelist, StyleInjectionTarget injectedFrames)
+    InjectedStyleSheetEntry(const String& source, const Vector<String>& whitelist, StyleInjectionTarget injectedFrames)
         : m_source(source)
         , m_whitelist(whitelist)
         , m_injectedFrames(injectedFrames)
@@ -53,8 +54,24 @@
     StyleInjectionTarget m_injectedFrames;
 };
 
-typedef Vector<OwnPtr<InjectedStyleSheet> > InjectedStyleSheetVector;
+typedef Vector<OwnPtr<InjectedStyleSheetEntry> > InjectedStyleSheetEntryVector;
+
+class InjectedStyleSheets {
+public:
+    static InjectedStyleSheets& instance();
+
+    void add(const String& source, const Vector<String>& whitelist, StyleInjectionTarget);
+    void removeAll();
+
+    const InjectedStyleSheetEntryVector& entries() const { return m_entries; }
+
+private:
+    InjectedStyleSheets() { }
+    void invalidateInjectedStyleSheetCacheInAllFrames();
+
+    InjectedStyleSheetEntryVector m_entries;
+};
 
 } // namespace WebCore
 
-#endif // InjectedStyleSheet_h
+#endif // InjectedStyleSheets_h
diff --git a/Source/core/page/Page.cpp b/Source/core/page/Page.cpp
index 849418f..2b964b3 100644
--- a/Source/core/page/Page.cpp
+++ b/Source/core/page/Page.cpp
@@ -28,12 +28,17 @@
 #include "core/editing/UndoStack.h"
 #include "core/events/Event.h"
 #include "core/events/ThreadLocalEventNames.h"
+#include "core/fetch/ResourceFetcher.h"
 #include "core/frame/DOMTimer.h"
 #include "core/frame/DOMWindow.h"
-#include "core/history/HistoryItem.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
+#include "core/loader/HistoryItem.h"
 #include "core/loader/ProgressTracker.h"
 #include "core/page/AutoscrollController.h"
 #include "core/page/Chrome.h"
@@ -41,19 +46,16 @@
 #include "core/page/ContextMenuController.h"
 #include "core/page/DragController.h"
 #include "core/page/FocusController.h"
-#include "core/frame/Frame.h"
 #include "core/page/FrameTree.h"
-#include "core/frame/FrameView.h"
-#include "core/page/PageConsole.h"
 #include "core/page/PageGroup.h"
 #include "core/page/PageLifecycleNotifier.h"
 #include "core/page/PointerLockController.h"
-#include "core/page/Settings.h"
+#include "core/page/StorageClient.h"
 #include "core/page/ValidationMessageClient.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/TextAutosizer.h"
 #include "core/storage/StorageNamespace.h"
-#include "core/workers/SharedWorkerRepositoryClient.h"
 #include "platform/plugins/PluginData.h"
 #include "wtf/HashMap.h"
 #include "wtf/RefCountedLeakCounter.h"
@@ -62,20 +64,22 @@
 
 namespace WebCore {
 
-static HashSet<Page*>* allPages;
-
 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, pageCounter, ("Page"));
 
+// static
+HashSet<Page*>& Page::allPages()
+{
+    DEFINE_STATIC_LOCAL(HashSet<Page*>, allPages, ());
+    return allPages;
+}
+
 void Page::networkStateChanged(bool online)
 {
-    if (!allPages)
-        return;
-
     Vector<RefPtr<Frame> > frames;
 
     // Get all the frames of all the pages in all the page groups
-    HashSet<Page*>::iterator end = allPages->end();
-    for (HashSet<Page*>::iterator it = allPages->begin(); it != end; ++it) {
+    HashSet<Page*>::iterator end = allPages().end();
+    for (HashSet<Page*>::iterator it = allPages().begin(); it != end; ++it) {
         for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
             frames.append(frame);
         InspectorInstrumentation::networkStateChanged(*it, online);
@@ -97,7 +101,8 @@
 }
 
 Page::Page(PageClients& pageClients)
-    : m_autoscrollController(AutoscrollController::create(*this))
+    : SettingsDelegate(Settings::create())
+    , m_autoscrollController(AutoscrollController::create(*this))
     , m_chrome(Chrome::create(this, pageClients.chromeClient))
     , m_dragCaretController(DragCaretController::create())
     , m_dragController(DragController::create(this, pageClients.dragClient))
@@ -105,15 +110,14 @@
     , m_contextMenuController(ContextMenuController::create(this, pageClients.contextMenuClient))
     , m_inspectorController(InspectorController::create(this, pageClients.inspectorClient))
     , m_pointerLockController(PointerLockController::create(this))
-    , m_history(adoptPtr(new HistoryController(this)))
-    , m_settings(Settings::create(this))
+    , m_historyController(adoptPtr(new HistoryController(this)))
     , m_progress(ProgressTracker::create())
     , m_undoStack(UndoStack::create())
     , m_backForwardClient(pageClients.backForwardClient)
     , m_editorClient(pageClients.editorClient)
     , m_validationMessageClient(0)
-    , m_sharedWorkerRepositoryClient(0)
     , m_spellCheckerClient(pageClients.spellCheckerClient)
+    , m_storageClient(pageClients.storageClient)
     , m_subframeCount(0)
     , m_openedByDOM(false)
     , m_tabKeyCyclesThroughElements(true)
@@ -127,15 +131,12 @@
 #ifndef NDEBUG
     , m_isPainting(false)
 #endif
-    , m_console(PageConsole::create(this))
+    , m_frameHost(FrameHost::create(*this))
 {
     ASSERT(m_editorClient);
 
-    if (!allPages)
-        allPages = new HashSet<Page*>;
-
-    ASSERT(!allPages->contains(this));
-    allPages->add(this);
+    ASSERT(!allPages().contains(this));
+    allPages().add(this);
 
 #ifndef NDEBUG
     pageCounter.increment();
@@ -146,11 +147,11 @@
 {
     m_mainFrame->setView(0);
     clearPageGroup();
-    allPages->remove(this);
+    allPages().remove(this);
 
     for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        frame->willDetachPage();
-        frame->detachFromPage();
+        frame->willDetachFrameHost();
+        frame->detachFromFrameHost();
     }
 
     m_inspectorController->inspectedPageDestroyed();
@@ -211,8 +212,6 @@
     m_contextMenuController->documentDetached(document);
     if (m_validationMessageClient)
         m_validationMessageClient->documentDetached(*document);
-    if (m_sharedWorkerRepositoryClient)
-        m_sharedWorkerRepositoryClient->documentDetached(document);
 }
 
 bool Page::openedByDOM() const
@@ -251,12 +250,10 @@
 
 void Page::scheduleForcedStyleRecalcForAllPages()
 {
-    if (!allPages)
-        return;
-    HashSet<Page*>::iterator end = allPages->end();
-    for (HashSet<Page*>::iterator it = allPages->begin(); it != end; ++it)
+    HashSet<Page*>::iterator end = allPages().end();
+    for (HashSet<Page*>::iterator it = allPages().begin(); it != end; ++it)
         for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
-            frame->document()->setNeedsStyleRecalc();
+            frame->document()->setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 void Page::setNeedsRecalcStyleInAllFrames()
@@ -265,17 +262,27 @@
         frame->document()->styleResolverChanged(RecalcStyleDeferred);
 }
 
+void Page::setNeedsLayoutInAllFrames()
+{
+    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
+        if (FrameView* view = frame->view()) {
+            view->setNeedsLayout();
+            view->scheduleRelayout();
+        }
+    }
+}
+
 void Page::refreshPlugins(bool reload)
 {
-    if (!allPages)
+    if (allPages().isEmpty())
         return;
 
     PluginData::refresh();
 
     Vector<RefPtr<Frame> > framesNeedingReload;
 
-    HashSet<Page*>::iterator end = allPages->end();
-    for (HashSet<Page*>::iterator it = allPages->begin(); it != end; ++it) {
+    HashSet<Page*>::iterator end = allPages().end();
+    for (HashSet<Page*>::iterator it = allPages().begin(); it != end; ++it) {
         Page* page = *it;
 
         // Clear out the page's plug-in data.
@@ -329,7 +336,7 @@
         return;
 
     m_defersLoading = defers;
-    m_history->setDefersLoading(defers);
+    m_historyController->setDefersLoading(defers);
     for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
         frame->loader().setDefersLoading(defers);
 }
@@ -348,7 +355,7 @@
         m_chrome->client().deviceOrPageScaleFactorChanged();
 
         if (view)
-            view->setViewportConstrainedObjectsNeedLayout();
+            view->viewportConstrainedVisibleContentRectChanged(true, true);
     }
 
     if (view && view->scrollPosition() != origin)
@@ -369,42 +376,24 @@
     }
 }
 
-void Page::setPagination(const Pagination& pagination)
+void Page::allVisitedStateChanged()
 {
-    if (m_pagination == pagination)
-        return;
-
-    m_pagination = pagination;
-
-    setNeedsRecalcStyleInAllFrames();
-}
-
-void Page::allVisitedStateChanged(PageGroup* group)
-{
-    ASSERT(group);
-    if (!allPages)
-        return;
-
-    HashSet<Page*>::iterator pagesEnd = allPages->end();
-    for (HashSet<Page*>::iterator it = allPages->begin(); it != pagesEnd; ++it) {
+    HashSet<Page*>::iterator pagesEnd = allPages().end();
+    for (HashSet<Page*>::iterator it = allPages().begin(); it != pagesEnd; ++it) {
         Page* page = *it;
-        if (page->m_group != group)
+        if (page->m_group != PageGroup::sharedGroup())
             continue;
         for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree().traverseNext())
             frame->document()->visitedLinkState().invalidateStyleForAllLinks();
     }
 }
 
-void Page::visitedStateChanged(PageGroup* group, LinkHash linkHash)
+void Page::visitedStateChanged(LinkHash linkHash)
 {
-    ASSERT(group);
-    if (!allPages)
-        return;
-
-    HashSet<Page*>::iterator pagesEnd = allPages->end();
-    for (HashSet<Page*>::iterator it = allPages->begin(); it != pagesEnd; ++it) {
+    HashSet<Page*>::iterator pagesEnd = allPages().end();
+    for (HashSet<Page*>::iterator it = allPages().begin(); it != pagesEnd; ++it) {
         Page* page = *it;
-        if (page->m_group != group)
+        if (page->m_group != PageGroup::sharedGroup())
             continue;
         for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree().traverseNext())
             frame->document()->visitedLinkState().invalidateStyleForLink(linkHash);
@@ -414,7 +403,7 @@
 StorageNamespace* Page::sessionStorage(bool optionalCreate)
 {
     if (!m_sessionStorage && optionalCreate)
-        m_sessionStorage = StorageNamespace::sessionStorageNamespace(this);
+        m_sessionStorage = m_storageClient->createSessionStorageNamespace();
     return m_sessionStorage.get();
 }
 
@@ -435,12 +424,6 @@
     return m_timerAlignmentInterval;
 }
 
-void Page::dnsPrefetchingStateChanged()
-{
-    for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
-        frame->document()->initDNSPrefetch();
-}
-
 #if !ASSERT_DISABLED
 void Page::checkSubframeCountConsistency() const
 {
@@ -469,7 +452,7 @@
         lifecycleNotifier().notifyPageVisibilityChanged();
 
     if (!isInitialState && m_mainFrame)
-        m_mainFrame->dispatchVisibilityStateChangeEvent();
+        m_mainFrame->didChangeVisibilityState();
 }
 
 PageVisibilityState Page::visibilityState() const
@@ -487,18 +470,70 @@
     m_multisamplingChangedObservers.remove(observer);
 }
 
-void Page::multisamplingChanged()
+void Page::settingsChanged(SettingsDelegate::ChangeType changeType)
 {
-    HashSet<MultisamplingChangedObserver*>::iterator stop = m_multisamplingChangedObservers.end();
-    for (HashSet<MultisamplingChangedObserver*>::iterator it = m_multisamplingChangedObservers.begin(); it != stop; ++it)
-        (*it)->multisamplingChanged(m_settings->openGLMultisamplingEnabled());
+    switch (changeType) {
+    case SettingsDelegate::StyleChange:
+        setNeedsRecalcStyleInAllFrames();
+        break;
+    case SettingsDelegate::ViewportDescriptionChange:
+        if (mainFrame())
+            mainFrame()->document()->updateViewportDescription();
+        break;
+    case SettingsDelegate::MediaTypeChange:
+        m_mainFrame->view()->setMediaType(AtomicString(settings().mediaTypeOverride()));
+        setNeedsRecalcStyleInAllFrames();
+        break;
+    case SettingsDelegate::DNSPrefetchingChange:
+        for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
+            frame->document()->initDNSPrefetch();
+        break;
+    case SettingsDelegate::MultisamplingChange: {
+        HashSet<MultisamplingChangedObserver*>::iterator stop = m_multisamplingChangedObservers.end();
+        for (HashSet<MultisamplingChangedObserver*>::iterator it = m_multisamplingChangedObservers.begin(); it != stop; ++it)
+            (*it)->multisamplingChanged(m_settings->openGLMultisamplingEnabled());
+        break;
+    }
+    case SettingsDelegate::ImageLoadingChange:
+        for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
+            frame->document()->fetcher()->setImagesEnabled(settings().imagesEnabled());
+            frame->document()->fetcher()->setAutoLoadImages(settings().loadsImagesAutomatically());
+        }
+        break;
+    case SettingsDelegate::TextAutosizingChange:
+        // FTA needs both setNeedsRecalcStyle and setNeedsLayout after a setting change.
+        if (RuntimeEnabledFeatures::fastTextAutosizingEnabled()) {
+            setNeedsRecalcStyleInAllFrames();
+        } else {
+            // FIXME: I wonder if this needs to traverse frames like in WebViewImpl::resize, or whether there is only one document per Settings instance?
+            for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
+                TextAutosizer* textAutosizer = frame->document()->textAutosizer();
+                if (textAutosizer)
+                    textAutosizer->recalculateMultipliers();
+            }
+        }
+        // TextAutosizing updates RenderStyle during layout phase (via TextAutosizer::processSubtree).
+        // We should invoke setNeedsLayout here.
+        setNeedsLayoutInAllFrames();
+        break;
+    case SettingsDelegate::ScriptEnableChange:
+        m_inspectorController->scriptsEnabled(settings().scriptEnabled());
+        break;
+    case SettingsDelegate::FontFamilyChange:
+        for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
+            frame->document()->styleEngine()->updateGenericFontFamilySettings();
+        setNeedsRecalcStyleInAllFrames();
+        break;
+    }
 }
 
 void Page::didCommitLoad(Frame* frame)
 {
     lifecycleNotifier().notifyDidCommitLoad(frame);
-    if (m_mainFrame == frame)
+    if (m_mainFrame == frame) {
         useCounter().didCommitLoad();
+        m_inspectorController->didCommitLoadForMainFrame();
+    }
 }
 
 PageLifecycleNotifier& Page::lifecycleNotifier()
@@ -519,6 +554,7 @@
     , inspectorClient(0)
     , backForwardClient(0)
     , spellCheckerClient(0)
+    , storageClient(0)
 {
 }
 
diff --git a/Source/core/page/Page.h b/Source/core/page/Page.h
index db25f98..c043c36 100644
--- a/Source/core/page/Page.h
+++ b/Source/core/page/Page.h
@@ -22,10 +22,10 @@
 #define Page_h
 
 #include "core/dom/ViewportDescription.h"
-#include "core/page/PageVisibilityState.h"
+#include "core/frame/SettingsDelegate.h"
 #include "core/frame/UseCounter.h"
-#include "core/loader/HistoryController.h"
-#include "core/rendering/Pagination.h"
+#include "core/page/HistoryController.h"
+#include "core/page/PageVisibilityState.h"
 #include "platform/LifecycleContext.h"
 #include "platform/Supplementable.h"
 #include "platform/geometry/LayoutRect.h"
@@ -51,13 +51,13 @@
 class EditorClient;
 class FocusController;
 class Frame;
+class FrameHost;
 class FrameSelection;
 class HaltablePlugin;
 class HistoryItem;
 class InspectorClient;
 class InspectorController;
 class Node;
-class PageConsole;
 class PageGroup;
 class PageLifecycleNotifier;
 class PlatformMouseEvent;
@@ -68,11 +68,11 @@
 class RenderBox;
 class RenderObject;
 class RenderTheme;
+class StorageClient;
 class VisibleSelection;
 class ScrollableArea;
 class ScrollingCoordinator;
 class Settings;
-class SharedWorkerRepositoryClient;
 class SpellCheckerClient;
 class StorageNamespace;
 class UndoStack;
@@ -82,7 +82,7 @@
 
 float deviceScaleFactor(Frame*);
 
-class Page : public Supplementable<Page>, public LifecycleContext<Page> {
+class Page FINAL : public Supplementable<Page>, public LifecycleContext<Page>, public SettingsDelegate {
     WTF_MAKE_NONCOPYABLE(Page);
     friend class Settings;
 public:
@@ -102,10 +102,17 @@
         InspectorClient* inspectorClient;
         BackForwardClient* backForwardClient;
         SpellCheckerClient* spellCheckerClient;
+        StorageClient* storageClient;
     };
 
     explicit Page(PageClients&);
-    ~Page();
+    virtual ~Page();
+
+    // This method returns all pages, incl. private ones associated with
+    // inspector overlay, popups, SVGImage, etc.
+    static HashSet<Page*>& allPages();
+
+    FrameHost& frameHost() { return *m_frameHost; }
 
     void setNeedsRecalcStyleInAllFrames();
 
@@ -118,7 +125,7 @@
     SpellCheckerClient& spellCheckerClient() const { return *m_spellCheckerClient; }
     UndoStack& undoStack() const { return *m_undoStack; }
 
-    HistoryController& history() const { return *m_history; }
+    HistoryController& historyController() const { return *m_historyController; }
 
     void setMainFrame(PassRefPtr<Frame>);
     Frame* mainFrame() const { return m_mainFrame.get(); }
@@ -128,6 +135,7 @@
     bool openedByDOM() const;
     void setOpenedByDOM();
 
+    // FIXME: PageGroup should probably just be removed, see comment in PageGroup.h
     enum PageGroupType { PrivatePageGroup, SharedPageGroup };
     void setGroupType(PageGroupType);
     void clearPageGroup();
@@ -152,8 +160,6 @@
     PointerLockController& pointerLockController() const { return *m_pointerLockController; }
     ValidationMessageClient* validationMessageClient() const { return m_validationMessageClient; }
     void setValidationMessageClient(ValidationMessageClient* client) { m_validationMessageClient = client; }
-    SharedWorkerRepositoryClient* sharedWorkerRepositoryClient() { return m_sharedWorkerRepositoryClient; }
-    void setSharedWorkerRepositoryClient(SharedWorkerRepositoryClient* client) { m_sharedWorkerRepositoryClient = client; }
 
     ScrollingCoordinator* scrollingCoordinator();
 
@@ -171,6 +177,9 @@
 
     void unmarkAllTextMatches();
 
+    // DefersLoading is used to delay loads during modal dialogs.
+    // Modal dialogs are supposed to freeze all background processes
+    // in the page, including prevent additional loads from staring/continuing.
     void setDefersLoading(bool);
     bool defersLoading() const { return m_defersLoading; }
 
@@ -180,19 +189,11 @@
     float deviceScaleFactor() const { return m_deviceScaleFactor; }
     void setDeviceScaleFactor(float);
 
-    // Page and FrameView both store a Pagination value. Page::pagination() is set only by API,
-    // and FrameView::pagination() is set only by CSS. Page::pagination() will affect all
-    // FrameViews in the page cache, but FrameView::pagination() only affects the current
-    // FrameView.
-    const Pagination& pagination() const { return m_pagination; }
-    void setPagination(const Pagination&);
-
-    void dnsPrefetchingStateChanged();
-
-    static void allVisitedStateChanged(PageGroup*);
-    static void visitedStateChanged(PageGroup*, LinkHash visitedHash);
+    static void allVisitedStateChanged();
+    static void visitedStateChanged(LinkHash visitedHash);
 
     StorageNamespace* sessionStorage(bool optionalCreate = true);
+    StorageClient& storageClient() const { return *m_storageClient; }
 
     // Don't allow more than a certain number of frames in a page.
     // This seems like a reasonable upper bound, and otherwise mutually
@@ -211,8 +212,6 @@
     bool isPainting() const { return m_isPainting; }
 #endif
 
-    PageConsole& console() { return *m_console; }
-
     double timerAlignmentInterval() const;
 
     class MultisamplingChangedObserver {
@@ -222,7 +221,6 @@
 
     void addMultisamplingChangedObserver(MultisamplingChangedObserver*);
     void removeMultisamplingChangedObserver(MultisamplingChangedObserver*);
-    void multisamplingChanged();
 
     void didCommitLoad(Frame*);
 
@@ -243,6 +241,11 @@
 
     void setTimerAlignmentInterval(double);
 
+    void setNeedsLayoutInAllFrames();
+
+    // SettingsDelegate overrides.
+    virtual void settingsChanged(SettingsDelegate::ChangeType) OVERRIDE;
+
     const OwnPtr<AutoscrollController> m_autoscrollController;
     const OwnPtr<Chrome> m_chrome;
     const OwnPtr<DragCaretController> m_dragCaretController;
@@ -251,10 +254,9 @@
     const OwnPtr<ContextMenuController> m_contextMenuController;
     const OwnPtr<InspectorController> m_inspectorController;
     const OwnPtr<PointerLockController> m_pointerLockController;
-    RefPtr<ScrollingCoordinator> m_scrollingCoordinator;
+    OwnPtr<ScrollingCoordinator> m_scrollingCoordinator;
 
-    const OwnPtr<HistoryController> m_history;
-    const OwnPtr<Settings> m_settings;
+    const OwnPtr<HistoryController> m_historyController;
     const OwnPtr<ProgressTracker> m_progress;
     const OwnPtr<UndoStack> m_undoStack;
 
@@ -265,8 +267,8 @@
     BackForwardClient* m_backForwardClient;
     EditorClient* const m_editorClient;
     ValidationMessageClient* m_validationMessageClient;
-    SharedWorkerRepositoryClient* m_sharedWorkerRepositoryClient;
     SpellCheckerClient* const m_spellCheckerClient;
+    StorageClient* m_storageClient;
 
     UseCounter m_useCounter;
 
@@ -279,8 +281,6 @@
     float m_pageScaleFactor;
     float m_deviceScaleFactor;
 
-    Pagination m_pagination;
-
     RefPtr<PageGroup> m_group;
 
     OwnPtr<StorageNamespace> m_sessionStorage;
@@ -295,9 +295,11 @@
     bool m_isPainting;
 #endif
 
-    const OwnPtr<PageConsole> m_console;
-
     HashSet<MultisamplingChangedObserver*> m_multisamplingChangedObservers;
+
+    // A pointer to all the interfaces provided to in-process Frames for this Page.
+    // FIXME: Most of the members of Page should move onto FrameHost.
+    OwnPtr<FrameHost> m_frameHost;
 };
 
 } // namespace WebCore
diff --git a/Source/core/page/PageGroup.cpp b/Source/core/page/PageGroup.cpp
index b4a7271..2893355 100644
--- a/Source/core/page/PageGroup.cpp
+++ b/Source/core/page/PageGroup.cpp
@@ -26,8 +26,6 @@
 #include "config.h"
 #include "core/page/PageGroup.h"
 
-#include "core/dom/Document.h"
-#include "core/dom/StyleEngine.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
 #include "wtf/StdLibExtras.h"
@@ -40,7 +38,6 @@
 
 PageGroup::~PageGroup()
 {
-    removeInjectedStyleSheets();
 }
 
 PageGroup* PageGroup::sharedGroup()
@@ -63,26 +60,4 @@
     m_pages.remove(page);
 }
 
-void PageGroup::injectStyleSheet(const String& source, const Vector<String>& whitelist, StyleInjectionTarget injectIn)
-{
-    m_injectedStyleSheets.append(adoptPtr(new InjectedStyleSheet(source, whitelist, injectIn)));
-    invalidatedInjectedStyleSheetCacheInAllFrames();
-}
-
-void PageGroup::removeInjectedStyleSheets()
-{
-    m_injectedStyleSheets.clear();
-    invalidatedInjectedStyleSheetCacheInAllFrames();
-}
-
-void PageGroup::invalidatedInjectedStyleSheetCacheInAllFrames()
-{
-    // Clear our cached sheets and have them just reparse.
-    HashSet<Page*>::const_iterator end = m_pages.end();
-    for (HashSet<Page*>::const_iterator it = m_pages.begin(); it != end; ++it) {
-        for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
-            frame->document()->styleEngine()->invalidateInjectedStyleSheetCache();
-    }
-}
-
 } // namespace WebCore
diff --git a/Source/core/page/PageGroup.h b/Source/core/page/PageGroup.h
index 65b24a1..4ce3bc9 100644
--- a/Source/core/page/PageGroup.h
+++ b/Source/core/page/PageGroup.h
@@ -26,7 +26,7 @@
 #ifndef PageGroup_h
 #define PageGroup_h
 
-#include "core/page/InjectedStyleSheet.h"
+#include "core/page/InjectedStyleSheets.h"
 #include "platform/Supplementable.h"
 #include "wtf/HashSet.h"
 #include "wtf/Noncopyable.h"
@@ -35,10 +35,12 @@
 
 namespace WebCore {
 
-    class KURL;
     class Page;
-    class SecurityOrigin;
 
+    // FIXME: This is really more of a "Settings Group" than a Page Group.
+    // It has nothing to do with Page. There is one shared PageGroup
+    // in the renderer process, which all normal Pages belong to. There are also
+    // additional private PageGroups for SVGImage, Inspector Overlay, etc.
     class PageGroup : public Supplementable<PageGroup>, public RefCounted<PageGroup> {
         WTF_MAKE_NONCOPYABLE(PageGroup); WTF_MAKE_FAST_ALLOCATED;
     public:
@@ -52,18 +54,10 @@
         void addPage(Page*);
         void removePage(Page*);
 
-        void injectStyleSheet(const String& source, const Vector<String>& whitelist, StyleInjectionTarget);
-        void removeInjectedStyleSheets();
-
-        const InjectedStyleSheetVector& injectedStyleSheets() const { return m_injectedStyleSheets; }
-
     private:
         PageGroup();
 
-        void invalidatedInjectedStyleSheetCacheInAllFrames();
-
         HashSet<Page*> m_pages;
-        InjectedStyleSheetVector m_injectedStyleSheets;
     };
 
 } // namespace WebCore
diff --git a/Source/core/page/PageLifecycleNotifier.h b/Source/core/page/PageLifecycleNotifier.h
index 5514101..c910e29 100644
--- a/Source/core/page/PageLifecycleNotifier.h
+++ b/Source/core/page/PageLifecycleNotifier.h
@@ -36,7 +36,7 @@
 class Page;
 class Frame;
 
-class PageLifecycleNotifier : public LifecycleNotifier<Page> {
+class PageLifecycleNotifier FINAL : public LifecycleNotifier<Page> {
 public:
     static PassOwnPtr<PageLifecycleNotifier> create(Page*);
 
diff --git a/Source/core/page/PagePopupClient.cpp b/Source/core/page/PagePopupClient.cpp
index f3e792f..c5e14a2 100644
--- a/Source/core/page/PagePopupClient.cpp
+++ b/Source/core/page/PagePopupClient.cpp
@@ -35,11 +35,11 @@
 
 namespace WebCore {
 
-#define addLiteral(literal, writer)    writer.addData(literal, sizeof(literal) - 1)
+#define addLiteral(literal, data)    data->append(literal, sizeof(literal) - 1)
 
-void PagePopupClient::addJavaScriptString(const String& str, DocumentWriter& writer)
+void PagePopupClient::addJavaScriptString(const String& str, SharedBuffer* data)
 {
-    addLiteral("\"", writer);
+    addLiteral("\"", data);
     StringBuilder builder;
     builder.reserveCapacity(str.length());
     for (unsigned i = 0; i < str.length(); ++i) {
@@ -47,66 +47,66 @@
             builder.append('\\');
         builder.append(str[i]);
     }
-    addString(builder.toString(), writer);
-    addLiteral("\"", writer);
+    addString(builder.toString(), data);
+    addLiteral("\"", data);
 }
 
-void PagePopupClient::addProperty(const char* name, const String& value, DocumentWriter& writer)
+void PagePopupClient::addProperty(const char* name, const String& value, SharedBuffer* data)
 {
-    writer.addData(name, strlen(name));
-    addLiteral(": ", writer);
-    addJavaScriptString(value, writer);
-    addLiteral(",\n", writer);
+    data->append(name, strlen(name));
+    addLiteral(": ", data);
+    addJavaScriptString(value, data);
+    addLiteral(",\n", data);
 }
 
-void PagePopupClient::addProperty(const char* name, int value, DocumentWriter& writer)
+void PagePopupClient::addProperty(const char* name, int value, SharedBuffer* data)
 {
-    writer.addData(name, strlen(name));
-    addLiteral(": ", writer);
-    addString(String::number(value), writer);
-    addLiteral(",\n", writer);
+    data->append(name, strlen(name));
+    addLiteral(": ", data);
+    addString(String::number(value), data);
+    addLiteral(",\n", data);
 }
 
-void PagePopupClient::addProperty(const char* name, unsigned value, DocumentWriter& writer)
+void PagePopupClient::addProperty(const char* name, unsigned value, SharedBuffer* data)
 {
-    writer.addData(name, strlen(name));
-    addLiteral(": ", writer);
-    addString(String::number(value), writer);
-    addLiteral(",\n", writer);
+    data->append(name, strlen(name));
+    addLiteral(": ", data);
+    addString(String::number(value), data);
+    addLiteral(",\n", data);
 }
 
-void PagePopupClient::addProperty(const char* name, bool value, DocumentWriter& writer)
+void PagePopupClient::addProperty(const char* name, bool value, SharedBuffer* data)
 {
-    writer.addData(name, strlen(name));
-    addLiteral(": ", writer);
+    data->append(name, strlen(name));
+    addLiteral(": ", data);
     if (value)
-        addLiteral("true", writer);
+        addLiteral("true", data);
     else
-        addLiteral("false", writer);
-    addLiteral(",\n", writer);
+        addLiteral("false", data);
+    addLiteral(",\n", data);
 }
 
-void PagePopupClient::addProperty(const char* name, const Vector<String>& values, DocumentWriter& writer)
+void PagePopupClient::addProperty(const char* name, const Vector<String>& values, SharedBuffer* data)
 {
-    writer.addData(name, strlen(name));
-    addLiteral(": [", writer);
+    data->append(name, strlen(name));
+    addLiteral(": [", data);
     for (unsigned i = 0; i < values.size(); ++i) {
         if (i)
-            addLiteral(",", writer);
-        addJavaScriptString(values[i], writer);
+            addLiteral(",", data);
+        addJavaScriptString(values[i], data);
     }
-    addLiteral("],\n", writer);
+    addLiteral("],\n", data);
 }
 
-void PagePopupClient::addProperty(const char* name, const IntRect& rect, DocumentWriter& writer)
+void PagePopupClient::addProperty(const char* name, const IntRect& rect, SharedBuffer* data)
 {
-    writer.addData(name, strlen(name));
-    addLiteral(": {", writer);
-    addProperty("x", rect.x(), writer);
-    addProperty("y", rect.y(), writer);
-    addProperty("width", rect.width(), writer);
-    addProperty("height", rect.height(), writer);
-    addLiteral("},\n", writer);
+    data->append(name, strlen(name));
+    addLiteral(": {", data);
+    addProperty("x", rect.x(), data);
+    addProperty("y", rect.y(), data);
+    addProperty("width", rect.width(), data);
+    addProperty("height", rect.height(), data);
+    addLiteral("},\n", data);
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/PagePopupClient.h b/Source/core/page/PagePopupClient.h
index 812e973..4f86eb6 100644
--- a/Source/core/page/PagePopupClient.h
+++ b/Source/core/page/PagePopupClient.h
@@ -31,26 +31,25 @@
 #ifndef PagePopupClient_h
 #define PagePopupClient_h
 
-#include "core/loader/DocumentWriter.h"
+#include "platform/SharedBuffer.h"
 #include "platform/geometry/IntRect.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-class DocumentWriter;
 class Locale;
 
 class PagePopupClient {
 public:
     virtual IntSize contentSize() = 0;
 
-    // Provide an HTML source through the specified DocumentWriter. The HTML
+    // Provide an HTML source to the specified buffer. The HTML
     // source is rendered in a PagePopup.
     // The content HTML supports:
     //  - No <select> popups
     //  - window.setValueAndClosePopup(number, string).
-    virtual void writeDocument(DocumentWriter&) = 0;
+    virtual void writeDocument(SharedBuffer*) = 0;
 
     // Returns a Locale object associated to the client.
     virtual Locale& locale() = 0;
@@ -71,20 +70,20 @@
     virtual ~PagePopupClient() { }
 
     // Helper functions to be used in PagePopupClient::writeDocument().
-    static void addString(const String&, DocumentWriter&);
-    static void addJavaScriptString(const String&, DocumentWriter&);
-    static void addProperty(const char* name, const String& value, DocumentWriter&);
-    static void addProperty(const char* name, int value, DocumentWriter&);
-    static void addProperty(const char* name, unsigned value, DocumentWriter&);
-    static void addProperty(const char* name, bool value, DocumentWriter&);
-    static void addProperty(const char* name, const Vector<String>& values, DocumentWriter&);
-    static void addProperty(const char* name, const IntRect&, DocumentWriter&);
+    static void addString(const String&, SharedBuffer*);
+    static void addJavaScriptString(const String&, SharedBuffer*);
+    static void addProperty(const char* name, const String& value, SharedBuffer*);
+    static void addProperty(const char* name, int value, SharedBuffer*);
+    static void addProperty(const char* name, unsigned value, SharedBuffer*);
+    static void addProperty(const char* name, bool value, SharedBuffer*);
+    static void addProperty(const char* name, const Vector<String>& values, SharedBuffer*);
+    static void addProperty(const char* name, const IntRect&, SharedBuffer*);
 };
 
-inline void PagePopupClient::addString(const String& str, DocumentWriter& writer)
+inline void PagePopupClient::addString(const String& str, SharedBuffer* data)
 {
     CString str8 = str.utf8();
-    writer.addData(str8.data(), str8.length());
+    data->append(str8.data(), str8.length());
 }
 
 }
diff --git a/Source/core/page/PageSerializer.cpp b/Source/core/page/PageSerializer.cpp
index d41f871..ccf0a28 100644
--- a/Source/core/page/PageSerializer.cpp
+++ b/Source/core/page/PageSerializer.cpp
@@ -48,13 +48,13 @@
 #include "core/editing/MarkupAccumulator.h"
 #include "core/fetch/FontResource.h"
 #include "core/fetch/ImageResource.h"
+#include "core/frame/Frame.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLStyleElement.h"
-#include "core/html/parser/HTMLMetaCharsetParser.h"
-#include "core/frame/Frame.h"
+#include "core/html/parser/HTMLParserIdioms.h"
 #include "core/page/Page.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/style/StyleFetchedImage.h"
@@ -68,29 +68,29 @@
 
 namespace WebCore {
 
-static bool isCharsetSpecifyingNode(Node* node)
+static bool isCharsetSpecifyingNode(const Node& node)
 {
-    if (!node->isHTMLElement())
+    if (!node.isHTMLElement())
         return false;
 
-    HTMLElement* element = toHTMLElement(node);
-    if (!element->hasTagName(HTMLNames::metaTag))
+    const HTMLElement& element = toHTMLElement(node);
+    if (!element.hasTagName(HTMLNames::metaTag))
         return false;
-    HTMLMetaCharsetParser::AttributeList attributes;
-    if (element->hasAttributes()) {
-        for (unsigned i = 0; i < element->attributeCount(); ++i) {
-            const Attribute* attribute = element->attributeItem(i);
+    HTMLAttributeList attributes;
+    if (element.hasAttributes()) {
+        for (unsigned i = 0; i < element.attributeCount(); ++i) {
+            const Attribute* attribute = element.attributeItem(i);
             // FIXME: We should deal appropriately with the attribute if they have a namespace.
-            attributes.append(std::make_pair(attribute->name().toString(), attribute->value().string()));
+            attributes.append(std::make_pair(attribute->name().localName(), attribute->value().string()));
         }
     }
-    WTF::TextEncoding textEncoding = HTMLMetaCharsetParser::encodingFromMetaAttributes(attributes);
+    WTF::TextEncoding textEncoding = encodingFromMetaAttributes(attributes);
     return textEncoding.isValid();
 }
 
-static bool shouldIgnoreElement(Element* element)
+static bool shouldIgnoreElement(const Element& element)
 {
-    return element->hasTagName(HTMLNames::scriptTag) || element->hasTagName(HTMLNames::noscriptTag) || isCharsetSpecifyingNode(element);
+    return element.hasTagName(HTMLNames::scriptTag) || element.hasTagName(HTMLNames::noscriptTag) || isCharsetSpecifyingNode(element);
 }
 
 static const QualifiedName& frameOwnerURLAttributeName(const HTMLFrameOwnerElement& frameOwner)
@@ -99,23 +99,23 @@
     return frameOwner.hasTagName(HTMLNames::objectTag) ? HTMLNames::dataAttr : HTMLNames::srcAttr;
 }
 
-class SerializerMarkupAccumulator : public WebCore::MarkupAccumulator {
+class SerializerMarkupAccumulator FINAL : public MarkupAccumulator {
 public:
-    SerializerMarkupAccumulator(PageSerializer*, Document*, Vector<Node*>*);
+    SerializerMarkupAccumulator(PageSerializer*, const Document&, Vector<Node*>*);
     virtual ~SerializerMarkupAccumulator();
 
 protected:
-    virtual void appendText(StringBuilder& out, Text*);
-    virtual void appendElement(StringBuilder& out, Element*, Namespaces*);
-    virtual void appendCustomAttributes(StringBuilder& out, Element*, Namespaces*);
-    virtual void appendEndTag(Node*);
+    virtual void appendText(StringBuilder& out, Text&) OVERRIDE;
+    virtual void appendElement(StringBuilder& out, Element&, Namespaces*) OVERRIDE;
+    virtual void appendCustomAttributes(StringBuilder& out, const Element&, Namespaces*) OVERRIDE;
+    virtual void appendEndTag(const Node&) OVERRIDE;
 
 private:
     PageSerializer* m_serializer;
-    Document* m_document;
+    const Document& m_document;
 };
 
-SerializerMarkupAccumulator::SerializerMarkupAccumulator(PageSerializer* serializer, Document* document, Vector<Node*>* nodes)
+SerializerMarkupAccumulator::SerializerMarkupAccumulator(PageSerializer* serializer, const Document& document, Vector<Node*>* nodes)
     : MarkupAccumulator(nodes, ResolveAllURLs)
     , m_serializer(serializer)
     , m_document(document)
@@ -126,34 +126,34 @@
 {
 }
 
-void SerializerMarkupAccumulator::appendText(StringBuilder& out, Text* text)
+void SerializerMarkupAccumulator::appendText(StringBuilder& out, Text& text)
 {
-    Element* parent = text->parentElement();
-    if (parent && !shouldIgnoreElement(parent))
+    Element* parent = text.parentElement();
+    if (parent && !shouldIgnoreElement(*parent))
         MarkupAccumulator::appendText(out, text);
 }
 
-void SerializerMarkupAccumulator::appendElement(StringBuilder& out, Element* element, Namespaces* namespaces)
+void SerializerMarkupAccumulator::appendElement(StringBuilder& out, Element& element, Namespaces* namespaces)
 {
     if (!shouldIgnoreElement(element))
         MarkupAccumulator::appendElement(out, element, namespaces);
 
-    if (element->hasTagName(HTMLNames::headTag)) {
+    if (element.hasTagName(HTMLNames::headTag)) {
         out.append("<meta charset=\"");
-        out.append(m_document->charset());
+        out.append(m_document.charset());
         out.append("\">");
     }
 
     // FIXME: For object (plugins) tags and video tag we could replace them by an image of their current contents.
 }
 
-void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& out, Element* element, Namespaces* namespaces)
+void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& out, const Element& element, Namespaces* namespaces)
 {
-    if (!element->isFrameOwnerElement())
+    if (!element.isFrameOwnerElement())
         return;
 
-    HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(element);
-    Frame* frame = frameOwner->contentFrame();
+    const HTMLFrameOwnerElement& frameOwner = toHTMLFrameOwnerElement(element);
+    Frame* frame = frameOwner.contentFrame();
     if (!frame)
         return;
 
@@ -163,12 +163,12 @@
 
     // We need to give a fake location to blank frames so they can be referenced by the serialized frame.
     url = m_serializer->urlForBlankFrame(frame);
-    appendAttribute(out, element, Attribute(frameOwnerURLAttributeName(*frameOwner), url.string()), namespaces);
+    appendAttribute(out, element, Attribute(frameOwnerURLAttributeName(frameOwner), AtomicString(url.string())), namespaces);
 }
 
-void SerializerMarkupAccumulator::appendEndTag(Node* node)
+void SerializerMarkupAccumulator::appendEndTag(const Node& node)
 {
-    if (node->isElementNode() && !shouldIgnoreElement(toElement(node)))
+    if (node.isElementNode() && !shouldIgnoreElement(toElement(node)))
         MarkupAccumulator::appendEndTag(node);
 }
 
@@ -185,8 +185,9 @@
 
 void PageSerializer::serializeFrame(Frame* frame)
 {
-    Document* document = frame->document();
-    KURL url = document->url();
+    ASSERT(frame->document());
+    Document& document = *frame->document();
+    KURL url = document.url();
     if (!url.isValid() || url.isBlankURL()) {
         // For blank frames we generate a fake URL so they can be referenced by their containing frame.
         url = urlForBlankFrame(frame);
@@ -199,51 +200,52 @@
         return;
     }
 
-    Vector<Node*> nodes;
-    SerializerMarkupAccumulator accumulator(this, document, &nodes);
-    WTF::TextEncoding textEncoding(document->charset());
-    CString data;
+    WTF::TextEncoding textEncoding(document.charset());
     if (!textEncoding.isValid()) {
         // FIXME: iframes used as images trigger this. We should deal with them correctly.
         return;
     }
+
+    Vector<Node*> serializedNodes;
+    SerializerMarkupAccumulator accumulator(this, document, &serializedNodes);
     String text = accumulator.serializeNodes(document, IncludeNode);
     CString frameHTML = textEncoding.normalizeAndEncode(text, WTF::EntitiesForUnencodables);
-    m_resources->append(SerializedResource(url, document->suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length())));
+    m_resources->append(SerializedResource(url, document.suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length())));
     m_resourceURLs.add(url);
 
-    for (Vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) {
-        Node* node = *iter;
-        if (!node->isElementNode())
+    for (Vector<Node*>::iterator iter = serializedNodes.begin(); iter != serializedNodes.end(); ++iter) {
+        ASSERT(*iter);
+        Node& node = **iter;
+        if (!node.isElementNode())
             continue;
 
-        Element* element = toElement(node);
+        Element& element = toElement(node);
         // We have to process in-line style as it might contain some resources (typically background images).
-        if (element->isStyledElement())
-            retrieveResourcesForProperties(element->inlineStyle(), document);
+        if (element.isStyledElement())
+            retrieveResourcesForProperties(element.inlineStyle(), document);
 
-        if (element->hasTagName(HTMLNames::imgTag)) {
-            HTMLImageElement* imageElement = toHTMLImageElement(element);
-            KURL url = document->completeURL(imageElement->getAttribute(HTMLNames::srcAttr));
-            ImageResource* cachedImage = imageElement->cachedImage();
-            addImageToResources(cachedImage, imageElement->renderer(), url);
-        } else if (element->hasTagName(HTMLNames::inputTag)) {
-            HTMLInputElement* inputElement = toHTMLInputElement(element);
-            if (inputElement->isImageButton() && inputElement->hasImageLoader()) {
-                KURL url = inputElement->src();
-                ImageResource* cachedImage = inputElement->imageLoader()->image();
-                addImageToResources(cachedImage, inputElement->renderer(), url);
+        if (element.hasTagName(HTMLNames::imgTag)) {
+            HTMLImageElement& imageElement = toHTMLImageElement(element);
+            KURL url = document.completeURL(imageElement.getAttribute(HTMLNames::srcAttr));
+            ImageResource* cachedImage = imageElement.cachedImage();
+            addImageToResources(cachedImage, imageElement.renderer(), url);
+        } else if (element.hasTagName(HTMLNames::inputTag)) {
+            HTMLInputElement& inputElement = toHTMLInputElement(element);
+            if (inputElement.isImageButton() && inputElement.hasImageLoader()) {
+                KURL url = inputElement.src();
+                ImageResource* cachedImage = inputElement.imageLoader()->image();
+                addImageToResources(cachedImage, inputElement.renderer(), url);
             }
-        } else if (element->hasTagName(HTMLNames::linkTag)) {
-            HTMLLinkElement* linkElement = toHTMLLinkElement(element);
-            if (CSSStyleSheet* sheet = linkElement->sheet()) {
-                KURL url = document->completeURL(linkElement->getAttribute(HTMLNames::hrefAttr));
+        } else if (element.hasTagName(HTMLNames::linkTag)) {
+            HTMLLinkElement& linkElement = toHTMLLinkElement(element);
+            if (CSSStyleSheet* sheet = linkElement.sheet()) {
+                KURL url = document.completeURL(linkElement.getAttribute(HTMLNames::hrefAttr));
                 serializeCSSStyleSheet(sheet, url);
                 ASSERT(m_resourceURLs.contains(url));
             }
-        } else if (element->hasTagName(HTMLNames::styleTag)) {
-            HTMLStyleElement* styleElement = toHTMLStyleElement(element);
-            if (CSSStyleSheet* sheet = styleElement->sheet())
+        } else if (element.hasTagName(HTMLNames::styleTag)) {
+            HTMLStyleElement& styleElement = toHTMLStyleElement(element);
+            if (CSSStyleSheet* sheet = styleElement.sheet())
                 serializeCSSStyleSheet(sheet, KURL());
         }
     }
@@ -263,11 +265,12 @@
             if (i < styleSheet->length() - 1)
                 cssText.append("\n\n");
         }
-        Document* document = styleSheet->ownerDocument();
+        ASSERT(styleSheet->ownerDocument());
+        Document& document = *styleSheet->ownerDocument();
         // Some rules have resources associated with them that we need to retrieve.
         if (rule->type() == CSSRule::IMPORT_RULE) {
             CSSImportRule* importRule = toCSSImportRule(rule);
-            KURL importURL = document->completeURL(importRule->href());
+            KURL importURL = document.completeURL(importRule->href());
             if (m_resourceURLs.contains(importURL))
                 continue;
             serializeCSSStyleSheet(importRule->styleSheet(), importURL);
@@ -331,7 +334,7 @@
     addToResources(font, data, font->url());
 }
 
-void PageSerializer::retrieveResourcesForProperties(const StylePropertySet* styleDeclaration, Document* document)
+void PageSerializer::retrieveResourcesForProperties(const StylePropertySet* styleDeclaration, Document& document)
 {
     if (!styleDeclaration)
         return;
@@ -346,7 +349,7 @@
     }
 }
 
-void PageSerializer::retrieveResourcesForCSSValue(CSSValue* cssValue, Document* document)
+void PageSerializer::retrieveResourcesForCSSValue(CSSValue* cssValue, Document& document)
 {
     if (cssValue->isImageValue()) {
         CSSImageValue* imageValue = toCSSImageValue(cssValue);
@@ -362,7 +365,7 @@
             return;
         }
 
-        addFontToResources(fontFaceSrcValue->fetch(document));
+        addFontToResources(fontFaceSrcValue->fetch(&document));
     } else if (cssValue->isValueList()) {
         CSSValueList* cssValueList = toCSSValueList(cssValue);
         for (unsigned i = 0; i < cssValueList->length(); i++)
diff --git a/Source/core/page/PageSerializer.h b/Source/core/page/PageSerializer.h
index 745af7e..05b5f32 100644
--- a/Source/core/page/PageSerializer.h
+++ b/Source/core/page/PageSerializer.h
@@ -81,8 +81,8 @@
     void addImageToResources(ImageResource*, RenderObject*, const KURL&);
     void addFontToResources(FontResource*);
 
-    void retrieveResourcesForProperties(const StylePropertySet*, Document*);
-    void retrieveResourcesForCSSValue(CSSValue*, Document*);
+    void retrieveResourcesForProperties(const StylePropertySet*, Document&);
+    void retrieveResourcesForCSSValue(CSSValue*, Document&);
 
     Vector<SerializedResource>* m_resources;
     ListHashSet<KURL> m_resourceURLs;
diff --git a/Source/core/page/PointerLockController.cpp b/Source/core/page/PointerLockController.cpp
index d83f7b4..9866aa8 100644
--- a/Source/core/page/PointerLockController.cpp
+++ b/Source/core/page/PointerLockController.cpp
@@ -37,6 +37,7 @@
 
 PointerLockController::PointerLockController(Page* page)
     : m_page(page)
+    , m_lockPending(false)
 {
 }
 
diff --git a/Source/core/page/PrintContext.cpp b/Source/core/page/PrintContext.cpp
index 61a4f8a..cded884 100644
--- a/Source/core/page/PrintContext.cpp
+++ b/Source/core/page/PrintContext.cpp
@@ -168,7 +168,7 @@
     FloatSize minLayoutSize = m_frame->resizePageRectsKeepingRatio(originalPageSize, FloatSize(width * printingMinimumShrinkFactor, height * printingMinimumShrinkFactor));
 
     // This changes layout, so callers need to make sure that they don't paint to screen while in printing mode.
-    m_frame->setPrinting(true, minLayoutSize, originalPageSize, printingMaximumShrinkFactor / printingMinimumShrinkFactor, AdjustViewSize);
+    m_frame->setPrinting(true, minLayoutSize, originalPageSize, printingMaximumShrinkFactor / printingMinimumShrinkFactor);
 }
 
 float PrintContext::computeAutomaticScaleFactor(const FloatSize& availablePaperSize)
@@ -219,7 +219,7 @@
 {
     ASSERT(m_isPrinting);
     m_isPrinting = false;
-    m_frame->setPrinting(false, FloatSize(), FloatSize(), 0, AdjustViewSize);
+    m_frame->setPrinting(false, FloatSize(), FloatSize(), 0);
     m_linkedDestinations.clear();
     m_linkedDestinationsValid = false;
 }
diff --git a/Source/core/page/Selection.idl b/Source/core/page/Selection.idl
index 8f03f8e..9c5b2d7 100644
--- a/Source/core/page/Selection.idl
+++ b/Source/core/page/Selection.idl
@@ -76,7 +76,7 @@
                           [Default=Undefined] optional long baseOffset,
                           [Default=Undefined] optional Node extentNode,
                           [Default=Undefined] optional long extentOffset);
-    [RaisesException] void setPosition([Default=Undefined] optional Node node,
+    [RaisesException, ImplementedAs=collapse] void setPosition([Default=Undefined] optional Node node,
                      [Default=Undefined] optional long offset);
 
     // IE extentions
diff --git a/Source/core/page/Settings.cpp b/Source/core/page/Settings.cpp
deleted file mode 100644
index 4249b5e..0000000
--- a/Source/core/page/Settings.cpp
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-#include "core/page/Settings.h"
-
-#include <limits>
-#include "core/dom/Document.h"
-#include "core/fetch/ResourceFetcher.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Chrome.h"
-#include "core/frame/Frame.h"
-#include "core/page/FrameTree.h"
-#include "core/frame/FrameView.h"
-#include "core/page/Page.h"
-#include "core/rendering/TextAutosizer.h"
-#include "platform/scroll/ScrollbarTheme.h"
-
-using namespace std;
-
-namespace WebCore {
-
-static void setImageLoadingSettings(Page* page)
-{
-    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        frame->document()->fetcher()->setImagesEnabled(page->settings().areImagesEnabled());
-        frame->document()->fetcher()->setAutoLoadImages(page->settings().loadsImagesAutomatically());
-    }
-}
-
-// NOTEs
-//  1) EditingMacBehavior comprises builds on Mac;
-//  2) EditingWindowsBehavior comprises builds on Windows;
-//  3) EditingUnixBehavior comprises all unix-based systems, but Darwin/MacOS/Android (and then abusing the terminology);
-//  4) EditingAndroidBehavior comprises Android builds.
-// 99) MacEditingBehavior is used a fallback.
-static EditingBehaviorType editingBehaviorTypeForPlatform()
-{
-    return
-#if OS(MACOSX)
-    EditingMacBehavior
-#elif OS(WIN)
-    EditingWindowsBehavior
-#elif OS(ANDROID)
-    EditingAndroidBehavior
-#else // Rest of the UNIX-like systems
-    EditingUnixBehavior
-#endif
-    ;
-}
-
-static const bool defaultUnifiedTextCheckerEnabled = false;
-#if OS(MACOSX)
-static const bool defaultSmartInsertDeleteEnabled = true;
-#else
-static const bool defaultSmartInsertDeleteEnabled = false;
-#endif
-#if OS(WIN)
-static const bool defaultSelectTrailingWhitespaceEnabled = true;
-#else
-static const bool defaultSelectTrailingWhitespaceEnabled = false;
-#endif
-
-Settings::Settings(Page* page)
-    : m_page(0)
-    , m_mediaTypeOverride("screen")
-    , m_accessibilityFontScaleFactor(1)
-    , m_deviceScaleAdjustment(1.0f)
-#if HACK_FORCE_TEXT_AUTOSIZING_ON_DESKTOP
-    , m_textAutosizingWindowSizeOverride(320, 480)
-    , m_textAutosizingEnabled(true)
-#else
-    , m_textAutosizingEnabled(false)
-#endif
-    , m_useWideViewport(true)
-    , m_loadWithOverviewMode(true)
-    SETTINGS_INITIALIZER_LIST
-    , m_isJavaEnabled(false)
-    , m_loadsImagesAutomatically(false)
-    , m_areImagesEnabled(true)
-    , m_arePluginsEnabled(false)
-    , m_isScriptEnabled(false)
-    , m_dnsPrefetchingEnabled(false)
-    , m_touchEventEmulationEnabled(false)
-    , m_openGLMultisamplingEnabled(false)
-    , m_viewportEnabled(false)
-    , m_viewportMetaEnabled(false)
-    , m_compositorDrivenAcceleratedScrollingEnabled(false)
-    , m_layerSquashingEnabled(false)
-    , m_setImageLoadingSettingsTimer(this, &Settings::imageLoadingSettingsTimerFired)
-{
-    m_page = page; // Page is not yet fully initialized wen constructing Settings, so keeping m_page null over initializeDefaultFontFamilies() call.
-}
-
-PassOwnPtr<Settings> Settings::create(Page* page)
-{
-    return adoptPtr(new Settings(page));
-}
-
-SETTINGS_SETTER_BODIES
-
-void Settings::setTextAutosizingEnabled(bool textAutosizingEnabled)
-{
-    if (m_textAutosizingEnabled == textAutosizingEnabled)
-        return;
-
-    m_textAutosizingEnabled = textAutosizingEnabled;
-    m_page->setNeedsRecalcStyleInAllFrames();
-}
-
-bool Settings::textAutosizingEnabled() const
-{
-    return InspectorInstrumentation::overrideTextAutosizing(m_page, m_textAutosizingEnabled);
-}
-
-void Settings::setTextAutosizingWindowSizeOverride(const IntSize& textAutosizingWindowSizeOverride)
-{
-    if (m_textAutosizingWindowSizeOverride == textAutosizingWindowSizeOverride)
-        return;
-
-    m_textAutosizingWindowSizeOverride = textAutosizingWindowSizeOverride;
-    m_page->setNeedsRecalcStyleInAllFrames();
-}
-
-void Settings::setUseWideViewport(bool useWideViewport)
-{
-    if (m_useWideViewport == useWideViewport)
-        return;
-
-    m_useWideViewport = useWideViewport;
-    if (m_page->mainFrame())
-        m_page->chrome().dispatchViewportPropertiesDidChange(m_page->mainFrame()->document()->viewportDescription());
-}
-
-void Settings::setLoadWithOverviewMode(bool loadWithOverviewMode)
-{
-    if (m_loadWithOverviewMode == loadWithOverviewMode)
-        return;
-
-    m_loadWithOverviewMode = loadWithOverviewMode;
-    if (m_page->mainFrame())
-        m_page->chrome().dispatchViewportPropertiesDidChange(m_page->mainFrame()->document()->viewportDescription());
-}
-
-void Settings::recalculateTextAutosizingMultipliers()
-{
-    // FIXME: I wonder if this needs to traverse frames like in WebViewImpl::resize, or whether there is only one document per Settings instance?
-    for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        TextAutosizer* textAutosizer = frame->document()->textAutosizer();
-        if (textAutosizer)
-            textAutosizer->recalculateMultipliers();
-    }
-
-    m_page->setNeedsRecalcStyleInAllFrames();
-}
-
-void Settings::setAccessibilityFontScaleFactor(float fontScaleFactor)
-{
-    m_accessibilityFontScaleFactor = fontScaleFactor;
-    recalculateTextAutosizingMultipliers();
-}
-
-void Settings::setDeviceScaleAdjustment(float deviceScaleAdjustment)
-{
-    m_deviceScaleAdjustment = deviceScaleAdjustment;
-    recalculateTextAutosizingMultipliers();
-}
-
-float Settings::deviceScaleAdjustment() const
-{
-    return InspectorInstrumentation::overrideFontScaleFactor(m_page, m_deviceScaleAdjustment);
-}
-
-void Settings::setMediaTypeOverride(const String& mediaTypeOverride)
-{
-    if (m_mediaTypeOverride == mediaTypeOverride)
-        return;
-
-    m_mediaTypeOverride = mediaTypeOverride;
-
-    Frame* mainFrame = m_page->mainFrame();
-    ASSERT(mainFrame);
-    FrameView* view = mainFrame->view();
-    ASSERT(view);
-
-    view->setMediaType(mediaTypeOverride);
-    m_page->setNeedsRecalcStyleInAllFrames();
-}
-
-void Settings::setLoadsImagesAutomatically(bool loadsImagesAutomatically)
-{
-    m_loadsImagesAutomatically = loadsImagesAutomatically;
-
-    // Changing this setting to true might immediately start new loads for images that had previously had loading disabled.
-    // If this happens while a WebView is being dealloc'ed, and we don't know the WebView is being dealloc'ed, these new loads
-    // can cause crashes downstream when the WebView memory has actually been free'd.
-    // One example where this can happen is in Mac apps that subclass WebView then do work in their overridden dealloc methods.
-    // Starting these loads synchronously is not important.  By putting it on a 0-delay, properly closing the Page cancels them
-    // before they have a chance to really start.
-    // See http://webkit.org/b/60572 for more discussion.
-    m_setImageLoadingSettingsTimer.startOneShot(0);
-}
-
-void Settings::imageLoadingSettingsTimerFired(Timer<Settings>*)
-{
-    setImageLoadingSettings(m_page);
-}
-
-void Settings::setScriptEnabled(bool isScriptEnabled)
-{
-    m_isScriptEnabled = isScriptEnabled;
-    InspectorInstrumentation::scriptsEnabled(m_page, m_isScriptEnabled);
-}
-
-void Settings::setJavaEnabled(bool isJavaEnabled)
-{
-    m_isJavaEnabled = isJavaEnabled;
-}
-
-void Settings::setImagesEnabled(bool areImagesEnabled)
-{
-    m_areImagesEnabled = areImagesEnabled;
-
-    // See comment in setLoadsImagesAutomatically.
-    m_setImageLoadingSettingsTimer.startOneShot(0);
-}
-
-void Settings::setPluginsEnabled(bool arePluginsEnabled)
-{
-    m_arePluginsEnabled = arePluginsEnabled;
-}
-
-void Settings::setDNSPrefetchingEnabled(bool dnsPrefetchingEnabled)
-{
-    if (m_dnsPrefetchingEnabled == dnsPrefetchingEnabled)
-        return;
-
-    m_dnsPrefetchingEnabled = dnsPrefetchingEnabled;
-    m_page->dnsPrefetchingStateChanged();
-}
-
-void Settings::setMockScrollbarsEnabled(bool flag)
-{
-    ScrollbarTheme::setMockScrollbarsEnabled(flag);
-}
-
-bool Settings::mockScrollbarsEnabled()
-{
-    return ScrollbarTheme::mockScrollbarsEnabled();
-}
-
-void Settings::setOpenGLMultisamplingEnabled(bool flag)
-{
-    if (m_openGLMultisamplingEnabled == flag)
-        return;
-
-    m_openGLMultisamplingEnabled = flag;
-    m_page->multisamplingChanged();
-}
-
-bool Settings::openGLMultisamplingEnabled()
-{
-    return m_openGLMultisamplingEnabled;
-}
-
-void Settings::setViewportEnabled(bool enabled)
-{
-    if (m_viewportEnabled == enabled)
-        return;
-
-    m_viewportEnabled = enabled;
-    if (m_page->mainFrame())
-        m_page->mainFrame()->document()->updateViewportDescription();
-}
-
-void Settings::setViewportMetaEnabled(bool enabled)
-{
-    m_viewportMetaEnabled = enabled;
-}
-
-} // namespace WebCore
diff --git a/Source/core/page/Settings.h b/Source/core/page/Settings.h
deleted file mode 100644
index 5d16321..0000000
--- a/Source/core/page/Settings.h
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
- *           (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef Settings_h
-#define Settings_h
-
-#include "SettingsMacros.h"
-#include "core/editing/EditingBehaviorTypes.h"
-#include "platform/Timer.h"
-#include "platform/fonts/GenericFontFamilySettings.h"
-#include "platform/geometry/IntSize.h"
-#include "platform/weborigin/KURL.h"
-
-namespace WebCore {
-
-class Page;
-
-enum EditableLinkBehavior {
-    EditableLinkDefaultBehavior,
-    EditableLinkAlwaysLive,
-    EditableLinkOnlyLiveWithShiftKey,
-    EditableLinkLiveWhenNotFocused,
-    EditableLinkNeverLive
-};
-
-class Settings {
-    WTF_MAKE_NONCOPYABLE(Settings); WTF_MAKE_FAST_ALLOCATED;
-public:
-    static PassOwnPtr<Settings> create(Page*);
-
-    GenericFontFamilySettings& genericFontFamilySettings() { return m_genericFontFamilySettings; }
-
-    void setTextAutosizingEnabled(bool);
-    bool textAutosizingEnabled() const;
-
-    // Font scale factor for accessibility, applied as part of text autosizing.
-    void setAccessibilityFontScaleFactor(float);
-    float accessibilityFontScaleFactor() const { return m_accessibilityFontScaleFactor; }
-
-    // Compensates for poor text legibility on mobile devices. This value is
-    // multiplied by the font scale factor when performing text autosizing of
-    // websites that do not set an explicit viewport description.
-    void setDeviceScaleAdjustment(float);
-    float deviceScaleAdjustment() const;
-
-    // Only set by Layout Tests, and only used if textAutosizingEnabled() returns true.
-    void setTextAutosizingWindowSizeOverride(const IntSize&);
-    const IntSize& textAutosizingWindowSizeOverride() const { return m_textAutosizingWindowSizeOverride; }
-
-    void setUseWideViewport(bool);
-    bool useWideViewport() const { return m_useWideViewport; }
-
-    void setLoadWithOverviewMode(bool);
-    bool loadWithOverviewMode() const { return m_loadWithOverviewMode; }
-
-    // Only set by Layout Tests.
-    void setMediaTypeOverride(const String&);
-    const String& mediaTypeOverride() const { return m_mediaTypeOverride; }
-
-    // Unlike areImagesEnabled, this only suppresses the network load of
-    // the image URL.  A cached image will still be rendered if requested.
-    void setLoadsImagesAutomatically(bool);
-    bool loadsImagesAutomatically() const { return m_loadsImagesAutomatically; }
-
-    // Clients that execute script should call ScriptController::canExecuteScripts()
-    // instead of this function. ScriptController::canExecuteScripts() checks the
-    // HTML sandbox, plug-in sandboxing, and other important details.
-    bool isScriptEnabled() const { return m_isScriptEnabled; }
-    void setScriptEnabled(bool);
-
-    SETTINGS_GETTERS_AND_SETTERS
-
-    void setJavaEnabled(bool);
-    bool isJavaEnabled() const { return m_isJavaEnabled; }
-
-    void setImagesEnabled(bool);
-    bool areImagesEnabled() const { return m_areImagesEnabled; }
-
-    void setPluginsEnabled(bool);
-    bool arePluginsEnabled() const { return m_arePluginsEnabled; }
-
-    void setDNSPrefetchingEnabled(bool);
-    bool dnsPrefetchingEnabled() const { return m_dnsPrefetchingEnabled; }
-
-    static void setMockScrollbarsEnabled(bool flag);
-    static bool mockScrollbarsEnabled();
-
-    void setTouchEventEmulationEnabled(bool enabled) { m_touchEventEmulationEnabled = enabled; }
-    bool isTouchEventEmulationEnabled() const { return m_touchEventEmulationEnabled; }
-
-    void setOpenGLMultisamplingEnabled(bool flag);
-    bool openGLMultisamplingEnabled();
-
-    void setViewportEnabled(bool);
-    bool viewportEnabled() const { return m_viewportEnabled; }
-
-    void setViewportMetaEnabled(bool);
-    bool viewportMetaEnabled() const
-    {
-        return m_viewportMetaEnabled;
-    }
-
-    // FIXME: This is a temporary flag and should be removed once accelerated
-    // overflow scroll is ready (crbug.com/254111).
-    void setCompositorDrivenAcceleratedScrollingEnabled(bool enabled) { m_compositorDrivenAcceleratedScrollingEnabled = enabled; }
-    bool isCompositorDrivenAcceleratedScrollingEnabled() const { return m_compositorDrivenAcceleratedScrollingEnabled; }
-
-    // FIXME: This is a temporary flag and should be removed when squashing is ready.
-    // (crbug.com/261605)
-    void setLayerSquashingEnabled(bool enabled) { m_layerSquashingEnabled = enabled; }
-    bool isLayerSquashingEnabled() const { return m_layerSquashingEnabled; }
-
-private:
-    explicit Settings(Page*);
-
-    Page* m_page;
-
-    String m_mediaTypeOverride;
-    GenericFontFamilySettings m_genericFontFamilySettings;
-    float m_accessibilityFontScaleFactor;
-    float m_deviceScaleAdjustment;
-    IntSize m_textAutosizingWindowSizeOverride;
-    bool m_textAutosizingEnabled : 1;
-    bool m_useWideViewport : 1;
-    bool m_loadWithOverviewMode : 1;
-
-    SETTINGS_MEMBER_VARIABLES
-
-    bool m_isJavaEnabled : 1;
-    bool m_loadsImagesAutomatically : 1;
-    bool m_areImagesEnabled : 1;
-    bool m_arePluginsEnabled : 1;
-    bool m_isScriptEnabled : 1;
-    bool m_dnsPrefetchingEnabled : 1;
-
-    bool m_touchEventEmulationEnabled : 1;
-    bool m_openGLMultisamplingEnabled : 1;
-    bool m_viewportEnabled : 1;
-    bool m_viewportMetaEnabled : 1;
-
-    // FIXME: This is a temporary flag and should be removed once accelerated
-    // overflow scroll is ready (crbug.com/254111).
-    bool m_compositorDrivenAcceleratedScrollingEnabled : 1;
-
-    // FIXME: This is a temporary flag and should be removed when squashing is ready.
-    bool m_layerSquashingEnabled : 1;
-
-    Timer<Settings> m_setImageLoadingSettingsTimer;
-    void imageLoadingSettingsTimerFired(Timer<Settings>*);
-    void recalculateTextAutosizingMultipliers();
-};
-
-} // namespace WebCore
-
-#endif // Settings_h
diff --git a/Source/core/page/SpatialNavigation.cpp b/Source/core/page/SpatialNavigation.cpp
index afb75ad..fc7bd00 100644
--- a/Source/core/page/SpatialNavigation.cpp
+++ b/Source/core/page/SpatialNavigation.cpp
@@ -36,23 +36,25 @@
 #include "core/page/FrameTree.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderLayer.h"
 #include "platform/geometry/IntRect.h"
 
 namespace WebCore {
 
-static RectsAlignment alignmentForRects(FocusDirection, const LayoutRect&, const LayoutRect&, const LayoutSize& viewSize);
-static bool areRectsFullyAligned(FocusDirection, const LayoutRect&, const LayoutRect&);
-static bool areRectsPartiallyAligned(FocusDirection, const LayoutRect&, const LayoutRect&);
-static bool areRectsMoreThanFullScreenApart(FocusDirection, const LayoutRect& curRect, const LayoutRect& targetRect, const LayoutSize& viewSize);
-static bool isRectInDirection(FocusDirection, const LayoutRect&, const LayoutRect&);
+using namespace HTMLNames;
+
+static RectsAlignment alignmentForRects(FocusType, const LayoutRect&, const LayoutRect&, const LayoutSize& viewSize);
+static bool areRectsFullyAligned(FocusType, const LayoutRect&, const LayoutRect&);
+static bool areRectsPartiallyAligned(FocusType, const LayoutRect&, const LayoutRect&);
+static bool areRectsMoreThanFullScreenApart(FocusType, const LayoutRect& curRect, const LayoutRect& targetRect, const LayoutSize& viewSize);
+static bool isRectInDirection(FocusType, const LayoutRect&, const LayoutRect&);
 static void deflateIfOverlapped(LayoutRect&, LayoutRect&);
 static LayoutRect rectToAbsoluteCoordinates(Frame* initialFrame, const LayoutRect&);
-static void entryAndExitPointsForDirection(FocusDirection, const LayoutRect& startingRect, const LayoutRect& potentialRect, LayoutPoint& exitPoint, LayoutPoint& entryPoint);
+static void entryAndExitPointsForDirection(FocusType, const LayoutRect& startingRect, const LayoutRect& potentialRect, LayoutPoint& exitPoint, LayoutPoint& entryPoint);
 static bool isScrollableNode(const Node*);
 
-FocusCandidate::FocusCandidate(Node* node, FocusDirection direction)
+FocusCandidate::FocusCandidate(Node* node, FocusType type)
     : visibleNode(0)
     , focusableNode(0)
     , enclosingScrollableBox(0)
@@ -66,14 +68,14 @@
     ASSERT(node);
     ASSERT(node->isElementNode());
 
-    if (isHTMLAreaElement(node)) {
+    if (node->hasTagName(areaTag)) {
         HTMLAreaElement* area = toHTMLAreaElement(node);
         HTMLImageElement* image = area->imageElement();
         if (!image || !image->renderer())
             return;
 
         visibleNode = image;
-        rect = virtualRectForAreaElementAndDirection(area, direction);
+        rect = virtualRectForAreaElementAndDirection(area, type);
     } else {
         if (!node->renderer())
             return;
@@ -84,7 +86,7 @@
 
     focusableNode = node;
     isOffscreen = hasOffscreenRect(visibleNode);
-    isOffscreenAfterScrolling = hasOffscreenRect(visibleNode, direction);
+    isOffscreenAfterScrolling = hasOffscreenRect(visibleNode, type);
 }
 
 bool isSpatialNavigationEnabled(const Frame* frame)
@@ -92,40 +94,40 @@
     return (frame && frame->settings() && frame->settings()->spatialNavigationEnabled());
 }
 
-static RectsAlignment alignmentForRects(FocusDirection direction, const LayoutRect& curRect, const LayoutRect& targetRect, const LayoutSize& viewSize)
+static RectsAlignment alignmentForRects(FocusType type, const LayoutRect& curRect, const LayoutRect& targetRect, const LayoutSize& viewSize)
 {
     // If we found a node in full alignment, but it is too far away, ignore it.
-    if (areRectsMoreThanFullScreenApart(direction, curRect, targetRect, viewSize))
+    if (areRectsMoreThanFullScreenApart(type, curRect, targetRect, viewSize))
         return None;
 
-    if (areRectsFullyAligned(direction, curRect, targetRect))
+    if (areRectsFullyAligned(type, curRect, targetRect))
         return Full;
 
-    if (areRectsPartiallyAligned(direction, curRect, targetRect))
+    if (areRectsPartiallyAligned(type, curRect, targetRect))
         return Partial;
 
     return None;
 }
 
-static inline bool isHorizontalMove(FocusDirection direction)
+static inline bool isHorizontalMove(FocusType type)
 {
-    return direction == FocusDirectionLeft || direction == FocusDirectionRight;
+    return type == FocusTypeLeft || type == FocusTypeRight;
 }
 
-static inline LayoutUnit start(FocusDirection direction, const LayoutRect& rect)
+static inline LayoutUnit start(FocusType type, const LayoutRect& rect)
 {
-    return isHorizontalMove(direction) ? rect.y() : rect.x();
+    return isHorizontalMove(type) ? rect.y() : rect.x();
 }
 
-static inline LayoutUnit middle(FocusDirection direction, const LayoutRect& rect)
+static inline LayoutUnit middle(FocusType type, const LayoutRect& rect)
 {
     LayoutPoint center(rect.center());
-    return isHorizontalMove(direction) ? center.y(): center.x();
+    return isHorizontalMove(type) ? center.y(): center.x();
 }
 
-static inline LayoutUnit end(FocusDirection direction, const LayoutRect& rect)
+static inline LayoutUnit end(FocusType type, const LayoutRect& rect)
 {
-    return isHorizontalMove(direction) ? rect.maxY() : rect.maxX();
+    return isHorizontalMove(type) ? rect.maxY() : rect.maxX();
 }
 
 // This method checks if rects |a| and |b| are fully aligned either vertically or
@@ -135,24 +137,24 @@
 // operations.
 // * a = Current focused node's rect.
 // * b = Focus candidate node's rect.
-static bool areRectsFullyAligned(FocusDirection direction, const LayoutRect& a, const LayoutRect& b)
+static bool areRectsFullyAligned(FocusType type, const LayoutRect& a, const LayoutRect& b)
 {
     LayoutUnit aStart, bStart, aEnd, bEnd;
 
-    switch (direction) {
-    case FocusDirectionLeft:
+    switch (type) {
+    case FocusTypeLeft:
         aStart = a.x();
         bEnd = b.maxX();
         break;
-    case FocusDirectionRight:
+    case FocusTypeRight:
         aStart = b.x();
         bEnd = a.maxX();
         break;
-    case FocusDirectionUp:
+    case FocusTypeUp:
         aStart = a.y();
         bEnd = b.y();
         break;
-    case FocusDirectionDown:
+    case FocusTypeDown:
         aStart = b.y();
         bEnd = a.y();
         break;
@@ -164,14 +166,14 @@
     if (aStart < bEnd)
         return false;
 
-    aStart = start(direction, a);
-    bStart = start(direction, b);
+    aStart = start(type, a);
+    bStart = start(type, b);
 
-    LayoutUnit aMiddle = middle(direction, a);
-    LayoutUnit bMiddle = middle(direction, b);
+    LayoutUnit aMiddle = middle(type, a);
+    LayoutUnit bMiddle = middle(type, b);
 
-    aEnd = end(direction, a);
-    bEnd = end(direction, b);
+    aEnd = end(type, a);
+    bEnd = end(type, b);
 
     // Picture of the totally aligned logic:
     //
@@ -207,13 +209,13 @@
 // horizontally or vertically.
 // * a = Current focused node's rect.
 // * b = Focus candidate node's rect.
-static bool areRectsPartiallyAligned(FocusDirection direction, const LayoutRect& a, const LayoutRect& b)
+static bool areRectsPartiallyAligned(FocusType type, const LayoutRect& a, const LayoutRect& b)
 {
-    LayoutUnit aStart  = start(direction, a);
-    LayoutUnit bStart  = start(direction, b);
-    LayoutUnit bMiddle = middle(direction, b);
-    LayoutUnit aEnd = end(direction, a);
-    LayoutUnit bEnd = end(direction, b);
+    LayoutUnit aStart  = start(type, a);
+    LayoutUnit bStart  = start(type, b);
+    LayoutUnit bMiddle = middle(type, b);
+    LayoutUnit aEnd = end(type, a);
+    LayoutUnit bEnd = end(type, b);
 
     // Picture of the partially aligned logic:
     //
@@ -235,18 +237,18 @@
             || (bMiddle >= aStart && bMiddle <= aEnd));
 }
 
-static bool areRectsMoreThanFullScreenApart(FocusDirection direction, const LayoutRect& curRect, const LayoutRect& targetRect, const LayoutSize& viewSize)
+static bool areRectsMoreThanFullScreenApart(FocusType type, const LayoutRect& curRect, const LayoutRect& targetRect, const LayoutSize& viewSize)
 {
-    ASSERT(isRectInDirection(direction, curRect, targetRect));
+    ASSERT(isRectInDirection(type, curRect, targetRect));
 
-    switch (direction) {
-    case FocusDirectionLeft:
+    switch (type) {
+    case FocusTypeLeft:
         return curRect.x() - targetRect.maxX() > viewSize.width();
-    case FocusDirectionRight:
+    case FocusTypeRight:
         return targetRect.x() - curRect.maxX() > viewSize.width();
-    case FocusDirectionUp:
+    case FocusTypeUp:
         return curRect.y() - targetRect.maxY() > viewSize.height();
-    case FocusDirectionDown:
+    case FocusTypeDown:
         return targetRect.y() - curRect.maxY() > viewSize.height();
     default:
         ASSERT_NOT_REACHED();
@@ -266,16 +268,16 @@
     return a.x() > b.maxX();
 }
 
-static bool isRectInDirection(FocusDirection direction, const LayoutRect& curRect, const LayoutRect& targetRect)
+static bool isRectInDirection(FocusType type, const LayoutRect& curRect, const LayoutRect& targetRect)
 {
-    switch (direction) {
-    case FocusDirectionLeft:
+    switch (type) {
+    case FocusTypeLeft:
         return targetRect.maxX() <= curRect.x();
-    case FocusDirectionRight:
+    case FocusTypeRight:
         return targetRect.x() >= curRect.maxX();
-    case FocusDirectionUp:
+    case FocusTypeUp:
         return targetRect.maxY() <= curRect.y();
-    case FocusDirectionDown:
+    case FocusTypeDown:
         return targetRect.y() >= curRect.maxY();
     default:
         ASSERT_NOT_REACHED();
@@ -286,7 +288,7 @@
 // Checks if |node| is offscreen the visible area (viewport) of its container
 // document. In case it is, one can scroll in direction or take any different
 // desired action later on.
-bool hasOffscreenRect(Node* node, FocusDirection direction)
+bool hasOffscreenRect(Node* node, FocusType type)
 {
     // Get the FrameView in which |node| is (which means the current viewport if |node|
     // is not in an inner document), so we can check if its content rect is visible
@@ -302,19 +304,19 @@
     // exposed after we scroll. Adjust the viewport to post-scrolling position.
     // If the container has overflow:hidden, we cannot scroll, so we do not pass direction
     // and we do not adjust for scrolling.
-    switch (direction) {
-    case FocusDirectionLeft:
+    switch (type) {
+    case FocusTypeLeft:
         containerViewportRect.setX(containerViewportRect.x() - ScrollableArea::pixelsPerLineStep());
         containerViewportRect.setWidth(containerViewportRect.width() + ScrollableArea::pixelsPerLineStep());
         break;
-    case FocusDirectionRight:
+    case FocusTypeRight:
         containerViewportRect.setWidth(containerViewportRect.width() + ScrollableArea::pixelsPerLineStep());
         break;
-    case FocusDirectionUp:
+    case FocusTypeUp:
         containerViewportRect.setY(containerViewportRect.y() - ScrollableArea::pixelsPerLineStep());
         containerViewportRect.setHeight(containerViewportRect.height() + ScrollableArea::pixelsPerLineStep());
         break;
-    case FocusDirectionDown:
+    case FocusTypeDown:
         containerViewportRect.setHeight(containerViewportRect.height() + ScrollableArea::pixelsPerLineStep());
         break;
     default:
@@ -332,24 +334,24 @@
     return !containerViewportRect.intersects(rect);
 }
 
-bool scrollInDirection(Frame* frame, FocusDirection direction)
+bool scrollInDirection(Frame* frame, FocusType type)
 {
     ASSERT(frame);
 
-    if (frame && canScrollInDirection(frame->document(), direction)) {
+    if (frame && canScrollInDirection(frame->document(), type)) {
         LayoutUnit dx = 0;
         LayoutUnit dy = 0;
-        switch (direction) {
-        case FocusDirectionLeft:
+        switch (type) {
+        case FocusTypeLeft:
             dx = - ScrollableArea::pixelsPerLineStep();
             break;
-        case FocusDirectionRight:
+        case FocusTypeRight:
             dx = ScrollableArea::pixelsPerLineStep();
             break;
-        case FocusDirectionUp:
+        case FocusTypeUp:
             dy = - ScrollableArea::pixelsPerLineStep();
             break;
-        case FocusDirectionDown:
+        case FocusTypeDown:
             dy = ScrollableArea::pixelsPerLineStep();
             break;
         default:
@@ -363,30 +365,30 @@
     return false;
 }
 
-bool scrollInDirection(Node* container, FocusDirection direction)
+bool scrollInDirection(Node* container, FocusType type)
 {
     ASSERT(container);
     if (container->isDocumentNode())
-        return scrollInDirection(toDocument(container)->frame(), direction);
+        return scrollInDirection(toDocument(container)->frame(), type);
 
     if (!container->renderBox())
         return false;
 
-    if (canScrollInDirection(container, direction)) {
+    if (canScrollInDirection(container, type)) {
         LayoutUnit dx = 0;
         LayoutUnit dy = 0;
-        switch (direction) {
-        case FocusDirectionLeft:
+        switch (type) {
+        case FocusTypeLeft:
             dx = - std::min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollLeft());
             break;
-        case FocusDirectionRight:
+        case FocusTypeRight:
             ASSERT(container->renderBox()->scrollWidth() > (container->renderBox()->scrollLeft() + container->renderBox()->clientWidth()));
             dx = std::min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollWidth() - (container->renderBox()->scrollLeft() + container->renderBox()->clientWidth()));
             break;
-        case FocusDirectionUp:
+        case FocusTypeUp:
             dy = - std::min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollTop());
             break;
-        case FocusDirectionDown:
+        case FocusTypeDown:
             ASSERT(container->renderBox()->scrollHeight() - (container->renderBox()->scrollTop() + container->renderBox()->clientHeight()));
             dy = std::min<LayoutUnit>(ScrollableArea::pixelsPerLineStep(), container->renderBox()->scrollHeight() - (container->renderBox()->scrollTop() + container->renderBox()->clientHeight()));
             break;
@@ -430,37 +432,37 @@
     return false;
 }
 
-Node* scrollableEnclosingBoxOrParentFrameForNodeInDirection(FocusDirection direction, Node* node)
+Node* scrollableEnclosingBoxOrParentFrameForNodeInDirection(FocusType type, Node* node)
 {
     ASSERT(node);
     Node* parent = node;
     do {
         if (parent->isDocumentNode())
-            parent = toDocument(parent)->document().frame()->ownerElement();
+            parent = toDocument(parent)->frame()->ownerElement();
         else
             parent = parent->parentOrShadowHostNode();
-    } while (parent && !canScrollInDirection(parent, direction) && !parent->isDocumentNode());
+    } while (parent && !canScrollInDirection(parent, type) && !parent->isDocumentNode());
 
     return parent;
 }
 
-bool canScrollInDirection(const Node* container, FocusDirection direction)
+bool canScrollInDirection(const Node* container, FocusType type)
 {
     ASSERT(container);
     if (container->isDocumentNode())
-        return canScrollInDirection(toDocument(container)->frame(), direction);
+        return canScrollInDirection(toDocument(container)->frame(), type);
 
     if (!isScrollableNode(container))
         return false;
 
-    switch (direction) {
-    case FocusDirectionLeft:
+    switch (type) {
+    case FocusTypeLeft:
         return (container->renderer()->style()->overflowX() != OHIDDEN && container->renderBox()->scrollLeft() > 0);
-    case FocusDirectionUp:
+    case FocusTypeUp:
         return (container->renderer()->style()->overflowY() != OHIDDEN && container->renderBox()->scrollTop() > 0);
-    case FocusDirectionRight:
+    case FocusTypeRight:
         return (container->renderer()->style()->overflowX() != OHIDDEN && container->renderBox()->scrollLeft() + container->renderBox()->clientWidth() < container->renderBox()->scrollWidth());
-    case FocusDirectionDown:
+    case FocusTypeDown:
         return (container->renderer()->style()->overflowY() != OHIDDEN && container->renderBox()->scrollTop() + container->renderBox()->clientHeight() < container->renderBox()->scrollHeight());
     default:
         ASSERT_NOT_REACHED();
@@ -468,29 +470,29 @@
     }
 }
 
-bool canScrollInDirection(const Frame* frame, FocusDirection direction)
+bool canScrollInDirection(const Frame* frame, FocusType type)
 {
     if (!frame->view())
         return false;
     ScrollbarMode verticalMode;
     ScrollbarMode horizontalMode;
-    frame->view()->calculateScrollbarModesForLayout(horizontalMode, verticalMode);
-    if ((direction == FocusDirectionLeft || direction == FocusDirectionRight) && ScrollbarAlwaysOff == horizontalMode)
+    frame->view()->calculateScrollbarModesForLayoutAndSetViewportRenderer(horizontalMode, verticalMode);
+    if ((type == FocusTypeLeft || type == FocusTypeRight) && ScrollbarAlwaysOff == horizontalMode)
         return false;
-    if ((direction == FocusDirectionUp || direction == FocusDirectionDown) &&  ScrollbarAlwaysOff == verticalMode)
+    if ((type == FocusTypeUp || type == FocusTypeDown) &&  ScrollbarAlwaysOff == verticalMode)
         return false;
     LayoutSize size = frame->view()->contentsSize();
     LayoutSize offset = frame->view()->scrollOffset();
     LayoutRect rect = frame->view()->visibleContentRect(ScrollableArea::IncludeScrollbars);
 
-    switch (direction) {
-    case FocusDirectionLeft:
+    switch (type) {
+    case FocusTypeLeft:
         return offset.width() > 0;
-    case FocusDirectionUp:
+    case FocusTypeUp:
         return offset.height() > 0;
-    case FocusDirectionRight:
+    case FocusTypeRight:
         return rect.width() + offset.width() < size.width();
-    case FocusDirectionDown:
+    case FocusTypeDown:
         return rect.height() + offset.height() < size.height();
     default:
         ASSERT_NOT_REACHED();
@@ -537,22 +539,22 @@
 
 // This method calculates the exitPoint from the startingRect and the entryPoint into the candidate rect.
 // The line between those 2 points is the closest distance between the 2 rects.
-void entryAndExitPointsForDirection(FocusDirection direction, const LayoutRect& startingRect, const LayoutRect& potentialRect, LayoutPoint& exitPoint, LayoutPoint& entryPoint)
+void entryAndExitPointsForDirection(FocusType type, const LayoutRect& startingRect, const LayoutRect& potentialRect, LayoutPoint& exitPoint, LayoutPoint& entryPoint)
 {
-    switch (direction) {
-    case FocusDirectionLeft:
+    switch (type) {
+    case FocusTypeLeft:
         exitPoint.setX(startingRect.x());
         entryPoint.setX(potentialRect.maxX());
         break;
-    case FocusDirectionUp:
+    case FocusTypeUp:
         exitPoint.setY(startingRect.y());
         entryPoint.setY(potentialRect.maxY());
         break;
-    case FocusDirectionRight:
+    case FocusTypeRight:
         exitPoint.setX(startingRect.maxX());
         entryPoint.setX(potentialRect.x());
         break;
-    case FocusDirectionDown:
+    case FocusTypeDown:
         exitPoint.setY(startingRect.maxY());
         entryPoint.setY(potentialRect.y());
         break;
@@ -560,9 +562,9 @@
         ASSERT_NOT_REACHED();
     }
 
-    switch (direction) {
-    case FocusDirectionLeft:
-    case FocusDirectionRight:
+    switch (type) {
+    case FocusTypeLeft:
+    case FocusTypeRight:
         if (below(startingRect, potentialRect)) {
             exitPoint.setY(startingRect.y());
             entryPoint.setY(potentialRect.maxY());
@@ -574,8 +576,8 @@
             entryPoint.setY(exitPoint.y());
         }
         break;
-    case FocusDirectionUp:
-    case FocusDirectionDown:
+    case FocusTypeUp:
+    case FocusTypeDown:
         if (rightOf(startingRect, potentialRect)) {
             exitPoint.setX(startingRect.x());
             entryPoint.setX(potentialRect.maxX());
@@ -603,7 +605,7 @@
     if (!firstCandidate.rect.intersects(secondCandidate.rect))
         return false;
 
-    if (isHTMLAreaElement(firstCandidate.focusableNode) || isHTMLAreaElement(secondCandidate.focusableNode))
+    if (firstCandidate.focusableNode->hasTagName(areaTag) || secondCandidate.focusableNode->hasTagName(areaTag))
         return false;
 
     if (!firstCandidate.visibleNode->renderer()->isRenderInline() || !secondCandidate.visibleNode->renderer()->isRenderInline())
@@ -615,10 +617,10 @@
     return true;
 }
 
-void distanceDataForNode(FocusDirection direction, const FocusCandidate& current, FocusCandidate& candidate)
+void distanceDataForNode(FocusType type, const FocusCandidate& current, FocusCandidate& candidate)
 {
     if (areElementsOnSameLine(current, candidate)) {
-        if ((direction == FocusDirectionUp && current.rect.y() > candidate.rect.y()) || (direction == FocusDirectionDown && candidate.rect.y() > current.rect.y())) {
+        if ((type == FocusTypeUp && current.rect.y() > candidate.rect.y()) || (type == FocusTypeDown && candidate.rect.y() > current.rect.y())) {
             candidate.distance = 0;
             candidate.alignment = Full;
             return;
@@ -629,29 +631,29 @@
     LayoutRect currentRect = current.rect;
     deflateIfOverlapped(currentRect, nodeRect);
 
-    if (!isRectInDirection(direction, currentRect, nodeRect))
+    if (!isRectInDirection(type, currentRect, nodeRect))
         return;
 
     LayoutPoint exitPoint;
     LayoutPoint entryPoint;
     LayoutUnit sameAxisDistance = 0;
     LayoutUnit otherAxisDistance = 0;
-    entryAndExitPointsForDirection(direction, currentRect, nodeRect, exitPoint, entryPoint);
+    entryAndExitPointsForDirection(type, currentRect, nodeRect, exitPoint, entryPoint);
 
-    switch (direction) {
-    case FocusDirectionLeft:
+    switch (type) {
+    case FocusTypeLeft:
         sameAxisDistance = exitPoint.x() - entryPoint.x();
         otherAxisDistance = absoluteValue(exitPoint.y() - entryPoint.y());
         break;
-    case FocusDirectionUp:
+    case FocusTypeUp:
         sameAxisDistance = exitPoint.y() - entryPoint.y();
         otherAxisDistance = absoluteValue(exitPoint.x() - entryPoint.x());
         break;
-    case FocusDirectionRight:
+    case FocusTypeRight:
         sameAxisDistance = entryPoint.x() - exitPoint.x();
         otherAxisDistance = absoluteValue(entryPoint.y() - exitPoint.y());
         break;
-    case FocusDirectionDown:
+    case FocusTypeDown:
         sameAxisDistance = entryPoint.y() - exitPoint.y();
         otherAxisDistance = absoluteValue(entryPoint.x() - exitPoint.x());
         break;
@@ -671,22 +673,22 @@
     float distance = euclidianDistance + sameAxisDistance + 2 * otherAxisDistance;
     candidate.distance = roundf(distance);
     LayoutSize viewSize = candidate.visibleNode->document().page()->mainFrame()->view()->visibleContentRect().size();
-    candidate.alignment = alignmentForRects(direction, currentRect, nodeRect, viewSize);
+    candidate.alignment = alignmentForRects(type, currentRect, nodeRect, viewSize);
 }
 
-bool canBeScrolledIntoView(FocusDirection direction, const FocusCandidate& candidate)
+bool canBeScrolledIntoView(FocusType type, const FocusCandidate& candidate)
 {
     ASSERT(candidate.visibleNode && candidate.isOffscreen);
     LayoutRect candidateRect = candidate.rect;
     for (Node* parentNode = candidate.visibleNode->parentNode(); parentNode; parentNode = parentNode->parentNode()) {
         LayoutRect parentRect = nodeRectInAbsoluteCoordinates(parentNode);
         if (!candidateRect.intersects(parentRect)) {
-            if (((direction == FocusDirectionLeft || direction == FocusDirectionRight) && parentNode->renderer()->style()->overflowX() == OHIDDEN)
-                || ((direction == FocusDirectionUp || direction == FocusDirectionDown) && parentNode->renderer()->style()->overflowY() == OHIDDEN))
+            if (((type == FocusTypeLeft || type == FocusTypeRight) && parentNode->renderer()->style()->overflowX() == OHIDDEN)
+                || ((type == FocusTypeUp || type == FocusTypeDown) && parentNode->renderer()->style()->overflowY() == OHIDDEN))
                 return false;
         }
         if (parentNode == candidate.enclosingScrollableBox)
-            return canScrollInDirection(parentNode, direction);
+            return canScrollInDirection(parentNode, type);
     }
     return true;
 }
@@ -695,22 +697,22 @@
 // Compose a virtual starting rect if there is no focused node or if it is off screen.
 // The virtual rect is the edge of the container or frame. We select which
 // edge depending on the direction of the navigation.
-LayoutRect virtualRectForDirection(FocusDirection direction, const LayoutRect& startingRect, LayoutUnit width)
+LayoutRect virtualRectForDirection(FocusType type, const LayoutRect& startingRect, LayoutUnit width)
 {
     LayoutRect virtualStartingRect = startingRect;
-    switch (direction) {
-    case FocusDirectionLeft:
+    switch (type) {
+    case FocusTypeLeft:
         virtualStartingRect.setX(virtualStartingRect.maxX() - width);
         virtualStartingRect.setWidth(width);
         break;
-    case FocusDirectionUp:
+    case FocusTypeUp:
         virtualStartingRect.setY(virtualStartingRect.maxY() - width);
         virtualStartingRect.setHeight(width);
         break;
-    case FocusDirectionRight:
+    case FocusTypeRight:
         virtualStartingRect.setWidth(width);
         break;
-    case FocusDirectionDown:
+    case FocusTypeDown:
         virtualStartingRect.setHeight(width);
         break;
     default:
@@ -720,13 +722,13 @@
     return virtualStartingRect;
 }
 
-LayoutRect virtualRectForAreaElementAndDirection(HTMLAreaElement* area, FocusDirection direction)
+LayoutRect virtualRectForAreaElementAndDirection(HTMLAreaElement* area, FocusType type)
 {
     ASSERT(area);
     ASSERT(area->imageElement());
     // Area elements tend to overlap more than other focusable elements. We flatten the rect of the area elements
     // to minimize the effect of overlapping areas.
-    LayoutRect rect = virtualRectForDirection(direction, rectToAbsoluteCoordinates(area->document().frame(), area->computeRect(area->imageElement()->renderer())), 1);
+    LayoutRect rect = virtualRectForDirection(type, rectToAbsoluteCoordinates(area->document().frame(), area->computeRect(area->imageElement()->renderer())), 1);
     return rect;
 }
 
diff --git a/Source/core/page/SpatialNavigation.h b/Source/core/page/SpatialNavigation.h
index 1e2f56c..616dada 100644
--- a/Source/core/page/SpatialNavigation.h
+++ b/Source/core/page/SpatialNavigation.h
@@ -23,7 +23,7 @@
 
 #include "core/dom/Node.h"
 #include "core/html/HTMLFrameOwnerElement.h"
-#include "core/page/FocusDirection.h"
+#include "core/page/FocusType.h"
 #include "platform/geometry/LayoutRect.h"
 
 #include <limits>
@@ -111,8 +111,8 @@
     {
     }
 
-    FocusCandidate(Node* n, FocusDirection);
-    explicit FocusCandidate(HTMLAreaElement* area, FocusDirection);
+    FocusCandidate(Node*, FocusType);
+    explicit FocusCandidate(HTMLAreaElement*, FocusType);
     bool isNull() const { return !visibleNode; }
     bool inScrollableContainer() const { return visibleNode && enclosingScrollableBox; }
     bool isFrameOwnerElement() const { return visibleNode && visibleNode->isFrameOwnerElement(); }
@@ -133,19 +133,19 @@
     bool isOffscreenAfterScrolling;
 };
 
-bool hasOffscreenRect(Node*, FocusDirection direction = FocusDirectionNone);
-bool scrollInDirection(Frame*, FocusDirection);
-bool scrollInDirection(Node* container, FocusDirection);
-bool canScrollInDirection(const Node* container, FocusDirection);
-bool canScrollInDirection(const Frame*, FocusDirection);
-bool canBeScrolledIntoView(FocusDirection, const FocusCandidate&);
+bool hasOffscreenRect(Node*, FocusType = FocusTypeNone);
+bool scrollInDirection(Frame*, FocusType);
+bool scrollInDirection(Node* container, FocusType);
+bool canScrollInDirection(const Node* container, FocusType);
+bool canScrollInDirection(const Frame*, FocusType);
+bool canBeScrolledIntoView(FocusType, const FocusCandidate&);
 bool areElementsOnSameLine(const FocusCandidate& firstCandidate, const FocusCandidate& secondCandidate);
-void distanceDataForNode(FocusDirection, const FocusCandidate& current, FocusCandidate& candidate);
-Node* scrollableEnclosingBoxOrParentFrameForNodeInDirection(FocusDirection, Node*);
+void distanceDataForNode(FocusType, const FocusCandidate& current, FocusCandidate&);
+Node* scrollableEnclosingBoxOrParentFrameForNodeInDirection(FocusType, Node*);
 LayoutRect nodeRectInAbsoluteCoordinates(Node*, bool ignoreBorder = false);
 LayoutRect frameRectInAbsoluteCoordinates(Frame*);
-LayoutRect virtualRectForDirection(FocusDirection, const LayoutRect& startingRect, LayoutUnit width = 0);
-LayoutRect virtualRectForAreaElementAndDirection(HTMLAreaElement*, FocusDirection);
+LayoutRect virtualRectForDirection(FocusType, const LayoutRect& startingRect, LayoutUnit width = 0);
+LayoutRect virtualRectForAreaElementAndDirection(HTMLAreaElement*, FocusType);
 HTMLFrameOwnerElement* frameOwnerElement(FocusCandidate&);
 
 } // namspace WebCore
diff --git a/Source/core/page/StorageClient.h b/Source/core/page/StorageClient.h
new file mode 100644
index 0000000..331d23c
--- /dev/null
+++ b/Source/core/page/StorageClient.h
@@ -0,0 +1,25 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef StorageClient_h
+#define StorageClient_h
+
+#include "core/storage/StorageArea.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class StorageNamespace;
+
+class StorageClient {
+public:
+    virtual ~StorageClient() { }
+
+    virtual PassOwnPtr<StorageNamespace> createSessionStorageNamespace() = 0;
+    virtual bool canAccessStorage(Frame*, StorageType) const = 0;
+};
+
+} // namespace WebCore
+
+#endif // StorageClient_h
diff --git a/Source/core/page/TouchAdjustment.cpp b/Source/core/page/TouchAdjustment.cpp
index 41d4eef..be85ae4 100644
--- a/Source/core/page/TouchAdjustment.cpp
+++ b/Source/core/page/TouchAdjustment.cpp
@@ -150,8 +150,8 @@
     if (!node->isTextNode())
         return appendBasicSubtargetsForNode(node, subtargets);
 
-    Text* textNode = static_cast<WebCore::Text*>(node);
-    RenderText* textRenderer = static_cast<RenderText*>(textNode->renderer());
+    Text* textNode = toText(node);
+    RenderText* textRenderer = toRenderText(textNode->renderer());
 
     if (textRenderer->frame()->editor().behavior().shouldSelectOnContextualMenuClick()) {
         // Make subtargets out of every word.
diff --git a/Source/core/page/TouchDisambiguation.cpp b/Source/core/page/TouchDisambiguation.cpp
index 5fda7d8d..9d9b8c0 100644
--- a/Source/core/page/TouchDisambiguation.cpp
+++ b/Source/core/page/TouchDisambiguation.cpp
@@ -38,7 +38,6 @@
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/NodeTraversal.h"
-#include "core/html/HTMLHtmlElement.h"
 #include "core/page/EventHandler.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
@@ -126,10 +125,10 @@
         for (Node* node = it->get(); node; node = node->parentNode()) {
             if (blackList.contains(node))
                 continue;
-            if (node->isDocumentNode() || isHTMLHtmlElement(node) || node->hasTagName(HTMLNames::bodyTag))
+            if (node->isDocumentNode() || node->hasTagName(HTMLNames::htmlTag) || node->hasTagName(HTMLNames::bodyTag))
                 break;
             if (node->willRespondToMouseClickEvents()) {
-                TouchTargetData& targetData = touchTargets.add(node, TouchTargetData()).iterator->value;
+                TouchTargetData& targetData = touchTargets.add(node, TouchTargetData()).storedValue->value;
                 targetData.windowBoundingBox = boundingBoxForEventNodes(node);
                 targetData.score = scoreTouchTarget(touchPoint, touchPointPadding, targetData.windowBoundingBox);
                 bestScore = max(bestScore, targetData.score);
diff --git a/Source/core/page/WindowPagePopup.idl b/Source/core/page/WindowPagePopup.idl
index e4b5839..0b81785 100644
--- a/Source/core/page/WindowPagePopup.idl
+++ b/Source/core/page/WindowPagePopup.idl
@@ -29,8 +29,9 @@
  */
 
 [
+    ImplementedAs=DOMWindowPagePopup,
+    PerContextEnabled=PagePopup,
     RuntimeEnabled=PagePopup,
-    ImplementedAs=DOMWindowPagePopup
 ] partial interface Window {
-    [PerContextEnabled=PagePopup] readonly attribute PagePopupController pagePopupController;
+    readonly attribute PagePopupController pagePopupController;
 };
diff --git a/Source/core/page/scrolling/ScrollingConstraints.h b/Source/core/page/scrolling/ScrollingConstraints.h
index 993f234..857430e 100644
--- a/Source/core/page/scrolling/ScrollingConstraints.h
+++ b/Source/core/page/scrolling/ScrollingConstraints.h
@@ -73,7 +73,7 @@
     AnchorEdges m_anchorEdges;
 };
 
-class FixedPositionViewportConstraints : public ViewportConstraints {
+class FixedPositionViewportConstraints FINAL : public ViewportConstraints {
 public:
     FixedPositionViewportConstraints()
         : ViewportConstraints()
@@ -104,13 +104,13 @@
     bool operator!=(const FixedPositionViewportConstraints& other) const { return !(*this == other); }
 
 private:
-    virtual ConstraintType constraintType() const OVERRIDE { return FixedPositionConstaint; };
+    virtual ConstraintType constraintType() const OVERRIDE { return FixedPositionConstaint; }
 
     FloatRect m_viewportRectAtLastLayout;
     FloatPoint m_layerPositionAtLastLayout;
 };
 
-class StickyPositionViewportConstraints : public ViewportConstraints {
+class StickyPositionViewportConstraints FINAL : public ViewportConstraints {
 public:
     StickyPositionViewportConstraints()
         : m_leftOffset(0)
@@ -172,7 +172,7 @@
     bool operator!=(const StickyPositionViewportConstraints& other) const { return !(*this == other); }
 
 private:
-    virtual ConstraintType constraintType() const OVERRIDE { return StickyPositionConstraint; };
+    virtual ConstraintType constraintType() const OVERRIDE { return StickyPositionConstraint; }
 
     float m_leftOffset;
     float m_rightOffset;
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.cpp b/Source/core/page/scrolling/ScrollingCoordinator.cpp
index 83057f3..76571fb 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -35,10 +35,10 @@
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/chromium/support/WebScrollbarThemeGeometryNative.h"
+#include "core/frame/Settings.h"
 #include "platform/TraceEvent.h"
 #include "platform/exported/WebScrollbarImpl.h"
+#include "platform/exported/WebScrollbarThemeGeometryNative.h"
 #include "platform/geometry/Region.h"
 #include "platform/geometry/TransformState.h"
 #include "platform/graphics/GraphicsLayer.h"
@@ -80,15 +80,25 @@
     return graphicsLayer ? scrollingWebLayerForGraphicsLayer(graphicsLayer) : 0;
 }
 
-PassRefPtr<ScrollingCoordinator> ScrollingCoordinator::create(Page* page)
+WebLayer* ScrollingCoordinator::containerWebLayerForScrollableArea(ScrollableArea* scrollableArea)
 {
-    return adoptRef(new ScrollingCoordinator(page));
+    GraphicsLayer* graphicsLayer = scrollLayerForScrollableArea(scrollableArea);
+    if (!graphicsLayer)
+        return 0;
+    graphicsLayer = graphicsLayer->parent();
+    return graphicsLayer ? graphicsLayer->platformLayer() : 0;
+}
+
+PassOwnPtr<ScrollingCoordinator> ScrollingCoordinator::create(Page* page)
+{
+    return adoptPtr(new ScrollingCoordinator(page));
 }
 
 ScrollingCoordinator::ScrollingCoordinator(Page* page)
     : m_page(page)
     , m_scrollGestureRegionIsDirty(false)
     , m_touchEventTargetRectsAreDirty(false)
+    , m_shouldScrollOnMainThreadDirty(false)
     , m_wasFrameScrollable(false)
     , m_lastMainThreadScrollingReasons(0)
 {
@@ -124,9 +134,9 @@
 
 void ScrollingCoordinator::notifyLayoutUpdated()
 {
-    // These computations need to happen after compositing is updated.
     m_scrollGestureRegionIsDirty = true;
     m_touchEventTargetRectsAreDirty = true;
+    m_shouldScrollOnMainThreadDirty = true;
 }
 
 void ScrollingCoordinator::updateAfterCompositingChange()
@@ -154,10 +164,17 @@
 
     FrameView* frameView = m_page->mainFrame()->view();
     bool frameIsScrollable = frameView && frameView->isScrollable();
-    if (m_wasFrameScrollable != frameIsScrollable)
-        updateShouldUpdateScrollLayerPositionOnMainThread();
+    if (m_shouldScrollOnMainThreadDirty || m_wasFrameScrollable != frameIsScrollable) {
+        setShouldUpdateScrollLayerPositionOnMainThread(mainThreadScrollingReasons());
+        m_shouldScrollOnMainThreadDirty = false;
+    }
     m_wasFrameScrollable = frameIsScrollable;
 
+    // The mainFrame view doesn't get included in the FrameTree below, so we
+    // update its size separately.
+    if (WebLayer* scrollingWebLayer = frameView ? scrollingWebLayerForScrollableArea(frameView) : 0)
+        scrollingWebLayer->setBounds(frameView->contentsSize());
+
     const FrameTree& tree = m_page->mainFrame()->tree();
     for (const Frame* child = tree.firstChild(); child; child = child->tree().nextSibling()) {
         if (WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(child->view()))
@@ -200,7 +217,7 @@
 {
     ASSERT(layer->hasCompositedLayerMapping());
     CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
-    GraphicsLayer* mainLayer = compositedLayerMapping->childForSuperlayers();
+    GraphicsLayer* mainLayer = compositedLayerMapping->localRootForOwningLayer();
 
     // Avoid unnecessary commits
     clearPositionConstraintExceptForLayer(compositedLayerMapping->ancestorClippingLayer(), mainLayer);
@@ -250,7 +267,7 @@
     scrollbarGraphicsLayer->setDrawsContent(true);
 }
 
-static void setupScrollbarLayer(GraphicsLayer* scrollbarGraphicsLayer, WebScrollbarLayer* scrollbarLayer, WebLayer* scrollLayer)
+static void setupScrollbarLayer(GraphicsLayer* scrollbarGraphicsLayer, WebScrollbarLayer* scrollbarLayer, WebLayer* scrollLayer, WebLayer* containerLayer)
 {
     ASSERT(scrollbarGraphicsLayer);
     ASSERT(scrollbarLayer);
@@ -260,6 +277,7 @@
         return;
     }
     scrollbarLayer->setScrollLayer(scrollLayer);
+    scrollbarLayer->setClipLayer(containerLayer);
     scrollbarGraphicsLayer->setContentsToPlatformLayer(scrollbarLayer->layer());
     scrollbarGraphicsLayer->setDrawsContent(false);
 }
@@ -267,7 +285,7 @@
 WebScrollbarLayer* ScrollingCoordinator::addWebScrollbarLayer(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, PassOwnPtr<blink::WebScrollbarLayer> scrollbarLayer)
 {
     ScrollbarMap& scrollbars = orientation == HorizontalScrollbar ? m_horizontalScrollbars : m_verticalScrollbars;
-    return scrollbars.add(scrollableArea, scrollbarLayer).iterator->value.get();
+    return scrollbars.add(scrollableArea, scrollbarLayer).storedValue->value.get();
 }
 
 WebScrollbarLayer* ScrollingCoordinator::getWebScrollbarLayer(ScrollableArea* scrollableArea, ScrollbarOrientation orientation)
@@ -325,7 +343,9 @@
             scrollbarGraphicsLayer->setContentsOpaque(isMainFrame && isOpaqueScrollbar);
         scrollbarLayer->layer()->setOpaque(scrollbarGraphicsLayer->contentsOpaque());
 
-        setupScrollbarLayer(scrollbarGraphicsLayer, scrollbarLayer, scrollingWebLayerForScrollableArea(scrollableArea));
+        WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(scrollableArea);
+        WebLayer* containerLayer = containerWebLayerForScrollableArea(scrollableArea);
+        setupScrollbarLayer(scrollbarGraphicsLayer, scrollbarLayer, scrollLayer, containerLayer);
     } else
         removeWebScrollbarLayer(scrollableArea, orientation);
 }
@@ -339,10 +359,11 @@
     }
 
     WebLayer* webLayer = scrollingWebLayerForScrollableArea(scrollableArea);
+    WebLayer* containerLayer = containerWebLayerForScrollableArea(scrollableArea);
     if (webLayer) {
-        webLayer->setScrollable(true);
+        webLayer->setScrollClipLayer(containerLayer);
         webLayer->setScrollPosition(IntPoint(scrollableArea->scrollPosition() - scrollableArea->minimumScrollPosition()));
-        webLayer->setMaxScrollPosition(IntSize(scrollableArea->scrollSize(HorizontalScrollbar), scrollableArea->scrollSize(VerticalScrollbar)));
+        webLayer->setBounds(scrollableArea->contentsSize());
         bool canScrollX = scrollableArea->userInputScrollable(HorizontalScrollbar);
         bool canScrollY = scrollableArea->userInputScrollable(VerticalScrollbar);
         webLayer->setUserScrollable(canScrollX, canScrollY);
@@ -350,12 +371,12 @@
     if (WebScrollbarLayer* scrollbarLayer = getWebScrollbarLayer(scrollableArea, HorizontalScrollbar)) {
         GraphicsLayer* horizontalScrollbarLayer = horizontalScrollbarLayerForScrollableArea(scrollableArea);
         if (horizontalScrollbarLayer)
-            setupScrollbarLayer(horizontalScrollbarLayer, scrollbarLayer, webLayer);
+            setupScrollbarLayer(horizontalScrollbarLayer, scrollbarLayer, webLayer, containerLayer);
     }
     if (WebScrollbarLayer* scrollbarLayer = getWebScrollbarLayer(scrollableArea, VerticalScrollbar)) {
         GraphicsLayer* verticalScrollbarLayer = verticalScrollbarLayerForScrollableArea(scrollableArea);
         if (verticalScrollbarLayer)
-            setupScrollbarLayer(verticalScrollbarLayer, scrollbarLayer, webLayer);
+            setupScrollbarLayer(verticalScrollbarLayer, scrollbarLayer, webLayer, containerLayer);
     }
 
     return !!webLayer;
@@ -374,8 +395,9 @@
         const RenderLayer* containingLayer = child->ownerRenderer()->enclosingLayer();
         LayerFrameMap::iterator iter = map->find(containingLayer);
         if (iter == map->end())
-            iter = map->add(containingLayer, Vector<const Frame*>()).iterator;
-        iter->value.append(child);
+            map->add(containingLayer, Vector<const Frame*>()).storedValue->value.append(child);
+        else
+            iter->value.append(child);
     }
 }
 
@@ -409,8 +431,11 @@
         }
 
         LayerHitTestRects::iterator compIter = compositorRects.find(compositedLayer);
+        Vector<LayoutRect>* compIterValue;
         if (compIter == compositorRects.end())
-            compIter = compositorRects.add(compositedLayer, Vector<LayoutRect>()).iterator;
+            compIterValue = &compositorRects.add(compositedLayer, Vector<LayoutRect>()).storedValue->value;
+        else
+            compIterValue = &compIter->value;
         // Transform each rect to the co-ordinate space of it's enclosing composited layer.
         for (size_t i = 0; i < layerIter->value.size(); ++i) {
             LayoutRect rect = layerIter->value[i];
@@ -423,7 +448,7 @@
                 if (compositedLayer->renderer()->hasOverflowClip())
                     rect.move(compositedLayer->renderBox()->scrolledContentOffset());
             }
-            compIter->value.append(rect);
+            compIterValue->append(rect);
         }
     }
 
@@ -482,10 +507,12 @@
     MapCoordinatesFlags flags = UseTransforms;
     if (touchHandlerInChildFrame)
         flags |= TraverseDocumentBoundaries;
+    RenderLayer* rootLayer = mainFrame->contentRenderer()->layer();
     RenderGeometryMap geometryMap(flags);
+    geometryMap.pushMappingsToAncestor(rootLayer, 0);
     LayerFrameMap layerChildFrameMap;
     makeLayerChildFrameMap(mainFrame, &layerChildFrameMap);
-    convertLayerRectsToEnclosingCompositedLayerRecursive(mainFrame->contentRenderer()->layer(), layerRects, compositorRects, geometryMap, layersWithRects, layerChildFrameMap);
+    convertLayerRectsToEnclosingCompositedLayerRecursive(rootLayer, layerRects, compositorRects, geometryMap, layersWithRects, layerChildFrameMap);
 }
 
 void ScrollingCoordinator::updateTouchEventTargetRectsIfNeeded()
@@ -557,7 +584,7 @@
     }
 }
 
-void ScrollingCoordinator::touchEventTargetRectsDidChange(const Document*)
+void ScrollingCoordinator::touchEventTargetRectsDidChange()
 {
     if (!touchHitTestingEnabled())
         return;
@@ -731,8 +758,24 @@
                 if (targets->contains(ancestor))
                     hasTouchEventTargetAncestor = true;
             }
-            if (!hasTouchEventTargetAncestor)
+            if (!hasTouchEventTargetAncestor) {
+                // Walk up the tree to the outermost non-composited scrollable layer.
+                RenderLayer* enclosingNonCompositedScrollLayer = 0;
+                for (RenderLayer* parent = renderer->enclosingLayer(); parent && parent->compositingState() == NotComposited; parent = parent->parent()) {
+                    if (parent->scrollsOverflow())
+                        enclosingNonCompositedScrollLayer = parent;
+                }
+
+                // Report the whole non-composited scroll layer as a touch hit rect because any
+                // rects inside of it may move around relative to their enclosing composited layer
+                // without causing the rects to be recomputed. Non-composited scrolling occurs on
+                // the main thread, so we're not getting much benefit from compositor touch hit
+                // testing in this case anyway.
+                if (enclosingNonCompositedScrollLayer)
+                    enclosingNonCompositedScrollLayer->computeSelfHitTestRects(rects);
+
                 renderer->computeLayerHitTestRects(rects);
+            }
         }
     }
 
@@ -778,7 +821,7 @@
     if (!coordinatesScrollingForFrameView(frameView))
         return;
 
-    updateShouldUpdateScrollLayerPositionOnMainThread();
+    m_shouldScrollOnMainThreadDirty = true;
 }
 
 void ScrollingCoordinator::frameViewFixedObjectsDidChange(FrameView* frameView)
@@ -789,7 +832,7 @@
     if (!coordinatesScrollingForFrameView(frameView))
         return;
 
-    updateShouldUpdateScrollLayerPositionOnMainThread();
+    m_shouldScrollOnMainThreadDirty = true;
 }
 
 GraphicsLayer* ScrollingCoordinator::scrollLayerForScrollableArea(ScrollableArea* scrollableArea)
@@ -835,7 +878,6 @@
 
     notifyLayoutUpdated();
     recomputeWheelEventHandlerCountForFrameView(frameView);
-    updateShouldUpdateScrollLayerPositionOnMainThread();
 }
 
 #if OS(MACOSX)
@@ -883,7 +925,7 @@
     // frame. If it does not exist or if it is not scrollable, there is no
     // reason to force main thread scrolling.
     FrameView* frameView = m_page->mainFrame()->view();
-    if (!frameView || !frameView->isScrollable())
+    if (!frameView)
         return static_cast<MainThreadScrollingReasons>(0);
 
     MainThreadScrollingReasons mainThreadScrollingReasons = (MainThreadScrollingReasons)0;
@@ -896,11 +938,6 @@
     return mainThreadScrollingReasons;
 }
 
-void ScrollingCoordinator::updateShouldUpdateScrollLayerPositionOnMainThread()
-{
-    setShouldUpdateScrollLayerPositionOnMainThread(mainThreadScrollingReasons());
-}
-
 String ScrollingCoordinator::mainThreadScrollingReasonsAsText(MainThreadScrollingReasons reasons)
 {
     StringBuilder stringBuilder;
@@ -919,14 +956,20 @@
 
 String ScrollingCoordinator::mainThreadScrollingReasonsAsText() const
 {
+    ASSERT(m_page->mainFrame()->document()->lifecycle().state() >= DocumentLifecycle::CompositingClean);
     return mainThreadScrollingReasonsAsText(m_lastMainThreadScrollingReasons);
 }
 
-bool ScrollingCoordinator::frameViewIsScrollableIsDirty() const
+bool ScrollingCoordinator::frameViewIsDirty() const
 {
     FrameView* frameView = m_page->mainFrame()->view();
     bool frameIsScrollable = frameView && frameView->isScrollable();
-    return frameIsScrollable != m_wasFrameScrollable;
+    if (frameIsScrollable != m_wasFrameScrollable)
+        return true;
+
+    if (WebLayer* scrollLayer = frameView ? scrollingWebLayerForScrollableArea(frameView) : 0)
+        return blink::WebSize(frameView->contentsSize()) != scrollLayer->bounds();
+    return false;
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.h b/Source/core/page/scrolling/ScrollingCoordinator.h
index 3acfe9a..cad3ee5 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.h
+++ b/Source/core/page/scrolling/ScrollingCoordinator.h
@@ -50,9 +50,9 @@
 class ScrollableArea;
 class ViewportConstraints;
 
-class ScrollingCoordinator : public RefCounted<ScrollingCoordinator> {
+class ScrollingCoordinator {
 public:
-    static PassRefPtr<ScrollingCoordinator> create(Page*);
+    static PassOwnPtr<ScrollingCoordinator> create(Page*);
     ~ScrollingCoordinator();
 
     void pageDestroyed();
@@ -66,7 +66,7 @@
     // Should be called after compositing has been updated.
     void updateAfterCompositingChange();
 
-    bool needsToUpdateAfterCompositingChange() const { return m_scrollGestureRegionIsDirty || m_touchEventTargetRectsAreDirty || frameViewIsScrollableIsDirty(); }
+    bool needsToUpdateAfterCompositingChange() const { return m_scrollGestureRegionIsDirty || m_touchEventTargetRectsAreDirty || frameViewIsDirty(); }
 
     // Should be called whenever a wheel event handler is added or removed in the
     // frame view's underlying document.
@@ -103,7 +103,7 @@
     void scrollableAreaScrollbarLayerDidChange(ScrollableArea*, ScrollbarOrientation);
     void setLayerIsContainerForFixedPositionLayers(GraphicsLayer*, bool);
     void updateLayerPositionConstraint(RenderLayer*);
-    void touchEventTargetRectsDidChange(const Document*);
+    void touchEventTargetRectsDidChange();
     void willDestroyRenderLayer(RenderLayer*);
 
     void updateScrollParentForGraphicsLayer(GraphicsLayer* child, RenderLayer* parent);
@@ -136,15 +136,16 @@
     // Dirty flags used to idenfity what really needs to be computed after compositing is updated.
     bool m_scrollGestureRegionIsDirty;
     bool m_touchEventTargetRectsAreDirty;
+    bool m_shouldScrollOnMainThreadDirty;
 
 private:
     void recomputeWheelEventHandlerCountForFrameView(FrameView*);
     void setShouldUpdateScrollLayerPositionOnMainThread(MainThreadScrollingReasons);
 
     bool hasVisibleSlowRepaintViewportConstrainedObjects(FrameView*) const;
-    void updateShouldUpdateScrollLayerPositionOnMainThread();
 
     static blink::WebLayer* scrollingWebLayerForScrollableArea(ScrollableArea*);
+    static blink::WebLayer* containerWebLayerForScrollableArea(ScrollableArea*);
 
     bool touchHitTestingEnabled() const;
     void setShouldHandleScrollGestureOnMainThreadRegion(const Region&);
@@ -156,7 +157,7 @@
     blink::WebScrollbarLayer* getWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation);
     void removeWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation);
 
-    bool frameViewIsScrollableIsDirty() const;
+    bool frameViewIsDirty() const;
 
     typedef HashMap<ScrollableArea*, OwnPtr<blink::WebScrollbarLayer> > ScrollbarMap;
     ScrollbarMap m_horizontalScrollbars;
diff --git a/Source/core/platform/CryptoResult.h b/Source/core/platform/CryptoResult.h
deleted file mode 100644
index 45aaef5..0000000
--- a/Source/core/platform/CryptoResult.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef CryptoResult_h
-#define CryptoResult_h
-
-#include "public/platform/WebCrypto.h"
-#include "wtf/ThreadSafeRefCounted.h"
-
-namespace WebCore {
-
-// Receives notification of completion of the crypto operation.
-class CryptoResult : public ThreadSafeRefCounted<CryptoResult> {
-public:
-    virtual ~CryptoResult() { }
-
-    virtual void completeWithError() = 0;
-    virtual void completeWithBuffer(const blink::WebArrayBuffer&) = 0;
-    virtual void completeWithBoolean(bool) = 0;
-    virtual void completeWithKey(const blink::WebCryptoKey&) = 0;
-    virtual void completeWithKeyPair(const blink::WebCryptoKey& publicKey, const blink::WebCryptoKey& privateKey) = 0;
-
-    blink::WebCryptoResult result()
-    {
-        return blink::WebCryptoResult(this);
-    }
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/DEPS b/Source/core/platform/DEPS
deleted file mode 100644
index 80d631a..0000000
--- a/Source/core/platform/DEPS
+++ /dev/null
@@ -1,17 +0,0 @@
-# This file dictates which directories can be included in the source files of this folder.
-# Please run Tools/Scripts/check-blink-deps after modifying this file.
-
-include_rules = [
-    "-core",
-    "+core/platform",
-    "+dl",
-    "+skia",
-    "+third_party",
-    # platform/ shouldn't depends on core/ but unfortunately does (crbug.com/258901).
-    # Please don't add anything to this list of exceptions.
-    "!core/dom",
-    "!core/fileapi",
-    "!core/html",
-    "!core/fetch",
-    "!core/rendering",
-]
diff --git a/Source/core/platform/DragImage.cpp b/Source/core/platform/DragImage.cpp
deleted file mode 100644
index 22d3f17..0000000
--- a/Source/core/platform/DragImage.cpp
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc.  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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-#include "core/platform/DragImage.h"
-
-#include "platform/fonts/Font.h"
-#include "platform/fonts/FontCache.h"
-#include "platform/fonts/FontDescription.h"
-#include "platform/fonts/FontMetrics.h"
-#include "platform/geometry/FloatPoint.h"
-#include "platform/geometry/FloatRect.h"
-#include "platform/geometry/IntPoint.h"
-#include "platform/graphics/BitmapImage.h"
-#include "platform/graphics/Color.h"
-#include "platform/graphics/GraphicsContext.h"
-#include "platform/graphics/Image.h"
-#include "platform/graphics/ImageBuffer.h"
-#include "platform/graphics/skia/NativeImageSkia.h"
-#include "platform/text/StringTruncator.h"
-#include "platform/text/TextRun.h"
-#include "platform/transforms/AffineTransform.h"
-#include "platform/weborigin/KURL.h"
-#include "skia/ext/image_operations.h"
-#include "third_party/skia/include/core/SkCanvas.h"
-#include "third_party/skia/include/core/SkMatrix.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-#include <algorithm>
-
-namespace WebCore {
-
-const float kDragLabelBorderX = 4;
-// Keep border_y in synch with DragController::LinkDragBorderInset.
-const float kDragLabelBorderY = 2;
-const float kLabelBorderYOffset = 2;
-
-const float kMaxDragLabelWidth = 300;
-const float kMaxDragLabelStringWidth = (kMaxDragLabelWidth - 2 * kDragLabelBorderX);
-
-const float kDragLinkLabelFontSize = 11;
-const float kDragLinkUrlFontSize = 10;
-
-PassOwnPtr<DragImage> DragImage::create(Image* image, RespectImageOrientationEnum shouldRespectImageOrientation)
-{
-    if (!image)
-        return nullptr;
-
-    RefPtr<NativeImageSkia> bitmap = image->nativeImageForCurrentFrame();
-    if (!bitmap)
-        return nullptr;
-
-    if (image->isBitmapImage()) {
-        ImageOrientation orientation = DefaultImageOrientation;
-        BitmapImage* bitmapImage = toBitmapImage(image);
-        IntSize sizeRespectingOrientation = bitmapImage->sizeRespectingOrientation();
-
-        if (shouldRespectImageOrientation == RespectImageOrientation)
-            orientation = bitmapImage->currentFrameOrientation();
-
-        if (orientation != DefaultImageOrientation) {
-            FloatRect destRect(FloatPoint(), sizeRespectingOrientation);
-            if (orientation.usesWidthAsHeight())
-                destRect = destRect.transposedRect();
-
-            SkBitmap skBitmap;
-            skBitmap.setConfig(
-                SkBitmap::kARGB_8888_Config, sizeRespectingOrientation.width(), sizeRespectingOrientation.height());
-            if (!skBitmap.allocPixels())
-                return nullptr;
-
-            SkCanvas canvas(skBitmap);
-            canvas.concat(affineTransformToSkMatrix(orientation.transformFromDefault(sizeRespectingOrientation)));
-            canvas.drawBitmapRect(bitmap->bitmap(), 0, destRect);
-
-            return adoptPtr(new DragImage(skBitmap, bitmap->resolutionScale()));
-        }
-    }
-
-    SkBitmap skBitmap;
-    if (!bitmap->bitmap().copyTo(&skBitmap, SkBitmap::kARGB_8888_Config))
-        return nullptr;
-    return adoptPtr(new DragImage(skBitmap, bitmap->resolutionScale()));
-}
-
-static Font deriveDragLabelFont(int size, FontWeight fontWeight, const FontDescription& systemFont)
-{
-    FontDescription description = systemFont;
-    description.setWeight(fontWeight);
-    description.setSpecifiedSize(size);
-    description.setComputedSize(size);
-    Font result(description, 0, 0);
-    result.update(0);
-    return result;
-}
-
-PassOwnPtr<DragImage> DragImage::create(const KURL& url, const String& inLabel, const FontDescription& systemFont, float deviceScaleFactor)
-{
-    const Font labelFont = deriveDragLabelFont(kDragLinkLabelFontSize, FontWeightBold, systemFont);
-    const Font urlFont = deriveDragLabelFont(kDragLinkUrlFontSize, FontWeightNormal, systemFont);
-    FontCachePurgePreventer fontCachePurgePreventer;
-
-    bool drawURLString = true;
-    bool clipURLString = false;
-    bool clipLabelString = false;
-
-    String urlString = url.string();
-    String label = inLabel;
-    if (label.isEmpty()) {
-        drawURLString = false;
-        label = urlString;
-    }
-
-    // First step is drawing the link drag image width.
-    TextRun labelRun(label.impl());
-    TextRun urlRun(urlString.impl());
-    IntSize labelSize(labelFont.width(labelRun), labelFont.fontMetrics().ascent() + labelFont.fontMetrics().descent());
-
-    if (labelSize.width() > kMaxDragLabelStringWidth) {
-        labelSize.setWidth(kMaxDragLabelStringWidth);
-        clipLabelString = true;
-    }
-
-    IntSize urlStringSize;
-    IntSize imageSize(labelSize.width() + kDragLabelBorderX * 2, labelSize.height() + kDragLabelBorderY * 2);
-
-    if (drawURLString) {
-        urlStringSize.setWidth(urlFont.width(urlRun));
-        urlStringSize.setHeight(urlFont.fontMetrics().ascent() + urlFont.fontMetrics().descent());
-        imageSize.setHeight(imageSize.height() + urlStringSize.height());
-        if (urlStringSize.width() > kMaxDragLabelStringWidth) {
-            imageSize.setWidth(kMaxDragLabelWidth);
-            clipURLString = true;
-        } else
-            imageSize.setWidth(std::max(labelSize.width(), urlStringSize.width()) + kDragLabelBorderX * 2);
-    }
-
-    // We now know how big the image needs to be, so we create and
-    // fill the background
-    IntSize scaledImageSize = imageSize;
-    scaledImageSize.scale(deviceScaleFactor);
-    OwnPtr<ImageBuffer> buffer(ImageBuffer::create(scaledImageSize));
-    if (!buffer)
-        return nullptr;
-    buffer->context()->scale(FloatSize(deviceScaleFactor, deviceScaleFactor));
-
-    const float DragLabelRadius = 5;
-    const IntSize radii(DragLabelRadius, DragLabelRadius);
-    IntRect rect(IntPoint(), imageSize);
-    const Color backgroundColor(140, 140, 140);
-    buffer->context()->fillRoundedRect(rect, radii, radii, radii, radii, backgroundColor);
-
-    // Draw the text
-    if (drawURLString) {
-        if (clipURLString)
-            urlString = StringTruncator::centerTruncate(urlString, imageSize.width() - (kDragLabelBorderX * 2.0f), urlFont, StringTruncator::EnableRoundingHacks);
-        IntPoint textPos(kDragLabelBorderX, imageSize.height() - (kLabelBorderYOffset + urlFont.fontMetrics().descent()));
-        TextRun textRun(urlString);
-        buffer->context()->drawText(urlFont, TextRunPaintInfo(textRun), textPos);
-    }
-
-    if (clipLabelString)
-        label = StringTruncator::rightTruncate(label, imageSize.width() - (kDragLabelBorderX * 2.0f), labelFont, StringTruncator::EnableRoundingHacks);
-
-    IntPoint textPos(kDragLabelBorderX, kDragLabelBorderY + labelFont.pixelSize());
-    TextRun textRun(label);
-    buffer->context()->drawText(urlFont, TextRunPaintInfo(textRun), textPos);
-
-    RefPtr<Image> image = buffer->copyImage();
-    return DragImage::create(image.get());
-}
-
-DragImage::DragImage(const SkBitmap& bitmap, float resolutionScale)
-    : m_bitmap(bitmap)
-    , m_resolutionScale(resolutionScale)
-{
-}
-
-DragImage::~DragImage()
-{
-}
-
-void DragImage::fitToMaxSize(const IntSize& srcSize, const IntSize& maxSize)
-{
-    float heightResizeRatio = 0.0f;
-    float widthResizeRatio = 0.0f;
-    float resizeRatio = -1.0f;
-    IntSize originalSize = size();
-
-    if (srcSize.width() > maxSize.width()) {
-        widthResizeRatio = maxSize.width() / static_cast<float>(srcSize.width());
-        resizeRatio = widthResizeRatio;
-    }
-
-    if (srcSize.height() > maxSize.height()) {
-        heightResizeRatio = maxSize.height() / static_cast<float>(srcSize.height());
-        if ((resizeRatio < 0.0f) || (resizeRatio > heightResizeRatio))
-            resizeRatio = heightResizeRatio;
-    }
-
-    if (srcSize == originalSize) {
-        if (resizeRatio > 0.0f)
-            scale(resizeRatio, resizeRatio);
-        return;
-    }
-
-    // The image was scaled in the webpage so at minimum we must account for that scaling
-    float scaleX = srcSize.width() / static_cast<float>(originalSize.width());
-    float scaleY = srcSize.height() / static_cast<float>(originalSize.height());
-    if (resizeRatio > 0.0f) {
-        scaleX *= resizeRatio;
-        scaleY *= resizeRatio;
-    }
-
-    scale(scaleX, scaleY);
-}
-
-void DragImage::scale(float scaleX, float scaleY)
-{
-    int imageWidth = scaleX * m_bitmap.width();
-    int imageHeight = scaleY * m_bitmap.height();
-    m_bitmap = skia::ImageOperations::Resize(
-        m_bitmap, skia::ImageOperations::RESIZE_LANCZOS3, imageWidth, imageHeight);
-}
-
-void DragImage::dissolveToFraction(float fraction)
-{
-    m_bitmap.setAlphaType(kPremul_SkAlphaType);
-    SkAutoLockPixels lock(m_bitmap);
-
-    for (int row = 0; row < m_bitmap.height(); ++row) {
-        for (int column = 0; column < m_bitmap.width(); ++column) {
-            uint32_t* pixel = m_bitmap.getAddr32(column, row);
-            *pixel = SkPreMultiplyARGB(
-                SkColorGetA(*pixel) * fraction,
-                SkColorGetR(*pixel),
-                SkColorGetG(*pixel),
-                SkColorGetB(*pixel));
-        }
-    }
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/DragImage.h b/Source/core/platform/DragImage.h
deleted file mode 100644
index 72f969e..0000000
--- a/Source/core/platform/DragImage.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc.  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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef DragImage_h
-#define DragImage_h
-
-#include "platform/geometry/IntSize.h"
-#include "platform/graphics/ImageOrientation.h"
-#include "third_party/skia/include/core/SkBitmap.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class FontDescription;
-class Image;
-class KURL;
-
-class DragImage {
-public:
-    static PassOwnPtr<DragImage> create(Image*, RespectImageOrientationEnum = DoNotRespectImageOrientation);
-    static PassOwnPtr<DragImage> create(const KURL&, const String& label, const FontDescription& systemFont, float deviceScaleFactor);
-    ~DragImage();
-
-    const SkBitmap& bitmap() { return m_bitmap; }
-    float resolutionScale() const { return m_resolutionScale; }
-    IntSize size() const { return IntSize(m_bitmap.width(), m_bitmap.height()); }
-
-    void fitToMaxSize(const IntSize& srcSize, const IntSize& maxSize);
-    void scale(float scaleX, float scaleY);
-    void dissolveToFraction(float fraction);
-
-private:
-    DragImage(const SkBitmap&, float resolutionScale);
-
-    SkBitmap m_bitmap;
-    float m_resolutionScale;
-};
-
-}
-
-#endif // DragImage_h
diff --git a/Source/core/platform/PopupMenuClient.h b/Source/core/platform/PopupMenuClient.h
deleted file mode 100644
index 74da471..0000000
--- a/Source/core/platform/PopupMenuClient.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
- * Copyright (C) 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef PopupMenuClient_h
-#define PopupMenuClient_h
-
-#include "core/platform/PopupMenuStyle.h"
-#include "platform/LayoutUnit.h"
-#include "platform/scroll/ScrollTypes.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class Color;
-class FontSelector;
-class HostWindow;
-class Scrollbar;
-class ScrollableArea;
-
-class PopupMenuClient {
-public:
-    virtual ~PopupMenuClient() {}
-    virtual void valueChanged(unsigned listIndex, bool fireEvents = true) = 0;
-    virtual void selectionChanged(unsigned listIndex, bool fireEvents = true) = 0;
-    virtual void selectionCleared() = 0;
-
-    virtual String itemText(unsigned listIndex) const = 0;
-    virtual String itemLabel(unsigned listIndex) const = 0;
-    virtual String itemIcon(unsigned listIndex) const = 0;
-    virtual String itemToolTip(unsigned listIndex) const = 0;
-    virtual String itemAccessibilityText(unsigned listIndex) const = 0;
-    virtual bool itemIsEnabled(unsigned listIndex) const = 0;
-    virtual PopupMenuStyle itemStyle(unsigned listIndex) const = 0;
-    virtual PopupMenuStyle menuStyle() const = 0;
-    virtual int clientInsetLeft() const = 0;
-    virtual int clientInsetRight() const = 0;
-    virtual LayoutUnit clientPaddingLeft() const = 0;
-    virtual LayoutUnit clientPaddingRight() const = 0;
-    virtual int listSize() const = 0;
-    virtual int selectedIndex() const = 0;
-    virtual void popupDidHide() = 0;
-    virtual bool itemIsSeparator(unsigned listIndex) const = 0;
-    virtual bool itemIsLabel(unsigned listIndex) const = 0;
-    virtual bool itemIsSelected(unsigned listIndex) const = 0;
-    virtual bool valueShouldChangeOnHotTrack() const = 0;
-    virtual void setTextFromItem(unsigned listIndex) = 0;
-
-    virtual void listBoxSelectItem(int /*listIndex*/, bool /*allowMultiplySelections*/, bool /*shift*/, bool /*fireOnChangeNow*/ = true) { ASSERT_NOT_REACHED(); }
-    virtual bool multiple() const
-    {
-        ASSERT_NOT_REACHED();
-        return false;
-    }
-
-    virtual FontSelector* fontSelector() const = 0;
-    virtual HostWindow* hostWindow() const = 0;
-
-    virtual PassRefPtr<Scrollbar> createScrollbar(ScrollableArea*, ScrollbarOrientation, ScrollbarControlSize) = 0;
-};
-
-}
-
-#endif
diff --git a/Source/core/platform/PopupMenuStyle.h b/Source/core/platform/PopupMenuStyle.h
deleted file mode 100644
index 8386531..0000000
--- a/Source/core/platform/PopupMenuStyle.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2008, 2011 Apple Inc.  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 APPLE INC. ``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 APPLE INC. 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.
- */
-
-#ifndef PopupMenuStyle_h
-#define PopupMenuStyle_h
-
-#include "platform/Length.h"
-#include "platform/fonts/Font.h"
-#include "platform/graphics/Color.h"
-#include "platform/text/TextDirection.h"
-
-namespace WebCore {
-
-class PopupMenuStyle {
-public:
-    enum PopupMenuType { SelectPopup, AutofillPopup };
-    enum BackgroundColorType { DefaultBackgroundColor, CustomBackgroundColor };
-    PopupMenuStyle(const Color& foreground, const Color& background, const Font& font, bool visible, bool isDisplayNone, Length textIndent, TextDirection textDirection, bool hasTextDirectionOverride, BackgroundColorType backgroundColorType = DefaultBackgroundColor, PopupMenuType menuType = SelectPopup)
-        : m_foregroundColor(foreground)
-        , m_backgroundColor(background)
-        , m_font(font)
-        , m_visible(visible)
-        , m_isDisplayNone(isDisplayNone)
-        , m_textIndent(textIndent)
-        , m_textDirection(textDirection)
-        , m_hasTextDirectionOverride(hasTextDirectionOverride)
-        , m_backgroundColorType(backgroundColorType)
-        , m_menuType(menuType)
-    {
-    }
-
-    const Color& foregroundColor() const { return m_foregroundColor; }
-    const Color& backgroundColor() const { return m_backgroundColor; }
-    const Font& font() const { return m_font; }
-    bool isVisible() const { return m_visible; }
-    bool isDisplayNone() const { return m_isDisplayNone; }
-    Length textIndent() const { return m_textIndent; }
-    TextDirection textDirection() const { return m_textDirection; }
-    bool hasTextDirectionOverride() const { return m_hasTextDirectionOverride; }
-    BackgroundColorType backgroundColorType() const { return m_backgroundColorType; }
-    PopupMenuType menuType() const { return m_menuType; }
-private:
-    Color m_foregroundColor;
-    Color m_backgroundColor;
-    Font m_font;
-    bool m_visible;
-    bool m_isDisplayNone;
-    Length m_textIndent;
-    TextDirection m_textDirection;
-    bool m_hasTextDirectionOverride;
-    BackgroundColorType m_backgroundColorType;
-    PopupMenuType m_menuType;
-};
-
-} // namespace WebCore
-
-#endif // PopupMenuStyle_h
diff --git a/Source/core/platform/animation/AnimationTranslationUtil.cpp b/Source/core/platform/animation/AnimationTranslationUtil.cpp
deleted file mode 100644
index cbb7c79..0000000
--- a/Source/core/platform/animation/AnimationTranslationUtil.cpp
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-#include "config.h"
-
-#include "core/platform/animation/AnimationTranslationUtil.h"
-
-#include "core/platform/animation/CSSAnimationData.h"
-#include "core/platform/animation/KeyframeValueList.h"
-#include "platform/LengthFunctions.h"
-#include "platform/geometry/FloatSize.h"
-#include "platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "platform/transforms/InterpolatedTransformOperation.h"
-#include "platform/transforms/Matrix3DTransformOperation.h"
-#include "platform/transforms/MatrixTransformOperation.h"
-#include "platform/transforms/PerspectiveTransformOperation.h"
-#include "platform/transforms/RotateTransformOperation.h"
-#include "platform/transforms/ScaleTransformOperation.h"
-#include "platform/transforms/SkewTransformOperation.h"
-#include "platform/transforms/TransformationMatrix.h"
-#include "platform/transforms/TranslateTransformOperation.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebAnimation.h"
-#include "public/platform/WebAnimationCurve.h"
-#include "public/platform/WebCompositorSupport.h"
-#include "public/platform/WebFilterAnimationCurve.h"
-#include "public/platform/WebFloatAnimationCurve.h"
-#include "public/platform/WebTransformAnimationCurve.h"
-
-#include "wtf/OwnPtr.h"
-#include "wtf/text/CString.h"
-
-using namespace std;
-using namespace blink;
-
-namespace WebCore {
-
-void toWebTransformOperations(const TransformOperations& transformOperations, const FloatSize& boxSize, WebTransformOperations* webTransformOperations)
-{
-    // We need to do a deep copy the transformOperations may contain ref pointers to TransformOperation objects.
-    for (size_t j = 0; j < transformOperations.size(); ++j) {
-        switch (transformOperations.operations()[j]->type()) {
-        case TransformOperation::ScaleX:
-        case TransformOperation::ScaleY:
-        case TransformOperation::ScaleZ:
-        case TransformOperation::Scale3D:
-        case TransformOperation::Scale: {
-            ScaleTransformOperation* transform = static_cast<ScaleTransformOperation*>(transformOperations.operations()[j].get());
-            webTransformOperations->appendScale(transform->x(), transform->y(), transform->z());
-            break;
-        }
-        case TransformOperation::TranslateX:
-        case TransformOperation::TranslateY:
-        case TransformOperation::TranslateZ:
-        case TransformOperation::Translate3D:
-        case TransformOperation::Translate: {
-            TranslateTransformOperation* transform = static_cast<TranslateTransformOperation*>(transformOperations.operations()[j].get());
-            webTransformOperations->appendTranslate(floatValueForLength(transform->x(), boxSize.width()), floatValueForLength(transform->y(), boxSize.height()), floatValueForLength(transform->z(), 1));
-            break;
-        }
-        case TransformOperation::RotateX:
-        case TransformOperation::RotateY:
-        case TransformOperation::Rotate3D:
-        case TransformOperation::Rotate: {
-            RotateTransformOperation* transform = static_cast<RotateTransformOperation*>(transformOperations.operations()[j].get());
-            webTransformOperations->appendRotate(transform->x(), transform->y(), transform->z(), transform->angle());
-            break;
-        }
-        case TransformOperation::SkewX:
-        case TransformOperation::SkewY:
-        case TransformOperation::Skew: {
-            SkewTransformOperation* transform = static_cast<SkewTransformOperation*>(transformOperations.operations()[j].get());
-            webTransformOperations->appendSkew(transform->angleX(), transform->angleY());
-            break;
-        }
-        case TransformOperation::Matrix: {
-            MatrixTransformOperation* transform = static_cast<MatrixTransformOperation*>(transformOperations.operations()[j].get());
-            TransformationMatrix m = transform->matrix();
-            webTransformOperations->appendMatrix(TransformationMatrix::toSkMatrix44(m));
-            break;
-        }
-        case TransformOperation::Matrix3D: {
-            Matrix3DTransformOperation* transform = static_cast<Matrix3DTransformOperation*>(transformOperations.operations()[j].get());
-            TransformationMatrix m = transform->matrix();
-            webTransformOperations->appendMatrix(TransformationMatrix::toSkMatrix44(m));
-            break;
-        }
-        case TransformOperation::Perspective: {
-            PerspectiveTransformOperation* transform = static_cast<PerspectiveTransformOperation*>(transformOperations.operations()[j].get());
-            webTransformOperations->appendPerspective(floatValueForLength(transform->perspective(), 0));
-            break;
-        }
-        case TransformOperation::Interpolated: {
-            TransformationMatrix m;
-            transformOperations.operations()[j]->apply(m, boxSize);
-            webTransformOperations->appendMatrix(TransformationMatrix::toSkMatrix44(m));
-            break;
-        }
-        case TransformOperation::Identity:
-            webTransformOperations->appendIdentity();
-            break;
-        case TransformOperation::None:
-            // Do nothing.
-            break;
-        } // switch
-    } // for each operation
-}
-
-template <class Value, class Keyframe, class Curve>
-bool appendKeyframeWithStandardTimingFunction(Curve* curve, double keyTime, const Value* value, const Value* lastValue, blink::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize&)
-{
-    curve->add(Keyframe(keyTime, value->value()), timingFunctionType);
-    return true;
-}
-
-template <class Value, class Keyframe, class Curve>
-bool appendKeyframeWithCustomBezierTimingFunction(Curve* curve, double keyTime, const Value* value, const Value* lastValue, double x1, double y1, double x2, double y2, const FloatSize&)
-{
-    curve->add(Keyframe(keyTime, value->value()), x1, y1, x2, y2);
-    return true;
-}
-
-template <>
-bool appendKeyframeWithStandardTimingFunction<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(WebTransformAnimationCurve* curve, double keyTime, const TransformAnimationValue* value, const TransformAnimationValue* lastValue, blink::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize& boxSize)
-{
-    bool canBlend = !lastValue;
-    OwnPtr<WebTransformOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
-    if (!operations)
-        return false;
-    toWebTransformOperations(*value->value(), boxSize, operations.get());
-    if (!canBlend) {
-        OwnPtr<WebTransformOperations> lastOperations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
-        if (!lastOperations)
-            return false;
-        toWebTransformOperations(*lastValue->value(), boxSize, lastOperations.get());
-        canBlend = lastOperations->canBlendWith(*operations);
-    }
-    if (canBlend) {
-        curve->add(WebTransformKeyframe(keyTime, operations.release()), timingFunctionType);
-        return true;
-    }
-    return false;
-}
-
-template <>
-bool appendKeyframeWithCustomBezierTimingFunction<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(WebTransformAnimationCurve* curve, double keyTime, const TransformAnimationValue* value, const TransformAnimationValue* lastValue, double x1, double y1, double x2, double y2, const FloatSize& boxSize)
-{
-    bool canBlend = !lastValue;
-    OwnPtr<WebTransformOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
-    if (!operations)
-        return false;
-    toWebTransformOperations(*value->value(), boxSize, operations.get());
-    if (!canBlend) {
-        OwnPtr<WebTransformOperations> lastOperations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
-        if (!lastOperations)
-            return false;
-        toWebTransformOperations(*lastValue->value(), boxSize, lastOperations.get());
-        canBlend = lastOperations->canBlendWith(*operations);
-    }
-    if (canBlend) {
-        curve->add(WebTransformKeyframe(keyTime, operations.release()), x1, y1, x2, y2);
-        return true;
-    }
-    return false;
-}
-
-bool toWebFilterOperations(const FilterOperations& inOperations, WebFilterOperations* outOperations)
-{
-    SkiaImageFilterBuilder builder;
-    FilterOutsets outsets = inOperations.outsets();
-    builder.setCropOffset(FloatSize(outsets.left(), outsets.top()));
-    return builder.buildFilterOperations(inOperations, outOperations);
-}
-
-template <>
-bool appendKeyframeWithStandardTimingFunction<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(WebFilterAnimationCurve* curve, double keyTime, const FilterAnimationValue* value, const FilterAnimationValue* lastValue, blink::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize& boxSize)
-{
-    // FIXME(ajuma): In order to animate pixel-moving filters on the compositor thread, we need
-    // to update overlap testing to take into account the bounds within which the animation
-    // will be contained, and we need the compositor to update layer bounds as the animation
-    // progresses.
-    if (value->value()->hasFilterThatMovesPixels())
-        return false;
-    OwnPtr<WebFilterOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
-    if (!toWebFilterOperations(*(value->value()), operations.get()))
-        return false;
-    curve->add(WebFilterKeyframe(keyTime, operations.release()), timingFunctionType);
-    return true;
-}
-
-template <>
-bool appendKeyframeWithCustomBezierTimingFunction<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(WebFilterAnimationCurve* curve, double keyTime, const FilterAnimationValue* value, const FilterAnimationValue* lastValue, double x1, double y1, double x2, double y2, const FloatSize& boxSize)
-{
-    // FIXME(ajuma): In order to animate pixel-moving filters on the compositor thread, we need
-    // to update overlap testing to take into account the bounds within which the animation
-    // will be contained, and we need the compositor to update layer bounds as the animation
-    // progresses.
-    if (value->value()->hasFilterThatMovesPixels())
-        return false;
-
-    OwnPtr<WebFilterOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
-    if (!toWebFilterOperations(*(value->value()), operations.get()))
-        return false;
-    curve->add(WebFilterKeyframe(keyTime, operations.release()), x1, y1, x2, y2);
-    return true;
-}
-
-template <class Value, class Keyframe, class Curve>
-PassOwnPtr<blink::WebAnimation> createWebAnimation(const KeyframeValueList& valueList, const CSSAnimationData* animation, int animationId, double timeOffset, Curve* curve, blink::WebAnimation::TargetProperty targetProperty, const FloatSize& boxSize)
-{
-    bool alternate = false;
-    bool reverse = false;
-    if (animation && animation->isDirectionSet()) {
-        CSSAnimationData::AnimationDirection direction = animation->direction();
-        if (direction == CSSAnimationData::AnimationDirectionAlternate || direction == CSSAnimationData::AnimationDirectionAlternateReverse)
-            alternate = true;
-        if (direction == CSSAnimationData::AnimationDirectionReverse || direction == CSSAnimationData::AnimationDirectionAlternateReverse)
-            reverse = true;
-    }
-
-    for (size_t i = 0; i < valueList.size(); i++) {
-        size_t index = reverse ? valueList.size() - i - 1 : i;
-        const Value* originalValue = static_cast<const Value*>(valueList.at(index));
-        const Value* lastOriginalValue = 0;
-        if (valueList.size() > 1 && ((reverse && index + 1 < valueList.size()) || (!reverse && index > 0)))
-            lastOriginalValue = static_cast<const Value*>(valueList.at(reverse ? index + 1 : index - 1));
-
-        const TimingFunction* originalTimingFunction = originalValue->timingFunction();
-
-        // If there hasn't been a timing function associated with this keyframe, use the
-        // animation's timing function, if we have one.
-        if (!originalTimingFunction && animation->isTimingFunctionSet())
-            originalTimingFunction = animation->timingFunction();
-
-        // Ease is the default timing function.
-        blink::WebAnimationCurve::TimingFunctionType timingFunctionType = blink::WebAnimationCurve::TimingFunctionTypeEase;
-
-        bool isUsingCustomBezierTimingFunction = false;
-        double x1 = 0;
-        double y1 = 0;
-        double x2 = 1;
-        double y2 = 1;
-
-        if (originalTimingFunction) {
-            switch (originalTimingFunction->type()) {
-            case TimingFunction::StepsFunction:
-                // FIXME: add support for steps timing function.
-                return nullptr;
-            case TimingFunction::LinearFunction:
-                // This doesn't need to be flipped when the animation is reversed.
-                timingFunctionType = blink::WebAnimationCurve::TimingFunctionTypeLinear;
-                break;
-            case TimingFunction::CubicBezierFunction:
-                {
-                    const CubicBezierTimingFunction* originalBezierTimingFunction = toCubicBezierTimingFunction(originalTimingFunction);
-                    isUsingCustomBezierTimingFunction = true;
-                    x1 = originalBezierTimingFunction->x1();
-                    y1 = originalBezierTimingFunction->y1();
-                    x2 = originalBezierTimingFunction->x2();
-                    y2 = originalBezierTimingFunction->y2();
-                    if (reverse) {
-                        // When the animation is reversed, we need to swap the
-                        // start and end keyframes, and flip the timing
-                        // function in both x and y.
-                        double x1Old = x1;
-                        double y1Old = y1;
-                        x1 = 1 - x2;
-                        y1 = 1 - y2;
-                        x2 = 1 - x1Old;
-                        y2 = 1 - y1Old;
-                    }
-                    break;
-                }
-            default:
-                ASSERT_NOT_REACHED();
-            } // switch
-        }
-
-        double duration = (animation && animation->isDurationSet()) ? animation->duration() : 1;
-        double keyTime = originalValue->keyTime() * duration;
-
-        if (reverse)
-            keyTime = duration - keyTime;
-
-        bool addedKeyframe = false;
-        if (isUsingCustomBezierTimingFunction)
-            addedKeyframe = appendKeyframeWithCustomBezierTimingFunction<Value, Keyframe, Curve>(curve, keyTime, originalValue, lastOriginalValue, x1, y1, x2, y2, boxSize);
-        else
-            addedKeyframe = appendKeyframeWithStandardTimingFunction<Value, Keyframe, Curve>(curve, keyTime, originalValue, lastOriginalValue, timingFunctionType, boxSize);
-
-        if (!addedKeyframe)
-            return nullptr;
-    }
-
-    OwnPtr<blink::WebAnimation> webAnimation = adoptPtr(Platform::current()->compositorSupport()->createAnimation(*curve, targetProperty, animationId));
-
-    int iterations = (animation && animation->isIterationCountSet()) ? animation->iterationCount() : 1;
-    webAnimation->setIterations(iterations);
-    webAnimation->setAlternatesDirection(alternate);
-
-    // If timeOffset > 0, then the animation has started in the past.
-    webAnimation->setTimeOffset(timeOffset);
-
-    return webAnimation.release();
-}
-
-PassOwnPtr<blink::WebAnimation> createWebAnimation(const KeyframeValueList& values, const CSSAnimationData* animation, int animationId, double timeOffset, const FloatSize& boxSize)
-{
-    switch (values.property()) {
-    case AnimatedPropertyWebkitTransform: {
-        OwnPtr<WebTransformAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createTransformAnimationCurve());
-        return createWebAnimation<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), blink::WebAnimation::TargetPropertyTransform, FloatSize(boxSize));
-    }
-
-    case AnimatedPropertyOpacity: {
-        OwnPtr<WebFloatAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createFloatAnimationCurve());
-        return createWebAnimation<FloatAnimationValue, WebFloatKeyframe, WebFloatAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), blink::WebAnimation::TargetPropertyOpacity, FloatSize());
-    }
-
-    case AnimatedPropertyWebkitFilter: {
-        OwnPtr<WebFilterAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createFilterAnimationCurve());
-        return createWebAnimation<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), blink::WebAnimation::TargetPropertyFilter, FloatSize(boxSize));
-    }
-
-    case AnimatedPropertyBackgroundColor:
-    case AnimatedPropertyInvalid:
-        return nullptr;
-    }
-
-    return nullptr;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/animation/AnimationTranslationUtil.h b/Source/core/platform/animation/AnimationTranslationUtil.h
deleted file mode 100644
index 2c95cdf..0000000
--- a/Source/core/platform/animation/AnimationTranslationUtil.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef AnimationTranslationUtil_h
-#define AnimationTranslationUtil_h
-
-#include "platform/graphics/filters/FilterOperations.h"
-#include "platform/transforms/TransformOperations.h"
-#include "public/platform/WebTransformOperations.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace blink {
-class WebAnimation;
-class WebFilterOperations;
-}
-
-namespace WebCore {
-
-class KeyframeValueList;
-class CSSAnimationData;
-class FloatSize;
-
-
-// Translates WebCore animation data into a WebAnimation. If we are unable
-// to perform this translation, we return nullptr. This can happen if
-//   - a steps timing function is used,
-//   - a property other than AnimatedPropertyWebkitTransform, or AnimatedPropertyOpacity is animated, or
-//   - a transform animation involves a non-invertable transform.
-PassOwnPtr<blink::WebAnimation> createWebAnimation(const KeyframeValueList&, const CSSAnimationData*, int animationId, double timeOffset, const FloatSize& boxSize);
-
-void toWebTransformOperations(const TransformOperations& inOperations, const FloatSize& boxSize, blink::WebTransformOperations* outOperations);
-
-bool toWebFilterOperations(const FilterOperations& inOperations, blink::WebFilterOperations* outOperations);
-} // namespace WebCore
-
-#endif // AnimationTranslationUtil_h
diff --git a/Source/core/platform/animation/AnimationTranslationUtilTest.cpp b/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
deleted file mode 100644
index 59dcbe9..0000000
--- a/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-#include "config.h"
-
-#include "core/platform/animation/AnimationTranslationUtil.h"
-
-#include "core/platform/animation/CSSAnimationData.h"
-#include "core/platform/animation/KeyframeValueList.h"
-#include "platform/geometry/IntSize.h"
-#include "platform/graphics/filters/FilterOperations.h"
-#include "platform/transforms/Matrix3DTransformOperation.h"
-#include "platform/transforms/RotateTransformOperation.h"
-#include "platform/transforms/ScaleTransformOperation.h"
-#include "platform/transforms/TransformOperations.h"
-#include "platform/transforms/TranslateTransformOperation.h"
-#include "public/platform/WebAnimation.h"
-#include "public/platform/WebFilterOperations.h"
-#include "wtf/RefPtr.h"
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-using namespace blink;
-
-namespace {
-
-class WebTransformOperationsMock : public blink::WebTransformOperations {
-public:
-    MOCK_CONST_METHOD1(canBlendWith, bool(const WebTransformOperations&));
-    MOCK_METHOD3(appendTranslate, void(double, double, double));
-    MOCK_METHOD4(appendRotate, void(double, double, double, double));
-    MOCK_METHOD3(appendScale, void(double, double, double));
-    MOCK_METHOD2(appendSkew, void(double, double));
-    MOCK_METHOD1(appendPerspective, void(double));
-    MOCK_METHOD1(appendMatrix, void(const SkMatrix44&));
-    MOCK_METHOD0(appendIdentity, void());
-    MOCK_CONST_METHOD0(isIdentity, bool());
-};
-
-class WebFilterOperationsMock : public blink::WebFilterOperations {
-public:
-    MOCK_METHOD1(appendGrayscaleFilter, void(float));
-    MOCK_METHOD1(appendSepiaFilter, void(float));
-    MOCK_METHOD1(appendSaturateFilter, void(float));
-    MOCK_METHOD1(appendHueRotateFilter, void(float));
-    MOCK_METHOD1(appendInvertFilter, void(float));
-    MOCK_METHOD1(appendBrightnessFilter, void(float));
-    MOCK_METHOD1(appendContrastFilter, void(float));
-    MOCK_METHOD1(appendOpacityFilter, void(float));
-    MOCK_METHOD1(appendBlurFilter, void(float));
-    MOCK_METHOD3(appendDropShadowFilter, void(WebPoint, float, WebColor));
-    MOCK_METHOD1(appendColorMatrixFilter, void(SkScalar[20]));
-    MOCK_METHOD2(appendZoomFilter, void(float, int));
-    MOCK_METHOD1(appendSaturatingBrightnessFilter, void(float));
-    MOCK_METHOD1(appendReferenceFilter, void(SkImageFilter*));
-    MOCK_METHOD0(clear, void());
-};
-
-bool animationCanBeTranslated(const KeyframeValueList& values, CSSAnimationData* animation)
-{
-    IntSize boxSize;
-    return createWebAnimation(values, animation, 0, 0, boxSize);
-}
-
-TEST(AnimationTranslationUtilTest, createOpacityAnimation)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyOpacity);
-    values.insert(adoptPtr(new FloatAnimationValue(0, 0)));
-    values.insert(adoptPtr(new FloatAnimationValue(duration, 1)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createFilterAnimation)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitFilter);
-
-    FilterOperations operations1;
-    operations1.operations().append(BasicColorMatrixFilterOperation::create(0.5, FilterOperation::SATURATE));
-    values.insert(adoptPtr(new FilterAnimationValue(0, &operations1)));
-
-    FilterOperations operations2;
-    operations2.operations().append(BasicColorMatrixFilterOperation::create(1.0, FilterOperation::SATURATE));
-    values.insert(adoptPtr(new FilterAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimation)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformOperations operations1;
-    operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformOperations operations2;
-    operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithBigRotation)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformOperations operations1;
-    operations1.operations().append(RotateTransformOperation::create(0, TransformOperation::Rotate));
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformOperations operations2;
-    operations2.operations().append(RotateTransformOperation::create(270, TransformOperation::Rotate));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithBigRotationAndEmptyTransformOperationList)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformOperations operations1;
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformOperations operations2;
-    operations2.operations().append(RotateTransformOperation::create(270, TransformOperation::Rotate));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithRotationInvolvingNegativeAngles)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformOperations operations1;
-    operations1.operations().append(RotateTransformOperation::create(-330, TransformOperation::Rotate));
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformOperations operations2;
-    operations2.operations().append(RotateTransformOperation::create(-320, TransformOperation::Rotate));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithSmallRotationInvolvingLargeAngles)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformOperations operations1;
-    operations1.operations().append(RotateTransformOperation::create(270, TransformOperation::Rotate));
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformOperations operations2;
-    operations2.operations().append(RotateTransformOperation::create(360, TransformOperation::Rotate));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithNonDecomposableMatrix)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformationMatrix matrix1;
-    TransformOperations operations1;
-    operations1.operations().append(Matrix3DTransformOperation::create(matrix1));
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformationMatrix matrix2;
-    matrix2.setM11(0);
-    TransformOperations operations2;
-    operations2.operations().append(Matrix3DTransformOperation::create(matrix2));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-
-    EXPECT_FALSE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithNonInvertibleTransform)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformOperations operations1;
-    operations1.operations().append(ScaleTransformOperation::create(1, 1, 1, TransformOperation::Scale3D));
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformOperations operations2;
-    operations2.operations().append(ScaleTransformOperation::create(1, 0, 1, TransformOperation::Scale3D));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createReversedAnimation)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformOperations operations1;
-    operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformOperations operations2;
-    operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-    animation->setDirection(CSSAnimationData::AnimationDirectionReverse);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createAlternatingAnimation)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformOperations operations1;
-    operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformOperations operations2;
-    operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-    animation->setDirection(CSSAnimationData::AnimationDirectionAlternate);
-    animation->setIterationCount(2);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createReversedAlternatingAnimation)
-{
-    const double duration = 1;
-    WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
-    TransformOperations operations1;
-    operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
-    values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
-    TransformOperations operations2;
-    operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
-    values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
-    RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
-    animation->setDuration(duration);
-    animation->setDirection(CSSAnimationData::AnimationDirectionAlternateReverse);
-    animation->setIterationCount(2);
-
-    EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, transformsWork)
-{
-    TransformOperations ops;
-    FloatSize box(100, 200);
-    WebTransformOperationsMock outOps;
-
-    EXPECT_CALL(outOps, appendTranslate(2, 0, 0));
-    EXPECT_CALL(outOps, appendTranslate(2, 60, 0));
-    EXPECT_CALL(outOps, appendRotate(0.1, 0.2, 0.3, 200000.4));
-    EXPECT_CALL(outOps, appendScale(50.2, 100, -4));
-
-    ops.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
-    ops.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Percent), Length(30, WebCore::Percent), TransformOperation::Translate));
-    ops.operations().append(RotateTransformOperation::create(0.1, 0.2, 0.3, 200000.4, TransformOperation::Rotate3D));
-    ops.operations().append(ScaleTransformOperation::create(50.2, 100, -4, TransformOperation::Scale3D));
-    toWebTransformOperations(ops, box, &outOps);
-}
-
-TEST(AnimationTranslationUtilTest, filtersWork)
-{
-    FilterOperations ops;
-    WebFilterOperationsMock outOps;
-
-    EXPECT_CALL(outOps, appendSaturateFilter(0.5));
-    EXPECT_CALL(outOps, appendGrayscaleFilter(0.2f));
-    EXPECT_CALL(outOps, appendSepiaFilter(0.8f));
-    EXPECT_CALL(outOps, appendOpacityFilter(0.1f));
-
-    ops.operations().append(BasicColorMatrixFilterOperation::create(0.5, FilterOperation::SATURATE));
-    ops.operations().append(BasicColorMatrixFilterOperation::create(0.2, FilterOperation::GRAYSCALE));
-    ops.operations().append(BasicColorMatrixFilterOperation::create(0.8, FilterOperation::SEPIA));
-    ops.operations().append(BasicColorMatrixFilterOperation::create(0.1, FilterOperation::OPACITY));
-    toWebFilterOperations(ops, &outOps);
-}
-
-}
-
diff --git a/Source/core/platform/animation/AnimationValue.h b/Source/core/platform/animation/AnimationValue.h
deleted file mode 100644
index cba337c..0000000
--- a/Source/core/platform/animation/AnimationValue.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. 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 APPLE INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef AnimationValue_h
-#define AnimationValue_h
-
-#include "core/platform/animation/TimingFunction.h"
-#include "platform/graphics/filters/FilterOperations.h"
-#include "platform/transforms/TransformOperations.h"
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-// Base class for animation values (also used for transitions). Here to
-// represent values for properties being animated via the GraphicsLayer,
-// without pulling in style-related data from outside of the platform directory.
-class AnimationValue {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    explicit AnimationValue(double keyTime, PassRefPtr<TimingFunction> timingFunction = 0)
-        : m_keyTime(keyTime)
-        , m_timingFunction(timingFunction)
-    {
-    }
-
-    virtual ~AnimationValue() { }
-
-    double keyTime() const { return m_keyTime; }
-    const TimingFunction* timingFunction() const { return m_timingFunction.get(); }
-    virtual PassOwnPtr<AnimationValue> clone() const = 0;
-
-private:
-    double m_keyTime;
-    RefPtr<TimingFunction> m_timingFunction;
-};
-
-// Used to store one float value of an animation.
-class FloatAnimationValue : public AnimationValue {
-public:
-    FloatAnimationValue(double keyTime, float value, PassRefPtr<TimingFunction> timingFunction = 0)
-        : AnimationValue(keyTime, timingFunction)
-        , m_value(value)
-    {
-    }
-    virtual PassOwnPtr<AnimationValue> clone() const OVERRIDE { return adoptPtr(new FloatAnimationValue(*this)); }
-
-    float value() const { return m_value; }
-
-private:
-    float m_value;
-};
-
-// Used to store one transform value in a keyframe list.
-class TransformAnimationValue : public AnimationValue {
-public:
-    explicit TransformAnimationValue(double keyTime, const TransformOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
-        : AnimationValue(keyTime, timingFunction)
-    {
-        if (value)
-            m_value = *value;
-    }
-    virtual PassOwnPtr<AnimationValue> clone() const OVERRIDE { return adoptPtr(new TransformAnimationValue(*this)); }
-
-    const TransformOperations* value() const { return &m_value; }
-
-private:
-    TransformOperations m_value;
-};
-
-// Used to store one filter value in a keyframe list.
-class FilterAnimationValue : public AnimationValue {
-public:
-    explicit FilterAnimationValue(double keyTime, const FilterOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
-        : AnimationValue(keyTime, timingFunction)
-    {
-        if (value)
-            m_value = *value;
-    }
-    virtual PassOwnPtr<AnimationValue> clone() const OVERRIDE { return adoptPtr(new FilterAnimationValue(*this)); }
-
-    const FilterOperations* value() const { return &m_value; }
-
-private:
-    FilterOperations m_value;
-};
-
-} // namespace WebCore
-
-#endif // AnimationValue_h
diff --git a/Source/core/platform/animation/KeyframeValueList.cpp b/Source/core/platform/animation/KeyframeValueList.cpp
deleted file mode 100644
index 174172c..0000000
--- a/Source/core/platform/animation/KeyframeValueList.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. 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 APPLE INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-
-#include "core/platform/animation/KeyframeValueList.h"
-
-namespace WebCore {
-
-void KeyframeValueList::insert(PassOwnPtr<const AnimationValue> value)
-{
-    for (size_t i = 0; i < m_values.size(); ++i) {
-        const AnimationValue* curValue = m_values[i].get();
-        if (curValue->keyTime() == value->keyTime()) {
-            ASSERT_NOT_REACHED();
-            // insert after
-            m_values.insert(i + 1, value);
-            return;
-        }
-        if (curValue->keyTime() > value->keyTime()) {
-            // insert before
-            m_values.insert(i, value);
-            return;
-        }
-    }
-
-    m_values.append(value);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/animation/KeyframeValueList.h b/Source/core/platform/animation/KeyframeValueList.h
deleted file mode 100644
index 86ffb00..0000000
--- a/Source/core/platform/animation/KeyframeValueList.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. 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 APPLE INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef KeyframeValueList_h
-#define KeyframeValueList_h
-
-#include "core/platform/animation/AnimationValue.h"
-
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-enum AnimatedPropertyID {
-    AnimatedPropertyInvalid,
-    AnimatedPropertyWebkitTransform,
-    AnimatedPropertyOpacity,
-    AnimatedPropertyBackgroundColor,
-    AnimatedPropertyWebkitFilter
-};
-
-// Used to store a series of values in a keyframe list.
-// Values will all be of the same type, which can be inferred from the property.
-class KeyframeValueList {
-public:
-    explicit KeyframeValueList(AnimatedPropertyID property)
-        : m_property(property)
-    {
-    }
-
-    KeyframeValueList(const KeyframeValueList& other)
-        : m_property(other.property())
-    {
-        for (size_t i = 0; i < other.m_values.size(); ++i)
-            m_values.append(other.m_values[i]->clone());
-    }
-
-    KeyframeValueList& operator=(const KeyframeValueList& other)
-    {
-        KeyframeValueList copy(other);
-        swap(copy);
-        return *this;
-    }
-
-    void swap(KeyframeValueList& other)
-    {
-        std::swap(m_property, other.m_property);
-        m_values.swap(other.m_values);
-    }
-
-    AnimatedPropertyID property() const { return m_property; }
-
-    size_t size() const { return m_values.size(); }
-    const AnimationValue* at(size_t i) const { return m_values.at(i).get(); }
-
-    // Insert, sorted by keyTime.
-    void insert(PassOwnPtr<const AnimationValue>);
-
-protected:
-    Vector<OwnPtr<const AnimationValue> > m_values;
-    AnimatedPropertyID m_property;
-};
-
-} // namespace WebCore
-
-#endif // KeyframeValueList_h
diff --git a/Source/core/platform/animation/TimingFunction.h b/Source/core/platform/animation/TimingFunction.h
deleted file mode 100644
index 147d86b..0000000
--- a/Source/core/platform/animation/TimingFunction.h
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- *           (C) 2000 Antti Koivisto (koivisto@kde.org)
- *           (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef TimingFunction_h
-#define TimingFunction_h
-
-#include "RuntimeEnabledFeatures.h"
-#include "platform/animation/AnimationUtilities.h" // For blend()
-#include "platform/animation/UnitBezier.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/Vector.h"
-#include <algorithm>
-
-
-namespace WebCore {
-
-class TimingFunction : public RefCounted<TimingFunction> {
-public:
-
-    enum Type {
-        LinearFunction, CubicBezierFunction, StepsFunction, ChainedFunction
-    };
-
-    virtual ~TimingFunction() { }
-
-    Type type() const { return m_type; }
-
-    // Evaluates the timing function at the given fraction. The accuracy parameter provides a hint as to the required
-    // accuracy and is not guaranteed.
-    virtual double evaluate(double fraction, double accuracy) const = 0;
-
-protected:
-    TimingFunction(Type type)
-        : m_type(type)
-    {
-    }
-
-private:
-    Type m_type;
-};
-
-class LinearTimingFunction : public TimingFunction {
-public:
-    static PassRefPtr<LinearTimingFunction> create()
-    {
-        return adoptRef(new LinearTimingFunction);
-    }
-
-    ~LinearTimingFunction() { }
-
-    virtual double evaluate(double fraction, double) const
-    {
-        ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1));
-        ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
-        return fraction;
-    }
-
-private:
-    LinearTimingFunction()
-        : TimingFunction(LinearFunction)
-    {
-    }
-};
-
-
-// Forward declare so we can friend it below. Don't use in production code!
-class ChainedTimingFunctionTestHelper;
-
-class CubicBezierTimingFunction : public TimingFunction {
-public:
-    enum SubType {
-        Ease,
-        EaseIn,
-        EaseOut,
-        EaseInOut,
-        Custom
-    };
-
-    static PassRefPtr<CubicBezierTimingFunction> create(double x1, double y1, double x2, double y2)
-    {
-        return adoptRef(new CubicBezierTimingFunction(Custom, x1, y1, x2, y2));
-    }
-
-    static CubicBezierTimingFunction* preset(SubType subType)
-    {
-        switch (subType) {
-        case Ease:
-            {
-                DEFINE_STATIC_REF(CubicBezierTimingFunction, ease, (adoptRef(new CubicBezierTimingFunction(Ease, 0.25, 0.1, 0.25, 1.0))));
-                return ease;
-            }
-        case EaseIn:
-            {
-                DEFINE_STATIC_REF(CubicBezierTimingFunction, easeIn, (adoptRef(new CubicBezierTimingFunction(EaseIn, 0.42, 0.0, 1.0, 1.0))));
-                return easeIn;
-            }
-        case EaseOut:
-            {
-                DEFINE_STATIC_REF(CubicBezierTimingFunction, easeOut, (adoptRef(new CubicBezierTimingFunction(EaseOut, 0.0, 0.0, 0.58, 1.0))));
-                return easeOut;
-            }
-        case EaseInOut:
-            {
-                DEFINE_STATIC_REF(CubicBezierTimingFunction, easeInOut, (adoptRef(new CubicBezierTimingFunction(EaseInOut, 0.42, 0.0, 0.58, 1.0))));
-                return easeInOut;
-            }
-        default:
-            ASSERT_NOT_REACHED();
-            return 0;
-        }
-    }
-
-    ~CubicBezierTimingFunction() { }
-
-    virtual double evaluate(double fraction, double accuracy) const
-    {
-        ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1));
-        ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
-        if (!m_bezier)
-            m_bezier = adoptPtr(new UnitBezier(m_x1, m_y1, m_x2, m_y2));
-        return m_bezier->solve(fraction, accuracy);
-    }
-
-    double x1() const { return m_x1; }
-    double y1() const { return m_y1; }
-    double x2() const { return m_x2; }
-    double y2() const { return m_y2; }
-
-    SubType subType() const { return m_subType; }
-
-private:
-    explicit CubicBezierTimingFunction(SubType subType, double x1, double y1, double x2, double y2)
-        : TimingFunction(CubicBezierFunction)
-        , m_x1(x1)
-        , m_y1(y1)
-        , m_x2(x2)
-        , m_y2(y2)
-        , m_subType(subType)
-    {
-    }
-
-    double m_x1;
-    double m_y1;
-    double m_x2;
-    double m_y2;
-    SubType m_subType;
-    mutable OwnPtr<UnitBezier> m_bezier;
-};
-
-class StepsTimingFunction : public TimingFunction {
-public:
-    enum SubType {
-        Start,
-        End,
-        Custom
-    };
-
-    static PassRefPtr<StepsTimingFunction> create(int steps, bool stepAtStart)
-    {
-        return adoptRef(new StepsTimingFunction(Custom, steps, stepAtStart));
-    }
-
-    static StepsTimingFunction* preset(SubType subType)
-    {
-        switch (subType) {
-        case Start:
-            {
-                DEFINE_STATIC_REF(StepsTimingFunction, start, (adoptRef(new StepsTimingFunction(Start, 1, true))));
-                return start;
-            }
-        case End:
-            {
-                DEFINE_STATIC_REF(StepsTimingFunction, end, (adoptRef(new StepsTimingFunction(End, 1, false))));
-                return end;
-            }
-        default:
-            ASSERT_NOT_REACHED();
-            return 0;
-        }
-    }
-
-
-    ~StepsTimingFunction() { }
-
-    virtual double evaluate(double fraction, double) const
-    {
-        ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1));
-        ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
-        return std::min(1.0, (floor(m_steps * fraction) + m_stepAtStart) / m_steps);
-    }
-
-    int numberOfSteps() const { return m_steps; }
-    bool stepAtStart() const { return m_stepAtStart; }
-
-    SubType subType() const { return m_subType; }
-
-private:
-    StepsTimingFunction(SubType subType, int steps, bool stepAtStart)
-        : TimingFunction(StepsFunction)
-        , m_steps(steps)
-        , m_stepAtStart(stepAtStart)
-        , m_subType(subType)
-    {
-    }
-
-    int m_steps;
-    bool m_stepAtStart;
-    SubType m_subType;
-};
-
-class ChainedTimingFunction : public TimingFunction {
-public:
-    static PassRefPtr<ChainedTimingFunction> create()
-    {
-        return adoptRef(new ChainedTimingFunction);
-    }
-
-    void appendSegment(double upperBound, TimingFunction* timingFunction)
-    {
-        double max = m_segments.isEmpty() ? 0 : m_segments.last().max();
-        ASSERT(upperBound > max);
-        m_segments.append(Segment(max, upperBound, timingFunction));
-    }
-    virtual double evaluate(double fraction, double accuracy) const
-    {
-        ASSERT_WITH_MESSAGE(fraction >= 0 && fraction <= 1, "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
-        ASSERT(!m_segments.isEmpty());
-        ASSERT(m_segments.last().max() == 1);
-        size_t i = 0;
-        const Segment* segment = &m_segments[i++];
-        while (fraction >= segment->max() && i < m_segments.size()) {
-            segment = &m_segments[i++];
-        }
-        return segment->evaluate(fraction, accuracy);
-    }
-
-private:
-    class Segment {
-    public:
-        Segment(double min, double max, TimingFunction* timingFunction)
-            : m_min(min)
-            , m_max(max)
-            , m_timingFunction(timingFunction)
-        { ASSERT(timingFunction); }
-
-        double max() const { return m_max; }
-        double evaluate(double fraction, double accuracy) const
-        {
-            return scaleFromLocal(m_timingFunction->evaluate(scaleToLocal(fraction), accuracy));
-        }
-
-    private:
-        double scaleToLocal(double x) const { return (x - m_min) / (m_max - m_min); }
-        double scaleFromLocal(double x) const { return blend(m_min, m_max, x); }
-
-        double m_min;
-        double m_max;
-        RefPtr<TimingFunction> m_timingFunction;
-
-        // FIXME: Come up with a public API for the segments and remove this.
-        friend class CompositorAnimationsImpl;
-        friend class CompositorAnimations;
-
-        // Allow the compositor to reverse the timing function.
-        friend class CompositorAnimationsTimingFunctionReverser;
-
-        // Allow PrintTo/operator== of the segments. Can be removed once
-        // ChainedTimingFunction has a public API for segments.
-        friend class ChainedTimingFunctionTestHelper;
-    };
-
-    ChainedTimingFunction()
-        : TimingFunction(ChainedFunction)
-    {
-        ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
-    }
-
-    Vector<Segment> m_segments;
-
-    // FIXME: Come up with a public API for the segments and remove this.
-    friend class CompositorAnimationsImpl;
-    friend class CompositorAnimations;
-
-    // Allow the compositor to reverse the timing function.
-    friend class CompositorAnimationsTimingFunctionReverser;
-
-    // Allow PrintTo/operator== of the segments. Can be removed once
-    // ChainedTimingFunction has a public API for segments.
-    friend class ChainedTimingFunctionTestHelper;
-};
-
-#define DEFINE_TIMING_FUNCTION_TYPE_CASTS(typeName) \
-    DEFINE_TYPE_CASTS( \
-        typeName##TimingFunction, TimingFunction, value, \
-        value->type() == TimingFunction::typeName##Function, \
-        value.type() == TimingFunction::typeName##Function)
-
-DEFINE_TIMING_FUNCTION_TYPE_CASTS(Linear);
-DEFINE_TIMING_FUNCTION_TYPE_CASTS(CubicBezier);
-DEFINE_TIMING_FUNCTION_TYPE_CASTS(Steps);
-DEFINE_TIMING_FUNCTION_TYPE_CASTS(Chained);
-
-} // namespace WebCore
-
-#endif // TimingFunction_h
diff --git a/Source/core/platform/animation/TimingFunctionTestHelper.cpp b/Source/core/platform/animation/TimingFunctionTestHelper.cpp
deleted file mode 100644
index f1eeb96..0000000
--- a/Source/core/platform/animation/TimingFunctionTestHelper.cpp
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * Copyright (c) 2013, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/platform/animation/TimingFunctionTestHelper.h"
-
-
-namespace WebCore {
-
-// This class exists so that ChainedTimingFunction only needs to friend one thing.
-class ChainedTimingFunctionTestHelper {
-    static void PrintTo(const ChainedTimingFunction& timingFunction, ::std::ostream* os)
-    {
-        // Forward declare the generic PrintTo function as ChainedTimingFunction needs to call it.
-        void PrintTo(const TimingFunction&, ::std::ostream*);
-
-        *os << "ChainedTimingFunction@" << &timingFunction << "(";
-        for (size_t i = 0; i < timingFunction.m_segments.size(); i++) {
-            ChainedTimingFunction::Segment segment = timingFunction.m_segments[i];
-            PrintTo(*(segment.m_timingFunction.get()), os);
-            *os << "[" << segment.m_min << " -> " << segment.m_max << "]";
-            if (i+1 != timingFunction.m_segments.size()) {
-                *os << ", ";
-            }
-        }
-        *os << ")";
-    }
-
-    static bool equals(const ChainedTimingFunction& lhs, const TimingFunction& rhs)
-    {
-        if (rhs.type() != TimingFunction::ChainedFunction)
-            return false;
-
-        if (&lhs == &rhs)
-            return true;
-
-        const ChainedTimingFunction& ctf = toChainedTimingFunction(rhs);
-        if (lhs.m_segments.size() != ctf.m_segments.size())
-            return false;
-
-        for (size_t i = 0; i < lhs.m_segments.size(); i++) {
-            if (!equals(lhs.m_segments[i], ctf.m_segments[i]))
-                return false;
-        }
-        return true;
-    }
-
-    static bool equals(const ChainedTimingFunction::Segment& lhs, const ChainedTimingFunction::Segment& rhs)
-    {
-        if (&lhs == &rhs)
-            return true;
-
-        if ((lhs.m_min != rhs.m_min) || (lhs.m_max != rhs.m_max))
-            return false;
-
-        if (lhs.m_timingFunction == rhs.m_timingFunction)
-            return true;
-
-        ASSERT(lhs.m_timingFunction);
-        ASSERT(rhs.m_timingFunction);
-
-        return (*(lhs.m_timingFunction.get())) == (*(rhs.m_timingFunction.get()));
-    }
-
-    friend void PrintTo(const ChainedTimingFunction&, ::std::ostream*);
-    friend bool operator==(const ChainedTimingFunction& lhs, const TimingFunction& rhs);
-};
-
-void PrintTo(const LinearTimingFunction& timingFunction, ::std::ostream* os)
-{
-    *os << "LinearTimingFunction@" << &timingFunction;
-}
-
-void PrintTo(const CubicBezierTimingFunction& timingFunction, ::std::ostream* os)
-{
-    *os << "CubicBezierTimingFunction@" << &timingFunction << "(";
-    switch (timingFunction.subType()) {
-    case CubicBezierTimingFunction::Ease:
-        *os << "Ease";
-        break;
-    case CubicBezierTimingFunction::EaseIn:
-        *os << "EaseIn";
-        break;
-    case CubicBezierTimingFunction::EaseOut:
-        *os << "EaseOut";
-        break;
-    case CubicBezierTimingFunction::EaseInOut:
-        *os << "EaseInOut";
-        break;
-    case CubicBezierTimingFunction::Custom:
-        *os << "Custom";
-        break;
-    default:
-        ASSERT_NOT_REACHED();
-    }
-    *os << ", " << timingFunction.x1();
-    *os << ", " << timingFunction.y1();
-    *os << ", " << timingFunction.x2();
-    *os << ", " << timingFunction.y2();
-    *os << ")";
-}
-
-void PrintTo(const StepsTimingFunction& timingFunction, ::std::ostream* os)
-{
-    *os << "StepsTimingFunction@" << &timingFunction << "(";
-    switch (timingFunction.subType()) {
-    case StepsTimingFunction::Start:
-        *os << "Start";
-        break;
-    case StepsTimingFunction::End:
-        *os << "End";
-        break;
-    case StepsTimingFunction::Custom:
-        *os << "Custom";
-        break;
-    default:
-        ASSERT_NOT_REACHED();
-    }
-    *os << ", " << timingFunction.numberOfSteps();
-    *os << ", " << (timingFunction.stepAtStart() ? "true" : "false");
-    *os << ")";
-}
-
-void PrintTo(const ChainedTimingFunction& timingFunction, ::std::ostream* os)
-{
-    ChainedTimingFunctionTestHelper::PrintTo(timingFunction, os);
-}
-
-// The generic PrintTo *must* come after the non-generic PrintTo otherwise it
-// will end up calling itself.
-void PrintTo(const TimingFunction& timingFunction, ::std::ostream* os)
-{
-    switch (timingFunction.type()) {
-    case TimingFunction::LinearFunction: {
-        const LinearTimingFunction& linear = toLinearTimingFunction(timingFunction);
-        PrintTo(linear, os);
-        return;
-    }
-    case TimingFunction::CubicBezierFunction: {
-        const CubicBezierTimingFunction& cubic = toCubicBezierTimingFunction(timingFunction);
-        PrintTo(cubic, os);
-        return;
-    }
-    case TimingFunction::StepsFunction: {
-        const StepsTimingFunction& step = toStepsTimingFunction(timingFunction);
-        PrintTo(step, os);
-        return;
-    }
-    case TimingFunction::ChainedFunction: {
-        const ChainedTimingFunction& chained = toChainedTimingFunction(timingFunction);
-        PrintTo(chained, os);
-        return;
-    }
-    default:
-        ASSERT_NOT_REACHED();
-    }
-}
-
-bool operator==(const LinearTimingFunction& lhs, const TimingFunction& rhs)
-{
-    return rhs.type() == TimingFunction::LinearFunction;
-}
-
-bool operator==(const CubicBezierTimingFunction& lhs, const TimingFunction& rhs)
-{
-    if (rhs.type() != TimingFunction::CubicBezierFunction)
-        return false;
-
-    const CubicBezierTimingFunction& ctf = toCubicBezierTimingFunction(rhs);
-    if ((lhs.subType() == CubicBezierTimingFunction::Custom) && (ctf.subType() == CubicBezierTimingFunction::Custom))
-        return (lhs.x1() == ctf.x1()) && (lhs.y1() == ctf.y1()) && (lhs.x2() == ctf.x2()) && (lhs.y2() == ctf.y2());
-
-    return lhs.subType() == ctf.subType();
-}
-
-bool operator==(const StepsTimingFunction& lhs, const TimingFunction& rhs)
-{
-    if (rhs.type() != TimingFunction::StepsFunction)
-        return false;
-
-    const StepsTimingFunction& stf = toStepsTimingFunction(rhs);
-    if ((lhs.subType() == StepsTimingFunction::Custom) && (stf.subType() == StepsTimingFunction::Custom))
-        return (lhs.numberOfSteps() == stf.numberOfSteps()) && (lhs.stepAtStart() == stf.stepAtStart());
-
-    return lhs.subType() == stf.subType();
-}
-
-bool operator==(const ChainedTimingFunction& lhs, const TimingFunction& rhs)
-{
-    return ChainedTimingFunctionTestHelper::equals(lhs, rhs);
-}
-
-// Like in the PrintTo case, the generic operator== *must* come after the
-// non-generic operator== otherwise it will end up calling itself.
-bool operator==(const TimingFunction& lhs, const TimingFunction& rhs)
-{
-    switch (lhs.type()) {
-    case TimingFunction::LinearFunction: {
-        const LinearTimingFunction& linear = toLinearTimingFunction(lhs);
-        return (linear == rhs);
-    }
-    case TimingFunction::CubicBezierFunction: {
-        const CubicBezierTimingFunction& cubic = toCubicBezierTimingFunction(lhs);
-        return (cubic == rhs);
-    }
-    case TimingFunction::StepsFunction: {
-        const StepsTimingFunction& step = toStepsTimingFunction(lhs);
-        return (step == rhs);
-    }
-    case TimingFunction::ChainedFunction: {
-        const ChainedTimingFunction& chained = toChainedTimingFunction(lhs);
-        return (chained == rhs);
-    }
-    default:
-        ASSERT_NOT_REACHED();
-    }
-    return false;
-}
-
-// No need to define specific operator!= as they can all come via this function.
-bool operator!=(const TimingFunction& lhs, const TimingFunction& rhs)
-{
-    return !(lhs == rhs);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/animation/TimingFunctionTestHelper.h b/Source/core/platform/animation/TimingFunctionTestHelper.h
deleted file mode 100644
index 06eaf06..0000000
--- a/Source/core/platform/animation/TimingFunctionTestHelper.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2013, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-/**
- * Make testing with gtest and gmock nicer by adding pretty print and other
- * helper functions.
- */
-
-#ifndef TimingFunctionTestHelper_h
-#define TimingFunctionTestHelper_h
-
-#include "core/platform/animation/TimingFunction.h"
-
-#include <ostream> // NOLINT
-
-namespace WebCore {
-
-// PrintTo functions
-void PrintTo(const LinearTimingFunction&, ::std::ostream*);
-void PrintTo(const CubicBezierTimingFunction&, ::std::ostream*);
-void PrintTo(const StepsTimingFunction&, ::std::ostream*);
-void PrintTo(const ChainedTimingFunction&, ::std::ostream*);
-void PrintTo(const TimingFunction&, ::std::ostream*);
-
-// operator== functions
-bool operator==(const LinearTimingFunction&, const TimingFunction&);
-bool operator==(const CubicBezierTimingFunction&, const TimingFunction&);
-bool operator==(const StepsTimingFunction&, const TimingFunction&);
-bool operator==(const ChainedTimingFunction&, const TimingFunction&);
-
-bool operator==(const TimingFunction&, const TimingFunction&);
-bool operator!=(const TimingFunction&, const TimingFunction&);
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp b/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp
deleted file mode 100644
index 01059a6..0000000
--- a/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp
+++ /dev/null
@@ -1,326 +0,0 @@
-/*
- * Copyright (c) 2013, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-
-#include "core/platform/animation/TimingFunctionTestHelper.h"
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-#include <sstream>
-#include <string>
-
-// FIXME: Remove once https://codereview.chromium.org/50603011/ lands.
-#define EXPECT_REFV_EQ(a, b) EXPECT_EQ(*(a.get()), *(b.get()))
-#define EXPECT_REFV_NE(a, b) EXPECT_NE(*(a.get()), *(b.get()))
-
-// Couple of macros to quickly assert a bunch of timing functions are not
-// equal.
-#define NE_STRINGIZE(x) NE_STRINGIZE2(x)
-#define NE_STRINGIZE2(x) #x
-#define NE_HELPER(v) \
-    Vector<std::pair<std::string, RefPtr<TimingFunction> > > v;
-#define NE_HELPER_APPEND(v, x) \
-    v.append(std::make_pair(std::string("Line " NE_STRINGIZE(__LINE__) ":" # x), x))
-#define NE_HELPER_LOOP(v) \
-    for (size_t i = 0; i != v.size(); ++i) { \
-        for (size_t j = 0; j != v.size(); ++j) { \
-            if (i == j) \
-                continue; \
-            EXPECT_REFV_NE(v[i].second, v[j].second) \
-                << v[i].first \
-                << " (" << ::testing::PrintToString(*v[i].second.get()) << ")" \
-                << "  ==  " \
-                << v[j].first \
-                << " (" << ::testing::PrintToString(*v[j].second.get()) << ")" \
-                << "\n"; \
-        } \
-    }
-
-namespace {
-
-using namespace WebCore;
-
-class TimingFunctionTestHelperTest : public ::testing::Test {
-
-public:
-    // Make sure that the CubicBezierTimingFunction call goes via the generic
-    // TimingFunction PrintTo.
-    ::std::string PrintToString(RefPtr<CubicBezierTimingFunction> timing)
-    {
-        RefPtr<TimingFunction> generic = timing;
-        return PrintToString(generic.get());
-    }
-
-    ::std::string PrintToString(RefPtr<TimingFunction> timing)
-    {
-        return PrintToString(timing.get());
-    }
-
-    ::std::string PrintToString(const TimingFunction* timing)
-    {
-        return ::testing::PrintToString(*timing);
-    }
-};
-
-TEST_F(TimingFunctionTestHelperTest, LinearPrintTo)
-{
-    RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
-    EXPECT_THAT(
-        PrintToString(linearTiming),
-        ::testing::MatchesRegex("LinearTimingFunction@.*"));
-}
-
-TEST_F(TimingFunctionTestHelperTest, CubicPrintTo)
-{
-    RefPtr<TimingFunction> cubicEaseTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
-    EXPECT_THAT(
-        PrintToString(cubicEaseTiming),
-        ::testing::MatchesRegex("CubicBezierTimingFunction@.*\\(EaseIn, 0.42, 0, 1, 1\\)"));
-
-    RefPtr<TimingFunction> cubicCustomTiming = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
-    EXPECT_THAT(
-        PrintToString(cubicCustomTiming),
-        ::testing::MatchesRegex("CubicBezierTimingFunction@.*\\(Custom, 0.17, 0.67, 1, -1.73\\)"));
-}
-
-TEST_F(TimingFunctionTestHelperTest, StepPrintTo)
-{
-    RefPtr<TimingFunction> stepTimingStart = StepsTimingFunction::preset(StepsTimingFunction::Start);
-    EXPECT_THAT(
-        PrintToString(stepTimingStart),
-        ::testing::MatchesRegex("StepsTimingFunction@.*\\(Start, 1, true\\)"));
-
-    RefPtr<TimingFunction> stepTimingCustom = StepsTimingFunction::create(5, false);
-    EXPECT_THAT(
-        PrintToString(stepTimingCustom),
-        ::testing::MatchesRegex("StepsTimingFunction@.*\\(Custom, 5, false\\)"));
-}
-
-TEST_F(TimingFunctionTestHelperTest, ChainedPrintTo)
-{
-    RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
-    RefPtr<ChainedTimingFunction> chainedLinearSingle = ChainedTimingFunction::create();
-    chainedLinearSingle->appendSegment(1.0, linearTiming.get());
-    EXPECT_THAT(
-        PrintToString(chainedLinearSingle),
-        ::testing::MatchesRegex(
-            "ChainedTimingFunction@.*\\("
-                "LinearTimingFunction@.*\\[0 -> 1\\]"
-            "\\)"));
-
-    RefPtr<TimingFunction> cubicCustomTiming = CubicBezierTimingFunction::create(1.0, 0.0, 1, -1);
-
-    RefPtr<ChainedTimingFunction> chainedMixed = ChainedTimingFunction::create();
-    chainedMixed->appendSegment(0.75, chainedLinearSingle.get());
-    chainedMixed->appendSegment(1.0, cubicCustomTiming.get());
-    EXPECT_THAT(
-        PrintToString(chainedMixed),
-        ::testing::MatchesRegex(
-            "ChainedTimingFunction@.*\\("
-                "ChainedTimingFunction@.*\\("
-                    "LinearTimingFunction@.*\\[0 -> 1\\]"
-                "\\)\\[0 -> 0.75\\], "
-                "CubicBezierTimingFunction@.*\\(Custom, 1, 0, 1, -1\\)\\[0.75 -> 1\\]"
-            "\\)"));
-}
-
-TEST_F(TimingFunctionTestHelperTest, BaseOperatorEq)
-{
-    RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
-    RefPtr<TimingFunction> cubicTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
-    RefPtr<TimingFunction> cubicTiming2 = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
-    RefPtr<TimingFunction> stepsTiming1 = StepsTimingFunction::preset(StepsTimingFunction::End);
-    RefPtr<TimingFunction> stepsTiming2 = StepsTimingFunction::create(5, true);
-
-    RefPtr<ChainedTimingFunction> chainedTiming1 = ChainedTimingFunction::create();
-    chainedTiming1->appendSegment(1.0, linearTiming.get());
-
-    RefPtr<ChainedTimingFunction> chainedTiming2 = ChainedTimingFunction::create();
-    chainedTiming2->appendSegment(0.5, cubicTiming1.get());
-    chainedTiming2->appendSegment(1.0, cubicTiming2.get());
-
-    NE_HELPER(v);
-    NE_HELPER_APPEND(v, linearTiming);
-    NE_HELPER_APPEND(v, cubicTiming1);
-    NE_HELPER_APPEND(v, cubicTiming2);
-    NE_HELPER_APPEND(v, stepsTiming1);
-    NE_HELPER_APPEND(v, stepsTiming2);
-    NE_HELPER_APPEND(v, chainedTiming1);
-    NE_HELPER_APPEND(v, chainedTiming2);
-    NE_HELPER_LOOP(v);
-}
-
-TEST_F(TimingFunctionTestHelperTest, LinearOperatorEq)
-{
-    RefPtr<TimingFunction> linearTiming1 = LinearTimingFunction::create();
-    RefPtr<TimingFunction> linearTiming2 = LinearTimingFunction::create();
-    EXPECT_REFV_EQ(linearTiming1, linearTiming1);
-    EXPECT_REFV_EQ(linearTiming1, linearTiming2);
-}
-
-TEST_F(TimingFunctionTestHelperTest, CubicOperatorEq)
-{
-    RefPtr<TimingFunction> cubicEaseInTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
-    RefPtr<TimingFunction> cubicEaseInTiming2 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
-    EXPECT_REFV_EQ(cubicEaseInTiming1, cubicEaseInTiming1);
-    EXPECT_REFV_EQ(cubicEaseInTiming1, cubicEaseInTiming2);
-
-    RefPtr<TimingFunction> cubicEaseOutTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
-    RefPtr<TimingFunction> cubicEaseOutTiming2 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
-    EXPECT_REFV_EQ(cubicEaseOutTiming1, cubicEaseOutTiming2);
-
-    RefPtr<TimingFunction> cubicEaseInOutTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut);
-    RefPtr<TimingFunction> cubicEaseInOutTiming2 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut);
-    EXPECT_REFV_EQ(cubicEaseInOutTiming1, cubicEaseInOutTiming2);
-
-    RefPtr<TimingFunction> cubicCustomTiming1 = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
-    RefPtr<TimingFunction> cubicCustomTiming2 = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
-    EXPECT_REFV_EQ(cubicCustomTiming1, cubicCustomTiming2);
-
-    NE_HELPER(v);
-    NE_HELPER_APPEND(v, cubicEaseInTiming1);
-    NE_HELPER_APPEND(v, cubicEaseOutTiming1);
-    NE_HELPER_APPEND(v, cubicEaseInOutTiming1);
-    NE_HELPER_APPEND(v, cubicCustomTiming1);
-    NE_HELPER_LOOP(v);
-}
-
-TEST_F(TimingFunctionTestHelperTest, CubicOperatorEqReflectivity)
-{
-    RefPtr<TimingFunction> cubicA = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
-    RefPtr<TimingFunction> cubicB = CubicBezierTimingFunction::create(0.42, 0.0, 1.0, 1.0);
-    EXPECT_REFV_NE(cubicA, cubicB);
-    EXPECT_REFV_NE(cubicB, cubicA);
-}
-
-TEST_F(TimingFunctionTestHelperTest, StepsOperatorEq)
-{
-    RefPtr<TimingFunction> stepsTimingStart1 = StepsTimingFunction::preset(StepsTimingFunction::Start);
-    RefPtr<TimingFunction> stepsTimingStart2 = StepsTimingFunction::preset(StepsTimingFunction::Start);
-    EXPECT_REFV_EQ(stepsTimingStart1, stepsTimingStart1);
-    EXPECT_REFV_EQ(stepsTimingStart1, stepsTimingStart2);
-
-    RefPtr<TimingFunction> stepsTimingEnd1 = StepsTimingFunction::preset(StepsTimingFunction::End);
-    RefPtr<TimingFunction> stepsTimingEnd2 = StepsTimingFunction::preset(StepsTimingFunction::End);
-    EXPECT_REFV_EQ(stepsTimingEnd1, stepsTimingEnd2);
-
-    RefPtr<TimingFunction> stepsTimingCustom1 = StepsTimingFunction::create(5, true);
-    RefPtr<TimingFunction> stepsTimingCustom2 = StepsTimingFunction::create(5, false);
-    RefPtr<TimingFunction> stepsTimingCustom3 = StepsTimingFunction::create(7, true);
-    RefPtr<TimingFunction> stepsTimingCustom4 = StepsTimingFunction::create(7, false);
-
-    EXPECT_REFV_EQ(stepsTimingCustom1, StepsTimingFunction::create(5, true));
-    EXPECT_REFV_EQ(stepsTimingCustom2, StepsTimingFunction::create(5, false));
-    EXPECT_REFV_EQ(stepsTimingCustom3, StepsTimingFunction::create(7, true));
-    EXPECT_REFV_EQ(stepsTimingCustom4, StepsTimingFunction::create(7, false));
-
-    NE_HELPER(v);
-    NE_HELPER_APPEND(v, stepsTimingStart1);
-    NE_HELPER_APPEND(v, stepsTimingEnd1);
-    NE_HELPER_APPEND(v, stepsTimingCustom1);
-    NE_HELPER_APPEND(v, stepsTimingCustom2);
-    NE_HELPER_APPEND(v, stepsTimingCustom3);
-    NE_HELPER_APPEND(v, stepsTimingCustom4);
-    NE_HELPER_LOOP(v);
-}
-
-TEST_F(TimingFunctionTestHelperTest, StepsOperatorEqReflectivity)
-{
-    RefPtr<TimingFunction> stepsA = StepsTimingFunction::preset(StepsTimingFunction::Start);
-    RefPtr<TimingFunction> stepsB = StepsTimingFunction::create(1, true);
-    EXPECT_REFV_NE(stepsA, stepsB);
-    EXPECT_REFV_NE(stepsB, stepsA);
-}
-
-TEST_F(TimingFunctionTestHelperTest, ChainedEq)
-{
-    // Single item in chain
-    RefPtr<TimingFunction> cubicTiming1 = CubicBezierTimingFunction::create(0.25, 0.1, 0.25, 1.0);
-    RefPtr<TimingFunction> cubicTiming2 = CubicBezierTimingFunction::create(0.25, 0.1, 0.25, 1.0);
-    RefPtr<TimingFunction> cubicTiming3 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
-
-    RefPtr<ChainedTimingFunction> chainedSingleCubic1 = ChainedTimingFunction::create();
-    chainedSingleCubic1->appendSegment(1.0, cubicTiming1.get());
-    EXPECT_REFV_EQ(chainedSingleCubic1, chainedSingleCubic1);
-
-    RefPtr<ChainedTimingFunction> chainedSingleCubic2 = ChainedTimingFunction::create();
-    chainedSingleCubic2->appendSegment(1.0, cubicTiming1.get()); // Same inner timing function
-    EXPECT_REFV_EQ(chainedSingleCubic1, chainedSingleCubic2);
-
-    RefPtr<ChainedTimingFunction> chainedSingleCubic3 = ChainedTimingFunction::create();
-    chainedSingleCubic3->appendSegment(1.0, cubicTiming2.get()); // == inner timing function
-    EXPECT_REFV_EQ(chainedSingleCubic1, chainedSingleCubic3);
-
-    RefPtr<ChainedTimingFunction> chainedSingleCubic4 = ChainedTimingFunction::create();
-    chainedSingleCubic4->appendSegment(0.5, cubicTiming1.get()); // Different offset
-    EXPECT_REFV_NE(chainedSingleCubic1, chainedSingleCubic4);
-    EXPECT_REFV_NE(chainedSingleCubic3, chainedSingleCubic4);
-
-    RefPtr<ChainedTimingFunction> chainedSingleCubic5 = ChainedTimingFunction::create();
-    chainedSingleCubic5->appendSegment(1.0, cubicTiming3.get()); // != inner timing function (same type)
-    EXPECT_REFV_NE(chainedSingleCubic1, chainedSingleCubic5);
-    EXPECT_REFV_NE(chainedSingleCubic2, chainedSingleCubic5);
-    EXPECT_REFV_NE(chainedSingleCubic3, chainedSingleCubic5);
-    EXPECT_REFV_NE(chainedSingleCubic4, chainedSingleCubic5);
-
-    RefPtr<TimingFunction> linearTiming1 = LinearTimingFunction::create();
-    RefPtr<ChainedTimingFunction> chainedSingleLinear1 = ChainedTimingFunction::create();
-    chainedSingleLinear1->appendSegment(1.0, linearTiming1.get()); // != inner timing function (different type)
-    EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic1);
-    EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic2);
-    EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic3);
-    EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic4);
-
-    // Multiple items in chain
-    RefPtr<ChainedTimingFunction> chainedMixed1 = ChainedTimingFunction::create();
-    chainedMixed1->appendSegment(0.25, chainedSingleLinear1.get());
-    chainedMixed1->appendSegment(1.0, cubicTiming1.get());
-
-    RefPtr<ChainedTimingFunction> chainedMixed2 = ChainedTimingFunction::create();
-    chainedMixed2->appendSegment(0.25, chainedSingleLinear1.get());
-    chainedMixed2->appendSegment(1.0, cubicTiming1.get());
-
-    RefPtr<ChainedTimingFunction> chainedMixed3 = ChainedTimingFunction::create();
-    chainedMixed3->appendSegment(0.25, chainedSingleLinear1.get());
-    chainedMixed3->appendSegment(1.0, cubicTiming2.get());
-
-    EXPECT_REFV_EQ(chainedMixed1, chainedMixed2);
-    EXPECT_REFV_EQ(chainedMixed1, chainedMixed3);
-    EXPECT_REFV_NE(chainedMixed1, chainedSingleCubic1);
-    EXPECT_REFV_NE(chainedMixed1, chainedSingleLinear1);
-
-    RefPtr<ChainedTimingFunction> chainedMixed4 = ChainedTimingFunction::create();
-    chainedMixed4->appendSegment(0.20, chainedSingleLinear1.get()); // Different offset
-    chainedMixed4->appendSegment(1.0, cubicTiming1.get());
-    EXPECT_REFV_NE(chainedMixed1, chainedMixed4);
-}
-
-} // namespace
diff --git a/Source/core/platform/chromium/ChromiumDataObject.cpp b/Source/core/platform/chromium/ChromiumDataObject.cpp
deleted file mode 100644
index dbb6641..0000000
--- a/Source/core/platform/chromium/ChromiumDataObject.cpp
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
-
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/DataTransferItem.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/platform/Pasteboard.h"
-#include "platform/clipboard/ClipboardMimeTypes.h"
-#include "platform/clipboard/ClipboardUtilities.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebClipboard.h"
-
-namespace WebCore {
-
-PassRefPtr<ChromiumDataObject> ChromiumDataObject::createFromPasteboard(PasteMode pasteMode)
-{
-    RefPtr<ChromiumDataObject> dataObject = create();
-    blink::WebClipboard::Buffer buffer = Pasteboard::generalPasteboard()->buffer();
-    uint64_t sequenceNumber = blink::Platform::current()->clipboard()->sequenceNumber(buffer);
-    bool ignored;
-    blink::WebVector<blink::WebString> webTypes = blink::Platform::current()->clipboard()->readAvailableTypes(buffer, &ignored);
-    ListHashSet<String> types;
-    for (size_t i = 0; i < webTypes.size(); ++i)
-        types.add(webTypes[i]);
-    for (ListHashSet<String>::const_iterator it = types.begin(); it != types.end(); ++it) {
-        if (pasteMode == PlainTextOnly && *it != mimeTypeTextPlain)
-            continue;
-        dataObject->m_itemList.append(ChromiumDataObjectItem::createFromPasteboard(*it, sequenceNumber));
-    }
-    return dataObject.release();
-}
-
-PassRefPtr<ChromiumDataObject> ChromiumDataObject::create()
-{
-    return adoptRef(new ChromiumDataObject());
-}
-
-PassRefPtr<ChromiumDataObject> ChromiumDataObject::copy() const
-{
-    return adoptRef(new ChromiumDataObject(*this));
-}
-
-size_t ChromiumDataObject::length() const
-{
-    return m_itemList.size();
-}
-
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::item(unsigned long index)
-{
-    if (index >= length())
-        return 0;
-    return m_itemList[index];
-}
-
-void ChromiumDataObject::deleteItem(unsigned long index)
-{
-    if (index >= length())
-        return;
-    m_itemList.remove(index);
-}
-
-void ChromiumDataObject::clearAll()
-{
-    m_itemList.clear();
-}
-
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(const String& data, const String& type, ExceptionState& exceptionState)
-{
-    RefPtr<ChromiumDataObjectItem> item = ChromiumDataObjectItem::createFromString(type, data);
-    if (!internalAddStringItem(item)) {
-        exceptionState.throwDOMException(NotSupportedError, "An item already exists for type '" + type + "'.");
-        return 0;
-    }
-    return item;
-}
-
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(PassRefPtr<File> file)
-{
-    if (!file)
-        return 0;
-
-    RefPtr<ChromiumDataObjectItem> item = ChromiumDataObjectItem::createFromFile(file);
-    m_itemList.append(item);
-    return item;
-}
-
-void ChromiumDataObject::clearData(const String& type)
-{
-    for (size_t i = 0; i < m_itemList.size(); ++i) {
-        if (m_itemList[i]->kind() == DataTransferItem::kindString && m_itemList[i]->type() == type) {
-            // Per the spec, type must be unique among all items of kind 'string'.
-            m_itemList.remove(i);
-            return;
-        }
-    }
-}
-
-void ChromiumDataObject::clearAllExceptFiles()
-{
-    for (size_t i = 0; i < m_itemList.size(); ) {
-        if (m_itemList[i]->kind() != DataTransferItem::kindFile) {
-            m_itemList.remove(i);
-            continue;
-        }
-        ++i;
-    }
-}
-
-ListHashSet<String> ChromiumDataObject::types() const
-{
-    ListHashSet<String> results;
-    bool containsFiles = false;
-    for (size_t i = 0; i < m_itemList.size(); ++i) {
-        if (m_itemList[i]->kind() == DataTransferItem::kindString)
-            results.add(m_itemList[i]->type());
-        else if (m_itemList[i]->kind() == DataTransferItem::kindFile)
-            containsFiles = true;
-        else
-            ASSERT_NOT_REACHED();
-    }
-    if (containsFiles)
-        results.add(mimeTypeFiles);
-    return results;
-}
-
-String ChromiumDataObject::getData(const String& type) const
-{
-    for (size_t i = 0; i < m_itemList.size(); ++i)  {
-        if (m_itemList[i]->kind() == DataTransferItem::kindString && m_itemList[i]->type() == type)
-            return m_itemList[i]->internalGetAsString();
-    }
-    return String();
-}
-
-bool ChromiumDataObject::setData(const String& type, const String& data)
-{
-    clearData(type);
-    add(data, type, ASSERT_NO_EXCEPTION);
-    return true;
-}
-
-void ChromiumDataObject::urlAndTitle(String& url, String* title) const
-{
-    RefPtr<ChromiumDataObjectItem> item = findStringItem(mimeTypeTextURIList);
-    if (!item)
-        return;
-    url = convertURIListToURL(item->internalGetAsString());
-    if (title)
-        *title = item->title();
-}
-
-void ChromiumDataObject::setURLAndTitle(const String& url, const String& title)
-{
-    clearData(mimeTypeTextURIList);
-    internalAddStringItem(ChromiumDataObjectItem::createFromURL(url, title));
-}
-
-void ChromiumDataObject::htmlAndBaseURL(String& html, KURL& baseURL) const
-{
-    RefPtr<ChromiumDataObjectItem> item = findStringItem(mimeTypeTextHTML);
-    if (!item)
-        return;
-    html = item->internalGetAsString();
-    baseURL = item->baseURL();
-}
-
-void ChromiumDataObject::setHTMLAndBaseURL(const String& html, const KURL& baseURL)
-{
-    clearData(mimeTypeTextHTML);
-    internalAddStringItem(ChromiumDataObjectItem::createFromHTML(html, baseURL));
-}
-
-bool ChromiumDataObject::containsFilenames() const
-{
-    for (size_t i = 0; i < m_itemList.size(); ++i)
-        if (m_itemList[i]->isFilename())
-            return true;
-    return false;
-}
-
-Vector<String> ChromiumDataObject::filenames() const
-{
-    Vector<String> results;
-    for (size_t i = 0; i < m_itemList.size(); ++i)
-        if (m_itemList[i]->isFilename())
-            results.append(static_cast<File*>(m_itemList[i]->getAsFile().get())->path());
-    return results;
-}
-
-void ChromiumDataObject::addFilename(const String& filename, const String& displayName)
-{
-    internalAddFileItem(ChromiumDataObjectItem::createFromFile(File::createWithName(filename, displayName, File::AllContentTypes)));
-}
-
-void ChromiumDataObject::addSharedBuffer(const String& name, PassRefPtr<SharedBuffer> buffer)
-{
-    internalAddFileItem(ChromiumDataObjectItem::createFromSharedBuffer(name, buffer));
-}
-
-ChromiumDataObject::ChromiumDataObject()
-    : m_modifierKeyState(0)
-{
-}
-
-ChromiumDataObject::ChromiumDataObject(const ChromiumDataObject& other)
-    : RefCounted<ChromiumDataObject>()
-    , m_itemList(other.m_itemList)
-    , m_modifierKeyState(0)
-{
-}
-
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::findStringItem(const String& type) const
-{
-    for (size_t i = 0; i < m_itemList.size(); ++i) {
-        if (m_itemList[i]->kind() == DataTransferItem::kindString && m_itemList[i]->type() == type)
-            return m_itemList[i];
-    }
-    return 0;
-}
-
-bool ChromiumDataObject::internalAddStringItem(PassRefPtr<ChromiumDataObjectItem> item)
-{
-    ASSERT(item->kind() == DataTransferItem::kindString);
-    for (size_t i = 0; i < m_itemList.size(); ++i)
-        if (m_itemList[i]->kind() == DataTransferItem::kindString && m_itemList[i]->type() == item->type())
-            return false;
-
-    m_itemList.append(item);
-    return true;
-}
-
-void ChromiumDataObject::internalAddFileItem(PassRefPtr<ChromiumDataObjectItem> item)
-{
-    ASSERT(item->kind() == DataTransferItem::kindFile);
-    m_itemList.append(item);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/chromium/FramelessScrollView.cpp b/Source/core/platform/chromium/FramelessScrollView.cpp
deleted file mode 100644
index 8c810f5..0000000
--- a/Source/core/platform/chromium/FramelessScrollView.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/platform/chromium/FramelessScrollView.h"
-
-#include "core/platform/chromium/FramelessScrollViewClient.h"
-
-namespace WebCore {
-
-FramelessScrollView::~FramelessScrollView()
-{
-    // Remove native scrollbars now before we lose the connection to the HostWindow.
-    setHasHorizontalScrollbar(false);
-    setHasVerticalScrollbar(false);
-}
-
-void FramelessScrollView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
-{
-    // Add in our offset within the ScrollView.
-    IntRect dirtyRect = rect;
-    dirtyRect.move(scrollbar->x(), scrollbar->y());
-    invalidateRect(dirtyRect);
-}
-
-bool FramelessScrollView::isActive() const
-{
-    // FIXME
-    return true;
-}
-
-ScrollableArea* FramelessScrollView::enclosingScrollableArea() const
-{
-    // FIXME: Look for an ancestor scrollable area that can be scrolled.
-    return 0;
-}
-
-bool FramelessScrollView::scrollbarsCanBeActive() const
-{
-    return isActive();
-}
-
-IntRect FramelessScrollView::scrollableAreaBoundingBox() const
-{
-    return windowClipRect(false);
-}
-
-void FramelessScrollView::invalidateRect(const IntRect& rect)
-{
-    if (HostWindow* h = hostWindow())
-        h->invalidateContentsAndRootView(rect);
-}
-
-HostWindow* FramelessScrollView::hostWindow() const
-{
-    return const_cast<FramelessScrollViewClient*>(m_client);
-}
-
-IntRect FramelessScrollView::windowClipRect(bool clipToContents) const
-{
-    IntRect clipRect = visibleContentRect(clipToContents ? ExcludeScrollbars : IncludeScrollbars);
-    if (shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar())
-        clipRect.move(verticalScrollbar()->width(), 0);
-    return contentsToWindow(clipRect);
-}
-
-void FramelessScrollView::paintContents(GraphicsContext*, const IntRect&)
-{
-}
-
-void FramelessScrollView::contentsResized()
-{
-}
-
-void FramelessScrollView::scrollbarExistenceDidChange()
-{
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/chromium/FramelessScrollView.h b/Source/core/platform/chromium/FramelessScrollView.h
deleted file mode 100644
index 0d04e8e..0000000
--- a/Source/core/platform/chromium/FramelessScrollView.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef FramelessScrollView_h
-#define FramelessScrollView_h
-
-#include "platform/scroll/ScrollView.h"
-
-namespace WebCore {
-
-    class FramelessScrollViewClient;
-    class PlatformGestureEvent;
-    class PlatformKeyboardEvent;
-    class PlatformMouseEvent;
-    class PlatformTouchEvent;
-    class PlatformWheelEvent;
-
-    // A FramelessScrollView is a ScrollView that can be used to render custom
-    // content, which does not have an associated Frame.
-    //
-    // NOTE: It may be better to just develop a custom subclass of Widget that
-    // can have scroll bars for this instead of trying to reuse ScrollView.
-    //
-    class FramelessScrollView : public ScrollView {
-    public:
-        FramelessScrollView() : m_client(0) {}
-        ~FramelessScrollView();
-
-        FramelessScrollViewClient* client() const { return m_client; }
-        void setClient(FramelessScrollViewClient* client) { m_client = client; }
-
-        // Event handlers that subclasses must implement.
-        virtual bool handleMouseDownEvent(const PlatformMouseEvent&) = 0;
-        virtual bool handleMouseMoveEvent(const PlatformMouseEvent&) = 0;
-        virtual bool handleMouseReleaseEvent(const PlatformMouseEvent&) = 0;
-        virtual bool handleWheelEvent(const PlatformWheelEvent&) = 0;
-        virtual bool handleKeyEvent(const PlatformKeyboardEvent&) = 0;
-        virtual bool handleTouchEvent(const PlatformTouchEvent&) = 0;
-        virtual bool handleGestureEvent(const PlatformGestureEvent&) = 0;
-
-        // ScrollableArea public methods:
-        virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&) OVERRIDE;
-        virtual bool isActive() const OVERRIDE;
-        virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
-        virtual bool scrollbarsCanBeActive() const OVERRIDE;
-        virtual IntRect scrollableAreaBoundingBox() const OVERRIDE;
-
-        // Widget public methods:
-        virtual void invalidateRect(const IntRect&);
-
-        // ScrollView public methods:
-        virtual HostWindow* hostWindow() const;
-        virtual IntRect windowClipRect(bool clipToContents = true) const;
-
-    protected:
-        // ScrollView protected methods:
-        virtual void paintContents(GraphicsContext*, const IntRect&);
-        virtual void contentsResized();
-        virtual void scrollbarExistenceDidChange();
-
-    private:
-        FramelessScrollViewClient* m_client;
-    };
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/chromium/FramelessScrollViewClient.h b/Source/core/platform/chromium/FramelessScrollViewClient.h
deleted file mode 100644
index 048dd45..0000000
--- a/Source/core/platform/chromium/FramelessScrollViewClient.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef FramelessScrollViewClient_h
-#define FramelessScrollViewClient_h
-
-#include "platform/HostWindow.h"
-
-namespace WebCore {
-    class FramelessScrollView;
-
-    class FramelessScrollViewClient : public HostWindow {
-    public:
-        virtual void popupClosed(FramelessScrollView* popup_view) = 0;
-    };
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp b/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp
deleted file mode 100644
index e2a2df1..0000000
--- a/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- * Copyright 2007, The Android Open Source Project
- * Copyright (C) 2006, 2007 Apple Inc.  All rights reserved.
- * Copyright (C) 2006 Michael Emmel mike.emmel@gmail.com
- * Copyright (C) 2007 Holger Hans Peter Freyther
- * Copyright (C) 2008 Collabora, Ltd.  All rights reserved.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * 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 THE COPYRIGHT HOLDERS ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-#include "core/platform/chromium/KeyboardCodes.h"
-
-#include <android/keycodes.h>
-
-namespace WebCore {
-
-// The Android NDK does not provide values for these yet:
-enum {
-    AKEYCODE_ESCAPE          = 111,
-    AKEYCODE_FORWARD_DEL     = 112,
-    AKEYCODE_CTRL_LEFT       = 113,
-    AKEYCODE_CTRL_RIGHT      = 114,
-    AKEYCODE_CAPS_LOCK       = 115,
-    AKEYCODE_SCROLL_LOCK     = 116,
-    AKEYCODE_META_LEFT       = 117,
-    AKEYCODE_META_RIGHT      = 118,
-    AKEYCODE_BREAK           = 121,
-    AKEYCODE_INSERT          = 124,
-    AKEYCODE_MEDIA_PLAY      = 126,
-    AKEYCODE_MEDIA_PAUSE     = 127,
-    AKEYCODE_F1              = 131,
-    AKEYCODE_F2              = 132,
-    AKEYCODE_F3              = 133,
-    AKEYCODE_F4              = 134,
-    AKEYCODE_F5              = 135,
-    AKEYCODE_F6              = 136,
-    AKEYCODE_F7              = 137,
-    AKEYCODE_F8              = 138,
-    AKEYCODE_F9              = 139,
-    AKEYCODE_F10             = 140,
-    AKEYCODE_F11             = 141,
-    AKEYCODE_F12             = 142,
-    AKEYCODE_NUM_LOCK        = 143,
-    AKEYCODE_NUMPAD_0        = 144,
-    AKEYCODE_NUMPAD_1        = 145,
-    AKEYCODE_NUMPAD_2        = 146,
-    AKEYCODE_NUMPAD_3        = 147,
-    AKEYCODE_NUMPAD_4        = 148,
-    AKEYCODE_NUMPAD_5        = 149,
-    AKEYCODE_NUMPAD_6        = 150,
-    AKEYCODE_NUMPAD_7        = 151,
-    AKEYCODE_NUMPAD_8        = 152,
-    AKEYCODE_NUMPAD_9        = 153,
-    AKEYCODE_NUMPAD_DIVIDE   = 154,
-    AKEYCODE_NUMPAD_MULTIPLY = 155,
-    AKEYCODE_NUMPAD_SUBTRACT = 156,
-    AKEYCODE_NUMPAD_ADD      = 157,
-    AKEYCODE_NUMPAD_DOT      = 158,
-    AKEYCODE_VOLUME_MUTE     = 164,
-    AKEYCODE_CHANNEL_UP      = 166,
-    AKEYCODE_CHANNEL_DOWN    = 167,
-};
-
-int windowsKeyCodeForKeyEvent(unsigned int keyCode)
-{
-    // Does not provide all key codes, and does not handle all keys.
-    switch (keyCode) {
-    case AKEYCODE_DEL:
-        return VKEY_BACK;
-    case AKEYCODE_TAB:
-        return VKEY_TAB;
-    case AKEYCODE_CLEAR:
-        return VKEY_CLEAR;
-    case AKEYCODE_DPAD_CENTER:
-    case AKEYCODE_ENTER:
-        return VKEY_RETURN;
-    case AKEYCODE_SHIFT_LEFT:
-        return VKEY_LSHIFT;
-    case AKEYCODE_SHIFT_RIGHT:
-        return VKEY_RSHIFT;
-    // Back will serve as escape, although we may not have access to it.
-    case AKEYCODE_BACK:
-        return VKEY_ESCAPE;
-    case AKEYCODE_SPACE:
-        return VKEY_SPACE;
-    case AKEYCODE_HOME:
-        return VKEY_HOME;
-    case AKEYCODE_DPAD_LEFT:
-        return VKEY_LEFT;
-    case AKEYCODE_DPAD_UP:
-        return VKEY_UP;
-    case AKEYCODE_DPAD_RIGHT:
-        return VKEY_RIGHT;
-    case AKEYCODE_DPAD_DOWN:
-        return VKEY_DOWN;
-    case AKEYCODE_0:
-        return VKEY_0;
-    case AKEYCODE_1:
-        return VKEY_1;
-    case AKEYCODE_2:
-        return VKEY_2;
-    case AKEYCODE_3:
-        return VKEY_3;
-    case AKEYCODE_4:
-        return VKEY_4;
-    case AKEYCODE_5:
-        return VKEY_5;
-    case AKEYCODE_6:
-        return VKEY_6;
-    case AKEYCODE_7:
-        return VKEY_7;
-    case AKEYCODE_8:
-        return VKEY_8;
-    case AKEYCODE_9:
-        return VKEY_9;
-    case AKEYCODE_A:
-        return VKEY_A;
-    case AKEYCODE_B:
-        return VKEY_B;
-    case AKEYCODE_C:
-        return VKEY_C;
-    case AKEYCODE_D:
-        return VKEY_D;
-    case AKEYCODE_E:
-        return VKEY_E;
-    case AKEYCODE_F:
-        return VKEY_F;
-    case AKEYCODE_G:
-        return VKEY_G;
-    case AKEYCODE_H:
-        return VKEY_H;
-    case AKEYCODE_I:
-        return VKEY_I;
-    case AKEYCODE_J:
-        return VKEY_J;
-    case AKEYCODE_K:
-        return VKEY_K;
-    case AKEYCODE_L:
-        return VKEY_L;
-    case AKEYCODE_M:
-        return VKEY_M;
-    case AKEYCODE_N:
-        return VKEY_N;
-    case AKEYCODE_O:
-        return VKEY_O;
-    case AKEYCODE_P:
-        return VKEY_P;
-    case AKEYCODE_Q:
-        return VKEY_Q;
-    case AKEYCODE_R:
-        return VKEY_R;
-    case AKEYCODE_S:
-        return VKEY_S;
-    case AKEYCODE_T:
-        return VKEY_T;
-    case AKEYCODE_U:
-        return VKEY_U;
-    case AKEYCODE_V:
-        return VKEY_V;
-    case AKEYCODE_W:
-        return VKEY_W;
-    case AKEYCODE_X:
-        return VKEY_X;
-    case AKEYCODE_Y:
-        return VKEY_Y;
-    case AKEYCODE_Z:
-        return VKEY_Z;
-    case AKEYCODE_VOLUME_DOWN:
-        return VKEY_VOLUME_DOWN;
-    case AKEYCODE_VOLUME_UP:
-        return VKEY_VOLUME_UP;
-    case AKEYCODE_MEDIA_NEXT:
-        return VKEY_MEDIA_NEXT_TRACK;
-    case AKEYCODE_MEDIA_PREVIOUS:
-        return VKEY_MEDIA_PREV_TRACK;
-    case AKEYCODE_MEDIA_STOP:
-        return VKEY_MEDIA_STOP;
-    case AKEYCODE_MEDIA_PAUSE:
-        return VKEY_MEDIA_PLAY_PAUSE;
-    // Colon key.
-    case AKEYCODE_SEMICOLON:
-        return VKEY_OEM_1;
-    case AKEYCODE_COMMA:
-        return VKEY_OEM_COMMA;
-    case AKEYCODE_MINUS:
-        return VKEY_OEM_MINUS;
-    case AKEYCODE_EQUALS:
-        return VKEY_OEM_PLUS;
-    case AKEYCODE_PERIOD:
-        return VKEY_OEM_PERIOD;
-    case AKEYCODE_SLASH:
-        return VKEY_OEM_2;
-    case AKEYCODE_LEFT_BRACKET:
-        return VKEY_OEM_4;
-    case AKEYCODE_BACKSLASH:
-        return VKEY_OEM_5;
-    case AKEYCODE_RIGHT_BRACKET:
-        return VKEY_OEM_6;
-    case AKEYCODE_MUTE:
-    case AKEYCODE_VOLUME_MUTE:
-        return VKEY_VOLUME_MUTE;
-    case AKEYCODE_ESCAPE:
-        return VKEY_ESCAPE;
-    case AKEYCODE_MEDIA_PLAY:
-    case AKEYCODE_MEDIA_PLAY_PAUSE:
-        return VKEY_MEDIA_PLAY_PAUSE;
-    case AKEYCODE_CALL:
-        return VKEY_END;
-    case AKEYCODE_ALT_LEFT:
-        return VKEY_LMENU;
-    case AKEYCODE_ALT_RIGHT:
-        return VKEY_RMENU;
-    case AKEYCODE_GRAVE:
-        return VKEY_OEM_3;
-    case AKEYCODE_APOSTROPHE:
-        return VKEY_OEM_3;
-    case AKEYCODE_MEDIA_REWIND:
-        return VKEY_OEM_103;
-    case AKEYCODE_MEDIA_FAST_FORWARD:
-        return VKEY_OEM_104;
-    case AKEYCODE_PAGE_UP:
-        return VKEY_PRIOR;
-    case AKEYCODE_PAGE_DOWN:
-        return VKEY_NEXT;
-    case AKEYCODE_FORWARD_DEL:
-        return VKEY_DELETE;
-    case AKEYCODE_CTRL_LEFT:
-        return VKEY_LCONTROL;
-    case AKEYCODE_CTRL_RIGHT:
-        return VKEY_RCONTROL;
-    case AKEYCODE_CAPS_LOCK:
-        return VKEY_CAPITAL;
-    case AKEYCODE_SCROLL_LOCK:
-        return VKEY_SCROLL;
-    case AKEYCODE_META_LEFT:
-        return VKEY_LWIN;
-    case AKEYCODE_META_RIGHT:
-        return VKEY_RWIN;
-    case AKEYCODE_BREAK:
-        return VKEY_PAUSE;
-    case AKEYCODE_INSERT:
-        return VKEY_INSERT;
-    case AKEYCODE_F1:
-        return VKEY_F1;
-    case AKEYCODE_F2:
-        return VKEY_F2;
-    case AKEYCODE_F3:
-        return VKEY_F3;
-    case AKEYCODE_F4:
-        return VKEY_F4;
-    case AKEYCODE_F5:
-        return VKEY_F5;
-    case AKEYCODE_F6:
-        return VKEY_F6;
-    case AKEYCODE_F7:
-        return VKEY_F7;
-    case AKEYCODE_F8:
-        return VKEY_F8;
-    case AKEYCODE_F9:
-        return VKEY_F9;
-    case AKEYCODE_F10:
-        return VKEY_F10;
-    case AKEYCODE_F11:
-        return VKEY_F11;
-    case AKEYCODE_F12:
-        return VKEY_F12;
-    case AKEYCODE_NUM_LOCK:
-        return VKEY_NUMLOCK;
-    case AKEYCODE_NUMPAD_0:
-        return VKEY_NUMPAD0;
-    case AKEYCODE_NUMPAD_1:
-        return VKEY_NUMPAD1;
-    case AKEYCODE_NUMPAD_2:
-        return VKEY_NUMPAD2;
-    case AKEYCODE_NUMPAD_3:
-        return VKEY_NUMPAD3;
-    case AKEYCODE_NUMPAD_4:
-        return VKEY_NUMPAD4;
-    case AKEYCODE_NUMPAD_5:
-        return VKEY_NUMPAD5;
-    case AKEYCODE_NUMPAD_6:
-        return VKEY_NUMPAD6;
-    case AKEYCODE_NUMPAD_7:
-        return VKEY_NUMPAD7;
-    case AKEYCODE_NUMPAD_8:
-        return VKEY_NUMPAD8;
-    case AKEYCODE_NUMPAD_9:
-        return VKEY_NUMPAD9;
-    case AKEYCODE_NUMPAD_DIVIDE:
-        return VKEY_DIVIDE;
-    case AKEYCODE_NUMPAD_MULTIPLY:
-        return VKEY_MULTIPLY;
-    case AKEYCODE_NUMPAD_SUBTRACT:
-        return VKEY_SUBTRACT;
-    case AKEYCODE_NUMPAD_ADD:
-        return VKEY_ADD;
-    case AKEYCODE_NUMPAD_DOT:
-        return VKEY_DECIMAL;
-    case AKEYCODE_CHANNEL_UP:
-        return VKEY_PRIOR;
-    case AKEYCODE_CHANNEL_DOWN:
-        return VKEY_NEXT;
-    default:
-        return 0;
-    }
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/chromium/KeyCodeConversionGtk.cpp b/Source/core/platform/chromium/KeyCodeConversionGtk.cpp
deleted file mode 100644
index 354acc0..0000000
--- a/Source/core/platform/chromium/KeyCodeConversionGtk.cpp
+++ /dev/null
@@ -1,436 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc.  All rights reserved.
- * Copyright (C) 2006 Michael Emmel mike.emmel@gmail.com
- * Copyright (C) 2007 Holger Hans Peter Freyther
- * Copyright (C) 2008 Collabora, Ltd.  All rights reserved.
- * Copyright (C) 2008, 2009 Google Inc.
- *
- * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-// windowsKeyCodeForKeyEvent is copied from platform/gtk/KeyEventGtk.cpp
-
-#include "config.h"
-#include "core/platform/chromium/KeyCodeConversion.h"
-
-#include "core/platform/chromium/KeyboardCodes.h"
-
-#include <gdk/gdkkeysyms.h>
-
-namespace WebCore {
-
-int windowsKeyCodeForKeyEvent(unsigned keycode)
-{
-    switch (keycode) {
-    case GDK_KP_0:
-        return VKEY_NUMPAD0; // (60) Numeric keypad 0 key
-    case GDK_KP_1:
-        return VKEY_NUMPAD1; // (61) Numeric keypad 1 key
-    case GDK_KP_2:
-        return  VKEY_NUMPAD2; // (62) Numeric keypad 2 key
-    case GDK_KP_3:
-        return VKEY_NUMPAD3; // (63) Numeric keypad 3 key
-    case GDK_KP_4:
-        return VKEY_NUMPAD4; // (64) Numeric keypad 4 key
-    case GDK_KP_5:
-        return VKEY_NUMPAD5; //(65) Numeric keypad 5 key
-    case GDK_KP_6:
-        return VKEY_NUMPAD6; // (66) Numeric keypad 6 key
-    case GDK_KP_7:
-        return VKEY_NUMPAD7; // (67) Numeric keypad 7 key
-    case GDK_KP_8:
-        return VKEY_NUMPAD8; // (68) Numeric keypad 8 key
-    case GDK_KP_9:
-        return VKEY_NUMPAD9; // (69) Numeric keypad 9 key
-    case GDK_KP_Multiply:
-        return VKEY_MULTIPLY; // (6A) Multiply key
-    case GDK_KP_Add:
-        return VKEY_ADD; // (6B) Add key
-    case GDK_KP_Subtract:
-        return VKEY_SUBTRACT; // (6D) Subtract key
-    case GDK_KP_Decimal:
-        return VKEY_DECIMAL; // (6E) Decimal key
-    case GDK_KP_Divide:
-        return VKEY_DIVIDE; // (6F) Divide key
-
-    case GDK_KP_Page_Up:
-        return VKEY_PRIOR; // (21) PAGE UP key
-    case GDK_KP_Page_Down:
-        return VKEY_NEXT; // (22) PAGE DOWN key
-    case GDK_KP_End:
-        return VKEY_END; // (23) END key
-    case GDK_KP_Home:
-        return VKEY_HOME; // (24) HOME key
-    case GDK_KP_Left:
-        return VKEY_LEFT; // (25) LEFT ARROW key
-    case GDK_KP_Up:
-        return VKEY_UP; // (26) UP ARROW key
-    case GDK_KP_Right:
-        return VKEY_RIGHT; // (27) RIGHT ARROW key
-    case GDK_KP_Down:
-        return VKEY_DOWN; // (28) DOWN ARROW key
-    case GDK_KP_Begin:
-        return VKEY_CLEAR; // (12) CLEAR key
-    case GDK_KP_Insert:
-        return VKEY_INSERT; // (45) INS key
-    case GDK_KP_Delete:
-        return VKEY_DELETE; // (46) DEL key
-
-    case GDK_BackSpace:
-        return VKEY_BACK; // (08) BACKSPACE key
-    case GDK_ISO_Left_Tab:
-    case GDK_3270_BackTab:
-    case GDK_Tab:
-        return VKEY_TAB; // (09) TAB key
-    case GDK_Clear:
-        return VKEY_CLEAR; // (0C) CLEAR key
-    case GDK_ISO_Enter:
-    case GDK_KP_Enter:
-    case GDK_Return:
-        return VKEY_RETURN; //(0D) Return key
-    case GDK_Shift_L:
-        return VKEY_LSHIFT; // (A0) Left SHIFT key
-    case GDK_Shift_R:
-        return VKEY_RSHIFT; // (A1) Right SHIFT key
-    case GDK_Control_L:
-        return VKEY_LCONTROL; // (A2) Left CTRL key
-    case GDK_Control_R:
-        return VKEY_RCONTROL; // (A3) Right CTRL key
-    case GDK_Menu:
-        return VKEY_APPS;  // (5D) Applications key (Natural keyboard)
-    case GDK_Alt_L:
-    case GDK_Meta_L:
-        return VKEY_LMENU; // (A4) Left ALT key
-    case GDK_Alt_R:
-    case GDK_Meta_R:
-    case GDK_ISO_Level3_Shift:
-        return VKEY_RMENU; // (A5) Right ALT key
-
-    case GDK_Pause:
-        return VKEY_PAUSE; // (13) PAUSE key
-    case GDK_Caps_Lock:
-        return VKEY_CAPITAL; // (14) CAPS LOCK key
-    case GDK_Kana_Lock:
-    case GDK_Kana_Shift:
-        return VKEY_KANA; // (15) Input Method Editor (IME) Kana mode
-    case GDK_Hangul:
-        return VKEY_HANGUL; // VKEY_HANGUL (15) IME Hangul mode
-        // VKEY_JUNJA (17) IME Junja mode
-        // VKEY_FINAL (18) IME final mode
-    case GDK_Hangul_Hanja:
-        return VKEY_HANJA; // (19) IME Hanja mode
-    case GDK_Kanji:
-        return VKEY_KANJI; // (19) IME Kanji mode
-    case GDK_Escape:
-        return VKEY_ESCAPE; // (1B) ESC key
-        // VKEY_CONVERT (1C) IME convert
-        // VKEY_NONCONVERT (1D) IME nonconvert
-        // VKEY_ACCEPT (1E) IME accept
-        // VKEY_MODECHANGE (1F) IME mode change request
-    case GDK_space:
-        return VKEY_SPACE; // (20) SPACEBAR
-    case GDK_Page_Up:
-        return VKEY_PRIOR; // (21) PAGE UP key
-    case GDK_Page_Down:
-        return VKEY_NEXT; // (22) PAGE DOWN key
-    case GDK_End:
-        return VKEY_END; // (23) END key
-    case GDK_Home:
-        return VKEY_HOME; // (24) HOME key
-    case GDK_Left:
-        return VKEY_LEFT; // (25) LEFT ARROW key
-    case GDK_Up:
-        return VKEY_UP; // (26) UP ARROW key
-    case GDK_Right:
-        return VKEY_RIGHT; // (27) RIGHT ARROW key
-    case GDK_Down:
-        return VKEY_DOWN; // (28) DOWN ARROW key
-    case GDK_Select:
-        return VKEY_SELECT; // (29) SELECT key
-    case GDK_Print:
-        return VKEY_PRINT; // (2A) PRINT key
-    case GDK_Execute:
-        return VKEY_EXECUTE;// (2B) EXECUTE key
-        //dunno on this
-        //case GDK_PrintScreen:
-        //      return VKEY_SNAPSHOT; // (2C) PRINT SCREEN key
-    case GDK_Insert:
-        return VKEY_INSERT; // (2D) INS key
-    case GDK_Delete:
-        return VKEY_DELETE; // (2E) DEL key
-    case GDK_Help:
-        return VKEY_HELP; // (2F) HELP key
-    case GDK_0:
-    case GDK_parenright:
-        return VKEY_0;    //  (30) 0) key
-    case GDK_1:
-    case GDK_exclam:
-        return VKEY_1; //  (31) 1 ! key
-    case GDK_2:
-    case GDK_at:
-        return VKEY_2; //  (32) 2 & key
-    case GDK_3:
-    case GDK_numbersign:
-        return VKEY_3; //case '3': case '#';
-    case GDK_4:
-    case GDK_dollar: //  (34) 4 key '$';
-        return VKEY_4;
-    case GDK_5:
-    case GDK_percent:
-        return VKEY_5; //  (35) 5 key  '%'
-    case GDK_6:
-    case GDK_asciicircum:
-        return VKEY_6; //  (36) 6 key  '^'
-    case GDK_7:
-    case GDK_ampersand:
-        return VKEY_7; //  (37) 7 key  case '&'
-    case GDK_8:
-    case GDK_asterisk:
-        return VKEY_8; //  (38) 8 key  '*'
-    case GDK_9:
-    case GDK_parenleft:
-        return VKEY_9; //  (39) 9 key '('
-    case GDK_a:
-    case GDK_A:
-        return VKEY_A; //  (41) A key case 'a': case 'A': return 0x41;
-    case GDK_b:
-    case GDK_B:
-        return VKEY_B; //  (42) B key case 'b': case 'B': return 0x42;
-    case GDK_c:
-    case GDK_C:
-        return VKEY_C; //  (43) C key case 'c': case 'C': return 0x43;
-    case GDK_d:
-    case GDK_D:
-        return VKEY_D; //  (44) D key case 'd': case 'D': return 0x44;
-    case GDK_e:
-    case GDK_E:
-        return VKEY_E; //  (45) E key case 'e': case 'E': return 0x45;
-    case GDK_f:
-    case GDK_F:
-        return VKEY_F; //  (46) F key case 'f': case 'F': return 0x46;
-    case GDK_g:
-    case GDK_G:
-        return VKEY_G; //  (47) G key case 'g': case 'G': return 0x47;
-    case GDK_h:
-    case GDK_H:
-        return VKEY_H; //  (48) H key case 'h': case 'H': return 0x48;
-    case GDK_i:
-    case GDK_I:
-        return VKEY_I; //  (49) I key case 'i': case 'I': return 0x49;
-    case GDK_j:
-    case GDK_J:
-        return VKEY_J; //  (4A) J key case 'j': case 'J': return 0x4A;
-    case GDK_k:
-    case GDK_K:
-        return VKEY_K; //  (4B) K key case 'k': case 'K': return 0x4B;
-    case GDK_l:
-    case GDK_L:
-        return VKEY_L; //  (4C) L key case 'l': case 'L': return 0x4C;
-    case GDK_m:
-    case GDK_M:
-        return VKEY_M; //  (4D) M key case 'm': case 'M': return 0x4D;
-    case GDK_n:
-    case GDK_N:
-        return VKEY_N; //  (4E) N key case 'n': case 'N': return 0x4E;
-    case GDK_o:
-    case GDK_O:
-        return VKEY_O; //  (4F) O key case 'o': case 'O': return 0x4F;
-    case GDK_p:
-    case GDK_P:
-        return VKEY_P; //  (50) P key case 'p': case 'P': return 0x50;
-    case GDK_q:
-    case GDK_Q:
-        return VKEY_Q; //  (51) Q key case 'q': case 'Q': return 0x51;
-    case GDK_r:
-    case GDK_R:
-        return VKEY_R; //  (52) R key case 'r': case 'R': return 0x52;
-    case GDK_s:
-    case GDK_S:
-        return VKEY_S; //  (53) S key case 's': case 'S': return 0x53;
-    case GDK_t:
-    case GDK_T:
-        return VKEY_T; //  (54) T key case 't': case 'T': return 0x54;
-    case GDK_u:
-    case GDK_U:
-        return VKEY_U; //  (55) U key case 'u': case 'U': return 0x55;
-    case GDK_v:
-    case GDK_V:
-        return VKEY_V; //  (56) V key case 'v': case 'V': return 0x56;
-    case GDK_w:
-    case GDK_W:
-        return VKEY_W; //  (57) W key case 'w': case 'W': return 0x57;
-    case GDK_x:
-    case GDK_X:
-        return VKEY_X; //  (58) X key case 'x': case 'X': return 0x58;
-    case GDK_y:
-    case GDK_Y:
-        return VKEY_Y; //  (59) Y key case 'y': case 'Y': return 0x59;
-    case GDK_z:
-    case GDK_Z:
-        return VKEY_Z; //  (5A) Z key case 'z': case 'Z': return 0x5A;
-    case GDK_Super_L:
-        return VKEY_LWIN; // (5B) Left Windows key (Microsoft Natural keyboard)
-    case GDK_Super_R:
-        return VKEY_RWIN; // (5C) Right Windows key (Natural keyboard)
-        // VKEY_SLEEP (5F) Computer Sleep key
-        // VKEY_SEPARATOR (6C) Separator key
-        // VKEY_SUBTRACT (6D) Subtract key
-        // VKEY_DECIMAL (6E) Decimal key
-        // VKEY_DIVIDE (6F) Divide key
-        // handled by key code above
-
-    case GDK_Num_Lock:
-        return VKEY_NUMLOCK; // (90) NUM LOCK key
-
-    case GDK_Scroll_Lock:
-        return VKEY_SCROLL; // (91) SCROLL LOCK key
-
-        // VKEY_LSHIFT (A0) Left SHIFT key
-        // VKEY_RSHIFT (A1) Right SHIFT key
-        // VKEY_LCONTROL (A2) Left CONTROL key
-        // VKEY_RCONTROL (A3) Right CONTROL key
-        // VKEY_LMENU (A4) Left MENU key
-        // VKEY_RMENU (A5) Right MENU key
-    case GDK_Back:
-        return VKEY_BROWSER_BACK; // (A6) Windows 2000/XP: Browser Back key
-    case GDK_Forward:
-        return VKEY_BROWSER_FORWARD; // (A7) Windows 2000/XP: Browser Forward key
-    case GDK_Refresh:
-        return VKEY_BROWSER_REFRESH; // (A8) Windows 2000/XP: Browser Refresh key
-    case GDK_Stop:
-        return VKEY_BROWSER_STOP; // (A9) Windows 2000/XP: Browser Stop key
-    case GDK_Search:
-        return VKEY_BROWSER_SEARCH; // (AA) Windows 2000/XP: Browser Search key
-    case GDK_Favorites:
-        return VKEY_BROWSER_FAVORITES; // (AB) Windows 2000/XP: Browser Favorites key
-    case GDK_HomePage:
-        return VKEY_BROWSER_HOME; // (AC) Windows 2000/XP: Browser Start and Home key
-    case GDK_AudioMute:
-        return VKEY_VOLUME_MUTE; // (AD) Windows 2000/XP: Volume Mute key
-    case GDK_AudioLowerVolume:
-        return VKEY_VOLUME_DOWN; // (AE) Windows 2000/XP: Volume Down key
-    case GDK_AudioRaiseVolume:
-        return VKEY_VOLUME_UP; // (AF) Windows 2000/XP: Volume Up key
-    case GDK_AudioNext:
-        return VKEY_MEDIA_NEXT_TRACK; // (B0) Windows 2000/XP: Next Track key
-    case GDK_AudioPrev:
-        return VKEY_MEDIA_PREV_TRACK; // (B1) Windows 2000/XP: Previous Track key
-    case GDK_AudioStop:
-        return VKEY_MEDIA_STOP; // (B2) Windows 2000/XP: Stop Media key
-    case GDK_AudioPlay:
-        return VKEY_MEDIA_PLAY_PAUSE; // (B3) Windows 2000/XP: Play/Pause Media key
-    case GDK_Mail:
-        return VKEY_MEDIA_LAUNCH_MAIL; // (B4) Windows 2000/XP: Start Mail key
-        // VKEY_LAUNCH_MEDIA_SELECT (B5) Windows 2000/XP: Select Media key
-    case GDK_LaunchA:
-        return VKEY_MEDIA_LAUNCH_APP1; // (B6) Windows 2000/XP: Start Application 1 key
-    case GDK_LaunchB:
-        return VKEY_MEDIA_LAUNCH_APP2; // (B7) Windows 2000/XP: Start Application 2 key
-
-        // VKEY_OEM_1 (BA) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ';:' key
-    case GDK_semicolon:
-    case GDK_colon:
-        return VKEY_OEM_1; //case ';': case ':': return 0xBA;
-        // VKEY_OEM_PLUS (BB) Windows 2000/XP: For any country/region, the '+' key
-    case GDK_plus:
-    case GDK_equal:
-        return VKEY_OEM_PLUS; //case '=': case '+': return 0xBB;
-        // VKEY_OEM_COMMA (BC) Windows 2000/XP: For any country/region, the ',' key
-    case GDK_comma:
-    case GDK_less:
-        return VKEY_OEM_COMMA; //case ',': case '<': return 0xBC;
-        // VKEY_OEM_MINUS (BD) Windows 2000/XP: For any country/region, the '-' key
-    case GDK_minus:
-    case GDK_underscore:
-        return VKEY_OEM_MINUS; //case '-': case '_': return 0xBD;
-        // VKEY_OEM_PERIOD (BE) Windows 2000/XP: For any country/region, the '.' key
-    case GDK_period:
-    case GDK_greater:
-        return VKEY_OEM_PERIOD; //case '.': case '>': return 0xBE;
-        // VKEY_OEM_2 (BF) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key
-    case GDK_slash:
-    case GDK_question:
-        return VKEY_OEM_2; //case '/': case '?': return 0xBF;
-        // VKEY_OEM_3 (C0) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key
-    case GDK_asciitilde:
-    case GDK_quoteleft:
-        return VKEY_OEM_3; //case '`': case '~': return 0xC0;
-        // VKEY_OEM_4 (DB) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key
-    case GDK_bracketleft:
-    case GDK_braceleft:
-        return VKEY_OEM_4; //case '[': case '{': return 0xDB;
-        // VKEY_OEM_5 (DC) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key
-    case GDK_backslash:
-    case GDK_bar:
-        return VKEY_OEM_5; //case '\\': case '|': return 0xDC;
-        // VKEY_OEM_6 (DD) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key
-    case GDK_bracketright:
-    case GDK_braceright:
-        return VKEY_OEM_6; // case ']': case '}': return 0xDD;
-        // VKEY_OEM_7 (DE) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key
-    case GDK_quoteright:
-    case GDK_quotedbl:
-        return VKEY_OEM_7; // case '\'': case '"': return 0xDE;
-        // VKEY_OEM_8 (DF) Used for miscellaneous characters; it can vary by keyboard.
-        // VKEY_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
-        // VKEY_PROCESSKEY (E5) Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
-        // VKEY_PACKET (E7) Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VKEY_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT,SendInput, WM_KEYDOWN, and WM_KEYUP
-        // VKEY_ATTN (F6) Attn key
-        // VKEY_CRSEL (F7) CrSel key
-        // VKEY_EXSEL (F8) ExSel key
-        // VKEY_EREOF (F9) Erase EOF key
-        // VKEY_PLAY (FA) Play key
-        // VKEY_ZOOM (FB) Zoom key
-        // VKEY_NONAME (FC) Reserved for future use
-        // VKEY_PA1 (FD) PA1 key
-        // VKEY_OEM_CLEAR (FE) Clear key
-    case GDK_F1:
-    case GDK_F2:
-    case GDK_F3:
-    case GDK_F4:
-    case GDK_F5:
-    case GDK_F6:
-    case GDK_F7:
-    case GDK_F8:
-    case GDK_F9:
-    case GDK_F10:
-    case GDK_F11:
-    case GDK_F12:
-    case GDK_F13:
-    case GDK_F14:
-    case GDK_F15:
-    case GDK_F16:
-    case GDK_F17:
-    case GDK_F18:
-    case GDK_F19:
-    case GDK_F20:
-    case GDK_F21:
-    case GDK_F22:
-    case GDK_F23:
-    case GDK_F24:
-        return VKEY_F1 + (keycode - GDK_F1);
-    default:
-        return 0;
-    }
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/chromium/KeyboardCodes.h b/Source/core/platform/chromium/KeyboardCodes.h
deleted file mode 100644
index 70a14e9..0000000
--- a/Source/core/platform/chromium/KeyboardCodes.h
+++ /dev/null
@@ -1,561 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef KeyboardCodes_h
-#define KeyboardCodes_h
-
-#if OS(WIN)
-#include <windows.h>
-#endif
-
-#include "platform/WindowsKeyboardCodes.h"
-
-namespace WebCore {
-
-    enum {
-        // VKEY_LBUTTON (01) Left mouse button
-        // VKEY_RBUTTON (02) Right mouse button
-        // VKEY_CANCEL (03) Control-break processing
-        // VKEY_MBUTTON (04) Middle mouse button (three-button mouse)
-        // VKEY_XBUTTON1 (05)
-        // VKEY_XBUTTON2 (06)
-
-        // VKEY_BACK (08) BACKSPACE key
-        VKEY_BACK = VK_BACK,
-
-        // VKEY_TAB (09) TAB key
-        VKEY_TAB = VK_TAB,
-
-        // VKEY_CLEAR (0C) CLEAR key
-        VKEY_CLEAR = VK_CLEAR,
-
-        // VKEY_RETURN (0D)
-        VKEY_RETURN = VK_RETURN,
-
-        // VKEY_SHIFT (10) SHIFT key
-        VKEY_SHIFT = VK_SHIFT,
-
-        // VKEY_CONTROL (11) CTRL key
-        VKEY_CONTROL = VK_CONTROL,
-
-        // VKEY_MENU (12) ALT key
-        VKEY_MENU = VK_MENU,
-
-        // VKEY_PAUSE (13) PAUSE key
-        VKEY_PAUSE = VK_PAUSE,
-
-        // VKEY_CAPITAL (14) CAPS LOCK key
-        VKEY_CAPITAL = VK_CAPITAL,
-
-        // VKEY_KANA (15) Input Method Editor (IME) Kana mode
-        VKEY_KANA = VK_KANA,
-
-        // VKEY_HANGUEL (15) IME Hanguel mode (maintained for compatibility, use VKEY_HANGUL)
-        // VKEY_HANGUL (15) IME Hangul mode
-        VKEY_HANGUL = VK_HANGUL,
-
-        // VKEY_JUNJA (17) IME Junja mode
-        VKEY_JUNJA = VK_JUNJA,
-
-        // VKEY_FINAL (18) IME final mode
-        VKEY_FINAL = VK_FINAL,
-
-        // VKEY_HANJA (19) IME Hanja mode
-        VKEY_HANJA = VK_HANJA,
-
-        // VKEY_KANJI (19) IME Kanji mode
-        VKEY_KANJI = VK_KANJI,
-
-        // VKEY_ESCAPE (1B) ESC key
-        VKEY_ESCAPE = VK_ESCAPE,
-
-        // VKEY_CONVERT (1C) IME convert
-        VKEY_CONVERT = VK_CONVERT,
-
-        // VKEY_NONCONVERT (1D) IME nonconvert
-        VKEY_NONCONVERT = VK_NONCONVERT,
-
-        // VKEY_ACCEPT (1E) IME accept
-        VKEY_ACCEPT = VK_ACCEPT,
-
-        // VKEY_MODECHANGE (1F) IME mode change request
-        VKEY_MODECHANGE = VK_MODECHANGE,
-
-        // VKEY_SPACE (20) SPACEBAR
-        VKEY_SPACE = VK_SPACE,
-
-        // VKEY_PRIOR (21) PAGE UP key
-        VKEY_PRIOR = VK_PRIOR,
-
-        // VKEY_NEXT (22) PAGE DOWN key
-        VKEY_NEXT = VK_NEXT,
-
-        // VKEY_END (23) END key
-        VKEY_END = VK_END,
-
-        // VKEY_HOME (24) HOME key
-        VKEY_HOME = VK_HOME,
-
-        // VKEY_LEFT (25) LEFT ARROW key
-        VKEY_LEFT = VK_LEFT,
-
-        // VKEY_UP (26) UP ARROW key
-        VKEY_UP = VK_UP,
-
-        // VKEY_RIGHT (27) RIGHT ARROW key
-        VKEY_RIGHT = VK_RIGHT,
-
-        // VKEY_DOWN (28) DOWN ARROW key
-        VKEY_DOWN = VK_DOWN,
-
-        // VKEY_SELECT (29) SELECT key
-        VKEY_SELECT = VK_SELECT,
-
-        // VKEY_PRINT (2A) PRINT key
-        VKEY_PRINT = VK_PRINT,
-
-        // VKEY_EXECUTE (2B) EXECUTE key
-        VKEY_EXECUTE = VK_EXECUTE,
-
-        // VKEY_SNAPSHOT (2C) PRINT SCREEN key
-        VKEY_SNAPSHOT = VK_SNAPSHOT,
-
-        // VKEY_INSERT (2D) INS key
-        VKEY_INSERT = VK_INSERT,
-
-        // VKEY_DELETE (2E) DEL key
-        VKEY_DELETE = VK_DELETE,
-
-        // VKEY_HELP (2F) HELP key
-        VKEY_HELP = VK_HELP,
-
-        // (30) 0 key
-        VKEY_0 = '0',
-
-        // (31) 1 key
-        VKEY_1 = '1',
-
-        // (32) 2 key
-        VKEY_2 = '2',
-
-        // (33) 3 key
-        VKEY_3 = '3',
-
-        // (34) 4 key
-        VKEY_4 = '4',
-
-        // (35) 5 key,
-
-        VKEY_5 = '5',
-
-        // (36) 6 key
-        VKEY_6 = '6',
-
-        // (37) 7 key
-        VKEY_7 = '7',
-
-        // (38) 8 key
-        VKEY_8 = '8',
-
-        // (39) 9 key
-        VKEY_9 = '9',
-
-        // (41) A key
-        VKEY_A = 'A',
-
-        // (42) B key
-        VKEY_B = 'B',
-
-        // (43) C key
-        VKEY_C = 'C',
-
-        // (44) D key
-        VKEY_D = 'D',
-
-        // (45) E key
-        VKEY_E = 'E',
-
-        // (46) F key
-        VKEY_F = 'F',
-
-        // (47) G key
-        VKEY_G = 'G',
-
-        // (48) H key
-        VKEY_H = 'H',
-
-        // (49) I key
-        VKEY_I = 'I',
-
-        // (4A) J key
-        VKEY_J = 'J',
-
-        // (4B) K key
-        VKEY_K = 'K',
-
-        // (4C) L key
-        VKEY_L = 'L',
-
-        // (4D) M key
-        VKEY_M = 'M',
-
-        // (4E) N key
-        VKEY_N = 'N',
-
-        // (4F) O key
-        VKEY_O = 'O',
-
-        // (50) P key
-        VKEY_P = 'P',
-
-        // (51) Q key
-        VKEY_Q = 'Q',
-
-        // (52) R key
-        VKEY_R = 'R',
-
-        // (53) S key
-        VKEY_S = 'S',
-
-        // (54) T key
-        VKEY_T = 'T',
-
-        // (55) U key
-        VKEY_U = 'U',
-
-        // (56) V key
-        VKEY_V = 'V',
-
-        // (57) W key
-        VKEY_W = 'W',
-
-        // (58) X key
-        VKEY_X = 'X',
-
-        // (59) Y key
-        VKEY_Y = 'Y',
-
-        // (5A) Z key
-        VKEY_Z = 'Z',
-
-        // VKEY_LWIN (5B) Left Windows key (Microsoft Natural keyboard)
-        VKEY_LWIN = VK_LWIN,
-
-        // VKEY_RWIN (5C) Right Windows key (Natural keyboard)
-        VKEY_RWIN = VK_RWIN,
-
-        // VKEY_APPS (5D) Applications key (Natural keyboard)
-        VKEY_APPS = VK_APPS,
-
-        // VKEY_SLEEP (5F) Computer Sleep key
-        VKEY_SLEEP = VK_SLEEP,
-
-        // VKEY_NUMPAD0 (60) Numeric keypad 0 key
-        VKEY_NUMPAD0 = VK_NUMPAD0,
-
-        // VKEY_NUMPAD1 (61) Numeric keypad 1 key
-        VKEY_NUMPAD1 = VK_NUMPAD1,
-
-        // VKEY_NUMPAD2 (62) Numeric keypad 2 key
-        VKEY_NUMPAD2 = VK_NUMPAD2,
-
-        // VKEY_NUMPAD3 (63) Numeric keypad 3 key
-        VKEY_NUMPAD3 = VK_NUMPAD3,
-
-        // VKEY_NUMPAD4 (64) Numeric keypad 4 key
-        VKEY_NUMPAD4 = VK_NUMPAD4,
-
-        // VKEY_NUMPAD5 (65) Numeric keypad 5 key
-        VKEY_NUMPAD5 = VK_NUMPAD5,
-
-        // VKEY_NUMPAD6 (66) Numeric keypad 6 key
-        VKEY_NUMPAD6 = VK_NUMPAD6,
-
-        // VKEY_NUMPAD7 (67) Numeric keypad 7 key
-        VKEY_NUMPAD7 = VK_NUMPAD7,
-
-        // VKEY_NUMPAD8 (68) Numeric keypad 8 key
-        VKEY_NUMPAD8 = VK_NUMPAD8,
-
-        // VKEY_NUMPAD9 (69) Numeric keypad 9 key
-        VKEY_NUMPAD9 = VK_NUMPAD9,
-
-        // VKEY_MULTIPLY (6A) Multiply key
-        VKEY_MULTIPLY = VK_MULTIPLY,
-
-        // VKEY_ADD (6B) Add key
-        VKEY_ADD = VK_ADD,
-
-        // VKEY_SEPARATOR (6C) Separator key
-        VKEY_SEPARATOR = VK_SEPARATOR,
-
-        // VKEY_SUBTRACT (6D) Subtract key
-        VKEY_SUBTRACT = VK_SUBTRACT,
-
-        // VKEY_DECIMAL (6E) Decimal key
-        VKEY_DECIMAL = VK_DECIMAL,
-
-        // VKEY_DIVIDE (6F) Divide key
-        VKEY_DIVIDE = VK_DIVIDE,
-
-        // VKEY_F1 (70) F1 key
-        VKEY_F1 = VK_F1,
-
-        // VKEY_F2 (71) F2 key
-        VKEY_F2 = VK_F2,
-
-        // VKEY_F3 (72) F3 key
-        VKEY_F3 = VK_F3,
-
-        // VKEY_F4 (73) F4 key
-        VKEY_F4 = VK_F4,
-
-        // VKEY_F5 (74) F5 key
-        VKEY_F5 = VK_F5,
-
-        // VKEY_F6 (75) F6 key
-        VKEY_F6 = VK_F6,
-
-        // VKEY_F7 (76) F7 key
-        VKEY_F7 = VK_F7,
-
-        // VKEY_F8 (77) F8 key
-        VKEY_F8 = VK_F8,
-
-        // VKEY_F9 (78) F9 key
-        VKEY_F9 = VK_F9,
-
-        // VKEY_F10 (79) F10 key
-        VKEY_F10 = VK_F10,
-
-        // VKEY_F11 (7A) F11 key
-        VKEY_F11 = VK_F11,
-
-        // VKEY_F12 (7B) F12 key
-        VKEY_F12 = VK_F12,
-
-        // VKEY_F13 (7C) F13 key
-        VKEY_F13 = VK_F13,
-
-        // VKEY_F14 (7D) F14 key
-        VKEY_F14 = VK_F14,
-
-        // VKEY_F15 (7E) F15 key
-        VKEY_F15 = VK_F15,
-
-        // VKEY_F16 (7F) F16 key
-        VKEY_F16 = VK_F16,
-
-        // VKEY_F17 (80H) F17 key
-        VKEY_F17 = VK_F17,
-
-        // VKEY_F18 (81H) F18 key
-        VKEY_F18 = VK_F18,
-
-        // VKEY_F19 (82H) F19 key
-        VKEY_F19 = VK_F19,
-
-        // VKEY_F20 (83H) F20 key
-        VKEY_F20 = VK_F20,
-
-        // VKEY_F21 (84H) F21 key
-        VKEY_F21 = VK_F21,
-
-        // VKEY_F22 (85H) F22 key
-        VKEY_F22 = VK_F22,
-
-        // VKEY_F23 (86H) F23 key
-        VKEY_F23 = VK_F23,
-
-        // VKEY_F24 (87H) F24 key
-        VKEY_F24 = VK_F24,
-
-        // VKEY_NUMLOCK (90) NUM LOCK key
-        VKEY_NUMLOCK = VK_NUMLOCK,
-
-        // VKEY_SCROLL (91) SCROLL LOCK key
-        VKEY_SCROLL = VK_SCROLL,
-
-        // VKEY_LSHIFT (A0) Left SHIFT key
-        VKEY_LSHIFT = VK_LSHIFT,
-
-        // VKEY_RSHIFT (A1) Right SHIFT key
-        VKEY_RSHIFT = VK_RSHIFT,
-
-        // VKEY_LCONTROL (A2) Left CONTROL key
-        VKEY_LCONTROL = VK_LCONTROL,
-
-        // VKEY_RCONTROL (A3) Right CONTROL key
-        VKEY_RCONTROL = VK_RCONTROL,
-
-        // VKEY_LMENU (A4) Left MENU key
-        VKEY_LMENU = VK_LMENU,
-
-        // VKEY_RMENU (A5) Right MENU key
-        VKEY_RMENU = VK_RMENU,
-
-        // VKEY_BROWSER_BACK (A6) Windows 2000/XP: Browser Back key
-        VKEY_BROWSER_BACK = VK_BROWSER_BACK,
-
-        // VKEY_BROWSER_FORWARD (A7) Windows 2000/XP: Browser Forward key
-        VKEY_BROWSER_FORWARD = VK_BROWSER_FORWARD,
-
-        // VKEY_BROWSER_REFRESH (A8) Windows 2000/XP: Browser Refresh key
-        VKEY_BROWSER_REFRESH = VK_BROWSER_REFRESH,
-
-        // VKEY_BROWSER_STOP (A9) Windows 2000/XP: Browser Stop key
-        VKEY_BROWSER_STOP = VK_BROWSER_STOP,
-
-        // VKEY_BROWSER_SEARCH (AA) Windows 2000/XP: Browser Search key
-        VKEY_BROWSER_SEARCH = VK_BROWSER_SEARCH,
-
-        // VKEY_BROWSER_FAVORITES (AB) Windows 2000/XP: Browser Favorites key
-        VKEY_BROWSER_FAVORITES = VK_BROWSER_FAVORITES,
-
-        // VKEY_BROWSER_HOME (AC) Windows 2000/XP: Browser Start and Home key
-        VKEY_BROWSER_HOME = VK_BROWSER_HOME,
-
-        // VKEY_VOLUME_MUTE (AD) Windows 2000/XP: Volume Mute key
-        VKEY_VOLUME_MUTE = VK_VOLUME_MUTE,
-
-        // VKEY_VOLUME_DOWN (AE) Windows 2000/XP: Volume Down key
-        VKEY_VOLUME_DOWN = VK_VOLUME_DOWN,
-
-        // VKEY_VOLUME_UP (AF) Windows 2000/XP: Volume Up key
-        VKEY_VOLUME_UP = VK_VOLUME_UP,
-
-        // VKEY_MEDIA_NEXT_TRACK (B0) Windows 2000/XP: Next Track key
-        VKEY_MEDIA_NEXT_TRACK = VK_MEDIA_NEXT_TRACK,
-
-        // VKEY_MEDIA_PREV_TRACK (B1) Windows 2000/XP: Previous Track key
-        VKEY_MEDIA_PREV_TRACK = VK_MEDIA_PREV_TRACK,
-
-        // VKEY_MEDIA_STOP (B2) Windows 2000/XP: Stop Media key
-        VKEY_MEDIA_STOP = VK_MEDIA_STOP,
-
-        // VKEY_MEDIA_PLAY_PAUSE (B3) Windows 2000/XP: Play/Pause Media key
-        VKEY_MEDIA_PLAY_PAUSE = VK_MEDIA_PLAY_PAUSE,
-
-        // VKEY_LAUNCH_MAIL (B4) Windows 2000/XP: Start Mail key
-        VKEY_MEDIA_LAUNCH_MAIL = 0xB4,
-
-        // VKEY_LAUNCH_MEDIA_SELECT (B5) Windows 2000/XP: Select Media key
-        VKEY_MEDIA_LAUNCH_MEDIA_SELECT = 0xB5,
-
-        // VKEY_LAUNCH_APP1 (B6) Windows 2000/XP: Start Application 1 key
-        VKEY_MEDIA_LAUNCH_APP1 = 0xB6,
-
-        // VKEY_LAUNCH_APP2 (B7) Windows 2000/XP: Start Application 2 key
-        VKEY_MEDIA_LAUNCH_APP2 = 0xB7,
-
-        // VKEY_OEM_1 (BA) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ',:' key
-        VKEY_OEM_1 = VK_OEM_1,
-
-        // VKEY_OEM_PLUS (BB) Windows 2000/XP: For any country/region, the '+' key
-        VKEY_OEM_PLUS = VK_OEM_PLUS,
-
-        // VKEY_OEM_COMMA (BC) Windows 2000/XP: For any country/region, the ',' key
-        VKEY_OEM_COMMA = VK_OEM_COMMA,
-
-        // VKEY_OEM_MINUS (BD) Windows 2000/XP: For any country/region, the '-' key
-        VKEY_OEM_MINUS = VK_OEM_MINUS,
-
-        // VKEY_OEM_PERIOD (BE) Windows 2000/XP: For any country/region, the '.' key
-        VKEY_OEM_PERIOD = VK_OEM_PERIOD,
-
-        // VKEY_OEM_2 (BF) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key
-        VKEY_OEM_2 = VK_OEM_2,
-
-        // VKEY_OEM_3 (C0) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key
-        VKEY_OEM_3 = VK_OEM_3,
-
-        // VKEY_OEM_4 (DB) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key
-        VKEY_OEM_4 = VK_OEM_4,
-
-        // VKEY_OEM_5 (DC) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key
-        VKEY_OEM_5 = VK_OEM_5,
-
-        // VKEY_OEM_6 (DD) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key
-        VKEY_OEM_6 = VK_OEM_6,
-
-        // VKEY_OEM_7 (DE) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key
-        VKEY_OEM_7 = VK_OEM_7,
-
-        // VKEY_OEM_8 (DF) Used for miscellaneous characters, it can vary by keyboard.
-        VKEY_OEM_8 = VK_OEM_8,
-
-        // VKEY_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
-        VKEY_OEM_102 = VK_OEM_102,
-
-        // VKEY_OEM_103 (E3) GTV KEYCODE_MEDIA_REWIND
-        VKEY_OEM_103 = 0xE3,
-
-        // VKEY_OEM_104 (E4) GTV KEYCODE_MEDIA_FAST_FORWARD
-        VKEY_OEM_104 = 0xE4,
-
-        // VKEY_PROCESSKEY (E5) Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
-        VKEY_PROCESSKEY = VK_PROCESSKEY,
-
-        // VKEY_PACKET (E7) Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VKEY_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT,SendInput, WM_KEYDOWN, and WM_KEYUP
-        VKEY_PACKET = VK_PACKET,
-
-        // VKEY_ATTN (F6) Attn key
-        VKEY_ATTN = VK_ATTN,
-
-        // VKEY_CRSEL (F7) CrSel key
-        VKEY_CRSEL = VK_CRSEL,
-
-        // VKEY_EXSEL (F8) ExSel key
-        VKEY_EXSEL = VK_EXSEL,
-
-        // VKEY_EREOF (F9) Erase EOF key
-        VKEY_EREOF = VK_EREOF,
-
-        // VKEY_PLAY (FA) Play key
-        VKEY_PLAY = VK_PLAY,
-
-        // VKEY_ZOOM (FB) Zoom key
-        VKEY_ZOOM = VK_ZOOM,
-
-        // VKEY_NONAME (FC) Reserved for future use
-        VKEY_NONAME = VK_NONAME,
-
-        // VKEY_PA1 (FD) PA1 key
-        VKEY_PA1 = VK_PA1,
-
-        // VKEY_OEM_CLEAR (FE) Clear key
-        VKEY_OEM_CLEAR = VK_OEM_CLEAR,
-
-        VKEY_UNKNOWN = 0
-    };
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/chromium/support/WebArrayBuffer.cpp b/Source/core/platform/chromium/support/WebArrayBuffer.cpp
deleted file mode 100644
index 05429fe..0000000
--- a/Source/core/platform/chromium/support/WebArrayBuffer.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "public/platform/WebArrayBuffer.h"
-
-#include "bindings/v8/custom/V8ArrayBufferCustom.h"
-#include "wtf/ArrayBuffer.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace WebCore;
-
-namespace blink {
-
-WebArrayBuffer WebArrayBuffer::create(unsigned numElements, unsigned elementByteSize)
-{
-    RefPtr<ArrayBuffer> buffer = ArrayBuffer::create(numElements, elementByteSize);
-    return WebArrayBuffer(buffer);
-}
-
-void WebArrayBuffer::reset()
-{
-    m_private.reset();
-}
-
-void WebArrayBuffer::assign(const WebArrayBuffer& other)
-{
-    m_private = other.m_private;
-}
-
-void* WebArrayBuffer::data() const
-{
-    if (!isNull())
-        return const_cast<void*>(m_private->data());
-    return 0;
-}
-
-unsigned WebArrayBuffer::byteLength() const
-{
-    if (!isNull())
-        return m_private->byteLength();
-    return 0;
-}
-
-v8::Handle<v8::Value> WebArrayBuffer::toV8Value()
-{
-    if (!m_private.get())
-        return v8::Handle<v8::Value>();
-    return toV8(m_private.get(), v8::Handle<v8::Object>(), v8::Isolate::GetCurrent());
-}
-
-WebArrayBuffer* WebArrayBuffer::createFromV8Value(v8::Handle<v8::Value> value)
-{
-    if (!V8ArrayBuffer::hasInstanceInAnyWorld(value, v8::Isolate::GetCurrent()))
-        return 0;
-    WTF::ArrayBuffer* buffer = V8ArrayBuffer::toNative(value->ToObject());
-    return new WebArrayBuffer(buffer);
-}
-
-WebArrayBuffer::WebArrayBuffer(const WTF::PassRefPtr<WTF::ArrayBuffer>& blob)
-    : m_private(blob)
-{
-}
-
-WebArrayBuffer& WebArrayBuffer::operator=(const WTF::PassRefPtr<WTF::ArrayBuffer>& blob)
-{
-    m_private = blob;
-    return *this;
-}
-
-WebArrayBuffer::operator WTF::PassRefPtr<WTF::ArrayBuffer>() const
-{
-    return m_private.get();
-}
-
-} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebCrypto.cpp b/Source/core/platform/chromium/support/WebCrypto.cpp
deleted file mode 100644
index 3fd68af..0000000
--- a/Source/core/platform/chromium/support/WebCrypto.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "public/platform/WebCrypto.h"
-
-#include "core/platform/CryptoResult.h"
-#include "public/platform/WebArrayBuffer.h"
-#include <string.h>
-
-namespace blink {
-
-void WebCryptoResult::completeWithError()
-{
-    m_impl->completeWithError();
-    reset();
-}
-
-void WebCryptoResult::completeWithBuffer(const WebArrayBuffer& buffer)
-{
-    RELEASE_ASSERT(!buffer.isNull());
-    m_impl->completeWithBuffer(buffer);
-    reset();
-}
-
-void WebCryptoResult::completeWithBuffer(const void* bytes, unsigned bytesSize)
-{
-    WebArrayBuffer buffer = blink::WebArrayBuffer::create(bytesSize, 1);
-    RELEASE_ASSERT(!buffer.isNull());
-    memcpy(buffer.data(), bytes, bytesSize);
-    completeWithBuffer(buffer);
-}
-
-void WebCryptoResult::completeWithBoolean(bool b)
-{
-    m_impl->completeWithBoolean(b);
-    reset();
-}
-
-void WebCryptoResult::completeWithKey(const WebCryptoKey& key)
-{
-    ASSERT(!key.isNull());
-    m_impl->completeWithKey(key);
-    reset();
-}
-
-void WebCryptoResult::completeWithKeyPair(const WebCryptoKey& publicKey, const WebCryptoKey& privateKey)
-{
-    ASSERT(!publicKey.isNull());
-    ASSERT(!privateKey.isNull());
-    m_impl->completeWithKeyPair(publicKey, privateKey);
-    reset();
-}
-
-WebCryptoResult::WebCryptoResult(const WTF::PassRefPtr<WebCore::CryptoResult>& impl)
-    : m_impl(impl)
-{
-    ASSERT(m_impl.get());
-}
-
-void WebCryptoResult::reset()
-{
-    m_impl.reset();
-}
-
-void WebCryptoResult::assign(const WebCryptoResult& o)
-{
-    m_impl = o.m_impl;
-}
-
-} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebCursorInfo.cpp b/Source/core/platform/chromium/support/WebCursorInfo.cpp
deleted file mode 100644
index 3f04e51..0000000
--- a/Source/core/platform/chromium/support/WebCursorInfo.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "public/platform/WebCursorInfo.h"
-
-#include "platform/Cursor.h"
-
-using namespace WebCore;
-
-namespace blink {
-
-WebCursorInfo::WebCursorInfo(const Cursor& cursor)
-    : type(static_cast<Type>(cursor.type()))
-    , hotSpot(cursor.hotSpot())
-    , imageScaleFactor(cursor.imageScaleFactor())
-    , customImage(cursor.image())
-#ifdef WIN32
-    , externalHandle(0)
-#endif
-{
-}
-
-} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebMediaStream.cpp b/Source/core/platform/chromium/support/WebMediaStream.cpp
deleted file mode 100644
index 7572def..0000000
--- a/Source/core/platform/chromium/support/WebMediaStream.cpp
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-#include "config.h"
-
-#include "public/platform/WebMediaStream.h"
-
-#include "core/platform/mediastream/MediaStreamDescriptor.h"
-#include "platform/UUID.h"
-#include "platform/mediastream/MediaStreamComponent.h"
-#include "platform/mediastream/MediaStreamSource.h"
-#include "public/platform/WebMediaStreamSource.h"
-#include "public/platform/WebMediaStreamTrack.h"
-#include "public/platform/WebString.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-using namespace WebCore;
-
-namespace blink {
-
-namespace {
-
-class ExtraDataContainer : public MediaStreamDescriptor::ExtraData {
-public:
-    ExtraDataContainer(WebMediaStream::ExtraData* extraData) : m_extraData(adoptPtr(extraData)) { }
-
-    WebMediaStream::ExtraData* extraData() { return m_extraData.get(); }
-
-private:
-    OwnPtr<WebMediaStream::ExtraData> m_extraData;
-};
-
-} // namespace
-
-WebMediaStream::WebMediaStream(const PassRefPtr<WebCore::MediaStreamDescriptor>& mediaStreamDescriptor)
-    : m_private(mediaStreamDescriptor)
-{
-}
-
-WebMediaStream::WebMediaStream(WebCore::MediaStreamDescriptor* mediaStreamDescriptor)
-    : m_private(mediaStreamDescriptor)
-{
-}
-
-void WebMediaStream::reset()
-{
-    m_private.reset();
-}
-
-WebString WebMediaStream::id() const
-{
-    return m_private->id();
-}
-
-WebMediaStream::ExtraData* WebMediaStream::extraData() const
-{
-    RefPtr<MediaStreamDescriptor::ExtraData> data = m_private->extraData();
-    if (!data)
-        return 0;
-    return static_cast<ExtraDataContainer*>(data.get())->extraData();
-}
-
-void WebMediaStream::setExtraData(ExtraData* extraData)
-{
-    m_private->setExtraData(adoptRef(new ExtraDataContainer(extraData)));
-}
-
-void WebMediaStream::audioTracks(WebVector<WebMediaStreamTrack>& webTracks) const
-{
-    size_t numberOfTracks = m_private->numberOfAudioComponents();
-    WebVector<WebMediaStreamTrack> result(numberOfTracks);
-    for (size_t i = 0; i < numberOfTracks; ++i)
-        result[i] = m_private->audioComponent(i);
-    webTracks.swap(result);
-}
-
-void WebMediaStream::videoTracks(WebVector<WebMediaStreamTrack>& webTracks) const
-{
-    size_t numberOfTracks = m_private->numberOfVideoComponents();
-    WebVector<WebMediaStreamTrack> result(numberOfTracks);
-    for (size_t i = 0; i < numberOfTracks; ++i)
-        result[i] = m_private->videoComponent(i);
-    webTracks.swap(result);
-}
-
-void WebMediaStream::addTrack(const WebMediaStreamTrack& track)
-{
-    ASSERT(!isNull());
-    m_private->addRemoteTrack(track);
-}
-
-void WebMediaStream::removeTrack(const WebMediaStreamTrack& track)
-{
-    ASSERT(!isNull());
-    m_private->removeRemoteTrack(track);
-}
-
-WebMediaStream& WebMediaStream::operator=(const PassRefPtr<WebCore::MediaStreamDescriptor>& mediaStreamDescriptor)
-{
-    m_private = mediaStreamDescriptor;
-    return *this;
-}
-
-WebMediaStream::operator PassRefPtr<WebCore::MediaStreamDescriptor>() const
-{
-    return m_private.get();
-}
-
-WebMediaStream::operator WebCore::MediaStreamDescriptor*() const
-{
-    return m_private.get();
-}
-
-void WebMediaStream::initialize(const WebVector<WebMediaStreamTrack>& audioTracks, const WebVector<WebMediaStreamTrack>& videoTracks)
-{
-    initialize(createCanonicalUUIDString(), audioTracks, videoTracks);
-}
-
-void WebMediaStream::initialize(const WebString& label, const WebVector<WebMediaStreamTrack>& audioTracks, const WebVector<WebMediaStreamTrack>& videoTracks)
-{
-    MediaStreamComponentVector audio, video;
-    for (size_t i = 0; i < audioTracks.size(); ++i) {
-        MediaStreamComponent* component = audioTracks[i];
-        audio.append(component);
-    }
-    for (size_t i = 0; i < videoTracks.size(); ++i) {
-        MediaStreamComponent* component = videoTracks[i];
-        video.append(component);
-    }
-    m_private = MediaStreamDescriptor::create(label, audio, video);
-}
-
-void WebMediaStream::assign(const WebMediaStream& other)
-{
-    m_private = other.m_private;
-}
-
-} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp b/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
deleted file mode 100644
index 39dabdf..0000000
--- a/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-#include "config.h"
-
-#include "public/platform/WebMediaStreamTrack.h"
-
-#include "platform/mediastream/MediaStreamComponent.h"
-#include "platform/mediastream/MediaStreamSource.h"
-#include "public/platform/WebAudioSourceProvider.h"
-#include "public/platform/WebMediaStream.h"
-#include "public/platform/WebMediaStreamSource.h"
-#include "public/platform/WebString.h"
-#include "wtf/Vector.h"
-
-using namespace WebCore;
-
-namespace blink {
-
-namespace {
-
-class ExtraDataContainer : public MediaStreamComponent::ExtraData {
-public:
-    explicit ExtraDataContainer(PassOwnPtr<WebMediaStreamTrack::ExtraData> extraData) : m_extraData(extraData) { }
-
-    WebMediaStreamTrack::ExtraData* extraData() { return m_extraData.get(); }
-
-private:
-    OwnPtr<WebMediaStreamTrack::ExtraData> m_extraData;
-};
-
-} // namespace
-
-WebMediaStreamTrack::WebMediaStreamTrack(PassRefPtr<WebCore::MediaStreamComponent> mediaStreamComponent)
-    : m_private(mediaStreamComponent)
-{
-}
-
-WebMediaStreamTrack::WebMediaStreamTrack(WebCore::MediaStreamComponent* mediaStreamComponent)
-    : m_private(mediaStreamComponent)
-{
-}
-
-WebMediaStreamTrack& WebMediaStreamTrack::operator=(WebCore::MediaStreamComponent* mediaStreamComponent)
-{
-    m_private = mediaStreamComponent;
-    return *this;
-}
-
-void WebMediaStreamTrack::initialize(const WebMediaStreamSource& source)
-{
-    m_private = MediaStreamComponent::create(source);
-}
-
-void WebMediaStreamTrack::initialize(const WebString& id, const WebMediaStreamSource& source)
-{
-    m_private = MediaStreamComponent::create(id, source);
-}
-
-void WebMediaStreamTrack::reset()
-{
-    m_private.reset();
-}
-
-WebMediaStreamTrack::operator PassRefPtr<MediaStreamComponent>() const
-{
-    return m_private.get();
-}
-
-WebMediaStreamTrack::operator MediaStreamComponent*() const
-{
-    return m_private.get();
-}
-
-bool WebMediaStreamTrack::isEnabled() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->enabled();
-}
-
-WebString WebMediaStreamTrack::id() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->id();
-}
-
-WebMediaStream WebMediaStreamTrack::stream() const
-{
-    ASSERT(!m_private.isNull());
-    return WebMediaStream(m_private->stream());
-}
-
-WebMediaStreamSource WebMediaStreamTrack::source() const
-{
-    ASSERT(!m_private.isNull());
-    return WebMediaStreamSource(m_private->source());
-}
-
-WebMediaStreamTrack::ExtraData* WebMediaStreamTrack::extraData() const
-{
-    RefPtr<MediaStreamComponent::ExtraData> data = m_private->extraData();
-    if (!data)
-        return 0;
-    return static_cast<ExtraDataContainer*>(data.get())->extraData();
-}
-
-void WebMediaStreamTrack::setExtraData(ExtraData* extraData)
-{
-    m_private->setExtraData(adoptRef(new ExtraDataContainer(adoptPtr(extraData))));
-}
-
-void WebMediaStreamTrack::setSourceProvider(WebAudioSourceProvider* provider)
-{
-#if ENABLE(WEB_AUDIO)
-    ASSERT(!m_private.isNull());
-    m_private->setSourceProvider(provider);
-#endif // ENABLE(WEB_AUDIO)
-}
-
-void WebMediaStreamTrack::assign(const WebMediaStreamTrack& other)
-{
-    m_private = other.m_private;
-}
-
-} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp b/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
deleted file mode 100644
index 1fc0caf..0000000
--- a/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-
-#include "public/platform/WebRTCSessionDescription.h"
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "public/platform/WebString.h"
-
-namespace blink {
-
-class WebRTCSessionDescriptionPrivate FINAL : public RefCounted<WebRTCSessionDescriptionPrivate> {
-public:
-    static PassRefPtr<WebRTCSessionDescriptionPrivate> create(const WebString& type, const WebString& sdp);
-
-    WebString type() { return m_type; }
-    void setType(const WebString& type) { m_type = type; }
-
-    WebString sdp() { return m_sdp; }
-    void setSdp(const WebString& sdp) { m_sdp = sdp; }
-
-private:
-    WebRTCSessionDescriptionPrivate(const WebString& type, const WebString& sdp);
-
-    WebString m_type;
-    WebString m_sdp;
-};
-
-PassRefPtr<WebRTCSessionDescriptionPrivate> WebRTCSessionDescriptionPrivate::create(const WebString& type, const WebString& sdp)
-{
-    return adoptRef(new WebRTCSessionDescriptionPrivate(type, sdp));
-}
-
-WebRTCSessionDescriptionPrivate::WebRTCSessionDescriptionPrivate(const WebString& type, const WebString& sdp)
-    : m_type(type)
-    , m_sdp(sdp)
-{
-}
-
-void WebRTCSessionDescription::assign(const WebRTCSessionDescription& other)
-{
-    m_private = other.m_private;
-}
-
-void WebRTCSessionDescription::reset()
-{
-    m_private.reset();
-}
-
-void WebRTCSessionDescription::initialize(const WebString& type, const WebString& sdp)
-{
-    m_private = WebRTCSessionDescriptionPrivate::create(type, sdp);
-}
-
-WebString WebRTCSessionDescription::type() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->type();
-}
-
-void WebRTCSessionDescription::setType(const WebString& type)
-{
-    ASSERT(!m_private.isNull());
-    return m_private->setType(type);
-}
-
-WebString WebRTCSessionDescription::sdp() const
-{
-    ASSERT(!m_private.isNull());
-    return m_private->sdp();
-}
-
-void WebRTCSessionDescription::setSDP(const WebString& sdp)
-{
-    ASSERT(!m_private.isNull());
-    return m_private->setSdp(sdp);
-}
-
-} // namespace blink
-
diff --git a/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp b/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp
deleted file mode 100644
index b35f305..0000000
--- a/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-
-#include "public/platform/WebRTCSessionDescriptionRequest.h"
-
-#include "platform/mediastream/RTCSessionDescriptionRequest.h"
-#include "public/platform/WebRTCSessionDescription.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace WebCore;
-
-namespace blink {
-
-namespace {
-
-class ExtraDataContainer : public RTCSessionDescriptionRequest::ExtraData {
-public:
-    ExtraDataContainer(WebRTCSessionDescriptionRequest::ExtraData* extraData) : m_extraData(adoptPtr(extraData)) { }
-
-    WebRTCSessionDescriptionRequest::ExtraData* extraData() { return m_extraData.get(); }
-
-private:
-    OwnPtr<WebRTCSessionDescriptionRequest::ExtraData> m_extraData;
-};
-
-} // namespace
-
-WebRTCSessionDescriptionRequest::WebRTCSessionDescriptionRequest(const PassRefPtr<RTCSessionDescriptionRequest>& constraints)
-    : m_private(constraints)
-{
-}
-
-void WebRTCSessionDescriptionRequest::assign(const WebRTCSessionDescriptionRequest& other)
-{
-    m_private = other.m_private;
-}
-
-void WebRTCSessionDescriptionRequest::reset()
-{
-    m_private.reset();
-}
-
-void WebRTCSessionDescriptionRequest::requestSucceeded(const WebRTCSessionDescription& sessionDescription) const
-{
-    ASSERT(m_private.get());
-    m_private->requestSucceeded(sessionDescription);
-}
-
-void WebRTCSessionDescriptionRequest::requestFailed(const WebString& error) const
-{
-    ASSERT(m_private.get());
-    m_private->requestFailed(error);
-}
-
-WebRTCSessionDescriptionRequest::ExtraData* WebRTCSessionDescriptionRequest::extraData() const
-{
-    RefPtr<RTCSessionDescriptionRequest::ExtraData> data = m_private->extraData();
-    if (!data)
-        return 0;
-    return static_cast<ExtraDataContainer*>(data.get())->extraData();
-}
-
-void WebRTCSessionDescriptionRequest::setExtraData(ExtraData* extraData)
-{
-    m_private->setExtraData(adoptRef(new ExtraDataContainer(extraData)));
-}
-
-} // namespace blink
-
diff --git a/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp b/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp
deleted file mode 100644
index 617bd56..0000000
--- a/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-
-#include "public/platform/WebRTCStatsRequest.h"
-
-#include "core/platform/mediastream/RTCStatsRequest.h"
-#include "modules/mediastream/RTCStatsResponse.h"
-#include "public/platform/WebMediaStream.h"
-#include "public/platform/WebMediaStreamTrack.h"
-#include "public/platform/WebRTCStatsResponse.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace WebCore;
-
-namespace blink {
-
-WebRTCStatsRequest::WebRTCStatsRequest(const PassRefPtr<RTCStatsRequest>& request)
-    : m_private(request)
-{
-}
-
-void WebRTCStatsRequest::assign(const WebRTCStatsRequest& other)
-{
-    m_private = other.m_private;
-}
-
-void WebRTCStatsRequest::reset()
-{
-    m_private.reset();
-}
-
-WebRTCStatsResponse WebRTCStatsRequest::createResponse() const
-{
-    return WebRTCStatsResponse(m_private->createResponse());
-}
-
-bool WebRTCStatsRequest::hasSelector() const
-{
-    return m_private->hasSelector();
-}
-
-const WebMediaStream WebRTCStatsRequest::stream() const
-{
-    return WebMediaStream(m_private->stream());
-}
-
-const WebMediaStreamTrack WebRTCStatsRequest::component() const
-{
-    return WebMediaStreamTrack(m_private->component());
-}
-
-void WebRTCStatsRequest::requestSucceeded(const WebRTCStatsResponse& response) const
-{
-    m_private->requestSucceeded(response);
-}
-
-} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
deleted file mode 100644
index ffa0193..0000000
--- a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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 APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#include "config.h"
-
-#include "core/platform/chromium/support/WebScrollbarThemeGeometryNative.h"
-
-#include "platform/exported/WebScrollbarThemeClientImpl.h"
-#include "platform/scroll/ScrollbarTheme.h"
-#include "public/platform/WebScrollbar.h"
-
-using namespace WebCore;
-
-namespace blink {
-
-PassOwnPtr<blink::WebScrollbarThemeGeometryNative> WebScrollbarThemeGeometryNative::create(WebCore::ScrollbarTheme* theme)
-{
-    return adoptPtr(new WebScrollbarThemeGeometryNative(theme));
-}
-
-WebScrollbarThemeGeometryNative::WebScrollbarThemeGeometryNative(WebCore::ScrollbarTheme* theme)
-    : m_theme(theme)
-{
-}
-
-WebScrollbarThemeGeometryNative* WebScrollbarThemeGeometryNative::clone() const
-{
-    return new WebScrollbarThemeGeometryNative(m_theme);
-}
-
-int WebScrollbarThemeGeometryNative::thumbPosition(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->thumbPosition(&client);
-}
-
-int WebScrollbarThemeGeometryNative::thumbLength(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->thumbLength(&client);
-}
-
-int WebScrollbarThemeGeometryNative::trackPosition(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->trackPosition(&client);
-}
-
-int WebScrollbarThemeGeometryNative::trackLength(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->trackLength(&client);
-}
-
-bool WebScrollbarThemeGeometryNative::hasButtons(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->hasButtons(&client);
-}
-
-bool WebScrollbarThemeGeometryNative::hasThumb(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->hasThumb(&client);
-}
-
-WebRect WebScrollbarThemeGeometryNative::trackRect(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->trackRect(&client);
-}
-
-WebRect WebScrollbarThemeGeometryNative::thumbRect(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->thumbRect(&client);
-}
-
-int WebScrollbarThemeGeometryNative::minimumThumbLength(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->minimumThumbLength(&client);
-}
-
-int WebScrollbarThemeGeometryNative::scrollbarThickness(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->scrollbarThickness(client.controlSize());
-}
-
-WebRect WebScrollbarThemeGeometryNative::backButtonStartRect(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->backButtonRect(&client, BackButtonStartPart, false);
-}
-
-WebRect WebScrollbarThemeGeometryNative::backButtonEndRect(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->backButtonRect(&client, BackButtonEndPart, false);
-}
-
-WebRect WebScrollbarThemeGeometryNative::forwardButtonStartRect(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->forwardButtonRect(&client, ForwardButtonStartPart, false);
-}
-
-WebRect WebScrollbarThemeGeometryNative::forwardButtonEndRect(WebScrollbar* scrollbar)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->forwardButtonRect(&client, ForwardButtonEndPart, false);
-}
-
-WebRect WebScrollbarThemeGeometryNative::constrainTrackRectToTrackPieces(WebScrollbar* scrollbar, const WebRect& rect)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    return m_theme->constrainTrackRectToTrackPieces(&client, IntRect(rect));
-}
-
-void WebScrollbarThemeGeometryNative::splitTrack(WebScrollbar* scrollbar, const WebRect& webTrack, WebRect& webStartTrack, WebRect& webThumb, WebRect& webEndTrack)
-{
-    WebScrollbarThemeClientImpl client(scrollbar);
-    IntRect track(webTrack);
-    IntRect startTrack;
-    IntRect thumb;
-    IntRect endTrack;
-    m_theme->splitTrack(&client, track, startTrack, thumb, endTrack);
-
-    webStartTrack = startTrack;
-    webThumb = thumb;
-    webEndTrack = endTrack;
-}
-
-} // namespace blink
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h b/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
deleted file mode 100644
index d24ac7e..0000000
--- a/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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 APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
- */
-
-#ifndef WebScrollbarThemeGeometryNative_h
-#define WebScrollbarThemeGeometryNative_h
-
-#include "public/platform/WebRect.h"
-#include "public/platform/WebScrollbarThemeGeometry.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-class ScrollbarTheme;
-}
-
-namespace blink {
-
-class WebScrollbar;
-
-class WebScrollbarThemeGeometryNative : public WebScrollbarThemeGeometry {
-public:
-    static PassOwnPtr<WebScrollbarThemeGeometryNative> create(WebCore::ScrollbarTheme*);
-
-    // WebScrollbarThemeGeometry overrides
-    virtual WebScrollbarThemeGeometryNative* clone() const OVERRIDE;
-    virtual int thumbPosition(WebScrollbar*) OVERRIDE;
-    virtual int thumbLength(WebScrollbar*) OVERRIDE;
-    virtual int trackPosition(WebScrollbar*) OVERRIDE;
-    virtual int trackLength(WebScrollbar*) OVERRIDE;
-    virtual bool hasButtons(WebScrollbar*) OVERRIDE;
-    virtual bool hasThumb(WebScrollbar*) OVERRIDE;
-    virtual WebRect trackRect(WebScrollbar*) OVERRIDE;
-    virtual WebRect thumbRect(WebScrollbar*) OVERRIDE;
-    virtual int minimumThumbLength(WebScrollbar*) OVERRIDE;
-    virtual int scrollbarThickness(WebScrollbar*) OVERRIDE;
-    virtual WebRect backButtonStartRect(WebScrollbar*) OVERRIDE;
-    virtual WebRect backButtonEndRect(WebScrollbar*) OVERRIDE;
-    virtual WebRect forwardButtonStartRect(WebScrollbar*) OVERRIDE;
-    virtual WebRect forwardButtonEndRect(WebScrollbar*) OVERRIDE;
-    virtual WebRect constrainTrackRectToTrackPieces(WebScrollbar*, const WebRect&) OVERRIDE;
-    virtual void splitTrack(WebScrollbar*, const WebRect& track, WebRect& startTrack, WebRect& thumb, WebRect& endTrack) OVERRIDE;
-
-private:
-    explicit WebScrollbarThemeGeometryNative(WebCore::ScrollbarTheme*);
-
-    // The theme is not owned by this class. It is assumed that the theme is a
-    // static pointer and its lifetime is essentially infinite. Only thread-safe
-    // functions on the theme can be called by this theme.
-    WebCore::ScrollbarTheme* m_theme;
-};
-
-} // namespace blink
-
-#endif
diff --git a/Source/core/platform/mac/ThemeMac.h b/Source/core/platform/mac/ThemeMac.h
deleted file mode 100644
index 3e4d44b..0000000
--- a/Source/core/platform/mac/ThemeMac.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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.
- */
-
-#ifndef ThemeMac_h
-#define ThemeMac_h
-
-#include "platform/Theme.h"
-
-@interface NSFont(WebCoreTheme)
-- (NSString*)webCoreFamilyName;
-@end
-
-namespace WebCore {
-
-class ThemeMac : public Theme {
-public:
-    ThemeMac() { }
-    virtual ~ThemeMac() { }
-
-    virtual int baselinePositionAdjustment(ControlPart) const;
-
-    virtual FontDescription controlFont(ControlPart, const FontDescription&, float zoomFactor) const;
-
-    virtual LengthSize controlSize(ControlPart, const FontDescription&, const LengthSize&, float zoomFactor) const;
-    virtual LengthSize minimumControlSize(ControlPart, const FontDescription&, float zoomFactor) const;
-
-    virtual LengthBox controlPadding(ControlPart, const FontDescription&, const LengthBox& zoomedBox, float zoomFactor) const;
-    virtual LengthBox controlBorder(ControlPart, const FontDescription&, const LengthBox& zoomedBox, float zoomFactor) const;
-
-    virtual bool controlRequiresPreWhiteSpace(ControlPart part) const { return part == PushButtonPart; }
-
-    virtual void paint(ControlPart, ControlStates, GraphicsContext*, const IntRect&, float zoomFactor, ScrollView*) const;
-    virtual void inflateControlPaintRect(ControlPart, ControlStates, IntRect&, float zoomFactor) const;
-
-    // FIXME: Once RenderThemeMac is converted over to use Theme then this can be internal to ThemeMac.
-    static NSView* ensuredView(ScrollView*);
-    static void setFocusRingClipRect(const FloatRect&);
-};
-
-} // namespace WebCore
-
-#endif // ThemeMac_h
diff --git a/Source/core/platform/mac/ThemeMac.mm b/Source/core/platform/mac/ThemeMac.mm
deleted file mode 100644
index e24ee65..0000000
--- a/Source/core/platform/mac/ThemeMac.mm
+++ /dev/null
@@ -1,728 +0,0 @@
-/*
- * Copyright (C) 2008, 2010, 2011, 2012 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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. 
- */
-
-#import "config.h"
-#import "core/platform/mac/ThemeMac.h"
-
-#import <Carbon/Carbon.h>
-#import "platform/graphics/GraphicsContextStateSaver.h"
-#import "platform/mac/BlockExceptions.h"
-#import "platform/mac/LocalCurrentGraphicsContext.h"
-#import "platform/mac/WebCoreNSCellExtras.h"
-#import "platform/scroll/ScrollView.h"
-#include "wtf/StdLibExtras.h"
-
-using namespace std;
-
-NSRect focusRingClipRect;
-
-// This is a view whose sole purpose is to tell AppKit that it's flipped.
-@interface WebCoreFlippedView : NSControl
-@end
-
-@implementation WebCoreFlippedView
-
-- (BOOL)isFlipped
-{
-    return YES;
-}
-
-- (NSText *)currentEditor
-{
-    return nil;
-}
-
-- (BOOL)_automaticFocusRingDisabled
-{
-    return YES;
-}
-
-- (NSRect)_focusRingVisibleRect
-{
-    if (NSIsEmptyRect(focusRingClipRect))
-        return [self visibleRect];
-
-    NSRect rect = focusRingClipRect;
-    rect.origin.y = [self bounds].size.height - NSMaxY(rect);
-
-    return rect;
-}
-
-- (NSView *)_focusRingClipAncestor
-{
-    return self;
-}
-
-@end
-
-@implementation NSFont (WebCoreTheme)
-
-- (NSString*)webCoreFamilyName
-{
-    if ([[self familyName] hasPrefix:@"."])
-        return [self fontName];
-
-    return [self familyName];
-}
-
-@end
-
-namespace WebCore {
-
-enum {
-    topMargin,
-    rightMargin,
-    bottomMargin,
-    leftMargin
-};
-
-Theme* platformTheme()
-{
-    DEFINE_STATIC_LOCAL(ThemeMac, themeMac, ());
-    return &themeMac;
-}
-
-// Helper functions used by a bunch of different control parts.
-
-static NSControlSize controlSizeForFont(const FontDescription& fontDescription)
-{
-    int fontSize = fontDescription.computedPixelSize();
-    if (fontSize >= 16)
-        return NSRegularControlSize;
-    if (fontSize >= 11)
-        return NSSmallControlSize;
-    return NSMiniControlSize;
-}
-
-static LengthSize sizeFromNSControlSize(NSControlSize nsControlSize, const LengthSize& zoomedSize, float zoomFactor, const IntSize* sizes)
-{
-    IntSize controlSize = sizes[nsControlSize];
-    if (zoomFactor != 1.0f)
-        controlSize = IntSize(controlSize.width() * zoomFactor, controlSize.height() * zoomFactor);
-    LengthSize result = zoomedSize;
-    if (zoomedSize.width().isIntrinsicOrAuto() && controlSize.width() > 0)
-        result.setWidth(Length(controlSize.width(), Fixed));
-    if (zoomedSize.height().isIntrinsicOrAuto() && controlSize.height() > 0)
-        result.setHeight(Length(controlSize.height(), Fixed));
-    return result;
-}
-
-static LengthSize sizeFromFont(const FontDescription& fontDescription, const LengthSize& zoomedSize, float zoomFactor, const IntSize* sizes)
-{
-    return sizeFromNSControlSize(controlSizeForFont(fontDescription), zoomedSize, zoomFactor, sizes);
-}
-
-static ControlSize controlSizeFromPixelSize(const IntSize* sizes, const IntSize& minZoomedSize, float zoomFactor)
-{
-    if (minZoomedSize.width() >= static_cast<int>(sizes[NSRegularControlSize].width() * zoomFactor) &&
-        minZoomedSize.height() >= static_cast<int>(sizes[NSRegularControlSize].height() * zoomFactor))
-        return NSRegularControlSize;
-    if (minZoomedSize.width() >= static_cast<int>(sizes[NSSmallControlSize].width() * zoomFactor) &&
-        minZoomedSize.height() >= static_cast<int>(sizes[NSSmallControlSize].height() * zoomFactor))
-        return NSSmallControlSize;
-    return NSMiniControlSize;
-}
-
-static void setControlSize(NSCell* cell, const IntSize* sizes, const IntSize& minZoomedSize, float zoomFactor)
-{
-    ControlSize size = controlSizeFromPixelSize(sizes, minZoomedSize, zoomFactor);
-    if (size != [cell controlSize]) // Only update if we have to, since AppKit does work even if the size is the same.
-        [cell setControlSize:(NSControlSize)size];
-}
-
-static void updateStates(NSCell* cell, ControlStates states)
-{
-    // Hover state is not supported by Aqua.
-    
-    // Pressed state
-    bool oldPressed = [cell isHighlighted];
-    bool pressed = states & PressedState;
-    if (pressed != oldPressed)
-        [cell setHighlighted:pressed];
-    
-    // Enabled state
-    bool oldEnabled = [cell isEnabled];
-    bool enabled = states & EnabledState;
-    if (enabled != oldEnabled)
-        [cell setEnabled:enabled];
-    
-#if BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING
-    // Focused state
-    bool oldFocused = [cell showsFirstResponder];
-    bool focused = states & FocusState;
-    if (focused != oldFocused)
-        [cell setShowsFirstResponder:focused];
-#endif
-
-    // Checked and Indeterminate
-    bool oldIndeterminate = [cell state] == NSMixedState;
-    bool indeterminate = (states & IndeterminateState);
-    bool checked = states & CheckedState;
-    bool oldChecked = [cell state] == NSOnState;
-    if (oldIndeterminate != indeterminate || checked != oldChecked)
-        [cell setState:indeterminate ? NSMixedState : (checked ? NSOnState : NSOffState)];
-        
-    // Window inactive state does not need to be checked explicitly, since we paint parented to 
-    // a view in a window whose key state can be detected.
-}
-
-static ThemeDrawState convertControlStatesToThemeDrawState(ThemeButtonKind kind, ControlStates states)
-{
-    if (states & ReadOnlyState)
-        return kThemeStateUnavailableInactive;
-    if (!(states & EnabledState))
-        return kThemeStateUnavailableInactive;
-
-    // Do not process PressedState if !EnabledState or ReadOnlyState.
-    if (states & PressedState) {
-        if (kind == kThemeIncDecButton || kind == kThemeIncDecButtonSmall || kind == kThemeIncDecButtonMini)
-            return states & SpinUpState ? kThemeStatePressedUp : kThemeStatePressedDown;
-        return kThemeStatePressed;
-    }
-    return kThemeStateActive;
-}
-
-static IntRect inflateRect(const IntRect& zoomedRect, const IntSize& zoomedSize, const int* margins, float zoomFactor)
-{
-    // Only do the inflation if the available width/height are too small.  Otherwise try to
-    // fit the glow/check space into the available box's width/height.
-    int widthDelta = zoomedRect.width() - (zoomedSize.width() + margins[leftMargin] * zoomFactor + margins[rightMargin] * zoomFactor);
-    int heightDelta = zoomedRect.height() - (zoomedSize.height() + margins[topMargin] * zoomFactor + margins[bottomMargin] * zoomFactor);
-    IntRect result(zoomedRect);
-    if (widthDelta < 0) {
-        result.setX(result.x() - margins[leftMargin] * zoomFactor);
-        result.setWidth(result.width() - widthDelta);
-    }
-    if (heightDelta < 0) {
-        result.setY(result.y() - margins[topMargin] * zoomFactor);
-        result.setHeight(result.height() - heightDelta);
-    }
-    return result;
-}
-
-// Checkboxes
-
-static const IntSize* checkboxSizes()
-{
-    static const IntSize sizes[3] = { IntSize(14, 14), IntSize(12, 12), IntSize(10, 10) };
-    return sizes;
-}
-
-static const int* checkboxMargins(NSControlSize controlSize)
-{
-    static const int margins[3][4] =
-    {
-        { 3, 4, 4, 2 },
-        { 4, 3, 3, 3 },
-        { 4, 3, 3, 3 },
-    };
-    return margins[controlSize];
-}
-
-static LengthSize checkboxSize(const FontDescription& fontDescription, const LengthSize& zoomedSize, float zoomFactor)
-{
-    // If the width and height are both specified, then we have nothing to do.
-    if (!zoomedSize.width().isIntrinsicOrAuto() && !zoomedSize.height().isIntrinsicOrAuto())
-        return zoomedSize;
-
-    // Use the font size to determine the intrinsic width of the control.
-    return sizeFromFont(fontDescription, zoomedSize, zoomFactor, checkboxSizes());
-}
-
-static NSButtonCell *checkbox(ControlStates states, const IntRect& zoomedRect, float zoomFactor)
-{
-    static NSButtonCell *checkboxCell;
-    if (!checkboxCell) {
-        checkboxCell = [[NSButtonCell alloc] init];
-        [checkboxCell setButtonType:NSSwitchButton];
-        [checkboxCell setTitle:nil];
-        [checkboxCell setAllowsMixedState:YES];
-        [checkboxCell setFocusRingType:NSFocusRingTypeExterior];
-    }
-    
-    // Set the control size based off the rectangle we're painting into.
-    setControlSize(checkboxCell, checkboxSizes(), zoomedRect.size(), zoomFactor);
-
-    // Update the various states we respond to.
-    updateStates(checkboxCell, states);
-    
-    return checkboxCell;
-}
-
-// FIXME: Share more code with radio buttons.
-static void paintCheckbox(ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView* scrollView)
-{
-    BEGIN_BLOCK_OBJC_EXCEPTIONS
-
-    // Determine the width and height needed for the control and prepare the cell for painting.
-    NSButtonCell *checkboxCell = checkbox(states, zoomedRect, zoomFactor);
-    GraphicsContextStateSaver stateSaver(*context);
-
-    NSControlSize controlSize = [checkboxCell controlSize];
-    IntSize zoomedSize = checkboxSizes()[controlSize];
-    zoomedSize.setWidth(zoomedSize.width() * zoomFactor);
-    zoomedSize.setHeight(zoomedSize.height() * zoomFactor);
-    IntRect inflatedRect = inflateRect(zoomedRect, zoomedSize, checkboxMargins(controlSize), zoomFactor);
-    
-    if (zoomFactor != 1.0f) {
-        inflatedRect.setWidth(inflatedRect.width() / zoomFactor);
-        inflatedRect.setHeight(inflatedRect.height() / zoomFactor);
-        context->translate(inflatedRect.x(), inflatedRect.y());
-        context->scale(FloatSize(zoomFactor, zoomFactor));
-        context->translate(-inflatedRect.x(), -inflatedRect.y());
-    }
-
-    LocalCurrentGraphicsContext localContext(context);
-    NSView *view = ThemeMac::ensuredView(scrollView);
-    [checkboxCell drawWithFrame:NSRect(inflatedRect) inView:view];
-#if !BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING
-    if (states & FocusState)
-        [checkboxCell _web_drawFocusRingWithFrame:NSRect(inflatedRect) inView:view];
-#endif
-    [checkboxCell setControlView:nil];
-    
-    END_BLOCK_OBJC_EXCEPTIONS
-}
-
-// Radio Buttons
-
-static const IntSize* radioSizes()
-{
-    static const IntSize sizes[3] = { IntSize(14, 15), IntSize(12, 13), IntSize(10, 10) };
-    return sizes;
-}
-
-static const int* radioMargins(NSControlSize controlSize)
-{
-    static const int margins[3][4] =
-    {
-        { 2, 2, 4, 2 },
-        { 3, 2, 3, 2 },
-        { 1, 0, 2, 0 },
-    };
-    return margins[controlSize];
-}
-
-static LengthSize radioSize(const FontDescription& fontDescription, const LengthSize& zoomedSize, float zoomFactor)
-{
-    // If the width and height are both specified, then we have nothing to do.
-    if (!zoomedSize.width().isIntrinsicOrAuto() && !zoomedSize.height().isIntrinsicOrAuto())
-        return zoomedSize;
-
-    // Use the font size to determine the intrinsic width of the control.
-    return sizeFromFont(fontDescription, zoomedSize, zoomFactor, radioSizes());
-}
-
-static NSButtonCell *radio(ControlStates states, const IntRect& zoomedRect, float zoomFactor)
-{
-    static NSButtonCell *radioCell;
-    if (!radioCell) {
-        radioCell = [[NSButtonCell alloc] init];
-        [radioCell setButtonType:NSRadioButton];
-        [radioCell setTitle:nil];
-        [radioCell setFocusRingType:NSFocusRingTypeExterior];
-    }
-    
-    // Set the control size based off the rectangle we're painting into.
-    setControlSize(radioCell, radioSizes(), zoomedRect.size(), zoomFactor);
-
-    // Update the various states we respond to.
-    updateStates(radioCell, states);
-    
-    return radioCell;
-}
-
-static void paintRadio(ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView* scrollView)
-{
-    // Determine the width and height needed for the control and prepare the cell for painting.
-    NSButtonCell *radioCell = radio(states, zoomedRect, zoomFactor);
-    GraphicsContextStateSaver stateSaver(*context);
-
-    NSControlSize controlSize = [radioCell controlSize];
-    IntSize zoomedSize = radioSizes()[controlSize];
-    zoomedSize.setWidth(zoomedSize.width() * zoomFactor);
-    zoomedSize.setHeight(zoomedSize.height() * zoomFactor);
-    IntRect inflatedRect = inflateRect(zoomedRect, zoomedSize, radioMargins(controlSize), zoomFactor);
-    
-    if (zoomFactor != 1.0f) {
-        inflatedRect.setWidth(inflatedRect.width() / zoomFactor);
-        inflatedRect.setHeight(inflatedRect.height() / zoomFactor);
-        context->translate(inflatedRect.x(), inflatedRect.y());
-        context->scale(FloatSize(zoomFactor, zoomFactor));
-        context->translate(-inflatedRect.x(), -inflatedRect.y());
-    }
-
-    LocalCurrentGraphicsContext localContext(context);
-    BEGIN_BLOCK_OBJC_EXCEPTIONS
-    NSView *view = ThemeMac::ensuredView(scrollView);
-    [radioCell drawWithFrame:NSRect(inflatedRect) inView:view];
-#if !BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING
-    if (states & FocusState)
-        [radioCell _web_drawFocusRingWithFrame:NSRect(inflatedRect) inView:view];
-#endif
-    [radioCell setControlView:nil];
-    END_BLOCK_OBJC_EXCEPTIONS
-}
-
-// Buttons
-
-// Buttons really only constrain height. They respect width.
-static const IntSize* buttonSizes()
-{
-    static const IntSize sizes[3] = { IntSize(0, 21), IntSize(0, 18), IntSize(0, 15) };
-    return sizes;
-}
-
-static const int* buttonMargins(NSControlSize controlSize)
-{
-    static const int margins[3][4] =
-    {
-        { 4, 6, 7, 6 },
-        { 4, 5, 6, 5 },
-        { 0, 1, 1, 1 },
-    };
-    return margins[controlSize];
-}
-
-static void setUpButtonCell(NSButtonCell *cell, ControlPart part, ControlStates states, const IntRect& zoomedRect, float zoomFactor)
-{
-    // Set the control size based off the rectangle we're painting into.
-    const IntSize* sizes = buttonSizes();
-    if (part == SquareButtonPart || zoomedRect.height() > buttonSizes()[NSRegularControlSize].height() * zoomFactor) {
-        // Use the square button
-        if ([cell bezelStyle] != NSShadowlessSquareBezelStyle)
-            [cell setBezelStyle:NSShadowlessSquareBezelStyle];
-    } else if ([cell bezelStyle] != NSRoundedBezelStyle)
-        [cell setBezelStyle:NSRoundedBezelStyle];
-
-    setControlSize(cell, sizes, zoomedRect.size(), zoomFactor);
-
-    // Update the various states we respond to.
-    updateStates(cell, states);
-}
-
-static NSButtonCell *button(ControlPart part, ControlStates states, const IntRect& zoomedRect, float zoomFactor)
-{
-    static NSButtonCell *cell = nil;
-    if (!cell) {
-        cell = [[NSButtonCell alloc] init];
-        [cell setTitle:nil];
-        [cell setButtonType:NSMomentaryPushInButton];
-    }
-    setUpButtonCell(cell, part, states, zoomedRect, zoomFactor);
-    return cell;
-}
-
-static void paintButton(ControlPart part, ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView* scrollView)
-{
-    BEGIN_BLOCK_OBJC_EXCEPTIONS
-    
-    // Determine the width and height needed for the control and prepare the cell for painting.
-    NSButtonCell *buttonCell = button(part, states, zoomedRect, zoomFactor);
-    GraphicsContextStateSaver stateSaver(*context);
-
-    NSControlSize controlSize = [buttonCell controlSize];
-    IntSize zoomedSize = buttonSizes()[controlSize];
-    zoomedSize.setWidth(zoomedRect.width()); // Buttons don't ever constrain width, so the zoomed width can just be honored.
-    zoomedSize.setHeight(zoomedSize.height() * zoomFactor);
-    IntRect inflatedRect = zoomedRect;
-    if ([buttonCell bezelStyle] == NSRoundedBezelStyle) {
-        // Center the button within the available space.
-        if (inflatedRect.height() > zoomedSize.height()) {
-            inflatedRect.setY(inflatedRect.y() + (inflatedRect.height() - zoomedSize.height()) / 2);
-            inflatedRect.setHeight(zoomedSize.height());
-        }
-
-        // Now inflate it to account for the shadow.
-        inflatedRect = inflateRect(inflatedRect, zoomedSize, buttonMargins(controlSize), zoomFactor);
-
-        if (zoomFactor != 1.0f) {
-            inflatedRect.setWidth(inflatedRect.width() / zoomFactor);
-            inflatedRect.setHeight(inflatedRect.height() / zoomFactor);
-            context->translate(inflatedRect.x(), inflatedRect.y());
-            context->scale(FloatSize(zoomFactor, zoomFactor));
-            context->translate(-inflatedRect.x(), -inflatedRect.y());
-        }
-    } 
-
-    LocalCurrentGraphicsContext localContext(context);
-    NSView *view = ThemeMac::ensuredView(scrollView);
-
-    [buttonCell drawWithFrame:NSRect(inflatedRect) inView:view];
-#if !BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING
-    if (states & FocusState)
-        [buttonCell _web_drawFocusRingWithFrame:NSRect(inflatedRect) inView:view];
-#endif
-    [buttonCell setControlView:nil];
-
-    END_BLOCK_OBJC_EXCEPTIONS
-}
-
-// Stepper
-
-static const IntSize* stepperSizes()
-{
-    static const IntSize sizes[3] = { IntSize(19, 27), IntSize(15, 22), IntSize(13, 15) };
-    return sizes;
-}
-
-// We don't use controlSizeForFont() for steppers because the stepper height
-// should be equal to or less than the corresponding text field height,
-static NSControlSize stepperControlSizeForFont(const FontDescription& fontDescription)
-{
-    int fontSize = fontDescription.computedPixelSize();
-    if (fontSize >= 18)
-        return NSRegularControlSize;
-    if (fontSize >= 13)
-        return NSSmallControlSize;
-    return NSMiniControlSize;
-}
-
-static void paintStepper(ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView*)
-{
-    // We don't use NSStepperCell because there are no ways to draw an
-    // NSStepperCell with the up button highlighted.
-
-    HIThemeButtonDrawInfo drawInfo;
-    drawInfo.version = 0;
-    drawInfo.state = convertControlStatesToThemeDrawState(kThemeIncDecButton, states);
-    drawInfo.adornment = kThemeAdornmentDefault;
-    ControlSize controlSize = controlSizeFromPixelSize(stepperSizes(), zoomedRect.size(), zoomFactor);
-    if (controlSize == NSSmallControlSize)
-        drawInfo.kind = kThemeIncDecButtonSmall;
-    else if (controlSize == NSMiniControlSize)
-        drawInfo.kind = kThemeIncDecButtonMini;
-    else
-        drawInfo.kind = kThemeIncDecButton;
-
-    IntRect rect(zoomedRect);
-    GraphicsContextStateSaver stateSaver(*context);
-    if (zoomFactor != 1.0f) {
-        rect.setWidth(rect.width() / zoomFactor);
-        rect.setHeight(rect.height() / zoomFactor);
-        context->translate(rect.x(), rect.y());
-        context->scale(FloatSize(zoomFactor, zoomFactor));
-        context->translate(-rect.x(), -rect.y());
-    }
-    CGRect bounds(rect);
-    CGRect backgroundBounds;
-    HIThemeGetButtonBackgroundBounds(&bounds, &drawInfo, &backgroundBounds);
-    // Center the stepper rectangle in the specified area.
-    backgroundBounds.origin.x = bounds.origin.x + (bounds.size.width - backgroundBounds.size.width) / 2;
-    if (backgroundBounds.size.height < bounds.size.height) {
-        int heightDiff = clampToInteger(bounds.size.height - backgroundBounds.size.height);
-        backgroundBounds.origin.y = bounds.origin.y + (heightDiff / 2) + 1;
-    }
-
-    LocalCurrentGraphicsContext localContext(context);
-    HIThemeDrawButton(&backgroundBounds, &drawInfo, localContext.cgContext(), kHIThemeOrientationNormal, 0);
-}
-
-// This will ensure that we always return a valid NSView, even if ScrollView doesn't have an associated document NSView.
-// If the ScrollView doesn't have an NSView, we will return a fake NSView whose sole purpose is to tell AppKit that it's flipped.
-NSView *ThemeMac::ensuredView(ScrollView* scrollView)
-{
-
-    // Use a fake flipped view.
-    static NSView *flippedView = [[WebCoreFlippedView alloc] init];
-    [flippedView setFrameSize:NSSizeFromCGSize(scrollView->contentsSize())];
-
-    return flippedView;
-}
-
-void ThemeMac::setFocusRingClipRect(const FloatRect& rect)
-{
-    focusRingClipRect = rect;
-}
-
-// Theme overrides
-
-int ThemeMac::baselinePositionAdjustment(ControlPart part) const
-{
-    if (part == CheckboxPart || part == RadioPart)
-        return -2;
-    return Theme::baselinePositionAdjustment(part);
-}
-
-FontDescription ThemeMac::controlFont(ControlPart part, const FontDescription& fontDescription, float zoomFactor) const
-{
-    switch (part) {
-        case PushButtonPart: {
-            FontDescription result;
-            result.setIsAbsoluteSize(true);
-            result.setGenericFamily(FontDescription::SerifFamily);
-
-            NSFont* nsFont = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:controlSizeForFont(fontDescription)]];
-            result.firstFamily().setFamily([nsFont webCoreFamilyName]);
-            result.setComputedSize([nsFont pointSize] * zoomFactor);
-            result.setSpecifiedSize([nsFont pointSize] * zoomFactor);
-            return result;
-        }
-        default:
-            return Theme::controlFont(part, fontDescription, zoomFactor);
-    }
-}
-
-LengthSize ThemeMac::controlSize(ControlPart part, const FontDescription& fontDescription, const LengthSize& zoomedSize, float zoomFactor) const
-{
-    switch (part) {
-        case CheckboxPart:
-            return checkboxSize(fontDescription, zoomedSize, zoomFactor);
-        case RadioPart:
-            return radioSize(fontDescription, zoomedSize, zoomFactor);
-        case PushButtonPart:
-            // Height is reset to auto so that specified heights can be ignored.
-            return sizeFromFont(fontDescription, LengthSize(zoomedSize.width(), Length()), zoomFactor, buttonSizes());
-        case InnerSpinButtonPart:
-            if (!zoomedSize.width().isIntrinsicOrAuto() && !zoomedSize.height().isIntrinsicOrAuto())
-                return zoomedSize;
-            return sizeFromNSControlSize(stepperControlSizeForFont(fontDescription), zoomedSize, zoomFactor, stepperSizes());
-        default:
-            return zoomedSize;
-    }
-}
-
-LengthSize ThemeMac::minimumControlSize(ControlPart part, const FontDescription& fontDescription, float zoomFactor) const
-{
-    switch (part) {
-        case SquareButtonPart:
-        case ButtonPart:
-            return LengthSize(Length(0, Fixed), Length(static_cast<int>(15 * zoomFactor), Fixed));
-        case InnerSpinButtonPart:{
-            IntSize base = stepperSizes()[NSMiniControlSize];
-            return LengthSize(Length(static_cast<int>(base.width() * zoomFactor), Fixed),
-                              Length(static_cast<int>(base.height() * zoomFactor), Fixed));
-        }
-        default:
-            return Theme::minimumControlSize(part, fontDescription, zoomFactor);
-    }
-}
-
-LengthBox ThemeMac::controlBorder(ControlPart part, const FontDescription& fontDescription, const LengthBox& zoomedBox, float zoomFactor) const
-{
-    switch (part) {
-        case SquareButtonPart:
-        case ButtonPart:
-            return LengthBox(0, zoomedBox.right().value(), 0, zoomedBox.left().value());
-        default:
-            return Theme::controlBorder(part, fontDescription, zoomedBox, zoomFactor);
-    }
-}
-
-LengthBox ThemeMac::controlPadding(ControlPart part, const FontDescription& fontDescription, const LengthBox& zoomedBox, float zoomFactor) const
-{
-    switch (part) {
-        case PushButtonPart: {
-            // Just use 8px.  AppKit wants to use 11px for mini buttons, but that padding is just too large
-            // for real-world Web sites (creating a huge necessary minimum width for buttons whose space is
-            // by definition constrained, since we select mini only for small cramped environments.
-            // This also guarantees the HTML <button> will match our rendering by default, since we're using a consistent
-            // padding.
-            const int padding = 8 * zoomFactor;
-            return LengthBox(0, padding, 0, padding);
-        }
-        default:
-            return Theme::controlPadding(part, fontDescription, zoomedBox, zoomFactor);
-    }
-}
-
-void ThemeMac::inflateControlPaintRect(ControlPart part, ControlStates states, IntRect& zoomedRect, float zoomFactor) const
-{
-    BEGIN_BLOCK_OBJC_EXCEPTIONS
-    switch (part) {
-        case CheckboxPart: {
-            // We inflate the rect as needed to account for padding included in the cell to accommodate the checkbox
-            // shadow" and the check.  We don't consider this part of the bounds of the control in WebKit.
-            NSCell *cell = checkbox(states, zoomedRect, zoomFactor);
-            NSControlSize controlSize = [cell controlSize];
-            IntSize zoomedSize = checkboxSizes()[controlSize];
-            zoomedSize.setHeight(zoomedSize.height() * zoomFactor);
-            zoomedSize.setWidth(zoomedSize.width() * zoomFactor);
-            zoomedRect = inflateRect(zoomedRect, zoomedSize, checkboxMargins(controlSize), zoomFactor);
-            break;
-        }
-        case RadioPart: {
-            // We inflate the rect as needed to account for padding included in the cell to accommodate the radio button
-            // shadow".  We don't consider this part of the bounds of the control in WebKit.
-            NSCell *cell = radio(states, zoomedRect, zoomFactor);
-            NSControlSize controlSize = [cell controlSize];
-            IntSize zoomedSize = radioSizes()[controlSize];
-            zoomedSize.setHeight(zoomedSize.height() * zoomFactor);
-            zoomedSize.setWidth(zoomedSize.width() * zoomFactor);
-            zoomedRect = inflateRect(zoomedRect, zoomedSize, radioMargins(controlSize), zoomFactor);
-            break;
-        }
-        case PushButtonPart:
-        case ButtonPart: {
-            NSButtonCell *cell = button(part, states, zoomedRect, zoomFactor);
-            NSControlSize controlSize = [cell controlSize];
-
-            // We inflate the rect as needed to account for the Aqua button's shadow.
-            if ([cell bezelStyle] == NSRoundedBezelStyle) {
-                IntSize zoomedSize = buttonSizes()[controlSize];
-                zoomedSize.setHeight(zoomedSize.height() * zoomFactor);
-                zoomedSize.setWidth(zoomedRect.width()); // Buttons don't ever constrain width, so the zoomed width can just be honored.
-                zoomedRect = inflateRect(zoomedRect, zoomedSize, buttonMargins(controlSize), zoomFactor);
-            }
-            break;
-        }
-        case InnerSpinButtonPart: {
-            static const int stepperMargin[4] = { 0, 0, 0, 0 };
-            ControlSize controlSize = controlSizeFromPixelSize(stepperSizes(), zoomedRect.size(), zoomFactor);
-            IntSize zoomedSize = stepperSizes()[controlSize];
-            zoomedSize.setHeight(zoomedSize.height() * zoomFactor);
-            zoomedSize.setWidth(zoomedSize.width() * zoomFactor);
-            zoomedRect = inflateRect(zoomedRect, zoomedSize, stepperMargin, zoomFactor);
-            break;
-        }
-        default:
-            break;
-    }
-    END_BLOCK_OBJC_EXCEPTIONS
-}
-
-void ThemeMac::paint(ControlPart part, ControlStates states, GraphicsContext* context, const IntRect& zoomedRect, float zoomFactor, ScrollView* scrollView) const
-{
-    switch (part) {
-        case CheckboxPart:
-            paintCheckbox(states, context, zoomedRect, zoomFactor, scrollView);
-            break;
-        case RadioPart:
-            paintRadio(states, context, zoomedRect, zoomFactor, scrollView);
-            break;
-        case PushButtonPart:
-        case ButtonPart:
-        case SquareButtonPart:
-            paintButton(part, states, context, zoomedRect, zoomFactor, scrollView);
-            break;
-        case InnerSpinButtonPart:
-            paintStepper(states, context, zoomedRect, zoomFactor, scrollView);
-            break;
-        default:
-            break;
-    }
-}
-
-}
diff --git a/Source/core/platform/mediastream/MediaStreamCenter.cpp b/Source/core/platform/mediastream/MediaStreamCenter.cpp
deleted file mode 100644
index 3baadb4..0000000
--- a/Source/core/platform/mediastream/MediaStreamCenter.cpp
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * Copyright (C) 2012 Google Inc. 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.
- * 3. Neither the name of Ericsson nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-
-#include "core/platform/mediastream/MediaStreamCenter.h"
-
-#include "core/platform/mediastream/MediaStreamDescriptor.h"
-#include "modules/mediastream/MediaStreamTrackSourcesRequest.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebMediaStream.h"
-#include "public/platform/WebMediaStreamCenter.h"
-#include "public/platform/WebMediaStreamTrack.h"
-#include "public/platform/WebMediaStreamTrackSourcesRequest.h"
-#include "wtf/MainThread.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-MediaStreamCenter& MediaStreamCenter::instance()
-{
-    ASSERT(isMainThread());
-    DEFINE_STATIC_LOCAL(MediaStreamCenter, center, ());
-    return center;
-}
-
-MediaStreamCenter::MediaStreamCenter()
-    : m_private(adoptPtr(blink::Platform::current()->createMediaStreamCenter(this)))
-{
-}
-
-MediaStreamCenter::~MediaStreamCenter()
-{
-}
-
-bool MediaStreamCenter::getMediaStreamTrackSources(PassRefPtr<MediaStreamTrackSourcesRequest> request)
-{
-    return m_private && m_private->getMediaStreamTrackSources(request);
-}
-
-void MediaStreamCenter::didSetMediaStreamTrackEnabled(MediaStreamDescriptor* stream,  MediaStreamComponent* component)
-{
-    if (m_private) {
-        if (component->enabled()) {
-            m_private->didEnableMediaStreamTrack(stream, component);
-            m_private->didEnableMediaStreamTrack(component);
-        } else {
-            m_private->didDisableMediaStreamTrack(stream, component);
-            m_private->didDisableMediaStreamTrack(component);
-        }
-    }
-}
-
-bool MediaStreamCenter::didAddMediaStreamTrack(MediaStreamDescriptor* stream, MediaStreamComponent* component)
-{
-    return m_private && m_private->didAddMediaStreamTrack(stream, component);
-}
-
-bool MediaStreamCenter::didRemoveMediaStreamTrack(MediaStreamDescriptor* stream, MediaStreamComponent* component)
-{
-    return m_private && m_private->didRemoveMediaStreamTrack(stream, component);
-}
-
-void MediaStreamCenter::didStopLocalMediaStream(MediaStreamDescriptor* stream)
-{
-    if (m_private)
-        m_private->didStopLocalMediaStream(stream);
-}
-
-bool MediaStreamCenter::didStopMediaStreamTrack(MediaStreamComponent* track)
-{
-    return m_private && m_private->didStopMediaStreamTrack(track);
-}
-
-void MediaStreamCenter::didCreateMediaStream(MediaStreamDescriptor* stream)
-{
-    if (m_private) {
-        blink::WebMediaStream webStream(stream);
-        m_private->didCreateMediaStream(webStream);
-    }
-}
-
-void MediaStreamCenter::didCreateMediaStreamTrack(MediaStreamComponent* track)
-{
-    if (m_private)
-        m_private->didCreateMediaStreamTrack(track);
-}
-
-void MediaStreamCenter::stopLocalMediaStream(const blink::WebMediaStream& webStream)
-{
-    MediaStreamDescriptor* stream = webStream;
-    MediaStreamDescriptorClient* client = stream->client();
-    if (client)
-        client->streamEnded();
-    else
-        stream->setEnded();
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/mediastream/MediaStreamCenter.h b/Source/core/platform/mediastream/MediaStreamCenter.h
deleted file mode 100644
index 7a3630b..0000000
--- a/Source/core/platform/mediastream/MediaStreamCenter.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * Copyright (C) 2012 Google Inc. 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.
- * 3. Neither the name of Ericsson nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef MediaStreamCenter_h
-#define MediaStreamCenter_h
-
-#include "public/platform/WebMediaStreamCenterClient.h"
-#include "public/platform/WebVector.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace blink {
-class WebMediaStream;
-class WebMediaStreamCenter;
-class WebMediaStreamTrack;
-}
-
-namespace WebCore {
-
-class MediaStreamComponent;
-class MediaStreamDescriptor;
-class MediaStreamTrackSourcesRequest;
-
-class MediaStreamCenter : public blink::WebMediaStreamCenterClient {
-public:
-    ~MediaStreamCenter();
-
-    static MediaStreamCenter& instance();
-
-    bool getMediaStreamTrackSources(PassRefPtr<MediaStreamTrackSourcesRequest>);
-
-    void didCreateMediaStreamTrack(MediaStreamComponent*);
-    void didSetMediaStreamTrackEnabled(MediaStreamDescriptor*, MediaStreamComponent*);
-    bool didStopMediaStreamTrack(MediaStreamComponent*);
-
-    void didCreateMediaStream(MediaStreamDescriptor*);
-    bool didAddMediaStreamTrack(MediaStreamDescriptor*, MediaStreamComponent*);
-    bool didRemoveMediaStreamTrack(MediaStreamDescriptor*, MediaStreamComponent*);
-    void didStopLocalMediaStream(MediaStreamDescriptor*);
-
-    // blink::WebMediaStreamCenterClient
-    virtual void stopLocalMediaStream(const blink::WebMediaStream&) OVERRIDE;
-
-private:
-    MediaStreamCenter();
-
-    OwnPtr<blink::WebMediaStreamCenter> m_private;
-};
-
-} // namespace WebCore
-
-#endif // MediaStreamCenter_h
diff --git a/Source/core/platform/mediastream/MediaStreamDescriptor.cpp b/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
deleted file mode 100644
index 7ec27a3..0000000
--- a/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-
-#include "core/platform/mediastream/MediaStreamDescriptor.h"
-
-#include "platform/UUID.h"
-
-namespace WebCore {
-
-PassRefPtr<MediaStreamDescriptor> MediaStreamDescriptor::create(const MediaStreamSourceVector& audioSources, const MediaStreamSourceVector& videoSources)
-{
-    return adoptRef(new MediaStreamDescriptor(createCanonicalUUIDString(), audioSources, videoSources));
-}
-
-PassRefPtr<MediaStreamDescriptor> MediaStreamDescriptor::create(const String& id, const MediaStreamComponentVector& audioComponents, const MediaStreamComponentVector& videoComponents)
-{
-    return adoptRef(new MediaStreamDescriptor(id, audioComponents, videoComponents));
-}
-
-void MediaStreamDescriptor::addComponent(PassRefPtr<MediaStreamComponent> component)
-{
-    switch (component->source()->type()) {
-    case MediaStreamSource::TypeAudio:
-        if (m_audioComponents.find(component) == kNotFound)
-            m_audioComponents.append(component);
-        break;
-    case MediaStreamSource::TypeVideo:
-        if (m_videoComponents.find(component) == kNotFound)
-            m_videoComponents.append(component);
-        break;
-    }
-}
-
-void MediaStreamDescriptor::removeComponent(PassRefPtr<MediaStreamComponent> component)
-{
-    size_t pos = kNotFound;
-    switch (component->source()->type()) {
-    case MediaStreamSource::TypeAudio:
-        pos = m_audioComponents.find(component);
-        if (pos != kNotFound)
-            m_audioComponents.remove(pos);
-        break;
-    case MediaStreamSource::TypeVideo:
-        pos = m_videoComponents.find(component);
-        if (pos != kNotFound)
-            m_videoComponents.remove(pos);
-        break;
-    }
-}
-
-void MediaStreamDescriptor::addRemoteTrack(MediaStreamComponent* component)
-{
-    if (m_client)
-        m_client->addRemoteTrack(component);
-    else
-        addComponent(component);
-}
-
-void MediaStreamDescriptor::removeRemoteTrack(MediaStreamComponent* component)
-{
-    if (m_client)
-        m_client->removeRemoteTrack(component);
-    else
-        removeComponent(component);
-}
-
-MediaStreamDescriptor::MediaStreamDescriptor(const String& id, const MediaStreamSourceVector& audioSources, const MediaStreamSourceVector& videoSources)
-    : m_client(0)
-    , m_id(id)
-    , m_ended(false)
-{
-    ASSERT(m_id.length());
-    for (size_t i = 0; i < audioSources.size(); i++)
-        m_audioComponents.append(MediaStreamComponent::create(this, audioSources[i]));
-
-    for (size_t i = 0; i < videoSources.size(); i++)
-        m_videoComponents.append(MediaStreamComponent::create(this, videoSources[i]));
-}
-
-MediaStreamDescriptor::MediaStreamDescriptor(const String& id, const MediaStreamComponentVector& audioComponents, const MediaStreamComponentVector& videoComponents)
-    : m_client(0)
-    , m_id(id)
-    , m_ended(false)
-{
-    ASSERT(m_id.length());
-    for (MediaStreamComponentVector::const_iterator iter = audioComponents.begin(); iter != audioComponents.end(); ++iter) {
-        (*iter)->setStream(this);
-        m_audioComponents.append((*iter));
-    }
-    for (MediaStreamComponentVector::const_iterator iter = videoComponents.begin(); iter != videoComponents.end(); ++iter) {
-        (*iter)->setStream(this);
-        m_videoComponents.append((*iter));
-    }
-}
-
-MediaStreamDescriptor::~MediaStreamDescriptor()
-{
-    for (MediaStreamComponentVector::iterator iter = m_audioComponents.begin(); iter != m_audioComponents.end(); ++iter)
-        (*iter)->setStream(0);
-
-    for (MediaStreamComponentVector::iterator iter = m_videoComponents.begin(); iter != m_videoComponents.end(); ++iter)
-        (*iter)->setStream(0);
-}
-
-} // namespace WebCore
-
diff --git a/Source/core/platform/mediastream/MediaStreamDescriptor.h b/Source/core/platform/mediastream/MediaStreamDescriptor.h
deleted file mode 100644
index 383602b..0000000
--- a/Source/core/platform/mediastream/MediaStreamDescriptor.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * Copyright (C) 2012 Google Inc. 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.
- * 3. Neither the name of Ericsson nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef MediaStreamDescriptor_h
-#define MediaStreamDescriptor_h
-
-#include "platform/mediastream/MediaStreamComponent.h"
-#include "platform/mediastream/MediaStreamSource.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class MediaStreamDescriptorClient {
-public:
-    virtual ~MediaStreamDescriptorClient() { }
-
-    virtual void trackEnded() = 0;
-    virtual void streamEnded() = 0;
-    virtual void addRemoteTrack(MediaStreamComponent*) = 0;
-    virtual void removeRemoteTrack(MediaStreamComponent*) = 0;
-};
-
-class MediaStreamDescriptor FINAL : public RefCounted<MediaStreamDescriptor> {
-public:
-    class ExtraData : public RefCounted<ExtraData> {
-    public:
-        virtual ~ExtraData() { }
-    };
-
-    static PassRefPtr<MediaStreamDescriptor> create(const MediaStreamSourceVector& audioSources, const MediaStreamSourceVector& videoSources);
-
-    static PassRefPtr<MediaStreamDescriptor> create(const String& id, const MediaStreamComponentVector& audioComponents, const MediaStreamComponentVector& videoComponents);
-
-    ~MediaStreamDescriptor();
-
-    MediaStreamDescriptorClient* client() const { return m_client; }
-    void setClient(MediaStreamDescriptorClient* client) { m_client = client; }
-
-    String id() const { return m_id; }
-
-    unsigned numberOfAudioComponents() const { return m_audioComponents.size(); }
-    MediaStreamComponent* audioComponent(unsigned index) const { return m_audioComponents[index].get(); }
-
-    unsigned numberOfVideoComponents() const { return m_videoComponents.size(); }
-    MediaStreamComponent* videoComponent(unsigned index) const { return m_videoComponents[index].get(); }
-
-    void addComponent(PassRefPtr<MediaStreamComponent>);
-    void removeComponent(PassRefPtr<MediaStreamComponent>);
-
-    void addRemoteTrack(MediaStreamComponent*);
-    void removeRemoteTrack(MediaStreamComponent*);
-
-    bool ended() const { return m_ended; }
-    void setEnded() { m_ended = true; }
-
-    PassRefPtr<ExtraData> extraData() const { return m_extraData; }
-    void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
-
-private:
-    MediaStreamDescriptor(const String& id, const MediaStreamSourceVector& audioSources, const MediaStreamSourceVector& videoSources);
-    MediaStreamDescriptor(const String& id, const MediaStreamComponentVector& audioComponents, const MediaStreamComponentVector& videoComponents);
-
-    MediaStreamDescriptorClient* m_client;
-    String m_id;
-    Vector<RefPtr<MediaStreamComponent> > m_audioComponents;
-    Vector<RefPtr<MediaStreamComponent> > m_videoComponents;
-    bool m_ended;
-
-    RefPtr<ExtraData> m_extraData;
-};
-
-typedef Vector<RefPtr<MediaStreamDescriptor> > MediaStreamDescriptorVector;
-
-} // namespace WebCore
-
-#endif // MediaStreamDescriptor_h
diff --git a/Source/core/platform/mediastream/RTCDataChannelHandler.cpp b/Source/core/platform/mediastream/RTCDataChannelHandler.cpp
deleted file mode 100644
index 7c91a11..0000000
--- a/Source/core/platform/mediastream/RTCDataChannelHandler.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-#include "config.h"
-#include "core/platform/mediastream/RTCDataChannelHandler.h"
-
-namespace WebCore {
-
-PassOwnPtr<RTCDataChannelHandler> RTCDataChannelHandler::create(blink::WebRTCDataChannelHandler* webHandler)
-{
-    return adoptPtr(new RTCDataChannelHandler(webHandler));
-}
-
-RTCDataChannelHandler::RTCDataChannelHandler(blink::WebRTCDataChannelHandler* webHandler)
-    : m_webHandler(adoptPtr(webHandler))
-    , m_client(0)
-{
-}
-
-RTCDataChannelHandler::~RTCDataChannelHandler()
-{
-}
-
-void RTCDataChannelHandler::setClient(RTCDataChannelHandlerClient* client)
-{
-    m_client = client;
-    m_webHandler->setClient(m_client ? this : 0);
-}
-
-String RTCDataChannelHandler::label() const
-{
-    return m_webHandler->label();
-}
-
-bool RTCDataChannelHandler::isReliable() const
-{
-    return m_webHandler->isReliable();
-}
-
-bool RTCDataChannelHandler::ordered() const
-{
-    return m_webHandler->ordered();
-}
-
-unsigned short RTCDataChannelHandler::maxRetransmitTime() const
-{
-    return m_webHandler->maxRetransmitTime();
-}
-
-unsigned short RTCDataChannelHandler::maxRetransmits() const
-{
-    return m_webHandler->maxRetransmits();
-}
-
-String RTCDataChannelHandler::protocol() const
-{
-    return m_webHandler->protocol();
-}
-
-bool RTCDataChannelHandler::negotiated() const
-{
-    return m_webHandler->negotiated();
-}
-
-unsigned short RTCDataChannelHandler::id() const
-{
-    return m_webHandler->id();
-}
-
-unsigned long RTCDataChannelHandler::bufferedAmount()
-{
-    return m_webHandler->bufferedAmount();
-}
-
-bool RTCDataChannelHandler::sendStringData(const String& data)
-{
-    return m_webHandler->sendStringData(data);
-}
-
-bool RTCDataChannelHandler::sendRawData(const char* data, size_t size)
-{
-    return m_webHandler->sendRawData(data, size);
-}
-
-void RTCDataChannelHandler::close()
-{
-    m_webHandler->close();
-}
-
-void RTCDataChannelHandler::didChangeReadyState(WebRTCDataChannelHandlerClient::ReadyState state) const
-{
-    if (m_client)
-        m_client->didChangeReadyState(static_cast<RTCDataChannelHandlerClient::ReadyState>(state));
-}
-
-void RTCDataChannelHandler::didReceiveStringData(const blink::WebString& data) const
-{
-    if (m_client)
-        m_client->didReceiveStringData(data);
-}
-
-void RTCDataChannelHandler::didReceiveRawData(const char* data, size_t size) const
-{
-    if (m_client)
-        m_client->didReceiveRawData(data, size);
-}
-
-void RTCDataChannelHandler::didDetectError() const
-{
-    if (m_client)
-        m_client->didDetectError();
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/mediastream/RTCDataChannelHandler.h b/Source/core/platform/mediastream/RTCDataChannelHandler.h
deleted file mode 100644
index d860dad..0000000
--- a/Source/core/platform/mediastream/RTCDataChannelHandler.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-#ifndef RTCDataChannelHandler_h
-#define RTCDataChannelHandler_h
-
-#include "core/platform/mediastream/RTCDataChannelHandlerClient.h"
-#include "public/platform/WebRTCDataChannelHandler.h"
-#include "public/platform/WebRTCDataChannelHandlerClient.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class RTCDataChannelHandlerClient;
-
-class RTCDataChannelHandler : public blink::WebRTCDataChannelHandlerClient {
-public:
-    static PassOwnPtr<RTCDataChannelHandler> create(blink::WebRTCDataChannelHandler*);
-    virtual ~RTCDataChannelHandler();
-
-    void setClient(RTCDataChannelHandlerClient*);
-
-    String label() const;
-
-    // DEPRECATED
-    bool isReliable() const;
-
-    bool ordered() const;
-    unsigned short maxRetransmitTime() const;
-    unsigned short maxRetransmits() const;
-    String protocol() const;
-    bool negotiated() const;
-    unsigned short id() const;
-
-    unsigned long bufferedAmount();
-    bool sendStringData(const String&);
-    bool sendRawData(const char*, size_t);
-    void close();
-
-    // blink::WebRTCDataChannelHandlerClient implementation.
-    virtual void didChangeReadyState(ReadyState) const OVERRIDE;
-    virtual void didReceiveStringData(const blink::WebString&) const OVERRIDE;
-    virtual void didReceiveRawData(const char*, size_t) const OVERRIDE;
-    virtual void didDetectError() const OVERRIDE;
-
-private:
-    explicit RTCDataChannelHandler(blink::WebRTCDataChannelHandler*);
-
-    OwnPtr<blink::WebRTCDataChannelHandler> m_webHandler;
-    RTCDataChannelHandlerClient* m_client;
-};
-
-} // namespace WebCore
-
-#endif // RTCDataChannelHandler_h
diff --git a/Source/core/platform/mediastream/RTCDataChannelHandlerClient.h b/Source/core/platform/mediastream/RTCDataChannelHandlerClient.h
deleted file mode 100644
index ceaf13c..0000000
--- a/Source/core/platform/mediastream/RTCDataChannelHandlerClient.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-#ifndef RTCDataChannelHandlerClient_h
-#define RTCDataChannelHandlerClient_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class RTCDataChannelHandlerClient {
-public:
-    enum ReadyState {
-        ReadyStateConnecting = 0,
-        ReadyStateOpen = 1,
-        ReadyStateClosing = 2,
-        ReadyStateClosed = 3,
-    };
-
-    virtual ~RTCDataChannelHandlerClient() { }
-
-    virtual void didChangeReadyState(ReadyState) = 0;
-    virtual void didReceiveStringData(const String&) = 0;
-    virtual void didReceiveRawData(const char*, size_t) = 0;
-    virtual void didDetectError() = 0;
-};
-
-} // namespace WebCore
-
-#endif // RTCDataChannelHandlerClient_h
diff --git a/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp b/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
deleted file mode 100644
index b27cabb..0000000
--- a/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/platform/mediastream/RTCPeerConnectionHandler.h"
-
-#include "core/platform/mediastream/RTCDataChannelHandler.h"
-#include "core/platform/mediastream/RTCPeerConnectionHandlerClient.h"
-#include "core/platform/mediastream/RTCStatsRequest.h"
-#include "platform/mediastream/MediaConstraints.h"
-#include "platform/mediastream/MediaStreamComponent.h"
-#include "platform/mediastream/RTCConfiguration.h"
-#include "platform/mediastream/RTCDTMFSenderHandler.h"
-#include "platform/mediastream/RTCSessionDescriptionRequest.h"
-#include "platform/mediastream/RTCVoidRequest.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebMediaConstraints.h"
-#include "public/platform/WebMediaStream.h"
-#include "public/platform/WebMediaStreamTrack.h"
-#include "public/platform/WebRTCConfiguration.h"
-#include "public/platform/WebRTCDTMFSenderHandler.h"
-#include "public/platform/WebRTCDataChannelHandler.h"
-#include "public/platform/WebRTCICECandidate.h"
-#include "public/platform/WebRTCSessionDescription.h"
-#include "public/platform/WebRTCSessionDescriptionRequest.h"
-#include "public/platform/WebRTCStatsRequest.h"
-#include "public/platform/WebRTCVoidRequest.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-blink::WebRTCPeerConnectionHandler* RTCPeerConnectionHandler::toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler* handler)
-{
-    return static_cast<RTCPeerConnectionHandler*>(handler)->m_webHandler.get();
-}
-
-PassOwnPtr<RTCPeerConnectionHandler> RTCPeerConnectionHandler::create(RTCPeerConnectionHandlerClient* client)
-{
-    ASSERT(client);
-    OwnPtr<RTCPeerConnectionHandler> handler = adoptPtr(new RTCPeerConnectionHandler(client));
-
-    if (!handler->createWebHandler())
-        return nullptr;
-
-    return handler.release();
-}
-
-RTCPeerConnectionHandler::RTCPeerConnectionHandler(RTCPeerConnectionHandlerClient* client)
-    : m_client(client)
-{
-}
-
-RTCPeerConnectionHandler::~RTCPeerConnectionHandler()
-{
-}
-
-bool RTCPeerConnectionHandler::createWebHandler()
-{
-    m_webHandler = adoptPtr(blink::Platform::current()->createRTCPeerConnectionHandler(this));
-    return m_webHandler;
-}
-
-bool RTCPeerConnectionHandler::initialize(PassRefPtr<RTCConfiguration> configuration, PassRefPtr<MediaConstraints> constraints)
-{
-    return m_webHandler->initialize(configuration, constraints);
-}
-
-void RTCPeerConnectionHandler::createOffer(PassRefPtr<RTCSessionDescriptionRequest> request, PassRefPtr<MediaConstraints> constraints)
-{
-    m_webHandler->createOffer(request, constraints);
-}
-
-void RTCPeerConnectionHandler::createAnswer(PassRefPtr<RTCSessionDescriptionRequest> request, PassRefPtr<MediaConstraints> constraints)
-{
-    m_webHandler->createAnswer(request, constraints);
-}
-
-void RTCPeerConnectionHandler::setLocalDescription(PassRefPtr<RTCVoidRequest> request, blink::WebRTCSessionDescription sessionDescription)
-{
-    m_webHandler->setLocalDescription(request, sessionDescription);
-}
-
-void RTCPeerConnectionHandler::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, blink::WebRTCSessionDescription sessionDescription)
-{
-    m_webHandler->setRemoteDescription(request, sessionDescription);
-}
-
-bool RTCPeerConnectionHandler::updateIce(PassRefPtr<RTCConfiguration> configuration, PassRefPtr<MediaConstraints> constraints)
-{
-    return m_webHandler->updateICE(configuration, constraints);
-}
-
-bool RTCPeerConnectionHandler::addIceCandidate(blink::WebRTCICECandidate iceCandidate)
-{
-    return m_webHandler->addICECandidate(iceCandidate);
-}
-
-bool RTCPeerConnectionHandler::addIceCandidate(PassRefPtr<RTCVoidRequest> request, blink::WebRTCICECandidate iceCandidate)
-{
-    return m_webHandler->addICECandidate(request, iceCandidate);
-}
-
-blink::WebRTCSessionDescription RTCPeerConnectionHandler::localDescription()
-{
-    return m_webHandler->localDescription();
-}
-
-blink::WebRTCSessionDescription RTCPeerConnectionHandler::remoteDescription()
-{
-    return m_webHandler->remoteDescription();
-}
-
-bool RTCPeerConnectionHandler::addStream(PassRefPtr<MediaStreamDescriptor> mediaStream, PassRefPtr<MediaConstraints> constraints)
-{
-    return m_webHandler->addStream(mediaStream, constraints);
-}
-
-void RTCPeerConnectionHandler::removeStream(PassRefPtr<MediaStreamDescriptor> mediaStream)
-{
-    m_webHandler->removeStream(mediaStream);
-}
-
-void RTCPeerConnectionHandler::getStats(PassRefPtr<RTCStatsRequest> request)
-{
-    m_webHandler->getStats(request);
-}
-
-PassOwnPtr<RTCDataChannelHandler> RTCPeerConnectionHandler::createDataChannel(const String& label, const blink::WebRTCDataChannelInit& init)
-{
-    blink::WebRTCDataChannelHandler* webHandler = m_webHandler->createDataChannel(label, init);
-    if (!webHandler)
-        return nullptr;
-
-    return RTCDataChannelHandler::create(webHandler);
-}
-
-PassOwnPtr<RTCDTMFSenderHandler> RTCPeerConnectionHandler::createDTMFSender(PassRefPtr<MediaStreamComponent> track)
-{
-    blink::WebRTCDTMFSenderHandler* webHandler = m_webHandler->createDTMFSender(track);
-    if (!webHandler)
-        return nullptr;
-
-    return RTCDTMFSenderHandler::create(webHandler);
-}
-
-void RTCPeerConnectionHandler::stop()
-{
-    m_webHandler->stop();
-}
-
-void RTCPeerConnectionHandler::negotiationNeeded()
-{
-    m_client->negotiationNeeded();
-}
-
-void RTCPeerConnectionHandler::didGenerateICECandidate(const blink::WebRTCICECandidate& iceCandidate)
-{
-    m_client->didGenerateIceCandidate(iceCandidate);
-}
-
-void RTCPeerConnectionHandler::didChangeSignalingState(blink::WebRTCPeerConnectionHandlerClient::SignalingState state)
-{
-    m_client->didChangeSignalingState(static_cast<RTCPeerConnectionHandlerClient::SignalingState>(state));
-}
-
-void RTCPeerConnectionHandler::didChangeICEGatheringState(blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState state)
-{
-    m_client->didChangeIceGatheringState(static_cast<RTCPeerConnectionHandlerClient::IceGatheringState>(state));
-}
-
-void RTCPeerConnectionHandler::didChangeICEConnectionState(blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState state)
-{
-    m_client->didChangeIceConnectionState(static_cast<RTCPeerConnectionHandlerClient::IceConnectionState>(state));
-}
-
-void RTCPeerConnectionHandler::didAddRemoteStream(const blink::WebMediaStream& webMediaStreamDescriptor)
-{
-    m_client->didAddRemoteStream(webMediaStreamDescriptor);
-}
-
-void RTCPeerConnectionHandler::didRemoveRemoteStream(const blink::WebMediaStream& webMediaStreamDescriptor)
-{
-    m_client->didRemoveRemoteStream(webMediaStreamDescriptor);
-}
-
-void RTCPeerConnectionHandler::didAddRemoteDataChannel(blink::WebRTCDataChannelHandler* webHandler)
-{
-    ASSERT(webHandler);
-    m_client->didAddRemoteDataChannel(RTCDataChannelHandler::create(webHandler));
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/mediastream/RTCPeerConnectionHandler.h b/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
deleted file mode 100644
index 9510a60..0000000
--- a/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef RTCPeerConnectionHandler_h
-#define RTCPeerConnectionHandler_h
-
-#include "core/platform/mediastream/MediaStreamDescriptor.h"
-#include "public/platform/WebRTCPeerConnectionHandler.h"
-#include "public/platform/WebRTCPeerConnectionHandlerClient.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassRefPtr.h"
-
-namespace blink {
-class WebMediaStream;
-class WebRTCICECandidate;
-class WebRTCSessionDescription;
-struct WebRTCDataChannelInit;
-}
-
-namespace WebCore {
-
-class MediaConstraints;
-class MediaStreamComponent;
-class RTCConfiguration;
-class RTCDTMFSenderHandler;
-class RTCDataChannelHandler;
-class RTCPeerConnectionHandlerClient;
-class RTCSessionDescriptionRequest;
-class RTCStatsRequest;
-class RTCVoidRequest;
-
-class RTCPeerConnectionHandler : public blink::WebRTCPeerConnectionHandlerClient {
-public:
-    static PassOwnPtr<RTCPeerConnectionHandler> create(RTCPeerConnectionHandlerClient*);
-    virtual ~RTCPeerConnectionHandler();
-
-    bool createWebHandler();
-
-    bool initialize(PassRefPtr<RTCConfiguration>, PassRefPtr<MediaConstraints>);
-
-    void createOffer(PassRefPtr<RTCSessionDescriptionRequest>, PassRefPtr<MediaConstraints>);
-    void createAnswer(PassRefPtr<RTCSessionDescriptionRequest>, PassRefPtr<MediaConstraints>);
-    void setLocalDescription(PassRefPtr<RTCVoidRequest>, blink::WebRTCSessionDescription);
-    void setRemoteDescription(PassRefPtr<RTCVoidRequest>, blink::WebRTCSessionDescription);
-    blink::WebRTCSessionDescription localDescription();
-    blink::WebRTCSessionDescription remoteDescription();
-    bool updateIce(PassRefPtr<RTCConfiguration>, PassRefPtr<MediaConstraints>);
-
-    // DEPRECATED
-    bool addIceCandidate(blink::WebRTCICECandidate);
-
-    bool addIceCandidate(PassRefPtr<RTCVoidRequest>, blink::WebRTCICECandidate);
-    bool addStream(PassRefPtr<MediaStreamDescriptor>, PassRefPtr<MediaConstraints>);
-    void removeStream(PassRefPtr<MediaStreamDescriptor>);
-    void getStats(PassRefPtr<RTCStatsRequest>);
-    PassOwnPtr<RTCDataChannelHandler> createDataChannel(const String& label, const blink::WebRTCDataChannelInit&);
-    PassOwnPtr<RTCDTMFSenderHandler> createDTMFSender(PassRefPtr<MediaStreamComponent>);
-    void stop();
-
-    // blink::WebRTCPeerConnectionHandlerClient implementation.
-    virtual void negotiationNeeded() OVERRIDE;
-    virtual void didGenerateICECandidate(const blink::WebRTCICECandidate&) OVERRIDE;
-    virtual void didChangeSignalingState(blink::WebRTCPeerConnectionHandlerClient::SignalingState) OVERRIDE;
-    virtual void didChangeICEGatheringState(blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState) OVERRIDE;
-    virtual void didChangeICEConnectionState(blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState) OVERRIDE;
-    virtual void didAddRemoteStream(const blink::WebMediaStream&) OVERRIDE;
-    virtual void didRemoveRemoteStream(const blink::WebMediaStream&) OVERRIDE;
-    virtual void didAddRemoteDataChannel(blink::WebRTCDataChannelHandler*) OVERRIDE;
-
-    static blink::WebRTCPeerConnectionHandler* toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler*);
-
-private:
-    explicit RTCPeerConnectionHandler(RTCPeerConnectionHandlerClient*);
-
-    OwnPtr<blink::WebRTCPeerConnectionHandler> m_webHandler;
-    RTCPeerConnectionHandlerClient* m_client;
-};
-
-} // namespace WebCore
-
-#endif // RTCPeerConnectionHandler_h
diff --git a/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h b/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h
deleted file mode 100644
index 46f276f..0000000
--- a/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2012 Google AB. 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.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef RTCPeerConnectionHandlerClient_h
-#define RTCPeerConnectionHandlerClient_h
-
-#include "wtf/PassRefPtr.h"
-
-namespace blink {
-class WebRTCICECandidate;
-}
-
-namespace WebCore {
-
-class MediaStreamDescriptor;
-class RTCDataChannelHandler;
-
-class RTCPeerConnectionHandlerClient {
-public:
-    enum SignalingState {
-        SignalingStateStable = 1,
-        SignalingStateHaveLocalOffer = 2,
-        SignalingStateHaveRemoteOffer = 3,
-        SignalingStateHaveLocalPrAnswer = 4,
-        SignalingStateHaveRemotePrAnswer = 5,
-        SignalingStateClosed = 6,
-    };
-
-    enum IceConnectionState {
-        IceConnectionStateNew = 1,
-        IceConnectionStateChecking = 2,
-        IceConnectionStateConnected = 3,
-        IceConnectionStateCompleted = 4,
-        IceConnectionStateFailed = 5,
-        IceConnectionStateDisconnected = 6,
-        IceConnectionStateClosed = 7
-    };
-
-    enum IceGatheringState {
-        IceGatheringStateNew = 1,
-        IceGatheringStateGathering = 2,
-        IceGatheringStateComplete = 3
-    };
-
-    virtual ~RTCPeerConnectionHandlerClient() { }
-
-    virtual void negotiationNeeded() = 0;
-    virtual void didGenerateIceCandidate(blink::WebRTCICECandidate) = 0;
-    virtual void didChangeSignalingState(SignalingState) = 0;
-    virtual void didChangeIceGatheringState(IceGatheringState) = 0;
-    virtual void didChangeIceConnectionState(IceConnectionState) = 0;
-    virtual void didAddRemoteStream(PassRefPtr<MediaStreamDescriptor>) = 0;
-    virtual void didRemoveRemoteStream(MediaStreamDescriptor*) = 0;
-    virtual void didAddRemoteDataChannel(PassOwnPtr<RTCDataChannelHandler>) = 0;
-};
-
-} // namespace WebCore
-
-#endif // RTCPeerConnectionHandlerClient_h
diff --git a/Source/core/platform/mediastream/RTCStatsRequest.h b/Source/core/platform/mediastream/RTCStatsRequest.h
deleted file mode 100644
index 5f93fe0..0000000
--- a/Source/core/platform/mediastream/RTCStatsRequest.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. 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.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef RTCStatsRequest_h
-#define RTCStatsRequest_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class MediaStreamComponent;
-class MediaStreamDescriptor;
-class RTCStatsResponseBase;
-
-class RTCStatsRequest : public RefCounted<RTCStatsRequest> {
-public:
-    virtual ~RTCStatsRequest() { }
-
-    virtual PassRefPtr<RTCStatsResponseBase> createResponse() = 0;
-    virtual bool hasSelector() = 0;
-    virtual MediaStreamDescriptor* stream() = 0;
-    virtual MediaStreamComponent* component() = 0;
-    virtual void requestSucceeded(PassRefPtr<RTCStatsResponseBase>) = 0;
-
-protected:
-    RTCStatsRequest() { }
-};
-
-} // namespace WebCore
-
-#endif // RTCStatsRequest_h
diff --git a/Source/core/platform/mock/GeolocationClientMock.cpp b/Source/core/platform/mock/GeolocationClientMock.cpp
deleted file mode 100644
index 8b0be67..0000000
--- a/Source/core/platform/mock/GeolocationClientMock.cpp
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * Copyright (C) 2012 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#include "config.h"
-#include "core/platform/mock/GeolocationClientMock.h"
-
-#include "modules/geolocation/GeolocationController.h"
-#include "modules/geolocation/GeolocationError.h"
-#include "modules/geolocation/GeolocationPosition.h"
-
-namespace WebCore {
-
-GeolocationClientMock::GeolocationClientMock()
-    : m_controller(0)
-    , m_hasError(false)
-    , m_controllerTimer(this, &GeolocationClientMock::controllerTimerFired)
-    , m_permissionTimer(this, &GeolocationClientMock::permissionTimerFired)
-    , m_isActive(false)
-    , m_permissionState(PermissionStateUnset)
-{
-}
-
-GeolocationClientMock::~GeolocationClientMock()
-{
-    ASSERT(!m_isActive);
-}
-
-void GeolocationClientMock::setController(GeolocationController *controller)
-{
-    ASSERT(controller && !m_controller);
-    m_controller = controller;
-}
-
-void GeolocationClientMock::setPosition(PassRefPtr<GeolocationPosition> position)
-{
-    m_lastPosition = position;
-    clearError();
-    asyncUpdateController();
-}
-
-void GeolocationClientMock::setPositionUnavailableError(const String& errorMessage)
-{
-    m_hasError = true;
-    m_errorMessage = errorMessage;
-    m_lastPosition = nullptr;
-    asyncUpdateController();
-}
-
-void GeolocationClientMock::setPermission(bool allowed)
-{
-    m_permissionState = allowed ? PermissionStateAllowed : PermissionStateDenied;
-    asyncUpdatePermission();
-}
-
-int GeolocationClientMock::numberOfPendingPermissionRequests() const
-{
-    return m_pendingPermission.size();
-}
-
-void GeolocationClientMock::requestPermission(Geolocation* geolocation)
-{
-    m_pendingPermission.add(geolocation);
-    if (m_permissionState != PermissionStateUnset)
-        asyncUpdatePermission();
-}
-
-void GeolocationClientMock::cancelPermissionRequest(Geolocation* geolocation)
-{
-    // Called from Geolocation::disconnectFrame() in response to Frame destruction.
-    m_pendingPermission.remove(geolocation);
-    if (m_pendingPermission.isEmpty() && m_permissionTimer.isActive())
-        m_permissionTimer.stop();
-}
-
-void GeolocationClientMock::asyncUpdatePermission()
-{
-    ASSERT(m_permissionState != PermissionStateUnset);
-    if (!m_permissionTimer.isActive())
-        m_permissionTimer.startOneShot(0);
-}
-
-void GeolocationClientMock::permissionTimerFired(WebCore::Timer<GeolocationClientMock>* timer)
-{
-    ASSERT_UNUSED(timer, timer == &m_permissionTimer);
-    ASSERT(m_permissionState != PermissionStateUnset);
-    bool allowed = m_permissionState == PermissionStateAllowed;
-    GeolocationSet::iterator end = m_pendingPermission.end();
-
-    // Once permission has been set (or denied) on a Geolocation object, there can be
-    // no further requests for permission to the mock. Consequently the callbacks
-    // which fire synchronously from Geolocation::setIsAllowed() cannot reentrantly modify
-    // m_pendingPermission.
-    for (GeolocationSet::iterator it = m_pendingPermission.begin(); it != end; ++it)
-        (*it)->setIsAllowed(allowed);
-    m_pendingPermission.clear();
-}
-
-void GeolocationClientMock::reset()
-{
-    m_lastPosition = 0;
-    clearError();
-    m_permissionState = PermissionStateUnset;
-}
-
-void GeolocationClientMock::geolocationDestroyed()
-{
-    ASSERT(!m_isActive);
-}
-
-void GeolocationClientMock::startUpdating()
-{
-    ASSERT(!m_isActive);
-    m_isActive = true;
-    asyncUpdateController();
-}
-
-void GeolocationClientMock::stopUpdating()
-{
-    ASSERT(m_isActive);
-    m_isActive = false;
-    m_controllerTimer.stop();
-}
-
-void GeolocationClientMock::setEnableHighAccuracy(bool)
-{
-    // FIXME: We need to add some tests regarding "high accuracy" mode.
-    // See https://bugs.webkit.org/show_bug.cgi?id=49438
-}
-
-GeolocationPosition* GeolocationClientMock::lastPosition()
-{
-    return m_lastPosition.get();
-}
-
-void GeolocationClientMock::asyncUpdateController()
-{
-    ASSERT(m_controller);
-    if (m_isActive && !m_controllerTimer.isActive())
-        m_controllerTimer.startOneShot(0);
-}
-
-void GeolocationClientMock::controllerTimerFired(Timer<GeolocationClientMock>* timer)
-{
-    ASSERT_UNUSED(timer, timer == &m_controllerTimer);
-    ASSERT(m_controller);
-
-    if (m_lastPosition.get()) {
-        ASSERT(!m_hasError);
-        m_controller->positionChanged(m_lastPosition.get());
-    } else if (m_hasError) {
-        RefPtr<GeolocationError> geolocatioError = GeolocationError::create(GeolocationError::PositionUnavailable, m_errorMessage);
-        m_controller->errorOccurred(geolocatioError.get());
-    }
-}
-
-void GeolocationClientMock::clearError()
-{
-    m_hasError = false;
-    m_errorMessage = String();
-}
-
-} // WebCore
diff --git a/Source/core/platform/mock/GeolocationClientMock.h b/Source/core/platform/mock/GeolocationClientMock.h
deleted file mode 100644
index 884184d..0000000
--- a/Source/core/platform/mock/GeolocationClientMock.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * Copyright (C) 2012 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-#ifndef GeolocationClientMock_h
-#define GeolocationClientMock_h
-
-#include "modules/geolocation/GeolocationClient.h"
-#include "platform/Timer.h"
-#include "wtf/HashSet.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class GeolocationController;
-class GeolocationPosition;
-
-// FIXME: this should not be in WebCore. It should be moved to WebKit.
-// Provides a mock object for the geolocation client.
-class GeolocationClientMock : public GeolocationClient {
-public:
-    GeolocationClientMock();
-    virtual ~GeolocationClientMock();
-
-    void reset();
-    void setController(GeolocationController*);
-
-    void setPosition(PassRefPtr<GeolocationPosition>);
-    void setPositionUnavailableError(const String& errorMessage);
-    void setPermission(bool allowed);
-    int numberOfPendingPermissionRequests() const;
-
-    // GeolocationClient
-    virtual void geolocationDestroyed() OVERRIDE;
-    virtual void startUpdating() OVERRIDE;
-    virtual void stopUpdating() OVERRIDE;
-    virtual void setEnableHighAccuracy(bool) OVERRIDE;
-    virtual GeolocationPosition* lastPosition() OVERRIDE;
-    virtual void requestPermission(Geolocation*) OVERRIDE;
-    virtual void cancelPermissionRequest(Geolocation*) OVERRIDE;
-
-private:
-    void asyncUpdateController();
-    void controllerTimerFired(Timer<GeolocationClientMock>*);
-
-    void asyncUpdatePermission();
-    void permissionTimerFired(Timer<GeolocationClientMock>*);
-
-    void clearError();
-
-    GeolocationController* m_controller;
-    RefPtr<GeolocationPosition> m_lastPosition;
-    bool m_hasError;
-    String m_errorMessage;
-    Timer<GeolocationClientMock> m_controllerTimer;
-    Timer<GeolocationClientMock> m_permissionTimer;
-    bool m_isActive;
-
-    enum PermissionState {
-        PermissionStateUnset,
-        PermissionStateAllowed,
-        PermissionStateDenied,
-    } m_permissionState;
-    typedef WTF::HashSet<RefPtr<Geolocation> > GeolocationSet;
-    GeolocationSet m_pendingPermission;
-};
-
-}
-
-#endif
diff --git a/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp b/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
deleted file mode 100644
index bc0b940..0000000
--- a/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc.  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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-
-#include "core/platform/mock/PlatformSpeechSynthesizerMock.h"
-
-#include "platform/speech/PlatformSpeechSynthesisUtterance.h"
-
-namespace WebCore {
-
-PassOwnPtr<PlatformSpeechSynthesizerMock> PlatformSpeechSynthesizerMock::create(PlatformSpeechSynthesizerClient* client)
-{
-    OwnPtr<PlatformSpeechSynthesizerMock> synthesizer = adoptPtr(new PlatformSpeechSynthesizerMock(client));
-    synthesizer->initializeVoiceList();
-    client->voicesDidChange();
-    return synthesizer.release();
-}
-
-PlatformSpeechSynthesizerMock::PlatformSpeechSynthesizerMock(PlatformSpeechSynthesizerClient* client)
-    : PlatformSpeechSynthesizer(client)
-    , m_speakingFinishedTimer(this, &PlatformSpeechSynthesizerMock::speakingFinished)
-{
-}
-
-PlatformSpeechSynthesizerMock::~PlatformSpeechSynthesizerMock()
-{
-    m_speakingFinishedTimer.stop();
-}
-
-void PlatformSpeechSynthesizerMock::speakingFinished(Timer<PlatformSpeechSynthesizerMock>*)
-{
-    ASSERT(m_utterance.get());
-    client()->didFinishSpeaking(m_utterance);
-    m_utterance = 0;
-}
-
-void PlatformSpeechSynthesizerMock::initializeVoiceList()
-{
-    m_voiceList.clear();
-    m_voiceList.append(PlatformSpeechSynthesisVoice::create(String("mock.voice.bruce"), String("bruce"), String("en-US"), true, true));
-    m_voiceList.append(PlatformSpeechSynthesisVoice::create(String("mock.voice.clark"), String("clark"), String("en-US"), true, false));
-    m_voiceList.append(PlatformSpeechSynthesisVoice::create(String("mock.voice.logan"), String("logan"), String("fr-CA"), true, true));
-}
-
-void PlatformSpeechSynthesizerMock::speak(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
-{
-    ASSERT(!m_utterance);
-    m_utterance = utterance;
-    client()->didStartSpeaking(m_utterance);
-
-    // Fire a fake word and then sentence boundary event.
-    client()->boundaryEventOccurred(m_utterance, SpeechWordBoundary, 0);
-    client()->boundaryEventOccurred(m_utterance, SpeechSentenceBoundary, m_utterance->text().length());
-
-    // Give the fake speech job some time so that pause and other functions have time to be called.
-    m_speakingFinishedTimer.startOneShot(.1);
-}
-
-void PlatformSpeechSynthesizerMock::cancel()
-{
-    if (!m_utterance)
-        return;
-
-    m_speakingFinishedTimer.stop();
-    client()->speakingErrorOccurred(m_utterance);
-    m_utterance = 0;
-}
-
-void PlatformSpeechSynthesizerMock::pause()
-{
-    client()->didPauseSpeaking(m_utterance);
-}
-
-void PlatformSpeechSynthesizerMock::resume()
-{
-    client()->didResumeSpeaking(m_utterance);
-}
-
-
-} // namespace WebCore
diff --git a/Source/core/platform/mock/PlatformSpeechSynthesizerMock.h b/Source/core/platform/mock/PlatformSpeechSynthesizerMock.h
deleted file mode 100644
index 3378c83..0000000
--- a/Source/core/platform/mock/PlatformSpeechSynthesizerMock.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc.  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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef PlatformSpeechSynthesizerMock_h
-#define PlatformSpeechSynthesizerMock_h
-
-#include "platform/Timer.h"
-#include "platform/speech/PlatformSpeechSynthesizer.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class PlatformSpeechSynthesizerMock : public PlatformSpeechSynthesizer {
-public:
-    static PassOwnPtr<PlatformSpeechSynthesizerMock> create(PlatformSpeechSynthesizerClient*);
-
-    virtual ~PlatformSpeechSynthesizerMock();
-    virtual void speak(PassRefPtr<PlatformSpeechSynthesisUtterance>);
-    virtual void pause();
-    virtual void resume();
-    virtual void cancel();
-
-private:
-    explicit PlatformSpeechSynthesizerMock(PlatformSpeechSynthesizerClient*);
-    virtual void initializeVoiceList();
-    void speakingFinished(Timer<PlatformSpeechSynthesizerMock>*);
-
-    Timer<PlatformSpeechSynthesizerMock> m_speakingFinishedTimer;
-    RefPtr<PlatformSpeechSynthesisUtterance> m_utterance;
-};
-
-} // namespace WebCore
-
-#endif // PlatformSpeechSynthesizer_h
diff --git a/Source/core/plugins/DOMMimeType.cpp b/Source/core/plugins/DOMMimeType.cpp
index 3e35097..84b08e7 100644
--- a/Source/core/plugins/DOMMimeType.cpp
+++ b/Source/core/plugins/DOMMimeType.cpp
@@ -27,6 +27,8 @@
 
 namespace WebCore {
 
+DEFINE_GC_INFO(DOMMimeType);
+
 DOMMimeType::DOMMimeType(PassRefPtr<PluginData> pluginData, Frame* frame, unsigned index)
     : FrameDestructionObserver(frame)
     , m_pluginData(pluginData)
@@ -62,8 +64,11 @@
     return mimeClassInfo().desc;
 }
 
-PassRefPtr<DOMPlugin> DOMMimeType::enabledPlugin() const
+PassRefPtrWillBeRawPtr<DOMPlugin> DOMMimeType::enabledPlugin() const
 {
+    // FIXME: allowPlugins is just a client call. We should not need
+    // to bounce through the page or mainframe or loader to get there.
+    // Something like: m_frame->host()->client()->allowPlugins().
     if (!m_frame || !m_frame->page() || !m_frame->page()->mainFrame()->loader().allowPlugins(NotAboutToInstantiatePlugin))
         return 0;
 
diff --git a/Source/core/plugins/DOMMimeType.h b/Source/core/plugins/DOMMimeType.h
index 8670725..e0401be 100644
--- a/Source/core/plugins/DOMMimeType.h
+++ b/Source/core/plugins/DOMMimeType.h
@@ -22,6 +22,7 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/frame/FrameDestructionObserver.h"
+#include "heap/Handle.h"
 #include "platform/plugins/PluginData.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
@@ -33,15 +34,21 @@
 class DOMPlugin;
 class Frame;
 
-class DOMMimeType : public RefCounted<DOMMimeType>, public ScriptWrappable, public FrameDestructionObserver {
+class DOMMimeType FINAL : public RefCountedWillBeGarbageCollectedFinalized<DOMMimeType>, public ScriptWrappable, public FrameDestructionObserver {
+    DECLARE_GC_INFO;
 public:
-    static PassRefPtr<DOMMimeType> create(PassRefPtr<PluginData> pluginData, Frame* frame, unsigned index) { return adoptRef(new DOMMimeType(pluginData, frame, index)); }
-    ~DOMMimeType();
+    static PassRefPtrWillBeRawPtr<DOMMimeType> create(PassRefPtr<PluginData> pluginData, Frame* frame, unsigned index)
+    {
+        return adoptRefWillBeNoop(new DOMMimeType(pluginData, frame, index));
+    }
+    virtual ~DOMMimeType();
 
-    const String &type() const;
+    const String& type() const;
     String suffixes() const;
-    const String &description() const;
-    PassRefPtr<DOMPlugin> enabledPlugin() const;
+    const String& description() const;
+    PassRefPtrWillBeRawPtr<DOMPlugin> enabledPlugin() const;
+
+    void trace(Visitor*) { }
 
 private:
     const MimeClassInfo& mimeClassInfo() const { return m_pluginData->mimes()[m_index]; }
diff --git a/Source/core/plugins/DOMMimeTypeArray.cpp b/Source/core/plugins/DOMMimeTypeArray.cpp
index cddfa83..e2f948b 100644
--- a/Source/core/plugins/DOMMimeTypeArray.cpp
+++ b/Source/core/plugins/DOMMimeTypeArray.cpp
@@ -27,6 +27,8 @@
 
 namespace WebCore {
 
+DEFINE_GC_INFO(DOMMimeTypeArray);
+
 DOMMimeTypeArray::DOMMimeTypeArray(Frame* frame)
     : DOMWindowProperty(frame)
 {
@@ -45,7 +47,7 @@
     return data->mimes().size();
 }
 
-PassRefPtr<DOMMimeType> DOMMimeTypeArray::item(unsigned index)
+PassRefPtrWillBeRawPtr<DOMMimeType> DOMMimeTypeArray::item(unsigned index)
 {
     PluginData* data = getPluginData();
     if (!data)
@@ -69,7 +71,7 @@
     return false;
 }
 
-PassRefPtr<DOMMimeType> DOMMimeTypeArray::namedItem(const AtomicString& propertyName)
+PassRefPtrWillBeRawPtr<DOMMimeType> DOMMimeTypeArray::namedItem(const AtomicString& propertyName)
 {
     PluginData *data = getPluginData();
     if (!data)
diff --git a/Source/core/plugins/DOMMimeTypeArray.h b/Source/core/plugins/DOMMimeTypeArray.h
index 651edee..e65562b 100644
--- a/Source/core/plugins/DOMMimeTypeArray.h
+++ b/Source/core/plugins/DOMMimeTypeArray.h
@@ -24,6 +24,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/frame/DOMWindowProperty.h"
 #include "core/plugins/DOMMimeType.h"
+#include "heap/Handle.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
@@ -34,15 +35,21 @@
 class Frame;
 class PluginData;
 
-class DOMMimeTypeArray : public ScriptWrappable, public RefCounted<DOMMimeTypeArray>, public DOMWindowProperty {
+class DOMMimeTypeArray FINAL : public RefCountedWillBeGarbageCollectedFinalized<DOMMimeTypeArray>, public ScriptWrappable, public DOMWindowProperty {
+    DECLARE_GC_INFO;
 public:
-    static PassRefPtr<DOMMimeTypeArray> create(Frame* frame) { return adoptRef(new DOMMimeTypeArray(frame)); }
-    ~DOMMimeTypeArray();
+    static PassRefPtrWillBeRawPtr<DOMMimeTypeArray> create(Frame* frame)
+    {
+        return adoptRefWillBeNoop(new DOMMimeTypeArray(frame));
+    }
+    virtual ~DOMMimeTypeArray();
 
     unsigned length() const;
-    PassRefPtr<DOMMimeType> item(unsigned index);
+    PassRefPtrWillBeRawPtr<DOMMimeType> item(unsigned index);
     bool canGetItemsForName(const AtomicString& propertyName);
-    PassRefPtr<DOMMimeType> namedItem(const AtomicString& propertyName);
+    PassRefPtrWillBeRawPtr<DOMMimeType> namedItem(const AtomicString& propertyName);
+
+    void trace(Visitor*) { }
 
 private:
     explicit DOMMimeTypeArray(Frame*);
diff --git a/Source/core/plugins/DOMPlugin.cpp b/Source/core/plugins/DOMPlugin.cpp
index eb4b99c..67492d6 100644
--- a/Source/core/plugins/DOMPlugin.cpp
+++ b/Source/core/plugins/DOMPlugin.cpp
@@ -24,6 +24,8 @@
 
 namespace WebCore {
 
+DEFINE_GC_INFO(DOMPlugin);
+
 DOMPlugin::DOMPlugin(PluginData* pluginData, Frame* frame, unsigned index)
     : FrameDestructionObserver(frame)
     , m_pluginData(pluginData)
@@ -56,7 +58,7 @@
     return pluginInfo().mimes.size();
 }
 
-PassRefPtr<DOMMimeType> DOMPlugin::item(unsigned index)
+PassRefPtrWillBeRawPtr<DOMMimeType> DOMPlugin::item(unsigned index)
 {
     if (index >= pluginInfo().mimes.size())
         return 0;
@@ -80,7 +82,7 @@
     return false;
 }
 
-PassRefPtr<DOMMimeType> DOMPlugin::namedItem(const AtomicString& propertyName)
+PassRefPtrWillBeRawPtr<DOMMimeType> DOMPlugin::namedItem(const AtomicString& propertyName)
 {
     const Vector<MimeClassInfo>& mimes = m_pluginData->mimes();
     for (unsigned i = 0; i < mimes.size(); ++i)
diff --git a/Source/core/plugins/DOMPlugin.h b/Source/core/plugins/DOMPlugin.h
index 1cc0611..2e96015 100644
--- a/Source/core/plugins/DOMPlugin.h
+++ b/Source/core/plugins/DOMPlugin.h
@@ -23,6 +23,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/frame/FrameDestructionObserver.h"
 #include "core/plugins/DOMMimeType.h"
+#include "heap/Handle.h"
 #include "wtf/Forward.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
@@ -32,10 +33,14 @@
 class Plugin;
 class PluginData;
 
-class DOMPlugin : public ScriptWrappable, public RefCounted<DOMPlugin>, public FrameDestructionObserver {
+class DOMPlugin FINAL : public RefCountedWillBeGarbageCollectedFinalized<DOMPlugin>, public ScriptWrappable, public FrameDestructionObserver {
+    DECLARE_GC_INFO;
 public:
-    static PassRefPtr<DOMPlugin> create(PluginData* pluginData, Frame* frame, unsigned index) { return adoptRef(new DOMPlugin(pluginData, frame, index)); }
-    ~DOMPlugin();
+    static PassRefPtrWillBeRawPtr<DOMPlugin> create(PluginData* pluginData, Frame* frame, unsigned index)
+    {
+        return adoptRefWillBeNoop(new DOMPlugin(pluginData, frame, index));
+    }
+    virtual ~DOMPlugin();
 
     String name() const;
     String filename() const;
@@ -43,9 +48,11 @@
 
     unsigned length() const;
 
-    PassRefPtr<DOMMimeType> item(unsigned index);
+    PassRefPtrWillBeRawPtr<DOMMimeType> item(unsigned index);
     bool canGetItemsForName(const AtomicString& propertyName);
-    PassRefPtr<DOMMimeType> namedItem(const AtomicString& propertyName);
+    PassRefPtrWillBeRawPtr<DOMMimeType> namedItem(const AtomicString& propertyName);
+
+    void trace(Visitor*) { }
 
 private:
     const PluginInfo& pluginInfo() const { return m_pluginData->plugins()[m_index]; }
diff --git a/Source/core/plugins/DOMPluginArray.cpp b/Source/core/plugins/DOMPluginArray.cpp
index bb2b169..d865985 100644
--- a/Source/core/plugins/DOMPluginArray.cpp
+++ b/Source/core/plugins/DOMPluginArray.cpp
@@ -27,6 +27,8 @@
 
 namespace WebCore {
 
+DEFINE_GC_INFO(DOMPluginArray);
+
 DOMPluginArray::DOMPluginArray(Frame* frame)
     : DOMWindowProperty(frame)
 {
@@ -45,7 +47,7 @@
     return data->plugins().size();
 }
 
-PassRefPtr<DOMPlugin> DOMPluginArray::item(unsigned index)
+PassRefPtrWillBeRawPtr<DOMPlugin> DOMPluginArray::item(unsigned index)
 {
     PluginData* data = pluginData();
     if (!data)
@@ -69,7 +71,7 @@
     return false;
 }
 
-PassRefPtr<DOMPlugin> DOMPluginArray::namedItem(const AtomicString& propertyName)
+PassRefPtrWillBeRawPtr<DOMPlugin> DOMPluginArray::namedItem(const AtomicString& propertyName)
 {
     PluginData* data = pluginData();
     if (!data)
diff --git a/Source/core/plugins/DOMPluginArray.h b/Source/core/plugins/DOMPluginArray.h
index 922b777..2ea687a 100644
--- a/Source/core/plugins/DOMPluginArray.h
+++ b/Source/core/plugins/DOMPluginArray.h
@@ -24,6 +24,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/frame/DOMWindowProperty.h"
 #include "core/plugins/DOMPlugin.h"
+#include "heap/Handle.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
@@ -34,18 +35,24 @@
 class Frame;
 class PluginData;
 
-class DOMPluginArray : public ScriptWrappable, public RefCounted<DOMPluginArray>, public DOMWindowProperty {
+class DOMPluginArray FINAL : public RefCountedWillBeGarbageCollected<DOMPluginArray>, public ScriptWrappable, public DOMWindowProperty {
+    DECLARE_GC_INFO;
 public:
-    static PassRefPtr<DOMPluginArray> create(Frame* frame) { return adoptRef(new DOMPluginArray(frame)); }
-    ~DOMPluginArray();
+    static PassRefPtrWillBeRawPtr<DOMPluginArray> create(Frame* frame)
+    {
+        return adoptRefWillBeNoop(new DOMPluginArray(frame));
+    }
+    virtual ~DOMPluginArray();
 
     unsigned length() const;
-    PassRefPtr<DOMPlugin> item(unsigned index);
+    PassRefPtrWillBeRawPtr<DOMPlugin> item(unsigned index);
     bool canGetItemsForName(const AtomicString& propertyName);
-    PassRefPtr<DOMPlugin> namedItem(const AtomicString& propertyName);
+    PassRefPtrWillBeRawPtr<DOMPlugin> namedItem(const AtomicString& propertyName);
 
     void refresh(bool reload);
 
+    void trace(Visitor*) { }
+
 private:
     explicit DOMPluginArray(Frame*);
     PluginData* pluginData() const;
diff --git a/Source/core/plugins/MimeType.idl b/Source/core/plugins/MimeType.idl
index 7af6fc1..26c6cc4 100644
--- a/Source/core/plugins/MimeType.idl
+++ b/Source/core/plugins/MimeType.idl
@@ -19,6 +19,7 @@
 */
 
 [
+    WillBeGarbageCollected,
     ImplementedAs=DOMMimeType
 ] interface MimeType {
     readonly attribute DOMString type;
diff --git a/Source/core/plugins/MimeTypeArray.idl b/Source/core/plugins/MimeTypeArray.idl
index ea11b6b..0a33ada 100644
--- a/Source/core/plugins/MimeTypeArray.idl
+++ b/Source/core/plugins/MimeTypeArray.idl
@@ -19,11 +19,12 @@
 */
 
 [
+    WillBeGarbageCollected,
     ImplementedAs=DOMMimeTypeArray
 ] interface MimeTypeArray {
     readonly attribute unsigned long length;
     getter MimeType item([Default=Undefined] optional unsigned long index);
     MimeType namedItem([Default=Undefined] optional DOMString name);
-    [NotEnumerable, ImplementedAs=namedItem] getter MimeType([Default=Undefined] optional DOMString name);
+    [NotEnumerable, ImplementedAs=namedItem] getter MimeType ([Default=Undefined] optional DOMString name);
 };
 
diff --git a/Source/core/plugins/Plugin.idl b/Source/core/plugins/Plugin.idl
index c1259e1..689df50 100644
--- a/Source/core/plugins/Plugin.idl
+++ b/Source/core/plugins/Plugin.idl
@@ -19,6 +19,7 @@
 */
 
 [
+    WillBeGarbageCollected,
     ImplementedAs=DOMPlugin
 ] interface Plugin {
     readonly attribute DOMString name;
diff --git a/Source/core/plugins/PluginArray.idl b/Source/core/plugins/PluginArray.idl
index 47d9cc2..dc2ab1d 100644
--- a/Source/core/plugins/PluginArray.idl
+++ b/Source/core/plugins/PluginArray.idl
@@ -19,6 +19,7 @@
 */
 
 [
+    WillBeGarbageCollected,
     ImplementedAs=DOMPluginArray
 ] interface PluginArray {
     readonly attribute unsigned long length;
diff --git a/Source/core/plugins/PluginView.h b/Source/core/plugins/PluginView.h
index fd40d40..7020f42 100644
--- a/Source/core/plugins/PluginView.h
+++ b/Source/core/plugins/PluginView.h
@@ -42,7 +42,7 @@
 
 class PluginView : public Widget {
 public:
-    virtual bool isPluginView() const { return true; }
+    virtual bool isPluginView() const OVERRIDE FINAL { return true; }
 
     virtual blink::WebLayer* platformLayer() const { return 0; }
     virtual NPObject* scriptableObject() { return 0; }
@@ -61,20 +61,7 @@
     PluginView() : Widget() { }
 };
 
-inline PluginView* toPluginView(Widget* widget)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isPluginView());
-    return static_cast<PluginView*>(widget);
-}
-
-inline const PluginView* toPluginView(const Widget* widget)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!widget || widget->isPluginView());
-    return static_cast<const PluginView*>(widget);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toPluginView(const PluginView*);
+DEFINE_TYPE_CASTS(PluginView, Widget, widget, widget->isPluginView(), widget.isPluginView());
 
 } // namespace WebCore
 
diff --git a/Source/core/rendering/AutoTableLayout.h b/Source/core/rendering/AutoTableLayout.h
index dfdd985..9336d0f 100644
--- a/Source/core/rendering/AutoTableLayout.h
+++ b/Source/core/rendering/AutoTableLayout.h
@@ -34,7 +34,7 @@
 class AutoTableLayout FINAL : public TableLayout {
 public:
     AutoTableLayout(RenderTable*);
-    ~AutoTableLayout();
+    virtual ~AutoTableLayout();
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth) OVERRIDE;
     virtual void applyPreferredLogicalWidthQuirks(LayoutUnit& minWidth, LayoutUnit& maxWidth) const OVERRIDE;
diff --git a/Source/core/rendering/BidiRun.cpp b/Source/core/rendering/BidiRun.cpp
deleted file mode 100644
index 4af7881..0000000
--- a/Source/core/rendering/BidiRun.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Andrew Wellington (proton@wiretapped.net)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/rendering/BidiRun.h"
-#include "platform/Partitions.h"
-#include "wtf/RefCountedLeakCounter.h"
-
-using namespace WTF;
-
-namespace WebCore {
-
-DEFINE_DEBUG_ONLY_GLOBAL(RefCountedLeakCounter, bidiRunCounter, ("BidiRun"));
-
-void* BidiRun::operator new(size_t sz)
-{
-#ifndef NDEBUG
-    bidiRunCounter.increment();
-#endif
-    return partitionAlloc(Partitions::getRenderingPartition(), sz);
-}
-
-void BidiRun::operator delete(void* ptr)
-{
-#ifndef NDEBUG
-    bidiRunCounter.decrement();
-#endif
-    partitionFree(ptr);
-}
-
-}
diff --git a/Source/core/rendering/BidiRun.h b/Source/core/rendering/BidiRun.h
index 85f8f4a..770101f 100644
--- a/Source/core/rendering/BidiRun.h
+++ b/Source/core/rendering/BidiRun.h
@@ -44,10 +44,6 @@
         m_startsSegment = false;
     }
 
-    // BidiRuns are allocated out of the rendering partition.
-    void* operator new(size_t);
-    void operator delete(void*);
-
     BidiRun* next() { return static_cast<BidiRun*>(m_next); }
     RenderObject* object() { return m_object; }
 
diff --git a/Source/core/rendering/ClipPathOperation.h b/Source/core/rendering/ClipPathOperation.h
index 7d50a10..bf64113 100644
--- a/Source/core/rendering/ClipPathOperation.h
+++ b/Source/core/rendering/ClipPathOperation.h
@@ -63,15 +63,15 @@
     OperationType m_type;
 };
 
-class ReferenceClipPathOperation : public ClipPathOperation {
+class ReferenceClipPathOperation FINAL : public ClipPathOperation {
 public:
-    static PassRefPtr<ReferenceClipPathOperation> create(const String& url, const String& fragment)
+    static PassRefPtr<ReferenceClipPathOperation> create(const String& url, const AtomicString& fragment)
     {
         return adoptRef(new ReferenceClipPathOperation(url, fragment));
     }
 
     const String& url() const { return m_url; }
-    const String& fragment() const { return m_fragment; }
+    const AtomicString& fragment() const { return m_fragment; }
 
 private:
     virtual bool operator==(const ClipPathOperation& o) const OVERRIDE
@@ -79,7 +79,7 @@
         return isSameType(o) && m_url == static_cast<const ReferenceClipPathOperation&>(o).m_url;
     }
 
-    ReferenceClipPathOperation(const String& url, const String& fragment)
+    ReferenceClipPathOperation(const String& url, const AtomicString& fragment)
         : ClipPathOperation(REFERENCE)
         , m_url(url)
         , m_fragment(fragment)
@@ -87,12 +87,12 @@
     }
 
     String m_url;
-    String m_fragment;
+    AtomicString m_fragment;
 };
 
 DEFINE_TYPE_CASTS(ReferenceClipPathOperation, ClipPathOperation, op, op->type() == ClipPathOperation::REFERENCE, op.type() == ClipPathOperation::REFERENCE);
 
-class ShapeClipPathOperation : public ClipPathOperation {
+class ShapeClipPathOperation FINAL : public ClipPathOperation {
 public:
     static PassRefPtr<ShapeClipPathOperation> create(PassRefPtr<BasicShape> shape)
     {
@@ -111,10 +111,7 @@
     }
 
 private:
-    virtual bool operator==(const ClipPathOperation& o) const OVERRIDE
-    {
-        return isSameType(o) && m_shape == static_cast<const ShapeClipPathOperation&>(o).m_shape;
-    }
+    virtual bool operator==(const ClipPathOperation&) const OVERRIDE;
 
     ShapeClipPathOperation(PassRefPtr<BasicShape> shape)
         : ClipPathOperation(SHAPE)
@@ -128,6 +125,11 @@
 
 DEFINE_TYPE_CASTS(ShapeClipPathOperation, ClipPathOperation, op, op->type() == ClipPathOperation::SHAPE, op.type() == ClipPathOperation::SHAPE);
 
+inline bool ShapeClipPathOperation::operator==(const ClipPathOperation& o) const
+{
+    return isSameType(o) && *m_shape == *toShapeClipPathOperation(o).m_shape;
+}
+
 }
 
 #endif // ClipPathOperation_h
diff --git a/Source/core/rendering/ColumnInfo.h b/Source/core/rendering/ColumnInfo.h
index 3972281..c463de3 100644
--- a/Source/core/rendering/ColumnInfo.h
+++ b/Source/core/rendering/ColumnInfo.h
@@ -45,7 +45,6 @@
         , m_forcedBreaks(0)
         , m_maximumDistanceBetweenForcedBreaks(0)
         , m_forcedBreakOffset(0)
-        , m_paginationUnit(Column)
     {
     }
 
@@ -98,10 +97,6 @@
         m_forcedBreakOffset = offsetFromFirstPage;
     }
 
-    enum PaginationUnit { Column, Page };
-    PaginationUnit paginationUnit() const { return m_paginationUnit; }
-    void setPaginationUnit(PaginationUnit paginationUnit) { m_paginationUnit = paginationUnit; }
-
 private:
     LayoutUnit m_desiredColumnWidth;
     unsigned m_desiredColumnCount;
@@ -114,7 +109,6 @@
     int m_forcedBreaks; // FIXME: We will ultimately need to cache more information to balance around forced breaks properly.
     LayoutUnit m_maximumDistanceBetweenForcedBreaks;
     LayoutUnit m_forcedBreakOffset;
-    PaginationUnit m_paginationUnit;
 };
 
 }
diff --git a/Source/core/rendering/CompositedLayerMapping.cpp b/Source/core/rendering/CompositedLayerMapping.cpp
index 885864d..9eb6f3c 100644
--- a/Source/core/rendering/CompositedLayerMapping.cpp
+++ b/Source/core/rendering/CompositedLayerMapping.cpp
@@ -38,8 +38,7 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Chrome.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Settings.h"
-#include "core/frame/animation/AnimationController.h"
+#include "core/frame/Settings.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/FilterEffectRenderer.h"
@@ -51,13 +50,10 @@
 #include "core/rendering/RenderLayerStackingNodeIterator.h"
 #include "core/rendering/RenderVideo.h"
 #include "core/rendering/RenderView.h"
-#include "core/rendering/animation/WebAnimationProvider.h"
 #include "core/rendering/style/KeyframeList.h"
 #include "platform/LengthFunctions.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/graphics/GraphicsContext.h"
-#include "platform/graphics/GraphicsContext3D.h"
-#include "platform/graphics/filters/custom/CustomFilterOperation.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/text/StringBuilder.h"
 
@@ -158,9 +154,7 @@
 
 CompositedLayerMapping::CompositedLayerMapping(RenderLayer* layer)
     : m_owningLayer(layer)
-    , m_animationProvider(adoptPtr(new WebAnimationProvider))
     , m_artificiallyInflatedBounds(false)
-    , m_boundsConstrainedByClipping(false)
     , m_isMainFrameRenderViewLayer(false)
     , m_requiresOwnBackingStoreForIntrinsicReasons(true)
     , m_requiresOwnBackingStoreForAncestorReasons(true)
@@ -175,13 +169,24 @@
 
 CompositedLayerMapping::~CompositedLayerMapping()
 {
+    // Do not leave the destroyed pointer dangling on any RenderLayers that painted to this mapping's squashing layer.
+    for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
+        RenderLayer* oldSquashedLayer = m_squashedLayers[i].renderLayer;
+        if (oldSquashedLayer->groupedMapping() == this) {
+            oldSquashedLayer->setGroupedMapping(0);
+            oldSquashedLayer->setLostGroupedMapping(true);
+        }
+    }
+
     updateClippingLayers(false, false);
     updateOverflowControlsLayers(false, false, false);
+    updateChildTransformLayer(false);
     updateForegroundLayer(false);
     updateBackgroundLayer(false);
     updateMaskLayer(false);
     updateClippingMaskLayers(false);
     updateScrollingLayers(false);
+    updateSquashingLayers(false);
     destroyGraphicsLayers();
 }
 
@@ -227,6 +232,7 @@
     m_foregroundLayer = nullptr;
     m_backgroundLayer = nullptr;
     m_childContainmentLayer = nullptr;
+    m_childTransformLayer = nullptr;
     m_maskLayer = nullptr;
     m_childClippingMaskLayer = nullptr;
 
@@ -340,7 +346,7 @@
     // on whether or not descendands will paint into our backing). Update this value now.
     updateDrawsContent(isSimpleContainerCompositingLayer());
 
-    IntRect layerBounds = compositor()->calculateCompositedBounds(m_owningLayer, m_owningLayer);
+    LayoutRect layerBounds = compositor()->calculateCompositedBounds(m_owningLayer, m_owningLayer);
 
     // Clip to the size of the document or enclosing overflow-scroll layer.
     // If this or an ancestor is transformed, we can't currently compute the correct rect to intersect with.
@@ -356,16 +362,13 @@
             clippingBounds = view->unscaledDocumentRect();
 
         if (m_owningLayer != rootLayer)
-            clippingBounds.intersect(m_owningLayer->backgroundClipRect(ClipRectsContext(rootLayer, 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
+            clippingBounds.intersect(m_owningLayer->clipper().backgroundClipRect(ClipRectsContext(rootLayer, AbsoluteClipRects)).rect());
 
         LayoutPoint delta;
         m_owningLayer->convertToLayerCoords(rootLayer, delta);
         clippingBounds.move(-delta.x(), -delta.y());
 
-        layerBounds.intersect(pixelSnappedIntRect(clippingBounds));
-        m_boundsConstrainedByClipping = true;
-    } else {
-        m_boundsConstrainedByClipping = false;
+        layerBounds.intersect(clippingBounds);
     }
 
     // If the element has a transform-origin that has fixed lengths, and the renderer has zero size,
@@ -387,7 +390,9 @@
     if (renderer()->isRenderPart()) {
         if (RenderLayerCompositor* innerCompositor = RenderLayerCompositor::frameContentsCompositor(toRenderPart(renderer()))) {
             innerCompositor->frameViewDidChangeSize();
-            innerCompositor->frameViewDidChangeLocation(contentsBox().location());
+            // We can floor this point because our frameviews are always aligned to pixel boundaries.
+            ASSERT(contentsBox().location() == flooredIntPoint(contentsBox().location()));
+            innerCompositor->frameViewDidChangeLocation(flooredIntPoint(contentsBox().location()));
         }
     }
 }
@@ -458,6 +463,7 @@
         if (m_owningLayer->renderer()->containingBlock()->enclosingLayer() == m_owningLayer->ancestorCompositedScrollingLayer())
             needsAncestorClip = false;
     }
+
     if (updateClippingLayers(needsAncestorClip, needsDescendentsClippingLayer))
         layerConfigChanged = true;
 
@@ -467,9 +473,19 @@
     if (updateScrollingLayers(m_owningLayer->needsCompositedScrolling()))
         layerConfigChanged = true;
 
+    bool hasPerspective = false;
+    if (RenderStyle* style = renderer->style())
+        hasPerspective = style->hasPerspective();
+    bool needsChildTransformLayer = hasPerspective && (layerForChildrenTransform() == m_childTransformLayer.get());
+    if (updateChildTransformLayer(needsChildTransformLayer))
+        layerConfigChanged = true;
+
     updateScrollParent(scrollParent);
     updateClipParent(m_owningLayer->clipParent());
 
+    if (updateSquashingLayers(!m_squashedLayers.isEmpty()))
+        layerConfigChanged = true;
+
     if (layerConfigChanged)
         updateInternalHierarchy();
 
@@ -504,6 +520,10 @@
     if (renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing()) {
         PluginView* pluginView = toPluginView(toRenderWidget(renderer)->widget());
         m_graphicsLayer->setContentsToPlatformLayer(pluginView->platformLayer());
+    } else if (renderer->node() && renderer->node()->isFrameOwnerElement() && toHTMLFrameOwnerElement(renderer->node())->contentFrame()) {
+        blink::WebLayer* layer = toHTMLFrameOwnerElement(renderer->node())->contentFrame()->remotePlatformLayer();
+        if (layer)
+            m_graphicsLayer->setContentsToPlatformLayer(layer);
     } else if (renderer->isVideo()) {
         HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer->node());
         m_graphicsLayer->setContentsToPlatformLayer(mediaElement->platformLayer());
@@ -523,14 +543,81 @@
 {
     LayoutRect result = PaintInfo::infiniteRect();
     if (renderer->hasOverflowClip())
-        result = renderer->overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
+        result = renderer->overflowClipRect(LayoutPoint());
 
     if (renderer->hasClip())
-        result.intersect(renderer->clipRect(LayoutPoint(), 0)); // FIXME: Incorrect for CSS regions.
+        result.intersect(renderer->clipRect(LayoutPoint()));
 
     return pixelSnappedIntRect(result);
 }
 
+void CompositedLayerMapping::adjustBoundsForSubPixelAccumulation(const RenderLayer* compositedAncestor, IntRect& localBounds, IntRect& relativeBounds, IntPoint& delta)
+{
+    LayoutRect localRawCompositingBounds = compositedBounds();
+    LayoutPoint rawDelta;
+    m_owningLayer->convertToLayerCoords(compositedAncestor, rawDelta);
+    delta = flooredIntPoint(rawDelta);
+    m_subpixelAccumulation = toLayoutSize(rawDelta).fraction();
+    RELEASE_ASSERT(m_subpixelAccumulation.width() < 1 && m_subpixelAccumulation.height() < 1);
+
+    // Move the bounds by the subpixel accumulation so that it pixel-snaps relative to absolute pixels instead of local coordinates.
+    localRawCompositingBounds.move(m_subpixelAccumulation);
+    localBounds = pixelSnappedIntRect(localRawCompositingBounds);
+
+    relativeBounds = localBounds;
+    relativeBounds.moveBy(delta);
+}
+
+void CompositedLayerMapping::updateSquashingLayerGeometry(const IntPoint& delta)
+{
+    if (!m_squashingLayer)
+        return;
+
+    ASSERT(compositor()->layerSquashingEnabled());
+
+    LayoutRect totalSquashBounds;
+    for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
+        LayoutRect squashedBounds = compositor()->calculateCompositedBounds(m_squashedLayers[i].renderLayer, m_squashedLayers[i].renderLayer);
+
+        // Store the local bounds of the RenderLayer subtree before applying the offset.
+        m_squashedLayers[i].compositedBounds = squashedBounds;
+
+        squashedBounds.move(m_squashedLayers[i].offsetFromSquashingCLM);
+        totalSquashBounds.unite(squashedBounds);
+    }
+
+    // The totalSquashBounds is positioned with respect to m_owningLayer of this CompositedLayerMapping.
+    // But the squashingLayer needs to be positioned with respect to the ancestor CompositedLayerMapping.
+    // The conversion between m_owningLayer and the ancestor CLM is already computed in the caller as |delta|.
+    // FIXME: probably not the right place to round from LayoutPoint to IntPoint?
+    IntPoint squashLayerPosition = pixelSnappedIntRect(totalSquashBounds).location();
+    squashLayerPosition.moveBy(delta);
+
+    // FIXME: this could be skipped for accelerated overflow scrolling, somehow.
+    m_squashingLayer->setNeedsDisplay();
+
+    m_squashingLayer->setPosition(squashLayerPosition);
+    m_squashingLayer->setSize(totalSquashBounds.size());
+
+    // Now that the squashing bounds are known, we can convert the RenderLayer painting offsets
+    // from CLM owning layer space to the squashing layer space.
+    //
+    // The painting offset we want to compute for each squashed RenderLayer is essentially the position of
+    // the squashed RenderLayer described w.r.t. m_squashingLayer's origin. For this purpose we already cached
+    // offsetFromSquashingCLM before, which describes where the squashed RenderLayer is located w.r.t.
+    // m_owningLayer. So we just need to convert that point from m_owningLayer space to m_squashingLayer
+    // space. This is simply done by subtracing totalSquashBounds... but then the offset overall needs to be
+    // negated because that's the direction that the painting code expects the offset to be.
+    for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
+        m_squashedLayers[i].offsetFromRenderer = IntSize(-m_squashedLayers[i].offsetFromSquashingCLM.width() + totalSquashBounds.x(),
+            -m_squashedLayers[i].offsetFromSquashingCLM.height() + totalSquashBounds.y());
+
+        // FIXME: find a better design to avoid this redundant value - most likely it will make
+        // sense to move the paint task info into RenderLayer's m_compositingProperties.
+        m_squashedLayers[i].renderLayer->setOffsetFromSquashingLayerOrigin(m_squashedLayers[i].offsetFromRenderer);
+    }
+}
+
 void CompositedLayerMapping::updateGraphicsLayerGeometry()
 {
     // If we haven't built z-order lists yet, wait until later.
@@ -539,15 +626,11 @@
 
     // Set transform property, if it is not animating. We have to do this here because the transform
     // is affected by the layer dimensions.
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
-        ? !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitTransform)
-        : !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitTransform))
+    if (!hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitTransform))
         updateTransform(renderer()->style());
 
     // Set opacity, if it is not animating.
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
-        ? !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyOpacity)
-        : !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyOpacity))
+    if (!hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyOpacity))
         updateOpacity(renderer()->style());
 
     bool isSimpleContainer = isSimpleContainerCompositingLayer();
@@ -566,9 +649,6 @@
     m_graphicsLayer->setContentsVisible(contentsVisible);
 
     RenderStyle* style = renderer()->style();
-    // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
-    bool preserves3D = style->transformStyle3D() == TransformStyle3DPreserve3D && !renderer()->hasReflection();
-    m_graphicsLayer->setPreserves3D(preserves3D);
     m_graphicsLayer->setBackfaceVisibility(style->backfaceVisibility() == BackfaceVisibilityVisible);
 
     RenderLayer* compAncestor = m_owningLayer->ancestorCompositingLayer();
@@ -580,12 +660,10 @@
         ancestorCompositingBounds = pixelSnappedIntRect(compAncestor->compositedLayerMapping()->compositedBounds());
     }
 
-    IntRect localCompositingBounds = pixelSnappedIntRect(compositedBounds());
-
-    IntRect relativeCompositingBounds(localCompositingBounds);
+    IntRect localCompositingBounds;
+    IntRect relativeCompositingBounds;
     IntPoint delta;
-    m_owningLayer->convertToPixelSnappedLayerCoords(compAncestor, delta);
-    relativeCompositingBounds.moveBy(delta);
+    adjustBoundsForSubPixelAccumulation(compAncestor, localCompositingBounds, relativeCompositingBounds, delta);
 
     IntPoint graphicsLayerParentLocation;
     if (compAncestor && compAncestor->compositedLayerMapping()->hasClippingLayer()) {
@@ -610,8 +688,8 @@
         // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
         // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
         // for a compositing layer, rootLayer is the layer itself.
-        ClipRectsContext clipRectsContext(compAncestor, 0, TemporaryClipRects, IgnoreOverlayScrollbarSize, IgnoreOverflowClip);
-        IntRect parentClipRect = pixelSnappedIntRect(m_owningLayer->backgroundClipRect(clipRectsContext).rect()); // FIXME: Incorrect for CSS regions.
+        ClipRectsContext clipRectsContext(compAncestor, TemporaryClipRects, IgnoreOverlayScrollbarSize, IgnoreOverflowClip);
+        IntRect parentClipRect = pixelSnappedIntRect(m_owningLayer->clipper().backgroundClipRect(clipRectsContext).rect());
         ASSERT(parentClipRect != PaintInfo::infiniteRect());
         m_ancestorClippingLayer->setPosition(FloatPoint(parentClipRect.location() - graphicsLayerParentLocation));
         m_ancestorClippingLayer->setSize(parentClipRect.size());
@@ -629,14 +707,8 @@
     m_graphicsLayer->setOffsetFromRenderer(toIntSize(localCompositingBounds.location()));
 
     FloatSize oldSize = m_graphicsLayer->size();
-    if (oldSize != contentsSize) {
+    if (oldSize != contentsSize)
         m_graphicsLayer->setSize(contentsSize);
-        // Usually invalidation will happen via layout etc, but if we've affected the layer
-        // size by constraining relative to a clipping ancestor or the viewport, we
-        // have to invalidate to avoid showing stretched content.
-        if (m_boundsConstrainedByClipping)
-            m_graphicsLayer->setNeedsDisplay();
-    }
 
     // If we have a layer that clips children, position it.
     IntRect clippingBox;
@@ -650,6 +722,8 @@
             m_childClippingMaskLayer->setSize(clipLayer->size());
             m_childClippingMaskLayer->setOffsetFromRenderer(clipLayer->offsetFromRenderer());
         }
+    } else if (m_childTransformLayer) {
+        m_childTransformLayer->setSize(contentsSize);
     }
 
     if (m_maskLayer) {
@@ -665,39 +739,21 @@
         const IntRect borderBox = toRenderBox(renderer())->pixelSnappedBorderBoxRect();
 
         // Get layout bounds in the coords of compAncestor to match relativeCompositingBounds.
-        IntRect layerBounds = IntRect(delta, borderBox.size());
+        IntRect layerBounds(delta + roundedIntSize(m_subpixelAccumulation), borderBox.size());
 
         // Update properties that depend on layer dimensions
         FloatPoint3D transformOrigin = computeTransformOrigin(borderBox);
         // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
-        FloatPoint3D anchor(relativeCompositingBounds.width() != 0.0f ? ((layerBounds.x() - relativeCompositingBounds.x()) + transformOrigin.x()) / relativeCompositingBounds.width()  : 0.5f,
-            relativeCompositingBounds.height() != 0.0f ? ((layerBounds.y() - relativeCompositingBounds.y()) + transformOrigin.y()) / relativeCompositingBounds.height() : 0.5f,
+        FloatPoint3D anchor(
+            relativeCompositingBounds.width() ? (layerBounds.x() - relativeCompositingBounds.x() + transformOrigin.x()) / relativeCompositingBounds.width()  : 0.5f,
+            relativeCompositingBounds.height() ? (layerBounds.y() - relativeCompositingBounds.y() + transformOrigin.y()) / relativeCompositingBounds.height() : 0.5f,
             transformOrigin.z());
         m_graphicsLayer->setAnchorPoint(anchor);
-
-        RenderStyle* style = renderer()->style();
-        GraphicsLayer* clipLayer = clippingLayer();
-        if (style->hasPerspective()) {
-            TransformationMatrix t = owningLayer()->perspectiveTransform();
-
-            if (clipLayer) {
-                clipLayer->setChildrenTransform(t);
-                m_graphicsLayer->setChildrenTransform(TransformationMatrix());
-            } else {
-                m_graphicsLayer->setChildrenTransform(t);
-            }
-        } else {
-            if (clipLayer)
-                clipLayer->setChildrenTransform(TransformationMatrix());
-            else
-                m_graphicsLayer->setChildrenTransform(TransformationMatrix());
-        }
     } else {
         m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5f, 0.5f, 0));
     }
 
     if (m_foregroundLayer) {
-        FloatPoint foregroundPosition;
         FloatSize foregroundSize = contentsSize;
         IntSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
         if (hasClippingLayer()) {
@@ -707,7 +763,7 @@
             foregroundOffset = toIntSize(clippingBox.location());
         }
 
-        m_foregroundLayer->setPosition(foregroundPosition);
+        m_foregroundLayer->setPosition(FloatPoint());
         if (foregroundSize != m_foregroundLayer->size()) {
             m_foregroundLayer->setSize(foregroundSize);
             m_foregroundLayer->setNeedsDisplay();
@@ -716,13 +772,12 @@
     }
 
     if (m_backgroundLayer) {
-        FloatPoint backgroundPosition;
         FloatSize backgroundSize = contentsSize;
         if (backgroundLayerPaintsFixedRootBackground()) {
             FrameView* frameView = toRenderView(renderer())->frameView();
             backgroundSize = frameView->visibleContentRect().size();
         }
-        m_backgroundLayer->setPosition(backgroundPosition);
+        m_backgroundLayer->setPosition(FloatPoint());
         if (backgroundSize != m_backgroundLayer->size()) {
             m_backgroundLayer->setSize(backgroundSize);
             m_backgroundLayer->setNeedsDisplay();
@@ -750,7 +805,7 @@
             clientBox.move(renderBox->verticalScrollbarWidth(), 0);
 
         IntSize adjustedScrollOffset = m_owningLayer->scrollableArea()->adjustedScrollOffset();
-        m_scrollingLayer->setPosition(FloatPoint(clientBox.location() - localCompositingBounds.location()));
+        m_scrollingLayer->setPosition(FloatPoint(clientBox.location() - localCompositingBounds.location() + roundedIntSize(m_subpixelAccumulation)));
         m_scrollingLayer->setSize(clientBox.size());
 
         IntSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
@@ -770,12 +825,8 @@
 
         IntSize scrollingContentsOffset = toIntSize(clientBox.location() - adjustedScrollOffset);
         if (scrollingContentsOffset != m_scrollingContentsLayer->offsetFromRenderer() || scrollSize != m_scrollingContentsLayer->size()) {
-            bool scrollingCoordinatorHandlesOffset = compositor()->scrollingLayerDidChange(m_owningLayer);
-
-            if (scrollingCoordinatorHandlesOffset)
-                m_scrollingContentsLayer->setPosition(-m_owningLayer->scrollableArea()->scrollOrigin());
-            else
-                m_scrollingContentsLayer->setPosition(FloatPoint(-adjustedScrollOffset));
+            bool coordinatorHandlesOffset = compositor()->scrollingLayerDidChange(m_owningLayer);
+            m_scrollingContentsLayer->setPosition(coordinatorHandlesOffset ? FloatPoint() : FloatPoint(-adjustedScrollOffset));
         }
 
         m_scrollingContentsLayer->setSize(scrollSize);
@@ -790,7 +841,9 @@
         }
     }
 
-    if (m_owningLayer->scrollableArea())
+    updateSquashingLayerGeometry(delta);
+
+    if (m_owningLayer->scrollableArea() && m_owningLayer->scrollableArea()->scrollsOverflow())
         m_owningLayer->scrollableArea()->positionOverflowControls();
 
     // We can't make this call in RenderLayerCompositor::allocateOrClearCompositedLayerMapping
@@ -807,6 +860,9 @@
     updateDrawsContent(isSimpleContainer);
     updateContentsOpaque();
     updateAfterWidgetResize();
+    updateRenderingContext();
+    updateShouldFlattenTransform();
+    updateChildrenTransform();
     registerScrollingLayers();
 
     updateCompositingReasons();
@@ -827,7 +883,8 @@
     // layer is further up in the hierarchy, we need to avoid marking the root render view
     // layer as a container.
     bool isContainer = m_owningLayer->hasTransform() && !m_owningLayer->isRootLayer();
-    scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(childForSuperlayers(), isContainer);
+    // FIXME: we should make certain that childForSuperLayers will never be the m_squashingContainmentLayer here
+    scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(localRootForOwningLayer(), isContainer);
 }
 
 void CompositedLayerMapping::updateInternalHierarchy()
@@ -842,43 +899,58 @@
     if (m_ancestorClippingLayer)
         m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
 
-    if (m_childContainmentLayer) {
-        m_childContainmentLayer->removeFromParent();
+    if (m_childContainmentLayer)
         m_graphicsLayer->addChild(m_childContainmentLayer.get());
-    }
+    else if (m_childTransformLayer)
+        m_graphicsLayer->addChild(m_childTransformLayer.get());
 
     if (m_scrollingLayer) {
-        GraphicsLayer* superlayer = m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
-        m_scrollingLayer->removeFromParent();
-        superlayer->addChild(m_scrollingLayer.get());
+        GraphicsLayer* superLayer = m_graphicsLayer.get();
+
+        if (m_childContainmentLayer)
+            superLayer = m_childContainmentLayer.get();
+
+        if (m_childTransformLayer)
+            superLayer = m_childTransformLayer.get();
+
+        superLayer->addChild(m_scrollingLayer.get());
     }
 
     // The clip for child layers does not include space for overflow controls, so they exist as
     // siblings of the clipping layer if we have one. Normal children of this layer are set as
     // children of the clipping layer.
-    if (m_layerForHorizontalScrollbar) {
-        m_layerForHorizontalScrollbar->removeFromParent();
+    if (m_layerForHorizontalScrollbar)
         m_graphicsLayer->addChild(m_layerForHorizontalScrollbar.get());
-    }
-    if (m_layerForVerticalScrollbar) {
-        m_layerForVerticalScrollbar->removeFromParent();
+    if (m_layerForVerticalScrollbar)
         m_graphicsLayer->addChild(m_layerForVerticalScrollbar.get());
-    }
-    if (m_layerForScrollCorner) {
-        m_layerForScrollCorner->removeFromParent();
+    if (m_layerForScrollCorner)
         m_graphicsLayer->addChild(m_layerForScrollCorner.get());
+
+    // The squashing containment layer, if it exists, becomes a no-op parent.
+    if (m_squashingLayer) {
+        ASSERT(compositor()->layerSquashingEnabled());
+        ASSERT(m_squashingContainmentLayer);
+
+        m_squashingContainmentLayer->removeAllChildren();
+
+        if (m_ancestorClippingLayer)
+            m_squashingContainmentLayer->addChild(m_ancestorClippingLayer.get());
+        else
+            m_squashingContainmentLayer->addChild(m_graphicsLayer.get());
+
+        m_squashingContainmentLayer->addChild(m_squashingLayer.get());
     }
 }
 
 void CompositedLayerMapping::updateContentsRect(bool isSimpleContainer)
 {
-    IntRect contentsRect;
+    LayoutRect contentsRect;
     if (isSimpleContainer && renderer()->hasBackground())
         contentsRect = backgroundBox();
     else
         contentsRect = contentsBox();
 
-    m_graphicsLayer->setContentsRect(contentsRect);
+    m_graphicsLayer->setContentsRect(pixelSnappedIntRect(contentsRect));
 }
 
 void CompositedLayerMapping::updateDrawsContent(bool isSimpleContainer)
@@ -901,7 +973,7 @@
         CanvasRenderingContext* context = toHTMLCanvasElement(renderer()->node())->renderingContext();
         // Content layer may be null if context is lost.
         if (blink::WebLayer* contentLayer = context->platformLayer()) {
-            Color bgColor;
+            Color bgColor(Color::transparent);
             if (contentLayerSupportsDirectBackgroundComposition(renderer())) {
                 bgColor = rendererBackgroundColor();
                 hasPaintedContent = false;
@@ -919,6 +991,26 @@
         m_backgroundLayer->setDrawsContent(hasPaintedContent);
 }
 
+void CompositedLayerMapping::updateChildrenTransform()
+{
+    if (GraphicsLayer* childTransformLayer = layerForChildrenTransform()) {
+        childTransformLayer->setTransform(owningLayer()->perspectiveTransform());
+        bool hasPerspective = false;
+        if (RenderStyle* style = m_owningLayer->renderer()->style())
+            hasPerspective = style->hasPerspective();
+        if (hasPerspective)
+            childTransformLayer->setShouldFlattenTransform(false);
+
+        // Note, if the target is the scrolling layer, we need to ensure that the
+        // scrolling content layer doesn't flatten the transform. (It would be nice
+        // if we could apply transform to the scrolling content layer, but that's
+        // too late, we need the children transform to be applied _before_ the
+        // scrolling offset.)
+        if (childTransformLayer == m_scrollingLayer.get())
+            m_scrollingContentsLayer->setShouldFlattenTransform(false);
+    }
+}
+
 // Return true if the layers changed.
 bool CompositedLayerMapping::updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip)
 {
@@ -953,45 +1045,45 @@
     return layersChanged;
 }
 
+bool CompositedLayerMapping::updateChildTransformLayer(bool needsChildTransformLayer)
+{
+    bool layersChanged = false;
+
+    if (needsChildTransformLayer) {
+        if (!m_childTransformLayer) {
+            m_childTransformLayer = createGraphicsLayer(CompositingReasonPerspective);
+            m_childTransformLayer->setDrawsContent(false);
+            m_childTransformLayer->setShouldFlattenTransform(false);
+            layersChanged = true;
+        }
+    } else if (m_childTransformLayer) {
+        m_childTransformLayer->removeFromParent();
+        m_childTransformLayer = nullptr;
+        layersChanged = true;
+    }
+
+    return layersChanged;
+}
+
 void CompositedLayerMapping::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
 {
     m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;
 }
 
+// Only a member function so it can call createGraphicsLayer.
+bool CompositedLayerMapping::toggleScrollbarLayerIfNeeded(OwnPtr<GraphicsLayer>& layer, bool needsLayer)
+{
+    if (needsLayer == !!layer)
+        return false;
+    layer = needsLayer ? createGraphicsLayer(CompositingReasonLayerForScrollbar) : nullptr;
+    return true;
+}
+
 bool CompositedLayerMapping::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
 {
-    bool horizontalScrollbarLayerChanged = false;
-    if (needsHorizontalScrollbarLayer) {
-        if (!m_layerForHorizontalScrollbar) {
-            m_layerForHorizontalScrollbar = createGraphicsLayer(CompositingReasonLayerForScrollbar);
-            horizontalScrollbarLayerChanged = true;
-        }
-    } else if (m_layerForHorizontalScrollbar) {
-        m_layerForHorizontalScrollbar = nullptr;
-        horizontalScrollbarLayerChanged = true;
-    }
-
-    bool verticalScrollbarLayerChanged = false;
-    if (needsVerticalScrollbarLayer) {
-        if (!m_layerForVerticalScrollbar) {
-            m_layerForVerticalScrollbar = createGraphicsLayer(CompositingReasonLayerForScrollbar);
-            verticalScrollbarLayerChanged = true;
-        }
-    } else if (m_layerForVerticalScrollbar) {
-        m_layerForVerticalScrollbar = nullptr;
-        verticalScrollbarLayerChanged = true;
-    }
-
-    bool scrollCornerLayerChanged = false;
-    if (needsScrollCornerLayer) {
-        if (!m_layerForScrollCorner) {
-            m_layerForScrollCorner = createGraphicsLayer(CompositingReasonLayerForScrollbar);
-            scrollCornerLayerChanged = true;
-        }
-    } else if (m_layerForScrollCorner) {
-        m_layerForScrollCorner = nullptr;
-        scrollCornerLayerChanged = true;
-    }
+    bool horizontalScrollbarLayerChanged = toggleScrollbarLayerIfNeeded(m_layerForHorizontalScrollbar, needsHorizontalScrollbarLayer);
+    bool verticalScrollbarLayerChanged = toggleScrollbarLayerIfNeeded(m_layerForVerticalScrollbar, needsVerticalScrollbarLayer);
+    bool scrollCornerLayerChanged = toggleScrollbarLayerIfNeeded(m_layerForScrollCorner, needsScrollCornerLayer);
 
     if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
         if (horizontalScrollbarLayerChanged)
@@ -1005,7 +1097,7 @@
 
 void CompositedLayerMapping::positionOverflowControlsLayers(const IntSize& offsetFromRoot)
 {
-    IntSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
+    IntSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer() - roundedIntSize(m_subpixelAccumulation);
     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
         Scrollbar* hBar = m_owningLayer->scrollableArea()->horizontalScrollbar();
         if (hBar) {
@@ -1056,6 +1148,101 @@
     return false;
 }
 
+enum ApplyToGraphicsLayersModeFlags {
+    ApplyToCoreLayers = (1 << 0),
+    ApplyToSquashingLayer = (1 << 1),
+    ApplyToScrollbarLayers = (1 << 2),
+    ApplyToBackgroundLayer = (1 << 3),
+    ApplyToMaskLayers = (1 << 4),
+    ApplyToContentLayers = (1 << 5),
+    ApplyToAllGraphicsLayers = (ApplyToSquashingLayer | ApplyToScrollbarLayers | ApplyToBackgroundLayer | ApplyToMaskLayers | ApplyToCoreLayers | ApplyToContentLayers)
+};
+typedef unsigned ApplyToGraphicsLayersMode;
+
+template <typename Func>
+static void ApplyToGraphicsLayers(const CompositedLayerMapping* mapping, const Func& f, ApplyToGraphicsLayersMode mode)
+{
+    ASSERT(mode);
+
+    if ((mode & ApplyToCoreLayers) && mapping->squashingContainmentLayer())
+        f(mapping->squashingContainmentLayer());
+    if ((mode & ApplyToCoreLayers) && mapping->childTransformLayer())
+        f(mapping->childTransformLayer());
+    if ((mode & ApplyToCoreLayers) && mapping->ancestorClippingLayer())
+        f(mapping->ancestorClippingLayer());
+    if (((mode & ApplyToCoreLayers) || (mode & ApplyToContentLayers)) && mapping->mainGraphicsLayer())
+        f(mapping->mainGraphicsLayer());
+    if ((mode & ApplyToCoreLayers) && mapping->clippingLayer())
+        f(mapping->clippingLayer());
+    if ((mode & ApplyToCoreLayers) && mapping->scrollingLayer())
+        f(mapping->scrollingLayer());
+    if (((mode & ApplyToCoreLayers) || (mode & ApplyToContentLayers)) && mapping->scrollingContentsLayer())
+        f(mapping->scrollingContentsLayer());
+    if (((mode & ApplyToCoreLayers) || (mode & ApplyToContentLayers)) && mapping->foregroundLayer())
+        f(mapping->foregroundLayer());
+
+    if ((mode & ApplyToSquashingLayer) && mapping->squashingLayer())
+        f(mapping->squashingLayer());
+
+    if (((mode & ApplyToMaskLayers) || (mode & ApplyToContentLayers)) && mapping->maskLayer())
+        f(mapping->maskLayer());
+    if (((mode & ApplyToMaskLayers) || (mode & ApplyToContentLayers)) && mapping->childClippingMaskLayer())
+        f(mapping->childClippingMaskLayer());
+
+    if (((mode & ApplyToBackgroundLayer) || (mode & ApplyToContentLayers)) && mapping->backgroundLayer())
+        f(mapping->backgroundLayer());
+
+    if ((mode & ApplyToScrollbarLayers) && mapping->layerForHorizontalScrollbar())
+        f(mapping->layerForHorizontalScrollbar());
+    if ((mode & ApplyToScrollbarLayers) && mapping->layerForVerticalScrollbar())
+        f(mapping->layerForVerticalScrollbar());
+    if ((mode & ApplyToScrollbarLayers) && mapping->layerForScrollCorner())
+        f(mapping->layerForScrollCorner());
+}
+
+struct UpdateRenderingContextFunctor {
+    void operator() (GraphicsLayer* layer) const { layer->setRenderingContext(renderingContext); }
+    int renderingContext;
+};
+
+void CompositedLayerMapping::updateRenderingContext()
+{
+    // All layers but the squashing layer (which contains 'alien' content) should be included in this
+    // rendering context.
+    int id = 0;
+
+    // NB, it is illegal at this point to query an ancestor's compositing state. Some compositing
+    // reasons depend on the compositing state of ancestors. So if we want a rendering context id
+    // for the context root, we cannot ask for the id of its associated WebLayer now; it may not have
+    // one yet. We could do a second past after doing the compositing updates to get these ids,
+    // but this would actually be harmful. We do not want to attach any semantic meaning to
+    // the context id other than the fact that they group a number of layers together for the
+    // sake of 3d sorting. So instead we will ask the compositor to vend us an arbitrary, but
+    // consistent id.
+    if (RenderLayer* root = m_owningLayer->renderingContextRoot()) {
+        if (Node* node = root->renderer()->node())
+            id = static_cast<int>(WTF::PtrHash<Node*>::hash(node));
+    }
+
+    UpdateRenderingContextFunctor functor = { id };
+    ApplyToGraphicsLayersMode mode = ApplyToAllGraphicsLayers & ~ApplyToSquashingLayer;
+    ApplyToGraphicsLayers<UpdateRenderingContextFunctor>(this, functor, mode);
+}
+
+struct UpdateShouldFlattenTransformFunctor {
+    void operator() (GraphicsLayer* layer) const { layer->setShouldFlattenTransform(shouldFlatten); }
+    bool shouldFlatten;
+};
+
+void CompositedLayerMapping::updateShouldFlattenTransform()
+{
+    // All CLM-managed layers that could affect a descendant layer should update their
+    // should-flatten-transform value (the other layers' transforms don't matter here).
+    UpdateShouldFlattenTransformFunctor functor = { m_owningLayer->shouldFlattenTransform() };
+    ApplyToGraphicsLayersMode mode = ApplyToCoreLayers;
+    ApplyToGraphicsLayers(this, functor, mode);
+}
+
 bool CompositedLayerMapping::updateForegroundLayer(bool needsForegroundLayer)
 {
     bool layerChanged = false;
@@ -1206,8 +1393,9 @@
 
 void CompositedLayerMapping::updateScrollParent(RenderLayer* scrollParent)
 {
+
     if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
-        GraphicsLayer* topmostLayer = childForSuperlayers();
+        GraphicsLayer* topmostLayer = localRootForOwningLayer();
         updateScrollParentForGraphicsLayer(m_ancestorClippingLayer.get(), topmostLayer, scrollParent, scrollingCoordinator);
         updateScrollParentForGraphicsLayer(m_graphicsLayer.get(), topmostLayer, scrollParent, scrollingCoordinator);
     }
@@ -1219,6 +1407,43 @@
         scrollingCoordinator->updateClipParentForGraphicsLayer(m_graphicsLayer.get(), clipParent);
 }
 
+bool CompositedLayerMapping::updateSquashingLayers(bool needsSquashingLayers)
+{
+    bool layersChanged = false;
+
+    if (needsSquashingLayers) {
+        ASSERT(compositor()->layerSquashingEnabled());
+
+        if (!m_squashingLayer) {
+            ASSERT(!m_squashingContainmentLayer);
+
+            m_squashingLayer = createGraphicsLayer(CompositingReasonOverlap);
+            m_squashingLayer->setDrawsContent(true);
+
+            // FIXME: containment layer needs a new CompositingReason, CompositingReasonOverlap is not appropriate.
+            m_squashingContainmentLayer = createGraphicsLayer(CompositingReasonOverlap);
+            layersChanged = true;
+        }
+
+        ASSERT(m_squashingLayer && m_squashingContainmentLayer);
+    } else {
+        if (m_squashingLayer) {
+            m_squashingLayer->removeFromParent();
+            m_squashingLayer = nullptr;
+            // FIXME: do we need to invalidate something here?
+
+            ASSERT(m_squashingContainmentLayer);
+            m_squashingContainmentLayer->removeFromParent();
+            m_squashingContainmentLayer = nullptr;
+            layersChanged = true;
+        }
+
+        ASSERT(!m_squashingLayer && !m_squashingContainmentLayer);
+    }
+
+    return layersChanged;
+}
+
 GraphicsLayerPaintingPhase CompositedLayerMapping::paintingPhaseForPrimaryLayer() const
 {
     unsigned phase = 0;
@@ -1282,10 +1507,9 @@
     Color backgroundColor = rendererBackgroundColor();
     if (isSimpleContainer) {
         m_graphicsLayer->setContentsToSolidColor(backgroundColor);
-        m_graphicsLayer->setBackgroundColor(Color());
+        m_graphicsLayer->setBackgroundColor(Color::transparent);
     } else {
-        // An unset (invalid) color will remove the solid color.
-        m_graphicsLayer->setContentsToSolidColor(Color());
+        m_graphicsLayer->setContentsToSolidColor(Color::transparent);
         m_graphicsLayer->setBackgroundColor(backgroundColor);
     }
 }
@@ -1531,23 +1755,23 @@
 }
 
 // Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
-IntSize CompositedLayerMapping::contentOffsetInCompostingLayer() const
+LayoutSize CompositedLayerMapping::contentOffsetInCompostingLayer() const
 {
-    return IntSize(-m_compositedBounds.x(), -m_compositedBounds.y());
+    return LayoutSize(-m_compositedBounds.x(), -m_compositedBounds.y());
 }
 
-IntRect CompositedLayerMapping::contentsBox() const
+LayoutRect CompositedLayerMapping::contentsBox() const
 {
-    IntRect contentsBox = contentsRect(renderer());
+    LayoutRect contentsBox = contentsRect(renderer());
     contentsBox.move(contentOffsetInCompostingLayer());
     return contentsBox;
 }
 
 IntRect CompositedLayerMapping::backgroundBox() const
 {
-    IntRect backgroundBox = backgroundRect(renderer());
+    LayoutRect backgroundBox = backgroundRect(renderer());
     backgroundBox.move(contentOffsetInCompostingLayer());
-    return backgroundBox;
+    return pixelSnappedIntRect(backgroundBox);
 }
 
 GraphicsLayer* CompositedLayerMapping::parentForSublayers() const
@@ -1555,10 +1779,16 @@
     if (m_scrollingContentsLayer)
         return m_scrollingContentsLayer.get();
 
-    return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
+    if (m_childContainmentLayer)
+        return m_childContainmentLayer.get();
+
+    if (m_childTransformLayer)
+        return m_childTransformLayer.get();
+
+    return m_graphicsLayer.get();
 }
 
-GraphicsLayer* CompositedLayerMapping::childForSuperlayers() const
+GraphicsLayer* CompositedLayerMapping::localRootForOwningLayer() const
 {
     if (m_ancestorClippingLayer)
         return m_ancestorClippingLayer.get();
@@ -1566,6 +1796,23 @@
     return m_graphicsLayer.get();
 }
 
+GraphicsLayer* CompositedLayerMapping::childForSuperlayers() const
+{
+    if (m_squashingContainmentLayer)
+        return m_squashingContainmentLayer.get();
+
+    return localRootForOwningLayer();
+}
+
+GraphicsLayer* CompositedLayerMapping::layerForChildrenTransform() const
+{
+    if (GraphicsLayer* clipLayer = clippingLayer())
+        return clipLayer;
+    if (m_scrollingLayer)
+        return m_scrollingLayer.get();
+    return m_childTransformLayer.get();
+}
+
 bool CompositedLayerMapping::updateRequiresOwnBackingStoreForAncestorReasons(const RenderLayer* compositingAncestorLayer)
 {
     bool previousRequiresOwnBackingStoreForAncestorReasons = m_requiresOwnBackingStoreForAncestorReasons;
@@ -1588,6 +1835,7 @@
     m_requiresOwnBackingStoreForIntrinsicReasons = m_owningLayer->isRootLayer()
         || (m_owningLayer->compositingReasons() & CompositingReasonComboReasonsThatRequireOwnBacking)
         || m_owningLayer->transform()
+        || m_owningLayer->clipsCompositingDescendantsWithBorderRadius() // FIXME: Revisit this if the paintsIntoCompositedAncestor state is removed.
         || renderer->isTransparent()
         || renderer->hasMask()
         || renderer->hasReflection()
@@ -1611,78 +1859,48 @@
 void CompositedLayerMapping::setBlendMode(blink::WebBlendMode blendMode)
 {
     if (m_ancestorClippingLayer) {
-        ASSERT(childForSuperlayers() == m_ancestorClippingLayer.get());
+        m_ancestorClippingLayer->setBlendMode(blendMode);
         m_graphicsLayer->setBlendMode(blink::WebBlendModeNormal);
     } else {
-        ASSERT(childForSuperlayers() == m_graphicsLayer.get());
+        m_graphicsLayer->setBlendMode(blendMode);
     }
-    childForSuperlayers()->setBlendMode(blendMode);
 }
 
+struct SetContentsNeedsDisplayFunctor {
+    void operator() (GraphicsLayer* layer) const
+    {
+        if (layer->drawsContent())
+            layer->setNeedsDisplay();
+    }
+};
+
 void CompositedLayerMapping::setContentsNeedDisplay()
 {
+    // FIXME: need to split out repaints for the background.
     ASSERT(!paintsIntoCompositedAncestor());
-
-    if (m_graphicsLayer && m_graphicsLayer->drawsContent())
-        m_graphicsLayer->setNeedsDisplay();
-
-    if (m_foregroundLayer && m_foregroundLayer->drawsContent())
-        m_foregroundLayer->setNeedsDisplay();
-
-    if (m_backgroundLayer && m_backgroundLayer->drawsContent())
-        m_backgroundLayer->setNeedsDisplay();
-
-    if (m_maskLayer && m_maskLayer->drawsContent())
-        m_maskLayer->setNeedsDisplay();
-
-    if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent())
-        m_childClippingMaskLayer->setNeedsDisplay();
-
-    if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent())
-        m_scrollingContentsLayer->setNeedsDisplay();
+    ApplyToGraphicsLayers(this, SetContentsNeedsDisplayFunctor(), ApplyToContentLayers);
 }
 
+struct SetContentsNeedsDisplayInRectFunctor {
+    void operator() (GraphicsLayer* layer) const
+    {
+        if (layer->drawsContent()) {
+            IntRect layerDirtyRect = r;
+            layerDirtyRect.move(-layer->offsetFromRenderer());
+            layer->setNeedsDisplayInRect(layerDirtyRect);
+        }
+    }
+
+    IntRect r;
+};
+
 // r is in the coordinate space of the layer's render object
 void CompositedLayerMapping::setContentsNeedDisplayInRect(const IntRect& r)
 {
-    ASSERT(!paintsIntoCompositedAncestor());
-
-    if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
-        IntRect layerDirtyRect = r;
-        layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer());
-        m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect);
-    }
-
-    if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
-        IntRect layerDirtyRect = r;
-        layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer());
-        m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect);
-    }
-
     // FIXME: need to split out repaints for the background.
-    if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
-        IntRect layerDirtyRect = r;
-        layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer());
-        m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect);
-    }
-
-    if (m_maskLayer && m_maskLayer->drawsContent()) {
-        IntRect layerDirtyRect = r;
-        layerDirtyRect.move(-m_maskLayer->offsetFromRenderer());
-        m_maskLayer->setNeedsDisplayInRect(layerDirtyRect);
-    }
-
-    if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent()) {
-        IntRect layerDirtyRect = r;
-        layerDirtyRect.move(-m_childClippingMaskLayer->offsetFromRenderer());
-        m_childClippingMaskLayer->setNeedsDisplayInRect(layerDirtyRect);
-    }
-
-    if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent()) {
-        IntRect layerDirtyRect = r;
-        layerDirtyRect.move(-m_scrollingContentsLayer->offsetFromRenderer());
-        m_scrollingContentsLayer->setNeedsDisplayInRect(layerDirtyRect);
-    }
+    ASSERT(!paintsIntoCompositedAncestor());
+    SetContentsNeedsDisplayInRectFunctor functor = { r };
+    ApplyToGraphicsLayers(this, functor, ApplyToContentLayers);
 }
 
 void CompositedLayerMapping::doPaintTask(GraphicsLayerPaintInfo& paintInfo, GraphicsContext* context,
@@ -1720,28 +1938,39 @@
     // assuming that the context's space was not affected by the RenderLayer
     // painting code.
 
-    LayoutSize offset = paintInfo.offsetFromRenderer;
+    IntSize offset = paintInfo.offsetFromRenderer;
     context->translate(-offset);
-    LayoutRect relativeClip(clip);
-    relativeClip.move(offset);
 
     // The dirtyRect is in the coords of the painting root.
-    IntRect dirtyRect = pixelSnappedIntRect(relativeClip);
-    if (!(paintInfo.paintingPhase & GraphicsLayerPaintOverflowContents))
-        dirtyRect.intersect(paintInfo.compositedBounds);
+    IntRect dirtyRect(clip);
+    dirtyRect.move(offset);
+
+    if (!(paintInfo.paintingPhase & GraphicsLayerPaintOverflowContents)) {
+        LayoutRect bounds = paintInfo.compositedBounds;
+        bounds.move(m_subpixelAccumulation);
+        dirtyRect.intersect(pixelSnappedIntRect(bounds));
+    } else {
+        dirtyRect.move(roundedIntSize(m_subpixelAccumulation));
+    }
 
 #ifndef NDEBUG
     paintInfo.renderLayer->renderer()->assertSubtreeIsLaidOut();
 #endif
 
-    // FIXME: GraphicsLayers need a way to split for RenderRegions.
-    LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, LayoutSize());
-    paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags);
+    if (paintInfo.renderLayer->compositingState() != PaintsIntoGroupedBacking) {
+        // FIXME: GraphicsLayers need a way to split for RenderRegions.
+        LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, m_subpixelAccumulation);
+        paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags);
 
-    ASSERT(!paintInfo.isBackgroundLayer || paintFlags & PaintLayerPaintingRootBackgroundOnly);
+        ASSERT(!paintInfo.isBackgroundLayer || paintFlags & PaintLayerPaintingRootBackgroundOnly);
 
-    if (paintInfo.renderLayer->containsDirtyOverlayScrollbars())
-        paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags | PaintLayerPaintingOverlayScrollbars);
+        if (paintInfo.renderLayer->containsDirtyOverlayScrollbars())
+            paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags | PaintLayerPaintingOverlayScrollbars);
+    } else {
+        ASSERT(compositor()->layerSquashingEnabled());
+        LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, LayoutSize());
+        paintInfo.renderLayer->paintLayer(context, paintingInfo, paintFlags);
+    }
 
     ASSERT(!paintInfo.renderLayer->m_usedTransparency);
 
@@ -1766,7 +1995,10 @@
 // Up-call from compositing layer drawing callback.
 void CompositedLayerMapping::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase paintingPhase, const IntRect& clip)
 {
+    // https://code.google.com/p/chromium/issues/detail?id=343772
+    DisableCompositingQueryAsserts disabler;
 #ifndef NDEBUG
+    // FIXME: once the state machine is ready, this can be removed and we can refer to that instead.
     if (Page* page = renderer()->frame()->page())
         page->setIsPainting(true);
 #endif
@@ -1788,6 +2020,10 @@
 
         // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
         doPaintTask(paintInfo, &context, clip);
+    } else if (graphicsLayer == m_squashingLayer.get()) {
+        ASSERT(compositor()->layerSquashingEnabled());
+        for (size_t i = 0; i < m_squashedLayers.size(); ++i)
+            doPaintTask(m_squashedLayers[i], &context, clip);
     } else if (graphicsLayer == layerForHorizontalScrollbar()) {
         paintScrollbar(m_owningLayer->scrollableArea()->horizontalScrollbar(), context, clip);
     } else if (graphicsLayer == layerForVerticalScrollbar()) {
@@ -1809,49 +2045,22 @@
 #endif
 }
 
-void CompositedLayerMapping::didCommitChangesForLayer(const GraphicsLayer* layer) const
-{
-}
-
-bool CompositedLayerMapping::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
-{
-    if (graphicsLayer != m_graphicsLayer.get())
-        return false;
-
-    if (m_owningLayer->hasTransform()) {
-        transform = m_owningLayer->currentTransform(RenderStyle::ExcludeTransformOrigin);
-        return true;
-    }
-    return false;
-}
-
 bool CompositedLayerMapping::isTrackingRepaints() const
 {
     GraphicsLayerClient* client = compositor();
     return client ? client->isTrackingRepaints() : false;
 }
 
-static void collectTrackedRepaintRectsForGraphicsLayer(GraphicsLayer* graphicsLayer, Vector<FloatRect>& rects)
-{
-    if (graphicsLayer)
-        graphicsLayer->collectTrackedRepaintRects(rects);
-}
+struct CollectTrackedRepaintRectsFunctor {
+    void operator() (GraphicsLayer* layer) const { layer->collectTrackedRepaintRects(*rects); }
+    Vector<FloatRect>* rects;
+};
 
 PassOwnPtr<Vector<FloatRect> > CompositedLayerMapping::collectTrackedRepaintRects() const
 {
     OwnPtr<Vector<FloatRect> > rects = adoptPtr(new Vector<FloatRect>);
-    collectTrackedRepaintRectsForGraphicsLayer(m_ancestorClippingLayer.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_graphicsLayer.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_childContainmentLayer.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_scrollingLayer.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_scrollingContentsLayer.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_maskLayer.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_childClippingMaskLayer.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_foregroundLayer.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_backgroundLayer.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_layerForHorizontalScrollbar.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_layerForVerticalScrollbar.get(), *rects);
-    collectTrackedRepaintRectsForGraphicsLayer(m_layerForScrollCorner.get(), *rects);
+    CollectTrackedRepaintRectsFunctor functor = { rects.get() };
+    ApplyToGraphicsLayers(this, functor, ApplyToAllGraphicsLayers);
     return rects.release();
 }
 
@@ -1862,127 +2071,75 @@
 }
 #endif
 
-bool CompositedLayerMapping::startAnimation(double timeOffset, const CSSAnimationData* anim, const KeyframeList& keyframes)
+void CompositedLayerMapping::notifyAnimationStarted(const GraphicsLayer*, double wallClockTime, double monotonicTime)
 {
-    bool hasTransform = renderer()->isBox() && keyframes.containsProperty(CSSPropertyWebkitTransform);
-    IntSize boxSize;
-    if (hasTransform)
-        boxSize = toRenderBox(renderer())->pixelSnappedBorderBoxRect().size();
-    WebAnimations animations(m_animationProvider->startAnimation(timeOffset, anim, keyframes, hasTransform, boxSize));
-    if (animations.isEmpty())
-        return false;
-
-    bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
-    bool hasFilter = keyframes.containsProperty(CSSPropertyWebkitFilter);
-    int animationId = m_animationProvider->getWebAnimationId(keyframes.animationName());
-
-    // Animating only some properties of the animation is not supported. So if the
-    // GraphicsLayer rejects any property of the animation, we have to remove the
-    // animation and return false to indicate un-accelerated animation is required.
-    if (hasTransform) {
-        if (!animations.m_transformAnimation || !m_graphicsLayer->addAnimation(animations.m_transformAnimation.release()))
-            return false;
-    }
-    if (hasOpacity) {
-        if (!animations.m_opacityAnimation || !m_graphicsLayer->addAnimation(animations.m_opacityAnimation.release())) {
-            if (hasTransform)
-                m_graphicsLayer->removeAnimation(animationId);
-            return false;
-        }
-    }
-    if (hasFilter) {
-        if (!animations.m_filterAnimation || !m_graphicsLayer->addAnimation(animations.m_filterAnimation.release())) {
-            if (hasTransform || hasOpacity)
-                m_graphicsLayer->removeAnimation(animationId);
-            return false;
-        }
-    }
-    return true;
+    renderer()->node()->document().cssPendingAnimations().notifyCompositorAnimationStarted(monotonicTime);
 }
 
-void CompositedLayerMapping::animationPaused(double timeOffset, const String& animationName)
-{
-    int animationId = m_animationProvider->getWebAnimationId(animationName);
-    ASSERT(animationId);
-    m_graphicsLayer->pauseAnimation(animationId, timeOffset);
-}
-
-void CompositedLayerMapping::animationFinished(const String& animationName)
-{
-    int animationId = m_animationProvider->getWebAnimationId(animationName);
-    ASSERT(animationId);
-    m_graphicsLayer->removeAnimation(animationId);
-}
-
-bool CompositedLayerMapping::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
-{
-    ASSERT(property != CSSPropertyInvalid);
-    IntSize boxSize;
-    if (property == CSSPropertyWebkitTransform && m_owningLayer->hasTransform()) {
-        ASSERT(renderer()->isBox());
-        boxSize = toRenderBox(renderer())->pixelSnappedBorderBoxRect().size();
-    }
-    float fromOpacity = 0;
-    float toOpacity = 0;
-    if (property == CSSPropertyOpacity) {
-        fromOpacity = compositingOpacity(fromStyle->opacity());
-        toOpacity = compositingOpacity(toStyle->opacity());
-    }
-
-    // Although KeyframeAnimation can have multiple properties of the animation, ImplicitAnimation (= Transition) has only one animation property.
-    WebAnimations animations(m_animationProvider->startTransition(timeOffset, property, fromStyle,
-        toStyle, m_owningLayer->hasTransform(), m_owningLayer->hasFilter(), boxSize, fromOpacity, toOpacity));
-    if (animations.m_transformAnimation && m_graphicsLayer->addAnimation(animations.m_transformAnimation.release())) {
-        // To ensure that the correct transform is visible when the animation ends, also set the final transform.
-        updateTransform(toStyle);
-        return true;
-    }
-    if (animations.m_opacityAnimation && m_graphicsLayer->addAnimation(animations.m_opacityAnimation.release())) {
-        // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
-        updateOpacity(toStyle);
-        return true;
-    }
-    if (animations.m_filterAnimation && m_graphicsLayer->addAnimation(animations.m_filterAnimation.release())) {
-        // To ensure that the correct filter is visible when the animation ends, also set the final filter.
-        updateFilters(toStyle);
-        return true;
-    }
-
-    return false;
-}
-
-void CompositedLayerMapping::transitionPaused(double timeOffset, CSSPropertyID property)
-{
-    int animationId = m_animationProvider->getWebAnimationId(property);
-    ASSERT(animationId);
-    m_graphicsLayer->pauseAnimation(animationId, timeOffset);
-}
-
-void CompositedLayerMapping::transitionFinished(CSSPropertyID property)
-{
-    int animationId = m_animationProvider->getWebAnimationId(property);
-    ASSERT(animationId);
-    m_graphicsLayer->removeAnimation(animationId);
-}
-
-void CompositedLayerMapping::notifyAnimationStarted(const GraphicsLayer*, double time)
-{
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-        renderer()->node()->document().cssPendingAnimations().notifyCompositorAnimationStarted(monotonicallyIncreasingTime() - (currentTime() - time));
-    else
-        renderer()->animation().notifyAnimationStarted(renderer(), time);
-}
-
-IntRect CompositedLayerMapping::compositedBounds() const
+LayoutRect CompositedLayerMapping::compositedBounds() const
 {
     return m_compositedBounds;
 }
 
-void CompositedLayerMapping::setCompositedBounds(const IntRect& bounds)
+void CompositedLayerMapping::setCompositedBounds(const LayoutRect& bounds)
 {
     m_compositedBounds = bounds;
 }
 
+bool CompositedLayerMapping::updateSquashingLayerAssignment(RenderLayer* layer, IntSize offsetFromSquashingCLM, size_t nextSquashedLayerIndex)
+{
+    ASSERT(compositor()->layerSquashingEnabled());
+
+    GraphicsLayerPaintInfo paintInfo;
+    paintInfo.renderLayer = layer;
+    // NOTE: composited bounds are updated elsewhere
+    // NOTE: offsetFromRenderer is updated elsewhere
+    paintInfo.offsetFromSquashingCLM = offsetFromSquashingCLM;
+    paintInfo.paintingPhase = GraphicsLayerPaintAllWithOverflowClip;
+    paintInfo.isBackgroundLayer = false;
+
+    // Change tracking on squashing layers: at the first sign of something changed, just invalidate the layer.
+    // FIXME: Perhaps we can find a tighter more clever mechanism later.
+    bool updatedAssignment = false;
+    if (nextSquashedLayerIndex < m_squashedLayers.size()) {
+        if (!paintInfo.isEquivalentForSquashing(m_squashedLayers[nextSquashedLayerIndex])) {
+            updatedAssignment = true;
+        }
+        m_squashedLayers[nextSquashedLayerIndex] = paintInfo;
+    } else {
+        m_squashedLayers.append(paintInfo);
+        updatedAssignment = true;
+    }
+    layer->setGroupedMapping(this);
+    return updatedAssignment;
+}
+
+void CompositedLayerMapping::removeRenderLayerFromSquashingGraphicsLayer(const RenderLayer* layer)
+{
+    size_t layerIndex = kNotFound;
+
+    for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
+        if (m_squashedLayers[i].renderLayer == layer) {
+            layerIndex = i;
+            break;
+        }
+    }
+
+    if (layerIndex == kNotFound)
+        return;
+
+    m_squashedLayers.remove(layerIndex);
+}
+
+void CompositedLayerMapping::finishAccumulatingSquashingLayers(size_t nextSquashedLayerIndex)
+{
+    ASSERT(compositor()->layerSquashingEnabled());
+
+    // Any additional squashed RenderLayers in the array no longer exist, and removing invalidates the squashingLayer contents.
+    if (nextSquashedLayerIndex < m_squashedLayers.size())
+        m_squashedLayers.remove(nextSquashedLayerIndex, m_squashedLayers.size() - nextSquashedLayerIndex);
+}
+
 CompositingLayerType CompositedLayerMapping::compositingLayerType() const
 {
     if (m_graphicsLayer->hasContentsLayer())
@@ -1994,41 +2151,15 @@
     return ContainerCompositingLayer;
 }
 
-double CompositedLayerMapping::backingStoreMemoryEstimate() const
-{
-    double backingMemory;
-
-    // m_ancestorClippingLayer and m_childContainmentLayer are just used for masking or containment, so have no backing.
-    backingMemory = m_graphicsLayer->backingStoreMemoryEstimate();
-    if (m_foregroundLayer)
-        backingMemory += m_foregroundLayer->backingStoreMemoryEstimate();
-    if (m_backgroundLayer)
-        backingMemory += m_backgroundLayer->backingStoreMemoryEstimate();
-    if (m_maskLayer)
-        backingMemory += m_maskLayer->backingStoreMemoryEstimate();
-    if (m_childClippingMaskLayer)
-        backingMemory += m_childClippingMaskLayer->backingStoreMemoryEstimate();
-
-    if (m_scrollingContentsLayer)
-        backingMemory += m_scrollingContentsLayer->backingStoreMemoryEstimate();
-
-    if (m_layerForHorizontalScrollbar)
-        backingMemory += m_layerForHorizontalScrollbar->backingStoreMemoryEstimate();
-
-    if (m_layerForVerticalScrollbar)
-        backingMemory += m_layerForVerticalScrollbar->backingStoreMemoryEstimate();
-
-    if (m_layerForScrollCorner)
-        backingMemory += m_layerForScrollCorner->backingStoreMemoryEstimate();
-
-    return backingMemory;
-}
-
 String CompositedLayerMapping::debugName(const GraphicsLayer* graphicsLayer)
 {
     String name;
     if (graphicsLayer == m_graphicsLayer.get()) {
         name = m_owningLayer->debugName();
+    } else if (graphicsLayer == m_squashingContainmentLayer.get()) {
+        name = "Squashing Containment Layer";
+    } else if (graphicsLayer == m_squashingLayer.get()) {
+        name = "Squashing Layer";
     } else if (graphicsLayer == m_ancestorClippingLayer.get()) {
         name = "Ancestor Clipping Layer";
     } else if (graphicsLayer == m_foregroundLayer.get()) {
@@ -2037,6 +2168,8 @@
         name = m_owningLayer->debugName() + " (background) Layer";
     } else if (graphicsLayer == m_childContainmentLayer.get()) {
         name = "Child Containment Layer";
+    } else if (graphicsLayer == m_childTransformLayer.get()) {
+        name = "Child Transform Layer";
     } else if (graphicsLayer == m_maskLayer.get()) {
         name = "Mask Layer";
     } else if (graphicsLayer == m_childClippingMaskLayer.get()) {
diff --git a/Source/core/rendering/CompositedLayerMapping.h b/Source/core/rendering/CompositedLayerMapping.h
index 2db2349..a1f39e8 100644
--- a/Source/core/rendering/CompositedLayerMapping.h
+++ b/Source/core/rendering/CompositedLayerMapping.h
@@ -37,7 +37,6 @@
 
 class KeyframeList;
 class RenderLayerCompositor;
-class WebAnimationProvider;
 
 enum CompositingLayerType {
     NormalCompositingLayer, // non-tiled layer with backing store
@@ -50,13 +49,30 @@
 struct GraphicsLayerPaintInfo {
     RenderLayer* renderLayer;
 
-    IntRect compositedBounds;
+    LayoutRect compositedBounds;
 
+    // At first, the m_squashingLayer's bounds/location are not known. The value offsetFromSquashingCLM is
+    // an intermediate offset for a squashed RenderLayer, described with respect to the CompositedLayerMapping's
+    // owning layer that would eventually have the m_squashingLayer. Once the shared GraphicsLayer's bounds are
+    // known, then we can trivially convert this offset to m_squashingLayer's space.
+    IntSize offsetFromSquashingCLM;
+
+    // Offset describing where this squashed RenderLayer paints into the shared GraphicsLayer backing.
     IntSize offsetFromRenderer;
 
     GraphicsLayerPaintingPhase paintingPhase;
 
     bool isBackgroundLayer;
+
+    bool isEquivalentForSquashing(const GraphicsLayerPaintInfo& other)
+    {
+        // FIXME: offsetFromRenderer and compositedBounds should not be checked here, because
+        // they are not yet fixed at the time this function is used.
+        return renderLayer == other.renderLayer
+            && offsetFromSquashingCLM == other.offsetFromSquashingCLM
+            && paintingPhase == other.paintingPhase
+            && isBackgroundLayer == other.isBackgroundLayer;
+    }
 };
 
 // CompositedLayerMapping keeps track of how RenderLayers of the render tree correspond to
@@ -66,11 +82,11 @@
 //
 // Currently (Oct. 2013) there is one CompositedLayerMapping for each RenderLayer,
 // but this is likely to evolve soon.
-class CompositedLayerMapping : public GraphicsLayerClient {
+class CompositedLayerMapping FINAL : public GraphicsLayerClient {
     WTF_MAKE_NONCOPYABLE(CompositedLayerMapping); WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit CompositedLayerMapping(RenderLayer*);
-    ~CompositedLayerMapping();
+    virtual ~CompositedLayerMapping();
 
     RenderLayer* owningLayer() const { return m_owningLayer; }
 
@@ -110,10 +126,22 @@
     GraphicsLayer* scrollingContentsLayer() const { return m_scrollingContentsLayer.get(); }
 
     bool hasMaskLayer() const { return m_maskLayer; }
+    GraphicsLayer* maskLayer() const { return m_maskLayer.get(); }
+
     bool hasChildClippingMaskLayer() const { return m_childClippingMaskLayer; }
+    GraphicsLayer* childClippingMaskLayer() const { return m_childClippingMaskLayer.get(); }
 
     GraphicsLayer* parentForSublayers() const;
     GraphicsLayer* childForSuperlayers() const;
+    // localRootForOwningLayer does not include the m_squashingContainmentLayer, which is technically not associated with this CLM's owning layer.
+    GraphicsLayer* localRootForOwningLayer() const;
+
+    GraphicsLayer* childTransformLayer() const { return m_childTransformLayer.get(); }
+
+    GraphicsLayer* squashingContainmentLayer() const { return m_squashingContainmentLayer.get(); }
+    GraphicsLayer* squashingLayer() const { return m_squashingLayer.get(); }
+    // Contains the bottommost layer in the hierarchy that can contain the children transform.
+    GraphicsLayer* layerForChildrenTransform() const;
 
     // Returns true for a composited layer that has no backing store of its own, so
     // paints into some ancestor layer.
@@ -135,40 +163,34 @@
     // Notification from the renderer that its content changed.
     void contentChanged(ContentChangeType);
 
-    // Interface to start, finish, suspend and resume animations and transitions
-    bool startTransition(double, CSSPropertyID, const RenderStyle* fromStyle, const RenderStyle* toStyle);
-    void transitionPaused(double timeOffset, CSSPropertyID);
-    void transitionFinished(CSSPropertyID);
-
-    bool startAnimation(double timeOffset, const CSSAnimationData*, const KeyframeList& keyframes);
-    void animationPaused(double timeOffset, const String& name);
-    void animationFinished(const String& name);
-
-    IntRect compositedBounds() const;
-    void setCompositedBounds(const IntRect&);
+    LayoutRect compositedBounds() const;
+    void setCompositedBounds(const LayoutRect&);
     void updateCompositedBounds();
 
     void updateAfterWidgetResize();
     void positionOverflowControlsLayers(const IntSize& offsetFromRoot);
     bool hasUnpositionedOverflowControlsLayers() const;
 
+    // Returns true if the assignment actually changed the assigned squashing layer.
+    bool updateSquashingLayerAssignment(RenderLayer*, IntSize offsetFromSquashingCLM, size_t nextSquashedLayerIndex);
+    void removeRenderLayerFromSquashingGraphicsLayer(const RenderLayer*);
+
+    void finishAccumulatingSquashingLayers(size_t nextSquashedLayerIndex);
+    void updateRenderingContext();
+    void updateShouldFlattenTransform();
+
     // GraphicsLayerClient interface
-    virtual void notifyAnimationStarted(const GraphicsLayer*, double startTime) OVERRIDE;
-
+    virtual void notifyAnimationStarted(const GraphicsLayer*, double wallClockTime, double monotonicTime) OVERRIDE;
     virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect& clip) OVERRIDE;
-
-    virtual void didCommitChangesForLayer(const GraphicsLayer*) const OVERRIDE;
-    virtual bool getCurrentTransform(const GraphicsLayer*, TransformationMatrix&) const OVERRIDE;
-
     virtual bool isTrackingRepaints() const OVERRIDE;
 
     PassOwnPtr<Vector<FloatRect> > collectTrackedRepaintRects() const;
 
 #ifndef NDEBUG
-    virtual void verifyNotPainting();
+    virtual void verifyNotPainting() OVERRIDE;
 #endif
 
-    IntRect contentsBox() const;
+    LayoutRect contentsBox() const;
     IntRect backgroundBox() const;
 
     // For informative purposes only.
@@ -181,24 +203,24 @@
     void updateFilters(const RenderStyle*);
     bool canCompositeFilters() const { return m_canCompositeFilters; }
 
-    // Return an estimate of the backing store area (in pixels) allocated by this object's GraphicsLayers.
-    double backingStoreMemoryEstimate() const;
-
     void setBlendMode(blink::WebBlendMode);
 
     virtual String debugName(const GraphicsLayer*) OVERRIDE;
 
+    LayoutSize subpixelAccumulation() const { return m_subpixelAccumulation; }
 private:
     void createPrimaryGraphicsLayer();
     void destroyGraphicsLayers();
 
     PassOwnPtr<GraphicsLayer> createGraphicsLayer(CompositingReasons);
+    bool toggleScrollbarLayerIfNeeded(OwnPtr<GraphicsLayer>&, bool needsLayer);
 
     RenderLayerModelObject* renderer() const { return m_owningLayer->renderer(); }
     RenderLayerCompositor* compositor() const { return m_owningLayer->compositor(); }
 
     void updateInternalHierarchy();
     bool updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip);
+    bool updateChildTransformLayer(bool needsChildTransformLayer);
     bool updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer);
     bool updateForegroundLayer(bool needsForegroundLayer);
     bool updateBackgroundLayer(bool needsBackgroundLayer);
@@ -210,19 +232,25 @@
     bool updateScrollingLayers(bool scrollingLayers);
     void updateScrollParent(RenderLayer*);
     void updateClipParent(RenderLayer*);
+    bool updateSquashingLayers(bool needsSquashingLayers);
     void updateDrawsContent(bool isSimpleContainer);
+    void updateChildrenTransform();
     void registerScrollingLayers();
 
+    void adjustBoundsForSubPixelAccumulation(const RenderLayer* compositedAncestor, IntRect& localCompositingBounds, IntRect& relativeCompositingBounds, IntPoint& delta);
+
     void setBackgroundLayerPaintsFixedRootBackground(bool);
 
     GraphicsLayerPaintingPhase paintingPhaseForPrimaryLayer() const;
 
-    IntSize contentOffsetInCompostingLayer() const;
+    LayoutSize contentOffsetInCompostingLayer() const;
     // Result is transform origin in pixels.
     FloatPoint3D computeTransformOrigin(const IntRect& borderBox) const;
     // Result is perspective origin in pixels.
     FloatPoint computePerspectiveOrigin(const IntRect& borderBox) const;
 
+    void updateSquashingLayerGeometry(const IntPoint& delta);
+
     void updateOpacity(const RenderStyle*);
     void updateTransform(const RenderStyle*);
     void updateLayerBlendMode(const RenderStyle*);
@@ -263,7 +291,7 @@
     //
     //  + m_ancestorClippingLayer [OPTIONAL]
     //     + m_graphicsLayer
-    //        + m_childContainmentLayer [OPTIONAL] <-OR-> m_scrollingLayer [OPTIONAL]
+    //        + m_childContainmentLayer [OPTIONAL] <-OR-> m_scrollingLayer [OPTIONAL] <-OR-> m_childTransformLayer
     //                                                     + m_scrollingContentsLayer [OPTIONAL]
     //
     // We need an ancestor clipping layer if our clipping ancestor is not our ancestor in the
@@ -289,6 +317,7 @@
     OwnPtr<GraphicsLayer> m_ancestorClippingLayer; // Only used if we are clipped by an ancestor which is not a stacking context.
     OwnPtr<GraphicsLayer> m_graphicsLayer;
     OwnPtr<GraphicsLayer> m_childContainmentLayer; // Only used if we have clipping on a stacking context with compositing children.
+    OwnPtr<GraphicsLayer> m_childTransformLayer; // Only used if we have perspective and no m_childContainmentLayer.
     OwnPtr<GraphicsLayer> m_scrollingLayer; // Only used if the layer is using composited scrolling.
     OwnPtr<GraphicsLayer> m_scrollingContentsLayer; // Only used if the layer is using composited scrolling.
 
@@ -327,12 +356,14 @@
     OwnPtr<GraphicsLayer> m_layerForVerticalScrollbar;
     OwnPtr<GraphicsLayer> m_layerForScrollCorner;
 
-    OwnPtr<WebAnimationProvider> m_animationProvider;
+    OwnPtr<GraphicsLayer> m_squashingContainmentLayer; // Only used if any squashed layers exist, to contain the squashed layers as siblings to the rest of the GraphicsLayer tree chunk.
+    OwnPtr<GraphicsLayer> m_squashingLayer; // Only used if any squashed layers exist, this is the backing that squashed layers paint into.
+    Vector<GraphicsLayerPaintInfo> m_squashedLayers;
 
-    IntRect m_compositedBounds;
+    LayoutRect m_compositedBounds;
+    LayoutSize m_subpixelAccumulation; // The accumulated subpixel offset of the compositedBounds compared to absolute coordinates.
 
     bool m_artificiallyInflatedBounds; // bounds had to be made non-zero to make transform-origin work
-    bool m_boundsConstrainedByClipping;
     bool m_isMainFrameRenderViewLayer;
     bool m_requiresOwnBackingStoreForIntrinsicReasons;
     bool m_requiresOwnBackingStoreForAncestorReasons;
diff --git a/Source/core/rendering/CompositingReasons.h b/Source/core/rendering/CompositingReasons.h
deleted file mode 100644
index b079990..0000000
--- a/Source/core/rendering/CompositingReasons.h
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CompositingReasons_h
-#define CompositingReasons_h
-
-#include "wtf/MathExtras.h"
-#include <stdint.h>
-
-namespace WebCore {
-
-const uint64_t CompositingReasonNone                                   = 0;
-
-// Intrinsic reasons that can be known right away by the layer
-const uint64_t CompositingReason3DTransform                            = UINT64_C(1) << 0;
-const uint64_t CompositingReasonVideo                                  = UINT64_C(1) << 1;
-const uint64_t CompositingReasonCanvas                                 = UINT64_C(1) << 2;
-const uint64_t CompositingReasonPlugin                                 = UINT64_C(1) << 3;
-const uint64_t CompositingReasonIFrame                                 = UINT64_C(1) << 4;
-const uint64_t CompositingReasonBackfaceVisibilityHidden               = UINT64_C(1) << 5;
-const uint64_t CompositingReasonAnimation                              = UINT64_C(1) << 6;
-const uint64_t CompositingReasonFilters                                = UINT64_C(1) << 7;
-const uint64_t CompositingReasonPositionFixed                          = UINT64_C(1) << 8;
-const uint64_t CompositingReasonPositionSticky                         = UINT64_C(1) << 9;
-const uint64_t CompositingReasonOverflowScrollingTouch                 = UINT64_C(1) << 10;
-
-// Overlap reasons that require knowing what's behind you in paint-order before knowing the answer
-const uint64_t CompositingReasonAssumedOverlap                         = UINT64_C(1) << 12;
-const uint64_t CompositingReasonOverlap                                = UINT64_C(1) << 13;
-const uint64_t CompositingReasonNegativeZIndexChildren                 = UINT64_C(1) << 14;
-
-// Subtree reasons that require knowing what the status of your subtree is before knowing the answer
-const uint64_t CompositingReasonTransformWithCompositedDescendants     = UINT64_C(1) << 15;
-const uint64_t CompositingReasonOpacityWithCompositedDescendants       = UINT64_C(1) << 16;
-const uint64_t CompositingReasonMaskWithCompositedDescendants          = UINT64_C(1) << 17;
-const uint64_t CompositingReasonReflectionWithCompositedDescendants    = UINT64_C(1) << 18;
-const uint64_t CompositingReasonFilterWithCompositedDescendants        = UINT64_C(1) << 19;
-const uint64_t CompositingReasonBlendingWithCompositedDescendants      = UINT64_C(1) << 20;
-const uint64_t CompositingReasonClipsCompositingDescendants            = UINT64_C(1) << 21;
-const uint64_t CompositingReasonPerspective                            = UINT64_C(1) << 22;
-const uint64_t CompositingReasonPreserve3D                             = UINT64_C(1) << 23;
-const uint64_t CompositingReasonReflectionOfCompositedParent           = UINT64_C(1) << 24;
-
-// The root layer is a special case that may be forced to be a layer, but also it needs to be
-// a layer if anything else in the subtree is composited.
-const uint64_t CompositingReasonRoot                                   = UINT64_C(1) << 25;
-
-// CompositedLayerMapping internal hierarchy reasons
-const uint64_t CompositingReasonLayerForClip                           = UINT64_C(1) << 26;
-const uint64_t CompositingReasonLayerForScrollbar                      = UINT64_C(1) << 27;
-const uint64_t CompositingReasonLayerForScrollingContainer             = UINT64_C(1) << 28;
-const uint64_t CompositingReasonLayerForForeground                     = UINT64_C(1) << 29;
-const uint64_t CompositingReasonLayerForBackground                     = UINT64_C(1) << 30;
-const uint64_t CompositingReasonLayerForMask                           = UINT64_C(1) << 31;
-
-// FIXME: the following compositing reasons need to be re-organized to fit with categories
-// used in all the other reasons above.
-const uint64_t CompositingReasonOverflowScrollingParent                = UINT64_C(1) << 32;
-const uint64_t CompositingReasonOutOfFlowClipping                      = UINT64_C(1) << 33;
-
-const uint64_t CompositingReasonLayerForVideoOverlay                   = UINT64_C(1) << 34;
-const uint64_t CompositingReasonIsolateCompositedDescendants           = UINT64_C(1) << 35;
-
-const uint64_t CompositingReasonComboAllDirectReasons =
-    CompositingReason3DTransform
-    | CompositingReasonVideo
-    | CompositingReasonCanvas
-    | CompositingReasonPlugin
-    | CompositingReasonIFrame
-    | CompositingReasonBackfaceVisibilityHidden
-    | CompositingReasonAnimation
-    | CompositingReasonFilters
-    | CompositingReasonPositionFixed
-    | CompositingReasonPositionSticky
-    | CompositingReasonOverflowScrollingTouch
-    | CompositingReasonOverflowScrollingParent
-    | CompositingReasonOutOfFlowClipping;
-
-const uint64_t CompositingReasonComboReasonsThatRequireOwnBacking =
-    CompositingReasonComboAllDirectReasons
-    | CompositingReasonOverlap
-    | CompositingReasonAssumedOverlap
-    | CompositingReasonNegativeZIndexChildren
-    | CompositingReasonTransformWithCompositedDescendants
-    | CompositingReasonOpacityWithCompositedDescendants
-    | CompositingReasonMaskWithCompositedDescendants
-    | CompositingReasonFilterWithCompositedDescendants
-    | CompositingReasonBlendingWithCompositedDescendants
-    | CompositingReasonIsolateCompositedDescendants
-    | CompositingReasonPreserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
-
-// Note: if you add more reasons here, you will need to update WebCompositingReasons as well.
-typedef uint64_t CompositingReasons;
-
-
-} // namespace WebCore
-
-#endif // CompositingReasons_h
diff --git a/Source/core/rendering/CompositingState.h b/Source/core/rendering/CompositingState.h
index fa44ae1..3873871 100644
--- a/Source/core/rendering/CompositingState.h
+++ b/Source/core/rendering/CompositingState.h
@@ -18,6 +18,10 @@
     HasOwnBackingButPaintsIntoAncestor = 1,
 
     PaintsIntoOwnBacking = 2,
+
+    // In this state, the RenderLayer subtree paints into a backing that is shared by
+    // several RenderLayer subtrees.
+    PaintsIntoGroupedBacking = 3
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/EllipsisBox.cpp b/Source/core/rendering/EllipsisBox.cpp
index be6213f..5eb42de 100644
--- a/Source/core/rendering/EllipsisBox.cpp
+++ b/Source/core/rendering/EllipsisBox.cpp
@@ -37,17 +37,29 @@
 {
     GraphicsContext* context = paintInfo.context;
     RenderStyle* style = m_renderer->style(isFirstLineStyle());
+
+    const Font& font = style->font();
+    FloatPoint boxOrigin = locationIncludingFlipping();
+    LayoutPoint adjustedPaintOffset = paintOffset;
+    if (!isHorizontal())
+        adjustedPaintOffset.move(0, -virtualLogicalHeight());
+    boxOrigin.move(adjustedPaintOffset.x(), adjustedPaintOffset.y());
+    FloatRect boxRect(boxOrigin, LayoutSize(logicalWidth(), virtualLogicalHeight()));
+    GraphicsContextStateSaver stateSaver(*context);
+    if (!isHorizontal())
+        context->concatCTM(InlineTextBox::rotation(boxRect, InlineTextBox::Clockwise));
+    FloatPoint textOrigin = FloatPoint(boxOrigin.x(), boxOrigin.y() + font.fontMetrics().ascent());
+
     Color styleTextColor = m_renderer->resolveColor(style, CSSPropertyWebkitTextFillColor);
     if (styleTextColor != context->fillColor())
         context->setFillColor(styleTextColor);
 
-    const Font& font = style->font();
     if (selectionState() != RenderObject::SelectionNone) {
-        paintSelection(context, paintOffset, style, font);
+        paintSelection(context, boxOrigin, style, font);
 
         // Select the correct color for painting the text.
         Color foreground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionForegroundColor();
-        if (foreground.isValid() && foreground != styleTextColor)
+        if (foreground != styleTextColor)
             context->setFillColor(foreground);
     }
 
@@ -58,10 +70,10 @@
         DrawLooper drawLooper;
         for (size_t i = shadowList->shadows().size(); i--; ) {
             const ShadowData& shadow = shadowList->shadows()[i];
-            int shadowX = isHorizontal() ? shadow.x() : shadow.y();
-            int shadowY = isHorizontal() ? shadow.y() : -shadow.x();
+            float shadowX = isHorizontal() ? shadow.x() : shadow.y();
+            float shadowY = isHorizontal() ? shadow.y() : -shadow.x();
             FloatSize offset(shadowX, shadowY);
-            drawLooper.addShadow(offset, shadow.blur(), m_renderer->resolveColor(shadow.color()),
+            drawLooper.addShadow(offset, shadow.blur(), shadow.color(),
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
         }
         drawLooper.addUnmodifiedContent();
@@ -69,10 +81,6 @@
     }
 
     // FIXME: Why is this always LTR? Fix by passing correct text run flags below.
-    FloatPoint boxOrigin(paintOffset);
-    boxOrigin.move(x(), y());
-    FloatRect boxRect(boxOrigin, LayoutSize(logicalWidth(), logicalHeight()));
-    FloatPoint textOrigin(boxOrigin.x(), boxOrigin.y() + style->fontMetrics().ascent());
     TextRun textRun = RenderBlockFlow::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion);
     TextRunPaintInfo textRunPaintInfo(textRun);
     textRunPaintInfo.bounds = boxRect;
@@ -124,14 +132,14 @@
     RenderStyle* style = m_renderer->style(isFirstLineStyle());
     const Font& font = style->font();
     // FIXME: Why is this always LTR? Fix by passing correct text run flags below.
-    return enclosingIntRect(font.selectionRectForText(RenderBlockFlow::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), IntPoint(x(), y() + root()->selectionTopAdjustedForPrecedingBlock()), root()->selectionHeightAdjustedForPrecedingBlock()));
+    return enclosingIntRect(font.selectionRectForText(RenderBlockFlow::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), IntPoint(logicalLeft(), logicalTop() + root()->selectionTopAdjustedForPrecedingBlock()), root()->selectionHeightAdjustedForPrecedingBlock()));
 }
 
-void EllipsisBox::paintSelection(GraphicsContext* context, const LayoutPoint& paintOffset, RenderStyle* style, const Font& font)
+void EllipsisBox::paintSelection(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font)
 {
     Color textColor = m_renderer->resolveColor(style, CSSPropertyColor);
     Color c = m_renderer->selectionBackgroundColor();
-    if (!c.isValid() || !c.alpha())
+    if (!c.alpha())
         return;
 
     // If the text color ends up being the same as the selection background, invert the selection
@@ -140,13 +148,16 @@
         c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
 
     GraphicsContextStateSaver stateSaver(*context);
+    LayoutUnit selectionBottom = root()->selectionBottom();
     LayoutUnit top = root()->selectionTop();
     LayoutUnit h = root()->selectionHeight();
-    FloatRect clipRect(x() + paintOffset.x(), top + paintOffset.y(), m_logicalWidth, h);
+    const int deltaY = roundToInt(renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - top);
+    const FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
+    FloatRect clipRect(localOrigin, FloatSize(m_logicalWidth, h));
     alignSelectionRectToDevicePixels(clipRect);
     context->clip(clipRect);
     // FIXME: Why is this always LTR? Fix by passing correct text run flags below.
-    context->drawHighlightForText(font, RenderBlockFlow::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), roundedIntPoint(LayoutPoint(x() + paintOffset.x(), y() + paintOffset.y() + top)), h, c);
+    context->drawHighlightForText(font, RenderBlockFlow::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), localOrigin, h, c);
 }
 
 bool EllipsisBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
@@ -164,7 +175,9 @@
         }
     }
 
-    LayoutRect boundsRect(adjustedLocation, LayoutSize(m_logicalWidth, m_height));
+    FloatPoint boxOrigin = locationIncludingFlipping();
+    boxOrigin.moveBy(accumulatedOffset);
+    FloatRect boundsRect(boxOrigin, size());
     if (visibleToHitTestRequest(request) && boundsRect.intersects(HitTestLocation::rectForPoint(locationInContainer.point(), 0, 0, 0, 0))) {
         renderer()->updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
         if (!result.addNodeToRectBasedTestResult(renderer()->node(), request, locationInContainer, boundsRect))
diff --git a/Source/core/rendering/EllipsisBox.h b/Source/core/rendering/EllipsisBox.h
index 9382e77..149a851 100644
--- a/Source/core/rendering/EllipsisBox.h
+++ b/Source/core/rendering/EllipsisBox.h
@@ -30,25 +30,27 @@
 class EllipsisBox FINAL : public InlineBox {
 public:
     EllipsisBox(RenderObject* obj, const AtomicString& ellipsisStr, InlineFlowBox* parent,
-                int width, int height, int y, bool firstLine, bool isVertical, InlineBox* markupBox)
-        : InlineBox(obj, FloatPoint(0, y), width, firstLine, true, false, false, isVertical, 0, 0, parent)
+        int width, int height, int x, int y, bool firstLine, bool isVertical, InlineBox* markupBox)
+        : InlineBox(obj, FloatPoint(x, y), width, firstLine, true, false, false, isVertical, 0, 0, parent)
         , m_shouldPaintMarkupBox(markupBox)
         , m_height(height)
         , m_str(ellipsisStr)
         , m_selectionState(RenderObject::SelectionNone)
     {
+        setHasVirtualLogicalHeight();
     }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom);
+    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
     void setSelectionState(RenderObject::SelectionState s) { m_selectionState = s; }
     IntRect selectionRect();
 
+    virtual float virtualLogicalHeight() const OVERRIDE { return m_height; }
 private:
     void paintMarkupBox(PaintInfo&, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom, RenderStyle*);
-    virtual int height() const { return m_height; }
-    virtual RenderObject::SelectionState selectionState() { return m_selectionState; }
-    void paintSelection(GraphicsContext*, const LayoutPoint&, RenderStyle*, const Font&);
+    int height() const { return m_height; }
+    virtual RenderObject::SelectionState selectionState() OVERRIDE { return m_selectionState; }
+    void paintSelection(GraphicsContext*, const FloatPoint&, RenderStyle*, const Font&);
     InlineBox* markupBox() const;
 
     bool m_shouldPaintMarkupBox;
diff --git a/Source/core/rendering/FastTextAutosizer.cpp b/Source/core/rendering/FastTextAutosizer.cpp
index 11d33da..6b9d0df 100644
--- a/Source/core/rendering/FastTextAutosizer.cpp
+++ b/Source/core/rendering/FastTextAutosizer.cpp
@@ -32,101 +32,524 @@
 #include "core/rendering/FastTextAutosizer.h"
 
 #include "core/dom/Document.h"
-#include "core/page/Settings.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
+#include "core/page/Page.h"
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderListItem.h"
+#include "core/rendering/RenderListMarker.h"
+#include "core/rendering/RenderView.h"
 #include "core/rendering/TextAutosizer.h"
 
+using namespace std;
+
 namespace WebCore {
 
-FastTextAutosizer::FastTextAutosizer(Document* document)
+FastTextAutosizer::FastTextAutosizer(const Document* document)
     : m_document(document)
+#ifndef NDEBUG
+    , m_renderViewInfoPrepared(false)
+#endif
 {
 }
 
 void FastTextAutosizer::record(const RenderBlock* block)
 {
-    if (!m_document->settings()
-        || !m_document->settings()->textAutosizingEnabled()
-        || m_document->printing()
-        || !m_document->page())
+    if (!enabled())
         return;
 
-    if (!TextAutosizer::isAutosizingContainer(block))
+    ASSERT(!m_blocksThatHaveBegunLayout.contains(block));
+
+    if (!isFingerprintingCandidate(block))
         return;
 
-    AtomicString blockFingerprint = fingerprint(block);
-    HashMap<AtomicString, OwnPtr<Cluster> >::AddResult result =
-        m_clusterForFingerprint.add(blockFingerprint, PassOwnPtr<Cluster>());
+    AtomicString fingerprint = computeFingerprint(block);
+    if (fingerprint.isNull())
+        return;
 
-    if (result.isNewEntry)
-        result.iterator->value = adoptPtr(new Cluster(blockFingerprint));
-
-    Cluster* cluster = result.iterator->value.get();
-    cluster->m_blocks.add(block);
-
-    m_clusterForBlock.set(block, cluster);
+    m_fingerprintMapper.add(block, fingerprint);
 }
 
 void FastTextAutosizer::destroy(const RenderBlock* block)
 {
-    Cluster* cluster = m_clusterForBlock.take(block);
-    if (!cluster)
+    if (!enabled())
         return;
-    cluster->m_blocks.remove(block);
-    if (cluster->m_blocks.isEmpty()) {
-        // This deletes the Cluster.
-        m_clusterForFingerprint.remove(cluster->m_fingerprint);
+    ASSERT(!m_blocksThatHaveBegunLayout.contains(block));
+
+    m_fingerprintMapper.remove(block);
+}
+
+bool FastTextAutosizer::isLayoutRoot(const RenderBlock* block) const
+{
+    RenderObject* layoutRoot = m_document->view()->layoutRoot(true);
+    if (!layoutRoot)
+        layoutRoot = m_document->renderer();
+    return block == layoutRoot;
+}
+
+void FastTextAutosizer::beginLayout(RenderBlock* block)
+{
+    ASSERT(enabled());
+#ifndef NDEBUG
+    m_blocksThatHaveBegunLayout.add(block);
+#endif
+    ASSERT(m_clusterStack.isEmpty() == isLayoutRoot(block));
+
+    if (isLayoutRoot(block)) {
+        prepareRenderViewInfo();
+    } else if (block == currentCluster()->m_root) {
+        // Ignore beginLayout on the same block twice.
+        // This can happen with paginated overflow.
         return;
     }
-    cluster->m_multiplier = 0;
+
+    if (Cluster* cluster = maybeCreateCluster(block))
+        m_clusterStack.append(adoptPtr(cluster));
+
+    if (block->childrenInline())
+        inflate(block);
+}
+
+void FastTextAutosizer::inflateListItem(RenderListItem* listItem, RenderListMarker* listItemMarker)
+{
+    if (!enabled())
+        return;
+    ASSERT(listItem && listItemMarker);
+#ifndef NDEBUG
+    m_blocksThatHaveBegunLayout.add(listItem);
+#endif
+    // Force the LI to be inside the DBCAT when computing the multiplier.
+    // This guarantees that the DBCAT has entered layout, so we can ask for its width.
+    // It also makes sense because the list marker is autosized like a text node.
+    float multiplier = clusterMultiplier(currentCluster());
+
+    applyMultiplier(listItem, multiplier);
+    applyMultiplier(listItemMarker, multiplier);
+}
+
+void FastTextAutosizer::endLayout(RenderBlock* block)
+{
+    ASSERT(enabled());
+    if (isLayoutRoot(block)) {
+        m_superclusters.clear();
+#ifndef NDEBUG
+        m_blocksThatHaveBegunLayout.clear();
+#endif
+    }
+
+    if (currentCluster()->m_root == block)
+        m_clusterStack.removeLast();
+
+    ASSERT(m_clusterStack.isEmpty() == isLayoutRoot(block));
 }
 
 void FastTextAutosizer::inflate(RenderBlock* block)
 {
-    Cluster* cluster = 0;
-    for (const RenderObject* clusterBlock = block; clusterBlock && !cluster; clusterBlock = clusterBlock->parent()) {
-        if (clusterBlock->isRenderBlock())
-            cluster = m_clusterForBlock.get(toRenderBlock(clusterBlock));
-    }
-    if (!cluster)
-        return;
-    if (!cluster->m_multiplier)
-        cluster->m_multiplier = computeMultiplier(cluster);
-    if (cluster->m_multiplier == 1)
-        return;
-
-    for (InlineWalker walker(block); !walker.atEnd(); walker.advance()) {
-        RenderObject* inlineObj = walker.current();
-        if (inlineObj->isRenderBlock() && m_clusterForBlock.contains(toRenderBlock(inlineObj)))
-            continue;
-
-        RefPtr<RenderStyle> style = RenderStyle::clone(inlineObj->style());
-        style->setTextAutosizingMultiplier(cluster->m_multiplier);
-        style->setUnique();
-        inlineObj->setStyleInternal(style.release());
+    Cluster* cluster = currentCluster();
+    float multiplier = 0;
+    for (RenderObject* descendant = nextChildSkippingChildrenOfBlocks(block, block); descendant; descendant = nextChildSkippingChildrenOfBlocks(descendant, block)) {
+        if (descendant->isText()) {
+            // We only calculate this multiplier on-demand to ensure the parent block of this text
+            // has entered layout.
+            if (!multiplier)
+                multiplier = cluster->m_autosize ? clusterMultiplier(cluster) : 1.0f;
+            applyMultiplier(descendant, multiplier);
+            applyMultiplier(descendant->parent(), multiplier); // Parent handles line spacing.
+        }
     }
 }
 
-AtomicString FastTextAutosizer::fingerprint(const RenderBlock* block)
+bool FastTextAutosizer::enabled()
 {
-    // FIXME(crbug.com/322340): Implement a better fingerprinting algorithm.
-    return String::number((unsigned long long) block);
+    if (!m_document->settings() || !m_document->page() || m_document->printing())
+        return false;
+
+    return m_document->settings()->textAutosizingEnabled();
 }
 
-float FastTextAutosizer::computeMultiplier(const FastTextAutosizer::Cluster* cluster)
+void FastTextAutosizer::prepareRenderViewInfo()
 {
-    const WTF::HashSet<const RenderBlock*>& blocks = cluster->m_blocks;
+    RenderView* renderView = toRenderView(m_document->renderer());
+    bool horizontalWritingMode = isHorizontalWritingMode(renderView->style()->writingMode());
 
-    bool shouldAutosize = false;
-    for (WTF::HashSet<const RenderBlock*>::iterator it = blocks.begin(); it != blocks.end(); ++it)
-        shouldAutosize |= TextAutosizer::containerShouldBeAutosized(*it);
+    Frame* mainFrame = m_document->page()->mainFrame();
+    IntSize frameSize = m_document->settings()->textAutosizingWindowSizeOverride();
+    if (frameSize.isEmpty())
+        frameSize = mainFrame->view()->unscaledVisibleContentSize(ScrollableArea::IncludeScrollbars);
+    m_frameWidth = horizontalWritingMode ? frameSize.width() : frameSize.height();
 
-    if (!shouldAutosize)
-        return 1.0f;
+    IntSize layoutSize = m_document->page()->mainFrame()->view()->layoutSize();
+    m_layoutWidth = horizontalWritingMode ? layoutSize.width() : layoutSize.height();
 
-    // FIXME(crbug.com/322344): Implement multiplier computation.
-    return 1.5f;
+    // Compute the base font scale multiplier based on device and accessibility settings.
+    m_baseMultiplier = m_document->settings()->accessibilityFontScaleFactor();
+    // If the page has a meta viewport or @viewport, don't apply the device scale adjustment.
+    const ViewportDescription& viewportDescription = m_document->page()->mainFrame()->document()->viewportDescription();
+    if (!viewportDescription.isSpecifiedByAuthor()) {
+        float deviceScaleAdjustment = m_document->settings()->deviceScaleAdjustment();
+        m_baseMultiplier *= deviceScaleAdjustment;
+    }
+#ifndef NDEBUG
+    m_renderViewInfoPrepared = true;
+#endif
+}
+
+bool FastTextAutosizer::isFingerprintingCandidate(const RenderBlock* block)
+{
+    // FIXME: move the logic out of TextAutosizer.cpp into this class.
+    return block->isRenderView()
+        || (TextAutosizer::isAutosizingContainer(block)
+            && TextAutosizer::isIndependentDescendant(block));
+}
+
+bool FastTextAutosizer::clusterWouldHaveEnoughTextToAutosize(const RenderBlock* root)
+{
+    Cluster hypotheticalCluster(root, true, 0);
+    return clusterHasEnoughTextToAutosize(&hypotheticalCluster);
+}
+
+bool FastTextAutosizer::clusterHasEnoughTextToAutosize(Cluster* cluster)
+{
+    const RenderBlock* root = cluster->m_root;
+
+    // TextAreas and user-modifiable areas get a free pass to autosize regardless of text content.
+    if (root->isTextArea() || (root->style() && root->style()->userModify() != READ_ONLY))
+        return true;
+
+    static const float minLinesOfText = 4;
+    if (textLength(cluster) >= root->contentLogicalWidth() * minLinesOfText)
+        return true;
+
+    return false;
+}
+
+float FastTextAutosizer::textLength(Cluster* cluster)
+{
+    if (cluster->m_textLength >= 0)
+        return cluster->m_textLength;
+
+    float length = 0;
+    const RenderBlock* root = cluster->m_root;
+    bool measureLocalText = TextAutosizer::containerShouldBeAutosized(root);
+    RenderObject* descendant = root->nextInPreOrder(root);
+    while (descendant) {
+        // FIXME: We should skip over text from descendant clusters (see:
+        //        clusters-sufficient-text-except-in-root.html). This currently includes text
+        //        from descendant clusters.
+
+        if (measureLocalText && descendant->isText()) {
+            // Note: Using text().stripWhiteSpace().length() instead of renderedTextLength() because
+            // the lineboxes will not be built until layout. These values can be different.
+            length += toRenderText(descendant)->text().stripWhiteSpace().length() * descendant->style()->specifiedFontSize();
+        }
+        descendant = descendant->nextInPreOrder(root);
+    }
+
+    return cluster->m_textLength = length;
+}
+
+AtomicString FastTextAutosizer::computeFingerprint(const RenderBlock* block)
+{
+    // FIXME(crbug.com/322340): Implement a fingerprinting algorithm.
+    return nullAtom;
+}
+
+FastTextAutosizer::Cluster* FastTextAutosizer::maybeCreateCluster(const RenderBlock* block)
+{
+    if (!TextAutosizer::isAutosizingContainer(block))
+        return 0;
+
+    Cluster* parentCluster = m_clusterStack.isEmpty() ? 0 : currentCluster();
+    ASSERT(parentCluster || isLayoutRoot(block));
+
+    // Create clusters to suppress / unsuppress autosizing based on containerShouldBeAutosized.
+    bool containerCanAutosize = TextAutosizer::containerShouldBeAutosized(block);
+    bool parentClusterCanAutosize = parentCluster && parentCluster->m_autosize;
+    bool createClusterThatMightAutosize = isLayoutRoot(block)
+        || mightBeWiderOrNarrowerDescendant(block)
+        || TextAutosizer::isIndependentDescendant(block);
+
+    // If the container would not alter the m_autosize bit, it doesn't need to be a cluster.
+    if (!createClusterThatMightAutosize && containerCanAutosize == parentClusterCanAutosize)
+        return 0;
+
+    return new Cluster(block, containerCanAutosize, parentCluster, getSupercluster(block));
+}
+
+FastTextAutosizer::Supercluster* FastTextAutosizer::getSupercluster(const RenderBlock* block)
+{
+    AtomicString fingerprint = m_fingerprintMapper.get(block);
+    if (fingerprint.isNull())
+        return 0;
+
+    BlockSet* roots = &m_fingerprintMapper.getBlocks(fingerprint);
+    if (roots->size() < 2)
+        return 0;
+
+    SuperclusterMap::AddResult addResult = m_superclusters.add(fingerprint, PassOwnPtr<Supercluster>());
+    if (!addResult.isNewEntry)
+        return addResult.storedValue->value.get();
+
+    Supercluster* supercluster = new Supercluster(roots);
+    addResult.storedValue->value = adoptPtr(supercluster);
+    return supercluster;
+}
+
+const RenderBlock* FastTextAutosizer::deepestCommonAncestor(BlockSet& blocks)
+{
+    // Find the lowest common ancestor of blocks.
+    // Note: this could be improved to not be O(b*h) for b blocks and tree height h.
+    HashCountedSet<const RenderBlock*> ancestors;
+    for (BlockSet::iterator it = blocks.begin(); it != blocks.end(); ++it) {
+        for (const RenderBlock* block = (*it); block; block = block->containingBlock()) {
+            ancestors.add(block);
+            // The first ancestor that has all of the blocks as children wins.
+            if (ancestors.count(block) == blocks.size())
+                return block;
+        }
+    }
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
+float FastTextAutosizer::clusterMultiplier(Cluster* cluster)
+{
+    ASSERT(m_renderViewInfoPrepared);
+    if (!cluster->m_multiplier) {
+
+        if (isLayoutRoot(cluster->m_root)
+            || TextAutosizer::isIndependentDescendant(cluster->m_root)
+            || isWiderDescendant(cluster)
+            || isNarrowerDescendant(cluster)) {
+
+            if (cluster->m_supercluster) {
+                cluster->m_multiplier = superclusterMultiplier(cluster->m_supercluster);
+            } else if (clusterHasEnoughTextToAutosize(cluster)) {
+                cluster->m_multiplier = multiplierFromBlock(deepestBlockContainingAllText(cluster));
+            } else {
+                cluster->m_multiplier = 1.0f;
+            }
+        } else {
+            cluster->m_multiplier = cluster->m_parent ? clusterMultiplier(cluster->m_parent) : 1.0f;
+        }
+    }
+    ASSERT(cluster->m_multiplier);
+    return cluster->m_multiplier;
+}
+
+float FastTextAutosizer::superclusterMultiplier(Supercluster* supercluster)
+{
+    if (!supercluster->m_multiplier) {
+        const BlockSet* roots = supercluster->m_roots;
+        // Set of the deepest block containing all text (DBCAT) of every cluster.
+        BlockSet dbcats;
+        for (BlockSet::iterator it = roots->begin(); it != roots->end(); ++it) {
+            dbcats.add(deepestBlockContainingAllText(*it));
+            supercluster->m_anyClusterHasEnoughText |= clusterWouldHaveEnoughTextToAutosize(*it);
+        }
+        supercluster->m_multiplier = supercluster->m_anyClusterHasEnoughText
+            ? multiplierFromBlock(deepestCommonAncestor(dbcats)) : 1.0f;
+    }
+    ASSERT(supercluster->m_multiplier);
+    return supercluster->m_multiplier;
+}
+
+float FastTextAutosizer::multiplierFromBlock(const RenderBlock* block)
+{
+    // If block->needsLayout() is false, it does not need to be in m_blocksThatHaveBegunLayout.
+    // This can happen during layout of a positioned object if the cluster's DBCAT is deeper
+    // than the positioned object's containing block, and wasn't marked as needing layout.
+    ASSERT(m_blocksThatHaveBegunLayout.contains(block) || !block->needsLayout());
+
+    // Block width, in CSS pixels.
+    float textBlockWidth = block->contentLogicalWidth();
+    float multiplier = min(textBlockWidth, static_cast<float>(m_layoutWidth)) / m_frameWidth;
+
+    return max(m_baseMultiplier * multiplier, 1.0f);
+}
+
+const RenderBlock* FastTextAutosizer::deepestBlockContainingAllText(Cluster* cluster)
+{
+    if (!cluster->m_deepestBlockContainingAllText)
+        cluster->m_deepestBlockContainingAllText = deepestBlockContainingAllText(cluster->m_root);
+
+    return cluster->m_deepestBlockContainingAllText;
+}
+
+// FIXME: Refactor this to look more like FastTextAutosizer::deepestCommonAncestor. This is copied
+//        from TextAutosizer::findDeepestBlockContainingAllText.
+const RenderBlock* FastTextAutosizer::deepestBlockContainingAllText(const RenderBlock* root)
+{
+    size_t firstDepth = 0;
+    const RenderObject* firstTextLeaf = findTextLeaf(root, firstDepth, First);
+    if (!firstTextLeaf)
+        return root;
+
+    size_t lastDepth = 0;
+    const RenderObject* lastTextLeaf = findTextLeaf(root, lastDepth, Last);
+    ASSERT(lastTextLeaf);
+
+    // Equalize the depths if necessary. Only one of the while loops below will get executed.
+    const RenderObject* firstNode = firstTextLeaf;
+    const RenderObject* lastNode = lastTextLeaf;
+    while (firstDepth > lastDepth) {
+        firstNode = firstNode->parent();
+        --firstDepth;
+    }
+    while (lastDepth > firstDepth) {
+        lastNode = lastNode->parent();
+        --lastDepth;
+    }
+
+    // Go up from both nodes until the parent is the same. Both pointers will point to the LCA then.
+    while (firstNode != lastNode) {
+        firstNode = firstNode->parent();
+        lastNode = lastNode->parent();
+    }
+
+    if (firstNode->isRenderBlock())
+        return toRenderBlock(firstNode);
+
+    // containingBlock() should never leave the cluster, since it only skips ancestors when finding
+    // the container of position:absolute/fixed blocks, and those cannot exist between a cluster and
+    // its text node's lowest common ancestor as isAutosizingCluster would have made them into their
+    // own independent cluster.
+    const RenderBlock* containingBlock = firstNode->containingBlock();
+    ASSERT(containingBlock->isDescendantOf(root));
+
+    return containingBlock;
+}
+
+const RenderObject* FastTextAutosizer::findTextLeaf(const RenderObject* parent, size_t& depth, TextLeafSearch firstOrLast)
+{
+    // List items are treated as text due to the marker.
+    // The actual renderer for the marker (RenderListMarker) may not be in the tree yet since it is added during layout.
+    if (parent->isListItem())
+        return parent;
+
+    if (parent->isEmpty())
+        return parent->isText() ? parent : 0;
+
+    ++depth;
+    const RenderObject* child = (firstOrLast == First) ? parent->firstChild() : parent->lastChild();
+    while (child) {
+        // Note: At this point clusters may not have been created for these blocks so we cannot rely
+        //       on m_clusters. Instead, we use a best-guess about whether the block will become a cluster.
+        if (!TextAutosizer::isAutosizingContainer(child) || !TextAutosizer::isIndependentDescendant(toRenderBlock(child))) {
+            const RenderObject* leaf = findTextLeaf(child, depth, firstOrLast);
+            if (leaf)
+                return leaf;
+        }
+        child = (firstOrLast == First) ? child->nextSibling() : child->previousSibling();
+    }
+    --depth;
+
+    return 0;
+}
+
+void FastTextAutosizer::applyMultiplier(RenderObject* renderer, float multiplier)
+{
+    ASSERT(renderer);
+    RenderStyle* currentStyle = renderer->style();
+    if (currentStyle->textAutosizingMultiplier() == multiplier)
+        return;
+
+    // We need to clone the render style to avoid breaking style sharing.
+    RefPtr<RenderStyle> style = RenderStyle::clone(currentStyle);
+    style->setTextAutosizingMultiplier(multiplier);
+    style->setUnique();
+    renderer->setStyleInternal(style.release());
+}
+
+bool FastTextAutosizer::mightBeWiderOrNarrowerDescendant(const RenderBlock* block)
+{
+    // FIXME: This heuristic may need to be expanded to other ways a block can be wider or narrower
+    //        than its parent containing block.
+    return block->style() && block->style()->width().isSpecified();
+}
+
+bool FastTextAutosizer::isWiderDescendant(Cluster* cluster)
+{
+    if (!cluster->m_parent || !mightBeWiderOrNarrowerDescendant(cluster->m_root))
+        return true;
+    const RenderBlock* parentDeepestBlockContainingAllText = deepestBlockContainingAllText(cluster->m_parent);
+    ASSERT(m_blocksThatHaveBegunLayout.contains(cluster->m_root));
+    ASSERT(m_blocksThatHaveBegunLayout.contains(parentDeepestBlockContainingAllText));
+
+    // Clusters with a root that is wider than the deepestBlockContainingAllText of their parent
+    // autosize independently of their parent. Otherwise, they fall back to their parent's multiplier.
+    float contentWidth = cluster->m_root->contentLogicalWidth();
+    float clusterTextWidth = parentDeepestBlockContainingAllText->contentLogicalWidth();
+    return contentWidth > clusterTextWidth;
+}
+
+bool FastTextAutosizer::isNarrowerDescendant(Cluster* cluster)
+{
+    static float narrowWidthDifference = 200;
+
+    if (!cluster->m_parent || !mightBeWiderOrNarrowerDescendant(cluster->m_root))
+        return true;
+
+    const RenderBlock* parentDeepestBlockContainingAllText = deepestBlockContainingAllText(cluster->m_parent);
+    ASSERT(m_blocksThatHaveBegunLayout.contains(cluster->m_root));
+    ASSERT(m_blocksThatHaveBegunLayout.contains(parentDeepestBlockContainingAllText));
+
+    // Clusters with a root that is significantly narrower than the deepestBlockContainingAllText of
+    // their parent autosize independently of their parent. Otherwise, they fall back to their
+    // parent's multiplier.
+    float contentWidth = cluster->m_root->contentLogicalWidth();
+    float clusterTextWidth = parentDeepestBlockContainingAllText->contentLogicalWidth();
+    float widthDifference = clusterTextWidth - contentWidth;
+
+    return widthDifference > narrowWidthDifference;
+}
+
+FastTextAutosizer::Cluster* FastTextAutosizer::currentCluster() const
+{
+    ASSERT(!m_clusterStack.isEmpty());
+    return m_clusterStack.last().get();
+}
+
+void FastTextAutosizer::FingerprintMapper::add(const RenderBlock* block, AtomicString fingerprint)
+{
+    m_fingerprints.set(block, fingerprint);
+
+    ReverseFingerprintMap::AddResult addResult = m_blocksForFingerprint.add(fingerprint, PassOwnPtr<BlockSet>());
+    if (addResult.isNewEntry)
+        addResult.storedValue->value = adoptPtr(new BlockSet);
+    addResult.storedValue->value->add(block);
+}
+
+void FastTextAutosizer::FingerprintMapper::remove(const RenderBlock* block)
+{
+    AtomicString fingerprint = m_fingerprints.take(block);
+    if (fingerprint.isNull())
+        return;
+
+    ReverseFingerprintMap::iterator blocksIter = m_blocksForFingerprint.find(fingerprint);
+    BlockSet& blocks = *blocksIter->value;
+    blocks.remove(block);
+    if (blocks.isEmpty())
+        m_blocksForFingerprint.remove(blocksIter);
+}
+
+AtomicString FastTextAutosizer::FingerprintMapper::get(const RenderBlock* block)
+{
+    return m_fingerprints.get(block);
+}
+
+FastTextAutosizer::BlockSet& FastTextAutosizer::FingerprintMapper::getBlocks(AtomicString fingerprint)
+{
+    return *m_blocksForFingerprint.get(fingerprint);
+}
+
+RenderObject* FastTextAutosizer::nextChildSkippingChildrenOfBlocks(const RenderObject* current, const RenderObject* stayWithin)
+{
+    if (current == stayWithin || !current->isRenderBlock())
+        return current->nextInPreOrder(stayWithin);
+    return current->nextInPreOrderAfterChildren(stayWithin);
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/FastTextAutosizer.h b/Source/core/rendering/FastTextAutosizer.h
index 16265fd..50ba1bd 100644
--- a/Source/core/rendering/FastTextAutosizer.h
+++ b/Source/core/rendering/FastTextAutosizer.h
@@ -31,6 +31,8 @@
 #ifndef FastTextAutosizer_h
 #define FastTextAutosizer_h
 
+#include "core/rendering/RenderObject.h"
+#include "core/rendering/TextAutosizer.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/Noncopyable.h"
@@ -42,6 +44,8 @@
 
 class Document;
 class RenderBlock;
+class RenderListItem;
+class RenderListMarker;
 
 // Single-pass text autosizer (work in progress). Works in two stages:
 // (1) record information about page elements during style recalc
@@ -52,38 +56,164 @@
     WTF_MAKE_NONCOPYABLE(FastTextAutosizer);
 
 public:
-    static PassOwnPtr<FastTextAutosizer> create(Document* document)
+    static PassOwnPtr<FastTextAutosizer> create(const Document* document)
     {
         return adoptPtr(new FastTextAutosizer(document));
     }
 
     void record(const RenderBlock*);
     void destroy(const RenderBlock*);
-    void inflate(RenderBlock*);
+    void inflateListItem(RenderListItem*, RenderListMarker*);
+
+    class LayoutScope {
+    public:
+        explicit LayoutScope(Document& document, RenderBlock* block)
+        {
+            m_textAutosizer = document.fastTextAutosizer();
+            if (m_textAutosizer) {
+                if (!m_textAutosizer->enabled()) {
+                    m_textAutosizer = 0;
+                    return;
+                }
+                m_block = block;
+                m_textAutosizer->beginLayout(m_block);
+            }
+        }
+
+        ~LayoutScope()
+        {
+            if (m_textAutosizer)
+                m_textAutosizer->endLayout(m_block);
+        }
+    private:
+        FastTextAutosizer* m_textAutosizer;
+        RenderBlock* m_block;
+    };
 
 private:
-    // TODO: make a proper API for this class?
-    struct Cluster {
-        explicit Cluster(AtomicString fingerprint)
-            : m_fingerprint(fingerprint)
+    typedef HashSet<const RenderBlock*> BlockSet;
+
+    // A supercluster represents autosizing information about a set of two or
+    // more blocks that all have the same fingerprint. Clusters whose roots
+    // belong to a supercluster will share a common multiplier and
+    // text-length-based autosizing status.
+    struct Supercluster {
+        explicit Supercluster(const BlockSet* roots)
+            : m_roots(roots)
             , m_multiplier(0)
+            , m_anyClusterHasEnoughText(false)
         {
         }
 
-        AtomicString m_fingerprint;
-        WTF::HashSet<const RenderBlock*> m_blocks;
+        const BlockSet* const m_roots;
         float m_multiplier;
+        bool m_anyClusterHasEnoughText;
     };
 
-    explicit FastTextAutosizer(Document*);
+    struct Cluster {
+        explicit Cluster(const RenderBlock* root, bool autosize, Cluster* parent, Supercluster* supercluster = 0)
+            : m_root(root)
+            , m_deepestBlockContainingAllText(0)
+            , m_parent(parent)
+            , m_autosize(autosize)
+            , m_multiplier(0)
+            , m_textLength(-1)
+            , m_supercluster(supercluster)
+        {
+        }
 
-    AtomicString fingerprint(const RenderBlock*);
-    float computeMultiplier(const Cluster*);
+        const RenderBlock* const m_root;
+        // The deepest block containing all text is computed lazily (see:
+        // deepestBlockContainingAllText). A value of 0 indicates the value has not been computed yet.
+        const RenderBlock* m_deepestBlockContainingAllText;
+        Cluster* m_parent;
+        bool m_autosize;
+        // The multiplier is computed lazily (see: clusterMultiplier) because it must be calculated
+        // after the lowest block containing all text has entered layout (the
+        // m_blocksThatHaveBegunLayout assertions cover this). Note: the multiplier is still
+        // calculated when m_autosize is false because child clusters may depend on this multiplier.
+        float m_multiplier;
+        // Text length is computed lazily (see: textLength). This is an approximation and characters
+        // are assumed to be 1em wide. Negative values indicate the length has not been computed.
+        int m_textLength;
+        // A set of blocks that are similar to this block.
+        Supercluster* m_supercluster;
+    };
 
-    Document* m_document;
+    enum TextLeafSearch {
+        First,
+        Last
+    };
 
-    WTF::HashMap<const RenderBlock*, Cluster*> m_clusterForBlock;
-    WTF::HashMap<AtomicString, OwnPtr<Cluster> > m_clusterForFingerprint;
+    typedef HashMap<AtomicString, OwnPtr<Supercluster> > SuperclusterMap;
+    typedef Vector<OwnPtr<Cluster> > ClusterStack;
+
+    // Fingerprints are computed during style recalc, for (some subset of)
+    // blocks that will become cluster roots.
+    class FingerprintMapper {
+    public:
+        void add(const RenderBlock*, AtomicString);
+        void remove(const RenderBlock*);
+        AtomicString get(const RenderBlock*);
+        BlockSet& getBlocks(AtomicString);
+    private:
+        typedef HashMap<const RenderBlock*, AtomicString> FingerprintMap;
+        typedef HashMap<AtomicString, OwnPtr<BlockSet> > ReverseFingerprintMap;
+
+        FingerprintMap m_fingerprints;
+        ReverseFingerprintMap m_blocksForFingerprint;
+    };
+
+    explicit FastTextAutosizer(const Document*);
+
+    void beginLayout(RenderBlock*);
+    void endLayout(RenderBlock*);
+    void inflate(RenderBlock*);
+    bool enabled();
+    void prepareRenderViewInfo();
+    bool isFingerprintingCandidate(const RenderBlock*);
+    bool clusterHasEnoughTextToAutosize(Cluster*);
+    bool clusterWouldHaveEnoughTextToAutosize(const RenderBlock*);
+    float textLength(Cluster*);
+    AtomicString computeFingerprint(const RenderBlock*);
+    Cluster* maybeCreateCluster(const RenderBlock*);
+    Supercluster* getSupercluster(const RenderBlock*);
+    const RenderBlock* deepestCommonAncestor(BlockSet&);
+    float clusterMultiplier(Cluster*);
+    float superclusterMultiplier(Supercluster*);
+    float multiplierFromBlock(const RenderBlock*);
+    void applyMultiplier(RenderObject*, float);
+    bool mightBeWiderOrNarrowerDescendant(const RenderBlock*);
+    bool isWiderDescendant(Cluster*);
+    bool isNarrowerDescendant(Cluster*);
+    bool isLayoutRoot(const RenderBlock*) const;
+
+    Cluster* currentCluster() const;
+
+    RenderObject* nextChildSkippingChildrenOfBlocks(const RenderObject*, const RenderObject*);
+
+    const RenderBlock* deepestBlockContainingAllText(Cluster*);
+    const RenderBlock* deepestBlockContainingAllText(const RenderBlock*);
+    // Returns the first text leaf that is in the current cluster. We attempt to not include text
+    // from descendant clusters but because descendant clusters may not exist, this is only an approximation.
+    // The TraversalDirection controls whether we return the first or the last text leaf.
+    const RenderObject* findTextLeaf(const RenderObject*, size_t&, TextLeafSearch);
+
+    const Document* m_document;
+    int m_frameWidth; // Frame width in density-independent pixels (DIPs).
+    int m_layoutWidth; // Layout width in CSS pixels.
+    float m_baseMultiplier; // Includes accessibility font scale factor and device scale adjustment.
+#ifndef NDEBUG
+    bool m_renderViewInfoPrepared;
+    BlockSet m_blocksThatHaveBegunLayout; // Used to ensure we don't compute properties of a block before beginLayout() is called on it.
+#endif
+
+    // Clusters are created and destroyed during layout. The map key is the
+    // cluster root. Clusters whose roots share the same fingerprint use the
+    // same multiplier.
+    SuperclusterMap m_superclusters;
+    ClusterStack m_clusterStack;
+    FingerprintMapper m_fingerprintMapper;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/FilterEffectRenderer.cpp b/Source/core/rendering/FilterEffectRenderer.cpp
index ff60e9b..9b10d69 100644
--- a/Source/core/rendering/FilterEffectRenderer.cpp
+++ b/Source/core/rendering/FilterEffectRenderer.cpp
@@ -45,10 +45,6 @@
 #include "platform/graphics/filters/FEComponentTransfer.h"
 #include "platform/graphics/filters/FEDropShadow.h"
 #include "platform/graphics/filters/FEGaussianBlur.h"
-#include "platform/graphics/filters/custom/CustomFilterGlobalContext.h"
-#include "platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
-#include "platform/graphics/filters/custom/FECustomFilter.h"
-#include "platform/graphics/filters/custom/ValidatedCustomFilterOperation.h"
 #include "platform/graphics/gpu/AcceleratedImageBufferSurface.h"
 #include "wtf/MathExtras.h"
 #include <algorithm>
@@ -78,27 +74,12 @@
     return true;
 }
 
-static PassRefPtr<FECustomFilter> createCustomFilterEffect(Filter* filter, Document* document, ValidatedCustomFilterOperation* operation)
-{
-    if (!document)
-        return 0;
-
-    CustomFilterGlobalContext* globalContext = document->renderView()->customFilterGlobalContext();
-    globalContext->prepareContextIfNeeded();
-    if (!globalContext->context())
-        return 0;
-
-    return FECustomFilter::create(filter, globalContext->context(), operation->validatedProgram(), operation->parameters(),
-        operation->meshRows(), operation->meshColumns(),  operation->meshType());
-}
-
 FilterEffectRenderer::FilterEffectRenderer()
     : Filter(AffineTransform())
     , m_graphicsBufferAttached(false)
     , m_hasFilterThatMovesPixels(false)
     , m_hasCustomShaderFilter(false)
 {
-    setFilterResolution(FloatSize(1, 1));
     m_sourceGraphic = SourceGraphic::create(this);
 }
 
@@ -256,18 +237,6 @@
             effect = FEDropShadow::create(this, stdDeviation, stdDeviation, x, y, dropShadowOperation->color(), 1);
             break;
         }
-        case FilterOperation::CUSTOM:
-            // CUSTOM operations are always converted to VALIDATED_CUSTOM before getting here.
-            // The conversion happens in RenderLayer::computeFilterOperations.
-            ASSERT_NOT_REACHED();
-            break;
-        case FilterOperation::VALIDATED_CUSTOM: {
-            Document* document = renderer ? &renderer->document() : 0;
-            effect = createCustomFilterEffect(this, document, toValidatedCustomFilterOperation(filterOperation));
-            if (effect)
-                m_hasCustomShaderFilter = true;
-            break;
-        }
         default:
             break;
         }
@@ -283,7 +252,7 @@
         }
     }
 
-    // We need to keep the old effects alive until this point, so that filters like FECustomFilter
+    // We need to keep the old effects alive until this point, so that SVG reference filters
     // can share cached resources across frames.
     m_lastEffect = previousEffect;
 
@@ -294,9 +263,10 @@
     return true;
 }
 
-bool FilterEffectRenderer::updateBackingStoreRect(const FloatRect& filterRect)
+bool FilterEffectRenderer::updateBackingStoreRect(const FloatRect& floatFilterRect)
 {
-    if (!filterRect.isZero() && isFilterSizeValid(filterRect)) {
+    IntRect filterRect = enclosingIntRect(floatFilterRect);
+    if (!filterRect.isEmpty() && isFilterSizeValid(filterRect)) {
         FloatRect currentSourceRect = sourceImageRect();
         if (filterRect != currentSourceRect) {
             setSourceImageRect(filterRect);
@@ -349,11 +319,9 @@
     }
     // The result of this function is the area in the "filterBoxRect" that needs to be repainted, so that we fully cover the "dirtyRect".
     FloatRect rectForRepaint = dirtyRect;
-    rectForRepaint.move(-filterBoxRect.location().x(), -filterBoxRect.location().y());
     float inf = std::numeric_limits<float>::infinity();
     FloatRect clipRect = FloatRect(FloatPoint(-inf, -inf), FloatSize(inf, inf));
     rectForRepaint = lastEffect()->getSourceRect(rectForRepaint, clipRect);
-    rectForRepaint.move(filterBoxRect.location().x(), filterBoxRect.location().y());
     rectForRepaint.intersect(filterBoxRect);
     return LayoutRect(rectForRepaint);
 }
@@ -364,8 +332,21 @@
     m_renderLayer = renderLayer;
     m_repaintRect = dirtyRect;
 
+    // Get the zoom factor to scale the filterSourceRect input
+    const RenderLayerModelObject* renderer = renderLayer->renderer();
+    const RenderStyle* style = renderer ? renderer->style() : 0;
+    float zoom = style ? style->effectiveZoom() : 1.0f;
+
+    // Prepare a transformation that brings the coordinates into the space
+    // filter coordinates are defined in.
+    AffineTransform absoluteTransform;
+    absoluteTransform.translate(filterBoxRect.x(), filterBoxRect.y());
+    absoluteTransform.scale(zoom, zoom);
+
     FilterEffectRenderer* filter = renderLayer->filterRenderer();
-    LayoutRect filterSourceRect = filter->computeSourceImageRectForDirtyRect(filterBoxRect, dirtyRect);
+    filter->setAbsoluteTransform(absoluteTransform);
+
+    IntRect filterSourceRect = pixelSnappedIntRect(filter->computeSourceImageRectForDirtyRect(filterBoxRect, dirtyRect));
 
     if (filterSourceRect.isEmpty()) {
         // The dirty rect is not in view, just bail out.
@@ -373,16 +354,7 @@
         return false;
     }
 
-    // Get the zoom factor to scale the filterSourceRect input
-    const RenderLayerModelObject* renderer = renderLayer->renderer();
-    const RenderStyle* style = renderer ? renderer->style() : 0;
-    float zoom = style ? style->effectiveZoom() : 1.0f;
-
-    AffineTransform absoluteTransform;
-    absoluteTransform.translate(filterBoxRect.x(), filterBoxRect.y());
-    filter->setAbsoluteTransform(absoluteTransform);
-    filter->setAbsoluteFilterRegion(AffineTransform().scale(zoom).mapRect(filterSourceRect));
-    filter->setFilterRegion(absoluteTransform.inverse().mapRect(filterSourceRect));
+    filter->setFilterRegion(filter->mapAbsoluteRectToLocalRect(filterSourceRect));
     filter->lastEffect()->determineFilterPrimitiveSubregion(MapRectForward);
 
     bool hasUpdatedBackingStore = filter->updateBackingStoreRect(filterSourceRect);
diff --git a/Source/core/rendering/FilterEffectRenderer.h b/Source/core/rendering/FilterEffectRenderer.h
index 54f67f0..ce9cdaa 100644
--- a/Source/core/rendering/FilterEffectRenderer.h
+++ b/Source/core/rendering/FilterEffectRenderer.h
@@ -43,7 +43,6 @@
 namespace WebCore {
 
 class ShaderResource;
-class CustomFilterProgram;
 class Document;
 class GraphicsContext;
 class RenderLayer;
@@ -74,7 +73,7 @@
     bool m_haveFilterEffect;
 };
 
-class FilterEffectRenderer : public Filter
+class FilterEffectRenderer FINAL : public Filter
 {
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -83,12 +82,12 @@
         return adoptRef(new FilterEffectRenderer());
     }
 
-    void setSourceImageRect(const FloatRect& sourceImageRect)
+    void setSourceImageRect(const IntRect& sourceImageRect)
     {
         m_sourceDrawingRegion = sourceImageRect;
         m_graphicsBufferAttached = false;
     }
-    virtual FloatRect sourceImageRect() const { return m_sourceDrawingRegion; }
+    virtual IntRect sourceImageRect() const OVERRIDE { return m_sourceDrawingRegion; }
 
     GraphicsContext* inputContext();
     ImageBuffer* output() const { return lastEffect()->asImageBuffer(); }
@@ -114,7 +113,7 @@
     FilterEffectRenderer();
     virtual ~FilterEffectRenderer();
 
-    FloatRect m_sourceDrawingRegion;
+    IntRect m_sourceDrawingRegion;
 
     RefPtr<SourceGraphic> m_sourceGraphic;
     RefPtr<FilterEffect> m_lastEffect;
diff --git a/Source/core/rendering/FixedTableLayout.cpp b/Source/core/rendering/FixedTableLayout.cpp
index 83cc6ce..195d9af 100644
--- a/Source/core/rendering/FixedTableLayout.cpp
+++ b/Source/core/rendering/FixedTableLayout.cpp
@@ -148,7 +148,7 @@
         unsigned span = cell->colSpan();
         int fixedBorderBoxLogicalWidth = 0;
         // FIXME: Support other length types. If the width is non-auto, it should probably just use
-        // RenderBox::computeLogicalWidthInRegionUsing to compute the width.
+        // RenderBox::computeLogicalWidthUsing to compute the width.
         if (logicalWidth.isFixed() && logicalWidth.isPositive()) {
             fixedBorderBoxLogicalWidth = cell->adjustBorderBoxLogicalWidthForBoxSizing(logicalWidth.value());
             logicalWidth.setValue(fixedBorderBoxLogicalWidth);
diff --git a/Source/core/rendering/FloatingObjects.cpp b/Source/core/rendering/FloatingObjects.cpp
index 152a3a3..7f202d3 100644
--- a/Source/core/rendering/FloatingObjects.cpp
+++ b/Source/core/rendering/FloatingObjects.cpp
@@ -93,7 +93,6 @@
 PassOwnPtr<FloatingObject> FloatingObject::unsafeClone() const
 {
     OwnPtr<FloatingObject> cloneObject = adoptPtr(new FloatingObject(renderer(), type(), m_frameRect, m_shouldPaint, m_isDescendant));
-    cloneObject->m_originatingLine = m_originatingLine;
     cloneObject->m_paginationStrut = m_paginationStrut;
     cloneObject->m_isPlaced = m_isPlaced;
     return cloneObject.release();
diff --git a/Source/core/rendering/FlowThreadController.cpp b/Source/core/rendering/FlowThreadController.cpp
index 521085e..59e5cf1 100644
--- a/Source/core/rendering/FlowThreadController.cpp
+++ b/Source/core/rendering/FlowThreadController.cpp
@@ -31,218 +31,16 @@
 
 #include "core/rendering/FlowThreadController.h"
 
-#include "core/dom/NamedFlowCollection.h"
-#include "core/rendering/RenderFlowThread.h"
-#include "core/rendering/RenderNamedFlowThread.h"
-#include "wtf/text/AtomicString.h"
-
 namespace WebCore {
 
-PassOwnPtr<FlowThreadController> FlowThreadController::create(RenderView* view)
+PassOwnPtr<FlowThreadController> FlowThreadController::create()
 {
-    return adoptPtr(new FlowThreadController(view));
+    return adoptPtr(new FlowThreadController);
 }
 
-FlowThreadController::FlowThreadController(RenderView* view)
-    : m_view(view)
-    , m_currentRenderFlowThread(0)
-    , m_isRenderNamedFlowThreadOrderDirty(false)
-    , m_flowThreadsWithAutoLogicalHeightRegions(0)
+FlowThreadController::FlowThreadController()
+    : m_currentRenderFlowThread(0)
 {
 }
 
-FlowThreadController::~FlowThreadController()
-{
-}
-
-RenderNamedFlowThread* FlowThreadController::ensureRenderFlowThreadWithName(const AtomicString& name)
-{
-    if (!m_renderNamedFlowThreadList)
-        m_renderNamedFlowThreadList = adoptPtr(new RenderNamedFlowThreadList());
-    else {
-        for (RenderNamedFlowThreadList::iterator iter = m_renderNamedFlowThreadList->begin(); iter != m_renderNamedFlowThreadList->end(); ++iter) {
-            RenderNamedFlowThread* flowRenderer = *iter;
-            if (flowRenderer->flowThreadName() == name)
-                return flowRenderer;
-        }
-    }
-
-    NamedFlowCollection* namedFlows = m_view->document().namedFlows();
-
-    // Sanity check for the absence of a named flow in the "CREATED" state with the same name.
-    ASSERT(!namedFlows->flowByName(name));
-
-    RenderNamedFlowThread* flowRenderer = RenderNamedFlowThread::createAnonymous(&m_view->document(), namedFlows->ensureFlowWithName(name));
-    flowRenderer->setStyle(RenderFlowThread::createFlowThreadStyle(m_view->style()));
-    m_renderNamedFlowThreadList->add(flowRenderer);
-
-    // Keep the flow renderer as a child of RenderView.
-    m_view->addChild(flowRenderer);
-
-    setIsRenderNamedFlowThreadOrderDirty(true);
-
-    return flowRenderer;
-}
-
-void FlowThreadController::styleDidChange()
-{
-    RenderStyle* viewStyle = m_view->style();
-    for (RenderNamedFlowThreadList::iterator iter = m_renderNamedFlowThreadList->begin(); iter != m_renderNamedFlowThreadList->end(); ++iter) {
-        RenderNamedFlowThread* flowRenderer = *iter;
-        flowRenderer->setStyle(RenderFlowThread::createFlowThreadStyle(viewStyle));
-    }
-}
-
-void FlowThreadController::layoutRenderNamedFlowThreads()
-{
-    updateFlowThreadsChainIfNecessary();
-
-    for (RenderNamedFlowThreadList::iterator iter = m_renderNamedFlowThreadList->begin(); iter != m_renderNamedFlowThreadList->end(); ++iter) {
-        RenderNamedFlowThread* flowRenderer = *iter;
-        flowRenderer->layoutIfNeeded();
-    }
-}
-
-void FlowThreadController::registerNamedFlowContentNode(Node* contentNode, RenderNamedFlowThread* namedFlow)
-{
-    ASSERT(contentNode && contentNode->isElementNode());
-    ASSERT(namedFlow);
-    ASSERT(!m_mapNamedFlowContentNodes.contains(contentNode));
-    ASSERT(!namedFlow->hasContentNode(contentNode));
-    m_mapNamedFlowContentNodes.add(contentNode, namedFlow);
-    namedFlow->registerNamedFlowContentNode(contentNode);
-}
-
-void FlowThreadController::unregisterNamedFlowContentNode(Node* contentNode)
-{
-    ASSERT(contentNode && contentNode->isElementNode());
-    HashMap<const Node*, RenderNamedFlowThread*>::iterator it = m_mapNamedFlowContentNodes.find(contentNode);
-    ASSERT_WITH_SECURITY_IMPLICATION(it != m_mapNamedFlowContentNodes.end());
-    ASSERT(it->value);
-    ASSERT(it->value->hasContentNode(contentNode));
-    it->value->unregisterNamedFlowContentNode(contentNode);
-    m_mapNamedFlowContentNodes.remove(contentNode);
-}
-
-void FlowThreadController::updateFlowThreadsChainIfNecessary()
-{
-    ASSERT(m_renderNamedFlowThreadList);
-    ASSERT(isAutoLogicalHeightRegionsCountConsistent());
-
-    // Remove the left-over flow threads.
-    RenderNamedFlowThreadList toRemoveList;
-    for (RenderNamedFlowThreadList::iterator iter = m_renderNamedFlowThreadList->begin(); iter != m_renderNamedFlowThreadList->end(); ++iter) {
-        RenderNamedFlowThread* flowRenderer = *iter;
-        if (flowRenderer->isMarkedForDestruction())
-            toRemoveList.add(flowRenderer);
-    }
-
-    if (toRemoveList.size() > 0)
-        setIsRenderNamedFlowThreadOrderDirty(true);
-
-    for (RenderNamedFlowThreadList::iterator iter = toRemoveList.begin(); iter != toRemoveList.end(); ++iter) {
-        RenderNamedFlowThread* flowRenderer = *iter;
-        m_renderNamedFlowThreadList->remove(flowRenderer);
-        flowRenderer->destroy();
-    }
-
-    if (isRenderNamedFlowThreadOrderDirty()) {
-        // Arrange the thread list according to dependencies.
-        RenderNamedFlowThreadList sortedList;
-        for (RenderNamedFlowThreadList::iterator iter = m_renderNamedFlowThreadList->begin(); iter != m_renderNamedFlowThreadList->end(); ++iter) {
-            RenderNamedFlowThread* flowRenderer = *iter;
-            if (sortedList.contains(flowRenderer))
-                continue;
-            flowRenderer->pushDependencies(sortedList);
-            sortedList.add(flowRenderer);
-        }
-        m_renderNamedFlowThreadList->swap(sortedList);
-        setIsRenderNamedFlowThreadOrderDirty(false);
-    }
-}
-
-bool FlowThreadController::updateFlowThreadsNeedingLayout()
-{
-    bool needsTwoPassLayout = false;
-
-    for (RenderNamedFlowThreadList::iterator iter = m_renderNamedFlowThreadList->begin(); iter != m_renderNamedFlowThreadList->end(); ++iter) {
-        RenderNamedFlowThread* flowRenderer = *iter;
-        ASSERT(!flowRenderer->needsTwoPhasesLayout());
-        flowRenderer->setInConstrainedLayoutPhase(false);
-        if (flowRenderer->needsLayout() && flowRenderer->hasAutoLogicalHeightRegions())
-            needsTwoPassLayout = true;
-    }
-
-    if (needsTwoPassLayout)
-        resetFlowThreadsWithAutoHeightRegions();
-
-    return needsTwoPassLayout;
-}
-
-bool FlowThreadController::updateFlowThreadsNeedingTwoStepLayout()
-{
-    bool needsTwoPassLayout = false;
-
-    for (RenderNamedFlowThreadList::iterator iter = m_renderNamedFlowThreadList->begin(); iter != m_renderNamedFlowThreadList->end(); ++iter) {
-        RenderNamedFlowThread* flowRenderer = *iter;
-        if (flowRenderer->needsTwoPhasesLayout()) {
-            needsTwoPassLayout = true;
-            break;
-        }
-    }
-
-    if (needsTwoPassLayout)
-        resetFlowThreadsWithAutoHeightRegions();
-
-    return needsTwoPassLayout;
-}
-
-void FlowThreadController::resetFlowThreadsWithAutoHeightRegions()
-{
-    for (RenderNamedFlowThreadList::iterator iter = m_renderNamedFlowThreadList->begin(); iter != m_renderNamedFlowThreadList->end(); ++iter) {
-        RenderNamedFlowThread* flowRenderer = *iter;
-        if (flowRenderer->hasAutoLogicalHeightRegions()) {
-            flowRenderer->markAutoLogicalHeightRegionsForLayout();
-            flowRenderer->invalidateRegions();
-        }
-    }
-}
-
-void FlowThreadController::updateFlowThreadsIntoConstrainedPhase()
-{
-    // Walk the flow chain in reverse order to update the auto-height regions and compute correct sizes for the containing regions. Only after this we can
-    // set the flow in the constrained layout phase.
-    for (RenderNamedFlowThreadList::reverse_iterator iter = m_renderNamedFlowThreadList->rbegin(); iter != m_renderNamedFlowThreadList->rend(); ++iter) {
-        RenderNamedFlowThread* flowRenderer = *iter;
-        ASSERT(!flowRenderer->hasRegions() || flowRenderer->hasValidRegionInfo());
-        flowRenderer->layoutIfNeeded();
-        if (flowRenderer->hasAutoLogicalHeightRegions()) {
-            ASSERT(flowRenderer->needsTwoPhasesLayout());
-            flowRenderer->markAutoLogicalHeightRegionsForLayout();
-        }
-        flowRenderer->setInConstrainedLayoutPhase(true);
-        flowRenderer->clearNeedsTwoPhasesLayout();
-    }
-}
-
-bool FlowThreadController::isContentNodeRegisteredWithAnyNamedFlow(const Node* contentNode) const
-{
-    return m_mapNamedFlowContentNodes.contains(contentNode);
-}
-
-#ifndef NDEBUG
-bool FlowThreadController::isAutoLogicalHeightRegionsCountConsistent() const
-{
-    if (!hasRenderNamedFlowThreads())
-        return !hasFlowThreadsWithAutoLogicalHeightRegions();
-
-    for (RenderNamedFlowThreadList::iterator iter = m_renderNamedFlowThreadList->begin(); iter != m_renderNamedFlowThreadList->end(); ++iter) {
-        if (!(*iter)->isAutoLogicalHeightRegionsCountConsistent())
-            return false;
-    }
-
-    return true;
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/rendering/FlowThreadController.h b/Source/core/rendering/FlowThreadController.h
index 7f56615..1b1372b 100644
--- a/Source/core/rendering/FlowThreadController.h
+++ b/Source/core/rendering/FlowThreadController.h
@@ -30,69 +30,26 @@
 #ifndef FlowThreadController_h
 #define FlowThreadController_h
 
-#include "core/rendering/RenderView.h"
-#include "wtf/ListHashSet.h"
-#include "wtf/OwnPtr.h"
+#include "wtf/FastAllocBase.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
 class RenderFlowThread;
-class RenderNamedFlowThread;
-
-typedef ListHashSet<RenderNamedFlowThread*> RenderNamedFlowThreadList;
 
 class FlowThreadController {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<FlowThreadController> create(RenderView*);
-    ~FlowThreadController();
+    static PassOwnPtr<FlowThreadController> create();
 
     RenderFlowThread* currentRenderFlowThread() const { return m_currentRenderFlowThread; }
     void setCurrentRenderFlowThread(RenderFlowThread* flowThread) { m_currentRenderFlowThread = flowThread; }
 
-    bool isRenderNamedFlowThreadOrderDirty() const { return m_isRenderNamedFlowThreadOrderDirty; }
-    void setIsRenderNamedFlowThreadOrderDirty(bool dirty)
-    {
-        m_isRenderNamedFlowThreadOrderDirty = dirty;
-        if (dirty)
-            m_view->setNeedsLayout();
-    }
-
-    RenderNamedFlowThread* ensureRenderFlowThreadWithName(const AtomicString&);
-    const RenderNamedFlowThreadList* renderNamedFlowThreadList() const { return m_renderNamedFlowThreadList.get(); }
-    bool hasRenderNamedFlowThreads() const { return m_renderNamedFlowThreadList && !m_renderNamedFlowThreadList->isEmpty(); }
-    void layoutRenderNamedFlowThreads();
-    void styleDidChange();
-
-    void registerNamedFlowContentNode(Node*, RenderNamedFlowThread*);
-    void unregisterNamedFlowContentNode(Node*);
-    bool isContentNodeRegisteredWithAnyNamedFlow(const Node*) const;
-
-    bool hasFlowThreadsWithAutoLogicalHeightRegions() const { return m_flowThreadsWithAutoLogicalHeightRegions; }
-    void incrementFlowThreadsWithAutoLogicalHeightRegions() { ++m_flowThreadsWithAutoLogicalHeightRegions; }
-    void decrementFlowThreadsWithAutoLogicalHeightRegions() { ASSERT(m_flowThreadsWithAutoLogicalHeightRegions > 0); --m_flowThreadsWithAutoLogicalHeightRegions; }
-
-    bool updateFlowThreadsNeedingLayout();
-    bool updateFlowThreadsNeedingTwoStepLayout();
-    void updateFlowThreadsIntoConstrainedPhase();
-
-#ifndef NDEBUG
-    bool isAutoLogicalHeightRegionsCountConsistent() const;
-#endif
-
 protected:
-    FlowThreadController(RenderView*);
-    void updateFlowThreadsChainIfNecessary();
-    void resetFlowThreadsWithAutoHeightRegions();
+    FlowThreadController();
 
 private:
-    RenderView* m_view;
     RenderFlowThread* m_currentRenderFlowThread;
-    bool m_isRenderNamedFlowThreadOrderDirty;
-    unsigned m_flowThreadsWithAutoLogicalHeightRegions;
-    OwnPtr<RenderNamedFlowThreadList> m_renderNamedFlowThreadList;
-    // maps a content node to its render flow thread.
-    HashMap<const Node*, RenderNamedFlowThread*> m_mapNamedFlowContentNodes;
 };
 
 }
diff --git a/Source/core/rendering/HitTestLocation.cpp b/Source/core/rendering/HitTestLocation.cpp
index f532480..03582df 100644
--- a/Source/core/rendering/HitTestLocation.cpp
+++ b/Source/core/rendering/HitTestLocation.cpp
@@ -31,8 +31,7 @@
 using namespace HTMLNames;
 
 HitTestLocation::HitTestLocation()
-    : m_region(0)
-    , m_isRectBased(false)
+    : m_isRectBased(false)
     , m_isRectilinear(true)
 {
 }
@@ -42,7 +41,6 @@
     , m_boundingBox(rectForPoint(point, 0, 0, 0, 0))
     , m_transformedPoint(point)
     , m_transformedRect(m_boundingBox)
-    , m_region(0)
     , m_isRectBased(false)
     , m_isRectilinear(true)
 {
@@ -53,7 +51,6 @@
     , m_boundingBox(rectForPoint(m_point, 0, 0, 0, 0))
     , m_transformedPoint(point)
     , m_transformedRect(m_boundingBox)
-    , m_region(0)
     , m_isRectBased(false)
     , m_isRectilinear(true)
 {
@@ -62,7 +59,6 @@
 HitTestLocation::HitTestLocation(const FloatPoint& point, const FloatQuad& quad)
     : m_transformedPoint(point)
     , m_transformedRect(quad)
-    , m_region(0)
     , m_isRectBased(true)
 {
     m_point = flooredLayoutPoint(point);
@@ -74,19 +70,17 @@
     : m_point(centerPoint)
     , m_boundingBox(rectForPoint(centerPoint, topPadding, rightPadding, bottomPadding, leftPadding))
     , m_transformedPoint(centerPoint)
-    , m_region(0)
     , m_isRectBased(topPadding || rightPadding || bottomPadding || leftPadding)
     , m_isRectilinear(true)
 {
     m_transformedRect = FloatQuad(m_boundingBox);
 }
 
-HitTestLocation::HitTestLocation(const HitTestLocation& other, const LayoutSize& offset, RenderRegion* region)
+HitTestLocation::HitTestLocation(const HitTestLocation& other, const LayoutSize& offset)
     : m_point(other.m_point)
     , m_boundingBox(other.m_boundingBox)
     , m_transformedPoint(other.m_transformedPoint)
     , m_transformedRect(other.m_transformedRect)
-    , m_region(region ? region : other.m_region)
     , m_isRectBased(other.m_isRectBased)
     , m_isRectilinear(other.m_isRectilinear)
 {
@@ -98,7 +92,6 @@
     , m_boundingBox(other.m_boundingBox)
     , m_transformedPoint(other.m_transformedPoint)
     , m_transformedRect(other.m_transformedRect)
-    , m_region(other.m_region)
     , m_isRectBased(other.m_isRectBased)
     , m_isRectilinear(other.m_isRectilinear)
 {
@@ -114,7 +107,6 @@
     m_boundingBox = other.m_boundingBox;
     m_transformedPoint = other.m_transformedPoint;
     m_transformedRect = other.m_transformedRect;
-    m_region = other.m_region;
     m_isRectBased = other.m_isRectBased;
     m_isRectilinear = other.m_isRectilinear;
 
diff --git a/Source/core/rendering/HitTestLocation.h b/Source/core/rendering/HitTestLocation.h
index 7edcd8e..828cf29 100644
--- a/Source/core/rendering/HitTestLocation.h
+++ b/Source/core/rendering/HitTestLocation.h
@@ -38,7 +38,6 @@
 class Image;
 class KURL;
 class Node;
-class RenderRegion;
 class Scrollbar;
 
 class HitTestLocation {
@@ -50,8 +49,7 @@
     HitTestLocation(const FloatPoint&, const FloatQuad&);
     // Pass non-zero padding values to perform a rect-based hit test.
     HitTestLocation(const LayoutPoint& centerPoint, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding);
-    // Make a copy the HitTestLocation in a new region by applying given offset to internal point and area.
-    HitTestLocation(const HitTestLocation&, const LayoutSize& offset, RenderRegion* = 0);
+    HitTestLocation(const HitTestLocation&, const LayoutSize& offset);
     HitTestLocation(const HitTestLocation&);
     ~HitTestLocation();
     HitTestLocation& operator=(const HitTestLocation&);
@@ -59,8 +57,6 @@
     const LayoutPoint& point() const { return m_point; }
     IntPoint roundedPoint() const { return roundedIntPoint(m_point); }
 
-    RenderRegion* region() const { return m_region; }
-
     // Rect-based hit test related methods.
     bool isRectBasedTest() const { return m_isRectBased; }
     bool isRectilinear() const { return m_isRectilinear; }
@@ -91,8 +87,6 @@
     FloatPoint m_transformedPoint;
     FloatQuad m_transformedRect;
 
-    RenderRegion* m_region; // The region we're inside.
-
     bool m_isRectBased;
     bool m_isRectilinear;
 };
diff --git a/Source/core/rendering/HitTestResult.cpp b/Source/core/rendering/HitTestResult.cpp
index ad4e162..ac573ea 100644
--- a/Source/core/rendering/HitTestResult.cpp
+++ b/Source/core/rendering/HitTestResult.cpp
@@ -31,12 +31,9 @@
 #include "core/editing/FrameSelection.h"
 #include "core/fetch/ImageResource.h"
 #include "core/html/HTMLAnchorElement.h"
-#include "core/html/HTMLAreaElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLMediaElement.h"
-#include "core/html/HTMLTextAreaElement.h"
-#include "core/html/HTMLVideoElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/frame/Frame.h"
 #include "core/page/FrameTree.h"
@@ -191,18 +188,6 @@
     return 0;
 }
 
-Frame* HitTestResult::targetFrame() const
-{
-    if (!m_innerURLElement)
-        return 0;
-
-    Frame* frame = m_innerURLElement->document().frame();
-    if (!frame)
-        return 0;
-
-    return frame->tree().find(m_innerURLElement->target());
-}
-
 bool HitTestResult::isSelected() const
 {
     if (!m_innerNonSharedNode)
@@ -325,8 +310,8 @@
     if (!(m_innerNonSharedNode->renderer() && m_innerNonSharedNode->renderer()->isMedia()))
         return 0;
 
-    if (isHTMLVideoElement(m_innerNonSharedNode.get()) || m_innerNonSharedNode->hasTagName(HTMLNames::audioTag))
-        return toHTMLMediaElement(m_innerNonSharedNode.get());
+    if (isHTMLMediaElement(*m_innerNonSharedNode))
+        return toHTMLMediaElement(m_innerNonSharedNode);
     return 0;
 }
 
@@ -336,7 +321,7 @@
         return KURL();
 
     AtomicString urlString;
-    if (isHTMLAnchorElement(m_innerURLElement.get()) || isHTMLAreaElement(m_innerURLElement.get()) || m_innerURLElement->hasTagName(linkTag))
+    if (m_innerURLElement->hasTagName(aTag) || m_innerURLElement->hasTagName(areaTag) || m_innerURLElement->hasTagName(linkTag))
         urlString = m_innerURLElement->getAttribute(hrefAttr);
     else if (m_innerURLElement->hasTagName(SVGNames::aTag))
         urlString = m_innerURLElement->getAttribute(XLinkNames::hrefAttr);
@@ -351,7 +336,7 @@
     if (!m_innerURLElement)
         return false;
 
-    if (isHTMLAnchorElement(m_innerURLElement.get()))
+    if (m_innerURLElement->hasTagName(aTag))
         return toHTMLAnchorElement(m_innerURLElement)->isLiveLink();
 
     if (m_innerURLElement->hasTagName(SVGNames::aTag))
@@ -400,7 +385,7 @@
     if (!m_innerNonSharedNode)
         return false;
 
-    if (isHTMLTextAreaElement(m_innerNonSharedNode.get()))
+    if (m_innerNonSharedNode->hasTagName(textareaTag))
         return true;
 
     if (m_innerNonSharedNode->hasTagName(inputTag))
diff --git a/Source/core/rendering/HitTestResult.h b/Source/core/rendering/HitTestResult.h
index 490596e..39cadf3 100644
--- a/Source/core/rendering/HitTestResult.h
+++ b/Source/core/rendering/HitTestResult.h
@@ -42,7 +42,6 @@
 class KURL;
 class Node;
 class RenderObject;
-class RenderRegion;
 class Scrollbar;
 
 class HitTestResult {
@@ -96,7 +95,6 @@
     void setIsFirstLetter(bool b) { m_isFirstLetter = b; }
     void setIsOverWidget(bool b) { m_isOverWidget = b; }
 
-    Frame* targetFrame() const;
     bool isSelected() const;
     String spellingToolTip(TextDirection&) const;
     String title(TextDirection&) const;
diff --git a/Source/core/rendering/InlineBox.h b/Source/core/rendering/InlineBox.h
index 3d6e73a..5803cd1 100644
--- a/Source/core/rendering/InlineBox.h
+++ b/Source/core/rendering/InlineBox.h
@@ -197,8 +197,8 @@
 
     const FloatPoint& topLeft() const { return m_topLeft; }
 
-    float width() const { return isHorizontal() ? logicalWidth() : logicalHeight(); }
-    float height() const { return isHorizontal() ? logicalHeight() : logicalWidth(); }
+    float width() const { return isHorizontal() ? logicalWidth() : hasVirtualLogicalHeight() ? virtualLogicalHeight() : logicalHeight(); }
+    float height() const { return isHorizontal() ? hasVirtualLogicalHeight() ? virtualLogicalHeight() : logicalHeight() : logicalWidth(); }
     FloatSize size() const { return FloatSize(width(), height()); }
     float right() const { return left() + width(); }
     float bottom() const { return top() + height(); }
diff --git a/Source/core/rendering/InlineFlowBox.cpp b/Source/core/rendering/InlineFlowBox.cpp
index 68952fc..66e89f3 100644
--- a/Source/core/rendering/InlineFlowBox.cpp
+++ b/Source/core/rendering/InlineFlowBox.cpp
@@ -382,7 +382,7 @@
             RenderText* rt = toRenderText(text->renderer());
             if (rt->textLength()) {
                 if (needsWordSpacing && isSpaceOrNewline(rt->characterAt(text->start())))
-                    logicalLeft += rt->style(isFirstLineStyle())->font().wordSpacing();
+                    logicalLeft += rt->style(isFirstLineStyle())->font().fontDescription().wordSpacing();
                 needsWordSpacing = !isSpaceOrNewline(rt->characterAt(text->end()));
             }
             text->setLogicalLeft(logicalLeft);
@@ -862,7 +862,7 @@
 
     // If letter-spacing is negative, we should factor that into right layout overflow. (Even in RTL, letter-spacing is
     // applied to the right, so this is not an issue with left overflow.
-    rightGlyphOverflow -= min(0, (int)style->font().letterSpacing());
+    rightGlyphOverflow -= min(0, (int)style->font().fontDescription().letterSpacing());
 
     LayoutUnit textShadowLogicalTop;
     LayoutUnit textShadowLogicalBottom;
@@ -1359,7 +1359,7 @@
     }
 
     LayoutRect paintRect = LayoutRect(adjustedPaintOffset, frameRect.size());
-    paintFillLayers(paintInfo, Color(), renderer()->style()->maskLayers(), paintRect, compositeOp);
+    paintFillLayers(paintInfo, Color::transparent, renderer()->style()->maskLayers(), paintRect, compositeOp);
 
     bool hasBoxImage = maskBoxImage && maskBoxImage->canRender(renderer(), renderer()->style()->effectiveZoom());
     if (!hasBoxImage || !maskBoxImage->isLoaded()) {
diff --git a/Source/core/rendering/InlineFlowBox.h b/Source/core/rendering/InlineFlowBox.h
index 066098f..e5478fe 100644
--- a/Source/core/rendering/InlineFlowBox.h
+++ b/Source/core/rendering/InlineFlowBox.h
@@ -68,8 +68,8 @@
 #ifndef NDEBUG
     virtual ~InlineFlowBox();
 
-    virtual void showLineTreeAndMark(const InlineBox* = 0, const char* = 0, const InlineBox* = 0, const char* = 0, const RenderObject* = 0, int = 0) const;
-    virtual const char* boxName() const;
+    virtual void showLineTreeAndMark(const InlineBox* = 0, const char* = 0, const InlineBox* = 0, const char* = 0, const RenderObject* = 0, int = 0) const OVERRIDE;
+    virtual const char* boxName() const OVERRIDE;
 #endif
 
     InlineFlowBox* prevLineBox() const { return m_prevLineBox; }
@@ -99,7 +99,7 @@
     virtual void deleteLine() OVERRIDE FINAL;
     virtual void extractLine() OVERRIDE FINAL;
     virtual void attachLine() OVERRIDE FINAL;
-    virtual void adjustPosition(float dx, float dy);
+    virtual void adjustPosition(float dx, float dy) OVERRIDE;
 
     virtual void extractLineBoxFromRenderObject();
     virtual void attachLineBoxToRenderObject();
@@ -114,7 +114,7 @@
     void paintFillLayers(const PaintInfo&, const Color&, const FillLayer*, const LayoutRect&, CompositeOperator = CompositeSourceOver);
     void paintFillLayer(const PaintInfo&, const Color&, const FillLayer*, const LayoutRect&, CompositeOperator = CompositeSourceOver);
     void paintBoxShadow(const PaintInfo&, RenderStyle*, ShadowStyle, const LayoutRect&);
-    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom);
+    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
 
     bool boxShadowCanBeAppliedToBackground(const FillLayer&) const;
@@ -199,7 +199,7 @@
 
     void removeChild(InlineBox* child);
 
-    virtual RenderObject::SelectionState selectionState();
+    virtual RenderObject::SelectionState selectionState() OVERRIDE;
 
     virtual bool canAccommodateEllipsis(bool ltr, int blockEdge, int ellipsisWidth) const OVERRIDE FINAL;
     virtual float placeEllipsisBox(bool ltr, float blockLeftEdge, float blockRightEdge, float ellipsisWidth, float &truncatedWidth, bool&) OVERRIDE;
diff --git a/Source/core/rendering/InlineIterator.h b/Source/core/rendering/InlineIterator.h
index cbd866e..feb0d11 100644
--- a/Source/core/rendering/InlineIterator.h
+++ b/Source/core/rendering/InlineIterator.h
@@ -43,16 +43,16 @@
     InlineIterator()
         : m_root(0)
         , m_obj(0)
-        , m_pos(0)
         , m_nextBreakablePosition(-1)
+        , m_pos(0)
     {
     }
 
     InlineIterator(RenderObject* root, RenderObject* o, unsigned p)
         : m_root(root)
         , m_obj(o)
-        , m_pos(p)
         , m_nextBreakablePosition(-1)
+        , m_pos(p)
     {
     }
 
@@ -73,7 +73,11 @@
     RenderObject* object() const { return m_obj; }
     void setObject(RenderObject* object) { m_obj = object; }
 
+    int nextBreakablePosition() const { return m_nextBreakablePosition; }
+    void setNextBreakablePosition(int position) { m_nextBreakablePosition = position; }
+
     unsigned offset() const { return m_pos; }
+    void setOffset(unsigned position) { m_pos = position; }
     RenderObject* root() const { return m_root; }
 
     void fastIncrementInTextNode();
@@ -100,20 +104,18 @@
     RenderObject* m_root;
     RenderObject* m_obj;
 
-// FIXME: These should be private.
-public:
-    unsigned m_pos;
     int m_nextBreakablePosition;
+    unsigned m_pos;
 };
 
 inline bool operator==(const InlineIterator& it1, const InlineIterator& it2)
 {
-    return it1.m_pos == it2.m_pos && it1.object() == it2.object();
+    return it1.offset() == it2.offset() && it1.object() == it2.object();
 }
 
 inline bool operator!=(const InlineIterator& it1, const InlineIterator& it2)
 {
-    return it1.m_pos != it2.m_pos || it1.object() != it2.object();
+    return it1.offset() != it2.offset() || it1.object() != it2.object();
 }
 
 static inline WTF::Unicode::Direction embedCharFromDirection(TextDirection dir, EUnicodeBidi unicodeBidi)
@@ -359,12 +361,28 @@
     bool m_atEndOfInline;
 };
 
+static inline bool endOfLineHasIsolatedObjectAncestor(const InlineIterator& isolatedIterator, const InlineIterator& ancestorItertor)
+{
+    if (!isolatedIterator.object() || !isIsolated(isolatedIterator.object()->style()->unicodeBidi()))
+        return false;
+
+    RenderObject* innerIsolatedObject = isolatedIterator.object();
+    while (innerIsolatedObject && innerIsolatedObject != isolatedIterator.root()) {
+        if (innerIsolatedObject == ancestorItertor.object())
+            return true;
+        innerIsolatedObject = innerIsolatedObject->parent();
+    }
+    return false;
+}
+
 inline void InlineIterator::increment(InlineBidiResolver* resolver, IncrementRule rule)
 {
     if (!m_obj)
         return;
 
-    if (resolver && resolver->inIsolate() && rule == FastIncrementInIsolatedRenderer) {
+    if (rule == FastIncrementInIsolatedRenderer
+        && resolver && resolver->inIsolate()
+        && !endOfLineHasIsolatedObjectAncestor(resolver->endOfLine(), resolver->position())) {
         moveTo(bidiNextSkippingEmptyInlines(m_root, m_obj, resolver), 0);
         return;
     }
@@ -426,13 +444,74 @@
 {
     bool inEndOfLine = m_current == end || m_current.atEnd() || (inIsolate() && m_current.object() == end.object());
     if (inIsolate() && inEndOfLine) {
-        m_current.moveTo(m_current.object(), end.m_pos, m_current.m_nextBreakablePosition);
+        m_current.moveTo(m_current.object(), end.offset(), m_current.nextBreakablePosition());
         m_last = m_current;
         updateStatusLastFromCurrentDirection(WTF::Unicode::OtherNeutral);
     }
     return inEndOfLine;
 }
 
+static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
+{
+    if (character == ' ' || character == '\t' || character == softHyphen)
+        return true;
+    if (character == '\n')
+        return !renderer->style()->preserveNewline();
+    return false;
+}
+
+template <typename CharacterType>
+static inline int findFirstTrailingSpace(RenderText* lastText, const CharacterType* characters, int start, int stop)
+{
+    int firstSpace = stop;
+    while (firstSpace > start) {
+        UChar current = characters[firstSpace - 1];
+        if (!isCollapsibleSpace(current, lastText))
+            break;
+        firstSpace--;
+    }
+
+    return firstSpace;
+}
+
+template <>
+inline int InlineBidiResolver::findFirstTrailingSpaceAtRun(BidiRun* run)
+{
+    ASSERT(run);
+    RenderObject* lastObject = run->m_object;
+    if (!lastObject->isText())
+        return run->m_stop;
+
+    RenderText* lastText = toRenderText(lastObject);
+    int firstSpace;
+    if (lastText->is8Bit())
+        firstSpace = findFirstTrailingSpace(lastText, lastText->characters8(), run->start(), run->stop());
+    else
+        firstSpace = findFirstTrailingSpace(lastText, lastText->characters16(), run->start(), run->stop());
+    return firstSpace;
+}
+
+template <>
+inline BidiRun* InlineBidiResolver::addTrailingRun(int start, int stop, BidiRun* run, BidiContext* context, TextDirection direction)
+{
+    BidiRun* newTrailingRun = new BidiRun(start, stop, run->m_object, context, WTF::Unicode::OtherNeutral);
+    if (direction == LTR)
+        m_runs.addRun(newTrailingRun);
+    else
+        m_runs.prependRun(newTrailingRun);
+
+    return newTrailingRun;
+}
+
+template <>
+inline bool InlineBidiResolver::needsToApplyL1Rule()
+{
+    if (!m_runs.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
+        || !m_runs.logicallyLastRun()->m_object->style()->autoWrap())
+        return false;
+    return true;
+}
+
 static inline bool isIsolatedInline(RenderObject* object)
 {
     ASSERT(object);
@@ -553,18 +632,18 @@
         return;
 
     LineMidpointState& lineMidpointState = resolver.midpointState();
-    bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
+    bool haveNextMidpoint = (lineMidpointState.currentMidpoint() < lineMidpointState.numMidpoints());
     InlineIterator nextMidpoint;
     if (haveNextMidpoint)
-        nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
-    if (lineMidpointState.betweenMidpoints) {
+        nextMidpoint = lineMidpointState.midpoints()[lineMidpointState.currentMidpoint()];
+    if (lineMidpointState.betweenMidpoints()) {
         if (!(haveNextMidpoint && nextMidpoint.object() == obj))
             return;
         // This is a new start point. Stop ignoring objects and
         // adjust our start.
-        lineMidpointState.betweenMidpoints = false;
-        start = nextMidpoint.m_pos;
-        lineMidpointState.currentMidpoint++;
+        lineMidpointState.setBetweenMidpoints(false);
+        start = nextMidpoint.offset();
+        lineMidpointState.incrementCurrentMidpoint();
         if (start < end)
             return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, end, resolver, behavior, tracker);
     } else {
@@ -575,13 +654,13 @@
 
         // An end midpoint has been encountered within our object. We
         // need to go ahead and append a run with our endpoint.
-        if (nextMidpoint.m_pos + 1 <= end) {
-            lineMidpointState.betweenMidpoints = true;
-            lineMidpointState.currentMidpoint++;
-            if (nextMidpoint.m_pos != UINT_MAX) { // UINT_MAX means stop at the object and don't nclude any of it.
-                if (nextMidpoint.m_pos + 1 > start)
-                    appendRunObjectIfNecessary(obj, start, nextMidpoint.m_pos + 1, resolver, behavior, tracker);
-                return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, nextMidpoint.m_pos + 1, end, resolver, behavior, tracker);
+        if (nextMidpoint.offset() + 1 <= end) {
+            lineMidpointState.setBetweenMidpoints(true);
+            lineMidpointState.incrementCurrentMidpoint();
+            if (nextMidpoint.offset() != UINT_MAX) { // UINT_MAX means stop at the object and don't nclude any of it.
+                if (nextMidpoint.offset() + 1 > start)
+                    appendRunObjectIfNecessary(obj, start, nextMidpoint.offset() + 1, resolver, behavior, tracker);
+                return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, nextMidpoint.offset() + 1, end, resolver, behavior, tracker);
             }
         } else {
             appendRunObjectIfNecessary(obj, start, end, resolver, behavior, tracker);
@@ -603,7 +682,7 @@
         // Initialize our state depending on if we're starting in the middle of such an inline.
         // FIXME: Could this initialize from this->inIsolate() instead of walking up the render tree?
         IsolateTracker isolateTracker(numberOfIsolateAncestors(m_sor));
-        int start = m_sor.m_pos;
+        int start = m_sor.offset();
         RenderObject* obj = m_sor.object();
         while (obj && obj != m_eor.object() && obj != m_endOfRunAtEndOfLine.object()) {
             if (isolateTracker.inIsolate())
@@ -614,12 +693,12 @@
             start = 0;
             obj = bidiNextSkippingEmptyInlines(m_sor.root(), obj, &isolateTracker);
         }
-        bool isEndOfLine = obj == m_endOfLine.object() && !m_endOfLine.m_pos;
+        bool isEndOfLine = obj == m_endOfLine.object() && !m_endOfLine.offset();
         if (obj && !isEndOfLine) {
-            unsigned pos = obj == m_eor.object() ? m_eor.m_pos : INT_MAX;
-            if (obj == m_endOfRunAtEndOfLine.object() && m_endOfRunAtEndOfLine.m_pos <= pos) {
+            unsigned pos = obj == m_eor.object() ? m_eor.offset() : INT_MAX;
+            if (obj == m_endOfRunAtEndOfLine.object() && m_endOfRunAtEndOfLine.offset() <= pos) {
                 m_reachedEndOfLine = true;
-                pos = m_endOfRunAtEndOfLine.m_pos;
+                pos = m_endOfRunAtEndOfLine.offset();
             }
             // It's OK to add runs for zero-length RenderObjects, just don't make the run larger than it should be
             int end = obj->length() ? pos + 1 : 0;
@@ -631,7 +710,11 @@
 
         if (isEndOfLine)
             m_reachedEndOfLine = true;
-        m_eor.increment();
+        // If isolateTrack is inIsolate, the next |start of run| can not be the current isolated renderer.
+        if (isolateTracker.inIsolate())
+            m_eor.moveTo(bidiNextSkippingEmptyInlines(m_eor.root(), m_eor.object()), 0);
+        else
+            m_eor.increment();
         m_sor = m_eor;
     }
 
diff --git a/Source/core/rendering/InlineTextBox.cpp b/Source/core/rendering/InlineTextBox.cpp
index 88432a7..d36b8b4 100644
--- a/Source/core/rendering/InlineTextBox.cpp
+++ b/Source/core/rendering/InlineTextBox.cpp
@@ -31,7 +31,7 @@
 #include "core/editing/InputMethodController.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/AbstractInlineTextBox.h"
 #include "core/rendering/EllipsisBox.h"
 #include "core/rendering/HitTestResult.h"
@@ -211,8 +211,6 @@
     StringBuilder charactersWithHyphen;
     bool respectHyphen = ePos == m_len && hasHyphen();
     TextRun textRun = constructTextRun(styleToUse, font, respectHyphen ? &charactersWithHyphen : 0);
-    if (respectHyphen)
-        endPos = textRun.length();
 
     FloatPoint startingPoint = FloatPoint(logicalLeft(), selTop);
     LayoutRect r;
@@ -269,8 +267,8 @@
     // Criteria for full truncation:
     // LTR: the left edge of the ellipsis is to the left of our text run.
     // RTL: the right edge of the ellipsis is to the right of our text run.
-    bool ltrFullTruncation = flowIsLTR && ellipsisX <= left();
-    bool rtlFullTruncation = !flowIsLTR && ellipsisX >= left() + logicalWidth();
+    bool ltrFullTruncation = flowIsLTR && ellipsisX <= logicalLeft();
+    bool rtlFullTruncation = !flowIsLTR && ellipsisX >= logicalLeft() + logicalWidth();
     if (ltrFullTruncation || rtlFullTruncation) {
         // Too far.  Just set full truncation, but return -1 and let the ellipsis just be placed at the edge of the box.
         m_truncation = cFullTruncation;
@@ -278,8 +276,8 @@
         return -1;
     }
 
-    bool ltrEllipsisWithinBox = flowIsLTR && (ellipsisX < right());
-    bool rtlEllipsisWithinBox = !flowIsLTR && (ellipsisX > left());
+    bool ltrEllipsisWithinBox = flowIsLTR && (ellipsisX < logicalRight());
+    bool rtlEllipsisWithinBox = !flowIsLTR && (ellipsisX > logicalLeft());
     if (ltrEllipsisWithinBox || rtlEllipsisWithinBox) {
         foundBox = true;
 
@@ -288,9 +286,9 @@
         // must keep track of these separately.
         bool ltr = isLeftToRightDirection();
         if (ltr != flowIsLTR) {
-          // Width in pixels of the visible portion of the box, excluding the ellipsis.
-          int visibleBoxWidth = visibleRightEdge - visibleLeftEdge  - ellipsisWidth;
-          ellipsisX = ltr ? left() + visibleBoxWidth : right() - visibleBoxWidth;
+            // Width in pixels of the visible portion of the box, excluding the ellipsis.
+            int visibleBoxWidth = visibleRightEdge - visibleLeftEdge  - ellipsisWidth;
+            ellipsisX = ltr ? logicalLeft() + visibleBoxWidth : logicalRight() - visibleBoxWidth;
         }
 
         int offset = offsetForPosition(ellipsisX, false);
@@ -299,7 +297,7 @@
             // and the ellipsis edge.
             m_truncation = cFullTruncation;
             truncatedWidth += ellipsisWidth;
-            return min(ellipsisX, x());
+            return min(ellipsisX, logicalLeft());
         }
 
         // Set the truncation index on the text run.
@@ -307,7 +305,7 @@
 
         // If we got here that means that we were only partially truncated and we need to return the pixel offset at which
         // to place the ellipsis.
-        float widthOfVisibleText = toRenderText(renderer())->width(m_start, offset, textPos(), isFirstLineStyle());
+        float widthOfVisibleText = toRenderText(renderer())->width(m_start, offset, textPos(), flowIsLTR ? LTR : RTL, isFirstLineStyle());
 
         // The ellipsis needs to be placed just after the last visible character.
         // Where "after" is defined by the flow directionality, not the inline
@@ -316,9 +314,9 @@
         // have a situation such as |Hello| -> |...He|
         truncatedWidth += widthOfVisibleText + ellipsisWidth;
         if (flowIsLTR)
-            return left() + widthOfVisibleText;
+            return logicalLeft() + widthOfVisibleText;
         else
-            return right() - widthOfVisibleText - ellipsisWidth;
+            return logicalRight() - widthOfVisibleText - ellipsisWidth;
     }
     truncatedWidth += logicalWidth();
     return -1;
@@ -402,10 +400,10 @@
         DrawLooper drawLooper;
         for (size_t i = shadowList->shadows().size(); i--; ) {
             const ShadowData& shadow = shadowList->shadows()[i];
-            int shadowX = horizontal ? shadow.x() : shadow.y();
-            int shadowY = horizontal ? shadow.y() : -shadow.x();
+            float shadowX = horizontal ? shadow.x() : shadow.y();
+            float shadowY = horizontal ? shadow.y() : -shadow.x();
             FloatSize offset(shadowX, shadowY);
-            drawLooper.addShadow(offset, shadow.blur(), renderer->resolveColor(shadow.color()),
+            drawLooper.addShadow(offset, shadow.blur(), shadow.color(),
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
         }
         drawLooper.addUnmodifiedContent();
@@ -467,14 +465,6 @@
     return !rubyText || !rubyText->firstLineBox();
 }
 
-enum RotationDirection { Counterclockwise, Clockwise };
-
-static inline AffineTransform rotation(const FloatRect& boxRect, RotationDirection clockwise)
-{
-    return clockwise ? AffineTransform(0, 1, -1, 0, boxRect.x() + boxRect.maxY(), boxRect.maxY() - boxRect.x())
-        : AffineTransform(0, -1, 1, 0, boxRect.x() - boxRect.maxY(), boxRect.x() + boxRect.maxY());
-}
-
 void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /*lineTop*/, LayoutUnit /*lineBottom*/)
 {
     if (isLineBreak() || !paintInfo.shouldPaintWithinRoot(renderer()) || renderer()->style()->visibility() != VISIBLE ||
@@ -514,7 +504,7 @@
             // farther to the right.
             // NOTE: WebKit's behavior differs from that of IE which appears to just overlay the ellipsis on top of the
             // truncated string i.e.  |Hello|CBA| -> |...lo|CBA|
-            LayoutUnit widthOfVisibleText = toRenderText(renderer())->width(m_start, m_truncation, textPos(), isFirstLineStyle());
+            LayoutUnit widthOfVisibleText = toRenderText(renderer())->width(m_start, m_truncation, textPos(), isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
             LayoutUnit widthOfHiddenText = m_logicalWidth - widthOfVisibleText;
             // FIXME: The hit testing logic also needs to take this translation into account.
             LayoutSize truncationOffset(isLeftToRightDirection() ? widthOfHiddenText : -widthOfHiddenText, 0);
@@ -595,14 +585,14 @@
     if (haveSelection) {
         // Check foreground color first.
         Color foreground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionForegroundColor();
-        if (foreground.isValid() && foreground != selectionFillColor && foreground != Color::transparent) {
+        if (foreground != selectionFillColor) {
             if (!paintSelectedTextOnly)
                 paintSelectedTextSeparately = true;
             selectionFillColor = foreground;
         }
 
         Color emphasisMarkForeground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionEmphasisMarkColor();
-        if (emphasisMarkForeground.isValid() && emphasisMarkForeground != selectionEmphasisMarkColor) {
+        if (emphasisMarkForeground != selectionEmphasisMarkColor) {
             if (!paintSelectedTextOnly)
                 paintSelectedTextSeparately = true;
             selectionEmphasisMarkColor = emphasisMarkForeground;
@@ -831,7 +821,7 @@
         return;
 
     Color c = renderer()->selectionBackgroundColor();
-    if (!c.isValid() || !c.alpha())
+    if (!c.alpha())
         return;
 
     // If the text color ends up being the same as the selection background, invert the selection
@@ -1072,13 +1062,13 @@
 
     float width = m_logicalWidth;
     if (m_truncation != cNoTruncation) {
-        width = toRenderText(renderer())->width(m_start, m_truncation, textPos(), isFirstLineStyle());
+        width = toRenderText(renderer())->width(m_start, m_truncation, textPos(), isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
         if (!isLeftToRightDirection())
             localOrigin.move(m_logicalWidth - width, 0);
     }
 
     // Get the text decoration colors.
-    Color underline, overline, linethrough;
+    Color underline(Color::transparent), overline(Color::transparent), linethrough(Color::transparent);
     renderer()->getTextDecorationColors(deco, underline, overline, linethrough, true);
     if (isFirstLineStyle())
         renderer()->getTextDecorationColors(deco, underline, overline, linethrough, true, true);
@@ -1094,21 +1084,27 @@
     size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
     // Set the thick of the line to be 10% (or something else ?)of the computed font size and not less than 1px.
     // Using computedFontSize should take care of zoom as well.
-    const float textDecorationThickness = std::max(1.f, styleToUse->computedFontSize() / 10.f);
+
+    // Update Underline thickness, in case we have Faulty Font Metrics calculating underline thickness by old method.
+    float textDecorationThickness = styleToUse->fontMetrics().underlineThickness();
+    int fontHeightInt  = (int)(styleToUse->fontMetrics().floatHeight() + 0.5);
+    if ((textDecorationThickness == 0.f) || (textDecorationThickness >= (fontHeightInt >> 1)))
+        textDecorationThickness = std::max(1.f, styleToUse->computedFontSize() / 10.f);
+
     context->setStrokeThickness(textDecorationThickness);
 
-    int extraOffset = 0;
+    float extraOffset = 0;
     if (!linesAreOpaque && shadowCount > 1) {
         FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
         for (size_t i = shadowCount; i--; ) {
             const ShadowData& s = shadowList->shadows()[i];
             FloatRect shadowRect(localOrigin, FloatSize(width, baseline + 2));
             shadowRect.inflate(s.blur());
-            int shadowX = isHorizontal() ? s.x() : s.y();
-            int shadowY = isHorizontal() ? s.y() : -s.x();
+            float shadowX = isHorizontal() ? s.x() : s.y();
+            float shadowY = isHorizontal() ? s.y() : -s.x();
             shadowRect.move(shadowX, shadowY);
             clipRect.unite(shadowRect);
-            extraOffset = max(extraOffset, max(0, shadowY) + s.blur());
+            extraOffset = max(extraOffset, max(0.0f, shadowY) + s.blur());
         }
         context->clip(clipRect);
         extraOffset += baseline + 2;
@@ -1124,8 +1120,8 @@
                 extraOffset = 0;
             }
             const ShadowData& shadow = shadowList->shadows()[i];
-            int shadowX = isHorizontal() ? shadow.x() : shadow.y();
-            int shadowY = isHorizontal() ? shadow.y() : -shadow.x();
+            float shadowX = isHorizontal() ? shadow.x() : shadow.y();
+            float shadowY = isHorizontal() ? shadow.y() : -shadow.x();
             context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow.blur(), shadow.color());
         }
 
@@ -1301,7 +1297,7 @@
 
     // Give any document markers that touch this run a chance to draw before the text has been drawn.
     // Note end() points at the last char, not one past it like endOffset and ranges do.
-    for ( ; markerIt != markers.end(); markerIt++) {
+    for ( ; markerIt != markers.end(); ++markerIt) {
         DocumentMarker* marker = *markerIt;
 
         // Paint either the background markers or the foreground markers, but not both
@@ -1359,7 +1355,7 @@
     if (paintStart <= underline.startOffset) {
         paintStart = underline.startOffset;
         useWholeWidth = false;
-        start = toRenderText(renderer())->width(m_start, paintStart - m_start, textPos(), isFirstLineStyle());
+        start = toRenderText(renderer())->width(m_start, paintStart - m_start, textPos(), isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
     }
     if (paintEnd != underline.endOffset) {      // end points at the last char, not past it
         paintEnd = min(paintEnd, (unsigned)underline.endOffset);
@@ -1370,7 +1366,7 @@
         useWholeWidth = false;
     }
     if (!useWholeWidth) {
-        width = toRenderText(renderer())->width(paintStart, paintEnd - paintStart, textPos() + start, isFirstLineStyle());
+        width = toRenderText(renderer())->width(paintStart, paintEnd - paintStart, textPos() + start, isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
     }
 
     // Thick marked text underlines are 2px thick as long as there is room for the 2px line under the baseline.
@@ -1531,6 +1527,7 @@
 
     TextRun run(string, textPos(), expansion(), expansionBehavior(), direction(), dirOverride() || style->rtlOrdering() == VisualOrder, !textRenderer->canUseSimpleFontCodePath());
     run.setTabSize(!style->collapseWhiteSpace(), style->tabSize());
+    run.setCharacterScanForCodePath(!textRenderer->canUseSimpleFontCodePath());
     if (textRunNeedsRenderingContext(font))
         run.setRenderingContext(SVGTextRunRenderingContext::create(textRenderer));
 
diff --git a/Source/core/rendering/InlineTextBox.h b/Source/core/rendering/InlineTextBox.h
index 5994d67..9292607 100644
--- a/Source/core/rendering/InlineTextBox.h
+++ b/Source/core/rendering/InlineTextBox.h
@@ -25,6 +25,7 @@
 
 #include "core/rendering/InlineBox.h"
 #include "core/rendering/RenderText.h" // so textRenderer() can be inline
+#include "platform/graphics/GraphicsContext.h"
 #include "platform/text/TextRun.h"
 #include "wtf/Forward.h"
 
@@ -93,10 +94,12 @@
     LayoutUnit logicalRightVisualOverflow() const { return logicalOverflowRect().maxX(); }
 
 #ifndef NDEBUG
-    virtual void showBox(int = 0) const;
-    virtual const char* boxName() const;
+    virtual void showBox(int = 0) const OVERRIDE;
+    virtual const char* boxName() const OVERRIDE;
 #endif
 
+    enum RotationDirection { Counterclockwise, Clockwise };
+    static AffineTransform rotation(const FloatRect& boxRect, RotationDirection);
 private:
     LayoutUnit selectionTop();
     LayoutUnit selectionBottom();
@@ -108,14 +111,14 @@
 
 public:
     TextRun constructTextRunForInspector(RenderStyle*, const Font&) const;
-    virtual FloatRect calculateBoundaries() const { return FloatRect(x(), y(), width(), height()); }
+    virtual FloatRect calculateBoundaries() const OVERRIDE { return FloatRect(x(), y(), width(), height()); }
 
     virtual LayoutRect localSelectionRect(int startPos, int endPos);
     bool isSelected(int startPos, int endPos) const;
     void selectionStartEnd(int& sPos, int& ePos);
 
 protected:
-    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom);
+    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
 
 public:
@@ -177,11 +180,13 @@
     void paintDocumentMarkers(GraphicsContext*, const FloatPoint& boxOrigin, RenderStyle*, const Font&, bool background);
     void paintCompositionUnderline(GraphicsContext*, const FloatPoint& boxOrigin, const CompositionUnderline&);
 
+    // These functions both paint markers and update the DocumentMarker's renderedRect.
+    virtual void paintDocumentMarker(GraphicsContext*, const FloatPoint& boxOrigin, DocumentMarker*, RenderStyle*, const Font&, bool grammar);
+    virtual void paintTextMatchMarker(GraphicsContext*, const FloatPoint& boxOrigin, DocumentMarker*, RenderStyle*, const Font&);
+
 private:
     void paintDecoration(GraphicsContext*, const FloatPoint& boxOrigin, TextDecoration, TextDecorationStyle, const ShadowList*);
     void paintSelection(GraphicsContext*, const FloatPoint& boxOrigin, RenderStyle*, const Font&, Color textColor);
-    void paintDocumentMarker(GraphicsContext*, const FloatPoint& boxOrigin, DocumentMarker*, RenderStyle*, const Font&, bool grammar);
-    void paintTextMatchMarker(GraphicsContext*, const FloatPoint& boxOrigin, DocumentMarker*, RenderStyle*, const Font&);
 
     TextRun::ExpansionBehavior expansionBehavior() const
     {
@@ -199,6 +204,12 @@
 
 void alignSelectionRectToDevicePixels(FloatRect&);
 
+inline AffineTransform InlineTextBox::rotation(const FloatRect& boxRect, RotationDirection rotationDirection)
+{
+    return rotationDirection == Clockwise ? AffineTransform(0, 1, -1, 0, boxRect.x() + boxRect.maxY(), boxRect.maxY() - boxRect.x())
+        : AffineTransform(0, -1, 1, 0, boxRect.x() - boxRect.maxY(), boxRect.x() + boxRect.maxY());
+}
+
 } // namespace WebCore
 
 #endif // InlineTextBox_h
diff --git a/Source/core/rendering/LayerPaintingInfo.h b/Source/core/rendering/LayerPaintingInfo.h
index b9af031..421e61b 100644
--- a/Source/core/rendering/LayerPaintingInfo.h
+++ b/Source/core/rendering/LayerPaintingInfo.h
@@ -74,13 +74,12 @@
 struct LayerPaintingInfo {
     LayerPaintingInfo(RenderLayer* inRootLayer, const LayoutRect& inDirtyRect,
         PaintBehavior inPaintBehavior, const LayoutSize& inSubPixelAccumulation,
-        RenderObject* inPaintingRoot = 0, RenderRegion*inRegion = 0,
+        RenderObject* inPaintingRoot = 0,
         OverlapTestRequestMap* inOverlapTestRequests = 0)
         : rootLayer(inRootLayer)
         , paintingRoot(inPaintingRoot)
         , paintDirtyRect(inDirtyRect)
         , subPixelAccumulation(inSubPixelAccumulation)
-        , region(inRegion)
         , overlapTestRequests(inOverlapTestRequests)
         , paintBehavior(inPaintBehavior)
         , clipToDirtyRect(true)
@@ -89,7 +88,6 @@
     RenderObject* paintingRoot; // only paint descendants of this object
     LayoutRect paintDirtyRect; // relative to rootLayer;
     LayoutSize subPixelAccumulation;
-    RenderRegion* region; // May be null.
     OverlapTestRequestMap* overlapTestRequests; // May be null.
     PaintBehavior paintBehavior;
     bool clipToDirtyRect;
diff --git a/Source/core/rendering/LayoutState.cpp b/Source/core/rendering/LayoutState.cpp
index 1837cbf..8c46caa 100644
--- a/Source/core/rendering/LayoutState.cpp
+++ b/Source/core/rendering/LayoutState.cpp
@@ -35,7 +35,6 @@
 
 LayoutState::LayoutState(LayoutState* prev, RenderBox* renderer, const LayoutSize& offset, LayoutUnit pageLogicalHeight, bool pageLogicalHeightChanged, ColumnInfo* columnInfo)
     : m_columnInfo(columnInfo)
-    , m_lineGrid(0)
     , m_next(prev)
     , m_shapeInsideInfo(0)
 #ifndef NDEBUG
@@ -69,7 +68,9 @@
         m_clipRect = prev->m_clipRect;
 
     if (renderer->hasOverflowClip()) {
-        LayoutRect clipRect(toPoint(m_paintOffset) + renderer->view()->layoutDelta(), renderer->cachedSizeForOverflowClip());
+        LayoutSize deltaSize = RuntimeEnabledFeatures::repaintAfterLayoutEnabled() ? LayoutSize() : renderer->view()->layoutDelta();
+
+        LayoutRect clipRect(toPoint(m_paintOffset) + deltaSize, renderer->cachedSizeForOverflowClip());
         if (m_clipped)
             m_clipRect.intersect(clipRect);
         else {
@@ -100,34 +101,26 @@
             m_pageLogicalHeight = 0;
     }
 
-    // Propagate line grid information.
-    propagateLineGridInfo(renderer);
-
     if (!m_columnInfo)
         m_columnInfo = m_next->m_columnInfo;
 
     if (renderer->isRenderBlock()) {
         const RenderBlock* renderBlock = toRenderBlock(renderer);
         m_shapeInsideInfo = renderBlock->shapeInsideInfo();
-        if (!m_shapeInsideInfo && m_next->m_shapeInsideInfo && renderBlock->allowsShapeInsideInfoSharing())
+        if (!m_shapeInsideInfo && m_next->m_shapeInsideInfo && renderBlock->allowsShapeInsideInfoSharing(m_next->m_shapeInsideInfo->owner()))
             m_shapeInsideInfo = m_next->m_shapeInsideInfo;
     }
 
-    m_layoutDelta = m_next->m_layoutDelta;
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+        m_layoutDelta = m_next->m_layoutDelta;
 #if !ASSERT_DISABLED
-    m_layoutDeltaXSaturated = m_next->m_layoutDeltaXSaturated;
-    m_layoutDeltaYSaturated = m_next->m_layoutDeltaYSaturated;
+        m_layoutDeltaXSaturated = m_next->m_layoutDeltaXSaturated;
+        m_layoutDeltaYSaturated = m_next->m_layoutDeltaYSaturated;
 #endif
+    }
 
     m_isPaginated = m_pageLogicalHeight || m_columnInfo || renderer->isRenderFlowThread();
 
-    if (lineGrid() && renderer->hasColumns() && renderer->style()->hasInlineColumnAxis())
-        computeLineGridPaginationOrigin(renderer);
-
-    // If we have a new grid to track, then add it to our set.
-    if (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isRenderBlockFlow())
-        establishLineGrid(toRenderBlockFlow(renderer));
-
     // FIXME: <http://bugs.webkit.org/show_bug.cgi?id=13443> Apply control clip if present.
 }
 
@@ -140,7 +133,6 @@
     , m_layoutDeltaYSaturated(false)
 #endif
     , m_columnInfo(0)
-    , m_lineGrid(0)
     , m_next(0)
     , m_shapeInsideInfo(0)
     , m_pageLogicalHeight(0)
@@ -177,7 +169,7 @@
     m_columnInfo = m_next->m_columnInfo;
 }
 
-LayoutUnit LayoutState::pageLogicalOffset(RenderBox* child, LayoutUnit childLogicalOffset) const
+LayoutUnit LayoutState::pageLogicalOffset(const RenderBox* child, LayoutUnit childLogicalOffset) const
 {
     if (child->isHorizontalWritingMode())
         return m_layoutOffset.height() + childLogicalOffset - m_pageOffset.height();
@@ -191,84 +183,4 @@
     m_columnInfo->addForcedBreak(pageLogicalOffset(child, childLogicalOffset));
 }
 
-void LayoutState::propagateLineGridInfo(RenderBox* renderer)
-{
-    // Disable line grids for objects we don't support. For now this includes overflow:scroll/auto, inline blocks and
-    // writing mode roots.
-    if (!m_next || renderer->isUnsplittableForPagination())
-        return;
-
-    m_lineGrid = m_next->m_lineGrid;
-    m_lineGridOffset = m_next->m_lineGridOffset;
-    m_lineGridPaginationOrigin = m_next->m_lineGridPaginationOrigin;
-}
-
-void LayoutState::establishLineGrid(RenderBlockFlow* block)
-{
-    // First check to see if this grid has been established already.
-    if (m_lineGrid) {
-        if (m_lineGrid->style()->lineGrid() == block->style()->lineGrid())
-            return;
-        RenderBlockFlow* currentGrid = m_lineGrid;
-        for (LayoutState* currentState = m_next; currentState; currentState = currentState->m_next) {
-            if (currentState->m_lineGrid == currentGrid)
-                continue;
-            currentGrid = currentState->m_lineGrid;
-            if (!currentGrid)
-                break;
-            if (currentGrid->style()->lineGrid() == block->style()->lineGrid()) {
-                m_lineGrid = currentGrid;
-                m_lineGridOffset = currentState->m_lineGridOffset;
-                return;
-            }
-        }
-    }
-
-    // We didn't find an already-established grid with this identifier. Our render object establishes the grid.
-    m_lineGrid = block;
-    m_lineGridOffset = m_layoutOffset;
-}
-
-void LayoutState::computeLineGridPaginationOrigin(RenderBox* renderer)
-{
-    // We need to cache a line grid pagination origin so that we understand how to reset the line grid
-    // at the top of each column.
-    // Get the current line grid and offset.
-    if (!lineGrid() || lineGrid()->style()->writingMode() != renderer->style()->writingMode())
-        return;
-
-    // Get the hypothetical line box used to establish the grid.
-    RootInlineBox* lineGridBox = lineGrid()->lineGridBox();
-    if (!lineGridBox)
-        return;
-
-    bool isHorizontalWritingMode = lineGrid()->isHorizontalWritingMode();
-
-    LayoutUnit lineGridBlockOffset = isHorizontalWritingMode ? lineGridOffset().height() : lineGridOffset().width();
-
-    // Now determine our position on the grid. Our baseline needs to be adjusted to the nearest baseline multiple
-    // as established by the line box.
-    // FIXME: Need to handle crazy line-box-contain values that cause the root line box to not be considered. I assume
-    // the grid should honor line-box-contain.
-    LayoutUnit gridLineHeight = lineGridBox->lineBottomWithLeading() - lineGridBox->lineTopWithLeading();
-    if (!gridLineHeight)
-        return;
-
-    LayoutUnit firstLineTopWithLeading = lineGridBlockOffset + lineGridBox->lineTopWithLeading();
-
-    if (isPaginated() && pageLogicalHeight()) {
-        LayoutUnit pageLogicalTop = renderer->isHorizontalWritingMode() ? m_pageOffset.height() : m_pageOffset.width();
-        if (pageLogicalTop > firstLineTopWithLeading) {
-            // Shift to the next highest line grid multiple past the page logical top. Cache the delta
-            // between this new value and the page logical top as the pagination origin.
-            LayoutUnit remainder = roundToInt(pageLogicalTop - firstLineTopWithLeading) % roundToInt(gridLineHeight);
-            LayoutUnit paginationDelta = gridLineHeight - remainder;
-            if (isHorizontalWritingMode)
-                m_lineGridPaginationOrigin.setHeight(paginationDelta);
-            else
-                m_lineGridPaginationOrigin.setWidth(paginationDelta);
-        }
-    }
-}
-
 } // namespace WebCore
diff --git a/Source/core/rendering/LayoutState.h b/Source/core/rendering/LayoutState.h
index 16aa5b6..bc38e74 100644
--- a/Source/core/rendering/LayoutState.h
+++ b/Source/core/rendering/LayoutState.h
@@ -51,7 +51,6 @@
         , m_layoutDeltaYSaturated(false)
 #endif
         , m_columnInfo(0)
-        , m_lineGrid(0)
         , m_next(0)
         , m_shapeInsideInfo(0)
         , m_pageLogicalHeight(0)
@@ -69,36 +68,27 @@
     void operator delete(void*);
 
     void clearPaginationInformation();
-    bool isPaginatingColumns() const { return m_columnInfo && m_columnInfo->paginationUnit() == ColumnInfo::Column; }
+    bool isPaginatingColumns() const { return m_columnInfo; }
     bool isPaginated() const { return m_isPaginated; }
 
     // The page logical offset is the object's offset from the top of the page in the page progression
     // direction (so an x-offset in vertical text and a y-offset for horizontal text).
-    LayoutUnit pageLogicalOffset(RenderBox*, LayoutUnit childLogicalOffset) const;
+    LayoutUnit pageLogicalOffset(const RenderBox*, LayoutUnit childLogicalOffset) const;
 
     void addForcedColumnBreak(RenderBox*, LayoutUnit childLogicalOffset);
 
     LayoutUnit pageLogicalHeight() const { return m_pageLogicalHeight; }
     bool pageLogicalHeightChanged() const { return m_pageLogicalHeightChanged; }
 
-    RenderBlockFlow* lineGrid() const { return m_lineGrid; }
-    LayoutSize lineGridOffset() const { return m_lineGridOffset; }
-    LayoutSize lineGridPaginationOrigin() const { return m_lineGridPaginationOrigin; }
-
     LayoutSize layoutOffset() const { return m_layoutOffset; }
 
-    bool needsBlockDirectionLocationSetBeforeLayout() const { return m_lineGrid || (m_isPaginated && m_pageLogicalHeight); }
+    bool needsBlockDirectionLocationSetBeforeLayout() const { return m_isPaginated && m_pageLogicalHeight; }
 
     ShapeInsideInfo* shapeInsideInfo() const { return m_shapeInsideInfo; }
 
 #ifndef NDEBUG
     RenderObject* renderer() const { return m_renderer; }
 #endif
-private:
-    void propagateLineGridInfo(RenderBox*);
-    void establishLineGrid(RenderBlockFlow*);
-
-    void computeLineGridPaginationOrigin(RenderBox*);
 
 public:
     // Do not add anything apart from bitfields until after m_columnInfo. See https://bugs.webkit.org/show_bug.cgi?id=100173
@@ -112,8 +102,6 @@
 #endif
     // If the enclosing pagination model is a column model, then this will store column information for easy retrieval/manipulation.
     ColumnInfo* m_columnInfo;
-    // The current line grid that we're snapping to and the offset of the start of the grid.
-    RenderBlockFlow* m_lineGrid;
     LayoutState* m_next;
     ShapeInsideInfo* m_shapeInsideInfo;
 
@@ -134,8 +122,6 @@
     LayoutUnit m_pageLogicalHeight;
     // The offset of the start of the first page in the nearest enclosing pagination model.
     LayoutSize m_pageOffset;
-    LayoutSize m_lineGridOffset;
-    LayoutSize m_lineGridPaginationOrigin;
 
 #ifndef NDEBUG
     RenderObject* m_renderer;
diff --git a/Source/core/rendering/Pagination.cpp b/Source/core/rendering/Pagination.cpp
deleted file mode 100644
index 26822b0..0000000
--- a/Source/core/rendering/Pagination.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/rendering/Pagination.h"
-
-#include "core/rendering/style/RenderStyle.h"
-
-namespace WebCore {
-
-void Pagination::setStylesForPaginationMode(Mode paginationMode, RenderStyle* style)
-{
-    if (paginationMode == Unpaginated)
-        return;
-
-    switch (paginationMode) {
-    case LeftToRightPaginated:
-        style->setColumnAxis(HorizontalColumnAxis);
-        if (style->isHorizontalWritingMode())
-            style->setColumnProgression(style->isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
-        else
-            style->setColumnProgression(style->isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
-        break;
-    case RightToLeftPaginated:
-        style->setColumnAxis(HorizontalColumnAxis);
-        if (style->isHorizontalWritingMode())
-            style->setColumnProgression(style->isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
-        else
-            style->setColumnProgression(style->isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
-        break;
-    case TopToBottomPaginated:
-        style->setColumnAxis(VerticalColumnAxis);
-        if (style->isHorizontalWritingMode())
-            style->setColumnProgression(style->isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
-        else
-            style->setColumnProgression(style->isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
-        break;
-    case BottomToTopPaginated:
-        style->setColumnAxis(VerticalColumnAxis);
-        if (style->isHorizontalWritingMode())
-            style->setColumnProgression(style->isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
-        else
-            style->setColumnProgression(style->isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
-        break;
-    case Unpaginated:
-        ASSERT_NOT_REACHED();
-        break;
-    }
-}
-
-} // namespace WebCore
diff --git a/Source/core/rendering/Pagination.h b/Source/core/rendering/Pagination.h
deleted file mode 100644
index ce695f7..0000000
--- a/Source/core/rendering/Pagination.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. 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 APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
- */
-
-#ifndef Pagination_h
-#define Pagination_h
-
-namespace WebCore {
-
-class RenderStyle;
-
-struct Pagination {
-    enum Mode { Unpaginated, LeftToRightPaginated, RightToLeftPaginated, TopToBottomPaginated, BottomToTopPaginated };
-
-    Pagination()
-        : mode(Unpaginated)
-        , behavesLikeColumns(false)
-        , pageLength(0)
-        , gap(0)
-    {
-    };
-
-    bool operator==(const Pagination& other) const
-    {
-        return mode == other.mode && behavesLikeColumns == other.behavesLikeColumns && pageLength == other.pageLength && gap == other.gap;
-    }
-
-    bool operator!=(const Pagination& other) const
-    {
-        return mode != other.mode || behavesLikeColumns != other.behavesLikeColumns || pageLength != other.pageLength || gap != other.gap;
-    }
-
-    Mode mode;
-    bool behavesLikeColumns;
-    unsigned pageLength;
-    unsigned gap;
-
-    static void setStylesForPaginationMode(Mode, RenderStyle*);
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/rendering/PaintInfo.h b/Source/core/rendering/PaintInfo.h
index be99ec3..c6940e3 100644
--- a/Source/core/rendering/PaintInfo.h
+++ b/Source/core/rendering/PaintInfo.h
@@ -40,7 +40,6 @@
 class RenderInline;
 class RenderLayerModelObject;
 class RenderObject;
-class RenderRegion;
 class RenderWidget;
 
 typedef HashMap<RenderWidget*, IntRect> OverlapTestRequestMap;
@@ -51,14 +50,13 @@
  */
 struct PaintInfo {
     PaintInfo(GraphicsContext* newContext, const IntRect& newRect, PaintPhase newPhase, PaintBehavior newPaintBehavior,
-        RenderObject* newPaintingRoot = 0, RenderRegion* region = 0, ListHashSet<RenderInline*>* newOutlineObjects = 0,
+        RenderObject* newPaintingRoot = 0, ListHashSet<RenderInline*>* newOutlineObjects = 0,
         OverlapTestRequestMap* overlapTestRequests = 0, const RenderLayerModelObject* newPaintContainer = 0)
         : context(newContext)
         , rect(newRect)
         , phase(newPhase)
         , paintBehavior(newPaintBehavior)
         , paintingRoot(newPaintingRoot)
-        , renderRegion(region)
         , overlapTestRequests(overlapTestRequests)
         , m_paintContainer(newPaintContainer)
         , m_outlineObjects(newOutlineObjects)
@@ -87,9 +85,9 @@
     bool skipRootBackground() const { return paintBehavior & PaintBehaviorSkipRootBackground; }
     bool paintRootBackgroundOnly() const { return paintBehavior & PaintBehaviorRootBackgroundOnly; }
 
-    void applyTransform(const AffineTransform& localToAncestorTransform)
+    void applyTransform(const AffineTransform& localToAncestorTransform, bool identityStatusUnknown = true)
     {
-        if (localToAncestorTransform.isIdentity())
+        if (identityStatusUnknown && localToAncestorTransform.isIdentity())
             return;
 
         context->concatCTM(localToAncestorTransform);
@@ -112,7 +110,6 @@
     PaintPhase phase;
     PaintBehavior paintBehavior;
     RenderObject* paintingRoot; // used to draw just one element and its visual kids
-    RenderRegion* renderRegion;
     OverlapTestRequestMap* overlapTestRequests;
 
 private:
diff --git a/Source/core/rendering/RegionOversetState.h b/Source/core/rendering/RegionOversetState.h
deleted file mode 100644
index e29e370..0000000
--- a/Source/core/rendering/RegionOversetState.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef RegionOversetState_h
-#define RegionOversetState_h
-
-namespace WebCore {
-
-enum RegionOversetState {
-    RegionUndefined,
-    RegionEmpty,
-    RegionFit,
-    RegionOverset
-};
-
-} // namespace WebCore
-
-#endif // RegionOversetState_h
diff --git a/Source/core/rendering/RenderApplet.h b/Source/core/rendering/RenderApplet.h
index 3a0f7af..9f740f4 100644
--- a/Source/core/rendering/RenderApplet.h
+++ b/Source/core/rendering/RenderApplet.h
@@ -34,7 +34,7 @@
     virtual ~RenderApplet();
 
 private:
-    virtual const char* renderName() const { return "RenderApplet"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderApplet"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderBR.cpp b/Source/core/rendering/RenderBR.cpp
index ea74001..7704a1e 100644
--- a/Source/core/rendering/RenderBR.cpp
+++ b/Source/core/rendering/RenderBR.cpp
@@ -48,11 +48,11 @@
     if (firstLine && document().styleEngine()->usesFirstLineRules()) {
         RenderStyle* s = style(firstLine);
         if (s != style())
-            return s->computedLineHeight(view());
+            return s->computedLineHeight();
     }
 
     if (m_lineHeight == -1)
-        m_lineHeight = style()->computedLineHeight(view());
+        m_lineHeight = style()->computedLineHeight();
 
     return m_lineHeight;
 }
diff --git a/Source/core/rendering/RenderBR.h b/Source/core/rendering/RenderBR.h
index 62d1a53..e94ca2d 100644
--- a/Source/core/rendering/RenderBR.h
+++ b/Source/core/rendering/RenderBR.h
@@ -36,25 +36,25 @@
     explicit RenderBR(Node*);
     virtual ~RenderBR();
 
-    virtual const char* renderName() const { return "RenderBR"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderBR"; }
 
     virtual LayoutRect selectionRectForRepaint(const RenderLayerModelObject* /*repaintContainer*/, bool /*clipToVisibleContent*/) OVERRIDE { return LayoutRect(); }
 
-    virtual float width(unsigned /*from*/, unsigned /*len*/, const Font&, float /*xPos*/, HashSet<const SimpleFontData*>* = 0 /*fallbackFonts*/ , GlyphOverflow* = 0) const { return 0; }
-    virtual float width(unsigned /*from*/, unsigned /*len*/, float /*xpos*/, bool = false /*firstLine*/, HashSet<const SimpleFontData*>* = 0 /*fallbackFonts*/, GlyphOverflow* = 0) const { return 0; }
+    virtual float width(unsigned /*from*/, unsigned /*len*/, const Font&, float /*xPos*/, TextDirection, HashSet<const SimpleFontData*>* = 0 /*fallbackFonts*/ , GlyphOverflow* = 0) const OVERRIDE { return 0; }
+    virtual float width(unsigned /*from*/, unsigned /*len*/, float /*xpos*/, TextDirection, bool = false /*firstLine*/, HashSet<const SimpleFontData*>* = 0 /*fallbackFonts*/, GlyphOverflow* = 0) const OVERRIDE { return 0; }
 
     int lineHeight(bool firstLine) const;
 
     // overrides
-    virtual bool isBR() const { return true; }
+    virtual bool isBR() const OVERRIDE { return true; }
 
-    virtual int caretMinOffset() const;
-    virtual int caretMaxOffset() const;
+    virtual int caretMinOffset() const OVERRIDE;
+    virtual int caretMaxOffset() const OVERRIDE;
 
     virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE FINAL;
 
 protected:
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
 private:
     mutable int m_lineHeight;
diff --git a/Source/core/rendering/RenderBlock.cpp b/Source/core/rendering/RenderBlock.cpp
index 17b0167..bfefb11 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -36,7 +36,7 @@
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/FastTextAutosizer.h"
 #include "core/rendering/GraphicsContextAnnotator.h"
 #include "core/rendering/HitTestLocation.h"
@@ -49,12 +49,13 @@
 #include "core/rendering/RenderCombineText.h"
 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
 #include "core/rendering/RenderFlexibleBox.h"
+#include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderMarquee.h"
-#include "core/rendering/RenderNamedFlowThread.h"
 #include "core/rendering/RenderRegion.h"
 #include "core/rendering/RenderTableCell.h"
+#include "core/rendering/RenderTextControl.h"
 #include "core/rendering/RenderTextFragment.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
@@ -82,7 +83,15 @@
     uint32_t bitfields;
 };
 
+struct SameSizeAsRenderBlockRareData {
+    int paginationStrut;
+    int pageLogicalOffset;
+    void* pointers[1];
+    uint32_t bitfields;
+};
+
 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
+COMPILE_ASSERT(sizeof(RenderBlock::RenderBlockRareData) == sizeof(SameSizeAsRenderBlockRareData), RenderBlockRareData_should_stay_small);
 
 typedef WTF::HashMap<const RenderBox*, OwnPtr<ColumnInfo> > ColumnInfoMap;
 static ColumnInfoMap* gColumnInfoMap = 0;
@@ -150,6 +159,7 @@
     , m_beingDestroyed(false)
     , m_hasMarkupTruncation(false)
     , m_hasBorderOrPaddingLogicalWidthChanged(false)
+    , m_hasOnlySelfCollapsingChildren(false)
 {
     setChildrenInline(true);
 }
@@ -174,8 +184,11 @@
 
 static void appendImageIfNotNull(Vector<ImageResource*>& imageResources, const StyleImage* styleImage)
 {
-    if (styleImage && styleImage->cachedImage())
-        imageResources.append(styleImage->cachedImage());
+    if (styleImage && styleImage->cachedImage()) {
+        ImageResource* imageResource = styleImage->cachedImage();
+        if (imageResource && !imageResource->isLoaded())
+            imageResources.append(styleImage->cachedImage());
+    }
 }
 
 static void appendLayers(Vector<ImageResource*>& images, const FillLayer* styleLayer)
@@ -185,8 +198,26 @@
     }
 }
 
+static void appendImagesFromStyle(Vector<ImageResource*>& images, RenderStyle& blockStyle)
+{
+    appendLayers(images, blockStyle.backgroundLayers());
+    appendLayers(images, blockStyle.maskLayers());
+
+    const ContentData* contentData = blockStyle.contentData();
+    if (contentData && contentData->isImage()) {
+        const ImageContentData* imageContentData = static_cast<const ImageContentData*>(contentData);
+        appendImageIfNotNull(images, imageContentData->image());
+    }
+    if (blockStyle.boxReflect())
+        appendImageIfNotNull(images, blockStyle.boxReflect()->mask().image());
+    appendImageIfNotNull(images, blockStyle.listStyleImage());
+    appendImageIfNotNull(images, blockStyle.borderImageSource());
+    appendImageIfNotNull(images, blockStyle.maskBoxImageSource());
+}
+
 RenderBlock::~RenderBlock()
 {
+    ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
     if (hasColumns())
         gColumnInfoMap->take(this);
     if (gPercentHeightDescendantsMap)
@@ -240,8 +271,7 @@
     if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
         gDelayedUpdateScrollInfoSet->remove(this);
 
-    FastTextAutosizer* textAutosizer = document().fastTextAutosizer();
-    if (textAutosizer)
+    if (FastTextAutosizer* textAutosizer = document().fastTextAutosizer())
         textAutosizer->destroy(this);
 
     RenderBox::willBeDestroyed();
@@ -310,8 +340,7 @@
         }
     }
 
-    FastTextAutosizer* textAutosizer = document().fastTextAutosizer();
-    if (textAutosizer)
+    if (FastTextAutosizer* textAutosizer = document().fastTextAutosizer())
         textAutosizer->record(this);
 
     propagateStyleToAnonymousChildren(true);
@@ -320,6 +349,15 @@
     // It's possible for our border/padding to change, but for the overall logical width of the block to
     // end up being the same. We keep track of this change so in layoutBlock, we can know to set relayoutChildren=true.
     m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
+
+    // If the style has unloaded images, want to notify the ResourceLoadPriorityOptimizer so that
+    // network priorities can be set.
+    Vector<ImageResource*> images;
+    appendImagesFromStyle(images, *newStyle);
+    if (images.isEmpty())
+        ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
+    else
+        ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this);
 }
 
 RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
@@ -725,7 +763,7 @@
                 || beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
                 ) {
                 // Insert the child into the anonymous block box instead of here.
-                if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
+                if (newChild->isInline() || newChild->isFloatingOrOutOfFlowPositioned() || beforeChild->parent()->firstChild() != beforeChild)
                     beforeChild->parent()->addChild(newChild, beforeChild);
                 else
                     addChild(newChild, beforeChild->parent());
@@ -886,19 +924,6 @@
         cache->recomputeIsIgnored(this);
 }
 
-RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
-{
-    RootInlineBox* rootBox = createRootInlineBox();
-    m_lineBoxes.appendLineBox(rootBox);
-
-    if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
-        if (AXObjectCache* cache = document().existingAXObjectCache())
-            cache->recomputeIsIgnored(this);
-    }
-
-    return rootBox;
-}
-
 void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
 {
     // makeChildrenNonInline takes a block whose children are *all* inline and it
@@ -1033,8 +1058,6 @@
     // Explicitly delete the child's line box tree, or the special anonymous
     // block handling in willBeDestroyed will cause problems.
     child->deleteLineBoxTree();
-    if (childFlowThread && childFlowThread->isRenderNamedFlowThread())
-        toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(child);
     child->destroy();
 }
 
@@ -1058,8 +1081,8 @@
     bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
     if (canMergeAnonymousBlocks && prev && next) {
         prev->setNeedsLayoutAndPrefWidthsRecalc();
-        RenderBlock* nextBlock = toRenderBlock(next);
-        RenderBlock* prevBlock = toRenderBlock(prev);
+        RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
+        RenderBlockFlow* prevBlock = toRenderBlockFlow(prev);
 
         if (prev->childrenInline() != next->childrenInline()) {
             RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
@@ -1154,12 +1177,22 @@
 
 bool RenderBlock::isSelfCollapsingBlock() const
 {
+    // Placeholder elements are not laid out until the dimensions of their parent text control are known, so they
+    // don't get layout until their parent has had layout - this is unique in the layout tree and means
+    // when we call isSelfCollapsingBlock on them we find that they still need layout.
+    ASSERT(!needsLayout() || (node() && node()->isElementNode() && toElement(node())->shadowPseudoId() == "-webkit-input-placeholder"));
+
     // We are not self-collapsing if we
     // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
     // (b) are a table,
     // (c) have border/padding,
     // (d) have a min-height
     // (e) have specified that one of our margins can't collapse using a CSS extension
+    // (f) establish a new block formatting context.
+
+    if (createsBlockFormattingContext())
+        return false;
+
     if (logicalHeight() > 0
         || isTable() || borderAndPaddingLogicalHeight()
         || style()->logicalMinHeight().isPositive()
@@ -1186,6 +1219,8 @@
 
         // Whether or not we collapse is dependent on whether all our normal flow children
         // are also self-collapsing.
+        if (m_hasOnlySelfCollapsingChildren)
+            return true;
         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
             if (child->isFloatingOrOutOfFlowPositioned())
                 continue;
@@ -1268,42 +1303,13 @@
     invalidateBackgroundObscurationStatus();
 }
 
-void RenderBlock::didLayout(ResourceLoadPriorityOptimizer& optimizer)
+bool RenderBlock::updateImageLoadingPriorities()
 {
-    RenderBox::didLayout(optimizer);
-    updateStyleImageLoadingPriorities(optimizer);
-}
-
-void RenderBlock::didScroll(ResourceLoadPriorityOptimizer& optimizer)
-{
-    RenderBox::didScroll(optimizer);
-    updateStyleImageLoadingPriorities(optimizer);
-}
-
-void RenderBlock::updateStyleImageLoadingPriorities(ResourceLoadPriorityOptimizer& optimizer)
-{
-    RenderStyle* blockStyle = style();
-    if (!blockStyle)
-        return;
-
     Vector<ImageResource*> images;
-
-    appendLayers(images, blockStyle->backgroundLayers());
-    appendLayers(images, blockStyle->maskLayers());
-
-    const ContentData* contentData = blockStyle->contentData();
-    if (contentData && contentData->isImage()) {
-        const ImageContentData* imageContentData = static_cast<const ImageContentData*>(contentData);
-        appendImageIfNotNull(images, imageContentData->image());
-    }
-    if (blockStyle->boxReflect())
-        appendImageIfNotNull(images, blockStyle->boxReflect()->mask().image());
-    appendImageIfNotNull(images, blockStyle->listStyleImage());
-    appendImageIfNotNull(images, blockStyle->borderImageSource());
-    appendImageIfNotNull(images, blockStyle->maskBoxImageSource());
+    appendImagesFromStyle(images, *style());
 
     if (images.isEmpty())
-        return;
+        return false;
 
     LayoutRect viewBounds = viewRect();
     LayoutRect objectBounds = absoluteContentBox();
@@ -1319,7 +1325,9 @@
         ResourceLoadPriorityOptimizer::Visible : ResourceLoadPriorityOptimizer::NotVisible;
 
     for (Vector<ImageResource*>::iterator it = images.begin(), end = images.end(); it != end; ++it)
-        optimizer.notifyImageResourceVisibility(*it, status);
+        ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->notifyImageResourceVisibility(*it, status);
+
+    return true;
 }
 
 void RenderBlock::relayoutShapeDescendantIfMoved(RenderBlock* child, LayoutSize offset)
@@ -1336,18 +1344,20 @@
 
 ShapeInsideInfo* RenderBlock::layoutShapeInsideInfo() const
 {
-    ShapeInsideInfo* shapeInsideInfo = view()->layoutState()->shapeInsideInfo();
+    if (ShapeInsideInfo* shapeInsideInfo = view()->layoutState()->shapeInsideInfo())
+        return shapeInsideInfo;
 
-    if (!shapeInsideInfo && flowThreadContainingBlock() && allowsShapeInsideInfoSharing()) {
+    RenderFlowThread* flowThread = flowThreadContainingBlock();
+    if (allowsShapeInsideInfoSharing(flowThread)) {
         LayoutUnit lineHeight = this->lineHeight(false, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
         // regionAtBlockOffset returns regions like an array first={0,N-1}, second={N,M-1}, ...
         LayoutUnit offset = logicalHeight() + lineHeight - LayoutUnit(1);
         RenderRegion* region = regionAtBlockOffset(offset);
         if (region && region->logicalHeight())
-            shapeInsideInfo = region->shapeInsideInfo();
+            return region->shapeInsideInfo();
     }
 
-    return shapeInsideInfo;
+    return 0;
 }
 
 LayoutSize RenderBlock::logicalOffsetFromShapeAncestorContainer(const RenderBlock* container) const
@@ -1395,10 +1405,6 @@
         shapeInsideInfo->dirtyShapeSize();
         markShapeInsideDescendantsForLayout();
     }
-
-    ShapeValue* shapeOutsideValue = style()->shapeOutside();
-    if (isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image)
-        parent()->setNeedsLayoutAndPrefWidthsRecalc();
 }
 
 void RenderBlock::updateShapeInsideInfoAfterStyleChange(const ShapeValue* shapeInside, const ShapeValue* oldShapeInside)
@@ -1457,14 +1463,8 @@
     if (!shapeInsideInfo)
         return;
 
-    if (isRenderNamedFlowFragment()) {
-        ShapeInsideInfo* parentShapeInsideInfo = toRenderBlock(parent())->shapeInsideInfo();
-        ASSERT(parentShapeInsideInfo);
-        shapeInsideInfo->setShapeSize(parentShapeInsideInfo->shapeSize().width(), parentShapeInsideInfo->shapeSize().height());
-    } else {
-        bool percentageLogicalHeightResolvable = percentageLogicalHeightIsResolvableFromBlock(this, false);
-        shapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
-    }
+    bool percentageLogicalHeightResolvable = percentageLogicalHeightIsResolvableFromBlock(this, false);
+    shapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
 }
 
 void RenderBlock::updateRegionsAndShapesAfterChildLayout(RenderFlowThread* flowThread, bool heightChanged)
@@ -1497,37 +1497,7 @@
     return oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth() || hasBorderOrPaddingLogicalWidthChanged;
 }
 
-void RenderBlock::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
-{
-    ColumnInfo* colInfo = columnInfo();
-    if (hasColumns()) {
-        if (!pageLogicalHeight) {
-            // We need to go ahead and set our explicit page height if one exists, so that we can
-            // avoid doing two layout passes.
-            updateLogicalHeight();
-            LayoutUnit columnHeight = contentLogicalHeight();
-            if (columnHeight > 0) {
-                pageLogicalHeight = columnHeight;
-                hasSpecifiedPageLogicalHeight = true;
-            }
-            setLogicalHeight(0);
-        }
-        if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
-            colInfo->setColumnHeight(pageLogicalHeight);
-            pageLogicalHeightChanged = true;
-        }
-
-        if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
-            colInfo->clearForcedBreaks();
-
-        colInfo->setPaginationUnit(paginationUnit());
-    } else if (isRenderFlowThread()) {
-        pageLogicalHeight = 1; // This is just a hack to always make sure we have a page logical height.
-        pageLogicalHeightChanged = toRenderFlowThread(this)->pageLogicalSizeChanged();
-    }
-}
-
-void RenderBlock::layoutBlock(bool, LayoutUnit)
+void RenderBlock::layoutBlock(bool)
 {
     ASSERT_NOT_REACHED();
     clearNeedsLayout();
@@ -1580,9 +1550,6 @@
 
     // Add visual overflow from theme.
     addVisualOverflowFromTheme();
-
-    if (isRenderNamedFlowThread())
-        toRenderNamedFlowThread(this)->computeOversetStateForRegions(oldClientAfterEdge);
 }
 
 void RenderBlock::addOverflowFromBlockChildren()
@@ -1620,34 +1587,10 @@
     addVisualOverflow(inflatedRect);
 }
 
-bool RenderBlock::expandsToEncloseOverhangingFloats() const
+bool RenderBlock::createsBlockFormattingContext() const
 {
     return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || (parent() && parent()->isFlexibleBoxIncludingDeprecated())
-           || hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
-}
-
-LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* region)
-{
-    LayoutUnit startPosition = startOffsetForContent(region);
-
-    // Add in our start margin.
-    LayoutUnit oldPosition = startPosition + childMarginStart;
-    LayoutUnit newPosition = oldPosition;
-
-    LayoutUnit blockOffset = logicalTopForChild(child);
-    if (region)
-        blockOffset = max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage()));
-
-    LayoutUnit startOff = startOffsetForLineInRegion(blockOffset, false, region, logicalHeightForChild(child));
-
-    if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
-        if (childMarginStart < 0)
-            startOff += childMarginStart;
-        newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
-    } else if (startOff != startPosition)
-        newPosition = startOff + childMarginStart;
-
-    return newPosition - oldPosition;
+        || style()->specifiesColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot() || style()->columnSpan();
 }
 
 void RenderBlock::determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode applyDelta)
@@ -1664,7 +1607,7 @@
     // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats.  They need
     // to shift over as necessary to dodge any floats that might get in the way.
     if (child->avoidsFloats() && containsFloats() && !flowThreadContainingBlock())
-        newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
+        newPosition += toRenderBlockFlow(this)->computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
 
     setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
 }
@@ -1672,11 +1615,11 @@
 void RenderBlock::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
 {
     if (isHorizontalWritingMode()) {
-        if (applyDelta == ApplyLayoutDelta)
+        if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
             view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
         child->setX(logicalLeft);
     } else {
-        if (applyDelta == ApplyLayoutDelta)
+        if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
         child->setY(logicalLeft);
     }
@@ -1685,11 +1628,11 @@
 void RenderBlock::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
 {
     if (isHorizontalWritingMode()) {
-        if (applyDelta == ApplyLayoutDelta)
+        if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
         child->setY(logicalTop);
     } else {
-        if (applyDelta == ApplyLayoutDelta)
+        if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
             view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
         child->setX(logicalTop);
     }
@@ -1748,6 +1691,8 @@
     if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
         return false;
 
+    FastTextAutosizer::LayoutScope fastTextAutosizerLayoutScope(document(), this);
+
     // Lay out positioned descendants or objects that just need to recompute overflow.
     if (needsSimplifiedNormalFlowLayout())
         simplifiedNormalFlowLayout();
@@ -2648,38 +2593,18 @@
 
 LayoutUnit RenderBlock::logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
 {
-    LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
-    if (logicalLeft == logicalLeftOffsetForContent()) {
-        if (rootBlock != this)
-            // The border can potentially be further extended by our containingBlock().
-            return containingBlock()->logicalLeftSelectionOffset(rootBlock, position + logicalTop());
-        return logicalLeft;
-    } else {
-        RenderBlock* cb = this;
-        while (cb != rootBlock) {
-            logicalLeft += cb->logicalLeft();
-            cb = cb->containingBlock();
-        }
-    }
-    return logicalLeft;
+    // The border can potentially be further extended by our containingBlock().
+    if (rootBlock != this)
+        return containingBlock()->logicalLeftSelectionOffset(rootBlock, position + logicalTop());
+    return logicalLeftOffsetForContent();
 }
 
 LayoutUnit RenderBlock::logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
 {
-    LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
-    if (logicalRight == logicalRightOffsetForContent()) {
-        if (rootBlock != this)
-            // The border can potentially be further extended by our containingBlock().
-            return containingBlock()->logicalRightSelectionOffset(rootBlock, position + logicalTop());
-        return logicalRight;
-    } else {
-        RenderBlock* cb = this;
-        while (cb != rootBlock) {
-            logicalRight += cb->logicalLeft();
-            cb = cb->containingBlock();
-        }
-    }
-    return logicalRight;
+    // The border can potentially be further extended by our containingBlock().
+    if (rootBlock != this)
+        return containingBlock()->logicalRightSelectionOffset(rootBlock, position + logicalTop());
+    return logicalRightOffsetForContent();
 }
 
 RenderBlock* RenderBlock::blockBeforeWithinSelectionRoot(LayoutSize& offset) const
@@ -2913,107 +2838,9 @@
 LayoutUnit RenderBlock::textIndentOffset() const
 {
     LayoutUnit cw = 0;
-    RenderView* renderView = 0;
     if (style()->textIndent().isPercent())
         cw = containingBlock()->availableLogicalWidth();
-    else if (style()->textIndent().isViewportPercentage())
-        renderView = view();
-    return minimumValueForLength(style()->textIndent(), cw, renderView);
-}
-
-LayoutUnit RenderBlock::logicalLeftOffsetForContent(RenderRegion* region) const
-{
-    LayoutUnit logicalLeftOffset = style()->isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
-    if (!region)
-        return logicalLeftOffset;
-    LayoutRect boxRect = borderBoxRectInRegion(region);
-    return logicalLeftOffset + (isHorizontalWritingMode() ? boxRect.x() : boxRect.y());
-}
-
-LayoutUnit RenderBlock::logicalRightOffsetForContent(RenderRegion* region) const
-{
-    LayoutUnit logicalRightOffset = style()->isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
-    logicalRightOffset += availableLogicalWidth();
-    if (!region)
-        return logicalRightOffset;
-    LayoutRect boxRect = borderBoxRectInRegion(region);
-    return logicalRightOffset - (logicalWidth() - (isHorizontalWritingMode() ? boxRect.maxX() : boxRect.maxY()));
-}
-
-LayoutUnit RenderBlock::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
-{
-    LayoutUnit left = offsetFromFloats;
-
-    if (applyTextIndent && style()->isLeftToRightDirection())
-        left += textIndentOffset();
-
-    if (style()->lineAlign() == LineAlignNone)
-        return left;
-
-    // Push in our left offset so that it is aligned with the character grid.
-    LayoutState* layoutState = view()->layoutState();
-    if (!layoutState)
-        return left;
-
-    RenderBlock* lineGrid = layoutState->lineGrid();
-    if (!lineGrid || lineGrid->style()->writingMode() != style()->writingMode())
-        return left;
-
-    // FIXME: Should letter-spacing apply? This is complicated since it doesn't apply at the edge?
-    float maxCharWidth = lineGrid->style()->font().primaryFont()->maxCharWidth();
-    if (!maxCharWidth)
-        return left;
-
-    LayoutUnit lineGridOffset = lineGrid->isHorizontalWritingMode() ? layoutState->lineGridOffset().width(): layoutState->lineGridOffset().height();
-    LayoutUnit layoutOffset = lineGrid->isHorizontalWritingMode() ? layoutState->layoutOffset().width() : layoutState->layoutOffset().height();
-
-    // Push in to the nearest character width.
-    // FIXME: This is wrong for RTL (https://bugs.webkit.org/show_bug.cgi?id=79945).
-    // FIXME: This doesn't work with columns or regions (https://bugs.webkit.org/show_bug.cgi?id=79942).
-    // FIXME: This doesn't work when the inline position of the object isn't set ahead of time.
-    // FIXME: Dynamic changes to the font or to the inline position need to result in a deep relayout.
-    // (https://bugs.webkit.org/show_bug.cgi?id=79944)
-    float remainder = fmodf(maxCharWidth - fmodf(left + layoutOffset - lineGridOffset, maxCharWidth), maxCharWidth);
-    left += remainder;
-    return left;
-}
-
-LayoutUnit RenderBlock::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
-{
-    LayoutUnit right = offsetFromFloats;
-
-    if (applyTextIndent && !style()->isLeftToRightDirection())
-        right -= textIndentOffset();
-
-    if (style()->lineAlign() == LineAlignNone)
-        return right;
-
-    // Push in our right offset so that it is aligned with the character grid.
-    LayoutState* layoutState = view()->layoutState();
-    if (!layoutState)
-        return right;
-
-    RenderBlock* lineGrid = layoutState->lineGrid();
-    if (!lineGrid || lineGrid->style()->writingMode() != style()->writingMode())
-        return right;
-
-    // FIXME: Should letter-spacing apply? This is complicated since it doesn't apply at the edge?
-    float maxCharWidth = lineGrid->style()->font().primaryFont()->maxCharWidth();
-    if (!maxCharWidth)
-        return right;
-
-    LayoutUnit lineGridOffset = lineGrid->isHorizontalWritingMode() ? layoutState->lineGridOffset().width(): layoutState->lineGridOffset().height();
-    LayoutUnit layoutOffset = lineGrid->isHorizontalWritingMode() ? layoutState->layoutOffset().width() : layoutState->layoutOffset().height();
-
-    // Push in to the nearest character width.
-    // FIXME: This is wrong for RTL (https://bugs.webkit.org/show_bug.cgi?id=79945).
-    // FIXME: This doesn't work with columns or regions (https://bugs.webkit.org/show_bug.cgi?id=79942).
-    // FIXME: This doesn't work when the inline position of the object isn't set ahead of time.
-    // FIXME: Dynamic changes to the font or to the inline position need to result in a deep relayout.
-    // (https://bugs.webkit.org/show_bug.cgi?id=79944)
-    float remainder = fmodf(fmodf(right + layoutOffset - lineGridOffset, maxCharWidth), maxCharWidth);
-    right -= LayoutUnit::fromFloatCeil(remainder);
-    return right;
+    return minimumValueForLength(style()->textIndent(), cw);
 }
 
 void RenderBlock::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
@@ -3086,7 +2913,9 @@
             return false;
     }
 
-    if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && isPointInOverflowControl(result, locationInContainer.point(), adjustedLocation)) {
+    if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground)
+        && visibleToHitTestRequest(request)
+        && isPointInOverflowControl(result, locationInContainer.point(), adjustedLocation)) {
         updateHitTestResult(result, locationInContainer.point() - localOffset);
         // FIXME: isPointInOverflowControl() doesn't handle rect-based tests yet.
         if (!result.addNodeToRectBasedTestResult(nodeForHitTest(), request, locationInContainer))
@@ -3096,7 +2925,7 @@
     // If we have clipping, then we can't have any spillout.
     bool useOverflowClip = hasOverflowClip() && !hasSelfPaintingLayer();
     bool useClip = (hasControlClip() || useOverflowClip);
-    bool checkChildren = !useClip || (hasControlClip() ? locationInContainer.intersects(controlClipRect(adjustedLocation)) : locationInContainer.intersects(overflowClipRect(adjustedLocation, locationInContainer.region(), IncludeOverlayScrollbarSize)));
+    bool checkChildren = !useClip || (hasControlClip() ? locationInContainer.intersects(controlClipRect(adjustedLocation)) : locationInContainer.intersects(overflowClipRect(adjustedLocation, IncludeOverlayScrollbarSize)));
     if (checkChildren) {
         // Hit test descendants first.
         LayoutSize scrolledOffset(localOffset);
@@ -3121,7 +2950,7 @@
     if (!isRenderView() && style()->hasBorderRadius()) {
         LayoutRect borderRect = borderBoxRect();
         borderRect.moveBy(adjustedLocation);
-        RoundedRect border = style()->getRoundedBorderFor(borderRect, view());
+        RoundedRect border = style()->getRoundedBorderFor(borderRect);
         if (!locationInContainer.intersects(border))
             return false;
     }
@@ -3237,9 +3066,6 @@
 
 bool RenderBlock::hitTestContents(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
 {
-    if (isRenderRegion())
-        return toRenderRegion(this)->hitTestFlowThreadContents(request, result, locationInContainer, accumulatedOffset, hitTestAction);
-
     if (childrenInline() && !isTable()) {
         // We have to hit-test our line boxes.
         if (m_lineBoxes.hitTest(this, request, result, locationInContainer, accumulatedOffset, hitTestAction))
@@ -3528,9 +3354,9 @@
 
 bool RenderBlock::requiresColumns(int desiredColumnCount) const
 {
-    // If overflow-y is set to paged-x or paged-y on the body or html element, we'll handle the paginating
-    // in the RenderView instead.
-    bool isPaginated = (style()->overflowY() == OPAGEDX || style()->overflowY() == OPAGEDY) && !(isRoot() || isBody());
+    // Paged overflow is treated as multicol here, unless this element was the one that got its
+    // overflow propagated to the viewport.
+    bool isPaginated = style()->isOverflowPaged() && node() != document().viewportDefiningElement();
 
     return firstChild()
         && (desiredColumnCount != 1 || !style()->hasAutoColumnWidth() || !style()->hasInlineColumnAxis() || isPaginated)
@@ -3557,39 +3383,17 @@
             gColumnInfoMap->add(this, adoptPtr(info));
             setHasColumns(true);
         }
-        info->setDesiredColumnCount(count);
         info->setDesiredColumnWidth(width);
-        info->setProgressionAxis(style()->hasInlineColumnAxis() ? ColumnInfo::InlineAxis : ColumnInfo::BlockAxis);
-        info->setProgressionIsReversed(style()->columnProgression() == ReverseColumnProgression);
+        if (style()->isOverflowPaged()) {
+            info->setProgressionAxis(style()->hasInlinePaginationAxis() ? ColumnInfo::InlineAxis : ColumnInfo::BlockAxis);
+        } else {
+            info->setDesiredColumnCount(count);
+            info->setProgressionAxis(style()->hasInlineColumnAxis() ? ColumnInfo::InlineAxis : ColumnInfo::BlockAxis);
+            info->setProgressionIsReversed(style()->columnProgression() == ReverseColumnProgression);
+        }
     }
 }
 
-void RenderBlock::updateColumnInfoFromStyle(RenderStyle* style)
-{
-    if (!hasColumns())
-        return;
-
-    ColumnInfo* info = gColumnInfoMap->get(this);
-
-    bool needsLayout = false;
-    ColumnInfo::Axis oldAxis = info->progressionAxis();
-    ColumnInfo::Axis newAxis = style->hasInlineColumnAxis() ? ColumnInfo::InlineAxis : ColumnInfo::BlockAxis;
-    if (oldAxis != newAxis) {
-        info->setProgressionAxis(newAxis);
-        needsLayout = true;
-    }
-
-    bool oldProgressionIsReversed = info->progressionIsReversed();
-    bool newProgressionIsReversed = style->columnProgression() == ReverseColumnProgression;
-    if (oldProgressionIsReversed != newProgressionIsReversed) {
-        info->setProgressionIsReversed(newProgressionIsReversed);
-        needsLayout = true;
-    }
-
-    if (needsLayout)
-        setNeedsLayoutAndPrefWidthsRecalc();
-}
-
 LayoutUnit RenderBlock::desiredColumnWidth() const
 {
     if (!hasColumns())
@@ -3597,13 +3401,6 @@
     return gColumnInfoMap->get(this)->desiredColumnWidth();
 }
 
-unsigned RenderBlock::desiredColumnCount() const
-{
-    if (!hasColumns())
-        return 1;
-    return gColumnInfoMap->get(this)->desiredColumnCount();
-}
-
 ColumnInfo* RenderBlock::columnInfo() const
 {
     if (!hasColumns())
@@ -3645,17 +3442,6 @@
     return LayoutRect(colLogicalTop, colLogicalLeft, colLogicalHeight, colLogicalWidth);
 }
 
-bool RenderBlock::relayoutToAvoidWidows(LayoutStateMaintainer& statePusher)
-{
-    if (!shouldBreakAtLineToAvoidWidow())
-        return false;
-
-    statePusher.pop();
-    setEverHadLayout(true);
-    layoutBlock(false);
-    return true;
-}
-
 void RenderBlock::adjustPointToColumnContents(LayoutPoint& point) const
 {
     // Just bail if we have no columns.
@@ -4058,8 +3844,8 @@
         RenderText* t = toRenderText(trailingSpaceChild);
         const UChar space = ' ';
         const Font& font = t->style()->font(); // FIXME: This ignores first-line.
-        float spaceWidth = font.width(RenderBlockFlow::constructTextRun(t, font, &space, 1, t->style()));
-        inlineMax -= spaceWidth + font.wordSpacing();
+        float spaceWidth = font.width(RenderBlockFlow::constructTextRun(t, font, &space, 1, t->style(), LTR));
+        inlineMax -= spaceWidth + font.fontDescription().wordSpacing();
         if (inlineMin > inlineMax)
             inlineMin = inlineMax;
     }
@@ -4110,7 +3896,7 @@
     // Signals the text indent was more negative than the min preferred width
     bool hasRemainingNegativeTextIndent = false;
 
-    LayoutUnit textIndent = minimumValueForLength(styleToUse->textIndent(), cw, view());
+    LayoutUnit textIndent = minimumValueForLength(styleToUse->textIndent(), cw);
     RenderObject* prevFloat = 0;
     bool isPrevChildInlineFlow = false;
     bool shouldBreakLineAfterText = false;
@@ -4287,7 +4073,7 @@
                 t->trimmedPrefWidths(inlineMax,
                     firstLineMinWidth, hasBreakableStart, lastLineMinWidth, hasBreakableEnd,
                     hasBreakableChar, hasBreak, firstLineMaxWidth, lastLineMaxWidth,
-                    childMin, childMax, stripFrontSpaces);
+                    childMin, childMax, stripFrontSpaces, styleToUse->direction());
 
                 // This text object will not be rendered, but it may still provide a breaking opportunity.
                 if (!hasBreak && childMax == 0) {
@@ -4514,22 +4300,27 @@
     if (firstLine && document().styleEngine()->usesFirstLineRules()) {
         RenderStyle* s = style(firstLine);
         if (s != style())
-            return s->computedLineHeight(view());
+            return s->computedLineHeight();
     }
 
     if (m_lineHeight == -1)
-        m_lineHeight = style()->computedLineHeight(view());
+        m_lineHeight = style()->computedLineHeight();
 
     return m_lineHeight;
 }
 
+int RenderBlock::beforeMarginInLineDirection(LineDirectionMode direction) const
+{
+    return direction == HorizontalLine ? marginTop() : marginRight();
+}
+
 int RenderBlock::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
 {
     // Inline blocks are replaced elements. Otherwise, just pass off to
     // the base class.  If we're being queried as though we're the root line
     // box, then the fact that we're an inline-block is irrelevant, and we behave
     // just like a block.
-    if (isReplaced() && linePositionMode == PositionOnContainingLine) {
+    if (isInline() && linePositionMode == PositionOnContainingLine) {
         // For "leaf" theme objects, let the theme decide what the baseline position is.
         // FIXME: Might be better to have a custom CSS property instead, so that if the theme
         // is turned off, checkboxes/radios will still have decent baselines.
@@ -4558,7 +4349,7 @@
                 baselinePos = -1;
         }
         if (baselinePos != -1)
-            return direction == HorizontalLine ? marginTop() + baselinePos : marginRight() + baselinePos;
+            return beforeMarginInLineDirection(direction) + baselinePos;
 
         return RenderBox::baselinePosition(baselineType, firstLine, direction, linePositionMode);
     }
@@ -4608,7 +4399,7 @@
 
 int RenderBlock::inlineBlockBaseline(LineDirectionMode direction) const
 {
-    if (style()->overflowY() != OVISIBLE) {
+    if (!style()->isOverflowVisible()) {
         // We are not calling RenderBox::baselinePosition here because the caller should add the margin-top/margin-right, not us.
         return direction == HorizontalLine ? height() + m_marginBox.bottom() : width() + m_marginBox.left();
     }
@@ -4785,15 +4576,10 @@
 static inline unsigned firstLetterLength(const String& text)
 {
     unsigned length = 0;
-    bool punctuationOpen = false;
 
     // Account for leading spaces and punctuation.
-    while (length < text.length() && shouldSkipForFirstLetter((text)[length])) {
-        if (isPunctuationForFirstLetter((text)[length]))
-            punctuationOpen = true;
-
+    while (length < text.length() && shouldSkipForFirstLetter((text)[length]))
         length++;
-    }
 
     // Bail if we didn't find a letter
     if (text.length() && length == text.length())
@@ -4802,9 +4588,6 @@
     // Account for first letter.
     length++;
 
-    if (!punctuationOpen)
-        return length;
-
     // Keep looking for whitespace and allowed punctuation, but avoid
     // accumulating just whitespace into the :first-letter.
     for (unsigned scanLength = length; scanLength < text.length(); ++scanLength) {
@@ -5064,7 +4847,7 @@
     LayoutUnit leftEdge = borderLeft() + paddingLeft();
     LayoutUnit rightEdge = leftEdge + oldWidth;
     left = min(rightEdge, max(leftEdge, left));
-    right = max(leftEdge, min(rightEdge, right));
+    right = max(left, min(rightEdge, right));
 
     LayoutUnit newContentWidth = right - left;
     if (newContentWidth == oldWidth)
@@ -5329,25 +5112,6 @@
     return createAnonymousWithParentRendererAndDisplay(parent, style()->display());
 }
 
-bool RenderBlock::hasNextPage(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
-{
-    ASSERT(view()->layoutState() && view()->layoutState()->isPaginated());
-
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (!flowThread)
-        return true; // Printing and multi-column both make new pages to accommodate content.
-
-    // See if we're in the last region.
-    LayoutUnit pageOffset = offsetFromLogicalTopOfFirstPage() + logicalOffset;
-    RenderRegion* region = flowThread->regionAtBlockOffset(pageOffset, this);
-    if (!region)
-        return false;
-    if (region->isLastRegion())
-        return region->isRenderRegionSet() || region->style()->regionFragment() == BreakRegionFragment
-            || (pageBoundaryRule == IncludePageBoundary && pageOffset == region->logicalTopForFlowThreadContent());
-    return true;
-}
-
 LayoutUnit RenderBlock::nextPageLogicalTop(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
 {
     LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
@@ -5361,11 +5125,6 @@
     return logicalOffset + remainingLogicalHeight;
 }
 
-ColumnInfo::PaginationUnit RenderBlock::paginationUnit() const
-{
-    return ColumnInfo::Column;
-}
-
 LayoutUnit RenderBlock::pageLogicalTopForOffset(LayoutUnit offset) const
 {
     RenderView* renderView = view();
@@ -5416,42 +5175,25 @@
 {
     bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
     bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight;
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
     bool isUnsplittable = child->isUnsplittableForPagination() || (checkColumnBreaks && child->style()->columnBreakInside() == PBAVOID)
-        || (checkPageBreaks && child->style()->pageBreakInside() == PBAVOID)
-        || (checkRegionBreaks && child->style()->regionBreakInside() == PBAVOID);
+        || (checkPageBreaks && child->style()->pageBreakInside() == PBAVOID);
     if (!isUnsplittable)
         return logicalOffset;
     LayoutUnit childLogicalHeight = logicalHeightForChild(child) + (includeMargins ? marginBeforeForChild(child) + marginAfterForChild(child) : LayoutUnit());
     LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
-    bool hasUniformPageLogicalHeight = !flowThread || flowThread->regionsHaveUniformLogicalHeight();
     updateMinimumPageHeight(logicalOffset, childLogicalHeight);
-    if (!pageLogicalHeight || (hasUniformPageLogicalHeight && childLogicalHeight > pageLogicalHeight)
-        || !hasNextPage(logicalOffset))
+    if (!pageLogicalHeight || childLogicalHeight > pageLogicalHeight)
         return logicalOffset;
     LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
-    if (remainingLogicalHeight < childLogicalHeight) {
-        if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, childLogicalHeight))
-            return logicalOffset;
+    if (remainingLogicalHeight < childLogicalHeight)
         return logicalOffset + remainingLogicalHeight;
-    }
     return logicalOffset;
 }
 
 bool RenderBlock::pushToNextPageWithMinimumLogicalHeight(LayoutUnit& adjustment, LayoutUnit logicalOffset, LayoutUnit minimumLogicalHeight) const
 {
-    bool checkRegion = false;
-    for (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment); pageLogicalHeight;
-        pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment)) {
-        if (minimumLogicalHeight <= pageLogicalHeight)
-            return true;
-        if (!hasNextPage(logicalOffset + adjustment))
-            return false;
-        adjustment += pageLogicalHeight;
-        checkRegion = true;
-    }
-    return !checkRegion;
+    // FIXME: multicol will need to do some work here, when we implement support for multiple rows.
+    return false;
 }
 
 void RenderBlock::setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage)
@@ -5519,8 +5261,7 @@
     bool hasUniformPageLogicalHeight = !flowThread || flowThread->regionsHaveUniformLogicalHeight();
     // If lineHeight is greater than pageLogicalHeight, but logicalVisualOverflow.height() still fits, we are
     // still going to add a strut, so that the visible overflow fits on a single page.
-    if (!pageLogicalHeight || (hasUniformPageLogicalHeight && logicalVisualOverflow.height() > pageLogicalHeight)
-        || !hasNextPage(logicalOffset))
+    if (!pageLogicalHeight || (hasUniformPageLogicalHeight && logicalVisualOverflow.height() > pageLogicalHeight))
         // FIXME: In case the line aligns with the top of the page (or it's slightly shifted downwards) it will not be marked as the first line in the page.
         // From here, the fix is not straightforward because it's not easy to always determine when the current line is the first in the page.
         return;
@@ -5559,34 +5300,6 @@
     }
 }
 
-void RenderBlock::updateRegionForLine(RootInlineBox* lineBox) const
-{
-    ASSERT(lineBox);
-    lineBox->setContainingRegion(regionAtBlockOffset(lineBox->lineTopWithLeading()));
-
-    RootInlineBox* prevLineBox = lineBox->prevRootBox();
-    if (!prevLineBox)
-        return;
-
-    // This check is more accurate than the one in |adjustLinePositionForPagination| because it takes into
-    // account just the container changes between lines. The before mentioned function doesn't set the flag
-    // correctly if the line is positioned at the top of the last fragment container.
-    if (lineBox->containingRegion() != prevLineBox->containingRegion())
-        lineBox->setIsFirstAfterPageBreak(true);
-}
-
-bool RenderBlock::lineWidthForPaginatedLineChanged(RootInlineBox* rootBox, LayoutUnit lineDelta, RenderFlowThread* flowThread) const
-{
-    if (!flowThread)
-        return false;
-
-    RenderRegion* currentRegion = regionAtBlockOffset(rootBox->lineTopWithLeading() + lineDelta);
-    // Just bail if the region didn't change.
-    if (rootBox->containingRegion() == currentRegion)
-        return false;
-    return rootBox->paginatedLineWidth() != availableLogicalWidthForContent(currentRegion);
-}
-
 LayoutUnit RenderBlock::offsetFromLogicalTopOfFirstPage() const
 {
     LayoutState* layoutState = view()->layoutState();
@@ -5617,38 +5330,6 @@
     return flowThread->regionAtBlockOffset(offsetFromLogicalTopOfFirstPage() + blockOffset, true);
 }
 
-bool RenderBlock::logicalWidthChangedInRegions(RenderFlowThread* flowThread) const
-{
-    if (!flowThread || !flowThread->hasValidRegionInfo())
-        return false;
-
-    return flowThread->logicalWidthChangedInRegionsForBlock(this);
-}
-
-RenderRegion* RenderBlock::clampToStartAndEndRegions(RenderRegion* region) const
-{
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-
-    ASSERT(isRenderView() || (region && flowThread));
-    if (isRenderView())
-        return region;
-
-    // We need to clamp to the block, since we want any lines or blocks that overflow out of the
-    // logical top or logical bottom of the block to size as though the border box in the first and
-    // last regions extended infinitely. Otherwise the lines are going to size according to the regions
-    // they overflow into, which makes no sense when this block doesn't exist in |region| at all.
-    RenderRegion* startRegion;
-    RenderRegion* endRegion;
-    flowThread->getRegionRangeForBox(this, startRegion, endRegion);
-
-    if (startRegion && region->logicalTopForFlowThreadContent() < startRegion->logicalTopForFlowThreadContent())
-        return startRegion;
-    if (endRegion && region->logicalTopForFlowThreadContent() > endRegion->logicalTopForFlowThreadContent())
-        return endRegion;
-
-    return region;
-}
-
 LayoutUnit RenderBlock::collapsedMarginBeforeForChild(const RenderBox* child) const
 {
     // If the child has the same directionality as we do, then we can just return its
diff --git a/Source/core/rendering/RenderBlock.h b/Source/core/rendering/RenderBlock.h
index 2706f41..16e2057 100644
--- a/Source/core/rendering/RenderBlock.h
+++ b/Source/core/rendering/RenderBlock.h
@@ -40,24 +40,19 @@
 
 class BasicShape;
 class BidiContext;
-class InlineIterator;
 class LayoutStateMaintainer;
 class LineLayoutState;
 class RenderInline;
+class RenderRegion;
 class RenderText;
 
 struct BidiRun;
 struct PaintInfo;
 class LineInfo;
 class RenderRubyRun;
-class TextLayout;
 class WordMeasurement;
 
-template <class Iterator, class Run> class BidiResolver;
 template <class Run> class BidiRunList;
-template <class Iterator> struct MidpointState;
-typedef BidiResolver<InlineIterator, BidiRun> InlineBidiResolver;
-typedef MidpointState<InlineIterator> LineMidpointState;
 typedef WTF::ListHashSet<RenderBox*, 16> TrackedRendererListHashSet;
 typedef WTF::HashMap<const RenderBlock*, OwnPtr<TrackedRendererListHashSet> > TrackedDescendantsMap;
 typedef WTF::HashMap<const RenderBox*, OwnPtr<HashSet<RenderBlock*> > > TrackedContainerMap;
@@ -93,12 +88,11 @@
 
     // These two functions are overridden for inline-block.
     virtual LayoutUnit lineHeight(bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE FINAL;
-    virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
+    virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
 
     LayoutUnit minLineHeightForReplacedRenderer(bool isFirstLine, LayoutUnit replacedHeight) const;
 
     RenderLineBoxList* lineBoxes() { return &m_lineBoxes; }
-    const RenderLineBoxList* lineBoxes() const { return &m_lineBoxes; }
 
     InlineFlowBox* firstLineBox() const { return m_lineBoxes.firstLineBox(); }
     InlineFlowBox* lastLineBox() const { return m_lineBoxes.lastLineBox(); }
@@ -106,10 +100,10 @@
     // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
     virtual void deleteLineBoxTree();
 
-    virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0);
-    virtual void removeChild(RenderObject*);
+    virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0) OVERRIDE;
+    virtual void removeChild(RenderObject*) OVERRIDE;
 
-    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0);
+    virtual void layoutBlock(bool relayoutChildren);
 
     void insertPositionedObject(RenderBox*);
     static void removePositionedObject(RenderBox*);
@@ -142,8 +136,6 @@
     bool hasMarginBeforeQuirk(const RenderBox* child) const;
     bool hasMarginAfterQuirk(const RenderBox* child) const;
 
-    RootInlineBox* createAndAppendRootInlineBox();
-
     void markShapeInsideDescendantsForLayout();
     void markPositionedObjectsForLayout();
     // FIXME: Do we really need this to be virtual? It's just so we can call this on
@@ -153,67 +145,6 @@
     // FIXME-BLOCKFLOW: Remove virtualizaion when all of the line layout code has been moved out of RenderBlock
     virtual bool containsFloats() const { return false; }
 
-    // Versions that can compute line offsets with the region and page offset passed in. Used for speed to avoid having to
-    // compute the region all over again when you already know it.
-    LayoutUnit availableLogicalWidthForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
-    {
-        return max<LayoutUnit>(0, logicalRightOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight)
-            - logicalLeftOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight));
-    }
-    LayoutUnit logicalRightOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
-    {
-        return logicalRightOffsetForLine(position, logicalRightOffsetForContent(region), shouldIndentText, logicalHeight);
-    }
-    LayoutUnit logicalLeftOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
-    {
-        return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(region), shouldIndentText, logicalHeight);
-    }
-    LayoutUnit startOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
-    {
-        return style()->isLeftToRightDirection() ? logicalLeftOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight)
-            : logicalWidth() - logicalRightOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight);
-    }
-    LayoutUnit endOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
-    {
-        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight)
-            : logicalWidth() - logicalRightOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight);
-    }
-
-    LayoutUnit availableLogicalWidthForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
-    {
-        return availableLogicalWidthForLineInRegion(position, shouldIndentText, regionAtBlockOffset(position), logicalHeight);
-    }
-    LayoutUnit logicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
-    {
-        return logicalRightOffsetForLine(position, logicalRightOffsetForContent(position), shouldIndentText, logicalHeight);
-    }
-    LayoutUnit logicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
-    {
-        return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(position), shouldIndentText, logicalHeight);
-    }
-    LayoutUnit pixelSnappedLogicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
-    {
-        return roundToInt(logicalLeftOffsetForLine(position, shouldIndentText, logicalHeight));
-    }
-    LayoutUnit pixelSnappedLogicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
-    {
-        // FIXME: Multicolumn layouts break carrying over subpixel values to the logical right offset because the lines may be shifted
-        // by a subpixel value for all but the first column. This can lead to the actual pixel snapped width of the column being off
-        // by one pixel when rendered versus layed out, which can result in the line being clipped. For now, we have to floor.
-        // https://bugs.webkit.org/show_bug.cgi?id=105461
-        return floorToInt(logicalRightOffsetForLine(position, shouldIndentText, logicalHeight));
-    }
-    LayoutUnit startOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
-    {
-        return style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, logicalHeight)
-            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, logicalHeight);
-    }
-    LayoutUnit endOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
-    {
-        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, logicalHeight)
-            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, logicalHeight);
-    }
-
     LayoutUnit textIndentOffset() const;
 
     virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE;
@@ -273,8 +204,6 @@
     ColumnInfo* columnInfo() const;
     int columnGap() const;
 
-    void updateColumnInfoFromStyle(RenderStyle*);
-
     // These two functions take the ColumnInfo* to avoid repeated lookups of the info in the global HashMap.
     unsigned columnCount(ColumnInfo*) const;
     LayoutRect columnRectAt(ColumnInfo*, unsigned) const;
@@ -317,46 +246,12 @@
 
     virtual void scrollbarsChanged(bool /*horizontalScrollbarChanged*/, bool /*verticalScrollbarChanged*/) { };
 
-    LayoutUnit logicalLeftOffsetForContent(RenderRegion*) const;
-    LayoutUnit logicalRightOffsetForContent(RenderRegion*) const;
-    LayoutUnit availableLogicalWidthForContent(RenderRegion* region) const
-    {
-        return max<LayoutUnit>(0, logicalRightOffsetForContent(region) - logicalLeftOffsetForContent(region)); }
-    LayoutUnit startOffsetForContent(RenderRegion* region) const
-    {
-        return style()->isLeftToRightDirection() ? logicalLeftOffsetForContent(region) : logicalWidth() - logicalRightOffsetForContent(region);
-    }
-    LayoutUnit endOffsetForContent(RenderRegion* region) const
-    {
-        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForContent(region) : logicalWidth() - logicalRightOffsetForContent(region);
-    }
-    LayoutUnit logicalLeftOffsetForContent(LayoutUnit blockOffset) const
-    {
-        return logicalLeftOffsetForContent(regionAtBlockOffset(blockOffset));
-    }
-    LayoutUnit logicalRightOffsetForContent(LayoutUnit blockOffset) const
-    {
-        return logicalRightOffsetForContent(regionAtBlockOffset(blockOffset));
-    }
-    LayoutUnit availableLogicalWidthForContent(LayoutUnit blockOffset) const
-    {
-        return availableLogicalWidthForContent(regionAtBlockOffset(blockOffset));
-    }
-    LayoutUnit startOffsetForContent(LayoutUnit blockOffset) const
-    {
-        return startOffsetForContent(regionAtBlockOffset(blockOffset));
-    }
-    LayoutUnit endOffsetForContent(LayoutUnit blockOffset) const
-    {
-        return endOffsetForContent(regionAtBlockOffset(blockOffset));
-    }
+    LayoutUnit availableLogicalWidthForContent() const { return max<LayoutUnit>(0, logicalRightOffsetForContent() - logicalLeftOffsetForContent()); }
     LayoutUnit logicalLeftOffsetForContent() const { return isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop(); }
     LayoutUnit logicalRightOffsetForContent() const { return logicalLeftOffsetForContent() + availableLogicalWidth(); }
     LayoutUnit startOffsetForContent() const { return style()->isLeftToRightDirection() ? logicalLeftOffsetForContent() : logicalWidth() - logicalRightOffsetForContent(); }
     LayoutUnit endOffsetForContent() const { return !style()->isLeftToRightDirection() ? logicalLeftOffsetForContent() : logicalWidth() - logicalRightOffsetForContent(); }
 
-    LayoutUnit computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* = 0);
-
 #ifndef NDEBUG
     void checkPositionedObjectsNeedLayout();
     void showLineTreeAndMark(const InlineBox* = 0, const char* = 0, const InlineBox* = 0, const char* = 0, const RenderObject* = 0) const;
@@ -379,7 +274,7 @@
         m_rareData->m_shapeInsideInfo = value;
     }
     ShapeInsideInfo* layoutShapeInsideInfo() const;
-    bool allowsShapeInsideInfoSharing() const { return !isInline() && !isFloating(); }
+    bool allowsShapeInsideInfoSharing(const RenderBlock* other) const;
     LayoutSize logicalOffsetFromShapeAncestorContainer(const RenderBlock* container) const;
     virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
@@ -388,37 +283,28 @@
     // It is expected that the caller will call this function independent of the value of paintInfo.phase.
     static void paintAsInlineBlock(RenderObject*, PaintInfo&, const LayoutPoint&);
 protected:
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
     void dirtyForLayoutFromPercentageHeightDescendants(SubtreeLayoutScope&);
 
-    virtual void layout();
-    virtual void didLayout(ResourceLoadPriorityOptimizer&);
-    virtual void didScroll(ResourceLoadPriorityOptimizer&);
-    void updateStyleImageLoadingPriorities(ResourceLoadPriorityOptimizer&);
+    virtual void layout() OVERRIDE;
+    virtual bool updateImageLoadingPriorities() OVERRIDE FINAL;
 
     void layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly = false);
     void markFixedPositionObjectForLayoutIfNeeded(RenderObject* child, SubtreeLayoutScope&);
 
     LayoutUnit marginIntrinsicLogicalWidthForChild(RenderBox* child) const;
 
+    int beforeMarginInLineDirection(LineDirectionMode) const;
+
     virtual bool supportsPartialLayout() const OVERRIDE { return true; };
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
-    virtual void paintObject(PaintInfo&, const LayoutPoint&);
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual void paintObject(PaintInfo&, const LayoutPoint&) OVERRIDE;
     virtual void paintChildren(PaintInfo&, const LayoutPoint&);
     void paintChild(RenderBox*, PaintInfo&, const LayoutPoint&);
     void paintChildAsInlineBlock(RenderBox*, PaintInfo&, const LayoutPoint&);
 
-    LayoutUnit logicalRightOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit logicalHeight = 0) const
-    {
-        return adjustLogicalRightOffsetForLine(logicalRightFloatOffsetForLine(logicalTop, fixedOffset, logicalHeight), applyTextIndent);
-    }
-    LayoutUnit logicalLeftOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit logicalHeight = 0) const
-    {
-        return adjustLogicalLeftOffsetForLine(logicalLeftFloatOffsetForLine(logicalTop, fixedOffset, logicalHeight), applyTextIndent);
-    }
-
     virtual void adjustInlineDirectionLineBounds(int /* expansionOpportunityCount */, float& /* logicalLeft */, float& /* logicalWidth */) const { }
 
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
@@ -427,11 +313,11 @@
     virtual void computePreferredLogicalWidths() OVERRIDE;
     void adjustIntrinsicLogicalWidthsForColumns(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const;
 
-    virtual int firstLineBoxBaseline() const;
+    virtual int firstLineBoxBaseline() const OVERRIDE;
     virtual int inlineBlockBaseline(LineDirectionMode) const OVERRIDE;
     int lastLineBoxBaseline(LineDirectionMode) const;
 
-    virtual void updateHitTestResult(HitTestResult&, const LayoutPoint&);
+    virtual void updateHitTestResult(HitTestResult&, const LayoutPoint&) OVERRIDE;
 
     // Delay update scrollbar until finishDelayRepaint() will be
     // called. This function is used when a flexbox is laying out its
@@ -443,8 +329,8 @@
 
     void updateScrollInfoAfterLayout();
 
-    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle);
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     virtual bool hasLineIfEmpty() const;
 
@@ -470,18 +356,9 @@
 
     void updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox*);
 
-    virtual void checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight);
-
     virtual bool isInlineBlockOrInlineTable() const OVERRIDE FINAL { return isInline() && isReplaced(); }
 
 private:
-    // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
-    virtual LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit) const { return fixedOffset; }
-    // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
-    virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit) const { return fixedOffset; }
-    LayoutUnit adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
-    LayoutUnit adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
-
     void computeShapeSize();
     void updateRegionsAndShapesAfterChildLayout(RenderFlowThread*, bool);
     void updateShapeInsideInfoAfterStyleChange(const ShapeValue*, const ShapeValue* oldShape);
@@ -490,7 +367,7 @@
     virtual RenderObjectChildList* virtualChildren() OVERRIDE FINAL { return children(); }
     virtual const RenderObjectChildList* virtualChildren() const OVERRIDE FINAL { return children(); }
 
-    virtual const char* renderName() const;
+    virtual const char* renderName() const OVERRIDE;
 
     virtual bool isRenderBlock() const OVERRIDE FINAL { return true; }
 
@@ -498,24 +375,20 @@
     virtual void removeLeftoverAnonymousBlock(RenderBlock* child);
 
     static void collapseAnonymousBlockChild(RenderBlock* parent, RenderBlock* child);
-    // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
-    virtual void moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert) { moveAllChildrenTo(toBlock, fullRemoveInsert); }
 
     virtual void dirtyLinesFromChangedChild(RenderObject* child) OVERRIDE FINAL { m_lineBoxes.dirtyLinesFromChangedChild(this, child); }
 
     void addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild);
-    void addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild);
+    virtual void addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild) OVERRIDE;
     void addChildToAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild);
 
     void addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild = 0);
 
-    virtual bool isSelfCollapsingBlock() const OVERRIDE FINAL;
+    virtual bool isSelfCollapsingBlock() const OVERRIDE;
 
     void insertIntoTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*&, TrackedContainerMap*&);
     static void removeFromTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*&, TrackedContainerMap*&);
 
-    virtual RootInlineBox* createRootInlineBox() { return 0; } // Subclassed by RenderBlockFlow, SVG and Ruby.
-
     // Called to lay out the legend for a fieldset or the ruby text of a ruby run.
     virtual RenderObject* layoutSpecialExcludedChild(bool /*relayoutChildren*/, SubtreeLayoutScope&) { return 0; }
 
@@ -535,7 +408,7 @@
     bool hasCaret() const { return hasCaret(CursorCaret) || hasCaret(DragCaret); }
     bool hasCaret(CaretType) const;
 
-    virtual bool avoidsFloats() const;
+    virtual bool avoidsFloats() const OVERRIDE;
 
     bool hitTestColumns(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction);
     bool hitTestContents(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction);
@@ -550,7 +423,7 @@
 
     // Obtains the nearest enclosing block (including this block) that contributes a first-line style to our inline
     // children.
-    virtual RenderBlock* firstLineBlock() const;
+    virtual RenderBlock* firstLineBlock() const OVERRIDE;
 
     virtual LayoutRect rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const OVERRIDE FINAL;
     virtual RenderStyle* outlineStyleForRepaint() const OVERRIDE FINAL;
@@ -571,17 +444,16 @@
                                 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo*);
     LayoutRect blockSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
                                  LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo*);
-    LayoutUnit logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position);
-    LayoutUnit logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position);
+    virtual LayoutUnit logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position);
+    virtual LayoutUnit logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position);
 
     // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
     virtual void clipOutFloatingObjects(RenderBlock*, const PaintInfo*, const LayoutPoint&, const LayoutSize&) { };
 
-    virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const;
-    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
+    virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE;
+    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const OVERRIDE;
 
     LayoutUnit desiredColumnWidth() const;
-    unsigned desiredColumnCount() const;
 
     void paintContinuationOutlines(PaintInfo&, const LayoutPoint&);
 
@@ -597,11 +469,9 @@
     Position positionForBox(InlineBox*, bool start = true) const;
     PositionWithAffinity positionForPointWithInlineChildren(const LayoutPoint&);
 
-    virtual void calcColumnWidth();
+    void calcColumnWidth();
     void makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlockFlow* newBlockBox, RenderObject* newChild);
 
-    bool expandsToEncloseOverhangingFloats() const;
-
     void splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock, RenderBlock* middleBlock,
                      RenderObject* beforeChild, RenderBoxModelObject* oldCont);
     void splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
@@ -616,9 +486,6 @@
 protected:
     void determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode = DoNotApplyLayoutDelta);
 
-    // Pagination routines.
-    bool relayoutToAvoidWidows(LayoutStateMaintainer&);
-
     // Returns the logicalOffset at the top of the next page. If the offset passed in is already at the top of the current page,
     // then nextPageLogicalTop with ExcludePageBoundary will still move to the top of the next page. nextPageLogicalTop with
     // IncludePageBoundary set will not.
@@ -626,9 +493,8 @@
     // For a page height of 800px, the first rule will return 800 if the value passed in is 0. The second rule will simply return 0.
     enum PageBoundaryRule { ExcludePageBoundary, IncludePageBoundary };
     LayoutUnit nextPageLogicalTop(LayoutUnit logicalOffset, PageBoundaryRule = ExcludePageBoundary) const;
-    bool hasNextPage(LayoutUnit logicalOffset, PageBoundaryRule = ExcludePageBoundary) const;
 
-    virtual ColumnInfo::PaginationUnit paginationUnit() const;
+    bool createsBlockFormattingContext() const;
 
 public:
     LayoutUnit pageLogicalTopForOffset(LayoutUnit offset) const;
@@ -648,19 +514,11 @@
 
     LayoutUnit adjustForUnsplittableChild(RenderBox* child, LayoutUnit logicalOffset, bool includeMargins = false); // If the child is unsplittable and can't fit on the current page, return the top of the next page/column.
     void adjustLinePositionForPagination(RootInlineBox*, LayoutUnit& deltaOffset, RenderFlowThread*); // Computes a deltaOffset value that put a line at the top of the next page if it doesn't fit on the current page.
-    void updateRegionForLine(RootInlineBox*) const;
 
     // Adjust from painting offsets to the local coords of this renderer
     void offsetForContents(LayoutPoint&) const;
 
-    // This function is called to test a line box that has moved in the block direction to see if it has ended up in a new
-    // region/page/column that has a different available line width than the old one. Used to know when you have to dirty a
-    // line, i.e., that it can't be re-used.
-    bool lineWidthForPaginatedLineChanged(RootInlineBox*, LayoutUnit lineDelta, RenderFlowThread*) const;
-
-    bool logicalWidthChangedInRegions(RenderFlowThread*) const;
-
-    virtual bool requiresColumns(int desiredColumnCount) const;
+    bool requiresColumns(int desiredColumnCount) const;
 
     virtual bool updateLogicalWidthAndColumnWidth();
 
@@ -669,7 +527,6 @@
 public:
     virtual LayoutUnit offsetFromLogicalTopOfFirstPage() const OVERRIDE FINAL;
     RenderRegion* regionAtBlockOffset(LayoutUnit) const;
-    RenderRegion* clampToStartAndEndRegions(RenderRegion*) const;
 
 public:
 
@@ -688,9 +545,9 @@
         LayoutUnit m_paginationStrut;
         LayoutUnit m_pageLogicalOffset;
 
-        int m_lineBreakToAvoidWidow;
         OwnPtr<ShapeInsideInfo> m_shapeInsideInfo;
-        bool m_didBreakAtLineToAvoidWidow : 1;
+        int m_lineBreakToAvoidWidow : 31;
+        unsigned m_didBreakAtLineToAvoidWidow : 1;
      };
 
 protected:
@@ -699,12 +556,13 @@
     RenderObjectChildList m_children;
     RenderLineBoxList m_lineBoxes;   // All of the root line boxes created for this block flow.  For example, <div>Hello<br>world.</div> will have two total lines for the <div>.
 
-    mutable signed m_lineHeight : 27;
+    mutable signed m_lineHeight : 26;
     unsigned m_hasMarginBeforeQuirk : 1; // Note these quirk values can't be put in RenderBlockRareData since they are set too frequently.
     unsigned m_hasMarginAfterQuirk : 1;
     unsigned m_beingDestroyed : 1;
     unsigned m_hasMarkupTruncation : 1;
     unsigned m_hasBorderOrPaddingLogicalWidthChanged : 1;
+    mutable unsigned m_hasOnlySelfCollapsingChildren : 1;
 
     // RenderRubyBase objects need to be able to split and merge, moving their children around
     // (calling moveChildTo, moveAllChildrenTo, and makeChildrenNonInline).
@@ -717,6 +575,20 @@
     friend class RenderBlockFlow;
 };
 
+
+inline bool RenderBlock::allowsShapeInsideInfoSharing(const RenderBlock* other) const
+{
+    if (!other)
+        return false;
+    for (const RenderBlock* current = this; current && current != other && !current->isRenderFlowThread(); current = current->containingBlock()) {
+        if (current->isInline() || current->isFloating())
+            return false;
+        if (current->parent() != current->containingBlock())
+            return false;
+    }
+    return true;
+}
+
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderBlock, isRenderBlock());
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderBlockFlow.cpp b/Source/core/rendering/RenderBlockFlow.cpp
index b53e835..a7ff4f4 100644
--- a/Source/core/rendering/RenderBlockFlow.cpp
+++ b/Source/core/rendering/RenderBlockFlow.cpp
@@ -31,17 +31,20 @@
 #include "config.h"
 #include "core/rendering/RenderBlockFlow.h"
 
+#include "core/accessibility/AXObjectCache.h"
 #include "core/frame/FrameView.h"
+#include "core/rendering/FastTextAutosizer.h"
 #include "core/rendering/HitTestLocation.h"
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
-#include "core/rendering/LineWidth.h"
+#include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderNamedFlowFragment.h"
-#include "core/rendering/RenderNamedFlowThread.h"
+#include "core/rendering/RenderMultiColumnBlock.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/line/LineWidth.h"
 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
+#include "platform/text/BidiTextRun.h"
 
 using namespace std;
 
@@ -61,6 +64,7 @@
     bool m_canCollapseWithChildren : 1;
     bool m_canCollapseMarginBeforeWithChildren : 1;
     bool m_canCollapseMarginAfterWithChildren : 1;
+    bool m_canCollapseMarginAfterWithLastChild: 1;
 
     // Whether or not we are a quirky container, i.e., do we collapse away top and bottom
     // margins in our container. Table cells and the body are the common examples. We
@@ -118,6 +122,7 @@
 
     void setMargin(LayoutUnit p, LayoutUnit n) { ASSERT(!m_discardMargin); m_positiveMargin = p; m_negativeMargin = n; }
     void setCanCollapseMarginAfterWithChildren(bool collapse) { m_canCollapseMarginAfterWithChildren = collapse; }
+    void setCanCollapseMarginAfterWithLastChild(bool collapse) { m_canCollapseMarginAfterWithLastChild = collapse; }
     void setDiscardMargin(bool value) { m_discardMargin = value; }
 
     bool atBeforeSideOfBlock() const { return m_atBeforeSideOfBlock; }
@@ -125,6 +130,7 @@
     bool canCollapseWithMarginAfter() const { return m_atAfterSideOfBlock && m_canCollapseMarginAfterWithChildren; }
     bool canCollapseMarginBeforeWithChildren() const { return m_canCollapseMarginBeforeWithChildren; }
     bool canCollapseMarginAfterWithChildren() const { return m_canCollapseMarginAfterWithChildren; }
+    bool canCollapseMarginAfterWithLastChild() const { return m_canCollapseMarginAfterWithLastChild; }
     bool quirkContainer() const { return m_quirkContainer; }
     bool determinedMarginBeforeQuirk() const { return m_determinedMarginBeforeQuirk; }
     bool hasMarginBeforeQuirk() const { return m_hasMarginBeforeQuirk; }
@@ -134,7 +140,6 @@
     bool discardMargin() const { return m_discardMargin; }
     LayoutUnit margin() const { return m_positiveMargin - m_negativeMargin; }
 };
-
 static bool inNormalFlow(RenderBox* child)
 {
     RenderBlock* curr = child->containingBlock();
@@ -171,80 +176,110 @@
     return toRenderBlockFlow(createAnonymousWithParentRendererAndDisplay(this, BLOCK));
 }
 
-void RenderBlockFlow::willBeDestroyed()
+void RenderBlockFlow::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
 {
-    if (lineGridBox())
-        lineGridBox()->destroy();
+    ColumnInfo* colInfo = columnInfo();
+    if (hasColumns()) {
+        if (!pageLogicalHeight) {
+            LayoutUnit oldLogicalHeight = logicalHeight();
+            setLogicalHeight(0);
+            // We need to go ahead and set our explicit page height if one exists, so that we can
+            // avoid doing two layout passes.
+            updateLogicalHeight();
+            LayoutUnit columnHeight = contentLogicalHeight();
+            if (columnHeight > 0) {
+                pageLogicalHeight = columnHeight;
+                hasSpecifiedPageLogicalHeight = true;
+            }
+            setLogicalHeight(oldLogicalHeight);
+        }
+        if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
+            colInfo->setColumnHeight(pageLogicalHeight);
+            pageLogicalHeightChanged = true;
+        }
 
-    if (renderNamedFlowFragment())
-        setRenderNamedFlowFragment(0);
-
-    RenderBlock::willBeDestroyed();
+        if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
+            colInfo->clearForcedBreaks();
+    } else if (isRenderFlowThread()) {
+        pageLogicalHeight = 1; // This is just a hack to always make sure we have a page logical height.
+        pageLogicalHeightChanged = toRenderFlowThread(this)->pageLogicalSizeChanged();
+    }
 }
 
-bool RenderBlockFlow::relayoutForPagination(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer& statePusher)
+bool RenderBlockFlow::shouldRelayoutForPagination(LayoutUnit& pageLogicalHeight, LayoutUnit layoutOverflowLogicalBottom) const
 {
-    if (!hasColumns())
-        return false;
-
-    OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
-    if (childrenInline())
-        addOverflowFromInlineChildren();
-    else
-        addOverflowFromBlockChildren();
-    LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderBefore() - paddingBefore();
-
     // FIXME: We don't balance properly at all in the presence of forced page breaks. We need to understand what
     // the distance between forced page breaks is so that we can avoid making the minimum column height too tall.
     ColumnInfo* colInfo = columnInfo();
-    if (!hasSpecifiedPageLogicalHeight) {
-        LayoutUnit columnHeight = pageLogicalHeight;
-        int minColumnCount = colInfo->forcedBreaks() + 1;
-        int desiredColumnCount = colInfo->desiredColumnCount();
-        if (minColumnCount >= desiredColumnCount) {
-            // The forced page breaks are in control of the balancing. Just set the column height to the
-            // maximum page break distance.
-            if (!pageLogicalHeight) {
-                LayoutUnit distanceBetweenBreaks = max<LayoutUnit>(colInfo->maximumDistanceBetweenForcedBreaks(),
-                    view()->layoutState()->pageLogicalOffset(this, borderBefore() + paddingBefore() + layoutOverflowLogicalBottom) - colInfo->forcedBreakOffset());
-                columnHeight = max(colInfo->minimumColumnHeight(), distanceBetweenBreaks);
-            }
-        } else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
-            // Now that we know the intrinsic height of the columns, we have to rebalance them.
-            columnHeight = max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf((float)layoutOverflowLogicalBottom / desiredColumnCount));
+    LayoutUnit columnHeight = pageLogicalHeight;
+    const int minColumnCount = colInfo->forcedBreaks() + 1;
+    const int desiredColumnCount = colInfo->desiredColumnCount();
+    if (minColumnCount >= desiredColumnCount) {
+        // The forced page breaks are in control of the balancing. Just set the column height to the
+        // maximum page break distance.
+        if (!pageLogicalHeight) {
+            LayoutUnit distanceBetweenBreaks = max<LayoutUnit>(colInfo->maximumDistanceBetweenForcedBreaks(),
+                view()->layoutState()->pageLogicalOffset(this, borderBefore() + paddingBefore() + layoutOverflowLogicalBottom) - colInfo->forcedBreakOffset());
+            columnHeight = max(colInfo->minimumColumnHeight(), distanceBetweenBreaks);
         }
-
-        if (columnHeight && columnHeight != pageLogicalHeight) {
-            statePusher.pop();
-            setEverHadLayout(true);
-            layoutBlock(false, columnHeight);
-            return true;
-        }
+    } else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
+        // Now that we know the intrinsic height of the columns, we have to rebalance them.
+        columnHeight = max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf((float)layoutOverflowLogicalBottom / desiredColumnCount));
     }
 
-    if (pageLogicalHeight)
-        colInfo->setColumnCountAndHeight(ceilf((float)layoutOverflowLogicalBottom / pageLogicalHeight), pageLogicalHeight);
-
-    if (columnCount(colInfo)) {
-        setLogicalHeight(borderBefore() + paddingBefore() + colInfo->columnHeight() + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
-        m_overflow.clear();
-    } else {
-        m_overflow = savedOverflow.release();
+    if (columnHeight && columnHeight != pageLogicalHeight) {
+        pageLogicalHeight = columnHeight;
+        return true;
     }
 
     return false;
 }
 
-void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
+void RenderBlockFlow::setColumnCountAndHeight(unsigned count, LayoutUnit pageLogicalHeight)
+{
+    ColumnInfo* colInfo = columnInfo();
+    if (pageLogicalHeight)
+        colInfo->setColumnCountAndHeight(count, pageLogicalHeight);
+
+    if (columnCount(colInfo)) {
+        setLogicalHeight(borderBefore() + paddingBefore() + colInfo->columnHeight() + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
+        m_overflow.clear();
+    }
+}
+
+bool RenderBlockFlow::isSelfCollapsingBlock() const
+{
+    m_hasOnlySelfCollapsingChildren = RenderBlock::isSelfCollapsingBlock();
+    return m_hasOnlySelfCollapsingChildren;
+}
+
+void RenderBlockFlow::layoutBlock(bool relayoutChildren)
 {
     ASSERT(needsLayout());
+    ASSERT(isInlineBlockOrInlineTable() || !isInline());
 
-    if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can cause us to come in here. Bail.
-        return;
+    // If we are self-collapsing with self-collapsing descendants this will get set to save us burrowing through our
+    // descendants every time in |isSelfCollapsingBlock|. We reset it here so that |isSelfCollapsingBlock| attempts to burrow
+    // at least once and so that it always gives a reliable result reflecting the latest layout.
+    m_hasOnlySelfCollapsingChildren = false;
 
     if (!relayoutChildren && simplifiedLayout())
         return;
 
+    SubtreeLayoutScope layoutScope(this);
+
+    // Multiple passes might be required for column and pagination based layout
+    // In the case of the old column code the number of passes will only be two
+    // however, in the newer column code the number of passes could equal the
+    // number of columns.
+    bool done = false;
+    LayoutUnit pageLogicalHeight = 0;
+    while (!done)
+        done = layoutBlockFlow(relayoutChildren, pageLogicalHeight, layoutScope);
+}
+
+inline bool RenderBlockFlow::layoutBlockFlow(bool relayoutChildren, LayoutUnit &pageLogicalHeight, SubtreeLayoutScope& layoutScope)
+{
     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
 
     if (updateLogicalWidthAndColumnWidth())
@@ -252,27 +287,17 @@
 
     rebuildFloatsFromIntruding();
 
-    LayoutUnit previousHeight = logicalHeight();
-    // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
-    // for consistency with other render classes?
-    setLogicalHeight(0);
-
     bool pageLogicalHeightChanged = false;
     bool hasSpecifiedPageLogicalHeight = false;
     checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
 
     RenderView* renderView = view();
-    RenderStyle* styleToUse = style();
-    LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
+    LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
 
     // Regions changing widths can force us to relayout our children.
     RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (logicalWidthChangedInRegions(flowThread))
-        relayoutChildren = true;
     if (updateRegionsAndShapesLogicalSize(flowThread))
         relayoutChildren = true;
-    if (!relayoutChildren && isRenderNamedFlowFragmentContainer())
-        relayoutChildren = true;
 
     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
     // our current maximal positive and negative margins. These values are used when we
@@ -284,48 +309,74 @@
     //
     // Start out by setting our margin values to our current margins. Table cells have
     // no margins, so we don't fill in the values for table cells.
-    bool isCell = isTableCell();
-    if (!isCell) {
+    if (!isTableCell()) {
         initMaxMarginValues();
-
-        setHasMarginBeforeQuirk(styleToUse->hasMarginBeforeQuirk());
-        setHasMarginAfterQuirk(styleToUse->hasMarginAfterQuirk());
+        setHasMarginBeforeQuirk(style()->hasMarginBeforeQuirk());
+        setHasMarginAfterQuirk(style()->hasMarginAfterQuirk());
         setPaginationStrut(0);
     }
 
-    SubtreeLayoutScope layoutScope(this);
+    LayoutUnit beforeEdge = borderBefore() + paddingBefore();
+    LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
+    LayoutUnit previousHeight = logicalHeight();
+    setLogicalHeight(beforeEdge);
 
     m_repaintLogicalTop = 0;
     m_repaintLogicalBottom = 0;
     LayoutUnit maxFloatLogicalBottom = 0;
     if (!firstChild() && !isAnonymousBlock())
         setChildrenInline(true);
+
+    FastTextAutosizer::LayoutScope fastTextAutosizerLayoutScope(document(), this);
+
     if (childrenInline())
-        layoutInlineChildren(relayoutChildren, m_repaintLogicalTop, m_repaintLogicalBottom);
+        layoutInlineChildren(relayoutChildren, m_repaintLogicalTop, m_repaintLogicalBottom, afterEdge);
     else
-        layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom, layoutScope);
+        layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom, layoutScope, beforeEdge, afterEdge);
 
     if (frameView()->partialLayout().isStopping()) {
         statePusher.pop();
-        return;
+        return true;
     }
 
     // Expand our intrinsic height to encompass floats.
-    LayoutUnit toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
-    if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
-        setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
+    if (lowestFloatLogicalBottom() > (logicalHeight() - afterEdge) && createsBlockFormattingContext())
+        setLogicalHeight(lowestFloatLogicalBottom() + afterEdge);
 
-    if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher) || relayoutToAvoidWidows(statePusher)) {
-        ASSERT(!shouldBreakAtLineToAvoidWidow());
-        return;
+    if (isRenderMultiColumnBlock()) {
+        if (toRenderMultiColumnBlock(this)->shouldRelayoutMultiColumnBlock()) {
+            setChildNeedsLayout(MarkOnlyThis);
+            statePusher.pop();
+            return false;
+        }
+    } else if (hasColumns()) {
+        OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
+        if (childrenInline())
+            addOverflowFromInlineChildren();
+        else
+            addOverflowFromBlockChildren();
+        LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderBefore() - paddingBefore();
+        m_overflow = savedOverflow.release();
+
+        if (!hasSpecifiedPageLogicalHeight && shouldRelayoutForPagination(pageLogicalHeight, layoutOverflowLogicalBottom)) {
+            statePusher.pop();
+            setEverHadLayout(true);
+            return false;
+        }
+
+        setColumnCountAndHeight(ceilf((float)layoutOverflowLogicalBottom / pageLogicalHeight), pageLogicalHeight);
+    }
+
+    if (shouldBreakAtLineToAvoidWidow()) {
+        statePusher.pop();
+        setEverHadLayout(true);
+        return false;
     }
 
     // Calculate our new height.
     LayoutUnit oldHeight = logicalHeight();
     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
 
-    // Before updating the final size of the flow thread make sure a forced break is applied after the content.
-    // This ensures the size information is correctly computed for the last auto-height region receiving content.
     if (isRenderFlowThread())
         toRenderFlowThread(this)->applyBreakAfterContent(oldClientAfterEdge);
 
@@ -360,7 +411,7 @@
     fitBorderToLinesIfNeeded();
 
     if (frameView()->partialLayout().isStopping())
-        return;
+        return true;
 
     if (renderView->layoutState()->m_pageLogicalHeight)
         setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
@@ -373,7 +424,7 @@
 
     // Repaint with our new bounds if they are different from our old bounds.
     bool didFullRepaint = repainter.repaintAfterLayout();
-    if (!didFullRepaint && m_repaintLogicalTop != m_repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
+    if (!didFullRepaint && m_repaintLogicalTop != m_repaintLogicalBottom && (style()->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
         if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
             setShouldRepaintOverflowIfNeeded(true);
         else
@@ -381,6 +432,7 @@
     }
 
     clearNeedsLayout();
+    return true;
 }
 
 void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
@@ -402,7 +454,7 @@
     LayoutUnit oldLogicalTop = logicalTopForChild(child);
 
 #if !ASSERT_DISABLED
-    LayoutSize oldLayoutDelta = view()->layoutDelta();
+    LayoutSize oldLayoutDelta = RuntimeEnabledFeatures::repaintAfterLayoutEnabled() ? LayoutSize() : view()->layoutDelta();
 #endif
     // Go ahead and position the child as though it didn't collapse with the top.
     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
@@ -447,13 +499,14 @@
 
     // Cache if we are at the top of the block right now.
     bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
+    bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
 
     // Now determine the correct ypos based off examination of collapsing margin
     // values.
-    LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
+    LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo, childIsSelfCollapsing);
 
     // Now check for clear.
-    LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
+    LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear, childIsSelfCollapsing);
 
     bool paginated = view()->layoutState()->isPaginated();
     if (paginated) {
@@ -487,9 +540,16 @@
         child->layoutIfNeeded();
     }
 
+    // If we previously encountered a self-collapsing sibling of this child that had clearance then
+    // we set this bit to ensure we would not collapse the child's margins, and those of any subsequent
+    // self-collapsing siblings, with our parent. If this child is not self-collapsing then it can
+    // collapse its margins with the parent so reset the bit.
+    if (!marginInfo.canCollapseMarginAfterWithLastChild() && !childIsSelfCollapsing)
+        marginInfo.setCanCollapseMarginAfterWithLastChild(true);
+
     // We are no longer at the top of the block if we encounter a non-empty child.
     // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
-    if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
+    if (marginInfo.atBeforeSideOfBlock() && !childIsSelfCollapsing)
         marginInfo.setAtBeforeSideOfBlock(false);
 
     // Now place the child in the correct left position
@@ -510,7 +570,8 @@
         maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(childRenderBlockFlow, !childNeededLayout));
 
     if (childOffset.width() || childOffset.height()) {
-        view()->addLayoutDelta(childOffset);
+        if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+            view()->addLayoutDelta(childOffset);
 
         // If the child moved, we have to repaint it as well as any floating/positioned
         // descendants. An exception is if we need a layout. In this case, we know we're going to
@@ -521,7 +582,7 @@
             child->repaintDuringLayoutIfMoved(oldRect);
     }
 
-    if (!childHadLayout && child->checkForRepaintDuringLayout()) {
+    if (!childHadLayout && child->checkForRepaint()) {
         if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
             child->repaint();
         child->repaintOverhangingFloats(true);
@@ -534,7 +595,9 @@
             setLogicalHeight(newHeight);
     }
 
-    ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+        ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
+    }
 }
 
 LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock)
@@ -761,19 +824,10 @@
     }
 }
 
-void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope& layoutScope)
+void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope& layoutScope, LayoutUnit beforeEdge, LayoutUnit afterEdge)
 {
     dirtyForLayoutFromPercentageHeightDescendants(layoutScope);
 
-    LayoutUnit beforeEdge = borderBefore() + paddingBefore();
-    LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
-
-    setLogicalHeight(beforeEdge);
-
-    // Lay out our hypothetical grid line as though it occurs at the top of the block.
-    if (view()->layoutState()->lineGrid() == this)
-        layoutLineGridBox();
-
     // The margin struct caches all our current margin collapsing state. The compact struct caches state when we encounter compacts,
     MarginInfo marginInfo(this, beforeEdge, afterEdge);
 
@@ -786,6 +840,7 @@
     maxFloatLogicalBottom = 0;
 
     RenderBox* next = firstChildBox();
+    RenderBox* lastNormalFlowChild = 0;
 
     while (next) {
         RenderBox* child = next;
@@ -811,20 +866,23 @@
 
         // Lay out the child.
         layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
+        lastNormalFlowChild = child;
 
         // If doing a partial layout and the child was the target renderer, early exit here.
         if (frameView()->partialLayout().checkPartialLayoutComplete(child))
-            break;
+            return;
+
     }
 
     // Now do the handling of the bottom of the block, adding in our bottom border/padding and
     // determining the correct collapsed bottom margin information.
-    handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
+    handleAfterSideOfBlock(lastNormalFlowChild, beforeEdge, afterEdge, marginInfo);
 }
 
 // Our MarginInfo state used when laying out block children.
 MarginInfo::MarginInfo(RenderBlockFlow* blockFlow, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
-    : m_atBeforeSideOfBlock(true)
+    : m_canCollapseMarginAfterWithLastChild(true)
+    , m_atBeforeSideOfBlock(true)
     , m_atAfterSideOfBlock(false)
     , m_hasMarginBeforeQuirk(false)
     , m_hasMarginAfterQuirk(false)
@@ -833,10 +891,7 @@
 {
     RenderStyle* blockStyle = blockFlow->style();
     ASSERT(blockFlow->isRenderView() || blockFlow->parent());
-    m_canCollapseWithChildren = !blockFlow->isRenderView() && !blockFlow->isRoot() && !blockFlow->isOutOfFlowPositioned()
-        && !blockFlow->isFloating() && !blockFlow->isTableCell() && !blockFlow->hasOverflowClip() && !blockFlow->isInlineBlockOrInlineTable()
-        && !blockFlow->isRenderFlowThread() && !blockFlow->isWritingModeRoot() && !blockFlow->parent()->isFlexibleBox()
-        && blockStyle->hasAutoColumnCount() && blockStyle->hasAutoColumnWidth() && !blockStyle->columnSpan();
+    m_canCollapseWithChildren = !blockFlow->createsBlockFormattingContext() && !blockFlow->isRenderFlowThread() && !blockFlow->isRenderView();
 
     m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
 
@@ -915,11 +970,10 @@
     return RenderBlockFlow::MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
 }
 
-LayoutUnit RenderBlockFlow::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
+LayoutUnit RenderBlockFlow::collapseMargins(RenderBox* child, MarginInfo& marginInfo, bool childIsSelfCollapsing)
 {
     bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
     bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
-    bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
 
     // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
     childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
@@ -987,11 +1041,12 @@
 
     LayoutUnit clearanceForSelfCollapsingBlock;
     RenderObject* prev = child->previousSibling();
+    RenderBlockFlow* previousBlockFlow =  prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned() ? toRenderBlockFlow(prev) : 0;
     // If the child's previous sibling is a self-collapsing block that cleared a float then its top border edge has been set at the bottom border edge
     // of the float. Since we want to collapse the child's top margin with the self-collapsing block's top and bottom margins we need to adjust our parent's height to match the
     // margin top of the self-collapsing block. If the resulting collapsed margin leaves the child still intruding into the float then we will want to clear it.
-    if (!marginInfo.canCollapseWithMarginBefore() && prev && prev->isRenderBlockFlow() && toRenderBlockFlow(prev)->isSelfCollapsingBlock()) {
-        clearanceForSelfCollapsingBlock = toRenderBlockFlow(prev)->marginOffsetForSelfCollapsingBlock();
+    if (!marginInfo.canCollapseWithMarginBefore() && previousBlockFlow && previousBlockFlow->isSelfCollapsingBlock()) {
+        clearanceForSelfCollapsingBlock = previousBlockFlow->marginOffsetForSelfCollapsingBlock();
         setLogicalHeight(logicalHeight() - clearanceForSelfCollapsingBlock);
     }
 
@@ -1053,21 +1108,19 @@
     // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
     // collapsed into the page edge.
     LayoutState* layoutState = view()->layoutState();
-    if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
-        && hasNextPage(beforeCollapseLogicalTop)) {
+    if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop) {
         LayoutUnit oldLogicalTop = logicalTop;
         logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
         setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
     }
 
-    if (prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
+    if (previousBlockFlow) {
         // If |child| is a self-collapsing block it may have collapsed into a previous sibling and although it hasn't reduced the height of the parent yet
         // any floats from the parent will now overhang.
-        RenderBlockFlow* blockFlow = toRenderBlockFlow(prev);
         LayoutUnit oldLogicalHeight = logicalHeight();
         setLogicalHeight(logicalTop);
-        if (blockFlow->containsFloats() && !blockFlow->avoidsFloats() && (blockFlow->logicalTop() + blockFlow->lowestFloatLogicalBottom()) > logicalTop)
-            addOverhangingFloats(blockFlow, false);
+        if (previousBlockFlow->containsFloats() && !previousBlockFlow->avoidsFloats() && (previousBlockFlow->logicalTop() + previousBlockFlow->lowestFloatLogicalBottom()) > logicalTop)
+            addOverhangingFloats(previousBlockFlow, false);
         setLogicalHeight(oldLogicalHeight);
 
         // If |child|'s previous sibling is a self-collapsing block that cleared a float and margin collapsing resulted in |child| moving up
@@ -1105,13 +1158,35 @@
     }
 }
 
-LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
+LayoutUnit RenderBlockFlow::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart)
+{
+    LayoutUnit startPosition = startOffsetForContent();
+
+    // Add in our start margin.
+    LayoutUnit oldPosition = startPosition + childMarginStart;
+    LayoutUnit newPosition = oldPosition;
+
+    LayoutUnit blockOffset = logicalTopForChild(child);
+    LayoutUnit startOff = startOffsetForLine(blockOffset, false, logicalHeightForChild(child));
+
+    if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
+        if (childMarginStart < 0)
+            startOff += childMarginStart;
+        newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
+    } else if (startOff != startPosition) {
+        newPosition = startOff + childMarginStart;
+    }
+
+    return newPosition - oldPosition;
+}
+
+LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos, bool childIsSelfCollapsing)
 {
     LayoutUnit heightIncrease = getClearDelta(child, yPos);
     if (!heightIncrease)
         return yPos;
 
-    if (child->isSelfCollapsingBlock()) {
+    if (childIsSelfCollapsing) {
         bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
 
         // For self-collapsing blocks that clear, they can still collapse their
@@ -1130,15 +1205,9 @@
         // CSS2.1 states:
         // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
         // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
-        // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
-        // for a block with height - if none is found then don't allow the margins to collapse with the parent.
-        bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
-        for (RenderBox* curr = child->nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
-            if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
-                wouldCollapseMarginsWithParent = false;
-        }
-        if (wouldCollapseMarginsWithParent)
-            marginInfo.setCanCollapseMarginAfterWithChildren(false);
+        // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Set a bit to ensure
+        // this happens; it will get reset if we encounter an in-flow sibling that is not self-collapsing.
+        marginInfo.setCanCollapseMarginAfterWithLastChild(false);
 
         // For now set the border-top of |child| flush with the bottom border-edge of the float so it can layout any floating or positioned children of
         // its own at the correct vertical position. If subsequent siblings attempt to collapse with |child|'s margins in |collapseMargins| we will
@@ -1280,8 +1349,7 @@
     // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
     // page.
     LayoutState* layoutState = view()->layoutState();
-    if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
-        && hasNextPage(logicalHeight()))
+    if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight())
         logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
 
     logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
@@ -1332,16 +1400,18 @@
     setLogicalHeight(logicalHeight() - marginOffset);
 }
 
-void RenderBlockFlow::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
+void RenderBlockFlow::handleAfterSideOfBlock(RenderBox* lastChild, LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
 {
     marginInfo.setAtAfterSideOfBlock(true);
 
     // If our last child was a self-collapsing block with clearance then our logical height is flush with the
     // bottom edge of the float that the child clears. The correct vertical position for the margin-collapsing we want
     // to perform now is at the child's margin-top - so adjust our height to that position.
-    RenderObject* child = lastChild();
-    if (child && child->isRenderBlockFlow() && toRenderBlockFlow(child)->isSelfCollapsingBlock())
-        setLogicalHeight(logicalHeight() - toRenderBlockFlow(child)->marginOffsetForSelfCollapsingBlock());
+    if (lastChild && lastChild->isRenderBlockFlow() && lastChild->isSelfCollapsingBlock())
+        setLogicalHeight(logicalHeight() - toRenderBlockFlow(lastChild)->marginOffsetForSelfCollapsingBlock());
+
+    if (marginInfo.canCollapseMarginAfterWithChildren() && !marginInfo.canCollapseMarginAfterWithLastChild())
+        marginInfo.setCanCollapseMarginAfterWithChildren(false);
 
     // If we can't collapse with children then go ahead and add in the bottom margin.
     if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
@@ -1477,19 +1547,21 @@
 LayoutUnit RenderBlockFlow::applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset)
 {
     // FIXME: Add page break checking here when we support printing.
-    bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
-    bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
     RenderFlowThread* flowThread = flowThreadContainingBlock();
-    bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
-    bool checkBeforeAlways = (checkColumnBreaks && child->style()->columnBreakBefore() == PBALWAYS) || (checkPageBreaks && child->style()->pageBreakBefore() == PBALWAYS)
-        || (checkRegionBreaks && child->style()->regionBreakBefore() == PBALWAYS);
-    if (checkBeforeAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
-        if (checkColumnBreaks)
-            view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
-        if (checkRegionBreaks) {
-            LayoutUnit offsetBreakAdjustment = 0;
-            if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset, child, true, &offsetBreakAdjustment))
-                return logicalOffset + offsetBreakAdjustment;
+    bool isInsideMulticolFlowThread = flowThread;
+    bool checkColumnBreaks = isInsideMulticolFlowThread || view()->layoutState()->isPaginatingColumns();
+    bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
+    bool checkBeforeAlways = (checkColumnBreaks && child->style()->columnBreakBefore() == PBALWAYS)
+        || (checkPageBreaks && child->style()->pageBreakBefore() == PBALWAYS);
+    if (checkBeforeAlways && inNormalFlow(child)) {
+        if (checkColumnBreaks) {
+            if (isInsideMulticolFlowThread) {
+                LayoutUnit offsetBreakAdjustment = 0;
+                if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset, child, true, &offsetBreakAdjustment))
+                    return logicalOffset + offsetBreakAdjustment;
+            } else {
+                view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
+            }
         }
         return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
     }
@@ -1499,24 +1571,26 @@
 LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
 {
     // FIXME: Add page break checking here when we support printing.
-    bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
-    bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
     RenderFlowThread* flowThread = flowThreadContainingBlock();
-    bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
-    bool checkAfterAlways = (checkColumnBreaks && child->style()->columnBreakAfter() == PBALWAYS) || (checkPageBreaks && child->style()->pageBreakAfter() == PBALWAYS)
-        || (checkRegionBreaks && child->style()->regionBreakAfter() == PBALWAYS);
-    if (checkAfterAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
+    bool isInsideMulticolFlowThread = flowThread;
+    bool checkColumnBreaks = isInsideMulticolFlowThread || view()->layoutState()->isPaginatingColumns();
+    bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
+    bool checkAfterAlways = (checkColumnBreaks && child->style()->columnBreakAfter() == PBALWAYS)
+        || (checkPageBreaks && child->style()->pageBreakAfter() == PBALWAYS);
+    if (checkAfterAlways && inNormalFlow(child)) {
         LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
 
         // So our margin doesn't participate in the next collapsing steps.
         marginInfo.clearMargin();
 
-        if (checkColumnBreaks)
-            view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
-        if (checkRegionBreaks) {
-            LayoutUnit offsetBreakAdjustment = 0;
-            if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, child, false, &offsetBreakAdjustment))
-                return logicalOffset + marginOffset + offsetBreakAdjustment;
+        if (checkColumnBreaks) {
+            if (isInsideMulticolFlowThread) {
+                LayoutUnit offsetBreakAdjustment = 0;
+                if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, child, false, &offsetBreakAdjustment))
+                    return logicalOffset + marginOffset + offsetBreakAdjustment;
+            } else {
+                view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
+            }
         }
         return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
     }
@@ -1540,10 +1614,23 @@
 void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
 {
     RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
-    if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
+    if (!hasColumns() && (recomputeFloats || createsBlockFormattingContext() || hasSelfPaintingLayer()))
         addOverflowFromFloats();
 }
 
+RootInlineBox* RenderBlockFlow::createAndAppendRootInlineBox()
+{
+    RootInlineBox* rootBox = createRootInlineBox();
+    m_lineBoxes.appendLineBox(rootBox);
+
+    if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
+        if (AXObjectCache* cache = document().existingAXObjectCache())
+            cache->recomputeIsIgnored(this);
+    }
+
+    return rootBox;
+}
+
 void RenderBlockFlow::deleteLineBoxTree()
 {
     if (containsFloats())
@@ -1632,11 +1719,10 @@
         LayoutUnit newLogicalTop = logicalTop;
         while (true) {
             LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
-            if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent(newLogicalTop))
+            if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent())
                 return newLogicalTop - logicalTop;
 
-            RenderRegion* region = regionAtBlockOffset(logicalTopForChild(child));
-            LayoutRect borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
+            LayoutRect borderBox = child->borderBoxRect();
             LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
 
             // FIXME: None of this is right for perpendicular writing-mode children.
@@ -1647,8 +1733,7 @@
 
             child->setLogicalTop(newLogicalTop);
             child->updateLogicalWidth();
-            region = regionAtBlockOffset(logicalTopForChild(child));
-            borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
+            borderBox = child->borderBoxRect();
             LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
 
             child->setLogicalTop(childOldLogicalTop);
@@ -1724,9 +1809,6 @@
         parentBlockFlow->markAllDescendantsWithFloatsForLayout();
         parentBlockFlow->markSiblingsWithFloatsForLayout();
     }
-
-    if (renderNamedFlowFragment())
-        renderNamedFlowFragment()->setStyleForNamedFlowFragment(style());
 }
 
 void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox* child, LayoutUnit logicalTop)
@@ -1734,15 +1816,11 @@
     if (child->style()->isOriginalDisplayInlineType())
         setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, false));
     else
-        setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
+        setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent());
 }
 
 void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
 {
-    if (flowThreadContainingBlock()) {
-        // Shift the inline position to exclude the region offset.
-        inlinePosition += startOffsetForContent() - startOffsetForContent(blockOffset);
-    }
     child->layer()->setStaticInlinePosition(inlinePosition);
 }
 
@@ -1975,10 +2053,30 @@
     return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
 }
 
+LayoutUnit RenderBlockFlow::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
+{
+    LayoutUnit left = offsetFromFloats;
+
+    if (applyTextIndent && style()->isLeftToRightDirection())
+        left += textIndentOffset();
+
+    return left;
+}
+
+LayoutUnit RenderBlockFlow::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
+{
+    LayoutUnit right = offsetFromFloats;
+
+    if (applyTextIndent && !style()->isLeftToRightDirection())
+        right -= textIndentOffset();
+
+    return right;
+}
+
 LayoutPoint RenderBlockFlow::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
 {
     RenderBox* childBox = floatingObject->renderer();
-    LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
+    LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
     LayoutUnit logicalRightOffset; // Constant part of right offset.
     // FIXME Bug 102948: This only works for shape outside directly set on this block.
     ShapeInsideInfo* shapeInsideInfo = this->layoutShapeInsideInfo();
@@ -2001,7 +2099,7 @@
             logicalLeftOffset += segments[0].logicalLeft;
         }
     } else {
-        logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset);
+        logicalRightOffset = logicalRightOffsetForContent();
     }
 
     LayoutUnit floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
@@ -2019,8 +2117,8 @@
             floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
             if (insideFlowThread) {
                 // Have to re-evaluate all of our offsets, since they may have changed.
-                logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
-                logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
+                logicalRightOffset = logicalRightOffsetForContent(); // Constant part of right offset.
+                logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
                 floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
             }
         }
@@ -2034,8 +2132,8 @@
             floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
             if (insideFlowThread) {
                 // Have to re-evaluate all of our offsets, since they may have changed.
-                logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
-                logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
+                logicalRightOffset = logicalRightOffsetForContent(); // Constant part of right offset.
+                logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
                 floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
             }
         }
@@ -2182,8 +2280,9 @@
             continue;
 
         RenderBox* childBox = floatingObject->renderer();
-        LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
+        LayoutRectRecorder childBoxRecorder(*childBox);
 
+        LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
         LayoutRect oldRect = childBox->frameRect();
 
         if (childBox->style()->clear() & CLEFT)
@@ -2245,7 +2344,8 @@
             shapeOutside->setShapeSize(logicalWidthForChild(childBox), logicalHeightForChild(childBox));
 
         // If the child moved, we have to repaint it.
-        if (childBox->checkForRepaintDuringLayout())
+        if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()
+            && childBox->checkForRepaintDuringLayout())
             childBox->repaintDuringLayoutIfMoved(oldRect);
     }
     return true;
@@ -2511,12 +2611,46 @@
     return result;
 }
 
+LayoutUnit RenderBlockFlow::logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
+{
+    LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
+    if (logicalLeft == logicalLeftOffsetForContent())
+        return RenderBlock::logicalLeftSelectionOffset(rootBlock, position);
+
+    RenderBlock* cb = this;
+    while (cb != rootBlock) {
+        logicalLeft += cb->logicalLeft();
+        cb = cb->containingBlock();
+    }
+    return logicalLeft;
+}
+
+LayoutUnit RenderBlockFlow::logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
+{
+    LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
+    if (logicalRight == logicalRightOffsetForContent())
+        return RenderBlock::logicalRightSelectionOffset(rootBlock, position);
+
+    RenderBlock* cb = this;
+    while (cb != rootBlock) {
+        logicalRight += cb->logicalLeft();
+        cb = cb->containingBlock();
+    }
+    return logicalRight;
+}
+
+/*template <typename CharacterType>
+static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
+{
+    return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
+}*/
+
 template <typename CharacterType>
-static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
 {
     ASSERT(style);
 
-    TextDirection textDirection = LTR;
+    TextDirection textDirection = direction;
     bool directionalOverride = style->rtlOrdering() == VisualOrder;
 
     TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
@@ -2527,11 +2661,11 @@
 }
 
 template <typename CharacterType>
-static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
+static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
 {
     ASSERT(style);
 
-    TextDirection textDirection = LTR;
+    TextDirection textDirection = direction;
     bool directionalOverride = style->rtlOrdering() == VisualOrder;
     if (flags != DefaultTextRunFlags) {
         if (flags & RespectDirection)
@@ -2539,6 +2673,7 @@
         if (flags & RespectDirectionOverride)
             directionalOverride |= isOverride(style->unicodeBidi());
     }
+
     TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
     if (textRunNeedsRenderingContext(font))
         run.setRenderingContext(SVGTextRunRenderingContext::create(context));
@@ -2546,39 +2681,47 @@
     return run;
 }
 
-TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const LChar* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const LChar* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
 {
-    return constructTextRunInternal(context, font, characters, length, style, expansion);
+    return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
 }
 
-TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
 {
-    return constructTextRunInternal(context, font, characters, length, style, expansion);
+    return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
 }
 
-TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
 {
     if (text->is8Bit())
-        return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, expansion);
-    return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, expansion);
+        return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, direction, expansion);
+    return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, direction, expansion);
 }
 
-TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
 {
     ASSERT(offset + length <= text->textLength());
     if (text->is8Bit())
-        return constructTextRunInternal(context, font, text->characters8() + offset, length, style, expansion);
-    return constructTextRunInternal(context, font, text->characters16() + offset, length, style, expansion);
+        return constructTextRunInternal(context, font, text->characters8() + offset, length, style, direction, expansion);
+    return constructTextRunInternal(context, font, text->characters16() + offset, length, style, direction, expansion);
+}
+
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
+{
+    unsigned length = string.length();
+    if (!length)
+        return constructTextRunInternal(context, font, static_cast<const LChar*>(0), length, style, direction, expansion, flags);
+    if (string.is8Bit())
+        return constructTextRunInternal(context, font, string.characters8(), length, style, direction, expansion, flags);
+    return constructTextRunInternal(context, font, string.characters16(), length, style, direction, expansion, flags);
 }
 
 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
 {
-    unsigned length = string.length();
-    if (!length)
-        return constructTextRunInternal(context, font, static_cast<const LChar*>(0), length, style, expansion, flags);
-    if (string.is8Bit())
-        return constructTextRunInternal(context, font, string.characters8(), length, style, expansion, flags);
-    return constructTextRunInternal(context, font, string.characters16(), length, style, expansion, flags);
+    bool hasStrongDirectionality;
+    return constructTextRun(context, font, string, style,
+        determineDirectionality(string, hasStrongDirectionality),
+        expansion, flags);
 }
 
 RootInlineBox* RenderBlockFlow::createRootInlineBox()
@@ -2586,55 +2729,6 @@
     return new RootInlineBox(this);
 }
 
-void RenderBlockFlow::createRenderNamedFlowFragmentIfNeeded()
-{
-    if (!RuntimeEnabledFeatures::cssRegionsEnabled()
-        || renderNamedFlowFragment()
-        || isRenderNamedFlowFragment())
-        return;
-
-    RenderStyle* styleToUse = style();
-    if (styleToUse->isDisplayRegionType() && styleToUse->hasFlowFrom() && document().renderView()) {
-        RenderNamedFlowFragment* flowFragment = RenderNamedFlowFragment::createAnonymous(&document());
-        flowFragment->setStyleForNamedFlowFragment(styleToUse);
-        setRenderNamedFlowFragment(flowFragment);
-        addChild(flowFragment);
-    }
-}
-
-void RenderBlockFlow::insertedIntoTree()
-{
-    RenderBlock::insertedIntoTree();
-
-    createRenderNamedFlowFragmentIfNeeded();
-}
-
-bool RenderBlockFlow::canHaveChildren() const
-{
-    return !renderNamedFlowFragment() ? RenderBlock::canHaveChildren() : renderNamedFlowFragment()->canHaveChildren();
-}
-
-bool RenderBlockFlow::canHaveGeneratedChildren() const
-{
-    return !renderNamedFlowFragment() ? RenderBlock::canHaveGeneratedChildren() : renderNamedFlowFragment()->canHaveGeneratedChildren();
-}
-
-void RenderBlockFlow::updateLogicalHeight()
-{
-    RenderBlock::updateLogicalHeight();
-
-    if (renderNamedFlowFragment())
-        renderNamedFlowFragment()->setLogicalHeight(max<LayoutUnit>(0, logicalHeight() - borderAndPaddingLogicalHeight()));
-}
-
-void RenderBlockFlow::setRenderNamedFlowFragment(RenderNamedFlowFragment* flowFragment)
-{
-    RenderBlockFlow::RenderBlockFlowRareData& rareData = ensureRareData();
-    if (rareData.m_renderNamedFlowFragment)
-        rareData.m_renderNamedFlowFragment->destroy();
-    rareData.m_renderNamedFlowFragment = flowFragment;
-}
-
 RenderBlockFlow::RenderBlockFlowRareData& RenderBlockFlow::ensureRareData()
 {
     if (m_rareData)
diff --git a/Source/core/rendering/RenderBlockFlow.h b/Source/core/rendering/RenderBlockFlow.h
index e683881..d769175 100644
--- a/Source/core/rendering/RenderBlockFlow.h
+++ b/Source/core/rendering/RenderBlockFlow.h
@@ -38,6 +38,7 @@
 
 #include "core/rendering/FloatingObjects.h"
 #include "core/rendering/RenderBlock.h"
+#include "core/rendering/line/TrailingObjects.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 
 namespace WebCore {
@@ -45,7 +46,6 @@
 class MarginInfo;
 class LineBreaker;
 class LineWidth;
-class RenderNamedFlowFragment;
 
 class RenderBlockFlow : public RenderBlock {
 public:
@@ -57,11 +57,53 @@
 
     virtual bool isRenderBlockFlow() const OVERRIDE FINAL { return true; }
 
-    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE;
+    virtual void layoutBlock(bool relayoutChildren) OVERRIDE;
 
     virtual void computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats = false) OVERRIDE;
     virtual void deleteLineBoxTree() OVERRIDE FINAL;
 
+    LayoutUnit availableLogicalWidthForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
+    {
+        return max<LayoutUnit>(0, logicalRightOffsetForLine(position, shouldIndentText, logicalHeight) - logicalLeftOffsetForLine(position, shouldIndentText, logicalHeight));
+    }
+    LayoutUnit logicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
+    {
+        return logicalRightOffsetForLine(position, logicalRightOffsetForContent(), shouldIndentText, logicalHeight);
+    }
+    LayoutUnit logicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
+    {
+        return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(), shouldIndentText, logicalHeight);
+    }
+    LayoutUnit pixelSnappedLogicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
+    {
+        return roundToInt(logicalLeftOffsetForLine(position, shouldIndentText, logicalHeight));
+    }
+    LayoutUnit pixelSnappedLogicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
+    {
+        // FIXME: Multicolumn layouts break carrying over subpixel values to the logical right offset because the lines may be shifted
+        // by a subpixel value for all but the first column. This can lead to the actual pixel snapped width of the column being off
+        // by one pixel when rendered versus layed out, which can result in the line being clipped. For now, we have to floor.
+        // https://bugs.webkit.org/show_bug.cgi?id=105461
+        return floorToInt(logicalRightOffsetForLine(position, shouldIndentText, logicalHeight));
+    }
+    LayoutUnit startOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
+    {
+        return style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, logicalHeight)
+            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, logicalHeight);
+    }
+    LayoutUnit endOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
+    {
+        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, logicalHeight)
+            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, logicalHeight);
+    }
+
+    virtual LayoutUnit logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position) OVERRIDE;
+    virtual LayoutUnit logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position) OVERRIDE;
+
+    LayoutUnit computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart);
+
+    RootInlineBox* createAndAppendRootInlineBox();
+
     void markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove = 0, bool inLayout = true);
     void markSiblingsWithFloatsForLayout(RenderBox* floatToRemove = 0);
 
@@ -70,6 +112,8 @@
 
     void removeFloatingObjects();
 
+    void moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert);
+
     bool generatesLineBoxesForInlineChild(RenderObject*);
 
     LayoutUnit logicalTopForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->y() : floatingObject->x(); }
@@ -124,47 +168,36 @@
         return obj->isFloating() || (obj->isOutOfFlowPositioned() && !obj->style()->isOriginalDisplayInlineType() && !obj->container()->isRenderInline());
     }
 
+    // Direction resolved from string value.
     static TextRun constructTextRun(RenderObject* context, const Font&, const String&, RenderStyle*,
         TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, TextRunFlags = DefaultTextRunFlags);
 
-    static TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, RenderStyle*,
+    // Explicit direction.
+    static TextRun constructTextRun(RenderObject* context, const Font&, const String&, RenderStyle*, TextDirection,
+        TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, TextRunFlags = DefaultTextRunFlags);
+
+    static TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, RenderStyle*, TextDirection,
         TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
 
-    static TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, unsigned offset, unsigned length, RenderStyle*,
+    static TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, unsigned offset, unsigned length, RenderStyle*, TextDirection,
         TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
 
     static TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, unsigned offset, RenderStyle*,
         TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
 
-    static TextRun constructTextRun(RenderObject* context, const Font&, const LChar* characters, int length, RenderStyle*,
+    static TextRun constructTextRun(RenderObject* context, const Font&, const LChar* characters, int length, RenderStyle*, TextDirection,
         TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
 
-    static TextRun constructTextRun(RenderObject* context, const Font&, const UChar* characters, int length, RenderStyle*,
+    static TextRun constructTextRun(RenderObject* context, const Font&, const UChar* characters, int length, RenderStyle*, TextDirection,
         TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
 
-    RootInlineBox* lineGridBox() const { return m_rareData ? m_rareData->m_lineGridBox : 0; }
-    void setLineGridBox(RootInlineBox* box)
-    {
-        RenderBlockFlow::RenderBlockFlowRareData& rareData = ensureRareData();
-        if (rareData.m_lineGridBox)
-            rareData.m_lineGridBox->destroy();
-        rareData.m_lineGridBox = box;
-    }
-    void layoutLineGridBox();
-
     void addOverflowFromInlineChildren();
 
     GapRects inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
         LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo*);
 protected:
-    // Only used by RenderSVGText, which explicitly overrides RenderBlock::layoutBlock(), do NOT use for anything else.
-    void forceLayoutInlineChildren()
-    {
-        LayoutUnit repaintLogicalTop = 0;
-        LayoutUnit repaintLogicalBottom = 0;
-        rebuildFloatsFromIntruding();
-        layoutInlineChildren(true, repaintLogicalTop, repaintLogicalBottom);
-    }
+    void rebuildFloatsFromIntruding();
+    void layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom, LayoutUnit afterEdge);
 
     void createFloatingObjects();
 
@@ -173,18 +206,23 @@
 
     void addOverflowFromFloats();
 
-    virtual void insertedIntoTree() OVERRIDE;
-    virtual void willBeDestroyed() OVERRIDE;
+    LayoutUnit logicalRightOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit logicalHeight = 0) const
+    {
+        return adjustLogicalRightOffsetForLine(logicalRightFloatOffsetForLine(logicalTop, fixedOffset, logicalHeight), applyTextIndent);
+    }
+    LayoutUnit logicalLeftOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit logicalHeight = 0) const
+    {
+        return adjustLogicalLeftOffsetForLine(logicalLeftFloatOffsetForLine(logicalTop, fixedOffset, logicalHeight), applyTextIndent);
+    }
+
 private:
-    void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope&);
-    void layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom);
+    bool layoutBlockFlow(bool relayoutChildren, LayoutUnit& pageLogicalHeight, SubtreeLayoutScope&);
+    void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope&, LayoutUnit beforeEdge, LayoutUnit afterEdge);
 
     void layoutBlockChild(RenderBox* child, MarginInfo&, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom);
     void adjustPositionedBlock(RenderBox* child, const MarginInfo&);
     void adjustFloatingBlock(const MarginInfo&);
 
-    void rebuildFloatsFromIntruding();
-
     LayoutPoint flipFloatForWritingModeForChild(const FloatingObject*, const LayoutPoint&) const;
 
     LayoutUnit xPositionForFloatIncludingMargin(const FloatingObject* child) const
@@ -225,25 +263,30 @@
 
     virtual bool hitTestFloats(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) OVERRIDE FINAL;
 
-    virtual void moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert) OVERRIDE;
     virtual void repaintOverhangingFloats(bool paintAllDescendants) OVERRIDE FINAL;
-    virtual void repaintOverflow() OVERRIDE;
+    virtual void repaintOverflow() OVERRIDE FINAL;
     virtual void paintFloats(PaintInfo&, const LayoutPoint&, bool preservePhase = false) OVERRIDE FINAL;
     virtual void clipOutFloatingObjects(RenderBlock*, const PaintInfo*, const LayoutPoint&, const LayoutSize&) OVERRIDE;
     void clearFloats(EClear);
 
-    virtual LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const OVERRIDE;
-    virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const OVERRIDE;
+    LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const;
+    LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const;
 
     LayoutUnit logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const;
     LayoutUnit logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const;
 
+    LayoutUnit adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
+    LayoutUnit adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
+
     virtual void adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const OVERRIDE; // Helper function for borderFitAdjust
 
-    virtual RootInlineBox* createRootInlineBox() OVERRIDE;
+    virtual RootInlineBox* createRootInlineBox(); // Subclassed by SVG
 
     void updateLogicalWidthForAlignment(const ETextAlign&, const RootInlineBox*, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount);
-    virtual bool relayoutForPagination(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer&);
+    virtual void checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight);
+    bool shouldRelayoutForPagination(LayoutUnit& pageLogicalHeight, LayoutUnit layoutOverflowLogicalBottom) const;
+    void setColumnCountAndHeight(unsigned count, LayoutUnit pageLogicalHeight);
+
 public:
     struct FloatWithRect {
         FloatWithRect(RenderBox* f)
@@ -285,18 +328,14 @@
     };
     MarginValues marginValuesForChild(RenderBox* child) const;
 
-    virtual void updateLogicalHeight() OVERRIDE;
-
     // Allocated only when some of these fields have non-default values
     struct RenderBlockFlowRareData {
         WTF_MAKE_NONCOPYABLE(RenderBlockFlowRareData); WTF_MAKE_FAST_ALLOCATED;
     public:
         RenderBlockFlowRareData(const RenderBlockFlow* block)
             : m_margins(positiveMarginBeforeDefault(block), negativeMarginBeforeDefault(block), positiveMarginAfterDefault(block), negativeMarginAfterDefault(block))
-            , m_lineGridBox(0)
             , m_discardMarginBefore(false)
             , m_discardMarginAfter(false)
-            , m_renderNamedFlowFragment(0)
         {
         }
 
@@ -319,17 +358,11 @@
 
         MarginValues m_margins;
 
-        RootInlineBox* m_lineGridBox;
-
         bool m_discardMarginBefore : 1;
         bool m_discardMarginAfter : 1;
-        RenderNamedFlowFragment* m_renderNamedFlowFragment;
     };
     LayoutUnit marginOffsetForSelfCollapsingBlock();
 
-    RenderNamedFlowFragment* renderNamedFlowFragment() const { return m_rareData ? m_rareData->m_renderNamedFlowFragment : 0; }
-    void setRenderNamedFlowFragment(RenderNamedFlowFragment*);
-
 protected:
     LayoutUnit maxPositiveMarginBefore() const { return m_rareData ? m_rareData->m_margins.positiveMarginBefore() : RenderBlockFlowRareData::positiveMarginBeforeDefault(this); }
     LayoutUnit maxNegativeMarginBefore() const { return m_rareData ? m_rareData->m_margins.negativeMarginBefore() : RenderBlockFlowRareData::negativeMarginBeforeDefault(this); }
@@ -367,11 +400,11 @@
     virtual LayoutUnit collapsedMarginBefore() const OVERRIDE FINAL { return maxPositiveMarginBefore() - maxNegativeMarginBefore(); }
     virtual LayoutUnit collapsedMarginAfter() const OVERRIDE FINAL { return maxPositiveMarginAfter() - maxNegativeMarginAfter(); }
 
-    LayoutUnit collapseMargins(RenderBox* child, MarginInfo&);
-    LayoutUnit clearFloatsIfNeeded(RenderBox* child, MarginInfo&, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos);
+    LayoutUnit collapseMargins(RenderBox* child, MarginInfo&, bool childIsSelfCollapsing);
+    LayoutUnit clearFloatsIfNeeded(RenderBox* child, MarginInfo&, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos, bool childIsSelfCollapsing);
     LayoutUnit estimateLogicalTopPosition(RenderBox* child, const MarginInfo&, LayoutUnit& estimateWithoutPagination);
     void marginBeforeEstimateForChild(RenderBox*, LayoutUnit&, LayoutUnit&, bool&) const;
-    void handleAfterSideOfBlock(LayoutUnit top, LayoutUnit bottom, MarginInfo&);
+    void handleAfterSideOfBlock(RenderBox* lastChild, LayoutUnit top, LayoutUnit bottom, MarginInfo&);
     void setCollapsedBottomMargin(const MarginInfo&);
 
     LayoutUnit applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset); // If the child has a before break, then return a new yPos that shifts to the top of the next page/column.
@@ -382,16 +415,12 @@
     // Used to store state between styleWillChange and styleDidChange
     static bool s_canPropagateFloatIntoSibling;
 
-    virtual bool canHaveChildren() const OVERRIDE;
-    virtual bool canHaveGeneratedChildren() const OVERRIDE;
-
-    void createRenderNamedFlowFragmentIfNeeded();
-
     RenderBlockFlowRareData& ensureRareData();
 
     LayoutUnit m_repaintLogicalTop;
     LayoutUnit m_repaintLogicalBottom;
 
+    virtual bool isSelfCollapsingBlock() const OVERRIDE;
 protected:
     OwnPtr<RenderBlockFlowRareData> m_rareData;
     OwnPtr<FloatingObjects> m_floatingObjects;
@@ -417,7 +446,7 @@
     void appendFloatingObjectToLastLine(FloatingObject*);
     // Helper function for layoutInlineChildren()
     RootInlineBox* createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>&, const InlineIterator& end, LineInfo&, VerticalPositionCache&, BidiRun* trailingSpaceRun, WordMeasurements&);
-    void layoutRunsAndFloats(LineLayoutState&, bool hasInlineChild);
+    void layoutRunsAndFloats(LineLayoutState&);
     const InlineIterator& restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight,  FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver&,  const InlineIterator&);
     void layoutRunsAndFloatsInRange(LineLayoutState&, InlineBidiResolver&, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines);
     void updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*&, const LayoutSize&, LineLayoutState&);
diff --git a/Source/core/rendering/RenderBlockLineLayout.cpp b/Source/core/rendering/RenderBlockLineLayout.cpp
index 8c5019e..89f3a70 100644
--- a/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -22,7 +22,6 @@
 
 #include "config.h"
 
-#include "core/rendering/FastTextAutosizer.h"
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderCounter.h"
 #include "core/rendering/RenderFlowThread.h"
@@ -34,7 +33,10 @@
 #include "core/rendering/TrailingFloatsRootInlineBox.h"
 #include "core/rendering/VerticalPositionCache.h"
 #include "core/rendering/line/BreakingContextInlineHeaders.h"
+#include "core/rendering/line/LineLayoutState.h"
+#include "core/rendering/line/LineWidth.h"
 #include "core/rendering/svg/SVGRootInlineBox.h"
+#include "platform/fonts/Character.h"
 #include "platform/text/BidiResolver.h"
 #include "wtf/RefCountedLeakCounter.h"
 #include "wtf/StdLibExtras.h"
@@ -43,41 +45,8 @@
 
 namespace WebCore {
 
-static IndentTextOrNot requiresIndent(bool isFirstLine, bool isAfterHardLineBreak, RenderStyle* style)
-{
-    if (isFirstLine)
-        return IndentText;
-    if (isAfterHardLineBreak && style->textIndentLine() == TextIndentEachLine)
-        return IndentText;
-
-    return DoNotIndentText;
-}
-
-class LineBreaker {
-public:
-    friend class BreakingContext;
-    LineBreaker(RenderBlockFlow* block)
-        : m_block(block)
-    {
-        reset();
-    }
-
-    InlineIterator nextLineBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
-
-    bool lineWasHyphenated() { return m_hyphenated; }
-    const Vector<RenderBox*>& positionedObjects() { return m_positionedObjects; }
-    EClear clear() { return m_clear; }
-private:
-    void reset();
-
-    InlineIterator nextSegmentBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
-    void skipLeadingWhitespace(InlineBidiResolver&, LineInfo&, FloatingObject* lastFloatFromPreviousLine, LineWidth&);
-
-    RenderBlockFlow* m_block;
-    bool m_hyphenated;
-    EClear m_clear;
-    Vector<RenderBox*> m_positionedObjects;
-};
+using namespace std;
+using namespace WTF::Unicode;
 
 static RenderObject* firstRenderObjectForDirectionalityDetermination(RenderObject* root, RenderObject* current = 0)
 {
@@ -135,7 +104,7 @@
 static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
 {
     if (isRootLineBox)
-        return toRenderBlock(obj)->createAndAppendRootInlineBox();
+        return toRenderBlockFlow(obj)->createAndAppendRootInlineBox();
 
     if (obj->isText()) {
         InlineTextBox* textBox = toRenderText(obj)->createInlineTextBox();
@@ -466,11 +435,11 @@
     LayoutUnit hyphenWidth = 0;
     if (toInlineTextBox(run->m_box)->hasHyphen()) {
         const Font& font = renderer->style(lineInfo.isFirstLine())->font();
-        hyphenWidth = measureHyphenWidth(renderer, font);
+        hyphenWidth = measureHyphenWidth(renderer, font, run->direction());
     }
     float measuredWidth = 0;
 
-    bool kerningIsEnabled = font.typesettingFeatures() & Kerning;
+    bool kerningIsEnabled = font.fontDescription().typesettingFeatures() & Kerning;
 
 #if OS(MACOSX)
     // FIXME: Having any font feature settings enabled can lead to selection gaps on
@@ -495,7 +464,7 @@
             lastEndOffset = wordMeasurement.endOffset;
             if (kerningIsEnabled && lastEndOffset == run->m_stop) {
                 int wordLength = lastEndOffset - wordMeasurement.startOffset;
-                measuredWidth += renderer->width(wordMeasurement.startOffset, wordLength, xPos, lineInfo.isFirstLine());
+                measuredWidth += renderer->width(wordMeasurement.startOffset, wordLength, xPos, run->direction(), lineInfo.isFirstLine());
                 if (i > 0 && wordLength == 1 && renderer->characterAt(wordMeasurement.startOffset) == ' ')
                     measuredWidth += renderer->style()->wordSpacing();
             } else
@@ -514,19 +483,19 @@
     }
 
     if (!measuredWidth)
-        measuredWidth = renderer->width(run->m_start, run->m_stop - run->m_start, xPos, lineInfo.isFirstLine(), &fallbackFonts, &glyphOverflow);
+        measuredWidth = renderer->width(run->m_start, run->m_stop - run->m_start, xPos, run->direction(), lineInfo.isFirstLine(), &fallbackFonts, &glyphOverflow);
 
     run->m_box->setLogicalWidth(measuredWidth + hyphenWidth);
     if (!fallbackFonts.isEmpty()) {
         ASSERT(run->m_box->isText());
-        GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).iterator;
+        GlyphOverflowAndFallbackFontsMap::ValueType* it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).storedValue;
         ASSERT(it->value.first.isEmpty());
         copyToVector(fallbackFonts, it->value.first);
         run->m_box->parent()->clearDescendantsHaveSameLineHeightAndBaseline();
     }
     if ((glyphOverflow.top || glyphOverflow.bottom || glyphOverflow.left || glyphOverflow.right)) {
         ASSERT(run->m_box->isText());
-        GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).iterator;
+        GlyphOverflowAndFallbackFontsMap::ValueType* it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).storedValue;
         it->value.second = glyphOverflow;
         run->m_box->clearKnownToHaveNoOverflow();
     }
@@ -712,16 +681,16 @@
                     toInlineTextBox(r->m_box)->setCanHaveLeadingExpansion(true);
                 unsigned opportunitiesInRun;
                 if (rt->is8Bit())
-                    opportunitiesInRun = Font::expansionOpportunityCount(rt->characters8() + r->m_start, r->m_stop - r->m_start, r->m_box->direction(), isAfterExpansion);
+                    opportunitiesInRun = Character::expansionOpportunityCount(rt->characters8() + r->m_start, r->m_stop - r->m_start, r->m_box->direction(), isAfterExpansion);
                 else
-                    opportunitiesInRun = Font::expansionOpportunityCount(rt->characters16() + r->m_start, r->m_stop - r->m_start, r->m_box->direction(), isAfterExpansion);
+                    opportunitiesInRun = Character::expansionOpportunityCount(rt->characters16() + r->m_start, r->m_stop - r->m_start, r->m_box->direction(), isAfterExpansion);
                 expansionOpportunities.append(opportunitiesInRun);
                 expansionOpportunityCount += opportunitiesInRun;
             }
 
             if (int length = rt->textLength()) {
                 if (!r->m_start && needsWordSpacing && isSpaceOrNewline(rt->characterAt(r->m_start)))
-                    totalLogicalWidth += rt->style(lineInfo.isFirstLine())->font().wordSpacing();
+                    totalLogicalWidth += rt->style(lineInfo.isFirstLine())->font().fontDescription().wordSpacing();
                 needsWordSpacing = !isSpaceOrNewline(rt->characterAt(r->m_stop - 1)) && r->m_stop == length;
             }
 
@@ -781,80 +750,6 @@
     lineBox->markDirty(false);
 }
 
-static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
-{
-    if (character == ' ' || character == '\t' || character == softHyphen)
-        return true;
-    if (character == '\n')
-        return !renderer->style()->preserveNewline();
-    return false;
-}
-
-template <typename CharacterType>
-static inline int findFirstTrailingSpace(RenderText* lastText, const CharacterType* characters, int start, int stop)
-{
-    int firstSpace = stop;
-    while (firstSpace > start) {
-        UChar current = characters[firstSpace - 1];
-        if (!isCollapsibleSpace(current, lastText))
-            break;
-        firstSpace--;
-    }
-
-    return firstSpace;
-}
-
-inline BidiRun* RenderBlockFlow::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
-{
-    if (!bidiRuns.runCount()
-        || !bidiRuns.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
-        || !bidiRuns.logicallyLastRun()->m_object->style()->autoWrap())
-        return 0;
-
-    BidiRun* trailingSpaceRun = bidiRuns.logicallyLastRun();
-    RenderObject* lastObject = trailingSpaceRun->m_object;
-    if (!lastObject->isText())
-        return 0;
-
-    RenderText* lastText = toRenderText(lastObject);
-    int firstSpace;
-    if (lastText->is8Bit())
-        firstSpace = findFirstTrailingSpace(lastText, lastText->characters8(), trailingSpaceRun->start(), trailingSpaceRun->stop());
-    else
-        firstSpace = findFirstTrailingSpace(lastText, lastText->characters16(), trailingSpaceRun->start(), trailingSpaceRun->stop());
-
-    if (firstSpace == trailingSpaceRun->stop())
-        return 0;
-
-    TextDirection direction = style()->direction();
-    bool shouldReorder = trailingSpaceRun != (direction == LTR ? bidiRuns.lastRun() : bidiRuns.firstRun());
-    if (firstSpace != trailingSpaceRun->start()) {
-        BidiContext* baseContext = currentContext;
-        while (BidiContext* parent = baseContext->parent())
-            baseContext = parent;
-
-        BidiRun* newTrailingRun = new BidiRun(firstSpace, trailingSpaceRun->m_stop, trailingSpaceRun->m_object, baseContext, OtherNeutral);
-        trailingSpaceRun->m_stop = firstSpace;
-        if (direction == LTR)
-            bidiRuns.addRun(newTrailingRun);
-        else
-            bidiRuns.prependRun(newTrailingRun);
-        trailingSpaceRun = newTrailingRun;
-        return trailingSpaceRun;
-    }
-    if (!shouldReorder)
-        return trailingSpaceRun;
-
-    if (direction == LTR) {
-        bidiRuns.moveRunToEnd(trailingSpaceRun);
-        trailingSpaceRun->m_level = 0;
-    } else {
-        bidiRuns.moveRunToBeginning(trailingSpaceRun);
-        trailingSpaceRun->m_level = 1;
-    }
-    return trailingSpaceRun;
-}
-
 void RenderBlockFlow::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
 {
     ASSERT(!floatingObject->originatingLine());
@@ -919,7 +814,7 @@
         LineMidpointState& isolatedLineMidpointState = isolatedResolver.midpointState();
         isolatedLineMidpointState = topResolver.midpointStateForIsolatedRun(isolatedRun);
         EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi();
-        TextDirection direction = isolatedInline->style()->direction();
+        TextDirection direction;
         if (unicodeBidi == Plaintext) {
             if (isNewUBAParagraph)
                 direction = determinePlaintextDirectionality(isolatedInline, startObj);
@@ -980,11 +875,11 @@
         InlineIterator segmentEnd(iterator.root, iterator.object, iterator.offset);
         if (i) {
             ASSERT(segmentStart.object());
-            BidiRun* segmentMarker = createRun(segmentStart.m_pos, segmentStart.m_pos, segmentStart.object(), topResolver);
+            BidiRun* segmentMarker = createRun(segmentStart.offset(), segmentStart.offset(), segmentStart.object(), topResolver);
             segmentMarker->m_startsSegment = true;
             bidiRuns.addRun(segmentMarker);
             // Do not collapse midpoints between segments
-            topResolver.midpointState().betweenMidpoints = false;
+            topResolver.midpointState().setBetweenMidpoints(false);
         }
         if (!segmentIsEmpty(segmentStart, segmentEnd)) {
             topResolver.setPosition(segmentStart, numberOfIsolateAncestors(segmentStart));
@@ -1036,95 +931,6 @@
     return lineBox;
 }
 
-// Like LayoutState for layout(), LineLayoutState keeps track of global information
-// during an entire linebox tree layout pass (aka layoutInlineChildren).
-class LineLayoutState {
-public:
-    LineLayoutState(bool fullLayout, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom, RenderFlowThread* flowThread)
-        : m_lastFloat(0)
-        , m_endLine(0)
-        , m_floatIndex(0)
-        , m_endLineLogicalTop(0)
-        , m_endLineMatched(false)
-        , m_checkForFloatsFromLastLine(false)
-        , m_isFullLayout(fullLayout)
-        , m_repaintLogicalTop(repaintLogicalTop)
-        , m_repaintLogicalBottom(repaintLogicalBottom)
-        , m_adjustedLogicalLineTop(0)
-        , m_usesRepaintBounds(false)
-        , m_flowThread(flowThread)
-    { }
-
-    void markForFullLayout() { m_isFullLayout = true; }
-    bool isFullLayout() const { return m_isFullLayout; }
-
-    bool usesRepaintBounds() const { return m_usesRepaintBounds; }
-
-    void setRepaintRange(LayoutUnit logicalHeight)
-    {
-        m_usesRepaintBounds = true;
-        m_repaintLogicalTop = m_repaintLogicalBottom = logicalHeight;
-    }
-
-    void updateRepaintRangeFromBox(RootInlineBox* box, LayoutUnit paginationDelta = 0)
-    {
-        m_usesRepaintBounds = true;
-        m_repaintLogicalTop = min(m_repaintLogicalTop, box->logicalTopVisualOverflow() + min<LayoutUnit>(paginationDelta, 0));
-        m_repaintLogicalBottom = max(m_repaintLogicalBottom, box->logicalBottomVisualOverflow() + max<LayoutUnit>(paginationDelta, 0));
-    }
-
-    bool endLineMatched() const { return m_endLineMatched; }
-    void setEndLineMatched(bool endLineMatched) { m_endLineMatched = endLineMatched; }
-
-    bool checkForFloatsFromLastLine() const { return m_checkForFloatsFromLastLine; }
-    void setCheckForFloatsFromLastLine(bool check) { m_checkForFloatsFromLastLine = check; }
-
-    LineInfo& lineInfo() { return m_lineInfo; }
-    const LineInfo& lineInfo() const { return m_lineInfo; }
-
-    LayoutUnit endLineLogicalTop() const { return m_endLineLogicalTop; }
-    void setEndLineLogicalTop(LayoutUnit logicalTop) { m_endLineLogicalTop = logicalTop; }
-
-    RootInlineBox* endLine() const { return m_endLine; }
-    void setEndLine(RootInlineBox* line) { m_endLine = line; }
-
-    FloatingObject* lastFloat() const { return m_lastFloat; }
-    void setLastFloat(FloatingObject* lastFloat) { m_lastFloat = lastFloat; }
-
-    Vector<RenderBlockFlow::FloatWithRect>& floats() { return m_floats; }
-
-    unsigned floatIndex() const { return m_floatIndex; }
-    void setFloatIndex(unsigned floatIndex) { m_floatIndex = floatIndex; }
-
-    LayoutUnit adjustedLogicalLineTop() const { return m_adjustedLogicalLineTop; }
-    void setAdjustedLogicalLineTop(LayoutUnit value) { m_adjustedLogicalLineTop = value; }
-
-    RenderFlowThread* flowThread() const { return m_flowThread; }
-    void setFlowThread(RenderFlowThread* thread) { m_flowThread = thread; }
-
-private:
-    Vector<RenderBlockFlow::FloatWithRect> m_floats;
-    FloatingObject* m_lastFloat;
-    RootInlineBox* m_endLine;
-    LineInfo m_lineInfo;
-    unsigned m_floatIndex;
-    LayoutUnit m_endLineLogicalTop;
-    bool m_endLineMatched;
-    bool m_checkForFloatsFromLastLine;
-
-    bool m_isFullLayout;
-
-    // FIXME: Should this be a range object instead of two ints?
-    LayoutUnit& m_repaintLogicalTop;
-    LayoutUnit& m_repaintLogicalBottom;
-
-    LayoutUnit m_adjustedLogicalLineTop;
-
-    bool m_usesRepaintBounds;
-
-    RenderFlowThread* m_flowThread;
-};
-
 static void deleteLineRange(LineLayoutState& layoutState, RootInlineBox* startLine, RootInlineBox* stopLine = 0)
 {
     RootInlineBox* boxToDelete = startLine;
@@ -1138,7 +944,7 @@
     }
 }
 
-void RenderBlockFlow::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
+void RenderBlockFlow::layoutRunsAndFloats(LineLayoutState& layoutState)
 {
     // We want to skip ahead to the first dirty line
     InlineBidiResolver resolver;
@@ -1150,28 +956,6 @@
             consecutiveHyphenatedLines++;
     }
 
-    // FIXME: This would make more sense outside of this function, but since
-    // determineStartPosition can change the fullLayout flag we have to do this here. Failure to call
-    // determineStartPosition first will break fast/repaint/line-flow-with-floats-9.html.
-    if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) {
-        // Mark as needing a full layout to force us to repaint. Allow regions
-        // to reflow as needed.
-        setNeedsLayout(MarkOnlyThis);
-
-        if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
-            setShouldDoFullRepaintAfterLayout(true);
-        } else {
-            RenderView* v = view();
-            if (v && !v->doingFullRepaint() && hasLayer()) {
-                // Because we waited until we were already inside layout to discover
-                // that the block really needed a full layout, we missed our chance to repaint the layer
-                // before layout started. Luckily the layer has cached the repaint rect for its original
-                // position and size, and so we can use that to make a repaint happen now.
-                repaintUsingContainer(containerForRepaint(), pixelSnappedIntRect(layer()->repainter().repaintRect()));
-            }
-        }
-    }
-
     if (containsFloats())
         layoutState.setLastFloat(m_floatingObjects->set().last());
 
@@ -1311,7 +1095,8 @@
         shapeBottomInFlowThread = shapeInsideInfo->shapeLogicalBottom() + currentRegion->logicalTopForFlowThreadContent();
 
     bool lineOverLapsWithShapeBottom = shapeBottomInFlowThread < logicalLineBottomInFlowThread;
-    bool lineOverLapsWithRegionBottom = logicalLineBottomInFlowThread > logicalRegionBottomInFlowThread;
+    bool lineTopAdjustedIntoNextRegion = layoutState.adjustedLogicalLineTop() >= currentRegion->logicalHeight();
+    bool lineOverLapsWithRegionBottom = logicalLineBottomInFlowThread > logicalRegionBottomInFlowThread || lineTopAdjustedIntoNextRegion;
     bool overFlowsToNextRegion = nextRegion && (lineOverLapsWithShapeBottom || lineOverLapsWithRegionBottom);
 
     // If the line is between two shapes/regions we position the line to the top of the next shape/region
@@ -1327,6 +1112,9 @@
         logicalLineBottomInFlowThread = logicalLineTopInFlowThread + lineHeight;
         logicalRegionTopInFlowThread = currentRegion->logicalTopForFlowThreadContent();
         logicalRegionBottomInFlowThread = logicalRegionTopInFlowThread + currentRegion->logicalHeight() - currentRegion->borderAndPaddingBefore() - currentRegion->borderAndPaddingAfter();
+
+        if (lineTopAdjustedIntoNextRegion)
+            layoutState.setAdjustedLogicalLineTop(0);
     }
 
     if (!shapeInsideInfo)
@@ -1398,7 +1186,7 @@
     LayoutSize logicalOffsetFromShapeContainer;
     ShapeInsideInfo* shapeInsideInfo = layoutShapeInsideInfo();
     if (shapeInsideInfo) {
-        ASSERT(shapeInsideInfo->owner() == this || allowsShapeInsideInfoSharing());
+        ASSERT(shapeInsideInfo->owner() == this || allowsShapeInsideInfoSharing(shapeInsideInfo->owner()));
         if (shapeInsideInfo != this->shapeInsideInfo()) {
             // FIXME Bug 100284: If subsequent LayoutStates are pushed, we will have to add
             // their offsets from the original shape-inside container.
@@ -1455,10 +1243,9 @@
         // This is a short-cut for empty lines.
         if (layoutState.lineInfo().isEmpty()) {
             if (lastRootBox())
-                lastRootBox()->setLineBreakInfo(endOfLine.object(), endOfLine.m_pos, resolver.status());
+                lastRootBox()->setLineBreakInfo(endOfLine.object(), endOfLine.offset(), resolver.status());
         } else {
             VisualDirectionOverride override = (styleToUse->rtlOrdering() == VisualOrder ? (styleToUse->direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride);
-
             if (isNewUBAParagraph && styleToUse->unicodeBidi() == Plaintext && !resolver.context()->parent()) {
                 TextDirection direction = determinePlaintextDirectionality(resolver.position().root(), resolver.position().object(), resolver.position().offset());
                 resolver.setStatus(BidiStatus(direction, isOverride(styleToUse->unicodeBidi())));
@@ -1468,7 +1255,7 @@
             constructBidiRunsForLine(this, resolver, bidiRuns, endOfLine, override, layoutState.lineInfo().previousLineBrokeCleanly(), isNewUBAParagraph);
             ASSERT(resolver.position() == endOfLine);
 
-            BidiRun* trailingSpaceRun = !layoutState.lineInfo().previousLineBrokeCleanly() ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0;
+            BidiRun* trailingSpaceRun = resolver.trailingSpaceRun();
 
             if (bidiRuns.runCount() && lineBreaker.lineWasHyphenated()) {
                 bidiRuns.logicallyLastRun()->m_hasHyphen = true;
@@ -1487,7 +1274,7 @@
             resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
 
             if (lineBox) {
-                lineBox->setLineBreakInfo(endOfLine.object(), endOfLine.m_pos, resolver.status());
+                lineBox->setLineBreakInfo(endOfLine.object(), endOfLine.offset(), resolver.status());
                 if (layoutState.usesRepaintBounds())
                     layoutState.updateRepaintRangeFromBox(lineBox);
 
@@ -1509,9 +1296,6 @@
 
                         setLogicalHeight(lineBox->lineBottomWithLeading());
                     }
-
-                    if (layoutState.flowThread())
-                        updateRegionForLine(lineBox);
                 }
             }
         }
@@ -1630,8 +1414,6 @@
                     layoutState.updateRepaintRangeFromBox(line, delta);
                     line->adjustBlockDirectionPosition(delta);
                 }
-                if (layoutState.flowThread())
-                    updateRegionForLine(line);
                 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
                     Vector<RenderBox*>::iterator end = cleanLineFloats->end();
                     for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
@@ -1665,12 +1447,10 @@
             LayoutUnit blockLogicalHeight = logicalHeight();
             trailingFloatsLineBox->alignBoxesInBlockDirection(blockLogicalHeight, textBoxDataMap, verticalPositionCache);
             trailingFloatsLineBox->setLineTopBottomPositions(blockLogicalHeight, blockLogicalHeight, blockLogicalHeight, blockLogicalHeight);
-            trailingFloatsLineBox->setPaginatedLineWidth(availableLogicalWidthForContent(blockLogicalHeight));
+            trailingFloatsLineBox->setPaginatedLineWidth(availableLogicalWidthForContent());
             LayoutRect logicalLayoutOverflow(0, blockLogicalHeight, 1, bottomLayoutOverflow - blockLogicalHeight);
             LayoutRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight);
             trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom());
-            if (layoutState.flowThread())
-                updateRegionForLine(trailingFloatsLineBox);
         }
 
         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
@@ -1697,7 +1477,7 @@
     for (size_t i = 0; i < floatCount; ++i) {
         if (!floats[i].everHadLayout) {
             RenderBox* f = floats[i].object;
-            if (!f->x() && !f->y() && f->checkForRepaintDuringLayout()) {
+            if (!f->x() && !f->y() && f->checkForRepaint()) {
                 if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
                     f->setShouldDoFullRepaintAfterLayout(true);
                 else
@@ -1707,18 +1487,8 @@
     }
 }
 
-void RenderBlockFlow::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
+void RenderBlockFlow::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom, LayoutUnit afterEdge)
 {
-    FastTextAutosizer* textAutosizer = document().fastTextAutosizer();
-    if (textAutosizer)
-        textAutosizer->inflate(this);
-
-    setLogicalHeight(borderBefore() + paddingBefore());
-
-    // Lay out our hypothetical grid line as though it occurs at the top of the block.
-    if (view()->layoutState() && view()->layoutState()->lineGrid() == this)
-        layoutLineGridBox();
-
     RenderFlowThread* flowThread = flowThreadContainingBlock();
     bool clearLinesForPagination = firstLineBox() && flowThread && !flowThread->hasRegions();
 
@@ -1752,25 +1522,19 @@
         // the replaced elements later. In partial layout mode, line boxes are not
         // deleted and only dirtied. In that case, we can layout the replaced
         // elements at the same time.
-        bool hasInlineChild = false;
         Vector<RenderBox*> replacedChildren;
         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
             RenderObject* o = walker.current();
 
             LayoutRectRecorder recorder(*o, !o->isText());
 
-            if (!hasInlineChild && o->isInline())
-                hasInlineChild = true;
+            if (!layoutState.hasInlineChild() && o->isInline())
+                layoutState.setHasInlineChild(true);
 
             if (o->isReplaced() || o->isFloating() || o->isOutOfFlowPositioned()) {
                 RenderBox* box = toRenderBox(o);
 
-                if (relayoutChildren || box->hasRelativeDimensions())
-                    o->setChildNeedsLayout(MarkOnlyThis);
-
-                // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
-                if (relayoutChildren && box->needsPreferredWidthsRecalculation())
-                    o->setPreferredLogicalWidthsDirty(MarkOnlyThis);
+                updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, box);
 
                 if (o->isOutOfFlowPositioned())
                     o->containingBlock()->insertPositionedObject(box);
@@ -1796,7 +1560,7 @@
         for (size_t i = 0; i < replacedChildren.size(); i++)
             replacedChildren[i]->layoutIfNeeded();
 
-        layoutRunsAndFloats(layoutState, hasInlineChild);
+        layoutRunsAndFloats(layoutState);
     }
 
     // Expand the last line to accommodate Ruby and emphasis marks.
@@ -1810,7 +1574,7 @@
     }
 
     // Now add in the bottom border/padding.
-    setLogicalHeight(logicalHeight() + lastLineAnnotationsAdjustment + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
+    setLogicalHeight(logicalHeight() + lastLineAnnotationsAdjustment + afterEdge);
 
     if (!firstLineBox() && hasLineIfEmpty())
         setLogicalHeight(logicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
@@ -1865,10 +1629,6 @@
         size_t floatIndex = 0;
         for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) {
             if (paginated) {
-                if (lineWidthForPaginatedLineChanged(curr, 0, layoutState.flowThread())) {
-                    curr->markDirty();
-                    break;
-                }
                 paginationDelta -= curr->paginationStrut();
                 adjustLinePositionForPagination(curr, paginationDelta, layoutState.flowThread());
                 if (paginationDelta) {
@@ -1881,8 +1641,6 @@
                     layoutState.updateRepaintRangeFromBox(curr, paginationDelta);
                     curr->adjustBlockDirectionPosition(paginationDelta);
                 }
-                if (layoutState.flowThread())
-                    updateRegionForLine(curr);
             }
 
             // If a new float has been inserted before this line or before its last known float, just do a full layout.
@@ -1900,6 +1658,13 @@
     }
 
     if (layoutState.isFullLayout()) {
+        // If we encountered a new float and have inline children, mark ourself to force us to repaint.
+        if (layoutState.hasInlineChild() && !selfNeedsLayout()) {
+            setNeedsLayout(MarkOnlyThis);
+            if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+                setShouldDoFullRepaintAfterLayout(true);
+        }
+
         // FIXME: This should just call deleteLineBoxTree, but that causes
         // crashes for fast/repaint tests.
         curr = firstRootBox();
@@ -2028,8 +1793,6 @@
                 adjustLinePositionForPagination(lineBox, lineDelta, layoutState.flowThread());
                 lineBox->setPaginationStrut(oldPaginationStrut);
             }
-            if (lineWidthForPaginatedLineChanged(lineBox, lineDelta, layoutState.flowThread()))
-                return false;
         }
     }
 
@@ -2070,7 +1833,7 @@
     RootInlineBox* originalEndLine = layoutState.endLine();
     RootInlineBox* line = originalEndLine;
     for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
-        if (line->lineBreakObj() == resolver.position().object() && line->lineBreakPos() == resolver.position().m_pos) {
+        if (line->lineBreakObj() == resolver.position().object() && line->lineBreakPos() == resolver.position().offset()) {
             // We have a match.
             if (line->lineBreakBidiStatus() != resolver.status())
                 return false; // ...but the bidi state doesn't match.
@@ -2105,139 +1868,6 @@
     return !it.atEnd();
 }
 
-void LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo& lineInfo,
-                                                     FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
-{
-    while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) {
-        RenderObject* object = resolver.position().object();
-        if (object->isOutOfFlowPositioned()) {
-            setStaticPositions(m_block, toRenderBox(object));
-            if (object->style()->isOriginalDisplayInlineType()) {
-                resolver.runs().addRun(createRun(0, 1, object, resolver));
-                lineInfo.incrementRunsFromLeadingWhitespace();
-            }
-        } else if (object->isFloating())
-            m_block->positionNewFloatOnLine(m_block->insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, lineInfo, width);
-        else if (object->isText() && object->style()->hasTextCombine() && object->isCombineText() && !toRenderCombineText(object)->isCombined()) {
-            toRenderCombineText(object)->combineText();
-            if (toRenderCombineText(object)->isCombined())
-                continue;
-        }
-        resolver.position().increment(&resolver);
-    }
-    resolver.commitExplicitEmbedding();
-}
-
-void LineBreaker::reset()
-{
-    m_positionedObjects.clear();
-    m_hyphenated = false;
-    m_clear = CNONE;
-}
-
-InlineIterator LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
-{
-    ShapeInsideInfo* shapeInsideInfo = m_block->layoutShapeInsideInfo();
-
-    if (!shapeInsideInfo || !shapeInsideInfo->lineOverlapsShapeBounds())
-        return nextSegmentBreak(resolver, lineInfo, renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
-
-    InlineIterator end = resolver.position();
-    InlineIterator oldEnd = end;
-
-    if (!shapeInsideInfo->hasSegments()) {
-        end = nextSegmentBreak(resolver, lineInfo, renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
-        resolver.setPositionIgnoringNestedIsolates(oldEnd);
-        return oldEnd;
-    }
-
-    const SegmentList& segments = shapeInsideInfo->segments();
-    SegmentRangeList& segmentRanges = shapeInsideInfo->segmentRanges();
-
-    for (unsigned i = 0; i < segments.size() && !end.atEnd(); i++) {
-        const InlineIterator segmentStart = resolver.position();
-        end = nextSegmentBreak(resolver, lineInfo, renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
-
-        ASSERT(segmentRanges.size() == i);
-        if (resolver.position().atEnd()) {
-            segmentRanges.append(LineSegmentRange(segmentStart, end));
-            break;
-        }
-        if (resolver.position() == end) {
-            // Nothing fit this segment
-            end = segmentStart;
-            segmentRanges.append(LineSegmentRange(segmentStart, segmentStart));
-            resolver.setPositionIgnoringNestedIsolates(segmentStart);
-        } else {
-            // Note that resolver.position is already skipping some of the white space at the beginning of the line,
-            // so that's why segmentStart might be different than resolver.position().
-            LineSegmentRange range(resolver.position(), end);
-            segmentRanges.append(range);
-            resolver.setPosition(end, numberOfIsolateAncestors(end));
-
-            if (lineInfo.previousLineBrokeCleanly()) {
-                // If we hit a new line break, just stop adding anything to this line.
-                break;
-            }
-        }
-    }
-    resolver.setPositionIgnoringNestedIsolates(oldEnd);
-    return end;
-}
-
-InlineIterator LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
-{
-    reset();
-
-    ASSERT(resolver.position().root() == m_block);
-
-    bool appliedStartWidth = resolver.position().m_pos > 0;
-
-    LineWidth width(*m_block, lineInfo.isFirstLine(), requiresIndent(lineInfo.isFirstLine(), lineInfo.previousLineBrokeCleanly(), m_block->style()));
-
-    skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width);
-
-    if (resolver.position().atEnd())
-        return resolver.position();
-
-    BreakingContext context(resolver, lineInfo, width, renderTextInfo, lastFloatFromPreviousLine, appliedStartWidth, m_block);
-
-    while (context.currentObject()) {
-        context.initializeForCurrentObject();
-        if (context.currentObject()->isBR()) {
-            context.handleBR(m_clear);
-        } else if (context.currentObject()->isOutOfFlowPositioned()) {
-            context.handleOutOfFlowPositioned(m_positionedObjects);
-        } else if (context.currentObject()->isFloating()) {
-            context.handleFloat();
-        } else if (context.currentObject()->isRenderInline()) {
-            context.handleEmptyInline();
-        } else if (context.currentObject()->isReplaced()) {
-            context.handleReplaced();
-        } else if (context.currentObject()->isText()) {
-            if (context.handleText(wordMeasurements, m_hyphenated)) {
-                // We've hit a hard text line break. Our line break iterator is updated, so go ahead and early return.
-                return context.lineBreak();
-            }
-        } else {
-            ASSERT_NOT_REACHED();
-        }
-
-        if (context.atEnd())
-            return context.handleEndOfLine();
-
-        context.commitAndUpdateLineBreakIfNeeded();
-
-        if (context.atEnd())
-            return context.handleEndOfLine();
-
-        context.increment();
-    }
-
-    context.clearLineBreakIfFitsOnLine();
-
-    return context.handleEndOfLine();
-}
 
 void RenderBlockFlow::addOverflowFromInlineChildren()
 {
@@ -2283,8 +1913,10 @@
     const Font& font = style()->font();
     DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1));
     const Font& firstLineFont = firstLineStyle()->font();
-    int firstLineEllipsisWidth = firstLineFont.width(constructTextRun(this, firstLineFont, &horizontalEllipsis, 1, firstLineStyle()));
-    int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(constructTextRun(this, font, &horizontalEllipsis, 1, style()));
+    // FIXME: We should probably not hard-code the direction here. https://crbug.com/333004
+    TextDirection ellipsisDirection = LTR;
+    int firstLineEllipsisWidth = firstLineFont.width(constructTextRun(this, firstLineFont, &horizontalEllipsis, 1, firstLineStyle(), ellipsisDirection));
+    int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(constructTextRun(this, font, &horizontalEllipsis, 1, style(), ellipsisDirection));
 
     // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
     // if the right edge of a line box exceeds that.  For RTL, we use the left edge of the padding box and
@@ -2296,9 +1928,10 @@
     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
         // FIXME: Use pixelSnappedLogicalRightOffsetForLine instead of snapping it ourselves once the column workaround in said method has been fixed.
         // https://bugs.webkit.org/show_bug.cgi?id=105461
-        int blockRightEdge = snapSizeToPixel(logicalRightOffsetForLine(curr->lineTop(), firstLine), curr->x());
+        float currLogicalLeft = curr->logicalLeft();
+        int blockRightEdge = snapSizeToPixel(logicalRightOffsetForLine(curr->lineTop(), firstLine), currLogicalLeft);
         int blockLeftEdge = pixelSnappedLogicalLeftOffsetForLine(curr->lineTop(), firstLine);
-        int lineBoxEdge = ltr ? snapSizeToPixel(curr->x() + curr->logicalWidth(), curr->x()) : snapSizeToPixel(curr->x(), 0);
+        int lineBoxEdge = ltr ? snapSizeToPixel(currLogicalLeft + curr->logicalWidth(), currLogicalLeft) : snapSizeToPixel(currLogicalLeft, 0);
         if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
             // This line spills out of our box in the appropriate direction.  Now we need to see if the line
             // can be truncated.  In order for truncation to be possible, the line must have sufficient space to
@@ -2311,12 +1944,13 @@
                 float totalLogicalWidth = curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
 
                 float logicalLeft = 0; // We are only intersted in the delta from the base position.
-                float truncatedWidth = pixelSnappedLogicalRightOffsetForLine(curr->lineTop(), firstLine);
-                updateLogicalWidthForAlignment(textAlign, curr, 0, logicalLeft, totalLogicalWidth, truncatedWidth, 0);
+                float snappedLogicalLeft = pixelSnappedLogicalLeftOffsetForLine(curr->lineTop(), firstLine);
+                float availableLogicalWidth = pixelSnappedLogicalRightOffsetForLine(curr->lineTop(), firstLine) - snappedLogicalLeft;
+                updateLogicalWidthForAlignment(textAlign, curr, 0, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
                 if (ltr)
                     curr->adjustLogicalPosition(logicalLeft, 0);
                 else
-                    curr->adjustLogicalPosition(-(truncatedWidth - (logicalLeft + totalLogicalWidth)), 0);
+                    curr->adjustLogicalPosition(logicalLeft - (availableLogicalWidth - totalLogicalWidth), 0);
             }
         }
         firstLine = false;
@@ -2394,27 +2028,4 @@
     return logicalLeft;
 }
 
-void RenderBlockFlow::layoutLineGridBox()
-{
-    if (style()->lineGrid() == RenderStyle::initialLineGrid()) {
-        setLineGridBox(0);
-        return;
-    }
-
-    setLineGridBox(0);
-
-    RootInlineBox* lineGridBox = new RootInlineBox(this);
-    lineGridBox->setHasTextChildren(); // Needed to make the line ascent/descent actually be honored in quirks mode.
-    lineGridBox->setConstructed();
-    GlyphOverflowAndFallbackFontsMap textBoxDataMap;
-    VerticalPositionCache verticalPositionCache;
-    lineGridBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache);
-
-    setLineGridBox(lineGridBox);
-
-    // FIXME: If any of the characteristics of the box change compared to the old one, then we need to do a deep dirtying
-    // (similar to what happens when the page height changes). Ideally, though, we only do this if someone is actually snapping
-    // to this grid.
-}
-
 }
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index 87f875e..aee4dcc 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -34,8 +34,6 @@
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/html/HTMLFrameOwnerElement.h"
-#include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLTextAreaElement.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/AutoscrollController.h"
@@ -44,19 +42,18 @@
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderBoxRegionInfo.h"
+#include "core/rendering/RenderDeprecatedFlexibleBox.h"
 #include "core/rendering/RenderFlexibleBox.h"
-#include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderGrid.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderListMarker.h"
-#include "core/rendering/RenderRegion.h"
 #include "core/rendering/RenderTableCell.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
+#include "platform/LengthFunctions.h"
 #include "platform/geometry/FloatQuad.h"
 #include "platform/geometry/TransformState.h"
 #include "platform/graphics/GraphicsContextStateSaver.h"
@@ -69,10 +66,9 @@
 
 // Used by flexible boxes when flexing this element and by table cells.
 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
-static OverrideSizeMap* gOverrideHeightMap = 0;
-static OverrideSizeMap* gOverrideWidthMap = 0;
 
 // Used by grid elements to properly size their grid items.
+// FIXME: Move these into RenderBoxRareData.
 static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = 0;
 static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = 0;
 
@@ -95,64 +91,13 @@
 
 RenderBox::RenderBox(ContainerNode* node)
     : RenderBoxModelObject(node)
+    , m_intrinsicContentLogicalHeight(-1)
     , m_minPreferredLogicalWidth(-1)
     , m_maxPreferredLogicalWidth(-1)
-    , m_intrinsicContentLogicalHeight(-1)
-    , m_inlineBoxWrapper(0)
 {
     setIsBox();
 }
 
-RenderBox::~RenderBox()
-{
-}
-
-LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
-{
-    if (!region)
-        return borderBoxRect();
-
-    // Compute the logical width and placement in this region.
-    RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, cacheFlag);
-    if (!boxInfo)
-        return borderBoxRect();
-
-    // We have cached insets.
-    LayoutUnit logicalWidth = boxInfo->logicalWidth();
-    LayoutUnit logicalLeft = boxInfo->logicalLeft();
-
-    // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts.
-    // FIXME: Doesn't work right with perpendicular writing modes.
-    const RenderBlock* currentBox = containingBlock();
-    RenderBoxRegionInfo* currentBoxInfo = currentBox->renderBoxRegionInfo(region);
-    while (currentBoxInfo && currentBoxInfo->isShifted()) {
-        if (currentBox->style()->direction() == LTR)
-            logicalLeft += currentBoxInfo->logicalLeft();
-        else
-            logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft();
-        currentBox = currentBox->containingBlock();
-        region = currentBox->clampToStartAndEndRegions(region);
-        currentBoxInfo = currentBox->renderBoxRegionInfo(region);
-    }
-
-    if (cacheFlag == DoNotCacheRenderBoxRegionInfo)
-        delete boxInfo;
-
-    if (isHorizontalWritingMode())
-        return LayoutRect(logicalLeft, 0, logicalWidth, height());
-    return LayoutRect(0, logicalLeft, width(), logicalWidth);
-}
-
-void RenderBox::clearRenderBoxRegionInfo()
-{
-    if (isRenderFlowThread())
-        return;
-
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (flowThread)
-        flowThread->removeRenderBoxRegionInfo(this);
-}
-
 void RenderBox::willBeDestroyed()
 {
     clearOverrideSize();
@@ -199,7 +144,7 @@
         // The background of the root element or the body element could propagate up to
         // the canvas.  Just dirty the entire canvas when our style changes substantially.
         if (diff >= StyleDifferenceRepaint && node() &&
-            (isHTMLHtmlElement(node()) || node()->hasTagName(bodyTag))) {
+            (node()->hasTagName(htmlTag) || node()->hasTagName(bodyTag))) {
             view()->repaint();
 
             if (oldStyle->hasEntirelyFixedBackground() != newStyle->hasEntirelyFixedBackground())
@@ -333,33 +278,19 @@
 
     setFloating(!isOutOfFlowPositioned() && styleToUse->isFloating());
 
-    // We also handle <body> and <html>, whose overflow applies to the viewport.
-    if (styleToUse->overflowX() != OVISIBLE && !isRootObject && isRenderBlock()) {
-        bool boxHasOverflowClip = true;
-        if (isBody()) {
-            // Overflow on the body can propagate to the viewport under the following conditions.
-            // (1) The root element is <html>.
-            // (2) We are the primary <body> (can be checked by looking at document.body).
-            // (3) The root element has visible overflow.
-            if (isHTMLHtmlElement(document().documentElement())
-                && document().body() == node()
-                && document().documentElement()->renderer()->style()->overflowX() == OVISIBLE)
-                boxHasOverflowClip = false;
-        }
-
-        // Check for overflow clip.
-        // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
-        if (boxHasOverflowClip) {
-            // If we are getting an overflow clip, preemptively erase any overflowing content.
-            // FIXME: This should probably consult RenderOverflow.
-            if (!hasOverflowClip())
+    bool boxHasOverflowClip = false;
+    if (!styleToUse->isOverflowVisible() && isRenderBlock() && !isViewObject) {
+        // If overflow has been propagated to the viewport, it has no effect here.
+        if (node() != document().viewportDefiningElement()) {
+            boxHasOverflowClip = true;
+            if (!hasOverflowClip()) {
+                // If we are getting an overflow clip, preemptively erase any overflowing content.
+                // FIXME: This should probably consult RenderOverflow.
                 repaint();
-
-            setHasOverflowClip(true);
+            }
         }
-    } else {
-        setHasOverflowClip(false);
     }
+    setHasOverflowClip(boxHasOverflowClip);
 
     setHasTransform(styleToUse->hasTransformRelatedProperty());
     setHasReflection(styleToUse->boxReflect());
@@ -608,12 +539,12 @@
         layer()->updateTransform();
 }
 
-LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb, RenderRegion* region) const
+LayoutUnit RenderBox::constrainLogicalWidthByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb) const
 {
     RenderStyle* styleToUse = style();
     if (!styleToUse->logicalMaxWidth().isUndefined())
-        logicalWidth = min(logicalWidth, computeLogicalWidthInRegionUsing(MaxSize, styleToUse->logicalMaxWidth(), availableWidth, cb, region));
-    return max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse->logicalMinWidth(), availableWidth, cb, region));
+        logicalWidth = min(logicalWidth, computeLogicalWidthUsing(MaxSize, styleToUse->logicalMaxWidth(), availableWidth, cb));
+    return max(logicalWidth, computeLogicalWidthUsing(MinSize, styleToUse->logicalMinWidth(), availableWidth, cb));
 }
 
 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
@@ -668,9 +599,11 @@
         box = containerRelativeQuad.enclosingBoundingBox();
     }
 
-    // FIXME: layoutDelta needs to be applied in parts before/after transforms and
-    // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
-    box.move(view()->layoutDelta());
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+        // FIXME: layoutDelta needs to be applied in parts before/after transforms and
+        // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
+        box.move(view()->layoutDelta());
+    }
 
     return box;
 }
@@ -729,10 +662,9 @@
 {
     if (!style()->boxReflect())
         return 0;
-    RenderView* renderView = view();
     if (style()->boxReflect()->direction() == ReflectionLeft || style()->boxReflect()->direction() == ReflectionRight)
-        return valueForLength(style()->boxReflect()->offset(), borderBoxRect().width(), renderView);
-    return valueForLength(style()->boxReflect()->offset(), borderBoxRect().height(), renderView);
+        return valueForLength(style()->boxReflect()->offset(), borderBoxRect().width());
+    return valueForLength(style()->boxReflect()->offset(), borderBoxRect().height());
 }
 
 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
@@ -793,12 +725,15 @@
     return 0;
 }
 
-bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
+bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float delta)
 {
+    // Logical scroll is a higher level concept, all directions by here must be physical
+    ASSERT(!isLogical(direction));
+
     if (!layer() || !layer()->scrollableArea())
         return false;
 
-    return layer()->scrollableArea()->scroll(direction, granularity, multiplier);
+    return layer()->scrollableArea()->scroll(direction, granularity, delta);
 }
 
 bool RenderBox::canBeScrolledAndHasScrollableArea() const
@@ -997,17 +932,21 @@
 
 void RenderBox::applyCachedClipAndScrollOffsetForRepaint(LayoutRect& paintRect) const
 {
+    flipForWritingMode(paintRect);
     paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
 
     // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
-    if (usesCompositedScrolling())
+    if (usesCompositedScrolling()) {
+        flipForWritingMode(paintRect);
         return;
+    }
 
     // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
     // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
     // anyway if its size does change.
     LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
     paintRect = intersection(paintRect, clipRect);
+    flipForWritingMode(paintRect);
 }
 
 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
@@ -1042,38 +981,36 @@
 
 bool RenderBox::hasOverrideHeight() const
 {
-    return gOverrideHeightMap && gOverrideHeightMap->contains(this);
+    return m_rareData && m_rareData->m_overrideLogicalContentHeight != -1;
 }
 
 bool RenderBox::hasOverrideWidth() const
 {
-    return gOverrideWidthMap && gOverrideWidthMap->contains(this);
+    return m_rareData && m_rareData->m_overrideLogicalContentWidth != -1;
 }
 
 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
 {
-    if (!gOverrideHeightMap)
-        gOverrideHeightMap = new OverrideSizeMap();
-    gOverrideHeightMap->set(this, height);
+    ASSERT(height >= 0);
+    ensureRareData().m_overrideLogicalContentHeight = height;
 }
 
 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
 {
-    if (!gOverrideWidthMap)
-        gOverrideWidthMap = new OverrideSizeMap();
-    gOverrideWidthMap->set(this, width);
+    ASSERT(width >= 0);
+    ensureRareData().m_overrideLogicalContentWidth = width;
 }
 
 void RenderBox::clearOverrideLogicalContentHeight()
 {
-    if (gOverrideHeightMap)
-        gOverrideHeightMap->remove(this);
+    if (m_rareData)
+        m_rareData->m_overrideLogicalContentHeight = -1;
 }
 
 void RenderBox::clearOverrideLogicalContentWidth()
 {
-    if (gOverrideWidthMap)
-        gOverrideWidthMap->remove(this);
+    if (m_rareData)
+        m_rareData->m_overrideLogicalContentWidth = -1;
 }
 
 void RenderBox::clearOverrideSize()
@@ -1085,13 +1022,13 @@
 LayoutUnit RenderBox::overrideLogicalContentWidth() const
 {
     ASSERT(hasOverrideWidth());
-    return gOverrideWidthMap->get(this);
+    return m_rareData->m_overrideLogicalContentWidth;
 }
 
 LayoutUnit RenderBox::overrideLogicalContentHeight() const
 {
     ASSERT(hasOverrideHeight());
-    return gOverrideHeightMap->get(this);
+    return m_rareData->m_overrideLogicalContentHeight;
 }
 
 LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const
@@ -1188,7 +1125,7 @@
 
     // Check our bounds next. For this purpose always assume that we can only be hit in the
     // foreground phase (which is true for replaced elements like images).
-    LayoutRect boundsRect = borderBoxRectInRegion(locationInContainer.region());
+    LayoutRect boundsRect = borderBoxRect();
     boundsRect.moveBy(adjustedLocation);
     if (visibleToHitTestRequest(request) && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
         updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
@@ -1264,7 +1201,7 @@
     if (!paintInfo.shouldPaintWithinRoot(this))
         return;
 
-    LayoutRect paintRect = borderBoxRectInRegion(paintInfo.renderRegion);
+    LayoutRect paintRect = borderBoxRect();
     paintRect.moveBy(paintOffset);
     paintBoxDecorationsWithRect(paintInfo, paintOffset, paintRect);
 }
@@ -1283,7 +1220,7 @@
         // To avoid the background color bleeding out behind the border, we'll render background and border
         // into a transparency layer, and then clip that in one go (which requires setting up the clip before
         // beginning the layer).
-        RoundedRect border = style()->getRoundedBorderFor(paintRect, view());
+        RoundedRect border = style()->getRoundedBorderFor(paintRect);
         stateSaver.save();
         paintInfo.context->clipRoundedRect(border);
         paintInfo.context->beginTransparencyLayer(1);
@@ -1336,7 +1273,7 @@
     LayoutRect backgroundRect = pixelSnappedIntRect(borderBoxRect());
 
     Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
-    if (backgroundColor.isValid() && backgroundColor.alpha())
+    if (backgroundColor.alpha())
         return backgroundRect;
     if (!style()->backgroundLayers()->image() || style()->backgroundLayers()->next())
         return backgroundRect;
@@ -1351,7 +1288,7 @@
         return false;
 
     Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
-    if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
+    if (backgroundColor.hasAlpha())
         return false;
 
     // If the element has appearance, it might be painted by theme.
@@ -1472,7 +1409,7 @@
     // If there is only one layer and no image, check whether the background color is opaque
     if (!fillLayer->next() && !fillLayer->hasImage()) {
         Color bgColor = resolveColor(CSSPropertyBackgroundColor);
-        if (bgColor.isValid() && bgColor.alpha() == 255)
+        if (bgColor.alpha() == 255)
             return true;
     }
 
@@ -1532,7 +1469,7 @@
     }
 
     if (allMaskImagesLoaded) {
-        paintFillLayers(paintInfo, Color(), style()->maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
+        paintFillLayers(paintInfo, Color::transparent, style()->maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
         paintNinePieceImage(paintInfo.context, paintRect, style(), style()->maskBoxImage(), compositeOp);
     }
 
@@ -1629,11 +1566,16 @@
         return;
     }
 
+    ShapeValue* shapeOutsideValue = style()->shapeOutside();
+    if (!frameView()->isInPerformLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
+        ShapeOutsideInfo::ensureInfo(this)->dirtyShapeSize();
+        markShapeOutsideDependentsForLayout();
+    }
+
     bool didFullRepaint = repaintLayerRectsForImage(image, style()->backgroundLayers(), true);
     if (!didFullRepaint)
         repaintLayerRectsForImage(image, style()->maskLayers(), false);
 
-
     if (hasLayer() && layer()->hasCompositedMask() && layersUseImage(image, style()->maskLayers()))
         layer()->contentChanged(MaskImageChanged);
 }
@@ -1693,7 +1635,7 @@
     if (!isControlClip && !isOverflowClip)
         return false;
 
-    LayoutRect clipRect = isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, paintInfo.renderRegion);
+    LayoutRect clipRect = isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset);
     RoundedRect clipRoundedRect(0, 0, 0, 0);
     bool hasBorderRadius = style()->hasBorderRadius();
     if (hasBorderRadius)
@@ -1746,11 +1688,11 @@
         paintInfo.phase = originalPhase;
 }
 
-LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy)
+LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, OverlayScrollbarSizeRelevancy relevancy)
 {
     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
     // here.
-    LayoutRect clipRect = borderBoxRectInRegion(region);
+    LayoutRect clipRect = borderBoxRect();
     clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
     clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
 
@@ -1765,47 +1707,36 @@
     return clipRect;
 }
 
-LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
+LayoutRect RenderBox::clipRect(const LayoutPoint& location)
 {
-    LayoutRect borderBoxRect = borderBoxRectInRegion(region);
+    LayoutRect borderBoxRect = this->borderBoxRect();
     LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
-    RenderView* renderView = view();
 
     if (!style()->clipLeft().isAuto()) {
-        LayoutUnit c = valueForLength(style()->clipLeft(), borderBoxRect.width(), renderView);
+        LayoutUnit c = valueForLength(style()->clipLeft(), borderBoxRect.width());
         clipRect.move(c, 0);
         clipRect.contract(c, 0);
     }
 
-    // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
-    // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
-
     if (!style()->clipRight().isAuto())
-        clipRect.contract(width() - valueForLength(style()->clipRight(), width(), renderView), 0);
+        clipRect.contract(width() - valueForLength(style()->clipRight(), width()), 0);
 
     if (!style()->clipTop().isAuto()) {
-        LayoutUnit c = valueForLength(style()->clipTop(), borderBoxRect.height(), renderView);
+        LayoutUnit c = valueForLength(style()->clipTop(), borderBoxRect.height());
         clipRect.move(0, c);
         clipRect.contract(0, c);
     }
 
     if (!style()->clipBottom().isAuto())
-        clipRect.contract(0, height() - valueForLength(style()->clipBottom(), height(), renderView));
+        clipRect.contract(0, height() - valueForLength(style()->clipBottom(), height()));
 
     return clipRect;
 }
 
-LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb, RenderRegion* region) const
+LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb) const
 {
-    RenderRegion* containingBlockRegion = 0;
     LayoutUnit logicalTopPosition = logicalTop();
-    if (region) {
-        LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
-        logicalTopPosition = max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
-        containingBlockRegion = cb->clampToStartAndEndRegions(region);
-    }
-
-    LayoutUnit result = cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion) - childMarginStart - childMarginEnd;
+    LayoutUnit result = cb->availableLogicalWidthForLine(logicalTopPosition, false) - childMarginStart - childMarginEnd;
 
     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
@@ -1813,9 +1744,9 @@
     // doesn't fit, we can use the line offset, but we need to grow it by the margin to reflect the fact that the margin was
     // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
     if (childMarginStart > 0) {
-        LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion);
+        LayoutUnit startContentSide = cb->startOffsetForContent();
         LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
-        LayoutUnit startOffset = cb->startOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion);
+        LayoutUnit startOffset = cb->startOffsetForLine(logicalTopPosition, false);
         if (startOffset > startContentSideWithMargin)
             result += childMarginStart;
         else
@@ -1823,9 +1754,9 @@
     }
 
     if (childMarginEnd > 0) {
-        LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion);
+        LayoutUnit endContentSide = cb->endOffsetForContent();
         LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
-        LayoutUnit endOffset = cb->endOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion);
+        LayoutUnit endOffset = cb->endOffsetForLine(logicalTopPosition, false);
         if (endOffset > endContentSideWithMargin)
             result += childMarginEnd;
         else
@@ -1853,33 +1784,12 @@
     return cb->availableLogicalHeight(heightType);
 }
 
-LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
-{
-    if (!region)
-        return containingBlockLogicalWidthForContent();
-
-    RenderBlock* cb = containingBlock();
-    RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
-    // FIXME: It's unclear if a region's content should use the containing block's override logical width.
-    // If it should, the following line should call containingBlockLogicalWidthForContent.
-    LayoutUnit result = cb->availableLogicalWidth();
-    RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
-    if (!boxInfo)
-        return result;
-    return max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
-}
-
-LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
+LayoutUnit RenderBox::containingBlockAvailableLineWidth() const
 {
     RenderBlock* cb = containingBlock();
-    RenderRegion* containingBlockRegion = 0;
-    LayoutUnit logicalTopPosition = logicalTop();
-    if (region) {
-        LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
-        logicalTopPosition = max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
-        containingBlockRegion = cb->clampToStartAndEndRegions(region);
-    }
-    return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
+    if (cb->isRenderBlockFlow())
+        return toRenderBlockFlow(cb)->availableLogicalWidthForLine(logicalTop(), false, availableLogicalHeight(IncludeMarginBorderPadding));
+    return 0;
 }
 
 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
@@ -1980,11 +1890,7 @@
 
 LayoutSize RenderBox::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
 {
-    // A region "has" boxes inside it without being their container.
-    // FIXME: change container() / containingBlock() to count for boxes being positioned relative to the region, not the
-    // FlowThread. This requires a separate patch as a simple test with such a change in container() causes 129 out of
-    // 337 regions tests to fail.
-    ASSERT(o == container() || o->isRenderRegion());
+    ASSERT(o == container());
 
     LayoutSize offset;
     if (isInFlowPositioned())
@@ -2026,12 +1932,14 @@
 
 void RenderBox::dirtyLineBoxes(bool fullLayout)
 {
-    if (m_inlineBoxWrapper) {
+    if (inlineBoxWrapper()) {
         if (fullLayout) {
-            m_inlineBoxWrapper->destroy();
-            m_inlineBoxWrapper = 0;
-        } else
-            m_inlineBoxWrapper->dirtyLineBoxes();
+            inlineBoxWrapper()->destroy();
+            ASSERT(m_rareData);
+            m_rareData->m_inlineBoxWrapper = 0;
+        } else {
+            inlineBoxWrapper()->dirtyLineBoxes();
+        }
     }
 }
 
@@ -2069,11 +1977,12 @@
 
 void RenderBox::deleteLineBoxWrapper()
 {
-    if (m_inlineBoxWrapper) {
+    if (inlineBoxWrapper()) {
         if (!documentBeingDestroyed())
-            m_inlineBoxWrapper->remove();
-        m_inlineBoxWrapper->destroy();
-        m_inlineBoxWrapper = 0;
+            inlineBoxWrapper()->remove();
+        inlineBoxWrapper()->destroy();
+        ASSERT(m_rareData);
+        m_rareData->m_inlineBoxWrapper = 0;
     }
 }
 
@@ -2085,7 +1994,7 @@
     LayoutRect r = visualOverflowRect();
 
     RenderView* v = view();
-    if (v) {
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && v) {
         // FIXME: layoutDelta needs to be applied in parts before/after transforms and
         // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
         r.move(v->layoutDelta());
@@ -2226,7 +2135,7 @@
 void RenderBox::updateLogicalWidth()
 {
     LogicalExtentComputedValues computedValues;
-    computeLogicalWidthInRegion(computedValues);
+    computeLogicalWidth(computedValues);
 
     setLogicalWidth(computedValues.m_extent);
     setLogicalLeft(computedValues.m_position);
@@ -2266,7 +2175,7 @@
     return maxWidth;
 }
 
-void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
+void RenderBox::computeLogicalWidth(LogicalExtentComputedValues& computedValues) const
 {
     computedValues.m_extent = logicalWidth();
     computedValues.m_position = logicalLeft();
@@ -2276,7 +2185,7 @@
     if (isOutOfFlowPositioned()) {
         // FIXME: This calculation is not patched for block-flow yet.
         // https://bugs.webkit.org/show_bug.cgi?id=46500
-        computePositionedLogicalWidth(computedValues, region);
+        computePositionedLogicalWidth(computedValues);
         return;
     }
 
@@ -2303,16 +2212,15 @@
     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse->logicalWidth();
 
     RenderBlock* cb = containingBlock();
-    LayoutUnit containerLogicalWidth = max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
+    LayoutUnit containerLogicalWidth = max<LayoutUnit>(0, containingBlockLogicalWidthForContent());
     bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
 
     if (isInline() && !isInlineBlockOrInlineTable()) {
         // just calculate margins
-        RenderView* renderView = view();
-        computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth, renderView);
-        computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth, renderView);
+        computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth);
+        computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth);
         if (treatAsReplaced)
-            computedValues.m_extent = max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
+            computedValues.m_extent = max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
         return;
     }
 
@@ -2323,19 +2231,18 @@
         LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
         if (hasPerpendicularContainingBlock)
             containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
-        LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse->logicalWidth(), containerWidthInInlineDirection, cb, region);
-        computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
+        LayoutUnit preferredWidth = computeLogicalWidthUsing(MainOrPreferredSize, styleToUse->logicalWidth(), containerWidthInInlineDirection, cb);
+        computedValues.m_extent = constrainLogicalWidthByMinMax(preferredWidth, containerWidthInInlineDirection, cb);
     }
 
     // Margin calculations.
     if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
-        RenderView* renderView = view();
-        computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth, renderView);
-        computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth, renderView);
+        computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth);
+        computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth);
     } else {
         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
         if (avoidsFloats() && cb->containsFloats())
-            containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
+            containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidth();
         bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
@@ -2375,9 +2282,8 @@
 
 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
 {
-    RenderView* renderView = view();
-    marginStart = minimumValueForLength(style()->marginStart(), availableLogicalWidth, renderView);
-    marginEnd = minimumValueForLength(style()->marginEnd(), availableLogicalWidth, renderView);
+    marginStart = minimumValueForLength(style()->marginStart(), availableLogicalWidth);
+    marginEnd = minimumValueForLength(style()->marginEnd(), availableLogicalWidth);
     return availableLogicalWidth - marginStart - marginEnd;
 }
 
@@ -2406,12 +2312,11 @@
     return 0;
 }
 
-LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
-    const RenderBlock* cb, RenderRegion* region) const
+LayoutUnit RenderBox::computeLogicalWidthUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* cb) const
 {
     if (!logicalWidth.isIntrinsicOrAuto()) {
         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
-        return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth, view()));
+        return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
     }
 
     if (logicalWidth.isIntrinsic())
@@ -2422,7 +2327,7 @@
     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
 
     if (shrinkToAvoidFloats() && cb->containsFloats())
-        logicalWidthResult = min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb), region));
+        logicalWidthResult = min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb)));
 
     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
         return max(minPreferredLogicalWidth(), min(maxPreferredLogicalWidth(), logicalWidthResult));
@@ -2437,7 +2342,7 @@
     ASSERT(parent->style()->isColumnFlexDirection());
     if (flexitem->style()->marginStart().isAuto() || flexitem->style()->marginEnd().isAuto())
         return false;
-    return flexitem->style()->alignSelf() == AlignStretch || (flexitem->style()->alignSelf() == AlignAuto && parent->style()->alignItems() == AlignStretch);
+    return flexitem->style()->alignSelf() == ItemPositionStretch || (flexitem->style()->alignSelf() == ItemPositionAuto && parent->style()->alignItems() == ItemPositionStretch);
 }
 
 static bool isStretchingColumnFlexItem(const RenderObject* flexitem)
@@ -2509,11 +2414,8 @@
 
 bool RenderBox::autoWidthShouldFitContent() const
 {
-    if (node() && (node()->hasTagName(inputTag) || node()->hasTagName(selectTag) || node()->hasTagName(buttonTag)
-        || isHTMLTextAreaElement(node()) || node()->hasTagName(legendTag)))
-        return true;
-
-    return false;
+    return node() && (node()->hasTagName(inputTag) || node()->hasTagName(selectTag) || node()->hasTagName(buttonTag)
+        || node()->hasTagName(textareaTag) || (node()->hasTagName(legendTag) && !style()->hasOutOfFlowPosition()));
 }
 
 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
@@ -2521,12 +2423,11 @@
     const RenderStyle* containingBlockStyle = containingBlock->style();
     Length marginStartLength = style()->marginStartUsing(containingBlockStyle);
     Length marginEndLength = style()->marginEndUsing(containingBlockStyle);
-    RenderView* renderView = view();
 
     if (isFloating() || isInline()) {
         // Inline blocks/tables and floats don't have their margins increased.
-        marginStart = minimumValueForLength(marginStartLength, containerWidth, renderView);
-        marginEnd = minimumValueForLength(marginEndLength, containerWidth, renderView);
+        marginStart = minimumValueForLength(marginStartLength, containerWidth);
+        marginEnd = minimumValueForLength(marginEndLength, containerWidth);
         return;
     }
 
@@ -2544,8 +2445,8 @@
     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style()->textAlign() == WEBKIT_CENTER)) {
         // Other browsers center the margin box for align=center elements so we match them here.
-        LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth, renderView);
-        LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth, renderView);
+        LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
+        LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
         LayoutUnit centeredMarginBoxStart = max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
         marginStart = centeredMarginBoxStart + marginStartWidth;
         marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
@@ -2554,7 +2455,7 @@
 
     // Case Two: The object is being pushed to the start of the containing block's available logical width.
     if (marginEndLength.isAuto() && childWidth < containerWidth) {
-        marginStart = valueForLength(marginStartLength, containerWidth, renderView);
+        marginStart = valueForLength(marginStartLength, containerWidth);
         marginEnd = containerWidth - childWidth - marginStart;
         return;
     }
@@ -2563,80 +2464,15 @@
     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
         || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
     if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
-        marginEnd = valueForLength(marginEndLength, containerWidth, renderView);
+        marginEnd = valueForLength(marginEndLength, containerWidth);
         marginStart = containerWidth - childWidth - marginEnd;
         return;
     }
 
     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
     // auto margins will just turn into 0.
-    marginStart = minimumValueForLength(marginStartLength, containerWidth, renderView);
-    marginEnd = minimumValueForLength(marginEndLength, containerWidth, renderView);
-}
-
-RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
-{
-    // Make sure nobody is trying to call this with a null region.
-    if (!region)
-        return 0;
-
-    // If we have computed our width in this region already, it will be cached, and we can
-    // just return it.
-    RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
-    if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
-        return boxInfo;
-
-    // No cached value was found, so we have to compute our insets in this region.
-    // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
-    // support to cover all boxes.
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style()->writingMode() != style()->writingMode())
-        return 0;
-
-    LogicalExtentComputedValues computedValues;
-    computeLogicalWidthInRegion(computedValues, region);
-
-    // Now determine the insets based off where this object is supposed to be positioned.
-    RenderBlock* cb = containingBlock();
-    RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
-    RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion);
-    LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
-    LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
-
-    LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
-    LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
-    LayoutUnit logicalWidthInRegion = computedValues.m_extent;
-    LayoutUnit logicalLeftInRegion = computedValues.m_position;
-    LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
-    LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
-    LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
-    LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
-    LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
-
-    LayoutUnit logicalLeftOffset = 0;
-
-    if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) {
-        LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(this, marginStartInRegion, region);
-        if (cb->style()->isLeftToRightDirection())
-            logicalLeftDelta += startPositionDelta;
-        else
-            logicalRightDelta += startPositionDelta;
-    }
-
-    if (cb->style()->isLeftToRightDirection())
-        logicalLeftOffset += logicalLeftDelta;
-    else
-        logicalLeftOffset -= (widthDelta + logicalRightDelta);
-
-    LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
-    bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
-            || (style()->isLeftToRightDirection() && logicalLeftOffset)
-            || (!style()->isLeftToRightDirection() && logicalRightOffset);
-
-    // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
-    if (cacheFlag == CacheRenderBoxRegionInfo)
-        return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
-    return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
+    marginStart = minimumValueForLength(marginStartLength, containerWidth);
+    marginEnd = minimumValueForLength(marginEndLength, containerWidth);
 }
 
 static bool shouldFlipBeforeAfterMargins(const RenderStyle* containingBlockStyle, const RenderStyle* childStyle)
@@ -2735,8 +2571,7 @@
         // Block children of horizontal flexible boxes fill the height of the box.
         // FIXME: Account for block-flow in flexible boxes.
         // https://bugs.webkit.org/show_bug.cgi?id=46418
-        if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL
-                && parent()->isStretchingChildren()) {
+        if (h.isAuto() && inHorizontalBox && toRenderDeprecatedFlexibleBox(parent())->isStretchingChildren()) {
             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
             checkMinMaxHeight = false;
         }
@@ -2760,8 +2595,8 @@
         if (hasPerpendicularContainingBlock) {
             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), style());
             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
-                    shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
-                    shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
+                shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
+                shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
         }
     }
 
@@ -2837,8 +2672,6 @@
         return height.value();
     if (height.isPercent())
         return computePercentageLogicalHeight(height);
-    if (height.isViewportPercentage())
-        return valueForLength(height, 0, view());
     return -1;
 }
 
@@ -2916,17 +2749,6 @@
             LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), -1);
             availableHeight = max<LayoutUnit>(0, contentBoxHeight);
         }
-    } else if (cbstyle->logicalHeight().isViewportPercentage()) {
-        LayoutUnit heightWithScrollbar = valueForLength(cbstyle->logicalHeight(), 0, view());
-        if (heightWithScrollbar != -1) {
-            LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
-            // We need to adjust for min/max height because this method does not
-            // handle the min/max of the current block, its caller does. So the
-            // return value from the recursive call will not have been adjusted
-            // yet.
-            LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), -1);
-            availableHeight = max<LayoutUnit>(0, contentBoxHeight);
-        }
     } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
         // Don't allow this to affect the block' height() member variable, since this
         // can get called while the block is still laying out its kids.
@@ -2976,11 +2798,6 @@
             LayoutUnit availableLogicalWidth = 0;
             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
         }
-        case ViewportPercentageWidth:
-        case ViewportPercentageHeight:
-        case ViewportPercentageMin:
-        case ViewportPercentageMax:
-            return adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, 0, view()));
         case FitContent:
         case FillAvailable:
         case Percent:
@@ -3001,9 +2818,12 @@
         case Intrinsic:
         case MinIntrinsic:
         case Auto:
-        case ExtendToZoom:
         case Undefined:
             return intrinsicLogicalWidth();
+        case ExtendToZoom:
+        case DeviceWidth:
+        case DeviceHeight:
+            break;
     }
 
     ASSERT_NOT_REACHED();
@@ -3074,11 +2894,6 @@
             }
             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
         }
-        case ViewportPercentageWidth:
-        case ViewportPercentageHeight:
-        case ViewportPercentageMin:
-        case ViewportPercentageMax:
-            return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, 0, view()));
         case MinContent:
         case MaxContent:
         case FitContent:
@@ -3150,10 +2965,9 @@
     // Margins are calculated with respect to the logical width of
     // the containing block (8.3)
     LayoutUnit cw = containingBlockLogicalWidthForContent();
-    RenderView* renderView = view();
     RenderStyle* containingBlockStyle = containingBlock->style();
-    marginBefore = minimumValueForLength(style()->marginBeforeUsing(containingBlockStyle), cw, renderView);
-    marginAfter = minimumValueForLength(style()->marginAfterUsing(containingBlockStyle), cw, renderView);
+    marginBefore = minimumValueForLength(style()->marginBeforeUsing(containingBlockStyle), cw);
+    marginAfter = minimumValueForLength(style()->marginAfterUsing(containingBlockStyle), cw);
 }
 
 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
@@ -3165,44 +2979,22 @@
     containingBlock->setMarginAfterForChild(this, marginAfter);
 }
 
-LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
+LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
 {
     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
         return containingBlockLogicalHeightForPositioned(containingBlock, false);
 
     // Use viewport as container for top-level fixed-position elements.
     if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
-        const RenderView* view = static_cast<const RenderView*>(containingBlock);
+        const RenderView* view = toRenderView(containingBlock);
         if (FrameView* frameView = view->frameView()) {
             LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
             return containingBlock->isHorizontalWritingMode() ? viewportRect.width() : viewportRect.height();
         }
     }
 
-    if (containingBlock->isBox()) {
-        RenderFlowThread* flowThread = flowThreadContainingBlock();
-        if (!flowThread)
-            return toRenderBox(containingBlock)->clientLogicalWidth();
-
-        const RenderBlock* cb = toRenderBlock(containingBlock);
-        RenderBoxRegionInfo* boxInfo = 0;
-        if (!region) {
-            if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode)
-                return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion();
-            if (isWritingModeRoot()) {
-                LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage();
-                RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
-                if (cbRegion) {
-                    cbRegion = cb->clampToStartAndEndRegions(cbRegion);
-                    boxInfo = cb->renderBoxRegionInfo(cbRegion);
-                }
-            }
-        } else if (region && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
-            RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
-            boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
-        }
-        return (boxInfo) ? max<LayoutUnit>(0, cb->clientLogicalWidth() - (cb->logicalWidth() - boxInfo->logicalWidth())) : cb->clientLogicalWidth();
-    }
+    if (containingBlock->isBox())
+        return toRenderBox(containingBlock)->clientLogicalWidth();
 
     ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
 
@@ -3230,11 +3022,11 @@
 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
 {
     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
-        return containingBlockLogicalWidthForPositioned(containingBlock, 0, false);
+        return containingBlockLogicalWidthForPositioned(containingBlock, false);
 
     // Use viewport as container for top-level fixed-position elements.
     if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
-        const RenderView* view = static_cast<const RenderView*>(containingBlock);
+        const RenderView* view = toRenderView(containingBlock);
         if (FrameView* frameView = view->frameView()) {
             LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
             return containingBlock->isHorizontalWritingMode() ? viewportRect.height() : viewportRect.width();
@@ -3242,12 +3034,9 @@
     }
 
     if (containingBlock->isBox()) {
-        const RenderBlock* cb = toRenderBlock(containingBlock);
-        LayoutUnit result = cb->clientLogicalHeight();
-        RenderFlowThread* flowThread = flowThreadContainingBlock();
-        if (flowThread && containingBlock->isRenderFlowThread() && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode())
-            return toRenderFlowThread(containingBlock)->contentLogicalHeightOfFirstRegion();
-        return result;
+        const RenderBlock* cb = containingBlock->isRenderBlock() ?
+            toRenderBlock(containingBlock) : containingBlock->containingBlock();
+        return cb->clientLogicalHeight();
     }
 
     ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
@@ -3270,7 +3059,7 @@
     return heightResult;
 }
 
-static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
+static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
 {
     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
         return;
@@ -3283,13 +3072,6 @@
                 staticPosition += toRenderBox(curr)->logicalLeft();
                 if (toRenderBox(curr)->isRelPositioned())
                     staticPosition += toRenderBox(curr)->relativePositionOffset().width();
-                if (region && curr->isRenderBlock()) {
-                    const RenderBlock* cb = toRenderBlock(curr);
-                    region = cb->clampToStartAndEndRegions(region);
-                    RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region);
-                    if (boxInfo)
-                        staticPosition += boxInfo->logicalLeft();
-                }
             } else if (curr->isInline()) {
                 if (curr->isRelPositioned()) {
                     if (!curr->style()->logicalLeft().isAuto())
@@ -3312,17 +3094,6 @@
                 }
                 if (curr == enclosingBox)
                     staticPosition -= enclosingBox->logicalWidth();
-                if (region && curr->isRenderBlock()) {
-                    const RenderBlock* cb = toRenderBlock(curr);
-                    region = cb->clampToStartAndEndRegions(region);
-                    RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region);
-                    if (boxInfo) {
-                        if (curr != containerBlock)
-                            staticPosition -= cb->logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
-                        if (curr == enclosingBox)
-                            staticPosition += enclosingBox->logicalWidth() - boxInfo->logicalWidth();
-                    }
-                }
             } else if (curr->isInline()) {
                 if (curr->isRelPositioned()) {
                     if (!curr->style()->logicalLeft().isAuto())
@@ -3338,11 +3109,9 @@
     }
 }
 
-void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
+void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues) const
 {
     if (isReplaced()) {
-        // FIXME: Positioned replaced elements inside a flow thread are not working properly
-        // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
         computePositionedLogicalWidthReplaced(computedValues);
         return;
     }
@@ -3367,7 +3136,7 @@
     // relative positioned inline.
     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
 
-    const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
+    const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
 
     // Use the container block's direction except when calculating the static distance
     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
@@ -3408,7 +3177,7 @@
 
     // see FIXME 1
     // Calculate the static distance if needed.
-    computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
+    computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth);
 
     // Calculate constraint equation values for 'width' case.
     computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
@@ -3451,25 +3220,6 @@
     }
 
     computedValues.m_extent += bordersPlusPadding;
-
-    // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
-    // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode() && containerBlock->isRenderBlock()) {
-        ASSERT(containerBlock->canHaveBoxInfoInRegion());
-        LayoutUnit logicalLeftPos = computedValues.m_position;
-        const RenderBlock* cb = toRenderBlock(containerBlock);
-        LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage();
-        RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
-        if (cbRegion) {
-            cbRegion = cb->clampToStartAndEndRegions(cbRegion);
-            RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion);
-            if (boxInfo) {
-                logicalLeftPos += boxInfo->logicalLeft();
-                computedValues.m_position = logicalLeftPos;
-            }
-        }
-    }
 }
 
 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
@@ -3506,12 +3256,11 @@
 
     LayoutUnit logicalLeftValue = 0;
 
-    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
+    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
 
     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
     bool logicalLeftIsAuto = logicalLeft.isAuto();
     bool logicalRightIsAuto = logicalRight.isAuto();
-    RenderView* renderView = view();
     LayoutUnit& marginLogicalLeftValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
     LayoutUnit& marginLogicalRightValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
@@ -3530,10 +3279,10 @@
         // NOTE:  It is not necessary to solve for 'right' in the over constrained
         // case because the value is not used for any further calculations.
 
-        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
-        computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth, renderView));
+        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
+        computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
 
-        const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth, renderView) + bordersPlusPadding);
+        const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
 
         // Margins are now the only unknown
         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
@@ -3554,16 +3303,16 @@
             }
         } else if (marginLogicalLeft.isAuto()) {
             // Solve for left margin
-            marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth, renderView);
+            marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
         } else if (marginLogicalRight.isAuto()) {
             // Solve for right margin
-            marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth, renderView);
+            marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
         } else {
             // Over-constrained, solve for left if direction is RTL
-            marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth, renderView);
-            marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth, renderView);
+            marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
+            marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
 
             // Use the containing block's direction rather than the parent block's
             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
@@ -3613,8 +3362,8 @@
         // because the value is not used for any further calculations.
 
         // Calculate margins, 'auto' margins are ignored.
-        marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth, renderView);
-        marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth, renderView);
+        marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
+        marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
 
         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
 
@@ -3622,7 +3371,7 @@
         // Use rule/case that applies.
         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
             // RULE 1: (use shrink-to-fit for width, and solve of left)
-            LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
+            LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
 
             // FIXME: would it be better to have shrink-to-fit in one step?
             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
@@ -3632,24 +3381,24 @@
             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
-            logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
+            logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
 
             shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
             // RULE 4: (solve for left)
-            computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth, renderView));
-            logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth, renderView));
+            computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
+            logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
             // RULE 5: (solve for width)
-            logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
+            logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
             if (autoWidthShouldFitContent())
                 shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
             else
-                computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth, renderView));
+                computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
             // RULE 6: (no need solve for right)
-            logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
-            computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth, renderView));
+            logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
+            computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
         }
     }
 
@@ -3781,25 +3530,6 @@
 
     // Set final height value.
     computedValues.m_extent += bordersPlusPadding;
-
-    // Adjust logicalTop if we need to for perpendicular writing modes in regions.
-    // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (flowThread && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode() && containerBlock->isRenderBlock()) {
-        ASSERT(containerBlock->canHaveBoxInfoInRegion());
-        LayoutUnit logicalTopPos = computedValues.m_position;
-        const RenderBlock* cb = toRenderBlock(containerBlock);
-        LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage() - logicalLeft();
-        RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
-        if (cbRegion) {
-            cbRegion = cb->clampToStartAndEndRegions(cbRegion);
-            RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion);
-            if (boxInfo) {
-                logicalTopPos += boxInfo->logicalLeft();
-                computedValues.m_position = logicalTopPos;
-            }
-        }
-    }
 }
 
 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
@@ -3836,14 +3566,13 @@
     LayoutUnit logicalHeightValue;
     LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding;
 
-    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
+    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
 
     LayoutUnit logicalTopValue = 0;
 
     bool logicalHeightIsAuto = logicalHeightLength.isAuto();
     bool logicalTopIsAuto = logicalTop.isAuto();
     bool logicalBottomIsAuto = logicalBottom.isAuto();
-    RenderView* renderView = view();
 
     LayoutUnit resolvedLogicalHeight;
     // Height is never unsolved for tables.
@@ -3854,7 +3583,7 @@
         if (logicalHeightLength.isIntrinsic())
             resolvedLogicalHeight = computeIntrinsicLogicalContentHeightUsing(logicalHeightLength, contentLogicalHeight, bordersPlusPadding);
         else
-            resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight, renderView));
+            resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight));
     }
 
     if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
@@ -3870,9 +3599,9 @@
         // case because the value is not used for any further calculations.
 
         logicalHeightValue = resolvedLogicalHeight;
-        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
+        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
 
-        const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight, renderView) + bordersPlusPadding);
+        const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight) + bordersPlusPadding);
 
         // Margins are now the only unknown
         if (marginBefore.isAuto() && marginAfter.isAuto()) {
@@ -3882,16 +3611,16 @@
             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before; // account for odd valued differences
         } else if (marginBefore.isAuto()) {
             // Solve for top margin
-            computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth, renderView);
+            computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
             computedValues.m_margins.m_before = availableSpace - computedValues.m_margins.m_after;
         } else if (marginAfter.isAuto()) {
             // Solve for bottom margin
-            computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth, renderView);
+            computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before;
         } else {
             // Over-constrained, (no need solve for bottom)
-            computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth, renderView);
-            computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth, renderView);
+            computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
+            computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
         }
     } else {
         /*--------------------------------------------------------------------*\
@@ -3920,8 +3649,8 @@
         // because the value is not used for any further calculations.
 
         // Calculate margins, 'auto' margins are ignored.
-        computedValues.m_margins.m_before = minimumValueForLength(marginBefore, containerRelativeLogicalWidth, renderView);
-        computedValues.m_margins.m_after = minimumValueForLength(marginAfter, containerRelativeLogicalWidth, renderView);
+        computedValues.m_margins.m_before = minimumValueForLength(marginBefore, containerRelativeLogicalWidth);
+        computedValues.m_margins.m_after = minimumValueForLength(marginAfter, containerRelativeLogicalWidth);
 
         const LayoutUnit availableSpace = containerLogicalHeight - (computedValues.m_margins.m_before + computedValues.m_margins.m_after + bordersPlusPadding);
 
@@ -3929,23 +3658,23 @@
         if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
             // RULE 1: (height is content based, solve of top)
             logicalHeightValue = contentLogicalHeight;
-            logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight, renderView));
+            logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
         } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
             // RULE 3: (height is content based, no need solve of bottom)
-            logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
+            logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
             logicalHeightValue = contentLogicalHeight;
         } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
             // RULE 4: (solve of top)
             logicalHeightValue = resolvedLogicalHeight;
-            logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight, renderView));
+            logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
         } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
             // RULE 5: (solve of height)
-            logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
-            logicalHeightValue = max<LayoutUnit>(0, availableSpace - (logicalTopValue + valueForLength(logicalBottom, containerLogicalHeight, renderView)));
+            logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
+            logicalHeightValue = max<LayoutUnit>(0, availableSpace - (logicalTopValue + valueForLength(logicalBottom, containerLogicalHeight)));
         } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
             // RULE 6: (no need solve of bottom)
             logicalHeightValue = resolvedLogicalHeight;
-            logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
+            logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
         }
     }
     computedValues.m_extent = logicalHeightValue;
@@ -3968,7 +3697,7 @@
     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
 
     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
-    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
+    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
 
     // To match WinIE, in quirks mode use the parent's 'direction' property
     // instead of the the container block's.
@@ -4000,7 +3729,7 @@
      *    else if 'direction' is 'rtl', set 'right' to the static position.
     \*-----------------------------------------------------------------------*/
     // see FIXME 1
-    computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, 0); // FIXME: Pass the region.
+    computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth);
 
     /*-----------------------------------------------------------------------*\
      * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
@@ -4023,14 +3752,13 @@
     \*-----------------------------------------------------------------------*/
     LayoutUnit logicalLeftValue = 0;
     LayoutUnit logicalRightValue = 0;
-    RenderView* renderView = view();
 
     if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
         // 'left' and 'right' cannot be 'auto' due to step 3
         ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
 
-        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
-        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
+        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
+        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
 
         LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
         if (difference > 0) {
@@ -4053,39 +3781,39 @@
      *    that value.
     \*-----------------------------------------------------------------------*/
     } else if (logicalLeft.isAuto()) {
-        marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth, renderView);
-        marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth, renderView);
-        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
+        marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
+        marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
+        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
 
         // Solve for 'left'
         logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
     } else if (logicalRight.isAuto()) {
-        marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth, renderView);
-        marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth, renderView);
-        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
+        marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
+        marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
+        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
 
         // Solve for 'right'
         logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
     } else if (marginLogicalLeft.isAuto()) {
-        marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth, renderView);
-        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
-        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
+        marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
+        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
+        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
 
         // Solve for 'margin-left'
         marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
     } else if (marginLogicalRight.isAuto()) {
-        marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth, renderView);
-        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
-        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
+        marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
+        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
+        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
 
         // Solve for 'margin-right'
         marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
     } else {
         // Nothing is 'auto', just calculate the values.
-        marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth, renderView);
-        marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth, renderView);
-        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
-        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
+        marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
+        marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
+        logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
+        logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
         // If the containing block is right-to-left, then push the left position as far to the right as possible
         if (containerDirection == RTL) {
             int totalLogicalWidth = computedValues.m_extent + logicalLeftValue + logicalRightValue +  marginLogicalLeftAlias + marginLogicalRightAlias;
@@ -4137,7 +3865,7 @@
     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
 
     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
-    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
+    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
 
     // Variables to solve.
     Length marginBefore = style()->marginBefore();
@@ -4147,7 +3875,6 @@
 
     Length logicalTop = style()->logicalTop();
     Length logicalBottom = style()->logicalBottom();
-    RenderView* renderView = view();
 
     /*-----------------------------------------------------------------------*\
      * 1. The used value of 'height' is determined as for inline replaced
@@ -4191,8 +3918,8 @@
         // 'top' and 'bottom' cannot be 'auto' due to step 2 and 3 combined.
         ASSERT(!(logicalTop.isAuto() || logicalBottom.isAuto()));
 
-        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
-        logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight, renderView);
+        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
+        logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
 
         LayoutUnit difference = availableSpace - (logicalTopValue + logicalBottomValue);
         // NOTE: This may result in negative values.
@@ -4204,39 +3931,39 @@
      *    for that value.
     \*-----------------------------------------------------------------------*/
     } else if (logicalTop.isAuto()) {
-        marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth, renderView);
-        marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth, renderView);
-        logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight, renderView);
+        marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
+        marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
+        logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
 
         // Solve for 'top'
         logicalTopValue = availableSpace - (logicalBottomValue + marginBeforeAlias + marginAfterAlias);
     } else if (logicalBottom.isAuto()) {
-        marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth, renderView);
-        marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth, renderView);
-        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
+        marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
+        marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
+        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
 
         // Solve for 'bottom'
         // NOTE: It is not necessary to solve for 'bottom' because we don't ever
         // use the value.
     } else if (marginBefore.isAuto()) {
-        marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth, renderView);
-        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
-        logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight, renderView);
+        marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
+        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
+        logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
 
         // Solve for 'margin-top'
         marginBeforeAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginAfterAlias);
     } else if (marginAfter.isAuto()) {
-        marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth, renderView);
-        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
-        logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight, renderView);
+        marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
+        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
+        logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
 
         // Solve for 'margin-bottom'
         marginAfterAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginBeforeAlias);
     } else {
         // Nothing is 'auto', just calculate the values.
-        marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth, renderView);
-        marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth, renderView);
-        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
+        marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
+        marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
+        logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
         // NOTE: It is not necessary to solve for 'bottom' because we don't ever
         // use the value.
      }
@@ -4702,6 +4429,11 @@
 {
     // Only propagate interior layout overflow if we don't clip it.
     LayoutRect rect = borderBoxRect();
+    // We want to include the margin, but only when it adds height. Quirky margins don't contribute height
+    // nor do the margins of self-collapsing blocks.
+    if (!style()->hasMarginAfterQuirk() && !isSelfCollapsingBlock())
+        rect.expand(isHorizontalWritingMode() ? LayoutSize(LayoutUnit(), marginAfter()) : LayoutSize(marginAfter(), LayoutUnit()));
+
     if (!hasOverflowClip())
         rect.unite(layoutOverflowRect());
 
@@ -4877,22 +4609,11 @@
     return LayoutSize(rect.x(), rect.y());
 }
 
-bool RenderBox::hasRelativeDimensions() const
-{
-    // FIXME: This should probably include viewport percentage heights as well.
-    return style()->height().isPercent() || style()->width().isPercent()
-        || style()->maxHeight().isPercent() || style()->maxWidth().isPercent()
-        || style()->minHeight().isPercent() || style()->minWidth().isPercent();
-}
-
 bool RenderBox::hasRelativeLogicalHeight() const
 {
     return style()->logicalHeight().isPercent()
         || style()->logicalMinHeight().isPercent()
-        || style()->logicalMaxHeight().isPercent()
-        || style()->logicalHeight().isViewportPercentage()
-        || style()->logicalMinHeight().isViewportPercentage()
-        || style()->logicalMaxHeight().isViewportPercentage();
+        || style()->logicalMaxHeight().isPercent();
 }
 
 static void markBoxForRelayoutAfterSplit(RenderBox* box)
diff --git a/Source/core/rendering/RenderBox.h b/Source/core/rendering/RenderBox.h
index 350b640..0ec1ff8 100644
--- a/Source/core/rendering/RenderBox.h
+++ b/Source/core/rendering/RenderBox.h
@@ -30,8 +30,6 @@
 
 namespace WebCore {
 
-class RenderBoxRegionInfo;
-class RenderRegion;
 struct PaintInfo;
 
 enum SizeType { MainOrPreferredSize, MinSize, MaxSize };
@@ -47,14 +45,39 @@
     ScrollOffsetClamped
 };
 
+struct RenderBoxRareData {
+    WTF_MAKE_NONCOPYABLE(RenderBoxRareData); WTF_MAKE_FAST_ALLOCATED;
+public:
+    RenderBoxRareData()
+        : m_inlineBoxWrapper(0)
+        , m_overrideLogicalContentHeight(-1)
+        , m_overrideLogicalContentWidth(-1)
+    {
+    }
+
+    // For inline replaced elements, the inline box that owns us.
+    InlineBox* m_inlineBoxWrapper;
+
+    LayoutUnit m_overrideLogicalContentHeight;
+    LayoutUnit m_overrideLogicalContentWidth;
+};
+
+
 class RenderBox : public RenderBoxModelObject {
 public:
     explicit RenderBox(ContainerNode*);
-    virtual ~RenderBox();
 
     // hasAutoZIndex only returns true if the element is positioned or a flex-item since
     // position:static elements that are not flex-items get their z-index coerced to auto.
-    virtual bool requiresLayer() const OVERRIDE { return isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasOverflowClip() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns() || !style()->hasAutoZIndex(); }
+    virtual LayerType layerTypeRequired() const OVERRIDE
+    {
+        if (isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns() || !style()->hasAutoZIndex())
+            return NormalLayer;
+        if (hasOverflowClip())
+            return OverflowClipLayer;
+
+        return NoLayer;
+    }
 
     virtual bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const OVERRIDE;
 
@@ -87,7 +110,7 @@
     LayoutUnit logicalWidth() const { return style()->isHorizontalWritingMode() ? width() : height(); }
     LayoutUnit logicalHeight() const { return style()->isHorizontalWritingMode() ? height() : width(); }
 
-    LayoutUnit constrainLogicalWidthInRegionByMinMax(LayoutUnit, LayoutUnit, RenderBlock*, RenderRegion* = 0) const;
+    LayoutUnit constrainLogicalWidthByMinMax(LayoutUnit, LayoutUnit, RenderBlock*) const;
     LayoutUnit constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const;
     LayoutUnit constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const;
 
@@ -217,8 +240,8 @@
 
     // IE extensions. Used to calculate offsetWidth/Height.  Overridden by inlines (RenderFlow)
     // to return the remaining width on a given line (and the height of a single line).
-    virtual LayoutUnit offsetWidth() const { return width(); }
-    virtual LayoutUnit offsetHeight() const { return height(); }
+    virtual LayoutUnit offsetWidth() const OVERRIDE { return width(); }
+    virtual LayoutUnit offsetHeight() const OVERRIDE { return height(); }
 
     virtual int pixelSnappedOffsetWidth() const OVERRIDE FINAL;
     virtual int pixelSnappedOffsetHeight() const OVERRIDE FINAL;
@@ -304,20 +327,20 @@
     virtual LayoutUnit collapsedMarginBefore() const { return marginBefore(); }
     virtual LayoutUnit collapsedMarginAfter() const { return marginAfter(); }
 
-    virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const;
-    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
+    virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE;
+    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const OVERRIDE;
 
     LayoutRect reflectionBox() const;
     int reflectionOffset() const;
     // Given a rect in the object's coordinate space, returns the corresponding rect in the reflection.
     LayoutRect reflectedRect(const LayoutRect&) const;
 
-    virtual void layout();
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual void layout() OVERRIDE;
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 
-    virtual LayoutUnit minPreferredLogicalWidth() const;
-    virtual LayoutUnit maxPreferredLogicalWidth() const;
+    virtual LayoutUnit minPreferredLogicalWidth() const OVERRIDE;
+    virtual LayoutUnit maxPreferredLogicalWidth() const OVERRIDE;
 
     // FIXME: We should rename these back to overrideLogicalHeight/Width and have them store
     // the border-box height/width like the regular height/width accessors on RenderBox.
@@ -342,7 +365,7 @@
     void clearContainingBlockOverrideSize();
     void clearOverrideContainingBlockContentLogicalHeight();
 
-    virtual LayoutSize offsetFromContainer(RenderObject*, const LayoutPoint&, bool* offsetDependsOnPoint = 0) const;
+    virtual LayoutSize offsetFromContainer(RenderObject*, const LayoutPoint&, bool* offsetDependsOnPoint = 0) const OVERRIDE;
 
     LayoutUnit adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const;
     LayoutUnit adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const;
@@ -372,9 +395,6 @@
     void computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const;
     void computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock);
 
-    enum RenderBoxRegionInfoFlags { CacheRenderBoxRegionInfo, DoNotCacheRenderBoxRegionInfo };
-    LayoutRect borderBoxRectInRegion(RenderRegion*, RenderBoxRegionInfoFlags = CacheRenderBoxRegionInfo) const;
-    void clearRenderBoxRegionInfo();
     virtual LayoutUnit offsetFromLogicalTopOfFirstPage() const;
 
     void positionLineBox(InlineBox*);
@@ -385,7 +405,7 @@
     // For inline replaced elements, this function returns the inline box that owns us.  Enables
     // the replaced RenderObject to quickly determine what line it is contained on and to easily
     // iterate over structures on the line.
-    InlineBox* inlineBoxWrapper() const { return m_inlineBoxWrapper; }
+    InlineBox* inlineBoxWrapper() const { return m_rareData ? m_rareData->m_inlineBoxWrapper : 0; }
     void setInlineBoxWrapper(InlineBox*);
     void deleteLineBoxWrapper();
 
@@ -394,23 +414,21 @@
     void repaintDuringLayoutIfMoved(const LayoutRect&);
     virtual void repaintOverhangingFloats(bool paintAllDescendants);
 
-    virtual LayoutUnit containingBlockLogicalWidthForContent() const;
+    virtual LayoutUnit containingBlockLogicalWidthForContent() const OVERRIDE;
     LayoutUnit containingBlockLogicalHeightForContent(AvailableLogicalHeightType) const;
 
-    LayoutUnit containingBlockLogicalWidthForContentInRegion(RenderRegion*) const;
-    LayoutUnit containingBlockAvailableLineWidthInRegion(RenderRegion*) const;
+    LayoutUnit containingBlockAvailableLineWidth() const;
     LayoutUnit perpendicularContainingBlockLogicalHeight() const;
 
     virtual void updateLogicalWidth();
     virtual void updateLogicalHeight();
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const;
 
-    RenderBoxRegionInfo* renderBoxRegionInfo(RenderRegion*, RenderBoxRegionInfoFlags = CacheRenderBoxRegionInfo) const;
-    void computeLogicalWidthInRegion(LogicalExtentComputedValues&, RenderRegion* = 0) const;
+    void computeLogicalWidth(LogicalExtentComputedValues&) const;
 
     bool stretchesToViewport() const
     {
-        return document().inQuirksMode() && style()->logicalHeight().isAuto() && !isFloatingOrOutOfFlowPositioned() && (isRoot() || isBody()) && !document().shouldDisplaySeamlesslyWithParent() && !isInline();
+        return document().inQuirksMode() && style()->logicalHeight().isAuto() && !isFloatingOrOutOfFlowPositioned() && (isRoot() || isBody()) && !isInline();
     }
 
     virtual LayoutSize intrinsicSize() const { return LayoutSize(); }
@@ -421,9 +439,9 @@
     // of a containing block).  HTML4 buttons, <select>s, <input>s, legends, and floating/compact elements do this.
     bool sizesLogicalWidthToFitContent(SizeType) const;
 
-    LayoutUnit shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb, RenderRegion*) const;
+    LayoutUnit shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb) const;
 
-    LayoutUnit computeLogicalWidthInRegionUsing(SizeType, Length logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* containingBlock, RenderRegion*) const;
+    LayoutUnit computeLogicalWidthUsing(SizeType, Length logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* containingBlock) const;
     LayoutUnit computeLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const;
     LayoutUnit computeContentLogicalHeight(const Length& height, LayoutUnit intrinsicContentHeight) const;
     LayoutUnit computeContentAndScrollbarLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const;
@@ -452,7 +470,7 @@
     int horizontalScrollbarHeight() const;
     int instrinsicScrollbarLogicalWidth() const;
     int scrollbarLogicalHeight() const { return style()->isHorizontalWritingMode() ? horizontalScrollbarHeight() : verticalScrollbarWidth(); }
-    virtual bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1);
+    virtual bool scroll(ScrollDirection, ScrollGranularity, float delta = 1);
     bool canBeScrolledAndHasScrollableArea() const;
     virtual bool canBeProgramaticallyScrolled() const;
     virtual void autoscroll(const IntPoint&);
@@ -480,10 +498,10 @@
     bool hasUnsplittableScrollingOverflow() const;
     bool isUnsplittableForPagination() const;
 
-    virtual LayoutRect localCaretRect(InlineBox*, int caretOffset, LayoutUnit* extraWidthToEndOfLine = 0);
+    virtual LayoutRect localCaretRect(InlineBox*, int caretOffset, LayoutUnit* extraWidthToEndOfLine = 0) OVERRIDE;
 
-    virtual LayoutRect overflowClipRect(const LayoutPoint& location, RenderRegion*, OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize);
-    LayoutRect clipRect(const LayoutPoint& location, RenderRegion*);
+    virtual LayoutRect overflowClipRect(const LayoutPoint& location, OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize);
+    LayoutRect clipRect(const LayoutPoint& location);
     virtual bool hasControlClip() const { return false; }
     virtual LayoutRect controlClipRect(const LayoutPoint&) const { return LayoutRect(); }
     bool pushContentsClip(PaintInfo&, const LayoutPoint& accumulatedOffset, ContentsClipBehavior);
@@ -493,7 +511,7 @@
     virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&);
     virtual void paintMask(PaintInfo&, const LayoutPoint&);
     virtual void paintClippingMask(PaintInfo&, const LayoutPoint&);
-    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0);
+    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
     // Called when a positioned object moves but doesn't necessarily change size.  A simplified layout is attempted
     // that just updates the object's position. If the size does change, the object remains dirty.
@@ -529,7 +547,7 @@
     bool isDeprecatedFlexItem() const { return !isInline() && !isFloatingOrOutOfFlowPositioned() && parent() && parent()->isDeprecatedFlexibleBox(); }
     bool isFlexItemIncludingDeprecated() const { return !isInline() && !isFloatingOrOutOfFlowPositioned() && parent() && parent()->isFlexibleBoxIncludingDeprecated(); }
 
-    virtual LayoutUnit lineHeight(bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
+    virtual LayoutUnit lineHeight(bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
     virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
 
     virtual LayoutUnit offsetLeft() const OVERRIDE;
@@ -563,7 +581,6 @@
     LayoutSize cachedSizeForOverflowClip() const;
     void applyCachedClipAndScrollOffsetForRepaint(LayoutRect& paintRect) const;
 
-    virtual bool hasRelativeDimensions() const;
     virtual bool hasRelativeLogicalHeight() const;
 
     bool hasHorizontalLayoutOverflow() const
@@ -606,17 +623,17 @@
     }
 
 protected:
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
-    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle);
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
     virtual void updateFromStyle() OVERRIDE;
 
     LayoutRect backgroundPaintedExtent() const;
     virtual bool foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const;
     virtual bool computeBackgroundIsKnownToBeObscured() OVERRIDE;
 
-    virtual void paintBackgroundWithBorderAndBoxShadow(PaintInfo&, const LayoutRect&, BackgroundBleedAvoidance);
+    void paintBackgroundWithBorderAndBoxShadow(PaintInfo&, const LayoutRect&, BackgroundBleedAvoidance);
     void paintBackground(const PaintInfo&, const LayoutRect&, BackgroundBleedAvoidance = BackgroundBleedNone);
 
     void paintFillLayer(const PaintInfo&, const Color&, const FillLayer*, const LayoutRect&, BackgroundBleedAvoidance, CompositeOperator, RenderObject* backgroundObject);
@@ -628,7 +645,7 @@
     BackgroundBleedAvoidance determineBackgroundBleedAvoidance(GraphicsContext*) const;
     bool backgroundHasOpaqueTopLayer() const;
 
-    void computePositionedLogicalWidth(LogicalExtentComputedValues&, RenderRegion* = 0) const;
+    void computePositionedLogicalWidth(LogicalExtentComputedValues&) const;
 
     LayoutUnit computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const;
     LayoutUnit computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, LayoutUnit intrinsicContentHeight, LayoutUnit borderAndPadding) const;
@@ -636,7 +653,7 @@
     virtual bool shouldComputeSizeAsReplaced() const { return isReplaced() && !isInlineBlockOrInlineTable(); }
 
     virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE;
-    virtual void mapAbsoluteToLocalPoint(MapCoordinatesFlags, TransformState&) const;
+    virtual void mapAbsoluteToLocalPoint(MapCoordinatesFlags, TransformState&) const OVERRIDE;
 
     void paintRootBoxFillLayers(const PaintInfo&);
 
@@ -657,7 +674,7 @@
 
     bool skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock) const;
 
-    LayoutUnit containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* = 0, bool checkForPerpendicularWritingMode = true) const;
+    LayoutUnit containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode = true) const;
     LayoutUnit containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode = true) const;
 
     LayoutUnit viewLogicalHeightForPercentages() const;
@@ -687,10 +704,22 @@
 
     virtual LayoutRect frameRectForStickyPositioning() const OVERRIDE FINAL { return frameRect(); }
 
+    RenderBoxRareData& ensureRareData()
+    {
+        if (!m_rareData)
+            m_rareData = adoptPtr(new RenderBoxRareData());
+        return *m_rareData.get();
+    }
+
 private:
     // The width/height of the contents + borders + padding.  The x/y location is relative to our container (which is not always our parent).
     LayoutRect m_frameRect;
 
+    // Our intrinsic height, used for min-height: min-content etc. Maintained by
+    // updateLogicalHeight. This is logicalHeight() before it is clamped to
+    // min/max.
+    LayoutUnit m_intrinsicContentLogicalHeight;
+
 protected:
     LayoutBoxExtent m_marginBox;
 
@@ -700,16 +729,11 @@
     // The preferred logical width of the element if it never breaks any lines at all.
     LayoutUnit m_maxPreferredLogicalWidth;
 
-    // Our intrinsic height, used for min-height: min-content etc. Maintained by
-    // updateLogicalHeight. This is logicalHeight() before it is clamped to
-    // min/max.
-    LayoutUnit m_intrinsicContentLogicalHeight;
-
-    // For inline replaced elements, the inline box that owns us.
-    InlineBox* m_inlineBoxWrapper;
-
     // Our overflow information.
     OwnPtr<RenderOverflow> m_overflow;
+
+private:
+    OwnPtr<RenderBoxRareData> m_rareData;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderBox, isBox());
@@ -742,16 +766,16 @@
 inline void RenderBox::setInlineBoxWrapper(InlineBox* boxWrapper)
 {
     if (boxWrapper) {
-        ASSERT(!m_inlineBoxWrapper);
+        ASSERT(!inlineBoxWrapper());
         // m_inlineBoxWrapper should already be 0. Deleting it is a safeguard against security issues.
         // Otherwise, there will two line box wrappers keeping the reference to this renderer, and
         // only one will be notified when the renderer is getting destroyed. The second line box wrapper
         // will keep a stale reference.
-        if (UNLIKELY(m_inlineBoxWrapper != 0))
+        if (UNLIKELY(inlineBoxWrapper() != 0))
             deleteLineBoxWrapper();
     }
 
-    m_inlineBoxWrapper = boxWrapper;
+    ensureRareData().m_inlineBoxWrapper = boxWrapper;
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderBoxModelObject.cpp b/Source/core/rendering/RenderBoxModelObject.cpp
index e39ec21..b48e46f 100644
--- a/Source/core/rendering/RenderBoxModelObject.cpp
+++ b/Source/core/rendering/RenderBoxModelObject.cpp
@@ -27,17 +27,17 @@
 #include "core/rendering/RenderBoxModelObject.h"
 
 #include "HTMLNames.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLFrameOwnerElement.h"
-#include "core/page/Settings.h"
 #include "core/page/scrolling/ScrollingConstraints.h"
 #include "core/rendering/CompositedLayerMapping.h"
 #include "core/rendering/ImageQualityController.h"
 #include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderNamedFlowThread.h"
 #include "core/rendering/RenderRegion.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/ShadowList.h"
@@ -100,48 +100,6 @@
     return view()->compositor()->hasAcceleratedCompositing();
 }
 
-bool RenderBoxModelObject::startTransition(double timeOffset, CSSPropertyID propertyId, const RenderStyle* fromStyle, const RenderStyle* toStyle)
-{
-    ASSERT(hasLayer());
-    ASSERT(compositingState() == PaintsIntoOwnBacking);
-    return layer()->compositedLayerMapping()->startTransition(timeOffset, propertyId, fromStyle, toStyle);
-}
-
-void RenderBoxModelObject::transitionPaused(double timeOffset, CSSPropertyID propertyId)
-{
-    ASSERT(hasLayer());
-    ASSERT(compositingState() == PaintsIntoOwnBacking);
-    layer()->compositedLayerMapping()->transitionPaused(timeOffset, propertyId);
-}
-
-void RenderBoxModelObject::transitionFinished(CSSPropertyID propertyId)
-{
-    ASSERT(hasLayer());
-    ASSERT(compositingState() == PaintsIntoOwnBacking);
-    layer()->compositedLayerMapping()->transitionFinished(propertyId);
-}
-
-bool RenderBoxModelObject::startAnimation(double timeOffset, const CSSAnimationData* animation, const KeyframeList& keyframes)
-{
-    ASSERT(hasLayer());
-    ASSERT(compositingState() == PaintsIntoOwnBacking);
-    return layer()->compositedLayerMapping()->startAnimation(timeOffset, animation, keyframes);
-}
-
-void RenderBoxModelObject::animationPaused(double timeOffset, const String& name)
-{
-    ASSERT(hasLayer());
-    ASSERT(compositingState() == PaintsIntoOwnBacking);
-    layer()->compositedLayerMapping()->animationPaused(timeOffset, name);
-}
-
-void RenderBoxModelObject::animationFinished(const String& name)
-{
-    ASSERT(hasLayer());
-    ASSERT(compositingState() == PaintsIntoOwnBacking);
-    layer()->compositedLayerMapping()->animationFinished(name);
-}
-
 bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
 {
     return ImageQualityController::imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
@@ -240,11 +198,11 @@
     // call availableWidth on our containing block.
     if (!style()->left().isAuto()) {
         if (!style()->right().isAuto() && !containingBlock->style()->isLeftToRightDirection())
-            offset.setWidth(-valueForLength(style()->right(), containingBlock->availableWidth(), view()));
+            offset.setWidth(-valueForLength(style()->right(), containingBlock->availableWidth()));
         else
-            offset.expand(valueForLength(style()->left(), containingBlock->availableWidth(), view()), 0);
+            offset.expand(valueForLength(style()->left(), containingBlock->availableWidth()), 0);
     } else if (!style()->right().isAuto()) {
-        offset.expand(-valueForLength(style()->right(), containingBlock->availableWidth(), view()), 0);
+        offset.expand(-valueForLength(style()->right(), containingBlock->availableWidth()), 0);
     }
 
     // If the containing block of a relatively positioned element does not
@@ -257,13 +215,13 @@
         && (!containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight()
             || !style()->top().isPercent()
             || containingBlock->stretchesToViewport()))
-        offset.expand(0, valueForLength(style()->top(), containingBlock->availableHeight(), view()));
+        offset.expand(0, valueForLength(style()->top(), containingBlock->availableHeight()));
 
     else if (!style()->bottom().isAuto()
         && (!containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight()
             || !style()->bottom().isPercent()
             || containingBlock->stretchesToViewport()))
-        offset.expand(0, -valueForLength(style()->bottom(), containingBlock->availableHeight(), view()));
+        offset.expand(0, -valueForLength(style()->bottom(), containingBlock->availableHeight()));
 
     return offset;
 }
@@ -294,11 +252,8 @@
             else if (isStickyPositioned())
                 referencePoint.move(stickyPositionOffset());
 
-            // CSS regions specification says that region flows should return the body element as their offsetParent.
-            // Since we will bypass the body’s renderer anyway, just end the loop if we encounter a region flow (named flow thread).
-            // See http://dev.w3.org/csswg/css-regions/#cssomview-offset-attributes
             RenderObject* current;
-            for (current = parent(); current != offsetParent && !current->isRenderNamedFlowThread() && current->parent(); current = current->parent()) {
+            for (current = parent(); current != offsetParent && current->parent(); current = current->parent()) {
                 // FIXME: What are we supposed to do inside SVG content?
                 if (!isOutOfFlowPositioned()) {
                     if (current->isBox() && !current->isTableRow())
@@ -307,11 +262,7 @@
                 }
             }
 
-            // Compute the offset position for elements inside named flow threads for which the offsetParent was the body.
-            // See https://code.google.com/p/chromium/issues/detail?id=242168
-            if (current->isRenderNamedFlowThread())
-                referencePoint = toRenderNamedFlowThread(current)->adjustedPositionRelativeToOffsetParent(*this, referencePoint);
-            else if (offsetParent->isBox() && offsetParent->isBody() && !offsetParent->isPositioned())
+            if (offsetParent->isBox() && offsetParent->isBody() && !offsetParent->isPositioned())
                 referencePoint.moveBy(toRenderBox(offsetParent)->topLeftLocation());
         }
     }
@@ -319,7 +270,7 @@
     return referencePoint;
 }
 
-void RenderBoxModelObject::computeStickyPositionConstraints(StickyPositionViewportConstraints& constraints, const FloatRect& viewportRect) const
+void RenderBoxModelObject::computeStickyPositionConstraints(StickyPositionViewportConstraints& constraints, const FloatRect& constrainingRect) const
 {
     RenderBlock* containingBlock = this->containingBlock();
 
@@ -328,10 +279,10 @@
 
     // Sticky positioned element ignore any override logical width on the containing block (as they don't call
     // containingBlockLogicalWidthForContent). It's unclear whether this is totally fine.
-    LayoutBoxExtent minMargin(minimumValueForLength(style()->marginTop(), maxWidth, view()),
-        minimumValueForLength(style()->marginRight(), maxWidth, view()),
-        minimumValueForLength(style()->marginBottom(), maxWidth, view()),
-        minimumValueForLength(style()->marginLeft(), maxWidth, view()));
+    LayoutBoxExtent minMargin(minimumValueForLength(style()->marginTop(), maxWidth),
+        minimumValueForLength(style()->marginRight(), maxWidth),
+        minimumValueForLength(style()->marginBottom(), maxWidth),
+        minimumValueForLength(style()->marginLeft(), maxWidth));
 
     // Compute the container-relative area within which the sticky element is allowed to move.
     containerContentRect.contract(minMargin);
@@ -347,40 +298,56 @@
     // Map to the view to avoid including page scale factor.
     FloatRect absContainerFrame = containingBlock->localToContainerQuad(FloatRect(FloatPoint(), containingBlock->size()), view()).boundingBox();
 
+    if (containingBlock->hasOverflowClip()) {
+        IntSize scrollOffset = containingBlock->layer()->scrollableArea()->adjustedScrollOffset();
+        stickyLocation -= scrollOffset;
+    }
+
     // We can't call localToAbsolute on |this| because that will recur. FIXME: For now, assume that |this| is not transformed.
     FloatRect absoluteStickyBoxRect(absContainerFrame.location() + stickyLocation, flippedStickyBoxRect.size());
     constraints.setAbsoluteStickyBoxRect(absoluteStickyBoxRect);
 
     if (!style()->left().isAuto()) {
-        constraints.setLeftOffset(valueForLength(style()->left(), viewportRect.width(), view()));
+        constraints.setLeftOffset(valueForLength(style()->left(), constrainingRect.width()));
         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
     }
 
     if (!style()->right().isAuto()) {
-        constraints.setRightOffset(valueForLength(style()->right(), viewportRect.width(), view()));
+        constraints.setRightOffset(valueForLength(style()->right(), constrainingRect.width()));
         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
     }
 
     if (!style()->top().isAuto()) {
-        constraints.setTopOffset(valueForLength(style()->top(), viewportRect.height(), view()));
+        constraints.setTopOffset(valueForLength(style()->top(), constrainingRect.height()));
         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
     }
 
     if (!style()->bottom().isAuto()) {
-        constraints.setBottomOffset(valueForLength(style()->bottom(), viewportRect.height(), view()));
+        constraints.setBottomOffset(valueForLength(style()->bottom(), constrainingRect.height() ));
         constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
     }
 }
 
 LayoutSize RenderBoxModelObject::stickyPositionOffset() const
 {
-    LayoutRect viewportRect = view()->frameView()->viewportConstrainedVisibleContentRect();
+    FloatRect constrainingRect;
+
+    ASSERT(hasLayer());
+    RenderLayer* enclosingClippingLayer = layer()->enclosingOverflowClipLayer(ExcludeSelf);
+    if (enclosingClippingLayer) {
+        RenderBox* enclosingClippingBox = toRenderBox(enclosingClippingLayer->renderer());
+        LayoutRect clipRect = enclosingClippingBox->overflowClipRect(LayoutPoint());
+        constrainingRect = enclosingClippingBox->localToContainerQuad(FloatRect(clipRect), view()).boundingBox();
+    } else {
+        LayoutRect viewportRect = view()->frameView()->viewportConstrainedVisibleContentRect();
+        constrainingRect = viewportRect;
+    }
 
     StickyPositionViewportConstraints constraints;
-    computeStickyPositionConstraints(constraints, viewportRect);
+    computeStickyPositionConstraints(constraints, constrainingRect);
 
     // The sticky offset is physical, so we can just return the delta computed in absolute coords (though it may be wrong with transforms).
-    return LayoutSize(constraints.computeStickyOffset(viewportRect));
+    return LayoutSize(constraints.computeStickyOffset(constrainingRect));
 }
 
 LayoutSize RenderBoxModelObject::offsetForInFlowPosition() const
@@ -421,21 +388,17 @@
 LayoutUnit RenderBoxModelObject::computedCSSPadding(Length padding) const
 {
     LayoutUnit w = 0;
-    RenderView* renderView = 0;
     if (padding.isPercent())
         w = containingBlockLogicalWidthForContent();
-    else if (padding.isViewportPercentage())
-        renderView = view();
-    return minimumValueForLength(padding, w, renderView);
+    return minimumValueForLength(padding, w);
 }
 
 RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
     bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
 {
-    RenderView* renderView = view();
-    RoundedRect border = style()->getRoundedBorderFor(borderRect, renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
+    RoundedRect border = style()->getRoundedBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);
     if (box && (box->nextLineBox() || box->prevLineBox())) {
-        RoundedRect segmentBorder = style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
+        RoundedRect segmentBorder = style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), includeLogicalLeftEdge, includeLogicalRightEdge);
         border.setRadii(segmentBorder.radii());
     }
 
@@ -510,7 +473,7 @@
         if (boxShadow.style() != Normal)
             continue;
         FloatSize shadowOffset(boxShadow.x(), boxShadow.y());
-        context->setShadow(shadowOffset, boxShadow.blur(), renderer->resolveColor(boxShadow.color()),
+        context->setShadow(shadowOffset, boxShadow.blur(), boxShadow.color(),
             DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
         return;
     }
@@ -552,14 +515,14 @@
     // while rendering.)
     if (forceBackgroundToWhite) {
         // Note that we can't reuse this variable below because the bgColor might be changed
-        bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha();
+        bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.alpha();
         if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
             bgColor = Color::white;
             shouldPaintBackgroundImage = false;
         }
     }
 
-    bool colorVisible = bgColor.isValid() && bgColor.alpha();
+    bool colorVisible = bgColor.alpha();
 
     // Fast path for drawing simple color backgrounds.
     if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
@@ -614,7 +577,7 @@
     if (clippedWithLocalScrolling) {
         // Clip to the overflow area.
         RenderBox* thisBox = toRenderBox(this);
-        context->clip(thisBox->overflowClipRect(rect.location(), paintInfo.renderRegion));
+        context->clip(thisBox->overflowClipRect(rect.location()));
 
         // Adjust the paint rect to reflect a scrolled content box with borders at the ends.
         IntSize offset = thisBox->scrolledContentOffset();
@@ -669,7 +632,7 @@
     bool isOpaqueRoot = false;
     if (isRoot) {
         isOpaqueRoot = true;
-        if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255) && view()->frameView()) {
+        if (!bgLayer->next() && bgColor.hasAlpha() && view()->frameView()) {
             Element* ownerElement = document().ownerElement();
             if (ownerElement) {
                 if (!ownerElement->hasTagName(frameTag)) {
@@ -702,29 +665,28 @@
             if (!boxShadowShouldBeAppliedToBackground)
                 backgroundRect.intersect(paintInfo.rect);
 
-            // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
-            Color baseColor;
-            bool shouldClearBackground = false;
-            if (isOpaqueRoot) {
-                baseColor = view()->frameView()->baseBackgroundColor();
-                if (!baseColor.alpha())
-                    shouldClearBackground = true;
-            }
-
             GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
             if (boxShadowShouldBeAppliedToBackground)
                 applyBoxShadowForBackground(context, this);
 
-            if (baseColor.alpha()) {
-                if (bgColor.alpha())
-                    baseColor = baseColor.blend(bgColor);
+            if (isOpaqueRoot) {
+                // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
+                Color baseColor = view()->frameView()->baseBackgroundColor();
+                bool shouldClearDocumentBackground = document().settings() && document().settings()->shouldClearDocumentBackground();
+                CompositeOperator operation = shouldClearDocumentBackground ? CompositeCopy : context->compositeOperation();
 
-                context->fillRect(backgroundRect, baseColor, CompositeCopy);
+                if (baseColor.alpha()) {
+                    if (bgColor.alpha())
+                        baseColor = baseColor.blend(bgColor);
+                    context->fillRect(backgroundRect, baseColor, operation);
+                } else if (bgColor.alpha()) {
+                    context->fillRect(backgroundRect, bgColor, operation);
+                } else if (shouldClearDocumentBackground) {
+                    context->clearRect(backgroundRect);
+                }
             } else if (bgColor.alpha()) {
-                CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
-                context->fillRect(backgroundRect, bgColor, operation);
-            } else if (shouldClearBackground)
-                context->clearRect(backgroundRect);
+                context->fillRect(backgroundRect, bgColor, context->compositeOperation());
+            }
         }
     }
 
@@ -755,7 +717,7 @@
 
         // Now draw the text into the mask. We do this by painting using a special paint phase that signals to
         // InlineTextBoxes that they should just add their contents to the clip.
-        PaintInfo info(context, maskRect, PaintPhaseTextClip, PaintBehaviorForceBlackText, 0, paintInfo.renderRegion);
+        PaintInfo info(context, maskRect, PaintPhaseTextClip, PaintBehaviorForceBlackText, 0);
         context->setCompositeOperation(CompositeSourceOver);
         if (box) {
             RootInlineBox* root = box->root();
@@ -881,7 +843,6 @@
 
     IntSize imageIntrinsicSize = calculateImageIntrinsicDimensions(image, positioningAreaSize, ScaleByEffectiveZoom);
     imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor());
-    RenderView* renderView = view();
     switch (type) {
         case SizeLength: {
             LayoutSize tileSize = positioningAreaSize;
@@ -891,13 +852,13 @@
 
             if (layerWidth.isFixed())
                 tileSize.setWidth(layerWidth.value());
-            else if (layerWidth.isPercent() || layerWidth.isViewportPercentage())
-                tileSize.setWidth(valueForLength(layerWidth, positioningAreaSize.width(), renderView));
+            else if (layerWidth.isPercent())
+                tileSize.setWidth(valueForLength(layerWidth, positioningAreaSize.width()));
 
             if (layerHeight.isFixed())
                 tileSize.setHeight(layerHeight.value());
-            else if (layerHeight.isPercent() || layerHeight.isViewportPercentage())
-                tileSize.setHeight(valueForLength(layerHeight, positioningAreaSize.height(), renderView));
+            else if (layerHeight.isPercent())
+                tileSize.setHeight(valueForLength(layerHeight, positioningAreaSize.height()));
 
             applySubPixelHeuristicForTileSize(tileSize, positioningAreaSize);
 
@@ -1008,6 +969,17 @@
     // Determine the background positioning area and set destRect to the background painting area.
     // destRect will be adjusted later if the background is non-repeating.
     bool fixedAttachment = fillLayer->attachment() == FixedBackgroundAttachment;
+
+#if ENABLE(FAST_MOBILE_SCROLLING)
+    if (view()->frameView() && view()->frameView()->canBlitOnScroll()) {
+        // As a side effect of an optimization to blit on scroll, we do not honor the CSS
+        // property "background-attachment: fixed" because it may result in rendering
+        // artifacts. Note, these artifacts only appear if we are blitting on scroll of
+        // a page that has fixed background images.
+        fixedAttachment = false;
+    }
+#endif
+
     if (!fixedAttachment) {
         geometry.setDestRect(snappedPaintRect);
 
@@ -1054,11 +1026,10 @@
 
     EFillRepeat backgroundRepeatX = fillLayer->repeatX();
     EFillRepeat backgroundRepeatY = fillLayer->repeatY();
-    RenderView* renderView = view();
     int availableWidth = positioningAreaSize.width() - geometry.tileSize().width();
     int availableHeight = positioningAreaSize.height() - geometry.tileSize().height();
 
-    LayoutUnit computedXPosition = minimumValueForLength(fillLayer->xPosition(), availableWidth, renderView, true);
+    LayoutUnit computedXPosition = roundedMinimumValueForLength(fillLayer->xPosition(), availableWidth);
     if (backgroundRepeatX == RoundFill && positioningAreaSize.width() > 0 && fillTileSize.width() > 0) {
         long nrTiles = max(1l, lroundf((float)positioningAreaSize.width() / fillTileSize.width()));
 
@@ -1072,7 +1043,7 @@
         geometry.setSpaceSize(IntSize());
     }
 
-    LayoutUnit computedYPosition = minimumValueForLength(fillLayer->yPosition(), availableHeight, renderView, true);
+    LayoutUnit computedYPosition = roundedMinimumValueForLength(fillLayer->yPosition(), availableHeight);
     if (backgroundRepeatY == RoundFill && positioningAreaSize.height() > 0 && fillTileSize.height() > 0) {
         long nrTiles = max(1l, lroundf((float)positioningAreaSize.height() / fillTileSize.height()));
 
@@ -1094,7 +1065,7 @@
         int actualWidth = geometry.tileSize().width() + space;
 
         if (space >= 0) {
-            computedXPosition = minimumValueForLength(Length(), availableWidth, renderView, true);
+            computedXPosition = roundedMinimumValueForLength(Length(), availableWidth);
             geometry.setSpaceSize(IntSize(space, 0));
             geometry.setPhaseX(actualWidth ? actualWidth - roundToInt(computedXPosition + left) % actualWidth : 0);
         } else {
@@ -1115,7 +1086,7 @@
         int actualHeight = geometry.tileSize().height() + space;
 
         if (space >= 0) {
-            computedYPosition = minimumValueForLength(Length(), availableHeight, renderView, true);
+            computedYPosition = roundedMinimumValueForLength(Length(), availableHeight);
             geometry.setSpaceSize(IntSize(geometry.spaceSize().width(), space));
             geometry.setPhaseY(actualHeight ? actualHeight - roundToInt(computedYPosition + top) % actualHeight : 0);
         } else {
@@ -1135,13 +1106,13 @@
     geometry.setDestOrigin(geometry.destRect().location());
 }
 
-static LayoutUnit computeBorderImageSide(const BorderImageLength& borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent, RenderView* renderView)
+static LayoutUnit computeBorderImageSide(const BorderImageLength& borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent)
 {
     if (borderSlice.isNumber())
         return borderSlice.number() * borderSide;
     if (borderSlice.length().isAuto())
         return imageSide;
-    return valueForLength(borderSlice.length(), boxExtent, renderView);
+    return valueForLength(borderSlice.length(), boxExtent);
 }
 
 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle* style,
@@ -1170,21 +1141,20 @@
 
     int imageWidth = imageSize.width();
     int imageHeight = imageSize.height();
-    RenderView* renderView = view();
 
     float imageScaleFactor = styleImage->imageScaleFactor();
-    int topSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().top(), imageHeight, renderView)) * imageScaleFactor;
-    int rightSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().right(), imageWidth, renderView)) * imageScaleFactor;
-    int bottomSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().bottom(), imageHeight, renderView)) * imageScaleFactor;
-    int leftSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().left(), imageWidth, renderView)) * imageScaleFactor;
+    int topSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().top(), imageHeight)) * imageScaleFactor;
+    int rightSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().right(), imageWidth)) * imageScaleFactor;
+    int bottomSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().bottom(), imageHeight)) * imageScaleFactor;
+    int leftSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().left(), imageWidth)) * imageScaleFactor;
 
     ENinePieceImageRule hRule = ninePieceImage.horizontalRule();
     ENinePieceImageRule vRule = ninePieceImage.verticalRule();
 
-    int topWidth = computeBorderImageSide(ninePieceImage.borderSlices().top(), style->borderTopWidth(), topSlice, borderImageRect.height(), renderView);
-    int rightWidth = computeBorderImageSide(ninePieceImage.borderSlices().right(), style->borderRightWidth(), rightSlice, borderImageRect.width(), renderView);
-    int bottomWidth = computeBorderImageSide(ninePieceImage.borderSlices().bottom(), style->borderBottomWidth(), bottomSlice, borderImageRect.height(), renderView);
-    int leftWidth = computeBorderImageSide(ninePieceImage.borderSlices().left(), style->borderLeftWidth(), leftSlice, borderImageRect.width(), renderView);
+    int topWidth = computeBorderImageSide(ninePieceImage.borderSlices().top(), style->borderTopWidth(), topSlice, borderImageRect.height());
+    int rightWidth = computeBorderImageSide(ninePieceImage.borderSlices().right(), style->borderRightWidth(), rightSlice, borderImageRect.width());
+    int bottomWidth = computeBorderImageSide(ninePieceImage.borderSlices().bottom(), style->borderBottomWidth(), bottomSlice, borderImageRect.height());
+    int leftWidth = computeBorderImageSide(ninePieceImage.borderSlices().left(), style->borderLeftWidth(), leftSlice, borderImageRect.width());
 
     // Reduce the widths if they're too large.
     // The spec says: Given Lwidth as the width of the border image area, Lheight as its height, and Wside as the border image width
@@ -1734,7 +1704,7 @@
 
     BorderEdge edges[4];
     getBorderEdgeInfo(edges, style, includeLogicalLeftEdge, includeLogicalRightEdge);
-    RoundedRect outerBorder = style->getRoundedBorderFor(rect, view(), includeLogicalLeftEdge, includeLogicalRightEdge);
+    RoundedRect outerBorder = style->getRoundedBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge);
     RoundedRect innerBorder = style->getRoundedInnerBorderFor(borderInnerRectAdjustedForBleedAvoidance(graphicsContext, rect, bleedAvoidance), includeLogicalLeftEdge, includeLogicalRightEdge);
 
     bool haveAlphaColor = false;
@@ -2436,7 +2406,7 @@
         return false;
 
     Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
-    if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
+    if (backgroundColor.hasAlpha())
         return false;
 
     const FillLayer* lastBackgroundLayer = style()->backgroundLayers();
@@ -2466,11 +2436,11 @@
         return;
 
     RoundedRect border = (shadowStyle == Inset) ? s->getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge)
-                                                   : s->getRoundedBorderFor(paintRect, view(), includeLogicalLeftEdge, includeLogicalRightEdge);
+        : s->getRoundedBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge);
 
     bool hasBorderRadius = s->hasBorderRadius();
     bool isHorizontal = s->isHorizontalWritingMode();
-    bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
+    bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
 
     GraphicsContextStateSaver stateSaver(*context, false);
 
@@ -2480,22 +2450,22 @@
         if (shadow.style() != shadowStyle)
             continue;
 
-        IntSize shadowOffset(shadow.x(), shadow.y());
-        int shadowBlur = shadow.blur();
-        int shadowSpread = shadow.spread();
+        FloatSize shadowOffset(shadow.x(), shadow.y());
+        float shadowBlur = shadow.blur();
+        float shadowSpread = shadow.spread();
 
         if (shadowOffset.isZero() && !shadowBlur && !shadowSpread)
             continue;
 
-        const Color& shadowColor = resolveColor(shadow.color());
+        const Color& shadowColor = shadow.color();
 
         if (shadow.style() == Normal) {
-            RoundedRect fillRect = border;
+            FloatRect fillRect = border.rect();
             fillRect.inflate(shadowSpread);
             if (fillRect.isEmpty())
                 continue;
 
-            IntRect shadowRect(border.rect());
+            FloatRect shadowRect(border.rect());
             shadowRect.inflate(shadowBlur + shadowSpread);
             shadowRect.move(shadowOffset);
 
@@ -2516,6 +2486,8 @@
                         context->clipOutRoundedRect(rectToClipOut);
                     }
                 } else {
+                    // This IntRect is correct even with fractional shadows, because it is used for the rectangle
+                    // of the box itself, which is always pixel-aligned.
                     IntRect rectToClipOut = border.rect();
 
                     // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
@@ -2543,20 +2515,25 @@
             context->setDrawLooper(drawLooper);
 
             if (hasBorderRadius) {
-                RoundedRect influenceRect(shadowRect, border.radii());
+                RoundedRect influenceRect(pixelSnappedIntRect(LayoutRect(shadowRect)), border.radii());
                 influenceRect.expandRadii(2 * shadowBlur + shadowSpread);
                 if (allCornersClippedOut(influenceRect, info.rect))
-                    context->fillRect(fillRect.rect(), Color::black);
+                    context->fillRect(fillRect, Color::black);
                 else {
-                    fillRect.expandRadii(shadowSpread);
-                    if (!fillRect.isRenderable())
-                        fillRect.adjustRadii();
-                    context->fillRoundedRect(fillRect, Color::black);
+                    // TODO: support non-integer shadows - crbug.com/334829
+                    RoundedRect roundedFillRect = border;
+                    roundedFillRect.inflate(shadowSpread);
+
+                    roundedFillRect.expandRadii(shadowSpread);
+                    if (!roundedFillRect.isRenderable())
+                        roundedFillRect.adjustRadii();
+                    context->fillRoundedRect(roundedFillRect, Color::black);
                 }
             } else {
-                context->fillRect(fillRect.rect(), Color::black);
+                context->fillRect(fillRect, Color::black);
             }
         } else {
+            // The inset shadow case.
             GraphicsContext::Edges clippedEdges = GraphicsContext::NoEdge;
             if (!includeLogicalLeftEdge) {
                 if (isHorizontal)
@@ -2570,7 +2547,8 @@
                 else
                     clippedEdges |= GraphicsContext::BottomEdge;
             }
-            context->drawInnerShadow(border, shadowColor, shadowOffset, shadowBlur, shadowSpread, clippedEdges);
+            // TODO: support non-integer shadows - crbug.com/334828
+            context->drawInnerShadow(border, shadowColor, flooredIntSize(shadowOffset), shadowBlur, shadowSpread, clippedEdges);
         }
     }
 }
diff --git a/Source/core/rendering/RenderBoxModelObject.h b/Source/core/rendering/RenderBoxModelObject.h
index 31b3186..52e8fb0 100644
--- a/Source/core/rendering/RenderBoxModelObject.h
+++ b/Source/core/rendering/RenderBoxModelObject.h
@@ -66,7 +66,7 @@
     LayoutSize relativePositionOffset() const;
     LayoutSize relativePositionLogicalOffset() const { return style()->isHorizontalWritingMode() ? relativePositionOffset() : relativePositionOffset().transposedSize(); }
 
-    void computeStickyPositionConstraints(StickyPositionViewportConstraints&, const FloatRect& viewportRect) const;
+    void computeStickyPositionConstraints(StickyPositionViewportConstraints&, const FloatRect& constrainingRect) const;
     LayoutSize stickyPositionOffset() const;
     LayoutSize stickyPositionLogicalOffset() const { return style()->isHorizontalWritingMode() ? stickyPositionOffset() : stickyPositionOffset().transposedSize(); }
 
@@ -86,7 +86,13 @@
 
     virtual void updateFromStyle() OVERRIDE;
 
-    virtual bool requiresLayer() const OVERRIDE { return isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns(); }
+    virtual LayerType layerTypeRequired() const OVERRIDE
+    {
+        if (isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns())
+            return NormalLayer;
+
+        return NoLayer;
+    }
 
     // This will work on inlines to return the bounding box of all of the lines' border boxes.
     virtual IntRect borderBoundingBox() const = 0;
@@ -178,25 +184,15 @@
 
     void highQualityRepaintTimerFired(Timer<RenderBoxModelObject>*);
 
-    virtual void setSelectionState(SelectionState s);
-
-    bool canHaveBoxInfoInRegion() const { return !isFloating() && !isReplaced() && !isInline() && !hasColumns() && !isTableCell() && isRenderBlock() && !isRenderSVGBlock(); }
+    virtual void setSelectionState(SelectionState) OVERRIDE;
 
     void contentChanged(ContentChangeType);
     bool hasAcceleratedCompositing() const;
 
-    bool startTransition(double, CSSPropertyID, const RenderStyle* fromStyle, const RenderStyle* toStyle);
-    void transitionPaused(double timeOffset, CSSPropertyID);
-    void transitionFinished(CSSPropertyID);
-
-    bool startAnimation(double timeOffset, const CSSAnimationData*, const KeyframeList& keyframes);
-    void animationPaused(double timeOffset, const String& name);
-    void animationFinished(const String& name);
-
     virtual void computeLayerHitTestRects(LayerHitTestRects&) const OVERRIDE;
 
 protected:
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
     class BackgroundImageGeometry {
     public:
diff --git a/Source/core/rendering/RenderBoxRegionInfo.h b/Source/core/rendering/RenderBoxRegionInfo.h
deleted file mode 100644
index 3bde47e..0000000
--- a/Source/core/rendering/RenderBoxRegionInfo.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc.  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 APPLE INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-
-#ifndef RenderBoxRegionInfo_h
-#define RenderBoxRegionInfo_h
-
-#include "platform/LayoutUnit.h"
-#include "wtf/FastAllocBase.h"
-
-namespace WebCore {
-
-class RenderBoxRegionInfo {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    RenderBoxRegionInfo(LayoutUnit logicalLeft, LayoutUnit logicalWidth, bool isShifted)
-        : m_logicalLeft(logicalLeft)
-        , m_logicalWidth(logicalWidth)
-        , m_isShifted(isShifted)
-    { }
-
-    LayoutUnit logicalLeft() const { return m_logicalLeft; }
-    LayoutUnit logicalWidth() const { return m_logicalWidth; }
-
-    void shiftLogicalLeft(LayoutUnit delta) { m_logicalLeft += delta; m_isShifted = true; }
-
-    bool isShifted() const { return m_isShifted; }
-
-private:
-    LayoutUnit m_logicalLeft;
-    LayoutUnit m_logicalWidth;
-    bool m_isShifted;
-};
-
-} // namespace WebCore
-
-#endif // RenderBoxRegionInfo_h
diff --git a/Source/core/rendering/RenderButton.h b/Source/core/rendering/RenderButton.h
index 33df32b..246bab6 100644
--- a/Source/core/rendering/RenderButton.h
+++ b/Source/core/rendering/RenderButton.h
@@ -36,15 +36,16 @@
     explicit RenderButton(Element*);
     virtual ~RenderButton();
 
-    virtual const char* renderName() const { return "RenderButton"; }
-    virtual bool isRenderButton() const { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderButton"; }
+    virtual bool isRenderButton() const OVERRIDE { return true; }
 
     virtual bool canBeSelectionLeaf() const OVERRIDE { return node() && node()->rendererIsEditable(); }
+    virtual bool canCollapseAnonymousBlockChild() const OVERRIDE { return true; }
 
-    virtual void addChild(RenderObject* newChild, RenderObject *beforeChild = 0);
-    virtual void removeChild(RenderObject*);
-    virtual void removeLeftoverAnonymousBlock(RenderBlock*) { }
-    virtual bool createsAnonymousWrapper() const { return true; }
+    virtual void addChild(RenderObject* newChild, RenderObject *beforeChild = 0) OVERRIDE;
+    virtual void removeChild(RenderObject*) OVERRIDE;
+    virtual void removeLeftoverAnonymousBlock(RenderBlock*) OVERRIDE { }
+    virtual bool createsAnonymousWrapper() const OVERRIDE { return true; }
 
     void setupInnerStyle(RenderStyle*);
 
@@ -52,16 +53,16 @@
     virtual bool canHaveWhitespaceChildren() const OVERRIDE { return true; }
 
     virtual bool canHaveGeneratedChildren() const OVERRIDE;
-    virtual bool hasControlClip() const { return true; }
-    virtual LayoutRect controlClipRect(const LayoutPoint&) const;
+    virtual bool hasControlClip() const OVERRIDE { return true; }
+    virtual LayoutRect controlClipRect(const LayoutPoint&) const OVERRIDE;
 
     virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode) const OVERRIDE;
 
 private:
-    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle);
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
-    virtual bool hasLineIfEmpty() const { return node() && node()->hasTagName(HTMLNames::inputTag); }
+    virtual bool hasLineIfEmpty() const OVERRIDE { return node() && node()->hasTagName(HTMLNames::inputTag); }
 
     RenderBlock* m_inner;
 };
diff --git a/Source/core/rendering/RenderCombineText.cpp b/Source/core/rendering/RenderCombineText.cpp
index 75ae66d..da7ef5b 100644
--- a/Source/core/rendering/RenderCombineText.cpp
+++ b/Source/core/rendering/RenderCombineText.cpp
@@ -55,21 +55,21 @@
     m_needsFontUpdate = true;
 }
 
-float RenderCombineText::width(unsigned from, unsigned length, const Font& font, float xPosition, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
+float RenderCombineText::width(unsigned from, unsigned length, const Font& font, float xPosition, TextDirection direction, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
 {
     if (hasEmptyText())
         return 0;
 
     if (m_isCombined)
-        return font.size();
+        return font.fontDescription().computedSize();
 
-    return RenderText::width(from, length, font, xPosition, fallbackFonts, glyphOverflow);
+    return RenderText::width(from, length, font, xPosition, direction, fallbackFonts, glyphOverflow);
 }
 
 void RenderCombineText::adjustTextOrigin(FloatPoint& textOrigin, const FloatRect& boxRect) const
 {
     if (m_isCombined)
-        textOrigin.move(boxRect.height() / 2 - ceilf(m_combinedTextWidth) / 2, style()->font().pixelSize());
+        textOrigin.move(boxRect.height() / 2 - ceilf(m_combinedTextWidth) / 2, style()->font().fontDescription().computedPixelSize());
 }
 
 void RenderCombineText::getStringToRender(int start, StringView& string, int& length) const
@@ -96,7 +96,7 @@
     if (style()->isHorizontalWritingMode())
         return;
 
-    TextRun run = RenderBlockFlow::constructTextRun(this, originalFont(), this, style());
+    TextRun run = RenderBlockFlow::constructTextRun(this, originalFont(), this, style(), style()->direction());
     FontDescription description = originalFont().fontDescription();
     float emWidth = description.computedSize() * textCombineMargin;
     bool shouldUpdateFont = false;
@@ -114,7 +114,7 @@
         static const FontWidthVariant widthVariants[] = { HalfWidth, ThirdWidth, QuarterWidth };
         for (size_t i = 0 ; i < WTF_ARRAY_LENGTH(widthVariants) ; ++i) {
             description.setWidthVariant(widthVariants[i]);
-            Font compressedFont = Font(description, style()->font().letterSpacing(), style()->font().wordSpacing());
+            Font compressedFont = Font(description);
             compressedFont.update(fontSelector);
             float runWidth = compressedFont.width(run);
             if (runWidth <= emWidth) {
diff --git a/Source/core/rendering/RenderCombineText.h b/Source/core/rendering/RenderCombineText.h
index ce196d4..8e521f2 100644
--- a/Source/core/rendering/RenderCombineText.h
+++ b/Source/core/rendering/RenderCombineText.h
@@ -34,15 +34,15 @@
     void adjustTextOrigin(FloatPoint& textOrigin, const FloatRect& boxRect) const;
     void getStringToRender(int, StringView&, int& length) const;
     bool isCombined() const { return m_isCombined; }
-    float combinedTextWidth(const Font& font) const { return font.size(); }
+    float combinedTextWidth(const Font& font) const { return font.fontDescription().computedSize(); }
     const Font& originalFont() const { return parent()->style()->font(); }
 
 private:
-    virtual bool isCombineText() const { return true; }
-    virtual float width(unsigned from, unsigned length, const Font&, float xPosition, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
-    virtual const char* renderName() const { return "RenderCombineText"; }
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
-    virtual void setTextInternal(PassRefPtr<StringImpl>);
+    virtual bool isCombineText() const OVERRIDE { return true; }
+    virtual float width(unsigned from, unsigned length, const Font&, float xPosition, TextDirection, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const OVERRIDE;
+    virtual const char* renderName() const OVERRIDE { return "RenderCombineText"; }
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+    virtual void setTextInternal(PassRefPtr<StringImpl>) OVERRIDE;
 
     float m_combinedTextWidth;
     bool m_isCombined : 1;
diff --git a/Source/core/rendering/RenderCounter.h b/Source/core/rendering/RenderCounter.h
index 85cdff3..15d2b51 100644
--- a/Source/core/rendering/RenderCounter.h
+++ b/Source/core/rendering/RenderCounter.h
@@ -43,12 +43,12 @@
     void updateCounter();
 
 protected:
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
 private:
-    virtual const char* renderName() const;
-    virtual bool isCounter() const;
-    virtual PassRefPtr<StringImpl> originalText() const;
+    virtual const char* renderName() const OVERRIDE;
+    virtual bool isCounter() const OVERRIDE;
+    virtual PassRefPtr<StringImpl> originalText() const OVERRIDE;
 
     // Removes the reference to the CounterNode associated with this renderer.
     // This is used to cause a counter display update when the CounterNode tree changes.
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
index 9babdc2..676a735 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
@@ -250,7 +250,7 @@
     clearPreferredLogicalWidthsDirty();
 }
 
-void RenderDeprecatedFlexibleBox::layoutBlock(bool relayoutChildren, LayoutUnit)
+void RenderDeprecatedFlexibleBox::layoutBlock(bool relayoutChildren)
 {
     ASSERT(needsLayout());
 
@@ -260,10 +260,7 @@
     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
 
-    // Regions changing widths can force us to relayout our children.
     RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (logicalWidthChangedInRegions(flowThread))
-        relayoutChildren = true;
     if (updateRegionsAndShapesLogicalSize(flowThread))
         relayoutChildren = true;
 
@@ -426,7 +423,7 @@
             if (child->isOutOfFlowPositioned()) {
                 child->containingBlock()->insertPositionedObject(child);
                 RenderLayer* childLayer = child->layer();
-                childLayer->setStaticInlinePosition(xPos); // FIXME: Not right for regions.
+                childLayer->setStaticInlinePosition(xPos);
                 if (childLayer->staticBlockPosition() != yPos) {
                     childLayer->setStaticBlockPosition(yPos);
                     if (child->style()->hasStaticBlockPosition(style()->isHorizontalWritingMode()))
@@ -664,7 +661,7 @@
             if (child->isOutOfFlowPositioned()) {
                 child->containingBlock()->insertPositionedObject(child);
                 RenderLayer* childLayer = child->layer();
-                childLayer->setStaticInlinePosition(borderStart() + paddingStart()); // FIXME: Not right for regions.
+                childLayer->setStaticInlinePosition(borderStart() + paddingStart());
                 if (childLayer->staticBlockPosition() != height()) {
                     childLayer->setStaticBlockPosition(height());
                     if (child->style()->hasStaticBlockPosition(style()->isHorizontalWritingMode()))
@@ -948,15 +945,15 @@
         LayoutUnit totalWidth;
         InlineBox* anchorBox = lastLine->lastChild();
         if (anchorBox && anchorBox->renderer()->style()->isLink())
-            totalWidth = anchorBox->logicalWidth() + font.width(RenderBlockFlow::constructTextRun(this, font, ellipsisAndSpace, 2, style()));
+            totalWidth = anchorBox->logicalWidth() + font.width(RenderBlockFlow::constructTextRun(this, font, ellipsisAndSpace, 2, style(), style()->direction()));
         else {
             anchorBox = 0;
-            totalWidth = font.width(RenderBlockFlow::constructTextRun(this, font, &horizontalEllipsis, 1, style()));
+            totalWidth = font.width(RenderBlockFlow::constructTextRun(this, font, &horizontalEllipsis, 1, style(), style()->direction()));
         }
 
         // See if this width can be accommodated on the last visible line
-        RenderBlock* destBlock = toRenderBlock(lastVisibleLine->renderer());
-        RenderBlock* srcBlock = toRenderBlock(lastLine->renderer());
+        RenderBlockFlow* destBlock = lastVisibleLine->block();
+        RenderBlockFlow* srcBlock = lastLine->block();
 
         // FIXME: Directions of src/destBlock could be different from our direction and from one another.
         if (!srcBlock->style()->isLeftToRightDirection())
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.h b/Source/core/rendering/RenderDeprecatedFlexibleBox.h
index ff039da..91ba298 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.h
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.h
@@ -36,17 +36,17 @@
 
     static RenderDeprecatedFlexibleBox* createAnonymous(Document*);
 
-    virtual const char* renderName() const;
+    virtual const char* renderName() const OVERRIDE;
 
     virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
 
-    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageHeight = 0);
+    virtual void layoutBlock(bool relayoutChildren) OVERRIDE;
     void layoutHorizontalBox(bool relayoutChildren);
     void layoutVerticalBox(bool relayoutChildren);
 
-    virtual bool avoidsFloats() const { return true; }
-    virtual bool isDeprecatedFlexibleBox() const { return true; }
-    virtual bool isStretchingChildren() const { return m_stretchingChildren; }
+    virtual bool avoidsFloats() const OVERRIDE { return true; }
+    virtual bool isDeprecatedFlexibleBox() const OVERRIDE { return true; }
+    bool isStretchingChildren() const { return m_stretchingChildren; }
     virtual bool canCollapseAnonymousBlockChild() const OVERRIDE { return false; }
 
     void placeChild(RenderBox* child, const LayoutPoint& location);
@@ -70,6 +70,8 @@
     void clearLineClamp();
 };
 
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderDeprecatedFlexibleBox, isDeprecatedFlexibleBox());
+
 } // namespace WebCore
 
 #endif // RenderDeprecatedFlexibleBox_h
diff --git a/Source/core/rendering/RenderDetailsMarker.h b/Source/core/rendering/RenderDetailsMarker.h
index aa996c8..6876cda 100644
--- a/Source/core/rendering/RenderDetailsMarker.h
+++ b/Source/core/rendering/RenderDetailsMarker.h
@@ -34,10 +34,10 @@
     Orientation orientation() const;
 
 private:
-    virtual const char* renderName() const { return "RenderDetailsMarker"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderDetailsMarker"; }
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
-    virtual bool isDetailsMarker() const { return true; }
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual bool isDetailsMarker() const OVERRIDE { return true; }
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     bool isOpen() const;
     Path getCanonicalPath() const;
diff --git a/Source/core/rendering/RenderEmbeddedObject.cpp b/Source/core/rendering/RenderEmbeddedObject.cpp
index 40d4457..9dac195 100644
--- a/Source/core/rendering/RenderEmbeddedObject.cpp
+++ b/Source/core/rendering/RenderEmbeddedObject.cpp
@@ -29,7 +29,7 @@
 #include "core/html/HTMLIFrameElement.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
@@ -64,12 +64,13 @@
 {
 }
 
-bool RenderEmbeddedObject::requiresLayer() const
+LayerType RenderEmbeddedObject::layerTypeRequired() const
 {
-    if (RenderPart::requiresLayer())
-        return true;
+    LayerType type = RenderPart::layerTypeRequired();
+    if (type != NoLayer)
+        return type;
 
-    return allowsAcceleratedCompositing();
+    return allowsAcceleratedCompositing() ? NormalLayer : NoLayer;
 }
 
 bool RenderEmbeddedObject::allowsAcceleratedCompositing() const
@@ -174,7 +175,7 @@
     if (!settings)
         return false;
     fontDescription.setComputedSize(fontDescription.specifiedSize());
-    font = Font(fontDescription, 0, 0);
+    font = Font(fontDescription);
     font.update(0);
 
     run = TextRun(m_unavailablePluginReplacementText);
@@ -244,25 +245,6 @@
     statePusher.pop();
 }
 
-void RenderEmbeddedObject::viewCleared()
-{
-    // This is required for <object> elements whose contents are rendered by WebCore (e.g. src="foo.html").
-    if (node() && widget() && widget()->isFrameView()) {
-        FrameView* view = toFrameView(widget());
-        int marginWidth = -1;
-        int marginHeight = -1;
-        if (node()->hasTagName(iframeTag)) {
-            HTMLIFrameElement* frame = toHTMLIFrameElement(node());
-            marginWidth = frame->marginWidth();
-            marginHeight = frame->marginHeight();
-        }
-        if (marginWidth != -1)
-            view->setMarginWidth(marginWidth);
-        if (marginHeight != -1)
-            view->setMarginHeight(marginHeight);
-    }
-}
-
 bool RenderEmbeddedObject::scroll(ScrollDirection direction, ScrollGranularity granularity, float)
 {
     return false;
diff --git a/Source/core/rendering/RenderEmbeddedObject.h b/Source/core/rendering/RenderEmbeddedObject.h
index 679658e..9d48481 100644
--- a/Source/core/rendering/RenderEmbeddedObject.h
+++ b/Source/core/rendering/RenderEmbeddedObject.h
@@ -61,15 +61,13 @@
     virtual void layout() OVERRIDE FINAL;
 
 private:
-    virtual const char* renderName() const { return "RenderEmbeddedObject"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderEmbeddedObject"; }
     virtual bool isEmbeddedObject() const OVERRIDE FINAL { return true; }
 
     void paintSnapshotImage(PaintInfo&, const LayoutPoint&, Image*);
     virtual void paintContents(PaintInfo&, const LayoutPoint&) OVERRIDE FINAL;
 
-    virtual bool requiresLayer() const OVERRIDE FINAL;
-
-    virtual void viewCleared() OVERRIDE FINAL;
+    virtual LayerType layerTypeRequired() const OVERRIDE FINAL;
 
     virtual bool scroll(ScrollDirection, ScrollGranularity, float multiplier) OVERRIDE FINAL;
 
diff --git a/Source/core/rendering/RenderFieldset.cpp b/Source/core/rendering/RenderFieldset.cpp
index b3962cf..2537a9d 100644
--- a/Source/core/rendering/RenderFieldset.cpp
+++ b/Source/core/rendering/RenderFieldset.cpp
@@ -43,7 +43,7 @@
 
 void RenderFieldset::computePreferredLogicalWidths()
 {
-    RenderBlock::computePreferredLogicalWidths();
+    RenderBlockFlow::computePreferredLogicalWidths();
     if (RenderBox* legend = findLegend()) {
         int legendMinWidth = legend->minPreferredLogicalWidth();
 
@@ -143,7 +143,7 @@
     LayoutRect paintRect(paintOffset, size());
     RenderBox* legend = findLegend();
     if (!legend)
-        return RenderBlock::paintBoxDecorations(paintInfo, paintOffset);
+        return RenderBlockFlow::paintBoxDecorations(paintInfo, paintOffset);
 
     // FIXME: We need to work with "rl" and "bt" block flow directions.  In those
     // cases the legend is embedded in the right and bottom borders respectively.
@@ -194,7 +194,7 @@
     LayoutRect paintRect = LayoutRect(paintOffset, size());
     RenderBox* legend = findLegend();
     if (!legend)
-        return RenderBlock::paintMask(paintInfo, paintOffset);
+        return RenderBlockFlow::paintMask(paintInfo, paintOffset);
 
     // FIXME: We need to work with "rl" and "bt" block flow directions.  In those
     // cases the legend is embedded in the right and bottom borders respectively.
diff --git a/Source/core/rendering/RenderFieldset.h b/Source/core/rendering/RenderFieldset.h
index 944ab4c..545f10c 100644
--- a/Source/core/rendering/RenderFieldset.h
+++ b/Source/core/rendering/RenderFieldset.h
@@ -36,18 +36,18 @@
     RenderBox* findLegend(FindLegendOption = IgnoreFloatingOrOutOfFlow) const;
 
 private:
-    virtual const char* renderName() const { return "RenderFieldSet"; }
-    virtual bool isFieldset() const { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderFieldSet"; }
+    virtual bool isFieldset() const OVERRIDE { return true; }
 
-    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
+    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&) OVERRIDE;
 
-    virtual void computePreferredLogicalWidths();
-    virtual bool avoidsFloats() const { return true; }
+    virtual void computePreferredLogicalWidths() OVERRIDE;
+    virtual bool avoidsFloats() const OVERRIDE { return true; }
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
-    virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&);
-    virtual void paintMask(PaintInfo&, const LayoutPoint&);
+    virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual void paintMask(PaintInfo&, const LayoutPoint&) OVERRIDE;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderFieldset, isFieldset());
diff --git a/Source/core/rendering/RenderFileUploadControl.cpp b/Source/core/rendering/RenderFileUploadControl.cpp
index 80a822f..5829bec 100644
--- a/Source/core/rendering/RenderFileUploadControl.cpp
+++ b/Source/core/rendering/RenderFileUploadControl.cpp
@@ -143,7 +143,7 @@
     }
 
     // Paint the children.
-    RenderBlock::paintObject(paintInfo, paintOffset);
+    RenderBlockFlow::paintObject(paintInfo, paintOffset);
 }
 
 void RenderFileUploadControl::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
diff --git a/Source/core/rendering/RenderFileUploadControl.h b/Source/core/rendering/RenderFileUploadControl.h
index f83bb2a..85c4126 100644
--- a/Source/core/rendering/RenderFileUploadControl.h
+++ b/Source/core/rendering/RenderFileUploadControl.h
@@ -36,24 +36,24 @@
     RenderFileUploadControl(HTMLInputElement*);
     virtual ~RenderFileUploadControl();
 
-    virtual bool isFileUploadControl() const { return true; }
+    virtual bool isFileUploadControl() const OVERRIDE { return true; }
 
     String buttonValue();
     String fileTextValue() const;
 
 private:
-    virtual const char* renderName() const { return "RenderFileUploadControl"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderFileUploadControl"; }
 
-    virtual void updateFromElement();
+    virtual void updateFromElement() OVERRIDE;
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
-    virtual void computePreferredLogicalWidths();
-    virtual void paintObject(PaintInfo&, const LayoutPoint&);
+    virtual void computePreferredLogicalWidths() OVERRIDE;
+    virtual void paintObject(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
     int maxFilenameWidth() const;
 
-    virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE FINAL;
+    virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE;
 
     HTMLInputElement* uploadButton() const;
 
diff --git a/Source/core/rendering/RenderFlexibleBox.cpp b/Source/core/rendering/RenderFlexibleBox.cpp
index 65c8222..52772a5 100644
--- a/Source/core/rendering/RenderFlexibleBox.cpp
+++ b/Source/core/rendering/RenderFlexibleBox.cpp
@@ -31,11 +31,13 @@
 #include "config.h"
 #include "core/rendering/RenderFlexibleBox.h"
 
-#include <limits>
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
+#include "platform/LengthFunctions.h"
 #include "wtf/MathExtras.h"
+#include <limits>
 
 namespace WebCore {
 
@@ -141,8 +143,7 @@
     if (baseline == -1)
         baseline = synthesizedBaselineFromContentBox(this, direction);
 
-    int marginAscent = direction == HorizontalLine ? marginTop() : marginRight();
-    return baseline + marginAscent;
+    return beforeMarginInLineDirection(direction) + baseline;
 }
 
 int RenderFlexibleBox::firstLineBoxBaseline() const
@@ -154,7 +155,7 @@
     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
         if (child->isOutOfFlowPositioned())
             continue;
-        if (alignmentForChild(child) == AlignBaseline && !hasAutoMarginsInCrossAxis(child)) {
+        if (alignmentForChild(child) == ItemPositionBaseline && !hasAutoMarginsInCrossAxis(child)) {
             baselineChild = child;
             break;
         }
@@ -195,30 +196,36 @@
     return synthesizedBaselineFromContentBox(this, direction) + marginAscent;
 }
 
-static EAlignItems resolveAlignment(const RenderStyle* parentStyle, const RenderStyle* childStyle)
+static ItemPosition resolveAlignment(const RenderStyle* parentStyle, const RenderStyle* childStyle)
 {
-    EAlignItems align = childStyle->alignSelf();
-    if (align == AlignAuto)
+    ItemPosition align = childStyle->alignSelf();
+    if (align == ItemPositionAuto)
         align = parentStyle->alignItems();
     return align;
 }
 
+void RenderFlexibleBox::removeChild(RenderObject* child)
+{
+    RenderBlock::removeChild(child);
+    m_intrinsicSizeAlongMainAxis.remove(child);
+}
+
 void RenderFlexibleBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
     RenderBlock::styleDidChange(diff, oldStyle);
 
-    if (oldStyle && oldStyle->alignItems() == AlignStretch && diff == StyleDifferenceLayout) {
+    if (oldStyle && oldStyle->alignItems() == ItemPositionStretch && diff == StyleDifferenceLayout) {
         // Flex items that were previously stretching need to be relayed out so we can compute new available cross axis space.
         // This is only necessary for stretching since other alignment values don't change the size of the box.
         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
-            EAlignItems previousAlignment = resolveAlignment(oldStyle, child->style());
-            if (previousAlignment == AlignStretch && previousAlignment != resolveAlignment(style(), child->style()))
+            ItemPosition previousAlignment = resolveAlignment(oldStyle, child->style());
+            if (previousAlignment == ItemPositionStretch && previousAlignment != resolveAlignment(style(), child->style()))
                 child->setChildNeedsLayout(MarkOnlyThis);
         }
     }
 }
 
-void RenderFlexibleBox::layoutBlock(bool relayoutChildren, LayoutUnit)
+void RenderFlexibleBox::layoutBlock(bool relayoutChildren)
 {
     ASSERT(needsLayout());
 
@@ -226,6 +233,7 @@
         return;
 
     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
+    LayoutRectRecorder recorder(*this);
 
     if (updateLogicalWidthAndColumnWidth())
         relayoutChildren = true;
@@ -235,10 +243,7 @@
 
     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
 
-    // Regions changing widths can force us to relayout our children.
     RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (logicalWidthChangedInRegions(flowThread))
-        relayoutChildren = true;
     if (updateRegionsAndShapesLogicalSize(flowThread))
         relayoutChildren = true;
 
@@ -340,7 +345,7 @@
         LayoutUnit childLogicalBottom = logicalTopForChild(child) + logicalHeightForChild(child) + marginAfterForChild(child);
         maxChildLogicalBottom = std::max(maxChildLogicalBottom, childLogicalBottom);
     }
-    return std::max(clientLogicalBottom(), maxChildLogicalBottom);
+    return std::max(clientLogicalBottom(), maxChildLogicalBottom + paddingAfter());
 }
 
 bool RenderFlexibleBox::hasOrthogonalFlow(RenderBox* child) const
@@ -439,9 +444,7 @@
             child->layoutIfNeeded();
         return child->computeContentLogicalHeight(size, child->logicalHeight() - child->borderAndPaddingLogicalHeight());
     }
-    // FIXME: Figure out how this should work for regions and pass in the appropriate values.
-    RenderRegion* region = 0;
-    return child->computeLogicalWidthInRegionUsing(sizeType, size, contentLogicalWidth(), this, region) - child->borderAndPaddingLogicalWidth();
+    return child->computeLogicalWidthUsing(sizeType, size, contentLogicalWidth(), this) - child->borderAndPaddingLogicalWidth();
 }
 
 WritingMode RenderFlexibleBox::transformedWritingMode() const
@@ -633,20 +636,34 @@
     return isHorizontalFlow() ? child->verticalScrollbarWidth() : child->horizontalScrollbarHeight();
 }
 
-LayoutUnit RenderFlexibleBox::preferredMainAxisContentExtentForChild(RenderBox* child, bool hasInfiniteLineLength)
+static inline bool preferredMainAxisExtentDependsOnLayout(const Length& flexBasis, bool hasInfiniteLineLength)
 {
-    bool hasOverrideSize = child->hasOverrideWidth() || child->hasOverrideHeight();
-    if (hasOverrideSize)
-        child->clearOverrideSize();
+    return flexBasis.isAuto() || (flexBasis.isFixed() && !flexBasis.value() && hasInfiniteLineLength);
+}
+
+bool RenderFlexibleBox::childPreferredMainAxisContentExtentRequiresLayout(RenderBox* child, bool hasInfiniteLineLength) const
+{
+    return preferredMainAxisExtentDependsOnLayout(flexBasisForChild(child), hasInfiniteLineLength) && hasOrthogonalFlow(child);
+}
+
+LayoutUnit RenderFlexibleBox::preferredMainAxisContentExtentForChild(RenderBox* child, bool hasInfiniteLineLength, bool relayoutChildren)
+{
+    child->clearOverrideSize();
 
     Length flexBasis = flexBasisForChild(child);
-    if (flexBasis.isAuto() || (flexBasis.isFixed() && !flexBasis.value() && hasInfiniteLineLength)) {
+    if (preferredMainAxisExtentDependsOnLayout(flexBasis, hasInfiniteLineLength)) {
+        LayoutUnit mainAxisExtent;
         if (hasOrthogonalFlow(child)) {
-            if (hasOverrideSize)
-                child->setChildNeedsLayout(MarkOnlyThis);
-            child->layoutIfNeeded();
+            if (child->needsLayout() || relayoutChildren) {
+                m_intrinsicSizeAlongMainAxis.remove(child);
+                child->forceChildLayout();
+                m_intrinsicSizeAlongMainAxis.set(child, child->logicalHeight());
+            }
+            ASSERT(m_intrinsicSizeAlongMainAxis.contains(child));
+            mainAxisExtent = m_intrinsicSizeAlongMainAxis.get(child);
+        } else {
+            mainAxisExtent = child->maxPreferredLogicalWidth();
         }
-        LayoutUnit mainAxisExtent = hasOrthogonalFlow(child) ? child->logicalHeight() : child->maxPreferredLogicalWidth();
         ASSERT(mainAxisExtent - mainAxisBorderAndPaddingExtentForChild(child) >= 0);
         return mainAxisExtent - mainAxisBorderAndPaddingExtentForChild(child);
     }
@@ -661,21 +678,23 @@
     double totalWeightedFlexShrink;
     LayoutUnit sumHypotheticalMainSize;
 
+    Vector<LayoutUnit, 16> childSizes;
+
     m_orderIterator.first();
     LayoutUnit crossAxisOffset = flowAwareBorderBefore() + flowAwarePaddingBefore();
     bool hasInfiniteLineLength = false;
-    while (computeNextFlexLine(orderedChildren, sumFlexBaseSize, totalFlexGrow, totalWeightedFlexShrink, sumHypotheticalMainSize, hasInfiniteLineLength)) {
+    while (computeNextFlexLine(orderedChildren, sumFlexBaseSize, totalFlexGrow, totalWeightedFlexShrink, sumHypotheticalMainSize, hasInfiniteLineLength, relayoutChildren)) {
         LayoutUnit containerMainInnerSize = mainAxisContentExtent(sumHypotheticalMainSize);
         LayoutUnit availableFreeSpace = containerMainInnerSize - sumFlexBaseSize;
         FlexSign flexSign = (sumHypotheticalMainSize < containerMainInnerSize) ? PositiveFlexibility : NegativeFlexibility;
         InflexibleFlexItemSize inflexibleItems;
-        Vector<LayoutUnit> childSizes;
+        childSizes.reserveCapacity(orderedChildren.size());
         while (!resolveFlexibleLengths(flexSign, orderedChildren, availableFreeSpace, totalFlexGrow, totalWeightedFlexShrink, inflexibleItems, childSizes, hasInfiniteLineLength)) {
             ASSERT(totalFlexGrow >= 0 && totalWeightedFlexShrink >= 0);
             ASSERT(inflexibleItems.size() > 0);
         }
 
-        layoutAndPlaceChildren(crossAxisOffset, orderedChildren, childSizes, availableFreeSpace, relayoutChildren, lineContexts);
+        layoutAndPlaceChildren(crossAxisOffset, orderedChildren, childSizes, availableFreeSpace, relayoutChildren, lineContexts, hasInfiniteLineLength);
     }
     if (hasLineIfEmpty()) {
         // Even if computeNextFlexLine returns true, the flexbox might not have
@@ -814,17 +833,16 @@
     return ascent + flowAwareMarginBeforeForChild(child);
 }
 
-LayoutUnit RenderFlexibleBox::computeChildMarginValue(Length margin, RenderView* view)
+LayoutUnit RenderFlexibleBox::computeChildMarginValue(Length margin)
 {
     // When resolving the margins, we use the content size for resolving percent and calc (for percents in calc expressions) margins.
     // Fortunately, percent margins are always computed with respect to the block's width, even for margin-top and margin-bottom.
     LayoutUnit availableSize = contentLogicalWidth();
-    return minimumValueForLength(margin, availableSize, view);
+    return minimumValueForLength(margin, availableSize);
 }
 
 void RenderFlexibleBox::prepareOrderIteratorAndMargins()
 {
-    RenderView* renderView = view();
     OrderIteratorPopulator populator(m_orderIterator);
 
     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
@@ -836,11 +854,11 @@
         // Before running the flex algorithm, 'auto' has a margin of 0.
         // Also, if we're not auto sizing, we don't do a layout that computes the start/end margins.
         if (isHorizontalFlow()) {
-            child->setMarginLeft(computeChildMarginValue(child->style()->marginLeft(), renderView));
-            child->setMarginRight(computeChildMarginValue(child->style()->marginRight(), renderView));
+            child->setMarginLeft(computeChildMarginValue(child->style()->marginLeft()));
+            child->setMarginRight(computeChildMarginValue(child->style()->marginRight()));
         } else {
-            child->setMarginTop(computeChildMarginValue(child->style()->marginTop(), renderView));
-            child->setMarginBottom(computeChildMarginValue(child->style()->marginBottom(), renderView));
+            child->setMarginTop(computeChildMarginValue(child->style()->marginTop()));
+            child->setMarginBottom(computeChildMarginValue(child->style()->marginBottom()));
         }
     }
 }
@@ -861,7 +879,7 @@
     return std::max(childSize, minExtent);
 }
 
-bool RenderFlexibleBox::computeNextFlexLine(OrderedFlexItemList& orderedChildren, LayoutUnit& sumFlexBaseSize, double& totalFlexGrow, double& totalWeightedFlexShrink, LayoutUnit& sumHypotheticalMainSize, bool& hasInfiniteLineLength)
+bool RenderFlexibleBox::computeNextFlexLine(OrderedFlexItemList& orderedChildren, LayoutUnit& sumFlexBaseSize, double& totalFlexGrow, double& totalWeightedFlexShrink, LayoutUnit& sumHypotheticalMainSize, bool& hasInfiniteLineLength, bool relayoutChildren)
 {
     orderedChildren.clear();
     sumFlexBaseSize = 0;
@@ -882,7 +900,7 @@
             continue;
         }
 
-        LayoutUnit childMainAxisExtent = preferredMainAxisContentExtentForChild(child, hasInfiniteLineLength);
+        LayoutUnit childMainAxisExtent = preferredMainAxisContentExtentForChild(child, hasInfiniteLineLength, relayoutChildren);
         LayoutUnit childMainAxisMarginBorderPadding = mainAxisBorderAndPaddingExtentForChild(child)
             + (isHorizontalFlow() ? child->marginWidth() : child->marginHeight());
         LayoutUnit childFlexBaseSize = childMainAxisExtent + childMainAxisMarginBorderPadding;
@@ -916,9 +934,9 @@
 }
 
 // Returns true if we successfully ran the algorithm and sized the flex items.
-bool RenderFlexibleBox::resolveFlexibleLengths(FlexSign flexSign, const OrderedFlexItemList& children, LayoutUnit& availableFreeSpace, double& totalFlexGrow, double& totalWeightedFlexShrink, InflexibleFlexItemSize& inflexibleItems, Vector<LayoutUnit>& childSizes, bool hasInfiniteLineLength)
+bool RenderFlexibleBox::resolveFlexibleLengths(FlexSign flexSign, const OrderedFlexItemList& children, LayoutUnit& availableFreeSpace, double& totalFlexGrow, double& totalWeightedFlexShrink, InflexibleFlexItemSize& inflexibleItems, Vector<LayoutUnit, 16>& childSizes, bool hasInfiniteLineLength)
 {
-    childSizes.clear();
+    childSizes.resize(0);
     LayoutUnit totalViolation = 0;
     LayoutUnit usedFreeSpace = 0;
     Vector<Violation> minViolations;
@@ -1006,7 +1024,7 @@
     LayoutUnit inlinePosition = isColumnFlow() ? crossAxisOffset : mainAxisOffset;
     if (layoutMode == FlipForRowReverse && style()->flexDirection() == FlowRowReverse)
         inlinePosition = mainAxisExtent() - mainAxisOffset;
-    childLayer->setStaticInlinePosition(inlinePosition); // FIXME: Not right for regions.
+    childLayer->setStaticInlinePosition(inlinePosition);
 
     LayoutUnit staticBlockPosition = isColumnFlow() ? mainAxisOffset : crossAxisOffset;
     if (childLayer->staticBlockPosition() != staticBlockPosition) {
@@ -1016,18 +1034,18 @@
     }
 }
 
-EAlignItems RenderFlexibleBox::alignmentForChild(RenderBox* child) const
+ItemPosition RenderFlexibleBox::alignmentForChild(RenderBox* child) const
 {
-    EAlignItems align = resolveAlignment(style(), child->style());
+    ItemPosition align = resolveAlignment(style(), child->style());
 
-    if (align == AlignBaseline && hasOrthogonalFlow(child))
-        align = AlignFlexStart;
+    if (align == ItemPositionBaseline && hasOrthogonalFlow(child))
+        align = ItemPositionFlexStart;
 
     if (style()->flexWrap() == FlexWrapReverse) {
-        if (align == AlignFlexStart)
-            align = AlignFlexEnd;
-        else if (align == AlignFlexEnd)
-            align = AlignFlexStart;
+        if (align == ItemPositionFlexStart)
+            align = ItemPositionFlexEnd;
+        else if (align == ItemPositionFlexEnd)
+            align = ItemPositionFlexStart;
     }
 
     return align;
@@ -1044,22 +1062,25 @@
     return count;
 }
 
-bool RenderFlexibleBox::needToStretchChild(RenderBox* child)
-{
-    if (alignmentForChild(child) != AlignStretch)
-        return false;
-
-    Length crossAxisLength = isHorizontalFlow() ? child->style()->height() : child->style()->width();
-    return crossAxisLength.isAuto();
-}
-
 void RenderFlexibleBox::resetAutoMarginsAndLogicalTopInCrossAxis(RenderBox* child)
 {
-    if (hasAutoMarginsInCrossAxis(child))
+    if (hasAutoMarginsInCrossAxis(child)) {
         child->updateLogicalHeight();
+        if (isHorizontalFlow()) {
+            if (child->style()->marginTop().isAuto())
+                child->setMarginTop(0);
+            if (child->style()->marginBottom().isAuto())
+                child->setMarginBottom(0);
+        } else {
+            if (child->style()->marginLeft().isAuto())
+                child->setMarginLeft(0);
+            if (child->style()->marginRight().isAuto())
+                child->setMarginRight(0);
+        }
+    }
 }
 
-void RenderFlexibleBox::layoutAndPlaceChildren(LayoutUnit& crossAxisOffset, const OrderedFlexItemList& children, const Vector<LayoutUnit>& childSizes, LayoutUnit availableFreeSpace, bool relayoutChildren, Vector<LineContext>& lineContexts)
+void RenderFlexibleBox::layoutAndPlaceChildren(LayoutUnit& crossAxisOffset, const OrderedFlexItemList& children, const Vector<LayoutUnit, 16>& childSizes, LayoutUnit availableFreeSpace, bool relayoutChildren, Vector<LineContext>& lineContexts, bool hasInfiniteLineLength)
 {
     ASSERT(childSizes.size() == children.size());
 
@@ -1077,6 +1098,8 @@
     bool shouldFlipMainAxis = !isColumnFlow() && !isLeftToRightFlow();
     for (size_t i = 0; i < children.size(); ++i) {
         RenderBox* child = children[i];
+        LayoutRectRecorder recorder(*child);
+
         if (child->isOutOfFlowPositioned()) {
             prepareChildForPositionedLayout(child, mainAxisOffset, crossAxisOffset, FlipForRowReverse);
             continue;
@@ -1084,20 +1107,21 @@
 
         LayoutUnit childPreferredSize = childSizes[i] + mainAxisBorderAndPaddingExtentForChild(child);
         setLogicalOverrideSize(child, childPreferredSize);
-        // FIXME: Can avoid laying out here in some cases. See https://webkit.org/b/87905.
-        if (needToStretchChild(child) || childPreferredSize != mainAxisExtentForChild(child))
+        if (childPreferredSize != mainAxisExtentForChild(child)) {
             child->setChildNeedsLayout(MarkOnlyThis);
-        else {
+        } else {
             // To avoid double applying margin changes in updateAutoMarginsInCrossAxis, we reset the margins here.
             resetAutoMarginsAndLogicalTopInCrossAxis(child);
         }
-        updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
+        // We may have already forced relayout for orthogonal flowing children in preferredMainAxisContentExtentForChild.
+        bool forceChildRelayout = relayoutChildren && !childPreferredMainAxisContentExtentRequiresLayout(child, hasInfiniteLineLength);
+        updateBlockChildDirtyBitsBeforeLayout(forceChildRelayout, child);
         child->layoutIfNeeded();
 
         updateAutoMarginsInMainAxis(child, autoMarginOffset);
 
         LayoutUnit childCrossAxisMarginBoxExtent;
-        if (alignmentForChild(child) == AlignBaseline && !hasAutoMarginsInCrossAxis(child)) {
+        if (alignmentForChild(child) == ItemPositionBaseline && !hasAutoMarginsInCrossAxis(child)) {
             LayoutUnit ascent = marginBoxAscentForChild(child);
             LayoutUnit descent = (crossAxisMarginExtentForChild(child) + crossAxisExtentForChild(child)) - ascent;
 
@@ -1157,6 +1181,8 @@
     size_t seenInFlowPositionedChildren = 0;
     for (size_t i = 0; i < children.size(); ++i) {
         RenderBox* child = children[i];
+        LayoutRectRecorder recorder(*child);
+
         if (child->isOutOfFlowPositioned()) {
             child->layer()->setStaticBlockPosition(mainAxisOffset);
             continue;
@@ -1260,25 +1286,25 @@
                 continue;
 
             switch (alignmentForChild(child)) {
-            case AlignAuto:
+            case ItemPositionAuto:
                 ASSERT_NOT_REACHED();
                 break;
-            case AlignStretch: {
+            case ItemPositionStretch: {
                 applyStretchAlignmentToChild(child, lineCrossAxisExtent);
                 // Since wrap-reverse flips cross start and cross end, strech children should be aligned with the cross end.
                 if (style()->flexWrap() == FlexWrapReverse)
                     adjustAlignmentForChild(child, availableAlignmentSpaceForChild(lineCrossAxisExtent, child));
                 break;
             }
-            case AlignFlexStart:
+            case ItemPositionFlexStart:
                 break;
-            case AlignFlexEnd:
+            case ItemPositionFlexEnd:
                 adjustAlignmentForChild(child, availableAlignmentSpaceForChild(lineCrossAxisExtent, child));
                 break;
-            case AlignCenter:
+            case ItemPositionCenter:
                 adjustAlignmentForChild(child, availableAlignmentSpaceForChild(lineCrossAxisExtent, child) / 2);
                 break;
-            case AlignBaseline: {
+            case ItemPositionBaseline: {
                 // FIXME: If we get here in columns, we want the use the descent, except we currently can't get the ascent/descent of orthogonal children.
                 // https://bugs.webkit.org/show_bug.cgi?id=98076
                 LayoutUnit ascent = marginBoxAscentForChild(child);
@@ -1289,6 +1315,16 @@
                     minMarginAfterBaseline = std::min(minMarginAfterBaseline, availableAlignmentSpaceForChild(lineCrossAxisExtent, child) - startOffset);
                 break;
             }
+            case ItemPositionSelfStart:
+            case ItemPositionSelfEnd:
+            case ItemPositionStart:
+            case ItemPositionEnd:
+            case ItemPositionLeft:
+            case ItemPositionRight:
+                // FIXME: File a bug about implementing that. The extended grammar
+                // is not enabled by default so we shouldn't hit this codepath.
+                ASSERT_NOT_REACHED();
+                break;
             }
         }
         minMarginAfterBaselines.append(minMarginAfterBaseline);
@@ -1304,7 +1340,7 @@
         LayoutUnit minMarginAfterBaseline = minMarginAfterBaselines[lineNumber];
         for (size_t childNumber = 0; childNumber < lineContexts[lineNumber].numberOfChildren; ++childNumber, child = m_orderIterator.next()) {
             ASSERT(child);
-            if (alignmentForChild(child) == AlignBaseline && !hasAutoMarginsInCrossAxis(child) && minMarginAfterBaseline)
+            if (alignmentForChild(child) == ItemPositionBaseline && !hasAutoMarginsInCrossAxis(child) && minMarginAfterBaseline)
                 adjustAlignmentForChild(child, minMarginAfterBaseline);
         }
     }
@@ -1330,7 +1366,7 @@
         // FIXME: If the child doesn't have orthogonal flow, then it already has an override width set, so use it.
         if (hasOrthogonalFlow(child)) {
             LayoutUnit childWidth = std::max<LayoutUnit>(0, lineCrossAxisExtent - crossAxisMarginExtentForChild(child));
-            childWidth = child->constrainLogicalWidthInRegionByMinMax(childWidth, childWidth, this);
+            childWidth = child->constrainLogicalWidthByMinMax(childWidth, childWidth, this);
 
             if (childWidth != child->logicalWidth()) {
                 child->setOverrideLogicalContentWidth(childWidth - child->borderAndPaddingLogicalWidth());
diff --git a/Source/core/rendering/RenderFlexibleBox.h b/Source/core/rendering/RenderFlexibleBox.h
index c9297da..0801168 100644
--- a/Source/core/rendering/RenderFlexibleBox.h
+++ b/Source/core/rendering/RenderFlexibleBox.h
@@ -47,8 +47,8 @@
 
     virtual bool isFlexibleBox() const OVERRIDE FINAL { return true; }
     virtual bool avoidsFloats() const OVERRIDE FINAL { return true; }
-    virtual bool canCollapseAnonymousBlockChild() const OVERRIDE FINAL { return false; }
-    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE FINAL;
+    virtual bool canCollapseAnonymousBlockChild() const OVERRIDE { return false; }
+    virtual void layoutBlock(bool relayoutChildren) OVERRIDE FINAL;
 
     virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
     virtual int firstLineBoxBaseline() const OVERRIDE;
@@ -63,7 +63,8 @@
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+    virtual void removeChild(RenderObject*) OVERRIDE;
 
 private:
     enum FlexSign {
@@ -117,10 +118,11 @@
     // FIXME: Supporting layout deltas.
     void setFlowAwareLocationForChild(RenderBox* child, const LayoutPoint&);
     void adjustAlignmentForChild(RenderBox* child, LayoutUnit);
-    EAlignItems alignmentForChild(RenderBox* child) const;
+    ItemPosition alignmentForChild(RenderBox* child) const;
     LayoutUnit mainAxisBorderAndPaddingExtentForChild(RenderBox* child) const;
     LayoutUnit mainAxisScrollbarExtentForChild(RenderBox* child) const;
-    LayoutUnit preferredMainAxisContentExtentForChild(RenderBox* child, bool hasInfiniteLineLength);
+    LayoutUnit preferredMainAxisContentExtentForChild(RenderBox* child, bool hasInfiniteLineLength, bool relayoutChildren = false);
+    bool childPreferredMainAxisContentExtentRequiresLayout(RenderBox* child, bool hasInfiniteLineLength) const;
 
     void layoutFlexItems(bool relayoutChildren, Vector<LineContext>&);
     LayoutUnit autoMarginOffsetInMainAxis(const OrderedFlexItemList&, LayoutUnit& availableFreeSpace);
@@ -135,21 +137,20 @@
     LayoutUnit availableAlignmentSpaceForChild(LayoutUnit lineCrossAxisExtent, RenderBox*);
     LayoutUnit marginBoxAscentForChild(RenderBox*);
 
-    LayoutUnit computeChildMarginValue(Length margin, RenderView*);
+    LayoutUnit computeChildMarginValue(Length margin);
     void prepareOrderIteratorAndMargins();
     LayoutUnit adjustChildSizeForMinAndMax(RenderBox*, LayoutUnit childSize);
     // The hypothetical main size of an item is the flex base size clamped according to its min and max main size properties
-    bool computeNextFlexLine(OrderedFlexItemList& orderedChildren, LayoutUnit& sumFlexBaseSize, double& totalFlexGrow, double& totalWeightedFlexShrink, LayoutUnit& sumHypotheticalMainSize, bool& hasInfiniteLineLength);
+    bool computeNextFlexLine(OrderedFlexItemList& orderedChildren, LayoutUnit& sumFlexBaseSize, double& totalFlexGrow, double& totalWeightedFlexShrink, LayoutUnit& sumHypotheticalMainSize, bool& hasInfiniteLineLength, bool relayoutChildren);
 
-    bool resolveFlexibleLengths(FlexSign, const OrderedFlexItemList&, LayoutUnit& availableFreeSpace, double& totalFlexGrow, double& totalWeightedFlexShrink, InflexibleFlexItemSize&, Vector<LayoutUnit>& childSizes, bool hasInfiniteLineLength);
+    bool resolveFlexibleLengths(FlexSign, const OrderedFlexItemList&, LayoutUnit& availableFreeSpace, double& totalFlexGrow, double& totalWeightedFlexShrink, InflexibleFlexItemSize&, Vector<LayoutUnit, 16>& childSizes, bool hasInfiniteLineLength);
     void freezeViolations(const Vector<Violation>&, LayoutUnit& availableFreeSpace, double& totalFlexGrow, double& totalWeightedFlexShrink, InflexibleFlexItemSize&, bool hasInfiniteLineLength);
 
     void resetAutoMarginsAndLogicalTopInCrossAxis(RenderBox*);
-    bool needToStretchChild(RenderBox*);
     void setLogicalOverrideSize(RenderBox* child, LayoutUnit childPreferredSize);
     void prepareChildForPositionedLayout(RenderBox* child, LayoutUnit mainAxisOffset, LayoutUnit crossAxisOffset, PositionedLayoutMode);
     size_t numberOfInFlowPositionedChildren(const OrderedFlexItemList&) const;
-    void layoutAndPlaceChildren(LayoutUnit& crossAxisOffset, const OrderedFlexItemList&, const Vector<LayoutUnit>& childSizes, LayoutUnit availableFreeSpace, bool relayoutChildren, Vector<LineContext>&);
+    void layoutAndPlaceChildren(LayoutUnit& crossAxisOffset, const OrderedFlexItemList&, const Vector<LayoutUnit, 16>& childSizes, LayoutUnit availableFreeSpace, bool relayoutChildren, Vector<LineContext>&, bool hasInfiniteLineLength);
     void layoutColumnReverse(const OrderedFlexItemList&, LayoutUnit crossAxisOffset, LayoutUnit availableFreeSpace);
     void alignFlexLines(Vector<LineContext>&);
     void alignChildren(const Vector<LineContext>&);
@@ -157,6 +158,9 @@
     void flipForRightToLeftColumn();
     void flipForWrapReverse(const Vector<LineContext>&, LayoutUnit crossAxisStartEdge);
 
+    // This is used to cache the preferred size for orthogonal flow children so we don't have to relayout to get it
+    HashMap<const RenderObject*, LayoutUnit> m_intrinsicSizeAlongMainAxis;
+
     mutable OrderIterator m_orderIterator;
     int m_numberOfInFlowChildrenOnFirstLine;
 };
diff --git a/Source/core/rendering/RenderFlowThread.cpp b/Source/core/rendering/RenderFlowThread.cpp
index 2e9bb88..a42e8b6 100644
--- a/Source/core/rendering/RenderFlowThread.cpp
+++ b/Source/core/rendering/RenderFlowThread.cpp
@@ -37,7 +37,6 @@
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderBoxRegionInfo.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderRegion.h"
@@ -50,16 +49,9 @@
 RenderFlowThread::RenderFlowThread()
     : RenderBlockFlow(0)
     , m_previousRegionCount(0)
-    , m_autoLogicalHeightRegionsCount(0)
     , m_regionsInvalidated(false)
-    , m_regionsHaveUniformLogicalWidth(true)
     , m_regionsHaveUniformLogicalHeight(true)
-    , m_hasRegionsWithStyling(false)
-    , m_dispatchRegionLayoutUpdateEvent(false)
-    , m_dispatchRegionOversetChangeEvent(false)
     , m_pageLogicalSizeChanged(false)
-    , m_inConstrainedLayoutPhase(false)
-    , m_needsTwoPhasesLayout(false)
 {
     setFlowThreadState(InsideOutOfFlowThread);
 }
@@ -80,21 +72,6 @@
     return newStyle.release();
 }
 
-void RenderFlowThread::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
-    RenderBlock::styleDidChange(diff, oldStyle);
-
-    if (oldStyle && oldStyle->writingMode() != style()->writingMode())
-        invalidateRegions();
-}
-
-void RenderFlowThread::removeFlowChildInfo(RenderObject* child)
-{
-    if (child->isBox())
-        removeRenderBoxRegionInfo(toRenderBox(child));
-    clearRenderObjectCustomStyle(child);
-}
-
 void RenderFlowThread::addRegionToThread(RenderRegion* renderRegion)
 {
     ASSERT(renderRegion);
@@ -116,8 +93,6 @@
     }
 
     m_regionRangeMap.clear();
-    m_breakBeforeToRegionMap.clear();
-    m_breakAfterToRegionMap.clear();
     setNeedsLayout();
 
     m_regionsInvalidated = true;
@@ -148,7 +123,6 @@
 {
     if (m_regionsInvalidated) {
         m_regionsInvalidated = false;
-        m_regionsHaveUniformLogicalWidth = true;
         m_regionsHaveUniformLogicalHeight = true;
 
         if (hasRegions()) {
@@ -158,27 +132,12 @@
 
             for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
                 RenderRegion* region = *iter;
-                ASSERT(!region->needsLayout() || region->isRenderRegionSet());
-
-                region->deleteAllRenderBoxRegionInfo();
-
-                // In the normal layout phase we need to initialize the computedAutoHeight for auto-height regions.
-                // See initializeRegionsComputedAutoHeight for the explanation.
-                // Also, if we have auto-height regions we can't assume m_regionsHaveUniformLogicalHeight to be true in the first phase
-                // because the auto-height regions don't have their height computed yet.
-                if (!inConstrainedLayoutPhase() && region->hasAutoLogicalHeight()) {
-                    region->setComputedAutoHeight(region->maxPageLogicalHeight());
-                    m_regionsHaveUniformLogicalHeight = false;
-                }
-
                 LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
                 LayoutUnit regionLogicalHeight = region->pageLogicalHeight();
 
                 if (!firstRegionVisited) {
                     firstRegionVisited = true;
                 } else {
-                    if (m_regionsHaveUniformLogicalWidth && previousRegionLogicalWidth != regionLogicalWidth)
-                        m_regionsHaveUniformLogicalWidth = false;
                     if (m_regionsHaveUniformLogicalHeight && previousRegionLogicalHeight != regionLogicalHeight)
                         m_regionsHaveUniformLogicalHeight = false;
                 }
@@ -197,17 +156,8 @@
     LayoutRectRecorder recorder(*this);
     m_pageLogicalSizeChanged = m_regionsInvalidated && everHadLayout();
 
-    // In case this is the second pass of the normal phase we need to update the auto-height regions to their initial value.
-    // If the region chain was invalidated this will happen anyway.
-    if (!m_regionsInvalidated && !inConstrainedLayoutPhase())
-        initializeRegionsComputedAutoHeight();
-
     validateRegions();
 
-    // This is the first phase of the layout and because we have auto-height regions we'll need a second
-    // pass to update the flow with the computed auto-height regions.
-    m_needsTwoPhasesLayout = !inConstrainedLayoutPhase() && hasAutoLogicalHeightRegions();
-
     CurrentRenderFlowThreadMaintainer currentFlowThreadSetter(this);
     RenderBlockFlow::layout();
 
@@ -215,33 +165,11 @@
 
     if (lastRegion())
         lastRegion()->expandToEncompassFlowThreadContentsIfNeeded();
-
-    if (shouldDispatchRegionLayoutUpdateEvent())
-        dispatchRegionLayoutUpdateEvent();
-
-    if (shouldDispatchRegionOversetChangeEvent())
-        dispatchRegionOversetChangeEvent();
 }
 
 void RenderFlowThread::updateLogicalWidth()
 {
-    LayoutUnit logicalWidth = initialLogicalWidth();
-    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        ASSERT(!region->needsLayout() || region->isRenderRegionSet());
-        logicalWidth = max(region->pageLogicalWidth(), logicalWidth);
-    }
-    setLogicalWidth(logicalWidth);
-
-    // If the regions have non-uniform logical widths, then insert inset information for the RenderFlowThread.
-    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
-        if (regionLogicalWidth != logicalWidth) {
-            LayoutUnit logicalLeft = style()->direction() == LTR ? LayoutUnit() : logicalWidth - regionLogicalWidth;
-            region->setRenderBoxRegionInfo(this, logicalLeft, regionLogicalWidth, false);
-        }
-    }
+    setLogicalWidth(initialLogicalWidth());
 }
 
 void RenderFlowThread::computeLogicalHeight(LayoutUnit, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
@@ -251,8 +179,6 @@
 
     for (RenderRegionList::const_iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
         RenderRegion* region = *iter;
-        ASSERT(!region->needsLayout() || region->isRenderRegionSet());
-
         computedValues.m_extent += region->logicalHeightOfAllFlowThreadContent();
     }
 }
@@ -265,90 +191,11 @@
     return regionClippingRect;
 }
 
-void RenderFlowThread::paintFlowThreadPortionInRegion(PaintInfo& paintInfo, RenderRegion* region, const LayoutRect& flowThreadPortionRect, const LayoutRect& flowThreadPortionOverflowRect, const LayoutPoint& paintOffset) const
-{
-    GraphicsContext* context = paintInfo.context;
-    if (!context)
-        return;
-
-    // RenderFlowThread should start painting its content in a position that is offset
-    // from the region rect's current position. The amount of offset is equal to the location of
-    // the flow thread portion in the flow thread's local coordinates.
-    // Note that we have to pixel snap the location at which we're going to paint, since this is necessary
-    // to minimize the amount of incorrect snapping that would otherwise occur.
-    // If we tried to paint by applying a non-integral translation, then all the
-    // layout code that attempted to pixel snap would be incorrect.
-    IntPoint adjustedPaintOffset;
-    LayoutPoint portionLocation;
-    if (style()->isFlippedBlocksWritingMode()) {
-        LayoutRect flippedFlowThreadPortionRect(flowThreadPortionRect);
-        flipForWritingMode(flippedFlowThreadPortionRect);
-        portionLocation = flippedFlowThreadPortionRect.location();
-    } else {
-        portionLocation = flowThreadPortionRect.location();
-    }
-    adjustedPaintOffset = roundedIntPoint(paintOffset - portionLocation);
-
-    // The clipping rect for the region is set up by assuming the flowThreadPortionRect is going to paint offset from adjustedPaintOffset.
-    // Remember that we pixel snapped and moved the paintOffset and stored the snapped result in adjustedPaintOffset. Now we add back in
-    // the flowThreadPortionRect's location to get the spot where we expect the portion to actually paint. This can be non-integral and
-    // that's ok. We then pixel snap the resulting clipping rect to account for snapping that will occur when the flow thread paints.
-    IntRect regionClippingRect = pixelSnappedIntRect(computeRegionClippingRect(adjustedPaintOffset + portionLocation, flowThreadPortionRect, flowThreadPortionOverflowRect));
-
-    PaintInfo info(paintInfo);
-    info.rect.intersect(regionClippingRect);
-
-    if (!info.rect.isEmpty()) {
-        context->save();
-
-        context->clip(regionClippingRect);
-
-        context->translate(adjustedPaintOffset.x(), adjustedPaintOffset.y());
-        info.rect.moveBy(-adjustedPaintOffset);
-
-        if (info.phase == PaintPhaseTextClip)
-            info.paintBehavior = PaintBehaviorForceBlackText;
-
-        layer()->paint(context, info.rect, info.paintBehavior, 0, region, PaintLayerTemporaryClipRects);
-
-        context->restore();
-    }
-}
-
 bool RenderFlowThread::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
 {
     if (hitTestAction == HitTestBlockBackground)
         return false;
-    return RenderBlock::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction);
-}
-
-bool RenderFlowThread::hitTestFlowThreadPortionInRegion(RenderRegion* region, const LayoutRect& flowThreadPortionRect, const LayoutRect& flowThreadPortionOverflowRect, const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) const
-{
-    LayoutRect regionClippingRect = computeRegionClippingRect(accumulatedOffset, flowThreadPortionRect, flowThreadPortionOverflowRect);
-    if (!regionClippingRect.contains(locationInContainer.point()))
-        return false;
-
-    LayoutSize renderFlowThreadOffset;
-    if (style()->isFlippedBlocksWritingMode()) {
-        LayoutRect flippedFlowThreadPortionRect(flowThreadPortionRect);
-        flipForWritingMode(flippedFlowThreadPortionRect);
-        renderFlowThreadOffset = accumulatedOffset - flippedFlowThreadPortionRect.location();
-    } else {
-        renderFlowThreadOffset = accumulatedOffset - flowThreadPortionRect.location();
-    }
-
-    // Always ignore clipping, since the RenderFlowThread has nothing to do with the bounds of the FrameView.
-    HitTestRequest newRequest(request.type() | HitTestRequest::IgnoreClipping | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
-
-    // Make a new temporary HitTestLocation in the new region.
-    HitTestLocation newHitTestLocation(locationInContainer, -renderFlowThreadOffset, region);
-
-    bool isPointInsideFlowThread = layer()->hitTest(newRequest, newHitTestLocation, result);
-
-    // FIXME: Should we set result.m_localPoint back to the RenderRegion's coordinate space or leave it in the RenderFlowThread's coordinate
-    // space? Right now it's staying in the RenderFlowThread's coordinate space, which may end up being ok. We will know more when we get around to
-    // patching positionForPoint.
-    return isPointInsideFlowThread;
+    return RenderBlockFlow::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction);
 }
 
 bool RenderFlowThread::shouldRepaint(const LayoutRect& r) const
@@ -392,7 +239,7 @@
 
     // If no region was found, the offset is in the flow thread overflow.
     // The last region will contain the offset if extendLastRegion is set or if the last region is a set.
-    if (!adapter.result() && !m_regionList.isEmpty() && (extendLastRegion || m_regionList.last()->isRenderRegionSet()))
+    if (!adapter.result() && !m_regionList.isEmpty())
         return m_regionList.last();
 
     return adapter.result();
@@ -430,9 +277,8 @@
     // FIXME: This needs to be adapted for different writing modes inside the flow thread.
     RenderRegion* startRegion = regionAtBlockOffset(referencePoint.y());
     if (startRegion) {
-        RenderBoxModelObject* startRegionBox = startRegion->isRenderNamedFlowFragment() ? toRenderBoxModelObject(startRegion->parent()) : startRegion;
         // Take into account the offset coordinates of the region.
-        RenderObject* currObject = startRegionBox;
+        RenderObject* currObject = startRegion;
         RenderObject* currOffsetParentRenderer;
         Element* currOffsetParentElement;
         while ((currOffsetParentElement = currObject->offsetParent()) && (currOffsetParentRenderer = currOffsetParentElement->renderer())) {
@@ -452,7 +298,7 @@
         // and is no longer valid) and recompute it using the region in which it flows as reference.
         bool wasComputedRelativeToOtherRegion = false;
         const RenderBlock* objContainingBlock = boxModelObject.containingBlock();
-        while (objContainingBlock && !objContainingBlock->isRenderNamedFlowThread()) {
+        while (objContainingBlock) {
             // Check if this object is in a different region.
             RenderRegion* parentStartRegion = 0;
             RenderRegion* parentEndRegion = 0;
@@ -465,12 +311,6 @@
         }
 
         if (wasComputedRelativeToOtherRegion) {
-            if (boxModelObject.isBox()) {
-                // Use borderBoxRectInRegion to account for variations such as percentage margins.
-                LayoutRect borderBoxRect = toRenderBox(&boxModelObject)->borderBoxRectInRegion(startRegion, RenderBox::DoNotCacheRenderBoxRegionInfo);
-                referencePoint.move(borderBoxRect.location().x(), 0);
-            }
-
             // Get the logical top coordinate of the current object.
             LayoutUnit top = 0;
             if (boxModelObject.isRenderBlock()) {
@@ -489,7 +329,7 @@
             // and compute the object's top, relative to the region's top.
             LayoutUnit regionLogicalTop = startRegion->pageLogicalTopForOffset(top);
             LayoutUnit topRelativeToRegion = top - regionLogicalTop;
-            referencePoint.setY(startRegionBox->offsetTop() + topRelativeToRegion);
+            referencePoint.setY(startRegion->offsetTop() + topRelativeToRegion);
 
             // Since the top has been overriden, check if the
             // relative/sticky positioning must be reconsidered.
@@ -501,7 +341,7 @@
 
         // Since we're looking for the offset relative to the body, we must also
         // take into consideration the borders of the region.
-        referencePoint.move(startRegionBox->borderLeft(), startRegionBox->borderTop());
+        referencePoint.move(startRegion->borderLeft(), startRegion->borderTop());
     }
 
     return referencePoint;
@@ -571,100 +411,6 @@
     return renderRegion;
 }
 
-void RenderFlowThread::removeRenderBoxRegionInfo(RenderBox* box)
-{
-    if (!hasRegions())
-        return;
-
-    // If the region chain was invalidated the next layout will clear the box information from all the regions.
-    if (m_regionsInvalidated) {
-        ASSERT(selfNeedsLayout());
-        return;
-    }
-
-    RenderRegion* startRegion;
-    RenderRegion* endRegion;
-    getRegionRangeForBox(box, startRegion, endRegion);
-
-    for (RenderRegionList::iterator iter = m_regionList.find(startRegion); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        region->removeRenderBoxRegionInfo(box);
-        if (region == endRegion)
-            break;
-    }
-
-#ifndef NDEBUG
-    // We have to make sure we did not leave any RenderBoxRegionInfo attached.
-    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        ASSERT(!region->renderBoxRegionInfo(box));
-    }
-#endif
-
-    m_regionRangeMap.remove(box);
-}
-
-bool RenderFlowThread::logicalWidthChangedInRegionsForBlock(const RenderBlock* block)
-{
-    if (!hasRegions())
-        return false;
-
-    RenderRegion* startRegion;
-    RenderRegion* endRegion;
-    getRegionRangeForBox(block, startRegion, endRegion);
-
-    // When the region chain is invalidated the box information is discarded so we must assume the width has changed.
-    if (m_pageLogicalSizeChanged && !startRegion)
-        return true;
-
-    // Not necessary for the flow thread, since we already computed the correct info for it.
-    if (block == this)
-        return false;
-
-    for (RenderRegionList::iterator iter = m_regionList.find(startRegion); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        ASSERT(!region->needsLayout() || region->isRenderRegionSet());
-
-        OwnPtr<RenderBoxRegionInfo> oldInfo = region->takeRenderBoxRegionInfo(block);
-        if (!oldInfo)
-            continue;
-
-        LayoutUnit oldLogicalWidth = oldInfo->logicalWidth();
-        RenderBoxRegionInfo* newInfo = block->renderBoxRegionInfo(region);
-        if (!newInfo || newInfo->logicalWidth() != oldLogicalWidth)
-            return true;
-
-        if (region == endRegion)
-            break;
-    }
-
-    return false;
-}
-
-LayoutUnit RenderFlowThread::contentLogicalWidthOfFirstRegion() const
-{
-    RenderRegion* firstValidRegionInFlow = firstRegion();
-    if (!firstValidRegionInFlow)
-        return 0;
-    return isHorizontalWritingMode() ? firstValidRegionInFlow->contentWidth() : firstValidRegionInFlow->contentHeight();
-}
-
-LayoutUnit RenderFlowThread::contentLogicalHeightOfFirstRegion() const
-{
-    RenderRegion* firstValidRegionInFlow = firstRegion();
-    if (!firstValidRegionInFlow)
-        return 0;
-    return isHorizontalWritingMode() ? firstValidRegionInFlow->contentHeight() : firstValidRegionInFlow->contentWidth();
-}
-
-LayoutUnit RenderFlowThread::contentLogicalLeftOfFirstRegion() const
-{
-    RenderRegion* firstValidRegionInFlow = firstRegion();
-    if (!firstValidRegionInFlow)
-        return 0;
-    return isHorizontalWritingMode() ? firstValidRegionInFlow->flowThreadPortionRect().x() : firstValidRegionInFlow->flowThreadPortionRect().y();
-}
-
 RenderRegion* RenderFlowThread::firstRegion() const
 {
     if (!hasValidRegionInfo())
@@ -679,32 +425,6 @@
     return m_regionList.last();
 }
 
-void RenderFlowThread::clearRenderObjectCustomStyle(const RenderObject* object,
-    const RenderRegion* oldStartRegion, const RenderRegion* oldEndRegion,
-    const RenderRegion* newStartRegion, const RenderRegion* newEndRegion)
-{
-    // Clear the styles for the object in the regions.
-    // The styles are not cleared for the regions that are contained in both ranges.
-    bool insideOldRegionRange = false;
-    bool insideNewRegionRange = false;
-    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-
-        if (oldStartRegion == region)
-            insideOldRegionRange = true;
-        if (newStartRegion == region)
-            insideNewRegionRange = true;
-
-        if (!(insideOldRegionRange && insideNewRegionRange))
-            region->clearObjectStyleInRegion(object);
-
-        if (oldEndRegion == region)
-            insideOldRegionRange = false;
-        if (newEndRegion == region)
-            insideNewRegionRange = false;
-    }
-}
-
 void RenderFlowThread::setRegionRangeForBox(const RenderBox* box, LayoutUnit offsetFromLogicalTopOfFirstPage)
 {
     if (!hasRegions())
@@ -716,7 +436,6 @@
     RenderRegionRangeMap::iterator it = m_regionRangeMap.find(box);
     if (it == m_regionRangeMap.end()) {
         m_regionRangeMap.set(box, RenderRegionRange(startRegion, endRegion));
-        clearRenderObjectCustomStyle(box);
         return;
     }
 
@@ -725,21 +444,6 @@
     if (range.startRegion() == startRegion && range.endRegion() == endRegion)
         return;
 
-    // Delete any info that we find before our new startRegion and after our new endRegion.
-    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        if (region == startRegion) {
-            iter = m_regionList.find(endRegion);
-            continue;
-        }
-
-        region->removeRenderBoxRegionInfo(box);
-
-        if (region == range.endRegion())
-            break;
-    }
-
-    clearRenderObjectCustomStyle(box, range.startRegion(), range.endRegion(), startRegion, endRegion);
     range.setRange(startRegion, endRegion);
 }
 
@@ -779,126 +483,15 @@
     return false;
 }
 
-// Check if the content is flown into at least a region with region styling rules.
-void RenderFlowThread::checkRegionsWithStyling()
+void RenderFlowThread::updateRegionsFlowThreadPortionRect()
 {
-    bool hasRegionsWithStyling = false;
-    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        if (region->hasCustomRegionStyle()) {
-            hasRegionsWithStyling = true;
-            break;
-        }
-    }
-    m_hasRegionsWithStyling = hasRegionsWithStyling;
-}
-
-bool RenderFlowThread::objectInFlowRegion(const RenderObject* object, const RenderRegion* region) const
-{
-    ASSERT(object);
-    ASSERT(region);
-
-    RenderFlowThread* flowThread = object->flowThreadContainingBlock();
-    if (flowThread != this)
-        return false;
-    if (!m_regionList.contains(const_cast<RenderRegion*>(region)))
-        return false;
-
-    RenderBox* enclosingBox = object->enclosingBox();
-    RenderRegion* enclosingBoxStartRegion = 0;
-    RenderRegion* enclosingBoxEndRegion = 0;
-    getRegionRangeForBox(enclosingBox, enclosingBoxStartRegion, enclosingBoxEndRegion);
-    if (!regionInRange(region, enclosingBoxStartRegion, enclosingBoxEndRegion))
-        return false;
-
-    if (object->isBox())
-        return true;
-
-    LayoutRect objectABBRect = object->absoluteBoundingBoxRect(true);
-    if (!objectABBRect.width())
-        objectABBRect.setWidth(1);
-    if (!objectABBRect.height())
-        objectABBRect.setHeight(1);
-    if (objectABBRect.intersects(region->absoluteBoundingBoxRect(true)))
-        return true;
-
-    if (region == lastRegion()) {
-        // If the object does not intersect any of the enclosing box regions
-        // then the object is in last region.
-        for (RenderRegionList::const_iterator it = m_regionList.find(enclosingBoxStartRegion); it != m_regionList.end(); ++it) {
-            const RenderRegion* currRegion = *it;
-            if (currRegion == region)
-                break;
-            if (objectABBRect.intersects(currRegion->absoluteBoundingBoxRect(true)))
-                return false;
-        }
-        return true;
-    }
-
-    return false;
-}
-
-#ifndef NDEBUG
-bool RenderFlowThread::isAutoLogicalHeightRegionsCountConsistent() const
-{
-    unsigned autoLogicalHeightRegions = 0;
-    for (RenderRegionList::const_iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        const RenderRegion* region = *iter;
-        if (region->hasAutoLogicalHeight())
-            autoLogicalHeightRegions++;
-    }
-
-    return autoLogicalHeightRegions == m_autoLogicalHeightRegionsCount;
-}
-#endif
-
-// During the normal layout phase of the named flow the regions are initialized with a height equal to their max-height.
-// This way unforced breaks are automatically placed when a region is full and the content height/position correctly estimated.
-// Also, the region where a forced break falls is exactly the region found at the forced break offset inside the flow content.
-void RenderFlowThread::initializeRegionsComputedAutoHeight(RenderRegion* startRegion)
-{
-    ASSERT(!inConstrainedLayoutPhase());
-    if (!hasAutoLogicalHeightRegions())
-        return;
-
-    RenderRegionList::iterator regionIter = startRegion ? m_regionList.find(startRegion) : m_regionList.begin();
-    for (; regionIter != m_regionList.end(); ++regionIter) {
-        RenderRegion* region = *regionIter;
-        if (region->hasAutoLogicalHeight())
-            region->setComputedAutoHeight(region->maxPageLogicalHeight());
-    }
-}
-
-void RenderFlowThread::markAutoLogicalHeightRegionsForLayout()
-{
-    ASSERT(hasAutoLogicalHeightRegions());
-
-    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        if (!region->hasAutoLogicalHeight())
-            continue;
-
-        // FIXME: We need to find a way to avoid marking all the regions ancestors for layout
-        // as we are already inside layout.
-        region->setNeedsLayout();
-    }
-}
-
-void RenderFlowThread::updateRegionsFlowThreadPortionRect(const RenderRegion* lastRegionWithContent)
-{
-    ASSERT(!lastRegionWithContent || (!inConstrainedLayoutPhase() && hasAutoLogicalHeightRegions()));
     LayoutUnit logicalHeight = 0;
-    bool emptyRegionsSegment = false;
     // FIXME: Optimize not to clear the interval all the time. This implies manually managing the tree nodes lifecycle.
     m_regionIntervalTree.clear();
     m_regionIntervalTree.initIfNeeded();
     for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
         RenderRegion* region = *iter;
 
-        // If we find an empty auto-height region, clear the computedAutoHeight value.
-        if (emptyRegionsSegment && region->hasAutoLogicalHeight())
-            region->clearComputedAutoHeight();
-
         LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
         LayoutUnit regionLogicalHeight = std::min<LayoutUnit>(RenderFlowThread::maxLogicalHeight() - logicalHeight, region->logicalHeightOfAllFlowThreadContent());
 
@@ -909,104 +502,7 @@
         m_regionIntervalTree.add(RegionIntervalTree::createInterval(logicalHeight, logicalHeight + regionLogicalHeight, region));
 
         logicalHeight += regionLogicalHeight;
-
-        // Once we find the last region with content the next regions are considered empty.
-        if (lastRegionWithContent == region)
-            emptyRegionsSegment = true;
     }
-
-    ASSERT(!lastRegionWithContent || emptyRegionsSegment);
-}
-
-// Even if we require the break to occur at offsetBreakInFlowThread, because regions may have min/max-height values,
-// it is possible that the break will occur at a different offset than the original one required.
-// offsetBreakAdjustment measures the different between the requested break offset and the current break offset.
-bool RenderFlowThread::addForcedRegionBreak(LayoutUnit offsetBreakInFlowThread, RenderObject* breakChild, bool isBefore, LayoutUnit* offsetBreakAdjustment)
-{
-    // We take breaks into account for height computation for auto logical height regions
-    // only in the layout phase in which we lay out the flows threads unconstrained
-    // and we use the content breaks to determine the computedAutoHeight for
-    // auto logical height regions.
-    if (inConstrainedLayoutPhase())
-        return false;
-
-    // Breaks can come before or after some objects. We need to track these objects, so that if we get
-    // multiple breaks for the same object (for example because of multiple layouts on the same object),
-    // we need to invalidate every other region after the old one and start computing from fresh.
-    RenderObjectToRegionMap& mapToUse = isBefore ? m_breakBeforeToRegionMap : m_breakAfterToRegionMap;
-    RenderObjectToRegionMap::iterator iter = mapToUse.find(breakChild);
-    if (iter != mapToUse.end()) {
-        RenderRegionList::iterator regionIter = m_regionList.find(iter->value);
-        ASSERT_WITH_SECURITY_IMPLICATION(regionIter != m_regionList.end());
-        ASSERT((*regionIter)->hasAutoLogicalHeight());
-        initializeRegionsComputedAutoHeight(*regionIter);
-
-        // We need to update the regions flow thread portion rect because we are going to process
-        // a break on these regions.
-        updateRegionsFlowThreadPortionRect();
-    }
-
-    // Simulate a region break at offsetBreakInFlowThread. If it points inside an auto logical height region,
-    // then it determines the region computed auto height.
-    RenderRegion* region = regionAtBlockOffset(offsetBreakInFlowThread);
-    if (!region)
-        return false;
-
-    bool lastBreakAfterContent = breakChild == this;
-    bool hasComputedAutoHeight = false;
-
-    LayoutUnit currentRegionOffsetInFlowThread = isHorizontalWritingMode() ? region->flowThreadPortionRect().y() : region->flowThreadPortionRect().x();
-    LayoutUnit offsetBreakInCurrentRegion = offsetBreakInFlowThread - currentRegionOffsetInFlowThread;
-
-    if (region->hasAutoLogicalHeight()) {
-        // A forced break can appear only in an auto-height region that didn't have a forced break before.
-        // This ASSERT is a good-enough heuristic to verify the above condition.
-        ASSERT(region->maxPageLogicalHeight() == region->computedAutoHeight());
-
-        mapToUse.set(breakChild, region);
-
-        hasComputedAutoHeight = true;
-
-        // Compute the region height pretending that the offsetBreakInCurrentRegion is the logicalHeight for the auto-height region.
-        LayoutUnit regionComputedAutoHeight = region->constrainContentBoxLogicalHeightByMinMax(offsetBreakInCurrentRegion, -1);
-
-        // The new height of this region needs to be smaller than the initial value, the max height. A forced break is the only way to change the initial
-        // height of an auto-height region besides content ending.
-        ASSERT(regionComputedAutoHeight <= region->maxPageLogicalHeight());
-
-        region->setComputedAutoHeight(regionComputedAutoHeight);
-
-        currentRegionOffsetInFlowThread += regionComputedAutoHeight;
-    } else {
-        currentRegionOffsetInFlowThread += isHorizontalWritingMode() ? region->flowThreadPortionRect().height() : region->flowThreadPortionRect().width();
-    }
-
-    // If the break was found inside an auto-height region its size changed so we need to recompute the flow thread portion rectangles.
-    // Also, if this is the last break after the content we need to clear the computedAutoHeight value on the last empty regions.
-    if (hasAutoLogicalHeightRegions() && lastBreakAfterContent)
-        updateRegionsFlowThreadPortionRect(region);
-    else if (hasComputedAutoHeight)
-        updateRegionsFlowThreadPortionRect();
-
-    if (offsetBreakAdjustment)
-        *offsetBreakAdjustment = max<LayoutUnit>(0, currentRegionOffsetInFlowThread - offsetBreakInFlowThread);
-
-    return hasComputedAutoHeight;
-}
-
-void RenderFlowThread::incrementAutoLogicalHeightRegions()
-{
-    if (!m_autoLogicalHeightRegionsCount)
-        view()->flowThreadController()->incrementFlowThreadsWithAutoLogicalHeightRegions();
-    ++m_autoLogicalHeightRegionsCount;
-}
-
-void RenderFlowThread::decrementAutoLogicalHeightRegions()
-{
-    ASSERT(m_autoLogicalHeightRegionsCount > 0);
-    --m_autoLogicalHeightRegionsCount;
-    if (!m_autoLogicalHeightRegionsCount)
-        view()->flowThreadController()->decrementFlowThreadsWithAutoLogicalHeightRegions();
 }
 
 void RenderFlowThread::collectLayerFragments(LayerFragments& layerFragments, const LayoutRect& layerBoundingBox, const LayoutRect& dirtyRect)
@@ -1167,7 +663,6 @@
         return;
     RenderView* view = m_renderFlowThread->view();
     m_previousRenderFlowThread = view->flowThreadController()->currentRenderFlowThread();
-    ASSERT(!m_previousRenderFlowThread || !renderFlowThread->isRenderNamedFlowThread());
     view->flowThreadController()->setCurrentRenderFlowThread(m_renderFlowThread);
 }
 
diff --git a/Source/core/rendering/RenderFlowThread.h b/Source/core/rendering/RenderFlowThread.h
index 7986768..96010d9 100644
--- a/Source/core/rendering/RenderFlowThread.h
+++ b/Source/core/rendering/RenderFlowThread.h
@@ -63,14 +63,9 @@
 
     // Always create a RenderLayer for the RenderFlowThread so that we
     // can easily avoid drawing the children directly.
-    virtual bool requiresLayer() const OVERRIDE FINAL { return true; }
+    virtual LayerType layerTypeRequired() const OVERRIDE FINAL { return NormalLayer; }
 
-    virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
-
-    void removeFlowChildInfo(RenderObject*);
-#ifndef NDEBUG
-    bool hasChildInfo(RenderObject* child) const { return child && child->isBox() && m_regionRangeMap.contains(toRenderBox(child)); }
-#endif
+    virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE FINAL;
 
     virtual void addRegionToThread(RenderRegion*);
     virtual void removeRegionFromThread(RenderRegion*);
@@ -79,14 +74,7 @@
     virtual void updateLogicalWidth() OVERRIDE FINAL;
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
 
-    void paintFlowThreadPortionInRegion(PaintInfo&, RenderRegion*, const LayoutRect& flowThreadPortionRect, const LayoutRect& flowThreadPortionOverflowRect, const LayoutPoint&) const;
-    bool hitTestFlowThreadPortionInRegion(RenderRegion*, const LayoutRect& flowThreadPortionRect, const LayoutRect& flowThreadPortionOverflowRect, const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) const;
-
     bool hasRegions() const { return m_regionList.size(); }
-    // Check if the content is flown into at least a region with region styling rules.
-    bool hasRegionsWithStyling() const { return m_hasRegionsWithStyling; }
-    void checkRegionsWithStyling();
-    virtual void regionChangedWritingMode(RenderRegion*) { }
 
     void validateRegions();
     void invalidateRegions();
@@ -94,8 +82,6 @@
 
     static PassRefPtr<RenderStyle> createFlowThreadStyle(RenderStyle* parentStyle);
 
-    void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
-
     void repaintRectangleInRegions(const LayoutRect&) const;
 
     LayoutPoint adjustedPositionRelativeToOffsetParent(const RenderBoxModelObject&, const LayoutPoint&);
@@ -116,18 +102,10 @@
 
     RenderRegion* regionFromAbsolutePointAndBox(IntPoint, const RenderBox* flowedBox);
 
-    bool regionsHaveUniformLogicalWidth() const { return m_regionsHaveUniformLogicalWidth; }
     bool regionsHaveUniformLogicalHeight() const { return m_regionsHaveUniformLogicalHeight; }
 
     RenderRegion* mapFromFlowToRegion(TransformState&) const;
 
-    void removeRenderBoxRegionInfo(RenderBox*);
-    bool logicalWidthChangedInRegionsForBlock(const RenderBlock*);
-
-    LayoutUnit contentLogicalWidthOfFirstRegion() const;
-    LayoutUnit contentLogicalHeightOfFirstRegion() const;
-    LayoutUnit contentLogicalLeftOfFirstRegion() const;
-
     RenderRegion* firstRegion() const;
     RenderRegion* lastRegion() const;
 
@@ -137,37 +115,14 @@
     void setRegionRangeForBox(const RenderBox*, LayoutUnit offsetFromLogicalTopOfFirstPage);
     void getRegionRangeForBox(const RenderBox*, RenderRegion*& startRegion, RenderRegion*& endRegion) const;
 
-    void clearRenderObjectCustomStyle(const RenderObject*,
-        const RenderRegion* oldStartRegion = 0, const RenderRegion* oldEndRegion = 0,
-        const RenderRegion* newStartRegion = 0, const RenderRegion* newEndRegion = 0);
-
-    // Check if the object is in region and the region is part of this flow thread.
-    bool objectInFlowRegion(const RenderObject*, const RenderRegion*) const;
-
-    void markAutoLogicalHeightRegionsForLayout();
-
-    bool addForcedRegionBreak(LayoutUnit, RenderObject* breakChild, bool isBefore, LayoutUnit* offsetBreakAdjustment = 0);
+    virtual bool addForcedRegionBreak(LayoutUnit, RenderObject* breakChild, bool isBefore, LayoutUnit* offsetBreakAdjustment = 0) { return false; }
     void applyBreakAfterContent(LayoutUnit);
 
     bool pageLogicalSizeChanged() const { return m_pageLogicalSizeChanged; }
 
-    bool hasAutoLogicalHeightRegions() const { ASSERT(isAutoLogicalHeightRegionsCountConsistent()); return m_autoLogicalHeightRegionsCount; }
-    void incrementAutoLogicalHeightRegions();
-    void decrementAutoLogicalHeightRegions();
-
-#ifndef NDEBUG
-    bool isAutoLogicalHeightRegionsCountConsistent() const;
-#endif
-
     void collectLayerFragments(LayerFragments&, const LayoutRect& layerBoundingBox, const LayoutRect& dirtyRect);
     LayoutRect fragmentsBoundingBox(const LayoutRect& layerBoundingBox);
 
-    void setInConstrainedLayoutPhase(bool value) { m_inConstrainedLayoutPhase = value; }
-    bool inConstrainedLayoutPhase() const { return m_inConstrainedLayoutPhase; }
-
-    bool needsTwoPhasesLayout() const { return m_needsTwoPhasesLayout; }
-    void clearNeedsTwoPhasesLayout() { m_needsTwoPhasesLayout = false; }
-
     void pushFlowThreadLayoutState(const RenderObject*);
     void popFlowThreadLayoutState();
     LayoutUnit offsetFromLogicalTopOfFirstRegion(const RenderBlock*) const;
@@ -182,26 +137,14 @@
     // no regions have been generated yet.
     virtual LayoutUnit initialLogicalWidth() const { return 0; };
 
-    virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE;
+    virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE FINAL;
 
-    void updateRegionsFlowThreadPortionRect(const RenderRegion* = 0);
+    void updateRegionsFlowThreadPortionRect();
     bool shouldRepaint(const LayoutRect&) const;
     bool regionInRange(const RenderRegion* targetRegion, const RenderRegion* startRegion, const RenderRegion* endRegion) const;
 
     LayoutRect computeRegionClippingRect(const LayoutPoint&, const LayoutRect&, const LayoutRect&) const;
 
-    void setDispatchRegionLayoutUpdateEvent(bool value) { m_dispatchRegionLayoutUpdateEvent = value; }
-    bool shouldDispatchRegionLayoutUpdateEvent() { return m_dispatchRegionLayoutUpdateEvent; }
-
-    void setDispatchRegionOversetChangeEvent(bool value) { m_dispatchRegionOversetChangeEvent = value; }
-    bool shouldDispatchRegionOversetChangeEvent() const { return m_dispatchRegionOversetChangeEvent; }
-
-    // Override if the flow thread implementation supports dispatching events when the flow layout is updated (e.g. for named flows)
-    virtual void dispatchRegionLayoutUpdateEvent() { m_dispatchRegionLayoutUpdateEvent = false; }
-    virtual void dispatchRegionOversetChangeEvent() { m_dispatchRegionOversetChangeEvent = false; }
-
-    void initializeRegionsComputedAutoHeight(RenderRegion* = 0);
-
     virtual void autoGenerateRegionsToBlockOffset(LayoutUnit) { };
 
     bool cachedOffsetFromLogicalTopOfFirstRegion(const RenderBox*, LayoutUnit&) const;
@@ -265,10 +208,6 @@
     typedef HashMap<const RenderBox*, RenderRegionRange> RenderRegionRangeMap;
     RenderRegionRangeMap m_regionRangeMap;
 
-    typedef HashMap<RenderObject*, RenderRegion*> RenderObjectToRegionMap;
-    RenderObjectToRegionMap m_breakBeforeToRegionMap;
-    RenderObjectToRegionMap m_breakAfterToRegionMap;
-
     // Stack of objects that pushed a LayoutState object on the RenderView. The
     // objects on the stack are the ones that are curently in the process of being
     // laid out.
@@ -276,22 +215,14 @@
     typedef HashMap<const RenderBox*, LayoutUnit> RenderBoxToOffsetMap;
     RenderBoxToOffsetMap m_boxesToOffsetMap;
 
-    unsigned m_autoLogicalHeightRegionsCount;
-
     RegionIntervalTree m_regionIntervalTree;
 
     bool m_regionsInvalidated : 1;
-    bool m_regionsHaveUniformLogicalWidth : 1;
     bool m_regionsHaveUniformLogicalHeight : 1;
-    bool m_hasRegionsWithStyling : 1;
-    bool m_dispatchRegionLayoutUpdateEvent : 1;
-    bool m_dispatchRegionOversetChangeEvent : 1;
     bool m_pageLogicalSizeChanged : 1;
-    bool m_inConstrainedLayoutPhase : 1;
-    bool m_needsTwoPhasesLayout : 1;
 
 private:
-    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+    virtual bool supportsPartialLayout() const OVERRIDE FINAL { return false; }
 
 };
 
diff --git a/Source/core/rendering/RenderFrame.cpp b/Source/core/rendering/RenderFrame.cpp
index 329ae34..3468cc3 100644
--- a/Source/core/rendering/RenderFrame.cpp
+++ b/Source/core/rendering/RenderFrame.cpp
@@ -47,21 +47,4 @@
         toRenderFrameSet(parent())->notifyFrameEdgeInfoChanged();
 }
 
-void RenderFrame::viewCleared()
-{
-    HTMLFrameElement* element = toHTMLFrameElement(node());
-    if (!element || !widget() || !widget()->isFrameView())
-        return;
-
-    FrameView* view = toFrameView(widget());
-
-    int marginWidth = element->marginWidth();
-    int marginHeight = element->marginHeight();
-
-    if (marginWidth != -1)
-        view->setMarginWidth(marginWidth);
-    if (marginHeight != -1)
-        view->setMarginHeight(marginHeight);
-}
-
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderFrame.h b/Source/core/rendering/RenderFrame.h
index 55391b9..8d95319 100644
--- a/Source/core/rendering/RenderFrame.h
+++ b/Source/core/rendering/RenderFrame.h
@@ -37,12 +37,10 @@
     FrameEdgeInfo edgeInfo() const;
 
 private:
-    virtual const char* renderName() const { return "RenderFrame"; }
-    virtual bool isFrame() const { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderFrame"; }
+    virtual bool isFrame() const OVERRIDE { return true; }
 
-    virtual void updateFromElement();
-
-    virtual void viewCleared();
+    virtual void updateFromElement() OVERRIDE;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderFrame, isFrame());
diff --git a/Source/core/rendering/RenderFrameSet.cpp b/Source/core/rendering/RenderFrameSet.cpp
index a0bf472..40cdbd0 100644
--- a/Source/core/rendering/RenderFrameSet.cpp
+++ b/Source/core/rendering/RenderFrameSet.cpp
@@ -442,7 +442,7 @@
     ASSERT(needsLayout());
 
     LayoutRectRecorder recorder(*this);
-    bool doFullRepaint = !RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && selfNeedsLayout() && checkForRepaintDuringLayout();
+    bool doFullRepaint = selfNeedsLayout() && checkForRepaintDuringLayout();
     LayoutRect oldBounds;
     RenderLayerModelObject* repaintContainer = 0;
     if (doFullRepaint) {
diff --git a/Source/core/rendering/RenderFrameSet.h b/Source/core/rendering/RenderFrameSet.h
index 21f90ea..df5c385 100644
--- a/Source/core/rendering/RenderFrameSet.h
+++ b/Source/core/rendering/RenderFrameSet.h
@@ -94,16 +94,16 @@
         int m_splitResizeOffset;
     };
 
-    virtual RenderObjectChildList* virtualChildren() { return children(); }
-    virtual const RenderObjectChildList* virtualChildren() const { return children(); }
+    virtual RenderObjectChildList* virtualChildren() OVERRIDE { return children(); }
+    virtual const RenderObjectChildList* virtualChildren() const OVERRIDE { return children(); }
 
-    virtual const char* renderName() const { return "RenderFrameSet"; }
-    virtual bool isFrameSet() const { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderFrameSet"; }
+    virtual bool isFrameSet() const OVERRIDE { return true; }
 
-    virtual void layout();
-    virtual void paint(PaintInfo&, const LayoutPoint&);
-    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const;
-    virtual CursorDirective getCursor(const LayoutPoint&, Cursor&) const;
+    virtual void layout() OVERRIDE;
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
+    virtual CursorDirective getCursor(const LayoutPoint&, Cursor&) const OVERRIDE;
 
     inline HTMLFrameSetElement* frameSet() const;
 
diff --git a/Source/core/rendering/RenderFullScreen.cpp b/Source/core/rendering/RenderFullScreen.cpp
index 23fa992..664bc02 100644
--- a/Source/core/rendering/RenderFullScreen.cpp
+++ b/Source/core/rendering/RenderFullScreen.cpp
@@ -39,9 +39,9 @@
         setDocumentForAnonymous(&owner->document());
     }
 private:
-    virtual bool isRenderFullScreenPlaceholder() const { return true; }
+    virtual bool isRenderFullScreenPlaceholder() const OVERRIDE { return true; }
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
     RenderFullScreen* m_owner;
 };
 
@@ -95,7 +95,7 @@
 
     fullscreenStyle->setDisplay(FLEX);
     fullscreenStyle->setJustifyContent(JustifyCenter);
-    fullscreenStyle->setAlignItems(AlignCenter);
+    fullscreenStyle->setAlignItems(ItemPositionCenter);
     fullscreenStyle->setFlexDirection(FlowColumn);
 
     fullscreenStyle->setPosition(FixedPosition);
@@ -104,7 +104,7 @@
     fullscreenStyle->setLeft(Length(0, WebCore::Fixed));
     fullscreenStyle->setTop(Length(0, WebCore::Fixed));
 
-    fullscreenStyle->setBackgroundColor(Color::black);
+    fullscreenStyle->setBackgroundColor(StyleColor(Color::black));
 
     return fullscreenStyle.release();
 }
diff --git a/Source/core/rendering/RenderFullScreen.h b/Source/core/rendering/RenderFullScreen.h
index 48c40f4..285dbd2 100644
--- a/Source/core/rendering/RenderFullScreen.h
+++ b/Source/core/rendering/RenderFullScreen.h
@@ -34,8 +34,8 @@
 public:
     static RenderFullScreen* createAnonymous(Document*);
 
-    virtual bool isRenderFullScreen() const { return true; }
-    virtual const char* renderName() const { return "RenderFullScreen"; }
+    virtual bool isRenderFullScreen() const OVERRIDE { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderFullScreen"; }
 
     void setPlaceholder(RenderBlock*);
     RenderBlock* placeholder() { return m_placeholder; }
@@ -47,8 +47,7 @@
 
 private:
     RenderFullScreen();
-    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
 protected:
     RenderBlock* m_placeholder;
diff --git a/Source/core/rendering/RenderGeometryMap.cpp b/Source/core/rendering/RenderGeometryMap.cpp
index 9f51c37..07ab16f 100644
--- a/Source/core/rendering/RenderGeometryMap.cpp
+++ b/Source/core/rendering/RenderGeometryMap.cpp
@@ -27,7 +27,6 @@
 #include "core/rendering/RenderGeometryMap.h"
 
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
 #include "platform/geometry/TransformState.h"
diff --git a/Source/core/rendering/RenderGeometryMap.h b/Source/core/rendering/RenderGeometryMap.h
index 8049bbb..b37805a 100644
--- a/Source/core/rendering/RenderGeometryMap.h
+++ b/Source/core/rendering/RenderGeometryMap.h
@@ -144,7 +144,7 @@
 namespace WTF {
 // This is required for a struct with OwnPtr. We know RenderGeometryMapStep is simple enough that
 // initializing to 0 and moving with memcpy (and then not destructing the original) will work.
-template<> struct VectorTraits<WebCore::RenderGeometryMapStep> : SimpleClassVectorTraits { };
+template<> struct VectorTraits<WebCore::RenderGeometryMapStep> : SimpleClassVectorTraits<WebCore::RenderGeometryMapStep> { };
 }
 
 #endif // RenderGeometryMap_h
diff --git a/Source/core/rendering/RenderGrid.cpp b/Source/core/rendering/RenderGrid.cpp
index 38c296a..2485447 100644
--- a/Source/core/rendering/RenderGrid.cpp
+++ b/Source/core/rendering/RenderGrid.cpp
@@ -26,10 +26,12 @@
 #include "config.h"
 #include "core/rendering/RenderGrid.h"
 
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/GridCoordinate.h"
+#include "platform/LengthFunctions.h"
 
 namespace WebCore {
 
@@ -75,7 +77,7 @@
     }
 
     // Required by std::sort.
-    GridTrackForNormalization operator=(const GridTrackForNormalization& o)
+    GridTrackForNormalization& operator=(const GridTrackForNormalization& o)
     {
         m_track = o.m_track;
         m_flex = o.m_flex;
@@ -168,7 +170,6 @@
     : RenderBlock(element)
     , m_gridIsDirty(true)
     , m_orderIterator(this)
-    , m_gridItemOverflowGridArea(false)
 {
     // All of our children must be block level.
     setChildrenInline(false);
@@ -237,8 +238,8 @@
 
 bool RenderGrid::explicitGridDidResize(const RenderStyle* oldStyle) const
 {
-    return oldStyle->gridDefinitionColumns().size() != style()->gridDefinitionColumns().size()
-        || oldStyle->gridDefinitionRows().size() != style()->gridDefinitionRows().size();
+    return oldStyle->gridTemplateColumns().size() != style()->gridTemplateColumns().size()
+        || oldStyle->gridTemplateRows().size() != style()->gridTemplateRows().size();
 }
 
 bool RenderGrid::namedGridLinesDefinitionDidChange(const RenderStyle* oldStyle) const
@@ -247,7 +248,7 @@
         || oldStyle->namedGridColumnLines() != style()->namedGridColumnLines();
 }
 
-void RenderGrid::layoutBlock(bool relayoutChildren, LayoutUnit)
+void RenderGrid::layoutBlock(bool relayoutChildren)
 {
     ASSERT(needsLayout());
 
@@ -259,10 +260,7 @@
     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
 
-    // Regions changing widths can force us to relayout our children.
     RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (logicalWidthChangedInRegions(flowThread))
-        relayoutChildren = true;
     if (updateRegionsAndShapesLogicalSize(flowThread))
         relayoutChildren = true;
 
@@ -304,7 +302,7 @@
 
     GridSizingData sizingData(gridColumnCount(), gridRowCount());
     LayoutUnit availableLogicalSpace = 0;
-    const_cast<RenderGrid*>(this)->computedUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
+    const_cast<RenderGrid*>(this)->computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
 
     for (size_t i = 0; i < sizingData.columnTracks.size(); ++i) {
         LayoutUnit minTrackBreadth = sizingData.columnTracks[i].m_usedBreadth;
@@ -337,16 +335,24 @@
     clearPreferredLogicalWidthsDirty();
 }
 
-void RenderGrid::computedUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
+void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
 {
     LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
-    computedUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
+    computeUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
 }
 
-void RenderGrid::computedUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
+static bool gridElementIsShrinkToFit(const RenderStyle& style)
+{
+    return style.isFloating() || style.position() == AbsolutePosition;
+}
+
+void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
 {
     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
+    Vector<size_t> flexibleSizedTracksIndex;
     sizingData.contentSizedTracksIndex.shrink(0);
+
+    // 1. Initialize per Grid track variables.
     for (size_t i = 0; i < tracks.size(); ++i) {
         GridTrack& track = tracks[i];
         const GridTrackSize& trackSize = gridTrackSize(direction, i);
@@ -360,8 +366,11 @@
 
         if (trackSize.isContentSized())
             sizingData.contentSizedTracksIndex.append(i);
+        if (trackSize.maxTrackBreadth().isFlex())
+            flexibleSizedTracksIndex.append(i);
     }
 
+    // 2. Resolve content-based TrackSizingFunctions.
     if (!sizingData.contentSizedTracksIndex.isEmpty())
         resolveContentBasedTrackSizingFunctions(direction, sizingData, availableLogicalSpace);
 
@@ -370,26 +379,60 @@
         availableLogicalSpace -= tracks[i].m_usedBreadth;
     }
 
-    if (availableLogicalSpace <= 0)
+    const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style()->logicalHeight().isAuto() : gridElementIsShrinkToFit(*style());
+
+    if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
         return;
 
+    // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until
+    // availableLogicalSpace (RemainingSpace in the specs) is exhausted.
     const size_t tracksSize = tracks.size();
-    Vector<GridTrack*> tracksForDistribution(tracksSize);
-    for (size_t i = 0; i < tracksSize; ++i)
-        tracksForDistribution[i] = tracks.data() + i;
+    if (!hasUndefinedRemainingSpace) {
+        Vector<GridTrack*> tracksForDistribution(tracksSize);
+        for (size_t i = 0; i < tracksSize; ++i)
+            tracksForDistribution[i] = tracks.data() + i;
 
-    distributeSpaceToTracks(tracksForDistribution, 0, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, sizingData, availableLogicalSpace);
+        distributeSpaceToTracks(tracksForDistribution, 0, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, sizingData, availableLogicalSpace);
+    } else {
+        for (size_t i = 0; i < tracksSize; ++i)
+            tracks[i].m_usedBreadth = tracks[i].m_maxBreadth;
+    }
+
+    if (flexibleSizedTracksIndex.isEmpty())
+        return;
 
     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
+    double normalizedFractionBreadth = 0;
+    if (!hasUndefinedRemainingSpace) {
+        normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, GridSpan(0, tracks.size() - 1), direction, availableLogicalSpace);
+    } else {
+        for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
+            const size_t trackIndex = flexibleSizedTracksIndex[i];
+            const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
+            normalizedFractionBreadth = std::max(normalizedFractionBreadth, tracks[trackIndex].m_usedBreadth / trackSize.maxTrackBreadth().flex());
+        }
 
-    // FIXME: Handle the case where RemainingSpace is not defined.
-    double normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, direction, availableLogicalSpace);
-    for (size_t i = 0; i < tracksSize; ++i) {
-        const GridTrackSize& trackSize = gridTrackSize(direction, i);
-        if (!trackSize.maxTrackBreadth().isFlex())
-            continue;
+        for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
+            GridIterator iterator(m_grid, direction, flexibleSizedTracksIndex[i]);
+            while (RenderBox* gridItem = iterator.nextGridItem()) {
+                const GridCoordinate coordinate = cachedGridCoordinate(gridItem);
+                const GridSpan span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
 
-        tracks[i].m_usedBreadth = std::max<LayoutUnit>(tracks[i].m_usedBreadth, normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
+                // Do not include already processed items.
+                if (i > 0 && span.initialPositionIndex <= flexibleSizedTracksIndex[i - 1])
+                    continue;
+
+                double itemNormalizedFlexBreadth = computeNormalizedFractionBreadth(tracks, span, direction, maxContentForChild(gridItem, direction, sizingData.columnTracks));
+                normalizedFractionBreadth = std::max(normalizedFractionBreadth, itemNormalizedFlexBreadth);
+            }
+        }
+    }
+
+    for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
+        const size_t trackIndex = flexibleSizedTracksIndex[i];
+        const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
+
+        tracks[trackIndex].m_usedBreadth = std::max<LayoutUnit>(tracks[trackIndex].m_usedBreadth, normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
     }
 }
 
@@ -428,7 +471,7 @@
 {
     ASSERT(trackLength.isSpecified());
     // FIXME: The -1 here should be replaced by whatever the intrinsic height of the grid is.
-    return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : computeContentLogicalHeight(style()->logicalHeight(), -1), view());
+    return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : computeContentLogicalHeight(style()->logicalHeight(), -1));
 }
 
 static bool sortByGridNormalizedFlexValue(const GridTrackForNormalization& track1, const GridTrackForNormalization& track2)
@@ -436,12 +479,12 @@
     return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
 }
 
-double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, GridTrackSizingDirection direction, LayoutUnit availableLogicalSpace) const
+double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit availableLogicalSpace) const
 {
     // |availableLogicalSpace| already accounts for the used breadths so no need to remove it here.
 
     Vector<GridTrackForNormalization> tracksForNormalization;
-    for (size_t i = 0; i < tracks.size(); ++i) {
+    for (size_t i = tracksSpan.initialPositionIndex; i <= tracksSpan.finalPositionIndex; ++i) {
         const GridTrackSize& trackSize = gridTrackSize(direction, i);
         if (!trackSize.maxTrackBreadth().isFlex())
             continue;
@@ -449,9 +492,8 @@
         tracksForNormalization.append(GridTrackForNormalization(tracks[i], trackSize.maxTrackBreadth().flex()));
     }
 
-    // FIXME: Ideally we shouldn't come here without any <flex> grid track.
-    if (tracksForNormalization.isEmpty())
-        return LayoutUnit();
+    // The function is not called if we don't have <flex> grid tracks
+    ASSERT(!tracksForNormalization.isEmpty());
 
     std::sort(tracksForNormalization.begin(), tracksForNormalization.end(), sortByGridNormalizedFlexValue);
 
@@ -483,21 +525,31 @@
 
 const GridTrackSize& RenderGrid::gridTrackSize(GridTrackSizingDirection direction, size_t i) const
 {
-    const Vector<GridTrackSize>& trackStyles = (direction == ForColumns) ? style()->gridDefinitionColumns() : style()->gridDefinitionRows();
+    const Vector<GridTrackSize>& trackStyles = (direction == ForColumns) ? style()->gridTemplateColumns() : style()->gridTemplateRows();
     if (i >= trackStyles.size())
         return (direction == ForColumns) ? style()->gridAutoColumns() : style()->gridAutoRows();
 
-    return trackStyles[i];
+    const GridTrackSize& trackSize = trackStyles[i];
+    // If the logical width/height of the grid container is indefinite, percentage values are treated as <auto>.
+    if (trackSize.isPercentage()) {
+        Length logicalSize = direction == ForColumns ? style()->logicalWidth() : style()->logicalHeight();
+        if (logicalSize.isIntrinsicOrAuto()) {
+            DEFINE_STATIC_LOCAL(GridTrackSize, autoTrackSize, (Length(Auto)));
+            return autoTrackSize;
+        }
+    }
+
+    return trackSize;
 }
 
 size_t RenderGrid::explicitGridColumnCount() const
 {
-    return style()->gridDefinitionColumns().size();
+    return style()->gridTemplateColumns().size();
 }
 
 size_t RenderGrid::explicitGridRowCount() const
 {
-    return style()->gridDefinitionRows().size();
+    return style()->gridTemplateRows().size();
 }
 
 size_t RenderGrid::explicitGridSizeForSide(GridPositionSide side) const
@@ -508,10 +560,12 @@
 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox* child, Vector<GridTrack>& columnTracks)
 {
     SubtreeLayoutScope layoutScope(child);
-    if (child->style()->logicalHeight().isPercent())
+    LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
+    LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
+    if (child->style()->logicalHeight().isPercent() || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth)
         layoutScope.setNeedsLayout(child);
 
-    child->setOverrideContainingBlockContentLogicalWidth(gridAreaBreadthForChild(child, ForColumns, columnTracks));
+    child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
     child->setOverrideContainingBlockContentLogicalHeight(-1);
@@ -717,8 +771,8 @@
         insertItemIntoGrid(child, GridCoordinate(*rowPositions, *columnPositions));
     }
 
-    ASSERT(gridRowCount() >= style()->gridDefinitionRows().size());
-    ASSERT(gridColumnCount() >= style()->gridDefinitionColumns().size());
+    ASSERT(gridRowCount() >= style()->gridTemplateRows().size());
+    ASSERT(gridColumnCount() >= style()->gridTemplateColumns().size());
 
     if (autoFlow == AutoFlowNone) {
         // If we did collect some grid items, they won't be placed thus never laid out.
@@ -832,6 +886,7 @@
     m_grid.resize(0);
     m_gridItemCoordinate.clear();
     m_gridIsDirty = true;
+    m_gridItemsOverflowingGridArea.resize(0);
 }
 
 void RenderGrid::layoutGridItems()
@@ -839,14 +894,17 @@
     placeItemsOnGrid();
 
     GridSizingData sizingData(gridColumnCount(), gridRowCount());
-    computedUsedBreadthOfGridTracks(ForColumns, sizingData);
+    computeUsedBreadthOfGridTracks(ForColumns, sizingData);
     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
-    computedUsedBreadthOfGridTracks(ForRows, sizingData);
+    computeUsedBreadthOfGridTracks(ForRows, sizingData);
     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
 
     populateGridPositions(sizingData);
+    m_gridItemsOverflowingGridArea.resize(0);
 
     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
+        LayoutRectRecorder recorder(*child);
+
         // Because the grid area cannot be styled, we don't need to adjust
         // the grid breadth to account for 'box-sizing'.
         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
@@ -869,11 +927,18 @@
         // now, just size as if we were a regular child.
         child->layoutIfNeeded();
 
-        child->setLogicalLocation(findChildLogicalPosition(child, sizingData));
+#ifndef NDEBUG
+        const GridCoordinate& coordinate = cachedGridCoordinate(child);
+        ASSERT(coordinate.columns.initialPositionIndex < sizingData.columnTracks.size());
+        ASSERT(coordinate.rows.initialPositionIndex < sizingData.rowTracks.size());
+#endif
+        child->setLogicalLocation(findChildLogicalPosition(child));
 
-        // For correctness, we disable some painting optimizations if we have a child overflowing its grid area.
-        m_gridItemOverflowGridArea = child->logicalHeight() > overrideContainingBlockContentLogicalHeight
-            || child->logicalWidth() > overrideContainingBlockContentLogicalWidth;
+        // Keep track of children overflowing their grid area as we might need to paint them even if the grid-area is
+        // not visible
+        if (child->logicalHeight() > overrideContainingBlockContentLogicalHeight
+            || child->logicalWidth() > overrideContainingBlockContentLogicalWidth)
+            m_gridItemsOverflowingGridArea.append(child);
 
         // If the child moved, we have to repaint it as well as any floating/positioned
         // descendants. An exception is if we need a layout. In this case, we know we're going to
@@ -1072,14 +1137,127 @@
         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].m_usedBreadth;
 }
 
-LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox* child, const GridSizingData& sizingData)
+LayoutUnit RenderGrid::startOfColumnForChild(const RenderBox* child) const
 {
     const GridCoordinate& coordinate = cachedGridCoordinate(child);
-    ASSERT(coordinate.columns.initialPositionIndex < sizingData.columnTracks.size());
-    ASSERT(coordinate.rows.initialPositionIndex < sizingData.rowTracks.size());
+    LayoutUnit startOfColumn = m_columnPositions[coordinate.columns.initialPositionIndex];
+    // The grid items should be inside the grid container's border box, that's why they need to be shifted.
+    // FIXME: This should account for the grid item's <overflow-position>.
+    return startOfColumn + marginStartForChild(child);
+}
+
+LayoutUnit RenderGrid::endOfColumnForChild(const RenderBox* child) const
+{
+    const GridCoordinate& coordinate = cachedGridCoordinate(child);
+    LayoutUnit startOfColumn = m_columnPositions[coordinate.columns.initialPositionIndex];
+    // The grid items should be inside the grid container's border box, that's why they need to be shifted.
+    LayoutUnit columnPosition = startOfColumn + marginStartForChild(child);
+
+    LayoutUnit endOfColumn = m_columnPositions[coordinate.columns.finalPositionIndex + 1];
+    // FIXME: This should account for the grid item's <overflow-position>.
+    return columnPosition + std::max<LayoutUnit>(0, endOfColumn - m_columnPositions[coordinate.columns.initialPositionIndex] - child->logicalWidth());
+}
+
+LayoutUnit RenderGrid::columnPositionAlignedWithGridContainerStart(const RenderBox* child) const
+{
+    if (style()->isLeftToRightDirection())
+        return startOfColumnForChild(child);
+
+    return endOfColumnForChild(child);
+}
+
+LayoutUnit RenderGrid::columnPositionAlignedWithGridContainerEnd(const RenderBox* child) const
+{
+    if (!style()->isLeftToRightDirection())
+        return startOfColumnForChild(child);
+
+    return endOfColumnForChild(child);
+}
+
+LayoutUnit RenderGrid::centeredColumnPositionForChild(const RenderBox* child) const
+{
+    const GridCoordinate& coordinate = cachedGridCoordinate(child);
+    LayoutUnit startOfColumn = m_columnPositions[coordinate.columns.initialPositionIndex];
+    LayoutUnit endOfColumn = m_columnPositions[coordinate.columns.finalPositionIndex + 1];
+    LayoutUnit columnPosition = startOfColumn + marginStartForChild(child);
+    return columnPosition + std::max<LayoutUnit>(0, endOfColumn - startOfColumn - child->logicalWidth()) / 2;
+}
+
+LayoutUnit RenderGrid::columnPositionForChild(const RenderBox* child) const
+{
+    ItemPosition childJustifySelf = child->style()->justifySelf();
+    switch (childJustifySelf) {
+    case ItemPositionSelfStart:
+        // self-start is based on the child's direction. That's why we need to check against the grid container's direction.
+        if (child->style()->direction() != style()->direction())
+            return columnPositionAlignedWithGridContainerEnd(child);
+
+        return columnPositionAlignedWithGridContainerStart(child);
+    case ItemPositionSelfEnd:
+        // self-end is based on the child's direction. That's why we need to check against the grid container's direction.
+        if (child->style()->direction() != style()->direction())
+            return columnPositionAlignedWithGridContainerStart(child);
+
+        return columnPositionAlignedWithGridContainerEnd(child);
+
+    case ItemPositionFlexStart:
+    case ItemPositionFlexEnd:
+        // Only used in flex layout, for other layout, it's equivalent to 'start'.
+        return columnPositionAlignedWithGridContainerStart(child);
+
+    case ItemPositionLeft:
+        // If the property's axis is not parallel with the inline axis, this is equivalent to ‘start’.
+        if (!isHorizontalWritingMode())
+            return columnPositionAlignedWithGridContainerStart(child);
+
+        if (style()->isLeftToRightDirection())
+            return columnPositionAlignedWithGridContainerStart(child);
+
+        return columnPositionAlignedWithGridContainerEnd(child);
+    case ItemPositionRight:
+        // If the property's axis is not parallel with the inline axis, this is equivalent to ‘start’.
+        if (!isHorizontalWritingMode())
+            return columnPositionAlignedWithGridContainerStart(child);
+
+        if (style()->isLeftToRightDirection())
+            return columnPositionAlignedWithGridContainerEnd(child);
+
+        return columnPositionAlignedWithGridContainerStart(child);
+
+    case ItemPositionCenter:
+        return centeredColumnPositionForChild(child);
+    case ItemPositionStart:
+        return columnPositionAlignedWithGridContainerStart(child);
+    case ItemPositionEnd:
+        return columnPositionAlignedWithGridContainerEnd(child);
+
+    case ItemPositionAuto:
+    case ItemPositionStretch:
+    case ItemPositionBaseline:
+        // FIXME: Implement the previous values. For now, we always start align the child.
+        return startOfColumnForChild(child);
+    }
+
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
+LayoutUnit RenderGrid::rowPositionForChild(const RenderBox* child) const
+{
+    const GridCoordinate& coordinate = cachedGridCoordinate(child);
 
     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
-    return LayoutPoint(m_columnPositions[coordinate.columns.initialPositionIndex] + marginStartForChild(child), m_rowPositions[coordinate.rows.initialPositionIndex] + marginBeforeForChild(child));
+    LayoutUnit startOfRow = m_rowPositions[coordinate.rows.initialPositionIndex];
+    LayoutUnit rowPosition = startOfRow + marginBeforeForChild(child);
+
+    // FIXME: This function should account for 'align-self'.
+
+    return rowPosition;
+}
+
+LayoutPoint RenderGrid::findChildLogicalPosition(const RenderBox* child) const
+{
+    return LayoutPoint(columnPositionForChild(child), rowPositionForChild(child));
 }
 
 static GridSpan dirtiedGridAreas(const Vector<LayoutUnit>& coordinates, LayoutUnit start, LayoutUnit end)
@@ -1095,39 +1273,93 @@
     return GridSpan(startGridAreaIndex, endGridAreaIndex);
 }
 
-void RenderGrid::paintChildrenSlowCase(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
+class GridCoordinateSorter {
+public:
+    GridCoordinateSorter(RenderGrid* renderer) : m_renderer(renderer) { }
+
+    bool operator()(const RenderBox* firstItem, const RenderBox* secondItem) const
+    {
+        GridCoordinate first = m_renderer->cachedGridCoordinate(firstItem);
+        GridCoordinate second = m_renderer->cachedGridCoordinate(secondItem);
+
+        if (first.rows.initialPositionIndex < second.rows.initialPositionIndex)
+            return true;
+        if (first.rows.initialPositionIndex > second.rows.initialPositionIndex)
+            return false;
+        return first.columns.finalPositionIndex < second.columns.finalPositionIndex;
+    }
+private:
+    RenderGrid* m_renderer;
+};
+
+static inline bool isInSameRowBeforeDirtyArea(const GridCoordinate& coordinate, size_t row, const GridSpan& dirtiedColumns)
 {
-    for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
-        paintChild(child, paintInfo, paintOffset);
+    return coordinate.rows.initialPositionIndex == row && coordinate.columns.initialPositionIndex < dirtiedColumns.initialPositionIndex;
+}
+
+static inline bool isInSameRowAfterDirtyArea(const GridCoordinate& coordinate, size_t row, const GridSpan& dirtiedColumns)
+{
+    return coordinate.rows.initialPositionIndex == row && coordinate.columns.initialPositionIndex >= dirtiedColumns.finalPositionIndex;
+}
+
+static inline bool rowIsBeforeDirtyArea(const GridCoordinate& coordinate, const GridSpan& dirtiedRows)
+{
+    return coordinate.rows.initialPositionIndex < dirtiedRows.initialPositionIndex;
 }
 
 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     ASSERT_WITH_SECURITY_IMPLICATION(!gridIsDirty());
 
-    if (m_gridItemOverflowGridArea) {
-        paintChildrenSlowCase(paintInfo, paintOffset);
-        return;
-    }
-
     LayoutRect localRepaintRect = paintInfo.rect;
     localRepaintRect.moveBy(-paintOffset);
 
     GridSpan dirtiedColumns = dirtiedGridAreas(m_columnPositions, localRepaintRect.x(), localRepaintRect.maxX());
     GridSpan dirtiedRows = dirtiedGridAreas(m_rowPositions, localRepaintRect.y(), localRepaintRect.maxY());
 
+    // Sort the overflowing grid items according to their positions in the grid. We collect items during the layout
+    // process following DOM's order but we have to paint following grid's.
+    std::stable_sort(m_gridItemsOverflowingGridArea.begin(), m_gridItemsOverflowingGridArea.end(), GridCoordinateSorter(this));
+
     OrderIterator paintIterator(this);
     {
         OrderIteratorPopulator populator(paintIterator);
+        Vector<RenderBox*>::const_iterator overflowIterator = m_gridItemsOverflowingGridArea.begin();
+        Vector<RenderBox*>::const_iterator end = m_gridItemsOverflowingGridArea.end();
+
+        for (; overflowIterator != end && rowIsBeforeDirtyArea(cachedGridCoordinate(*overflowIterator), dirtiedRows); ++overflowIterator) {
+            if ((*overflowIterator)->frameRect().intersects(localRepaintRect))
+                populator.storeChild(*overflowIterator);
+        }
 
         for (size_t row = dirtiedRows.initialPositionIndex; row < dirtiedRows.finalPositionIndex; ++row) {
+
+            for (; overflowIterator != end && isInSameRowBeforeDirtyArea(cachedGridCoordinate(*overflowIterator), row, dirtiedColumns); ++overflowIterator) {
+                if ((*overflowIterator)->frameRect().intersects(localRepaintRect))
+                    populator.storeChild(*overflowIterator);
+            }
+
             for (size_t column = dirtiedColumns.initialPositionIndex; column < dirtiedColumns.finalPositionIndex; ++column) {
                 const Vector<RenderBox*, 1>& children = m_grid[row][column];
                 // FIXME: If we start adding spanning children in all grid areas they span, this
                 // would make us paint them several times, which is wrong!
-                for (size_t j = 0; j < children.size(); ++j)
+                for (size_t j = 0; j < children.size(); ++j) {
                     populator.storeChild(children[j]);
+                    // Do not paint overflowing grid items twice.
+                    if (overflowIterator != end && *overflowIterator == children[j])
+                        ++overflowIterator;
+                }
             }
+
+            for (; overflowIterator != end && isInSameRowAfterDirtyArea(cachedGridCoordinate(*overflowIterator), row, dirtiedColumns); ++overflowIterator) {
+                if ((*overflowIterator)->frameRect().intersects(localRepaintRect))
+                    populator.storeChild(*overflowIterator);
+            }
+        }
+
+        for (; overflowIterator != end; ++overflowIterator) {
+            if ((*overflowIterator)->frameRect().intersects(localRepaintRect))
+                populator.storeChild(*overflowIterator);
         }
     }
 
diff --git a/Source/core/rendering/RenderGrid.h b/Source/core/rendering/RenderGrid.h
index f8a4de3..7e7cf0a 100644
--- a/Source/core/rendering/RenderGrid.h
+++ b/Source/core/rendering/RenderGrid.h
@@ -47,7 +47,7 @@
 
     virtual const char* renderName() const OVERRIDE;
 
-    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE;
+    virtual void layoutBlock(bool relayoutChildren) OVERRIDE;
 
     virtual bool avoidsFloats() const OVERRIDE { return true; }
     virtual bool canCollapseAnonymousBlockChild() const OVERRIDE { return false; }
@@ -72,8 +72,8 @@
 
     class GridIterator;
     struct GridSizingData;
-    void computedUsedBreadthOfGridTracks(GridTrackSizingDirection, GridSizingData&);
-    void computedUsedBreadthOfGridTracks(GridTrackSizingDirection, GridSizingData&, LayoutUnit& availableLogicalSpace);
+    void computeUsedBreadthOfGridTracks(GridTrackSizingDirection, GridSizingData&);
+    void computeUsedBreadthOfGridTracks(GridTrackSizingDirection, GridSizingData&, LayoutUnit& availableLogicalSpace);
     LayoutUnit computeUsedBreadthOfMinLength(GridTrackSizingDirection, const GridLength&) const;
     LayoutUnit computeUsedBreadthOfMaxLength(GridTrackSizingDirection, const GridLength&, LayoutUnit usedBreadth) const;
     LayoutUnit computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection, const Length&) const;
@@ -102,7 +102,7 @@
     void resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection, GridSizingData&, RenderBox*, FilterFunction, SizingFunction, AccumulatorGetter, AccumulatorGrowFunction);
     void distributeSpaceToTracks(Vector<GridTrack*>&, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter, AccumulatorGrowFunction, GridSizingData&, LayoutUnit& availableLogicalSpace);
 
-    double computeNormalizedFractionBreadth(Vector<GridTrack>&, GridTrackSizingDirection, LayoutUnit availableLogicalSpace) const;
+    double computeNormalizedFractionBreadth(Vector<GridTrack>&, const GridSpan& tracksSpan, GridTrackSizingDirection, LayoutUnit availableLogicalSpace) const;
 
     const GridTrackSize& gridTrackSize(GridTrackSizingDirection, size_t) const;
     size_t explicitGridColumnCount() const;
@@ -112,7 +112,14 @@
     LayoutUnit logicalContentHeightForChild(RenderBox*, Vector<GridTrack>&);
     LayoutUnit minContentForChild(RenderBox*, GridTrackSizingDirection, Vector<GridTrack>& columnTracks);
     LayoutUnit maxContentForChild(RenderBox*, GridTrackSizingDirection, Vector<GridTrack>& columnTracks);
-    LayoutPoint findChildLogicalPosition(RenderBox*, const GridSizingData&);
+    LayoutUnit startOfColumnForChild(const RenderBox* child) const;
+    LayoutUnit endOfColumnForChild(const RenderBox* child) const;
+    LayoutUnit columnPositionAlignedWithGridContainerStart(const RenderBox*) const;
+    LayoutUnit columnPositionAlignedWithGridContainerEnd(const RenderBox*) const;
+    LayoutUnit centeredColumnPositionForChild(const RenderBox*) const;
+    LayoutUnit columnPositionForChild(const RenderBox*) const;
+    LayoutUnit rowPositionForChild(const RenderBox*) const;
+    LayoutPoint findChildLogicalPosition(const RenderBox*) const;
     GridCoordinate cachedGridCoordinate(const RenderBox*) const;
 
     GridSpan resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, GridTrackSizingDirection, size_t) const;
@@ -126,8 +133,7 @@
 
     LayoutUnit gridAreaBreadthForChild(const RenderBox* child, GridTrackSizingDirection, const Vector<GridTrack>&) const;
 
-    virtual void paintChildren(PaintInfo&, const LayoutPoint&) OVERRIDE FINAL;
-    void paintChildrenSlowCase(PaintInfo&, const LayoutPoint&);
+    virtual void paintChildren(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     bool gridIsDirty() const { return m_gridIsDirty; }
 
@@ -154,7 +160,9 @@
     Vector<LayoutUnit> m_columnPositions;
     HashMap<const RenderBox*, GridCoordinate> m_gridItemCoordinate;
     OrderIterator m_orderIterator;
-    bool m_gridItemOverflowGridArea;
+    Vector<RenderBox*> m_gridItemsOverflowingGridArea;
+
+    friend class GridCoordinateSorter;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderGrid, isRenderGrid());
diff --git a/Source/core/rendering/RenderHTMLCanvas.cpp b/Source/core/rendering/RenderHTMLCanvas.cpp
index 96a06bb..1b83517 100644
--- a/Source/core/rendering/RenderHTMLCanvas.cpp
+++ b/Source/core/rendering/RenderHTMLCanvas.cpp
@@ -44,13 +44,17 @@
     view()->frameView()->setIsVisuallyNonEmpty();
 }
 
-bool RenderHTMLCanvas::requiresLayer() const
+LayerType RenderHTMLCanvas::layerTypeRequired() const
 {
-    if (RenderReplaced::requiresLayer())
-        return true;
+    LayerType type = RenderReplaced::layerTypeRequired();
+    if (type != NoLayer)
+        return type;
 
     HTMLCanvasElement* canvas = toHTMLCanvasElement(node());
-    return canvas && canvas->renderingContext() && canvas->renderingContext()->isAccelerated();
+    if (canvas && canvas->renderingContext() && canvas->renderingContext()->isAccelerated())
+        return NormalLayer;
+
+    return NoLayer;
 }
 
 void RenderHTMLCanvas::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
diff --git a/Source/core/rendering/RenderHTMLCanvas.h b/Source/core/rendering/RenderHTMLCanvas.h
index 6cdaf64..3c810d2 100644
--- a/Source/core/rendering/RenderHTMLCanvas.h
+++ b/Source/core/rendering/RenderHTMLCanvas.h
@@ -36,15 +36,15 @@
 public:
     explicit RenderHTMLCanvas(HTMLCanvasElement*);
 
-    virtual bool isCanvas() const { return true; }
-    virtual bool requiresLayer() const;
+    virtual bool isCanvas() const OVERRIDE { return true; }
+    virtual LayerType layerTypeRequired() const OVERRIDE;
 
     void canvasSizeChanged();
 
 private:
-    virtual const char* renderName() const { return "RenderHTMLCanvas"; }
-    virtual void paintReplaced(PaintInfo&, const LayoutPoint&);
-    virtual void intrinsicSizeChanged() { canvasSizeChanged(); }
+    virtual const char* renderName() const OVERRIDE { return "RenderHTMLCanvas"; }
+    virtual void paintReplaced(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual void intrinsicSizeChanged() OVERRIDE { canvasSizeChanged(); }
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderHTMLCanvas, isCanvas());
diff --git a/Source/core/rendering/RenderIFrame.cpp b/Source/core/rendering/RenderIFrame.cpp
index 85016cc..986240a 100644
--- a/Source/core/rendering/RenderIFrame.cpp
+++ b/Source/core/rendering/RenderIFrame.cpp
@@ -44,47 +44,21 @@
 
 bool RenderIFrame::shouldComputeSizeAsReplaced() const
 {
-    // When we're seamless, we use normal block/box sizing code except when inline.
-    return !isSeamless();
+    return true;
 }
 
 bool RenderIFrame::isInlineBlockOrInlineTable() const
 {
-    return isSeamless() && isInline();
+    return isInline();
 }
 
-LayoutUnit RenderIFrame::minPreferredLogicalWidth() const
+LayerType RenderIFrame::layerTypeRequired() const
 {
-    if (!isSeamless())
-        return RenderPart::minPreferredLogicalWidth();
+    LayerType type = RenderPart::layerTypeRequired();
+    if (type != NoLayer)
+        return type;
 
-    RenderView* childRoot = contentRootRenderer();
-    if (!childRoot)
-        return 0;
-
-    return childRoot->minPreferredLogicalWidth() + borderAndPaddingLogicalWidth();
-}
-
-LayoutUnit RenderIFrame::maxPreferredLogicalWidth() const
-{
-    if (!isSeamless())
-        return RenderPart::maxPreferredLogicalWidth();
-
-    RenderView* childRoot = contentRootRenderer();
-    if (!childRoot)
-        return 0;
-
-    return childRoot->maxPreferredLogicalWidth() + borderAndPaddingLogicalWidth();
-}
-
-bool RenderIFrame::isSeamless() const
-{
-    return node() && node()->hasTagName(iframeTag) && toHTMLIFrameElement(node())->shouldDisplaySeamlessly();
-}
-
-bool RenderIFrame::requiresLayer() const
-{
-    return RenderPart::requiresLayer() || style()->resize() != RESIZE_NONE;
+    return NormalLayer;
 }
 
 RenderView* RenderIFrame::contentRootRenderer() const
@@ -95,44 +69,14 @@
     return childFrameView ? childFrameView->frame().contentRenderer() : 0;
 }
 
-void RenderIFrame::layoutSeamlessly()
-{
-    updateLogicalWidth();
-    // FIXME: Containers set their height to 0 before laying out their kids (as we're doing here)
-    // however, this causes FrameView::layout() to add vertical scrollbars, incorrectly inflating
-    // the resulting contentHeight(). We'll need to make FrameView::layout() smarter.
-    setLogicalHeight(0);
-    updateWidgetPosition(); // Tell the Widget about our new width/height (it will also layout the child document).
-
-    // Laying out our kids is normally responsible for adjusting our height, so we set it here.
-    // Replaced elements normally do not respect padding, but seamless elements should: we'll add
-    // both padding and border to the child's logical height here.
-    FrameView* childFrameView = toFrameView(widget());
-    if (childFrameView) // Widget should never be null during layout(), but just in case.
-        setLogicalHeight(childFrameView->contentsHeight() + borderTop() + borderBottom() + paddingTop() + paddingBottom());
-    updateLogicalHeight();
-
-    updateWidgetPosition(); // Notify the Widget of our final height.
-
-    // Assert that the child document did a complete layout.
-    RenderView* childRoot = childFrameView ? childFrameView->frame().contentRenderer() : 0;
-    ASSERT(!childFrameView || !childFrameView->layoutPending());
-    ASSERT_UNUSED(childRoot, !childRoot || !childRoot->needsLayout());
-}
-
 void RenderIFrame::layout()
 {
     ASSERT(needsLayout());
 
     LayoutRectRecorder recorder(*this);
-    if (isSeamless()) {
-        layoutSeamlessly();
-        // Do not return so as to share the layer and overflow updates below.
-    } else {
-        updateLogicalWidth();
-        // No kids to layout as a replaced element.
-        updateLogicalHeight();
-    }
+    updateLogicalWidth();
+    // No kids to layout as a replaced element.
+    updateLogicalHeight();
 
     m_overflow.clear();
     addVisualEffectOverflow();
diff --git a/Source/core/rendering/RenderIFrame.h b/Source/core/rendering/RenderIFrame.h
index e8a6197..93f19d6 100644
--- a/Source/core/rendering/RenderIFrame.h
+++ b/Source/core/rendering/RenderIFrame.h
@@ -36,12 +36,7 @@
 public:
     explicit RenderIFrame(Element*);
 
-    bool isSeamless() const;
-
 private:
-    virtual LayoutUnit minPreferredLogicalWidth() const OVERRIDE;
-    virtual LayoutUnit maxPreferredLogicalWidth() const OVERRIDE;
-
     virtual bool shouldComputeSizeAsReplaced() const OVERRIDE;
     virtual bool isInlineBlockOrInlineTable() const OVERRIDE;
 
@@ -51,9 +46,7 @@
 
     virtual const char* renderName() const OVERRIDE { return "RenderPartObject"; } // Lying for now to avoid breaking tests
 
-    virtual bool requiresLayer() const OVERRIDE;
-
-    void layoutSeamlessly();
+    virtual LayerType layerTypeRequired() const OVERRIDE;
 
     RenderView* contentRootRenderer() const;
 };
diff --git a/Source/core/rendering/RenderImage.cpp b/Source/core/rendering/RenderImage.cpp
index 1be7657..7e7e5ea 100644
--- a/Source/core/rendering/RenderImage.cpp
+++ b/Source/core/rendering/RenderImage.cpp
@@ -57,12 +57,12 @@
 
 RenderImage::RenderImage(Element* element)
     : RenderReplaced(element, IntSize())
-    , m_needsToSetSizeForAltText(false)
     , m_didIncrementVisuallyNonEmptyPixelCount(false)
     , m_isGeneratedContent(false)
     , m_imageDevicePixelRatio(1.0f)
 {
     updateAltText();
+    ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this);
 }
 
 RenderImage* RenderImage::createAnonymous(Document* document)
@@ -144,11 +144,6 @@
 void RenderImage::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
     RenderReplaced::styleDidChange(diff, oldStyle);
-    if (m_needsToSetSizeForAltText) {
-        if (!m_altText.isEmpty() && setImageSizeForAltText(m_imageResource->cachedImage()))
-            imageDimensionsChanged(true /* imageSizeChanged */);
-        m_needsToSetSizeForAltText = false;
-    }
 }
 
 void RenderImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
@@ -179,17 +174,8 @@
     bool imageSizeChanged = false;
 
     // Set image dimensions, taking into account the size of the alt text.
-    if (m_imageResource->errorOccurred() || !newImage) {
-        if (!m_altText.isEmpty() && document().hasPendingStyleRecalc()) {
-            ASSERT(node());
-            if (node()) {
-                m_needsToSetSizeForAltText = true;
-                node()->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
-            }
-            return;
-        }
+    if (m_imageResource->errorOccurred() || !newImage)
         imageSizeChanged = setImageSizeForAltText(m_imageResource->cachedImage());
-    }
 
     imageDimensionsChanged(imageSizeChanged, rect);
 }
@@ -232,7 +218,7 @@
         bool hasOverrideSize = hasOverrideHeight() || hasOverrideWidth();
         if (!hasOverrideSize && !imageSizeChanged) {
             LogicalExtentComputedValues computedValues;
-            computeLogicalWidthInRegion(computedValues);
+            computeLogicalWidth(computedValues);
             LayoutUnit newWidth = computedValues.m_extent;
             computeLogicalHeight(height(), 0, computedValues);
             LayoutUnit newHeight = computedValues.m_extent;
@@ -274,7 +260,11 @@
         } else
             repaintRect = contentBoxRect();
 
-        repaintRectangle(repaintRect);
+        {
+            // FIXME: We should not be allowing repaint during layout. crbug.com/339584
+            AllowRepaintScope scoper(frameView());
+            repaintRectangle(repaintRect);
+        }
 
         // Tell any potential compositing layers that the image needs updating.
         contentChanged(ImageChanged);
@@ -360,16 +350,21 @@
 
                 // Only draw the alt text if it'll fit within the content box,
                 // and only if it fits above the error image.
-                TextRun textRun = RenderBlockFlow::constructTextRun(this, font, m_altText, style());
+                TextRun textRun = RenderBlockFlow::constructTextRun(this, font, m_altText, style(), TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, DefaultTextRunFlags | RespectDirection);
                 LayoutUnit textWidth = font.width(textRun);
                 TextRunPaintInfo textRunPaintInfo(textRun);
                 textRunPaintInfo.bounds = FloatRect(textRectOrigin, FloatSize(textWidth, fontMetrics.height()));
                 context->setFillColor(resolveColor(CSSPropertyColor));
+                if (textRun.direction() == RTL) {
+                    int availableWidth = cWidth - static_cast<int>(paddingWidth);
+                    textOrigin.move(availableWidth - ceilf(textWidth), 0);
+                }
                 if (errorPictureDrawn) {
                     if (usableWidth >= textWidth && fontMetrics.height() <= imageOffset.height())
-                        context->drawText(font, textRunPaintInfo, textOrigin);
-                } else if (usableWidth >= textWidth && usableHeight >= fontMetrics.height())
-                    context->drawText(font, textRunPaintInfo, textOrigin);
+                        context->drawBidiText(font, textRunPaintInfo, textOrigin);
+                } else if (usableWidth >= textWidth && usableHeight >= fontMetrics.height()) {
+                    context->drawBidiText(font, textRunPaintInfo, textOrigin);
+                }
             }
         }
     } else if (m_imageResource->hasImage() && cWidth > 0 && cHeight > 0) {
@@ -413,7 +408,7 @@
         return;
 
     Element* focusedElement = document.focusedElement();
-    if (!focusedElement || !isHTMLAreaElement(focusedElement))
+    if (!focusedElement || !focusedElement->hasTagName(areaTag))
         return;
 
     HTMLAreaElement* areaElement = toHTMLAreaElement(focusedElement);
@@ -573,22 +568,10 @@
     updateInnerContentRect();
 }
 
-void RenderImage::didLayout(ResourceLoadPriorityOptimizer& optimizer)
-{
-    RenderReplaced::didLayout(optimizer);
-    updateImageLoadingPriority(optimizer);
-}
-
-void RenderImage::didScroll(ResourceLoadPriorityOptimizer& optimizer)
-{
-    RenderReplaced::didScroll(optimizer);
-    updateImageLoadingPriority(optimizer);
-}
-
-void RenderImage::updateImageLoadingPriority(ResourceLoadPriorityOptimizer& optimizer)
+bool RenderImage::updateImageLoadingPriorities()
 {
     if (!m_imageResource || !m_imageResource->cachedImage() || m_imageResource->cachedImage()->isLoaded())
-        return;
+        return false;
 
     LayoutRect viewBounds = viewRect();
     LayoutRect objectBounds = absoluteContentBox();
@@ -604,7 +587,9 @@
     ResourceLoadPriorityOptimizer::VisibilityStatus status = isVisible ?
         ResourceLoadPriorityOptimizer::Visible : ResourceLoadPriorityOptimizer::NotVisible;
 
-    optimizer.notifyImageResourceVisibility(m_imageResource->cachedImage(), status);
+    ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->notifyImageResourceVisibility(m_imageResource->cachedImage(), status);
+
+    return true;
 }
 
 void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
@@ -621,7 +606,8 @@
         }
     }
     // Don't compute an intrinsic ratio to preserve historical WebKit behavior if we're painting alt text and/or a broken image.
-    if (m_imageResource && m_imageResource->errorOccurred()) {
+    // Video is excluded from this behavior because video elements have a default aspect ratio that a failed poster image load should not override.
+    if (m_imageResource && m_imageResource->errorOccurred() && !isVideo()) {
         intrinsicRatio = 1;
         return;
     }
diff --git a/Source/core/rendering/RenderImage.h b/Source/core/rendering/RenderImage.h
index d7e67f0..56171af 100644
--- a/Source/core/rendering/RenderImage.h
+++ b/Source/core/rendering/RenderImage.h
@@ -71,28 +71,26 @@
 
     virtual void styleDidChange(StyleDifference, const RenderStyle*) OVERRIDE FINAL;
 
-    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0);
+    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
     void paintIntoRect(GraphicsContext*, const LayoutRect&);
     virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE FINAL;
-    virtual void layout();
-    virtual void didLayout(ResourceLoadPriorityOptimizer&);
-    virtual void didScroll(ResourceLoadPriorityOptimizer&);
-    void updateImageLoadingPriority(ResourceLoadPriorityOptimizer&);
+    virtual void layout() OVERRIDE;
+    virtual bool updateImageLoadingPriorities() OVERRIDE FINAL;
 
-    virtual void intrinsicSizeChanged()
+    virtual void intrinsicSizeChanged() OVERRIDE
     {
         if (m_imageResource)
             imageChanged(m_imageResource->imagePtr());
     }
 
 private:
-    virtual const char* renderName() const { return "RenderImage"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderImage"; }
 
-    virtual bool isImage() const { return true; }
+    virtual bool isImage() const OVERRIDE { return true; }
     virtual bool isRenderImage() const OVERRIDE FINAL { return true; }
 
-    virtual void paintReplaced(PaintInfo&, const LayoutPoint&);
+    virtual void paintReplaced(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     virtual bool foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const OVERRIDE FINAL;
     virtual bool computeBackgroundIsKnownToBeObscured() OVERRIDE FINAL;
@@ -115,7 +113,6 @@
     // Text to display as long as the image isn't available.
     String m_altText;
     OwnPtr<RenderImageResource> m_imageResource;
-    bool m_needsToSetSizeForAltText;
     bool m_didIncrementVisuallyNonEmptyPixelCount;
     bool m_isGeneratedContent;
     float m_imageDevicePixelRatio;
diff --git a/Source/core/rendering/RenderImageResource.cpp b/Source/core/rendering/RenderImageResource.cpp
index 12ab723..01be325 100644
--- a/Source/core/rendering/RenderImageResource.cpp
+++ b/Source/core/rendering/RenderImageResource.cpp
@@ -97,11 +97,6 @@
         m_cachedImage->setContainerSizeForRenderer(m_renderer, imageContainerSize, m_renderer->style()->effectiveZoom());
 }
 
-Image* RenderImageResource::nullImage()
-{
-    return Image::nullImage();
-}
-
 LayoutSize RenderImageResource::getImageSize(float multiplier, ImageResource::SizeType type) const
 {
     if (!m_cachedImage)
diff --git a/Source/core/rendering/RenderImageResource.h b/Source/core/rendering/RenderImageResource.h
index cae42e2..2850d72 100644
--- a/Source/core/rendering/RenderImageResource.h
+++ b/Source/core/rendering/RenderImageResource.h
@@ -29,8 +29,6 @@
 #include "core/fetch/ImageResource.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/rendering/style/StyleImage.h"
-#include "platform/geometry/LayoutSize.h"
-#include "platform/graphics/Image.h"
 
 namespace WebCore {
 
@@ -55,7 +53,10 @@
 
     void resetAnimation();
 
-    virtual PassRefPtr<Image> image(int /* width */ = 0, int /* height */ = 0) const { return m_cachedImage ? m_cachedImage->imageForRenderer(m_renderer) : nullImage(); }
+    virtual PassRefPtr<Image> image(int /* width */ = 0, int /* height */ = 0) const
+    {
+        return m_cachedImage ? m_cachedImage->imageForRenderer(m_renderer) : Image::nullImage();
+    }
     virtual bool errorOccurred() const { return m_cachedImage && m_cachedImage->errorOccurred(); }
 
     virtual void setContainerSizeForRenderer(const IntSize&);
@@ -74,7 +75,6 @@
     ResourcePtr<ImageResource> m_cachedImage;
 
 private:
-    static Image* nullImage();
     LayoutSize getImageSize(float multiplier, ImageResource::SizeType) const;
 };
 
diff --git a/Source/core/rendering/RenderImageResourceStyleImage.h b/Source/core/rendering/RenderImageResourceStyleImage.h
index 6844e2a..098cc63 100644
--- a/Source/core/rendering/RenderImageResourceStyleImage.h
+++ b/Source/core/rendering/RenderImageResourceStyleImage.h
@@ -34,7 +34,7 @@
 
 class RenderObject;
 
-class RenderImageResourceStyleImage : public RenderImageResource {
+class RenderImageResourceStyleImage FINAL : public RenderImageResource {
 public:
     virtual ~RenderImageResourceStyleImage();
 
@@ -42,22 +42,22 @@
     {
         return adoptPtr(new RenderImageResourceStyleImage(styleImage));
     }
-    virtual void initialize(RenderObject*);
-    virtual void shutdown();
+    virtual void initialize(RenderObject*) OVERRIDE;
+    virtual void shutdown() OVERRIDE;
 
-    virtual bool hasImage() const { return true; }
-    virtual PassRefPtr<Image> image(int width = 0, int height = 0) const;
-    virtual bool errorOccurred() const { return m_styleImage->errorOccurred(); }
+    virtual bool hasImage() const OVERRIDE { return true; }
+    virtual PassRefPtr<Image> image(int width = 0, int height = 0) const OVERRIDE;
+    virtual bool errorOccurred() const OVERRIDE { return m_styleImage->errorOccurred(); }
 
-    virtual void setContainerSizeForRenderer(const IntSize&);
-    virtual bool usesImageContainerSize() const { return m_styleImage->usesImageContainerSize(); }
-    virtual bool imageHasRelativeWidth() const { return m_styleImage->imageHasRelativeWidth(); }
-    virtual bool imageHasRelativeHeight() const { return m_styleImage->imageHasRelativeHeight(); }
+    virtual void setContainerSizeForRenderer(const IntSize&) OVERRIDE;
+    virtual bool usesImageContainerSize() const OVERRIDE { return m_styleImage->usesImageContainerSize(); }
+    virtual bool imageHasRelativeWidth() const OVERRIDE { return m_styleImage->imageHasRelativeWidth(); }
+    virtual bool imageHasRelativeHeight() const OVERRIDE { return m_styleImage->imageHasRelativeHeight(); }
 
     virtual LayoutSize imageSize(float multiplier) const OVERRIDE { return m_styleImage->imageSize(m_renderer, multiplier); }
     virtual LayoutSize intrinsicSize(float multiplier) const OVERRIDE { return m_styleImage->imageSize(m_renderer, multiplier); }
 
-    virtual WrappedImagePtr imagePtr() const { return m_styleImage->data(); }
+    virtual WrappedImagePtr imagePtr() const OVERRIDE { return m_styleImage->data(); }
 
 private:
     RenderImageResourceStyleImage(StyleImage*);
diff --git a/Source/core/rendering/RenderInline.cpp b/Source/core/rendering/RenderInline.cpp
index bd82486..90a4c32 100644
--- a/Source/core/rendering/RenderInline.cpp
+++ b/Source/core/rendering/RenderInline.cpp
@@ -210,14 +210,12 @@
     RenderStyle* parentStyle = parent()->style();
     RenderInline* parentRenderInline = parent()->isRenderInline() ? toRenderInline(parent()) : 0;
     bool checkFonts = document().inNoQuirksMode();
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
     bool alwaysCreateLineBoxes = (parentRenderInline && parentRenderInline->alwaysCreateLineBoxes())
         || (parentRenderInline && parentStyle->verticalAlign() != BASELINE)
         || style()->verticalAlign() != BASELINE
         || style()->textEmphasisMark() != TextEmphasisMarkNone
         || (checkFonts && (!parentStyle->font().fontMetrics().hasIdenticalAscentDescentAndLineGap(style()->font().fontMetrics())
-        || parentStyle->lineHeight() != style()->lineHeight()))
-        || (flowThread && flowThread->hasRegionsWithStyling());
+        || parentStyle->lineHeight() != style()->lineHeight()));
 
     if (!alwaysCreateLineBoxes && checkFonts && document().styleEngine()->usesFirstLineRules()) {
         // Have to check the first line style as well.
@@ -696,8 +694,6 @@
         return margin.value();
     if (margin.isPercent())
         return minimumValueForLength(margin, max<LayoutUnit>(0, renderer->containingBlock()->availableLogicalWidth()));
-    if (margin.isViewportPercentage())
-        return valueForLength(margin, 0, renderer->view());
     return 0;
 }
 
@@ -1290,10 +1286,10 @@
     if (firstLine && document().styleEngine()->usesFirstLineRules()) {
         RenderStyle* s = style(firstLine);
         if (s != style())
-            return s->computedLineHeight(view());
+            return s->computedLineHeight();
     }
 
-    return style()->computedLineHeight(view());
+    return style()->computedLineHeight();
 }
 
 int RenderInline::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
diff --git a/Source/core/rendering/RenderInline.h b/Source/core/rendering/RenderInline.h
index c69f025..e3a9f0c 100644
--- a/Source/core/rendering/RenderInline.h
+++ b/Source/core/rendering/RenderInline.h
@@ -40,7 +40,7 @@
     RenderObject* firstChild() const { ASSERT(children() == virtualChildren()); return children()->firstChild(); }
     RenderObject* lastChild() const { ASSERT(children() == virtualChildren()); return children()->lastChild(); }
 
-    virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0);
+    virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0) OVERRIDE;
 
     Element* node() const { return toElement(RenderBoxModelObject::node()); }
 
@@ -54,7 +54,7 @@
     virtual LayoutUnit marginEnd(const RenderStyle* otherStyle = 0) const OVERRIDE FINAL;
 
     virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE FINAL;
-    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
+    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const OVERRIDE;
 
     virtual LayoutSize offsetFromContainer(RenderObject*, const LayoutPoint&, bool* offsetDependsOnPoint = 0) const OVERRIDE FINAL;
 
@@ -96,7 +96,7 @@
     bool hitTestCulledInline(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset);
 
 protected:
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
@@ -108,7 +108,7 @@
     const RenderObjectChildList* children() const { return &m_children; }
     RenderObjectChildList* children() { return &m_children; }
 
-    virtual const char* renderName() const;
+    virtual const char* renderName() const OVERRIDE;
 
     virtual bool isRenderInline() const OVERRIDE FINAL { return true; }
 
@@ -135,7 +135,7 @@
 
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE FINAL;
 
-    virtual bool requiresLayer() const { return isInFlowPositioned() || createsGroup() || hasClipPath(); }
+    virtual LayerType layerTypeRequired() const OVERRIDE { return isInFlowPositioned() || createsGroup() || hasClipPath() ? NormalLayer : NoLayer; }
 
     virtual LayoutUnit offsetLeft() const OVERRIDE FINAL;
     virtual LayoutUnit offsetTop() const OVERRIDE FINAL;
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index a492706..26a550c 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -52,12 +52,12 @@
 #include "core/css/PseudoStyleRequest.h"
 #include "core/dom/Document.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/html/HTMLFrameElement.h"
+#include "core/frame/DeprecatedScheduleStyleRecalcDuringLayout.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
+#include "core/html/HTMLFrameElement.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/frame/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/rendering/ColumnInfo.h"
 #include "core/rendering/CompositedLayerMapping.h"
@@ -84,10 +84,6 @@
 #include "platform/graphics/GraphicsContextStateSaver.h"
 #include "platform/graphics/filters/ReferenceFilter.h"
 #include "platform/graphics/filters/SourceGraphic.h"
-#include "platform/graphics/filters/custom/CustomFilterGlobalContext.h"
-#include "platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
-#include "platform/graphics/filters/custom/ValidatedCustomFilterOperation.h"
 #include "platform/transforms/ScaleTransformOperation.h"
 #include "platform/transforms/TransformationMatrix.h"
 #include "platform/transforms/TranslateTransformOperation.h"
@@ -99,10 +95,18 @@
 
 namespace WebCore {
 
+namespace {
+
+static CompositingQueryMode gCompositingQueryMode =
+    CompositingQueriesAreOnlyAllowedInCertainDocumentLifecyclePhases;
+
+} // namespace
+
 using namespace HTMLNames;
 
-RenderLayer::RenderLayer(RenderLayerModelObject* renderer)
-    : m_hasSelfPaintingLayerDescendant(false)
+RenderLayer::RenderLayer(RenderLayerModelObject* renderer, LayerType type)
+    : m_isOverflowOnlyLayer(type == OverflowClipLayer)
+    , m_hasSelfPaintingLayerDescendant(false)
     , m_hasSelfPaintingLayerDescendantDirty(false)
     , m_hasOutOfFlowPositionedDescendant(false)
     , m_hasOutOfFlowPositionedDescendantDirty(true)
@@ -110,8 +114,6 @@
     , m_isUnclippedDescendant(false)
     , m_isRootLayer(renderer->isRenderView())
     , m_usedTransparency(false)
-    , m_childLayerHasBlendMode(false)
-    , m_childLayerHasBlendModeStatusDirty(false)
     , m_visibleContentStatusDirty(true)
     , m_hasVisibleContent(false)
     , m_visibleDescendantStatusDirty(false)
@@ -123,7 +125,6 @@
     , m_containsDirtyOverlayScrollbars(false)
     , m_canSkipRepaintRectsUpdateOnScroll(renderer->isTableCell())
     , m_hasFilterInfo(false)
-    , m_blendMode(blink::WebBlendModeNormal)
     , m_renderer(renderer)
     , m_parent(0)
     , m_previous(0)
@@ -133,8 +134,11 @@
     , m_staticInlinePosition(0)
     , m_staticBlockPosition(0)
     , m_enclosingPaginationLayer(0)
+    , m_3dRenderingContextRoot(0)
+    , m_groupedMapping(0)
     , m_repainter(renderer)
     , m_clipper(renderer)
+    , m_blendInfo(renderer)
 {
     updateStackingNode();
 
@@ -160,6 +164,11 @@
 
     removeFilterInfoIfNeeded();
 
+    if (groupedMapping()) {
+        groupedMapping()->removeRenderLayerFromSquashingGraphicsLayer(this);
+        setGroupedMapping(0);
+    }
+
     // Child layers will be deleted by their corresponding render objects, so
     // we don't need to delete them ourselves.
 
@@ -168,8 +177,10 @@
 
 String RenderLayer::debugName() const
 {
-    if (isReflection())
+    if (isReflection()) {
+        ASSERT(m_reflectionInfo);
         return m_reflectionInfo->debugName();
+    }
     return renderer()->debugName();
 }
 
@@ -182,9 +193,11 @@
 
 void RenderLayer::contentChanged(ContentChangeType changeType)
 {
+    DisableCompositingQueryAsserts disabler;
+
     // This can get called when video becomes accelerated, so the layers may change.
-    if ((changeType == CanvasChanged || changeType == VideoChanged || changeType == FullScreenChanged) && compositor()->updateLayerCompositingState(this))
-        compositor()->setCompositingLayersNeedRebuild();
+    if (changeType == CanvasChanged || changeType == VideoChanged || changeType == FullScreenChanged)
+        compositor()->updateLayerCompositingState(this);
 
     if (m_compositedLayerMapping)
         m_compositedLayerMapping->contentChanged(changeType);
@@ -200,6 +213,8 @@
     if (!renderer()->hasFilter())
         return false;
 
+    // https://code.google.com/p/chromium/issues/detail?id=343759
+    DisableCompositingQueryAsserts disabler;
     if (compositingState() != PaintsIntoOwnBacking)
         return true;
 
@@ -241,6 +256,12 @@
 
 void RenderLayer::updateLayerPositionsAfterLayout(const RenderLayer* rootLayer, UpdateLayerPositionsFlags flags)
 {
+    TRACE_EVENT0("blink_rendering", "RenderLayer::updateLayerPositionsAfterLayout");
+
+    // FIXME: Remove incremental compositing updates after fixing the chicken/egg issues
+    // https://code.google.com/p/chromium/issues/detail?id=343756
+    DisableCompositingQueryAsserts disabler;
+
     RenderGeometryMap geometryMap(UseTransforms);
     if (this != rootLayer)
         geometryMap.pushMappingsToAncestor(parent(), 0);
@@ -367,23 +388,6 @@
     }
 }
 
-bool RenderLayer::acceleratedCompositingForOverflowScrollEnabled() const
-{
-    const Settings* settings = renderer()->document().settings();
-    return settings && settings->acceleratedCompositingForOverflowScrollEnabled();
-}
-
-// FIXME: This is a temporary flag and should be removed once accelerated
-// overflow scroll is ready (crbug.com/254111).
-bool RenderLayer::compositorDrivenAcceleratedScrollingEnabled() const
-{
-    if (!acceleratedCompositingForOverflowScrollEnabled())
-        return false;
-
-    const Settings* settings = renderer()->document().settings();
-    return settings && settings->isCompositorDrivenAcceleratedScrollingEnabled();
-}
-
 bool RenderLayer::scrollsWithRespectTo(const RenderLayer* other) const
 {
     const EPosition position = renderer()->style()->position();
@@ -494,6 +498,9 @@
 
     if (flags & HasSeenViewportConstrainedAncestor
         || (flags & IsOverflowScroll && flags & HasSeenAncestorWithOverflowClip && !m_canSkipRepaintRectsUpdateOnScroll)) {
+        // FIXME: Remove incremental compositing updates after fixing the chicken/egg issues
+        // https://code.google.com/p/chromium/issues/detail?id=343756
+        DisableCompositingQueryAsserts disabler;
         // FIXME: We could track the repaint container as we walk down the tree.
         repainter().computeRepaintRects(renderer()->containerForRepaint(), geometryMap);
     } else {
@@ -514,30 +521,6 @@
         geometryMap->popMappingsToAncestor(parent());
 }
 
-bool RenderLayer::hasBlendMode() const
-{
-    return RuntimeEnabledFeatures::cssCompositingEnabled() && renderer()->hasBlendMode();
-}
-
-void RenderLayer::updateBlendMode()
-{
-    if (!RuntimeEnabledFeatures::cssCompositingEnabled())
-        return;
-
-    bool hadBlendMode = m_blendMode != blink::WebBlendModeNormal;
-    blink::WebBlendMode newBlendMode = renderer()->style()->blendMode();
-    if (newBlendMode != m_blendMode) {
-        m_blendMode = newBlendMode;
-
-        // Only update the flag if a blend mode is set or unset.
-        if (parent() && (!hadBlendMode || !hasBlendMode()))
-            parent()->dirtyAncestorChainBlendedDescendantStatus();
-
-        if (hasCompositedLayerMapping())
-            compositedLayerMapping()->setBlendMode(newBlendMode);
-    }
-}
-
 void RenderLayer::updateTransform()
 {
     // hasTransform() on the renderer is also true when there is transform-style: preserve-3d or perspective set,
@@ -568,20 +551,27 @@
         dirty3DTransformedDescendantStatus();
 }
 
+// Note: this function assumes that all ancestors have an updated 3d rendering context root.
+void RenderLayer::update3dRenderingContext()
+{
+    m_3dRenderingContextRoot = 0;
+
+    if (!shouldFlattenTransform())
+        m_3dRenderingContextRoot = this;
+
+    if (RenderObject* containingBlock = renderer()->containingBlock()) {
+        if (RenderLayer* ancestorLayer = containingBlock->enclosingLayer()) {
+            if (!ancestorLayer->shouldFlattenTransform())
+                m_3dRenderingContextRoot = ancestorLayer->renderingContextRoot();
+        }
+    }
+}
+
 TransformationMatrix RenderLayer::currentTransform(RenderStyle::ApplyTransformOrigin applyOrigin) const
 {
     if (!m_transform)
         return TransformationMatrix();
 
-    // FIXME: handle this under web-animations
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled() && renderer()->style()->isRunningAcceleratedAnimation()) {
-        TransformationMatrix currTransform;
-        RefPtr<RenderStyle> style = renderer()->animation().getAnimatedStyleForRenderer(renderer());
-        style->applyTransform(currTransform, renderBox()->pixelSnappedBorderBoxRect().size(), applyOrigin);
-        makeMatrixRenderable(currTransform, canRender3DTransforms());
-        return currTransform;
-    }
-
     // m_transform includes transform-origin, so we need to recompute the transform here.
     if (applyOrigin == RenderStyle::ExcludeTransformOrigin) {
         RenderBox* box = renderBox();
@@ -608,6 +598,18 @@
     return *m_transform;
 }
 
+RenderLayer* RenderLayer::enclosingOverflowClipLayer(IncludeSelfOrNot includeSelf) const
+{
+    const RenderLayer* layer = (includeSelf == IncludeSelf) ? this : parent();
+    while (layer) {
+        if (layer->renderer()->hasOverflowClip())
+            return const_cast<RenderLayer*>(layer);
+
+        layer = layer->parent();
+    }
+    return 0;
+}
+
 static bool checkContainingBlockChainForPagination(RenderLayerModelObject* renderer, RenderBox* ancestorColumnsRenderer)
 {
     RenderView* view = renderer->view();
@@ -632,8 +634,7 @@
 
 bool RenderLayer::useRegionBasedColumns() const
 {
-    const Settings* settings = renderer()->document().settings();
-    return settings && settings->regionBasedColumnsEnabled();
+    return renderer()->document().regionBasedColumnsEnabled();
 }
 
 void RenderLayer::updatePagination()
@@ -757,33 +758,6 @@
     }
 }
 
-void RenderLayer::dirtyAncestorChainBlendedDescendantStatus()
-{
-    for (RenderLayer* layer = this; layer; layer = layer->parent()) {
-        if (layer->m_childLayerHasBlendModeStatusDirty)
-            break;
-
-        layer->m_childLayerHasBlendModeStatusDirty = true;
-
-        if (layer->stackingNode()->isStackingContext())
-            break;
-    }
-}
-
-void RenderLayer::setAncestorChainBlendedDescendant()
-{
-    for (RenderLayer* layer = this; layer; layer = layer->parent()) {
-        if (!layer->m_childLayerHasBlendModeStatusDirty && layer->childLayerHasBlendMode())
-            break;
-
-        layer->m_childLayerHasBlendMode = true;
-        layer->m_childLayerHasBlendModeStatusDirty = false;
-
-        if (layer->stackingNode()->isStackingContext())
-            break;
-    }
-}
-
 void RenderLayer::updateHasUnclippedDescendant()
 {
     TRACE_EVENT0("blink_rendering", "RenderLayer::updateHasUnclippedDescendant");
@@ -857,19 +831,22 @@
         m_hasOutOfFlowPositionedDescendantDirty = false;
     }
 
-    if (m_childLayerHasBlendModeStatusDirty) {
-        m_childLayerHasBlendMode = false;
+    if (m_blendInfo.childLayerHasBlendModeStatusDirty()) {
+        m_blendInfo.setChildLayerHasBlendMode(false);
         for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
             if (!child->stackingNode()->isStackingContext())
                 child->updateDescendantDependentFlags();
 
-            bool childLayerHasBlendMode = child->paintsWithBlendMode() || (child->m_childLayerHasBlendMode && !child->stackingNode()->isStackingContext());
-            m_childLayerHasBlendMode |= childLayerHasBlendMode;
+            bool childLayerHasBlendMode = child->blendInfo().childLayerHasBlendModeWhileDirty();
+            childLayerHasBlendMode |= child->paintsWithBlendMode()
+                || (childLayerHasBlendMode && !child->stackingNode()->isStackingContext());
 
-            if (m_childLayerHasBlendMode)
+            m_blendInfo.setChildLayerHasBlendMode(childLayerHasBlendMode);
+
+            if (childLayerHasBlendMode)
                 break;
         }
-        m_childLayerHasBlendModeStatusDirty = false;
+        m_blendInfo.setChildLayerHasBlendModeStatusDirty(false);
     }
 
     if (m_visibleContentStatusDirty) {
@@ -1085,14 +1062,6 @@
     return curr;
 }
 
-RenderLayer* RenderLayer::enclosingScrollableLayer() const
-{
-    if (RenderBox* enclosingScrollableBox = renderer()->enclosingScrollableBox())
-        return enclosingScrollableBox->layer();
-
-    return 0;
-}
-
 RenderLayer* RenderLayer::enclosingTransformedAncestor() const
 {
     RenderLayer* curr = parent();
@@ -1102,35 +1071,40 @@
     return curr;
 }
 
-static inline const RenderLayer* compositingContainer(const RenderLayer* layer)
+const RenderLayer* RenderLayer::compositingContainer() const
 {
-    return layer->stackingNode()->isNormalFlowOnly() ? layer->parent() : (layer->stackingNode()->ancestorStackingContainerNode() ? layer->stackingNode()->ancestorStackingContainerNode()->layer() : 0);
+    return stackingNode()->isNormalFlowOnly() ? parent() : (stackingNode()->ancestorStackingContainerNode() ? stackingNode()->ancestorStackingContainerNode()->layer() : 0);
 }
 
 // FIXME: having two different functions named enclosingCompositingLayer and enclosingCompositingLayerForRepaint
 // is error-prone and misleading for reading code that uses these functions - especially compounded with
-// the includeSelf option. It is very likely that some call sites of this function actually mean to use
-// enclosingCompositingLayerForRepaint().
-RenderLayer* RenderLayer::enclosingCompositingLayer(bool includeSelf) const
+// the includeSelf option. It is very likely that we don't even want either of these functions; A layer
+// should be told explicitly which GraphicsLayer is the repaintContainer for a RenderLayer, and
+// any other use cases should probably have an API between the non-compositing and compositing sides of code.
+RenderLayer* RenderLayer::enclosingCompositingLayer(IncludeSelfOrNot includeSelf) const
 {
-    if (includeSelf && hasCompositedLayerMapping())
+    ASSERT(isAllowedToQueryCompositingState());
+
+    if ((includeSelf == IncludeSelf) && compositingState() != NotComposited && compositingState() != PaintsIntoGroupedBacking)
         return const_cast<RenderLayer*>(this);
 
-    for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
-        if (curr->hasCompositedLayerMapping())
+    for (const RenderLayer* curr = compositingContainer(); curr; curr = curr->compositingContainer()) {
+        if (curr->compositingState() != NotComposited && curr->compositingState() != PaintsIntoGroupedBacking)
             return const_cast<RenderLayer*>(curr);
     }
 
     return 0;
 }
 
-RenderLayer* RenderLayer::enclosingCompositingLayerForRepaint(bool includeSelf) const
+RenderLayer* RenderLayer::enclosingCompositingLayerForRepaint(IncludeSelfOrNot includeSelf) const
 {
-    if (includeSelf && compositingState() == PaintsIntoOwnBacking)
+    ASSERT(isAllowedToQueryCompositingState());
+
+    if ((includeSelf == IncludeSelf) && (compositingState() == PaintsIntoOwnBacking || compositingState() == PaintsIntoGroupedBacking))
         return const_cast<RenderLayer*>(this);
 
-    for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
-        if (curr->compositingState() == PaintsIntoOwnBacking)
+    for (const RenderLayer* curr = compositingContainer(); curr; curr = curr->compositingContainer()) {
+        if (curr->compositingState() == PaintsIntoOwnBacking || curr->compositingState() == PaintsIntoGroupedBacking)
             return const_cast<RenderLayer*>(curr);
     }
 
@@ -1139,7 +1113,9 @@
 
 RenderLayer* RenderLayer::ancestorCompositedScrollingLayer() const
 {
-    if (!acceleratedCompositingForOverflowScrollEnabled())
+    ASSERT(isAllowedToQueryCompositingState());
+
+    if (!renderer()->acceleratedCompositingForOverflowScrollEnabled())
         return 0;
 
     RenderObject* containingBlock = renderer()->containingBlock();
@@ -1168,9 +1144,9 @@
     return 0;
 }
 
-RenderLayer* RenderLayer::enclosingFilterLayer(bool includeSelf) const
+RenderLayer* RenderLayer::enclosingFilterLayer(IncludeSelfOrNot includeSelf) const
 {
-    const RenderLayer* curr = includeSelf ? this : parent();
+    const RenderLayer* curr = (includeSelf == IncludeSelf) ? this : parent();
     for (; curr; curr = curr->parent()) {
         if (curr->requiresFullLayerImageForFilters())
             return const_cast<RenderLayer*>(curr);
@@ -1189,28 +1165,6 @@
     return false;
 }
 
-RenderLayer* RenderLayer::clippingRootForPainting() const
-{
-    if (hasCompositedLayerMapping())
-        return const_cast<RenderLayer*>(this);
-
-    const RenderLayer* current = this;
-    while (current) {
-        if (current->isRootLayer())
-            return const_cast<RenderLayer*>(current);
-
-        current = compositingContainer(current);
-        ASSERT(current);
-        if (current->transform()
-            || (current->compositingState() == PaintsIntoOwnBacking)
-        )
-            return const_cast<RenderLayer*>(current);
-    }
-
-    ASSERT_NOT_REACHED();
-    return 0;
-}
-
 bool RenderLayer::cannotBlitToWindow() const
 {
     if (isTransparent() || m_reflectionInfo || hasTransform())
@@ -1335,7 +1289,7 @@
 
 void RenderLayer::beginTransparencyLayers(GraphicsContext* context, const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior)
 {
-    bool createTransparencyLayerForBlendMode = m_stackingNode->isStackingContext() && m_childLayerHasBlendMode;
+    bool createTransparencyLayerForBlendMode = m_stackingNode->isStackingContext() && m_blendInfo.childLayerHasBlendMode();
     if (context->paintingDisabled() || ((paintsWithTransparency(paintBehavior) || paintsWithBlendMode() || createTransparencyLayerForBlendMode) && m_usedTransparency))
         return;
 
@@ -1348,10 +1302,14 @@
         context->save();
         LayoutRect clipRect = paintingExtent(rootLayer, paintDirtyRect, paintBehavior);
         context->clip(clipRect);
+
         if (paintsWithBlendMode())
-            context->setCompositeOperation(context->compositeOperation(), m_blendMode);
+            context->setCompositeOperation(context->compositeOperation(), m_blendInfo.blendMode());
 
         context->beginTransparencyLayer(renderer()->opacity());
+
+        if (paintsWithBlendMode())
+            context->setCompositeOperation(context->compositeOperation(), blink::WebBlendModeNormal);
 #ifdef REVEAL_TRANSPARENCY_LAYERS
         context->setFillColor(Color(0.0f, 0.0f, 0.5f, 0.2f));
         context->fillRect(clipRect);
@@ -1405,8 +1363,8 @@
     if (child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant())
         setAncestorChainHasSelfPaintingLayerDescendant();
 
-    if (child->paintsWithBlendMode() || child->childLayerHasBlendMode())
-        setAncestorChainBlendedDescendant();
+    if (child->paintsWithBlendMode() || child->blendInfo().childLayerHasBlendMode())
+        m_blendInfo.setAncestorChainBlendedDescendant();
 
     if (subtreeContainsOutOfFlowPositionedLayer(child)) {
         // Now that the out of flow positioned descendant is in the tree, we
@@ -1466,8 +1424,8 @@
     if (oldChild->m_hasVisibleContent || oldChild->m_hasVisibleDescendant)
         dirtyAncestorChainVisibleDescendantStatus();
 
-    if (oldChild->paintsWithBlendMode() || oldChild->childLayerHasBlendMode())
-        dirtyAncestorChainBlendedDescendantStatus();
+    if (oldChild->paintsWithBlendMode() || oldChild->blendInfo().childLayerHasBlendMode())
+        m_blendInfo.dirtyAncestorChainBlendedDescendantStatus();
 
     if (oldChild->isSelfPaintingLayer() || oldChild->hasSelfPaintingLayerDescendant())
         dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
@@ -1557,7 +1515,7 @@
     // FIXME: Positioning of out-of-flow(fixed, absolute) elements collected in a RenderFlowThread
     // may need to be revisited in a future patch.
     // If the fixed renderer is inside a RenderFlowThread, we should not compute location using localToAbsolute,
-    // since localToAbsolute maps the coordinates from named flow to regions coordinates and regions can be
+    // since localToAbsolute maps the coordinates from flow thread to regions coordinates and regions can be
     // positioned in a completely different place in the viewport (RenderView).
     if (position == FixedPosition && !fixedFlowThreadContainer && (!ancestorLayer || ancestorLayer == renderer->view()->layer())) {
         // If the fixed layer's container is the root, just add in the offset of the view. We can obtain this by calling
@@ -1671,7 +1629,7 @@
 
 RenderLayer* RenderLayer::scrollParent() const
 {
-    if (!compositorDrivenAcceleratedScrollingEnabled())
+    if (!renderer()->compositorDrivenAcceleratedScrollingEnabled())
         return 0;
 
     // Normal flow elements will be parented under the main scrolling layer, so
@@ -1713,7 +1671,7 @@
     RenderLayer* clipParent = 0;
     if ((compositingReasons() & CompositingReasonOutOfFlowClipping) && !needsAncestorClip) {
         if (RenderObject* containingBlock = renderer()->containingBlock())
-            clipParent = containingBlock->enclosingLayer()->enclosingCompositingLayer(true);
+            clipParent = containingBlock->enclosingLayer()->enclosingCompositingLayer();
     }
 
     return clipParent;
@@ -1737,6 +1695,7 @@
 
 void RenderLayer::updateReflectionInfo(const RenderStyle* oldStyle)
 {
+    ASSERT(!oldStyle || !renderer()->style()->reflectionDataEquivalent(oldStyle));
     if (renderer()->hasReflection()) {
         if (!m_reflectionInfo)
             m_reflectionInfo = adoptPtr(new RenderLayerReflectionInfo(toRenderBox(renderer())));
@@ -1774,11 +1733,11 @@
     return m_scrollableArea && (m_scrollableArea->hasScrollbar() || m_scrollableArea->hasScrollCorner() || renderer()->style()->resize() != RESIZE_NONE);
 }
 
-void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot, RenderRegion* region, PaintLayerFlags paintFlags)
+void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot, PaintLayerFlags paintFlags)
 {
     OverlapTestRequestMap overlapTestRequests;
 
-    LayerPaintingInfo paintingInfo(this, enclosingIntRect(damageRect), paintBehavior, LayoutSize(), paintingRoot, region, &overlapTestRequests);
+    LayerPaintingInfo paintingInfo(this, enclosingIntRect(damageRect), paintBehavior, LayoutSize(), paintingRoot, &overlapTestRequests);
     paintLayer(context, paintingInfo, paintFlags);
 
     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
@@ -1883,7 +1842,10 @@
 
 void RenderLayer::paintLayer(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
 {
-    if (compositingState() != NotComposited) {
+    // https://code.google.com/p/chromium/issues/detail?id=343772
+    DisableCompositingQueryAsserts disabler;
+
+    if (compositingState() != NotComposited && compositingState() != PaintsIntoGroupedBacking) {
         // The updatingControlTints() painting pass goes through compositing layers,
         // but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
         if (context->updatingControlTints() || (paintingInfo.paintBehavior & PaintBehaviorFlattenCompositingLayers)) {
@@ -1938,9 +1900,9 @@
         // Make sure the parent's clip rects have been calculated.
         ClipRect clipRect = paintingInfo.paintDirtyRect;
         if (parent()) {
-            ClipRectsContext clipRectsContext(paintingInfo.rootLayer, paintingInfo.region, (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects,
+            ClipRectsContext clipRectsContext(paintingInfo.rootLayer, (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects,
                 IgnoreOverlayScrollbarSize, (paintFlags & PaintLayerPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip);
-            clipRect = backgroundClipRect(clipRectsContext);
+            clipRect = clipper().backgroundClipRect(clipRectsContext);
             clipRect.intersect(paintingInfo.paintDirtyRect);
 
             // Push the parent coordinate space's clip.
@@ -2010,7 +1972,10 @@
     LayoutPoint offsetFromRoot;
     convertToLayerCoords(paintingInfo.rootLayer, offsetFromRoot);
 
-    IntRect rootRelativeBounds;
+    if (compositingState() == PaintsIntoOwnBacking)
+        offsetFromRoot.move(m_compositedLayerMapping->subpixelAccumulation());
+
+    LayoutRect rootRelativeBounds;
     bool rootRelativeBoundsComputed = false;
 
     // Apply clip-path to context.
@@ -2054,7 +2019,7 @@
 
     // Blending operations must be performed only with the nearest ancestor stacking context.
     // Note that there is no need to create a transparency layer if we're painting the root.
-    bool createTransparencyLayerForBlendMode = !renderer()->isRoot() && m_stackingNode->isStackingContext() && m_childLayerHasBlendMode;
+    bool createTransparencyLayerForBlendMode = !renderer()->isRoot() && m_stackingNode->isStackingContext() && m_blendInfo.childLayerHasBlendMode();
 
     if (createTransparencyLayerForBlendMode)
         beginTransparencyLayers(context, paintingInfo.rootLayer, paintingInfo.paintDirtyRect, paintingInfo.paintBehavior);
@@ -2067,10 +2032,8 @@
         LayoutRect filterRepaintRect = filterInfo->dirtySourceRect();
         filterRepaintRect.move(offsetFromRoot.x(), offsetFromRoot.y());
 
-        if (!rootRelativeBoundsComputed) {
+        if (!rootRelativeBoundsComputed)
             rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, &offsetFromRoot, 0);
-            rootRelativeBoundsComputed = true;
-        }
 
         if (filterPainter.prepareFilterEffect(this, rootRelativeBounds, paintingInfo.paintDirtyRect, filterRepaintRect)) {
             // Now we know for sure, that the source image will be updated, so we can revert our tracking repaint rect back to zero.
@@ -2130,9 +2093,9 @@
     if (shouldPaintContent || shouldPaintOutline || isPaintingOverlayScrollbars) {
         // Collect the fragments. This will compute the clip rectangles and paint offsets for each layer fragment, as well as whether or not the content of each
         // fragment should paint.
-        collectFragments(layerFragments, localPaintingInfo.rootLayer, localPaintingInfo.region, localPaintingInfo.paintDirtyRect,
+        collectFragments(layerFragments, localPaintingInfo.rootLayer, localPaintingInfo.paintDirtyRect,
             (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, IgnoreOverlayScrollbarSize,
-            (isPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip, &offsetFromRoot);
+            (isPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip, &offsetFromRoot, localPaintingInfo.subPixelAccumulation);
         updatePaintingInfoForFragments(layerFragments, localPaintingInfo, paintFlags, shouldPaintContent, &offsetFromRoot);
     }
 
@@ -2203,12 +2166,15 @@
     LayoutSize adjustedSubPixelAccumulation = paintingInfo.subPixelAccumulation + (delta - roundedDelta);
 
     // Apply the transform.
-    GraphicsContextStateSaver stateSaver(*context);
-    context->concatCTM(transform.toAffineTransform());
+    GraphicsContextStateSaver stateSaver(*context, false);
+    if (!transform.isIdentity()) {
+        stateSaver.save();
+        context->concatCTM(transform.toAffineTransform());
+    }
 
     // Now do a paint with the root layer shifted to be us.
     LayerPaintingInfo transformedPaintingInfo(this, enclosingIntRect(transform.inverse().mapRect(paintingInfo.paintDirtyRect)), paintingInfo.paintBehavior,
-        adjustedSubPixelAccumulation, paintingInfo.paintingRoot, paintingInfo.region, paintingInfo.overlapTestRequests);
+        adjustedSubPixelAccumulation, paintingInfo.paintingRoot, paintingInfo.overlapTestRequests);
     paintLayerContentsAndReflection(context, transformedPaintingInfo, paintFlags);
 }
 
@@ -2224,6 +2190,11 @@
     RenderLayerStackingNodeIterator iterator(*m_stackingNode, childrenToVisit);
     while (RenderLayerStackingNode* child = iterator.next()) {
         RenderLayer* childLayer = child->layer();
+
+        // Squashed RenderLayers should not paint into their ancestor.
+        if (childLayer->compositingState() == PaintsIntoGroupedBacking)
+            continue;
+
         if (!childLayer->isPaginated())
             childLayer->paintLayer(context, paintingInfo, paintFlags);
         else
@@ -2231,15 +2202,15 @@
     }
 }
 
-void RenderLayer::collectFragments(LayerFragments& fragments, const RenderLayer* rootLayer, RenderRegion* region, const LayoutRect& dirtyRect,
+void RenderLayer::collectFragments(LayerFragments& fragments, const RenderLayer* rootLayer, const LayoutRect& dirtyRect,
     ClipRectsType clipRectsType, OverlayScrollbarSizeRelevancy inOverlayScrollbarSizeRelevancy, ShouldRespectOverflowClip respectOverflowClip, const LayoutPoint* offsetFromRoot,
-    const LayoutRect* layerBoundingBox)
+    const LayoutSize& subPixelAccumulation, const LayoutRect* layerBoundingBox)
 {
     if (!enclosingPaginationLayer() || hasTransform()) {
         // For unpaginated layers, there is only one fragment.
         LayerFragment fragment;
-        ClipRectsContext clipRectsContext(rootLayer, region, clipRectsType, inOverlayScrollbarSizeRelevancy, respectOverflowClip);
-        calculateRects(clipRectsContext, dirtyRect, fragment.layerBounds, fragment.backgroundRect, fragment.foregroundRect, fragment.outlineRect, offsetFromRoot);
+        ClipRectsContext clipRectsContext(rootLayer, clipRectsType, inOverlayScrollbarSizeRelevancy, respectOverflowClip, subPixelAccumulation);
+        clipper().calculateRects(clipRectsContext, dirtyRect, fragment.layerBounds, fragment.backgroundRect, fragment.foregroundRect, fragment.outlineRect, offsetFromRoot);
         fragments.append(fragment);
         return;
     }
@@ -2250,12 +2221,12 @@
 
     // Calculate clip rects relative to the enclosingPaginationLayer. The purpose of this call is to determine our bounds clipped to intermediate
     // layers between us and the pagination context. It's important to minimize the number of fragments we need to create and this helps with that.
-    ClipRectsContext paginationClipRectsContext(enclosingPaginationLayer(), region, clipRectsType, inOverlayScrollbarSizeRelevancy, respectOverflowClip);
+    ClipRectsContext paginationClipRectsContext(enclosingPaginationLayer(), clipRectsType, inOverlayScrollbarSizeRelevancy, respectOverflowClip);
     LayoutRect layerBoundsInFlowThread;
     ClipRect backgroundRectInFlowThread;
     ClipRect foregroundRectInFlowThread;
     ClipRect outlineRectInFlowThread;
-    calculateRects(paginationClipRectsContext, PaintInfo::infiniteRect(), layerBoundsInFlowThread, backgroundRectInFlowThread, foregroundRectInFlowThread,
+    clipper().calculateRects(paginationClipRectsContext, PaintInfo::infiniteRect(), layerBoundsInFlowThread, backgroundRectInFlowThread, foregroundRectInFlowThread,
         outlineRectInFlowThread, &offsetWithinPaginatedLayer);
 
     // Take our bounding box within the flow thread and clip it.
@@ -2279,8 +2250,8 @@
     // Get the parent clip rects of the pagination layer, since we need to intersect with that when painting column contents.
     ClipRect ancestorClipRect = dirtyRect;
     if (enclosingPaginationLayer()->parent()) {
-        ClipRectsContext clipRectsContext(rootLayer, region, clipRectsType, inOverlayScrollbarSizeRelevancy, respectOverflowClip);
-        ancestorClipRect = enclosingPaginationLayer()->backgroundClipRect(clipRectsContext);
+        ClipRectsContext clipRectsContext(rootLayer, clipRectsType, inOverlayScrollbarSizeRelevancy, respectOverflowClip);
+        ancestorClipRect = enclosingPaginationLayer()->clipper().backgroundClipRect(clipRectsContext);
         ancestorClipRect.intersect(dirtyRect);
     }
 
@@ -2322,9 +2293,9 @@
     LayerFragments enclosingPaginationFragments;
     LayoutPoint offsetOfPaginationLayerFromRoot;
     LayoutRect transformedExtent = transparencyClipBox(this, enclosingPaginationLayer(), PaintingTransparencyClipBox, RootOfTransparencyClipBox, paintingInfo.paintBehavior);
-    enclosingPaginationLayer()->collectFragments(enclosingPaginationFragments, paintingInfo.rootLayer, paintingInfo.region, paintingInfo.paintDirtyRect,
+    enclosingPaginationLayer()->collectFragments(enclosingPaginationFragments, paintingInfo.rootLayer, paintingInfo.paintDirtyRect,
         (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, IgnoreOverlayScrollbarSize,
-        (paintFlags & PaintLayerPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip, &offsetOfPaginationLayerFromRoot, &transformedExtent);
+        (paintFlags & PaintLayerPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip, &offsetOfPaginationLayerFromRoot, paintingInfo.subPixelAccumulation, &transformedExtent);
 
     for (size_t i = 0; i < enclosingPaginationFragments.size(); ++i) {
         const LayerFragment& fragment = enclosingPaginationFragments.at(i);
@@ -2337,9 +2308,9 @@
         if (parent() != enclosingPaginationLayer()) {
             enclosingPaginationLayer()->convertToLayerCoords(paintingInfo.rootLayer, offsetOfPaginationLayerFromRoot);
 
-            ClipRectsContext clipRectsContext(enclosingPaginationLayer(), paintingInfo.region, (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects,
+            ClipRectsContext clipRectsContext(enclosingPaginationLayer(), (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects,
                 IgnoreOverlayScrollbarSize, (paintFlags & PaintLayerPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip);
-            LayoutRect parentClipRect = backgroundClipRect(clipRectsContext).rect();
+            LayoutRect parentClipRect = clipper().backgroundClipRect(clipRectsContext).rect();
             parentClipRect.moveBy(fragment.paginationOffset + offsetOfPaginationLayerFromRoot);
             clipRect.intersect(parentClipRect);
         }
@@ -2350,6 +2321,15 @@
     }
 }
 
+static inline LayoutSize subPixelAccumulationIfNeeded(const LayoutSize& subPixelAccumulation, CompositingState compositingState)
+{
+    // Only apply the sub-pixel accumulation if we don't paint into our own backing layer, otherwise the position
+    // of the renderer already includes any sub-pixel offset.
+    if (compositingState == PaintsIntoOwnBacking)
+        return LayoutSize();
+    return subPixelAccumulation;
+}
+
 void RenderLayer::paintBackgroundForFragments(const LayerFragments& layerFragments, GraphicsContext* context, GraphicsContext* transparencyLayerContext,
     const LayoutRect& transparencyPaintDirtyRect, bool haveTransparency, const LayerPaintingInfo& localPaintingInfo, PaintBehavior paintBehavior,
     RenderObject* paintingRootForRenderer)
@@ -2371,8 +2351,8 @@
 
         // Paint the background.
         // FIXME: Eventually we will collect the region from the fragment itself instead of just from the paint info.
-        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.backgroundRect.rect()), PaintPhaseBlockBackground, paintBehavior, paintingRootForRenderer, localPaintingInfo.region, 0, 0, localPaintingInfo.rootLayer->renderer());
-        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation));
+        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.backgroundRect.rect()), PaintPhaseBlockBackground, paintBehavior, paintingRootForRenderer, 0, 0, localPaintingInfo.rootLayer->renderer());
+        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + subPixelAccumulationIfNeeded(localPaintingInfo.subPixelAccumulation, compositingState())));
 
         if (localPaintingInfo.clipToDirtyRect)
             restoreClip(context, localPaintingInfo.paintDirtyRect, fragment.backgroundRect);
@@ -2429,10 +2409,10 @@
         if (shouldClip)
             clipToRect(localPaintingInfo.rootLayer, context, localPaintingInfo.paintDirtyRect, fragment.foregroundRect);
 
-        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.foregroundRect.rect()), phase, paintBehavior, paintingRootForRenderer, localPaintingInfo.region, 0, 0, localPaintingInfo.rootLayer->renderer());
+        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.foregroundRect.rect()), phase, paintBehavior, paintingRootForRenderer, 0, 0, localPaintingInfo.rootLayer->renderer());
         if (phase == PaintPhaseForeground)
             paintInfo.overlapTestRequests = localPaintingInfo.overlapTestRequests;
-        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation));
+        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + subPixelAccumulationIfNeeded(localPaintingInfo.subPixelAccumulation, compositingState())));
 
         if (shouldClip)
             restoreClip(context, localPaintingInfo.paintDirtyRect, fragment.foregroundRect);
@@ -2448,9 +2428,9 @@
             continue;
 
         // Paint our own outline
-        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.outlineRect.rect()), PaintPhaseSelfOutline, paintBehavior, paintingRootForRenderer, localPaintingInfo.region, 0, 0, localPaintingInfo.rootLayer->renderer());
+        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.outlineRect.rect()), PaintPhaseSelfOutline, paintBehavior, paintingRootForRenderer, 0, 0, localPaintingInfo.rootLayer->renderer());
         clipToRect(localPaintingInfo.rootLayer, context, localPaintingInfo.paintDirtyRect, fragment.outlineRect, DoNotIncludeSelfForBorderRadius);
-        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation));
+        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + subPixelAccumulationIfNeeded(localPaintingInfo.subPixelAccumulation, compositingState())));
         restoreClip(context, localPaintingInfo.paintDirtyRect, fragment.outlineRect);
     }
 }
@@ -2468,8 +2448,8 @@
 
         // Paint the mask.
         // FIXME: Eventually we will collect the region from the fragment itself instead of just from the paint info.
-        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.backgroundRect.rect()), PaintPhaseMask, PaintBehaviorNormal, paintingRootForRenderer, localPaintingInfo.region, 0, 0, localPaintingInfo.rootLayer->renderer());
-        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation));
+        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.backgroundRect.rect()), PaintPhaseMask, PaintBehaviorNormal, paintingRootForRenderer, 0, 0, localPaintingInfo.rootLayer->renderer());
+        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + subPixelAccumulationIfNeeded(localPaintingInfo.subPixelAccumulation, compositingState())));
 
         if (localPaintingInfo.clipToDirtyRect)
             restoreClip(context, localPaintingInfo.paintDirtyRect, fragment.backgroundRect);
@@ -2488,8 +2468,8 @@
             clipToRect(localPaintingInfo.rootLayer, context, localPaintingInfo.paintDirtyRect, fragment.foregroundRect, IncludeSelfForBorderRadius); // Child clipping mask painting will handle clipping to self.
 
         // Paint the the clipped mask.
-        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.backgroundRect.rect()), PaintPhaseClippingMask, PaintBehaviorNormal, paintingRootForRenderer, localPaintingInfo.region, 0, 0, localPaintingInfo.rootLayer->renderer());
-        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation));
+        PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.backgroundRect.rect()), PaintPhaseClippingMask, PaintBehaviorNormal, paintingRootForRenderer, 0, 0, localPaintingInfo.rootLayer->renderer());
+        renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + subPixelAccumulationIfNeeded(localPaintingInfo.subPixelAccumulation, compositingState())));
 
         if (localPaintingInfo.clipToDirtyRect)
             restoreClip(context, localPaintingInfo.paintDirtyRect, fragment.foregroundRect);
@@ -2502,7 +2482,7 @@
         const LayerFragment& fragment = layerFragments.at(i);
         clipToRect(localPaintingInfo.rootLayer, context, localPaintingInfo.paintDirtyRect, fragment.backgroundRect);
         if (RenderLayerScrollableArea* scrollableArea = this->scrollableArea())
-            scrollableArea->paintOverflowControls(context, roundedIntPoint(toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation)), pixelSnappedIntRect(fragment.backgroundRect.rect()), true);
+            scrollableArea->paintOverflowControls(context, roundedIntPoint(toPoint(fragment.layerBounds.location() - renderBoxLocation() + subPixelAccumulationIfNeeded(localPaintingInfo.subPixelAccumulation, compositingState()))), pixelSnappedIntRect(fragment.backgroundRect.rect()), true);
         restoreClip(context, localPaintingInfo.paintDirtyRect, fragment.backgroundRect);
     }
 }
@@ -2793,8 +2773,8 @@
 
         // Make sure the parent's clip rects have been calculated.
         if (parent()) {
-            ClipRectsContext clipRectsContext(rootLayer, hitTestLocation.region(), RootRelativeClipRects, IncludeOverlayScrollbarSize);
-            ClipRect clipRect = backgroundClipRect(clipRectsContext);
+            ClipRectsContext clipRectsContext(rootLayer, RootRelativeClipRects, IncludeOverlayScrollbarSize);
+            ClipRect clipRect = clipper().backgroundClipRect(clipRectsContext);
             // Go ahead and test the enclosing clip now.
             if (!clipRect.intersects(hitTestLocation))
                 return 0;
@@ -2879,7 +2859,7 @@
 
     // Collect the fragments. This will compute the clip rectangles for each layer fragment.
     LayerFragments layerFragments;
-    collectFragments(layerFragments, rootLayer, hitTestLocation.region(), hitTestRect, RootRelativeClipRects, IncludeOverlayScrollbarSize);
+    collectFragments(layerFragments, rootLayer, hitTestRect, RootRelativeClipRects, IncludeOverlayScrollbarSize);
 
     if (m_scrollableArea && m_scrollableArea->hitTestResizerInFragments(layerFragments, hitTestLocation)) {
         renderer()->updateHitTestResult(result, hitTestLocation.point());
@@ -2962,8 +2942,8 @@
     LayerFragments enclosingPaginationFragments;
     LayoutPoint offsetOfPaginationLayerFromRoot;
     LayoutRect transformedExtent = transparencyClipBox(this, enclosingPaginationLayer(), HitTestingTransparencyClipBox, RootOfTransparencyClipBox);
-    enclosingPaginationLayer()->collectFragments(enclosingPaginationFragments, rootLayer, hitTestLocation.region(), hitTestRect,
-        RootRelativeClipRects, IncludeOverlayScrollbarSize, RespectOverflowClip, &offsetOfPaginationLayerFromRoot, &transformedExtent);
+    enclosingPaginationLayer()->collectFragments(enclosingPaginationFragments, rootLayer, hitTestRect,
+        RootRelativeClipRects, IncludeOverlayScrollbarSize, RespectOverflowClip, &offsetOfPaginationLayerFromRoot, LayoutSize(), &transformedExtent);
 
     for (int i = enclosingPaginationFragments.size() - 1; i >= 0; --i) {
         const LayerFragment& fragment = enclosingPaginationFragments.at(i);
@@ -2976,8 +2956,8 @@
         if (parent() != enclosingPaginationLayer()) {
             enclosingPaginationLayer()->convertToLayerCoords(rootLayer, offsetOfPaginationLayerFromRoot);
 
-            ClipRectsContext clipRectsContext(enclosingPaginationLayer(), hitTestLocation.region(), RootRelativeClipRects, IncludeOverlayScrollbarSize);
-            LayoutRect parentClipRect = backgroundClipRect(clipRectsContext).rect();
+            ClipRectsContext clipRectsContext(enclosingPaginationLayer(), RootRelativeClipRects, IncludeOverlayScrollbarSize);
+            LayoutRect parentClipRect = clipper().backgroundClipRect(clipRectsContext).rect();
             parentClipRect.moveBy(fragment.paginationOffset + offsetOfPaginationLayerFromRoot);
             clipRect.intersect(parentClipRect);
         }
@@ -3209,163 +3189,6 @@
     return 0;
 }
 
-void RenderLayer::parentClipRects(const ClipRectsContext& clipRectsContext, ClipRects& clipRects) const
-{
-    ASSERT(parent());
-    if (clipRectsContext.clipRectsType == TemporaryClipRects) {
-        parent()->clipper().calculateClipRects(clipRectsContext, clipRects);
-        return;
-    }
-
-    parent()->m_clipper.updateClipRects(clipRectsContext);
-    clipRects = *parent()->clipper().clipRects(clipRectsContext);
-}
-
-static inline ClipRect backgroundClipRectForPosition(const ClipRects& parentRects, EPosition position)
-{
-    if (position == FixedPosition)
-        return parentRects.fixedClipRect();
-
-    if (position == AbsolutePosition)
-        return parentRects.posClipRect();
-
-    return parentRects.overflowClipRect();
-}
-
-ClipRect RenderLayer::backgroundClipRect(const ClipRectsContext& clipRectsContext) const
-{
-    ASSERT(parent());
-
-    ClipRects parentRects;
-
-    // If we cross into a different pagination context, then we can't rely on the cache.
-    // Just switch over to using TemporaryClipRects.
-    if (clipRectsContext.clipRectsType != TemporaryClipRects && parent()->enclosingPaginationLayer() != enclosingPaginationLayer()) {
-        ClipRectsContext tempContext(clipRectsContext);
-        tempContext.clipRectsType = TemporaryClipRects;
-        parentClipRects(tempContext, parentRects);
-    } else
-        parentClipRects(clipRectsContext, parentRects);
-
-    ClipRect backgroundClipRect = backgroundClipRectForPosition(parentRects, renderer()->style()->position());
-    RenderView* view = renderer()->view();
-    ASSERT(view);
-
-    // Note: infinite clipRects should not be scrolled here, otherwise they will accidentally no longer be considered infinite.
-    if (parentRects.fixed() && clipRectsContext.rootLayer->renderer() == view && backgroundClipRect != PaintInfo::infiniteRect())
-        backgroundClipRect.move(view->frameView()->scrollOffsetForFixedPosition());
-
-    return backgroundClipRect;
-}
-
-void RenderLayer::calculateRects(const ClipRectsContext& clipRectsContext, const LayoutRect& paintDirtyRect, LayoutRect& layerBounds,
-    ClipRect& backgroundRect, ClipRect& foregroundRect, ClipRect& outlineRect, const LayoutPoint* offsetFromRoot) const
-{
-    if (clipRectsContext.rootLayer != this && parent()) {
-        backgroundRect = backgroundClipRect(clipRectsContext);
-        backgroundRect.intersect(paintDirtyRect);
-    } else
-        backgroundRect = paintDirtyRect;
-
-    foregroundRect = backgroundRect;
-    outlineRect = backgroundRect;
-
-    LayoutPoint offset;
-    if (offsetFromRoot)
-        offset = *offsetFromRoot;
-    else
-        convertToLayerCoords(clipRectsContext.rootLayer, offset);
-    layerBounds = LayoutRect(offset, size());
-
-    // Update the clip rects that will be passed to child layers.
-    if (renderer()->hasOverflowClip()) {
-        // This layer establishes a clip of some kind.
-        if (this != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip == RespectOverflowClip) {
-            foregroundRect.intersect(toRenderBox(renderer())->overflowClipRect(offset, clipRectsContext.region, clipRectsContext.overlayScrollbarSizeRelevancy));
-            if (renderer()->style()->hasBorderRadius())
-                foregroundRect.setHasRadius(true);
-        }
-
-        // If we establish an overflow clip at all, then go ahead and make sure our background
-        // rect is intersected with our layer's bounds including our visual overflow,
-        // since any visual overflow like box-shadow or border-outset is not clipped by overflow:auto/hidden.
-        if (renderBox()->hasVisualOverflow()) {
-            // FIXME: Perhaps we should be propagating the borderbox as the clip rect for children, even though
-            //        we may need to inflate our clip specifically for shadows or outsets.
-            // FIXME: Does not do the right thing with CSS regions yet, since we don't yet factor in the
-            // individual region boxes as overflow.
-            LayoutRect layerBoundsWithVisualOverflow = renderBox()->visualOverflowRect();
-            renderBox()->flipForWritingMode(layerBoundsWithVisualOverflow); // Layers are in physical coordinates, so the overflow has to be flipped.
-            layerBoundsWithVisualOverflow.moveBy(offset);
-            if (this != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip == RespectOverflowClip)
-                backgroundRect.intersect(layerBoundsWithVisualOverflow);
-        } else {
-            // Shift the bounds to be for our region only.
-            LayoutRect bounds = renderBox()->borderBoxRectInRegion(clipRectsContext.region);
-            bounds.moveBy(offset);
-            if (this != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip == RespectOverflowClip)
-                backgroundRect.intersect(bounds);
-        }
-    }
-
-    // CSS clip (different than clipping due to overflow) can clip to any box, even if it falls outside of the border box.
-    if (renderer()->hasClip()) {
-        // Clip applies to *us* as well, so go ahead and update the damageRect.
-        LayoutRect newPosClip = toRenderBox(renderer())->clipRect(offset, clipRectsContext.region);
-        backgroundRect.intersect(newPosClip);
-        foregroundRect.intersect(newPosClip);
-        outlineRect.intersect(newPosClip);
-    }
-}
-
-LayoutRect RenderLayer::childrenClipRect() const
-{
-    // FIXME: border-radius not accounted for.
-    // FIXME: Regions not accounted for.
-    RenderView* renderView = renderer()->view();
-    RenderLayer* clippingRootLayer = clippingRootForPainting();
-    LayoutRect layerBounds;
-    ClipRect backgroundRect, foregroundRect, outlineRect;
-    ClipRectsContext clipRectsContext(clippingRootLayer, 0, TemporaryClipRects);
-    // Need to use temporary clip rects, because the value of 'dontClipToOverflow' may be different from the painting path (<rdar://problem/11844909>).
-    calculateRects(clipRectsContext, renderView->unscaledDocumentRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
-    return clippingRootLayer->renderer()->localToAbsoluteQuad(FloatQuad(foregroundRect.rect())).enclosingBoundingBox();
-}
-
-LayoutRect RenderLayer::selfClipRect() const
-{
-    // FIXME: border-radius not accounted for.
-    // FIXME: Regions not accounted for.
-    RenderView* renderView = renderer()->view();
-    RenderLayer* clippingRootLayer = clippingRootForPainting();
-    LayoutRect layerBounds;
-    ClipRect backgroundRect, foregroundRect, outlineRect;
-    ClipRectsContext clipRectsContext(clippingRootLayer, 0, PaintingClipRects);
-    calculateRects(clipRectsContext, renderView->documentRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
-    return clippingRootLayer->renderer()->localToAbsoluteQuad(FloatQuad(backgroundRect.rect())).enclosingBoundingBox();
-}
-
-LayoutRect RenderLayer::localClipRect() const
-{
-    // FIXME: border-radius not accounted for.
-    // FIXME: Regions not accounted for.
-    RenderLayer* clippingRootLayer = clippingRootForPainting();
-    LayoutRect layerBounds;
-    ClipRect backgroundRect, foregroundRect, outlineRect;
-    ClipRectsContext clipRectsContext(clippingRootLayer, 0, PaintingClipRects);
-    calculateRects(clipRectsContext, PaintInfo::infiniteRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
-
-    LayoutRect clipRect = backgroundRect.rect();
-    if (clipRect == PaintInfo::infiniteRect())
-        return clipRect;
-
-    LayoutPoint clippingRootOffset;
-    convertToLayerCoords(clippingRootLayer, clippingRootOffset);
-    clipRect.moveBy(-clippingRootOffset);
-
-    return clipRect;
-}
-
 void RenderLayer::addBlockSelectionGapsBounds(const LayoutRect& bounds)
 {
     m_blockSelectionGapsBounds.unite(enclosingIntRect(bounds));
@@ -3391,10 +3214,10 @@
         RenderBox* box = renderBox();
         rect.move(-box->scrolledContentOffset());
         if (!scrollableArea()->usesCompositedScrolling())
-            rect.intersect(box->overflowClipRect(LayoutPoint(), 0)); // FIXME: Regions not accounted for.
+            rect.intersect(box->overflowClipRect(LayoutPoint()));
     }
     if (renderer()->hasClip())
-        rect.intersect(toRenderBox(renderer())->clipRect(LayoutPoint(), 0)); // FIXME: Regions not accounted for.
+        rect.intersect(toRenderBox(renderer())->clipRect(LayoutPoint()));
     if (!rect.isEmpty())
         renderer()->repaintRectangle(rect);
 }
@@ -3518,14 +3341,14 @@
     return pixelSnappedIntRect(boundingBox(root()));
 }
 
-IntRect RenderLayer::calculateLayerBounds(const RenderLayer* ancestorLayer, const LayoutPoint* offsetFromRoot, CalculateLayerBoundsFlags flags) const
+LayoutRect RenderLayer::calculateLayerBounds(const RenderLayer* ancestorLayer, const LayoutPoint* offsetFromRoot, CalculateLayerBoundsFlags flags) const
 {
     if (!isSelfPaintingLayer())
-        return IntRect();
+        return LayoutRect();
 
     // FIXME: This could be improved to do a check like hasVisibleNonCompositingDescendantLayers() (bug 92580).
     if ((flags & ExcludeHiddenDescendants) && this != ancestorLayer && !hasVisibleContent() && !hasVisibleDescendant())
-        return IntRect();
+        return LayoutRect();
 
     RenderLayerModelObject* renderer = this->renderer();
 
@@ -3555,10 +3378,11 @@
     }
 
     LayoutRect unionBounds = boundingBoxRect;
+
     bool shouldIncludeTransform = paintsWithTransform(PaintBehaviorNormal) || (transform() && flags & PretendLayerHasOwnBacking);
 
     if (flags & UseLocalClipRectIfPossible) {
-        LayoutRect localClipRect = this->localClipRect();
+        LayoutRect localClipRect = clipper().localClipRect();
         if (localClipRect != PaintInfo::infiniteRect()) {
             if ((flags & IncludeSelfTransform) && shouldIncludeTransform)
                 localClipRect = transform()->mapRect(localClipRect);
@@ -3566,7 +3390,7 @@
             LayoutPoint ancestorRelOffset;
             convertToLayerCoords(ancestorLayer, ancestorRelOffset);
             localClipRect.moveBy(ancestorRelOffset);
-            return pixelSnappedIntRect(localClipRect);
+            return localClipRect;
         }
     }
 
@@ -3578,7 +3402,7 @@
     if (m_reflectionInfo) {
         RenderLayer* reflectionLayer = m_reflectionInfo->reflectionLayer();
         if (!reflectionLayer->hasCompositedLayerMapping()) {
-            IntRect childUnionBounds = reflectionLayer->calculateLayerBounds(this, 0, descendantFlags);
+            LayoutRect childUnionBounds = reflectionLayer->calculateLayerBounds(this, 0, descendantFlags);
             unionBounds.unite(childUnionBounds);
         }
     }
@@ -3598,12 +3422,12 @@
         // prior to updating its bounds. The requires-own-backing-store-for-ancestor-reasons
         // could be stale. Refresh them now.
         if (node->layer()->hasCompositedLayerMapping()) {
-            RenderLayer* enclosingCompositingLayer = node->layer()->enclosingCompositingLayer(false);
+            RenderLayer* enclosingCompositingLayer = node->layer()->enclosingCompositingLayer(ExcludeSelf);
             node->layer()->compositedLayerMapping()->updateRequiresOwnBackingStoreForAncestorReasons(enclosingCompositingLayer);
         }
 
         if (flags & IncludeCompositedDescendants || !node->layer()->hasCompositedLayerMapping()) {
-            IntRect childUnionBounds = node->layer()->calculateLayerBounds(this, 0, descendantFlags);
+            LayoutRect childUnionBounds = node->layer()->calculateLayerBounds(this, 0, descendantFlags);
             unionBounds.unite(childUnionBounds);
         }
     }
@@ -3627,14 +3451,22 @@
         convertToLayerCoords(ancestorLayer, ancestorRelOffset);
     unionBounds.moveBy(ancestorRelOffset);
 
-    return pixelSnappedIntRect(unionBounds);
+    return unionBounds;
 }
 
 CompositingState RenderLayer::compositingState() const
 {
+    ASSERT(isAllowedToQueryCompositingState());
+
     // This is computed procedurally so there is no redundant state variable that
     // can get out of sync from the real actual compositing state.
 
+    if (m_groupedMapping) {
+        ASSERT(compositor()->layerSquashingEnabled());
+        ASSERT(!m_compositedLayerMapping);
+        return PaintsIntoGroupedBacking;
+    }
+
     if (!m_compositedLayerMapping)
         return NotComposited;
 
@@ -3645,24 +3477,28 @@
     return PaintsIntoOwnBacking;
 }
 
+bool RenderLayer::isAllowedToQueryCompositingState() const
+{
+    if (gCompositingQueryMode == CompositingQueriesAreAllowed)
+        return true;
+    return renderer()->document().lifecycle().state() >= DocumentLifecycle::InCompositingUpdate;
+}
+
 CompositedLayerMappingPtr RenderLayer::ensureCompositedLayerMapping()
 {
     if (!m_compositedLayerMapping) {
         m_compositedLayerMapping = adoptPtr(new CompositedLayerMapping(this));
-        compositor()->layerBecameComposited(this);
 
         updateOrRemoveFilterEffectRenderer();
 
         if (RuntimeEnabledFeatures::cssCompositingEnabled())
-            compositedLayerMapping()->setBlendMode(m_blendMode);
+            compositedLayerMapping()->setBlendMode(m_blendInfo.blendMode());
     }
     return m_compositedLayerMapping.get();
 }
 
 void RenderLayer::clearCompositedLayerMapping(bool layerBeingDestroyed)
 {
-    if (m_compositedLayerMapping && !renderer()->documentBeingDestroyed())
-        compositor()->layerBecameNonComposited(this);
     m_compositedLayerMapping.clear();
 
     if (!layerBeingDestroyed)
@@ -3679,11 +3515,27 @@
     return m_compositedLayerMapping && m_compositedLayerMapping->hasChildClippingMaskLayer();
 }
 
+bool RenderLayer::clipsCompositingDescendantsWithBorderRadius() const
+{
+    RenderStyle* style = renderer()->style();
+    if (!style)
+        return false;
+
+    return compositor()->clipsCompositingDescendants(this) && style->hasBorderRadius();
+}
+
 bool RenderLayer::paintsWithTransform(PaintBehavior paintBehavior) const
 {
     return transform() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || compositingState() != PaintsIntoOwnBacking);
 }
 
+bool RenderLayer::paintsWithBlendMode() const
+{
+    // https://code.google.com/p/chromium/issues/detail?id=343759
+    DisableCompositingQueryAsserts disabler;
+    return m_blendInfo.hasBlendMode() && compositingState() != PaintsIntoOwnBacking;
+}
+
 bool RenderLayer::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
 {
     if (!isSelfPaintingLayer() && !hasSelfPaintingLayerDescendant())
@@ -3761,16 +3613,9 @@
 
 bool RenderLayer::shouldBeSelfPaintingLayer() const
 {
-    return !m_stackingNode->isNormalFlowOnly()
+    return !m_isOverflowOnlyLayer
         || (m_scrollableArea && m_scrollableArea->hasOverlayScrollbars())
-        || needsCompositedScrolling()
-        || renderer()->hasReflection()
-        || renderer()->hasMask()
-        || renderer()->isTableRow()
-        || renderer()->isCanvas()
-        || renderer()->isVideo()
-        || renderer()->isEmbeddedObject()
-        || renderer()->isRenderIFrame();
+        || needsCompositedScrolling();
 }
 
 void RenderLayer::updateSelfPaintingLayer()
@@ -3841,16 +3686,9 @@
     return false;
 }
 
-void RenderLayer::updateVisibilityAfterStyleChange(const RenderStyle* oldStyle)
-{
-    if (!oldStyle || (oldStyle->visibility() != renderer()->style()->visibility()))
-        compositor()->setNeedsUpdateCompositingRequirementsState();
-}
-
 void RenderLayer::updateOutOfFlowPositioned(const RenderStyle* oldStyle)
 {
-    if (oldStyle && (renderer()->style()->position() == oldStyle->position()))
-        return;
+    ASSERT(!oldStyle || renderer()->style()->position() != oldStyle->position());
 
     bool wasOutOfFlowPositioned = oldStyle && (oldStyle->position() == AbsolutePosition || oldStyle->position() == FixedPosition);
     bool isOutOfFlowPositioned = renderer()->isOutOfFlowPositioned();
@@ -3901,7 +3739,11 @@
 inline bool RenderLayer::needsCompositingLayersRebuiltForOverflow(const RenderStyle* oldStyle, const RenderStyle* newStyle) const
 {
     ASSERT(newStyle);
-    return !hasCompositedLayerMapping() && oldStyle && (oldStyle->overflowX() != newStyle->overflowX()) && m_stackingNode->ancestorStackingContainerNode()->layer()->hasCompositingDescendant();
+    return !hasCompositedLayerMapping()
+        && oldStyle
+        && (oldStyle->overflowX() != newStyle->overflowX())
+        && m_stackingNode->ancestorStackingContainerNode()
+        && m_stackingNode->ancestorStackingContainerNode()->layer()->hasCompositingDescendant();
 }
 
 inline bool RenderLayer::needsCompositingLayersRebuiltForFilters(const RenderStyle* oldStyle, const RenderStyle* newStyle, bool didPaintWithFilters) const
@@ -3909,9 +3751,7 @@
     if (!hasOrHadFilters(oldStyle, newStyle))
         return false;
 
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
-        ? hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitFilter)
-        : renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter)) {
+    if (hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitFilter)) {
 
         // When the compositor is performing the filter animation, we shouldn't touch the compositing layers.
         // All of the layers above us should have been promoted to compositing layers already.
@@ -3957,49 +3797,70 @@
     updateOrRemoveFilterClients();
     // During an accelerated animation, both WebKit and the compositor animate properties.
     // However, WebKit shouldn't ask the compositor to update its filters if the compositor is performing the animation.
-    if (hasCompositedLayerMapping() && (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
-        ? !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitFilter)
-        : !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter)))
+    if (hasCompositedLayerMapping() && !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitFilter))
         compositedLayerMapping()->updateFilters(renderer()->style());
     updateOrRemoveFilterEffectRenderer();
 }
 
-void RenderLayer::styleChanged(StyleDifference, const RenderStyle* oldStyle)
+void RenderLayer::styleChanged(StyleDifference diff, const RenderStyle* oldStyle)
 {
     m_stackingNode->updateIsNormalFlowOnly();
 
     if (m_scrollableArea)
         m_scrollableArea->updateAfterStyleChange(oldStyle);
     m_stackingNode->updateStackingNodesAfterStyleChange(oldStyle);
-    updateVisibilityAfterStyleChange(oldStyle);
+
+    if (!oldStyle || oldStyle->visibility() != renderer()->style()->visibility()) {
+        ASSERT(!oldStyle || diff >= StyleDifferenceRepaint);
+        compositor()->setNeedsUpdateCompositingRequirementsState();
+    }
+
     // Overlay scrollbars can make this layer self-painting so we need
     // to recompute the bit once scrollbars have been updated.
     updateSelfPaintingLayer();
-    updateOutOfFlowPositioned(oldStyle);
 
-    updateReflectionInfo(oldStyle);
+    if (!oldStyle || renderer()->style()->position() != oldStyle->position()) {
+        ASSERT(!oldStyle || diff >= StyleDifferenceLayout);
+        updateOutOfFlowPositioned(oldStyle);
+    }
+
+    if (!oldStyle || !renderer()->style()->reflectionDataEquivalent(oldStyle)) {
+        ASSERT(!oldStyle || diff >= StyleDifferenceLayout);
+        updateReflectionInfo(oldStyle);
+    }
 
     if (RuntimeEnabledFeatures::cssCompositingEnabled())
-        updateBlendMode();
+        m_blendInfo.updateBlendMode();
 
     updateDescendantDependentFlags();
-    updateTransform();
+
+    if (!oldStyle || !renderer()->style()->transformDataEquivalent(oldStyle))
+        updateTransform();
 
     bool didPaintWithFilters = false;
 
-    if (paintsWithFilters())
-        didPaintWithFilters = true;
-    updateFilters(oldStyle, renderer()->style());
+    {
+        // https://code.google.com/p/chromium/issues/detail?id=343759
+        DisableCompositingQueryAsserts disabler;
+        if (paintsWithFilters())
+            didPaintWithFilters = true;
+        updateFilters(oldStyle, renderer()->style());
+    }
+
+    // FIXME: Remove incremental compositing updates after fixing the chicken/egg issues
+    // https://code.google.com/p/chromium/issues/detail?id=343756
+    DisableCompositingQueryAsserts disabler;
 
     const RenderStyle* newStyle = renderer()->style();
-    if (compositor()->updateLayerCompositingState(this)
-        || needsCompositingLayersRebuiltForClip(oldStyle, newStyle)
+
+    compositor()->updateLayerCompositingState(this);
+    // FIXME: this compositing logic should be pushed into the compositing code, not here.
+    if (needsCompositingLayersRebuiltForClip(oldStyle, newStyle)
         || needsCompositingLayersRebuiltForOverflow(oldStyle, newStyle)
         || needsCompositingLayersRebuiltForFilters(oldStyle, newStyle, didPaintWithFilters)
-        || needsCompositingLayersRebuiltForBlending(oldStyle, newStyle))
+        || needsCompositingLayersRebuiltForBlending(oldStyle, newStyle)) {
         compositor()->setCompositingLayersNeedRebuild();
-    else if (hasCompositedLayerMapping())
-        compositedLayerMapping()->updateGraphicsLayerGeometry();
+    }
 }
 
 bool RenderLayer::scrollsOverflow() const
@@ -4010,13 +3871,6 @@
     return false;
 }
 
-bool RenderLayer::isCSSCustomFilterEnabled() const
-{
-    // We only want to enable shaders if WebGL is also enabled on this platform.
-    const Settings* settings = renderer()->document().settings();
-    return settings && RuntimeEnabledFeatures::cssCustomFilterEnabled() && settings->webGLEnabled();
-}
-
 FilterOperations RenderLayer::computeFilterOperations(const RenderStyle* style)
 {
     const FilterOperations& filters = style->filter();
@@ -4029,47 +3883,14 @@
             // FIXME: Cache the ReferenceFilter if it didn't change.
             RefPtr<ReferenceFilter> referenceFilter = ReferenceFilter::create();
             float zoom = style->effectiveZoom() * WebCore::deviceScaleFactor(renderer()->frame());
-            referenceFilter->setFilterResolution(FloatSize(zoom, zoom));
+            referenceFilter->setAbsoluteTransform(AffineTransform().scale(zoom, zoom));
             referenceFilter->setLastEffect(ReferenceFilterBuilder::build(referenceFilter.get(), renderer(), referenceFilter->sourceGraphic(),
                 referenceOperation));
             referenceOperation->setFilter(referenceFilter.release());
         }
     }
 
-    if (!filters.hasCustomFilter())
-        return filters;
-
-    if (!isCSSCustomFilterEnabled()) {
-        // CSS Custom filters should not parse at all in this case, but there might be
-        // remaining styles that were parsed when the flag was enabled. Reproduces in DumpRenderTree
-        // because it resets the flag while the previous test is still loaded.
-        return FilterOperations();
-    }
-
-    FilterOperations outputFilters;
-    for (size_t i = 0; i < filters.size(); ++i) {
-        RefPtr<FilterOperation> filterOperation = filters.operations().at(i);
-        if (filterOperation->type() == FilterOperation::CUSTOM) {
-            // We have to wait until the program of CSS Shaders is loaded before setting it on the layer.
-            // Note that we will handle the loading of the shaders and repainting of the layer in updateOrRemoveFilterClients.
-            const CustomFilterOperation* customOperation = toCustomFilterOperation(filterOperation.get());
-            RefPtr<CustomFilterProgram> program = customOperation->program();
-            if (!program->isLoaded())
-                continue;
-
-            CustomFilterGlobalContext* globalContext = renderer()->view()->customFilterGlobalContext();
-            RefPtr<CustomFilterValidatedProgram> validatedProgram = globalContext->getValidatedProgram(program->programInfo());
-            if (!validatedProgram->isInitialized())
-                continue;
-
-            RefPtr<ValidatedCustomFilterOperation> validatedOperation = ValidatedCustomFilterOperation::create(validatedProgram.release(),
-                customOperation->parameters(), customOperation->meshRows(), customOperation->meshColumns(), customOperation->meshType());
-            outputFilters.operations().append(validatedOperation.release());
-            continue;
-        }
-        outputFilters.operations().append(filterOperation.release());
-    }
-    return outputFilters;
+    return filters;
 }
 
 void RenderLayer::updateOrRemoveFilterClients()
@@ -4079,11 +3900,6 @@
         return;
     }
 
-    if (renderer()->style()->filter().hasCustomFilter())
-        ensureFilterInfo()->updateCustomFilterClients(renderer()->style()->filter());
-    else if (hasFilterInfo())
-        filterInfo()->removeCustomFilterClients();
-
     if (renderer()->style()->filter().hasReferenceFilter())
         ensureFilterInfo()->updateReferenceFilterClients(renderer()->style()->filter());
     else if (hasFilterInfo())
@@ -4122,38 +3938,64 @@
 
 void RenderLayer::filterNeedsRepaint()
 {
-    toElement(renderer()->node())->scheduleLayerUpdate();
-    if (renderer()->view())
-        renderer()->repaint();
+    {
+        DeprecatedScheduleStyleRecalcDuringLayout marker(renderer()->document().lifecycle());
+        // It's possible for scheduleLayerUpdate to schedule a style recalc, which
+        // is a problem because this function can be called while performing layout.
+        // Presumably this represents an illegal data flow of layout or compositing
+        // information into the style system.
+        toElement(renderer()->node())->scheduleLayerUpdate();
+    }
+
+    if (renderer()->view()) {
+        if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && renderer()->frameView()->isInPerformLayout())
+            renderer()->setShouldDoFullRepaintAfterLayout(true);
+        else
+            renderer()->repaint();
+    }
 }
 
 void RenderLayer::addLayerHitTestRects(LayerHitTestRects& rects) const
 {
+    computeSelfHitTestRects(rects);
+    for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
+        child->addLayerHitTestRects(rects);
+}
+
+void RenderLayer::computeSelfHitTestRects(LayerHitTestRects& rects) const
+{
     if (!size().isEmpty()) {
         Vector<LayoutRect> rect;
 
         if (renderBox() && renderBox()->scrollsOverflow()) {
             // For scrolling layers, rects are taken to be in the space of the contents.
-            // We need to include both the entire contents, and also the bounding box
-            // of the layer in the space of it's parent (eg. for border / scroll bars).
-            rect.append(m_scrollableArea->overflowRect());
+            // We need to include the bounding box of the layer in the space of its parent
+            // (eg. for border / scroll bars) and if it's composited then the entire contents
+            // as well as they may be on another composited layer. Skip reporting contents
+            // for non-composited layers as they'll get projected to the same layer as the
+            // bounding box.
+            if (compositingState() != NotComposited)
+                rect.append(m_scrollableArea->overflowRect());
+
             rects.set(this, rect);
             if (const RenderLayer* parentLayer = parent()) {
                 LayerHitTestRects::iterator iter = rects.find(parentLayer);
-                if (iter == rects.end())
-                    iter = rects.add(parentLayer, Vector<LayoutRect>()).iterator;
-                iter->value.append(boundingBox(parentLayer));
+                if (iter == rects.end()) {
+                    rects.add(parentLayer, Vector<LayoutRect>()).storedValue->value.append(boundingBox(parentLayer));
+                } else {
+                    iter->value.append(boundingBox(parentLayer));
+                }
             }
         } else {
             rect.append(localBoundingBox());
             rects.set(this, rect);
         }
     }
-
-    for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
-        child->addLayerHitTestRects(rects);
 }
 
+DisableCompositingQueryAsserts::DisableCompositingQueryAsserts()
+    : m_disabler(gCompositingQueryMode, CompositingQueriesAreAllowed) { }
+
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/RenderLayer.h b/Source/core/rendering/RenderLayer.h
index 1066428..4d9d0ee 100644
--- a/Source/core/rendering/RenderLayer.h
+++ b/Source/core/rendering/RenderLayer.h
@@ -46,10 +46,9 @@
 #define RenderLayer_h
 
 #include "core/rendering/CompositedLayerMappingPtr.h"
-#include "core/rendering/CompositingReasons.h"
 #include "core/rendering/LayerPaintingInfo.h"
-#include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBox.h"
+#include "core/rendering/RenderLayerBlendInfo.h"
 #include "core/rendering/RenderLayerClipper.h"
 #include "core/rendering/RenderLayerFilterInfo.h"
 #include "core/rendering/RenderLayerReflectionInfo.h"
@@ -57,6 +56,7 @@
 #include "core/rendering/RenderLayerScrollableArea.h"
 #include "core/rendering/RenderLayerStackingNode.h"
 #include "core/rendering/RenderLayerStackingNodeIterator.h"
+#include "platform/graphics/CompositingReasons.h"
 #include "wtf/OwnPtr.h"
 
 namespace WebCore {
@@ -66,19 +66,37 @@
 class HitTestRequest;
 class HitTestResult;
 class HitTestingTransformState;
-class PlatformEvent;
 class RenderFlowThread;
 class RenderGeometryMap;
 class CompositedLayerMapping;
 class RenderLayerCompositor;
 class RenderReplica;
-class RenderScrollbarPart;
 class RenderStyle;
-class RenderView;
-class Scrollbar;
 class TransformationMatrix;
 
 enum BorderRadiusClippingRule { IncludeSelfForBorderRadius, DoNotIncludeSelfForBorderRadius };
+enum IncludeSelfOrNot { IncludeSelf, ExcludeSelf };
+
+enum CompositedScrollingHistogramBuckets {
+    IsScrollableAreaBucket = 0,
+    NeedsToBeStackingContainerBucket = 1,
+    WillUseCompositedScrollingBucket = 2,
+    CompositedScrollingHistogramMax = 3
+};
+
+enum CompositingQueryMode {
+    CompositingQueriesAreAllowed,
+    CompositingQueriesAreOnlyAllowedInCertainDocumentLifecyclePhases
+};
+
+// FIXME: remove this once the compositing query ASSERTS are no longer hit.
+class DisableCompositingQueryAsserts {
+    WTF_MAKE_NONCOPYABLE(DisableCompositingQueryAsserts);
+public:
+    DisableCompositingQueryAsserts();
+private:
+    TemporaryChange<CompositingQueryMode> m_disabler;
+};
 
 class RenderLayer {
 public:
@@ -88,7 +106,7 @@
     // FIXME: Needed until we move all the necessary bits to the new class.
     friend class RenderLayerScrollableArea;
 
-    RenderLayer(RenderLayerModelObject*);
+    RenderLayer(RenderLayerModelObject*, LayerType);
     ~RenderLayer();
 
     String debugName() const;
@@ -101,6 +119,8 @@
     RenderLayer* firstChild() const { return m_first; }
     RenderLayer* lastChild() const { return m_last; }
 
+    const RenderLayer* compositingContainer() const;
+
     void addChild(RenderLayer* newChild, RenderLayer* beforeChild = 0);
     RenderLayer* removeChild(RenderLayer*);
 
@@ -111,6 +131,9 @@
 
     bool isSelfPaintingLayer() const { return m_isSelfPaintingLayer; }
 
+    bool isOverflowOnlyLayer() const { return m_isOverflowOnlyLayer; }
+    void setIsOverflowOnlyLayer(bool isOverflowOnlyLayer) { m_isOverflowOnlyLayer = isOverflowOnlyLayer; }
+
     bool cannotBlitToWindow() const;
 
     bool isTransparent() const;
@@ -166,8 +189,8 @@
     RenderLayer* enclosingPaginationLayer() const { return m_enclosingPaginationLayer; }
 
     void updateTransform();
-
-    void updateBlendMode();
+    void update3dRenderingContext();
+    RenderLayer* renderingContextRoot() const { return m_3dRenderingContextRoot; }
 
     const LayoutSize& offsetForInFlowPosition() const { return m_offsetForInFlowPosition; }
 
@@ -206,8 +229,6 @@
     void setHasOutOfFlowPositionedDescendant(bool hasDescendant) { m_hasOutOfFlowPositionedDescendant = hasDescendant; }
     void setHasOutOfFlowPositionedDescendantDirty(bool dirty) { m_hasOutOfFlowPositionedDescendantDirty = dirty; }
 
-    bool childLayerHasBlendMode() const { ASSERT(!m_childLayerHasBlendModeStatusDirty); return m_childLayerHasBlendMode; }
-
     bool hasUnclippedDescendant() const { return m_hasUnclippedDescendant; }
     void setHasUnclippedDescendant(bool hasDescendant) { m_hasUnclippedDescendant = hasDescendant; }
     void updateHasUnclippedDescendant();
@@ -220,17 +241,13 @@
     // the <html> layer and the root layer).
     RenderLayer* enclosingPositionedAncestor() const;
 
-    // Returns the nearest enclosing layer that is scrollable.
-    RenderLayer* enclosingScrollableLayer() const;
-
-    // The layer relative to which clipping rects for this layer are computed.
-    RenderLayer* clippingRootForPainting() const;
+    RenderLayer* enclosingOverflowClipLayer(IncludeSelfOrNot = IncludeSelf) const;
 
     // Enclosing compositing layer; if includeSelf is true, may return this.
-    RenderLayer* enclosingCompositingLayer(bool includeSelf = true) const;
-    RenderLayer* enclosingCompositingLayerForRepaint(bool includeSelf = true) const;
+    RenderLayer* enclosingCompositingLayer(IncludeSelfOrNot = IncludeSelf) const;
+    RenderLayer* enclosingCompositingLayerForRepaint(IncludeSelfOrNot = IncludeSelf) const;
     // Ancestor compositing layer, excluding this.
-    RenderLayer* ancestorCompositingLayer() const { return enclosingCompositingLayer(false); }
+    RenderLayer* ancestorCompositingLayer() const { return enclosingCompositingLayer(ExcludeSelf); }
 
     // Ancestor composited scrolling layer at or above our containing block.
     RenderLayer* ancestorCompositedScrollingLayer() const;
@@ -238,7 +255,7 @@
     // Ancestor scrolling layer at or above our containing block.
     RenderLayer* ancestorScrollingLayer() const;
 
-    RenderLayer* enclosingFilterLayer(bool includeSelf = true) const;
+    RenderLayer* enclosingFilterLayer(IncludeSelfOrNot = IncludeSelf) const;
     RenderLayer* enclosingFilterRepaintLayer() const;
     bool hasAncestorWithFilterOutsets() const;
 
@@ -257,23 +274,11 @@
     // paints the layers that intersect the damage rect from back to
     // front.  The hitTest method looks for mouse events by walking
     // layers that intersect the point from front to back.
-    void paint(GraphicsContext*, const LayoutRect& damageRect, PaintBehavior = PaintBehaviorNormal, RenderObject* paintingRoot = 0,
-        RenderRegion* = 0, PaintLayerFlags = 0);
+    void paint(GraphicsContext*, const LayoutRect& damageRect, PaintBehavior = PaintBehaviorNormal, RenderObject* paintingRoot = 0, PaintLayerFlags = 0);
     bool hitTest(const HitTestRequest&, HitTestResult&);
     bool hitTest(const HitTestRequest&, const HitTestLocation&, HitTestResult&);
     void paintOverlayScrollbars(GraphicsContext*, const LayoutRect& damageRect, PaintBehavior, RenderObject* paintingRoot = 0);
 
-    // This method figures out our layerBounds in coordinates relative to
-    // |rootLayer}.  It also computes our background and foreground clip rects
-    // for painting/event handling.
-    // Pass offsetFromRoot if known.
-    void calculateRects(const ClipRectsContext&, const LayoutRect& paintDirtyRect, LayoutRect& layerBounds,
-        ClipRect& backgroundRect, ClipRect& foregroundRect, ClipRect& outlineRect, const LayoutPoint* offsetFromRoot = 0) const;
-
-    LayoutRect childrenClipRect() const; // Returns the foreground clip rect of the layer in the document's coordinate space.
-    LayoutRect selfClipRect() const; // Returns the background clip rect of the layer in the document's coordinate space.
-    LayoutRect localClipRect() const; // Returns the background clip rect of the layer in the local coordinate space.
-
     // Pass offsetFromRoot if known.
     bool intersectsDamageRect(const LayoutRect& layerBounds, const LayoutRect& damageRect, const RenderLayer* rootLayer, const LayoutPoint* offsetFromRoot = 0) const;
 
@@ -305,7 +310,7 @@
     bool overlapBoundsIncludeChildren() const { return hasFilter() && renderer()->style()->filter().hasFilterThatMovesPixels(); }
 
     // Can pass offsetFromRoot if known.
-    IntRect calculateLayerBounds(const RenderLayer* ancestorLayer, const LayoutPoint* offsetFromRoot = 0, CalculateLayerBoundsFlags = DefaultCalculateLayerBoundsFlags) const;
+    LayoutRect calculateLayerBounds(const RenderLayer* ancestorLayer, const LayoutPoint* offsetFromRoot = 0, CalculateLayerBoundsFlags = DefaultCalculateLayerBoundsFlags) const;
 
     // WARNING: This method returns the offset for the parent as this is what updateLayerPositions expects.
     LayoutPoint computeOffsetFromRoot(bool& hasLayerOffset) const;
@@ -333,11 +338,13 @@
     bool preserves3D() const { return renderer()->style()->transformStyle3D() == TransformStyle3DPreserve3D; }
     bool has3DTransform() const { return m_transform && !m_transform->isAffine(); }
 
+    // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
+    bool shouldFlattenTransform() const { return renderer()->hasReflection() || !renderer()->style() || renderer()->style()->transformStyle3D() != TransformStyle3DPreserve3D; }
+
     void filterNeedsRepaint();
     bool hasFilter() const { return renderer()->hasFilter(); }
 
-    bool hasBlendMode() const;
-    bool paintsWithBlendMode() const { return hasBlendMode() && compositingState() != PaintsIntoOwnBacking; }
+    bool paintsWithBlendMode() const;
 
     void* operator new(size_t);
     // Only safe to call from RenderLayerModelObject::destroyLayer()
@@ -345,6 +352,10 @@
 
     CompositingState compositingState() const;
 
+    // This returns true if our document is in a phase of its lifestyle during which
+    // compositing state may legally be read.
+    bool isAllowedToQueryCompositingState() const;
+
     CompositedLayerMappingPtr compositedLayerMapping() const { return m_compositedLayerMapping.get(); }
     CompositedLayerMappingPtr ensureCompositedLayerMapping();
 
@@ -354,10 +365,15 @@
     bool hasCompositedLayerMapping() const { return m_compositedLayerMapping.get(); }
     void clearCompositedLayerMapping(bool layerBeingDestroyed = false);
 
+    CompositedLayerMapping* groupedMapping() const { return m_groupedMapping; }
+    void setGroupedMapping(CompositedLayerMapping* groupedMapping) { m_groupedMapping = groupedMapping; }
+
     bool hasCompositedMask() const;
     bool hasCompositedClippingMask() const;
     bool needsCompositedScrolling() const { return m_scrollableArea && m_scrollableArea->needsCompositedScrolling(); }
 
+    bool clipsCompositingDescendantsWithBorderRadius() const;
+
     RenderLayer* scrollParent() const;
     RenderLayer* clipParent() const;
 
@@ -380,8 +396,6 @@
     bool containsDirtyOverlayScrollbars() const { return m_containsDirtyOverlayScrollbars; }
     void setContainsDirtyOverlayScrollbars(bool dirtyScrollbars) { m_containsDirtyOverlayScrollbars = dirtyScrollbars; }
 
-    bool isCSSCustomFilterEnabled() const;
-
     FilterOperations computeFilterOperations(const RenderStyle*);
     bool paintsWithFilters() const;
     bool requiresFullLayerImageForFilters() const;
@@ -426,10 +440,14 @@
 
     void addLayerHitTestRects(LayerHitTestRects&) const;
 
+    // Compute rects only for this layer
+    void computeSelfHitTestRects(LayerHitTestRects&) const;
+
     // FIXME: This should probably return a ScrollableArea but a lot of internal methods are mistakenly exposed.
     RenderLayerScrollableArea* scrollableArea() const { return m_scrollableArea.get(); }
     RenderLayerRepainter& repainter() { return m_repainter; }
     RenderLayerClipper& clipper() { return m_clipper; }
+    const RenderLayerClipper& clipper() const { return m_clipper; }
 
     inline bool isPositionedContainer() const
     {
@@ -444,6 +462,15 @@
 
     PassOwnPtr<Vector<FloatRect> > collectTrackedRepaintRects() const;
 
+    RenderLayerBlendInfo& blendInfo() { return m_blendInfo; }
+
+    void setOffsetFromSquashingLayerOrigin(IntSize offset) { m_compositingProperties.offsetFromSquashingLayerOrigin = offset; }
+    IntSize offsetFromSquashingLayerOrigin() const { return m_compositingProperties.offsetFromSquashingLayerOrigin; }
+
+    bool scrollsOverflow() const;
+
+    bool hasDirectReasonsForCompositing() const { return compositingReasons() & CompositingReasonComboAllDirectReasons; }
+
 private:
     bool hasOverflowControls() const;
 
@@ -455,17 +482,11 @@
     void setAncestorChainHasOutOfFlowPositionedDescendant();
     void dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
 
-    bool acceleratedCompositingForOverflowScrollEnabled() const;
-    // FIXME: This is a temporary flag and should be removed once accelerated
-    // overflow scroll is ready (crbug.com/254111).
-    bool compositorDrivenAcceleratedScrollingEnabled() const;
-
     void clipToRect(RenderLayer* rootLayer, GraphicsContext*, const LayoutRect& paintDirtyRect, const ClipRect&,
                     BorderRadiusClippingRule = IncludeSelfForBorderRadius);
     void restoreClip(GraphicsContext*, const LayoutRect& paintDirtyRect, const ClipRect&);
 
     void updateSelfPaintingLayer();
-    void updateVisibilityAfterStyleChange(const RenderStyle* oldStyle);
 
     void updateOutOfFlowPositioned(const RenderStyle* oldStyle);
 
@@ -501,9 +522,10 @@
     void paintPaginatedChildLayer(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
     void paintChildLayerIntoColumns(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags, const Vector<RenderLayer*>& columnLayers, size_t columnIndex);
 
-    void collectFragments(LayerFragments&, const RenderLayer* rootLayer, RenderRegion*, const LayoutRect& dirtyRect,
+    void collectFragments(LayerFragments&, const RenderLayer* rootLayer, const LayoutRect& dirtyRect,
         ClipRectsType, OverlayScrollbarSizeRelevancy inOverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize,
-        ShouldRespectOverflowClip = RespectOverflowClip, const LayoutPoint* offsetFromRoot = 0, const LayoutRect* layerBoundingBox = 0);
+        ShouldRespectOverflowClip = RespectOverflowClip, const LayoutPoint* offsetFromRoot = 0,
+        const LayoutSize& subPixelAccumulation = LayoutSize(), const LayoutRect* layerBoundingBox = 0);
     void updatePaintingInfoForFragments(LayerFragments&, const LayerPaintingInfo&, PaintLayerFlags, bool shouldPaintContent, const LayoutPoint* offsetFromRoot);
     void paintBackgroundForFragments(const LayerFragments&, GraphicsContext*, GraphicsContext* transparencyLayerContext,
         const LayoutRect& transparencyPaintDirtyRect, bool haveTransparency, const LayerPaintingInfo&, PaintBehavior, RenderObject* paintingRootForRenderer);
@@ -561,22 +583,11 @@
     bool requiresScrollableArea() const { return renderBox(); }
     void updateScrollableArea();
 
-    // Returns true our scrollable area is in the FrameView's collection of scrollable areas. This can
-    // only happen if we're both scrollable, and we do in fact overflow.
-    bool scrollsOverflow() const;
-
     void dirtyAncestorChainVisibleDescendantStatus();
     void setAncestorChainHasVisibleDescendant();
 
-    void dirtyAncestorChainBlendedDescendantStatus();
-    void setAncestorChainBlendedDescendant();
-
     void updateDescendantDependentFlags();
 
-    // This flag is computed by RenderLayerCompositor, which knows more about 3d hierarchies than we do.
-    void setHas3DTransformedDescendant(bool b) { m_has3DTransformedDescendant = b; }
-    bool has3DTransformedDescendant() const { return m_has3DTransformedDescendant; }
-
     void dirty3DTransformedDescendantStatus();
     // Both updates the status, and returns true if descendants of this have 3d.
     bool update3DTransformedDescendantStatus();
@@ -584,9 +595,6 @@
     void updateOrRemoveFilterClients();
     void updateOrRemoveFilterEffectRenderer();
 
-    void parentClipRects(const ClipRectsContext&, ClipRects&) const;
-    ClipRect backgroundClipRect(const ClipRectsContext&) const;
-
     LayoutRect paintingExtent(const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior);
 
     RenderLayer* enclosingTransformedAncestor() const;
@@ -605,6 +613,9 @@
     bool shouldIsolateCompositedDescendants() const { return m_compositingProperties.shouldIsolateCompositedDescendants; }
     void setShouldIsolateCompositedDescendants(bool b)  { m_compositingProperties.shouldIsolateCompositedDescendants = b; }
 
+    bool lostGroupedMapping() const { return m_compositingProperties.lostGroupedMapping; }
+    void setLostGroupedMapping(bool b) { m_compositingProperties.lostGroupedMapping = b; }
+
     void setCompositingReasons(CompositingReasons reasons) { m_compositingProperties.compositingReasons = reasons; }
     CompositingReasons compositingReasons() const { return m_compositingProperties.compositingReasons; }
 
@@ -613,7 +624,11 @@
     friend class RenderLayerModelObject;
 
 protected:
+    // Self-painting layer is an optimization where we avoid the heavy RenderLayer painting
+    // machinery for a RenderLayer allocated only to handle the overflow clip case.
+    // FIXME(crbug.com/332791): Self-painting layer should be merged into the overflow-only concept.
     unsigned m_isSelfPaintingLayer : 1;
+    unsigned m_isOverflowOnlyLayer : 1;
 
     // If have no self-painting descendants, we don't have to walk our children during painting. This can lead to
     // significant savings, especially if the tree has lots of non-self-painting layers grouped together (e.g. table cells).
@@ -637,9 +652,6 @@
                                  // we ended up painting this layer or any descendants (and therefore need to
                                  // blend).
 
-    unsigned m_childLayerHasBlendMode : 1;
-    unsigned m_childLayerHasBlendModeStatusDirty : 1;
-
     unsigned m_visibleContentStatusDirty : 1;
     unsigned m_hasVisibleContent : 1;
     unsigned m_visibleDescendantStatusDirty : 1;
@@ -663,8 +675,6 @@
 
     unsigned m_hasFilterInfo : 1;
 
-    blink::WebBlendMode m_blendMode;
-
     RenderLayerModelObject* m_renderer;
 
     RenderLayer* m_parent;
@@ -691,6 +701,10 @@
     // Pointer to the enclosing RenderLayer that caused us to be paginated. It is 0 if we are not paginated.
     RenderLayer* m_enclosingPaginationLayer;
 
+    // Pointer to the enclosing RenderLayer that establishes the 3d rendering context in which this layer participates.
+    // If it 0, it does not participate in a 3d rendering context.
+    RenderLayer* m_3dRenderingContextRoot;
+
     // Properties that are computed while updating compositing layers. These values may be dirty/invalid if
     // compositing status is not up-to-date before using them.
     struct CompositingProperties {
@@ -698,6 +712,7 @@
             : hasCompositingDescendant(false)
             , hasNonCompositedChild(false)
             , shouldIsolateCompositedDescendants(false)
+            , lostGroupedMapping(false)
             , viewportConstrainedNotCompositedReason(NoNotCompositedReason)
             , compositingReasons(CompositingReasonNone)
         { }
@@ -712,32 +727,35 @@
         // Should be for stacking contexts having unisolated blending descendants.
         bool shouldIsolateCompositedDescendants : 1;
 
+        // True if this render layer just lost its grouped mapping due to the CompositedLayerMapping being destroyed,
+        // and we don't yet know to what graphics layer this RenderLayer will be assigned.
+        bool lostGroupedMapping : 1;
+
         // The reason, if any exists, that a fixed-position layer is chosen not to be composited.
         unsigned viewportConstrainedNotCompositedReason : 2;
 
         // Once computed, indicates all that a layer needs to become composited using the CompositingReasons enum bitfield.
         CompositingReasons compositingReasons;
+
+        // Used for invalidating this layer's contents on the squashing GraphicsLayer.
+        IntSize offsetFromSquashingLayerOrigin;
     };
 
     CompositingProperties m_compositingProperties;
 
 private:
-    enum CompositedScrollingHistogramBuckets {
-        IsScrollableAreaBucket = 0,
-        NeedsToBeStackingContainerBucket = 1,
-        WillUseCompositedScrollingBucket = 2,
-        CompositedScrollingHistogramMax = 3
-    };
-
     IntRect m_blockSelectionGapsBounds;
 
     OwnPtr<CompositedLayerMapping> m_compositedLayerMapping;
     OwnPtr<RenderLayerScrollableArea> m_scrollableArea;
 
+    CompositedLayerMapping* m_groupedMapping;
+
     RenderLayerRepainter m_repainter;
     RenderLayerClipper m_clipper; // FIXME: Lazily allocate?
     OwnPtr<RenderLayerStackingNode> m_stackingNode;
     OwnPtr<RenderLayerReflectionInfo> m_reflectionInfo;
+    RenderLayerBlendInfo m_blendInfo;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderLayerBlendInfo.cpp b/Source/core/rendering/RenderLayerBlendInfo.cpp
new file mode 100644
index 0000000..aeebc4e
--- /dev/null
+++ b/Source/core/rendering/RenderLayerBlendInfo.cpp
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ *   Robert O'Callahan <roc+@cs.cmu.edu>
+ *   David Baron <dbaron@fas.harvard.edu>
+ *   Christian Biesinger <cbiesinger@web.de>
+ *   Randall Jesup <rjesup@wgate.com>
+ *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ *   Josh Soref <timeless@mac.com>
+ *   Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above.  If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderLayerBlendInfo.h"
+
+#include "core/rendering/CompositedLayerMapping.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderLayerModelObject.h"
+
+namespace WebCore {
+
+RenderLayerBlendInfo::RenderLayerBlendInfo(RenderLayerModelObject* renderer)
+    : m_renderer(renderer)
+    , m_blendMode(blink::WebBlendModeNormal)
+    , m_childLayerHasBlendMode(false)
+    , m_childLayerHasBlendModeStatusDirty(false)
+{
+}
+
+bool RenderLayerBlendInfo::hasBlendMode() const
+{
+    return RuntimeEnabledFeatures::cssCompositingEnabled() && m_renderer->hasBlendMode();
+}
+
+void RenderLayerBlendInfo::updateBlendMode()
+{
+    if (!RuntimeEnabledFeatures::cssCompositingEnabled())
+        return;
+
+    blink::WebBlendMode newBlendMode = m_renderer->style()->blendMode();
+    if (newBlendMode == m_blendMode)
+        return;
+
+    bool hadBlendMode = m_blendMode != blink::WebBlendModeNormal;
+    m_blendMode = newBlendMode;
+
+    RenderLayer* layer = m_renderer->layer();
+    // Only update the flag if a blend mode is set or unset.
+    if (layer->parent() && (!hadBlendMode || !hasBlendMode()))
+        layer->parent()->blendInfo().dirtyAncestorChainBlendedDescendantStatus();
+
+    if (layer->hasCompositedLayerMapping())
+        layer->compositedLayerMapping()->setBlendMode(newBlendMode);
+}
+
+void RenderLayerBlendInfo::dirtyAncestorChainBlendedDescendantStatus()
+{
+    for (RenderLayer* layer = m_renderer->layer(); layer; layer = layer->parent()) {
+        if (layer->blendInfo().childLayerHasBlendModeStatusDirty())
+            break;
+
+        layer->blendInfo().setChildLayerHasBlendModeStatusDirty(true);
+
+        if (layer->stackingNode()->isStackingContext())
+            break;
+    }
+}
+
+void RenderLayerBlendInfo::setAncestorChainBlendedDescendant()
+{
+    for (RenderLayer* layer = m_renderer->layer(); layer; layer = layer->parent()) {
+        if (!layer->blendInfo().childLayerHasBlendModeStatusDirty() && layer->blendInfo().childLayerHasBlendMode())
+            break;
+
+        layer->blendInfo().setChildLayerHasBlendMode(true);
+        layer->blendInfo().setChildLayerHasBlendModeStatusDirty(false);
+
+        if (layer->stackingNode()->isStackingContext())
+            break;
+    }
+}
+
+} // namespace WebCore
diff --git a/Source/core/rendering/RenderLayerBlendInfo.h b/Source/core/rendering/RenderLayerBlendInfo.h
new file mode 100644
index 0000000..a138b9b
--- /dev/null
+++ b/Source/core/rendering/RenderLayerBlendInfo.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ *   Robert O'Callahan <roc+@cs.cmu.edu>
+ *   David Baron <dbaron@fas.harvard.edu>
+ *   Christian Biesinger <cbiesinger@web.de>
+ *   Randall Jesup <rjesup@wgate.com>
+ *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ *   Josh Soref <timeless@mac.com>
+ *   Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above.  If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#ifndef RenderLayerBlendInfo_h
+#define RenderLayerBlendInfo_h
+
+#include "public/platform/WebBlendMode.h"
+#include "wtf/Assertions.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class RenderLayerModelObject;
+
+class RenderLayerBlendInfo {
+    WTF_MAKE_NONCOPYABLE(RenderLayerBlendInfo);
+public:
+    explicit RenderLayerBlendInfo(RenderLayerModelObject*);
+
+    bool hasBlendMode() const;
+    void updateBlendMode();
+
+    bool childLayerHasBlendMode() const
+    {
+        ASSERT(!m_childLayerHasBlendModeStatusDirty);
+        return m_childLayerHasBlendMode;
+    }
+    bool childLayerHasBlendModeWhileDirty() const { return m_childLayerHasBlendMode; }
+
+    void setChildLayerHasBlendMode(bool b) { m_childLayerHasBlendMode = b; }
+
+    bool childLayerHasBlendModeStatusDirty() const { return m_childLayerHasBlendModeStatusDirty; }
+    void setChildLayerHasBlendModeStatusDirty(bool b) { m_childLayerHasBlendModeStatusDirty = b; }
+
+    void setAncestorChainBlendedDescendant();
+    void dirtyAncestorChainBlendedDescendantStatus();
+
+    blink::WebBlendMode blendMode() const { return m_blendMode; }
+
+private:
+    RenderLayerModelObject* m_renderer;
+    blink::WebBlendMode m_blendMode;
+
+    unsigned m_childLayerHasBlendMode : 1;
+    unsigned m_childLayerHasBlendModeStatusDirty : 1;
+};
+
+} // namespace WebCore
+
+#endif // RenderLayerBlendInfo_h
diff --git a/Source/core/rendering/RenderLayerClipper.cpp b/Source/core/rendering/RenderLayerClipper.cpp
index afc8d2a..c1284a9 100644
--- a/Source/core/rendering/RenderLayerClipper.cpp
+++ b/Source/core/rendering/RenderLayerClipper.cpp
@@ -54,8 +54,11 @@
     ClipRectsType clipRectsType = clipRectsContext.clipRectsType;
     ASSERT(clipRectsType < NumCachedClipRectsTypes);
     if (m_clipRectsCache && m_clipRectsCache->getClipRects(clipRectsType, clipRectsContext.respectOverflowClip)) {
-        ASSERT(clipRectsContext.rootLayer == m_clipRectsCache->m_clipRectsRoot[clipRectsType]);
-        ASSERT(m_clipRectsCache->m_scrollbarRelevancy[clipRectsType] == clipRectsContext.overlayScrollbarSizeRelevancy);
+        // FIXME: these asserts trigger for squashing. Need to update this code to support squashing as appropriate.
+        // These ASSERTs also are triggering ASSERTs on some ChromeOS tests:
+        // https://code.google.com/p/chromium/issues/detail?id=342478
+        // ASSERT(clipRectsContext.rootLayer == m_clipRectsCache->m_clipRectsRoot[clipRectsType]);
+        // ASSERT(m_clipRectsCache->m_scrollbarRelevancy[clipRectsType] == clipRectsContext.overlayScrollbarSizeRelevancy);
 
 #ifdef CHECK_CACHED_CLIP_RECTS
         // This code is useful to check cached clip rects, but is too expensive to leave enabled in debug builds by default.
@@ -115,6 +118,112 @@
     }
 }
 
+LayoutRect RenderLayerClipper::childrenClipRect() const
+{
+    // FIXME: border-radius not accounted for.
+    // FIXME: Regions not accounted for.
+    RenderView* renderView = m_renderer->view();
+    RenderLayer* clippingRootLayer = clippingRootForPainting();
+    LayoutRect layerBounds;
+    ClipRect backgroundRect, foregroundRect, outlineRect;
+    ClipRectsContext clipRectsContext(clippingRootLayer, TemporaryClipRects);
+    // Need to use temporary clip rects, because the value of 'dontClipToOverflow' may be different from the painting path (<rdar://problem/11844909>).
+    calculateRects(clipRectsContext, renderView->unscaledDocumentRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
+    return clippingRootLayer->renderer()->localToAbsoluteQuad(FloatQuad(foregroundRect.rect())).enclosingBoundingBox();
+}
+
+LayoutRect RenderLayerClipper::selfClipRect() const
+{
+    // FIXME: border-radius not accounted for.
+    RenderView* renderView = m_renderer->view();
+    RenderLayer* clippingRootLayer = clippingRootForPainting();
+    LayoutRect layerBounds;
+    ClipRect backgroundRect, foregroundRect, outlineRect;
+    ClipRectsContext clipRectsContext(clippingRootLayer, PaintingClipRects);
+    calculateRects(clipRectsContext, renderView->documentRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
+    return clippingRootLayer->renderer()->localToAbsoluteQuad(FloatQuad(backgroundRect.rect())).enclosingBoundingBox();
+}
+
+LayoutRect RenderLayerClipper::localClipRect() const
+{
+    // FIXME: border-radius not accounted for.
+    RenderLayer* clippingRootLayer = clippingRootForPainting();
+    LayoutRect layerBounds;
+    ClipRect backgroundRect, foregroundRect, outlineRect;
+    ClipRectsContext clipRectsContext(clippingRootLayer, PaintingClipRects);
+    calculateRects(clipRectsContext, PaintInfo::infiniteRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
+
+    LayoutRect clipRect = backgroundRect.rect();
+    if (clipRect == PaintInfo::infiniteRect())
+        return clipRect;
+
+    LayoutPoint clippingRootOffset;
+    m_renderer->layer()->convertToLayerCoords(clippingRootLayer, clippingRootOffset);
+    clipRect.moveBy(-clippingRootOffset);
+
+    return clipRect;
+}
+
+void RenderLayerClipper::calculateRects(const ClipRectsContext& clipRectsContext, const LayoutRect& paintDirtyRect, LayoutRect& layerBounds,
+    ClipRect& backgroundRect, ClipRect& foregroundRect, ClipRect& outlineRect, const LayoutPoint* offsetFromRoot) const
+{
+    if (clipRectsContext.rootLayer != m_renderer->layer() && m_renderer->layer()->parent()) {
+        backgroundRect = backgroundClipRect(clipRectsContext);
+        backgroundRect.intersect(paintDirtyRect);
+    } else {
+        backgroundRect = paintDirtyRect;
+    }
+
+    foregroundRect = backgroundRect;
+    outlineRect = backgroundRect;
+
+    LayoutPoint offset;
+    if (offsetFromRoot)
+        offset = *offsetFromRoot;
+    else
+        m_renderer->layer()->convertToLayerCoords(clipRectsContext.rootLayer, offset);
+    layerBounds = LayoutRect(offset, m_renderer->layer()->size());
+
+    // Update the clip rects that will be passed to child layers.
+    if (m_renderer->hasOverflowClip()) {
+        // This layer establishes a clip of some kind.
+        if (m_renderer->layer() != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip == RespectOverflowClip) {
+            foregroundRect.intersect(toRenderBox(m_renderer)->overflowClipRect(offset, clipRectsContext.overlayScrollbarSizeRelevancy));
+            if (m_renderer->style()->hasBorderRadius())
+                foregroundRect.setHasRadius(true);
+        }
+
+        // If we establish an overflow clip at all, then go ahead and make sure our background
+        // rect is intersected with our layer's bounds including our visual overflow,
+        // since any visual overflow like box-shadow or border-outset is not clipped by overflow:auto/hidden.
+        if (toRenderBox(m_renderer)->hasVisualOverflow()) {
+            // FIXME: Perhaps we should be propagating the borderbox as the clip rect for children, even though
+            //        we may need to inflate our clip specifically for shadows or outsets.
+            // FIXME: Does not do the right thing with CSS regions yet, since we don't yet factor in the
+            // individual region boxes as overflow.
+            LayoutRect layerBoundsWithVisualOverflow = toRenderBox(m_renderer)->visualOverflowRect();
+            toRenderBox(m_renderer)->flipForWritingMode(layerBoundsWithVisualOverflow); // Layers are in physical coordinates, so the overflow has to be flipped.
+            layerBoundsWithVisualOverflow.moveBy(offset);
+            if (m_renderer->layer() != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip == RespectOverflowClip)
+                backgroundRect.intersect(layerBoundsWithVisualOverflow);
+        } else {
+            LayoutRect bounds = toRenderBox(m_renderer)->borderBoxRect();
+            bounds.moveBy(offset);
+            if (m_renderer->layer() != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip == RespectOverflowClip)
+                backgroundRect.intersect(bounds);
+        }
+    }
+
+    // CSS clip (different than clipping due to overflow) can clip to any box, even if it falls outside of the border box.
+    if (m_renderer->hasClip()) {
+        // Clip applies to *us* as well, so go ahead and update the damageRect.
+        LayoutRect newPosClip = toRenderBox(m_renderer)->clipRect(offset);
+        backgroundRect.intersect(newPosClip);
+        foregroundRect.intersect(newPosClip);
+        outlineRect.intersect(newPosClip);
+    }
+}
+
 void RenderLayerClipper::calculateClipRects(const ClipRectsContext& clipRectsContext, ClipRects& clipRects) const
 {
     if (!m_renderer->layer()->parent()) {
@@ -171,7 +280,7 @@
         }
 
         if (m_renderer->hasOverflowClip()) {
-            ClipRect newOverflowClip = toRenderBox(m_renderer)->overflowClipRect(offset, clipRectsContext.region, clipRectsContext.overlayScrollbarSizeRelevancy);
+            ClipRect newOverflowClip = toRenderBox(m_renderer)->overflowClipRect(offset, clipRectsContext.overlayScrollbarSizeRelevancy);
             if (m_renderer->style()->hasBorderRadius())
                 newOverflowClip.setHasRadius(true);
             clipRects.setOverflowClipRect(intersection(newOverflowClip, clipRects.overflowClipRect()));
@@ -179,7 +288,7 @@
                 clipRects.setPosClipRect(intersection(newOverflowClip, clipRects.posClipRect()));
         }
         if (m_renderer->hasClip()) {
-            LayoutRect newPosClip = toRenderBox(m_renderer)->clipRect(offset, clipRectsContext.region);
+            LayoutRect newPosClip = toRenderBox(m_renderer)->clipRect(offset);
             clipRects.setPosClipRect(intersection(newPosClip, clipRects.posClipRect()));
             clipRects.setOverflowClipRect(intersection(newPosClip, clipRects.overflowClipRect()));
             clipRects.setFixedClipRect(intersection(newPosClip, clipRects.fixedClipRect()));
@@ -187,4 +296,78 @@
     }
 }
 
+static inline ClipRect backgroundClipRectForPosition(const ClipRects& parentRects, EPosition position)
+{
+    if (position == FixedPosition)
+        return parentRects.fixedClipRect();
+
+    if (position == AbsolutePosition)
+        return parentRects.posClipRect();
+
+    return parentRects.overflowClipRect();
+}
+
+ClipRect RenderLayerClipper::backgroundClipRect(const ClipRectsContext& clipRectsContext) const
+{
+    ASSERT(m_renderer->layer()->parent());
+
+    ClipRects parentRects;
+
+    // If we cross into a different pagination context, then we can't rely on the cache.
+    // Just switch over to using TemporaryClipRects.
+    if (clipRectsContext.clipRectsType != TemporaryClipRects && m_renderer->layer()->parent()->enclosingPaginationLayer() != m_renderer->layer()->enclosingPaginationLayer()) {
+        ClipRectsContext tempContext(clipRectsContext);
+        tempContext.clipRectsType = TemporaryClipRects;
+        parentClipRects(tempContext, parentRects);
+    } else {
+        parentClipRects(clipRectsContext, parentRects);
+    }
+
+    ClipRect backgroundClipRect = backgroundClipRectForPosition(parentRects, m_renderer->style()->position());
+    RenderView* view = m_renderer->view();
+    ASSERT(view);
+
+    // Note: infinite clipRects should not be scrolled here, otherwise they will accidentally no longer be considered infinite.
+    if (parentRects.fixed() && clipRectsContext.rootLayer->renderer() == view && backgroundClipRect != PaintInfo::infiniteRect())
+        backgroundClipRect.move(view->frameView()->scrollOffsetForFixedPosition());
+
+    return backgroundClipRect;
+}
+
+void RenderLayerClipper::parentClipRects(const ClipRectsContext& clipRectsContext, ClipRects& clipRects) const
+{
+    ASSERT(m_renderer->layer()->parent());
+
+    RenderLayerClipper& parentClipper = m_renderer->layer()->parent()->clipper();
+    if (clipRectsContext.clipRectsType == TemporaryClipRects) {
+        parentClipper.calculateClipRects(clipRectsContext, clipRects);
+        return;
+    }
+
+    parentClipper.updateClipRects(clipRectsContext);
+    clipRects = *parentClipper.clipRects(clipRectsContext);
+}
+
+RenderLayer* RenderLayerClipper::clippingRootForPainting() const
+{
+    if (m_renderer->hasCompositedLayerMapping())
+        return const_cast<RenderLayer*>(m_renderer->layer());
+
+    const RenderLayer* current = m_renderer->layer();
+    while (current) {
+        if (current->isRootLayer())
+            return const_cast<RenderLayer*>(current);
+
+        current = current->compositingContainer();
+        ASSERT(current);
+        if (current->transform()
+            || (current->compositingState() == PaintsIntoOwnBacking)
+        )
+            return const_cast<RenderLayer*>(current);
+    }
+
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderLayerClipper.h b/Source/core/rendering/RenderLayerClipper.h
index 03a3ef1..1d6551a 100644
--- a/Source/core/rendering/RenderLayerClipper.h
+++ b/Source/core/rendering/RenderLayerClipper.h
@@ -51,21 +51,20 @@
 namespace WebCore {
 
 class RenderLayer;
-class RenderRegion;
 
 struct ClipRectsContext {
-    ClipRectsContext(const RenderLayer* inRootLayer, RenderRegion* inRegion, ClipRectsType inClipRectsType, OverlayScrollbarSizeRelevancy inOverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize, ShouldRespectOverflowClip inRespectOverflowClip = RespectOverflowClip)
+    ClipRectsContext(const RenderLayer* inRootLayer, ClipRectsType inClipRectsType, OverlayScrollbarSizeRelevancy inOverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize, ShouldRespectOverflowClip inRespectOverflowClip = RespectOverflowClip, const LayoutSize& inSubPixelAccumulation = LayoutSize())
         : rootLayer(inRootLayer)
-        , region(inRegion)
         , clipRectsType(inClipRectsType)
         , overlayScrollbarSizeRelevancy(inOverlayScrollbarSizeRelevancy)
         , respectOverflowClip(inRespectOverflowClip)
+        , subPixelAccumulation(inSubPixelAccumulation)
     { }
     const RenderLayer* rootLayer;
-    RenderRegion* region;
     ClipRectsType clipRectsType;
     OverlayScrollbarSizeRelevancy overlayScrollbarSizeRelevancy;
     ShouldRespectOverflowClip respectOverflowClip;
+    const LayoutSize& subPixelAccumulation;
 };
 
 class RenderLayerClipper {
@@ -88,11 +87,31 @@
     void clearClipRectsIncludingDescendants(ClipRectsType typeToClear = AllClipRectTypes);
     void clearClipRects(ClipRectsType typeToClear = AllClipRectTypes);
 
+    LayoutRect childrenClipRect() const; // Returns the foreground clip rect of the layer in the document's coordinate space.
+    LayoutRect selfClipRect() const; // Returns the background clip rect of the layer in the document's coordinate space.
+    LayoutRect localClipRect() const; // Returns the background clip rect of the layer in the local coordinate space.
+
+    ClipRect backgroundClipRect(const ClipRectsContext&) const;
+
+    // FIXME: The following functions should be private.
+
+    // This method figures out our layerBounds in coordinates relative to
+    // |rootLayer}. It also computes our background and foreground clip rects
+    // for painting/event handling.
+    // Pass offsetFromRoot if known.
+    void calculateRects(const ClipRectsContext&, const LayoutRect& paintDirtyRect, LayoutRect& layerBounds,
+        ClipRect& backgroundRect, ClipRect& foregroundRect, ClipRect& outlineRect, const LayoutPoint* offsetFromRoot = 0) const;
+
     // Compute and return the clip rects. If useCached is true, will used previously computed clip rects on ancestors
     // (rather than computing them all from scratch up the parent chain).
     void calculateClipRects(const ClipRectsContext&, ClipRects&) const;
 
 private:
+    void parentClipRects(const ClipRectsContext&, ClipRects&) const;
+
+    // The layer relative to which clipping rects for this layer are computed.
+    RenderLayer* clippingRootForPainting() const;
+
     // FIXME: Could this be a RenderBox?
     RenderLayerModelObject* m_renderer;
 
diff --git a/Source/core/rendering/RenderLayerCompositor.cpp b/Source/core/rendering/RenderLayerCompositor.cpp
index 4d86a66..137d720 100644
--- a/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/RenderLayerCompositor.cpp
@@ -34,17 +34,17 @@
 #include "core/animation/DocumentAnimations.h"
 #include "core/dom/FullscreenElementStack.h"
 #include "core/dom/NodeList.h"
+#include "core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
 #include "core/html/HTMLCanvasElement.h"
 #include "core/html/HTMLIFrameElement.h"
-#include "core/html/HTMLVideoElement.h"
+#include "core/html/HTMLMediaElement.h"
 #include "core/html/canvas/CanvasRenderingContext.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Chrome.h"
-#include "core/frame/Frame.h"
-#include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/frame/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingConstraints.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/rendering/CompositedLayerMapping.h"
@@ -174,8 +174,9 @@
 };
 
 struct CompositingRecursionData {
-    CompositingRecursionData(RenderLayer* compAncestor, bool testOverlap)
+    CompositingRecursionData(RenderLayer* compAncestor, RenderLayer* mostRecentCompositedLayer, bool testOverlap)
         : m_compositingAncestor(compAncestor)
+        , m_mostRecentCompositedLayer(mostRecentCompositedLayer)
         , m_subtreeIsCompositing(false)
         , m_hasUnisolatedCompositedBlendingDescendant(false)
         , m_testingOverlap(testOverlap)
@@ -187,6 +188,7 @@
 
     CompositingRecursionData(const CompositingRecursionData& other)
         : m_compositingAncestor(other.m_compositingAncestor)
+        , m_mostRecentCompositedLayer(other.m_mostRecentCompositedLayer)
         , m_subtreeIsCompositing(other.m_subtreeIsCompositing)
         , m_hasUnisolatedCompositedBlendingDescendant(other.m_hasUnisolatedCompositedBlendingDescendant)
         , m_testingOverlap(other.m_testingOverlap)
@@ -197,6 +199,7 @@
     }
 
     RenderLayer* m_compositingAncestor;
+    RenderLayer* m_mostRecentCompositedLayer; // in paint order regardless of hierarchy.
     bool m_subtreeIsCompositing;
     bool m_hasUnisolatedCompositedBlendingDescendant;
     bool m_testingOverlap;
@@ -210,7 +213,6 @@
     : m_renderView(renderView)
     , m_hasAcceleratedCompositing(true)
     , m_compositingTriggers(static_cast<ChromeClient::CompositingTriggerFlags>(ChromeClient::AllTriggers))
-    , m_compositedLayerCount(0)
     , m_showRepaintCounter(false)
     , m_needsToRecomputeCompositingRequirements(false)
     , m_needsToUpdateLayerTreeGeometry(false)
@@ -275,10 +277,10 @@
     m_forceCompositingMode = forceCompositingMode;
 }
 
-bool RenderLayerCompositor::isLayerSquashingEnabled() const
+bool RenderLayerCompositor::layerSquashingEnabled() const
 {
     if (Settings* settings = m_renderView->document().settings())
-        return settings->isLayerSquashingEnabled();
+        return settings->layerSquashingEnabled();
 
     return false;
 }
@@ -290,30 +292,11 @@
 
 void RenderLayerCompositor::setCompositingLayersNeedRebuild(bool needRebuild)
 {
+    // FIXME: crbug,com/332248 ideally this could be merged with setNeedsCompositingUpdate().
     if (inCompositingMode())
         m_compositingLayersNeedRebuild = needRebuild;
-}
 
-void RenderLayerCompositor::didChangeVisibleRect()
-{
-    GraphicsLayer* rootLayer = rootGraphicsLayer();
-    if (!rootLayer)
-        return;
-
-    FrameView* frameView = m_renderView ? m_renderView->frameView() : 0;
-    if (!frameView)
-        return;
-
-    IntRect visibleRect = m_containerLayer ? IntRect(IntPoint(), frameView->contentsSize()) : frameView->visibleContentRect();
-    if (rootLayer->visibleRectChangeRequiresFlush(visibleRect)) {
-        if (Page* page = this->page())
-            page->chrome().client().scheduleCompositingLayerFlush();
-    }
-}
-
-bool RenderLayerCompositor::hasAnyAdditionalCompositedLayers(const RenderLayer* rootLayer) const
-{
-    return m_compositedLayerCount > (rootLayer->hasCompositedLayerMapping() ? 1 : 0);
+    m_renderView->frameView()->scheduleAnimation();
 }
 
 void RenderLayerCompositor::updateCompositingRequirementsState()
@@ -325,7 +308,7 @@
 
     m_needsUpdateCompositingRequirementsState = false;
 
-    if (!rootRenderLayer() || !rootRenderLayer()->acceleratedCompositingForOverflowScrollEnabled())
+    if (!rootRenderLayer() || !m_renderView->acceleratedCompositingForOverflowScrollEnabled())
         return;
 
     for (HashSet<RenderLayer*>::iterator it = m_outOfFlowPositionedLayers.begin(); it != m_outOfFlowPositionedLayers.end(); ++it)
@@ -348,7 +331,7 @@
             return 0;
         fullscreenElement = FullscreenElementStack::currentFullScreenElementFrom(document);
     }
-    if (!fullscreenElement || !isHTMLVideoElement(fullscreenElement))
+    if (!fullscreenElement || !fullscreenElement->hasTagName(videoTag))
         return 0;
     RenderObject* renderer = fullscreenElement->renderer();
     if (!renderer)
@@ -365,37 +348,28 @@
     if (frame && frame->contentRenderer()) {
         RenderLayerCompositor* frameCompositor = frame->contentRenderer()->compositor();
         if (frameCompositor && !frameCompositor->isMainFrame())
-            frame->contentRenderer()->compositor()->updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
+            frame->contentRenderer()->compositor()->updateCompositingLayers();
     }
 }
 
-void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType)
+void RenderLayerCompositor::setNeedsCompositingUpdate(CompositingUpdateType updateType)
 {
+    // FIXME: this code was historically part of updateCompositingLayers, and
+    // for now is kept totally equivalent to the previous implementation. We
+    // should carefully clean up the awkward early-exit semantics, balancing between
+    // skipping unnecessary compositing updates and not incorrectly skipping
+    // necessary updates.
+
     // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
     if (m_renderView->needsLayout())
         return;
 
-    if (updateType == CompositingUpdateFinishAllDeferredWork && isMainFrame() && m_renderView->frameView())
-        finishCompositingUpdateForFrameTree(&m_renderView->frameView()->frame());
-
     if (m_forceCompositingMode && !m_compositing)
         enableCompositingMode(true);
 
     if (!m_needsToRecomputeCompositingRequirements && !m_compositing)
         return;
 
-    AnimationUpdateBlock animationUpdateBlock(m_renderView->frameView()->frame().animation());
-
-    TemporaryChange<bool> postLayoutChange(m_inPostLayoutUpdate, true);
-
-    bool needCompositingRequirementsUpdate = false;
-    bool needHierarchyAndGeometryUpdate = false;
-    bool needGeometryUpdate = false;
-    bool needsToUpdateScrollingCoordinator = false;
-
-    // CompositingUpdateFinishAllDeferredWork is the only updateType that will actually do any work in this
-    // function. All other updateTypes will simply mark that something needed updating, and defer the actual
-    // update. This way we only need to compute all compositing state once for every frame drawn (if needed).
     switch (updateType) {
     case CompositingUpdateAfterStyleChange:
     case CompositingUpdateAfterLayout:
@@ -408,19 +382,46 @@
     case CompositingUpdateOnCompositedScroll:
         m_needsToUpdateLayerTreeGeometry = true;
         break;
-    case CompositingUpdateFinishAllDeferredWork:
-        needCompositingRequirementsUpdate = m_needsToRecomputeCompositingRequirements;
-        needHierarchyAndGeometryUpdate = m_compositingLayersNeedRebuild;
-        needGeometryUpdate = m_needsToUpdateLayerTreeGeometry;
-        needsToUpdateScrollingCoordinator = scrollingCoordinator() ? scrollingCoordinator()->needsToUpdateAfterCompositingChange() : false;
-        break;
     }
 
+    m_renderView->frameView()->scheduleAnimation();
+}
+
+void RenderLayerCompositor::updateCompositingLayers()
+{
+    TRACE_EVENT0("blink_rendering", "RenderLayerCompositor::updateCompositingLayers");
+
+    // FIXME: We should carefully clean up the awkward early-exit semantics, balancing
+    // between skipping unnecessary compositing updates and not incorrectly skipping
+    // necessary updates.
+
+    // Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
+    // FIXME: Can we assert that we never return here?
+    if (m_renderView->needsLayout())
+        return;
+
+    lifecycle().advanceTo(DocumentLifecycle::InCompositingUpdate);
+    DocumentLifecycle::Scope lifecycleScope(lifecycle(), DocumentLifecycle::CompositingClean);
+
+    if (isMainFrame() && m_renderView->frameView())
+        finishCompositingUpdateForFrameTree(&m_renderView->frameView()->frame());
+
+    if (m_forceCompositingMode && !m_compositing)
+        enableCompositingMode(true);
+
+    if (!m_needsToRecomputeCompositingRequirements && !m_compositing)
+        return;
+
+    TemporaryChange<bool> postLayoutChange(m_inPostLayoutUpdate, true);
+
+    bool needCompositingRequirementsUpdate = m_needsToRecomputeCompositingRequirements;
+    bool needHierarchyAndGeometryUpdate = m_compositingLayersNeedRebuild;
+    bool needGeometryUpdate = m_needsToUpdateLayerTreeGeometry;
+    bool needsToUpdateScrollingCoordinator = scrollingCoordinator() ? scrollingCoordinator()->needsToUpdateAfterCompositingChange() : false;
+
     if (!needCompositingRequirementsUpdate && !needHierarchyAndGeometryUpdate && !needGeometryUpdate && !needsToUpdateScrollingCoordinator)
         return;
 
-    ASSERT(updateType == CompositingUpdateFinishAllDeferredWork);
-
     // Only clear the flags if we're updating the entire hierarchy.
     m_compositingLayersNeedRebuild = false;
     m_needsToUpdateLayerTreeGeometry = false;
@@ -430,7 +431,7 @@
     if (needCompositingRequirementsUpdate) {
         // Go through the layers in presentation order, so that we can compute which RenderLayers need compositing layers.
         // FIXME: we could maybe do this and the hierarchy udpate in one pass, but the parenting logic would be more complex.
-        CompositingRecursionData recursionData(updateRoot, true);
+        CompositingRecursionData recursionData(updateRoot, 0, true);
         bool layersChanged = false;
         bool saw3DTransform = false;
         {
@@ -442,14 +443,23 @@
             // should be removed as soon as proper overlap testing based on
             // scrolling and animation bounds is implemented (crbug.com/252472).
             Vector<RenderLayer*> unclippedDescendants;
-            computeCompositingRequirements(0, updateRoot, &overlapTestRequestMap, recursionData, layersChanged, saw3DTransform, unclippedDescendants);
+            computeCompositingRequirements(0, updateRoot, &overlapTestRequestMap, recursionData, saw3DTransform, unclippedDescendants);
+        }
 
+        {
+            TRACE_EVENT0("blink_rendering", "RenderLayerCompositor::assignLayersToBackings");
+            assignLayersToBackings(updateRoot, layersChanged);
+        }
+
+        {
+            TRACE_EVENT0("blink_rendering", "RenderLayerCompositor::updateHasVisibleNonLayerContentLoop");
             const FrameView::ScrollableAreaSet* scrollableAreas = m_renderView->frameView()->scrollableAreas();
             if (scrollableAreas) {
                 for (FrameView::ScrollableAreaSet::iterator it = scrollableAreas->begin(); it != scrollableAreas->end(); ++it)
                     (*it)->updateHasVisibleNonLayerContent();
             }
         }
+
         needHierarchyAndGeometryUpdate |= layersChanged;
     }
 
@@ -469,15 +479,15 @@
                 childList.append(video->compositedLayerMapping()->mainGraphicsLayer());
             }
         }
-        // Even when childList is empty, don't drop out of compositing mode if there are
-        // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
-        if (childList.isEmpty() && !hasAnyAdditionalCompositedLayers(updateRoot))
+
+        if (childList.isEmpty())
             destroyRootLayer();
         else
             m_rootContentLayer->setChildren(childList);
     } else if (needGeometryUpdate) {
         // We just need to do a geometry update. This is only used for position:fixed scrolling;
         // most of the time, geometry is updated via RenderLayer::styleChanged().
+        TRACE_EVENT0("blink_rendering", "RenderLayerCompositor::updateLayerTreeGeometry");
         updateLayerTreeGeometry(updateRoot);
     }
 
@@ -496,14 +506,25 @@
         InspectorInstrumentation::layerTreeDidChange(page());
 }
 
-void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer* renderLayer)
-{
-    ASSERT(m_compositedLayerCount > 0);
-    --m_compositedLayerCount;
-}
-
 static bool requiresCompositing(CompositingReasons reasons)
 {
+    // Any reasons other than overlap or assumed overlap will require the layer to be separately compositing.
+    return reasons & ~CompositingReasonComboSquashableReasons;
+}
+
+static bool requiresSquashing(CompositingReasons reasons)
+{
+    // If the layer has overlap or assumed overlap, but no other reasons, then it should be squashed.
+    return !requiresCompositing(reasons) && (reasons & CompositingReasonComboSquashableReasons);
+}
+
+static bool requiresCompositingOrSquashing(CompositingReasons reasons)
+{
+#ifndef NDEBUG
+    bool fastAnswer = reasons != CompositingReasonNone;
+    bool slowAnswer = requiresCompositing(reasons) || requiresSquashing(reasons);
+    ASSERT(fastAnswer == slowAnswer);
+#endif
     return reasons != CompositingReasonNone;
 }
 
@@ -520,37 +541,46 @@
 bool RenderLayerCompositor::allocateOrClearCompositedLayerMapping(RenderLayer* layer)
 {
     bool compositedLayerMappingChanged = false;
-    RenderLayer::ViewportConstrainedNotCompositedReason viewportConstrainedNotCompositedReason = RenderLayer::NoNotCompositedReason;
-    requiresCompositingForPosition(layer->renderer(), layer, &viewportConstrainedNotCompositedReason);
+    bool nonCompositedReasonChanged = updateLayerIfViewportConstrained(layer);
+    CompositingStateTransitionType compositedLayerUpdate = computeCompositedLayerUpdate(layer);
 
     // FIXME: It would be nice to directly use the layer's compositing reason,
     // but allocateOrClearCompositedLayerMapping also gets called without having updated compositing
     // requirements fully.
-    if (needsToBeComposited(layer)) {
+    switch (compositedLayerUpdate) {
+    case AllocateOwnCompositedLayerMapping:
+        ASSERT(!layer->hasCompositedLayerMapping());
         enableCompositingMode();
 
-        if (!layer->hasCompositedLayerMapping()) {
-            // If we need to repaint, do so before allocating the compositedLayerMapping
-            repaintOnCompositingChange(layer);
+        // If we need to repaint, do so before allocating the compositedLayerMapping
+        repaintOnCompositingChange(layer);
+        layer->ensureCompositedLayerMapping();
+        compositedLayerMappingChanged = true;
 
-            layer->ensureCompositedLayerMapping();
-            compositedLayerMappingChanged = true;
-
-            // At this time, the ScrollingCooridnator only supports the top-level frame.
-            if (layer->isRootLayer() && isMainFrame()) {
-                if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
-                    scrollingCoordinator->frameViewRootLayerDidChange(m_renderView->frameView());
-            }
-
-            // This layer and all of its descendants have cached repaints rects that are relative to
-            // the repaint container, so change when compositing changes; we need to update them here.
-            if (layer->parent())
-                layer->repainter().computeRepaintRectsIncludingDescendants();
+        // At this time, the ScrollingCooridnator only supports the top-level frame.
+        if (layer->isRootLayer() && isMainFrame()) {
+            if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
+                scrollingCoordinator->frameViewRootLayerDidChange(m_renderView->frameView());
         }
 
-        if (layer->compositedLayerMapping()->updateRequiresOwnBackingStoreForIntrinsicReasons())
-            compositedLayerMappingChanged = true;
-    } else {
+        // If this layer was previously squashed, we need to remove its reference to a groupedMapping right away, so
+        // that computing repaint rects will know the layer's correct compositingState.
+        // FIXME: do we need to also remove the layer from it's location in the squashing list of its groupedMapping?
+        // Need to create a test where a squashed layer pops into compositing. And also to cover all other
+        // sorts of compositingState transitions.
+        layer->setLostGroupedMapping(false);
+        layer->setGroupedMapping(0);
+
+        // FIXME: it seems premature to compute this before all compositing state has been updated?
+        // This layer and all of its descendants have cached repaints rects that are relative to
+        // the repaint container, so change when compositing changes; we need to update them here.
+        if (layer->parent())
+            layer->repainter().computeRepaintRectsIncludingDescendants();
+
+        break;
+    case RemoveOwnCompositedLayerMapping:
+    // PutInSquashingLayer means you might have to remove the composited layer mapping first.
+    case PutInSquashingLayer:
         if (layer->hasCompositedLayerMapping()) {
             // If we're removing the compositedLayerMapping from a reflection, clear the source GraphicsLayer's pointer to
             // its replica GraphicsLayer. In practice this should never happen because reflectee and reflection
@@ -575,8 +605,17 @@
             // If we need to repaint, do so now that we've removed the compositedLayerMapping
             repaintOnCompositingChange(layer);
         }
+
+        break;
+    case RemoveFromSquashingLayer:
+    case NoCompositingStateChange:
+        // Do nothing.
+        break;
     }
 
+    if (layer->hasCompositedLayerMapping() && layer->compositedLayerMapping()->updateRequiresOwnBackingStoreForIntrinsicReasons())
+        compositedLayerMappingChanged = true;
+
     if (compositedLayerMappingChanged && layer->renderer()->isRenderPart()) {
         RenderLayerCompositor* innerCompositor = frameContentsCompositor(toRenderPart(layer->renderer()));
         if (innerCompositor && innerCompositor->inCompositingMode())
@@ -588,32 +627,143 @@
 
     // If a fixed position layer gained/lost a compositedLayerMapping or the reason not compositing it changed,
     // the scrolling coordinator needs to recalculate whether it can do fast scrolling.
-    bool nonCompositedReasonChanged = false;
-    if (layer->renderer()->style()->position() == FixedPosition) {
-        if (layer->viewportConstrainedNotCompositedReason() != viewportConstrainedNotCompositedReason) {
-            layer->setViewportConstrainedNotCompositedReason(viewportConstrainedNotCompositedReason);
-            nonCompositedReasonChanged = true;
-        }
-        if (compositedLayerMappingChanged || nonCompositedReasonChanged) {
-            if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
-                scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView->frameView());
-        }
+    if (compositedLayerMappingChanged || nonCompositedReasonChanged) {
+        if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
+            scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView->frameView());
     }
 
     return compositedLayerMappingChanged || nonCompositedReasonChanged;
 }
 
-bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer* layer)
+static IntPoint computeOffsetFromAbsolute(RenderLayer* layer)
+{
+    TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
+    layer->renderer()->mapLocalToContainer(0, transformState, ApplyContainerFlip);
+    transformState.flatten();
+    return roundedIntPoint(transformState.lastPlanarPoint());
+}
+
+bool RenderLayerCompositor::updateSquashingAssignment(RenderLayer* layer, SquashingState& squashingState)
+{
+    CompositingStateTransitionType compositedLayerUpdate = computeCompositedLayerUpdate(layer);
+
+    // NOTE: In the future as we generalize this, the background of this layer may need to be assigned to a different backing than
+    // the squashed RenderLayer's own primary contents. This would happen when we have a composited negative z-index element that needs
+    // to paint on top of the background, but below the layer's main contents. For now, because we always composite layers
+    // when they have a composited negative z-index child, such layers will never need squashing so it is not yet an issue.
+    if (compositedLayerUpdate == PutInSquashingLayer) {
+        // A layer that is squashed with other layers cannot have its own CompositedLayerMapping.
+        ASSERT(!layer->hasCompositedLayerMapping());
+        ASSERT(squashingState.hasMostRecentMapping);
+
+        IntPoint offsetFromAbsoluteForSquashedLayer = computeOffsetFromAbsolute(layer);
+
+        IntSize offsetFromSquashingCLM(offsetFromAbsoluteForSquashedLayer.x() - squashingState.offsetFromAbsoluteForSquashingCLM.x(),
+            offsetFromAbsoluteForSquashedLayer.y() - squashingState.offsetFromAbsoluteForSquashingCLM.y());
+
+        bool changedSquashingLayer =
+            squashingState.mostRecentMapping->updateSquashingLayerAssignment(layer, offsetFromSquashingCLM, squashingState.nextSquashedLayerIndex);
+        squashingState.nextSquashedLayerIndex++;
+
+        if (!changedSquashingLayer)
+            return true;
+
+        layer->clipper().clearClipRectsIncludingDescendants();
+
+        // If we need to repaint, do so before allocating the layer to the squashing layer.
+        repaintOnCompositingChange(layer);
+
+        // FIXME: it seems premature to compute this before all compositing state has been updated?
+        // This layer and all of its descendants have cached repaints rects that are relative to
+        // the repaint container, so change when compositing changes; we need to update them here.
+
+        // FIXME: what's up with parent()?
+        if (layer->parent())
+            layer->repainter().computeRepaintRectsIncludingDescendants();
+
+        return true;
+    } else if (compositedLayerUpdate == RemoveFromSquashingLayer) {
+        layer->setGroupedMapping(0);
+
+        // This layer and all of its descendants have cached repaints rects that are relative to
+        // the repaint container, so change when compositing changes; we need to update them here.
+        layer->repainter().computeRepaintRectsIncludingDescendants();
+
+        // If we need to repaint, do so now that we've removed it from a squashed layer
+        repaintOnCompositingChange(layer);
+
+        layer->setLostGroupedMapping(false);
+        return true;
+    }
+    return false;
+}
+
+bool RenderLayerCompositor::updateLayerIfViewportConstrained(RenderLayer* layer)
+{
+    RenderLayer::ViewportConstrainedNotCompositedReason viewportConstrainedNotCompositedReason = RenderLayer::NoNotCompositedReason;
+    requiresCompositingForPosition(layer->renderer(), layer, &viewportConstrainedNotCompositedReason);
+
+    if (layer->viewportConstrainedNotCompositedReason() != viewportConstrainedNotCompositedReason) {
+        ASSERT(layer->renderer()->style()->position() == FixedPosition);
+
+        layer->setViewportConstrainedNotCompositedReason(viewportConstrainedNotCompositedReason);
+        return true;
+    }
+    return false;
+}
+
+RenderLayerCompositor::CompositingStateTransitionType RenderLayerCompositor::computeCompositedLayerUpdate(const RenderLayer* layer)
+{
+    CompositingStateTransitionType update = NoCompositingStateChange;
+    if (needsOwnBacking(layer)) {
+        if (!layer->hasCompositedLayerMapping()) {
+            update = AllocateOwnCompositedLayerMapping;
+        }
+    } else {
+        if (layer->hasCompositedLayerMapping())
+            update = RemoveOwnCompositedLayerMapping;
+
+        if (layerSquashingEnabled()) {
+            if (requiresSquashing(layer->compositingReasons())) {
+                // We can't compute at this time whether the squashing layer update is a no-op,
+                // since that requires walking the render layer tree.
+                update = PutInSquashingLayer;
+            } else if (layer->groupedMapping() || layer->lostGroupedMapping()) {
+                update = RemoveFromSquashingLayer;
+            }
+        }
+    }
+    return update;
+}
+
+// These are temporary hacks to work around chicken-egg issues while we continue to refactor the compositing code.
+// See crbug.com/339892 for a list of tests that fail if this method is removed.
+void RenderLayerCompositor::applyUpdateLayerCompositingStateChickenEggHacks(RenderLayer* layer, CompositingStateTransitionType compositedLayerUpdate)
+{
+    if (compositedLayerUpdate != NoCompositingStateChange)
+        allocateOrClearCompositedLayerMapping(layer);
+}
+
+void RenderLayerCompositor::updateLayerCompositingState(RenderLayer* layer)
 {
     updateDirectCompositingReasons(layer);
-    bool layerChanged = allocateOrClearCompositedLayerMapping(layer);
+    CompositingStateTransitionType compositedLayerUpdate = computeCompositedLayerUpdate(layer);
+
+    if (compositedLayerUpdate != NoCompositingStateChange) {
+        setCompositingLayersNeedRebuild();
+        setNeedsToRecomputeCompositingRequirements();
+    }
 
     // See if we need content or clipping layers. Methods called here should assume
     // that the compositing state of descendant layers has not been updated yet.
-    if (layer->hasCompositedLayerMapping() && layer->compositedLayerMapping()->updateGraphicsLayerConfiguration())
-        layerChanged = true;
+    if (layer->hasCompositedLayerMapping() && layer->compositedLayerMapping()->updateGraphicsLayerConfiguration()) {
+        setCompositingLayersNeedRebuild();
+    } else if (compositedLayerUpdate == NoCompositingStateChange) {
+        if (layer->compositingState() == PaintsIntoOwnBacking || layer->compositingState() == HasOwnBackingButPaintsIntoAncestor)
+            setCompositingLayersNeedRebuild();
+    }
 
-    return layerChanged;
+    applyUpdateLayerCompositingStateChickenEggHacks(layer, compositedLayerUpdate);
 }
 
 void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer* layer)
@@ -632,26 +782,32 @@
 // This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
 void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer* layer, const LayoutRect& rect)
 {
-    RenderLayer* compositedAncestor = layer->enclosingCompositingLayerForRepaint(false /*exclude self*/);
+    RenderLayer* compositedAncestor = layer->enclosingCompositingLayerForRepaint(ExcludeSelf);
     if (compositedAncestor) {
-        ASSERT(compositedAncestor->compositingState() == PaintsIntoOwnBacking);
-
+        // FIXME: make sure repaintRect is computed correctly for squashed scenario
         LayoutPoint offset;
         layer->convertToLayerCoords(compositedAncestor, offset);
 
         LayoutRect repaintRect = rect;
         repaintRect.moveBy(offset);
 
-        compositedAncestor->repainter().setBackingNeedsRepaintInRect(repaintRect);
+        if (compositedAncestor->compositingState() == PaintsIntoOwnBacking) {
+            compositedAncestor->repainter().setBackingNeedsRepaintInRect(repaintRect);
+        } else if (compositedAncestor->compositingState() == PaintsIntoGroupedBacking) {
+            // FIXME: Need to perform the correct coordinate conversion for repaintRect here, including transforms
+            compositedAncestor->groupedMapping()->squashingLayer()->setNeedsDisplayInRect(repaintRect);
+        } else {
+            ASSERT_NOT_REACHED();
+        }
     }
 }
 
 // The bounds of the GraphicsLayer created for a compositing layer is the union of the bounds of all the descendant
 // RenderLayers that are rendered by the composited RenderLayer.
-IntRect RenderLayerCompositor::calculateCompositedBounds(const RenderLayer* layer, const RenderLayer* ancestorLayer) const
+LayoutRect RenderLayerCompositor::calculateCompositedBounds(const RenderLayer* layer, const RenderLayer* ancestorLayer) const
 {
     if (!canBeComposited(layer))
-        return IntRect();
+        return LayoutRect();
 
     RenderLayer::CalculateLayerBoundsFlags flags = RenderLayer::DefaultCalculateLayerBoundsFlags | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask;
 #if HAVE(COMPOSITOR_FILTER_OUTSETS)
@@ -673,7 +829,13 @@
         return;
 
     removeViewportConstrainedLayer(child);
-    repaintInCompositedAncestor(child, child->compositedLayerMapping()->compositedBounds());
+
+    {
+        // FIXME: This is called from within RenderLayer::removeChild, which is called from RenderObject::RemoveChild.
+        // There's no guarantee that compositor state is up to date.
+        DisableCompositingQueryAsserts disabler;
+        repaintInCompositedAncestor(child, child->compositedLayerMapping()->compositedBounds());
+    }
 
     setCompositingParent(child, 0);
     setCompositingLayersNeedRebuild();
@@ -706,7 +868,7 @@
         boundsComputed = true;
     }
 
-    IntRect clipRect = pixelSnappedIntRect(layer->backgroundClipRect(ClipRectsContext(rootRenderLayer(), 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
+    IntRect clipRect = pixelSnappedIntRect(layer->clipper().backgroundClipRect(ClipRectsContext(rootRenderLayer(), AbsoluteClipRects)).rect());
     clipRect.intersect(layerBounds);
     overlapMap.add(layer, clipRect);
 }
@@ -745,7 +907,7 @@
 //      must be compositing so that its contents render over that child.
 //      This implies that its positive z-index children must also be compositing.
 //
-void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer* layer, OverlapMap* overlapMap, CompositingRecursionData& currentRecursionData, bool& layersChanged, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants)
+void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer* layer, OverlapMap* overlapMap, CompositingRecursionData& currentRecursionData, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants)
 {
     layer->stackingNode()->updateLayerListsIfNeeded();
 
@@ -769,17 +931,15 @@
     if (currentRecursionData.m_compositingAncestor && currentRecursionData.m_compositingAncestor->renderer()->isVideo())
         directReasons |= CompositingReasonLayerForVideoOverlay;
 
-    if (canBeComposited(layer)) {
+    if (canBeComposited(layer))
         reasonsToComposite |= directReasons;
-        reasonsToComposite |= (inCompositingMode() && layer->isRootLayer()) ? CompositingReasonRoot : CompositingReasonNone;
-    }
 
     // Next, accumulate reasons related to overlap.
     // If overlap testing is used, this reason will be overridden. If overlap testing is not
     // used, we must assume we overlap if there is anything composited behind us in paint-order.
     CompositingReasons overlapCompositingReason = currentRecursionData.m_subtreeIsCompositing ? CompositingReasonAssumedOverlap : CompositingReasonNone;
 
-    if (rootRenderLayer()->compositorDrivenAcceleratedScrollingEnabled()) {
+    if (m_renderView->compositorDrivenAcceleratedScrollingEnabled()) {
         Vector<size_t> unclippedDescendantsToRemove;
         for (size_t i = 0; i < unclippedDescendants.size(); i++) {
             RenderLayer* unclippedDescendant = unclippedDescendants.at(i);
@@ -807,7 +967,7 @@
     bool haveComputedBounds = false;
     IntRect absBounds;
     // If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map.
-    if (overlapMap && !overlapMap->isEmpty() && currentRecursionData.m_testingOverlap && !requiresCompositing(directReasons)) {
+    if (overlapMap && !overlapMap->isEmpty() && currentRecursionData.m_testingOverlap && !requiresCompositingOrSquashing(directReasons)) {
         // If we're testing for overlap, we only need to composite if we overlap something that is already composited.
         absBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(layer->overlapBounds()));
 
@@ -820,14 +980,23 @@
 
     reasonsToComposite |= overlapCompositingReason;
 
+    // If the layer is squashable, but would scroll differently than the
+    // most recent backing that it would squash onto, then don't squash it.
+    // Note that this happens before we know all possible compositing reasons
+    // for this layer, but it's OK because we're just forcing the layer conservatively
+    // to be separately composited rather than squashed, anyway.
+    if (currentRecursionData.m_mostRecentCompositedLayer && requiresSquashing(reasonsToComposite)
+        && layer->scrollsWithRespectTo(currentRecursionData.m_mostRecentCompositedLayer))
+        reasonsToComposite |= CompositingReasonOverlapsWithoutSquashingTarget;
+
     // The children of this layer don't need to composite, unless there is
     // a compositing layer among them, so start by inheriting the compositing
     // ancestor with m_subtreeIsCompositing set to false.
     CompositingRecursionData childRecursionData(currentRecursionData);
     childRecursionData.m_subtreeIsCompositing = false;
 
-    bool willBeComposited = canBeComposited(layer) && requiresCompositing(reasonsToComposite);
-    if (willBeComposited) {
+    bool willBeCompositedOrSquashed = canBeComposited(layer) && requiresCompositingOrSquashing(reasonsToComposite);
+    if (willBeCompositedOrSquashed) {
         // Tell the parent it has compositing descendants.
         currentRecursionData.m_subtreeIsCompositing = true;
         // This layer now acts as the ancestor for kids.
@@ -853,18 +1022,18 @@
     if (layer->stackingNode()->isStackingContainer()) {
         RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
         while (RenderLayerStackingNode* curNode = iterator.next()) {
-            computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
+            computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, anyDescendantHas3DTransform, unclippedDescendants);
 
             // If we have to make a layer for this child, make one now so we can have a contents layer
             // (since we need to ensure that the -ve z-order child renders underneath our contents).
             if (childRecursionData.m_subtreeIsCompositing) {
                 reasonsToComposite |= CompositingReasonNegativeZIndexChildren;
 
-                if (!willBeComposited) {
+                if (!willBeCompositedOrSquashed) {
                     // make layer compositing
                     childRecursionData.m_compositingAncestor = layer;
                     overlapMap->beginNewOverlapTestingContext();
-                    willBeComposited = true;
+                    willBeCompositedOrSquashed = true;
                     willHaveForegroundLayer = true;
 
                     // FIXME: temporary solution for the first negative z-index composited child:
@@ -885,7 +1054,7 @@
     }
 
     if (overlapMap && willHaveForegroundLayer) {
-        ASSERT(willBeComposited);
+        ASSERT(willBeCompositedOrSquashed);
         // A foreground layer effectively is a new backing for all subsequent children, so
         // we don't need to test for overlap with anything behind this. So, we can finish
         // the previous context that was accumulating rects for the negative z-index
@@ -897,16 +1066,23 @@
         childRecursionData.m_testingOverlap = true;
     }
 
+    if (requiresCompositing(reasonsToComposite)) {
+        currentRecursionData.m_mostRecentCompositedLayer = layer;
+        childRecursionData.m_mostRecentCompositedLayer = layer;
+    }
+
     RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
     while (RenderLayerStackingNode* curNode = iterator.next())
-        computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
+        computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, anyDescendantHas3DTransform, unclippedDescendants);
+
+    currentRecursionData.m_mostRecentCompositedLayer = childRecursionData.m_mostRecentCompositedLayer;
 
     // Now that the subtree has been traversed, we can check for compositing reasons that depended on the state of the subtree.
 
     // If we entered compositing mode during the recursion, the root will also need to be composited (as long as accelerated compositing is enabled).
     if (layer->isRootLayer()) {
         if (inCompositingMode() && m_hasAcceleratedCompositing)
-            willBeComposited = true;
+            willBeCompositedOrSquashed = true;
     }
 
     // All layers (even ones that aren't being composited) need to get added to
@@ -925,7 +1101,7 @@
     // Now check for reasons to become composited that depend on the state of descendant layers.
     CompositingReasons subtreeCompositingReasons = subtreeReasonsForCompositing(layer->renderer(), childRecursionData.m_subtreeIsCompositing, anyDescendantHas3DTransform);
     reasonsToComposite |= subtreeCompositingReasons;
-    if (!willBeComposited && canBeComposited(layer) && requiresCompositing(subtreeCompositingReasons)) {
+    if (!willBeCompositedOrSquashed && canBeComposited(layer) && requiresCompositingOrSquashing(subtreeCompositingReasons)) {
         childRecursionData.m_compositingAncestor = layer;
         if (overlapMap) {
             // FIXME: this context push is effectively a no-op but needs to exist for
@@ -934,13 +1110,13 @@
             overlapMap->beginNewOverlapTestingContext();
             addToOverlapMapRecursive(*overlapMap, layer);
         }
-        willBeComposited = true;
+        willBeCompositedOrSquashed = true;
     }
 
     // If the original layer is composited, the reflection needs to be, too.
     if (layer->reflectionInfo()) {
         // FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
-        CompositingReasons reflectionCompositingReason = willBeComposited ? CompositingReasonReflectionOfCompositedParent : CompositingReasonNone;
+        CompositingReasons reflectionCompositingReason = willBeCompositedOrSquashed ? CompositingReasonReflectionOfCompositedParent : CompositingReasonNone;
         layer->reflectionInfo()->reflectionLayer()->setCompositingReasons(layer->reflectionInfo()->reflectionLayer()->compositingReasons() | reflectionCompositingReason);
     }
 
@@ -948,7 +1124,7 @@
     if (childRecursionData.m_subtreeIsCompositing)
         currentRecursionData.m_subtreeIsCompositing = true;
 
-    if (willBeComposited && layer->hasBlendMode())
+    if (willBeCompositedOrSquashed && layer->blendInfo().hasBlendMode())
         currentRecursionData.m_hasUnisolatedCompositedBlendingDescendant = true;
 
     // Set the flag to say that this SC has compositing children.
@@ -964,35 +1140,100 @@
     if (overlapMap && childRecursionData.m_compositingAncestor == layer && !layer->isRootLayer())
         overlapMap->finishCurrentOverlapTestingContext();
 
-    // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
-    // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
-    // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
-    // FIXME: hasAnyAdditionalCompositedLayers() code seems fishy. We need to make root layer logic more obvious.
-    if (layer->isRootLayer() && !childRecursionData.m_subtreeIsCompositing && !requiresCompositing(directReasons) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
-        enableCompositingMode(false);
-        willBeComposited = false;
-        reasonsToComposite = CompositingReasonNone;
+    if (layer->isRootLayer()) {
+        // The root layer needs to be composited if anything else in the tree is composited.
+        // Otherwise, we can disable compositing entirely.
+        if (childRecursionData.m_subtreeIsCompositing || requiresCompositingOrSquashing(reasonsToComposite) || m_forceCompositingMode) {
+            willBeCompositedOrSquashed = true;
+            reasonsToComposite |= CompositingReasonRoot;
+        } else {
+            enableCompositingMode(false);
+            willBeCompositedOrSquashed = false;
+            reasonsToComposite = CompositingReasonNone;
+        }
     }
 
+    if (requiresCompositing(reasonsToComposite))
+        currentRecursionData.m_mostRecentCompositedLayer = layer;
+
     // At this point we have finished collecting all reasons to composite this layer.
     layer->setCompositingReasons(reasonsToComposite);
 
-    if (!willBeComposited && layer->parent())
+    if (!willBeCompositedOrSquashed && layer->parent())
         layer->parent()->setHasNonCompositedChild(true);
 
-    // Allocate or deallocate the compositedLayerMapping now, so that we can know the layer's compositing state reliably during tree traversal in rebuildCompositingLayerTree().
-    if (allocateOrClearCompositedLayerMapping(layer))
-        layersChanged = true;
-
-    if (layer->reflectionInfo() && updateLayerCompositingState(layer->reflectionInfo()->reflectionLayer()))
-        layersChanged = true;
-
     descendantHas3DTransform |= anyDescendantHas3DTransform || layer->has3DTransform();
 
     if (overlapMap)
         overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
 }
 
+void RenderLayerCompositor::SquashingState::updateSquashingStateForNewMapping(CompositedLayerMappingPtr newCompositedLayerMapping, bool hasNewCompositedLayerMapping, IntPoint newOffsetFromAbsoluteForSquashingCLM)
+{
+    // The most recent backing is done accumulating any more squashing layers.
+    if (hasMostRecentMapping)
+        mostRecentMapping->finishAccumulatingSquashingLayers(nextSquashedLayerIndex);
+
+    nextSquashedLayerIndex = 0;
+    mostRecentMapping = newCompositedLayerMapping;
+    hasMostRecentMapping = hasNewCompositedLayerMapping;
+    offsetFromAbsoluteForSquashingCLM = newOffsetFromAbsoluteForSquashingCLM;
+}
+
+void RenderLayerCompositor::assignLayersToBackings(RenderLayer* updateRoot, bool& layersChanged)
+{
+    SquashingState squashingState;
+    assignLayersToBackingsInternal(updateRoot, squashingState, layersChanged);
+    if (squashingState.hasMostRecentMapping)
+        squashingState.mostRecentMapping->finishAccumulatingSquashingLayers(squashingState.nextSquashedLayerIndex);
+}
+
+void RenderLayerCompositor::assignLayersToBackingsForReflectionLayer(RenderLayer* reflectionLayer, bool& layersChanged)
+{
+    if (computeCompositedLayerUpdate(reflectionLayer) != NoCompositingStateChange) {
+        layersChanged = true;
+        allocateOrClearCompositedLayerMapping(reflectionLayer);
+    }
+    updateDirectCompositingReasons(reflectionLayer);
+    if (reflectionLayer->hasCompositedLayerMapping())
+        reflectionLayer->compositedLayerMapping()->updateGraphicsLayerConfiguration();
+}
+
+void RenderLayerCompositor::assignLayersToBackingsInternal(RenderLayer* layer, SquashingState& squashingState, bool& layersChanged)
+{
+    if (allocateOrClearCompositedLayerMapping(layer))
+        layersChanged = true;
+
+    // FIXME: special-casing reflection layers here is not right.
+    if (layer->reflectionInfo())
+        assignLayersToBackingsForReflectionLayer(layer->reflectionInfo()->reflectionLayer(), layersChanged);
+
+    // Add this layer to a squashing backing if needed.
+    if (layerSquashingEnabled()) {
+        if (updateSquashingAssignment(layer, squashingState))
+            layersChanged = true;
+    }
+
+    if (layer->stackingNode()->isStackingContainer()) {
+        RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
+        while (RenderLayerStackingNode* curNode = iterator.next())
+            assignLayersToBackingsInternal(curNode->layer(), squashingState, layersChanged);
+    }
+
+    if (layerSquashingEnabled()) {
+        // At this point, if the layer is to be "separately" composited, then its backing becomes the most recent in paint-order.
+        if (layer->compositingState() == PaintsIntoOwnBacking || layer->compositingState() == HasOwnBackingButPaintsIntoAncestor) {
+            ASSERT(!requiresSquashing(layer->compositingReasons()));
+            IntPoint offsetFromAbsoluteForSquashingCLM = computeOffsetFromAbsolute(layer);
+            squashingState.updateSquashingStateForNewMapping(layer->compositedLayerMapping(), layer->hasCompositedLayerMapping(), offsetFromAbsoluteForSquashingCLM);
+        }
+    }
+
+    RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
+    while (RenderLayerStackingNode* curNode = iterator.next())
+        assignLayersToBackingsInternal(curNode->layer(), squashingState, layersChanged);
+}
+
 void RenderLayerCompositor::setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer)
 {
     ASSERT(!parentLayer || childLayer->ancestorCompositingLayer() == parentLayer);
@@ -1030,6 +1271,34 @@
     return o->supportsAcceleratedRendering();
 }
 
+void RenderLayerCompositor::updateGraphicsLayersMappedToRenderLayer(RenderLayer* layer)
+{
+    if (!layer->hasCompositedLayerMapping())
+        return;
+
+    CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
+
+    // Note carefully: here we assume that the compositing state of all descendants have been updated already,
+    // so it is legitimate to compute and cache the composited bounds for this layer.
+    compositedLayerMapping->updateCompositedBounds();
+
+    if (layer->reflectionInfo()) {
+        RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
+        ASSERT(reflectionLayer);
+        if (reflectionLayer->hasCompositedLayerMapping())
+            reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
+    }
+
+    compositedLayerMapping->updateGraphicsLayerConfiguration();
+    compositedLayerMapping->updateGraphicsLayerGeometry();
+
+    if (!layer->parent())
+        updateRootLayerPosition();
+
+    if (compositedLayerMapping->hasUnpositionedOverflowControlsLayers())
+        layer->scrollableArea()->positionOverflowControls();
+}
+
 void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer, int depth)
 {
     // Make the layer compositing if necessary, and set up clipping and content layers.
@@ -1037,6 +1306,7 @@
     // have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
 
     layer->stackingNode()->updateLayerListsIfNeeded();
+    layer->update3dRenderingContext();
 
     // Used for gathering UMA data about the effect on memory usage of promoting all layers
     // that have a webkit-transition on opacity or transform and intersect the viewport.
@@ -1050,26 +1320,11 @@
 
     const bool hasCompositedLayerMapping = layer->hasCompositedLayerMapping();
     CompositedLayerMappingPtr currentCompositedLayerMapping = layer->compositedLayerMapping();
+
+    updateGraphicsLayersMappedToRenderLayer(layer);
+
+    // Grab some stats for histograms.
     if (hasCompositedLayerMapping) {
-        // The compositing state of all our children has been updated already, so now
-        // we can compute and cache the composited bounds for this layer.
-        currentCompositedLayerMapping->updateCompositedBounds();
-
-        if (layer->reflectionInfo()) {
-            RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
-            if (reflectionLayer->hasCompositedLayerMapping())
-                reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
-        }
-
-        currentCompositedLayerMapping->updateGraphicsLayerConfiguration();
-        currentCompositedLayerMapping->updateGraphicsLayerGeometry();
-
-        if (!layer->parent())
-            updateRootLayerPosition();
-
-        if (currentCompositedLayerMapping->hasUnpositionedOverflowControlsLayers())
-            layer->scrollableArea()->positionOverflowControls();
-
         pixelsWithoutPromotingAllTransitions += layer->size().height() * layer->size().width();
     } else {
         if ((layer->renderer()->style()->transitionForProperty(CSSPropertyOpacity) ||
@@ -1189,15 +1444,6 @@
     blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
         ScrolledMainFrameBucket,
         AcceleratedFixedRootBackgroundHistogramMax);
-
-    if (!m_renderView->rootBackgroundIsEntirelyFixed())
-        return;
-
-    blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
-        !!fixedRootBackgroundLayer()
-            ? ScrolledMainFrameWithAcceleratedFixedRootBackground
-            : ScrolledMainFrameWithUnacceleratedFixedRootBackground,
-        AcceleratedFixedRootBackgroundHistogramMax);
 }
 
 void RenderLayerCompositor::frameViewDidLayout()
@@ -1242,7 +1488,7 @@
 String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
 {
     // Before dumping the layer tree, finish any pending compositing update.
-    updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
+    updateCompositingLayers();
 
     if (!m_rootContentLayer)
         return String();
@@ -1300,24 +1546,7 @@
 // This just updates layer geometry without changing the hierarchy.
 void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer)
 {
-    if (layer->hasCompositedLayerMapping()) {
-        CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
-        // The compositing state of all our children has been updated already, so now
-        // we can compute and cache the composited bounds for this layer.
-        compositedLayerMapping->updateCompositedBounds();
-
-        if (layer->reflectionInfo()) {
-            RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
-            if (reflectionLayer->hasCompositedLayerMapping())
-                reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
-        }
-
-        compositedLayerMapping->updateGraphicsLayerConfiguration();
-        compositedLayerMapping->updateGraphicsLayerGeometry();
-
-        if (!layer->parent())
-            updateRootLayerPosition();
-    }
+    updateGraphicsLayersMappedToRenderLayer(layer);
 
 #if !ASSERT_DISABLED
     LayerListMutationDetector mutationChecker(layer->stackingNode());
@@ -1415,6 +1644,11 @@
     return m_scrollLayer.get();
 }
 
+GraphicsLayer* RenderLayerCompositor::containerLayer() const
+{
+    return m_containerLayer.get();
+}
+
 void RenderLayerCompositor::setIsInWindow(bool isInWindow)
 {
     if (!inCompositingMode())
@@ -1484,12 +1718,15 @@
     layer->setCompositingReasons(layerReasons);
 }
 
-bool RenderLayerCompositor::needsToBeComposited(const RenderLayer* layer) const
+bool RenderLayerCompositor::needsOwnBacking(const RenderLayer* layer) const
 {
     if (!canBeComposited(layer))
         return false;
 
-    return requiresCompositing(layer->compositingReasons()) || (inCompositingMode() && layer->isRootLayer());
+    // If squashing is disabled, then layers that would have been squashed should just be separately composited.
+    bool needsOwnBackingForDisabledSquashing = !layerSquashingEnabled() && requiresSquashing(layer->compositingReasons());
+
+    return requiresCompositing(layer->compositingReasons()) || needsOwnBackingForDisabledSquashing || (inCompositingMode() && layer->isRootLayer());
 }
 
 bool RenderLayerCompositor::canBeComposited(const RenderLayer* layer) const
@@ -1554,6 +1791,7 @@
     if (!layer->hasCompositedLayerMapping() || !layer->parent())
         return false;
 
+    // FIXME: need to double-check if semantics of ancestorCompositingLayer() work correctly here?
     const RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
     if (!compositingAncestor)
         return false;
@@ -1575,7 +1813,7 @@
     if (!computeClipRoot || computeClipRoot == layer)
         return false;
 
-    return layer->backgroundClipRect(ClipRectsContext(computeClipRoot, 0, TemporaryClipRects)).rect() != PaintInfo::infiniteRect(); // FIXME: Incorrect for CSS regions.
+    return layer->clipper().backgroundClipRect(ClipRectsContext(computeClipRoot, TemporaryClipRects)).rect() != PaintInfo::infiniteRect();
 }
 
 // Return true if the given layer is a stacking context and has compositing child
@@ -1673,6 +1911,9 @@
     if (!frameRenderer->requiresAcceleratedCompositing())
         return false;
 
+    if (frameRenderer->node() && frameRenderer->node()->isFrameOwnerElement() && toHTMLFrameOwnerElement(frameRenderer->node())->contentFrame() && toHTMLFrameOwnerElement(frameRenderer->node())->contentFrame()->remotePlatformLayer())
+        return true;
+
     // FIXME: this seems bogus. If we don't know the layout position/size of the frame yet, wouldn't that be handled elsehwere?
     m_needsToRecomputeCompositingRequirements = true;
 
@@ -1699,9 +1940,6 @@
     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
         return false;
 
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-        return renderer->animation().isRunningAcceleratableAnimationOnRenderer(renderer);
-
     return shouldCompositeForActiveAnimations(*renderer);
 }
 
@@ -1785,7 +2023,25 @@
 
 bool RenderLayerCompositor::requiresCompositingForOutOfFlowClipping(const RenderLayer* layer) const
 {
-    return layer->compositorDrivenAcceleratedScrollingEnabled() && layer->isUnclippedDescendant();
+    return m_renderView->compositorDrivenAcceleratedScrollingEnabled() && layer->isUnclippedDescendant();
+}
+
+static bool isViewportConstrainedFixedOrStickyLayer(const RenderLayer* layer)
+{
+    if (layer->renderer()->isStickyPositioned())
+        return !layer->enclosingOverflowClipLayer(ExcludeSelf);
+
+    if (layer->renderer()->style()->position() != FixedPosition)
+        return false;
+
+    for (const RenderLayerStackingNode* stackingContainer = layer->stackingNode(); stackingContainer;
+        stackingContainer = stackingContainer->ancestorStackingContainerNode()) {
+        if (stackingContainer->layer()->compositingState() != NotComposited
+            && stackingContainer->layer()->renderer()->style()->position() == FixedPosition)
+            return false;
+    }
+
+    return true;
 }
 
 bool RenderLayerCompositor::requiresCompositingForPosition(RenderObject* renderer, const RenderLayer* layer, RenderLayer::ViewportConstrainedNotCompositedReason* viewportConstrainedNotCompositedReason) const
@@ -1812,7 +2068,7 @@
     }
 
     if (isSticky)
-        return true;
+        return isViewportConstrainedFixedOrStickyLayer(layer);
 
     RenderObject* container = renderer->container();
     // If the renderer is not hooked up yet then we have to wait until it is.
@@ -1898,8 +2154,6 @@
 {
     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
         return false;
-    if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-        return renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
     return hasActiveAnimations(*renderer, CSSPropertyWebkitTransform);
 }
 
@@ -2000,7 +2254,7 @@
 
 void RenderLayerCompositor::setTracksRepaints(bool tracksRepaints)
 {
-    updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
+    updateCompositingLayers();
     m_isTrackingRepaints = tracksRepaints;
 }
 
@@ -2009,11 +2263,6 @@
     return m_isTrackingRepaints;
 }
 
-void RenderLayerCompositor::didCommitChangesForLayer(const GraphicsLayer*) const
-{
-    // Nothing to do here yet.
-}
-
 static bool shouldCompositeOverflowControls(FrameView* view)
 {
     if (Page* page = view->frame().page()) {
@@ -2238,9 +2487,12 @@
             break;
         }
         case RootLayerAttachedViaEnclosingFrame: {
+            HTMLFrameOwnerElement* ownerElement = m_renderView->document().ownerElement();
+            ASSERT(ownerElement);
+            DeprecatedScheduleStyleRecalcDuringCompositingUpdate marker(ownerElement->document().lifecycle());
             // The layer will get hooked up via CompositedLayerMapping::updateGraphicsLayerConfiguration()
             // for the frame's renderer in the parent document.
-            m_renderView->document().ownerElement()->scheduleLayerUpdate();
+            ownerElement->scheduleLayerUpdate();
             break;
         }
     }
@@ -2262,8 +2514,10 @@
         else
             m_rootContentLayer->removeFromParent();
 
-        if (HTMLFrameOwnerElement* ownerElement = m_renderView->document().ownerElement())
+        if (HTMLFrameOwnerElement* ownerElement = m_renderView->document().ownerElement()) {
+            DeprecatedScheduleStyleRecalcDuringCompositingUpdate marker(ownerElement->document().lifecycle());
             ownerElement->scheduleLayerUpdate();
+        }
         break;
     }
     case RootLayerAttachedViaChromeClient: {
@@ -2302,14 +2556,21 @@
     Frame& frame = m_renderView->frameView()->frame();
 
     for (Frame* child = frame.tree().firstChild(); child; child = child->tree().traverseNext(&frame)) {
-        if (child->document() && child->document()->ownerElement())
-            child->document()->ownerElement()->scheduleLayerUpdate();
+        if (!child->document())
+            continue; // FIXME: Can this happen?
+        if (HTMLFrameOwnerElement* ownerElement = child->document()->ownerElement()) {
+            DeprecatedScheduleStyleRecalcDuringCompositingUpdate marker(ownerElement->document().lifecycle());
+            ownerElement->scheduleLayerUpdate();
+        }
     }
 
     // Compositing also affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so
     // we need to schedule a style recalc in our parent document.
-    if (HTMLFrameOwnerElement* ownerElement = m_renderView->document().ownerElement())
+    if (HTMLFrameOwnerElement* ownerElement = m_renderView->document().ownerElement()) {
+        ownerElement->document().renderView()->compositor()->setNeedsToRecomputeCompositingRequirements();
+        DeprecatedScheduleStyleRecalcDuringCompositingUpdate marker(ownerElement->document().lifecycle());
         ownerElement->scheduleLayerUpdate();
+    }
 }
 
 bool RenderLayerCompositor::layerHas3DContent(const RenderLayer* layer) const
@@ -2338,25 +2599,9 @@
     return false;
 }
 
-static bool isRootmostFixedOrStickyLayer(RenderLayer* layer)
-{
-    if (layer->renderer()->isStickyPositioned())
-        return true;
-
-    if (layer->renderer()->style()->position() != FixedPosition)
-        return false;
-
-    for (RenderLayerStackingNode* stackingContainerNode = layer->stackingNode()->ancestorStackingContainerNode(); stackingContainerNode; stackingContainerNode = stackingContainerNode->ancestorStackingContainerNode()) {
-        if (stackingContainerNode->layer()->hasCompositedLayerMapping() && stackingContainerNode->layer()->renderer()->style()->position() == FixedPosition)
-            return false;
-    }
-
-    return true;
-}
-
 void RenderLayerCompositor::updateViewportConstraintStatus(RenderLayer* layer)
 {
-    if (isRootmostFixedOrStickyLayer(layer))
+    if (isViewportConstrainedFixedOrStickyLayer(layer))
         addViewportConstrainedLayer(layer);
     else
         removeViewportConstrainedLayer(layer);
@@ -2416,6 +2661,8 @@
 StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportConstraints(RenderLayer* layer) const
 {
     ASSERT(layer->hasCompositedLayerMapping());
+    // We should never get here for stickies constrained by an enclosing clipping layer.
+    ASSERT(!layer->enclosingOverflowClipLayer(ExcludeSelf));
 
     FrameView* frameView = m_renderView->frameView();
     LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
@@ -2454,6 +2701,11 @@
     return m_renderView->frameView()->frame().page();
 }
 
+DocumentLifecycle& RenderLayerCompositor::lifecycle() const
+{
+    return m_renderView->document().lifecycle();
+}
+
 String RenderLayerCompositor::debugName(const GraphicsLayer* graphicsLayer)
 {
     String name;
diff --git a/Source/core/rendering/RenderLayerCompositor.h b/Source/core/rendering/RenderLayerCompositor.h
index 43c28df..dcac830 100644
--- a/Source/core/rendering/RenderLayerCompositor.h
+++ b/Source/core/rendering/RenderLayerCompositor.h
@@ -48,7 +48,6 @@
     CompositingUpdateAfterLayout,
     CompositingUpdateOnScroll,
     CompositingUpdateOnCompositedScroll,
-    CompositingUpdateFinishAllDeferredWork
 };
 
 // RenderLayerCompositor manages the hierarchy of
@@ -58,11 +57,11 @@
 //
 // There is one RenderLayerCompositor per RenderView.
 
-class RenderLayerCompositor : public GraphicsLayerClient {
+class RenderLayerCompositor FINAL : public GraphicsLayerClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit RenderLayerCompositor(RenderView*);
-    ~RenderLayerCompositor();
+    virtual ~RenderLayerCompositor();
 
     // Return true if this RenderView is in "compositing mode" (i.e. has one or more
     // composited RenderLayers)
@@ -75,7 +74,7 @@
 
     // Returns true if the accelerated compositing is enabled
     bool hasAcceleratedCompositing() const { return m_hasAcceleratedCompositing; }
-    bool isLayerSquashingEnabled() const;
+    bool layerSquashingEnabled() const;
 
     bool canRender3DTransforms() const;
 
@@ -87,20 +86,21 @@
     void setCompositingLayersNeedRebuild(bool needRebuild = true);
     bool compositingLayersNeedRebuild() const { return m_compositingLayersNeedRebuild; }
 
-    // Called when something outside WebKit affects the visible rect (e.g. delegated scrolling). Might schedule a layer flush.
-    void didChangeVisibleRect();
-
     // Updating properties required for determining if compositing is necessary.
     void updateCompositingRequirementsState();
     void setNeedsUpdateCompositingRequirementsState() { m_needsUpdateCompositingRequirementsState = true; }
 
+    // Used to indicate that a compositing update will be needed for the next frame that gets drawn.
+    void setNeedsCompositingUpdate(CompositingUpdateType);
+
     // Main entry point for a full update. As needed, this function will compute compositing requirements,
     // rebuild the composited layer tree, and/or update all the properties assocaited with each layer of the
     // composited layer tree.
-    void updateCompositingLayers(CompositingUpdateType);
+    void updateCompositingLayers();
 
-    // Update the compositing state of the given layer. Returns true if that state changed.
-    bool updateLayerCompositingState(RenderLayer*);
+    // Update the compositing dirty bits, based on the compositing-impacting properties of the layer.
+    // (At the moment, it also has some legacy compatibility hacks.)
+    void updateLayerCompositingState(RenderLayer*);
 
     // Update the geometry for compositing children of compositingAncestor.
     void updateCompositingDescendantGeometry(RenderLayerStackingNode* compositingAncestor, RenderLayer*, bool compositedChildrenOnly);
@@ -119,7 +119,7 @@
 
     // Return the bounding box required for compositing layer and its childern, relative to ancestorLayer.
     // If layerBoundingBox is not 0, on return it contains the bounding box of this layer only.
-    IntRect calculateCompositedBounds(const RenderLayer*, const RenderLayer* ancestorLayer) const;
+    LayoutRect calculateCompositedBounds(const RenderLayer*, const RenderLayer* ancestorLayer) const;
 
     // Repaint the appropriate layers when the given RenderLayer starts or stops being composited.
     void repaintOnCompositingChange(RenderLayer*);
@@ -139,6 +139,7 @@
     RenderLayer* rootRenderLayer() const;
     GraphicsLayer* rootGraphicsLayer() const;
     GraphicsLayer* scrollLayer() const;
+    GraphicsLayer* containerLayer() const;
 
     enum RootLayerAttachment {
         RootLayerUnattached,
@@ -154,9 +155,6 @@
 
     void clearMappingForAllRenderLayers();
 
-    void layerBecameComposited(const RenderLayer*) { ++m_compositedLayerCount; }
-    void layerBecameNonComposited(const RenderLayer*);
-
     // Use by RenderVideo to ask if it should try to use accelerated compositing.
     bool canAccelerateVideoRendering(RenderVideo*) const;
 
@@ -180,8 +178,6 @@
 
     String layerTreeAsText(LayerTreeFlags);
 
-    virtual void didCommitChangesForLayer(const GraphicsLayer*) const OVERRIDE;
-
     GraphicsLayer* layerForHorizontalScrollbar() const { return m_layerForHorizontalScrollbar.get(); }
     GraphicsLayer* layerForVerticalScrollbar() const { return m_layerForVerticalScrollbar.get(); }
     GraphicsLayer* layerForScrollCorner() const { return m_layerForScrollCorner.get(); }
@@ -202,14 +198,47 @@
 private:
     class OverlapMap;
 
+    enum CompositingStateTransitionType {
+        NoCompositingStateChange,
+        AllocateOwnCompositedLayerMapping,
+        RemoveOwnCompositedLayerMapping,
+        PutInSquashingLayer,
+        RemoveFromSquashingLayer
+    };
+
+    struct SquashingState {
+        SquashingState()
+            : mostRecentMapping(0)
+            , hasMostRecentMapping(false)
+            , nextSquashedLayerIndex(0) { }
+
+        void updateSquashingStateForNewMapping(CompositedLayerMappingPtr, bool hasNewCompositedLayerMapping, IntPoint newOffsetFromAbsoluteForSquashingCLM);
+
+        // The most recent composited backing that the layer should squash onto if needed.
+        CompositedLayerMappingPtr mostRecentMapping;
+        bool hasMostRecentMapping;
+
+        // Absolute coordinates of the compositedLayerMapping's owning layer. This is used for computing the correct
+        // positions of renderlayers when they paint into the squashing layer.
+        IntPoint offsetFromAbsoluteForSquashingCLM;
+
+        // Counter that tracks what index the next RenderLayer would be if it gets squashed to the current squashing layer.
+        size_t nextSquashedLayerIndex;
+    };
+
+    CompositingStateTransitionType computeCompositedLayerUpdate(const RenderLayer*);
+    // Make updates to the layer based on viewport-constrained properties such as position:fixed. This can in turn affect
+    // compositing.
+    bool updateLayerIfViewportConstrained(RenderLayer*);
+
     // GraphicsLayerClient implementation
-    virtual void notifyAnimationStarted(const GraphicsLayer*, double) OVERRIDE { }
+    virtual void notifyAnimationStarted(const GraphicsLayer*, double, double) OVERRIDE { }
     virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect&) OVERRIDE;
 
     virtual bool isTrackingRepaints() const OVERRIDE;
 
-    // Whether the given RL needs a compositing layer.
-    bool needsToBeComposited(const RenderLayer*) const;
+    // Whether the given RL needs to paint into its own separate backing (and hence would need its own CompositedLayerMapping).
+    bool needsOwnBacking(const RenderLayer*) const;
     // Whether the layer could ever be composited.
     bool canBeComposited(const RenderLayer*) const;
 
@@ -223,6 +252,7 @@
 
     // Make or destroy the CompositedLayerMapping for this layer; returns true if the compositedLayerMapping changed.
     bool allocateOrClearCompositedLayerMapping(RenderLayer*);
+    bool updateSquashingAssignment(RenderLayer*, SquashingState&);
 
     void clearMappingForRenderLayerIncludingDescendants(RenderLayer*);
 
@@ -237,7 +267,15 @@
     static void finishCompositingUpdateForFrameTree(Frame*);
 
     // Returns true if any layer's compositing changed
-    void computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer*, OverlapMap*, struct CompositingRecursionData&, bool& layersChanged, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants);
+    void computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer*, OverlapMap*, struct CompositingRecursionData&, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants);
+
+    // Defines which RenderLayers will paint into which composited backings, by allocating and destroying CompositedLayerMappings as needed.
+    void assignLayersToBackings(RenderLayer*, bool& layersChanged);
+    void assignLayersToBackingsInternal(RenderLayer*, SquashingState&, bool& layersChanged);
+
+    // Allocates, sets up hierarchy, and sets appropriate properties for the GraphicsLayers that correspond to a given
+    // composited RenderLayer. Does nothing if the given RenderLayer does not have a CompositedLayerMapping.
+    void updateGraphicsLayersMappedToRenderLayer(RenderLayer*);
 
     // Recurses down the tree, parenting descendant compositing layers and collecting an array of child layers for the current compositing layer.
     void rebuildCompositingLayerTree(RenderLayer*, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, int depth);
@@ -300,14 +338,18 @@
     bool requiresOverhangLayers() const;
 #endif
 
+    void applyUpdateLayerCompositingStateChickenEggHacks(RenderLayer*, CompositingStateTransitionType compositedLayerUpdate);
+    void assignLayersToBackingsForReflectionLayer(RenderLayer* reflectionLayer, bool& layersChanged);
+
 private:
+    DocumentLifecycle& lifecycle() const;
+
     RenderView* m_renderView;
     OwnPtr<GraphicsLayer> m_rootContentLayer;
 
     bool m_hasAcceleratedCompositing;
     ChromeClient::CompositingTriggerFlags m_compositingTriggers;
 
-    int m_compositedLayerCount;
     bool m_showRepaintCounter;
 
     // FIXME: This should absolutely not be mutable.
diff --git a/Source/core/rendering/RenderLayerFilterInfo.cpp b/Source/core/rendering/RenderLayerFilterInfo.cpp
index 600ced9..bfb25ee 100644
--- a/Source/core/rendering/RenderLayerFilterInfo.cpp
+++ b/Source/core/rendering/RenderLayerFilterInfo.cpp
@@ -39,8 +39,6 @@
 #include "core/svg/SVGFilterElement.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "core/svg/graphics/filters/SVGFilter.h"
-#include "platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "platform/graphics/filters/custom/CustomFilterProgram.h"
 
 namespace WebCore {
 
@@ -95,7 +93,6 @@
 
 RenderLayerFilterInfo::~RenderLayerFilterInfo()
 {
-    removeCustomFilterClients();
     removeReferenceFilterClients();
 }
 
@@ -156,39 +153,5 @@
     m_internalSVGReferences.clear();
 }
 
-void RenderLayerFilterInfo::notifyCustomFilterProgramLoaded(CustomFilterProgram*)
-{
-    RenderObject* renderer = m_layer->renderer();
-    toElement(renderer->node())->scheduleLayerUpdate();
-    renderer->repaint();
-}
-
-void RenderLayerFilterInfo::updateCustomFilterClients(const FilterOperations& operations)
-{
-    if (!operations.size()) {
-        removeCustomFilterClients();
-        return;
-    }
-    CustomFilterProgramList cachedCustomFilterPrograms;
-    for (size_t i = 0; i < operations.size(); ++i) {
-        const FilterOperation* filterOperation = operations.at(i);
-        if (filterOperation->type() != FilterOperation::CUSTOM)
-            continue;
-        RefPtr<CustomFilterProgram> program = toCustomFilterOperation(filterOperation)->program();
-        cachedCustomFilterPrograms.append(program);
-        program->addClient(this);
-    }
-    // Remove the old clients here, after we've added the new ones, so that we don't flicker if some shaders are unchanged.
-    removeCustomFilterClients();
-    m_cachedCustomFilterPrograms.swap(cachedCustomFilterPrograms);
-}
-
-void RenderLayerFilterInfo::removeCustomFilterClients()
-{
-    for (size_t i = 0; i < m_cachedCustomFilterPrograms.size(); ++i)
-        m_cachedCustomFilterPrograms.at(i)->removeClient(this);
-    m_cachedCustomFilterPrograms.clear();
-}
-
 } // namespace WebCore
 
diff --git a/Source/core/rendering/RenderLayerFilterInfo.h b/Source/core/rendering/RenderLayerFilterInfo.h
index f982008..c60e35f 100644
--- a/Source/core/rendering/RenderLayerFilterInfo.h
+++ b/Source/core/rendering/RenderLayerFilterInfo.h
@@ -34,7 +34,6 @@
 #include "core/fetch/DocumentResource.h"
 #include "platform/geometry/LayoutRect.h"
 #include "platform/graphics/filters/FilterOperation.h"
-#include "platform/graphics/filters/custom/CustomFilterProgramClient.h"
 #include "wtf/HashMap.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
@@ -48,7 +47,7 @@
 
 typedef HashMap<const RenderLayer*, RenderLayerFilterInfo*> RenderLayerFilterInfoMap;
 
-class RenderLayerFilterInfo : public CustomFilterProgramClient, public DocumentResourceClient {
+class RenderLayerFilterInfo FINAL : public DocumentResourceClient {
 public:
     static RenderLayerFilterInfo* filterInfoForRenderLayer(const RenderLayer*);
     static RenderLayerFilterInfo* createFilterInfoForRenderLayerIfNeeded(RenderLayer*);
@@ -61,28 +60,19 @@
     FilterEffectRenderer* renderer() const { return m_renderer.get(); }
     void setRenderer(PassRefPtr<FilterEffectRenderer>);
 
-    // Implementation of the CustomFilterProgramClient interface.
-    virtual void notifyCustomFilterProgramLoaded(CustomFilterProgram*);
-
-    void updateCustomFilterClients(const FilterOperations&);
-    void removeCustomFilterClients();
-
     void updateReferenceFilterClients(const FilterOperations&);
-    virtual void notifyFinished(Resource*);
+    virtual void notifyFinished(Resource*) OVERRIDE;
     void removeReferenceFilterClients();
 
 private:
     RenderLayerFilterInfo(RenderLayer*);
-    ~RenderLayerFilterInfo();
+    virtual ~RenderLayerFilterInfo();
 
     RenderLayer* m_layer;
 
     RefPtr<FilterEffectRenderer> m_renderer;
     LayoutRect m_dirtySourceRect;
 
-    typedef Vector<RefPtr<CustomFilterProgram> > CustomFilterProgramList;
-    CustomFilterProgramList m_cachedCustomFilterPrograms;
-
     static RenderLayerFilterInfoMap* s_filterMap;
     Vector<RefPtr<Element> > m_internalSVGReferences;
     Vector<ResourcePtr<DocumentResource> > m_externalSVGReferences;
diff --git a/Source/core/rendering/RenderLayerModelObject.cpp b/Source/core/rendering/RenderLayerModelObject.cpp
index f21b8d2..e0039fc 100644
--- a/Source/core/rendering/RenderLayerModelObject.cpp
+++ b/Source/core/rendering/RenderLayerModelObject.cpp
@@ -53,10 +53,10 @@
     m_layer = nullptr;
 }
 
-void RenderLayerModelObject::createLayer()
+void RenderLayerModelObject::createLayer(LayerType type)
 {
     ASSERT(!m_layer);
-    m_layer = adoptPtr(new RenderLayer(this));
+    m_layer = adoptPtr(new RenderLayer(this, type));
     setHasLayer(true);
     m_layer->insertOnlyThisLayer();
 }
@@ -141,11 +141,12 @@
     RenderObject::styleDidChange(diff, oldStyle);
     updateFromStyle();
 
-    if (requiresLayer()) {
+    LayerType type = layerTypeRequired();
+    if (type != NoLayer) {
         if (!layer() && layerCreationAllowedForSubtree()) {
             if (s_wasFloating && isFloating())
                 setChildNeedsLayout();
-            createLayer();
+            createLayer(type);
             if (parent() && !needsLayout() && containingBlock()) {
                 layer()->repainter().setRepaintStatus(NeedsFullRepaint);
                 // There is only one layer to update, it is not worth using |cachedOffset| since
@@ -164,6 +165,10 @@
     }
 
     if (layer()) {
+        // FIXME: Ideally we shouldn't need this setter but we can't easily infer an overflow-only layer
+        // from the style.
+        layer()->setIsOverflowOnlyLayer(type == OverflowClipLayer);
+
         layer()->styleChanged(diff, oldStyle);
         if (hadLayer && layer()->isSelfPaintingLayer() != layerWasSelfPainting)
             setChildNeedsLayout();
@@ -209,5 +214,10 @@
     return m_layer ? m_layer->hasCompositedLayerMapping() : false;
 }
 
+CompositedLayerMapping* RenderLayerModelObject::groupedMapping() const
+{
+    return m_layer ? m_layer->groupedMapping() : 0;
+}
+
 } // namespace WebCore
 
diff --git a/Source/core/rendering/RenderLayerModelObject.h b/Source/core/rendering/RenderLayerModelObject.h
index c19c3d2..e4d34f3 100644
--- a/Source/core/rendering/RenderLayerModelObject.h
+++ b/Source/core/rendering/RenderLayerModelObject.h
@@ -32,6 +32,12 @@
 class CompositedLayerMapping;
 class ScrollableArea;
 
+enum LayerType {
+    NoLayer,
+    OverflowClipLayer,
+    NormalLayer
+};
+
 class RenderLayerModelObject : public RenderObject {
 public:
     explicit RenderLayerModelObject(ContainerNode*);
@@ -48,7 +54,7 @@
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
     virtual void updateFromStyle() { }
 
-    virtual bool requiresLayer() const = 0;
+    virtual LayerType layerTypeRequired() const = 0;
 
     // Returns true if the background is painted opaque in the given rect.
     // The query rect is given in local coordinate system.
@@ -59,9 +65,10 @@
 
     CompositedLayerMappingPtr compositedLayerMapping() const;
     bool hasCompositedLayerMapping() const;
+    CompositedLayerMapping* groupedMapping() const;
 
 protected:
-    void createLayer();
+    void createLayer(LayerType);
 
     virtual void willBeDestroyed() OVERRIDE;
 
diff --git a/Source/core/rendering/RenderLayerRepainter.cpp b/Source/core/rendering/RenderLayerRepainter.cpp
index e6aa19e..a06d55f 100644
--- a/Source/core/rendering/RenderLayerRepainter.cpp
+++ b/Source/core/rendering/RenderLayerRepainter.cpp
@@ -59,6 +59,9 @@
 
 void RenderLayerRepainter::repaintAfterLayout(RenderGeometryMap* geometryMap, bool shouldCheckForRepaint)
 {
+    // FIXME: really, we're in the repaint phase here, and the following queries are legal.
+    // Until those states are fully fledged, I'll just disable the ASSERTS.
+    DisableCompositingQueryAsserts disabler;
     if (m_renderer->layer()->hasVisibleContent()) {
         RenderView* view = m_renderer->view();
         ASSERT(view);
@@ -155,16 +158,22 @@
 
 void RenderLayerRepainter::setBackingNeedsRepaint()
 {
-    ASSERT(m_renderer->hasCompositedLayerMapping());
-    m_renderer->compositedLayerMapping()->setContentsNeedDisplay();
+    ASSERT(m_renderer->compositingState() != NotComposited);
+
+    if (m_renderer->compositingState() == PaintsIntoGroupedBacking) {
+        // FIXME: should probably setNeedsDisplayInRect for this layer's bounds only.
+        m_renderer->groupedMapping()->squashingLayer()->setNeedsDisplay();
+    } else {
+        m_renderer->compositedLayerMapping()->setContentsNeedDisplay();
+    }
 }
 
 void RenderLayerRepainter::setBackingNeedsRepaintInRect(const LayoutRect& r)
 {
     // https://bugs.webkit.org/show_bug.cgi?id=61159 describes an unreproducible crash here,
     // so assert but check that the layer is composited.
-    ASSERT(m_renderer->hasCompositedLayerMapping());
-    if (!m_renderer->hasCompositedLayerMapping()) {
+    ASSERT(m_renderer->compositingState() != NotComposited);
+    if (m_renderer->compositingState() == NotComposited) {
         // If we're trying to repaint the placeholder document layer, propagate the
         // repaint to the native view system.
         LayoutRect absRect(r);
@@ -176,7 +185,18 @@
         if (view)
             view->repaintViewRectangle(absRect);
     } else {
-        m_renderer->compositedLayerMapping()->setContentsNeedDisplayInRect(pixelSnappedIntRect(r));
+        if (m_renderer->compositingState() == PaintsIntoGroupedBacking) {
+            // FIXME: LayoutRect rounding to IntRect is probably not a good idea.
+            IntRect offsetRect = pixelSnappedIntRect(r);
+            if (m_renderer->hasTransform())
+                offsetRect = m_renderer->layer()->transform()->mapRect(pixelSnappedIntRect(r));
+
+            offsetRect.move(-m_renderer->layer()->offsetFromSquashingLayerOrigin());
+            m_renderer->groupedMapping()->squashingLayer()->setNeedsDisplayInRect(offsetRect);
+        } else {
+            IntRect repaintRect = pixelSnappedIntRect(r.location() +  m_renderer->compositedLayerMapping()->subpixelAccumulation(), r.size());
+            m_renderer->compositedLayerMapping()->setContentsNeedDisplayInRect(repaintRect);
+        }
     }
 }
 
diff --git a/Source/core/rendering/RenderLayerScrollableArea.cpp b/Source/core/rendering/RenderLayerScrollableArea.cpp
index 0486111..0cc87c2 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.cpp
+++ b/Source/core/rendering/RenderLayerScrollableArea.cpp
@@ -56,6 +56,7 @@
 #include "core/page/Page.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/rendering/CompositedLayerMapping.h"
+#include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderScrollbar.h"
@@ -191,7 +192,27 @@
         scrollRect.move(verticalScrollbarStart(0, m_box->width()), m_box->borderTop());
     else
         scrollRect.move(horizontalScrollbarStart(0), m_box->height() - m_box->borderBottom() - scrollbar->height());
-    m_box->repaintRectangle(scrollRect);
+
+    if (scrollRect.isEmpty())
+        return;
+
+    LayoutRect repaintRect = scrollRect;
+    m_box->flipForWritingMode(repaintRect);
+
+    IntRect intRect = pixelSnappedIntRect(repaintRect);
+
+    if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && m_box->frameView()->isInPerformLayout()) {
+        if (scrollbar == m_vBar.get()) {
+            m_verticalBarDamage = intRect;
+            m_hasVerticalBarDamage = true;
+        } else {
+            m_horizontalBarDamage = intRect;
+            m_hasHorizontalBarDamage = true;
+        }
+
+    } else {
+        m_box->repaintRectangle(intRect);
+    }
 }
 
 void RenderLayerScrollableArea::invalidateScrollCornerRect(const IntRect& rect)
@@ -330,38 +351,34 @@
     setScrollOffset(toIntSize(newScrollOffset));
 
     Frame* frame = m_box->frame();
+    ASSERT(frame);
+
+    RefPtr<FrameView> frameView = m_box->frameView();
+
     InspectorInstrumentation::willScrollLayer(m_box);
 
-    RenderView* view = m_box->view();
-
-    // We should have a RenderView if we're trying to scroll.
-    ASSERT(view);
-
     // Update the positions of our child layers (if needed as only fixed layers should be impacted by a scroll).
     // We don't update compositing layers, because we need to do a deep update from the compositing ancestor.
-    bool inLayout = view ? view->frameView()->isInLayout() : false;
-    if (!inLayout) {
+    if (!frameView->isInPerformLayout()) {
         // If we're in the middle of layout, we'll just update layers once layout has finished.
         layer()->updateLayerPositionsAfterOverflowScroll();
-        if (view) {
-            // Update regions, scrolling may change the clip of a particular region.
-            view->frameView()->updateAnnotatedRegions();
-            view->updateWidgetPositions();
-        }
-
+        // Update regions, scrolling may change the clip of a particular region.
+        frameView->updateAnnotatedRegions();
+        // FIXME: We shouldn't call updateWidgetPositions() here since it might tear down the render tree,
+        // for now we just crash to avoid allowing an attacker to use after free.
+        frameView->updateWidgetPositions();
+        RELEASE_ASSERT(frameView->renderView());
         updateCompositingLayersAfterScroll();
     }
 
     RenderLayerModelObject* repaintContainer = m_box->containerForRepaint();
-    if (frame) {
-        // The caret rect needs to be invalidated after scrolling
-        frame->selection().setCaretRectNeedsUpdate();
+    // The caret rect needs to be invalidated after scrolling
+    frame->selection().setCaretRectNeedsUpdate();
 
-        FloatQuad quadForFakeMouseMoveEvent = FloatQuad(layer()->repainter().repaintRect());
-        if (repaintContainer)
-            quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
-        frame->eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
-    }
+    FloatQuad quadForFakeMouseMoveEvent = FloatQuad(layer()->repainter().repaintRect());
+    if (repaintContainer)
+        quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
+    frame->eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
 
     bool requiresRepaint = true;
 
@@ -377,8 +394,12 @@
     }
 
     // Just schedule a full repaint of our object.
-    if (view && requiresRepaint)
-        m_box->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(layer()->repainter().repaintRect()));
+    if (requiresRepaint) {
+        if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && m_box->frameView()->isInPerformLayout())
+            m_box->setShouldDoFullRepaintAfterLayout(true);
+        else
+            m_box->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(layer()->repainter().repaintRect()));
+    }
 
     // Schedule the scroll DOM event.
     if (m_box->node())
@@ -533,6 +554,8 @@
     if (m_box->style()->appearance() == ListboxPart)
         return;
 
+    LayoutRectRecorder recorder(*m_box);
+
     m_scrollDimensionsDirty = true;
     IntSize originalScrollOffset = adjustedScrollOffset();
 
@@ -574,7 +597,8 @@
         if (m_box->document().hasAnnotatedRegions())
             m_box->document().setAnnotatedRegionsDirty(true);
 
-        m_box->repaint();
+        if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+            m_box->repaint();
 
         if (m_box->style()->overflowX() == OAUTO || m_box->style()->overflowY() == OAUTO) {
             if (!m_inOverflowRelayout) {
@@ -606,9 +630,15 @@
 
     updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
 
-    // Composited scrolling may need to be enabled or disabled if the amount of overflow changed.
-    if (m_box->view() && m_box->view()->compositor()->updateLayerCompositingState(m_box->layer()))
-        m_box->view()->compositor()->setCompositingLayersNeedRebuild();
+    {
+        // FIXME: We should not be allowing repaint during layout. crbug.com/336251
+        AllowRepaintScope scoper(m_box->view()->frameView());
+
+        // FIXME: Remove incremental compositing updates after fixing the chicken/egg issues
+        // https://code.google.com/p/chromium/issues/detail?id=343756
+        DisableCompositingQueryAsserts disabler;
+        m_box->view()->compositor()->updateLayerCompositingState(m_box->layer());
+    }
 }
 
 bool RenderLayerScrollableArea::hasHorizontalOverflow() const
@@ -651,6 +681,10 @@
     if (m_box->style()->appearance() == ListboxPart)
         return;
 
+    // RenderView shouldn't provide scrollbars on its own.
+    if (m_box->isRenderView())
+        return;
+
     if (!m_scrollDimensionsDirty)
         updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
 
@@ -1346,14 +1380,14 @@
         // Count the total number of RenderLayers that are scrollable areas for
         // any period. We only want to record this at most once per RenderLayer.
         if (requiresScrollableArea && !m_isScrollableAreaHasBeenRecorded) {
-            blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::IsScrollableAreaBucket, RenderLayer::CompositedScrollingHistogramMax);
+            blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", IsScrollableAreaBucket, CompositedScrollingHistogramMax);
             m_isScrollableAreaHasBeenRecorded = true;
         }
 
         // We always want composited scrolling if compositor driven accelerated
         // scrolling is enabled. Since we will not update needs composited scrolling
         // in this case, we must force our state to update.
-        if (layer()->compositorDrivenAcceleratedScrollingEnabled())
+        if (m_box->compositorDrivenAcceleratedScrollingEnabled())
             layer()->didUpdateNeedsCompositedScrolling();
         else if (requiresScrollableArea)
             m_box->view()->compositor()->setNeedsUpdateCompositingRequirementsState();
@@ -1370,20 +1404,20 @@
     layer()->updateDescendantDependentFlags();
 
     ASSERT(scrollsOverflow());
-    const bool needsToBeStackingContainer = layer()->acceleratedCompositingForOverflowScrollEnabled()
+    const bool needsToBeStackingContainer = m_box->acceleratedCompositingForOverflowScrollEnabled()
         && layer()->stackingNode()->descendantsAreContiguousInStackingOrder()
         && !layer()->hasUnclippedDescendant();
 
     const bool needsToBeStackingContainerDidChange = layer()->stackingNode()->setNeedsToBeStackingContainer(needsToBeStackingContainer);
 
     const bool needsCompositedScrolling = needsToBeStackingContainer
-        || layer()->compositorDrivenAcceleratedScrollingEnabled();
+        || m_box->compositorDrivenAcceleratedScrollingEnabled();
 
     // We gather a boolean value for use with Google UMA histograms to
     // quantify the actual effects of a set of patches attempting to
     // relax composited scrolling requirements, thereby increasing the
     // number of composited overflow divs.
-    if (layer()->acceleratedCompositingForOverflowScrollEnabled())
+    if (m_box->acceleratedCompositingForOverflowScrollEnabled())
         blink::Platform::current()->histogramEnumeration("Renderer.NeedsCompositedScrolling", needsCompositedScrolling, 2);
 
     const bool needsCompositedScrollingDidChange = setNeedsCompositedScrolling(needsCompositedScrolling);
@@ -1405,8 +1439,8 @@
     // Count the total number of RenderLayers which need composited scrolling at
     // some point. This should be recorded at most once per RenderLayer, so we
     // check m_willUseCompositedScrollingHasBeenRecorded.
-    if (layer()->acceleratedCompositingForOverflowScrollEnabled() && !m_willUseCompositedScrollingHasBeenRecorded) {
-        blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::WillUseCompositedScrollingBucket, RenderLayer::CompositedScrollingHistogramMax);
+    if (m_box->acceleratedCompositingForOverflowScrollEnabled() && !m_willUseCompositedScrollingHasBeenRecorded) {
+        blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", WillUseCompositedScrollingBucket, CompositedScrollingHistogramMax);
         m_willUseCompositedScrollingHasBeenRecorded = true;
     }
 
@@ -1428,9 +1462,9 @@
         // repositioning, so we should be able to enqueue a partial update compositing layers from there.
         // this feature was overridden for now by deferred compositing updates.
         if (usesCompositedScrolling())
-            compositor->updateCompositingLayers(CompositingUpdateOnCompositedScroll);
+            compositor->setNeedsCompositingUpdate(CompositingUpdateOnCompositedScroll);
         else
-            compositor->updateCompositingLayers(CompositingUpdateOnScroll);
+            compositor->setNeedsCompositingUpdate(CompositingUpdateOnScroll);
     }
 }
 
diff --git a/Source/core/rendering/RenderLayerScrollableArea.h b/Source/core/rendering/RenderLayerScrollableArea.h
index 0444ca7..02ab6af 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.h
+++ b/Source/core/rendering/RenderLayerScrollableArea.h
@@ -167,6 +167,9 @@
 
     LayoutRect exposeRect(const LayoutRect&, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
 
+    // Returns true our scrollable area is in the FrameView's collection of scrollable areas. This can
+    // only happen if we're both scrollable, and we do in fact overflow. This means that overflow: hidden
+    // layers never get added to the FrameView's collection.
     bool scrollsOverflow() const;
 
     // Rectangle encompassing the scroll corner and resizer rect.
diff --git a/Source/core/rendering/RenderLayerStackingNode.cpp b/Source/core/rendering/RenderLayerStackingNode.cpp
index 8f25001..4d1b706 100644
--- a/Source/core/rendering/RenderLayerStackingNode.cpp
+++ b/Source/core/rendering/RenderLayerStackingNode.cpp
@@ -154,7 +154,7 @@
     if (!renderer()->documentBeingDestroyed()) {
         compositor()->setNeedsUpdateCompositingRequirementsState();
         compositor()->setCompositingLayersNeedRebuild();
-        if (layer()->acceleratedCompositingForOverflowScrollEnabled())
+        if (renderer()->acceleratedCompositingForOverflowScrollEnabled())
             compositor()->setNeedsToRecomputeCompositingRequirements();
     }
 }
@@ -195,7 +195,7 @@
 
     if (!renderer()->documentBeingDestroyed()) {
         compositor()->setCompositingLayersNeedRebuild();
-        if (layer()->acceleratedCompositingForOverflowScrollEnabled())
+        if (renderer()->acceleratedCompositingForOverflowScrollEnabled())
             compositor()->setNeedsToRecomputeCompositingRequirements();
     }
 }
@@ -217,10 +217,9 @@
     OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList, const RenderLayerStackingNode* nodeToForceAsStackingContainer,
     CollectLayersBehavior collectLayersBehavior)
 {
-    bool includeHiddenLayers = compositor()->inCompositingMode();
     for (RenderLayer* child = layer()->firstChild(); child; child = child->nextSibling()) {
         if (!layer()->reflectionInfo() || layer()->reflectionInfo()->reflectionLayer() != child)
-            child->stackingNode()->collectLayers(includeHiddenLayers, posZOrderList, negZOrderList, nodeToForceAsStackingContainer, collectLayersBehavior);
+            child->stackingNode()->collectLayers(posZOrderList, negZOrderList, nodeToForceAsStackingContainer, collectLayersBehavior);
     }
 
     // Sort the two lists.
@@ -270,8 +269,7 @@
     m_normalFlowListDirty = false;
 }
 
-void RenderLayerStackingNode::collectLayers(bool includeHiddenLayers,
-    OwnPtr<Vector<RenderLayerStackingNode*> >& posBuffer, OwnPtr<Vector<RenderLayerStackingNode*> >& negBuffer,
+void RenderLayerStackingNode::collectLayers(OwnPtr<Vector<RenderLayerStackingNode*> >& posBuffer, OwnPtr<Vector<RenderLayerStackingNode*> >& negBuffer,
     const RenderLayerStackingNode* nodeToForceAsStackingContainer, CollectLayersBehavior collectLayersBehavior)
 {
     if (layer()->isInTopLayer())
@@ -305,8 +303,7 @@
     }
 
     // Overflow layers are just painted by their enclosing layers, so they don't get put in zorder lists.
-    bool includeHiddenLayer = includeHiddenLayers || (layer()->hasVisibleContent() || (layer()->hasVisibleDescendant() && isStacking));
-    if (includeHiddenLayer && !isNormalFlow && !layer()->isOutOfFlowRenderFlowThread()) {
+    if (!isNormalFlow && !layer()->isOutOfFlowRenderFlowThread()) {
         // Determine which buffer the child should be in.
         OwnPtr<Vector<RenderLayerStackingNode*> >& buffer = (zIndex() >= 0) ? posBuffer : negBuffer;
 
@@ -320,11 +317,11 @@
 
     // Recur into our children to collect more layers, but only if we don't establish
     // a stacking context/container.
-    if ((includeHiddenLayers || layer()->hasVisibleDescendant()) && !isStacking) {
+    if (!isStacking) {
         for (RenderLayer* child = layer()->firstChild(); child; child = child->nextSibling()) {
             // Ignore reflections.
             if (!layer()->reflectionInfo() || layer()->reflectionInfo()->reflectionLayer() != child)
-                child->stackingNode()->collectLayers(includeHiddenLayers, posBuffer, negBuffer, nodeToForceAsStackingContainer, collectLayersBehavior);
+                child->stackingNode()->collectLayers(posBuffer, negBuffer, nodeToForceAsStackingContainer, collectLayersBehavior);
         }
     }
 }
@@ -429,8 +426,7 @@
         || renderer()->hasClipPath()
         || renderer()->hasFilter()
         || renderer()->hasBlendMode()
-        || layer()->isTransparent()
-        || renderer()->style()->hasFlowFrom();
+        || layer()->isTransparent();
 
     return couldBeNormalFlow && !preventsElementFromBeingNormalFlow;
 }
@@ -460,11 +456,10 @@
 {
     TRACE_EVENT0("blink_rendering,comp-scroll", "RenderLayerStackingNode::updateDescendantsAreContiguousInStackingOrder");
 
-    const RenderLayer* currentLayer = layer();
-    if (isStackingContext() || !m_descendantsAreContiguousInStackingOrderDirty || !currentLayer->acceleratedCompositingForOverflowScrollEnabled())
+    if (isStackingContext() || !m_descendantsAreContiguousInStackingOrderDirty || !renderer()->acceleratedCompositingForOverflowScrollEnabled())
         return;
 
-    if (!currentLayer->scrollsOverflow())
+    if (!layer()->scrollsOverflow())
         return;
 
     RenderLayerStackingNode* stackingNode = ancestorStackingNode();
@@ -626,8 +621,8 @@
     // Count the total number of RenderLayers which need to be stacking
     // containers some point. This should be recorded at most once per
     // RenderLayer, so we check m_needsToBeStackingContainerHasBeenRecorded.
-    if (layer()->acceleratedCompositingForOverflowScrollEnabled() && !m_needsToBeStackingContainerHasBeenRecorded) {
-        blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::NeedsToBeStackingContainerBucket, RenderLayer::CompositedScrollingHistogramMax);
+    if (renderer()->acceleratedCompositingForOverflowScrollEnabled() && !m_needsToBeStackingContainerHasBeenRecorded) {
+        blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", NeedsToBeStackingContainerBucket, CompositedScrollingHistogramMax);
         m_needsToBeStackingContainerHasBeenRecorded = true;
     }
 
diff --git a/Source/core/rendering/RenderLayerStackingNode.h b/Source/core/rendering/RenderLayerStackingNode.h
index d19cc50..12d7490 100644
--- a/Source/core/rendering/RenderLayerStackingNode.h
+++ b/Source/core/rendering/RenderLayerStackingNode.h
@@ -159,7 +159,7 @@
         const RenderLayerStackingNode* nodeToForceAsStackingContainer = 0,
         CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
 
-    void collectLayers(bool includeHiddenLayers, OwnPtr<Vector<RenderLayerStackingNode*> >&,
+    void collectLayers(OwnPtr<Vector<RenderLayerStackingNode*> >&,
         OwnPtr<Vector<RenderLayerStackingNode*> >&, const RenderLayerStackingNode* nodeToForceAsStackingContainer = 0,
         CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
 
diff --git a/Source/core/rendering/RenderListBox.cpp b/Source/core/rendering/RenderListBox.cpp
index f27f916..d529308 100644
--- a/Source/core/rendering/RenderListBox.cpp
+++ b/Source/core/rendering/RenderListBox.cpp
@@ -57,6 +57,7 @@
 #include "platform/fonts/FontCache.h"
 #include "platform/graphics/GraphicsContext.h"
 #include "platform/scroll/Scrollbar.h"
+#include "platform/text/BidiTextRun.h"
 
 using namespace std;
 
@@ -103,6 +104,13 @@
         frameView->removeScrollableArea(this);
 }
 
+// FIXME: Instead of this hack we should add a ShadowRoot to <select> with no insertion point
+// to prevent children from rendering.
+bool RenderListBox::isChildAllowed(RenderObject* object, RenderStyle*) const
+{
+    return object->isAnonymous() && !object->isRenderFullScreen();
+}
+
 inline HTMLSelectElement* RenderListBox::selectElement() const
 {
     return toHTMLSelectElement(node());
@@ -123,18 +131,22 @@
             Font itemFont = style()->font();
             if (element->hasTagName(optionTag)) {
                 text = toHTMLOptionElement(element)->textIndentedToRespectGroupLabel();
-            } else if (isHTMLOptGroupElement(element)) {
+            } else if (element->hasTagName(optgroupTag)) {
                 text = toHTMLOptGroupElement(element)->groupLabelText();
                 FontDescription d = itemFont.fontDescription();
                 d.setWeight(d.bolderWeight());
-                itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
+                itemFont = Font(d);
                 itemFont.update(document().styleEngine()->fontSelector());
             }
 
             if (!text.isEmpty()) {
                 applyTextTransform(style(), text, ' ');
-                // FIXME: Why is this always LTR? Can't text direction affect the width?
+
+                bool hasStrongDirectionality;
+                TextDirection direction = determineDirectionality(text, hasStrongDirectionality);
                 TextRun textRun = constructTextRun(this, itemFont, text, style(), TextRun::AllowTrailingExpansion);
+                if (hasStrongDirectionality)
+                    textRun.setDirection(direction);
                 textRun.disableRoundingHacks();
                 float textWidth = itemFont.width(textRun);
                 width = max(width, textWidth);
@@ -199,7 +211,7 @@
 {
     maxLogicalWidth = m_optionsWidth + 2 * optionsSpacingHorizontal;
     if (m_vBar)
-        maxLogicalWidth += m_vBar->width();
+        maxLogicalWidth += verticalScrollbarWidth();
     if (!style()->width().isPercent())
         minLogicalWidth = maxLogicalWidth;
 }
@@ -272,7 +284,7 @@
 LayoutRect RenderListBox::itemBoundingBoxRect(const LayoutPoint& additionalOffset, int index)
 {
     // For RTL, items start after the left-side vertical scrollbar.
-    int scrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? m_vBar->width() : 0;
+    int scrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? verticalScrollbarWidth() : 0;
     return LayoutRect(additionalOffset.x() + borderLeft() + paddingLeft() + scrollbarOffset,
         additionalOffset.y() + borderTop() + paddingTop() + itemHeight() * (index - m_indexOffset),
         contentWidth(), itemHeight());
@@ -294,7 +306,7 @@
     }
 
     // Paint the children.
-    RenderBlock::paintObject(paintInfo, paintOffset);
+    RenderBlockFlow::paintObject(paintInfo, paintOffset);
 
     switch (paintInfo.phase) {
     // Depending on whether we have overlay scrollbars they
@@ -324,7 +336,7 @@
 void RenderListBox::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer)
 {
     if (!isSpatialNavigationEnabled(frame()))
-        return RenderBlock::addFocusRingRects(rects, additionalOffset, paintContainer);
+        return RenderBlockFlow::addFocusRingRects(rects, additionalOffset, paintContainer);
 
     HTMLSelectElement* select = selectElement();
 
@@ -353,7 +365,7 @@
     if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
         scrollbarLeft = borderLeft();
     else
-        scrollbarLeft = width() - borderRight() - m_vBar->width();
+        scrollbarLeft = width() - borderRight() - verticalScrollbarWidth();
     return scrollbarLeft;
 }
 
@@ -362,7 +374,7 @@
     if (m_vBar) {
         IntRect scrollRect = pixelSnappedIntRect(paintOffset.x() + scrollbarLeft(),
             paintOffset.y() + borderTop(),
-            m_vBar->width(),
+            verticalScrollbarWidth(),
             height() - (borderTop() + borderBottom()));
         m_vBar->setFrameRect(scrollRect);
         m_vBar->paint(paintInfo.context, paintInfo.rect);
@@ -409,7 +421,7 @@
     bool isOptionElement = element->hasTagName(optionTag);
     if (isOptionElement)
         itemText = toHTMLOptionElement(element)->textIndentedToRespectGroupLabel();
-    else if (isHTMLOptGroupElement(element))
+    else if (element->hasTagName(optgroupTag))
         itemText = toHTMLOptGroupElement(element)->groupLabelText();
     applyTextTransform(style(), itemText, ' ');
 
@@ -429,10 +441,10 @@
     LayoutRect r = itemBoundingBoxRect(paintOffset, listIndex);
     r.move(itemOffsetForAlignment(textRun, itemStyle, itemFont, r));
 
-    if (isHTMLOptGroupElement(element)) {
+    if (element->hasTagName(optgroupTag)) {
         FontDescription d = itemFont.fontDescription();
         d.setWeight(d.bolderWeight());
-        itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
+        itemFont = Font(d);
         itemFont.update(document().styleEngine()->fontSelector());
     }
 
@@ -472,7 +484,7 @@
 
     LayoutRect vertRect(accumulatedOffset.x() + scrollbarLeft(),
                         accumulatedOffset.y() + borderTop(),
-                        m_vBar->width(),
+                        verticalScrollbarWidth(),
                         height() - borderTop() - borderBottom());
 
     if (vertRect.contains(locationInContainer)) {
@@ -490,7 +502,7 @@
     if (offset.height() < borderTop() + paddingTop() || offset.height() > height() - paddingBottom() - borderBottom())
         return -1;
 
-    int scrollbarWidth = m_vBar ? m_vBar->width() : 0;
+    int scrollbarWidth = verticalScrollbarWidth();
     int rightScrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? scrollbarWidth : 0;
     int leftScrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? 0 : scrollbarWidth;
     if (offset.width() < borderLeft() + paddingLeft() + rightScrollbarOffset
@@ -648,7 +660,12 @@
         return;
 
     m_indexOffset = newOffset;
-    repaint();
+
+    if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && frameView()->isInPerformLayout())
+        setShouldDoFullRepaintAfterLayout(true);
+    else
+        repaint();
+
     node()->document().enqueueScrollEventForNode(node());
 }
 
@@ -701,7 +718,7 @@
 
 bool RenderListBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
 {
-    if (!RenderBlock::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction))
+    if (!RenderBlockFlow::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction))
         return false;
     const Vector<HTMLElement*>& listItems = selectElement()->listItems();
     int size = numItems();
@@ -726,7 +743,7 @@
 {
     LayoutRect clipRect = contentBoxRect();
     if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
-        clipRect.moveBy(additionalOffset + LayoutPoint(m_vBar->width(), 0));
+        clipRect.moveBy(additionalOffset + LayoutPoint(verticalScrollbarWidth(), 0));
     else
         clipRect.moveBy(additionalOffset);
     return clipRect;
@@ -745,7 +762,22 @@
         scrollRect.move(borderLeft(), borderTop());
     else
         scrollRect.move(width() - borderRight() - scrollbar->width(), borderTop());
-    repaintRectangle(scrollRect);
+
+    if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && frameView()->isInPerformLayout()) {
+        m_verticalBarDamage = scrollRect;
+        m_hasVerticalBarDamage = true;
+    } else {
+        repaintRectangle(scrollRect);
+    }
+}
+
+void RenderListBox::repaintScrollbarIfNeeded()
+{
+    if (!hasVerticalBarDamage())
+        return;
+    repaintRectangle(verticalBarDamage());
+
+    resetScrollbarDamage();
 }
 
 IntRect RenderListBox::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
@@ -848,7 +880,7 @@
 
 IntPoint RenderListBox::maximumScrollPosition() const
 {
-    return IntPoint(0, numItems() - numVisibleItems());
+    return IntPoint(0, std::max(numItems() - numVisibleItems(), 0));
 }
 
 bool RenderListBox::userInputScrollable(ScrollbarOrientation orientation) const
diff --git a/Source/core/rendering/RenderListBox.h b/Source/core/rendering/RenderListBox.h
index c86b508..dfe947a 100644
--- a/Source/core/rendering/RenderListBox.h
+++ b/Source/core/rendering/RenderListBox.h
@@ -57,47 +57,49 @@
 
     int size() const;
 
+    void repaintScrollbarIfNeeded();
+
 private:
     HTMLSelectElement* selectElement() const;
 
-    virtual const char* renderName() const { return "RenderListBox"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderListBox"; }
 
-    virtual bool isListBox() const { return true; }
+    virtual bool isListBox() const OVERRIDE { return true; }
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
 
-    virtual void updateFromElement();
-    virtual bool hasControlClip() const { return true; }
-    virtual void paintObject(PaintInfo&, const LayoutPoint&);
-    virtual LayoutRect controlClipRect(const LayoutPoint&) const;
+    virtual void updateFromElement() OVERRIDE;
+    virtual bool hasControlClip() const OVERRIDE { return true; }
+    virtual void paintObject(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual LayoutRect controlClipRect(const LayoutPoint&) const OVERRIDE;
 
-    virtual bool isPointInOverflowControl(HitTestResult&, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset);
+    virtual bool isPointInOverflowControl(HitTestResult&, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset) OVERRIDE;
 
     virtual bool scroll(ScrollDirection, ScrollGranularity, float) OVERRIDE;
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE;
-    virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
+    virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
     virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer = 0) OVERRIDE;
 
-    virtual bool canBeProgramaticallyScrolled() const { return true; }
-    virtual void autoscroll(const IntPoint&);
-    virtual void stopAutoscroll();
+    virtual bool canBeProgramaticallyScrolled() const OVERRIDE { return true; }
+    virtual void autoscroll(const IntPoint&) OVERRIDE;
+    virtual void stopAutoscroll() OVERRIDE;
 
-    virtual bool shouldPanScroll() const { return true; }
-    virtual void panScroll(const IntPoint&);
+    virtual void panScroll(const IntPoint&) OVERRIDE;
 
-    virtual int verticalScrollbarWidth() const;
-    virtual int scrollLeft() const;
-    virtual int scrollTop() const;
-    virtual int scrollWidth() const;
-    virtual int scrollHeight() const;
-    virtual void setScrollLeft(int);
-    virtual void setScrollTop(int);
+    virtual int verticalScrollbarWidth() const OVERRIDE;
+    virtual int scrollLeft() const OVERRIDE;
+    virtual int scrollTop() const OVERRIDE;
+    virtual int scrollWidth() const OVERRIDE;
+    virtual int scrollHeight() const OVERRIDE;
+    virtual void setScrollLeft(int) OVERRIDE;
+    virtual void setScrollTop(int) OVERRIDE;
 
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 
@@ -125,9 +127,9 @@
     virtual IntPoint maximumScrollPosition() const OVERRIDE;
     virtual bool userInputScrollable(ScrollbarOrientation) const OVERRIDE;
     virtual bool shouldPlaceVerticalScrollbarOnLeft() const OVERRIDE;
-    virtual int lineStep(ScrollbarOrientation) const;
-    virtual int pageStep(ScrollbarOrientation) const;
-    virtual float pixelStep(ScrollbarOrientation) const;
+    virtual int lineStep(ScrollbarOrientation) const OVERRIDE;
+    virtual int pageStep(ScrollbarOrientation) const OVERRIDE;
+    virtual float pixelStep(ScrollbarOrientation) const OVERRIDE;
 
 
     virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
diff --git a/Source/core/rendering/RenderListItem.cpp b/Source/core/rendering/RenderListItem.cpp
index b3b57a5..8fce613 100644
--- a/Source/core/rendering/RenderListItem.cpp
+++ b/Source/core/rendering/RenderListItem.cpp
@@ -27,6 +27,7 @@
 #include "HTMLNames.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/html/HTMLOListElement.h"
+#include "core/rendering/FastTextAutosizer.h"
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderListMarker.h"
 #include "core/rendering/RenderView.h"
@@ -51,7 +52,7 @@
 
 void RenderListItem::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
-    RenderBlock::styleDidChange(diff, oldStyle);
+    RenderBlockFlow::styleDidChange(diff, oldStyle);
 
     if (style()->listStyleType() != NoneListStyle
         || (style()->listStyleImage() && !style()->listStyleImage()->errorOccurred())) {
@@ -316,6 +317,14 @@
 {
     ASSERT(needsLayout());
 
+    // The marker must be autosized before calling updateMarkerLocation.
+    // It cannot be done in the parent's beginLayout because it is not yet in the render tree.
+    if (m_marker) {
+        FastTextAutosizer* textAutosizer = document().fastTextAutosizer();
+        if (textAutosizer)
+            textAutosizer->inflateListItem(this, m_marker);
+    }
+
     LayoutRectRecorder recorder(*this);
     updateMarkerLocation();
     RenderBlockFlow::layout();
diff --git a/Source/core/rendering/RenderListItem.h b/Source/core/rendering/RenderListItem.h
index 797ccc7..f3b42fb 100644
--- a/Source/core/rendering/RenderListItem.h
+++ b/Source/core/rendering/RenderListItem.h
@@ -49,34 +49,34 @@
     String markerTextWithSuffix() const;
 
     void updateListMarkerNumbers();
+    void updateMarkerLocation();
 
     static void updateItemValuesForOrderedList(const HTMLOListElement*);
     static unsigned itemCountForOrderedList(const HTMLOListElement*);
 
 private:
-    virtual const char* renderName() const { return "RenderListItem"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderListItem"; }
 
-    virtual bool isListItem() const { return true; }
+    virtual bool isListItem() const OVERRIDE { return true; }
 
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
     virtual void insertedIntoTree() OVERRIDE;
     virtual void willBeRemovedFromTree() OVERRIDE;
 
-    virtual bool isEmpty() const;
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual bool isEmpty() const OVERRIDE;
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
     void positionListMarker();
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
-    virtual void addOverflowFromChildren();
+    virtual void addOverflowFromChildren() OVERRIDE;
 
-    void updateMarkerLocation();
     inline int calcValue() const;
     void updateValueNow() const;
     void explicitValueChanged();
diff --git a/Source/core/rendering/RenderListMarker.cpp b/Source/core/rendering/RenderListMarker.cpp
index f054974..b66aab5 100644
--- a/Source/core/rendering/RenderListMarker.cpp
+++ b/Source/core/rendering/RenderListMarker.cpp
@@ -1116,8 +1116,8 @@
     InlineBox* box = inlineBoxWrapper();
     if (!box)
         return LayoutRect(LayoutPoint(), size());
-    RootInlineBox* root = m_inlineBoxWrapper->root();
-    LayoutUnit newLogicalTop = root->block()->style()->isFlippedBlocksWritingMode() ? m_inlineBoxWrapper->logicalBottom() - root->selectionBottom() : root->selectionTop() - m_inlineBoxWrapper->logicalTop();
+    RootInlineBox* root = inlineBoxWrapper()->root();
+    LayoutUnit newLogicalTop = root->block()->style()->isFlippedBlocksWritingMode() ? inlineBoxWrapper()->logicalBottom() - root->selectionBottom() : root->selectionTop() - inlineBoxWrapper()->logicalTop();
     if (root->block()->style()->isHorizontalWritingMode())
         return LayoutRect(0, newLogicalTop, width(), root->selectionHeight());
     return LayoutRect(newLogicalTop, 0, root->selectionHeight(), height());
@@ -1301,21 +1301,19 @@
         }
 
         const UChar suffix = listMarkerSuffix(type, m_listItem->value());
+        UChar suffixStr[2] = {
+            style()->isLeftToRightDirection() ? suffix : ' ',
+            style()->isLeftToRightDirection() ? ' ' : suffix
+        };
+        TextRun suffixRun = RenderBlockFlow::constructTextRun(this, font, suffixStr, 2, style(), style()->direction());
+        TextRunPaintInfo suffixRunInfo(suffixRun);
+        suffixRunInfo.bounds = marker;
+
         if (style()->isLeftToRightDirection()) {
             context->drawText(font, textRunPaintInfo, textOrigin);
-
-            UChar suffixSpace[2] = { suffix, ' ' };
-            TextRun suffixRun = RenderBlockFlow::constructTextRun(this, font, suffixSpace, 2, style());
-            TextRunPaintInfo suffixRunInfo(suffixRun);
-            suffixRunInfo.bounds = marker;
             context->drawText(font, suffixRunInfo, textOrigin + IntSize(font.width(textRun), 0));
         } else {
-            UChar spaceSuffix[2] = { ' ', suffix };
-            TextRun suffixRun = RenderBlockFlow::constructTextRun(this, font, spaceSuffix, 2, style());
-            TextRunPaintInfo suffixRunInfo(suffixRun);
-            suffixRunInfo.bounds = marker;
             context->drawText(font, suffixRunInfo, textOrigin);
-
             context->drawText(font, textRunPaintInfo, textOrigin + IntSize(font.width(suffixRun), 0));
         }
     }
@@ -1583,7 +1581,7 @@
             else {
                 LayoutUnit itemWidth = font.width(m_text);
                 UChar suffixSpace[2] = { listMarkerSuffix(type, m_listItem->value()), ' ' };
-                LayoutUnit suffixSpaceWidth = font.width(RenderBlockFlow::constructTextRun(this, font, suffixSpace, 2, style()));
+                LayoutUnit suffixSpaceWidth = font.width(RenderBlockFlow::constructTextRun(this, font, suffixSpace, 2, style(), style()->direction()));
                 logicalWidth = itemWidth + suffixSpaceWidth;
             }
             break;
@@ -1809,7 +1807,7 @@
             const Font& font = style()->font();
             int itemWidth = font.width(m_text);
             UChar suffixSpace[2] = { listMarkerSuffix(type, m_listItem->value()), ' ' };
-            int suffixSpaceWidth = font.width(RenderBlockFlow::constructTextRun(this, font, suffixSpace, 2, style()));
+            int suffixSpaceWidth = font.width(RenderBlockFlow::constructTextRun(this, font, suffixSpace, 2, style(), style()->direction()));
             relativeRect = IntRect(0, 0, itemWidth + suffixSpaceWidth, font.fontMetrics().height());
     }
 
@@ -1826,8 +1824,8 @@
     // The selection state for our containing block hierarchy is updated by the base class call.
     RenderBox::setSelectionState(state);
 
-    if (m_inlineBoxWrapper && canUpdateSelectionOnRootLineBoxes())
-        if (RootInlineBox* root = m_inlineBoxWrapper->root())
+    if (inlineBoxWrapper() && canUpdateSelectionOnRootLineBoxes())
+        if (RootInlineBox* root = inlineBoxWrapper()->root())
             root->setHasSelectedChildren(state != SelectionNone);
 }
 
diff --git a/Source/core/rendering/RenderListMarker.h b/Source/core/rendering/RenderListMarker.h
index d0002ff..c533ace 100644
--- a/Source/core/rendering/RenderListMarker.h
+++ b/Source/core/rendering/RenderListMarker.h
@@ -49,34 +49,34 @@
 private:
     RenderListMarker(RenderListItem*);
 
-    virtual const char* renderName() const { return "RenderListMarker"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderListMarker"; }
     virtual void computePreferredLogicalWidths() OVERRIDE;
 
-    virtual bool isListMarker() const { return true; }
+    virtual bool isListMarker() const OVERRIDE { return true; }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
-    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0);
+    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
-    virtual InlineBox* createInlineBox();
+    virtual InlineBox* createInlineBox() OVERRIDE;
 
-    virtual LayoutUnit lineHeight(bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
-    virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
+    virtual LayoutUnit lineHeight(bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
+    virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
 
-    bool isImage() const;
+    virtual bool isImage() const OVERRIDE;
     bool isText() const { return !isImage(); }
 
-    virtual void setSelectionState(SelectionState);
+    virtual void setSelectionState(SelectionState) OVERRIDE;
     virtual LayoutRect selectionRectForRepaint(const RenderLayerModelObject* repaintContainer, bool clipToVisibleContent = true) OVERRIDE;
-    virtual bool canBeSelectionLeaf() const { return true; }
+    virtual bool canBeSelectionLeaf() const OVERRIDE { return true; }
 
     void updateMargins();
     void updateContent();
 
-    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle);
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     IntRect getRelativeMarkerRect();
     LayoutRect localSelectionRect();
diff --git a/Source/core/rendering/RenderMarquee.cpp b/Source/core/rendering/RenderMarquee.cpp
index 10340b3..9dce7e7 100644
--- a/Source/core/rendering/RenderMarquee.cpp
+++ b/Source/core/rendering/RenderMarquee.cpp
@@ -52,6 +52,7 @@
 #include "core/frame/UseCounter.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
+#include "platform/LengthFunctions.h"
 
 using namespace std;
 
@@ -59,11 +60,11 @@
 
 using namespace HTMLNames;
 
-RenderMarquee::RenderMarquee(Element* element)
+RenderMarquee::RenderMarquee(HTMLMarqueeElement* element)
     : RenderBlockFlow(element)
     , m_currentLoop(0)
     , m_totalLoops(0)
-    , m_timer(this, &RenderMarquee::timerFired)
+    , m_timer(element, &HTMLMarqueeElement::timerFired)
     , m_start(0)
     , m_end(0)
     , m_speed(0)
@@ -215,7 +216,7 @@
 
 void RenderMarquee::styleDidChange(StyleDifference difference, const RenderStyle* oldStyle)
 {
-    RenderBlock::styleDidChange(difference, oldStyle);
+    RenderBlockFlow::styleDidChange(difference, oldStyle);
 
     RenderStyle* s = style();
 
@@ -259,14 +260,14 @@
         m_timer.stop();
 }
 
-void RenderMarquee::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
+void RenderMarquee::layoutBlock(bool relayoutChildren)
 {
-    RenderBlockFlow::layoutBlock(relayoutChildren, pageLogicalHeight);
+    RenderBlockFlow::layoutBlock(relayoutChildren);
 
     updateMarqueePosition();
 }
 
-void RenderMarquee::timerFired(Timer<RenderMarquee>*)
+void RenderMarquee::timerFired()
 {
     // FIXME: Why do we need to check the view and not just the RenderMarquee itself?
     if (view()->needsLayout())
diff --git a/Source/core/rendering/RenderMarquee.h b/Source/core/rendering/RenderMarquee.h
index ab37ed8..458f7dd 100644
--- a/Source/core/rendering/RenderMarquee.h
+++ b/Source/core/rendering/RenderMarquee.h
@@ -44,6 +44,7 @@
 #ifndef RenderMarquee_h
 #define RenderMarquee_h
 
+#include "core/html/HTMLMarqueeElement.h"
 #include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "platform/Length.h"
@@ -56,7 +57,7 @@
 // This class handles the auto-scrolling for <marquee>
 class RenderMarquee FINAL : public RenderBlockFlow {
 public:
-    explicit RenderMarquee(Element*);
+    explicit RenderMarquee(HTMLMarqueeElement*);
     virtual ~RenderMarquee();
 
     int speed() const { return m_speed; }
@@ -79,22 +80,22 @@
     // However <marquee> tests are very timing dependent so we need to keep the existing timing.
     void updateMarqueePosition();
 
+    void timerFired();
+
 private:
-    virtual const char* renderName() const OVERRIDE FINAL;
+    virtual const char* renderName() const OVERRIDE;
 
-    virtual bool isMarquee() const OVERRIDE FINAL { return true; }
+    virtual bool isMarquee() const OVERRIDE { return true; }
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
-    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE FINAL;
+    virtual void layoutBlock(bool relayoutChildren) OVERRIDE;
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
-    void timerFired(Timer<RenderMarquee>*);
-
     int m_currentLoop;
     int m_totalLoops;
-    Timer<RenderMarquee> m_timer;
+    Timer<HTMLMarqueeElement> m_timer;
     int m_start;
     int m_end;
     int m_speed;
diff --git a/Source/core/rendering/RenderMedia.cpp b/Source/core/rendering/RenderMedia.cpp
index aacc6ae..f00de2e 100644
--- a/Source/core/rendering/RenderMedia.cpp
+++ b/Source/core/rendering/RenderMedia.cpp
@@ -29,7 +29,6 @@
 
 #include "core/html/HTMLMediaElement.h"
 #include "core/rendering/LayoutRectRecorder.h"
-#include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderView.h"
 
 namespace WebCore {
@@ -61,14 +60,6 @@
         return;
 
     bool controlsNeedLayout = controlsRenderer->needsLayout();
-    // If the region chain has changed we also need to relayout the controls to update the region box info.
-    // FIXME: We can do better once we compute region box info for RenderReplaced, not only for RenderBlock.
-    const RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (flowThread && !controlsNeedLayout) {
-        if (flowThread->pageLogicalSizeChanged())
-            controlsNeedLayout = true;
-    }
-
     LayoutSize newSize = contentBoxRect().size();
     if (newSize == oldSize && !controlsNeedLayout)
         return;
diff --git a/Source/core/rendering/RenderMedia.h b/Source/core/rendering/RenderMedia.h
index ada064b..b79c0ae 100644
--- a/Source/core/rendering/RenderMedia.h
+++ b/Source/core/rendering/RenderMedia.h
@@ -46,7 +46,7 @@
     HTMLMediaElement* mediaElement() const;
 
 protected:
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
 private:
     virtual RenderObjectChildList* virtualChildren() OVERRIDE FINAL { return children(); }
@@ -57,10 +57,10 @@
     virtual bool canHaveGeneratedChildren() const OVERRIDE FINAL { return false; }
     virtual bool canHaveChildren() const OVERRIDE FINAL { return true; }
 
-    virtual const char* renderName() const { return "RenderMedia"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderMedia"; }
     virtual bool isMedia() const OVERRIDE FINAL { return true; }
     virtual bool isImage() const OVERRIDE FINAL { return false; }
-    virtual void paintReplaced(PaintInfo&, const LayoutPoint&);
+    virtual void paintReplaced(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     RenderObjectChildList m_children;
 };
diff --git a/Source/core/rendering/RenderMediaControlElements.cpp b/Source/core/rendering/RenderMediaControlElements.cpp
index da2babc..e332416 100644
--- a/Source/core/rendering/RenderMediaControlElements.cpp
+++ b/Source/core/rendering/RenderMediaControlElements.cpp
@@ -29,6 +29,7 @@
 
 #include "core/rendering/RenderMediaControlElements.h"
 
+#include "core/frame/DeprecatedScheduleStyleRecalcDuringLayout.h"
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderView.h"
 
@@ -42,16 +43,16 @@
 void RenderTextTrackContainerElement::layout()
 {
     LayoutRectRecorder recorder(*this);
-    RenderBlock::layout();
+    RenderBlockFlow::layout();
     if (style()->display() == NONE)
         return;
 
     ASSERT(mediaControlElementType(node()) == MediaTextTrackDisplayContainer);
 
+    DeprecatedScheduleStyleRecalcDuringLayout marker(node()->document().lifecycle());
+
     LayoutStateDisabler layoutStateDisabler(view());
     static_cast<MediaControlTextTrackContainerElement*>(node())->updateSizes();
 }
 
-
 } // namespace WebCore
-
diff --git a/Source/core/rendering/RenderMediaControlElements.h b/Source/core/rendering/RenderMediaControlElements.h
index 90a7d5e..3282f34 100644
--- a/Source/core/rendering/RenderMediaControlElements.h
+++ b/Source/core/rendering/RenderMediaControlElements.h
@@ -39,7 +39,7 @@
     RenderTextTrackContainerElement(Element*);
 
 private:
-    virtual void layout();
+    virtual void layout() OVERRIDE;
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 };
 
diff --git a/Source/core/rendering/RenderMediaControls.cpp b/Source/core/rendering/RenderMediaControls.cpp
index 13d1620..868cf6b 100644
--- a/Source/core/rendering/RenderMediaControls.cpp
+++ b/Source/core/rendering/RenderMediaControls.cpp
@@ -133,9 +133,7 @@
     int borderRadius = rect.height() / 2;
     IntSize radii(borderRadius, borderRadius);
     Color sliderBackgroundColor = Color(11, 11, 11);
-    context->save();
     context->fillRoundedRect(rect, radii, radii, radii, radii, sliderBackgroundColor);
-    context->restore();
 }
 
 static void paintSliderRangeHighlight(const IntRect& rect, const RenderStyle* style, GraphicsContext* context, int startPosition, int endPosition, Color startColor, Color endColor)
@@ -156,10 +154,8 @@
     // Make sure the range width is bigger than border radius at the edges to retain rounded corners.
     if (startOffset < borderRadius && rangeWidth < borderRadius)
         rangeWidth = borderRadius;
-    if (endOffset < borderRadius && rangeWidth < borderRadius) {
-        startPosition -= borderRadius - rangeWidth;
+    if (endOffset < borderRadius && rangeWidth < borderRadius)
         rangeWidth = borderRadius;
-    }
 
     // Set rectangle to highlight range.
     IntRect highlightRect = rect;
@@ -365,16 +361,11 @@
         return paintMediaFullscreenButton(object, paintInfo, rect);
     case MediaOverlayPlayButton:
         return paintMediaOverlayPlayButton(object, paintInfo, rect);
-    case MediaVolumeSliderMuteButton:
-    case MediaSeekBackButton:
-    case MediaSeekForwardButton:
     case MediaVolumeSliderContainer:
     case MediaTimelineContainer:
     case MediaCurrentTimeDisplay:
     case MediaTimeRemainingDisplay:
     case MediaControlsPanel:
-    case MediaRewindButton:
-    case MediaReturnToRealtimeButton:
     case MediaStatusDisplay:
     case MediaHideClosedCaptionsButton:
     case MediaTextTrackDisplayContainer:
diff --git a/Source/core/rendering/RenderMenuList.cpp b/Source/core/rendering/RenderMenuList.cpp
index 57c8afc..1ed8698 100644
--- a/Source/core/rendering/RenderMenuList.cpp
+++ b/Source/core/rendering/RenderMenuList.cpp
@@ -32,13 +32,13 @@
 #include "core/css/CSSFontSelector.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/NodeRenderStyle.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/FrameView.h"
 #include "core/html/HTMLOptGroupElement.h"
 #include "core/html/HTMLOptionElement.h"
 #include "core/html/HTMLSelectElement.h"
 #include "core/page/Chrome.h"
-#include "core/frame/Frame.h"
-#include "core/frame/FrameView.h"
-#include "core/page/Page.h"
 #include "core/rendering/RenderBR.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderTheme.h"
@@ -73,6 +73,13 @@
     m_popup = 0;
 }
 
+// FIXME: Instead of this hack we should add a ShadowRoot to <select> with no insertion point
+// to prevent children from rendering.
+bool RenderMenuList::isChildAllowed(RenderObject* object, RenderStyle*) const
+{
+    return object->isAnonymous() && !object->isRenderFullScreen();
+}
+
 void RenderMenuList::createInnerBlock()
 {
     if (m_innerBlock) {
@@ -99,10 +106,10 @@
     // Use margin:auto instead of align-items:center to get safe centering, i.e.
     // when the content overflows, treat it the same as align-items: flex-start.
     // But we only do that for the cases where html.css would otherwise use center.
-    if (style()->alignItems() == AlignCenter) {
+    if (style()->alignItems() == ItemPositionCenter) {
         innerStyle->setMarginTop(Length());
         innerStyle->setMarginBottom(Length());
-        innerStyle->setAlignSelf(AlignFlexStart);
+        innerStyle->setAlignSelf(ItemPositionFlexStart);
     }
 
     innerStyle->setPaddingLeft(Length(RenderTheme::theme().popupInternalPaddingLeft(style()), Fixed));
@@ -175,7 +182,7 @@
             // Add in the option's text indent.  We can't calculate percentage values for now.
             float optionWidth = 0;
             if (RenderStyle* optionStyle = element->renderStyle())
-                optionWidth += minimumValueForLength(optionStyle->textIndent(), 0, view());
+                optionWidth += minimumValueForLength(optionStyle->textIndent(), 0);
             if (!text.isEmpty())
                 optionWidth += style()->font().width(text);
             maxOptionWidth = max(maxOptionWidth, optionWidth);
@@ -315,7 +322,7 @@
     if (m_popupIsVisible)
         return;
 
-    if (document().page()->chrome().hasOpenedPopup())
+    if (document().frameHost()->chrome().hasOpenedPopup())
         return;
 
     // Create m_innerBlock here so it ends up as the first child.
@@ -323,7 +330,7 @@
     // inside the showPopup call and it would fail.
     createInnerBlock();
     if (!m_popup)
-        m_popup = document().page()->chrome().createPopupMenu(*document().frame(), this);
+        m_popup = document().frameHost()->chrome().createPopupMenu(*document().frame(), this);
     m_popupIsVisible = true;
 
     FloatQuad quad(localToAbsoluteQuad(FloatQuad(borderBoundingBox())));
@@ -391,7 +398,7 @@
 
     String itemString;
     Element* element = listItems[listIndex];
-    if (isHTMLOptGroupElement(element))
+    if (element->hasTagName(optgroupTag))
         itemString = toHTMLOptGroupElement(element)->groupLabelText();
     else if (element->hasTagName(optionTag))
         itemString = toHTMLOptionElement(element)->textIndentedToRespectGroupLabel();
@@ -400,16 +407,6 @@
     return itemString;
 }
 
-String RenderMenuList::itemLabel(unsigned) const
-{
-    return String();
-}
-
-String RenderMenuList::itemIcon(unsigned) const
-{
-    return String();
-}
-
 String RenderMenuList::itemAccessibilityText(unsigned listIndex) const
 {
     // Allow the accessible name be changed if necessary.
@@ -438,7 +435,7 @@
 
     bool groupEnabled = true;
     if (Element* parentElement = element->parentElement()) {
-        if (isHTMLOptGroupElement(parentElement))
+        if (parentElement->hasTagName(optgroupTag))
             groupEnabled = !parentElement->isDisabledFormControl();
     }
     if (!groupEnabled)
@@ -485,7 +482,7 @@
     Color backgroundColor;
     if (element->renderStyle())
         backgroundColor = resolveColor(element->renderStyle(), CSSPropertyBackgroundColor);
-    itemHasCustomBackgroundColor = backgroundColor.isValid() && backgroundColor.alpha();
+    itemHasCustomBackgroundColor = backgroundColor.alpha();
     // If the item has an opaque background color, return that.
     if (!backgroundColor.hasAlpha()) {
         itemBackgroundColor = backgroundColor;
@@ -511,32 +508,6 @@
         s->display() == NONE, s->textIndent(), style()->direction(), isOverride(style()->unicodeBidi()));
 }
 
-HostWindow* RenderMenuList::hostWindow() const
-{
-    return document().view()->hostWindow();
-}
-
-PassRefPtr<Scrollbar> RenderMenuList::createScrollbar(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, ScrollbarControlSize controlSize)
-{
-    RefPtr<Scrollbar> widget;
-    bool hasCustomScrollbarStyle = style()->hasPseudoStyle(SCROLLBAR);
-    if (hasCustomScrollbarStyle)
-        widget = RenderScrollbar::createCustomScrollbar(scrollableArea, orientation, this->node());
-    else
-        widget = Scrollbar::create(scrollableArea, orientation, controlSize);
-    return widget.release();
-}
-
-int RenderMenuList::clientInsetLeft() const
-{
-    return 0;
-}
-
-int RenderMenuList::clientInsetRight() const
-{
-    return 0;
-}
-
 LayoutUnit RenderMenuList::clientPaddingLeft() const
 {
     return paddingLeft() + m_innerBlock->paddingLeft();
@@ -583,7 +554,7 @@
 bool RenderMenuList::itemIsLabel(unsigned listIndex) const
 {
     const Vector<HTMLElement*>& listItems = selectElement()->listItems();
-    return listIndex < listItems.size() && isHTMLOptGroupElement(listItems[listIndex]);
+    return listIndex < listItems.size() && listItems[listIndex]->hasTagName(optgroupTag);
 }
 
 bool RenderMenuList::itemIsSelected(unsigned listIndex) const
@@ -600,9 +571,4 @@
     setTextFromOption(selectElement()->listToOptionIndex(listIndex));
 }
 
-FontSelector* RenderMenuList::fontSelector() const
-{
-    return document().styleEngine()->fontSelector();
-}
-
 }
diff --git a/Source/core/rendering/RenderMenuList.h b/Source/core/rendering/RenderMenuList.h
index 7c22cd6..b7dc98c 100644
--- a/Source/core/rendering/RenderMenuList.h
+++ b/Source/core/rendering/RenderMenuList.h
@@ -24,9 +24,9 @@
 #ifndef RenderMenuList_h
 #define RenderMenuList_h
 
-#include "core/platform/PopupMenuClient.h"
 #include "core/rendering/RenderFlexibleBox.h"
 #include "platform/PopupMenu.h"
+#include "platform/PopupMenuClient.h"
 #include "platform/geometry/LayoutRect.h"
 
 namespace WebCore {
@@ -54,39 +54,36 @@
 private:
     HTMLSelectElement* selectElement() const;
 
-    virtual bool isMenuList() const { return true; }
+    virtual bool isMenuList() const OVERRIDE { return true; }
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
 
-    virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0);
-    virtual void removeChild(RenderObject*);
-    virtual bool createsAnonymousWrapper() const { return true; }
+    virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0) OVERRIDE;
+    virtual void removeChild(RenderObject*) OVERRIDE;
+    virtual bool createsAnonymousWrapper() const OVERRIDE { return true; }
 
-    virtual void updateFromElement();
+    virtual void updateFromElement() OVERRIDE;
 
-    virtual LayoutRect controlClipRect(const LayoutPoint&) const;
-    virtual bool hasControlClip() const { return true; }
+    virtual LayoutRect controlClipRect(const LayoutPoint&) const OVERRIDE;
+    virtual bool hasControlClip() const OVERRIDE { return true; }
     virtual bool canHaveGeneratedChildren() const OVERRIDE { return false; }
 
-    virtual const char* renderName() const { return "RenderMenuList"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderMenuList"; }
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE;
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     // PopupMenuClient methods
     virtual void valueChanged(unsigned listIndex, bool fireOnChange = true) OVERRIDE;
     virtual void selectionChanged(unsigned, bool) OVERRIDE { }
     virtual void selectionCleared() OVERRIDE { }
     virtual String itemText(unsigned listIndex) const OVERRIDE;
-    virtual String itemLabel(unsigned listIndex) const OVERRIDE;
-    virtual String itemIcon(unsigned listIndex) const OVERRIDE;
     virtual String itemToolTip(unsigned listIndex) const OVERRIDE;
     virtual String itemAccessibilityText(unsigned listIndex) const OVERRIDE;
     virtual bool itemIsEnabled(unsigned listIndex) const OVERRIDE;
     virtual PopupMenuStyle itemStyle(unsigned listIndex) const OVERRIDE;
     virtual PopupMenuStyle menuStyle() const OVERRIDE;
-    virtual int clientInsetLeft() const OVERRIDE;
-    virtual int clientInsetRight() const OVERRIDE;
     virtual LayoutUnit clientPaddingLeft() const OVERRIDE;
     virtual LayoutUnit clientPaddingRight() const OVERRIDE;
     virtual int listSize() const OVERRIDE;
@@ -95,15 +92,11 @@
     virtual bool itemIsSeparator(unsigned listIndex) const OVERRIDE;
     virtual bool itemIsLabel(unsigned listIndex) const OVERRIDE;
     virtual bool itemIsSelected(unsigned listIndex) const OVERRIDE;
-    virtual bool valueShouldChangeOnHotTrack() const OVERRIDE { return true; }
     virtual void setTextFromItem(unsigned listIndex) OVERRIDE;
     virtual void listBoxSelectItem(int listIndex, bool allowMultiplySelections, bool shift, bool fireOnChangeNow = true) OVERRIDE;
     virtual bool multiple() const OVERRIDE;
-    virtual FontSelector* fontSelector() const OVERRIDE;
-    virtual HostWindow* hostWindow() const OVERRIDE;
-    virtual PassRefPtr<Scrollbar> createScrollbar(ScrollableArea*, ScrollbarOrientation, ScrollbarControlSize) OVERRIDE;
 
-    virtual bool hasLineIfEmpty() const { return true; }
+    virtual bool hasLineIfEmpty() const OVERRIDE { return true; }
 
     // Flexbox defines baselines differently than regular blocks.
     // For backwards compatibility, menulists need to do the regular block behavior.
diff --git a/Source/core/rendering/RenderMeter.cpp b/Source/core/rendering/RenderMeter.cpp
index a4982a9..d4765ab 100644
--- a/Source/core/rendering/RenderMeter.cpp
+++ b/Source/core/rendering/RenderMeter.cpp
@@ -44,7 +44,7 @@
 {
     ASSERT(node());
 
-    if (isHTMLMeterElement(node()))
+    if (node()->hasTagName(meterTag))
         return toHTMLMeterElement(node());
 
     ASSERT(node()->shadowHost());
diff --git a/Source/core/rendering/RenderMeter.h b/Source/core/rendering/RenderMeter.h
index d1f1e43..a984799 100644
--- a/Source/core/rendering/RenderMeter.h
+++ b/Source/core/rendering/RenderMeter.h
@@ -34,7 +34,7 @@
     virtual ~RenderMeter();
 
     HTMLMeterElement* meterElement() const;
-    virtual void updateFromElement();
+    virtual void updateFromElement() OVERRIDE;
 
 private:
     virtual void updateLogicalWidth() OVERRIDE;
@@ -42,8 +42,8 @@
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
-    virtual const char* renderName() const { return "RenderMeter"; }
-    virtual bool isMeter() const { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderMeter"; }
+    virtual bool isMeter() const OVERRIDE { return true; }
 
     double valueRatio() const;
 };
diff --git a/Source/core/rendering/RenderMultiColumnBlock.cpp b/Source/core/rendering/RenderMultiColumnBlock.cpp
index 53c1fe8..75d291b 100644
--- a/Source/core/rendering/RenderMultiColumnBlock.cpp
+++ b/Source/core/rendering/RenderMultiColumnBlock.cpp
@@ -41,12 +41,13 @@
     , m_columnWidth(0)
     , m_columnHeightAvailable(0)
     , m_inBalancingPass(false)
+    , m_needsRebalancing(false)
 {
 }
 
 void RenderMultiColumnBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
-    RenderBlock::styleDidChange(diff, oldStyle);
+    RenderBlockFlow::styleDidChange(diff, oldStyle);
     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox())
         child->setStyle(RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK));
 }
@@ -79,7 +80,7 @@
 
 bool RenderMultiColumnBlock::updateLogicalWidthAndColumnWidth()
 {
-    bool relayoutChildren = RenderBlock::updateLogicalWidthAndColumnWidth();
+    bool relayoutChildren = RenderBlockFlow::updateLogicalWidthAndColumnWidth();
     LayoutUnit oldColumnWidth = m_columnWidth;
     computeColumnCountAndWidth();
     if (m_columnWidth != oldColumnWidth)
@@ -95,45 +96,32 @@
     setLogicalHeight(0);
 }
 
-bool RenderMultiColumnBlock::relayoutForPagination(bool, LayoutUnit, LayoutStateMaintainer& statePusher)
+bool RenderMultiColumnBlock::shouldRelayoutMultiColumnBlock()
 {
-    if (m_inBalancingPass || !requiresBalancing())
+    if (!m_needsRebalancing)
         return false;
-    m_inBalancingPass = true; // Prevent re-entering this method (and recursion into layout).
 
-    bool needsRelayout;
-    bool neededRelayout = false;
-    bool firstPass = true;
-    do {
-        // Column heights may change here because of balancing. We may have to do multiple layout
-        // passes, depending on how the contents is fitted to the changed column heights. In most
-        // cases, laying out again twice or even just once will suffice. Sometimes we need more
-        // passes than that, though, but the number of retries should not exceed the number of
-        // columns, unless we have a bug.
-        needsRelayout = false;
-        for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
-            if (childBox != m_flowThread && childBox->isRenderMultiColumnSet()) {
-                RenderMultiColumnSet* multicolSet = toRenderMultiColumnSet(childBox);
-                if (multicolSet->calculateBalancedHeight(firstPass)) {
-                    multicolSet->setChildNeedsLayout(MarkOnlyThis);
-                    needsRelayout = true;
-                }
+    // Column heights may change here because of balancing. We may have to do multiple layout
+    // passes, depending on how the contents is fitted to the changed column heights. In most
+    // cases, laying out again twice or even just once will suffice. Sometimes we need more
+    // passes than that, though, but the number of retries should not exceed the number of
+    // columns, unless we have a bug.
+    bool needsRelayout = false;
+    for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
+        if (childBox != m_flowThread && childBox->isRenderMultiColumnSet()) {
+            RenderMultiColumnSet* multicolSet = toRenderMultiColumnSet(childBox);
+            if (multicolSet->recalculateBalancedHeight(!m_inBalancingPass)) {
+                multicolSet->setChildNeedsLayout(MarkOnlyThis);
+                needsRelayout = true;
             }
         }
+    }
 
-        if (needsRelayout) {
-            // Layout again. Column balancing resulted in a new height.
-            neededRelayout = true;
-            m_flowThread->setChildNeedsLayout(MarkOnlyThis);
-            setChildNeedsLayout(MarkOnlyThis);
-            if (firstPass)
-                statePusher.pop();
-            layoutBlock(false);
-        }
-        firstPass = false;
-    } while (needsRelayout);
-    m_inBalancingPass = false;
-    return neededRelayout;
+    if (needsRelayout)
+        m_flowThread->setChildNeedsLayout(MarkOnlyThis);
+
+    m_inBalancingPass = needsRelayout;
+    return needsRelayout;
 }
 
 void RenderMultiColumnBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
@@ -141,7 +129,7 @@
     if (!m_flowThread) {
         m_flowThread = RenderMultiColumnFlowThread::createAnonymous(&document());
         m_flowThread->setStyle(RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK));
-        RenderBlock::addChild(m_flowThread);
+        RenderBlockFlow::addChild(m_flowThread);
     }
     m_flowThread->addChild(newChild, beforeChild);
 }
@@ -172,6 +160,18 @@
     if (relayoutChildren)
         layoutScope.setChildNeedsLayout(m_flowThread);
 
+    if (requiresBalancing()) {
+        // At the end of multicol layout, relayoutForPagination() is called unconditionally, but if
+        // no children are to be laid out (e.g. fixed width with layout already being up-to-date),
+        // we want to prevent it from doing any work, so that the column balancing machinery doesn't
+        // kick in and trigger additional unnecessary layout passes. Actually, it's not just a good
+        // idea in general to not waste time on balancing content that hasn't been re-laid out; we
+        // are actually required to guarantee this. The calculation of implicit breaks needs to be
+        // preceded by a proper layout pass, since it's layout that sets up content runs, and the
+        // runs get deleted right after every pass.
+        m_needsRebalancing = shouldInvalidateRegions || m_flowThread->needsLayout();
+    }
+
     setLogicalTopForChild(m_flowThread, borderBefore() + paddingBefore());
     m_flowThread->layoutIfNeeded();
     determineLogicalLeftPositionForChild(m_flowThread);
diff --git a/Source/core/rendering/RenderMultiColumnBlock.h b/Source/core/rendering/RenderMultiColumnBlock.h
index ac92d2f..8b6115e 100644
--- a/Source/core/rendering/RenderMultiColumnBlock.h
+++ b/Source/core/rendering/RenderMultiColumnBlock.h
@@ -46,18 +46,19 @@
 
     bool requiresBalancing() const { return !m_columnHeightAvailable || style()->columnFill() == ColumnFillBalance; }
 
-private:
-    virtual bool isRenderMultiColumnBlock() const { return true; }
+    bool shouldRelayoutMultiColumnBlock();
 
-    virtual const char* renderName() const;
+private:
+    virtual bool isRenderMultiColumnBlock() const OVERRIDE { return true; }
+
+    virtual const char* renderName() const OVERRIDE;
 
     virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&) OVERRIDE;
 
     virtual void styleDidChange(StyleDifference, const RenderStyle*) OVERRIDE;
 
     virtual bool updateLogicalWidthAndColumnWidth() OVERRIDE;
-    virtual void checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight) OVERRIDE;
-    virtual bool relayoutForPagination(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer&) OVERRIDE;
+    virtual void checkForPaginationLogicalHeightChange(LayoutUnit&, bool&, bool&) OVERRIDE;
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
@@ -73,6 +74,7 @@
                               // These values will be cached (eventually) for multi-column blocks.
     LayoutUnit m_columnHeightAvailable; // Total height available to columns, or 0 if auto.
     bool m_inBalancingPass; // Set when relayouting for column balancing.
+    bool m_needsRebalancing;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderMultiColumnBlock, isRenderMultiColumnBlock());
diff --git a/Source/core/rendering/RenderMultiColumnFlowThread.cpp b/Source/core/rendering/RenderMultiColumnFlowThread.cpp
index 1a2fc6f..86ee4ed 100644
--- a/Source/core/rendering/RenderMultiColumnFlowThread.cpp
+++ b/Source/core/rendering/RenderMultiColumnFlowThread.cpp
@@ -116,4 +116,15 @@
         multicolSet->updateMinimumColumnHeight(minHeight);
 }
 
+bool RenderMultiColumnFlowThread::addForcedRegionBreak(LayoutUnit offset, RenderObject* /*breakChild*/, bool /*isBefore*/, LayoutUnit* offsetBreakAdjustment)
+{
+    if (RenderMultiColumnSet* multicolSet = toRenderMultiColumnSet(regionAtBlockOffset(offset))) {
+        multicolSet->addForcedBreak(offset);
+        if (offsetBreakAdjustment)
+            *offsetBreakAdjustment = pageLogicalHeightForOffset(offset) ? pageRemainingLogicalHeightForOffset(offset, IncludePageBoundary) : LayoutUnit();
+        return true;
+    }
+    return false;
+}
+
 }
diff --git a/Source/core/rendering/RenderMultiColumnFlowThread.h b/Source/core/rendering/RenderMultiColumnFlowThread.h
index ace5c43..45b4d93 100644
--- a/Source/core/rendering/RenderMultiColumnFlowThread.h
+++ b/Source/core/rendering/RenderMultiColumnFlowThread.h
@@ -33,7 +33,7 @@
 
 class RenderMultiColumnFlowThread FINAL : public RenderFlowThread {
 public:
-    ~RenderMultiColumnFlowThread();
+    virtual ~RenderMultiColumnFlowThread();
 
     static RenderMultiColumnFlowThread* createAnonymous(Document*);
 
@@ -46,6 +46,7 @@
     virtual LayoutUnit initialLogicalWidth() const OVERRIDE;
     virtual void setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage) OVERRIDE;
     virtual void updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight) OVERRIDE;
+    virtual bool addForcedRegionBreak(LayoutUnit, RenderObject* breakChild, bool isBefore, LayoutUnit* offsetBreakAdjustment = 0) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderMultiColumnSet.cpp b/Source/core/rendering/RenderMultiColumnSet.cpp
index 4490737..a38addb 100644
--- a/Source/core/rendering/RenderMultiColumnSet.cpp
+++ b/Source/core/rendering/RenderMultiColumnSet.cpp
@@ -40,12 +40,9 @@
     , m_computedColumnCount(1)
     , m_computedColumnWidth(0)
     , m_computedColumnHeight(0)
-    , m_maxColumnHeight(LayoutUnit::max())
-    , m_minSpaceShortage(LayoutUnit::max())
+    , m_maxColumnHeight(RenderFlowThread::maxLogicalHeight())
+    , m_minSpaceShortage(RenderFlowThread::maxLogicalHeight())
     , m_minimumColumnHeight(0)
-    , m_forcedBreaksCount(0)
-    , m_maximumDistanceBetweenForcedBreaks(0)
-    , m_forcedBreakOffset(0)
 {
 }
 
@@ -81,46 +78,122 @@
     // FIXME: the height may also be affected by the enclosing pagination context, if any.
 }
 
-bool RenderMultiColumnSet::calculateBalancedHeight(bool initial)
+unsigned RenderMultiColumnSet::findRunWithTallestColumns() const
 {
-    ASSERT(toRenderMultiColumnBlock(parent())->requiresBalancing());
-    LayoutUnit oldColumnHeight = m_computedColumnHeight;
-    LayoutUnit currentMinSpaceShortage = m_minSpaceShortage;
-    m_minSpaceShortage = LayoutUnit::max();
+    unsigned indexWithLargestHeight = 0;
+    LayoutUnit largestHeight;
+    LayoutUnit previousOffset;
+    size_t runCount = m_contentRuns.size();
+    ASSERT(runCount);
+    for (size_t i = 0; i < runCount; i++) {
+        const ContentRun& run = m_contentRuns[i];
+        LayoutUnit height = run.columnLogicalHeight(previousOffset);
+        if (largestHeight < height) {
+            largestHeight = height;
+            indexWithLargestHeight = i;
+        }
+        previousOffset = run.breakOffset();
+    }
+    return indexWithLargestHeight;
+}
 
+void RenderMultiColumnSet::distributeImplicitBreaks()
+{
+    unsigned breakCount = forcedBreaksCount();
+
+#ifndef NDEBUG
+    // There should be no implicit breaks assumed at this point.
+    for (unsigned i = 0; i < breakCount; i++)
+        ASSERT(!m_contentRuns[i].assumedImplicitBreaks());
+#endif // NDEBUG
+
+    // There will always be at least one break, since the flow thread reports a "forced break" at
+    // end of content.
+    ASSERT(breakCount >= 1);
+
+    // If there is room for more breaks (to reach the used value of column-count), imagine that we
+    // insert implicit breaks at suitable locations. At any given time, the content run with the
+    // currently tallest columns will get another implicit break "inserted", which will increase its
+    // column count by one and shrink its columns' height. Repeat until we have the desired total
+    // number of breaks. The largest column height among the runs will then be the initial column
+    // height for the balancer to use.
+    while (breakCount < m_computedColumnCount) {
+        unsigned index = findRunWithTallestColumns();
+        m_contentRuns[index].assumeAnotherImplicitBreak();
+        breakCount++;
+    }
+}
+
+LayoutUnit RenderMultiColumnSet::calculateBalancedHeight(bool initial) const
+{
     if (initial) {
         // Start with the lowest imaginable column height.
-        LayoutUnit logicalHeightGuess = ceilf(float(flowThread()->logicalHeight()) / float(m_computedColumnCount));
-        logicalHeightGuess = max(logicalHeightGuess, m_minimumColumnHeight);
-        setAndConstrainColumnHeight(logicalHeightGuess);
-
-        // The multicol container now typically needs at least one more layout pass with a new
-        // column height, but if height was specified, we only need to do this if we found that we
-        // might need less space than that. On the other hand, if we determined that the columns
-        // need to be as tall as the specified height of the container, we have already laid it out
-        // correctly, and there's no need for another pass.
-        return m_computedColumnHeight != oldColumnHeight;
+        unsigned index = findRunWithTallestColumns();
+        LayoutUnit startOffset = index > 0 ? m_contentRuns[index - 1].breakOffset() : LayoutUnit();
+        return std::max<LayoutUnit>(m_contentRuns[index].columnLogicalHeight(startOffset), m_minimumColumnHeight);
     }
 
     if (columnCount() <= computedColumnCount()) {
         // With the current column height, the content fits without creating overflowing columns. We're done.
-        return false;
+        return m_computedColumnHeight;
+    }
+
+    if (forcedBreaksCount() > 1 && forcedBreaksCount() >= computedColumnCount()) {
+        // Too many forced breaks to allow any implicit breaks. Initial balancing should already
+        // have set a good height. There's nothing more we should do.
+        return m_computedColumnHeight;
     }
 
     // If the initial guessed column height wasn't enough, stretch it now. Stretch by the lowest
     // amount of space shortage found during layout.
 
-    ASSERT(currentMinSpaceShortage != LayoutUnit::max()); // If this can actually happen, we probably have a bug.
-    if (currentMinSpaceShortage == LayoutUnit::max())
-        return false; // So bail out rather than looping infinitely.
+    ASSERT(m_minSpaceShortage > 0); // We should never _shrink_ the height!
+    ASSERT(m_minSpaceShortage != RenderFlowThread::maxLogicalHeight()); // If this happens, we probably have a bug.
+    if (m_minSpaceShortage == RenderFlowThread::maxLogicalHeight())
+        return m_computedColumnHeight; // So bail out rather than looping infinitely.
 
-    setAndConstrainColumnHeight(m_computedColumnHeight + currentMinSpaceShortage);
+    return m_computedColumnHeight + m_minSpaceShortage;
+}
 
-    // If we reach the maximum column height (typically set by the height or max-height property),
-    // we may not be allowed to stretch further. Return true only if stretching
-    // succeeded. Otherwise, we're done.
-    ASSERT(m_computedColumnHeight >= oldColumnHeight); // We shouldn't be able to shrink the height!
-    return m_computedColumnHeight > oldColumnHeight;
+void RenderMultiColumnSet::clearForcedBreaks()
+{
+    m_contentRuns.clear();
+}
+
+void RenderMultiColumnSet::addForcedBreak(LayoutUnit offsetFromFirstPage)
+{
+    if (!toRenderMultiColumnBlock(parent())->requiresBalancing())
+        return;
+    if (!m_contentRuns.isEmpty() && offsetFromFirstPage <= m_contentRuns.last().breakOffset())
+        return;
+    // Append another item as long as we haven't exceeded used column count. What ends up in the
+    // overflow area shouldn't affect column balancing.
+    if (m_contentRuns.size() < m_computedColumnCount)
+        m_contentRuns.append(ContentRun(offsetFromFirstPage));
+}
+
+bool RenderMultiColumnSet::recalculateBalancedHeight(bool initial)
+{
+    ASSERT(toRenderMultiColumnBlock(parent())->requiresBalancing());
+
+    LayoutUnit oldColumnHeight = m_computedColumnHeight;
+    if (initial)
+        distributeImplicitBreaks();
+    LayoutUnit newColumnHeight = calculateBalancedHeight(initial);
+    setAndConstrainColumnHeight(newColumnHeight);
+
+    // After having calculated an initial column height, the multicol container typically needs at
+    // least one more layout pass with a new column height, but if a height was specified, we only
+    // need to do this if we think that we need less space than specified. Conversely, if we
+    // determined that the columns need to be as tall as the specified height of the container, we
+    // have already laid it out correctly, and there's no need for another pass.
+
+    if (m_computedColumnHeight == oldColumnHeight)
+        return false; // No change. We're done.
+
+    m_minSpaceShortage = RenderFlowThread::maxLogicalHeight();
+    clearForcedBreaks();
+    return true; // Need another pass.
 }
 
 void RenderMultiColumnSet::recordSpaceShortage(LayoutUnit spaceShortage)
@@ -171,12 +244,15 @@
 
     if (multicolBlock->requiresBalancing()) {
         // Set maximum column height. We will not stretch beyond this.
-        m_maxColumnHeight = LayoutUnit::max();
-        if (!multicolStyle->logicalHeight().isAuto())
+        m_maxColumnHeight = RenderFlowThread::maxLogicalHeight();
+        if (!multicolStyle->logicalHeight().isAuto()) {
             m_maxColumnHeight = multicolBlock->computeContentLogicalHeight(multicolStyle->logicalHeight(), -1);
+            if (m_maxColumnHeight == -1)
+                m_maxColumnHeight = RenderFlowThread::maxLogicalHeight();
+        }
         if (!multicolStyle->logicalMaxHeight().isUndefined()) {
             LayoutUnit logicalMaxHeight = multicolBlock->computeContentLogicalHeight(multicolStyle->logicalMaxHeight(), -1);
-            if (m_maxColumnHeight > logicalMaxHeight)
+            if (logicalMaxHeight != -1 && m_maxColumnHeight > logicalMaxHeight)
                 m_maxColumnHeight = logicalMaxHeight;
         }
         m_maxColumnHeight = heightAdjustedForSetOffset(m_maxColumnHeight);
@@ -185,6 +261,8 @@
         setAndConstrainColumnHeight(heightAdjustedForSetOffset(multicolBlock->columnHeightAvailable()));
     }
 
+    clearForcedBreaks();
+
     // Nuke previously stored minimum column height. Contents may have changed for all we know.
     m_minimumColumnHeight = 0;
 }
@@ -308,7 +386,7 @@
     if (style()->visibility() != VISIBLE)
         return;
 
-    RenderBlock::paintObject(paintInfo, paintOffset);
+    RenderBlockFlow::paintObject(paintInfo, paintOffset);
 
     // FIXME: Right now we're only painting in the foreground phase.
     // Columns should technically respect phases and allow for background/float/foreground overlap etc., just like
diff --git a/Source/core/rendering/RenderMultiColumnSet.h b/Source/core/rendering/RenderMultiColumnSet.h
index 3ebfc5e..0e0152f 100644
--- a/Source/core/rendering/RenderMultiColumnSet.h
+++ b/Source/core/rendering/RenderMultiColumnSet.h
@@ -28,6 +28,7 @@
 #define RenderMultiColumnSet_h
 
 #include "core/rendering/RenderRegionSet.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -62,30 +63,14 @@
     void updateMinimumColumnHeight(LayoutUnit height) { m_minimumColumnHeight = std::max(height, m_minimumColumnHeight); }
     LayoutUnit minimumColumnHeight() const { return m_minimumColumnHeight; }
 
-    unsigned forcedBreaksCount() const { return m_forcedBreaksCount; }
-    LayoutUnit forcedBreakOffset() const { return m_forcedBreakOffset; }
-    LayoutUnit maximumDistanceBetweenForcedBreaks() const { return m_maximumDistanceBetweenForcedBreaks; }
-    void clearForcedBreaks()
-    {
-        m_forcedBreaksCount = 0;
-        m_maximumDistanceBetweenForcedBreaks = 0;
-        m_forcedBreakOffset = 0;
-    }
-    void addForcedBreak(LayoutUnit offsetFromFirstPage)
-    {
-        ASSERT(!computedColumnHeight());
-        LayoutUnit distanceFromLastBreak = offsetFromFirstPage - m_forcedBreakOffset;
-        if (!distanceFromLastBreak)
-            return;
-        m_forcedBreaksCount++;
-        m_maximumDistanceBetweenForcedBreaks = std::max(m_maximumDistanceBetweenForcedBreaks, distanceFromLastBreak);
-        m_forcedBreakOffset = offsetFromFirstPage;
-    }
+    unsigned forcedBreaksCount() const { return m_contentRuns.size(); }
+    void clearForcedBreaks();
+    void addForcedBreak(LayoutUnit offsetFromFirstPage);
 
-    // Calculate the column height when contents are supposed to be balanced. If 'initial' is set,
-    // guess an initial column height; otherwise, stretch the column height a tad. Return true if
-    // column height changed and another layout pass is required.
-    bool calculateBalancedHeight(bool initial);
+    // (Re-)calculate the column height when contents are supposed to be balanced. If 'initial' is
+    // set, guess an initial column height; otherwise, stretch the column height a tad. Return true
+    // if column height changed and another layout pass is required.
+    bool recalculateBalancedHeight(bool initial);
 
     // Record space shortage (the amount of space that would have been enough to prevent some
     // element from being moved to the next column) at a column break. The smallest amount of space
@@ -112,15 +97,11 @@
     // FIXME: This will change once we have column sets constrained by enclosing pages, etc.
     virtual LayoutUnit logicalHeightOfAllFlowThreadContent() const OVERRIDE { return m_computedColumnHeight; }
 
-    // FIXME: For now we return false, but it's likely we will leverage the auto height region code to do column
-    // balancing. That's why we have an override of this function that is distinct from RenderRegionSet's override.
-    virtual bool shouldHaveAutoLogicalHeight() const OVERRIDE { return false; }
-
     virtual void repaintFlowThreadContent(const LayoutRect& repaintRect) const OVERRIDE;
 
     virtual void collectLayerFragments(LayerFragments&, const LayoutRect& layerBoundingBox, const LayoutRect& dirtyRect) OVERRIDE;
 
-    virtual const char* renderName() const;
+    virtual const char* renderName() const OVERRIDE;
 
     void paintColumnRules(PaintInfo&, const LayoutPoint& paintOffset);
 
@@ -139,17 +120,52 @@
 
     void setAndConstrainColumnHeight(LayoutUnit);
 
-    unsigned m_computedColumnCount;
-    LayoutUnit m_computedColumnWidth;
+    // Return the index of the content run with the currently tallest columns, taking all implicit
+    // breaks assumed so far into account.
+    unsigned findRunWithTallestColumns() const;
+
+    // Given the current list of content runs, make assumptions about where we need to insert
+    // implicit breaks (if there's room for any at all; depending on the number of explicit breaks),
+    // and store the results. This is needed in order to balance the columns.
+    void distributeImplicitBreaks();
+
+    LayoutUnit calculateBalancedHeight(bool initial) const;
+
+    unsigned m_computedColumnCount; // Used column count (the resulting 'N' from the pseudo-algorithm in the multicol spec)
+    LayoutUnit m_computedColumnWidth; // Used column width (the resulting 'W' from the pseudo-algorithm in the multicol spec)
     LayoutUnit m_computedColumnHeight;
 
     // The following variables are used when balancing the column set.
     LayoutUnit m_maxColumnHeight; // Maximum column height allowed.
     LayoutUnit m_minSpaceShortage; // The smallest amout of space shortage that caused a column break.
     LayoutUnit m_minimumColumnHeight;
-    unsigned m_forcedBreaksCount; // FIXME: We will ultimately need to cache more information to balance around forced breaks properly.
-    LayoutUnit m_maximumDistanceBetweenForcedBreaks;
-    LayoutUnit m_forcedBreakOffset;
+
+    // A run of content without explicit (forced) breaks; i.e. a flow thread portion between two
+    // explicit breaks, between flow thread start and an explicit break, between an explicit break
+    // and flow thread end, or, in cases when there are no explicit breaks at all: between flow flow
+    // thread start and flow thread end. We need to know where the explicit breaks are, in order to
+    // figure out where the implicit breaks will end up, so that we get the columns properly
+    // balanced. A content run starts out as representing one single column, and will represent one
+    // additional column for each implicit break "inserted" there.
+    class ContentRun {
+    public:
+        ContentRun(LayoutUnit breakOffset)
+            : m_breakOffset(breakOffset)
+            , m_assumedImplicitBreaks(0) { }
+
+        unsigned assumedImplicitBreaks() const { return m_assumedImplicitBreaks; }
+        void assumeAnotherImplicitBreak() { m_assumedImplicitBreaks++; }
+        LayoutUnit breakOffset() const { return m_breakOffset; }
+
+        // Return the column height that this content run would require, considering the implicit
+        // breaks assumed so far.
+        LayoutUnit columnLogicalHeight(LayoutUnit startOffset) const { return ceilf(float(m_breakOffset - startOffset) / float(m_assumedImplicitBreaks + 1)); }
+
+    private:
+        LayoutUnit m_breakOffset; // Flow thread offset where this run ends.
+        unsigned m_assumedImplicitBreaks; // Number of implicit breaks in this run assumed so far.
+    };
+    Vector<ContentRun, 1> m_contentRuns;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderMultiColumnSet, isRenderMultiColumnSet());
diff --git a/Source/core/rendering/RenderNamedFlowFragment.cpp b/Source/core/rendering/RenderNamedFlowFragment.cpp
deleted file mode 100644
index 5a754e9..0000000
--- a/Source/core/rendering/RenderNamedFlowFragment.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2013 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-#include "config.h"
-#include "core/rendering/RenderNamedFlowFragment.h"
-
-#include "core/rendering/FlowThreadController.h"
-#include "core/rendering/RenderBoxRegionInfo.h"
-#include "core/rendering/RenderFlowThread.h"
-#include "core/rendering/RenderNamedFlowThread.h"
-#include "core/rendering/RenderView.h"
-
-using namespace std;
-
-namespace WebCore {
-
-RenderNamedFlowFragment::RenderNamedFlowFragment()
-    : RenderRegion(0, 0)
-{
-}
-
-RenderNamedFlowFragment::~RenderNamedFlowFragment()
-{
-}
-
-RenderNamedFlowFragment* RenderNamedFlowFragment::createAnonymous(Document* document)
-{
-    RenderNamedFlowFragment* region = new RenderNamedFlowFragment();
-    region->setDocumentForAnonymous(document);
-    return region;
-}
-
-void RenderNamedFlowFragment::setStyleForNamedFlowFragment(const RenderStyle* parentStyle)
-{
-    RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parentStyle, BLOCK);
-
-    newStyle->setFlowThread(parentStyle->flowThread());
-    newStyle->setRegionThread(parentStyle->regionThread());
-    newStyle->setRegionFragment(parentStyle->regionFragment());
-    newStyle->setShapeInside(parentStyle->shapeInside());
-    newStyle->setOverflowX(parentStyle->overflowX());
-    newStyle->setOverflowY(parentStyle->overflowY());
-
-    setStyle(newStyle.release());
-}
-
-void RenderNamedFlowFragment::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
-    RenderRegion::styleDidChange(diff, oldStyle);
-
-    if (parent() && parent()->needsLayout())
-        setNeedsLayout();
-}
-
-// FIXME: flex items as regions with flex-basis: 0 inside a flex container
-// with flex-direction: column should not be treated as auto-height regions
-bool RenderNamedFlowFragment::shouldHaveAutoLogicalHeight() const
-{
-    ASSERT(parent());
-
-    RenderStyle* styleToUse = parent()->style();
-    bool hasSpecifiedEndpointsForHeight = styleToUse->logicalTop().isSpecified() && styleToUse->logicalBottom().isSpecified();
-    bool hasAnchoredEndpointsForHeight = isOutOfFlowPositioned() && hasSpecifiedEndpointsForHeight;
-    bool hasAutoHeightStyle = styleToUse->logicalHeight().isAuto()
-        || styleToUse->logicalHeight().isFitContent()
-        || styleToUse->logicalHeight().isMaxContent()
-        || styleToUse->logicalHeight().isMinContent();
-    return hasAutoHeightStyle && !hasAnchoredEndpointsForHeight;
-}
-
-LayoutUnit RenderNamedFlowFragment::maxPageLogicalHeight() const
-{
-    ASSERT(m_flowThread);
-    ASSERT(hasAutoLogicalHeight() && !m_flowThread->inConstrainedLayoutPhase());
-    ASSERT(isAnonymous());
-    ASSERT(parent());
-
-    RenderStyle* styleToUse = parent()->style();
-    return styleToUse->logicalMaxHeight().isUndefined() ? RenderFlowThread::maxLogicalHeight() : toRenderBlock(parent())->computeReplacedLogicalHeightUsing(styleToUse->logicalMaxHeight());
-}
-
-}
diff --git a/Source/core/rendering/RenderNamedFlowFragment.h b/Source/core/rendering/RenderNamedFlowFragment.h
deleted file mode 100644
index f02f263..0000000
--- a/Source/core/rendering/RenderNamedFlowFragment.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2013 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef RenderNamedFlowFragment_h
-#define RenderNamedFlowFragment_h
-
-#include "core/rendering/RenderRegion.h"
-
-namespace WebCore {
-
-class Element;
-class RenderStyle;
-
-// RenderNamedFlowFragment represents a region that is responsible for the fragmentation of
-// the RenderNamedFlowThread content.
-//
-// A RenderNamedFlowFragment object is created as an anonymous child for a RenderBlockFlow object
-// that has a valid -webkit-flow-from property.
-//
-// This allows a non-replaced block to behave like a region if needed, following the CSSRegions specification:
-// http://dev.w3.org/csswg/css-regions/#the-flow-from-property.
-// list-item, table-caption, table-cell can become regions in addition to block | inline-block.
-
-class RenderNamedFlowFragment FINAL : public RenderRegion {
-public:
-    virtual ~RenderNamedFlowFragment();
-    static RenderNamedFlowFragment* createAnonymous(Document*);
-
-    void setStyleForNamedFlowFragment(const RenderStyle*);
-
-    virtual bool isRenderNamedFlowFragment() const OVERRIDE { return true; }
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
-
-    virtual LayoutUnit maxPageLogicalHeight() const OVERRIDE;
-
-protected:
-    RenderNamedFlowFragment();
-
-private:
-    virtual bool shouldHaveAutoLogicalHeight() const OVERRIDE;
-    virtual const char* renderName() const OVERRIDE { return "RenderNamedFlowFragment"; }
-};
-
-inline RenderNamedFlowFragment* toRenderNamedFlowFragment(RenderObject* object)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderNamedFlowFragment());
-    return static_cast<RenderNamedFlowFragment*>(object);
-}
-
-inline const RenderNamedFlowFragment* toRenderNamedFlowFragment(const RenderObject* object)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderNamedFlowFragment());
-    return static_cast<const RenderNamedFlowFragment*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderNamedFlowFragment(const RenderNamedFlowFragment*);
-
-}
-
-#endif // RenderNamedFlowFragment_h
diff --git a/Source/core/rendering/RenderNamedFlowThread.cpp b/Source/core/rendering/RenderNamedFlowThread.cpp
deleted file mode 100644
index 7204954..0000000
--- a/Source/core/rendering/RenderNamedFlowThread.cpp
+++ /dev/null
@@ -1,730 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc.  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 APPLE INC. ``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 APPLE COMPUTER, INC. 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 IN..0TERRUPTION) 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.
- */
-
-#include "config.h"
-#include "core/rendering/RenderNamedFlowThread.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/NamedFlow.h"
-#include "core/dom/NodeRenderingTraversal.h"
-#include "core/dom/NodeTraversal.h"
-#include "core/dom/Position.h"
-#include "core/dom/Range.h"
-#include "core/dom/Text.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/rendering/FlowThreadController.h"
-#include "core/rendering/InlineTextBox.h"
-#include "core/rendering/RenderInline.h"
-#include "core/rendering/RenderRegion.h"
-#include "core/rendering/RenderText.h"
-#include "core/rendering/RenderView.h"
-
-namespace WebCore {
-
-RenderNamedFlowThread* RenderNamedFlowThread::createAnonymous(Document* document, PassRefPtr<NamedFlow> namedFlow)
-{
-    ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
-    RenderNamedFlowThread* renderer = new RenderNamedFlowThread(namedFlow);
-    renderer->setDocumentForAnonymous(document);
-    return renderer;
-}
-
-RenderNamedFlowThread::RenderNamedFlowThread(PassRefPtr<NamedFlow> namedFlow)
-    : m_overset(true)
-    , m_namedFlow(namedFlow)
-    , m_regionLayoutUpdateEventTimer(this, &RenderNamedFlowThread::regionLayoutUpdateEventTimerFired)
-    , m_regionOversetChangeEventTimer(this, &RenderNamedFlowThread::regionOversetChangeEventTimerFired)
-{
-}
-
-RenderNamedFlowThread::~RenderNamedFlowThread()
-{
-    // The flow thread can be destroyed without unregistering the content nodes if the document is destroyed.
-    // This can lead to problems because the nodes are still marked as belonging to a flow thread.
-    clearContentNodes();
-
-    // Also leave the NamedFlow object in a consistent state by calling mark for destruction.
-    setMarkForDestruction();
-}
-
-const char* RenderNamedFlowThread::renderName() const
-{
-    return "RenderNamedFlowThread";
-}
-
-void RenderNamedFlowThread::clearContentNodes()
-{
-    for (NamedFlowContentNodes::iterator it = m_contentNodes.begin(); it != m_contentNodes.end(); ++it) {
-        Node* contentNode = *it;
-
-        ASSERT(contentNode && contentNode->isElementNode());
-        ASSERT(contentNode->inNamedFlow());
-        ASSERT(contentNode->document() == document());
-
-        contentNode->clearInNamedFlow();
-    }
-
-    m_contentNodes.clear();
-}
-
-void RenderNamedFlowThread::updateWritingMode()
-{
-    RenderRegion* firstRegion = m_regionList.first();
-    if (!firstRegion)
-        return;
-    if (style()->writingMode() == firstRegion->style()->writingMode())
-        return;
-
-    // The first region defines the principal writing mode for the entire flow.
-    RefPtr<RenderStyle> newStyle = RenderStyle::clone(style());
-    newStyle->setWritingMode(firstRegion->style()->writingMode());
-    setStyle(newStyle.release());
-}
-
-RenderObject* RenderNamedFlowThread::nextRendererForNode(Node* node) const
-{
-    FlowThreadChildList::const_iterator it = m_flowThreadChildList.begin();
-    FlowThreadChildList::const_iterator end = m_flowThreadChildList.end();
-
-    for (; it != end; ++it) {
-        RenderObject* child = *it;
-        ASSERT(child->node());
-        unsigned short position = node->compareDocumentPosition(child->node());
-        if (position & Node::DOCUMENT_POSITION_FOLLOWING)
-            return child;
-    }
-
-    return 0;
-}
-
-RenderObject* RenderNamedFlowThread::previousRendererForNode(Node* node) const
-{
-    if (m_flowThreadChildList.isEmpty())
-        return 0;
-
-    FlowThreadChildList::const_iterator begin = m_flowThreadChildList.begin();
-    FlowThreadChildList::const_iterator end = m_flowThreadChildList.end();
-    FlowThreadChildList::const_iterator it = end;
-
-    do {
-        --it;
-        RenderObject* child = *it;
-        ASSERT(child->node());
-        unsigned short position = node->compareDocumentPosition(child->node());
-        if (position & Node::DOCUMENT_POSITION_PRECEDING)
-            return child;
-    } while (it != begin);
-
-    return 0;
-}
-
-void RenderNamedFlowThread::addFlowChild(RenderObject* newChild)
-{
-    // The child list is used to sort the flow thread's children render objects
-    // based on their corresponding nodes DOM order. The list is needed to avoid searching the whole DOM.
-
-    Node* childNode = newChild->node();
-
-    // Do not add anonymous objects.
-    if (!childNode)
-        return;
-
-    ASSERT(childNode->isElementNode());
-
-    RenderObject* beforeChild = nextRendererForNode(childNode);
-    if (beforeChild)
-        m_flowThreadChildList.insertBefore(beforeChild, newChild);
-    else
-        m_flowThreadChildList.add(newChild);
-}
-
-void RenderNamedFlowThread::removeFlowChild(RenderObject* child)
-{
-    m_flowThreadChildList.remove(child);
-}
-
-bool RenderNamedFlowThread::dependsOn(RenderNamedFlowThread* otherRenderFlowThread) const
-{
-    if (m_layoutBeforeThreadsSet.contains(otherRenderFlowThread))
-        return true;
-
-    // Recursively traverse the m_layoutBeforeThreadsSet.
-    RenderNamedFlowThreadCountedSet::const_iterator iterator = m_layoutBeforeThreadsSet.begin();
-    RenderNamedFlowThreadCountedSet::const_iterator end = m_layoutBeforeThreadsSet.end();
-    for (; iterator != end; ++iterator) {
-        const RenderNamedFlowThread* beforeFlowThread = (*iterator).key;
-        if (beforeFlowThread->dependsOn(otherRenderFlowThread))
-            return true;
-    }
-
-    return false;
-}
-
-// Compare two regions to determine in which one the content should flow first.
-// The function returns true if the first passed region is "less" than the second passed region.
-// If the first region appears before second region in DOM,
-// the first region is "less" than the second region.
-// If the first region is "less" than the second region, the first region receives content before second region.
-static bool compareRenderRegions(const RenderRegion* firstRegion, const RenderRegion* secondRegion)
-{
-    ASSERT(firstRegion);
-    ASSERT(secondRegion);
-
-    ASSERT(firstRegion->generatingNodeForRegion());
-    ASSERT(secondRegion->generatingNodeForRegion());
-
-    // If the regions belong to different nodes, compare their position in the DOM.
-    if (firstRegion->generatingNodeForRegion() != secondRegion->generatingNodeForRegion()) {
-        unsigned short position = firstRegion->generatingNodeForRegion()->compareDocumentPosition(secondRegion->generatingNodeForRegion());
-
-        // If the second region is contained in the first one, the first region is "less" if it's :before.
-        if (position & Node::DOCUMENT_POSITION_CONTAINED_BY) {
-            ASSERT(secondRegion->style()->styleType() == NOPSEUDO);
-            return firstRegion->style()->styleType() == BEFORE;
-        }
-
-        // If the second region contains the first region, the first region is "less" if the second is :after.
-        if (position & Node::DOCUMENT_POSITION_CONTAINS) {
-            ASSERT(firstRegion->style()->styleType() == NOPSEUDO);
-            return secondRegion->style()->styleType() == AFTER;
-        }
-
-        return (position & Node::DOCUMENT_POSITION_FOLLOWING);
-    }
-
-    // FIXME: Currently it's not possible for an element to be both a region and have pseudo-children. The case is covered anyway.
-    switch (firstRegion->style()->styleType()) {
-    case BEFORE:
-        // The second region can be the node or the after pseudo-element (before is smaller than any of those).
-        return true;
-    case AFTER:
-        // The second region can be the node or the before pseudo-element (after is greater than any of those).
-        return false;
-    case NOPSEUDO:
-        // The second region can either be the before or the after pseudo-element (the node is only smaller than the after pseudo-element).
-        return firstRegion->style()->styleType() == AFTER;
-    default:
-        break;
-    }
-
-    ASSERT_NOT_REACHED();
-    return true;
-}
-
-// This helper function adds a region to a list preserving the order property of the list.
-static void addRegionToList(RenderRegionList& regionList, RenderRegion* renderRegion)
-{
-    if (regionList.isEmpty()) {
-        regionList.add(renderRegion);
-    } else {
-        // Find the first region "greater" than renderRegion.
-        RenderRegionList::iterator it = regionList.begin();
-        while (it != regionList.end() && !compareRenderRegions(renderRegion, *it))
-            ++it;
-        regionList.insertBefore(it, renderRegion);
-    }
-}
-
-void RenderNamedFlowThread::addRegionToNamedFlowThread(RenderRegion* renderRegion)
-{
-    ASSERT(renderRegion);
-    ASSERT(!renderRegion->isValid());
-
-    if (renderRegion->parentNamedFlowThread())
-        addDependencyOnFlowThread(renderRegion->parentNamedFlowThread());
-
-    renderRegion->setIsValid(true);
-    addRegionToList(m_regionList, renderRegion);
-
-    if (m_regionList.first() == renderRegion)
-        updateWritingMode();
-}
-
-void RenderNamedFlowThread::addRegionToThread(RenderRegion* renderRegion)
-{
-    ASSERT(renderRegion);
-    ASSERT(!renderRegion->isValid());
-
-    resetMarkForDestruction();
-
-    if (renderRegion->parentNamedFlowThread() && renderRegion->parentNamedFlowThread()->dependsOn(this)) {
-        // The order of invalid regions is irrelevant.
-        m_invalidRegionList.add(renderRegion);
-        // Register ourself to get a notification when the state changes.
-        renderRegion->parentNamedFlowThread()->m_observerThreadsSet.add(this);
-        return;
-    }
-
-    addRegionToNamedFlowThread(renderRegion);
-
-    invalidateRegions();
-}
-
-void RenderNamedFlowThread::removeRegionFromThread(RenderRegion* renderRegion)
-{
-    ASSERT(renderRegion);
-
-    if (renderRegion->parentNamedFlowThread()) {
-        if (!renderRegion->isValid()) {
-            ASSERT(m_invalidRegionList.contains(renderRegion));
-            m_invalidRegionList.remove(renderRegion);
-            renderRegion->parentNamedFlowThread()->m_observerThreadsSet.remove(this);
-            // No need to invalidate the regions rectangles. The removed region
-            // was not taken into account. Just return here.
-            return;
-        }
-        removeDependencyOnFlowThread(renderRegion->parentNamedFlowThread());
-    }
-
-    ASSERT(m_regionList.contains(renderRegion));
-    bool wasFirst = m_regionList.first() == renderRegion;
-    m_regionList.remove(renderRegion);
-
-    if (canBeDestroyed())
-        setMarkForDestruction();
-
-    // After removing all the regions in the flow the following layout needs to dispatch the regionLayoutUpdate event
-    if (m_regionList.isEmpty())
-        setDispatchRegionLayoutUpdateEvent(true);
-    else if (wasFirst)
-        updateWritingMode();
-
-    invalidateRegions();
-}
-
-void RenderNamedFlowThread::regionChangedWritingMode(RenderRegion* region)
-{
-    if (m_regionList.first() == region)
-        updateWritingMode();
-}
-
-void RenderNamedFlowThread::computeOversetStateForRegions(LayoutUnit oldClientAfterEdge)
-{
-    LayoutUnit height = oldClientAfterEdge;
-
-    // FIXME: the visual overflow of middle region (if it is the last one to contain any content in a render flow thread)
-    // might not be taken into account because the render flow thread height is greater that that regions height + its visual overflow
-    // because of how computeLogicalHeight is implemented for RenderFlowThread (as a sum of all regions height).
-    // This means that the middle region will be marked as fit (even if it has visual overflow flowing into the next region)
-    if (hasRenderOverflow()
-        && ( (isHorizontalWritingMode() && visualOverflowRect().maxY() > clientBoxRect().maxY())
-            || (!isHorizontalWritingMode() && visualOverflowRect().maxX() > clientBoxRect().maxX())))
-        height = isHorizontalWritingMode() ? visualOverflowRect().maxY() : visualOverflowRect().maxX();
-
-    RenderRegion* lastReg = lastRegion();
-    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        LayoutUnit flowMin = height - (isHorizontalWritingMode() ? region->flowThreadPortionRect().y() : region->flowThreadPortionRect().x());
-        LayoutUnit flowMax = height - (isHorizontalWritingMode() ? region->flowThreadPortionRect().maxY() : region->flowThreadPortionRect().maxX());
-        RegionOversetState previousState = region->regionOversetState();
-        RegionOversetState state = RegionFit;
-        if (flowMin <= 0)
-            state = RegionEmpty;
-        if (flowMax > 0 && region == lastReg)
-            state = RegionOverset;
-        region->setRegionOversetState(state);
-        // determine whether the NamedFlow object should dispatch a regionLayoutUpdate event
-        // FIXME: currently it cannot determine whether a region whose regionOverset state remained either "fit" or "overset" has actually
-        // changed, so it just assumes that the NamedFlow should dispatch the event
-        if (previousState != state
-            || state == RegionFit
-            || state == RegionOverset)
-            setDispatchRegionLayoutUpdateEvent(true);
-
-        if (previousState != state)
-            setDispatchRegionOversetChangeEvent(true);
-    }
-
-    // If the number of regions has changed since we last computed the overset property, schedule the regionOversetChange event.
-    if (previousRegionCountChanged()) {
-        setDispatchRegionOversetChangeEvent(true);
-        updatePreviousRegionCount();
-    }
-
-    // With the regions overflow state computed we can also set the overset flag for the named flow.
-    // If there are no valid regions in the chain, overset is true.
-    m_overset = lastReg ? lastReg->regionOversetState() == RegionOverset : true;
-}
-
-void RenderNamedFlowThread::checkInvalidRegions()
-{
-    Vector<RenderRegion*> newValidRegions;
-    for (RenderRegionList::iterator iter = m_invalidRegionList.begin(); iter != m_invalidRegionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        // The only reason a region would be invalid is because it has a parent flow thread.
-        ASSERT(!region->isValid() && region->parentNamedFlowThread());
-        if (region->parentNamedFlowThread()->dependsOn(this))
-            continue;
-
-        newValidRegions.append(region);
-    }
-
-    for (Vector<RenderRegion*>::iterator iter = newValidRegions.begin(); iter != newValidRegions.end(); ++iter) {
-        RenderRegion* region = *iter;
-        m_invalidRegionList.remove(region);
-        region->parentNamedFlowThread()->m_observerThreadsSet.remove(this);
-        addRegionToNamedFlowThread(region);
-    }
-
-    if (!newValidRegions.isEmpty())
-        invalidateRegions();
-
-    if (m_observerThreadsSet.isEmpty())
-        return;
-
-    // Notify all the flow threads that were dependent on this flow.
-
-    // Create a copy of the list first. That's because observers might change the list when calling checkInvalidRegions.
-    Vector<RenderNamedFlowThread*> observers;
-    copyToVector(m_observerThreadsSet, observers);
-
-    for (size_t i = 0; i < observers.size(); ++i) {
-        RenderNamedFlowThread* flowThread = observers.at(i);
-        flowThread->checkInvalidRegions();
-    }
-}
-
-void RenderNamedFlowThread::addDependencyOnFlowThread(RenderNamedFlowThread* otherFlowThread)
-{
-    RenderNamedFlowThreadCountedSet::AddResult result = m_layoutBeforeThreadsSet.add(otherFlowThread);
-    if (result.isNewEntry) {
-        // This is the first time we see this dependency. Make sure we recalculate all the dependencies.
-        view()->flowThreadController()->setIsRenderNamedFlowThreadOrderDirty(true);
-    }
-}
-
-void RenderNamedFlowThread::removeDependencyOnFlowThread(RenderNamedFlowThread* otherFlowThread)
-{
-    bool removed = m_layoutBeforeThreadsSet.remove(otherFlowThread);
-    if (removed) {
-        checkInvalidRegions();
-        view()->flowThreadController()->setIsRenderNamedFlowThreadOrderDirty(true);
-    }
-}
-
-void RenderNamedFlowThread::pushDependencies(RenderNamedFlowThreadList& list)
-{
-    for (RenderNamedFlowThreadCountedSet::iterator iter = m_layoutBeforeThreadsSet.begin(); iter != m_layoutBeforeThreadsSet.end(); ++iter) {
-        RenderNamedFlowThread* flowThread = (*iter).key;
-        if (list.contains(flowThread))
-            continue;
-        flowThread->pushDependencies(list);
-        list.add(flowThread);
-    }
-}
-
-// The content nodes list contains those nodes with -webkit-flow-into: flow.
-// An element with display:none should also be listed among those nodes.
-// The list of nodes is ordered.
-void RenderNamedFlowThread::registerNamedFlowContentNode(Node* contentNode)
-{
-    ASSERT(contentNode && contentNode->isElementNode());
-    ASSERT(contentNode->document() == document());
-
-    contentNode->setInNamedFlow();
-
-    resetMarkForDestruction();
-
-    // Find the first content node following the new content node.
-    for (NamedFlowContentNodes::iterator it = m_contentNodes.begin(); it != m_contentNodes.end(); ++it) {
-        Node* node = *it;
-        unsigned short position = contentNode->compareDocumentPosition(node);
-        if (position & Node::DOCUMENT_POSITION_FOLLOWING) {
-            m_contentNodes.insertBefore(node, contentNode);
-            return;
-        }
-    }
-    m_contentNodes.add(contentNode);
-}
-
-void RenderNamedFlowThread::unregisterNamedFlowContentNode(Node* contentNode)
-{
-    ASSERT(contentNode && contentNode->isElementNode());
-    ASSERT(m_contentNodes.contains(contentNode));
-    ASSERT(contentNode->inNamedFlow());
-    ASSERT(contentNode->document() == document());
-
-    contentNode->clearInNamedFlow();
-    m_contentNodes.remove(contentNode);
-
-    if (canBeDestroyed())
-        setMarkForDestruction();
-}
-
-const AtomicString& RenderNamedFlowThread::flowThreadName() const
-{
-    return m_namedFlow->name();
-}
-
-bool RenderNamedFlowThread::isChildAllowed(RenderObject* child, RenderStyle* style) const
-{
-    if (!child->node())
-        return true;
-
-    ASSERT(child->node()->isElementNode());
-    Node* originalParent = NodeRenderingTraversal::parent(child->node());
-    if (!originalParent || !originalParent->renderer())
-        return true;
-
-    return originalParent->renderer()->isChildAllowed(child, style);
-}
-
-void RenderNamedFlowThread::dispatchRegionLayoutUpdateEvent()
-{
-    RenderFlowThread::dispatchRegionLayoutUpdateEvent();
-    InspectorInstrumentation::didUpdateRegionLayout(&document(), m_namedFlow.get());
-
-    if (!m_regionLayoutUpdateEventTimer.isActive() && m_namedFlow->hasEventListeners())
-        m_regionLayoutUpdateEventTimer.startOneShot(0);
-}
-
-void RenderNamedFlowThread::dispatchRegionOversetChangeEvent()
-{
-    RenderFlowThread::dispatchRegionOversetChangeEvent();
-    InspectorInstrumentation::didChangeRegionOverset(&document(), m_namedFlow.get());
-
-    if (!m_regionOversetChangeEventTimer.isActive() && m_namedFlow->hasEventListeners())
-        m_regionOversetChangeEventTimer.startOneShot(0);
-}
-
-void RenderNamedFlowThread::regionLayoutUpdateEventTimerFired(Timer<RenderNamedFlowThread>*)
-{
-    ASSERT(m_namedFlow);
-
-    m_namedFlow->dispatchRegionLayoutUpdateEvent();
-}
-
-void RenderNamedFlowThread::regionOversetChangeEventTimerFired(Timer<RenderNamedFlowThread>*)
-{
-    ASSERT(m_namedFlow);
-
-    m_namedFlow->dispatchRegionOversetChangeEvent();
-}
-
-void RenderNamedFlowThread::setMarkForDestruction()
-{
-    if (m_namedFlow->flowState() == NamedFlow::FlowStateNull)
-        return;
-
-    m_namedFlow->setRenderer(0);
-    // After this call ends, the renderer can be safely destroyed.
-    // The NamedFlow object may outlive its renderer if it's referenced from a script and may be reatached to one if the named flow is recreated in the stylesheet.
-}
-
-void RenderNamedFlowThread::resetMarkForDestruction()
-{
-    if (m_namedFlow->flowState() == NamedFlow::FlowStateCreated)
-        return;
-
-    m_namedFlow->setRenderer(this);
-}
-
-bool RenderNamedFlowThread::isMarkedForDestruction() const
-{
-    // Flow threads in the "NULL" state can be destroyed.
-    return m_namedFlow->flowState() == NamedFlow::FlowStateNull;
-}
-
-static bool isContainedInNodes(Vector<Node*> others, Node* node)
-{
-    for (size_t i = 0; i < others.size(); i++) {
-        Node* other = others.at(i);
-        if (other->contains(node))
-            return true;
-    }
-    return false;
-}
-
-static bool boxIntersectsRegion(LayoutUnit logicalTopForBox, LayoutUnit logicalBottomForBox, LayoutUnit logicalTopForRegion, LayoutUnit logicalBottomForRegion)
-{
-    bool regionIsEmpty = logicalBottomForRegion != LayoutUnit::max() && logicalTopForRegion != LayoutUnit::min()
-        && (logicalBottomForRegion - logicalTopForRegion) <= 0;
-    return  (logicalBottomForBox - logicalTopForBox) > 0
-        && !regionIsEmpty
-        && logicalTopForBox < logicalBottomForRegion && logicalTopForRegion < logicalBottomForBox;
-}
-
-// Retrieve the next node to be visited while computing the ranges inside a region.
-static Node* nextNodeInsideContentNode(const Node& currNode, const Node* contentNode)
-{
-    ASSERT(contentNode && contentNode->inNamedFlow());
-
-    if (currNode.renderer() && currNode.renderer()->isSVGRoot())
-        return NodeTraversal::nextSkippingChildren(currNode, contentNode);
-    return NodeTraversal::next(currNode, contentNode);
-}
-
-void RenderNamedFlowThread::getRanges(Vector<RefPtr<Range> >& rangeObjects, const RenderRegion* region) const
-{
-    LayoutUnit logicalTopForRegion;
-    LayoutUnit logicalBottomForRegion;
-
-    // extend the first region top to contain everything up to its logical height
-    if (region->isFirstRegion())
-        logicalTopForRegion = LayoutUnit::min();
-    else
-        logicalTopForRegion =  region->logicalTopForFlowThreadContent();
-
-    // extend the last region to contain everything above its y()
-    if (region->isLastRegion())
-        logicalBottomForRegion = LayoutUnit::max();
-    else
-        logicalBottomForRegion = region->logicalBottomForFlowThreadContent();
-
-    Vector<Node*> nodes;
-    // eliminate the contentNodes that are descendants of other contentNodes
-    for (NamedFlowContentNodes::const_iterator it = contentNodes().begin(); it != contentNodes().end(); ++it) {
-        Node* node = *it;
-        if (!isContainedInNodes(nodes, node))
-            nodes.append(node);
-    }
-
-    for (size_t i = 0; i < nodes.size(); i++) {
-        Node* contentNode = nodes.at(i);
-        if (!contentNode->renderer())
-            continue;
-
-        RefPtr<Range> range = Range::create(contentNode->document());
-        bool foundStartPosition = false;
-        bool startsAboveRegion = true;
-        bool endsBelowRegion = true;
-        bool skipOverOutsideNodes = false;
-        Node* lastEndNode = 0;
-
-        for (Node* node = contentNode; node; node = nextNodeInsideContentNode(*node, contentNode)) {
-            RenderObject* renderer = node->renderer();
-            if (!renderer)
-                continue;
-
-            LayoutRect boundingBox;
-            if (renderer->isRenderInline()) {
-                boundingBox = toRenderInline(renderer)->linesBoundingBox();
-            } else if (renderer->isText()) {
-                boundingBox = toRenderText(renderer)->linesBoundingBox();
-            } else {
-                boundingBox =  toRenderBox(renderer)->frameRect();
-                if (toRenderBox(renderer)->isRelPositioned())
-                    boundingBox.move(toRenderBox(renderer)->relativePositionLogicalOffset());
-            }
-
-            LayoutUnit offsetTop = renderer->containingBlock()->offsetFromLogicalTopOfFirstPage();
-            const LayoutPoint logicalOffsetFromTop(isHorizontalWritingMode() ? LayoutUnit() :  offsetTop,
-                isHorizontalWritingMode() ? offsetTop : LayoutUnit());
-
-            boundingBox.moveBy(logicalOffsetFromTop);
-
-            LayoutUnit logicalTopForRenderer = region->logicalTopOfFlowThreadContentRect(boundingBox);
-            LayoutUnit logicalBottomForRenderer = region->logicalBottomOfFlowThreadContentRect(boundingBox);
-
-            // if the bounding box of the current element doesn't intersect the region box
-            // close the current range only if the start element began inside the region,
-            // otherwise just move the start position after this node and keep skipping them until we found a proper start position.
-            if (!boxIntersectsRegion(logicalTopForRenderer, logicalBottomForRenderer, logicalTopForRegion, logicalBottomForRegion)) {
-                if (foundStartPosition) {
-                    if (!startsAboveRegion) {
-                        if (range->intersectsNode(node, IGNORE_EXCEPTION))
-                            range->setEndBefore(node, IGNORE_EXCEPTION);
-                        rangeObjects.append(range->cloneRange(IGNORE_EXCEPTION));
-                        range = Range::create(contentNode->document());
-                        startsAboveRegion = true;
-                    } else {
-                        skipOverOutsideNodes = true;
-                    }
-                }
-                if (skipOverOutsideNodes)
-                    range->setStartAfter(node, IGNORE_EXCEPTION);
-                foundStartPosition = false;
-                continue;
-            }
-
-            // start position
-            if (logicalTopForRenderer < logicalTopForRegion && startsAboveRegion) {
-                if (renderer->isText()) { // Text crosses region top
-                    // for Text elements, just find the last textbox that is contained inside the region and use its start() offset as start position
-                    RenderText* textRenderer = toRenderText(renderer);
-                    for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
-                        if (offsetTop + box->logicalBottom() < logicalTopForRegion)
-                            continue;
-                        range->setStart(Position(toText(node), box->start()));
-                        startsAboveRegion = false;
-                        break;
-                    }
-                } else { // node crosses region top
-                    // for all elements, except Text, just set the start position to be before their children
-                    startsAboveRegion = true;
-                    range->setStart(Position(node, Position::PositionIsBeforeChildren));
-                }
-            } else { // node starts inside region
-                // for elements that start inside the region, set the start position to be before them. If we found one, we will just skip the others until
-                // the range is closed.
-                if (startsAboveRegion) {
-                    startsAboveRegion = false;
-                    range->setStartBefore(node, IGNORE_EXCEPTION);
-                }
-            }
-            skipOverOutsideNodes  = false;
-            foundStartPosition = true;
-
-            // end position
-            if (logicalBottomForRegion < logicalBottomForRenderer && (endsBelowRegion || (!endsBelowRegion && !node->isDescendantOf(lastEndNode)))) {
-                // for Text elements, just find just find the last textbox that is contained inside the region and use its start()+len() offset as end position
-                if (renderer->isText()) { // Text crosses region bottom
-                    RenderText* textRenderer = toRenderText(renderer);
-                    InlineTextBox* lastBox = 0;
-                    for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
-                        if ((offsetTop + box->logicalTop()) < logicalBottomForRegion) {
-                            lastBox = box;
-                            continue;
-                        }
-                        ASSERT(lastBox);
-                        if (lastBox)
-                            range->setEnd(Position(toText(node), lastBox->start() + lastBox->len()));
-                        break;
-                    }
-                    endsBelowRegion = false;
-                    lastEndNode = node;
-                } else { // node crosses region bottom
-                    // for all elements, except Text, just set the start position to be after their children
-                    range->setEnd(Position(node, Position::PositionIsAfterChildren));
-                    endsBelowRegion = true;
-                    lastEndNode = node;
-                }
-            } else { // node ends inside region
-                // for elements that ends inside the region, set the end position to be after them
-                // allow this end position to be changed only by other elements that are not descendants of the current end node
-                if (endsBelowRegion || (!endsBelowRegion && !node->isDescendantOf(lastEndNode))) {
-                    range->setEndAfter(node, IGNORE_EXCEPTION);
-                    endsBelowRegion = false;
-                    lastEndNode = node;
-                }
-            }
-        }
-        if (foundStartPosition || skipOverOutsideNodes)
-            rangeObjects.append(range);
-    }
-}
-
-}
diff --git a/Source/core/rendering/RenderNamedFlowThread.h b/Source/core/rendering/RenderNamedFlowThread.h
deleted file mode 100644
index 6528c11..0000000
--- a/Source/core/rendering/RenderNamedFlowThread.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc.  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 APPLE INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-
-#ifndef RenderNamedFlowThread_h
-#define RenderNamedFlowThread_h
-
-#include "core/rendering/RenderFlowThread.h"
-#include "platform/Timer.h"
-#include "wtf/HashCountedSet.h"
-#include "wtf/ListHashSet.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class NamedFlow;
-class Node;
-class RenderNamedFlowThread;
-
-typedef ListHashSet<RenderNamedFlowThread*> RenderNamedFlowThreadList;
-typedef HashCountedSet<RenderNamedFlowThread*> RenderNamedFlowThreadCountedSet;
-typedef ListHashSet<Node*> NamedFlowContentNodes;
-
-class RenderNamedFlowThread FINAL : public RenderFlowThread {
-public:
-    virtual ~RenderNamedFlowThread();
-
-    static RenderNamedFlowThread* createAnonymous(Document*, PassRefPtr<NamedFlow>);
-
-    const AtomicString& flowThreadName() const;
-
-    const RenderRegionList& invalidRenderRegionList() const { return m_invalidRegionList; }
-
-    RenderObject* nextRendererForNode(Node*) const;
-    RenderObject* previousRendererForNode(Node*) const;
-
-    void addFlowChild(RenderObject* newChild);
-    void removeFlowChild(RenderObject*);
-    bool hasChildren() const { return !m_flowThreadChildList.isEmpty(); }
-#ifndef NDEBUG
-    bool hasChild(RenderObject* child) const { return m_flowThreadChildList.contains(child); }
-#endif
-
-    void pushDependencies(RenderNamedFlowThreadList&);
-
-    virtual void addRegionToThread(RenderRegion*) OVERRIDE;
-    virtual void removeRegionFromThread(RenderRegion*) OVERRIDE;
-
-    virtual void regionChangedWritingMode(RenderRegion*) OVERRIDE;
-
-    bool overset() const { return m_overset; }
-    void computeOversetStateForRegions(LayoutUnit oldClientAfterEdge);
-
-    void registerNamedFlowContentNode(Node*);
-    void unregisterNamedFlowContentNode(Node*);
-    const NamedFlowContentNodes& contentNodes() const { return m_contentNodes; }
-    bool hasContentNode(Node* contentNode) const { ASSERT(contentNode); return m_contentNodes.contains(contentNode); }
-    bool isMarkedForDestruction() const;
-    void getRanges(Vector<RefPtr<Range> >&, const RenderRegion*) const;
-
-protected:
-    void setMarkForDestruction();
-    void resetMarkForDestruction();
-
-private:
-    RenderNamedFlowThread(PassRefPtr<NamedFlow>);
-
-    virtual const char* renderName() const OVERRIDE;
-    virtual bool isRenderNamedFlowThread() const OVERRIDE { return true; }
-    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
-
-    virtual void dispatchRegionLayoutUpdateEvent() OVERRIDE;
-    virtual void dispatchRegionOversetChangeEvent() OVERRIDE;
-
-    bool dependsOn(RenderNamedFlowThread* otherRenderFlowThread) const;
-    void addDependencyOnFlowThread(RenderNamedFlowThread*);
-    void removeDependencyOnFlowThread(RenderNamedFlowThread*);
-
-    void addRegionToNamedFlowThread(RenderRegion*);
-
-    void checkInvalidRegions();
-
-    bool canBeDestroyed() const { return m_invalidRegionList.isEmpty() && m_regionList.isEmpty() && m_contentNodes.isEmpty(); }
-    void regionLayoutUpdateEventTimerFired(Timer<RenderNamedFlowThread>*);
-    void regionOversetChangeEventTimerFired(Timer<RenderNamedFlowThread>*);
-    void clearContentNodes();
-    void updateWritingMode();
-
-private:
-    // Observer flow threads have invalid regions that depend on the state of this thread
-    // to re-validate their regions. Keeping a set of observer threads make it easy
-    // to notify them when a region was removed from this flow.
-    RenderNamedFlowThreadCountedSet m_observerThreadsSet;
-
-    // Some threads need to have a complete layout before we layout this flow.
-    // That's because they contain a RenderRegion that should display this thread. The set makes it
-    // easy to sort the order of threads layout.
-    RenderNamedFlowThreadCountedSet m_layoutBeforeThreadsSet;
-
-    // Holds the sorted children of a named flow. This is the only way we can get the ordering right.
-    typedef ListHashSet<RenderObject*> FlowThreadChildList;
-    FlowThreadChildList m_flowThreadChildList;
-
-    NamedFlowContentNodes m_contentNodes;
-
-    RenderRegionList m_invalidRegionList;
-
-    bool m_overset : 1;
-
-    // The DOM Object that represents a named flow.
-    RefPtr<NamedFlow> m_namedFlow;
-
-    Timer<RenderNamedFlowThread> m_regionLayoutUpdateEventTimer;
-    Timer<RenderNamedFlowThread> m_regionOversetChangeEventTimer;
-};
-
-DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderNamedFlowThread, isRenderNamedFlowThread());
-
-} // namespace WebCore
-
-#endif // RenderNamedFlowThread_h
-
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index 10b5709..a778300 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -35,6 +35,7 @@
 #include "core/editing/EditingBoundary.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/htmlediting.h"
+#include "core/fetch/ResourceLoadPriorityOptimizer.h"
 #include "core/fetch/ResourceLoader.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLElement.h"
@@ -45,9 +46,8 @@
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/frame/UseCounter.h"
-#include "core/frame/animation/AnimationController.h"
 #include "core/rendering/CompositedLayerMapping.h"
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/HitTestResult.h"
@@ -55,6 +55,7 @@
 #include "core/rendering/RenderCounter.h"
 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
 #include "core/rendering/RenderFlexibleBox.h"
+#include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderGrid.h"
 #include "core/rendering/RenderImage.h"
@@ -65,10 +66,6 @@
 #include "core/rendering/RenderListItem.h"
 #include "core/rendering/RenderMarquee.h"
 #include "core/rendering/RenderMultiColumnBlock.h"
-#include "core/rendering/RenderNamedFlowThread.h"
-#include "core/rendering/RenderRegion.h"
-#include "core/rendering/RenderRuby.h"
-#include "core/rendering/RenderRubyText.h"
 #include "core/rendering/RenderScrollbarPart.h"
 #include "core/rendering/RenderTableCaption.h"
 #include "core/rendering/RenderTableCell.h"
@@ -140,8 +137,6 @@
 
 RenderObject* RenderObject::createObject(Element* element, RenderStyle* style)
 {
-    Document& doc = element->document();
-
     // Minimal support for content properties replacing an entire element.
     // Works only if we have exactly one piece of content and it's a URL.
     // Otherwise acts as if we didn't support this feature.
@@ -161,16 +156,6 @@
         return image;
     }
 
-    if (element->hasTagName(rubyTag)) {
-        if (style->display() == INLINE)
-            return new RenderRubyAsInline(element);
-        else if (style->display() == BLOCK)
-            return new RenderRubyAsBlock(element);
-    }
-    // treat <rt> as ruby text ONLY if it still has its default treatment of block
-    if (element->hasTagName(rtTag) && style->display() == BLOCK)
-        return new RenderRubyText(element);
-
     switch (style->display()) {
     case NONE:
         return 0;
@@ -178,7 +163,7 @@
         return new RenderInline(element);
     case BLOCK:
     case INLINE_BLOCK:
-        if ((!style->hasAutoColumnCount() || !style->hasAutoColumnWidth()) && doc.regionBasedColumnsEnabled())
+        if ((!style->hasAutoColumnCount() || !style->hasAutoColumnWidth()) && element->document().regionBasedColumnsEnabled())
             return new RenderMultiColumnBlock(element);
         return new RenderBlockFlow(element);
     case LIST_ITEM:
@@ -235,6 +220,7 @@
 
 RenderObject::~RenderObject()
 {
+    ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
 #ifndef NDEBUG
     ASSERT(!m_hasAXObject);
     renderObjectCounter.decrement();
@@ -280,14 +266,12 @@
 
 void RenderObject::setFlowThreadStateIncludingDescendants(FlowThreadState state)
 {
-    setFlowThreadState(state);
-
-    for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
-        // If the child is a fragmentation context it already updated the descendants flag accordingly.
-        if (child->isRenderFlowThread())
+    for (RenderObject *object = this; object; object = object->nextInPreOrder(this)) {
+        // If object is a fragmentation context it already updated the descendants flag accordingly.
+        if (object->isRenderFlowThread())
             continue;
-        ASSERT(state != child->flowThreadState());
-        child->setFlowThreadStateIncludingDescendants(state);
+        ASSERT(state != object->flowThreadState());
+        object->setFlowThreadState(state);
     }
 }
 
@@ -340,7 +324,7 @@
     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
     // <g>s to have renderers - at least that's how our implementation works. Consider:
     // <g display="none"><foreignObject><body style="position: relative">FOO...
-    // - requiresLayer() would return true for the <body>, creating a new RenderLayer
+    // - layerTypeRequired() would return true for the <body>, creating a new RenderLayer
     // - when the document is painted, both layers are painted. The <body> layer doesn't
     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
@@ -431,19 +415,6 @@
     return child;
 }
 
-RenderObject* RenderObject::firstLeafChild() const
-{
-    RenderObject* r = firstChild();
-    while (r) {
-        RenderObject* n = 0;
-        n = r->firstChild();
-        if (!n)
-            break;
-        r = n;
-    }
-    return r;
-}
-
 RenderObject* RenderObject::lastLeafChild() const
 {
     RenderObject* r = lastChild();
@@ -635,15 +606,6 @@
     return 0;
 }
 
-RenderNamedFlowThread* RenderObject::renderNamedFlowThreadWrapper() const
-{
-    RenderObject* object = const_cast<RenderObject*>(this);
-    while (object && object->isAnonymousBlock() && !object->isRenderNamedFlowThread())
-        object = object->parent();
-
-    return object && object->isRenderNamedFlowThread() ? toRenderNamedFlowThread(object) : 0;
-}
-
 RenderBlock* RenderObject::firstLineBlock() const
 {
     return 0;
@@ -840,6 +802,9 @@
             o = o->parent();
         }
 
+        if (o && !o->isRenderBlock())
+            o = o->containingBlock();
+
         while (o && o->isAnonymousBlock())
             o = o->containingBlock();
     } else {
@@ -1358,6 +1323,9 @@
 
     if (v->usesCompositing()) {
         if (RenderLayer* parentLayer = enclosingLayer()) {
+            // FIXME: CompositingState is not necessarily up to date for many callers of this function.
+            DisableCompositingQueryAsserts disabler;
+
             RenderLayer* compLayer = parentLayer->enclosingCompositingLayerForRepaint();
             if (compLayer)
                 repaintContainer = compLayer->renderer();
@@ -1397,6 +1365,36 @@
         return;
     }
 
+    // FIXME: Don't read compositing state here since we do this in the middle of recalc/layout.
+    DisableCompositingQueryAsserts disabler;
+    if (repaintContainer->compositingState() == PaintsIntoGroupedBacking) {
+        ASSERT(repaintContainer->groupedMapping());
+
+        // Not clean, but if squashing layer does not yet exist here (e.g. repaint invalidation coming from within recomputing compositing requirements)
+        // then it's ok to just exit here, since the squashing layer will get repainted when it is newly created.
+        if (!repaintContainer->groupedMapping()->squashingLayer())
+            return;
+
+
+        IntRect offsetRect(r);
+
+        // First, convert the repaint rect into the space of the repaintContainer
+        TransformState transformState(TransformState::ApplyTransformDirection, FloatQuad(FloatRect(r)));
+        mapLocalToContainer(repaintContainer, transformState, ApplyContainerFlip);
+        transformState.flatten();
+        offsetRect = transformState.lastPlanarQuad().enclosingBoundingBox();
+
+        // FIXME: the repaint rect computed below could be tighter in uncommon nested transform cases, if we passed the quad
+        // directly to the next chunk of code.
+
+        // Then, convert the repaint rect from repaintConainer space into the squashing GraphicsLayer's coordinates.
+        if (repaintContainer->hasTransform())
+            offsetRect = repaintContainer->layer()->transform()->mapRect(r);
+        offsetRect.move(-repaintContainer->layer()->offsetFromSquashingLayerOrigin());
+        repaintContainer->groupedMapping()->squashingLayer()->setNeedsDisplayInRect(offsetRect);
+        return;
+    }
+
     if (repaintContainer->isRenderFlowThread()) {
         toRenderFlowThread(repaintContainer)->repaintRectangleInRegions(r);
         return;
@@ -1412,10 +1410,7 @@
         ASSERT(repaintContainer == v);
         bool viewHasCompositedLayer = v->hasLayer() && v->layer()->compositingState() == PaintsIntoOwnBacking;
         if (!viewHasCompositedLayer) {
-            IntRect repaintRectangle = r;
-            if (viewHasCompositedLayer &&  v->layer()->transform())
-                repaintRectangle = v->layer()->transform()->mapRect(r);
-            v->repaintViewRectangle(repaintRectangle);
+            v->repaintViewRectangle(r);
             return;
         }
     }
@@ -1436,6 +1431,9 @@
     if (view->document().printing())
         return; // Don't repaint if we're printing.
 
+    // FIXME: really, we're in the repaint phase here, and the following queries are legal.
+    // Until those states are fully fledged, I'll just disable the ASSERTS.
+    DisableCompositingQueryAsserts disabler;
     RenderLayerModelObject* repaintContainer = containerForRepaint();
     repaintUsingContainer(repaintContainer ? repaintContainer : view, pixelSnappedIntRect(clippedOverflowRectForRepaint(repaintContainer)));
 }
@@ -1452,9 +1450,11 @@
 
     LayoutRect dirtyRect(r);
 
-    // FIXME: layoutDelta needs to be applied in parts before/after transforms and
-    // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
-    dirtyRect.move(view->layoutDelta());
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+        // FIXME: layoutDelta needs to be applied in parts before/after transforms and
+        // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
+        dirtyRect.move(view->layoutDelta());
+    }
 
     RenderLayerModelObject* repaintContainer = containerForRepaint();
     computeRectForRepaint(repaintContainer, dirtyRect);
@@ -1486,8 +1486,8 @@
     if (!fullRepaint && style()->hasBorderRadius()) {
         // If a border-radius exists and width/height is smaller than
         // radius width/height, we cannot use delta-repaint.
-        RoundedRect oldRoundedRect = style()->getRoundedBorderFor(oldBounds, v);
-        RoundedRect newRoundedRect = style()->getRoundedBorderFor(newBounds, v);
+        RoundedRect oldRoundedRect = style()->getRoundedBorderFor(oldBounds);
+        RoundedRect newRoundedRect = style()->getRoundedBorderFor(newBounds);
         fullRepaint = oldRoundedRect.radii() != newRoundedRect.radii();
     }
     if (!fullRepaint) {
@@ -1551,11 +1551,12 @@
         int borderRight = isBox() ? toRenderBox(this)->borderRight() : 0;
         LayoutUnit boxWidth = isBox() ? toRenderBox(this)->width() : LayoutUnit();
         LayoutUnit minInsetRightShadowExtent = min<LayoutUnit>(-insetShadowExtent.right(), min<LayoutUnit>(newBounds.width(), oldBounds.width()));
-        LayoutUnit borderWidth = max<LayoutUnit>(borderRight, max<LayoutUnit>(valueForLength(style()->borderTopRightRadius().width(), boxWidth, v), valueForLength(style()->borderBottomRightRadius().width(), boxWidth, v)));
-        LayoutUnit decorationsWidth = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderWidth + minInsetRightShadowExtent) + max<LayoutUnit>(outlineWidth, shadowRight);
-        LayoutRect rightRect(newOutlineBox.x() + min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
+        LayoutUnit borderWidth = max<LayoutUnit>(borderRight, max<LayoutUnit>(valueForLength(style()->borderTopRightRadius().width(), boxWidth), valueForLength(style()->borderBottomRightRadius().width(), boxWidth)));
+        LayoutUnit decorationsLeftWidth = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderWidth + minInsetRightShadowExtent) + max<LayoutUnit>(outlineWidth, -shadowLeft);
+        LayoutUnit decorationsRightWidth = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderWidth + minInsetRightShadowExtent) + max<LayoutUnit>(outlineWidth, shadowRight);
+        LayoutRect rightRect(newOutlineBox.x() + min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsLeftWidth,
             newOutlineBox.y(),
-            width + decorationsWidth,
+            width + decorationsLeftWidth + decorationsRightWidth,
             max(newOutlineBox.height(), oldOutlineBox.height()));
         LayoutUnit right = min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
         if (rightRect.x() < right) {
@@ -1571,12 +1572,13 @@
         int borderBottom = isBox() ? toRenderBox(this)->borderBottom() : 0;
         LayoutUnit boxHeight = isBox() ? toRenderBox(this)->height() : LayoutUnit();
         LayoutUnit minInsetBottomShadowExtent = min<LayoutUnit>(-insetShadowExtent.bottom(), min<LayoutUnit>(newBounds.height(), oldBounds.height()));
-        LayoutUnit borderHeight = max<LayoutUnit>(borderBottom, max<LayoutUnit>(valueForLength(style()->borderBottomLeftRadius().height(), boxHeight, v), valueForLength(style()->borderBottomRightRadius().height(), boxHeight, v)));
-        LayoutUnit decorationsHeight = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderHeight + minInsetBottomShadowExtent) + max<LayoutUnit>(outlineWidth, shadowBottom);
+        LayoutUnit borderHeight = max<LayoutUnit>(borderBottom, max<LayoutUnit>(valueForLength(style()->borderBottomLeftRadius().height(), boxHeight), valueForLength(style()->borderBottomRightRadius().height(), boxHeight)));
+        LayoutUnit decorationsTopHeight = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderHeight + minInsetBottomShadowExtent) + max<LayoutUnit>(outlineWidth, -shadowTop);
+        LayoutUnit decorationsBottomHeight = max<LayoutUnit>(-outlineStyle->outlineOffset(), borderHeight + minInsetBottomShadowExtent) + max<LayoutUnit>(outlineWidth, shadowBottom);
         LayoutRect bottomRect(newOutlineBox.x(),
-            min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
+            min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsTopHeight,
             max(newOutlineBox.width(), oldOutlineBox.width()),
-            height + decorationsHeight);
+            height + decorationsTopHeight + decorationsBottomHeight);
         LayoutUnit bottom = min(newBounds.maxY(), oldBounds.maxY());
         if (bottomRect.y() < bottom) {
             bottomRect.setHeight(min(bottomRect.height(), bottom - bottomRect.y()));
@@ -1590,11 +1592,16 @@
 {
 }
 
-bool RenderObject::checkForRepaintDuringLayout() const
+bool RenderObject::checkForRepaint() const
 {
     return !document().view()->needsFullRepaint() && !hasLayer() && everHadLayout();
 }
 
+bool RenderObject::checkForRepaintDuringLayout() const
+{
+    return !RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && checkForRepaint();
+}
+
 LayoutRect RenderObject::rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const
 {
     LayoutRect r(clippedOverflowRectForRepaint(repaintContainer));
@@ -1712,19 +1719,14 @@
 
 Color RenderObject::selectionBackgroundColor() const
 {
-    Color backgroundColor;
-    if (isSelectable()) {
-        RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
-        if (pseudoStyle && resolveColor(pseudoStyle.get(), CSSPropertyBackgroundColor).isValid()) {
-            backgroundColor = resolveColor(pseudoStyle.get(), CSSPropertyBackgroundColor).blendWithWhite();
-        } else {
-            backgroundColor = frame()->selection().isFocusedAndActive() ?
-                RenderTheme::theme().activeSelectionBackgroundColor() :
-                RenderTheme::theme().inactiveSelectionBackgroundColor();
-        }
-    }
+    if (!isSelectable())
+        return Color::transparent;
 
-    return backgroundColor;
+    if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION)))
+        return resolveColor(pseudoStyle.get(), CSSPropertyBackgroundColor).blendWithWhite();
+    return frame()->selection().isFocusedAndActive() ?
+        RenderTheme::theme().activeSelectionBackgroundColor() :
+        RenderTheme::theme().inactiveSelectionBackgroundColor();
 }
 
 Color RenderObject::selectionColor(int colorProperty) const
@@ -1732,19 +1734,15 @@
     // If the element is unselectable, or we are only painting the selection,
     // don't override the foreground color with the selection foreground color.
     if (!isSelectable() || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
-        return Color::transparent;
+        return resolveColor(colorProperty);
 
-    Color color;
-    if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION))) {
-        Color selectionColor = resolveColor(pseudoStyle.get(), colorProperty);
-        color = selectionColor.isValid() ? selectionColor : resolveColor(pseudoStyle.get(), CSSPropertyColor);
-    } else {
-        color = frame()->selection().isFocusedAndActive() ?
-            RenderTheme::theme().activeSelectionForegroundColor() :
-            RenderTheme::theme().inactiveSelectionForegroundColor();
-    }
-
-    return color;
+    if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION)))
+        return resolveColor(pseudoStyle.get(), colorProperty);
+    if (!RenderTheme::theme().supportsSelectionForegroundColors())
+        return resolveColor(colorProperty);
+    return frame()->selection().isFocusedAndActive() ?
+        RenderTheme::theme().activeSelectionForegroundColor() :
+        RenderTheme::theme().inactiveSelectionForegroundColor();
 }
 
 Color RenderObject::selectionForegroundColor() const
@@ -1781,15 +1779,6 @@
     }
 }
 
-void RenderObject::setAnimatableStyle(PassRefPtr<RenderStyle> style)
-{
-    if (!isText() && style && !RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
-        setStyle(animation().updateAnimations(*this, *style));
-        return;
-    }
-    setStyle(style);
-}
-
 StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
 {
     // If transform changed, and the layer does not paint into its own separate backing, then we need to do a layout.
@@ -1800,7 +1789,7 @@
         // Text nodes share style with their parents but transforms don't apply to them,
         // hence the !isText() check.
         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
-        if (!isText() && (!hasLayer() || toRenderLayerModelObject(this)->layer()->compositingState() != PaintsIntoOwnBacking)) {
+        if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->hasDirectReasonsForCompositing())) {
             // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
             // then we actually need SimplifiedLayoutAndPositionedMovement.
             if (!hasLayer())
@@ -1815,25 +1804,27 @@
 
     // If opacity or filters changed, and the layer does not paint into its own separate backing, then we need to repaint (also
     // ignoring text nodes)
-    if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
-        if (!isText() && (!hasLayer() || toRenderLayerModelObject(this)->layer()->compositingState() != PaintsIntoOwnBacking))
-            diff = StyleDifferenceRepaintLayer;
-        else if (diff < StyleDifferenceRecompositeLayer)
-            diff = StyleDifferenceRecompositeLayer;
-    }
-    if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
-        RenderLayer* layer = toRenderLayerModelObject(this)->layer();
-        if (layer->compositingState() != PaintsIntoOwnBacking || layer->paintsWithFilters())
+    if (contextSensitiveProperties & ContextSensitivePropertyOpacity && diff <= StyleDifferenceRepaintLayer) {
+        if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->hasDirectReasonsForCompositing()))
             diff = StyleDifferenceRepaintLayer;
         else if (diff < StyleDifferenceRecompositeLayer)
             diff = StyleDifferenceRecompositeLayer;
     }
 
-    // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
+    if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer() && diff <= StyleDifferenceRepaintLayer) {
+        RenderLayer* layer = toRenderLayerModelObject(this)->layer();
+        if (!layer->hasDirectReasonsForCompositing() || layer->paintsWithFilters())
+            diff = StyleDifferenceRepaintLayer;
+        else if (diff < StyleDifferenceRecompositeLayer)
+            diff = StyleDifferenceRecompositeLayer;
+    }
+
+    // The answer to layerTypeRequired() for plugins, iframes, and canvas can change without the actual
     // style changing, since it depends on whether we decide to composite these elements. When the
     // layer status of one of these elements changes, we need to force a layout.
     if (diff == StyleDifferenceEqual && style() && isLayerModelObject()) {
-        if (hasLayer() != toRenderLayerModelObject(this)->requiresLayer())
+        bool requiresLayer = toRenderLayerModelObject(this)->layerTypeRequired() != NoLayer;
+        if (hasLayer() != requiresLayer)
             diff = StyleDifferenceLayout;
     }
 
@@ -1869,6 +1860,8 @@
 
 inline bool RenderObject::hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor() const
 {
+    if (style()->hasBorder() || style()->hasOutline())
+        return true;
     for (const RenderObject* r = firstChild(); r; r = r->nextSibling()) {
         if (r->isText() && !toRenderText(r)->isAllCollapsibleWhitespace())
             return true;
@@ -2012,11 +2005,20 @@
         s_affectsParentBlock = false;
 
     if (view()->frameView()) {
-        bool newStyleSlowScroll = newStyle && newStyle->hasFixedBackgroundImage();
-        bool oldStyleSlowScroll = m_style && m_style->hasFixedBackgroundImage();
+        bool shouldBlitOnFixedBackgroundImage = false;
+#if ENABLE(FAST_MOBILE_SCROLLING)
+        // On low-powered/mobile devices, preventing blitting on a scroll can cause noticeable delays
+        // when scrolling a page with a fixed background image. As an optimization, assuming there are
+        // no fixed positoned elements on the page, we can acclerate scrolling (via blitting) if we
+        // ignore the CSS property "background-attachment: fixed".
+        shouldBlitOnFixedBackgroundImage = true;
+#endif
+
+        bool newStyleSlowScroll = newStyle && !shouldBlitOnFixedBackgroundImage && newStyle->hasFixedBackgroundImage();
+        bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
 
         bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
-        if (drawsRootBackground) {
+        if (drawsRootBackground && !shouldBlitOnFixedBackgroundImage) {
             if (view()->compositor()->supportsFixedRootBackgroundCompositing()) {
                 if (newStyleSlowScroll && newStyle->hasEntirelyFixedBackground())
                     newStyleSlowScroll = false;
@@ -2377,12 +2379,15 @@
     const size_t maxRectsPerLayer = 100;
 
     LayerHitTestRects::iterator iter = layerRects.find(currentLayer);
+    Vector<WebCore::LayoutRect>* iterValue;
     if (iter == layerRects.end())
-        iter = layerRects.add(currentLayer, Vector<LayoutRect>()).iterator;
+        iterValue = &layerRects.add(currentLayer, Vector<LayoutRect>()).storedValue->value;
+    else
+        iterValue = &iter->value;
     for (size_t i = 0; i < ownRects.size(); i++) {
         if (!containerRect.contains(ownRects[i])) {
-            iter->value.append(ownRects[i]);
-            if (iter->value.size() > maxRectsPerLayer) {
+            iterValue->append(ownRects[i]);
+            if (iterValue->size() > maxRectsPerLayer) {
                 // Just mark the entire layer instead, and switch to walking the layer
                 // tree instead of the render tree.
                 layerRects.remove(currentLayer);
@@ -2428,7 +2433,7 @@
 RenderObject* RenderObject::rendererForRootBackground()
 {
     ASSERT(isRoot());
-    if (!hasBackground() && node() && isHTMLHtmlElement(node())) {
+    if (!hasBackground() && node() && node()->hasTagName(htmlTag)) {
         // Locate the <body> element using the DOM. This is easier than trying
         // to crawl around a render tree with potential :before/:after content and
         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
@@ -2519,7 +2524,7 @@
                 // This indicates a failure to layout the child, which is why
                 // the layout root is still set to |this|. Make sure to clear it
                 // since we are getting destroyed.
-                view->clearLayoutRoot();
+                view->clearLayoutSubtreeRoot();
             }
         }
     }
@@ -2536,7 +2541,6 @@
     if (Frame* frame = this->frame()) {
         if (frame->page())
             frame->page()->autoscrollController().stopAutoscrollIfNeeded(this);
-        frame->animation().cancelAnimations(this);
     }
 
     // For accessibility management, notify the parent of the imminent change to its child set.
@@ -2551,18 +2555,6 @@
     if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->remove(this);
 
-#ifndef NDEBUG
-    if (!documentBeingDestroyed() && view() && view()->hasRenderNamedFlowThreads()) {
-        // After remove, the object and the associated information should not be in any flow thread.
-        const RenderNamedFlowThreadList* flowThreadList = view()->flowThreadController()->renderNamedFlowThreadList();
-        for (RenderNamedFlowThreadList::const_iterator iter = flowThreadList->begin(); iter != flowThreadList->end(); ++iter) {
-            const RenderNamedFlowThread* renderFlowThread = *iter;
-            ASSERT(!renderFlowThread->hasChild(this));
-            ASSERT(!renderFlowThread->hasChildInfo(this));
-        }
-    }
-#endif
-
     // If this renderer had a parent, remove should have destroyed any counters
     // attached to this renderer and marked the affected other counters for
     // reevaluation. This apparently redundant check is here for the case when
@@ -2599,9 +2591,6 @@
 
     if (!isFloating() && parent()->childrenInline())
         parent()->dirtyLinesFromChangedChild(this);
-
-    if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
-        containerFlowThread->addFlowChild(this);
 }
 
 void RenderObject::willBeRemovedFromTree()
@@ -2627,11 +2616,9 @@
 
     removeFromRenderFlowThread();
 
-    if (RenderNamedFlowThread* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
-        containerFlowThread->removeFlowChild(this);
-
     // Update cached boundaries in SVG renderers if a child is removed.
-    parent()->setNeedsBoundariesUpdate();
+    if (parent()->isSVG())
+        parent()->setNeedsBoundariesUpdate();
 }
 
 void RenderObject::removeFromRenderFlowThread()
@@ -2653,11 +2640,6 @@
             child->removeFromRenderFlowThreadRecursive(renderFlowThread);
     }
 
-    RenderFlowThread* localFlowThread = renderFlowThread;
-    if (flowThreadState() == InsideInFlowThread)
-        localFlowThread = flowThreadContainingBlock(); // We have to ask. We can't just assume we are in the same flow thread.
-    if (localFlowThread)
-        localFlowThread->removeFlowChildInfo(this);
     setFlowThreadState(NotInsideFlowThread);
 }
 
@@ -2738,8 +2720,12 @@
 {
     bool valueChanged = (dragOn != isDragging());
     setIsDragging(dragOn);
-    if (valueChanged && node() && (style()->affectedByDrag() || (node()->isElementNode() && toElement(node())->childrenAffectedByDrag())))
-        node()->setNeedsStyleRecalc();
+    if (valueChanged && node()) {
+        if (node()->isElementNode() && toElement(node())->childrenAffectedByDrag())
+            node()->setNeedsStyleRecalc(SubtreeStyleChange);
+        else if (style()->affectedByDrag())
+            node()->setNeedsStyleRecalc(LocalStyleChange);
+    }
     for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling())
         curr->updateDragState(dragOn);
 }
@@ -2749,6 +2735,23 @@
     return hasLayer() ? toRenderLayerModelObject(this)->layer()->compositingState() : NotComposited;
 }
 
+bool RenderObject::acceleratedCompositingForOverflowScrollEnabled() const
+{
+    const Settings* settings = document().settings();
+    return settings && settings->acceleratedCompositingForOverflowScrollEnabled();
+}
+
+// FIXME: This is a temporary flag and should be removed once accelerated
+// overflow scroll is ready (crbug.com/254111).
+bool RenderObject::compositorDrivenAcceleratedScrollingEnabled() const
+{
+    if (!acceleratedCompositingForOverflowScrollEnabled())
+        return false;
+
+    const Settings* settings = document().settings();
+    return settings && settings->compositorDrivenAcceleratedScrollingEnabled();
+}
+
 bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
 {
     bool inside = false;
@@ -2815,31 +2818,6 @@
     }
 }
 
-void RenderObject::layout()
-{
-    ASSERT(needsLayout());
-    LayoutRectRecorder recorder(*this);
-    RenderObject* child = firstChild();
-    while (child) {
-        child->layoutIfNeeded();
-        ASSERT(!child->needsLayout());
-        child = child->nextSibling();
-    }
-    clearNeedsLayout();
-}
-
-void RenderObject::didLayout(ResourceLoadPriorityOptimizer& priorityModifier)
-{
-    for (RenderObject* child = firstChild(); child; child = child->nextSibling())
-        child->didLayout(priorityModifier);
-}
-
-void RenderObject::didScroll(ResourceLoadPriorityOptimizer& priorityModifier)
-{
-    for (RenderObject* child = firstChild(); child; child = child->nextSibling())
-        child->didScroll(priorityModifier);
-}
-
 void RenderObject::forceLayout()
 {
     setSelfNeedsLayout(true);
@@ -2955,20 +2933,19 @@
 
 static Color decorationColor(const RenderObject* object, RenderStyle* style)
 {
-    Color result;
     // Check for text decoration color first.
-    result = object->resolveColor(style, CSSPropertyTextDecorationColor);
-    if (result.isValid())
-        return result;
+    StyleColor result = style->visitedDependentDecorationColor();
+    if (!result.isCurrentColor())
+        return result.color();
+
     if (style->textStrokeWidth() > 0) {
         // Prefer stroke color if possible but not if it's fully transparent.
-        result = object->resolveColor(style, CSSPropertyWebkitTextStrokeColor);
-        if (result.alpha())
-            return result;
+        Color textStrokeColor = object->resolveColor(style, CSSPropertyWebkitTextStrokeColor);
+        if (textStrokeColor.alpha())
+            return textStrokeColor;
     }
 
-    result = object->resolveColor(style, CSSPropertyWebkitTextFillColor);
-    return result;
+    return object->resolveColor(style, CSSPropertyWebkitTextFillColor);
 }
 
 void RenderObject::getTextDecorationColors(unsigned decorations, Color& underline, Color& overline,
@@ -3003,7 +2980,7 @@
         curr = curr->parent();
         if (curr && curr->isAnonymousBlock() && toRenderBlock(curr)->continuation())
             curr = toRenderBlock(curr)->continuation();
-    } while (curr && decorations && (!quirksMode || !curr->node() || (!isHTMLAnchorElement(curr->node()) && !curr->node()->hasTagName(fontTag))));
+    } while (curr && decorations && (!quirksMode || !curr->node() || (!curr->node()->hasTagName(aTag) && !curr->node()->hasTagName(fontTag))));
 
     // If we bailed out, use the element we bailed out at (typically a <font> or <a> element).
     if (decorations && curr) {
@@ -3061,7 +3038,7 @@
 
     // If we're not in a window (i.e., we're dormant from being in a background tab)
     // then we don't want to render either.
-    return !document().view()->isOffscreen();
+    return document().view()->isVisible();
 }
 
 int RenderObject::maximalOutlineSize(PaintPhase p) const
@@ -3111,11 +3088,6 @@
     rect.inflate(outlineSize);
 }
 
-AnimationController& RenderObject::animation() const
-{
-    return frame()->animation();
-}
-
 bool RenderObject::isInert() const
 {
     const RenderObject* renderer = this;
@@ -3129,33 +3101,6 @@
     imageChanged(static_cast<WrappedImagePtr>(image), rect);
 }
 
-RenderObject* RenderObject::hoverAncestor() const
-{
-    // When searching for the hover ancestor and encountering a named flow thread,
-    // the search will continue with the DOM ancestor of the top-most element
-    // in the named flow thread.
-    // See https://code.google.com/p/chromium/issues/detail?id=243278
-    RenderObject* hoverAncestor = parent();
-
-    // Skip anonymous blocks directly flowed into flow threads as it would
-    // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
-    if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
-        hoverAncestor = hoverAncestor->parent();
-
-    if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
-        hoverAncestor = 0;
-
-        Node* node = this->node();
-        if (node) {
-            Node* domAncestorNode = node->parentNode();
-            if (domAncestorNode)
-                hoverAncestor = domAncestorNode->renderer();
-        }
-    }
-
-    return hoverAncestor;
-}
-
 Element* RenderObject::offsetParent() const
 {
     if (isRoot() || isBody())
@@ -3173,10 +3118,6 @@
     for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
         // Spec: http://www.w3.org/TR/cssom-view/#offset-attributes
 
-        // CSS regions specification says that region flows should return the body element as their offsetParent.
-        if (ancestor->isRenderNamedFlowThread())
-            return document().body();
-
         node = ancestor->node();
 
         if (!node)
@@ -3185,10 +3126,10 @@
         if (ancestor->isPositioned())
             break;
 
-        if (node->hasTagName(HTMLNames::bodyTag))
+        if (node->hasTagName(bodyTag))
             break;
 
-        if (!isPositioned() && (isHTMLTableElement(node) || node->hasTagName(tdTag) || node->hasTagName(thTag)))
+        if (!isPositioned() && (node->hasTagName(tableTag) || node->hasTagName(tdTag) || node->hasTagName(thTag)))
             break;
 
         // Webkit specific extension where offsetParent stops at zoom level changes.
@@ -3329,27 +3270,11 @@
     return false;
 }
 
-// FIXME: This should really use local coords
-// Works on absolute coords - expensive to call
-bool RenderObject::isContainedInParentBoundingBox() const
-{
-    if (!parent())
-        return false;
-
-    IntRect parentRect = parent()->absoluteBoundingBoxRect();
-    return parentRect.contains(absoluteBoundingBoxRect());
-}
-
 bool RenderObject::isRelayoutBoundaryForInspector() const
 {
     return objectIsRelayoutBoundary(this);
 }
 
-bool RenderObject::isRenderNamedFlowFragmentContainer() const
-{
-    return isRenderBlockFlow() && toRenderBlockFlow(this)->renderNamedFlowFragment();
-}
-
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/RenderObject.h b/Source/core/rendering/RenderObject.h
index b53071a..7fd2dfe 100644
--- a/Source/core/rendering/RenderObject.h
+++ b/Source/core/rendering/RenderObject.h
@@ -31,10 +31,9 @@
 #include "core/dom/StyleEngine.h"
 #include "core/fetch/ImageResourceClient.h"
 #include "core/rendering/CompositingState.h"
-#include "core/rendering/LayoutIndicator.h"
 #include "core/rendering/PaintPhase.h"
 #include "core/rendering/RenderObjectChildList.h"
-#include "core/rendering/ScrollBehavior.h"
+#include "core/rendering/ScrollAlignment.h"
 #include "core/rendering/SubtreeLayoutScope.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/style/StyleInheritedData.h"
@@ -45,7 +44,6 @@
 namespace WebCore {
 
 class AffineTransform;
-class AnimationController;
 class Cursor;
 class Document;
 class HitTestLocation;
@@ -62,7 +60,6 @@
 class RenderGeometryMap;
 class RenderLayer;
 class RenderLayerModelObject;
-class RenderNamedFlowThread;
 class RenderSVGResourceContainer;
 class RenderTable;
 class RenderTheme;
@@ -120,10 +117,6 @@
     {
         return draggable == o.draggable && bounds == o.bounds;
     }
-    bool operator!=(const AnnotatedRegionValue& o) const
-    {
-        return !(*this == o);
-    }
 
     LayoutRect bounds;
     bool draggable;
@@ -188,7 +181,6 @@
     RenderObject* previousInPreOrder(const RenderObject* stayWithin) const;
     RenderObject* childAt(unsigned) const;
 
-    RenderObject* firstLeafChild() const;
     RenderObject* lastLeafChild() const;
 
     // The following six functions are used when the render tree hierarchy changes to make sure layers get
@@ -218,8 +210,6 @@
         return locateFlowThreadContainingBlock();
     }
 
-    RenderNamedFlowThread* renderNamedFlowThreadWrapper() const;
-
     virtual bool isEmpty() const { return firstChild() == 0; }
 
 #ifndef NDEBUG
@@ -346,14 +336,12 @@
     virtual bool isProgress() const { return false; }
     virtual bool isRenderBlock() const { return false; }
     virtual bool isRenderBlockFlow() const { return false; }
-    virtual bool isRenderSVGBlock() const { return false; };
     virtual bool isRenderButton() const { return false; }
     virtual bool isRenderIFrame() const { return false; }
     virtual bool isRenderImage() const { return false; }
     virtual bool isRenderInline() const { return false; }
     virtual bool isRenderPart() const { return false; }
     virtual bool isRenderRegion() const { return false; }
-    virtual bool isRenderNamedFlowFragment() const { return false; }
     virtual bool isRenderView() const { return false; }
     virtual bool isReplica() const { return false; }
 
@@ -382,10 +370,8 @@
     virtual bool isRenderGrid() const { return false; }
 
     virtual bool isRenderFlowThread() const { return false; }
-    virtual bool isRenderNamedFlowThread() const { return false; }
     bool isInFlowRenderFlowThread() const { return isRenderFlowThread() && !isOutOfFlowPositioned(); }
     bool isOutOfFlowRenderFlowThread() const { return isRenderFlowThread() && isOutOfFlowPositioned(); }
-    bool isRenderNamedFlowFragmentContainer() const;
 
     virtual bool isRenderMultiColumnBlock() const { return false; }
     virtual bool isRenderMultiColumnSet() const { return false; }
@@ -402,9 +388,7 @@
     inline bool isBeforeContent() const;
     inline bool isAfterContent() const;
     inline bool isBeforeOrAfterContent() const;
-    static inline bool isBeforeContent(const RenderObject* obj) { return obj && obj->isBeforeContent(); }
     static inline bool isAfterContent(const RenderObject* obj) { return obj && obj->isAfterContent(); }
-    static inline bool isBeforeOrAfterContent(const RenderObject* obj) { return obj && obj->isBeforeOrAfterContent(); }
 
     bool hasCounterNodeMap() const { return m_bitfields.hasCounterNodeMap(); }
     void setHasCounterNodeMap(bool hasCounterNodeMap) { m_bitfields.setHasCounterNodeMap(hasCounterNodeMap); }
@@ -436,6 +420,7 @@
 
     // FIXME: Until all SVG renders can be subclasses of RenderSVGModelObject we have
     // to add SVG renderer methods to RenderObject with an ASSERT_NOT_REACHED() default implementation.
+    virtual bool isSVG() const { return false; }
     virtual bool isSVGRoot() const { return false; }
     virtual bool isSVGContainer() const { return false; }
     virtual bool isSVGTransformableContainer() const { return false; }
@@ -459,7 +444,6 @@
     // to inherit from RenderSVGObject -> RenderObject (some need RenderBlock inheritance for instance)
     virtual void setNeedsTransformUpdate() { }
     virtual void setNeedsBoundariesUpdate();
-    virtual bool needsBoundariesUpdate() { return false; }
 
     // Per SVG 1.1 objectBoundingBox ignores clipping, masking, filter effects, opacity and stroke-width.
     // This is used for all computation of objectBoundingBox relative units and by SVGLocatable::getBBox().
@@ -509,7 +493,6 @@
     bool isAnonymousColumnSpanBlock() const { return style()->columnSpan() && isAnonymousBlock(); }
     bool isElementContinuation() const { return node() && node()->renderer() != this; }
     bool isInlineElementContinuation() const { return isElementContinuation() && isInline(); }
-    bool isBlockElementContinuation() const { return isElementContinuation() && !isInline(); }
     virtual RenderBoxModelObject* virtualContinuation() const { return 0; }
 
     bool isFloating() const { return m_bitfields.floating(); }
@@ -599,7 +582,6 @@
 
     Node* nonPseudoNode() const
     {
-        ASSERT(!LayoutIndicator::inLayout());
         return isPseudoElement() ? 0 : node();
     }
 
@@ -622,7 +604,7 @@
     // is true if the renderer returned is an ancestor of repaintContainer.
     RenderObject* container(const RenderLayerModelObject* repaintContainer = 0, bool* repaintContainerSkipped = 0) const;
 
-    virtual RenderObject* hoverAncestor() const;
+    virtual RenderObject* hoverAncestor() const { return parent(); }
 
     Element* offsetParent() const;
 
@@ -673,10 +655,12 @@
 
     virtual void paint(PaintInfo&, const LayoutPoint&);
 
-    // Recursive function that computes the size and position of this object and all its descendants.
-    virtual void layout();
-    virtual void didLayout(ResourceLoadPriorityOptimizer&);
-    virtual void didScroll(ResourceLoadPriorityOptimizer&);
+    // Subclasses must reimplement this method to compute the size and position
+    // of this object and all its descendants.
+    virtual void layout() = 0;
+    virtual bool updateImageLoadingPriorities() { return false; }
+    void setHasPendingResourceUpdate(bool hasPendingResourceUpdate) { m_bitfields.setHasPendingResourceUpdate(hasPendingResourceUpdate); }
+    bool hasPendingResourceUpdate() const { return m_bitfields.hasPendingResourceUpdate(); }
 
     /* This function performs a layout only if one is needed. */
     void layoutIfNeeded() { if (needsLayout()) layout(); }
@@ -695,6 +679,10 @@
     void collectAnnotatedRegions(Vector<AnnotatedRegionValue>&);
 
     CompositingState compositingState() const;
+    bool acceleratedCompositingForOverflowScrollEnabled() const;
+    // FIXME: This is a temporary flag and should be removed once accelerated
+    // overflow scroll is ready (crbug.com/254111).
+    bool compositorDrivenAcceleratedScrollingEnabled() const;
 
     bool hitTest(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter = HitTestAll);
     virtual void updateHitTestResult(HitTestResult&, const LayoutPoint&);
@@ -706,11 +694,6 @@
 
     virtual void dirtyLinesFromChangedChild(RenderObject*);
 
-    // Called to update a style that is allowed to trigger animations.
-    // FIXME: Right now this will typically be called only when updating happens from the DOM on explicit elements.
-    // We don't yet handle generated content animation such as first-letter or before/after (we'll worry about this later).
-    void setAnimatableStyle(PassRefPtr<RenderStyle>);
-
     // Set the style of the object and update the state of the object accordingly.
     void setStyle(PassRefPtr<RenderStyle>);
 
@@ -762,8 +745,6 @@
     IntRect absoluteBoundingBoxRect(bool useTransform = true) const;
     IntRect absoluteBoundingBoxRectIgnoringTransforms() const { return absoluteBoundingBoxRect(false); }
 
-    bool isContainedInParentBoundingBox() const;
-
     // Build an array of quads in absolute coords for line boxes
     virtual void absoluteQuads(Vector<FloatQuad>&, bool* /*wasFixed*/ = 0) const { }
 
@@ -791,17 +772,6 @@
         return style()->visitedDependentColor(colorProperty);
     }
 
-    inline Color resolveColor(int colorProperty, Color fallback) const
-    {
-        Color color = resolveColor(colorProperty);
-        return color.isValid() ? color : fallback;
-    }
-
-    inline Color resolveColor(Color color) const
-    {
-        return color;
-    }
-
     // Used only by Element::pseudoStyleCacheIsInvalid to get a first line style based off of a
     // given new style, without accessing the cache.
     PassRefPtr<RenderStyle> uncachedFirstLineStyle(RenderStyle*) const;
@@ -835,6 +805,7 @@
 
     virtual void repaintOverflow();
 
+    bool checkForRepaint() const;
     bool checkForRepaintDuringLayout() const;
 
     // Returns the rect that should be repainted whenever this object changes.  The rect is in the view's
@@ -849,12 +820,6 @@
     virtual LayoutRect outlineBoundsForRepaint(const RenderLayerModelObject* /*repaintContainer*/, const RenderGeometryMap* = 0) const { return LayoutRect(); }
 
     // Given a rect in the object's coordinate space, compute a rect suitable for repainting
-    // that rect in view coordinates.
-    void computeAbsoluteRepaintRect(LayoutRect& r, bool fixed = false) const
-    {
-        computeRectForRepaint(0, r, fixed);
-    }
-    // Given a rect in the object's coordinate space, compute a rect suitable for repainting
     // that rect in the coordinate space of repaintContainer.
     virtual void computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect&, bool fixed = false) const;
     virtual void computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed = false) const;
@@ -930,7 +895,6 @@
 
     // Virtual function helpers for the deprecated Flexible Box Layout (display: -webkit-box).
     virtual bool isDeprecatedFlexibleBox() const { return false; }
-    virtual bool isStretchingChildren() const { return false; }
 
     // Virtual function helper for the new FlexibleBox Layout (display: -webkit-flex).
     virtual bool isFlexibleBox() const { return false; }
@@ -949,16 +913,14 @@
     virtual int previousOffsetForBackwardDeletion(int current) const;
     virtual int nextOffset(int current) const;
 
-    virtual void imageChanged(ImageResource*, const IntRect* = 0);
+    virtual void imageChanged(ImageResource*, const IntRect* = 0) OVERRIDE FINAL;
     virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) { }
-    virtual bool willRenderImage(ImageResource*);
+    virtual bool willRenderImage(ImageResource*) OVERRIDE FINAL;
 
     void selectionStartEnd(int& spos, int& epos) const;
 
     void remove() { if (parent()) parent()->removeChild(this); }
 
-    AnimationController& animation() const;
-
     bool isInert() const;
     bool visibleToHitTestRequest(const HitTestRequest& request) const { return style()->visibility() == VISIBLE && (request.ignorePointerEventsNone() || style()->pointerEvents() != PE_NONE) && !isInert(); }
     bool visibleToHitTesting() const { return style()->visibility() == VISIBLE && style()->pointerEvents() != PE_NONE && !isInert(); }
@@ -1156,10 +1118,11 @@
             , m_selectionState(SelectionNone)
             , m_flowThreadState(NotInsideFlowThread)
             , m_boxDecorationState(NoBoxDecorations)
+            , m_hasPendingResourceUpdate(false)
         {
         }
 
-        // 32 bits have been used in the first word, and 2 in the second.
+        // 32 bits have been used in the first word, and 3 in the second.
         ADD_BOOLEAN_BITFIELD(selfNeedsLayout, SelfNeedsLayout);
         ADD_BOOLEAN_BITFIELD(shouldDoFullRepaintAfterLayout, ShouldDoFullRepaintAfterLayout);
         ADD_BOOLEAN_BITFIELD(shouldRepaintOverflowIfNeeded, ShouldRepaintOverflowIfNeeded);
@@ -1200,6 +1163,9 @@
         unsigned m_boxDecorationState : 2; // BoxDecorationState
 
     public:
+
+        ADD_BOOLEAN_BITFIELD(hasPendingResourceUpdate, HasPendingResourceUpdate);
+
         bool isOutOfFlowPositioned() const { return m_positionedState == IsOutOfFlowPositioned; }
         bool isRelPositioned() const { return m_positionedState == IsRelativelyPositioned; }
         bool isStickyPositioned() const { return m_positionedState == IsStickyPositioned; }
diff --git a/Source/core/rendering/RenderObjectChildList.cpp b/Source/core/rendering/RenderObjectChildList.cpp
index 80cee46..1dffa35 100644
--- a/Source/core/rendering/RenderObjectChildList.cpp
+++ b/Source/core/rendering/RenderObjectChildList.cpp
@@ -56,16 +56,21 @@
     if (oldChild->isFloatingOrOutOfFlowPositioned())
         toRenderBox(oldChild)->removeFloatingOrPositionedChildFromBlockLists();
 
-    // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
-    // that a positioned child got yanked). We also repaint, so that the area exposed when the child
-    // disappears gets repainted properly.
-    if (!owner->documentBeingDestroyed() && notifyRenderer && oldChild->everHadLayout()) {
-        oldChild->setNeedsLayoutAndPrefWidthsRecalc();
-        // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
-        if (oldChild->isBody())
-            owner->view()->repaint();
-        else
-            oldChild->repaint();
+    {
+        // FIXME: We should not be allowing repaint during layout. crbug.com/336250
+        AllowRepaintScope scoper(owner->frameView());
+
+        // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
+        // that a positioned child got yanked). We also repaint, so that the area exposed when the child
+        // disappears gets repainted properly.
+        if (!owner->documentBeingDestroyed() && notifyRenderer && oldChild->everHadLayout()) {
+            oldChild->setNeedsLayoutAndPrefWidthsRecalc();
+            // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
+            if (oldChild->isBody())
+                owner->view()->repaint();
+            else
+                oldChild->repaint();
+        }
     }
 
     // If we have a line box wrapper, delete it.
diff --git a/Source/core/rendering/RenderPart.cpp b/Source/core/rendering/RenderPart.cpp
index 33db879..689219e 100644
--- a/Source/core/rendering/RenderPart.cpp
+++ b/Source/core/rendering/RenderPart.cpp
@@ -25,8 +25,9 @@
 #include "config.h"
 #include "core/rendering/RenderPart.h"
 
-#include "core/html/HTMLFrameElementBase.h"
+#include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
+#include "core/html/HTMLFrameElementBase.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderLayer.h"
@@ -54,22 +55,15 @@
         return;
 
     RenderWidget::setWidget(widget);
-
-    // make sure the scrollbars are set correctly for restore
-    // ### find better fix
-    viewCleared();
 }
 
-void RenderPart::viewCleared()
+LayerType RenderPart::layerTypeRequired() const
 {
-}
+    LayerType type = RenderWidget::layerTypeRequired();
+    if (type != NoLayer)
+        return type;
 
-bool RenderPart::requiresLayer() const
-{
-    if (RenderWidget::requiresLayer())
-        return true;
-
-    return requiresAcceleratedCompositing();
+    return requiresAcceleratedCompositing() ? NormalLayer : NoLayer;
 }
 
 bool RenderPart::requiresAcceleratedCompositing() const
@@ -85,6 +79,9 @@
         return false;
 
     HTMLFrameOwnerElement* element = toHTMLFrameOwnerElement(node());
+    if (element->contentFrame() && element->contentFrame()->remotePlatformLayer())
+        return true;
+
     if (Document* contentDocument = element->contentDocument()) {
         if (RenderView* view = contentDocument->renderView())
             return view->usesCompositing();
diff --git a/Source/core/rendering/RenderPart.h b/Source/core/rendering/RenderPart.h
index f26a7e2..707fde3 100644
--- a/Source/core/rendering/RenderPart.h
+++ b/Source/core/rendering/RenderPart.h
@@ -34,7 +34,6 @@
     virtual ~RenderPart();
 
     virtual void setWidget(PassRefPtr<Widget>) OVERRIDE FINAL;
-    virtual void viewCleared();
 
     bool requiresAcceleratedCompositing() const;
 
@@ -44,11 +43,11 @@
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 
 protected:
-    virtual bool requiresLayer() const;
+    virtual LayerType layerTypeRequired() const OVERRIDE;
 
 private:
     virtual bool isRenderPart() const OVERRIDE FINAL { return true; }
-    virtual const char* renderName() const { return "RenderPart"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderPart"; }
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderPart, isRenderPart());
diff --git a/Source/core/rendering/RenderProgress.cpp b/Source/core/rendering/RenderProgress.cpp
index 9bf99a8..c44ce5c 100644
--- a/Source/core/rendering/RenderProgress.cpp
+++ b/Source/core/rendering/RenderProgress.cpp
@@ -55,7 +55,7 @@
 
     updateAnimationState();
     repaint();
-    RenderBlock::updateFromElement();
+    RenderBlockFlow::updateFromElement();
 }
 
 double RenderProgress::animationProgress() const
@@ -98,7 +98,7 @@
     if (!node())
         return 0;
 
-    if (isHTMLProgressElement(node()))
+    if (node()->hasTagName(HTMLNames::progressTag))
         return toHTMLProgressElement(node());
 
     ASSERT(node()->shadowHost());
diff --git a/Source/core/rendering/RenderProgress.h b/Source/core/rendering/RenderProgress.h
index bd1cac9..c1014d2 100644
--- a/Source/core/rendering/RenderProgress.h
+++ b/Source/core/rendering/RenderProgress.h
@@ -37,13 +37,13 @@
     double animationStartTime() const { return m_animationStartTime; }
 
     bool isDeterminate() const;
-    virtual void updateFromElement();
+    virtual void updateFromElement() OVERRIDE;
 
     HTMLProgressElement* progressElement() const;
 
 private:
-    virtual const char* renderName() const { return "RenderProgress"; }
-    virtual bool isProgress() const { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderProgress"; }
+    virtual bool isProgress() const OVERRIDE { return true; }
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
     void animationTimerFired(Timer<RenderProgress>*);
diff --git a/Source/core/rendering/RenderRegion.cpp b/Source/core/rendering/RenderRegion.cpp
index 0614d3a..36a6b58 100644
--- a/Source/core/rendering/RenderRegion.cpp
+++ b/Source/core/rendering/RenderRegion.cpp
@@ -34,8 +34,7 @@
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/HitTestLocation.h"
 #include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderBoxRegionInfo.h"
-#include "core/rendering/RenderNamedFlowThread.h"
+#include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderView.h"
 
 using namespace std;
@@ -45,11 +44,7 @@
 RenderRegion::RenderRegion(Element* element, RenderFlowThread* flowThread)
     : RenderBlockFlow(element)
     , m_flowThread(flowThread)
-    , m_parentNamedFlowThread(0)
-    , m_computedAutoHeight(-1)
     , m_isValid(false)
-    , m_hasCustomRegionStyle(false)
-    , m_hasAutoLogicalHeight(false)
 {
 }
 
@@ -62,29 +57,12 @@
 LayoutUnit RenderRegion::pageLogicalHeight() const
 {
     ASSERT(m_flowThread);
-    if (hasComputedAutoHeight() && !m_flowThread->inConstrainedLayoutPhase()) {
-        ASSERT(hasAutoLogicalHeight());
-        return computedAutoHeight();
-    }
     return m_flowThread->isHorizontalWritingMode() ? contentHeight() : contentWidth();
 }
 
-// This method returns the maximum page size of a region with auto-height. This is the initial
-// height value for auto-height regions in the first layout phase of the parent named flow.
-LayoutUnit RenderRegion::maxPageLogicalHeight() const
-{
-    ASSERT(m_flowThread);
-    ASSERT(hasAutoLogicalHeight() && !m_flowThread->inConstrainedLayoutPhase());
-    return style()->logicalMaxHeight().isUndefined() ? RenderFlowThread::maxLogicalHeight() : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
-}
-
 LayoutUnit RenderRegion::logicalHeightOfAllFlowThreadContent() const
 {
     ASSERT(m_flowThread);
-    if (hasComputedAutoHeight() && !m_flowThread->inConstrainedLayoutPhase()) {
-        ASSERT(hasAutoLogicalHeight());
-        return computedAutoHeight();
-    }
     return m_flowThread->isHorizontalWritingMode() ? contentHeight() : contentWidth();
 }
 
@@ -97,8 +75,7 @@
 {
     ASSERT(isValid());
 
-    bool isLastRegionWithRegionFragmentBreak = (isLastPortion && (style()->regionFragment() == BreakRegionFragment));
-    if (hasOverflowClip() || isLastRegionWithRegionFragmentBreak)
+    if (hasOverflowClip())
         return flowThreadPortionRect;
 
     LayoutRect flowThreadOverflow = m_flowThread->visualOverflowRect();
@@ -109,42 +86,20 @@
     if (m_flowThread->isHorizontalWritingMode()) {
         LayoutUnit minY = isFirstPortion ? (flowThreadOverflow.y() - outlineSize) : flowThreadPortionRect.y();
         LayoutUnit maxY = isLastPortion ? max(flowThreadPortionRect.maxY(), flowThreadOverflow.maxY()) + outlineSize : flowThreadPortionRect.maxY();
-        bool clipX = style()->overflowX() != OVISIBLE;
-        LayoutUnit minX = clipX ? flowThreadPortionRect.x() : min(flowThreadPortionRect.x(), flowThreadOverflow.x() - outlineSize);
-        LayoutUnit maxX = clipX ? flowThreadPortionRect.maxX() : max(flowThreadPortionRect.maxX(), (flowThreadOverflow.maxX() + outlineSize));
+        LayoutUnit minX = min(flowThreadPortionRect.x(), flowThreadOverflow.x() - outlineSize);
+        LayoutUnit maxX = max(flowThreadPortionRect.maxX(), (flowThreadOverflow.maxX() + outlineSize));
         clipRect = LayoutRect(minX, minY, maxX - minX, maxY - minY);
     } else {
         LayoutUnit minX = isFirstPortion ? (flowThreadOverflow.x() - outlineSize) : flowThreadPortionRect.x();
         LayoutUnit maxX = isLastPortion ? max(flowThreadPortionRect.maxX(), flowThreadOverflow.maxX()) + outlineSize : flowThreadPortionRect.maxX();
-        bool clipY = style()->overflowY() != OVISIBLE;
-        LayoutUnit minY = clipY ? flowThreadPortionRect.y() : min(flowThreadPortionRect.y(), (flowThreadOverflow.y() - outlineSize));
-        LayoutUnit maxY = clipY ? flowThreadPortionRect.maxY() : max(flowThreadPortionRect.y(), (flowThreadOverflow.maxY() + outlineSize));
+        LayoutUnit minY = min(flowThreadPortionRect.y(), (flowThreadOverflow.y() - outlineSize));
+        LayoutUnit maxY = max(flowThreadPortionRect.y(), (flowThreadOverflow.maxY() + outlineSize));
         clipRect = LayoutRect(minX, minY, maxX - minX, maxY - minY);
     }
 
     return clipRect;
 }
 
-RegionOversetState RenderRegion::regionOversetState() const
-{
-    if (isValid() && element())
-        return element()->regionOversetState();
-
-    return RegionUndefined;
-}
-
-void RenderRegion::setRegionOversetState(RegionOversetState state)
-{
-    if (element())
-        element()->setRegionOversetState(state);
-}
-
-Element* RenderRegion::element() const
-{
-    ASSERT(nodeForRegion() && nodeForRegion()->isElementNode());
-    return toElement(nodeForRegion());
-}
-
 LayoutUnit RenderRegion::pageLogicalTopForOffset(LayoutUnit /* offset */) const
 {
     return flowThread()->isHorizontalWritingMode() ? flowThreadPortionRect().y() : flowThreadPortionRect().x();
@@ -164,148 +119,10 @@
     return m_flowThread->lastRegion() == this;
 }
 
-static bool shouldPaintRegionContentsInPhase(PaintPhase phase)
-{
-    return phase == PaintPhaseForeground
-        || phase == PaintPhaseSelection
-        || phase == PaintPhaseTextClip;
-}
-
-void RenderRegion::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
-{
-    if (style()->visibility() != VISIBLE)
-        return;
-
-    RenderBlock::paintObject(paintInfo, paintOffset);
-
-    if (!isValid())
-        return;
-
-    // Delegate painting of content in region to RenderFlowThread.
-    // RenderFlowThread is a self painting layer (being a positioned object) who is painting its children, the collected objects.
-    // Since we do not want to paint the flow thread content multiple times (for each painting phase of the region object),
-    // we allow the flow thread painting only in certain phases.
-    if (!shouldPaintRegionContentsInPhase(paintInfo.phase))
-        return;
-
-    setRegionObjectsRegionStyle();
-    m_flowThread->paintFlowThreadPortionInRegion(paintInfo, this, flowThreadPortionRect(), flowThreadPortionOverflowRect(), LayoutPoint(paintOffset.x() + borderLeft() + paddingLeft(), paintOffset.y() + borderTop() + paddingTop()));
-    restoreRegionObjectsOriginalStyle();
-}
-
-// Hit Testing
-bool RenderRegion::hitTestFlowThreadContents(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
-{
-    if (!isValid() || action != HitTestForeground)
-        return false;
-
-    LayoutRect boundsRect = borderBoxRectInRegion(locationInContainer.region());
-    boundsRect.moveBy(accumulatedOffset);
-    if (visibleToHitTesting() && locationInContainer.intersects(boundsRect)) {
-        if (m_flowThread->hitTestFlowThreadPortionInRegion(this, flowThreadPortionRect(), flowThreadPortionOverflowRect(), request, result,
-            locationInContainer, LayoutPoint(accumulatedOffset.x() + borderLeft() + paddingLeft(), accumulatedOffset.y() + borderTop() + paddingTop())))
-            return true;
-    }
-
-    return false;
-}
-
-void RenderRegion::checkRegionStyle()
-{
-    ASSERT(m_flowThread);
-    bool customRegionStyle = false;
-
-    // FIXME: Region styling doesn't work for pseudo elements.
-    if (isElementBasedRegion())
-        customRegionStyle = view()->document().ensureStyleResolver().checkRegionStyle(this->element());
-
-    setHasCustomRegionStyle(customRegionStyle);
-    m_flowThread->checkRegionsWithStyling();
-}
-
-void RenderRegion::incrementAutoLogicalHeightCount()
-{
-    ASSERT(isValid());
-    ASSERT(m_hasAutoLogicalHeight);
-
-    m_flowThread->incrementAutoLogicalHeightRegions();
-}
-
-void RenderRegion::decrementAutoLogicalHeightCount()
-{
-    ASSERT(isValid());
-
-    m_flowThread->decrementAutoLogicalHeightRegions();
-}
-
-void RenderRegion::updateRegionHasAutoLogicalHeightFlag()
-{
-    ASSERT(m_flowThread);
-
-    if (!isValid())
-        return;
-
-    bool didHaveAutoLogicalHeight = m_hasAutoLogicalHeight;
-    m_hasAutoLogicalHeight = shouldHaveAutoLogicalHeight();
-    if (m_hasAutoLogicalHeight != didHaveAutoLogicalHeight) {
-        if (m_hasAutoLogicalHeight) {
-            incrementAutoLogicalHeightCount();
-        } else {
-            clearComputedAutoHeight();
-            decrementAutoLogicalHeightCount();
-        }
-    }
-}
-
-bool RenderRegion::shouldHaveAutoLogicalHeight() const
-{
-    bool hasSpecifiedEndpointsForHeight = style()->logicalTop().isSpecified() && style()->logicalBottom().isSpecified();
-    bool hasAnchoredEndpointsForHeight = isOutOfFlowPositioned() && hasSpecifiedEndpointsForHeight;
-    bool hasAutoHeightStyle = style()->logicalHeight().isAuto() || style()->logicalHeight().isFitContent()
-        || style()->logicalHeight().isMaxContent() || style()->logicalHeight().isMinContent();
-    return hasAutoHeightStyle && !hasAnchoredEndpointsForHeight;
-}
-
-void RenderRegion::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
-    RenderBlock::styleDidChange(diff, oldStyle);
-
-    // If the region is not attached to any thread, there is no need to check
-    // whether the region has region styling since no content will be displayed
-    // into the region.
-    if (!m_flowThread) {
-        setHasCustomRegionStyle(false);
-        return;
-    }
-
-    checkRegionStyle();
-    updateRegionHasAutoLogicalHeightFlag();
-
-    if (oldStyle && oldStyle->writingMode() != style()->writingMode())
-        m_flowThread->regionChangedWritingMode(this);
-}
-
-void RenderRegion::layoutBlock(bool relayoutChildren, LayoutUnit)
+void RenderRegion::layoutBlock(bool relayoutChildren)
 {
     RenderBlockFlow::layoutBlock(relayoutChildren);
 
-    if (isValid()) {
-        LayoutRect oldRegionRect(flowThreadPortionRect());
-        if (!isHorizontalWritingMode())
-            oldRegionRect = oldRegionRect.transposedRect();
-
-        if (hasAutoLogicalHeight() && !m_flowThread->inConstrainedLayoutPhase()) {
-            m_flowThread->invalidateRegions();
-            clearComputedAutoHeight();
-            return;
-        }
-
-        if (!isRenderRegionSet() && (oldRegionRect.width() != pageLogicalWidth() || oldRegionRect.height() != pageLogicalHeight())) {
-            // This can happen even if we are in the inConstrainedLayoutPhase and it will trigger a pathological layout of the flow thread.
-            m_flowThread->invalidateRegions();
-        }
-    }
-
     // FIXME: We need to find a way to set up overflow properly. Our flow thread hasn't gotten a layout
     // yet, so we can't look to it for correct information. It's possible we could wait until after the RenderFlowThread
     // gets a layout, and then try to propagate overflow information back to the region, and then mark for a second layout.
@@ -314,8 +131,6 @@
     // The big problem though is that overflow needs to be region-specific. We can't simply use the RenderFlowThread's global
     // overflow values, since then we'd always think any narrow region had huge overflow (all the way to the width of the
     // RenderFlowThread itself).
-    //
-    // We'll need to expand RenderBoxRegionInfo to also hold left and right overflow values.
 }
 
 void RenderRegion::repaintFlowThreadContent(const LayoutRect& repaintRect) const
@@ -348,29 +163,6 @@
     repaintRectangle(clippedRect);
 }
 
-void RenderRegion::installFlowThread()
-{
-    ASSERT(view());
-
-    m_flowThread = view()->flowThreadController()->ensureRenderFlowThreadWithName(style()->regionThread());
-
-    // By now the flow thread should already be added to the rendering tree,
-    // so we go up the rendering parents and check that this region is not part of the same
-    // flow that it actually needs to display. It would create a circular reference.
-    RenderObject* parentObject = parent();
-    m_parentNamedFlowThread = 0;
-    for ( ; parentObject; parentObject = parentObject->parent()) {
-        if (parentObject->isRenderNamedFlowThread()) {
-            m_parentNamedFlowThread = toRenderNamedFlowThread(parentObject);
-            // Do not take into account a region that links a flow with itself. The dependency
-            // cannot change, so it is not worth adding it to the list.
-            if (m_flowThread == m_parentNamedFlowThread)
-                m_flowThread = 0;
-            break;
-        }
-    }
-}
-
 void RenderRegion::attachRegion()
 {
     if (documentBeingDestroyed())
@@ -379,72 +171,19 @@
     // A region starts off invalid.
     setIsValid(false);
 
-    // Initialize the flow thread reference and create the flow thread object if needed.
-    // The flow thread lifetime is influenced by the number of regions attached to it,
-    // and we are attaching the region to the flow thread.
-    installFlowThread();
-
     if (!m_flowThread)
         return;
 
     // Only after adding the region to the thread, the region is marked to be valid.
     m_flowThread->addRegionToThread(this);
-
-    // The region just got attached to the flow thread, lets check whether
-    // it has region styling rules associated.
-    checkRegionStyle();
-
-    if (!isValid())
-        return;
-
-    m_hasAutoLogicalHeight = shouldHaveAutoLogicalHeight();
-    if (hasAutoLogicalHeight())
-        incrementAutoLogicalHeightCount();
 }
 
 void RenderRegion::detachRegion()
 {
     if (m_flowThread) {
         m_flowThread->removeRegionFromThread(this);
-        if (hasAutoLogicalHeight())
-            decrementAutoLogicalHeightCount();
+        m_flowThread = 0;
     }
-    m_flowThread = 0;
-}
-
-RenderBoxRegionInfo* RenderRegion::renderBoxRegionInfo(const RenderBox* box) const
-{
-    ASSERT(isValid());
-    return m_renderBoxRegionInfo.get(box);
-}
-
-RenderBoxRegionInfo* RenderRegion::setRenderBoxRegionInfo(const RenderBox* box, LayoutUnit logicalLeftInset, LayoutUnit logicalRightInset,
-    bool containingBlockChainIsInset)
-{
-    ASSERT(isValid());
-
-    OwnPtr<RenderBoxRegionInfo>& boxInfo = m_renderBoxRegionInfo.add(box, nullptr).iterator->value;
-    if (boxInfo)
-        *boxInfo = RenderBoxRegionInfo(logicalLeftInset, logicalRightInset, containingBlockChainIsInset);
-    else
-        boxInfo = adoptPtr(new RenderBoxRegionInfo(logicalLeftInset, logicalRightInset, containingBlockChainIsInset));
-
-    return boxInfo.get();
-}
-
-PassOwnPtr<RenderBoxRegionInfo> RenderRegion::takeRenderBoxRegionInfo(const RenderBox* box)
-{
-    return m_renderBoxRegionInfo.take(box);
-}
-
-void RenderRegion::removeRenderBoxRegionInfo(const RenderBox* box)
-{
-    m_renderBoxRegionInfo.remove(box);
-}
-
-void RenderRegion::deleteAllRenderBoxRegionInfo()
-{
-    m_renderBoxRegionInfo.clear();
 }
 
 LayoutUnit RenderRegion::logicalTopOfFlowThreadContentRect(const LayoutRect& rect) const
@@ -459,167 +198,24 @@
     return flowThread()->isHorizontalWritingMode() ? rect.maxY() : rect.maxX();
 }
 
-void RenderRegion::setRegionObjectsRegionStyle()
-{
-    if (!hasCustomRegionStyle())
-        return;
-
-    // Start from content nodes and recursively compute the style in region for the render objects below.
-    // If the style in region was already computed, used that style instead of computing a new one.
-    RenderNamedFlowThread* namedFlow = view()->flowThreadController()->ensureRenderFlowThreadWithName(style()->regionThread());
-    const NamedFlowContentNodes& contentNodes = namedFlow->contentNodes();
-
-    for (NamedFlowContentNodes::const_iterator iter = contentNodes.begin(), end = contentNodes.end(); iter != end; ++iter) {
-        const Node* node = *iter;
-        // The list of content nodes contains also the nodes with display:none.
-        if (!node->renderer())
-            continue;
-
-        RenderObject* object = node->renderer();
-        // If the content node does not flow any of its children in this region,
-        // we do not compute any style for them in this region.
-        if (!flowThread()->objectInFlowRegion(object, this))
-            continue;
-
-        // If the object has style in region, use that instead of computing a new one.
-        RenderObjectRegionStyleMap::iterator it = m_renderObjectRegionStyle.find(object);
-        RefPtr<RenderStyle> objectStyleInRegion;
-        bool objectRegionStyleCached = false;
-        if (it != m_renderObjectRegionStyle.end()) {
-            objectStyleInRegion = it->value.style;
-            ASSERT(it->value.cached);
-            objectRegionStyleCached = true;
-        } else {
-            objectStyleInRegion = computeStyleInRegion(object);
-        }
-
-        setObjectStyleInRegion(object, objectStyleInRegion, objectRegionStyleCached);
-
-        computeChildrenStyleInRegion(object);
-    }
-}
-
-void RenderRegion::restoreRegionObjectsOriginalStyle()
-{
-    if (!hasCustomRegionStyle())
-        return;
-
-    RenderObjectRegionStyleMap temp;
-    for (RenderObjectRegionStyleMap::iterator iter = m_renderObjectRegionStyle.begin(), end = m_renderObjectRegionStyle.end(); iter != end; ++iter) {
-        RenderObject* object = const_cast<RenderObject*>(iter->key);
-        RefPtr<RenderStyle> objectRegionStyle = object->style();
-        RefPtr<RenderStyle> objectOriginalStyle = iter->value.style;
-        object->setStyleInternal(objectOriginalStyle);
-
-        bool shouldCacheRegionStyle = iter->value.cached;
-        if (!shouldCacheRegionStyle) {
-            // Check whether we should cache the computed style in region.
-            unsigned changedContextSensitiveProperties = ContextSensitivePropertyNone;
-            StyleDifference styleDiff = objectOriginalStyle->diff(objectRegionStyle.get(), changedContextSensitiveProperties);
-            if (styleDiff < StyleDifferenceLayoutPositionedMovementOnly)
-                shouldCacheRegionStyle = true;
-        }
-        if (shouldCacheRegionStyle) {
-            ObjectRegionStyleInfo styleInfo;
-            styleInfo.style = objectRegionStyle;
-            styleInfo.cached = true;
-            temp.set(object, styleInfo);
-        }
-    }
-
-    m_renderObjectRegionStyle.swap(temp);
-}
-
 void RenderRegion::insertedIntoTree()
 {
-    RenderBlock::insertedIntoTree();
+    RenderBlockFlow::insertedIntoTree();
 
     attachRegion();
 }
 
 void RenderRegion::willBeRemovedFromTree()
 {
-    RenderBlock::willBeRemovedFromTree();
+    RenderBlockFlow::willBeRemovedFromTree();
 
     detachRegion();
 }
 
-PassRefPtr<RenderStyle> RenderRegion::computeStyleInRegion(const RenderObject* object)
-{
-    ASSERT(object);
-    ASSERT(object->view());
-    ASSERT(!object->isAnonymous());
-    ASSERT(object->node() && object->node()->isElementNode());
-
-    // FIXME: Region styling fails for pseudo-elements because the renderers don't have a node.
-    Element* element = toElement(object->node());
-    RefPtr<RenderStyle> renderObjectRegionStyle = object->view()->document().ensureStyleResolver().styleForElement(element, 0, DisallowStyleSharing, MatchAllRules, this);
-
-    return renderObjectRegionStyle.release();
-}
-
-void RenderRegion::computeChildrenStyleInRegion(const RenderObject* object)
-{
-    for (RenderObject* child = object->lastChild(); child; child = child->previousSibling()) {
-
-        RenderObjectRegionStyleMap::iterator it = m_renderObjectRegionStyle.find(child);
-
-        RefPtr<RenderStyle> childStyleInRegion;
-        bool objectRegionStyleCached = false;
-        if (it != m_renderObjectRegionStyle.end()) {
-            childStyleInRegion = it->value.style;
-            objectRegionStyleCached = true;
-        } else {
-            if (child->isAnonymous() || child->isInFlowRenderFlowThread())
-                childStyleInRegion = RenderStyle::createAnonymousStyleWithDisplay(object->style(), child->style()->display());
-            else if (child->isText())
-                childStyleInRegion = RenderStyle::clone(object->style());
-            else
-                childStyleInRegion = computeStyleInRegion(child);
-        }
-
-        setObjectStyleInRegion(child, childStyleInRegion, objectRegionStyleCached);
-
-        computeChildrenStyleInRegion(child);
-    }
-}
-
-void RenderRegion::setObjectStyleInRegion(RenderObject* object, PassRefPtr<RenderStyle> styleInRegion, bool objectRegionStyleCached)
-{
-    ASSERT(object->flowThreadContainingBlock());
-
-    RefPtr<RenderStyle> objectOriginalStyle = object->style();
-    object->setStyleInternal(styleInRegion);
-
-    if (object->isBoxModelObject() && !object->hasBoxDecorations()) {
-        bool hasBoxDecorations = object->isTableCell()
-        || object->style()->hasBackground()
-        || object->style()->hasBorder()
-        || object->style()->hasAppearance()
-        || object->style()->boxShadow();
-        object->setHasBoxDecorations(hasBoxDecorations);
-    }
-
-    ObjectRegionStyleInfo styleInfo;
-    styleInfo.style = objectOriginalStyle;
-    styleInfo.cached = objectRegionStyleCached;
-    m_renderObjectRegionStyle.set(object, styleInfo);
-}
-
-void RenderRegion::clearObjectStyleInRegion(const RenderObject* object)
-{
-    ASSERT(object);
-    m_renderObjectRegionStyle.remove(object);
-
-    // Clear the style for the children of this object.
-    for (RenderObject* child = object->lastChild(); child; child = child->previousSibling())
-        clearObjectStyleInRegion(child);
-}
-
 void RenderRegion::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
 {
     if (!isValid()) {
-        RenderBlock::computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
+        RenderBlockFlow::computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
         return;
     }
 
@@ -627,62 +223,4 @@
     maxLogicalWidth = m_flowThread->maxPreferredLogicalWidth();
 }
 
-void RenderRegion::getRanges(Vector<RefPtr<Range> >& rangeObjects) const
-{
-    RenderNamedFlowThread* namedFlow = view()->flowThreadController()->ensureRenderFlowThreadWithName(style()->regionThread());
-    namedFlow->getRanges(rangeObjects, this);
-}
-
-void RenderRegion::updateLogicalHeight()
-{
-    RenderBlock::updateLogicalHeight();
-
-    if (!hasAutoLogicalHeight())
-        return;
-
-    // We want to update the logical height based on the computed auto-height
-    // only if the view is in the layout phase in which all the
-    // auto logical height regions have a computed auto-height.
-    if (!m_flowThread->inConstrainedLayoutPhase())
-        return;
-
-    // There may be regions with auto logical height that during the prerequisite layout phase
-    // did not have the chance to layout flow thread content. Because of that, these regions do not
-    // have a computedAutoHeight and they will not be able to fragment any flow
-    // thread content.
-    if (!hasComputedAutoHeight())
-        return;
-
-    LayoutUnit autoHeight = hasOverrideHeight() ? overrideLogicalContentHeight() : computedAutoHeight();
-
-    LayoutUnit newLogicalHeight = autoHeight + borderAndPaddingLogicalHeight();
-    ASSERT(newLogicalHeight < RenderFlowThread::maxLogicalHeight());
-    if (newLogicalHeight > logicalHeight()) {
-        setLogicalHeight(newLogicalHeight);
-        // Recalculate position of the render block after new logical height is set.
-        // (needed in absolute positioning case with bottom alignment for example)
-        RenderBlock::updateLogicalHeight();
-    }
-}
-
-Node* RenderRegion::nodeForRegion() const
-{
-    if (parent() && isRenderNamedFlowFragment())
-        return parent()->node();
-    return node();
-}
-
-Node* RenderRegion::generatingNodeForRegion() const
-{
-    if (parent() && isRenderNamedFlowFragment())
-        return parent()->generatingNode();
-    return generatingNode();
-}
-
-bool RenderRegion::isElementBasedRegion() const
-{
-    Node* node = nodeForRegion();
-    return node && node->isElementNode() && !node->isPseudoElement();
-}
-
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderRegion.h b/Source/core/rendering/RenderRegion.h
index c05d613..b57d159 100644
--- a/Source/core/rendering/RenderRegion.h
+++ b/Source/core/rendering/RenderRegion.h
@@ -38,19 +38,13 @@
 struct LayerFragment;
 typedef Vector<LayerFragment, 1> LayerFragments;
 class RenderBox;
-class RenderBoxRegionInfo;
 class RenderFlowThread;
-class RenderNamedFlowThread;
 
 class RenderRegion : public RenderBlockFlow {
 public:
     explicit RenderRegion(Element*, RenderFlowThread*);
 
-    virtual bool isRenderRegion() const OVERRIDE { return true; }
-
-    bool hitTestFlowThreadContents(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction);
-
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+    virtual bool isRenderRegion() const OVERRIDE FINAL { return true; }
 
     void setFlowThreadPortionRect(const LayoutRect& rect) { m_flowThreadPortionRect = rect; }
     LayoutRect flowThreadPortionRect() const { return m_flowThreadPortionRect; }
@@ -59,72 +53,31 @@
     void attachRegion();
     void detachRegion();
 
-    RenderNamedFlowThread* parentNamedFlowThread() const { return m_parentNamedFlowThread; }
     RenderFlowThread* flowThread() const { return m_flowThread; }
 
     // Valid regions do not create circular dependencies with other flows.
     bool isValid() const { return m_isValid; }
     void setIsValid(bool valid) { m_isValid = valid; }
 
-    bool hasCustomRegionStyle() const { return m_hasCustomRegionStyle; }
-    void setHasCustomRegionStyle(bool hasCustomRegionStyle) { m_hasCustomRegionStyle = hasCustomRegionStyle; }
-
-    RenderBoxRegionInfo* renderBoxRegionInfo(const RenderBox*) const;
-    RenderBoxRegionInfo* setRenderBoxRegionInfo(const RenderBox*, LayoutUnit logicalLeftInset, LayoutUnit logicalRightInset,
-        bool containingBlockChainIsInset);
-    PassOwnPtr<RenderBoxRegionInfo> takeRenderBoxRegionInfo(const RenderBox*);
-    void removeRenderBoxRegionInfo(const RenderBox*);
-
-    void deleteAllRenderBoxRegionInfo();
-
     bool isFirstRegion() const;
     bool isLastRegion() const;
 
-    void clearObjectStyleInRegion(const RenderObject*);
-
-    RegionOversetState regionOversetState() const;
-    void setRegionOversetState(RegionOversetState);
-
     // These methods represent the width and height of a "page" and for a RenderRegion they are just the
     // content width and content height of a region. For RenderRegionSets, however, they will be the width and
     // height of a single column or page in the set.
     virtual LayoutUnit pageLogicalWidth() const;
     virtual LayoutUnit pageLogicalHeight() const;
-    virtual LayoutUnit maxPageLogicalHeight() const;
 
     LayoutUnit logicalTopOfFlowThreadContentRect(const LayoutRect&) const;
     LayoutUnit logicalBottomOfFlowThreadContentRect(const LayoutRect&) const;
     LayoutUnit logicalTopForFlowThreadContent() const { return logicalTopOfFlowThreadContentRect(flowThreadPortionRect()); };
     LayoutUnit logicalBottomForFlowThreadContent() const { return logicalBottomOfFlowThreadContentRect(flowThreadPortionRect()); };
 
-    void getRanges(Vector<RefPtr<Range> >&) const;
-
     // This method represents the logical height of the entire flow thread portion used by the region or set.
     // For RenderRegions it matches logicalPaginationHeight(), but for sets it is the height of all the pages
     // or columns added together.
     virtual LayoutUnit logicalHeightOfAllFlowThreadContent() const;
 
-    bool hasAutoLogicalHeight() const { return m_hasAutoLogicalHeight; }
-
-    const LayoutUnit& computedAutoHeight() const
-    {
-        ASSERT(hasComputedAutoHeight());
-        return m_computedAutoHeight;
-    }
-
-    void setComputedAutoHeight(LayoutUnit computedAutoHeight)
-    {
-        ASSERT(computedAutoHeight >= 0);
-        m_computedAutoHeight = computedAutoHeight;
-    }
-
-    void clearComputedAutoHeight()
-    {
-        m_computedAutoHeight = -1;
-    }
-
-    bool hasComputedAutoHeight() const { return (m_computedAutoHeight >= 0); }
-
     // The top of the nearest page inside the region. For RenderRegions, this is just the logical top of the
     // flow thread portion we contain. For sets, we have to figure out the top of the nearest column or
     // page.
@@ -132,94 +85,35 @@
 
     virtual void expandToEncompassFlowThreadContentsIfNeeded() { };
 
-    // Whether or not this region is a set.
-    virtual bool isRenderRegionSet() const { return false; }
-
     virtual void repaintFlowThreadContent(const LayoutRect& repaintRect) const;
 
     virtual void collectLayerFragments(LayerFragments&, const LayoutRect&, const LayoutRect&) { }
 
-    virtual bool canHaveChildren() const OVERRIDE { return false; }
-    virtual bool canHaveGeneratedChildren() const OVERRIDE { return true; }
-
-    bool isElementBasedRegion() const;
-
-    Node* nodeForRegion() const;
-    Node* generatingNodeForRegion() const;
+    virtual bool canHaveChildren() const OVERRIDE FINAL { return false; }
+    virtual bool canHaveGeneratedChildren() const OVERRIDE FINAL { return true; }
 
     virtual const char* renderName() const OVERRIDE { return "RenderRegion"; }
 
 protected:
-    void setRegionObjectsRegionStyle();
-    void restoreRegionObjectsOriginalStyle();
-
-    virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
+    virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE FINAL;
 
     LayoutRect overflowRectForFlowThreadPortion(const LayoutRect& flowThreadPortionRect, bool isFirstPortion, bool isLastPortion) const;
     void repaintFlowThreadContentRectangle(const LayoutRect& repaintRect, const LayoutRect& flowThreadPortionRect,
         const LayoutRect& flowThreadPortionOverflowRect, const LayoutPoint& regionLocation) const;
 
-    virtual bool shouldHaveAutoLogicalHeight() const;
-
 private:
-    virtual void insertedIntoTree() OVERRIDE;
-    virtual void willBeRemovedFromTree() OVERRIDE;
+    virtual void insertedIntoTree() OVERRIDE FINAL;
+    virtual void willBeRemovedFromTree() OVERRIDE FINAL;
 
-    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE;
-    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
-    virtual void paintObject(PaintInfo&, const LayoutPoint&) OVERRIDE;
-
-    virtual void updateLogicalHeight() OVERRIDE;
-
-    virtual void installFlowThread();
-
-    PassRefPtr<RenderStyle> computeStyleInRegion(const RenderObject*);
-    void computeChildrenStyleInRegion(const RenderObject*);
-    void setObjectStyleInRegion(RenderObject*, PassRefPtr<RenderStyle>, bool objectRegionStyleCached);
-
-    void checkRegionStyle();
-    void updateRegionHasAutoLogicalHeightFlag();
-
-    void incrementAutoLogicalHeightCount();
-    void decrementAutoLogicalHeightCount();
-
-    Element* element() const;
+    virtual void layoutBlock(bool relayoutChildren) OVERRIDE FINAL;
+    virtual bool supportsPartialLayout() const OVERRIDE FINAL { return false; }
 
 protected:
     RenderFlowThread* m_flowThread;
 
 private:
-    // If this RenderRegion is displayed as part of another named flow,
-    // we need to create a dependency tree, so that layout of the
-    // regions is always done before the regions themselves.
-    RenderNamedFlowThread* m_parentNamedFlowThread;
     LayoutRect m_flowThreadPortionRect;
-
-    // This map holds unique information about a block that is split across regions.
-    // A RenderBoxRegionInfo* tells us about any layout information for a RenderBox that
-    // is unique to the region. For now it just holds logical width information for RenderBlocks, but eventually
-    // it will also hold a custom style for any box (for region styling).
-    typedef HashMap<const RenderBox*, OwnPtr<RenderBoxRegionInfo> > RenderBoxRegionInfoMap;
-    RenderBoxRegionInfoMap m_renderBoxRegionInfo;
-
-    struct ObjectRegionStyleInfo {
-        // Used to store the original style of the object in region
-        // so that the original style is properly restored after paint.
-        // Also used to store computed style of the object in region between
-        // region paintings, so that the style in region is computed only
-        // when necessary.
-        RefPtr<RenderStyle> style;
-        // True if the computed style in region is cached.
-        bool cached;
-    };
-    typedef HashMap<const RenderObject*, ObjectRegionStyleInfo > RenderObjectRegionStyleMap;
-    RenderObjectRegionStyleMap m_renderObjectRegionStyle;
-
-    LayoutUnit m_computedAutoHeight;
-
     bool m_isValid : 1;
-    bool m_hasCustomRegionStyle : 1;
-    bool m_hasAutoLogicalHeight : 1;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderRegion, isRenderRegion());
diff --git a/Source/core/rendering/RenderRegionSet.cpp b/Source/core/rendering/RenderRegionSet.cpp
index 9336115..9aaf5ed 100644
--- a/Source/core/rendering/RenderRegionSet.cpp
+++ b/Source/core/rendering/RenderRegionSet.cpp
@@ -35,12 +35,6 @@
 {
 }
 
-void RenderRegionSet::installFlowThread()
-{
-    // We don't have to do anything, since we were able to connect the flow thread
-    // in the constructor.
-}
-
 void RenderRegionSet::expandToEncompassFlowThreadContentsIfNeeded()
 {
     // Whenever the last region is a set, it always expands its region rect to consume all
diff --git a/Source/core/rendering/RenderRegionSet.h b/Source/core/rendering/RenderRegionSet.h
index 6802852..fc2151b 100644
--- a/Source/core/rendering/RenderRegionSet.h
+++ b/Source/core/rendering/RenderRegionSet.h
@@ -27,7 +27,6 @@
 #ifndef RenderRegionSet_h
 #define RenderRegionSet_h
 
-#include "core/rendering/RenderBoxRegionInfo.h"
 #include "core/rendering/RenderRegion.h"
 
 namespace WebCore {
@@ -49,17 +48,10 @@
 public:
     RenderRegionSet(Element*, RenderFlowThread*);
 
-protected:
-    virtual bool shouldHaveAutoLogicalHeight() const OVERRIDE { return false; }
-
 private:
-    virtual void installFlowThread() OVERRIDE FINAL;
-
     virtual void expandToEncompassFlowThreadContentsIfNeeded() OVERRIDE FINAL;
 
     virtual const char* renderName() const = 0;
-
-    virtual bool isRenderRegionSet() const OVERRIDE FINAL { return true; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderReplaced.cpp b/Source/core/rendering/RenderReplaced.cpp
index 059cd20..ead5b9c 100644
--- a/Source/core/rendering/RenderReplaced.cpp
+++ b/Source/core/rendering/RenderReplaced.cpp
@@ -32,6 +32,7 @@
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
+#include "platform/LengthFunctions.h"
 #include "platform/graphics/GraphicsContext.h"
 
 using namespace std;
@@ -196,9 +197,9 @@
     // Early exit if the element touches the edges.
     LayoutUnit top = adjustedPaintOffset.y() + visualOverflowRect().y();
     LayoutUnit bottom = adjustedPaintOffset.y() + visualOverflowRect().maxY();
-    if (isSelected() && m_inlineBoxWrapper) {
-        LayoutUnit selTop = paintOffset.y() + m_inlineBoxWrapper->root()->selectionTop();
-        LayoutUnit selBottom = paintOffset.y() + selTop + m_inlineBoxWrapper->root()->selectionHeight();
+    if (isSelected() && inlineBoxWrapper()) {
+        LayoutUnit selTop = paintOffset.y() + inlineBoxWrapper()->root()->selectionTop();
+        LayoutUnit selBottom = paintOffset.y() + selTop + inlineBoxWrapper()->root()->selectionHeight();
         top = min(selTop, top);
         bottom = max(selBottom, bottom);
     }
@@ -358,8 +359,8 @@
         ASSERT_NOT_REACHED();
     }
 
-    LayoutUnit xOffset = minimumValueForLength(style()->objectPosition().x(), contentRect.width() - finalRect.width(), view());
-    LayoutUnit yOffset = minimumValueForLength(style()->objectPosition().y(), contentRect.height() - finalRect.height(), view());
+    LayoutUnit xOffset = minimumValueForLength(style()->objectPosition().x(), contentRect.width() - finalRect.width());
+    LayoutUnit yOffset = minimumValueForLength(style()->objectPosition().y(), contentRect.height() - finalRect.height());
     finalRect.move(xOffset, yOffset);
 
     return finalRect;
@@ -566,12 +567,12 @@
     if (checkWhetherSelected && !isSelected())
         return LayoutRect();
 
-    if (!m_inlineBoxWrapper)
+    if (!inlineBoxWrapper())
         // We're a block-level replaced element.  Just return our own dimensions.
         return LayoutRect(LayoutPoint(), size());
 
-    RootInlineBox* root = m_inlineBoxWrapper->root();
-    LayoutUnit newLogicalTop = root->block()->style()->isFlippedBlocksWritingMode() ? m_inlineBoxWrapper->logicalBottom() - root->selectionBottom() : root->selectionTop() - m_inlineBoxWrapper->logicalTop();
+    RootInlineBox* root = inlineBoxWrapper()->root();
+    LayoutUnit newLogicalTop = root->block()->style()->isFlippedBlocksWritingMode() ? inlineBoxWrapper()->logicalBottom() - root->selectionBottom() : root->selectionTop() - inlineBoxWrapper()->logicalTop();
     if (root->block()->style()->isHorizontalWritingMode())
         return LayoutRect(0, newLogicalTop, width(), root->selectionHeight());
     return LayoutRect(newLogicalTop, 0, root->selectionHeight(), height());
@@ -582,8 +583,8 @@
     // The selection state for our containing block hierarchy is updated by the base class call.
     RenderBox::setSelectionState(state);
 
-    if (m_inlineBoxWrapper && canUpdateSelectionOnRootLineBoxes())
-        if (RootInlineBox* root = m_inlineBoxWrapper->root())
+    if (inlineBoxWrapper() && canUpdateSelectionOnRootLineBoxes())
+        if (RootInlineBox* root = inlineBoxWrapper()->root())
             root->setHasSelectedChildren(isSelected());
 }
 
@@ -620,7 +621,7 @@
     LayoutRect r = unionRect(localSelectionRect(false), visualOverflowRect());
 
     RenderView* v = view();
-    if (v) {
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && v) {
         // FIXME: layoutDelta needs to be applied in parts before/after transforms and
         // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
         r.move(v->layoutDelta());
diff --git a/Source/core/rendering/RenderReplaced.h b/Source/core/rendering/RenderReplaced.h
index e5db970..012d754 100644
--- a/Source/core/rendering/RenderReplaced.h
+++ b/Source/core/rendering/RenderReplaced.h
@@ -33,21 +33,21 @@
     virtual ~RenderReplaced();
 
     virtual LayoutUnit computeReplacedLogicalWidth(ShouldComputePreferred  = ComputeActual) const OVERRIDE;
-    virtual LayoutUnit computeReplacedLogicalHeight() const;
+    virtual LayoutUnit computeReplacedLogicalHeight() const OVERRIDE;
 
     bool hasReplacedLogicalWidth() const;
     bool hasReplacedLogicalHeight() const;
+    LayoutRect replacedContentRect(const LayoutSize* overriddenIntrinsicSize = 0) const;
 
     virtual bool needsPreferredWidthsRecalculation() const OVERRIDE;
 
 protected:
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
     virtual LayoutSize intrinsicSize() const OVERRIDE FINAL { return m_intrinsicSize; }
-    LayoutRect replacedContentRect(const LayoutSize* overriddenIntrinsicSize = 0) const;
-    virtual void computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const;
+    virtual void computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const OVERRIDE;
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE FINAL;
 
@@ -57,21 +57,21 @@
 
     bool isSelected() const;
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     void setIntrinsicSize(const LayoutSize& intrinsicSize) { m_intrinsicSize = intrinsicSize; }
     virtual void intrinsicSizeChanged();
     virtual bool hasRelativeIntrinsicLogicalWidth() const { return false; }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
     bool shouldPaint(PaintInfo&, const LayoutPoint&);
     LayoutRect localSelectionRect(bool checkWhetherSelected = true) const; // This is in local coordinates, but it's a physical rect (so the top left corner is physical top left).
 
 private:
     virtual RenderBox* embeddedContentBox() const { return 0; }
-    virtual const char* renderName() const { return "RenderReplaced"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderReplaced"; }
 
-    virtual bool canHaveChildren() const { return false; }
+    virtual bool canHaveChildren() const OVERRIDE { return false; }
 
     virtual void computePreferredLogicalWidths() OVERRIDE FINAL;
     virtual void paintReplaced(PaintInfo&, const LayoutPoint&) { }
@@ -80,7 +80,7 @@
 
     virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE FINAL;
 
-    virtual bool canBeSelectionLeaf() const { return true; }
+    virtual bool canBeSelectionLeaf() const OVERRIDE { return true; }
 
     virtual LayoutRect selectionRectForRepaint(const RenderLayerModelObject* repaintContainer, bool clipToVisibleContent = true) OVERRIDE FINAL;
     void computeAspectRatioInformationForRenderBox(RenderBox*, FloatSize& constrainedSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const;
diff --git a/Source/core/rendering/RenderReplica.cpp b/Source/core/rendering/RenderReplica.cpp
index d7885c2..5b2bb61 100644
--- a/Source/core/rendering/RenderReplica.cpp
+++ b/Source/core/rendering/RenderReplica.cpp
@@ -84,7 +84,7 @@
         // Turn around and paint the parent layer. Use temporary clipRects, so that the layer doesn't end up caching clip rects
         // computing using the wrong rootLayer
         RenderLayer* rootPaintingLayer = layer()->transform() ? layer()->parent() : layer()->enclosingTransformedAncestor();
-        LayerPaintingInfo paintingInfo(rootPaintingLayer, paintInfo.rect, PaintBehaviorNormal, LayoutSize(), 0, paintInfo.renderRegion);
+        LayerPaintingInfo paintingInfo(rootPaintingLayer, paintInfo.rect, PaintBehaviorNormal, LayoutSize(), 0);
         PaintLayerFlags flags = PaintLayerHaveTransparency | PaintLayerAppliedTransform | PaintLayerTemporaryClipRects | PaintLayerPaintingReflection;
         layer()->parent()->paintLayer(paintInfo.context, paintingInfo, flags);
     } else if (paintInfo.phase == PaintPhaseMask)
diff --git a/Source/core/rendering/RenderReplica.h b/Source/core/rendering/RenderReplica.h
index 43bee56..84bbc6f 100644
--- a/Source/core/rendering/RenderReplica.h
+++ b/Source/core/rendering/RenderReplica.h
@@ -39,19 +39,19 @@
 
     virtual ~RenderReplica();
 
-    virtual const char* renderName() const { return "RenderReplica"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderReplica"; }
 
-    virtual bool requiresLayer() const { return true; }
+    virtual LayerType layerTypeRequired() const OVERRIDE { return NormalLayer; }
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
 private:
     RenderReplica();
 
-    virtual bool isReplica() const { return true; }
-    virtual void computePreferredLogicalWidths();
+    virtual bool isReplica() const OVERRIDE { return true; }
+    virtual void computePreferredLogicalWidths() OVERRIDE;
 
 };
 
diff --git a/Source/core/rendering/RenderRuby.cpp b/Source/core/rendering/RenderRuby.cpp
index 8a9ef79..ece92cd 100644
--- a/Source/core/rendering/RenderRuby.cpp
+++ b/Source/core/rendering/RenderRuby.cpp
@@ -225,7 +225,7 @@
 
 void RenderRubyAsBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
-    RenderBlock::styleDidChange(diff, oldStyle);
+    RenderBlockFlow::styleDidChange(diff, oldStyle);
     propagateStyleToAnonymousChildren();
 }
 
@@ -235,13 +235,13 @@
     if (child->isBeforeContent()) {
         if (child->isInline()) {
             // Add generated inline content normally
-            RenderBlock::addChild(child, firstChild());
+            RenderBlockFlow::addChild(child, firstChild());
         } else {
             // Wrap non-inline content with an anonymous inline-block.
             RenderBlock* beforeBlock = rubyBeforeBlock(this);
             if (!beforeBlock) {
                 beforeBlock = createAnonymousRubyInlineBlock(this);
-                RenderBlock::addChild(beforeBlock, firstChild());
+                RenderBlockFlow::addChild(beforeBlock, firstChild());
             }
             beforeBlock->addChild(child);
         }
@@ -250,13 +250,13 @@
     if (child->isAfterContent()) {
         if (child->isInline()) {
             // Add generated inline content normally
-            RenderBlock::addChild(child);
+            RenderBlockFlow::addChild(child);
         } else {
             // Wrap non-inline content with an anonymous inline-block.
             RenderBlock* afterBlock = rubyAfterBlock(this);
             if (!afterBlock) {
                 afterBlock = createAnonymousRubyInlineBlock(this);
-                RenderBlock::addChild(afterBlock);
+                RenderBlockFlow::addChild(afterBlock);
             }
             afterBlock->addChild(child);
         }
@@ -265,7 +265,7 @@
 
     // If the child is a ruby run, just add it normally.
     if (child->isRubyRun()) {
-        RenderBlock::addChild(child, beforeChild);
+        RenderBlockFlow::addChild(child, beforeChild);
         return;
     }
 
@@ -289,7 +289,7 @@
     RenderRubyRun* lastRun = lastRubyRun(this);
     if (!lastRun || lastRun->hasRubyText()) {
         lastRun = RenderRubyRun::staticCreateRubyRun(this);
-        RenderBlock::addChild(lastRun, beforeChild);
+        RenderBlockFlow::addChild(lastRun, beforeChild);
     }
     lastRun->addChild(child);
 }
@@ -300,7 +300,7 @@
     // just use the normal remove method.
     if (child->parent() == this) {
         ASSERT(child->isRubyRun() || child->isBeforeContent() || child->isAfterContent() || isAnonymousRubyInlineBlock(child));
-        RenderBlock::removeChild(child);
+        RenderBlockFlow::removeChild(child);
         return;
     }
     // If the child's parent is an anoymous block (must be generated :before/:after content)
diff --git a/Source/core/rendering/RenderRuby.h b/Source/core/rendering/RenderRuby.h
index d9da35b..afa0d55 100644
--- a/Source/core/rendering/RenderRuby.h
+++ b/Source/core/rendering/RenderRuby.h
@@ -56,18 +56,16 @@
     RenderRubyAsInline(Element*);
     virtual ~RenderRubyAsInline();
 
-    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0);
-    virtual void removeChild(RenderObject* child);
+    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
+    virtual void removeChild(RenderObject* child) OVERRIDE;
 
 protected:
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
 private:
-    virtual bool isRuby() const { return true; }
-    virtual const char* renderName() const { return "RenderRuby (inline)"; }
-    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
-    virtual bool createsAnonymousWrapper() const { return true; }
-    virtual void removeLeftoverAnonymousBlock(RenderBlock*) { ASSERT_NOT_REACHED(); }
+    virtual bool isRuby() const OVERRIDE { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderRuby (inline)"; }
+    virtual bool createsAnonymousWrapper() const OVERRIDE { return true; }
 };
 
 // <ruby> when used as 'display:block' or 'display:inline-block'
@@ -76,18 +74,18 @@
     RenderRubyAsBlock(Element*);
     virtual ~RenderRubyAsBlock();
 
-    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0);
-    virtual void removeChild(RenderObject* child);
+    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
+    virtual void removeChild(RenderObject* child) OVERRIDE;
 
 protected:
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
 private:
-    virtual bool isRuby() const { return true; }
-    virtual const char* renderName() const { return "RenderRuby (block)"; }
+    virtual bool isRuby() const OVERRIDE { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderRuby (block)"; }
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
-    virtual bool createsAnonymousWrapper() const { return true; }
-    virtual void removeLeftoverAnonymousBlock(RenderBlock*) { ASSERT_NOT_REACHED(); }
+    virtual bool createsAnonymousWrapper() const OVERRIDE { return true; }
+    virtual void removeLeftoverAnonymousBlock(RenderBlock*) OVERRIDE { ASSERT_NOT_REACHED(); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderRubyBase.h b/Source/core/rendering/RenderRubyBase.h
index 197aebb..800515d 100644
--- a/Source/core/rendering/RenderRubyBase.h
+++ b/Source/core/rendering/RenderRubyBase.h
@@ -43,17 +43,17 @@
 
     static RenderRubyBase* createAnonymous(Document*);
 
-    virtual const char* renderName() const { return "RenderRubyBase (anonymous)"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderRubyBase (anonymous)"; }
 
-    virtual bool isRubyBase() const { return true; }
+    virtual bool isRubyBase() const OVERRIDE { return true; }
 
-    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const;
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
 
 private:
     RenderRubyBase();
 
-    virtual ETextAlign textAlignmentForLine(bool endsWithSoftBreak) const;
-    virtual void adjustInlineDirectionLineBounds(int expansionOpportunityCount, float& logicalLeft, float& logicalWidth) const;
+    virtual ETextAlign textAlignmentForLine(bool endsWithSoftBreak) const OVERRIDE;
+    virtual void adjustInlineDirectionLineBounds(int expansionOpportunityCount, float& logicalLeft, float& logicalWidth) const OVERRIDE;
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
diff --git a/Source/core/rendering/RenderRubyRun.cpp b/Source/core/rendering/RenderRubyRun.cpp
index fe58c87..d89704c 100644
--- a/Source/core/rendering/RenderRubyRun.cpp
+++ b/Source/core/rendering/RenderRubyRun.cpp
@@ -91,7 +91,7 @@
     RenderRubyBase* base = rubyBase();
     if (!base) {
         base = createRubyBase();
-        RenderBlock::addChild(base);
+        RenderBlockFlow::addChild(base);
     }
     return base;
 }
@@ -119,7 +119,7 @@
             // RenderRuby has already ascertained that we can add the child here.
             ASSERT(!hasRubyText());
             // prepend ruby texts as first child
-            RenderBlock::addChild(child, firstChild());
+            RenderBlockFlow::addChild(child, firstChild());
         }  else if (beforeChild->isRubyText()) {
             // New text is inserted just before another.
             // In this case the new text takes the place of the old one, and
@@ -133,8 +133,8 @@
             // Note: Doing it in this order and not using RenderRubyRun's methods,
             // in order to avoid automatic removal of the ruby run in case there is no
             // other child besides the old ruby text.
-            RenderBlock::addChild(child, beforeChild);
-            RenderBlock::removeChild(beforeChild);
+            RenderBlockFlow::addChild(child, beforeChild);
+            RenderBlockFlow::removeChild(beforeChild);
             newRun->addChild(beforeChild);
         } else if (hasRubyBase()) {
             // Insertion before a ruby base object.
@@ -176,13 +176,13 @@
         }
     }
 
-    RenderBlock::removeChild(child);
+    RenderBlockFlow::removeChild(child);
 
     if (!beingDestroyed() && !documentBeingDestroyed()) {
         // Check if our base (if any) is now empty. If so, destroy it.
         RenderBlock* base = rubyBase();
         if (base && !base->firstChild()) {
-            RenderBlock::removeChild(base);
+            RenderBlockFlow::removeChild(base);
             base->deleteLineBoxTree();
             base->destroy();
         }
@@ -230,7 +230,7 @@
 void RenderRubyRun::layout()
 {
     LayoutRectRecorder recorder(*this);
-    RenderBlock::layout();
+    RenderBlockFlow::layout();
 
     RenderRubyText* rt = rubyText();
     if (!rt)
diff --git a/Source/core/rendering/RenderRubyRun.h b/Source/core/rendering/RenderRubyRun.h
index 2005bc1..65b1243 100644
--- a/Source/core/rendering/RenderRubyRun.h
+++ b/Source/core/rendering/RenderRubyRun.h
@@ -47,20 +47,20 @@
 
     bool hasRubyText() const;
     bool hasRubyBase() const;
-    bool isEmpty() const;
+    virtual bool isEmpty() const OVERRIDE;
     RenderRubyText* rubyText() const;
     RenderRubyBase* rubyBase() const;
     RenderRubyBase* rubyBaseSafe(); // creates the base if it doesn't already exist
 
-    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
-    virtual void layout();
+    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&) OVERRIDE;
+    virtual void layout() OVERRIDE;
 
-    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const;
-    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0);
-    virtual void removeChild(RenderObject* child);
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
+    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
+    virtual void removeChild(RenderObject* child) OVERRIDE;
 
-    virtual RenderBlock* firstLineBlock() const;
-    virtual void updateFirstLetter();
+    virtual RenderBlock* firstLineBlock() const OVERRIDE;
+    virtual void updateFirstLetter() OVERRIDE;
 
     void getOverhang(bool firstLine, RenderObject* startRenderer, RenderObject* endRenderer, int& startOverhang, int& endOverhang) const;
 
@@ -72,11 +72,11 @@
 private:
     RenderRubyRun();
 
-    virtual bool isRubyRun() const { return true; }
-    virtual const char* renderName() const { return "RenderRubyRun (anonymous)"; }
+    virtual bool isRubyRun() const OVERRIDE { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderRubyRun (anonymous)"; }
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
-    virtual bool createsAnonymousWrapper() const { return true; }
-    virtual void removeLeftoverAnonymousBlock(RenderBlock*) { }
+    virtual bool createsAnonymousWrapper() const OVERRIDE { return true; }
+    virtual void removeLeftoverAnonymousBlock(RenderBlock*) OVERRIDE { }
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderRubyRun, isRubyRun());
diff --git a/Source/core/rendering/RenderRubyText.cpp b/Source/core/rendering/RenderRubyText.cpp
index 3e5a60f..3cbc0e5 100644
--- a/Source/core/rendering/RenderRubyText.cpp
+++ b/Source/core/rendering/RenderRubyText.cpp
@@ -67,7 +67,7 @@
     ETextAlign textAlign = style()->textAlign();
     // FIXME: This check is bogus since user can set the initial value.
     if (textAlign != RenderStyle::initialTextAlign())
-        return RenderBlock::adjustInlineDirectionLineBounds(expansionOpportunityCount, logicalLeft, logicalWidth);
+        return RenderBlockFlow::adjustInlineDirectionLineBounds(expansionOpportunityCount, logicalLeft, logicalWidth);
 
     int maxPreferredLogicalWidth = this->maxPreferredLogicalWidth();
     if (maxPreferredLogicalWidth >= logicalWidth)
diff --git a/Source/core/rendering/RenderRubyText.h b/Source/core/rendering/RenderRubyText.h
index b1cb992..0f35383 100644
--- a/Source/core/rendering/RenderRubyText.h
+++ b/Source/core/rendering/RenderRubyText.h
@@ -40,19 +40,19 @@
     RenderRubyText(Element*);
     virtual ~RenderRubyText();
 
-    virtual const char* renderName() const { return "RenderRubyText"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderRubyText"; }
 
-    virtual bool isRubyText() const { return true; }
+    virtual bool isRubyText() const OVERRIDE { return true; }
 
-    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const;
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
 
 private:
-    virtual bool avoidsFloats() const;
+    virtual bool avoidsFloats() const OVERRIDE;
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
-    virtual ETextAlign textAlignmentForLine(bool endsWithSoftBreak) const;
-    virtual void adjustInlineDirectionLineBounds(int expansionOpportunityCount, float& logicalLeft, float& logicalWidth) const;
+    virtual ETextAlign textAlignmentForLine(bool endsWithSoftBreak) const OVERRIDE;
+    virtual void adjustInlineDirectionLineBounds(int expansionOpportunityCount, float& logicalLeft, float& logicalWidth) const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderScrollbar.cpp b/Source/core/rendering/RenderScrollbar.cpp
index a3aaeac..f2f7a89 100644
--- a/Source/core/rendering/RenderScrollbar.cpp
+++ b/Source/core/rendering/RenderScrollbar.cpp
@@ -156,7 +156,7 @@
     // This is because WebKit assumes scrollbar to be always painted and missing background
     // causes visual artifact like non-repainted dirty region.
     if (result && m_owningFrame && m_owningFrame->view() && !m_owningFrame->view()->isTransparent() && !result->hasBackground())
-        result->setBackgroundColor(Color::white);
+        result->setBackgroundColor(StyleColor(Color::white));
 
     return result;
 }
diff --git a/Source/core/rendering/RenderScrollbar.h b/Source/core/rendering/RenderScrollbar.h
index 07692c2..d9a9718 100644
--- a/Source/core/rendering/RenderScrollbar.h
+++ b/Source/core/rendering/RenderScrollbar.h
@@ -38,7 +38,7 @@
 class RenderScrollbarPart;
 class RenderStyle;
 
-class RenderScrollbar : public Scrollbar {
+class RenderScrollbar FINAL : public Scrollbar {
 protected:
     RenderScrollbar(ScrollableArea*, ScrollbarOrientation, Node*, Frame*);
 
@@ -57,20 +57,20 @@
 
     int minimumThumbLength();
 
-    virtual bool isOverlayScrollbar() const { return false; }
+    virtual bool isOverlayScrollbar() const OVERRIDE { return false; }
 
 private:
     virtual void setParent(Widget*) OVERRIDE;
-    virtual void setEnabled(bool);
+    virtual void setEnabled(bool) OVERRIDE;
 
-    virtual void paint(GraphicsContext*, const IntRect& damageRect);
+    virtual void paint(GraphicsContext*, const IntRect& damageRect) OVERRIDE;
 
-    virtual void setHoveredPart(ScrollbarPart);
-    virtual void setPressedPart(ScrollbarPart);
+    virtual void setHoveredPart(ScrollbarPart) OVERRIDE;
+    virtual void setPressedPart(ScrollbarPart) OVERRIDE;
 
-    virtual void styleChanged();
+    virtual void styleChanged() OVERRIDE;
 
-    virtual bool isCustomScrollbar() const { return true; }
+    virtual bool isCustomScrollbar() const OVERRIDE { return true; }
 
     void updateScrollbarParts(bool destroy = false);
 
@@ -87,14 +87,7 @@
     HashMap<unsigned, RenderScrollbarPart*> m_parts;
 };
 
-inline RenderScrollbar* toRenderScrollbar(ScrollbarThemeClient* scrollbar)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!scrollbar || scrollbar->isCustomScrollbar());
-    return static_cast<RenderScrollbar*>(scrollbar);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderScrollbar(const RenderScrollbar*);
+DEFINE_TYPE_CASTS(RenderScrollbar, ScrollbarThemeClient, scrollbar, scrollbar->isCustomScrollbar(), scrollbar.isCustomScrollbar());
 
 } // namespace WebCore
 
diff --git a/Source/core/rendering/RenderScrollbarPart.cpp b/Source/core/rendering/RenderScrollbarPart.cpp
index 13a35eb..7603d74 100644
--- a/Source/core/rendering/RenderScrollbarPart.cpp
+++ b/Source/core/rendering/RenderScrollbarPart.cpp
@@ -31,6 +31,7 @@
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderScrollbarTheme.h"
 #include "core/rendering/RenderView.h"
+#include "platform/LengthFunctions.h"
 
 using namespace std;
 
@@ -88,10 +89,10 @@
     }
 }
 
-static int calcScrollbarThicknessUsing(SizeType sizeType, const Length& length, int containingLength, RenderView* renderView)
+static int calcScrollbarThicknessUsing(SizeType sizeType, const Length& length, int containingLength)
 {
     if (!length.isIntrinsicOrAuto() || (sizeType == MinSize && length.isAuto()))
-        return minimumValueForLength(length, containingLength, renderView);
+        return minimumValueForLength(length, containingLength);
     return ScrollbarTheme::theme()->scrollbarThickness();
 }
 
@@ -99,36 +100,34 @@
 {
     if (!m_scrollbar->owningRenderer())
         return;
-    RenderView* renderView = view();
     // FIXME: We are querying layout information but nothing guarantees that it's up-to-date, especially since we are called at style change.
     // FIXME: Querying the style's border information doesn't work on table cells with collapsing borders.
     int visibleSize = m_scrollbar->owningRenderer()->width() - m_scrollbar->owningRenderer()->style()->borderLeftWidth() - m_scrollbar->owningRenderer()->style()->borderRightWidth();
-    int w = calcScrollbarThicknessUsing(MainOrPreferredSize, style()->width(), visibleSize, renderView);
-    int minWidth = calcScrollbarThicknessUsing(MinSize, style()->minWidth(), visibleSize, renderView);
-    int maxWidth = style()->maxWidth().isUndefined() ? w : calcScrollbarThicknessUsing(MaxSize, style()->maxWidth(), visibleSize, renderView);
+    int w = calcScrollbarThicknessUsing(MainOrPreferredSize, style()->width(), visibleSize);
+    int minWidth = calcScrollbarThicknessUsing(MinSize, style()->minWidth(), visibleSize);
+    int maxWidth = style()->maxWidth().isUndefined() ? w : calcScrollbarThicknessUsing(MaxSize, style()->maxWidth(), visibleSize);
     setWidth(max(minWidth, min(maxWidth, w)));
 
     // Buttons and track pieces can all have margins along the axis of the scrollbar.
-    m_marginBox.setLeft(minimumValueForLength(style()->marginLeft(), visibleSize, renderView));
-    m_marginBox.setRight(minimumValueForLength(style()->marginRight(), visibleSize, renderView));
+    m_marginBox.setLeft(minimumValueForLength(style()->marginLeft(), visibleSize));
+    m_marginBox.setRight(minimumValueForLength(style()->marginRight(), visibleSize));
 }
 
 void RenderScrollbarPart::computeScrollbarHeight()
 {
     if (!m_scrollbar->owningRenderer())
         return;
-    RenderView* renderView = view();
     // FIXME: We are querying layout information but nothing guarantees that it's up-to-date, especially since we are called at style change.
     // FIXME: Querying the style's border information doesn't work on table cells with collapsing borders.
     int visibleSize = m_scrollbar->owningRenderer()->height() -  m_scrollbar->owningRenderer()->style()->borderTopWidth() - m_scrollbar->owningRenderer()->style()->borderBottomWidth();
-    int h = calcScrollbarThicknessUsing(MainOrPreferredSize, style()->height(), visibleSize, renderView);
-    int minHeight = calcScrollbarThicknessUsing(MinSize, style()->minHeight(), visibleSize, renderView);
-    int maxHeight = style()->maxHeight().isUndefined() ? h : calcScrollbarThicknessUsing(MaxSize, style()->maxHeight(), visibleSize, renderView);
+    int h = calcScrollbarThicknessUsing(MainOrPreferredSize, style()->height(), visibleSize);
+    int minHeight = calcScrollbarThicknessUsing(MinSize, style()->minHeight(), visibleSize);
+    int maxHeight = style()->maxHeight().isUndefined() ? h : calcScrollbarThicknessUsing(MaxSize, style()->maxHeight(), visibleSize);
     setHeight(max(minHeight, min(maxHeight, h)));
 
     // Buttons and track pieces can all have margins along the axis of the scrollbar.
-    m_marginBox.setTop(minimumValueForLength(style()->marginTop(), visibleSize, renderView));
-    m_marginBox.setBottom(minimumValueForLength(style()->marginBottom(), visibleSize, renderView));
+    m_marginBox.setTop(minimumValueForLength(style()->marginTop(), visibleSize));
+    m_marginBox.setBottom(minimumValueForLength(style()->marginBottom(), visibleSize));
 }
 
 void RenderScrollbarPart::computePreferredLogicalWidths()
diff --git a/Source/core/rendering/RenderScrollbarPart.h b/Source/core/rendering/RenderScrollbarPart.h
index a1f2465..fa6695a 100644
--- a/Source/core/rendering/RenderScrollbarPart.h
+++ b/Source/core/rendering/RenderScrollbarPart.h
@@ -39,11 +39,11 @@
 
     virtual ~RenderScrollbarPart();
 
-    virtual const char* renderName() const { return "RenderScrollbarPart"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderScrollbarPart"; }
 
-    virtual bool requiresLayer() const { return false; }
+    virtual LayerType layerTypeRequired() const OVERRIDE { return NoLayer; }
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
     void paintIntoRect(GraphicsContext*, const LayoutPoint&, const LayoutRect&);
 
@@ -53,18 +53,18 @@
     virtual LayoutUnit marginLeft() const OVERRIDE { ASSERT(isIntegerValue(m_marginBox.left())); return m_marginBox.left(); }
     virtual LayoutUnit marginRight() const OVERRIDE { ASSERT(isIntegerValue(m_marginBox.right())); return m_marginBox.right(); }
 
-    virtual bool isRenderScrollbarPart() const { return true; }
+    virtual bool isRenderScrollbarPart() const OVERRIDE { return true; }
     RenderObject* rendererOwningScrollbar() const;
 
 protected:
-    virtual void styleWillChange(StyleDifference diff, const RenderStyle* newStyle);
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
-    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0);
+    virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
 private:
     RenderScrollbarPart(RenderScrollbar*, ScrollbarPart);
 
-    virtual void computePreferredLogicalWidths();
+    virtual void computePreferredLogicalWidths() OVERRIDE;
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
diff --git a/Source/core/rendering/RenderScrollbarTheme.h b/Source/core/rendering/RenderScrollbarTheme.h
index 0b5b56e..8340ca5 100644
--- a/Source/core/rendering/RenderScrollbarTheme.h
+++ b/Source/core/rendering/RenderScrollbarTheme.h
@@ -33,7 +33,7 @@
 class PlatformMouseEvent;
 class Scrollbar;
 
-class RenderScrollbarTheme : public ScrollbarTheme {
+class RenderScrollbarTheme FINAL : public ScrollbarTheme {
 public:
     virtual ~RenderScrollbarTheme() { }
 
diff --git a/Source/core/rendering/RenderSlider.h b/Source/core/rendering/RenderSlider.h
index a627e2c..5163ada 100644
--- a/Source/core/rendering/RenderSlider.h
+++ b/Source/core/rendering/RenderSlider.h
@@ -39,13 +39,13 @@
     bool inDragMode() const;
 
 private:
-    virtual const char* renderName() const { return "RenderSlider"; }
-    virtual bool isSlider() const { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSlider"; }
+    virtual bool isSlider() const OVERRIDE { return true; }
 
-    virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
+    virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE;
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
     SliderThumbElement* sliderThumbElement() const;
 };
diff --git a/Source/core/rendering/RenderTable.cpp b/Source/core/rendering/RenderTable.cpp
index b0b848b..80fe1d6 100644
--- a/Source/core/rendering/RenderTable.cpp
+++ b/Source/core/rendering/RenderTable.cpp
@@ -28,7 +28,6 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/html/HTMLTableElement.h"
 #include "core/frame/FrameView.h"
 #include "core/rendering/AutoTableLayout.h"
 #include "core/rendering/FixedTableLayout.h"
@@ -63,6 +62,7 @@
     , m_needsSectionRecalc(false)
     , m_columnLogicalWidthChanged(false)
     , m_columnRenderersValid(false)
+    , m_hasCellColspanThatDeterminesTableWidth(false)
     , m_hSpacing(0)
     , m_vSpacing(0)
     , m_borderStart(0)
@@ -117,6 +117,14 @@
         ptr = 0;
 }
 
+static inline bool needsTableSection(RenderObject* object)
+{
+    // Return true if 'object' can't exist in an anonymous table without being
+    // wrapped in a table section box.
+    EDisplay display = object->style()->display();
+    return display != TABLE_CAPTION && display != TABLE_COLUMN_GROUP && display != TABLE_COLUMN;
+}
+
 void RenderTable::addChild(RenderObject* child, RenderObject* beforeChild)
 {
     bool wrapInAnonymousSection = !child->isOutOfFlowPositioned();
@@ -156,9 +164,7 @@
             default:
                 ASSERT_NOT_REACHED();
         }
-    } else if (child->isTableCell() || child->isTableRow())
-        wrapInAnonymousSection = true;
-    else
+    } else
         wrapInAnonymousSection = true;
 
     if (child->isTableSection())
@@ -186,7 +192,7 @@
     }
 
     RenderObject* lastBox = beforeChild;
-    while (lastBox && lastBox->parent()->isAnonymous() && !lastBox->isTableSection() && lastBox->style()->display() != TABLE_CAPTION && lastBox->style()->display() != TABLE_COLUMN_GROUP)
+    while (lastBox && lastBox->parent()->isAnonymous() && !lastBox->isTableSection() && needsTableSection(lastBox))
         lastBox = lastBox->parent();
     if (lastBox && lastBox->isAnonymous() && !isAfterContent(lastBox)) {
         if (beforeChild == lastBox)
@@ -195,7 +201,7 @@
         return;
     }
 
-    if (beforeChild && !beforeChild->isTableSection() && beforeChild->style()->display() != TABLE_CAPTION && beforeChild->style()->display() != TABLE_COLUMN_GROUP)
+    if (beforeChild && !beforeChild->isTableSection() && needsTableSection(beforeChild))
         beforeChild = 0;
 
     RenderTableSection* section = RenderTableSection::createAnonymousWithParentRenderer(this);
@@ -253,7 +259,6 @@
     }
 
     RenderBlock* cb = containingBlock();
-    RenderView* renderView = view();
 
     LayoutUnit availableLogicalWidth = containingBlockLogicalWidthForContent();
     bool hasPerpendicularContainingBlock = cb->style()->isHorizontalWritingMode() != style()->isHorizontalWritingMode();
@@ -264,16 +269,14 @@
         setLogicalWidth(convertStyleLogicalWidthToComputedWidth(styleLogicalWidth, containerWidthInInlineDirection));
     else {
         // Subtract out any fixed margins from our available width for auto width tables.
-        LayoutUnit marginStart = minimumValueForLength(style()->marginStart(), availableLogicalWidth, renderView);
-        LayoutUnit marginEnd = minimumValueForLength(style()->marginEnd(), availableLogicalWidth, renderView);
+        LayoutUnit marginStart = minimumValueForLength(style()->marginStart(), availableLogicalWidth);
+        LayoutUnit marginEnd = minimumValueForLength(style()->marginEnd(), availableLogicalWidth);
         LayoutUnit marginTotal = marginStart + marginEnd;
 
         // Subtract out our margins to get the available content width.
         LayoutUnit availableContentLogicalWidth = max<LayoutUnit>(0, containerWidthInInlineDirection - marginTotal);
-        if (shrinkToAvoidFloats() && cb->containsFloats() && !hasPerpendicularContainingBlock) {
-            // FIXME: Work with regions someday.
-            availableContentLogicalWidth = shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb), 0);
-        }
+        if (shrinkToAvoidFloats() && cb->containsFloats() && !hasPerpendicularContainingBlock)
+            availableContentLogicalWidth = shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb));
 
         // Ensure we aren't bigger than our available width.
         setLogicalWidth(min<int>(availableContentLogicalWidth, maxPreferredLogicalWidth()));
@@ -303,7 +306,7 @@
     if (!hasPerpendicularContainingBlock) {
         LayoutUnit containerLogicalWidthForAutoMargins = availableLogicalWidth;
         if (avoidsFloats() && cb->containsFloats())
-            containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(0); // FIXME: Work with regions someday.
+            containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidth();
         ComputedMarginValues marginValues;
         bool hasInvertedDirection =  cb->style()->isLeftToRightDirection() == style()->isLeftToRightDirection();
         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, logicalWidth(),
@@ -312,8 +315,8 @@
         setMarginStart(marginValues.m_start);
         setMarginEnd(marginValues.m_end);
     } else {
-        setMarginStart(minimumValueForLength(style()->marginStart(), availableLogicalWidth, renderView));
-        setMarginEnd(minimumValueForLength(style()->marginEnd(), availableLogicalWidth, renderView));
+        setMarginStart(minimumValueForLength(style()->marginStart(), availableLogicalWidth));
+        setMarginEnd(minimumValueForLength(style()->marginEnd(), availableLogicalWidth));
     }
 
     // We should NEVER shrink the table below the min-content logical width, or else the table can't accomodate
@@ -331,11 +334,11 @@
 
     // HTML tables' width styles already include borders and paddings, but CSS tables' width styles do not.
     LayoutUnit borders = 0;
-    bool isCSSTable = !node() || !isHTMLTableElement(node());
+    bool isCSSTable = !node() || !node()->hasTagName(tableTag);
     if (isCSSTable && styleLogicalWidth.isSpecified() && styleLogicalWidth.isPositive() && style()->boxSizing() == CONTENT_BOX)
         borders = borderStart() + borderEnd() + (collapseBorders() ? LayoutUnit() : paddingStart() + paddingEnd());
 
-    return minimumValueForLength(styleLogicalWidth, availableWidth, view()) + borders;
+    return minimumValueForLength(styleLogicalWidth, availableWidth) + borders;
 }
 
 LayoutUnit RenderTable::convertStyleLogicalHeightToComputedHeight(const Length& styleLogicalHeight)
@@ -348,14 +351,12 @@
         // HTML tables size as though CSS height includes border/padding, CSS tables do not.
         LayoutUnit borders = LayoutUnit();
         // FIXME: We cannot apply box-sizing: content-box on <table> which other browsers allow.
-        if ((node() && isHTMLTableElement(node())) || style()->boxSizing() == BORDER_BOX) {
+        if ((node() && node()->hasTagName(tableTag)) || style()->boxSizing() == BORDER_BOX) {
             borders = borderAndPadding;
         }
         computedLogicalHeight = styleLogicalHeight.value() - borders;
     } else if (styleLogicalHeight.isPercent())
         computedLogicalHeight = computePercentageLogicalHeight(styleLogicalHeight);
-    else if (styleLogicalHeight.isViewportPercentage())
-        computedLogicalHeight = minimumValueForLength(styleLogicalHeight, 0, view());
     else if (styleLogicalHeight.isIntrinsic())
         computedLogicalHeight = computeIntrinsicLogicalContentHeightUsing(styleLogicalHeight, logicalHeight() - borderAndPadding, borderAndPadding);
     else
@@ -370,17 +371,22 @@
     if (caption->needsLayout()) {
         // The margins may not be available but ensure the caption is at least located beneath any previous sibling caption
         // so that it does not mistakenly think any floats in the previous caption intrude into it.
-        caption->setLogicalLocation(LayoutPoint(caption->marginStart(), caption->marginBefore() + logicalHeight()));
+        caption->setLogicalLocation(LayoutPoint(caption->marginStart(), collapsedMarginBeforeForChild(caption) + logicalHeight()));
         // If RenderTableCaption ever gets a layout() function, use it here.
         caption->layoutIfNeeded();
     }
     // Apply the margins to the location now that they are definitely available from layout
-    caption->setLogicalLocation(LayoutPoint(caption->marginStart(), caption->marginBefore() + logicalHeight()));
+    LayoutUnit captionLogicalTop = collapsedMarginBeforeForChild(caption) + logicalHeight();
+    if (view()->layoutState()->isPaginated()) {
+        captionLogicalTop += caption->paginationStrut();
+        caption->setPaginationStrut(0);
+    }
+    caption->setLogicalLocation(LayoutPoint(caption->marginStart(), captionLogicalTop));
 
     if (!selfNeedsLayout() && caption->checkForRepaintDuringLayout())
         caption->repaintDuringLayoutIfMoved(captionRect);
 
-    setLogicalHeight(logicalHeight() + caption->logicalHeight() + caption->marginBefore() + caption->marginAfter());
+    setLogicalHeight(logicalHeight() + caption->logicalHeight() + collapsedMarginBeforeForChild(caption) + collapsedMarginAfterForChild(caption));
 }
 
 void RenderTable::distributeExtraLogicalHeight(int extraLogicalHeight)
@@ -570,7 +576,8 @@
 
     bool didFullRepaint = repainter.repaintAfterLayout();
     // Repaint with our new bounds if they are different from our old bounds.
-    if (!didFullRepaint && sectionMoved) {
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()
+        && !didFullRepaint && sectionMoved) {
         if (style()->isHorizontalWritingMode())
             repaintRectangle(LayoutRect(visualOverflowRect().x(), movedSectionLogicalTop, visualOverflowRect().width(), visualOverflowRect().maxY() - movedSectionLogicalTop));
         else
@@ -773,13 +780,13 @@
         m_minPreferredLogicalWidth = max(m_minPreferredLogicalWidth, m_captions[i]->minPreferredLogicalWidth());
 
     RenderStyle* styleToUse = style();
-    // FIXME: This should probably be checking for isSpecified since you should be able to use percentage, calc or viewport relative values for min-width.
+    // FIXME: This should probably be checking for isSpecified since you should be able to use percentage or calc values for min-width.
     if (styleToUse->logicalMinWidth().isFixed() && styleToUse->logicalMinWidth().value() > 0) {
         m_maxPreferredLogicalWidth = std::max(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
         m_minPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
     }
 
-    // FIXME: This should probably be checking for isSpecified since you should be able to use percentage, calc or viewport relative values for maxWidth.
+    // FIXME: This should probably be checking for isSpecified since you should be able to use percentage or calc values for maxWidth.
     if (styleToUse->logicalMaxWidth().isFixed()) {
         // We don't constrain m_minPreferredLogicalWidth as the table should be at least the size of its min-content, regardless of 'max-width'.
         m_maxPreferredLogicalWidth = std::min(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMaxWidth().value()));
@@ -827,6 +834,10 @@
     unsigned newColumnIndex = m_columns.size();
     m_columns.append(ColumnStruct(span));
 
+    // Unless the table has cell(s) with colspan that exceed the number of columns afforded
+    // by the other rows in the table we can use the fast path when mapping columns to effective columns.
+    m_hasCellColspanThatDeterminesTableWidth = m_hasCellColspanThatDeterminesTableWidth || span > 1;
+
     // Propagate the change in our columns representation to the sections that don't need
     // cell recalc. If they do, they will be synced up directly with m_columns later.
     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
@@ -901,6 +912,7 @@
     m_foot = 0;
     m_firstBody = 0;
     m_hasColElements = false;
+    m_hasCellColspanThatDeterminesTableWidth = hasCellColspanThatDeterminesTableWidth();
 
     // We need to get valid pointers to caption, head, foot and first body again
     RenderObject* nextSibling;
@@ -1331,9 +1343,12 @@
 int RenderTable::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
 {
     ASSERT(linePositionMode == PositionOnContainingLine);
-    LayoutUnit baseline = firstLineBoxBaseline();
-    if (baseline != -1)
+    int baseline = firstLineBoxBaseline();
+    if (baseline != -1) {
+        if (isInline())
+            return beforeMarginInLineDirection(direction) + baseline;
         return baseline;
+    }
 
     return RenderBox::baselinePosition(baselineType, firstLine, direction, linePositionMode);
 }
@@ -1367,9 +1382,9 @@
     return -1;
 }
 
-LayoutRect RenderTable::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy)
+LayoutRect RenderTable::overflowClipRect(const LayoutPoint& location, OverlayScrollbarSizeRelevancy relevancy)
 {
-    LayoutRect rect = RenderBlock::overflowClipRect(location, region, relevancy);
+    LayoutRect rect = RenderBlock::overflowClipRect(location, relevancy);
 
     // If we have a caption, expand the clip to include the caption.
     // FIXME: Technically this is wrong, but it's virtually impossible to fix this
@@ -1395,7 +1410,7 @@
     LayoutPoint adjustedLocation = accumulatedOffset + location();
 
     // Check kids first.
-    if (!hasOverflowClip() || locationInContainer.intersects(overflowClipRect(adjustedLocation, locationInContainer.region()))) {
+    if (!hasOverflowClip() || locationInContainer.intersects(overflowClipRect(adjustedLocation))) {
         for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
             if (child->isBox() && !toRenderBox(child)->hasSelfPaintingLayer() && (child->isTableSection() || child->isTableCaption())) {
                 LayoutPoint childPoint = flipForWritingModeForChild(toRenderBox(child), adjustedLocation);
diff --git a/Source/core/rendering/RenderTable.h b/Source/core/rendering/RenderTable.h
index ba7ab67..9c460df 100644
--- a/Source/core/rendering/RenderTable.h
+++ b/Source/core/rendering/RenderTable.h
@@ -52,33 +52,33 @@
 
     bool collapseBorders() const { return style()->borderCollapse(); }
 
-    int borderStart() const { return m_borderStart; }
-    int borderEnd() const { return m_borderEnd; }
-    int borderBefore() const;
-    int borderAfter() const;
+    virtual int borderStart() const OVERRIDE { return m_borderStart; }
+    virtual int borderEnd() const OVERRIDE { return m_borderEnd; }
+    virtual int borderBefore() const OVERRIDE;
+    virtual int borderAfter() const OVERRIDE;
 
-    int borderLeft() const
+    virtual int borderLeft() const OVERRIDE
     {
         if (style()->isHorizontalWritingMode())
             return style()->isLeftToRightDirection() ? borderStart() : borderEnd();
         return style()->isFlippedBlocksWritingMode() ? borderAfter() : borderBefore();
     }
 
-    int borderRight() const
+    virtual int borderRight() const OVERRIDE
     {
         if (style()->isHorizontalWritingMode())
             return style()->isLeftToRightDirection() ? borderEnd() : borderStart();
         return style()->isFlippedBlocksWritingMode() ? borderBefore() : borderAfter();
     }
 
-    int borderTop() const
+    virtual int borderTop() const OVERRIDE
     {
         if (style()->isHorizontalWritingMode())
             return style()->isFlippedBlocksWritingMode() ? borderAfter() : borderBefore();
         return style()->isLeftToRightDirection() ? borderStart() : borderEnd();
     }
 
-    int borderBottom() const
+    virtual int borderBottom() const OVERRIDE
     {
         if (style()->isHorizontalWritingMode())
             return style()->isFlippedBlocksWritingMode() ? borderBefore() : borderAfter();
@@ -124,7 +124,7 @@
     int calcBorderEnd() const;
     void recalcBordersInRowDirection();
 
-    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0);
+    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
 
     struct ColumnStruct {
         explicit ColumnStruct(unsigned initialSpan = 1)
@@ -171,6 +171,9 @@
 
     unsigned colToEffCol(unsigned column) const
     {
+        if (!m_hasCellColspanThatDeterminesTableWidth)
+            return column;
+
         unsigned effColumn = 0;
         unsigned numColumns = numEffCols();
         for (unsigned c = 0; effColumn < numColumns && c + m_columns[effColumn].span - 1 < column; ++effColumn)
@@ -180,6 +183,9 @@
 
     unsigned effColToCol(unsigned effCol) const
     {
+        if (!m_hasCellColspanThatDeterminesTableWidth)
+            return effCol;
+
         unsigned c = 0;
         for (unsigned i = 0; i < effCol; i++)
             c += m_columns[i].span;
@@ -263,21 +269,21 @@
     void removeColumn(const RenderTableCol*);
 
 protected:
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
-    virtual void simplifiedNormalFlowLayout();
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+    virtual void simplifiedNormalFlowLayout() OVERRIDE;
 
 private:
-    virtual const char* renderName() const { return "RenderTable"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderTable"; }
 
-    virtual bool isTable() const { return true; }
+    virtual bool isTable() const OVERRIDE { return true; }
 
-    virtual bool avoidsFloats() const { return true; }
+    virtual bool avoidsFloats() const OVERRIDE { return true; }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
-    virtual void paintObject(PaintInfo&, const LayoutPoint&);
-    virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&);
-    virtual void paintMask(PaintInfo&, const LayoutPoint&);
-    virtual void layout();
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual void paintObject(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual void paintMask(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual void layout() OVERRIDE;
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth) const OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE;
@@ -292,17 +298,17 @@
     void updateColumnCache() const;
     void invalidateCachedColumns();
 
-    virtual RenderBlock* firstLineBlock() const;
-    virtual void updateFirstLetter();
+    virtual RenderBlock* firstLineBlock() const OVERRIDE;
+    virtual void updateFirstLetter() OVERRIDE;
 
     virtual void updateLogicalWidth() OVERRIDE;
 
     LayoutUnit convertStyleLogicalWidthToComputedWidth(const Length& styleLogicalWidth, LayoutUnit availableWidth);
     LayoutUnit convertStyleLogicalHeightToComputedHeight(const Length& styleLogicalHeight);
 
-    virtual LayoutRect overflowClipRect(const LayoutPoint& location, RenderRegion*, OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize);
+    virtual LayoutRect overflowClipRect(const LayoutPoint& location, OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) OVERRIDE;
 
-    virtual void addOverflowFromChildren();
+    virtual void addOverflowFromChildren() OVERRIDE;
 
     void subtractCaptionRect(LayoutRect&) const;
 
@@ -332,6 +338,15 @@
 
     bool m_columnLogicalWidthChanged : 1;
     mutable bool m_columnRenderersValid: 1;
+    mutable bool m_hasCellColspanThatDeterminesTableWidth : 1;
+    bool hasCellColspanThatDeterminesTableWidth() const
+    {
+        for (unsigned c = 0; c < numEffCols(); c++) {
+            if (m_columns[c].span > 1)
+                return true;
+        }
+        return false;
+    }
 
     short m_hSpacing;
     short m_vSpacing;
diff --git a/Source/core/rendering/RenderTableCaption.cpp b/Source/core/rendering/RenderTableCaption.cpp
index af677b7..24dc5ec 100644
--- a/Source/core/rendering/RenderTableCaption.cpp
+++ b/Source/core/rendering/RenderTableCaption.cpp
@@ -48,7 +48,7 @@
 
 void RenderTableCaption::willBeRemovedFromTree()
 {
-    RenderBlock::willBeRemovedFromTree();
+    RenderBlockFlow::willBeRemovedFromTree();
 
     table()->removeCaption(this);
 }
diff --git a/Source/core/rendering/RenderTableCell.cpp b/Source/core/rendering/RenderTableCell.cpp
index 9737da4..e33032a 100644
--- a/Source/core/rendering/RenderTableCell.cpp
+++ b/Source/core/rendering/RenderTableCell.cpp
@@ -66,7 +66,7 @@
 
 void RenderTableCell::willBeRemovedFromTree()
 {
-    RenderBlock::willBeRemovedFromTree();
+    RenderBlockFlow::willBeRemovedFromTree();
 
     section()->setNeedsCellRecalc();
     section()->removeCachedCollapsedBorders(this);
@@ -149,7 +149,7 @@
     // grids.  We must refresh those grids before the child cells try to use them.
     table()->recalcSectionsIfNeeded();
 
-    RenderBlock::computePreferredLogicalWidths();
+    RenderBlockFlow::computePreferredLogicalWidths();
     if (node() && style()->autoWrap()) {
         // See if nowrap was set.
         Length w = styleOrColLogicalWidth();
@@ -311,7 +311,7 @@
 {
     ASSERT(o == container());
 
-    LayoutSize offset = RenderBlock::offsetFromContainer(o, point, offsetDependsOnPoint);
+    LayoutSize offset = RenderBlockFlow::offsetFromContainer(o, point, offsetDependsOnPoint);
     if (parent())
         offset -= parentBox()->locationOffset();
 
@@ -325,7 +325,7 @@
     // the table is going to recalculate the grid, relayout and repaint its current rect, which
     // includes any outside borders of this cell.
     if (!table()->collapseBorders() || table()->needsSectionRecalc())
-        return RenderBlock::clippedOverflowRectForRepaint(repaintContainer);
+        return RenderBlockFlow::clippedOverflowRectForRepaint(repaintContainer);
 
     bool rtl = !styleForCellFlow()->isLeftToRightDirection();
     int outlineSize = style()->outlineSize();
@@ -360,10 +360,12 @@
     LayoutPoint location(max<LayoutUnit>(left, -visualOverflowRect().x()), max<LayoutUnit>(top, -visualOverflowRect().y()));
     LayoutRect r(-location.x(), -location.y(), location.x() + max(width() + right, visualOverflowRect().maxX()), location.y() + max(height() + bottom, visualOverflowRect().maxY()));
 
-    if (RenderView* v = view()) {
-        // FIXME: layoutDelta needs to be applied in parts before/after transforms and
-        // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
-        r.move(v->layoutDelta());
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+        if (RenderView* v = view()) {
+            // FIXME: layoutDelta needs to be applied in parts before/after transforms and
+            // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
+            r.move(v->layoutDelta());
+        }
     }
     computeRectForRepaint(repaintContainer, r);
     return r;
@@ -377,7 +379,7 @@
     RenderView* v = view();
     if ((!v || !v->layoutStateEnabled() || repaintContainer) && parent())
         r.moveBy(-parentBox()->location()); // Rows are in the same coordinate space, so don't add their offset in.
-    RenderBlock::computeRectForRepaint(repaintContainer, r, fixed);
+    RenderBlockFlow::computeRectForRepaint(repaintContainer, r, fixed);
 }
 
 LayoutUnit RenderTableCell::cellBaselinePosition() const
@@ -396,7 +398,7 @@
     ASSERT(style()->display() == TABLE_CELL);
     ASSERT(!row() || row()->rowIndexWasSet());
 
-    RenderBlock::styleDidChange(diff, oldStyle);
+    RenderBlockFlow::styleDidChange(diff, oldStyle);
     setHasBoxDecorations(true);
 
     if (parent() && section() && oldStyle && style()->height() != oldStyle->height())
@@ -894,44 +896,44 @@
 
 int RenderTableCell::borderLeft() const
 {
-    return table()->collapseBorders() ? borderHalfLeft(false) : RenderBlock::borderLeft();
+    return table()->collapseBorders() ? borderHalfLeft(false) : RenderBlockFlow::borderLeft();
 }
 
 int RenderTableCell::borderRight() const
 {
-    return table()->collapseBorders() ? borderHalfRight(false) : RenderBlock::borderRight();
+    return table()->collapseBorders() ? borderHalfRight(false) : RenderBlockFlow::borderRight();
 }
 
 int RenderTableCell::borderTop() const
 {
-    return table()->collapseBorders() ? borderHalfTop(false) : RenderBlock::borderTop();
+    return table()->collapseBorders() ? borderHalfTop(false) : RenderBlockFlow::borderTop();
 }
 
 int RenderTableCell::borderBottom() const
 {
-    return table()->collapseBorders() ? borderHalfBottom(false) : RenderBlock::borderBottom();
+    return table()->collapseBorders() ? borderHalfBottom(false) : RenderBlockFlow::borderBottom();
 }
 
 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=46191, make the collapsed border drawing
 // work with different block flow values instead of being hard-coded to top-to-bottom.
 int RenderTableCell::borderStart() const
 {
-    return table()->collapseBorders() ? borderHalfStart(false) : RenderBlock::borderStart();
+    return table()->collapseBorders() ? borderHalfStart(false) : RenderBlockFlow::borderStart();
 }
 
 int RenderTableCell::borderEnd() const
 {
-    return table()->collapseBorders() ? borderHalfEnd(false) : RenderBlock::borderEnd();
+    return table()->collapseBorders() ? borderHalfEnd(false) : RenderBlockFlow::borderEnd();
 }
 
 int RenderTableCell::borderBefore() const
 {
-    return table()->collapseBorders() ? borderHalfBefore(false) : RenderBlock::borderBefore();
+    return table()->collapseBorders() ? borderHalfBefore(false) : RenderBlockFlow::borderBefore();
 }
 
 int RenderTableCell::borderAfter() const
 {
-    return table()->collapseBorders() ? borderHalfAfter(false) : RenderBlock::borderAfter();
+    return table()->collapseBorders() ? borderHalfAfter(false) : RenderBlockFlow::borderAfter();
 }
 
 int RenderTableCell::borderHalfLeft(bool outer) const
@@ -1001,7 +1003,7 @@
 void RenderTableCell::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     ASSERT(paintInfo.phase != PaintPhaseCollapsedTableBorders);
-    RenderBlock::paint(paintInfo, paintOffset);
+    RenderBlockFlow::paint(paintInfo, paintOffset);
 }
 
 static EBorderStyle collapsedBorderStyle(EBorderStyle style)
@@ -1159,7 +1161,7 @@
     for (CollapsedBorder* border = borders.nextBorder(); border; border = borders.nextBorder()) {
         if (border->borderValue.isSameIgnoringColor(*table()->currentBorderValue())) {
             drawLineForBoxSide(graphicsContext, border->x1, border->y1, border->x2, border->y2, border->side,
-                resolveColor(border->borderValue.color()), border->style, 0, 0, antialias);
+                border->borderValue.color().resolve(style()->visitedDependentColor(CSSPropertyColor)), border->style, 0, 0, antialias);
         }
     }
 }
@@ -1186,7 +1188,7 @@
     Color c = backgroundObject->resolveColor(CSSPropertyBackgroundColor);
     const FillLayer* bgLayer = backgroundObject->style()->backgroundLayers();
 
-    if (bgLayer->hasImage() || c.isValid()) {
+    if (bgLayer->hasImage() || c.alpha()) {
         // We have to clip here because the background would paint
         // on top of the borders otherwise.  This only matters for cells and rows.
         bool shouldClip = backgroundObject->hasLayer() && (backgroundObject == this || backgroundObject == parent()) && tableElt->collapseBorders();
diff --git a/Source/core/rendering/RenderTableCell.h b/Source/core/rendering/RenderTableCell.h
index 9eeb48e..212cc05 100644
--- a/Source/core/rendering/RenderTableCell.h
+++ b/Source/core/rendering/RenderTableCell.h
@@ -28,6 +28,7 @@
 #include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderTableRow.h"
 #include "core/rendering/RenderTableSection.h"
+#include "platform/LengthFunctions.h"
 
 namespace WebCore {
 
@@ -97,7 +98,7 @@
     {
         // FIXME: This function does too much work, and is very hot during table layout!
         int adjustedLogicalHeight = pixelSnappedLogicalHeight() - (intrinsicPaddingBefore() + intrinsicPaddingAfter());
-        int styleLogicalHeight = valueForLength(style()->logicalHeight(), 0, view());
+        int styleLogicalHeight = valueForLength(style()->logicalHeight(), 0);
         // In strict mode, box-sizing: content-box do the right thing and actually add in the border and padding.
         // Call computedCSSPadding* directly to avoid including implicitPadding.
         if (!document().inQuirksMode() && style()->boxSizing() != BORDER_BOX)
@@ -108,23 +109,23 @@
 
     void setCellLogicalWidth(int constrainedLogicalWidth, SubtreeLayoutScope&);
 
-    virtual int borderLeft() const;
-    virtual int borderRight() const;
-    virtual int borderTop() const;
-    virtual int borderBottom() const;
-    virtual int borderStart() const;
-    virtual int borderEnd() const;
-    virtual int borderBefore() const;
-    virtual int borderAfter() const;
+    virtual int borderLeft() const OVERRIDE;
+    virtual int borderRight() const OVERRIDE;
+    virtual int borderTop() const OVERRIDE;
+    virtual int borderBottom() const OVERRIDE;
+    virtual int borderStart() const OVERRIDE;
+    virtual int borderEnd() const OVERRIDE;
+    virtual int borderBefore() const OVERRIDE;
+    virtual int borderAfter() const OVERRIDE;
 
     void collectBorderValues(RenderTable::CollapsedBorderValues&) const;
     static void sortBorderValues(RenderTable::CollapsedBorderValues&);
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     void paintCollapsedBorders(PaintInfo&, const LayoutPoint&);
     void paintBackgroundsBehindCell(PaintInfo&, const LayoutPoint&, RenderObject* backgroundObject);
@@ -155,7 +156,7 @@
 
     void setOverrideLogicalContentHeightFromRowHeight(LayoutUnit);
 
-    virtual void scrollbarsChanged(bool horizontalScrollbarChanged, bool verticalScrollbarChanged);
+    virtual void scrollbarsChanged(bool horizontalScrollbarChanged, bool verticalScrollbarChanged) OVERRIDE;
 
     bool cellWidthChanged() const { return m_cellWidthChanged; }
     void setCellWidthChanged(bool b = true) { m_cellWidthChanged = b; }
@@ -216,26 +217,26 @@
     }
 #endif
 protected:
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
-    virtual void computePreferredLogicalWidths();
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+    virtual void computePreferredLogicalWidths() OVERRIDE;
 
     virtual void addLayerHitTestRects(LayerHitTestRects&, const RenderLayer* currentCompositedLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const OVERRIDE;
 
 private:
-    virtual const char* renderName() const { return (isAnonymous() || isPseudoElement()) ? "RenderTableCell (anonymous)" : "RenderTableCell"; }
+    virtual const char* renderName() const OVERRIDE { return (isAnonymous() || isPseudoElement()) ? "RenderTableCell (anonymous)" : "RenderTableCell"; }
 
-    virtual bool isTableCell() const { return true; }
+    virtual bool isTableCell() const OVERRIDE { return true; }
 
     virtual void willBeRemovedFromTree() OVERRIDE;
 
     virtual void updateLogicalWidth() OVERRIDE;
 
-    virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&);
-    virtual void paintMask(PaintInfo&, const LayoutPoint&);
+    virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual void paintMask(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     virtual bool boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance, InlineFlowBox*) const OVERRIDE;
 
-    virtual LayoutSize offsetFromContainer(RenderObject*, const LayoutPoint&, bool* offsetDependsOnPoint = 0) const;
+    virtual LayoutSize offsetFromContainer(RenderObject*, const LayoutPoint&, bool* offsetDependsOnPoint = 0) const OVERRIDE;
     virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const OVERRIDE;
     virtual void computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect&, bool fixed = false) const OVERRIDE;
 
diff --git a/Source/core/rendering/RenderTableCol.h b/Source/core/rendering/RenderTableCol.h
index a28f360..f3ccef5 100644
--- a/Source/core/rendering/RenderTableCol.h
+++ b/Source/core/rendering/RenderTableCol.h
@@ -77,25 +77,25 @@
     const BorderValue& borderAdjoiningCellAfter(const RenderTableCell*) const;
 
 private:
-    virtual RenderObjectChildList* virtualChildren() { return children(); }
-    virtual const RenderObjectChildList* virtualChildren() const { return children(); }
+    virtual RenderObjectChildList* virtualChildren() OVERRIDE { return children(); }
+    virtual const RenderObjectChildList* virtualChildren() const OVERRIDE { return children(); }
 
-    virtual const char* renderName() const { return "RenderTableCol"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderTableCol"; }
     virtual bool isRenderTableCol() const OVERRIDE { return true; }
-    virtual void updateFromElement();
+    virtual void updateFromElement() OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE { ASSERT_NOT_REACHED(); }
 
     virtual void insertedIntoTree() OVERRIDE;
     virtual void willBeRemovedFromTree() OVERRIDE;
 
-    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const;
-    virtual bool canHaveChildren() const;
-    virtual bool requiresLayer() const { return false; }
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
+    virtual bool canHaveChildren() const OVERRIDE;
+    virtual LayerType layerTypeRequired() const OVERRIDE { return NoLayer; }
 
     virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const OVERRIDE;
-    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0);
+    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     RenderTable* table() const;
 
diff --git a/Source/core/rendering/RenderTableRow.cpp b/Source/core/rendering/RenderTableRow.cpp
index 528ae08..02cc260 100644
--- a/Source/core/rendering/RenderTableRow.cpp
+++ b/Source/core/rendering/RenderTableRow.cpp
@@ -181,15 +181,21 @@
         }
     }
 
-    // We only ever need to repaint if our cells didn't, which menas that they didn't need
+    // We only ever need to repaint if our cells didn't, which means that they didn't need
     // layout, so we know that our bounds didn't change. This code is just making up for
     // the fact that we did not repaint in setStyle() because we had a layout hint.
     // We cannot call repaint() because our clippedOverflowRectForRepaint() is taken from the
     // parent table, and being mid-layout, that is invalid. Instead, we repaint our cells.
-    if (selfNeedsLayout() && checkForRepaintDuringLayout()) {
+    if (selfNeedsLayout() && checkForRepaint()) {
         for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
-            if (child->isTableCell())
-                child->repaint();
+            if (child->isTableCell()) {
+                if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+                    // FIXME: Is this needed with repaint After Layout?
+                    child->setShouldDoFullRepaintAfterLayout(true);
+                } else {
+                    child->repaint();
+                }
+            }
         }
     }
 
diff --git a/Source/core/rendering/RenderTableRow.h b/Source/core/rendering/RenderTableRow.h
index 735f903..28be9df 100644
--- a/Source/core/rendering/RenderTableRow.h
+++ b/Source/core/rendering/RenderTableRow.h
@@ -89,27 +89,36 @@
     const BorderValue& borderAdjoiningEndCell(const RenderTableCell*) const;
 
 private:
-    virtual RenderObjectChildList* virtualChildren() { return children(); }
-    virtual const RenderObjectChildList* virtualChildren() const { return children(); }
+    virtual RenderObjectChildList* virtualChildren() OVERRIDE { return children(); }
+    virtual const RenderObjectChildList* virtualChildren() const OVERRIDE { return children(); }
 
-    virtual const char* renderName() const { return (isAnonymous() || isPseudoElement()) ? "RenderTableRow (anonymous)" : "RenderTableRow"; }
+    virtual const char* renderName() const OVERRIDE { return (isAnonymous() || isPseudoElement()) ? "RenderTableRow (anonymous)" : "RenderTableRow"; }
 
-    virtual bool isTableRow() const { return true; }
+    virtual bool isTableRow() const OVERRIDE { return true; }
 
     virtual void willBeRemovedFromTree() OVERRIDE;
 
-    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0);
-    virtual void layout();
-    virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const;
+    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
+    virtual void layout() OVERRIDE;
+    virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const OVERRIDE;
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 
-    virtual bool requiresLayer() const OVERRIDE { return hasOverflowClip() || hasTransform() || hasHiddenBackface() || hasClipPath() || createsGroup(); }
+    virtual LayerType layerTypeRequired() const OVERRIDE
+    {
+        if (hasTransform() || hasHiddenBackface() || hasClipPath() || createsGroup() || isStickyPositioned())
+            return NormalLayer;
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+        if (hasOverflowClip())
+            return OverflowClipLayer;
 
-    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0);
+        return NoLayer;
+    }
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
+
+    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
+
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     RenderObjectChildList m_children;
     unsigned m_rowIndex : 31;
diff --git a/Source/core/rendering/RenderTableSection.cpp b/Source/core/rendering/RenderTableSection.cpp
index ab6d4da..c88b490 100644
--- a/Source/core/rendering/RenderTableSection.cpp
+++ b/Source/core/rendering/RenderTableSection.cpp
@@ -619,8 +619,7 @@
 
     RenderTableCell* cell;
 
-    RenderView* viewRenderer = view();
-    LayoutStateMaintainer statePusher(viewRenderer);
+    LayoutStateMaintainer statePusher(view());
 
     m_rowPos.resize(m_grid.size() + 1);
 
@@ -640,7 +639,7 @@
         LayoutUnit baselineDescent = 0;
 
         // Our base size is the biggest logical height from our cells' styles (excluding row spanning cells).
-        m_rowPos[r + 1] = max(m_rowPos[r] + minimumValueForLength(m_grid[r].logicalHeight, 0, viewRenderer).round(), 0);
+        m_rowPos[r + 1] = max(m_rowPos[r] + minimumValueForLength(m_grid[r].logicalHeight, 0).round(), 0);
 
         Row& row = m_grid[r].row;
         unsigned totalCols = row.size();
@@ -653,33 +652,25 @@
                 if (current.inColSpan && cell->rowSpan() == 1)
                     continue;
 
-                if (RuntimeEnabledFeatures::rowSpanLogicalHeightSpreadingEnabled()) {
-                    if (cell->rowSpan() > 1) {
-                        // For row spanning cells, we only handle them for the first row they span. This ensures we take their baseline into account.
-                        if (lastRowSpanCell != cell && cell->rowIndex() == r) {
+                if (cell->rowSpan() > 1) {
+                    // For row spanning cells, we only handle them for the first row they span. This ensures we take their baseline into account.
+                    if (lastRowSpanCell != cell && cell->rowIndex() == r) {
 #ifndef NDEBUG
-                            ASSERT(!uniqueCells.contains(cell));
-                            uniqueCells.add(cell);
+                        ASSERT(!uniqueCells.contains(cell));
+                        uniqueCells.add(cell);
 #endif
 
-                            rowSpanCells.append(cell);
-                            lastRowSpanCell = cell;
+                        rowSpanCells.append(cell);
+                        lastRowSpanCell = cell;
 
-                            // Find out the baseline. The baseline is set on the first row in a rowSpan.
-                            updateBaselineForCell(cell, r, baselineDescent);
-                        }
-                        continue;
+                        // Find out the baseline. The baseline is set on the first row in a rowSpan.
+                        updateBaselineForCell(cell, r, baselineDescent);
                     }
-
-                    ASSERT(cell->rowSpan() == 1);
-                } else {
-                    // FIXME: We add all the logical row of a rowspan to the last rows
-                    // until crbug.com/78724 is fixed and the runtime flag removed.
-                    // This avoids propagating temporary regressions while we fix the bug.
-                    if ((cell->rowIndex() + cell->rowSpan() - 1) != r)
-                        continue;
+                    continue;
                 }
 
+                ASSERT(cell->rowSpan() == 1);
+
                 if (cell->hasOverrideHeight()) {
                     if (!statePusher.didPush()) {
                         // Technically, we should also push state for the row, but since
@@ -691,20 +682,10 @@
                     cell->forceChildLayout();
                 }
 
-                if (RuntimeEnabledFeatures::rowSpanLogicalHeightSpreadingEnabled()) {
-                    m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[r] + cell->logicalHeightForRowSizing());
+                m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[r] + cell->logicalHeightForRowSizing());
 
-                    // Find out the baseline.
-                    updateBaselineForCell(cell, r, baselineDescent);
-                } else {
-                    // For row spanning cells, |r| is the last row in the span.
-                    unsigned cellStartRow = cell->rowIndex();
-
-                    m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[cellStartRow] + cell->logicalHeightForRowSizing());
-
-                    // Find out the baseline.
-                    updateBaselineForCell(cell, cellStartRow, baselineDescent);
-                }
+                // Find out the baseline.
+                updateBaselineForCell(cell, r, baselineDescent);
             }
         }
 
@@ -713,10 +694,8 @@
         m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[r]);
     }
 
-    if (!rowSpanCells.isEmpty()) {
-        ASSERT(RuntimeEnabledFeatures::rowSpanLogicalHeightSpreadingEnabled());
+    if (!rowSpanCells.isEmpty())
         distributeRowSpanHeightToRows(rowSpanCells);
-    }
 
     ASSERT(!needsLayout());
 
@@ -753,6 +732,8 @@
             if (!cell || current.inColSpan)
                 continue;
 
+            LayoutRectRecorder cellRecorder(*cell);
+
             unsigned endCol = startColumn;
             unsigned cspan = cell->colSpan();
             while (cspan && endCol < cols) {
@@ -910,6 +891,8 @@
             if (!cell || cs.inColSpan)
                 continue;
 
+            LayoutRectRecorder cellRecorder(*cell);
+
             int rowIndex = cell->rowIndex();
             int rHeight = m_rowPos[rowIndex + cell->rowSpan()] - m_rowPos[rowIndex] - vspacing;
 
@@ -990,7 +973,8 @@
 
             LayoutSize childOffset(cell->location() - oldCellRect.location());
             if (childOffset.width() || childOffset.height()) {
-                view()->addLayoutDelta(childOffset);
+                if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+                    view()->addLayoutDelta(childOffset);
 
                 // If the child moved, we have to repaint it as well as any floating/positioned
                 // descendants.  An exception is if we need a layout.  In this case, we know we're going to
@@ -1062,7 +1046,7 @@
     ASSERT(hasOverflowingCell == this->hasOverflowingCell());
 }
 
-int RenderTableSection::calcOuterBorderBefore() const
+int RenderTableSection::calcBlockDirectionOuterBorder(BlockBorderSide side) const
 {
     unsigned totalCols = table()->numEffCols();
     if (!m_grid.size() || !totalCols)
@@ -1070,13 +1054,13 @@
 
     unsigned borderWidth = 0;
 
-    const BorderValue& sb = style()->borderBefore();
+    const BorderValue& sb = side == BorderBefore ? style()->borderBefore() : style()->borderAfter();
     if (sb.style() == BHIDDEN)
         return -1;
     if (sb.style() > BHIDDEN)
         borderWidth = sb.width();
 
-    const BorderValue& rb = firstChild()->style()->borderBefore();
+    const BorderValue& rb = side == BorderBefore ? firstChild()->style()->borderBefore() : lastChild()->style()->borderAfter();
     if (rb.style() == BHIDDEN)
         return -1;
     if (rb.style() > BHIDDEN && rb.width() > borderWidth)
@@ -1084,14 +1068,15 @@
 
     bool allHidden = true;
     for (unsigned c = 0; c < totalCols; c++) {
-        const CellStruct& current = cellAt(0, c);
+        const CellStruct& current = cellAt(side == BorderBefore ? 0 : m_grid.size() - 1, c);
         if (current.inColSpan || !current.hasCells())
             continue;
-        const BorderValue& cb = current.primaryCell()->style()->borderBefore(); // FIXME: Make this work with perpendicular and flipped cells.
+        const RenderStyle* primaryCellStyle = current.primaryCell()->style();
+        const BorderValue& cb = side == BorderBefore ? primaryCellStyle->borderBefore() : primaryCellStyle->borderAfter(); // FIXME: Make this work with perpendicular and flipped cells.
         // FIXME: Don't repeat for the same col group
         RenderTableCol* colGroup = table()->colElement(c);
         if (colGroup) {
-            const BorderValue& gb = colGroup->style()->borderBefore();
+            const BorderValue& gb = side == BorderBefore ? colGroup->style()->borderBefore() : colGroup->style()->borderAfter();
             if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
                 continue;
             allHidden = false;
@@ -1110,76 +1095,28 @@
     if (allHidden)
         return -1;
 
+    if (side == BorderAfter)
+        borderWidth++; // Distribute rounding error
     return borderWidth / 2;
 }
 
-int RenderTableSection::calcOuterBorderAfter() const
+int RenderTableSection::calcInlineDirectionOuterBorder(InlineBorderSide side) const
 {
     unsigned totalCols = table()->numEffCols();
     if (!m_grid.size() || !totalCols)
         return 0;
+    unsigned colIndex = side == BorderStart ? 0 : totalCols - 1;
 
     unsigned borderWidth = 0;
 
-    const BorderValue& sb = style()->borderAfter();
+    const BorderValue& sb = side == BorderStart ? style()->borderStart() : style()->borderEnd();
     if (sb.style() == BHIDDEN)
         return -1;
     if (sb.style() > BHIDDEN)
         borderWidth = sb.width();
 
-    const BorderValue& rb = lastChild()->style()->borderAfter();
-    if (rb.style() == BHIDDEN)
-        return -1;
-    if (rb.style() > BHIDDEN && rb.width() > borderWidth)
-        borderWidth = rb.width();
-
-    bool allHidden = true;
-    for (unsigned c = 0; c < totalCols; c++) {
-        const CellStruct& current = cellAt(m_grid.size() - 1, c);
-        if (current.inColSpan || !current.hasCells())
-            continue;
-        const BorderValue& cb = current.primaryCell()->style()->borderAfter(); // FIXME: Make this work with perpendicular and flipped cells.
-        // FIXME: Don't repeat for the same col group
-        RenderTableCol* colGroup = table()->colElement(c);
-        if (colGroup) {
-            const BorderValue& gb = colGroup->style()->borderAfter();
-            if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
-                continue;
-            allHidden = false;
-            if (gb.style() > BHIDDEN && gb.width() > borderWidth)
-                borderWidth = gb.width();
-            if (cb.style() > BHIDDEN && cb.width() > borderWidth)
-                borderWidth = cb.width();
-        } else {
-            if (cb.style() == BHIDDEN)
-                continue;
-            allHidden = false;
-            if (cb.style() > BHIDDEN && cb.width() > borderWidth)
-                borderWidth = cb.width();
-        }
-    }
-    if (allHidden)
-        return -1;
-
-    return (borderWidth + 1) / 2;
-}
-
-int RenderTableSection::calcOuterBorderStart() const
-{
-    unsigned totalCols = table()->numEffCols();
-    if (!m_grid.size() || !totalCols)
-        return 0;
-
-    unsigned borderWidth = 0;
-
-    const BorderValue& sb = style()->borderStart();
-    if (sb.style() == BHIDDEN)
-        return -1;
-    if (sb.style() > BHIDDEN)
-        borderWidth = sb.width();
-
-    if (RenderTableCol* colGroup = table()->colElement(0)) {
-        const BorderValue& gb = colGroup->style()->borderStart();
+    if (RenderTableCol* colGroup = table()->colElement(colIndex)) {
+        const BorderValue& gb = side == BorderStart ? colGroup->style()->borderStart() : colGroup->style()->borderEnd();
         if (gb.style() == BHIDDEN)
             return -1;
         if (gb.style() > BHIDDEN && gb.width() > borderWidth)
@@ -1188,12 +1125,14 @@
 
     bool allHidden = true;
     for (unsigned r = 0; r < m_grid.size(); r++) {
-        const CellStruct& current = cellAt(r, 0);
+        const CellStruct& current = cellAt(r, colIndex);
         if (!current.hasCells())
             continue;
         // FIXME: Don't repeat for the same cell
-        const BorderValue& cb = current.primaryCell()->style()->borderStart(); // FIXME: Make this work with perpendicular and flipped cells.
-        const BorderValue& rb = current.primaryCell()->parent()->style()->borderStart();
+        const RenderStyle* primaryCellStyle = current.primaryCell()->style();
+        const RenderStyle* primaryCellParentStyle = current.primaryCell()->parent()->style();
+        const BorderValue& cb = side == BorderStart ? primaryCellStyle->borderStart() : primaryCellStyle->borderEnd(); // FIXME: Make this work with perpendicular and flipped cells.
+        const BorderValue& rb = side == BorderStart ? primaryCellParentStyle->borderStart() : primaryCellParentStyle->borderEnd();
         if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
             continue;
         allHidden = false;
@@ -1205,59 +1144,17 @@
     if (allHidden)
         return -1;
 
-    return (borderWidth + (table()->style()->isLeftToRightDirection() ? 0 : 1)) / 2;
-}
-
-int RenderTableSection::calcOuterBorderEnd() const
-{
-    unsigned totalCols = table()->numEffCols();
-    if (!m_grid.size() || !totalCols)
-        return 0;
-
-    unsigned borderWidth = 0;
-
-    const BorderValue& sb = style()->borderEnd();
-    if (sb.style() == BHIDDEN)
-        return -1;
-    if (sb.style() > BHIDDEN)
-        borderWidth = sb.width();
-
-    if (RenderTableCol* colGroup = table()->colElement(totalCols - 1)) {
-        const BorderValue& gb = colGroup->style()->borderEnd();
-        if (gb.style() == BHIDDEN)
-            return -1;
-        if (gb.style() > BHIDDEN && gb.width() > borderWidth)
-            borderWidth = gb.width();
-    }
-
-    bool allHidden = true;
-    for (unsigned r = 0; r < m_grid.size(); r++) {
-        const CellStruct& current = cellAt(r, totalCols - 1);
-        if (!current.hasCells())
-            continue;
-        // FIXME: Don't repeat for the same cell
-        const BorderValue& cb = current.primaryCell()->style()->borderEnd(); // FIXME: Make this work with perpendicular and flipped cells.
-        const BorderValue& rb = current.primaryCell()->parent()->style()->borderEnd();
-        if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
-            continue;
-        allHidden = false;
-        if (cb.style() > BHIDDEN && cb.width() > borderWidth)
-            borderWidth = cb.width();
-        if (rb.style() > BHIDDEN && rb.width() > borderWidth)
-            borderWidth = rb.width();
-    }
-    if (allHidden)
-        return -1;
-
-    return (borderWidth + (table()->style()->isLeftToRightDirection() ? 1 : 0)) / 2;
+    if ((side == BorderStart) != table()->style()->isLeftToRightDirection())
+        borderWidth++; // Distribute rounding error
+    return borderWidth / 2;
 }
 
 void RenderTableSection::recalcOuterBorder()
 {
-    m_outerBorderBefore = calcOuterBorderBefore();
-    m_outerBorderAfter = calcOuterBorderAfter();
-    m_outerBorderStart = calcOuterBorderStart();
-    m_outerBorderEnd = calcOuterBorderEnd();
+    m_outerBorderBefore = calcBlockDirectionOuterBorder(BorderBefore);
+    m_outerBorderAfter = calcBlockDirectionOuterBorder(BorderAfter);
+    m_outerBorderStart = calcInlineDirectionOuterBorder(BorderStart);
+    m_outerBorderEnd = calcInlineDirectionOuterBorder(BorderEnd);
 }
 
 int RenderTableSection::firstLineBoxBaseline() const
@@ -1711,7 +1608,7 @@
     // Just forward to our children always.
     LayoutPoint adjustedLocation = accumulatedOffset + location();
 
-    if (hasOverflowClip() && !locationInContainer.intersects(overflowClipRect(adjustedLocation, locationInContainer.region())))
+    if (hasOverflowClip() && !locationInContainer.intersects(overflowClipRect(adjustedLocation)))
         return false;
 
     if (hasOverflowingCell()) {
@@ -1814,7 +1711,9 @@
         cellLocation.setX(table()->columnPositions()[effectiveColumn] + horizontalBorderSpacing);
 
     cell->setLogicalLocation(cellLocation);
-    view()->addLayoutDelta(oldCellLocation - cell->location());
+
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+        view()->addLayoutDelta(oldCellLocation - cell->location());
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderTableSection.h b/Source/core/rendering/RenderTableSection.h
index 42b51ec..37f49e2 100644
--- a/Source/core/rendering/RenderTableSection.h
+++ b/Source/core/rendering/RenderTableSection.h
@@ -71,7 +71,7 @@
     const RenderObjectChildList* children() const { return &m_children; }
     RenderObjectChildList* children() { return &m_children; }
 
-    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0);
+    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
 
     virtual int firstLineBoxBaseline() const OVERRIDE;
 
@@ -174,10 +174,10 @@
     void appendColumn(unsigned pos);
     void splitColumn(unsigned pos, unsigned first);
 
-    int calcOuterBorderBefore() const;
-    int calcOuterBorderAfter() const;
-    int calcOuterBorderStart() const;
-    int calcOuterBorderEnd() const;
+    enum BlockBorderSide { BorderBefore, BorderAfter };
+    int calcBlockDirectionOuterBorder(BlockBorderSide) const;
+    enum InlineBorderSide { BorderStart, BorderEnd };
+    int calcInlineDirectionOuterBorder(InlineBorderSide) const;
     void recalcOuterBorder();
 
     int outerBorderBefore() const { return m_outerBorderBefore; }
@@ -218,24 +218,24 @@
     virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
 protected:
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
 private:
-    virtual RenderObjectChildList* virtualChildren() { return children(); }
-    virtual const RenderObjectChildList* virtualChildren() const { return children(); }
+    virtual RenderObjectChildList* virtualChildren() OVERRIDE { return children(); }
+    virtual const RenderObjectChildList* virtualChildren() const OVERRIDE { return children(); }
 
-    virtual const char* renderName() const { return (isAnonymous() || isPseudoElement()) ? "RenderTableSection (anonymous)" : "RenderTableSection"; }
+    virtual const char* renderName() const OVERRIDE { return (isAnonymous() || isPseudoElement()) ? "RenderTableSection (anonymous)" : "RenderTableSection"; }
 
-    virtual bool isTableSection() const { return true; }
+    virtual bool isTableSection() const OVERRIDE { return true; }
 
     virtual void willBeRemovedFromTree() OVERRIDE;
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
-    virtual void paintCell(RenderTableCell*, PaintInfo&, const LayoutPoint&);
-    virtual void paintObject(PaintInfo&, const LayoutPoint&);
+    void paintCell(RenderTableCell*, PaintInfo&, const LayoutPoint&);
+    virtual void paintObject(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
-    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0);
+    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 
diff --git a/Source/core/rendering/RenderText.cpp b/Source/core/rendering/RenderText.cpp
index 8fcee94..88ac68e 100644
--- a/Source/core/rendering/RenderText.cpp
+++ b/Source/core/rendering/RenderText.cpp
@@ -28,9 +28,9 @@
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/Text.h"
 #include "core/editing/TextIterator.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/rendering/AbstractInlineTextBox.h"
 #include "core/rendering/EllipsisBox.h"
 #include "core/rendering/InlineTextBox.h"
@@ -39,8 +39,11 @@
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/break_lines.h"
+#include "platform/fonts/Character.h"
 #include "platform/geometry/FloatQuad.h"
+#include "platform/text/BidiResolver.h"
 #include "platform/text/TextBreakIterator.h"
+#include "platform/text/TextRunIterator.h"
 #include "wtf/text/StringBuffer.h"
 #include "wtf/text/StringBuilder.h"
 #include "wtf/unicode/CharacterNames.h"
@@ -64,7 +67,7 @@
 typedef HashMap<RenderText*, SecureTextTimer*> SecureTextTimerMap;
 static SecureTextTimerMap* gSecureTextTimers = 0;
 
-class SecureTextTimer : public TimerBase {
+class SecureTextTimer FINAL : public TimerBase {
 public:
     SecureTextTimer(RenderText* renderText)
         : m_renderText(renderText)
@@ -82,7 +85,7 @@
     unsigned lastTypedCharacterOffset() { return m_lastTypedCharacterOffset; }
 
 private:
-    virtual void fired()
+    virtual void fired() OVERRIDE
     {
         ASSERT(gSecureTextTimers->contains(m_renderText));
         m_renderText->setText(m_renderText->text().impl(), true /* forcing setting text as it may be masked later */);
@@ -720,7 +723,7 @@
     return style()->isHorizontalWritingMode() ? IntRect(left, top, caretWidth, height) : IntRect(top, left, height, caretWidth);
 }
 
-ALWAYS_INLINE float RenderText::widthFromCache(const Font& f, int start, int len, float xPos, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
+ALWAYS_INLINE float RenderText::widthFromCache(const Font& f, int start, int len, float xPos, TextDirection textDirection, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
 {
     if (style()->hasTextCombine() && isCombineText()) {
         const RenderCombineText* combineText = toRenderCombineText(this);
@@ -728,7 +731,7 @@
             return combineText->combinedTextWidth(f);
     }
 
-    if (f.isFixedPitch() && !f.isSmallCaps() && m_isAllASCII && (!glyphOverflow || !glyphOverflow->computeBounds)) {
+    if (f.isFixedPitch() && !f.fontDescription().smallCaps() && m_isAllASCII && (!glyphOverflow || !glyphOverflow->computeBounds)) {
         float monospaceCharacterWidth = f.spaceWidth();
         float w = 0;
         bool isSpace;
@@ -755,12 +758,12 @@
                 isSpace = false;
             }
             if (isSpace && i > start)
-                w += f.wordSpacing();
+                w += f.fontDescription().wordSpacing();
         }
         return w;
     }
 
-    TextRun run = RenderBlockFlow::constructTextRun(const_cast<RenderText*>(this), f, this, start, len, style());
+    TextRun run = RenderBlockFlow::constructTextRun(const_cast<RenderText*>(this), f, this, start, len, style(), textDirection);
     run.setCharactersLength(textLength() - start);
     ASSERT(run.charactersLength() >= run.length());
 
@@ -775,7 +778,8 @@
     float& lastLineMinWidth, bool& hasBreakableEnd,
     bool& hasBreakableChar, bool& hasBreak,
     float& firstLineMaxWidth, float& lastLineMaxWidth,
-    float& minWidth, float& maxWidth, bool& stripFrontSpaces)
+    float& minWidth, float& maxWidth, bool& stripFrontSpaces,
+    TextDirection direction)
 {
     bool collapseWhiteSpace = style()->collapseWhiteSpace();
     if (!collapseWhiteSpace)
@@ -815,10 +819,10 @@
         const Font& font = style()->font(); // FIXME: This ignores first-line.
         if (stripFrontSpaces) {
             const UChar space = ' ';
-            float spaceWidth = font.width(RenderBlockFlow::constructTextRun(this, font, &space, 1, style()));
+            float spaceWidth = font.width(RenderBlockFlow::constructTextRun(this, font, &space, 1, style(), direction));
             maxWidth -= spaceWidth;
         } else {
-            maxWidth += font.wordSpacing();
+            maxWidth += font.fontDescription().wordSpacing();
         }
     }
 
@@ -839,7 +843,7 @@
                 linelen++;
 
             if (linelen) {
-                lastLineMaxWidth = widthFromCache(f, i, linelen, leadWidth + lastLineMaxWidth, 0, 0);
+                lastLineMaxWidth = widthFromCache(f, i, linelen, leadWidth + lastLineMaxWidth, direction, 0, 0);
                 if (firstLine) {
                     firstLine = false;
                     leadWidth = 0;
@@ -886,10 +890,10 @@
         m_knownToHaveNoOverflowAndNoFallbackFonts = true;
 }
 
-static inline float hyphenWidth(RenderText* renderer, const Font& font)
+static inline float hyphenWidth(RenderText* renderer, const Font& font, TextDirection direction)
 {
     RenderStyle* style = renderer->style();
-    return font.width(RenderBlockFlow::constructTextRun(renderer, font, style->hyphenString().string(), style));
+    return font.width(RenderBlockFlow::constructTextRun(renderer, font, style->hyphenString().string(), style, direction));
 }
 
 void RenderText::computePreferredLogicalWidths(float leadWidth, HashSet<const SimpleFontData*>& fallbackFonts, GlyphOverflow& glyphOverflow)
@@ -928,7 +932,7 @@
 
     // Non-zero only when kerning is enabled, in which case we measure words with their trailing
     // space, then subtract its width.
-    float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(RenderBlockFlow::constructTextRun(this, f, &space, 1, styleToUse)) + wordSpacing : 0;
+    float wordTrailingSpaceWidth = f.fontDescription().typesettingFeatures() & Kerning ? f.width(RenderBlockFlow::constructTextRun(this, f, &space, 1, styleToUse, LTR)) + wordSpacing : 0;
 
     // If automatic hyphenation is allowed, we keep track of the width of the widest word (or word
     // fragment) encountered so far, and only try hyphenating words that are wider.
@@ -937,11 +941,27 @@
 
     bool breakAll = (styleToUse->wordBreak() == BreakAllWordBreak || styleToUse->wordBreak() == BreakWordBreak) && styleToUse->autoWrap();
 
+    TextRun textRun(text());
+    BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver;
+    bidiResolver.setStatus(BidiStatus(textRun.direction(), textRun.directionalOverride()));
+    bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&textRun, 0));
+    bool hardLineBreak = false;
+    bool reorderRuns = false;
+    bidiResolver.createBidiRunsForLine(TextRunIterator(&textRun, textRun.length()), NoVisualOverride, hardLineBreak, reorderRuns);
+
+    BidiRunList<BidiCharacterRun>& bidiRuns = bidiResolver.runs();
+    BidiCharacterRun* run = bidiRuns.firstRun();
     for (int i = 0; i < len; i++) {
         UChar c = uncheckedCharacterAt(i);
 
-        bool previousCharacterIsSpace = isSpace;
+        while (i > run->stop())
+            run = run->next();
 
+        ASSERT(run);
+        ASSERT(i >= run->start() && i <= run->stop());
+        TextDirection textDirection = run->direction();
+
+        bool previousCharacterIsSpace = isSpace;
         bool isNewline = false;
         if (c == '\n') {
             if (styleToUse->preserveNewline()) {
@@ -979,7 +999,7 @@
             lastWordBoundary++;
             continue;
         } else if (c == softHyphen) {
-            currMaxWidth += widthFromCache(f, lastWordBoundary, i - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow);
+            currMaxWidth += widthFromCache(f, lastWordBoundary, i - lastWordBoundary, leadWidth + currMaxWidth, textDirection, &fallbackFonts, &glyphOverflow);
             if (firstGlyphLeftOverflow < 0)
                 firstGlyphLeftOverflow = glyphOverflow.left;
             lastWordBoundary = i + 1;
@@ -1002,16 +1022,18 @@
             }
         }
 
+        // Terminate word boundary at bidi run boundary.
+        j = min(j, run->stop() + 1);
         int wordLen = j - i;
         if (wordLen) {
             bool isSpace = (j < len) && c == ' ';
             float w;
             if (wordTrailingSpaceWidth && isSpace)
-                w = widthFromCache(f, i, wordLen + 1, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow) - wordTrailingSpaceWidth;
+                w = widthFromCache(f, i, wordLen + 1, leadWidth + currMaxWidth, textDirection, &fallbackFonts, &glyphOverflow) - wordTrailingSpaceWidth;
             else {
-                w = widthFromCache(f, i, wordLen, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow);
+                w = widthFromCache(f, i, wordLen, leadWidth + currMaxWidth, textDirection, &fallbackFonts, &glyphOverflow);
                 if (c == softHyphen)
-                    currMinWidth += hyphenWidth(this, f);
+                    currMinWidth += hyphenWidth(this, f, textDirection);
             }
 
             maxWordWidth = max(maxWordWidth, w);
@@ -1023,7 +1045,7 @@
                 if (lastWordBoundary == i)
                     currMaxWidth += w;
                 else
-                    currMaxWidth += widthFromCache(f, lastWordBoundary, j - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow);
+                    currMaxWidth += widthFromCache(f, lastWordBoundary, j - lastWordBoundary, leadWidth + currMaxWidth, textDirection, &fallbackFonts, &glyphOverflow);
                 lastWordBoundary = j;
             }
 
@@ -1074,7 +1096,7 @@
                     m_maxWidth = currMaxWidth;
                 currMaxWidth = 0;
             } else {
-                TextRun run = RenderBlockFlow::constructTextRun(this, f, this, i, 1, styleToUse);
+                TextRun run = RenderBlockFlow::constructTextRun(this, f, this, i, 1, styleToUse, textDirection);
                 run.setCharactersLength(len - i);
                 ASSERT(run.charactersLength() >= run.length());
                 run.setTabSize(!style()->collapseWhiteSpace(), style()->tabSize());
@@ -1088,6 +1110,7 @@
             lastWordBoundary++;
         }
     }
+    bidiRuns.deleteRuns();
 
     if (firstGlyphLeftOverflow > 0)
         glyphOverflow.left = firstGlyphLeftOverflow;
@@ -1385,7 +1408,11 @@
         return;
 
     setTextInternal(text);
-    setNeedsLayoutAndPrefWidthsRecalc();
+    // If preferredLogicalWidthsDirty() of an orphan child is true, RenderObjectChildList::
+    // insertChildNode() fails to set true to owner. To avoid that, we call
+    // setNeedsLayoutAndPrefWidthsRecalc() only if this RenderText has parent.
+    if (parent())
+        setNeedsLayoutAndPrefWidthsRecalc();
     m_knownToHaveNoOverflowAndNoFallbackFonts = false;
 
     if (AXObjectCache* cache = document().existingAXObjectCache())
@@ -1445,7 +1472,7 @@
     m_containsReversedText |= !s->isLeftToRightDirection();
 }
 
-float RenderText::width(unsigned from, unsigned len, float xPos, bool firstLine, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
+float RenderText::width(unsigned from, unsigned len, float xPos, TextDirection textDirection, bool firstLine, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
 {
     if (from >= textLength())
         return 0;
@@ -1453,10 +1480,10 @@
     if (from + len > textLength())
         len = textLength() - from;
 
-    return width(from, len, style(firstLine)->font(), xPos, fallbackFonts, glyphOverflow);
+    return width(from, len, style(firstLine)->font(), xPos, textDirection, fallbackFonts, glyphOverflow);
 }
 
-float RenderText::width(unsigned from, unsigned len, const Font& f, float xPos, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
+float RenderText::width(unsigned from, unsigned len, const Font& f, float xPos, TextDirection textDirection, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
 {
     ASSERT(from + len <= textLength());
     if (!textLength())
@@ -1475,10 +1502,11 @@
                 w = m_maxWidth;
             } else
                 w = maxLogicalWidth();
-        } else
-            w = widthFromCache(f, from, len, xPos, fallbackFonts, glyphOverflow);
+        } else {
+            w = widthFromCache(f, from, len, xPos, textDirection, fallbackFonts, glyphOverflow);
+        }
     } else {
-        TextRun run = RenderBlockFlow::constructTextRun(const_cast<RenderText*>(this), f, this, from, len, style());
+        TextRun run = RenderBlockFlow::constructTextRun(const_cast<RenderText*>(this), f, this, from, len, style(), textDirection);
         run.setCharactersLength(textLength() - from);
         ASSERT(run.charactersLength() >= run.length());
 
@@ -1809,7 +1837,7 @@
 {
     if (isAllASCII() || m_text.is8Bit())
         return true;
-    return Font::characterRangeCodePath(characters16(), length()) == Font::Simple;
+    return Character::characterRangeCodePath(characters16(), length()) == SimplePath;
 }
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/RenderText.h b/Source/core/rendering/RenderText.h
index 13af4be..9f0bca6 100644
--- a/Source/core/rendering/RenderText.h
+++ b/Source/core/rendering/RenderText.h
@@ -24,6 +24,8 @@
 #define RenderText_h
 
 #include "core/rendering/RenderObject.h"
+#include "platform/LengthFunctions.h"
+#include "platform/text/TextPath.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 
@@ -42,7 +44,7 @@
     virtual ~RenderText();
 #endif
 
-    virtual const char* renderName() const;
+    virtual const char* renderName() const OVERRIDE;
 
     virtual bool isTextFragment() const;
     virtual bool isWordBreak() const;
@@ -82,8 +84,8 @@
     unsigned textLength() const { return m_text.length(); } // non virtual implementation of length()
     void positionLineBox(InlineBox*);
 
-    virtual float width(unsigned from, unsigned len, const Font&, float xPos, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
-    virtual float width(unsigned from, unsigned len, float xPos, bool firstLine = false, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
+    virtual float width(unsigned from, unsigned len, const Font&, float xPos, TextDirection, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
+    virtual float width(unsigned from, unsigned len, float xPos, TextDirection, bool firstLine = false, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
 
     float minLogicalWidth() const;
     float maxLogicalWidth() const;
@@ -93,7 +95,8 @@
         float& lastLineMinWidth, bool& hasBreakableEnd,
         bool& hasBreakableChar, bool& hasBreak,
         float& firstLineMaxWidth, float& lastLineMaxWidth,
-        float& minWidth, float& maxWidth, bool& stripFrontSpaces);
+        float& minWidth, float& maxWidth, bool& stripFrontSpaces,
+        TextDirection);
 
     virtual IntRect linesBoundingBox() const;
     LayoutRect linesVisualOverflowBoundingBox() const;
@@ -107,21 +110,21 @@
 
     virtual void transformText();
 
-    virtual bool canBeSelectionLeaf() const { return true; }
+    virtual bool canBeSelectionLeaf() const OVERRIDE { return true; }
     virtual void setSelectionState(SelectionState s) OVERRIDE FINAL;
     virtual LayoutRect selectionRectForRepaint(const RenderLayerModelObject* repaintContainer, bool clipToVisibleContent = true) OVERRIDE;
-    virtual LayoutRect localCaretRect(InlineBox*, int caretOffset, LayoutUnit* extraWidthToEndOfLine = 0);
+    virtual LayoutRect localCaretRect(InlineBox*, int caretOffset, LayoutUnit* extraWidthToEndOfLine = 0) OVERRIDE;
 
-    LayoutUnit marginLeft() const { return minimumValueForLength(style()->marginLeft(), 0, view()); }
-    LayoutUnit marginRight() const { return minimumValueForLength(style()->marginRight(), 0, view()); }
+    LayoutUnit marginLeft() const { return minimumValueForLength(style()->marginLeft(), 0); }
+    LayoutUnit marginRight() const { return minimumValueForLength(style()->marginRight(), 0); }
 
     virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const OVERRIDE FINAL;
 
     InlineTextBox* firstTextBox() const { return m_firstTextBox; }
     InlineTextBox* lastTextBox() const { return m_lastTextBox; }
 
-    virtual int caretMinOffset() const;
-    virtual int caretMaxOffset() const;
+    virtual int caretMinOffset() const OVERRIDE;
+    virtual int caretMaxOffset() const OVERRIDE;
     unsigned renderedTextLength() const;
 
     virtual int previousOffset(int current) const OVERRIDE FINAL;
@@ -148,10 +151,10 @@
 
 protected:
     virtual void computePreferredLogicalWidths(float leadWidth);
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
     virtual void styleWillChange(StyleDifference, const RenderStyle*) OVERRIDE FINAL { }
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     virtual void setTextInternal(PassRefPtr<StringImpl>);
     virtual UChar previousCharacter() const;
@@ -176,7 +179,7 @@
 
     void deleteTextBoxes();
     bool containsOnlyWhitespace(unsigned from, unsigned len) const;
-    float widthFromCache(const Font&, int start, int len, float xPos, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow*) const;
+    float widthFromCache(const Font&, int start, int len, float xPos, TextDirection, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow*) const;
     bool isAllASCII() const { return m_isAllASCII; }
 
     void secureText(UChar mask);
diff --git a/Source/core/rendering/RenderTextControl.cpp b/Source/core/rendering/RenderTextControl.cpp
index d420fbf..690a1c4 100644
--- a/Source/core/rendering/RenderTextControl.cpp
+++ b/Source/core/rendering/RenderTextControl.cpp
@@ -57,15 +57,15 @@
     // FIXME: This is a terrible hack to get the caret over the placeholder text since it'll
     // make us paint the placeholder first. (See https://trac.webkit.org/changeset/118733)
     Node* node = newChild->node();
-    if (node && node->isElementNode() && toElement(node)->pseudo() == "-webkit-input-placeholder")
-        RenderBlock::addChild(newChild, firstChild());
+    if (node && node->isElementNode() && toElement(node)->shadowPseudoId() == "-webkit-input-placeholder")
+        RenderBlockFlow::addChild(newChild, firstChild());
     else
-        RenderBlock::addChild(newChild, beforeChild);
+        RenderBlockFlow::addChild(newChild, beforeChild);
 }
 
 void RenderTextControl::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
 {
-    RenderBlock::styleDidChange(diff, oldStyle);
+    RenderBlockFlow::styleDidChange(diff, oldStyle);
     Element* innerText = innerTextElement();
     if (!innerText)
         return;
@@ -76,7 +76,7 @@
         innerTextRenderer->style()->setHeight(Length());
         innerTextRenderer->style()->setWidth(Length());
         innerTextRenderer->setStyle(createInnerTextStyle(style()));
-        innerText->setNeedsStyleRecalc();
+        innerText->setNeedsStyleRecalc(SubtreeStyleChange);
     }
     textFormControlElement()->updatePlaceholderVisibility(false);
 }
@@ -234,13 +234,13 @@
 {
     // This matches the unitsPerEm value for MS Shell Dlg and Courier New from the "head" font table.
     float unitsPerEm = 2048.0f;
-    return roundf(style()->font().size() * x / unitsPerEm);
+    return roundf(style()->font().fontDescription().computedSize() * x / unitsPerEm);
 }
 
 void RenderTextControl::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
 {
     // Use average character width. Matches IE.
-    AtomicString family = style()->font().family().family();
+    AtomicString family = style()->font().fontDescription().family().family();
     maxLogicalWidth = preferredContentLogicalWidth(const_cast<RenderTextControl*>(this)->getAvgCharWidth(family));
     if (RenderBox* innerTextRenderBox = innerTextElement()->renderBox())
         maxLogicalWidth += innerTextRenderBox->paddingStart() + innerTextRenderBox->paddingEnd();
diff --git a/Source/core/rendering/RenderTextControl.h b/Source/core/rendering/RenderTextControl.h
index 6269af8..db23e59 100644
--- a/Source/core/rendering/RenderTextControl.h
+++ b/Source/core/rendering/RenderTextControl.h
@@ -45,7 +45,7 @@
     int scrollbarThickness() const;
     void adjustInnerTextStyle(RenderStyle* textBlockStyle) const;
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
     void hitInnerTextElement(HitTestResult&, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset);
 
@@ -59,9 +59,9 @@
     virtual LayoutUnit preferredContentLogicalWidth(float charWidth) const = 0;
     virtual LayoutUnit computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const = 0;
 
-    virtual void updateFromElement();
+    virtual void updateFromElement() OVERRIDE;
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
-    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
+    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&) OVERRIDE;
 
     // We need to override this function because we don't want overflow:hidden on an <input>
     // to affect the baseline calculation. This is necessary because we are an inline-block
@@ -69,20 +69,20 @@
     virtual int inlineBlockBaseline(LineDirectionMode direction) const OVERRIDE { return lastLineBoxBaseline(direction); }
 
 private:
-    virtual const char* renderName() const { return "RenderTextControl"; }
-    virtual bool isTextControl() const { return true; }
-    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
-    virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
-    virtual void computePreferredLogicalWidths() OVERRIDE;
-    virtual void removeLeftoverAnonymousBlock(RenderBlock*) { }
-    virtual bool avoidsFloats() const { return true; }
-    virtual bool canHaveGeneratedChildren() const OVERRIDE { return false; }
+    virtual const char* renderName() const OVERRIDE { return "RenderTextControl"; }
+    virtual bool isTextControl() const OVERRIDE FINAL { return true; }
+    virtual bool supportsPartialLayout() const OVERRIDE FINAL { return false; }
+    virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE FINAL;
+    virtual void computePreferredLogicalWidths() OVERRIDE FINAL;
+    virtual void removeLeftoverAnonymousBlock(RenderBlock*) OVERRIDE FINAL { }
+    virtual bool avoidsFloats() const OVERRIDE FINAL { return true; }
+    virtual bool canHaveGeneratedChildren() const OVERRIDE FINAL { return false; }
 
     virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0) OVERRIDE FINAL;
 
-    virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer = 0) OVERRIDE;
+    virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer = 0) OVERRIDE FINAL;
 
-    virtual bool canBeProgramaticallyScrolled() const { return true; }
+    virtual bool canBeProgramaticallyScrolled() const OVERRIDE FINAL { return true; }
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTextControl, isTextControl());
@@ -104,7 +104,6 @@
     }
     virtual int firstLineBoxBaseline() const OVERRIDE { return RenderBlock::firstLineBoxBaseline(); }
     virtual int inlineBlockBaseline(LineDirectionMode direction) const OVERRIDE { return lastLineBoxBaseline(direction); }
-    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 };
 
 
diff --git a/Source/core/rendering/RenderTextControlMultiLine.cpp b/Source/core/rendering/RenderTextControlMultiLine.cpp
index 01fa15a..ffef0c7 100644
--- a/Source/core/rendering/RenderTextControlMultiLine.cpp
+++ b/Source/core/rendering/RenderTextControlMultiLine.cpp
@@ -35,8 +35,6 @@
 
 RenderTextControlMultiLine::~RenderTextControlMultiLine()
 {
-    if (node() && node()->inDocument())
-        toHTMLTextAreaElement(node())->rendererWillBeDestroyed();
 }
 
 bool RenderTextControlMultiLine::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
diff --git a/Source/core/rendering/RenderTextControlMultiLine.h b/Source/core/rendering/RenderTextControlMultiLine.h
index 3371c26..871e582 100644
--- a/Source/core/rendering/RenderTextControlMultiLine.h
+++ b/Source/core/rendering/RenderTextControlMultiLine.h
@@ -34,19 +34,19 @@
     virtual ~RenderTextControlMultiLine();
 
 private:
-    virtual bool isTextArea() const { return true; }
+    virtual bool isTextArea() const OVERRIDE { return true; }
 
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 
-    virtual float getAvgCharWidth(AtomicString family);
-    virtual LayoutUnit preferredContentLogicalWidth(float charWidth) const;
+    virtual float getAvgCharWidth(AtomicString family) OVERRIDE;
+    virtual LayoutUnit preferredContentLogicalWidth(float charWidth) const OVERRIDE;
     virtual LayoutUnit computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const OVERRIDE;
     // We override the two baseline functions because we want our baseline to be the bottom of our margin box.
     virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
     virtual int inlineBlockBaseline(LineDirectionMode) const OVERRIDE { return -1; }
 
-    virtual PassRefPtr<RenderStyle> createInnerTextStyle(const RenderStyle* startStyle) const;
-    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
+    virtual PassRefPtr<RenderStyle> createInnerTextStyle(const RenderStyle* startStyle) const OVERRIDE;
+    virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&) OVERRIDE;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTextControlMultiLine, isTextArea());
diff --git a/Source/core/rendering/RenderTextControlSingleLine.cpp b/Source/core/rendering/RenderTextControlSingleLine.cpp
index 04ecfea..4a0c073 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.cpp
+++ b/Source/core/rendering/RenderTextControlSingleLine.cpp
@@ -181,6 +181,8 @@
     HTMLElement* placeholderElement = inputElement()->placeholderElement();
     if (RenderBox* placeholderBox = placeholderElement ? placeholderElement->renderBox() : 0) {
         LayoutSize innerTextSize;
+        LayoutRectRecorder placeholderBoxRecorder(*placeholderBox);
+
         if (innerTextRenderer)
             innerTextSize = innerTextRenderer->size();
         placeholderBox->style()->setWidth(Length(innerTextSize.width() - placeholderBox->borderAndPaddingWidth(), Fixed));
@@ -199,7 +201,7 @@
 
         if (!placeholderBoxHadLayout && placeholderBox->checkForRepaintDuringLayout()) {
             // This assumes a shadow tree without floats. If floats are added, the
-            // logic should be shared with RenderBlock::layoutBlockChild.
+            // logic should be shared with RenderBlockFlow::layoutBlockChild.
             placeholderBox->repaint();
         }
         // The placeholder gets layout last, after the parent text control and its other children,
@@ -316,7 +318,7 @@
     LayoutUnit result = LayoutUnit::fromFloatCeil(charWidth * factor);
 
     float maxCharWidth = 0.f;
-    AtomicString family = style()->font().family().family();
+    AtomicString family = style()->font().fontDescription().family().family();
     // Since Lucida Grande is the default font, we want this to match the width
     // of MS Shell Dlg, the default font for textareas in Firefox, Safari Win and
     // IE for some encodings (in IE, the default font is encoding specific).
@@ -374,6 +376,9 @@
     textBlockStyle->setDisplay(BLOCK);
     textBlockStyle->setUnique();
 
+    if (inputElement()->shouldRevealPassword())
+        textBlockStyle->setTextSecurity(TSNONE);
+
     return textBlockStyle.release();
 }
 
@@ -395,28 +400,28 @@
 {
     if (innerTextElement())
         return innerTextElement()->scrollWidth();
-    return RenderBlock::scrollWidth();
+    return RenderBlockFlow::scrollWidth();
 }
 
 int RenderTextControlSingleLine::scrollHeight() const
 {
     if (innerTextElement())
         return innerTextElement()->scrollHeight();
-    return RenderBlock::scrollHeight();
+    return RenderBlockFlow::scrollHeight();
 }
 
 int RenderTextControlSingleLine::scrollLeft() const
 {
     if (innerTextElement())
         return innerTextElement()->scrollLeft();
-    return RenderBlock::scrollLeft();
+    return RenderBlockFlow::scrollLeft();
 }
 
 int RenderTextControlSingleLine::scrollTop() const
 {
     if (innerTextElement())
         return innerTextElement()->scrollTop();
-    return RenderBlock::scrollTop();
+    return RenderBlockFlow::scrollTop();
 }
 
 void RenderTextControlSingleLine::setScrollLeft(int newLeft)
diff --git a/Source/core/rendering/RenderTextControlSingleLine.h b/Source/core/rendering/RenderTextControlSingleLine.h
index 64a07cc..950c361 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.h
+++ b/Source/core/rendering/RenderTextControlSingleLine.h
@@ -35,7 +35,7 @@
     RenderTextControlSingleLine(HTMLInputElement*);
     virtual ~RenderTextControlSingleLine();
     // FIXME: Move createInnerTextStyle() to TextControlInnerTextElement.
-    virtual PassRefPtr<RenderStyle> createInnerTextStyle(const RenderStyle* startStyle) const;
+    virtual PassRefPtr<RenderStyle> createInnerTextStyle(const RenderStyle* startStyle) const OVERRIDE FINAL;
 
     void capsLockStateMayHaveChanged();
 
@@ -45,34 +45,34 @@
     Element* containerElement() const;
     Element* editingViewPortElement() const;
     HTMLInputElement* inputElement() const;
-    virtual void updateFromElement() OVERRIDE;
+    virtual void updateFromElement() OVERRIDE FINAL;
 
 private:
-    virtual bool hasControlClip() const;
-    virtual LayoutRect controlClipRect(const LayoutPoint&) const;
-    virtual bool isTextField() const { return true; }
+    virtual bool hasControlClip() const OVERRIDE FINAL;
+    virtual LayoutRect controlClipRect(const LayoutPoint&) const OVERRIDE FINAL;
+    virtual bool isTextField() const OVERRIDE FINAL { return true; }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
-    virtual void layout();
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual void layout() OVERRIDE;
 
-    virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
+    virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE FINAL;
 
-    virtual void autoscroll(const IntPoint&);
+    virtual void autoscroll(const IntPoint&) OVERRIDE FINAL;
 
     // Subclassed to forward to our inner div.
-    virtual int scrollLeft() const;
-    virtual int scrollTop() const;
-    virtual int scrollWidth() const;
-    virtual int scrollHeight() const;
-    virtual void setScrollLeft(int);
-    virtual void setScrollTop(int);
+    virtual int scrollLeft() const OVERRIDE FINAL;
+    virtual int scrollTop() const OVERRIDE FINAL;
+    virtual int scrollWidth() const OVERRIDE FINAL;
+    virtual int scrollHeight() const OVERRIDE FINAL;
+    virtual void setScrollLeft(int) OVERRIDE FINAL;
+    virtual void setScrollTop(int) OVERRIDE FINAL;
 
     int textBlockWidth() const;
-    virtual float getAvgCharWidth(AtomicString family);
-    virtual LayoutUnit preferredContentLogicalWidth(float charWidth) const;
+    virtual float getAvgCharWidth(AtomicString family) OVERRIDE FINAL;
+    virtual LayoutUnit preferredContentLogicalWidth(float charWidth) const OVERRIDE FINAL;
     virtual LayoutUnit computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const OVERRIDE;
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
 
     bool textShouldBeTruncated() const;
 
diff --git a/Source/core/rendering/RenderTextFragment.h b/Source/core/rendering/RenderTextFragment.h
index 44bbfe8..9d81d43 100644
--- a/Source/core/rendering/RenderTextFragment.h
+++ b/Source/core/rendering/RenderTextFragment.h
@@ -37,7 +37,7 @@
     RenderTextFragment(Node*, StringImpl*);
     virtual ~RenderTextFragment();
 
-    virtual bool isTextFragment() const { return true; }
+    virtual bool isTextFragment() const OVERRIDE { return true; }
 
     virtual bool canBeSelectionLeaf() const OVERRIDE { return node() && node()->rendererIsEditable(); }
 
@@ -50,19 +50,19 @@
     RenderText* firstRenderTextInFirstLetter() const;
 
     StringImpl* contentString() const { return m_contentString.get(); }
-    virtual PassRefPtr<StringImpl> originalText() const;
+    virtual PassRefPtr<StringImpl> originalText() const OVERRIDE;
 
     virtual void setText(PassRefPtr<StringImpl>, bool force = false) OVERRIDE;
 
     virtual void transformText() OVERRIDE;
 
 protected:
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
 private:
-    virtual void willBeDestroyed();
+    virtual void willBeDestroyed() OVERRIDE;
 
-    virtual UChar previousCharacter() const;
+    virtual UChar previousCharacter() const OVERRIDE;
     RenderBlock* blockForAccompanyingFirstLetter() const;
     virtual void updateHitTestResult(HitTestResult&, const LayoutPoint&) OVERRIDE;
 
diff --git a/Source/core/rendering/RenderTheme.cpp b/Source/core/rendering/RenderTheme.cpp
index 062a2ee..329aa85 100644
--- a/Source/core/rendering/RenderTheme.cpp
+++ b/Source/core/rendering/RenderTheme.cpp
@@ -43,7 +43,7 @@
 #include "core/page/FocusController.h"
 #include "core/frame/Frame.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderMeter.h"
 #include "core/rendering/RenderView.h"
@@ -69,12 +69,6 @@
 
 using namespace HTMLNames;
 
-static Color& customFocusRingColor()
-{
-    DEFINE_STATIC_LOCAL(Color, color, ());
-    return color;
-}
-
 static blink::WebFallbackThemeEngine::State getWebFallbackThemeState(const RenderTheme* theme, const RenderObject* o)
 {
     if (!theme->isEnabled(o))
@@ -88,8 +82,9 @@
 }
 
 RenderTheme::RenderTheme()
+    : m_hasCustomFocusRingColor(false)
 #if USE(NEW_THEME)
-    : m_platformTheme(platformTheme())
+    , m_platformTheme(platformTheme())
 #endif
 {
 }
@@ -311,22 +306,12 @@
         return paintMediaOverlayPlayButton(o, paintInfo, r);
     case MediaMuteButtonPart:
         return paintMediaMuteButton(o, paintInfo, r);
-    case MediaSeekBackButtonPart:
-        return paintMediaSeekBackButton(o, paintInfo, r);
-    case MediaSeekForwardButtonPart:
-        return paintMediaSeekForwardButton(o, paintInfo, r);
-    case MediaRewindButtonPart:
-        return paintMediaRewindButton(o, paintInfo, r);
-    case MediaReturnToRealtimeButtonPart:
-        return paintMediaReturnToRealtimeButton(o, paintInfo, r);
     case MediaToggleClosedCaptionsButtonPart:
         return paintMediaToggleClosedCaptionsButton(o, paintInfo, r);
     case MediaSliderPart:
         return paintMediaSliderTrack(o, paintInfo, r);
     case MediaSliderThumbPart:
         return paintMediaSliderThumb(o, paintInfo, r);
-    case MediaVolumeSliderMuteButtonPart:
-        return paintMediaMuteButton(o, paintInfo, r);
     case MediaVolumeSliderContainerPart:
         return paintMediaVolumeSliderContainer(o, paintInfo, r);
     case MediaVolumeSliderPart:
@@ -455,19 +440,14 @@
 
 String RenderTheme::extraDefaultStyleSheet()
 {
-    if (!RuntimeEnabledFeatures::dataListElementEnabled() && !RuntimeEnabledFeatures::dialogElementEnabled())
-        return String();
     StringBuilder runtimeCSS;
 
-    if (RuntimeEnabledFeatures::dataListElementEnabled()) {
-        runtimeCSS.appendLiteral("datalist {display: none ;}");
+    runtimeCSS.appendLiteral("datalist {display: none ;}");
 
-        if (RuntimeEnabledFeatures::inputTypeColorEnabled()) {
-            runtimeCSS.appendLiteral("input[type=\"color\"][list] { -webkit-appearance: menulist; width: 88px; height: 23px;}");
-            runtimeCSS.appendLiteral("input[type=\"color\"][list]::-webkit-color-swatch-wrapper { padding-left: 8px; padding-right: 24px;}");
-            runtimeCSS.appendLiteral("input[type=\"color\"][list]::-webkit-color-swatch { border-color: #000000;}");
-        }
-    }
+    runtimeCSS.appendLiteral("input[type=\"color\"][list] { -webkit-appearance: menulist; width: 88px; height: 23px;}");
+    runtimeCSS.appendLiteral("input[type=\"color\"][list]::-webkit-color-swatch-wrapper { padding-left: 8px; padding-right: 24px;}");
+    runtimeCSS.appendLiteral("input[type=\"color\"][list]::-webkit-color-swatch { border-color: #000000;}");
+
     if (RuntimeEnabledFeatures::dialogElementEnabled()) {
         runtimeCSS.appendLiteral("dialog:not([open]) { display: none; }");
         runtimeCSS.appendLiteral("dialog { position: absolute; left: 0; right: 0; width: -webkit-fit-content; height: -webkit-fit-content; margin: auto; border: solid; padding: 1em; background: white; color: black;}");
@@ -502,58 +482,42 @@
 
 Color RenderTheme::activeSelectionBackgroundColor() const
 {
-    if (!m_activeSelectionBackgroundColor.isValid())
-        m_activeSelectionBackgroundColor = platformActiveSelectionBackgroundColor().blendWithWhite();
-    return m_activeSelectionBackgroundColor;
+    return platformActiveSelectionBackgroundColor().blendWithWhite();
 }
 
 Color RenderTheme::inactiveSelectionBackgroundColor() const
 {
-    if (!m_inactiveSelectionBackgroundColor.isValid())
-        m_inactiveSelectionBackgroundColor = platformInactiveSelectionBackgroundColor().blendWithWhite();
-    return m_inactiveSelectionBackgroundColor;
+    return platformInactiveSelectionBackgroundColor().blendWithWhite();
 }
 
 Color RenderTheme::activeSelectionForegroundColor() const
 {
-    if (!m_activeSelectionForegroundColor.isValid() && supportsSelectionForegroundColors())
-        m_activeSelectionForegroundColor = platformActiveSelectionForegroundColor();
-    return m_activeSelectionForegroundColor;
+    return platformActiveSelectionForegroundColor();
 }
 
 Color RenderTheme::inactiveSelectionForegroundColor() const
 {
-    if (!m_inactiveSelectionForegroundColor.isValid() && supportsSelectionForegroundColors())
-        m_inactiveSelectionForegroundColor = platformInactiveSelectionForegroundColor();
-    return m_inactiveSelectionForegroundColor;
+    return platformInactiveSelectionForegroundColor();
 }
 
 Color RenderTheme::activeListBoxSelectionBackgroundColor() const
 {
-    if (!m_activeListBoxSelectionBackgroundColor.isValid())
-        m_activeListBoxSelectionBackgroundColor = platformActiveListBoxSelectionBackgroundColor();
-    return m_activeListBoxSelectionBackgroundColor;
+    return platformActiveListBoxSelectionBackgroundColor();
 }
 
 Color RenderTheme::inactiveListBoxSelectionBackgroundColor() const
 {
-    if (!m_inactiveListBoxSelectionBackgroundColor.isValid())
-        m_inactiveListBoxSelectionBackgroundColor = platformInactiveListBoxSelectionBackgroundColor();
-    return m_inactiveListBoxSelectionBackgroundColor;
+    return platformInactiveListBoxSelectionBackgroundColor();
 }
 
 Color RenderTheme::activeListBoxSelectionForegroundColor() const
 {
-    if (!m_activeListBoxSelectionForegroundColor.isValid() && supportsListBoxSelectionForegroundColors())
-        m_activeListBoxSelectionForegroundColor = platformActiveListBoxSelectionForegroundColor();
-    return m_activeListBoxSelectionForegroundColor;
+    return platformActiveListBoxSelectionForegroundColor();
 }
 
 Color RenderTheme::inactiveListBoxSelectionForegroundColor() const
 {
-    if (!m_inactiveListBoxSelectionForegroundColor.isValid() && supportsListBoxSelectionForegroundColors())
-        m_inactiveListBoxSelectionForegroundColor = platformInactiveListBoxSelectionForegroundColor();
-    return m_inactiveListBoxSelectionForegroundColor;
+    return platformInactiveListBoxSelectionForegroundColor();
 }
 
 Color RenderTheme::platformActiveSelectionBackgroundColor() const
@@ -963,9 +927,9 @@
     RefPtr<HTMLCollection> options = dataList->options();
     GraphicsContextStateSaver stateSaver(*paintInfo.context);
     paintInfo.context->setFillColor(o->resolveColor(CSSPropertyColor));
-    for (unsigned i = 0; Node* node = options->item(i); i++) {
-        ASSERT(node->hasTagName(optionTag));
-        HTMLOptionElement* optionElement = toHTMLOptionElement(node);
+    for (unsigned i = 0; Element* element = options->item(i); i++) {
+        ASSERT(element->hasTagName(optionTag));
+        HTMLOptionElement* optionElement = toHTMLOptionElement(element);
         String value = optionElement->value();
         if (!input->isValidValue(value))
             continue;
@@ -1027,16 +991,6 @@
 
 void RenderTheme::platformColorsDidChange()
 {
-    m_activeSelectionForegroundColor = Color();
-    m_inactiveSelectionForegroundColor = Color();
-    m_activeSelectionBackgroundColor = Color();
-    m_inactiveSelectionBackgroundColor = Color();
-
-    m_activeListBoxSelectionForegroundColor = Color();
-    m_inactiveListBoxSelectionForegroundColor = Color();
-    m_activeListBoxSelectionBackgroundColor = Color();
-    m_inactiveListBoxSelectionForegroundColor = Color();
-
     Page::scheduleForcedStyleRecalcForAllPages();
 }
 
@@ -1116,6 +1070,7 @@
     default:
         break;
     }
+    ASSERT_NOT_REACHED();
     return Color();
 }
 
@@ -1136,12 +1091,13 @@
 
 void RenderTheme::setCustomFocusRingColor(const Color& c)
 {
-    customFocusRingColor() = c;
+    m_customFocusRingColor = c;
+    m_hasCustomFocusRingColor = true;
 }
 
-Color RenderTheme::focusRingColor()
+Color RenderTheme::focusRingColor() const
 {
-    return customFocusRingColor().isValid() ? customFocusRingColor() : theme().platformFocusRingColor();
+    return m_hasCustomFocusRingColor ? m_customFocusRingColor : theme().platformFocusRingColor();
 }
 
 String RenderTheme::fileListNameForWidth(Locale& locale, const FileList* fileList, const Font& font, int width) const
diff --git a/Source/core/rendering/RenderTheme.h b/Source/core/rendering/RenderTheme.h
index 30a1c14..12f765a 100644
--- a/Source/core/rendering/RenderTheme.h
+++ b/Source/core/rendering/RenderTheme.h
@@ -139,9 +139,9 @@
     virtual Color platformActiveTextSearchHighlightColor() const;
     virtual Color platformInactiveTextSearchHighlightColor() const;
 
-    static Color focusRingColor();
+    Color focusRingColor() const;
     virtual Color platformFocusRingColor() const { return Color(0, 0, 0); }
-    static void setCustomFocusRingColor(const Color&);
+    void setCustomFocusRingColor(const Color&);
     static Color tapHighlightColor();
     virtual Color platformTapHighlightColor() const { return RenderTheme::defaultTapHighlightColor; }
     virtual void platformColorsDidChange();
@@ -173,9 +173,6 @@
     virtual double animationDurationForProgressBar(RenderProgress*) const;
 
     // Media controls
-    virtual bool supportsClosedCaptioning() const { return false; }
-    virtual bool hasOwnDisabledStateHandlingFor(ControlPart) const { return false; }
-    virtual bool usesVerticalVolumeSlider() const { return true; }
     virtual String formatMediaControlsTime(float time) const;
     virtual String formatMediaControlsCurrentTime(float currentTime, float duration) const;
 
@@ -201,6 +198,8 @@
 
     virtual bool shouldOpenPickerWithF4Key() const;
 
+    virtual bool supportsSelectionForegroundColors() const { return true; }
+
 protected:
     // The platform selection color.
     virtual Color platformActiveSelectionBackgroundColor() const;
@@ -215,8 +214,6 @@
 
     // A method asking if the theme is able to draw the focus ring.
     virtual bool supportsFocusRing(const RenderStyle*) const;
-    virtual bool supportsSelectionForegroundColors() const { return true; }
-    virtual bool supportsListBoxSelectionForegroundColors() const { return true; }
 
 #if !USE(NEW_THEME)
     // Methods for each appearance value.
@@ -275,15 +272,11 @@
     virtual bool paintMediaPlayButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaOverlayPlayButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaMuteButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
-    virtual bool paintMediaSeekBackButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
-    virtual bool paintMediaSeekForwardButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaVolumeSliderContainer(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaVolumeSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaVolumeSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
-    virtual bool paintMediaRewindButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
-    virtual bool paintMediaReturnToRealtimeButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaToggleClosedCaptionsButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaControlsBackground(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
     virtual bool paintMediaCurrentTime(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
@@ -314,15 +307,8 @@
     bool isReadOnlyControl(const RenderObject*) const;
 
 private:
-    mutable Color m_activeSelectionBackgroundColor;
-    mutable Color m_inactiveSelectionBackgroundColor;
-    mutable Color m_activeSelectionForegroundColor;
-    mutable Color m_inactiveSelectionForegroundColor;
-
-    mutable Color m_activeListBoxSelectionBackgroundColor;
-    mutable Color m_inactiveListBoxSelectionBackgroundColor;
-    mutable Color m_activeListBoxSelectionForegroundColor;
-    mutable Color m_inactiveListBoxSelectionForegroundColor;
+    Color m_customFocusRingColor;
+    bool m_hasCustomFocusRingColor;
 
     // This color is expected to be drawn on a semi-transparent overlay,
     // making it more transparent than its alpha value indicates.
diff --git a/Source/core/rendering/RenderThemeChromiumAndroid.cpp b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
index 97522ef..40ac251 100644
--- a/Source/core/rendering/RenderThemeChromiumAndroid.cpp
+++ b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
@@ -37,8 +37,8 @@
 #include "platform/LayoutTestSupport.h"
 #include "platform/graphics/Color.h"
 #include "platform/scroll/ScrollbarTheme.h"
-#include "public/platform/android/WebThemeEngine.h"
 #include "public/platform/Platform.h"
+#include "public/platform/WebThemeEngine.h"
 #include "wtf/StdLibExtras.h"
 
 namespace WebCore {
diff --git a/Source/core/rendering/RenderThemeChromiumAndroid.h b/Source/core/rendering/RenderThemeChromiumAndroid.h
index 93abb21..ffd6e2b 100644
--- a/Source/core/rendering/RenderThemeChromiumAndroid.h
+++ b/Source/core/rendering/RenderThemeChromiumAndroid.h
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class RenderThemeChromiumAndroid : public RenderThemeChromiumDefault {
+class RenderThemeChromiumAndroid FINAL : public RenderThemeChromiumDefault {
 public:
     static PassRefPtr<RenderTheme> create();
     virtual String extraDefaultStyleSheet() OVERRIDE;
diff --git a/Source/core/rendering/RenderThemeChromiumDefault.cpp b/Source/core/rendering/RenderThemeChromiumDefault.cpp
index 67cffd5..c1a04da 100644
--- a/Source/core/rendering/RenderThemeChromiumDefault.cpp
+++ b/Source/core/rendering/RenderThemeChromiumDefault.cpp
@@ -34,9 +34,9 @@
 #include "platform/graphics/Color.h"
 #include "platform/graphics/GraphicsContext.h"
 #include "platform/graphics/GraphicsContextStateSaver.h"
-#include "public/platform/default/WebThemeEngine.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebRect.h"
+#include "public/platform/WebThemeEngine.h"
 #include "wtf/StdLibExtras.h"
 
 namespace WebCore {
@@ -255,9 +255,10 @@
     extraParams.button.indeterminate = isIndeterminate(o);
 
     float zoomLevel = o->style()->effectiveZoom();
-    GraphicsContextStateSaver stateSaver(*i.context);
+    GraphicsContextStateSaver stateSaver(*i.context, false);
     IntRect unzoomedRect = rect;
     if (zoomLevel != 1) {
+        stateSaver.save();
         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
         i.context->translate(unzoomedRect.x(), unzoomedRect.y());
@@ -333,8 +334,7 @@
 
     blink::WebCanvas* canvas = i.context->canvas();
 
-    // Fallback to white if the specified color object is invalid.
-    Color backgroundColor = o->resolveColor(CSSPropertyBackgroundColor, Color::white);
+    Color backgroundColor = o->resolveColor(CSSPropertyBackgroundColor);
     extraParams.textField.backgroundColor = backgroundColor.rgb();
 
     blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartTextField, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
@@ -386,6 +386,40 @@
     return false;
 }
 
+bool RenderThemeChromiumDefault::paintMenuListButton(RenderObject* o, const PaintInfo& i, const IntRect& rect)
+{
+    if (!o->isBox())
+        return false;
+
+    const int right = rect.x() + rect.width();
+    const int middle = rect.y() + rect.height() / 2;
+
+    blink::WebThemeEngine::ExtraParams extraParams;
+    extraParams.menuList.arrowY = middle;
+    extraParams.menuList.hasBorder = false;
+    extraParams.menuList.hasBorderRadius = o->style()->hasBorderRadius();
+    extraParams.menuList.backgroundColor = Color::transparent;
+    extraParams.menuList.fillContentArea = false;
+
+    if (useMockTheme()) {
+        const RenderBox* box = toRenderBox(o);
+        // The size and position of the drop-down button is different between
+        // the mock theme and the regular aura theme.
+        int spacingTop = box->borderTop() + box->paddingTop();
+        int spacingBottom = box->borderBottom() + box->paddingBottom();
+        int spacingRight = box->borderRight() + box->paddingRight();
+        extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 4 + spacingRight: right - 13 - spacingRight;
+        extraParams.menuList.arrowHeight = rect.height() - spacingBottom - spacingTop;
+    } else {
+        extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 7 : right - 13;
+    }
+
+    blink::WebCanvas* canvas = i.context->canvas();
+
+    blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartMenuList, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
+    return false;
+}
+
 bool RenderThemeChromiumDefault::paintSliderTrack(RenderObject* o, const PaintInfo& i, const IntRect& rect)
 {
     blink::WebThemeEngine::ExtraParams extraParams;
@@ -396,9 +430,10 @@
 
     // FIXME: Mock theme doesn't handle zoomed sliders.
     float zoomLevel = useMockTheme() ? 1 : o->style()->effectiveZoom();
-    GraphicsContextStateSaver stateSaver(*i.context);
+    GraphicsContextStateSaver stateSaver(*i.context, false);
     IntRect unzoomedRect = rect;
     if (zoomLevel != 1) {
+        stateSaver.save();
         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
         i.context->translate(unzoomedRect.x(), unzoomedRect.y());
@@ -420,9 +455,10 @@
 
     // FIXME: Mock theme doesn't handle zoomed sliders.
     float zoomLevel = useMockTheme() ? 1 : o->style()->effectiveZoom();
-    GraphicsContextStateSaver stateSaver(*i.context);
+    GraphicsContextStateSaver stateSaver(*i.context, false);
     IntRect unzoomedRect = rect;
     if (zoomLevel != 1) {
+        stateSaver.save();
         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
         i.context->translate(unzoomedRect.x(), unzoomedRect.y());
diff --git a/Source/core/rendering/RenderThemeChromiumDefault.h b/Source/core/rendering/RenderThemeChromiumDefault.h
index bba1aa5..6a08626 100644
--- a/Source/core/rendering/RenderThemeChromiumDefault.h
+++ b/Source/core/rendering/RenderThemeChromiumDefault.h
@@ -36,12 +36,12 @@
 class RenderThemeChromiumDefault : public RenderThemeChromiumSkia {
 public:
     static PassRefPtr<RenderTheme> create();
-    virtual String extraDefaultStyleSheet();
+    virtual String extraDefaultStyleSheet() OVERRIDE;
 
-    virtual Color systemColor(CSSValueID) const;
+    virtual Color systemColor(CSSValueID) const OVERRIDE;
 
     // A method asking if the control changes its tint when the window has focus or not.
-    virtual bool controlSupportsTints(const RenderObject*) const;
+    virtual bool controlSupportsTints(const RenderObject*) const OVERRIDE;
 
     virtual bool supportsFocusRing(const RenderStyle*) const OVERRIDE;
 
@@ -51,36 +51,37 @@
     virtual Color inactiveListBoxSelectionBackgroundColor() const;
     virtual Color inactiveListBoxSelectionForegroundColor() const;
 
-    virtual Color platformActiveSelectionBackgroundColor() const;
-    virtual Color platformInactiveSelectionBackgroundColor() const;
-    virtual Color platformActiveSelectionForegroundColor() const;
-    virtual Color platformInactiveSelectionForegroundColor() const;
+    virtual Color platformActiveSelectionBackgroundColor() const OVERRIDE;
+    virtual Color platformInactiveSelectionBackgroundColor() const OVERRIDE;
+    virtual Color platformActiveSelectionForegroundColor() const OVERRIDE;
+    virtual Color platformInactiveSelectionForegroundColor() const OVERRIDE;
 
     virtual IntSize sliderTickSize() const OVERRIDE;
     virtual int sliderTickOffsetFromTrackCenter() const OVERRIDE;
-    virtual void adjustSliderThumbSize(RenderStyle*, Element*) const;
+    virtual void adjustSliderThumbSize(RenderStyle*, Element*) const OVERRIDE;
 
     static void setCaretBlinkInterval(double);
-    virtual double caretBlinkIntervalInternal() const;
+    virtual double caretBlinkIntervalInternal() const OVERRIDE;
 
-    virtual bool paintCheckbox(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void setCheckboxSize(RenderStyle*) const;
+    virtual bool paintCheckbox(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual void setCheckboxSize(RenderStyle*) const OVERRIDE;
 
-    virtual bool paintRadio(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void setRadioSize(RenderStyle*) const;
+    virtual bool paintRadio(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual void setRadioSize(RenderStyle*) const OVERRIDE;
 
-    virtual bool paintButton(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const;
-    virtual bool paintInnerSpinButton(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const OVERRIDE;
+    virtual bool paintInnerSpinButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual bool popsMenuBySpaceOrReturn() const OVERRIDE { return true; }
+    virtual bool popsMenuBySpaceOrReturn() const OVERRIDE FINAL { return true; }
 
-    virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
     virtual bool shouldOpenPickerWithF4Key() const OVERRIDE;
 
@@ -93,7 +94,7 @@
 
 private:
     // A general method asking if any control tinting is supported at all.
-    virtual bool supportsControlTints() const;
+    virtual bool supportsControlTints() const OVERRIDE;
 
     static double m_caretBlinkInterval;
 
diff --git a/Source/core/rendering/RenderThemeChromiumFontProvider.cpp b/Source/core/rendering/RenderThemeChromiumFontProvider.cpp
index 527f855..b8083e0 100644
--- a/Source/core/rendering/RenderThemeChromiumFontProvider.cpp
+++ b/Source/core/rendering/RenderThemeChromiumFontProvider.cpp
@@ -46,9 +46,9 @@
 // FIXME: The only case where we know we don't match IE is for ANSI encodings.
 // IE uses MS Shell Dlg there, which we render incorrectly at certain pixel
 // sizes (e.g. 15px). So, for now we just use Arial.
-const String& RenderThemeChromiumFontProvider::defaultGUIFont()
+const AtomicString& RenderThemeChromiumFontProvider::defaultGUIFont()
 {
-    DEFINE_STATIC_LOCAL(String, fontFace, ("Arial"));
+    DEFINE_STATIC_LOCAL(const AtomicString, fontFace, ("Arial", AtomicString::ConstructFromLiteral));
     return fontFace;
 }
 
diff --git a/Source/core/rendering/RenderThemeChromiumFontProvider.h b/Source/core/rendering/RenderThemeChromiumFontProvider.h
index 57589c2..f6ce1df 100644
--- a/Source/core/rendering/RenderThemeChromiumFontProvider.h
+++ b/Source/core/rendering/RenderThemeChromiumFontProvider.h
@@ -42,7 +42,7 @@
     static void setDefaultFontSize(int);
 
 protected:
-    static const WTF::String& defaultGUIFont();
+    static const WTF::AtomicString& defaultGUIFont();
 
     static float s_defaultFontSize;
 };
diff --git a/Source/core/rendering/RenderThemeChromiumMac.h b/Source/core/rendering/RenderThemeChromiumMac.h
index 371ecc6..4742574 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.h
+++ b/Source/core/rendering/RenderThemeChromiumMac.h
@@ -32,7 +32,7 @@
 
 namespace WebCore {
 
-class RenderThemeChromiumMac : public RenderTheme {
+class RenderThemeChromiumMac FINAL : public RenderTheme {
 public:
     static PassRefPtr<RenderTheme> create();
 
@@ -48,6 +48,7 @@
 
     virtual Color platformActiveSelectionBackgroundColor() const OVERRIDE;
     virtual Color platformInactiveSelectionBackgroundColor() const OVERRIDE;
+    virtual Color platformActiveSelectionForegroundColor() const OVERRIDE;
     virtual Color platformActiveListBoxSelectionBackgroundColor() const OVERRIDE;
     virtual Color platformActiveListBoxSelectionForegroundColor() const OVERRIDE;
     virtual Color platformInactiveListBoxSelectionBackgroundColor() const OVERRIDE;
@@ -88,41 +89,39 @@
 
     virtual Color systemColor(CSSValueID) const OVERRIDE;
 
+    virtual bool supportsSelectionForegroundColors() const OVERRIDE { return false; }
+
 protected:
     RenderThemeChromiumMac();
     virtual ~RenderThemeChromiumMac();
 
-    virtual bool supportsSelectionForegroundColors() const OVERRIDE { return false; }
+    virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual void adjustMenuListStyle(RenderStyle*, Element*) const OVERRIDE;
 
-    virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustMenuListStyle(RenderStyle*, Element*) const;
+    virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const OVERRIDE;
 
-    virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const;
+    virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintSearchField(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual void adjustSearchFieldStyle(RenderStyle*, Element*) const OVERRIDE;
 
-    virtual bool paintSearchField(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustSearchFieldStyle(RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldCancelButtonStyle(RenderStyle*, Element*) const OVERRIDE;
+    virtual bool paintSearchFieldCancelButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual void adjustSearchFieldCancelButtonStyle(RenderStyle*, Element*) const;
-    virtual bool paintSearchFieldCancelButton(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual void adjustSearchFieldDecorationStyle(RenderStyle*, Element*) const OVERRIDE;
+    virtual bool paintSearchFieldDecoration(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual void adjustSearchFieldDecorationStyle(RenderStyle*, Element*) const;
-    virtual bool paintSearchFieldDecoration(RenderObject*, const PaintInfo&, const IntRect&);
-
-    virtual void adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const;
-    virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&);
-
-    virtual bool supportsClosedCaptioning() const { return true; }
+    virtual void adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const OVERRIDE;
+    virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
 private:
     virtual String fileListNameForWidth(Locale&, const FileList*, const Font&, int width) const OVERRIDE;
@@ -174,21 +173,19 @@
 
 protected:
     virtual void adjustMediaSliderThumbSize(RenderStyle*) const;
-    virtual bool paintMediaPlayButton(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaMuteButton(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual String extraFullScreenStyleSheet();
+    virtual bool paintMediaPlayButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaMuteButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual String extraFullScreenStyleSheet() OVERRIDE;
 
-    virtual bool paintMediaSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaVolumeSliderContainer(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaVolumeSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaVolumeSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool hasOwnDisabledStateHandlingFor(ControlPart) const { return true; }
-    virtual bool usesVerticalVolumeSlider() const { return false; }
-    virtual String formatMediaControlsTime(float time) const;
-    virtual String formatMediaControlsCurrentTime(float currentTime, float duration) const;
-    virtual bool paintMediaFullscreenButton(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaToggleClosedCaptionsButton(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintMediaSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaVolumeSliderContainer(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaVolumeSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaVolumeSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual String formatMediaControlsTime(float time) const OVERRIDE;
+    virtual String formatMediaControlsCurrentTime(float currentTime, float duration) const OVERRIDE;
+    virtual bool paintMediaFullscreenButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaToggleClosedCaptionsButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
     // Controls color values returned from platformFocusRingColor(). systemColor() will be used when false.
     bool usesTestModeFocusRingColor() const;
@@ -199,7 +196,7 @@
 
 private:
     virtual void updateActiveState(NSCell*, const RenderObject*);
-    virtual String extraDefaultStyleSheet();
+    virtual String extraDefaultStyleSheet() OVERRIDE;
     virtual bool shouldShowPlaceholderWhenFocused() const OVERRIDE;
 
     mutable RetainPtr<NSPopUpButtonCell> m_popupButton;
diff --git a/Source/core/rendering/RenderThemeChromiumMac.mm b/Source/core/rendering/RenderThemeChromiumMac.mm
index 82f39e2..dfdd539 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.mm
+++ b/Source/core/rendering/RenderThemeChromiumMac.mm
@@ -34,7 +34,6 @@
 #import "core/html/TimeRanges.h"
 #import "core/html/shadow/MediaControlElements.h"
 #import "core/frame/FrameView.h"
-#import "core/platform/mac/ThemeMac.h"
 #import "core/rendering/PaintInfo.h"
 #import "core/rendering/RenderLayer.h"
 #import "core/rendering/RenderMedia.h"
@@ -53,6 +52,7 @@
 #import "platform/graphics/cg/GraphicsContextCG.h"
 #import "platform/mac/ColorMac.h"
 #import "platform/mac/LocalCurrentGraphicsContext.h"
+#import "platform/mac/ThemeMac.h"
 #import "platform/mac/WebCoreNSCellExtras.h"
 #import "platform/text/PlatformLocale.h"
 #import "platform/text/StringTruncator.h"
@@ -194,6 +194,11 @@
     return Color(static_cast<int>(255.0 * [color redComponent]), static_cast<int>(255.0 * [color greenComponent]), static_cast<int>(255.0 * [color blueComponent]));
 }
 
+Color RenderThemeChromiumMac::platformActiveSelectionForegroundColor() const
+{
+    return Color::black;
+}
+
 Color RenderThemeChromiumMac::platformActiveListBoxSelectionBackgroundColor() const
 {
     NSColor* color = [[NSColor alternateSelectedControlColor] colorUsingColorSpaceName:NSDeviceRGBColorSpace];
@@ -394,6 +399,7 @@
     }
 
     Color color;
+    bool needsFallback = false;
     switch (cssValueId) {
         case CSSValueActiveborder:
             color = convertNSColorToColor([NSColor keyboardFocusIndicatorColor]);
@@ -406,6 +412,7 @@
             break;
         case CSSValueBackground:
             // Use theme independent default
+            needsFallback = true;
             break;
         case CSSValueButtonface:
             // We use this value instead of NSColor's controlColor to avoid website incompatibilities.
@@ -491,14 +498,14 @@
             color = convertNSColorToColor([NSColor windowFrameTextColor]);
             break;
         default:
+            needsFallback = true;
             break;
     }
 
-    if (!color.isValid())
+    if (needsFallback)
         color = RenderTheme::systemColor(cssValueId);
 
-    if (color.isValid())
-        m_systemColorCache.set(cssValueId, color.rgb());
+    m_systemColorCache.set(cssValueId, color.rgb());
 
     return color;
 }
@@ -1155,7 +1162,7 @@
 
     GraphicsContextStateSaver stateSaver(*paintInfo.context);
 
-    RoundedRect border = o->style()->getRoundedBorderFor(r, o->view());
+    RoundedRect border = o->style()->getRoundedBorderFor(r);
     int radius = border.radii().topLeft().width();
 
     CGColorSpaceRef cspace = deviceRGBColorSpaceRef();
diff --git a/Source/core/rendering/RenderThemeChromiumSkia.cpp b/Source/core/rendering/RenderThemeChromiumSkia.cpp
index 2a7e3c2..26396e8 100644
--- a/Source/core/rendering/RenderThemeChromiumSkia.cpp
+++ b/Source/core/rendering/RenderThemeChromiumSkia.cpp
@@ -91,11 +91,6 @@
     return false;
 }
 
-bool RenderThemeChromiumSkia::supportsClosedCaptioning() const
-{
-    return true;
-}
-
 Color RenderThemeChromiumSkia::platformActiveSelectionBackgroundColor() const
 {
     return Color(0x1e, 0x90, 0xff);
diff --git a/Source/core/rendering/RenderThemeChromiumSkia.h b/Source/core/rendering/RenderThemeChromiumSkia.h
index f3550c7..acf210d 100644
--- a/Source/core/rendering/RenderThemeChromiumSkia.h
+++ b/Source/core/rendering/RenderThemeChromiumSkia.h
@@ -39,8 +39,8 @@
     RenderThemeChromiumSkia();
     virtual ~RenderThemeChromiumSkia();
 
-    virtual String extraDefaultStyleSheet();
-    virtual String extraQuirksStyleSheet();
+    virtual String extraDefaultStyleSheet() OVERRIDE;
+    virtual String extraQuirksStyleSheet() OVERRIDE;
 
     virtual Color platformTapHighlightColor() const OVERRIDE
     {
@@ -48,57 +48,56 @@
     }
 
     // A method asking if the theme's controls actually care about redrawing when hovered.
-    virtual bool supportsHover(const RenderStyle*) const;
+    virtual bool supportsHover(const RenderStyle*) const OVERRIDE FINAL;
 
     // A method asking if the theme is able to draw the focus ring.
-    virtual bool supportsFocusRing(const RenderStyle*) const;
+    virtual bool supportsFocusRing(const RenderStyle*) const OVERRIDE;
 
-    virtual bool supportsClosedCaptioning() const OVERRIDE;
     // The platform selection color.
-    virtual Color platformActiveSelectionBackgroundColor() const;
-    virtual Color platformInactiveSelectionBackgroundColor() const;
-    virtual Color platformActiveSelectionForegroundColor() const;
-    virtual Color platformInactiveSelectionForegroundColor() const;
-    virtual Color platformFocusRingColor() const;
+    virtual Color platformActiveSelectionBackgroundColor() const OVERRIDE;
+    virtual Color platformInactiveSelectionBackgroundColor() const OVERRIDE;
+    virtual Color platformActiveSelectionForegroundColor() const OVERRIDE;
+    virtual Color platformInactiveSelectionForegroundColor() const OVERRIDE;
+    virtual Color platformFocusRingColor() const OVERRIDE;
 
     // To change the blink interval, override caretBlinkIntervalInternal instead of this one so that we may share layout test code an intercepts.
-    virtual double caretBlinkInterval() const;
+    virtual double caretBlinkInterval() const OVERRIDE;
 
     // System fonts.
-    virtual void systemFont(CSSValueID, FontDescription&) const;
+    virtual void systemFont(CSSValueID, FontDescription&) const OVERRIDE;
 
-    virtual int minimumMenuListSize(RenderStyle*) const;
+    virtual int minimumMenuListSize(RenderStyle*) const OVERRIDE;
 
-    virtual void setCheckboxSize(RenderStyle*) const;
+    virtual void setCheckboxSize(RenderStyle*) const OVERRIDE;
 
-    virtual void setRadioSize(RenderStyle*) const;
+    virtual void setRadioSize(RenderStyle*) const OVERRIDE;
 
-    virtual void adjustButtonStyle(RenderStyle*, Element*) const;
+    virtual void adjustButtonStyle(RenderStyle*, Element*) const OVERRIDE;
 
-    virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual void adjustSearchFieldStyle(RenderStyle*, Element*) const;
-    virtual bool paintSearchField(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual void adjustSearchFieldStyle(RenderStyle*, Element*) const OVERRIDE;
+    virtual bool paintSearchField(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual void adjustSearchFieldCancelButtonStyle(RenderStyle*, Element*) const;
-    virtual bool paintSearchFieldCancelButton(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual void adjustSearchFieldCancelButtonStyle(RenderStyle*, Element*) const OVERRIDE;
+    virtual bool paintSearchFieldCancelButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual void adjustSearchFieldDecorationStyle(RenderStyle*, Element*) const;
+    virtual void adjustSearchFieldDecorationStyle(RenderStyle*, Element*) const OVERRIDE;
 
-    virtual void adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const;
-    virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual void adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const OVERRIDE;
+    virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual bool paintMediaSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaVolumeSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual void adjustSliderThumbSize(RenderStyle*, Element*) const;
-    virtual bool paintMediaSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaToggleClosedCaptionsButton(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaVolumeSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaPlayButton(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual bool paintMediaMuteButton(RenderObject*, const PaintInfo&, const IntRect&);
-    virtual String formatMediaControlsTime(float time) const;
-    virtual String formatMediaControlsCurrentTime(float currentTime, float duration) const;
-    virtual bool paintMediaFullscreenButton(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual bool paintMediaSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaVolumeSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual void adjustSliderThumbSize(RenderStyle*, Element*) const OVERRIDE;
+    virtual bool paintMediaSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaToggleClosedCaptionsButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaVolumeSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaPlayButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual bool paintMediaMuteButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+    virtual String formatMediaControlsTime(float time) const OVERRIDE;
+    virtual String formatMediaControlsCurrentTime(float currentTime, float duration) const OVERRIDE;
+    virtual bool paintMediaFullscreenButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
     // MenuList refers to an unstyled menulist (meaning a menulist without
     // background-color or border set) and MenuListButton refers to a styled
@@ -109,22 +108,18 @@
     // In short, we either go down the MenuList code path or the MenuListButton
     // codepath. We never go down both. And in both cases, they render the
     // entire menulist.
-    virtual void adjustMenuListStyle(RenderStyle*, Element*) const;
-    virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const;
-    virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&);
+    virtual void adjustMenuListStyle(RenderStyle*, Element*) const OVERRIDE;
+    virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const OVERRIDE;
+    virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
 
-    virtual double animationRepeatIntervalForProgressBar(RenderProgress*) const;
-    virtual double animationDurationForProgressBar(RenderProgress*) const;
+    virtual double animationRepeatIntervalForProgressBar(RenderProgress*) const OVERRIDE;
+    virtual double animationDurationForProgressBar(RenderProgress*) const OVERRIDE;
 
     // These methods define the padding for the MenuList's inner block.
-    virtual int popupInternalPaddingLeft(RenderStyle*) const;
-    virtual int popupInternalPaddingRight(RenderStyle*) const;
-    virtual int popupInternalPaddingTop(RenderStyle*) const;
-    virtual int popupInternalPaddingBottom(RenderStyle*) const;
-
-    // Media controls
-    virtual bool hasOwnDisabledStateHandlingFor(ControlPart) const { return true; }
-    virtual bool usesVerticalVolumeSlider() const { return false; }
+    virtual int popupInternalPaddingLeft(RenderStyle*) const OVERRIDE;
+    virtual int popupInternalPaddingRight(RenderStyle*) const OVERRIDE;
+    virtual int popupInternalPaddingTop(RenderStyle*) const OVERRIDE;
+    virtual int popupInternalPaddingBottom(RenderStyle*) const OVERRIDE;
 
     // Provide a way to pass the default font size from the Settings object
     // to the render theme. FIXME: http://b/1129186 A cleaner way would be
diff --git a/Source/core/rendering/RenderThemeChromiumWin.cpp b/Source/core/rendering/RenderThemeChromiumWin.cpp
deleted file mode 100644
index b122407..0000000
--- a/Source/core/rendering/RenderThemeChromiumWin.cpp
+++ /dev/null
@@ -1,660 +0,0 @@
-/*
- * This file is part of the WebKit project.
- *
- * Copyright (C) 2006 Apple Computer, Inc.
- * Copyright (C) 2008, 2009 Google, Inc.
- * Copyright (C) 2009 Kenneth Rohde Christiansen
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA 02111-1307, USA.
- *
- */
-
-#include "config.h"
-#include "core/rendering/RenderThemeChromiumWin.h"
-
-#include <windows.h>
-#include <uxtheme.h>
-#include <vssym32.h>
-
-#include "CSSValueKeywords.h"
-#include "HTMLNames.h"
-#include "core/html/HTMLMediaElement.h"
-#include "core/html/shadow/MediaControlElements.h"
-#include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderBox.h"
-#include "core/rendering/RenderProgress.h"
-#include "core/rendering/RenderSlider.h"
-#include "platform/LayoutTestSupport.h"
-#include "platform/fonts/FontSelector.h"
-#include "platform/graphics/GraphicsContext.h"
-#include "platform/graphics/win/TransparencyWin.h"
-#include "platform/scroll/ScrollbarTheme.h"
-#include "platform/win/SystemInfo.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebColor.h"
-#include "public/platform/WebRect.h"
-#include "public/platform/win/WebThemeEngine.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/StdLibExtras.h"
-
-// FIXME: This dependency should eventually be removed.
-#include <skia/ext/skia_utils_win.h>
-
-namespace WebCore {
-
-// The standard width for the menu list drop-down button when run under
-// layout test mode. Use the value that's currently captured in most baselines.
-static const int kStandardMenuListButtonWidth = 17;
-
-namespace {
-// We must not create multiple ThemePainter instances.
-class ThemePainter {
-public:
-    ThemePainter(GraphicsContext* context, const IntRect& r)
-    {
-#ifndef NDEBUG
-        ASSERT(!s_hasInstance);
-        s_hasInstance = true;
-#endif
-        TransparencyWin::TransformMode transformMode = getTransformMode(context->getCTM());
-        m_helper.init(context, getLayerMode(context, transformMode), transformMode, r);
-
-        if (!m_helper.context()) {
-            // TransparencyWin doesn't have well-defined copy-ctor nor op=()
-            // so we re-initialize it instead of assigning a fresh istance.
-            // On the reinitialization, we fallback to use NoLayer mode.
-            // Note that the original initialization failure can be caused by
-            // a failure of an internal buffer allocation and NoLayer mode
-            // does not have such buffer allocations.
-            m_helper.~TransparencyWin();
-            new (&m_helper) TransparencyWin();
-            m_helper.init(context, TransparencyWin::NoLayer, transformMode, r);
-        }
-    }
-
-    ~ThemePainter()
-    {
-        m_helper.composite();
-#ifndef NDEBUG
-        s_hasInstance = false;
-#endif
-    }
-
-    GraphicsContext* context() { return m_helper.context(); }
-    const IntRect& drawRect() { return m_helper.drawRect(); }
-
-private:
-
-    static TransparencyWin::LayerMode getLayerMode(GraphicsContext* context, TransparencyWin::TransformMode transformMode)
-    {
-        if (!context->isCertainlyOpaque()) // Might have transparent background.
-            return TransparencyWin::WhiteLayer;
-        if (context->canvas()->isDrawingToLayer()) // Needs antialiasing help.
-            return TransparencyWin::OpaqueCompositeLayer;
-        // Nothing interesting.
-        return transformMode == TransparencyWin::KeepTransform ? TransparencyWin::NoLayer : TransparencyWin::OpaqueCompositeLayer;
-    }
-
-    static TransparencyWin::TransformMode getTransformMode(const AffineTransform& matrix)
-    {
-        if (matrix.b() || matrix.c()) // Skew.
-            return TransparencyWin::Untransform;
-        if (matrix.a() != 1.0 || matrix.d() != 1.0) // Scale.
-            return TransparencyWin::ScaleTransform;
-        // Nothing interesting.
-        return TransparencyWin::KeepTransform;
-    }
-
-    TransparencyWin m_helper;
-#ifndef NDEBUG
-    static bool s_hasInstance;
-#endif
-};
-
-#ifndef NDEBUG
-bool ThemePainter::s_hasInstance = false;
-#endif
-
-} // namespace
-
-// Internal static helper functions.  We don't put them in an anonymous
-// namespace so they have easier access to the WebCore namespace.
-
-static bool supportsFocus(ControlPart appearance)
-{
-    switch (appearance) {
-    case SquareButtonPart:
-    case PushButtonPart:
-    case ButtonPart:
-    case SearchFieldPart:
-    case TextFieldPart:
-    case TextAreaPart:
-        return true;
-    }
-    return false;
-}
-
-static double querySystemBlinkInterval(double defaultInterval)
-{
-    UINT blinkTime = GetCaretBlinkTime();
-    if (!blinkTime)
-        return defaultInterval;
-    if (blinkTime == INFINITE)
-        return 0;
-    return blinkTime / 1000.0;
-}
-
-PassRefPtr<RenderTheme> RenderThemeChromiumWin::create()
-{
-    return adoptRef(new RenderThemeChromiumWin);
-}
-
-RenderTheme& RenderTheme::theme()
-{
-    DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumWin::create()));
-    return *renderTheme;
-}
-
-bool RenderThemeChromiumWin::supportsFocusRing(const RenderStyle* style) const
-{
-    // Let webkit draw one of its halo rings around any focused element,
-    // except push buttons. For buttons we use the windows PBS_DEFAULTED
-    // styling to give it a blue border.
-    return style->appearance() == ButtonPart
-            || style->appearance() == PushButtonPart
-            || style->appearance() == SquareButtonPart;
-}
-
-Color RenderThemeChromiumWin::platformActiveSelectionBackgroundColor() const
-{
-    if (isRunningLayoutTest())
-        return Color(0x00, 0x00, 0xff); // Royal blue.
-    COLORREF color = GetSysColor(COLOR_HIGHLIGHT);
-    return Color(GetRValue(color), GetGValue(color), GetBValue(color), 0xff);
-}
-
-Color RenderThemeChromiumWin::platformInactiveSelectionBackgroundColor() const
-{
-    if (isRunningLayoutTest())
-        return Color(0x99, 0x99, 0x99); // Medium gray.
-    COLORREF color = GetSysColor(COLOR_GRAYTEXT);
-    return Color(GetRValue(color), GetGValue(color), GetBValue(color), 0xff);
-}
-
-Color RenderThemeChromiumWin::platformActiveSelectionForegroundColor() const
-{
-    if (isRunningLayoutTest())
-        return Color(0xff, 0xff, 0xcc); // Pale yellow.
-    COLORREF color = GetSysColor(COLOR_HIGHLIGHTTEXT);
-    return Color(GetRValue(color), GetGValue(color), GetBValue(color), 0xff);
-}
-
-Color RenderThemeChromiumWin::platformInactiveSelectionForegroundColor() const
-{
-    return Color::white;
-}
-
-Color RenderThemeChromiumWin::platformActiveTextSearchHighlightColor() const
-{
-    return Color(0xff, 0x96, 0x32); // Orange.
-}
-
-Color RenderThemeChromiumWin::platformInactiveTextSearchHighlightColor() const
-{
-    return Color(0xff, 0xff, 0x96); // Yellow.
-}
-
-// Map a CSSValue* system color to an index understood by GetSysColor().
-static int cssValueIdToSysColorIndex(int cssValueId)
-{
-    switch (cssValueId) {
-    case CSSValueActiveborder: return COLOR_ACTIVEBORDER;
-    case CSSValueActivecaption: return COLOR_ACTIVECAPTION;
-    case CSSValueAppworkspace: return COLOR_APPWORKSPACE;
-    case CSSValueBackground: return COLOR_BACKGROUND;
-    case CSSValueButtonface: return COLOR_BTNFACE;
-    case CSSValueButtonhighlight: return COLOR_BTNHIGHLIGHT;
-    case CSSValueButtonshadow: return COLOR_BTNSHADOW;
-    case CSSValueButtontext: return COLOR_BTNTEXT;
-    case CSSValueCaptiontext: return COLOR_CAPTIONTEXT;
-    case CSSValueGraytext: return COLOR_GRAYTEXT;
-    case CSSValueHighlight: return COLOR_HIGHLIGHT;
-    case CSSValueHighlighttext: return COLOR_HIGHLIGHTTEXT;
-    case CSSValueInactiveborder: return COLOR_INACTIVEBORDER;
-    case CSSValueInactivecaption: return COLOR_INACTIVECAPTION;
-    case CSSValueInactivecaptiontext: return COLOR_INACTIVECAPTIONTEXT;
-    case CSSValueInfobackground: return COLOR_INFOBK;
-    case CSSValueInfotext: return COLOR_INFOTEXT;
-    case CSSValueMenu: return COLOR_MENU;
-    case CSSValueMenutext: return COLOR_MENUTEXT;
-    case CSSValueScrollbar: return COLOR_SCROLLBAR;
-    case CSSValueThreeddarkshadow: return COLOR_3DDKSHADOW;
-    case CSSValueThreedface: return COLOR_3DFACE;
-    case CSSValueThreedhighlight: return COLOR_3DHIGHLIGHT;
-    case CSSValueThreedlightshadow: return COLOR_3DLIGHT;
-    case CSSValueThreedshadow: return COLOR_3DSHADOW;
-    case CSSValueWindow: return COLOR_WINDOW;
-    case CSSValueWindowframe: return COLOR_WINDOWFRAME;
-    case CSSValueWindowtext: return COLOR_WINDOWTEXT;
-    default: return -1; // Unsupported CSSValue
-    }
-}
-
-Color RenderThemeChromiumWin::systemColor(CSSValueID cssValueId) const
-{
-    int sysColorIndex = cssValueIdToSysColorIndex(cssValueId);
-    if (isRunningLayoutTest() || (sysColorIndex == -1))
-        return RenderTheme::systemColor(cssValueId);
-
-    COLORREF color = GetSysColor(sysColorIndex);
-    return Color(GetRValue(color), GetGValue(color), GetBValue(color));
-}
-
-IntSize RenderThemeChromiumWin::sliderTickSize() const
-{
-    return IntSize(1, 3);
-}
-
-int RenderThemeChromiumWin::sliderTickOffsetFromTrackCenter() const
-{
-    return 11;
-}
-
-void RenderThemeChromiumWin::adjustSliderThumbSize(RenderStyle* style, Element* element) const
-{
-    // These sizes match what WinXP draws for various menus.
-    const int sliderThumbAlongAxis = 11;
-    const int sliderThumbAcrossAxis = 21;
-    if (style->appearance() == SliderThumbHorizontalPart) {
-        style->setWidth(Length(sliderThumbAlongAxis, Fixed));
-        style->setHeight(Length(sliderThumbAcrossAxis, Fixed));
-    } else if (style->appearance() == SliderThumbVerticalPart) {
-        style->setWidth(Length(sliderThumbAcrossAxis, Fixed));
-        style->setHeight(Length(sliderThumbAlongAxis, Fixed));
-    } else
-        RenderThemeChromiumSkia::adjustSliderThumbSize(style, element);
-}
-
-bool RenderThemeChromiumWin::paintCheckbox(RenderObject* o, const PaintInfo& i, const IntRect& r)
-{
-    return paintButton(o, i, r);
-}
-bool RenderThemeChromiumWin::paintRadio(RenderObject* o, const PaintInfo& i, const IntRect& r)
-{
-    return paintButton(o, i, r);
-}
-
-bool RenderThemeChromiumWin::paintButton(RenderObject* o, const PaintInfo& i, const IntRect& r)
-{
-    const ThemeData& themeData = getThemeData(o);
-
-    ThemePainter painter(i.context, r);
-    blink::WebCanvas* canvas = painter.context()->canvas();
-    blink::Platform::current()->themeEngine()->paintButton(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()));
-    return false;
-}
-
-bool RenderThemeChromiumWin::paintTextField(RenderObject* o, const PaintInfo& i, const IntRect& r)
-{
-    return paintTextFieldInternal(o, i, r, true);
-}
-
-bool RenderThemeChromiumWin::paintSliderTrack(RenderObject* o, const PaintInfo& i, const IntRect& r)
-{
-    const ThemeData& themeData = getThemeData(o);
-
-    ThemePainter painter(i.context, r);
-    blink::WebCanvas* canvas = painter.context()->canvas();
-    blink::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()));
-
-    paintSliderTicks(o, i, r);
-
-    return false;
-}
-
-bool RenderThemeChromiumWin::paintSliderThumb(RenderObject* o, const PaintInfo& i, const IntRect& r)
-{
-    const ThemeData& themeData = getThemeData(o);
-
-    ThemePainter painter(i.context, r);
-    blink::WebCanvas* canvas = painter.context()->canvas();
-    blink::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()));
-
-    return false;
-}
-
-static int menuListButtonWidth()
-{
-    static int width = isRunningLayoutTest() ? kStandardMenuListButtonWidth :
-        IntSize(blink::Platform::current()->themeEngine()->getSize(SBP_ARROWBTN)).width();
-    return width;
-}
-
-// Used to paint unstyled menulists (i.e. with the default border)
-bool RenderThemeChromiumWin::paintMenuList(RenderObject* o, const PaintInfo& i, const IntRect& r)
-{
-    if (!o->isBox())
-        return false;
-
-    const RenderBox* box = toRenderBox(o);
-    int borderRight = box->borderRight();
-    int borderLeft = box->borderLeft();
-    int borderTop = box->borderTop();
-    int borderBottom = box->borderBottom();
-
-    // If all the borders are 0, then tell skia not to paint the border on the
-    // textfield.  FIXME: http://b/1210017 Figure out how to get Windows to not
-    // draw individual borders and then pass that to skia so we can avoid
-    // drawing any borders that are set to 0. For non-zero borders, we draw the
-    // border, but webkit just draws over it.
-    bool drawEdges = !(!borderRight && !borderLeft && !borderTop && !borderBottom);
-
-    paintTextFieldInternal(o, i, r, drawEdges);
-    return paintMenuListButton(o, i, r);
-}
-
-bool RenderThemeChromiumWin::paintMenuListButton(RenderObject* o, const PaintInfo& i, const IntRect& r)
-{
-    if (!o->isBox())
-        return false;
-
-    const RenderBox* box = toRenderBox(o);
-    // Take padding and border into account.  If the MenuList is smaller than
-    // the size of a button, make sure to shrink it appropriately and not put
-    // its x position to the left of the menulist.
-    const int buttonWidth = menuListButtonWidth();
-    int spacingLeft = box->borderLeft() + box->paddingLeft();
-    int spacingRight = box->borderRight() + box->paddingRight();
-    int spacingTop = box->borderTop() + box->paddingTop();
-    int spacingBottom = box->borderBottom() + box->paddingBottom();
-
-    int buttonX;
-    if (r.maxX() - r.x() < buttonWidth)
-        buttonX = r.x();
-    else
-        buttonX = o->style()->direction() == LTR ? r.maxX() - spacingRight - buttonWidth : r.x() + spacingLeft;
-
-    // Compute the rectangle of the button in the destination image.
-    IntRect rect(buttonX,
-                 r.y() + spacingTop,
-                 std::min(buttonWidth, r.maxX() - r.x()),
-                 r.height() - (spacingTop + spacingBottom));
-
-    // Get the correct theme data for a textfield and paint the menu.
-    ThemePainter painter(i.context, rect);
-    blink::WebCanvas* canvas = painter.context()->canvas();
-    blink::Platform::current()->themeEngine()->paintMenuList(canvas, CP_DROPDOWNBUTTON, determineState(o), determineClassicState(o), blink::WebRect(painter.drawRect()));
-    return false;
-}
-
-double RenderThemeChromiumWin::caretBlinkIntervalInternal() const
-{
-    // This involves a system call, so we cache the result.
-    static double blinkInterval = querySystemBlinkInterval(RenderTheme::caretBlinkInterval());
-    return blinkInterval;
-}
-
-unsigned RenderThemeChromiumWin::determineState(RenderObject* o, ControlSubPart subPart)
-{
-    unsigned result = TS_NORMAL;
-    ControlPart appearance = o->style()->appearance();
-    if (!isEnabled(o))
-        result = TS_DISABLED;
-    else if (isReadOnlyControl(o))
-        result = (appearance == TextFieldPart || appearance == TextAreaPart || appearance == SearchFieldPart) ? ETS_READONLY : TS_DISABLED;
-    // Active overrides hover and focused.
-    else if (isPressed(o) && (subPart == SpinButtonUp) == isSpinUpButtonPartPressed(o))
-        result = TS_PRESSED;
-    else if (supportsFocus(appearance) && isFocused(o))
-        result = ETS_FOCUSED;
-    else if (isHovered(o) && (subPart == SpinButtonUp) == isSpinUpButtonPartHovered(o))
-        result = TS_HOT;
-
-    // CBS_UNCHECKED*: 1-4
-    // CBS_CHECKED*: 5-8
-    // CBS_MIXED*: 9-12
-    if (isIndeterminate(o))
-        result += 8;
-    else if (isChecked(o))
-        result += 4;
-    return result;
-}
-
-unsigned RenderThemeChromiumWin::determineSliderThumbState(RenderObject* o)
-{
-    unsigned result = TUS_NORMAL;
-    if (!isEnabled(o))
-        result = TUS_DISABLED;
-    else if (supportsFocus(o->style()->appearance()) && isFocused(o))
-        result = TUS_FOCUSED;
-    else if (isPressed(o))
-        result = TUS_PRESSED;
-    else if (isHovered(o))
-        result = TUS_HOT;
-    return result;
-}
-
-unsigned RenderThemeChromiumWin::determineClassicState(RenderObject* o, ControlSubPart subPart)
-{
-    unsigned result = 0;
-
-    ControlPart part = o->style()->appearance();
-
-    // Sliders are always in the normal state.
-    if (part == SliderHorizontalPart || part == SliderVerticalPart)
-        return result;
-
-    // So are readonly text fields.
-    if (isReadOnlyControl(o) && (part == TextFieldPart || part == TextAreaPart || part == SearchFieldPart))
-        return result;
-
-    if (part == SliderThumbHorizontalPart || part == SliderThumbVerticalPart) {
-        if (!isEnabled(o))
-            result = DFCS_INACTIVE;
-        else if (isPressed(o)) // Active supersedes hover
-            result = DFCS_PUSHED;
-        else if (isHovered(o))
-            result = DFCS_HOT;
-    } else {
-        if (!isEnabled(o) || isReadOnlyControl(o))
-            result = DFCS_INACTIVE;
-        // Active supersedes hover
-        else if (isPressed(o) && (subPart == SpinButtonUp) == isSpinUpButtonPartPressed(o))
-            result = DFCS_PUSHED;
-        else if (supportsFocus(part) && isFocused(o)) // So does focused
-            result = 0;
-        else if (isHovered(o) && (subPart == SpinButtonUp) == isSpinUpButtonPartHovered(o))
-            result = DFCS_HOT;
-        // Classic theme can't represent indeterminate states. Use unchecked appearance.
-        if (isChecked(o) && !isIndeterminate(o))
-            result |= DFCS_CHECKED;
-    }
-    return result;
-}
-
-ThemeData RenderThemeChromiumWin::getThemeData(RenderObject* o, ControlSubPart subPart)
-{
-    ThemeData result;
-    switch (o->style()->appearance()) {
-    case CheckboxPart:
-        result.m_part = BP_CHECKBOX;
-        result.m_state = determineState(o);
-        result.m_classicState = DFCS_BUTTONCHECK;
-        break;
-    case RadioPart:
-        result.m_part = BP_RADIOBUTTON;
-        result.m_state = determineState(o);
-        result.m_classicState = DFCS_BUTTONRADIO;
-        break;
-    case SquareButtonPart:
-    case PushButtonPart:
-    case ButtonPart:
-        result.m_part = BP_PUSHBUTTON;
-        result.m_state = determineState(o);
-        result.m_classicState = DFCS_BUTTONPUSH;
-        break;
-    case SliderHorizontalPart:
-        result.m_part = TKP_TRACK;
-        result.m_state = TRS_NORMAL;
-        break;
-    case SliderVerticalPart:
-        result.m_part = TKP_TRACKVERT;
-        result.m_state = TRVS_NORMAL;
-        break;
-    case SliderThumbHorizontalPart:
-        result.m_part = TKP_THUMBBOTTOM;
-        result.m_state = determineSliderThumbState(o);
-        break;
-    case SliderThumbVerticalPart:
-        result.m_part = TKP_THUMBVERT;
-        result.m_state = determineSliderThumbState(o);
-        break;
-    case ListboxPart:
-    case MenulistPart:
-    case MenulistButtonPart:
-    case SearchFieldPart:
-    case TextFieldPart:
-    case TextAreaPart:
-        result.m_part = EP_EDITTEXT;
-        result.m_state = determineState(o);
-        break;
-    case InnerSpinButtonPart:
-        result.m_part = subPart == SpinButtonUp ? SPNP_UP : SPNP_DOWN;
-        result.m_state = determineState(o, subPart);
-        result.m_classicState = subPart == SpinButtonUp ? DFCS_SCROLLUP : DFCS_SCROLLDOWN;
-        break;
-    }
-
-    result.m_classicState |= determineClassicState(o, subPart);
-
-    return result;
-}
-
-bool RenderThemeChromiumWin::paintTextFieldInternal(RenderObject* o,
-                                                    const PaintInfo& i,
-                                                    const IntRect& r,
-                                                    bool drawEdges)
-{
-    // Fallback to white if the specified color object is invalid.
-    Color backgroundColor(Color::white);
-    if (o->style()->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
-        backgroundColor = o->style()->visitedDependentColor(CSSPropertyBackgroundColor);
-
-    // If we have background-image, don't fill the content area to expose the
-    // parent's background. Also, we shouldn't fill the content area if the
-    // alpha of the color is 0. The API of Windows GDI ignores the alpha.
-    //
-    // Note that we should paint the content area white if we have neither the
-    // background color nor background image explicitly specified to keep the
-    // appearance of select element consistent with other browsers.
-    bool fillContentArea = !o->style()->hasBackgroundImage() && backgroundColor.alpha();
-
-    if (o->style()->hasBorderRadius()) {
-        // If the style has rounded borders, setup the context to clip the
-        // background (themed or filled) appropriately.
-        // FIXME: make sure we do the right thing if css background-clip is set.
-        i.context->save();
-        i.context->clipRoundedRect(o->style()->getRoundedBorderFor(r));
-    }
-    {
-        const ThemeData& themeData = getThemeData(o);
-        ThemePainter painter(i.context, r);
-        blink::WebCanvas* canvas = painter.context()->canvas();
-        blink::Platform::current()->themeEngine()->paintTextField(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()), backgroundColor.rgb(), fillContentArea, drawEdges);
-        // End of block commits the painter before restoring context.
-    }
-    if (o->style()->hasBorderRadius())
-        i.context->restore();
-    return false;
-}
-
-void RenderThemeChromiumWin::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const
-{
-    int width = ScrollbarTheme::theme()->scrollbarThickness();
-    style->setWidth(Length(width, Fixed));
-    style->setMinWidth(Length(width, Fixed));
-}
-
-bool RenderThemeChromiumWin::paintInnerSpinButton(RenderObject* object, const PaintInfo& info, const IntRect& rect)
-{
-    IntRect half = rect;
-
-    // Need explicit blocks to avoid to create multiple ThemePainter instances.
-    {
-        half.setHeight(rect.height() / 2);
-        const ThemeData& upThemeData = getThemeData(object, SpinButtonUp);
-        ThemePainter upPainter(info.context, half);
-        blink::WebCanvas* canvas = upPainter.context()->canvas();
-        blink::Platform::current()->themeEngine()->paintSpinButton(canvas, upThemeData.m_part, upThemeData.m_state, upThemeData.m_classicState, blink::WebRect(upPainter.drawRect()));
-    }
-
-    {
-        half.setY(rect.y() + rect.height() / 2);
-        const ThemeData& downThemeData = getThemeData(object, SpinButtonDown);
-        ThemePainter downPainter(info.context, half);
-        blink::WebCanvas* canvas = downPainter.context()->canvas();
-        blink::Platform::current()->themeEngine()->paintSpinButton(canvas, downThemeData.m_part, downThemeData.m_state, downThemeData.m_classicState, blink::WebRect(downPainter.drawRect()));
-    }
-    return false;
-}
-
-// MSDN says that update intervals for the bar is 30ms.
-// http://msdn.microsoft.com/en-us/library/bb760842(v=VS.85).aspx
-static const double progressAnimationFrameRate = 0.033;
-
-double RenderThemeChromiumWin::animationRepeatIntervalForProgressBar(RenderProgress*) const
-{
-    return progressAnimationFrameRate;
-}
-
-double RenderThemeChromiumWin::animationDurationForProgressBar(RenderProgress* renderProgress) const
-{
-    // On Chromium Windows port, animationProgress() and associated values aren't used.
-    // So here we can return arbitrary positive value.
-    return progressAnimationFrameRate;
-}
-
-bool RenderThemeChromiumWin::paintProgressBar(RenderObject* o, const PaintInfo& i, const IntRect& r)
-{
-    if (!o->isProgress())
-        return true;
-
-    RenderProgress* renderProgress = toRenderProgress(o);
-    // For indeterminate bar, valueRect is ignored and it is computed by the theme engine
-    // because the animation is a platform detail and WebKit doesn't need to know how.
-    IntRect valueRect = renderProgress->isDeterminate() ? determinateProgressValueRectFor(renderProgress, r) : IntRect(0, 0, 0, 0);
-    double animatedSeconds = renderProgress->animationStartTime() ?  WTF::currentTime() - renderProgress->animationStartTime() : 0;
-    ThemePainter painter(i.context, r);
-    DirectionFlippingScope scope(o, i, r);
-    blink::WebCanvas* canvas = painter.context()->canvas();
-    blink::Platform::current()->themeEngine()->paintProgressBar(canvas, blink::WebRect(r), blink::WebRect(valueRect), renderProgress->isDeterminate(), animatedSeconds);
-    return false;
-}
-
-bool RenderThemeChromiumWin::shouldOpenPickerWithF4Key() const
-{
-    return true;
-}
-
-bool RenderThemeChromiumWin::shouldUseFallbackTheme(RenderStyle* style) const
-{
-    ControlPart part = style->appearance();
-    if (part == CheckboxPart || part == RadioPart)
-        return style->effectiveZoom() != 1;
-    return false;
-}
-
-} // namespace WebCore
diff --git a/Source/core/rendering/RenderThemeChromiumWin.h b/Source/core/rendering/RenderThemeChromiumWin.h
deleted file mode 100644
index b44e44b..0000000
--- a/Source/core/rendering/RenderThemeChromiumWin.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * This file is part of the WebKit project.
- *
- * Copyright (C) 2006 Apple Computer, Inc.
- * Copyright (C) 2008, 2009 Google, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef RenderThemeChromiumWin_h
-#define RenderThemeChromiumWin_h
-
-#include "core/rendering/RenderThemeChromiumSkia.h"
-
-#if WIN32
-typedef void* HANDLE;
-typedef struct HINSTANCE__* HINSTANCE;
-typedef HINSTANCE HMODULE;
-#endif
-
-namespace WebCore {
-
-struct ThemeData {
-    ThemeData() : m_part(0), m_state(0), m_classicState(0) { }
-
-    unsigned m_part;
-    unsigned m_state;
-    unsigned m_classicState;
-};
-
-class RenderThemeChromiumWin : public RenderThemeChromiumSkia {
-public:
-    static PassRefPtr<RenderTheme> create();
-
-    // A method asking if the theme is able to draw the focus ring.
-    virtual bool supportsFocusRing(const RenderStyle*) const OVERRIDE;
-
-    // The platform selection color.
-    virtual Color platformActiveSelectionBackgroundColor() const OVERRIDE;
-    virtual Color platformInactiveSelectionBackgroundColor() const OVERRIDE;
-    virtual Color platformActiveSelectionForegroundColor() const OVERRIDE;
-    virtual Color platformInactiveSelectionForegroundColor() const OVERRIDE;
-    virtual Color platformActiveTextSearchHighlightColor() const OVERRIDE;
-    virtual Color platformInactiveTextSearchHighlightColor() const OVERRIDE;
-
-    virtual Color systemColor(CSSValueID) const OVERRIDE;
-
-    virtual IntSize sliderTickSize() const OVERRIDE;
-    virtual int sliderTickOffsetFromTrackCenter() const OVERRIDE;
-    virtual void adjustSliderThumbSize(RenderStyle*, Element*) const OVERRIDE;
-
-    // Various paint functions.
-    virtual bool paintCheckbox(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-    virtual bool paintRadio(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-    virtual bool paintButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-    virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-    virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-    virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-
-    // MenuList refers to an unstyled menulist (meaning a menulist without
-    // background-color or border set) and MenuListButton refers to a styled
-    // menulist (a menulist with background-color or border set).
-    virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-    virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-
-    virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const OVERRIDE;
-    virtual bool paintInnerSpinButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-
-    virtual double animationRepeatIntervalForProgressBar(RenderProgress*) const OVERRIDE;
-    virtual double animationDurationForProgressBar(RenderProgress*) const OVERRIDE;
-    virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
-
-    virtual bool shouldOpenPickerWithF4Key() const OVERRIDE;
-
-protected:
-    virtual double caretBlinkIntervalInternal() const OVERRIDE;
-    virtual bool shouldUseFallbackTheme(RenderStyle*) const OVERRIDE;
-
-private:
-    enum ControlSubPart {
-        None,
-        SpinButtonDown,
-        SpinButtonUp,
-    };
-
-    RenderThemeChromiumWin() { }
-    virtual ~RenderThemeChromiumWin() { }
-
-    unsigned determineState(RenderObject*, ControlSubPart = None);
-    unsigned determineSliderThumbState(RenderObject*);
-    unsigned determineClassicState(RenderObject*, ControlSubPart = None);
-
-    ThemeData getThemeData(RenderObject*, ControlSubPart = None);
-
-    bool paintTextFieldInternal(RenderObject*, const PaintInfo&, const IntRect&, bool);
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/rendering/RenderTreeAsText.cpp b/Source/core/rendering/RenderTreeAsText.cpp
index e95412e..6a639ed 100644
--- a/Source/core/rendering/RenderTreeAsText.cpp
+++ b/Source/core/rendering/RenderTreeAsText.cpp
@@ -40,13 +40,12 @@
 #include "core/rendering/RenderBR.h"
 #include "core/rendering/RenderDetailsMarker.h"
 #include "core/rendering/RenderFileUploadControl.h"
+#include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderListItem.h"
 #include "core/rendering/RenderListMarker.h"
-#include "core/rendering/RenderNamedFlowThread.h"
 #include "core/rendering/RenderPart.h"
-#include "core/rendering/RenderRegion.h"
 #include "core/rendering/RenderTableCell.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
@@ -227,17 +226,17 @@
             // Do not dump invalid or transparent backgrounds, since that is the default.
             Color backgroundColor = o.resolveColor(CSSPropertyBackgroundColor);
             if (o.parent()->resolveColor(CSSPropertyBackgroundColor) != backgroundColor
-                && backgroundColor.isValid() && backgroundColor.rgb())
+                && backgroundColor.rgb())
                 ts << " [bgcolor=" << backgroundColor.nameForRenderTreeAsText() << "]";
 
             Color textFillColor = o.resolveColor(CSSPropertyWebkitTextFillColor);
             if (o.parent()->resolveColor(CSSPropertyWebkitTextFillColor) != textFillColor
-                && textFillColor.isValid() && textFillColor != color && textFillColor.rgb())
+                && textFillColor != color && textFillColor.rgb())
                 ts << " [textFillColor=" << textFillColor.nameForRenderTreeAsText() << "]";
 
             Color textStrokeColor = o.resolveColor(CSSPropertyWebkitTextStrokeColor);
             if (o.parent()->resolveColor(CSSPropertyWebkitTextStrokeColor) != textStrokeColor
-                && textStrokeColor.isValid() && textStrokeColor != color && textStrokeColor.rgb())
+                && textStrokeColor != color && textStrokeColor.rgb())
                 ts << " [textStrokeColor=" << textStrokeColor.nameForRenderTreeAsText() << "]";
 
             if (o.parent()->style()->textStrokeWidth() != o.style()->textStrokeWidth() && o.style()->textStrokeWidth() > 0)
@@ -513,6 +512,9 @@
 
     writeIndent(ts, indent);
 
+    if (l.renderer()->style()->visibility() == HIDDEN)
+        ts << "hidden ";
+
     ts << "layer ";
 
     if (behavior & RenderAsTextShowAddresses)
@@ -565,91 +567,6 @@
         write(ts, *l.renderer(), indent + 1, behavior);
 }
 
-static void writeRenderRegionList(const RenderRegionList& flowThreadRegionList, TextStream& ts, int indent)
-{
-    for (RenderRegionList::const_iterator itRR = flowThreadRegionList.begin(); itRR != flowThreadRegionList.end(); ++itRR) {
-        const RenderRegion* renderRegion = *itRR;
-
-        writeIndent(ts, indent);
-        ts << renderRegion->renderName();
-
-        Node* generatingNodeForRegion = renderRegion->generatingNodeForRegion();
-        if (generatingNodeForRegion) {
-            if (renderRegion->hasCustomRegionStyle())
-                ts << " region style: 1";
-            if (renderRegion->hasAutoLogicalHeight())
-                ts << " hasAutoLogicalHeight";
-
-            bool isRenderNamedFlowFragment = renderRegion->isRenderNamedFlowFragment();
-            if (isRenderNamedFlowFragment)
-                ts << " (anonymous child of";
-
-            StringBuilder tagName;
-            tagName.append(generatingNodeForRegion->nodeName());
-
-            Node* nodeForRegion = renderRegion->nodeForRegion();
-            if (nodeForRegion->isPseudoElement()) {
-                if (nodeForRegion->isBeforePseudoElement())
-                    tagName.append("::before");
-                else if (nodeForRegion->isAfterPseudoElement())
-                    tagName.append("::after");
-            }
-
-            ts << " {" << tagName.toString() << "}";
-
-            if (generatingNodeForRegion->isElementNode() && generatingNodeForRegion->hasID()) {
-                Element* element = toElement(generatingNodeForRegion);
-                ts << " #" << element->idForStyleResolution();
-            }
-
-            if (isRenderNamedFlowFragment)
-                ts << ")";
-        }
-
-        if (!renderRegion->isValid())
-            ts << " invalid";
-
-        ts << "\n";
-    }
-}
-
-static void writeRenderNamedFlowThreads(TextStream& ts, RenderView* renderView, const RenderLayer* rootLayer,
-                        const LayoutRect& paintRect, int indent, RenderAsTextBehavior behavior)
-{
-    if (!renderView->hasRenderNamedFlowThreads())
-        return;
-
-    const RenderNamedFlowThreadList* list = renderView->flowThreadController()->renderNamedFlowThreadList();
-
-    writeIndent(ts, indent);
-    ts << "Named flows\n";
-
-    for (RenderNamedFlowThreadList::const_iterator iter = list->begin(); iter != list->end(); ++iter) {
-        const RenderNamedFlowThread* renderFlowThread = *iter;
-
-        writeIndent(ts, indent + 1);
-        ts << "Named flow '" << renderFlowThread->flowThreadName() << "'\n";
-
-        RenderLayer* layer = renderFlowThread->layer();
-        RenderTreeAsText::writeLayers(ts, rootLayer, layer, paintRect, indent + 2, behavior);
-
-        // Display the valid and invalid render regions attached to this flow thread.
-        const RenderRegionList& validRegionsList = renderFlowThread->renderRegionList();
-        if (!validRegionsList.isEmpty()) {
-            writeIndent(ts, indent + 2);
-            ts << "Regions for named flow '" << renderFlowThread->flowThreadName() << "'\n";
-            writeRenderRegionList(validRegionsList, ts, indent + 3);
-        }
-
-        const RenderRegionList& invalidRegionsList = renderFlowThread->invalidRenderRegionList();
-        if (!invalidRegionsList.isEmpty()) {
-            writeIndent(ts, indent + 2);
-            ts << "Invalid regions for named flow '" << renderFlowThread->flowThreadName() << "'\n";
-            writeRenderRegionList(invalidRegionsList, ts, indent + 3);
-        }
-    }
-}
-
 void RenderTreeAsText::writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLayer* layer,
                         const LayoutRect& paintRect, int indent, RenderAsTextBehavior behavior)
 {
@@ -664,7 +581,7 @@
     // Calculate the clip rects we should use.
     LayoutRect layerBounds;
     ClipRect damageRect, clipRectToApply, outlineRect;
-    layer->calculateRects(ClipRectsContext(rootLayer, 0, TemporaryClipRects), paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);
+    layer->clipper().calculateRects(ClipRectsContext(rootLayer, TemporaryClipRects), paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);
 
     // Ensure our lists are up-to-date.
     layer->stackingNode()->updateLayerListsIfNeeded();
@@ -711,13 +628,6 @@
         for (unsigned i = 0; i != posList->size(); ++i)
             writeLayers(ts, rootLayer, posList->at(i)->layer(), paintDirtyRect, currIndent, behavior);
     }
-
-    // Altough the RenderFlowThread requires a layer, it is not collected by its parent,
-    // so we have to treat it as a special case.
-    if (layer->renderer()->isRenderView()) {
-        RenderView* renderView = toRenderView(layer->renderer());
-        writeRenderNamedFlowThreads(ts, renderView, rootLayer, paintDirtyRect, indent, behavior);
-    }
 }
 
 static String nodePosition(Node* node)
diff --git a/Source/core/rendering/RenderVideo.cpp b/Source/core/rendering/RenderVideo.cpp
index b498f90..5737494 100644
--- a/Source/core/rendering/RenderVideo.cpp
+++ b/Source/core/rendering/RenderVideo.cpp
@@ -32,7 +32,6 @@
 #include "core/html/HTMLVideoElement.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Page.h"
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderFullScreen.h"
@@ -193,7 +192,6 @@
 
 HTMLVideoElement* RenderVideo::videoElement() const
 {
-    ASSERT(isHTMLVideoElement(node()));
     return toHTMLVideoElement(node());
 }
 
diff --git a/Source/core/rendering/RenderVideo.h b/Source/core/rendering/RenderVideo.h
index 40a400d..81f1d68 100644
--- a/Source/core/rendering/RenderVideo.h
+++ b/Source/core/rendering/RenderVideo.h
@@ -44,35 +44,35 @@
 
     bool supportsAcceleratedRendering() const;
 
-    virtual bool shouldDisplayVideo() const;
+    bool shouldDisplayVideo() const;
 
 private:
-    virtual void updateFromElement();
+    virtual void updateFromElement() OVERRIDE;
     inline HTMLVideoElement* videoElement() const;
 
-    virtual void intrinsicSizeChanged();
+    virtual void intrinsicSizeChanged() OVERRIDE;
     LayoutSize calculateIntrinsicSize();
     void updateIntrinsicSize();
 
-    virtual void imageChanged(WrappedImagePtr, const IntRect*);
+    virtual void imageChanged(WrappedImagePtr, const IntRect*) OVERRIDE;
 
-    virtual const char* renderName() const { return "RenderVideo"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderVideo"; }
 
-    virtual bool requiresLayer() const { return true; }
-    virtual bool isVideo() const { return true; }
+    virtual LayerType layerTypeRequired() const OVERRIDE { return NormalLayer; }
+    virtual bool isVideo() const OVERRIDE { return true; }
 
-    virtual void paintReplaced(PaintInfo&, const LayoutPoint&);
+    virtual void paintReplaced(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
     virtual LayoutUnit computeReplacedLogicalWidth(ShouldComputePreferred  = ComputeActual) const OVERRIDE;
-    virtual LayoutUnit computeReplacedLogicalHeight() const;
+    virtual LayoutUnit computeReplacedLogicalHeight() const OVERRIDE;
     virtual LayoutUnit minimumReplacedHeight() const OVERRIDE;
 
-    virtual LayoutUnit offsetLeft() const;
-    virtual LayoutUnit offsetTop() const;
-    virtual LayoutUnit offsetWidth() const;
-    virtual LayoutUnit offsetHeight() const;
+    virtual LayoutUnit offsetLeft() const OVERRIDE;
+    virtual LayoutUnit offsetTop() const OVERRIDE;
+    virtual LayoutUnit offsetWidth() const OVERRIDE;
+    virtual LayoutUnit offsetHeight() const OVERRIDE;
 
     void updatePlayer();
 
diff --git a/Source/core/rendering/RenderView.cpp b/Source/core/rendering/RenderView.cpp
index 0595569..c101b70 100644
--- a/Source/core/rendering/RenderView.cpp
+++ b/Source/core/rendering/RenderView.cpp
@@ -40,12 +40,10 @@
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderSelectionInfo.h"
-#include "core/rendering/RenderWidget.h"
 #include "core/svg/SVGDocumentExtensions.h"
 #include "platform/geometry/FloatQuad.h"
 #include "platform/geometry/TransformState.h"
 #include "platform/graphics/GraphicsContext.h"
-#include "platform/graphics/filters/custom/CustomFilterGlobalContext.h"
 
 namespace WebCore {
 
@@ -111,7 +109,7 @@
     // If we have columns, then the available logical height is reduced to the column height.
     if (hasColumns())
         return columnInfo()->columnHeight();
-    return RenderBlock::availableLogicalHeight(heightType);
+    return RenderBlockFlow::availableLogicalHeight(heightType);
 }
 
 bool RenderView::isChildAllowed(RenderObject* child, RenderStyle*) const
@@ -119,8 +117,9 @@
     return child->isBox();
 }
 
-static bool dialogNeedsCentering(const RenderStyle* style)
+static bool canCenterDialog(const RenderStyle* style)
 {
+    // FIXME: We must center for FixedPosition as well.
     return style->position() == AbsolutePosition && style->hasAutoTopAndBottom();
 }
 
@@ -130,12 +129,13 @@
     if (dialog->centeringMode() == HTMLDialogElement::NotCentered)
         return;
     if (dialog->centeringMode() == HTMLDialogElement::Centered) {
-        if (dialogNeedsCentering(box->style()))
+        if (canCenterDialog(box->style()))
             box->setY(dialog->centeredPosition());
         return;
     }
 
-    if (!dialogNeedsCentering(box->style())) {
+    ASSERT(dialog->centeringMode() == HTMLDialogElement::NeedsCentering);
+    if (!canCenterDialog(box->style())) {
         dialog->setNotCentered();
         return;
     }
@@ -167,7 +167,7 @@
     ASSERT(needsLayout());
 
     LayoutRectRecorder recorder(*this);
-    RenderBlock::layout();
+    RenderBlockFlow::layout();
 
     if (RuntimeEnabledFeatures::dialogElementEnabled())
         positionDialogs();
@@ -175,9 +175,6 @@
     if (m_frameView->partialLayout().isStopping())
         return;
 
-    if (hasRenderNamedFlowThreads())
-        flowThreadController()->layoutRenderNamedFlowThreads();
-
 #ifndef NDEBUG
     checkLayoutState(state);
 #endif
@@ -186,117 +183,21 @@
 #ifndef NDEBUG
 void RenderView::checkLayoutState(const LayoutState& state)
 {
-    ASSERT(layoutDeltaMatches(LayoutSize()));
+    if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+        ASSERT(layoutDeltaMatches(LayoutSize()));
+    }
     ASSERT(!m_layoutStateDisableCount);
     ASSERT(m_layoutState == &state);
 }
 #endif
 
-static RenderBox* enclosingSeamlessRenderer(const Document& doc)
+void RenderView::initializeLayoutState(LayoutState& state)
 {
-    Element* ownerElement = doc.seamlessParentIFrame();
-    if (!ownerElement)
-        return 0;
-    return ownerElement->renderBox();
-}
-
-void RenderView::addChild(RenderObject* newChild, RenderObject* beforeChild)
-{
-    // Seamless iframes are considered part of an enclosing render flow thread from the parent document. This is necessary for them to look
-    // up regions in the parent document during layout.
-    if (newChild && !newChild->isRenderFlowThread()) {
-        RenderBox* seamlessBox = enclosingSeamlessRenderer(document());
-        if (seamlessBox && seamlessBox->flowThreadContainingBlock())
-            newChild->setFlowThreadState(seamlessBox->flowThreadState());
-    }
-    RenderBlock::addChild(newChild, beforeChild);
-}
-
-bool RenderView::initializeLayoutState(LayoutState& state)
-{
-    bool isSeamlessAncestorInFlowThread = false;
-
     // FIXME: May be better to push a clip and avoid issuing offscreen repaints.
     state.m_clipped = false;
-
-    // Check the writing mode of the seamless ancestor. It has to match our document's writing mode, or we won't inherit any
-    // pagination information.
-    RenderBox* seamlessAncestor = enclosingSeamlessRenderer(document());
-    LayoutState* seamlessLayoutState = seamlessAncestor ? seamlessAncestor->view()->layoutState() : 0;
-    bool shouldInheritPagination = seamlessLayoutState && !m_pageLogicalHeight && seamlessAncestor->style()->writingMode() == style()->writingMode();
-
-    state.m_pageLogicalHeight = shouldInheritPagination ? seamlessLayoutState->m_pageLogicalHeight : m_pageLogicalHeight;
-    state.m_pageLogicalHeightChanged = shouldInheritPagination ? seamlessLayoutState->m_pageLogicalHeightChanged : m_pageLogicalHeightChanged;
+    state.m_pageLogicalHeight = m_pageLogicalHeight;
+    state.m_pageLogicalHeightChanged = m_pageLogicalHeightChanged;
     state.m_isPaginated = state.m_pageLogicalHeight;
-    if (state.m_isPaginated && shouldInheritPagination) {
-        // Set up the correct pagination offset. We can use a negative offset in order to push the top of the RenderView into its correct place
-        // on a page. We can take the iframe's offset from the logical top of the first page and make the negative into the pagination offset within the child
-        // view.
-        bool isFlipped = seamlessAncestor->style()->isFlippedBlocksWritingMode();
-        LayoutSize layoutOffset = seamlessLayoutState->layoutOffset();
-        LayoutSize iFrameOffset(layoutOffset.width() + seamlessAncestor->x() + (!isFlipped ? seamlessAncestor->borderLeft() + seamlessAncestor->paddingLeft() :
-            seamlessAncestor->borderRight() + seamlessAncestor->paddingRight()),
-            layoutOffset.height() + seamlessAncestor->y() + (!isFlipped ? seamlessAncestor->borderTop() + seamlessAncestor->paddingTop() :
-            seamlessAncestor->borderBottom() + seamlessAncestor->paddingBottom()));
-
-        LayoutSize offsetDelta = seamlessLayoutState->m_pageOffset - iFrameOffset;
-        state.m_pageOffset = offsetDelta;
-
-        // Set the current render flow thread to point to our ancestor. This will allow the seamless document to locate the correct
-        // regions when doing a layout.
-        if (seamlessAncestor->flowThreadContainingBlock()) {
-            flowThreadController()->setCurrentRenderFlowThread(seamlessAncestor->view()->flowThreadController()->currentRenderFlowThread());
-            isSeamlessAncestorInFlowThread = true;
-        }
-    }
-
-    // FIXME: We need to make line grids and exclusions work with seamless iframes as well here. Basically all layout state information needs
-    // to propagate here and not just pagination information.
-    return isSeamlessAncestorInFlowThread;
-}
-
-// The algorithm below assumes this is a full layout. In case there are previously computed values for regions, supplemental steps are taken
-// to ensure the results are the same as those obtained from a full layout (i.e. the auto-height regions from all the flows are marked as needing
-// layout).
-// 1. The flows are laid out from the outer flow to the inner flow. This successfully computes the outer non-auto-height regions size so the
-// inner flows have the necessary information to correctly fragment the content.
-// 2. The flows are laid out from the inner flow to the outer flow. After an inner flow is laid out it goes into the constrained layout phase
-// and marks the auto-height regions they need layout. This means the outer flows will relayout if they depend on regions with auto-height regions
-// belonging to inner flows. This step will correctly set the computedAutoHeight for the auto-height regions. It's possible for non-auto-height
-// regions to relayout if they depend on auto-height regions. This will invalidate the inner flow threads and mark them as needing layout.
-// 3. The last step is to do one last layout if there are pathological dependencies between non-auto-height regions and auto-height regions
-// as detected in the previous step.
-void RenderView::layoutContentInAutoLogicalHeightRegions(const LayoutState& state)
-{
-    if (!m_frameView->partialLayout().isStopping()) {
-        // Disable partial layout for any two-pass layout algorithm.
-        m_frameView->partialLayout().reset();
-    }
-
-    // We need to invalidate all the flows with auto-height regions if one such flow needs layout.
-    // If none is found we do a layout a check back again afterwards.
-    if (!flowThreadController()->updateFlowThreadsNeedingLayout()) {
-        // Do a first layout of the content. In some cases more layouts are not needed (e.g. only flows with non-auto-height regions have changed).
-        layoutContent(state);
-
-        // If we find no named flow needing a two step layout after the first layout, exit early.
-        // Otherwise, initiate the two step layout algorithm and recompute all the flows.
-        if (!flowThreadController()->updateFlowThreadsNeedingTwoStepLayout())
-            return;
-    }
-
-    // Layout to recompute all the named flows with auto-height regions.
-    layoutContent(state);
-
-    // Propagate the computed auto-height values upwards.
-    // Non-auto-height regions may invalidate the flow thread because they depended on auto-height regions, but that's ok.
-    flowThreadController()->updateFlowThreadsIntoConstrainedPhase();
-
-    // Do one last layout that should update the auto-height regions found in the main flow
-    // and solve pathological dependencies between regions (e.g. a non-auto-height region depending
-    // on an auto-height one).
-    if (needsLayout())
-        layoutContent(state);
 }
 
 void RenderView::layout()
@@ -320,10 +221,7 @@
             if ((child->isBox() && toRenderBox(child)->hasRelativeLogicalHeight())
                     || child->style()->logicalHeight().isPercent()
                     || child->style()->logicalMinHeight().isPercent()
-                    || child->style()->logicalMaxHeight().isPercent()
-                    || child->style()->logicalHeight().isViewportPercentage()
-                    || child->style()->logicalMinHeight().isViewportPercentage()
-                    || child->style()->logicalMaxHeight().isViewportPercentage())
+                    || child->style()->logicalMaxHeight().isPercent())
                 layoutScope.setChildNeedsLayout(child);
         }
 
@@ -336,15 +234,12 @@
         return;
 
     LayoutState state;
-    bool isSeamlessAncestorInFlowThread = initializeLayoutState(state);
+    initializeLayoutState(state);
 
     m_pageLogicalHeightChanged = false;
     m_layoutState = &state;
 
-    if (checkTwoPassLayoutForAutoHeightRegions())
-        layoutContentInAutoLogicalHeightRegions(state);
-    else
-        layoutContent(state);
+    layoutContent(state);
 
     if (m_frameView->partialLayout().isStopping()) {
         m_layoutState = 0;
@@ -356,9 +251,6 @@
 #endif
     m_layoutState = 0;
     clearNeedsLayout();
-
-    if (isSeamlessAncestorInFlowThread)
-        flowThreadController()->setCurrentRenderFlowThread(0);
 }
 
 void RenderView::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
@@ -444,32 +336,6 @@
     rects.append(LayoutRect(LayoutPoint::zero(), frameView()->contentsSize()));
 }
 
-bool RenderView::requiresColumns(int desiredColumnCount) const
-{
-    if (m_frameView)
-        return m_frameView->pagination().mode != Pagination::Unpaginated;
-
-    return RenderBlock::requiresColumns(desiredColumnCount);
-}
-
-void RenderView::calcColumnWidth()
-{
-    int columnWidth = contentLogicalWidth();
-    if (m_frameView && style()->hasInlineColumnAxis()) {
-        if (int pageLength = m_frameView->pagination().pageLength)
-            columnWidth = pageLength;
-    }
-    setDesiredColumnCountAndWidth(1, columnWidth);
-}
-
-ColumnInfo::PaginationUnit RenderView::paginationUnit() const
-{
-    if (m_frameView)
-        return m_frameView->pagination().behavesLikeColumns ? ColumnInfo::Column : ColumnInfo::Page;
-
-    return ColumnInfo::Page;
-}
-
 void RenderView::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     // If we ever require layout but receive a paint anyway, something has gone horribly wrong.
@@ -480,33 +346,41 @@
     ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
 
     // This avoids painting garbage between columns if there is a column gap.
-    if (m_frameView && m_frameView->pagination().mode != Pagination::Unpaginated)
+    if (m_frameView && style()->isOverflowPaged())
         paintInfo.context->fillRect(paintInfo.rect, m_frameView->baseBackgroundColor());
 
     paintObject(paintInfo, paintOffset);
 }
 
-static inline bool rendererObscuresBackground(RenderObject* rootObject)
+static inline bool rendererObscuresBackground(RenderBox* rootBox)
 {
-    if (!rootObject)
-        return false;
-
-    RenderStyle* style = rootObject->style();
+    ASSERT(rootBox);
+    RenderStyle* style = rootBox->style();
     if (style->visibility() != VISIBLE
         || style->opacity() != 1
         || style->hasTransform())
         return false;
 
-    if (rootObject->compositingState() == PaintsIntoOwnBacking)
+    if (rootBox->compositingState() == PaintsIntoOwnBacking)
         return false;
 
-    const RenderObject* rootRenderer = rootObject->rendererForRootBackground();
+    const RenderObject* rootRenderer = rootBox->rendererForRootBackground();
     if (rootRenderer->style()->backgroundClip() == TextFillBox)
         return false;
 
     return true;
 }
 
+bool RenderView::rootFillsViewportBackground(RenderBox* rootBox) const
+{
+    ASSERT(rootBox);
+    // CSS Boxes always fill the viewport background (see paintRootBoxFillLayers)
+    if (!rootBox->isSVG())
+        return true;
+
+    return rootBox->frameRect().contains(frameRect());
+}
+
 void RenderView::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint&)
 {
     // Check to see if we are enclosed by a layer that requires complex painting rules.  If so, we cannot blit
@@ -534,21 +408,13 @@
     if (paintInfo.skipRootBackground())
         return;
 
-    bool rootFillsViewport = false;
-    bool rootObscuresBackground = false;
+    bool shouldPaintBackground = true;
     Node* documentElement = document().documentElement();
-    if (RenderObject* rootRenderer = documentElement ? documentElement->renderer() : 0) {
-        // The document element's renderer is currently forced to be a block, but may not always be.
-        RenderBox* rootBox = rootRenderer->isBox() ? toRenderBox(rootRenderer) : 0;
-        rootFillsViewport = rootBox && !rootBox->x() && !rootBox->y() && rootBox->width() >= width() && rootBox->height() >= height();
-        rootObscuresBackground = rendererObscuresBackground(rootRenderer);
-    }
-
-    Page* page = document().page();
-    float pageScaleFactor = page ? page->pageScaleFactor() : 1;
+    if (RenderBox* rootBox = documentElement ? toRenderBox(documentElement->renderer()) : 0)
+        shouldPaintBackground = !rootFillsViewportBackground(rootBox) || !rendererObscuresBackground(rootBox);
 
     // If painting will entirely fill the view, no need to fill the background.
-    if (rootFillsViewport && rootObscuresBackground && pageScaleFactor >= 1)
+    if (!shouldPaintBackground)
         return;
 
     // This code typically only executes if the root element's visibility has been set to hidden,
@@ -608,6 +474,9 @@
 
     repaintViewRectangle(ur);
 
+    // FIXME: We don't actually know how to hit these ASSERTS.
+    DisableCompositingQueryAsserts disabler;
+
     if (compositor()->inCompositingMode()) {
         IntRect repaintRect = pixelSnappedIntRect(ur);
         compositor()->repaintCompositedLayers(&repaintRect);
@@ -618,6 +487,9 @@
 {
     repaint();
 
+    // The only way we know how to hit these ASSERTS below this point is via the Chromium OS login screen.
+    DisableCompositingQueryAsserts disabler;
+
     if (compositor()->inCompositingMode())
         compositor()->repaintCompositedLayers();
 }
@@ -682,7 +554,7 @@
             selectedObjects.set(os, adoptPtr(new RenderSelectionInfo(os, clipToVisibleContent)));
             RenderBlock* cb = os->containingBlock();
             while (cb && !cb->isRenderView()) {
-                OwnPtr<RenderSelectionInfo>& blockInfo = selectedObjects.add(cb, nullptr).iterator->value;
+                OwnPtr<RenderSelectionInfo>& blockInfo = selectedObjects.add(cb, nullptr).storedValue->value;
                 if (blockInfo)
                     break;
                 blockInfo = adoptPtr(new RenderSelectionInfo(cb, clipToVisibleContent));
@@ -810,7 +682,7 @@
             if (blockRepaintMode == RepaintNewXOROld) {
                 RenderBlock* cb = os->containingBlock();
                 while (cb && !cb->isRenderView()) {
-                    OwnPtr<RenderBlockSelectionInfo>& blockInfo = oldSelectedBlocks.add(cb, nullptr).iterator->value;
+                    OwnPtr<RenderBlockSelectionInfo>& blockInfo = oldSelectedBlocks.add(cb, nullptr).storedValue->value;
                     if (blockInfo)
                         break;
                     blockInfo = adoptPtr(new RenderBlockSelectionInfo(cb));
@@ -865,7 +737,7 @@
             newSelectedObjects.set(o, adoptPtr(new RenderSelectionInfo(o, true)));
             RenderBlock* cb = o->containingBlock();
             while (cb && !cb->isRenderView()) {
-                OwnPtr<RenderBlockSelectionInfo>& blockInfo = newSelectedBlocks.add(cb, nullptr).iterator->value;
+                OwnPtr<RenderBlockSelectionInfo>& blockInfo = newSelectedBlocks.add(cb, nullptr).storedValue->value;
                 if (blockInfo)
                     break;
                 blockInfo = adoptPtr(new RenderBlockSelectionInfo(cb));
@@ -879,8 +751,6 @@
     if (!m_frameView || blockRepaintMode == RepaintNothing)
         return;
 
-    FrameView::DeferredRepaintScope deferRepaints(*m_frameView);
-
     // Have any of the old selected objects changed compared to the new selection?
     for (SelectedObjectMap::iterator i = oldSelectedObjects.begin(); i != oldObjectsEnd; ++i) {
         RenderObject* obj = i->key;
@@ -950,57 +820,6 @@
     return m_frameView->frame().shouldUsePrintingLayout();
 }
 
-size_t RenderView::getRetainedWidgets(Vector<RenderWidget*>& renderWidgets)
-{
-    size_t size = m_widgets.size();
-
-    renderWidgets.reserveCapacity(size);
-
-    RenderWidgetSet::const_iterator end = m_widgets.end();
-    for (RenderWidgetSet::const_iterator it = m_widgets.begin(); it != end; ++it) {
-        renderWidgets.uncheckedAppend(*it);
-        (*it)->ref();
-    }
-
-    return size;
-}
-
-void RenderView::releaseWidgets(Vector<RenderWidget*>& renderWidgets)
-{
-    size_t size = renderWidgets.size();
-
-    for (size_t i = 0; i < size; ++i)
-        renderWidgets[i]->deref();
-}
-
-void RenderView::updateWidgetPositions()
-{
-    // updateWidgetPosition() can possibly cause layout to be re-entered (via plug-ins running
-    // scripts in response to NPP_SetWindow, for example), so we need to keep the Widgets
-    // alive during enumeration.
-
-    Vector<RenderWidget*> renderWidgets;
-    size_t size = getRetainedWidgets(renderWidgets);
-
-    for (size_t i = 0; i < size; ++i)
-        renderWidgets[i]->updateWidgetPosition();
-
-    for (size_t i = 0; i < size; ++i)
-        renderWidgets[i]->widgetPositionsUpdated();
-
-    releaseWidgets(renderWidgets);
-}
-
-void RenderView::addWidget(RenderWidget* o)
-{
-    m_widgets.add(o);
-}
-
-void RenderView::removeWidget(RenderWidget* o)
-{
-    m_widgets.remove(o);
-}
-
 LayoutRect RenderView::viewRect() const
 {
     if (shouldUsePrintingLayout())
@@ -1067,16 +886,9 @@
     return width;
 }
 
-int RenderView::viewLogicalHeight(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion) const
+int RenderView::viewLogicalHeight() const
 {
-    int height = style()->isHorizontalWritingMode() ? viewHeight(scrollbarInclusion) : viewWidth(scrollbarInclusion);
-
-    if (hasColumns() && !style()->hasInlineColumnAxis()) {
-        if (int pageLength = m_frameView->pagination().pageLength)
-            height = pageLength;
-    }
-
-    return height;
+    return style()->isHorizontalWritingMode() ? viewHeight(ScrollableArea::ExcludeScrollbars) : viewWidth(ScrollableArea::ExcludeScrollbars);
 }
 
 float RenderView::zoomFactor() const
@@ -1141,34 +953,10 @@
         m_compositor->setIsInWindow(isInWindow);
 }
 
-CustomFilterGlobalContext* RenderView::customFilterGlobalContext()
-{
-    if (!m_customFilterGlobalContext)
-        m_customFilterGlobalContext = adoptPtr(new CustomFilterGlobalContext());
-    return m_customFilterGlobalContext.get();
-}
-
-void RenderView::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
-    RenderBlock::styleDidChange(diff, oldStyle);
-    if (hasRenderNamedFlowThreads())
-        flowThreadController()->styleDidChange();
-}
-
-bool RenderView::hasRenderNamedFlowThreads() const
-{
-    return m_flowThreadController && m_flowThreadController->hasRenderNamedFlowThreads();
-}
-
-bool RenderView::checkTwoPassLayoutForAutoHeightRegions() const
-{
-    return hasRenderNamedFlowThreads() && m_flowThreadController->hasFlowThreadsWithAutoLogicalHeightRegions();
-}
-
 FlowThreadController* RenderView::flowThreadController()
 {
     if (!m_flowThreadController)
-        m_flowThreadController = FlowThreadController::create(this);
+        m_flowThreadController = FlowThreadController::create();
 
     return m_flowThreadController.get();
 }
@@ -1213,64 +1001,16 @@
     return m_frameView->hasOpaqueBackground();
 }
 
-LayoutUnit RenderView::viewportPercentageWidth(float percentage) const
+double RenderView::layoutViewportWidth() const
 {
-    return viewLogicalWidth(ScrollableArea::IncludeScrollbars) * percentage / 100.f;
+    float scale = m_frameView ? m_frameView->frame().pageZoomFactor() : 1;
+    return viewWidth(ScrollableArea::IncludeScrollbars) / scale;
 }
 
-LayoutUnit RenderView::viewportPercentageHeight(float percentage) const
+double RenderView::layoutViewportHeight() const
 {
-    return viewLogicalHeight(ScrollableArea::IncludeScrollbars) * percentage / 100.f;
-}
-
-LayoutUnit RenderView::viewportPercentageMin(float percentage) const
-{
-    return std::min(viewLogicalWidth(ScrollableArea::IncludeScrollbars), viewLogicalHeight(ScrollableArea::IncludeScrollbars))
-        * percentage / 100.f;
-}
-
-LayoutUnit RenderView::viewportPercentageMax(float percentage) const
-{
-    return std::max(viewLogicalWidth(ScrollableArea::IncludeScrollbars), viewLogicalHeight(ScrollableArea::IncludeScrollbars))
-        * percentage / 100.f;
-}
-
-FragmentationDisabler::FragmentationDisabler(RenderObject* root)
-{
-    RenderView* renderView = root->view();
-    ASSERT(renderView);
-
-    LayoutState* layoutState = renderView->layoutState();
-
-    m_root = root;
-    m_fragmenting = layoutState && layoutState->isPaginated();
-    m_flowThreadState = m_root->flowThreadState();
-#ifndef NDEBUG
-    m_layoutState = layoutState;
-#endif
-
-    if (layoutState)
-        layoutState->m_isPaginated = false;
-
-    if (m_flowThreadState != RenderObject::NotInsideFlowThread)
-        m_root->setFlowThreadStateIncludingDescendants(RenderObject::NotInsideFlowThread);
-}
-
-FragmentationDisabler::~FragmentationDisabler()
-{
-    RenderView* renderView = m_root->view();
-    ASSERT(renderView);
-
-    LayoutState* layoutState = renderView->layoutState();
-#ifndef NDEBUG
-    ASSERT(m_layoutState == layoutState);
-#endif
-
-    if (layoutState)
-        layoutState->m_isPaginated = m_fragmenting;
-
-    if (m_flowThreadState != RenderObject::NotInsideFlowThread)
-        m_root->setFlowThreadStateIncludingDescendants(m_flowThreadState);
+    float scale = m_frameView ? m_frameView->frame().pageZoomFactor() : 1;
+    return viewHeight(ScrollableArea::IncludeScrollbars) / scale;
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderView.h b/Source/core/rendering/RenderView.h
index 8da5c9d..8d1f8b4 100644
--- a/Source/core/rendering/RenderView.h
+++ b/Source/core/rendering/RenderView.h
@@ -23,7 +23,6 @@
 #define RenderView_h
 
 #include "core/frame/FrameView.h"
-#include "core/rendering/LayoutIndicator.h"
 #include "core/rendering/LayoutState.h"
 #include "core/rendering/RenderBlockFlow.h"
 #include "platform/PODFreeListArena.h"
@@ -32,11 +31,9 @@
 
 namespace WebCore {
 
-class CustomFilterGlobalContext;
 class FlowThreadController;
 class RenderLayerCompositor;
 class RenderQuote;
-class RenderWidget;
 
 // The root of the render tree, corresponding to the CSS initial containing block.
 // It's dimensions match that of the logical viewport (which may be different from
@@ -54,7 +51,7 @@
 
     virtual bool isRenderView() const OVERRIDE { return true; }
 
-    virtual bool requiresLayer() const OVERRIDE { return true; }
+    virtual LayerType layerTypeRequired() const OVERRIDE { return NormalLayer; }
 
     virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
 
@@ -69,11 +66,11 @@
     // The same as the FrameView's layoutHeight/layoutWidth but with null check guards.
     int viewHeight(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
     int viewWidth(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
-    int viewLogicalWidth(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const
+    int viewLogicalWidth() const
     {
-        return style()->isHorizontalWritingMode() ? viewWidth(scrollbarInclusion) : viewHeight(scrollbarInclusion);
+        return style()->isHorizontalWritingMode() ? viewWidth(ScrollableArea::ExcludeScrollbars) : viewHeight(ScrollableArea::ExcludeScrollbars);
     }
-    int viewLogicalHeight(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
+    int viewLogicalHeight() const;
 
     float zoomFactor() const;
 
@@ -86,7 +83,7 @@
     void repaintRectangleInViewAndCompositedLayers(const LayoutRect&);
     void repaintViewAndCompositedLayers();
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
     virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     enum SelectionRepaintMode { RepaintNewXOROld, RepaintNewMinusOld, RepaintNothing };
@@ -99,8 +96,8 @@
     void selectionStartEnd(int& startPos, int& endPos) const;
     void repaintSelection() const;
 
-    virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const;
-    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
+    virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE;
+    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const OVERRIDE;
 
     void setMaximalOutlineSize(int o);
     int maximalOutlineSize() const { return m_maximalOutlineSize; }
@@ -110,19 +107,17 @@
 
     virtual LayoutRect viewRect() const OVERRIDE;
 
-    void updateWidgetPositions();
-    void addWidget(RenderWidget*);
-    void removeWidget(RenderWidget*);
-
     // layoutDelta is used transiently during layout to store how far an object has moved from its
     // last layout location, in order to repaint correctly.
     // If we're doing a full repaint m_layoutState will be 0, but in that case layoutDelta doesn't matter.
     LayoutSize layoutDelta() const
     {
+        ASSERT(!RuntimeEnabledFeatures::repaintAfterLayoutEnabled());
         return m_layoutState ? m_layoutState->m_layoutDelta : LayoutSize();
     }
     void addLayoutDelta(const LayoutSize& delta)
     {
+        ASSERT(!RuntimeEnabledFeatures::repaintAfterLayoutEnabled());
         if (m_layoutState) {
             m_layoutState->m_layoutDelta += delta;
 #if !ASSERT_DISABLED
@@ -135,6 +130,7 @@
 #if !ASSERT_DISABLED
     bool layoutDeltaMatches(const LayoutSize& delta)
     {
+        ASSERT(!RuntimeEnabledFeatures::repaintAfterLayoutEnabled());
         if (!m_layoutState)
             return false;
         return (delta.width() == m_layoutState->m_layoutDelta.width() || m_layoutState->m_layoutDeltaXSaturated) && (delta.height() == m_layoutState->m_layoutDelta.height() || m_layoutState->m_layoutDeltaYSaturated);
@@ -153,7 +149,7 @@
     bool layoutStateEnabled() const { return m_layoutStateDisableCount == 0 && m_layoutState; }
     LayoutState* layoutState() const { return m_layoutState; }
 
-    virtual void updateHitTestResult(HitTestResult&, const LayoutPoint&);
+    virtual void updateHitTestResult(HitTestResult&, const LayoutPoint&) OVERRIDE;
 
     LayoutUnit pageLogicalHeight() const { return m_pageLogicalHeight; }
     void setPageLogicalHeight(LayoutUnit height)
@@ -170,8 +166,6 @@
     RenderLayerCompositor* compositor();
     bool usesCompositing() const;
 
-    CustomFilterGlobalContext* customFilterGlobalContext();
-
     IntRect unscaledDocumentRect() const;
     LayoutRect backgroundRect(RenderBox* backgroundRenderer) const;
 
@@ -180,12 +174,8 @@
     // Renderer that paints the root background has background-images which all have background-attachment: fixed.
     bool rootBackgroundIsEntirelyFixed() const;
 
-    bool hasRenderNamedFlowThreads() const;
-    bool checkTwoPassLayoutForAutoHeightRegions() const;
     FlowThreadController* flowThreadController();
 
-    void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
-
     IntervalArena* intervalArena();
 
     void setRenderQuoteHead(RenderQuote* head) { m_renderQuoteHead = head; }
@@ -199,37 +189,30 @@
     void removeRenderCounter() { ASSERT(m_renderCounterCount > 0); m_renderCounterCount--; }
     bool hasRenderCounters() { return m_renderCounterCount; }
 
-    virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0) OVERRIDE;
+    virtual bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const OVERRIDE;
 
-    virtual bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const OVERRIDE FINAL;
-
-    LayoutUnit viewportPercentageWidth(float percentage) const;
-    LayoutUnit viewportPercentageHeight(float percentage) const;
-    LayoutUnit viewportPercentageMin(float percentage) const;
-    LayoutUnit viewportPercentageMax(float percentage) const;
+    double layoutViewportWidth() const;
+    double layoutViewportHeight() const;
 
 private:
     virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE;
     virtual const RenderObject* pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&) const OVERRIDE;
-    virtual void mapAbsoluteToLocalPoint(MapCoordinatesFlags, TransformState&) const;
-    virtual bool requiresColumns(int desiredColumnCount) const OVERRIDE;
+    virtual void mapAbsoluteToLocalPoint(MapCoordinatesFlags, TransformState&) const OVERRIDE;
     virtual void computeSelfHitTestRects(Vector<LayoutRect>&, const LayoutPoint& layerOffset) const OVERRIDE;
 
-    bool initializeLayoutState(LayoutState&);
-
-    virtual void calcColumnWidth() OVERRIDE;
-    virtual ColumnInfo::PaginationUnit paginationUnit() const OVERRIDE;
+    void initializeLayoutState(LayoutState&);
 
     bool shouldRepaint(const LayoutRect&) const;
 
+    bool rootFillsViewportBackground(RenderBox* rootBox) const;
+
     // These functions may only be accessed by LayoutStateMaintainer.
     bool pushLayoutState(RenderBox* renderer, const LayoutSize& offset, LayoutUnit pageHeight = 0, bool pageHeightChanged = false, ColumnInfo* colInfo = 0)
     {
         // We push LayoutState even if layoutState is disabled because it stores layoutDelta too.
         if (!doingFullRepaint() || m_layoutState->isPaginated() || renderer->hasColumns() || renderer->flowThreadContainingBlock()
-            || m_layoutState->lineGrid() || (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isRenderBlockFlow())
             || (renderer->isRenderBlock() && toRenderBlock(renderer)->shapeInsideInfo())
-            || (m_layoutState->shapeInsideInfo() && renderer->isRenderBlock() && !toRenderBlock(renderer)->allowsShapeInsideInfoSharing())
+            || (m_layoutState->shapeInsideInfo() && renderer->isRenderBlock() && !toRenderBlock(renderer)->allowsShapeInsideInfoSharing(m_layoutState->shapeInsideInfo()->owner()))
             ) {
             pushLayoutStateForCurrentFlowThread(renderer);
             m_layoutState = new LayoutState(m_layoutState, renderer, offset, pageHeight, pageHeightChanged, colInfo);
@@ -255,7 +238,6 @@
     void enableLayoutState() { ASSERT(m_layoutStateDisableCount > 0); m_layoutStateDisableCount--; }
 
     void layoutContent(const LayoutState&);
-    void layoutContentInAutoLogicalHeightRegions(const LayoutState&);
 #ifndef NDEBUG
     void checkLayoutState(const LayoutState&);
 #endif
@@ -263,9 +245,6 @@
     void positionDialog(RenderBox*);
     void positionDialogs();
 
-    size_t getRetainedWidgets(Vector<RenderWidget*>&);
-    void releaseWidgets(Vector<RenderWidget*>&);
-
     void pushLayoutStateForCurrentFlowThread(const RenderObject*);
     void popLayoutStateForCurrentFlowThread();
 
@@ -285,15 +264,11 @@
     int m_maximalOutlineSize; // Used to apply a fudge factor to dirty-rect checks on blocks/tables.
     int m_oldMaximalOutlineSize; // The fudge factor from the previous layout.
 
-    typedef HashSet<RenderWidget*> RenderWidgetSet;
-    RenderWidgetSet m_widgets;
-
     LayoutUnit m_pageLogicalHeight;
     bool m_pageLogicalHeightChanged;
     LayoutState* m_layoutState;
     unsigned m_layoutStateDisableCount;
     OwnPtr<RenderLayerCompositor> m_compositor;
-    OwnPtr<CustomFilterGlobalContext> m_customFilterGlobalContext;
     OwnPtr<FlowThreadController> m_flowThreadController;
     RefPtr<IntervalArena> m_intervalArena;
 
@@ -386,20 +361,6 @@
     RenderView* m_view;
 };
 
-class FragmentationDisabler {
-    WTF_MAKE_NONCOPYABLE(FragmentationDisabler);
-public:
-    FragmentationDisabler(RenderObject* root);
-    ~FragmentationDisabler();
-private:
-    RenderObject* m_root;
-    RenderObject::FlowThreadState m_flowThreadState;
-    bool m_fragmenting;
-#ifndef NDEBUG
-    LayoutState* m_layoutState;
-#endif
-};
-
 } // namespace WebCore
 
 #endif // RenderView_h
diff --git a/Source/core/rendering/RenderWidget.cpp b/Source/core/rendering/RenderWidget.cpp
index 7e353e1..e911068 100644
--- a/Source/core/rendering/RenderWidget.cpp
+++ b/Source/core/rendering/RenderWidget.cpp
@@ -32,11 +32,8 @@
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
-#include "platform/graphics/GraphicsContext.h"
 #include "wtf/HashMap.h"
 
-using namespace std;
-
 namespace WebCore {
 
 typedef HashMap<RefPtr<Widget>, FrameView*> WidgetToParentMap;
@@ -90,19 +87,18 @@
 RenderWidget::RenderWidget(Element* element)
     : RenderReplaced(element)
     , m_widget(0)
-    , m_frameView(element->document().view())
     // Reference counting is used to prevent the widget from being
     // destroyed while inside the Widget code, which might not be
     // able to handle that.
     , m_refCount(1)
 {
-    view()->addWidget(this);
+    ASSERT(element);
+    frameView()->addWidget(this);
 }
 
 void RenderWidget::willBeDestroyed()
 {
-    if (RenderView* v = view())
-        v->removeWidget(this);
+    frameView()->removeWidget(this);
 
     if (AXObjectCache* cache = document().existingAXObjectCache()) {
         cache->childrenChanged(this->parent());
@@ -140,28 +136,24 @@
     if (!node())
         return false;
 
-    IntRect clipRect = roundedIntRect(enclosingLayer()->childrenClipRect());
     IntRect newFrame = roundedIntRect(frame);
-    bool clipChanged = m_clipRect != clipRect;
-    bool frameRectChanged = m_widget->frameRect() != newFrame;
 
-    if (!frameRectChanged && !clipChanged)
+    if (m_widget->frameRect() == newFrame)
         return false;
 
-    m_clipRect = clipRect;
-
     RefPtr<RenderWidget> protector(this);
     RefPtr<Node> protectedNode(node());
     m_widget->setFrameRect(newFrame);
 
-    if (clipChanged && !frameRectChanged)
-        m_widget->clipRectChanged();
+    {
+        // FIXME: Remove incremental compositing updates after fixing the chicken/egg issues
+        // https://code.google.com/p/chromium/issues/detail?id=343756
+        DisableCompositingQueryAsserts disabler;
+        if (hasLayer() && layer()->compositingState() == PaintsIntoOwnBacking)
+            layer()->compositedLayerMapping()->updateAfterWidgetResize();
+    }
 
-    if (hasLayer() && layer()->compositingState() == PaintsIntoOwnBacking)
-        layer()->compositedLayerMapping()->updateAfterWidgetResize();
-
-    bool boundsChanged = m_widget->frameRect().size() != newFrame.size();
-    return boundsChanged;
+    return m_widget->frameRect().size() != newFrame.size();
 }
 
 bool RenderWidget::updateWidgetGeometry()
@@ -201,7 +193,7 @@
                 repaint();
             }
         }
-        moveWidgetToParentSoon(m_widget.get(), m_frameView);
+        moveWidgetToParentSoon(m_widget.get(), frameView());
     }
 
     if (AXObjectCache* cache = document().existingAXObjectCache())
@@ -280,7 +272,7 @@
     if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && hasOutline())
         paintOutline(paintInfo, LayoutRect(adjustedPaintOffset, size()));
 
-    if (!m_frameView || paintInfo.phase != PaintPhaseForeground)
+    if (paintInfo.phase != PaintPhaseForeground)
         return;
 
     if (style()->hasBorderRadius()) {
@@ -349,14 +341,6 @@
     m_widget->widgetPositionsUpdated();
 }
 
-IntRect RenderWidget::windowClipRect() const
-{
-    if (!m_frameView)
-        return IntRect();
-
-    return intersection(m_frameView->contentsToWindow(m_clipRect), m_frameView->windowClipRect());
-}
-
 void RenderWidget::clearWidget()
 {
     m_widget = 0;
diff --git a/Source/core/rendering/RenderWidget.h b/Source/core/rendering/RenderWidget.h
index b9ed0f9..51c2ecf 100644
--- a/Source/core/rendering/RenderWidget.h
+++ b/Source/core/rendering/RenderWidget.h
@@ -36,7 +36,6 @@
 
     void updateWidgetPosition();
     void widgetPositionsUpdated();
-    IntRect windowClipRect() const;
 
     void setIsOverlapped(bool);
 
@@ -50,16 +49,14 @@
     };
 
 protected:
-    RenderWidget(Element*);
-
-    FrameView* frameView() const { return m_frameView; }
+    explicit RenderWidget(Element*);
 
     void clearWidget();
 
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
-    virtual void layout();
-    virtual void paint(PaintInfo&, const LayoutPoint&);
-    virtual CursorDirective getCursor(const LayoutPoint&, Cursor&) const;
+    virtual void layout() OVERRIDE;
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual CursorDirective getCursor(const LayoutPoint&, Cursor&) const OVERRIDE FINAL;
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 
     virtual void paintContents(PaintInfo&, const LayoutPoint&);
@@ -74,8 +71,6 @@
     bool updateWidgetGeometry();
 
     RefPtr<Widget> m_widget;
-    FrameView* m_frameView;
-    IntRect m_clipRect; // The rectangle needs to remain correct after scrolling, so it is stored in content view coordinates, and not clipped to window.
     int m_refCount;
 };
 
diff --git a/Source/core/rendering/RenderWordBreak.h b/Source/core/rendering/RenderWordBreak.h
index acf3c60..d5b0d31 100644
--- a/Source/core/rendering/RenderWordBreak.h
+++ b/Source/core/rendering/RenderWordBreak.h
@@ -37,8 +37,8 @@
 public:
     explicit RenderWordBreak(HTMLElement*);
 
-    virtual const char* renderName() const;
-    virtual bool isWordBreak() const;
+    virtual const char* renderName() const OVERRIDE;
+    virtual bool isWordBreak() const OVERRIDE;
 };
 
 }
diff --git a/Source/core/rendering/RootInlineBox.cpp b/Source/core/rendering/RootInlineBox.cpp
index 33cf9ad..b110fc6 100644
--- a/Source/core/rendering/RootInlineBox.cpp
+++ b/Source/core/rendering/RootInlineBox.cpp
@@ -129,7 +129,7 @@
     // Create an ellipsis box.
     EllipsisBox* ellipsisBox = new EllipsisBox(renderer(), ellipsisStr, this,
         ellipsisWidth - (markupBox ? markupBox->logicalWidth() : 0), logicalHeight(),
-        y(), !prevRootBox(), isHorizontal(), markupBox);
+        x(), y(), !prevRootBox(), isHorizontal(), markupBox);
 
     if (!gEllipsisBoxMap)
         gEllipsisBoxMap = new EllipsisBoxMap();
@@ -137,8 +137,8 @@
     setHasEllipsisBox(true);
 
     // FIXME: Do we need an RTL version of this?
-    if (ltr && (x() + logicalWidth() + ellipsisWidth) <= blockRightEdge) {
-        ellipsisBox->setX(x() + logicalWidth());
+    if (ltr && (logicalLeft() + logicalWidth() + ellipsisWidth) <= blockRightEdge) {
+        ellipsisBox->setLogicalLeft(logicalLeft() + logicalWidth());
         return logicalWidth() + ellipsisWidth;
     }
 
@@ -148,7 +148,7 @@
     bool foundBox = false;
     float truncatedWidth = 0;
     float position = placeEllipsisBox(ltr, blockLeftEdge, blockRightEdge, ellipsisWidth, truncatedWidth, foundBox);
-    ellipsisBox->setX(position);
+    ellipsisBox->setLogicalLeft(position);
     return truncatedWidth;
 }
 
@@ -209,29 +209,6 @@
     }
 }
 
-RenderRegion* RootInlineBox::containingRegion() const
-{
-    RenderRegion* region = m_fragmentationData ? m_fragmentationData->m_containingRegion : 0;
-
-#ifndef NDEBUG
-    if (region) {
-        RenderFlowThread* flowThread = block()->flowThreadContainingBlock();
-        const RenderRegionList& regionList = flowThread->renderRegionList();
-        ASSERT(regionList.contains(region));
-    }
-#endif
-
-    return region;
-}
-
-void RootInlineBox::setContainingRegion(RenderRegion* region)
-{
-    ASSERT(!isDirty());
-    ASSERT(block()->flowThreadContainingBlock());
-    LineFragmentationData* fragmentationData  = ensureLineFragmentationData();
-    fragmentationData->m_containingRegion = region;
-}
-
 LayoutUnit RootInlineBox::alignBoxesInBlockDirection(LayoutUnit heightOfBlock, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
 {
     // SVG will handle vertical alignment on its own.
@@ -272,7 +249,7 @@
     maxHeight = max<LayoutUnit>(0, maxHeight); // FIXME: Is this really necessary?
 
     setLineTopBottomPositions(lineTop, lineBottom, heightOfBlock, heightOfBlock + maxHeight);
-    setPaginatedLineWidth(block()->availableLogicalWidthForContent(heightOfBlock));
+    setPaginatedLineWidth(block()->availableLogicalWidthForContent());
 
     LayoutUnit annotationsAdjustment = beforeAnnotationsAdjustment();
     if (annotationsAdjustment) {
@@ -282,12 +259,6 @@
         heightOfBlock += annotationsAdjustment;
     }
 
-    LayoutUnit gridSnapAdjustment = lineSnapAdjustment();
-    if (gridSnapAdjustment) {
-        adjustBlockDirectionPosition(gridSnapAdjustment);
-        heightOfBlock += gridSnapAdjustment;
-    }
-
     return heightOfBlock + maxHeight;
 }
 
@@ -329,97 +300,6 @@
     return result;
 }
 
-LayoutUnit RootInlineBox::lineSnapAdjustment(LayoutUnit delta) const
-{
-    // If our block doesn't have snapping turned on, do nothing.
-    // FIXME: Implement bounds snapping.
-    if (block()->style()->lineSnap() == LineSnapNone)
-        return 0;
-
-    // Get the current line grid and offset.
-    LayoutState* layoutState = block()->view()->layoutState();
-    RenderBlockFlow* lineGrid = layoutState->lineGrid();
-    LayoutSize lineGridOffset = layoutState->lineGridOffset();
-    if (!lineGrid || lineGrid->style()->writingMode() != block()->style()->writingMode())
-        return 0;
-
-    // Get the hypothetical line box used to establish the grid.
-    RootInlineBox* lineGridBox = lineGrid->lineGridBox();
-    if (!lineGridBox)
-        return 0;
-
-    LayoutUnit lineGridBlockOffset = lineGrid->isHorizontalWritingMode() ? lineGridOffset.height() : lineGridOffset.width();
-    LayoutUnit blockOffset = block()->isHorizontalWritingMode() ? layoutState->layoutOffset().height() : layoutState->layoutOffset().width();
-
-    // Now determine our position on the grid. Our baseline needs to be adjusted to the nearest baseline multiple
-    // as established by the line box.
-    // FIXME: Need to handle crazy line-box-contain values that cause the root line box to not be considered. I assume
-    // the grid should honor line-box-contain.
-    LayoutUnit gridLineHeight = lineGridBox->lineBottomWithLeading() - lineGridBox->lineTopWithLeading();
-    if (!gridLineHeight)
-        return 0;
-
-    LayoutUnit lineGridFontAscent = lineGrid->style()->fontMetrics().ascent(baselineType());
-    LayoutUnit lineGridFontHeight = lineGridBox->logicalHeight();
-    LayoutUnit firstTextTop = lineGridBlockOffset + lineGridBox->logicalTop();
-    LayoutUnit firstLineTopWithLeading = lineGridBlockOffset + lineGridBox->lineTopWithLeading();
-    LayoutUnit firstBaselinePosition = firstTextTop + lineGridFontAscent;
-
-    LayoutUnit currentTextTop = blockOffset + logicalTop() + delta;
-    LayoutUnit currentFontAscent = block()->style()->fontMetrics().ascent(baselineType());
-    LayoutUnit currentBaselinePosition = currentTextTop + currentFontAscent;
-
-    LayoutUnit lineGridPaginationOrigin = isHorizontal() ? layoutState->lineGridPaginationOrigin().height() : layoutState->lineGridPaginationOrigin().width();
-
-    // If we're paginated, see if we're on a page after the first one. If so, the grid resets on subsequent pages.
-    // FIXME: If the grid is an ancestor of the pagination establisher, then this is incorrect.
-    LayoutUnit pageLogicalTop = 0;
-    if (layoutState->isPaginated() && layoutState->pageLogicalHeight()) {
-        pageLogicalTop = block()->pageLogicalTopForOffset(lineTopWithLeading() + delta);
-        if (pageLogicalTop > firstLineTopWithLeading)
-            firstTextTop = pageLogicalTop + lineGridBox->logicalTop() - lineGrid->borderBefore() - lineGrid->paddingBefore() + lineGridPaginationOrigin;
-    }
-
-    if (block()->style()->lineSnap() == LineSnapContain) {
-        // Compute the desired offset from the text-top of a grid line.
-        // Look at our height (logicalHeight()).
-        // Look at the total available height. It's going to be (textBottom - textTop) + (n-1)*(multiple with leading)
-        // where n is number of grid lines required to enclose us.
-        if (logicalHeight() <= lineGridFontHeight)
-            firstTextTop += (lineGridFontHeight - logicalHeight()) / 2;
-        else {
-            LayoutUnit numberOfLinesWithLeading = ceilf(static_cast<float>(logicalHeight() - lineGridFontHeight) / gridLineHeight);
-            LayoutUnit totalHeight = lineGridFontHeight + numberOfLinesWithLeading * gridLineHeight;
-            firstTextTop += (totalHeight - logicalHeight()) / 2;
-        }
-        firstBaselinePosition = firstTextTop + currentFontAscent;
-    } else
-        firstBaselinePosition = firstTextTop + lineGridFontAscent;
-
-    // If we're above the first line, just push to the first line.
-    if (currentBaselinePosition < firstBaselinePosition)
-        return delta + firstBaselinePosition - currentBaselinePosition;
-
-    // Otherwise we're in the middle of the grid somewhere. Just push to the next line.
-    LayoutUnit baselineOffset = currentBaselinePosition - firstBaselinePosition;
-    LayoutUnit remainder = roundToInt(baselineOffset) % roundToInt(gridLineHeight);
-    LayoutUnit result = delta;
-    if (remainder)
-        result += gridLineHeight - remainder;
-
-    // If we aren't paginated we can return the result.
-    if (!layoutState->isPaginated() || !layoutState->pageLogicalHeight() || result == delta)
-        return result;
-
-    // We may end up shifted to a new page. We need to do a re-snap when that happens.
-    LayoutUnit newPageLogicalTop = block()->pageLogicalTopForOffset(lineBottomWithLeading() + result);
-    if (newPageLogicalTop == pageLogicalTop)
-        return result;
-
-    // Put ourselves at the top of the next page to force a snap onto the new grid established by that page.
-    return lineSnapAdjustment(newPageLogicalTop - (blockOffset + lineTopWithLeading()));
-}
-
 GapRects RootInlineBox::lineSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
                                          LayoutUnit selTop, LayoutUnit selHeight, const PaintInfo* paintInfo)
 {
@@ -865,7 +745,7 @@
     if (verticalAlign != BASELINE) {
         const Font& font = parent->style(firstLine)->font();
         const FontMetrics& fontMetrics = font.fontMetrics();
-        int fontSize = font.pixelSize();
+        int fontSize = font.fontDescription().computedPixelSize();
 
         LineDirectionMode lineDirection = parent->isHorizontalWritingMode() ? HorizontalLine : VerticalLine;
 
@@ -891,7 +771,7 @@
                 lineHeight = renderer->style()->computedLineHeight();
             else
                 lineHeight = renderer->lineHeight(firstLine, lineDirection);
-            verticalPosition -= valueForLength(renderer->style()->verticalAlignLength(), lineHeight, renderer->view());
+            verticalPosition -= valueForLength(renderer->style()->verticalAlignLength(), lineHeight);
         }
     }
 
diff --git a/Source/core/rendering/RootInlineBox.h b/Source/core/rendering/RootInlineBox.h
index 7dfde5f..92ea130 100644
--- a/Source/core/rendering/RootInlineBox.h
+++ b/Source/core/rendering/RootInlineBox.h
@@ -29,7 +29,6 @@
 class EllipsisBox;
 class HitTestResult;
 class RenderBlockFlow;
-class RenderRegion;
 
 struct BidiStatus;
 struct GapRects;
@@ -64,9 +63,6 @@
     LayoutUnit paginatedLineWidth() const { return m_fragmentationData ? m_fragmentationData->m_paginatedLineWidth : LayoutUnit(0); }
     void setPaginatedLineWidth(LayoutUnit width) { ensureLineFragmentationData()->m_paginatedLineWidth = width; }
 
-    RenderRegion* containingRegion() const;
-    void setContainingRegion(RenderRegion*);
-
     LayoutUnit selectionTop() const;
     LayoutUnit selectionBottom() const;
     LayoutUnit selectionHeight() const { return max<LayoutUnit>(0, selectionBottom() - selectionTop()); }
@@ -117,7 +113,7 @@
     virtual int baselinePosition(FontBaseline baselineType) const OVERRIDE FINAL;
     virtual LayoutUnit lineHeight() const OVERRIDE FINAL;
 
-    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom);
+    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE FINAL;
 
     using InlineBox::hasSelectedChildren;
@@ -189,11 +185,9 @@
     Node* getLogicalEndBoxWithNode(InlineBox*&) const;
 
 #ifndef NDEBUG
-    virtual const char* boxName() const;
+    virtual const char* boxName() const OVERRIDE;
 #endif
 private:
-    LayoutUnit lineSnapAdjustment(LayoutUnit delta = 0) const;
-
     LayoutUnit beforeAnnotationsAdjustment() const;
 
     struct LineFragmentationData;
@@ -223,17 +217,13 @@
         WTF_MAKE_NONCOPYABLE(LineFragmentationData); WTF_MAKE_FAST_ALLOCATED;
     public:
         LineFragmentationData()
-            : m_containingRegion(0)
-            , m_paginationStrut(0)
+            : m_paginationStrut(0)
             , m_paginatedLineWidth(0)
             , m_isFirstAfterPageBreak(false)
         {
 
         }
 
-        // It should not be assumed the |containingRegion| is always valid.
-        // It can also be 0 if the flow has no region chain.
-        RenderRegion* m_containingRegion;
         LayoutUnit m_paginationStrut;
         LayoutUnit m_paginatedLineWidth;
         bool m_isFirstAfterPageBreak;
diff --git a/Source/core/rendering/ScrollBehavior.cpp b/Source/core/rendering/ScrollAlignment.cpp
similarity index 79%
rename from Source/core/rendering/ScrollBehavior.cpp
rename to Source/core/rendering/ScrollAlignment.cpp
index d331f1d..433a086 100644
--- a/Source/core/rendering/ScrollBehavior.cpp
+++ b/Source/core/rendering/ScrollAlignment.cpp
@@ -42,24 +42,24 @@
  */
 
 #include "config.h"
-#include "core/rendering/ScrollBehavior.h"
+#include "core/rendering/ScrollAlignment.h"
 
 #include "platform/geometry/LayoutRect.h"
 
 namespace WebCore {
 
-const ScrollAlignment ScrollAlignment::alignCenterIfNeeded = { noScroll, alignCenter, alignToClosestEdge };
-const ScrollAlignment ScrollAlignment::alignToEdgeIfNeeded = { noScroll, alignToClosestEdge, alignToClosestEdge };
-const ScrollAlignment ScrollAlignment::alignCenterAlways = { alignCenter, alignCenter, alignCenter };
-const ScrollAlignment ScrollAlignment::alignTopAlways = { alignTop, alignTop, alignTop };
-const ScrollAlignment ScrollAlignment::alignBottomAlways = { alignBottom, alignBottom, alignBottom };
+const ScrollAlignment ScrollAlignment::alignCenterIfNeeded = { ScrollAlignmentNoScroll, ScrollAlignmentCenter, ScrollAlignmentClosestEdge };
+const ScrollAlignment ScrollAlignment::alignToEdgeIfNeeded = { ScrollAlignmentNoScroll, ScrollAlignmentClosestEdge, ScrollAlignmentClosestEdge };
+const ScrollAlignment ScrollAlignment::alignCenterAlways = { ScrollAlignmentCenter, ScrollAlignmentCenter, ScrollAlignmentCenter };
+const ScrollAlignment ScrollAlignment::alignTopAlways = { ScrollAlignmentTop, ScrollAlignmentTop, ScrollAlignmentTop };
+const ScrollAlignment ScrollAlignment::alignBottomAlways = { ScrollAlignmentBottom, ScrollAlignmentBottom, ScrollAlignmentBottom };
 
 #define MIN_INTERSECT_FOR_REVEAL 32
 
 LayoutRect ScrollAlignment::getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
 {
     // Determine the appropriate X behavior.
-    ScrollBehavior scrollX;
+    ScrollAlignmentBehavior scrollX;
     LayoutRect exposeRectX(exposeRect.x(), visibleRect.y(), exposeRect.width(), visibleRect.height());
     LayoutUnit intersectWidth = intersection(visibleRect, exposeRectX).width();
     if (intersectWidth == exposeRect.width() || intersectWidth >= MIN_INTERSECT_FOR_REVEAL) {
@@ -70,8 +70,8 @@
     } else if (intersectWidth == visibleRect.width()) {
         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
         scrollX = getVisibleBehavior(alignX);
-        if (scrollX == alignCenter)
-            scrollX = noScroll;
+        if (scrollX == ScrollAlignmentCenter)
+            scrollX = ScrollAlignmentNoScroll;
     } else if (intersectWidth > 0) {
         // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
         scrollX = getPartialBehavior(alignX);
@@ -79,29 +79,29 @@
         scrollX = getHiddenBehavior(alignX);
     }
 
-    if (scrollX == alignToClosestEdge) {
+    if (scrollX == ScrollAlignmentClosestEdge) {
         // Closest edge is the right in two cases:
         // (1) exposeRect to the right of and smaller than visibleRect
         // (2) exposeRect to the left of and larger than visibleRect
         if ((exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
             || (exposeRect.maxX() < visibleRect.maxX() && exposeRect.width() > visibleRect.width())) {
-            scrollX = alignRight;
+            scrollX = ScrollAlignmentRight;
         }
     }
 
     // Given the X behavior, compute the X coordinate.
     LayoutUnit x;
-    if (scrollX == noScroll)
+    if (scrollX == ScrollAlignmentNoScroll)
         x = visibleRect.x();
-    else if (scrollX == alignRight)
+    else if (scrollX == ScrollAlignmentRight)
         x = exposeRect.maxX() - visibleRect.width();
-    else if (scrollX == alignCenter)
+    else if (scrollX == ScrollAlignmentCenter)
         x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
     else
         x = exposeRect.x();
 
     // Determine the appropriate Y behavior.
-    ScrollBehavior scrollY;
+    ScrollAlignmentBehavior scrollY;
     LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
     LayoutUnit intersectHeight = intersection(visibleRect, exposeRectY).height();
     if (intersectHeight == exposeRect.height()) {
@@ -110,8 +110,8 @@
     } else if (intersectHeight == visibleRect.height()) {
         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
         scrollY = getVisibleBehavior(alignY);
-        if (scrollY == alignCenter)
-            scrollY = noScroll;
+        if (scrollY == ScrollAlignmentCenter)
+            scrollY = ScrollAlignmentNoScroll;
     } else if (intersectHeight > 0) {
         // If the rectangle is partially visible, use the specified partial behavior
         scrollY = getPartialBehavior(alignY);
@@ -119,23 +119,23 @@
         scrollY = getHiddenBehavior(alignY);
     }
 
-    if (scrollY == alignToClosestEdge) {
+    if (scrollY == ScrollAlignmentClosestEdge) {
         // Closest edge is the bottom in two cases:
         // (1) exposeRect below and smaller than visibleRect
         // (2) exposeRect above and larger than visibleRect
         if ((exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
             || (exposeRect.maxY() < visibleRect.maxY() && exposeRect.height() > visibleRect.height())) {
-            scrollY = alignBottom;
+            scrollY = ScrollAlignmentBottom;
         }
     }
 
     // Given the Y behavior, compute the Y coordinate.
     LayoutUnit y;
-    if (scrollY == noScroll)
+    if (scrollY == ScrollAlignmentNoScroll)
         y = visibleRect.y();
-    else if (scrollY == alignBottom)
+    else if (scrollY == ScrollAlignmentBottom)
         y = exposeRect.maxY() - visibleRect.height();
-    else if (scrollY == alignCenter)
+    else if (scrollY == ScrollAlignmentCenter)
         y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
     else
         y = exposeRect.y();
diff --git a/Source/core/rendering/ScrollBehavior.h b/Source/core/rendering/ScrollAlignment.h
similarity index 78%
rename from Source/core/rendering/ScrollBehavior.h
rename to Source/core/rendering/ScrollAlignment.h
index 7c683d8..f22b1d9 100644
--- a/Source/core/rendering/ScrollBehavior.h
+++ b/Source/core/rendering/ScrollAlignment.h
@@ -41,27 +41,27 @@
  * version of this file under any of the LGPL, the MPL or the GPL.
  */
 
-#ifndef ScrollBehavior_h
-#define ScrollBehavior_h
+#ifndef ScrollAlignment_h
+#define ScrollAlignment_h
 
 namespace WebCore {
 
-enum ScrollBehavior {
-    noScroll,
-    alignCenter,
-    alignTop,
-    alignBottom,
-    alignLeft,
-    alignRight,
-    alignToClosestEdge
+enum ScrollAlignmentBehavior {
+    ScrollAlignmentNoScroll,
+    ScrollAlignmentCenter,
+    ScrollAlignmentTop,
+    ScrollAlignmentBottom,
+    ScrollAlignmentLeft,
+    ScrollAlignmentRight,
+    ScrollAlignmentClosestEdge
 };
 
 class LayoutRect;
 
 struct ScrollAlignment {
-    static ScrollBehavior getVisibleBehavior(const ScrollAlignment& s) { return s.m_rectVisible; }
-    static ScrollBehavior getPartialBehavior(const ScrollAlignment& s) { return s.m_rectPartial; }
-    static ScrollBehavior getHiddenBehavior(const ScrollAlignment& s) { return s.m_rectHidden; }
+    static ScrollAlignmentBehavior getVisibleBehavior(const ScrollAlignment& s) { return s.m_rectVisible; }
+    static ScrollAlignmentBehavior getPartialBehavior(const ScrollAlignment& s) { return s.m_rectPartial; }
+    static ScrollAlignmentBehavior getHiddenBehavior(const ScrollAlignment& s) { return s.m_rectHidden; }
 
     // FIXME: This function should probably go somewhere else but where?
     static LayoutRect getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
@@ -72,12 +72,12 @@
     static const ScrollAlignment alignTopAlways;
     static const ScrollAlignment alignBottomAlways;
 
-    ScrollBehavior m_rectVisible;
-    ScrollBehavior m_rectHidden;
-    ScrollBehavior m_rectPartial;
+    ScrollAlignmentBehavior m_rectVisible;
+    ScrollAlignmentBehavior m_rectHidden;
+    ScrollAlignmentBehavior m_rectPartial;
 };
 
 
 }; // namespace WebCore
 
-#endif // ScrollBehavior_h
+#endif // ScrollAlignment_h
diff --git a/Source/core/rendering/SubtreeLayoutScope.cpp b/Source/core/rendering/SubtreeLayoutScope.cpp
index d650513..48b1f35 100644
--- a/Source/core/rendering/SubtreeLayoutScope.cpp
+++ b/Source/core/rendering/SubtreeLayoutScope.cpp
@@ -39,7 +39,7 @@
 SubtreeLayoutScope::SubtreeLayoutScope(RenderObject* root)
     : m_root(root)
 {
-    RELEASE_ASSERT(m_root->document().view()->isInLayout());
+    RELEASE_ASSERT(m_root->document().view()->isInPerformLayout());
 }
 
 SubtreeLayoutScope::~SubtreeLayoutScope()
diff --git a/Source/core/rendering/TextAutosizer.cpp b/Source/core/rendering/TextAutosizer.cpp
index 73babc5..b14768d 100644
--- a/Source/core/rendering/TextAutosizer.cpp
+++ b/Source/core/rendering/TextAutosizer.cpp
@@ -25,8 +25,8 @@
 
 #include "core/dom/Document.h"
 #include "core/html/HTMLElement.h"
+#include "core/frame/Settings.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Settings.h"
 #include "core/rendering/RenderListItem.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderText.h"
@@ -36,10 +36,11 @@
 #include "platform/TraceEvent.h"
 #include "platform/geometry/IntSize.h"
 #include "wtf/StdLibExtras.h"
-#include "wtf/Vector.h"
 
 namespace WebCore {
 
+#define AUTOSIZING_CLUSTER_HASH
+
 using namespace HTMLNames;
 
 struct TextAutosizingWindowInfo {
@@ -47,26 +48,25 @@
     IntSize minLayoutSize;
 };
 
-// Represents cluster related data. Instances should not persist between calls to processSubtree.
-struct TextAutosizingClusterInfo {
-    explicit TextAutosizingClusterInfo(RenderBlock* root)
-        : root(root)
-        , blockContainingAllText(0)
-        , maxAllowedDifferenceFromTextWidth(150)
+// Represents a POD of a selection of fields for hashing. The fields are selected to detect similar
+// nodes in the Render Tree from the viewpoint of text autosizing.
+struct RenderObjectPodForHash {
+    RenderObjectPodForHash()
+        : qualifiedNameHash(0)
+        , packedStyleProperties(0)
+        , width(0)
     {
     }
+    ~RenderObjectPodForHash() { }
 
-    RenderBlock* root;
-    const RenderBlock* blockContainingAllText;
+    unsigned qualifiedNameHash;
 
-    // Upper limit on the difference between the width of the cluster's block containing all
-    // text and that of a narrow child before the child becomes a separate cluster.
-    float maxAllowedDifferenceFromTextWidth;
-
-    // Descendants of the cluster that are narrower than the block containing all text and must be
-    // processed together.
-    Vector<TextAutosizingClusterInfo> narrowDescendants;
+    // Style specific selection of signals
+    unsigned packedStyleProperties;
+    float width;
 };
+// To allow for efficient hashing using StringHasher.
+COMPILE_ASSERT(!(sizeof(RenderObjectPodForHash) % sizeof(UChar)), RenderObjectPodForHashMultipleOfUchar);
 
 #ifdef AUTOSIZING_DOM_DEBUG_INFO
 static void writeDebugInfo(RenderObject* renderObject, const AtomicString& output)
@@ -110,11 +110,64 @@
     return 0;
 }
 
+static Node* getGeneratingElementNode(const RenderObject* renderer)
+{
+    Node* node = renderer->generatingNode();
+    return (node && node->isElementNode()) ? node : 0;
+}
+
+static unsigned hashMemory(const void* data, size_t length)
+{
+    return StringHasher::computeHash<UChar>(static_cast<const UChar*>(data), length / sizeof(UChar));
+}
+
+static unsigned computeLocalHash(const RenderObject* renderer)
+{
+    Node* generatingElementNode = getGeneratingElementNode(renderer);
+    ASSERT(generatingElementNode);
+
+    RenderObjectPodForHash podForHash;
+    podForHash.qualifiedNameHash = QualifiedNameHash::hash(toElement(generatingElementNode)->tagQName());
+
+    if (RenderStyle* style = renderer->style()) {
+        podForHash.packedStyleProperties = style->direction();
+        podForHash.packedStyleProperties |= (style->position() << 1);
+        podForHash.packedStyleProperties |= (style->floating() << 4);
+        podForHash.packedStyleProperties |= (style->display() << 6);
+        podForHash.packedStyleProperties |= (style->width().type() << 11);
+        // packedStyleProperties effectively using 15 bits now.
+
+        // consider for adding: writing mode, padding.
+
+        podForHash.width = style->width().getFloatValue();
+    }
+
+    return hashMemory(&podForHash, sizeof(podForHash));
+}
+
 TextAutosizer::TextAutosizer(Document* document)
     : m_document(document)
 {
 }
 
+unsigned TextAutosizer::getCachedHash(const RenderObject* renderer, bool putInCacheIfAbsent)
+{
+    HashMap<const RenderObject*, unsigned>::const_iterator it = m_hashCache.find(renderer);
+    if (it != m_hashCache.end())
+        return it->value;
+
+    RenderObject* rendererParent = renderer->parent();
+    while (rendererParent && !getGeneratingElementNode(rendererParent))
+        rendererParent = rendererParent->parent();
+
+    const unsigned parentHashValue = rendererParent ? getCachedHash(rendererParent, true) : 0;
+    const unsigned hashes[2] = { parentHashValue, computeLocalHash(renderer) };
+    const unsigned combinedHashValue = hashMemory(hashes, sizeof(hashes));
+    if (putInCacheIfAbsent)
+        m_hashCache.add(renderer, combinedHashValue);
+    return combinedHashValue;
+}
+
 void TextAutosizer::recalculateMultipliers()
 {
     RenderObject* renderer = m_document->renderer();
@@ -129,11 +182,16 @@
 {
     TRACE_EVENT0("webkit", "TextAutosizer::processSubtree");
 
-    if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->document().printing() || !m_document->page())
+    if (!m_document->settings() || layoutRoot->view()->document().printing() || !m_document->page())
         return false;
 
-    Frame* mainFrame = m_document->page()->mainFrame();
+    bool textAutosizingEnabled = m_document->settings()->textAutosizingEnabled();
+    if (!textAutosizingEnabled)
+        return false;
 
+    InspectorInstrumentation::willAutosizeText(layoutRoot);
+
+    Frame* mainFrame = m_document->page()->mainFrame();
     TextAutosizingWindowInfo windowInfo;
 
     // Window area, in logical (density-independent) pixels.
@@ -160,11 +218,22 @@
     // Note: this might suppress autosizing of an inner cluster with a different writing mode.
     // It's not clear what the correct behavior is for mixed writing modes anyway.
     if (!cluster || clusterMultiplier(cluster->style()->writingMode(), windowInfo,
-        std::numeric_limits<float>::infinity()) == 1.0f)
+        std::numeric_limits<float>::infinity()) == 1.0f) {
+        InspectorInstrumentation::didAutosizeText(layoutRoot);
         return false;
+    }
 
     TextAutosizingClusterInfo clusterInfo(cluster);
     processCluster(clusterInfo, container, layoutRoot, windowInfo);
+
+#ifdef AUTOSIZING_CLUSTER_HASH
+    // Second pass to autosize stale non-autosized clusters for consistency.
+    secondPassProcessStaleNonAutosizedClusters();
+    m_hashCache.clear();
+    m_hashToMultiplier.clear();
+    m_hashesToAutosizeSecondPass.clear();
+    m_nonAutosizedClusters.clear();
+#endif
     InspectorInstrumentation::didAutosizeText(layoutRoot);
     return true;
 }
@@ -182,7 +251,8 @@
     // If the page has a meta viewport or @viewport, don't apply the device scale adjustment.
     const ViewportDescription& viewportDescription = m_document->page()->mainFrame()->document()->viewportDescription();
     if (!viewportDescription.isSpecifiedByAuthor()) {
-        multiplier *= m_document->settings()->deviceScaleAdjustment();
+        float deviceScaleAdjustment = m_document->settings()->deviceScaleAdjustment();
+        multiplier *= deviceScaleAdjustment;
     }
     return std::max(1.0f, multiplier);
 }
@@ -200,6 +270,58 @@
         processCompositeCluster(narrowDescendantsGroups[i], windowInfo);
 }
 
+unsigned TextAutosizer::computeCompositeClusterHash(Vector<TextAutosizingClusterInfo>& clusterInfos)
+{
+    if (clusterInfos.size() == 1 && getGeneratingElementNode(clusterInfos[0].root))
+        return getCachedHash(clusterInfos[0].root, false);
+
+    // FIXME: consider hashing clusters for which clusterInfos.size() > 1
+    return 0;
+}
+
+void TextAutosizer::addNonAutosizedCluster(unsigned key, TextAutosizingClusterInfo& value)
+{
+    HashMap<unsigned, OwnPtr<Vector<TextAutosizingClusterInfo> > >::const_iterator it = m_nonAutosizedClusters.find(key);
+    if (it == m_nonAutosizedClusters.end()) {
+        m_nonAutosizedClusters.add(key, adoptPtr(new Vector<TextAutosizingClusterInfo>(1, value)));
+        return;
+    }
+    it->value->append(value);
+}
+
+float TextAutosizer::computeMultiplier(Vector<TextAutosizingClusterInfo>& clusterInfos, const TextAutosizingWindowInfo& windowInfo, float textWidth)
+{
+#ifdef AUTOSIZING_CLUSTER_HASH
+    // When hashing is enabled this function returns a multiplier based on previously seen clusters.
+    // It will return a non-unit multiplier if a cluster with the same hash value has been previously
+    // autosized.
+    unsigned clusterHash = computeCompositeClusterHash(clusterInfos);
+#else
+    unsigned clusterHash = 0;
+#endif
+
+    if (clusterHash) {
+        HashMap<unsigned, float>::iterator it = m_hashToMultiplier.find(clusterHash);
+        if (it != m_hashToMultiplier.end())
+            return it->value;
+    }
+
+    if (compositeClusterShouldBeAutosized(clusterInfos, textWidth)) {
+        float multiplier = clusterMultiplier(clusterInfos[0].root->style()->writingMode(), windowInfo, textWidth);
+        if (clusterHash) {
+            if (multiplier > 1 && m_nonAutosizedClusters.contains(clusterHash))
+                m_hashesToAutosizeSecondPass.append(clusterHash);
+            m_hashToMultiplier.add(clusterHash, multiplier);
+        }
+        return multiplier;
+    }
+
+    if (clusterHash)
+        addNonAutosizedCluster(clusterHash, clusterInfos[0]);
+
+    return 1.0f;
+}
+
 void TextAutosizer::processCluster(TextAutosizingClusterInfo& clusterInfo, RenderBlock* container, RenderObject* subtreeRoot, const TextAutosizingWindowInfo& windowInfo)
 {
     // Many pages set a max-width on their content. So especially for the RenderView, instead of
@@ -208,9 +330,10 @@
     // text), and use its width instead.
     clusterInfo.blockContainingAllText = findDeepestBlockContainingAllText(clusterInfo.root);
     float textWidth = clusterInfo.blockContainingAllText->contentLogicalWidth();
-    float multiplier =  1.0;
-    if (clusterShouldBeAutosized(clusterInfo, textWidth))
-        multiplier = clusterMultiplier(clusterInfo.root->style()->writingMode(), windowInfo, textWidth);
+
+    Vector<TextAutosizingClusterInfo> clusterInfos(1, clusterInfo);
+    float multiplier = computeMultiplier(clusterInfos, windowInfo, textWidth);
+
     processClusterInternal(clusterInfo, container, subtreeRoot, windowInfo, multiplier);
 }
 
@@ -226,15 +349,49 @@
         maxTextWidth = max<float>(maxTextWidth, clusterInfo.blockContainingAllText->contentLogicalWidth());
     }
 
-    float multiplier = 1.0;
-    if (compositeClusterShouldBeAutosized(clusterInfos, maxTextWidth))
-        multiplier = clusterMultiplier(clusterInfos[0].root->style()->writingMode(), windowInfo, maxTextWidth);
+    float multiplier =  computeMultiplier(clusterInfos, windowInfo, maxTextWidth);
     for (size_t i = 0; i < clusterInfos.size(); ++i) {
         ASSERT(clusterInfos[i].root->style()->writingMode() == clusterInfos[0].root->style()->writingMode());
         processClusterInternal(clusterInfos[i], clusterInfos[i].root, clusterInfos[i].root, windowInfo, multiplier);
     }
 }
 
+void TextAutosizer::secondPassProcessStaleNonAutosizedClusters()
+{
+    for (size_t i = 0; i < m_hashesToAutosizeSecondPass.size(); ++i) {
+        unsigned hash = m_hashesToAutosizeSecondPass[i];
+        float multiplier = m_hashToMultiplier.get(hash);
+        Vector<TextAutosizingClusterInfo>* val = m_nonAutosizedClusters.get(hash);
+        for (Vector<TextAutosizingClusterInfo>::iterator it2 = val->begin(); it2 != val->end(); ++it2)
+            processStaleContainer(multiplier, (*it2).root, *it2);
+    }
+}
+
+void TextAutosizer::processStaleContainer(float multiplier, RenderBlock* cluster, TextAutosizingClusterInfo& clusterInfo)
+{
+    ASSERT(isAutosizingContainer(cluster));
+
+    // This method is different from processContainer() mainly in that it does not recurse into sub-clusters.
+    // Multiplier updates are restricted to the specified cluster only. Also the multiplier > 1 by construction
+    // of m_hashesToAutosizeSecondPass, so we don't need to check it explicitly.
+    float localMultiplier = containerShouldBeAutosized(cluster) ? multiplier : 1;
+
+    RenderObject* descendant = nextInPreOrderSkippingDescendantsOfContainers(cluster, cluster);
+    while (descendant) {
+        if (descendant->isText()) {
+            if (localMultiplier != 1 && descendant->style()->textAutosizingMultiplier() == 1) {
+                setMultiplier(descendant, localMultiplier);
+                setMultiplier(descendant->parent(), localMultiplier); // Parent does line spacing.
+            }
+        } else if (isAutosizingContainer(descendant)) {
+            RenderBlock* descendantBlock = toRenderBlock(descendant);
+            if (!isAutosizingCluster(descendantBlock, clusterInfo))
+                processStaleContainer(multiplier, descendantBlock, clusterInfo);
+        }
+        descendant = nextInPreOrderSkippingDescendantsOfContainers(descendant, cluster);
+    }
+}
+
 void TextAutosizer::processContainer(float multiplier, RenderBlock* container, TextAutosizingClusterInfo& clusterInfo, RenderObject* subtreeRoot, const TextAutosizingWindowInfo& windowInfo)
 {
     ASSERT(isAutosizingContainer(container));
@@ -242,7 +399,7 @@
     writeDebugInfo(container, "container");
 #endif
 
-    float localMultiplier = containerShouldBeAutosized(container) ? multiplier: 1;
+    float localMultiplier = (multiplier > 1 && containerShouldBeAutosized(container)) ? multiplier: 1;
 
     RenderObject* descendant = nextInPreOrderSkippingDescendantsOfContainers(subtreeRoot, subtreeRoot);
     while (descendant) {
@@ -336,7 +493,10 @@
     // - Must not be list items, as items in the same list should look consistent (*).
     // - Must not be normal list items, as items in the same list should look
     //   consistent, unless they are floating or position:absolute/fixed.
-    if (!renderer->isRenderBlock() || (renderer->isInline() && !renderer->style()->isDisplayReplacedType()))
+    Node* node = renderer->generatingNode();
+    if ((node && !node->hasChildNodes())
+        || !renderer->isRenderBlock()
+        || (renderer->isInline() && !renderer->style()->isDisplayReplacedType()))
         return false;
     if (renderer->isListItem())
         return renderer->isFloating() || renderer->isOutOfFlowPositioned();
@@ -409,6 +569,7 @@
     // from the box's parent (we want to avoid having significantly different
     // width blocks within a cluster, since the narrower blocks would end up
     // larger than would otherwise be necessary).
+    RenderBlock* containingBlock = renderer->containingBlock();
     return renderer->isRenderView()
         || renderer->isFloating()
         || renderer->isOutOfFlowPositioned()
@@ -416,7 +577,7 @@
         || renderer->isTableCaption()
         || renderer->isFlexibleBoxIncludingDeprecated()
         || renderer->hasColumns()
-        || renderer->containingBlock()->isHorizontalWritingMode() != renderer->isHorizontalWritingMode()
+        || (containingBlock && containingBlock->isHorizontalWritingMode() != renderer->isHorizontalWritingMode())
         || renderer->style()->isDisplayReplacedType()
         || renderer->isTextArea()
         || renderer->style()->userModify() != READ_ONLY;
@@ -525,12 +686,6 @@
     return false;
 }
 
-bool TextAutosizer::clusterShouldBeAutosized(TextAutosizingClusterInfo& clusterInfo, float blockWidth)
-{
-    Vector<TextAutosizingClusterInfo> clusterInfos(1, clusterInfo);
-    return compositeClusterShouldBeAutosized(clusterInfos, blockWidth);
-}
-
 bool TextAutosizer::compositeClusterShouldBeAutosized(Vector<TextAutosizingClusterInfo>& clusterInfos, float blockWidth)
 {
     // Don't autosize clusters that contain less than 4 lines of text (in
diff --git a/Source/core/rendering/TextAutosizer.h b/Source/core/rendering/TextAutosizer.h
index dda763e..8b8b51a 100644
--- a/Source/core/rendering/TextAutosizer.h
+++ b/Source/core/rendering/TextAutosizer.h
@@ -28,7 +28,9 @@
 
 #include "HTMLNames.h"
 #include "platform/text/WritingMode.h"
+#include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
@@ -38,7 +40,27 @@
 class RenderObject;
 class RenderText;
 struct TextAutosizingWindowInfo;
-struct TextAutosizingClusterInfo;
+
+// Represents cluster related data. Instances should not persist between calls to processSubtree.
+struct TextAutosizingClusterInfo {
+    explicit TextAutosizingClusterInfo(RenderBlock* root)
+        : root(root)
+        , blockContainingAllText(0)
+        , maxAllowedDifferenceFromTextWidth(150)
+    {
+    }
+
+    RenderBlock* root;
+    const RenderBlock* blockContainingAllText;
+
+    // Upper limit on the difference between the width of the cluster's block containing all
+    // text and that of a narrow child before the child becomes a separate cluster.
+    float maxAllowedDifferenceFromTextWidth;
+
+    // Descendants of the cluster that are narrower than the block containing all text and must be
+    // processed together.
+    Vector<TextAutosizingClusterInfo> narrowDescendants;
+};
 
 class TextAutosizer FINAL {
     WTF_MAKE_NONCOPYABLE(TextAutosizer);
@@ -71,6 +93,8 @@
     void setMultiplier(RenderObject*, float);
     void setMultiplierForList(RenderObject* renderer, float multiplier);
 
+    unsigned getCachedHash(const RenderObject* renderer, bool putInCacheIfAbsent);
+
     static bool isAutosizingContainer(const RenderObject*);
     static bool isNarrowDescendant(const RenderBlock*, TextAutosizingClusterInfo& parentClusterInfo);
     static bool isWiderDescendant(const RenderBlock*, const TextAutosizingClusterInfo& parentClusterInfo);
@@ -81,9 +105,10 @@
     static bool containerContainsOneOfTags(const RenderBlock* cluster, const Vector<QualifiedName>& tags);
     static bool containerIsRowOfLinks(const RenderObject* container);
     static bool contentHeightIsConstrained(const RenderBlock* container);
-    static bool clusterShouldBeAutosized(TextAutosizingClusterInfo&, float blockWidth);
     static bool compositeClusterShouldBeAutosized(Vector<TextAutosizingClusterInfo>&, float blockWidth);
     static void measureDescendantTextWidth(const RenderBlock* container, TextAutosizingClusterInfo&, float minTextWidth, float& textWidth);
+    unsigned computeCompositeClusterHash(Vector<TextAutosizingClusterInfo>&);
+    float computeMultiplier(Vector<TextAutosizingClusterInfo>&, const TextAutosizingWindowInfo&, float textWidth);
 
     // Use to traverse the tree of descendants, excluding descendants of containers (but returning the containers themselves).
     static RenderObject* nextInPreOrderSkippingDescendantsOfContainers(const RenderObject*, const RenderObject* stayWithin);
@@ -99,7 +124,20 @@
     // |blockContainingAllText|.
     static void getNarrowDescendantsGroupedByWidth(const TextAutosizingClusterInfo& parentClusterInfo, Vector<Vector<TextAutosizingClusterInfo> >&);
 
+    void addNonAutosizedCluster(unsigned key, TextAutosizingClusterInfo& value);
+    void secondPassProcessStaleNonAutosizedClusters();
+    void processStaleContainer(float multiplier, RenderBlock* cluster, TextAutosizingClusterInfo&);
+
     Document* m_document;
+
+    HashMap<const RenderObject*, unsigned> m_hashCache;
+
+    // Mapping from all autosized (i.e. multiplier > 1) cluster hashes to their respective multipliers.
+    HashMap<unsigned, float> m_hashToMultiplier;
+    Vector<unsigned> m_hashesToAutosizeSecondPass;
+
+    // Mapping from a cluster hash to the corresponding cluster infos which have not been autosized yet.
+    HashMap<unsigned, OwnPtr<Vector<TextAutosizingClusterInfo> > > m_nonAutosizedClusters;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/TrailingFloatsRootInlineBox.h b/Source/core/rendering/TrailingFloatsRootInlineBox.h
index 8036f5a..ce3309f 100644
--- a/Source/core/rendering/TrailingFloatsRootInlineBox.h
+++ b/Source/core/rendering/TrailingFloatsRootInlineBox.h
@@ -39,7 +39,7 @@
     }
 
 private:
-    virtual float virtualLogicalHeight() const { return 0; }
+    virtual float virtualLogicalHeight() const OVERRIDE { return 0; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/animation/WebAnimationProvider.cpp b/Source/core/rendering/animation/WebAnimationProvider.cpp
deleted file mode 100644
index 473e3ff..0000000
--- a/Source/core/rendering/animation/WebAnimationProvider.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * Copyright (C) 2013 Intel Corporation. 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 APPLE INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#include "config.h"
-
-#include "core/rendering/animation/WebAnimationProvider.h"
-
-#include "core/platform/animation/AnimationTranslationUtil.h"
-#include "core/platform/animation/CSSAnimationData.h"
-#include "core/rendering/style/KeyframeList.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "public/platform/WebAnimation.h"
-#include "wtf/text/StringBuilder.h"
-
-using blink::WebAnimation;
-
-namespace WebCore {
-
-namespace {
-
-String animationNameForTransition(AnimatedPropertyID property)
-{
-    // | is not a valid identifier character in CSS, so this can never conflict with a keyframe identifier.
-    StringBuilder id;
-    id.appendLiteral("-|transition");
-    id.appendNumber(static_cast<int>(property));
-    id.append('-');
-    return id.toString();
-}
-
-AnimatedPropertyID cssToGraphicsLayerProperty(CSSPropertyID cssProperty)
-{
-    switch (cssProperty) {
-    case CSSPropertyWebkitTransform:
-        return AnimatedPropertyWebkitTransform;
-    case CSSPropertyOpacity:
-        return AnimatedPropertyOpacity;
-    case CSSPropertyBackgroundColor:
-        ASSERT_NOT_REACHED();
-        return AnimatedPropertyInvalid; // Chromium compositor cannot accelerate background color yet.
-    case CSSPropertyWebkitFilter:
-        return AnimatedPropertyWebkitFilter;
-    default:
-        // It's fine if we see other css properties here; they are just not accelerated.
-        break;
-    }
-    return AnimatedPropertyInvalid;
-}
-
-} // namespace
-
-WebAnimations::WebAnimations()
-{
-}
-
-WebAnimations::~WebAnimations()
-{
-}
-
-// Copy constructor is needed to use this struct as a return value. It actually moves the ownership, not copy.
-WebAnimations::WebAnimations(const WebAnimations& other)
-{
-    ASSERT(isEmpty());
-    m_transformAnimation.swap(const_cast<OwnPtr<WebAnimation>& >(other.m_transformAnimation));
-    m_opacityAnimation.swap(const_cast<OwnPtr<WebAnimation>& >(other.m_opacityAnimation));
-    m_filterAnimation.swap(const_cast<OwnPtr<WebAnimation>& >(other.m_filterAnimation));
-    ASSERT(other.isEmpty());
-}
-
-bool WebAnimations::isEmpty() const
-{
-    return !m_transformAnimation && !m_opacityAnimation && !m_filterAnimation;
-}
-
-WebAnimationProvider::WebAnimationProvider()
-{
-}
-
-WebAnimationProvider::~WebAnimationProvider()
-{
-}
-
-int WebAnimationProvider::getWebAnimationId(const String& animationName) const
-{
-    if (!m_animationIdMap.contains(animationName))
-        return 0;
-    return m_animationIdMap.get(animationName);
-}
-
-int WebAnimationProvider::getWebAnimationId(CSSPropertyID property) const
-{
-    AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
-    ASSERT(animatedProperty != AnimatedPropertyInvalid);
-    return getWebAnimationId(animationNameForTransition(animatedProperty));
-}
-
-WebAnimations WebAnimationProvider::startAnimation(double timeOffset, const CSSAnimationData* anim, const KeyframeList& keyframes, bool hasTransform, const IntSize& boxSize)
-{
-    ASSERT(hasTransform || boxSize.isEmpty());
-    bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
-    bool hasFilter = keyframes.containsProperty(CSSPropertyWebkitFilter);
-
-    if (!hasOpacity && !hasTransform && !hasFilter)
-        return WebAnimations();
-
-    KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
-    KeyframeValueList opacityVector(AnimatedPropertyOpacity);
-    KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
-
-    size_t numKeyframes = keyframes.size();
-    for (size_t i = 0; i < numKeyframes; ++i) {
-        const KeyframeValue& currentKeyframe = keyframes[i];
-        const RenderStyle* keyframeStyle = currentKeyframe.style();
-        double key = currentKeyframe.key();
-
-        if (!keyframeStyle)
-            continue;
-
-        // Get timing function.
-        RefPtr<TimingFunction> tf = KeyframeValue::timingFunction(*keyframeStyle);
-
-        bool isFirstOrLastKeyframe = !key || key == 1;
-        if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
-            transformVector.insert(adoptPtr(new TransformAnimationValue(key, &(keyframeStyle->transform()), tf)));
-
-        if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
-            opacityVector.insert(adoptPtr(new FloatAnimationValue(key, keyframeStyle->opacity(), tf)));
-
-        if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitFilter))
-            filterVector.insert(adoptPtr(new FilterAnimationValue(key, &(keyframeStyle->filter()), tf)));
-    }
-    WebAnimations resultAnimations;
-    if (hasTransform)
-        resultAnimations.m_transformAnimation = createWebAnimationAndStoreId(transformVector, boxSize, anim, keyframes.animationName(), timeOffset);
-    if (hasOpacity)
-        resultAnimations.m_opacityAnimation = createWebAnimationAndStoreId(opacityVector, IntSize(), anim, keyframes.animationName(), timeOffset);
-    if (hasFilter)
-        resultAnimations.m_filterAnimation = createWebAnimationAndStoreId(filterVector, IntSize(), anim, keyframes.animationName(), timeOffset);
-
-    return resultAnimations;
-}
-
-WebAnimations WebAnimationProvider::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle, bool hasTransform, bool hasFilter, const IntSize& boxSize, float fromOpacity, float toOpacity)
-{
-    ASSERT(property != CSSPropertyInvalid);
-    ASSERT(property == CSSPropertyOpacity || (!fromOpacity && !toOpacity));
-
-    WebAnimations resultAnimations;
-    if (property == CSSPropertyOpacity) {
-        const CSSAnimationData* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
-        if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
-            KeyframeValueList opacityVector(AnimatedPropertyOpacity);
-            opacityVector.insert(adoptPtr(new FloatAnimationValue(0, fromOpacity)));
-            opacityVector.insert(adoptPtr(new FloatAnimationValue(1, toOpacity)));
-            resultAnimations.m_opacityAnimation = createWebAnimationAndStoreId(opacityVector, IntSize(), opacityAnim, animationNameForTransition(AnimatedPropertyOpacity), timeOffset);
-        }
-    }
-    if (property == CSSPropertyWebkitTransform && hasTransform) {
-        const CSSAnimationData* transformAnim = toStyle->transitionForProperty(CSSPropertyWebkitTransform);
-        if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
-            KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
-            transformVector.insert(adoptPtr(new TransformAnimationValue(0, &fromStyle->transform())));
-            transformVector.insert(adoptPtr(new TransformAnimationValue(1, &toStyle->transform())));
-            resultAnimations.m_transformAnimation = createWebAnimationAndStoreId(transformVector, boxSize, transformAnim, animationNameForTransition(AnimatedPropertyWebkitTransform), timeOffset);
-        }
-    }
-    if (property == CSSPropertyWebkitFilter && hasFilter) {
-        const CSSAnimationData* filterAnim = toStyle->transitionForProperty(CSSPropertyWebkitFilter);
-        if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
-            KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
-            filterVector.insert(adoptPtr(new FilterAnimationValue(0, &fromStyle->filter())));
-            filterVector.insert(adoptPtr(new FilterAnimationValue(1, &toStyle->filter())));
-            resultAnimations.m_filterAnimation = createWebAnimationAndStoreId(filterVector, IntSize(), filterAnim, animationNameForTransition(AnimatedPropertyWebkitFilter), timeOffset);
-        }
-    }
-
-    return resultAnimations;
-}
-
-PassOwnPtr<WebAnimation> WebAnimationProvider::createWebAnimationAndStoreId(const KeyframeValueList& values, const IntSize& boxSize, const CSSAnimationData* animation, const String& animationName, double timeOffset)
-{
-    int animationId = getWebAnimationId(animationName);
-    OwnPtr<WebAnimation> webAnimation(createWebAnimation(values, animation, animationId, timeOffset, boxSize));
-    if (!webAnimation)
-        return PassOwnPtr<WebAnimation>();
-
-    if (!animationId)
-        m_animationIdMap.set(animationName, webAnimation->id());
-    return webAnimation.release();
-}
-
-} // namespace WebCore
diff --git a/Source/core/rendering/animation/WebAnimationProvider.h b/Source/core/rendering/animation/WebAnimationProvider.h
deleted file mode 100644
index 724de2e..0000000
--- a/Source/core/rendering/animation/WebAnimationProvider.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2013 Intel Corporation. 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 APPLE INC. ``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 APPLE COMPUTER, INC. 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.
- */
-
-#ifndef WebAnimationProvider_h
-#define WebAnimationProvider_h
-
-#include "CSSPropertyNames.h"
-#include "core/platform/animation/KeyframeValueList.h"
-#include "wtf/HashMap.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace blink {
-class WebAnimation;
-}
-
-namespace WebCore {
-class CSSAnimationData;
-class IntSize;
-class KeyframeList;
-class RenderStyle;
-
-struct WebAnimations {
-    WebAnimations();
-    ~WebAnimations();
-    WebAnimations(const WebAnimations&);
-    bool isEmpty() const;
-    OwnPtr<blink::WebAnimation> m_transformAnimation;
-    OwnPtr<blink::WebAnimation> m_opacityAnimation;
-    OwnPtr<blink::WebAnimation> m_filterAnimation;
-};
-
-class WebAnimationProvider {
-    WTF_MAKE_NONCOPYABLE(WebAnimationProvider); WTF_MAKE_FAST_ALLOCATED;
-public:
-    WebAnimationProvider();
-    ~WebAnimationProvider();
-
-    int getWebAnimationId(const String& animationName) const;
-    int getWebAnimationId(CSSPropertyID) const;
-    WebAnimations startAnimation(double timeOffset, const CSSAnimationData*, const KeyframeList&, bool hasTransform, const IntSize& boxSize);
-    WebAnimations startTransition(double timeOffset, CSSPropertyID, const RenderStyle* fromStyle, const RenderStyle* toStyle, bool hasTransform, bool hasFilter, const IntSize& boxSize, float fromOpacity, float toOpacity);
-
-private:
-    PassOwnPtr<blink::WebAnimation> createWebAnimationAndStoreId(const KeyframeValueList&, const IntSize& boxSize, const CSSAnimationData*, const String& animationName, double timeOffset);
-
-    typedef HashMap<String, int> AnimationIdMap;
-    AnimationIdMap m_animationIdMap;
-};
-
-} // namespace WebCore
-
-#endif // WebAnimationProvider_h
diff --git a/Source/core/rendering/line/BreakingContext.cpp b/Source/core/rendering/line/BreakingContext.cpp
new file mode 100644
index 0000000..95bd0a7
--- /dev/null
+++ b/Source/core/rendering/line/BreakingContext.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Adobe Systems Incorporated.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/rendering/line/BreakingContextInlineHeaders.h"
+
+namespace WebCore {
+
+InlineIterator BreakingContext::handleEndOfLine()
+{
+    ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo();
+    bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments();
+
+    if (m_lineBreak == m_resolver.position() && (!m_lineBreak.object() || !m_lineBreak.object()->isBR()) && segmentAllowsOverflow) {
+        // we just add as much as possible
+        if (m_blockStyle->whiteSpace() == PRE && !m_current.offset()) {
+            m_lineBreak.moveTo(m_lastObject, m_lastObject->isText() ? m_lastObject->length() : 0);
+        } else if (m_lineBreak.object()) {
+            // Don't ever break in the middle of a word if we can help it.
+            // There's no room at all. We just have to be on this line,
+            // even though we'll spill out.
+            m_lineBreak.moveTo(m_current.object(), m_current.offset());
+        }
+    }
+
+    // FIXME Bug 100049: We do not need to consume input in a multi-segment line
+    // unless no segment will.
+    // make sure we consume at least one char/object.
+    if (m_lineBreak == m_resolver.position() && segmentAllowsOverflow)
+        m_lineBreak.increment();
+
+    // Sanity check our midpoints.
+    m_lineMidpointState.checkMidpoints(m_lineBreak);
+
+    m_trailingObjects.updateMidpointsForTrailingBoxes(m_lineMidpointState, m_lineBreak, TrailingObjects::CollapseFirstSpace);
+
+    // We might have made lineBreak an iterator that points past the end
+    // of the object. Do this adjustment to make it point to the start
+    // of the next object instead to avoid confusing the rest of the
+    // code.
+    if (m_lineBreak.offset()) {
+        // This loop enforces the invariant that line breaks should never point
+        // at an empty inline. See http://crbug.com/305904.
+        do {
+            m_lineBreak.setOffset(m_lineBreak.offset() - 1);
+            m_lineBreak.increment();
+        } while (!m_lineBreak.atEnd() && isEmptyInline(m_lineBreak.object()));
+    }
+
+    return m_lineBreak;
+}
+
+}
diff --git a/Source/core/rendering/line/BreakingContextInlineHeaders.h b/Source/core/rendering/line/BreakingContextInlineHeaders.h
index 989d7e3..5d74124 100644
--- a/Source/core/rendering/line/BreakingContextInlineHeaders.h
+++ b/Source/core/rendering/line/BreakingContextInlineHeaders.h
@@ -26,43 +26,24 @@
 
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/InlineTextBox.h"
-#include "core/rendering/LineWidth.h"
 #include "core/rendering/RenderCombineText.h"
 #include "core/rendering/RenderInline.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderListMarker.h"
+#include "core/rendering/RenderRubyRun.h"
 #include "core/rendering/break_lines.h"
+#include "core/rendering/line/LineBreaker.h"
 #include "core/rendering/line/LineInfo.h"
+#include "core/rendering/line/LineWidth.h"
+#include "core/rendering/line/TrailingObjects.h"
 #include "core/rendering/shapes/ShapeInsideInfo.h"
 #include "core/rendering/svg/RenderSVGInlineText.h"
 
 namespace WebCore {
 
-using namespace std;
-using namespace WTF;
-using namespace Unicode;
-
 // We don't let our line box tree for a single line get any deeper than this.
 const unsigned cMaxLineDepth = 200;
 
-struct RenderTextInfo {
-    // Destruction of m_layout requires TextLayout to be a complete type, so the constructor and destructor are made non-inline to avoid compilation errors.
-    RenderTextInfo();
-    ~RenderTextInfo();
-
-    RenderText* m_text;
-    OwnPtr<TextLayout> m_layout;
-    LazyLineBreakIterator m_lineBreakIterator;
-    const Font* m_font;
-
-    void createLayout(RenderText* renderText, float xPos, bool collapseWhiteSpace)
-    {
-#if OS(MACOSX)
-        m_layout = m_font->createLayoutForMacComplexText(RenderBlockFlow::constructTextRun(renderText, *m_font, renderText, renderText->style()), renderText->textLength(), xPos, collapseWhiteSpace);
-#else
-        m_layout = nullptr;
-#endif
-    }
-};
-
 class WordMeasurement {
 public:
     WordMeasurement()
@@ -80,129 +61,6 @@
     HashSet<const SimpleFontData*> fallbackFonts;
 };
 
-// Don't call this directly. Use one of the descriptive helper functions below.
-inline void deprecatedAddMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
-{
-    if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
-        lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
-
-    InlineIterator* midpoints = lineMidpointState.midpoints.data();
-    midpoints[lineMidpointState.numMidpoints++] = midpoint;
-}
-
-inline void startIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
-{
-    ASSERT(!(lineMidpointState.numMidpoints % 2));
-    deprecatedAddMidpoint(lineMidpointState, midpoint);
-}
-
-inline void stopIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
-{
-    ASSERT(lineMidpointState.numMidpoints % 2);
-    deprecatedAddMidpoint(lineMidpointState, midpoint);
-}
-
-// When ignoring spaces, this needs to be called for objects that need line boxes such as RenderInlines or
-// hard line breaks to ensure that they're not ignored.
-inline void ensureLineBoxInsideIgnoredSpaces(LineMidpointState& lineMidpointState, RenderObject* renderer)
-{
-    InlineIterator midpoint(0, renderer, 0);
-    stopIgnoringSpaces(lineMidpointState, midpoint);
-    startIgnoringSpaces(lineMidpointState, midpoint);
-}
-
-// Adding a pair of midpoints before a character will split it out into a new line box.
-inline void ensureCharacterGetsLineBox(LineMidpointState& lineMidpointState, InlineIterator& textParagraphSeparator)
-{
-    InlineIterator midpoint(0, textParagraphSeparator.object(), textParagraphSeparator.m_pos);
-    startIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.object(), textParagraphSeparator.m_pos - 1));
-    stopIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.object(), textParagraphSeparator.m_pos));
-}
-
-class TrailingObjects {
-public:
-    TrailingObjects();
-    void setTrailingWhitespace(RenderText*);
-    void clear();
-    void appendBoxIfNeeded(RenderBox*);
-
-    enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
-
-    void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
-
-private:
-    RenderText* m_whitespace;
-    Vector<RenderBox*, 4> m_boxes;
-};
-
-TrailingObjects::TrailingObjects()
-    : m_whitespace(0)
-{
-}
-
-inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
-{
-    ASSERT(whitespace);
-    m_whitespace = whitespace;
-}
-
-inline void TrailingObjects::clear()
-{
-    m_whitespace = 0;
-    // Using resize(0) rather than clear() here saves 2% on
-    // PerformanceTests/Layout/line-layout.html because we avoid freeing and
-    // re-allocating the underlying buffer repeatedly.
-    m_boxes.resize(0);
-}
-
-inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
-{
-    if (m_whitespace)
-        m_boxes.append(box);
-}
-
-void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
-{
-    if (!m_whitespace)
-        return;
-
-    // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
-    // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
-    if (lineMidpointState.numMidpoints % 2) {
-        // Find the trailing space object's midpoint.
-        int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
-        for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].object() != m_whitespace; --trailingSpaceMidpoint) { }
-        ASSERT(trailingSpaceMidpoint >= 0);
-        if (collapseFirstSpace == CollapseFirstSpace)
-            lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
-
-        // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
-        // ignoring spaces.
-        size_t currentMidpoint = trailingSpaceMidpoint + 1;
-        for (size_t i = 0; i < m_boxes.size(); ++i) {
-            if (currentMidpoint >= lineMidpointState.numMidpoints) {
-                // We don't have a midpoint for this box yet.
-                ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
-            } else {
-                ASSERT(lineMidpointState.midpoints[currentMidpoint].object() == m_boxes[i]);
-                ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].object() == m_boxes[i]);
-            }
-            currentMidpoint += 2;
-        }
-    } else if (!lBreak.object()) {
-        ASSERT(m_whitespace->isText());
-        ASSERT(collapseFirstSpace == CollapseFirstSpace);
-        // Add a new end midpoint that stops right at the very end.
-        unsigned length = m_whitespace->textLength();
-        unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
-        InlineIterator endMid(0, m_whitespace, pos);
-        startIgnoringSpaces(lineMidpointState, endMid);
-        for (size_t i = 0; i < m_boxes.size(); ++i) {
-            ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
-        }
-    }
-}
-
 class BreakingContext {
 public:
     BreakingContext(InlineBidiResolver& resolver, LineInfo& inLineInfo, LineWidth& lineWidth, RenderTextInfo& inRenderTextInfo, FloatingObject* inLastFloatFromPreviousLine, bool appliedStartWidth, RenderBlockFlow* block)
@@ -309,8 +167,6 @@
     TrailingObjects m_trailingObjects;
 };
 
-enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
-
 inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo, WhitespacePosition whitespacePosition)
 {
     // CSS2 16.6.1
@@ -441,7 +297,7 @@
         // need to check for floats to clear - so if we're ignoring spaces, stop ignoring them and add a
         // run for this object.
         if (m_ignoringSpaces && m_currentStyle->clear() != CNONE)
-            ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, br);
+            m_lineMidpointState.ensureLineBoxInsideIgnoredSpaces(br);
 
         if (!m_lineInfo.isEmpty())
             clear = m_currentStyle->clear();
@@ -495,7 +351,7 @@
     RenderBox* box = toRenderBox(m_current.object());
     bool isInlineType = box->style()->isOriginalDisplayInlineType();
     if (!isInlineType) {
-        m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight()));
+        m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent());
     } else {
         // If our original display was an INLINE type, then we can go ahead
         // and determine our static y position now.
@@ -506,7 +362,7 @@
     // then start ignoring spaces again.
     if (isInlineType || box->container()->isRenderInline()) {
         if (m_ignoringSpaces)
-            ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, box);
+            m_lineMidpointState.ensureLineBoxInsideIgnoredSpaces(box);
         m_trailingObjects.appendBoxIfNeeded(box);
     } else {
         positionedObjects.append(box);
@@ -527,7 +383,7 @@
     if (m_floatsFitOnLine && m_width.fitsOnLine(m_block->logicalWidthForFloat(floatingObject))) {
         m_block->positionNewFloatOnLine(floatingObject, m_lastFloatFromPreviousLine, m_lineInfo, m_width);
         if (m_lineBreak.object() == m_current.object()) {
-            ASSERT(!m_lineBreak.m_pos);
+            ASSERT(!m_lineBreak.offset());
             m_lineBreak.increment();
         }
     } else {
@@ -549,7 +405,7 @@
         RenderText* nextText = toRenderText(next);
         UChar nextChar = nextText->characterAt(0);
         if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
-            startIgnoringSpaces(lineMidpointState, InlineIterator(0, o, 0));
+            lineMidpointState.startIgnoringSpaces(InlineIterator(0, o, 0));
             return true;
         }
     }
@@ -576,7 +432,7 @@
             m_lineInfo.setEmpty(false, m_block, &m_width);
         if (m_ignoringSpaces) {
             m_trailingObjects.clear();
-            ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, m_current.object());
+            m_lineMidpointState.ensureLineBoxInsideIgnoredSpaces(m_current.object());
         } else if (m_blockStyle->collapseWhiteSpace() && m_resolver.position().object() == m_current.object()
             && shouldSkipWhitespaceAfterStartObject(m_block, m_current.object(), m_lineMidpointState)) {
             // Like with list markers, we start ignoring spaces to make sure that any
@@ -603,7 +459,7 @@
     }
 
     if (m_ignoringSpaces)
-        stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.object(), 0));
+        m_lineMidpointState.stopIgnoringSpaces(InlineIterator(0, m_current.object(), 0));
 
     m_lineInfo.setEmpty(false, m_block, &m_width);
     m_ignoringSpaces = false;
@@ -633,7 +489,7 @@
 
 inline bool iteratorIsBeyondEndOfRenderCombineText(const InlineIterator& iter, RenderCombineText* renderer)
 {
-    return iter.object() == renderer && iter.m_pos >= renderer->textLength();
+    return iter.object() == renderer && iter.offset() >= renderer->textLength();
 }
 
 inline void nextCharacter(UChar& currentCharacter, UChar& lastCharacter, UChar& secondToLastCharacter)
@@ -692,22 +548,27 @@
     width.updateAvailableWidth();
 }
 
-inline float measureHyphenWidth(RenderText* renderer, const Font& font)
+inline float measureHyphenWidth(RenderText* renderer, const Font& font, TextDirection textDirection)
 {
     RenderStyle* style = renderer->style();
-    return font.width(RenderBlockFlow::constructTextRun(renderer, font, style->hyphenString().string(), style));
+    return font.width(RenderBlockFlow::constructTextRun(renderer, font,
+        style->hyphenString().string(), style, textDirection));
 }
 
-ALWAYS_INLINE float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace, HashSet<const SimpleFontData*>* fallbackFonts = 0, TextLayout* layout = 0)
+ALWAYS_INLINE TextDirection textDirectionFromUnicode(WTF::Unicode::Direction direction)
 {
+    return direction == WTF::Unicode::RightToLeft
+        || direction == WTF::Unicode::RightToLeftArabic ? RTL : LTR;
+}
+
+ALWAYS_INLINE float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, WTF::Unicode::Direction direction, bool collapseWhiteSpace, HashSet<const SimpleFontData*>* fallbackFonts = 0)
+{
+    TextDirection textDirection = textDirectionFromUnicode(direction);
     GlyphOverflow glyphOverflow;
     if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
-        return text->width(from, len, font, xPos, fallbackFonts, &glyphOverflow);
+        return text->width(from, len, font, xPos, textDirection, fallbackFonts, &glyphOverflow);
 
-    if (layout)
-        return Font::width(*layout, from, len, fallbackFonts);
-
-    TextRun run = RenderBlockFlow::constructTextRun(text, font, text, from, len, text->style());
+    TextRun run = RenderBlockFlow::constructTextRun(text, font, text, from, len, text->style(), textDirection);
     run.setCharactersLength(text->textLength() - from);
     ASSERT(run.charactersLength() >= run.length());
 
@@ -719,13 +580,20 @@
 
 inline bool BreakingContext::handleText(WordMeasurements& wordMeasurements, bool& hyphenated)
 {
-    if (!m_current.m_pos)
+    if (!m_current.offset())
         m_appliedStartWidth = false;
 
     RenderText* renderText = toRenderText(m_current.object());
 
     bool isSVGText = renderText->isSVGInlineText();
 
+    // If we have left a no-wrap inline and entered an autowrap inline while ignoring spaces
+    // then we need to mark the start of the autowrap inline as a potential linebreak now.
+    if (m_autoWrap && !RenderStyle::autoWrap(m_lastWS) && m_ignoringSpaces) {
+        m_width.commit();
+        m_lineBreak.moveToStartOf(m_current.object());
+    }
+
     if (renderText->style()->hasTextCombine() && m_current.object()->isCombineText() && !toRenderCombineText(m_current.object())->isCombined()) {
         RenderCombineText* combineRenderer = toRenderCombineText(m_current.object());
         combineRenderer->combineText();
@@ -741,7 +609,7 @@
     const Font& font = style->font();
     bool isFixedPitch = font.isFixedPitch();
 
-    unsigned lastSpace = m_current.m_pos;
+    unsigned lastSpace = m_current.offset();
     float wordSpacing = m_currentStyle->wordSpacing();
     float lastSpaceWordSpacing = 0;
     float wordSpacingForWordMeasurement = 0;
@@ -763,28 +631,28 @@
     if (renderText->isWordBreak()) {
         m_width.commit();
         m_lineBreak.moveToStartOf(m_current.object());
-        ASSERT(m_current.m_pos == renderText->textLength());
+        ASSERT(m_current.offset() == renderText->textLength());
     }
 
     if (m_renderTextInfo.m_text != renderText) {
         m_renderTextInfo.m_text = renderText;
         m_renderTextInfo.m_font = &font;
-        m_renderTextInfo.createLayout(renderText, m_width.currentWidth(), m_collapseWhiteSpace);
         m_renderTextInfo.m_lineBreakIterator.resetStringAndReleaseIterator(renderText->text(), style->locale());
-    } else if (m_renderTextInfo.m_layout && m_renderTextInfo.m_font != &font) {
+    } else if (m_renderTextInfo.m_font != &font) {
         m_renderTextInfo.m_font = &font;
-        m_renderTextInfo.createLayout(renderText, m_width.currentWidth(), m_collapseWhiteSpace);
     }
 
-    TextLayout* textLayout = m_renderTextInfo.m_layout.get();
-
-    // Non-zero only when kerning is enabled and TextLayout isn't used, in which case we measure
+    // Non-zero only when kerning is enabled, in which case we measure
     // words with their trailing space, then subtract its width.
-    float wordTrailingSpaceWidth = (font.typesettingFeatures() & Kerning) && !textLayout ? font.width(RenderBlockFlow::constructTextRun(renderText, font, &space, 1, style)) + wordSpacing : 0;
+    float wordTrailingSpaceWidth = (font.fontDescription().typesettingFeatures() & Kerning) ?
+        font.width(RenderBlockFlow::constructTextRun(
+            renderText, font, &space, 1, style,
+            textDirectionFromUnicode(m_resolver.position().direction()))) + wordSpacing
+        : 0;
 
     UChar lastCharacter = m_renderTextInfo.m_lineBreakIterator.lastCharacter();
     UChar secondToLastCharacter = m_renderTextInfo.m_lineBreakIterator.secondToLastCharacter();
-    for (; m_current.m_pos < renderText->textLength(); m_current.fastIncrementInTextNode()) {
+    for (; m_current.offset() < renderText->textLength(); m_current.fastIncrementInTextNode()) {
         bool previousCharacterIsSpace = m_currentCharacterIsSpace;
         bool previousCharacterShouldCollapseIfPreWap = m_currentCharacterShouldCollapseIfPreWap;
         UChar c = m_current.current();
@@ -794,7 +662,7 @@
             m_lineInfo.setEmpty(false, m_block, &m_width);
 
         if (c == softHyphen && m_autoWrap && !hyphenWidth) {
-            hyphenWidth = measureHyphenWidth(renderText, font);
+            hyphenWidth = measureHyphenWidth(renderText, font, textDirectionFromUnicode(m_resolver.position().direction()));
             m_width.addUncommittedWidth(hyphenWidth);
         }
 
@@ -802,12 +670,14 @@
 
         if ((breakAll || breakWords) && !midWordBreak) {
             wrapW += charWidth;
-            bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && m_current.m_pos + 1 < renderText->textLength() && U16_IS_TRAIL((*renderText)[m_current.m_pos + 1]);
-            charWidth = textWidth(renderText, m_current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, font, m_width.committedWidth() + wrapW, isFixedPitch, m_collapseWhiteSpace, 0, textLayout);
+            bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && m_current.offset() + 1 < renderText->textLength() && U16_IS_TRAIL((*renderText)[m_current.offset() + 1]);
+            charWidth = textWidth(renderText, m_current.offset(), midWordBreakIsBeforeSurrogatePair ? 2 : 1, font, m_width.committedWidth() + wrapW, isFixedPitch, m_resolver.position().direction(), m_collapseWhiteSpace, 0);
             midWordBreak = m_width.committedWidth() + wrapW + charWidth > m_width.availableWidth();
         }
 
-        bool betweenWords = c == '\n' || (m_currWS != PRE && !m_atStart && isBreakable(m_renderTextInfo.m_lineBreakIterator, m_current.m_pos, m_current.m_nextBreakablePosition));
+        int nextBreakablePosition = m_current.nextBreakablePosition();
+        bool betweenWords = c == '\n' || (m_currWS != PRE && !m_atStart && isBreakable(m_renderTextInfo.m_lineBreakIterator, m_current.offset(), nextBreakablePosition));
+        m_current.setNextBreakablePosition(nextBreakablePosition);
 
         if (betweenWords || midWordBreak) {
             bool stoppedIgnoringSpaces = false;
@@ -818,8 +688,8 @@
                     // new point.
                     m_ignoringSpaces = false;
                     wordSpacingForWordMeasurement = 0;
-                    lastSpace = m_current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
-                    stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.object(), m_current.m_pos));
+                    lastSpace = m_current.offset(); // e.g., "Foo    goo", don't add in any of the ignored spaces.
+                    m_lineMidpointState.stopIgnoringSpaces(InlineIterator(0, m_current.object(), m_current.offset()));
                     stoppedIgnoringSpaces = true;
                 } else {
                     // Just keep ignoring these spaces.
@@ -832,14 +702,14 @@
             WordMeasurement& wordMeasurement = wordMeasurements.last();
 
             wordMeasurement.renderer = renderText;
-            wordMeasurement.endOffset = m_current.m_pos;
+            wordMeasurement.endOffset = m_current.offset();
             wordMeasurement.startOffset = lastSpace;
 
             float additionalTmpW;
             if (wordTrailingSpaceWidth && c == ' ')
-                additionalTmpW = textWidth(renderText, lastSpace, m_current.m_pos + 1 - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) - wordTrailingSpaceWidth;
+                additionalTmpW = textWidth(renderText, lastSpace, m_current.offset() + 1 - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_resolver.position().direction(), m_collapseWhiteSpace, &wordMeasurement.fallbackFonts) - wordTrailingSpaceWidth;
             else
-                additionalTmpW = textWidth(renderText, lastSpace, m_current.m_pos - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
+                additionalTmpW = textWidth(renderText, lastSpace, m_current.offset() - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_resolver.position().direction(), m_collapseWhiteSpace, &wordMeasurement.fallbackFonts);
 
             wordMeasurement.width = additionalTmpW + wordSpacingForWordMeasurement;
             additionalTmpW += lastSpaceWordSpacing;
@@ -862,7 +732,7 @@
                 // as candidate width for this line.
                 bool lineWasTooWide = false;
                 if (m_width.fitsOnLine() && m_currentCharacterIsSpace && m_currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) {
-                    float charWidth = textWidth(renderText, m_current.m_pos, 1, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) + (applyWordSpacing ? wordSpacing : 0);
+                    float charWidth = textWidth(renderText, m_current.offset(), 1, font, m_width.currentWidth(), isFixedPitch, m_resolver.position().direction(), m_collapseWhiteSpace, &wordMeasurement.fallbackFonts) + (applyWordSpacing ? wordSpacing : 0);
                     // Check if line is too big even without the extra space
                     // at the end of the line. If it is not, do nothing.
                     // If the line needs the extra whitespace to be too long,
@@ -870,23 +740,23 @@
                     // additional whitespace.
                     if (!m_width.fitsOnLine(charWidth)) {
                         lineWasTooWide = true;
-                        m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+                        m_lineBreak.moveTo(m_current.object(), m_current.offset(), m_current.nextBreakablePosition());
                         skipTrailingWhitespace(m_lineBreak, m_lineInfo);
                     }
                 }
                 if (lineWasTooWide || !m_width.fitsOnLine()) {
                     if (m_lineBreak.atTextParagraphSeparator()) {
-                        if (!stoppedIgnoringSpaces && m_current.m_pos > 0)
-                            ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
+                        if (!stoppedIgnoringSpaces && m_current.offset() > 0)
+                            m_lineMidpointState.ensureCharacterGetsLineBox(m_current);
                         m_lineBreak.increment();
                         m_lineInfo.setPreviousLineBrokeCleanly(true);
-                        wordMeasurement.endOffset = m_lineBreak.m_pos;
+                        wordMeasurement.endOffset = m_lineBreak.offset();
                     }
-                    if (m_lineBreak.object() && m_lineBreak.m_pos && m_lineBreak.object()->isText() && toRenderText(m_lineBreak.object())->textLength() && toRenderText(m_lineBreak.object())->characterAt(m_lineBreak.m_pos - 1) == softHyphen)
+                    if (m_lineBreak.object() && m_lineBreak.offset() && m_lineBreak.object()->isText() && toRenderText(m_lineBreak.object())->textLength() && toRenderText(m_lineBreak.object())->characterAt(m_lineBreak.offset() - 1) == softHyphen)
                         hyphenated = true;
-                    if (m_lineBreak.m_pos && m_lineBreak.m_pos != (unsigned)wordMeasurement.endOffset && !wordMeasurement.width) {
+                    if (m_lineBreak.offset() && m_lineBreak.offset() != (unsigned)wordMeasurement.endOffset && !wordMeasurement.width) {
                         if (charWidth) {
-                            wordMeasurement.endOffset = m_lineBreak.m_pos;
+                            wordMeasurement.endOffset = m_lineBreak.offset();
                             wordMeasurement.width = charWidth;
                         }
                     }
@@ -907,9 +777,9 @@
             }
 
             if (c == '\n' && m_preservesNewline) {
-                if (!stoppedIgnoringSpaces && m_current.m_pos > 0)
-                    ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
-                m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+                if (!stoppedIgnoringSpaces && m_current.offset())
+                    m_lineMidpointState.ensureCharacterGetsLineBox(m_current);
+                m_lineBreak.moveTo(m_current.object(), m_current.offset(), m_current.nextBreakablePosition());
                 m_lineBreak.increment();
                 m_lineInfo.setPreviousLineBrokeCleanly(true);
                 return true;
@@ -918,23 +788,23 @@
             if (m_autoWrap && betweenWords) {
                 m_width.commit();
                 wrapW = 0;
-                m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+                m_lineBreak.moveTo(m_current.object(), m_current.offset(), m_current.nextBreakablePosition());
                 // Auto-wrapping text should not wrap in the middle of a word once it has had an
                 // opportunity to break after a word.
                 breakWords = false;
             }
 
-            if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) {
+            if (midWordBreak && !U16_IS_TRAIL(c) && !(WTF::Unicode::category(c) & (WTF::Unicode::Mark_NonSpacing | WTF::Unicode::Mark_Enclosing | WTF::Unicode::Mark_SpacingCombining))) {
                 // Remember this as a breakable position in case
                 // adding the end width forces a break.
-                m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+                m_lineBreak.moveTo(m_current.object(), m_current.offset(), m_current.nextBreakablePosition());
                 midWordBreak &= (breakWords || breakAll);
             }
 
             if (betweenWords) {
                 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
                 wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurement.width) ? wordSpacing : 0;
-                lastSpace = m_current.m_pos;
+                lastSpace = m_current.offset();
             }
 
             if (!m_ignoringSpaces && m_currentStyle->collapseWhiteSpace()) {
@@ -947,7 +817,7 @@
                     // We just entered a mode where we are ignoring
                     // spaces. Create a midpoint to terminate the run
                     // before the second space.
-                    startIgnoringSpaces(m_lineMidpointState, m_startOfIgnoredSpaces);
+                    m_lineMidpointState.startIgnoringSpaces(m_startOfIgnoredSpaces);
                     m_trailingObjects.updateMidpointsForTrailingBoxes(m_lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
                 }
             }
@@ -957,24 +827,24 @@
             m_ignoringSpaces = false;
             lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
             wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurements.last().width) ? wordSpacing : 0;
-            lastSpace = m_current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
-            stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.object(), m_current.m_pos));
+            lastSpace = m_current.offset(); // e.g., "Foo    goo", don't add in any of the ignored spaces.
+            m_lineMidpointState.stopIgnoringSpaces(InlineIterator(0, m_current.object(), m_current.offset()));
         }
 
-        if (isSVGText && m_current.m_pos > 0) {
+        if (isSVGText && m_current.offset()) {
             // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
-            if (toRenderSVGInlineText(renderText)->characterStartsNewTextChunk(m_current.m_pos))
-                ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
+            if (toRenderSVGInlineText(renderText)->characterStartsNewTextChunk(m_current.offset()))
+                m_lineMidpointState.ensureCharacterGetsLineBox(m_current);
         }
 
         if (m_currentCharacterIsSpace && !previousCharacterIsSpace) {
             m_startOfIgnoredSpaces.setObject(m_current.object());
-            m_startOfIgnoredSpaces.m_pos = m_current.m_pos;
+            m_startOfIgnoredSpaces.setOffset(m_current.offset());
         }
 
         if (!m_currentCharacterIsSpace && previousCharacterShouldCollapseIfPreWap) {
             if (m_autoWrap && m_currentStyle->breakOnlyAfterWhiteSpace())
-                m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+                m_lineBreak.moveTo(m_current.object(), m_current.offset(), m_current.nextBreakablePosition());
         }
 
         if (m_collapseWhiteSpace && m_currentCharacterIsSpace && !m_ignoringSpaces)
@@ -993,9 +863,9 @@
     wordMeasurement.renderer = renderText;
 
     // IMPORTANT: current.m_pos is > length here!
-    float additionalTmpW = m_ignoringSpaces ? 0 : textWidth(renderText, lastSpace, m_current.m_pos - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
+    float additionalTmpW = m_ignoringSpaces ? 0 : textWidth(renderText, lastSpace, m_current.offset() - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_resolver.position().direction(), m_collapseWhiteSpace, &wordMeasurement.fallbackFonts);
     wordMeasurement.startOffset = lastSpace;
-    wordMeasurement.endOffset = m_current.m_pos;
+    wordMeasurement.endOffset = m_current.offset();
     wordMeasurement.width = m_ignoringSpaces ? 0 : additionalTmpW + wordSpacingForWordMeasurement;
     additionalTmpW += lastSpaceWordSpacing;
     m_width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(m_current.object(), !m_appliedStartWidth, m_includeEndWidth));
@@ -1075,69 +945,14 @@
     }
 }
 
-inline void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
+inline IndentTextOrNot requiresIndent(bool isFirstLine, bool isAfterHardLineBreak, RenderStyle* style)
 {
-    // Check to see if our last midpoint is a start point beyond the line break. If so,
-    // shave it off the list, and shave off a trailing space if the previous end point doesn't
-    // preserve whitespace.
-    if (lBreak.object() && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
-        InlineIterator* midpoints = lineMidpointState.midpoints.data();
-        InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
-        const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
-        InlineIterator currpoint = endpoint;
-        while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
-            currpoint.increment();
-        if (currpoint == lBreak) {
-            // We hit the line break before the start point. Shave off the start point.
-            lineMidpointState.numMidpoints--;
-            if (endpoint.object()->style()->collapseWhiteSpace() && endpoint.object()->isText())
-                endpoint.m_pos--;
-        }
-    }
-}
+    if (isFirstLine)
+        return IndentText;
+    if (isAfterHardLineBreak && style->textIndentLine() == TextIndentEachLine)
+        return IndentText;
 
-InlineIterator BreakingContext::handleEndOfLine()
-{
-    ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo();
-    bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments();
-
-    if (m_lineBreak == m_resolver.position() && (!m_lineBreak.object() || !m_lineBreak.object()->isBR()) && segmentAllowsOverflow) {
-        // we just add as much as possible
-        if (m_blockStyle->whiteSpace() == PRE && !m_current.m_pos) {
-            m_lineBreak.moveTo(m_lastObject, m_lastObject->isText() ? m_lastObject->length() : 0);
-        } else if (m_lineBreak.object()) {
-            // Don't ever break in the middle of a word if we can help it.
-            // There's no room at all. We just have to be on this line,
-            // even though we'll spill out.
-            m_lineBreak.moveTo(m_current.object(), m_current.m_pos);
-        }
-    }
-
-    // FIXME Bug 100049: We do not need to consume input in a multi-segment line
-    // unless no segment will.
-    // make sure we consume at least one char/object.
-    if (m_lineBreak == m_resolver.position() && segmentAllowsOverflow)
-        m_lineBreak.increment();
-
-    // Sanity check our midpoints.
-    checkMidpoints(m_lineMidpointState, m_lineBreak);
-
-    m_trailingObjects.updateMidpointsForTrailingBoxes(m_lineMidpointState, m_lineBreak, TrailingObjects::CollapseFirstSpace);
-
-    // We might have made lineBreak an iterator that points past the end
-    // of the object. Do this adjustment to make it point to the start
-    // of the next object instead to avoid confusing the rest of the
-    // code.
-    if (m_lineBreak.m_pos > 0) {
-        // This loop enforces the invariant that line breaks should never point
-        // at an empty inline. See http://crbug.com/305904.
-        do {
-            m_lineBreak.m_pos--;
-            m_lineBreak.increment();
-        } while (!m_lineBreak.atEnd() && isEmptyInline(m_lineBreak.object()));
-    }
-
-    return m_lineBreak;
+    return DoNotIndentText;
 }
 
 }
diff --git a/Source/core/rendering/line/LineBreaker.cpp b/Source/core/rendering/line/LineBreaker.cpp
new file mode 100644
index 0000000..f6c50cb
--- /dev/null
+++ b/Source/core/rendering/line/LineBreaker.cpp
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/rendering/line/LineBreaker.h"
+
+#include "core/rendering/line/BreakingContextInlineHeaders.h"
+
+namespace WebCore {
+
+void LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo& lineInfo,
+    FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
+{
+    while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) {
+        RenderObject* object = resolver.position().object();
+        if (object->isOutOfFlowPositioned()) {
+            setStaticPositions(m_block, toRenderBox(object));
+            if (object->style()->isOriginalDisplayInlineType()) {
+                resolver.runs().addRun(createRun(0, 1, object, resolver));
+                lineInfo.incrementRunsFromLeadingWhitespace();
+            }
+        } else if (object->isFloating()) {
+            m_block->positionNewFloatOnLine(m_block->insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, lineInfo, width);
+        } else if (object->isText() && object->style()->hasTextCombine() && object->isCombineText() && !toRenderCombineText(object)->isCombined()) {
+            toRenderCombineText(object)->combineText();
+            if (toRenderCombineText(object)->isCombined())
+                continue;
+        }
+        resolver.position().increment(&resolver);
+    }
+    resolver.commitExplicitEmbedding();
+}
+
+void LineBreaker::reset()
+{
+    m_positionedObjects.clear();
+    m_hyphenated = false;
+    m_clear = CNONE;
+}
+
+InlineIterator LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
+{
+    ShapeInsideInfo* shapeInsideInfo = m_block->layoutShapeInsideInfo();
+
+    if (!shapeInsideInfo || !shapeInsideInfo->lineOverlapsShapeBounds())
+        return nextSegmentBreak(resolver, lineInfo, renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
+
+    InlineIterator end = resolver.position();
+    InlineIterator oldEnd = end;
+
+    if (!shapeInsideInfo->hasSegments()) {
+        end = nextSegmentBreak(resolver, lineInfo, renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
+        resolver.setPositionIgnoringNestedIsolates(oldEnd);
+        return oldEnd;
+    }
+
+    const SegmentList& segments = shapeInsideInfo->segments();
+    SegmentRangeList& segmentRanges = shapeInsideInfo->segmentRanges();
+
+    for (unsigned i = 0; i < segments.size() && !end.atEnd(); i++) {
+        const InlineIterator segmentStart = resolver.position();
+        end = nextSegmentBreak(resolver, lineInfo, renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
+
+        ASSERT(segmentRanges.size() == i);
+        if (resolver.position().atEnd()) {
+            segmentRanges.append(LineSegmentRange(segmentStart, end));
+            break;
+        }
+        if (resolver.position() == end) {
+            // Nothing fit this segment
+            end = segmentStart;
+            segmentRanges.append(LineSegmentRange(segmentStart, segmentStart));
+            resolver.setPositionIgnoringNestedIsolates(segmentStart);
+        } else {
+            // Note that resolver.position is already skipping some of the white space at the beginning of the line,
+            // so that's why segmentStart might be different than resolver.position().
+            LineSegmentRange range(resolver.position(), end);
+            segmentRanges.append(range);
+            resolver.setPosition(end, numberOfIsolateAncestors(end));
+
+            if (lineInfo.previousLineBrokeCleanly()) {
+                // If we hit a new line break, just stop adding anything to this line.
+                break;
+            }
+        }
+    }
+    resolver.setPositionIgnoringNestedIsolates(oldEnd);
+    return end;
+}
+
+InlineIterator LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
+{
+    reset();
+
+    ASSERT(resolver.position().root() == m_block);
+
+    bool appliedStartWidth = resolver.position().offset() > 0;
+
+    LineWidth width(*m_block, lineInfo.isFirstLine(), requiresIndent(lineInfo.isFirstLine(), lineInfo.previousLineBrokeCleanly(), m_block->style()));
+
+    skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width);
+
+    if (resolver.position().atEnd())
+        return resolver.position();
+
+    BreakingContext context(resolver, lineInfo, width, renderTextInfo, lastFloatFromPreviousLine, appliedStartWidth, m_block);
+
+    while (context.currentObject()) {
+        context.initializeForCurrentObject();
+        if (context.currentObject()->isBR()) {
+            context.handleBR(m_clear);
+        } else if (context.currentObject()->isOutOfFlowPositioned()) {
+            context.handleOutOfFlowPositioned(m_positionedObjects);
+        } else if (context.currentObject()->isFloating()) {
+            context.handleFloat();
+        } else if (context.currentObject()->isRenderInline()) {
+            context.handleEmptyInline();
+        } else if (context.currentObject()->isReplaced()) {
+            context.handleReplaced();
+        } else if (context.currentObject()->isText()) {
+            if (context.handleText(wordMeasurements, m_hyphenated)) {
+                // We've hit a hard text line break. Our line break iterator is updated, so go ahead and early return.
+                return context.lineBreak();
+            }
+        } else {
+            ASSERT_NOT_REACHED();
+        }
+
+        if (context.atEnd())
+            return context.handleEndOfLine();
+
+        context.commitAndUpdateLineBreakIfNeeded();
+
+        if (context.atEnd())
+            return context.handleEndOfLine();
+
+        context.increment();
+    }
+
+    context.clearLineBreakIfFitsOnLine();
+
+    return context.handleEndOfLine();
+}
+
+}
diff --git a/Source/core/rendering/line/LineBreaker.h b/Source/core/rendering/line/LineBreaker.h
new file mode 100644
index 0000000..df320ea
--- /dev/null
+++ b/Source/core/rendering/line/LineBreaker.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef LineBreaker_h
+#define LineBreaker_h
+
+#include "core/rendering/InlineIterator.h"
+#include "core/rendering/line/LineInfo.h"
+#include "platform/text/TextBreakIterator.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
+
+class RenderText;
+
+struct RenderTextInfo {
+    RenderTextInfo();
+    ~RenderTextInfo();
+
+    RenderText* m_text;
+    LazyLineBreakIterator m_lineBreakIterator;
+    const Font* m_font;
+};
+
+class LineBreaker {
+public:
+    friend class BreakingContext;
+    LineBreaker(RenderBlockFlow* block)
+        : m_block(block)
+    {
+        reset();
+    }
+
+    InlineIterator nextLineBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
+
+    bool lineWasHyphenated() { return m_hyphenated; }
+    const Vector<RenderBox*>& positionedObjects() { return m_positionedObjects; }
+    EClear clear() { return m_clear; }
+private:
+    void reset();
+
+    InlineIterator nextSegmentBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
+    void skipLeadingWhitespace(InlineBidiResolver&, LineInfo&, FloatingObject* lastFloatFromPreviousLine, LineWidth&);
+
+    RenderBlockFlow* m_block;
+    bool m_hyphenated;
+    EClear m_clear;
+    Vector<RenderBox*> m_positionedObjects;
+};
+
+}
+
+#endif // LineBreaker_h
diff --git a/Source/core/rendering/line/LineInfo.h b/Source/core/rendering/line/LineInfo.h
index 337da11..bd5ad16 100644
--- a/Source/core/rendering/line/LineInfo.h
+++ b/Source/core/rendering/line/LineInfo.h
@@ -24,6 +24,8 @@
 #ifndef LineInfo_h
 #define LineInfo_h
 
+#include "core/rendering/line/LineWidth.h"
+
 namespace WebCore {
 
 class LineInfo {
diff --git a/Source/core/rendering/line/LineLayoutState.h b/Source/core/rendering/line/LineLayoutState.h
new file mode 100644
index 0000000..bc7480f
--- /dev/null
+++ b/Source/core/rendering/line/LineLayoutState.h
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Adobe Systems Incorporated. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef LineLayoutState_h
+#define LineLayoutState_h
+
+#include "core/rendering/RenderBlockFlow.h"
+#include "platform/geometry/LayoutRect.h"
+
+namespace WebCore {
+
+class RenderBlockFlow;
+
+// Like LayoutState for layout(), LineLayoutState keeps track of global information
+// during an entire linebox tree layout pass (aka layoutInlineChildren).
+class LineLayoutState {
+public:
+    LineLayoutState(bool fullLayout, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom, RenderFlowThread* flowThread)
+        : m_lastFloat(0)
+        , m_endLine(0)
+        , m_floatIndex(0)
+        , m_endLineLogicalTop(0)
+        , m_endLineMatched(false)
+        , m_checkForFloatsFromLastLine(false)
+        , m_hasInlineChild(false)
+        , m_isFullLayout(fullLayout)
+        , m_repaintLogicalTop(repaintLogicalTop)
+        , m_repaintLogicalBottom(repaintLogicalBottom)
+        , m_adjustedLogicalLineTop(0)
+        , m_usesRepaintBounds(false)
+        , m_flowThread(flowThread)
+    { }
+
+    void markForFullLayout() { m_isFullLayout = true; }
+    bool isFullLayout() const { return m_isFullLayout; }
+
+    bool usesRepaintBounds() const { return m_usesRepaintBounds; }
+
+    void setRepaintRange(LayoutUnit logicalHeight)
+    {
+        m_usesRepaintBounds = true;
+        m_repaintLogicalTop = m_repaintLogicalBottom = logicalHeight;
+    }
+
+    void updateRepaintRangeFromBox(RootInlineBox* box, LayoutUnit paginationDelta = 0)
+    {
+        m_usesRepaintBounds = true;
+        m_repaintLogicalTop = std::min(m_repaintLogicalTop, box->logicalTopVisualOverflow() + std::min<LayoutUnit>(paginationDelta, 0));
+        m_repaintLogicalBottom = std::max(m_repaintLogicalBottom, box->logicalBottomVisualOverflow() + std::max<LayoutUnit>(paginationDelta, 0));
+    }
+
+    bool endLineMatched() const { return m_endLineMatched; }
+    void setEndLineMatched(bool endLineMatched) { m_endLineMatched = endLineMatched; }
+
+    bool checkForFloatsFromLastLine() const { return m_checkForFloatsFromLastLine; }
+    void setCheckForFloatsFromLastLine(bool check) { m_checkForFloatsFromLastLine = check; }
+
+    bool hasInlineChild() const { return m_hasInlineChild; }
+    void setHasInlineChild(bool hasInlineChild) { m_hasInlineChild = hasInlineChild; }
+
+    LineInfo& lineInfo() { return m_lineInfo; }
+    const LineInfo& lineInfo() const { return m_lineInfo; }
+
+    LayoutUnit endLineLogicalTop() const { return m_endLineLogicalTop; }
+    void setEndLineLogicalTop(LayoutUnit logicalTop) { m_endLineLogicalTop = logicalTop; }
+
+    RootInlineBox* endLine() const { return m_endLine; }
+    void setEndLine(RootInlineBox* line) { m_endLine = line; }
+
+    FloatingObject* lastFloat() const { return m_lastFloat; }
+    void setLastFloat(FloatingObject* lastFloat) { m_lastFloat = lastFloat; }
+
+    Vector<RenderBlockFlow::FloatWithRect>& floats() { return m_floats; }
+
+    unsigned floatIndex() const { return m_floatIndex; }
+    void setFloatIndex(unsigned floatIndex) { m_floatIndex = floatIndex; }
+
+    LayoutUnit adjustedLogicalLineTop() const { return m_adjustedLogicalLineTop; }
+    void setAdjustedLogicalLineTop(LayoutUnit value) { m_adjustedLogicalLineTop = value; }
+
+    RenderFlowThread* flowThread() const { return m_flowThread; }
+    void setFlowThread(RenderFlowThread* thread) { m_flowThread = thread; }
+
+private:
+    Vector<RenderBlockFlow::FloatWithRect> m_floats;
+    FloatingObject* m_lastFloat;
+    RootInlineBox* m_endLine;
+    LineInfo m_lineInfo;
+    unsigned m_floatIndex;
+    LayoutUnit m_endLineLogicalTop;
+    bool m_endLineMatched;
+    bool m_checkForFloatsFromLastLine;
+    // Used as a performance optimization to avoid doing a full repaint when our floats
+    // change but we don't have any inline children.
+    bool m_hasInlineChild;
+
+    bool m_isFullLayout;
+
+    // FIXME: Should this be a range object instead of two ints?
+    LayoutUnit& m_repaintLogicalTop;
+    LayoutUnit& m_repaintLogicalBottom;
+
+    LayoutUnit m_adjustedLogicalLineTop;
+
+    bool m_usesRepaintBounds;
+
+    RenderFlowThread* m_flowThread;
+};
+
+}
+
+#endif // LineLayoutState_h
diff --git a/Source/core/rendering/LineWidth.cpp b/Source/core/rendering/line/LineWidth.cpp
similarity index 99%
rename from Source/core/rendering/LineWidth.cpp
rename to Source/core/rendering/line/LineWidth.cpp
index ea720e2..194267a 100644
--- a/Source/core/rendering/LineWidth.cpp
+++ b/Source/core/rendering/line/LineWidth.cpp
@@ -28,7 +28,7 @@
  */
 
 #include "config.h"
-#include "core/rendering/LineWidth.h"
+#include "core/rendering/line/LineWidth.h"
 
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderRubyRun.h"
diff --git a/Source/core/rendering/LineWidth.h b/Source/core/rendering/line/LineWidth.h
similarity index 100%
rename from Source/core/rendering/LineWidth.h
rename to Source/core/rendering/line/LineWidth.h
diff --git a/Source/core/rendering/line/TrailingObjects.cpp b/Source/core/rendering/line/TrailingObjects.cpp
new file mode 100644
index 0000000..c91e2ae
--- /dev/null
+++ b/Source/core/rendering/line/TrailingObjects.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Adobe Systems Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/rendering/line/TrailingObjects.h"
+
+#include "core/rendering/InlineIterator.h"
+
+namespace WebCore {
+
+void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
+{
+    if (!m_whitespace)
+        return;
+
+    // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
+    // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
+    if (lineMidpointState.numMidpoints() % 2) {
+        // Find the trailing space object's midpoint.
+        int trailingSpaceMidpoint = lineMidpointState.numMidpoints() - 1;
+        for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints()[trailingSpaceMidpoint].object() != m_whitespace; --trailingSpaceMidpoint) { }
+        ASSERT(trailingSpaceMidpoint >= 0);
+        if (collapseFirstSpace == CollapseFirstSpace)
+            lineMidpointState.midpoints()[trailingSpaceMidpoint].setOffset(lineMidpointState.midpoints()[trailingSpaceMidpoint].offset() -1);
+
+        // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
+        // ignoring spaces.
+        size_t currentMidpoint = trailingSpaceMidpoint + 1;
+        for (size_t i = 0; i < m_boxes.size(); ++i) {
+            if (currentMidpoint >= lineMidpointState.numMidpoints()) {
+                // We don't have a midpoint for this box yet.
+                lineMidpointState.ensureLineBoxInsideIgnoredSpaces(m_boxes[i]);
+            } else {
+                ASSERT(lineMidpointState.midpoints()[currentMidpoint].object() == m_boxes[i]);
+                ASSERT(lineMidpointState.midpoints()[currentMidpoint + 1].object() == m_boxes[i]);
+            }
+            currentMidpoint += 2;
+        }
+    } else if (!lBreak.object()) {
+        ASSERT(m_whitespace->isText());
+        ASSERT(collapseFirstSpace == CollapseFirstSpace);
+        // Add a new end midpoint that stops right at the very end.
+        unsigned length = m_whitespace->textLength();
+        unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
+        InlineIterator endMid(0, m_whitespace, pos);
+        lineMidpointState.startIgnoringSpaces(endMid);
+        for (size_t i = 0; i < m_boxes.size(); ++i) {
+            lineMidpointState.ensureLineBoxInsideIgnoredSpaces(m_boxes[i]);
+        }
+    }
+}
+
+}
diff --git a/Source/core/rendering/line/TrailingObjects.h b/Source/core/rendering/line/TrailingObjects.h
new file mode 100644
index 0000000..9bfd378
--- /dev/null
+++ b/Source/core/rendering/line/TrailingObjects.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Adobe Systems Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef TrailingObjects_h
+#define TrailingObjects_h
+
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class InlineIterator;
+class RenderBox;
+class RenderText;
+
+struct BidiRun;
+
+template <class Iterator, class Run> class BidiResolver;
+template <class Iterator> class MidpointState;
+typedef BidiResolver<InlineIterator, BidiRun> InlineBidiResolver;
+typedef MidpointState<InlineIterator> LineMidpointState;
+
+class TrailingObjects {
+public:
+    TrailingObjects()
+        : m_whitespace(0)
+    {
+    }
+
+    void setTrailingWhitespace(RenderText* whitespace)
+    {
+        ASSERT(whitespace);
+        m_whitespace = whitespace;
+    }
+
+    void clear()
+    {
+        m_whitespace = 0;
+        // Using resize(0) rather than clear() here saves 2% on
+        // PerformanceTests/Layout/line-layout.html because we avoid freeing and
+        // re-allocating the underlying buffer repeatedly.
+        m_boxes.resize(0);
+    }
+
+    void appendBoxIfNeeded(RenderBox* box)
+    {
+        if (m_whitespace)
+            m_boxes.append(box);
+    }
+
+    enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
+
+    void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
+
+private:
+    RenderText* m_whitespace;
+    Vector<RenderBox*, 4> m_boxes;
+};
+
+}
+
+#endif // TrailingObjects_h
diff --git a/Source/core/rendering/shapes/BoxShape.cpp b/Source/core/rendering/shapes/BoxShape.cpp
index 1234e4e..5638140 100644
--- a/Source/core/rendering/shapes/BoxShape.cpp
+++ b/Source/core/rendering/shapes/BoxShape.cpp
@@ -34,36 +34,62 @@
 
 namespace WebCore {
 
-BoxShape::BoxShape(const FloatRoundedRect& bounds, float shapeMargin, float shapePadding)
-    : Shape()
-    , m_bounds(bounds)
-    , m_marginBounds(bounds)
-    , m_paddingBounds(bounds)
+LayoutRect BoxShape::shapeMarginLogicalBoundingBox() const
 {
-    if (shapeMargin > 0) {
-        m_marginBounds.inflate(shapeMargin);
-        m_marginBounds.expandRadii(shapeMargin);
+    FloatRect marginBounds(m_bounds.rect());
+    if (shapeMargin() > 0)
+        marginBounds.inflate(shapeMargin());
+    return static_cast<LayoutRect>(marginBounds);
+}
+
+LayoutRect BoxShape::shapePaddingLogicalBoundingBox() const
+{
+    FloatRect paddingBounds(m_bounds.rect());
+    if (shapePadding() > 0)
+        paddingBounds.inflate(-shapePadding());
+    return static_cast<LayoutRect>(paddingBounds);
+}
+
+FloatRoundedRect BoxShape::shapeMarginBounds() const
+{
+    FloatRoundedRect marginBounds(m_bounds);
+    if (shapeMargin() > 0) {
+        marginBounds.inflate(shapeMargin());
+        marginBounds.expandRadii(shapeMargin());
     }
-    if (shapePadding > 0) {
-        m_paddingBounds.inflate(-shapePadding);
-        m_paddingBounds.expandRadii(-shapePadding);
+    return marginBounds;
+}
+
+FloatRoundedRect BoxShape::shapePaddingBounds() const
+{
+    FloatRoundedRect paddingBounds(m_bounds);
+    if (shapePadding() > 0) {
+        paddingBounds.inflate(-shapePadding());
+        paddingBounds.expandRadii(-shapePadding());
     }
+    return paddingBounds;
 }
 
 void BoxShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
-    if (m_marginBounds.isEmpty())
+    const FloatRoundedRect& marginBounds = shapeMarginBounds();
+    if (marginBounds.isEmpty() || !lineOverlapsShapeMarginBounds(logicalTop, logicalHeight))
         return;
 
     float y1 = logicalTop;
     float y2 = logicalTop + logicalHeight;
-    const FloatRect& rect = m_marginBounds.rect();
+    const FloatRect& rect = marginBounds.rect();
 
-    if (y2 <= rect.y() || y1 >= rect.maxY())
+    if (!marginBounds.isRounded()) {
+        result.append(LineSegment(marginBounds.rect().x(), marginBounds.rect().maxX()));
         return;
+    }
 
-    if (!m_marginBounds.isRounded()) {
-        result.append(LineSegment(m_marginBounds.rect().x(), m_marginBounds.rect().maxX()));
+    float topCornerMaxY = std::max<float>(marginBounds.topLeftCorner().maxY(), marginBounds.topRightCorner().maxY());
+    float bottomCornerMinY = std::min<float>(marginBounds.bottomLeftCorner().y(), marginBounds.bottomRightCorner().y());
+
+    if (y1 <= topCornerMaxY && y2 >= bottomCornerMinY) {
+        result.append(LineSegment(rect.x(), rect.maxX()));
         return;
     }
 
@@ -72,12 +98,12 @@
     float minXIntercept;
     float maxXIntercept;
 
-    if (m_marginBounds.xInterceptsAtY(y1, minXIntercept, maxXIntercept)) {
+    if (marginBounds.xInterceptsAtY(y1, minXIntercept, maxXIntercept)) {
         x1 = std::min<float>(x1, minXIntercept);
         x2 = std::max<float>(x2, maxXIntercept);
     }
 
-    if (m_marginBounds.xInterceptsAtY(y2, minXIntercept, maxXIntercept)) {
+    if (marginBounds.xInterceptsAtY(y2, minXIntercept, maxXIntercept)) {
         x1 = std::min<float>(x1, minXIntercept);
         x2 = std::max<float>(x2, maxXIntercept);
     }
@@ -88,19 +114,41 @@
 
 void BoxShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
-    if (m_paddingBounds.isEmpty())
+    const FloatRoundedRect& paddingBounds = shapePaddingBounds();
+    if (paddingBounds.isEmpty())
         return;
 
-    const FloatRect& rect = m_paddingBounds.rect();
-    if (logicalTop < rect.y() || logicalTop + logicalHeight > rect.maxY())
+    float y1 = logicalTop;
+    float y2 = logicalTop + logicalHeight;
+    const FloatRect& rect = paddingBounds.rect();
+
+    if (y1 < rect.y() || y2 > rect.maxY())
         return;
 
-    // FIXME: this method is only a stub, https://bugs.webkit.org/show_bug.cgi?id=124605.
+    if (!paddingBounds.isRounded()) {
+        result.append(LineSegment(rect.x(), rect.maxX()));
+        return;
+    }
 
-    result.append(LineSegment(rect.x(), rect.maxX()));
+    float x1 = rect.x();
+    float x2 = rect.maxX();
+    float minXIntercept;
+    float maxXIntercept;
+
+    if (paddingBounds.xInterceptsAtY(y1, minXIntercept, maxXIntercept)) {
+        x1 = std::max<float>(x1, minXIntercept);
+        x2 = std::min<float>(x2, maxXIntercept);
+    }
+
+    if (paddingBounds.xInterceptsAtY(y2, minXIntercept, maxXIntercept)) {
+        x1 = std::max<float>(x1, minXIntercept);
+        x2 = std::min<float>(x2, maxXIntercept);
+    }
+
+    result.append(LineSegment(x1, x2));
 }
 
-bool BoxShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize&, LayoutUnit& result) const
+bool BoxShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize&, LayoutUnit& result) const
 {
     // FIXME: this method is only a stub, https://bugs.webkit.org/show_bug.cgi?id=124606.
 
diff --git a/Source/core/rendering/shapes/BoxShape.h b/Source/core/rendering/shapes/BoxShape.h
index 881a1e8..70f067b 100644
--- a/Source/core/rendering/shapes/BoxShape.h
+++ b/Source/core/rendering/shapes/BoxShape.h
@@ -35,21 +35,26 @@
 
 namespace WebCore {
 
-class BoxShape : public Shape {
+class BoxShape FINAL : public Shape {
 public:
-    BoxShape(const FloatRoundedRect& bounds, float shapeMargin, float shapePadding);
+    BoxShape(const FloatRoundedRect& bounds)
+        : Shape()
+        , m_bounds(bounds)
+    {
+    }
 
-    virtual LayoutRect shapeMarginLogicalBoundingBox() const OVERRIDE { return static_cast<LayoutRect>(m_marginBounds.rect()); }
-    virtual LayoutRect shapePaddingLogicalBoundingBox() const OVERRIDE { return static_cast<LayoutRect>(m_paddingBounds.rect()); }
+    virtual LayoutRect shapeMarginLogicalBoundingBox() const OVERRIDE;
+    virtual LayoutRect shapePaddingLogicalBoundingBox() const OVERRIDE;
     virtual bool isEmpty() const OVERRIDE { return m_bounds.isEmpty(); }
     virtual void getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
     virtual void getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
-    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
+    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
 
 private:
+    FloatRoundedRect shapeMarginBounds() const;
+    FloatRoundedRect shapePaddingBounds() const;
+
     FloatRoundedRect m_bounds;
-    FloatRoundedRect m_marginBounds;
-    FloatRoundedRect m_paddingBounds;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/shapes/BoxShapeTest.cpp b/Source/core/rendering/shapes/BoxShapeTest.cpp
new file mode 100644
index 0000000..33af931
--- /dev/null
+++ b/Source/core/rendering/shapes/BoxShapeTest.cpp
@@ -0,0 +1,203 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE
+ * COPYRIGHT HOLDER 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.
+ */
+
+#include "config.h"
+
+#include "core/rendering/shapes/BoxShape.h"
+
+#include "platform/geometry/RoundedRect.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+class BoxShapeTest : public ::testing::Test {
+protected:
+    BoxShapeTest() { }
+
+    PassOwnPtr<Shape> createBoxShape(const RoundedRect& bounds, float shapeMargin, float shapePadding)
+    {
+        return Shape::createLayoutBoxShape(bounds, TopToBottomWritingMode, Length(shapeMargin, Fixed), Length(shapePadding, Fixed));
+    }
+};
+
+} // namespace WebCore
+
+namespace {
+
+using namespace WebCore;
+
+#define TEST_EXCLUDED_INTERVAL(shapePtr, lineTop, lineHeight, expectedLeft, expectedRight) \
+{                                                                                          \
+    SegmentList result;                                                                    \
+    shapePtr->getExcludedIntervals(lineTop, lineHeight, result);                           \
+    EXPECT_EQ(1u, result.size());                                                          \
+    if (result.size() == 1u) {                                                             \
+        EXPECT_FLOAT_EQ(expectedLeft, result[0].logicalLeft);                              \
+        EXPECT_FLOAT_EQ(expectedRight, result[0].logicalRight);                            \
+    }                                                                                      \
+}
+
+#define TEST_NO_EXCLUDED_INTERVAL(shapePtr, lineTop, lineHeight) \
+{                                                                \
+    SegmentList result;                                          \
+    shapePtr->getExcludedIntervals(lineTop, lineHeight, result); \
+    EXPECT_EQ(0u, result.size());                                \
+}
+
+#define TEST_INCLUDED_INTERVAL(shapePtr, lineTop, lineHeight, expectedLeft, expectedRight) \
+{                                                                                          \
+    SegmentList result;                                                                    \
+    shapePtr->getIncludedIntervals(lineTop, lineHeight, result);                           \
+    EXPECT_EQ(1u, result.size());                                                          \
+    if (result.size() == 1u) {                                                             \
+        EXPECT_FLOAT_EQ(expectedLeft, result[0].logicalLeft);                              \
+        EXPECT_FLOAT_EQ(expectedRight, result[0].logicalRight);                            \
+    }                                                                                      \
+}
+
+#define TEST_NO_INCLUDED_INTERVAL(shapePtr, lineTop, lineHeight) \
+{                                                                \
+    SegmentList result;                                          \
+    shapePtr->getIncludedIntervals(lineTop, lineHeight, result); \
+    EXPECT_EQ(0u, result.size());                                \
+}
+
+/* The BoxShape is based on a 100x50 rectangle at 0,0. The shape-margin value is 10,
+ * so the shapeMarginBoundingBox rectangle is 120x70 at -10,-10:
+ *
+ *   -10,-10   110,-10
+ *       +--------+
+ *       |        |
+ *       +--------+
+ *   -10,60     60,60
+ *
+ * The shape-padding value is 20, so the shapePaddingBoundingBox
+ * rectangle is 60x10 at 20,20:
+ *
+ *     20,20    80,20
+ *       +--------+
+ *       |        |
+ *       +--------+
+ *     20,30    80,30
+ */
+TEST_F(BoxShapeTest, zeroRadii)
+{
+    OwnPtr<Shape> shape = createBoxShape(RoundedRect(0, 0, 100, 50), 10, 20);
+    EXPECT_FALSE(shape->isEmpty());
+
+    EXPECT_EQ(LayoutRect(-10, -10, 120, 70), shape->shapeMarginLogicalBoundingBox());
+    EXPECT_EQ(LayoutRect(20, 20, 60, 10), shape->shapePaddingLogicalBoundingBox());
+
+    // A BoxShape's bounds include the top edge but not the bottom edge.
+    // Similarly a "line", specified as top,height to the overlap methods,
+    // is defined as top <= y < top + height.
+
+    EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(-9, 1));
+    EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(-10, 0));
+    EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(-10, 200));
+    EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(5, 10));
+    EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(59, 1));
+
+    EXPECT_FALSE(shape->lineOverlapsShapeMarginBounds(-12, 2));
+    EXPECT_FALSE(shape->lineOverlapsShapeMarginBounds(60, 1));
+    EXPECT_FALSE(shape->lineOverlapsShapeMarginBounds(100, 200));
+
+    TEST_EXCLUDED_INTERVAL(shape, -9, 1, -10, 110);
+    TEST_EXCLUDED_INTERVAL(shape, -10, 0, -10, 110);
+    TEST_EXCLUDED_INTERVAL(shape, -10, 200, -10, 110);
+    TEST_EXCLUDED_INTERVAL(shape, 5, 10, -10, 110);
+    TEST_EXCLUDED_INTERVAL(shape, 59, 1, -10, 110);
+
+    TEST_NO_EXCLUDED_INTERVAL(shape, -12, 2);
+    TEST_NO_EXCLUDED_INTERVAL(shape, 60, 1);
+    TEST_NO_EXCLUDED_INTERVAL(shape, 100, 200);
+
+    EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(21, 1));
+    EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(20, 0));
+    EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(-10, 200));
+    EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(25, 35));
+    EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(29, 1));
+
+    EXPECT_FALSE(shape->lineOverlapsShapePaddingBounds(18, 2));
+    EXPECT_FALSE(shape->lineOverlapsShapePaddingBounds(30, 1));
+    EXPECT_FALSE(shape->lineOverlapsShapePaddingBounds(100, 200));
+
+    // A BoxShape only includes a line if the lines's top and
+    // bottom fit within the shapePaddingLogicalBoundingBox:
+    // top >= box.y && top + height <= box.maxY
+
+    TEST_INCLUDED_INTERVAL(shape, 21, 1, 20, 80);
+    TEST_INCLUDED_INTERVAL(shape, 20, 0, 20, 80);
+    TEST_INCLUDED_INTERVAL(shape, 20, 10, 20, 80);
+    TEST_INCLUDED_INTERVAL(shape, 25, 5, 20, 80);
+    TEST_INCLUDED_INTERVAL(shape, 29, 1, 20, 80);
+
+    TEST_NO_INCLUDED_INTERVAL(shape, 18, 2);
+    TEST_NO_INCLUDED_INTERVAL(shape, 30, 1);
+    TEST_NO_INCLUDED_INTERVAL(shape, 100, 200);
+    TEST_NO_INCLUDED_INTERVAL(shape, 19, 10);
+    TEST_NO_INCLUDED_INTERVAL(shape, 20, 100);
+}
+
+/* BoxShape geometry for this test. Corner radii are in parens, x and y intercepts
+ * for the elliptical corners are noted. The rectangle itself is at 0,0 with width and height 100.
+ *
+ *         (10, 15)  x=10      x=90 (10, 20)
+ *                (--+---------+--)
+ *           y=15 +--|         |-+ y=20
+ *                |               |
+ *                |               |
+ *           y=85 + -|         |- + y=70
+ *                (--+---------+--)
+ *       (25, 15)  x=25      x=80  (20, 30)
+ */
+TEST_F(BoxShapeTest, getIntervals)
+{
+    const RoundedRect::Radii cornerRadii(IntSize(10, 15), IntSize(10, 20), IntSize(25, 15), IntSize(20, 30));
+    OwnPtr<Shape> shape = createBoxShape(RoundedRect(IntRect(0, 0, 100, 100), cornerRadii), 0, 0);
+    EXPECT_FALSE(shape->isEmpty());
+
+    EXPECT_EQ(LayoutRect(0, 0, 100, 100), shape->shapeMarginLogicalBoundingBox());
+    EXPECT_EQ(LayoutRect(0, 0, 100, 100), shape->shapePaddingLogicalBoundingBox());
+
+    TEST_INCLUDED_INTERVAL(shape, 5, 25, 2.5464401f, 96.61438f);
+    TEST_INCLUDED_INTERVAL(shape, 15, 1, 0, 99.682457f);
+    TEST_INCLUDED_INTERVAL(shape, 20, 50, 0, 100);
+    TEST_INCLUDED_INTERVAL(shape, 85, 10, 6.3661003f, 91.05542f);
+
+    TEST_EXCLUDED_INTERVAL(shape, 10, 95, 0, 100);
+    TEST_EXCLUDED_INTERVAL(shape, 5, 25, 0, 100);
+    TEST_EXCLUDED_INTERVAL(shape, 15, 6, 0, 100);
+    TEST_EXCLUDED_INTERVAL(shape, 20, 50, 0, 100);
+    TEST_EXCLUDED_INTERVAL(shape, 69, 5, 0, 100);
+    TEST_EXCLUDED_INTERVAL(shape, 85, 10, 0, 97.320511f);
+}
+
+} // namespace
diff --git a/Source/core/rendering/shapes/PolygonShape.cpp b/Source/core/rendering/shapes/PolygonShape.cpp
index 26ddcf3..041440b 100644
--- a/Source/core/rendering/shapes/PolygonShape.cpp
+++ b/Source/core/rendering/shapes/PolygonShape.cpp
@@ -443,7 +443,7 @@
     return false;
 }
 
-bool PolygonShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
+bool PolygonShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize& minLogicalIntervalSize, LayoutUnit& result) const
 {
     float minIntervalTop = minLogicalIntervalTop;
     float minIntervalHeight = minLogicalIntervalSize.height();
diff --git a/Source/core/rendering/shapes/PolygonShape.h b/Source/core/rendering/shapes/PolygonShape.h
index 38b0d8e..9f0e93a 100644
--- a/Source/core/rendering/shapes/PolygonShape.h
+++ b/Source/core/rendering/shapes/PolygonShape.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class OffsetPolygonEdge : public VertexPair {
+class OffsetPolygonEdge FINAL : public VertexPair {
 public:
     enum Basis {
         Edge,
@@ -79,7 +79,7 @@
     Basis m_basis;
 };
 
-class PolygonShape : public Shape {
+class PolygonShape FINAL : public Shape {
     WTF_MAKE_NONCOPYABLE(PolygonShape);
 public:
     PolygonShape(PassOwnPtr<Vector<FloatPoint> > vertices, WindRule fillRule)
@@ -95,7 +95,7 @@
     virtual bool isEmpty() const OVERRIDE { return m_polygon.isEmpty(); }
     virtual void getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
     virtual void getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
-    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
+    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
 
 private:
     const FloatPolygon& shapeMarginBounds() const;
diff --git a/Source/core/rendering/shapes/RasterShape.cpp b/Source/core/rendering/shapes/RasterShape.cpp
index 78b0021..32a0511 100644
--- a/Source/core/rendering/shapes/RasterShape.cpp
+++ b/Source/core/rendering/shapes/RasterShape.cpp
@@ -302,7 +302,7 @@
     appendLineSegments(includedIntervals, result);
 }
 
-bool RasterShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
+bool RasterShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize& minLogicalIntervalSize, LayoutUnit& result) const
 {
     const RasterShapeIntervals& intervals = paddingIntervals();
     if (intervals.isEmpty())
diff --git a/Source/core/rendering/shapes/RasterShape.h b/Source/core/rendering/shapes/RasterShape.h
index 903eabb..4b178fd 100644
--- a/Source/core/rendering/shapes/RasterShape.h
+++ b/Source/core/rendering/shapes/RasterShape.h
@@ -84,7 +84,7 @@
     unsigned m_shapeMargin;
 };
 
-class RasterShape : public Shape {
+class RasterShape FINAL : public Shape {
     WTF_MAKE_NONCOPYABLE(RasterShape);
 public:
     RasterShape(PassOwnPtr<RasterShapeIntervals> intervals, const IntSize& imageSize)
@@ -99,7 +99,7 @@
     virtual bool isEmpty() const OVERRIDE { return m_intervals->isEmpty(); }
     virtual void getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
     virtual void getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
-    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
+    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
 
 private:
     const RasterShapeIntervals& marginIntervals() const;
diff --git a/Source/core/rendering/shapes/RectangleShape.cpp b/Source/core/rendering/shapes/RectangleShape.cpp
index 210fcf4..3e1e9c9 100644
--- a/Source/core/rendering/shapes/RectangleShape.cpp
+++ b/Source/core/rendering/shapes/RectangleShape.cpp
@@ -46,64 +46,36 @@
     return ry * sqrt(1 - (x * x) / (rx * rx));
 }
 
-RectangleShape::ShapeBounds RectangleShape::ShapeBounds::paddingBounds(float padding) const
+FloatRect RectangleShape::shapePaddingBounds() const
 {
-    ASSERT(padding >= 0);
-    if (!padding || isEmpty())
-        return *this;
+    ASSERT(shapePadding() >= 0);
+    if (!shapePadding() || isEmpty())
+        return m_bounds;
 
-    float boundsX = x() + std::min(width() / 2, padding);
-    float boundsY = y() + std::min(height() / 2, padding);
-    float boundsWidth = std::max(0.0f, width() - padding * 2);
-    float boundsHeight = std::max(0.0f, height() - padding * 2);
-    float boundsRadiusX = std::max(0.0f, rx() - padding);
-    float boundsRadiusY = std::max(0.0f, ry() - padding);
-    return RectangleShape::ShapeBounds(FloatRect(boundsX, boundsY, boundsWidth, boundsHeight), FloatSize(boundsRadiusX, boundsRadiusY));
+    float boundsX = x() + std::min(width() / 2, shapePadding());
+    float boundsY = y() + std::min(height() / 2, shapePadding());
+    float boundsWidth = std::max(0.0f, width() - shapePadding() * 2);
+    float boundsHeight = std::max(0.0f, height() - shapePadding() * 2);
+
+    return FloatRect(boundsX, boundsY, boundsWidth, boundsHeight);
 }
 
-RectangleShape::ShapeBounds RectangleShape::ShapeBounds::marginBounds(float margin) const
+FloatRect RectangleShape::shapeMarginBounds() const
 {
-    ASSERT(margin >= 0);
-    if (!margin)
-        return *this;
+    ASSERT(shapeMargin() >= 0);
+    if (!shapeMargin())
+        return m_bounds;
 
-    float boundsX = x() - margin;
-    float boundsY = y() - margin;
-    float boundsWidth = width() + margin * 2;
-    float boundsHeight = height() + margin * 2;
-    float boundsRadiusX = rx() + margin;
-    float boundsRadiusY = ry() + margin;
-    return RectangleShape::ShapeBounds(FloatRect(boundsX, boundsY, boundsWidth, boundsHeight), FloatSize(boundsRadiusX, boundsRadiusY));
-}
-
-FloatPoint RectangleShape::ShapeBounds::cornerInterceptForWidth(float widthAtIntercept) const
-{
-    float xi = (width() - widthAtIntercept) / 2;
-    float yi = ry() - ellipseYIntercept(rx() - xi, rx(), ry());
-    return FloatPoint(xi, yi);
-}
-
-RectangleShape::ShapeBounds RectangleShape::shapePaddingBounds() const
-{
-    if (!m_haveInitializedPaddingBounds) {
-        m_haveInitializedPaddingBounds = true;
-        m_paddingBounds = m_bounds.paddingBounds(shapePadding());
-    }
-    return m_paddingBounds;
-}
-
-RectangleShape::ShapeBounds RectangleShape::shapeMarginBounds() const
-{
-    if (!m_haveInitializedMarginBounds) {
-        m_haveInitializedMarginBounds = true;
-        m_marginBounds = m_bounds.marginBounds(shapeMargin());
-    }
-    return m_marginBounds;
+    float boundsX = x() - shapeMargin();
+    float boundsY = y() - shapeMargin();
+    float boundsWidth = width() + shapeMargin() * 2;
+    float boundsHeight = height() + shapeMargin() * 2;
+    return FloatRect(boundsX, boundsY, boundsWidth, boundsHeight);
 }
 
 void RectangleShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
-    const RectangleShape::ShapeBounds& bounds = shapeMarginBounds();
+    const FloatRect& bounds = shapeMarginBounds();
     if (bounds.isEmpty())
         return;
 
@@ -116,17 +88,20 @@
     float x1 = bounds.x();
     float x2 = bounds.maxX();
 
-    if (bounds.ry() > 0) {
-        if (y2 < bounds.y() + bounds.ry()) {
-            float yi = y2 - bounds.y() - bounds.ry();
-            float xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
-            x1 = bounds.x() + bounds.rx() - xi;
-            x2 = bounds.maxX() - bounds.rx() + xi;
-        } else if (y1 > bounds.maxY() - bounds.ry()) {
-            float yi =  y1 - (bounds.maxY() - bounds.ry());
-            float xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
-            x1 = bounds.x() + bounds.rx() - xi;
-            x2 = bounds.maxX() - bounds.rx() + xi;
+    float marginRadiusX = rx() + shapeMargin();
+    float marginRadiusY = ry() + shapeMargin();
+
+    if (marginRadiusY > 0) {
+        if (y2 < bounds.y() + marginRadiusY) {
+            float yi = y2 - bounds.y() - marginRadiusY;
+            float xi = ellipseXIntercept(yi, marginRadiusX, marginRadiusY);
+            x1 = bounds.x() + marginRadiusX - xi;
+            x2 = bounds.maxX() - marginRadiusX + xi;
+        } else if (y1 > bounds.maxY() - marginRadiusY) {
+            float yi =  y1 - (bounds.maxY() - marginRadiusY);
+            float xi = ellipseXIntercept(yi, marginRadiusX, marginRadiusY);
+            x1 = bounds.x() + marginRadiusX - xi;
+            x2 = bounds.maxX() - marginRadiusX + xi;
         }
     }
 
@@ -135,7 +110,7 @@
 
 void RectangleShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
-    const RectangleShape::ShapeBounds& bounds = shapePaddingBounds();
+    const FloatRect& bounds = shapePaddingBounds();
     if (bounds.isEmpty())
         return;
 
@@ -148,43 +123,53 @@
     float x1 = bounds.x();
     float x2 = bounds.maxX();
 
-    if (bounds.ry() > 0) {
-        bool y1InterceptsCorner = y1 < bounds.y() + bounds.ry();
-        bool y2InterceptsCorner = y2 > bounds.maxY() - bounds.ry();
+    float paddingRadiusX = std::max(0.0f, rx() - shapePadding());
+    float paddingRadiusY = std::max(0.0f, ry() - shapePadding());
+
+    if (paddingRadiusX > 0) {
+        bool y1InterceptsCorner = y1 < bounds.y() + paddingRadiusY;
+        bool y2InterceptsCorner = y2 > bounds.maxY() - paddingRadiusY;
         float xi = 0;
 
         if (y1InterceptsCorner && y2InterceptsCorner) {
             if  (y1 < bounds.height() + 2 * bounds.y() - y2) {
-                float yi = y1 - bounds.y() - bounds.ry();
-                xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
+                float yi = y1 - bounds.y() - paddingRadiusY;
+                xi = ellipseXIntercept(yi, paddingRadiusX, paddingRadiusY);
             } else {
-                float yi =  y2 - (bounds.maxY() - bounds.ry());
-                xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
+                float yi =  y2 - (bounds.maxY() - paddingRadiusY);
+                xi = ellipseXIntercept(yi, paddingRadiusX, paddingRadiusY);
             }
         } else if (y1InterceptsCorner) {
-            float yi = y1 - bounds.y() - bounds.ry();
-            xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
+            float yi = y1 - bounds.y() - paddingRadiusY;
+            xi = ellipseXIntercept(yi, paddingRadiusX, paddingRadiusY);
         } else if (y2InterceptsCorner) {
-            float yi =  y2 - (bounds.maxY() - bounds.ry());
-            xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
+            float yi =  y2 - (bounds.maxY() - paddingRadiusY);
+            xi = ellipseXIntercept(yi, paddingRadiusX, paddingRadiusY);
         }
 
         if (y1InterceptsCorner || y2InterceptsCorner) {
-            x1 = bounds.x() + bounds.rx() - xi;
-            x2 = bounds.maxX() - bounds.rx() + xi;
+            x1 = bounds.x() + paddingRadiusX - xi;
+            x2 = bounds.maxX() - paddingRadiusX + xi;
         }
     }
 
     result.append(LineSegment(x1, x2));
 }
 
-bool RectangleShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
+static FloatPoint cornerInterceptForWidth(float width, float widthAtIntercept, float rx, float ry)
+{
+    float xi = (width - widthAtIntercept) / 2;
+    float yi = ry - ellipseYIntercept(rx - xi, rx, ry);
+    return FloatPoint(xi, yi);
+}
+
+bool RectangleShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize& minLogicalIntervalSize, LayoutUnit& result) const
 {
     float minIntervalTop = minLogicalIntervalTop;
     float minIntervalHeight = minLogicalIntervalSize.height();
     float minIntervalWidth = minLogicalIntervalSize.width();
 
-    const RectangleShape::ShapeBounds& bounds = shapePaddingBounds();
+    const FloatRect& bounds = shapePaddingBounds();
     if (bounds.isEmpty() || minIntervalWidth > bounds.width())
         return false;
 
@@ -194,8 +179,11 @@
     if (maxY > bounds.maxY())
         return false;
 
-    bool intervalOverlapsMinCorner = minY < bounds.y() + bounds.ry();
-    bool intervalOverlapsMaxCorner = maxY > bounds.maxY() - bounds.ry();
+    float paddingRadiusX = std::max(0.0f, rx() - shapePadding());
+    float paddingRadiusY = std::max(0.0f, ry() - shapePadding());
+
+    bool intervalOverlapsMinCorner = minY < bounds.y() + paddingRadiusY;
+    bool intervalOverlapsMaxCorner = maxY > bounds.maxY() - paddingRadiusY;
 
     if (!intervalOverlapsMinCorner && !intervalOverlapsMaxCorner) {
         result = minY;
@@ -204,8 +192,8 @@
 
     float centerY = bounds.y() + bounds.height() / 2;
     bool minCornerDefinesX = fabs(centerY - minY) > fabs(centerY - maxY);
-    bool intervalFitsWithinCorners = minIntervalWidth + 2 * bounds.rx() <= bounds.width();
-    FloatPoint cornerIntercept = bounds.cornerInterceptForWidth(minIntervalWidth);
+    bool intervalFitsWithinCorners = minIntervalWidth + 2 * paddingRadiusX <= bounds.width();
+    FloatPoint cornerIntercept = cornerInterceptForWidth(bounds.width(), minIntervalWidth, paddingRadiusX, paddingRadiusY);
 
     if (intervalOverlapsMinCorner && (!intervalOverlapsMaxCorner || minCornerDefinesX)) {
         if (intervalFitsWithinCorners || bounds.y() + cornerIntercept.y() < minY) {
diff --git a/Source/core/rendering/shapes/RectangleShape.h b/Source/core/rendering/shapes/RectangleShape.h
index 35db8a4..a9c9b4b 100644
--- a/Source/core/rendering/shapes/RectangleShape.h
+++ b/Source/core/rendering/shapes/RectangleShape.h
@@ -39,13 +39,12 @@
 
 namespace WebCore {
 
-class RectangleShape : public Shape {
+class RectangleShape FINAL : public Shape {
 public:
     RectangleShape(const FloatRect& bounds, const FloatSize& radii)
         : Shape()
-        , m_bounds(bounds, radii)
-        , m_haveInitializedMarginBounds(false)
-        , m_haveInitializedPaddingBounds(false)
+        , m_bounds(bounds)
+        , m_radii(radii)
     {
     }
 
@@ -54,36 +53,21 @@
     virtual bool isEmpty() const OVERRIDE { return m_bounds.isEmpty(); }
     virtual void getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
     virtual void getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
-    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
+    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
 
 private:
-    class ShapeBounds : public FloatRect {
-    public:
-        ShapeBounds() { }
-        ShapeBounds(const FloatRect& bounds, const FloatSize& radii)
-            : FloatRect(bounds)
-            , m_radii(radii)
-        {
-        }
+    FloatRect shapeMarginBounds() const;
+    FloatRect shapePaddingBounds() const;
 
-        float rx() const { return m_radii.width(); }
-        float ry() const { return m_radii.height(); }
-        ShapeBounds marginBounds(float shapeMargin) const;
-        ShapeBounds paddingBounds(float shapePadding) const;
-        FloatPoint cornerInterceptForWidth(float width) const;
+    float rx() const { return m_radii.width(); }
+    float ry() const { return m_radii.height(); }
+    float x() const { return m_bounds.x(); }
+    float y() const { return m_bounds.y(); }
+    float width() const { return m_bounds.width(); }
+    float height() const { return m_bounds.height(); }
 
-    private:
-        FloatSize m_radii;
-    };
-
-    ShapeBounds shapeMarginBounds() const;
-    ShapeBounds shapePaddingBounds() const;
-
-    ShapeBounds m_bounds;
-    mutable ShapeBounds m_marginBounds;
-    mutable ShapeBounds m_paddingBounds;
-    mutable bool m_haveInitializedMarginBounds : 1;
-    mutable bool m_haveInitializedPaddingBounds : 1;
+    FloatRect m_bounds;
+    FloatSize m_radii;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/shapes/Shape.cpp b/Source/core/rendering/shapes/Shape.cpp
index febc027..6db8939 100644
--- a/Source/core/rendering/shapes/Shape.cpp
+++ b/Source/core/rendering/shapes/Shape.cpp
@@ -30,6 +30,7 @@
 #include "config.h"
 #include "core/rendering/shapes/Shape.h"
 
+#include "core/css/BasicShapeFunctions.h"
 #include "core/fetch/ImageResource.h"
 #include "core/rendering/shapes/BoxShape.h"
 #include "core/rendering/shapes/PolygonShape.h"
@@ -45,10 +46,10 @@
 
 namespace WebCore {
 
-static PassOwnPtr<Shape> createBoxShape(const FloatRoundedRect& bounds, float shapeMargin, float shapePadding)
+static PassOwnPtr<Shape> createInsetShape(const FloatRoundedRect& bounds)
 {
     ASSERT(bounds.rect().width() >= 0 && bounds.rect().height() >= 0);
-    return adoptPtr(new BoxShape(bounds, shapeMargin, shapePadding));
+    return adoptPtr(new BoxShape(bounds));
 }
 
 static PassOwnPtr<Shape> createRectangleShape(const FloatRect& bounds, const FloatSize& radii)
@@ -138,8 +139,8 @@
         break;
     }
 
-    case BasicShape::BasicShapeCircleType: {
-        const BasicShapeCircle* circle = static_cast<const BasicShapeCircle*>(basicShape);
+    case BasicShape::DeprecatedBasicShapeCircleType: {
+        const DeprecatedBasicShapeCircle* circle = static_cast<const DeprecatedBasicShapeCircle*>(basicShape);
         float centerX = floatValueForLength(circle->centerX(), boxWidth);
         float centerY = floatValueForLength(circle->centerY(), boxHeight);
         // This method of computing the radius is as defined in SVG
@@ -153,8 +154,18 @@
         break;
     }
 
-    case BasicShape::BasicShapeEllipseType: {
-        const BasicShapeEllipse* ellipse = static_cast<const BasicShapeEllipse*>(basicShape);
+    case BasicShape::BasicShapeCircleType: {
+        const BasicShapeCircle* circle = static_cast<const BasicShapeCircle*>(basicShape);
+        FloatPoint center = floatPointForCenterCoordinate(circle->centerX(), circle->centerY(), FloatSize(boxWidth, boxHeight));
+        float radius = circle->floatValueForRadiusInBox(FloatSize(boxWidth, boxHeight));
+        FloatPoint logicalCenter = physicalPointToLogical(center, logicalBoxSize.height(), writingMode);
+
+        shape = createCircleShape(logicalCenter, radius);
+        break;
+    }
+
+    case BasicShape::DeprecatedBasicShapeEllipseType: {
+        const DeprecatedBasicShapeEllipse* ellipse = static_cast<const DeprecatedBasicShapeEllipse*>(basicShape);
         float centerX = floatValueForLength(ellipse->centerX(), boxWidth);
         float centerY = floatValueForLength(ellipse->centerY(), boxHeight);
         float radiusX = floatValueForLength(ellipse->radiusX(), boxWidth);
@@ -166,6 +177,17 @@
         break;
     }
 
+    case BasicShape::BasicShapeEllipseType: {
+        const BasicShapeEllipse* ellipse = static_cast<const BasicShapeEllipse*>(basicShape);
+        FloatPoint center = floatPointForCenterCoordinate(ellipse->centerX(), ellipse->centerY(), FloatSize(boxWidth, boxHeight));
+        float radiusX = ellipse->floatValueForRadiusInBox(ellipse->radiusX(), center.x(), boxWidth);
+        float radiusY = ellipse->floatValueForRadiusInBox(ellipse->radiusY(), center.y(), boxHeight);
+        FloatPoint logicalCenter = physicalPointToLogical(center, logicalBoxSize.height(), writingMode);
+
+        shape = createEllipseShape(logicalCenter, FloatSize(radiusX, radiusY));
+        break;
+    }
+
     case BasicShape::BasicShapePolygonType: {
         const BasicShapePolygon* polygon = static_cast<const BasicShapePolygon*>(basicShape);
         const Vector<Length>& values = polygon->values();
@@ -201,6 +223,26 @@
         break;
     }
 
+    case BasicShape::BasicShapeInsetType: {
+        const BasicShapeInset& inset = *static_cast<const BasicShapeInset*>(basicShape);
+        float left = floatValueForLength(inset.left(), boxWidth);
+        float top = floatValueForLength(inset.top(), boxHeight);
+        float right = floatValueForLength(inset.right(), boxWidth);
+        float bottom = floatValueForLength(inset.bottom(), boxHeight);
+        FloatRect rect(left, top, boxWidth - left - right, boxHeight - top - bottom);
+        FloatRect logicalRect = physicalRectToLogical(rect, logicalBoxSize.height(), writingMode);
+
+        FloatSize boxSize(boxWidth, boxHeight);
+        FloatRoundedRect::Radii cornerRadii(
+            floatSizeForLengthSize(inset.topLeftRadius(), boxSize),
+            floatSizeForLengthSize(inset.topRightRadius(), boxSize),
+            floatSizeForLengthSize(inset.bottomLeftRadius(), boxSize),
+            floatSizeForLengthSize(inset.bottomRightRadius(), boxSize));
+
+        shape = createInsetShape(FloatRoundedRect(logicalRect, cornerRadii));
+        break;
+    }
+
     default:
         ASSERT_NOT_REACHED();
     }
@@ -212,58 +254,57 @@
     return shape.release();
 }
 
-PassOwnPtr<Shape> Shape::createShape(const StyleImage* styleImage, float threshold, const LayoutSize&, WritingMode writingMode, Length margin, Length padding)
+PassOwnPtr<Shape> Shape::createRasterShape(const StyleImage& styleImage, float threshold, const LayoutRect& imageRect, const LayoutSize&, WritingMode writingMode, Length margin, Length padding)
 {
-    ASSERT(styleImage && styleImage->isImageResource() && styleImage->cachedImage() && styleImage->cachedImage()->image());
+    ASSERT(styleImage.cachedImage());
+    ASSERT(styleImage.cachedImage()->hasImage());
 
-    Image* image = styleImage->cachedImage()->image();
-    const IntSize& imageSize = image->size();
-    OwnPtr<RasterShapeIntervals> intervals = adoptPtr(new RasterShapeIntervals(imageSize.height()));
-    OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(imageSize);
+    IntRect toRect = pixelSnappedIntRect(imageRect);
+    IntSize bufferSize = toRect.size();
+    IntSize rasterSize = IntSize(toRect.maxX(), toRect.maxY());
+    OwnPtr<RasterShapeIntervals> intervals = adoptPtr(new RasterShapeIntervals(rasterSize.height()));
+    OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(bufferSize);
+
     if (imageBuffer) {
         GraphicsContext* graphicsContext = imageBuffer->context();
-        graphicsContext->drawImage(image, IntPoint());
+        graphicsContext->drawImage(styleImage.cachedImage()->image(), FloatRect(0, 0, bufferSize.width(), bufferSize.height()));
 
-        RefPtr<Uint8ClampedArray> pixelArray = imageBuffer->getUnmultipliedImageData(IntRect(IntPoint(), imageSize));
+        RefPtr<Uint8ClampedArray> pixelArray = imageBuffer->getUnmultipliedImageData(IntRect(IntPoint(), bufferSize));
         unsigned pixelArrayLength = pixelArray->length();
         unsigned pixelArrayOffset = 3; // Each pixel is four bytes: RGBA.
         uint8_t alphaPixelThreshold = threshold * 255;
 
-        ASSERT(static_cast<unsigned>(imageSize.width() * imageSize.height() * 4) == pixelArrayLength);
+        ASSERT(static_cast<unsigned>(bufferSize.width() * bufferSize.height() * 4) == pixelArrayLength);
 
-        for (int y = 0; y < imageSize.height(); ++y) {
+        for (int y = 0; y < bufferSize.height(); ++y) {
             int startX = -1;
-            for (int x = 0; x < imageSize.width() && pixelArrayOffset < pixelArrayLength; ++x, pixelArrayOffset += 4) {
+            for (int x = 0; x < bufferSize.width() && pixelArrayOffset < pixelArrayLength; ++x, pixelArrayOffset += 4) {
                 uint8_t alpha = pixelArray->item(pixelArrayOffset);
                 if ((startX == -1) && alpha > alphaPixelThreshold) {
                     startX = x;
-                } else if (startX != -1 && (alpha <= alphaPixelThreshold || x == imageSize.width() - 1)) {
-                    intervals->appendInterval(y, startX, x);
+                } else if (startX != -1 && (alpha <= alphaPixelThreshold || x == bufferSize.width() - 1)) {
+                    intervals->appendInterval(y + toRect.y(), startX + toRect.x(), x + toRect.x());
                     startX = -1;
                 }
             }
         }
     }
 
-    OwnPtr<RasterShape> rasterShape = adoptPtr(new RasterShape(intervals.release(), imageSize));
+    OwnPtr<RasterShape> rasterShape = adoptPtr(new RasterShape(intervals.release(), rasterSize));
     rasterShape->m_writingMode = writingMode;
     rasterShape->m_margin = floatValueForLength(margin, 0);
     rasterShape->m_padding = floatValueForLength(padding, 0);
     return rasterShape.release();
 }
 
-PassOwnPtr<Shape> Shape::createLayoutBoxShape(const LayoutSize& logicalSize, WritingMode writingMode, const Length& margin, const Length& padding)
+PassOwnPtr<Shape> Shape::createLayoutBoxShape(const RoundedRect& roundedRect, WritingMode writingMode, const Length& margin, const Length& padding)
 {
-    FloatRect rect(0, 0, logicalSize.width(), logicalSize.height());
-    FloatSize radii(0, 0);
-    FloatRoundedRect bounds(rect, radii, radii, radii, radii);
-    float shapeMargin = floatValueForLength(margin, 0);
-    float shapePadding = floatValueForLength(padding, 0);
-
-    OwnPtr<Shape> shape = createBoxShape(bounds, shapeMargin, shapePadding);
+    FloatRect rect(0, 0, roundedRect.rect().width(), roundedRect.rect().height());
+    FloatRoundedRect bounds(rect, roundedRect.radii());
+    OwnPtr<Shape> shape = createInsetShape(bounds);
     shape->m_writingMode = writingMode;
-    shape->m_margin = shapeMargin;
-    shape->m_padding = shapePadding;
+    shape->m_margin = floatValueForLength(margin, 0);
+    shape->m_padding = floatValueForLength(padding, 0);
 
     return shape.release();
 }
diff --git a/Source/core/rendering/shapes/Shape.h b/Source/core/rendering/shapes/Shape.h
index de9aef9..53bd379 100644
--- a/Source/core/rendering/shapes/Shape.h
+++ b/Source/core/rendering/shapes/Shape.h
@@ -33,6 +33,7 @@
 #include "core/rendering/style/BasicShapes.h"
 #include "core/rendering/style/StyleImage.h"
 #include "platform/geometry/LayoutRect.h"
+#include "platform/geometry/RoundedRect.h"
 #include "platform/text/WritingMode.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
@@ -61,8 +62,8 @@
 class Shape {
 public:
     static PassOwnPtr<Shape> createShape(const BasicShape*, const LayoutSize& logicalBoxSize, WritingMode, Length margin, Length padding);
-    static PassOwnPtr<Shape> createShape(const StyleImage*, float threshold, const LayoutSize& logicalBoxSize, WritingMode, Length margin, Length padding);
-    static PassOwnPtr<Shape> createLayoutBoxShape(const LayoutSize& logicalBoxSize, WritingMode, const Length& margin, const Length& padding);
+    static PassOwnPtr<Shape> createRasterShape(const StyleImage&, float threshold, const LayoutRect& imageRect, const LayoutSize& logicalBoxSize, WritingMode, Length margin, Length padding);
+    static PassOwnPtr<Shape> createLayoutBoxShape(const RoundedRect&, WritingMode, const Length& margin, const Length& padding);
 
     virtual ~Shape() { }
 
@@ -71,7 +72,7 @@
     virtual bool isEmpty() const = 0;
     virtual void getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const = 0;
     virtual void getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const = 0;
-    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const = 0;
+    virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const FloatSize& minLogicalIntervalSize, LayoutUnit& result) const = 0;
     bool lineOverlapsShapeMarginBounds(LayoutUnit lineTop, LayoutUnit lineHeight) const { return lineOverlapsBoundingBox(lineTop, lineHeight, shapeMarginLogicalBoundingBox()); }
     bool lineOverlapsShapePaddingBounds(LayoutUnit lineTop, LayoutUnit lineHeight) const { return lineOverlapsBoundingBox(lineTop, lineHeight, shapePaddingLogicalBoundingBox()); }
 
diff --git a/Source/core/rendering/shapes/ShapeInfo.cpp b/Source/core/rendering/shapes/ShapeInfo.cpp
index e266871..72020e6 100644
--- a/Source/core/rendering/shapes/ShapeInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInfo.cpp
@@ -30,7 +30,8 @@
 #include "config.h"
 #include "core/rendering/shapes/ShapeInfo.h"
 
-#include "core/rendering/RenderRegion.h"
+#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderImage.h"
 
 namespace WebCore {
 
@@ -46,6 +47,16 @@
     return false;
 }
 
+static LayoutRect getShapeImageRect(const StyleImage& styleImage, const RenderBox* renderBox)
+{
+    if (renderBox->isRenderImage())
+        return toRenderImage(renderBox)->replacedContentRect();
+
+    ASSERT(styleImage.cachedImage());
+    ASSERT(styleImage.cachedImage()->hasImage());
+    return LayoutRect(LayoutPoint(), styleImage.cachedImage()->image()->size());
+}
+
 template<class RenderType>
 const Shape* ShapeInfo<RenderType>::computedShape() const
 {
@@ -64,13 +75,17 @@
         ASSERT(shapeValue->shape());
         m_shape = Shape::createShape(shapeValue->shape(), m_shapeLogicalSize, writingMode, margin, padding);
         break;
-    case ShapeValue::Image:
+    case ShapeValue::Image: {
         ASSERT(shapeValue->image());
-        m_shape = Shape::createShape(shapeValue->image(), shapeImageThreshold, m_shapeLogicalSize, writingMode, margin, padding);
+        const StyleImage& styleImage = *(shapeValue->image());
+        m_shape = Shape::createRasterShape(styleImage, shapeImageThreshold, getShapeImageRect(styleImage, m_renderer), m_shapeLogicalSize, writingMode, margin, padding);
         break;
-    case ShapeValue::Box:
-        m_shape = Shape::createLayoutBoxShape(m_shapeLogicalSize, writingMode, margin, padding);
+    }
+    case ShapeValue::Box: {
+        const RoundedRect& shapeRect = m_renderer->style()->getRoundedBorderFor(LayoutRect(LayoutPoint(), m_shapeLogicalSize), m_renderer->view());
+        m_shape = Shape::createLayoutBoxShape(shapeRect, writingMode, margin, padding);
         break;
+    }
     case ShapeValue::Outside:
         // Outside should have already resolved to a different shape value.
         ASSERT_NOT_REACHED();
diff --git a/Source/core/rendering/shapes/ShapeInfo.h b/Source/core/rendering/shapes/ShapeInfo.h
index 1314f34..00f9a02 100644
--- a/Source/core/rendering/shapes/ShapeInfo.h
+++ b/Source/core/rendering/shapes/ShapeInfo.h
@@ -49,7 +49,7 @@
         if (InfoType* info = infoMap.get(key))
             return info;
         typename InfoMap::AddResult result = infoMap.add(key, InfoType::createInfo(key));
-        return result.iterator->value.get();
+        return result.storedValue->value.get();
     }
     static void removeInfo(const KeyType* key) { infoMap().remove(key); }
     static InfoType* info(const KeyType* key) { return infoMap().get(key); }
@@ -70,26 +70,24 @@
 
     void setShapeSize(LayoutUnit logicalWidth, LayoutUnit logicalHeight)
     {
-        if (shapeValue()->type() == ShapeValue::Box) {
-            switch (shapeValue()->layoutBox()) {
-            case MarginBox:
-                logicalHeight += m_renderer->marginLogicalHeight();
-                logicalWidth += m_renderer->marginLogicalWidth();
-                break;
-            case BorderBox:
-                break;
-            case PaddingBox:
-                logicalHeight -= m_renderer->borderLogicalHeight();
-                logicalWidth -= m_renderer->borderLogicalWidth();
-                break;
-            case ContentBox:
-                logicalHeight -= m_renderer->borderAndPaddingLogicalHeight();
-                logicalWidth -= m_renderer->borderAndPaddingLogicalWidth();
-                break;
-            }
-        } else if (m_renderer->style()->boxSizing() == CONTENT_BOX) {
+        switch (resolvedLayoutBox()) {
+        case MarginBox:
+            logicalHeight += m_renderer->marginLogicalHeight();
+            logicalWidth += m_renderer->marginLogicalWidth();
+            break;
+        case BorderBox:
+            break;
+        case PaddingBox:
+            logicalHeight -= m_renderer->borderLogicalHeight();
+            logicalWidth -= m_renderer->borderLogicalWidth();
+            break;
+        case ContentBox:
             logicalHeight -= m_renderer->borderAndPaddingLogicalHeight();
             logicalWidth -= m_renderer->borderAndPaddingLogicalWidth();
+            break;
+        case BoxMissing:
+            // A non-missing box value must be supplied.
+            ASSERT_NOT_REACHED();
         }
 
         LayoutSize newLogicalSize(logicalWidth, logicalHeight);
@@ -125,42 +123,45 @@
 
     const Shape* computedShape() const;
 
+    virtual LayoutBox resolvedLayoutBox() const = 0;
     virtual LayoutRect computedShapeLogicalBoundingBox() const = 0;
     virtual ShapeValue* shapeValue() const = 0;
     virtual void getIntervals(LayoutUnit, LayoutUnit, SegmentList&) const = 0;
 
     LayoutUnit logicalTopOffset() const
     {
-        if (shapeValue()->type() == ShapeValue::Box) {
-            switch (shapeValue()->layoutBox()) {
-            case MarginBox:
-                return -m_renderer->marginBefore();
-            case BorderBox:
-                return LayoutUnit();
-            case PaddingBox:
-                return m_renderer->borderBefore();
-            case ContentBox:
-                return m_renderer->borderAndPaddingBefore();
-            }
+        switch (resolvedLayoutBox()) {
+        case MarginBox:
+            return -m_renderer->marginBefore();
+        case BorderBox:
+            return LayoutUnit();
+        case PaddingBox:
+            return m_renderer->borderBefore();
+        case ContentBox:
+            return m_renderer->borderAndPaddingBefore();
+        case BoxMissing:
+            // A non-missing box value must be supplied.
+            ASSERT_NOT_REACHED();
         }
-        return m_renderer->style()->boxSizing() == CONTENT_BOX ? m_renderer->borderAndPaddingBefore() : LayoutUnit();
+        return LayoutUnit();
     }
 
     LayoutUnit logicalLeftOffset() const
     {
-        if (shapeValue()->type() == ShapeValue::Box) {
-            switch (shapeValue()->layoutBox()) {
-            case MarginBox:
-                return -m_renderer->marginStart();
-            case BorderBox:
-                return LayoutUnit();
-            case PaddingBox:
-                return m_renderer->borderStart();
-            case ContentBox:
-                return m_renderer->borderAndPaddingStart();
-            }
+        switch (resolvedLayoutBox()) {
+        case MarginBox:
+            return -m_renderer->marginStart();
+        case BorderBox:
+            return LayoutUnit();
+        case PaddingBox:
+            return m_renderer->borderStart();
+        case ContentBox:
+            return m_renderer->borderAndPaddingStart();
+        case BoxMissing:
+            // A non-missing box value must be supplied.
+            ASSERT_NOT_REACHED();
         }
-        return (m_renderer->style()->boxSizing() == CONTENT_BOX && !m_renderer->isRenderRegion()) ? m_renderer->borderAndPaddingStart() : LayoutUnit();
+        return LayoutUnit();
     }
 
     LayoutUnit m_shapeLineTop;
diff --git a/Source/core/rendering/shapes/ShapeInsideInfo.cpp b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
index 301200b..13da8af 100644
--- a/Source/core/rendering/shapes/ShapeInsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
@@ -49,10 +49,11 @@
 
     switch (shapeValue->type()) {
     case ShapeValue::Shape:
-        return shapeValue->shape() && shapeValue->shape()->type() != BasicShape::BasicShapeInsetRectangleType;
+        return shapeValue->shape() && shapeValue->shape()->type() != BasicShape::BasicShapeInsetRectangleType && shapeValue->shape()->type() != BasicShape::BasicShapeInsetType;
     case ShapeValue::Image:
         return shapeValue->isImageValid() && checkShapeImageOrigin(renderer->document(), *(shapeValue->image()->cachedImage()));
     case ShapeValue::Box:
+        return true;
     case ShapeValue::Outside:
         return false;
     }
@@ -91,7 +92,7 @@
         return false;
 
     LayoutUnit newLineTop;
-    if (shape->firstIncludedIntervalLogicalTop(m_shapeLineTop, LayoutSize(minSegmentWidth, m_lineHeight), newLineTop)) {
+    if (shape->firstIncludedIntervalLogicalTop(m_shapeLineTop, FloatSize(minSegmentWidth, m_lineHeight), newLineTop)) {
         if (newLineTop > m_shapeLineTop) {
             m_shapeLineTop = newLineTop;
             return true;
@@ -106,7 +107,7 @@
     return m_renderer->style()->resolvedShapeInside();
 }
 
-LayoutUnit ShapeInsideInfo::computeFirstFitPositionForFloat(const LayoutSize floatSize) const
+LayoutUnit ShapeInsideInfo::computeFirstFitPositionForFloat(const FloatSize& floatSize) const
 {
     if (!computedShape() || !floatSize.width() || shapeLogicalBottom() < logicalLineTop())
         return 0;
diff --git a/Source/core/rendering/shapes/ShapeInsideInfo.h b/Source/core/rendering/shapes/ShapeInsideInfo.h
index 0f0f385..7828c05 100644
--- a/Source/core/rendering/shapes/ShapeInsideInfo.h
+++ b/Source/core/rendering/shapes/ShapeInsideInfo.h
@@ -89,7 +89,7 @@
     }
     void clearSegments() { m_segments.clear(); }
     bool adjustLogicalLineTop(float minSegmentWidth);
-    LayoutUnit computeFirstFitPositionForFloat(const LayoutSize) const;
+    LayoutUnit computeFirstFitPositionForFloat(const FloatSize&) const;
 
     void setNeedsLayout(bool value) { m_needsLayout = value; }
     bool needsLayout() { return m_needsLayout; }
@@ -100,6 +100,12 @@
     }
 
 protected:
+    virtual LayoutBox resolvedLayoutBox() const OVERRIDE
+    {
+        if (shapeValue()->layoutBox() == BoxMissing)
+            return ContentBox;
+        return shapeValue()->layoutBox();
+    }
     virtual LayoutRect computedShapeLogicalBoundingBox() const OVERRIDE { return computedShape()->shapePaddingLogicalBoundingBox(); }
     virtual ShapeValue* shapeValue() const OVERRIDE;
     virtual void getIntervals(LayoutUnit lineTop, LayoutUnit lineHeight, SegmentList& segments) const OVERRIDE
diff --git a/Source/core/rendering/shapes/ShapeOutsideInfo.h b/Source/core/rendering/shapes/ShapeOutsideInfo.h
index 82b31f6..17f5ddb 100644
--- a/Source/core/rendering/shapes/ShapeOutsideInfo.h
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.h
@@ -55,6 +55,12 @@
     }
 
 protected:
+    virtual LayoutBox resolvedLayoutBox() const OVERRIDE
+    {
+        if (shapeValue()->layoutBox() == BoxMissing)
+            return MarginBox;
+        return shapeValue()->layoutBox();
+    }
     virtual LayoutRect computedShapeLogicalBoundingBox() const OVERRIDE { return computedShape()->shapeMarginLogicalBoundingBox(); }
     virtual ShapeValue* shapeValue() const OVERRIDE;
     virtual void getIntervals(LayoutUnit lineTop, LayoutUnit lineHeight, SegmentList& segments) const OVERRIDE
diff --git a/Source/core/rendering/style/BasicShapes.cpp b/Source/core/rendering/style/BasicShapes.cpp
index 1eed605..8b9cbc5 100644
--- a/Source/core/rendering/style/BasicShapes.cpp
+++ b/Source/core/rendering/style/BasicShapes.cpp
@@ -28,8 +28,9 @@
  */
 
 #include "config.h"
-
 #include "core/rendering/style/BasicShapes.h"
+
+#include "core/css/BasicShapeFunctions.h"
 #include "platform/LengthFunctions.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/graphics/Path.h"
@@ -39,15 +40,35 @@
 bool BasicShape::canBlend(const BasicShape* other) const
 {
     // FIXME: Support animations between different shapes in the future.
-    if (type() != other->type())
+    if (!other || !isSameType(*other))
         return false;
 
     // Just polygons with same number of vertices can be animated.
     if (type() == BasicShape::BasicShapePolygonType
-        && static_cast<const BasicShapePolygon*>(this)->values().size() != static_cast<const BasicShapePolygon*>(other)->values().size())
+        && (static_cast<const BasicShapePolygon*>(this)->values().size() != static_cast<const BasicShapePolygon*>(other)->values().size()
+        || static_cast<const BasicShapePolygon*>(this)->windRule() != static_cast<const BasicShapePolygon*>(other)->windRule()))
         return false;
 
-    return true;
+    // Circles with keywords for radii or center coordinates cannot be animated.
+    if (type() == BasicShape::BasicShapeCircleType) {
+        const BasicShapeCircle* thisCircle = static_cast<const BasicShapeCircle*>(this);
+        const BasicShapeCircle* otherCircle = static_cast<const BasicShapeCircle*>(other);
+        if (!thisCircle->radius().canBlend(otherCircle->radius())
+            || !thisCircle->centerX().canBlend(otherCircle->centerX())
+            || !thisCircle->centerY().canBlend(otherCircle->centerY()))
+            return false;
+    }
+
+    // Ellipses with keywords for radii or center coordinates cannot be animated.
+    if (type() != BasicShape::BasicShapeEllipseType)
+        return true;
+
+    const BasicShapeEllipse* thisEllipse = static_cast<const BasicShapeEllipse*>(this);
+    const BasicShapeEllipse* otherEllipse = static_cast<const BasicShapeEllipse*>(other);
+    return (thisEllipse->radiusX().canBlend(otherEllipse->radiusX())
+        && thisEllipse->radiusY().canBlend(otherEllipse->radiusY())
+        && thisEllipse->centerX().canBlend(otherEllipse->centerX())
+        && thisEllipse->centerY().canBlend(otherEllipse->centerY()));
 }
 
 void BasicShapeRectangle::path(Path& path, const FloatRect& boundingBox)
@@ -69,7 +90,7 @@
 
 PassRefPtr<BasicShape> BasicShapeRectangle::blend(const BasicShape* other, double progress) const
 {
-    ASSERT(type() == other->type());
+    ASSERT(other && isSameType(*other));
 
     const BasicShapeRectangle* o = static_cast<const BasicShapeRectangle*>(other);
     RefPtr<BasicShapeRectangle> result =  BasicShapeRectangle::create();
@@ -82,10 +103,26 @@
     return result.release();
 }
 
-void BasicShapeCircle::path(Path& path, const FloatRect& boundingBox)
+bool BasicShapeRectangle::operator==(const BasicShape& o) const
+{
+    if (!isSameType(o))
+        return false;
+    const BasicShapeRectangle& other = toBasicShapeRectangle(o);
+    return m_y == other.m_y && m_x == other.m_x && m_width == other.m_width && m_height == other.m_height && m_cornerRadiusX == other.m_cornerRadiusX && m_cornerRadiusY == other.m_cornerRadiusY;
+}
+
+bool DeprecatedBasicShapeCircle::operator==(const BasicShape& o) const
+{
+    if (!isSameType(o))
+        return false;
+    const DeprecatedBasicShapeCircle& other = toDeprecatedBasicShapeCircle(o);
+    return m_centerX == other.m_centerX && m_centerY == other.m_centerY && m_radius == other.m_radius;
+}
+
+void DeprecatedBasicShapeCircle::path(Path& path, const FloatRect& boundingBox)
 {
     ASSERT(path.isEmpty());
-    float diagonal = sqrtf((boundingBox.width() * boundingBox.width() + boundingBox.height() * boundingBox.height()) / 2);
+    float diagonal = hypotf(boundingBox.width(), boundingBox.height()) / sqrtf(2);
     float centerX = floatValueForLength(m_centerX, boundingBox.width());
     float centerY = floatValueForLength(m_centerY, boundingBox.height());
     float radius = floatValueForLength(m_radius, diagonal);
@@ -97,19 +134,66 @@
     ));
 }
 
-PassRefPtr<BasicShape> BasicShapeCircle::blend(const BasicShape* other, double progress) const
+PassRefPtr<BasicShape> DeprecatedBasicShapeCircle::blend(const BasicShape* other, double progress) const
 {
-    ASSERT(type() == other->type());
+    ASSERT(other && isSameType(*other));
 
-    const BasicShapeCircle* o = static_cast<const BasicShapeCircle*>(other);
-    RefPtr<BasicShapeCircle> result =  BasicShapeCircle::create();
+    const DeprecatedBasicShapeCircle* o = static_cast<const DeprecatedBasicShapeCircle*>(other);
+    RefPtr<DeprecatedBasicShapeCircle> result =  DeprecatedBasicShapeCircle::create();
     result->setCenterX(m_centerX.blend(o->centerX(), progress, ValueRangeAll));
     result->setCenterY(m_centerY.blend(o->centerY(), progress, ValueRangeAll));
     result->setRadius(m_radius.blend(o->radius(), progress, ValueRangeNonNegative));
     return result.release();
 }
 
-void BasicShapeEllipse::path(Path& path, const FloatRect& boundingBox)
+bool BasicShapeCircle::operator==(const BasicShape& o) const
+{
+    if (!isSameType(o))
+        return false;
+    const BasicShapeCircle& other = toBasicShapeCircle(o);
+    return m_centerX == other.m_centerX && m_centerY == other.m_centerY && m_radius == other.m_radius;
+}
+
+float BasicShapeCircle::floatValueForRadiusInBox(FloatSize boxSize) const
+{
+    if (m_radius.type() == BasicShapeRadius::Value)
+        return floatValueForLength(m_radius.value(), hypotf(boxSize.width(), boxSize.height()) / sqrtf(2));
+
+    FloatPoint center = floatPointForCenterCoordinate(m_centerX, m_centerY, boxSize);
+
+    if (m_radius.type() == BasicShapeRadius::ClosestSide)
+        return std::min(std::min(center.x(), boxSize.width() - center.x()), std::min(center.y(), boxSize.height() - center.y()));
+
+    // If radius.type() == BasicShapeRadius::FarthestSide.
+    return std::max(std::max(center.x(), boxSize.width() - center.x()), std::max(center.y(), boxSize.height() - center.y()));
+}
+
+void BasicShapeCircle::path(Path& path, const FloatRect& boundingBox)
+{
+    ASSERT(path.isEmpty());
+    FloatPoint center = floatPointForCenterCoordinate(m_centerX, m_centerY, boundingBox.size());
+    float radius = floatValueForRadiusInBox(boundingBox.size());
+    path.addEllipse(FloatRect(
+        center.x() - radius + boundingBox.x(),
+        center.y() - radius + boundingBox.y(),
+        radius * 2,
+        radius * 2
+    ));
+}
+
+PassRefPtr<BasicShape> BasicShapeCircle::blend(const BasicShape* other, double progress) const
+{
+    ASSERT(type() == other->type());
+    const BasicShapeCircle* o = static_cast<const BasicShapeCircle*>(other);
+    RefPtr<BasicShapeCircle> result =  BasicShapeCircle::create();
+
+    result->setCenterX(m_centerX.blend(o->centerX(), progress));
+    result->setCenterY(m_centerY.blend(o->centerY(), progress));
+    result->setRadius(m_radius.blend(o->radius(), progress));
+    return result.release();
+}
+
+void DeprecatedBasicShapeEllipse::path(Path& path, const FloatRect& boundingBox)
 {
     ASSERT(path.isEmpty());
     float centerX = floatValueForLength(m_centerX, boundingBox.width());
@@ -124,12 +208,20 @@
     ));
 }
 
-PassRefPtr<BasicShape> BasicShapeEllipse::blend(const BasicShape* other, double progress) const
+bool DeprecatedBasicShapeEllipse::operator==(const BasicShape& o) const
 {
-    ASSERT(type() == other->type());
+    if (!isSameType(o))
+        return false;
+    const DeprecatedBasicShapeEllipse& other = toDeprecatedBasicShapeEllipse(o);
+    return m_centerX == other.m_centerX && m_centerY == other.m_centerY && m_radiusX == other.m_radiusX && m_radiusY == other.m_radiusY;
+}
 
-    const BasicShapeEllipse* o = static_cast<const BasicShapeEllipse*>(other);
-    RefPtr<BasicShapeEllipse> result =  BasicShapeEllipse::create();
+PassRefPtr<BasicShape> DeprecatedBasicShapeEllipse::blend(const BasicShape* other, double progress) const
+{
+    ASSERT(other && isSameType(*other));
+
+    const DeprecatedBasicShapeEllipse* o = static_cast<const DeprecatedBasicShapeEllipse*>(other);
+    RefPtr<DeprecatedBasicShapeEllipse> result = DeprecatedBasicShapeEllipse::create();
     result->setCenterX(m_centerX.blend(o->centerX(), progress, ValueRangeAll));
     result->setCenterY(m_centerY.blend(o->centerY(), progress, ValueRangeAll));
     result->setRadiusX(m_radiusX.blend(o->radiusX(), progress, ValueRangeNonNegative));
@@ -137,6 +229,62 @@
     return result.release();
 }
 
+bool BasicShapeEllipse::operator==(const BasicShape& o) const
+{
+    if (!isSameType(o))
+        return false;
+    const BasicShapeEllipse& other = toBasicShapeEllipse(o);
+    return m_centerX == other.m_centerX && m_centerY == other.m_centerY && m_radiusX == other.m_radiusX && m_radiusY == other.m_radiusY;
+}
+
+float BasicShapeEllipse::floatValueForRadiusInBox(const BasicShapeRadius& radius, float center, float boxWidthOrHeight) const
+{
+    if (radius.type() == BasicShapeRadius::Value)
+        return floatValueForLength(radius.value(), boxWidthOrHeight);
+
+    if (radius.type() == BasicShapeRadius::ClosestSide)
+        return std::min(center, boxWidthOrHeight - center);
+
+    ASSERT(radius.type() == BasicShapeRadius::FarthestSide);
+    return std::max(center, boxWidthOrHeight - center);
+}
+
+void BasicShapeEllipse::path(Path& path, const FloatRect& boundingBox)
+{
+    ASSERT(path.isEmpty());
+    FloatPoint center = floatPointForCenterCoordinate(m_centerX, m_centerY, boundingBox.size());
+    float radiusX = floatValueForRadiusInBox(m_radiusX, center.x(), boundingBox.width());
+    float radiusY = floatValueForRadiusInBox(m_radiusY, center.y(), boundingBox.height());
+    path.addEllipse(FloatRect(
+        center.x() - radiusX + boundingBox.x(),
+        center.y() - radiusY + boundingBox.y(),
+        radiusX * 2,
+        radiusY * 2
+    ));
+}
+
+PassRefPtr<BasicShape> BasicShapeEllipse::blend(const BasicShape* other, double progress) const
+{
+    ASSERT(type() == other->type());
+    const BasicShapeEllipse* o = static_cast<const BasicShapeEllipse*>(other);
+    RefPtr<BasicShapeEllipse> result =  BasicShapeEllipse::create();
+
+    if (m_radiusX.type() != BasicShapeRadius::Value || o->radiusX().type() != BasicShapeRadius::Value
+        || m_radiusY.type() != BasicShapeRadius::Value || o->radiusY().type() != BasicShapeRadius::Value) {
+        result->setCenterX(o->centerX());
+        result->setCenterY(o->centerY());
+        result->setRadiusX(o->radiusX());
+        result->setRadiusY(o->radiusY());
+        return result;
+    }
+
+    result->setCenterX(m_centerX.blend(o->centerX(), progress));
+    result->setCenterY(m_centerY.blend(o->centerY(), progress));
+    result->setRadiusX(m_radiusX.blend(o->radiusX(), progress));
+    result->setRadiusY(m_radiusY.blend(o->radiusY(), progress));
+    return result.release();
+}
+
 void BasicShapePolygon::path(Path& path, const FloatRect& boundingBox)
 {
     ASSERT(path.isEmpty());
@@ -157,7 +305,7 @@
 
 PassRefPtr<BasicShape> BasicShapePolygon::blend(const BasicShape* other, double progress) const
 {
-    ASSERT(type() == other->type());
+    ASSERT(other && isSameType(*other));
 
     const BasicShapePolygon* o = static_cast<const BasicShapePolygon*>(other);
     ASSERT(m_values.size() == o->values().size());
@@ -178,6 +326,14 @@
     return result.release();
 }
 
+bool BasicShapePolygon::operator==(const BasicShape& o) const
+{
+    if (!isSameType(o))
+        return false;
+    const BasicShapePolygon& other = toBasicShapePolygon(o);
+    return m_windRule == other.m_windRule && m_values == other.m_values;
+}
+
 void BasicShapeInsetRectangle::path(Path& path, const FloatRect& boundingBox)
 {
     ASSERT(path.isEmpty());
@@ -199,7 +355,7 @@
 
 PassRefPtr<BasicShape> BasicShapeInsetRectangle::blend(const BasicShape* other, double progress) const
 {
-    ASSERT(type() == other->type());
+    ASSERT(other && isSameType(*other));
 
     const BasicShapeInsetRectangle* o = static_cast<const BasicShapeInsetRectangle*>(other);
     RefPtr<BasicShapeInsetRectangle> result =  BasicShapeInsetRectangle::create();
@@ -211,4 +367,60 @@
     result->setCornerRadiusY(m_cornerRadiusY.blend(o->cornerRadiusY(), progress, ValueRangeNonNegative));
     return result.release();
 }
+
+bool BasicShapeInsetRectangle::operator==(const BasicShape& o) const
+{
+    if (!isSameType(o))
+        return false;
+    const BasicShapeInsetRectangle& other = toBasicShapeInsetRectangle(o);
+    return m_right == other.m_right && m_top == other.m_top && m_bottom == other.m_bottom && m_left == other.m_left && m_cornerRadiusX == other.m_cornerRadiusX && m_cornerRadiusY == other.m_cornerRadiusY;
+}
+
+static FloatSize floatSizeForLengthSize(const LengthSize& lengthSize, const FloatRect& boundingBox)
+{
+    return FloatSize(floatValueForLength(lengthSize.width(), boundingBox.width()),
+        floatValueForLength(lengthSize.height(), boundingBox.height()));
+}
+
+void BasicShapeInset::path(Path& path, const FloatRect& boundingBox)
+{
+    ASSERT(path.isEmpty());
+    float left = floatValueForLength(m_left, boundingBox.width());
+    float top = floatValueForLength(m_top, boundingBox.height());
+    path.addRoundedRect(
+        FloatRect(
+            left + boundingBox.x(),
+            top + boundingBox.y(),
+            std::max<float>(boundingBox.width() - left - floatValueForLength(m_right, boundingBox.width()), 0),
+            std::max<float>(boundingBox.height() - top - floatValueForLength(m_bottom, boundingBox.height()), 0)
+        ),
+        floatSizeForLengthSize(m_topLeftRadius, boundingBox),
+        floatSizeForLengthSize(m_topRightRadius, boundingBox),
+        floatSizeForLengthSize(m_bottomLeftRadius, boundingBox),
+        floatSizeForLengthSize(m_bottomRightRadius, boundingBox)
+    );
+}
+
+PassRefPtr<BasicShape> BasicShapeInset::blend(const BasicShape* other, double) const
+{
+    ASSERT(type() == other->type());
+    // FIXME: Implement blend for BasicShapeInset.
+    return 0;
+}
+
+bool BasicShapeInset::operator==(const BasicShape& o) const
+{
+    if (!isSameType(o))
+        return false;
+    const BasicShapeInset& other = toBasicShapeInset(o);
+    return m_right == other.m_right
+        && m_top == other.m_top
+        && m_bottom == other.m_bottom
+        && m_left == other.m_left
+        && m_topLeftRadius == other.m_topLeftRadius
+        && m_topRightRadius == other.m_topRightRadius
+        && m_bottomRightRadius == other.m_bottomRightRadius
+        && m_bottomLeftRadius == other.m_bottomLeftRadius;
+}
+
 }
diff --git a/Source/core/rendering/style/BasicShapes.h b/Source/core/rendering/style/BasicShapes.h
index b8735a8..683ec38 100644
--- a/Source/core/rendering/style/BasicShapes.h
+++ b/Source/core/rendering/style/BasicShapes.h
@@ -30,7 +30,9 @@
 #ifndef BasicShapes_h
 #define BasicShapes_h
 
+#include "core/rendering/style/RenderStyleConstants.h"
 #include "platform/Length.h"
+#include "platform/LengthSize.h"
 #include "platform/graphics/WindRule.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
@@ -39,6 +41,7 @@
 namespace WebCore {
 
 class FloatRect;
+class FloatSize;
 class Path;
 
 class BasicShape : public RefCounted<BasicShape> {
@@ -46,25 +49,43 @@
     virtual ~BasicShape() { }
 
     enum Type {
-        BasicShapeRectangleType = 1,
-        BasicShapeCircleType = 2,
-        BasicShapeEllipseType = 3,
-        BasicShapePolygonType = 4,
-        BasicShapeInsetRectangleType = 5
+        BasicShapeRectangleType,
+        DeprecatedBasicShapeCircleType,
+        DeprecatedBasicShapeEllipseType,
+        BasicShapeEllipseType,
+        BasicShapePolygonType,
+        BasicShapeInsetRectangleType,
+        BasicShapeCircleType,
+        BasicShapeInsetType
     };
 
     bool canBlend(const BasicShape*) const;
+    bool isSameType(const BasicShape& other) const { return type() == other.type(); }
 
     virtual void path(Path&, const FloatRect&) = 0;
     virtual WindRule windRule() const { return RULE_NONZERO; }
     virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const = 0;
+    virtual bool operator==(const BasicShape&) const = 0;
 
     virtual Type type() const = 0;
+
+    LayoutBox layoutBox() const { return m_layoutBox; }
+    void setLayoutBox(LayoutBox layoutBox) { m_layoutBox = layoutBox; }
+
 protected:
-    BasicShape() { }
+    BasicShape()
+        : m_layoutBox(BoxMissing)
+    {
+    }
+
+private:
+    LayoutBox m_layoutBox;
 };
 
-class BasicShapeRectangle : public BasicShape {
+#define DEFINE_BASICSHAPE_TYPE_CASTS(thisType) \
+    DEFINE_TYPE_CASTS(thisType, BasicShape, value, value->type() == BasicShape::thisType##Type, value.type() == BasicShape::thisType##Type)
+
+class BasicShapeRectangle FINAL : public BasicShape {
 public:
     static PassRefPtr<BasicShapeRectangle> create() { return adoptRef(new BasicShapeRectangle); }
 
@@ -81,19 +102,18 @@
     void setHeight(Length height) { m_height = height; }
     void setCornerRadiusX(Length radiusX)
     {
-        ASSERT(!radiusX.isUndefined());
         m_cornerRadiusX = radiusX;
     }
     void setCornerRadiusY(Length radiusY)
     {
-        ASSERT(!radiusY.isUndefined());
         m_cornerRadiusY = radiusY;
     }
 
     virtual void path(Path&, const FloatRect&) OVERRIDE;
     virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
+    virtual bool operator==(const BasicShape&) const OVERRIDE;
 
-    virtual Type type() const { return BasicShapeRectangleType; }
+    virtual Type type() const OVERRIDE { return BasicShapeRectangleType; }
 private:
     BasicShapeRectangle() { }
 
@@ -105,10 +125,113 @@
     Length m_cornerRadiusY;
 };
 
-class BasicShapeCircle : public BasicShape {
+DEFINE_BASICSHAPE_TYPE_CASTS(BasicShapeRectangle);
+
+class BasicShapeCenterCoordinate {
+public:
+    enum Keyword {
+        None,
+        Top,
+        Right,
+        Bottom,
+        Left
+    };
+    BasicShapeCenterCoordinate() : m_keyword(None), m_length(Undefined) { }
+    explicit BasicShapeCenterCoordinate(Length length) : m_keyword(None), m_length(length) { }
+    BasicShapeCenterCoordinate(Keyword keyword, Length length) : m_keyword(keyword), m_length(length) { }
+    BasicShapeCenterCoordinate(const BasicShapeCenterCoordinate& other) : m_keyword(other.keyword()), m_length(other.length()) { }
+    bool operator==(const BasicShapeCenterCoordinate& other) const { return m_keyword == other.m_keyword && m_length == other.m_length; }
+
+    Keyword keyword() const { return m_keyword; }
+    const Length& length() const { return m_length; }
+
+    bool canBlend(const BasicShapeCenterCoordinate& other) const
+    {
+        // FIXME determine how to interpolate between keywords. See issue 330248.
+        return m_keyword == None && other.keyword() == None;
+    }
+
+    BasicShapeCenterCoordinate blend(const BasicShapeCenterCoordinate& other, double progress) const
+    {
+        if (m_keyword != None || other.keyword() != None)
+            return BasicShapeCenterCoordinate(other);
+
+        return BasicShapeCenterCoordinate(m_length.blend(other.length(), progress, ValueRangeAll));
+    }
+
+private:
+    Keyword m_keyword;
+    Length m_length;
+};
+
+class BasicShapeRadius {
+public:
+    enum Type {
+        Value,
+        ClosestSide,
+        FarthestSide
+    };
+    BasicShapeRadius() : m_value(Undefined), m_type(ClosestSide) { }
+    explicit BasicShapeRadius(Length v) : m_value(v), m_type(Value) { }
+    explicit BasicShapeRadius(Type t) : m_value(Undefined), m_type(t) { }
+    BasicShapeRadius(const BasicShapeRadius& other) : m_value(other.value()), m_type(other.type()) { }
+    bool operator==(const BasicShapeRadius& other) const { return m_type == other.m_type && m_value == other.m_value; }
+
+    const Length& value() const { return m_value; }
+    Type type() const { return m_type; }
+
+    bool canBlend(const BasicShapeRadius& other) const
+    {
+        // FIXME determine how to interpolate between keywords. See issue 330248.
+        return m_type == Value && other.type() == Value;
+    }
+
+    BasicShapeRadius blend(const BasicShapeRadius& other, double progress) const
+    {
+        if (m_type != Value || other.type() != Value)
+            return BasicShapeRadius(other);
+
+        return BasicShapeRadius(m_value.blend(other.value(), progress, ValueRangeAll));
+    }
+
+private:
+    Length m_value;
+    Type m_type;
+
+};
+
+class BasicShapeCircle FINAL : public BasicShape {
 public:
     static PassRefPtr<BasicShapeCircle> create() { return adoptRef(new BasicShapeCircle); }
 
+    const BasicShapeCenterCoordinate& centerX() const { return m_centerX; }
+    const BasicShapeCenterCoordinate& centerY() const { return m_centerY; }
+    const BasicShapeRadius& radius() const { return m_radius; }
+
+    float floatValueForRadiusInBox(FloatSize) const;
+    void setCenterX(BasicShapeCenterCoordinate centerX) { m_centerX = centerX; }
+    void setCenterY(BasicShapeCenterCoordinate centerY) { m_centerY = centerY; }
+    void setRadius(BasicShapeRadius radius) { m_radius = radius; }
+
+    virtual void path(Path&, const FloatRect&) OVERRIDE;
+    virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
+    virtual bool operator==(const BasicShape&) const OVERRIDE;
+
+    virtual Type type() const OVERRIDE { return BasicShapeCircleType; }
+private:
+    BasicShapeCircle() { }
+
+    BasicShapeCenterCoordinate m_centerX;
+    BasicShapeCenterCoordinate m_centerY;
+    BasicShapeRadius m_radius;
+};
+
+DEFINE_BASICSHAPE_TYPE_CASTS(BasicShapeCircle);
+
+class DeprecatedBasicShapeCircle FINAL : public BasicShape {
+public:
+    static PassRefPtr<DeprecatedBasicShapeCircle> create() { return adoptRef(new DeprecatedBasicShapeCircle); }
+
     Length centerX() const { return m_centerX; }
     Length centerY() const { return m_centerY; }
     Length radius() const { return m_radius; }
@@ -119,20 +242,54 @@
 
     virtual void path(Path&, const FloatRect&) OVERRIDE;
     virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
+    virtual bool operator==(const BasicShape&) const OVERRIDE;
 
-    virtual Type type() const { return BasicShapeCircleType; }
+    virtual Type type() const OVERRIDE { return DeprecatedBasicShapeCircleType; }
 private:
-    BasicShapeCircle() { }
+    DeprecatedBasicShapeCircle() { }
 
     Length m_centerX;
     Length m_centerY;
     Length m_radius;
 };
 
-class BasicShapeEllipse : public BasicShape {
+DEFINE_BASICSHAPE_TYPE_CASTS(DeprecatedBasicShapeCircle);
+
+class BasicShapeEllipse FINAL : public BasicShape {
 public:
     static PassRefPtr<BasicShapeEllipse> create() { return adoptRef(new BasicShapeEllipse); }
 
+    const BasicShapeCenterCoordinate& centerX() const { return m_centerX; }
+    const BasicShapeCenterCoordinate& centerY() const { return m_centerY; }
+    const BasicShapeRadius& radiusX() const { return m_radiusX; }
+    const BasicShapeRadius& radiusY() const { return m_radiusY; }
+    float floatValueForRadiusInBox(const BasicShapeRadius&, float center, float boxWidthOrHeight) const;
+
+    void setCenterX(BasicShapeCenterCoordinate centerX) { m_centerX = centerX; }
+    void setCenterY(BasicShapeCenterCoordinate centerY) { m_centerY = centerY; }
+    void setRadiusX(BasicShapeRadius radiusX) { m_radiusX = radiusX; }
+    void setRadiusY(BasicShapeRadius radiusY) { m_radiusY = radiusY; }
+
+    virtual void path(Path&, const FloatRect&) OVERRIDE;
+    virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
+    virtual bool operator==(const BasicShape&) const OVERRIDE;
+
+    virtual Type type() const OVERRIDE { return BasicShapeEllipseType; }
+private:
+    BasicShapeEllipse() { }
+
+    BasicShapeCenterCoordinate m_centerX;
+    BasicShapeCenterCoordinate m_centerY;
+    BasicShapeRadius m_radiusX;
+    BasicShapeRadius m_radiusY;
+};
+
+DEFINE_BASICSHAPE_TYPE_CASTS(BasicShapeEllipse);
+
+class DeprecatedBasicShapeEllipse FINAL : public BasicShape {
+public:
+    static PassRefPtr<DeprecatedBasicShapeEllipse> create() { return adoptRef(new DeprecatedBasicShapeEllipse); }
+
     Length centerX() const { return m_centerX; }
     Length centerY() const { return m_centerY; }
     Length radiusX() const { return m_radiusX; }
@@ -145,10 +302,11 @@
 
     virtual void path(Path&, const FloatRect&) OVERRIDE;
     virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
+    virtual bool operator==(const BasicShape&) const OVERRIDE;
 
-    virtual Type type() const { return BasicShapeEllipseType; }
+    virtual Type type() const OVERRIDE { return DeprecatedBasicShapeEllipseType; }
 private:
-    BasicShapeEllipse() { }
+    DeprecatedBasicShapeEllipse() { }
 
     Length m_centerX;
     Length m_centerY;
@@ -156,7 +314,9 @@
     Length m_radiusY;
 };
 
-class BasicShapePolygon : public BasicShape {
+DEFINE_BASICSHAPE_TYPE_CASTS(DeprecatedBasicShapeEllipse);
+
+class BasicShapePolygon FINAL : public BasicShape {
 public:
     static PassRefPtr<BasicShapePolygon> create() { return adoptRef(new BasicShapePolygon); }
 
@@ -169,10 +329,11 @@
 
     virtual void path(Path&, const FloatRect&) OVERRIDE;
     virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
+    virtual bool operator==(const BasicShape&) const OVERRIDE;
 
-    virtual WindRule windRule() const { return m_windRule; }
+    virtual WindRule windRule() const OVERRIDE { return m_windRule; }
 
-    virtual Type type() const { return BasicShapePolygonType; }
+    virtual Type type() const OVERRIDE { return BasicShapePolygonType; }
 private:
     BasicShapePolygon()
         : m_windRule(RULE_NONZERO)
@@ -182,7 +343,9 @@
     Vector<Length> m_values;
 };
 
-class BasicShapeInsetRectangle : public BasicShape {
+DEFINE_BASICSHAPE_TYPE_CASTS(BasicShapePolygon);
+
+class BasicShapeInsetRectangle FINAL : public BasicShape {
 public:
     static PassRefPtr<BasicShapeInsetRectangle> create() { return adoptRef(new BasicShapeInsetRectangle); }
 
@@ -199,19 +362,18 @@
     void setLeft(Length left) { m_left = left; }
     void setCornerRadiusX(Length radiusX)
     {
-        ASSERT(!radiusX.isUndefined());
         m_cornerRadiusX = radiusX;
     }
     void setCornerRadiusY(Length radiusY)
     {
-        ASSERT(!radiusY.isUndefined());
         m_cornerRadiusY = radiusY;
     }
 
     virtual void path(Path&, const FloatRect&) OVERRIDE;
     virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
+    virtual bool operator==(const BasicShape&) const OVERRIDE;
 
-    virtual Type type() const { return BasicShapeInsetRectangleType; }
+    virtual Type type() const OVERRIDE { return BasicShapeInsetRectangleType; }
 private:
     BasicShapeInsetRectangle() { }
 
@@ -222,5 +384,53 @@
     Length m_cornerRadiusX;
     Length m_cornerRadiusY;
 };
+
+DEFINE_BASICSHAPE_TYPE_CASTS(BasicShapeInsetRectangle);
+
+class BasicShapeInset : public BasicShape {
+public:
+    static PassRefPtr<BasicShapeInset> create() { return adoptRef(new BasicShapeInset); }
+
+    const Length& top() const { return m_top; }
+    const Length& right() const { return m_right; }
+    const Length& bottom() const { return m_bottom; }
+    const Length& left() const { return m_left; }
+
+    const LengthSize& topLeftRadius() const { return m_topLeftRadius; }
+    const LengthSize& topRightRadius() const { return m_topRightRadius; }
+    const LengthSize& bottomRightRadius() const { return m_bottomRightRadius; }
+    const LengthSize& bottomLeftRadius() const { return m_bottomLeftRadius; }
+
+    void setTop(Length top) { m_top = top; }
+    void setRight(Length right) { m_right = right; }
+    void setBottom(Length bottom) { m_bottom = bottom; }
+    void setLeft(Length left) { m_left = left; }
+
+    void setTopLeftRadius(LengthSize radius) { m_topLeftRadius = radius; }
+    void setTopRightRadius(LengthSize radius) { m_topRightRadius = radius; }
+    void setBottomRightRadius(LengthSize radius) { m_bottomRightRadius = radius; }
+    void setBottomLeftRadius(LengthSize radius) { m_bottomLeftRadius = radius; }
+
+    virtual void path(Path&, const FloatRect&) OVERRIDE;
+    virtual PassRefPtr<BasicShape> blend(const BasicShape*, double) const OVERRIDE;
+    virtual bool operator==(const BasicShape&) const OVERRIDE;
+
+    virtual Type type() const OVERRIDE { return BasicShapeInsetType; }
+private:
+    BasicShapeInset() { }
+
+    Length m_right;
+    Length m_top;
+    Length m_bottom;
+    Length m_left;
+
+    LengthSize m_topLeftRadius;
+    LengthSize m_topRightRadius;
+    LengthSize m_bottomRightRadius;
+    LengthSize m_bottomLeftRadius;
+};
+
+DEFINE_BASICSHAPE_TYPE_CASTS(BasicShapeInset);
+
 }
 #endif
diff --git a/Source/core/rendering/style/BorderValue.h b/Source/core/rendering/style/BorderValue.h
index dcd5096..8703132 100644
--- a/Source/core/rendering/style/BorderValue.h
+++ b/Source/core/rendering/style/BorderValue.h
@@ -25,6 +25,7 @@
 #ifndef BorderValue_h
 #define BorderValue_h
 
+#include "core/css/StyleColor.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "platform/graphics/Color.h"
 
@@ -35,7 +36,7 @@
 public:
     BorderValue()
         : m_color(0)
-        , m_colorIsValid(false)
+        , m_colorIsCurrentColor(true)
         , m_width(3)
         , m_style(BNONE)
         , m_isAuto(AUTO_OFF)
@@ -49,7 +50,7 @@
 
     bool isTransparent() const
     {
-        return m_colorIsValid && !alphaChannel(m_color);
+        return !m_colorIsCurrentColor && !m_color.alpha();
     }
 
     bool isVisible(bool checkStyle = true) const
@@ -59,7 +60,7 @@
 
     bool operator==(const BorderValue& o) const
     {
-        return m_width == o.m_width && m_style == o.m_style && m_color == o.m_color && m_colorIsValid == o.m_colorIsValid;
+        return m_width == o.m_width && m_style == o.m_style && m_color == o.m_color && m_colorIsCurrentColor == o.m_colorIsCurrentColor;
     }
 
     bool operator!=(const BorderValue& o) const
@@ -67,20 +68,20 @@
         return !(*this == o);
     }
 
-    void setColor(const Color& color)
+    void setColor(const StyleColor& color)
     {
-        m_color = color.rgb();
-        m_colorIsValid = color.isValid();
+        m_color = color.resolve(Color());
+        m_colorIsCurrentColor = color.isCurrentColor();
     }
 
-    Color color() const { return Color(m_color, m_colorIsValid); }
+    StyleColor color() const { return m_colorIsCurrentColor ? StyleColor::currentColor() : StyleColor(m_color); }
 
     unsigned width() const { return m_width; }
     EBorderStyle style() const { return static_cast<EBorderStyle>(m_style); }
 
 protected:
-    RGBA32 m_color;
-    unsigned m_colorIsValid : 1;
+    Color m_color;
+    unsigned m_colorIsCurrentColor : 1;
 
     unsigned m_width : 26;
     unsigned m_style : 4; // EBorderStyle
diff --git a/Source/core/rendering/style/CachedUAStyle.h b/Source/core/rendering/style/CachedUAStyle.h
index f56d66f..2b98e51 100644
--- a/Source/core/rendering/style/CachedUAStyle.h
+++ b/Source/core/rendering/style/CachedUAStyle.h
@@ -35,11 +35,13 @@
     CachedUAStyle()
         : hasAppearance(false)
         , backgroundLayers(BackgroundFillLayer)
+        , backgroundColor(StyleColor::currentColor())
     { }
 
     explicit CachedUAStyle(const RenderStyle* style)
         : hasAppearance(style->hasAppearance())
         , backgroundLayers(BackgroundFillLayer)
+        , backgroundColor(StyleColor::currentColor())
     {
         // RenderTheme::adjustStyle is the only consumer of this data.
         // It only cares about the styles if appearance is set,
@@ -54,7 +56,7 @@
     bool hasAppearance;
     BorderData border;
     FillLayer backgroundLayers;
-    Color backgroundColor;
+    StyleColor backgroundColor;
 };
 
 
diff --git a/Source/core/rendering/style/CollapsedBorderValue.h b/Source/core/rendering/style/CollapsedBorderValue.h
index ef16dba..ac7b057 100644
--- a/Source/core/rendering/style/CollapsedBorderValue.h
+++ b/Source/core/rendering/style/CollapsedBorderValue.h
@@ -33,7 +33,7 @@
 public:
     CollapsedBorderValue()
         : m_color(0)
-        , m_colorIsValid(false)
+        , m_colorIsCurrentColor(true)
         , m_width(0)
         , m_style(BNONE)
         , m_precedence(BOFF)
@@ -41,9 +41,9 @@
     {
     }
 
-    CollapsedBorderValue(const BorderValue& border, const Color& color, EBorderPrecedence precedence)
-        : m_color(color.rgb())
-        , m_colorIsValid(color.isValid())
+    CollapsedBorderValue(const BorderValue& border, const StyleColor& color, EBorderPrecedence precedence)
+        : m_color(color.resolve(Color()))
+        , m_colorIsCurrentColor(color.isCurrentColor())
         , m_width(border.nonZero() ? border.width() : 0)
         , m_style(border.style())
         , m_precedence(precedence)
@@ -54,7 +54,7 @@
     unsigned width() const { return m_style > BHIDDEN ? m_width : 0; }
     EBorderStyle style() const { return static_cast<EBorderStyle>(m_style); }
     bool exists() const { return m_precedence != BOFF; }
-    Color color() const { return Color(m_color, m_colorIsValid); }
+    StyleColor color() const { return m_colorIsCurrentColor ? StyleColor::currentColor() : StyleColor(m_color); }
     bool isTransparent() const { return m_transparent; }
     EBorderPrecedence precedence() const { return static_cast<EBorderPrecedence>(m_precedence); }
 
@@ -64,8 +64,8 @@
     }
 
 private:
-    RGBA32 m_color;
-    unsigned m_colorIsValid : 1;
+    Color m_color;
+    unsigned m_colorIsCurrentColor : 1;
     unsigned m_width : 23;
     unsigned m_style : 4; // EBorderStyle
     unsigned m_precedence : 3; // EBorderPrecedence
diff --git a/Source/core/rendering/style/ContentData.h b/Source/core/rendering/style/ContentData.h
index 77dd561..a01f6cc 100644
--- a/Source/core/rendering/style/ContentData.h
+++ b/Source/core/rendering/style/ContentData.h
@@ -66,7 +66,7 @@
     OwnPtr<ContentData> m_next;
 };
 
-class ImageContentData : public ContentData {
+class ImageContentData FINAL : public ContentData {
     friend class ContentData;
 public:
     const StyleImage* image() const { return m_image.get(); }
@@ -89,7 +89,7 @@
     {
     }
 
-    virtual PassOwnPtr<ContentData> cloneInternal() const
+    virtual PassOwnPtr<ContentData> cloneInternal() const OVERRIDE
     {
         RefPtr<StyleImage> image = const_cast<StyleImage*>(this->image());
         return create(image.release());
@@ -98,7 +98,7 @@
     RefPtr<StyleImage> m_image;
 };
 
-class TextContentData : public ContentData {
+class TextContentData FINAL : public ContentData {
     friend class ContentData;
 public:
     const String& text() const { return m_text; }
@@ -120,12 +120,12 @@
     {
     }
 
-    virtual PassOwnPtr<ContentData> cloneInternal() const { return create(text()); }
+    virtual PassOwnPtr<ContentData> cloneInternal() const OVERRIDE { return create(text()); }
 
     String m_text;
 };
 
-class CounterContentData : public ContentData {
+class CounterContentData FINAL : public ContentData {
     friend class ContentData;
 public:
     const CounterContent* counter() const { return m_counter.get(); }
@@ -140,7 +140,7 @@
     {
     }
 
-    virtual PassOwnPtr<ContentData> cloneInternal() const
+    virtual PassOwnPtr<ContentData> cloneInternal() const OVERRIDE
     {
         OwnPtr<CounterContent> counterData = adoptPtr(new CounterContent(*counter()));
         return create(counterData.release());
@@ -156,7 +156,7 @@
     OwnPtr<CounterContent> m_counter;
 };
 
-class QuoteContentData : public ContentData {
+class QuoteContentData FINAL : public ContentData {
     friend class ContentData;
 public:
     QuoteType quote() const { return m_quote; }
@@ -178,7 +178,7 @@
     {
     }
 
-    virtual PassOwnPtr<ContentData> cloneInternal() const { return create(quote()); }
+    virtual PassOwnPtr<ContentData> cloneInternal() const OVERRIDE { return create(quote()); }
 
     QuoteType m_quote;
 };
diff --git a/Source/core/rendering/style/FillLayer.cpp b/Source/core/rendering/style/FillLayer.cpp
index 62f349c..0df7e95 100644
--- a/Source/core/rendering/style/FillLayer.cpp
+++ b/Source/core/rendering/style/FillLayer.cpp
@@ -34,8 +34,8 @@
 
     LengthSize m_sizeLength;
 
-    unsigned m_bitfields: 32;
-    unsigned m_bitfields2: 1;
+    unsigned m_bitfields1;
+    unsigned m_bitfields2;
 };
 
 COMPILE_ASSERT(sizeof(FillLayer) == sizeof(SameSizeAsFillLayer), FillLayer_should_stay_small);
@@ -65,8 +65,8 @@
     , m_repeatYSet(useInitialValues)
     , m_xPosSet(useInitialValues)
     , m_yPosSet(useInitialValues)
-    , m_backgroundXOriginSet(useInitialValues)
-    , m_backgroundYOriginSet(useInitialValues)
+    , m_backgroundXOriginSet(false)
+    , m_backgroundYOriginSet(false)
     , m_compositeSet(useInitialValues || type == MaskFillLayer)
     , m_blendModeSet(useInitialValues)
     , m_maskSourceTypeSet(useInitialValues)
diff --git a/Source/core/rendering/style/GridLength.h b/Source/core/rendering/style/GridLength.h
index dadf7da..e822d08 100644
--- a/Source/core/rendering/style/GridLength.h
+++ b/Source/core/rendering/style/GridLength.h
@@ -40,32 +40,26 @@
 // an new unit to Length.h.
 class GridLength {
 public:
-    GridLength()
-        : m_length(Undefined)
-        , m_flex(0)
-        , m_type(LengthType)
-    {
-    }
-
     GridLength(const Length& length)
         : m_length(length)
         , m_flex(0)
         , m_type(LengthType)
     {
+        ASSERT(!length.isUndefined());
+    }
+
+    explicit GridLength(double flex)
+        : m_flex(flex)
+        , m_type(FlexType)
+    {
     }
 
     bool isLength() const { return m_type == LengthType; }
     bool isFlex() const { return m_type == FlexType; }
 
     const Length& length() const { ASSERT(isLength()); return m_length; }
-    Length& length() { ASSERT(isLength()); return m_length; }
 
     double flex() const { ASSERT(isFlex()); return m_flex; }
-    void setFlex(double flex)
-    {
-        m_type = FlexType;
-        m_flex = flex;
-    }
 
     bool operator==(const GridLength& o) const
     {
diff --git a/Source/core/rendering/style/GridTrackSize.h b/Source/core/rendering/style/GridTrackSize.h
index 584b47a..b64e5e3 100644
--- a/Source/core/rendering/style/GridTrackSize.h
+++ b/Source/core/rendering/style/GridTrackSize.h
@@ -42,30 +42,27 @@
 
 class GridTrackSize {
 public:
-    GridTrackSize()
+    GridTrackSize(const GridLength& length)
         : m_type(LengthTrackSizing)
-        , m_minTrackBreadth(Undefined)
-        , m_maxTrackBreadth(Undefined)
+        , m_minTrackBreadth(length)
+        , m_maxTrackBreadth(length)
         , m_minTrackBreadthIsMinOrMaxContent(false)
         , m_minTrackBreadthIsMaxContent(false)
         , m_maxTrackBreadthIsMinOrMaxContent(false)
         , m_maxTrackBreadthIsMaxContent(false)
     {
-        // Someone has to set a valid lenght type through setLength or
-        // setMinMax before using the object.
+        cacheMinMaxTrackBreadthTypes();
     }
 
-    GridTrackSize(LengthType type)
-        : m_type(LengthTrackSizing)
-        , m_minTrackBreadth(type)
-        , m_maxTrackBreadth(type)
+    GridTrackSize(const GridLength& minTrackBreadth, const GridLength& maxTrackBreadth)
+        : m_type(MinMaxTrackSizing)
+        , m_minTrackBreadth(minTrackBreadth)
+        , m_maxTrackBreadth(maxTrackBreadth)
         , m_minTrackBreadthIsMinOrMaxContent(false)
         , m_minTrackBreadthIsMaxContent(false)
         , m_maxTrackBreadthIsMinOrMaxContent(false)
         , m_maxTrackBreadthIsMaxContent(false)
     {
-        ASSERT(type != Undefined);
-
         cacheMinMaxTrackBreadthTypes();
     }
 
@@ -74,24 +71,13 @@
         ASSERT(m_type == LengthTrackSizing);
         ASSERT(m_minTrackBreadth == m_maxTrackBreadth);
         const GridLength& minTrackBreadth = m_minTrackBreadth;
-        ASSERT(!minTrackBreadth.isLength() || !minTrackBreadth.length().isUndefined());
         return minTrackBreadth;
     }
 
-    void setLength(const GridLength& length)
-    {
-        m_type = LengthTrackSizing;
-        m_minTrackBreadth = length;
-        m_maxTrackBreadth = length;
-
-        cacheMinMaxTrackBreadthTypes();
-    }
-
     const GridLength& minTrackBreadth() const
     {
-        ASSERT(!m_minTrackBreadth.isLength() || !m_minTrackBreadth.length().isUndefined());
         if (m_minTrackBreadth.isLength() && m_minTrackBreadth.length().isAuto()) {
-            DEFINE_STATIC_LOCAL(GridLength, minContent, (MinContent));
+            DEFINE_STATIC_LOCAL(GridLength, minContent, (Length(MinContent)));
             return minContent;
         }
         return m_minTrackBreadth;
@@ -99,27 +85,19 @@
 
     const GridLength& maxTrackBreadth() const
     {
-        ASSERT(!m_maxTrackBreadth.isLength() || !m_maxTrackBreadth.length().isUndefined());
         if (m_maxTrackBreadth.isLength() && m_maxTrackBreadth.length().isAuto()) {
-            DEFINE_STATIC_LOCAL(GridLength, maxContent, (MaxContent));
+            DEFINE_STATIC_LOCAL(GridLength, maxContent, (Length(MaxContent)));
             return maxContent;
         }
         return m_maxTrackBreadth;
     }
 
-    void setMinMax(const GridLength& minTrackBreadth, const GridLength& maxTrackBreadth)
-    {
-        m_type = MinMaxTrackSizing;
-        m_minTrackBreadth = minTrackBreadth;
-        m_maxTrackBreadth = maxTrackBreadth;
-
-        cacheMinMaxTrackBreadthTypes();
-    }
-
     GridTrackSizeType type() const { return m_type; }
 
     bool isContentSized() const { return m_minTrackBreadth.isContentSized() || m_maxTrackBreadth.isContentSized(); }
 
+    bool isPercentage() const { return m_type == LengthTrackSizing && length().isLength() && length().length().isPercent(); }
+
     bool operator==(const GridTrackSize& other) const
     {
         return m_type == other.m_type && m_minTrackBreadth == other.m_minTrackBreadth && m_maxTrackBreadth == other.m_maxTrackBreadth;
diff --git a/Source/core/rendering/style/OutlineValue.h b/Source/core/rendering/style/OutlineValue.h
index ccf3c27..e70b232 100644
--- a/Source/core/rendering/style/OutlineValue.h
+++ b/Source/core/rendering/style/OutlineValue.h
@@ -39,7 +39,7 @@
 
     bool operator==(const OutlineValue& o) const
     {
-        return m_width == o.m_width && m_style == o.m_style && m_color == o.m_color && m_colorIsValid == o.m_colorIsValid && m_offset == o.m_offset && m_isAuto == o.m_isAuto;
+        return BorderValue::operator==(o) && m_offset == o.m_offset && m_isAuto == o.m_isAuto;
     }
 
     bool operator!=(const OutlineValue& o) const
diff --git a/Source/core/rendering/style/RenderStyle.cpp b/Source/core/rendering/style/RenderStyle.cpp
index 84dea11..3744a0c 100644
--- a/Source/core/rendering/style/RenderStyle.cpp
+++ b/Source/core/rendering/style/RenderStyle.cpp
@@ -34,6 +34,7 @@
 #include "core/rendering/style/ShadowList.h"
 #include "core/rendering/style/StyleImage.h"
 #include "core/rendering/style/StyleInheritedData.h"
+#include "platform/LengthFunctions.h"
 #include "platform/fonts/Font.h"
 #include "platform/fonts/FontSelector.h"
 #include "wtf/MathExtras.h"
@@ -179,9 +180,7 @@
         || oldStyle->columnSpan() != newStyle->columnSpan()
         || oldStyle->specifiesAutoColumns() != newStyle->specifiesAutoColumns()
         || !oldStyle->contentDataEquivalent(newStyle)
-        || oldStyle->hasTextCombine() != newStyle->hasTextCombine()
-        || oldStyle->flowThread() != newStyle->flowThread()
-        || oldStyle->regionThread() != newStyle->regionThread())
+        || oldStyle->hasTextCombine() != newStyle->hasTextCombine())
         return Reattach;
 
     if (*oldStyle == *newStyle)
@@ -233,6 +232,7 @@
     noninherited_flags._page_break_inside = other->noninherited_flags._page_break_inside;
     noninherited_flags.explicitInheritance = other->noninherited_flags.explicitInheritance;
     noninherited_flags.currentColor = other->noninherited_flags.currentColor;
+    noninherited_flags.hasViewportUnits = other->noninherited_flags.hasViewportUnits;
     if (m_svgStyle != other->m_svgStyle)
         m_svgStyle.access()->copyNonInheritedFrom(other->m_svgStyle.get());
     ASSERT(zoom() == initialZoom());
@@ -336,7 +336,7 @@
         && rareInheritedData.get() == other->rareInheritedData.get();
 }
 
-static bool positionedObjectMoved(const LengthBox& a, const LengthBox& b, const Length& width)
+static bool positionedObjectMovedOnly(const LengthBox& a, const LengthBox& b, const Length& width)
 {
     // If any unit types are different, then we can't guarantee
     // that this was just a movement.
@@ -353,9 +353,11 @@
         return false;
     if (!a.top().isIntrinsicOrAuto() && !a.bottom().isIntrinsicOrAuto())
         return false;
-    // If our width is auto and left or right is specified then this
+    // If our width is auto and left or right is specified and changed then this
     // is not just a movement - we need to resize to our container.
-    if ((!a.left().isIntrinsicOrAuto() || !a.right().isIntrinsicOrAuto()) && width.isIntrinsicOrAuto())
+    if (width.isIntrinsicOrAuto()
+        && ((!a.left().isIntrinsicOrAuto() && a.left() != b.left())
+            || (!a.right().isIntrinsicOrAuto() && a.right() != b.right())))
         return false;
 
     // One of the units is fixed or percent in both directions and stayed
@@ -367,48 +369,68 @@
 {
     changedContextSensitiveProperties = ContextSensitivePropertyNone;
 
+    // Note, we use .get() on each DataRef below because DataRef::operator== will do a deep
+    // compare, which is duplicate work when we're going to compare each property inside
+    // this function anyway.
+
     StyleDifference svgChange = StyleDifferenceEqual;
-    if (m_svgStyle != other->m_svgStyle) {
+    if (m_svgStyle.get() != other->m_svgStyle.get()) {
         svgChange = m_svgStyle->diff(other->m_svgStyle.get());
         if (svgChange == StyleDifferenceLayout)
             return svgChange;
     }
 
-    if (m_box->width() != other->m_box->width()
-        || m_box->minWidth() != other->m_box->minWidth()
-        || m_box->maxWidth() != other->m_box->maxWidth()
-        || m_box->height() != other->m_box->height()
-        || m_box->minHeight() != other->m_box->minHeight()
-        || m_box->maxHeight() != other->m_box->maxHeight())
-        return StyleDifferenceLayout;
+    if (m_box.get() != other->m_box.get()) {
+        if (m_box->width() != other->m_box->width()
+            || m_box->minWidth() != other->m_box->minWidth()
+            || m_box->maxWidth() != other->m_box->maxWidth()
+            || m_box->height() != other->m_box->height()
+            || m_box->minHeight() != other->m_box->minHeight()
+            || m_box->maxHeight() != other->m_box->maxHeight())
+            return StyleDifferenceLayout;
 
-    if (m_box->verticalAlign() != other->m_box->verticalAlign() || noninherited_flags._vertical_align != other->noninherited_flags._vertical_align)
-        return StyleDifferenceLayout;
+        if (m_box->verticalAlign() != other->m_box->verticalAlign())
+            return StyleDifferenceLayout;
 
-    if (m_box->boxSizing() != other->m_box->boxSizing())
-        return StyleDifferenceLayout;
+        if (m_box->boxSizing() != other->m_box->boxSizing())
+            return StyleDifferenceLayout;
+    }
 
-    if (surround->margin != other->surround->margin)
-        return StyleDifferenceLayout;
+    if (surround.get() != other->surround.get()) {
+        if (surround->margin != other->surround->margin)
+            return StyleDifferenceLayout;
 
-    if (surround->padding != other->surround->padding)
-        return StyleDifferenceLayout;
+        if (surround->padding != other->surround->padding)
+            return StyleDifferenceLayout;
+
+        // If our border widths change, then we need to layout. Other changes to borders only necessitate a repaint.
+        if (borderLeftWidth() != other->borderLeftWidth()
+            || borderTopWidth() != other->borderTopWidth()
+            || borderBottomWidth() != other->borderBottomWidth()
+            || borderRightWidth() != other->borderRightWidth())
+            return StyleDifferenceLayout;
+    }
 
     if (rareNonInheritedData.get() != other->rareNonInheritedData.get()) {
         if (rareNonInheritedData->m_appearance != other->rareNonInheritedData->m_appearance
             || rareNonInheritedData->marginBeforeCollapse != other->rareNonInheritedData->marginBeforeCollapse
             || rareNonInheritedData->marginAfterCollapse != other->rareNonInheritedData->marginAfterCollapse
             || rareNonInheritedData->lineClamp != other->rareNonInheritedData->lineClamp
-            || rareNonInheritedData->textOverflow != other->rareNonInheritedData->textOverflow)
-            return StyleDifferenceLayout;
-
-        if (rareNonInheritedData->m_regionFragment != other->rareNonInheritedData->m_regionFragment)
-            return StyleDifferenceLayout;
-
-        if (rareNonInheritedData->m_wrapFlow != other->rareNonInheritedData->m_wrapFlow
+            || rareNonInheritedData->textOverflow != other->rareNonInheritedData->textOverflow
+            || rareNonInheritedData->m_wrapFlow != other->rareNonInheritedData->m_wrapFlow
             || rareNonInheritedData->m_wrapThrough != other->rareNonInheritedData->m_wrapThrough
             || rareNonInheritedData->m_shapeMargin != other->rareNonInheritedData->m_shapeMargin
-            || rareNonInheritedData->m_shapePadding != other->rareNonInheritedData->m_shapePadding)
+            || rareNonInheritedData->m_shapePadding != other->rareNonInheritedData->m_shapePadding
+            || rareNonInheritedData->m_order != other->rareNonInheritedData->m_order
+            || rareNonInheritedData->m_alignContent != other->rareNonInheritedData->m_alignContent
+            || rareNonInheritedData->m_alignItems != other->rareNonInheritedData->m_alignItems
+            || rareNonInheritedData->m_alignSelf != other->rareNonInheritedData->m_alignSelf
+            || rareNonInheritedData->m_justifyContent != other->rareNonInheritedData->m_justifyContent
+            || rareNonInheritedData->m_grid.get() != other->rareNonInheritedData->m_grid.get()
+            || rareNonInheritedData->m_gridItem.get() != other->rareNonInheritedData->m_gridItem.get()
+            || rareNonInheritedData->m_shapeInside != other->rareNonInheritedData->m_shapeInside
+            || rareNonInheritedData->m_textCombine != other->rareNonInheritedData->m_textCombine
+            || rareNonInheritedData->hasFilters() != other->rareNonInheritedData->hasFilters())
             return StyleDifferenceLayout;
 
         if (rareNonInheritedData->m_deprecatedFlexibleBox.get() != other->rareNonInheritedData->m_deprecatedFlexibleBox.get()
@@ -418,12 +440,6 @@
         if (rareNonInheritedData->m_flexibleBox.get() != other->rareNonInheritedData->m_flexibleBox.get()
             && *rareNonInheritedData->m_flexibleBox.get() != *other->rareNonInheritedData->m_flexibleBox.get())
             return StyleDifferenceLayout;
-        if (rareNonInheritedData->m_order != other->rareNonInheritedData->m_order
-            || rareNonInheritedData->m_alignContent != other->rareNonInheritedData->m_alignContent
-            || rareNonInheritedData->m_alignItems != other->rareNonInheritedData->m_alignItems
-            || rareNonInheritedData->m_alignSelf != other->rareNonInheritedData->m_alignSelf
-            || rareNonInheritedData->m_justifyContent != other->rareNonInheritedData->m_justifyContent)
-            return StyleDifferenceLayout;
 
         // FIXME: We should add an optimized form of layout that just recomputes visual overflow.
         if (!rareNonInheritedData->shadowDataEquivalent(*other->rareNonInheritedData.get()))
@@ -436,19 +452,28 @@
             && *rareNonInheritedData->m_multiCol.get() != *other->rareNonInheritedData->m_multiCol.get())
             return StyleDifferenceLayout;
 
-        if (rareNonInheritedData->m_transform.get() != other->rareNonInheritedData->m_transform.get()
-            && *rareNonInheritedData->m_transform.get() != *other->rareNonInheritedData->m_transform.get()) {
+        if (!transformDataEquivalent(other)) {
             // Don't return early here; instead take note of the type of
             // change, and deal with it when looking at compositing.
             changedContextSensitiveProperties |= ContextSensitivePropertyTransform;
         }
 
-        if (rareNonInheritedData->m_grid.get() != other->rareNonInheritedData->m_grid.get()
-            || rareNonInheritedData->m_gridItem.get() != other->rareNonInheritedData->m_gridItem.get())
+        // If the counter directives change, trigger a relayout to re-calculate counter values and rebuild the counter node tree.
+        const CounterDirectiveMap* mapA = rareNonInheritedData->m_counterDirectives.get();
+        const CounterDirectiveMap* mapB = other->rareNonInheritedData->m_counterDirectives.get();
+        if (!(mapA == mapB || (mapA && mapB && *mapA == *mapB)))
             return StyleDifferenceLayout;
 
-        if (rareNonInheritedData->m_shapeInside != other->rareNonInheritedData->m_shapeInside)
+        // We only need do layout for opacity changes if adding or losing opacity could trigger a change
+        // in us being a stacking context.
+        if (hasAutoZIndex() != other->hasAutoZIndex() && rareNonInheritedData->hasOpacity() != other->rareNonInheritedData->hasOpacity()) {
+            // FIXME: We would like to use SimplifiedLayout here, but we can't quite do that yet.
+            // We need to make sure SimplifiedLayout can operate correctly on RenderInlines (we will need
+            // to add a selfNeedsSimplifiedLayout bit in order to not get confused and taint every line).
+            // In addition we need to solve the floating object issue when layers come and go. Right now
+            // a full layout is necessary to keep floating object lists sane.
             return StyleDifferenceLayout;
+        }
     }
 
     if (rareInheritedData.get() != other->rareInheritedData.get()) {
@@ -470,40 +495,52 @@
             || rareInheritedData->textEmphasisMark != other->rareInheritedData->textEmphasisMark
             || rareInheritedData->textEmphasisPosition != other->rareInheritedData->textEmphasisPosition
             || rareInheritedData->textEmphasisCustomMark != other->rareInheritedData->textEmphasisCustomMark
-            || rareInheritedData->m_textAlignLast != other->rareInheritedData->m_textAlignLast
             || rareInheritedData->m_textJustify != other->rareInheritedData->m_textJustify
             || rareInheritedData->m_textOrientation != other->rareInheritedData->m_textOrientation
             || rareInheritedData->m_tabSize != other->rareInheritedData->m_tabSize
             || rareInheritedData->m_lineBoxContain != other->rareInheritedData->m_lineBoxContain
-            || rareInheritedData->m_lineGrid != other->rareInheritedData->m_lineGrid
-            || rareInheritedData->m_lineSnap != other->rareInheritedData->m_lineSnap
-            || rareInheritedData->m_lineAlign != other->rareInheritedData->m_lineAlign
-            || rareInheritedData->listStyleImage != other->rareInheritedData->listStyleImage)
+            || rareInheritedData->listStyleImage != other->rareInheritedData->listStyleImage
+            || rareInheritedData->textStrokeWidth != other->rareInheritedData->textStrokeWidth)
             return StyleDifferenceLayout;
 
         if (!rareInheritedData->shadowDataEquivalent(*other->rareInheritedData.get()))
             return StyleDifferenceLayout;
 
-        if (textStrokeWidth() != other->textStrokeWidth())
+        if (!QuotesData::equals(rareInheritedData->quotes.get(), other->rareInheritedData->quotes.get()))
             return StyleDifferenceLayout;
     }
 
     if (visual->m_textAutosizingMultiplier != other->visual->m_textAutosizingMultiplier)
         return StyleDifferenceLayout;
 
-    if (inherited->line_height != other->inherited->line_height
+    if (inherited.get() != other->inherited.get()) {
+        if (inherited->line_height != other->inherited->line_height
         || inherited->font != other->inherited->font
         || inherited->horizontal_border_spacing != other->inherited->horizontal_border_spacing
-        || inherited->vertical_border_spacing != other->inherited->vertical_border_spacing
-        || inherited_flags._box_direction != other->inherited_flags._box_direction
+        || inherited->vertical_border_spacing != other->inherited->vertical_border_spacing)
+        return StyleDifferenceLayout;
+    }
+
+    if (inherited_flags._box_direction != other->inherited_flags._box_direction
         || inherited_flags.m_rtlOrdering != other->inherited_flags.m_rtlOrdering
-        || noninherited_flags._position != other->noninherited_flags._position
-        || noninherited_flags._floating != other->noninherited_flags._floating
-        || noninherited_flags._originalDisplay != other->noninherited_flags._originalDisplay)
+        || inherited_flags._text_align != other->inherited_flags._text_align
+        || inherited_flags._text_transform != other->inherited_flags._text_transform
+        || inherited_flags._direction != other->inherited_flags._direction
+        || inherited_flags._white_space != other->inherited_flags._white_space
+        || inherited_flags.m_writingMode != other->inherited_flags.m_writingMode)
         return StyleDifferenceLayout;
 
+    if (noninherited_flags._overflowX != other->noninherited_flags._overflowX
+        || noninherited_flags._overflowY != other->noninherited_flags._overflowY
+        || noninherited_flags._clear != other->noninherited_flags._clear
+        || noninherited_flags._unicodeBidi != other->noninherited_flags._unicodeBidi
+        || noninherited_flags._position != other->noninherited_flags._position
+        || noninherited_flags._floating != other->noninherited_flags._floating
+        || noninherited_flags._originalDisplay != other->noninherited_flags._originalDisplay
+        || noninherited_flags._vertical_align != other->noninherited_flags._vertical_align)
+        return StyleDifferenceLayout;
 
-    if (((int)noninherited_flags._effectiveDisplay) >= TABLE) {
+    if (noninherited_flags._effectiveDisplay >= FIRST_TABLE_DISPLAY && noninherited_flags._effectiveDisplay <= LAST_TABLE_DISPLAY) {
         if (inherited_flags._border_collapse != other->inherited_flags._border_collapse
             || inherited_flags._empty_cells != other->inherited_flags._empty_cells
             || inherited_flags._caption_side != other->inherited_flags._caption_side
@@ -522,67 +559,15 @@
                 || (borderRightStyle() == BHIDDEN && other->borderRightStyle() == BNONE)
                 || (borderRightStyle() == BNONE && other->borderRightStyle() == BHIDDEN)))
             return StyleDifferenceLayout;
-    }
-
-    if (noninherited_flags._effectiveDisplay == LIST_ITEM) {
+    } else if (noninherited_flags._effectiveDisplay == LIST_ITEM) {
         if (inherited_flags._list_style_type != other->inherited_flags._list_style_type
             || inherited_flags._list_style_position != other->inherited_flags._list_style_position)
             return StyleDifferenceLayout;
     }
 
-    if (inherited_flags._text_align != other->inherited_flags._text_align
-        || inherited_flags._text_transform != other->inherited_flags._text_transform
-        || inherited_flags._direction != other->inherited_flags._direction
-        || inherited_flags._white_space != other->inherited_flags._white_space
-        || noninherited_flags._clear != other->noninherited_flags._clear
-        || noninherited_flags._unicodeBidi != other->noninherited_flags._unicodeBidi)
-        return StyleDifferenceLayout;
-
-    // Check block flow direction.
-    if (inherited_flags.m_writingMode != other->inherited_flags.m_writingMode)
-        return StyleDifferenceLayout;
-
-    // Check text combine mode.
-    if (rareNonInheritedData->m_textCombine != other->rareNonInheritedData->m_textCombine)
-        return StyleDifferenceLayout;
-
-    // Overflow returns a layout hint.
-    if (noninherited_flags._overflowX != other->noninherited_flags._overflowX
-        || noninherited_flags._overflowY != other->noninherited_flags._overflowY)
-        return StyleDifferenceLayout;
-
-    // If our border widths change, then we need to layout.  Other changes to borders
-    // only necessitate a repaint.
-    if (borderLeftWidth() != other->borderLeftWidth()
-        || borderTopWidth() != other->borderTopWidth()
-        || borderBottomWidth() != other->borderBottomWidth()
-        || borderRightWidth() != other->borderRightWidth())
-        return StyleDifferenceLayout;
-
-    // If the counter directives change, trigger a relayout to re-calculate counter values and rebuild the counter node tree.
-    const CounterDirectiveMap* mapA = rareNonInheritedData->m_counterDirectives.get();
-    const CounterDirectiveMap* mapB = other->rareNonInheritedData->m_counterDirectives.get();
-    if (!(mapA == mapB || (mapA && mapB && *mapA == *mapB)))
-        return StyleDifferenceLayout;
-
     if ((visibility() == COLLAPSE) != (other->visibility() == COLLAPSE))
         return StyleDifferenceLayout;
 
-    if (rareNonInheritedData->hasOpacity() != other->rareNonInheritedData->hasOpacity()) {
-        // FIXME: We would like to use SimplifiedLayout here, but we can't quite do that yet.
-        // We need to make sure SimplifiedLayout can operate correctly on RenderInlines (we will need
-        // to add a selfNeedsSimplifiedLayout bit in order to not get confused and taint every line).
-        // In addition we need to solve the floating object issue when layers come and go. Right now
-        // a full layout is necessary to keep floating object lists sane.
-        return StyleDifferenceLayout;
-    }
-
-    if (rareNonInheritedData->hasFilters() != other->rareNonInheritedData->hasFilters())
-        return StyleDifferenceLayout;
-
-    if (!QuotesData::equals(rareInheritedData->quotes.get(), other->rareInheritedData->quotes.get()))
-        return StyleDifferenceLayout;
-
     // SVGRenderStyle::diff() might have returned StyleDifferenceRepaint, eg. if fill changes.
     // If eg. the font-size changed at the same time, we're not allowed to return StyleDifferenceRepaint,
     // but have to return StyleDifferenceLayout, that's why  this if branch comes after all branches
@@ -590,27 +575,32 @@
     if (svgChange != StyleDifferenceEqual)
         return svgChange;
 
-    // Make sure these left/top/right/bottom checks stay below all layout checks and above
-    // all visible checks.
-    if (position() != StaticPosition) {
-        if (surround->offset != other->surround->offset) {
-             // Optimize for the case where a positioned layer is moving but not changing size.
-            if (position() == AbsolutePosition && positionedObjectMoved(surround->offset, other->surround->offset, m_box->width()))
-
-                return StyleDifferenceLayoutPositionedMovementOnly;
-
-            // FIXME: We would like to use SimplifiedLayout for relative positioning, but we can't quite do that yet.
-            // We need to make sure SimplifiedLayout can operate correctly on RenderInlines (we will need
-            // to add a selfNeedsSimplifiedLayout bit in order to not get confused and taint every line).
-            return StyleDifferenceLayout;
-        } else if (m_box->zIndex() != other->m_box->zIndex() || m_box->hasAutoZIndex() != other->m_box->hasAutoZIndex()
-                 || visual->clip != other->visual->clip || visual->hasClip != other->visual->hasClip)
-            return StyleDifferenceRepaintLayer;
+    // NOTE: This block must be last in this function for the StyleDifferenceLayoutPositionedMovementOnly
+    // optimization to work properly.
+    if (position() != StaticPosition && surround->offset != other->surround->offset) {
+        // Optimize for the case where a positioned layer is moving but not changing size.
+        if ((position() == AbsolutePosition || position() == FixedPosition)
+            && positionedObjectMovedOnly(surround->offset, other->surround->offset, m_box->width())
+            && repaintOnlyDiff(other, changedContextSensitiveProperties) == StyleDifferenceEqual)
+            return StyleDifferenceLayoutPositionedMovementOnly;
+        // FIXME: We would like to use SimplifiedLayout for relative positioning, but we can't quite do that yet.
+        // We need to make sure SimplifiedLayout can operate correctly on RenderInlines (we will need
+        // to add a selfNeedsSimplifiedLayout bit in order to not get confused and taint every line).
+        return StyleDifferenceLayout;
     }
 
-    if (RuntimeEnabledFeatures::cssCompositingEnabled())
-        if (rareNonInheritedData->m_effectiveBlendMode != other->rareNonInheritedData->m_effectiveBlendMode)
-            return StyleDifferenceRepaintLayer;
+    return repaintOnlyDiff(other, changedContextSensitiveProperties);
+}
+
+StyleDifference RenderStyle::repaintOnlyDiff(const RenderStyle* other, unsigned& changedContextSensitiveProperties) const
+{
+    if (position() != StaticPosition && (m_box->zIndex() != other->m_box->zIndex() || m_box->hasAutoZIndex() != other->m_box->hasAutoZIndex()
+        || visual->clip != other->visual->clip || visual->hasClip != other->visual->hasClip))
+        return StyleDifferenceRepaintLayer;
+
+    if (RuntimeEnabledFeatures::cssCompositingEnabled() && (rareNonInheritedData->m_effectiveBlendMode != other->rareNonInheritedData->m_effectiveBlendMode
+        || rareNonInheritedData->m_isolation != other->rareNonInheritedData->m_isolation))
+        return StyleDifferenceRepaintLayer;
 
     if (rareNonInheritedData->opacity != other->rareNonInheritedData->opacity) {
         // Don't return early here; instead take note of the type of change,
@@ -876,8 +866,8 @@
     float offsetY = transformOriginY().type() == Percent ? boundingBox.y() : 0;
 
     if (applyTransformOrigin) {
-        transform.translate3d(floatValueForLength(transformOriginX(), boundingBox.width(), 0) + offsetX,
-            floatValueForLength(transformOriginY(), boundingBox.height(), 0) + offsetY,
+        transform.translate3d(floatValueForLength(transformOriginX(), boundingBox.width()) + offsetX,
+            floatValueForLength(transformOriginY(), boundingBox.height()) + offsetY,
             transformOriginZ());
     }
 
@@ -886,8 +876,8 @@
         transformOperations[i]->apply(transform, boundingBox.size());
 
     if (applyTransformOrigin) {
-        transform.translate3d(-floatValueForLength(transformOriginX(), boundingBox.width(), 0) - offsetX,
-            -floatValueForLength(transformOriginY(), boundingBox.height(), 0) - offsetY,
+        transform.translate3d(-floatValueForLength(transformOriginX(), boundingBox.width()) - offsetX,
+            -floatValueForLength(transformOriginY(), boundingBox.height()) - offsetY,
             -transformOriginZ());
     }
 }
@@ -902,17 +892,17 @@
     rareNonInheritedData.access()->m_boxShadow = s;
 }
 
-static RoundedRect::Radii calcRadiiFor(const BorderData& border, IntSize size, RenderView* renderView)
+static RoundedRect::Radii calcRadiiFor(const BorderData& border, IntSize size)
 {
     return RoundedRect::Radii(
-        IntSize(valueForLength(border.topLeft().width(), size.width(), renderView),
-                valueForLength(border.topLeft().height(), size.height(), renderView)),
-        IntSize(valueForLength(border.topRight().width(), size.width(), renderView),
-                valueForLength(border.topRight().height(), size.height(), renderView)),
-        IntSize(valueForLength(border.bottomLeft().width(), size.width(), renderView),
-                valueForLength(border.bottomLeft().height(), size.height(), renderView)),
-        IntSize(valueForLength(border.bottomRight().width(), size.width(), renderView),
-                valueForLength(border.bottomRight().height(), size.height(), renderView)));
+        IntSize(valueForLength(border.topLeft().width(), size.width()),
+            valueForLength(border.topLeft().height(), size.height())),
+        IntSize(valueForLength(border.topRight().width(), size.width()),
+            valueForLength(border.topRight().height(), size.height())),
+        IntSize(valueForLength(border.bottomLeft().width(), size.width()),
+            valueForLength(border.bottomLeft().height(), size.height())),
+        IntSize(valueForLength(border.bottomRight().width(), size.width()),
+            valueForLength(border.bottomRight().height(), size.height())));
 }
 
 static float calcConstraintScaleFor(const IntRect& rect, const RoundedRect::Radii& radii)
@@ -964,12 +954,12 @@
 void RenderStyle::setHorizontalBorderSpacing(short v) { SET_VAR(inherited, horizontal_border_spacing, v); }
 void RenderStyle::setVerticalBorderSpacing(short v) { SET_VAR(inherited, vertical_border_spacing, v); }
 
-RoundedRect RenderStyle::getRoundedBorderFor(const LayoutRect& borderRect, RenderView* renderView, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
+RoundedRect RenderStyle::getRoundedBorderFor(const LayoutRect& borderRect, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
 {
     IntRect snappedBorderRect(pixelSnappedIntRect(borderRect));
     RoundedRect roundedRect(snappedBorderRect);
     if (hasBorderRadius()) {
-        RoundedRect::Radii radii = calcRadiiFor(surround->border, snappedBorderRect.size(), renderView);
+        RoundedRect::Radii radii = calcRadiiFor(surround->border, snappedBorderRect.size());
         radii.scale(calcConstraintScaleFor(snappedBorderRect, radii));
         roundedRect.includeLogicalEdges(radii, isHorizontalWritingMode(), includeLogicalLeftEdge, includeLogicalRightEdge);
     }
@@ -1184,15 +1174,15 @@
 const FontDescription& RenderStyle::fontDescription() const { return inherited->font.fontDescription(); }
 float RenderStyle::specifiedFontSize() const { return fontDescription().specifiedSize(); }
 float RenderStyle::computedFontSize() const { return fontDescription().computedSize(); }
-int RenderStyle::fontSize() const { return inherited->font.pixelSize(); }
+int RenderStyle::fontSize() const { return fontDescription().computedPixelSize(); }
 
-float RenderStyle::wordSpacing() const { return inherited->font.wordSpacing(); }
-float RenderStyle::letterSpacing() const { return inherited->font.letterSpacing(); }
+float RenderStyle::wordSpacing() const { return fontDescription().wordSpacing(); }
+float RenderStyle::letterSpacing() const { return fontDescription().letterSpacing(); }
 
 bool RenderStyle::setFontDescription(const FontDescription& v)
 {
     if (inherited->font.fontDescription() != v) {
-        inherited.access()->font = Font(v, inherited->font.letterSpacing(), inherited->font.wordSpacing());
+        inherited.access()->font = Font(v);
         return true;
     }
     return false;
@@ -1214,7 +1204,7 @@
 }
 void RenderStyle::setLineHeight(Length specifiedLineHeight) { SET_VAR(inherited, line_height, specifiedLineHeight); }
 
-int RenderStyle::computedLineHeight(RenderView* renderView) const
+int RenderStyle::computedLineHeight() const
 {
     const Length& lh = lineHeight();
 
@@ -1225,14 +1215,11 @@
     if (lh.isPercent())
         return minimumValueForLength(lh, fontSize());
 
-    if (lh.isViewportPercentage())
-        return valueForLength(lh, 0, renderView);
-
     return lh.value();
 }
 
-void RenderStyle::setWordSpacing(float v) { inherited.access()->font.setWordSpacing(v); }
-void RenderStyle::setLetterSpacing(float v) { inherited.access()->font.setLetterSpacing(v); }
+void RenderStyle::setWordSpacing(float v) { inherited.access()->font.mutableFontDescription().setWordSpacing(v); }
+void RenderStyle::setLetterSpacing(float v) { inherited.access()->font.mutableFontDescription().setLetterSpacing(v); }
 
 void RenderStyle::setFontSize(float size)
 {
@@ -1272,7 +1259,7 @@
         const ShadowData& shadow = shadowList->shadows()[i];
         if (shadow.style() == Inset)
             continue;
-        int blurAndSpread = shadow.blur() + shadow.spread();
+        float blurAndSpread = shadow.blur() + shadow.spread();
 
         top = min<LayoutUnit>(top, shadow.y() - blurAndSpread);
         right = max<LayoutUnit>(right, shadow.x() + blurAndSpread);
@@ -1293,7 +1280,7 @@
         const ShadowData& shadow = shadowList->shadows()[i];
         if (shadow.style() == Normal)
             continue;
-        int blurAndSpread = shadow.blur() + shadow.spread();
+        float blurAndSpread = shadow.blur() + shadow.spread();
         top = max<LayoutUnit>(top, shadow.y() + blurAndSpread);
         right = min<LayoutUnit>(right, shadow.x() - blurAndSpread);
         bottom = min<LayoutUnit>(bottom, shadow.y() - blurAndSpread);
@@ -1313,7 +1300,7 @@
         const ShadowData& shadow = shadowList->shadows()[i];
         if (shadow.style() == Inset)
             continue;
-        int blurAndSpread = shadow.blur() + shadow.spread();
+        float blurAndSpread = shadow.blur() + shadow.spread();
 
         left = min<LayoutUnit>(left, shadow.x() - blurAndSpread);
         right = max<LayoutUnit>(right, shadow.x() + blurAndSpread);
@@ -1330,20 +1317,27 @@
         const ShadowData& shadow = shadowList->shadows()[i];
         if (shadow.style() == Inset)
             continue;
-        int blurAndSpread = shadow.blur() + shadow.spread();
+        float blurAndSpread = shadow.blur() + shadow.spread();
 
         top = min<LayoutUnit>(top, shadow.y() - blurAndSpread);
         bottom = max<LayoutUnit>(bottom, shadow.y() + blurAndSpread);
     }
 }
 
+StyleColor RenderStyle::visitedDependentDecorationColor() const
+{
+    // Text decoration color fallback is handled in RenderObject::decorationColor.
+    return insideLink() == InsideVisitedLink ? visitedLinkTextDecorationColor() : textDecorationColor();
+}
+
 Color RenderStyle::colorIncludingFallback(int colorProperty, bool visitedLink) const
 {
-    Color result;
+    StyleColor result(StyleColor::currentColor());
     EBorderStyle borderStyle = BNONE;
     switch (colorProperty) {
     case CSSPropertyBackgroundColor:
-        return visitedLink ? visitedLinkBackgroundColor() : backgroundColor(); // Background color doesn't fall back.
+        result = visitedLink ? visitedLinkBackgroundColor() : backgroundColor();
+        break;
     case CSSPropertyBorderLeftColor:
         result = visitedLink ? visitedLinkBorderLeftColor() : borderLeftColor();
         borderStyle = borderLeftStyle();
@@ -1369,9 +1363,6 @@
     case CSSPropertyWebkitColumnRuleColor:
         result = visitedLink ? visitedLinkColumnRuleColor() : columnRuleColor();
         break;
-    case CSSPropertyTextDecorationColor:
-        // Text decoration color fallback is handled in RenderObject::decorationColor.
-        return visitedLink ? visitedLinkTextDecorationColor() : textDecorationColor();
     case CSSPropertyWebkitTextEmphasisColor:
         result = visitedLink ? visitedLinkTextEmphasisColor() : textEmphasisColor();
         break;
@@ -1398,13 +1389,14 @@
         break;
     }
 
-    if (!result.isValid()) {
-        if (!visitedLink && (borderStyle == INSET || borderStyle == OUTSET || borderStyle == RIDGE || borderStyle == GROOVE))
-            result.setRGB(238, 238, 238);
-        else
-            result = visitedLink ? visitedLinkColor() : color();
-    }
-    return result;
+    if (!result.isCurrentColor())
+        return result.color();
+
+    // FIXME: Treating styled borders with initial color differently causes problems
+    // See crbug.com/316559, crbug.com/276231
+    if (!visitedLink && (borderStyle == INSET || borderStyle == OUTSET || borderStyle == RIDGE || borderStyle == GROOVE))
+        return Color(238, 238, 238);
+    return visitedLink ? visitedLinkColor() : color();
 }
 
 Color RenderStyle::visitedDependentColor(int colorProperty) const
@@ -1415,10 +1407,6 @@
 
     Color visitedColor = colorIncludingFallback(colorProperty, true);
 
-    // Text decoration color validity is preserved (checked in RenderObject::decorationColor).
-    if (colorProperty == CSSPropertyTextDecorationColor)
-        return visitedColor;
-
     // FIXME: Technically someone could explicitly specify the color transparent, but for now we'll just
     // assume that if the background color is transparent that it wasn't set. Note that it's weird that
     // we're returning unvisited info for a visited link, but given our restriction that the alpha values
diff --git a/Source/core/rendering/style/RenderStyle.h b/Source/core/rendering/style/RenderStyle.h
index 72362f7..147734e 100644
--- a/Source/core/rendering/style/RenderStyle.h
+++ b/Source/core/rendering/style/RenderStyle.h
@@ -26,10 +26,9 @@
 #define RenderStyle_h
 
 #include "CSSPropertyNames.h"
-#include "core/css/CSSLengthFunctions.h"
+#include "core/animation/css/CSSAnimationDataList.h"
 #include "core/css/CSSLineBoxContainValue.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/platform/animation/CSSAnimationDataList.h"
 #include "core/rendering/style/BorderValue.h"
 #include "core/rendering/style/CounterDirectives.h"
 #include "core/rendering/style/DataRef.h"
@@ -65,6 +64,7 @@
 #include "platform/geometry/RoundedRect.h"
 #include "platform/graphics/Color.h"
 #include "platform/graphics/GraphicsTypes.h"
+#include "platform/scroll/ScrollableArea.h"
 #include "platform/text/TextDirection.h"
 #include "platform/text/UnicodeBidi.h"
 #include "platform/transforms/TransformOperations.h"
@@ -114,7 +114,7 @@
     friend class ApplyStyleCommand; // Editing has to only reveal unvisited info.
     friend class EditingStyle; // Editing has to only reveal unvisited info.
     friend class CSSComputedStyleDeclaration; // Ignores visited styles, so needs to be able to see unvisited info.
-    friend class PropertyWrapperMaybeInvalidColor; // Used by CSS animations. We can't allow them to animate based off visited colors.
+    friend class PropertyWrapperMaybeInvalidStyleColor; // Used by CSS animations. We can't allow them to animate based off visited colors.
     friend class StyleBuilderFunctions; // Sets color styles
     friend class CachedUAStyle; // Saves Border/Background information for later comparison.
 
@@ -243,7 +243,13 @@
         unsigned _table_layout : 1; // ETableLayout
 
         unsigned _unicodeBidi : 3; // EUnicodeBidi
-        // 31 bits
+
+        // This is set if we used viewport units when resolving a length.
+        // It is mutable so we can pass around const RenderStyles to resolve lengths.
+        mutable unsigned hasViewportUnits : 1;
+
+        // 32 bits
+
         unsigned _page_break_before : 2; // EPageBreak
         unsigned _page_break_after : 2; // EPageBreak
         unsigned _page_break_inside : 2; // EPageBreak
@@ -274,7 +280,7 @@
         unsigned _affectedByDrag : 1;
         unsigned _isLink : 1;
         // If you add more style bits here, you will also need to update RenderStyle::copyNonInheritedFrom()
-        // 60 bits
+        // 63 bits
     } noninherited_flags;
 
 // !END SYNC!
@@ -321,6 +327,7 @@
         noninherited_flags.emptyState = false;
         noninherited_flags.firstChildState = false;
         noninherited_flags.lastChildState = false;
+        noninherited_flags.hasViewportUnits = false;
         noninherited_flags.setAffectedByFocus(false);
         noninherited_flags.setAffectedByHover(false);
         noninherited_flags.setAffectedByActive(false);
@@ -362,8 +369,8 @@
 
     const PseudoStyleCache* cachedPseudoStyles() const { return m_cachedPseudoStyles.get(); }
 
-    void setVariable(const AtomicString& name, const String& value) { rareInheritedData.access()->m_variables.access()->setVariable(name, value); }
-    const HashMap<AtomicString, String>* variables() { return &(rareInheritedData->m_variables->m_data); }
+    void setHasViewportUnits(bool hasViewportUnits = true) const { noninherited_flags.hasViewportUnits = hasViewportUnits; }
+    bool hasViewportUnits() const { return noninherited_flags.hasViewportUnits; }
 
     bool affectedByFocus() const { return noninherited_flags.affectedByFocus(); }
     bool affectedByHover() const { return noninherited_flags.affectedByHover(); }
@@ -395,7 +402,7 @@
     bool hasBackground() const
     {
         Color color = visitedDependentColor(CSSPropertyBackgroundColor);
-        if (color.isValid() && color.alpha())
+        if (color.alpha())
             return true;
         return hasBackgroundImage();
     }
@@ -427,6 +434,7 @@
     bool hasPseudoStyle(PseudoId pseudo) const;
     void setHasPseudoStyle(PseudoId pseudo);
     bool hasUniquePseudoStyle() const;
+    bool hasPseudoElementStyle() const;
 
     // attribute getter methods
 
@@ -525,6 +533,9 @@
 
     EOverflow overflowX() const { return static_cast<EOverflow>(noninherited_flags._overflowX); }
     EOverflow overflowY() const { return static_cast<EOverflow>(noninherited_flags._overflowY); }
+    // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
+    bool isOverflowVisible() const { ASSERT(overflowX() != OVISIBLE || overflowX() == overflowY()); return overflowX() == OVISIBLE; }
+    bool isOverflowPaged() const { return overflowY() == OPAGEDX || overflowY() == OPAGEDY; }
 
     EVisibility visibility() const { return static_cast<EVisibility>(inherited_flags._visibility); }
     EVerticalAlign verticalAlign() const { return static_cast<EVerticalAlign>(noninherited_flags._vertical_align); }
@@ -572,7 +583,7 @@
 
     Length specifiedLineHeight() const;
     Length lineHeight() const;
-    int computedLineHeight(RenderView* = 0) const;
+    int computedLineHeight() const;
 
     EWhiteSpace whiteSpace() const { return static_cast<EWhiteSpace>(inherited_flags._white_space); }
     static bool autoWrap(EWhiteSpace ws)
@@ -749,16 +760,20 @@
     float flexShrink() const { return rareNonInheritedData->m_flexibleBox->m_flexShrink; }
     Length flexBasis() const { return rareNonInheritedData->m_flexibleBox->m_flexBasis; }
     EAlignContent alignContent() const { return static_cast<EAlignContent>(rareNonInheritedData->m_alignContent); }
-    EAlignItems alignItems() const { return static_cast<EAlignItems>(rareNonInheritedData->m_alignItems); }
-    EAlignItems alignSelf() const { return static_cast<EAlignItems>(rareNonInheritedData->m_alignSelf); }
+    ItemPosition alignItems() const { return static_cast<ItemPosition>(rareNonInheritedData->m_alignItems); }
+    OverflowAlignment alignItemsOverflowAlignment() const { return static_cast<OverflowAlignment>(rareNonInheritedData->m_alignItemsOverflowAlignment); }
+    ItemPosition alignSelf() const { return static_cast<ItemPosition>(rareNonInheritedData->m_alignSelf); }
+    OverflowAlignment alignSelfOverflowAlignment() const { return static_cast<OverflowAlignment>(rareNonInheritedData->m_alignSelfOverflowAlignment); }
     EFlexDirection flexDirection() const { return static_cast<EFlexDirection>(rareNonInheritedData->m_flexibleBox->m_flexDirection); }
     bool isColumnFlexDirection() const { return flexDirection() == FlowColumn || flexDirection() == FlowColumnReverse; }
     bool isReverseFlexDirection() const { return flexDirection() == FlowRowReverse || flexDirection() == FlowColumnReverse; }
     EFlexWrap flexWrap() const { return static_cast<EFlexWrap>(rareNonInheritedData->m_flexibleBox->m_flexWrap); }
     EJustifyContent justifyContent() const { return static_cast<EJustifyContent>(rareNonInheritedData->m_justifyContent); }
+    ItemPosition justifySelf() const { return static_cast<ItemPosition>(rareNonInheritedData->m_justifySelf); }
+    OverflowAlignment justifySelfOverflowAlignment() const { return static_cast<OverflowAlignment>(rareNonInheritedData->m_justifySelfOverflowAlignment); }
 
-    const Vector<GridTrackSize>& gridDefinitionColumns() const { return rareNonInheritedData->m_grid->m_gridDefinitionColumns; }
-    const Vector<GridTrackSize>& gridDefinitionRows() const { return rareNonInheritedData->m_grid->m_gridDefinitionRows; }
+    const Vector<GridTrackSize>& gridTemplateColumns() const { return rareNonInheritedData->m_grid->m_gridTemplateColumns; }
+    const Vector<GridTrackSize>& gridTemplateRows() const { return rareNonInheritedData->m_grid->m_gridTemplateRows; }
     const NamedGridLinesMap& namedGridColumnLines() const { return rareNonInheritedData->m_grid->m_namedGridColumnLines; }
     const NamedGridLinesMap& namedGridRowLines() const { return rareNonInheritedData->m_grid->m_namedGridRowLines; }
     const OrderedNamedGridLines& orderedNamedGridColumnLines() const { return rareNonInheritedData->m_grid->m_orderedNamedGridColumnLines; }
@@ -785,6 +800,8 @@
 
     EBoxDecorationBreak boxDecorationBreak() const { return m_box->boxDecorationBreak(); }
     StyleReflection* boxReflect() const { return rareNonInheritedData->m_boxReflect.get(); }
+    bool reflectionDataEquivalent(const RenderStyle* otherStyle) const { return rareNonInheritedData->reflectionDataEquivalent(*otherStyle->rareNonInheritedData); }
+
     EBoxSizing boxSizing() const { return m_box->boxSizing(); }
     Length marqueeIncrement() const { return rareNonInheritedData->m_marquee->increment; }
     int marqueeSpeed() const { return rareNonInheritedData->m_marquee->speed; }
@@ -810,6 +827,15 @@
         ColumnAxis axis = columnAxis();
         return axis == AutoColumnAxis || isHorizontalWritingMode() == (axis == HorizontalColumnAxis);
     }
+    bool hasInlinePaginationAxis() const
+    {
+        // If the pagination axis is parallel with the writing mode inline axis, columns may be laid
+        // out along the inline axis, just like for regular multicol. Otherwise, we need to lay out
+        // along the block axis.
+        if (isOverflowPaged())
+            return (overflowY() == OPAGEDX) == isHorizontalWritingMode();
+        return false;
+    }
     ColumnProgression columnProgression() const { return static_cast<ColumnProgression>(rareNonInheritedData->m_multiCol->m_progression); }
     float columnWidth() const { return rareNonInheritedData->m_multiCol->m_width; }
     bool hasAutoColumnWidth() const { return rareNonInheritedData->m_multiCol->m_autoWidth; }
@@ -827,14 +853,12 @@
     EPageBreak columnBreakBefore() const { return static_cast<EPageBreak>(rareNonInheritedData->m_multiCol->m_breakBefore); }
     EPageBreak columnBreakInside() const { return static_cast<EPageBreak>(rareNonInheritedData->m_multiCol->m_breakInside); }
     EPageBreak columnBreakAfter() const { return static_cast<EPageBreak>(rareNonInheritedData->m_multiCol->m_breakAfter); }
-    EPageBreak regionBreakBefore() const { return static_cast<EPageBreak>(rareNonInheritedData->m_regionBreakBefore); }
-    EPageBreak regionBreakInside() const { return static_cast<EPageBreak>(rareNonInheritedData->m_regionBreakInside); }
-    EPageBreak regionBreakAfter() const { return static_cast<EPageBreak>(rareNonInheritedData->m_regionBreakAfter); }
     const TransformOperations& transform() const { return rareNonInheritedData->m_transform->m_operations; }
     Length transformOriginX() const { return rareNonInheritedData->m_transform->m_x; }
     Length transformOriginY() const { return rareNonInheritedData->m_transform->m_y; }
     float transformOriginZ() const { return rareNonInheritedData->m_transform->m_z; }
     bool hasTransform() const { return !rareNonInheritedData->m_transform->m_operations.operations().isEmpty(); }
+    bool transformDataEquivalent(const RenderStyle* otherStyle) const { return rareNonInheritedData->m_transform == otherStyle->rareNonInheritedData->m_transform; }
 
     TextEmphasisFill textEmphasisFill() const { return static_cast<TextEmphasisFill>(rareInheritedData->textEmphasisFill); }
     TextEmphasisMark textEmphasisMark() const;
@@ -866,15 +890,6 @@
 
     // End CSS3 Getters
 
-    const AtomicString& flowThread() const { return rareNonInheritedData->m_flowThread; }
-    bool hasFlowFrom() const { return !rareNonInheritedData->m_regionThread.isNull(); }
-    const AtomicString& regionThread() const { return rareNonInheritedData->m_regionThread; }
-    RegionFragment regionFragment() const { return static_cast<RegionFragment>(rareNonInheritedData->m_regionFragment); }
-
-    const AtomicString& lineGrid() const { return rareInheritedData->m_lineGrid; }
-    LineSnap lineSnap() const { return static_cast<LineSnap>(rareInheritedData->m_lineSnap); }
-    LineAlign lineAlign() const { return static_cast<LineAlign>(rareInheritedData->m_lineAlign); }
-
     WrapFlow wrapFlow() const { return static_cast<WrapFlow>(rareNonInheritedData->m_wrapFlow); }
     WrapThrough wrapThrough() const { return static_cast<WrapThrough>(rareNonInheritedData->m_wrapThrough); }
 
@@ -936,6 +951,8 @@
     TouchAction touchAction() const { return static_cast<TouchAction>(rareNonInheritedData->m_touchAction); }
     TouchActionDelay touchActionDelay() const { return static_cast<TouchActionDelay>(rareInheritedData->m_touchActionDelay); }
 
+    ScrollBehavior scrollBehavior() const { return static_cast<ScrollBehavior>(rareNonInheritedData->m_scrollBehavior); }
+
 // attribute setter methods
 
     void setDisplay(EDisplay v) { noninherited_flags._effectiveDisplay = v; }
@@ -989,7 +1006,7 @@
     void resetBorderBottomLeftRadius() { SET_VAR(surround, border.m_bottomLeft, initialBorderRadius()); }
     void resetBorderBottomRightRadius() { SET_VAR(surround, border.m_bottomRight, initialBorderRadius()); }
 
-    void setBackgroundColor(const Color& v) { SET_VAR(m_background, m_color, v); }
+    void setBackgroundColor(const StyleColor& v) { SET_VAR(m_background, m_color, v); }
 
     void setBackgroundXPosition(Length length) { SET_VAR(m_background, m_background.m_xPosition, length); }
     void setBackgroundYPosition(Length length) { SET_VAR(m_background, m_background.m_yPosition, length); }
@@ -1019,7 +1036,7 @@
         setBorderRadius(LengthSize(Length(s.width(), Fixed), Length(s.height(), Fixed)));
     }
 
-    RoundedRect getRoundedBorderFor(const LayoutRect& borderRect, RenderView* = 0, bool includeLogicalLeftEdge = true, bool includeLogicalRightEdge = true) const;
+    RoundedRect getRoundedBorderFor(const LayoutRect& borderRect, bool includeLogicalLeftEdge = true, bool includeLogicalRightEdge = true) const;
     RoundedRect getRoundedInnerBorderFor(const LayoutRect& borderRect, bool includeLogicalLeftEdge = true, bool includeLogicalRightEdge = true) const;
 
     RoundedRect getRoundedInnerBorderFor(const LayoutRect& borderRect,
@@ -1027,21 +1044,21 @@
 
     void setBorderLeftWidth(unsigned v) { SET_VAR(surround, border.m_left.m_width, v); }
     void setBorderLeftStyle(EBorderStyle v) { SET_VAR(surround, border.m_left.m_style, v); }
-    void setBorderLeftColor(const Color& v) { SET_BORDERVALUE_COLOR(surround, border.m_left, v); }
+    void setBorderLeftColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(surround, border.m_left, v); }
     void setBorderRightWidth(unsigned v) { SET_VAR(surround, border.m_right.m_width, v); }
     void setBorderRightStyle(EBorderStyle v) { SET_VAR(surround, border.m_right.m_style, v); }
-    void setBorderRightColor(const Color& v) { SET_BORDERVALUE_COLOR(surround, border.m_right, v); }
+    void setBorderRightColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(surround, border.m_right, v); }
     void setBorderTopWidth(unsigned v) { SET_VAR(surround, border.m_top.m_width, v); }
     void setBorderTopStyle(EBorderStyle v) { SET_VAR(surround, border.m_top.m_style, v); }
-    void setBorderTopColor(const Color& v) { SET_BORDERVALUE_COLOR(surround, border.m_top, v); }
+    void setBorderTopColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(surround, border.m_top, v); }
     void setBorderBottomWidth(unsigned v) { SET_VAR(surround, border.m_bottom.m_width, v); }
     void setBorderBottomStyle(EBorderStyle v) { SET_VAR(surround, border.m_bottom.m_style, v); }
-    void setBorderBottomColor(const Color& v) { SET_BORDERVALUE_COLOR(surround, border.m_bottom, v); }
+    void setBorderBottomColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(surround, border.m_bottom, v); }
 
     void setOutlineWidth(unsigned short v) { SET_VAR(m_background, m_outline.m_width, v); }
     void setOutlineStyleIsAuto(OutlineIsAuto isAuto) { SET_VAR(m_background, m_outline.m_isAuto, isAuto); }
     void setOutlineStyle(EBorderStyle v) { SET_VAR(m_background, m_outline.m_style, v); }
-    void setOutlineColor(const Color& v) { SET_BORDERVALUE_COLOR(m_background, m_outline, v); }
+    void setOutlineColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(m_background, m_outline, v); }
 
     void setOverflowX(EOverflow v) { noninherited_flags._overflowX = v; }
     void setOverflowY(EOverflow v) { noninherited_flags._overflowY = v; }
@@ -1094,6 +1111,7 @@
 
     void setWhiteSpace(EWhiteSpace v) { inherited_flags._white_space = v; }
 
+    // FIXME: Remove these two and replace them with respective FontBuilder calls.
     void setWordSpacing(float);
     void setLetterSpacing(float);
 
@@ -1202,9 +1220,9 @@
     // CSS3 Setters
     void setOutlineOffset(int v) { SET_VAR(m_background, m_outline.m_offset, v); }
     void setTextShadow(PassRefPtr<ShadowList>);
-    void setTextStrokeColor(const Color& c) { SET_VAR(rareInheritedData, textStrokeColor, c); }
+    void setTextStrokeColor(const StyleColor& c) { SET_VAR(rareInheritedData, textStrokeColor, c); }
     void setTextStrokeWidth(float w) { SET_VAR(rareInheritedData, textStrokeWidth, w); }
-    void setTextFillColor(const Color& c) { SET_VAR(rareInheritedData, textFillColor, c); }
+    void setTextFillColor(const StyleColor& c) { SET_VAR(rareInheritedData, textFillColor, c); }
     void setOpacity(float f) { float v = clampTo<float>(f, 0, 1); SET_VAR(rareNonInheritedData, opacity, v); }
     void setAppearance(ControlPart a) { SET_VAR(rareNonInheritedData, m_appearance, a); }
     // For valid values of box-align see http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#alignment
@@ -1223,18 +1241,23 @@
     void setFlexGrow(float f) { SET_VAR(rareNonInheritedData.access()->m_flexibleBox, m_flexGrow, f); }
     void setFlexShrink(float f) { SET_VAR(rareNonInheritedData.access()->m_flexibleBox, m_flexShrink, f); }
     void setFlexBasis(Length length) { SET_VAR(rareNonInheritedData.access()->m_flexibleBox, m_flexBasis, length); }
-    void setOrder(int o) { SET_VAR(rareNonInheritedData, m_order, o); }
+    // We restrict the smallest value to int min + 2 because we use int min and int min + 1 as special values in a hash set.
+    void setOrder(int o) { SET_VAR(rareNonInheritedData, m_order, max(std::numeric_limits<int>::min() + 2, o)); }
     void addCallbackSelector(const String& selector);
     void setAlignContent(EAlignContent p) { SET_VAR(rareNonInheritedData, m_alignContent, p); }
-    void setAlignItems(EAlignItems a) { SET_VAR(rareNonInheritedData, m_alignItems, a); }
-    void setAlignSelf(EAlignItems a) { SET_VAR(rareNonInheritedData, m_alignSelf, a); }
+    void setAlignItems(ItemPosition a) { SET_VAR(rareNonInheritedData, m_alignItems, a); }
+    void setAlignItemsOverflowAlignment(OverflowAlignment overflowAlignment) { SET_VAR(rareNonInheritedData, m_alignItemsOverflowAlignment, overflowAlignment); }
+    void setAlignSelf(ItemPosition a) { SET_VAR(rareNonInheritedData, m_alignSelf, a); }
+    void setAlignSelfOverflowAlignment(OverflowAlignment overflowAlignment) { SET_VAR(rareNonInheritedData, m_alignSelfOverflowAlignment, overflowAlignment); }
     void setFlexDirection(EFlexDirection direction) { SET_VAR(rareNonInheritedData.access()->m_flexibleBox, m_flexDirection, direction); }
     void setFlexWrap(EFlexWrap w) { SET_VAR(rareNonInheritedData.access()->m_flexibleBox, m_flexWrap, w); }
     void setJustifyContent(EJustifyContent p) { SET_VAR(rareNonInheritedData, m_justifyContent, p); }
+    void setJustifySelf(ItemPosition justifySelf) { SET_VAR(rareNonInheritedData, m_justifySelf, justifySelf); }
+    void setJustifySelfOverflowAlignment(OverflowAlignment overflowAlignment) { SET_VAR(rareNonInheritedData, m_justifySelfOverflowAlignment, overflowAlignment); }
     void setGridAutoColumns(const GridTrackSize& length) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridAutoColumns, length); }
     void setGridAutoRows(const GridTrackSize& length) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridAutoRows, length); }
-    void setGridDefinitionColumns(const Vector<GridTrackSize>& lengths) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridDefinitionColumns, lengths); }
-    void setGridDefinitionRows(const Vector<GridTrackSize>& lengths) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridDefinitionRows, lengths); }
+    void setGridTemplateColumns(const Vector<GridTrackSize>& lengths) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridTemplateColumns, lengths); }
+    void setGridTemplateRows(const Vector<GridTrackSize>& lengths) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridTemplateRows, lengths); }
     void setNamedGridColumnLines(const NamedGridLinesMap& namedGridColumnLines) { SET_VAR(rareNonInheritedData.access()->m_grid, m_namedGridColumnLines, namedGridColumnLines); }
     void setNamedGridRowLines(const NamedGridLinesMap& namedGridRowLines) { SET_VAR(rareNonInheritedData.access()->m_grid, m_namedGridRowLines, namedGridRowLines); }
     void setOrderedNamedGridColumnLines(const OrderedNamedGridLines& orderedNamedGridColumnLines) { SET_VAR(rareNonInheritedData.access()->m_grid, m_orderedNamedGridColumnLines, orderedNamedGridColumnLines); }
@@ -1278,7 +1301,7 @@
     void setColumnFill(ColumnFill columnFill) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_fill, columnFill); }
     void setColumnGap(float f) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_normalGap, false); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_gap, f); }
     void setHasNormalColumnGap() { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_normalGap, true); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_gap, 0); }
-    void setColumnRuleColor(const Color& c) { SET_BORDERVALUE_COLOR(rareNonInheritedData.access()->m_multiCol, m_rule, c); }
+    void setColumnRuleColor(const StyleColor& c) { SET_BORDERVALUE_COLOR(rareNonInheritedData.access()->m_multiCol, m_rule, c); }
     void setColumnRuleStyle(EBorderStyle b) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_rule.m_style, b); }
     void setColumnRuleWidth(unsigned short w) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_rule.m_width, w); }
     void resetColumnRule() { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_rule, BorderValue()); }
@@ -1287,9 +1310,6 @@
     // For valid values of column-break-inside see http://www.w3.org/TR/css3-multicol/#break-before-break-after-break-inside
     void setColumnBreakInside(EPageBreak p) { ASSERT(p == PBAUTO || p == PBAVOID); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_breakInside, p); }
     void setColumnBreakAfter(EPageBreak p) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_breakAfter, p); }
-    void setRegionBreakBefore(EPageBreak p) { SET_VAR(rareNonInheritedData, m_regionBreakBefore, p); }
-    void setRegionBreakInside(EPageBreak p) { ASSERT(p == PBAUTO || p == PBAVOID); SET_VAR(rareNonInheritedData, m_regionBreakInside, p); }
-    void setRegionBreakAfter(EPageBreak p) { SET_VAR(rareNonInheritedData, m_regionBreakAfter, p); }
     void inheritColumnPropertiesFrom(RenderStyle* parent) { rareNonInheritedData.access()->m_multiCol = parent->rareNonInheritedData->m_multiCol; }
     void setTransform(const TransformOperations& ops) { SET_VAR(rareNonInheritedData.access()->m_transform, m_operations, ops); }
     void setTransformOriginX(Length l) { SET_VAR(rareNonInheritedData.access()->m_transform, m_x, l); }
@@ -1297,8 +1317,8 @@
     void setTransformOriginZ(float f) { SET_VAR(rareNonInheritedData.access()->m_transform, m_z, f); }
     void setSpeak(ESpeak s) { SET_VAR(rareInheritedData, speak, s); }
     void setTextCombine(TextCombine v) { SET_VAR(rareNonInheritedData, m_textCombine, v); }
-    void setTextDecorationColor(const Color& c) { SET_VAR(rareNonInheritedData, m_textDecorationColor, c); }
-    void setTextEmphasisColor(const Color& c) { SET_VAR(rareInheritedData, textEmphasisColor, c); }
+    void setTextDecorationColor(const StyleColor& c) { SET_VAR(rareNonInheritedData, m_textDecorationColor, c); }
+    void setTextEmphasisColor(const StyleColor& c) { SET_VAR(rareInheritedData, textEmphasisColor, c); }
     void setTextEmphasisFill(TextEmphasisFill fill) { SET_VAR(rareInheritedData, textEmphasisFill, fill); }
     void setTextEmphasisMark(TextEmphasisMark mark) { SET_VAR(rareInheritedData, textEmphasisMark, mark); }
     void setTextEmphasisCustomMark(const AtomicString& mark) { SET_VAR(rareInheritedData, textEmphasisCustomMark, mark); }
@@ -1316,14 +1336,6 @@
 
     // End CSS3 Setters
 
-    void setLineGrid(const AtomicString& lineGrid) { SET_VAR(rareInheritedData, m_lineGrid, lineGrid); }
-    void setLineSnap(LineSnap lineSnap) { SET_VAR(rareInheritedData, m_lineSnap, lineSnap); }
-    void setLineAlign(LineAlign lineAlign) { SET_VAR(rareInheritedData, m_lineAlign, lineAlign); }
-
-    void setFlowThread(const AtomicString& flowThread) { SET_VAR(rareNonInheritedData, m_flowThread, flowThread); }
-    void setRegionThread(const AtomicString& regionThread) { SET_VAR(rareNonInheritedData, m_regionThread, regionThread); }
-    void setRegionFragment(RegionFragment regionFragment) { SET_VAR(rareNonInheritedData, m_regionFragment, regionFragment); }
-
     void setWrapFlow(WrapFlow wrapFlow) { SET_VAR(rareNonInheritedData, m_wrapFlow, wrapFlow); }
     void setWrapThrough(WrapThrough wrapThrough) { SET_VAR(rareNonInheritedData, m_wrapThrough, wrapThrough); }
 
@@ -1361,6 +1373,8 @@
     void setTouchAction(TouchAction t) { SET_VAR(rareNonInheritedData, m_touchAction, t); }
     void setTouchActionDelay(TouchActionDelay t) { SET_VAR(rareInheritedData, m_touchActionDelay, t); }
 
+    void setScrollBehavior(ScrollBehavior b) { SET_VAR(rareNonInheritedData, m_scrollBehavior, b); }
+
     const SVGRenderStyle* svgStyle() const { return m_svgStyle.get(); }
     SVGRenderStyle* accessSVGStyle() { return m_svgStyle.access(); }
 
@@ -1375,12 +1389,12 @@
     void setStrokePaintColor(const Color& c) { accessSVGStyle()->setStrokePaint(SVGPaint::SVG_PAINTTYPE_RGBCOLOR, c, ""); }
     float strokeOpacity() const { return svgStyle()->strokeOpacity(); }
     void setStrokeOpacity(float f) { accessSVGStyle()->setStrokeOpacity(f); }
-    SVGLength strokeWidth() const { return svgStyle()->strokeWidth(); }
-    void setStrokeWidth(SVGLength w) { accessSVGStyle()->setStrokeWidth(w); }
-    Vector<SVGLength> strokeDashArray() const { return svgStyle()->strokeDashArray(); }
-    void setStrokeDashArray(Vector<SVGLength> array) { accessSVGStyle()->setStrokeDashArray(array); }
-    SVGLength strokeDashOffset() const { return svgStyle()->strokeDashOffset(); }
-    void setStrokeDashOffset(SVGLength d) { accessSVGStyle()->setStrokeDashOffset(d); }
+    PassRefPtr<SVGLength> strokeWidth() const { return svgStyle()->strokeWidth(); }
+    void setStrokeWidth(PassRefPtr<SVGLength> w) { accessSVGStyle()->setStrokeWidth(w); }
+    PassRefPtr<SVGLengthList> strokeDashArray() const { return svgStyle()->strokeDashArray(); }
+    void setStrokeDashArray(PassRefPtr<SVGLengthList> array) { accessSVGStyle()->setStrokeDashArray(array); }
+    PassRefPtr<SVGLength> strokeDashOffset() const { return svgStyle()->strokeDashOffset(); }
+    void setStrokeDashOffset(PassRefPtr<SVGLength> d) { accessSVGStyle()->setStrokeDashOffset(d); }
     float strokeMiterLimit() const { return svgStyle()->strokeMiterLimit(); }
     void setStrokeMiterLimit(float f) { accessSVGStyle()->setStrokeMiterLimit(f); }
 
@@ -1394,10 +1408,10 @@
     void setFloodColor(const Color& c) { accessSVGStyle()->setFloodColor(c); }
     void setLightingColor(const Color& c) { accessSVGStyle()->setLightingColor(c); }
 
-    SVGLength baselineShiftValue() const { return svgStyle()->baselineShiftValue(); }
-    void setBaselineShiftValue(SVGLength s) { accessSVGStyle()->setBaselineShiftValue(s); }
-    SVGLength kerning() const { return svgStyle()->kerning(); }
-    void setKerning(SVGLength k) { accessSVGStyle()->setKerning(k); }
+    PassRefPtr<SVGLength> baselineShiftValue() const { return svgStyle()->baselineShiftValue(); }
+    void setBaselineShiftValue(PassRefPtr<SVGLength> s) { accessSVGStyle()->setBaselineShiftValue(s); }
+    PassRefPtr<SVGLength> kerning() const { return svgStyle()->kerning(); }
+    void setKerning(PassRefPtr<SVGLength> k) { accessSVGStyle()->setKerning(k); }
 
     void setShapeInside(PassRefPtr<ShapeValue> value)
     {
@@ -1476,12 +1490,6 @@
     bool isDisplayReplacedType() const { return isDisplayReplacedType(display()); }
     bool isDisplayInlineType() const { return isDisplayInlineType(display()); }
     bool isOriginalDisplayInlineType() const { return isDisplayInlineType(originalDisplay()); }
-    bool isDisplayRegionType() const
-    {
-        return display() == BLOCK || display() == INLINE_BLOCK
-            || display() == TABLE_CELL || display() == TABLE_CAPTION
-            || display() == LIST_ITEM;
-    }
 
     bool setWritingMode(WritingMode v)
     {
@@ -1505,6 +1513,7 @@
     bool lastChildState() const { return noninherited_flags.lastChildState; }
     void setLastChildState() { setUnique(); noninherited_flags.lastChildState = true; }
 
+    StyleColor visitedDependentDecorationColor() const;
     Color visitedDependentColor(int colorProperty) const;
 
     void setHasExplicitlyInheritedProperties() { noninherited_flags.explicitInheritance = true; }
@@ -1589,11 +1598,15 @@
     static Length initialFlexBasis() { return Length(Auto); }
     static int initialOrder() { return 0; }
     static EAlignContent initialAlignContent() { return AlignContentStretch; }
-    static EAlignItems initialAlignItems() { return AlignStretch; }
-    static EAlignItems initialAlignSelf() { return AlignAuto; }
+    static ItemPosition initialAlignItems() { return ItemPositionStretch; }
+    static OverflowAlignment initialAlignItemsOverflowAlignment() { return OverflowAlignmentDefault; }
+    static ItemPosition initialAlignSelf() { return ItemPositionAuto; }
+    static OverflowAlignment initialAlignSelfOverflowAlignment() { return OverflowAlignmentDefault; }
     static EFlexDirection initialFlexDirection() { return FlowRow; }
     static EFlexWrap initialFlexWrap() { return FlexNoWrap; }
     static EJustifyContent initialJustifyContent() { return JustifyFlexStart; }
+    static ItemPosition initialJustifySelf() { return ItemPositionAuto; }
+    static OverflowAlignment initialJustifySelfOverflowAlignment() { return OverflowAlignmentDefault; }
     static int initialMarqueeLoopCount() { return -1; }
     static int initialMarqueeSpeed() { return 85; }
     static Length initialMarqueeIncrement() { return Length(6, Fixed); }
@@ -1653,15 +1666,16 @@
     static TouchActionDelay initialTouchActionDelay() { return TouchActionDelayScript; }
     static ShadowList* initialBoxShadow() { return 0; }
     static ShadowList* initialTextShadow() { return 0; }
+    static ScrollBehavior initialScrollBehavior() { return ScrollBehaviorInstant; }
 
     // The initial value is 'none' for grid tracks.
-    static Vector<GridTrackSize> initialGridDefinitionColumns() { return Vector<GridTrackSize>(); }
-    static Vector<GridTrackSize> initialGridDefinitionRows() { return Vector<GridTrackSize>(); }
+    static Vector<GridTrackSize> initialGridTemplateColumns() { return Vector<GridTrackSize>(); }
+    static Vector<GridTrackSize> initialGridTemplateRows() { return Vector<GridTrackSize>(); }
 
     static GridAutoFlow initialGridAutoFlow() { return AutoFlowNone; }
 
-    static GridTrackSize initialGridAutoColumns() { return GridTrackSize(Auto); }
-    static GridTrackSize initialGridAutoRows() { return GridTrackSize(Auto); }
+    static GridTrackSize initialGridAutoColumns() { return GridTrackSize(Length(Auto)); }
+    static GridTrackSize initialGridAutoRows() { return GridTrackSize(Length(Auto)); }
 
     static NamedGridLinesMap initialNamedGridColumnLines() { return NamedGridLinesMap(); }
     static NamedGridLinesMap initialNamedGridRowLines() { return NamedGridLinesMap(); }
@@ -1680,14 +1694,6 @@
 
     static unsigned initialTabSize() { return 8; }
 
-    static const AtomicString& initialLineGrid() { return nullAtom; }
-    static LineSnap initialLineSnap() { return LineSnapNone; }
-    static LineAlign initialLineAlign() { return LineAlignNone; }
-
-    static const AtomicString& initialFlowThread() { return nullAtom; }
-    static const AtomicString& initialRegionThread() { return nullAtom; }
-    static RegionFragment initialRegionFragment() { return AutoRegionFragment; }
-
     static WrapFlow initialWrapFlow() { return WrapFlowAuto; }
     static WrapThrough initialWrapThrough() { return WrapThroughWrap; }
 
@@ -1703,17 +1709,17 @@
     static EIsolation initialIsolation() { return IsolationAuto; }
 private:
     void setVisitedLinkColor(const Color&);
-    void setVisitedLinkBackgroundColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBackgroundColor, v); }
-    void setVisitedLinkBorderLeftColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderLeftColor, v); }
-    void setVisitedLinkBorderRightColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderRightColor, v); }
-    void setVisitedLinkBorderBottomColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderBottomColor, v); }
-    void setVisitedLinkBorderTopColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderTopColor, v); }
-    void setVisitedLinkOutlineColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkOutlineColor, v); }
-    void setVisitedLinkColumnRuleColor(const Color& v) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_visitedLinkColumnRuleColor, v); }
-    void setVisitedLinkTextDecorationColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkTextDecorationColor, v); }
-    void setVisitedLinkTextEmphasisColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextEmphasisColor, v); }
-    void setVisitedLinkTextFillColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextFillColor, v); }
-    void setVisitedLinkTextStrokeColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextStrokeColor, v); }
+    void setVisitedLinkBackgroundColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBackgroundColor, v); }
+    void setVisitedLinkBorderLeftColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderLeftColor, v); }
+    void setVisitedLinkBorderRightColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderRightColor, v); }
+    void setVisitedLinkBorderBottomColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderBottomColor, v); }
+    void setVisitedLinkBorderTopColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderTopColor, v); }
+    void setVisitedLinkOutlineColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkOutlineColor, v); }
+    void setVisitedLinkColumnRuleColor(const StyleColor& v) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_visitedLinkColumnRuleColor, v); }
+    void setVisitedLinkTextDecorationColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkTextDecorationColor, v); }
+    void setVisitedLinkTextEmphasisColor(const StyleColor& v) { SET_VAR(rareInheritedData, visitedLinkTextEmphasisColor, v); }
+    void setVisitedLinkTextFillColor(const StyleColor& v) { SET_VAR(rareInheritedData, visitedLinkTextFillColor, v); }
+    void setVisitedLinkTextStrokeColor(const StyleColor& v) { SET_VAR(rareInheritedData, visitedLinkTextStrokeColor, v); }
 
     void inheritUnicodeBidiFrom(const RenderStyle* parent) { noninherited_flags._unicodeBidi = parent->noninherited_flags._unicodeBidi; }
     void getShadowExtent(const ShadowList*, LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const;
@@ -1741,31 +1747,30 @@
     }
 
     // Color accessors are all private to make sure callers use visitedDependentColor instead to access them.
-    Color invalidColor() const { static Color invalid; return invalid; }
-    Color borderLeftColor() const { return surround->border.left().color(); }
-    Color borderRightColor() const { return surround->border.right().color(); }
-    Color borderTopColor() const { return surround->border.top().color(); }
-    Color borderBottomColor() const { return surround->border.bottom().color(); }
-    Color backgroundColor() const { return m_background->color(); }
+    StyleColor borderLeftColor() const { return surround->border.left().color(); }
+    StyleColor borderRightColor() const { return surround->border.right().color(); }
+    StyleColor borderTopColor() const { return surround->border.top().color(); }
+    StyleColor borderBottomColor() const { return surround->border.bottom().color(); }
+    StyleColor backgroundColor() const { return m_background->color(); }
     Color color() const;
-    Color columnRuleColor() const { return rareNonInheritedData->m_multiCol->m_rule.color(); }
-    Color outlineColor() const { return m_background->outline().color(); }
-    Color textEmphasisColor() const { return rareInheritedData->textEmphasisColor; }
-    Color textFillColor() const { return rareInheritedData->textFillColor; }
-    Color textStrokeColor() const { return rareInheritedData->textStrokeColor; }
+    StyleColor columnRuleColor() const { return rareNonInheritedData->m_multiCol->m_rule.color(); }
+    StyleColor outlineColor() const { return m_background->outline().color(); }
+    StyleColor textEmphasisColor() const { return rareInheritedData->textEmphasisColor; }
+    StyleColor textFillColor() const { return rareInheritedData->textFillColor; }
+    StyleColor textStrokeColor() const { return rareInheritedData->textStrokeColor; }
     Color visitedLinkColor() const;
-    Color visitedLinkBackgroundColor() const { return rareNonInheritedData->m_visitedLinkBackgroundColor; }
-    Color visitedLinkBorderLeftColor() const { return rareNonInheritedData->m_visitedLinkBorderLeftColor; }
-    Color visitedLinkBorderRightColor() const { return rareNonInheritedData->m_visitedLinkBorderRightColor; }
-    Color visitedLinkBorderBottomColor() const { return rareNonInheritedData->m_visitedLinkBorderBottomColor; }
-    Color visitedLinkBorderTopColor() const { return rareNonInheritedData->m_visitedLinkBorderTopColor; }
-    Color visitedLinkOutlineColor() const { return rareNonInheritedData->m_visitedLinkOutlineColor; }
-    Color visitedLinkColumnRuleColor() const { return rareNonInheritedData->m_multiCol->m_visitedLinkColumnRuleColor; }
-    Color textDecorationColor() const { return rareNonInheritedData->m_textDecorationColor; }
-    Color visitedLinkTextDecorationColor() const { return rareNonInheritedData->m_visitedLinkTextDecorationColor; }
-    Color visitedLinkTextEmphasisColor() const { return rareInheritedData->visitedLinkTextEmphasisColor; }
-    Color visitedLinkTextFillColor() const { return rareInheritedData->visitedLinkTextFillColor; }
-    Color visitedLinkTextStrokeColor() const { return rareInheritedData->visitedLinkTextStrokeColor; }
+    StyleColor visitedLinkBackgroundColor() const { return rareNonInheritedData->m_visitedLinkBackgroundColor; }
+    StyleColor visitedLinkBorderLeftColor() const { return rareNonInheritedData->m_visitedLinkBorderLeftColor; }
+    StyleColor visitedLinkBorderRightColor() const { return rareNonInheritedData->m_visitedLinkBorderRightColor; }
+    StyleColor visitedLinkBorderBottomColor() const { return rareNonInheritedData->m_visitedLinkBorderBottomColor; }
+    StyleColor visitedLinkBorderTopColor() const { return rareNonInheritedData->m_visitedLinkBorderTopColor; }
+    StyleColor visitedLinkOutlineColor() const { return rareNonInheritedData->m_visitedLinkOutlineColor; }
+    StyleColor visitedLinkColumnRuleColor() const { return rareNonInheritedData->m_multiCol->m_visitedLinkColumnRuleColor; }
+    StyleColor textDecorationColor() const { return rareNonInheritedData->m_textDecorationColor; }
+    StyleColor visitedLinkTextDecorationColor() const { return rareNonInheritedData->m_visitedLinkTextDecorationColor; }
+    StyleColor visitedLinkTextEmphasisColor() const { return rareInheritedData->visitedLinkTextEmphasisColor; }
+    StyleColor visitedLinkTextFillColor() const { return rareInheritedData->visitedLinkTextFillColor; }
+    StyleColor visitedLinkTextStrokeColor() const { return rareInheritedData->visitedLinkTextStrokeColor; }
 
     Color colorIncludingFallback(int colorProperty, bool visitedLink) const;
 
@@ -1774,6 +1779,7 @@
     Color lightingColor() const { return svgStyle()->lightingColor(); }
 
     void appendContent(PassOwnPtr<ContentData>);
+    StyleDifference repaintOnlyDiff(const RenderStyle* other, unsigned& changedContextSensitiveProperties) const;
 };
 
 inline int adjustForAbsoluteZoom(int value, float zoomFactor)
@@ -1862,6 +1868,11 @@
     noninherited_flags._pseudoBits |= 1 << (pseudo - 1);
 }
 
+inline bool RenderStyle::hasPseudoElementStyle() const
+{
+    return noninherited_flags._pseudoBits & PSEUDO_ELEMENT_MASK;
+}
+
 } // namespace WebCore
 
 #endif // RenderStyle_h
diff --git a/Source/core/rendering/style/RenderStyleConstants.h b/Source/core/rendering/style/RenderStyleConstants.h
index a37868e..020ed1c 100644
--- a/Source/core/rendering/style/RenderStyleConstants.h
+++ b/Source/core/rendering/style/RenderStyleConstants.h
@@ -31,6 +31,7 @@
 enum StyleRecalcChange {
     NoChange,
     NoInherit,
+    UpdatePseudoElements,
     Inherit,
     Force,
     Reattach,
@@ -81,13 +82,13 @@
     // If you add or remove a public ID, you must update _pseudoBits in RenderStyle.
     NOPSEUDO, FIRST_LINE, FIRST_LETTER, BEFORE, AFTER, BACKDROP, SELECTION, FIRST_LINE_INHERITED, SCROLLBAR,
     // Internal IDs follow:
-    SCROLLBAR_THUMB, SCROLLBAR_BUTTON, SCROLLBAR_TRACK, SCROLLBAR_TRACK_PIECE, SCROLLBAR_CORNER, RESIZER,
-    INPUT_LIST_BUTTON,
+    SCROLLBAR_THUMB, SCROLLBAR_BUTTON, SCROLLBAR_TRACK, SCROLLBAR_TRACK_PIECE, SCROLLBAR_CORNER, RESIZER, INPUT_LIST_BUTTON,
+    // Special values follow:
     AFTER_LAST_INTERNAL_PSEUDOID,
-    FULL_SCREEN, FULL_SCREEN_DOCUMENT, FULL_SCREEN_ANCESTOR,
     FIRST_PUBLIC_PSEUDOID = FIRST_LINE,
     FIRST_INTERNAL_PSEUDOID = SCROLLBAR_THUMB,
-    PUBLIC_PSEUDOID_MASK = ((1 << FIRST_INTERNAL_PSEUDOID) - 1) & ~((1 << FIRST_PUBLIC_PSEUDOID) - 1)
+    PUBLIC_PSEUDOID_MASK = ((1 << FIRST_INTERNAL_PSEUDOID) - 1) & ~((1 << FIRST_PUBLIC_PSEUDOID) - 1),
+    PSEUDO_ELEMENT_MASK = (1 << (BEFORE - 1)) | (1 << (AFTER - 1)) | (1 << (BACKDROP - 1))
 };
 
 enum ColumnFill { ColumnFillBalance, ColumnFillAuto };
@@ -191,7 +192,6 @@
 // CSS3 Flexbox Properties
 
 enum EAlignContent { AlignContentFlexStart, AlignContentFlexEnd, AlignContentCenter, AlignContentSpaceBetween, AlignContentSpaceAround, AlignContentStretch };
-enum EAlignItems { AlignAuto, AlignFlexStart, AlignFlexEnd, AlignCenter, AlignStretch, AlignBaseline };
 enum EFlexDirection { FlowRow, FlowRowReverse, FlowColumn, FlowColumnReverse };
 enum EFlexWrap { FlexNoWrap, FlexWrap, FlexWrapReverse };
 enum EJustifyContent { JustifyFlexStart, JustifyFlexEnd, JustifyCenter, JustifySpaceBetween, JustifySpaceAround };
@@ -450,7 +450,9 @@
     TABLE_CAPTION, BOX, INLINE_BOX,
     FLEX, INLINE_FLEX,
     GRID, INLINE_GRID,
-    NONE
+    NONE,
+    FIRST_TABLE_DISPLAY = TABLE,
+    LAST_TABLE_DISPLAY = TABLE_CAPTION
 };
 
 enum EInsideLink {
@@ -495,16 +497,10 @@
 
 enum Order { LogicalOrder = 0, VisualOrder };
 
-enum RegionFragment { AutoRegionFragment, BreakRegionFragment };
-
 enum ColumnAxis { HorizontalColumnAxis, VerticalColumnAxis, AutoColumnAxis };
 
 enum ColumnProgression { NormalColumnProgression, ReverseColumnProgression };
 
-enum LineSnap { LineSnapNone, LineSnapBaseline, LineSnapContain };
-
-enum LineAlign { LineAlignNone, LineAlignEdges };
-
 enum WrapFlow { WrapFlowAuto, WrapFlowBoth, WrapFlowStart, WrapFlowEnd, WrapFlowMaximum, WrapFlowClear };
 
 enum WrapThrough { WrapThroughWrap, WrapThroughNone };
@@ -515,18 +511,49 @@
 
 enum DraggableRegionMode { DraggableRegionNone, DraggableRegionDrag, DraggableRegionNoDrag };
 
-enum TouchAction { TouchActionNone, TouchActionAuto };
+static const size_t TouchActionBits = 3;
+enum TouchAction {
+    TouchActionAuto = 0x0,
+    TouchActionNone = 0x1,
+    TouchActionPanX = 0x2,
+    TouchActionPanY = 0x4
+};
+inline TouchAction operator| (TouchAction a, TouchAction b) { return TouchAction(int(a) | int(b)); }
+inline TouchAction& operator|= (TouchAction& a, TouchAction b) { return a = a | b; }
+inline TouchAction operator& (TouchAction a, TouchAction b) { return TouchAction(int(a) & int(b)); }
+inline TouchAction& operator&= (TouchAction& a, TouchAction b) { return a = a & b; }
 
 enum EIsolation { IsolationAuto, IsolationIsolate };
 
 enum TouchActionDelay { TouchActionDelayNone, TouchActionDelayScript };
 
+enum ItemPosition {
+    ItemPositionAuto,
+    ItemPositionStretch,
+    ItemPositionBaseline,
+    ItemPositionCenter,
+    ItemPositionStart,
+    ItemPositionEnd,
+    ItemPositionSelfStart,
+    ItemPositionSelfEnd,
+    ItemPositionFlexStart,
+    ItemPositionFlexEnd,
+    ItemPositionLeft,
+    ItemPositionRight
+};
+
+enum OverflowAlignment {
+    OverflowAlignmentDefault,
+    OverflowAlignmentTrue,
+    OverflowAlignmentSafe
+};
+
 // Reasonable maximum to prevent insane font sizes from causing crashes on some platforms (such as Windows).
 static const float maximumAllowedFontSize = 1000000.0f;
 
 enum TextIndentLine { TextIndentFirstLine, TextIndentEachLine };
 
-enum LayoutBox { MarginBox, BorderBox, PaddingBox, ContentBox };
+enum LayoutBox { BoxMissing = 0, MarginBox, BorderBox, PaddingBox, ContentBox };
 
 } // namespace WebCore
 
diff --git a/Source/core/rendering/style/SVGRenderStyle.h b/Source/core/rendering/style/SVGRenderStyle.h
index dba333e..2f94d94 100644
--- a/Source/core/rendering/style/SVGRenderStyle.h
+++ b/Source/core/rendering/style/SVGRenderStyle.h
@@ -79,48 +79,48 @@
     static SVGPaint::SVGPaintType initialStrokePaintType() { return SVGPaint::SVG_PAINTTYPE_NONE; }
     static Color initialStrokePaintColor() { return Color(); }
     static String initialStrokePaintUri() { return String(); }
-    static Vector<SVGLength> initialStrokeDashArray() { return Vector<SVGLength>(); }
+    static PassRefPtr<SVGLengthList> initialStrokeDashArray() { return SVGLengthList::create(); }
     static float initialStrokeMiterLimit() { return 4; }
     static float initialStopOpacity() { return 1; }
     static Color initialStopColor() { return Color(0, 0, 0); }
     static float initialFloodOpacity() { return 1; }
     static Color initialFloodColor() { return Color(0, 0, 0); }
     static Color initialLightingColor() { return Color(255, 255, 255); }
-    static String initialClipperResource() { return String(); }
-    static String initialFilterResource() { return String(); }
-    static String initialMaskerResource() { return String(); }
+    static const AtomicString& initialClipperResource() { return nullAtom; }
+    static const AtomicString& initialFilterResource() { return nullAtom; }
+    static const AtomicString& initialMaskerResource() { return nullAtom; }
     static String initialMarkerStartResource() { return String(); }
     static String initialMarkerMidResource() { return String(); }
     static String initialMarkerEndResource() { return String(); }
     static EMaskType initialMaskType() { return MT_LUMINANCE; }
     static EPaintOrder initialPaintOrder() { return PO_NORMAL; }
 
-    static SVGLength initialBaselineShiftValue()
+    static PassRefPtr<SVGLength> initialBaselineShiftValue()
     {
-        SVGLength length;
-        length.newValueSpecifiedUnits(LengthTypeNumber, 0, ASSERT_NO_EXCEPTION);
-        return length;
+        RefPtr<SVGLength> length = SVGLength::create();
+        length->newValueSpecifiedUnits(LengthTypeNumber, 0);
+        return length.release();
     }
 
-    static SVGLength initialKerning()
+    static PassRefPtr<SVGLength> initialKerning()
     {
-        SVGLength length;
-        length.newValueSpecifiedUnits(LengthTypeNumber, 0, ASSERT_NO_EXCEPTION);
-        return length;
+        RefPtr<SVGLength> length = SVGLength::create();
+        length->newValueSpecifiedUnits(LengthTypeNumber, 0);
+        return length.release();
     }
 
-    static SVGLength initialStrokeDashOffset()
+    static PassRefPtr<SVGLength> initialStrokeDashOffset()
     {
-        SVGLength length;
-        length.newValueSpecifiedUnits(LengthTypeNumber, 0, ASSERT_NO_EXCEPTION);
-        return length;
+        RefPtr<SVGLength> length = SVGLength::create();
+        length->newValueSpecifiedUnits(LengthTypeNumber, 0);
+        return length.release();
     }
 
-    static SVGLength initialStrokeWidth()
+    static PassRefPtr<SVGLength> initialStrokeWidth()
     {
-        SVGLength length;
-        length.newValueSpecifiedUnits(LengthTypeNumber, 1, ASSERT_NO_EXCEPTION);
-        return length;
+        RefPtr<SVGLength> length = SVGLength::create();
+        length->newValueSpecifiedUnits(LengthTypeNumber, 1);
+        return length.release();
     }
 
     // SVG CSS Property setters
@@ -196,7 +196,7 @@
         }
     }
 
-    void setStrokeDashArray(const Vector<SVGLength>& obj)
+    void setStrokeDashArray(PassRefPtr<SVGLengthList> obj)
     {
         if (!(stroke->dashArray == obj))
             stroke.access()->dashArray = obj;
@@ -208,19 +208,19 @@
             stroke.access()->miterLimit = obj;
     }
 
-    void setStrokeWidth(const SVGLength& obj)
+    void setStrokeWidth(PassRefPtr<SVGLength> obj)
     {
         if (!(stroke->width == obj))
             stroke.access()->width = obj;
     }
 
-    void setStrokeDashOffset(const SVGLength& obj)
+    void setStrokeDashOffset(PassRefPtr<SVGLength> obj)
     {
         if (!(stroke->dashOffset == obj))
             stroke.access()->dashOffset = obj;
     }
 
-    void setKerning(const SVGLength& obj)
+    void setKerning(PassRefPtr<SVGLength> obj)
     {
         if (!(text->kerning == obj))
             text.access()->kerning = obj;
@@ -256,26 +256,26 @@
             misc.access()->lightingColor = obj;
     }
 
-    void setBaselineShiftValue(const SVGLength& obj)
+    void setBaselineShiftValue(PassRefPtr<SVGLength> obj)
     {
         if (!(misc->baselineShiftValue == obj))
             misc.access()->baselineShiftValue = obj;
     }
 
     // Setters for non-inherited resources
-    void setClipperResource(const String& obj)
+    void setClipperResource(const AtomicString& obj)
     {
         if (!(resources->clipper == obj))
             resources.access()->clipper = obj;
     }
 
-    void setFilterResource(const String& obj)
+    void setFilterResource(const AtomicString& obj)
     {
         if (!(resources->filter == obj))
             resources.access()->filter = obj;
     }
 
-    void setMaskerResource(const String& obj)
+    void setMaskerResource(const AtomicString& obj)
     {
         if (!(resources->masker == obj))
             resources.access()->masker = obj;
@@ -326,20 +326,20 @@
     const SVGPaint::SVGPaintType& strokePaintType() const { return stroke->paintType; }
     const Color& strokePaintColor() const { return stroke->paintColor; }
     const String& strokePaintUri() const { return stroke->paintUri; }
-    Vector<SVGLength> strokeDashArray() const { return stroke->dashArray; }
+    PassRefPtr<SVGLengthList> strokeDashArray() const { return stroke->dashArray; }
     float strokeMiterLimit() const { return stroke->miterLimit; }
-    SVGLength strokeWidth() const { return stroke->width; }
-    SVGLength strokeDashOffset() const { return stroke->dashOffset; }
-    SVGLength kerning() const { return text->kerning; }
+    PassRefPtr<SVGLength> strokeWidth() const { return stroke->width; }
+    PassRefPtr<SVGLength> strokeDashOffset() const { return stroke->dashOffset; }
+    PassRefPtr<SVGLength> kerning() const { return text->kerning; }
     float stopOpacity() const { return stops->opacity; }
     const Color& stopColor() const { return stops->color; }
     float floodOpacity() const { return misc->floodOpacity; }
     const Color& floodColor() const { return misc->floodColor; }
     const Color& lightingColor() const { return misc->lightingColor; }
-    SVGLength baselineShiftValue() const { return misc->baselineShiftValue; }
-    String clipperResource() const { return resources->clipper; }
-    String filterResource() const { return resources->filter; }
-    String maskerResource() const { return resources->masker; }
+    PassRefPtr<SVGLength> baselineShiftValue() const { return misc->baselineShiftValue; }
+    const AtomicString& clipperResource() const { return resources->clipper; }
+    const AtomicString& filterResource() const { return resources->filter; }
+    const AtomicString& maskerResource() const { return resources->masker; }
     String markerStartResource() const { return inheritedResources->markerStart; }
     String markerMidResource() const { return inheritedResources->markerMid; }
     String markerEndResource() const { return inheritedResources->markerEnd; }
@@ -360,7 +360,7 @@
     bool hasFilter() const { return !filterResource().isEmpty(); }
     bool hasMarkers() const { return !markerStartResource().isEmpty() || !markerMidResource().isEmpty() || !markerEndResource().isEmpty(); }
     bool hasStroke() const { return strokePaintType() != SVGPaint::SVG_PAINTTYPE_NONE; }
-    bool hasVisibleStroke() const { return hasStroke() && !strokeWidth().isZero(); }
+    bool hasVisibleStroke() const { return hasStroke() && !strokeWidth()->isZero(); }
     bool hasFill() const { return fillPaintType() != SVGPaint::SVG_PAINTTYPE_NONE; }
     bool isVerticalWritingMode() const { return writingMode() == WM_TBRL || writingMode() == WM_TB; }
 
diff --git a/Source/core/rendering/style/SVGRenderStyleDefs.cpp b/Source/core/rendering/style/SVGRenderStyleDefs.cpp
index 56e4a06..8202953 100644
--- a/Source/core/rendering/style/SVGRenderStyleDefs.cpp
+++ b/Source/core/rendering/style/SVGRenderStyleDefs.cpp
@@ -86,9 +86,9 @@
     : RefCounted<StyleStrokeData>()
     , opacity(other.opacity)
     , miterLimit(other.miterLimit)
-    , width(other.width)
-    , dashOffset(other.dashOffset)
-    , dashArray(other.dashArray)
+    , width(other.width->clone())
+    , dashOffset(other.dashOffset->clone())
+    , dashArray(other.dashArray->clone())
     , paintType(other.paintType)
     , paintColor(other.paintColor)
     , paintUri(other.paintUri)
@@ -100,11 +100,11 @@
 
 bool StyleStrokeData::operator==(const StyleStrokeData& other) const
 {
-    return width == other.width
+    return *width == *other.width
         && opacity == other.opacity
         && miterLimit == other.miterLimit
-        && dashOffset == other.dashOffset
-        && dashArray == other.dashArray
+        && *dashOffset == *other.dashOffset
+        && *dashArray == *other.dashArray
         && paintType == other.paintType
         && paintColor == other.paintColor
         && paintUri == other.paintUri
@@ -139,13 +139,13 @@
 
 StyleTextData::StyleTextData(const StyleTextData& other)
     : RefCounted<StyleTextData>()
-    , kerning(other.kerning)
+    , kerning(other.kerning->clone())
 {
 }
 
 bool StyleTextData::operator==(const StyleTextData& other) const
 {
-    return kerning == other.kerning;
+    return *kerning == *other.kerning;
 }
 
 StyleMiscData::StyleMiscData()
@@ -161,7 +161,7 @@
     , floodColor(other.floodColor)
     , floodOpacity(other.floodOpacity)
     , lightingColor(other.lightingColor)
-    , baselineShiftValue(other.baselineShiftValue)
+    , baselineShiftValue(other.baselineShiftValue->clone())
 {
 }
 
@@ -170,7 +170,7 @@
     return floodOpacity == other.floodOpacity
         && floodColor == other.floodColor
         && lightingColor == other.lightingColor
-        && baselineShiftValue == other.baselineShiftValue;
+        && *baselineShiftValue == *other.baselineShiftValue;
 }
 
 StyleResourceData::StyleResourceData()
diff --git a/Source/core/rendering/style/SVGRenderStyleDefs.h b/Source/core/rendering/style/SVGRenderStyleDefs.h
index 9b32f78..e25a8b2 100644
--- a/Source/core/rendering/style/SVGRenderStyleDefs.h
+++ b/Source/core/rendering/style/SVGRenderStyleDefs.h
@@ -29,6 +29,7 @@
 #define SVGRenderStyleDefs_h
 
 #include "core/svg/SVGLength.h"
+#include "core/svg/SVGLengthList.h"
 #include "core/svg/SVGPaint.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
@@ -146,9 +147,9 @@
         float opacity;
         float miterLimit;
 
-        SVGLength width;
-        SVGLength dashOffset;
-        Vector<SVGLength> dashArray;
+        RefPtr<SVGLength> width;
+        RefPtr<SVGLength> dashOffset;
+        RefPtr<SVGLengthList> dashArray;
 
         SVGPaint::SVGPaintType paintType;
         Color paintColor;
@@ -192,7 +193,7 @@
             return !(*this == other);
         }
 
-        SVGLength kerning;
+        RefPtr<SVGLength> kerning;
 
     private:
         StyleTextData();
@@ -216,7 +217,7 @@
         Color lightingColor;
 
         // non-inherited text stuff lives here not in StyleTextData.
-        SVGLength baselineShiftValue;
+        RefPtr<SVGLength> baselineShiftValue;
 
     private:
         StyleMiscData();
@@ -235,9 +236,9 @@
             return !(*this == other);
         }
 
-        String clipper;
-        String filter;
-        String masker;
+        AtomicString clipper;
+        AtomicString filter;
+        AtomicString masker;
 
     private:
         StyleResourceData();
diff --git a/Source/core/rendering/style/ShadowData.cpp b/Source/core/rendering/style/ShadowData.cpp
index 7f81d90..d89b03e 100644
--- a/Source/core/rendering/style/ShadowData.cpp
+++ b/Source/core/rendering/style/ShadowData.cpp
@@ -41,7 +41,7 @@
         return *this;
 
     return ShadowData(WebCore::blend(from.location(), location(), progress),
-        clampTo<int>(WebCore::blend(from.blur(), blur(), progress), 0),
+        clampTo(WebCore::blend(from.blur(), blur(), progress), 0.0f),
         WebCore::blend(from.spread(), spread(), progress),
         style(),
         WebCore::blend(from.color(), color(), progress));
diff --git a/Source/core/rendering/style/ShadowData.h b/Source/core/rendering/style/ShadowData.h
index 574b3f8..fa5a063 100644
--- a/Source/core/rendering/style/ShadowData.h
+++ b/Source/core/rendering/style/ShadowData.h
@@ -25,7 +25,7 @@
 #ifndef ShadowData_h
 #define ShadowData_h
 
-#include "platform/geometry/IntPoint.h"
+#include "platform/geometry/FloatPoint.h"
 #include "platform/graphics/Color.h"
 
 namespace WebCore {
@@ -36,7 +36,7 @@
 class ShadowData {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    ShadowData(const IntPoint& location, int blur, int spread, ShadowStyle style, const Color& color)
+    ShadowData(const FloatPoint& location, float blur, float spread, ShadowStyle style, const Color& color)
         : m_location(location)
         , m_blur(blur)
         , m_spread(spread)
@@ -50,18 +50,19 @@
 
     ShadowData blend(const ShadowData& from, double progress) const;
 
-    int x() const { return m_location.x(); }
-    int y() const { return m_location.y(); }
-    IntPoint location() const { return m_location; }
-    int blur() const { return m_blur; }
-    int spread() const { return m_spread; }
+    float x() const { return m_location.x(); }
+    float y() const { return m_location.y(); }
+    FloatPoint location() const { return m_location; }
+    float blur() const { return m_blur; }
+    float spread() const { return m_spread; }
     ShadowStyle style() const { return m_style; }
     const Color& color() const { return m_color; }
 
 private:
-    IntPoint m_location;
-    int m_blur;
-    int m_spread;
+    FloatPoint m_location;
+    float m_blur;
+    float m_spread;
+    // FIXME: We should use StyleColor here to allow currentColor to work correctly with visited links
     Color m_color;
     ShadowStyle m_style;
 };
diff --git a/Source/core/rendering/style/ShadowList.cpp b/Source/core/rendering/style/ShadowList.cpp
index 675effe..8874d24 100644
--- a/Source/core/rendering/style/ShadowList.cpp
+++ b/Source/core/rendering/style/ShadowList.cpp
@@ -32,11 +32,10 @@
 #include "core/rendering/style/ShadowList.h"
 
 #include "platform/geometry/FloatRect.h"
-#include "platform/geometry/LayoutRect.h"
 
 namespace WebCore {
 
-static inline void calculateShadowExtent(const ShadowList* shadowList, int additionalOutlineSize, int& shadowLeft, int& shadowRight, int& shadowTop, int& shadowBottom)
+static inline void calculateShadowExtent(const ShadowList* shadowList, float additionalOutlineSize, float& shadowLeft, float& shadowRight, float& shadowTop, float& shadowBottom)
 {
     ASSERT(shadowList);
     size_t shadowCount = shadowList->shadows().size();
@@ -44,7 +43,7 @@
         const ShadowData& shadow = shadowList->shadows()[i];
         if (shadow.style() == Inset)
             continue;
-        int blurAndSpread = shadow.blur() + shadow.spread() + additionalOutlineSize;
+        float blurAndSpread = shadow.blur() + shadow.spread() + additionalOutlineSize;
         shadowLeft = std::min(shadow.x() - blurAndSpread, shadowLeft);
         shadowRight = std::max(shadow.x() + blurAndSpread, shadowRight);
         shadowTop = std::min(shadow.y() - blurAndSpread, shadowTop);
@@ -52,25 +51,19 @@
     }
 }
 
-void ShadowList::adjustRectForShadow(LayoutRect& rect, int additionalOutlineSize) const
+void ShadowList::adjustRectForShadow(LayoutRect& rect, float additionalOutlineSize) const
 {
-    int shadowLeft = 0;
-    int shadowRight = 0;
-    int shadowTop = 0;
-    int shadowBottom = 0;
-    calculateShadowExtent(this, additionalOutlineSize, shadowLeft, shadowRight, shadowTop, shadowBottom);
-
-    rect.move(shadowLeft, shadowTop);
-    rect.setWidth(rect.width() - shadowLeft + shadowRight);
-    rect.setHeight(rect.height() - shadowTop + shadowBottom);
+    FloatRect floatRect(rect);
+    adjustRectForShadow(floatRect);
+    rect = LayoutRect(floatRect);
 }
 
-void ShadowList::adjustRectForShadow(FloatRect& rect, int additionalOutlineSize) const
+void ShadowList::adjustRectForShadow(FloatRect& rect, float additionalOutlineSize) const
 {
-    int shadowLeft = 0;
-    int shadowRight = 0;
-    int shadowTop = 0;
-    int shadowBottom = 0;
+    float shadowLeft = 0;
+    float shadowRight = 0;
+    float shadowTop = 0;
+    float shadowBottom = 0;
     calculateShadowExtent(this, additionalOutlineSize, shadowLeft, shadowRight, shadowTop, shadowBottom);
 
     rect.move(shadowLeft, shadowTop);
@@ -87,8 +80,8 @@
 
     ShadowDataVector shadows;
 
-    DEFINE_STATIC_LOCAL(ShadowData, defaultShadowData, (IntPoint(), 0, 0, Normal, Color::transparent));
-    DEFINE_STATIC_LOCAL(ShadowData, defaultInsetShadowData, (IntPoint(), 0, 0, Inset, Color::transparent));
+    DEFINE_STATIC_LOCAL(ShadowData, defaultShadowData, (FloatPoint(), 0, 0, Normal, Color::transparent));
+    DEFINE_STATIC_LOCAL(ShadowData, defaultInsetShadowData, (FloatPoint(), 0, 0, Inset, Color::transparent));
 
     size_t maxLength = std::max(fromLength, toLength);
     for (size_t i = 0; i < maxLength; ++i) {
diff --git a/Source/core/rendering/style/ShadowList.h b/Source/core/rendering/style/ShadowList.h
index 12acedf..6a1a4c1 100644
--- a/Source/core/rendering/style/ShadowList.h
+++ b/Source/core/rendering/style/ShadowList.h
@@ -32,6 +32,7 @@
 #define ShadowList_h
 
 #include "core/rendering/style/ShadowData.h"
+#include "platform/geometry/LayoutRect.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
@@ -57,8 +58,8 @@
 
     static PassRefPtr<ShadowList> blend(const ShadowList* from, const ShadowList* to, double progress);
 
-    void adjustRectForShadow(LayoutRect&, int additionalOutlineSize = 0) const;
-    void adjustRectForShadow(FloatRect&, int additionalOutlineSize = 0) const;
+    void adjustRectForShadow(LayoutRect&, float additionalOutlineSize = 0) const;
+    void adjustRectForShadow(FloatRect&, float additionalOutlineSize = 0) const;
 
 private:
     ShadowList(ShadowDataVector& shadows)
diff --git a/Source/core/rendering/style/ShapeValue.h b/Source/core/rendering/style/ShapeValue.h
index 6b87280..72c2cb9 100644
--- a/Source/core/rendering/style/ShapeValue.h
+++ b/Source/core/rendering/style/ShapeValue.h
@@ -82,18 +82,18 @@
     LayoutBox layoutBox() const { return m_layoutBox; }
     void setLayoutBox(LayoutBox layoutBox) { m_layoutBox = layoutBox; }
 
-    bool operator==(const ShapeValue& other) const { return type() == other.type(); }
+    bool operator==(const ShapeValue& other) const;
 
 private:
     ShapeValue(PassRefPtr<BasicShape> shape)
         : m_type(Shape)
         , m_shape(shape)
-        , m_layoutBox(ContentBox)
+        , m_layoutBox(m_shape->layoutBox())
     {
     }
     ShapeValue(ShapeValueType type)
         : m_type(type)
-        , m_layoutBox(ContentBox)
+        , m_layoutBox(BoxMissing)
     {
     }
     ShapeValue(PassRefPtr<StyleImage> image)
@@ -115,6 +115,26 @@
     LayoutBox m_layoutBox;
 };
 
+inline bool ShapeValue::operator==(const ShapeValue& other) const
+{
+    if (type() != other.type())
+        return false;
+
+    switch (type()) {
+    case Shape:
+        return shape() == other.shape() && layoutBox() == other.layoutBox();
+    case Box:
+        return layoutBox() == other.layoutBox();
+    case Outside:
+        return true;
+    case Image:
+        return image() == other.image();
+    }
+
+    ASSERT_NOT_REACHED();
+    return false;
+}
+
 }
 
 #endif
diff --git a/Source/core/rendering/style/StyleBackgroundData.h b/Source/core/rendering/style/StyleBackgroundData.h
index fda242f..b1ff806 100644
--- a/Source/core/rendering/style/StyleBackgroundData.h
+++ b/Source/core/rendering/style/StyleBackgroundData.h
@@ -46,7 +46,7 @@
     }
 
     const FillLayer& background() const { return m_background; }
-    const Color& color() const { return m_color; }
+    const StyleColor& color() const { return m_color; }
     const OutlineValue& outline() const { return m_outline; }
 
 private:
@@ -56,7 +56,7 @@
     StyleBackgroundData(const StyleBackgroundData&);
 
     FillLayer m_background;
-    Color m_color;
+    StyleColor m_color;
     OutlineValue m_outline;
 };
 
diff --git a/Source/core/rendering/style/StyleCustomFilterProgram.cpp b/Source/core/rendering/style/StyleCustomFilterProgram.cpp
deleted file mode 100644
index 31c3d64..0000000
--- a/Source/core/rendering/style/StyleCustomFilterProgram.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2013 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#include "config.h"
-
-#include "core/rendering/style/StyleCustomFilterProgram.h"
-
-#include "core/rendering/style/StyleCustomFilterProgramCache.h"
-
-namespace WebCore {
-
-StyleCustomFilterProgram::~StyleCustomFilterProgram()
-{
-    if (m_cache)
-        m_cache->remove(this);
-}
-
-} // namespace WebCore
-
-
diff --git a/Source/core/rendering/style/StyleCustomFilterProgram.h b/Source/core/rendering/style/StyleCustomFilterProgram.h
deleted file mode 100644
index d79cf63..0000000
--- a/Source/core/rendering/style/StyleCustomFilterProgram.h
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef StyleCustomFilterProgram_h
-#define StyleCustomFilterProgram_h
-
-#include "core/fetch/ResourceClient.h"
-#include "core/fetch/ResourcePtr.h"
-#include "core/fetch/ShaderResource.h"
-#include "core/rendering/style/StyleShader.h"
-#include "platform/graphics/filters/custom/CustomFilterProgram.h"
-#include "platform/weborigin/KURL.h"
-#include "wtf/FastAllocBase.h"
-
-namespace WebCore {
-
-// CSS Shaders
-
-class StyleCustomFilterProgramCache;
-
-class StyleCustomFilterProgram : public CustomFilterProgram, public ResourceClient {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    static PassRefPtr<StyleCustomFilterProgram> create(KURL vertexShaderURL, PassRefPtr<StyleShader> vertexShader,
-        KURL fragmentShaderURL, PassRefPtr<StyleShader> fragmentShader, CustomFilterProgramType programType,
-        const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType)
-    {
-        return adoptRef(new StyleCustomFilterProgram(vertexShaderURL, vertexShader, fragmentShaderURL, fragmentShader, programType, mixSettings, meshType));
-    }
-
-    void setVertexShader(PassRefPtr<StyleShader> shader)
-    {
-        // The shader is immutable while in the cache.
-        ASSERT(!m_cache);
-        m_vertexShader = shader;
-    }
-    StyleShader* vertexShader() const { return m_vertexShader.get(); }
-
-    void setFragmentShader(PassRefPtr<StyleShader> shader)
-    {
-        // The shader is immutable while in the cache.
-        ASSERT(!m_cache);
-        m_fragmentShader = shader;
-    }
-    StyleShader* fragmentShader() const { return m_fragmentShader.get(); }
-
-    virtual String vertexShaderString() const
-    {
-        ASSERT(isLoaded());
-        return m_cachedVertexShader.get() ? m_cachedVertexShader->shaderString() : String();
-    }
-
-    virtual String fragmentShaderString() const
-    {
-        ASSERT(isLoaded());
-        return m_cachedFragmentShader.get() ? m_cachedFragmentShader->shaderString() : String();
-    }
-
-    virtual bool isLoaded() const
-    {
-        // Do not use the Resource:isLoaded method here, because it actually means !isLoading(),
-        // so missing and canceled resources will have isLoaded set to true, even if they are not loaded yet.
-        ASSERT(!m_vertexShader || m_vertexShader->isShaderResource());
-        ASSERT(!m_fragmentShader || m_fragmentShader->isShaderResource());
-
-        // If we failed to create resources for the vertex shader or the
-        // fragment shader, they won't be set here.
-        // This can happen if the ResourceFetcher is no longer accepting fetch
-        // requests because the page is being torn down.
-        if (!m_vertexShader && !m_fragmentShader)
-            return false;
-
-        ASSERT(m_cachedVertexShader.get() || m_cachedFragmentShader.get());
-        return (!m_cachedVertexShader.get() || m_isVertexShaderLoaded)
-            && (!m_cachedFragmentShader.get() || m_isFragmentShaderLoaded);
-    }
-
-    virtual void willHaveClients()
-    {
-        if (m_vertexShader) {
-            m_cachedVertexShader = m_vertexShader->resource();
-            m_cachedVertexShader->addClient(this);
-        }
-        if (m_fragmentShader) {
-            m_cachedFragmentShader = m_fragmentShader->resource();
-            m_cachedFragmentShader->addClient(this);
-        }
-    }
-
-    virtual void didRemoveLastClient()
-    {
-        if (m_cachedVertexShader.get()) {
-            m_cachedVertexShader->removeClient(this);
-            m_cachedVertexShader = 0;
-            m_isVertexShaderLoaded = false;
-        }
-        if (m_cachedFragmentShader.get()) {
-            m_cachedFragmentShader->removeClient(this);
-            m_cachedFragmentShader = 0;
-            m_isFragmentShaderLoaded = false;
-        }
-    }
-
-    virtual void notifyFinished(Resource* resource)
-    {
-        if (resource->errorOccurred())
-            return;
-        // Note that m_cachedVertexShader might be equal to m_cachedFragmentShader and it would only get one event in that case.
-        if (resource == m_cachedVertexShader.get())
-            m_isVertexShaderLoaded = true;
-        if (resource == m_cachedFragmentShader.get())
-            m_isFragmentShaderLoaded = true;
-        if (isLoaded())
-            notifyClients();
-    }
-
-    bool hasPendingShaders() const
-    {
-        return (m_vertexShader && m_vertexShader->isPendingShader())
-            || (m_fragmentShader && m_fragmentShader->isPendingShader());
-    }
-
-    // StyleCustomFilterProgramCache is responsible with updating the reference to the cache.
-    void setCache(StyleCustomFilterProgramCache* cache) { m_cache = cache; }
-    bool inCache() const { return m_cache; }
-
-    KURL vertexShaderURL() const { return m_vertexShaderURL; }
-    KURL fragmentShaderURL() const { return m_fragmentShaderURL; }
-
-private:
-    StyleCustomFilterProgram(KURL vertexShaderURL, PassRefPtr<StyleShader> vertexShader, KURL fragmentShaderURL, PassRefPtr<StyleShader> fragmentShader,
-        CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType)
-        : CustomFilterProgram(programType, mixSettings, meshType)
-        , m_vertexShader(vertexShader)
-        , m_fragmentShader(fragmentShader)
-        , m_vertexShaderURL(vertexShaderURL)
-        , m_fragmentShaderURL(fragmentShaderURL)
-        , m_cache(0)
-        , m_isVertexShaderLoaded(false)
-        , m_isFragmentShaderLoaded(false)
-    {
-    }
-
-    ~StyleCustomFilterProgram();
-
-    RefPtr<StyleShader> m_vertexShader;
-    RefPtr<StyleShader> m_fragmentShader;
-
-    ResourcePtr<ShaderResource> m_cachedVertexShader;
-    ResourcePtr<ShaderResource> m_cachedFragmentShader;
-
-    // The URLs form the key of the StyleCustomFilterProgram in the cache and are used
-    // to lookup the StyleCustomFilterProgram when it's removed from the cache.
-    KURL m_vertexShaderURL;
-    KURL m_fragmentShaderURL;
-
-    // The Cache is responsible of invalidating this reference.
-    StyleCustomFilterProgramCache* m_cache;
-
-    bool m_isVertexShaderLoaded;
-    bool m_isFragmentShaderLoaded;
-};
-
-} // namespace WebCore
-
-
-#endif // StyleCustomFilterProgram_h
diff --git a/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp b/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
deleted file mode 100644
index 87d3aba..0000000
--- a/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2013 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#include "config.h"
-
-#include "core/rendering/style/StyleCustomFilterProgramCache.h"
-
-#include "core/rendering/style/StyleCustomFilterProgram.h"
-
-namespace WebCore {
-
-static CustomFilterProgramInfo programCacheKey(StyleCustomFilterProgram* program)
-{
-    ASSERT(program->vertexShaderURL().isValid() || program->fragmentShaderURL().isValid());
-    return CustomFilterProgramInfo(program->vertexShaderURL().string(), program->fragmentShaderURL().string(),
-        program->programType(), program->mixSettings(), program->meshType());
-}
-
-PassOwnPtr<StyleCustomFilterProgramCache> StyleCustomFilterProgramCache::create()
-{
-    return adoptPtr(new StyleCustomFilterProgramCache());
-}
-
-StyleCustomFilterProgramCache::~StyleCustomFilterProgramCache()
-{
-    // Make sure the programs are not calling back into this object.
-    for (CacheMap::iterator iter = m_cache.begin(), end = m_cache.end(); iter != end; ++iter)
-        iter->value->setCache(0);
-}
-
-StyleCustomFilterProgram* StyleCustomFilterProgramCache::lookup(const CustomFilterProgramInfo& programInfo) const
-{
-    CacheMap::const_iterator iter = m_cache.find(programInfo);
-    return iter != m_cache.end() ? iter->value : 0;
-}
-
-StyleCustomFilterProgram* StyleCustomFilterProgramCache::lookup(StyleCustomFilterProgram* program) const
-{
-    return lookup(programCacheKey(program));
-}
-
-void StyleCustomFilterProgramCache::add(StyleCustomFilterProgram* program)
-{
-    CustomFilterProgramInfo key = programCacheKey(program);
-    ASSERT(m_cache.find(key) == m_cache.end());
-    m_cache.set(key, program);
-    program->setCache(this);
-}
-
-void StyleCustomFilterProgramCache::remove(StyleCustomFilterProgram* program)
-{
-    CacheMap::iterator iter = m_cache.find(programCacheKey(program));
-    ASSERT_WITH_SECURITY_IMPLICATION(iter != m_cache.end());
-    m_cache.remove(iter);
-}
-
-
-} // namespace WebCore
-
-
diff --git a/Source/core/rendering/style/StyleCustomFilterProgramCache.h b/Source/core/rendering/style/StyleCustomFilterProgramCache.h
deleted file mode 100644
index 2bc1652..0000000
--- a/Source/core/rendering/style/StyleCustomFilterProgramCache.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2013 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef StyleCustomFilterProgramCache_h
-#define StyleCustomFilterProgramCache_h
-
-#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "wtf/FastAllocBase.h"
-#include "wtf/HashMap.h"
-
-namespace WebCore {
-
-class StyleCustomFilterProgram;
-class CustomFilterProgramInfo;
-
-class StyleCustomFilterProgramCache {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    static PassOwnPtr<StyleCustomFilterProgramCache> create();
-    ~StyleCustomFilterProgramCache();
-
-    // Lookups a StyleCustomFilterProgram that has similar parameters with the specified program.
-    StyleCustomFilterProgram* lookup(StyleCustomFilterProgram*) const;
-    StyleCustomFilterProgram* lookup(const CustomFilterProgramInfo&) const;
-
-    void add(StyleCustomFilterProgram*);
-    void remove(StyleCustomFilterProgram*);
-
-private:
-    StyleCustomFilterProgramCache() { }
-
-    typedef HashMap<CustomFilterProgramInfo, StyleCustomFilterProgram*> CacheMap;
-    CacheMap m_cache;
-};
-
-} // namespace WebCore
-
-
-#endif // StyleCustomFilterProgramCache_h
diff --git a/Source/core/rendering/style/StyleFetchedImage.h b/Source/core/rendering/style/StyleFetchedImage.h
index e783439..1a2e507 100644
--- a/Source/core/rendering/style/StyleFetchedImage.h
+++ b/Source/core/rendering/style/StyleFetchedImage.h
@@ -32,28 +32,28 @@
 
 class ImageResource;
 
-class StyleFetchedImage : public StyleImage, private ImageResourceClient {
+class StyleFetchedImage FINAL : public StyleImage, private ImageResourceClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassRefPtr<StyleFetchedImage> create(ImageResource* image) { return adoptRef(new StyleFetchedImage(image)); }
     virtual ~StyleFetchedImage();
 
-    virtual WrappedImagePtr data() const { return m_image.get(); }
+    virtual WrappedImagePtr data() const OVERRIDE { return m_image.get(); }
 
-    virtual PassRefPtr<CSSValue> cssValue() const;
+    virtual PassRefPtr<CSSValue> cssValue() const OVERRIDE;
 
-    virtual bool canRender(const RenderObject*, float multiplier) const;
-    virtual bool isLoaded() const;
-    virtual bool errorOccurred() const;
+    virtual bool canRender(const RenderObject*, float multiplier) const OVERRIDE;
+    virtual bool isLoaded() const OVERRIDE;
+    virtual bool errorOccurred() const OVERRIDE;
     virtual LayoutSize imageSize(const RenderObject*, float multiplier) const OVERRIDE;
-    virtual bool imageHasRelativeWidth() const;
-    virtual bool imageHasRelativeHeight() const;
-    virtual void computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio);
-    virtual bool usesImageContainerSize() const;
-    virtual void setContainerSizeForRenderer(const RenderObject*, const IntSize&, float);
-    virtual void addClient(RenderObject*);
-    virtual void removeClient(RenderObject*);
-    virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const;
+    virtual bool imageHasRelativeWidth() const OVERRIDE;
+    virtual bool imageHasRelativeHeight() const OVERRIDE;
+    virtual void computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio) OVERRIDE;
+    virtual bool usesImageContainerSize() const OVERRIDE;
+    virtual void setContainerSizeForRenderer(const RenderObject*, const IntSize&, float) OVERRIDE;
+    virtual void addClient(RenderObject*) OVERRIDE;
+    virtual void removeClient(RenderObject*) OVERRIDE;
+    virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const OVERRIDE;
     virtual bool knownToBeOpaque(const RenderObject*) const OVERRIDE;
     virtual ImageResource* cachedImage() const OVERRIDE { return m_image.get(); }
 
diff --git a/Source/core/rendering/style/StyleFetchedImageSet.h b/Source/core/rendering/style/StyleFetchedImageSet.h
index 873c142..3f137ab 100644
--- a/Source/core/rendering/style/StyleFetchedImageSet.h
+++ b/Source/core/rendering/style/StyleFetchedImageSet.h
@@ -38,7 +38,7 @@
 
 // This class keeps one cached image and has access to a set of alternatives.
 
-class StyleFetchedImageSet : public StyleImage, private ImageResourceClient {
+class StyleFetchedImageSet FINAL : public StyleImage, private ImageResourceClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassRefPtr<StyleFetchedImageSet> create(ImageResource* image, float imageScaleFactor, CSSImageSetValue* value)
@@ -47,28 +47,28 @@
     }
     virtual ~StyleFetchedImageSet();
 
-    virtual PassRefPtr<CSSValue> cssValue() const;
+    virtual PassRefPtr<CSSValue> cssValue() const OVERRIDE;
 
     // FIXME: This is used by StyleImage for equals comparison, but this implementation
     // only looks at the image from the set that we have loaded. I'm not sure if that is
     // meaningful enough or not.
-    virtual WrappedImagePtr data() const { return m_bestFitImage.get(); }
+    virtual WrappedImagePtr data() const OVERRIDE { return m_bestFitImage.get(); }
 
     void clearImageSetValue() { m_imageSetValue = 0; }
 
-    virtual bool canRender(const RenderObject*, float multiplier) const;
-    virtual bool isLoaded() const;
-    virtual bool errorOccurred() const;
-    virtual LayoutSize imageSize(const RenderObject*, float multiplier) const;
-    virtual bool imageHasRelativeWidth() const;
-    virtual bool imageHasRelativeHeight() const;
-    virtual void computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio);
-    virtual bool usesImageContainerSize() const;
-    virtual void setContainerSizeForRenderer(const RenderObject*, const IntSize&, float);
-    virtual void addClient(RenderObject*);
-    virtual void removeClient(RenderObject*);
-    virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const;
-    virtual float imageScaleFactor() const { return m_imageScaleFactor; }
+    virtual bool canRender(const RenderObject*, float multiplier) const OVERRIDE;
+    virtual bool isLoaded() const OVERRIDE;
+    virtual bool errorOccurred() const OVERRIDE;
+    virtual LayoutSize imageSize(const RenderObject*, float multiplier) const OVERRIDE;
+    virtual bool imageHasRelativeWidth() const OVERRIDE;
+    virtual bool imageHasRelativeHeight() const OVERRIDE;
+    virtual void computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio) OVERRIDE;
+    virtual bool usesImageContainerSize() const OVERRIDE;
+    virtual void setContainerSizeForRenderer(const RenderObject*, const IntSize&, float) OVERRIDE;
+    virtual void addClient(RenderObject*) OVERRIDE;
+    virtual void removeClient(RenderObject*) OVERRIDE;
+    virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const OVERRIDE;
+    virtual float imageScaleFactor() const OVERRIDE { return m_imageScaleFactor; }
     virtual bool knownToBeOpaque(const RenderObject*) const OVERRIDE;
     virtual ImageResource* cachedImage() const OVERRIDE { return m_bestFitImage.get(); }
 
@@ -77,6 +77,11 @@
 
     ResourcePtr<ImageResource> m_bestFitImage;
     float m_imageScaleFactor;
+
+    // FIXME: oilpan: Change to RawPtrWillBeMember when moving this class onto oilpan heap.
+    // Also add "if !ENABLE(OILPAN)" around clearImageSetValue above as well as around its
+    // caller since it should not be needed once both of the objects are on the heap and
+    // oilpan is enabled.
     CSSImageSetValue* m_imageSetValue; // Not retained; it owns us.
 };
 
diff --git a/Source/core/rendering/style/StyleFetchedShader.cpp b/Source/core/rendering/style/StyleFetchedShader.cpp
deleted file mode 100644
index 13a8b98..0000000
--- a/Source/core/rendering/style/StyleFetchedShader.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#include "config.h"
-
-#include "core/rendering/style/StyleFetchedShader.h"
-
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/fetch/ShaderResource.h"
-
-namespace WebCore {
-
-
-StyleFetchedShader::StyleFetchedShader(ShaderResource* shader)
-    : m_shader(shader)
-{
-    m_isShaderResource = true;
-}
-
-PassRefPtr<CSSValue> StyleFetchedShader::cssValue() const
-{
-    return CSSPrimitiveValue::create(m_shader->url().string(), CSSPrimitiveValue::CSS_URI);
-}
-
-} // namespace WebCore
-
-
diff --git a/Source/core/rendering/style/StyleFetchedShader.h b/Source/core/rendering/style/StyleFetchedShader.h
deleted file mode 100644
index 104a90c..0000000
--- a/Source/core/rendering/style/StyleFetchedShader.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef StyleFetchedShader_h
-#define StyleFetchedShader_h
-
-#include "core/fetch/ResourcePtr.h"
-#include "core/rendering/style/StyleShader.h"
-
-namespace WebCore {
-
-class ShaderResource;
-
-class StyleFetchedShader : public StyleShader {
-public:
-    // FIXME: Keep a reference to the actual ShaderResource in this class.
-    static PassRefPtr<StyleFetchedShader> create(ShaderResource* shader) { return adoptRef(new StyleFetchedShader(shader)); }
-
-    virtual PassRefPtr<CSSValue> cssValue() const;
-
-    virtual ShaderResource* resource() const { return m_shader.get(); }
-
-private:
-    StyleFetchedShader(ShaderResource*);
-
-    ResourcePtr<ShaderResource> m_shader;
-};
-
-}
-
-#endif // StyleFetchedShader_h
diff --git a/Source/core/rendering/style/StyleGeneratedImage.cpp b/Source/core/rendering/style/StyleGeneratedImage.cpp
index 2ec1c87..6a50c14 100644
--- a/Source/core/rendering/style/StyleGeneratedImage.cpp
+++ b/Source/core/rendering/style/StyleGeneratedImage.cpp
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-StyleGeneratedImage::StyleGeneratedImage(PassRefPtr<CSSImageGeneratorValue> value)
+StyleGeneratedImage::StyleGeneratedImage(PassRefPtrWillBeRawPtr<CSSImageGeneratorValue> value)
     : m_imageGeneratorValue(value)
     , m_fixedSize(m_imageGeneratorValue->isFixedSize())
 {
@@ -39,7 +39,7 @@
 
 PassRefPtr<CSSValue> StyleGeneratedImage::cssValue() const
 {
-    return m_imageGeneratorValue;
+    return m_imageGeneratorValue.get();
 }
 
 LayoutSize StyleGeneratedImage::imageSize(const RenderObject* renderer, float multiplier) const
diff --git a/Source/core/rendering/style/StyleGeneratedImage.h b/Source/core/rendering/style/StyleGeneratedImage.h
index bf93af4..69c3f9b 100644
--- a/Source/core/rendering/style/StyleGeneratedImage.h
+++ b/Source/core/rendering/style/StyleGeneratedImage.h
@@ -31,32 +31,33 @@
 class CSSValue;
 class CSSImageGeneratorValue;
 
-class StyleGeneratedImage : public StyleImage {
+class StyleGeneratedImage FINAL : public StyleImage {
 public:
     static PassRefPtr<StyleGeneratedImage> create(CSSImageGeneratorValue* value)
     {
         return adoptRef(new StyleGeneratedImage(value));
     }
 
-    virtual WrappedImagePtr data() const { return m_imageGeneratorValue.get(); }
+    virtual WrappedImagePtr data() const OVERRIDE { return m_imageGeneratorValue.get(); }
 
-    virtual PassRefPtr<CSSValue> cssValue() const;
+    virtual PassRefPtr<CSSValue> cssValue() const OVERRIDE;
 
     virtual LayoutSize imageSize(const RenderObject*, float multiplier) const OVERRIDE;
-    virtual bool imageHasRelativeWidth() const { return !m_fixedSize; }
-    virtual bool imageHasRelativeHeight() const { return !m_fixedSize; }
-    virtual void computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio);
-    virtual bool usesImageContainerSize() const { return !m_fixedSize; }
-    virtual void setContainerSizeForRenderer(const RenderObject*, const IntSize& containerSize, float) { m_containerSize = containerSize; }
-    virtual void addClient(RenderObject*);
-    virtual void removeClient(RenderObject*);
-    virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const;
+    virtual bool imageHasRelativeWidth() const OVERRIDE { return !m_fixedSize; }
+    virtual bool imageHasRelativeHeight() const OVERRIDE { return !m_fixedSize; }
+    virtual void computeIntrinsicDimensions(const RenderObject*, Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio) OVERRIDE;
+    virtual bool usesImageContainerSize() const OVERRIDE { return !m_fixedSize; }
+    virtual void setContainerSizeForRenderer(const RenderObject*, const IntSize& containerSize, float) OVERRIDE { m_containerSize = containerSize; }
+    virtual void addClient(RenderObject*) OVERRIDE;
+    virtual void removeClient(RenderObject*) OVERRIDE;
+    virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const OVERRIDE;
     virtual bool knownToBeOpaque(const RenderObject*) const OVERRIDE;
 
 private:
-    StyleGeneratedImage(PassRefPtr<CSSImageGeneratorValue>);
+    StyleGeneratedImage(PassRefPtrWillBeRawPtr<CSSImageGeneratorValue>);
 
-    RefPtr<CSSImageGeneratorValue> m_imageGeneratorValue;
+    // FIXME: oilpan: change to member once StyleImage is moved to the oilpan heap
+    RefPtrWillBePersistent<CSSImageGeneratorValue> m_imageGeneratorValue;
     IntSize m_containerSize;
     bool m_fixedSize;
 };
diff --git a/Source/core/rendering/style/StyleGridData.cpp b/Source/core/rendering/style/StyleGridData.cpp
index a3f8a34..d323864 100644
--- a/Source/core/rendering/style/StyleGridData.cpp
+++ b/Source/core/rendering/style/StyleGridData.cpp
@@ -31,8 +31,8 @@
 namespace WebCore {
 
 StyleGridData::StyleGridData()
-    : m_gridDefinitionColumns(RenderStyle::initialGridDefinitionColumns())
-    , m_gridDefinitionRows(RenderStyle::initialGridDefinitionRows())
+    : m_gridTemplateColumns(RenderStyle::initialGridTemplateColumns())
+    , m_gridTemplateRows(RenderStyle::initialGridTemplateRows())
     , m_namedGridColumnLines(RenderStyle::initialNamedGridColumnLines())
     , m_namedGridRowLines(RenderStyle::initialNamedGridRowLines())
     , m_orderedNamedGridColumnLines(RenderStyle::initialOrderedNamedGridColumnLines())
@@ -48,8 +48,8 @@
 
 StyleGridData::StyleGridData(const StyleGridData& o)
     : RefCounted<StyleGridData>()
-    , m_gridDefinitionColumns(o.m_gridDefinitionColumns)
-    , m_gridDefinitionRows(o.m_gridDefinitionRows)
+    , m_gridTemplateColumns(o.m_gridTemplateColumns)
+    , m_gridTemplateRows(o.m_gridTemplateRows)
     , m_namedGridColumnLines(o.m_namedGridColumnLines)
     , m_namedGridRowLines(o.m_namedGridRowLines)
     , m_orderedNamedGridColumnLines(o.m_orderedNamedGridColumnLines)
diff --git a/Source/core/rendering/style/StyleGridData.h b/Source/core/rendering/style/StyleGridData.h
index c7f5e54..da14eaa 100644
--- a/Source/core/rendering/style/StyleGridData.h
+++ b/Source/core/rendering/style/StyleGridData.h
@@ -46,7 +46,7 @@
 
     bool operator==(const StyleGridData& o) const
     {
-        return m_gridDefinitionColumns == o.m_gridDefinitionColumns && m_gridDefinitionRows == o.m_gridDefinitionRows && m_gridAutoFlow == o.m_gridAutoFlow && m_gridAutoRows == o.m_gridAutoRows && m_gridAutoColumns == o.m_gridAutoColumns && m_namedGridColumnLines == o.m_namedGridColumnLines && m_namedGridRowLines == o.m_namedGridRowLines && m_orderedNamedGridColumnLines == o.m_orderedNamedGridColumnLines && m_orderedNamedGridRowLines == o.m_orderedNamedGridRowLines && m_namedGridArea == o.m_namedGridArea && m_namedGridArea == o.m_namedGridArea && m_namedGridAreaRowCount == o.m_namedGridAreaRowCount && m_namedGridAreaColumnCount == o.m_namedGridAreaColumnCount;
+        return m_gridTemplateColumns == o.m_gridTemplateColumns && m_gridTemplateRows == o.m_gridTemplateRows && m_gridAutoFlow == o.m_gridAutoFlow && m_gridAutoRows == o.m_gridAutoRows && m_gridAutoColumns == o.m_gridAutoColumns && m_namedGridColumnLines == o.m_namedGridColumnLines && m_namedGridRowLines == o.m_namedGridRowLines && m_orderedNamedGridColumnLines == o.m_orderedNamedGridColumnLines && m_orderedNamedGridRowLines == o.m_orderedNamedGridRowLines && m_namedGridArea == o.m_namedGridArea && m_namedGridArea == o.m_namedGridArea && m_namedGridAreaRowCount == o.m_namedGridAreaRowCount && m_namedGridAreaColumnCount == o.m_namedGridAreaColumnCount;
     }
 
     bool operator!=(const StyleGridData& o) const
@@ -54,8 +54,8 @@
         return !(*this == o);
     }
 
-    Vector<GridTrackSize> m_gridDefinitionColumns;
-    Vector<GridTrackSize> m_gridDefinitionRows;
+    Vector<GridTrackSize> m_gridTemplateColumns;
+    Vector<GridTrackSize> m_gridTemplateRows;
 
     NamedGridLinesMap m_namedGridColumnLines;
     NamedGridLinesMap m_namedGridRowLines;
diff --git a/Source/core/rendering/style/StyleMultiColData.cpp b/Source/core/rendering/style/StyleMultiColData.cpp
index 90897bb..29757d7 100644
--- a/Source/core/rendering/style/StyleMultiColData.cpp
+++ b/Source/core/rendering/style/StyleMultiColData.cpp
@@ -30,6 +30,7 @@
     : m_width(0)
     , m_count(RenderStyle::initialColumnCount())
     , m_gap(0)
+    , m_visitedLinkColumnRuleColor(StyleColor::currentColor())
     , m_autoWidth(true)
     , m_autoCount(true)
     , m_normalGap(true)
diff --git a/Source/core/rendering/style/StyleMultiColData.h b/Source/core/rendering/style/StyleMultiColData.h
index fcf6680..1864548 100644
--- a/Source/core/rendering/style/StyleMultiColData.h
+++ b/Source/core/rendering/style/StyleMultiColData.h
@@ -57,7 +57,7 @@
     unsigned short m_count;
     float m_gap;
     BorderValue m_rule;
-    Color m_visitedLinkColumnRuleColor;
+    StyleColor m_visitedLinkColumnRuleColor;
 
     bool m_autoWidth : 1;
     bool m_autoCount : 1;
diff --git a/Source/core/rendering/style/StylePendingImage.h b/Source/core/rendering/style/StylePendingImage.h
index 4589f59..a52481d 100644
--- a/Source/core/rendering/style/StylePendingImage.h
+++ b/Source/core/rendering/style/StylePendingImage.h
@@ -39,32 +39,32 @@
 // style resolution, in order to avoid loading images that are not referenced by the final style.
 // They should never exist in a RenderStyle after it has been returned from the style selector.
 
-class StylePendingImage : public StyleImage {
+class StylePendingImage FINAL : public StyleImage {
 public:
     static PassRefPtr<StylePendingImage> create(CSSValue* value) { return adoptRef(new StylePendingImage(value)); }
 
-    virtual WrappedImagePtr data() const { return m_value; }
+    virtual WrappedImagePtr data() const OVERRIDE { return m_value; }
 
-    virtual PassRefPtr<CSSValue> cssValue() const { return m_value; }
+    virtual PassRefPtr<CSSValue> cssValue() const OVERRIDE { return m_value; }
     CSSImageValue* cssImageValue() const { return m_value->isImageValue() ? toCSSImageValue(m_value) : 0; }
     CSSImageGeneratorValue* cssImageGeneratorValue() const { return m_value->isImageGeneratorValue() ? toCSSImageGeneratorValue(m_value) : 0; }
     CSSCursorImageValue* cssCursorImageValue() const { return m_value->isCursorImageValue() ? toCSSCursorImageValue(m_value) : 0; }
     CSSImageSetValue* cssImageSetValue() const { return m_value->isImageSetValue() ? toCSSImageSetValue(m_value) : 0; }
 
     virtual LayoutSize imageSize(const RenderObject*, float /*multiplier*/) const OVERRIDE { return LayoutSize(); }
-    virtual bool imageHasRelativeWidth() const { return false; }
-    virtual bool imageHasRelativeHeight() const { return false; }
-    virtual void computeIntrinsicDimensions(const RenderObject*, Length& /* intrinsicWidth */ , Length& /* intrinsicHeight */, FloatSize& /* intrinsicRatio */) { }
-    virtual bool usesImageContainerSize() const { return false; }
-    virtual void setContainerSizeForRenderer(const RenderObject*, const IntSize&, float) { }
-    virtual void addClient(RenderObject*) { }
-    virtual void removeClient(RenderObject*) { }
-    virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const
+    virtual bool imageHasRelativeWidth() const OVERRIDE { return false; }
+    virtual bool imageHasRelativeHeight() const OVERRIDE { return false; }
+    virtual void computeIntrinsicDimensions(const RenderObject*, Length& /* intrinsicWidth */ , Length& /* intrinsicHeight */, FloatSize& /* intrinsicRatio */) OVERRIDE { }
+    virtual bool usesImageContainerSize() const OVERRIDE { return false; }
+    virtual void setContainerSizeForRenderer(const RenderObject*, const IntSize&, float) OVERRIDE { }
+    virtual void addClient(RenderObject*) OVERRIDE { }
+    virtual void removeClient(RenderObject*) OVERRIDE { }
+    virtual PassRefPtr<Image> image(RenderObject*, const IntSize&) const OVERRIDE
     {
         ASSERT_NOT_REACHED();
         return 0;
     }
-    virtual bool knownToBeOpaque(const RenderObject*) const { return false; }
+    virtual bool knownToBeOpaque(const RenderObject*) const OVERRIDE { return false; }
 
 private:
     StylePendingImage(CSSValue* value)
diff --git a/Source/core/rendering/style/StylePendingShader.h b/Source/core/rendering/style/StylePendingShader.h
deleted file mode 100644
index 1158e33..0000000
--- a/Source/core/rendering/style/StylePendingShader.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef StylePendingShader_h
-#define StylePendingShader_h
-
-#include "core/css/CSSShaderValue.h"
-#include "core/css/CSSValue.h"
-#include "core/rendering/style/StyleShader.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-class WebKitCSSShaderValue;
-
-class StylePendingShader : public StyleShader {
-public:
-    static PassRefPtr<StylePendingShader> create(CSSShaderValue* value) { return adoptRef(new StylePendingShader(value)); }
-
-    virtual PassRefPtr<CSSValue> cssValue() const { return m_value; }
-    CSSShaderValue* cssShaderValue() const { return m_value; }
-private:
-    StylePendingShader(CSSShaderValue* value)
-        : m_value(value)
-    {
-         m_isPendingShader = true;
-    }
-
-    CSSShaderValue* m_value; // Not retained; it owns us.
-};
-
-}
-
-#endif // StylePendingShader_h
diff --git a/Source/core/rendering/style/StyleRareInheritedData.cpp b/Source/core/rendering/style/StyleRareInheritedData.cpp
index 1a1769c..3a62854 100644
--- a/Source/core/rendering/style/StyleRareInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareInheritedData.cpp
@@ -33,11 +33,11 @@
 
 struct SameSizeAsStyleRareInheritedData : public RefCounted<SameSizeAsStyleRareInheritedData> {
     void* styleImage;
-    Color firstColor;
+    StyleColor firstColor;
     float firstFloat;
-    Color colors[5];
+    StyleColor colors[5];
     void* ownPtrs[1];
-    AtomicString atomicStrings[5];
+    AtomicString atomicStrings[4];
     void* refPtrs[2];
     Length lengths[1];
     float secondFloat;
@@ -47,15 +47,19 @@
     short hyphenationShorts[3];
 
     Color touchColors;
-
-    void* variableDataRefs[1];
 };
 
 COMPILE_ASSERT(sizeof(StyleRareInheritedData) == sizeof(SameSizeAsStyleRareInheritedData), StyleRareInheritedData_should_bit_pack);
 
 StyleRareInheritedData::StyleRareInheritedData()
     : listStyleImage(RenderStyle::initialListStyleImage())
+    , textStrokeColor(StyleColor::currentColor())
     , textStrokeWidth(RenderStyle::initialTextStrokeWidth())
+    , textFillColor(StyleColor::currentColor())
+    , textEmphasisColor(StyleColor::currentColor())
+    , visitedLinkTextStrokeColor(StyleColor::currentColor())
+    , visitedLinkTextFillColor(StyleColor::currentColor())
+    , visitedLinkTextEmphasisColor(StyleColor::currentColor())
     , indent(RenderStyle::initialTextIndent())
     , m_effectiveZoom(RenderStyle::initialZoom())
     , widows(RenderStyle::initialWidows())
@@ -80,19 +84,15 @@
     , m_textIndentLine(RenderStyle::initialTextIndentLine())
     , m_lineBoxContain(RenderStyle::initialLineBoxContain())
     , m_imageRendering(RenderStyle::initialImageRendering())
-    , m_lineSnap(RenderStyle::initialLineSnap())
-    , m_lineAlign(RenderStyle::initialLineAlign())
     , m_textUnderlinePosition(RenderStyle::initialTextUnderlinePosition())
     , m_rubyPosition(RenderStyle::initialRubyPosition())
     , m_touchActionDelay(RenderStyle::initialTouchActionDelay())
     , hyphenationLimitBefore(-1)
     , hyphenationLimitAfter(-1)
     , hyphenationLimitLines(-1)
-    , m_lineGrid(RenderStyle::initialLineGrid())
     , m_tabSize(RenderStyle::initialTabSize())
     , tapHighlightColor(RenderStyle::initialTapHighlightColor())
 {
-    m_variables.init();
 }
 
 StyleRareInheritedData::StyleRareInheritedData(const StyleRareInheritedData& o)
@@ -132,8 +132,6 @@
     , m_textIndentLine(o.m_textIndentLine)
     , m_lineBoxContain(o.m_lineBoxContain)
     , m_imageRendering(o.m_imageRendering)
-    , m_lineSnap(o.m_lineSnap)
-    , m_lineAlign(o.m_lineAlign)
     , m_textUnderlinePosition(o.m_textUnderlinePosition)
     , m_rubyPosition(o.m_rubyPosition)
     , m_touchActionDelay(o.m_touchActionDelay)
@@ -143,10 +141,8 @@
     , hyphenationLimitLines(o.hyphenationLimitLines)
     , locale(o.locale)
     , textEmphasisCustomMark(o.textEmphasisCustomMark)
-    , m_lineGrid(o.m_lineGrid)
     , m_tabSize(o.m_tabSize)
     , tapHighlightColor(o.tapHighlightColor)
-    , m_variables(o.m_variables)
 {
 }
 
@@ -208,13 +204,9 @@
         && textEmphasisCustomMark == o.textEmphasisCustomMark
         && QuotesData::equals(quotes.get(), o.quotes.get())
         && m_tabSize == o.m_tabSize
-        && m_lineGrid == o.m_lineGrid
         && m_imageRendering == o.m_imageRendering
         && m_textUnderlinePosition == o.m_textUnderlinePosition
         && m_rubyPosition == o.m_rubyPosition
-        && m_lineSnap == o.m_lineSnap
-        && m_variables == o.m_variables
-        && m_lineAlign == o.m_lineAlign
         && StyleImage::imagesEquivalent(listStyleImage.get(), o.listStyleImage.get());
 }
 
diff --git a/Source/core/rendering/style/StyleRareInheritedData.h b/Source/core/rendering/style/StyleRareInheritedData.h
index 11d3c4b..b4d080e 100644
--- a/Source/core/rendering/style/StyleRareInheritedData.h
+++ b/Source/core/rendering/style/StyleRareInheritedData.h
@@ -25,8 +25,8 @@
 #ifndef StyleRareInheritedData_h
 #define StyleRareInheritedData_h
 
+#include "core/css/StyleColor.h"
 #include "core/rendering/style/DataRef.h"
-#include "core/rendering/style/StyleVariableData.h"
 #include "platform/Length.h"
 #include "platform/graphics/Color.h"
 #include "wtf/PassRefPtr.h"
@@ -58,14 +58,14 @@
 
     RefPtr<StyleImage> listStyleImage;
 
-    Color textStrokeColor;
+    StyleColor textStrokeColor;
     float textStrokeWidth;
-    Color textFillColor;
-    Color textEmphasisColor;
+    StyleColor textFillColor;
+    StyleColor textEmphasisColor;
 
-    Color visitedLinkTextStrokeColor;
-    Color visitedLinkTextFillColor;
-    Color visitedLinkTextEmphasisColor;
+    StyleColor visitedLinkTextStrokeColor;
+    StyleColor visitedLinkTextFillColor;
+    StyleColor visitedLinkTextEmphasisColor;
 
     RefPtr<ShadowList> textShadow; // Our text shadow information for shadowed text drawing.
     AtomicString highlight; // Apple-specific extension for custom highlight rendering.
@@ -99,8 +99,6 @@
     unsigned m_lineBoxContain: 7; // LineBoxContain
     // CSS Image Values Level 3
     unsigned m_imageRendering : 2; // EImageRendering
-    unsigned m_lineSnap : 2; // LineSnap
-    unsigned m_lineAlign : 1; // LineAlign
     unsigned m_textUnderlinePosition : 2; // TextUnderlinePosition
     unsigned m_rubyPosition : 1; // RubyPosition
     unsigned m_touchActionDelay : 1; // TouchActionDelay
@@ -115,13 +113,10 @@
     AtomicString textEmphasisCustomMark;
     RefPtr<QuotesData> quotes;
 
-    AtomicString m_lineGrid;
     unsigned m_tabSize;
 
     Color tapHighlightColor;
 
-    DataRef<StyleVariableData> m_variables;
-
 private:
     StyleRareInheritedData();
     StyleRareInheritedData(const StyleRareInheritedData&);
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.cpp b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
index 2d31278..820c3dc 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
@@ -48,21 +48,24 @@
     , m_shapePadding(RenderStyle::initialShapePadding())
     , m_shapeImageThreshold(RenderStyle::initialShapeImageThreshold())
     , m_clipPath(RenderStyle::initialClipPath())
+    , m_textDecorationColor(StyleColor::currentColor())
+    , m_visitedLinkTextDecorationColor(StyleColor::currentColor())
     , m_visitedLinkBackgroundColor(RenderStyle::initialBackgroundColor())
+    , m_visitedLinkOutlineColor(StyleColor::currentColor())
+    , m_visitedLinkBorderLeftColor(StyleColor::currentColor())
+    , m_visitedLinkBorderRightColor(StyleColor::currentColor())
+    , m_visitedLinkBorderTopColor(StyleColor::currentColor())
+    , m_visitedLinkBorderBottomColor(StyleColor::currentColor())
     , m_order(RenderStyle::initialOrder())
     , m_objectPosition(RenderStyle::initialObjectPosition())
-    , m_flowThread(RenderStyle::initialFlowThread())
-    , m_regionThread(RenderStyle::initialRegionThread())
-    , m_regionFragment(RenderStyle::initialRegionFragment())
-    , m_regionBreakAfter(RenderStyle::initialPageBreak())
-    , m_regionBreakBefore(RenderStyle::initialPageBreak())
-    , m_regionBreakInside(RenderStyle::initialPageBreak())
     , m_pageSizeType(PAGE_SIZE_AUTO)
     , m_transformStyle3D(RenderStyle::initialTransformStyle3D())
     , m_backfaceVisibility(RenderStyle::initialBackfaceVisibility())
     , m_alignContent(RenderStyle::initialAlignContent())
     , m_alignItems(RenderStyle::initialAlignItems())
+    , m_alignItemsOverflowAlignment(RenderStyle::initialAlignItemsOverflowAlignment())
     , m_alignSelf(RenderStyle::initialAlignSelf())
+    , m_alignSelfOverflowAlignment(RenderStyle::initialAlignSelfOverflowAlignment())
     , m_justifyContent(RenderStyle::initialJustifyContent())
     , userDrag(RenderStyle::initialUserDrag())
     , textOverflow(RenderStyle::initialTextOverflow())
@@ -80,6 +83,9 @@
     , m_touchAction(RenderStyle::initialTouchAction())
     , m_objectFit(RenderStyle::initialObjectFit())
     , m_isolation(RenderStyle::initialIsolation())
+    , m_justifySelf(RenderStyle::initialJustifySelf())
+    , m_justifySelfOverflowAlignment(RenderStyle::initialJustifySelfOverflowAlignment())
+    , m_scrollBehavior(RenderStyle::initialScrollBehavior())
 {
     m_maskBoxImage.setMaskDefaults();
 }
@@ -127,18 +133,14 @@
     , m_visitedLinkBorderBottomColor(o.m_visitedLinkBorderBottomColor)
     , m_order(o.m_order)
     , m_objectPosition(o.m_objectPosition)
-    , m_flowThread(o.m_flowThread)
-    , m_regionThread(o.m_regionThread)
-    , m_regionFragment(o.m_regionFragment)
-    , m_regionBreakAfter(o.m_regionBreakAfter)
-    , m_regionBreakBefore(o.m_regionBreakBefore)
-    , m_regionBreakInside(o.m_regionBreakInside)
     , m_pageSizeType(o.m_pageSizeType)
     , m_transformStyle3D(o.m_transformStyle3D)
     , m_backfaceVisibility(o.m_backfaceVisibility)
     , m_alignContent(o.m_alignContent)
     , m_alignItems(o.m_alignItems)
+    , m_alignItemsOverflowAlignment(o.m_alignItemsOverflowAlignment)
     , m_alignSelf(o.m_alignSelf)
+    , m_alignSelfOverflowAlignment(o.m_alignSelfOverflowAlignment)
     , m_justifyContent(o.m_justifyContent)
     , userDrag(o.userDrag)
     , textOverflow(o.textOverflow)
@@ -156,6 +158,9 @@
     , m_touchAction(o.m_touchAction)
     , m_objectFit(o.m_objectFit)
     , m_isolation(o.m_isolation)
+    , m_justifySelf(o.m_justifySelf)
+    , m_justifySelfOverflowAlignment(o.m_justifySelfOverflowAlignment)
+    , m_scrollBehavior(o.m_scrollBehavior)
 {
 }
 
@@ -210,18 +215,14 @@
         && m_order == o.m_order
         && m_objectPosition == o.m_objectPosition
         && m_callbackSelectors == o.m_callbackSelectors
-        && m_flowThread == o.m_flowThread
-        && m_regionThread == o.m_regionThread
-        && m_regionFragment == o.m_regionFragment
-        && m_regionBreakAfter == o.m_regionBreakAfter
-        && m_regionBreakBefore == o.m_regionBreakBefore
-        && m_regionBreakInside == o.m_regionBreakInside
         && m_pageSizeType == o.m_pageSizeType
         && m_transformStyle3D == o.m_transformStyle3D
         && m_backfaceVisibility == o.m_backfaceVisibility
         && m_alignContent == o.m_alignContent
         && m_alignItems == o.m_alignItems
+        && m_alignItemsOverflowAlignment == o.m_alignItemsOverflowAlignment
         && m_alignSelf == o.m_alignSelf
+        && m_alignSelfOverflowAlignment == o.m_alignSelfOverflowAlignment
         && m_justifyContent == o.m_justifyContent
         && userDrag == o.userDrag
         && textOverflow == o.textOverflow
@@ -238,7 +239,10 @@
         && m_hasAspectRatio == o.m_hasAspectRatio
         && m_touchAction == o.m_touchAction
         && m_objectFit == o.m_objectFit
-        && m_isolation == o.m_isolation;
+        && m_isolation == o.m_isolation
+        && m_justifySelf == o.m_justifySelf
+        && m_justifySelfOverflowAlignment == o.m_justifySelfOverflowAlignment
+        && m_scrollBehavior == o.m_scrollBehavior;
 }
 
 bool StyleRareNonInheritedData::contentDataEquivalent(const StyleRareNonInheritedData& o) const
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.h b/Source/core/rendering/style/StyleRareNonInheritedData.h
index 7009e42..de00e62 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.h
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.h
@@ -25,6 +25,7 @@
 #ifndef StyleRareNonInheritedData_h
 #define StyleRareNonInheritedData_h
 
+#include "core/css/StyleColor.h"
 #include "core/rendering/ClipPathOperation.h"
 #include "core/rendering/style/BasicShapes.h"
 #include "core/rendering/style/CounterDirectives.h"
@@ -33,6 +34,7 @@
 #include "core/rendering/style/FillLayer.h"
 #include "core/rendering/style/LineClampValue.h"
 #include "core/rendering/style/NinePieceImage.h"
+#include "core/rendering/style/RenderStyleConstants.h"
 #include "core/rendering/style/ShapeValue.h"
 #include "platform/LengthPoint.h"
 #include "wtf/OwnPtr.h"
@@ -43,6 +45,7 @@
 
 class ContentData;
 class CSSAnimationDataList;
+class LengthSize;
 class ShadowList;
 class StyleDeprecatedFlexibleBoxData;
 class StyleFilterData;
@@ -55,8 +58,6 @@
 class StyleResolver;
 class StyleTransformData;
 
-struct LengthSize;
-
 // Page size type.
 // StyleRareNonInheritedData::m_pageSize is meaningful only when
 // StyleRareNonInheritedData::m_pageSizeType is PAGE_SIZE_RESOLVED.
@@ -134,14 +135,14 @@
 
     RefPtr<ClipPathOperation> m_clipPath;
 
-    Color m_textDecorationColor;
-    Color m_visitedLinkTextDecorationColor;
-    Color m_visitedLinkBackgroundColor;
-    Color m_visitedLinkOutlineColor;
-    Color m_visitedLinkBorderLeftColor;
-    Color m_visitedLinkBorderRightColor;
-    Color m_visitedLinkBorderTopColor;
-    Color m_visitedLinkBorderBottomColor;
+    StyleColor m_textDecorationColor;
+    StyleColor m_visitedLinkTextDecorationColor;
+    StyleColor m_visitedLinkBackgroundColor;
+    StyleColor m_visitedLinkOutlineColor;
+    StyleColor m_visitedLinkBorderLeftColor;
+    StyleColor m_visitedLinkBorderRightColor;
+    StyleColor m_visitedLinkBorderTopColor;
+    StyleColor m_visitedLinkBorderBottomColor;
 
     int m_order;
 
@@ -149,21 +150,15 @@
 
     Vector<String> m_callbackSelectors;
 
-    AtomicString m_flowThread;
-    AtomicString m_regionThread;
-    unsigned m_regionFragment : 1; // RegionFragment
-
-    unsigned m_regionBreakAfter : 2; // EPageBreak
-    unsigned m_regionBreakBefore : 2; // EPageBreak
-    unsigned m_regionBreakInside : 2; // EPageBreak
-
     unsigned m_pageSizeType : 2; // PageSizeType
     unsigned m_transformStyle3D : 1; // ETransformStyle3D
     unsigned m_backfaceVisibility : 1; // EBackfaceVisibility
 
     unsigned m_alignContent : 3; // EAlignContent
-    unsigned m_alignItems : 3; // EAlignItems
-    unsigned m_alignSelf : 3; // EAlignItems
+    unsigned m_alignItems : 4; // ItemPosition
+    unsigned m_alignItemsOverflowAlignment : 2; // OverflowAlignment
+    unsigned m_alignSelf : 4; // ItemPosition
+    unsigned m_alignSelfOverflowAlignment : 2; // OverflowAlignment
     unsigned m_justifyContent : 3; // EJustifyContent
 
     unsigned userDrag : 2; // EUserDrag
@@ -184,12 +179,19 @@
 
     unsigned m_effectiveBlendMode: 5; // EBlendMode
 
-    unsigned m_touchAction : 1; // TouchAction
+    unsigned m_touchAction : TouchActionBits; // TouchAction
 
     unsigned m_objectFit : 3; // ObjectFit
 
     unsigned m_isolation : 1; // Isolation
 
+    unsigned m_justifySelf : 4; // ItemPosition
+    unsigned m_justifySelfOverflowAlignment : 2; // OverflowAlignment
+
+    // ScrollBehavior. 'scroll-behavior' has 2 accepted values, but ScrollBehavior has a third
+    // value (that can only be specified using CSSOM scroll APIs) so 2 bits are needed.
+    unsigned m_scrollBehavior: 2;
+
 private:
     StyleRareNonInheritedData();
     StyleRareNonInheritedData(const StyleRareNonInheritedData&);
diff --git a/Source/core/rendering/style/StyleShader.h b/Source/core/rendering/style/StyleShader.h
deleted file mode 100644
index c5927e6..0000000
--- a/Source/core/rendering/style/StyleShader.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER “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 THE COPYRIGHT HOLDER 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.
- */
-
-#ifndef StyleShader_h
-#define StyleShader_h
-
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class ShaderResource;
-class CSSValue;
-
-class StyleShader : public RefCounted<StyleShader> {
-public:
-    virtual ~StyleShader() { }
-
-    ALWAYS_INLINE bool isShaderResource() const { return m_isShaderResource; }
-    ALWAYS_INLINE bool isPendingShader() const { return m_isPendingShader; }
-
-    virtual PassRefPtr<CSSValue> cssValue() const = 0;
-
-    virtual ShaderResource* resource() const { return 0; }
-
-protected:
-    StyleShader()
-        : m_isShaderResource(false)
-        , m_isPendingShader(false)
-    {
-    }
-    bool m_isShaderResource : 1;
-    bool m_isPendingShader : 1;
-};
-
-}
-
-
-#endif // StyleShader_h
diff --git a/Source/core/rendering/style/StyleVariableData.h b/Source/core/rendering/style/StyleVariableData.h
deleted file mode 100644
index 23429f1..0000000
--- a/Source/core/rendering/style/StyleVariableData.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * 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.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "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 THE COPYRIGHT
- * OWNER 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.
- */
-
-
-#ifndef StyleVariableData_h
-#define StyleVariableData_h
-
-#include "wtf/Forward.h"
-#include "wtf/HashMap.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/AtomicStringHash.h"
-
-namespace WebCore {
-
-class CursorList;
-class QuotesData;
-class ShadowData;
-
-class StyleVariableData : public RefCounted<StyleVariableData> {
-public:
-    static PassRefPtr<StyleVariableData> create() { return adoptRef(new StyleVariableData()); }
-    PassRefPtr<StyleVariableData> copy() const { return adoptRef(new StyleVariableData(*this)); }
-
-    bool operator==(const StyleVariableData& other) const { return other.m_data == m_data; }
-    bool operator!=(const StyleVariableData& other) const { return !(*this == other); }
-
-    void setVariable(const AtomicString& name, const String& value) { m_data.set(name, value); }
-
-    HashMap<AtomicString, String> m_data;
-private:
-    explicit StyleVariableData() : RefCounted<StyleVariableData>() { }
-    StyleVariableData(const StyleVariableData& other) : RefCounted<StyleVariableData>(), m_data(HashMap<AtomicString, String>(other.m_data)) { }
-};
-
-} // namespace WebCore
-
-#endif /* StyleVariableData_h */
diff --git a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
index 8c0a5c5..4dca2dd 100644
--- a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
+++ b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
@@ -82,8 +82,7 @@
         eColorInterpolation = svgStyle->colorInterpolationFilters();
     } else {
         // Otherwise, use the slow path by using string comparison (used by external svg files)
-        RefPtr<CSSValue> cssValue = svgElement->getPresentationAttribute(
-            SVGNames::color_interpolation_filtersAttr.toString());
+        RefPtr<CSSValue> cssValue = svgElement->getPresentationAttribute(AtomicString(SVGNames::color_interpolation_filtersAttr.toString()));
         if (cssValue.get() && cssValue->isPrimitiveValue()) {
             const CSSPrimitiveValue& primitiveValue = *((CSSPrimitiveValue*)cssValue.get());
             eColorInterpolation = (EColorInterpolation)primitiveValue;
@@ -169,7 +168,7 @@
         ColorSpace colorSpace = filterColorSpace;
         if (useFilterColorSpace || getSVGElementColorSpace(effectElement, colorSpace))
             effect->setOperatingColorSpace(colorSpace);
-        builder->add(effectElement->resultCurrentValue(), effect);
+        builder->add(AtomicString(effectElement->result()->currentValue()->value()), effect);
     }
     return builder->lastEffect();
 }
diff --git a/Source/core/rendering/svg/RenderSVGBlock.cpp b/Source/core/rendering/svg/RenderSVGBlock.cpp
index ab40394..f66247f 100644
--- a/Source/core/rendering/svg/RenderSVGBlock.cpp
+++ b/Source/core/rendering/svg/RenderSVGBlock.cpp
@@ -24,6 +24,7 @@
 #include "core/rendering/svg/RenderSVGBlock.h"
 
 #include "core/rendering/style/ShadowList.h"
+#include "core/rendering/svg/SVGRenderSupport.h"
 #include "core/rendering/svg/SVGResourcesCache.h"
 #include "core/svg/SVGElement.h"
 
@@ -50,7 +51,7 @@
 
     // RenderSVGlock, used by Render(SVGText|ForeignObject), is not allowed to call setHasOverflowClip(true).
     // RenderBlock assumes a layer to be present when the overflow clip functionality is requested. Both
-    // Render(SVGText|ForeignObject) return 'false' on 'requiresLayer'. Fine for RenderSVGText.
+    // Render(SVGText|ForeignObject) return 'NoLayer' on 'layerTypeRequired'. Fine for RenderSVGText.
     //
     // If we want to support overflow rules for <foreignObject> we can choose between two solutions:
     // a) make RenderSVGForeignObject require layers and SVG layer aware
@@ -84,4 +85,30 @@
     SVGResourcesCache::clientStyleChanged(this, diff, style());
 }
 
+void RenderSVGBlock::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags, bool* wasFixed) const
+{
+    SVGRenderSupport::mapLocalToContainer(this, repaintContainer, transformState, wasFixed);
+}
+
+const RenderObject* RenderSVGBlock::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
+{
+    return SVGRenderSupport::pushMappingToContainer(this, ancestorToStopAt, geometryMap);
+}
+
+LayoutRect RenderSVGBlock::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
+{
+    return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
+}
+
+void RenderSVGBlock::computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
+{
+    SVGRenderSupport::computeFloatRectForRepaint(this, repaintContainer, repaintRect, fixed);
+}
+
+bool RenderSVGBlock::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation&, const LayoutPoint&, HitTestAction)
+{
+    ASSERT_NOT_REACHED();
+    return false;
+}
+
 }
diff --git a/Source/core/rendering/svg/RenderSVGBlock.h b/Source/core/rendering/svg/RenderSVGBlock.h
index 6f08eb1..c503536 100644
--- a/Source/core/rendering/svg/RenderSVGBlock.h
+++ b/Source/core/rendering/svg/RenderSVGBlock.h
@@ -32,19 +32,33 @@
 
     virtual LayoutRect visualOverflowRect() const OVERRIDE FINAL;
 
+    virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const OVERRIDE FINAL;
+    virtual void computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect&, bool fixed = false) const OVERRIDE FINAL;
+
+    virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE FINAL;
+    virtual const RenderObject* pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&) const OVERRIDE FINAL;
+
+    virtual AffineTransform localTransform() const OVERRIDE FINAL { return m_localTransform; }
+
+    virtual LayerType layerTypeRequired() const OVERRIDE FINAL { return NoLayer; }
+
 protected:
     virtual void willBeDestroyed() OVERRIDE;
 
+    AffineTransform m_localTransform;
+
 private:
     virtual void updateFromStyle() OVERRIDE FINAL;
 
-    virtual bool isRenderSVGBlock() const OVERRIDE FINAL { return true; };
+    virtual bool isSVG() const OVERRIDE FINAL { return true; }
 
-    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+    virtual bool supportsPartialLayout() const OVERRIDE FINAL { return false; }
 
     virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE FINAL;
 
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
+
+    virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 };
 
 }
diff --git a/Source/core/rendering/svg/RenderSVGContainer.h b/Source/core/rendering/svg/RenderSVGContainer.h
index fd4e74d..28385fa 100644
--- a/Source/core/rendering/svg/RenderSVGContainer.h
+++ b/Source/core/rendering/svg/RenderSVGContainer.h
@@ -40,9 +40,8 @@
     const RenderObjectChildList* children() const { return &m_children; }
     RenderObjectChildList* children() { return &m_children; }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
     virtual void setNeedsBoundariesUpdate() OVERRIDE FINAL { m_needsBoundariesUpdate = true; }
-    virtual bool needsBoundariesUpdate() OVERRIDE FINAL { return m_needsBoundariesUpdate; }
     virtual bool didTransformToRootUpdate() { return false; }
     bool isObjectBoundingBoxValid() const { return m_objectBoundingBoxValid; }
 
@@ -51,9 +50,9 @@
     virtual const RenderObjectChildList* virtualChildren() const OVERRIDE FINAL { return children(); }
 
     virtual bool isSVGContainer() const OVERRIDE FINAL { return true; }
-    virtual const char* renderName() const { return "RenderSVGContainer"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGContainer"; }
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
     virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE FINAL;
     virtual void removeChild(RenderObject*) OVERRIDE FINAL;
@@ -63,7 +62,7 @@
     virtual FloatRect strokeBoundingBox() const OVERRIDE FINAL { return m_strokeBoundingBox; }
     virtual FloatRect repaintRectInLocalCoordinates() const OVERRIDE FINAL { return m_repaintBoundingBox; }
 
-    virtual bool nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint& pointInParent, HitTestAction);
+    virtual bool nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint& pointInParent, HitTestAction) OVERRIDE;
 
     // Allow RenderSVGTransformableContainer to hook in at the right time in layout()
     virtual bool calculateLocalTransform() { return false; }
diff --git a/Source/core/rendering/svg/RenderSVGEllipse.cpp b/Source/core/rendering/svg/RenderSVGEllipse.cpp
index ac5c649..1b09e25 100644
--- a/Source/core/rendering/svg/RenderSVGEllipse.cpp
+++ b/Source/core/rendering/svg/RenderSVGEllipse.cpp
@@ -80,17 +80,17 @@
         SVGCircleElement* circle = toSVGCircleElement(element());
 
         SVGLengthContext lengthContext(circle);
-        float radius = circle->rCurrentValue().value(lengthContext);
+        float radius = circle->r()->currentValue()->value(lengthContext);
         m_radii = FloatSize(radius, radius);
-        m_center = FloatPoint(circle->cxCurrentValue().value(lengthContext), circle->cyCurrentValue().value(lengthContext));
+        m_center = FloatPoint(circle->cx()->currentValue()->value(lengthContext), circle->cy()->currentValue()->value(lengthContext));
         return;
     }
 
     SVGEllipseElement* ellipse = toSVGEllipseElement(element());
 
     SVGLengthContext lengthContext(ellipse);
-    m_radii = FloatSize(ellipse->rxCurrentValue().value(lengthContext), ellipse->ryCurrentValue().value(lengthContext));
-    m_center = FloatPoint(ellipse->cxCurrentValue().value(lengthContext), ellipse->cyCurrentValue().value(lengthContext));
+    m_radii = FloatSize(ellipse->rx()->currentValue()->value(lengthContext), ellipse->ry()->currentValue()->value(lengthContext));
+    m_center = FloatPoint(ellipse->cx()->currentValue()->value(lengthContext), ellipse->cy()->currentValue()->value(lengthContext));
 }
 
 void RenderSVGEllipse::fillShape(GraphicsContext* context) const
diff --git a/Source/core/rendering/svg/RenderSVGEllipse.h b/Source/core/rendering/svg/RenderSVGEllipse.h
index f06e5c1..c26cd02 100644
--- a/Source/core/rendering/svg/RenderSVGEllipse.h
+++ b/Source/core/rendering/svg/RenderSVGEllipse.h
@@ -37,14 +37,14 @@
     virtual ~RenderSVGEllipse();
 
 private:
-    virtual const char* renderName() const { return "RenderSVGEllipse"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGEllipse"; }
 
-    virtual void updateShapeFromElement();
-    virtual bool isEmpty() const { return m_usePathFallback ? RenderSVGShape::isEmpty() : m_fillBoundingBox.isEmpty(); };
-    virtual void fillShape(GraphicsContext*) const;
-    virtual void strokeShape(GraphicsContext*) const;
-    virtual bool shapeDependentStrokeContains(const FloatPoint&);
-    virtual bool shapeDependentFillContains(const FloatPoint&, const WindRule) const;
+    virtual void updateShapeFromElement() OVERRIDE;
+    virtual bool isEmpty() const OVERRIDE { return m_usePathFallback ? RenderSVGShape::isEmpty() : m_fillBoundingBox.isEmpty(); }
+    virtual void fillShape(GraphicsContext*) const OVERRIDE;
+    virtual void strokeShape(GraphicsContext*) const OVERRIDE;
+    virtual bool shapeDependentStrokeContains(const FloatPoint&) OVERRIDE;
+    virtual bool shapeDependentFillContains(const FloatPoint&, const WindRule) const OVERRIDE;
     void calculateRadiiAndCenter();
 
 private:
diff --git a/Source/core/rendering/svg/RenderSVGForeignObject.cpp b/Source/core/rendering/svg/RenderSVGForeignObject.cpp
index e27e037..c9d3ceb 100644
--- a/Source/core/rendering/svg/RenderSVGForeignObject.cpp
+++ b/Source/core/rendering/svg/RenderSVGForeignObject.cpp
@@ -45,6 +45,12 @@
 {
 }
 
+bool RenderSVGForeignObject::isChildAllowed(RenderObject* child, RenderStyle* style) const
+{
+    // Disallow arbitary SVG content. Only allow proper <svg xmlns="svgNS"> subdocuments.
+    return !child->isSVG() || child->isSVGRoot();
+}
+
 void RenderSVGForeignObject::paint(PaintInfo& paintInfo, const LayoutPoint&)
 {
     if (paintInfo.context->paintingDisabled()
@@ -85,16 +91,6 @@
     }
 }
 
-LayoutRect RenderSVGForeignObject::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
-{
-    return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
-}
-
-void RenderSVGForeignObject::computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
-{
-    SVGRenderSupport::computeFloatRectForRepaint(this, repaintContainer, repaintRect, fixed);
-}
-
 const AffineTransform& RenderSVGForeignObject::localToParentTransform() const
 {
     m_localToParentTransform = localTransform();
@@ -138,8 +134,8 @@
 
     // Cache viewport boundaries
     SVGLengthContext lengthContext(foreign);
-    FloatPoint viewportLocation(foreign->xCurrentValue().value(lengthContext), foreign->yCurrentValue().value(lengthContext));
-    m_viewport = FloatRect(viewportLocation, FloatSize(foreign->widthCurrentValue().value(lengthContext), foreign->heightCurrentValue().value(lengthContext)));
+    FloatPoint viewportLocation(foreign->x()->currentValue()->value(lengthContext), foreign->y()->currentValue()->value(lengthContext));
+    m_viewport = FloatRect(viewportLocation, FloatSize(foreign->width()->currentValue()->value(lengthContext), foreign->height()->currentValue()->value(lengthContext)));
     if (!updateCachedBoundariesInParents)
         updateCachedBoundariesInParents = oldViewport != m_viewport;
 
@@ -165,6 +161,14 @@
     repainter.repaintAfterLayout();
 }
 
+void RenderSVGForeignObject::computeRectForRepaint(const RenderLayerModelObject* repaintContainer,
+    LayoutRect& rect, bool fixed) const
+{
+    FloatRect r(rect);
+    SVGRenderSupport::computeFloatRectForRepaint(this, repaintContainer, r, fixed);
+    rect = enclosingLayoutRect(r);
+}
+
 bool RenderSVGForeignObject::nodeAtFloatPoint(const HitTestRequest& request, HitTestResult& result, const FloatPoint& pointInParent, HitTestAction hitTestAction)
 {
     // Embedded content is drawn in the foreground phase.
@@ -184,20 +188,4 @@
         || RenderBlock::nodeAtPoint(request, result, hitTestLocation, LayoutPoint(), HitTestChildBlockBackgrounds);
 }
 
-bool RenderSVGForeignObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation&, const LayoutPoint&, HitTestAction)
-{
-    ASSERT_NOT_REACHED();
-    return false;
-}
-
-void RenderSVGForeignObject::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags, bool* wasFixed) const
-{
-    SVGRenderSupport::mapLocalToContainer(this, repaintContainer, transformState, wasFixed);
-}
-
-const RenderObject* RenderSVGForeignObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
-{
-    return SVGRenderSupport::pushMappingToContainer(this, ancestorToStopAt, geometryMap);
-}
-
 }
diff --git a/Source/core/rendering/svg/RenderSVGForeignObject.h b/Source/core/rendering/svg/RenderSVGForeignObject.h
index 63cdac1..e4d7219 100644
--- a/Source/core/rendering/svg/RenderSVGForeignObject.h
+++ b/Source/core/rendering/svg/RenderSVGForeignObject.h
@@ -32,38 +32,32 @@
     explicit RenderSVGForeignObject(SVGForeignObjectElement*);
     virtual ~RenderSVGForeignObject();
 
-    virtual const char* renderName() const { return "RenderSVGForeignObject"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGForeignObject"; }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
 
-    virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const OVERRIDE;
-    virtual void computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect&, bool fixed = false) const OVERRIDE;
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
-    virtual bool requiresLayer() const { return false; }
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
-    virtual FloatRect objectBoundingBox() const { return FloatRect(FloatPoint(), m_viewport.size()); }
-    virtual FloatRect strokeBoundingBox() const { return FloatRect(FloatPoint(), m_viewport.size()); }
-    virtual FloatRect repaintRectInLocalCoordinates() const { return FloatRect(FloatPoint(), m_viewport.size()); }
+    virtual FloatRect objectBoundingBox() const OVERRIDE { return FloatRect(FloatPoint(), m_viewport.size()); }
+    virtual FloatRect strokeBoundingBox() const OVERRIDE { return FloatRect(FloatPoint(), m_viewport.size()); }
+    virtual FloatRect repaintRectInLocalCoordinates() const OVERRIDE { return FloatRect(FloatPoint(), m_viewport.size()); }
 
-    virtual bool nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint& pointInParent, HitTestAction);
-    virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
-    virtual bool isSVGForeignObject() const { return true; }
+    virtual void computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect&, bool fixed = false) const OVERRIDE;
+    virtual bool nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint& pointInParent, HitTestAction) OVERRIDE;
+    virtual bool isSVGForeignObject() const OVERRIDE { return true; }
 
-    virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE;
-    virtual const RenderObject* pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&) const OVERRIDE;
-    virtual void setNeedsTransformUpdate() { m_needsTransformUpdate = true; }
+    virtual void setNeedsTransformUpdate() OVERRIDE { m_needsTransformUpdate = true; }
 
 private:
     virtual void updateLogicalWidth() OVERRIDE;
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
 
-    virtual const AffineTransform& localToParentTransform() const;
-    virtual AffineTransform localTransform() const { return m_localTransform; }
+    virtual const AffineTransform& localToParentTransform() const OVERRIDE;
 
     bool m_needsTransformUpdate : 1;
     FloatRect m_viewport;
-    AffineTransform m_localTransform;
     mutable AffineTransform m_localToParentTransform;
 };
 
diff --git a/Source/core/rendering/svg/RenderSVGGradientStop.h b/Source/core/rendering/svg/RenderSVGGradientStop.h
index e56274e..731441c 100644
--- a/Source/core/rendering/svg/RenderSVGGradientStop.h
+++ b/Source/core/rendering/svg/RenderSVGGradientStop.h
@@ -34,21 +34,22 @@
     explicit RenderSVGGradientStop(SVGStopElement*);
     virtual ~RenderSVGGradientStop();
 
-    virtual bool isSVGGradientStop() const { return true; }
-    virtual const char* renderName() const { return "RenderSVGGradientStop"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGGradientStop"; }
+    virtual bool isSVGGradientStop() const OVERRIDE { return true; }
+    virtual bool isSVG() const OVERRIDE { return true; }
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
     // This overrides are needed to prevent ASSERTs on <svg><stop /></svg>
     // RenderObject's default implementations ASSERT_NOT_REACHED()
     // https://bugs.webkit.org/show_bug.cgi?id=20400
     virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject*) const OVERRIDE { return LayoutRect(); }
-    virtual FloatRect objectBoundingBox() const { return FloatRect(); }
-    virtual FloatRect strokeBoundingBox() const { return FloatRect(); }
-    virtual FloatRect repaintRectInLocalCoordinates() const { return FloatRect(); }
+    virtual FloatRect objectBoundingBox() const OVERRIDE { return FloatRect(); }
+    virtual FloatRect strokeBoundingBox() const OVERRIDE { return FloatRect(); }
+    virtual FloatRect repaintRectInLocalCoordinates() const OVERRIDE { return FloatRect(); }
 
 protected:
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
 private:
     SVGGradientElement* gradientElement() const;
diff --git a/Source/core/rendering/svg/RenderSVGHiddenContainer.h b/Source/core/rendering/svg/RenderSVGHiddenContainer.h
index f8e57d3..517b500 100644
--- a/Source/core/rendering/svg/RenderSVGHiddenContainer.h
+++ b/Source/core/rendering/svg/RenderSVGHiddenContainer.h
@@ -32,10 +32,10 @@
 public:
     explicit RenderSVGHiddenContainer(SVGElement*);
 
-    virtual const char* renderName() const { return "RenderSVGHiddenContainer"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGHiddenContainer"; }
 
 protected:
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
 private:
     virtual bool isSVGHiddenContainer() const OVERRIDE FINAL { return true; }
diff --git a/Source/core/rendering/svg/RenderSVGImage.cpp b/Source/core/rendering/svg/RenderSVGImage.cpp
index 3e066ec..0eebb39 100644
--- a/Source/core/rendering/svg/RenderSVGImage.cpp
+++ b/Source/core/rendering/svg/RenderSVGImage.cpp
@@ -64,12 +64,12 @@
     bool updatedViewport = false;
 
     SVGLengthContext lengthContext(image);
-    m_objectBoundingBox = FloatRect(image->xCurrentValue().value(lengthContext), image->yCurrentValue().value(lengthContext), image->widthCurrentValue().value(lengthContext), image->heightCurrentValue().value(lengthContext));
+    m_objectBoundingBox = FloatRect(image->x()->currentValue()->value(lengthContext), image->y()->currentValue()->value(lengthContext), image->width()->currentValue()->value(lengthContext), image->height()->currentValue()->value(lengthContext));
 
     // Images with preserveAspectRatio=none should force non-uniform scaling. This can be achieved
     // by setting the image's container size to its intrinsic size.
     // See: http://www.w3.org/TR/SVG/single-page.html, 7.8 The ‘preserveAspectRatio’ attribute.
-    if (image->preserveAspectRatioCurrentValue().align() == SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE) {
+    if (image->preserveAspectRatio()->currentValue()->align() == SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE) {
         if (ImageResource* cachedImage = m_imageResource->cachedImage()) {
             LayoutSize intrinsicSize = cachedImage->imageSizeForRenderer(0, style()->effectiveZoom());
             if (intrinsicSize != m_imageResource->imageSize(style()->effectiveZoom())) {
@@ -136,14 +136,16 @@
     PaintInfo childPaintInfo(paintInfo);
     bool drawsOutline = style()->outlineWidth() && (childPaintInfo.phase == PaintPhaseOutline || childPaintInfo.phase == PaintPhaseSelfOutline);
     if (drawsOutline || childPaintInfo.phase == PaintPhaseForeground) {
-        GraphicsContextStateSaver stateSaver(*childPaintInfo.context);
-        childPaintInfo.applyTransform(m_localTransform);
-
-        if (childPaintInfo.phase == PaintPhaseForeground) {
+        GraphicsContextStateSaver stateSaver(*childPaintInfo.context, false);
+        if (!m_localTransform.isIdentity()) {
+            stateSaver.save();
+            childPaintInfo.applyTransform(m_localTransform, false);
+        }
+        if (childPaintInfo.phase == PaintPhaseForeground && !m_objectBoundingBox.isEmpty()) {
             SVGRenderingContext renderingContext(this, childPaintInfo);
 
             if (renderingContext.isRenderingPrepared()) {
-                if (style()->svgStyle()->bufferedRendering() == BR_STATIC  && renderingContext.bufferForeground(m_bufferedForeground))
+                if (style()->svgStyle()->bufferedRendering() == BR_STATIC && renderingContext.bufferForeground(m_bufferedForeground))
                     return;
 
                 paintForeground(childPaintInfo);
@@ -162,7 +164,7 @@
     FloatRect srcRect(0, 0, image->width(), image->height());
 
     SVGImageElement* imageElement = toSVGImageElement(element());
-    imageElement->preserveAspectRatioCurrentValue().transformRect(destRect, srcRect);
+    imageElement->preserveAspectRatio()->currentValue()->transformRect(destRect, srcRect);
 
     bool useLowQualityScaling = false;
     if (style()->svgStyle()->bufferedRendering() != BR_STATIC)
diff --git a/Source/core/rendering/svg/RenderSVGImage.h b/Source/core/rendering/svg/RenderSVGImage.h
index ce1536d..ce3c0d2 100644
--- a/Source/core/rendering/svg/RenderSVGImage.h
+++ b/Source/core/rendering/svg/RenderSVGImage.h
@@ -37,39 +37,36 @@
     virtual ~RenderSVGImage();
 
     bool updateImageViewport();
-    virtual void setNeedsBoundariesUpdate() { m_needsBoundariesUpdate = true; }
-    virtual bool needsBoundariesUpdate() OVERRIDE { return m_needsBoundariesUpdate; }
-    virtual void setNeedsTransformUpdate() { m_needsTransformUpdate = true; }
+    virtual void setNeedsBoundariesUpdate() OVERRIDE { m_needsBoundariesUpdate = true; }
+    virtual void setNeedsTransformUpdate() OVERRIDE { m_needsTransformUpdate = true; }
 
     RenderImageResource* imageResource() { return m_imageResource.get(); }
-    const RenderImageResource* imageResource() const { return m_imageResource.get(); }
 
     // Note: Assumes the PaintInfo context has had all local transforms applied.
     void paintForeground(PaintInfo&);
 
 private:
-    virtual const char* renderName() const { return "RenderSVGImage"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGImage"; }
     virtual bool isSVGImage() const OVERRIDE { return true; }
 
-    virtual const AffineTransform& localToParentTransform() const { return m_localTransform; }
+    virtual const AffineTransform& localToParentTransform() const OVERRIDE { return m_localTransform; }
 
-    virtual FloatRect objectBoundingBox() const { return m_objectBoundingBox; }
-    virtual FloatRect strokeBoundingBox() const { return m_objectBoundingBox; }
-    virtual FloatRect repaintRectInLocalCoordinates() const { return m_repaintBoundingBox; }
+    virtual FloatRect objectBoundingBox() const OVERRIDE { return m_objectBoundingBox; }
+    virtual FloatRect strokeBoundingBox() const OVERRIDE { return m_objectBoundingBox; }
+    virtual FloatRect repaintRectInLocalCoordinates() const OVERRIDE { return m_repaintBoundingBox; }
 
     virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer = 0) OVERRIDE;
 
-    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0);
+    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
-    virtual void layout();
-    virtual void paint(PaintInfo&, const LayoutPoint&);
+    virtual void layout() OVERRIDE;
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     void invalidateBufferedForeground();
 
-    virtual bool nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint& pointInParent, HitTestAction);
+    virtual bool nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint& pointInParent, HitTestAction) OVERRIDE;
 
-    virtual AffineTransform localTransform() const { return m_localTransform; }
-    void calculateImageViewport();
+    virtual AffineTransform localTransform() const OVERRIDE { return m_localTransform; }
 
     bool m_needsBoundariesUpdate : 1;
     bool m_needsTransformUpdate : 1;
diff --git a/Source/core/rendering/svg/RenderSVGInline.cpp b/Source/core/rendering/svg/RenderSVGInline.cpp
index 68b1a40..64f6b4d 100644
--- a/Source/core/rendering/svg/RenderSVGInline.cpp
+++ b/Source/core/rendering/svg/RenderSVGInline.cpp
@@ -23,6 +23,7 @@
 
 #include "core/rendering/svg/RenderSVGInline.h"
 
+#include "SVGNames.h"
 #include "core/rendering/svg/RenderSVGText.h"
 #include "core/rendering/svg/SVGInlineFlowBox.h"
 #include "core/rendering/svg/SVGRenderSupport.h"
@@ -32,7 +33,16 @@
 
 bool RenderSVGInline::isChildAllowed(RenderObject* child, RenderStyle* style) const
 {
-    if (SVGRenderSupport::isEmptySVGInlineText(child))
+    if (child->isText())
+        return SVGRenderSupport::isRenderableTextNode(child);
+
+    if (node()->hasTagName(SVGNames::aTag)) {
+        // Disallow direct descendant 'a'.
+        if (child->node()->hasTagName(SVGNames::aTag))
+            return false;
+    }
+
+    if (!child->isSVGInline() && !child->isSVGInlineText())
         return false;
 
     return RenderInline::isChildAllowed(child, style);
diff --git a/Source/core/rendering/svg/RenderSVGInline.h b/Source/core/rendering/svg/RenderSVGInline.h
index 43634a3..bc0f607 100644
--- a/Source/core/rendering/svg/RenderSVGInline.h
+++ b/Source/core/rendering/svg/RenderSVGInline.h
@@ -29,9 +29,10 @@
 public:
     explicit RenderSVGInline(Element*);
 
-    virtual const char* renderName() const { return "RenderSVGInline"; }
-    virtual bool requiresLayer() const OVERRIDE FINAL { return false; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGInline"; }
+    virtual LayerType layerTypeRequired() const OVERRIDE FINAL { return NoLayer; }
     virtual bool isSVGInline() const OVERRIDE FINAL { return true; }
+    virtual bool isSVG() const OVERRIDE FINAL { return true; }
 
     virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
 
diff --git a/Source/core/rendering/svg/RenderSVGInlineText.cpp b/Source/core/rendering/svg/RenderSVGInlineText.cpp
index e8041f8..5a6420c 100644
--- a/Source/core/rendering/svg/RenderSVGInlineText.cpp
+++ b/Source/core/rendering/svg/RenderSVGInlineText.cpp
@@ -235,7 +235,7 @@
     // FIXME: We need to better handle the case when we compute very small fonts below (below 1pt).
     fontDescription.setComputedSize(FontSize::getComputedSizeFromSpecifiedSize(&document, scalingFactor, fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), DoNotUseSmartMinimumForFontSize));
 
-    scaledFont = Font(fontDescription, 0, 0);
+    scaledFont = Font(fontDescription);
     scaledFont.update(document.styleEngine()->fontSelector());
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGInlineText.h b/Source/core/rendering/svg/RenderSVGInlineText.h
index 1cbebb7..011eaf9 100644
--- a/Source/core/rendering/svg/RenderSVGInlineText.h
+++ b/Source/core/rendering/svg/RenderSVGInlineText.h
@@ -45,20 +45,20 @@
     FloatRect floatLinesBoundingBox() const;
 
 private:
-    virtual const char* renderName() const { return "RenderSVGInlineText"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGInlineText"; }
 
-    virtual void setTextInternal(PassRefPtr<StringImpl>);
-    virtual void styleDidChange(StyleDifference, const RenderStyle*);
+    virtual void setTextInternal(PassRefPtr<StringImpl>) OVERRIDE;
+    virtual void styleDidChange(StyleDifference, const RenderStyle*) OVERRIDE;
 
-    virtual FloatRect objectBoundingBox() const { return floatLinesBoundingBox(); }
+    virtual FloatRect objectBoundingBox() const OVERRIDE { return floatLinesBoundingBox(); }
 
-    virtual bool requiresLayer() const { return false; }
-    virtual bool isSVGInlineText() const { return true; }
+    virtual bool isSVGInlineText() const OVERRIDE { return true; }
+    virtual bool isSVG() const OVERRIDE { return true; }
 
-    virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE FINAL;
-    virtual LayoutRect localCaretRect(InlineBox*, int caretOffset, LayoutUnit* extraWidthToEndOfLine = 0);
-    virtual IntRect linesBoundingBox() const;
-    virtual InlineTextBox* createTextBox();
+    virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE;
+    virtual LayoutRect localCaretRect(InlineBox*, int caretOffset, LayoutUnit* extraWidthToEndOfLine = 0) OVERRIDE;
+    virtual IntRect linesBoundingBox() const OVERRIDE;
+    virtual InlineTextBox* createTextBox() OVERRIDE;
 
     float m_scalingFactor;
     Font m_scaledFont;
diff --git a/Source/core/rendering/svg/RenderSVGModelObject.cpp b/Source/core/rendering/svg/RenderSVGModelObject.cpp
index 12da706..294dfda 100644
--- a/Source/core/rendering/svg/RenderSVGModelObject.cpp
+++ b/Source/core/rendering/svg/RenderSVGModelObject.cpp
@@ -44,6 +44,11 @@
 {
 }
 
+bool RenderSVGModelObject::isChildAllowed(RenderObject* child, RenderStyle*) const
+{
+    return child->isSVG() && !(child->isSVGInline() || child->isSVGInlineText());
+}
+
 LayoutRect RenderSVGModelObject::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
 {
     return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
@@ -175,7 +180,7 @@
     quads.append(localToAbsoluteQuad(FloatQuad(repaintRectInLocalCoordinates())));
 }
 
-bool RenderSVGModelObject::checkIntersection(RenderObject* renderer, const SVGRect& rect)
+bool RenderSVGModelObject::checkIntersection(RenderObject* renderer, const FloatRect& rect)
 {
     if (!renderer || renderer->style()->pointerEvents() == PE_NONE)
         return false;
@@ -188,7 +193,7 @@
     return intersectsAllowingEmpty(rect, ctm.mapRect(svgElement->renderer()->repaintRectInLocalCoordinates()));
 }
 
-bool RenderSVGModelObject::checkEnclosure(RenderObject* renderer, const SVGRect& rect)
+bool RenderSVGModelObject::checkEnclosure(RenderObject* renderer, const FloatRect& rect)
 {
     if (!renderer || renderer->style()->pointerEvents() == PE_NONE)
         return false;
diff --git a/Source/core/rendering/svg/RenderSVGModelObject.h b/Source/core/rendering/svg/RenderSVGModelObject.h
index c8df10a..e9370e6 100644
--- a/Source/core/rendering/svg/RenderSVGModelObject.h
+++ b/Source/core/rendering/svg/RenderSVGModelObject.h
@@ -34,7 +34,7 @@
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/svg/SVGRenderSupport.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGRect.h"
+#include "platform/geometry/FloatRect.h"
 
 namespace WebCore {
 
@@ -49,34 +49,39 @@
 public:
     explicit RenderSVGModelObject(SVGElement*);
 
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
+    virtual bool canHaveWhitespaceChildren() const OVERRIDE { return false; }
+
     virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const OVERRIDE;
     virtual void computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect&, bool fixed = false) const OVERRIDE FINAL;
     virtual LayoutRect outlineBoundsForRepaint(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap*) const OVERRIDE FINAL;
 
     virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE FINAL;
-    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
+    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const OVERRIDE;
 
     virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE FINAL;
     virtual const RenderObject* pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&) const OVERRIDE FINAL;
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
 
-    static bool checkIntersection(RenderObject*, const SVGRect&);
-    static bool checkEnclosure(RenderObject*, const SVGRect&);
+    static bool checkIntersection(RenderObject*, const FloatRect&);
+    static bool checkEnclosure(RenderObject*, const FloatRect&);
 
-    virtual void computeLayerHitTestRects(LayerHitTestRects&) const OVERRIDE;
+    virtual void computeLayerHitTestRects(LayerHitTestRects&) const OVERRIDE FINAL;
 
     SVGElement* element() const { return toSVGElement(RenderObject::node()); }
 
+    virtual bool isSVG() const OVERRIDE FINAL { return true; }
+
 protected:
-    virtual void addLayerHitTestRects(LayerHitTestRects&, const RenderLayer* currentCompositedLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const OVERRIDE;
-    virtual void willBeDestroyed();
+    virtual void addLayerHitTestRects(LayerHitTestRects&, const RenderLayer* currentCompositedLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const OVERRIDE FINAL;
+    virtual void willBeDestroyed() OVERRIDE;
 
 private:
     // RenderSVGModelObject subclasses should use element() instead.
     void node() const WTF_DELETED_FUNCTION;
 
     // This method should never be called, SVG uses a different nodeAtPoint method
-    bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
+    virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE FINAL;
     virtual void absoluteFocusRingQuads(Vector<FloatQuad>&) OVERRIDE FINAL;
 };
 
diff --git a/Source/core/rendering/svg/RenderSVGPath.h b/Source/core/rendering/svg/RenderSVGPath.h
index 8cec15c..48b3676 100644
--- a/Source/core/rendering/svg/RenderSVGPath.h
+++ b/Source/core/rendering/svg/RenderSVGPath.h
@@ -37,7 +37,7 @@
 
 private:
     virtual bool isSVGPath() const OVERRIDE { return true; }
-    virtual const char* renderName() const { return "RenderSVGPath"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGPath"; }
 
     virtual void updateShapeFromElement() OVERRIDE;
     FloatRect calculateUpdatedStrokeBoundingBox() const;
diff --git a/Source/core/rendering/svg/RenderSVGRect.cpp b/Source/core/rendering/svg/RenderSVGRect.cpp
index dfe4471..ce79642 100644
--- a/Source/core/rendering/svg/RenderSVGRect.cpp
+++ b/Source/core/rendering/svg/RenderSVGRect.cpp
@@ -55,18 +55,18 @@
 
     SVGLengthContext lengthContext(rect);
     // Fallback to RenderSVGShape if rect has rounded corners or a non-scaling stroke.
-    if (rect->rxCurrentValue().value(lengthContext) > 0 || rect->ryCurrentValue().value(lengthContext) > 0 || hasNonScalingStroke()) {
+    if (rect->rx()->currentValue()->value(lengthContext) > 0 || rect->ry()->currentValue()->value(lengthContext) > 0 || hasNonScalingStroke()) {
         RenderSVGShape::updateShapeFromElement();
         m_usePathFallback = true;
         return;
     }
 
     m_usePathFallback = false;
-    FloatSize boundingBoxSize(rect->widthCurrentValue().value(lengthContext), rect->heightCurrentValue().value(lengthContext));
+    FloatSize boundingBoxSize(rect->width()->currentValue()->value(lengthContext), rect->height()->currentValue()->value(lengthContext));
     if (boundingBoxSize.isEmpty())
         return;
 
-    m_fillBoundingBox = FloatRect(FloatPoint(rect->xCurrentValue().value(lengthContext), rect->yCurrentValue().value(lengthContext)), boundingBoxSize);
+    m_fillBoundingBox = FloatRect(FloatPoint(rect->x()->currentValue()->value(lengthContext), rect->y()->currentValue()->value(lengthContext)), boundingBoxSize);
 
     // To decide if the stroke contains a point we create two rects which represent the inner and
     // the outer stroke borders. A stroke contains the point, if the point is between them.
diff --git a/Source/core/rendering/svg/RenderSVGRect.h b/Source/core/rendering/svg/RenderSVGRect.h
index 1a5d6e0..afc65e3 100644
--- a/Source/core/rendering/svg/RenderSVGRect.h
+++ b/Source/core/rendering/svg/RenderSVGRect.h
@@ -39,14 +39,14 @@
     virtual ~RenderSVGRect();
 
 private:
-    virtual const char* renderName() const { return "RenderSVGRect"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGRect"; }
 
-    virtual void updateShapeFromElement();
-    virtual bool isEmpty() const { return m_usePathFallback ? RenderSVGShape::isEmpty() : m_fillBoundingBox.isEmpty(); };
-    virtual void fillShape(GraphicsContext*) const;
-    virtual void strokeShape(GraphicsContext*) const;
-    virtual bool shapeDependentStrokeContains(const FloatPoint&);
-    virtual bool shapeDependentFillContains(const FloatPoint&, const WindRule) const;
+    virtual void updateShapeFromElement() OVERRIDE;
+    virtual bool isEmpty() const OVERRIDE { return m_usePathFallback ? RenderSVGShape::isEmpty() : m_fillBoundingBox.isEmpty(); }
+    virtual void fillShape(GraphicsContext*) const OVERRIDE;
+    virtual void strokeShape(GraphicsContext*) const OVERRIDE;
+    virtual bool shapeDependentStrokeContains(const FloatPoint&) OVERRIDE;
+    virtual bool shapeDependentFillContains(const FloatPoint&, const WindRule) const OVERRIDE;
 
 private:
     FloatRect m_innerStrokeRect;
diff --git a/Source/core/rendering/svg/RenderSVGResource.cpp b/Source/core/rendering/svg/RenderSVGResource.cpp
index 4dd3ae0..f6e7b7b 100644
--- a/Source/core/rendering/svg/RenderSVGResource.cpp
+++ b/Source/core/rendering/svg/RenderSVGResource.cpp
@@ -35,22 +35,25 @@
 
 namespace WebCore {
 
-static inline bool inheritColorFromParentStyleIfNeeded(RenderObject* object, bool applyToFill, Color& color)
+static inline bool inheritColorFromParentStyle(RenderObject* object, bool applyToFill, Color& color)
 {
-    if (color.isValid())
-        return true;
     if (!object->parent() || !object->parent()->style())
         return false;
     const SVGRenderStyle* parentSVGStyle = object->parent()->style()->svgStyle();
+    SVGPaint::SVGPaintType paintType = applyToFill ? parentSVGStyle->fillPaintType() : parentSVGStyle->strokePaintType();
+    if (paintType != SVGPaint::SVG_PAINTTYPE_RGBCOLOR && paintType != SVGPaint::SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR)
+        return false;
     color = applyToFill ? parentSVGStyle->fillPaintColor() : parentSVGStyle->strokePaintColor();
     return true;
 }
 
-static inline RenderSVGResource* requestPaintingResource(RenderSVGResourceMode mode, RenderObject* object, const RenderStyle* style, Color& fallbackColor)
+static inline RenderSVGResource* requestPaintingResource(RenderSVGResourceMode mode, RenderObject* object, const RenderStyle* style, bool& hasFallback)
 {
     ASSERT(object);
     ASSERT(style);
 
+    hasFallback = false;
+
     // If we have no style at all, ignore it.
     const SVGRenderStyle* svgStyle = style->svgStyle();
     if (!svgStyle)
@@ -82,6 +85,7 @@
         return 0;
 
     Color color;
+    bool hasColor = false;
     switch (paintType) {
     case SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR:
     case SVGPaint::SVG_PAINTTYPE_RGBCOLOR:
@@ -90,6 +94,7 @@
     case SVGPaint::SVG_PAINTTYPE_URI_RGBCOLOR:
     case SVGPaint::SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
         color = applyToFill ? svgStyle->fillPaintColor() : svgStyle->strokePaintColor();
+        hasColor = true;
     default:
         break;
     }
@@ -101,15 +106,15 @@
         // For SVG_PAINTTYPE_CURRENTCOLOR, 'color' already contains the 'visitedColor'.
         if (visitedPaintType < SVGPaint::SVG_PAINTTYPE_URI_NONE && visitedPaintType != SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR) {
             const Color& visitedColor = applyToFill ? svgStyle->visitedLinkFillPaintColor() : svgStyle->visitedLinkStrokePaintColor();
-            if (visitedColor.isValid())
-                color = Color(visitedColor.red(), visitedColor.green(), visitedColor.blue(), color.alpha());
+            color = Color(visitedColor.red(), visitedColor.green(), visitedColor.blue(), color.alpha());
+            hasColor = true;
         }
     }
 
     // If the primary resource is just a color, return immediately.
     RenderSVGResourceSolidColor* colorResource = RenderSVGResource::sharedSolidPaintingResource();
     if (paintType < SVGPaint::SVG_PAINTTYPE_URI_NONE) {
-        if (!inheritColorFromParentStyleIfNeeded(object, applyToFill, color))
+        if (!hasColor && !inheritColorFromParentStyle(object, applyToFill, color))
             return 0;
 
         colorResource->setColor(color);
@@ -119,7 +124,7 @@
     // If no resources are associated with the given renderer, return the color resource.
     SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(object);
     if (!resources) {
-        if (paintType == SVGPaint::SVG_PAINTTYPE_URI_NONE || !inheritColorFromParentStyleIfNeeded(object, applyToFill, color))
+        if (paintType == SVGPaint::SVG_PAINTTYPE_URI_NONE || (!hasColor && !inheritColorFromParentStyle(object, applyToFill, color)))
             return 0;
 
         colorResource->setColor(color);
@@ -129,7 +134,7 @@
     // If the requested resource is not available, return the color resource.
     RenderSVGResource* uriResource = mode == ApplyToFillMode ? resources->fill() : resources->stroke();
     if (!uriResource) {
-        if (!inheritColorFromParentStyleIfNeeded(object, applyToFill, color))
+        if (!hasColor && !inheritColorFromParentStyle(object, applyToFill, color))
             return 0;
 
         colorResource->setColor(color);
@@ -137,19 +142,22 @@
     }
 
     // The paint server resource exists, though it may be invalid (pattern with width/height=0). Pass the fallback color to our caller
-    // so it can use the solid color painting resource, if applyResource() on the URI resource failed.
-    fallbackColor = color;
+    // via sharedSolidPaintingResource so it can use the solid color painting resource, if applyResource() on the URI resource failed.
+    if (hasColor) {
+        colorResource->setColor(color);
+        hasFallback = true;
+    }
     return uriResource;
 }
 
-RenderSVGResource* RenderSVGResource::fillPaintingResource(RenderObject* object, const RenderStyle* style, Color& fallbackColor)
+RenderSVGResource* RenderSVGResource::fillPaintingResource(RenderObject* object, const RenderStyle* style, bool& hasFallback)
 {
-    return requestPaintingResource(ApplyToFillMode, object, style, fallbackColor);
+    return requestPaintingResource(ApplyToFillMode, object, style, hasFallback);
 }
 
-RenderSVGResource* RenderSVGResource::strokePaintingResource(RenderObject* object, const RenderStyle* style, Color& fallbackColor)
+RenderSVGResource* RenderSVGResource::strokePaintingResource(RenderObject* object, const RenderStyle* style, bool& hasFallback)
 {
-    return requestPaintingResource(ApplyToStrokeMode, object, style, fallbackColor);
+    return requestPaintingResource(ApplyToStrokeMode, object, style, hasFallback);
 }
 
 RenderSVGResourceSolidColor* RenderSVGResource::sharedSolidPaintingResource()
diff --git a/Source/core/rendering/svg/RenderSVGResource.h b/Source/core/rendering/svg/RenderSVGResource.h
index 676562d..0008f97 100644
--- a/Source/core/rendering/svg/RenderSVGResource.h
+++ b/Source/core/rendering/svg/RenderSVGResource.h
@@ -75,8 +75,9 @@
     }
 
     // Helper utilities used in the render tree to access resources used for painting shapes/text (gradients & patterns & solid colors only)
-    static RenderSVGResource* fillPaintingResource(RenderObject*, const RenderStyle*, Color& fallbackColor);
-    static RenderSVGResource* strokePaintingResource(RenderObject*, const RenderStyle*, Color& fallbackColor);
+    // If hasFallback gets set to true, the sharedSolidPaintingResource is set to a fallback color.
+    static RenderSVGResource* fillPaintingResource(RenderObject*, const RenderStyle*, bool& hasFallback);
+    static RenderSVGResource* strokePaintingResource(RenderObject*, const RenderStyle*, bool& hasFallback);
     static RenderSVGResourceSolidColor* sharedSolidPaintingResource();
 
     static void markForLayoutAndParentResourceInvalidation(RenderObject*, bool needsLayout = true);
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
index b98db0f..104230d 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
@@ -258,7 +258,10 @@
     ASSERT(context);
     ASSERT(frame());
 
-    context->beginRecording(repaintRectInLocalCoordinates());
+    // Using strokeBoundingBox (instead of repaintRectInLocalCoordinates) to avoid the intersection
+    // with local clips/mask, which may yield incorrect results when mixing objectBoundingBox and
+    // userSpaceOnUse units (http://crbug.com/294900).
+    context->beginRecording(strokeBoundingBox());
 
     // Switch to a paint behavior where all children of this <clipPath> will be rendered using special constraints:
     // - fill-opacity/stroke-opacity/opacity set to 1
@@ -353,7 +356,7 @@
     return false;
 }
 
-FloatRect RenderSVGResourceClipper::resourceBoundingBox(RenderObject* object)
+FloatRect RenderSVGResourceClipper::resourceBoundingBox(const RenderObject* object)
 {
     // Resource was not layouted yet. Give back the boundingBox of the object.
     if (selfNeedsLayout())
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.h b/Source/core/rendering/svg/RenderSVGResourceClipper.h
index ae89b1e..26da827 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.h
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.h
@@ -45,13 +45,13 @@
     explicit RenderSVGResourceClipper(SVGClipPathElement*);
     virtual ~RenderSVGResourceClipper();
 
-    virtual const char* renderName() const { return "RenderSVGResourceClipper"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGResourceClipper"; }
 
-    virtual void removeAllClientsFromCache(bool markForInvalidation = true);
-    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true);
+    virtual void removeAllClientsFromCache(bool markForInvalidation = true) OVERRIDE;
+    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true) OVERRIDE;
 
-    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE FINAL;
-    virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short, const Path*, const RenderSVGShape*) OVERRIDE FINAL;
+    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE;
+    virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short, const Path*, const RenderSVGShape*) OVERRIDE;
 
     // FIXME: Filters are also stateful resources that could benefit from having their state managed
     //        on the caller stack instead of the current hashmap. We should look at refactoring these
@@ -64,9 +64,9 @@
     // FIXME: We made applyClippingToContext public because we cannot call applyResource on HTML elements (it asserts on RenderObject::objectBoundingBox)
     bool applyClippingToContext(RenderObject*, const FloatRect&, const FloatRect&, GraphicsContext*, ClipperContext&);
 
-    FloatRect resourceBoundingBox(RenderObject*);
+    FloatRect resourceBoundingBox(const RenderObject*);
 
-    virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
+    virtual RenderSVGResourceType resourceType() const OVERRIDE { return s_resourceType; }
 
     bool hitTestClipContent(const FloatRect&, const FloatPoint&);
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
index 61c783d..0f7ac9b 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
@@ -149,8 +149,12 @@
         client->setNeedsBoundariesUpdate();
         break;
     case RepaintInvalidation:
-        if (client->view())
-            client->repaint();
+        if (client->view()) {
+            if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && frameView()->isInPerformLayout())
+                client->setShouldDoFullRepaintAfterLayout(true);
+            else
+                client->repaint();
+        }
         break;
     case ParentOnlyInvalidation:
         break;
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.h b/Source/core/rendering/svg/RenderSVGResourceContainer.h
index 71d3c6f..5bd1d42 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.h
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.h
@@ -33,7 +33,7 @@
     explicit RenderSVGResourceContainer(SVGElement*);
     virtual ~RenderSVGResourceContainer();
 
-    virtual void layout();
+    virtual void layout() OVERRIDE;
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
 
     virtual bool isSVGResourceContainer() const OVERRIDE FINAL { return true; }
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
index 9d4c578..08bb896 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
@@ -25,11 +25,12 @@
 
 #include "core/rendering/svg/RenderSVGResourceFilter.h"
 
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/svg/RenderSVGResourceFilterPrimitive.h"
 #include "core/rendering/svg/SVGRenderingContext.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "platform/graphics/UnacceleratedImageBufferSurface.h"
+#include "platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "platform/graphics/filters/SourceAlpha.h"
 #include "platform/graphics/filters/SourceGraphic.h"
 #include "platform/graphics/gpu/AcceleratedImageBufferSurface.h"
@@ -50,6 +51,11 @@
     m_filter.clear();
 }
 
+bool RenderSVGResourceFilter::isChildAllowed(RenderObject* child, RenderStyle*) const
+{
+    return child->isSVGResourceFilterPrimitive();
+}
+
 void RenderSVGResourceFilter::removeAllClientsFromCache(bool markForInvalidation)
 {
     m_filter.clear();
@@ -96,7 +102,7 @@
         effect->setEffectBoundaries(SVGLengthContext::resolveRectangle<SVGFilterPrimitiveStandardAttributes>(effectElement, filterElement->primitiveUnitsCurrentValue(), targetBoundingBox));
         effect->setOperatingColorSpace(
             effectElement->renderer()->style()->svgStyle()->colorInterpolationFilters() == CI_LINEARRGB ? ColorSpaceLinearRGB : ColorSpaceDeviceRGB);
-        builder->add(effectElement->resultCurrentValue(), effect);
+        builder->add(AtomicString(effectElement->result()->currentValue()->value()), effect);
     }
     return builder.release();
 }
@@ -104,22 +110,21 @@
 bool RenderSVGResourceFilter::fitsInMaximumImageSize(const FloatSize& size, FloatSize& scale)
 {
     bool matchesFilterSize = true;
-    if (size.width() > kMaxFilterSize) {
-        scale.setWidth(scale.width() * kMaxFilterSize / size.width());
+    if (size.width() * scale.width() > kMaxFilterSize) {
+        scale.setWidth(kMaxFilterSize / size.width());
         matchesFilterSize = false;
     }
-    if (size.height() > kMaxFilterSize) {
-        scale.setHeight(scale.height() * kMaxFilterSize / size.height());
+    if (size.height() * scale.height() > kMaxFilterSize) {
+        scale.setHeight(kMaxFilterSize / size.height());
         matchesFilterSize = false;
     }
 
     return matchesFilterSize;
 }
 
-static bool createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform,
-    OwnPtr<ImageBuffer>& imageBuffer, bool accelerated)
+static bool createImageBuffer(const Filter* filter, OwnPtr<ImageBuffer>& imageBuffer, bool accelerated)
 {
-    IntRect paintRect = SVGRenderingContext::calculateImageBufferRect(targetRect, absoluteTransform);
+    IntRect paintRect = filter->sourceImageRect();
     // Don't create empty ImageBuffers.
     if (paintRect.isEmpty())
         return false;
@@ -137,8 +142,7 @@
     ASSERT(imageContext);
 
     imageContext->translate(-paintRect.x(), -paintRect.y());
-    imageContext->concatCTM(absoluteTransform);
-
+    imageContext->concatCTM(filter->absoluteTransform());
     imageBuffer = image.release();
     return true;
 }
@@ -151,7 +155,11 @@
 
     clearInvalidationMask();
 
-    if (m_filter.contains(object)) {
+    bool deferredFiltersEnabled = object->document().settings()->deferredFiltersEnabled();
+    if (deferredFiltersEnabled) {
+        if (m_objects.contains(object))
+            return false; // We're in a cycle.
+    } else if (m_filter.contains(object)) {
         FilterData* filterData = m_filter.get(object);
         if (filterData->state == FilterData::PaintingSource || filterData->state == FilterData::Applying)
             filterData->state = FilterData::CycleDetected;
@@ -172,54 +180,77 @@
     if (!absoluteTransform.isInvertible())
         return false;
 
-    // Eliminate shear of the absolute transformation matrix, to be able to produce unsheared tile images for feTile.
-    filterData->shearFreeAbsoluteTransform = AffineTransform(absoluteTransform.xScale(), 0, 0, absoluteTransform.yScale(), 0, 0);
+    // Filters cannot handle a full transformation, only scales in each direction.
+    FloatSize filterScale;
 
-    // Determine absolute boundaries of the filter and the drawing region.
-    FloatRect absoluteFilterBoundaries = filterData->shearFreeAbsoluteTransform.mapRect(filterData->boundaries);
+    // Calculate the scale factor for the filter.
+    // Also see http://www.w3.org/TR/SVG/filters.html#FilterEffectsRegion
+    if (filterElement->hasAttribute(SVGNames::filterResAttr)) {
+        //  If resolution is specified, scale to match it.
+        filterScale = FloatSize(
+            filterElement->filterResX()->currentValue()->value() / filterData->boundaries.width(),
+            filterElement->filterResY()->currentValue()->value() / filterData->boundaries.height());
+    } else {
+        // Otherwise, use the scale of the absolute transform.
+        filterScale = FloatSize(absoluteTransform.xScale(), absoluteTransform.yScale());
+    }
+    // The size of the scaled filter boundaries shouldn't be bigger than kMaxFilterSize.
+    // Intermediate filters are limited by the filter boundaries so they can't be bigger than this.
+    fitsInMaximumImageSize(filterData->boundaries.size(), filterScale);
+
     filterData->drawingRegion = object->strokeBoundingBox();
     filterData->drawingRegion.intersect(filterData->boundaries);
-    FloatRect absoluteDrawingRegion = filterData->shearFreeAbsoluteTransform.mapRect(filterData->drawingRegion);
+    FloatRect absoluteDrawingRegion = filterData->drawingRegion;
+    if (!deferredFiltersEnabled)
+        absoluteDrawingRegion.scale(filterScale.width(), filterScale.height());
+
+    IntRect intDrawingRegion = enclosingIntRect(absoluteDrawingRegion);
 
     // Create the SVGFilter object.
     bool primitiveBoundingBoxMode = filterElement->primitiveUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX;
-    filterData->filter = SVGFilter::create(filterData->shearFreeAbsoluteTransform, absoluteDrawingRegion, targetBoundingBox, filterData->boundaries, primitiveBoundingBoxMode);
+    filterData->shearFreeAbsoluteTransform = AffineTransform();
+    if (!deferredFiltersEnabled)
+        filterData->shearFreeAbsoluteTransform.scale(filterScale.width(), filterScale.height());
+    filterData->filter = SVGFilter::create(filterData->shearFreeAbsoluteTransform, intDrawingRegion, targetBoundingBox, filterData->boundaries, primitiveBoundingBoxMode);
 
     // Create all relevant filter primitives.
     filterData->builder = buildPrimitives(filterData->filter.get());
     if (!filterData->builder)
         return false;
 
-    // Calculate the scale factor for the use of filterRes.
-    // Also see http://www.w3.org/TR/SVG/filters.html#FilterEffectsRegion
-    FloatSize scale(1, 1);
-    if (filterElement->hasAttribute(SVGNames::filterResAttr)) {
-        scale.setWidth(filterElement->filterResXCurrentValue() / absoluteFilterBoundaries.width());
-        scale.setHeight(filterElement->filterResYCurrentValue() / absoluteFilterBoundaries.height());
-    }
-
-    if (scale.isEmpty())
-        return false;
-
-    // Determine scale factor for filter. The size of intermediate ImageBuffers shouldn't be bigger than kMaxFilterSize.
-    FloatRect tempSourceRect = absoluteDrawingRegion;
-    tempSourceRect.scale(scale.width(), scale.height());
-    fitsInMaximumImageSize(tempSourceRect.size(), scale);
-
-    // Set the scale level in SVGFilter.
-    filterData->filter->setFilterResolution(scale);
-
     FilterEffect* lastEffect = filterData->builder->lastEffect();
     if (!lastEffect)
         return false;
 
     lastEffect->determineFilterPrimitiveSubregion(ClipToFilterRegion);
-    FloatRect subRegion = lastEffect->maxEffectRect();
-    // At least one FilterEffect has a too big image size,
-    // recalculate the effect sizes with new scale factors.
-    if (!fitsInMaximumImageSize(subRegion.size(), scale)) {
-        filterData->filter->setFilterResolution(scale);
-        lastEffect->determineFilterPrimitiveSubregion(ClipToFilterRegion);
+
+    if (deferredFiltersEnabled) {
+        SkiaImageFilterBuilder builder(context);
+        FloatRect oldBounds = context->getClipBounds();
+        m_objects.set(object, oldBounds);
+        RefPtr<ImageFilter> imageFilter = builder.build(lastEffect, ColorSpaceDeviceRGB);
+        FloatRect boundaries = enclosingIntRect(filterData->boundaries);
+        if (filterElement->hasAttribute(SVGNames::filterResAttr)) {
+            context->save();
+            // Get boundaries in device coords.
+            FloatSize size = context->getCTM().mapSize(boundaries.size());
+            // Compute the scale amount required so that the resulting offscreen is exactly filterResX by filterResY pixels.
+            FloatSize filterResScale(
+                filterElement->filterResX()->currentValue()->value() / size.width(),
+                filterElement->filterResY()->currentValue()->value() / size.height());
+            // Scale the CTM so the primitive is drawn to filterRes.
+            context->translate(boundaries.x(), boundaries.y());
+            context->scale(filterResScale);
+            context->translate(-boundaries.x(), -boundaries.y());
+            // Create a resize filter with the inverse scale.
+            imageFilter = builder.buildResize(1 / filterResScale.width(), 1 / filterResScale.height(), imageFilter.get());
+            // Clip the context so that the offscreen created in beginLayer()
+            // is clipped to filterResX by filerResY. Use Replace mode since
+            // this clip may be larger than the parent device.
+            context->clipRectReplace(boundaries);
+        }
+        context->beginLayer(1, CompositeSourceOver, &boundaries, ColorFilterNone, imageFilter.get());
+        return true;
     }
 
     // If the drawingRegion is empty, we have something like <g filter=".."/>.
@@ -231,14 +262,9 @@
         return false;
     }
 
-    // Change the coordinate transformation applied to the filtered element to reflect the resolution of the filter.
-    AffineTransform effectiveTransform;
-    effectiveTransform.scale(scale.width(), scale.height());
-    effectiveTransform.multiply(filterData->shearFreeAbsoluteTransform);
-
     OwnPtr<ImageBuffer> sourceGraphic;
     bool isAccelerated = object->document().settings()->acceleratedFiltersEnabled();
-    if (!createImageBuffer(filterData->drawingRegion, effectiveTransform, sourceGraphic, isAccelerated)) {
+    if (!createImageBuffer(filterData->filter.get(), sourceGraphic, isAccelerated)) {
         ASSERT(!m_filter.contains(object));
         filterData->savedContext = context;
         m_filter.set(object, filterData.release());
@@ -268,6 +294,23 @@
     ASSERT(context);
     ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
 
+    if (object->document().settings()->deferredFiltersEnabled()) {
+        SVGFilterElement* filterElement = toSVGFilterElement(element());
+        if (filterElement->hasAttribute(SVGNames::filterResAttr)) {
+            // Restore the clip bounds before endLayer(), so the filtered
+            // image draw is clipped to the original device bounds, not the
+            // clip we set before the beginLayer() above.
+            FloatRect oldBounds = m_objects.get(object);
+            context->clipRectReplace(oldBounds);
+            context->endLayer();
+            context->restore();
+        } else {
+            context->endLayer();
+        }
+        m_objects.remove(object);
+        return;
+    }
+
     FilterData* filterData = m_filter.get(object);
     if (!filterData)
         return;
@@ -319,19 +362,13 @@
 
         ImageBuffer* resultImage = lastEffect->asImageBuffer();
         if (resultImage) {
-            context->concatCTM(filterData->shearFreeAbsoluteTransform.inverse());
-
-            context->scale(FloatSize(1 / filterData->filter->filterResolution().width(), 1 / filterData->filter->filterResolution().height()));
-            context->drawImageBuffer(resultImage, lastEffect->absolutePaintRect());
-            context->scale(filterData->filter->filterResolution());
-
-            context->concatCTM(filterData->shearFreeAbsoluteTransform);
+            context->drawImageBuffer(resultImage, filterData->filter->mapAbsoluteRectToLocalRect(lastEffect->absolutePaintRect()));
         }
     }
     filterData->sourceGraphicBuffer.clear();
 }
 
-FloatRect RenderSVGResourceFilter::resourceBoundingBox(RenderObject* object)
+FloatRect RenderSVGResourceFilter::resourceBoundingBox(const RenderObject* object)
 {
     if (SVGFilterElement* element = toSVGFilterElement(this->element()))
         return SVGLengthContext::resolveRectangle<SVGFilterElement>(element, element->filterUnitsCurrentValue(), object->objectBoundingBox());
@@ -341,6 +378,12 @@
 
 void RenderSVGResourceFilter::primitiveAttributeChanged(RenderObject* object, const QualifiedName& attribute)
 {
+    if (object->document().settings()->deferredFiltersEnabled()) {
+        markAllClientsForInvalidation(RepaintInvalidation);
+        markAllClientLayersForInvalidation();
+        return;
+    }
+
     FilterMap::iterator it = m_filter.begin();
     FilterMap::iterator end = m_filter.end();
     SVGFilterPrimitiveStandardAttributes* primitve = static_cast<SVGFilterPrimitiveStandardAttributes*>(object->node());
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.h b/Source/core/rendering/svg/RenderSVGResourceFilter.h
index 6455b03..20af2f2 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.h
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.h
@@ -60,16 +60,18 @@
     explicit RenderSVGResourceFilter(SVGFilterElement*);
     virtual ~RenderSVGResourceFilter();
 
-    virtual const char* renderName() const { return "RenderSVGResourceFilter"; }
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
+
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGResourceFilter"; }
     virtual bool isSVGResourceFilter() const OVERRIDE { return true; }
 
-    virtual void removeAllClientsFromCache(bool markForInvalidation = true);
-    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true);
+    virtual void removeAllClientsFromCache(bool markForInvalidation = true) OVERRIDE;
+    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true) OVERRIDE;
 
-    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode);
-    virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*);
+    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE;
+    virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*) OVERRIDE;
 
-    FloatRect resourceBoundingBox(RenderObject*);
+    FloatRect resourceBoundingBox(const RenderObject*);
 
     PassRefPtr<SVGFilterBuilder> buildPrimitives(SVGFilter*);
 
@@ -78,7 +80,7 @@
 
     void primitiveAttributeChanged(RenderObject*, const QualifiedName&);
 
-    virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
+    virtual RenderSVGResourceType resourceType() const OVERRIDE { return s_resourceType; }
     static const RenderSVGResourceType s_resourceType;
 
     FloatRect drawingRegion(RenderObject*) const;
@@ -87,6 +89,10 @@
 
     typedef HashMap<RenderObject*, OwnPtr<FilterData> > FilterMap;
     FilterMap m_filter;
+
+    HashMap<RenderObject*, FloatRect> m_objects;
+
+    static bool s_deferredFilterRendering;
 };
 
 DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGResourceFilter, isSVGResourceFilter());
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h b/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h
index 704df3d..b2a293d 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h
+++ b/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h
@@ -38,10 +38,12 @@
     {
     }
 
-    virtual void styleDidChange(StyleDifference, const RenderStyle*);
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE { return false; }
 
-    virtual const char* renderName() const { return "RenderSVGResourceFilterPrimitive"; }
-    virtual bool isSVGResourceFilterPrimitive() const { return true; }
+    virtual void styleDidChange(StyleDifference, const RenderStyle*) OVERRIDE;
+
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGResourceFilterPrimitive"; }
+    virtual bool isSVGResourceFilterPrimitive() const OVERRIDE { return true; }
 
     inline void primitiveAttributeChanged(const QualifiedName& attribute)
     {
diff --git a/Source/core/rendering/svg/RenderSVGResourceGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
index 4e432a5..b26cdff 100644
--- a/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
@@ -81,7 +81,7 @@
     if (gradientUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX && objectBoundingBox.isEmpty())
         return false;
 
-    OwnPtr<GradientData>& gradientData = m_gradientMap.add(object, nullptr).iterator->value;
+    OwnPtr<GradientData>& gradientData = m_gradientMap.add(object, nullptr).storedValue->value;
     if (!gradientData)
         gradientData = adoptPtr(new GradientData);
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
index ba1c3d2..b829e40 100644
--- a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
+++ b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
@@ -33,15 +33,15 @@
     explicit RenderSVGResourceLinearGradient(SVGLinearGradientElement*);
     virtual ~RenderSVGResourceLinearGradient();
 
-    virtual const char* renderName() const { return "RenderSVGResourceLinearGradient"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGResourceLinearGradient"; }
 
-    virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
+    virtual RenderSVGResourceType resourceType() const OVERRIDE { return s_resourceType; }
     static const RenderSVGResourceType s_resourceType;
 
-    virtual SVGUnitTypes::SVGUnitType gradientUnits() const { return m_attributes.gradientUnits(); }
-    virtual void calculateGradientTransform(AffineTransform& transform) { transform = m_attributes.gradientTransform(); }
-    virtual bool collectGradientAttributes(SVGGradientElement*);
-    virtual void buildGradient(GradientData*) const;
+    virtual SVGUnitTypes::SVGUnitType gradientUnits() const OVERRIDE { return m_attributes.gradientUnits(); }
+    virtual void calculateGradientTransform(AffineTransform& transform) OVERRIDE { transform = m_attributes.gradientTransform(); }
+    virtual bool collectGradientAttributes(SVGGradientElement*) OVERRIDE;
+    virtual void buildGradient(GradientData*) const OVERRIDE;
 
     FloatPoint startPoint(const LinearGradientAttributes&) const;
     FloatPoint endPoint(const LinearGradientAttributes&) const;
diff --git a/Source/core/rendering/svg/RenderSVGResourceMarker.cpp b/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
index d3de3b7..e8943ca 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
@@ -52,10 +52,6 @@
     LayoutRectRecorder recorder(*this);
     TemporaryChange<bool> inLayoutChange(m_isInLayout, true);
 
-    // Invalidate all resources if our layout changed.
-    if (everHadLayout() && selfNeedsLayout())
-        removeAllClientsFromCache();
-
     // RenderSVGHiddenContainer overwrites layout(). We need the
     // layouting of RenderSVGContainer for calculating  local
     // transformations and repaint.
@@ -105,7 +101,7 @@
     ASSERT(marker);
 
     SVGLengthContext lengthContext(marker);
-    return FloatPoint(marker->refXCurrentValue().value(lengthContext), marker->refYCurrentValue().value(lengthContext));
+    return FloatPoint(marker->refX()->currentValue()->value(lengthContext), marker->refY()->currentValue()->value(lengthContext));
 }
 
 float RenderSVGResourceMarker::angle() const
@@ -142,12 +138,15 @@
     // An empty viewBox disables rendering.
     SVGMarkerElement* marker = toSVGMarkerElement(element());
     ASSERT(marker);
-    if (marker->hasAttribute(SVGNames::viewBoxAttr) && marker->viewBoxCurrentValue().isValid() && marker->viewBoxCurrentValue().isEmpty())
+    if (marker->hasAttribute(SVGNames::viewBoxAttr) && marker->viewBox()->currentValue()->isValid() && marker->viewBox()->currentValue()->value().isEmpty())
         return;
 
     PaintInfo info(paintInfo);
-    GraphicsContextStateSaver stateSaver(*info.context);
-    info.applyTransform(transform);
+    GraphicsContextStateSaver stateSaver(*info.context, false);
+    if (!transform.isIdentity()) {
+        stateSaver.save();
+        info.applyTransform(transform, false);
+    }
     RenderSVGContainer::paint(info, IntPoint());
 }
 
@@ -181,8 +180,8 @@
     ASSERT(marker);
 
     SVGLengthContext lengthContext(marker);
-    float w = marker->markerWidthCurrentValue().value(lengthContext);
-    float h = marker->markerHeightCurrentValue().value(lengthContext);
+    float w = marker->markerWidth()->currentValue()->value(lengthContext);
+    float h = marker->markerHeight()->currentValue()->value(lengthContext);
     m_viewport = FloatRect(0, 0, w, h);
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceMarker.h b/Source/core/rendering/svg/RenderSVGResourceMarker.h
index 625b37a..0305065 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMarker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMarker.h
@@ -36,30 +36,30 @@
     explicit RenderSVGResourceMarker(SVGMarkerElement*);
     virtual ~RenderSVGResourceMarker();
 
-    virtual const char* renderName() const { return "RenderSVGResourceMarker"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGResourceMarker"; }
 
-    virtual void removeAllClientsFromCache(bool markForInvalidation = true);
-    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true);
+    virtual void removeAllClientsFromCache(bool markForInvalidation = true) OVERRIDE;
+    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true) OVERRIDE;
 
     void draw(PaintInfo&, const AffineTransform&);
 
     // Calculates marker boundaries, mapped to the target element's coordinate space
     FloatRect markerBoundaries(const AffineTransform& markerTransformation) const;
 
-    virtual void applyViewportClip(PaintInfo&);
-    virtual void layout();
-    virtual void calcViewport();
+    virtual void applyViewportClip(PaintInfo&) OVERRIDE;
+    virtual void layout() OVERRIDE;
+    virtual void calcViewport() OVERRIDE;
 
-    virtual const AffineTransform& localToParentTransform() const;
+    virtual const AffineTransform& localToParentTransform() const OVERRIDE;
     AffineTransform markerTransformation(const FloatPoint& origin, float angle, float strokeWidth) const;
 
-    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short) { return false; }
+    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short) OVERRIDE { return false; }
 
     FloatPoint referencePoint() const;
     float angle() const;
     SVGMarkerUnitsType markerUnits() const { return toSVGMarkerElement(element())->markerUnitsCurrentValue(); }
 
-    virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
+    virtual RenderSVGResourceType resourceType() const OVERRIDE { return s_resourceType; }
     static const RenderSVGResourceType s_resourceType;
 
 private:
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
index 43c64ca..85a5775 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
@@ -133,7 +133,10 @@
 {
     ASSERT(context);
 
-    context->beginRecording(repaintRectInLocalCoordinates());
+    // Using strokeBoundingBox (instead of repaintRectInLocalCoordinates) to avoid the intersection
+    // with local clips/mask, which may yield incorrect results when mixing objectBoundingBox and
+    // userSpaceOnUse units (http://crbug.com/294900).
+    context->beginRecording(strokeBoundingBox());
     for (Node* childNode = element()->firstChild(); childNode; childNode = childNode->nextSibling()) {
         RenderObject* renderer = childNode->renderer();
         if (!childNode->isSVGElement() || !renderer)
@@ -161,7 +164,7 @@
     }
 }
 
-FloatRect RenderSVGResourceMasker::resourceBoundingBox(RenderObject* object)
+FloatRect RenderSVGResourceMasker::resourceBoundingBox(const RenderObject* object)
 {
     SVGMaskElement* maskElement = toSVGMaskElement(element());
     ASSERT(maskElement);
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.h b/Source/core/rendering/svg/RenderSVGResourceMasker.h
index 2af5275..d4476f8 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.h
@@ -40,18 +40,18 @@
     explicit RenderSVGResourceMasker(SVGMaskElement*);
     virtual ~RenderSVGResourceMasker();
 
-    virtual const char* renderName() const { return "RenderSVGResourceMasker"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGResourceMasker"; }
 
-    virtual void removeAllClientsFromCache(bool markForInvalidation = true);
-    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true);
+    virtual void removeAllClientsFromCache(bool markForInvalidation = true) OVERRIDE;
+    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true) OVERRIDE;
     virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE;
     virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short, const Path*, const RenderSVGShape*) OVERRIDE;
-    FloatRect resourceBoundingBox(RenderObject*);
+    FloatRect resourceBoundingBox(const RenderObject*);
 
     SVGUnitTypes::SVGUnitType maskUnits() const { return toSVGMaskElement(element())->maskUnitsCurrentValue(); }
     SVGUnitTypes::SVGUnitType maskContentUnits() const { return toSVGMaskElement(element())->maskContentUnitsCurrentValue(); }
 
-    virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
+    virtual RenderSVGResourceType resourceType() const OVERRIDE { return s_resourceType; }
     static const RenderSVGResourceType s_resourceType;
 
 private:
diff --git a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
index c107a79..353e454 100644
--- a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
@@ -53,6 +53,7 @@
 
 PatternData* RenderSVGResourcePattern::buildPattern(RenderObject* object, unsigned short resourceMode)
 {
+    ASSERT(object);
     PatternData* currentData = m_patternMap.get(object);
     if (currentData && currentData->pattern)
         return currentData;
@@ -128,7 +129,7 @@
     // Various calls above may trigger invalidations in some fringe cases (ImageBuffer allocation
     // failures in the SVG image cache for example). To avoid having our PatternData deleted by
     // removeAllClientsFromCache(), we only make it visible in the cache at the very end.
-    return m_patternMap.set(object, patternData.release()).iterator->value.get();
+    return m_patternMap.set(object, patternData.release()).storedValue->value.get();
 }
 
 bool RenderSVGResourcePattern::applyResource(RenderObject* object, RenderStyle* style, GraphicsContext*& context, unsigned short resourceMode)
diff --git a/Source/core/rendering/svg/RenderSVGResourcePattern.h b/Source/core/rendering/svg/RenderSVGResourcePattern.h
index 56a8318..e9468ef 100644
--- a/Source/core/rendering/svg/RenderSVGResourcePattern.h
+++ b/Source/core/rendering/svg/RenderSVGResourcePattern.h
@@ -46,15 +46,15 @@
 public:
     explicit RenderSVGResourcePattern(SVGPatternElement*);
 
-    virtual const char* renderName() const { return "RenderSVGResourcePattern"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGResourcePattern"; }
 
-    virtual void removeAllClientsFromCache(bool markForInvalidation = true);
-    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true);
+    virtual void removeAllClientsFromCache(bool markForInvalidation = true) OVERRIDE;
+    virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true) OVERRIDE;
 
-    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode);
-    virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*);
+    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE;
+    virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*) OVERRIDE;
 
-    virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
+    virtual RenderSVGResourceType resourceType() const OVERRIDE { return s_resourceType; }
     static const RenderSVGResourceType s_resourceType;
 
 private:
diff --git a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
index 43ee076..1f9145a 100644
--- a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
+++ b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
@@ -33,15 +33,15 @@
     explicit RenderSVGResourceRadialGradient(SVGRadialGradientElement*);
     virtual ~RenderSVGResourceRadialGradient();
 
-    virtual const char* renderName() const { return "RenderSVGResourceRadialGradient"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGResourceRadialGradient"; }
 
-    virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
+    virtual RenderSVGResourceType resourceType() const OVERRIDE { return s_resourceType; }
     static const RenderSVGResourceType s_resourceType;
 
-    virtual SVGUnitTypes::SVGUnitType gradientUnits() const { return m_attributes.gradientUnits(); }
-    virtual void calculateGradientTransform(AffineTransform& transform) { transform = m_attributes.gradientTransform(); }
-    virtual bool collectGradientAttributes(SVGGradientElement*);
-    virtual void buildGradient(GradientData*) const;
+    virtual SVGUnitTypes::SVGUnitType gradientUnits() const OVERRIDE { return m_attributes.gradientUnits(); }
+    virtual void calculateGradientTransform(AffineTransform& transform) OVERRIDE { transform = m_attributes.gradientTransform(); }
+    virtual bool collectGradientAttributes(SVGGradientElement*) OVERRIDE;
+    virtual void buildGradient(GradientData*) const OVERRIDE;
 
     FloatPoint centerPoint(const RadialGradientAttributes&) const;
     FloatPoint focalPoint(const RadialGradientAttributes&) const;
diff --git a/Source/core/rendering/svg/RenderSVGResourceSolidColor.h b/Source/core/rendering/svg/RenderSVGResourceSolidColor.h
index 85937ce..3583a0d 100644
--- a/Source/core/rendering/svg/RenderSVGResourceSolidColor.h
+++ b/Source/core/rendering/svg/RenderSVGResourceSolidColor.h
@@ -26,18 +26,18 @@
 
 namespace WebCore {
 
-class RenderSVGResourceSolidColor : public RenderSVGResource {
+class RenderSVGResourceSolidColor FINAL : public RenderSVGResource {
 public:
     RenderSVGResourceSolidColor();
     virtual ~RenderSVGResourceSolidColor();
 
-    virtual void removeAllClientsFromCache(bool = true) { }
-    virtual void removeClientFromCache(RenderObject*, bool = true) { }
+    virtual void removeAllClientsFromCache(bool = true) OVERRIDE { }
+    virtual void removeClientFromCache(RenderObject*, bool = true) OVERRIDE { }
 
-    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode);
-    virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*);
+    virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE;
+    virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*) OVERRIDE;
 
-    virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
+    virtual RenderSVGResourceType resourceType() const OVERRIDE { return s_resourceType; }
     static const RenderSVGResourceType s_resourceType;
 
     const Color& color() const { return m_color; }
diff --git a/Source/core/rendering/svg/RenderSVGRoot.cpp b/Source/core/rendering/svg/RenderSVGRoot.cpp
index b318d5b..ecdad3d 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.cpp
+++ b/Source/core/rendering/svg/RenderSVGRoot.cpp
@@ -25,10 +25,7 @@
 
 #include "core/rendering/svg/RenderSVGRoot.h"
 
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/LayoutRectRecorder.h"
 #include "core/rendering/LayoutRepainter.h"
@@ -41,6 +38,7 @@
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGSVGElement.h"
 #include "core/svg/graphics/SVGImage.h"
+#include "platform/LengthFunctions.h"
 #include "platform/graphics/GraphicsContext.h"
 
 using namespace std;
@@ -82,9 +80,9 @@
     //   resolving both values to user units.
     if (intrinsicWidthAttribute.isFixed() || intrinsicHeightAttribute.isFixed()) {
         if (intrinsicWidthAttribute.isFixed())
-            intrinsicSize.setWidth(floatValueForLength(intrinsicWidthAttribute, 0, 0));
+            intrinsicSize.setWidth(floatValueForLength(intrinsicWidthAttribute, 0));
         if (intrinsicHeightAttribute.isFixed())
-            intrinsicSize.setHeight(floatValueForLength(intrinsicHeightAttribute, 0, 0));
+            intrinsicSize.setHeight(floatValueForLength(intrinsicHeightAttribute, 0));
         if (!intrinsicSize.isEmpty())
             intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
         return;
@@ -94,7 +92,7 @@
     //   aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG document
     //   fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
     //   calculated and is considered unspecified.
-    intrinsicSize = svg->viewBoxCurrentValue().size();
+    intrinsicSize = svg->viewBox()->currentValue()->value().size();
     if (!intrinsicSize.isEmpty()) {
         // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
         intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
@@ -131,9 +129,9 @@
     return frame->document()->isSVGDocument();
 }
 
-static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize, RenderView* renderView)
+static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize)
 {
-    return static_cast<LayoutUnit>(valueForLength(length, maxSize, renderView) * (length.isFixed() ? scale : 1));
+    return static_cast<LayoutUnit>(valueForLength(length, maxSize) * (length.isFixed() ? scale : 1));
 }
 
 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
@@ -149,7 +147,7 @@
         return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
 
     if (svg->widthAttributeEstablishesViewport())
-        return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth(), view());
+        return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth());
 
     // SVG embedded through object/embed/iframe.
     if (isEmbeddedThroughFrameContainingSVGDocument())
@@ -183,7 +181,7 @@
         } else
             RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
 
-        return resolveLengthAttributeForSVG(height, style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding), view());
+        return resolveLengthAttributeForSVG(height, style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding));
     }
 
     // SVG embedded through object/embed/iframe.
@@ -261,7 +259,7 @@
     childPaintInfo.context->save();
 
     // Apply initial viewport clip - not affected by overflow handling
-    childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset, paintInfo.renderRegion)));
+    childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset)));
 
     // Convert from container offsets (html renderers) to a relative transform (svg renderers).
     // Transform from our paint container's coordinate system to our local coords.
@@ -302,6 +300,11 @@
     SVGResourcesCache::clientStyleChanged(this, diff, style());
 }
 
+bool RenderSVGRoot::isChildAllowed(RenderObject* child, RenderStyle*) const
+{
+    return child->isSVG() && !(child->isSVGInline() || child->isSVGInlineText());
+}
+
 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
 {
     RenderReplaced::addChild(child, beforeChild);
@@ -333,10 +336,10 @@
     SVGSVGElement* svg = toSVGSVGElement(node());
     ASSERT(svg);
     float scale = style()->effectiveZoom();
-    SVGPoint translate = svg->currentTranslate();
+    FloatPoint translate = svg->currentTranslate();
     LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
     m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
-    if (borderAndPadding.isEmpty() && scale == 1 && translate == SVGPoint::zero())
+    if (borderAndPadding.isEmpty() && scale == 1 && translate == FloatPoint::zero())
         return;
     m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
 }
@@ -431,14 +434,6 @@
     return false;
 }
 
-bool RenderSVGRoot::hasRelativeDimensions() const
-{
-    SVGSVGElement* svg = toSVGSVGElement(node());
-    ASSERT(svg);
-
-    return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent() || svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent();
-}
-
 bool RenderSVGRoot::hasRelativeIntrinsicLogicalWidth() const
 {
     SVGSVGElement* svg = toSVGSVGElement(node());
diff --git a/Source/core/rendering/svg/RenderSVGRoot.h b/Source/core/rendering/svg/RenderSVGRoot.h
index c28ed7e..d549044 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.h
+++ b/Source/core/rendering/svg/RenderSVGRoot.h
@@ -40,7 +40,7 @@
     bool isEmbeddedThroughSVGImage() const;
     bool isEmbeddedThroughFrameContainingSVGDocument() const;
 
-    virtual void computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const;
+    virtual void computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const OVERRIDE;
 
     RenderObject* firstChild() const { ASSERT(children() == virtualChildren()); return children()->firstChild(); }
     RenderObject* lastChild() const { ASSERT(children() == virtualChildren()); return children()->lastChild(); }
@@ -49,14 +49,12 @@
     RenderObjectChildList* children() { return &m_children; }
 
     bool isLayoutSizeChanged() const { return m_isLayoutSizeChanged; }
-    virtual void setNeedsBoundariesUpdate() { m_needsBoundariesOrTransformUpdate = true; }
-    virtual bool needsBoundariesUpdate() OVERRIDE { return m_needsBoundariesOrTransformUpdate; }
-    virtual void setNeedsTransformUpdate() { m_needsBoundariesOrTransformUpdate = true; }
+    virtual void setNeedsBoundariesUpdate() OVERRIDE { m_needsBoundariesOrTransformUpdate = true; }
+    virtual void setNeedsTransformUpdate() OVERRIDE { m_needsBoundariesOrTransformUpdate = true; }
 
     IntSize containerSize() const { return m_containerSize; }
     void setContainerSize(const IntSize& containerSize) { m_containerSize = containerSize; }
 
-    virtual bool hasRelativeDimensions() const OVERRIDE;
     virtual bool hasRelativeIntrinsicLogicalWidth() const OVERRIDE;
     virtual bool hasRelativeLogicalHeight() const OVERRIDE;
 
@@ -64,33 +62,33 @@
     const AffineTransform& localToBorderBoxTransform() const { return m_localToBorderBoxTransform; }
 
 private:
-    virtual RenderObjectChildList* virtualChildren() { return children(); }
-    virtual const RenderObjectChildList* virtualChildren() const { return children(); }
+    virtual RenderObjectChildList* virtualChildren() OVERRIDE { return children(); }
+    virtual const RenderObjectChildList* virtualChildren() const OVERRIDE { return children(); }
 
-    virtual bool isSVGRoot() const { return true; }
-    virtual const char* renderName() const { return "RenderSVGRoot"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGRoot"; }
+    virtual bool isSVGRoot() const OVERRIDE { return true; }
+    virtual bool isSVG() const OVERRIDE { return true; }
 
     virtual LayoutUnit computeReplacedLogicalWidth(ShouldComputePreferred  = ComputeActual) const OVERRIDE;
-    virtual LayoutUnit computeReplacedLogicalHeight() const;
-    virtual void layout();
-    virtual void paintReplaced(PaintInfo&, const LayoutPoint&);
+    virtual LayoutUnit computeReplacedLogicalHeight() const OVERRIDE;
+    virtual void layout() OVERRIDE;
+    virtual void paintReplaced(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
-    virtual void willBeDestroyed();
-    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+    virtual void willBeDestroyed() OVERRIDE;
+    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
     virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
     virtual void removeChild(RenderObject*) OVERRIDE;
+    virtual bool canHaveWhitespaceChildren() const OVERRIDE { return false; }
 
     virtual void insertedIntoTree() OVERRIDE;
     virtual void willBeRemovedFromTree() OVERRIDE;
 
-    virtual const AffineTransform& localToParentTransform() const;
+    virtual const AffineTransform& localToParentTransform() const OVERRIDE;
 
-    bool fillContains(const FloatPoint&) const;
-    bool strokeContains(const FloatPoint&) const;
-
-    virtual FloatRect objectBoundingBox() const { return m_objectBoundingBox; }
-    virtual FloatRect strokeBoundingBox() const { return m_strokeBoundingBox; }
-    virtual FloatRect repaintRectInLocalCoordinates() const { return m_repaintBoundingBox; }
+    virtual FloatRect objectBoundingBox() const OVERRIDE { return m_objectBoundingBox; }
+    virtual FloatRect strokeBoundingBox() const OVERRIDE { return m_strokeBoundingBox; }
+    virtual FloatRect repaintRectInLocalCoordinates() const OVERRIDE { return m_repaintBoundingBox; }
 
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 
@@ -100,8 +98,8 @@
     virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE;
     virtual const RenderObject* pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&) const OVERRIDE;
 
-    virtual bool canBeSelectionLeaf() const { return false; }
-    virtual bool canHaveChildren() const { return true; }
+    virtual bool canBeSelectionLeaf() const OVERRIDE { return false; }
+    virtual bool canHaveChildren() const OVERRIDE { return true; }
 
     void updateCachedBoundaries();
     void buildLocalToBorderBoxTransform();
diff --git a/Source/core/rendering/svg/RenderSVGShape.cpp b/Source/core/rendering/svg/RenderSVGShape.cpp
index 04298f7..21655ff 100644
--- a/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -119,8 +119,8 @@
     if (!m_fillBoundingBox.contains(point))
         return false;
 
-    Color fallbackColor;
-    if (requiresFill && !RenderSVGResource::fillPaintingResource(this, style(), fallbackColor))
+    bool hasFallback;
+    if (requiresFill && !RenderSVGResource::fillPaintingResource(this, style(), hasFallback))
         return false;
 
     return shapeDependentFillContains(point, fillRule);
@@ -131,8 +131,8 @@
     if (!strokeBoundingBox().contains(point))
         return false;
 
-    Color fallbackColor;
-    if (requiresStroke && !RenderSVGResource::strokePaintingResource(this, style(), fallbackColor))
+    bool hasFallback;
+    if (requiresStroke && !RenderSVGResource::strokePaintingResource(this, style(), hasFallback))
         return false;
 
     return shapeDependentStrokeContains(point);
@@ -213,13 +213,12 @@
 
 void RenderSVGShape::fillShape(RenderStyle* style, GraphicsContext* context)
 {
-    Color fallbackColor;
-    if (RenderSVGResource* fillPaintingResource = RenderSVGResource::fillPaintingResource(this, style, fallbackColor)) {
-        if (fillPaintingResource->applyResource(this, style, context, ApplyToFillMode))
+    bool hasFallback;
+    if (RenderSVGResource* fillPaintingResource = RenderSVGResource::fillPaintingResource(this, style, hasFallback)) {
+        if (fillPaintingResource->applyResource(this, style, context, ApplyToFillMode)) {
             fillPaintingResource->postApplyResource(this, context, ApplyToFillMode, 0, this);
-        else if (fallbackColor.isValid()) {
+        } else if (hasFallback) {
             RenderSVGResourceSolidColor* fallbackResource = RenderSVGResource::sharedSolidPaintingResource();
-            fallbackResource->setColor(fallbackColor);
             if (fallbackResource->applyResource(this, style, context, ApplyToFillMode))
                 fallbackResource->postApplyResource(this, context, ApplyToFillMode, 0, this);
         }
@@ -228,13 +227,12 @@
 
 void RenderSVGShape::strokeShape(RenderStyle* style, GraphicsContext* context)
 {
-    Color fallbackColor;
-    if (RenderSVGResource* strokePaintingResource = RenderSVGResource::strokePaintingResource(this, style, fallbackColor)) {
-        if (strokePaintingResource->applyResource(this, style, context, ApplyToStrokeMode))
+    bool hasFallback;
+    if (RenderSVGResource* strokePaintingResource = RenderSVGResource::strokePaintingResource(this, style, hasFallback)) {
+        if (strokePaintingResource->applyResource(this, style, context, ApplyToStrokeMode)) {
             strokePaintingResource->postApplyResource(this, context, ApplyToStrokeMode, 0, this);
-        else if (fallbackColor.isValid()) {
+        } else if (hasFallback) {
             RenderSVGResourceSolidColor* fallbackResource = RenderSVGResource::sharedSolidPaintingResource();
-            fallbackResource->setColor(fallbackColor);
             if (fallbackResource->applyResource(this, style, context, ApplyToStrokeMode))
                 fallbackResource->postApplyResource(this, context, ApplyToStrokeMode, 0, this);
         }
@@ -425,13 +423,13 @@
 float RenderSVGShape::strokeWidth() const
 {
     SVGLengthContext lengthContext(element());
-    return style()->svgStyle()->strokeWidth().value(lengthContext);
+    return style()->svgStyle()->strokeWidth()->value(lengthContext);
 }
 
 bool RenderSVGShape::hasSmoothStroke() const
 {
     const SVGRenderStyle* svgStyle = style()->svgStyle();
-    return svgStyle->strokeDashArray().isEmpty()
+    return svgStyle->strokeDashArray()->isEmpty()
         && svgStyle->strokeMiterLimit() == svgStyle->initialStrokeMiterLimit()
         && svgStyle->joinStyle() == svgStyle->initialJoinStyle()
         && svgStyle->capStyle() == svgStyle->initialCapStyle();
diff --git a/Source/core/rendering/svg/RenderSVGShape.h b/Source/core/rendering/svg/RenderSVGShape.h
index f800b2d..ca41092 100644
--- a/Source/core/rendering/svg/RenderSVGShape.h
+++ b/Source/core/rendering/svg/RenderSVGShape.h
@@ -51,7 +51,6 @@
 
     void setNeedsShapeUpdate() { m_needsShapeUpdate = true; }
     virtual void setNeedsBoundariesUpdate() OVERRIDE FINAL { m_needsBoundariesUpdate = true; }
-    virtual bool needsBoundariesUpdate() OVERRIDE FINAL { return m_needsBoundariesUpdate; }
     virtual void setNeedsTransformUpdate() OVERRIDE FINAL { m_needsTransformUpdate = true; }
     virtual void fillShape(GraphicsContext*) const;
     virtual void strokeShape(GraphicsContext*) const;
@@ -66,7 +65,7 @@
 
 protected:
     virtual void updateShapeFromElement();
-    virtual bool isEmpty() const;
+    virtual bool isEmpty() const OVERRIDE;
     virtual bool shapeDependentStrokeContains(const FloatPoint&);
     virtual bool shapeDependentFillContains(const FloatPoint&, const WindRule) const;
     float strokeWidth() const;
@@ -90,7 +89,7 @@
     virtual AffineTransform localTransform() const OVERRIDE FINAL { return m_localTransform; }
 
     virtual bool isSVGShape() const OVERRIDE FINAL { return true; }
-    virtual const char* renderName() const { return "RenderSVGShape"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGShape"; }
 
     virtual void layout() OVERRIDE FINAL;
     virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE FINAL;
@@ -116,7 +115,6 @@
 
 private:
     FloatRect m_repaintBoundingBox;
-    FloatRect m_repaintBoundingBoxExcludingShadow;
     AffineTransform m_localTransform;
     OwnPtr<Path> m_path;
     Vector<MarkerPosition> m_markerPositions;
diff --git a/Source/core/rendering/svg/RenderSVGTSpan.cpp b/Source/core/rendering/svg/RenderSVGTSpan.cpp
index 5f34538..9c71d54 100644
--- a/Source/core/rendering/svg/RenderSVGTSpan.cpp
+++ b/Source/core/rendering/svg/RenderSVGTSpan.cpp
@@ -24,6 +24,9 @@
 
 #include "core/rendering/svg/RenderSVGTSpan.h"
 
+#include "SVGNames.h"
+#include "core/rendering/svg/SVGRenderSupport.h"
+
 namespace WebCore {
 
 RenderSVGTSpan::RenderSVGTSpan(Element* element)
@@ -31,4 +34,19 @@
 {
 }
 
+bool RenderSVGTSpan::isChildAllowed(RenderObject* child, RenderStyle*) const
+{
+    // Always allow text (except empty textnodes and <br>).
+    if (child->isText())
+        return SVGRenderSupport::isRenderableTextNode(child);
+
+#if ENABLE(SVG_FONTS)
+    // Only allow other types of  children if this is not an 'altGlyph'.
+    if (node()->hasTagName(SVGNames::altGlyphTag))
+        return false;
+#endif
+
+    return child->isSVGInline() && !child->isSVGTextPath();
+}
+
 }
diff --git a/Source/core/rendering/svg/RenderSVGTSpan.h b/Source/core/rendering/svg/RenderSVGTSpan.h
index ba8cb31..7875119 100644
--- a/Source/core/rendering/svg/RenderSVGTSpan.h
+++ b/Source/core/rendering/svg/RenderSVGTSpan.h
@@ -28,7 +28,10 @@
 class RenderSVGTSpan FINAL : public RenderSVGInline {
 public:
     explicit RenderSVGTSpan(Element*);
-    virtual const char* renderName() const { return "RenderSVGTSpan"; }
+
+    virtual bool isChildAllowed(RenderObject* child, RenderStyle*) const OVERRIDE;
+
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGTSpan"; }
 };
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGText.cpp b/Source/core/rendering/svg/RenderSVGText.cpp
index ba45ce9..0a97525 100644
--- a/Source/core/rendering/svg/RenderSVGText.cpp
+++ b/Source/core/rendering/svg/RenderSVGText.cpp
@@ -70,7 +70,7 @@
 
 bool RenderSVGText::isChildAllowed(RenderObject* child, RenderStyle*) const
 {
-    return child->isInline() && !SVGRenderSupport::isEmptySVGInlineText(child);
+    return child->isSVGInline() || (child->isText() && SVGRenderSupport::isRenderableTextNode(child));
 }
 
 RenderSVGText* RenderSVGText::locateRenderSVGTextAncestor(RenderObject* start)
@@ -93,11 +93,6 @@
     return toRenderSVGText(start);
 }
 
-LayoutRect RenderSVGText::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
-{
-    return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
-}
-
 void RenderSVGText::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
 {
     FloatRect repaintRect = rect;
@@ -105,21 +100,6 @@
     rect = enclosingLayoutRect(repaintRect);
 }
 
-void RenderSVGText::computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
-{
-    SVGRenderSupport::computeFloatRectForRepaint(this, repaintContainer, repaintRect, fixed);
-}
-
-void RenderSVGText::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags, bool* wasFixed) const
-{
-    SVGRenderSupport::mapLocalToContainer(this, repaintContainer, transformState, wasFixed);
-}
-
-const RenderObject* RenderSVGText::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
-{
-    return SVGRenderSupport::pushMappingToContainer(this, ancestorToStopAt, geometryMap);
-}
-
 static inline void collectLayoutAttributes(RenderObject* text, Vector<SVGTextLayoutAttributes*>& attributes)
 {
     for (RenderObject* descendant = text; descendant; descendant = descendant->nextInPreOrder(text)) {
@@ -128,14 +108,15 @@
     }
 }
 
-static inline bool findPreviousAndNextAttributes(RenderObject* start, RenderSVGInlineText* locateElement, bool& stopAfterNext, SVGTextLayoutAttributes*& previous, SVGTextLayoutAttributes*& next)
+static inline bool findPreviousAndNextAttributes(RenderObject* root, RenderSVGInlineText* locateElement, SVGTextLayoutAttributes*& previous, SVGTextLayoutAttributes*& next)
 {
-    ASSERT(start);
+    ASSERT(root);
     ASSERT(locateElement);
-    // FIXME: Make this iterative.
-    for (RenderObject* child = start->firstChild(); child; child = child->nextSibling()) {
-        if (child->isSVGInlineText()) {
-            RenderSVGInlineText* text = toRenderSVGInlineText(child);
+    bool stopAfterNext = false;
+    RenderObject* current = root->firstChild();
+    while (current) {
+        if (current->isSVGInlineText()) {
+            RenderSVGInlineText* text = toRenderSVGInlineText(current);
             if (locateElement != text) {
                 if (stopAfterNext) {
                     next = text->layoutAttributes();
@@ -143,20 +124,19 @@
                 }
 
                 previous = text->layoutAttributes();
+            } else {
+                stopAfterNext = true;
+            }
+        } else if (current->isSVGInline()) {
+            // Descend into text content (if possible).
+            if (RenderObject* child = current->firstChild()) {
+                current = child;
                 continue;
             }
-
-            stopAfterNext = true;
-            continue;
         }
 
-        if (!child->isSVGInline())
-            continue;
-
-        if (findPreviousAndNextAttributes(child, locateElement, stopAfterNext, previous, next))
-            return true;
+        current = current->nextInPreOrderAfterChildren(root);
     }
-
     return false;
 }
 
@@ -201,11 +181,10 @@
         attributes = newLayoutAttributes[i];
         if (m_layoutAttributes.find(attributes) == kNotFound) {
             // Every time this is invoked, there's only a single new entry in the newLayoutAttributes list, compared to the old in m_layoutAttributes.
-            bool stopAfterNext = false;
             SVGTextLayoutAttributes* previous = 0;
             SVGTextLayoutAttributes* next = 0;
             ASSERT_UNUSED(child, attributes->context() == child);
-            findPreviousAndNextAttributes(this, attributes->context(), stopAfterNext, previous, next);
+            findPreviousAndNextAttributes(this, attributes->context(), previous, next);
 
             if (previous)
                 m_layoutAttributesBuilder.buildLayoutAttributesForTextRenderer(previous->context());
@@ -258,11 +237,10 @@
 
     // This logic requires that the 'text' child is still inserted in the tree.
     RenderSVGInlineText* text = toRenderSVGInlineText(child);
-    bool stopAfterNext = false;
     SVGTextLayoutAttributes* previous = 0;
     SVGTextLayoutAttributes* next = 0;
     if (!documentBeingDestroyed())
-        findPreviousAndNextAttributes(this, text, stopAfterNext, previous, next);
+        findPreviousAndNextAttributes(this, text, previous, next);
 
     if (previous)
         affectedAttributes.append(previous);
@@ -408,7 +386,16 @@
     // FIXME: We need to find a way to only layout the child boxes, if needed.
     FloatRect oldBoundaries = objectBoundingBox();
     ASSERT(childrenInline());
-    forceLayoutInlineChildren();
+
+    rebuildFloatsFromIntruding();
+
+    LayoutUnit beforeEdge = borderBefore() + paddingBefore();
+    LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
+    setLogicalHeight(beforeEdge);
+
+    LayoutUnit repaintLogicalTop = 0;
+    LayoutUnit repaintLogicalBottom = 0;
+    layoutInlineChildren(true, repaintLogicalTop, repaintLogicalBottom, afterEdge);
 
     if (m_needsReordering)
         m_needsReordering = false;
@@ -458,12 +445,6 @@
     return false;
 }
 
-bool RenderSVGText::nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation&, const LayoutPoint&, HitTestAction)
-{
-    ASSERT_NOT_REACHED();
-    return false;
-}
-
 PositionWithAffinity RenderSVGText::positionForPoint(const LayoutPoint& pointInContents)
 {
     RootInlineBox* rootBox = firstRootBox();
@@ -496,8 +477,12 @@
          return;
 
     PaintInfo blockInfo(paintInfo);
-    GraphicsContextStateSaver stateSaver(*blockInfo.context);
-    blockInfo.applyTransform(localToParentTransform());
+    GraphicsContextStateSaver stateSaver(*blockInfo.context, false);
+    const AffineTransform& localTransform = localToParentTransform();
+    if (!localTransform.isIdentity()) {
+        stateSaver.save();
+        blockInfo.applyTransform(localTransform, false);
+    }
     RenderBlock::paint(blockInfo, LayoutPoint());
 }
 
@@ -511,7 +496,7 @@
     ASSERT(node());
     ASSERT(node()->isSVGElement());
     SVGLengthContext lengthContext(toSVGElement(node()));
-    strokeBoundaries.inflate(svgStyle->strokeWidth().value(lengthContext));
+    strokeBoundaries.inflate(svgStyle->strokeWidth()->value(lengthContext));
     return strokeBoundaries;
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGText.h b/Source/core/rendering/svg/RenderSVGText.h
index 56fb0db..76bc693 100644
--- a/Source/core/rendering/svg/RenderSVGText.h
+++ b/Source/core/rendering/svg/RenderSVGText.h
@@ -37,12 +37,12 @@
     explicit RenderSVGText(SVGTextElement*);
     virtual ~RenderSVGText();
 
-    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const;
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
 
     void setNeedsPositioningValuesUpdate() { m_needsPositioningValuesUpdate = true; }
-    virtual void setNeedsTransformUpdate() { m_needsTransformUpdate = true; }
+    virtual void setNeedsTransformUpdate() OVERRIDE { m_needsTransformUpdate = true; }
     void setNeedsTextMetricsUpdate() { m_needsTextMetricsUpdate = true; }
-    virtual FloatRect repaintRectInLocalCoordinates() const;
+    virtual FloatRect repaintRectInLocalCoordinates() const OVERRIDE;
 
     static RenderSVGText* locateRenderSVGTextAncestor(RenderObject*);
     static const RenderSVGText* locateRenderSVGTextAncestor(const RenderObject*);
@@ -57,38 +57,31 @@
     void subtreeTextDidChange(RenderSVGInlineText*);
 
 private:
-    virtual const char* renderName() const { return "RenderSVGText"; }
-    virtual bool isSVGText() const { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGText"; }
+    virtual bool isSVGText() const OVERRIDE { return true; }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&);
-    virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
-    virtual bool nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint& pointInParent, HitTestAction);
-    virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE FINAL;
+    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
+    virtual bool nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint& pointInParent, HitTestAction) OVERRIDE;
+    virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE;
 
-    virtual bool requiresLayer() const { return false; }
-    virtual void layout();
+    virtual void layout() OVERRIDE;
 
-    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
+    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const OVERRIDE;
 
-    virtual LayoutRect clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const OVERRIDE;
     virtual void computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect&, bool fixed = false) const OVERRIDE;
-    virtual void computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect&, bool fixed = false) const OVERRIDE;
 
-    virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE;
-    virtual const RenderObject* pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&) const OVERRIDE;
-    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0);
+    virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
     virtual void removeChild(RenderObject*) OVERRIDE;
     virtual void willBeDestroyed() OVERRIDE;
 
-    virtual FloatRect objectBoundingBox() const { return frameRect(); }
-    virtual FloatRect strokeBoundingBox() const;
+    virtual FloatRect objectBoundingBox() const OVERRIDE { return frameRect(); }
+    virtual FloatRect strokeBoundingBox() const OVERRIDE;
 
-    virtual const AffineTransform& localToParentTransform() const { return m_localTransform; }
-    virtual AffineTransform localTransform() const { return m_localTransform; }
-    virtual RootInlineBox* createRootInlineBox();
+    virtual const AffineTransform& localToParentTransform() const OVERRIDE { return m_localTransform; }
+    virtual RootInlineBox* createRootInlineBox() OVERRIDE;
 
-    virtual RenderBlock* firstLineBlock() const;
-    virtual void updateFirstLetter();
+    virtual RenderBlock* firstLineBlock() const OVERRIDE;
+    virtual void updateFirstLetter() OVERRIDE;
 
     bool shouldHandleSubtreeMutations() const;
 
@@ -96,7 +89,6 @@
     bool m_needsPositioningValuesUpdate : 1;
     bool m_needsTransformUpdate : 1;
     bool m_needsTextMetricsUpdate : 1;
-    AffineTransform m_localTransform;
     SVGTextLayoutAttributesBuilder m_layoutAttributesBuilder;
     Vector<SVGTextLayoutAttributes*> m_layoutAttributes;
 };
diff --git a/Source/core/rendering/svg/RenderSVGTextPath.cpp b/Source/core/rendering/svg/RenderSVGTextPath.cpp
index f2068b8..26d2055 100644
--- a/Source/core/rendering/svg/RenderSVGTextPath.cpp
+++ b/Source/core/rendering/svg/RenderSVGTextPath.cpp
@@ -23,6 +23,7 @@
 
 #include "SVGNames.h"
 #include "core/rendering/svg/SVGPathData.h"
+#include "core/rendering/svg/SVGRenderSupport.h"
 #include "core/svg/SVGPathElement.h"
 #include "core/svg/SVGTextPathElement.h"
 
@@ -33,10 +34,24 @@
 {
 }
 
+bool RenderSVGTextPath::isChildAllowed(RenderObject* child, RenderStyle*) const
+{
+    if (child->isText())
+        return SVGRenderSupport::isRenderableTextNode(child);
+
+#if ENABLE(SVG_FONTS)
+    // 'altGlyph' is supported by the content model for 'textPath', but...
+    if (child->node()->hasTagName(SVGNames::altGlyphTag))
+        return false;
+#endif
+
+    return child->isSVGInline() && !child->isSVGTextPath();
+}
+
 Path RenderSVGTextPath::layoutPath() const
 {
     SVGTextPathElement* textPathElement = toSVGTextPathElement(node());
-    Element* targetElement = SVGURIReference::targetElementFromIRIString(textPathElement->hrefCurrentValue(), textPathElement->document());
+    Element* targetElement = SVGURIReference::targetElementFromIRIString(textPathElement->href()->currentValue()->value(), textPathElement->document());
     if (!targetElement || !targetElement->hasTagName(SVGNames::pathTag))
         return Path();
 
@@ -56,17 +71,7 @@
 
 float RenderSVGTextPath::startOffset() const
 {
-    return toSVGTextPathElement(node())->startOffsetCurrentValue().valueAsPercentage();
-}
-
-bool RenderSVGTextPath::exactAlignment() const
-{
-    return toSVGTextPathElement(node())->spacingCurrentValue() == SVGTextPathSpacingExact;
-}
-
-bool RenderSVGTextPath::stretchMethod() const
-{
-    return toSVGTextPathElement(node())->methodCurrentValue() == SVGTextPathMethodStretch;
+    return toSVGTextPathElement(node())->startOffset()->currentValue()->valueAsPercentage();
 }
 
 }
diff --git a/Source/core/rendering/svg/RenderSVGTextPath.h b/Source/core/rendering/svg/RenderSVGTextPath.h
index ba9ad79..6d98871 100644
--- a/Source/core/rendering/svg/RenderSVGTextPath.h
+++ b/Source/core/rendering/svg/RenderSVGTextPath.h
@@ -31,13 +31,13 @@
 
     Path layoutPath() const;
     float startOffset() const;
-    bool exactAlignment() const;
-    bool stretchMethod() const;
 
-    virtual bool isSVGTextPath() const { return true; }
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
+
+    virtual bool isSVGTextPath() const OVERRIDE { return true; }
 
 private:
-    virtual const char* renderName() const { return "RenderSVGTextPath"; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGTextPath"; }
 
     Path m_layoutPath;
 };
diff --git a/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp b/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp
index 52516c4..c55400c 100644
--- a/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp
@@ -37,6 +37,37 @@
 {
 }
 
+static bool hasValidPredecessor(const Node* node)
+{
+    ASSERT(node);
+    while ((node = node->previousSibling())) {
+        if (node->isSVGElement() && toSVGElement(node)->isValid())
+            return true;
+    }
+    return false;
+}
+
+bool RenderSVGTransformableContainer::isChildAllowed(RenderObject* child, RenderStyle* style) const
+{
+    if (element()->hasTagName(SVGNames::switchTag)) {
+        Node* node = child->node();
+        // Reject non-SVG/non-valid elements.
+        if (!node->isSVGElement() || !toSVGElement(node)->isValid())
+            return false;
+        // Reject this child if it isn't the first valid node.
+        if (hasValidPredecessor(node))
+            return false;
+    } else if (element()->hasTagName(SVGNames::aTag)) {
+        // http://www.w3.org/2003/01/REC-SVG11-20030114-errata#linking-text-environment
+        // The 'a' element may contain any element that its parent may contain, except itself.
+        if (child->node()->hasTagName(SVGNames::aTag))
+            return false;
+        if (parent() && parent()->isSVG())
+            return parent()->isChildAllowed(child, style);
+    }
+    return RenderSVGContainer::isChildAllowed(child, style);
+}
+
 bool RenderSVGTransformableContainer::calculateLocalTransform()
 {
     SVGGraphicsElement* element = toSVGGraphicsElement(this->element());
@@ -55,7 +86,9 @@
 
     if (useElement) {
         SVGLengthContext lengthContext(useElement);
-        FloatSize translation(useElement->xCurrentValue().value(lengthContext), useElement->yCurrentValue().value(lengthContext));
+        FloatSize translation(
+            useElement->x()->currentValue()->value(lengthContext),
+            useElement->y()->currentValue()->value(lengthContext));
         if (translation != m_lastTranslation)
             m_needsTransformUpdate = true;
         m_lastTranslation = translation;
diff --git a/Source/core/rendering/svg/RenderSVGTransformableContainer.h b/Source/core/rendering/svg/RenderSVGTransformableContainer.h
index 6aa752a..4b03d8a 100644
--- a/Source/core/rendering/svg/RenderSVGTransformableContainer.h
+++ b/Source/core/rendering/svg/RenderSVGTransformableContainer.h
@@ -30,14 +30,16 @@
 public:
     explicit RenderSVGTransformableContainer(SVGGraphicsElement*);
 
-    virtual bool isSVGTransformableContainer() const { return true; }
-    virtual const AffineTransform& localToParentTransform() const { return m_localTransform; }
-    virtual void setNeedsTransformUpdate() { m_needsTransformUpdate = true; }
-    virtual bool didTransformToRootUpdate() { return m_didTransformToRootUpdate; }
+    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
+
+    virtual bool isSVGTransformableContainer() const OVERRIDE { return true; }
+    virtual const AffineTransform& localToParentTransform() const OVERRIDE { return m_localTransform; }
+    virtual void setNeedsTransformUpdate() OVERRIDE { m_needsTransformUpdate = true; }
+    virtual bool didTransformToRootUpdate() OVERRIDE { return m_didTransformToRootUpdate; }
 
 private:
-    virtual bool calculateLocalTransform();
-    virtual AffineTransform localTransform() const { return m_localTransform; }
+    virtual bool calculateLocalTransform() OVERRIDE;
+    virtual AffineTransform localTransform() const OVERRIDE { return m_localTransform; }
 
     bool m_needsTransformUpdate : 1;
     bool m_didTransformToRootUpdate : 1;
diff --git a/Source/core/rendering/svg/RenderSVGViewportContainer.cpp b/Source/core/rendering/svg/RenderSVGViewportContainer.cpp
index 05234c1..63fa495 100644
--- a/Source/core/rendering/svg/RenderSVGViewportContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGViewportContainer.cpp
@@ -63,7 +63,7 @@
     FloatRect oldViewport = m_viewport;
 
     SVGLengthContext lengthContext(element);
-    m_viewport = FloatRect(svg->xCurrentValue().value(lengthContext), svg->yCurrentValue().value(lengthContext), svg->widthCurrentValue().value(lengthContext), svg->heightCurrentValue().value(lengthContext));
+    m_viewport = FloatRect(svg->x()->currentValue()->value(lengthContext), svg->y()->currentValue()->value(lengthContext), svg->width()->currentValue()->value(lengthContext), svg->height()->currentValue()->value(lengthContext));
 
     SVGElement* correspondingElement = svg->correspondingElement();
     if (correspondingElement && svg->isInShadowTree()) {
@@ -97,17 +97,19 @@
 
         SVGLengthContext lengthContext(element);
         if (useElement->hasAttribute(SVGNames::widthAttr))
-            m_viewport.setWidth(useElement->widthCurrentValue().value(lengthContext));
+            m_viewport.setWidth(useElement->width()->currentValue()->value(lengthContext));
         else if (isSymbolElement && svg->hasAttribute(SVGNames::widthAttr)) {
-            SVGLength containerWidth(LengthModeWidth, "100%");
-            m_viewport.setWidth(containerWidth.value(lengthContext));
+            RefPtr<SVGLength> containerWidth = SVGLength::create(LengthModeWidth);
+            containerWidth->setValueAsString("100%", ASSERT_NO_EXCEPTION);
+            m_viewport.setWidth(containerWidth->value(lengthContext));
         }
 
         if (useElement->hasAttribute(SVGNames::heightAttr))
-            m_viewport.setHeight(useElement->heightCurrentValue().value(lengthContext));
+            m_viewport.setHeight(useElement->height()->currentValue()->value(lengthContext));
         else if (isSymbolElement && svg->hasAttribute(SVGNames::heightAttr)) {
-            SVGLength containerHeight(LengthModeHeight, "100%");
-            m_viewport.setHeight(containerHeight.value(lengthContext));
+            RefPtr<SVGLength> containerHeight = SVGLength::create(LengthModeHeight);
+            containerHeight->setValueAsString("100%", ASSERT_NO_EXCEPTION);
+            m_viewport.setHeight(containerHeight->value(lengthContext));
         }
     }
 
diff --git a/Source/core/rendering/svg/RenderSVGViewportContainer.h b/Source/core/rendering/svg/RenderSVGViewportContainer.h
index b1b79ed..679bd05 100644
--- a/Source/core/rendering/svg/RenderSVGViewportContainer.h
+++ b/Source/core/rendering/svg/RenderSVGViewportContainer.h
@@ -35,25 +35,25 @@
     FloatRect viewport() const { return m_viewport; }
 
     bool isLayoutSizeChanged() const { return m_isLayoutSizeChanged; }
-    virtual bool didTransformToRootUpdate() { return m_didTransformToRootUpdate; }
+    virtual bool didTransformToRootUpdate() OVERRIDE { return m_didTransformToRootUpdate; }
 
-    virtual void determineIfLayoutSizeChanged();
-    virtual void setNeedsTransformUpdate() { m_needsTransformUpdate = true; }
+    virtual void determineIfLayoutSizeChanged() OVERRIDE;
+    virtual void setNeedsTransformUpdate() OVERRIDE { m_needsTransformUpdate = true; }
 
     virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
 private:
-    virtual bool isSVGViewportContainer() const { return true; }
-    virtual const char* renderName() const { return "RenderSVGViewportContainer"; }
+    virtual bool isSVGViewportContainer() const OVERRIDE { return true; }
+    virtual const char* renderName() const OVERRIDE { return "RenderSVGViewportContainer"; }
 
     AffineTransform viewportTransform() const;
-    virtual const AffineTransform& localToParentTransform() const { return m_localToParentTransform; }
+    virtual const AffineTransform& localToParentTransform() const OVERRIDE { return m_localToParentTransform; }
 
-    virtual void calcViewport();
-    virtual bool calculateLocalTransform();
+    virtual void calcViewport() OVERRIDE;
+    virtual bool calculateLocalTransform() OVERRIDE;
 
-    virtual void applyViewportClip(PaintInfo&);
-    virtual bool pointIsInsideViewportClip(const FloatPoint& pointInParent);
+    virtual void applyViewportClip(PaintInfo&) OVERRIDE;
+    virtual bool pointIsInsideViewportClip(const FloatPoint& pointInParent) OVERRIDE;
 
     FloatRect m_viewport;
     mutable AffineTransform m_localToParentTransform;
diff --git a/Source/core/rendering/svg/SVGInlineFlowBox.cpp b/Source/core/rendering/svg/SVGInlineFlowBox.cpp
index c4f5cdb..1832911 100644
--- a/Source/core/rendering/svg/SVGInlineFlowBox.cpp
+++ b/Source/core/rendering/svg/SVGInlineFlowBox.cpp
@@ -23,8 +23,6 @@
 #include "config.h"
 #include "core/rendering/svg/SVGInlineFlowBox.h"
 
-#include "core/dom/DocumentMarkerController.h"
-#include "core/dom/RenderedDocumentMarker.h"
 #include "core/rendering/svg/RenderSVGInlineText.h"
 #include "core/rendering/svg/SVGInlineTextBox.h"
 #include "core/rendering/svg/SVGRenderingContext.h"
@@ -47,7 +45,7 @@
     }
 }
 
-void SVGInlineFlowBox::paint(PaintInfo& paintInfo, const LayoutPoint&, LayoutUnit, LayoutUnit)
+void SVGInlineFlowBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit, LayoutUnit)
 {
     ASSERT(paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection);
     ASSERT(!paintInfo.context->paintingDisabled());
@@ -57,12 +55,8 @@
 
     SVGRenderingContext renderingContext(boxRenderer, paintInfo, SVGRenderingContext::SaveGraphicsContext);
     if (renderingContext.isRenderingPrepared()) {
-        for (InlineBox* child = firstChild(); child; child = child->nextOnLine()) {
-            if (child->isSVGInlineTextBox())
-                computeTextMatchMarkerRectForRenderer(toRenderSVGInlineText(toSVGInlineTextBox(child)->textRenderer()));
-
-            child->paint(paintInfo, LayoutPoint(), 0, 0);
-        }
+        for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
+            child->paint(paintInfo, paintOffset, 0, 0);
     }
 }
 
@@ -77,66 +71,4 @@
     return childRect;
 }
 
-void SVGInlineFlowBox::computeTextMatchMarkerRectForRenderer(RenderSVGInlineText* textRenderer)
-{
-    ASSERT(textRenderer);
-
-    Node* node = textRenderer->node();
-    if (!node || !node->inDocument())
-        return;
-
-    RenderStyle* style = textRenderer->style();
-    ASSERT(style);
-
-    AffineTransform fragmentTransform;
-    Document& document = textRenderer->document();
-    Vector<DocumentMarker*> markers = document.markers()->markersFor(textRenderer->node());
-
-    Vector<DocumentMarker*>::iterator markerEnd = markers.end();
-    for (Vector<DocumentMarker*>::iterator markerIt = markers.begin(); markerIt != markerEnd; ++markerIt) {
-        DocumentMarker* marker = *markerIt;
-
-        // SVG is only interessted in the TextMatch marker, for now.
-        if (marker->type() != DocumentMarker::TextMatch)
-            continue;
-
-        FloatRect markerRect;
-        for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
-            if (!box->isSVGInlineTextBox())
-                continue;
-
-            SVGInlineTextBox* textBox = toSVGInlineTextBox(box);
-
-            int markerStartPosition = max<int>(marker->startOffset() - textBox->start(), 0);
-            int markerEndPosition = min<int>(marker->endOffset() - textBox->start(), textBox->len());
-
-            if (markerStartPosition >= markerEndPosition)
-                continue;
-
-            int fragmentStartPosition = 0;
-            int fragmentEndPosition = 0;
-
-            const Vector<SVGTextFragment>& fragments = textBox->textFragments();
-            unsigned textFragmentsSize = fragments.size();
-            for (unsigned i = 0; i < textFragmentsSize; ++i) {
-                const SVGTextFragment& fragment = fragments.at(i);
-
-                fragmentStartPosition = markerStartPosition;
-                fragmentEndPosition = markerEndPosition;
-                if (!textBox->mapStartEndPositionsIntoFragmentCoordinates(fragment, fragmentStartPosition, fragmentEndPosition))
-                    continue;
-
-                FloatRect fragmentRect = textBox->selectionRectForTextFragment(fragment, fragmentStartPosition, fragmentEndPosition, style);
-                fragment.buildFragmentTransform(fragmentTransform);
-                if (!fragmentTransform.isIdentity())
-                    fragmentRect = fragmentTransform.mapRect(fragmentRect);
-
-                markerRect.unite(fragmentRect);
-            }
-        }
-
-        toRenderedDocumentMarker(marker)->setRenderedRect(textRenderer->localToAbsoluteQuad(markerRect).enclosingBoundingBox());
-    }
-}
-
 } // namespace WebCore
diff --git a/Source/core/rendering/svg/SVGInlineFlowBox.h b/Source/core/rendering/svg/SVGInlineFlowBox.h
index e76a9cc..b215b1f 100644
--- a/Source/core/rendering/svg/SVGInlineFlowBox.h
+++ b/Source/core/rendering/svg/SVGInlineFlowBox.h
@@ -35,16 +35,14 @@
     {
     }
 
-    virtual bool isSVGInlineFlowBox() const { return true; }
-    virtual float virtualLogicalHeight() const { return m_logicalHeight; }
+    virtual bool isSVGInlineFlowBox() const OVERRIDE { return true; }
+    virtual float virtualLogicalHeight() const OVERRIDE { return m_logicalHeight; }
     void setLogicalHeight(float h) { m_logicalHeight = h; }
 
     void paintSelectionBackground(PaintInfo&);
-    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom);
+    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
 
-    virtual FloatRect calculateBoundaries() const;
-
-    static void computeTextMatchMarkerRectForRenderer(RenderSVGInlineText*);
+    virtual FloatRect calculateBoundaries() const OVERRIDE;
 
 private:
     float m_logicalHeight;
diff --git a/Source/core/rendering/svg/SVGInlineTextBox.cpp b/Source/core/rendering/svg/SVGInlineTextBox.cpp
index 6c59382..df21423 100644
--- a/Source/core/rendering/svg/SVGInlineTextBox.cpp
+++ b/Source/core/rendering/svg/SVGInlineTextBox.cpp
@@ -22,11 +22,15 @@
 #include "config.h"
 #include "core/rendering/svg/SVGInlineTextBox.h"
 
+#include "core/dom/DocumentMarkerController.h"
+#include "core/dom/RenderedDocumentMarker.h"
+#include "core/editing/Editor.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/InlineFlowBox.h"
 #include "core/rendering/PointerEventsHitRules.h"
+#include "core/rendering/RenderTheme.h"
 #include "core/rendering/style/ShadowList.h"
 #include "core/rendering/svg/RenderSVGInlineText.h"
 #include "core/rendering/svg/RenderSVGResource.h"
@@ -184,7 +188,7 @@
 {
     // Font::pixelSize(), returns FontDescription::computedPixelSize(), which returns "int(x + 0.5)".
     // If the absolute font size on screen is below x=0.5, don't render anything.
-    return textRenderer->scaledFont().pixelSize();
+    return textRenderer->scaledFont().fontDescription().computedPixelSize();
 }
 
 void SVGInlineTextBox::paintSelectionBackground(PaintInfo& paintInfo)
@@ -207,7 +211,7 @@
         return;
 
     Color backgroundColor = renderer()->selectionBackgroundColor();
-    if (!backgroundColor.isValid() || !backgroundColor.alpha())
+    if (!backgroundColor.alpha())
         return;
 
     RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer());
@@ -218,13 +222,6 @@
     RenderStyle* style = parentRenderer->style();
     ASSERT(style);
 
-    RenderStyle* selectionStyle = style;
-    if (hasSelection) {
-        selectionStyle = parentRenderer->getCachedPseudoStyle(SELECTION);
-        if (!selectionStyle)
-            selectionStyle = style;
-    }
-
     int startPosition, endPosition;
     selectionStartEnd(startPosition, endPosition);
 
@@ -255,7 +252,7 @@
     ASSERT(!m_paintingResource);
 }
 
-void SVGInlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint&, LayoutUnit, LayoutUnit)
+void SVGInlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit, LayoutUnit)
 {
     ASSERT(paintInfo.shouldPaintWithinRoot(renderer()));
     ASSERT(paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection);
@@ -283,6 +280,8 @@
     RenderStyle* style = parentRenderer->style();
     ASSERT(style);
 
+    paintDocumentMarkers(paintInfo.context, paintOffset, style, textRenderer->scaledFont(), true);
+
     const SVGRenderStyle* svgStyle = style->svgStyle();
     ASSERT(svgStyle);
 
@@ -315,10 +314,12 @@
         SVGTextFragment& fragment = m_textFragments.at(i);
         ASSERT(!m_paintingResource);
 
-        GraphicsContextStateSaver stateSaver(*paintInfo.context);
+        GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
         fragment.buildFragmentTransform(fragmentTransform);
-        if (!fragmentTransform.isIdentity())
+        if (!fragmentTransform.isIdentity()) {
+            stateSaver.save();
             paintInfo.context->concatCTM(fragmentTransform);
+        }
 
         // Spec: All text decorations except line-through should be drawn before the text is filled and stroked; thus, the text is rendered on top of these decorations.
         unsigned decorations = style->textDecorationsInEffect();
@@ -364,16 +365,17 @@
 
 bool SVGInlineTextBox::acquirePaintingResource(GraphicsContext*& context, float scalingFactor, RenderObject* renderer, RenderStyle* style)
 {
+    // Callers must save the context state before calling when scalingFactor is not 1.
     ASSERT(scalingFactor);
     ASSERT(renderer);
     ASSERT(style);
     ASSERT(m_paintingResourceMode != ApplyToDefaultMode);
 
-    Color fallbackColor;
+    bool hasFallback;
     if (m_paintingResourceMode & ApplyToFillMode)
-        m_paintingResource = RenderSVGResource::fillPaintingResource(renderer, style, fallbackColor);
+        m_paintingResource = RenderSVGResource::fillPaintingResource(renderer, style, hasFallback);
     else if (m_paintingResourceMode & ApplyToStrokeMode)
-        m_paintingResource = RenderSVGResource::strokePaintingResource(renderer, style, fallbackColor);
+        m_paintingResource = RenderSVGResource::strokePaintingResource(renderer, style, hasFallback);
     else {
         // We're either called for stroking or filling.
         ASSERT_NOT_REACHED();
@@ -383,11 +385,8 @@
         return false;
 
     if (!m_paintingResource->applyResource(renderer, style, context, m_paintingResourceMode)) {
-        if (fallbackColor.isValid()) {
-            RenderSVGResourceSolidColor* fallbackResource = RenderSVGResource::sharedSolidPaintingResource();
-            fallbackResource->setColor(fallbackColor);
-
-            m_paintingResource = fallbackResource;
+        if (hasFallback) {
+            m_paintingResource = RenderSVGResource::sharedSolidPaintingResource();
             m_paintingResource->applyResource(renderer, style, context, m_paintingResourceMode);
         }
     }
@@ -523,7 +522,7 @@
 {
     // FIXME: For SVG Fonts we need to use the attributes defined in the <font-face> if specified.
     // Compatible with Batik/Opera
-    return font.size() / 20.0f;
+    return font.fontDescription().computedSize() / 20.0f;
 }
 
 static inline RenderObject* findRenderObjectDefininingTextDecoration(InlineFlowBox* parentBox)
@@ -596,8 +595,9 @@
     float width = fragment.width;
     const FontMetrics& scaledFontMetrics = scaledFont.fontMetrics();
 
-    GraphicsContextStateSaver stateSaver(*context);
+    GraphicsContextStateSaver stateSaver(*context, false);
     if (scalingFactor != 1) {
+        stateSaver.save();
         width *= scalingFactor;
         decorationOrigin.scale(scalingFactor, scalingFactor);
         context->scale(FloatSize(1 / scalingFactor, 1 / scalingFactor));
@@ -608,6 +608,8 @@
     Path path;
     path.addRect(FloatRect(decorationOrigin, FloatSize(width, thickness)));
 
+    // acquirePaintingResource also modifies state if the scalingFactor is non-identity.
+    // Above we have saved the state for this case.
     if (acquirePaintingResource(context, scalingFactor, decorationRenderer, decorationStyle))
         releasePaintingResource(context, &path);
 }
@@ -701,6 +703,69 @@
         paintTextWithShadows(context, style, textRun, fragment, endPosition, fragment.length);
 }
 
+void SVGInlineTextBox::paintDocumentMarker(GraphicsContext*, const FloatPoint&, DocumentMarker*, RenderStyle*, const Font&, bool)
+{
+    // SVG does not have support for generic document markers (e.g., spellchecking, etc).
+}
+
+void SVGInlineTextBox::paintTextMatchMarker(GraphicsContext* context, const FloatPoint&, DocumentMarker* marker, RenderStyle* style, const Font& font)
+{
+    // SVG is only interested in the TextMatch markers.
+    if (marker->type() != DocumentMarker::TextMatch)
+        return;
+
+    RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer());
+    ASSERT(textRenderer);
+
+    FloatRect markerRect;
+    AffineTransform fragmentTransform;
+    for (InlineTextBox* box = textRenderer->firstTextBox(); box; box = box->nextTextBox()) {
+        if (!box->isSVGInlineTextBox())
+            continue;
+
+        SVGInlineTextBox* textBox = toSVGInlineTextBox(box);
+
+        int markerStartPosition = max<int>(marker->startOffset() - textBox->start(), 0);
+        int markerEndPosition = min<int>(marker->endOffset() - textBox->start(), textBox->len());
+
+        if (markerStartPosition >= markerEndPosition)
+            continue;
+
+        const Vector<SVGTextFragment>& fragments = textBox->textFragments();
+        unsigned textFragmentsSize = fragments.size();
+        for (unsigned i = 0; i < textFragmentsSize; ++i) {
+            const SVGTextFragment& fragment = fragments.at(i);
+
+            int fragmentStartPosition = markerStartPosition;
+            int fragmentEndPosition = markerEndPosition;
+            if (!textBox->mapStartEndPositionsIntoFragmentCoordinates(fragment, fragmentStartPosition, fragmentEndPosition))
+                continue;
+
+            FloatRect fragmentRect = textBox->selectionRectForTextFragment(fragment, fragmentStartPosition, fragmentEndPosition, style);
+            fragment.buildFragmentTransform(fragmentTransform);
+            bool fragmentTransformIsIdentity = fragmentTransform.isIdentity();
+
+            // Draw the marker highlight.
+            if (renderer()->frame()->editor().markedTextMatchesAreHighlighted()) {
+                Color color = marker->activeMatch() ?
+                    RenderTheme::theme().platformActiveTextSearchHighlightColor() :
+                    RenderTheme::theme().platformInactiveTextSearchHighlightColor();
+                GraphicsContextStateSaver stateSaver(*context);
+                if (!fragmentTransformIsIdentity)
+                    context->concatCTM(fragmentTransform);
+                context->setFillColor(color);
+                context->fillRect(fragmentRect, color);
+            }
+
+            if (!fragmentTransformIsIdentity)
+                fragmentRect = fragmentTransform.mapRect(fragmentRect);
+            markerRect.unite(fragmentRect);
+        }
+    }
+
+    toRenderedDocumentMarker(marker)->setRenderedRect(textRenderer->localToAbsoluteQuad(markerRect).enclosingBoundingBox());
+}
+
 FloatRect SVGInlineTextBox::calculateBoundaries() const
 {
     FloatRect textRect;
diff --git a/Source/core/rendering/svg/SVGInlineTextBox.h b/Source/core/rendering/svg/SVGInlineTextBox.h
index e1549b0..2dfc2a8 100644
--- a/Source/core/rendering/svg/SVGInlineTextBox.h
+++ b/Source/core/rendering/svg/SVGInlineTextBox.h
@@ -34,29 +34,27 @@
 public:
     SVGInlineTextBox(RenderObject*);
 
-    virtual bool isSVGInlineTextBox() const { return true; }
+    virtual bool isSVGInlineTextBox() const OVERRIDE { return true; }
 
-    virtual float virtualLogicalHeight() const { return m_logicalHeight; }
+    virtual float virtualLogicalHeight() const OVERRIDE { return m_logicalHeight; }
     void setLogicalHeight(float height) { m_logicalHeight = height; }
 
-    virtual int selectionTop() { return top(); }
-    virtual int selectionHeight() { return static_cast<int>(ceilf(m_logicalHeight)); }
-    virtual int offsetForPosition(float x, bool includePartialGlyphs = true) const;
-    virtual float positionForOffset(int offset) const;
+    virtual int offsetForPosition(float x, bool includePartialGlyphs = true) const OVERRIDE;
+    virtual float positionForOffset(int offset) const OVERRIDE;
 
     void paintSelectionBackground(PaintInfo&);
-    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom);
-    virtual LayoutRect localSelectionRect(int startPosition, int endPosition);
+    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
+    virtual LayoutRect localSelectionRect(int startPosition, int endPosition) OVERRIDE;
 
     bool mapStartEndPositionsIntoFragmentCoordinates(const SVGTextFragment&, int& startPosition, int& endPosition) const;
 
-    virtual FloatRect calculateBoundaries() const;
+    virtual FloatRect calculateBoundaries() const OVERRIDE;
 
     void clearTextFragments() { m_textFragments.clear(); }
     Vector<SVGTextFragment>& textFragments() { return m_textFragments; }
     const Vector<SVGTextFragment>& textFragments() const { return m_textFragments; }
 
-    virtual void dirtyLineBoxes() OVERRIDE FINAL;
+    virtual void dirtyLineBoxes() OVERRIDE;
 
     bool startsNewTextChunk() const { return m_startsNewTextChunk; }
     void setStartsNewTextChunk(bool newTextChunk) { m_startsNewTextChunk = newTextChunk; }
@@ -78,6 +76,9 @@
     void paintTextWithShadows(GraphicsContext*, RenderStyle*, TextRun&, const SVGTextFragment&, int startPosition, int endPosition);
     void paintText(GraphicsContext*, RenderStyle*, RenderStyle* selectionStyle, const SVGTextFragment&, bool hasSelection, bool paintSelectedTextOnly);
 
+    virtual void paintDocumentMarker(GraphicsContext*, const FloatPoint&, DocumentMarker*, RenderStyle*, const Font&, bool) OVERRIDE FINAL;
+    virtual void paintTextMatchMarker(GraphicsContext*, const FloatPoint&, DocumentMarker*, RenderStyle*, const Font&) OVERRIDE FINAL;
+
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
 
 private:
diff --git a/Source/core/rendering/svg/SVGPathData.cpp b/Source/core/rendering/svg/SVGPathData.cpp
index f42f641..adafc73 100644
--- a/Source/core/rendering/svg/SVGPathData.cpp
+++ b/Source/core/rendering/svg/SVGPathData.cpp
@@ -39,9 +39,9 @@
     SVGCircleElement* circle = toSVGCircleElement(element);
 
     SVGLengthContext lengthContext(element);
-    float r = circle->rCurrentValue().value(lengthContext);
+    float r = circle->r()->currentValue()->value(lengthContext);
     if (r > 0)
-        path.addEllipse(FloatRect(circle->cxCurrentValue().value(lengthContext) - r, circle->cyCurrentValue().value(lengthContext) - r, r * 2, r * 2));
+        path.addEllipse(FloatRect(circle->cx()->currentValue()->value(lengthContext) - r, circle->cy()->currentValue()->value(lengthContext) - r, r * 2, r * 2));
 }
 
 static void updatePathFromEllipseElement(SVGElement* element, Path& path)
@@ -49,13 +49,13 @@
     SVGEllipseElement* ellipse = toSVGEllipseElement(element);
 
     SVGLengthContext lengthContext(element);
-    float rx = ellipse->rxCurrentValue().value(lengthContext);
+    float rx = ellipse->rx()->currentValue()->value(lengthContext);
     if (rx <= 0)
         return;
-    float ry = ellipse->ryCurrentValue().value(lengthContext);
+    float ry = ellipse->ry()->currentValue()->value(lengthContext);
     if (ry <= 0)
         return;
-    path.addEllipse(FloatRect(ellipse->cxCurrentValue().value(lengthContext) - rx, ellipse->cyCurrentValue().value(lengthContext) - ry, rx * 2, ry * 2));
+    path.addEllipse(FloatRect(ellipse->cx()->currentValue()->value(lengthContext) - rx, ellipse->cy()->currentValue()->value(lengthContext) - ry, rx * 2, ry * 2));
 }
 
 static void updatePathFromLineElement(SVGElement* element, Path& path)
@@ -63,8 +63,8 @@
     SVGLineElement* line = toSVGLineElement(element);
 
     SVGLengthContext lengthContext(element);
-    path.moveTo(FloatPoint(line->x1CurrentValue().value(lengthContext), line->y1CurrentValue().value(lengthContext)));
-    path.addLineTo(FloatPoint(line->x2CurrentValue().value(lengthContext), line->y2CurrentValue().value(lengthContext)));
+    path.moveTo(FloatPoint(line->x1()->currentValue()->value(lengthContext), line->y1()->currentValue()->value(lengthContext)));
+    path.addLineTo(FloatPoint(line->x2()->currentValue()->value(lengthContext), line->y2()->currentValue()->value(lengthContext)));
 }
 
 static void updatePathFromPathElement(SVGElement* element, Path& path)
@@ -72,32 +72,26 @@
     buildPathFromByteStream(toSVGPathElement(element)->pathByteStream(), path);
 }
 
-static void updatePathFromPolygonElement(SVGElement* element, Path& path)
-{
-    SVGPointList& points = toSVGPolygonElement(element)->pointsCurrentValue();
-    if (points.isEmpty())
-        return;
-
-    path.moveTo(points.first());
-
-    unsigned size = points.size();
-    for (unsigned i = 1; i < size; ++i)
-        path.addLineTo(points.at(i));
-
-    path.closeSubpath();
-}
-
 static void updatePathFromPolylineElement(SVGElement* element, Path& path)
 {
-    SVGPointList& points = toSVGPolylineElement(element)->pointsCurrentValue();
-    if (points.isEmpty())
+    RefPtr<SVGPointList> points = toSVGPolyElement(element)->points()->currentValue();
+    if (points->isEmpty())
         return;
 
-    path.moveTo(points.first());
+    SVGPointList::ConstIterator it = points->begin();
+    SVGPointList::ConstIterator itEnd = points->end();
+    ASSERT(it != itEnd);
+    path.moveTo(it->value());
+    ++it;
 
-    unsigned size = points.size();
-    for (unsigned i = 1; i < size; ++i)
-        path.addLineTo(points.at(i));
+    for (; it != itEnd; ++it)
+        path.addLineTo(it->value());
+}
+
+static void updatePathFromPolygonElement(SVGElement* element, Path& path)
+{
+    updatePathFromPolylineElement(element, path);
+    path.closeSubpath();
 }
 
 static void updatePathFromRectElement(SVGElement* element, Path& path)
@@ -105,19 +99,19 @@
     SVGRectElement* rect = toSVGRectElement(element);
 
     SVGLengthContext lengthContext(element);
-    float width = rect->widthCurrentValue().value(lengthContext);
+    float width = rect->width()->currentValue()->value(lengthContext);
     if (width <= 0)
         return;
-    float height = rect->heightCurrentValue().value(lengthContext);
+    float height = rect->height()->currentValue()->value(lengthContext);
     if (height <= 0)
         return;
-    float x = rect->xCurrentValue().value(lengthContext);
-    float y = rect->yCurrentValue().value(lengthContext);
-    bool hasRx = rect->rxCurrentValue().value(lengthContext) > 0;
-    bool hasRy = rect->ryCurrentValue().value(lengthContext) > 0;
+    float x = rect->x()->currentValue()->value(lengthContext);
+    float y = rect->y()->currentValue()->value(lengthContext);
+    float rx = rect->rx()->currentValue()->value(lengthContext);
+    float ry = rect->ry()->currentValue()->value(lengthContext);
+    bool hasRx = rx > 0;
+    bool hasRy = ry > 0;
     if (hasRx || hasRy) {
-        float rx = rect->rxCurrentValue().value(lengthContext);
-        float ry = rect->ryCurrentValue().value(lengthContext);
         if (!hasRx)
             rx = ry;
         else if (!hasRy)
diff --git a/Source/core/rendering/svg/SVGRenderSupport.cpp b/Source/core/rendering/svg/SVGRenderSupport.cpp
index 1b8c175..a9676a0 100644
--- a/Source/core/rendering/svg/SVGRenderSupport.cpp
+++ b/Source/core/rendering/svg/SVGRenderSupport.cpp
@@ -256,7 +256,7 @@
             // for the initial paint to avoid potential double-painting caused by non-sensical "old" bounds.
             // We could handle this in the individual objects, but for now it's easier to have
             // parent containers call repaint().  (RenderBlock::layout* has similar logic.)
-            if (!childEverHadLayout)
+            if (!childEverHadLayout && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
                 child->repaint();
         } else if (layoutSizeChanged)
             notlayoutedObjects.add(child);
@@ -296,11 +296,10 @@
     return object->style()->overflowX() == OHIDDEN;
 }
 
-void SVGRenderSupport::intersectRepaintRectWithResources(const RenderObject* object, FloatRect& repaintRect)
+void SVGRenderSupport::intersectRepaintRectWithResources(const RenderObject* renderer, FloatRect& repaintRect)
 {
-    ASSERT(object);
+    ASSERT(renderer);
 
-    RenderObject* renderer = const_cast<RenderObject*>(object);
     SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(renderer);
     if (!resources)
         return;
@@ -357,21 +356,22 @@
     ASSERT(svgStyle);
 
     SVGLengthContext lengthContext(toSVGElement(object->node()));
-    context->setStrokeThickness(svgStyle->strokeWidth().value(lengthContext));
+    context->setStrokeThickness(svgStyle->strokeWidth()->value(lengthContext));
     context->setLineCap(svgStyle->capStyle());
     context->setLineJoin(svgStyle->joinStyle());
     context->setMiterLimit(svgStyle->strokeMiterLimit());
 
-    const Vector<SVGLength>& dashes = svgStyle->strokeDashArray();
-    if (dashes.isEmpty())
+    RefPtr<SVGLengthList> dashes = svgStyle->strokeDashArray();
+    if (dashes->isEmpty())
         return;
 
     DashArray dashArray;
-    const Vector<SVGLength>::const_iterator end = dashes.end();
-    for (Vector<SVGLength>::const_iterator it = dashes.begin(); it != end; ++it)
-        dashArray.append((*it).value(lengthContext));
+    SVGLengthList::ConstIterator it = dashes->begin();
+    SVGLengthList::ConstIterator itEnd = dashes->end();
+    for (; it != itEnd; ++it)
+        dashArray.append(it->value(lengthContext));
 
-    context->setLineDash(dashArray, svgStyle->strokeDashOffset().value(lengthContext));
+    context->setLineDash(dashArray, svgStyle->strokeDashOffset()->value(lengthContext));
 }
 
 void SVGRenderSupport::applyStrokeStyleToStrokeData(StrokeData* strokeData, const RenderStyle* style, const RenderObject* object)
@@ -386,21 +386,21 @@
     ASSERT(svgStyle);
 
     SVGLengthContext lengthContext(toSVGElement(object->node()));
-    strokeData->setThickness(svgStyle->strokeWidth().value(lengthContext));
+    strokeData->setThickness(svgStyle->strokeWidth()->value(lengthContext));
     strokeData->setLineCap(svgStyle->capStyle());
     strokeData->setLineJoin(svgStyle->joinStyle());
     strokeData->setMiterLimit(svgStyle->strokeMiterLimit());
 
-    const Vector<SVGLength>& dashes = svgStyle->strokeDashArray();
-    if (dashes.isEmpty())
+    RefPtr<SVGLengthList> dashes = svgStyle->strokeDashArray();
+    if (dashes->isEmpty())
         return;
 
     DashArray dashArray;
-    const Vector<SVGLength>::const_iterator end = dashes.end();
-    for (Vector<SVGLength>::const_iterator it = dashes.begin(); it != end; ++it)
-        dashArray.append((*it).value(lengthContext));
+    size_t length = dashes->numberOfItems();
+    for (size_t i = 0; i < length; ++i)
+        dashArray.append(dashes->at(i)->value(lengthContext));
 
-    strokeData->setLineDash(dashArray, svgStyle->strokeDashOffset().value(lengthContext));
+    strokeData->setLineDash(dashArray, svgStyle->strokeDashOffset()->value(lengthContext));
 }
 
 bool SVGRenderSupport::isEmptySVGInlineText(const RenderObject* object)
@@ -411,4 +411,11 @@
     return object->isSVGInlineText() && toRenderSVGInlineText(object)->hasEmptyText();
 }
 
+bool SVGRenderSupport::isRenderableTextNode(const RenderObject* object)
+{
+    ASSERT(object->isText());
+    // <br> is marked as text, but is not handled by the SVG rendering code-path.
+    return object->isSVGInlineText() && !toRenderSVGInlineText(object)->hasEmptyText();
+}
+
 }
diff --git a/Source/core/rendering/svg/SVGRenderSupport.h b/Source/core/rendering/svg/SVGRenderSupport.h
index 4265f64..cf5a005 100644
--- a/Source/core/rendering/svg/SVGRenderSupport.h
+++ b/Source/core/rendering/svg/SVGRenderSupport.h
@@ -84,6 +84,10 @@
     // Helper method for determining whether an RenderSVGInlineText object has zero length text.
     static bool isEmptySVGInlineText(const RenderObject*);
 
+    // Helper method for determining if a RenderObject marked as text (isText()== true)
+    // can/will be rendered as part of a <text>.
+    static bool isRenderableTextNode(const RenderObject*);
+
 private:
     // This class is not constructable.
     SVGRenderSupport();
diff --git a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
index b92e9b9..0057e85 100644
--- a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
+++ b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
@@ -260,21 +260,22 @@
         const RenderSVGShape& shape = static_cast<const RenderSVGShape&>(object);
         ASSERT(shape.element());
 
-        Color fallbackColor;
-        if (RenderSVGResource* strokePaintingResource = RenderSVGResource::strokePaintingResource(const_cast<RenderSVGShape*>(&shape), shape.style(), fallbackColor)) {
+        bool hasFallback;
+        if (RenderSVGResource* strokePaintingResource = RenderSVGResource::strokePaintingResource(const_cast<RenderSVGShape*>(&shape), shape.style(), hasFallback)) {
             TextStreamSeparator s(" ");
             ts << " [stroke={" << s;
             writeSVGPaintingResource(ts, strokePaintingResource);
 
             SVGLengthContext lengthContext(shape.element());
-            double dashOffset = svgStyle->strokeDashOffset().value(lengthContext);
-            double strokeWidth = svgStyle->strokeWidth().value(lengthContext);
-            const Vector<SVGLength>& dashes = svgStyle->strokeDashArray();
+            double dashOffset = svgStyle->strokeDashOffset()->value(lengthContext);
+            double strokeWidth = svgStyle->strokeWidth()->value(lengthContext);
+            RefPtr<SVGLengthList> dashes = svgStyle->strokeDashArray();
 
             DashArray dashArray;
-            const Vector<SVGLength>::const_iterator end = dashes.end();
-            for (Vector<SVGLength>::const_iterator it = dashes.begin(); it != end; ++it)
-                dashArray.append((*it).value(lengthContext));
+            SVGLengthList::ConstIterator it = dashes->begin();
+            SVGLengthList::ConstIterator itEnd = dashes->end();
+            for (; it != itEnd; ++it)
+                dashArray.append(it->value(lengthContext));
 
             writeIfNotDefault(ts, "opacity", svgStyle->strokeOpacity(), 1.0f);
             writeIfNotDefault(ts, "stroke width", strokeWidth, 1.0);
@@ -288,7 +289,7 @@
             ts << "}]";
         }
 
-        if (RenderSVGResource* fillPaintingResource = RenderSVGResource::fillPaintingResource(const_cast<RenderSVGShape*>(&shape), shape.style(), fallbackColor)) {
+        if (RenderSVGResource* fillPaintingResource = RenderSVGResource::fillPaintingResource(const_cast<RenderSVGShape*>(&shape), shape.style(), hasFallback)) {
             TextStreamSeparator s(" ");
             ts << " [fill={" << s;
             writeSVGPaintingResource(ts, fillPaintingResource);
@@ -321,29 +322,29 @@
 
     if (svgElement->hasTagName(SVGNames::rectTag)) {
         SVGRectElement* element = toSVGRectElement(svgElement);
-        writeNameValuePair(ts, "x", element->xCurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "y", element->yCurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "width", element->widthCurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "height", element->heightCurrentValue().value(lengthContext));
+        writeNameValuePair(ts, "x", element->x()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "y", element->y()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "width", element->width()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "height", element->height()->currentValue()->value(lengthContext));
     } else if (svgElement->hasTagName(SVGNames::lineTag)) {
         SVGLineElement* element = toSVGLineElement(svgElement);
-        writeNameValuePair(ts, "x1", element->x1CurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "y1", element->y1CurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "x2", element->x2CurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "y2", element->y2CurrentValue().value(lengthContext));
+        writeNameValuePair(ts, "x1", element->x1()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "y1", element->y1()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "x2", element->x2()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "y2", element->y2()->currentValue()->value(lengthContext));
     } else if (svgElement->hasTagName(SVGNames::ellipseTag)) {
         SVGEllipseElement* element = toSVGEllipseElement(svgElement);
-        writeNameValuePair(ts, "cx", element->cxCurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "cy", element->cyCurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "rx", element->rxCurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "ry", element->ryCurrentValue().value(lengthContext));
+        writeNameValuePair(ts, "cx", element->cx()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "cy", element->cy()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "rx", element->rx()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "ry", element->ry()->currentValue()->value(lengthContext));
     } else if (svgElement->hasTagName(SVGNames::circleTag)) {
         SVGCircleElement* element = toSVGCircleElement(svgElement);
-        writeNameValuePair(ts, "cx", element->cxCurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "cy", element->cyCurrentValue().value(lengthContext));
-        writeNameValuePair(ts, "r", element->rCurrentValue().value(lengthContext));
+        writeNameValuePair(ts, "cx", element->cx()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "cy", element->cy()->currentValue()->value(lengthContext));
+        writeNameValuePair(ts, "r", element->r()->currentValue()->value(lengthContext));
     } else if (svgElement->hasTagName(SVGNames::polygonTag) || svgElement->hasTagName(SVGNames::polylineTag)) {
-        writeNameAndQuotedValue(ts, "points", toSVGPolyElement(svgElement)->pointsCurrentValue().valueAsString());
+        writeNameAndQuotedValue(ts, "points", toSVGPolyElement(svgElement)->points()->currentValue()->valueAsString());
     } else if (svgElement->hasTagName(SVGNames::pathTag)) {
         String pathString;
         // FIXME: We should switch to UnalteredParsing here - this will affect the path dumping output of dozens of tests.
@@ -490,7 +491,8 @@
         ts << "\n";
         // Creating a placeholder filter which is passed to the builder.
         FloatRect dummyRect;
-        RefPtr<SVGFilter> dummyFilter = SVGFilter::create(AffineTransform(), dummyRect, dummyRect, dummyRect, true);
+        IntRect dummyIntRect;
+        RefPtr<SVGFilter> dummyFilter = SVGFilter::create(AffineTransform(), dummyIntRect, dummyRect, dummyRect, true);
         if (RefPtr<SVGFilterBuilder> builder = filter->buildPrimitives(dummyFilter.get())) {
             if (FilterEffect* lastEffect = builder->lastEffect())
                 lastEffect->externalRepresentation(ts, indent + 1);
@@ -614,7 +616,7 @@
     if (!style)
         return;
 
-    ts << " [offset=" << stopElement->offsetCurrentValue() << "] [color=" << stopElement->stopColorIncludingOpacity() << "]\n";
+    ts << " [offset=" << stopElement->offset()->currentValue()->value() << "] [color=" << stopElement->stopColorIncludingOpacity() << "]\n";
 }
 
 void writeResources(TextStream& ts, const RenderObject& object, int indent)
diff --git a/Source/core/rendering/svg/SVGRenderingContext.cpp b/Source/core/rendering/svg/SVGRenderingContext.cpp
index 5346143..a699609 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.cpp
+++ b/Source/core/rendering/svg/SVGRenderingContext.cpp
@@ -27,8 +27,9 @@
 #include "core/rendering/svg/SVGRenderingContext.h"
 
 #include "core/frame/Frame.h"
+#include "core/frame/FrameHost.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Page.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/svg/RenderSVGImage.h"
 #include "core/rendering/svg/RenderSVGResource.h"
@@ -114,22 +115,26 @@
     // Setup transparency layers before setting up SVG resources!
     bool isRenderingMask = isRenderingMaskImage(m_object);
     float opacity = isRenderingMask ? 1 : style->opacity();
-    blink::WebBlendMode blendMode = isRenderingMask ? blink::WebBlendModeNormal : style->blendMode();
-    if (opacity < 1 || blendMode != blink::WebBlendModeNormal) {
-        FloatRect repaintRect = m_object->repaintRectInLocalCoordinates();
+    bool hasBlendMode = style->hasBlendMode() && !isRenderingMask;
 
-        if (opacity < 1 || blendMode != blink::WebBlendModeNormal) {
-            m_paintInfo->context->clip(repaintRect);
-            if (blendMode != blink::WebBlendModeNormal) {
-                if (!(m_renderingFlags & RestoreGraphicsContext)) {
-                    m_paintInfo->context->save();
-                    m_renderingFlags |= RestoreGraphicsContext;
-                }
-                m_paintInfo->context->setCompositeOperation(CompositeSourceOver, blendMode);
+    if (opacity < 1 || hasBlendMode || style->hasIsolation()) {
+        FloatRect repaintRect = m_object->repaintRectInLocalCoordinates();
+        m_paintInfo->context->clip(repaintRect);
+
+        if (hasBlendMode) {
+            if (!(m_renderingFlags & RestoreGraphicsContext)) {
+                m_paintInfo->context->save();
+                m_renderingFlags |= RestoreGraphicsContext;
             }
-            m_paintInfo->context->beginTransparencyLayer(opacity);
-            m_renderingFlags |= EndOpacityLayer;
+            m_paintInfo->context->setCompositeOperation(CompositeSourceOver, style->blendMode());
         }
+
+        m_paintInfo->context->beginTransparencyLayer(opacity);
+
+        if (hasBlendMode)
+            m_paintInfo->context->setCompositeOperation(CompositeSourceOver, blink::WebBlendModeNormal);
+
+        m_renderingFlags |= EndOpacityLayer;
     }
 
     ClipPathOperation* clipPathOperation = style->clipPath();
@@ -179,7 +184,8 @@
             // changes, we need to paint the whole filter region. Otherwise, elements not visible
             // at the time of the initial paint (due to scrolling, window size, etc.) will never
             // be drawn.
-            m_paintInfo->rect = IntRect(m_filter->drawingRegion(m_object));
+            if (!m_object->document().settings()->deferredFiltersEnabled())
+                m_paintInfo->rect = IntRect(m_filter->drawingRegion(m_object));
         }
     }
 
@@ -204,13 +210,11 @@
 void SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(const RenderObject* renderer, AffineTransform& absoluteTransform)
 {
     ASSERT(renderer);
-    absoluteTransform = currentContentTransformation();
-
-    float deviceScaleFactor = 1;
-    if (Page* page = renderer->document().page())
-        deviceScaleFactor = page->deviceScaleFactor();
+    // We're about to possibly clear renderer, so save the deviceScaleFactor now.
+    float deviceScaleFactor = renderer->document().frameHost()->deviceScaleFactor();
 
     // Walk up the render tree, accumulating SVG transforms.
+    absoluteTransform = currentContentTransformation();
     while (renderer) {
         absoluteTransform = renderer->localToParentTransform() * absoluteTransform;
         if (renderer->isSVGRoot())
@@ -235,8 +239,7 @@
         layer = layer->parent();
     }
 
-    if (deviceScaleFactor != 1)
-        absoluteTransform.scale(deviceScaleFactor);
+    absoluteTransform.scale(deviceScaleFactor);
 }
 
 void SVGRenderingContext::renderSubtree(GraphicsContext* context, RenderObject* item, const AffineTransform& subtreeContentTransformation)
@@ -262,12 +265,6 @@
     return FloatRect(absoluteTargetRect.location(), absoluteTargetRect.size().shrunkTo(maxImageBufferSize));
 }
 
-IntSize SVGRenderingContext::clampedAbsoluteSize(const IntSize& absoluteSize)
-{
-    const IntSize maxImageBufferSize(kMaxImageBufferSize, kMaxImageBufferSize);
-    return absoluteSize.shrunkTo(maxImageBufferSize);
-}
-
 void SVGRenderingContext::clear2DRotation(AffineTransform& transform)
 {
     AffineTransform::DecomposedType decomposition;
diff --git a/Source/core/rendering/svg/SVGRenderingContext.h b/Source/core/rendering/svg/SVGRenderingContext.h
index 5a9ee9e..742e0a0 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.h
+++ b/Source/core/rendering/svg/SVGRenderingContext.h
@@ -80,7 +80,6 @@
 
     static float calculateScreenFontSizeScalingFactor(const RenderObject*);
     static void calculateTransformationToOutermostCoordinateSystem(const RenderObject*, AffineTransform& absoluteTransform);
-    static IntSize clampedAbsoluteSize(const IntSize&);
     static FloatRect clampedAbsoluteTargetRect(const FloatRect& absoluteTargetRect);
     static void clear2DRotation(AffineTransform&);
 
diff --git a/Source/core/rendering/svg/SVGResources.cpp b/Source/core/rendering/svg/SVGResources.cpp
index 5c42dbc..22059f2 100644
--- a/Source/core/rendering/svg/SVGResources.cpp
+++ b/Source/core/rendering/svg/SVGResources.cpp
@@ -137,24 +137,39 @@
     return s_tagList;
 }
 
-static inline String targetReferenceFromResource(SVGElement* element)
+static inline AtomicString targetReferenceFromResource(SVGElement* element)
 {
     String target;
     if (element->hasTagName(SVGNames::patternTag))
-        target = toSVGPatternElement(element)->hrefCurrentValue();
+        target = toSVGPatternElement(element)->href()->currentValue()->value();
     else if (element->hasTagName(SVGNames::linearGradientTag) || element->hasTagName(SVGNames::radialGradientTag))
-        target = toSVGGradientElement(element)->hrefCurrentValue();
+        target = toSVGGradientElement(element)->href()->currentValue()->value();
     else if (element->hasTagName(SVGNames::filterTag))
-        target = toSVGFilterElement(element)->hrefCurrentValue();
+        target = toSVGFilterElement(element)->href()->currentValue()->value();
     else
         ASSERT_NOT_REACHED();
 
     return SVGURIReference::fragmentIdentifierFromIRIString(target, element->document());
 }
 
+static inline bool svgPaintTypeHasURL(SVGPaint::SVGPaintType paintType)
+{
+    switch (paintType) {
+    case SVGPaint::SVG_PAINTTYPE_URI_NONE:
+    case SVGPaint::SVG_PAINTTYPE_URI_CURRENTCOLOR:
+    case SVGPaint::SVG_PAINTTYPE_URI_RGBCOLOR:
+    case SVGPaint::SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR:
+    case SVGPaint::SVG_PAINTTYPE_URI:
+        return true;
+    default:
+        break;
+    }
+    return false;
+}
+
 static inline RenderSVGResourceContainer* paintingResourceFromSVGPaint(Document& document, const SVGPaint::SVGPaintType& paintType, const String& paintUri, AtomicString& id, bool& hasPendingResource)
 {
-    if (paintType != SVGPaint::SVG_PAINTTYPE_URI && paintType != SVGPaint::SVG_PAINTTYPE_URI_RGBCOLOR)
+    if (!svgPaintTypeHasURL(paintType))
         return 0;
 
     id = SVGURIReference::fragmentIdentifierFromIRIString(paintUri, document);
@@ -218,19 +233,19 @@
     OwnPtr<SVGResources> resources;
     if (clipperFilterMaskerTags().contains(tagName)) {
         if (style->hasClipper()) {
-            AtomicString id(style->clipperResource());
+            AtomicString id = style->clipperResource();
             if (!ensureResources(resources)->setClipper(getRenderSVGResourceById<RenderSVGResourceClipper>(document, id)))
                 registerPendingResource(extensions, id, element);
         }
 
         if (style->hasFilter()) {
-            AtomicString id(style->filterResource());
+            AtomicString id = style->filterResource();
             if (!ensureResources(resources)->setFilter(getRenderSVGResourceById<RenderSVGResourceFilter>(document, id)))
                 registerPendingResource(extensions, id, element);
         }
 
         if (style->hasMasker()) {
-            AtomicString id(style->maskerResource());
+            AtomicString id = style->maskerResource();
             if (!ensureResources(resources)->setMasker(getRenderSVGResourceById<RenderSVGResourceMasker>(document, id)))
                 registerPendingResource(extensions, id, element);
         }
@@ -271,7 +286,7 @@
     }
 
     if (chainableResourceTags().contains(tagName)) {
-        AtomicString id(targetReferenceFromResource(element));
+        AtomicString id = targetReferenceFromResource(element);
         if (!ensureResources(resources)->setLinkedResource(getRenderSVGResourceContainerById(document, id)))
             registerPendingResource(extensions, id, element);
     }
diff --git a/Source/core/rendering/svg/SVGResources.h b/Source/core/rendering/svg/SVGResources.h
index 8eb10ad..5f3a8d4 100644
--- a/Source/core/rendering/svg/SVGResources.h
+++ b/Source/core/rendering/svg/SVGResources.h
@@ -20,6 +20,7 @@
 #ifndef SVGResources_h
 #define SVGResources_h
 
+#include "wtf/FastAllocBase.h"
 #include "wtf/HashSet.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/OwnPtr.h"
diff --git a/Source/core/rendering/svg/SVGResourcesCache.cpp b/Source/core/rendering/svg/SVGResourcesCache.cpp
index 7a8ed18..f0a3365 100644
--- a/Source/core/rendering/svg/SVGResourcesCache.cpp
+++ b/Source/core/rendering/svg/SVGResourcesCache.cpp
@@ -51,7 +51,7 @@
         return;
 
     // Put object in cache.
-    SVGResources* resources = m_cache.set(object, newResources.release()).iterator->value.get();
+    SVGResources* resources = m_cache.set(object, newResources.release()).storedValue->value.get();
 
     // Run cycle-detection _afterwards_, so self-references can be caught as well.
     SVGResourcesCycleSolver solver(object, resources);
diff --git a/Source/core/rendering/svg/SVGResourcesCache.h b/Source/core/rendering/svg/SVGResourcesCache.h
index ff5e9f9..e019d9e 100644
--- a/Source/core/rendering/svg/SVGResourcesCache.h
+++ b/Source/core/rendering/svg/SVGResourcesCache.h
@@ -21,6 +21,7 @@
 #define SVGResourcesCache_h
 
 #include "core/rendering/style/RenderStyleConstants.h"
+#include "wtf/FastAllocBase.h"
 #include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/OwnPtr.h"
diff --git a/Source/core/rendering/svg/SVGRootInlineBox.cpp b/Source/core/rendering/svg/SVGRootInlineBox.cpp
index ec9a953..04284b6 100644
--- a/Source/core/rendering/svg/SVGRootInlineBox.cpp
+++ b/Source/core/rendering/svg/SVGRootInlineBox.cpp
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-void SVGRootInlineBox::paint(PaintInfo& paintInfo, const LayoutPoint&, LayoutUnit, LayoutUnit)
+void SVGRootInlineBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit, LayoutUnit)
 {
     ASSERT(paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection);
     ASSERT(!paintInfo.context->paintingDisabled());
@@ -56,12 +56,8 @@
 
     SVGRenderingContext renderingContext(boxRenderer, paintInfo, SVGRenderingContext::SaveGraphicsContext);
     if (renderingContext.isRenderingPrepared()) {
-        for (InlineBox* child = firstChild(); child; child = child->nextOnLine()) {
-            if (child->isSVGInlineTextBox())
-                SVGInlineFlowBox::computeTextMatchMarkerRectForRenderer(toRenderSVGInlineText(toSVGInlineTextBox(child)->textRenderer()));
-
-            child->paint(paintInfo, LayoutPoint(), 0, 0);
-        }
+        for (InlineBox* child = firstChild(); child; child = child->nextOnLine())
+            child->paint(paintInfo, paintOffset, 0, 0);
     }
 }
 
diff --git a/Source/core/rendering/svg/SVGRootInlineBox.h b/Source/core/rendering/svg/SVGRootInlineBox.h
index efbe2f6..0193429 100644
--- a/Source/core/rendering/svg/SVGRootInlineBox.h
+++ b/Source/core/rendering/svg/SVGRootInlineBox.h
@@ -39,14 +39,14 @@
     {
     }
 
-    virtual bool isSVGRootInlineBox() const OVERRIDE FINAL { return true; }
+    virtual bool isSVGRootInlineBox() const OVERRIDE { return true; }
 
-    virtual float virtualLogicalHeight() const OVERRIDE FINAL { return m_logicalHeight; }
+    virtual float virtualLogicalHeight() const OVERRIDE { return m_logicalHeight; }
     void setLogicalHeight(float height) { m_logicalHeight = height; }
 
-    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE FINAL;
+    virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom) OVERRIDE;
 
-    virtual void markDirty(bool dirty = true) OVERRIDE FINAL;
+    virtual void markDirty(bool dirty = true) OVERRIDE;
 
     void computePerCharacterLayoutInformation();
 
diff --git a/Source/core/rendering/svg/SVGTextChunkBuilder.cpp b/Source/core/rendering/svg/SVGTextChunkBuilder.cpp
index d26d868..3c64a64 100644
--- a/Source/core/rendering/svg/SVGTextChunkBuilder.cpp
+++ b/Source/core/rendering/svg/SVGTextChunkBuilder.cpp
@@ -127,7 +127,10 @@
     float desiredTextLength = 0;
     if (SVGTextContentElement* textContentElement = SVGTextContentElement::elementFromRenderer(textRenderer->parent())) {
         SVGLengthContext lengthContext(textContentElement);
-        desiredTextLength = textContentElement->specifiedTextLength().value(lengthContext);
+        if (textContentElement->textLengthIsSpecifiedByUser())
+            desiredTextLength = textContentElement->textLength()->currentValue()->value(lengthContext);
+        else
+            desiredTextLength = 0;
 
         switch (textContentElement->lengthAdjustCurrentValue()) {
         case SVGLengthAdjustUnknown:
diff --git a/Source/core/rendering/svg/SVGTextLayoutAttributesBuilder.cpp b/Source/core/rendering/svg/SVGTextLayoutAttributesBuilder.cpp
index 7c65a7e..778acbc 100644
--- a/Source/core/rendering/svg/SVGTextLayoutAttributesBuilder.cpp
+++ b/Source/core/rendering/svg/SVGTextLayoutAttributesBuilder.cpp
@@ -163,43 +163,43 @@
 static inline void updateCharacterData(unsigned i, float& lastRotation, SVGCharacterData& data, const SVGLengthContext& lengthContext, const SVGLengthList* xList, const SVGLengthList* yList, const SVGLengthList* dxList, const SVGLengthList* dyList, const SVGNumberList* rotateList)
 {
     if (xList)
-        data.x = xList->at(i).value(lengthContext);
+        data.x = xList->at(i)->value(lengthContext);
     if (yList)
-        data.y = yList->at(i).value(lengthContext);
+        data.y = yList->at(i)->value(lengthContext);
     if (dxList)
-        data.dx = dxList->at(i).value(lengthContext);
+        data.dx = dxList->at(i)->value(lengthContext);
     if (dyList)
-        data.dy = dyList->at(i).value(lengthContext);
+        data.dy = dyList->at(i)->value(lengthContext);
     if (rotateList) {
-        data.rotate = rotateList->at(i).value();
+        data.rotate = rotateList->at(i)->value();
         lastRotation = data.rotate;
     }
 }
 
 void SVGTextLayoutAttributesBuilder::fillCharacterDataMap(const TextPosition& position)
 {
-    const SVGLengthList& xList = position.element->xCurrentValue();
-    const SVGLengthList& yList = position.element->yCurrentValue();
-    const SVGLengthList& dxList = position.element->dxCurrentValue();
-    const SVGLengthList& dyList = position.element->dyCurrentValue();
-    const SVGNumberList& rotateList = position.element->rotateCurrentValue();
+    RefPtr<SVGLengthList> xList = position.element->x()->currentValue();
+    RefPtr<SVGLengthList> yList = position.element->y()->currentValue();
+    RefPtr<SVGLengthList> dxList = position.element->dx()->currentValue();
+    RefPtr<SVGLengthList> dyList = position.element->dy()->currentValue();
+    RefPtr<SVGNumberList> rotateList = position.element->rotate()->currentValue();
 
-    unsigned xListSize = xList.size();
-    unsigned yListSize = yList.size();
-    unsigned dxListSize = dxList.size();
-    unsigned dyListSize = dyList.size();
-    unsigned rotateListSize = rotateList.size();
+    unsigned xListSize = xList->numberOfItems();
+    unsigned yListSize = yList->numberOfItems();
+    unsigned dxListSize = dxList->numberOfItems();
+    unsigned dyListSize = dyList->numberOfItems();
+    unsigned rotateListSize = rotateList->numberOfItems();
     if (!xListSize && !yListSize && !dxListSize && !dyListSize && !rotateListSize)
         return;
 
     float lastRotation = SVGTextLayoutAttributes::emptyValue();
     SVGLengthContext lengthContext(position.element);
     for (unsigned i = 0; i < position.length; ++i) {
-        const SVGLengthList* xListPtr = i < xListSize ? &xList : 0;
-        const SVGLengthList* yListPtr = i < yListSize ? &yList : 0;
-        const SVGLengthList* dxListPtr = i < dxListSize ? &dxList : 0;
-        const SVGLengthList* dyListPtr = i < dyListSize ? &dyList : 0;
-        const SVGNumberList* rotateListPtr = i < rotateListSize ? &rotateList : 0;
+        const SVGLengthList* xListPtr = i < xListSize ? xList.get() : 0;
+        const SVGLengthList* yListPtr = i < yListSize ? yList.get() : 0;
+        const SVGLengthList* dxListPtr = i < dxListSize ? dxList.get() : 0;
+        const SVGLengthList* dyListPtr = i < dyListSize ? dyList.get() : 0;
+        const SVGNumberList* rotateListPtr = i < rotateListSize ? rotateList.get() : 0;
         if (!xListPtr && !yListPtr && !dxListPtr && !dyListPtr && !rotateListPtr)
             break;
 
@@ -218,7 +218,7 @@
     if (lastRotation == SVGTextLayoutAttributes::emptyValue())
         return;
 
-    for (unsigned i = rotateList.size(); i < position.length; ++i) {
+    for (unsigned i = rotateList->numberOfItems(); i < position.length; ++i) {
         SVGCharacterDataMap::iterator it = m_characterDataMap.find(position.start + i + 1);
         if (it == m_characterDataMap.end()) {
             SVGCharacterData data;
diff --git a/Source/core/rendering/svg/SVGTextLayoutEngine.cpp b/Source/core/rendering/svg/SVGTextLayoutEngine.cpp
index 0ade353..ba2e95f 100644
--- a/Source/core/rendering/svg/SVGTextLayoutEngine.cpp
+++ b/Source/core/rendering/svg/SVGTextLayoutEngine.cpp
@@ -47,6 +47,7 @@
     , m_dy(0)
     , m_isVerticalText(false)
     , m_inPathLayout(false)
+    , m_textPathCalculator(0)
     , m_textPathLength(0)
     , m_textPathCurrentOffset(0)
     , m_textPathSpacing(0)
@@ -148,7 +149,7 @@
     while (currentParent) {
         if (SVGTextContentElement* textContentElement = SVGTextContentElement::elementFromRenderer(currentParent)) {
             SVGLengthContext lengthContext(textContentElement);
-            if (textContentElement->lengthAdjustCurrentValue() == SVGLengthAdjustSpacing && textContentElement->specifiedTextLength().value(lengthContext) > 0)
+            if (textContentElement->lengthAdjustCurrentValue() == SVGLengthAdjustSpacing && textContentElement->textLengthIsSpecifiedByUser())
                 return true;
         }
 
@@ -169,11 +170,12 @@
     m_inPathLayout = true;
     RenderSVGTextPath* textPath = toRenderSVGTextPath(object);
 
-    m_textPath = textPath->layoutPath();
-    if (m_textPath.isEmpty())
+    Path path = textPath->layoutPath();
+    if (path.isEmpty())
         return;
+    m_textPathCalculator = new Path::PositionCalculator(path);
     m_textPathStartOffset = textPath->startOffset();
-    m_textPathLength = m_textPath.length();
+    m_textPathLength = path.length();
     if (m_textPathStartOffset > 0 && m_textPathStartOffset <= 1)
         m_textPathStartOffset *= m_textPathLength;
 
@@ -207,7 +209,10 @@
     if (SVGTextContentElement* textContentElement = SVGTextContentElement::elementFromRenderer(textPath)) {
         SVGLengthContext lengthContext(textContentElement);
         lengthAdjust = textContentElement->lengthAdjustCurrentValue();
-        desiredTextLength = textContentElement->specifiedTextLength().value(lengthContext);
+        if (textContentElement->textLengthIsSpecifiedByUser())
+            desiredTextLength = textContentElement->textLength()->currentValue()->value(lengthContext);
+        else
+            desiredTextLength = 0;
     }
 
     if (!desiredTextLength)
@@ -222,7 +227,8 @@
 void SVGTextLayoutEngine::endTextPathLayout()
 {
     m_inPathLayout = false;
-    m_textPath = Path();
+    delete m_textPathCalculator;
+    m_textPathCalculator = 0;
     m_textPathLength = 0;
     m_textPathStartOffset = 0;
     m_textPathCurrentOffset = 0;
@@ -421,7 +427,7 @@
 
 void SVGTextLayoutEngine::layoutTextOnLineOrPath(SVGInlineTextBox* textBox, RenderSVGInlineText* text, const RenderStyle* style)
 {
-    if (m_inPathLayout && m_textPath.isEmpty())
+    if (m_inPathLayout && !m_textPathCalculator)
         return;
 
     SVGElement* lengthContext = toSVGElement(text->parent()->node());
@@ -552,14 +558,11 @@
             if (textPathOffset > m_textPathLength)
                 break;
 
-            bool ok = false;
-            FloatPoint point = m_textPath.pointAtLength(textPathOffset, ok);
-            ASSERT(ok);
-
+            FloatPoint point;
+            bool ok = m_textPathCalculator->pointAndNormalAtLength(textPathOffset, point, angle);
+            ASSERT_UNUSED(ok, ok);
             x = point.x();
             y = point.y();
-            angle = m_textPath.normalAngleAtLength(textPathOffset, ok);
-            ASSERT(ok);
 
             // For vertical text on path, the actual angle has to be rotated 90 degrees anti-clockwise, not the orientation angle!
             if (m_isVerticalText)
diff --git a/Source/core/rendering/svg/SVGTextLayoutEngine.h b/Source/core/rendering/svg/SVGTextLayoutEngine.h
index 165a241..f793353 100644
--- a/Source/core/rendering/svg/SVGTextLayoutEngine.h
+++ b/Source/core/rendering/svg/SVGTextLayoutEngine.h
@@ -50,7 +50,6 @@
     SVGTextLayoutEngine(Vector<SVGTextLayoutAttributes*>&);
 
     Vector<SVGTextLayoutAttributes*>& layoutAttributes() { return m_layoutAttributes; }
-    SVGTextChunkBuilder& chunkLayoutBuilder() { return m_chunkLayoutBuilder; }
 
     void beginTextPathLayout(RenderObject*, SVGTextLayoutEngine& lineLayout);
     void endTextPathLayout();
@@ -97,7 +96,7 @@
     bool m_inPathLayout;
 
     // Text on path layout
-    Path m_textPath;
+    Path::PositionCalculator* m_textPathCalculator;
     float m_textPathLength;
     float m_textPathStartOffset;
     float m_textPathCurrentOffset;
diff --git a/Source/core/rendering/svg/SVGTextLayoutEngineBaseline.cpp b/Source/core/rendering/svg/SVGTextLayoutEngineBaseline.cpp
index 3825b4b..9979b49 100644
--- a/Source/core/rendering/svg/SVGTextLayoutEngineBaseline.cpp
+++ b/Source/core/rendering/svg/SVGTextLayoutEngineBaseline.cpp
@@ -38,12 +38,12 @@
 float SVGTextLayoutEngineBaseline::calculateBaselineShift(const SVGRenderStyle* style, SVGElement* contextElement) const
 {
     if (style->baselineShift() == BS_LENGTH) {
-        SVGLength baselineShiftValueLength = style->baselineShiftValue();
-        if (baselineShiftValueLength.unitType() == LengthTypePercentage)
-            return baselineShiftValueLength.valueAsPercentage() * m_font.pixelSize();
+        RefPtr<SVGLength> baselineShiftValueLength = style->baselineShiftValue();
+        if (baselineShiftValueLength->unitType() == LengthTypePercentage)
+            return baselineShiftValueLength->valueAsPercentage() * m_font.fontDescription().computedPixelSize();
 
         SVGLengthContext lengthContext(contextElement);
-        return baselineShiftValueLength.value(lengthContext);
+        return baselineShiftValueLength->value(lengthContext);
     }
 
     switch (style->baselineShift()) {
diff --git a/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp b/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp
index 6f68e47..282d5bc 100644
--- a/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp
+++ b/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp
@@ -23,6 +23,7 @@
 
 #include "core/rendering/style/SVGRenderStyle.h"
 #include "core/svg/SVGLengthContext.h"
+#include "platform/fonts/Character.h"
 #include "platform/fonts/Font.h"
 
 #if ENABLE(SVG_FONTS)
@@ -72,7 +73,7 @@
 
     m_lastGlyph = currentGlyph;
     m_lastGlyph.isValid = true;
-    kerning *= m_font.size() / m_font.fontMetrics().unitsPerEm();
+    kerning *= m_font.fontDescription().computedSize() / m_font.fontMetrics().unitsPerEm();
     return kerning;
 #else
     return false;
@@ -82,24 +83,24 @@
 float SVGTextLayoutEngineSpacing::calculateCSSKerningAndSpacing(const SVGRenderStyle* style, SVGElement* contextElement, UChar currentCharacter)
 {
     float kerning = 0;
-    SVGLength kerningLength = style->kerning();
-    if (kerningLength.unitType() == LengthTypePercentage)
-        kerning = kerningLength.valueAsPercentage() * m_font.pixelSize();
+    RefPtr<SVGLength> kerningLength = style->kerning();
+    if (kerningLength->unitType() == LengthTypePercentage)
+        kerning = kerningLength->valueAsPercentage() * m_font.fontDescription().computedPixelSize();
     else {
         SVGLengthContext lengthContext(contextElement);
-        kerning = kerningLength.value(lengthContext);
+        kerning = kerningLength->value(lengthContext);
     }
 
     UChar lastCharacter = m_lastCharacter;
     m_lastCharacter = currentCharacter;
 
-    if (!kerning && !m_font.letterSpacing() && !m_font.wordSpacing())
+    if (!kerning && !m_font.fontDescription().letterSpacing() && !m_font.fontDescription().wordSpacing())
         return 0;
 
-    float spacing = m_font.letterSpacing() + kerning;
-    if (currentCharacter && lastCharacter && m_font.wordSpacing()) {
-        if (Font::treatAsSpace(currentCharacter) && !Font::treatAsSpace(lastCharacter))
-            spacing += m_font.wordSpacing();
+    float spacing = m_font.fontDescription().letterSpacing() + kerning;
+    if (currentCharacter && lastCharacter && m_font.fontDescription().wordSpacing()) {
+        if (Character::treatAsSpace(currentCharacter) && !Character::treatAsSpace(lastCharacter))
+            spacing += m_font.fontDescription().wordSpacing();
     }
 
     return spacing;
diff --git a/Source/core/rendering/svg/SVGTextMetrics.h b/Source/core/rendering/svg/SVGTextMetrics.h
index 3f1ddea..3629339 100644
--- a/Source/core/rendering/svg/SVGTextMetrics.h
+++ b/Source/core/rendering/svg/SVGTextMetrics.h
@@ -55,13 +55,6 @@
         {
         }
 
-        bool operator==(const Glyph& other)
-        {
-            return isValid == other.isValid
-                && name == other.name
-                && unicodeString == other.unicodeString;
-        }
-
         bool isValid;
         String name;
         String unicodeString;
diff --git a/Source/core/rendering/svg/SVGTextMetricsBuilder.cpp b/Source/core/rendering/svg/SVGTextMetricsBuilder.cpp
index 46a2797..55dc71f 100644
--- a/Source/core/rendering/svg/SVGTextMetricsBuilder.cpp
+++ b/Source/core/rendering/svg/SVGTextMetricsBuilder.cpp
@@ -23,6 +23,7 @@
 
 #include "core/rendering/svg/RenderSVGInlineText.h"
 #include "core/rendering/svg/RenderSVGText.h"
+#include "platform/text/TextPath.h"
 
 namespace WebCore {
 
@@ -101,7 +102,9 @@
 
     const Font& scaledFont = text->scaledFont();
     m_run = SVGTextMetrics::constructTextRun(text, 0, text->textLength());
-    m_isComplexText = scaledFont.codePath(m_run) == Font::Complex;
+    CodePath codePath = scaledFont.codePath(m_run);
+    m_isComplexText = codePath == ComplexPath;
+    m_run.setCharacterScanForCodePath(!m_isComplexText);
 
     if (m_isComplexText)
         m_simpleWidthIterator.clear();
diff --git a/Source/core/rendering/svg/SVGTextQuery.cpp b/Source/core/rendering/svg/SVGTextQuery.cpp
index 4bf2a3c..d6cf4fd 100644
--- a/Source/core/rendering/svg/SVGTextQuery.cpp
+++ b/Source/core/rendering/svg/SVGTextQuery.cpp
@@ -215,15 +215,11 @@
         return;
 
     if (lastPositionOffset != -1 && lastPositionOffset - positionOffset > 1) {
-        if (alterStartPosition && startPosition > lastPositionOffset && startPosition < static_cast<int>(positionOffset)) {
+        if (alterStartPosition && startPosition > lastPositionOffset && startPosition < static_cast<int>(positionOffset))
             startPosition = lastPositionOffset;
-            alterStartPosition = false;
-        }
 
-        if (alterEndPosition && endPosition > lastPositionOffset && endPosition < static_cast<int>(positionOffset)) {
+        if (alterEndPosition && endPosition > lastPositionOffset && endPosition < static_cast<int>(positionOffset))
             endPosition = positionOffset;
-            alterEndPosition = false;
-        }
     }
 }
 
@@ -499,10 +495,10 @@
     return true;
 }
 
-SVGRect SVGTextQuery::extentOfCharacter(unsigned position) const
+FloatRect SVGTextQuery::extentOfCharacter(unsigned position) const
 {
     if (m_textBoxes.isEmpty())
-        return SVGRect();
+        return FloatRect();
 
     ExtentOfCharacterData data(position);
     executeQuery(&data, &SVGTextQuery::extentOfCharacterCallback);
@@ -540,7 +536,7 @@
     return false;
 }
 
-int SVGTextQuery::characterNumberAtPosition(const SVGPoint& position) const
+int SVGTextQuery::characterNumberAtPosition(const FloatPoint& position) const
 {
     if (m_textBoxes.isEmpty())
         return -1;
diff --git a/Source/core/rendering/svg/SVGTextQuery.h b/Source/core/rendering/svg/SVGTextQuery.h
index 652d751..a5601f7 100644
--- a/Source/core/rendering/svg/SVGTextQuery.h
+++ b/Source/core/rendering/svg/SVGTextQuery.h
@@ -21,8 +21,8 @@
 #define SVGTextQuery_h
 
 #include "core/rendering/svg/SVGTextFragment.h"
-#include "core/svg/SVGPoint.h"
-#include "core/svg/SVGRect.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/geometry/FloatRect.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
@@ -41,8 +41,8 @@
     FloatPoint startPositionOfCharacter(unsigned position) const;
     FloatPoint endPositionOfCharacter(unsigned position) const;
     float rotationOfCharacter(unsigned position) const;
-    SVGRect extentOfCharacter(unsigned position) const;
-    int characterNumberAtPosition(const SVGPoint&) const;
+    FloatRect extentOfCharacter(unsigned position) const;
+    int characterNumberAtPosition(const FloatPoint&) const;
 
     // Public helper struct. Private classes in SVGTextQuery inherit from it.
     struct Data;
diff --git a/Source/core/rendering/svg/SVGTextRunRenderingContext.h b/Source/core/rendering/svg/SVGTextRunRenderingContext.h
index e71eca2..e03f939 100644
--- a/Source/core/rendering/svg/SVGTextRunRenderingContext.h
+++ b/Source/core/rendering/svg/SVGTextRunRenderingContext.h
@@ -29,7 +29,7 @@
 class RenderObject;
 class RenderSVGResource;
 
-class SVGTextRunRenderingContext : public TextRun::RenderingContext {
+class SVGTextRunRenderingContext FINAL : public TextRun::RenderingContext {
 public:
     static PassRefPtr<SVGTextRunRenderingContext> create(RenderObject* renderer)
     {
@@ -42,9 +42,9 @@
     RenderSVGResource* activePaintingResource() const { return m_activePaintingResource; }
     void setActivePaintingResource(RenderSVGResource* object) { m_activePaintingResource = object; }
 
-    virtual GlyphData glyphDataForCharacter(const Font&, const TextRun&, WidthIterator&, UChar32 character, bool mirror, int currentCharacter, unsigned& advanceLength);
-    virtual void drawSVGGlyphs(GraphicsContext*, const TextRun&, const SimpleFontData*, const GlyphBuffer&, int from, int to, const FloatPoint&) const;
-    virtual float floatWidthUsingSVGFont(const Font&, const TextRun&, int& charsConsumed, String& glyphName) const;
+    virtual GlyphData glyphDataForCharacter(const Font&, const TextRun&, WidthIterator&, UChar32 character, bool mirror, int currentCharacter, unsigned& advanceLength) OVERRIDE;
+    virtual void drawSVGGlyphs(GraphicsContext*, const TextRun&, const SimpleFontData*, const GlyphBuffer&, int from, int to, const FloatPoint&) const OVERRIDE;
+    virtual float floatWidthUsingSVGFont(const Font&, const TextRun&, int& charsConsumed, String& glyphName) const OVERRIDE;
 #endif
 
 private:
diff --git a/Source/core/speech/SpeechInput.h b/Source/core/speech/SpeechInput.h
index dcc7171..338111a 100644
--- a/Source/core/speech/SpeechInput.h
+++ b/Source/core/speech/SpeechInput.h
@@ -48,7 +48,7 @@
 // This class connects the input elements requiring speech input with the platform specific
 // speech recognition engine. It provides methods for the input elements to activate speech
 // recognition and methods for the speech recognition engine to return back the results.
-class SpeechInput : public SpeechInputListener, public Supplement<Page> {
+class SpeechInput FINAL : public SpeechInputListener, public Supplement<Page> {
     WTF_MAKE_NONCOPYABLE(SpeechInput);
 public:
     virtual ~SpeechInput();
@@ -71,9 +71,9 @@
     void cancelRecognition(int);
 
     // SpeechInputListener methods.
-    virtual void didCompleteRecording(int);
-    virtual void didCompleteRecognition(int);
-    virtual void setRecognitionResult(int, const SpeechInputResultArray&);
+    virtual void didCompleteRecording(int) OVERRIDE;
+    virtual void didCompleteRecognition(int) OVERRIDE;
+    virtual void setRecognitionResult(int, const SpeechInputResultArray&) OVERRIDE;
 
 private:
     explicit SpeechInput(SpeechInputClient*);
diff --git a/Source/core/speech/SpeechInputEvent.h b/Source/core/speech/SpeechInputEvent.h
index 1a00925..d9cd9be 100644
--- a/Source/core/speech/SpeechInputEvent.h
+++ b/Source/core/speech/SpeechInputEvent.h
@@ -35,15 +35,15 @@
 
 namespace WebCore {
 
-class SpeechInputEvent : public Event {
+class SpeechInputEvent FINAL : public Event {
 public:
     static PassRefPtr<SpeechInputEvent> create();
     static PassRefPtr<SpeechInputEvent> create(const AtomicString& eventType, const SpeechInputResultArray& results);
-    ~SpeechInputEvent();
+    virtual ~SpeechInputEvent();
 
     SpeechInputResultList* results() const { return m_results.get(); }
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     SpeechInputEvent();
diff --git a/Source/core/storage/Storage.cpp b/Source/core/storage/Storage.cpp
index 76abd82..3b7d77a 100644
--- a/Source/core/storage/Storage.cpp
+++ b/Source/core/storage/Storage.cpp
@@ -33,12 +33,14 @@
 
 namespace WebCore {
 
-PassRefPtr<Storage> Storage::create(Frame* frame, PassOwnPtr<StorageArea> storageArea)
+DEFINE_GC_INFO(Storage);
+
+PassRefPtrWillBeRawPtr<Storage> Storage::create(Frame* frame, PassOwnPtrWillBeRawPtr<StorageArea> storageArea)
 {
-    return adoptRef(new Storage(frame, storageArea));
+    return adoptRefWillBeNoop(new Storage(frame, storageArea));
 }
 
-Storage::Storage(Frame* frame, PassOwnPtr<StorageArea> storageArea)
+Storage::Storage(Frame* frame, PassOwnPtrWillBeRawPtr<StorageArea> storageArea)
     : DOMWindowProperty(frame)
     , m_storageArea(storageArea)
 {
@@ -78,20 +80,23 @@
     return anonymousNamedSetter(AtomicString::number(index), value, exceptionState);
 }
 
-bool Storage::anonymousNamedDeleter(const AtomicString& name, ExceptionState& exceptionState)
+DeleteResult Storage::anonymousNamedDeleter(const AtomicString& name, ExceptionState& exceptionState)
 {
     bool found = contains(name, exceptionState);
-    if (!found || exceptionState.hadException())
-        return false;
+    if (!found)
+        return DeleteUnknownProperty;
+    if (exceptionState.hadException())
+        return DeleteReject;
     removeItem(name, exceptionState);
     if (exceptionState.hadException())
-        return false;
-    return true;
+        return DeleteReject;
+    return DeleteSuccess;
 }
 
-bool Storage::anonymousIndexedDeleter(unsigned index, ExceptionState& exceptionState)
+DeleteResult Storage::anonymousIndexedDeleter(unsigned index, ExceptionState& exceptionState)
 {
-    return anonymousNamedDeleter(AtomicString::number(index), exceptionState);
+    DeleteResult result = anonymousNamedDeleter(AtomicString::number(index), exceptionState);
+    return result == DeleteUnknownProperty ? DeleteSuccess : result;
 }
 
 void Storage::namedPropertyEnumerator(Vector<String>& names, ExceptionState& exceptionState)
@@ -122,4 +127,9 @@
     return true;
 }
 
+void Storage::trace(Visitor* visitor)
+{
+    visitor->trace(m_storageArea);
+}
+
 }
diff --git a/Source/core/storage/Storage.h b/Source/core/storage/Storage.h
index 34e1317..083ec83 100644
--- a/Source/core/storage/Storage.h
+++ b/Source/core/storage/Storage.h
@@ -27,8 +27,10 @@
 #define Storage_h
 
 #include "bindings/v8/ScriptWrappable.h"
+#include "bindings/v8/V8Binding.h"
 #include "core/frame/DOMWindowProperty.h"
 #include "core/storage/StorageArea.h"
+#include "heap/Handle.h"
 #include "wtf/Forward.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
@@ -38,10 +40,11 @@
 class ExceptionState;
 class Frame;
 
-class Storage : public ScriptWrappable, public RefCounted<Storage>, public DOMWindowProperty {
+class Storage FINAL : public RefCountedWillBeGarbageCollectedFinalized<Storage>, public ScriptWrappable, public DOMWindowProperty {
+    DECLARE_GC_INFO;
 public:
-    static PassRefPtr<Storage> create(Frame*, PassOwnPtr<StorageArea>);
-    ~Storage();
+    static PassRefPtrWillBeRawPtr<Storage> create(Frame*, PassOwnPtrWillBeRawPtr<StorageArea>);
+    virtual ~Storage();
 
     unsigned length(ExceptionState& ec) const { return m_storageArea->length(ec, m_frame); }
     String key(unsigned index, ExceptionState& ec) const { return m_storageArea->key(index, ec, m_frame); }
@@ -57,15 +60,17 @@
     String anonymousNamedGetter(const AtomicString&, ExceptionState&);
     bool anonymousNamedSetter(const AtomicString& name, const AtomicString& value, ExceptionState&);
     bool anonymousIndexedSetter(unsigned, const AtomicString&, ExceptionState&);
-    bool anonymousNamedDeleter(const AtomicString&, ExceptionState&);
-    bool anonymousIndexedDeleter(unsigned, ExceptionState&);
+    DeleteResult anonymousNamedDeleter(const AtomicString&, ExceptionState&);
+    DeleteResult anonymousIndexedDeleter(unsigned, ExceptionState&);
     void namedPropertyEnumerator(Vector<String>&, ExceptionState&);
     bool namedPropertyQuery(const AtomicString&, ExceptionState&);
 
-private:
-    Storage(Frame*, PassOwnPtr<StorageArea>);
+    void trace(Visitor*);
 
-    OwnPtr<StorageArea> m_storageArea;
+private:
+    Storage(Frame*, PassOwnPtrWillBeRawPtr<StorageArea>);
+
+    OwnPtrWillBeMember<StorageArea> m_storageArea;
 };
 
 } // namespace WebCore
diff --git a/Source/core/storage/Storage.idl b/Source/core/storage/Storage.idl
index 90309fe..6eea590 100644
--- a/Source/core/storage/Storage.idl
+++ b/Source/core/storage/Storage.idl
@@ -23,18 +23,21 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface Storage {
-    [RaisesException, ImplementedAs=anonymousIndexedGetter, NotEnumerable] getter DOMString(unsigned long index);
-    [RaisesException, ImplementedAs=anonymousIndexedSetter] setter DOMString (unsigned long index, DOMString value);
-    [ImplementedAs=anonymousIndexedDeleter, RaisesException] deleter boolean (unsigned long index);
-    [RaisesException, ImplementedAs=anonymousNamedGetter] getter DOMString(DOMString name);
-    [RaisesException, ImplementedAs=anonymousNamedSetter] setter DOMString(DOMString name, DOMString value);
-    [ImplementedAs=anonymousNamedDeleter, RaisesException] deleter boolean (DOMString name);
-    [NotEnumerable, RaisesException=Getter] readonly attribute unsigned long length;
-    [NotEnumerable, TreatReturnedNullStringAs=Null, RaisesException] DOMString key(unsigned long index);
-    [NotEnumerable, TreatReturnedNullStringAs=Null, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] DOMString getItem(DOMString key);
-    [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void setItem(DOMString key, DOMString data);
-    [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void removeItem(DOMString key);
-    [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void clear();
-};
+[
+    WillBeGarbageCollected
+] interface Storage {
+    [NotEnumerable, RaisesException] getter DOMString (unsigned long index);
+    [RaisesException] setter DOMString (unsigned long index, DOMString value);
+    [RaisesException] deleter boolean (unsigned long index);
 
+    [RaisesException] getter DOMString (DOMString name);
+    [RaisesException] setter DOMString (DOMString name, DOMString value);
+    [RaisesException] deleter boolean (DOMString name);
+
+    [NotEnumerable, RaisesException=Getter] readonly attribute unsigned long length;
+    [NotEnumerable, RaisesException, TreatReturnedNullStringAs=Null] DOMString key(unsigned long index);
+    [ActivityLogging=ForIsolatedWorlds, NotEnumerable, PerWorldBindings, RaisesException, TreatReturnedNullStringAs=Null] DOMString getItem(DOMString key);
+    [ActivityLogging=ForIsolatedWorlds, NotEnumerable, RaisesException, PerWorldBindings] void setItem(DOMString key, DOMString data);
+    [ActivityLogging=ForIsolatedWorlds, NotEnumerable, PerWorldBindings, RaisesException] void removeItem(DOMString key);
+    [ActivityLogging=ForIsolatedWorlds, NotEnumerable, PerWorldBindings, RaisesException] void clear();
+};
diff --git a/Source/core/storage/StorageArea.cpp b/Source/core/storage/StorageArea.cpp
new file mode 100644
index 0000000..0453f72
--- /dev/null
+++ b/Source/core/storage/StorageArea.cpp
@@ -0,0 +1,195 @@
+/*
+ * Copyright (C) 2009 Google Inc. All Rights Reserved.
+ *           (C) 2008 Apple Inc.
+ *
+ * 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 GOOGLE INC. ``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 GOOGLE INC. 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.
+ */
+
+#include "config.h"
+#include "core/storage/StorageArea.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/Document.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/page/Page.h"
+#include "core/page/PageGroup.h"
+#include "core/page/StorageClient.h"
+#include "core/storage/Storage.h"
+#include "core/storage/StorageEvent.h"
+#include "core/storage/StorageNamespace.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "public/platform/WebStorageArea.h"
+#include "public/platform/WebString.h"
+#include "public/platform/WebURL.h"
+
+namespace WebCore {
+
+DEFINE_GC_INFO(StorageArea);
+
+StorageArea::StorageArea(PassOwnPtr<blink::WebStorageArea> storageArea, StorageType storageType)
+    : m_storageArea(storageArea)
+    , m_storageType(storageType)
+    , m_canAccessStorageCachedResult(false)
+    , m_canAccessStorageCachedFrame(0)
+{
+}
+
+StorageArea::~StorageArea()
+{
+}
+
+unsigned StorageArea::length(ExceptionState& exceptionState, Frame* frame)
+{
+    if (!canAccessStorage(frame)) {
+        exceptionState.throwSecurityError("access is denied for this document.");
+        return 0;
+    }
+    return m_storageArea->length();
+}
+
+String StorageArea::key(unsigned index, ExceptionState& exceptionState, Frame* frame)
+{
+    if (!canAccessStorage(frame)) {
+        exceptionState.throwSecurityError("access is denied for this document.");
+        return String();
+    }
+    return m_storageArea->key(index);
+}
+
+String StorageArea::getItem(const String& key, ExceptionState& exceptionState, Frame* frame)
+{
+    if (!canAccessStorage(frame)) {
+        exceptionState.throwSecurityError("access is denied for this document.");
+        return String();
+    }
+    return m_storageArea->getItem(key);
+}
+
+void StorageArea::setItem(const String& key, const String& value, ExceptionState& exceptionState, Frame* frame)
+{
+    if (!canAccessStorage(frame)) {
+        exceptionState.throwSecurityError("access is denied for this document.");
+        return;
+    }
+    blink::WebStorageArea::Result result = blink::WebStorageArea::ResultOK;
+    m_storageArea->setItem(key, value, frame->document()->url(), result);
+    if (result != blink::WebStorageArea::ResultOK)
+        exceptionState.throwDOMException(QuotaExceededError, "Setting the value of '" + key + "' exceeded the quota.");
+}
+
+void StorageArea::removeItem(const String& key, ExceptionState& exceptionState, Frame* frame)
+{
+    if (!canAccessStorage(frame)) {
+        exceptionState.throwSecurityError("access is denied for this document.");
+        return;
+    }
+    m_storageArea->removeItem(key, frame->document()->url());
+}
+
+void StorageArea::clear(ExceptionState& exceptionState, Frame* frame)
+{
+    if (!canAccessStorage(frame)) {
+        exceptionState.throwSecurityError("access is denied for this document.");
+        return;
+    }
+    m_storageArea->clear(frame->document()->url());
+}
+
+bool StorageArea::contains(const String& key, ExceptionState& exceptionState, Frame* frame)
+{
+    if (!canAccessStorage(frame)) {
+        exceptionState.throwSecurityError("access is denied for this document.");
+        return false;
+    }
+    return !getItem(key, exceptionState, frame).isNull();
+}
+
+bool StorageArea::canAccessStorage(Frame* frame)
+{
+    if (!frame || !frame->page())
+        return false;
+    if (m_canAccessStorageCachedFrame == frame)
+        return m_canAccessStorageCachedResult;
+    bool result = frame->page()->storageClient().canAccessStorage(frame, m_storageType);
+    m_canAccessStorageCachedFrame = frame;
+    m_canAccessStorageCachedResult = result;
+    return result;
+}
+
+size_t StorageArea::memoryBytesUsedByCache()
+{
+    return m_storageArea->memoryBytesUsedByCache();
+}
+
+void StorageArea::dispatchLocalStorageEvent(const String& key, const String& oldValue, const String& newValue, SecurityOrigin* securityOrigin, const KURL& pageURL, blink::WebStorageArea* sourceAreaInstance, bool originatedInProcess)
+{
+    // FIXME: This looks suspicious. Why doesn't this use allPages instead?
+    const HashSet<Page*>& pages = PageGroup::sharedGroup()->pages();
+    for (HashSet<Page*>::const_iterator it = pages.begin(); it != pages.end(); ++it) {
+        for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+            Storage* storage = frame->domWindow()->optionalLocalStorage();
+            if (storage && frame->document()->securityOrigin()->canAccess(securityOrigin) && !isEventSource(storage, sourceAreaInstance))
+                frame->domWindow()->enqueueWindowEvent(StorageEvent::create(EventTypeNames::storage, key, oldValue, newValue, pageURL, storage));
+        }
+        InspectorInstrumentation::didDispatchDOMStorageEvent(*it, key, oldValue, newValue, LocalStorage, securityOrigin);
+    }
+}
+
+static Page* findPageWithSessionStorageNamespace(const blink::WebStorageNamespace& sessionNamespace)
+{
+    // FIXME: This looks suspicious. Why doesn't this use allPages instead?
+    const HashSet<Page*>& pages = PageGroup::sharedGroup()->pages();
+    for (HashSet<Page*>::const_iterator it = pages.begin(); it != pages.end(); ++it) {
+        const bool dontCreateIfMissing = false;
+        StorageNamespace* storageNamespace = (*it)->sessionStorage(dontCreateIfMissing);
+        if (storageNamespace && storageNamespace->isSameNamespace(sessionNamespace))
+            return *it;
+    }
+    return 0;
+}
+
+void StorageArea::dispatchSessionStorageEvent(const String& key, const String& oldValue, const String& newValue, SecurityOrigin* securityOrigin, const KURL& pageURL, const blink::WebStorageNamespace& sessionNamespace, blink::WebStorageArea* sourceAreaInstance, bool originatedInProcess)
+{
+    Page* page = findPageWithSessionStorageNamespace(sessionNamespace);
+    if (!page)
+        return;
+
+    for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+        Storage* storage = frame->domWindow()->optionalSessionStorage();
+        if (storage && frame->document()->securityOrigin()->canAccess(securityOrigin) && !isEventSource(storage, sourceAreaInstance))
+            frame->domWindow()->enqueueWindowEvent(StorageEvent::create(EventTypeNames::storage, key, oldValue, newValue, pageURL, storage));
+    }
+    InspectorInstrumentation::didDispatchDOMStorageEvent(page, key, oldValue, newValue, SessionStorage, securityOrigin);
+}
+
+bool StorageArea::isEventSource(Storage* storage, blink::WebStorageArea* sourceAreaInstance)
+{
+    ASSERT(storage);
+    StorageArea* area = storage->area();
+    return area->m_storageArea == sourceAreaInstance;
+}
+
+} // namespace WebCore
diff --git a/Source/core/storage/StorageArea.h b/Source/core/storage/StorageArea.h
index 00114d5..c68f8e8 100644
--- a/Source/core/storage/StorageArea.h
+++ b/Source/core/storage/StorageArea.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2009 Google Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -10,10 +10,10 @@
  *    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 APPLE INC. ``AS IS'' AND ANY
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``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 APPLE INC. OR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL GOOGLE INC. 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
@@ -26,34 +26,63 @@
 #ifndef StorageArea_h
 #define StorageArea_h
 
-#include "wtf/Forward.h"
+#include "heap/Handle.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
 #include "wtf/text/WTFString.h"
 
+namespace blink {
+class WebStorageArea;
+class WebStorageNamespace;
+}
+
 namespace WebCore {
 
 class ExceptionState;
 class Frame;
+class KURL;
+class Page;
 class SecurityOrigin;
-class StorageSyncManager;
-enum StorageType { LocalStorage, SessionStorage };
+class Storage;
 
-class StorageArea {
+enum StorageType {
+    LocalStorage,
+    SessionStorage
+};
+
+class StorageArea : public NoBaseWillBeGarbageCollectedFinalized<StorageArea> {
+    DECLARE_GC_INFO;
 public:
-    virtual ~StorageArea() { }
+    StorageArea(PassOwnPtr<blink::WebStorageArea>, StorageType);
+    virtual ~StorageArea();
 
     // The HTML5 DOM Storage API
-    // FIXME: We should pass Document instead of Frame. Also, that parameter should go first.
-    virtual unsigned length(ExceptionState&, Frame* sourceFrame) = 0;
-    virtual String key(unsigned index, ExceptionState&, Frame* sourceFrame) = 0;
-    virtual String getItem(const String& key, ExceptionState&, Frame* sourceFrame) = 0;
-    virtual void setItem(const String& key, const String& value, ExceptionState&, Frame* sourceFrame) = 0;
-    virtual void removeItem(const String& key, ExceptionState&, Frame* sourceFrame) = 0;
-    virtual void clear(ExceptionState&, Frame* sourceFrame) = 0;
-    virtual bool contains(const String& key, ExceptionState&, Frame* sourceFrame) = 0;
+    unsigned length(ExceptionState&, Frame* sourceFrame);
+    String key(unsigned index, ExceptionState&, Frame* sourceFrame);
+    String getItem(const String& key, ExceptionState&, Frame* sourceFrame);
+    void setItem(const String& key, const String& value, ExceptionState&, Frame* sourceFrame);
+    void removeItem(const String& key, ExceptionState&, Frame* sourceFrame);
+    void clear(ExceptionState&, Frame* sourceFrame);
+    bool contains(const String& key, ExceptionState&, Frame* sourceFrame);
 
-    virtual bool canAccessStorage(Frame*) = 0;
+    bool canAccessStorage(Frame*);
+    size_t memoryBytesUsedByCache();
 
-    virtual size_t memoryBytesUsedByCache() = 0;
+    static void dispatchLocalStorageEvent(const String& key, const String& oldValue, const String& newValue,
+        SecurityOrigin*, const KURL& pageURL, blink::WebStorageArea* sourceAreaInstance, bool originatedInProcess);
+    static void dispatchSessionStorageEvent(const String& key, const String& oldValue, const String& newValue,
+        SecurityOrigin*, const KURL& pageURL, const blink::WebStorageNamespace&,
+        blink::WebStorageArea* sourceAreaInstance, bool originatedInProcess);
+
+    void trace(Visitor*) { }
+
+private:
+    static bool isEventSource(Storage*, blink::WebStorageArea* sourceAreaInstance);
+
+    OwnPtr<blink::WebStorageArea> m_storageArea;
+    StorageType m_storageType;
+    mutable bool m_canAccessStorageCachedResult;
+    mutable Frame* m_canAccessStorageCachedFrame;
 };
 
 } // namespace WebCore
diff --git a/Source/core/storage/StorageEvent.h b/Source/core/storage/StorageEvent.h
index 2e6743a..eaf165d 100644
--- a/Source/core/storage/StorageEvent.h
+++ b/Source/core/storage/StorageEvent.h
@@ -27,6 +27,7 @@
 #define StorageEvent_h
 
 #include "core/events/Event.h"
+#include "heap/Handle.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -34,16 +35,19 @@
 class Storage;
 
 struct StorageEventInit : public EventInit {
+    // FIXME: oilpan: Replace this with STACK_ALLOCATED.
+    DISALLOW_ALLOCATION();
+public:
     StorageEventInit();
 
     String key;
     String oldValue;
     String newValue;
     String url;
-    RefPtr<Storage> storageArea;
+    RefPtrWillBeRawPtr<Storage> storageArea;
 };
 
-class StorageEvent : public Event {
+class StorageEvent FINAL : public Event {
 public:
     static PassRefPtr<StorageEvent> create();
     static PassRefPtr<StorageEvent> create(const AtomicString& type, const String& key, const String& oldValue, const String& newValue, const String& url, Storage* storageArea);
@@ -62,7 +66,7 @@
     // Needed once we support init<blank>EventNS
     // void initStorageEventNS(in DOMString namespaceURI, in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in DOMString keyArg, in DOMString oldValueArg, in DOMString newValueArg, in DOMString urlArg, Storage storageAreaArg);
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     StorageEvent();
@@ -73,7 +77,7 @@
     String m_oldValue;
     String m_newValue;
     String m_url;
-    RefPtr<Storage> m_storageArea;
+    RefPtrWillBePersistent<Storage> m_storageArea;
 };
 
 } // namespace WebCore
diff --git a/Source/core/storage/StorageNamespace.cpp b/Source/core/storage/StorageNamespace.cpp
new file mode 100644
index 0000000..84f6074
--- /dev/null
+++ b/Source/core/storage/StorageNamespace.cpp
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2009 Google Inc. 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 GOOGLE INC. ``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 GOOGLE INC. 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.
+ */
+
+#include "config.h"
+#include "core/storage/StorageNamespace.h"
+
+#include "core/storage/StorageArea.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebStorageArea.h"
+#include "public/platform/WebStorageNamespace.h"
+#include "wtf/MainThread.h"
+
+namespace WebCore {
+
+StorageNamespace::StorageNamespace(PassOwnPtr<blink::WebStorageNamespace> webStorageNamespace)
+    : m_webStorageNamespace(webStorageNamespace)
+{
+}
+
+StorageNamespace::~StorageNamespace()
+{
+}
+
+PassOwnPtrWillBeRawPtr<StorageArea> StorageNamespace::localStorageArea(SecurityOrigin* origin)
+{
+    ASSERT(isMainThread());
+    static blink::WebStorageNamespace* localStorageNamespace = 0;
+    if (!localStorageNamespace)
+        localStorageNamespace = blink::Platform::current()->createLocalStorageNamespace();
+    return adoptPtrWillBeNoop(new StorageArea(adoptPtr(localStorageNamespace->createStorageArea(origin->toString())), LocalStorage));
+}
+
+PassOwnPtrWillBeRawPtr<StorageArea> StorageNamespace::storageArea(SecurityOrigin* origin)
+{
+    return adoptPtrWillBeNoop(new StorageArea(adoptPtr(m_webStorageNamespace->createStorageArea(origin->toString())), SessionStorage));
+}
+
+bool StorageNamespace::isSameNamespace(const blink::WebStorageNamespace& sessionNamespace) const
+{
+    return m_webStorageNamespace && m_webStorageNamespace->isSameNamespace(sessionNamespace);
+}
+
+} // namespace WebCore
diff --git a/Source/core/storage/StorageNamespace.h b/Source/core/storage/StorageNamespace.h
index e3f7a9b..debb4c9 100644
--- a/Source/core/storage/StorageNamespace.h
+++ b/Source/core/storage/StorageNamespace.h
@@ -26,8 +26,14 @@
 #ifndef StorageNamespace_h
 #define StorageNamespace_h
 
+#include "heap/Handle.h"
+#include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 
+namespace blink {
+class WebStorageNamespace;
+}
+
 namespace WebCore {
 
 class Page;
@@ -36,11 +42,16 @@
 
 class StorageNamespace {
 public:
-    static PassOwnPtr<StorageArea> localStorageArea(SecurityOrigin*);
-    static PassOwnPtr<StorageNamespace> sessionStorageNamespace(Page*);
+    explicit StorageNamespace(PassOwnPtr<blink::WebStorageNamespace>);
+    ~StorageNamespace();
 
-    virtual ~StorageNamespace() { }
-    virtual PassOwnPtr<StorageArea> storageArea(SecurityOrigin*) = 0;
+    static PassOwnPtrWillBeRawPtr<StorageArea> localStorageArea(SecurityOrigin*);
+
+    PassOwnPtrWillBeRawPtr<StorageArea> storageArea(SecurityOrigin*);
+    bool isSameNamespace(const blink::WebStorageNamespace& sessionNamespace) const;
+
+private:
+    OwnPtr<blink::WebStorageNamespace> m_webStorageNamespace;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/ColorDistance.cpp b/Source/core/svg/ColorDistance.cpp
index ba329f7..3af73c5 100644
--- a/Source/core/svg/ColorDistance.cpp
+++ b/Source/core/svg/ColorDistance.cpp
@@ -21,71 +21,22 @@
 #include "core/svg/ColorDistance.h"
 
 #include "platform/graphics/Color.h"
-#include "wtf/MathExtras.h"
 
 namespace WebCore {
 
-ColorDistance::ColorDistance()
-    : m_redDiff(0)
-    , m_greenDiff(0)
-    , m_blueDiff(0)
-{
-}
-
-ColorDistance::ColorDistance(const Color& fromColor, const Color& toColor)
-    : m_redDiff(toColor.red() - fromColor.red())
-    , m_greenDiff(toColor.green() - fromColor.green())
-    , m_blueDiff(toColor.blue() - fromColor.blue())
-{
-}
-
-ColorDistance::ColorDistance(int redDiff, int greenDiff, int blueDiff)
-    : m_redDiff(redDiff)
-    , m_greenDiff(greenDiff)
-    , m_blueDiff(blueDiff)
-{
-}
-
-static inline int clampColorValue(int v)
-{
-    if (v > 255)
-        v = 255;
-    else if (v < 0)
-        v = 0;
-    return v;
-}
-
-ColorDistance ColorDistance::scaledDistance(float scaleFactor) const
-{
-    return ColorDistance(static_cast<int>(scaleFactor * m_redDiff),
-                         static_cast<int>(scaleFactor * m_greenDiff),
-                         static_cast<int>(scaleFactor * m_blueDiff));
-}
-
-Color ColorDistance::clampColor(int red, int green, int blue, int alpha)
-{
-    return Color(clampColorValue(red), clampColorValue(green), clampColorValue(blue), clampColorValue(alpha));
-}
-
 Color ColorDistance::addColors(const Color& first, const Color& second)
 {
     return Color(first.red() + second.red(), first.green() + second.green(), first.blue() + second.blue());
 }
 
-Color ColorDistance::addToColor(const Color& color) const
+float ColorDistance::distance(const Color& fromColor, const Color& toColor)
 {
-    return Color(color.red() + m_redDiff, color.green() + m_greenDiff, color.blue() + m_blueDiff);
-}
+    int redDiff = toColor.red() - fromColor.red();
+    int greenDiff = toColor.green() - fromColor.green();
+    int blueDiff = toColor.blue() - fromColor.blue();
 
-bool ColorDistance::isZero() const
-{
-    return !m_redDiff && !m_blueDiff && !m_greenDiff;
-}
-
-float ColorDistance::distance() const
-{
     // This is just a simple distance calculation, not respecting color spaces
-    return sqrtf(m_redDiff * m_redDiff + m_blueDiff * m_blueDiff + m_greenDiff * m_greenDiff);
+    return sqrtf(redDiff * redDiff + blueDiff * blueDiff + greenDiff * greenDiff);
 }
 
 }
diff --git a/Source/core/svg/ColorDistance.h b/Source/core/svg/ColorDistance.h
index 4f8b3fd..0eddc28 100644
--- a/Source/core/svg/ColorDistance.h
+++ b/Source/core/svg/ColorDistance.h
@@ -26,25 +26,10 @@
 
 class ColorDistance {
 public:
-    ColorDistance();
-    ColorDistance(const Color& fromColor, const Color& toColor);
-    ColorDistance(int redDiff, int blueDiff, int greenDiff);
-
-    ColorDistance scaledDistance(float scaleFactor) const;
-    Color addToColor(const Color&) const;
-
     static Color addColors(const Color&, const Color&);
-    static Color clampColor(int red, int green, int blue, int alpha);
-
-    bool isZero() const;
-
-    float distance() const;
-
-private:
-    int m_redDiff;
-    int m_greenDiff;
-    int m_blueDiff;
+    static float distance(const Color& fromColor, const Color& toColor);
 };
+
 }
 
 #endif // ColorDistance_h
diff --git a/Source/core/svg/LinearGradientAttributes.h b/Source/core/svg/LinearGradientAttributes.h
index ccf47b1..30d4cac 100644
--- a/Source/core/svg/LinearGradientAttributes.h
+++ b/Source/core/svg/LinearGradientAttributes.h
@@ -25,26 +25,27 @@
 namespace WebCore {
 struct LinearGradientAttributes : GradientAttributes {
     LinearGradientAttributes()
-        : m_x1()
-        , m_y1()
-        , m_x2(LengthModeWidth, "100%")
-        , m_y2()
+        : m_x1(SVGLength::create(LengthModeWidth))
+        , m_y1(SVGLength::create(LengthModeWidth))
+        , m_x2(SVGLength::create(LengthModeWidth))
+        , m_y2(SVGLength::create(LengthModeWidth))
         , m_x1Set(false)
         , m_y1Set(false)
         , m_x2Set(false)
         , m_y2Set(false)
     {
+        m_x2->setValueAsString("100%", ASSERT_NO_EXCEPTION);
     }
 
-    SVGLength x1() const { return m_x1; }
-    SVGLength y1() const { return m_y1; }
-    SVGLength x2() const { return m_x2; }
-    SVGLength y2() const { return m_y2; }
+    SVGLength* x1() const { return m_x1.get(); }
+    SVGLength* y1() const { return m_y1.get(); }
+    SVGLength* x2() const { return m_x2.get(); }
+    SVGLength* y2() const { return m_y2.get(); }
 
-    void setX1(const SVGLength& value) { m_x1 = value; m_x1Set = true; }
-    void setY1(const SVGLength& value) { m_y1 = value; m_y1Set = true; }
-    void setX2(const SVGLength& value) { m_x2 = value; m_x2Set = true; }
-    void setY2(const SVGLength& value) { m_y2 = value; m_y2Set = true; }
+    void setX1(PassRefPtr<SVGLength> value) { m_x1 = value; m_x1Set = true; }
+    void setY1(PassRefPtr<SVGLength> value) { m_y1 = value; m_y1Set = true; }
+    void setX2(PassRefPtr<SVGLength> value) { m_x2 = value; m_x2Set = true; }
+    void setY2(PassRefPtr<SVGLength> value) { m_y2 = value; m_y2Set = true; }
 
     bool hasX1() const { return m_x1Set; }
     bool hasY1() const { return m_y1Set; }
@@ -53,10 +54,10 @@
 
 private:
     // Properties
-    SVGLength m_x1;
-    SVGLength m_y1;
-    SVGLength m_x2;
-    SVGLength m_y2;
+    RefPtr<SVGLength> m_x1;
+    RefPtr<SVGLength> m_y1;
+    RefPtr<SVGLength> m_x2;
+    RefPtr<SVGLength> m_y2;
 
     // Property states
     bool m_x1Set : 1;
diff --git a/Source/core/svg/PatternAttributes.h b/Source/core/svg/PatternAttributes.h
index 7e4ae75..3ce308a 100644
--- a/Source/core/svg/PatternAttributes.h
+++ b/Source/core/svg/PatternAttributes.h
@@ -30,12 +30,12 @@
 
 struct PatternAttributes {
     PatternAttributes()
-        : m_x()
-        , m_y()
-        , m_width()
-        , m_height()
+        : m_x(SVGLength::create(LengthModeWidth))
+        , m_y(SVGLength::create(LengthModeHeight))
+        , m_width(SVGLength::create(LengthModeWidth))
+        , m_height(SVGLength::create(LengthModeHeight))
         , m_viewBox()
-        , m_preserveAspectRatio()
+        , m_preserveAspectRatio(SVGPreserveAspectRatio::create())
         , m_patternUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
         , m_patternContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
         , m_patternContentElement(0)
@@ -52,36 +52,36 @@
     {
     }
 
-    SVGLength x() const { return m_x; }
-    SVGLength y() const { return m_y; }
-    SVGLength width() const { return m_width; }
-    SVGLength height() const { return m_height; }
+    SVGLength* x() const { return m_x.get(); }
+    SVGLength* y() const { return m_y.get(); }
+    SVGLength* width() const { return m_width.get(); }
+    SVGLength* height() const { return m_height.get(); }
     FloatRect viewBox() const { return m_viewBox; }
-    SVGPreserveAspectRatio preserveAspectRatio() const { return m_preserveAspectRatio; }
+    SVGPreserveAspectRatio* preserveAspectRatio() const { return m_preserveAspectRatio.get(); }
     SVGUnitTypes::SVGUnitType patternUnits() const { return m_patternUnits; }
     SVGUnitTypes::SVGUnitType patternContentUnits() const { return m_patternContentUnits; }
     AffineTransform patternTransform() const { return m_patternTransform; }
     const SVGPatternElement* patternContentElement() const { return m_patternContentElement; }
 
-    void setX(const SVGLength& value)
+    void setX(PassRefPtr<SVGLength> value)
     {
         m_x = value;
         m_xSet = true;
     }
 
-    void setY(const SVGLength& value)
+    void setY(PassRefPtr<SVGLength> value)
     {
         m_y = value;
         m_ySet = true;
     }
 
-    void setWidth(const SVGLength& value)
+    void setWidth(PassRefPtr<SVGLength> value)
     {
         m_width = value;
         m_widthSet = true;
     }
 
-    void setHeight(const SVGLength& value)
+    void setHeight(PassRefPtr<SVGLength> value)
     {
         m_height = value;
         m_heightSet = true;
@@ -93,7 +93,7 @@
         m_viewBoxSet = true;
     }
 
-    void setPreserveAspectRatio(const SVGPreserveAspectRatio& value)
+    void setPreserveAspectRatio(PassRefPtr<SVGPreserveAspectRatio> value)
     {
         m_preserveAspectRatio = value;
         m_preserveAspectRatioSet = true;
@@ -136,12 +136,12 @@
 
 private:
     // Properties
-    SVGLength m_x;
-    SVGLength m_y;
-    SVGLength m_width;
-    SVGLength m_height;
+    RefPtr<SVGLength> m_x;
+    RefPtr<SVGLength> m_y;
+    RefPtr<SVGLength> m_width;
+    RefPtr<SVGLength> m_height;
     FloatRect m_viewBox;
-    SVGPreserveAspectRatio m_preserveAspectRatio;
+    RefPtr<SVGPreserveAspectRatio> m_preserveAspectRatio;
     SVGUnitTypes::SVGUnitType m_patternUnits;
     SVGUnitTypes::SVGUnitType m_patternContentUnits;
     AffineTransform m_patternTransform;
diff --git a/Source/core/svg/RadialGradientAttributes.h b/Source/core/svg/RadialGradientAttributes.h
index f52dd32..ba0a8f4 100644
--- a/Source/core/svg/RadialGradientAttributes.h
+++ b/Source/core/svg/RadialGradientAttributes.h
@@ -25,9 +25,12 @@
 namespace WebCore {
 struct RadialGradientAttributes : GradientAttributes {
     RadialGradientAttributes()
-        : m_cx(LengthModeWidth, "50%")
-        , m_cy(LengthModeWidth, "50%")
-        , m_r(LengthModeWidth, "50%")
+        : m_cx(SVGLength::create(LengthModeWidth))
+        , m_cy(SVGLength::create(LengthModeHeight))
+        , m_r(SVGLength::create(LengthModeOther))
+        , m_fx(SVGLength::create(LengthModeWidth))
+        , m_fy(SVGLength::create(LengthModeHeight))
+        , m_fr(SVGLength::create(LengthModeOther))
         , m_cxSet(false)
         , m_cySet(false)
         , m_rSet(false)
@@ -35,21 +38,24 @@
         , m_fySet(false)
         , m_frSet(false)
     {
+        m_cx->setValueAsString("50%", IGNORE_EXCEPTION);
+        m_cy->setValueAsString("50%", IGNORE_EXCEPTION);
+        m_r->setValueAsString("50%", IGNORE_EXCEPTION);
     }
 
-    SVGLength cx() const { return m_cx; }
-    SVGLength cy() const { return m_cy; }
-    SVGLength r() const { return m_r; }
-    SVGLength fx() const { return m_fx; }
-    SVGLength fy() const { return m_fy; }
-    SVGLength fr() const { return m_fr; }
+    SVGLength* cx() const { return m_cx.get(); }
+    SVGLength* cy() const { return m_cy.get(); }
+    SVGLength* r() const { return m_r.get(); }
+    SVGLength* fx() const { return m_fx.get(); }
+    SVGLength* fy() const { return m_fy.get(); }
+    SVGLength* fr() const { return m_fr.get(); }
 
-    void setCx(const SVGLength& value) { m_cx = value; m_cxSet = true; }
-    void setCy(const SVGLength& value) { m_cy = value; m_cySet = true; }
-    void setR(const SVGLength& value) { m_r = value; m_rSet = true; }
-    void setFx(const SVGLength& value) { m_fx = value; m_fxSet = true; }
-    void setFy(const SVGLength& value) { m_fy = value; m_fySet = true; }
-    void setFr(const SVGLength& value) { m_fr = value; m_frSet = true; }
+    void setCx(PassRefPtr<SVGLength> value) { m_cx = value; m_cxSet = true; }
+    void setCy(PassRefPtr<SVGLength> value) { m_cy = value; m_cySet = true; }
+    void setR(PassRefPtr<SVGLength> value) { m_r = value; m_rSet = true; }
+    void setFx(PassRefPtr<SVGLength> value) { m_fx = value; m_fxSet = true; }
+    void setFy(PassRefPtr<SVGLength> value) { m_fy = value; m_fySet = true; }
+    void setFr(PassRefPtr<SVGLength> value) { m_fr = value; m_frSet = true; }
 
     bool hasCx() const { return m_cxSet; }
     bool hasCy() const { return m_cySet; }
@@ -60,12 +66,12 @@
 
 private:
     // Properties
-    SVGLength m_cx;
-    SVGLength m_cy;
-    SVGLength m_r;
-    SVGLength m_fx;
-    SVGLength m_fy;
-    SVGLength m_fr;
+    RefPtr<SVGLength> m_cx;
+    RefPtr<SVGLength> m_cy;
+    RefPtr<SVGLength> m_r;
+    RefPtr<SVGLength> m_fx;
+    RefPtr<SVGLength> m_fy;
+    RefPtr<SVGLength> m_fr;
 
     // Property states
     bool m_cxSet : 1;
diff --git a/Source/core/svg/SVGAElement.cpp b/Source/core/svg/SVGAElement.cpp
index 5590144..2142ba4 100644
--- a/Source/core/svg/SVGAElement.cpp
+++ b/Source/core/svg/SVGAElement.cpp
@@ -55,21 +55,18 @@
 using namespace HTMLNames;
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGAElement, SVGNames::targetAttr, SVGTarget, svgTarget)
-DEFINE_ANIMATED_STRING(SVGAElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGAElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGAElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(svgTarget)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGAElement::SVGAElement(Document& document)
     : SVGGraphicsElement(SVGNames::aTag, document)
+    , SVGURIReference(this)
+    , m_svgTarget(SVGAnimatedString::create(this, SVGNames::targetAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+    addToPropertyMap(m_svgTarget);
     registerAnimatedPropertiesForSVGAElement();
 }
 
@@ -94,7 +91,6 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGURIReference::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::targetAttr);
     }
     return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
@@ -107,17 +103,16 @@
         return;
     }
 
+    SVGParsingError parseError = NoError;
+
     if (name == SVGNames::targetAttr) {
-        setSVGTargetBaseValue(value);
-        return;
+        m_svgTarget->setBaseValueAsString(value, parseError);
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else {
+        ASSERT_NOT_REACHED();
     }
 
-    if (SVGURIReference::parseAttribute(name, value))
-        return;
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGAElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -133,10 +128,10 @@
     // as none of the other properties changes the linking behaviour for our <a> element.
     if (SVGURIReference::isKnownAttribute(attrName)) {
         bool wasLink = isLink();
-        setIsLink(!hrefCurrentValue().isNull());
+        setIsLink(!hrefString().isNull());
 
         if (wasLink != isLink())
-            setNeedsStyleRecalc();
+            setNeedsStyleRecalc(SubtreeStyleChange);
     }
 }
 
@@ -158,10 +153,10 @@
         }
 
         if (isLinkClick(event)) {
-            String url = stripLeadingAndTrailingHTMLSpaces(hrefCurrentValue());
+            String url = stripLeadingAndTrailingHTMLSpaces(hrefString());
 
             if (url[0] == '#') {
-                Element* targetElement = treeScope().getElementById(url.substring(1));
+                Element* targetElement = treeScope().getElementById(AtomicString(url.substring(1)));
                 if (targetElement && isSVGSMILElement(*targetElement)) {
                     toSVGSMILElement(targetElement)->beginByLinkActivation();
                     event->setDefaultHandled();
@@ -172,15 +167,15 @@
                     return;
             }
 
-            String target = this->target();
+            AtomicString target(m_svgTarget->currentValue()->value());
             if (target.isEmpty() && fastGetAttribute(XLinkNames::showAttr) == "new")
-                target = "_blank";
+                target = AtomicString("_blank", AtomicString::ConstructFromLiteral);
             event->setDefaultHandled();
 
             Frame* frame = document().frame();
             if (!frame)
                 return;
-            FrameLoadRequest frameRequest(document().securityOrigin(), ResourceRequest(document().completeURL(url)), target);
+            FrameLoadRequest frameRequest(&document(), ResourceRequest(document().completeURL(url)), target);
             frameRequest.setTriggeringEvent(event);
             frame->loader().load(frameRequest);
             return;
@@ -197,14 +192,6 @@
     return true;
 }
 
-bool SVGAElement::rendererIsFocusable() const
-{
-    if (renderer() && renderer()->absoluteClippedOverflowRect().isEmpty())
-        return false;
-
-    return SVGElement::rendererIsFocusable();
-}
-
 bool SVGAElement::isURLAttribute(const Attribute& attribute) const
 {
     return attribute.name().localName() == hrefAttr || SVGGraphicsElement::isURLAttribute(attribute);
@@ -225,16 +212,9 @@
     return false;
 }
 
-bool SVGAElement::childShouldCreateRenderer(const Node& child) const
+bool SVGAElement::willRespondToMouseClickEvents()
 {
-    // http://www.w3.org/2003/01/REC-SVG11-20030114-errata#linking-text-environment
-    // The 'a' element may contain any element that its parent may contain, except itself.
-    if (child.hasTagName(SVGNames::aTag))
-        return false;
-    if (parentNode() && parentNode()->isSVGElement())
-        return parentNode()->childShouldCreateRenderer(child);
-
-    return SVGElement::childShouldCreateRenderer(child);
+    return isLink() || SVGGraphicsElement::willRespondToMouseClickEvents();
 }
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGAElement.h b/Source/core/svg/SVGAElement.h
index 10036db..64519d2 100644
--- a/Source/core/svg/SVGAElement.h
+++ b/Source/core/svg/SVGAElement.h
@@ -23,48 +23,41 @@
 #define SVGAElement_h
 
 #include "core/svg/SVGAnimatedBoolean.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGURIReference.h"
 
 namespace WebCore {
 
 class SVGAElement FINAL : public SVGGraphicsElement,
-                          public SVGURIReference,
-                          public SVGExternalResourcesRequired {
+                          public SVGURIReference {
 public:
     static PassRefPtr<SVGAElement> create(Document&);
+    SVGAnimatedString* svgTarget() { return m_svgTarget.get(); }
 
 private:
     explicit SVGAElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
-
-    virtual String title() const;
-    virtual String target() const { return svgTargetCurrentValue(); }
+    virtual String title() const OVERRIDE;
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
-    virtual void defaultEventHandler(Event*);
+    virtual void defaultEventHandler(Event*) OVERRIDE;
 
     virtual bool supportsFocus() const OVERRIDE;
     virtual bool isMouseFocusable() const OVERRIDE;
     virtual bool isKeyboardFocusable() const OVERRIDE;
-    virtual bool rendererIsFocusable() const OVERRIDE;
-    virtual bool isURLAttribute(const Attribute&) const;
+    virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 
-    virtual bool childShouldCreateRenderer(const Node& child) const;
+    virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
+    RefPtr<SVGAnimatedString> m_svgTarget;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGAElement)
         // This declaration used to define a non-virtual "String& target() const" method, that clashes with "virtual String Element::target() const".
         // That's why it has been renamed to "svgTarget", the CodeGenerators take care of calling svgTargetAnimated() instead of targetAnimated(), see CodeGenerator.pm.
-        DECLARE_ANIMATED_STRING(SVGTarget, svgTarget)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGAElement.idl b/Source/core/svg/SVGAElement.idl
index bcbb517..8f0288e 100644
--- a/Source/core/svg/SVGAElement.idl
+++ b/Source/core/svg/SVGAElement.idl
@@ -27,6 +27,5 @@
     [ImplementedAs=svgTarget] readonly attribute SVGAnimatedString target;
 };
 
-SVGAElement implements SVGExternalResourcesRequired;
 SVGAElement implements SVGURIReference;
 
diff --git a/Source/core/svg/SVGAltGlyphDefElement.cpp b/Source/core/svg/SVGAltGlyphDefElement.cpp
index 4924ec5..5142195 100644
--- a/Source/core/svg/SVGAltGlyphDefElement.cpp
+++ b/Source/core/svg/SVGAltGlyphDefElement.cpp
@@ -39,7 +39,7 @@
     return adoptRef(new SVGAltGlyphDefElement(document));
 }
 
-bool SVGAltGlyphDefElement::hasValidGlyphElements(Vector<String>& glyphNames) const
+bool SVGAltGlyphDefElement::hasValidGlyphElements(Vector<AtomicString>& glyphNames) const
 {
     // Spec: http://www.w3.org/TR/SVG/text.html#AltGlyphDefElement
     // An 'altGlyphDef' can contain either of the following:
@@ -91,7 +91,7 @@
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
         if (!foundFirstAltGlyphItem && child->hasTagName(SVGNames::glyphRefTag)) {
             fountFirstGlyphRef = true;
-            String referredGlyphName;
+            AtomicString referredGlyphName;
 
             if (toSVGGlyphRefElement(child)->hasValidGlyphElement(referredGlyphName))
                 glyphNames.append(referredGlyphName);
@@ -105,11 +105,11 @@
             }
         } else if (!fountFirstGlyphRef && child->hasTagName(SVGNames::altGlyphItemTag)) {
             foundFirstAltGlyphItem = true;
-            Vector<String> referredGlyphNames;
+            Vector<AtomicString> referredGlyphNames;
 
             // As the spec says "The first 'altGlyphItem' in which all referenced glyphs
             // are available is chosen."
-            if (static_cast<SVGAltGlyphItemElement*>(child)->hasValidGlyphElements(glyphNames) && !glyphNames.isEmpty())
+            if (toSVGAltGlyphItemElement(child)->hasValidGlyphElements(glyphNames) && !glyphNames.isEmpty())
                 return true;
         }
     }
diff --git a/Source/core/svg/SVGAltGlyphDefElement.h b/Source/core/svg/SVGAltGlyphDefElement.h
index e557944..a23e725 100644
--- a/Source/core/svg/SVGAltGlyphDefElement.h
+++ b/Source/core/svg/SVGAltGlyphDefElement.h
@@ -21,6 +21,7 @@
 #define SVGAltGlyphDefElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/svg/SVGElement.h"
 #include "wtf/Vector.h"
 
@@ -30,7 +31,7 @@
 public:
     static PassRefPtr<SVGAltGlyphDefElement> create(Document&);
 
-    bool hasValidGlyphElements(Vector<String>& glyphNames) const;
+    bool hasValidGlyphElements(Vector<AtomicString>& glyphNames) const;
 
 private:
     explicit SVGAltGlyphDefElement(Document&);
@@ -38,6 +39,8 @@
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
+DEFINE_NODE_TYPE_CASTS(SVGAltGlyphDefElement, hasTagName(SVGNames::altGlyphDefTag));
+
 }
 
 #endif
diff --git a/Source/core/svg/SVGAltGlyphElement.cpp b/Source/core/svg/SVGAltGlyphElement.cpp
index b170919..d4e56d1 100644
--- a/Source/core/svg/SVGAltGlyphElement.cpp
+++ b/Source/core/svg/SVGAltGlyphElement.cpp
@@ -27,6 +27,7 @@
 
 #include "SVGNames.h"
 #include "XLinkNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/rendering/svg/RenderSVGTSpan.h"
@@ -35,15 +36,14 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGAltGlyphElement, XLinkNames::hrefAttr, Href, href)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGAltGlyphElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextPositioningElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGAltGlyphElement::SVGAltGlyphElement(Document& document)
     : SVGTextPositioningElement(SVGNames::altGlyphTag, document)
+    , SVGURIReference(this)
 {
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGAltGlyphElement();
@@ -56,7 +56,7 @@
 
 void SVGAltGlyphElement::setGlyphRef(const AtomicString&, ExceptionState& exceptionState)
 {
-    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::readOnly());
 }
 
 const AtomicString& SVGAltGlyphElement::glyphRef() const
@@ -66,7 +66,7 @@
 
 void SVGAltGlyphElement::setFormat(const AtomicString&, ExceptionState& exceptionState)
 {
-    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::readOnly());
 }
 
 const AtomicString& SVGAltGlyphElement::format() const
@@ -74,21 +74,14 @@
     return fastGetAttribute(SVGNames::formatAttr);
 }
 
-bool SVGAltGlyphElement::childShouldCreateRenderer(const Node& child) const
-{
-    if (child.isTextNode())
-        return true;
-    return false;
-}
-
 RenderObject* SVGAltGlyphElement::createRenderer(RenderStyle*)
 {
     return new RenderSVGTSpan(this);
 }
 
-bool SVGAltGlyphElement::hasValidGlyphElements(Vector<String>& glyphNames) const
+bool SVGAltGlyphElement::hasValidGlyphElements(Vector<AtomicString>& glyphNames) const
 {
-    String target;
+    AtomicString target;
     Element* element = targetElementFromIRIString(getAttribute(XLinkNames::hrefAttr), document(), &target);
     if (!element)
         return false;
@@ -99,7 +92,7 @@
     }
 
     if (element->hasTagName(SVGNames::altGlyphDefTag)
-        && static_cast<SVGAltGlyphDefElement*>(element)->hasValidGlyphElements(glyphNames))
+        && toSVGAltGlyphDefElement(element)->hasValidGlyphElements(glyphNames))
         return true;
 
     return false;
diff --git a/Source/core/svg/SVGAltGlyphElement.h b/Source/core/svg/SVGAltGlyphElement.h
index 841e1f0..ffa4bfb 100644
--- a/Source/core/svg/SVGAltGlyphElement.h
+++ b/Source/core/svg/SVGAltGlyphElement.h
@@ -23,6 +23,7 @@
 #define SVGAltGlyphElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/svg/SVGTextPositioningElement.h"
 #include "core/svg/SVGURIReference.h"
 #include "wtf/Vector.h"
@@ -42,19 +43,19 @@
     const AtomicString& format() const;
     void setFormat(const AtomicString&, ExceptionState&);
 
-    bool hasValidGlyphElements(Vector<String>& glyphNames) const;
+    bool hasValidGlyphElements(Vector<AtomicString>& glyphNames) const;
 
 private:
     explicit SVGAltGlyphElement(Document&);
 
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const Node& child) const;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGAltGlyphElement)
-        DECLARE_ANIMATED_STRING(Href, href)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+DEFINE_NODE_TYPE_CASTS(SVGAltGlyphElement, hasTagName(SVGNames::altGlyphTag));
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGAltGlyphItemElement.cpp b/Source/core/svg/SVGAltGlyphItemElement.cpp
index 662dfeb..abe9e8d 100644
--- a/Source/core/svg/SVGAltGlyphItemElement.cpp
+++ b/Source/core/svg/SVGAltGlyphItemElement.cpp
@@ -22,7 +22,6 @@
 #if ENABLE(SVG_FONTS)
 #include "core/svg/SVGAltGlyphItemElement.h"
 
-#include "SVGNames.h"
 #include "core/svg/SVGGlyphRefElement.h"
 
 namespace WebCore {
@@ -38,7 +37,7 @@
     return adoptRef(new SVGAltGlyphItemElement(document));
 }
 
-bool SVGAltGlyphItemElement::hasValidGlyphElements(Vector<String>& glyphNames) const
+bool SVGAltGlyphItemElement::hasValidGlyphElements(Vector<AtomicString>& glyphNames) const
 {
     // Spec: http://www.w3.org/TR/SVG/text.html#AltGlyphItemElement
     // The ‘altGlyphItem’ element defines a candidate set of possible glyph substitutions.
@@ -50,7 +49,7 @@
     // there is at least one glyph.
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
         if (child->hasTagName(SVGNames::glyphRefTag)) {
-            String referredGlyphName;
+            AtomicString referredGlyphName;
             if (toSVGGlyphRefElement(child)->hasValidGlyphElement(referredGlyphName))
                 glyphNames.append(referredGlyphName);
             else {
diff --git a/Source/core/svg/SVGAltGlyphItemElement.h b/Source/core/svg/SVGAltGlyphItemElement.h
index cf4c9b0..400596d 100644
--- a/Source/core/svg/SVGAltGlyphItemElement.h
+++ b/Source/core/svg/SVGAltGlyphItemElement.h
@@ -21,6 +21,7 @@
 #define SVGAltGlyphItemElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/svg/SVGElement.h"
 #include "wtf/Vector.h"
 
@@ -30,7 +31,7 @@
 public:
     static PassRefPtr<SVGAltGlyphItemElement> create(Document&);
 
-    bool hasValidGlyphElements(Vector<String>& glyphNames) const;
+    bool hasValidGlyphElements(Vector<AtomicString>& glyphNames) const;
 
 private:
     explicit SVGAltGlyphItemElement(Document&);
@@ -38,6 +39,8 @@
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
+DEFINE_NODE_TYPE_CASTS(SVGAltGlyphItemElement, hasTagName(SVGNames::altGlyphItemTag));
+
 }
 
 #endif
diff --git a/Source/core/svg/SVGAngle.cpp b/Source/core/svg/SVGAngle.cpp
index 30f4155..65cc9be 100644
--- a/Source/core/svg/SVGAngle.cpp
+++ b/Source/core/svg/SVGAngle.cpp
@@ -163,7 +163,7 @@
     bool success = value.is8Bit() ? parseValue<LChar>(value, valueInSpecifiedUnits, unitType)
                                   : parseValue<UChar>(value, valueInSpecifiedUnits, unitType);
     if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The value provided ('" + value + "') is invalid.");
         return;
     }
 
@@ -174,7 +174,7 @@
 void SVGAngle::newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits, ExceptionState& exceptionState)
 {
     if (unitType == SVG_ANGLETYPE_UNKNOWN || unitType > SVG_ANGLETYPE_GRAD) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "Cannot set value with unknown or invalid units (" + String::number(unitType) + ").");
         return;
     }
 
@@ -186,8 +186,12 @@
 
 void SVGAngle::convertToSpecifiedUnits(unsigned short unitType, ExceptionState& exceptionState)
 {
-    if (unitType == SVG_ANGLETYPE_UNKNOWN || m_unitType == SVG_ANGLETYPE_UNKNOWN || unitType > SVG_ANGLETYPE_GRAD) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+    if (unitType == SVG_ANGLETYPE_UNKNOWN || unitType > SVG_ANGLETYPE_GRAD) {
+        exceptionState.throwDOMException(NotSupportedError, "Cannot convert to unknown or invalid units (" + String::number(unitType) + ").");
+        return;
+    }
+    if (m_unitType == SVG_ANGLETYPE_UNKNOWN) {
+        exceptionState.throwDOMException(NotSupportedError, "Cannot convert from unknown or invalid units.");
         return;
     }
 
diff --git a/Source/core/svg/SVGAngle.idl b/Source/core/svg/SVGAngle.idl
index 665f6ea..423a6db 100644
--- a/Source/core/svg/SVGAngle.idl
+++ b/Source/core/svg/SVGAngle.idl
@@ -20,7 +20,9 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface SVGAngle {
+[
+    StrictTypeChecking,
+] interface SVGAngle {
     // Angle Unit Types
     const unsigned short SVG_ANGLETYPE_UNKNOWN = 0;
     const unsigned short SVG_ANGLETYPE_UNSPECIFIED = 1;
@@ -29,13 +31,13 @@
     const unsigned short SVG_ANGLETYPE_GRAD = 4;
 
     readonly attribute unsigned short unitType;
-    [StrictTypeChecking] attribute float value;
-    [StrictTypeChecking] attribute float valueInSpecifiedUnits;
+    attribute float value;
+    attribute float valueInSpecifiedUnits;
 
     [TreatNullAs=NullString, RaisesException=Setter] attribute DOMString valueAsString;
 
-    [StrictTypeChecking, RaisesException] void newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits);
+    [RaisesException] void newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits);
 
-    [StrictTypeChecking, RaisesException] void convertToSpecifiedUnits(unsigned short unitType);
+    [RaisesException] void convertToSpecifiedUnits(unsigned short unitType);
 };
 
diff --git a/Source/core/svg/SVGAnimateColorElement.cpp b/Source/core/svg/SVGAnimateColorElement.cpp
deleted file mode 100644
index 7bf3842..0000000
--- a/Source/core/svg/SVGAnimateColorElement.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "SVGNames.h"
-#include "core/frame/UseCounter.h"
-#include "core/svg/SVGAnimateColorElement.h"
-
-namespace WebCore {
-
-inline SVGAnimateColorElement::SVGAnimateColorElement(Document& document)
-    : SVGAnimateElement(SVGNames::animateColorTag, document)
-{
-    ScriptWrappable::init(this);
-
-    UseCounter::count(document, UseCounter::SVGAnimateColorElement);
-}
-
-PassRefPtr<SVGAnimateColorElement> SVGAnimateColorElement::create(Document& document)
-{
-    return adoptRef(new SVGAnimateColorElement(document));
-}
-
-static bool attributeValueIsCurrentColor(const String& value)
-{
-    DEFINE_STATIC_LOCAL(const AtomicString, currentColor, ("currentColor", AtomicString::ConstructFromLiteral));
-    return value == currentColor;
-}
-
-void SVGAnimateColorElement::determinePropertyValueTypes(const String& from, const String& to)
-{
-    SVGAnimateElement::determinePropertyValueTypes(from, to);
-    if (attributeValueIsCurrentColor(from))
-        m_fromPropertyValueType = CurrentColorValue;
-    if (attributeValueIsCurrentColor(to))
-        m_toPropertyValueType = CurrentColorValue;
-}
-
-}
diff --git a/Source/core/svg/SVGAnimateColorElement.h b/Source/core/svg/SVGAnimateColorElement.h
deleted file mode 100644
index f17ea26..0000000
--- a/Source/core/svg/SVGAnimateColorElement.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGAnimateColorElement_h
-#define SVGAnimateColorElement_h
-
-#include "core/svg/SVGAnimateElement.h"
-
-namespace WebCore {
-
-class SVGAnimateColorElement FINAL : public SVGAnimateElement {
-public:
-    static PassRefPtr<SVGAnimateColorElement> create(Document&);
-
-private:
-    explicit SVGAnimateColorElement(Document&);
-    virtual void determinePropertyValueTypes(const String& from, const String& to);
-};
-
-} // namespace WebCore
-
-#endif // SVGAnimateColorElement_h
diff --git a/Source/core/svg/SVGAnimateElement.cpp b/Source/core/svg/SVGAnimateElement.cpp
index 4d171f2..a7993c0 100644
--- a/Source/core/svg/SVGAnimateElement.cpp
+++ b/Source/core/svg/SVGAnimateElement.cpp
@@ -25,7 +25,7 @@
 #include "core/svg/SVGAnimateElement.h"
 
 #include "CSSPropertyNames.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/QualifiedName.h"
 #include "core/svg/SVGAnimatedType.h"
@@ -39,7 +39,7 @@
     : SVGAnimationElement(tagName, document)
     , m_animatedPropertyType(AnimatedString)
 {
-    ASSERT(hasTagName(SVGNames::animateTag) || hasTagName(SVGNames::setTag) || hasTagName(SVGNames::animateColorTag) || hasTagName(SVGNames::animateTransformTag));
+    ASSERT(hasTagName(SVGNames::animateTag) || hasTagName(SVGNames::setTag) || hasTagName(SVGNames::animateTransformTag));
     ScriptWrappable::init(this);
 }
 
@@ -74,8 +74,6 @@
 
     ASSERT(propertyTypes.size() <= 2);
     AnimatedPropertyType type = propertyTypes[0];
-    if (hasTagName(SVGNames::animateColorTag) && type != AnimatedColor)
-        return AnimatedUnknown;
 
     // Animations of transform lists are not allowed for <animate> or <set>
     // http://www.w3.org/TR/SVG/animate.html#AnimationAttributesAndProperties
@@ -99,7 +97,7 @@
 {
     ASSERT(resultElement);
     SVGElement* targetElement = this->targetElement();
-    if (!targetElement)
+    if (!targetElement || !isSVGAnimateElement(*resultElement))
         return;
 
     ASSERT(m_animatedPropertyType == determineAnimatedPropertyType(targetElement));
@@ -238,10 +236,8 @@
         computeCSSPropertyValue(targetElement, cssPropertyID(attributeName.localName()), baseValue);
     }
 
-    if (!m_animatedType)
+    if (!m_animatedType || !m_animatedType->setValueAsString(attributeName, baseValue))
         m_animatedType = animator->constructFromString(baseValue);
-    else
-        m_animatedType->setValueAsString(attributeName, baseValue);
 }
 
 static inline void applyCSSPropertyToTarget(SVGElement* targetElement, CSSPropertyID id, const String& value)
diff --git a/Source/core/svg/SVGAnimateElement.h b/Source/core/svg/SVGAnimateElement.h
index e8b2dc4..04660ca 100644
--- a/Source/core/svg/SVGAnimateElement.h
+++ b/Source/core/svg/SVGAnimateElement.h
@@ -24,6 +24,7 @@
 #define SVGAnimateElement_h
 
 #include "SVGNames.h"
+#include "core/svg/SVGAnimatedTypeAnimator.h"
 #include "core/svg/SVGAnimationElement.h"
 #include "wtf/OwnPtr.h"
 
@@ -43,19 +44,19 @@
 protected:
     SVGAnimateElement(const QualifiedName&, Document&);
 
-    virtual void resetAnimatedType();
-    virtual void clearAnimatedType(SVGElement* targetElement);
+    virtual void resetAnimatedType() OVERRIDE FINAL;
+    virtual void clearAnimatedType(SVGElement* targetElement) OVERRIDE FINAL;
 
-    virtual bool calculateToAtEndOfDurationValue(const String& toAtEndOfDurationString);
-    virtual bool calculateFromAndToValues(const String& fromString, const String& toString);
-    virtual bool calculateFromAndByValues(const String& fromString, const String& byString);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGSMILElement* resultElement);
-    virtual void applyResultsToTarget();
-    virtual float calculateDistance(const String& fromString, const String& toString);
-    virtual bool isAdditive() const OVERRIDE;
+    virtual bool calculateToAtEndOfDurationValue(const String& toAtEndOfDurationString) OVERRIDE FINAL;
+    virtual bool calculateFromAndToValues(const String& fromString, const String& toString) OVERRIDE FINAL;
+    virtual bool calculateFromAndByValues(const String& fromString, const String& byString) OVERRIDE FINAL;
+    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGSMILElement* resultElement) OVERRIDE FINAL;
+    virtual void applyResultsToTarget() OVERRIDE FINAL;
+    virtual float calculateDistance(const String& fromString, const String& toString) OVERRIDE FINAL;
+    virtual bool isAdditive() const OVERRIDE FINAL;
 
-    virtual void setTargetElement(SVGElement*) OVERRIDE;
-    virtual void setAttributeName(const QualifiedName&) OVERRIDE;
+    virtual void setTargetElement(SVGElement*) OVERRIDE FINAL;
+    virtual void setAttributeName(const QualifiedName&) OVERRIDE FINAL;
 
     AnimatedPropertyType m_animatedPropertyType;
 
@@ -64,7 +65,7 @@
     SVGAnimatedTypeAnimator* ensureAnimator();
     bool animatedPropertyTypeSupportsAddition() const;
 
-    virtual bool hasValidAttributeType();
+    virtual bool hasValidAttributeType() OVERRIDE;
 
     OwnPtr<SVGAnimatedType> m_fromType;
     OwnPtr<SVGAnimatedType> m_toType;
@@ -78,7 +79,6 @@
 inline bool isSVGAnimateElement(const Node& node)
 {
     return node.hasTagName(SVGNames::animateTag)
-        || node.hasTagName(SVGNames::animateColorTag)
         || node.hasTagName(SVGNames::animateTransformTag)
         || node.hasTagName(SVGNames::setTag);
 }
diff --git a/Source/core/svg/SVGAnimateMotionElement.cpp b/Source/core/svg/SVGAnimateMotionElement.cpp
index 9c76b31..fd90123 100644
--- a/Source/core/svg/SVGAnimateMotionElement.cpp
+++ b/Source/core/svg/SVGAnimateMotionElement.cpp
@@ -277,11 +277,10 @@
 
     ASSERT(!m_animationPath.isEmpty());
 
-    bool ok = false;
     float positionOnPath = m_animationPath.length() * percentage;
     FloatPoint position;
     float angle;
-    ok = m_animationPath.pointAndNormalAtLength(positionOnPath, position, angle);
+    bool ok = m_animationPath.pointAndNormalAtLength(positionOnPath, position, angle);
     if (!ok)
         return;
 
diff --git a/Source/core/svg/SVGAnimateMotionElement.h b/Source/core/svg/SVGAnimateMotionElement.h
index 46094a1..3dce19c 100644
--- a/Source/core/svg/SVGAnimateMotionElement.h
+++ b/Source/core/svg/SVGAnimateMotionElement.h
@@ -38,20 +38,20 @@
 private:
     explicit SVGAnimateMotionElement(Document&);
 
-    virtual bool hasValidAttributeType();
-    virtual bool hasValidAttributeName();
+    virtual bool hasValidAttributeType() OVERRIDE;
+    virtual bool hasValidAttributeName() OVERRIDE;
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
-    virtual void resetAnimatedType();
-    virtual void clearAnimatedType(SVGElement* targetElement);
-    virtual bool calculateToAtEndOfDurationValue(const String& toAtEndOfDurationString);
-    virtual bool calculateFromAndToValues(const String& fromString, const String& toString);
-    virtual bool calculateFromAndByValues(const String& fromString, const String& byString);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGSMILElement* resultElement);
-    virtual void applyResultsToTarget();
-    virtual float calculateDistance(const String& fromString, const String& toString);
+    virtual void resetAnimatedType() OVERRIDE;
+    virtual void clearAnimatedType(SVGElement* targetElement) OVERRIDE;
+    virtual bool calculateToAtEndOfDurationValue(const String& toAtEndOfDurationString) OVERRIDE;
+    virtual bool calculateFromAndToValues(const String& fromString, const String& toString) OVERRIDE;
+    virtual bool calculateFromAndByValues(const String& fromString, const String& byString) OVERRIDE;
+    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGSMILElement* resultElement) OVERRIDE;
+    virtual void applyResultsToTarget() OVERRIDE;
+    virtual float calculateDistance(const String& fromString, const String& toString) OVERRIDE;
 
     enum RotateMode {
         RotateAngle,
@@ -73,6 +73,8 @@
     Path m_animationPath;
 };
 
+DEFINE_NODE_TYPE_CASTS(SVGAnimateMotionElement, hasTagName(SVGNames::animateMotionTag));
+
 } // namespace WebCore
 
 #endif // SVGAnimateMotionElement_h
diff --git a/Source/core/svg/SVGAnimateTransformElement.h b/Source/core/svg/SVGAnimateTransformElement.h
index 86606d8..16b4637 100644
--- a/Source/core/svg/SVGAnimateTransformElement.h
+++ b/Source/core/svg/SVGAnimateTransformElement.h
@@ -39,7 +39,7 @@
 private:
     explicit SVGAnimateTransformElement(Document&);
 
-    virtual bool hasValidAttributeType();
+    virtual bool hasValidAttributeType() OVERRIDE;
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -47,6 +47,8 @@
     SVGTransform::SVGTransformType m_type;
 };
 
+DEFINE_NODE_TYPE_CASTS(SVGAnimateTransformElement, hasTagName(SVGNames::animateTransformTag));
+
 } // namespace WebCore
 
 #endif // SVGAnimateTransformElement_h
diff --git a/Source/core/svg/SVGAnimatedAngle.h b/Source/core/svg/SVGAnimatedAngle.h
index 047719a..2adbf19 100644
--- a/Source/core/svg/SVGAnimatedAngle.h
+++ b/Source/core/svg/SVGAnimatedAngle.h
@@ -38,21 +38,21 @@
 
 class SVGAnimationElement;
 
-class SVGAnimatedAngleAnimator : public SVGAnimatedTypeAnimator {
+class SVGAnimatedAngleAnimator FINAL : public SVGAnimatedTypeAnimator {
 public:
     SVGAnimatedAngleAnimator(SVGAnimationElement*, SVGElement*);
     virtual ~SVGAnimatedAngleAnimator() { }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
+    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&) OVERRIDE;
+    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*) OVERRIDE;
+    virtual void animValWillChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void animValDidChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+    virtual float calculateDistance(const String& fromString, const String& toString) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGAnimatedBoolean.cpp b/Source/core/svg/SVGAnimatedBoolean.cpp
deleted file mode 100644
index 656bee8..0000000
--- a/Source/core/svg/SVGAnimatedBoolean.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGAnimatedBoolean.h"
-
-#include "core/svg/SVGAnimateElement.h"
-
-namespace WebCore {
-
-SVGAnimatedBooleanAnimator::SVGAnimatedBooleanAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedBoolean, animationElement, contextElement)
-{
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedBooleanAnimator::constructFromString(const String& string)
-{
-    OwnPtr<SVGAnimatedType> animtedType = SVGAnimatedType::createBoolean(new bool);
-    animtedType->boolean() = (string == "true"); // wat?
-    return animtedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedBooleanAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createBoolean(constructFromBaseValue<SVGAnimatedBoolean>(animatedTypes));
-}
-
-void SVGAnimatedBooleanAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedBoolean>(animatedTypes);
-}
-
-void SVGAnimatedBooleanAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedBoolean>(animatedTypes, type, &SVGAnimatedType::boolean);
-}
-
-void SVGAnimatedBooleanAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedBoolean>(animatedTypes);
-}
-
-void SVGAnimatedBooleanAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedBoolean>(animatedTypes);
-}
-
-void SVGAnimatedBooleanAnimator::addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*)
-{
-    ASSERT_NOT_REACHED();
-}
-
-void SVGAnimatedBooleanAnimator::calculateAnimatedValue(float percentage, unsigned, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType*, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    bool fromBoolean = m_animationElement->animationMode() == ToAnimation ? animated->boolean() : from->boolean();
-    bool toBoolean = to->boolean();
-    bool& animatedBoolean = animated->boolean();
-
-    m_animationElement->animateDiscreteType<bool>(percentage, fromBoolean, toBoolean, animatedBoolean);
-}
-
-float SVGAnimatedBooleanAnimator::calculateDistance(const String&, const String&)
-{
-    // No paced animations for boolean.
-    return -1;
-}
-
-}
diff --git a/Source/core/svg/SVGAnimatedBoolean.h b/Source/core/svg/SVGAnimatedBoolean.h
index 442df07..e6772eb 100644
--- a/Source/core/svg/SVGAnimatedBoolean.h
+++ b/Source/core/svg/SVGAnimatedBoolean.h
@@ -1,58 +1,55 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedBoolean_h
 #define SVGAnimatedBoolean_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/properties/SVGAnimatedStaticPropertyTearOff.h"
+#include "core/svg/SVGBoolean.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedStaticPropertyTearOff<bool> SVGAnimatedBoolean;
-
-// Helper macros to declare/define a SVGAnimatedBoolean object
-#define DECLARE_ANIMATED_BOOLEAN(UpperProperty, LowerProperty) \
-DECLARE_ANIMATED_PROPERTY(SVGAnimatedBoolean, bool, UpperProperty, LowerProperty)
-
-#define DEFINE_ANIMATED_BOOLEAN(OwnerType, DOMAttribute, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedBoolean, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedBoolean, bool)
-
-class SVGAnimationElement;
-
-class SVGAnimatedBooleanAnimator : public SVGAnimatedTypeAnimator {
+class SVGAnimatedBoolean FINAL : public NewSVGAnimatedProperty<SVGBoolean> {
 public:
-    SVGAnimatedBooleanAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedBooleanAnimator() { }
+    static PassRefPtr<SVGAnimatedBoolean> create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGBoolean> initialValue)
+    {
+        return adoptRef(new SVGAnimatedBoolean(contextElement, attributeName, initialValue));
+    }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
-
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+protected:
+    SVGAnimatedBoolean(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGBoolean> initialValue)
+        : NewSVGAnimatedProperty<SVGBoolean>(contextElement, attributeName, initialValue)
+    {
+    }
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGAnimatedBoolean_h
diff --git a/Source/core/svg/SVGAnimatedBoolean.idl b/Source/core/svg/SVGAnimatedBoolean.idl
index 7fc919c..b78954a 100644
--- a/Source/core/svg/SVGAnimatedBoolean.idl
+++ b/Source/core/svg/SVGAnimatedBoolean.idl
@@ -23,8 +23,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGAnimatedBoolean {
-    [StrictTypeChecking, RaisesException=Setter] attribute boolean baseVal;
+[
+    StrictTypeChecking,
+] interface SVGAnimatedBoolean {
+    [RaisesException=Setter] attribute boolean baseVal;
     readonly attribute boolean animVal;
 };
 
diff --git a/Source/core/svg/SVGAnimatedColor.cpp b/Source/core/svg/SVGAnimatedColor.cpp
index ad478af..42ec7ea 100644
--- a/Source/core/svg/SVGAnimatedColor.cpp
+++ b/Source/core/svg/SVGAnimatedColor.cpp
@@ -28,85 +28,75 @@
 
 namespace WebCore {
 
-SVGAnimatedColorAnimator::SVGAnimatedColorAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedColor, animationElement, contextElement)
+String SVGColorProperty::valueAsString() const
 {
+    return m_styleColor.isCurrentColor() ? "currentColor" : m_styleColor.color().serializedAsCSSComponentValue();
 }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedColorAnimator::constructFromString(const String& string)
+PassRefPtr<NewSVGPropertyBase> SVGColorProperty::cloneForAnimation(const String&) const
 {
-    OwnPtr<SVGAnimatedType> animtedType = SVGAnimatedType::createColor(new Color);
-    animtedType->color() = string.isEmpty() ? Color() : SVGColor::colorFromRGBColorString(string);
-    return animtedType.release();
+    // SVGAnimatedColor is deprecated. So No SVG DOM animation.
+    ASSERT_NOT_REACHED();
+    return 0;
 }
 
-void SVGAnimatedColorAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedColor);
-    ASSERT(from->type() == to->type());
-    to->color() = ColorDistance::addColors(from->color(), to->color());
-}
-
-static inline void adjustForCurrentColor(SVGElement* targetElement, Color& color)
+static inline Color fallbackColorForCurrentColor(SVGElement* targetElement)
 {
     ASSERT(targetElement);
-
     if (RenderObject* targetRenderer = targetElement->renderer())
-        color = targetRenderer->style()->visitedDependentColor(CSSPropertyColor);
+        return targetRenderer->style()->visitedDependentColor(CSSPropertyColor);
     else
-        color = Color();
+        return Color::transparent;
 }
 
-static Color parseColorFromString(SVGAnimationElement*, const String& string)
+void SVGColorProperty::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement* contextElement)
 {
-    return SVGColor::colorFromRGBColorString(string);
+    ASSERT(contextElement);
+
+    Color fallbackColor = fallbackColorForCurrentColor(contextElement);
+    Color fromColor = toSVGColorProperty(other)->m_styleColor.resolve(fallbackColor);
+    Color toColor = m_styleColor.resolve(fallbackColor);
+    m_styleColor = StyleColor(ColorDistance::addColors(fromColor, toColor));
 }
 
-void SVGAnimatedColorAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
+void SVGColorProperty::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement)
 {
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
+    StyleColor fromStyleColor = toSVGColorProperty(fromValue)->m_styleColor;
+    StyleColor toStyleColor = toSVGColorProperty(toValue)->m_styleColor;
+    StyleColor toAtEndOfDurationStyleColor = toSVGColorProperty(toAtEndOfDurationValue)->m_styleColor;
 
-    Color fromColor = m_animationElement->animationMode() == ToAnimation ? animated->color() : from->color();
-    Color toColor = to->color();
-    const Color& toAtEndOfDurationColor = toAtEndOfDuration->color();
-    Color& animatedColor = animated->color();
+    // Apply currentColor rules.
+    ASSERT(contextElement);
+    Color fallbackColor = fallbackColorForCurrentColor(contextElement);
+    Color fromColor = fromStyleColor.resolve(fallbackColor);
+    Color toColor = toStyleColor.resolve(fallbackColor);
+    Color toAtEndOfDurationColor = toAtEndOfDurationStyleColor.resolve(fallbackColor);
+    Color animatedColor = m_styleColor.resolve(fallbackColor);
 
-    // Apply CSS inheritance rules.
-    m_animationElement->adjustForInheritance<Color>(parseColorFromString, m_animationElement->fromPropertyValueType(), fromColor, m_contextElement);
-    m_animationElement->adjustForInheritance<Color>(parseColorFromString, m_animationElement->toPropertyValueType(), toColor, m_contextElement);
-
-    // Apply <animateColor> rules.
-    if (m_animationElement->fromPropertyValueType() == CurrentColorValue)
-        adjustForCurrentColor(m_contextElement, fromColor);
-    if (m_animationElement->toPropertyValueType() == CurrentColorValue)
-        adjustForCurrentColor(m_contextElement, toColor);
-
+    ASSERT(animationElement);
     float animatedRed = animatedColor.red();
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromColor.red(), toColor.red(), toAtEndOfDurationColor.red(), animatedRed);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromColor.red(), toColor.red(), toAtEndOfDurationColor.red(), animatedRed);
 
     float animatedGreen = animatedColor.green();
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromColor.green(), toColor.green(), toAtEndOfDurationColor.green(), animatedGreen);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromColor.green(), toColor.green(), toAtEndOfDurationColor.green(), animatedGreen);
 
     float animatedBlue = animatedColor.blue();
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromColor.blue(), toColor.blue(), toAtEndOfDurationColor.blue(), animatedBlue);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromColor.blue(), toColor.blue(), toAtEndOfDurationColor.blue(), animatedBlue);
 
     float animatedAlpha = animatedColor.alpha();
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromColor.alpha(), toColor.alpha(), toAtEndOfDurationColor.alpha(), animatedAlpha);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromColor.alpha(), toColor.alpha(), toAtEndOfDurationColor.alpha(), animatedAlpha);
 
-    animatedColor = ColorDistance::clampColor(static_cast<int>(roundf(animatedRed)), static_cast<int>(roundf(animatedGreen)), static_cast<int>(roundf(animatedBlue)), static_cast<int>(roundf(animatedAlpha)));
+    m_styleColor = StyleColor(makeRGBA(roundf(animatedRed), roundf(animatedGreen), roundf(animatedBlue), roundf(animatedAlpha)));
 }
 
-float SVGAnimatedColorAnimator::calculateDistance(const String& fromString, const String& toString)
+float SVGColorProperty::calculateDistance(PassRefPtr<NewSVGPropertyBase> toValue, SVGElement* contextElement)
 {
-    ASSERT(m_contextElement);
-    Color from = SVGColor::colorFromRGBColorString(fromString);
-    if (!from.isValid())
-        return -1;
-    Color to = SVGColor::colorFromRGBColorString(toString);
-    if (!to.isValid())
-        return -1;
-    return ColorDistance(from, to).distance();
+    ASSERT(contextElement);
+    Color fallbackColor = fallbackColorForCurrentColor(contextElement);
+
+    Color fromColor = m_styleColor.resolve(fallbackColor);
+    Color toColor = toSVGColorProperty(toValue)->m_styleColor.resolve(fallbackColor);
+    return ColorDistance::distance(fromColor, toColor);
 }
 
 }
diff --git a/Source/core/svg/SVGAnimatedColor.h b/Source/core/svg/SVGAnimatedColor.h
index aa29efc..1778879 100644
--- a/Source/core/svg/SVGAnimatedColor.h
+++ b/Source/core/svg/SVGAnimatedColor.h
@@ -1,48 +1,78 @@
 /*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedColor_h
 #define SVGAnimatedColor_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
+#include "core/css/StyleColor.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
 class SVGAnimationElement;
 
-class SVGAnimatedColorAnimator : public SVGAnimatedTypeAnimator {
+// StyleColor adaptor to NewSVGPropertyBase. This is only used for SMIL animations.
+// FIXME: WebAnimations: Replacable with AnimatableColor once SMIL animations are implemented in WebAnimations.
+class SVGColorProperty FINAL : public NewSVGPropertyBase {
 public:
-    SVGAnimatedColorAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedColorAnimator() { }
+    static PassRefPtr<SVGColorProperty> create(StyleColor styleColor)
+    {
+        return adoptRef(new SVGColorProperty(styleColor));
+    }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&) { return PassOwnPtr<SVGAnimatedType>(); }
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&) { }
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*) { }
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&) { }
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&) { }
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+    virtual String valueAsString() const OVERRIDE;
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedColor; }
+
+private:
+    explicit SVGColorProperty(StyleColor styleColor)
+        : NewSVGPropertyBase(classType())
+        , m_styleColor(styleColor)
+    {
+    }
+
+    StyleColor m_styleColor;
 };
 
+inline PassRefPtr<SVGColorProperty> toSVGColorProperty(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGColorProperty::classType());
+    return static_pointer_cast<SVGColorProperty>(base.release());
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGAnimatedEnumeration.h b/Source/core/svg/SVGAnimatedEnumeration.h
index b56e0ad..939eaec 100644
--- a/Source/core/svg/SVGAnimatedEnumeration.h
+++ b/Source/core/svg/SVGAnimatedEnumeration.h
@@ -35,21 +35,21 @@
 #define DEFINE_ANIMATED_ENUMERATION(OwnerType, DOMAttribute, UpperProperty, LowerProperty, EnumType) \
 DEFINE_ANIMATED_PROPERTY(AnimatedEnumeration, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedEnumerationPropertyTearOff<EnumType>, EnumType)
 
-class SVGAnimatedEnumerationAnimator : public SVGAnimatedTypeAnimator {
+class SVGAnimatedEnumerationAnimator FINAL : public SVGAnimatedTypeAnimator {
 public:
     SVGAnimatedEnumerationAnimator(SVGAnimationElement*, SVGElement*);
     virtual ~SVGAnimatedEnumerationAnimator() { }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
+    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&) OVERRIDE;
+    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*) OVERRIDE;
+    virtual void animValWillChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void animValDidChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+    virtual float calculateDistance(const String& fromString, const String& toString) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGAnimatedEnumeration.idl b/Source/core/svg/SVGAnimatedEnumeration.idl
index e51c9c1..7ed1d19 100644
--- a/Source/core/svg/SVGAnimatedEnumeration.idl
+++ b/Source/core/svg/SVGAnimatedEnumeration.idl
@@ -23,8 +23,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGAnimatedEnumeration {
-    [StrictTypeChecking, RaisesException=Setter] attribute unsigned short baseVal;
+[
+    StrictTypeChecking,
+] interface SVGAnimatedEnumeration {
+    [RaisesException=Setter] attribute unsigned short baseVal;
     readonly attribute unsigned short animVal;
 };
-
diff --git a/Source/core/svg/SVGAnimatedInteger.cpp b/Source/core/svg/SVGAnimatedInteger.cpp
index ff7ccee..e7b9699 100644
--- a/Source/core/svg/SVGAnimatedInteger.cpp
+++ b/Source/core/svg/SVGAnimatedInteger.cpp
@@ -1,102 +1,49 @@
 /*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #include "config.h"
 #include "core/svg/SVGAnimatedInteger.h"
 
-#include "core/svg/SVGAnimateElement.h"
-#include "core/svg/SVGAnimatedNumber.h"
-#include "wtf/MathExtras.h"
+#include "core/svg/SVGAnimatedIntegerOptionalInteger.h"
 
 namespace WebCore {
 
-SVGAnimatedIntegerAnimator::SVGAnimatedIntegerAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedInteger, animationElement, contextElement)
+void SVGAnimatedInteger::synchronizeAttribute()
 {
-}
+    ASSERT(needsSynchronizeAttribute());
+    if (m_parentIntegerOptionalInteger) {
+        m_parentIntegerOptionalInteger->synchronizeAttribute();
+        return;
+    }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedIntegerAnimator::constructFromString(const String& string)
-{
-    OwnPtr<SVGAnimatedType> animtedType = SVGAnimatedType::createInteger(new int);
-    animtedType->integer() = string.toIntStrict();
-    return animtedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedIntegerAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createInteger(constructFromBaseValue<SVGAnimatedInteger>(animatedTypes));
-}
-
-void SVGAnimatedIntegerAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedInteger>(animatedTypes);
-}
-
-void SVGAnimatedIntegerAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedInteger>(animatedTypes, type, &SVGAnimatedType::integer);
-}
-
-void SVGAnimatedIntegerAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedInteger>(animatedTypes);
-}
-
-void SVGAnimatedIntegerAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedInteger>(animatedTypes);
-}
-
-void SVGAnimatedIntegerAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedInteger);
-    ASSERT(from->type() == to->type());
-
-    to->integer() += from->integer();
-}
-
-void SVGAnimatedIntegerAnimator::calculateAnimatedInteger(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, int fromInteger, int toInteger, int toAtEndOfDurationInteger, int& animatedInteger)
-{
-    float animatedNumber = animatedInteger;
-    animationElement->animateAdditiveNumber(percentage, repeatCount, fromInteger, toInteger, toAtEndOfDurationInteger, animatedNumber);
-    animatedInteger = static_cast<int>(roundf(animatedNumber));
-}
-
-void SVGAnimatedIntegerAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    int fromInteger = m_animationElement->animationMode() == ToAnimation ? animated->integer() : from->integer();
-    int toInteger = to->integer();
-    int toAtEndOfDurationInteger = toAtEndOfDuration->integer();
-    int& animatedInteger = animated->integer();
-
-    calculateAnimatedInteger(m_animationElement, percentage, repeatCount, fromInteger, toInteger, toAtEndOfDurationInteger, animatedInteger);
-}
-
-float SVGAnimatedIntegerAnimator::calculateDistance(const String& fromString, const String& toString)
-{
-    ASSERT(m_contextElement);
-    int from = fromString.toIntStrict();
-    int to = toString.toIntStrict();
-    return abs(to - from);
+    NewSVGAnimatedProperty<SVGInteger>::synchronizeAttribute();
 }
 
 }
diff --git a/Source/core/svg/SVGAnimatedInteger.h b/Source/core/svg/SVGAnimatedInteger.h
index 6bca857..84b78c3 100644
--- a/Source/core/svg/SVGAnimatedInteger.h
+++ b/Source/core/svg/SVGAnimatedInteger.h
@@ -1,64 +1,69 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedInteger_h
 #define SVGAnimatedInteger_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/properties/SVGAnimatedPropertyMacros.h"
-#include "core/svg/properties/SVGAnimatedStaticPropertyTearOff.h"
+#include "core/svg/SVGInteger.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedStaticPropertyTearOff<int> SVGAnimatedInteger;
+class SVGAnimatedIntegerOptionalInteger;
 
-// Helper macros to declare/define a SVGAnimatedInteger object
-#define DECLARE_ANIMATED_INTEGER(UpperProperty, LowerProperty) \
-DECLARE_ANIMATED_PROPERTY(SVGAnimatedInteger, int, UpperProperty, LowerProperty)
-
-#define DEFINE_ANIMATED_INTEGER(OwnerType, DOMAttribute, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedInteger, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedInteger, int)
-
-#define DEFINE_ANIMATED_INTEGER_MULTIPLE_WRAPPERS(OwnerType, DOMAttribute, SVGDOMAttributeIdentifier, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedIntegerOptionalInteger, OwnerType, DOMAttribute, SVGDOMAttributeIdentifier, UpperProperty, LowerProperty, SVGAnimatedInteger, int)
-
-class SVGAnimationElement;
-
-class SVGAnimatedIntegerAnimator : public SVGAnimatedTypeAnimator {
+// SVG Spec: http://www.w3.org/TR/SVG11/types.html#InterfaceSVGAnimatedInteger
+class SVGAnimatedInteger : public NewSVGAnimatedProperty<SVGInteger> {
 public:
-    SVGAnimatedIntegerAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedIntegerAnimator() { }
+    static PassRefPtr<SVGAnimatedInteger> create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGInteger> initialValue)
+    {
+        return adoptRef(new SVGAnimatedInteger(contextElement, attributeName, initialValue));
+    }
 
-    static void calculateAnimatedInteger(SVGAnimationElement*, float percentage, unsigned repeatCount, int fromInteger, int toInteger, int toAtEndOfDurationInteger, int& animatedInteger);
+    virtual void synchronizeAttribute() OVERRIDE;
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
+    void setParentOptionalInteger(SVGAnimatedIntegerOptionalInteger* numberOptionalInteger)
+    {
+        m_parentIntegerOptionalInteger = numberOptionalInteger;
+    }
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+protected:
+    SVGAnimatedInteger(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGInteger> initialValue)
+        : NewSVGAnimatedProperty<SVGInteger>(contextElement, attributeName, initialValue)
+        , m_parentIntegerOptionalInteger(0)
+    {
+    }
+
+    // FIXME: oilpan: This is kept as raw ptr as this is a back ptr. Change this to Member<> in oilpan.
+    SVGAnimatedIntegerOptionalInteger* m_parentIntegerOptionalInteger;
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGAnimatedInteger_h
diff --git a/Source/core/svg/SVGAnimatedInteger.idl b/Source/core/svg/SVGAnimatedInteger.idl
index 3c31681..14287a3 100644
--- a/Source/core/svg/SVGAnimatedInteger.idl
+++ b/Source/core/svg/SVGAnimatedInteger.idl
@@ -23,8 +23,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGAnimatedInteger {
-    [StrictTypeChecking, RaisesException=Setter] attribute long baseVal;
+[
+    StrictTypeChecking,
+] interface SVGAnimatedInteger {
+    [RaisesException=Setter] attribute long baseVal;
     readonly attribute long animVal;
 };
-
diff --git a/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp b/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp
index 6db1926..b87e561 100644
--- a/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp
+++ b/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp
@@ -1,108 +1,88 @@
 /*
- * Copyright (C) Research In Motion Limited 2012. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #include "config.h"
 
 #include "core/svg/SVGAnimatedIntegerOptionalInteger.h"
 
-#include "core/svg/SVGAnimateElement.h"
-#include "core/svg/SVGAnimatedInteger.h"
-#include "core/svg/SVGParserUtilities.h"
-
 namespace WebCore {
 
-SVGAnimatedIntegerOptionalIntegerAnimator::SVGAnimatedIntegerOptionalIntegerAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedIntegerOptionalInteger, animationElement, contextElement)
+SVGAnimatedIntegerOptionalInteger::SVGAnimatedIntegerOptionalInteger(SVGElement* contextElement, const QualifiedName& attributeName, float initialFirstValue, float initialSecondValue)
+    : NewSVGAnimatedPropertyCommon<SVGIntegerOptionalInteger>(contextElement, attributeName,
+        SVGIntegerOptionalInteger::create(SVGInteger::create(initialFirstValue), SVGInteger::create(initialSecondValue)))
+    , m_firstInteger(SVGAnimatedInteger::create(contextElement, attributeName, baseValue()->firstInteger()))
+    , m_secondInteger(SVGAnimatedInteger::create(contextElement, attributeName, baseValue()->secondInteger()))
 {
+    m_firstInteger->setParentOptionalInteger(this);
+    m_secondInteger->setParentOptionalInteger(this);
 }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedIntegerOptionalIntegerAnimator::constructFromString(const String& string)
+void SVGAnimatedIntegerOptionalInteger::animationStarted()
 {
-    OwnPtr<SVGAnimatedType> animtedType = SVGAnimatedType::createIntegerOptionalInteger(new pair<int, int>);
-    pair<int, int>& animatedInteger = animtedType->integerOptionalInteger();
-    float firstNumber = 0;
-    float secondNumber = 0;
-    if (!parseNumberOptionalNumber(string, firstNumber, secondNumber)) {
-        animatedInteger.first = 0;
-        animatedInteger.second = 0;
-    } else {
-        animatedInteger.first = static_cast<int>(roundf(firstNumber));
-        animatedInteger.second = static_cast<int>(roundf(secondNumber));
-    }
-    return animtedType.release();
+    NewSVGAnimatedPropertyCommon<SVGIntegerOptionalInteger>::animationStarted();
+    m_firstInteger->animationStarted();
+    m_secondInteger->animationStarted();
 }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedIntegerOptionalIntegerAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
+void SVGAnimatedIntegerOptionalInteger::setAnimatedValue(PassRefPtr<NewSVGPropertyBase> value)
 {
-    return SVGAnimatedType::createIntegerOptionalInteger(constructFromBaseValues<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes));
+    NewSVGAnimatedPropertyCommon<SVGIntegerOptionalInteger>::setAnimatedValue(value);
+    m_firstInteger->setAnimatedValue(currentValue()->firstInteger());
+    m_secondInteger->setAnimatedValue(currentValue()->secondInteger());
 }
 
-void SVGAnimatedIntegerOptionalIntegerAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
+void SVGAnimatedIntegerOptionalInteger::animationEnded()
 {
-    stopAnimValAnimationForTypes<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes);
+    NewSVGAnimatedPropertyCommon<SVGIntegerOptionalInteger>::animationEnded();
+    m_firstInteger->animationEnded();
+    m_secondInteger->animationEnded();
 }
 
-void SVGAnimatedIntegerOptionalIntegerAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
+void SVGAnimatedIntegerOptionalInteger::animValWillChange()
 {
-    resetFromBaseValues<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes, type, &SVGAnimatedType::integerOptionalInteger);
+    NewSVGAnimatedPropertyCommon<SVGIntegerOptionalInteger>::animValWillChange();
+    m_firstInteger->animValWillChange();
+    m_secondInteger->animValWillChange();
 }
 
-void SVGAnimatedIntegerOptionalIntegerAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
+void SVGAnimatedIntegerOptionalInteger::animValDidChange()
 {
-    animValWillChangeForTypes<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes);
+    NewSVGAnimatedPropertyCommon<SVGIntegerOptionalInteger>::animValDidChange();
+    m_firstInteger->animValDidChange();
+    m_secondInteger->animValDidChange();
 }
 
-void SVGAnimatedIntegerOptionalIntegerAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
+bool SVGAnimatedIntegerOptionalInteger::needsSynchronizeAttribute()
 {
-    animValDidChangeForTypes<SVGAnimatedInteger, SVGAnimatedInteger>(animatedTypes);
-}
-
-void SVGAnimatedIntegerOptionalIntegerAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedIntegerOptionalInteger);
-    ASSERT(from->type() == to->type());
-
-    const pair<int, int>& fromIntegerPair = from->integerOptionalInteger();
-    pair<int, int>& toIntegerPair = to->integerOptionalInteger();
-
-    toIntegerPair.first += fromIntegerPair.first;
-    toIntegerPair.second += fromIntegerPair.second;
-}
-
-void SVGAnimatedIntegerOptionalIntegerAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    const pair<int, int>& fromIntegerPair = m_animationElement->animationMode() == ToAnimation ? animated->integerOptionalInteger() : from->integerOptionalInteger();
-    const pair<int, int>& toIntegerPair = to->integerOptionalInteger();
-    const pair<int, int>& toAtEndOfDurationIntegerPair = toAtEndOfDuration->integerOptionalInteger();
-    pair<int, int>& animatedIntegerPair = animated->integerOptionalInteger();
-
-    SVGAnimatedIntegerAnimator::calculateAnimatedInteger(m_animationElement, percentage, repeatCount, fromIntegerPair.first, toIntegerPair.first, toAtEndOfDurationIntegerPair.first, animatedIntegerPair.first);
-    SVGAnimatedIntegerAnimator::calculateAnimatedInteger(m_animationElement, percentage, repeatCount, fromIntegerPair.second, toIntegerPair.second, toAtEndOfDurationIntegerPair.second, animatedIntegerPair.second);
-}
-
-float SVGAnimatedIntegerOptionalIntegerAnimator::calculateDistance(const String&, const String&)
-{
-    // FIXME: Distance calculation is not possible for SVGIntegerOptionalInteger right now. We need the distance for every single value.
-    return -1;
+    return m_firstInteger->needsSynchronizeAttribute()
+        || m_secondInteger->needsSynchronizeAttribute();
 }
 
 }
diff --git a/Source/core/svg/SVGAnimatedIntegerOptionalInteger.h b/Source/core/svg/SVGAnimatedIntegerOptionalInteger.h
index 05776be..0c1a272 100644
--- a/Source/core/svg/SVGAnimatedIntegerOptionalInteger.h
+++ b/Source/core/svg/SVGAnimatedIntegerOptionalInteger.h
@@ -1,48 +1,70 @@
 /*
- * Copyright (C) Research In Motion Limited 2012. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedIntegerOptionalInteger_h
 #define SVGAnimatedIntegerOptionalInteger_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
+#include "core/svg/SVGAnimatedInteger.h"
+#include "core/svg/SVGIntegerOptionalInteger.h"
 
 namespace WebCore {
 
-class SVGAnimationElement;
-
-class SVGAnimatedIntegerOptionalIntegerAnimator : public SVGAnimatedTypeAnimator {
+// SVG Spec: http://www.w3.org/TR/SVG11/types.html <number-optional-number>
+// Unlike other SVGAnimated* class, this class is not exposed to Javascript directly,
+// while DOM attribute and SMIL animations operate on this class.
+// From Javascript, the two SVGAnimatedIntegers |firstInteger| and |secondInteger| are used.
+// For example, see SVGFEDropShadowElement::stdDeviation{X,Y}()
+class SVGAnimatedIntegerOptionalInteger : public NewSVGAnimatedPropertyCommon<SVGIntegerOptionalInteger> {
 public:
-    SVGAnimatedIntegerOptionalIntegerAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedIntegerOptionalIntegerAnimator() { }
+    static PassRefPtr<SVGAnimatedIntegerOptionalInteger> create(SVGElement* contextElement, const QualifiedName& attributeName, float initialFirstValue = 0, float initialSecondValue = 0)
+    {
+        return adoptRef(new SVGAnimatedIntegerOptionalInteger(contextElement, attributeName, initialFirstValue, initialSecondValue));
+    }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
+    virtual void animationStarted() OVERRIDE;
+    virtual void setAnimatedValue(PassRefPtr<NewSVGPropertyBase>) OVERRIDE;
+    virtual bool needsSynchronizeAttribute() OVERRIDE;
+    virtual void animationEnded() OVERRIDE;
+    virtual void animValWillChange() OVERRIDE;
+    virtual void animValDidChange() OVERRIDE;
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+    SVGAnimatedInteger* firstInteger() { return m_firstInteger.get(); }
+    SVGAnimatedInteger* secondInteger() { return m_secondInteger.get(); }
+
+protected:
+    SVGAnimatedIntegerOptionalInteger(SVGElement* contextElement, const QualifiedName& attributeName, float initialFirstValue, float initialSecondValue);
+
+    RefPtr<SVGAnimatedInteger> m_firstInteger;
+    RefPtr<SVGAnimatedInteger> m_secondInteger;
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGAnimatedIntegerOptionalInteger_h
diff --git a/Source/core/svg/SVGAnimatedLength.cpp b/Source/core/svg/SVGAnimatedLength.cpp
index d1f127e..bc447b0 100644
--- a/Source/core/svg/SVGAnimatedLength.cpp
+++ b/Source/core/svg/SVGAnimatedLength.cpp
@@ -1,122 +1,56 @@
 /*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #include "config.h"
-#include "core/svg/SVGAnimatedLength.h"
 
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/svg/SVGAnimateElement.h"
-#include "core/svg/SVGAnimatedNumber.h"
+#include "core/svg/SVGAnimatedLength.h"
 
 namespace WebCore {
 
-SVGAnimatedLengthAnimator::SVGAnimatedLengthAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedLength, animationElement, contextElement)
-    , m_lengthMode(SVGLength::lengthModeForAnimatedLengthAttribute(animationElement->attributeName()))
+void SVGAnimatedLength::setDefaultValueAsString(const String& value)
 {
+    baseValue()->setValueAsString(value, ASSERT_NO_EXCEPTION);
 }
 
-static inline SVGLength& sharedSVGLength(SVGLengthMode mode, const String& valueAsString)
+void SVGAnimatedLength::setBaseValueAsString(const String& value, SVGLengthNegativeValuesMode mode, SVGParsingError& parseError)
 {
-    DEFINE_STATIC_LOCAL(SVGLength, sharedLength, ());
-    sharedLength.setValueAsString(valueAsString, mode, ASSERT_NO_EXCEPTION);
-    return sharedLength;
-}
+    TrackExceptionState es;
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedLengthAnimator::constructFromString(const String& string)
-{
-    return SVGAnimatedType::createLength(new SVGLength(m_lengthMode, string));
-}
+    baseValue()->setValueAsString(value, es);
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedLengthAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createLength(constructFromBaseValue<SVGAnimatedLength>(animatedTypes));
-}
-
-void SVGAnimatedLengthAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedLength>(animatedTypes);
-}
-
-void SVGAnimatedLengthAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedLength>(animatedTypes, type, &SVGAnimatedType::length);
-}
-
-void SVGAnimatedLengthAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedLength>(animatedTypes);
-}
-
-void SVGAnimatedLengthAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedLength>(animatedTypes);
-}
-
-void SVGAnimatedLengthAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedLength);
-    ASSERT(from->type() == to->type());
-
-    SVGLengthContext lengthContext(m_contextElement);
-    const SVGLength& fromLength = from->length();
-    SVGLength& toLength = to->length();
-
-    toLength.setValue(toLength.value(lengthContext) + fromLength.value(lengthContext), lengthContext, ASSERT_NO_EXCEPTION);
-}
-
-static SVGLength parseLengthFromString(SVGAnimationElement* animationElement, const String& string)
-{
-    return sharedSVGLength(SVGLength::lengthModeForAnimatedLengthAttribute(animationElement->attributeName()), string);
-}
-
-void SVGAnimatedLengthAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    SVGLength fromSVGLength = m_animationElement->animationMode() == ToAnimation ? animated->length() : from->length();
-    SVGLength toSVGLength = to->length();
-    const SVGLength& toAtEndOfDurationSVGLength = toAtEndOfDuration->length();
-    SVGLength& animatedSVGLength = animated->length();
-
-    // Apply CSS inheritance rules.
-    m_animationElement->adjustForInheritance<SVGLength>(parseLengthFromString, m_animationElement->fromPropertyValueType(), fromSVGLength, m_contextElement);
-    m_animationElement->adjustForInheritance<SVGLength>(parseLengthFromString, m_animationElement->toPropertyValueType(), toSVGLength, m_contextElement);
-
-    SVGLengthContext lengthContext(m_contextElement);
-    float animatedNumber = animatedSVGLength.value(lengthContext);
-    SVGLengthType unitType = percentage < 0.5 ? fromSVGLength.unitType() : toSVGLength.unitType();
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromSVGLength.value(lengthContext), toSVGLength.value(lengthContext), toAtEndOfDurationSVGLength.value(lengthContext), animatedNumber);
-
-    animatedSVGLength.setValue(lengthContext, animatedNumber, m_lengthMode, unitType, ASSERT_NO_EXCEPTION);
-}
-
-float SVGAnimatedLengthAnimator::calculateDistance(const String& fromString, const String& toString)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-    SVGLengthMode lengthMode = SVGLength::lengthModeForAnimatedLengthAttribute(m_animationElement->attributeName());
-    SVGLength from = SVGLength(lengthMode, fromString);
-    SVGLength to = SVGLength(lengthMode, toString);
-    SVGLengthContext lengthContext(m_contextElement);
-    return fabsf(to.value(lengthContext) - from.value(lengthContext));
+    if (es.hadException()) {
+        parseError = ParsingAttributeFailedError;
+        baseValue()->newValueSpecifiedUnits(LengthTypeNumber, 0);
+    } else if (mode == ForbidNegativeLengths && baseValue()->valueInSpecifiedUnits() < 0) {
+        parseError = NegativeValueForbiddenError;
+    }
 }
 
 }
diff --git a/Source/core/svg/SVGAnimatedLength.h b/Source/core/svg/SVGAnimatedLength.h
index d6f58ba..36efeb0 100644
--- a/Source/core/svg/SVGAnimatedLength.h
+++ b/Source/core/svg/SVGAnimatedLength.h
@@ -1,62 +1,58 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedLength_h
 #define SVGAnimatedLength_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/SVGLength.h"
-#include "core/svg/properties/SVGAnimatedPropertyTearOff.h"
+#include "core/svg/SVGLengthTearOff.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedPropertyTearOff<SVGLength> SVGAnimatedLength;
-
-// Helper macros to declare/define a SVGAnimatedLength object
-#define DECLARE_ANIMATED_LENGTH(UpperProperty, LowerProperty) \
-DECLARE_ANIMATED_PROPERTY(SVGAnimatedLength, SVGLength, UpperProperty, LowerProperty)
-
-#define DEFINE_ANIMATED_LENGTH(OwnerType, DOMAttribute, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedLength, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedLength, SVGLength)
-
-class SVGAnimationElement;
-
-class SVGAnimatedLengthAnimator : public SVGAnimatedTypeAnimator {
+class SVGAnimatedLength : public NewSVGAnimatedProperty<SVGLength> {
 public:
-    SVGAnimatedLengthAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedLengthAnimator() { }
+    static PassRefPtr<SVGAnimatedLength> create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGLength> initialValue)
+    {
+        return adoptRef(new SVGAnimatedLength(contextElement, attributeName, initialValue));
+    }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
+    void setDefaultValueAsString(const String&);
+    void setBaseValueAsString(const String&, SVGLengthNegativeValuesMode, SVGParsingError&);
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
-
-private:
-    SVGLengthMode m_lengthMode;
+protected:
+    SVGAnimatedLength(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGLength> initialValue)
+        : NewSVGAnimatedProperty<SVGLength>(contextElement, attributeName, initialValue)
+    {
+    }
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGAnimatedLength_h
diff --git a/Source/core/svg/SVGAnimatedLengthList.cpp b/Source/core/svg/SVGAnimatedLengthList.cpp
deleted file mode 100644
index 513114b..0000000
--- a/Source/core/svg/SVGAnimatedLengthList.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/svg/SVGAnimatedLengthList.h"
-
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/svg/SVGAnimateElement.h"
-#include "core/svg/SVGAnimatedNumber.h"
-
-namespace WebCore {
-
-SVGAnimatedLengthListAnimator::SVGAnimatedLengthListAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedLengthList, animationElement, contextElement)
-    , m_lengthMode(SVGLength::lengthModeForAnimatedLengthAttribute(animationElement->attributeName()))
-{
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedLengthListAnimator::constructFromString(const String& string)
-{
-    OwnPtr<SVGAnimatedType> animateType = SVGAnimatedType::createLengthList(new SVGLengthList);
-    animateType->lengthList().parse(string, m_lengthMode);
-    return animateType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedLengthListAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createLengthList(constructFromBaseValue<SVGAnimatedLengthList>(animatedTypes));
-}
-
-void SVGAnimatedLengthListAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedLengthList>(animatedTypes);
-}
-
-void SVGAnimatedLengthListAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedLengthList>(animatedTypes, type, &SVGAnimatedType::lengthList);
-}
-
-void SVGAnimatedLengthListAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedLengthList>(animatedTypes);
-}
-
-void SVGAnimatedLengthListAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedLengthList>(animatedTypes);
-}
-
-void SVGAnimatedLengthListAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedLengthList);
-    ASSERT(from->type() == to->type());
-
-    const SVGLengthList& fromLengthList = from->lengthList();
-    SVGLengthList& toLengthList = to->lengthList();
-
-    unsigned fromLengthListSize = fromLengthList.size();
-    if (!fromLengthListSize || fromLengthListSize != toLengthList.size())
-        return;
-
-    SVGLengthContext lengthContext(m_contextElement);
-    for (unsigned i = 0; i < fromLengthListSize; ++i)
-        toLengthList[i].setValue(toLengthList[i].value(lengthContext) + fromLengthList[i].value(lengthContext), lengthContext, ASSERT_NO_EXCEPTION);
-}
-
-static SVGLengthList parseLengthListFromString(SVGAnimationElement* animationElement, const String& string)
-{
-    SVGLengthList lengthList;
-    lengthList.parse(string, SVGLength::lengthModeForAnimatedLengthAttribute(animationElement->attributeName()));
-    return lengthList;
-}
-
-void SVGAnimatedLengthListAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    SVGLengthList fromLengthList = m_animationElement->animationMode() == ToAnimation ? animated->lengthList() : from->lengthList();
-    SVGLengthList toLengthList = to->lengthList();
-    const SVGLengthList& toAtEndOfDurationLengthList = toAtEndOfDuration->lengthList();
-    SVGLengthList& animatedLengthList = animated->lengthList();
-
-    // Apply CSS inheritance rules.
-    m_animationElement->adjustForInheritance<SVGLengthList>(parseLengthListFromString, m_animationElement->fromPropertyValueType(), fromLengthList, m_contextElement);
-    m_animationElement->adjustForInheritance<SVGLengthList>(parseLengthListFromString, m_animationElement->toPropertyValueType(), toLengthList, m_contextElement);
-
-    if (!m_animationElement->adjustFromToListValues<SVGLengthList>(fromLengthList, toLengthList, animatedLengthList, percentage))
-        return;
-
-    unsigned fromLengthListSize = fromLengthList.size();
-    unsigned toLengthListSize = toLengthList.size();
-    unsigned toAtEndOfDurationListSize = toAtEndOfDurationLengthList.size();
-
-    SVGLengthContext lengthContext(m_contextElement);
-    for (unsigned i = 0; i < toLengthListSize; ++i) {
-        float animatedNumber = animatedLengthList[i].value(lengthContext);
-        SVGLengthType unitType = toLengthList[i].unitType();
-        float effectiveFrom = 0;
-        if (fromLengthListSize) {
-            if (percentage < 0.5)
-                unitType = fromLengthList[i].unitType();
-            effectiveFrom = fromLengthList[i].value(lengthContext);
-        }
-        float effectiveToAtEnd = i < toAtEndOfDurationListSize ? toAtEndOfDurationLengthList[i].value(lengthContext) : 0;
-
-        m_animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom, toLengthList[i].value(lengthContext), effectiveToAtEnd, animatedNumber);
-        animatedLengthList[i].setValue(lengthContext, animatedNumber, m_lengthMode, unitType, ASSERT_NO_EXCEPTION);
-    }
-}
-
-float SVGAnimatedLengthListAnimator::calculateDistance(const String&, const String&)
-{
-    // FIXME: Distance calculation is not possible for SVGLengthList right now. We need the distance for every single value.
-    return -1;
-}
-
-}
diff --git a/Source/core/svg/SVGAnimatedLengthList.h b/Source/core/svg/SVGAnimatedLengthList.h
index 805b7b1..8b4f5f1 100644
--- a/Source/core/svg/SVGAnimatedLengthList.h
+++ b/Source/core/svg/SVGAnimatedLengthList.h
@@ -1,61 +1,42 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedLengthList_h
 #define SVGAnimatedLengthList_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/SVGLengthList.h"
-#include "core/svg/properties/SVGAnimatedListPropertyTearOff.h"
+#include "core/svg/SVGLengthListTearOff.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedListPropertyTearOff<SVGLengthList> SVGAnimatedLengthList;
-
-// Helper macros to declare/define a SVGAnimatedLengthList object
-#define DECLARE_ANIMATED_LENGTH_LIST(UpperProperty, LowerProperty) \
-DECLARE_ANIMATED_LIST_PROPERTY(SVGAnimatedLengthList, SVGLengthList, UpperProperty, LowerProperty)
-
-#define DEFINE_ANIMATED_LENGTH_LIST(OwnerType, DOMAttribute, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedLengthList, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedLengthList, SVGLengthList)
-
-class SVGAnimationElement;
-
-class SVGAnimatedLengthListAnimator : public SVGAnimatedTypeAnimator {
-public:
-    SVGAnimatedLengthListAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedLengthListAnimator() { }
-
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
-
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
-
-private:
-    SVGLengthMode m_lengthMode;
-};
+typedef NewSVGAnimatedProperty<SVGLengthList> SVGAnimatedLengthList;
 
 } // namespace WebCore
 
diff --git a/Source/core/svg/SVGAnimatedNewPropertyAnimator.cpp b/Source/core/svg/SVGAnimatedNewPropertyAnimator.cpp
new file mode 100644
index 0000000..328f822
--- /dev/null
+++ b/Source/core/svg/SVGAnimatedNewPropertyAnimator.cpp
@@ -0,0 +1,262 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/svg/SVGAnimatedNewPropertyAnimator.h"
+
+#include "core/svg/SVGAnimatedColor.h"
+#include "core/svg/SVGAnimationElement.h"
+#include "core/svg/SVGElementInstance.h"
+#include "core/svg/SVGLength.h"
+#include "core/svg/SVGLengthList.h"
+#include "core/svg/SVGNumber.h"
+#include "core/svg/SVGPointList.h"
+#include "core/svg/SVGString.h"
+
+namespace WebCore {
+
+SVGAnimatedNewPropertyAnimator::SVGAnimatedNewPropertyAnimator(AnimatedPropertyType type, SVGAnimationElement* animationElement, SVGElement* contextElement)
+    : SVGAnimatedTypeAnimator(type, animationElement, contextElement)
+{
+    ASSERT(m_animationElement);
+    ASSERT(m_contextElement);
+
+    const QualifiedName& attributeName = m_animationElement->attributeName();
+    m_animatedProperty = m_contextElement->propertyFromAttribute(attributeName);
+    if (m_animatedProperty)
+        ASSERT(m_animatedProperty->type() == m_type);
+}
+
+SVGAnimatedNewPropertyAnimator::~SVGAnimatedNewPropertyAnimator()
+{
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGAnimatedNewPropertyAnimator::createPropertyForAnimation(const String& value)
+{
+    if (isAnimatingSVGDom()) {
+        ASSERT(m_animatedProperty);
+
+        // SVG DOM animVal animation code-path.
+        return m_animatedProperty->currentValueBase()->cloneForAnimation(value);
+    }
+
+    ASSERT(isAnimatingCSSProperty());
+
+    // CSS properties animation code-path.
+    // Create a basic instance of the corresponding SVG property.
+    // The instance will not have full context info. (e.g. SVGLengthMode)
+
+    switch (m_type) {
+    case AnimatedColor:
+        return SVGColorProperty::create(value.isEmpty() ? StyleColor::currentColor() : SVGColor::colorFromRGBColorString(value));
+    case AnimatedNumber: {
+        RefPtr<SVGNumber> property = SVGNumber::create();
+        property->setValueAsString(value, IGNORE_EXCEPTION);
+        return property.release();
+    }
+    case AnimatedLength: {
+        RefPtr<SVGLength> property = SVGLength::create(LengthModeOther);
+        property->setValueAsString(value, IGNORE_EXCEPTION);
+        return property.release();
+    }
+    case AnimatedLengthList: {
+        RefPtr<SVGLengthList> property = SVGLengthList::create(LengthModeOther);
+        property->setValueAsString(value, IGNORE_EXCEPTION);
+        return property.release();
+    }
+    case AnimatedString: {
+        RefPtr<SVGString> property = SVGString::create();
+        property->setValueAsString(value, IGNORE_EXCEPTION);
+        return property.release();
+    }
+
+    // These types don't appear in the table in SVGElement::cssPropertyToTypeMap() and thus don't need support.
+    case AnimatedBoolean:
+    case AnimatedNumberList:
+    case AnimatedNumberOptionalNumber:
+    case AnimatedPoint:
+    case AnimatedPoints:
+    case AnimatedRect:
+        ASSERT_NOT_REACHED();
+
+    // These properties are not yet migrated to NewProperty implementation. see http://crbug.com/308818
+    case AnimatedAngle:
+    case AnimatedEnumeration:
+    case AnimatedInteger:
+    case AnimatedIntegerOptionalInteger:
+    case AnimatedPath:
+    case AnimatedPreserveAspectRatio:
+    case AnimatedStringList:
+    case AnimatedTransformList:
+        ASSERT_NOT_REACHED();
+
+    case AnimatedUnknown:
+        ASSERT_NOT_REACHED();
+    };
+
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
+PassOwnPtr<SVGAnimatedType> SVGAnimatedNewPropertyAnimator::constructFromString(const String& value)
+{
+    return SVGAnimatedType::createNewProperty(createPropertyForAnimation(value));
+}
+
+namespace {
+
+typedef void (NewSVGAnimatedPropertyBase::*NewSVGAnimatedPropertyMethod)();
+
+void invokeMethodOnAllTargetProperties(const SVGElementAnimatedPropertyList& list, const QualifiedName& attributeName, NewSVGAnimatedPropertyMethod method)
+{
+    SVGElementAnimatedPropertyList::const_iterator it = list.begin();
+    SVGElementAnimatedPropertyList::const_iterator itEnd = list.end();
+    for (; it != itEnd; ++it) {
+        RefPtr<NewSVGAnimatedPropertyBase> animatedProperty = it->element->propertyFromAttribute(attributeName);
+        if (animatedProperty)
+            (animatedProperty.get()->*method)();
+    }
+}
+
+void setAnimatedValueOnAllTargetProperties(const SVGElementAnimatedPropertyList& list, const QualifiedName& attributeName, PassRefPtr<NewSVGPropertyBase> passValue)
+{
+    RefPtr<NewSVGPropertyBase> value = passValue;
+
+    SVGElementAnimatedPropertyList::const_iterator it = list.begin();
+    SVGElementAnimatedPropertyList::const_iterator itEnd = list.end();
+    for (; it != itEnd; ++it) {
+        RefPtr<NewSVGAnimatedPropertyBase> animatedProperty = it->element->propertyFromAttribute(attributeName);
+        if (animatedProperty)
+            animatedProperty->setAnimatedValue(value);
+    }
+}
+
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGAnimatedNewPropertyAnimator::resetAnimation(const SVGElementAnimatedPropertyList& list)
+{
+    ASSERT(isAnimatingSVGDom());
+    RefPtr<NewSVGPropertyBase> animatedValue = m_animatedProperty->createAnimatedValue();
+    ASSERT(animatedValue->type() == m_type);
+    setAnimatedValueOnAllTargetProperties(list, m_animatedProperty->attributeName(), animatedValue);
+
+    return animatedValue.release();
+}
+
+PassOwnPtr<SVGAnimatedType> SVGAnimatedNewPropertyAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& list)
+{
+    ASSERT(isAnimatingSVGDom());
+    SVGElementInstance::InstanceUpdateBlocker blocker(m_contextElement);
+
+    invokeMethodOnAllTargetProperties(list, m_animatedProperty->attributeName(), &NewSVGAnimatedPropertyBase::animationStarted);
+
+    return SVGAnimatedType::createNewProperty(resetAnimation(list));
+}
+
+void SVGAnimatedNewPropertyAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& list)
+{
+    ASSERT(isAnimatingSVGDom());
+    SVGElementInstance::InstanceUpdateBlocker blocker(m_contextElement);
+
+    invokeMethodOnAllTargetProperties(list, m_animatedProperty->attributeName(), &NewSVGAnimatedPropertyBase::animationEnded);
+}
+
+void SVGAnimatedNewPropertyAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& list, SVGAnimatedType* animated)
+{
+    SVGElementInstance::InstanceUpdateBlocker blocker(m_contextElement);
+
+    animated->newProperty() = resetAnimation(list);
+}
+
+void SVGAnimatedNewPropertyAnimator::animValWillChange(const SVGElementAnimatedPropertyList& list)
+{
+    ASSERT(isAnimatingSVGDom());
+    SVGElementInstance::InstanceUpdateBlocker blocker(m_contextElement);
+
+    invokeMethodOnAllTargetProperties(list, m_animatedProperty->attributeName(), &NewSVGAnimatedPropertyBase::animValWillChange);
+}
+
+void SVGAnimatedNewPropertyAnimator::animValDidChange(const SVGElementAnimatedPropertyList& list)
+{
+    ASSERT(isAnimatingSVGDom());
+    SVGElementInstance::InstanceUpdateBlocker blocker(m_contextElement);
+
+    invokeMethodOnAllTargetProperties(list, m_animatedProperty->attributeName(), &NewSVGAnimatedPropertyBase::animValDidChange);
+}
+
+void SVGAnimatedNewPropertyAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
+{
+    to->newProperty()->add(from->newProperty(), m_contextElement);
+}
+
+class ParsePropertyFromString {
+public:
+    explicit ParsePropertyFromString(SVGAnimatedNewPropertyAnimator* animator)
+        : m_animator(animator)
+    {
+    }
+
+    PassRefPtr<NewSVGPropertyBase> operator()(SVGAnimationElement*, const String& value)
+    {
+        return m_animator->createPropertyForAnimation(value);
+    }
+
+private:
+    SVGAnimatedNewPropertyAnimator* m_animator;
+};
+
+void SVGAnimatedNewPropertyAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
+{
+    ASSERT(m_animationElement);
+    ASSERT(m_contextElement);
+
+    RefPtr<NewSVGPropertyBase> fromValue = m_animationElement->animationMode() == ToAnimation ? animated->newProperty() : from->newProperty();
+    RefPtr<NewSVGPropertyBase> toValue = to->newProperty();
+    RefPtr<NewSVGPropertyBase> toAtEndOfDurationValue = toAtEndOfDuration->newProperty();
+    RefPtr<NewSVGPropertyBase> animatedValue = animated->newProperty();
+
+    // Apply CSS inheritance rules.
+    ParsePropertyFromString parsePropertyFromString(this);
+    m_animationElement->adjustForInheritance<RefPtr<NewSVGPropertyBase>, ParsePropertyFromString>(parsePropertyFromString, m_animationElement->fromPropertyValueType(), fromValue, m_contextElement);
+    m_animationElement->adjustForInheritance<RefPtr<NewSVGPropertyBase>, ParsePropertyFromString>(parsePropertyFromString, m_animationElement->toPropertyValueType(), toValue, m_contextElement);
+
+    animatedValue->calculateAnimatedValue(m_animationElement, percentage, repeatCount, fromValue, toValue, toAtEndOfDurationValue, m_contextElement);
+}
+
+float SVGAnimatedNewPropertyAnimator::calculateDistance(const String& fromString, const String& toString)
+{
+    ASSERT(m_animationElement);
+    ASSERT(m_contextElement);
+    RefPtr<NewSVGPropertyBase> fromValue = createPropertyForAnimation(fromString);
+    RefPtr<NewSVGPropertyBase> toValue = createPropertyForAnimation(toString);
+    return fromValue->calculateDistance(toValue, m_contextElement);
+}
+
+} // namespace WebCore
diff --git a/Source/core/svg/SVGAnimatedNewPropertyAnimator.h b/Source/core/svg/SVGAnimatedNewPropertyAnimator.h
new file mode 100644
index 0000000..4057e31
--- /dev/null
+++ b/Source/core/svg/SVGAnimatedNewPropertyAnimator.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGAnimatedNewPropertyAnimator_h
+#define SVGAnimatedNewPropertyAnimator_h
+
+#include "core/svg/SVGAnimatedTypeAnimator.h"
+
+namespace WebCore {
+
+class NewSVGAnimatedPropertyBase;
+
+// Bridges new SVGProperty impl. to existing SVG animation impl.
+class SVGAnimatedNewPropertyAnimator FINAL : public SVGAnimatedTypeAnimator {
+public:
+    SVGAnimatedNewPropertyAnimator(AnimatedPropertyType, SVGAnimationElement*, SVGElement*);
+    virtual ~SVGAnimatedNewPropertyAnimator();
+
+    PassRefPtr<NewSVGPropertyBase> createPropertyForAnimation(const String&);
+
+    // SVGAnimatedTypeAnimator:
+    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&) OVERRIDE;
+
+    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*) OVERRIDE;
+    virtual void animValWillChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void animValDidChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+
+    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+    virtual float calculateDistance(const String& fromString, const String& toString) OVERRIDE;
+
+private:
+    PassRefPtr<NewSVGPropertyBase> resetAnimation(const SVGElementAnimatedPropertyList&);
+
+    bool isAnimatingSVGDom() const { return m_animatedProperty; }
+    bool isAnimatingCSSProperty() const { return !m_animatedProperty; }
+
+    RefPtr<NewSVGAnimatedPropertyBase> m_animatedProperty;
+};
+
+} // namespace WebCore
+
+#endif // SVGAnimatedNewPropertyAnimator_h
diff --git a/Source/core/svg/SVGAnimatedNumber.cpp b/Source/core/svg/SVGAnimatedNumber.cpp
index 4c759ee..9c1fc97 100644
--- a/Source/core/svg/SVGAnimatedNumber.cpp
+++ b/Source/core/svg/SVGAnimatedNumber.cpp
@@ -1,112 +1,49 @@
 /*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #include "config.h"
 
 #include "core/svg/SVGAnimatedNumber.h"
-
-#include "core/svg/SVGAnimateElement.h"
-#include "core/svg/SVGParserUtilities.h"
-
-using namespace std;
+#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
 
 namespace WebCore {
 
-SVGAnimatedNumberAnimator::SVGAnimatedNumberAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedNumber, animationElement, contextElement)
+void SVGAnimatedNumber::synchronizeAttribute()
 {
-}
+    ASSERT(needsSynchronizeAttribute());
+    if (m_parentNumberOptionalNumber) {
+        m_parentNumberOptionalNumber->synchronizeAttribute();
+        return;
+    }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedNumberAnimator::constructFromString(const String& string)
-{
-    OwnPtr<SVGAnimatedType> animtedType = SVGAnimatedType::createNumber(new float);
-    float& animatedNumber = animtedType->number();
-    if (!parseNumberFromString(string, animatedNumber))
-        animatedNumber = 0;
-    return animtedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedNumberAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createNumber(constructFromBaseValue<SVGAnimatedNumber>(animatedTypes));
-}
-
-void SVGAnimatedNumberAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedNumber>(animatedTypes);
-}
-
-void SVGAnimatedNumberAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedNumber>(animatedTypes, type, &SVGAnimatedType::number);
-}
-
-void SVGAnimatedNumberAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedNumber>(animatedTypes);
-}
-
-void SVGAnimatedNumberAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedNumber>(animatedTypes);
-}
-
-void SVGAnimatedNumberAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedNumber);
-    ASSERT(from->type() == to->type());
-
-    to->number() += from->number();
-}
-
-static float parseNumberFromString(SVGAnimationElement*, const String& string)
-{
-    float number = 0;
-    parseNumberFromString(string, number);
-    return number;
-}
-
-void SVGAnimatedNumberAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    float fromNumber = m_animationElement->animationMode() == ToAnimation ? animated->number() : from->number();
-    float toNumber = to->number();
-    float toAtEndOfDurationNumber = toAtEndOfDuration->number();
-    float& animatedNumber = animated->number();
-
-    // Apply CSS inheritance rules.
-    m_animationElement->adjustForInheritance<float>(parseNumberFromString, m_animationElement->fromPropertyValueType(), fromNumber, m_contextElement);
-    m_animationElement->adjustForInheritance<float>(parseNumberFromString, m_animationElement->toPropertyValueType(), toNumber, m_contextElement);
-
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromNumber, toNumber, toAtEndOfDurationNumber, animatedNumber);
-}
-
-float SVGAnimatedNumberAnimator::calculateDistance(const String& fromString, const String& toString)
-{
-    ASSERT(m_contextElement);
-    float from = 0;
-    float to = 0;
-    parseNumberFromString(fromString, from);
-    parseNumberFromString(toString, to);
-    return fabsf(to - from);
+    NewSVGAnimatedProperty<SVGNumber>::synchronizeAttribute();
 }
 
 }
diff --git a/Source/core/svg/SVGAnimatedNumber.h b/Source/core/svg/SVGAnimatedNumber.h
index 7c5e54e..3327908 100644
--- a/Source/core/svg/SVGAnimatedNumber.h
+++ b/Source/core/svg/SVGAnimatedNumber.h
@@ -1,62 +1,69 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedNumber_h
 #define SVGAnimatedNumber_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/properties/SVGAnimatedPropertyMacros.h"
-#include "core/svg/properties/SVGAnimatedStaticPropertyTearOff.h"
+#include "core/svg/SVGNumberTearOff.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedStaticPropertyTearOff<float> SVGAnimatedNumber;
+class SVGAnimatedNumberOptionalNumber;
 
-// Helper macros to declare/define a SVGAnimatedNumber object
-#define DECLARE_ANIMATED_NUMBER(UpperProperty, LowerProperty) \
-DECLARE_ANIMATED_PROPERTY(SVGAnimatedNumber, float, UpperProperty, LowerProperty)
-
-#define DEFINE_ANIMATED_NUMBER(OwnerType, DOMAttribute, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedNumber, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedNumber, float)
-
-#define DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(OwnerType, DOMAttribute, SVGDOMAttributeIdentifier, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedNumberOptionalNumber, OwnerType, DOMAttribute, SVGDOMAttributeIdentifier, UpperProperty, LowerProperty, SVGAnimatedNumber, float)
-
-class SVGAnimationElement;
-
-class SVGAnimatedNumberAnimator : public SVGAnimatedTypeAnimator {
+// SVG Spec: http://www.w3.org/TR/SVG11/types.html#InterfaceSVGAnimatedNumber
+class SVGAnimatedNumber : public NewSVGAnimatedProperty<SVGNumber> {
 public:
-    SVGAnimatedNumberAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedNumberAnimator() { }
+    static PassRefPtr<SVGAnimatedNumber> create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGNumber> initialValue)
+    {
+        return adoptRef(new SVGAnimatedNumber(contextElement, attributeName, initialValue));
+    }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
+    virtual void synchronizeAttribute() OVERRIDE;
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+    void setParentOptionalNumber(SVGAnimatedNumberOptionalNumber* numberOptionalNumber)
+    {
+        m_parentNumberOptionalNumber = numberOptionalNumber;
+    }
+
+protected:
+    SVGAnimatedNumber(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGNumber> initialValue)
+        : NewSVGAnimatedProperty<SVGNumber>(contextElement, attributeName, initialValue)
+        , m_parentNumberOptionalNumber(0)
+    {
+    }
+
+    // FIXME: oilpan: This is kept as raw ptr as this is a back ptr. Change this to Member<> in oilpan.
+    SVGAnimatedNumberOptionalNumber* m_parentNumberOptionalNumber;
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGAnimatedNumber_h
diff --git a/Source/core/svg/SVGAnimatedNumber.idl b/Source/core/svg/SVGAnimatedNumber.idl
index e8cc9ba..7890bef 100644
--- a/Source/core/svg/SVGAnimatedNumber.idl
+++ b/Source/core/svg/SVGAnimatedNumber.idl
@@ -24,8 +24,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGAnimatedNumber {
-    [StrictTypeChecking, RaisesException=Setter] attribute float baseVal;
+[
+    StrictTypeChecking,
+] interface SVGAnimatedNumber {
+    [RaisesException=Setter] attribute float baseVal;
     readonly attribute float animVal;
 };
-
diff --git a/Source/core/svg/SVGAnimatedNumberList.cpp b/Source/core/svg/SVGAnimatedNumberList.cpp
deleted file mode 100644
index 7f1d9e7..0000000
--- a/Source/core/svg/SVGAnimatedNumberList.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGAnimatedNumberList.h"
-
-#include "core/svg/SVGAnimateElement.h"
-#include "core/svg/SVGAnimatedNumber.h"
-
-namespace WebCore {
-
-SVGAnimatedNumberListAnimator::SVGAnimatedNumberListAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedNumberList, animationElement, contextElement)
-{
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedNumberListAnimator::constructFromString(const String& string)
-{
-    OwnPtr<SVGAnimatedType> animtedType = SVGAnimatedType::createNumberList(new SVGNumberList);
-    animtedType->numberList().parse(string);
-    return animtedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedNumberListAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createNumberList(constructFromBaseValue<SVGAnimatedNumberList>(animatedTypes));
-}
-
-void SVGAnimatedNumberListAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedNumberList>(animatedTypes);
-}
-
-void SVGAnimatedNumberListAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedNumberList>(animatedTypes, type, &SVGAnimatedType::numberList);
-}
-
-void SVGAnimatedNumberListAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedNumberList>(animatedTypes);
-}
-
-void SVGAnimatedNumberListAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedNumberList>(animatedTypes);
-}
-
-void SVGAnimatedNumberListAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedNumberList);
-    ASSERT(from->type() == to->type());
-
-    const SVGNumberList& fromNumberList = from->numberList();
-    SVGNumberList& toNumberList = to->numberList();
-
-    unsigned fromNumberListSize = fromNumberList.size();
-    if (!fromNumberListSize || fromNumberListSize != toNumberList.size())
-        return;
-
-    for (unsigned i = 0; i < fromNumberListSize; ++i)
-        toNumberList[i] += fromNumberList[i];
-}
-
-void SVGAnimatedNumberListAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-
-    const SVGNumberList& fromNumberList = m_animationElement->animationMode() == ToAnimation ? animated->numberList() : from->numberList();
-    const SVGNumberList& toNumberList = to->numberList();
-    const SVGNumberList& toAtEndOfDurationNumberList = toAtEndOfDuration->numberList();
-    SVGNumberList& animatedNumberList = animated->numberList();
-    if (!m_animationElement->adjustFromToListValues<SVGNumberList>(fromNumberList, toNumberList, animatedNumberList, percentage))
-        return;
-
-    unsigned fromNumberListSize = fromNumberList.size();
-    unsigned toNumberListSize = toNumberList.size();
-    unsigned toAtEndOfDurationSize = toAtEndOfDurationNumberList.size();
-
-    for (unsigned i = 0; i < toNumberListSize; ++i) {
-        float effectiveFrom = fromNumberListSize ? fromNumberList[i].value() : 0;
-        float effectiveToAtEnd = i < toAtEndOfDurationSize ? toAtEndOfDurationNumberList[i].value() : 0;
-        m_animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom, toNumberList[i].value(), effectiveToAtEnd, animatedNumberList[i].valueRef());
-    }
-}
-
-float SVGAnimatedNumberListAnimator::calculateDistance(const String&, const String&)
-{
-    // FIXME: Distance calculation is not possible for SVGNumberList right now. We need the distance for every single value.
-    return -1;
-}
-
-}
diff --git a/Source/core/svg/SVGAnimatedNumberList.h b/Source/core/svg/SVGAnimatedNumberList.h
index a144c3f..79ddef0 100644
--- a/Source/core/svg/SVGAnimatedNumberList.h
+++ b/Source/core/svg/SVGAnimatedNumberList.h
@@ -1,58 +1,42 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedNumberList_h
 #define SVGAnimatedNumberList_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/SVGNumberList.h"
-#include "core/svg/properties/SVGAnimatedListPropertyTearOff.h"
+#include "core/svg/SVGNumberListTearOff.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedListPropertyTearOff<SVGNumberList> SVGAnimatedNumberList;
-
-// Helper macros to declare/define a SVGAnimatedNumberList object
-#define DECLARE_ANIMATED_NUMBER_LIST(UpperProperty, LowerProperty) \
-DECLARE_ANIMATED_LIST_PROPERTY(SVGAnimatedNumberList, SVGNumberList, UpperProperty, LowerProperty)
-
-#define DEFINE_ANIMATED_NUMBER_LIST(OwnerType, DOMAttribute, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedNumberList, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedNumberList, SVGNumberList)
-
-class SVGAnimationElement;
-
-class SVGAnimatedNumberListAnimator : public SVGAnimatedTypeAnimator {
-public:
-    SVGAnimatedNumberListAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedNumberListAnimator() { }
-
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
-
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
-};
+typedef NewSVGAnimatedProperty<SVGNumberList> SVGAnimatedNumberList;
 
 } // namespace WebCore
 
diff --git a/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp b/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp
index e3e55a6..1073b73 100644
--- a/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp
+++ b/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp
@@ -21,85 +21,57 @@
 
 #include "core/svg/SVGAnimatedNumberOptionalNumber.h"
 
-#include "core/svg/SVGAnimateElement.h"
-#include "core/svg/SVGAnimatedNumber.h"
-#include "core/svg/SVGParserUtilities.h"
-
-using namespace std;
-
 namespace WebCore {
 
-SVGAnimatedNumberOptionalNumberAnimator::SVGAnimatedNumberOptionalNumberAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedNumberOptionalNumber, animationElement, contextElement)
+SVGAnimatedNumberOptionalNumber::SVGAnimatedNumberOptionalNumber(SVGElement* contextElement, const QualifiedName& attributeName, float initialFirstValue, float initialSecondValue)
+    : NewSVGAnimatedPropertyCommon<SVGNumberOptionalNumber>(contextElement, attributeName,
+        SVGNumberOptionalNumber::create(SVGNumber::create(initialFirstValue), SVGNumber::create(initialSecondValue)))
+    , m_firstNumber(SVGAnimatedNumber::create(contextElement, attributeName, baseValue()->firstNumber()))
+    , m_secondNumber(SVGAnimatedNumber::create(contextElement, attributeName, baseValue()->secondNumber()))
 {
+    m_firstNumber->setParentOptionalNumber(this);
+    m_secondNumber->setParentOptionalNumber(this);
 }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedNumberOptionalNumberAnimator::constructFromString(const String& string)
+void SVGAnimatedNumberOptionalNumber::animationStarted()
 {
-    OwnPtr<SVGAnimatedType> animtedType = SVGAnimatedType::createNumberOptionalNumber(new pair<float, float>);
-    pair<float, float>& animatedNumber = animtedType->numberOptionalNumber();
-    if (!parseNumberOptionalNumber(string, animatedNumber.first, animatedNumber.second)) {
-        animatedNumber.first = 0;
-        animatedNumber.second = 0;
-    }
-    return animtedType.release();
+    NewSVGAnimatedPropertyCommon<SVGNumberOptionalNumber>::animationStarted();
+    m_firstNumber->animationStarted();
+    m_secondNumber->animationStarted();
 }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedNumberOptionalNumberAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
+void SVGAnimatedNumberOptionalNumber::setAnimatedValue(PassRefPtr<NewSVGPropertyBase> value)
 {
-    return SVGAnimatedType::createNumberOptionalNumber(constructFromBaseValues<SVGAnimatedNumber, SVGAnimatedNumber>(animatedTypes));
+    NewSVGAnimatedPropertyCommon<SVGNumberOptionalNumber>::setAnimatedValue(value);
+    m_firstNumber->setAnimatedValue(currentValue()->firstNumber());
+    m_secondNumber->setAnimatedValue(currentValue()->secondNumber());
 }
 
-void SVGAnimatedNumberOptionalNumberAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
+void SVGAnimatedNumberOptionalNumber::animationEnded()
 {
-    stopAnimValAnimationForTypes<SVGAnimatedNumber, SVGAnimatedNumber>(animatedTypes);
+    NewSVGAnimatedPropertyCommon<SVGNumberOptionalNumber>::animationEnded();
+    m_firstNumber->animationEnded();
+    m_secondNumber->animationEnded();
 }
 
-void SVGAnimatedNumberOptionalNumberAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
+void SVGAnimatedNumberOptionalNumber::animValWillChange()
 {
-    resetFromBaseValues<SVGAnimatedNumber, SVGAnimatedNumber>(animatedTypes, type, &SVGAnimatedType::numberOptionalNumber);
+    NewSVGAnimatedPropertyCommon<SVGNumberOptionalNumber>::animValWillChange();
+    m_firstNumber->animValWillChange();
+    m_secondNumber->animValWillChange();
 }
 
-void SVGAnimatedNumberOptionalNumberAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
+void SVGAnimatedNumberOptionalNumber::animValDidChange()
 {
-    animValWillChangeForTypes<SVGAnimatedNumber, SVGAnimatedNumber>(animatedTypes);
+    NewSVGAnimatedPropertyCommon<SVGNumberOptionalNumber>::animValDidChange();
+    m_firstNumber->animValDidChange();
+    m_secondNumber->animValDidChange();
 }
 
-void SVGAnimatedNumberOptionalNumberAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
+bool SVGAnimatedNumberOptionalNumber::needsSynchronizeAttribute()
 {
-    animValDidChangeForTypes<SVGAnimatedNumber, SVGAnimatedNumber>(animatedTypes);
-}
-
-void SVGAnimatedNumberOptionalNumberAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedNumberOptionalNumber);
-    ASSERT(from->type() == to->type());
-
-    const pair<float, float>& fromNumberPair = from->numberOptionalNumber();
-    pair<float, float>& toNumberPair = to->numberOptionalNumber();
-
-    toNumberPair.first += fromNumberPair.first;
-    toNumberPair.second += fromNumberPair.second;
-}
-
-void SVGAnimatedNumberOptionalNumberAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    const pair<float, float>& fromNumberPair = m_animationElement->animationMode() == ToAnimation ? animated->numberOptionalNumber() :  from->numberOptionalNumber();
-    const pair<float, float>& toNumberPair = to->numberOptionalNumber();
-    const pair<float, float>& toAtEndOfDurationNumberPair = toAtEndOfDuration->numberOptionalNumber();
-    pair<float, float>& animatedNumberPair = animated->numberOptionalNumber();
-
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromNumberPair.first, toNumberPair.first, toAtEndOfDurationNumberPair.first, animatedNumberPair.first);
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromNumberPair.second, toNumberPair.second, toAtEndOfDurationNumberPair.second, animatedNumberPair.second);
-}
-
-float SVGAnimatedNumberOptionalNumberAnimator::calculateDistance(const String&, const String&)
-{
-    // FIXME: Distance calculation is not possible for SVGNumberOptionalNumber right now. We need the distance for every single value.
-    return -1;
+    return m_firstNumber->needsSynchronizeAttribute()
+        || m_secondNumber->needsSynchronizeAttribute();
 }
 
 }
diff --git a/Source/core/svg/SVGAnimatedNumberOptionalNumber.h b/Source/core/svg/SVGAnimatedNumberOptionalNumber.h
index 3e43d9a..b9ff601 100644
--- a/Source/core/svg/SVGAnimatedNumberOptionalNumber.h
+++ b/Source/core/svg/SVGAnimatedNumberOptionalNumber.h
@@ -1,48 +1,70 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedNumberOptionalNumber_h
 #define SVGAnimatedNumberOptionalNumber_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
+#include "core/svg/SVGAnimatedNumber.h"
+#include "core/svg/SVGNumberOptionalNumber.h"
 
 namespace WebCore {
 
-class SVGAnimationElement;
-
-class SVGAnimatedNumberOptionalNumberAnimator : public SVGAnimatedTypeAnimator {
+// SVG Spec: http://www.w3.org/TR/SVG11/types.html <number-optional-number>
+// Unlike other SVGAnimated* class, this class is not exposed to Javascript directly,
+// while DOM attribute and SMIL animations operate on this class.
+// From Javascript, the two SVGAnimatedNumbers |firstNumber| and |secondNumber| are used.
+// For example, see SVGFEDropShadowElement::stdDeviation{X,Y}()
+class SVGAnimatedNumberOptionalNumber : public NewSVGAnimatedPropertyCommon<SVGNumberOptionalNumber> {
 public:
-    SVGAnimatedNumberOptionalNumberAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedNumberOptionalNumberAnimator() { }
+    static PassRefPtr<SVGAnimatedNumberOptionalNumber> create(SVGElement* contextElement, const QualifiedName& attributeName, float initialFirstValue = 0, float initialSecondValue = 0)
+    {
+        return adoptRef(new SVGAnimatedNumberOptionalNumber(contextElement, attributeName, initialFirstValue, initialSecondValue));
+    }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
+    virtual void animationStarted() OVERRIDE;
+    virtual void setAnimatedValue(PassRefPtr<NewSVGPropertyBase>) OVERRIDE;
+    virtual bool needsSynchronizeAttribute() OVERRIDE;
+    virtual void animationEnded() OVERRIDE;
+    virtual void animValWillChange() OVERRIDE;
+    virtual void animValDidChange() OVERRIDE;
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+    SVGAnimatedNumber* firstNumber() { return m_firstNumber.get(); }
+    SVGAnimatedNumber* secondNumber() { return m_secondNumber.get(); }
+
+protected:
+    SVGAnimatedNumberOptionalNumber(SVGElement* contextElement, const QualifiedName& attributeName, float initialFirstValue, float initialSecondValue);
+
+    RefPtr<SVGAnimatedNumber> m_firstNumber;
+    RefPtr<SVGAnimatedNumber> m_secondNumber;
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGAnimatedNumberOptionalNumber_h
diff --git a/Source/core/svg/SVGAnimatedPath.h b/Source/core/svg/SVGAnimatedPath.h
index cca7bbd..d7534b2 100644
--- a/Source/core/svg/SVGAnimatedPath.h
+++ b/Source/core/svg/SVGAnimatedPath.h
@@ -26,21 +26,21 @@
 
 class SVGAnimationElement;
 
-class SVGAnimatedPathAnimator : public SVGAnimatedTypeAnimator {
+class SVGAnimatedPathAnimator FINAL : public SVGAnimatedTypeAnimator {
 public:
     SVGAnimatedPathAnimator(SVGAnimationElement*, SVGElement*);
     virtual ~SVGAnimatedPathAnimator() { }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
+    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&) OVERRIDE;
+    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*) OVERRIDE;
+    virtual void animValWillChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void animValDidChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+    virtual float calculateDistance(const String& fromString, const String& toString) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGAnimatedPointList.cpp b/Source/core/svg/SVGAnimatedPointList.cpp
deleted file mode 100644
index fd68ad0..0000000
--- a/Source/core/svg/SVGAnimatedPointList.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011, 2012. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGAnimatedPointList.h"
-
-#include "core/svg/SVGAnimateElement.h"
-#include "core/svg/SVGParserUtilities.h"
-
-namespace WebCore {
-
-SVGAnimatedPointListAnimator::SVGAnimatedPointListAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedPoints, animationElement, contextElement)
-{
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedPointListAnimator::constructFromString(const String& string)
-{
-    OwnPtr<SVGAnimatedType> animtedType = SVGAnimatedType::createPointList(new SVGPointList);
-    pointsListFromSVGData(animtedType->pointList(), string);
-    return animtedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedPointListAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createPointList(constructFromBaseValue<SVGAnimatedPointList>(animatedTypes));
-}
-
-void SVGAnimatedPointListAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedPointList>(animatedTypes);
-}
-
-void SVGAnimatedPointListAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedPointList>(animatedTypes, type, &SVGAnimatedType::pointList);
-}
-
-void SVGAnimatedPointListAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedPointList>(animatedTypes);
-}
-
-void SVGAnimatedPointListAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedPointList>(animatedTypes);
-}
-
-void SVGAnimatedPointListAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedPoints);
-    ASSERT(from->type() == to->type());
-
-    const SVGPointList& fromPointList = from->pointList();
-    SVGPointList& toPointList = to->pointList();
-
-    unsigned fromPointListSize = fromPointList.size();
-    if (!fromPointListSize || fromPointListSize != toPointList.size())
-        return;
-
-    for (unsigned i = 0; i < fromPointListSize; ++i)
-        toPointList[i] += fromPointList[i];
-}
-
-void SVGAnimatedPointListAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-
-    const SVGPointList& fromPointList = m_animationElement->animationMode() == ToAnimation ? animated->pointList() : from->pointList();
-    const SVGPointList& toPointList = to->pointList();
-    const SVGPointList& toAtEndOfDurationPointList = toAtEndOfDuration->pointList();
-    SVGPointList& animatedPointList = animated->pointList();
-    if (!m_animationElement->adjustFromToListValues<SVGPointList>(fromPointList, toPointList, animatedPointList, percentage))
-        return;
-
-    unsigned fromPointListSize = fromPointList.size();
-    unsigned toPointListSize = toPointList.size();
-    unsigned toAtEndOfDurationSize = toAtEndOfDurationPointList.size();
-
-    for (unsigned i = 0; i < toPointListSize; ++i) {
-        FloatPoint effectiveFrom;
-        if (fromPointListSize)
-            effectiveFrom = fromPointList[i];
-        FloatPoint effectiveToAtEnd = i < toAtEndOfDurationSize ? toAtEndOfDurationPointList[i] : FloatPoint();
-
-        float animatedX = animatedPointList[i].x();
-        float animatedY = animatedPointList[i].y();
-        m_animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom.x(), toPointList[i].x(), effectiveToAtEnd.x(), animatedX);
-        m_animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom.y(), toPointList[i].y(), effectiveToAtEnd.y(), animatedY);
-        animatedPointList[i] = FloatPoint(animatedX, animatedY);
-    }
-}
-
-float SVGAnimatedPointListAnimator::calculateDistance(const String&, const String&)
-{
-    // FIXME: Distance calculation is not possible for SVGPointList right now. We need the distance of for every single value.
-    return -1;
-}
-
-}
diff --git a/Source/core/svg/SVGAnimatedPointList.h b/Source/core/svg/SVGAnimatedPointList.h
index 8a83524..5ea89d4 100644
--- a/Source/core/svg/SVGAnimatedPointList.h
+++ b/Source/core/svg/SVGAnimatedPointList.h
@@ -1,51 +1,42 @@
 /*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedPointList_h
 #define SVGAnimatedPointList_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/SVGPointList.h"
-#include "core/svg/properties/SVGAnimatedListPropertyTearOff.h"
+#include "core/svg/SVGPointListTearOff.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedListPropertyTearOff<SVGPointList> SVGAnimatedPointList;
-
-class SVGAnimationElement;
-
-class SVGAnimatedPointListAnimator : public SVGAnimatedTypeAnimator {
-public:
-    SVGAnimatedPointListAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedPointListAnimator() { }
-
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
-
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
-};
+typedef NewSVGAnimatedProperty<SVGPointList> SVGAnimatedPointList;
 
 } // namespace WebCore
 
diff --git a/Source/core/svg/SVGAnimatedPreserveAspectRatio.cpp b/Source/core/svg/SVGAnimatedPreserveAspectRatio.cpp
deleted file mode 100644
index 79f0178..0000000
--- a/Source/core/svg/SVGAnimatedPreserveAspectRatio.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
-
-#include "core/svg/SVGAnimateElement.h"
-
-namespace WebCore {
-
-SVGAnimatedPreserveAspectRatioAnimator::SVGAnimatedPreserveAspectRatioAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedPreserveAspectRatio, animationElement, contextElement)
-{
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedPreserveAspectRatioAnimator::constructFromString(const String& string)
-{
-    OwnPtr<SVGAnimatedType> animatedType = SVGAnimatedType::createPreserveAspectRatio(new SVGPreserveAspectRatio);
-    animatedType->preserveAspectRatio().parse(string);
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedPreserveAspectRatioAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createPreserveAspectRatio(constructFromBaseValue<SVGAnimatedPreserveAspectRatio>(animatedTypes));
-}
-
-void SVGAnimatedPreserveAspectRatioAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedPreserveAspectRatio>(animatedTypes);
-}
-
-void SVGAnimatedPreserveAspectRatioAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedPreserveAspectRatio>(animatedTypes, type, &SVGAnimatedType::preserveAspectRatio);
-}
-
-void SVGAnimatedPreserveAspectRatioAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedPreserveAspectRatio>(animatedTypes);
-}
-
-void SVGAnimatedPreserveAspectRatioAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedPreserveAspectRatio>(animatedTypes);
-}
-
-void SVGAnimatedPreserveAspectRatioAnimator::addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*)
-{
-    ASSERT_NOT_REACHED();
-}
-
-void SVGAnimatedPreserveAspectRatioAnimator::calculateAnimatedValue(float percentage, unsigned, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType*, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    const SVGPreserveAspectRatio& fromPreserveAspectRatio = m_animationElement->animationMode() == ToAnimation ? animated->preserveAspectRatio() : from->preserveAspectRatio();
-    const SVGPreserveAspectRatio& toPreserveAspectRatio = to->preserveAspectRatio();
-    SVGPreserveAspectRatio& animatedPreserveAspectRatio = animated->preserveAspectRatio();
-
-    m_animationElement->animateDiscreteType<SVGPreserveAspectRatio>(percentage, fromPreserveAspectRatio, toPreserveAspectRatio, animatedPreserveAspectRatio);
-}
-
-float SVGAnimatedPreserveAspectRatioAnimator::calculateDistance(const String&, const String&)
-{
-    // No paced animations for SVGPreserveAspectRatio.
-    return -1;
-}
-
-}
diff --git a/Source/core/svg/SVGAnimatedPreserveAspectRatio.h b/Source/core/svg/SVGAnimatedPreserveAspectRatio.h
index d08e698..1711570 100644
--- a/Source/core/svg/SVGAnimatedPreserveAspectRatio.h
+++ b/Source/core/svg/SVGAnimatedPreserveAspectRatio.h
@@ -1,59 +1,55 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedPreserveAspectRatio_h
 #define SVGAnimatedPreserveAspectRatio_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/SVGPreserveAspectRatio.h"
-#include "core/svg/properties/SVGAnimatedPropertyTearOff.h"
+#include "core/svg/SVGPreserveAspectRatioTearOff.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedPropertyTearOff<SVGPreserveAspectRatio> SVGAnimatedPreserveAspectRatio;
-
-// Helper macros to declare/define a SVGAnimatedPreserveAspectRatio object
-#define DECLARE_ANIMATED_PRESERVEASPECTRATIO(UpperProperty, LowerProperty) \
-DECLARE_ANIMATED_PROPERTY(SVGAnimatedPreserveAspectRatio, SVGPreserveAspectRatio, UpperProperty, LowerProperty)
-
-#define DEFINE_ANIMATED_PRESERVEASPECTRATIO(OwnerType, DOMAttribute, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedPreserveAspectRatio, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedPreserveAspectRatio, SVGPreserveAspectRatio)
-
-class SVGAnimationElement;
-
-class SVGAnimatedPreserveAspectRatioAnimator : public SVGAnimatedTypeAnimator {
+class SVGAnimatedPreserveAspectRatio : public NewSVGAnimatedProperty<SVGPreserveAspectRatio> {
 public:
-    SVGAnimatedPreserveAspectRatioAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedPreserveAspectRatioAnimator() { }
+    static PassRefPtr<SVGAnimatedPreserveAspectRatio> create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGPreserveAspectRatio> initialValue)
+    {
+        return adoptRef(new SVGAnimatedPreserveAspectRatio(contextElement, attributeName, initialValue));
+    }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
-
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+protected:
+    SVGAnimatedPreserveAspectRatio(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGPreserveAspectRatio> initialValue)
+        : NewSVGAnimatedProperty<SVGPreserveAspectRatio>(contextElement, attributeName, initialValue)
+    {
+    }
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGAnimatedPreserveAspectRatio_h
diff --git a/Source/core/svg/SVGAnimatedRect.cpp b/Source/core/svg/SVGAnimatedRect.cpp
deleted file mode 100644
index be2b0e1..0000000
--- a/Source/core/svg/SVGAnimatedRect.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGAnimatedRect.h"
-
-#include "core/svg/SVGAnimateElement.h"
-#include "core/svg/SVGParserUtilities.h"
-
-namespace WebCore {
-
-SVGAnimatedRectAnimator::SVGAnimatedRectAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedRect, animationElement, contextElement)
-{
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedRectAnimator::constructFromString(const String& string)
-{
-    OwnPtr<SVGAnimatedType> animatedType = SVGAnimatedType::createRect(new SVGRect);
-    parseRect(string, animatedType->rect());
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedRectAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createRect(constructFromBaseValue<SVGAnimatedRect>(animatedTypes));
-}
-
-void SVGAnimatedRectAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedRect>(animatedTypes);
-}
-
-void SVGAnimatedRectAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedRect>(animatedTypes, type, &SVGAnimatedType::rect);
-}
-
-void SVGAnimatedRectAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedRect>(animatedTypes);
-}
-
-void SVGAnimatedRectAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedRect>(animatedTypes);
-}
-
-void SVGAnimatedRectAnimator::addAnimatedTypes(SVGAnimatedType* from, SVGAnimatedType* to)
-{
-    ASSERT(from->type() == AnimatedRect);
-    ASSERT(from->type() == to->type());
-
-    to->rect() += from->rect();
-}
-
-void SVGAnimatedRectAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType* toAtEndOfDuration, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    const SVGRect& fromRect = m_animationElement->animationMode() == ToAnimation ? animated->rect() : from->rect();
-    const SVGRect& toRect = to->rect();
-    const SVGRect& toAtEndOfDurationRect = toAtEndOfDuration->rect();
-    SVGRect& animatedRect = animated->rect();
-
-    float animatedX = animatedRect.x();
-    float animatedY = animatedRect.y();
-    float animatedWidth = animatedRect.width();
-    float animatedHeight = animatedRect.height();
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromRect.x(), toRect.x(), toAtEndOfDurationRect.x(), animatedX);
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromRect.y(), toRect.y(), toAtEndOfDurationRect.y(), animatedY);
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromRect.width(), toRect.width(), toAtEndOfDurationRect.width(), animatedWidth);
-    m_animationElement->animateAdditiveNumber(percentage, repeatCount, fromRect.height(), toRect.height(), toAtEndOfDurationRect.height(), animatedHeight);
-
-    animatedRect = SVGRect(animatedX, animatedY, animatedWidth, animatedHeight);
-}
-
-float SVGAnimatedRectAnimator::calculateDistance(const String&, const String&)
-{
-    // FIXME: Distance calculation is not possible for SVGRect right now. We need the distance of for every single value.
-    return -1;
-}
-
-}
diff --git a/Source/core/svg/SVGAnimatedRect.h b/Source/core/svg/SVGAnimatedRect.h
index ccbaef8..c9e954d 100644
--- a/Source/core/svg/SVGAnimatedRect.h
+++ b/Source/core/svg/SVGAnimatedRect.h
@@ -1,60 +1,55 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedRect_h
 #define SVGAnimatedRect_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/SVGRect.h"
-#include "core/svg/properties/SVGAnimatedPropertyMacros.h"
-#include "core/svg/properties/SVGAnimatedPropertyTearOff.h"
+#include "core/svg/SVGRectTearOff.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedPropertyTearOff<SVGRect> SVGAnimatedRect;
-
-// Helper macros to declare/define a SVGAnimatedRect object
-#define DECLARE_ANIMATED_RECT(UpperProperty, LowerProperty) \
-DECLARE_ANIMATED_PROPERTY(SVGAnimatedRect, SVGRect, UpperProperty, LowerProperty)
-
-#define DEFINE_ANIMATED_RECT(OwnerType, DOMAttribute, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedRect, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedRect, SVGRect)
-
-class SVGAnimationElement;
-
-class SVGAnimatedRectAnimator : public SVGAnimatedTypeAnimator {
+class SVGAnimatedRect : public NewSVGAnimatedProperty<SVGRect> {
 public:
-    SVGAnimatedRectAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedRectAnimator() { }
+    static PassRefPtr<SVGAnimatedRect> create(SVGElement* contextElement, const QualifiedName& attributeName)
+    {
+        return adoptRef(new SVGAnimatedRect(contextElement, attributeName));
+    }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
-
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+protected:
+    SVGAnimatedRect(SVGElement* contextElement, const QualifiedName& attributeName)
+        : NewSVGAnimatedProperty<SVGRect>(contextElement, attributeName, SVGRect::create(SVGRect::InvalidSVGRectTag()))
+    {
+    }
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGAnimatedRect_h
diff --git a/Source/core/svg/SVGAnimatedString.cpp b/Source/core/svg/SVGAnimatedString.cpp
deleted file mode 100644
index 3e335d6..0000000
--- a/Source/core/svg/SVGAnimatedString.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGAnimatedString.h"
-
-#include "core/svg/SVGAnimateElement.h"
-
-namespace WebCore {
-
-SVGAnimatedStringAnimator::SVGAnimatedStringAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
-    : SVGAnimatedTypeAnimator(AnimatedString, animationElement, contextElement)
-{
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedStringAnimator::constructFromString(const String& string)
-{
-    OwnPtr<SVGAnimatedType> animatedType = SVGAnimatedType::createString(new String);
-    animatedType->string() = string;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedStringAnimator::startAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    return SVGAnimatedType::createString(constructFromBaseValue<SVGAnimatedString>(animatedTypes));
-}
-
-void SVGAnimatedStringAnimator::stopAnimValAnimation(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    stopAnimValAnimationForType<SVGAnimatedString>(animatedTypes);
-}
-
-void SVGAnimatedStringAnimator::resetAnimValToBaseVal(const SVGElementAnimatedPropertyList& animatedTypes, SVGAnimatedType* type)
-{
-    resetFromBaseValue<SVGAnimatedString>(animatedTypes, type, &SVGAnimatedType::string);
-}
-
-void SVGAnimatedStringAnimator::animValWillChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValWillChangeForType<SVGAnimatedString>(animatedTypes);
-}
-
-void SVGAnimatedStringAnimator::animValDidChange(const SVGElementAnimatedPropertyList& animatedTypes)
-{
-    animValDidChangeForType<SVGAnimatedString>(animatedTypes);
-}
-
-void SVGAnimatedStringAnimator::addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*)
-{
-    ASSERT_NOT_REACHED();
-}
-
-static String parseStringFromString(SVGAnimationElement*, const String& string)
-{
-    return string;
-}
-
-void SVGAnimatedStringAnimator::calculateAnimatedValue(float percentage, unsigned, SVGAnimatedType* from, SVGAnimatedType* to, SVGAnimatedType*, SVGAnimatedType* animated)
-{
-    ASSERT(m_animationElement);
-    ASSERT(m_contextElement);
-
-    String fromString = from->string();
-    String toString = to->string();
-    String& animatedString = animated->string();
-
-    // Apply CSS inheritance rules.
-    m_animationElement->adjustForInheritance<String>(parseStringFromString, m_animationElement->fromPropertyValueType(), fromString, m_contextElement);
-    m_animationElement->adjustForInheritance<String>(parseStringFromString, m_animationElement->toPropertyValueType(), toString, m_contextElement);
-
-    m_animationElement->animateDiscreteType<String>(percentage, fromString, toString, animatedString);
-}
-
-float SVGAnimatedStringAnimator::calculateDistance(const String&, const String&)
-{
-    // No paced animations for strings.
-    return -1;
-}
-
-}
diff --git a/Source/core/svg/SVGAnimatedString.h b/Source/core/svg/SVGAnimatedString.h
index 558d6ca..f8e5d21 100644
--- a/Source/core/svg/SVGAnimatedString.h
+++ b/Source/core/svg/SVGAnimatedString.h
@@ -1,59 +1,55 @@
 /*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGAnimatedString_h
 #define SVGAnimatedString_h
 
-#include "core/svg/SVGAnimatedTypeAnimator.h"
-#include "core/svg/properties/SVGAnimatedPropertyMacros.h"
-#include "core/svg/properties/SVGAnimatedStaticPropertyTearOff.h"
+#include "core/svg/SVGString.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 
 namespace WebCore {
 
-typedef SVGAnimatedStaticPropertyTearOff<String> SVGAnimatedString;
-
-// Helper macros to declare/define a SVGAnimatedString object
-#define DECLARE_ANIMATED_STRING(UpperProperty, LowerProperty) \
-DECLARE_ANIMATED_PROPERTY(SVGAnimatedString, String, UpperProperty, LowerProperty)
-
-#define DEFINE_ANIMATED_STRING(OwnerType, DOMAttribute, UpperProperty, LowerProperty) \
-DEFINE_ANIMATED_PROPERTY(AnimatedString, OwnerType, DOMAttribute, DOMAttribute.localName(), UpperProperty, LowerProperty, SVGAnimatedString, String)
-
-class SVGAnimationElement;
-
-class SVGAnimatedStringAnimator : public SVGAnimatedTypeAnimator {
+class SVGAnimatedString FINAL : public NewSVGAnimatedProperty<SVGString> {
 public:
-    SVGAnimatedStringAnimator(SVGAnimationElement*, SVGElement*);
-    virtual ~SVGAnimatedStringAnimator() { }
+    static PassRefPtr<SVGAnimatedString> create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGString> initialValue)
+    {
+        return adoptRef(new SVGAnimatedString(contextElement, attributeName, initialValue));
+    }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
-
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+protected:
+    SVGAnimatedString(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<SVGString> initialValue)
+        : NewSVGAnimatedProperty<SVGString>(contextElement, attributeName, initialValue)
+    {
+    }
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGAnimatedString_h
diff --git a/Source/core/svg/SVGAnimatedTransformList.cpp b/Source/core/svg/SVGAnimatedTransformList.cpp
index bc11a03..9a3971b 100644
--- a/Source/core/svg/SVGAnimatedTransformList.cpp
+++ b/Source/core/svg/SVGAnimatedTransformList.cpp
@@ -34,7 +34,7 @@
 
 SVGAnimatedTransformListAnimator::SVGAnimatedTransformListAnimator(SVGAnimationElement* animationElement, SVGElement* contextElement)
     : SVGAnimatedTypeAnimator(AnimatedTransformList, animationElement, contextElement)
-    , m_transformTypeString(SVGTransform::transformTypePrefixForParsing(static_cast<SVGAnimateTransformElement*>(animationElement)->transformType()))
+    , m_transformTypeString(SVGTransform::transformTypePrefixForParsing(toSVGAnimateTransformElement(animationElement)->transformType()))
 {
     // Only <animateTransform> uses this animator, as <animate> doesn't allow to animate transform lists directly.
     ASSERT(animationElement->hasTagName(SVGNames::animateTransformTag));
diff --git a/Source/core/svg/SVGAnimatedTransformList.h b/Source/core/svg/SVGAnimatedTransformList.h
index 58e09fd..01ee83a 100644
--- a/Source/core/svg/SVGAnimatedTransformList.h
+++ b/Source/core/svg/SVGAnimatedTransformList.h
@@ -36,21 +36,21 @@
 
 class SVGAnimationElement;
 
-class SVGAnimatedTransformListAnimator : public SVGAnimatedTypeAnimator {
+class SVGAnimatedTransformListAnimator FINAL : public SVGAnimatedTypeAnimator {
 public:
     SVGAnimatedTransformListAnimator(SVGAnimationElement*, SVGElement*);
     virtual ~SVGAnimatedTransformListAnimator() { }
 
-    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&);
-    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&);
-    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*);
-    virtual void animValWillChange(const SVGElementAnimatedPropertyList&);
-    virtual void animValDidChange(const SVGElementAnimatedPropertyList&);
+    virtual PassOwnPtr<SVGAnimatedType> constructFromString(const String&) OVERRIDE;
+    virtual PassOwnPtr<SVGAnimatedType> startAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void stopAnimValAnimation(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void resetAnimValToBaseVal(const SVGElementAnimatedPropertyList&, SVGAnimatedType*) OVERRIDE;
+    virtual void animValWillChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
+    virtual void animValDidChange(const SVGElementAnimatedPropertyList&) OVERRIDE;
 
-    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*);
-    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*);
-    virtual float calculateDistance(const String& fromString, const String& toString);
+    virtual void addAnimatedTypes(SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+    virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*, SVGAnimatedType*) OVERRIDE;
+    virtual float calculateDistance(const String& fromString, const String& toString) OVERRIDE;
 
 private:
     const String& m_transformTypeString;
diff --git a/Source/core/svg/SVGAnimatedType.cpp b/Source/core/svg/SVGAnimatedType.cpp
index 486773f..2912116 100644
--- a/Source/core/svg/SVGAnimatedType.cpp
+++ b/Source/core/svg/SVGAnimatedType.cpp
@@ -37,54 +37,38 @@
     case AnimatedAngle:
         delete m_data.angleAndEnumeration;
         break;
-    case AnimatedBoolean:
-        delete m_data.boolean;
-        break;
-    case AnimatedColor:
-        delete m_data.color;
-        break;
     case AnimatedEnumeration:
         delete m_data.enumeration;
         break;
-    case AnimatedInteger:
-        delete m_data.integer;
-        break;
-    case AnimatedIntegerOptionalInteger:
-        delete m_data.integerOptionalInteger;
-        break;
-    case AnimatedLength:
-        delete m_data.length;
-        break;
-    case AnimatedLengthList:
-        delete m_data.lengthList;
-        break;
-    case AnimatedNumber:
-        delete m_data.number;
-        break;
-    case AnimatedNumberList:
-        delete m_data.numberList;
-        break;
-    case AnimatedNumberOptionalNumber:
-        delete m_data.numberOptionalNumber;
-        break;
     case AnimatedPath:
         delete m_data.path;
         break;
-    case AnimatedPoints:
-        delete m_data.pointList;
-        break;
-    case AnimatedPreserveAspectRatio:
-        delete m_data.preserveAspectRatio;
-        break;
-    case AnimatedRect:
-        delete m_data.rect;
-        break;
-    case AnimatedString:
-        delete m_data.string;
-        break;
     case AnimatedTransformList:
         delete m_data.transformList;
         break;
+    // Below properties are migrated to new property implementation.
+    case AnimatedBoolean:
+    case AnimatedColor:
+    case AnimatedInteger:
+    case AnimatedIntegerOptionalInteger:
+    case AnimatedNumber:
+    case AnimatedNumberList:
+    case AnimatedNumberOptionalNumber:
+    case AnimatedLength:
+    case AnimatedLengthList:
+    case AnimatedPoints:
+    case AnimatedPreserveAspectRatio:
+    case AnimatedRect:
+    case AnimatedString:
+    case AnimatedStringList:
+        // handled by RefPtr
+        break;
+
+    // There is no SVGAnimatedPoint
+    case AnimatedPoint:
+        ASSERT_NOT_REACHED();
+        break;
+
     case AnimatedUnknown:
         ASSERT_NOT_REACHED();
         break;
@@ -99,22 +83,6 @@
     return animatedType.release();
 }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createBoolean(bool* boolean)
-{
-    ASSERT(boolean);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedBoolean));
-    animatedType->m_data.boolean = boolean;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createColor(Color* color)
-{
-    ASSERT(color);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedColor));
-    animatedType->m_data.color = color;
-    return animatedType.release();
-}
-
 PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createEnumeration(unsigned* enumeration)
 {
     ASSERT(enumeration);
@@ -123,62 +91,6 @@
     return animatedType.release();
 }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createInteger(int* integer)
-{
-    ASSERT(integer);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedInteger));
-    animatedType->m_data.integer = integer;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createIntegerOptionalInteger(pair<int, int>* integerOptionalInteger)
-{
-    ASSERT(integerOptionalInteger);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedIntegerOptionalInteger));
-    animatedType->m_data.integerOptionalInteger = integerOptionalInteger;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createLength(SVGLength* length)
-{
-    ASSERT(length);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedLength));
-    animatedType->m_data.length = length;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createLengthList(SVGLengthList* lengthList)
-{
-    ASSERT(lengthList);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedLengthList));
-    animatedType->m_data.lengthList = lengthList;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createNumber(float* number)
-{
-    ASSERT(number);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedNumber));
-    animatedType->m_data.number = number;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createNumberList(SVGNumberList* numberList)
-{
-    ASSERT(numberList);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedNumberList));
-    animatedType->m_data.numberList = numberList;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createNumberOptionalNumber(pair<float, float>* numberOptionalNumber)
-{
-    ASSERT(numberOptionalNumber);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedNumberOptionalNumber));
-    animatedType->m_data.numberOptionalNumber = numberOptionalNumber;
-    return animatedType.release();
-}
-
 PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createPath(PassOwnPtr<SVGPathByteStream> path)
 {
     ASSERT(path);
@@ -187,38 +99,6 @@
     return animatedType.release();
 }
 
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createPointList(SVGPointList* pointList)
-{
-    ASSERT(pointList);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedPoints));
-    animatedType->m_data.pointList = pointList;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createPreserveAspectRatio(SVGPreserveAspectRatio* preserveAspectRatio)
-{
-    ASSERT(preserveAspectRatio);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedPreserveAspectRatio));
-    animatedType->m_data.preserveAspectRatio = preserveAspectRatio;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createRect(SVGRect* rect)
-{
-    ASSERT(rect);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedRect));
-    animatedType->m_data.rect = rect;
-    return animatedType.release();
-}
-
-PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createString(String* string)
-{
-    ASSERT(string);
-    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(AnimatedString));
-    animatedType->m_data.string = string;
-    return animatedType.release();
-}
-
 PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createTransformList(SVGTransformList* transformList)
 {
     ASSERT(transformList);
@@ -227,28 +107,30 @@
     return animatedType.release();
 }
 
+PassOwnPtr<SVGAnimatedType> SVGAnimatedType::createNewProperty(PassRefPtr<NewSVGPropertyBase> newProperty)
+{
+    ASSERT(newProperty);
+    OwnPtr<SVGAnimatedType> animatedType = adoptPtr(new SVGAnimatedType(newProperty->type()));
+    animatedType->m_newProperty = newProperty;
+    return animatedType.release();
+}
+
 String SVGAnimatedType::valueAsString()
 {
     switch (m_type) {
+    // Below properties have migrated to new property implementation.
     case AnimatedColor:
-        ASSERT(m_data.color);
-        return m_data.color->serialized();
-    case AnimatedLength:
-        ASSERT(m_data.length);
-        return m_data.length->valueAsString();
-    case AnimatedLengthList:
-        ASSERT(m_data.lengthList);
-        return m_data.lengthList->valueAsString();
     case AnimatedNumber:
-        ASSERT(m_data.number);
-        return String::number(*m_data.number);
+    case AnimatedNumberList:
+    case AnimatedNumberOptionalNumber:
+    case AnimatedLength:
+    case AnimatedLengthList:
+    case AnimatedPoints:
+    case AnimatedPreserveAspectRatio:
     case AnimatedRect:
-        ASSERT(m_data.rect);
-        return String::number(m_data.rect->x()) + ' ' + String::number(m_data.rect->y()) + ' '
-             + String::number(m_data.rect->width()) + ' ' + String::number(m_data.rect->height());
     case AnimatedString:
-        ASSERT(m_data.string);
-        return *m_data.string;
+    case AnimatedStringList:
+        return m_newProperty->valueAsString();
 
     // These types don't appear in the table in SVGElement::cssPropertyToTypeMap() and thus don't need valueAsString() support.
     case AnimatedAngle:
@@ -256,11 +138,8 @@
     case AnimatedEnumeration:
     case AnimatedInteger:
     case AnimatedIntegerOptionalInteger:
-    case AnimatedNumberList:
-    case AnimatedNumberOptionalNumber:
     case AnimatedPath:
-    case AnimatedPoints:
-    case AnimatedPreserveAspectRatio:
+    case AnimatedPoint:
     case AnimatedTransformList:
     case AnimatedUnknown:
         // Only SVG DOM animations use these property types - that means valueAsString() is never used for those.
@@ -274,32 +153,20 @@
 bool SVGAnimatedType::setValueAsString(const QualifiedName& attrName, const String& value)
 {
     switch (m_type) {
+    // Below properties have migrated to new property implementation.
     case AnimatedColor:
-        ASSERT(m_data.color);
-        *m_data.color = value.isEmpty() ? Color() : SVGColor::colorFromRGBColorString(value);
-        break;
-    case AnimatedLength: {
-        ASSERT(m_data.length);
-        TrackExceptionState exceptionState;
-        m_data.length->setValueAsString(value, SVGLength::lengthModeForAnimatedLengthAttribute(attrName), exceptionState);
-        return !exceptionState.hadException();
-    }
-    case AnimatedLengthList:
-        ASSERT(m_data.lengthList);
-        m_data.lengthList->parse(value, SVGLength::lengthModeForAnimatedLengthAttribute(attrName));
-        break;
     case AnimatedNumber:
-        ASSERT(m_data.number);
-        parseNumberFromString(value, *m_data.number);
-        break;
+    case AnimatedNumberList:
+    case AnimatedNumberOptionalNumber:
+    case AnimatedLength:
+    case AnimatedLengthList:
+    case AnimatedPoints:
+    case AnimatedPreserveAspectRatio:
     case AnimatedRect:
-        ASSERT(m_data.rect);
-        parseRect(value, *m_data.rect);
-        break;
     case AnimatedString:
-        ASSERT(m_data.string);
-        *m_data.string = value;
-        break;
+    case AnimatedStringList:
+        // Always use createForAnimation call path for these implementations.
+        return false;
 
     // These types don't appear in the table in SVGElement::cssPropertyToTypeMap() and thus don't need setValueAsString() support.
     case AnimatedAngle:
@@ -307,11 +174,8 @@
     case AnimatedEnumeration:
     case AnimatedInteger:
     case AnimatedIntegerOptionalInteger:
-    case AnimatedNumberList:
-    case AnimatedNumberOptionalNumber:
     case AnimatedPath:
-    case AnimatedPoints:
-    case AnimatedPreserveAspectRatio:
+    case AnimatedPoint:
     case AnimatedTransformList:
     case AnimatedUnknown:
         // Only SVG DOM animations use these property types - that means setValueAsString() is never used for those.
diff --git a/Source/core/svg/SVGAnimatedType.h b/Source/core/svg/SVGAnimatedType.h
index 7c6aa01..7e7a2c7 100644
--- a/Source/core/svg/SVGAnimatedType.h
+++ b/Source/core/svg/SVGAnimatedType.h
@@ -20,15 +20,11 @@
 #ifndef SVGAnimatedType_h
 #define SVGAnimatedType_h
 
+#include "core/css/StyleColor.h"
 #include "core/svg/SVGAngle.h"
 #include "core/svg/SVGColor.h"
-#include "core/svg/SVGLength.h"
-#include "core/svg/SVGLengthList.h"
-#include "core/svg/SVGNumberList.h"
-#include "core/svg/SVGPointList.h"
-#include "core/svg/SVGPreserveAspectRatio.h"
-#include "core/svg/SVGRect.h"
 #include "core/svg/SVGTransformList.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
 #include "core/svg/properties/SVGPropertyInfo.h"
 
 namespace WebCore {
@@ -41,143 +37,23 @@
     ~SVGAnimatedType();
 
     static PassOwnPtr<SVGAnimatedType> createAngleAndEnumeration(std::pair<SVGAngle, unsigned>*);
-    static PassOwnPtr<SVGAnimatedType> createBoolean(bool*);
-    static PassOwnPtr<SVGAnimatedType> createColor(Color*);
+    static PassOwnPtr<SVGAnimatedType> createColor(StyleColor*);
     static PassOwnPtr<SVGAnimatedType> createEnumeration(unsigned*);
-    static PassOwnPtr<SVGAnimatedType> createInteger(int*);
-    static PassOwnPtr<SVGAnimatedType> createIntegerOptionalInteger(std::pair<int, int>*);
-    static PassOwnPtr<SVGAnimatedType> createLength(SVGLength*);
-    static PassOwnPtr<SVGAnimatedType> createLengthList(SVGLengthList*);
-    static PassOwnPtr<SVGAnimatedType> createNumber(float*);
-    static PassOwnPtr<SVGAnimatedType> createNumberList(SVGNumberList*);
-    static PassOwnPtr<SVGAnimatedType> createNumberOptionalNumber(std::pair<float, float>*);
     static PassOwnPtr<SVGAnimatedType> createPath(PassOwnPtr<SVGPathByteStream>);
-    static PassOwnPtr<SVGAnimatedType> createPointList(SVGPointList*);
-    static PassOwnPtr<SVGAnimatedType> createPreserveAspectRatio(SVGPreserveAspectRatio*);
-    static PassOwnPtr<SVGAnimatedType> createRect(SVGRect*);
-    static PassOwnPtr<SVGAnimatedType> createString(String*);
     static PassOwnPtr<SVGAnimatedType> createTransformList(SVGTransformList*);
+    // Temporary compatibility layer. This shouldn't be needed after all properties are switched to NewSVGAnimatedProperty impl.
+    static PassOwnPtr<SVGAnimatedType> createNewProperty(PassRefPtr<NewSVGPropertyBase>);
     static bool supportsAnimVal(AnimatedPropertyType);
 
     AnimatedPropertyType type() const { return m_type; }
 
-    // Non-mutable accessors.
-    const std::pair<SVGAngle, unsigned>& angleAndEnumeration() const
-    {
-        ASSERT(m_type == AnimatedAngle);
-        return *m_data.angleAndEnumeration;
-    }
-
-    const bool& boolean() const
-    {
-        ASSERT(m_type == AnimatedBoolean);
-        return *m_data.boolean;
-    }
-
-    const Color& color() const
-    {
-        ASSERT(m_type == AnimatedColor);
-        return *m_data.color;
-    }
-
-    const unsigned& enumeration() const
-    {
-        ASSERT(m_type == AnimatedEnumeration);
-        return *m_data.enumeration;
-    }
-
-    const int& integer() const
-    {
-        ASSERT(m_type == AnimatedInteger);
-        return *m_data.integer;
-    }
-
-    const pair<int, int>& integerOptionalInteger() const
-    {
-        ASSERT(m_type == AnimatedIntegerOptionalInteger);
-        return *m_data.integerOptionalInteger;
-    }
-
-    const SVGLength& length() const
-    {
-        ASSERT(m_type == AnimatedLength);
-        return *m_data.length;
-    }
-
-    const SVGLengthList& lengthList() const
-    {
-        ASSERT(m_type == AnimatedLengthList);
-        return *m_data.lengthList;
-    }
-
-    const float& number() const
-    {
-        ASSERT(m_type == AnimatedNumber);
-        return *m_data.number;
-    }
-
-    const SVGNumberList& numberList() const
-    {
-        ASSERT(m_type == AnimatedNumberList);
-        return *m_data.numberList;
-    }
-
-    const pair<float, float>& numberOptionalNumber() const
-    {
-        ASSERT(m_type == AnimatedNumberOptionalNumber);
-        return *m_data.numberOptionalNumber;
-    }
-
-    const SVGPathByteStream* path() const
-    {
-        ASSERT(m_type == AnimatedPath);
-        return m_data.path;
-    }
-
-    const SVGPointList& pointList() const
-    {
-        ASSERT(m_type == AnimatedPoints);
-        return *m_data.pointList;
-    }
-
-    const SVGPreserveAspectRatio& preserveAspectRatio() const
-    {
-        ASSERT(m_type == AnimatedPreserveAspectRatio);
-        return *m_data.preserveAspectRatio;
-    }
-
-    const SVGRect& rect() const
-    {
-        ASSERT(m_type == AnimatedRect);
-        return *m_data.rect;
-    }
-
-    const String& string() const
-    {
-        ASSERT(m_type == AnimatedString);
-        return *m_data.string;
-    }
-
-    const SVGTransformList& transformList() const
-    {
-        ASSERT(m_type == AnimatedTransformList);
-        return *m_data.transformList;
-    }
-
-    // Mutable accessors.
     std::pair<SVGAngle, unsigned>& angleAndEnumeration()
     {
         ASSERT(m_type == AnimatedAngle);
         return *m_data.angleAndEnumeration;
     }
 
-    bool& boolean()
-    {
-        ASSERT(m_type == AnimatedBoolean);
-        return *m_data.boolean;
-    }
-
-    Color& color()
+    StyleColor& color()
     {
         ASSERT(m_type == AnimatedColor);
         return *m_data.color;
@@ -189,84 +65,24 @@
         return *m_data.enumeration;
     }
 
-    int& integer()
-    {
-        ASSERT(m_type == AnimatedInteger);
-        return *m_data.integer;
-    }
-
-    pair<int, int>& integerOptionalInteger()
-    {
-        ASSERT(m_type == AnimatedIntegerOptionalInteger);
-        return *m_data.integerOptionalInteger;
-    }
-
-    SVGLength& length()
-    {
-        ASSERT(m_type == AnimatedLength);
-        return *m_data.length;
-    }
-
-    SVGLengthList& lengthList()
-    {
-        ASSERT(m_type == AnimatedLengthList);
-        return *m_data.lengthList;
-    }
-
-    float& number()
-    {
-        ASSERT(m_type == AnimatedNumber);
-        return *m_data.number;
-    }
-
-    SVGNumberList& numberList()
-    {
-        ASSERT(m_type == AnimatedNumberList);
-        return *m_data.numberList;
-    }
-
-    pair<float, float>& numberOptionalNumber()
-    {
-        ASSERT(m_type == AnimatedNumberOptionalNumber);
-        return *m_data.numberOptionalNumber;
-    }
-
     SVGPathByteStream* path()
     {
         ASSERT(m_type == AnimatedPath);
         return m_data.path;
     }
 
-    SVGPointList& pointList()
-    {
-        ASSERT(m_type == AnimatedPoints);
-        return *m_data.pointList;
-    }
-
-    SVGPreserveAspectRatio& preserveAspectRatio()
-    {
-        ASSERT(m_type == AnimatedPreserveAspectRatio);
-        return *m_data.preserveAspectRatio;
-    }
-
-    SVGRect& rect()
-    {
-        ASSERT(m_type == AnimatedRect);
-        return *m_data.rect;
-    }
-
-    String& string()
-    {
-        ASSERT(m_type == AnimatedString);
-        return *m_data.string;
-    }
-
     SVGTransformList& transformList()
     {
         ASSERT(m_type == AnimatedTransformList);
         return *m_data.transformList;
     }
 
+    RefPtr<NewSVGPropertyBase>& newProperty()
+    {
+        ASSERT(m_newProperty);
+        return m_newProperty;
+    }
+
     String valueAsString();
     bool setValueAsString(const QualifiedName&, const String&);
 
@@ -277,28 +93,16 @@
 
     union DataUnion {
         DataUnion()
-            : length(0)
         {
         }
 
         std::pair<SVGAngle, unsigned>* angleAndEnumeration;
-        bool* boolean;
-        Color* color;
+        StyleColor* color;
         unsigned* enumeration;
-        int* integer;
-        std::pair<int, int>* integerOptionalInteger;
-        SVGLength* length;
-        SVGLengthList* lengthList;
-        float* number;
-        SVGNumberList* numberList;
-        std::pair<float, float>* numberOptionalNumber;
         SVGPathByteStream* path;
-        SVGPreserveAspectRatio* preserveAspectRatio;
-        SVGPointList* pointList;
-        SVGRect* rect;
-        String* string;
         SVGTransformList* transformList;
     } m_data;
+    RefPtr<NewSVGPropertyBase> m_newProperty;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGAnimatedTypeAnimator.cpp b/Source/core/svg/SVGAnimatedTypeAnimator.cpp
index 290b538..6e833fd 100644
--- a/Source/core/svg/SVGAnimatedTypeAnimator.cpp
+++ b/Source/core/svg/SVGAnimatedTypeAnimator.cpp
@@ -40,6 +40,8 @@
     , m_animationElement(animationElement)
     , m_contextElement(contextElement)
 {
+    ASSERT(m_animationElement);
+    ASSERT(m_contextElement);
 }
 
 SVGAnimatedTypeAnimator::~SVGAnimatedTypeAnimator()
diff --git a/Source/core/svg/SVGAnimationElement.cpp b/Source/core/svg/SVGAnimationElement.cpp
index f17bd5e..718ca21 100644
--- a/Source/core/svg/SVGAnimationElement.cpp
+++ b/Source/core/svg/SVGAnimationElement.cpp
@@ -29,7 +29,7 @@
 #include "CSSPropertyNames.h"
 #include "SVGNames.h"
 #include "core/css/CSSComputedStyleDeclaration.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/frame/UseCounter.h"
 #include "core/svg/SVGAnimateElement.h"
 #include "core/svg/SVGElement.h"
@@ -40,15 +40,13 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_BOOLEAN(SVGAnimationElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGAnimationElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGAnimationElement::SVGAnimationElement(const QualifiedName& tagName, Document& document)
     : SVGSMILElement(tagName, document)
+    , SVGTests(this)
     , m_fromPropertyValueType(RegularPropertyValue)
     , m_toPropertyValueType(RegularPropertyValue)
     , m_animationValid(false)
@@ -153,7 +151,6 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGTests::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::valuesAttr);
         supportedAttributes.add(SVGNames::keyTimesAttr);
         supportedAttributes.add(SVGNames::keyPointsAttr);
@@ -222,8 +219,6 @@
 
     if (SVGTests::parseAttribute(name, value))
         return;
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
 
     ASSERT_NOT_REACHED();
 }
@@ -242,6 +237,8 @@
 {
     // Assumptions may not hold after an attribute change.
     m_animationValid = false;
+    m_lastValuesAnimationFrom = String();
+    m_lastValuesAnimationTo = String();
     setInactive();
 }
 
@@ -506,7 +503,7 @@
     }
 
     CalcMode calcMode = this->calcMode();
-    if (hasTagName(SVGNames::animateTag) || hasTagName(SVGNames::animateColorTag)) {
+    if (hasTagName(SVGNames::animateTag)) {
         AnimatedPropertyType attributeType = toSVGAnimateElement(this)->determineAnimatedPropertyType(targetElement());
         // Fall back to discrete animations for Strings.
         if (attributeType == AnimatedBoolean
diff --git a/Source/core/svg/SVGAnimationElement.h b/Source/core/svg/SVGAnimationElement.h
index 087529f..bec165a 100644
--- a/Source/core/svg/SVGAnimationElement.h
+++ b/Source/core/svg/SVGAnimationElement.h
@@ -26,10 +26,10 @@
 #define SVGAnimationElement_h
 
 #include "core/svg/SVGAnimatedBoolean.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGTests.h"
 #include "core/svg/animation/SVGSMILElement.h"
 #include "platform/animation/UnitBezier.h"
+#include "wtf/Functional.h"
 
 namespace WebCore {
 
@@ -43,11 +43,10 @@
     PathAnimation // Used by AnimateMotion.
 };
 
-// If we have 'currentColor' or 'inherit' as animation value, we need to grab
-// the value during the animation since the value can be animated itself.
+// If we have 'inherit' as animation value, we need to grab the value
+// during the animation since the value can be animated itself.
 enum AnimatedPropertyValueType {
     RegularPropertyValue,
-    CurrentColorValue,
     InheritValue
 };
 
@@ -63,8 +62,7 @@
 class SVGAnimatedType;
 
 class SVGAnimationElement : public SVGSMILElement,
-                            public SVGTests,
-                            public SVGExternalResourcesRequired {
+                            public SVGTests {
 public:
     // SVGAnimationElement
     float getStartTime() const;
@@ -94,17 +92,24 @@
     AnimatedPropertyValueType fromPropertyValueType() const { return m_fromPropertyValueType; }
     AnimatedPropertyValueType toPropertyValueType() const { return m_toPropertyValueType; }
 
+    // FIXME: In C++11, remove this as we can use default template argument.
     template<typename AnimatedType>
     void adjustForInheritance(AnimatedType (*parseTypeFromString)(SVGAnimationElement*, const String&),
                               AnimatedPropertyValueType valueType, AnimatedType& animatedType, SVGElement* contextElement)
     {
+        ASSERT(parseTypeFromString);
+        adjustForInheritance<AnimatedType, AnimatedType (*)(SVGAnimationElement*, const String&)>(parseTypeFromString, valueType, animatedType, contextElement);
+    }
+
+    template<typename AnimatedType, typename ParseTypeFromStringType>
+    void adjustForInheritance(ParseTypeFromStringType parseTypeFromString, AnimatedPropertyValueType valueType, AnimatedType& animatedType, SVGElement* contextElement)
+    {
         if (valueType != InheritValue)
             return;
         // Replace 'inherit' by its computed property value.
-        ASSERT(parseTypeFromString);
         String typeString;
         adjustForInheritance(contextElement, attributeName(), typeString);
-        animatedType = (*parseTypeFromString)(this, typeString);
+        animatedType = parseTypeFromString(this, typeString);
     }
 
     template<typename AnimatedType>
@@ -165,7 +170,7 @@
     SVGAnimationElement(const QualifiedName&, Document&);
 
     void computeCSSPropertyValue(SVGElement*, CSSPropertyID, String& value);
-    virtual void determinePropertyValueTypes(const String& from, const String& to);
+    void determinePropertyValueTypes(const String& from, const String& to);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -182,8 +187,6 @@
     String byValue() const;
     String fromValue() const;
 
-    String targetAttributeBaseValue();
-
     // from SVGSMILElement
     virtual void startedActiveInterval() OVERRIDE;
     virtual void updateAnimation(float percent, unsigned repeat, SVGSMILElement* resultElement) OVERRIDE;
@@ -219,18 +222,11 @@
     float calculatePercentForFromTo(float percent) const;
     unsigned calculateKeyTimesIndex(float percent) const;
 
-    void applyAnimatedValue(ShouldApplyAnimation, SVGElement* targetElement, const QualifiedName& attributeName, SVGAnimatedType*);
     void adjustForInheritance(SVGElement* targetElement, const QualifiedName& attributeName, String&);
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGAnimationElement)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
-
     void setCalcMode(const AtomicString&);
 
     bool m_animationValid;
diff --git a/Source/core/svg/SVGAnimationElement.idl b/Source/core/svg/SVGAnimationElement.idl
index 9e11278..945a2a3 100644
--- a/Source/core/svg/SVGAnimationElement.idl
+++ b/Source/core/svg/SVGAnimationElement.idl
@@ -37,5 +37,4 @@
     void endElementAt([Default=Undefined] optional float offset);
 };
 
-SVGAnimationElement implements SVGExternalResourcesRequired;
 SVGAnimationElement implements SVGTests;
diff --git a/Source/core/svg/SVGAnimatorFactory.h b/Source/core/svg/SVGAnimatorFactory.h
index 9ff3837..eb13b84 100644
--- a/Source/core/svg/SVGAnimatorFactory.h
+++ b/Source/core/svg/SVGAnimatorFactory.h
@@ -21,18 +21,10 @@
 #define SVGAnimatorFactory_h
 
 #include "core/svg/SVGAnimatedAngle.h"
-#include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedColor.h"
 #include "core/svg/SVGAnimatedEnumeration.h"
-#include "core/svg/SVGAnimatedInteger.h"
-#include "core/svg/SVGAnimatedIntegerOptionalInteger.h"
-#include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGAnimatedLengthList.h"
-#include "core/svg/SVGAnimatedNumber.h"
-#include "core/svg/SVGAnimatedNumberList.h"
-#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
+#include "core/svg/SVGAnimatedNewPropertyAnimator.h"
 #include "core/svg/SVGAnimatedPath.h"
-#include "core/svg/SVGAnimatedPointList.h"
 #include "core/svg/SVGAnimatedPreserveAspectRatio.h"
 #include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGAnimatedString.h"
@@ -52,38 +44,33 @@
         switch (attributeType) {
         case AnimatedAngle:
             return adoptPtr(new SVGAnimatedAngleAnimator(animationElement, contextElement));
-        case AnimatedBoolean:
-            return adoptPtr(new SVGAnimatedBooleanAnimator(animationElement, contextElement));
-        case AnimatedColor:
-            return adoptPtr(new SVGAnimatedColorAnimator(animationElement, contextElement));
         case AnimatedEnumeration:
             return adoptPtr(new SVGAnimatedEnumerationAnimator(animationElement, contextElement));
-        case AnimatedInteger:
-            return adoptPtr(new SVGAnimatedIntegerAnimator(animationElement, contextElement));
-        case AnimatedIntegerOptionalInteger:
-            return adoptPtr(new SVGAnimatedIntegerOptionalIntegerAnimator(animationElement, contextElement));
-        case AnimatedLength:
-            return adoptPtr(new SVGAnimatedLengthAnimator(animationElement, contextElement));
-        case AnimatedLengthList:
-            return adoptPtr(new SVGAnimatedLengthListAnimator(animationElement, contextElement));
-        case AnimatedNumber:
-            return adoptPtr(new SVGAnimatedNumberAnimator(animationElement, contextElement));
-        case AnimatedNumberList:
-            return adoptPtr(new SVGAnimatedNumberListAnimator(animationElement, contextElement));
-        case AnimatedNumberOptionalNumber:
-            return adoptPtr(new SVGAnimatedNumberOptionalNumberAnimator(animationElement, contextElement));
         case AnimatedPath:
             return adoptPtr(new SVGAnimatedPathAnimator(animationElement, contextElement));
-        case AnimatedPoints:
-            return adoptPtr(new SVGAnimatedPointListAnimator(animationElement, contextElement));
-        case AnimatedPreserveAspectRatio:
-            return adoptPtr(new SVGAnimatedPreserveAspectRatioAnimator(animationElement, contextElement));
-        case AnimatedRect:
-            return adoptPtr(new SVGAnimatedRectAnimator(animationElement, contextElement));
-        case AnimatedString:
-            return adoptPtr(new SVGAnimatedStringAnimator(animationElement, contextElement));
         case AnimatedTransformList:
             return adoptPtr(new SVGAnimatedTransformListAnimator(animationElement, contextElement));
+        // Below properties have migrated to new property implementation.
+        case AnimatedBoolean:
+        case AnimatedColor:
+        case AnimatedInteger:
+        case AnimatedIntegerOptionalInteger:
+        case AnimatedNumber:
+        case AnimatedNumberList:
+        case AnimatedNumberOptionalNumber:
+        case AnimatedLength:
+        case AnimatedLengthList:
+        case AnimatedPoints:
+        case AnimatedPreserveAspectRatio:
+        case AnimatedRect:
+        case AnimatedString:
+            return adoptPtr(new SVGAnimatedNewPropertyAnimator(attributeType, animationElement, contextElement));
+
+        // SVGAnimatedPoint/SVGAnimatedStringList does not exist.
+        case AnimatedPoint:
+        case AnimatedStringList:
+            ASSERT_NOT_REACHED();
+
         case AnimatedUnknown:
             break;
         }
diff --git a/Source/core/svg/SVGBoolean.cpp b/Source/core/svg/SVGBoolean.cpp
new file mode 100644
index 0000000..eeaa416
--- /dev/null
+++ b/Source/core/svg/SVGBoolean.cpp
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+
+#include "core/svg/SVGBoolean.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/svg/SVGAnimationElement.h"
+
+namespace WebCore {
+
+PassRefPtr<NewSVGPropertyBase> SVGBoolean::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGBoolean> svgBoolean = create();
+    svgBoolean->setValueAsString(value, IGNORE_EXCEPTION);
+    return svgBoolean.release();
+}
+
+String SVGBoolean::valueAsString() const
+{
+    return m_value ? "true" : "false";
+}
+
+void SVGBoolean::setValueAsString(const String& value, ExceptionState& exceptionState)
+{
+    if (value == "true") {
+        m_value = true;
+    } else if (value == "false") {
+        m_value = false;
+    } else {
+        exceptionState.throwDOMException(SyntaxError, "The value provided ('" + value + "') is invalid.");
+    }
+}
+
+void SVGBoolean::add(PassRefPtr<NewSVGPropertyBase>, SVGElement*)
+{
+    ASSERT_NOT_REACHED();
+}
+
+void SVGBoolean::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase>, SVGElement*)
+{
+    ASSERT(animationElement);
+    bool fromBoolean = animationElement->animationMode() == ToAnimation ? m_value : toSVGBoolean(from)->value();
+    bool toBoolean = toSVGBoolean(to)->value();
+
+    animationElement->animateDiscreteType<bool>(percentage, fromBoolean, toBoolean, m_value);
+}
+
+float SVGBoolean::calculateDistance(PassRefPtr<NewSVGPropertyBase>, SVGElement*)
+{
+    // No paced animations for boolean.
+    return -1;
+}
+
+}
diff --git a/Source/core/svg/SVGBoolean.h b/Source/core/svg/SVGBoolean.h
new file mode 100644
index 0000000..0c0da5b
--- /dev/null
+++ b/Source/core/svg/SVGBoolean.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGBoolean_h
+#define SVGBoolean_h
+
+#include "core/svg/properties/NewSVGProperty.h"
+
+namespace WebCore {
+
+class SVGBoolean : public NewSVGPropertyBase {
+public:
+    // SVGBoolean does not have a tear-off type.
+    typedef void TearOffType;
+    typedef bool PrimitiveType;
+
+    static PassRefPtr<SVGBoolean> create(bool value = false)
+    {
+        return adoptRef(new SVGBoolean(value));
+    }
+
+    PassRefPtr<SVGBoolean> clone() const { return create(m_value); }
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+
+    virtual String valueAsString() const OVERRIDE;
+    void setValueAsString(const String&, ExceptionState&);
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*) OVERRIDE;
+
+    bool operator==(const SVGBoolean& other) const { return m_value == other.m_value; }
+    bool operator!=(const SVGBoolean& other) const { return !operator==(other); }
+
+    bool value() const { return m_value; }
+    void setValue(bool value) { m_value = value; }
+
+    static AnimatedPropertyType classType() { return AnimatedBoolean; }
+
+private:
+    SVGBoolean(bool value)
+        : NewSVGPropertyBase(classType())
+        , m_value(value)
+    {
+    }
+
+    bool m_value;
+};
+
+inline PassRefPtr<SVGBoolean> toSVGBoolean(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGBoolean::classType());
+    return static_pointer_cast<SVGBoolean>(base.release());
+}
+
+} // namespace WebCore
+
+#endif // SVGBoolean_h
diff --git a/Source/core/svg/SVGCircleElement.cpp b/Source/core/svg/SVGCircleElement.cpp
index 6c66614..10bb166 100644
--- a/Source/core/svg/SVGCircleElement.cpp
+++ b/Source/core/svg/SVGCircleElement.cpp
@@ -30,26 +30,21 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGCircleElement, SVGNames::cxAttr, Cx, cx)
-DEFINE_ANIMATED_LENGTH(SVGCircleElement, SVGNames::cyAttr, Cy, cy)
-DEFINE_ANIMATED_LENGTH(SVGCircleElement, SVGNames::rAttr, R, r)
-DEFINE_ANIMATED_BOOLEAN(SVGCircleElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGCircleElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(cx)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(cy)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(r)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGCircleElement::SVGCircleElement(Document& document)
     : SVGGeometryElement(SVGNames::circleTag, document)
-    , m_cx(LengthModeWidth)
-    , m_cy(LengthModeHeight)
-    , m_r(LengthModeOther)
+    , m_cx(SVGAnimatedLength::create(this, SVGNames::cxAttr, SVGLength::create(LengthModeWidth)))
+    , m_cy(SVGAnimatedLength::create(this, SVGNames::cyAttr, SVGLength::create(LengthModeHeight)))
+    , m_r(SVGAnimatedLength::create(this, SVGNames::rAttr, SVGLength::create(LengthModeOther)))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_cx);
+    addToPropertyMap(m_cy);
+    addToPropertyMap(m_r);
     registerAnimatedPropertiesForSVGCircleElement();
 }
 
@@ -62,8 +57,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGLangSpace::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::cxAttr);
         supportedAttributes.add(SVGNames::cyAttr);
         supportedAttributes.add(SVGNames::rAttr);
@@ -78,14 +71,12 @@
     if (!isSupportedAttribute(name))
         SVGGeometryElement::parseAttribute(name, value);
     else if (name == SVGNames::cxAttr)
-        setCxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_cx->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::cyAttr)
-        setCyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_cy->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::rAttr)
-        setRBaseValue(SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths));
-    else if (SVGLangSpace::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)) {
-    } else
+        m_r->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    else
         ASSERT_NOT_REACHED();
 
     reportAttributeParsingError(parseError, name, value);
@@ -117,19 +108,14 @@
         return;
     }
 
-    if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
-        RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
-        return;
-    }
-
     ASSERT_NOT_REACHED();
 }
 
 bool SVGCircleElement::selfHasRelativeLengths() const
 {
-    return cxCurrentValue().isRelative()
-        || cyCurrentValue().isRelative()
-        || rCurrentValue().isRelative();
+    return m_cx->currentValue()->isRelative()
+        || m_cy->currentValue()->isRelative()
+        || m_r->currentValue()->isRelative();
 }
 
 RenderObject* SVGCircleElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGCircleElement.h b/Source/core/svg/SVGCircleElement.h
index eb689f8..b634318 100644
--- a/Source/core/svg/SVGCircleElement.h
+++ b/Source/core/svg/SVGCircleElement.h
@@ -24,35 +24,35 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGeometryElement.h"
 
 namespace WebCore {
 
-class SVGCircleElement FINAL : public SVGGeometryElement,
-                               public SVGExternalResourcesRequired {
+class SVGCircleElement FINAL : public SVGGeometryElement {
 public:
     static PassRefPtr<SVGCircleElement> create(Document&);
 
+    SVGAnimatedLength* cx() const { return m_cx.get(); }
+    SVGAnimatedLength* cy() const { return m_cy.get(); }
+    SVGAnimatedLength* r() const { return m_r.get(); }
+
 private:
     explicit SVGCircleElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_cx;
+    RefPtr<SVGAnimatedLength> m_cy;
+    RefPtr<SVGAnimatedLength> m_r;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGCircleElement)
-        DECLARE_ANIMATED_LENGTH(Cx, cx)
-        DECLARE_ANIMATED_LENGTH(Cy, cy)
-        DECLARE_ANIMATED_LENGTH(R, r)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGCircleElement.idl b/Source/core/svg/SVGCircleElement.idl
index 67f3d44..19630dd 100644
--- a/Source/core/svg/SVGCircleElement.idl
+++ b/Source/core/svg/SVGCircleElement.idl
@@ -30,5 +30,3 @@
     readonly attribute SVGAnimatedLength r;
 };
 
-SVGCircleElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGClipPathElement.cpp b/Source/core/svg/SVGClipPathElement.cpp
index c4224f1..f067830 100644
--- a/Source/core/svg/SVGClipPathElement.cpp
+++ b/Source/core/svg/SVGClipPathElement.cpp
@@ -30,11 +30,9 @@
 
 // Animated property definitions
 DEFINE_ANIMATED_ENUMERATION(SVGClipPathElement, SVGNames::clipPathUnitsAttr, ClipPathUnits, clipPathUnits, SVGUnitTypes::SVGUnitType)
-DEFINE_ANIMATED_BOOLEAN(SVGClipPathElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGClipPathElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(clipPathUnits)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
@@ -54,10 +52,9 @@
 bool SVGClipPathElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
-    if (supportedAttributes.isEmpty()) {
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
+    if (supportedAttributes.isEmpty())
         supportedAttributes.add(SVGNames::clipPathUnitsAttr);
-    }
+
     return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
@@ -75,9 +72,6 @@
         return;
     }
 
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
-
     ASSERT_NOT_REACHED();
 }
 
diff --git a/Source/core/svg/SVGClipPathElement.h b/Source/core/svg/SVGClipPathElement.h
index 0b0baec..62a8fb8 100644
--- a/Source/core/svg/SVGClipPathElement.h
+++ b/Source/core/svg/SVGClipPathElement.h
@@ -24,7 +24,6 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedEnumeration.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGUnitTypes.h"
 
@@ -32,27 +31,24 @@
 
 class RenderObject;
 
-class SVGClipPathElement FINAL : public SVGGraphicsElement,
-                                 public SVGExternalResourcesRequired {
+class SVGClipPathElement FINAL : public SVGGraphicsElement {
 public:
     static PassRefPtr<SVGClipPathElement> create(Document&);
 
 private:
     explicit SVGClipPathElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
-    virtual bool needsPendingResourceHandling() const { return false; }
+    virtual bool needsPendingResourceHandling() const OVERRIDE { return false; }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGClipPathElement)
         DECLARE_ANIMATED_ENUMERATION(ClipPathUnits, clipPathUnits, SVGUnitTypes::SVGUnitType)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGClipPathElement.idl b/Source/core/svg/SVGClipPathElement.idl
index 0d729d2..4bb7cf1 100644
--- a/Source/core/svg/SVGClipPathElement.idl
+++ b/Source/core/svg/SVGClipPathElement.idl
@@ -27,5 +27,3 @@
 interface SVGClipPathElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedEnumeration clipPathUnits;
 };
-
-SVGClipPathElement implements SVGExternalResourcesRequired;
diff --git a/Source/core/svg/SVGColor.cpp b/Source/core/svg/SVGColor.cpp
index 788ecf8..ba50d81 100644
--- a/Source/core/svg/SVGColor.cpp
+++ b/Source/core/svg/SVGColor.cpp
@@ -22,8 +22,9 @@
 #include "config.h"
 #include "core/svg/SVGColor.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/css/RGBColor.h"
 
 namespace WebCore {
@@ -45,30 +46,31 @@
     return RGBColor::create(m_color.rgb());
 }
 
-Color SVGColor::colorFromRGBColorString(const String& colorString)
+StyleColor SVGColor::colorFromRGBColorString(const String& colorString)
 {
     // FIXME: Rework css parser so it is more SVG aware.
     RGBA32 color;
-    if (CSSParser::parseColor(color, colorString.stripWhiteSpace()))
-        return color;
-    return Color();
+    if (BisonCSSParser::parseColor(color, colorString.stripWhiteSpace()))
+        return StyleColor(color);
+    // FIXME: This branch catches the string currentColor, but we should error if we have an illegal color value.
+    return StyleColor::currentColor();
 }
 
 void SVGColor::setRGBColor(const String&, ExceptionState& exceptionState)
 {
     // The whole SVGColor interface is deprecated in SVG 1.1 (2nd edition).
     // The setters are the most problematic part so we remove the support for those first.
-    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::readOnly());
 }
 
 void SVGColor::setRGBColorICCColor(const String&, const String&, ExceptionState& exceptionState)
 {
-    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::readOnly());
 }
 
 void SVGColor::setColor(unsigned short, const String&, const String&, ExceptionState& exceptionState)
 {
-    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::readOnly());
 }
 
 String SVGColor::customCSSText() const
@@ -79,10 +81,8 @@
     case SVG_COLORTYPE_RGBCOLOR_ICCCOLOR:
     case SVG_COLORTYPE_RGBCOLOR:
         // FIXME: No ICC color support.
-        return m_color.serialized();
+        return m_color.serializedAsCSSComponentValue();
     case SVG_COLORTYPE_CURRENTCOLOR:
-        if (m_color.isValid())
-            return m_color.serialized();
         return "currentColor";
     }
 
@@ -97,9 +97,9 @@
 {
 }
 
-PassRefPtr<SVGColor> SVGColor::cloneForCSSOM() const
+PassRefPtrWillBeRawPtr<SVGColor> SVGColor::cloneForCSSOM() const
 {
-    return adoptRef(new SVGColor(SVGColorClass, *this));
+    return adoptRefCountedWillBeRefCountedGarbageCollected(new SVGColor(SVGColorClass, *this));
 }
 
 bool SVGColor::equals(const SVGColor& other) const
diff --git a/Source/core/svg/SVGColor.h b/Source/core/svg/SVGColor.h
index 0341666..ea5bd57 100644
--- a/Source/core/svg/SVGColor.h
+++ b/Source/core/svg/SVGColor.h
@@ -23,6 +23,7 @@
 #define SVGColor_h
 
 #include "core/css/CSSValue.h"
+#include "core/css/StyleColor.h"
 #include "platform/graphics/Color.h"
 #include "wtf/PassRefPtr.h"
 
@@ -40,30 +41,32 @@
         SVG_COLORTYPE_CURRENTCOLOR = 3
     };
 
-    static PassRefPtr<SVGColor> createFromString(const String& rgbColor)
+    static PassRefPtrWillBeRawPtr<SVGColor> createFromString(const String& rgbColor)
     {
-        RefPtr<SVGColor> color = adoptRef(new SVGColor(SVG_COLORTYPE_RGBCOLOR));
-        color->setColor(colorFromRGBColorString(rgbColor));
+        RefPtrWillBeRawPtr<SVGColor> color = adoptRefCountedWillBeRefCountedGarbageCollected(new SVGColor(SVG_COLORTYPE_RGBCOLOR));
+        StyleColor styleColor = colorFromRGBColorString(rgbColor);
+        ASSERT(!styleColor.isCurrentColor());
+        color->setColor(styleColor.color());
         return color.release();
     }
 
-    static PassRefPtr<SVGColor> createFromColor(const Color& rgbColor)
+    static PassRefPtrWillBeRawPtr<SVGColor> createFromColor(const Color& rgbColor)
     {
-        RefPtr<SVGColor> color = adoptRef(new SVGColor(SVG_COLORTYPE_RGBCOLOR));
+        RefPtrWillBeRawPtr<SVGColor> color = adoptRefCountedWillBeRefCountedGarbageCollected(new SVGColor(SVG_COLORTYPE_RGBCOLOR));
         color->setColor(rgbColor);
         return color.release();
     }
 
-    static PassRefPtr<SVGColor> createCurrentColor()
+    static PassRefPtrWillBeRawPtr<SVGColor> createCurrentColor()
     {
-        return adoptRef(new SVGColor(SVG_COLORTYPE_CURRENTCOLOR));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new SVGColor(SVG_COLORTYPE_CURRENTCOLOR));
     }
 
     const Color& color() const { return m_color; }
     const SVGColorType& colorType() const { return m_colorType; }
     PassRefPtr<RGBColor> rgbColor() const;
 
-    static Color colorFromRGBColorString(const String&);
+    static StyleColor colorFromRGBColorString(const String&);
 
     void setRGBColor(const String& rgbColor, ExceptionState&);
     void setRGBColorICCColor(const String& rgbColor, const String& iccColor, ExceptionState&);
@@ -73,17 +76,23 @@
 
     ~SVGColor() { }
 
-    PassRefPtr<SVGColor> cloneForCSSOM() const;
+    PassRefPtrWillBeRawPtr<SVGColor> cloneForCSSOM() const;
 
     bool equals(const SVGColor&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { CSSValue::traceAfterDispatch(visitor); }
+
 protected:
     friend class CSSComputedStyleDeclaration;
 
     SVGColor(ClassType, const SVGColorType&);
     SVGColor(ClassType, const SVGColor& cloneFrom);
 
-    void setColor(const Color& color) { m_color = color; }
+    void setColor(const Color& color)
+    {
+        m_color = color;
+        setColorType(SVG_COLORTYPE_RGBCOLOR);
+    }
     void setColorType(const SVGColorType& type) { m_colorType = type; }
 
 private:
diff --git a/Source/core/svg/SVGColor.idl b/Source/core/svg/SVGColor.idl
deleted file mode 100644
index 6cce81e..0000000
--- a/Source/core/svg/SVGColor.idl
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2006 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-interface SVGColor : CSSValue {
-    const unsigned short SVG_COLORTYPE_UNKNOWN = 0;
-    const unsigned short SVG_COLORTYPE_RGBCOLOR = 1;
-    const unsigned short SVG_COLORTYPE_RGBCOLOR_ICCCOLOR = 2;
-    const unsigned short SVG_COLORTYPE_CURRENTCOLOR = 3;
-
-    readonly attribute unsigned short colorType;
-    readonly attribute RGBColor rgbColor;
-    // FIXME: readonly attribute SVGICCColor iccColor;
-
-    [StrictTypeChecking, RaisesException] void setRGBColor(DOMString rgbColor);
-
-    [StrictTypeChecking, RaisesException] void setRGBColorICCColor(DOMString rgbColor, DOMString iccColor);
-
-    [StrictTypeChecking, RaisesException] void setColor(unsigned short colorType, DOMString rgbColor, DOMString iccColor);
-};
-
diff --git a/Source/core/svg/SVGComponentTransferFunctionElement.cpp b/Source/core/svg/SVGComponentTransferFunctionElement.cpp
index 2e8818d..e4a1b50 100644
--- a/Source/core/svg/SVGComponentTransferFunctionElement.cpp
+++ b/Source/core/svg/SVGComponentTransferFunctionElement.cpp
@@ -32,31 +32,29 @@
 
 // Animated property definitions
 DEFINE_ANIMATED_ENUMERATION(SVGComponentTransferFunctionElement, SVGNames::typeAttr, Type, type, ComponentTransferType)
-DEFINE_ANIMATED_NUMBER_LIST(SVGComponentTransferFunctionElement, SVGNames::tableValuesAttr, TableValues, tableValues)
-DEFINE_ANIMATED_NUMBER(SVGComponentTransferFunctionElement, SVGNames::slopeAttr, Slope, slope)
-DEFINE_ANIMATED_NUMBER(SVGComponentTransferFunctionElement, SVGNames::interceptAttr, Intercept, intercept)
-DEFINE_ANIMATED_NUMBER(SVGComponentTransferFunctionElement, SVGNames::amplitudeAttr, Amplitude, amplitude)
-DEFINE_ANIMATED_NUMBER(SVGComponentTransferFunctionElement, SVGNames::exponentAttr, Exponent, exponent)
-DEFINE_ANIMATED_NUMBER(SVGComponentTransferFunctionElement, SVGNames::offsetAttr, Offset, offset)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGComponentTransferFunctionElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(type)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(tableValues)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(slope)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(intercept)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(amplitude)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(exponent)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(offset)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGComponentTransferFunctionElement::SVGComponentTransferFunctionElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
+    , m_tableValues(SVGAnimatedNumberList::create(this, SVGNames::tableValuesAttr, SVGNumberList::create()))
+    , m_slope(SVGAnimatedNumber::create(this, SVGNames::slopeAttr, SVGNumber::create(1)))
+    , m_intercept(SVGAnimatedNumber::create(this, SVGNames::interceptAttr, SVGNumber::create()))
+    , m_amplitude(SVGAnimatedNumber::create(this, SVGNames::amplitudeAttr, SVGNumber::create(1)))
+    , m_exponent(SVGAnimatedNumber::create(this, SVGNames::exponentAttr, SVGNumber::create(1)))
+    , m_offset(SVGAnimatedNumber::create(this, SVGNames::offsetAttr, SVGNumber::create()))
     , m_type(FECOMPONENTTRANSFER_TYPE_IDENTITY)
-    , m_slope(1)
-    , m_amplitude(1)
-    , m_exponent(1)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_tableValues);
+    addToPropertyMap(m_slope);
+    addToPropertyMap(m_intercept);
+    addToPropertyMap(m_amplitude);
+    addToPropertyMap(m_exponent);
+    addToPropertyMap(m_offset);
     registerAnimatedPropertiesForSVGComponentTransferFunctionElement();
 }
 
@@ -89,40 +87,22 @@
         return;
     }
 
-    if (name == SVGNames::tableValuesAttr) {
-        SVGNumberList newList;
-        newList.parse(value);
-        detachAnimatedTableValuesListWrappers(newList.size());
-        setTableValuesBaseValue(newList);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::slopeAttr) {
-        setSlopeBaseValue(value.toFloat());
-        return;
-    }
+    if (name == SVGNames::tableValuesAttr)
+        m_tableValues->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::slopeAttr)
+        m_slope->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::interceptAttr)
+        m_intercept->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::amplitudeAttr)
+        m_amplitude->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::exponentAttr)
+        m_exponent->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::offsetAttr)
+        m_offset->setBaseValueAsString(value, parseError);
 
-    if (name == SVGNames::interceptAttr) {
-        setInterceptBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::amplitudeAttr) {
-        setAmplitudeBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::exponentAttr) {
-        setExponentBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::offsetAttr) {
-        setOffsetBaseValue(value.toFloat());
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGComponentTransferFunctionElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -141,12 +121,12 @@
 {
     ComponentTransferFunction func;
     func.type = typeCurrentValue();
-    func.slope = slopeCurrentValue();
-    func.intercept = interceptCurrentValue();
-    func.amplitude = amplitudeCurrentValue();
-    func.exponent = exponentCurrentValue();
-    func.offset = offsetCurrentValue();
-    func.tableValues = tableValuesCurrentValue().toFloatVector();
+    func.slope = m_slope->currentValue()->value();
+    func.intercept = m_intercept->currentValue()->value();
+    func.amplitude = m_amplitude->currentValue()->value();
+    func.exponent = m_exponent->currentValue()->value();
+    func.offset = m_offset->currentValue()->value();
+    func.tableValues = m_tableValues->currentValue()->toFloatVector();
     return func;
 }
 
diff --git a/Source/core/svg/SVGComponentTransferFunctionElement.h b/Source/core/svg/SVGComponentTransferFunctionElement.h
index b794e71..7dfdcd8 100644
--- a/Source/core/svg/SVGComponentTransferFunctionElement.h
+++ b/Source/core/svg/SVGComponentTransferFunctionElement.h
@@ -24,6 +24,7 @@
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedNumber.h"
 #include "core/svg/SVGAnimatedNumberList.h"
+#include "core/svg/SVGElement.h"
 #include "platform/graphics/filters/FEComponentTransfer.h"
 
 namespace WebCore {
@@ -73,24 +74,32 @@
 public:
     ComponentTransferFunction transferFunction() const;
 
+    SVGAnimatedNumberList* tableValues() { return m_tableValues.get(); }
+    SVGAnimatedNumber* slope() { return m_slope.get(); }
+    SVGAnimatedNumber* intercept() { return m_intercept.get(); }
+    SVGAnimatedNumber* amplitude() { return m_amplitude.get(); }
+    SVGAnimatedNumber* exponent() { return m_exponent.get(); }
+    SVGAnimatedNumber* offset() { return m_offset.get(); }
+
 protected:
     SVGComponentTransferFunctionElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
-    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE FINAL;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE FINAL;
 
-    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE FINAL { return false; }
 
 private:
+    RefPtr<SVGAnimatedNumberList> m_tableValues;
+    RefPtr<SVGAnimatedNumber> m_slope;
+    RefPtr<SVGAnimatedNumber> m_intercept;
+    RefPtr<SVGAnimatedNumber> m_amplitude;
+    RefPtr<SVGAnimatedNumber> m_exponent;
+    RefPtr<SVGAnimatedNumber> m_offset;
+
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGComponentTransferFunctionElement)
         DECLARE_ANIMATED_ENUMERATION(Type, type, ComponentTransferType)
-        DECLARE_ANIMATED_NUMBER_LIST(TableValues, tableValues)
-        DECLARE_ANIMATED_NUMBER(Slope, slope)
-        DECLARE_ANIMATED_NUMBER(Intercept, intercept)
-        DECLARE_ANIMATED_NUMBER(Amplitude, amplitude)
-        DECLARE_ANIMATED_NUMBER(Exponent, exponent)
-        DECLARE_ANIMATED_NUMBER(Offset, offset)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGCursorElement.cpp b/Source/core/svg/SVGCursorElement.cpp
index 87cd2bc..c1bb5d7 100644
--- a/Source/core/svg/SVGCursorElement.cpp
+++ b/Source/core/svg/SVGCursorElement.cpp
@@ -30,25 +30,21 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGCursorElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGCursorElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_STRING(SVGCursorElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGCursorElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGCursorElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGCursorElement::SVGCursorElement(Document& document)
     : SVGElement(SVGNames::cursorTag, document)
-    , m_x(LengthModeWidth)
-    , m_y(LengthModeHeight)
+    , SVGTests(this)
+    , SVGURIReference(this)
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
     registerAnimatedPropertiesForSVGCursorElement();
 }
 
@@ -69,7 +65,6 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGTests::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         SVGURIReference::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::xAttr);
         supportedAttributes.add(SVGNames::yAttr);
@@ -81,17 +76,17 @@
 {
     SVGParsingError parseError = NoError;
 
-    if (!isSupportedAttribute(name))
+    if (!isSupportedAttribute(name)) {
         SVGElement::parseAttribute(name, value);
-    else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
-    else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (SVGTests::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)
-             || SVGURIReference::parseAttribute(name, value)) {
-    } else
+    } else if (name == SVGNames::xAttr) {
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::yAttr) {
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else if (SVGTests::parseAttribute(name, value)) {
+    } else {
         ASSERT_NOT_REACHED();
+    }
 
     reportAttributeParsingError(parseError, name, value);
 }
@@ -130,14 +125,7 @@
     HashSet<SVGElement*>::const_iterator end = m_clients.end();
 
     for (; it != end; ++it)
-        (*it)->setNeedsStyleRecalc();
-}
-
-void SVGCursorElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    SVGElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
+        (*it)->setNeedsStyleRecalc(SubtreeStyleChange);
 }
 
 }
diff --git a/Source/core/svg/SVGCursorElement.h b/Source/core/svg/SVGCursorElement.h
index b79d44f..56c02f2 100644
--- a/Source/core/svg/SVGCursorElement.h
+++ b/Source/core/svg/SVGCursorElement.h
@@ -21,11 +21,11 @@
 #ifndef SVGCursorElement_h
 #define SVGCursorElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGAnimatedString.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGTests.h"
 #include "core/svg/SVGURIReference.h"
 
@@ -33,7 +33,6 @@
 
 class SVGCursorElement FINAL : public SVGElement,
                                public SVGTests,
-                               public SVGExternalResourcesRequired,
                                public SVGURIReference {
 public:
     static PassRefPtr<SVGCursorElement> create(Document&);
@@ -44,34 +43,29 @@
     void removeClient(SVGElement*);
     void removeReferencedElement(SVGElement*);
 
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
 private:
     explicit SVGCursorElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
+    virtual bool isValid() const OVERRIDE { return SVGTests::isValid(); }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGCursorElement)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
-
     HashSet<SVGElement*> m_clients;
 };
 
+DEFINE_NODE_TYPE_CASTS(SVGCursorElement, hasTagName(SVGNames::cursorTag));
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGCursorElement.idl b/Source/core/svg/SVGCursorElement.idl
index d386935..7e35ec1 100644
--- a/Source/core/svg/SVGCursorElement.idl
+++ b/Source/core/svg/SVGCursorElement.idl
@@ -28,7 +28,6 @@
     readonly attribute SVGAnimatedLength y;
 };
 
-SVGCursorElement implements SVGExternalResourcesRequired;
 SVGCursorElement implements SVGURIReference;
 SVGCursorElement implements SVGTests;
 
diff --git a/Source/core/svg/SVGDefsElement.cpp b/Source/core/svg/SVGDefsElement.cpp
index ae425f3..188eb57 100644
--- a/Source/core/svg/SVGDefsElement.cpp
+++ b/Source/core/svg/SVGDefsElement.cpp
@@ -28,10 +28,8 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_BOOLEAN(SVGDefsElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGDefsElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
@@ -47,11 +45,6 @@
     return adoptRef(new SVGDefsElement(document));
 }
 
-bool SVGDefsElement::isValid() const
-{
-    return SVGTests::isValid();
-}
-
 RenderObject* SVGDefsElement::createRenderer(RenderStyle*)
 {
     return new RenderSVGHiddenContainer(this);
diff --git a/Source/core/svg/SVGDefsElement.h b/Source/core/svg/SVGDefsElement.h
index 60ff06b..86faeb7 100644
--- a/Source/core/svg/SVGDefsElement.h
+++ b/Source/core/svg/SVGDefsElement.h
@@ -22,25 +22,20 @@
 #define SVGDefsElement_h
 
 #include "core/svg/SVGAnimatedBoolean.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGDefsElement FINAL : public SVGGraphicsElement,
-                             public SVGExternalResourcesRequired {
+class SVGDefsElement FINAL : public SVGGraphicsElement {
 public:
     static PassRefPtr<SVGDefsElement> create(Document&);
 
 private:
     explicit SVGDefsElement(Document&);
 
-    virtual bool isValid() const;
-
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGDefsElement)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGDefsElement.idl b/Source/core/svg/SVGDefsElement.idl
index f4e727a..807db63 100644
--- a/Source/core/svg/SVGDefsElement.idl
+++ b/Source/core/svg/SVGDefsElement.idl
@@ -26,5 +26,3 @@
 interface SVGDefsElement : SVGGraphicsElement {
 };
 
-SVGDefsElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGDescElement.h b/Source/core/svg/SVGDescElement.h
index 181053d..6a68eb7 100644
--- a/Source/core/svg/SVGDescElement.h
+++ b/Source/core/svg/SVGDescElement.h
@@ -34,7 +34,7 @@
 private:
     explicit SVGDescElement(Document&);
 
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/NodeList.cpp b/Source/core/svg/SVGDiscardElement.cpp
similarity index 68%
copy from Source/core/dom/NodeList.cpp
copy to Source/core/svg/SVGDiscardElement.cpp
index fb06c70..0cc9cda 100644
--- a/Source/core/dom/NodeList.cpp
+++ b/Source/core/svg/SVGDiscardElement.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,29 +29,33 @@
  */
 
 #include "config.h"
-#include "core/dom/NodeList.h"
+#include "core/svg/SVGDiscardElement.h"
 
-#include "core/dom/Node.h"
+#include "SVGNames.h"
 
 namespace WebCore {
 
-void NodeList::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<Node>& returnValue0, bool& returnValue1Enabled, unsigned& returnValue1)
+SVGDiscardElement::SVGDiscardElement(Document& document)
+    : SVGSMILElement(SVGNames::discardTag, document)
 {
-    // Length property cannot be overridden.
-    DEFINE_STATIC_LOCAL(const AtomicString, length, ("length", AtomicString::ConstructFromLiteral));
-    if (name == length) {
-        returnValue1Enabled = true;
-        returnValue1 = this->length();
-        return;
-    }
-
-    Node* result = namedItem(name);
-    if (!result)
-        return;
-
-    returnValue0Enabled = true;
-    returnValue0 = result;
+    ScriptWrappable::init(this);
 }
 
+PassRefPtr<SVGDiscardElement> SVGDiscardElement::create(Document& document)
+{
+    return adoptRef(new SVGDiscardElement(document));
+}
 
-} // namespace WebCore
+bool SVGDiscardElement::hasValidAttributeType()
+{
+    // Even if there is no targetElement, discard is still a valid animation as it has to delete itself.
+    return true;
+}
+
+bool SVGDiscardElement::hasValidAttributeName()
+{
+    // discard does not use attributeName so it is always valid.
+    return true;
+}
+
+}
diff --git a/Source/core/frame/GraphicsLayerDebugInfo.h b/Source/core/svg/SVGDiscardElement.h
similarity index 62%
copy from Source/core/frame/GraphicsLayerDebugInfo.h
copy to Source/core/svg/SVGDiscardElement.h
index 26d2fce..653a1db 100644
--- a/Source/core/frame/GraphicsLayerDebugInfo.h
+++ b/Source/core/svg/SVGDiscardElement.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,23 +28,32 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef GraphicsLayerDebugInfo_h
-#define GraphicsLayerDebugInfo_h
+#ifndef SVGDiscardElement_h
+#define SVGDiscardElement_h
 
-#include "platform/geometry/LayoutRect.h"
-#include "public/platform/WebGraphicsLayerDebugInfo.h"
-
-#include "wtf/Vector.h"
+#include "core/svg/animation/SVGSMILElement.h"
 
 namespace WebCore {
 
-class GraphicsLayerDebugInfo FINAL : public blink::WebGraphicsLayerDebugInfo {
+class SVGDiscardElement FINAL : public SVGSMILElement {
 public:
-    virtual void appendAsTraceFormat(blink::WebString* out) const OVERRIDE;
-    virtual ~GraphicsLayerDebugInfo() { };
-    Vector<LayoutRect> m_currentLayoutRects;
+    static PassRefPtr<SVGDiscardElement> create(Document&);
+
+    virtual bool isSVGDiscardElement() const OVERRIDE { return true; }
+private:
+    explicit SVGDiscardElement(Document&);
+
+    virtual void resetAnimatedType() OVERRIDE { }
+    virtual void clearAnimatedType(SVGElement* targetElement) OVERRIDE { }
+    virtual void applyResultsToTarget() OVERRIDE { }
+    virtual bool hasValidAttributeType() OVERRIDE;
+    virtual bool hasValidAttributeName() OVERRIDE;
+    virtual void animationAttributeChanged() OVERRIDE { }
+
+    virtual void startedActiveInterval() OVERRIDE { }
+    virtual void updateAnimation(float percent, unsigned repeat, SVGSMILElement* resultElement) OVERRIDE { }
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGDiscardElement_h
diff --git a/Source/core/rendering/LayoutIndicator.cpp b/Source/core/svg/SVGDiscardElement.idl
similarity index 87%
rename from Source/core/rendering/LayoutIndicator.cpp
rename to Source/core/svg/SVGDiscardElement.idl
index a57c53c..54ee14a 100644
--- a/Source/core/rendering/LayoutIndicator.cpp
+++ b/Source/core/svg/SVGDiscardElement.idl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,15 +28,5 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/rendering/LayoutIndicator.h"
-
-namespace WebCore {
-
-#ifndef NDEBUG
-
-size_t LayoutIndicator::s_inLayout = 0;
-
-#endif
-
-}
+interface SVGDiscardElement : SVGElement {
+};
diff --git a/Source/core/svg/SVGDocument.cpp b/Source/core/svg/SVGDocument.cpp
index 876b66f..5e3a9bb 100644
--- a/Source/core/svg/SVGDocument.cpp
+++ b/Source/core/svg/SVGDocument.cpp
@@ -35,20 +35,24 @@
 namespace WebCore {
 
 SVGDocument::SVGDocument(const DocumentInit& initializer)
-    : Document(initializer, SVGDocumentClass)
+    : XMLDocument(initializer, XMLDocumentClass | SVGDocumentClass)
 {
-    ScriptWrappable::init(this);
 }
 
-SVGSVGElement* SVGDocument::rootElement() const
+SVGSVGElement* SVGDocument::rootElement(const Document* document)
 {
-    Element* elem = documentElement();
+    Element* elem = document->documentElement();
     if (elem && elem->hasTagName(SVGNames::svgTag))
         return toSVGSVGElement(elem);
 
     return 0;
 }
 
+SVGSVGElement* SVGDocument::rootElement() const
+{
+    return rootElement(this);
+}
+
 void SVGDocument::dispatchZoomEvent(float prevScale, float newScale)
 {
     RefPtr<SVGZoomEvent> event = SVGZoomEvent::create();
@@ -94,13 +98,6 @@
     }
 }
 
-bool SVGDocument::childShouldCreateRenderer(const Node& child) const
-{
-    if (child.hasTagName(SVGNames::svgTag))
-        return toSVGSVGElement(&child)->isValid();
-    return true;
-}
-
 PassRefPtr<Document> SVGDocument::cloneDocumentWithoutChildren()
 {
     return create(DocumentInit(url()));
diff --git a/Source/core/svg/SVGDocument.h b/Source/core/svg/SVGDocument.h
index a9b3392..78b3c7e 100644
--- a/Source/core/svg/SVGDocument.h
+++ b/Source/core/svg/SVGDocument.h
@@ -21,20 +21,21 @@
 #ifndef SVGDocument_h
 #define SVGDocument_h
 
-#include "core/dom/Document.h"
+#include "core/dom/XMLDocument.h"
 #include "platform/geometry/FloatPoint.h"
 
 namespace WebCore {
 
 class SVGSVGElement;
 
-class SVGDocument FINAL : public Document {
+class SVGDocument FINAL : public XMLDocument {
 public:
     static PassRefPtr<SVGDocument> create(const DocumentInit& initializer = DocumentInit())
     {
         return adoptRef(new SVGDocument(initializer));
     }
 
+    static SVGSVGElement* rootElement(const Document*);
     SVGSVGElement* rootElement() const;
 
     void dispatchZoomEvent(float prevScale, float newScale);
@@ -45,13 +46,11 @@
     void startPan(const FloatPoint& start);
     void updatePan(const FloatPoint& pos) const;
 
-    virtual PassRefPtr<Document> cloneDocumentWithoutChildren() OVERRIDE FINAL;
+    virtual PassRefPtr<Document> cloneDocumentWithoutChildren() OVERRIDE;
 
 private:
     explicit SVGDocument(const DocumentInit&);
 
-    virtual bool childShouldCreateRenderer(const Node& child) const;
-
     FloatPoint m_translate;
 };
 
diff --git a/Source/core/svg/SVGDocument.idl b/Source/core/svg/SVGDocument.idl
index dced411..0f1dafc 100644
--- a/Source/core/svg/SVGDocument.idl
+++ b/Source/core/svg/SVGDocument.idl
@@ -19,10 +19,7 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface SVGDocument : Document {
-    readonly attribute SVGSVGElement        rootElement;
-
-    // Overwrite the one in events::DocumentEvent
-    [RaisesException] Event createEvent([Default=Undefined] optional DOMString eventType);
+partial interface Document {
+    [MeasureAs=SVGDocumentRootElement] readonly attribute SVGSVGElement        rootElement;
 };
 
diff --git a/Source/core/svg/SVGDocumentExtensions.cpp b/Source/core/svg/SVGDocumentExtensions.cpp
index a135845..c4a5a8f 100644
--- a/Source/core/svg/SVGDocumentExtensions.cpp
+++ b/Source/core/svg/SVGDocumentExtensions.cpp
@@ -120,7 +120,10 @@
         SVGSVGElement* outerSVG = (*it).get();
         if (!outerSVG->isOutermostSVGSVGElement())
             continue;
-        outerSVG->sendSVGLoadEventIfPossible();
+
+        // don't dispatch the load event document is not wellformed (for XML/standalone svg)
+        if (outerSVG->document().wellFormed() || !outerSVG->document().isSVGDocument())
+            outerSVG->sendSVGLoadEventIfPossible();
     }
 }
 
@@ -150,8 +153,8 @@
 
     HashMap<AtomicString, OwnPtr<SVGPendingElements> >::AddResult result = m_pendingResources.add(id, nullptr);
     if (result.isNewEntry)
-        result.iterator->value = adoptPtr(new SVGPendingElements);
-    result.iterator->value->add(element);
+        result.storedValue->value = adoptPtr(new SVGPendingElements);
+    result.storedValue->value->add(element);
 
     element->setHasPendingResources();
 }
diff --git a/Source/core/svg/SVGElement.cpp b/Source/core/svg/SVGElement.cpp
index 0f940ab..5e5638a 100644
--- a/Source/core/svg/SVGElement.cpp
+++ b/Source/core/svg/SVGElement.cpp
@@ -31,11 +31,12 @@
 #include "XMLNames.h"
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/css/CSSCursorImageValue.h"
-#include "core/css/CSSParser.h"
+#include "core/css/parser/BisonCSSParser.h"
 #include "core/dom/Document.h"
 #include "core/dom/ElementTraversal.h"
-#include "core/events/Event.h"
 #include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/Event.h"
+#include "core/html/HTMLElement.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/svg/RenderSVGResourceContainer.h"
 #include "core/svg/SVGCursorElement.h"
@@ -51,10 +52,8 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGElement, HTMLNames::classAttr, ClassName, className)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(className)
 END_REGISTER_ANIMATED_PROPERTIES
 
 using namespace HTMLNames;
@@ -76,9 +75,13 @@
     , m_inRelativeLengthClientsInvalidation(false)
 #endif
     , m_animatedPropertiesDestructed(false)
+    // |m_isContextElement| must be initialized before |m_className|, as SVGAnimatedString tear-off c-tor currently set this to true.
     , m_isContextElement(false)
+    , m_hasSVGRareData(false)
+    , m_className(SVGAnimatedString::create(this, HTMLNames::classAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+    addToPropertyMap(m_className);
     registerAnimatedPropertiesForSVGElement();
     setHasCustomStyleCallbacks();
 }
@@ -146,7 +149,7 @@
         return;
 
     SVGDocumentExtensions* extensions = document.accessSVGExtensions();
-    String resourceId = getIdAttribute();
+    AtomicString resourceId = getIdAttribute();
     if (!extensions->hasPendingResource(resourceId))
         return;
 
@@ -247,7 +250,7 @@
 
     // Walk up the tree, to find out whether we're inside a <use> shadow tree, to find the right title.
     if (isInShadowTree()) {
-        Element* shadowHostElement = toShadowRoot(treeScope().rootNode())->host();
+        Element* shadowHostElement = toShadowRoot(treeScope().rootNode()).host();
         // At this time, SVG nodes are not allowed in non-<use> shadow trees, so any shadow root we do
         // have should be a use. The assert and following test is here to catch future shadow DOM changes
         // that do enable SVG in a shadow tree.
@@ -278,7 +281,7 @@
     return String();
 }
 
-PassRefPtr<CSSValue> SVGElement::getPresentationAttribute(const String& name)
+PassRefPtr<CSSValue> SVGElement::getPresentationAttribute(const AtomicString& name)
 {
     if (!hasAttributesWithoutUpdate())
         return 0;
@@ -295,10 +298,6 @@
     return cssValue ? cssValue->cloneForCSSOM() : 0;
 }
 
-bool SVGElement::isKnownAttribute(const QualifiedName& attrName)
-{
-    return isIdAttributeName(attrName);
-}
 
 bool SVGElement::instanceUpdatesBlocked() const
 {
@@ -317,16 +316,36 @@
     return AffineTransform();
 }
 
-String SVGElement::xmlbase() const
+const AtomicString& SVGElement::xmlbase() const
 {
     return fastGetAttribute(XMLNames::baseAttr);
 }
 
-void SVGElement::setXMLbase(const String& value)
+void SVGElement::setXMLbase(const AtomicString& value)
 {
     setAttribute(XMLNames::baseAttr, value);
 }
 
+const AtomicString& SVGElement::xmllang() const
+{
+    return fastGetAttribute(XMLNames::langAttr);
+}
+
+void SVGElement::setXMLlang(const AtomicString& value)
+{
+    setAttribute(XMLNames::langAttr, value);
+}
+
+const AtomicString& SVGElement::xmlspace() const
+{
+    return fastGetAttribute(XMLNames::spaceAttr);
+}
+
+void SVGElement::setXMLspace(const AtomicString& value)
+{
+    setAttribute(XMLNames::spaceAttr, value);
+}
+
 Node::InsertionNotificationRequest SVGElement::insertedInto(ContainerNode* rootParent)
 {
     Element::insertedInto(rootParent);
@@ -634,46 +653,23 @@
 
 void SVGElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
-    // standard events
-    if (name == onloadAttr)
-        setAttributeEventListener(EventTypeNames::load, createAttributeEventListener(this, name, value));
-    else if (name == onbeginAttr)
-        setAttributeEventListener(EventTypeNames::beginEvent, createAttributeEventListener(this, name, value));
-    else if (name == onendAttr)
-        setAttributeEventListener(EventTypeNames::endEvent, createAttributeEventListener(this, name, value));
-    else if (name == onrepeatAttr)
-        setAttributeEventListener(EventTypeNames::repeatEvent, createAttributeEventListener(this, name, value));
-    else if (name == onclickAttr)
-        setAttributeEventListener(EventTypeNames::click, createAttributeEventListener(this, name, value));
-    else if (name == onmousedownAttr)
-        setAttributeEventListener(EventTypeNames::mousedown, createAttributeEventListener(this, name, value));
-    else if (name == onmouseenterAttr)
-        setAttributeEventListener(EventTypeNames::mouseenter, createAttributeEventListener(this, name, value));
-    else if (name == onmouseleaveAttr)
-        setAttributeEventListener(EventTypeNames::mouseleave, createAttributeEventListener(this, name, value));
-    else if (name == onmousemoveAttr)
-        setAttributeEventListener(EventTypeNames::mousemove, createAttributeEventListener(this, name, value));
-    else if (name == onmouseoutAttr)
-        setAttributeEventListener(EventTypeNames::mouseout, createAttributeEventListener(this, name, value));
-    else if (name == onmouseoverAttr)
-        setAttributeEventListener(EventTypeNames::mouseover, createAttributeEventListener(this, name, value));
-    else if (name == onmouseupAttr)
-        setAttributeEventListener(EventTypeNames::mouseup, createAttributeEventListener(this, name, value));
-    else if (name == SVGNames::onfocusinAttr)
-        setAttributeEventListener(EventTypeNames::focusin, createAttributeEventListener(this, name, value));
-    else if (name == SVGNames::onfocusoutAttr)
-        setAttributeEventListener(EventTypeNames::focusout, createAttributeEventListener(this, name, value));
-    else if (name == SVGNames::onactivateAttr)
-        setAttributeEventListener(EventTypeNames::DOMActivate, createAttributeEventListener(this, name, value));
-    else if (name == HTMLNames::classAttr) {
+    if (name == HTMLNames::classAttr) {
         // SVG animation has currently requires special storage of values so we set
         // the className here. svgAttributeChanged actually causes the resulting
         // style updates (instead of Element::parseAttribute). We don't
         // tell Element about the change to avoid parsing the class list twice
-        setClassNameBaseValue(value);
-    } else if (SVGLangSpace::parseAttribute(name, value)) {
-    } else
-        Element::parseAttribute(name, value);
+        SVGParsingError parseError = NoError;
+        m_className->setBaseValueAsString(value, parseError);
+        reportAttributeParsingError(parseError, name, value);
+    } else if (name.matches(XMLNames::langAttr) || name.matches(XMLNames::spaceAttr)) {
+    } else {
+        // standard events
+        const AtomicString& eventName = HTMLElement::eventNameForAttributeName(name);
+        if (!eventName.isNull())
+            setAttributeEventListener(eventName, createAttributeEventListener(this, name, value));
+        else
+            Element::parseAttribute(name, value);
+    }
 }
 
 typedef HashMap<QualifiedName, AnimatedPropertyType> AttributeToPropertyTypeMap;
@@ -750,11 +746,27 @@
     if (!propertyTypes.isEmpty())
         return;
 
+    RefPtr<NewSVGAnimatedPropertyBase> animatedProperty = m_newAttributeToPropertyMap.get(attributeName);
+    if (animatedProperty)
+        propertyTypes.append(animatedProperty->type());
+
     AttributeToPropertyTypeMap& cssPropertyTypeMap = cssPropertyToTypeMap();
     if (cssPropertyTypeMap.contains(attributeName))
         propertyTypes.append(cssPropertyTypeMap.get(attributeName));
 }
 
+void SVGElement::addToPropertyMap(PassRefPtr<NewSVGAnimatedPropertyBase> passProperty)
+{
+    RefPtr<NewSVGAnimatedPropertyBase> property(passProperty);
+    QualifiedName attributeName = property->attributeName();
+    m_newAttributeToPropertyMap.set(attributeName, property.release());
+}
+
+PassRefPtr<NewSVGAnimatedPropertyBase> SVGElement::propertyFromAttribute(const QualifiedName& attributeName)
+{
+    return m_newAttributeToPropertyMap.get(attributeName);
+}
+
 bool SVGElement::isAnimatableCSSProperty(const QualifiedName& attrName)
 {
     return cssPropertyToTypeMap().contains(attrName);
@@ -880,12 +892,6 @@
     return false;
 }
 
-bool SVGElement::shouldMoveToFlowThread(RenderStyle* styleToUse) const
-{
-    // Allow only svg root elements to be directly collected by a render flow thread.
-    return parentNode() && !parentNode()->isSVGElement() && hasTagName(SVGNames::svgTag) && Element::shouldMoveToFlowThread(styleToUse);
-}
-
 void SVGElement::sendSVGLoadEventIfPossible(bool sendParentLoadEvents)
 {
     RefPtr<SVGElement> currentTarget = this;
@@ -893,7 +899,8 @@
         RefPtr<Element> parent;
         if (sendParentLoadEvents)
             parent = currentTarget->parentOrShadowHostElement(); // save the next parent to dispatch too incase dispatching the event changes the tree
-        if (hasLoadListener(currentTarget.get()))
+        if (hasLoadListener(currentTarget.get())
+            && (currentTarget->isStructurallyExternal() || currentTarget->isSVGSVGElement()))
             currentTarget->dispatchEvent(Event::create(EventTypeNames::load));
         currentTarget = (parent && parent->isSVGElement()) ? static_pointer_cast<SVGElement>(parent) : RefPtr<SVGElement>();
         SVGElement* element = currentTarget.get();
@@ -939,28 +946,8 @@
 
     // finishParsingChildren() is called when the close tag is reached for an element (e.g. </svg>)
     // we send SVGLoad events here if we can, otherwise they'll be sent when any required loads finish
-    sendSVGLoadEventIfPossible();
-}
-
-bool SVGElement::childShouldCreateRenderer(const Node& child) const
-{
-    DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, invalidTextContent, ());
-
-    if (invalidTextContent.isEmpty()) {
-        invalidTextContent.add(SVGNames::textPathTag);
-#if ENABLE(SVG_FONTS)
-        invalidTextContent.add(SVGNames::altGlyphTag);
-#endif
-        invalidTextContent.add(SVGNames::tspanTag);
-    }
-    if (child.isSVGElement()) {
-        const SVGElement* svgChild = toSVGElement(&child);
-        if (invalidTextContent.contains(svgChild->tagQName()))
-            return false;
-
-        return svgChild->isValid();
-    }
-    return false;
+    if (isSVGSVGElement())
+        sendSVGLoadEventIfPossible();
 }
 
 void SVGElement::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason)
@@ -985,7 +972,7 @@
     }
 
     if (attrName == HTMLNames::classAttr) {
-        classAttributeChanged(classNameCurrentValue());
+        classAttributeChanged(AtomicString(m_className->currentValue()->value()));
         SVGElementInstance::invalidateAllInstancesOfElement(this);
         return;
     }
@@ -1010,9 +997,22 @@
     SVGElement* nonConstThis = const_cast<SVGElement*>(this);
     if (name == anyQName()) {
         nonConstThis->localAttributeToPropertyMap().synchronizeProperties(nonConstThis);
+
+        AttributeToPropertyMap::const_iterator::Values it = m_newAttributeToPropertyMap.values().begin();
+        AttributeToPropertyMap::const_iterator::Values end = m_newAttributeToPropertyMap.values().end();
+        for (; it != end; ++it) {
+            if ((*it)->needsSynchronizeAttribute())
+                (*it)->synchronizeAttribute();
+        }
+
         elementData()->m_animatedSVGAttributesAreDirty = false;
-    } else
+    } else {
         nonConstThis->localAttributeToPropertyMap().synchronizeProperty(nonConstThis, name);
+
+        RefPtr<NewSVGAnimatedPropertyBase> property = m_newAttributeToPropertyMap.get(name);
+        if (property && property->needsSynchronizeAttribute())
+            property->synchronizeAttribute();
+    }
 }
 
 void SVGElement::synchronizeRequiredFeatures(SVGElement* contextElement)
@@ -1110,7 +1110,6 @@
         animatableAttributes.add(SVGNames::edgeModeAttr);
         animatableAttributes.add(SVGNames::elevationAttr);
         animatableAttributes.add(SVGNames::exponentAttr);
-        animatableAttributes.add(SVGNames::externalResourcesRequiredAttr);
         animatableAttributes.add(SVGNames::filterResAttr);
         animatableAttributes.add(SVGNames::filterUnitsAttr);
         animatableAttributes.add(SVGNames::fxAttr);
@@ -1196,5 +1195,4 @@
     return animatableAttributes.contains(name);
 }
 #endif
-
 }
diff --git a/Source/core/svg/SVGElement.h b/Source/core/svg/SVGElement.h
index f401221..2bac4f0 100644
--- a/Source/core/svg/SVGElement.h
+++ b/Source/core/svg/SVGElement.h
@@ -24,39 +24,40 @@
 
 #include "core/dom/Element.h"
 #include "core/svg/SVGAnimatedString.h"
-#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGParsingError.h"
 #include "core/svg/properties/SVGAnimatedPropertyMacros.h"
 #include "core/svg/properties/SVGPropertyInfo.h"
 #include "platform/Timer.h"
 #include "wtf/HashMap.h"
+#include "wtf/OwnPtr.h"
 
 namespace WebCore {
 
 class AffineTransform;
 class CSSCursorImageValue;
 class Document;
+class NewSVGAnimatedPropertyBase;
 class SubtreeLayoutScope;
 class SVGAttributeToPropertyMap;
 class SVGCursorElement;
 class SVGDocumentExtensions;
 class SVGElementInstance;
 class SVGElementRareData;
+class SVGFitToViewBox;
 class SVGSVGElement;
 
 void mapAttributeToCSSProperty(HashMap<StringImpl*, CSSPropertyID>* propertyNameToIdMap, const QualifiedName& attrName);
 
-class SVGElement : public Element, public SVGLangSpace {
+class SVGElement : public Element {
 public:
     virtual ~SVGElement();
 
     bool isOutermostSVGSVGElement() const;
 
-    virtual String title() const;
+    virtual String title() const OVERRIDE;
     bool hasRelativeLengths() const { return !m_elementsWithRelativeLengths.isEmpty(); }
     virtual bool supportsMarkers() const { return false; }
-    PassRefPtr<CSSValue> getPresentationAttribute(const String& name);
-    bool isKnownAttribute(const QualifiedName&);
+    PassRefPtr<CSSValue> getPresentationAttribute(const AtomicString& name);
     static bool isAnimatableCSSProperty(const QualifiedName&);
     enum CTMScope {
         NearestViewportScope, // Used by SVGGraphicsElement::getCTM()
@@ -68,8 +69,14 @@
     bool instanceUpdatesBlocked() const;
     void setInstanceUpdatesBlocked(bool);
 
-    String xmlbase() const;
-    void setXMLbase(const String&);
+    const AtomicString& xmlbase() const;
+    void setXMLbase(const AtomicString&);
+
+    const AtomicString& xmllang() const;
+    void setXMLlang(const AtomicString&);
+
+    const AtomicString& xmlspace() const;
+    void setXMLspace(const AtomicString&);
 
     SVGSVGElement* ownerSVGElement() const;
     SVGElement* viewportElement() const;
@@ -81,13 +88,16 @@
     virtual bool isFilterEffect() const { return false; }
     virtual bool isGradientStop() const { return false; }
     virtual bool isTextContent() const { return false; }
+    virtual bool isTextPositioning() const { return false; }
+    virtual bool isStructurallyExternal() const { return false; }
 
     // For SVGTests
     virtual bool isValid() const { return true; }
 
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual void animatedPropertyTypeForAttribute(const QualifiedName&, Vector<AnimatedPropertyType>&);
+    void animatedPropertyTypeForAttribute(const QualifiedName&, Vector<AnimatedPropertyType>&);
+    PassRefPtr<NewSVGAnimatedPropertyBase> propertyFromAttribute(const QualifiedName& attributeName);
 
     void sendSVGLoadEventIfPossible(bool sendParentLoadEvents = false);
     void sendSVGLoadEventIfPossibleAsynchronously();
@@ -112,7 +122,7 @@
 
     void synchronizeAnimatedSVGAttribute(const QualifiedName&) const;
 
-    virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
+    virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE FINAL;
 
     static void synchronizeRequiredFeatures(SVGElement* contextElement);
     static void synchronizeRequiredExtensions(SVGElement* contextElement);
@@ -123,7 +133,7 @@
     virtual void synchronizeSystemLanguage() { }
 
 #ifndef NDEBUG
-    bool isAnimatableAttribute(const QualifiedName&) const;
+    virtual bool isAnimatableAttribute(const QualifiedName&) const;
 #endif
 
     MutableStylePropertySet* animatedSMILStyleProperties() const;
@@ -132,24 +142,25 @@
 
     virtual bool haveLoadedRequiredResources();
 
-    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE;
-    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE;
-
-    virtual bool shouldMoveToFlowThread(RenderStyle*) const OVERRIDE;
+    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE FINAL;
+    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE FINAL;
 
     void invalidateRelativeLengthClients(SubtreeLayoutScope* = 0);
 
     bool isContextElement() const { return m_isContextElement; }
     void setContextElement() { m_isContextElement = true; }
 
+    void addToPropertyMap(PassRefPtr<NewSVGAnimatedPropertyBase>);
+
+    SVGAnimatedString* className() { return m_className.get(); }
+
 protected:
     SVGElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
-    virtual void finishParsingChildren();
+    virtual void finishParsingChildren() OVERRIDE;
     virtual void attributeChanged(const QualifiedName&, const AtomicString&, AttributeModificationReason = ModifiedDirectly) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
@@ -157,7 +168,7 @@
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
     static CSSPropertyID cssPropertyIdForSVGAttributeName(const QualifiedName&);
     void updateRelativeLengthsInformation() { updateRelativeLengthsInformation(selfHasRelativeLengths(), this); }
@@ -168,6 +179,12 @@
     SVGElementRareData* svgRareData() const;
     SVGElementRareData* ensureSVGRareData();
 
+    bool hasSVGRareData() const { return m_hasSVGRareData; }
+    void setHasSVGRareData() { m_hasSVGRareData = true; }
+    void clearHasSVGRareData() { m_hasSVGRareData = false; }
+
+    // SVGFitToViewBox::parseAttribute uses reportAttributeParsingError.
+    friend class SVGFitToViewBox;
     void reportAttributeParsingError(SVGParsingError, const QualifiedName&, const AtomicString&);
     bool hasFocusEventListeners() const;
 
@@ -195,10 +212,10 @@
 
     // FIXME: Author shadows should be allowed
     // https://bugs.webkit.org/show_bug.cgi?id=77938
-    virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
+    virtual bool areAuthorShadowsAllowed() const OVERRIDE FINAL { return false; }
 
     RenderStyle* computedStyle(PseudoId = NOPSEUDO);
-    virtual RenderStyle* virtualComputedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) { return computedStyle(pseudoElementSpecifier); }
+    virtual RenderStyle* virtualComputedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) OVERRIDE FINAL { return computedStyle(pseudoElementSpecifier); }
     virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
     virtual bool isKeyboardFocusable() const OVERRIDE;
 
@@ -212,15 +229,19 @@
 
     HashSet<SVGElement*> m_elementsWithRelativeLengths;
 
-    BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGElement)
-        DECLARE_ANIMATED_STRING(ClassName, className)
-    END_DECLARE_ANIMATED_PROPERTIES
+    typedef HashMap<QualifiedName, RefPtr<NewSVGAnimatedPropertyBase> > AttributeToPropertyMap;
+    AttributeToPropertyMap m_newAttributeToPropertyMap;
 
 #if !ASSERT_DISABLED
     bool m_inRelativeLengthClientsInvalidation;
 #endif
-    bool m_animatedPropertiesDestructed;
-    bool m_isContextElement;
+    unsigned m_animatedPropertiesDestructed : 1;
+    unsigned m_isContextElement : 1;
+    unsigned m_hasSVGRareData : 1;
+
+    RefPtr<SVGAnimatedString> m_className;
+    BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGElement)
+    END_DECLARE_ANIMATED_PROPERTIES
 };
 
 struct SVGAttributeHashTranslator {
diff --git a/Source/core/svg/SVGElement.idl b/Source/core/svg/SVGElement.idl
index d27e2ab..feffa7c 100644
--- a/Source/core/svg/SVGElement.idl
+++ b/Source/core/svg/SVGElement.idl
@@ -23,7 +23,7 @@
 [
     Custom=Wrap,
 ] interface SVGElement : Element {
-    [TreatNullAs=NullString] attribute DOMString xmlbase;
+    attribute DOMString xmlbase;
     readonly attribute SVGSVGElement ownerSVGElement;
     readonly attribute SVGElement viewportElement;
 
@@ -33,7 +33,10 @@
     readonly attribute SVGAnimatedString className;
     readonly attribute CSSStyleDeclaration style;
 
-    CSSValue getPresentationAttribute([Default=Undefined] optional DOMString name);
+    // CSSValue was deprecated in 2003:
+    // http://lists.w3.org/Archives/Public/www-style/2003Oct/0347.html
+    [DeprecateAs=SVGElementGetPresentationAttribute] CSSValue getPresentationAttribute([Default=Undefined] optional DOMString name);
 };
 
 SVGElement implements GlobalEventHandlers;
+
diff --git a/Source/core/svg/SVGElementInstance.h b/Source/core/svg/SVGElementInstance.h
index 66de33c..8ae0bfa 100644
--- a/Source/core/svg/SVGElementInstance.h
+++ b/Source/core/svg/SVGElementInstance.h
@@ -38,7 +38,7 @@
 class SVGUseElement;
 
 // SVGElementInstance mimics Node, but without providing all its functionality
-class SVGElementInstance : public EventTarget, public ScriptWrappable, public TreeShared<SVGElementInstance> {
+class SVGElementInstance FINAL : public EventTarget, public ScriptWrappable, public TreeShared<SVGElementInstance> {
     DEFINE_EVENT_TARGET_REFCOUNTING(TreeShared<SVGElementInstance>);
 public:
     static PassRefPtr<SVGElementInstance> create(SVGUseElement* correspondingUseElement, SVGUseElement* directUseElement, PassRefPtr<SVGElement> originalElement);
@@ -47,12 +47,12 @@
 
     void setParentOrShadowHostNode(SVGElementInstance* instance) { m_parentInstance = instance; }
 
-    virtual const AtomicString& interfaceName() const;
-    virtual ExecutionContext* executionContext() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
+    virtual ExecutionContext* executionContext() const OVERRIDE;
 
-    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
-    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
-    virtual void removeAllEventListeners();
+    virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE;
+    virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE;
+    virtual void removeAllEventListeners() OVERRIDE;
 
     using EventTarget::dispatchEvent;
     virtual bool dispatchEvent(PassRefPtr<Event>) OVERRIDE;
@@ -150,7 +150,7 @@
     void removedLastRef();
     bool hasTreeSharedParent() const { return !!m_parentInstance; }
 
-    virtual Node* toNode();
+    virtual Node* toNode() OVERRIDE;
 
     void appendChild(PassRefPtr<SVGElementInstance> child);
     void setShadowTreeElement(SVGElement*);
diff --git a/Source/core/svg/SVGEllipseElement.cpp b/Source/core/svg/SVGEllipseElement.cpp
index f5046eb..5da4774 100644
--- a/Source/core/svg/SVGEllipseElement.cpp
+++ b/Source/core/svg/SVGEllipseElement.cpp
@@ -30,29 +30,23 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGEllipseElement, SVGNames::cxAttr, Cx, cx)
-DEFINE_ANIMATED_LENGTH(SVGEllipseElement, SVGNames::cyAttr, Cy, cy)
-DEFINE_ANIMATED_LENGTH(SVGEllipseElement, SVGNames::rxAttr, Rx, rx)
-DEFINE_ANIMATED_LENGTH(SVGEllipseElement, SVGNames::ryAttr, Ry, ry)
-DEFINE_ANIMATED_BOOLEAN(SVGEllipseElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGEllipseElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(cx)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(cy)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(rx)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(ry)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGEllipseElement::SVGEllipseElement(Document& document)
     : SVGGeometryElement(SVGNames::ellipseTag, document)
-    , m_cx(LengthModeWidth)
-    , m_cy(LengthModeHeight)
-    , m_rx(LengthModeWidth)
-    , m_ry(LengthModeHeight)
+    , m_cx(SVGAnimatedLength::create(this, SVGNames::cxAttr, SVGLength::create(LengthModeWidth)))
+    , m_cy(SVGAnimatedLength::create(this, SVGNames::cyAttr, SVGLength::create(LengthModeHeight)))
+    , m_rx(SVGAnimatedLength::create(this, SVGNames::rxAttr, SVGLength::create(LengthModeWidth)))
+    , m_ry(SVGAnimatedLength::create(this, SVGNames::ryAttr, SVGLength::create(LengthModeHeight)))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_cx);
+    addToPropertyMap(m_cy);
+    addToPropertyMap(m_rx);
+    addToPropertyMap(m_ry);
     registerAnimatedPropertiesForSVGEllipseElement();
 }
 
@@ -65,8 +59,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGLangSpace::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::cxAttr);
         supportedAttributes.add(SVGNames::cyAttr);
         supportedAttributes.add(SVGNames::rxAttr);
@@ -82,16 +74,14 @@
     if (!isSupportedAttribute(name))
         SVGGeometryElement::parseAttribute(name, value);
     else if (name == SVGNames::cxAttr)
-        setCxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_cx->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::cyAttr)
-        setCyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_cy->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::rxAttr)
-        setRxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
+        m_rx->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::ryAttr)
-        setRyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGLangSpace::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)) {
-    } else
+        m_ry->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    else
         ASSERT_NOT_REACHED();
 
     reportAttributeParsingError(parseError, name, value);
@@ -124,20 +114,15 @@
         return;
     }
 
-    if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
-        RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
-        return;
-    }
-
     ASSERT_NOT_REACHED();
 }
 
 bool SVGEllipseElement::selfHasRelativeLengths() const
 {
-    return cxCurrentValue().isRelative()
-        || cyCurrentValue().isRelative()
-        || rxCurrentValue().isRelative()
-        || ryCurrentValue().isRelative();
+    return m_cx->currentValue()->isRelative()
+        || m_cy->currentValue()->isRelative()
+        || m_rx->currentValue()->isRelative()
+        || m_ry->currentValue()->isRelative();
 }
 
 RenderObject* SVGEllipseElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGEllipseElement.h b/Source/core/svg/SVGEllipseElement.h
index e0cc981..372c57d 100644
--- a/Source/core/svg/SVGEllipseElement.h
+++ b/Source/core/svg/SVGEllipseElement.h
@@ -24,36 +24,37 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGeometryElement.h"
 
 namespace WebCore {
 
-class SVGEllipseElement FINAL : public SVGGeometryElement,
-                                public SVGExternalResourcesRequired {
+class SVGEllipseElement FINAL : public SVGGeometryElement {
 public:
     static PassRefPtr<SVGEllipseElement> create(Document&);
 
+    SVGAnimatedLength* cx() const { return m_cx.get(); }
+    SVGAnimatedLength* cy() const { return m_cy.get(); }
+    SVGAnimatedLength* rx() const { return m_rx.get(); }
+    SVGAnimatedLength* ry() const { return m_ry.get(); }
+
 private:
     explicit SVGEllipseElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_cx;
+    RefPtr<SVGAnimatedLength> m_cy;
+    RefPtr<SVGAnimatedLength> m_rx;
+    RefPtr<SVGAnimatedLength> m_ry;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGEllipseElement)
-        DECLARE_ANIMATED_LENGTH(Cx, cx)
-        DECLARE_ANIMATED_LENGTH(Cy, cy)
-        DECLARE_ANIMATED_LENGTH(Rx, rx)
-        DECLARE_ANIMATED_LENGTH(Ry, ry)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGEllipseElement.idl b/Source/core/svg/SVGEllipseElement.idl
index fcd09c7..141ac2e 100644
--- a/Source/core/svg/SVGEllipseElement.idl
+++ b/Source/core/svg/SVGEllipseElement.idl
@@ -30,5 +30,3 @@
     readonly attribute SVGAnimatedLength ry;
 };
 
-SVGEllipseElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGExternalResourcesRequired.cpp b/Source/core/svg/SVGExternalResourcesRequired.cpp
deleted file mode 100644
index 74bfcc5..0000000
--- a/Source/core/svg/SVGExternalResourcesRequired.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2007 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGExternalResourcesRequired.h"
-
-#include "SVGNames.h"
-#include "core/svg/SVGElement.h"
-
-namespace WebCore {
-
-bool SVGExternalResourcesRequired::parseAttribute(const QualifiedName& name, const AtomicString& value)
-{
-    if (name == SVGNames::externalResourcesRequiredAttr) {
-        setExternalResourcesRequiredBaseValue(value == "true");
-        return true;
-    }
-
-    return false;
-}
-
-bool SVGExternalResourcesRequired::isKnownAttribute(const QualifiedName& attrName)
-{
-    return attrName == SVGNames::externalResourcesRequiredAttr;
-}
-
-void SVGExternalResourcesRequired::addSupportedAttributes(HashSet<QualifiedName>& supportedAttributes)
-{
-    supportedAttributes.add(SVGNames::externalResourcesRequiredAttr);
-}
-
-bool SVGExternalResourcesRequired::handleAttributeChange(SVGElement* targetElement, const QualifiedName& attrName)
-{
-    ASSERT(targetElement);
-    if (!isKnownAttribute(attrName))
-        return false;
-    if (!targetElement->inDocument())
-        return true;
-
-    // Handle dynamic updates of the 'externalResourcesRequired' attribute. Only possible case: changing from 'true' to 'false'
-    // causes an immediate dispatch of the SVGLoad event. If the attribute value was 'false' before inserting the script element
-    // in the document, the SVGLoad event has already been dispatched.
-    if (!externalResourcesRequiredBaseValue() && !haveFiredLoadEvent() && !isParserInserted()) {
-        setHaveFiredLoadEvent(true);
-        ASSERT(targetElement->haveLoadedRequiredResources());
-
-        targetElement->sendSVGLoadEventIfPossible();
-    }
-
-    return true;
-}
-
-void SVGExternalResourcesRequired::dispatchLoadEvent(SVGElement* targetElement)
-{
-    bool externalResourcesRequired = externalResourcesRequiredBaseValue();
-
-    if (isParserInserted())
-        ASSERT(externalResourcesRequired != haveFiredLoadEvent());
-    else if (haveFiredLoadEvent())
-        return;
-
-    // HTML and SVG differ completely in the 'onload' event handling of <script> elements.
-    // HTML fires the 'load' event after it sucessfully loaded a remote resource, otherwise an error event.
-    // SVG fires the SVGLoad event immediately after parsing the <script> element, if externalResourcesRequired
-    // is set to 'false', otherwise it dispatches the 'SVGLoad' event just after loading the remote resource.
-    if (!externalResourcesRequired)
-        return;
-
-    ASSERT(!haveFiredLoadEvent());
-
-    // Dispatch SVGLoad event
-    setHaveFiredLoadEvent(true);
-    ASSERT(targetElement->haveLoadedRequiredResources());
-
-    targetElement->sendSVGLoadEventIfPossible();
-}
-
-void SVGExternalResourcesRequired::insertedIntoDocument(SVGElement* targetElement)
-{
-    if (isParserInserted())
-        return;
-
-    // Eventually send SVGLoad event now for the dynamically inserted script element.
-    if (externalResourcesRequiredBaseValue())
-        return;
-    setHaveFiredLoadEvent(true);
-    targetElement->sendSVGLoadEventIfPossibleAsynchronously();
-}
-
-void SVGExternalResourcesRequired::finishParsingChildren()
-{
-    // A SVGLoad event has been fired by SVGElement::finishParsingChildren.
-    if (!externalResourcesRequiredBaseValue())
-        setHaveFiredLoadEvent(true);
-}
-
-bool SVGExternalResourcesRequired::haveLoadedRequiredResources() const
-{
-    return !externalResourcesRequiredBaseValue() || haveFiredLoadEvent();
-}
-
-}
diff --git a/Source/core/svg/SVGExternalResourcesRequired.h b/Source/core/svg/SVGExternalResourcesRequired.h
deleted file mode 100644
index 04b94fd..0000000
--- a/Source/core/svg/SVGExternalResourcesRequired.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGExternalResourcesRequired_h
-#define SVGExternalResourcesRequired_h
-
-#include "core/dom/QualifiedName.h"
-#include "wtf/HashSet.h"
-
-namespace WebCore {
-
-class Attribute;
-class SVGElement;
-
-// Notes on a SVG 1.1 spec discrepancy:
-// The SVG DOM defines the attribute externalResourcesRequired as being of type SVGAnimatedBoolean, whereas the
-// SVG language definition says that externalResourcesRequired is not animated. Because the SVG language definition
-// states that externalResourcesRequired cannot be animated, the animVal will always be the same as the baseVal.
-// FIXME: When implementing animVal support, make sure that animVal==baseVal for externalResourcesRequired
-class SVGExternalResourcesRequired {
-public:
-    virtual ~SVGExternalResourcesRequired() { }
-
-    bool parseAttribute(const QualifiedName&, const AtomicString&);
-    bool isKnownAttribute(const QualifiedName&);
-    void addSupportedAttributes(HashSet<QualifiedName>&);
-    bool handleAttributeChange(SVGElement*, const QualifiedName&);
-
-protected:
-    // These types look a bit awkward, but have to match the generic types of the SVGAnimatedProperty macros.
-    virtual void setExternalResourcesRequiredBaseValue(const bool&) = 0;
-    virtual bool& externalResourcesRequiredBaseValue() const = 0;
-
-    virtual void setHaveFiredLoadEvent(bool) { }
-    virtual bool isParserInserted() const { return false; }
-    virtual bool haveFiredLoadEvent() const { return false; }
-
-    void dispatchLoadEvent(SVGElement*);
-    void insertedIntoDocument(SVGElement*);
-    void finishParsingChildren();
-    bool haveLoadedRequiredResources() const;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/svg/SVGExternalResourcesRequired.idl b/Source/core/svg/SVGExternalResourcesRequired.idl
deleted file mode 100644
index efc8366..0000000
--- a/Source/core/svg/SVGExternalResourcesRequired.idl
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- * Copyright (C) 2006 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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.
- */
-
-[
-    NoInterfaceObject,
-    LegacyImplementedInBaseClass
-] interface SVGExternalResourcesRequired {
-    readonly attribute SVGAnimatedBoolean externalResourcesRequired;
-};
-
diff --git a/Source/core/svg/SVGFEBlendElement.cpp b/Source/core/svg/SVGFEBlendElement.cpp
index 832b4e4..53556fd 100644
--- a/Source/core/svg/SVGFEBlendElement.cpp
+++ b/Source/core/svg/SVGFEBlendElement.cpp
@@ -30,22 +30,22 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEBlendElement, SVGNames::inAttr, In1, in1)
-DEFINE_ANIMATED_STRING(SVGFEBlendElement, SVGNames::in2Attr, In2, in2)
 DEFINE_ANIMATED_ENUMERATION(SVGFEBlendElement, SVGNames::modeAttr, Mode, mode, BlendModeType)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEBlendElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in2)
     REGISTER_LOCAL_ANIMATED_PROPERTY(mode)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEBlendElement::SVGFEBlendElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feBlendTag, document)
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
+    , m_in2(SVGAnimatedString::create(this, SVGNames::in2Attr, SVGString::create()))
     , m_mode(FEBLEND_MODE_NORMAL)
 {
     ScriptWrappable::init(this);
+    addToPropertyMap(m_in1);
+    addToPropertyMap(m_in2);
     registerAnimatedPropertiesForSVGFEBlendElement();
 }
 
@@ -79,17 +79,16 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::in2Attr) {
-        setIn2BaseValue(value);
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::in2Attr)
+        m_in2->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 bool SVGFEBlendElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
@@ -126,8 +125,8 @@
 
 PassRefPtr<FilterEffect> SVGFEBlendElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
-    FilterEffect* input2 = filterBuilder->getEffectById(in2CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
+    FilterEffect* input2 = filterBuilder->getEffectById(AtomicString(m_in2->currentValue()->value()));
 
     if (!input1 || !input2)
         return 0;
diff --git a/Source/core/svg/SVGFEBlendElement.h b/Source/core/svg/SVGFEBlendElement.h
index 20e211d..ae91fba 100644
--- a/Source/core/svg/SVGFEBlendElement.h
+++ b/Source/core/svg/SVGFEBlendElement.h
@@ -71,19 +71,21 @@
 class SVGFEBlendElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
     static PassRefPtr<SVGFEBlendElement> create(Document&);
+    SVGAnimatedString* in1() { return m_in1.get(); }
+    SVGAnimatedString* in2() { return m_in2.get(); }
 
 private:
     explicit SVGFEBlendElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName);
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName) OVERRIDE;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
+    RefPtr<SVGAnimatedString> m_in1;
+    RefPtr<SVGAnimatedString> m_in2;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEBlendElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
-        DECLARE_ANIMATED_STRING(In2, in2)
         DECLARE_ANIMATED_ENUMERATION(Mode, mode, BlendModeType)
     END_DECLARE_ANIMATED_PROPERTIES
 };
diff --git a/Source/core/svg/SVGFEColorMatrixElement.cpp b/Source/core/svg/SVGFEColorMatrixElement.cpp
index a6fc8e4..56b9044 100644
--- a/Source/core/svg/SVGFEColorMatrixElement.cpp
+++ b/Source/core/svg/SVGFEColorMatrixElement.cpp
@@ -30,22 +30,23 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEColorMatrixElement, SVGNames::inAttr, In1, in1)
 DEFINE_ANIMATED_ENUMERATION(SVGFEColorMatrixElement, SVGNames::typeAttr, Type, type, ColorMatrixType)
-DEFINE_ANIMATED_NUMBER_LIST(SVGFEColorMatrixElement, SVGNames::valuesAttr, Values, values)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEColorMatrixElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
     REGISTER_LOCAL_ANIMATED_PROPERTY(type)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(values)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEColorMatrixElement::SVGFEColorMatrixElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feColorMatrixTag, document)
+    , m_values(SVGAnimatedNumberList::create(this, SVGNames::valuesAttr, SVGNumberList::create()))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
     , m_type(FECOLORMATRIX_TYPE_MATRIX)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_values);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFEColorMatrixElement();
 }
 
@@ -79,20 +80,16 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::valuesAttr) {
-        SVGNumberList newList;
-        newList.parse(value);
-        detachAnimatedValuesListWrappers(newList.size());
-        setValuesBaseValue(newList);
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::valuesAttr)
+        m_values->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 bool SVGFEColorMatrixElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
@@ -101,7 +98,7 @@
     if (attrName == SVGNames::typeAttr)
         return colorMatrix->setType(typeCurrentValue());
     if (attrName == SVGNames::valuesAttr)
-        return colorMatrix->setValues(valuesCurrentValue().toFloatVector());
+        return colorMatrix->setValues(m_values->currentValue()->toFloatVector());
 
     ASSERT_NOT_REACHED();
     return false;
@@ -131,7 +128,7 @@
 
 PassRefPtr<FilterEffect> SVGFEColorMatrixElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
 
     if (!input1)
         return 0;
@@ -156,15 +153,15 @@
             break;
         }
     } else {
-        SVGNumberList& values = valuesCurrentValue();
-        unsigned size = values.size();
+        RefPtr<SVGNumberList> values = m_values->currentValue();
+        size_t size = values->numberOfItems();
 
         if ((filterType == FECOLORMATRIX_TYPE_MATRIX && size != 20)
             || (filterType == FECOLORMATRIX_TYPE_HUEROTATE && size != 1)
             || (filterType == FECOLORMATRIX_TYPE_SATURATE && size != 1))
             return 0;
 
-        filterValues = values.toFloatVector();
+        filterValues = values->toFloatVector();
     }
 
     RefPtr<FilterEffect> effect = FEColorMatrix::create(filter, filterType, filterValues);
diff --git a/Source/core/svg/SVGFEColorMatrixElement.h b/Source/core/svg/SVGFEColorMatrixElement.h
index 1ed615f..9796c07 100644
--- a/Source/core/svg/SVGFEColorMatrixElement.h
+++ b/Source/core/svg/SVGFEColorMatrixElement.h
@@ -69,19 +69,22 @@
 public:
     static PassRefPtr<SVGFEColorMatrixElement> create(Document&);
 
+    SVGAnimatedNumberList* values() { return m_values.get(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
+
 private:
     explicit SVGFEColorMatrixElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&);
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&) OVERRIDE;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
+    RefPtr<SVGAnimatedNumberList> m_values;
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEColorMatrixElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
         DECLARE_ANIMATED_ENUMERATION(Type, type, ColorMatrixType)
-        DECLARE_ANIMATED_NUMBER_LIST(Values, values)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEComponentTransferElement.cpp b/Source/core/svg/SVGFEComponentTransferElement.cpp
index 127dac2..89cc6ea 100644
--- a/Source/core/svg/SVGFEComponentTransferElement.cpp
+++ b/Source/core/svg/SVGFEComponentTransferElement.cpp
@@ -33,17 +33,17 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEComponentTransferElement, SVGNames::inAttr, In1, in1)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEComponentTransferElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEComponentTransferElement::SVGFEComponentTransferElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feComponentTransferTag, document)
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFEComponentTransferElement();
 }
 
@@ -67,17 +67,19 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    ASSERT_NOT_REACHED();
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
+
+    reportAttributeParsingError(parseError, name, value);
 }
 
 PassRefPtr<FilterEffect> SVGFEComponentTransferElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
 
     if (!input1)
         return 0;
diff --git a/Source/core/svg/SVGFEComponentTransferElement.h b/Source/core/svg/SVGFEComponentTransferElement.h
index c83f1fe..460ddf5 100644
--- a/Source/core/svg/SVGFEComponentTransferElement.h
+++ b/Source/core/svg/SVGFEComponentTransferElement.h
@@ -29,6 +29,7 @@
 class SVGFEComponentTransferElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
     static PassRefPtr<SVGFEComponentTransferElement> create(Document&);
+    SVGAnimatedString* in1() { return m_in1.get(); }
 
 private:
     explicit SVGFEComponentTransferElement(Document&);
@@ -36,10 +37,10 @@
     // FIXME: svgAttributeChanged missing.
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEComponentTransferElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFECompositeElement.cpp b/Source/core/svg/SVGFECompositeElement.cpp
index d9afc49..62faa23 100644
--- a/Source/core/svg/SVGFECompositeElement.cpp
+++ b/Source/core/svg/SVGFECompositeElement.cpp
@@ -30,30 +30,31 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFECompositeElement, SVGNames::inAttr, In1, in1)
-DEFINE_ANIMATED_STRING(SVGFECompositeElement, SVGNames::in2Attr, In2, in2)
 DEFINE_ANIMATED_ENUMERATION(SVGFECompositeElement, SVGNames::operatorAttr, SVGOperator, svgOperator, CompositeOperationType)
-DEFINE_ANIMATED_NUMBER(SVGFECompositeElement, SVGNames::k1Attr, K1, k1)
-DEFINE_ANIMATED_NUMBER(SVGFECompositeElement, SVGNames::k2Attr, K2, k2)
-DEFINE_ANIMATED_NUMBER(SVGFECompositeElement, SVGNames::k3Attr, K3, k3)
-DEFINE_ANIMATED_NUMBER(SVGFECompositeElement, SVGNames::k4Attr, K4, k4)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFECompositeElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in2)
     REGISTER_LOCAL_ANIMATED_PROPERTY(svgOperator)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(k1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(k2)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(k3)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(k4)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFECompositeElement::SVGFECompositeElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feCompositeTag, document)
+    , m_k1(SVGAnimatedNumber::create(this, SVGNames::k1Attr, SVGNumber::create()))
+    , m_k2(SVGAnimatedNumber::create(this, SVGNames::k2Attr, SVGNumber::create()))
+    , m_k3(SVGAnimatedNumber::create(this, SVGNames::k3Attr, SVGNumber::create()))
+    , m_k4(SVGAnimatedNumber::create(this, SVGNames::k4Attr, SVGNumber::create()))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
+    , m_in2(SVGAnimatedString::create(this, SVGNames::in2Attr, SVGString::create()))
     , m_svgOperator(FECOMPOSITE_OPERATOR_OVER)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_k1);
+    addToPropertyMap(m_k2);
+    addToPropertyMap(m_k3);
+    addToPropertyMap(m_k4);
+    addToPropertyMap(m_in1);
+    addToPropertyMap(m_in2);
     registerAnimatedPropertiesForSVGFECompositeElement();
 }
 
@@ -91,37 +92,24 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::in2Attr) {
-        setIn2BaseValue(value);
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::in2Attr)
+        m_in2->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::k1Attr)
+        m_k1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::k2Attr)
+        m_k2->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::k3Attr)
+        m_k3->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::k4Attr)
+        m_k4->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::k1Attr) {
-        setK1BaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::k2Attr) {
-        setK2BaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::k3Attr) {
-        setK3BaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::k4Attr) {
-        setK4BaseValue(value.toFloat());
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 bool SVGFECompositeElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
@@ -130,13 +118,13 @@
     if (attrName == SVGNames::operatorAttr)
         return composite->setOperation(svgOperatorCurrentValue());
     if (attrName == SVGNames::k1Attr)
-        return composite->setK1(k1CurrentValue());
+        return composite->setK1(m_k1->currentValue()->value());
     if (attrName == SVGNames::k2Attr)
-        return composite->setK2(k2CurrentValue());
+        return composite->setK2(m_k2->currentValue()->value());
     if (attrName == SVGNames::k3Attr)
-        return composite->setK3(k3CurrentValue());
+        return composite->setK3(m_k3->currentValue()->value());
     if (attrName == SVGNames::k4Attr)
-        return composite->setK4(k4CurrentValue());
+        return composite->setK4(m_k4->currentValue()->value());
 
     ASSERT_NOT_REACHED();
     return false;
@@ -171,13 +159,13 @@
 
 PassRefPtr<FilterEffect> SVGFECompositeElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
-    FilterEffect* input2 = filterBuilder->getEffectById(in2CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
+    FilterEffect* input2 = filterBuilder->getEffectById(AtomicString(m_in2->currentValue()->value()));
 
     if (!input1 || !input2)
         return 0;
 
-    RefPtr<FilterEffect> effect = FEComposite::create(filter, svgOperatorCurrentValue(), k1CurrentValue(), k2CurrentValue(), k3CurrentValue(), k4CurrentValue());
+    RefPtr<FilterEffect> effect = FEComposite::create(filter, svgOperatorCurrentValue(), m_k1->currentValue()->value(), m_k2->currentValue()->value(), m_k3->currentValue()->value(), m_k4->currentValue()->value());
     FilterEffectVector& inputEffects = effect->inputEffects();
     inputEffects.reserveCapacity(2);
     inputEffects.append(input1);
diff --git a/Source/core/svg/SVGFECompositeElement.h b/Source/core/svg/SVGFECompositeElement.h
index dad0fb2..dae7b64 100644
--- a/Source/core/svg/SVGFECompositeElement.h
+++ b/Source/core/svg/SVGFECompositeElement.h
@@ -77,23 +77,30 @@
 public:
     static PassRefPtr<SVGFECompositeElement> create(Document&);
 
+    SVGAnimatedNumber* k1() { return m_k1.get(); }
+    SVGAnimatedNumber* k2() { return m_k2.get(); }
+    SVGAnimatedNumber* k3() { return m_k3.get(); }
+    SVGAnimatedNumber* k4() { return m_k4.get(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
+    SVGAnimatedString* in2() { return m_in2.get(); }
+
 private:
     explicit SVGFECompositeElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&);
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&) OVERRIDE;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
+    RefPtr<SVGAnimatedNumber> m_k1;
+    RefPtr<SVGAnimatedNumber> m_k2;
+    RefPtr<SVGAnimatedNumber> m_k3;
+    RefPtr<SVGAnimatedNumber> m_k4;
+    RefPtr<SVGAnimatedString> m_in1;
+    RefPtr<SVGAnimatedString> m_in2;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFECompositeElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
-        DECLARE_ANIMATED_STRING(In2, in2)
         DECLARE_ANIMATED_ENUMERATION(SVGOperator, svgOperator, CompositeOperationType)
-        DECLARE_ANIMATED_NUMBER(K1, k1)
-        DECLARE_ANIMATED_NUMBER(K2, k2)
-        DECLARE_ANIMATED_NUMBER(K3, k3)
-        DECLARE_ANIMATED_NUMBER(K4, k4)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEConvolveMatrixElement.cpp b/Source/core/svg/SVGFEConvolveMatrixElement.cpp
index 2fad4d9..6565c2f 100644
--- a/Source/core/svg/SVGFEConvolveMatrixElement.cpp
+++ b/Source/core/svg/SVGFEConvolveMatrixElement.cpp
@@ -33,40 +33,37 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEConvolveMatrixElement, SVGNames::inAttr, In1, in1)
-DEFINE_ANIMATED_INTEGER_MULTIPLE_WRAPPERS(SVGFEConvolveMatrixElement, SVGNames::orderAttr, orderXIdentifier(), OrderX, orderX)
-DEFINE_ANIMATED_INTEGER_MULTIPLE_WRAPPERS(SVGFEConvolveMatrixElement, SVGNames::orderAttr, orderYIdentifier(), OrderY, orderY)
-DEFINE_ANIMATED_NUMBER_LIST(SVGFEConvolveMatrixElement, SVGNames::kernelMatrixAttr, KernelMatrix, kernelMatrix)
-DEFINE_ANIMATED_NUMBER(SVGFEConvolveMatrixElement, SVGNames::divisorAttr, Divisor, divisor)
-DEFINE_ANIMATED_NUMBER(SVGFEConvolveMatrixElement, SVGNames::biasAttr, Bias, bias)
-DEFINE_ANIMATED_INTEGER(SVGFEConvolveMatrixElement, SVGNames::targetXAttr, TargetX, targetX)
-DEFINE_ANIMATED_INTEGER(SVGFEConvolveMatrixElement, SVGNames::targetYAttr, TargetY, targetY)
 DEFINE_ANIMATED_ENUMERATION(SVGFEConvolveMatrixElement, SVGNames::edgeModeAttr, EdgeMode, edgeMode, EdgeModeType)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEConvolveMatrixElement, SVGNames::kernelUnitLengthAttr, kernelUnitLengthXIdentifier(), KernelUnitLengthX, kernelUnitLengthX)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEConvolveMatrixElement, SVGNames::kernelUnitLengthAttr, kernelUnitLengthYIdentifier(), KernelUnitLengthY, kernelUnitLengthY)
-DEFINE_ANIMATED_BOOLEAN(SVGFEConvolveMatrixElement, SVGNames::preserveAlphaAttr, PreserveAlpha, preserveAlpha)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEConvolveMatrixElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(orderX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(orderY)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(kernelMatrix)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(divisor)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(bias)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(targetX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(targetY)
     REGISTER_LOCAL_ANIMATED_PROPERTY(edgeMode)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(kernelUnitLengthX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(kernelUnitLengthY)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAlpha)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEConvolveMatrixElement::SVGFEConvolveMatrixElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feConvolveMatrixTag, document)
+    , m_bias(SVGAnimatedNumber::create(this, SVGNames::biasAttr, SVGNumber::create()))
+    , m_divisor(SVGAnimatedNumber::create(this, SVGNames::divisorAttr, SVGNumber::create()))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
+    , m_kernelMatrix(SVGAnimatedNumberList::create(this, SVGNames::kernelMatrixAttr, SVGNumberList::create()))
+    , m_kernelUnitLength(SVGAnimatedNumberOptionalNumber::create(this, SVGNames::kernelUnitLengthAttr))
+    , m_order(SVGAnimatedIntegerOptionalInteger::create(this, SVGNames::orderAttr))
+    , m_preserveAlpha(SVGAnimatedBoolean::create(this, SVGNames::preserveAlphaAttr, SVGBoolean::create()))
+    , m_targetX(SVGAnimatedInteger::create(this, SVGNames::targetXAttr, SVGInteger::create()))
+    , m_targetY(SVGAnimatedInteger::create(this, SVGNames::targetYAttr, SVGInteger::create()))
     , m_edgeMode(EDGEMODE_DUPLICATE)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_preserveAlpha);
+    addToPropertyMap(m_divisor);
+    addToPropertyMap(m_bias);
+    addToPropertyMap(m_kernelUnitLength);
+    addToPropertyMap(m_kernelMatrix);
+    addToPropertyMap(m_in1);
+    addToPropertyMap(m_order);
+    addToPropertyMap(m_targetX);
+    addToPropertyMap(m_targetY);
     registerAnimatedPropertiesForSVGFEConvolveMatrixElement();
 }
 
@@ -75,30 +72,6 @@
     return adoptRef(new SVGFEConvolveMatrixElement(document));
 }
 
-const AtomicString& SVGFEConvolveMatrixElement::kernelUnitLengthXIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGKernelUnitLengthX", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGFEConvolveMatrixElement::kernelUnitLengthYIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGKernelUnitLengthY", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGFEConvolveMatrixElement::orderXIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGOrderX", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGFEConvolveMatrixElement::orderYIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGOrderY", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
 bool SVGFEConvolveMatrixElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
@@ -124,24 +97,6 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
-
-    if (name == SVGNames::orderAttr) {
-        float x, y;
-        if (parseNumberOptionalNumber(value, x, y) && x >= 1 && y >= 1) {
-            setOrderXBaseValue(x);
-            setOrderYBaseValue(y);
-        } else {
-            document().accessSVGExtensions()->reportWarning(
-                "feConvolveMatrix: problem parsing order=\"" + value
-                + "\". Filtered element will not be displayed.");
-        }
-        return;
-    }
-
     if (name == SVGNames::edgeModeAttr) {
         EdgeModeType propertyValue = SVGPropertyTraits<EdgeModeType>::fromString(value);
         if (propertyValue > 0)
@@ -153,66 +108,35 @@
         return;
     }
 
-    if (name == SVGNames::kernelMatrixAttr) {
-        SVGNumberList newList;
-        newList.parse(value);
-        detachAnimatedKernelMatrixListWrappers(newList.size());
-        setKernelMatrixBaseValue(newList);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::divisorAttr) {
-        float divisor = value.toFloat();
-        if (divisor)
-            setDivisorBaseValue(divisor);
-        else
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::divisorAttr)
+        m_divisor->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::biasAttr)
+        m_bias->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::kernelUnitLengthAttr)
+        m_kernelUnitLength->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::kernelMatrixAttr)
+        m_kernelMatrix->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::preserveAlphaAttr)
+        m_preserveAlpha->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::targetXAttr)
+        m_targetX->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::targetYAttr)
+        m_targetY->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::orderAttr) {
+        m_order->setBaseValueAsString(value, parseError);
+        if (parseError == NoError && (orderX()->baseValue()->value() < 1 || orderY()->baseValue()->value() < 1)) {
             document().accessSVGExtensions()->reportWarning(
-                "feConvolveMatrix: problem parsing divisor=\"" + value
-                + "\". Filtered element will not be displayed.");
-        return;
-    }
-
-    if (name == SVGNames::biasAttr) {
-        setBiasBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::targetXAttr) {
-        setTargetXBaseValue(value.string().toUIntStrict());
-        return;
-    }
-
-    if (name == SVGNames::targetYAttr) {
-        setTargetYBaseValue(value.string().toUIntStrict());
-        return;
-    }
-
-    if (name == SVGNames::kernelUnitLengthAttr) {
-        float x, y;
-        if (parseNumberOptionalNumber(value, x, y) && x > 0 && y > 0) {
-            setKernelUnitLengthXBaseValue(x);
-            setKernelUnitLengthYBaseValue(y);
-        } else {
-            document().accessSVGExtensions()->reportWarning(
-                "feConvolveMatrix: problem parsing kernelUnitLength=\"" + value
+                "feConvolveMatrix: problem parsing order=\"" + value
                 + "\". Filtered element will not be displayed.");
         }
-        return;
-    }
+    } else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::preserveAlphaAttr) {
-        if (value == "true")
-            setPreserveAlphaBaseValue(true);
-        else if (value == "false")
-            setPreserveAlphaBaseValue(false);
-        else
-            document().accessSVGExtensions()->reportWarning(
-                "feConvolveMatrix: problem parsing preserveAlphaAttr=\"" + value
-                + "\". Filtered element will not be displayed.");
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 bool SVGFEConvolveMatrixElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
@@ -221,36 +145,22 @@
     if (attrName == SVGNames::edgeModeAttr)
         return convolveMatrix->setEdgeMode(edgeModeCurrentValue());
     if (attrName == SVGNames::divisorAttr)
-        return convolveMatrix->setDivisor(divisorCurrentValue());
+        return convolveMatrix->setDivisor(m_divisor->currentValue()->value());
     if (attrName == SVGNames::biasAttr)
-        return convolveMatrix->setBias(biasCurrentValue());
+        return convolveMatrix->setBias(m_bias->currentValue()->value());
     if (attrName == SVGNames::targetXAttr)
-        return convolveMatrix->setTargetOffset(IntPoint(targetXCurrentValue(), targetYCurrentValue()));
+        return convolveMatrix->setTargetOffset(IntPoint(m_targetX->currentValue()->value(), m_targetY->currentValue()->value()));
     if (attrName == SVGNames::targetYAttr)
-        return convolveMatrix->setTargetOffset(IntPoint(targetXCurrentValue(), targetYCurrentValue()));
+        return convolveMatrix->setTargetOffset(IntPoint(m_targetX->currentValue()->value(), m_targetY->currentValue()->value()));
     if (attrName == SVGNames::kernelUnitLengthAttr)
-        return convolveMatrix->setKernelUnitLength(FloatPoint(kernelUnitLengthXCurrentValue(), kernelUnitLengthYCurrentValue()));
+        return convolveMatrix->setKernelUnitLength(FloatPoint(kernelUnitLengthX()->currentValue()->value(), kernelUnitLengthY()->currentValue()->value()));
     if (attrName == SVGNames::preserveAlphaAttr)
-        return convolveMatrix->setPreserveAlpha(preserveAlphaCurrentValue());
+        return convolveMatrix->setPreserveAlpha(m_preserveAlpha->currentValue()->value());
 
     ASSERT_NOT_REACHED();
     return false;
 }
 
-void SVGFEConvolveMatrixElement::setOrder(float x, float y)
-{
-    setOrderXBaseValue(x);
-    setOrderYBaseValue(y);
-    invalidate();
-}
-
-void SVGFEConvolveMatrixElement::setKernelUnitLength(float x, float y)
-{
-    setKernelUnitLengthXBaseValue(x);
-    setKernelUnitLengthYBaseValue(y);
-    invalidate();
-}
-
 void SVGFEConvolveMatrixElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
@@ -283,13 +193,13 @@
 
 PassRefPtr<FilterEffect> SVGFEConvolveMatrixElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
 
     if (!input1)
         return 0;
 
-    int orderXValue = orderXCurrentValue();
-    int orderYValue = orderYCurrentValue();
+    int orderXValue = orderX()->currentValue()->value();
+    int orderYValue = orderY()->currentValue()->value();
     if (!hasAttribute(SVGNames::orderAttr)) {
         orderXValue = 3;
         orderYValue = 3;
@@ -297,14 +207,14 @@
     // Spec says order must be > 0. Bail if it is not.
     if (orderXValue < 1 || orderYValue < 1)
         return 0;
-    SVGNumberList& kernelMatrix = this->kernelMatrixCurrentValue();
-    int kernelMatrixSize = kernelMatrix.size();
+    RefPtr<SVGNumberList> kernelMatrix = this->m_kernelMatrix->currentValue();
+    size_t kernelMatrixSize = kernelMatrix->numberOfItems();
     // The spec says this is a requirement, and should bail out if fails
-    if (orderXValue * orderYValue != kernelMatrixSize)
+    if (orderXValue * orderYValue != static_cast<int>(kernelMatrixSize))
         return 0;
 
-    int targetXValue = targetXCurrentValue();
-    int targetYValue = targetYCurrentValue();
+    int targetXValue = m_targetX->currentValue()->value();
+    int targetYValue = m_targetY->currentValue()->value();
     if (hasAttribute(SVGNames::targetXAttr) && (targetXValue < 0 || targetXValue >= orderXValue))
         return 0;
     // The spec says the default value is: targetX = floor ( orderX / 2 ))
@@ -317,8 +227,9 @@
         targetYValue = static_cast<int>(floorf(orderYValue / 2));
 
     // Spec says default kernelUnitLength is 1.0, and a specified length cannot be 0.
-    int kernelUnitLengthXValue = kernelUnitLengthXCurrentValue();
-    int kernelUnitLengthYValue = kernelUnitLengthYCurrentValue();
+    // FIXME: Why is this cast from float -> int -> float?
+    int kernelUnitLengthXValue = kernelUnitLengthX()->currentValue()->value();
+    int kernelUnitLengthYValue = kernelUnitLengthY()->currentValue()->value();
     if (!hasAttribute(SVGNames::kernelUnitLengthAttr)) {
         kernelUnitLengthXValue = 1;
         kernelUnitLengthYValue = 1;
@@ -326,20 +237,20 @@
     if (kernelUnitLengthXValue <= 0 || kernelUnitLengthYValue <= 0)
         return 0;
 
-    float divisorValue = divisorCurrentValue();
+    float divisorValue = m_divisor->currentValue()->value();
     if (hasAttribute(SVGNames::divisorAttr) && !divisorValue)
         return 0;
     if (!hasAttribute(SVGNames::divisorAttr)) {
-        for (int i = 0; i < kernelMatrixSize; ++i)
-            divisorValue += kernelMatrix.at(i).value();
+        for (size_t i = 0; i < kernelMatrixSize; ++i)
+            divisorValue += kernelMatrix->at(i)->value();
         if (!divisorValue)
             divisorValue = 1;
     }
 
     RefPtr<FilterEffect> effect = FEConvolveMatrix::create(filter,
                     IntSize(orderXValue, orderYValue), divisorValue,
-                    biasCurrentValue(), IntPoint(targetXValue, targetYValue), edgeModeCurrentValue(),
-                    FloatPoint(kernelUnitLengthXValue, kernelUnitLengthYValue), preserveAlphaCurrentValue(), kernelMatrix.toFloatVector());
+                    m_bias->currentValue()->value(), IntPoint(targetXValue, targetYValue), edgeModeCurrentValue(),
+                    FloatPoint(kernelUnitLengthXValue, kernelUnitLengthYValue), m_preserveAlpha->currentValue()->value(), m_kernelMatrix->currentValue()->toFloatVector());
     effect->inputEffects().append(input1);
     return effect.release();
 }
diff --git a/Source/core/svg/SVGFEConvolveMatrixElement.h b/Source/core/svg/SVGFEConvolveMatrixElement.h
index 4bc21ab..fab9faf 100644
--- a/Source/core/svg/SVGFEConvolveMatrixElement.h
+++ b/Source/core/svg/SVGFEConvolveMatrixElement.h
@@ -23,8 +23,10 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedInteger.h"
+#include "core/svg/SVGAnimatedIntegerOptionalInteger.h"
 #include "core/svg/SVGAnimatedNumber.h"
 #include "core/svg/SVGAnimatedNumberList.h"
+#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "platform/graphics/filters/FEConvolveMatrix.h"
 
@@ -67,36 +69,38 @@
 public:
     static PassRefPtr<SVGFEConvolveMatrixElement> create(Document&);
 
-    void setOrder(float orderX, float orderY);
-    void setKernelUnitLength(float kernelUnitLengthX, float kernelUnitLengthY);
+    SVGAnimatedBoolean* preserveAlpha() { return m_preserveAlpha.get(); }
+    SVGAnimatedNumber* divisor() { return m_divisor.get(); }
+    SVGAnimatedNumber* bias() { return m_bias.get(); }
+    SVGAnimatedNumber* kernelUnitLengthX() { return m_kernelUnitLength->firstNumber(); }
+    SVGAnimatedNumber* kernelUnitLengthY() { return m_kernelUnitLength->secondNumber(); }
+    SVGAnimatedNumberList* kernelMatrix() { return m_kernelMatrix.get(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
+    SVGAnimatedInteger* orderX() { return m_order->firstInteger(); }
+    SVGAnimatedInteger* orderY() { return m_order->secondInteger(); }
+    SVGAnimatedInteger* targetX() { return m_targetX.get(); }
+    SVGAnimatedInteger* targetY() { return m_targetY.get(); }
 
 private:
     explicit SVGFEConvolveMatrixElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&);
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&) OVERRIDE;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
-    static const AtomicString& orderXIdentifier();
-    static const AtomicString& orderYIdentifier();
-    static const AtomicString& kernelUnitLengthXIdentifier();
-    static const AtomicString& kernelUnitLengthYIdentifier();
-
+    RefPtr<SVGAnimatedNumber> m_bias;
+    RefPtr<SVGAnimatedNumber> m_divisor;
+    RefPtr<SVGAnimatedString> m_in1;
+    RefPtr<SVGAnimatedNumberList> m_kernelMatrix;
+    RefPtr<SVGAnimatedNumberOptionalNumber> m_kernelUnitLength;
+    RefPtr<SVGAnimatedIntegerOptionalInteger> m_order;
+    RefPtr<SVGAnimatedBoolean> m_preserveAlpha;
+    RefPtr<SVGAnimatedInteger> m_targetX;
+    RefPtr<SVGAnimatedInteger> m_targetY;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEConvolveMatrixElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
-        DECLARE_ANIMATED_INTEGER(OrderX, orderX)
-        DECLARE_ANIMATED_INTEGER(OrderY, orderY)
-        DECLARE_ANIMATED_NUMBER_LIST(KernelMatrix, kernelMatrix)
-        DECLARE_ANIMATED_NUMBER(Divisor, divisor)
-        DECLARE_ANIMATED_NUMBER(Bias, bias)
-        DECLARE_ANIMATED_INTEGER(TargetX, targetX)
-        DECLARE_ANIMATED_INTEGER(TargetY, targetY)
         DECLARE_ANIMATED_ENUMERATION(EdgeMode, edgeMode, EdgeModeType)
-        DECLARE_ANIMATED_NUMBER(KernelUnitLengthX, kernelUnitLengthX)
-        DECLARE_ANIMATED_NUMBER(KernelUnitLengthY, kernelUnitLengthY)
-        DECLARE_ANIMATED_BOOLEAN(PreserveAlpha, preserveAlpha)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEDiffuseLightingElement.cpp b/Source/core/svg/SVGFEDiffuseLightingElement.cpp
index 9d18e3c..328ad94 100644
--- a/Source/core/svg/SVGFEDiffuseLightingElement.cpp
+++ b/Source/core/svg/SVGFEDiffuseLightingElement.cpp
@@ -31,27 +31,24 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEDiffuseLightingElement, SVGNames::inAttr, In1, in1)
-DEFINE_ANIMATED_NUMBER(SVGFEDiffuseLightingElement, SVGNames::diffuseConstantAttr, DiffuseConstant, diffuseConstant)
-DEFINE_ANIMATED_NUMBER(SVGFEDiffuseLightingElement, SVGNames::surfaceScaleAttr, SurfaceScale, surfaceScale)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEDiffuseLightingElement, SVGNames::kernelUnitLengthAttr, kernelUnitLengthXIdentifier(), KernelUnitLengthX, kernelUnitLengthX)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEDiffuseLightingElement, SVGNames::kernelUnitLengthAttr, kernelUnitLengthYIdentifier(), KernelUnitLengthY, kernelUnitLengthY)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEDiffuseLightingElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(diffuseConstant)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(surfaceScale)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(kernelUnitLengthX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(kernelUnitLengthY)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feDiffuseLightingTag, document)
-    , m_diffuseConstant(1)
-    , m_surfaceScale(1)
+    , m_diffuseConstant(SVGAnimatedNumber::create(this, SVGNames::diffuseConstantAttr, SVGNumber::create(1)))
+    , m_surfaceScale(SVGAnimatedNumber::create(this, SVGNames::surfaceScaleAttr, SVGNumber::create(1)))
+    , m_kernelUnitLength(SVGAnimatedNumberOptionalNumber::create(this, SVGNames::kernelUnitLengthAttr))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_diffuseConstant);
+    addToPropertyMap(m_surfaceScale);
+    addToPropertyMap(m_kernelUnitLength);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFEDiffuseLightingElement();
 }
 
@@ -60,18 +57,6 @@
     return adoptRef(new SVGFEDiffuseLightingElement(document));
 }
 
-const AtomicString& SVGFEDiffuseLightingElement::kernelUnitLengthXIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGKernelUnitLengthX", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGFEDiffuseLightingElement::kernelUnitLengthYIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGKernelUnitLengthY", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
 bool SVGFEDiffuseLightingElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
@@ -92,31 +77,20 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::surfaceScaleAttr) {
-        setSurfaceScaleBaseValue(value.toFloat());
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::diffuseConstantAttr)
+        m_diffuseConstant->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::surfaceScaleAttr)
+        m_surfaceScale->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::kernelUnitLengthAttr)
+        m_kernelUnitLength->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::diffuseConstantAttr) {
-        setDiffuseConstantBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::kernelUnitLengthAttr) {
-        float x, y;
-        if (parseNumberOptionalNumber(value, x, y)) {
-            setKernelUnitLengthXBaseValue(x);
-            setKernelUnitLengthYBaseValue(y);
-        }
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 bool SVGFEDiffuseLightingElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
@@ -130,9 +104,9 @@
         return diffuseLighting->setLightingColor(renderer->style()->svgStyle()->lightingColor());
     }
     if (attrName == SVGNames::surfaceScaleAttr)
-        return diffuseLighting->setSurfaceScale(surfaceScaleCurrentValue());
+        return diffuseLighting->setSurfaceScale(m_surfaceScale->currentValue()->value());
     if (attrName == SVGNames::diffuseConstantAttr)
-        return diffuseLighting->setDiffuseConstant(diffuseConstantCurrentValue());
+        return diffuseLighting->setDiffuseConstant(m_diffuseConstant->currentValue()->value());
 
     LightSource* lightSource = const_cast<LightSource*>(diffuseLighting->lightSource());
     const SVGFELightElement* lightElement = SVGFELightElement::findLightElement(this);
@@ -140,25 +114,25 @@
     ASSERT(lightElement);
 
     if (attrName == SVGNames::azimuthAttr)
-        return lightSource->setAzimuth(lightElement->azimuthCurrentValue());
+        return lightSource->setAzimuth(lightElement->azimuth()->currentValue()->value());
     if (attrName == SVGNames::elevationAttr)
-        return lightSource->setElevation(lightElement->elevationCurrentValue());
+        return lightSource->setElevation(lightElement->elevation()->currentValue()->value());
     if (attrName == SVGNames::xAttr)
-        return lightSource->setX(lightElement->xCurrentValue());
+        return lightSource->setX(lightElement->x()->currentValue()->value());
     if (attrName == SVGNames::yAttr)
-        return lightSource->setY(lightElement->yCurrentValue());
+        return lightSource->setY(lightElement->y()->currentValue()->value());
     if (attrName == SVGNames::zAttr)
-        return lightSource->setZ(lightElement->zCurrentValue());
+        return lightSource->setZ(lightElement->z()->currentValue()->value());
     if (attrName == SVGNames::pointsAtXAttr)
-        return lightSource->setPointsAtX(lightElement->pointsAtXCurrentValue());
+        return lightSource->setPointsAtX(lightElement->pointsAtX()->currentValue()->value());
     if (attrName == SVGNames::pointsAtYAttr)
-        return lightSource->setPointsAtY(lightElement->pointsAtYCurrentValue());
+        return lightSource->setPointsAtY(lightElement->pointsAtY()->currentValue()->value());
     if (attrName == SVGNames::pointsAtZAttr)
-        return lightSource->setPointsAtZ(lightElement->pointsAtZCurrentValue());
+        return lightSource->setPointsAtZ(lightElement->pointsAtZ()->currentValue()->value());
     if (attrName == SVGNames::specularExponentAttr)
-        return lightSource->setSpecularExponent(lightElement->specularExponentCurrentValue());
+        return lightSource->setSpecularExponent(lightElement->specularExponent()->currentValue()->value());
     if (attrName == SVGNames::limitingConeAngleAttr)
-        return lightSource->setLimitingConeAngle(lightElement->limitingConeAngleCurrentValue());
+        return lightSource->setLimitingConeAngle(lightElement->limitingConeAngle()->currentValue()->value());
 
     ASSERT_NOT_REACHED();
     return false;
@@ -200,7 +174,7 @@
 
 PassRefPtr<FilterEffect> SVGFEDiffuseLightingElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
 
     if (!input1)
         return 0;
@@ -216,8 +190,8 @@
     ASSERT(renderer->style());
     Color color = renderer->style()->svgStyle()->lightingColor();
 
-    RefPtr<FilterEffect> effect = FEDiffuseLighting::create(filter, color, surfaceScaleCurrentValue(), diffuseConstantCurrentValue(),
-        kernelUnitLengthXCurrentValue(), kernelUnitLengthYCurrentValue(), lightSource.release());
+    RefPtr<FilterEffect> effect = FEDiffuseLighting::create(filter, color, m_surfaceScale->currentValue()->value(), m_diffuseConstant->currentValue()->value(),
+        kernelUnitLengthX()->currentValue()->value(), kernelUnitLengthY()->currentValue()->value(), lightSource.release());
     effect->inputEffects().append(input1);
     return effect.release();
 }
diff --git a/Source/core/svg/SVGFEDiffuseLightingElement.h b/Source/core/svg/SVGFEDiffuseLightingElement.h
index c3cbbc4..8820206 100644
--- a/Source/core/svg/SVGFEDiffuseLightingElement.h
+++ b/Source/core/svg/SVGFEDiffuseLightingElement.h
@@ -23,6 +23,7 @@
 #define SVGFEDiffuseLightingElement_h
 
 #include "SVGNames.h"
+#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
 #include "core/svg/SVGFELightElement.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 
@@ -36,24 +37,26 @@
     static PassRefPtr<SVGFEDiffuseLightingElement> create(Document&);
     void lightElementAttributeChanged(const SVGFELightElement*, const QualifiedName&);
 
+    SVGAnimatedNumber* diffuseConstant() { return m_diffuseConstant.get(); }
+    SVGAnimatedNumber* surfaceScale() { return m_surfaceScale.get(); }
+    SVGAnimatedNumber* kernelUnitLengthX() { return m_kernelUnitLength->firstNumber(); }
+    SVGAnimatedNumber* kernelUnitLengthY() { return m_kernelUnitLength->secondNumber(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
+
 private:
     explicit SVGFEDiffuseLightingElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&);
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&) OVERRIDE;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
-    static const AtomicString& kernelUnitLengthXIdentifier();
-    static const AtomicString& kernelUnitLengthYIdentifier();
-
+    RefPtr<SVGAnimatedNumber> m_diffuseConstant;
+    RefPtr<SVGAnimatedNumber> m_surfaceScale;
+    RefPtr<SVGAnimatedNumberOptionalNumber> m_kernelUnitLength;
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEDiffuseLightingElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
-        DECLARE_ANIMATED_NUMBER(DiffuseConstant, diffuseConstant)
-        DECLARE_ANIMATED_NUMBER(SurfaceScale, surfaceScale)
-        DECLARE_ANIMATED_NUMBER(KernelUnitLengthX, kernelUnitLengthX)
-        DECLARE_ANIMATED_NUMBER(KernelUnitLengthY, kernelUnitLengthY)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEDisplacementMapElement.cpp b/Source/core/svg/SVGFEDisplacementMapElement.cpp
index 6aff75b..f01722d 100644
--- a/Source/core/svg/SVGFEDisplacementMapElement.cpp
+++ b/Source/core/svg/SVGFEDisplacementMapElement.cpp
@@ -29,27 +29,28 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEDisplacementMapElement, SVGNames::inAttr, In1, in1)
-DEFINE_ANIMATED_STRING(SVGFEDisplacementMapElement, SVGNames::in2Attr, In2, in2)
 DEFINE_ANIMATED_ENUMERATION(SVGFEDisplacementMapElement, SVGNames::xChannelSelectorAttr, XChannelSelector, xChannelSelector, ChannelSelectorType)
 DEFINE_ANIMATED_ENUMERATION(SVGFEDisplacementMapElement, SVGNames::yChannelSelectorAttr, YChannelSelector, yChannelSelector, ChannelSelectorType)
-DEFINE_ANIMATED_NUMBER(SVGFEDisplacementMapElement, SVGNames::scaleAttr, Scale, scale)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEDisplacementMapElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in2)
     REGISTER_LOCAL_ANIMATED_PROPERTY(xChannelSelector)
     REGISTER_LOCAL_ANIMATED_PROPERTY(yChannelSelector)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(scale)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feDisplacementMapTag, document)
+    , m_scale(SVGAnimatedNumber::create(this, SVGNames::scaleAttr, SVGNumber::create(0)))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
+    , m_in2(SVGAnimatedString::create(this, SVGNames::in2Attr, SVGString::create()))
     , m_xChannelSelector(CHANNEL_A)
     , m_yChannelSelector(CHANNEL_A)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_scale);
+    addToPropertyMap(m_in1);
+    addToPropertyMap(m_in2);
     registerAnimatedPropertiesForSVGFEDisplacementMapElement();
 }
 
@@ -92,22 +93,18 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::in2Attr) {
-        setIn2BaseValue(value);
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::in2Attr)
+        m_in2->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::scaleAttr)
+        m_scale->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::scaleAttr) {
-        setScaleBaseValue(value.toFloat());
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 bool SVGFEDisplacementMapElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
@@ -118,7 +115,7 @@
     if (attrName == SVGNames::yChannelSelectorAttr)
         return displacementMap->setYChannelSelector(yChannelSelectorCurrentValue());
     if (attrName == SVGNames::scaleAttr)
-        return displacementMap->setScale(scaleCurrentValue());
+        return displacementMap->setScale(m_scale->currentValue()->value());
 
     ASSERT_NOT_REACHED();
     return false;
@@ -148,13 +145,13 @@
 
 PassRefPtr<FilterEffect> SVGFEDisplacementMapElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
-    FilterEffect* input2 = filterBuilder->getEffectById(in2CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
+    FilterEffect* input2 = filterBuilder->getEffectById(AtomicString(m_in2->currentValue()->value()));
 
     if (!input1 || !input2)
         return 0;
 
-    RefPtr<FilterEffect> effect = FEDisplacementMap::create(filter, xChannelSelectorCurrentValue(), yChannelSelectorCurrentValue(), scaleCurrentValue());
+    RefPtr<FilterEffect> effect = FEDisplacementMap::create(filter, xChannelSelectorCurrentValue(), yChannelSelectorCurrentValue(), m_scale->currentValue()->value());
     FilterEffectVector& inputEffects = effect->inputEffects();
     inputEffects.reserveCapacity(2);
     inputEffects.append(input1);
diff --git a/Source/core/svg/SVGFEDisplacementMapElement.h b/Source/core/svg/SVGFEDisplacementMapElement.h
index cb0c707..79ff363 100644
--- a/Source/core/svg/SVGFEDisplacementMapElement.h
+++ b/Source/core/svg/SVGFEDisplacementMapElement.h
@@ -70,21 +70,25 @@
 
     static ChannelSelectorType stringToChannel(const String&);
 
+    SVGAnimatedNumber* scale() { return m_scale.get(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
+    SVGAnimatedString* in2() { return m_in2.get(); }
+
 private:
     SVGFEDisplacementMapElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName);
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName) OVERRIDE;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
+    RefPtr<SVGAnimatedNumber> m_scale;
+    RefPtr<SVGAnimatedString> m_in1;
+    RefPtr<SVGAnimatedString> m_in2;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEDisplacementMapElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
-        DECLARE_ANIMATED_STRING(In2, in2)
         DECLARE_ANIMATED_ENUMERATION(XChannelSelector, xChannelSelector, ChannelSelectorType)
         DECLARE_ANIMATED_ENUMERATION(YChannelSelector, yChannelSelector, ChannelSelectorType)
-        DECLARE_ANIMATED_NUMBER(Scale, scale)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEDistantLightElement.cpp b/Source/core/svg/SVGFEDistantLightElement.cpp
index f641868..a6c9803 100644
--- a/Source/core/svg/SVGFEDistantLightElement.cpp
+++ b/Source/core/svg/SVGFEDistantLightElement.cpp
@@ -38,7 +38,7 @@
 
 PassRefPtr<LightSource> SVGFEDistantLightElement::lightSource() const
 {
-    return DistantLightSource::create(azimuthCurrentValue(), elevationCurrentValue());
+    return DistantLightSource::create(azimuth()->currentValue()->value(), elevation()->currentValue()->value());
 }
 
 }
diff --git a/Source/core/svg/SVGFEDistantLightElement.h b/Source/core/svg/SVGFEDistantLightElement.h
index 8a50cc8..69a024a 100644
--- a/Source/core/svg/SVGFEDistantLightElement.h
+++ b/Source/core/svg/SVGFEDistantLightElement.h
@@ -31,7 +31,7 @@
 private:
     explicit SVGFEDistantLightElement(Document&);
 
-    virtual PassRefPtr<LightSource> lightSource() const;
+    virtual PassRefPtr<LightSource> lightSource() const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFEDropShadowElement.cpp b/Source/core/svg/SVGFEDropShadowElement.cpp
index 366eaf3..5d219c5 100644
--- a/Source/core/svg/SVGFEDropShadowElement.cpp
+++ b/Source/core/svg/SVGFEDropShadowElement.cpp
@@ -31,29 +31,24 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEDropShadowElement, SVGNames::inAttr, In1, in1)
-DEFINE_ANIMATED_NUMBER(SVGFEDropShadowElement, SVGNames::dxAttr, Dx, dx)
-DEFINE_ANIMATED_NUMBER(SVGFEDropShadowElement, SVGNames::dyAttr, Dy, dy)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEDropShadowElement, SVGNames::stdDeviationAttr, stdDeviationXIdentifier(), StdDeviationX, stdDeviationX)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEDropShadowElement, SVGNames::stdDeviationAttr, stdDeviationYIdentifier(), StdDeviationY, stdDeviationY)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEDropShadowElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(dx)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(dy)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(stdDeviationX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(stdDeviationY)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEDropShadowElement::SVGFEDropShadowElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feDropShadowTag, document)
-    , m_dx(2)
-    , m_dy(2)
-    , m_stdDeviationX(2)
-    , m_stdDeviationY(2)
+    , m_dx(SVGAnimatedNumber::create(this, SVGNames::dxAttr, SVGNumber::create(2)))
+    , m_dy(SVGAnimatedNumber::create(this, SVGNames::dyAttr, SVGNumber::create(2)))
+    , m_stdDeviation(SVGAnimatedNumberOptionalNumber::create(this, SVGNames::stdDeviationAttr, 2, 2))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_dx);
+    addToPropertyMap(m_dy);
+    addToPropertyMap(m_stdDeviation);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFEDropShadowElement();
 }
 
@@ -62,22 +57,10 @@
     return adoptRef(new SVGFEDropShadowElement(document));
 }
 
-const AtomicString& SVGFEDropShadowElement::stdDeviationXIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGStdDeviationX", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGFEDropShadowElement::stdDeviationYIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGStdDeviationY", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
 void SVGFEDropShadowElement::setStdDeviation(float x, float y)
 {
-    setStdDeviationXBaseValue(x);
-    setStdDeviationYBaseValue(y);
+    stdDeviationX()->baseValue()->setValue(x);
+    stdDeviationY()->baseValue()->setValue(y);
     invalidate();
 }
 
@@ -100,31 +83,20 @@
         return;
     }
 
-    if (name == SVGNames::stdDeviationAttr) {
-        float x, y;
-        if (parseNumberOptionalNumber(value, x, y)) {
-            setStdDeviationXBaseValue(x);
-            setStdDeviationYBaseValue(y);
-        }
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::dxAttr)
+        m_dx->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::dyAttr)
+        m_dy->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::stdDeviationAttr)
+        m_stdDeviation->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::dxAttr) {
-        setDxBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::dyAttr) {
-        setDyBaseValue(value.toFloat());
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGFEDropShadowElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -153,7 +125,7 @@
     if (!renderer)
         return 0;
 
-    if (stdDeviationXCurrentValue() < 0 || stdDeviationYCurrentValue() < 0)
+    if (stdDeviationX()->currentValue()->value() < 0 || stdDeviationY()->currentValue()->value() < 0)
         return 0;
 
     ASSERT(renderer->style());
@@ -162,11 +134,11 @@
     Color color = svgStyle->floodColor();
     float opacity = svgStyle->floodOpacity();
 
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
     if (!input1)
         return 0;
 
-    RefPtr<FilterEffect> effect = FEDropShadow::create(filter, stdDeviationXCurrentValue(), stdDeviationYCurrentValue(), dxCurrentValue(), dyCurrentValue(), color, opacity);
+    RefPtr<FilterEffect> effect = FEDropShadow::create(filter, stdDeviationX()->currentValue()->value(), stdDeviationY()->currentValue()->value(), m_dx->currentValue()->value(), m_dy->currentValue()->value(), color, opacity);
     effect->inputEffects().append(input1);
     return effect.release();
 }
diff --git a/Source/core/svg/SVGFEDropShadowElement.h b/Source/core/svg/SVGFEDropShadowElement.h
index 2b48d76..c3f9d0e 100644
--- a/Source/core/svg/SVGFEDropShadowElement.h
+++ b/Source/core/svg/SVGFEDropShadowElement.h
@@ -21,6 +21,7 @@
 #define SVGFEDropShadowElement_h
 
 #include "core/svg/SVGAnimatedNumber.h"
+#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "platform/graphics/filters/FEDropShadow.h"
 
@@ -32,23 +33,28 @@
 
     void setStdDeviation(float stdDeviationX, float stdDeviationY);
 
+    SVGAnimatedNumber* dx() { return m_dx.get(); }
+    SVGAnimatedNumber* dy() { return m_dy.get(); }
+    SVGAnimatedNumber* stdDeviationX() { return m_stdDeviation->firstNumber(); }
+    SVGAnimatedNumber* stdDeviationY() { return m_stdDeviation->secondNumber(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
+
 private:
     explicit SVGFEDropShadowElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
     static const AtomicString& stdDeviationXIdentifier();
     static const AtomicString& stdDeviationYIdentifier();
 
+    RefPtr<SVGAnimatedNumber> m_dx;
+    RefPtr<SVGAnimatedNumber> m_dy;
+    RefPtr<SVGAnimatedNumberOptionalNumber> m_stdDeviation;
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEDropShadowElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
-        DECLARE_ANIMATED_NUMBER(Dx, dx)
-        DECLARE_ANIMATED_NUMBER(Dy, dy)
-        DECLARE_ANIMATED_NUMBER(StdDeviationX, stdDeviationX)
-        DECLARE_ANIMATED_NUMBER(StdDeviationY, stdDeviationY)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEFloodElement.h b/Source/core/svg/SVGFEFloodElement.h
index 4fa91b6..aff8c9f 100644
--- a/Source/core/svg/SVGFEFloodElement.h
+++ b/Source/core/svg/SVGFEFloodElement.h
@@ -33,8 +33,8 @@
 private:
     explicit SVGFEFloodElement(Document&);
 
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFEGaussianBlurElement.cpp b/Source/core/svg/SVGFEGaussianBlurElement.cpp
index 75cadff..35b3892 100644
--- a/Source/core/svg/SVGFEGaussianBlurElement.cpp
+++ b/Source/core/svg/SVGFEGaussianBlurElement.cpp
@@ -31,21 +31,20 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEGaussianBlurElement, SVGNames::inAttr, In1, in1)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEGaussianBlurElement, SVGNames::stdDeviationAttr, stdDeviationXIdentifier(), StdDeviationX, stdDeviationX)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEGaussianBlurElement, SVGNames::stdDeviationAttr, stdDeviationYIdentifier(), StdDeviationY, stdDeviationY)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEGaussianBlurElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(stdDeviationX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(stdDeviationY)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEGaussianBlurElement::SVGFEGaussianBlurElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feGaussianBlurTag, document)
+    , m_stdDeviation(SVGAnimatedNumberOptionalNumber::create(this, SVGNames::stdDeviationAttr, 0, 0))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_stdDeviation);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFEGaussianBlurElement();
 }
 
@@ -54,22 +53,10 @@
     return adoptRef(new SVGFEGaussianBlurElement(document));
 }
 
-const AtomicString& SVGFEGaussianBlurElement::stdDeviationXIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGStdDeviationX", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGFEGaussianBlurElement::stdDeviationYIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGStdDeviationY", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
 void SVGFEGaussianBlurElement::setStdDeviation(float x, float y)
 {
-    setStdDeviationXBaseValue(x);
-    setStdDeviationYBaseValue(y);
+    stdDeviationX()->baseValue()->setValue(x);
+    stdDeviationY()->baseValue()->setValue(y);
     invalidate();
 }
 
@@ -90,21 +77,16 @@
         return;
     }
 
-    if (name == SVGNames::stdDeviationAttr) {
-        float x, y;
-        if (parseNumberOptionalNumber(value, x, y)) {
-            setStdDeviationXBaseValue(x);
-            setStdDeviationYBaseValue(y);
-        }
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::stdDeviationAttr)
+        m_stdDeviation->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGFEGaussianBlurElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -126,15 +108,15 @@
 
 PassRefPtr<FilterEffect> SVGFEGaussianBlurElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
 
     if (!input1)
         return 0;
 
-    if (stdDeviationXCurrentValue() < 0 || stdDeviationYCurrentValue() < 0)
+    if (stdDeviationX()->currentValue()->value() < 0 || stdDeviationY()->currentValue()->value() < 0)
         return 0;
 
-    RefPtr<FilterEffect> effect = FEGaussianBlur::create(filter, stdDeviationXCurrentValue(), stdDeviationYCurrentValue());
+    RefPtr<FilterEffect> effect = FEGaussianBlur::create(filter, stdDeviationX()->currentValue()->value(), stdDeviationY()->currentValue()->value());
     effect->inputEffects().append(input1);
     return effect.release();
 }
diff --git a/Source/core/svg/SVGFEGaussianBlurElement.h b/Source/core/svg/SVGFEGaussianBlurElement.h
index 16b456b..063a644 100644
--- a/Source/core/svg/SVGFEGaussianBlurElement.h
+++ b/Source/core/svg/SVGFEGaussianBlurElement.h
@@ -21,7 +21,7 @@
 #ifndef SVGFEGaussianBlurElement_h
 #define SVGFEGaussianBlurElement_h
 
-#include "core/svg/SVGAnimatedNumber.h"
+#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "platform/graphics/filters/FEGaussianBlur.h"
 
@@ -33,21 +33,21 @@
 
     void setStdDeviation(float stdDeviationX, float stdDeviationY);
 
+    SVGAnimatedNumber* stdDeviationX() { return m_stdDeviation->firstNumber(); }
+    SVGAnimatedNumber* stdDeviationY() { return m_stdDeviation->secondNumber(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
+
 private:
     explicit SVGFEGaussianBlurElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
-    static const AtomicString& stdDeviationXIdentifier();
-    static const AtomicString& stdDeviationYIdentifier();
-
+    RefPtr<SVGAnimatedNumberOptionalNumber> m_stdDeviation;
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEGaussianBlurElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
-        DECLARE_ANIMATED_NUMBER(StdDeviationX, stdDeviationX)
-        DECLARE_ANIMATED_NUMBER(StdDeviationY, stdDeviationY)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEImageElement.cpp b/Source/core/svg/SVGFEImageElement.cpp
index b886a50..910af30 100644
--- a/Source/core/svg/SVGFEImageElement.cpp
+++ b/Source/core/svg/SVGFEImageElement.cpp
@@ -35,21 +35,18 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_PRESERVEASPECTRATIO(SVGFEImageElement, SVGNames::preserveAspectRatioAttr, PreserveAspectRatio, preserveAspectRatio)
-DEFINE_ANIMATED_STRING(SVGFEImageElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGFEImageElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEImageElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAspectRatio)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEImageElement::SVGFEImageElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feImageTag, document)
+    , SVGURIReference(this)
+    , m_preserveAspectRatio(SVGAnimatedPreserveAspectRatio::create(this, SVGNames::preserveAspectRatioAttr, SVGPreserveAspectRatio::create()))
 {
     ScriptWrappable::init(this);
+    addToPropertyMap(m_preserveAspectRatio);
     registerAnimatedPropertiesForSVGFEImageElement();
 }
 
@@ -83,7 +80,7 @@
 
 void SVGFEImageElement::fetchImageResource()
 {
-    FetchRequest request(ResourceRequest(ownerDocument()->completeURL(hrefCurrentValue())), localName());
+    FetchRequest request(ResourceRequest(ownerDocument()->completeURL(hrefString())), localName());
     m_cachedImage = document().fetcher()->fetchImage(request);
 
     if (m_cachedImage)
@@ -96,8 +93,8 @@
     if (!inDocument())
         return;
 
-    String id;
-    Element* target = SVGURIReference::targetElementFromIRIString(hrefCurrentValue(), document(), &id);
+    AtomicString id;
+    Element* target = SVGURIReference::targetElementFromIRIString(hrefString(), document(), &id);
     if (!target) {
         if (id.isEmpty())
             fetchImageResource();
@@ -119,7 +116,6 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGURIReference::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::preserveAspectRatioAttr);
     }
     return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
@@ -132,19 +128,16 @@
         return;
     }
 
+    SVGParsingError parseError = NoError;
+
     if (name == SVGNames::preserveAspectRatioAttr) {
-        SVGPreserveAspectRatio preserveAspectRatio;
-        preserveAspectRatio.parse(value);
-        setPreserveAspectRatioBaseValue(preserveAspectRatio);
-        return;
+        m_preserveAspectRatio->setBaseValueAsString(value, parseError);
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else {
+        ASSERT_NOT_REACHED();
     }
 
-    if (SVGURIReference::parseAttribute(name, value))
-        return;
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGFEImageElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -166,9 +159,6 @@
         return;
     }
 
-    if (SVGExternalResourcesRequired::isKnownAttribute(attrName))
-        return;
-
     ASSERT_NOT_REACHED();
 }
 
@@ -204,15 +194,8 @@
 PassRefPtr<FilterEffect> SVGFEImageElement::build(SVGFilterBuilder*, Filter* filter)
 {
     if (m_cachedImage)
-        return FEImage::createWithImage(filter, m_cachedImage->imageForRenderer(renderer()), preserveAspectRatioCurrentValue());
-    return FEImage::createWithIRIReference(filter, document(), hrefCurrentValue(), preserveAspectRatioCurrentValue());
-}
-
-void SVGFEImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    SVGFilterPrimitiveStandardAttributes::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
+        return FEImage::createWithImage(filter, m_cachedImage->imageForRenderer(renderer()), m_preserveAspectRatio->currentValue());
+    return FEImage::createWithIRIReference(filter, document(), hrefString(), m_preserveAspectRatio->currentValue());
 }
 
 }
diff --git a/Source/core/svg/SVGFEImageElement.h b/Source/core/svg/SVGFEImageElement.h
index 5e6bb04..9e3839b 100644
--- a/Source/core/svg/SVGFEImageElement.h
+++ b/Source/core/svg/SVGFEImageElement.h
@@ -26,7 +26,6 @@
 #include "core/fetch/ResourcePtr.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedPreserveAspectRatio.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "core/svg/SVGURIReference.h"
 #include "core/svg/graphics/filters/SVGFEImage.h"
@@ -36,7 +35,6 @@
 
 class SVGFEImageElement FINAL : public SVGFilterPrimitiveStandardAttributes,
                                 public SVGURIReference,
-                                public SVGExternalResourcesRequired,
                                 public ImageResourceClient {
 public:
     static PassRefPtr<SVGFEImageElement> create(Document&);
@@ -44,29 +42,27 @@
     bool currentFrameHasSingleSecurityOrigin() const;
 
     virtual ~SVGFEImageElement();
+    SVGAnimatedPreserveAspectRatio* preserveAspectRatio() { return m_preserveAspectRatio.get(); }
 
 private:
     explicit SVGFEImageElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual void notifyFinished(Resource*);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual void notifyFinished(Resource*) OVERRIDE;
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
     void clearResourceReferences();
     void fetchImageResource();
 
-    virtual void buildPendingResource();
+    virtual void buildPendingResource() OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
+    RefPtr<SVGAnimatedPreserveAspectRatio> m_preserveAspectRatio;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEImageElement)
-        DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
     ResourcePtr<ImageResource> m_cachedImage;
diff --git a/Source/core/svg/SVGFEImageElement.idl b/Source/core/svg/SVGFEImageElement.idl
index 40e4191..7bbad83 100644
--- a/Source/core/svg/SVGFEImageElement.idl
+++ b/Source/core/svg/SVGFEImageElement.idl
@@ -27,7 +27,6 @@
     readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio;
 };
 
-SVGFEImageElement implements SVGExternalResourcesRequired;
 SVGFEImageElement implements SVGFilterPrimitiveStandardAttributes;
 SVGFEImageElement implements SVGURIReference;
 
diff --git a/Source/core/svg/SVGFELightElement.cpp b/Source/core/svg/SVGFELightElement.cpp
index 4429044..ffd590d 100644
--- a/Source/core/svg/SVGFELightElement.cpp
+++ b/Source/core/svg/SVGFELightElement.cpp
@@ -33,45 +33,40 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::azimuthAttr, Azimuth, azimuth)
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::elevationAttr, Elevation, elevation)
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::zAttr, Z, z)
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::pointsAtXAttr, PointsAtX, pointsAtX)
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::pointsAtYAttr, PointsAtY, pointsAtY)
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::pointsAtZAttr, PointsAtZ, pointsAtZ)
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::specularExponentAttr, SpecularExponent, specularExponent)
-DEFINE_ANIMATED_NUMBER(SVGFELightElement, SVGNames::limitingConeAngleAttr, LimitingConeAngle, limitingConeAngle)
-
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFELightElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(azimuth)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(elevation)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(z)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(pointsAtX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(pointsAtY)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(pointsAtZ)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(specularExponent)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(limitingConeAngle)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGFELightElement::SVGFELightElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
-    , m_specularExponent(1)
+    , m_azimuth(SVGAnimatedNumber::create(this, SVGNames::azimuthAttr, SVGNumber::create()))
+    , m_elevation(SVGAnimatedNumber::create(this, SVGNames::elevationAttr, SVGNumber::create()))
+    , m_x(SVGAnimatedNumber::create(this, SVGNames::xAttr, SVGNumber::create()))
+    , m_y(SVGAnimatedNumber::create(this, SVGNames::yAttr, SVGNumber::create()))
+    , m_z(SVGAnimatedNumber::create(this, SVGNames::zAttr, SVGNumber::create()))
+    , m_pointsAtX(SVGAnimatedNumber::create(this, SVGNames::pointsAtXAttr, SVGNumber::create()))
+    , m_pointsAtY(SVGAnimatedNumber::create(this, SVGNames::pointsAtYAttr, SVGNumber::create()))
+    , m_pointsAtZ(SVGAnimatedNumber::create(this, SVGNames::pointsAtZAttr, SVGNumber::create()))
+    , m_specularExponent(SVGAnimatedNumber::create(this, SVGNames::specularExponentAttr, SVGNumber::create(1)))
+    , m_limitingConeAngle(SVGAnimatedNumber::create(this, SVGNames::limitingConeAngleAttr, SVGNumber::create()))
 {
+    addToPropertyMap(m_azimuth);
+    addToPropertyMap(m_elevation);
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_z);
+    addToPropertyMap(m_pointsAtX);
+    addToPropertyMap(m_pointsAtY);
+    addToPropertyMap(m_pointsAtZ);
+    addToPropertyMap(m_specularExponent);
+    addToPropertyMap(m_limitingConeAngle);
     registerAnimatedPropertiesForSVGFELightElement();
 }
 
 SVGFELightElement* SVGFELightElement::findLightElement(const SVGElement* svgElement)
 {
     for (Node* node = svgElement->firstChild(); node; node = node->nextSibling()) {
-        if (node->hasTagName(SVGNames::feDistantLightTag)
-            || node->hasTagName(SVGNames::fePointLightTag)
-            || node->hasTagName(SVGNames::feSpotLightTag)) {
-            return static_cast<SVGFELightElement*>(node);
-        }
+        if (isSVGFELightElement(*node))
+            return toSVGFELightElement(node);
     }
     return 0;
 }
@@ -109,57 +104,32 @@
         return;
     }
 
-    if (name == SVGNames::azimuthAttr) {
-        setAzimuthBaseValue(value.toFloat());
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::elevationAttr) {
-        setElevationBaseValue(value.toFloat());
-        return;
-    }
+    if (name == SVGNames::azimuthAttr)
+        m_azimuth->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::elevationAttr)
+        m_elevation->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::xAttr)
+        m_x->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::yAttr)
+        m_y->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::zAttr)
+        m_z->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::pointsAtXAttr)
+        m_pointsAtX->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::pointsAtYAttr)
+        m_pointsAtY->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::pointsAtZAttr)
+        m_pointsAtZ->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::specularExponentAttr)
+        m_specularExponent->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::limitingConeAngleAttr)
+        m_limitingConeAngle->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::xAttr) {
-        setXBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::yAttr) {
-        setYBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::zAttr) {
-        setZBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::pointsAtXAttr) {
-        setPointsAtXBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::pointsAtYAttr) {
-        setPointsAtYBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::pointsAtZAttr) {
-        setPointsAtZBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::specularExponentAttr) {
-        setSpecularExponentBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::limitingConeAngleAttr) {
-        setLimitingConeAngleBaseValue(value.toFloat());
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGFELightElement::svgAttributeChanged(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFELightElement.h b/Source/core/svg/SVGFELightElement.h
index 4473ed3..a9837bc 100644
--- a/Source/core/svg/SVGFELightElement.h
+++ b/Source/core/svg/SVGFELightElement.h
@@ -22,6 +22,7 @@
 #ifndef SVGFELightElement_h
 #define SVGFELightElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedNumber.h"
 #include "core/svg/SVGElement.h"
 #include "platform/graphics/filters/LightSource.h"
@@ -34,31 +35,59 @@
     static SVGFELightElement* findLightElement(const SVGElement*);
     static PassRefPtr<LightSource> findLightSource(const SVGElement*);
 
+    SVGAnimatedNumber* azimuth() { return m_azimuth.get(); }
+    const SVGAnimatedNumber* azimuth() const { return m_azimuth.get(); }
+    SVGAnimatedNumber* elevation() { return m_elevation.get(); }
+    const SVGAnimatedNumber* elevation() const { return m_elevation.get(); }
+    SVGAnimatedNumber* x() { return m_x.get(); }
+    const SVGAnimatedNumber* x() const { return m_x.get(); }
+    SVGAnimatedNumber* y() { return m_y.get(); }
+    const SVGAnimatedNumber* y() const { return m_y.get(); }
+    SVGAnimatedNumber* z() { return m_z.get(); }
+    const SVGAnimatedNumber* z() const { return m_z.get(); }
+    SVGAnimatedNumber* pointsAtX() { return m_pointsAtX.get(); }
+    const SVGAnimatedNumber* pointsAtX() const { return m_pointsAtX.get(); }
+    SVGAnimatedNumber* pointsAtY() { return m_pointsAtY.get(); }
+    const SVGAnimatedNumber* pointsAtY() const { return m_pointsAtY.get(); }
+    SVGAnimatedNumber* pointsAtZ() { return m_pointsAtZ.get(); }
+    const SVGAnimatedNumber* pointsAtZ() const { return m_pointsAtZ.get(); }
+    SVGAnimatedNumber* specularExponent() { return m_specularExponent.get(); }
+    const SVGAnimatedNumber* specularExponent() const { return m_specularExponent.get(); }
+    SVGAnimatedNumber* limitingConeAngle() { return m_limitingConeAngle.get(); }
+    const SVGAnimatedNumber* limitingConeAngle() const { return m_limitingConeAngle.get(); }
+
 protected:
     SVGFELightElement(const QualifiedName&, Document&);
 
 private:
     bool isSupportedAttribute(const QualifiedName&);
-    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE FINAL;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE FINAL;
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE FINAL;
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
+    RefPtr<SVGAnimatedNumber> m_azimuth;
+    RefPtr<SVGAnimatedNumber> m_elevation;
+    RefPtr<SVGAnimatedNumber> m_x;
+    RefPtr<SVGAnimatedNumber> m_y;
+    RefPtr<SVGAnimatedNumber> m_z;
+    RefPtr<SVGAnimatedNumber> m_pointsAtX;
+    RefPtr<SVGAnimatedNumber> m_pointsAtY;
+    RefPtr<SVGAnimatedNumber> m_pointsAtZ;
+    RefPtr<SVGAnimatedNumber> m_specularExponent;
+    RefPtr<SVGAnimatedNumber> m_limitingConeAngle;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFELightElement)
-        DECLARE_ANIMATED_NUMBER(Azimuth, azimuth)
-        DECLARE_ANIMATED_NUMBER(Elevation, elevation)
-        DECLARE_ANIMATED_NUMBER(X, x)
-        DECLARE_ANIMATED_NUMBER(Y, y)
-        DECLARE_ANIMATED_NUMBER(Z, z)
-        DECLARE_ANIMATED_NUMBER(PointsAtX, pointsAtX)
-        DECLARE_ANIMATED_NUMBER(PointsAtY, pointsAtY)
-        DECLARE_ANIMATED_NUMBER(PointsAtZ, pointsAtZ)
-        DECLARE_ANIMATED_NUMBER(SpecularExponent, specularExponent)
-        DECLARE_ANIMATED_NUMBER(LimitingConeAngle, limitingConeAngle)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline bool isSVGFELightElement(const Node& node)
+{
+    return node.hasTagName(SVGNames::feDistantLightTag) || node.hasTagName(SVGNames::fePointLightTag) || node.hasTagName(SVGNames::feSpotLightTag);
+}
+
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGFELightElement);
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFEMergeElement.cpp b/Source/core/svg/SVGFEMergeElement.cpp
index e1cf2db..e400149 100644
--- a/Source/core/svg/SVGFEMergeElement.cpp
+++ b/Source/core/svg/SVGFEMergeElement.cpp
@@ -46,7 +46,7 @@
     FilterEffectVector& mergeInputs = effect->inputEffects();
     for (Node* node = firstChild(); node; node = node->nextSibling()) {
         if (node->hasTagName(SVGNames::feMergeNodeTag)) {
-            FilterEffect* mergeEffect = filterBuilder->getEffectById(toSVGFEMergeNodeElement(node)->in1CurrentValue());
+            FilterEffect* mergeEffect = filterBuilder->getEffectById(AtomicString(toSVGFEMergeNodeElement(node)->in1()->currentValue()->value()));
             if (!mergeEffect)
                 return 0;
             mergeInputs.append(mergeEffect);
diff --git a/Source/core/svg/SVGFEMergeElement.h b/Source/core/svg/SVGFEMergeElement.h
index 9fae4a9..9237b05 100644
--- a/Source/core/svg/SVGFEMergeElement.h
+++ b/Source/core/svg/SVGFEMergeElement.h
@@ -33,7 +33,7 @@
 private:
     explicit SVGFEMergeElement(Document&);
 
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFEMergeNodeElement.cpp b/Source/core/svg/SVGFEMergeNodeElement.cpp
index 30df5a1..45e5b9b 100644
--- a/Source/core/svg/SVGFEMergeNodeElement.cpp
+++ b/Source/core/svg/SVGFEMergeNodeElement.cpp
@@ -28,16 +28,16 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEMergeNodeElement, SVGNames::inAttr, In1, in1)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEMergeNodeElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEMergeNodeElement::SVGFEMergeNodeElement(Document& document)
     : SVGElement(SVGNames::feMergeNodeTag, document)
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFEMergeNodeElement();
 }
 
@@ -61,12 +61,14 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    ASSERT_NOT_REACHED();
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
+
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGFEMergeNodeElement::svgAttributeChanged(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGFEMergeNodeElement.h b/Source/core/svg/SVGFEMergeNodeElement.h
index a076088..d928a07 100644
--- a/Source/core/svg/SVGFEMergeNodeElement.h
+++ b/Source/core/svg/SVGFEMergeNodeElement.h
@@ -30,18 +30,19 @@
 class SVGFEMergeNodeElement FINAL : public SVGElement {
 public:
     static PassRefPtr<SVGFEMergeNodeElement> create(Document&);
+    SVGAnimatedString* in1() { return m_in1.get(); }
 
 private:
     explicit SVGFEMergeNodeElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEMergeNodeElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEMorphologyElement.cpp b/Source/core/svg/SVGFEMorphologyElement.cpp
index 4f53858..c0ea10e 100644
--- a/Source/core/svg/SVGFEMorphologyElement.cpp
+++ b/Source/core/svg/SVGFEMorphologyElement.cpp
@@ -30,24 +30,23 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEMorphologyElement, SVGNames::inAttr, In1, in1)
 DEFINE_ANIMATED_ENUMERATION(SVGFEMorphologyElement, SVGNames::operatorAttr, SVGOperator, svgOperator, MorphologyOperatorType)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEMorphologyElement, SVGNames::radiusAttr, radiusXIdentifier(), RadiusX, radiusX)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEMorphologyElement, SVGNames::radiusAttr, radiusYIdentifier(), RadiusY, radiusY)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEMorphologyElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
     REGISTER_LOCAL_ANIMATED_PROPERTY(svgOperator)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(radiusX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(radiusY)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEMorphologyElement::SVGFEMorphologyElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feMorphologyTag, document)
+    , m_radius(SVGAnimatedNumberOptionalNumber::create(this, SVGNames::radiusAttr))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
     , m_svgOperator(FEMORPHOLOGY_OPERATOR_ERODE)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_radius);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFEMorphologyElement();
 }
 
@@ -56,22 +55,10 @@
     return adoptRef(new SVGFEMorphologyElement(document));
 }
 
-const AtomicString& SVGFEMorphologyElement::radiusXIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGRadiusX", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGFEMorphologyElement::radiusYIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGRadiusY", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
 void SVGFEMorphologyElement::setRadius(float x, float y)
 {
-    setRadiusXBaseValue(x);
-    setRadiusYBaseValue(y);
+    radiusX()->baseValue()->setValue(x);
+    radiusY()->baseValue()->setValue(y);
     invalidate();
 }
 
@@ -100,21 +87,16 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::radiusAttr) {
-        float x, y;
-        if (parseNumberOptionalNumber(value, x, y)) {
-            setRadiusXBaseValue(x);
-            setRadiusYBaseValue(y);
-        }
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::radiusAttr)
+        m_radius->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 bool SVGFEMorphologyElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
@@ -124,8 +106,8 @@
         return morphology->setMorphologyOperator(svgOperatorCurrentValue());
     if (attrName == SVGNames::radiusAttr) {
         // Both setRadius functions should be evaluated separately.
-        bool isRadiusXChanged = morphology->setRadiusX(radiusXCurrentValue());
-        bool isRadiusYChanged = morphology->setRadiusY(radiusYCurrentValue());
+        bool isRadiusXChanged = morphology->setRadiusX(radiusX()->currentValue()->value());
+        bool isRadiusYChanged = morphology->setRadiusY(radiusY()->currentValue()->value());
         return isRadiusXChanged || isRadiusYChanged;
     }
 
@@ -157,9 +139,9 @@
 
 PassRefPtr<FilterEffect> SVGFEMorphologyElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
-    float xRadius = radiusXCurrentValue();
-    float yRadius = radiusYCurrentValue();
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
+    float xRadius = radiusX()->currentValue()->value();
+    float yRadius = radiusY()->currentValue()->value();
 
     if (!input1)
         return 0;
diff --git a/Source/core/svg/SVGFEMorphologyElement.h b/Source/core/svg/SVGFEMorphologyElement.h
index 5462712..14591ba 100644
--- a/Source/core/svg/SVGFEMorphologyElement.h
+++ b/Source/core/svg/SVGFEMorphologyElement.h
@@ -21,7 +21,7 @@
 #define SVGFEMorphologyElement_h
 
 #include "core/svg/SVGAnimatedEnumeration.h"
-#include "core/svg/SVGAnimatedNumber.h"
+#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "platform/graphics/filters/FEMorphology.h"
 
@@ -62,23 +62,23 @@
 
     void setRadius(float radiusX, float radiusY);
 
+    SVGAnimatedNumber* radiusX() { return m_radius->firstNumber(); }
+    SVGAnimatedNumber* radiusY() { return m_radius->secondNumber(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
+
 private:
     explicit SVGFEMorphologyElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&);
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&) OVERRIDE;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
-    static const AtomicString& radiusXIdentifier();
-    static const AtomicString& radiusYIdentifier();
-
+    RefPtr<SVGAnimatedNumberOptionalNumber> m_radius;
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEMorphologyElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
         DECLARE_ANIMATED_ENUMERATION(SVGOperator, svgOperator, MorphologyOperatorType)
-        DECLARE_ANIMATED_NUMBER(RadiusX, radiusX)
-        DECLARE_ANIMATED_NUMBER(RadiusY, radiusY)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEOffsetElement.cpp b/Source/core/svg/SVGFEOffsetElement.cpp
index 7b29b59..585a9d4 100644
--- a/Source/core/svg/SVGFEOffsetElement.cpp
+++ b/Source/core/svg/SVGFEOffsetElement.cpp
@@ -30,21 +30,22 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFEOffsetElement, SVGNames::inAttr, In1, in1)
-DEFINE_ANIMATED_NUMBER(SVGFEOffsetElement, SVGNames::dxAttr, Dx, dx)
-DEFINE_ANIMATED_NUMBER(SVGFEOffsetElement, SVGNames::dyAttr, Dy, dy)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEOffsetElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(dx)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(dy)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFEOffsetElement::SVGFEOffsetElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feOffsetTag, document)
+    , m_dx(SVGAnimatedNumber::create(this, SVGNames::dxAttr, SVGNumber::create()))
+    , m_dy(SVGAnimatedNumber::create(this, SVGNames::dyAttr, SVGNumber::create()))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_dx);
+    addToPropertyMap(m_dy);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFEOffsetElement();
 }
 
@@ -71,22 +72,18 @@
         return;
     }
 
-    if (name == SVGNames::dxAttr) {
-        setDxBaseValue(value.toFloat());
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::dyAttr) {
-        setDyBaseValue(value.toFloat());
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::dxAttr)
+        m_dx->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::dyAttr)
+        m_dy->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGFEOffsetElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -108,12 +105,12 @@
 
 PassRefPtr<FilterEffect> SVGFEOffsetElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
 
     if (!input1)
         return 0;
 
-    RefPtr<FilterEffect> effect = FEOffset::create(filter, dxCurrentValue(), dyCurrentValue());
+    RefPtr<FilterEffect> effect = FEOffset::create(filter, m_dx->currentValue()->value(), m_dy->currentValue()->value());
     effect->inputEffects().append(input1);
     return effect.release();
 }
diff --git a/Source/core/svg/SVGFEOffsetElement.h b/Source/core/svg/SVGFEOffsetElement.h
index 7427864..4e7dba9 100644
--- a/Source/core/svg/SVGFEOffsetElement.h
+++ b/Source/core/svg/SVGFEOffsetElement.h
@@ -31,18 +31,21 @@
 public:
     static PassRefPtr<SVGFEOffsetElement> create(Document&);
 
+    SVGAnimatedNumber* dx() { return m_dx.get(); }
+    SVGAnimatedNumber* dy() { return m_dy.get(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
 private:
     explicit SVGFEOffsetElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
+    RefPtr<SVGAnimatedNumber> m_dx;
+    RefPtr<SVGAnimatedNumber> m_dy;
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEOffsetElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
-        DECLARE_ANIMATED_NUMBER(Dx, dx)
-        DECLARE_ANIMATED_NUMBER(Dy, dy)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFEPointLightElement.cpp b/Source/core/svg/SVGFEPointLightElement.cpp
index aba77a6..85055bd 100644
--- a/Source/core/svg/SVGFEPointLightElement.cpp
+++ b/Source/core/svg/SVGFEPointLightElement.cpp
@@ -38,7 +38,7 @@
 
 PassRefPtr<LightSource> SVGFEPointLightElement::lightSource() const
 {
-    return PointLightSource::create(FloatPoint3D(xCurrentValue(), yCurrentValue(), zCurrentValue()));
+    return PointLightSource::create(FloatPoint3D(x()->currentValue()->value(), y()->currentValue()->value(), z()->currentValue()->value()));
 }
 
 }
diff --git a/Source/core/svg/SVGFEPointLightElement.h b/Source/core/svg/SVGFEPointLightElement.h
index b32b951..1574aef 100644
--- a/Source/core/svg/SVGFEPointLightElement.h
+++ b/Source/core/svg/SVGFEPointLightElement.h
@@ -31,7 +31,7 @@
 private:
     explicit SVGFEPointLightElement(Document&);
 
-    virtual PassRefPtr<LightSource> lightSource() const;
+    virtual PassRefPtr<LightSource> lightSource() const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFESpecularLightingElement.cpp b/Source/core/svg/SVGFESpecularLightingElement.cpp
index eee1978..21782cf 100644
--- a/Source/core/svg/SVGFESpecularLightingElement.cpp
+++ b/Source/core/svg/SVGFESpecularLightingElement.cpp
@@ -32,30 +32,26 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFESpecularLightingElement, SVGNames::inAttr, In1, in1)
-DEFINE_ANIMATED_NUMBER(SVGFESpecularLightingElement, SVGNames::specularConstantAttr, SpecularConstant, specularConstant)
-DEFINE_ANIMATED_NUMBER(SVGFESpecularLightingElement, SVGNames::specularExponentAttr, SpecularExponent, specularExponent)
-DEFINE_ANIMATED_NUMBER(SVGFESpecularLightingElement, SVGNames::surfaceScaleAttr, SurfaceScale, surfaceScale)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFESpecularLightingElement, SVGNames::kernelUnitLengthAttr, kernelUnitLengthXIdentifier(), KernelUnitLengthX, kernelUnitLengthX)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFESpecularLightingElement, SVGNames::kernelUnitLengthAttr, kernelUnitLengthYIdentifier(), KernelUnitLengthY, kernelUnitLengthY)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFESpecularLightingElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(specularConstant)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(specularExponent)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(surfaceScale)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(kernelUnitLengthX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(kernelUnitLengthY)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFESpecularLightingElement::SVGFESpecularLightingElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feSpecularLightingTag, document)
-    , m_specularConstant(1)
-    , m_specularExponent(1)
-    , m_surfaceScale(1)
+    , m_specularConstant(SVGAnimatedNumber::create(this, SVGNames::specularConstantAttr, SVGNumber::create(1)))
+    , m_specularExponent(SVGAnimatedNumber::create(this, SVGNames::specularExponentAttr, SVGNumber::create(1)))
+    , m_surfaceScale(SVGAnimatedNumber::create(this, SVGNames::surfaceScaleAttr, SVGNumber::create(1)))
+    , m_kernelUnitLength(SVGAnimatedNumberOptionalNumber::create(this, SVGNames::surfaceScaleAttr))
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_specularConstant);
+    addToPropertyMap(m_specularExponent);
+    addToPropertyMap(m_surfaceScale);
+    addToPropertyMap(m_kernelUnitLength);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFESpecularLightingElement();
 }
 
@@ -64,18 +60,6 @@
     return adoptRef(new SVGFESpecularLightingElement(document));
 }
 
-const AtomicString& SVGFESpecularLightingElement::kernelUnitLengthXIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGKernelUnitLengthX", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGFESpecularLightingElement::kernelUnitLengthYIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGKernelUnitLengthY", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
 bool SVGFESpecularLightingElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
@@ -96,36 +80,22 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::surfaceScaleAttr) {
-        setSurfaceScaleBaseValue(value.toFloat());
-        return;
-    }
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::surfaceScaleAttr)
+        m_surfaceScale->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::specularConstantAttr)
+        m_specularConstant->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::specularExponentAttr)
+        m_specularExponent->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::kernelUnitLengthAttr)
+        m_kernelUnitLength->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::specularConstantAttr) {
-        setSpecularConstantBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::specularExponentAttr) {
-        setSpecularExponentBaseValue(value.toFloat());
-        return;
-    }
-
-    if (name == SVGNames::kernelUnitLengthAttr) {
-        float x, y;
-        if (parseNumberOptionalNumber(value, x, y)) {
-            setKernelUnitLengthXBaseValue(x);
-            setKernelUnitLengthYBaseValue(y);
-        }
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 bool SVGFESpecularLightingElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
@@ -139,37 +109,37 @@
         return specularLighting->setLightingColor(renderer->style()->svgStyle()->lightingColor());
     }
     if (attrName == SVGNames::surfaceScaleAttr)
-        return specularLighting->setSurfaceScale(surfaceScaleCurrentValue());
+        return specularLighting->setSurfaceScale(m_surfaceScale->currentValue()->value());
     if (attrName == SVGNames::specularConstantAttr)
-        return specularLighting->setSpecularConstant(specularConstantCurrentValue());
+        return specularLighting->setSpecularConstant(m_specularConstant->currentValue()->value());
     if (attrName == SVGNames::specularExponentAttr)
-        return specularLighting->setSpecularExponent(specularExponentCurrentValue());
+        return specularLighting->setSpecularExponent(m_specularExponent->currentValue()->value());
 
     LightSource* lightSource = const_cast<LightSource*>(specularLighting->lightSource());
-    const SVGFELightElement* lightElement = SVGFELightElement::findLightElement(this);
+    SVGFELightElement* lightElement = SVGFELightElement::findLightElement(this);
     ASSERT(lightSource);
     ASSERT(lightElement);
 
     if (attrName == SVGNames::azimuthAttr)
-        return lightSource->setAzimuth(lightElement->azimuthCurrentValue());
+        return lightSource->setAzimuth(lightElement->azimuth()->currentValue()->value());
     if (attrName == SVGNames::elevationAttr)
-        return lightSource->setElevation(lightElement->elevationCurrentValue());
+        return lightSource->setElevation(lightElement->elevation()->currentValue()->value());
     if (attrName == SVGNames::xAttr)
-        return lightSource->setX(lightElement->xCurrentValue());
+        return lightSource->setX(lightElement->x()->currentValue()->value());
     if (attrName == SVGNames::yAttr)
-        return lightSource->setY(lightElement->yCurrentValue());
+        return lightSource->setY(lightElement->y()->currentValue()->value());
     if (attrName == SVGNames::zAttr)
-        return lightSource->setZ(lightElement->zCurrentValue());
+        return lightSource->setZ(lightElement->z()->currentValue()->value());
     if (attrName == SVGNames::pointsAtXAttr)
-        return lightSource->setPointsAtX(lightElement->pointsAtXCurrentValue());
+        return lightSource->setPointsAtX(lightElement->pointsAtX()->currentValue()->value());
     if (attrName == SVGNames::pointsAtYAttr)
-        return lightSource->setPointsAtY(lightElement->pointsAtYCurrentValue());
+        return lightSource->setPointsAtY(lightElement->pointsAtY()->currentValue()->value());
     if (attrName == SVGNames::pointsAtZAttr)
-        return lightSource->setPointsAtZ(lightElement->pointsAtZCurrentValue());
+        return lightSource->setPointsAtZ(lightElement->pointsAtZ()->currentValue()->value());
     if (attrName == SVGNames::specularExponentAttr)
-        return lightSource->setSpecularExponent(lightElement->specularExponentCurrentValue());
+        return lightSource->setSpecularExponent(lightElement->specularExponent()->currentValue()->value());
     if (attrName == SVGNames::limitingConeAngleAttr)
-        return lightSource->setLimitingConeAngle(lightElement->limitingConeAngleCurrentValue());
+        return lightSource->setLimitingConeAngle(lightElement->limitingConeAngle()->currentValue()->value());
 
     ASSERT_NOT_REACHED();
     return false;
@@ -211,7 +181,7 @@
 
 PassRefPtr<FilterEffect> SVGFESpecularLightingElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
 
     if (!input1)
         return 0;
@@ -227,8 +197,8 @@
     ASSERT(renderer->style());
     Color color = renderer->style()->svgStyle()->lightingColor();
 
-    RefPtr<FilterEffect> effect = FESpecularLighting::create(filter, color, surfaceScaleCurrentValue(), specularConstantCurrentValue(),
-        specularExponentCurrentValue(), kernelUnitLengthXCurrentValue(), kernelUnitLengthYCurrentValue(), lightSource.release());
+    RefPtr<FilterEffect> effect = FESpecularLighting::create(filter, color, m_surfaceScale->currentValue()->value(), m_specularConstant->currentValue()->value(),
+        m_specularExponent->currentValue()->value(), kernelUnitLengthX()->currentValue()->value(), kernelUnitLengthY()->currentValue()->value(), lightSource.release());
     effect->inputEffects().append(input1);
     return effect.release();
 }
diff --git a/Source/core/svg/SVGFESpecularLightingElement.h b/Source/core/svg/SVGFESpecularLightingElement.h
index f76b161..c3b3367 100644
--- a/Source/core/svg/SVGFESpecularLightingElement.h
+++ b/Source/core/svg/SVGFESpecularLightingElement.h
@@ -24,6 +24,7 @@
 
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedNumber.h"
+#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
 #include "core/svg/SVGFELightElement.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "platform/graphics/filters/FESpecularLighting.h"
@@ -35,25 +36,30 @@
     static PassRefPtr<SVGFESpecularLightingElement> create(Document&);
     void lightElementAttributeChanged(const SVGFELightElement*, const QualifiedName&);
 
+    SVGAnimatedNumber* specularConstant() { return m_specularConstant.get(); }
+    SVGAnimatedNumber* specularExponent() { return m_specularExponent.get(); }
+    SVGAnimatedNumber* surfaceScale() { return m_surfaceScale.get(); }
+    SVGAnimatedNumber* kernelUnitLengthX() { return m_kernelUnitLength->firstNumber(); }
+    SVGAnimatedNumber* kernelUnitLengthY() { return m_kernelUnitLength->secondNumber(); }
+    SVGAnimatedString* in1() { return m_in1.get(); }
 private:
     explicit SVGFESpecularLightingElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&);
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&) OVERRIDE;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
     static const AtomicString& kernelUnitLengthXIdentifier();
     static const AtomicString& kernelUnitLengthYIdentifier();
 
+    RefPtr<SVGAnimatedNumber> m_specularConstant;
+    RefPtr<SVGAnimatedNumber> m_specularExponent;
+    RefPtr<SVGAnimatedNumber> m_surfaceScale;
+    RefPtr<SVGAnimatedNumberOptionalNumber> m_kernelUnitLength;
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFESpecularLightingElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
-        DECLARE_ANIMATED_NUMBER(SpecularConstant, specularConstant)
-        DECLARE_ANIMATED_NUMBER(SpecularExponent, specularExponent)
-        DECLARE_ANIMATED_NUMBER(SurfaceScale, surfaceScale)
-        DECLARE_ANIMATED_NUMBER(KernelUnitLengthX, kernelUnitLengthX)
-        DECLARE_ANIMATED_NUMBER(KernelUnitLengthY, kernelUnitLengthY)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFESpotLightElement.cpp b/Source/core/svg/SVGFESpotLightElement.cpp
index 2eafdb3..6ff8abc 100644
--- a/Source/core/svg/SVGFESpotLightElement.cpp
+++ b/Source/core/svg/SVGFESpotLightElement.cpp
@@ -38,10 +38,10 @@
 
 PassRefPtr<LightSource> SVGFESpotLightElement::lightSource() const
 {
-    FloatPoint3D pos(xCurrentValue(), yCurrentValue(), zCurrentValue());
-    FloatPoint3D direction(pointsAtXCurrentValue(), pointsAtYCurrentValue(), pointsAtZCurrentValue());
+    FloatPoint3D pos(x()->currentValue()->value(), y()->currentValue()->value(), z()->currentValue()->value());
+    FloatPoint3D direction(pointsAtX()->currentValue()->value(), pointsAtY()->currentValue()->value(), pointsAtZ()->currentValue()->value());
 
-    return SpotLightSource::create(pos, direction, specularExponentCurrentValue(), limitingConeAngleCurrentValue());
+    return SpotLightSource::create(pos, direction, specularExponent()->currentValue()->value(), limitingConeAngle()->currentValue()->value());
 }
 
 }
diff --git a/Source/core/svg/SVGFESpotLightElement.h b/Source/core/svg/SVGFESpotLightElement.h
index a36d762..9e84a2c 100644
--- a/Source/core/svg/SVGFESpotLightElement.h
+++ b/Source/core/svg/SVGFESpotLightElement.h
@@ -31,7 +31,7 @@
 private:
     explicit SVGFESpotLightElement(Document&);
 
-    virtual PassRefPtr<LightSource> lightSource() const;
+    virtual PassRefPtr<LightSource> lightSource() const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFETileElement.cpp b/Source/core/svg/SVGFETileElement.cpp
index f9833e8..ff8c0d7 100644
--- a/Source/core/svg/SVGFETileElement.cpp
+++ b/Source/core/svg/SVGFETileElement.cpp
@@ -30,17 +30,17 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGFETileElement, SVGNames::inAttr, In1, in1)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFETileElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFETileElement::SVGFETileElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feTileTag, document)
+    , m_in1(SVGAnimatedString::create(this, SVGNames::inAttr, SVGString::create()))
 {
     ScriptWrappable::init(this);
+    addToPropertyMap(m_in1);
     registerAnimatedPropertiesForSVGFETileElement();
 }
 
@@ -64,12 +64,14 @@
         return;
     }
 
-    if (name == SVGNames::inAttr) {
-        setIn1BaseValue(value);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    ASSERT_NOT_REACHED();
+    if (name == SVGNames::inAttr)
+        m_in1->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
+
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGFETileElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -91,7 +93,7 @@
 
 PassRefPtr<FilterEffect> SVGFETileElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
 {
-    FilterEffect* input1 = filterBuilder->getEffectById(in1CurrentValue());
+    FilterEffect* input1 = filterBuilder->getEffectById(AtomicString(m_in1->currentValue()->value()));
 
     if (!input1)
         return 0;
diff --git a/Source/core/svg/SVGFETileElement.h b/Source/core/svg/SVGFETileElement.h
index 0e605cd..9a5d109 100644
--- a/Source/core/svg/SVGFETileElement.h
+++ b/Source/core/svg/SVGFETileElement.h
@@ -29,17 +29,18 @@
 class SVGFETileElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
     static PassRefPtr<SVGFETileElement> create(Document&);
+    SVGAnimatedString* in1() { return m_in1.get(); }
 
 private:
     explicit SVGFETileElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
+    RefPtr<SVGAnimatedString> m_in1;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFETileElement)
-        DECLARE_ANIMATED_STRING(In1, in1)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFETurbulenceElement.cpp b/Source/core/svg/SVGFETurbulenceElement.cpp
index b020f0f..dfde8b5 100644
--- a/Source/core/svg/SVGFETurbulenceElement.cpp
+++ b/Source/core/svg/SVGFETurbulenceElement.cpp
@@ -29,18 +29,10 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFETurbulenceElement, SVGNames::baseFrequencyAttr, baseFrequencyXIdentifier(), BaseFrequencyX, baseFrequencyX)
-DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFETurbulenceElement, SVGNames::baseFrequencyAttr, baseFrequencyYIdentifier(), BaseFrequencyY, baseFrequencyY)
-DEFINE_ANIMATED_INTEGER(SVGFETurbulenceElement, SVGNames::numOctavesAttr, NumOctaves, numOctaves)
-DEFINE_ANIMATED_NUMBER(SVGFETurbulenceElement, SVGNames::seedAttr, Seed, seed)
 DEFINE_ANIMATED_ENUMERATION(SVGFETurbulenceElement, SVGNames::stitchTilesAttr, StitchTiles, stitchTiles, SVGStitchOptions)
 DEFINE_ANIMATED_ENUMERATION(SVGFETurbulenceElement, SVGNames::typeAttr, Type, type, TurbulenceType)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFETurbulenceElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(baseFrequencyX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(baseFrequencyY)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(numOctaves)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(seed)
     REGISTER_LOCAL_ANIMATED_PROPERTY(stitchTiles)
     REGISTER_LOCAL_ANIMATED_PROPERTY(type)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
@@ -48,11 +40,17 @@
 
 inline SVGFETurbulenceElement::SVGFETurbulenceElement(Document& document)
     : SVGFilterPrimitiveStandardAttributes(SVGNames::feTurbulenceTag, document)
-    , m_numOctaves(1)
+    , m_baseFrequency(SVGAnimatedNumberOptionalNumber::create(this, SVGNames::baseFrequencyAttr))
+    , m_seed(SVGAnimatedNumber::create(this, SVGNames::seedAttr, SVGNumber::create(0)))
+    , m_numOctaves(SVGAnimatedInteger::create(this, SVGNames::numOctavesAttr, SVGInteger::create(1)))
     , m_stitchTiles(SVG_STITCHTYPE_NOSTITCH)
     , m_type(FETURBULENCE_TYPE_TURBULENCE)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_baseFrequency);
+    addToPropertyMap(m_seed);
+    addToPropertyMap(m_numOctaves);
     registerAnimatedPropertiesForSVGFETurbulenceElement();
 }
 
@@ -61,18 +59,6 @@
     return adoptRef(new SVGFETurbulenceElement(document));
 }
 
-const AtomicString& SVGFETurbulenceElement::baseFrequencyXIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGBaseFrequencyX", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGFETurbulenceElement::baseFrequencyYIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGBaseFrequencyY", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
 bool SVGFETurbulenceElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
@@ -107,26 +93,18 @@
         return;
     }
 
-    if (name == SVGNames::baseFrequencyAttr) {
-        float x, y;
-        if (parseNumberOptionalNumber(value, x, y)) {
-            setBaseFrequencyXBaseValue(x);
-            setBaseFrequencyYBaseValue(y);
-        }
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::seedAttr) {
-        setSeedBaseValue(value.toFloat());
-        return;
-    }
+    if (name == SVGNames::baseFrequencyAttr)
+        m_baseFrequency->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::numOctavesAttr)
+        m_numOctaves->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::seedAttr)
+        m_seed->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::numOctavesAttr) {
-        setNumOctavesBaseValue(value.string().toUIntStrict());
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 bool SVGFETurbulenceElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
@@ -137,14 +115,14 @@
     if (attrName == SVGNames::stitchTilesAttr)
         return turbulence->setStitchTiles(stitchTilesCurrentValue());
     if (attrName == SVGNames::baseFrequencyAttr) {
-        bool baseFrequencyXChanged = turbulence->setBaseFrequencyX(baseFrequencyXCurrentValue());
-        bool baseFrequencyYChanged = turbulence->setBaseFrequencyY(baseFrequencyYCurrentValue());
+        bool baseFrequencyXChanged = turbulence->setBaseFrequencyX(baseFrequencyX()->currentValue()->value());
+        bool baseFrequencyYChanged = turbulence->setBaseFrequencyY(baseFrequencyY()->currentValue()->value());
         return (baseFrequencyXChanged || baseFrequencyYChanged);
     }
     if (attrName == SVGNames::seedAttr)
-        return turbulence->setSeed(seedCurrentValue());
+        return turbulence->setSeed(m_seed->currentValue()->value());
     if (attrName == SVGNames::numOctavesAttr)
-        return turbulence->setNumOctaves(numOctavesCurrentValue());
+        return turbulence->setNumOctaves(m_numOctaves->currentValue()->value());
 
     ASSERT_NOT_REACHED();
     return false;
@@ -173,9 +151,9 @@
 
 PassRefPtr<FilterEffect> SVGFETurbulenceElement::build(SVGFilterBuilder*, Filter* filter)
 {
-    if (baseFrequencyXCurrentValue() < 0 || baseFrequencyYCurrentValue() < 0)
+    if (baseFrequencyX()->currentValue()->value() < 0 || baseFrequencyY()->currentValue()->value() < 0)
         return 0;
-    return FETurbulence::create(filter, typeCurrentValue(), baseFrequencyXCurrentValue(), baseFrequencyYCurrentValue(), numOctavesCurrentValue(), seedCurrentValue(), stitchTilesCurrentValue() == SVG_STITCHTYPE_STITCH);
+    return FETurbulence::create(filter, typeCurrentValue(), baseFrequencyX()->currentValue()->value(), baseFrequencyY()->currentValue()->value(), m_numOctaves->currentValue()->value(), m_seed->currentValue()->value(), stitchTilesCurrentValue() == SVG_STITCHTYPE_STITCH);
 }
 
 }
diff --git a/Source/core/svg/SVGFETurbulenceElement.h b/Source/core/svg/SVGFETurbulenceElement.h
index b9ead22..467cd9c 100644
--- a/Source/core/svg/SVGFETurbulenceElement.h
+++ b/Source/core/svg/SVGFETurbulenceElement.h
@@ -24,6 +24,7 @@
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedInteger.h"
 #include "core/svg/SVGAnimatedNumber.h"
+#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 #include "platform/graphics/filters/FETurbulence.h"
 
@@ -97,23 +98,24 @@
 public:
     static PassRefPtr<SVGFETurbulenceElement> create(Document&);
 
+    SVGAnimatedNumber* baseFrequencyX() { return m_baseFrequency->firstNumber(); }
+    SVGAnimatedNumber* baseFrequencyY() { return m_baseFrequency->secondNumber(); }
+    SVGAnimatedNumber* seed() { return m_seed.get(); }
+    SVGAnimatedInteger* numOctaves() { return m_numOctaves.get(); }
+
 private:
     explicit SVGFETurbulenceElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName);
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
+    virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName) OVERRIDE;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*) OVERRIDE;
 
-    static const AtomicString& baseFrequencyXIdentifier();
-    static const AtomicString& baseFrequencyYIdentifier();
-
+    RefPtr<SVGAnimatedNumberOptionalNumber> m_baseFrequency;
+    RefPtr<SVGAnimatedNumber> m_seed;
+    RefPtr<SVGAnimatedInteger> m_numOctaves;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFETurbulenceElement)
-        DECLARE_ANIMATED_NUMBER(BaseFrequencyX, baseFrequencyX)
-        DECLARE_ANIMATED_NUMBER(BaseFrequencyY, baseFrequencyY)
-        DECLARE_ANIMATED_INTEGER(NumOctaves, numOctaves)
-        DECLARE_ANIMATED_NUMBER(Seed, seed)
         DECLARE_ANIMATED_ENUMERATION(StitchTiles, stitchTiles, SVGStitchOptions)
         DECLARE_ANIMATED_ENUMERATION(Type, type, TurbulenceType)
     END_DECLARE_ANIMATED_PROPERTIES
diff --git a/Source/core/svg/SVGFilterElement.cpp b/Source/core/svg/SVGFilterElement.cpp
index 3322336..83a92de 100644
--- a/Source/core/svg/SVGFilterElement.cpp
+++ b/Source/core/svg/SVGFilterElement.cpp
@@ -35,40 +35,37 @@
 // Animated property definitions
 DEFINE_ANIMATED_ENUMERATION(SVGFilterElement, SVGNames::filterUnitsAttr, FilterUnits, filterUnits, SVGUnitTypes::SVGUnitType)
 DEFINE_ANIMATED_ENUMERATION(SVGFilterElement, SVGNames::primitiveUnitsAttr, PrimitiveUnits, primitiveUnits, SVGUnitTypes::SVGUnitType)
-DEFINE_ANIMATED_LENGTH(SVGFilterElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGFilterElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH(SVGFilterElement, SVGNames::widthAttr, Width, width)
-DEFINE_ANIMATED_LENGTH(SVGFilterElement, SVGNames::heightAttr, Height, height)
-DEFINE_ANIMATED_INTEGER_MULTIPLE_WRAPPERS(SVGFilterElement, SVGNames::filterResAttr, filterResXIdentifier(), FilterResX, filterResX)
-DEFINE_ANIMATED_INTEGER_MULTIPLE_WRAPPERS(SVGFilterElement, SVGNames::filterResAttr, filterResYIdentifier(), FilterResY, filterResY)
-DEFINE_ANIMATED_STRING(SVGFilterElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGFilterElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFilterElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(filterUnits)
     REGISTER_LOCAL_ANIMATED_PROPERTY(primitiveUnits)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(width)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(height)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(filterResX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(filterResY)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGFilterElement::SVGFilterElement(Document& document)
     : SVGElement(SVGNames::filterTag, document)
+    , SVGURIReference(this)
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
+    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth)))
+    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight)))
+    , m_filterRes(SVGAnimatedIntegerOptionalInteger::create(this, SVGNames::filterResAttr))
     , m_filterUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
     , m_primitiveUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
-    , m_x(LengthModeWidth, "-10%")
-    , m_y(LengthModeHeight, "-10%")
-    , m_width(LengthModeWidth, "120%")
-    , m_height(LengthModeHeight, "120%")
 {
+    ScriptWrappable::init(this);
+
     // Spec: If the x/y attribute is not specified, the effect is as if a value of "-10%" were specified.
     // Spec: If the width/height attribute is not specified, the effect is as if a value of "120%" were specified.
-    ScriptWrappable::init(this);
+    m_x->setDefaultValueAsString("-10%");
+    m_y->setDefaultValueAsString("-10%");
+    m_width->setDefaultValueAsString("120%");
+    m_height->setDefaultValueAsString("120%");
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_width);
+    addToPropertyMap(m_height);
+    addToPropertyMap(m_filterRes);
     registerAnimatedPropertiesForSVGFilterElement();
 }
 
@@ -77,26 +74,13 @@
     return adoptRef(new SVGFilterElement(document));
 }
 
-const AtomicString& SVGFilterElement::filterResXIdentifier()
+void SVGFilterElement::setFilterRes(unsigned x, unsigned y)
 {
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGFilterResX", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
+    filterResX()->baseValue()->setValue(x);
+    filterResY()->baseValue()->setValue(y);
 
-const AtomicString& SVGFilterElement::filterResYIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGFilterResY", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-void SVGFilterElement::setFilterRes(unsigned filterResX, unsigned filterResY)
-{
-    setFilterResXBaseValue(filterResX);
-    setFilterResYBaseValue(filterResY);
-
-    RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
-    if (renderer)
-        renderer->invalidateCacheAndMarkForLayout();
+    invalidateSVGAttributes();
+    svgAttributeChanged(SVGNames::filterResAttr);
 }
 
 bool SVGFilterElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -104,7 +88,6 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGURIReference::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::filterUnitsAttr);
         supportedAttributes.add(SVGNames::primitiveUnitsAttr);
         supportedAttributes.add(SVGNames::xAttr);
@@ -120,9 +103,9 @@
 {
     SVGParsingError parseError = NoError;
 
-    if (!isSupportedAttribute(name))
+    if (!isSupportedAttribute(name)) {
         SVGElement::parseAttribute(name, value);
-    else if (name == SVGNames::filterUnitsAttr) {
+    } else if (name == SVGNames::filterUnitsAttr) {
         SVGUnitTypes::SVGUnitType propertyValue = SVGPropertyTraits<SVGUnitTypes::SVGUnitType>::fromString(value);
         if (propertyValue > 0)
             setFilterUnitsBaseValue(propertyValue);
@@ -130,24 +113,20 @@
         SVGUnitTypes::SVGUnitType propertyValue = SVGPropertyTraits<SVGUnitTypes::SVGUnitType>::fromString(value);
         if (propertyValue > 0)
             setPrimitiveUnitsBaseValue(propertyValue);
-    } else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
-    else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (name == SVGNames::widthAttr)
-        setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
-    else if (name == SVGNames::heightAttr)
-        setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (name == SVGNames::filterResAttr) {
-        float x, y;
-        if (parseNumberOptionalNumber(value, x, y)) {
-            setFilterResXBaseValue(x);
-            setFilterResYBaseValue(y);
-        }
-    } else if (SVGURIReference::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)) {
-    } else
+    } else if (name == SVGNames::xAttr) {
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::yAttr) {
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::widthAttr) {
+        m_width->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (name == SVGNames::heightAttr) {
+        m_height->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (name == SVGNames::filterResAttr) {
+        m_filterRes->setBaseValueAsString(value, parseError);
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else {
         ASSERT_NOT_REACHED();
+    }
 
     reportAttributeParsingError(parseError, name, value);
 }
@@ -195,51 +174,12 @@
     return renderer;
 }
 
-bool SVGFilterElement::childShouldCreateRenderer(const Node& child) const
-{
-    if (!child.isSVGElement())
-        return false;
-
-    const SVGElement* svgElement = toSVGElement(&child);
-
-    DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, allowedChildElementTags, ());
-    if (allowedChildElementTags.isEmpty()) {
-        allowedChildElementTags.add(SVGNames::feBlendTag);
-        allowedChildElementTags.add(SVGNames::feColorMatrixTag);
-        allowedChildElementTags.add(SVGNames::feComponentTransferTag);
-        allowedChildElementTags.add(SVGNames::feCompositeTag);
-        allowedChildElementTags.add(SVGNames::feConvolveMatrixTag);
-        allowedChildElementTags.add(SVGNames::feDiffuseLightingTag);
-        allowedChildElementTags.add(SVGNames::feDisplacementMapTag);
-        allowedChildElementTags.add(SVGNames::feDistantLightTag);
-        allowedChildElementTags.add(SVGNames::feDropShadowTag);
-        allowedChildElementTags.add(SVGNames::feFloodTag);
-        allowedChildElementTags.add(SVGNames::feFuncATag);
-        allowedChildElementTags.add(SVGNames::feFuncBTag);
-        allowedChildElementTags.add(SVGNames::feFuncGTag);
-        allowedChildElementTags.add(SVGNames::feFuncRTag);
-        allowedChildElementTags.add(SVGNames::feGaussianBlurTag);
-        allowedChildElementTags.add(SVGNames::feImageTag);
-        allowedChildElementTags.add(SVGNames::feMergeTag);
-        allowedChildElementTags.add(SVGNames::feMergeNodeTag);
-        allowedChildElementTags.add(SVGNames::feMorphologyTag);
-        allowedChildElementTags.add(SVGNames::feOffsetTag);
-        allowedChildElementTags.add(SVGNames::fePointLightTag);
-        allowedChildElementTags.add(SVGNames::feSpecularLightingTag);
-        allowedChildElementTags.add(SVGNames::feSpotLightTag);
-        allowedChildElementTags.add(SVGNames::feTileTag);
-        allowedChildElementTags.add(SVGNames::feTurbulenceTag);
-    }
-
-    return allowedChildElementTags.contains<SVGAttributeHashTranslator>(svgElement->tagQName());
-}
-
 bool SVGFilterElement::selfHasRelativeLengths() const
 {
-    return xCurrentValue().isRelative()
-        || yCurrentValue().isRelative()
-        || widthCurrentValue().isRelative()
-        || heightCurrentValue().isRelative();
+    return m_x->currentValue()->isRelative()
+        || m_y->currentValue()->isRelative()
+        || m_width->currentValue()->isRelative()
+        || m_height->currentValue()->isRelative();
 }
 
 void SVGFilterElement::addClient(Node* client)
diff --git a/Source/core/svg/SVGFilterElement.h b/Source/core/svg/SVGFilterElement.h
index 791939a..80c61b7 100644
--- a/Source/core/svg/SVGFilterElement.h
+++ b/Source/core/svg/SVGFilterElement.h
@@ -27,53 +27,52 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedInteger.h"
+#include "core/svg/SVGAnimatedIntegerOptionalInteger.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGURIReference.h"
 #include "core/svg/SVGUnitTypes.h"
 
 namespace WebCore {
 
 class SVGFilterElement FINAL : public SVGElement,
-                               public SVGURIReference,
-                               public SVGExternalResourcesRequired {
+                               public SVGURIReference {
 public:
     static PassRefPtr<SVGFilterElement> create(Document&);
 
-    void setFilterRes(unsigned filterResX, unsigned filterResY);
+    void setFilterRes(unsigned x, unsigned y);
     void addClient(Node*);
     void removeClient(Node*);
 
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
+    SVGAnimatedLength* width() const { return m_width.get(); }
+    SVGAnimatedLength* height() const { return m_height.get(); }
+    SVGAnimatedInteger* filterResX() { return m_filterRes->firstInteger(); }
+    SVGAnimatedInteger* filterResY() { return m_filterRes->secondInteger(); }
+
 private:
     explicit SVGFilterElement(Document&);
 
-    virtual bool needsPendingResourceHandling() const { return false; }
+    virtual bool needsPendingResourceHandling() const OVERRIDE { return false; }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
-    static const AtomicString& filterResXIdentifier();
-    static const AtomicString& filterResYIdentifier();
-
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
+    RefPtr<SVGAnimatedLength> m_width;
+    RefPtr<SVGAnimatedLength> m_height;
+    RefPtr<SVGAnimatedIntegerOptionalInteger> m_filterRes;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFilterElement)
         DECLARE_ANIMATED_ENUMERATION(FilterUnits, filterUnits, SVGUnitTypes::SVGUnitType)
         DECLARE_ANIMATED_ENUMERATION(PrimitiveUnits, primitiveUnits, SVGUnitTypes::SVGUnitType)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_LENGTH(Width, width)
-        DECLARE_ANIMATED_LENGTH(Height, height)
-        DECLARE_ANIMATED_INTEGER(FilterResX, filterResX)
-        DECLARE_ANIMATED_INTEGER(FilterResY, filterResY)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
     HashSet<RefPtr<Node> > m_clientsToAdd;
diff --git a/Source/core/svg/SVGFilterElement.idl b/Source/core/svg/SVGFilterElement.idl
index 7934751..6a6997c 100644
--- a/Source/core/svg/SVGFilterElement.idl
+++ b/Source/core/svg/SVGFilterElement.idl
@@ -24,7 +24,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGFilterElement : SVGElement {
+[
+    StrictTypeChecking,
+] interface SVGFilterElement : SVGElement {
     readonly attribute SVGAnimatedEnumeration filterUnits;
     readonly attribute SVGAnimatedEnumeration primitiveUnits;
     readonly attribute SVGAnimatedLength      x;
@@ -34,10 +36,9 @@
     readonly attribute SVGAnimatedInteger     filterResX;
     readonly attribute SVGAnimatedInteger     filterResY;
 
-    void setFilterRes([Default=Undefined] optional unsigned long filterResX,
-                      [Default=Undefined] optional unsigned long filterResY);
+    void setFilterRes(unsigned long filterResX,
+                      unsigned long filterResY);
 };
 
-SVGFilterElement implements SVGExternalResourcesRequired;
 SVGFilterElement implements SVGURIReference;
 
diff --git a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
index cb25ed4..dd5cbd7 100644
--- a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
+++ b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
@@ -32,30 +32,32 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGFilterPrimitiveStandardAttributes, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGFilterPrimitiveStandardAttributes, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH(SVGFilterPrimitiveStandardAttributes, SVGNames::widthAttr, Width, width)
-DEFINE_ANIMATED_LENGTH(SVGFilterPrimitiveStandardAttributes, SVGNames::heightAttr, Height, height)
-DEFINE_ANIMATED_STRING(SVGFilterPrimitiveStandardAttributes, SVGNames::resultAttr, Result, result)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(width)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(height)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(result)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGFilterPrimitiveStandardAttributes::SVGFilterPrimitiveStandardAttributes(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
-    , m_x(LengthModeWidth, "0%")
-    , m_y(LengthModeHeight, "0%")
-    , m_width(LengthModeWidth, "100%")
-    , m_height(LengthModeHeight, "100%")
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
+    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth)))
+    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight)))
+    , m_result(SVGAnimatedString::create(this, SVGNames::resultAttr, SVGString::create()))
 {
     // Spec: If the x/y attribute is not specified, the effect is as if a value of "0%" were specified.
+    m_x->setDefaultValueAsString("0%");
+    m_y->setDefaultValueAsString("0%");
+
     // Spec: If the width/height attribute is not specified, the effect is as if a value of "100%" were specified.
+    m_width->setDefaultValueAsString("100%");
+    m_height->setDefaultValueAsString("100%");
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_width);
+    addToPropertyMap(m_height);
+    addToPropertyMap(m_result);
     registerAnimatedPropertiesForSVGFilterPrimitiveStandardAttributes();
 }
 
@@ -79,15 +81,15 @@
     if (!isSupportedAttribute(name))
         SVGElement::parseAttribute(name, value);
     else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::widthAttr)
-        setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_width->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::heightAttr)
-        setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_height->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::resultAttr)
-        setResultBaseValue(value);
+        m_result->setBaseValueAsString(value, parseError);
     else
         ASSERT_NOT_REACHED();
 
diff --git a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h
index bbdc8ff..70c8f63 100644
--- a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h
+++ b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h
@@ -43,13 +43,26 @@
     // Returns true, if the new value is different from the old one.
     virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&);
 
+    // SVGFilterPrimitiveStandardAttributes JS API.
+    static SVGAnimatedLength* x(SVGFilterPrimitiveStandardAttributes* object) { return object->x(); }
+    static SVGAnimatedLength* y(SVGFilterPrimitiveStandardAttributes* object) { return object->y(); }
+    static SVGAnimatedLength* width(SVGFilterPrimitiveStandardAttributes* object) { return object->width(); }
+    static SVGAnimatedLength* height(SVGFilterPrimitiveStandardAttributes* object) { return object->height(); }
+    static SVGAnimatedString* result(SVGFilterPrimitiveStandardAttributes* object) { return object->result(); }
+
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
+    SVGAnimatedLength* width() const { return m_width.get(); }
+    SVGAnimatedLength* height() const { return m_height.get(); }
+    SVGAnimatedString* result() const { return m_result.get(); }
+
 protected:
     SVGFilterPrimitiveStandardAttributes(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
     inline void invalidate()
     {
@@ -60,18 +73,17 @@
     void primitiveAttributeChanged(const QualifiedName&);
 
 private:
-    virtual bool isFilterEffect() const { return true; }
+    virtual bool isFilterEffect() const OVERRIDE FINAL { return true; }
 
-    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE { return false; }
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE FINAL;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE FINAL;
 
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
+    RefPtr<SVGAnimatedLength> m_width;
+    RefPtr<SVGAnimatedLength> m_height;
+    RefPtr<SVGAnimatedString> m_result;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_LENGTH(Width, width)
-        DECLARE_ANIMATED_LENGTH(Height, height)
-        DECLARE_ANIMATED_STRING(Result, result)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.idl b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.idl
index 9f368ee..6ddcff6 100644
--- a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.idl
+++ b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.idl
@@ -25,8 +25,7 @@
  */
 
 [
-    NoInterfaceObject,
-    LegacyImplementedInBaseClass
+    NoInterfaceObject
 ] interface SVGFilterPrimitiveStandardAttributes {
     readonly attribute SVGAnimatedLength x;
     readonly attribute SVGAnimatedLength y;
diff --git a/Source/core/svg/SVGFitToViewBox.cpp b/Source/core/svg/SVGFitToViewBox.cpp
index 60425c8..e764ee8 100644
--- a/Source/core/svg/SVGFitToViewBox.cpp
+++ b/Source/core/svg/SVGFitToViewBox.cpp
@@ -1,6 +1,7 @@
 /*
  * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
  * Copyright (C) 2004, 2005, 2006, 2007, 2010 Rob Buis <buis@kde.org>
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -25,6 +26,7 @@
 #include "core/dom/Attribute.h"
 #include "core/dom/Document.h"
 #include "core/svg/SVGDocumentExtensions.h"
+#include "core/svg/SVGElement.h"
 #include "core/svg/SVGParserUtilities.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/transforms/AffineTransform.h"
@@ -32,77 +34,23 @@
 
 namespace WebCore {
 
-template<typename CharType>
-static bool parseViewBoxInternal(Document* document, const CharType*& ptr, const CharType* end, FloatRect& viewBox, bool validate)
+SVGFitToViewBox::SVGFitToViewBox(SVGElement* element, PropertyMapPolicy propertyMapPolicy)
+    : m_viewBox(SVGAnimatedRect::create(element, SVGNames::viewBoxAttr))
+    , m_preserveAspectRatio(SVGAnimatedPreserveAspectRatio::create(element, SVGNames::preserveAspectRatioAttr, SVGPreserveAspectRatio::create()))
 {
-    const CharType* start = ptr;
-
-    skipOptionalSVGSpaces(ptr, end);
-
-    float x = 0.0f;
-    float y = 0.0f;
-    float width = 0.0f;
-    float height = 0.0f;
-    bool valid = parseNumber(ptr, end, x) && parseNumber(ptr, end, y) && parseNumber(ptr, end, width) && parseNumber(ptr, end, height, false);
-    if (!validate) {
-        viewBox = FloatRect(x, y, width, height);
-        return true;
+    ASSERT(element);
+    if (propertyMapPolicy == PropertyMapPolicyAdd) {
+        element->addToPropertyMap(m_viewBox);
+        element->addToPropertyMap(m_preserveAspectRatio);
     }
-    if (!valid) {
-        document->accessSVGExtensions()->reportWarning("Problem parsing viewBox=\"" + String(start, end - start) + "\"");
-        return false;
-    }
-
-    if (width < 0.0) { // check that width is positive
-        document->accessSVGExtensions()->reportError("A negative value for ViewBox width is not allowed");
-        return false;
-    }
-    if (height < 0.0) { // check that height is positive
-        document->accessSVGExtensions()->reportError("A negative value for ViewBox height is not allowed");
-        return false;
-    }
-    skipOptionalSVGSpaces(ptr, end);
-    if (ptr < end) { // nothing should come after the last, fourth number
-        document->accessSVGExtensions()->reportWarning("Problem parsing viewBox=\"" + String(start, end - start) + "\"");
-        return false;
-    }
-
-    viewBox = FloatRect(x, y, width, height);
-    return true;
 }
 
-bool SVGFitToViewBox::parseViewBox(Document* document, const LChar*& ptr, const LChar* end, FloatRect& viewBox, bool validate)
-{
-    return parseViewBoxInternal(document, ptr, end, viewBox, validate);
-}
-
-bool SVGFitToViewBox::parseViewBox(Document* document, const UChar*& ptr, const UChar* end, FloatRect& viewBox, bool validate)
-{
-    return parseViewBoxInternal(document, ptr, end, viewBox, validate);
-}
-
-bool SVGFitToViewBox::parseViewBox(Document* document, const String& string, FloatRect& viewBox)
-{
-    if (string.isEmpty()) {
-        const LChar* ptr = 0;
-        return parseViewBoxInternal<LChar>(document, ptr, ptr, viewBox, true);
-    }
-    if (string.is8Bit()) {
-        const LChar* ptr = string.characters8();
-        const LChar* end = ptr + string.length();
-        return parseViewBox(document, ptr, end, viewBox, true);
-    }
-    const UChar* ptr = string.characters16();
-    const UChar* end = ptr + string.length();
-    return parseViewBox(document, ptr, end, viewBox, true);
-}
-
-AffineTransform SVGFitToViewBox::viewBoxToViewTransform(const FloatRect& viewBoxRect, const SVGPreserveAspectRatio& preserveAspectRatio, float viewWidth, float viewHeight)
+AffineTransform SVGFitToViewBox::viewBoxToViewTransform(const FloatRect& viewBoxRect, PassRefPtr<SVGPreserveAspectRatio> preserveAspectRatio, float viewWidth, float viewHeight)
 {
     if (!viewBoxRect.width() || !viewBoxRect.height())
         return AffineTransform();
 
-    return preserveAspectRatio.getCTM(viewBoxRect.x(), viewBoxRect.y(), viewBoxRect.width(), viewBoxRect.height(), viewWidth, viewHeight);
+    return preserveAspectRatio->getCTM(viewBoxRect.x(), viewBoxRect.y(), viewBoxRect.width(), viewBoxRect.height(), viewWidth, viewHeight);
 }
 
 bool SVGFitToViewBox::isKnownAttribute(const QualifiedName& attrName)
@@ -116,4 +64,10 @@
     supportedAttributes.add(SVGNames::preserveAspectRatioAttr);
 }
 
+void SVGFitToViewBox::updateViewBox(const FloatRect& rect)
+{
+    ASSERT(m_viewBox);
+    m_viewBox->baseValue()->setValue(rect);
+}
+
 }
diff --git a/Source/core/svg/SVGFitToViewBox.h b/Source/core/svg/SVGFitToViewBox.h
index ba8ca3c..3620dd4 100644
--- a/Source/core/svg/SVGFitToViewBox.h
+++ b/Source/core/svg/SVGFitToViewBox.h
@@ -1,6 +1,7 @@
 /*
  * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
  * Copyright (C) 2004, 2005, 2006, 2007, 2010 Rob Buis <buis@kde.org>
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -22,7 +23,12 @@
 #define SVGFitToViewBox_h
 
 #include "SVGNames.h"
+#include "core/dom/Document.h"
 #include "core/dom/QualifiedName.h"
+#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
+#include "core/svg/SVGAnimatedRect.h"
+#include "core/svg/SVGDocumentExtensions.h"
+#include "core/svg/SVGParsingError.h"
 #include "core/svg/SVGPreserveAspectRatio.h"
 #include "core/svg/SVGRect.h"
 #include "wtf/HashSet.h"
@@ -34,40 +40,54 @@
 
 class SVGFitToViewBox {
 public:
-    static AffineTransform viewBoxToViewTransform(const FloatRect& viewBoxRect, const SVGPreserveAspectRatio&, float viewWidth, float viewHeight);
+    enum PropertyMapPolicy {
+        PropertyMapPolicyAdd,
+        PropertyMapPolicySkip,
+    };
+
+    static AffineTransform viewBoxToViewTransform(const FloatRect& viewBoxRect, PassRefPtr<SVGPreserveAspectRatio>, float viewWidth, float viewHeight);
 
     static bool isKnownAttribute(const QualifiedName&);
     static void addSupportedAttributes(HashSet<QualifiedName>&);
 
-    template<class SVGElementTarget>
-    static bool parseAttribute(SVGElementTarget* target, const QualifiedName& name, const AtomicString& value)
+    bool parseAttribute(const QualifiedName& name, const AtomicString& value, Document& document, SVGParsingError& parseError)
     {
-        ASSERT(target);
         if (name == SVGNames::viewBoxAttr) {
-            FloatRect viewBox;
-            bool valueIsValid = !value.isNull() && parseViewBox(&target->document(), value, viewBox);
-            if (valueIsValid)
-                target->setViewBoxBaseValue(viewBox);
-            else
-                target->setViewBoxBaseValue(SVGRect(SVGRect::InvalidSVGRectTag()));
+            m_viewBox->setBaseValueAsString(value, parseError);
+            if (m_viewBox->baseValue()->width() < 0.0f) {
+                document.accessSVGExtensions()->reportError("A negative value for ViewBox width is not allowed");
+                m_viewBox->baseValue()->setInvalid();
+            }
+            if (m_viewBox->baseValue()->height() < 0.0f) {
+                document.accessSVGExtensions()->reportError("A negative value for ViewBox height is not allowed");
+                m_viewBox->baseValue()->setInvalid();
+            }
             return true;
         }
-
         if (name == SVGNames::preserveAspectRatioAttr) {
-            SVGPreserveAspectRatio preserveAspectRatio;
-            preserveAspectRatio.parse(value);
-            target->setPreserveAspectRatioBaseValue(preserveAspectRatio);
+            m_preserveAspectRatio->setBaseValueAsString(value, parseError);
             return true;
         }
-
         return false;
     }
 
-    static bool parseViewBox(Document*, const LChar*& start, const LChar* end, FloatRect& viewBox, bool validate = true);
-    static bool parseViewBox(Document*, const UChar*& start, const UChar* end, FloatRect& viewBox, bool validate = true);
+    // SVGFitToViewBox JS API.
+    static SVGAnimatedRect* viewBox(SVGFitToViewBox* object) { return object->viewBox(); }
+    static SVGAnimatedPreserveAspectRatio* preserveAspectRatio(SVGFitToViewBox* object) { return object->preserveAspectRatio(); }
+
+    SVGAnimatedRect* viewBox() const { return m_viewBox.get(); }
+    bool hasEmptyViewBox() const { return m_viewBox->currentValue()->isValid() && m_viewBox->currentValue()->value().isEmpty(); }
+    SVGAnimatedPreserveAspectRatio* preserveAspectRatio() const { return m_preserveAspectRatio.get(); }
+
+protected:
+    explicit SVGFitToViewBox(SVGElement*, PropertyMapPolicy = PropertyMapPolicyAdd);
+    void updateViewBox(const FloatRect&);
+    void clearViewBox() { m_viewBox = 0; }
+    void clearPreserveAspectRatio() { m_preserveAspectRatio = 0; }
 
 private:
-    static bool parseViewBox(Document*, const String&, FloatRect&);
+    RefPtr<SVGAnimatedRect> m_viewBox;
+    RefPtr<SVGAnimatedPreserveAspectRatio> m_preserveAspectRatio;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFitToViewBox.idl b/Source/core/svg/SVGFitToViewBox.idl
index 4e115fe..56bad0f 100644
--- a/Source/core/svg/SVGFitToViewBox.idl
+++ b/Source/core/svg/SVGFitToViewBox.idl
@@ -25,10 +25,8 @@
  */
 
 [
-    NoInterfaceObject,
-    LegacyImplementedInBaseClass
+    NoInterfaceObject
 ] interface SVGFitToViewBox {
     readonly attribute SVGAnimatedRect                viewBox;
     readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio;
 };
-
diff --git a/Source/core/svg/SVGFontData.cpp b/Source/core/svg/SVGFontData.cpp
index 64b6b3d..962e25d 100644
--- a/Source/core/svg/SVGFontData.cpp
+++ b/Source/core/svg/SVGFontData.cpp
@@ -30,6 +30,7 @@
 #include "core/svg/SVGFontElement.h"
 #include "core/svg/SVGFontFaceElement.h"
 #include "core/svg/SVGGlyphElement.h"
+#include "platform/fonts/Character.h"
 #include "platform/fonts/SVGGlyph.h"
 #include "platform/fonts/SimpleFontData.h"
 #include "platform/fonts/WidthIterator.h"
@@ -142,10 +143,10 @@
 
     if (run.is8Bit()) {
         remainingTextInRun = String(run.data8(currentCharacter), run.charactersLength() - currentCharacter);
-        remainingTextInRun = Font::normalizeSpaces(remainingTextInRun.characters8(), remainingTextInRun.length());
+        remainingTextInRun = Character::normalizeSpaces(remainingTextInRun.characters8(), remainingTextInRun.length());
     } else {
         remainingTextInRun = String(run.data16(currentCharacter), run.charactersLength() - currentCharacter);
-        remainingTextInRun = Font::normalizeSpaces(remainingTextInRun.characters16(), remainingTextInRun.length());
+        remainingTextInRun = Character::normalizeSpaces(remainingTextInRun.characters16(), remainingTextInRun.length());
     }
 
     if (mirror)
@@ -165,7 +166,7 @@
 
     String language;
     bool isVerticalText = false;
-    Vector<String> altGlyphNames;
+    Vector<AtomicString> altGlyphNames;
 
     if (renderObject) {
         RenderObject* parentRenderObject = renderObject->isText() ? renderObject->parent() : renderObject;
@@ -176,8 +177,7 @@
             language = parentRenderObjectElement->getAttribute(XMLNames::langAttr);
 
             if (parentRenderObjectElement->hasTagName(SVGNames::altGlyphTag)) {
-                SVGAltGlyphElement* altGlyph = static_cast<SVGAltGlyphElement*>(parentRenderObjectElement);
-                if (!altGlyph->hasValidGlyphElements(altGlyphNames))
+                if (!toSVGAltGlyphElement(parentRenderObjectElement)->hasValidGlyphElements(altGlyphNames))
                     altGlyphNames.clear();
             }
         }
diff --git a/Source/core/svg/SVGFontElement.cpp b/Source/core/svg/SVGFontElement.cpp
index 6f956f5..70d80b4 100644
--- a/Source/core/svg/SVGFontElement.cpp
+++ b/Source/core/svg/SVGFontElement.cpp
@@ -34,10 +34,8 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_BOOLEAN(SVGFontElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFontElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
diff --git a/Source/core/svg/SVGFontElement.h b/Source/core/svg/SVGFontElement.h
index f7d945e..c0cea8c 100644
--- a/Source/core/svg/SVGFontElement.h
+++ b/Source/core/svg/SVGFontElement.h
@@ -26,7 +26,6 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGlyphMap.h"
 #include "core/svg/SVGParserUtilities.h"
 
@@ -52,8 +51,7 @@
 
 class SVGMissingGlyphElement;
 
-class SVGFontElement FINAL : public SVGElement
-                           , public SVGExternalResourcesRequired {
+class SVGFontElement FINAL : public SVGElement {
 public:
     static PassRefPtr<SVGFontElement> create(Document&);
 
@@ -73,13 +71,12 @@
 private:
     explicit SVGFontElement(Document&);
 
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     void ensureGlyphCache();
     void registerLigaturesInGlyphCache(Vector<String>&);
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFontElement)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
     KerningPairVector m_horizontalKerningPairs;
diff --git a/Source/core/svg/SVGFontFaceElement.cpp b/Source/core/svg/SVGFontFaceElement.cpp
index a4907f5..1c142a7 100644
--- a/Source/core/svg/SVGFontFaceElement.cpp
+++ b/Source/core/svg/SVGFontFaceElement.cpp
@@ -28,7 +28,6 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "core/css/CSSFontFaceSrcValue.h"
-#include "core/css/CSSParser.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/CSSValueList.h"
 #include "core/css/StylePropertySet.h"
@@ -274,16 +273,8 @@
         return;
     }
 
-    // we currently ignore all but the first src element, alternatively we could concat them
-    SVGFontFaceSrcElement* srcElement = 0;
-
-    for (Node* child = firstChild(); child && !srcElement; child = child->nextSibling()) {
-        if (child->hasTagName(font_face_srcTag))
-            srcElement = static_cast<SVGFontFaceSrcElement*>(child);
-    }
-
     bool describesParentFont = parentNode()->hasTagName(SVGNames::fontTag);
-    RefPtr<CSSValueList> list;
+    RefPtrWillBeRawPtr<CSSValueList> list;
 
     if (describesParentFont) {
         m_fontElement = toSVGFontElement(parentNode());
@@ -292,8 +283,13 @@
         list->append(CSSFontFaceSrcValue::createLocal(fontFamily()));
     } else {
         m_fontElement = 0;
-        if (srcElement)
-            list = srcElement->srcValue();
+        // we currently ignore all but the last src element, alternatively we could concat them
+        for (Node* child = lastChild(); child && !list; child = child->previousSibling()) {
+            if (child->hasTagName(font_face_srcTag)) {
+                list = toSVGFontFaceSrcElement(child)->srcValue();
+                break;
+            }
+        }
     }
 
     if (!list || !list->length())
diff --git a/Source/core/svg/SVGFontFaceElement.h b/Source/core/svg/SVGFontFaceElement.h
index 0950ef4..8406a14 100644
--- a/Source/core/svg/SVGFontFaceElement.h
+++ b/Source/core/svg/SVGFontFaceElement.h
@@ -57,7 +57,7 @@
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
diff --git a/Source/core/svg/SVGFontFaceFormatElement.h b/Source/core/svg/SVGFontFaceFormatElement.h
index 986431a..d6df778 100644
--- a/Source/core/svg/SVGFontFaceFormatElement.h
+++ b/Source/core/svg/SVGFontFaceFormatElement.h
@@ -32,7 +32,7 @@
 private:
     explicit SVGFontFaceFormatElement(Document&);
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
diff --git a/Source/core/svg/SVGFontFaceNameElement.cpp b/Source/core/svg/SVGFontFaceNameElement.cpp
index 2675278..90dbd88 100644
--- a/Source/core/svg/SVGFontFaceNameElement.cpp
+++ b/Source/core/svg/SVGFontFaceNameElement.cpp
@@ -37,7 +37,7 @@
     return adoptRef(new SVGFontFaceNameElement(document));
 }
 
-PassRefPtr<CSSFontFaceSrcValue> SVGFontFaceNameElement::srcValue() const
+PassRefPtrWillBeRawPtr<CSSFontFaceSrcValue> SVGFontFaceNameElement::srcValue() const
 {
     return CSSFontFaceSrcValue::createLocal(fastGetAttribute(SVGNames::nameAttr));
 }
diff --git a/Source/core/svg/SVGFontFaceNameElement.h b/Source/core/svg/SVGFontFaceNameElement.h
index 8b93942..2f0cdab 100644
--- a/Source/core/svg/SVGFontFaceNameElement.h
+++ b/Source/core/svg/SVGFontFaceNameElement.h
@@ -32,7 +32,7 @@
 public:
     static PassRefPtr<SVGFontFaceNameElement> create(Document&);
 
-    PassRefPtr<CSSFontFaceSrcValue> srcValue() const;
+    PassRefPtrWillBeRawPtr<CSSFontFaceSrcValue> srcValue() const;
 
 private:
     explicit SVGFontFaceNameElement(Document&);
diff --git a/Source/core/svg/SVGFontFaceSrcElement.cpp b/Source/core/svg/SVGFontFaceSrcElement.cpp
index bc2254d..5bb34db 100644
--- a/Source/core/svg/SVGFontFaceSrcElement.cpp
+++ b/Source/core/svg/SVGFontFaceSrcElement.cpp
@@ -44,11 +44,11 @@
     return adoptRef(new SVGFontFaceSrcElement(document));
 }
 
-PassRefPtr<CSSValueList> SVGFontFaceSrcElement::srcValue() const
+PassRefPtrWillBeRawPtr<CSSValueList> SVGFontFaceSrcElement::srcValue() const
 {
-    RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    RefPtrWillBeRawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
-        RefPtr<CSSFontFaceSrcValue> srcValue;
+        RefPtrWillBeRawPtr<CSSFontFaceSrcValue> srcValue;
         if (child->hasTagName(font_face_uriTag))
             srcValue = toSVGFontFaceUriElement(child)->srcValue();
         else if (child->hasTagName(font_face_nameTag))
diff --git a/Source/core/svg/SVGFontFaceSrcElement.h b/Source/core/svg/SVGFontFaceSrcElement.h
index f7ef1af..1d53c88 100644
--- a/Source/core/svg/SVGFontFaceSrcElement.h
+++ b/Source/core/svg/SVGFontFaceSrcElement.h
@@ -21,6 +21,7 @@
 #define SVGFontFaceSrcElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/svg/SVGElement.h"
 
 namespace WebCore {
@@ -31,15 +32,17 @@
 public:
     static PassRefPtr<SVGFontFaceSrcElement> create(Document&);
 
-    PassRefPtr<CSSValueList> srcValue() const;
+    PassRefPtrWillBeRawPtr<CSSValueList> srcValue() const;
 
 private:
     explicit SVGFontFaceSrcElement(Document&);
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
+DEFINE_NODE_TYPE_CASTS(SVGFontFaceSrcElement, hasTagName(SVGNames::font_face_srcTag));
+
 } // namespace WebCore
 
 #endif // ENABLE(SVG_FONTS)
diff --git a/Source/core/svg/SVGFontFaceUriElement.cpp b/Source/core/svg/SVGFontFaceUriElement.cpp
index fabcf7f..f4b2b27 100644
--- a/Source/core/svg/SVGFontFaceUriElement.cpp
+++ b/Source/core/svg/SVGFontFaceUriElement.cpp
@@ -51,9 +51,9 @@
         m_resource->removeClient(this);
 }
 
-PassRefPtr<CSSFontFaceSrcValue> SVGFontFaceUriElement::srcValue() const
+PassRefPtrWillBeRawPtr<CSSFontFaceSrcValue> SVGFontFaceUriElement::srcValue() const
 {
-    RefPtr<CSSFontFaceSrcValue> src = CSSFontFaceSrcValue::create(getAttribute(XLinkNames::hrefAttr));
+    RefPtrWillBeRawPtr<CSSFontFaceSrcValue> src = CSSFontFaceSrcValue::create(getAttribute(XLinkNames::hrefAttr));
     AtomicString value(fastGetAttribute(formatAttr));
     src->setFormat(value.isEmpty() ? "svg" : value); // Default format
     return src.release();
@@ -61,7 +61,7 @@
 
 void SVGFontFaceUriElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
-    if (name == XLinkNames::hrefAttr)
+    if (name.matches(XLinkNames::hrefAttr))
         loadFont();
     else
         SVGElement::parseAttribute(name, value);
diff --git a/Source/core/svg/SVGFontFaceUriElement.h b/Source/core/svg/SVGFontFaceUriElement.h
index 338ce85..c545bec 100644
--- a/Source/core/svg/SVGFontFaceUriElement.h
+++ b/Source/core/svg/SVGFontFaceUriElement.h
@@ -36,13 +36,13 @@
 
     virtual ~SVGFontFaceUriElement();
 
-    PassRefPtr<CSSFontFaceSrcValue> srcValue() const;
+    PassRefPtrWillBeRawPtr<CSSFontFaceSrcValue> srcValue() const;
 
 private:
     explicit SVGFontFaceUriElement(Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
diff --git a/Source/core/svg/SVGForeignObjectElement.cpp b/Source/core/svg/SVGForeignObjectElement.cpp
index 8db9e53..0a8428a 100644
--- a/Source/core/svg/SVGForeignObjectElement.cpp
+++ b/Source/core/svg/SVGForeignObjectElement.cpp
@@ -31,31 +31,24 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGForeignObjectElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGForeignObjectElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH(SVGForeignObjectElement, SVGNames::widthAttr, Width, width)
-DEFINE_ANIMATED_LENGTH(SVGForeignObjectElement, SVGNames::heightAttr, Height, height)
-DEFINE_ANIMATED_STRING(SVGForeignObjectElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGForeignObjectElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGForeignObjectElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(width)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(height)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGForeignObjectElement::SVGForeignObjectElement(Document& document)
     : SVGGraphicsElement(SVGNames::foreignObjectTag, document)
-    , m_x(LengthModeWidth)
-    , m_y(LengthModeHeight)
-    , m_width(LengthModeWidth)
-    , m_height(LengthModeHeight)
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
+    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth)))
+    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight)))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_width);
+    addToPropertyMap(m_height);
     registerAnimatedPropertiesForSVGForeignObjectElement();
 }
 
@@ -68,7 +61,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::xAttr);
         supportedAttributes.add(SVGNames::yAttr);
         supportedAttributes.add(SVGNames::widthAttr);
@@ -84,15 +76,14 @@
     if (!isSupportedAttribute(name))
         SVGGraphicsElement::parseAttribute(name, value);
     else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::widthAttr)
-        setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_width->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::heightAttr)
-        setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (SVGExternalResourcesRequired::parseAttribute(name, value)) {
-    } else
+        m_height->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    else
         ASSERT_NOT_REACHED();
 
     reportAttributeParsingError(parseError, name, value);
@@ -124,16 +115,6 @@
     return new RenderSVGForeignObject(this);
 }
 
-bool SVGForeignObjectElement::childShouldCreateRenderer(const Node& child) const
-{
-    // Disallow arbitary SVG content. Only allow proper <svg xmlns="svgNS"> subdocuments.
-    if (child.isSVGElement())
-        return child.hasTagName(SVGNames::svgTag);
-
-    // Skip over SVG rules which disallow non-SVG kids
-    return Element::childShouldCreateRenderer(child);
-}
-
 bool SVGForeignObjectElement::rendererIsNeeded(const RenderStyle& style)
 {
     // Suppress foreignObject renderers in SVG hidden containers.
@@ -154,10 +135,10 @@
 
 bool SVGForeignObjectElement::selfHasRelativeLengths() const
 {
-    return xCurrentValue().isRelative()
-        || yCurrentValue().isRelative()
-        || widthCurrentValue().isRelative()
-        || heightCurrentValue().isRelative();
+    return m_x->currentValue()->isRelative()
+        || m_y->currentValue()->isRelative()
+        || m_width->currentValue()->isRelative()
+        || m_height->currentValue()->isRelative();
 }
 
 }
diff --git a/Source/core/svg/SVGForeignObjectElement.h b/Source/core/svg/SVGForeignObjectElement.h
index 38d3734..70a8aa5 100644
--- a/Source/core/svg/SVGForeignObjectElement.h
+++ b/Source/core/svg/SVGForeignObjectElement.h
@@ -23,38 +23,37 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGURIReference.h"
 
 namespace WebCore {
 
-class SVGForeignObjectElement FINAL : public SVGGraphicsElement,
-                                      public SVGExternalResourcesRequired {
+class SVGForeignObjectElement FINAL : public SVGGraphicsElement {
 public:
     static PassRefPtr<SVGForeignObjectElement> create(Document&);
 
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
+    SVGAnimatedLength* width() const { return m_width.get(); }
+    SVGAnimatedLength* height() const { return m_height.get(); }
+
 private:
     explicit SVGForeignObjectElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const Node& child) const;
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
+    RefPtr<SVGAnimatedLength> m_width;
+    RefPtr<SVGAnimatedLength> m_height;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGForeignObjectElement)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_LENGTH(Width, width)
-        DECLARE_ANIMATED_LENGTH(Height, height)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGForeignObjectElement.idl b/Source/core/svg/SVGForeignObjectElement.idl
index 778b9f5..3d348ff 100644
--- a/Source/core/svg/SVGForeignObjectElement.idl
+++ b/Source/core/svg/SVGForeignObjectElement.idl
@@ -30,5 +30,3 @@
     readonly attribute SVGAnimatedLength height;
 };
 
-SVGForeignObjectElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGGElement.cpp b/Source/core/svg/SVGGElement.cpp
index aa767c0..88beb1b 100644
--- a/Source/core/svg/SVGGElement.cpp
+++ b/Source/core/svg/SVGGElement.cpp
@@ -31,10 +31,8 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_BOOLEAN(SVGGElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGGElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
@@ -53,8 +51,6 @@
 bool SVGGElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
-    if (supportedAttributes.isEmpty())
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
     return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
@@ -65,9 +61,6 @@
         return;
     }
 
-    if (SVGLangSpace::parseAttribute(name, value))
-        return;
-
     ASSERT_NOT_REACHED();
 }
 
diff --git a/Source/core/svg/SVGGElement.h b/Source/core/svg/SVGGElement.h
index 255e514..3a7c85f 100644
--- a/Source/core/svg/SVGGElement.h
+++ b/Source/core/svg/SVGGElement.h
@@ -22,33 +22,29 @@
 #define SVGGElement_h
 
 #include "core/svg/SVGAnimatedBoolean.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGGElement FINAL : public SVGGraphicsElement,
-                          public SVGExternalResourcesRequired {
+class SVGGElement FINAL : public SVGGraphicsElement {
 public:
     static PassRefPtr<SVGGElement> create(Document&);
 
 protected:
     explicit SVGGElement(Document&, ConstructionType = CreateSVGElement);
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
 private:
-    virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGGElement)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGGElement.idl b/Source/core/svg/SVGGElement.idl
index 060969f..38a1146 100644
--- a/Source/core/svg/SVGGElement.idl
+++ b/Source/core/svg/SVGGElement.idl
@@ -26,5 +26,3 @@
 interface SVGGElement : SVGGraphicsElement {
 };
 
-SVGGElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGGeometryElement.cpp b/Source/core/svg/SVGGeometryElement.cpp
index 56b3d03..c8c125b 100644
--- a/Source/core/svg/SVGGeometryElement.cpp
+++ b/Source/core/svg/SVGGeometryElement.cpp
@@ -35,6 +35,7 @@
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/PointerEventsHitRules.h"
 #include "core/rendering/svg/RenderSVGShape.h"
+#include "core/svg/SVGPointTearOff.h"
 
 namespace WebCore {
 
@@ -43,7 +44,7 @@
 {
 }
 
-bool SVGGeometryElement::isPointInFill(const SVGPoint& point) const
+bool SVGGeometryElement::isPointInFill(PassRefPtr<SVGPointTearOff> point) const
 {
     document().updateLayoutIgnorePendingStylesheets();
 
@@ -54,10 +55,10 @@
     HitTestRequest request(HitTestRequest::ReadOnly);
     PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request, renderer()->style()->pointerEvents());
     hitRules.canHitStroke = false;
-    return toRenderSVGShape(renderer())->nodeAtFloatPointInternal(request, point, hitRules);
+    return toRenderSVGShape(renderer())->nodeAtFloatPointInternal(request, point->target()->value(), hitRules);
 }
 
-bool SVGGeometryElement::isPointInStroke(const SVGPoint& point) const
+bool SVGGeometryElement::isPointInStroke(PassRefPtr<SVGPointTearOff> point) const
 {
     document().updateLayoutIgnorePendingStylesheets();
 
@@ -68,7 +69,7 @@
     HitTestRequest request(HitTestRequest::ReadOnly);
     PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request, renderer()->style()->pointerEvents());
     hitRules.canHitFill = false;
-    return toRenderSVGShape(renderer())->nodeAtFloatPointInternal(request, point, hitRules);
+    return toRenderSVGShape(renderer())->nodeAtFloatPointInternal(request, point->target()->value(), hitRules);
 }
 
 }
diff --git a/Source/core/svg/SVGGeometryElement.h b/Source/core/svg/SVGGeometryElement.h
index 09fffa5..a4cf565 100644
--- a/Source/core/svg/SVGGeometryElement.h
+++ b/Source/core/svg/SVGGeometryElement.h
@@ -32,14 +32,15 @@
 #define SVGGeometryElement_h
 
 #include "core/svg/SVGGraphicsElement.h"
-#include "core/svg/SVGPoint.h"
 
 namespace WebCore {
 
+class SVGPointTearOff;
+
 class SVGGeometryElement : public SVGGraphicsElement {
 public:
-    bool isPointInFill(const SVGPoint&) const;
-    bool isPointInStroke(const SVGPoint&) const;
+    bool isPointInFill(PassRefPtr<SVGPointTearOff>) const;
+    bool isPointInStroke(PassRefPtr<SVGPointTearOff>) const;
 
 protected:
     SVGGeometryElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
diff --git a/Source/core/svg/SVGGeometryElement.idl b/Source/core/svg/SVGGeometryElement.idl
index d783758..8cb7022 100644
--- a/Source/core/svg/SVGGeometryElement.idl
+++ b/Source/core/svg/SVGGeometryElement.idl
@@ -28,7 +28,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGGeometryElement : SVGGraphicsElement {
+[
+    StrictTypeChecking,
+] interface SVGGeometryElement : SVGGraphicsElement {
     boolean isPointInFill(SVGPoint point);
     boolean isPointInStroke(SVGPoint point);
 };
diff --git a/Source/core/svg/SVGGlyphElement.h b/Source/core/svg/SVGGlyphElement.h
index 565eb1d..b4741e7 100644
--- a/Source/core/svg/SVGGlyphElement.h
+++ b/Source/core/svg/SVGGlyphElement.h
@@ -53,7 +53,7 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     void invalidateGlyphCache();
 };
diff --git a/Source/core/svg/SVGGlyphRefElement.cpp b/Source/core/svg/SVGGlyphRefElement.cpp
index 5fd1b1c..2385cad 100644
--- a/Source/core/svg/SVGGlyphRefElement.cpp
+++ b/Source/core/svg/SVGGlyphRefElement.cpp
@@ -29,15 +29,14 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGGlyphRefElement, XLinkNames::hrefAttr, Href, href)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGGlyphRefElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGGlyphRefElement::SVGGlyphRefElement(Document& document)
     : SVGElement(SVGNames::glyphRefTag, document)
+    , SVGURIReference(this)
     , m_x(0)
     , m_y(0)
     , m_dx(0)
@@ -52,7 +51,7 @@
     return adoptRef(new SVGGlyphRefElement(document));
 }
 
-bool SVGGlyphRefElement::hasValidGlyphElement(String& glyphName) const
+bool SVGGlyphRefElement::hasValidGlyphElement(AtomicString& glyphName) const
 {
     // FIXME: We only support xlink:href so far.
     // https://bugs.webkit.org/show_bug.cgi?id=64787
@@ -69,6 +68,7 @@
     const CharType* end = ptr + value.length();
 
     // FIXME: We need some error handling here.
+    SVGParsingError parseError = NoError;
     if (name == SVGNames::xAttr) {
         parseNumber(ptr, end, m_x);
     } else if (name == SVGNames::yAttr) {
@@ -77,11 +77,11 @@
         parseNumber(ptr, end, m_dx);
     } else if (name == SVGNames::dyAttr) {
         parseNumber(ptr, end, m_dy);
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
     } else {
-        if (SVGURIReference::parseAttribute(name, value))
-            return;
         SVGElement::parseAttribute(name, value);
     }
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGGlyphRefElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGGlyphRefElement.h b/Source/core/svg/SVGGlyphRefElement.h
index 8de1d2b..259da0e 100644
--- a/Source/core/svg/SVGGlyphRefElement.h
+++ b/Source/core/svg/SVGGlyphRefElement.h
@@ -32,7 +32,7 @@
 public:
     static PassRefPtr<SVGGlyphRefElement> create(Document&);
 
-    bool hasValidGlyphElement(String& glyphName) const;
+    bool hasValidGlyphElement(AtomicString& glyphName) const;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
     // DOM interface
@@ -53,10 +53,9 @@
     template<typename CharType>
     void parseAttributeInternal(const QualifiedName&, const AtomicString&);
 
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGGlyphRefElement)
-        DECLARE_ANIMATED_STRING(Href, href)
     END_DECLARE_ANIMATED_PROPERTIES
 
     float m_x;
diff --git a/Source/core/svg/SVGGradientElement.cpp b/Source/core/svg/SVGGradientElement.cpp
index a9a85d2..6d1ca06 100644
--- a/Source/core/svg/SVGGradientElement.cpp
+++ b/Source/core/svg/SVGGradientElement.cpp
@@ -39,20 +39,17 @@
 DEFINE_ANIMATED_ENUMERATION(SVGGradientElement, SVGNames::spreadMethodAttr, SpreadMethod, spreadMethod, SVGSpreadMethodType)
 DEFINE_ANIMATED_ENUMERATION(SVGGradientElement, SVGNames::gradientUnitsAttr, GradientUnits, gradientUnits, SVGUnitTypes::SVGUnitType)
 DEFINE_ANIMATED_TRANSFORM_LIST(SVGGradientElement, SVGNames::gradientTransformAttr, GradientTransform, gradientTransform)
-DEFINE_ANIMATED_STRING(SVGGradientElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGGradientElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGGradientElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(spreadMethod)
     REGISTER_LOCAL_ANIMATED_PROPERTY(gradientUnits)
     REGISTER_LOCAL_ANIMATED_PROPERTY(gradientTransform)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGGradientElement::SVGGradientElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
+    , SVGURIReference(this)
     , m_spreadMethod(SVGSpreadMethodPad)
     , m_gradientUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
 {
@@ -65,7 +62,6 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGURIReference::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::gradientUnitsAttr);
         supportedAttributes.add(SVGNames::gradientTransformAttr);
         supportedAttributes.add(SVGNames::spreadMethodAttr);
@@ -102,12 +98,14 @@
         return;
     }
 
-    if (SVGURIReference::parseAttribute(name, value))
-        return;
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
+    SVGParsingError parseError = NoError;
 
-    ASSERT_NOT_REACHED();
+    if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else {
+        ASSERT_NOT_REACHED();
+    }
+
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGGradientElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -149,7 +147,7 @@
         Color color = stop->stopColorIncludingOpacity();
 
         // Figure out right monotonic offset
-        float offset = stop->offsetCurrentValue();
+        float offset = stop->offset()->currentValue()->value();
         offset = std::min(std::max(previousOffset, offset), 1.0f);
         previousOffset = offset;
 
diff --git a/Source/core/svg/SVGGradientElement.h b/Source/core/svg/SVGGradientElement.h
index cb2c916..e57eb6b 100644
--- a/Source/core/svg/SVGGradientElement.h
+++ b/Source/core/svg/SVGGradientElement.h
@@ -26,7 +26,6 @@
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedTransformList.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGURIReference.h"
 #include "core/svg/SVGUnitTypes.h"
 #include "platform/graphics/Gradient.h"
@@ -74,8 +73,7 @@
 };
 
 class SVGGradientElement : public SVGElement,
-                           public SVGURIReference,
-                           public SVGExternalResourcesRequired {
+                           public SVGURIReference {
 public:
     enum {
         SVG_SPREADMETHOD_UNKNOWN = SVGSpreadMethodUnknown,
@@ -91,19 +89,17 @@
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
 private:
-    virtual bool needsPendingResourceHandling() const { return false; }
+    virtual bool needsPendingResourceHandling() const OVERRIDE FINAL { return false; }
 
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE FINAL;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGGradientElement)
         DECLARE_ANIMATED_ENUMERATION(SpreadMethod, spreadMethod, SVGSpreadMethodType)
         DECLARE_ANIMATED_ENUMERATION(GradientUnits, gradientUnits, SVGUnitTypes::SVGUnitType)
         DECLARE_ANIMATED_TRANSFORM_LIST(GradientTransform, gradientTransform)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGGradientElement.idl b/Source/core/svg/SVGGradientElement.idl
index cc2f00b..ff2e048 100644
--- a/Source/core/svg/SVGGradientElement.idl
+++ b/Source/core/svg/SVGGradientElement.idl
@@ -37,6 +37,5 @@
     readonly attribute SVGAnimatedEnumeration   spreadMethod;
 };
 
-SVGGradientElement implements SVGExternalResourcesRequired;
 SVGGradientElement implements SVGURIReference;
 
diff --git a/Source/core/svg/SVGGraphicsElement.cpp b/Source/core/svg/SVGGraphicsElement.cpp
index 95bb0c2..b02670e 100644
--- a/Source/core/svg/SVGGraphicsElement.cpp
+++ b/Source/core/svg/SVGGraphicsElement.cpp
@@ -37,11 +37,11 @@
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGGraphicsElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(transform)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGGraphicsElement::SVGGraphicsElement(const QualifiedName& tagName, Document& document, ConstructionType constructionType)
     : SVGElement(tagName, document, constructionType)
+    , SVGTests(this)
 {
     registerAnimatedPropertiesForSVGGraphicsElement();
 }
@@ -57,7 +57,7 @@
     if (target && target->isSVGGraphicsElement()) {
         AffineTransform targetCTM = toSVGGraphicsElement(target)->getCTM(AllowStyleUpdate);
         if (!targetCTM.isInvertible()) {
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+            exceptionState.throwDOMException(InvalidStateError, "The target transformation is not invertable.");
             return ctm;
         }
         ctm = targetCTM.inverse() * ctm;
@@ -223,26 +223,20 @@
     return farthest;
 }
 
-SVGRect SVGGraphicsElement::getBBox()
+FloatRect SVGGraphicsElement::getBBox()
 {
     document().updateLayoutIgnorePendingStylesheets();
 
     // FIXME: Eventually we should support getBBox for detached elements.
     if (!renderer())
-        return SVGRect();
+        return FloatRect();
 
     return renderer()->objectBoundingBox();
 }
 
-SVGRect SVGGraphicsElement::getStrokeBBox()
+PassRefPtr<SVGRectTearOff> SVGGraphicsElement::getBBoxFromJavascript()
 {
-    document().updateLayoutIgnorePendingStylesheets();
-
-    // FIXME: Eventually we should support getStrokeBBox for detached elements.
-    if (!renderer())
-        return SVGRect();
-
-    return renderer()->strokeBoundingBox();
+    return SVGRectTearOff::create(SVGRect::create(getBBox()), 0, PropertyIsNotAnimVal);
 }
 
 RenderObject* SVGGraphicsElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGGraphicsElement.h b/Source/core/svg/SVGGraphicsElement.h
index 6bc8830..8e1f311 100644
--- a/Source/core/svg/SVGGraphicsElement.h
+++ b/Source/core/svg/SVGGraphicsElement.h
@@ -23,6 +23,7 @@
 
 #include "core/svg/SVGAnimatedTransformList.h"
 #include "core/svg/SVGElement.h"
+#include "core/svg/SVGRectTearOff.h"
 #include "core/svg/SVGTests.h"
 
 namespace WebCore {
@@ -44,33 +45,30 @@
 
     virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const OVERRIDE { return animatedLocalTransform(); }
     virtual AffineTransform animatedLocalTransform() const;
-    virtual AffineTransform* supplementalTransform();
+    virtual AffineTransform* supplementalTransform() OVERRIDE;
 
-    virtual SVGRect getBBox();
-    SVGRect getStrokeBBox();
+    virtual FloatRect getBBox();
+    PassRefPtr<SVGRectTearOff> getBBoxFromJavascript();
 
     // "base class" methods for all the elements which render as paths
     virtual void toClipPath(Path&);
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+
+    virtual bool isValid() const OVERRIDE FINAL { return SVGTests::isValid(); }
 
 protected:
     SVGGraphicsElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGGraphicsElement)
         DECLARE_ANIMATED_TRANSFORM_LIST(Transform, transform)
     END_DECLARE_ANIMATED_PROPERTIES
 
 private:
-    virtual bool isSVGGraphicsElement() const OVERRIDE { return true; }
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
+    virtual bool isSVGGraphicsElement() const OVERRIDE FINAL { return true; }
 
     // Used by <animateMotion>
     OwnPtr<AffineTransform> m_supplementalTransform;
diff --git a/Source/core/svg/SVGGraphicsElement.idl b/Source/core/svg/SVGGraphicsElement.idl
index eed23aa..7666cdc 100644
--- a/Source/core/svg/SVGGraphicsElement.idl
+++ b/Source/core/svg/SVGGraphicsElement.idl
@@ -34,8 +34,7 @@
     [MeasureAs=SVGLocatableNearestViewportElement] readonly attribute SVGElement nearestViewportElement;
     [MeasureAs=SVGLocatableFarthestViewportElement] readonly attribute SVGElement farthestViewportElement;
 
-    SVGRect   getBBox();
-    SVGRect   getStrokeBBox();
+    [ImplementedAs=getBBoxFromJavascript] SVGRect getBBox();
     SVGMatrix getCTM();
     SVGMatrix getScreenCTM();
     [RaisesException] SVGMatrix getTransformToElement([Default=Undefined] optional SVGElement element);
diff --git a/Source/core/svg/SVGHKernElement.h b/Source/core/svg/SVGHKernElement.h
index d54d89d..7cb6665 100644
--- a/Source/core/svg/SVGHKernElement.h
+++ b/Source/core/svg/SVGHKernElement.h
@@ -40,7 +40,7 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGHKernElement, hasTagName(SVGNames::hkernTag));
diff --git a/Source/core/svg/SVGImageElement.cpp b/Source/core/svg/SVGImageElement.cpp
index a1873f5..21ed9fe 100644
--- a/Source/core/svg/SVGImageElement.cpp
+++ b/Source/core/svg/SVGImageElement.cpp
@@ -33,34 +33,29 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGImageElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGImageElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH(SVGImageElement, SVGNames::widthAttr, Width, width)
-DEFINE_ANIMATED_LENGTH(SVGImageElement, SVGNames::heightAttr, Height, height)
-DEFINE_ANIMATED_PRESERVEASPECTRATIO(SVGImageElement, SVGNames::preserveAspectRatioAttr, PreserveAspectRatio, preserveAspectRatio)
-DEFINE_ANIMATED_STRING(SVGImageElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGImageElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGImageElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(width)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(height)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAspectRatio)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGImageElement::SVGImageElement(Document& document)
     : SVGGraphicsElement(SVGNames::imageTag, document)
-    , m_x(LengthModeWidth)
-    , m_y(LengthModeHeight)
-    , m_width(LengthModeWidth)
-    , m_height(LengthModeHeight)
+    , SVGURIReference(this)
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
+    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth)))
+    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight)))
+    , m_preserveAspectRatio(SVGAnimatedPreserveAspectRatio::create(this, SVGNames::preserveAspectRatioAttr, SVGPreserveAspectRatio::create()))
     , m_imageLoader(this)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_width);
+    addToPropertyMap(m_height);
+
+    addToPropertyMap(m_preserveAspectRatio);
     registerAnimatedPropertiesForSVGImageElement();
 }
 
@@ -85,8 +80,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGLangSpace::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         SVGURIReference::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::xAttr);
         supportedAttributes.add(SVGNames::yAttr);
@@ -118,25 +111,22 @@
 {
     SVGParsingError parseError = NoError;
 
-    if (!isSupportedAttribute(name))
+    if (!isSupportedAttribute(name)) {
         SVGGraphicsElement::parseAttribute(name, value);
-    else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
-    else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (name == SVGNames::preserveAspectRatioAttr) {
-        SVGPreserveAspectRatio preserveAspectRatio;
-        preserveAspectRatio.parse(value);
-        setPreserveAspectRatioBaseValue(preserveAspectRatio);
-    } else if (name == SVGNames::widthAttr)
-        setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
-    else if (name == SVGNames::heightAttr)
-        setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGLangSpace::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)
-             || SVGURIReference::parseAttribute(name, value)) {
-    } else
+    } else if (name == SVGNames::xAttr) {
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::yAttr) {
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::widthAttr) {
+        m_width->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (name == SVGNames::heightAttr) {
+        m_height->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (name == SVGNames::preserveAspectRatioAttr) {
+        m_preserveAspectRatio->setBaseValueAsString(value, parseError);
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else {
         ASSERT_NOT_REACHED();
+    }
 
     reportAttributeParsingError(parseError, name, value);
 }
@@ -173,9 +163,7 @@
         return;
     }
 
-    if (attrName == SVGNames::preserveAspectRatioAttr
-        || SVGLangSpace::isKnownAttribute(attrName)
-        || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
+    if (attrName == SVGNames::preserveAspectRatioAttr) {
         RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
         return;
     }
@@ -185,10 +173,10 @@
 
 bool SVGImageElement::selfHasRelativeLengths() const
 {
-    return xCurrentValue().isRelative()
-        || yCurrentValue().isRelative()
-        || widthCurrentValue().isRelative()
-        || heightCurrentValue().isRelative();
+    return m_x->currentValue()->isRelative()
+        || m_y->currentValue()->isRelative()
+        || m_width->currentValue()->isRelative()
+        || m_height->currentValue()->isRelative();
 }
 
 RenderObject* SVGImageElement::createRenderer(RenderStyle*)
@@ -198,7 +186,7 @@
 
 bool SVGImageElement::haveLoadedRequiredResources()
 {
-    return !externalResourcesRequiredBaseValue() || !m_imageLoader.hasPendingActivity();
+    return !m_imageLoader.hasPendingActivity();
 }
 
 void SVGImageElement::attach(const AttachContext& context)
@@ -226,14 +214,7 @@
 
 const AtomicString SVGImageElement::imageSourceURL() const
 {
-    return hrefCurrentValue();
-}
-
-void SVGImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    SVGGraphicsElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
+    return AtomicString(hrefString());
 }
 
 void SVGImageElement::didMoveToNewDocument(Document& oldDocument)
diff --git a/Source/core/svg/SVGImageElement.h b/Source/core/svg/SVGImageElement.h
index 1270dc1..f3bf328 100644
--- a/Source/core/svg/SVGImageElement.h
+++ b/Source/core/svg/SVGImageElement.h
@@ -25,7 +25,6 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGAnimatedPreserveAspectRatio.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGImageLoader.h"
 #include "core/svg/SVGURIReference.h"
@@ -33,46 +32,48 @@
 namespace WebCore {
 
 class SVGImageElement FINAL : public SVGGraphicsElement,
-                              public SVGExternalResourcesRequired,
                               public SVGURIReference {
 public:
     static PassRefPtr<SVGImageElement> create(Document&);
 
     bool currentFrameHasSingleSecurityOrigin() const;
 
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
+    SVGAnimatedLength* width() const { return m_width.get(); }
+    SVGAnimatedLength* height() const { return m_height.get(); }
+    SVGAnimatedPreserveAspectRatio* preserveAspectRatio() { return m_preserveAspectRatio.get(); }
+
 private:
     explicit SVGImageElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
+    virtual bool isStructurallyExternal() const OVERRIDE { return !hrefString().isNull(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     virtual const AtomicString imageSourceURL() const OVERRIDE;
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
 
-    virtual bool haveLoadedRequiredResources();
+    virtual bool haveLoadedRequiredResources() OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
     virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
+    RefPtr<SVGAnimatedLength> m_width;
+    RefPtr<SVGAnimatedLength> m_height;
+    RefPtr<SVGAnimatedPreserveAspectRatio> m_preserveAspectRatio;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGImageElement)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_LENGTH(Width, width)
-        DECLARE_ANIMATED_LENGTH(Height, height)
-        DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
     SVGImageLoader m_imageLoader;
diff --git a/Source/core/svg/SVGImageElement.idl b/Source/core/svg/SVGImageElement.idl
index a2bc7b0..a659e29 100644
--- a/Source/core/svg/SVGImageElement.idl
+++ b/Source/core/svg/SVGImageElement.idl
@@ -31,6 +31,5 @@
     readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio;
 };
 
-SVGImageElement implements SVGExternalResourcesRequired;
 SVGImageElement implements SVGURIReference;
 
diff --git a/Source/core/svg/SVGImageLoader.cpp b/Source/core/svg/SVGImageLoader.cpp
index e889c61..c3bb79a 100644
--- a/Source/core/svg/SVGImageLoader.cpp
+++ b/Source/core/svg/SVGImageLoader.cpp
@@ -41,8 +41,7 @@
         element()->dispatchEvent(Event::create(EventTypeNames::error));
     else {
         SVGImageElement* imageElement = toSVGImageElement(element());
-        if (imageElement->externalResourcesRequiredBaseValue())
-            imageElement->sendSVGLoadEventIfPossible(true);
+        imageElement->sendSVGLoadEventIfPossible(true);
     }
 }
 
diff --git a/Source/core/svg/SVGImageLoader.h b/Source/core/svg/SVGImageLoader.h
index 38842e3..fc9de7e 100644
--- a/Source/core/svg/SVGImageLoader.h
+++ b/Source/core/svg/SVGImageLoader.h
@@ -26,13 +26,13 @@
 
 class SVGImageElement;
 
-class SVGImageLoader : public ImageLoader {
+class SVGImageLoader FINAL : public ImageLoader {
 public:
     SVGImageLoader(SVGImageElement*);
 
 private:
-    virtual void dispatchLoadEvent();
-    virtual String sourceURI(const AtomicString&) const;
+    virtual void dispatchLoadEvent() OVERRIDE;
+    virtual String sourceURI(const AtomicString&) const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGInteger.cpp b/Source/core/svg/SVGInteger.cpp
new file mode 100644
index 0000000..766d917
--- /dev/null
+++ b/Source/core/svg/SVGInteger.cpp
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/svg/SVGInteger.h"
+
+#include "core/svg/SVGAnimationElement.h"
+
+namespace WebCore {
+
+SVGInteger::SVGInteger(int value)
+    : NewSVGPropertyBase(classType())
+    , m_value(value)
+{
+}
+
+PassRefPtr<SVGInteger> SVGInteger::clone() const
+{
+    return create(m_value);
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGInteger::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGInteger> svgInteger = create();
+    svgInteger->setValueAsString(value, IGNORE_EXCEPTION);
+    return svgInteger.release();
+}
+
+String SVGInteger::valueAsString() const
+{
+    return String::number(m_value);
+}
+
+void SVGInteger::setValueAsString(const String& string, ExceptionState& exceptionState)
+{
+    if (string.isEmpty()) {
+        m_value = 0;
+        return;
+    }
+
+    bool valid = true;
+    m_value = string.toIntStrict(&valid);
+
+    if (!valid) {
+        exceptionState.throwDOMException(SyntaxError, "The value provided ('" + string + "') is invalid.");
+        m_value = 0;
+    }
+}
+
+void SVGInteger::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    setValue(m_value + toSVGInteger(other)->value());
+}
+
+void SVGInteger::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDuration, SVGElement*)
+{
+    ASSERT(animationElement);
+
+    RefPtr<SVGInteger> fromInteger = toSVGInteger(from);
+    RefPtr<SVGInteger> toInteger = toSVGInteger(to);
+    RefPtr<SVGInteger> toAtEndOfDurationInteger = toSVGInteger(toAtEndOfDuration);
+
+    float animatedFloat = m_value;
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromInteger->value(), toInteger->value(), toAtEndOfDurationInteger->value(), animatedFloat);
+    m_value = static_cast<int>(roundf(animatedFloat));
+}
+
+float SVGInteger::calculateDistance(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    return abs(m_value - toSVGInteger(other)->value());
+}
+
+}
diff --git a/Source/core/svg/SVGInteger.h b/Source/core/svg/SVGInteger.h
new file mode 100644
index 0000000..d1fb37f
--- /dev/null
+++ b/Source/core/svg/SVGInteger.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGInteger_h
+#define SVGInteger_h
+
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/svg/properties/NewSVGProperty.h"
+
+namespace WebCore {
+
+class SVGIntegerTearOff;
+
+class SVGInteger : public NewSVGPropertyBase {
+public:
+    typedef void TearOffType;
+    typedef int PrimitiveType;
+
+    static PassRefPtr<SVGInteger> create(int value = 0)
+    {
+        return adoptRef(new SVGInteger(value));
+    }
+
+    virtual PassRefPtr<SVGInteger> clone() const;
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+
+    int value() const { return m_value; }
+    void setValue(int value) { m_value = value; }
+
+    virtual String valueAsString() const OVERRIDE;
+    virtual void setValueAsString(const String&, ExceptionState&);
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedInteger; }
+
+protected:
+    explicit SVGInteger(int);
+
+    int m_value;
+};
+
+inline PassRefPtr<SVGInteger> toSVGInteger(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGInteger::classType());
+    return static_pointer_cast<SVGInteger>(base.release());
+}
+
+} // namespace WebCore
+
+#endif // SVGInteger_h
diff --git a/Source/core/svg/SVGIntegerOptionalInteger.cpp b/Source/core/svg/SVGIntegerOptionalInteger.cpp
new file mode 100644
index 0000000..c6070bf
--- /dev/null
+++ b/Source/core/svg/SVGIntegerOptionalInteger.cpp
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/svg/SVGIntegerOptionalInteger.h"
+
+#include "core/svg/SVGAnimationElement.h"
+#include "core/svg/SVGParserUtilities.h"
+
+namespace WebCore {
+
+SVGIntegerOptionalInteger::SVGIntegerOptionalInteger(PassRefPtr<SVGInteger> firstInteger, PassRefPtr<SVGInteger> secondInteger)
+    : NewSVGPropertyBase(classType())
+    , m_firstInteger(firstInteger)
+    , m_secondInteger(secondInteger)
+{
+}
+
+PassRefPtr<SVGIntegerOptionalInteger> SVGIntegerOptionalInteger::clone() const
+{
+    return SVGIntegerOptionalInteger::create(m_firstInteger->clone(), m_secondInteger->clone());
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGIntegerOptionalInteger::cloneForAnimation(const String& value) const
+{
+    float floatX, floatY;
+    if (!parseNumberOptionalNumber(value, floatX, floatY)) {
+        return SVGIntegerOptionalInteger::create(SVGInteger::create(0), SVGInteger::create(0));
+    }
+
+    int x = static_cast<int>(roundf(floatX));
+    int y = static_cast<int>(roundf(floatY));
+
+    return SVGIntegerOptionalInteger::create(SVGInteger::create(x), SVGInteger::create(y));
+}
+
+String SVGIntegerOptionalInteger::valueAsString() const
+{
+    if (m_firstInteger->value() == m_secondInteger->value()) {
+        return String::number(m_firstInteger->value());
+    }
+
+    return String::number(m_firstInteger->value()) + " " + String::number(m_secondInteger->value());
+}
+
+void SVGIntegerOptionalInteger::setValueAsString(const String& value, ExceptionState& exceptionState)
+{
+    float x, y;
+    if (!parseNumberOptionalNumber(value, x, y)) {
+        exceptionState.throwDOMException(SyntaxError, "The value provided ('" + value + "') is invalid.");
+        x = y = 0;
+    }
+
+    m_firstInteger->setValue(x);
+    m_secondInteger->setValue(y);
+}
+
+void SVGIntegerOptionalInteger::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    RefPtr<SVGIntegerOptionalInteger> otherIntegerOptionalInteger = toSVGIntegerOptionalInteger(other);
+
+    m_firstInteger->setValue(m_firstInteger->value() + otherIntegerOptionalInteger->m_firstInteger->value());
+    m_secondInteger->setValue(m_secondInteger->value() + otherIntegerOptionalInteger->m_secondInteger->value());
+}
+
+void SVGIntegerOptionalInteger::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDuration, SVGElement*)
+{
+    ASSERT(animationElement);
+
+    RefPtr<SVGIntegerOptionalInteger> fromInteger = toSVGIntegerOptionalInteger(from);
+    RefPtr<SVGIntegerOptionalInteger> toInteger = toSVGIntegerOptionalInteger(to);
+    RefPtr<SVGIntegerOptionalInteger> toAtEndOfDurationInteger = toSVGIntegerOptionalInteger(toAtEndOfDuration);
+
+    float x = m_firstInteger->value();
+    float y = m_secondInteger->value();
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromInteger->firstInteger()->value(), toInteger->firstInteger()->value(), toAtEndOfDurationInteger->firstInteger()->value(), x);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromInteger->secondInteger()->value(), toInteger->secondInteger()->value(), toAtEndOfDurationInteger->secondInteger()->value(), y);
+    m_firstInteger->setValue(static_cast<int>(roundf(x)));
+    m_secondInteger->setValue(static_cast<int>(roundf(y)));
+}
+
+float SVGIntegerOptionalInteger::calculateDistance(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    // FIXME: Distance calculation is not possible for SVGIntegerOptionalInteger right now. We need the distance for every single value.
+    return -1;
+}
+
+}
diff --git a/Source/core/svg/SVGIntegerOptionalInteger.h b/Source/core/svg/SVGIntegerOptionalInteger.h
new file mode 100644
index 0000000..d71997e
--- /dev/null
+++ b/Source/core/svg/SVGIntegerOptionalInteger.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGIntegerOptionalInteger_h
+#define SVGIntegerOptionalInteger_h
+
+#include "core/svg/SVGAnimatedInteger.h"
+
+namespace WebCore {
+
+class SVGIntegerOptionalInteger : public NewSVGPropertyBase {
+public:
+    // Tearoff of SVGIntegerOptionalInteger is never created.
+    typedef void TearOffType;
+    typedef void PrimitiveType;
+
+    static PassRefPtr<SVGIntegerOptionalInteger> create(PassRefPtr<SVGInteger> firstInteger, PassRefPtr<SVGInteger> secondInteger)
+    {
+        return adoptRef(new SVGIntegerOptionalInteger(firstInteger, secondInteger));
+    }
+
+    PassRefPtr<SVGIntegerOptionalInteger> clone() const;
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+
+    virtual String valueAsString() const OVERRIDE;
+    void setValueAsString(const String&, ExceptionState&);
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedIntegerOptionalInteger; }
+
+    PassRefPtr<SVGInteger> firstInteger() { return m_firstInteger; }
+    PassRefPtr<SVGInteger> secondInteger() { return m_secondInteger; }
+
+protected:
+    SVGIntegerOptionalInteger(PassRefPtr<SVGInteger> firstInteger, PassRefPtr<SVGInteger> secondInteger);
+
+    RefPtr<SVGInteger> m_firstInteger;
+    RefPtr<SVGInteger> m_secondInteger;
+};
+
+inline PassRefPtr<SVGIntegerOptionalInteger> toSVGIntegerOptionalInteger(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGIntegerOptionalInteger::classType());
+    return static_pointer_cast<SVGIntegerOptionalInteger>(base.release());
+}
+
+} // namespace WebCore
+
+#endif // SVGIntegerOptionalInteger_h
diff --git a/Source/core/svg/SVGLangSpace.cpp b/Source/core/svg/SVGLangSpace.cpp
deleted file mode 100644
index 1fe66e0..0000000
--- a/Source/core/svg/SVGLangSpace.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/svg/SVGLangSpace.h"
-
-#include "XMLNames.h"
-#include "wtf/StdLibExtras.h"
-
-namespace WebCore {
-
-void SVGLangSpace::setXMLlang(const AtomicString& xmlLang)
-{
-    m_lang = xmlLang;
-}
-
-const AtomicString& SVGLangSpace::xmlspace() const
-{
-    if (!m_space) {
-        DEFINE_STATIC_LOCAL(const AtomicString, defaultString, ("default", AtomicString::ConstructFromLiteral));
-        return defaultString;
-    }
-
-    return m_space;
-}
-
-void SVGLangSpace::setXMLspace(const AtomicString& xmlSpace)
-{
-    m_space = xmlSpace;
-}
-
-bool SVGLangSpace::parseAttribute(const QualifiedName& name, const AtomicString& value)
-{
-    if (name.matches(XMLNames::langAttr)) {
-        setXMLlang(value);
-        return true;
-    }
-    if (name.matches(XMLNames::spaceAttr)) {
-        setXMLspace(value);
-        return true;
-    }
-
-    return false;
-}
-
-bool SVGLangSpace::isKnownAttribute(const QualifiedName& attrName)
-{
-    return attrName.matches(XMLNames::langAttr) || attrName.matches(XMLNames::spaceAttr);
-}
-
-void SVGLangSpace::addSupportedAttributes(HashSet<QualifiedName>& supportedAttributes)
-{
-    QualifiedName langWithPrefix = XMLNames::langAttr;
-    langWithPrefix.setPrefix(xmlAtom);
-    supportedAttributes.add(langWithPrefix);
-    supportedAttributes.add(XMLNames::langAttr);
-
-    QualifiedName spaceWithPrefix = XMLNames::spaceAttr;
-    spaceWithPrefix.setPrefix(xmlAtom);
-    supportedAttributes.add(spaceWithPrefix);
-    supportedAttributes.add(XMLNames::spaceAttr);
-}
-
-}
diff --git a/Source/core/svg/SVGLangSpace.h b/Source/core/svg/SVGLangSpace.h
deleted file mode 100644
index 2e323c5..0000000
--- a/Source/core/svg/SVGLangSpace.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGLangSpace_h
-#define SVGLangSpace_h
-
-#include "core/dom/QualifiedName.h"
-#include "wtf/HashSet.h"
-
-namespace WebCore {
-
-class Attribute;
-
-class SVGLangSpace {
-public:
-    const AtomicString& xmllang() const { return m_lang; }
-    void setXMLlang(const AtomicString& xmlLang);
-
-    const AtomicString& xmlspace() const;
-    void setXMLspace(const AtomicString& xmlSpace);
-
-    bool parseAttribute(const QualifiedName&, const AtomicString&);
-    bool isKnownAttribute(const QualifiedName&);
-    void addSupportedAttributes(HashSet<QualifiedName>&);
-
-private:
-    AtomicString m_lang;
-    AtomicString m_space;
-};
-
-} // namespace WebCore
-
-#endif // SVGLangSpace_h
diff --git a/Source/core/svg/SVGLength.cpp b/Source/core/svg/SVGLength.cpp
index b6a9596..5cf61be 100644
--- a/Source/core/svg/SVGLength.cpp
+++ b/Source/core/svg/SVGLength.cpp
@@ -24,46 +24,20 @@
 #include "core/svg/SVGLength.h"
 
 #include "SVGNames.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "bindings/v8/ExceptionState.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/svg/SVGAnimationElement.h"
 #include "core/svg/SVGParserUtilities.h"
+#include "platform/animation/AnimationUtilities.h"
 #include "wtf/MathExtras.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-static inline SVGLengthMode toSVGLengthMode(unsigned short mode)
-{
-    ASSERT(mode >= LengthModeWidth && mode <= LengthModeOther);
-    return static_cast<SVGLengthMode>(mode);
-}
+namespace {
 
-static inline SVGLengthType toSVGLengthType(unsigned short type)
-{
-    ASSERT(type >= LengthTypeUnknown && type <= LengthTypePC);
-    return static_cast<SVGLengthType>(type);
-}
-
-static inline unsigned int storeUnit(SVGLengthMode mode, SVGLengthType type)
-{
-    return (mode << 4) | type;
-}
-
-static inline SVGLengthMode extractMode(unsigned int unit)
-{
-    unsigned int mode = unit >> 4;
-    return toSVGLengthMode(mode);
-}
-
-static inline SVGLengthType extractType(unsigned int unit)
-{
-    unsigned int mode = unit >> 4;
-    unsigned int type = unit ^ (mode << 4);
-    return toSVGLengthType(type);
-}
-
-static inline String lengthTypeToString(SVGLengthType type)
+inline String lengthTypeToString(SVGLengthType type)
 {
     switch (type) {
     case LengthTypeUnknown:
@@ -94,7 +68,7 @@
 }
 
 template<typename CharType>
-static SVGLengthType stringToLengthType(const CharType*& ptr, const CharType* end)
+SVGLengthType stringToLengthType(const CharType*& ptr, const CharType* end)
 {
     if (ptr == end)
         return LengthTypeNumber;
@@ -129,99 +103,81 @@
     return LengthTypeUnknown;
 }
 
-SVGLength::SVGLength(SVGLengthMode mode, const String& valueAsString)
-    : m_valueInSpecifiedUnits(0)
-    , m_unit(storeUnit(mode, LengthTypeNumber))
-{
-    setValueAsString(valueAsString, IGNORE_EXCEPTION);
-}
+} // namespace
 
-SVGLength::SVGLength(const SVGLengthContext& context, float value, SVGLengthMode mode, SVGLengthType unitType)
-    : m_valueInSpecifiedUnits(0)
-    , m_unit(storeUnit(mode, unitType))
-{
-    setValue(value, context, ASSERT_NO_EXCEPTION);
-}
-
-SVGLength::SVGLength(const SVGLength& other)
-    : m_valueInSpecifiedUnits(other.m_valueInSpecifiedUnits)
-    , m_unit(other.m_unit)
+SVGLength::SVGLength(SVGLengthMode mode)
+    : NewSVGPropertyBase(classType())
+    , m_valueInSpecifiedUnits(0)
+    , m_unitMode(mode)
+    , m_unitType(LengthTypeNumber)
 {
 }
 
-void SVGLength::setValueAsString(const String& valueAsString, SVGLengthMode mode, ExceptionState& exceptionState)
+SVGLength::SVGLength(const SVGLength& o)
+    : NewSVGPropertyBase(classType())
+    , m_valueInSpecifiedUnits(o.m_valueInSpecifiedUnits)
+    , m_unitMode(o.m_unitMode)
+    , m_unitType(o.m_unitType)
 {
-    m_valueInSpecifiedUnits = 0;
-    m_unit = storeUnit(mode, LengthTypeNumber);
-    setValueAsString(valueAsString, exceptionState);
+}
+
+PassRefPtr<SVGLength> SVGLength::clone() const
+{
+    return adoptRef(new SVGLength(*this));
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGLength::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGLength> length = create();
+
+    length->m_unitMode = m_unitMode;
+    length->m_unitType = m_unitType;
+
+    TrackExceptionState exceptionState;
+    length->setValueAsString(value, exceptionState);
+    if (exceptionState.hadException()) {
+        length->m_unitType = LengthTypeNumber;
+        length->m_valueInSpecifiedUnits = 0;
+    }
+
+    return length.release();
 }
 
 bool SVGLength::operator==(const SVGLength& other) const
 {
-    return m_unit == other.m_unit
+    return m_unitMode == other.m_unitMode
+        && m_unitType == other.m_unitType
         && m_valueInSpecifiedUnits == other.m_valueInSpecifiedUnits;
 }
 
-bool SVGLength::operator!=(const SVGLength& other) const
+float SVGLength::value(const SVGLengthContext& context, ExceptionState& es) const
 {
-    return !operator==(other);
+    return context.convertValueToUserUnits(m_valueInSpecifiedUnits, unitMode(), unitType(), es);
 }
 
-SVGLength SVGLength::construct(SVGLengthMode mode, const String& valueAsString, SVGParsingError& parseError, SVGLengthNegativeValuesMode negativeValuesMode)
-{
-    TrackExceptionState exceptionState;
-    SVGLength length(mode);
-
-    length.setValueAsString(valueAsString, exceptionState);
-
-    if (exceptionState.hadException())
-        parseError = ParsingAttributeFailedError;
-    else if (negativeValuesMode == ForbidNegativeLengths && length.valueInSpecifiedUnits() < 0)
-        parseError = NegativeValueForbiddenError;
-
-    return length;
-}
-
-SVGLengthType SVGLength::unitType() const
-{
-    return extractType(m_unit);
-}
-
-SVGLengthMode SVGLength::unitMode() const
-{
-    return extractMode(m_unit);
-}
-
-float SVGLength::value(const SVGLengthContext& context) const
-{
-    return value(context, IGNORE_EXCEPTION);
-}
-
-float SVGLength::value(const SVGLengthContext& context, ExceptionState& exceptionState) const
-{
-    return context.convertValueToUserUnits(m_valueInSpecifiedUnits, extractMode(m_unit), extractType(m_unit), exceptionState);
-}
-
-void SVGLength::setValue(const SVGLengthContext& context, float value, SVGLengthMode mode, SVGLengthType unitType, ExceptionState& exceptionState)
-{
-    m_unit = storeUnit(mode, unitType);
-    setValue(value, context, exceptionState);
-}
-
-void SVGLength::setValue(float value, const SVGLengthContext& context, ExceptionState& exceptionState)
+void SVGLength::setValue(float value, const SVGLengthContext& context, ExceptionState& es)
 {
     // 100% = 100.0 instead of 1.0 for historical reasons, this could eventually be changed
-    if (extractType(m_unit) == LengthTypePercentage)
+    if (m_unitType == LengthTypePercentage)
         value = value / 100;
 
-    float convertedValue = context.convertValueFromUserUnits(value, extractMode(m_unit), extractType(m_unit), exceptionState);
-    if (!exceptionState.hadException())
-        m_valueInSpecifiedUnits = convertedValue;
+    float convertedValue = context.convertValueFromUserUnits(value, unitMode(), unitType(), es);
+    if (es.hadException())
+        return;
+
+    m_valueInSpecifiedUnits = convertedValue;
 }
+
+void SVGLength::setUnitType(SVGLengthType type)
+{
+    ASSERT(type != LengthTypeUnknown && type <= LengthTypePC);
+    m_unitType = type;
+}
+
 float SVGLength::valueAsPercentage() const
 {
     // 100% = 100.0 instead of 1.0 for historical reasons, this could eventually be changed
-    if (extractType(m_unit) == LengthTypePercentage)
+    if (m_unitType == LengthTypePercentage)
         return m_valueInSpecifiedUnits / 100;
 
     return m_valueInSpecifiedUnits;
@@ -246,8 +202,11 @@
 
 void SVGLength::setValueAsString(const String& string, ExceptionState& exceptionState)
 {
-    if (string.isEmpty())
+    if (string.isEmpty()) {
+        m_unitType = LengthTypeNumber;
+        m_valueInSpecifiedUnits = 0;
         return;
+    }
 
     float convertedNumber = 0;
     SVGLengthType type = LengthTypeUnknown;
@@ -257,52 +216,44 @@
         parseValueInternal<UChar>(string, convertedNumber, type);
 
     if (!success) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The value provided ('" + string + "') is invalid.");
         return;
     }
 
-    m_unit = storeUnit(extractMode(m_unit), type);
+    m_unitType = type;
     m_valueInSpecifiedUnits = convertedNumber;
 }
 
 String SVGLength::valueAsString() const
 {
-    return String::number(m_valueInSpecifiedUnits) + lengthTypeToString(extractType(m_unit));
+    return String::number(m_valueInSpecifiedUnits) + lengthTypeToString(unitType());
 }
 
-void SVGLength::newValueSpecifiedUnits(unsigned short type, float value, ExceptionState& exceptionState)
+void SVGLength::newValueSpecifiedUnits(SVGLengthType type, float value)
 {
-    if (type == LengthTypeUnknown || type > LengthTypePC) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return;
-    }
-
-    m_unit = storeUnit(extractMode(m_unit), toSVGLengthType(type));
+    setUnitType(type);
     m_valueInSpecifiedUnits = value;
 }
 
-void SVGLength::convertToSpecifiedUnits(unsigned short type, const SVGLengthContext& context, ExceptionState& exceptionState)
+void SVGLength::convertToSpecifiedUnits(SVGLengthType type, const SVGLengthContext& context, ExceptionState& exceptionState)
 {
-    if (type == LengthTypeUnknown || type > LengthTypePC) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return;
-    }
+    ASSERT(type != LengthTypeUnknown && type <= LengthTypePC);
 
     float valueInUserUnits = value(context, exceptionState);
     if (exceptionState.hadException())
         return;
 
-    unsigned int originalUnitAndType = m_unit;
-    m_unit = storeUnit(extractMode(m_unit), toSVGLengthType(type));
+    SVGLengthType originalType = unitType();
+    m_unitType = type;
     setValue(valueInUserUnits, context, exceptionState);
     if (!exceptionState.hadException())
         return;
 
     // Eventually restore old unit and type
-    m_unit = originalUnitAndType;
+    m_unitType = originalType;
 }
 
-SVGLength SVGLength::fromCSSPrimitiveValue(CSSPrimitiveValue* value)
+PassRefPtr<SVGLength> SVGLength::fromCSSPrimitiveValue(CSSPrimitiveValue* value)
 {
     ASSERT(value);
 
@@ -345,21 +296,19 @@
     };
 
     if (svgType == LengthTypeUnknown)
-        return SVGLength();
+        return SVGLength::create();
 
-    TrackExceptionState exceptionState;
-    SVGLength length;
-    length.newValueSpecifiedUnits(svgType, value->getFloatValue(), exceptionState);
-    if (exceptionState.hadException())
-        return SVGLength();
-
-    return length;
+    RefPtr<SVGLength> length = SVGLength::create();
+    length->newValueSpecifiedUnits(svgType, value->getFloatValue());
+    return length.release();
 }
 
-PassRefPtr<CSSPrimitiveValue> SVGLength::toCSSPrimitiveValue(const SVGLength& length)
+PassRefPtrWillBeRawPtr<CSSPrimitiveValue> SVGLength::toCSSPrimitiveValue(PassRefPtr<SVGLength> passLength)
 {
+    RefPtr<SVGLength> length = passLength;
+
     CSSPrimitiveValue::UnitTypes cssType = CSSPrimitiveValue::CSS_UNKNOWN;
-    switch (length.unitType()) {
+    switch (length->unitType()) {
     case LengthTypeUnknown:
         break;
     case LengthTypeNumber:
@@ -394,7 +343,7 @@
         break;
     };
 
-    return CSSPrimitiveValue::create(length.valueInSpecifiedUnits(), cssType);
+    return CSSPrimitiveValue::create(length->valueInSpecifiedUnits(), cssType);
 }
 
 SVGLengthMode SVGLength::lengthModeForAnimatedLengthAttribute(const QualifiedName& attrName)
@@ -412,6 +361,8 @@
         s_lengthModeMap.set(SVGNames::fxAttr, LengthModeWidth);
         s_lengthModeMap.set(SVGNames::fyAttr, LengthModeHeight);
         s_lengthModeMap.set(SVGNames::rAttr, LengthModeOther);
+        s_lengthModeMap.set(SVGNames::rxAttr, LengthModeWidth);
+        s_lengthModeMap.set(SVGNames::ryAttr, LengthModeHeight);
         s_lengthModeMap.set(SVGNames::widthAttr, LengthModeWidth);
         s_lengthModeMap.set(SVGNames::heightAttr, LengthModeHeight);
         s_lengthModeMap.set(SVGNames::x1Attr, LengthModeWidth);
@@ -432,4 +383,85 @@
     return LengthModeOther;
 }
 
+PassRefPtr<SVGLength> SVGLength::blend(PassRefPtr<SVGLength> passFrom, float progress) const
+{
+    RefPtr<SVGLength> from = passFrom;
+
+    SVGLengthType toType = unitType();
+    SVGLengthType fromType = from->unitType();
+    if ((from->isZero() && isZero())
+        || fromType == LengthTypeUnknown
+        || toType == LengthTypeUnknown
+        || (!from->isZero() && fromType != LengthTypePercentage && toType == LengthTypePercentage)
+        || (!isZero() && fromType == LengthTypePercentage && toType != LengthTypePercentage)
+        || (!from->isZero() && !isZero() && (fromType == LengthTypeEMS || fromType == LengthTypeEXS) && fromType != toType))
+        return clone();
+
+    RefPtr<SVGLength> length = create();
+
+    if (fromType == LengthTypePercentage || toType == LengthTypePercentage) {
+        float fromPercent = from->valueAsPercentage() * 100;
+        float toPercent = valueAsPercentage() * 100;
+        length->newValueSpecifiedUnits(LengthTypePercentage, WebCore::blend(fromPercent, toPercent, progress));
+        return length;
+    }
+
+    if (fromType == toType || from->isZero() || isZero() || fromType == LengthTypeEMS || fromType == LengthTypeEXS) {
+        float fromValue = from->valueInSpecifiedUnits();
+        float toValue = valueInSpecifiedUnits();
+        if (isZero())
+            length->newValueSpecifiedUnits(fromType, WebCore::blend(fromValue, toValue, progress));
+        else
+            length->newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress));
+        return length;
+    }
+
+    ASSERT(!isRelative());
+    ASSERT(!from->isRelative());
+
+    TrackExceptionState es;
+    SVGLengthContext nonRelativeLengthContext(0);
+    float fromValueInUserUnits = nonRelativeLengthContext.convertValueToUserUnits(from->valueInSpecifiedUnits(), from->unitMode(), fromType, es);
+    if (es.hadException())
+        return create();
+
+    float fromValue = nonRelativeLengthContext.convertValueFromUserUnits(fromValueInUserUnits, unitMode(), toType, es);
+    if (es.hadException())
+        return create();
+
+    float toValue = valueInSpecifiedUnits();
+    length->newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress));
+    return length;
+}
+
+void SVGLength::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement* contextElement)
+{
+    SVGLengthContext lengthContext(contextElement);
+
+    setValue(value(lengthContext) + toSVGLength(other)->value(lengthContext), lengthContext, ASSERT_NO_EXCEPTION);
+}
+
+void SVGLength::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement)
+{
+    RefPtr<SVGLength> fromLength = toSVGLength(fromValue);
+    RefPtr<SVGLength> toLength = toSVGLength(toValue);
+    RefPtr<SVGLength> toAtEndOfDurationLength = toSVGLength(toAtEndOfDurationValue);
+
+    SVGLengthContext lengthContext(contextElement);
+    float animatedNumber = value(lengthContext, IGNORE_EXCEPTION);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromLength->value(lengthContext, IGNORE_EXCEPTION), toLength->value(lengthContext, IGNORE_EXCEPTION), toAtEndOfDurationLength->value(lengthContext, IGNORE_EXCEPTION), animatedNumber);
+
+    ASSERT(unitMode() == lengthModeForAnimatedLengthAttribute(animationElement->attributeName()));
+    m_unitType = percentage < 0.5 ? fromLength->unitType() : toLength->unitType();
+    setValue(animatedNumber, lengthContext, ASSERT_NO_EXCEPTION);
+}
+
+float SVGLength::calculateDistance(PassRefPtr<NewSVGPropertyBase> toValue, SVGElement* contextElement)
+{
+    SVGLengthContext lengthContext(contextElement);
+    RefPtr<SVGLength> toLength = toSVGLength(toValue);
+
+    return fabsf(toLength->value(lengthContext, IGNORE_EXCEPTION) - value(lengthContext, IGNORE_EXCEPTION));
+}
+
 }
diff --git a/Source/core/svg/SVGLength.h b/Source/core/svg/SVGLength.h
index 3131050..fede46b 100644
--- a/Source/core/svg/SVGLength.h
+++ b/Source/core/svg/SVGLength.h
@@ -21,11 +21,11 @@
 #ifndef SVGLength_h
 #define SVGLength_h
 
-#include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/svg/SVGLengthContext.h"
-#include "core/svg/SVGParsingError.h"
-#include "core/svg/properties/SVGPropertyTraits.h"
-#include "platform/animation/AnimationUtilities.h"
+#include "core/svg/properties/NewSVGProperty.h"
+#include "heap/Handle.h"
 
 namespace WebCore {
 
@@ -38,58 +38,51 @@
     ForbidNegativeLengths
 };
 
-class SVGLength {
-    WTF_MAKE_FAST_ALLOCATED;
+class SVGLengthTearOff;
+
+class SVGLength FINAL : public NewSVGPropertyBase {
 public:
-    // Forward declare these enums in the w3c naming scheme, for IDL generation
-    enum {
-        SVG_LENGTHTYPE_UNKNOWN = LengthTypeUnknown,
-        SVG_LENGTHTYPE_NUMBER = LengthTypeNumber,
-        SVG_LENGTHTYPE_PERCENTAGE = LengthTypePercentage,
-        SVG_LENGTHTYPE_EMS = LengthTypeEMS,
-        SVG_LENGTHTYPE_EXS = LengthTypeEXS,
-        SVG_LENGTHTYPE_PX = LengthTypePX,
-        SVG_LENGTHTYPE_CM = LengthTypeCM,
-        SVG_LENGTHTYPE_MM = LengthTypeMM,
-        SVG_LENGTHTYPE_IN = LengthTypeIN,
-        SVG_LENGTHTYPE_PT = LengthTypePT,
-        SVG_LENGTHTYPE_PC = LengthTypePC
-    };
+    typedef SVGLengthTearOff TearOffType;
 
-    SVGLength(SVGLengthMode = LengthModeOther, const String& valueAsString = String());
-    SVGLength(const SVGLengthContext&, float, SVGLengthMode = LengthModeOther, SVGLengthType = LengthTypeNumber);
-    SVGLength(const SVGLength&);
+    static PassRefPtr<SVGLength> create(SVGLengthMode mode = LengthModeOther)
+    {
+        return adoptRef(new SVGLength(mode));
+    }
 
-    SVGLengthType unitType() const;
-    SVGLengthMode unitMode() const;
+    PassRefPtr<SVGLength> clone() const;
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+
+    SVGLengthType unitType() const { return static_cast<SVGLengthType>(m_unitType); }
+    void setUnitType(SVGLengthType);
+    SVGLengthMode unitMode() const { return static_cast<SVGLengthMode>(m_unitMode); }
 
     bool operator==(const SVGLength&) const;
-    bool operator!=(const SVGLength&) const;
+    bool operator!=(const SVGLength& other) const { return !operator==(other); }
 
-    static SVGLength construct(SVGLengthMode, const String&, SVGParsingError&, SVGLengthNegativeValuesMode = AllowNegativeLengths);
-
-    float value(const SVGLengthContext&) const;
+    float value(const SVGLengthContext& context) const
+    {
+        return value(context, IGNORE_EXCEPTION);
+    }
     float value(const SVGLengthContext&, ExceptionState&) const;
     void setValue(float, const SVGLengthContext&, ExceptionState&);
-    void setValue(const SVGLengthContext&, float, SVGLengthMode, SVGLengthType, ExceptionState&);
 
     float valueInSpecifiedUnits() const { return m_valueInSpecifiedUnits; }
     void setValueInSpecifiedUnits(float value) { m_valueInSpecifiedUnits = value; }
 
     float valueAsPercentage() const;
 
-    String valueAsString() const;
+    virtual String valueAsString() const OVERRIDE;
     void setValueAsString(const String&, ExceptionState&);
-    void setValueAsString(const String&, SVGLengthMode, ExceptionState&);
 
-    void newValueSpecifiedUnits(unsigned short, float valueInSpecifiedUnits, ExceptionState&);
-    void convertToSpecifiedUnits(unsigned short, const SVGLengthContext&, ExceptionState&);
+    void newValueSpecifiedUnits(SVGLengthType, float valueInSpecifiedUnits);
+    void convertToSpecifiedUnits(SVGLengthType, const SVGLengthContext&, ExceptionState&);
 
     // Helper functions
     inline bool isRelative() const
     {
-        SVGLengthType type = unitType();
-        return type == LengthTypePercentage || type == LengthTypeEMS || type == LengthTypeEXS;
+        return m_unitType == LengthTypePercentage
+            || m_unitType == LengthTypeEMS
+            || m_unitType == LengthTypeEXS;
     }
 
     bool isZero() const
@@ -97,77 +90,33 @@
         return !m_valueInSpecifiedUnits;
     }
 
-    static SVGLength fromCSSPrimitiveValue(CSSPrimitiveValue*);
-    static PassRefPtr<CSSPrimitiveValue> toCSSPrimitiveValue(const SVGLength&);
+    static PassRefPtr<SVGLength> fromCSSPrimitiveValue(CSSPrimitiveValue*);
+    static PassRefPtrWillBeRawPtr<CSSPrimitiveValue> toCSSPrimitiveValue(PassRefPtr<SVGLength>);
     static SVGLengthMode lengthModeForAnimatedLengthAttribute(const QualifiedName&);
 
-    SVGLength blend(const SVGLength& from, float progress) const
-    {
-        SVGLengthType toType = unitType();
-        SVGLengthType fromType = from.unitType();
-        if ((from.isZero() && isZero())
-            || fromType == LengthTypeUnknown
-            || toType == LengthTypeUnknown
-            || (!from.isZero() && fromType != LengthTypePercentage && toType == LengthTypePercentage)
-            || (!isZero() && fromType == LengthTypePercentage && toType != LengthTypePercentage)
-            || (!from.isZero() && !isZero() && (fromType == LengthTypeEMS || fromType == LengthTypeEXS) && fromType != toType))
-            return *this;
+    PassRefPtr<SVGLength> blend(PassRefPtr<SVGLength> from, float progress) const;
 
-        SVGLength length;
-        TrackExceptionState exceptionState;
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement) OVERRIDE;
 
-        if (fromType == LengthTypePercentage || toType == LengthTypePercentage) {
-            float fromPercent = from.valueAsPercentage() * 100;
-            float toPercent = valueAsPercentage() * 100;
-            length.newValueSpecifiedUnits(LengthTypePercentage, WebCore::blend(fromPercent, toPercent, progress), exceptionState);
-            if (exceptionState.hadException())
-                return SVGLength();
-            return length;
-        }
-
-        if (fromType == toType || from.isZero() || isZero() || fromType == LengthTypeEMS || fromType == LengthTypeEXS) {
-            float fromValue = from.valueInSpecifiedUnits();
-            float toValue = valueInSpecifiedUnits();
-            if (isZero())
-                length.newValueSpecifiedUnits(fromType, WebCore::blend(fromValue, toValue, progress), exceptionState);
-            else
-                length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), exceptionState);
-            if (exceptionState.hadException())
-                return SVGLength();
-            return length;
-        }
-
-        ASSERT(!isRelative());
-        ASSERT(!from.isRelative());
-
-        SVGLengthContext nonRelativeLengthContext(0);
-        float fromValueInUserUnits = nonRelativeLengthContext.convertValueToUserUnits(from.valueInSpecifiedUnits(), from.unitMode(), fromType, exceptionState);
-        if (exceptionState.hadException())
-            return SVGLength();
-
-        float fromValue = nonRelativeLengthContext.convertValueFromUserUnits(fromValueInUserUnits, unitMode(), toType, exceptionState);
-        if (exceptionState.hadException())
-            return SVGLength();
-
-        float toValue = valueInSpecifiedUnits();
-        length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), exceptionState);
-
-        if (exceptionState.hadException())
-            return SVGLength();
-        return length;
-    }
+    static AnimatedPropertyType classType() { return AnimatedLength; }
 
 private:
+    SVGLength(SVGLengthMode);
+    SVGLength(const SVGLength&);
+
     float m_valueInSpecifiedUnits;
-    unsigned int m_unit;
+    unsigned m_unitMode : 2;
+    unsigned m_unitType : 4;
 };
 
-template<>
-struct SVGPropertyTraits<SVGLength> {
-    static SVGLength initialValue() { return SVGLength(); }
-    static String toString(const SVGLength& type) { return type.valueAsString(); }
-};
-
+inline PassRefPtr<SVGLength> toSVGLength(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGLength::classType());
+    return static_pointer_cast<SVGLength>(base.release());
+}
 
 } // namespace WebCore
 
diff --git a/Source/core/svg/SVGLength.idl b/Source/core/svg/SVGLength.idl
index 4d29af7..97d9fea 100644
--- a/Source/core/svg/SVGLength.idl
+++ b/Source/core/svg/SVGLength.idl
@@ -20,7 +20,11 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface SVGLength {
+[
+    ImplementedAs=SVGLengthTearOff,
+    SetWrapperReferenceTo(SVGElement contextElement),
+    StrictTypeChecking,
+] interface SVGLength {
     // Length Unit Types
     const unsigned short SVG_LENGTHTYPE_UNKNOWN    = 0;
     const unsigned short SVG_LENGTHTYPE_NUMBER     = 1;
@@ -35,14 +39,13 @@
     const unsigned short SVG_LENGTHTYPE_PC         = 10;
 
     readonly attribute unsigned short unitType;
-    [Custom, StrictTypeChecking, RaisesException] attribute float value;
+    [RaisesException] attribute float value;
 
-    [StrictTypeChecking] attribute float valueInSpecifiedUnits;
-    [TreatNullAs=NullString, StrictTypeChecking, RaisesException=Setter] attribute DOMString valueAsString;
+    [RaisesException=Setter] attribute float valueInSpecifiedUnits;
+    [TreatNullAs=NullString, RaisesException=Setter] attribute DOMString valueAsString;
 
-    [StrictTypeChecking, RaisesException] void newValueSpecifiedUnits(unsigned short unitType,
-                                                     float valueInSpecifiedUnits);
+    [RaisesException] void newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits);
 
-    [Custom, StrictTypeChecking, RaisesException] void convertToSpecifiedUnits(unsigned short unitType);
+    [RaisesException] void convertToSpecifiedUnits(unsigned short unitType);
 };
 
diff --git a/Source/core/svg/SVGLengthContext.cpp b/Source/core/svg/SVGLengthContext.cpp
index 2c81747..d168eb5 100644
--- a/Source/core/svg/SVGLengthContext.cpp
+++ b/Source/core/svg/SVGLengthContext.cpp
@@ -47,43 +47,54 @@
 {
 }
 
-FloatRect SVGLengthContext::resolveRectangle(const SVGElement* context, SVGUnitTypes::SVGUnitType type, const FloatRect& viewport, const SVGLength& x, const SVGLength& y, const SVGLength& width, const SVGLength& height)
+FloatRect SVGLengthContext::resolveRectangle(const SVGElement* context, SVGUnitTypes::SVGUnitType type, const FloatRect& viewport, PassRefPtr<SVGLength> passX, PassRefPtr<SVGLength> passY, PassRefPtr<SVGLength> passWidth, PassRefPtr<SVGLength> passHeight)
 {
+    RefPtr<SVGLength> x = passX;
+    RefPtr<SVGLength> y = passY;
+    RefPtr<SVGLength> width = passWidth;
+    RefPtr<SVGLength> height = passHeight;
+
     ASSERT(type != SVGUnitTypes::SVG_UNIT_TYPE_UNKNOWN);
     if (type == SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE) {
         SVGLengthContext lengthContext(context);
-        return FloatRect(x.value(lengthContext), y.value(lengthContext), width.value(lengthContext), height.value(lengthContext));
+        return FloatRect(x->value(lengthContext), y->value(lengthContext), width->value(lengthContext), height->value(lengthContext));
     }
 
     SVGLengthContext lengthContext(context, viewport);
-    return FloatRect(x.value(lengthContext) + viewport.x(),
-                     y.value(lengthContext) + viewport.y(),
-                     width.value(lengthContext),
-                     height.value(lengthContext));
+    return FloatRect(
+        x->value(lengthContext) + viewport.x(),
+        y->value(lengthContext) + viewport.y(),
+        width->value(lengthContext),
+        height->value(lengthContext));
 }
 
-FloatPoint SVGLengthContext::resolvePoint(const SVGElement* context, SVGUnitTypes::SVGUnitType type, const SVGLength& x, const SVGLength& y)
+FloatPoint SVGLengthContext::resolvePoint(const SVGElement* context, SVGUnitTypes::SVGUnitType type, PassRefPtr<SVGLength> passX, PassRefPtr<SVGLength> passY)
 {
+    RefPtr<SVGLength> x = passX;
+    RefPtr<SVGLength> y = passY;
+
     ASSERT(type != SVGUnitTypes::SVG_UNIT_TYPE_UNKNOWN);
     if (type == SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE) {
         SVGLengthContext lengthContext(context);
-        return FloatPoint(x.value(lengthContext), y.value(lengthContext));
+        return FloatPoint(x->value(lengthContext), y->value(lengthContext));
     }
 
     // FIXME: valueAsPercentage() won't be correct for eg. cm units. They need to be resolved in user space and then be considered in objectBoundingBox space.
-    return FloatPoint(x.valueAsPercentage(), y.valueAsPercentage());
+    return FloatPoint(x->valueAsPercentage(), y->valueAsPercentage());
 }
 
-float SVGLengthContext::resolveLength(const SVGElement* context, SVGUnitTypes::SVGUnitType type, const SVGLength& x)
+float SVGLengthContext::resolveLength(const SVGElement* context, SVGUnitTypes::SVGUnitType type, PassRefPtr<SVGLength> passX)
 {
+    RefPtr<SVGLength> x = passX;
+
     ASSERT(type != SVGUnitTypes::SVG_UNIT_TYPE_UNKNOWN);
     if (type == SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE) {
         SVGLengthContext lengthContext(context);
-        return x.value(lengthContext);
+        return x->value(lengthContext);
     }
 
     // FIXME: valueAsPercentage() won't be correct for eg. cm units. They need to be resolved in user space and then be considered in objectBoundingBox space.
-    return x.valueAsPercentage();
+    return x->valueAsPercentage();
 }
 
 float SVGLengthContext::convertValueToUserUnits(float value, SVGLengthMode mode, SVGLengthType fromUnit, ExceptionState& exceptionState) const
@@ -98,7 +109,7 @@
 
     switch (fromUnit) {
     case LengthTypeUnknown:
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The fromUnit provided is invalid.");
         return 0;
     case LengthTypeNumber:
         return value;
@@ -130,7 +141,7 @@
 {
     switch (toUnit) {
     case LengthTypeUnknown:
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The toUnit provided is invalid.");
         return 0;
     case LengthTypeNumber:
         return value;
@@ -162,7 +173,7 @@
 {
     FloatSize viewportSize;
     if (!determineViewport(viewportSize)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The viewport could not be determined.");
         return 0;
     }
 
@@ -183,7 +194,7 @@
 {
     FloatSize viewportSize;
     if (!determineViewport(viewportSize)) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "The viewport could not be determined.");
         return 0;
     }
 
@@ -206,11 +217,11 @@
         return 0;
 
     const ContainerNode* currentContext = context;
-    while (currentContext) {
+    do {
         if (currentContext->renderer())
             return currentContext->renderer()->style();
         currentContext = currentContext->parentNode();
-    }
+    } while (currentContext);
 
     // There must be at least a RenderSVGRoot renderer, carrying a style.
     ASSERT_NOT_REACHED();
@@ -221,13 +232,13 @@
 {
     RenderStyle* style = renderStyleForLengthResolving(m_context);
     if (!style) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "No context could be found.");
         return 0;
     }
 
     float fontSize = style->specifiedFontSize();
     if (!fontSize) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "No font-size could be determined.");
         return 0;
     }
 
@@ -238,7 +249,7 @@
 {
     RenderStyle* style = renderStyleForLengthResolving(m_context);
     if (!style) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "No context could be found.");
         return 0;
     }
 
@@ -249,7 +260,7 @@
 {
     RenderStyle* style = renderStyleForLengthResolving(m_context);
     if (!style) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "No context could be found.");
         return 0;
     }
 
@@ -257,7 +268,7 @@
     // if this causes problems in real world cases maybe it would be best to remove this
     float xHeight = ceilf(style->fontMetrics().xHeight());
     if (!xHeight) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "No x-height could be determined.");
         return 0;
     }
 
@@ -268,7 +279,7 @@
 {
     RenderStyle* style = renderStyleForLengthResolving(m_context);
     if (!style) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+        exceptionState.throwDOMException(NotSupportedError, "No context could be found.");
         return 0;
     }
 
@@ -299,7 +310,7 @@
     if (!viewportElement || !viewportElement->isSVGSVGElement())
         return false;
 
-    const SVGSVGElement* svg = static_cast<const SVGSVGElement*>(viewportElement);
+    const SVGSVGElement* svg = toSVGSVGElement(viewportElement);
     viewportSize = svg->currentViewBoxRect().size();
     if (viewportSize.isEmpty())
         viewportSize = svg->currentViewportSize();
diff --git a/Source/core/svg/SVGLengthContext.h b/Source/core/svg/SVGLengthContext.h
index 64c2370..5ad5c6a 100644
--- a/Source/core/svg/SVGLengthContext.h
+++ b/Source/core/svg/SVGLengthContext.h
@@ -56,12 +56,12 @@
     template<typename T>
     static FloatRect resolveRectangle(const T* context, SVGUnitTypes::SVGUnitType type, const FloatRect& viewport)
     {
-        return SVGLengthContext::resolveRectangle(context, type, viewport, context->xCurrentValue(), context->yCurrentValue(), context->widthCurrentValue(), context->heightCurrentValue());
+        return SVGLengthContext::resolveRectangle(context, type, viewport, context->x()->currentValue(), context->y()->currentValue(), context->width()->currentValue(), context->height()->currentValue());
     }
 
-    static FloatRect resolveRectangle(const SVGElement*, SVGUnitTypes::SVGUnitType, const FloatRect& viewport, const SVGLength& x, const SVGLength& y, const SVGLength& width, const SVGLength& height);
-    static FloatPoint resolvePoint(const SVGElement*, SVGUnitTypes::SVGUnitType, const SVGLength& x, const SVGLength& y);
-    static float resolveLength(const SVGElement*, SVGUnitTypes::SVGUnitType, const SVGLength&);
+    static FloatRect resolveRectangle(const SVGElement*, SVGUnitTypes::SVGUnitType, const FloatRect& viewport, PassRefPtr<SVGLength> x, PassRefPtr<SVGLength> y, PassRefPtr<SVGLength> width, PassRefPtr<SVGLength> height);
+    static FloatPoint resolvePoint(const SVGElement*, SVGUnitTypes::SVGUnitType, PassRefPtr<SVGLength> x, PassRefPtr<SVGLength> y);
+    static float resolveLength(const SVGElement*, SVGUnitTypes::SVGUnitType, PassRefPtr<SVGLength>);
 
     float convertValueToUserUnits(float, SVGLengthMode, SVGLengthType fromUnit, ExceptionState&) const;
     float convertValueFromUserUnits(float, SVGLengthMode, SVGLengthType toUnit, ExceptionState&) const;
diff --git a/Source/core/svg/SVGLengthList.cpp b/Source/core/svg/SVGLengthList.cpp
index 1518d2c..e6dbf56 100644
--- a/Source/core/svg/SVGLengthList.cpp
+++ b/Source/core/svg/SVGLengthList.cpp
@@ -21,17 +21,66 @@
 #include "config.h"
 #include "core/svg/SVGLengthList.h"
 
-#include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/svg/SVGAnimationElement.h"
 #include "core/svg/SVGParserUtilities.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
-template<typename CharType>
-void SVGLengthList::parseInternal(const CharType*& ptr, const CharType* end, SVGLengthMode mode)
+inline PassRefPtr<SVGLengthList> toSVGLengthList(PassRefPtr<NewSVGPropertyBase> passBase)
 {
-    TrackExceptionState exceptionState;
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGLengthList::classType());
+    return static_pointer_cast<SVGLengthList>(base.release());
+}
 
+SVGLengthList::SVGLengthList(SVGLengthMode mode)
+    : m_mode(mode)
+{
+}
+
+SVGLengthList::~SVGLengthList()
+{
+}
+
+PassRefPtr<SVGLengthList> SVGLengthList::clone()
+{
+    RefPtr<SVGLengthList> ret = SVGLengthList::create(m_mode);
+    ret->deepCopy(this);
+    return ret.release();
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGLengthList::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGLengthList> ret = SVGLengthList::create(m_mode);
+    ret->setValueAsString(value, IGNORE_EXCEPTION);
+    return ret.release();
+}
+
+String SVGLengthList::valueAsString() const
+{
+    StringBuilder builder;
+
+    ConstIterator it = begin();
+    ConstIterator itEnd = end();
+    if (it != itEnd) {
+        builder.append(it->valueAsString());
+        ++it;
+
+        for (; it != itEnd; ++it) {
+            builder.append(' ');
+            builder.append(it->valueAsString());
+        }
+    }
+
+    return builder.toString();
+}
+
+template <typename CharType>
+void SVGLengthList::parseInternal(const CharType*& ptr, const CharType* end, ExceptionState& exceptionState)
+{
+    clear();
     while (ptr < end) {
         const CharType* start = ptr;
         while (ptr < end && *ptr != ',' && !isSVGSpace(*ptr))
@@ -39,11 +88,11 @@
         if (ptr == start)
             break;
 
-        SVGLength length(mode);
+        RefPtr<SVGLength> length = SVGLength::create(m_mode);
         String valueString(start, ptr - start);
         if (valueString.isEmpty())
             return;
-        length.setValueAsString(valueString, exceptionState);
+        length->setValueAsString(valueString, exceptionState);
         if (exceptionState.hadException())
             return;
         append(length);
@@ -51,35 +100,103 @@
     }
 }
 
-void SVGLengthList::parse(const String& value, SVGLengthMode mode)
+void SVGLengthList::setValueAsString(const String& value, ExceptionState& exceptionState)
 {
-    clear();
     if (value.isEmpty())
         return;
     if (value.is8Bit()) {
         const LChar* ptr = value.characters8();
         const LChar* end = ptr + value.length();
-        parseInternal(ptr, end, mode);
+        parseInternal(ptr, end, exceptionState);
     } else {
         const UChar* ptr = value.characters16();
         const UChar* end = ptr + value.length();
-        parseInternal(ptr, end, mode);
+        parseInternal(ptr, end, exceptionState);
     }
 }
 
-String SVGLengthList::valueAsString() const
+void SVGLengthList::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement* contextElement)
 {
-    StringBuilder builder;
+    RefPtr<SVGLengthList> otherList = toSVGLengthList(other);
 
-    unsigned size = this->size();
-    for (unsigned i = 0; i < size; ++i) {
-        if (i > 0)
-            builder.append(' ');
+    if (numberOfItems() != otherList->numberOfItems())
+        return;
 
-        builder.append(at(i).valueAsString());
-    }
-
-    return builder.toString();
+    SVGLengthContext lengthContext(contextElement);
+    for (size_t i = 0; i < numberOfItems(); ++i)
+        at(i)->setValue(at(i)->value(lengthContext) + otherList->at(i)->value(lengthContext), lengthContext, ASSERT_NO_EXCEPTION);
 }
 
+bool SVGLengthList::adjustFromToListValues(PassRefPtr<SVGLengthList> passFromList, PassRefPtr<SVGLengthList> passToList, float percentage, bool isToAnimation, bool resizeAnimatedListIfNeeded)
+{
+    RefPtr<SVGLengthList> fromList = passFromList;
+    RefPtr<SVGLengthList> toList = passToList;
+
+    // If no 'to' value is given, nothing to animate.
+    size_t toListSize = toList->numberOfItems();
+    if (!toListSize)
+        return false;
+
+    // If the 'from' value is given and it's length doesn't match the 'to' value list length, fallback to a discrete animation.
+    size_t fromListSize = fromList->numberOfItems();
+    if (fromListSize != toListSize && fromListSize) {
+        if (percentage < 0.5) {
+            if (!isToAnimation)
+                deepCopy(fromList);
+        } else {
+            deepCopy(toList);
+        }
+
+        return false;
+    }
+
+    ASSERT(!fromListSize || fromListSize == toListSize);
+    if (resizeAnimatedListIfNeeded && numberOfItems() < toListSize) {
+        size_t paddingCount = toListSize - numberOfItems();
+        for (size_t i = 0; i < paddingCount; ++i)
+            append(SVGLength::create(m_mode));
+    }
+
+    return true;
+}
+
+void SVGLengthList::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement)
+{
+    RefPtr<SVGLengthList> fromList = toSVGLengthList(fromValue);
+    RefPtr<SVGLengthList> toList = toSVGLengthList(toValue);
+    RefPtr<SVGLengthList> toAtEndOfDurationList = toSVGLengthList(toAtEndOfDurationValue);
+
+    SVGLengthContext lengthContext(contextElement);
+    ASSERT(m_mode == SVGLength::lengthModeForAnimatedLengthAttribute(animationElement->attributeName()));
+
+    size_t fromLengthListSize = fromList->numberOfItems();
+    size_t toLengthListSize = toList->numberOfItems();
+    size_t toAtEndOfDurationListSize = toAtEndOfDurationList->numberOfItems();
+
+    if (!adjustFromToListValues(fromList, toList, percentage, animationElement->animationMode() == ToAnimation, true))
+        return;
+
+    for (size_t i = 0; i < toLengthListSize; ++i) {
+        float animatedNumber = at(i)->value(lengthContext);
+        SVGLengthType unitType = toList->at(i)->unitType();
+        float effectiveFrom = 0;
+        if (fromLengthListSize) {
+            if (percentage < 0.5)
+                unitType = fromList->at(i)->unitType();
+            effectiveFrom = fromList->at(i)->value(lengthContext);
+        }
+        float effectiveTo = toList->at(i)->value(lengthContext);
+        float effectiveToAtEnd = i < toAtEndOfDurationListSize ? toAtEndOfDurationList->at(i)->value(lengthContext) : 0;
+
+        animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom, effectiveTo, effectiveToAtEnd, animatedNumber);
+        at(i)->setUnitType(unitType);
+        at(i)->setValue(animatedNumber, lengthContext, ASSERT_NO_EXCEPTION);
+    }
+}
+
+float SVGLengthList::calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*)
+{
+    // FIXME: Distance calculation is not possible for SVGLengthList right now. We need the distance for every single value.
+    return -1;
+}
 }
diff --git a/Source/core/svg/SVGLengthList.h b/Source/core/svg/SVGLengthList.h
index 12afeed..0b65bad 100644
--- a/Source/core/svg/SVGLengthList.h
+++ b/Source/core/svg/SVGLengthList.h
@@ -1,51 +1,80 @@
 /*
- * Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGLengthList_h
 #define SVGLengthList_h
 
+#include "bindings/v8/ScriptWrappable.h"
 #include "core/svg/SVGLength.h"
-#include "wtf/Vector.h"
+#include "core/svg/properties/NewSVGListPropertyHelper.h"
 
 namespace WebCore {
 
-class SVGLengthList : public Vector<SVGLength> {
-public:
-    SVGLengthList() { }
+class SVGLengthListTearOff;
 
-    void parse(const String& value, SVGLengthMode);
-    String valueAsString() const;
+class SVGLengthList FINAL : public NewSVGListPropertyHelper<SVGLengthList, SVGLength> {
+public:
+    typedef SVGLengthListTearOff TearOffType;
+
+    static PassRefPtr<SVGLengthList> create(SVGLengthMode mode = LengthModeOther)
+    {
+        return adoptRef(new SVGLengthList(mode));
+    }
+
+    virtual ~SVGLengthList();
+
+    PassRefPtr<SVGLengthList> clone();
+
+    void setValueAsString(const String&, ExceptionState&);
+
+    // NewSVGPropertyBase:
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+    virtual String valueAsString() const OVERRIDE;
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedLengthList; }
 
 private:
-    template<typename CharType>
-    void parseInternal(const CharType*& ptr, const CharType* end, SVGLengthMode);
-};
+    explicit SVGLengthList(SVGLengthMode);
 
-template<>
-struct SVGPropertyTraits<SVGLengthList> {
-    typedef SVGLength ListItemType;
+    bool adjustFromToListValues(PassRefPtr<SVGLengthList> fromList, PassRefPtr<SVGLengthList> toList, float percentage, bool isToAnimation, bool resizeAnimatedListIfNeeded);
 
-    static SVGLengthList initialValue() { return SVGLengthList(); }
-    static String toString(const SVGLengthList& type) { return type.valueAsString(); }
+    template <typename CharType>
+    void parseInternal(const CharType*& ptr, const CharType* end, ExceptionState&);
+
+    SVGLengthMode m_mode;
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGLengthList_h
diff --git a/Source/core/svg/SVGLengthList.idl b/Source/core/svg/SVGLengthList.idl
index 4149ab6..eb9e607 100644
--- a/Source/core/svg/SVGLengthList.idl
+++ b/Source/core/svg/SVGLengthList.idl
@@ -24,15 +24,19 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGLengthList {
+[
+    ImplementedAs=SVGLengthListTearOff,
+    SetWrapperReferenceTo(SVGElement contextElement),
+    StrictTypeChecking,
+] interface SVGLengthList {
     readonly attribute unsigned long numberOfItems;
 
     [RaisesException] void clear();
-    [StrictTypeChecking, RaisesException] SVGLength initialize(SVGLength item);
-    [StrictTypeChecking, RaisesException] SVGLength getItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGLength insertItemBefore(SVGLength item, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGLength replaceItem(SVGLength item, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGLength removeItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGLength appendItem(SVGLength item);
+    [RaisesException] SVGLength initialize(SVGLength item);
+    [RaisesException] SVGLength getItem(unsigned long index);
+    [RaisesException] SVGLength insertItemBefore(SVGLength item, unsigned long index);
+    [RaisesException] SVGLength replaceItem(SVGLength item, unsigned long index);
+    [RaisesException] SVGLength removeItem(unsigned long index);
+    [RaisesException] SVGLength appendItem(SVGLength item);
 };
 
diff --git a/Source/core/svg/SVGLengthListTearOff.h b/Source/core/svg/SVGLengthListTearOff.h
new file mode 100644
index 0000000..b28dc8c
--- /dev/null
+++ b/Source/core/svg/SVGLengthListTearOff.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGLengthListTearOff_h
+#define SVGLengthListTearOff_h
+
+#include "core/svg/SVGLengthList.h"
+#include "core/svg/properties/NewSVGListPropertyTearOffHelper.h"
+
+namespace WebCore {
+
+class SVGLengthListTearOff FINAL :
+    public NewSVGListPropertyTearOffHelper<SVGLengthListTearOff, SVGLengthList>,
+    public ScriptWrappable {
+public:
+    static PassRefPtr<SVGLengthListTearOff> create(PassRefPtr<SVGLengthList> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+    {
+        return adoptRef(new SVGLengthListTearOff(target, contextElement, propertyIsAnimVal, attributeName));
+    }
+
+private:
+    SVGLengthListTearOff(PassRefPtr<SVGLengthList> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+        : NewSVGListPropertyTearOffHelper<SVGLengthListTearOff, SVGLengthList>(target, contextElement, propertyIsAnimVal, attributeName)
+    {
+        ScriptWrappable::init(this);
+    }
+};
+
+} // namespace WebCore
+
+#endif // SVGLengthListTearOff_h_
diff --git a/Source/core/svg/SVGLengthTearOff.cpp b/Source/core/svg/SVGLengthTearOff.cpp
new file mode 100644
index 0000000..04efb56
--- /dev/null
+++ b/Source/core/svg/SVGLengthTearOff.cpp
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+
+#include "core/svg/SVGLengthTearOff.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+
+namespace WebCore {
+
+namespace {
+
+inline SVGLengthType toSVGLengthType(unsigned short type)
+{
+    ASSERT(type >= LengthTypeUnknown && type <= LengthTypePC);
+    return static_cast<SVGLengthType>(type);
+}
+
+} // namespace
+
+SVGLengthType SVGLengthTearOff::unitType()
+{
+    return target()->unitType();
+}
+
+SVGLengthMode SVGLengthTearOff::unitMode()
+{
+    return target()->unitMode();
+}
+
+float SVGLengthTearOff::value(ExceptionState& es)
+{
+    SVGLengthContext lengthContext(contextElement());
+    return target()->value(lengthContext, es);
+}
+
+void SVGLengthTearOff::setValue(float value, ExceptionState& es)
+{
+    if (isImmutable()) {
+        es.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    SVGLengthContext lengthContext(contextElement());
+    target()->setValue(value, lengthContext, es);
+    commitChange();
+}
+
+float SVGLengthTearOff::valueInSpecifiedUnits()
+{
+    return target()->valueInSpecifiedUnits();
+}
+
+void SVGLengthTearOff::setValueInSpecifiedUnits(float value, ExceptionState& es)
+{
+    if (isImmutable()) {
+        es.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+    target()->setValueInSpecifiedUnits(value);
+    commitChange();
+}
+
+String SVGLengthTearOff::valueAsString()
+{
+    return target()->valueAsString();
+}
+
+void SVGLengthTearOff::setValueAsString(const String& str, ExceptionState& es)
+{
+    if (isImmutable()) {
+        es.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    target()->setValueAsString(str, es);
+    commitChange();
+}
+
+void SVGLengthTearOff::newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits, ExceptionState& exceptionState)
+{
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+        return;
+    }
+
+    if (unitType == LengthTypeUnknown || unitType > LengthTypePC) {
+        exceptionState.throwDOMException(NotSupportedError, "Cannot set value with unknown or invalid units (" + String::number(unitType) + ").");
+        return;
+    }
+
+    target()->newValueSpecifiedUnits(toSVGLengthType(unitType), valueInSpecifiedUnits);
+    commitChange();
+}
+
+void SVGLengthTearOff::convertToSpecifiedUnits(unsigned short unitType, ExceptionState& exceptionState)
+{
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+        return;
+    }
+
+    if (unitType == LengthTypeUnknown || unitType > LengthTypePC) {
+        exceptionState.throwDOMException(NotSupportedError, "Cannot convert to unknown or invalid units (" + String::number(unitType) + ").");
+        return;
+    }
+
+    SVGLengthContext lengthContext(contextElement());
+    target()->convertToSpecifiedUnits(toSVGLengthType(unitType), lengthContext, exceptionState);
+    commitChange();
+}
+
+SVGLengthTearOff::SVGLengthTearOff(PassRefPtr<SVGLength> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName)
+    : NewSVGPropertyTearOff<SVGLength>(target, contextElement, propertyIsAnimVal, attributeName)
+{
+    ScriptWrappable::init(this);
+}
+
+}
diff --git a/Source/core/svg/SVGLengthTearOff.h b/Source/core/svg/SVGLengthTearOff.h
new file mode 100644
index 0000000..2b98949
--- /dev/null
+++ b/Source/core/svg/SVGLengthTearOff.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGLengthTearOff_h
+#define SVGLengthTearOff_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/svg/SVGLength.h"
+#include "core/svg/properties/NewSVGPropertyTearOff.h"
+
+namespace WebCore {
+
+class SVGLengthTearOff FINAL : public NewSVGPropertyTearOff<SVGLength>, public ScriptWrappable {
+public:
+    // Forward declare these enums in the w3c naming scheme, for IDL generation
+    enum {
+        SVG_LENGTHTYPE_UNKNOWN = LengthTypeUnknown,
+        SVG_LENGTHTYPE_NUMBER = LengthTypeNumber,
+        SVG_LENGTHTYPE_PERCENTAGE = LengthTypePercentage,
+        SVG_LENGTHTYPE_EMS = LengthTypeEMS,
+        SVG_LENGTHTYPE_EXS = LengthTypeEXS,
+        SVG_LENGTHTYPE_PX = LengthTypePX,
+        SVG_LENGTHTYPE_CM = LengthTypeCM,
+        SVG_LENGTHTYPE_MM = LengthTypeMM,
+        SVG_LENGTHTYPE_IN = LengthTypeIN,
+        SVG_LENGTHTYPE_PT = LengthTypePT,
+        SVG_LENGTHTYPE_PC = LengthTypePC
+    };
+
+    static PassRefPtr<SVGLengthTearOff> create(PassRefPtr<SVGLength> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+    {
+        return adoptRef(new SVGLengthTearOff(target, contextElement, propertyIsAnimVal, attributeName));
+    }
+
+    SVGLengthType unitType();
+    SVGLengthMode unitMode();
+    float value(ExceptionState&);
+    void setValue(float value, ExceptionState&);
+    float valueInSpecifiedUnits();
+    void setValueInSpecifiedUnits(float value, ExceptionState&);
+    String valueAsString();
+    void setValueAsString(const String&, ExceptionState&);
+    void newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits, ExceptionState&);
+    void convertToSpecifiedUnits(unsigned short unitType, ExceptionState&);
+
+private:
+    SVGLengthTearOff(PassRefPtr<SVGLength>, SVGElement* contextElement, PropertyIsAnimValType, const QualifiedName& attributeName = nullQName());
+};
+
+} // namespace WebCore
+
+#endif // SVGLengthTearOff_h_
diff --git a/Source/core/svg/SVGLineElement.cpp b/Source/core/svg/SVGLineElement.cpp
index 9cd4a6e..1d9f7e9 100644
--- a/Source/core/svg/SVGLineElement.cpp
+++ b/Source/core/svg/SVGLineElement.cpp
@@ -29,29 +29,23 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGLineElement, SVGNames::x1Attr, X1, x1)
-DEFINE_ANIMATED_LENGTH(SVGLineElement, SVGNames::y1Attr, Y1, y1)
-DEFINE_ANIMATED_LENGTH(SVGLineElement, SVGNames::x2Attr, X2, x2)
-DEFINE_ANIMATED_LENGTH(SVGLineElement, SVGNames::y2Attr, Y2, y2)
-DEFINE_ANIMATED_BOOLEAN(SVGLineElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGLineElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x2)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y2)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGLineElement::SVGLineElement(Document& document)
     : SVGGeometryElement(SVGNames::lineTag, document)
-    , m_x1(LengthModeWidth)
-    , m_y1(LengthModeHeight)
-    , m_x2(LengthModeWidth)
-    , m_y2(LengthModeHeight)
+    , m_x1(SVGAnimatedLength::create(this, SVGNames::x1Attr, SVGLength::create(LengthModeWidth)))
+    , m_y1(SVGAnimatedLength::create(this, SVGNames::y1Attr, SVGLength::create(LengthModeHeight)))
+    , m_x2(SVGAnimatedLength::create(this, SVGNames::x2Attr, SVGLength::create(LengthModeWidth)))
+    , m_y2(SVGAnimatedLength::create(this, SVGNames::y2Attr, SVGLength::create(LengthModeHeight)))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_x1);
+    addToPropertyMap(m_y1);
+    addToPropertyMap(m_x2);
+    addToPropertyMap(m_y2);
     registerAnimatedPropertiesForSVGLineElement();
 }
 
@@ -64,8 +58,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGLangSpace::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::x1Attr);
         supportedAttributes.add(SVGNames::x2Attr);
         supportedAttributes.add(SVGNames::y1Attr);
@@ -81,16 +73,14 @@
     if (!isSupportedAttribute(name))
         SVGGeometryElement::parseAttribute(name, value);
     else if (name == SVGNames::x1Attr)
-        setX1BaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_x1->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::y1Attr)
-        setY1BaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_y1->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::x2Attr)
-        setX2BaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_x2->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::y2Attr)
-        setY2BaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (SVGLangSpace::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)) {
-    } else
+        m_y2->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    else
         ASSERT_NOT_REACHED();
 
     reportAttributeParsingError(parseError, name, value);
@@ -123,20 +113,15 @@
         return;
     }
 
-    if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
-        RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
-        return;
-    }
-
     ASSERT_NOT_REACHED();
 }
 
 bool SVGLineElement::selfHasRelativeLengths() const
 {
-    return x1CurrentValue().isRelative()
-        || y1CurrentValue().isRelative()
-        || x2CurrentValue().isRelative()
-        || y2CurrentValue().isRelative();
+    return m_x1->currentValue()->isRelative()
+        || m_y1->currentValue()->isRelative()
+        || m_x2->currentValue()->isRelative()
+        || m_y2->currentValue()->isRelative();
 }
 
 }
diff --git a/Source/core/svg/SVGLineElement.h b/Source/core/svg/SVGLineElement.h
index 68b961a..59a25be 100644
--- a/Source/core/svg/SVGLineElement.h
+++ b/Source/core/svg/SVGLineElement.h
@@ -24,36 +24,37 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGeometryElement.h"
 
 namespace WebCore {
 
-class SVGLineElement FINAL : public SVGGeometryElement,
-                             public SVGExternalResourcesRequired {
+class SVGLineElement FINAL : public SVGGeometryElement {
 public:
     static PassRefPtr<SVGLineElement> create(Document&);
 
+    SVGAnimatedLength* x1() const { return m_x1.get(); }
+    SVGAnimatedLength* y1() const { return m_y1.get(); }
+    SVGAnimatedLength* x2() const { return m_x2.get(); }
+    SVGAnimatedLength* y2() const { return m_y2.get(); }
+
 private:
     explicit SVGLineElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual bool supportsMarkers() const { return true; }
+    virtual bool supportsMarkers() const OVERRIDE { return true; }
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_x1;
+    RefPtr<SVGAnimatedLength> m_y1;
+    RefPtr<SVGAnimatedLength> m_x2;
+    RefPtr<SVGAnimatedLength> m_y2;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGLineElement)
-        DECLARE_ANIMATED_LENGTH(X1, x1)
-        DECLARE_ANIMATED_LENGTH(Y1, y1)
-        DECLARE_ANIMATED_LENGTH(X2, x2)
-        DECLARE_ANIMATED_LENGTH(Y2, y2)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGLineElement.idl b/Source/core/svg/SVGLineElement.idl
index a12e80b..5adea6f 100644
--- a/Source/core/svg/SVGLineElement.idl
+++ b/Source/core/svg/SVGLineElement.idl
@@ -30,5 +30,3 @@
     readonly attribute SVGAnimatedLength y2;
 };
 
-SVGLineElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGLinearGradientElement.cpp b/Source/core/svg/SVGLinearGradientElement.cpp
index 84cdebe..205f232 100644
--- a/Source/core/svg/SVGLinearGradientElement.cpp
+++ b/Source/core/svg/SVGLinearGradientElement.cpp
@@ -34,28 +34,26 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGLinearGradientElement, SVGNames::x1Attr, X1, x1)
-DEFINE_ANIMATED_LENGTH(SVGLinearGradientElement, SVGNames::y1Attr, Y1, y1)
-DEFINE_ANIMATED_LENGTH(SVGLinearGradientElement, SVGNames::x2Attr, X2, x2)
-DEFINE_ANIMATED_LENGTH(SVGLinearGradientElement, SVGNames::y2Attr, Y2, y2)
-
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGLinearGradientElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y1)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x2)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y2)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGradientElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGLinearGradientElement::SVGLinearGradientElement(Document& document)
     : SVGGradientElement(SVGNames::linearGradientTag, document)
-    , m_x1(LengthModeWidth)
-    , m_y1(LengthModeHeight)
-    , m_x2(LengthModeWidth, "100%")
-    , m_y2(LengthModeHeight)
+    , m_x1(SVGAnimatedLength::create(this, SVGNames::x1Attr, SVGLength::create(LengthModeWidth)))
+    , m_y1(SVGAnimatedLength::create(this, SVGNames::y1Attr, SVGLength::create(LengthModeHeight)))
+    , m_x2(SVGAnimatedLength::create(this, SVGNames::x2Attr, SVGLength::create(LengthModeWidth)))
+    , m_y2(SVGAnimatedLength::create(this, SVGNames::y2Attr, SVGLength::create(LengthModeHeight)))
 {
-    // Spec: If the x2 attribute is not specified, the effect is as if a value of "100%" were specified.
     ScriptWrappable::init(this);
+
+    // Spec: If the x2 attribute is not specified, the effect is as if a value of "100%" were specified.
+    m_x2->setDefaultValueAsString("100%");
+
+    addToPropertyMap(m_x1);
+    addToPropertyMap(m_y1);
+    addToPropertyMap(m_x2);
+    addToPropertyMap(m_y2);
     registerAnimatedPropertiesForSVGLinearGradientElement();
 }
 
@@ -83,13 +81,13 @@
     if (!isSupportedAttribute(name))
         SVGGradientElement::parseAttribute(name, value);
     else if (name == SVGNames::x1Attr)
-        setX1BaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_x1->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::y1Attr)
-        setY1BaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_y1->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::x2Attr)
-        setX2BaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_x2->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::y2Attr)
-        setY2BaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_y2->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else
         ASSERT_NOT_REACHED();
 
@@ -117,78 +115,84 @@
     return new RenderSVGResourceLinearGradient(this);
 }
 
+static void setGradientAttributes(SVGGradientElement* element, LinearGradientAttributes& attributes, bool isLinear = true)
+{
+    if (!attributes.hasSpreadMethod() && element->spreadMethodSpecified())
+        attributes.setSpreadMethod(element->spreadMethodCurrentValue());
+
+    if (!attributes.hasGradientUnits() && element->gradientUnitsSpecified())
+        attributes.setGradientUnits(element->gradientUnitsCurrentValue());
+
+    if (!attributes.hasGradientTransform() && element->gradientTransformSpecified()) {
+        AffineTransform transform;
+        element->gradientTransformCurrentValue().concatenate(transform);
+        attributes.setGradientTransform(transform);
+    }
+
+    if (!attributes.hasStops()) {
+        const Vector<Gradient::ColorStop>& stops(element->buildStops());
+        if (!stops.isEmpty())
+            attributes.setStops(stops);
+    }
+
+    if (isLinear) {
+        SVGLinearGradientElement* linear = toSVGLinearGradientElement(element);
+
+        if (!attributes.hasX1() && linear->x1()->isSpecified())
+            attributes.setX1(linear->x1()->currentValue());
+
+        if (!attributes.hasY1() && linear->y1()->isSpecified())
+            attributes.setY1(linear->y1()->currentValue());
+
+        if (!attributes.hasX2() && linear->x2()->isSpecified())
+            attributes.setX2(linear->x2()->currentValue());
+
+        if (!attributes.hasY2() && linear->y2()->isSpecified())
+            attributes.setY2(linear->y2()->currentValue());
+    }
+}
+
 bool SVGLinearGradientElement::collectGradientAttributes(LinearGradientAttributes& attributes)
 {
-    HashSet<SVGGradientElement*> processedGradients;
+    if (!renderer())
+        return false;
 
-    bool isLinear = true;
+    HashSet<SVGGradientElement*> processedGradients;
     SVGGradientElement* current = this;
 
-    while (current) {
-        if (!current->renderer())
-            return false;
+    setGradientAttributes(current, attributes);
+    processedGradients.add(current);
 
-        if (!attributes.hasSpreadMethod() && current->hasAttribute(SVGNames::spreadMethodAttr))
-            attributes.setSpreadMethod(current->spreadMethodCurrentValue());
-
-        if (!attributes.hasGradientUnits() && current->hasAttribute(SVGNames::gradientUnitsAttr))
-            attributes.setGradientUnits(current->gradientUnitsCurrentValue());
-
-        if (!attributes.hasGradientTransform() && current->hasAttribute(SVGNames::gradientTransformAttr)) {
-            AffineTransform transform;
-            current->gradientTransformCurrentValue().concatenate(transform);
-            attributes.setGradientTransform(transform);
-        }
-
-        if (!attributes.hasStops()) {
-            const Vector<Gradient::ColorStop>& stops(current->buildStops());
-            if (!stops.isEmpty())
-                attributes.setStops(stops);
-        }
-
-        if (isLinear) {
-            SVGLinearGradientElement* linear = toSVGLinearGradientElement(current);
-
-            if (!attributes.hasX1() && current->hasAttribute(SVGNames::x1Attr))
-                attributes.setX1(linear->x1CurrentValue());
-
-            if (!attributes.hasY1() && current->hasAttribute(SVGNames::y1Attr))
-                attributes.setY1(linear->y1CurrentValue());
-
-            if (!attributes.hasX2() && current->hasAttribute(SVGNames::x2Attr))
-                attributes.setX2(linear->x2CurrentValue());
-
-            if (!attributes.hasY2() && current->hasAttribute(SVGNames::y2Attr))
-                attributes.setY2(linear->y2CurrentValue());
-        }
-
-        processedGradients.add(current);
-
+    while (true) {
         // Respect xlink:href, take attributes from referenced element
-        Node* refNode = SVGURIReference::targetElementFromIRIString(current->hrefCurrentValue(), document());
-        if (refNode && (refNode->hasTagName(SVGNames::linearGradientTag) || refNode->hasTagName(SVGNames::radialGradientTag))) {
+        Node* refNode = SVGURIReference::targetElementFromIRIString(current->href()->currentValue()->value(), document());
+        if (refNode && isSVGGradientElement(*refNode)) {
             current = toSVGGradientElement(refNode);
 
             // Cycle detection
-            if (processedGradients.contains(current)) {
-                current = 0;
-                break;
-            }
+            if (processedGradients.contains(current))
+                return true;
 
-            isLinear = current->hasTagName(SVGNames::linearGradientTag);
-        } else
-            current = 0;
+            if (!current->renderer())
+                return false;
+
+            setGradientAttributes(current, attributes, current->hasTagName(SVGNames::linearGradientTag));
+            processedGradients.add(current);
+        } else {
+            return true;
+        }
     }
 
-    return true;
+    ASSERT_NOT_REACHED();
+    return false;
 }
 
 bool SVGLinearGradientElement::selfHasRelativeLengths() const
 {
-    return x1CurrentValue().isRelative()
-        || y1CurrentValue().isRelative()
-        || x2CurrentValue().isRelative()
-        || y2CurrentValue().isRelative();
+    return m_x1->currentValue()->isRelative()
+        || m_y1->currentValue()->isRelative()
+        || m_x2->currentValue()->isRelative()
+        || m_y2->currentValue()->isRelative();
 }
 
 }
diff --git a/Source/core/svg/SVGLinearGradientElement.h b/Source/core/svg/SVGLinearGradientElement.h
index 179424e..58ad6d4 100644
--- a/Source/core/svg/SVGLinearGradientElement.h
+++ b/Source/core/svg/SVGLinearGradientElement.h
@@ -35,22 +35,27 @@
 
     bool collectGradientAttributes(LinearGradientAttributes&);
 
+    SVGAnimatedLength* x1() const { return m_x1.get(); }
+    SVGAnimatedLength* y1() const { return m_y1.get(); }
+    SVGAnimatedLength* x2() const { return m_x2.get(); }
+    SVGAnimatedLength* y2() const { return m_y2.get(); }
+
 private:
     explicit SVGLinearGradientElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_x1;
+    RefPtr<SVGAnimatedLength> m_y1;
+    RefPtr<SVGAnimatedLength> m_x2;
+    RefPtr<SVGAnimatedLength> m_y2;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGLinearGradientElement)
-        DECLARE_ANIMATED_LENGTH(X1, x1)
-        DECLARE_ANIMATED_LENGTH(Y1, y1)
-        DECLARE_ANIMATED_LENGTH(X2, x2)
-        DECLARE_ANIMATED_LENGTH(Y2, y2)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGMPathElement.cpp b/Source/core/svg/SVGMPathElement.cpp
index 058738f..155f96b 100644
--- a/Source/core/svg/SVGMPathElement.cpp
+++ b/Source/core/svg/SVGMPathElement.cpp
@@ -30,16 +30,13 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGMPathElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGMPathElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGMPathElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGMPathElement::SVGMPathElement(Document& document)
     : SVGElement(SVGNames::mpathTag, document)
+    , SVGURIReference(this)
 {
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGMPathElement();
@@ -61,8 +58,8 @@
     if (!inDocument())
         return;
 
-    String id;
-    Element* target = SVGURIReference::targetElementFromIRIString(hrefCurrentValue(), document(), &id);
+    AtomicString id;
+    Element* target = SVGURIReference::targetElementFromIRIString(hrefString(), document(), &id);
     if (!target) {
         // Do not register as pending if we are already pending this resource.
         if (document().accessSVGExtensions()->isElementPendingResource(this, id))
@@ -107,24 +104,22 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGURIReference::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
     }
     return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGMPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
+    SVGParsingError parseError = NoError;
+
     if (!isSupportedAttribute(name)) {
         SVGElement::parseAttribute(name, value);
-        return;
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else {
+        ASSERT_NOT_REACHED();
     }
 
-    if (SVGURIReference::parseAttribute(name, value))
-        return;
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGMPathElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -141,15 +136,12 @@
         return;
     }
 
-    if (SVGExternalResourcesRequired::isKnownAttribute(attrName))
-        return;
-
     ASSERT_NOT_REACHED();
 }
 
 SVGPathElement* SVGMPathElement::pathElement()
 {
-    Element* target = targetElementFromIRIString(hrefCurrentValue(), document());
+    Element* target = targetElementFromIRIString(hrefString(), document());
     if (target && target->hasTagName(SVGNames::pathTag))
         return toSVGPathElement(target);
     return 0;
@@ -163,7 +155,7 @@
 void SVGMPathElement::notifyParentOfPathChange(ContainerNode* parent)
 {
     if (parent && parent->hasTagName(SVGNames::animateMotionTag))
-        static_cast<SVGAnimateMotionElement*>(parent)->updateAnimationPath();
+        toSVGAnimateMotionElement(parent)->updateAnimationPath();
 }
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGMPathElement.h b/Source/core/svg/SVGMPathElement.h
index 0bccf80..3799d83 100644
--- a/Source/core/svg/SVGMPathElement.h
+++ b/Source/core/svg/SVGMPathElement.h
@@ -24,7 +24,6 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedString.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGURIReference.h"
 
 namespace WebCore {
@@ -32,8 +31,7 @@
 class SVGPathElement;
 
 class SVGMPathElement FINAL : public SVGElement,
-                              public SVGURIReference,
-                              public SVGExternalResourcesRequired {
+                              public SVGURIReference {
 public:
     static PassRefPtr<SVGMPathElement> create(Document&);
 
@@ -46,10 +44,10 @@
 private:
     explicit SVGMPathElement(Document&);
 
-    void buildPendingResource();
+    virtual void buildPendingResource() OVERRIDE;
     void clearResourceReferences();
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    void removedFrom(ContainerNode*);
+    virtual void removedFrom(ContainerNode*) OVERRIDE;
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -59,8 +57,6 @@
     void notifyParentOfPathChange(ContainerNode*);
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGMPathElement)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGMPathElement.idl b/Source/core/svg/SVGMPathElement.idl
index 3849582..bb8aaf6 100644
--- a/Source/core/svg/SVGMPathElement.idl
+++ b/Source/core/svg/SVGMPathElement.idl
@@ -26,6 +26,5 @@
 interface SVGMPathElement : SVGElement {
 };
 
-SVGMPathElement implements SVGExternalResourcesRequired;
 SVGMPathElement implements SVGURIReference;
 
diff --git a/Source/core/svg/SVGMarkerElement.cpp b/Source/core/svg/SVGMarkerElement.cpp
index 8bb26d6..7ca8285 100644
--- a/Source/core/svg/SVGMarkerElement.cpp
+++ b/Source/core/svg/SVGMarkerElement.cpp
@@ -45,41 +45,37 @@
 }
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGMarkerElement, SVGNames::refXAttr, RefX, refX)
-DEFINE_ANIMATED_LENGTH(SVGMarkerElement, SVGNames::refYAttr, RefY, refY)
-DEFINE_ANIMATED_LENGTH(SVGMarkerElement, SVGNames::markerWidthAttr, MarkerWidth, markerWidth)
-DEFINE_ANIMATED_LENGTH(SVGMarkerElement, SVGNames::markerHeightAttr, MarkerHeight, markerHeight)
 DEFINE_ANIMATED_ENUMERATION(SVGMarkerElement, SVGNames::markerUnitsAttr, MarkerUnits, markerUnits, SVGMarkerUnitsType)
 DEFINE_ANIMATED_ANGLE_AND_ENUMERATION(SVGMarkerElement, SVGNames::orientAttr, orientAngleIdentifier(), OrientAngle, orientAngle)
-DEFINE_ANIMATED_BOOLEAN(SVGMarkerElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-DEFINE_ANIMATED_RECT(SVGMarkerElement, SVGNames::viewBoxAttr, ViewBox, viewBox)
-DEFINE_ANIMATED_PRESERVEASPECTRATIO(SVGMarkerElement, SVGNames::preserveAspectRatioAttr, PreserveAspectRatio, preserveAspectRatio)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGMarkerElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(refX)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(refY)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(markerWidth)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(markerHeight)
     REGISTER_LOCAL_ANIMATED_PROPERTY(markerUnits)
     REGISTER_LOCAL_ANIMATED_PROPERTY(orientAngle)
     REGISTER_LOCAL_ANIMATED_PROPERTY(orientType)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(viewBox)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAspectRatio)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGMarkerElement::SVGMarkerElement(Document& document)
     : SVGElement(SVGNames::markerTag, document)
+    , SVGFitToViewBox(this)
+    , m_refX(SVGAnimatedLength::create(this, SVGNames::refXAttr, SVGLength::create(LengthModeWidth)))
+    , m_refY(SVGAnimatedLength::create(this, SVGNames::refXAttr, SVGLength::create(LengthModeWidth)))
+    , m_markerWidth(SVGAnimatedLength::create(this, SVGNames::markerWidthAttr, SVGLength::create(LengthModeWidth)))
+    , m_markerHeight(SVGAnimatedLength::create(this, SVGNames::markerHeightAttr, SVGLength::create(LengthModeHeight)))
     , m_orientType(SVGMarkerOrientAngle)
-    , m_refX(LengthModeWidth)
-    , m_refY(LengthModeHeight)
-    , m_markerWidth(LengthModeWidth, "3")
-    , m_markerHeight(LengthModeHeight, "3")
     , m_markerUnits(SVGMarkerUnitsStrokeWidth)
 {
-    // Spec: If the markerWidth/markerHeight attribute is not specified, the effect is as if a value of "3" were specified.
     ScriptWrappable::init(this);
+
+    // Spec: If the markerWidth/markerHeight attribute is not specified, the effect is as if a value of "3" were specified.
+    m_markerWidth->setDefaultValueAsString("3");
+    m_markerHeight->setDefaultValueAsString("3");
+
+    addToPropertyMap(m_refX);
+    addToPropertyMap(m_refY);
+    addToPropertyMap(m_markerWidth);
+    addToPropertyMap(m_markerHeight);
+
     registerAnimatedPropertiesForSVGMarkerElement();
 }
 
@@ -102,14 +98,13 @@
 
 AffineTransform SVGMarkerElement::viewBoxToViewTransform(float viewWidth, float viewHeight) const
 {
-    return SVGFitToViewBox::viewBoxToViewTransform(viewBoxCurrentValue(), preserveAspectRatioCurrentValue(), viewWidth, viewHeight);
+    return SVGFitToViewBox::viewBoxToViewTransform(viewBox()->currentValue()->value(), preserveAspectRatio()->currentValue(), viewWidth, viewHeight);
 }
 
 bool SVGMarkerElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         SVGFitToViewBox::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::markerUnitsAttr);
         supportedAttributes.add(SVGNames::refXAttr);
@@ -132,13 +127,13 @@
         if (propertyValue > 0)
             setMarkerUnitsBaseValue(propertyValue);
     } else if (name == SVGNames::refXAttr)
-        setRefXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_refX->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::refYAttr)
-        setRefYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_refY->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::markerWidthAttr)
-        setMarkerWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_markerWidth->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::markerHeightAttr)
-        setMarkerHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_markerHeight->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::orientAttr) {
         SVGAngle angle;
         SVGMarkerOrientType orientType = SVGPropertyTraits<SVGMarkerOrientType>::fromString(value, angle);
@@ -146,10 +141,10 @@
             setOrientTypeBaseValue(orientType);
         if (orientType == SVGMarkerOrientAngle)
             setOrientAngleBaseValue(angle);
-    } else if (SVGExternalResourcesRequired::parseAttribute(name, value)
-             || SVGFitToViewBox::parseAttribute(this, name, value)) {
-    } else
+    } else if (SVGFitToViewBox::parseAttribute(name, value, document(), parseError)) {
+    } else {
         ASSERT_NOT_REACHED();
+    }
 
     reportAttributeParsingError(parseError, name, value);
 }
@@ -216,10 +211,10 @@
 
 bool SVGMarkerElement::selfHasRelativeLengths() const
 {
-    return refXCurrentValue().isRelative()
-        || refYCurrentValue().isRelative()
-        || markerWidthCurrentValue().isRelative()
-        || markerHeightCurrentValue().isRelative();
+    return m_refX->currentValue()->isRelative()
+        || m_refY->currentValue()->isRelative()
+        || m_markerWidth->currentValue()->isRelative()
+        || m_markerHeight->currentValue()->isRelative();
 }
 
 void SVGMarkerElement::synchronizeOrientType(SVGElement* contextElement)
diff --git a/Source/core/svg/SVGMarkerElement.h b/Source/core/svg/SVGMarkerElement.h
index da6b465..03e627c 100644
--- a/Source/core/svg/SVGMarkerElement.h
+++ b/Source/core/svg/SVGMarkerElement.h
@@ -26,10 +26,7 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
-#include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFitToViewBox.h"
 
 namespace WebCore {
@@ -95,7 +92,6 @@
 };
 
 class SVGMarkerElement FINAL : public SVGElement,
-                               public SVGExternalResourcesRequired,
                                public SVGFitToViewBox {
 public:
     // Forward declare enumerations in the W3C naming scheme, for IDL generation.
@@ -120,6 +116,11 @@
 
     static const SVGPropertyInfo* orientTypePropertyInfo();
 
+    SVGAnimatedLength* refX() const { return m_refX.get(); }
+    SVGAnimatedLength* refY() const { return m_refY.get(); }
+    SVGAnimatedLength* markerWidth() const { return m_markerWidth.get(); }
+    SVGAnimatedLength* markerHeight() const { return m_markerHeight.get(); }
+
     // Custom 'orientType' property.
     static void synchronizeOrientType(SVGElement* contextElement);
     static PassRefPtr<SVGAnimatedProperty> lookupOrCreateOrientTypeWrapper(SVGElement* contextElement);
@@ -131,35 +132,31 @@
 private:
     explicit SVGMarkerElement(Document&);
 
-    virtual bool needsPendingResourceHandling() const { return false; }
+    virtual bool needsPendingResourceHandling() const OVERRIDE { return false; }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool rendererIsNeeded(const RenderStyle&) { return true; }
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return true; }
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
     void synchronizeOrientType();
 
     static const AtomicString& orientTypeIdentifier();
     static const AtomicString& orientAngleIdentifier();
 
+    RefPtr<SVGAnimatedLength> m_refX;
+    RefPtr<SVGAnimatedLength> m_refY;
+    RefPtr<SVGAnimatedLength> m_markerWidth;
+    RefPtr<SVGAnimatedLength> m_markerHeight;
     mutable SVGSynchronizableAnimatedProperty<SVGMarkerOrientType> m_orientType;
-
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGMarkerElement)
-        DECLARE_ANIMATED_LENGTH(RefX, refX)
-        DECLARE_ANIMATED_LENGTH(RefY, refY)
-        DECLARE_ANIMATED_LENGTH(MarkerWidth, markerWidth)
-        DECLARE_ANIMATED_LENGTH(MarkerHeight, markerHeight)
         DECLARE_ANIMATED_ENUMERATION(MarkerUnits, markerUnits, SVGMarkerUnitsType)
         DECLARE_ANIMATED_ANGLE(OrientAngle, orientAngle)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
-        DECLARE_ANIMATED_RECT(ViewBox, viewBox)
-        DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGMarkerElement.idl b/Source/core/svg/SVGMarkerElement.idl
index 0918d76..0e22319 100644
--- a/Source/core/svg/SVGMarkerElement.idl
+++ b/Source/core/svg/SVGMarkerElement.idl
@@ -46,6 +46,5 @@
     void setOrientToAngle([Default=Undefined] optional SVGAngle angle);
 };
 
-SVGMarkerElement implements SVGExternalResourcesRequired;
 SVGMarkerElement implements SVGFitToViewBox;
 
diff --git a/Source/core/svg/SVGMaskElement.cpp b/Source/core/svg/SVGMaskElement.cpp
index 728dfcb..98343fb 100644
--- a/Source/core/svg/SVGMaskElement.cpp
+++ b/Source/core/svg/SVGMaskElement.cpp
@@ -33,36 +33,37 @@
 // Animated property definitions
 DEFINE_ANIMATED_ENUMERATION(SVGMaskElement, SVGNames::maskUnitsAttr, MaskUnits, maskUnits, SVGUnitTypes::SVGUnitType)
 DEFINE_ANIMATED_ENUMERATION(SVGMaskElement, SVGNames::maskContentUnitsAttr, MaskContentUnits, maskContentUnits, SVGUnitTypes::SVGUnitType)
-DEFINE_ANIMATED_LENGTH(SVGMaskElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGMaskElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH(SVGMaskElement, SVGNames::widthAttr, Width, width)
-DEFINE_ANIMATED_LENGTH(SVGMaskElement, SVGNames::heightAttr, Height, height)
-DEFINE_ANIMATED_BOOLEAN(SVGMaskElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGMaskElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(maskUnits)
     REGISTER_LOCAL_ANIMATED_PROPERTY(maskContentUnits)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(width)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(height)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGMaskElement::SVGMaskElement(Document& document)
     : SVGElement(SVGNames::maskTag, document)
+    , SVGTests(this)
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
+    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth)))
+    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight)))
     , m_maskUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
     , m_maskContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
-    , m_x(LengthModeWidth, "-10%")
-    , m_y(LengthModeHeight, "-10%")
-    , m_width(LengthModeWidth, "120%")
-    , m_height(LengthModeHeight, "120%")
 {
-    // Spec: If the x/y attribute is not specified, the effect is as if a value of "-10%" were specified.
-    // Spec: If the width/height attribute is not specified, the effect is as if a value of "120%" were specified.
     ScriptWrappable::init(this);
+
+    // Spec: If the x/y attribute is not specified, the effect is as if a value of "-10%" were specified.
+    m_x->setDefaultValueAsString("-10%");
+    m_y->setDefaultValueAsString("-10%");
+
+    // Spec: If the width/height attribute is not specified, the effect is as if a value of "120%" were specified.
+    m_width->setDefaultValueAsString("120%");
+    m_height->setDefaultValueAsString("120%");
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_width);
+    addToPropertyMap(m_height);
     registerAnimatedPropertiesForSVGMaskElement();
 }
 
@@ -76,7 +77,6 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGTests::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::maskUnitsAttr);
         supportedAttributes.add(SVGNames::maskContentUnitsAttr);
         supportedAttributes.add(SVGNames::xAttr);
@@ -104,15 +104,14 @@
             setMaskContentUnitsBaseValue(propertyValue);
         return;
     } else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::widthAttr)
-        setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_width->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::heightAttr)
-        setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (SVGTests::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)) {
+        m_height->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    else if (SVGTests::parseAttribute(name, value)) {
     } else
         ASSERT_NOT_REACHED();
 
@@ -157,10 +156,10 @@
 
 bool SVGMaskElement::selfHasRelativeLengths() const
 {
-    return xCurrentValue().isRelative()
-        || yCurrentValue().isRelative()
-        || widthCurrentValue().isRelative()
-        || heightCurrentValue().isRelative();
+    return m_x->currentValue()->isRelative()
+        || m_y->currentValue()->isRelative()
+        || m_width->currentValue()->isRelative()
+        || m_height->currentValue()->isRelative();
 }
 
 }
diff --git a/Source/core/svg/SVGMaskElement.h b/Source/core/svg/SVGMaskElement.h
index a4b09ae..e599a9f 100644
--- a/Source/core/svg/SVGMaskElement.h
+++ b/Source/core/svg/SVGMaskElement.h
@@ -25,47 +25,44 @@
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGTests.h"
 #include "core/svg/SVGUnitTypes.h"
 
 namespace WebCore {
 
 class SVGMaskElement FINAL : public SVGElement,
-                             public SVGTests,
-                             public SVGExternalResourcesRequired {
+                             public SVGTests {
 public:
     static PassRefPtr<SVGMaskElement> create(Document&);
 
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
+    SVGAnimatedLength* width() const { return m_width.get(); }
+    SVGAnimatedLength* height() const { return m_height.get(); }
+
 private:
     explicit SVGMaskElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
-    virtual bool needsPendingResourceHandling() const { return false; }
+    virtual bool isValid() const OVERRIDE { return SVGTests::isValid(); }
+    virtual bool needsPendingResourceHandling() const OVERRIDE { return false; }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
+    RefPtr<SVGAnimatedLength> m_width;
+    RefPtr<SVGAnimatedLength> m_height;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGMaskElement)
         DECLARE_ANIMATED_ENUMERATION(MaskUnits, maskUnits, SVGUnitTypes::SVGUnitType)
         DECLARE_ANIMATED_ENUMERATION(MaskContentUnits, maskContentUnits, SVGUnitTypes::SVGUnitType)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_LENGTH(Width, width)
-        DECLARE_ANIMATED_LENGTH(Height, height)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGMaskElement, hasTagName(SVGNames::maskTag));
diff --git a/Source/core/svg/SVGMaskElement.idl b/Source/core/svg/SVGMaskElement.idl
index 22658d5..0678551 100644
--- a/Source/core/svg/SVGMaskElement.idl
+++ b/Source/core/svg/SVGMaskElement.idl
@@ -33,6 +33,5 @@
     readonly attribute SVGAnimatedLength height;
 };
 
-SVGMaskElement implements SVGExternalResourcesRequired;
 SVGMaskElement implements SVGTests;
 
diff --git a/Source/core/svg/SVGMatrix.h b/Source/core/svg/SVGMatrix.h
index 3917b90..df536b5 100644
--- a/Source/core/svg/SVGMatrix.h
+++ b/Source/core/svg/SVGMatrix.h
@@ -106,12 +106,8 @@
     SVGMatrix inverse(ExceptionState& exceptionState) const
     {
         AffineTransform transform = AffineTransform::inverse();
-        if (!isInvertible()) {
-            // FIXME: This used to have a more specific error message:
-            // "An attempt was made to invert a matrix that is not invertible."
-            // When switching to SVG2 style exceptions we lost this information.
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
-        }
+        if (!isInvertible())
+            exceptionState.throwDOMException(InvalidStateError, "The matrix is not invertible.");
 
         return transform;
     }
@@ -119,7 +115,7 @@
     SVGMatrix rotateFromVector(double x, double y, ExceptionState& exceptionState)
     {
         if (!x || !y)
-            exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+            exceptionState.throwDOMException(InvalidAccessError, "Arguments cannot be zero.");
 
         AffineTransform copy = *this;
         copy.rotateFromVector(x, y);
diff --git a/Source/core/svg/SVGMatrix.idl b/Source/core/svg/SVGMatrix.idl
index af56029..eb28daa 100644
--- a/Source/core/svg/SVGMatrix.idl
+++ b/Source/core/svg/SVGMatrix.idl
@@ -21,27 +21,28 @@
  */
 
 [
-    SetReference(SVGTransform parent)
+    SetWrapperReferenceTo(SVGTransform parent),
+    StrictTypeChecking,
 ] interface SVGMatrix {
     // FIXME: these attributes should all be floats but since we implement
     // AffineTransform with doubles setting these as doubles makes more sense.
-    [StrictTypeChecking] attribute double a;
-    [StrictTypeChecking] attribute double b;
-    [StrictTypeChecking] attribute double c;
-    [StrictTypeChecking] attribute double d;
-    [StrictTypeChecking] attribute double e;
-    [StrictTypeChecking] attribute double f;
+    attribute double a;
+    attribute double b;
+    attribute double c;
+    attribute double d;
+    attribute double e;
+    attribute double f;
 
-    [StrictTypeChecking] SVGMatrix multiply(SVGMatrix secondMatrix);
+    SVGMatrix multiply(SVGMatrix secondMatrix);
     [RaisesException] SVGMatrix inverse();
-    [Immutable, StrictTypeChecking] SVGMatrix translate(float x, float y);
-    [Immutable, StrictTypeChecking] SVGMatrix scale(float scaleFactor);
-    [Immutable, StrictTypeChecking] SVGMatrix scaleNonUniform(float scaleFactorX, float scaleFactorY);
-    [Immutable, StrictTypeChecking] SVGMatrix rotate(float angle);
-    [StrictTypeChecking, RaisesException] SVGMatrix rotateFromVector(float x, float y);
+    [Immutable] SVGMatrix translate(float x, float y);
+    [Immutable] SVGMatrix scale(float scaleFactor);
+    [Immutable] SVGMatrix scaleNonUniform(float scaleFactorX, float scaleFactorY);
+    [Immutable] SVGMatrix rotate(float angle);
+    [RaisesException] SVGMatrix rotateFromVector(float x, float y);
     [Immutable] SVGMatrix flipX();
     [Immutable] SVGMatrix flipY();
-    [Immutable, StrictTypeChecking] SVGMatrix skewX(float angle);
-    [Immutable, StrictTypeChecking] SVGMatrix skewY(float angle);
+    [Immutable] SVGMatrix skewX(float angle);
+    [Immutable] SVGMatrix skewY(float angle);
 };
 
diff --git a/Source/core/svg/SVGMissingGlyphElement.h b/Source/core/svg/SVGMissingGlyphElement.h
index 9057582..fa1ef31 100644
--- a/Source/core/svg/SVGMissingGlyphElement.h
+++ b/Source/core/svg/SVGMissingGlyphElement.h
@@ -33,7 +33,7 @@
 private:
     explicit SVGMissingGlyphElement(Document&);
 
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGMissingGlyphElement, hasTagName(SVGNames::missing_glyphTag));
diff --git a/Source/core/svg/SVGNumber.cpp b/Source/core/svg/SVGNumber.cpp
new file mode 100644
index 0000000..f50197e
--- /dev/null
+++ b/Source/core/svg/SVGNumber.cpp
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/svg/SVGNumber.h"
+
+#include "core/svg/SVGAnimationElement.h"
+#include "core/svg/SVGParserUtilities.h"
+
+namespace WebCore {
+
+SVGNumber::SVGNumber(float value)
+    : NewSVGPropertyBase(classType())
+    , m_value(value)
+{
+}
+
+PassRefPtr<SVGNumber> SVGNumber::clone() const
+{
+    return create(m_value);
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGNumber::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGNumber> svgNumber = create();
+    svgNumber->setValueAsString(value, IGNORE_EXCEPTION);
+    return svgNumber.release();
+}
+
+String SVGNumber::valueAsString() const
+{
+    return String::number(m_value);
+}
+
+template<typename CharType>
+bool SVGNumber::parse(const CharType*& ptr, const CharType* end)
+{
+    if (!parseNumber(ptr, end, m_value, false)) {
+        m_value = 0;
+        return false;
+    }
+
+    if (ptr != end) {
+        m_value = 0;
+        return false;
+    }
+
+    return true;
+}
+
+void SVGNumber::setValueAsString(const String& string, ExceptionState& exceptionState)
+{
+    if (string.isEmpty()) {
+        m_value = 0;
+        return;
+    }
+
+    bool valid = false;
+    if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        valid = parse(ptr, end);
+    } else {
+        const UChar* ptr = string.characters16();
+        const UChar* end = ptr + string.length();
+        valid = parse(ptr, end);
+    }
+
+    if (!valid) {
+        exceptionState.throwDOMException(SyntaxError, "The value provided ('" + string + "') is invalid.");
+        m_value = 0;
+    }
+}
+
+void SVGNumber::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    setValue(m_value + toSVGNumber(other)->value());
+}
+
+void SVGNumber::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDuration, SVGElement*)
+{
+    ASSERT(animationElement);
+
+    RefPtr<SVGNumber> fromNumber = toSVGNumber(from);
+    RefPtr<SVGNumber> toNumber = toSVGNumber(to);
+    RefPtr<SVGNumber> toAtEndOfDurationNumber = toSVGNumber(toAtEndOfDuration);
+
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromNumber->value(), toNumber->value(), toAtEndOfDurationNumber->value(), m_value);
+}
+
+float SVGNumber::calculateDistance(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    return fabsf(m_value - toSVGNumber(other)->value());
+}
+
+PassRefPtr<SVGNumber> SVGNumberAcceptPercentage::clone() const
+{
+    return create(m_value);
+}
+
+void SVGNumberAcceptPercentage::setValueAsString(const String& string, ExceptionState& exceptionState)
+{
+    if (string.isEmpty()) {
+        m_value = 0;
+        return;
+    }
+
+    if (string.endsWith('%')) {
+        SVGNumber::setValueAsString(string.left(string.length() - 1), exceptionState);
+        if (exceptionState.hadException())
+            return;
+
+        m_value /= 100.0f;
+        return;
+    }
+
+    SVGNumber::setValueAsString(string, exceptionState);
+}
+
+SVGNumberAcceptPercentage::SVGNumberAcceptPercentage(float value)
+    : SVGNumber(value)
+{
+}
+
+}
diff --git a/Source/core/svg/SVGNumber.h b/Source/core/svg/SVGNumber.h
index db47ed0..3b74b98 100644
--- a/Source/core/svg/SVGNumber.h
+++ b/Source/core/svg/SVGNumber.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -31,44 +31,72 @@
 #ifndef SVGNumber_h
 #define SVGNumber_h
 
-#include "core/svg/properties/SVGPropertyTraits.h"
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/svg/properties/NewSVGProperty.h"
 
 namespace WebCore {
 
-class SVGNumber {
-    WTF_MAKE_FAST_ALLOCATED;
+class SVGNumberTearOff;
+
+class SVGNumber : public NewSVGPropertyBase {
 public:
-    SVGNumber()
-        : m_value(0)
+    // SVGNumber has a tear-off type, but SVGAnimatedNumber uses primitive type.
+    typedef SVGNumberTearOff TearOffType;
+    typedef float PrimitiveType;
+
+    static PassRefPtr<SVGNumber> create(float value = 0.0f)
     {
+        return adoptRef(new SVGNumber(value));
     }
 
-    SVGNumber(float value)
-        : m_value(value)
-    {
-    }
-
-    SVGNumber& operator+=(const SVGNumber& rhs)
-    {
-        m_value += rhs.value();
-        return *this;
-    }
+    virtual PassRefPtr<SVGNumber> clone() const;
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
 
     float value() const { return m_value; }
-    float& valueRef() { return m_value; }
-    String valueAsString() const { return String::number(m_value); }
     void setValue(float value) { m_value = value; }
 
-private:
+    virtual String valueAsString() const OVERRIDE;
+    virtual void setValueAsString(const String&, ExceptionState&);
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedNumber; }
+
+protected:
+    explicit SVGNumber(float);
+
+    template<typename CharType>
+    bool parse(const CharType*& ptr, const CharType* end);
+
     float m_value;
 };
 
-COMPILE_ASSERT(sizeof(SVGNumber) == sizeof(float), SVGNumber_same_size_as_float);
+inline PassRefPtr<SVGNumber> toSVGNumber(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGNumber::classType());
+    return static_pointer_cast<SVGNumber>(base.release());
+}
 
-template<>
-struct SVGPropertyTraits<SVGNumber> {
-    static SVGNumber initialValue() { return SVGNumber(); }
-    static String toString(const SVGNumber& type) { return type.valueAsString(); }
+// SVGNumber which also accepts percentage as its value.
+// This is used for <stop> "offset"
+// Spec: http://www.w3.org/TR/SVG11/pservers.html#GradientStops
+//   offset = "<number> | <percentage>"
+class SVGNumberAcceptPercentage FINAL : public SVGNumber {
+public:
+    static PassRefPtr<SVGNumberAcceptPercentage> create(float value = 0)
+    {
+        return adoptRef(new SVGNumberAcceptPercentage(value));
+    }
+
+    virtual PassRefPtr<SVGNumber> clone() const OVERRIDE;
+    virtual void setValueAsString(const String&, ExceptionState&) OVERRIDE;
+
+private:
+    SVGNumberAcceptPercentage(float value);
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGNumber.idl b/Source/core/svg/SVGNumber.idl
index c77bbc9..e873793 100644
--- a/Source/core/svg/SVGNumber.idl
+++ b/Source/core/svg/SVGNumber.idl
@@ -20,7 +20,11 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface SVGNumber {
-    [StrictTypeChecking] attribute float value;
+[
+    ImplementedAs=SVGNumberTearOff,
+    SetWrapperReferenceTo(SVGElement contextElement),
+    StrictTypeChecking,
+] interface SVGNumber {
+    [RaisesException=Setter] attribute float value;
 };
 
diff --git a/Source/core/svg/SVGNumberList.cpp b/Source/core/svg/SVGNumberList.cpp
index 94934d1..cf515fc 100644
--- a/Source/core/svg/SVGNumberList.cpp
+++ b/Source/core/svg/SVGNumberList.cpp
@@ -21,52 +21,182 @@
 #include "config.h"
 #include "core/svg/SVGNumberList.h"
 
+#include "core/svg/SVGAnimationElement.h"
 #include "core/svg/SVGParserUtilities.h"
 #include "wtf/text/StringBuilder.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-template<typename CharType>
-void SVGNumberList::parseInternal(const CharType*& ptr, const CharType* end)
+inline PassRefPtr<SVGNumberList> toSVGNumberList(PassRefPtr<NewSVGPropertyBase> passBase)
 {
-    // The spec strangely doesn't allow leading whitespace.  We might choose to violate that intentionally. (section 4.1)
-    while (ptr < end) {
-        float number = 0;
-        if (!parseNumber(ptr, end, number))
-            return;
-        append(number);
-    }
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGNumberList::classType());
+    return static_pointer_cast<SVGNumberList>(base.release());
 }
 
-void SVGNumberList::parse(const String& value)
+SVGNumberList::SVGNumberList()
 {
-    clear();
-    if (value.isEmpty())
-        return;
-    if (value.is8Bit()) {
-        const LChar* ptr = value.characters8();
-        const LChar* end = ptr + value.length();
-        parseInternal(ptr, end);
-    } else {
-        const UChar* ptr = value.characters16();
-        const UChar* end = ptr + value.length();
-        parseInternal(ptr, end);
-    }
+}
+
+SVGNumberList::~SVGNumberList()
+{
+}
+
+PassRefPtr<SVGNumberList> SVGNumberList::clone()
+{
+    RefPtr<SVGNumberList> svgNumberList = SVGNumberList::create();
+    svgNumberList->deepCopy(this);
+    return svgNumberList.release();
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGNumberList::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGNumberList> svgNumberList = SVGNumberList::create();
+    svgNumberList->setValueAsString(value, IGNORE_EXCEPTION);
+    return svgNumberList.release();
 }
 
 String SVGNumberList::valueAsString() const
 {
     StringBuilder builder;
 
-    unsigned size = this->size();
-    for (unsigned i = 0; i < size; ++i) {
-        if (i > 0)
-            builder.append(' ');
+    ConstIterator it = begin();
+    ConstIterator itEnd = end();
+    if (it != itEnd) {
+        builder.append(it->valueAsString());
+        ++it;
 
-        builder.append(at(i).valueAsString());
+        for (; it != itEnd; ++it) {
+            builder.append(' ');
+            builder.append(it->valueAsString());
+        }
     }
 
     return builder.toString();
 }
 
+template <typename CharType>
+bool SVGNumberList::parse(const CharType*& ptr, const CharType* end)
+{
+    clear();
+
+    while (ptr < end) {
+        float number = 0;
+        if (!parseNumber(ptr, end, number))
+            return false;
+        append(SVGNumber::create(number));
+    }
+
+    return true;
+}
+
+void SVGNumberList::setValueAsString(const String& value, ExceptionState& exceptionState)
+{
+    if (value.isEmpty()) {
+        clear();
+        return;
+    }
+
+    bool valid = false;
+    if (value.is8Bit()) {
+        const LChar* ptr = value.characters8();
+        const LChar* end = ptr + value.length();
+        valid = parse(ptr, end);
+    } else {
+        const UChar* ptr = value.characters16();
+        const UChar* end = ptr + value.length();
+        valid = parse(ptr, end);
+    }
+
+    if (!valid) {
+        exceptionState.throwDOMException(SyntaxError, "Problem parsing number list \""+value+"\"");
+        // No call to |clear()| here. SVG policy is to use valid items before error.
+        // Spec: http://www.w3.org/TR/SVG/single-page.html#implnote-ErrorProcessing
+    }
+}
+
+void SVGNumberList::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement* contextElement)
+{
+    RefPtr<SVGNumberList> otherList = toSVGNumberList(other);
+
+    if (numberOfItems() != otherList->numberOfItems())
+        return;
+
+    for (size_t i = 0; i < numberOfItems(); ++i)
+        at(i)->setValue(at(i)->value() + otherList->at(i)->value());
+}
+
+bool SVGNumberList::adjustFromToListValues(PassRefPtr<SVGNumberList> passFromList, PassRefPtr<SVGNumberList> passToList, float percentage, bool isToAnimation, bool resizeAnimatedListIfNeeded)
+{
+    RefPtr<SVGNumberList> fromList = passFromList;
+    RefPtr<SVGNumberList> toList = passToList;
+
+    // If no 'to' value is given, nothing to animate.
+    size_t toListSize = toList->numberOfItems();
+    if (!toListSize)
+        return false;
+
+    // If the 'from' value is given and it's length doesn't match the 'to' value list length, fallback to a discrete animation.
+    size_t fromListSize = fromList->numberOfItems();
+    if (fromListSize != toListSize && fromListSize) {
+        if (percentage < 0.5) {
+            if (!isToAnimation)
+                deepCopy(fromList);
+        } else {
+            deepCopy(toList);
+        }
+
+        return false;
+    }
+
+    ASSERT(!fromListSize || fromListSize == toListSize);
+    if (resizeAnimatedListIfNeeded && numberOfItems() < toListSize) {
+        size_t paddingCount = toListSize - numberOfItems();
+        for (size_t i = 0; i < paddingCount; ++i)
+            append(SVGNumber::create());
+    }
+
+    return true;
+}
+
+void SVGNumberList::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement)
+{
+    RefPtr<SVGNumberList> fromList = toSVGNumberList(fromValue);
+    RefPtr<SVGNumberList> toList = toSVGNumberList(toValue);
+    RefPtr<SVGNumberList> toAtEndOfDurationList = toSVGNumberList(toAtEndOfDurationValue);
+
+    size_t fromListSize = fromList->numberOfItems();
+    size_t toListSize = toList->numberOfItems();
+    size_t toAtEndOfDurationListSize = toAtEndOfDurationList->numberOfItems();
+
+    if (!adjustFromToListValues(fromList, toList, percentage, animationElement->animationMode() == ToAnimation, true))
+        return;
+
+    for (size_t i = 0; i < toListSize; ++i) {
+        float effectiveFrom = fromListSize ? fromList->at(i)->value() : 0;
+        float effectiveTo = toListSize ? toList->at(i)->value() : 0;
+        float effectiveToAtEnd = i < toAtEndOfDurationListSize ? toAtEndOfDurationList->at(i)->value() : 0;
+
+        float animated = at(i)->value();
+        animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom, effectiveTo, effectiveToAtEnd, animated);
+        at(i)->setValue(animated);
+    }
+}
+
+float SVGNumberList::calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*)
+{
+    // FIXME: Distance calculation is not possible for SVGNumberList right now. We need the distance for every single value.
+    return -1;
+}
+
+Vector<float> SVGNumberList::toFloatVector() const
+{
+    Vector<float> vec;
+    vec.reserveInitialCapacity(numberOfItems());
+    for (size_t i = 0; i < numberOfItems(); ++i)
+        vec.uncheckedAppend(at(i)->value());
+    return vec;
+}
+
 }
diff --git a/Source/core/svg/SVGNumberList.h b/Source/core/svg/SVGNumberList.h
index 0b12d5d..087d164 100644
--- a/Source/core/svg/SVGNumberList.h
+++ b/Source/core/svg/SVGNumberList.h
@@ -1,61 +1,80 @@
 /*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGNumberList_h
 #define SVGNumberList_h
 
+#include "bindings/v8/ScriptWrappable.h"
 #include "core/svg/SVGNumber.h"
-#include "core/svg/properties/SVGPropertyTraits.h"
-#include "wtf/Vector.h"
+#include "core/svg/properties/NewSVGListPropertyHelper.h"
 
 namespace WebCore {
 
-class SVGNumberList : public Vector<SVGNumber> {
+class SVGNumberListTearOff;
+
+class SVGNumberList FINAL : public NewSVGListPropertyHelper<SVGNumberList, SVGNumber> {
 public:
-    SVGNumberList() { }
+    typedef SVGNumberListTearOff TearOffType;
 
-    void parse(const String&);
-    String valueAsString() const;
-
-    Vector<float> toFloatVector() const
+    static PassRefPtr<SVGNumberList> create()
     {
-        Vector<float> result;
-        result.reserveInitialCapacity(size());
-        for (size_t i = 0; i < size(); ++i)
-            result.uncheckedAppend(at(i).value());
-        return result;
+        return adoptRef(new SVGNumberList());
     }
 
+    virtual ~SVGNumberList();
+
+    PassRefPtr<SVGNumberList> clone();
+
+    void setValueAsString(const String&, ExceptionState&);
+
+    // NewSVGPropertyBase:
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+    virtual String valueAsString() const OVERRIDE;
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedNumberList; }
+
+    Vector<float> toFloatVector() const;
+
 private:
-    template<typename CharType>
-    void parseInternal(const CharType*& ptr, const CharType* end);
-};
+    SVGNumberList();
 
-template<>
-struct SVGPropertyTraits<SVGNumberList> {
-    typedef SVGNumber ListItemType;
+    bool adjustFromToListValues(PassRefPtr<SVGNumberList> fromList, PassRefPtr<SVGNumberList> toList, float percentage, bool isToAnimation, bool resizeAnimatedListIfNeeded);
 
-    static SVGNumberList initialValue() { return SVGNumberList(); }
-    static String toString(const SVGNumberList& type) { return type.valueAsString(); }
+    template <typename CharType>
+    bool parse(const CharType*& ptr, const CharType* end);
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGNumberList_h
diff --git a/Source/core/svg/SVGNumberList.idl b/Source/core/svg/SVGNumberList.idl
index 4711cc6..1bc3a5b 100644
--- a/Source/core/svg/SVGNumberList.idl
+++ b/Source/core/svg/SVGNumberList.idl
@@ -24,15 +24,19 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGNumberList {
+[
+    ImplementedAs=SVGNumberListTearOff,
+    SetWrapperReferenceTo(SVGElement contextElement),
+    StrictTypeChecking,
+] interface SVGNumberList {
     readonly attribute unsigned long numberOfItems;
 
     [RaisesException] void clear();
-    [StrictTypeChecking, RaisesException] SVGNumber initialize(SVGNumber item);
-    [StrictTypeChecking, RaisesException] SVGNumber getItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGNumber insertItemBefore(SVGNumber item, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGNumber replaceItem(SVGNumber item, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGNumber removeItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGNumber appendItem(SVGNumber item);
+    [RaisesException] SVGNumber initialize(SVGNumber item);
+    [RaisesException] SVGNumber getItem(unsigned long index);
+    [RaisesException] SVGNumber insertItemBefore(SVGNumber item, unsigned long index);
+    [RaisesException] SVGNumber replaceItem(SVGNumber item, unsigned long index);
+    [RaisesException] SVGNumber removeItem(unsigned long index);
+    [RaisesException] SVGNumber appendItem(SVGNumber item);
 };
 
diff --git a/Source/core/svg/SVGNumberListTearOff.h b/Source/core/svg/SVGNumberListTearOff.h
new file mode 100644
index 0000000..81c8290
--- /dev/null
+++ b/Source/core/svg/SVGNumberListTearOff.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGNumberListTearOff_h
+#define SVGNumberListTearOff_h
+
+#include "core/svg/SVGNumberList.h"
+#include "core/svg/properties/NewSVGListPropertyTearOffHelper.h"
+
+namespace WebCore {
+
+class SVGNumberListTearOff FINAL :
+    public NewSVGListPropertyTearOffHelper<SVGNumberListTearOff, SVGNumberList>,
+    public ScriptWrappable {
+public:
+    static PassRefPtr<SVGNumberListTearOff> create(PassRefPtr<SVGNumberList> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+    {
+        return adoptRef(new SVGNumberListTearOff(target, contextElement, propertyIsAnimVal, attributeName));
+    }
+
+private:
+    SVGNumberListTearOff(PassRefPtr<SVGNumberList> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+        : NewSVGListPropertyTearOffHelper<SVGNumberListTearOff, SVGNumberList>(target, contextElement, propertyIsAnimVal, attributeName)
+    {
+        ScriptWrappable::init(this);
+    }
+};
+
+} // namespace WebCore
+
+#endif // SVGNumberListTearOff_h_
diff --git a/Source/core/svg/SVGNumberOptionalNumber.cpp b/Source/core/svg/SVGNumberOptionalNumber.cpp
new file mode 100644
index 0000000..b7510cb
--- /dev/null
+++ b/Source/core/svg/SVGNumberOptionalNumber.cpp
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/svg/SVGNumberOptionalNumber.h"
+
+#include "core/svg/SVGAnimationElement.h"
+#include "core/svg/SVGParserUtilities.h"
+
+namespace WebCore {
+
+SVGNumberOptionalNumber::SVGNumberOptionalNumber(PassRefPtr<SVGNumber> firstNumber, PassRefPtr<SVGNumber> secondNumber)
+    : NewSVGPropertyBase(classType())
+    , m_firstNumber(firstNumber)
+    , m_secondNumber(secondNumber)
+{
+}
+
+PassRefPtr<SVGNumberOptionalNumber> SVGNumberOptionalNumber::clone() const
+{
+    return SVGNumberOptionalNumber::create(m_firstNumber->clone(), m_secondNumber->clone());
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGNumberOptionalNumber::cloneForAnimation(const String& value) const
+{
+    float x, y;
+    if (!parseNumberOptionalNumber(value, x, y)) {
+        x = y = 0;
+    }
+
+    return SVGNumberOptionalNumber::create(SVGNumber::create(x), SVGNumber::create(y));
+}
+
+String SVGNumberOptionalNumber::valueAsString() const
+{
+    if (m_firstNumber->value() == m_secondNumber->value()) {
+        return String::number(m_firstNumber->value());
+    }
+
+    return String::number(m_firstNumber->value()) + " " + String::number(m_secondNumber->value());
+}
+
+void SVGNumberOptionalNumber::setValueAsString(const String& value, ExceptionState& exceptionState)
+{
+    float x, y;
+    if (!parseNumberOptionalNumber(value, x, y)) {
+        exceptionState.throwDOMException(SyntaxError, "The value provided ('" + value + "') is invalid.");
+        x = y = 0;
+    }
+
+    m_firstNumber->setValue(x);
+    m_secondNumber->setValue(y);
+}
+
+void SVGNumberOptionalNumber::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    RefPtr<SVGNumberOptionalNumber> otherNumberOptionalNumber = toSVGNumberOptionalNumber(other);
+
+    m_firstNumber->setValue(m_firstNumber->value() + otherNumberOptionalNumber->m_firstNumber->value());
+    m_secondNumber->setValue(m_secondNumber->value() + otherNumberOptionalNumber->m_secondNumber->value());
+}
+
+void SVGNumberOptionalNumber::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDuration, SVGElement*)
+{
+    ASSERT(animationElement);
+
+    RefPtr<SVGNumberOptionalNumber> fromNumber = toSVGNumberOptionalNumber(from);
+    RefPtr<SVGNumberOptionalNumber> toNumber = toSVGNumberOptionalNumber(to);
+    RefPtr<SVGNumberOptionalNumber> toAtEndOfDurationNumber = toSVGNumberOptionalNumber(toAtEndOfDuration);
+
+    float x = m_firstNumber->value();
+    float y = m_secondNumber->value();
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromNumber->firstNumber()->value(), toNumber->firstNumber()->value(), toAtEndOfDurationNumber->firstNumber()->value(), x);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromNumber->secondNumber()->value(), toNumber->secondNumber()->value(), toAtEndOfDurationNumber->secondNumber()->value(), y);
+    m_firstNumber->setValue(x);
+    m_secondNumber->setValue(y);
+}
+
+float SVGNumberOptionalNumber::calculateDistance(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    // FIXME: Distance calculation is not possible for SVGNumberOptionalNumber right now. We need the distance for every single value.
+    return -1;
+}
+
+}
diff --git a/Source/core/svg/SVGNumberOptionalNumber.h b/Source/core/svg/SVGNumberOptionalNumber.h
new file mode 100644
index 0000000..b54bc59
--- /dev/null
+++ b/Source/core/svg/SVGNumberOptionalNumber.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGNumberOptionalNumber_h
+#define SVGNumberOptionalNumber_h
+
+#include "core/svg/SVGAnimatedNumber.h"
+
+namespace WebCore {
+
+class SVGNumberOptionalNumber : public NewSVGPropertyBase {
+public:
+    // Tearoff of SVGNumberOptionalNumber is never created.
+    typedef void TearOffType;
+    typedef void PrimitiveType;
+
+    static PassRefPtr<SVGNumberOptionalNumber> create(PassRefPtr<SVGNumber> firstNumber, PassRefPtr<SVGNumber> secondNumber)
+    {
+        return adoptRef(new SVGNumberOptionalNumber(firstNumber, secondNumber));
+    }
+
+    PassRefPtr<SVGNumberOptionalNumber> clone() const;
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+
+    virtual String valueAsString() const OVERRIDE;
+    void setValueAsString(const String&, ExceptionState&);
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedNumberOptionalNumber; }
+
+    PassRefPtr<SVGNumber> firstNumber() { return m_firstNumber; }
+    PassRefPtr<SVGNumber> secondNumber() { return m_secondNumber; }
+
+protected:
+    SVGNumberOptionalNumber(PassRefPtr<SVGNumber> firstNumber, PassRefPtr<SVGNumber> secondNumber);
+
+    RefPtr<SVGNumber> m_firstNumber;
+    RefPtr<SVGNumber> m_secondNumber;
+};
+
+inline PassRefPtr<SVGNumberOptionalNumber> toSVGNumberOptionalNumber(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGNumberOptionalNumber::classType());
+    return static_pointer_cast<SVGNumberOptionalNumber>(base.release());
+}
+
+} // namespace WebCore
+
+#endif // SVGNumberOptionalNumber_h
diff --git a/Source/core/dom/NodeList.cpp b/Source/core/svg/SVGNumberTearOff.cpp
similarity index 68%
rename from Source/core/dom/NodeList.cpp
rename to Source/core/svg/SVGNumberTearOff.cpp
index fb06c70..534ca7a 100644
--- a/Source/core/dom/NodeList.cpp
+++ b/Source/core/svg/SVGNumberTearOff.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,29 +29,29 @@
  */
 
 #include "config.h"
-#include "core/dom/NodeList.h"
 
-#include "core/dom/Node.h"
+#include "core/svg/SVGNumberTearOff.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
 
 namespace WebCore {
 
-void NodeList::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<Node>& returnValue0, bool& returnValue1Enabled, unsigned& returnValue1)
+SVGNumberTearOff::SVGNumberTearOff(PassRefPtr<SVGNumber> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName)
+    : NewSVGPropertyTearOff<SVGNumber>(target, contextElement, propertyIsAnimVal, attributeName)
 {
-    // Length property cannot be overridden.
-    DEFINE_STATIC_LOCAL(const AtomicString, length, ("length", AtomicString::ConstructFromLiteral));
-    if (name == length) {
-        returnValue1Enabled = true;
-        returnValue1 = this->length();
+    ScriptWrappable::init(this);
+}
+
+void SVGNumberTearOff::setValue(float f, ExceptionState& exceptionState)
+{
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
         return;
     }
 
-    Node* result = namedItem(name);
-    if (!result)
-        return;
-
-    returnValue0Enabled = true;
-    returnValue0 = result;
+    target()->setValue(f);
+    commitChange();
 }
 
-
-} // namespace WebCore
+}
diff --git a/Source/core/html/ime/Composition.h b/Source/core/svg/SVGNumberTearOff.h
similarity index 63%
copy from Source/core/html/ime/Composition.h
copy to Source/core/svg/SVGNumberTearOff.h
index 4305466..69cff27 100644
--- a/Source/core/html/ime/Composition.h
+++ b/Source/core/svg/SVGNumberTearOff.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,36 +28,31 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef Composition_h
-#define Composition_h
+#ifndef SVGNumberTearOff_h
+#define SVGNumberTearOff_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
+#include "core/svg/SVGNumber.h"
+#include "core/svg/properties/NewSVGPropertyTearOff.h"
 
 namespace WebCore {
 
-class InputMethodContext;
+class SVGMatrix;
 
-class Composition : public ScriptWrappable {
+class SVGNumberTearOff : public NewSVGPropertyTearOff<SVGNumber>, public ScriptWrappable {
 public:
-    static PassOwnPtr<Composition> create(InputMethodContext*);
-    ~Composition();
+    static PassRefPtr<SVGNumberTearOff> create(PassRefPtr<SVGNumber> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+    {
+        return adoptRef(new SVGNumberTearOff(target, contextElement, propertyIsAnimVal, attributeName));
+    }
 
-    void ref();
-    void deref();
+    void setValue(float, ExceptionState&);
+    float value() { return target()->value(); }
 
-    String text() const;
-    int selectionStart() const;
-    int selectionEnd() const;
-    const Vector<unsigned>& getSegments() const;
-
-private:
-    explicit Composition(InputMethodContext*);
-
-    InputMethodContext* m_inputMethodContext;
+protected:
+    SVGNumberTearOff(PassRefPtr<SVGNumber>, SVGElement* contextElement, PropertyIsAnimValType, const QualifiedName& attributeName = nullQName());
 };
 
 } // namespace WebCore
 
-#endif // Composition_h
+#endif // SVGNumberTearOff_h_
diff --git a/Source/core/svg/SVGPaint.cpp b/Source/core/svg/SVGPaint.cpp
index 8aa13ae..f7e85f1 100644
--- a/Source/core/svg/SVGPaint.cpp
+++ b/Source/core/svg/SVGPaint.cpp
@@ -22,6 +22,7 @@
 #include "config.h"
 #include "core/svg/SVGPaint.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 
 namespace WebCore {
@@ -64,13 +65,14 @@
 
 void SVGPaint::setPaint(unsigned short, const String&, const String&, const String&, ExceptionState& exceptionState)
 {
-    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::readOnly());
 }
 
 String SVGPaint::customCSSText() const
 {
     switch (m_paintType) {
     case SVG_PAINTTYPE_UNKNOWN:
+        return String();
     case SVG_PAINTTYPE_RGBCOLOR:
     case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
     case SVG_PAINTTYPE_CURRENTCOLOR:
@@ -102,9 +104,9 @@
 {
 }
 
-PassRefPtr<SVGPaint> SVGPaint::cloneForCSSOM() const
+PassRefPtrWillBeRawPtr<SVGPaint> SVGPaint::cloneForCSSOM() const
 {
-    return adoptRef(new SVGPaint(*this));
+    return adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(*this));
 }
 
 bool SVGPaint::equals(const SVGPaint& other) const
diff --git a/Source/core/svg/SVGPaint.h b/Source/core/svg/SVGPaint.h
index f48b4b7..488c2e8 100644
--- a/Source/core/svg/SVGPaint.h
+++ b/Source/core/svg/SVGPaint.h
@@ -45,44 +45,50 @@
         SVG_PAINTTYPE_URI = 107
     };
 
-    static PassRefPtr<SVGPaint> createUnknown()
+    static PassRefPtrWillBeRawPtr<SVGPaint> createUnknown()
     {
-        return adoptRef(new SVGPaint(SVG_PAINTTYPE_UNKNOWN));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(SVG_PAINTTYPE_UNKNOWN));
     }
 
-    static PassRefPtr<SVGPaint> createNone()
+    static PassRefPtrWillBeRawPtr<SVGPaint> createNone()
     {
-        return adoptRef(new SVGPaint(SVG_PAINTTYPE_NONE));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(SVG_PAINTTYPE_NONE));
     }
 
-    static PassRefPtr<SVGPaint> createCurrentColor()
+    static PassRefPtrWillBeRawPtr<SVGPaint> createCurrentColor()
     {
-        return adoptRef(new SVGPaint(SVG_PAINTTYPE_CURRENTCOLOR));
+        return adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(SVG_PAINTTYPE_CURRENTCOLOR));
     }
 
-    static PassRefPtr<SVGPaint> createColor(const Color& color)
+    static PassRefPtrWillBeRawPtr<SVGPaint> createColor(const Color& color)
     {
-        RefPtr<SVGPaint> paint = adoptRef(new SVGPaint(SVG_PAINTTYPE_RGBCOLOR));
+        RefPtrWillBeRawPtr<SVGPaint> paint = adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(SVG_PAINTTYPE_RGBCOLOR));
         paint->setColor(color);
         return paint.release();
     }
 
-    static PassRefPtr<SVGPaint> createURI(const String& uri)
+    static PassRefPtrWillBeRawPtr<SVGPaint> createURI(const String& uri)
     {
-        RefPtr<SVGPaint> paint = adoptRef(new SVGPaint(SVG_PAINTTYPE_URI, uri));
+        RefPtrWillBeRawPtr<SVGPaint> paint = adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(SVG_PAINTTYPE_URI, uri));
         return paint.release();
     }
 
-    static PassRefPtr<SVGPaint> createURIAndColor(const String& uri, const Color& color)
+    static PassRefPtrWillBeRawPtr<SVGPaint> createURIAndColor(const String& uri, const Color& color)
     {
-        RefPtr<SVGPaint> paint = adoptRef(new SVGPaint(SVG_PAINTTYPE_URI_RGBCOLOR, uri));
+        RefPtrWillBeRawPtr<SVGPaint> paint = adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(SVG_PAINTTYPE_URI_RGBCOLOR, uri));
         paint->setColor(color);
         return paint.release();
     }
 
-    static PassRefPtr<SVGPaint> createURIAndNone(const String& uri)
+    static PassRefPtrWillBeRawPtr<SVGPaint> createURIAndNone(const String& uri)
     {
-        RefPtr<SVGPaint> paint = adoptRef(new SVGPaint(SVG_PAINTTYPE_URI_NONE, uri));
+        RefPtrWillBeRawPtr<SVGPaint> paint = adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(SVG_PAINTTYPE_URI_NONE, uri));
+        return paint.release();
+    }
+
+    static PassRefPtrWillBeRawPtr<SVGPaint> createURIAndCurrentColor(const String& uri)
+    {
+        RefPtrWillBeRawPtr<SVGPaint> paint = adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(SVG_PAINTTYPE_URI_CURRENTCOLOR, uri));
         return paint.release();
     }
 
@@ -94,16 +100,18 @@
 
     String customCSSText() const;
 
-    PassRefPtr<SVGPaint> cloneForCSSOM() const;
+    PassRefPtrWillBeRawPtr<SVGPaint> cloneForCSSOM() const;
 
     bool equals(const SVGPaint&) const;
 
+    void traceAfterDispatch(Visitor* visitor) { SVGColor::traceAfterDispatch(visitor); }
+
 private:
     friend class CSSComputedStyleDeclaration;
 
-    static PassRefPtr<SVGPaint> create(const SVGPaintType& type, const String& uri, const Color& color)
+    static PassRefPtrWillBeRawPtr<SVGPaint> create(const SVGPaintType& type, const String& uri, const Color& color)
     {
-        RefPtr<SVGPaint> paint = adoptRef(new SVGPaint(type, uri));
+        RefPtrWillBeRawPtr<SVGPaint> paint = adoptRefCountedWillBeRefCountedGarbageCollected(new SVGPaint(type, uri));
         paint->setColor(color);
         return paint.release();
     }
diff --git a/Source/core/svg/SVGPaint.idl b/Source/core/svg/SVGPaint.idl
deleted file mode 100644
index 8c1badb..0000000
--- a/Source/core/svg/SVGPaint.idl
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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.
- */
-
-interface SVGPaint : SVGColor {
-    const unsigned short SVG_PAINTTYPE_UNKNOWN = 0;
-    const unsigned short SVG_PAINTTYPE_RGBCOLOR = 1;
-    const unsigned short SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR = 2;
-    const unsigned short SVG_PAINTTYPE_NONE = 101;
-    const unsigned short SVG_PAINTTYPE_CURRENTCOLOR = 102;
-    const unsigned short SVG_PAINTTYPE_URI_NONE = 103;
-    const unsigned short SVG_PAINTTYPE_URI_CURRENTCOLOR = 104;
-    const unsigned short SVG_PAINTTYPE_URI_RGBCOLOR = 105;
-    const unsigned short SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR = 106;
-    const unsigned short SVG_PAINTTYPE_URI = 107;
-
-    readonly attribute unsigned short paintType;
-    readonly attribute DOMString uri;
-
-    [StrictTypeChecking] void setUri(DOMString uri);
-    [StrictTypeChecking, RaisesException] void setPaint(unsigned short paintType, DOMString uri, DOMString rgbColor, DOMString iccColor);
-};
-
diff --git a/Source/core/svg/SVGParserUtilities.cpp b/Source/core/svg/SVGParserUtilities.cpp
index 262ef62..7bedbb4 100644
--- a/Source/core/svg/SVGParserUtilities.cpp
+++ b/Source/core/svg/SVGParserUtilities.cpp
@@ -238,78 +238,6 @@
 }
 
 template<typename CharType>
-static bool genericParseRect(const CharType*& ptr, const CharType* end, FloatRect& rect)
-{
-    skipOptionalSVGSpaces(ptr, end);
-
-    float x = 0;
-    float y = 0;
-    float width = 0;
-    float height = 0;
-    bool valid = parseNumber(ptr, end, x) && parseNumber(ptr, end, y) && parseNumber(ptr, end, width) && parseNumber(ptr, end, height, false);
-    rect = FloatRect(x, y, width, height);
-    return valid;
-}
-
-bool parseRect(const String& string, FloatRect& rect)
-{
-    if (string.isEmpty())
-        return false;
-    if (string.is8Bit()) {
-        const LChar* ptr = string.characters8();
-        const LChar* end = ptr + string.length();
-        return genericParseRect(ptr, end, rect);
-    }
-    const UChar* ptr = string.characters16();
-    const UChar* end = ptr + string.length();
-    return genericParseRect(ptr, end, rect);
-}
-
-template<typename CharType>
-static bool genericParsePointsList(SVGPointList& pointsList, const CharType*& ptr, const CharType* end)
-{
-    skipOptionalSVGSpaces(ptr, end);
-
-    bool delimParsed = false;
-    while (ptr < end) {
-        delimParsed = false;
-        float xPos = 0.0f;
-        if (!parseNumber(ptr, end, xPos))
-           return false;
-
-        float yPos = 0.0f;
-        if (!parseNumber(ptr, end, yPos, false))
-            return false;
-
-        skipOptionalSVGSpaces(ptr, end);
-
-        if (ptr < end && *ptr == ',') {
-            delimParsed = true;
-            ptr++;
-        }
-        skipOptionalSVGSpaces(ptr, end);
-
-        pointsList.append(FloatPoint(xPos, yPos));
-    }
-    return ptr == end && !delimParsed;
-}
-
-// FIXME: Why is the out parameter first?
-bool pointsListFromSVGData(SVGPointList& pointsList, const String& points)
-{
-    if (points.isEmpty())
-        return true;
-    if (points.is8Bit()) {
-        const LChar* ptr = points.characters8();
-        const LChar* end = ptr + points.length();
-        return genericParsePointsList(pointsList, ptr, end);
-    }
-    const UChar* ptr = points.characters16();
-    const UChar* end = ptr + points.length();
-    return genericParsePointsList(pointsList, ptr, end);
-}
-
-template<typename CharType>
 static bool parseGlyphName(const CharType*& ptr, const CharType* end, HashSet<String>& values)
 {
     skipOptionalSVGSpaces(ptr, end);
diff --git a/Source/core/svg/SVGParserUtilities.h b/Source/core/svg/SVGParserUtilities.h
index 2946cf1..ef48605 100644
--- a/Source/core/svg/SVGParserUtilities.h
+++ b/Source/core/svg/SVGParserUtilities.h
@@ -44,7 +44,6 @@
 bool parseNumberOptionalNumber(const String& s, float& h, float& v);
 bool parseArcFlag(const LChar*& ptr, const LChar* end, bool& flag);
 bool parseArcFlag(const UChar*& ptr, const UChar* end, bool& flag);
-bool parseRect(const String&, FloatRect&);
 
 template <typename CharType>
 bool parseFloatPoint(const CharType*& current, const CharType* end, FloatPoint&);
diff --git a/Source/core/svg/SVGPathBuilder.h b/Source/core/svg/SVGPathBuilder.h
index 0c6a15d..7679891 100644
--- a/Source/core/svg/SVGPathBuilder.h
+++ b/Source/core/svg/SVGPathBuilder.h
@@ -31,30 +31,30 @@
 
 class Path;
 
-class SVGPathBuilder : public SVGPathConsumer {
+class SVGPathBuilder FINAL : public SVGPathConsumer {
 public:
     SVGPathBuilder();
 
     void setCurrentPath(Path* path) { m_path = path; }
 
 private:
-    virtual void incrementPathSegmentCount() { }
-    virtual bool continueConsuming() { return true; }
-    virtual void cleanup() { m_path = 0; }
+    virtual void incrementPathSegmentCount() OVERRIDE { }
+    virtual bool continueConsuming() OVERRIDE { return true; }
+    virtual void cleanup() OVERRIDE { m_path = 0; }
 
     // Used in UnalteredParsing/NormalizedParsing modes.
-    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode);
-    virtual void lineTo(const FloatPoint&, PathCoordinateMode);
-    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void closePath();
+    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode) OVERRIDE;
+    virtual void lineTo(const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void closePath() OVERRIDE;
 
     // Only used in UnalteredParsing mode.
-    virtual void lineToHorizontal(float, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void lineToVertical(float, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void arcTo(float, float, float, bool, bool, const FloatPoint&, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
+    virtual void lineToHorizontal(float, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void lineToVertical(float, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void arcTo(float, float, float, bool, bool, const FloatPoint&, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
 
     Path* m_path;
     FloatPoint m_current;
diff --git a/Source/core/svg/SVGPathByteStream.h b/Source/core/svg/SVGPathByteStream.h
index 184dad4..1fedc1e 100644
--- a/Source/core/svg/SVGPathByteStream.h
+++ b/Source/core/svg/SVGPathByteStream.h
@@ -26,21 +26,11 @@
 
 namespace WebCore {
 
-// Type definitions for the byte stream data
-typedef union {
-    bool value;
-    unsigned char bytes[sizeof(bool)];
-} BoolByte;
-
-typedef union {
-    float value;
-    unsigned char bytes[sizeof(float)];
-} FloatByte;
-
-typedef union {
-    unsigned short value;
-    unsigned char bytes[sizeof(unsigned short)];
-} UnsignedShortByte;
+template<typename DataType>
+union ByteType {
+    DataType value;
+    unsigned char bytes[sizeof(DataType)];
+};
 
 class SVGPathByteStream {
     WTF_MAKE_FAST_ALLOCATED;
@@ -61,13 +51,11 @@
     DataIterator begin() { return m_data.begin(); }
     DataIterator end() { return m_data.end(); }
     void append(unsigned char byte) { m_data.append(byte); }
-    void append(SVGPathByteStream* other)
-    {
-        for (DataIterator it = other->begin(); it != other->end(); ++it)
-            append(*it);
-    }
+    void append(SVGPathByteStream* other) { m_data.append(other->m_data); }
     void clear() { m_data.clear(); }
-    bool isEmpty() const { return !m_data.size(); }
+    void reserveInitialCapacity(size_t size) { m_data.reserveInitialCapacity(size); }
+    void shrinkToFit() { m_data.shrinkToFit(); }
+    bool isEmpty() const { return m_data.isEmpty(); }
     unsigned size() const { return m_data.size(); }
 
     // Only defined to let SVGAnimatedPathAnimator use the standard list code paths - this method is never called.
diff --git a/Source/core/svg/SVGPathByteStreamBuilder.cpp b/Source/core/svg/SVGPathByteStreamBuilder.cpp
index 31e50d0..85a58a2 100644
--- a/Source/core/svg/SVGPathByteStreamBuilder.cpp
+++ b/Source/core/svg/SVGPathByteStreamBuilder.cpp
@@ -26,6 +26,49 @@
 
 namespace WebCore {
 
+// Helper class that coalesces writes to a SVGPathByteStream to a local buffer.
+class CoalescingBuffer {
+public:
+    CoalescingBuffer(SVGPathByteStream* byteStream)
+        : m_currentOffset(0)
+        , m_byteStream(byteStream)
+    {
+        ASSERT(byteStream);
+    }
+    ~CoalescingBuffer()
+    {
+        for (size_t i = 0; i < m_currentOffset; ++i)
+            m_byteStream->append(m_bytes[i]);
+    }
+
+    template<typename DataType>
+    void writeType(DataType value)
+    {
+        ByteType<DataType> data;
+        data.value = value;
+        size_t typeSize = sizeof(ByteType<DataType>);
+        ASSERT(m_currentOffset + typeSize <= sizeof(m_bytes));
+        memcpy(m_bytes + m_currentOffset, data.bytes, typeSize);
+        m_currentOffset += typeSize;
+    }
+
+    void writeFlag(bool value) { writeType<bool>(value); }
+    void writeFloat(float value) { writeType<float>(value); }
+    void writeFloatPoint(const FloatPoint& point)
+    {
+        writeType<float>(point.x());
+        writeType<float>(point.y());
+    }
+    void writeSegmentType(unsigned short value) { writeType<unsigned short>(value); }
+
+private:
+    // Adjust size to fit the largest command (in serialized/byte-stream format).
+    // Currently a cubic segment.
+    size_t m_currentOffset;
+    unsigned char m_bytes[sizeof(unsigned short) + sizeof(FloatPoint) * 3];
+    SVGPathByteStream* m_byteStream;
+};
+
 SVGPathByteStreamBuilder::SVGPathByteStreamBuilder()
     : m_byteStream(0)
 {
@@ -33,80 +76,80 @@
 
 void SVGPathByteStreamBuilder::moveTo(const FloatPoint& targetPoint, bool, PathCoordinateMode mode)
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(mode == RelativeCoordinates ?  PathSegMoveToRel : PathSegMoveToAbs);
-    writeFloatPoint(targetPoint);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(mode == RelativeCoordinates ?  PathSegMoveToRel : PathSegMoveToAbs);
+    buffer.writeFloatPoint(targetPoint);
 }
 
 void SVGPathByteStreamBuilder::lineTo(const FloatPoint& targetPoint, PathCoordinateMode mode)
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(mode == RelativeCoordinates ? PathSegLineToRel : PathSegLineToAbs);
-    writeFloatPoint(targetPoint);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(mode == RelativeCoordinates ? PathSegLineToRel : PathSegLineToAbs);
+    buffer.writeFloatPoint(targetPoint);
 }
 
 void SVGPathByteStreamBuilder::lineToHorizontal(float x, PathCoordinateMode mode)
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(mode == RelativeCoordinates ? PathSegLineToHorizontalRel : PathSegLineToHorizontalAbs);
-    writeFloat(x);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(mode == RelativeCoordinates ? PathSegLineToHorizontalRel : PathSegLineToHorizontalAbs);
+    buffer.writeFloat(x);
 }
 
 void SVGPathByteStreamBuilder::lineToVertical(float y, PathCoordinateMode mode)
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(mode == RelativeCoordinates ? PathSegLineToVerticalRel : PathSegLineToVerticalAbs);
-    writeFloat(y);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(mode == RelativeCoordinates ? PathSegLineToVerticalRel : PathSegLineToVerticalAbs);
+    buffer.writeFloat(y);
 }
 
 void SVGPathByteStreamBuilder::curveToCubic(const FloatPoint& point1, const FloatPoint& point2, const FloatPoint& targetPoint, PathCoordinateMode mode)
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(mode == RelativeCoordinates ? PathSegCurveToCubicRel : PathSegCurveToCubicAbs);
-    writeFloatPoint(point1);
-    writeFloatPoint(point2);
-    writeFloatPoint(targetPoint);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(mode == RelativeCoordinates ? PathSegCurveToCubicRel : PathSegCurveToCubicAbs);
+    buffer.writeFloatPoint(point1);
+    buffer.writeFloatPoint(point2);
+    buffer.writeFloatPoint(targetPoint);
 }
 
 void SVGPathByteStreamBuilder::curveToCubicSmooth(const FloatPoint& point2, const FloatPoint& targetPoint, PathCoordinateMode mode)
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(mode == RelativeCoordinates ? PathSegCurveToCubicSmoothRel : PathSegCurveToCubicSmoothAbs);
-    writeFloatPoint(point2);
-    writeFloatPoint(targetPoint);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(mode == RelativeCoordinates ? PathSegCurveToCubicSmoothRel : PathSegCurveToCubicSmoothAbs);
+    buffer.writeFloatPoint(point2);
+    buffer.writeFloatPoint(targetPoint);
 }
 
 void SVGPathByteStreamBuilder::curveToQuadratic(const FloatPoint& point1, const FloatPoint& targetPoint, PathCoordinateMode mode)
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(mode == RelativeCoordinates ? PathSegCurveToQuadraticRel : PathSegCurveToQuadraticAbs);
-    writeFloatPoint(point1);
-    writeFloatPoint(targetPoint);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(mode == RelativeCoordinates ? PathSegCurveToQuadraticRel : PathSegCurveToQuadraticAbs);
+    buffer.writeFloatPoint(point1);
+    buffer.writeFloatPoint(targetPoint);
 }
 
 void SVGPathByteStreamBuilder::curveToQuadraticSmooth(const FloatPoint& targetPoint, PathCoordinateMode mode)
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(mode == RelativeCoordinates ? PathSegCurveToQuadraticSmoothRel : PathSegCurveToQuadraticSmoothAbs);
-    writeFloatPoint(targetPoint);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(mode == RelativeCoordinates ? PathSegCurveToQuadraticSmoothRel : PathSegCurveToQuadraticSmoothAbs);
+    buffer.writeFloatPoint(targetPoint);
 }
 
 void SVGPathByteStreamBuilder::arcTo(float r1, float r2, float angle, bool largeArcFlag, bool sweepFlag, const FloatPoint& targetPoint, PathCoordinateMode mode)
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(mode == RelativeCoordinates ? PathSegArcRel : PathSegArcAbs);
-    writeFloat(r1);
-    writeFloat(r2);
-    writeFloat(angle);
-    writeFlag(largeArcFlag);
-    writeFlag(sweepFlag);
-    writeFloatPoint(targetPoint);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(mode == RelativeCoordinates ? PathSegArcRel : PathSegArcAbs);
+    buffer.writeFloat(r1);
+    buffer.writeFloat(r2);
+    buffer.writeFloat(angle);
+    buffer.writeFlag(largeArcFlag);
+    buffer.writeFlag(sweepFlag);
+    buffer.writeFloatPoint(targetPoint);
 }
 
 void SVGPathByteStreamBuilder::closePath()
 {
-    ASSERT(m_byteStream);
-    writeSegmentType(PathSegClosePath);
+    CoalescingBuffer buffer(m_byteStream);
+    buffer.writeSegmentType(PathSegClosePath);
 }
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathByteStreamBuilder.h b/Source/core/svg/SVGPathByteStreamBuilder.h
index b3fd747..493b77a 100644
--- a/Source/core/svg/SVGPathByteStreamBuilder.h
+++ b/Source/core/svg/SVGPathByteStreamBuilder.h
@@ -28,65 +28,30 @@
 
 namespace WebCore {
 
-class SVGPathByteStreamBuilder : public SVGPathConsumer {
+class SVGPathByteStreamBuilder FINAL : public SVGPathConsumer {
 public:
     SVGPathByteStreamBuilder();
 
     void setCurrentByteStream(SVGPathByteStream* byteStream) { m_byteStream = byteStream; }
 
 private:
-    virtual void incrementPathSegmentCount() { }
-    virtual bool continueConsuming() { return true; }
-    virtual void cleanup() { m_byteStream = 0; }
+    virtual void incrementPathSegmentCount() OVERRIDE { }
+    virtual bool continueConsuming() OVERRIDE { return true; }
+    virtual void cleanup() OVERRIDE { m_byteStream = 0; }
 
     // Used in UnalteredParsing/NormalizedParsing modes.
-    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode);
-    virtual void lineTo(const FloatPoint&, PathCoordinateMode);
-    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void closePath();
+    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode) OVERRIDE;
+    virtual void lineTo(const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void closePath() OVERRIDE;
 
     // Only used in UnalteredParsing mode.
-    virtual void lineToHorizontal(float, PathCoordinateMode);
-    virtual void lineToVertical(float, PathCoordinateMode);
-    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode);
-    virtual void arcTo(float, float, float, bool largeArcFlag, bool sweepFlag, const FloatPoint&, PathCoordinateMode);
-
-    template<typename ByteType>
-    void writeType(const ByteType& type)
-    {
-        size_t typeSize = sizeof(ByteType);
-        for (size_t i = 0; i < typeSize; ++i)
-            m_byteStream->append(type.bytes[i]);
-    }
-
-    void writeFlag(bool value)
-    {
-        BoolByte data;
-        data.value = value;
-        writeType(data);
-    }
-
-    void writeFloat(float value)
-    {
-        FloatByte data;
-        data.value = value;
-        writeType(data);
-    }
-
-    void writeFloatPoint(const FloatPoint& point)
-    {
-        writeFloat(point.x());
-        writeFloat(point.y());
-    }
-
-    void writeSegmentType(unsigned short value)
-    {
-        UnsignedShortByte data;
-        data.value = value;
-        writeType(data);
-    }
+    virtual void lineToHorizontal(float, PathCoordinateMode) OVERRIDE;
+    virtual void lineToVertical(float, PathCoordinateMode) OVERRIDE;
+    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void arcTo(float, float, float, bool largeArcFlag, bool sweepFlag, const FloatPoint&, PathCoordinateMode) OVERRIDE;
 
     SVGPathByteStream* m_byteStream;
 };
diff --git a/Source/core/svg/SVGPathByteStreamSource.h b/Source/core/svg/SVGPathByteStreamSource.h
index 9dedab5..17ff698 100644
--- a/Source/core/svg/SVGPathByteStreamSource.h
+++ b/Source/core/svg/SVGPathByteStreamSource.h
@@ -27,7 +27,7 @@
 
 namespace WebCore {
 
-class SVGPathByteStreamSource : public SVGPathSource {
+class SVGPathByteStreamSource FINAL : public SVGPathSource {
 public:
     static PassOwnPtr<SVGPathByteStreamSource> create(SVGPathByteStream* stream)
     {
@@ -37,58 +37,42 @@
 private:
     SVGPathByteStreamSource(SVGPathByteStream*);
 
-    virtual bool hasMoreData() const;
-    virtual bool moveToNextToken() { return true; }
-    virtual bool parseSVGSegmentType(SVGPathSegType&);
-    virtual SVGPathSegType nextCommand(SVGPathSegType);
+    virtual bool hasMoreData() const OVERRIDE;
+    virtual bool moveToNextToken() OVERRIDE { return true; }
+    virtual bool parseSVGSegmentType(SVGPathSegType&) OVERRIDE;
+    virtual SVGPathSegType nextCommand(SVGPathSegType) OVERRIDE;
 
-    virtual bool parseMoveToSegment(FloatPoint&);
-    virtual bool parseLineToSegment(FloatPoint&);
-    virtual bool parseLineToHorizontalSegment(float&);
-    virtual bool parseLineToVerticalSegment(float&);
-    virtual bool parseCurveToCubicSegment(FloatPoint&, FloatPoint&, FloatPoint&);
-    virtual bool parseCurveToCubicSmoothSegment(FloatPoint&, FloatPoint&);
-    virtual bool parseCurveToQuadraticSegment(FloatPoint&, FloatPoint&);
-    virtual bool parseCurveToQuadraticSmoothSegment(FloatPoint&);
-    virtual bool parseArcToSegment(float&, float&, float&, bool&, bool&, FloatPoint&);
+    virtual bool parseMoveToSegment(FloatPoint&) OVERRIDE;
+    virtual bool parseLineToSegment(FloatPoint&) OVERRIDE;
+    virtual bool parseLineToHorizontalSegment(float&) OVERRIDE;
+    virtual bool parseLineToVerticalSegment(float&) OVERRIDE;
+    virtual bool parseCurveToCubicSegment(FloatPoint&, FloatPoint&, FloatPoint&) OVERRIDE;
+    virtual bool parseCurveToCubicSmoothSegment(FloatPoint&, FloatPoint&) OVERRIDE;
+    virtual bool parseCurveToQuadraticSegment(FloatPoint&, FloatPoint&) OVERRIDE;
+    virtual bool parseCurveToQuadraticSmoothSegment(FloatPoint&) OVERRIDE;
+    virtual bool parseArcToSegment(float&, float&, float&, bool&, bool&, FloatPoint&) OVERRIDE;
 
 #if COMPILER(MSVC)
 #pragma warning(disable: 4701)
 #endif
-    template<typename DataType, typename ByteType>
+    template<typename DataType>
     DataType readType()
     {
-        ByteType data;
-        size_t typeSize = sizeof(ByteType);
-
-        for (size_t i = 0; i < typeSize; ++i) {
-            ASSERT(m_streamCurrent < m_streamEnd);
-            data.bytes[i] = *m_streamCurrent;
-            ++m_streamCurrent;
-        }
-
+        ByteType<DataType> data;
+        size_t typeSize = sizeof(ByteType<DataType>);
+        ASSERT(m_streamCurrent + typeSize <= m_streamEnd);
+        memcpy(data.bytes, m_streamCurrent, typeSize);
+        m_streamCurrent += typeSize;
         return data.value;
     }
 
-    bool readFlag()
-    {
-        return readType<bool, BoolByte>();
-    }
-
-    float readFloat()
-    {
-        return readType<float, FloatByte>();
-    }
-
-    unsigned short readSVGSegmentType()
-    {
-        return readType<unsigned short, UnsignedShortByte>();
-    }
-
+    bool readFlag() { return readType<bool>(); }
+    float readFloat() { return readType<float>(); }
+    unsigned short readSVGSegmentType() { return readType<unsigned short>(); }
     FloatPoint readFloatPoint()
     {
-        float x = readType<float, FloatByte>();
-        float y = readType<float, FloatByte>();
+        float x = readType<float>();
+        float y = readType<float>();
         return FloatPoint(x, y);
     }
 
diff --git a/Source/core/svg/SVGPathElement.cpp b/Source/core/svg/SVGPathElement.cpp
index 82af73a..4fcb1f1 100644
--- a/Source/core/svg/SVGPathElement.cpp
+++ b/Source/core/svg/SVGPathElement.cpp
@@ -46,6 +46,7 @@
 #include "core/svg/SVGPathSegMovetoAbs.h"
 #include "core/svg/SVGPathSegMovetoRel.h"
 #include "core/svg/SVGPathUtilities.h"
+#include "core/svg/SVGPointTearOff.h"
 #include "core/svg/properties/SVGPathSegListPropertyTearOff.h"
 
 namespace WebCore {
@@ -66,13 +67,8 @@
 }
 
 // Animated property definitions
-DEFINE_ANIMATED_NUMBER(SVGPathElement, SVGNames::pathLengthAttr, PathLength, pathLength)
-DEFINE_ANIMATED_BOOLEAN(SVGPathElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGPathElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(d)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(pathLength)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
@@ -81,8 +77,11 @@
     , m_pathByteStream(SVGPathByteStream::create())
     , m_pathSegList(PathSegUnalteredRole)
     , m_isAnimValObserved(false)
+    , m_pathLength(SVGAnimatedNumber::create(this, SVGNames::pathLengthAttr, SVGNumber::create()))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_pathLength);
     registerAnimatedPropertiesForSVGPathElement();
 }
 
@@ -98,11 +97,11 @@
     return totalLength;
 }
 
-SVGPoint SVGPathElement::getPointAtLength(float length)
+PassRefPtr<SVGPointTearOff> SVGPathElement::getPointAtLength(float length)
 {
-    SVGPoint point;
+    FloatPoint point;
     getPointAtLengthOfSVGPathByteStream(pathByteStream(), length, point);
-    return point;
+    return SVGPointTearOff::create(SVGPoint::create(point), 0, PropertyIsNotAnimVal);
 }
 
 unsigned SVGPathElement::getPathSegAtLength(float length)
@@ -211,7 +210,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::dAttr);
         supportedAttributes.add(SVGNames::pathLengthAttr);
     }
@@ -231,17 +229,17 @@
         return;
     }
 
+    SVGParsingError parseError = NoError;
+
     if (name == SVGNames::pathLengthAttr) {
-        setPathLengthBaseValue(value.toFloat());
-        if (pathLengthBaseValue() < 0)
+        m_pathLength->setBaseValueAsString(value, parseError);
+        if (parseError == NoError && m_pathLength->baseValue()->value() < 0)
             document().accessSVGExtensions()->reportError("A negative value for path attribute <pathLength> is not allowed");
-        return;
+    } else {
+        ASSERT_NOT_REACHED();
     }
 
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGPathElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -327,7 +325,7 @@
     SVGPathElement* ownerType = toSVGPathElement(contextElement);
     if (!ownerType->m_pathSegList.shouldSynchronize)
         return;
-    ownerType->m_pathSegList.synchronize(ownerType, dPropertyInfo()->attributeName, ownerType->m_pathSegList.value.valueAsString());
+    ownerType->m_pathSegList.synchronize(ownerType, dPropertyInfo()->attributeName, AtomicString(ownerType->m_pathSegList.value.valueAsString()));
 }
 
 SVGPathSegListPropertyTearOff* SVGPathElement::pathSegList()
@@ -382,7 +380,7 @@
     RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
 }
 
-SVGRect SVGPathElement::getBBox()
+FloatRect SVGPathElement::getBBox()
 {
     // By default, getBBox() returns objectBoundingBox but that will include
     // markers so we override it to return just the path's bounding rect.
@@ -391,16 +389,10 @@
 
     // FIXME: Eventually we should support getBBox for detached elements.
     if (!renderer())
-        return SVGRect();
+        return FloatRect();
 
     RenderSVGPath* renderer = toRenderSVGPath(this->renderer());
     return renderer->path().boundingRect();
 }
 
-RenderObject* SVGPathElement::createRenderer(RenderStyle*)
-{
-    // By default, any subclass is expected to do path-based drawing
-    return new RenderSVGPath(this);
-}
-
 }
diff --git a/Source/core/svg/SVGPathElement.h b/Source/core/svg/SVGPathElement.h
index adc861c..99722ab 100644
--- a/Source/core/svg/SVGPathElement.h
+++ b/Source/core/svg/SVGPathElement.h
@@ -24,7 +24,6 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedNumber.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGeometryElement.h"
 #include "core/svg/SVGPathByteStream.h"
 #include "core/svg/SVGPathSegList.h"
@@ -52,15 +51,16 @@
 class SVGPathSegCurvetoQuadraticSmoothRel;
 class SVGPathSegListPropertyTearOff;
 
-class SVGPathElement FINAL : public SVGGeometryElement,
-                             public SVGExternalResourcesRequired {
+class SVGPathElement FINAL : public SVGGeometryElement {
 public:
     static PassRefPtr<SVGPathElement> create(Document&);
 
     float getTotalLength();
-    SVGPoint getPointAtLength(float distance);
+    PassRefPtr<SVGPointTearOff> getPointAtLength(float distance);
     unsigned getPathSegAtLength(float distance);
 
+    SVGAnimatedNumber* pathLength() { return m_pathLength.get(); }
+
     PassRefPtr<SVGPathSegClosePath> createSVGPathSegClosePath(SVGPathSegRole role = PathSegUndefinedRole);
     PassRefPtr<SVGPathSegMovetoAbs> createSVGPathSegMovetoAbs(float x, float y, SVGPathSegRole role = PathSegUndefinedRole);
     PassRefPtr<SVGPathSegMovetoRel> createSVGPathSegMovetoRel(float x, float y, SVGPathSegRole role = PathSegUndefinedRole);
@@ -91,7 +91,7 @@
 
     void pathSegListChanged(SVGPathSegRole, ListModification = ListModificationUnknown);
 
-    virtual SVGRect getBBox() OVERRIDE FINAL;
+    virtual FloatRect getBBox() OVERRIDE;
 
     static const SVGPropertyInfo* dPropertyInfo();
 
@@ -100,20 +100,17 @@
 private:
     explicit SVGPathElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual bool supportsMarkers() const { return true; }
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual bool supportsMarkers() const OVERRIDE { return true; }
 
     // Custom 'd' property
     static void synchronizeD(SVGElement* contextElement);
     static PassRefPtr<SVGAnimatedProperty> lookupOrCreateDWrapper(SVGElement* contextElement);
 
-    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-
     virtual Node::InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
@@ -123,9 +120,8 @@
     mutable SVGSynchronizableAnimatedProperty<SVGPathSegList> m_pathSegList;
     bool m_isAnimValObserved;
 
+    RefPtr<SVGAnimatedNumber> m_pathLength;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGPathElement)
-        DECLARE_ANIMATED_NUMBER(PathLength, pathLength)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGPathElement.idl b/Source/core/svg/SVGPathElement.idl
index 297b5b1..5acffd0 100644
--- a/Source/core/svg/SVGPathElement.idl
+++ b/Source/core/svg/SVGPathElement.idl
@@ -24,52 +24,56 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathElement : SVGGeometryElement {
+[
+    StrictTypeChecking,
+] interface SVGPathElement : SVGGeometryElement {
     readonly attribute SVGAnimatedNumber pathLength;
 
     float getTotalLength();
-    [StrictTypeChecking] SVGPoint getPointAtLength(float distance);
-    [StrictTypeChecking] unsigned long getPathSegAtLength(float distance);
+    SVGPoint getPointAtLength(float distance);
+    unsigned long getPathSegAtLength(float distance);
 
     SVGPathSegClosePath createSVGPathSegClosePath();
 
-    [StrictTypeChecking] SVGPathSegMovetoAbs createSVGPathSegMovetoAbs(float x, float y);
-    [StrictTypeChecking] SVGPathSegMovetoRel createSVGPathSegMovetoRel(float x, float y);
+    SVGPathSegMovetoAbs createSVGPathSegMovetoAbs(float x, float y);
+    SVGPathSegMovetoRel createSVGPathSegMovetoRel(float x, float y);
 
-    [StrictTypeChecking] SVGPathSegLinetoAbs createSVGPathSegLinetoAbs(float x, float y);
-    [StrictTypeChecking] SVGPathSegLinetoRel createSVGPathSegLinetoRel(float x, float y);
+    SVGPathSegLinetoAbs createSVGPathSegLinetoAbs(float x, float y);
+    SVGPathSegLinetoRel createSVGPathSegLinetoRel(float x, float y);
 
-    [StrictTypeChecking] SVGPathSegCurvetoCubicAbs
-        createSVGPathSegCurvetoCubicAbs(float x, float y, float x1, float y1, float x2, float y2);
-    [StrictTypeChecking] SVGPathSegCurvetoCubicRel
-        createSVGPathSegCurvetoCubicRel(float x, float y, float x1, float y1, float x2, float y2);
+    SVGPathSegCurvetoCubicAbs createSVGPathSegCurvetoCubicAbs(
+        float x, float y, float x1, float y1, float x2, float y2);
+    SVGPathSegCurvetoCubicRel createSVGPathSegCurvetoCubicRel(
+        float x, float y, float x1, float y1, float x2, float y2);
 
-    [StrictTypeChecking] SVGPathSegCurvetoQuadraticAbs
-        createSVGPathSegCurvetoQuadraticAbs(float x, float y, float x1, float y1);
-    [StrictTypeChecking] SVGPathSegCurvetoQuadraticRel
-        createSVGPathSegCurvetoQuadraticRel(float x, float y, float x1, float y1);
+    SVGPathSegCurvetoQuadraticAbs createSVGPathSegCurvetoQuadraticAbs(
+        float x, float y, float x1, float y1);
+    SVGPathSegCurvetoQuadraticRel createSVGPathSegCurvetoQuadraticRel(
+        float x, float y, float x1, float y1);
 
-    [StrictTypeChecking] SVGPathSegArcAbs
-        createSVGPathSegArcAbs(float x, float y, float r1, float r2, float angle, boolean largeArcFlag, boolean sweepFlag);
-    [StrictTypeChecking] SVGPathSegArcRel
-        createSVGPathSegArcRel(float x, float y, float r1, float r2, float angle, boolean largeArcFlag, boolean sweepFlag);
+    SVGPathSegArcAbs createSVGPathSegArcAbs(
+        float x, float y, float r1, float r2,
+        float angle, boolean largeArcFlag, boolean sweepFlag);
+    SVGPathSegArcRel createSVGPathSegArcRel(
+        float x, float y, float r1, float r2,
+        float angle, boolean largeArcFlag, boolean sweepFlag);
 
-    [StrictTypeChecking] SVGPathSegLinetoHorizontalAbs createSVGPathSegLinetoHorizontalAbs(float x);
-    [StrictTypeChecking] SVGPathSegLinetoHorizontalRel createSVGPathSegLinetoHorizontalRel(float x);
+    SVGPathSegLinetoHorizontalAbs createSVGPathSegLinetoHorizontalAbs(float x);
+    SVGPathSegLinetoHorizontalRel createSVGPathSegLinetoHorizontalRel(float x);
 
-    [StrictTypeChecking] SVGPathSegLinetoVerticalAbs createSVGPathSegLinetoVerticalAbs(float y);
-    [StrictTypeChecking] SVGPathSegLinetoVerticalRel createSVGPathSegLinetoVerticalRel(float y);
+    SVGPathSegLinetoVerticalAbs createSVGPathSegLinetoVerticalAbs(float y);
+    SVGPathSegLinetoVerticalRel createSVGPathSegLinetoVerticalRel(float y);
 
-    [StrictTypeChecking] SVGPathSegCurvetoCubicSmoothAbs createSVGPathSegCurvetoCubicSmoothAbs(float x, float y, float x2, float y2);
-    [StrictTypeChecking] SVGPathSegCurvetoCubicSmoothRel createSVGPathSegCurvetoCubicSmoothRel(float x, float y, float x2, float y2);
+    SVGPathSegCurvetoCubicSmoothAbs createSVGPathSegCurvetoCubicSmoothAbs(
+        float x, float y, float x2, float y2);
+    SVGPathSegCurvetoCubicSmoothRel createSVGPathSegCurvetoCubicSmoothRel(
+        float x, float y, float x2, float y2);
 
-    [StrictTypeChecking] SVGPathSegCurvetoQuadraticSmoothAbs createSVGPathSegCurvetoQuadraticSmoothAbs(float x, float y);
-    [StrictTypeChecking] SVGPathSegCurvetoQuadraticSmoothRel createSVGPathSegCurvetoQuadraticSmoothRel(float x, float y);
+    SVGPathSegCurvetoQuadraticSmoothAbs createSVGPathSegCurvetoQuadraticSmoothAbs(float x, float y);
+    SVGPathSegCurvetoQuadraticSmoothRel createSVGPathSegCurvetoQuadraticSmoothRel(float x, float y);
 
     readonly attribute SVGPathSegList pathSegList;
     readonly attribute SVGPathSegList normalizedPathSegList;
     readonly attribute SVGPathSegList animatedPathSegList;
     readonly attribute SVGPathSegList animatedNormalizedPathSegList;
 };
-
-SVGPathElement implements SVGExternalResourcesRequired;
diff --git a/Source/core/svg/SVGPathSegArcAbs.h b/Source/core/svg/SVGPathSegArcAbs.h
index 85e686e..74bfcda 100644
--- a/Source/core/svg/SVGPathSegArcAbs.h
+++ b/Source/core/svg/SVGPathSegArcAbs.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegArcAbs : public SVGPathSegArc {
+class SVGPathSegArcAbs FINAL : public SVGPathSegArc {
 public:
     static PassRefPtr<SVGPathSegArcAbs> create(SVGPathElement* element, SVGPathSegRole role, float x, float y, float r1, float r2, float angle, bool largeArcFlag, bool sweepFlag)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_ARC_ABS; }
-    virtual String pathSegTypeAsLetter() const { return "A"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_ARC_ABS; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "A"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegArcAbs.idl b/Source/core/svg/SVGPathSegArcAbs.idl
index a50286f..2f8e401 100644
--- a/Source/core/svg/SVGPathSegArcAbs.idl
+++ b/Source/core/svg/SVGPathSegArcAbs.idl
@@ -24,13 +24,14 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegArcAbs : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
-    [StrictTypeChecking] attribute float r1;
-    [StrictTypeChecking] attribute float r2;
-    [StrictTypeChecking] attribute float angle;
-    [StrictTypeChecking] attribute boolean largeArcFlag;
-    [StrictTypeChecking] attribute boolean sweepFlag;
+[
+    StrictTypeChecking,
+] interface SVGPathSegArcAbs : SVGPathSeg {
+    attribute float x;
+    attribute float y;
+    attribute float r1;
+    attribute float r2;
+    attribute float angle;
+    attribute boolean largeArcFlag;
+    attribute boolean sweepFlag;
 };
-
diff --git a/Source/core/svg/SVGPathSegArcRel.h b/Source/core/svg/SVGPathSegArcRel.h
index 076c930..5add5de 100644
--- a/Source/core/svg/SVGPathSegArcRel.h
+++ b/Source/core/svg/SVGPathSegArcRel.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegArcRel : public SVGPathSegArc {
+class SVGPathSegArcRel FINAL : public SVGPathSegArc {
 public:
     static PassRefPtr<SVGPathSegArcRel> create(SVGPathElement* element, SVGPathSegRole role, float x, float y, float r1, float r2, float angle, bool largeArcFlag, bool sweepFlag)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_ARC_REL; }
-    virtual String pathSegTypeAsLetter() const { return "a"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_ARC_REL; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "a"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegArcRel.idl b/Source/core/svg/SVGPathSegArcRel.idl
index d682c2c..2c81a87 100644
--- a/Source/core/svg/SVGPathSegArcRel.idl
+++ b/Source/core/svg/SVGPathSegArcRel.idl
@@ -24,13 +24,14 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegArcRel : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
-    [StrictTypeChecking] attribute float r1;
-    [StrictTypeChecking] attribute float r2;
-    [StrictTypeChecking] attribute float angle;
-    [StrictTypeChecking] attribute boolean largeArcFlag;
-    [StrictTypeChecking] attribute boolean sweepFlag;
+[
+    StrictTypeChecking,
+] interface SVGPathSegArcRel : SVGPathSeg {
+    attribute float x;
+    attribute float y;
+    attribute float r1;
+    attribute float r2;
+    attribute float angle;
+    attribute boolean largeArcFlag;
+    attribute boolean sweepFlag;
 };
-
diff --git a/Source/core/svg/SVGPathSegClosePath.h b/Source/core/svg/SVGPathSegClosePath.h
index 4c6adc2..5f2258f 100644
--- a/Source/core/svg/SVGPathSegClosePath.h
+++ b/Source/core/svg/SVGPathSegClosePath.h
@@ -25,7 +25,7 @@
 
 namespace WebCore {
 
-class SVGPathSegClosePath : public SVGPathSegWithContext {
+class SVGPathSegClosePath FINAL : public SVGPathSegWithContext {
 public:
     static PassRefPtr<SVGPathSegClosePath> create(SVGPathElement* element, SVGPathSegRole role)
     {
@@ -39,8 +39,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_CLOSEPATH; }
-    virtual String pathSegTypeAsLetter() const { return "Z"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_CLOSEPATH; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "Z"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegCurvetoCubicAbs.h b/Source/core/svg/SVGPathSegCurvetoCubicAbs.h
index 56718a8..77c6186 100644
--- a/Source/core/svg/SVGPathSegCurvetoCubicAbs.h
+++ b/Source/core/svg/SVGPathSegCurvetoCubicAbs.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegCurvetoCubicAbs : public SVGPathSegCurvetoCubic {
+class SVGPathSegCurvetoCubicAbs FINAL : public SVGPathSegCurvetoCubic {
 public:
     static PassRefPtr<SVGPathSegCurvetoCubicAbs> create(SVGPathElement* element, SVGPathSegRole role, float x, float y, float x1, float y1, float x2, float y2)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_CURVETO_CUBIC_ABS; }
-    virtual String pathSegTypeAsLetter() const { return "C"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_CURVETO_CUBIC_ABS; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "C"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegCurvetoCubicAbs.idl b/Source/core/svg/SVGPathSegCurvetoCubicAbs.idl
index 982cb68..c8703d6 100644
--- a/Source/core/svg/SVGPathSegCurvetoCubicAbs.idl
+++ b/Source/core/svg/SVGPathSegCurvetoCubicAbs.idl
@@ -24,12 +24,14 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegCurvetoCubicAbs : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
-    [StrictTypeChecking] attribute float x1;
-    [StrictTypeChecking] attribute float y1;
-    [StrictTypeChecking] attribute float x2;
-    [StrictTypeChecking] attribute float y2;
+[
+    StrictTypeChecking,
+] interface SVGPathSegCurvetoCubicAbs : SVGPathSeg {
+    attribute float x;
+    attribute float y;
+    attribute float x1;
+    attribute float y1;
+    attribute float x2;
+    attribute float y2;
 };
 
diff --git a/Source/core/svg/SVGPathSegCurvetoCubicRel.h b/Source/core/svg/SVGPathSegCurvetoCubicRel.h
index 3910fcd..bd944d3 100644
--- a/Source/core/svg/SVGPathSegCurvetoCubicRel.h
+++ b/Source/core/svg/SVGPathSegCurvetoCubicRel.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegCurvetoCubicRel : public SVGPathSegCurvetoCubic {
+class SVGPathSegCurvetoCubicRel FINAL : public SVGPathSegCurvetoCubic {
 public:
     static PassRefPtr<SVGPathSegCurvetoCubicRel> create(SVGPathElement* element, SVGPathSegRole role, float x, float y, float x1, float y1, float x2, float y2)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_CURVETO_CUBIC_REL; }
-    virtual String pathSegTypeAsLetter() const { return "c"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_CURVETO_CUBIC_REL; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "c"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegCurvetoCubicRel.idl b/Source/core/svg/SVGPathSegCurvetoCubicRel.idl
index 352bb42..645276d 100644
--- a/Source/core/svg/SVGPathSegCurvetoCubicRel.idl
+++ b/Source/core/svg/SVGPathSegCurvetoCubicRel.idl
@@ -24,12 +24,14 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegCurvetoCubicRel : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
-    [StrictTypeChecking] attribute float x1;
-    [StrictTypeChecking] attribute float y1;
-    [StrictTypeChecking] attribute float x2;
-    [StrictTypeChecking] attribute float y2;
+[
+    StrictTypeChecking,
+] interface SVGPathSegCurvetoCubicRel : SVGPathSeg {
+    attribute float x;
+    attribute float y;
+    attribute float x1;
+    attribute float y1;
+    attribute float x2;
+    attribute float y2;
 };
 
diff --git a/Source/core/svg/SVGPathSegCurvetoCubicSmoothAbs.h b/Source/core/svg/SVGPathSegCurvetoCubicSmoothAbs.h
index 3e36a58..d1f3fa4 100644
--- a/Source/core/svg/SVGPathSegCurvetoCubicSmoothAbs.h
+++ b/Source/core/svg/SVGPathSegCurvetoCubicSmoothAbs.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegCurvetoCubicSmoothAbs : public SVGPathSegCurvetoCubicSmooth {
+class SVGPathSegCurvetoCubicSmoothAbs FINAL : public SVGPathSegCurvetoCubicSmooth {
 public:
     static PassRefPtr<SVGPathSegCurvetoCubicSmoothAbs> create(SVGPathElement* element, SVGPathSegRole role, float x, float y, float x2, float y2)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_CURVETO_CUBIC_SMOOTH_ABS; }
-    virtual String pathSegTypeAsLetter() const { return "S"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_CURVETO_CUBIC_SMOOTH_ABS; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "S"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegCurvetoCubicSmoothAbs.idl b/Source/core/svg/SVGPathSegCurvetoCubicSmoothAbs.idl
index 050926a..aba3847 100644
--- a/Source/core/svg/SVGPathSegCurvetoCubicSmoothAbs.idl
+++ b/Source/core/svg/SVGPathSegCurvetoCubicSmoothAbs.idl
@@ -24,10 +24,11 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegCurvetoCubicSmoothAbs : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
-    [StrictTypeChecking] attribute float x2;
-    [StrictTypeChecking] attribute float y2;
+[
+    StrictTypeChecking,
+] interface SVGPathSegCurvetoCubicSmoothAbs : SVGPathSeg {
+    attribute float x;
+    attribute float y;
+    attribute float x2;
+    attribute float y2;
 };
-
diff --git a/Source/core/svg/SVGPathSegCurvetoCubicSmoothRel.h b/Source/core/svg/SVGPathSegCurvetoCubicSmoothRel.h
index 4b7be69..2fa5b9c 100644
--- a/Source/core/svg/SVGPathSegCurvetoCubicSmoothRel.h
+++ b/Source/core/svg/SVGPathSegCurvetoCubicSmoothRel.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegCurvetoCubicSmoothRel : public SVGPathSegCurvetoCubicSmooth {
+class SVGPathSegCurvetoCubicSmoothRel FINAL : public SVGPathSegCurvetoCubicSmooth {
 public:
     static PassRefPtr<SVGPathSegCurvetoCubicSmoothRel> create(SVGPathElement* element, SVGPathSegRole role, float x, float y, float x2, float y2)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_CURVETO_CUBIC_SMOOTH_REL; }
-    virtual String pathSegTypeAsLetter() const { return "s"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_CURVETO_CUBIC_SMOOTH_REL; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "s"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegCurvetoCubicSmoothRel.idl b/Source/core/svg/SVGPathSegCurvetoCubicSmoothRel.idl
index 85605de..34294a0 100644
--- a/Source/core/svg/SVGPathSegCurvetoCubicSmoothRel.idl
+++ b/Source/core/svg/SVGPathSegCurvetoCubicSmoothRel.idl
@@ -24,10 +24,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegCurvetoCubicSmoothRel : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
-    [StrictTypeChecking] attribute float x2;
-    [StrictTypeChecking] attribute float y2;
+[
+    StrictTypeChecking,
+] interface SVGPathSegCurvetoCubicSmoothRel : SVGPathSeg {
+    attribute float x;
+    attribute float y;
+    attribute float x2;
+    attribute float y2;
 };
 
diff --git a/Source/core/svg/SVGPathSegCurvetoQuadraticAbs.h b/Source/core/svg/SVGPathSegCurvetoQuadraticAbs.h
index 6d25dfe..16aadbd 100644
--- a/Source/core/svg/SVGPathSegCurvetoQuadraticAbs.h
+++ b/Source/core/svg/SVGPathSegCurvetoQuadraticAbs.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegCurvetoQuadraticAbs : public SVGPathSegCurvetoQuadratic {
+class SVGPathSegCurvetoQuadraticAbs FINAL : public SVGPathSegCurvetoQuadratic {
 public:
     static PassRefPtr<SVGPathSegCurvetoQuadraticAbs> create(SVGPathElement* element, SVGPathSegRole role, float x, float y, float x1, float y1)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_CURVETO_QUADRATIC_ABS; }
-    virtual String pathSegTypeAsLetter() const { return "Q"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_CURVETO_QUADRATIC_ABS; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "Q"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegCurvetoQuadraticAbs.idl b/Source/core/svg/SVGPathSegCurvetoQuadraticAbs.idl
index 7549e8e..7500b40 100644
--- a/Source/core/svg/SVGPathSegCurvetoQuadraticAbs.idl
+++ b/Source/core/svg/SVGPathSegCurvetoQuadraticAbs.idl
@@ -24,10 +24,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegCurvetoQuadraticAbs : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
-    [StrictTypeChecking] attribute float x1;
-    [StrictTypeChecking] attribute float y1;
+[
+    StrictTypeChecking,
+] interface SVGPathSegCurvetoQuadraticAbs : SVGPathSeg {
+    attribute float x;
+    attribute float y;
+    attribute float x1;
+    attribute float y1;
 };
 
diff --git a/Source/core/svg/SVGPathSegCurvetoQuadraticRel.h b/Source/core/svg/SVGPathSegCurvetoQuadraticRel.h
index 2c51a8b..ad2725a 100644
--- a/Source/core/svg/SVGPathSegCurvetoQuadraticRel.h
+++ b/Source/core/svg/SVGPathSegCurvetoQuadraticRel.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegCurvetoQuadraticRel : public SVGPathSegCurvetoQuadratic {
+class SVGPathSegCurvetoQuadraticRel FINAL : public SVGPathSegCurvetoQuadratic {
 public:
     static PassRefPtr<SVGPathSegCurvetoQuadraticRel> create(SVGPathElement* element, SVGPathSegRole role, float x, float y, float x1, float y1)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_CURVETO_QUADRATIC_REL; }
-    virtual String pathSegTypeAsLetter() const { return "q"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_CURVETO_QUADRATIC_REL; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "q"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegCurvetoQuadraticRel.idl b/Source/core/svg/SVGPathSegCurvetoQuadraticRel.idl
index cfd7e87..7554dfe 100644
--- a/Source/core/svg/SVGPathSegCurvetoQuadraticRel.idl
+++ b/Source/core/svg/SVGPathSegCurvetoQuadraticRel.idl
@@ -24,10 +24,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegCurvetoQuadraticRel : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
-    [StrictTypeChecking] attribute float x1;
-    [StrictTypeChecking] attribute float y1;
+[
+    StrictTypeChecking,
+] interface SVGPathSegCurvetoQuadraticRel : SVGPathSeg {
+    attribute float x;
+    attribute float y;
+    attribute float x1;
+    attribute float y1;
 };
 
diff --git a/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothAbs.h b/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothAbs.h
index 87b4942..e797b1d 100644
--- a/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothAbs.h
+++ b/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothAbs.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegCurvetoQuadraticSmoothAbs : public SVGPathSegSingleCoordinate {
+class SVGPathSegCurvetoQuadraticSmoothAbs FINAL : public SVGPathSegSingleCoordinate {
 public:
     static PassRefPtr<SVGPathSegCurvetoQuadraticSmoothAbs> create(SVGPathElement* element, SVGPathSegRole role, float x, float y)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS; }
-    virtual String pathSegTypeAsLetter() const { return "T"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "T"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothAbs.idl b/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothAbs.idl
index b5c5d3d..e84fa8c 100644
--- a/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothAbs.idl
+++ b/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothAbs.idl
@@ -24,8 +24,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegCurvetoQuadraticSmoothAbs : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
+[
+    StrictTypeChecking,
+] interface SVGPathSegCurvetoQuadraticSmoothAbs : SVGPathSeg {
+    attribute float x;
+    attribute float y;
 };
-
diff --git a/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothRel.h b/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothRel.h
index 8506e15..c011c42 100644
--- a/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothRel.h
+++ b/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothRel.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegCurvetoQuadraticSmoothRel : public SVGPathSegSingleCoordinate {
+class SVGPathSegCurvetoQuadraticSmoothRel FINAL : public SVGPathSegSingleCoordinate {
 public:
     static PassRefPtr<SVGPathSegCurvetoQuadraticSmoothRel> create(SVGPathElement* element, SVGPathSegRole role, float x, float y)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL; }
-    virtual String pathSegTypeAsLetter() const { return "t"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "t"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothRel.idl b/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothRel.idl
index d464af0..b50e2ae 100644
--- a/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothRel.idl
+++ b/Source/core/svg/SVGPathSegCurvetoQuadraticSmoothRel.idl
@@ -24,8 +24,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegCurvetoQuadraticSmoothRel : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
+[
+    StrictTypeChecking,
+] interface SVGPathSegCurvetoQuadraticSmoothRel : SVGPathSeg {
+    attribute float x;
+    attribute float y;
 };
-
diff --git a/Source/core/svg/SVGPathSegLinetoAbs.h b/Source/core/svg/SVGPathSegLinetoAbs.h
index ee575ea..b452ba3 100644
--- a/Source/core/svg/SVGPathSegLinetoAbs.h
+++ b/Source/core/svg/SVGPathSegLinetoAbs.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegLinetoAbs : public SVGPathSegSingleCoordinate {
+class SVGPathSegLinetoAbs FINAL : public SVGPathSegSingleCoordinate {
 public:
     static PassRefPtr<SVGPathSegLinetoAbs> create(SVGPathElement* element, SVGPathSegRole role, float x, float y)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_LINETO_ABS; }
-    virtual String pathSegTypeAsLetter() const { return "L"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_LINETO_ABS; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "L"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegLinetoAbs.idl b/Source/core/svg/SVGPathSegLinetoAbs.idl
index 1f9dd98..c6fb097 100644
--- a/Source/core/svg/SVGPathSegLinetoAbs.idl
+++ b/Source/core/svg/SVGPathSegLinetoAbs.idl
@@ -24,8 +24,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegLinetoAbs : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
+[
+    StrictTypeChecking,
+] interface SVGPathSegLinetoAbs : SVGPathSeg {
+    attribute float x;
+    attribute float y;
 };
-
diff --git a/Source/core/svg/SVGPathSegLinetoHorizontalAbs.h b/Source/core/svg/SVGPathSegLinetoHorizontalAbs.h
index 8e8f806..a54d7d1 100644
--- a/Source/core/svg/SVGPathSegLinetoHorizontalAbs.h
+++ b/Source/core/svg/SVGPathSegLinetoHorizontalAbs.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegLinetoHorizontalAbs : public SVGPathSegLinetoHorizontal {
+class SVGPathSegLinetoHorizontalAbs FINAL : public SVGPathSegLinetoHorizontal {
 public:
     static PassRefPtr<SVGPathSegLinetoHorizontalAbs> create(SVGPathElement* element, SVGPathSegRole role, float x)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_LINETO_HORIZONTAL_ABS; }
-    virtual String pathSegTypeAsLetter() const { return "H"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_LINETO_HORIZONTAL_ABS; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "H"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegLinetoHorizontalAbs.idl b/Source/core/svg/SVGPathSegLinetoHorizontalAbs.idl
index f36159d..16d58db 100644
--- a/Source/core/svg/SVGPathSegLinetoHorizontalAbs.idl
+++ b/Source/core/svg/SVGPathSegLinetoHorizontalAbs.idl
@@ -24,7 +24,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegLinetoHorizontalAbs : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
+[
+    StrictTypeChecking,
+] interface SVGPathSegLinetoHorizontalAbs : SVGPathSeg {
+    attribute float x;
 };
-
diff --git a/Source/core/svg/SVGPathSegLinetoHorizontalRel.h b/Source/core/svg/SVGPathSegLinetoHorizontalRel.h
index 974c41c..5c172a4 100644
--- a/Source/core/svg/SVGPathSegLinetoHorizontalRel.h
+++ b/Source/core/svg/SVGPathSegLinetoHorizontalRel.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegLinetoHorizontalRel : public SVGPathSegLinetoHorizontal {
+class SVGPathSegLinetoHorizontalRel FINAL : public SVGPathSegLinetoHorizontal {
 public:
     static PassRefPtr<SVGPathSegLinetoHorizontalRel> create(SVGPathElement* element, SVGPathSegRole role, float x)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_LINETO_HORIZONTAL_REL; }
-    virtual String pathSegTypeAsLetter() const { return "h"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_LINETO_HORIZONTAL_REL; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "h"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegLinetoHorizontalRel.idl b/Source/core/svg/SVGPathSegLinetoHorizontalRel.idl
index fdbb1c8..d48b6f6 100644
--- a/Source/core/svg/SVGPathSegLinetoHorizontalRel.idl
+++ b/Source/core/svg/SVGPathSegLinetoHorizontalRel.idl
@@ -24,7 +24,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegLinetoHorizontalRel : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
+[
+    StrictTypeChecking,
+] interface SVGPathSegLinetoHorizontalRel : SVGPathSeg {
+    attribute float x;
 };
-
diff --git a/Source/core/svg/SVGPathSegLinetoRel.h b/Source/core/svg/SVGPathSegLinetoRel.h
index 53dc883..d92d59f 100644
--- a/Source/core/svg/SVGPathSegLinetoRel.h
+++ b/Source/core/svg/SVGPathSegLinetoRel.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegLinetoRel : public SVGPathSegSingleCoordinate {
+class SVGPathSegLinetoRel FINAL : public SVGPathSegSingleCoordinate {
 public:
     static PassRefPtr<SVGPathSegLinetoRel> create(SVGPathElement* element, SVGPathSegRole role, float x, float y)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_LINETO_REL; }
-    virtual String pathSegTypeAsLetter() const { return "l"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_LINETO_REL; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "l"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegLinetoRel.idl b/Source/core/svg/SVGPathSegLinetoRel.idl
index 4d24898..fc3b88f 100644
--- a/Source/core/svg/SVGPathSegLinetoRel.idl
+++ b/Source/core/svg/SVGPathSegLinetoRel.idl
@@ -24,8 +24,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegLinetoRel : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
+[
+    StrictTypeChecking,
+] interface SVGPathSegLinetoRel : SVGPathSeg {
+    attribute float x;
+    attribute float y;
 };
-
diff --git a/Source/core/svg/SVGPathSegLinetoVerticalAbs.h b/Source/core/svg/SVGPathSegLinetoVerticalAbs.h
index 66d86a1..a8f9623 100644
--- a/Source/core/svg/SVGPathSegLinetoVerticalAbs.h
+++ b/Source/core/svg/SVGPathSegLinetoVerticalAbs.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegLinetoVerticalAbs : public SVGPathSegLinetoVertical {
+class SVGPathSegLinetoVerticalAbs FINAL : public SVGPathSegLinetoVertical {
 public:
     static PassRefPtr<SVGPathSegLinetoVerticalAbs> create(SVGPathElement* element, SVGPathSegRole role, float y)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_LINETO_VERTICAL_ABS; }
-    virtual String pathSegTypeAsLetter() const { return "V"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_LINETO_VERTICAL_ABS; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "V"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegLinetoVerticalAbs.idl b/Source/core/svg/SVGPathSegLinetoVerticalAbs.idl
index db7dc1c..22a09e3 100644
--- a/Source/core/svg/SVGPathSegLinetoVerticalAbs.idl
+++ b/Source/core/svg/SVGPathSegLinetoVerticalAbs.idl
@@ -24,7 +24,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegLinetoVerticalAbs : SVGPathSeg {
-    [StrictTypeChecking] attribute float y;
+[
+    StrictTypeChecking,
+] interface SVGPathSegLinetoVerticalAbs : SVGPathSeg {
+    attribute float y;
 };
-
diff --git a/Source/core/svg/SVGPathSegLinetoVerticalRel.h b/Source/core/svg/SVGPathSegLinetoVerticalRel.h
index f420315..7867580 100644
--- a/Source/core/svg/SVGPathSegLinetoVerticalRel.h
+++ b/Source/core/svg/SVGPathSegLinetoVerticalRel.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegLinetoVerticalRel : public SVGPathSegLinetoVertical {
+class SVGPathSegLinetoVerticalRel FINAL : public SVGPathSegLinetoVertical {
 public:
     static PassRefPtr<SVGPathSegLinetoVerticalRel> create(SVGPathElement* element, SVGPathSegRole role, float y)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_LINETO_VERTICAL_REL; }
-    virtual String pathSegTypeAsLetter() const { return "v"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_LINETO_VERTICAL_REL; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "v"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegLinetoVerticalRel.idl b/Source/core/svg/SVGPathSegLinetoVerticalRel.idl
index 24cf7ff..0ceaf8e 100644
--- a/Source/core/svg/SVGPathSegLinetoVerticalRel.idl
+++ b/Source/core/svg/SVGPathSegLinetoVerticalRel.idl
@@ -24,7 +24,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegLinetoVerticalRel : SVGPathSeg {
-    [StrictTypeChecking] attribute float y;
+[
+    StrictTypeChecking,
+] interface SVGPathSegLinetoVerticalRel : SVGPathSeg {
+    attribute float y;
 };
-
diff --git a/Source/core/svg/SVGPathSegList.idl b/Source/core/svg/SVGPathSegList.idl
index 33f734e..5214f9d 100644
--- a/Source/core/svg/SVGPathSegList.idl
+++ b/Source/core/svg/SVGPathSegList.idl
@@ -24,15 +24,16 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegList {
+[
+    StrictTypeChecking,
+] interface SVGPathSegList {
     readonly attribute unsigned long numberOfItems;
 
     [RaisesException] void clear();
-    [StrictTypeChecking, RaisesException] SVGPathSeg initialize(SVGPathSeg newItem);
-    [StrictTypeChecking, RaisesException] SVGPathSeg getItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGPathSeg insertItemBefore(SVGPathSeg newItem, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGPathSeg replaceItem(SVGPathSeg newItem, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGPathSeg removeItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGPathSeg appendItem(SVGPathSeg newItem);
+    [RaisesException] SVGPathSeg initialize(SVGPathSeg newItem);
+    [RaisesException] SVGPathSeg getItem(unsigned long index);
+    [RaisesException] SVGPathSeg insertItemBefore(SVGPathSeg newItem, unsigned long index);
+    [RaisesException] SVGPathSeg replaceItem(SVGPathSeg newItem, unsigned long index);
+    [RaisesException] SVGPathSeg removeItem(unsigned long index);
+    [RaisesException] SVGPathSeg appendItem(SVGPathSeg newItem);
 };
-
diff --git a/Source/core/svg/SVGPathSegListBuilder.h b/Source/core/svg/SVGPathSegListBuilder.h
index 7b5c3aa..8b209c6 100644
--- a/Source/core/svg/SVGPathSegListBuilder.h
+++ b/Source/core/svg/SVGPathSegListBuilder.h
@@ -32,7 +32,7 @@
 
 class SVGPathElement;
 
-class SVGPathSegListBuilder : public SVGPathConsumer {
+class SVGPathSegListBuilder FINAL : public SVGPathConsumer {
 public:
     SVGPathSegListBuilder();
 
@@ -41,9 +41,9 @@
     void setCurrentSVGPathSegRole(SVGPathSegRole pathSegRole) { m_pathSegRole = pathSegRole; }
 
 private:
-    virtual void incrementPathSegmentCount() { }
-    virtual bool continueConsuming() { return true; }
-    virtual void cleanup()
+    virtual void incrementPathSegmentCount() OVERRIDE { }
+    virtual bool continueConsuming() OVERRIDE { return true; }
+    virtual void cleanup() OVERRIDE
     {
         m_pathElement = 0;
         m_pathSegList = 0;
@@ -51,18 +51,18 @@
     }
 
     // Used in UnalteredParsing/NormalizedParsing modes.
-    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode);
-    virtual void lineTo(const FloatPoint&, PathCoordinateMode);
-    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void closePath();
+    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode) OVERRIDE;
+    virtual void lineTo(const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void closePath() OVERRIDE;
 
     // Only used in UnalteredParsing mode.
-    virtual void lineToHorizontal(float, PathCoordinateMode);
-    virtual void lineToVertical(float, PathCoordinateMode);
-    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode);
-    virtual void arcTo(float, float, float, bool largeArcFlag, bool sweepFlag, const FloatPoint&, PathCoordinateMode);
+    virtual void lineToHorizontal(float, PathCoordinateMode) OVERRIDE;
+    virtual void lineToVertical(float, PathCoordinateMode) OVERRIDE;
+    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void arcTo(float, float, float, bool largeArcFlag, bool sweepFlag, const FloatPoint&, PathCoordinateMode) OVERRIDE;
 
     SVGPathElement* m_pathElement;
     SVGPathSegList* m_pathSegList;
diff --git a/Source/core/svg/SVGPathSegListSource.h b/Source/core/svg/SVGPathSegListSource.h
index 9ff02c4..edcd67f 100644
--- a/Source/core/svg/SVGPathSegListSource.h
+++ b/Source/core/svg/SVGPathSegListSource.h
@@ -29,7 +29,7 @@
 
 namespace WebCore {
 
-class SVGPathSegListSource : public SVGPathSource {
+class SVGPathSegListSource FINAL : public SVGPathSource {
 public:
     static PassOwnPtr<SVGPathSegListSource> create(const SVGPathSegList& pathSegList)
     {
@@ -39,20 +39,20 @@
 private:
     SVGPathSegListSource(const SVGPathSegList&);
 
-    virtual bool hasMoreData() const;
-    virtual bool moveToNextToken() { return true; }
-    virtual bool parseSVGSegmentType(SVGPathSegType&);
-    virtual SVGPathSegType nextCommand(SVGPathSegType);
+    virtual bool hasMoreData() const OVERRIDE;
+    virtual bool moveToNextToken() OVERRIDE { return true; }
+    virtual bool parseSVGSegmentType(SVGPathSegType&) OVERRIDE;
+    virtual SVGPathSegType nextCommand(SVGPathSegType) OVERRIDE;
 
-    virtual bool parseMoveToSegment(FloatPoint&);
-    virtual bool parseLineToSegment(FloatPoint&);
-    virtual bool parseLineToHorizontalSegment(float&);
-    virtual bool parseLineToVerticalSegment(float&);
-    virtual bool parseCurveToCubicSegment(FloatPoint&, FloatPoint&, FloatPoint&);
-    virtual bool parseCurveToCubicSmoothSegment(FloatPoint&, FloatPoint&);
-    virtual bool parseCurveToQuadraticSegment(FloatPoint&, FloatPoint&);
-    virtual bool parseCurveToQuadraticSmoothSegment(FloatPoint&);
-    virtual bool parseArcToSegment(float&, float&, float&, bool&, bool&, FloatPoint&);
+    virtual bool parseMoveToSegment(FloatPoint&) OVERRIDE;
+    virtual bool parseLineToSegment(FloatPoint&) OVERRIDE;
+    virtual bool parseLineToHorizontalSegment(float&) OVERRIDE;
+    virtual bool parseLineToVerticalSegment(float&) OVERRIDE;
+    virtual bool parseCurveToCubicSegment(FloatPoint&, FloatPoint&, FloatPoint&) OVERRIDE;
+    virtual bool parseCurveToCubicSmoothSegment(FloatPoint&, FloatPoint&) OVERRIDE;
+    virtual bool parseCurveToQuadraticSegment(FloatPoint&, FloatPoint&) OVERRIDE;
+    virtual bool parseCurveToQuadraticSmoothSegment(FloatPoint&) OVERRIDE;
+    virtual bool parseArcToSegment(float&, float&, float&, bool&, bool&, FloatPoint&) OVERRIDE;
 
     const SVGPathSegList& m_pathSegList;
     RefPtr<SVGPathSeg> m_segment;
diff --git a/Source/core/svg/SVGPathSegMovetoAbs.h b/Source/core/svg/SVGPathSegMovetoAbs.h
index 4b6527e..5e2b0f8 100644
--- a/Source/core/svg/SVGPathSegMovetoAbs.h
+++ b/Source/core/svg/SVGPathSegMovetoAbs.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegMovetoAbs : public SVGPathSegSingleCoordinate {
+class SVGPathSegMovetoAbs FINAL : public SVGPathSegSingleCoordinate {
 public:
     static PassRefPtr<SVGPathSegMovetoAbs> create(SVGPathElement* element, SVGPathSegRole role, float x, float y)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_MOVETO_ABS; }
-    virtual String pathSegTypeAsLetter() const { return "M"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_MOVETO_ABS; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "M"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegMovetoAbs.idl b/Source/core/svg/SVGPathSegMovetoAbs.idl
index 220401e..d92e467 100644
--- a/Source/core/svg/SVGPathSegMovetoAbs.idl
+++ b/Source/core/svg/SVGPathSegMovetoAbs.idl
@@ -24,8 +24,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegMovetoAbs : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
+[
+    StrictTypeChecking,
+] interface SVGPathSegMovetoAbs : SVGPathSeg {
+    attribute float x;
+    attribute float y;
 };
-
diff --git a/Source/core/svg/SVGPathSegMovetoRel.h b/Source/core/svg/SVGPathSegMovetoRel.h
index 023c3e9..0d4b5d8 100644
--- a/Source/core/svg/SVGPathSegMovetoRel.h
+++ b/Source/core/svg/SVGPathSegMovetoRel.h
@@ -26,7 +26,7 @@
 
 namespace WebCore {
 
-class SVGPathSegMovetoRel : public SVGPathSegSingleCoordinate {
+class SVGPathSegMovetoRel FINAL : public SVGPathSegSingleCoordinate {
 public:
     static PassRefPtr<SVGPathSegMovetoRel> create(SVGPathElement* element, SVGPathSegRole role, float x, float y)
     {
@@ -40,8 +40,8 @@
         ScriptWrappable::init(this);
     }
 
-    virtual unsigned short pathSegType() const { return PATHSEG_MOVETO_REL; }
-    virtual String pathSegTypeAsLetter() const { return "m"; }
+    virtual unsigned short pathSegType() const OVERRIDE { return PATHSEG_MOVETO_REL; }
+    virtual String pathSegTypeAsLetter() const OVERRIDE { return "m"; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGPathSegMovetoRel.idl b/Source/core/svg/SVGPathSegMovetoRel.idl
index 5868685..30909c2 100644
--- a/Source/core/svg/SVGPathSegMovetoRel.idl
+++ b/Source/core/svg/SVGPathSegMovetoRel.idl
@@ -24,8 +24,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPathSegMovetoRel : SVGPathSeg {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
+[
+    StrictTypeChecking,
+] interface SVGPathSegMovetoRel : SVGPathSeg {
+    attribute float x;
+    attribute float y;
 };
-
diff --git a/Source/core/svg/SVGPathStringBuilder.h b/Source/core/svg/SVGPathStringBuilder.h
index 6893894..ec1709b 100644
--- a/Source/core/svg/SVGPathStringBuilder.h
+++ b/Source/core/svg/SVGPathStringBuilder.h
@@ -26,28 +26,28 @@
 
 namespace WebCore {
 
-class SVGPathStringBuilder : public SVGPathConsumer {
+class SVGPathStringBuilder FINAL : public SVGPathConsumer {
 public:
     String result();
 
 private:
-    virtual void cleanup() { m_stringBuilder.clear(); }
-    virtual void incrementPathSegmentCount() { }
-    virtual bool continueConsuming() { return true; }
+    virtual void cleanup() OVERRIDE { m_stringBuilder.clear(); }
+    virtual void incrementPathSegmentCount() OVERRIDE { }
+    virtual bool continueConsuming() OVERRIDE { return true; }
 
     // Used in UnalteredParsing/NormalizedParsing modes.
-    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode);
-    virtual void lineTo(const FloatPoint&, PathCoordinateMode);
-    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void closePath();
+    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode) OVERRIDE;
+    virtual void lineTo(const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void closePath() OVERRIDE;
 
     // Only used in UnalteredParsing mode.
-    virtual void lineToHorizontal(float, PathCoordinateMode);
-    virtual void lineToVertical(float, PathCoordinateMode);
-    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode);
-    virtual void arcTo(float, float, float, bool largeArcFlag, bool sweepFlag, const FloatPoint&, PathCoordinateMode);
+    virtual void lineToHorizontal(float, PathCoordinateMode) OVERRIDE;
+    virtual void lineToVertical(float, PathCoordinateMode) OVERRIDE;
+    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void arcTo(float, float, float, bool largeArcFlag, bool sweepFlag, const FloatPoint&, PathCoordinateMode) OVERRIDE;
 
     StringBuilder m_stringBuilder;
 };
diff --git a/Source/core/svg/SVGPathStringSource.h b/Source/core/svg/SVGPathStringSource.h
index a423ad8..bc85f4f 100644
--- a/Source/core/svg/SVGPathStringSource.h
+++ b/Source/core/svg/SVGPathStringSource.h
@@ -27,7 +27,7 @@
 
 namespace WebCore {
 
-class SVGPathStringSource : public SVGPathSource {
+class SVGPathStringSource FINAL : public SVGPathSource {
 public:
     static PassOwnPtr<SVGPathStringSource> create(const String& string)
     {
@@ -37,20 +37,20 @@
 private:
     SVGPathStringSource(const String&);
 
-    virtual bool hasMoreData() const;
-    virtual bool moveToNextToken();
-    virtual bool parseSVGSegmentType(SVGPathSegType&);
-    virtual SVGPathSegType nextCommand(SVGPathSegType previousCommand);
+    virtual bool hasMoreData() const OVERRIDE;
+    virtual bool moveToNextToken() OVERRIDE;
+    virtual bool parseSVGSegmentType(SVGPathSegType&) OVERRIDE;
+    virtual SVGPathSegType nextCommand(SVGPathSegType previousCommand) OVERRIDE;
 
-    virtual bool parseMoveToSegment(FloatPoint&);
-    virtual bool parseLineToSegment(FloatPoint&);
-    virtual bool parseLineToHorizontalSegment(float&);
-    virtual bool parseLineToVerticalSegment(float&);
-    virtual bool parseCurveToCubicSegment(FloatPoint&, FloatPoint&, FloatPoint&);
-    virtual bool parseCurveToCubicSmoothSegment(FloatPoint&, FloatPoint&);
-    virtual bool parseCurveToQuadraticSegment(FloatPoint&, FloatPoint&);
-    virtual bool parseCurveToQuadraticSmoothSegment(FloatPoint&);
-    virtual bool parseArcToSegment(float&, float&, float&, bool&, bool&, FloatPoint&);
+    virtual bool parseMoveToSegment(FloatPoint&) OVERRIDE;
+    virtual bool parseLineToSegment(FloatPoint&) OVERRIDE;
+    virtual bool parseLineToHorizontalSegment(float&) OVERRIDE;
+    virtual bool parseLineToVerticalSegment(float&) OVERRIDE;
+    virtual bool parseCurveToCubicSegment(FloatPoint&, FloatPoint&, FloatPoint&) OVERRIDE;
+    virtual bool parseCurveToCubicSmoothSegment(FloatPoint&, FloatPoint&) OVERRIDE;
+    virtual bool parseCurveToQuadraticSegment(FloatPoint&, FloatPoint&) OVERRIDE;
+    virtual bool parseCurveToQuadraticSmoothSegment(FloatPoint&) OVERRIDE;
+    virtual bool parseArcToSegment(float&, float&, float&, bool&, bool&, FloatPoint&) OVERRIDE;
 
     String m_string;
     bool m_is8BitSource;
diff --git a/Source/core/svg/SVGPathTraversalStateBuilder.cpp b/Source/core/svg/SVGPathTraversalStateBuilder.cpp
index 1fe2b5c..7798ede 100644
--- a/Source/core/svg/SVGPathTraversalStateBuilder.cpp
+++ b/Source/core/svg/SVGPathTraversalStateBuilder.cpp
@@ -87,7 +87,7 @@
     return m_traversalState->m_totalLength;
 }
 
-SVGPoint SVGPathTraversalStateBuilder::currentPoint()
+FloatPoint SVGPathTraversalStateBuilder::currentPoint()
 {
     ASSERT(m_traversalState);
     return m_traversalState->m_current;
diff --git a/Source/core/svg/SVGPathTraversalStateBuilder.h b/Source/core/svg/SVGPathTraversalStateBuilder.h
index 59c2434..22d7a13 100644
--- a/Source/core/svg/SVGPathTraversalStateBuilder.h
+++ b/Source/core/svg/SVGPathTraversalStateBuilder.h
@@ -28,35 +28,35 @@
 
 class PathTraversalState;
 
-class SVGPathTraversalStateBuilder : public SVGPathConsumer {
+class SVGPathTraversalStateBuilder FINAL : public SVGPathConsumer {
 public:
     SVGPathTraversalStateBuilder();
 
     unsigned pathSegmentIndex();
     float totalLength();
-    SVGPoint currentPoint();
+    FloatPoint currentPoint();
 
     void setCurrentTraversalState(PathTraversalState* traversalState) { m_traversalState = traversalState; }
     void setDesiredLength(float);
-    virtual void incrementPathSegmentCount();
-    virtual bool continueConsuming();
-    virtual void cleanup() { m_traversalState = 0; }
+    virtual void incrementPathSegmentCount() OVERRIDE;
+    virtual bool continueConsuming() OVERRIDE;
+    virtual void cleanup() OVERRIDE { m_traversalState = 0; }
 
 private:
     // Used in UnalteredParsing/NormalizedParsing modes.
-    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode);
-    virtual void lineTo(const FloatPoint&, PathCoordinateMode);
-    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode);
-    virtual void closePath();
+    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode) OVERRIDE;
+    virtual void lineTo(const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE;
+    virtual void closePath() OVERRIDE;
 
 private:
     // Not used for PathTraversalState.
-    virtual void lineToHorizontal(float, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void lineToVertical(float, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
-    virtual void arcTo(float, float, float, bool, bool, const FloatPoint&, PathCoordinateMode) { ASSERT_NOT_REACHED(); }
+    virtual void lineToHorizontal(float, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void lineToVertical(float, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
+    virtual void arcTo(float, float, float, bool, bool, const FloatPoint&, PathCoordinateMode) OVERRIDE { ASSERT_NOT_REACHED(); }
 
     PathTraversalState* m_traversalState;
 };
diff --git a/Source/core/svg/SVGPathUtilities.cpp b/Source/core/svg/SVGPathUtilities.cpp
index dcbeb40..9106d89 100644
--- a/Source/core/svg/SVGPathUtilities.cpp
+++ b/Source/core/svg/SVGPathUtilities.cpp
@@ -228,12 +228,18 @@
     if (d.isEmpty())
         return false;
 
+    // The string length is typically a minor overestimate of eventual byte stream size, so it avoids us a lot of reallocs.
+    result->reserveInitialCapacity(d.length());
+
     SVGPathByteStreamBuilder* builder = globalSVGPathByteStreamBuilder(result);
 
     OwnPtr<SVGPathStringSource> source = SVGPathStringSource::create(d);
     SVGPathParser* parser = globalSVGPathParser(source.get(), builder);
     bool ok = parser->parsePathDataFromSource(parsingMode);
     parser->cleanup();
+
+    result->shrinkToFit();
+
     return ok;
 }
 
@@ -312,7 +318,7 @@
     return ok;
 }
 
-bool getPointAtLengthOfSVGPathByteStream(SVGPathByteStream* stream, float length, SVGPoint& point)
+bool getPointAtLengthOfSVGPathByteStream(SVGPathByteStream* stream, float length, FloatPoint& point)
 {
     ASSERT(stream);
     if (stream->isEmpty())
diff --git a/Source/core/svg/SVGPathUtilities.h b/Source/core/svg/SVGPathUtilities.h
index 7c06c57..007a72e 100644
--- a/Source/core/svg/SVGPathUtilities.h
+++ b/Source/core/svg/SVGPathUtilities.h
@@ -21,7 +21,7 @@
 #define SVGPathUtilities_h
 
 #include "core/svg/SVGPathConsumer.h"
-#include "core/svg/SVGPoint.h"
+#include "platform/geometry/FloatPoint.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/text/WTFString.h"
 
@@ -54,7 +54,7 @@
 
 bool getSVGPathSegAtLengthFromSVGPathByteStream(SVGPathByteStream*, float length, unsigned& pathSeg);
 bool getTotalLengthOfSVGPathByteStream(SVGPathByteStream*, float& totalLength);
-bool getPointAtLengthOfSVGPathByteStream(SVGPathByteStream*, float length, SVGPoint&);
+bool getPointAtLengthOfSVGPathByteStream(SVGPathByteStream*, float length, FloatPoint&);
 
 } // namespace WebCore
 
diff --git a/Source/core/svg/SVGPatternElement.cpp b/Source/core/svg/SVGPatternElement.cpp
index 44e6745..661e234 100644
--- a/Source/core/svg/SVGPatternElement.cpp
+++ b/Source/core/svg/SVGPatternElement.cpp
@@ -24,6 +24,7 @@
 #include "core/svg/SVGPatternElement.h"
 
 #include "XLinkNames.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/rendering/svg/RenderSVGResourcePattern.h"
 #include "core/svg/PatternAttributes.h"
 #include "core/svg/SVGElementInstance.h"
@@ -32,44 +33,35 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGPatternElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGPatternElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH(SVGPatternElement, SVGNames::widthAttr, Width, width)
-DEFINE_ANIMATED_LENGTH(SVGPatternElement, SVGNames::heightAttr, Height, height)
 DEFINE_ANIMATED_ENUMERATION(SVGPatternElement, SVGNames::patternUnitsAttr, PatternUnits, patternUnits, SVGUnitTypes::SVGUnitType)
 DEFINE_ANIMATED_ENUMERATION(SVGPatternElement, SVGNames::patternContentUnitsAttr, PatternContentUnits, patternContentUnits, SVGUnitTypes::SVGUnitType)
 DEFINE_ANIMATED_TRANSFORM_LIST(SVGPatternElement, SVGNames::patternTransformAttr, PatternTransform, patternTransform)
-DEFINE_ANIMATED_STRING(SVGPatternElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGPatternElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-DEFINE_ANIMATED_RECT(SVGPatternElement, SVGNames::viewBoxAttr, ViewBox, viewBox)
-DEFINE_ANIMATED_PRESERVEASPECTRATIO(SVGPatternElement, SVGNames::preserveAspectRatioAttr, PreserveAspectRatio, preserveAspectRatio)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGPatternElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(width)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(height)
     REGISTER_LOCAL_ANIMATED_PROPERTY(patternUnits)
     REGISTER_LOCAL_ANIMATED_PROPERTY(patternContentUnits)
     REGISTER_LOCAL_ANIMATED_PROPERTY(patternTransform)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(viewBox)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAspectRatio)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGPatternElement::SVGPatternElement(Document& document)
     : SVGElement(SVGNames::patternTag, document)
-    , m_x(LengthModeWidth)
-    , m_y(LengthModeHeight)
-    , m_width(LengthModeWidth)
-    , m_height(LengthModeHeight)
+    , SVGURIReference(this)
+    , SVGTests(this)
+    , SVGFitToViewBox(this)
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
+    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth)))
+    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight)))
     , m_patternUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
     , m_patternContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_width);
+    addToPropertyMap(m_height);
     registerAnimatedPropertiesForSVGPatternElement();
 }
 
@@ -84,7 +76,6 @@
     if (supportedAttributes.isEmpty()) {
         SVGURIReference::addSupportedAttributes(supportedAttributes);
         SVGTests::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         SVGFitToViewBox::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::patternUnitsAttr);
         supportedAttributes.add(SVGNames::patternContentUnitsAttr);
@@ -101,9 +92,9 @@
 {
     SVGParsingError parseError = NoError;
 
-    if (!isSupportedAttribute(name))
+    if (!isSupportedAttribute(name)) {
         SVGElement::parseAttribute(name, value);
-    else if (name == SVGNames::patternUnitsAttr) {
+    } else if (name == SVGNames::patternUnitsAttr) {
         SVGUnitTypes::SVGUnitType propertyValue = SVGPropertyTraits<SVGUnitTypes::SVGUnitType>::fromString(value);
         if (propertyValue > 0)
             setPatternUnitsBaseValue(propertyValue);
@@ -119,20 +110,20 @@
         detachAnimatedPatternTransformListWrappers(newList.size());
         setPatternTransformBaseValue(newList);
         return;
-    } else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
-    else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (name == SVGNames::widthAttr)
-        setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
-    else if (name == SVGNames::heightAttr)
-        setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGURIReference::parseAttribute(name, value)
-             || SVGTests::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)
-             || SVGFitToViewBox::parseAttribute(this, name, value)) {
-    } else
+    } else if (name == SVGNames::xAttr) {
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::yAttr) {
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::widthAttr) {
+        m_width->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (name == SVGNames::heightAttr) {
+        m_height->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else if (SVGTests::parseAttribute(name, value)) {
+    } else if (SVGFitToViewBox::parseAttribute(name, value, document(), parseError)) {
+    } else {
         ASSERT_NOT_REACHED();
+    }
 
     reportAttributeParsingError(parseError, name, value);
 }
@@ -173,60 +164,65 @@
     return new RenderSVGResourcePattern(this);
 }
 
+static void setPatternAttributes(const SVGPatternElement* element, PatternAttributes& attributes)
+{
+    if (!attributes.hasX() && element->x()->isSpecified())
+        attributes.setX(element->x()->currentValue());
+
+    if (!attributes.hasY() && element->y()->isSpecified())
+        attributes.setY(element->y()->currentValue());
+
+    if (!attributes.hasWidth() && element->width()->isSpecified())
+        attributes.setWidth(element->width()->currentValue());
+
+    if (!attributes.hasHeight() && element->height()->isSpecified())
+        attributes.setHeight(element->height()->currentValue());
+
+    if (!attributes.hasViewBox() && element->viewBox()->isSpecified() && element->viewBox()->currentValue()->isValid())
+        attributes.setViewBox(element->viewBox()->currentValue()->value());
+
+    if (!attributes.hasPreserveAspectRatio() && element->preserveAspectRatio()->isSpecified())
+        attributes.setPreserveAspectRatio(element->preserveAspectRatio()->currentValue());
+
+    if (!attributes.hasPatternUnits() && element->patternUnitsSpecified())
+        attributes.setPatternUnits(element->patternUnitsCurrentValue());
+
+    if (!attributes.hasPatternContentUnits() && element->patternContentUnitsSpecified())
+        attributes.setPatternContentUnits(element->patternContentUnitsCurrentValue());
+
+    if (!attributes.hasPatternTransform() && element->patternTransformSpecified()) {
+        AffineTransform transform;
+        element->patternTransformCurrentValue().concatenate(transform);
+        attributes.setPatternTransform(transform);
+    }
+
+    if (!attributes.hasPatternContentElement() && ElementTraversal::firstWithin(*element))
+        attributes.setPatternContentElement(element);
+}
+
 void SVGPatternElement::collectPatternAttributes(PatternAttributes& attributes) const
 {
     HashSet<const SVGPatternElement*> processedPatterns;
-
     const SVGPatternElement* current = this;
-    while (current) {
-        if (!attributes.hasX() && current->hasAttribute(SVGNames::xAttr))
-            attributes.setX(current->xCurrentValue());
 
-        if (!attributes.hasY() && current->hasAttribute(SVGNames::yAttr))
-            attributes.setY(current->yCurrentValue());
-
-        if (!attributes.hasWidth() && current->hasAttribute(SVGNames::widthAttr))
-            attributes.setWidth(current->widthCurrentValue());
-
-        if (!attributes.hasHeight() && current->hasAttribute(SVGNames::heightAttr))
-            attributes.setHeight(current->heightCurrentValue());
-
-        if (!attributes.hasViewBox() && current->hasAttribute(SVGNames::viewBoxAttr) && current->viewBoxCurrentValue().isValid())
-            attributes.setViewBox(current->viewBoxCurrentValue());
-
-        if (!attributes.hasPreserveAspectRatio() && current->hasAttribute(SVGNames::preserveAspectRatioAttr))
-            attributes.setPreserveAspectRatio(current->preserveAspectRatioCurrentValue());
-
-        if (!attributes.hasPatternUnits() && current->hasAttribute(SVGNames::patternUnitsAttr))
-            attributes.setPatternUnits(current->patternUnitsCurrentValue());
-
-        if (!attributes.hasPatternContentUnits() && current->hasAttribute(SVGNames::patternContentUnitsAttr))
-            attributes.setPatternContentUnits(current->patternContentUnitsCurrentValue());
-
-        if (!attributes.hasPatternTransform() && current->hasAttribute(SVGNames::patternTransformAttr)) {
-            AffineTransform transform;
-            current->patternTransformCurrentValue().concatenate(transform);
-            attributes.setPatternTransform(transform);
-        }
-
-        if (!attributes.hasPatternContentElement() && current->childElementCount())
-            attributes.setPatternContentElement(current);
-
+    while (true) {
+        setPatternAttributes(current, attributes);
         processedPatterns.add(current);
 
         // Respect xlink:href, take attributes from referenced element
-        Node* refNode = SVGURIReference::targetElementFromIRIString(current->hrefCurrentValue(), document());
+        Node* refNode = SVGURIReference::targetElementFromIRIString(current->hrefString(), document());
         if (refNode && refNode->hasTagName(SVGNames::patternTag)) {
-            current = static_cast<const SVGPatternElement*>(const_cast<const Node*>(refNode));
+            current = toSVGPatternElement(const_cast<const Node*>(refNode));
 
             // Cycle detection
-            if (processedPatterns.contains(current)) {
-                current = 0;
-                break;
-            }
-        } else
-            current = 0;
+            if (processedPatterns.contains(current))
+                return;
+        } else {
+            return;
+        }
     }
+
+    ASSERT_NOT_REACHED();
 }
 
 AffineTransform SVGPatternElement::localCoordinateSpaceTransform(SVGElement::CTMScope) const
@@ -238,10 +234,10 @@
 
 bool SVGPatternElement::selfHasRelativeLengths() const
 {
-    return xCurrentValue().isRelative()
-        || yCurrentValue().isRelative()
-        || widthCurrentValue().isRelative()
-        || heightCurrentValue().isRelative();
+    return m_x->currentValue()->isRelative()
+        || m_y->currentValue()->isRelative()
+        || m_width->currentValue()->isRelative()
+        || m_height->currentValue()->isRelative();
 }
 
 }
diff --git a/Source/core/svg/SVGPatternElement.h b/Source/core/svg/SVGPatternElement.h
index 3536b4b..44cf6f9 100644
--- a/Source/core/svg/SVGPatternElement.h
+++ b/Source/core/svg/SVGPatternElement.h
@@ -25,11 +25,8 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
-#include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGAnimatedTransformList.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFitToViewBox.h"
 #include "core/svg/SVGTests.h"
 #include "core/svg/SVGURIReference.h"
@@ -42,48 +39,43 @@
 class SVGPatternElement FINAL : public SVGElement,
                                 public SVGURIReference,
                                 public SVGTests,
-                                public SVGExternalResourcesRequired,
                                 public SVGFitToViewBox {
 public:
     static PassRefPtr<SVGPatternElement> create(Document&);
 
     void collectPatternAttributes(PatternAttributes&) const;
 
-    virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const;
+    virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const OVERRIDE;
+
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
+    SVGAnimatedLength* width() const { return m_width.get(); }
+    SVGAnimatedLength* height() const { return m_height.get(); }
 
 private:
     explicit SVGPatternElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
-    virtual bool needsPendingResourceHandling() const { return false; }
+    virtual bool isValid() const OVERRIDE { return SVGTests::isValid(); }
+    virtual bool needsPendingResourceHandling() const OVERRIDE { return false; }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
+    RefPtr<SVGAnimatedLength> m_width;
+    RefPtr<SVGAnimatedLength> m_height;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGPatternElement)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_LENGTH(Width, width)
-        DECLARE_ANIMATED_LENGTH(Height, height)
         DECLARE_ANIMATED_ENUMERATION(PatternUnits, patternUnits, SVGUnitTypes::SVGUnitType)
         DECLARE_ANIMATED_ENUMERATION(PatternContentUnits, patternContentUnits, SVGUnitTypes::SVGUnitType)
         DECLARE_ANIMATED_TRANSFORM_LIST(PatternTransform, patternTransform)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
-        DECLARE_ANIMATED_RECT(ViewBox, viewBox)
-        DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGPatternElement, hasTagName(SVGNames::patternTag));
diff --git a/Source/core/svg/SVGPatternElement.idl b/Source/core/svg/SVGPatternElement.idl
index 55aa2e9..d91bb95 100644
--- a/Source/core/svg/SVGPatternElement.idl
+++ b/Source/core/svg/SVGPatternElement.idl
@@ -33,7 +33,6 @@
     readonly attribute SVGAnimatedLength        height;
 };
 
-SVGPatternElement implements SVGExternalResourcesRequired;
 SVGPatternElement implements SVGFitToViewBox;
 SVGPatternElement implements SVGTests;
 SVGPatternElement implements SVGURIReference;
diff --git a/Source/core/svg/SVGPoint.cpp b/Source/core/svg/SVGPoint.cpp
new file mode 100644
index 0000000..86068f3
--- /dev/null
+++ b/Source/core/svg/SVGPoint.cpp
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+
+#include "core/svg/SVGPoint.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/svg/SVGAnimationElement.h"
+#include "core/svg/SVGParserUtilities.h"
+#include "platform/transforms/AffineTransform.h"
+#include "wtf/text/StringBuilder.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+SVGPoint::SVGPoint()
+    : NewSVGPropertyBase(classType())
+{
+}
+
+SVGPoint::SVGPoint(const FloatPoint& point)
+    : NewSVGPropertyBase(classType())
+    , m_value(point)
+{
+}
+
+PassRefPtr<SVGPoint> SVGPoint::clone() const
+{
+    return SVGPoint::create(m_value);
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGPoint::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGPoint> point = SVGPoint::create();
+    point->setValueAsString(value, IGNORE_EXCEPTION);
+    return point.release();
+}
+
+template<typename CharType>
+void SVGPoint::parse(const CharType*& ptr, const CharType* end, ExceptionState& exceptionState)
+{
+    const CharType* start = ptr;
+
+    skipOptionalSVGSpaces(ptr, end);
+
+    float x = 0.0f;
+    float y = 0.0f;
+    bool valid = parseNumber(ptr, end, x) && parseNumber(ptr, end, y, false);
+
+    if (!valid) {
+        exceptionState.throwDOMException(SyntaxError, "Problem parsing point \"" + String(start, end - start) + "\"");
+        return;
+    }
+
+    skipOptionalSVGSpaces(ptr, end);
+    if (ptr < end) { // nothing should come after the last, fourth number
+        exceptionState.throwDOMException(SyntaxError, "Problem parsing point \"" + String(start, end - start) + "\"");
+        return;
+    }
+
+    m_value = FloatPoint(x, y);
+}
+
+FloatPoint SVGPoint::matrixTransform(const AffineTransform& transform) const
+{
+    double newX, newY;
+    transform.map(static_cast<double>(x()), static_cast<double>(y()), newX, newY);
+    return FloatPoint::narrowPrecision(newX, newY);
+}
+
+void SVGPoint::setValueAsString(const String& string, ExceptionState& exceptionState)
+{
+    if (string.isEmpty()) {
+        m_value = FloatPoint(0.0f, 0.0f);
+        return;
+    }
+
+    if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        parse(ptr, end, exceptionState);
+        return;
+    }
+
+    const UChar* ptr = string.characters16();
+    const UChar* end = ptr + string.length();
+    parse(ptr, end, exceptionState);
+}
+
+String SVGPoint::valueAsString() const
+{
+    StringBuilder builder;
+    builder.append(String::number(x()));
+    builder.append(' ');
+    builder.append(String::number(y()));
+    return builder.toString();
+}
+
+void SVGPoint::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    // SVGPoint is not animated by itself
+    ASSERT_NOT_REACHED();
+}
+
+void SVGPoint::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*)
+{
+    // SVGPoint is not animated by itself
+    ASSERT_NOT_REACHED();
+}
+
+float SVGPoint::calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement)
+{
+    // SVGPoint is not animated by itself
+    ASSERT_NOT_REACHED();
+    return 0.0f;
+}
+
+}
diff --git a/Source/core/svg/SVGPoint.h b/Source/core/svg/SVGPoint.h
index c258a0f..ba48226 100644
--- a/Source/core/svg/SVGPoint.h
+++ b/Source/core/svg/SVGPoint.h
@@ -1,36 +1,99 @@
 /*
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ * Copyright (C) 2014 Google Inc. 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.
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``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 APPLE INC. OR ITS 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.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGPoint_h
 #define SVGPoint_h
 
-#include "platform/geometry/FloatRect.h"
+#include "core/svg/properties/NewSVGProperty.h"
+#include "platform/geometry/FloatPoint.h"
 
 namespace WebCore {
 
-typedef FloatPoint SVGPoint;
+class AffineTransform;
+class SVGPointTearOff;
+
+class SVGPoint : public NewSVGPropertyBase {
+public:
+    typedef SVGPointTearOff TearOffType;
+
+    static PassRefPtr<SVGPoint> create()
+    {
+        return adoptRef(new SVGPoint());
+    }
+
+    static PassRefPtr<SVGPoint> create(const FloatPoint& point)
+    {
+        return adoptRef(new SVGPoint(point));
+    }
+
+    PassRefPtr<SVGPoint> clone() const;
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+
+    const FloatPoint& value() const { return m_value; }
+    void setValue(const FloatPoint& value) { m_value = value; }
+
+    float x() const { return m_value.x(); }
+    float y() const { return m_value.y(); }
+    void setX(float f) { m_value.setX(f); }
+    void setY(float f) { m_value.setY(f); }
+
+    FloatPoint matrixTransform(const AffineTransform&) const;
+
+    bool operator==(const SVGPoint&) const;
+    bool operator!=(const SVGPoint& other) const { return !operator==(other); }
+
+    virtual String valueAsString() const OVERRIDE;
+    void setValueAsString(const String&, ExceptionState&);
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedPoint; }
+
+private:
+    SVGPoint();
+    explicit SVGPoint(const FloatPoint&);
+
+    template<typename CharType>
+    void parse(const CharType*& ptr, const CharType* end, ExceptionState&);
+
+    FloatPoint m_value;
+};
+
+inline PassRefPtr<SVGPoint> toSVGPoint(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGPoint::classType());
+    return static_pointer_cast<SVGPoint>(base.release());
+}
 
 } // namespace WebCore
 
diff --git a/Source/core/svg/SVGPoint.idl b/Source/core/svg/SVGPoint.idl
index d8945c9..a222243 100644
--- a/Source/core/svg/SVGPoint.idl
+++ b/Source/core/svg/SVGPoint.idl
@@ -20,10 +20,13 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface SVGPoint {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
+[
+    ImplementedAs=SVGPointTearOff,
+    SetWrapperReferenceTo(SVGElement contextElement),
+    StrictTypeChecking,
+] interface SVGPoint {
+    [RaisesException=Setter] attribute float x;
+    [RaisesException=Setter] attribute float y;
 
-    [MeasureAs=SVGPointMatrixTransform, StrictTypeChecking] SVGPoint matrixTransform(SVGMatrix matrix);
+    [MeasureAs=SVGPointMatrixTransform] SVGPoint matrixTransform(SVGMatrix matrix);
 };
-
diff --git a/Source/core/svg/SVGPointList.cpp b/Source/core/svg/SVGPointList.cpp
index 3b7d9b9..e0910d6 100644
--- a/Source/core/svg/SVGPointList.cpp
+++ b/Source/core/svg/SVGPointList.cpp
@@ -21,26 +21,197 @@
 #include "config.h"
 #include "core/svg/SVGPointList.h"
 
+#include "core/svg/SVGAnimationElement.h"
+#include "core/svg/SVGParserUtilities.h"
 #include "platform/geometry/FloatPoint.h"
 #include "wtf/text/StringBuilder.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
+inline PassRefPtr<SVGPointList> toSVGPointList(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGPointList::classType());
+    return static_pointer_cast<SVGPointList>(base.release());
+}
+
+SVGPointList::SVGPointList()
+{
+}
+
+SVGPointList::~SVGPointList()
+{
+}
+
+PassRefPtr<SVGPointList> SVGPointList::clone()
+{
+    RefPtr<SVGPointList> svgPointList = SVGPointList::create();
+    svgPointList->deepCopy(this);
+    return svgPointList.release();
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGPointList::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGPointList> svgPointList = SVGPointList::create();
+    svgPointList->setValueAsString(value, IGNORE_EXCEPTION);
+    return svgPointList.release();
+}
+
 String SVGPointList::valueAsString() const
 {
     StringBuilder builder;
 
-    unsigned size = this->size();
-    for (unsigned i = 0; i < size; ++i) {
-        if (i > 0)
-            builder.append(' '); // FIXME: Shouldn't we use commas to seperate?
+    ConstIterator it = begin();
+    ConstIterator itEnd = end();
+    if (it != itEnd) {
+        builder.append(it->valueAsString());
+        ++it;
 
-        const FloatPoint& point = at(i);
-        builder.append(String::number(point.x()) + ' ' + String::number(point.y()));
+        for (; it != itEnd; ++it) {
+            builder.append(' ');
+            builder.append(it->valueAsString());
+        }
     }
 
     return builder.toString();
 }
 
+template <typename CharType>
+bool SVGPointList::parse(const CharType*& ptr, const CharType* end)
+{
+    clear();
+
+    skipOptionalSVGSpaces(ptr, end);
+    if (ptr >= end)
+        return true;
+
+    for (;;) {
+        float x = 0.0f;
+        float y = 0.0f;
+        bool valid = parseNumber(ptr, end, x) && parseNumber(ptr, end, y, false);
+        if (!valid) {
+            return false;
+        }
+        append(SVGPoint::create(FloatPoint(x, y)));
+
+        skipOptionalSVGSpaces(ptr, end);
+        if (ptr < end && *ptr == ',') {
+            ++ptr;
+            skipOptionalSVGSpaces(ptr, end);
+
+            // ',' requires the list to be continued
+            continue;
+        }
+
+        // check end of list
+        skipOptionalSVGSpaces(ptr, end);
+        if (ptr >= end)
+            return true;
+    }
+}
+
+void SVGPointList::setValueAsString(const String& value, ExceptionState& exceptionState)
+{
+    if (value.isEmpty()) {
+        clear();
+        return;
+    }
+
+    bool valid = false;
+    if (value.is8Bit()) {
+        const LChar* ptr = value.characters8();
+        const LChar* end = ptr + value.length();
+        valid = parse(ptr, end);
+    } else {
+        const UChar* ptr = value.characters16();
+        const UChar* end = ptr + value.length();
+        valid = parse(ptr, end);
+    }
+
+    if (!valid)
+        exceptionState.throwDOMException(SyntaxError, "Problem parsing points=\""+value+"\"");
+}
+
+void SVGPointList::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement* contextElement)
+{
+    RefPtr<SVGPointList> otherList = toSVGPointList(other);
+
+    if (numberOfItems() != otherList->numberOfItems())
+        return;
+
+    for (size_t i = 0; i < numberOfItems(); ++i)
+        at(i)->setValue(at(i)->value() + otherList->at(i)->value());
+}
+
+bool SVGPointList::adjustFromToListValues(PassRefPtr<SVGPointList> passFromList, PassRefPtr<SVGPointList> passToList, float percentage, bool isToAnimation, bool resizeAnimatedListIfNeeded)
+{
+    RefPtr<SVGPointList> fromList = passFromList;
+    RefPtr<SVGPointList> toList = passToList;
+
+    // If no 'to' value is given, nothing to animate.
+    size_t toListSize = toList->numberOfItems();
+    if (!toListSize)
+        return false;
+
+    // If the 'from' value is given and it's length doesn't match the 'to' value list length, fallback to a discrete animation.
+    size_t fromListSize = fromList->numberOfItems();
+    if (fromListSize != toListSize && fromListSize) {
+        if (percentage < 0.5) {
+            if (!isToAnimation)
+                deepCopy(fromList);
+        } else {
+            deepCopy(toList);
+        }
+
+        return false;
+    }
+
+    ASSERT(!fromListSize || fromListSize == toListSize);
+    if (resizeAnimatedListIfNeeded && numberOfItems() < toListSize) {
+        size_t paddingCount = toListSize - numberOfItems();
+        for (size_t i = 0; i < paddingCount; ++i)
+            append(SVGPoint::create());
+    }
+
+    return true;
+}
+
+void SVGPointList::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement)
+{
+    RefPtr<SVGPointList> fromList = toSVGPointList(fromValue);
+    RefPtr<SVGPointList> toList = toSVGPointList(toValue);
+    RefPtr<SVGPointList> toAtEndOfDurationList = toSVGPointList(toAtEndOfDurationValue);
+
+    size_t fromPointListSize = fromList->numberOfItems();
+    size_t toPointListSize = toList->numberOfItems();
+    size_t toAtEndOfDurationListSize = toAtEndOfDurationList->numberOfItems();
+
+    if (!adjustFromToListValues(fromList, toList, percentage, animationElement->animationMode() == ToAnimation, true))
+        return;
+
+    for (size_t i = 0; i < toPointListSize; ++i) {
+        float animatedX = at(i)->x();
+        float animatedY = at(i)->y();
+
+        FloatPoint effectiveFrom;
+        if (fromPointListSize)
+            effectiveFrom = fromList->at(i)->value();
+        FloatPoint effectiveTo = toList->at(i)->value();
+        FloatPoint effectiveToAtEnd;
+        if (i < toAtEndOfDurationListSize)
+            effectiveToAtEnd = toAtEndOfDurationList->at(i)->value();
+
+        animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom.x(), effectiveTo.x(), effectiveToAtEnd.x(), animatedX);
+        animationElement->animateAdditiveNumber(percentage, repeatCount, effectiveFrom.y(), effectiveTo.y(), effectiveToAtEnd.y(), animatedY);
+        at(i)->setValue(FloatPoint(animatedX, animatedY));
+    }
+}
+
+float SVGPointList::calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*)
+{
+    // FIXME: Distance calculation is not possible for SVGPointList right now. We need the distance for every single value.
+    return -1;
+}
+
 }
diff --git a/Source/core/svg/SVGPointList.h b/Source/core/svg/SVGPointList.h
index a745b10..357f257 100644
--- a/Source/core/svg/SVGPointList.h
+++ b/Source/core/svg/SVGPointList.h
@@ -1,45 +1,78 @@
 /*
- * Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGPointList_h
 #define SVGPointList_h
 
+#include "bindings/v8/ScriptWrappable.h"
 #include "core/svg/SVGPoint.h"
-#include "core/svg/properties/SVGPropertyTraits.h"
-#include "wtf/Vector.h"
+#include "core/svg/properties/NewSVGListPropertyHelper.h"
 
 namespace WebCore {
 
-class SVGPointList : public Vector<SVGPoint> {
+class SVGPointListTearOff;
+
+class SVGPointList FINAL : public NewSVGListPropertyHelper<SVGPointList, SVGPoint> {
 public:
-    SVGPointList() { }
+    typedef SVGPointListTearOff TearOffType;
 
-    String valueAsString() const;
-};
+    static PassRefPtr<SVGPointList> create()
+    {
+        return adoptRef(new SVGPointList());
+    }
 
-template<>
-struct SVGPropertyTraits<SVGPointList> {
-    static SVGPointList initialValue() { return SVGPointList(); }
-    typedef SVGPoint ListItemType;
+    virtual ~SVGPointList();
+
+    PassRefPtr<SVGPointList> clone();
+
+    void setValueAsString(const String&, ExceptionState&);
+
+    // NewSVGPropertyBase:
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+    virtual String valueAsString() const OVERRIDE;
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedPoints; }
+
+private:
+    SVGPointList();
+
+    bool adjustFromToListValues(PassRefPtr<SVGPointList> fromList, PassRefPtr<SVGPointList> toList, float percentage, bool isToAnimation, bool resizeAnimatedListIfNeeded);
+
+    template <typename CharType>
+    bool parse(const CharType*& ptr, const CharType* end);
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGPointList_h
diff --git a/Source/core/svg/SVGPointList.idl b/Source/core/svg/SVGPointList.idl
index f65d302..51aba12 100644
--- a/Source/core/svg/SVGPointList.idl
+++ b/Source/core/svg/SVGPointList.idl
@@ -23,15 +23,18 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPointList {
+[
+    ImplementedAs=SVGPointListTearOff,
+    SetWrapperReferenceTo(SVGElement contextElement),
+    StrictTypeChecking,
+] interface SVGPointList {
     readonly attribute unsigned long numberOfItems;
 
     [RaisesException] void clear();
-    [StrictTypeChecking, RaisesException] SVGPoint initialize(SVGPoint item);
-    [StrictTypeChecking, RaisesException] SVGPoint getItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGPoint insertItemBefore(SVGPoint item, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGPoint replaceItem(SVGPoint item, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGPoint removeItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGPoint appendItem(SVGPoint item);
+    [RaisesException] SVGPoint initialize(SVGPoint item);
+    [RaisesException] SVGPoint getItem(unsigned long index);
+    [RaisesException] SVGPoint insertItemBefore(SVGPoint item, unsigned long index);
+    [RaisesException] SVGPoint replaceItem(SVGPoint item, unsigned long index);
+    [RaisesException] SVGPoint removeItem(unsigned long index);
+    [RaisesException] SVGPoint appendItem(SVGPoint item);
 };
-
diff --git a/Source/core/svg/SVGPointListTearOff.h b/Source/core/svg/SVGPointListTearOff.h
new file mode 100644
index 0000000..c7a6319
--- /dev/null
+++ b/Source/core/svg/SVGPointListTearOff.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGPointListTearOff_h
+#define SVGPointListTearOff_h
+
+#include "core/svg/SVGPointList.h"
+#include "core/svg/properties/NewSVGListPropertyTearOffHelper.h"
+
+namespace WebCore {
+
+class SVGPointListTearOff FINAL :
+    public NewSVGListPropertyTearOffHelper<SVGPointListTearOff, SVGPointList>,
+    public ScriptWrappable {
+public:
+    static PassRefPtr<SVGPointListTearOff> create(PassRefPtr<SVGPointList> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+    {
+        return adoptRef(new SVGPointListTearOff(target, contextElement, propertyIsAnimVal, attributeName));
+    }
+
+private:
+    SVGPointListTearOff(PassRefPtr<SVGPointList> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+        : NewSVGListPropertyTearOffHelper<SVGPointListTearOff, SVGPointList>(target, contextElement, propertyIsAnimVal, attributeName)
+    {
+        ScriptWrappable::init(this);
+    }
+};
+
+} // namespace WebCore
+
+#endif // SVGPointListTearOff_h_
diff --git a/Source/core/svg/SVGPointTearOff.cpp b/Source/core/svg/SVGPointTearOff.cpp
new file mode 100644
index 0000000..5081029
--- /dev/null
+++ b/Source/core/svg/SVGPointTearOff.cpp
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+
+#include "core/svg/SVGPointTearOff.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/svg/SVGMatrix.h"
+
+namespace WebCore {
+
+SVGPointTearOff::SVGPointTearOff(PassRefPtr<SVGPoint> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName)
+    : NewSVGPropertyTearOff<SVGPoint>(target, contextElement, propertyIsAnimVal, attributeName)
+{
+    ScriptWrappable::init(this);
+}
+
+void SVGPointTearOff::setX(float f, ExceptionState& exceptionState)
+{
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    target()->setX(f);
+    commitChange();
+}
+
+void SVGPointTearOff::setY(float f, ExceptionState& exceptionState)
+{
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    target()->setY(f);
+    commitChange();
+}
+
+PassRefPtr<SVGPointTearOff> SVGPointTearOff::matrixTransform(SVGMatrix matrix)
+{
+    FloatPoint point = target()->matrixTransform(matrix);
+    return SVGPointTearOff::create(SVGPoint::create(point), 0, PropertyIsNotAnimVal);
+}
+
+}
diff --git a/Source/core/html/ime/Composition.h b/Source/core/svg/SVGPointTearOff.h
similarity index 61%
copy from Source/core/html/ime/Composition.h
copy to Source/core/svg/SVGPointTearOff.h
index 4305466..88d0ad9 100644
--- a/Source/core/html/ime/Composition.h
+++ b/Source/core/svg/SVGPointTearOff.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,36 +28,35 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef Composition_h
-#define Composition_h
+#ifndef SVGPointTearOff_h
+#define SVGPointTearOff_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
+#include "core/svg/SVGPoint.h"
+#include "core/svg/properties/NewSVGPropertyTearOff.h"
 
 namespace WebCore {
 
-class InputMethodContext;
+class SVGMatrix;
 
-class Composition : public ScriptWrappable {
+class SVGPointTearOff : public NewSVGPropertyTearOff<SVGPoint>, public ScriptWrappable {
 public:
-    static PassOwnPtr<Composition> create(InputMethodContext*);
-    ~Composition();
+    static PassRefPtr<SVGPointTearOff> create(PassRefPtr<SVGPoint> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+    {
+        return adoptRef(new SVGPointTearOff(target, contextElement, propertyIsAnimVal, attributeName));
+    }
 
-    void ref();
-    void deref();
+    void setX(float, ExceptionState&);
+    void setY(float, ExceptionState&);
+    float x() { return target()->x(); }
+    float y() { return target()->y(); }
 
-    String text() const;
-    int selectionStart() const;
-    int selectionEnd() const;
-    const Vector<unsigned>& getSegments() const;
+    PassRefPtr<SVGPointTearOff> matrixTransform(SVGMatrix);
 
-private:
-    explicit Composition(InputMethodContext*);
-
-    InputMethodContext* m_inputMethodContext;
+protected:
+    SVGPointTearOff(PassRefPtr<SVGPoint>, SVGElement* contextElement, PropertyIsAnimValType, const QualifiedName& attributeName = nullQName());
 };
 
 } // namespace WebCore
 
-#endif // Composition_h
+#endif // SVGPointTearOff_h_
diff --git a/Source/core/svg/SVGPolyElement.cpp b/Source/core/svg/SVGPolyElement.cpp
index 217d1ae..eea18f4 100644
--- a/Source/core/svg/SVGPolyElement.cpp
+++ b/Source/core/svg/SVGPolyElement.cpp
@@ -30,44 +30,17 @@
 
 namespace WebCore {
 
-// Define custom animated property 'points'.
-const SVGPropertyInfo* SVGPolyElement::pointsPropertyInfo()
-{
-    static const SVGPropertyInfo* s_propertyInfo = 0;
-    if (!s_propertyInfo) {
-        s_propertyInfo = new SVGPropertyInfo(AnimatedPoints,
-                                             PropertyIsReadWrite,
-                                             SVGNames::pointsAttr,
-                                             SVGNames::pointsAttr.localName(),
-                                             &SVGPolyElement::synchronizePoints,
-                                             &SVGPolyElement::lookupOrCreatePointsWrapper);
-    }
-    return s_propertyInfo;
-}
-
-SVGPointList& SVGPolyElement::pointsCurrentValue()
-{
-    SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGPolyElement, SVGAnimatedPointList>(this, pointsPropertyInfo());
-    if (wrapper && wrapper->isAnimating()) {
-        if (SVGListPropertyTearOff<SVGPointList>* ap = animatedPoints())
-            return ap->values();
-    }
-
-    return m_points.value;
-}
-
 // Animated property definitions
-DEFINE_ANIMATED_BOOLEAN(SVGPolyElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGPolyElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(points)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGPolyElement::SVGPolyElement(const QualifiedName& tagName, Document& document)
     : SVGGeometryElement(tagName, document)
+    , m_points(SVGAnimatedPointList::create(this, SVGNames::pointsAttr, SVGPointList::create()))
 {
+    addToPropertyMap(m_points);
     registerAnimatedPropertiesForSVGPolyElement();
 }
 
@@ -75,8 +48,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGLangSpace::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::pointsAttr);
     }
     return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
@@ -90,22 +61,12 @@
     }
 
     if (name == SVGNames::pointsAttr) {
-        SVGPointList newList;
-        if (!pointsListFromSVGData(newList, value))
-            document().accessSVGExtensions()->reportError("Problem parsing points=\"" + value + "\"");
-
-        if (SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGPolyElement, SVGAnimatedPointList>(this, pointsPropertyInfo()))
-            static_cast<SVGAnimatedPointList*>(wrapper)->detachListWrappers(newList.size());
-
-        m_points.value = newList;
+        SVGParsingError parseError = NoError;
+        m_points->setBaseValueAsString(value, parseError);
+        reportAttributeParsingError(parseError, name, value);
         return;
     }
 
-    if (SVGLangSpace::parseAttribute(name, value))
-        return;
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
-
     ASSERT_NOT_REACHED();
 }
 
@@ -128,41 +89,7 @@
         return;
     }
 
-    if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
-        RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
-        return;
-    }
-
     ASSERT_NOT_REACHED();
 }
 
-void SVGPolyElement::synchronizePoints(SVGElement* contextElement)
-{
-    ASSERT(contextElement);
-    SVGPolyElement* ownerType = toSVGPolyElement(contextElement);
-    if (!ownerType->m_points.shouldSynchronize)
-        return;
-    ownerType->m_points.synchronize(ownerType, pointsPropertyInfo()->attributeName, ownerType->m_points.value.valueAsString());
-}
-
-PassRefPtr<SVGAnimatedProperty> SVGPolyElement::lookupOrCreatePointsWrapper(SVGElement* contextElement)
-{
-    ASSERT(contextElement);
-    SVGPolyElement* ownerType = toSVGPolyElement(contextElement);
-    return SVGAnimatedProperty::lookupOrCreateWrapper<SVGPolyElement, SVGAnimatedPointList, SVGPointList>
-           (ownerType, pointsPropertyInfo(), ownerType->m_points.value);
-}
-
-SVGListPropertyTearOff<SVGPointList>* SVGPolyElement::points()
-{
-    m_points.shouldSynchronize = true;
-    return static_cast<SVGListPropertyTearOff<SVGPointList>*>(static_pointer_cast<SVGAnimatedPointList>(lookupOrCreatePointsWrapper(this))->baseVal());
-}
-
-SVGListPropertyTearOff<SVGPointList>* SVGPolyElement::animatedPoints()
-{
-    m_points.shouldSynchronize = true;
-    return static_cast<SVGListPropertyTearOff<SVGPointList>*>(static_pointer_cast<SVGAnimatedPointList>(lookupOrCreatePointsWrapper(this))->animVal());
-}
-
 }
diff --git a/Source/core/svg/SVGPolyElement.h b/Source/core/svg/SVGPolyElement.h
index 4cc4601..28e6f03 100644
--- a/Source/core/svg/SVGPolyElement.h
+++ b/Source/core/svg/SVGPolyElement.h
@@ -23,44 +23,34 @@
 
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
+#include "core/svg/SVGAnimatedPointList.h"
 #include "core/svg/SVGGeometryElement.h"
-#include "core/svg/SVGPointList.h"
 
 namespace WebCore {
 
-class SVGPolyElement : public SVGGeometryElement
-                     , public SVGExternalResourcesRequired {
+class SVGPolyElement : public SVGGeometryElement {
 public:
-    SVGListPropertyTearOff<SVGPointList>* points();
-    SVGListPropertyTearOff<SVGPointList>* animatedPoints();
+    SVGAnimatedPointList* points() { return m_points.get(); }
 
-    SVGPointList& pointsCurrentValue();
-
-    static const SVGPropertyInfo* pointsPropertyInfo();
+    PassRefPtr<SVGPointListTearOff> pointsFromJavascript() { return m_points->baseVal(); }
+    PassRefPtr<SVGPointListTearOff> animatedPoints() { return m_points->animVal(); }
 
 protected:
     SVGPolyElement(const QualifiedName&, Document&);
 
 private:
-    virtual bool isValid() const { return SVGTests::isValid(); }
-    virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
+    virtual bool supportsFocus() const OVERRIDE FINAL { return hasFocusEventListeners(); }
 
     bool isSupportedAttribute(const QualifiedName&);
-    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE FINAL;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE FINAL;
 
-    virtual bool supportsMarkers() const { return true; }
-
-    // Custom 'points' property
-    static void synchronizePoints(SVGElement* contextElement);
-    static PassRefPtr<SVGAnimatedProperty> lookupOrCreatePointsWrapper(SVGElement* contextElement);
-
-    mutable SVGSynchronizableAnimatedProperty<SVGPointList> m_points;
+    virtual bool supportsMarkers() const OVERRIDE FINAL { return true; }
 
 private:
+    RefPtr<SVGAnimatedPointList> m_points;
+
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGPolyElement)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGPolygonElement.idl b/Source/core/svg/SVGPolygonElement.idl
index be639f1..defe168 100644
--- a/Source/core/svg/SVGPolygonElement.idl
+++ b/Source/core/svg/SVGPolygonElement.idl
@@ -24,8 +24,6 @@
  */
 
 interface SVGPolygonElement : SVGGeometryElement {
-    readonly attribute SVGPointList points;
+    [ImplementedAs=pointsFromJavascript] readonly attribute SVGPointList points;
     readonly attribute SVGPointList animatedPoints;
 };
-
-SVGPolygonElement implements SVGExternalResourcesRequired;
diff --git a/Source/core/svg/SVGPolylineElement.idl b/Source/core/svg/SVGPolylineElement.idl
index 1fd499b..4d148d1 100644
--- a/Source/core/svg/SVGPolylineElement.idl
+++ b/Source/core/svg/SVGPolylineElement.idl
@@ -24,9 +24,7 @@
  */
 
 interface SVGPolylineElement : SVGGeometryElement {
-    readonly attribute SVGPointList points;
+    [ImplementedAs=pointsFromJavascript] readonly attribute SVGPointList points;
     readonly attribute SVGPointList animatedPoints;
 };
 
-SVGPolylineElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGPreserveAspectRatio.cpp b/Source/core/svg/SVGPreserveAspectRatio.cpp
index 5e9de72..027f362 100644
--- a/Source/core/svg/SVGPreserveAspectRatio.cpp
+++ b/Source/core/svg/SVGPreserveAspectRatio.cpp
@@ -23,7 +23,9 @@
 #include "core/svg/SVGPreserveAspectRatio.h"
 
 #include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/svg/SVGAnimationElement.h"
 #include "core/svg/SVGParserUtilities.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/transforms/AffineTransform.h"
@@ -32,142 +34,165 @@
 namespace WebCore {
 
 SVGPreserveAspectRatio::SVGPreserveAspectRatio()
-    : m_align(SVG_PRESERVEASPECTRATIO_XMIDYMID)
-    , m_meetOrSlice(SVG_MEETORSLICE_MEET)
+    : NewSVGPropertyBase(classType())
 {
+    setDefault();
 }
 
-void SVGPreserveAspectRatio::setAlign(unsigned short align, ExceptionState& exceptionState)
+void SVGPreserveAspectRatio::setDefault()
 {
-    if (align == SVG_PRESERVEASPECTRATIO_UNKNOWN || align > SVG_PRESERVEASPECTRATIO_XMAXYMAX) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return;
-    }
-
-    m_align = static_cast<SVGPreserveAspectRatioType>(align);
+    m_align = SVG_PRESERVEASPECTRATIO_XMIDYMID;
+    m_meetOrSlice = SVG_MEETORSLICE_MEET;
 }
 
-void SVGPreserveAspectRatio::setMeetOrSlice(unsigned short meetOrSlice, ExceptionState& exceptionState)
+PassRefPtr<SVGPreserveAspectRatio> SVGPreserveAspectRatio::clone() const
 {
-    if (meetOrSlice == SVG_MEETORSLICE_UNKNOWN || meetOrSlice > SVG_MEETORSLICE_SLICE) {
-        exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
-        return;
-    }
+    RefPtr<SVGPreserveAspectRatio> preserveAspectRatio = create();
 
-    m_meetOrSlice = static_cast<SVGMeetOrSliceType>(meetOrSlice);
+    preserveAspectRatio->m_align = m_align;
+    preserveAspectRatio->m_meetOrSlice = m_meetOrSlice;
+
+    return preserveAspectRatio.release();
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGPreserveAspectRatio::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGPreserveAspectRatio> preserveAspectRatio = create();
+
+    preserveAspectRatio->setValueAsString(value, IGNORE_EXCEPTION);
+
+    return preserveAspectRatio.release();
 }
 
 template<typename CharType>
 bool SVGPreserveAspectRatio::parseInternal(const CharType*& ptr, const CharType* end, bool validate)
 {
-    // FIXME: Rewrite this parser, without gotos!
+    SVGPreserveAspectRatioType align = SVG_PRESERVEASPECTRATIO_XMIDYMID;
+    SVGMeetOrSliceType meetOrSlice = SVG_MEETORSLICE_MEET;
+
+    setAlign(align);
+    setMeetOrSlice(meetOrSlice);
+
     if (!skipOptionalSVGSpaces(ptr, end))
-        goto bailOut;
+        return false;
 
     if (*ptr == 'd') {
         if (!skipString(ptr, end, "defer"))
-            goto bailOut;
+            return false;
 
         // FIXME: We just ignore the "defer" here.
         if (ptr == end)
             return true;
 
         if (!skipOptionalSVGSpaces(ptr, end))
-            goto bailOut;
+            return false;
     }
 
     if (*ptr == 'n') {
         if (!skipString(ptr, end, "none"))
-            goto bailOut;
-        m_align = SVG_PRESERVEASPECTRATIO_NONE;
+            return false;
+        align = SVG_PRESERVEASPECTRATIO_NONE;
         skipOptionalSVGSpaces(ptr, end);
     } else if (*ptr == 'x') {
         if ((end - ptr) < 8)
-            goto bailOut;
+            return false;
         if (ptr[1] != 'M' || ptr[4] != 'Y' || ptr[5] != 'M')
-            goto bailOut;
+            return false;
         if (ptr[2] == 'i') {
             if (ptr[3] == 'n') {
                 if (ptr[6] == 'i') {
                     if (ptr[7] == 'n')
-                        m_align = SVG_PRESERVEASPECTRATIO_XMINYMIN;
+                        align = SVG_PRESERVEASPECTRATIO_XMINYMIN;
                     else if (ptr[7] == 'd')
-                        m_align = SVG_PRESERVEASPECTRATIO_XMINYMID;
+                        align = SVG_PRESERVEASPECTRATIO_XMINYMID;
                     else
-                        goto bailOut;
-                } else if (ptr[6] == 'a' && ptr[7] == 'x')
-                     m_align = SVG_PRESERVEASPECTRATIO_XMINYMAX;
-                else
-                     goto bailOut;
+                        return false;
+                } else if (ptr[6] == 'a' && ptr[7] == 'x') {
+                    align = SVG_PRESERVEASPECTRATIO_XMINYMAX;
+                } else {
+                    return false;
+                }
             } else if (ptr[3] == 'd') {
                 if (ptr[6] == 'i') {
                     if (ptr[7] == 'n')
-                        m_align = SVG_PRESERVEASPECTRATIO_XMIDYMIN;
+                        align = SVG_PRESERVEASPECTRATIO_XMIDYMIN;
                     else if (ptr[7] == 'd')
-                        m_align = SVG_PRESERVEASPECTRATIO_XMIDYMID;
+                        align = SVG_PRESERVEASPECTRATIO_XMIDYMID;
                     else
-                        goto bailOut;
-                } else if (ptr[6] == 'a' && ptr[7] == 'x')
-                    m_align = SVG_PRESERVEASPECTRATIO_XMIDYMAX;
-                else
-                    goto bailOut;
-            } else
-                goto bailOut;
+                        return false;
+                } else if (ptr[6] == 'a' && ptr[7] == 'x') {
+                    align = SVG_PRESERVEASPECTRATIO_XMIDYMAX;
+                } else {
+                    return false;
+                }
+            } else {
+                return false;
+            }
         } else if (ptr[2] == 'a' && ptr[3] == 'x') {
             if (ptr[6] == 'i') {
                 if (ptr[7] == 'n')
-                    m_align = SVG_PRESERVEASPECTRATIO_XMAXYMIN;
+                    align = SVG_PRESERVEASPECTRATIO_XMAXYMIN;
                 else if (ptr[7] == 'd')
-                    m_align = SVG_PRESERVEASPECTRATIO_XMAXYMID;
+                    align = SVG_PRESERVEASPECTRATIO_XMAXYMID;
                 else
-                    goto bailOut;
-            } else if (ptr[6] == 'a' && ptr[7] == 'x')
-                m_align = SVG_PRESERVEASPECTRATIO_XMAXYMAX;
-            else
-                goto bailOut;
-        } else
-            goto bailOut;
+                    return false;
+            } else if (ptr[6] == 'a' && ptr[7] == 'x') {
+                align = SVG_PRESERVEASPECTRATIO_XMAXYMAX;
+            } else {
+                return false;
+            }
+        } else {
+            return false;
+        }
         ptr += 8;
         skipOptionalSVGSpaces(ptr, end);
-    } else
-        goto bailOut;
+    } else {
+        return false;
+    }
 
     if (ptr < end) {
         if (*ptr == 'm') {
             if (!skipString(ptr, end, "meet"))
-                goto bailOut;
+                return false;
             skipOptionalSVGSpaces(ptr, end);
         } else if (*ptr == 's') {
             if (!skipString(ptr, end, "slice"))
-                goto bailOut;
+                return false;
             skipOptionalSVGSpaces(ptr, end);
-            if (m_align != SVG_PRESERVEASPECTRATIO_NONE)
-                m_meetOrSlice = SVG_MEETORSLICE_SLICE;
+            if (align != SVG_PRESERVEASPECTRATIO_NONE)
+                meetOrSlice = SVG_MEETORSLICE_SLICE;
         }
     }
 
-    if (end != ptr && validate) {
-bailOut:
-        m_align = SVG_PRESERVEASPECTRATIO_XMIDYMID;
-        m_meetOrSlice = SVG_MEETORSLICE_MEET;
+    if (end != ptr && validate)
         return false;
-    }
+
+    setAlign(align);
+    setMeetOrSlice(meetOrSlice);
+
     return true;
 }
 
-void SVGPreserveAspectRatio::parse(const String& string)
+void SVGPreserveAspectRatio::setValueAsString(const String& string, ExceptionState& exceptionState)
 {
-    if (string.isEmpty()) {
-        const LChar* ptr = 0;
-        parseInternal(ptr, ptr, true);
-    } else if (string.is8Bit()) {
+    setDefault();
+
+    if (string.isEmpty())
+        return;
+
+    bool valid = false;
+    if (string.is8Bit()) {
         const LChar* ptr = string.characters8();
         const LChar* end = ptr + string.length();
-        parseInternal(ptr, end, true);
+        valid = parseInternal(ptr, end, true);
     } else {
         const UChar* ptr = string.characters16();
         const UChar* end = ptr + string.length();
-        parseInternal(ptr, end, true);
+        valid = parseInternal(ptr, end, true);
+    }
+
+    if (!valid) {
+        exceptionState.throwDOMException(SyntaxError, "The value provided ('" + string + "') is invalid.");
     }
 }
 
@@ -372,4 +397,28 @@
     }
 }
 
+void SVGPreserveAspectRatio::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    ASSERT_NOT_REACHED();
+}
+
+void SVGPreserveAspectRatio::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase>, SVGElement*)
+{
+    ASSERT(animationElement);
+
+    bool useToValue;
+    animationElement->animateDiscreteType(percentage, false, true, useToValue);
+
+    RefPtr<SVGPreserveAspectRatio> preserveAspectRatioToUse = useToValue ? toSVGPreserveAspectRatio(toValue) : toSVGPreserveAspectRatio(fromValue);
+
+    m_align = preserveAspectRatioToUse->m_align;
+    m_meetOrSlice = preserveAspectRatioToUse->m_meetOrSlice;
+}
+
+float SVGPreserveAspectRatio::calculateDistance(PassRefPtr<NewSVGPropertyBase> toValue, SVGElement* contextElement)
+{
+    // No paced animations for SVGPreserveAspectRatio.
+    return -1;
+}
+
 }
diff --git a/Source/core/svg/SVGPreserveAspectRatio.h b/Source/core/svg/SVGPreserveAspectRatio.h
index aae01cd..3336635 100644
--- a/Source/core/svg/SVGPreserveAspectRatio.h
+++ b/Source/core/svg/SVGPreserveAspectRatio.h
@@ -21,16 +21,15 @@
 #ifndef SVGPreserveAspectRatio_h
 #define SVGPreserveAspectRatio_h
 
-#include "core/svg/properties/SVGPropertyTraits.h"
+#include "core/svg/properties/NewSVGProperty.h"
 
 namespace WebCore {
 
 class AffineTransform;
-class ExceptionState;
 class FloatRect;
+class SVGPreserveAspectRatioTearOff;
 
-class SVGPreserveAspectRatio {
-    WTF_MAKE_FAST_ALLOCATED;
+class SVGPreserveAspectRatio : public NewSVGPropertyBase {
 public:
     enum SVGPreserveAspectRatioType {
         SVG_PRESERVEASPECTRATIO_UNKNOWN = 0,
@@ -52,13 +51,24 @@
         SVG_MEETORSLICE_SLICE = 2
     };
 
-    SVGPreserveAspectRatio();
+    typedef SVGPreserveAspectRatioTearOff TearOffType;
 
-    void setAlign(unsigned short align, ExceptionState&);
-    unsigned short align() const { return m_align; }
+    static PassRefPtr<SVGPreserveAspectRatio> create()
+    {
+        return adoptRef(new SVGPreserveAspectRatio());
+    }
 
-    void setMeetOrSlice(unsigned short, ExceptionState&);
-    unsigned short meetOrSlice() const { return m_meetOrSlice; }
+    virtual PassRefPtr<SVGPreserveAspectRatio> clone() const;
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+
+    bool operator==(const SVGPreserveAspectRatio&) const;
+    bool operator!=(const SVGPreserveAspectRatio& other) const { return !operator==(other); }
+
+    void setAlign(SVGPreserveAspectRatioType align) { m_align = align; }
+    SVGPreserveAspectRatioType align() const { return m_align; }
+
+    void setMeetOrSlice(SVGMeetOrSliceType meetOrSlice) { m_meetOrSlice = meetOrSlice; }
+    SVGMeetOrSliceType meetOrSlice() const { return m_meetOrSlice; }
 
     void transformRect(FloatRect& destRect, FloatRect& srcRect);
 
@@ -66,13 +76,21 @@
                            float logicWidth, float logicHeight,
                            float physWidth, float physHeight) const;
 
-    void parse(const String&);
-    bool parse(const LChar*& ptr, const LChar* end, bool validate);
+    virtual String valueAsString() const OVERRIDE;
+    virtual void setValueAsString(const String&, ExceptionState&);
     bool parse(const UChar*& ptr, const UChar* end, bool validate);
+    bool parse(const LChar*& ptr, const LChar* end, bool validate);
 
-    String valueAsString() const;
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedPreserveAspectRatio; }
 
 private:
+    SVGPreserveAspectRatio();
+
+    void setDefault();
     template<typename CharType>
     bool parseInternal(const CharType*& ptr, const CharType* end, bool validate);
 
@@ -80,11 +98,12 @@
     SVGMeetOrSliceType m_meetOrSlice;
 };
 
-template<>
-struct SVGPropertyTraits<SVGPreserveAspectRatio> {
-    static SVGPreserveAspectRatio initialValue() { return SVGPreserveAspectRatio(); }
-    static String toString(const SVGPreserveAspectRatio& type) { return type.valueAsString(); }
-};
+inline PassRefPtr<SVGPreserveAspectRatio> toSVGPreserveAspectRatio(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGPreserveAspectRatio::classType());
+    return static_pointer_cast<SVGPreserveAspectRatio>(base.release());
+}
 
 } // namespace WebCore
 
diff --git a/Source/core/svg/SVGPreserveAspectRatio.idl b/Source/core/svg/SVGPreserveAspectRatio.idl
index 477369e..1591630 100644
--- a/Source/core/svg/SVGPreserveAspectRatio.idl
+++ b/Source/core/svg/SVGPreserveAspectRatio.idl
@@ -23,8 +23,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGPreserveAspectRatio {
-    // Alignment Types
+[
+    StrictTypeChecking,
+    ImplementedAs=SVGPreserveAspectRatioTearOff,
+    SetWrapperReferenceTo(SVGElement contextElement)
+] interface SVGPreserveAspectRatio {
+    // Alignment types
     const unsigned short SVG_PRESERVEASPECTRATIO_UNKNOWN = 0;
     const unsigned short SVG_PRESERVEASPECTRATIO_NONE = 1;
     const unsigned short SVG_PRESERVEASPECTRATIO_XMINYMIN = 2;
@@ -37,13 +41,12 @@
     const unsigned short SVG_PRESERVEASPECTRATIO_XMIDYMAX = 9;
     const unsigned short SVG_PRESERVEASPECTRATIO_XMAXYMAX = 10;
 
-    // Meet-or-slice Types
+    // Meet-or-slice types
     const unsigned short SVG_MEETORSLICE_UNKNOWN = 0;
     const unsigned short SVG_MEETORSLICE_MEET = 1;
     const unsigned short SVG_MEETORSLICE_SLICE = 2;
 
-    [StrictTypeChecking, RaisesException=Setter] attribute unsigned short align;
+    [RaisesException=Setter] attribute unsigned short align;
 
-    [StrictTypeChecking, RaisesException=Setter] attribute unsigned short meetOrSlice;
+    [RaisesException=Setter] attribute unsigned short meetOrSlice;
 };
-
diff --git a/Source/core/svg/SVGPreserveAspectRatioTearOff.cpp b/Source/core/svg/SVGPreserveAspectRatioTearOff.cpp
new file mode 100644
index 0000000..5cab619
--- /dev/null
+++ b/Source/core/svg/SVGPreserveAspectRatioTearOff.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+
+#include "core/svg/SVGPreserveAspectRatioTearOff.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+
+namespace WebCore {
+
+void SVGPreserveAspectRatioTearOff::setAlign(unsigned short align, ExceptionState& exceptionState)
+{
+    if (align == SVG_PRESERVEASPECTRATIO_UNKNOWN || align > SVG_PRESERVEASPECTRATIO_XMAXYMAX) {
+        exceptionState.throwDOMException(NotSupportedError, "The alignment provided is invalid.");
+        return;
+    }
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    target()->setAlign(static_cast<SVGPreserveAspectRatio::SVGPreserveAspectRatioType>(align));
+}
+
+void SVGPreserveAspectRatioTearOff::setMeetOrSlice(unsigned short meetOrSlice, ExceptionState& exceptionState)
+{
+    if (meetOrSlice == SVG_MEETORSLICE_UNKNOWN || meetOrSlice > SVG_MEETORSLICE_SLICE) {
+        exceptionState.throwDOMException(NotSupportedError, "The meetOrSlice provided is invalid.");
+        return;
+    }
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    target()->setMeetOrSlice(static_cast<SVGPreserveAspectRatio::SVGMeetOrSliceType>(meetOrSlice));
+}
+
+SVGPreserveAspectRatioTearOff::SVGPreserveAspectRatioTearOff(PassRefPtr<SVGPreserveAspectRatio> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName)
+    : NewSVGPropertyTearOff<SVGPreserveAspectRatio>(target, contextElement, propertyIsAnimVal, attributeName)
+{
+    ScriptWrappable::init(this);
+}
+
+}
diff --git a/Source/core/svg/SVGPreserveAspectRatioTearOff.h b/Source/core/svg/SVGPreserveAspectRatioTearOff.h
new file mode 100644
index 0000000..ab8247c
--- /dev/null
+++ b/Source/core/svg/SVGPreserveAspectRatioTearOff.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGPreserveAspectRatioTearOff_h
+#define SVGPreserveAspectRatioTearOff_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/svg/SVGPreserveAspectRatio.h"
+#include "core/svg/properties/NewSVGPropertyTearOff.h"
+
+namespace WebCore {
+
+class SVGPreserveAspectRatioTearOff FINAL : public NewSVGPropertyTearOff<SVGPreserveAspectRatio>, public ScriptWrappable {
+public:
+    enum {
+        SVG_PRESERVEASPECTRATIO_UNKNOWN = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_UNKNOWN,
+        SVG_PRESERVEASPECTRATIO_NONE = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE,
+        SVG_PRESERVEASPECTRATIO_XMINYMIN = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMINYMIN,
+        SVG_PRESERVEASPECTRATIO_XMIDYMIN = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMIN,
+        SVG_PRESERVEASPECTRATIO_XMAXYMIN = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMIN,
+        SVG_PRESERVEASPECTRATIO_XMINYMID = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMINYMID,
+        SVG_PRESERVEASPECTRATIO_XMIDYMID = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMID,
+        SVG_PRESERVEASPECTRATIO_XMAXYMID = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMID,
+        SVG_PRESERVEASPECTRATIO_XMINYMAX = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMINYMAX,
+        SVG_PRESERVEASPECTRATIO_XMIDYMAX = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMAX,
+        SVG_PRESERVEASPECTRATIO_XMAXYMAX = SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMAX
+    };
+
+    enum {
+        SVG_MEETORSLICE_UNKNOWN = SVGPreserveAspectRatio::SVG_MEETORSLICE_UNKNOWN,
+        SVG_MEETORSLICE_MEET = SVGPreserveAspectRatio::SVG_MEETORSLICE_MEET,
+        SVG_MEETORSLICE_SLICE = SVGPreserveAspectRatio::SVG_MEETORSLICE_SLICE
+    };
+
+    static PassRefPtr<SVGPreserveAspectRatioTearOff> create(PassRefPtr<SVGPreserveAspectRatio> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+    {
+        return adoptRef(new SVGPreserveAspectRatioTearOff(target, contextElement, propertyIsAnimVal, attributeName));
+    }
+
+    void setAlign(unsigned short, ExceptionState&);
+    unsigned short align() { return target()->align(); }
+    void setMeetOrSlice(unsigned short, ExceptionState&);
+    unsigned short meetOrSlice() { return target()->meetOrSlice(); }
+
+private:
+    SVGPreserveAspectRatioTearOff(PassRefPtr<SVGPreserveAspectRatio>, SVGElement* contextElement, PropertyIsAnimValType, const QualifiedName& attributeName = nullQName());
+};
+
+} // namespace WebCore
+
+#endif // SVGPreserveAspectRatioTearOff_h_
diff --git a/Source/core/svg/SVGRadialGradientElement.cpp b/Source/core/svg/SVGRadialGradientElement.cpp
index af45582..a65b00b 100644
--- a/Source/core/svg/SVGRadialGradientElement.cpp
+++ b/Source/core/svg/SVGRadialGradientElement.cpp
@@ -33,34 +33,36 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGRadialGradientElement, SVGNames::cxAttr, Cx, cx)
-DEFINE_ANIMATED_LENGTH(SVGRadialGradientElement, SVGNames::cyAttr, Cy, cy)
-DEFINE_ANIMATED_LENGTH(SVGRadialGradientElement, SVGNames::rAttr, R, r)
-DEFINE_ANIMATED_LENGTH(SVGRadialGradientElement, SVGNames::fxAttr, Fx, fx)
-DEFINE_ANIMATED_LENGTH(SVGRadialGradientElement, SVGNames::fyAttr, Fy, fy)
-DEFINE_ANIMATED_LENGTH(SVGRadialGradientElement, SVGNames::frAttr, Fr, fr)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGRadialGradientElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(cx)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(cy)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(r)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(fx)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(fy)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(fr)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGradientElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGRadialGradientElement::SVGRadialGradientElement(Document& document)
     : SVGGradientElement(SVGNames::radialGradientTag, document)
-    , m_cx(LengthModeWidth, "50%")
-    , m_cy(LengthModeHeight, "50%")
-    , m_r(LengthModeOther, "50%")
-    , m_fx(LengthModeWidth)
-    , m_fy(LengthModeHeight)
-    , m_fr(LengthModeOther, "0%")
+    , m_cx(SVGAnimatedLength::create(this, SVGNames::cxAttr, SVGLength::create(LengthModeWidth)))
+    , m_cy(SVGAnimatedLength::create(this, SVGNames::cyAttr, SVGLength::create(LengthModeHeight)))
+    , m_r(SVGAnimatedLength::create(this, SVGNames::rAttr, SVGLength::create(LengthModeOther)))
+    , m_fx(SVGAnimatedLength::create(this, SVGNames::fxAttr, SVGLength::create(LengthModeWidth)))
+    , m_fy(SVGAnimatedLength::create(this, SVGNames::fyAttr, SVGLength::create(LengthModeHeight)))
+    , m_fr(SVGAnimatedLength::create(this, SVGNames::frAttr, SVGLength::create(LengthModeOther)))
 {
-    // Spec: If the cx/cy/r/fr attribute is not specified, the effect is as if a value of "50%" were specified.
     ScriptWrappable::init(this);
+
+    // Spec: If the cx/cy/r attribute is not specified, the effect is as if a value of "50%" were specified.
+    m_cx->setDefaultValueAsString("50%");
+    m_cy->setDefaultValueAsString("50%");
+    m_r->setDefaultValueAsString("50%");
+
+    // SVG2-Draft Spec: If the fr attributed is not specified, the effect is as if a value of "0%" were specified.
+    m_fr->setDefaultValueAsString("0%");
+
+    addToPropertyMap(m_cx);
+    addToPropertyMap(m_cy);
+    addToPropertyMap(m_r);
+    addToPropertyMap(m_fx);
+    addToPropertyMap(m_fy);
+    addToPropertyMap(m_fr);
     registerAnimatedPropertiesForSVGRadialGradientElement();
 }
 
@@ -90,17 +92,17 @@
     if (!isSupportedAttribute(name))
         SVGGradientElement::parseAttribute(name, value);
     else if (name == SVGNames::cxAttr)
-        setCxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_cx->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::cyAttr)
-        setCyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_cy->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::rAttr)
-        setRBaseValue(SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths));
+        m_r->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::fxAttr)
-        setFxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_fx->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::fyAttr)
-        setFyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_fy->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::frAttr)
-        setFrBaseValue(SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths));
+        m_fr->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else
         ASSERT_NOT_REACHED();
 
@@ -128,73 +130,78 @@
     return new RenderSVGResourceRadialGradient(this);
 }
 
+static void setGradientAttributes(SVGGradientElement* element, RadialGradientAttributes& attributes, bool isRadial = true)
+{
+    if (!attributes.hasSpreadMethod() && element->spreadMethodSpecified())
+        attributes.setSpreadMethod(element->spreadMethodCurrentValue());
+
+    if (!attributes.hasGradientUnits() && element->gradientUnitsSpecified())
+        attributes.setGradientUnits(element->gradientUnitsCurrentValue());
+
+    if (!attributes.hasGradientTransform() && element->gradientTransformSpecified()) {
+        AffineTransform transform;
+        element->gradientTransformCurrentValue().concatenate(transform);
+        attributes.setGradientTransform(transform);
+    }
+
+    if (!attributes.hasStops()) {
+        const Vector<Gradient::ColorStop>& stops(element->buildStops());
+        if (!stops.isEmpty())
+            attributes.setStops(stops);
+    }
+
+    if (isRadial) {
+        SVGRadialGradientElement* radial = toSVGRadialGradientElement(element);
+
+        if (!attributes.hasCx() && radial->cx()->isSpecified())
+            attributes.setCx(radial->cx()->currentValue());
+
+        if (!attributes.hasCy() && radial->cy()->isSpecified())
+            attributes.setCy(radial->cy()->currentValue());
+
+        if (!attributes.hasR() && radial->r()->isSpecified())
+            attributes.setR(radial->r()->currentValue());
+
+        if (!attributes.hasFx() && radial->fx()->isSpecified())
+            attributes.setFx(radial->fx()->currentValue());
+
+        if (!attributes.hasFy() && radial->fy()->isSpecified())
+            attributes.setFy(radial->fy()->currentValue());
+
+        if (!attributes.hasFr() && radial->fr()->isSpecified())
+            attributes.setFr(radial->fr()->currentValue());
+    }
+}
+
 bool SVGRadialGradientElement::collectGradientAttributes(RadialGradientAttributes& attributes)
 {
-    HashSet<SVGGradientElement*> processedGradients;
+    if (!renderer())
+        return false;
 
-    bool isRadial = true;
+    HashSet<SVGGradientElement*> processedGradients;
     SVGGradientElement* current = this;
 
-    while (current) {
-        if (!current->renderer())
-            return false;
+    setGradientAttributes(current, attributes);
+    processedGradients.add(current);
 
-        if (!attributes.hasSpreadMethod() && current->hasAttribute(SVGNames::spreadMethodAttr))
-            attributes.setSpreadMethod(current->spreadMethodCurrentValue());
-
-        if (!attributes.hasGradientUnits() && current->hasAttribute(SVGNames::gradientUnitsAttr))
-            attributes.setGradientUnits(current->gradientUnitsCurrentValue());
-
-        if (!attributes.hasGradientTransform() && current->hasAttribute(SVGNames::gradientTransformAttr)) {
-            AffineTransform transform;
-            current->gradientTransformCurrentValue().concatenate(transform);
-            attributes.setGradientTransform(transform);
-        }
-
-        if (!attributes.hasStops()) {
-            const Vector<Gradient::ColorStop>& stops(current->buildStops());
-            if (!stops.isEmpty())
-                attributes.setStops(stops);
-        }
-
-        if (isRadial) {
-            SVGRadialGradientElement* radial = toSVGRadialGradientElement(current);
-
-            if (!attributes.hasCx() && current->hasAttribute(SVGNames::cxAttr))
-                attributes.setCx(radial->cxCurrentValue());
-
-            if (!attributes.hasCy() && current->hasAttribute(SVGNames::cyAttr))
-                attributes.setCy(radial->cyCurrentValue());
-
-            if (!attributes.hasR() && current->hasAttribute(SVGNames::rAttr))
-                attributes.setR(radial->rCurrentValue());
-
-            if (!attributes.hasFx() && current->hasAttribute(SVGNames::fxAttr))
-                attributes.setFx(radial->fxCurrentValue());
-
-            if (!attributes.hasFy() && current->hasAttribute(SVGNames::fyAttr))
-                attributes.setFy(radial->fyCurrentValue());
-
-            if (!attributes.hasFr() && current->hasAttribute(SVGNames::frAttr))
-                attributes.setFr(radial->frCurrentValue());
-        }
-
-        processedGradients.add(current);
-
+    while (true) {
         // Respect xlink:href, take attributes from referenced element
-        Node* refNode = SVGURIReference::targetElementFromIRIString(current->hrefCurrentValue(), document());
-        if (refNode && (refNode->hasTagName(SVGNames::radialGradientTag) || refNode->hasTagName(SVGNames::linearGradientTag))) {
+        Node* refNode = SVGURIReference::targetElementFromIRIString(current->href()->currentValue()->value(), document());
+        if (refNode && isSVGGradientElement(*refNode)) {
             current = toSVGGradientElement(refNode);
 
             // Cycle detection
-            if (processedGradients.contains(current)) {
-                current = 0;
+            if (processedGradients.contains(current))
                 break;
-            }
 
-            isRadial = current->hasTagName(SVGNames::radialGradientTag);
-        } else
-            current = 0;
+            if (!current->renderer())
+                return false;
+
+            setGradientAttributes(current, attributes, current->hasTagName(SVGNames::radialGradientTag));
+            processedGradients.add(current);
+        } else {
+            break;
+        }
     }
 
     // Handle default values for fx/fy
@@ -203,17 +210,18 @@
 
     if (!attributes.hasFy())
         attributes.setFy(attributes.cy());
+
     return true;
 }
 
 bool SVGRadialGradientElement::selfHasRelativeLengths() const
 {
-    return cxCurrentValue().isRelative()
-        || cyCurrentValue().isRelative()
-        || rCurrentValue().isRelative()
-        || fxCurrentValue().isRelative()
-        || fyCurrentValue().isRelative()
-        || frCurrentValue().isRelative();
+    return m_cx->currentValue()->isRelative()
+        || m_cy->currentValue()->isRelative()
+        || m_r->currentValue()->isRelative()
+        || m_fx->currentValue()->isRelative()
+        || m_fy->currentValue()->isRelative()
+        || m_fr->currentValue()->isRelative();
 }
 
 }
diff --git a/Source/core/svg/SVGRadialGradientElement.h b/Source/core/svg/SVGRadialGradientElement.h
index e448d20..a4d9fa8 100644
--- a/Source/core/svg/SVGRadialGradientElement.h
+++ b/Source/core/svg/SVGRadialGradientElement.h
@@ -35,24 +35,31 @@
 
     bool collectGradientAttributes(RadialGradientAttributes&);
 
+    SVGAnimatedLength* cx() const { return m_cx.get(); }
+    SVGAnimatedLength* cy() const { return m_cy.get(); }
+    SVGAnimatedLength* r() const { return m_r.get(); }
+    SVGAnimatedLength* fx() const { return m_fx.get(); }
+    SVGAnimatedLength* fy() const { return m_fy.get(); }
+    SVGAnimatedLength* fr() const { return m_fr.get(); }
+
 private:
     explicit SVGRadialGradientElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_cx;
+    RefPtr<SVGAnimatedLength> m_cy;
+    RefPtr<SVGAnimatedLength> m_r;
+    RefPtr<SVGAnimatedLength> m_fx;
+    RefPtr<SVGAnimatedLength> m_fy;
+    RefPtr<SVGAnimatedLength> m_fr;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGRadialGradientElement)
-        DECLARE_ANIMATED_LENGTH(Cx, cx)
-        DECLARE_ANIMATED_LENGTH(Cy, cy)
-        DECLARE_ANIMATED_LENGTH(R, r)
-        DECLARE_ANIMATED_LENGTH(Fx, fx)
-        DECLARE_ANIMATED_LENGTH(Fy, fy)
-        DECLARE_ANIMATED_LENGTH(Fr, fr)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGRect.cpp b/Source/core/svg/SVGRect.cpp
new file mode 100644
index 0000000..85d3417
--- /dev/null
+++ b/Source/core/svg/SVGRect.cpp
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2004, 2005, 2006 Nikolas Zimmermann <zimmermann@kde.org>
+ * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+
+#include "core/svg/SVGRect.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/svg/SVGAnimationElement.h"
+#include "core/svg/SVGParserUtilities.h"
+#include "wtf/text/StringBuilder.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+SVGRect::SVGRect()
+    : NewSVGPropertyBase(classType())
+    , m_isValid(true)
+{
+}
+
+SVGRect::SVGRect(InvalidSVGRectTag)
+    : NewSVGPropertyBase(classType())
+{
+    setInvalid();
+}
+
+SVGRect::SVGRect(const FloatRect& rect)
+    : NewSVGPropertyBase(classType())
+    , m_isValid(true)
+    , m_value(rect)
+{
+}
+
+PassRefPtr<SVGRect> SVGRect::clone() const
+{
+    return SVGRect::create(m_value);
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGRect::cloneForAnimation(const String& value) const
+{
+    RefPtr<SVGRect> rect = SVGRect::create();
+    rect->setValueAsString(value, IGNORE_EXCEPTION);
+    return rect.release();
+}
+
+template<typename CharType>
+void SVGRect::parse(const CharType*& ptr, const CharType* end, ExceptionState& exceptionState)
+{
+    const CharType* start = ptr;
+
+    skipOptionalSVGSpaces(ptr, end);
+
+    float x = 0.0f;
+    float y = 0.0f;
+    float width = 0.0f;
+    float height = 0.0f;
+    bool valid = parseNumber(ptr, end, x) && parseNumber(ptr, end, y) && parseNumber(ptr, end, width) && parseNumber(ptr, end, height, false);
+
+    if (!valid) {
+        exceptionState.throwDOMException(SyntaxError, "Problem parsing rect \"" + String(start, end - start) + "\"");
+        setInvalid();
+        return;
+    }
+
+    skipOptionalSVGSpaces(ptr, end);
+    if (ptr < end) { // nothing should come after the last, fourth number
+        exceptionState.throwDOMException(SyntaxError, "Problem parsing rect \"" + String(start, end - start) + "\"");
+        setInvalid();
+        return;
+    }
+
+    m_value = FloatRect(x, y, width, height);
+    m_isValid = true;
+}
+
+void SVGRect::setValueAsString(const String& string, ExceptionState& exceptionState)
+{
+    if (string.isNull()) {
+        setInvalid();
+        return;
+    }
+    if (string.isEmpty()) {
+        m_value = FloatRect(0.0f, 0.0f, 0.0f, 0.0f);
+        m_isValid = true;
+        return;
+    }
+
+    if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        parse(ptr, end, exceptionState);
+        return;
+    }
+
+    const UChar* ptr = string.characters16();
+    const UChar* end = ptr + string.length();
+    parse(ptr, end, exceptionState);
+}
+
+String SVGRect::valueAsString() const
+{
+    StringBuilder builder;
+    builder.append(String::number(x()));
+    builder.append(' ');
+    builder.append(String::number(y()));
+    builder.append(' ');
+    builder.append(String::number(width()));
+    builder.append(' ');
+    builder.append(String::number(height()));
+    return builder.toString();
+}
+
+void SVGRect::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement*)
+{
+    m_value += toSVGRect(other)->value();
+}
+
+void SVGRect::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*)
+{
+    ASSERT(animationElement);
+    RefPtr<SVGRect> fromRect = animationElement->animationMode() == ToAnimation ? this : toSVGRect(fromValue);
+    RefPtr<SVGRect> toRect = toSVGRect(toValue);
+    RefPtr<SVGRect> toAtEndOfDurationRect = toSVGRect(toAtEndOfDurationValue);
+
+    float animatedX = x();
+    float animatedY = y();
+    float animatedWidth = width();
+    float animatedHeight = height();
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromRect->x(), toRect->x(), toAtEndOfDurationRect->x(), animatedX);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromRect->y(), toRect->y(), toAtEndOfDurationRect->y(), animatedY);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromRect->width(), toRect->width(), toAtEndOfDurationRect->width(), animatedWidth);
+    animationElement->animateAdditiveNumber(percentage, repeatCount, fromRect->height(), toRect->height(), toAtEndOfDurationRect->height(), animatedHeight);
+
+    m_value = FloatRect(animatedX, animatedY, animatedWidth, animatedHeight);
+}
+
+float SVGRect::calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement)
+{
+    // FIXME: Distance calculation is not possible for SVGRect right now. We need the distance for every single value.
+    return -1;
+}
+
+void SVGRect::setInvalid()
+{
+    m_value = FloatRect(0.0f, 0.0f, 0.0f, 0.0f);
+    m_isValid = false;
+}
+
+}
diff --git a/Source/core/svg/SVGRect.h b/Source/core/svg/SVGRect.h
index 775c196..b52c82a 100644
--- a/Source/core/svg/SVGRect.h
+++ b/Source/core/svg/SVGRect.h
@@ -20,55 +20,82 @@
 #ifndef SVGRect_h
 #define SVGRect_h
 
-#include "core/svg/properties/SVGPropertyTraits.h"
+#include "core/svg/properties/NewSVGProperty.h"
 #include "platform/geometry/FloatRect.h"
-#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
-class SVGRect : public FloatRect {
+class SVGRectTearOff;
+
+class SVGRect : public NewSVGPropertyBase {
 public:
+    typedef SVGRectTearOff TearOffType;
+
     struct InvalidSVGRectTag { };
 
-    SVGRect()
-        : m_isValid(true) { }
-    SVGRect(InvalidSVGRectTag)
-        : m_isValid(false) { }
-    SVGRect(const FloatRect& rect)
-        : FloatRect(rect), m_isValid(true) { }
-    SVGRect(const FloatPoint& location, const FloatSize& size)
-        : FloatRect(location, size), m_isValid(true) { }
-    SVGRect(float x, float y, float width, float height)
-        : FloatRect(x, y, width, height), m_isValid(true) { }
-    SVGRect(const IntRect& intRect)
-        : FloatRect(intRect), m_isValid(true) { }
-    SVGRect(const LayoutRect& layoutRect)
-        : FloatRect(layoutRect), m_isValid(true) { }
-    SVGRect(const SkRect& skRect)
-        : FloatRect(skRect), m_isValid(true) { }
+    static PassRefPtr<SVGRect> create()
+    {
+        return adoptRef(new SVGRect());
+    }
+
+    static PassRefPtr<SVGRect> create(InvalidSVGRectTag)
+    {
+        return adoptRef(new SVGRect(InvalidSVGRectTag()));
+    }
+
+    static PassRefPtr<SVGRect> create(const FloatRect& rect)
+    {
+        return adoptRef(new SVGRect(rect));
+    }
+
+    PassRefPtr<SVGRect> clone() const;
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+
+    const FloatRect& value() const { return m_value; }
+    void setValue(const FloatRect& v) { m_value = v; }
+
+    float x() const { return m_value.x(); }
+    float y() const { return m_value.y(); }
+    float width() const { return m_value.width(); }
+    float height() const { return m_value.height(); }
+    void setX(float f) { m_value.setX(f); }
+    void setY(float f) { m_value.setY(f); }
+    void setWidth(float f) { m_value.setWidth(f); }
+    void setHeight(float f) { m_value.setHeight(f); }
+
+    bool operator==(const SVGRect&) const;
+    bool operator!=(const SVGRect& other) const { return !operator==(other); }
+
+    virtual String valueAsString() const OVERRIDE;
+    void setValueAsString(const String&, ExceptionState&);
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement* contextElement) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement* contextElement) OVERRIDE;
 
     bool isValid() const { return m_isValid; }
+    void setInvalid();
+
+    static AnimatedPropertyType classType() { return AnimatedRect; }
 
 private:
+    SVGRect();
+    SVGRect(InvalidSVGRectTag);
+    SVGRect(const FloatRect&);
+
+    template<typename CharType>
+    void parse(const CharType*& ptr, const CharType* end, ExceptionState&);
+
     bool m_isValid;
+    FloatRect m_value;
 };
 
-template<>
-struct SVGPropertyTraits<SVGRect> {
-    static SVGRect initialValue() { return SVGRect(SVGRect::InvalidSVGRectTag()); }
-    static String toString(const SVGRect& type)
-    {
-        StringBuilder builder;
-        builder.append(String::number(type.x()));
-        builder.append(' ');
-        builder.append(String::number(type.y()));
-        builder.append(' ');
-        builder.append(String::number(type.width()));
-        builder.append(' ');
-        builder.append(String::number(type.height()));
-        return builder.toString();
-    }
-};
+inline PassRefPtr<SVGRect> toSVGRect(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGRect::classType());
+    return static_pointer_cast<SVGRect>(base.release());
+}
 
 } // namespace WebCore
 
diff --git a/Source/core/svg/SVGRect.idl b/Source/core/svg/SVGRect.idl
index e148788..3f1be98 100644
--- a/Source/core/svg/SVGRect.idl
+++ b/Source/core/svg/SVGRect.idl
@@ -20,10 +20,13 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface SVGRect {
-    [StrictTypeChecking] attribute float x;
-    [StrictTypeChecking] attribute float y;
-    [StrictTypeChecking] attribute float width;
-    [StrictTypeChecking] attribute float height;
+[
+    ImplementedAs=SVGRectTearOff,
+    SetWrapperReferenceTo(SVGElement contextElement),
+    StrictTypeChecking,
+] interface SVGRect {
+    [RaisesException=Setter] attribute float x;
+    [RaisesException=Setter] attribute float y;
+    [RaisesException=Setter] attribute float width;
+    [RaisesException=Setter] attribute float height;
 };
-
diff --git a/Source/core/svg/SVGRectElement.cpp b/Source/core/svg/SVGRectElement.cpp
index 997db63..e3fa044 100644
--- a/Source/core/svg/SVGRectElement.cpp
+++ b/Source/core/svg/SVGRectElement.cpp
@@ -30,35 +30,28 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGRectElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGRectElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH(SVGRectElement, SVGNames::widthAttr, Width, width)
-DEFINE_ANIMATED_LENGTH(SVGRectElement, SVGNames::heightAttr, Height, height)
-DEFINE_ANIMATED_LENGTH(SVGRectElement, SVGNames::rxAttr, Rx, rx)
-DEFINE_ANIMATED_LENGTH(SVGRectElement, SVGNames::ryAttr, Ry, ry)
-DEFINE_ANIMATED_BOOLEAN(SVGRectElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGRectElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(width)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(height)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(rx)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(ry)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGRectElement::SVGRectElement(Document& document)
     : SVGGeometryElement(SVGNames::rectTag, document)
-    , m_x(LengthModeWidth)
-    , m_y(LengthModeHeight)
-    , m_width(LengthModeWidth)
-    , m_height(LengthModeHeight)
-    , m_rx(LengthModeWidth)
-    , m_ry(LengthModeHeight)
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
+    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth)))
+    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight)))
+    , m_rx(SVGAnimatedLength::create(this, SVGNames::rxAttr, SVGLength::create(LengthModeWidth)))
+    , m_ry(SVGAnimatedLength::create(this, SVGNames::ryAttr, SVGLength::create(LengthModeHeight)))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_width);
+    addToPropertyMap(m_height);
+    addToPropertyMap(m_rx);
+    addToPropertyMap(m_ry);
+
     registerAnimatedPropertiesForSVGRectElement();
 }
 
@@ -71,8 +64,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGLangSpace::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::xAttr);
         supportedAttributes.add(SVGNames::yAttr);
         supportedAttributes.add(SVGNames::widthAttr);
@@ -90,20 +81,18 @@
     if (!isSupportedAttribute(name))
         SVGGeometryElement::parseAttribute(name, value);
     else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
     else if (name == SVGNames::rxAttr)
-        setRxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
+        m_rx->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::ryAttr)
-        setRyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
+        m_ry->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::widthAttr)
-        setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
+        m_width->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
     else if (name == SVGNames::heightAttr)
-        setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGLangSpace::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)) {
-    } else
+        m_height->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    else
         ASSERT_NOT_REACHED();
 
     reportAttributeParsingError(parseError, name, value);
@@ -138,22 +127,17 @@
         return;
     }
 
-    if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
-        RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
-        return;
-    }
-
     ASSERT_NOT_REACHED();
 }
 
 bool SVGRectElement::selfHasRelativeLengths() const
 {
-    return xCurrentValue().isRelative()
-        || yCurrentValue().isRelative()
-        || widthCurrentValue().isRelative()
-        || heightCurrentValue().isRelative()
-        || rxCurrentValue().isRelative()
-        || ryCurrentValue().isRelative();
+    return m_x->currentValue()->isRelative()
+        || m_y->currentValue()->isRelative()
+        || m_width->currentValue()->isRelative()
+        || m_height->currentValue()->isRelative()
+        || m_rx->currentValue()->isRelative()
+        || m_ry->currentValue()->isRelative();
 }
 
 RenderObject* SVGRectElement::createRenderer(RenderStyle*)
diff --git a/Source/core/svg/SVGRectElement.h b/Source/core/svg/SVGRectElement.h
index 1a50088..c838080 100644
--- a/Source/core/svg/SVGRectElement.h
+++ b/Source/core/svg/SVGRectElement.h
@@ -24,38 +24,41 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGeometryElement.h"
 
 namespace WebCore {
 
-class SVGRectElement FINAL : public SVGGeometryElement,
-                             public SVGExternalResourcesRequired {
+class SVGRectElement FINAL : public SVGGeometryElement {
 public:
     static PassRefPtr<SVGRectElement> create(Document&);
 
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
+    SVGAnimatedLength* width() const { return m_width.get(); }
+    SVGAnimatedLength* height() const { return m_height.get(); }
+    SVGAnimatedLength* rx() const { return m_rx.get(); }
+    SVGAnimatedLength* ry() const { return m_ry.get(); }
+
 private:
     explicit SVGRectElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
+    RefPtr<SVGAnimatedLength> m_width;
+    RefPtr<SVGAnimatedLength> m_height;
+    RefPtr<SVGAnimatedLength> m_rx;
+    RefPtr<SVGAnimatedLength> m_ry;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGRectElement)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_LENGTH(Width, width)
-        DECLARE_ANIMATED_LENGTH(Height, height)
-        DECLARE_ANIMATED_LENGTH(Rx, rx)
-        DECLARE_ANIMATED_LENGTH(Ry, ry)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGRectElement.idl b/Source/core/svg/SVGRectElement.idl
index a3cf85e..3bbe39a 100644
--- a/Source/core/svg/SVGRectElement.idl
+++ b/Source/core/svg/SVGRectElement.idl
@@ -33,5 +33,3 @@
     readonly attribute SVGAnimatedLength ry;
 };
 
-SVGRectElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGRectTearOff.cpp b/Source/core/svg/SVGRectTearOff.cpp
new file mode 100644
index 0000000..64a2538
--- /dev/null
+++ b/Source/core/svg/SVGRectTearOff.cpp
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+
+#include "core/svg/SVGRectTearOff.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+
+namespace WebCore {
+
+SVGRectTearOff::SVGRectTearOff(PassRefPtr<SVGRect> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName)
+    : NewSVGPropertyTearOff<SVGRect>(target, contextElement, propertyIsAnimVal, attributeName)
+{
+    ScriptWrappable::init(this);
+}
+
+void SVGRectTearOff::setX(float f, ExceptionState& exceptionState)
+{
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    target()->setX(f);
+    commitChange();
+}
+
+void SVGRectTearOff::setY(float f, ExceptionState& exceptionState)
+{
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    target()->setY(f);
+    commitChange();
+}
+
+void SVGRectTearOff::setWidth(float f, ExceptionState& exceptionState)
+{
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    target()->setWidth(f);
+    commitChange();
+}
+
+void SVGRectTearOff::setHeight(float f, ExceptionState& exceptionState)
+{
+    if (isImmutable()) {
+        exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+        return;
+    }
+
+    target()->setHeight(f);
+    commitChange();
+}
+
+}
diff --git a/Source/core/dom/DataTransferItem.h b/Source/core/svg/SVGRectTearOff.h
similarity index 60%
copy from Source/core/dom/DataTransferItem.h
copy to Source/core/svg/SVGRectTearOff.h
index 03dd377..46d3d9d 100644
--- a/Source/core/dom/DataTransferItem.h
+++ b/Source/core/svg/SVGRectTearOff.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,47 +28,35 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef DataTransferItem_h
-#define DataTransferItem_h
+#ifndef SVGRectTearOff_h
+#define SVGRectTearOff_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "wtf/Forward.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
+#include "core/svg/SVGRect.h"
+#include "core/svg/properties/NewSVGPropertyTearOff.h"
 
 namespace WebCore {
 
-class Blob;
-class ChromiumDataObjectItem;
-class Clipboard;
-class File;
-class StringCallback;
-class ExecutionContext;
-
-class DataTransferItem : public RefCounted<DataTransferItem>, public ScriptWrappable {
+class SVGRectTearOff : public NewSVGPropertyTearOff<SVGRect>, public ScriptWrappable {
 public:
-    static PassRefPtr<DataTransferItem> create(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObjectItem>);
-    ~DataTransferItem();
+    static PassRefPtr<SVGRectTearOff> create(PassRefPtr<SVGRect> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+    {
+        return adoptRef(new SVGRectTearOff(target, contextElement, propertyIsAnimVal, attributeName));
+    }
 
-    static const char kindString[];
-    static const char kindFile[];
-
-    String kind() const;
-    String type() const;
-
-    void getAsString(ExecutionContext*, PassOwnPtr<StringCallback>) const;
-    PassRefPtr<Blob> getAsFile() const;
-
-    Clipboard* clipboard() { return m_clipboard.get(); }
-    ChromiumDataObjectItem* dataObjectItem() { return m_item.get(); }
+    void setX(float, ExceptionState&);
+    void setY(float, ExceptionState&);
+    void setWidth(float, ExceptionState&);
+    void setHeight(float, ExceptionState&);
+    float x() { return target()->x(); }
+    float y() { return target()->y(); }
+    float width() { return target()->width(); }
+    float height() { return target()->height(); }
 
 private:
-    DataTransferItem(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObjectItem>);
-
-    RefPtr<Clipboard> m_clipboard;
-    RefPtr<ChromiumDataObjectItem> m_item;
+    SVGRectTearOff(PassRefPtr<SVGRect>, SVGElement* contextElement, PropertyIsAnimValType, const QualifiedName& attributeName = nullQName());
 };
 
 } // namespace WebCore
 
-#endif // DataTransferItem_h
+#endif // SVGRectTearOff_h_
diff --git a/Source/core/svg/SVGSVGElement.cpp b/Source/core/svg/SVGSVGElement.cpp
index 1a5f98b..c2df77e 100644
--- a/Source/core/svg/SVGSVGElement.cpp
+++ b/Source/core/svg/SVGSVGElement.cpp
@@ -46,7 +46,9 @@
 #include "core/rendering/svg/RenderSVGViewportContainer.h"
 #include "core/svg/SVGAngle.h"
 #include "core/svg/SVGElementInstance.h"
+#include "core/svg/SVGNumberTearOff.h"
 #include "core/svg/SVGPreserveAspectRatio.h"
+#include "core/svg/SVGRectTearOff.h"
 #include "core/svg/SVGTransform.h"
 #include "core/svg/SVGTransformList.h"
 #include "core/svg/SVGViewElement.h"
@@ -61,37 +63,31 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGSVGElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGSVGElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH(SVGSVGElement, SVGNames::widthAttr, Width, width)
-DEFINE_ANIMATED_LENGTH(SVGSVGElement, SVGNames::heightAttr, Height, height)
-DEFINE_ANIMATED_BOOLEAN(SVGSVGElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-DEFINE_ANIMATED_PRESERVEASPECTRATIO(SVGSVGElement, SVGNames::preserveAspectRatioAttr, PreserveAspectRatio, preserveAspectRatio)
-DEFINE_ANIMATED_RECT(SVGSVGElement, SVGNames::viewBoxAttr, ViewBox, viewBox)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGSVGElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(width)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(height)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(viewBox)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAspectRatio)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGSVGElement::SVGSVGElement(Document& doc)
     : SVGGraphicsElement(SVGNames::svgTag, doc)
-    , m_x(LengthModeWidth)
-    , m_y(LengthModeHeight)
-    , m_width(LengthModeWidth, "100%")
-    , m_height(LengthModeHeight, "100%")
+    , SVGFitToViewBox(this)
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
+    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth)))
+    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight)))
     , m_useCurrentView(false)
-    , m_zoomAndPan(SVGZoomAndPanMagnify)
     , m_timeContainer(SMILTimeContainer::create(this))
-    , m_weakFactory(this)
+    , m_translation(SVGPoint::create())
 {
     ScriptWrappable::init(this);
+
+    m_width->setDefaultValueAsString("100%");
+    m_height->setDefaultValueAsString("100%");
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_width);
+    addToPropertyMap(m_height);
     registerAnimatedPropertiesForSVGSVGElement();
 
     UseCounter::count(doc, UseCounter::SVGSVGElement);
@@ -104,6 +100,9 @@
 
 SVGSVGElement::~SVGSVGElement()
 {
+    if (m_viewSpec)
+        m_viewSpec->detachContextElement();
+
     // There are cases where removedFromDocument() is not called.
     // see ContainerNode::removeAllChildren, called by its destructor.
     document().accessSVGExtensions()->removeTimeContainer(this);
@@ -135,11 +134,11 @@
     setAttribute(SVGNames::contentStyleTypeAttr, type);
 }
 
-SVGRect SVGSVGElement::viewport() const
+PassRefPtr<SVGRectTearOff> SVGSVGElement::viewport() const
 {
     // FIXME: This method doesn't follow the spec and is basically untested. Parent documents are not considered here.
     // As we have no test coverage for this, we're going to disable it completly for now.
-    return SVGRect();
+    return SVGRectTearOff::create(SVGRect::create(), 0, PropertyIsNotAnimVal);
 }
 
 float SVGSVGElement::pixelUnitToMillimeterX() const
@@ -165,7 +164,7 @@
 SVGViewSpec* SVGSVGElement::currentView()
 {
     if (!m_viewSpec)
-        m_viewSpec = SVGViewSpec::create(m_weakFactory.createWeakPtr());
+        m_viewSpec = SVGViewSpec::create(this);
     return m_viewSpec.get();
 }
 
@@ -206,9 +205,34 @@
     frame->setPageZoomFactor(scale);
 }
 
-void SVGSVGElement::setCurrentTranslate(const FloatPoint& translation)
+class SVGCurrentTranslateTearOff : public SVGPointTearOff {
+public:
+    static PassRefPtr<SVGCurrentTranslateTearOff> create(SVGSVGElement* contextElement)
+    {
+        return adoptRef(new SVGCurrentTranslateTearOff(contextElement));
+    }
+
+    virtual void commitChange() OVERRIDE
+    {
+        ASSERT(contextElement());
+        toSVGSVGElement(contextElement())->updateCurrentTranslate();
+    }
+
+private:
+    SVGCurrentTranslateTearOff(SVGSVGElement* contextElement)
+        : SVGPointTearOff(contextElement->m_translation, contextElement, PropertyIsNotAnimVal)
+    {
+    }
+};
+
+PassRefPtr<SVGPointTearOff> SVGSVGElement::currentTranslateFromJavascript()
 {
-    m_translation = translation;
+    return SVGCurrentTranslateTearOff::create(this);
+}
+
+void SVGSVGElement::setCurrentTranslate(const FloatPoint& point)
+{
+    m_translation->setValue(point);
     updateCurrentTranslate();
 }
 
@@ -244,24 +268,23 @@
             return;
     }
 
-    if (name == HTMLNames::onabortAttr)
+    if (name == HTMLNames::onabortAttr) {
         document().setWindowAttributeEventListener(EventTypeNames::abort, createAttributeEventListener(document().frame(), name, value));
-    else if (name == HTMLNames::onerrorAttr)
+    } else if (name == HTMLNames::onerrorAttr) {
         document().setWindowAttributeEventListener(EventTypeNames::error, createAttributeEventListener(document().frame(), name, value));
-    else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
-    else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (name == SVGNames::widthAttr)
-        setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
-    else if (name == SVGNames::heightAttr)
-        setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGLangSpace::parseAttribute(name, value)
-               || SVGExternalResourcesRequired::parseAttribute(name, value)
-               || SVGFitToViewBox::parseAttribute(this, name, value)
-               || SVGZoomAndPan::parseAttribute(this, name, value)) {
-    } else
+    } else if (name == SVGNames::xAttr) {
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::yAttr) {
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::widthAttr) {
+        m_width->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (name == SVGNames::heightAttr) {
+        m_height->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (SVGFitToViewBox::parseAttribute(name, value, document(), parseError)) {
+    } else if (SVGZoomAndPan::parseAttribute(name, value)) {
+    } else {
         SVGGraphicsElement::parseAttribute(name, value);
+    }
 
     reportAttributeParsingError(parseError, name, value);
 }
@@ -296,8 +319,6 @@
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
 
     if (updateRelativeLengthsOrViewBox
-        || SVGLangSpace::isKnownAttribute(attrName)
-        || SVGExternalResourcesRequired::isKnownAttribute(attrName)
         || SVGZoomAndPan::isKnownAttribute(attrName)) {
         if (renderer())
             RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer());
@@ -307,28 +328,7 @@
     SVGGraphicsElement::svgAttributeChanged(attrName);
 }
 
-unsigned SVGSVGElement::suspendRedraw(unsigned /* maxWaitMilliseconds */)
-{
-    // FIXME: Implement me (see bug 11275)
-    return 0;
-}
-
-void SVGSVGElement::unsuspendRedraw(unsigned /* suspendHandleId */)
-{
-    // FIXME: Implement me (see bug 11275)
-}
-
-void SVGSVGElement::unsuspendRedrawAll()
-{
-    // FIXME: Implement me (see bug 11275)
-}
-
-void SVGSVGElement::forceRedraw()
-{
-    // FIXME: Implement me (see bug 11275)
-}
-
-PassRefPtr<NodeList> SVGSVGElement::collectIntersectionOrEnclosureList(const SVGRect& rect, SVGElement* referenceElement, CollectIntersectionOrEnclosure collect) const
+PassRefPtr<NodeList> SVGSVGElement::collectIntersectionOrEnclosureList(const FloatRect& rect, SVGElement* referenceElement, CollectIntersectionOrEnclosure collect) const
 {
     Vector<RefPtr<Node> > nodes;
     Element* element = ElementTraversal::next(*(referenceElement ? referenceElement : this));
@@ -336,10 +336,10 @@
         if (element->isSVGElement()) {
             SVGElement* svgElement = toSVGElement(element);
             if (collect == CollectIntersectionList) {
-                if (checkIntersection(svgElement, rect))
+                if (RenderSVGModelObject::checkIntersection(svgElement->renderer(), rect))
                     nodes.append(element);
             } else {
-                if (checkEnclosure(svgElement, rect))
+                if (RenderSVGModelObject::checkEnclosure(svgElement->renderer(), rect))
                     nodes.append(element);
             }
         }
@@ -349,28 +349,28 @@
     return StaticNodeList::adopt(nodes);
 }
 
-PassRefPtr<NodeList> SVGSVGElement::getIntersectionList(const SVGRect& rect, SVGElement* referenceElement) const
+PassRefPtr<NodeList> SVGSVGElement::getIntersectionList(PassRefPtr<SVGRectTearOff> passRect, SVGElement* referenceElement) const
 {
-    return collectIntersectionOrEnclosureList(rect, referenceElement, CollectIntersectionList);
+    RefPtr<SVGRectTearOff> rect = passRect;
+    return collectIntersectionOrEnclosureList(rect->target()->value(), referenceElement, CollectIntersectionList);
 }
 
-PassRefPtr<NodeList> SVGSVGElement::getEnclosureList(const SVGRect& rect, SVGElement* referenceElement) const
+PassRefPtr<NodeList> SVGSVGElement::getEnclosureList(PassRefPtr<SVGRectTearOff> passRect, SVGElement* referenceElement) const
 {
-    return collectIntersectionOrEnclosureList(rect, referenceElement, CollectEnclosureList);
+    RefPtr<SVGRectTearOff> rect = passRect;
+    return collectIntersectionOrEnclosureList(rect->target()->value(), referenceElement, CollectEnclosureList);
 }
 
-bool SVGSVGElement::checkIntersection(SVGElement* element, const SVGRect& rect) const
+bool SVGSVGElement::checkIntersection(SVGElement* element, PassRefPtr<SVGRectTearOff> passRect) const
 {
-    if (!element)
-        return false;
-    return RenderSVGModelObject::checkIntersection(element->renderer(), rect);
+    RefPtr<SVGRectTearOff> rect = passRect;
+    return RenderSVGModelObject::checkIntersection(element->renderer(), rect->target()->value());
 }
 
-bool SVGSVGElement::checkEnclosure(SVGElement* element, const SVGRect& rect) const
+bool SVGSVGElement::checkEnclosure(SVGElement* element, PassRefPtr<SVGRectTearOff> passRect) const
 {
-    if (!element)
-        return false;
-    return RenderSVGModelObject::checkEnclosure(element->renderer(), rect);
+    RefPtr<SVGRectTearOff> rect = passRect;
+    return RenderSVGModelObject::checkEnclosure(element->renderer(), rect->target()->value());
 }
 
 void SVGSVGElement::deselectAll()
@@ -379,14 +379,14 @@
         frame->selection().clear();
 }
 
-float SVGSVGElement::createSVGNumber()
+PassRefPtr<SVGNumberTearOff> SVGSVGElement::createSVGNumber()
 {
-    return 0.0f;
+    return SVGNumberTearOff::create(SVGNumber::create(0.0f), 0, PropertyIsNotAnimVal);
 }
 
-SVGLength SVGSVGElement::createSVGLength()
+PassRefPtr<SVGLengthTearOff> SVGSVGElement::createSVGLength()
 {
-    return SVGLength();
+    return SVGLengthTearOff::create(SVGLength::create(), 0, PropertyIsNotAnimVal);
 }
 
 SVGAngle SVGSVGElement::createSVGAngle()
@@ -394,9 +394,9 @@
     return SVGAngle();
 }
 
-SVGPoint SVGSVGElement::createSVGPoint()
+PassRefPtr<SVGPointTearOff> SVGSVGElement::createSVGPoint()
 {
-    return SVGPoint();
+    return SVGPointTearOff::create(SVGPoint::create(), 0, PropertyIsNotAnimVal);
 }
 
 SVGMatrix SVGSVGElement::createSVGMatrix()
@@ -404,9 +404,9 @@
     return SVGMatrix();
 }
 
-SVGRect SVGSVGElement::createSVGRect()
+PassRefPtr<SVGRectTearOff> SVGSVGElement::createSVGRect()
 {
-    return SVGRect();
+    return SVGRectTearOff::create(SVGRect::create(), 0, PropertyIsNotAnimVal);
 }
 
 SVGTransform SVGSVGElement::createSVGTransform()
@@ -430,7 +430,7 @@
     AffineTransform transform;
     if (!isOutermostSVGSVGElement()) {
         SVGLengthContext lengthContext(this);
-        transform.translate(xCurrentValue().value(lengthContext), yCurrentValue().value(lengthContext));
+        transform.translate(m_x->currentValue()->value(lengthContext), m_y->currentValue()->value(lengthContext));
     } else if (mode == SVGElement::ScreenScope) {
         if (RenderObject* renderer = this->renderer()) {
             FloatPoint location;
@@ -488,6 +488,8 @@
 Node::InsertionNotificationRequest SVGSVGElement::insertedInto(ContainerNode* rootParent)
 {
     if (rootParent->inDocument()) {
+        UseCounter::count(document(), UseCounter::SVGSVGElementInDocument);
+
         document().accessSVGExtensions()->addTimeContainer(this);
 
         // Animations are started at the end of document parsing and after firing the load event,
@@ -542,34 +544,34 @@
 
 bool SVGSVGElement::selfHasRelativeLengths() const
 {
-    return xCurrentValue().isRelative()
-        || yCurrentValue().isRelative()
-        || widthCurrentValue().isRelative()
-        || heightCurrentValue().isRelative()
+    return m_x->currentValue()->isRelative()
+        || m_y->currentValue()->isRelative()
+        || m_width->currentValue()->isRelative()
+        || m_height->currentValue()->isRelative()
         || hasAttribute(SVGNames::viewBoxAttr);
 }
 
-SVGRect SVGSVGElement::currentViewBoxRect() const
+FloatRect SVGSVGElement::currentViewBoxRect() const
 {
     if (m_useCurrentView)
-        return m_viewSpec ? m_viewSpec->viewBoxCurrentValue() : SVGRect();
+        return m_viewSpec ? m_viewSpec->viewBox()->currentValue()->value() : FloatRect();
 
-    FloatRect useViewBox = viewBoxCurrentValue();
+    FloatRect useViewBox = viewBox()->currentValue()->value();
     if (!useViewBox.isEmpty())
         return useViewBox;
     if (!renderer() || !renderer()->isSVGRoot())
-        return SVGRect();
+        return FloatRect();
     if (!toRenderSVGRoot(renderer())->isEmbeddedThroughSVGImage())
-        return SVGRect();
+        return FloatRect();
 
     Length intrinsicWidth = this->intrinsicWidth();
     Length intrinsicHeight = this->intrinsicHeight();
     if (!intrinsicWidth.isFixed() || !intrinsicHeight.isFixed())
-        return SVGRect();
+        return FloatRect();
 
     // If no viewBox is specified but non-relative width/height values, then we
     // should always synthesize a viewBox if we're embedded through a SVGImage.
-    return SVGRect(FloatPoint(), FloatSize(floatValueForLength(intrinsicWidth, 0, 0), floatValueForLength(intrinsicHeight, 0, 0)));
+    return FloatRect(FloatPoint(), FloatSize(floatValueForLength(intrinsicWidth, 0), floatValueForLength(intrinsicHeight, 0)));
 }
 
 FloatSize SVGSVGElement::currentViewportSize() const
@@ -642,11 +644,11 @@
 Length SVGSVGElement::intrinsicWidth(ConsiderCSSMode mode) const
 {
     if (widthAttributeEstablishesViewport() || mode == IgnoreCSSProperties) {
-        if (widthCurrentValue().unitType() == LengthTypePercentage)
-            return Length(widthCurrentValue().valueAsPercentage() * 100, Percent);
+        if (m_width->currentValue()->unitType() == LengthTypePercentage)
+            return Length(m_width->currentValue()->valueAsPercentage() * 100, Percent);
 
         SVGLengthContext lengthContext(this);
-        return Length(widthCurrentValue().value(lengthContext), Fixed);
+        return Length(m_width->currentValue()->value(lengthContext), Fixed);
     }
 
     ASSERT(renderer());
@@ -656,11 +658,11 @@
 Length SVGSVGElement::intrinsicHeight(ConsiderCSSMode mode) const
 {
     if (heightAttributeEstablishesViewport() || mode == IgnoreCSSProperties) {
-        if (heightCurrentValue().unitType() == LengthTypePercentage)
-            return Length(heightCurrentValue().valueAsPercentage() * 100, Percent);
+        if (m_height->currentValue()->unitType() == LengthTypePercentage)
+            return Length(m_height->currentValue()->valueAsPercentage() * 100, Percent);
 
         SVGLengthContext lengthContext(this);
-        return Length(heightCurrentValue().value(lengthContext), Fixed);
+        return Length(m_height->currentValue()->value(lengthContext), Fixed);
     }
 
     ASSERT(renderer());
@@ -670,9 +672,9 @@
 AffineTransform SVGSVGElement::viewBoxToViewTransform(float viewWidth, float viewHeight) const
 {
     if (!m_useCurrentView || !m_viewSpec)
-        return SVGFitToViewBox::viewBoxToViewTransform(currentViewBoxRect(), preserveAspectRatioCurrentValue(), viewWidth, viewHeight);
+        return SVGFitToViewBox::viewBoxToViewTransform(currentViewBoxRect(), preserveAspectRatio()->currentValue(), viewWidth, viewHeight);
 
-    AffineTransform ctm = SVGFitToViewBox::viewBoxToViewTransform(currentViewBoxRect(), m_viewSpec->preserveAspectRatioCurrentValue(), viewWidth, viewHeight);
+    AffineTransform ctm = SVGFitToViewBox::viewBoxToViewTransform(currentViewBoxRect(), m_viewSpec->preserveAspectRatio()->currentValue(), viewWidth, viewHeight);
     const SVGTransformList& transformList = m_viewSpec->transformBaseValue();
     if (transformList.isEmpty())
         return ctm;
@@ -742,19 +744,22 @@
     m_useCurrentView = true;
 
     if (viewElement->hasAttribute(SVGNames::viewBoxAttr))
-        view->setViewBoxBaseValue(viewElement->viewBoxCurrentValue());
+        view->viewBox()->baseValue()->setValue(viewElement->viewBox()->currentValue()->value());
     else
-        view->setViewBoxBaseValue(viewBoxCurrentValue());
+        view->viewBox()->baseValue()->setValue(viewBox()->currentValue()->value());
 
-    if (viewElement->hasAttribute(SVGNames::preserveAspectRatioAttr))
-        view->setPreserveAspectRatioBaseValue(viewElement->preserveAspectRatioBaseValue());
-    else
-        view->setPreserveAspectRatioBaseValue(preserveAspectRatioBaseValue());
+    if (viewElement->hasAttribute(SVGNames::preserveAspectRatioAttr)) {
+        view->preserveAspectRatio()->baseValue()->setAlign(viewElement->preserveAspectRatio()->currentValue()->align());
+        view->preserveAspectRatio()->baseValue()->setMeetOrSlice(viewElement->preserveAspectRatio()->currentValue()->meetOrSlice());
+    } else {
+        view->preserveAspectRatio()->baseValue()->setAlign(preserveAspectRatio()->currentValue()->align());
+        view->preserveAspectRatio()->baseValue()->setMeetOrSlice(preserveAspectRatio()->currentValue()->meetOrSlice());
+    }
 
     if (viewElement->hasAttribute(SVGNames::zoomAndPanAttr))
-        view->setZoomAndPanBaseValue(viewElement->zoomAndPan());
+        view->setZoomAndPan(viewElement->zoomAndPan());
     else
-        view->setZoomAndPanBaseValue(zoomAndPan());
+        view->setZoomAndPan(zoomAndPan());
 }
 
 // getElementById on SVGSVGElement is restricted to only the child subtree defined by the <svg> element.
diff --git a/Source/core/svg/SVGSVGElement.h b/Source/core/svg/SVGSVGElement.h
index 65f8c69..0941693 100644
--- a/Source/core/svg/SVGSVGElement.h
+++ b/Source/core/svg/SVGSVGElement.h
@@ -23,25 +23,23 @@
 
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
-#include "core/svg/SVGAnimatedRect.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFitToViewBox.h"
 #include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGLengthTearOff.h"
+#include "core/svg/SVGPointTearOff.h"
 #include "core/svg/SVGZoomAndPan.h"
-#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
 class SVGAngle;
 class SVGMatrix;
+class SVGNumberTearOff;
 class SVGTransform;
 class SVGViewSpec;
 class SVGViewElement;
 class SMILTimeContainer;
 
 class SVGSVGElement FINAL : public SVGGraphicsElement,
-                            public SVGExternalResourcesRequired,
                             public SVGFitToViewBox,
                             public SVGZoomAndPan {
 public:
@@ -50,7 +48,6 @@
     using SVGGraphicsElement::ref;
     using SVGGraphicsElement::deref;
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     // 'SVGSVGElement' functions
@@ -60,7 +57,7 @@
     const AtomicString& contentStyleType() const;
     void setContentStyleType(const AtomicString& type);
 
-    SVGRect viewport() const;
+    PassRefPtr<SVGRectTearOff> viewport() const;
 
     float pixelUnitToMillimeterX() const;
     float pixelUnitToMillimeterY() const;
@@ -79,16 +76,14 @@
     Length intrinsicWidth(ConsiderCSSMode = RespectCSSProperties) const;
     Length intrinsicHeight(ConsiderCSSMode = RespectCSSProperties) const;
     FloatSize currentViewportSize() const;
-    SVGRect currentViewBoxRect() const;
+    FloatRect currentViewBoxRect() const;
 
     float currentScale() const;
     void setCurrentScale(float scale);
 
-    SVGPoint& currentTranslate() { return m_translation; }
+    FloatPoint currentTranslate() { return m_translation->value(); }
     void setCurrentTranslate(const FloatPoint&);
-
-    // Only used from the bindings.
-    void updateCurrentTranslate();
+    PassRefPtr<SVGPointTearOff> currentTranslateFromJavascript();
 
     SMILTimeContainer* timeContainer() const { return m_timeContainer.get(); }
 
@@ -99,23 +94,24 @@
     float getCurrentTime() const;
     void setCurrentTime(float seconds);
 
-    unsigned suspendRedraw(unsigned maxWaitMilliseconds);
-    void unsuspendRedraw(unsigned suspendHandleId);
-    void unsuspendRedrawAll();
-    void forceRedraw();
+    // Stubs for the deprecated 'redraw' interface.
+    unsigned suspendRedraw(unsigned) { return 1; }
+    void unsuspendRedraw(unsigned) { }
+    void unsuspendRedrawAll() { }
+    void forceRedraw() { }
 
-    PassRefPtr<NodeList> getIntersectionList(const SVGRect&, SVGElement* referenceElement) const;
-    PassRefPtr<NodeList> getEnclosureList(const SVGRect&, SVGElement* referenceElement) const;
-    bool checkIntersection(SVGElement*, const SVGRect&) const;
-    bool checkEnclosure(SVGElement*, const SVGRect&) const;
+    PassRefPtr<NodeList> getIntersectionList(PassRefPtr<SVGRectTearOff>, SVGElement* referenceElement) const;
+    PassRefPtr<NodeList> getEnclosureList(PassRefPtr<SVGRectTearOff>, SVGElement* referenceElement) const;
+    bool checkIntersection(SVGElement*, PassRefPtr<SVGRectTearOff>) const;
+    bool checkEnclosure(SVGElement*, PassRefPtr<SVGRectTearOff>) const;
     void deselectAll();
 
-    static float createSVGNumber();
-    static SVGLength createSVGLength();
+    static PassRefPtr<SVGNumberTearOff> createSVGNumber();
+    static PassRefPtr<SVGLengthTearOff> createSVGLength();
     static SVGAngle createSVGAngle();
-    static SVGPoint createSVGPoint();
+    static PassRefPtr<SVGPointTearOff> createSVGPoint();
     static SVGMatrix createSVGMatrix();
-    static SVGRect createSVGRect();
+    static PassRefPtr<SVGRectTearOff> createSVGRect();
     static SVGTransform createSVGTransform();
     static SVGTransform createSVGTransformFromMatrix(const SVGMatrix&);
 
@@ -128,10 +124,10 @@
     bool widthAttributeEstablishesViewport() const;
     bool heightAttributeEstablishesViewport() const;
 
-    SVGZoomAndPanType zoomAndPan() const { return m_zoomAndPan; }
-    void setZoomAndPan(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
-
-    bool hasEmptyViewBox() const { return viewBoxCurrentValue().isValid() && viewBoxCurrentValue().isEmpty(); }
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
+    SVGAnimatedLength* width() const { return m_width.get(); }
+    SVGAnimatedLength* height() const { return m_height.get(); }
 
 private:
     explicit SVGSVGElement(Document&);
@@ -142,42 +138,41 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
     void inheritViewAttributes(SVGViewElement*);
 
+    void updateCurrentTranslate();
+
     enum CollectIntersectionOrEnclosure {
         CollectIntersectionList,
         CollectEnclosureList
     };
 
-    PassRefPtr<NodeList> collectIntersectionOrEnclosureList(const SVGRect&, SVGElement*, CollectIntersectionOrEnclosure) const;
+    PassRefPtr<NodeList> collectIntersectionOrEnclosureList(const FloatRect&, SVGElement*, CollectIntersectionOrEnclosure) const;
 
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
+    RefPtr<SVGAnimatedLength> m_width;
+    RefPtr<SVGAnimatedLength> m_height;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGSVGElement)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_LENGTH(Width, width)
-        DECLARE_ANIMATED_LENGTH(Height, height)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
-        DECLARE_ANIMATED_RECT(ViewBox, viewBox)
-        DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const;
+    virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const OVERRIDE;
 
     bool m_useCurrentView;
-    SVGZoomAndPanType m_zoomAndPan;
     RefPtr<SMILTimeContainer> m_timeContainer;
-    SVGPoint m_translation;
+    RefPtr<SVGPoint> m_translation;
     RefPtr<SVGViewSpec> m_viewSpec;
-    WeakPtrFactory<SVGSVGElement> m_weakFactory;
+
+    friend class SVGCurrentTranslateTearOff;
 };
 
 inline bool isSVGSVGElement(const Node& node)
diff --git a/Source/core/svg/SVGSVGElement.idl b/Source/core/svg/SVGSVGElement.idl
index 0edfc9a..d05aec3 100644
--- a/Source/core/svg/SVGSVGElement.idl
+++ b/Source/core/svg/SVGSVGElement.idl
@@ -22,7 +22,9 @@
 
 // TODO: no css::ViewCSS available!
 // TODO: no events::DocumentEvent available!
-interface SVGSVGElement : SVGGraphicsElement {
+[
+    StrictTypeChecking,
+] interface SVGSVGElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedLength x;
     readonly attribute SVGAnimatedLength y;
     readonly attribute SVGAnimatedLength width;
@@ -37,25 +39,21 @@
     readonly attribute boolean useCurrentView;
     readonly attribute SVGViewSpec currentView;
              attribute float currentScale;
-    readonly attribute SVGPoint currentTranslate;
+    [ImplementedAs=currentTranslateFromJavascript] readonly attribute SVGPoint currentTranslate;
 
-    unsigned long suspendRedraw([Default=Undefined] optional unsigned long maxWaitMilliseconds);
-    void unsuspendRedraw([Default=Undefined] optional unsigned long suspendHandleId);
+    unsigned long suspendRedraw(unsigned long maxWaitMilliseconds);
+    void unsuspendRedraw(unsigned long suspendHandleId);
     void unsuspendRedrawAll();
     void forceRedraw();
     void pauseAnimations();
     void unpauseAnimations();
     boolean animationsPaused();
     float getCurrentTime();
-    void setCurrentTime([Default=Undefined] optional float seconds);
-    NodeList getIntersectionList([Default=Undefined] optional SVGRect rect,
-                                 [Default=Undefined] optional SVGElement referenceElement);
-    NodeList getEnclosureList([Default=Undefined] optional SVGRect rect,
-                              [Default=Undefined] optional SVGElement referenceElement);
-    boolean checkIntersection([Default=Undefined] optional SVGElement element,
-                              [Default=Undefined] optional SVGRect rect);
-    boolean checkEnclosure([Default=Undefined] optional SVGElement element,
-                           [Default=Undefined] optional SVGRect rect);
+    void setCurrentTime(float seconds);
+    NodeList getIntersectionList(SVGRect rect, SVGElement? referenceElement);
+    NodeList getEnclosureList(SVGRect rect, SVGElement? referenceElement);
+    boolean checkIntersection(SVGElement element, SVGRect rect);
+    boolean checkEnclosure(SVGElement element, SVGRect rect);
     void deselectAll();
 
     SVGNumber createSVGNumber();
@@ -65,11 +63,9 @@
     SVGMatrix createSVGMatrix();
     SVGRect createSVGRect();
     SVGTransform createSVGTransform();
-    SVGTransform createSVGTransformFromMatrix([Default=Undefined] optional SVGMatrix matrix);
-    Element getElementById([Default=Undefined] optional DOMString elementId);
+    SVGTransform createSVGTransformFromMatrix(SVGMatrix matrix);
+    Element getElementById(DOMString elementId);
 };
 
-SVGSVGElement implements SVGExternalResourcesRequired;
 SVGSVGElement implements SVGFitToViewBox;
 SVGSVGElement implements SVGZoomAndPan;
-
diff --git a/Source/core/svg/SVGScriptElement.cpp b/Source/core/svg/SVGScriptElement.cpp
index 9a7040f..5d121fa 100644
--- a/Source/core/svg/SVGScriptElement.cpp
+++ b/Source/core/svg/SVGScriptElement.cpp
@@ -35,16 +35,13 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_STRING(SVGScriptElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGScriptElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGScriptElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGScriptElement::SVGScriptElement(Document& document, bool wasInsertedByParser, bool alreadyStarted)
     : SVGElement(SVGNames::scriptTag, document)
+    , SVGURIReference(this)
     , m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
     , m_loader(ScriptLoader::create(this, wasInsertedByParser, alreadyStarted))
 {
@@ -62,7 +59,6 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGURIReference::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::typeAttr);
         supportedAttributes.add(HTMLNames::onerrorAttr);
     }
@@ -76,22 +72,18 @@
         return;
     }
 
-    if (name == SVGNames::typeAttr) {
-        setType(value);
+    SVGParsingError parseError = NoError;
+    if (name == SVGNames::typeAttr)
         return;
-    }
 
     if (name == HTMLNames::onerrorAttr) {
         setAttributeEventListener(EventTypeNames::error, createAttributeEventListener(this, name, value));
-        return;
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else {
+        ASSERT_NOT_REACHED();
     }
 
-    if (SVGURIReference::parseAttribute(name, value))
-        return;
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGScriptElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -107,13 +99,10 @@
         return;
 
     if (SVGURIReference::isKnownAttribute(attrName)) {
-        m_loader->handleSourceAttribute(hrefCurrentValue());
+        m_loader->handleSourceAttribute(hrefString());
         return;
     }
 
-    if (SVGExternalResourcesRequired::handleAttributeChange(this, attrName))
-        return;
-
     ASSERT_NOT_REACHED();
 }
 
@@ -126,7 +115,11 @@
 void SVGScriptElement::didNotifySubtreeInsertionsToDocument()
 {
     m_loader->didNotifySubtreeInsertionsToDocument();
-    SVGExternalResourcesRequired::insertedIntoDocument(this);
+
+    if (!m_loader->isParserInserted()) {
+        m_loader->setHaveFiredLoadEvent(true);
+        sendSVGLoadEventIfPossibleAsynchronously();
+    }
 }
 
 void SVGScriptElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -137,35 +130,23 @@
 
 bool SVGScriptElement::isURLAttribute(const Attribute& attribute) const
 {
-    return attribute.name() == sourceAttributeValue();
+    return attribute.name() == AtomicString(sourceAttributeValue());
 }
 
 void SVGScriptElement::finishParsingChildren()
 {
     SVGElement::finishParsingChildren();
-    SVGExternalResourcesRequired::finishParsingChildren();
+    m_loader->setHaveFiredLoadEvent(true);
 }
 
-String SVGScriptElement::type() const
+bool SVGScriptElement::haveLoadedRequiredResources()
 {
-    return m_type;
-}
-
-void SVGScriptElement::setType(const String& type)
-{
-    m_type = type;
-}
-
-void SVGScriptElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    SVGElement::addSubresourceAttributeURLs(urls);
-
-    addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
+    return m_loader->haveFiredLoadEvent();
 }
 
 String SVGScriptElement::sourceAttributeValue() const
 {
-    return hrefCurrentValue();
+    return hrefString();
 }
 
 String SVGScriptElement::charsetAttributeValue() const
@@ -175,7 +156,7 @@
 
 String SVGScriptElement::typeAttributeValue() const
 {
-    return type();
+    return getAttribute(SVGNames::typeAttr).string();
 }
 
 String SVGScriptElement::languageAttributeValue() const
@@ -205,7 +186,7 @@
 
 bool SVGScriptElement::hasSourceAttribute() const
 {
-    return hasAttribute(XLinkNames::hrefAttr);
+    return href()->isSpecified();
 }
 
 PassRefPtr<Element> SVGScriptElement::cloneElementWithoutAttributesAndChildren()
@@ -213,24 +194,19 @@
     return adoptRef(new SVGScriptElement(document(), false, m_loader->alreadyStarted()));
 }
 
-void SVGScriptElement::setHaveFiredLoadEvent(bool haveFiredLoadEvent)
+void SVGScriptElement::dispatchLoadEvent()
 {
-    m_loader->setHaveFiredLoadEvent(haveFiredLoadEvent);
+    dispatchEvent(Event::create(EventTypeNames::load));
 }
 
-bool SVGScriptElement::isParserInserted() const
+#ifndef NDEBUG
+bool SVGScriptElement::isAnimatableAttribute(const QualifiedName& name) const
 {
-    return m_loader->isParserInserted();
-}
+    if (name == SVGNames::typeAttr)
+        return false;
 
-bool SVGScriptElement::haveFiredLoadEvent() const
-{
-    return m_loader->haveFiredLoadEvent();
+    return SVGElement::isAnimatableAttribute(name);
 }
-
-Timer<SVGElement>* SVGScriptElement::svgLoadEventTimer()
-{
-    return &m_svgLoadEventTimer;
-}
+#endif
 
 }
diff --git a/Source/core/svg/SVGScriptElement.h b/Source/core/svg/SVGScriptElement.h
index ec59d85..b11f5be 100644
--- a/Source/core/svg/SVGScriptElement.h
+++ b/Source/core/svg/SVGScriptElement.h
@@ -26,7 +26,6 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedString.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGURIReference.h"
 
 namespace WebCore {
@@ -36,7 +35,6 @@
 class SVGScriptElement FINAL
     : public SVGElement
     , public SVGURIReference
-    , public SVGExternalResourcesRequired
     , public ScriptLoaderClient {
 public:
     static PassRefPtr<SVGScriptElement> create(Document&, bool wasInsertedByParser);
@@ -46,6 +44,10 @@
 
     ScriptLoader* loader() const { return m_loader.get(); }
 
+#ifndef NDEBUG
+    virtual bool isAnimatableAttribute(const QualifiedName&) const OVERRIDE;
+#endif
+
 private:
     SVGScriptElement(Document&, bool wasInsertedByParser, bool alreadyStarted);
 
@@ -53,43 +55,35 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
-    virtual void finishParsingChildren();
+    virtual bool isStructurallyExternal() const OVERRIDE { return hasSourceAttribute(); }
+    virtual void finishParsingChildren() OVERRIDE;
 
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
+    virtual bool haveLoadedRequiredResources() OVERRIDE;
 
-    virtual bool haveLoadedRequiredResources() { return SVGExternalResourcesRequired::haveLoadedRequiredResources(); }
+    virtual String sourceAttributeValue() const OVERRIDE;
+    virtual String charsetAttributeValue() const OVERRIDE;
+    virtual String typeAttributeValue() const OVERRIDE;
+    virtual String languageAttributeValue() const OVERRIDE;
+    virtual String forAttributeValue() const OVERRIDE;
+    virtual String eventAttributeValue() const OVERRIDE;
+    virtual bool asyncAttributeValue() const OVERRIDE;
+    virtual bool deferAttributeValue() const OVERRIDE;
+    virtual bool hasSourceAttribute() const OVERRIDE;
 
-    virtual String sourceAttributeValue() const;
-    virtual String charsetAttributeValue() const;
-    virtual String typeAttributeValue() const;
-    virtual String languageAttributeValue() const;
-    virtual String forAttributeValue() const;
-    virtual String eventAttributeValue() const;
-    virtual bool asyncAttributeValue() const;
-    virtual bool deferAttributeValue() const;
-    virtual bool hasSourceAttribute() const;
+    virtual void dispatchLoadEvent() OVERRIDE;
 
-    virtual void dispatchLoadEvent() { SVGExternalResourcesRequired::dispatchLoadEvent(this); }
-
-    virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren();
+    virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren() OVERRIDE;
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
-    // SVGExternalResourcesRequired
-    virtual void setHaveFiredLoadEvent(bool) OVERRIDE;
-    virtual bool isParserInserted() const OVERRIDE;
-    virtual bool haveFiredLoadEvent() const OVERRIDE;
-    virtual Timer<SVGElement>* svgLoadEventTimer() OVERRIDE;
+    virtual Timer<SVGElement>* svgLoadEventTimer() OVERRIDE { return &m_svgLoadEventTimer; }
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGScriptElement)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    String m_type;
     Timer<SVGElement> m_svgLoadEventTimer;
     OwnPtr<ScriptLoader> m_loader;
 };
diff --git a/Source/core/svg/SVGScriptElement.idl b/Source/core/svg/SVGScriptElement.idl
index abaa80b..08c871f 100644
--- a/Source/core/svg/SVGScriptElement.idl
+++ b/Source/core/svg/SVGScriptElement.idl
@@ -24,9 +24,7 @@
  */
 
 interface SVGScriptElement : SVGElement {
-             [TreatNullAs=NullString] attribute DOMString type;
+    [Reflect] attribute DOMString type;
 };
 
-SVGScriptElement implements SVGExternalResourcesRequired;
 SVGScriptElement implements SVGURIReference;
-
diff --git a/Source/core/svg/SVGStaticStringList.cpp b/Source/core/svg/SVGStaticStringList.cpp
new file mode 100644
index 0000000..7a2697e
--- /dev/null
+++ b/Source/core/svg/SVGStaticStringList.cpp
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/svg/SVGStaticStringList.h"
+
+namespace WebCore {
+
+SVGStaticStringList::SVGStaticStringList(SVGElement* contextElement, const QualifiedName& attributeName)
+    : NewSVGAnimatedPropertyBase(AnimatedStringList, contextElement, attributeName)
+    , m_value(SVGStringList::create())
+{
+    ASSERT(contextElement);
+}
+
+SVGStaticStringList::~SVGStaticStringList()
+{
+}
+
+NewSVGPropertyBase* SVGStaticStringList::currentValueBase()
+{
+    return m_value.get();
+}
+
+void SVGStaticStringList::animationStarted()
+{
+    ASSERT_NOT_REACHED();
+}
+
+PassRefPtr<NewSVGPropertyBase> SVGStaticStringList::createAnimatedValue()
+{
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
+void SVGStaticStringList::setAnimatedValue(PassRefPtr<NewSVGPropertyBase>)
+{
+    ASSERT_NOT_REACHED();
+}
+
+void SVGStaticStringList::animationEnded()
+{
+    ASSERT_NOT_REACHED();
+}
+
+void SVGStaticStringList::animValWillChange()
+{
+    ASSERT_NOT_REACHED();
+}
+
+void SVGStaticStringList::animValDidChange()
+{
+    ASSERT_NOT_REACHED();
+}
+
+bool SVGStaticStringList::needsSynchronizeAttribute()
+{
+    return m_tearOff;
+}
+
+SVGStringListTearOff* SVGStaticStringList::tearOff()
+{
+    if (!m_tearOff)
+        m_tearOff = SVGStringListTearOff::create(m_value, contextElement(), PropertyIsNotAnimVal, attributeName());
+
+    return m_tearOff.get();
+}
+
+void SVGStaticStringList::setBaseValueAsString(const String& value, SVGParsingError& parseError)
+{
+    TrackExceptionState es;
+
+    m_value->setValueAsString(value, es);
+
+    if (es.hadException())
+        parseError = ParsingAttributeFailedError;
+}
+
+}
diff --git a/Source/core/svg/SVGStaticStringList.h b/Source/core/svg/SVGStaticStringList.h
new file mode 100644
index 0000000..e45cb9e
--- /dev/null
+++ b/Source/core/svg/SVGStaticStringList.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGStaticStringList_h
+#define SVGStaticStringList_h
+
+#include "core/svg/SVGStringListTearOff.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
+
+namespace WebCore {
+
+class SVGElement;
+
+// SVGStringList property implementations for SVGTests properties.
+// Inherits SVGAnimatedPropertyBase to enable XML attribute synchronization, but this is never animated.
+class SVGStaticStringList FINAL : public NewSVGAnimatedPropertyBase {
+public:
+    static PassRefPtr<SVGStaticStringList> create(SVGElement* contextElement, const QualifiedName& attributeName)
+    {
+        return adoptRef(new SVGStaticStringList(contextElement, attributeName));
+    }
+
+    virtual ~SVGStaticStringList();
+
+    // NewSVGAnimatedPropertyBase:
+    virtual NewSVGPropertyBase* currentValueBase() OVERRIDE;
+    virtual void animationStarted() OVERRIDE;
+    virtual PassRefPtr<NewSVGPropertyBase> createAnimatedValue() OVERRIDE;
+    virtual void setAnimatedValue(PassRefPtr<NewSVGPropertyBase>) OVERRIDE;
+    virtual void animationEnded() OVERRIDE;
+    virtual void animValWillChange() OVERRIDE;
+    virtual void animValDidChange() OVERRIDE;
+    virtual bool needsSynchronizeAttribute() OVERRIDE;
+
+    void setBaseValueAsString(const String& value, SVGParsingError& parseError);
+
+    SVGStringList* value() { return m_value.get(); }
+    SVGStringListTearOff* tearOff();
+
+private:
+    SVGStaticStringList(SVGElement*, const QualifiedName&);
+
+    RefPtr<SVGStringList> m_value;
+    RefPtr<SVGStringListTearOff> m_tearOff;
+};
+
+}
+
+#endif
diff --git a/Source/core/svg/SVGStopElement.cpp b/Source/core/svg/SVGStopElement.cpp
index b3d8509..2421deb 100644
--- a/Source/core/svg/SVGStopElement.cpp
+++ b/Source/core/svg/SVGStopElement.cpp
@@ -29,18 +29,17 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_NUMBER(SVGStopElement, SVGNames::offsetAttr, Offset, offset)
-
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGStopElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(offset)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGStopElement::SVGStopElement(Document& document)
     : SVGElement(SVGNames::stopTag, document)
-    , m_offset(0)
+    , m_offset(SVGAnimatedNumber::create(this, SVGNames::offsetAttr, SVGNumberAcceptPercentage::create()))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_offset);
     registerAnimatedPropertiesForSVGStopElement();
 }
 
@@ -64,15 +63,14 @@
         return;
     }
 
-    if (name == SVGNames::offsetAttr) {
-        if (value.endsWith('%'))
-            setOffsetBaseValue(value.string().left(value.length() - 1).toFloat() / 100.0f);
-        else
-            setOffsetBaseValue(value.toFloat());
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    ASSERT_NOT_REACHED();
+    if (name == SVGNames::offsetAttr)
+        m_offset->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
+
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGStopElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -112,10 +110,10 @@
     // which the renderer or style is null. This entire class is scheduled for removal (Bug WK 86941)
     // and we will tolerate this null check until then.
     if (!style || !style->svgStyle())
-        return Color(Color::transparent, true); // Transparent black.
+        return Color(Color::transparent); // Transparent black.
 
     const SVGRenderStyle* svgStyle = style->svgStyle();
-    return colorWithOverrideAlpha(svgStyle->stopColor().rgb(), svgStyle->stopOpacity());
+    return svgStyle->stopColor().combineWithAlpha(svgStyle->stopOpacity());
 }
 
 }
diff --git a/Source/core/svg/SVGStopElement.h b/Source/core/svg/SVGStopElement.h
index 6b941f2..fcd5215 100644
--- a/Source/core/svg/SVGStopElement.h
+++ b/Source/core/svg/SVGStopElement.h
@@ -33,20 +33,22 @@
 
     Color stopColorIncludingOpacity() const;
 
+    SVGAnimatedNumber* offset() { return m_offset.get(); }
+
 private:
     explicit SVGStopElement(Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
     virtual bool isGradientStop() const OVERRIDE { return true; }
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
+    RefPtr<SVGAnimatedNumber> m_offset;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGStopElement)
-        DECLARE_ANIMATED_NUMBER(Offset, offset)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGString.cpp b/Source/core/svg/SVGString.cpp
new file mode 100644
index 0000000..59411b8
--- /dev/null
+++ b/Source/core/svg/SVGString.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/svg/SVGString.h"
+
+#include "core/svg/SVGAnimateElement.h"
+
+namespace WebCore {
+
+void SVGString::add(PassRefPtr<NewSVGPropertyBase>, SVGElement*)
+{
+    ASSERT_NOT_REACHED();
+}
+
+void SVGString::calculateAnimatedValue(SVGAnimationElement* animationElement, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase>, SVGElement*)
+{
+    ASSERT(animationElement);
+
+    String fromString = toSVGString(from)->m_value;
+    String toString = toSVGString(to)->m_value;
+
+    animationElement->animateDiscreteType<String>(percentage, fromString, toString, m_value);
+}
+
+float SVGString::calculateDistance(PassRefPtr<NewSVGPropertyBase>, SVGElement*)
+{
+    // No paced animations for strings.
+    return -1;
+}
+
+}
diff --git a/Source/core/svg/SVGString.h b/Source/core/svg/SVGString.h
new file mode 100644
index 0000000..31bc758
--- /dev/null
+++ b/Source/core/svg/SVGString.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGString_h
+#define SVGString_h
+
+#include "core/svg/properties/NewSVGProperty.h"
+
+namespace WebCore {
+
+class SVGString : public NewSVGPropertyBase {
+public:
+    // SVGString does not have a tear-off type.
+    typedef void TearOffType;
+    typedef String PrimitiveType;
+
+    static PassRefPtr<SVGString> create()
+    {
+        return adoptRef(new SVGString());
+    }
+
+    static PassRefPtr<SVGString> create(const String& value)
+    {
+        return adoptRef(new SVGString(value));
+    }
+
+    PassRefPtr<SVGString> clone() const { return create(m_value); }
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String& value) const OVERRIDE
+    {
+        return create(value);
+    }
+
+    virtual String valueAsString() const OVERRIDE { return m_value; }
+    void setValueAsString(const String& value, ExceptionState&) { m_value = value; }
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*) OVERRIDE;
+
+    const String& value() const { return m_value; }
+    void setValue(const String& value) { m_value = value; }
+
+    static AnimatedPropertyType classType() { return AnimatedString; }
+
+private:
+    SVGString()
+        : NewSVGPropertyBase(classType())
+    {
+    }
+
+    explicit SVGString(const String& value)
+        : NewSVGPropertyBase(classType())
+        , m_value(value)
+    {
+    }
+
+    String m_value;
+};
+
+inline PassRefPtr<SVGString> toSVGString(PassRefPtr<NewSVGPropertyBase> passBase)
+{
+    RefPtr<NewSVGPropertyBase> base = passBase;
+    ASSERT(base->type() == SVGString::classType());
+    return static_pointer_cast<SVGString>(base.release());
+}
+
+} // namespace WebCore
+
+#endif // SVGString_h
diff --git a/Source/core/svg/SVGStringList.cpp b/Source/core/svg/SVGStringList.cpp
index c8ff9df..7cb411e 100644
--- a/Source/core/svg/SVGStringList.cpp
+++ b/Source/core/svg/SVGStringList.cpp
@@ -27,66 +27,158 @@
 
 namespace WebCore {
 
-void SVGStringList::commitChange(SVGElement* contextElement)
+SVGStringList::SVGStringList()
+    : NewSVGPropertyBase(classType())
 {
-    ASSERT(contextElement);
-    contextElement->invalidateSVGAttributes();
-    contextElement->svgAttributeChanged(m_attributeName);
 }
 
-void SVGStringList::reset(const String& string)
+SVGStringList::~SVGStringList()
 {
-    parse(string, ' ');
+}
 
-    // Add empty string, if list is empty.
-    if (isEmpty())
-        append(emptyString());
+void SVGStringList::initialize(const String& item)
+{
+    m_values.clear();
+    m_values.append(item);
+}
+
+String SVGStringList::getItem(size_t index, ExceptionState& exceptionState)
+{
+    if (!checkIndexBound(index, exceptionState))
+        return String();
+
+    return m_values.at(index);
+}
+
+void SVGStringList::insertItemBefore(const String& newItem, size_t index)
+{
+    // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list.
+    if (index > m_values.size())
+        index = m_values.size();
+
+    // Spec: Inserts a new item into the list at the specified position. The index of the item before which the new item is to be
+    // inserted. The first item is number 0. If the index is equal to 0, then the new item is inserted at the front of the list.
+    m_values.insert(index, newItem);
+}
+
+String SVGStringList::removeItem(size_t index, ExceptionState& exceptionState)
+{
+    if (!checkIndexBound(index, exceptionState))
+        return String();
+
+    String oldItem = m_values.at(index);
+    m_values.remove(index);
+    return oldItem;
+}
+
+void SVGStringList::appendItem(const String& newItem)
+{
+    m_values.append(newItem);
+}
+
+void SVGStringList::replaceItem(const String& newItem, size_t index, ExceptionState& exceptionState)
+{
+    if (!checkIndexBound(index, exceptionState))
+        return;
+
+    // Update the value at the desired position 'index'.
+    m_values[index] = newItem;
 }
 
 template<typename CharType>
-void SVGStringList::parseInternal(const CharType*& ptr, const CharType* end, UChar delimiter)
+void SVGStringList::parseInternal(const CharType*& ptr, const CharType* end)
 {
+    const UChar delimiter = ' ';
+
     while (ptr < end) {
         const CharType* start = ptr;
         while (ptr < end && *ptr != delimiter && !isSVGSpace(*ptr))
             ptr++;
         if (ptr == start)
             break;
-        append(String(start, ptr - start));
+        m_values.append(String(start, ptr - start));
         skipOptionalSVGSpacesOrDelimiter(ptr, end, delimiter);
     }
 }
 
-void SVGStringList::parse(const String& data, UChar delimiter)
+PassRefPtr<SVGStringList> SVGStringList::clone()
+{
+    RefPtr<SVGStringList> svgStringList = create();
+    svgStringList->m_values = m_values;
+    return svgStringList.release();
+}
+
+void SVGStringList::setValueAsString(const String& data, ExceptionState&)
 {
     // FIXME: Add more error checking and reporting.
-    clear();
+    m_values.clear();
     if (data.isEmpty())
         return;
     if (data.is8Bit()) {
         const LChar* ptr = data.characters8();
         const LChar* end = ptr + data.length();
-        parseInternal(ptr, end, delimiter);
+        parseInternal(ptr, end);
     } else {
         const UChar* ptr = data.characters16();
         const UChar* end = ptr + data.length();
-        parseInternal(ptr, end, delimiter);
+        parseInternal(ptr, end);
     }
 }
 
+PassRefPtr<NewSVGPropertyBase> SVGStringList::cloneForAnimation(const String& string) const
+{
+    RefPtr<SVGStringList> svgStringList = create();
+    svgStringList->setValueAsString(string, IGNORE_EXCEPTION);
+    return svgStringList.release();
+}
+
 String SVGStringList::valueAsString() const
 {
     StringBuilder builder;
 
-    unsigned size = this->size();
-    for (unsigned i = 0; i < size; ++i) {
-        if (i > 0)
-            builder.append(' ');
+    Vector<String>::const_iterator it = m_values.begin();
+    Vector<String>::const_iterator itEnd = m_values.end();
+    if (it != itEnd) {
+        builder.append(*it);
+        ++it;
 
-        builder.append(at(i));
+        for (; it != itEnd; ++it) {
+            builder.append(' ');
+            builder.append(*it);
+        }
     }
 
     return builder.toString();
 }
 
+bool SVGStringList::checkIndexBound(size_t index, ExceptionState& exceptionState)
+{
+    if (index >= m_values.size()) {
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("index", index, m_values.size()));
+        return false;
+    }
+
+    return true;
+}
+
+void SVGStringList::add(PassRefPtr<NewSVGPropertyBase> other, SVGElement* contextElement)
+{
+    // SVGStringList is never animated.
+    ASSERT_NOT_REACHED();
+}
+
+void SVGStringList::calculateAnimatedValue(SVGAnimationElement*, float, unsigned, PassRefPtr<NewSVGPropertyBase>, PassRefPtr<NewSVGPropertyBase>, PassRefPtr<NewSVGPropertyBase>, SVGElement*)
+{
+    // SVGStringList is never animated.
+    ASSERT_NOT_REACHED();
+}
+
+float SVGStringList::calculateDistance(PassRefPtr<NewSVGPropertyBase>, SVGElement*)
+{
+    // SVGStringList is never animated.
+    ASSERT_NOT_REACHED();
+
+    return -1.0f;
+}
+
 }
diff --git a/Source/core/svg/SVGStringList.h b/Source/core/svg/SVGStringList.h
index 53e398e..946f571 100644
--- a/Source/core/svg/SVGStringList.h
+++ b/Source/core/svg/SVGStringList.h
@@ -1,61 +1,100 @@
 /*
- * Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
  *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
  */
 
 #ifndef SVGStringList_h
 #define SVGStringList_h
 
-#include "core/dom/QualifiedName.h"
-#include "core/svg/properties/SVGPropertyTraits.h"
-#include "wtf/Vector.h"
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/svg/SVGString.h"
+#include "core/svg/properties/NewSVGListPropertyHelper.h"
 
 namespace WebCore {
 
-class SVGElement;
+class SVGStringListTearOff;
 
-class SVGStringList : public Vector<String> {
+// Implementation of SVGStringList spec:
+// http://www.w3.org/TR/SVG/single-page.html#types-InterfaceSVGStringList
+// See SVGStringListTearOff for actual Javascript interface.
+// Unlike other SVG*List implementations, SVGStringList is NOT tied to SVGString.
+// SVGStringList operates directly on DOMString.
+//
+// In short:
+//   SVGStringList has_a Vector<String>.
+//   SVGStringList items are exposed to Javascript as DOMString (not SVGString) as in the spec.
+//   SVGString is used only for boxing values for non-list string property SVGAnimatedString,
+//   and not used for SVGStringList.
+class SVGStringList FINAL : public NewSVGPropertyBase {
 public:
-    SVGStringList(const QualifiedName& attributeName)
-        : m_attributeName(attributeName)
+    typedef SVGStringListTearOff TearOffType;
+
+    static PassRefPtr<SVGStringList> create()
     {
+        return adoptRef(new SVGStringList());
     }
 
-    void reset(const String&);
-    void parse(const String&, UChar delimiter = ',');
+    virtual ~SVGStringList();
 
-    // Only used by SVGStringListPropertyTearOff.
-    void commitChange(SVGElement* contextElement);
+    const Vector<String>& values() const { return m_values; }
 
-    String valueAsString() const;
+    // SVGStringList DOM Spec implementation. These are only to be called from SVGStringListTearOff:
+    unsigned long numberOfItems() { return m_values.size(); }
+    void clear() { m_values.clear(); }
+    void initialize(const String&);
+    String getItem(size_t, ExceptionState&);
+    void insertItemBefore(const String&, size_t);
+    String removeItem(size_t, ExceptionState&);
+    void appendItem(const String&);
+    void replaceItem(const String&, size_t, ExceptionState&);
+
+    // NewSVGPropertyBase:
+    PassRefPtr<SVGStringList> clone();
+    void setValueAsString(const String&, ExceptionState&);
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const OVERRIDE;
+    virtual String valueAsString() const OVERRIDE;
+
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) OVERRIDE;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> fromValue, PassRefPtr<NewSVGPropertyBase> toValue, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*) OVERRIDE;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*) OVERRIDE;
+
+    static AnimatedPropertyType classType() { return AnimatedStringList; }
 
 private:
-    template<typename CharType>
-    void parseInternal(const CharType*& ptr, const CharType* end, UChar delimiter);
+    SVGStringList();
 
-    const QualifiedName& m_attributeName;
-};
+    template <typename CharType>
+    void parseInternal(const CharType*& ptr, const CharType* end);
+    bool checkIndexBound(size_t, ExceptionState&);
 
-template<>
-struct SVGPropertyTraits<SVGStringList> {
-    typedef String ListItemType;
+    Vector<String> m_values;
 };
 
 } // namespace WebCore
 
-#endif
+#endif // SVGStringList_h
diff --git a/Source/core/svg/SVGStringList.idl b/Source/core/svg/SVGStringList.idl
index 020b754..0b5dc41 100644
--- a/Source/core/svg/SVGStringList.idl
+++ b/Source/core/svg/SVGStringList.idl
@@ -23,15 +23,19 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGStringList {
+[
+    StrictTypeChecking,
+    SetWrapperReferenceTo(SVGElement contextElement),
+    ImplementedAs=SVGStringListTearOff
+] interface SVGStringList {
     readonly attribute unsigned long numberOfItems;
 
     [RaisesException] void clear();
-    [StrictTypeChecking, RaisesException] DOMString initialize(DOMString item);
-    [StrictTypeChecking, RaisesException] DOMString getItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] DOMString insertItemBefore(DOMString item, unsigned long index);
-    [StrictTypeChecking, RaisesException] DOMString replaceItem(DOMString item, unsigned long index);
-    [StrictTypeChecking, RaisesException] DOMString removeItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] DOMString appendItem(DOMString item);
+    [RaisesException] DOMString initialize(DOMString item);
+    [RaisesException] DOMString getItem(unsigned long index);
+    [RaisesException] DOMString insertItemBefore(DOMString item, unsigned long index);
+    [RaisesException] DOMString replaceItem(DOMString item, unsigned long index);
+    [RaisesException] DOMString removeItem(unsigned long index);
+    [RaisesException] DOMString appendItem(DOMString item);
 };
 
diff --git a/Source/core/rendering/LayoutIndicator.cpp b/Source/core/svg/SVGStringListTearOff.cpp
similarity index 78%
copy from Source/core/rendering/LayoutIndicator.cpp
copy to Source/core/svg/SVGStringListTearOff.cpp
index a57c53c..77c9753 100644
--- a/Source/core/rendering/LayoutIndicator.cpp
+++ b/Source/core/svg/SVGStringListTearOff.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2014 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,14 +29,14 @@
  */
 
 #include "config.h"
-#include "core/rendering/LayoutIndicator.h"
+#include "core/svg/SVGStringListTearOff.h"
 
 namespace WebCore {
 
-#ifndef NDEBUG
-
-size_t LayoutIndicator::s_inLayout = 0;
-
-#endif
+SVGStringListTearOff::SVGStringListTearOff(PassRefPtr<SVGStringList> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName)
+    : NewSVGPropertyTearOff<SVGStringList>(target, contextElement, propertyIsAnimVal, attributeName)
+{
+    ScriptWrappable::init(this);
+}
 
 }
diff --git a/Source/core/svg/SVGStringListTearOff.h b/Source/core/svg/SVGStringListTearOff.h
new file mode 100644
index 0000000..3e16f5c
--- /dev/null
+++ b/Source/core/svg/SVGStringListTearOff.h
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2014 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef SVGStringListTearOff_h
+#define SVGStringListTearOff_h
+
+#include "core/svg/SVGStringList.h"
+#include "core/svg/properties/NewSVGPropertyTearOff.h"
+
+namespace WebCore {
+
+class SVGStringListTearOff : public NewSVGPropertyTearOff<SVGStringList>, public ScriptWrappable {
+public:
+    static PassRefPtr<SVGStringListTearOff> create(PassRefPtr<SVGStringList> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+    {
+        return adoptRef(new SVGStringListTearOff(target, contextElement, propertyIsAnimVal, attributeName));
+    }
+
+    // SVGStringList DOM interface:
+
+    // WebIDL requires "unsigned long" type instead of size_t.
+    unsigned long numberOfItems()
+    {
+        return target()->numberOfItems();
+    }
+
+    void clear(ExceptionState& exceptionState)
+    {
+        if (isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return;
+        }
+
+        target()->clear();
+        commitChange();
+    }
+
+    String initialize(const String& item, ExceptionState& exceptionState)
+    {
+        if (isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return String();
+        }
+
+        target()->initialize(item);
+        commitChange();
+
+        return item;
+    }
+
+    String getItem(unsigned long index, ExceptionState& exceptionState)
+    {
+        return target()->getItem(index, exceptionState);
+    }
+
+    String insertItemBefore(const String& item, unsigned long index, ExceptionState& exceptionState)
+    {
+        if (isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return String();
+        }
+
+        target()->insertItemBefore(item, index);
+        commitChange();
+
+        return item;
+    }
+
+    String replaceItem(const String& item, unsigned long index, ExceptionState& exceptionState)
+    {
+        if (isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return String();
+        }
+
+        target()->replaceItem(item, index, exceptionState);
+        commitChange();
+
+        return item;
+    }
+
+    String removeItem(unsigned long index, ExceptionState& exceptionState)
+    {
+        if (isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return String();
+        }
+
+        String removedItem = target()->removeItem(index, exceptionState);
+        commitChange();
+
+        return removedItem;
+    }
+
+    String appendItem(const String& item, ExceptionState& exceptionState)
+    {
+        if (isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return String();
+        }
+
+        target()->appendItem(item);
+        commitChange();
+
+        return item;
+    }
+
+protected:
+    SVGStringListTearOff(PassRefPtr<SVGStringList>, SVGElement*, PropertyIsAnimValType, const QualifiedName&);
+};
+
+} // namespace WebCore
+
+#endif // SVGStringListTearOff_h_
diff --git a/Source/core/svg/SVGStyleElement.h b/Source/core/svg/SVGStyleElement.h
index 522f0af..6aeed2f 100644
--- a/Source/core/svg/SVGStyleElement.h
+++ b/Source/core/svg/SVGStyleElement.h
@@ -38,13 +38,13 @@
     bool disabled() const;
     void setDisabled(bool);
 
-    virtual const AtomicString& type() const;
+    virtual const AtomicString& type() const OVERRIDE;
     void setType(const AtomicString&);
 
-    virtual const AtomicString& media() const;
+    virtual const AtomicString& media() const OVERRIDE;
     void setMedia(const AtomicString&);
 
-    virtual String title() const;
+    virtual String title() const OVERRIDE;
     void setTitle(const AtomicString&);
 
 private:
@@ -55,14 +55,13 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual void finishParsingChildren();
+    virtual void finishParsingChildren() OVERRIDE;
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
-    virtual bool isLoading() const { return StyleElement::isLoading(); }
-    virtual bool sheetLoaded() { return StyleElement::sheetLoaded(document()); }
-    virtual void startLoadingDynamicSheet() { StyleElement::startLoadingDynamicSheet(document()); }
+    virtual bool sheetLoaded() OVERRIDE { return StyleElement::sheetLoaded(document()); }
+    virtual void startLoadingDynamicSheet() OVERRIDE { StyleElement::startLoadingDynamicSheet(document()); }
     virtual Timer<SVGElement>* svgLoadEventTimer() OVERRIDE { return &m_svgLoadEventTimer; }
 
     Timer<SVGElement> m_svgLoadEventTimer;
diff --git a/Source/core/svg/SVGSwitchElement.cpp b/Source/core/svg/SVGSwitchElement.cpp
index b4719ce..539ef59 100644
--- a/Source/core/svg/SVGSwitchElement.cpp
+++ b/Source/core/svg/SVGSwitchElement.cpp
@@ -29,10 +29,8 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_BOOLEAN(SVGSwitchElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGSwitchElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
@@ -50,24 +48,6 @@
     return adoptRef(new SVGSwitchElement(document));
 }
 
-bool SVGSwitchElement::childShouldCreateRenderer(const Node& child) const
-{
-    // FIXME: This function does not do what the comment below implies it does.
-    // It will create a renderer for any valid SVG element children, not just the first one.
-    for (Node* node = firstChild(); node; node = node->nextSibling()) {
-        if (!node->isSVGElement())
-            continue;
-
-        SVGElement* element = toSVGElement(node);
-        if (!element || !element->isValid())
-            continue;
-
-        return node == &child; // Only allow this child if it's the first valid child
-    }
-
-    return false;
-}
-
 RenderObject* SVGSwitchElement::createRenderer(RenderStyle*)
 {
     return new RenderSVGTransformableContainer(this);
diff --git a/Source/core/svg/SVGSwitchElement.h b/Source/core/svg/SVGSwitchElement.h
index 48312ea..89cc2eb 100644
--- a/Source/core/svg/SVGSwitchElement.h
+++ b/Source/core/svg/SVGSwitchElement.h
@@ -22,28 +22,22 @@
 #define SVGSwitchElement_h
 
 #include "core/svg/SVGAnimatedBoolean.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGSwitchElement FINAL : public SVGGraphicsElement,
-                               public SVGExternalResourcesRequired {
+class SVGSwitchElement FINAL : public SVGGraphicsElement {
 public:
     static PassRefPtr<SVGSwitchElement> create(Document&);
 
 private:
     explicit SVGSwitchElement(Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
-    virtual bool childShouldCreateRenderer(const Node& child) const;
-
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGSwitchElement)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGSwitchElement.idl b/Source/core/svg/SVGSwitchElement.idl
index 619855a..28d43b6 100644
--- a/Source/core/svg/SVGSwitchElement.idl
+++ b/Source/core/svg/SVGSwitchElement.idl
@@ -25,6 +25,3 @@
 
 interface SVGSwitchElement : SVGGraphicsElement {
 };
-
-SVGSwitchElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGSymbolElement.cpp b/Source/core/svg/SVGSymbolElement.cpp
index b9a405a..4035b25 100644
--- a/Source/core/svg/SVGSymbolElement.cpp
+++ b/Source/core/svg/SVGSymbolElement.cpp
@@ -29,21 +29,17 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_BOOLEAN(SVGSymbolElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-DEFINE_ANIMATED_PRESERVEASPECTRATIO(SVGSymbolElement, SVGNames::preserveAspectRatioAttr, PreserveAspectRatio, preserveAspectRatio)
-DEFINE_ANIMATED_RECT(SVGSymbolElement, SVGNames::viewBoxAttr, ViewBox, viewBox)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGSymbolElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(viewBox)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAspectRatio)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGSymbolElement::SVGSymbolElement(Document& document)
     : SVGElement(SVGNames::symbolTag, document)
+    , SVGFitToViewBox(this)
 {
     ScriptWrappable::init(this);
+
     registerAnimatedPropertiesForSVGSymbolElement();
 }
 
@@ -55,10 +51,9 @@
 bool SVGSymbolElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
-    if (supportedAttributes.isEmpty()) {
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
+    if (supportedAttributes.isEmpty())
         SVGFitToViewBox::addSupportedAttributes(supportedAttributes);
-    }
+
     return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
@@ -69,12 +64,13 @@
         return;
     }
 
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
-    if (SVGFitToViewBox::parseAttribute(this, name, value))
-        return;
+    SVGParsingError parseError = NoError;
+    if (SVGFitToViewBox::parseAttribute(name, value, document(), parseError)) {
+    } else {
+        ASSERT_NOT_REACHED();
+    }
 
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGSymbolElement::svgAttributeChanged(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGSymbolElement.h b/Source/core/svg/SVGSymbolElement.h
index d65a0da..5cebf40 100644
--- a/Source/core/svg/SVGSymbolElement.h
+++ b/Source/core/svg/SVGSymbolElement.h
@@ -22,16 +22,12 @@
 #define SVGSymbolElement_h
 
 #include "core/svg/SVGAnimatedBoolean.h"
-#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
-#include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFitToViewBox.h"
 
 namespace WebCore {
 
 class SVGSymbolElement FINAL : public SVGElement,
-                               public SVGExternalResourcesRequired,
                                public SVGFitToViewBox {
 public:
     static PassRefPtr<SVGSymbolElement> create(Document&);
@@ -43,16 +39,13 @@
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGSymbolElement)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
-        DECLARE_ANIMATED_RECT(ViewBox, viewBox)
-        DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGSymbolElement.idl b/Source/core/svg/SVGSymbolElement.idl
index aeb7d80..0d2ecae 100644
--- a/Source/core/svg/SVGSymbolElement.idl
+++ b/Source/core/svg/SVGSymbolElement.idl
@@ -26,5 +26,4 @@
 interface SVGSymbolElement : SVGElement {
 };
 
-SVGSymbolElement implements SVGExternalResourcesRequired;
 SVGSymbolElement implements SVGFitToViewBox;
diff --git a/Source/core/svg/SVGTSpanElement.cpp b/Source/core/svg/SVGTSpanElement.cpp
index 77f13fc..9aa1a93 100644
--- a/Source/core/svg/SVGTSpanElement.cpp
+++ b/Source/core/svg/SVGTSpanElement.cpp
@@ -43,19 +43,6 @@
     return new RenderSVGTSpan(this);
 }
 
-bool SVGTSpanElement::childShouldCreateRenderer(const Node& child) const
-{
-    if (child.isTextNode()
-        || child.hasTagName(SVGNames::aTag)
-#if ENABLE(SVG_FONTS)
-        || child.hasTagName(SVGNames::altGlyphTag)
-#endif
-        || child.hasTagName(SVGNames::tspanTag))
-        return true;
-
-    return false;
-}
-
 bool SVGTSpanElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (parentNode()
diff --git a/Source/core/svg/SVGTSpanElement.h b/Source/core/svg/SVGTSpanElement.h
index 547e9ee..7c6f41c 100644
--- a/Source/core/svg/SVGTSpanElement.h
+++ b/Source/core/svg/SVGTSpanElement.h
@@ -32,9 +32,8 @@
 private:
     explicit SVGTSpanElement(Document&);
 
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const Node& child) const;
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGTagNames.in b/Source/core/svg/SVGTagNames.in
index caf925d..db346cf 100644
--- a/Source/core/svg/SVGTagNames.in
+++ b/Source/core/svg/SVGTagNames.in
@@ -10,7 +10,7 @@
 altGlyphItem
 #endif
 animate
-animateColor
+animateColor interfaceName=SVGUnknownElement, JSInterfaceName=SVGElement, noConstructor
 animateMotion
 animateTransform
 set
@@ -20,6 +20,7 @@
 cursor
 defs
 desc
+discard
 ellipse
 feBlend
 feColorMatrix
diff --git a/Source/core/svg/SVGTests.cpp b/Source/core/svg/SVGTests.cpp
index 1332610..b555983 100644
--- a/Source/core/svg/SVGTests.cpp
+++ b/Source/core/svg/SVGTests.cpp
@@ -29,70 +29,19 @@
 
 namespace WebCore {
 
-// Define custom non-animated property 'requiredFeatures'.
-const SVGPropertyInfo* SVGTests::requiredFeaturesPropertyInfo()
+SVGTests::SVGTests(SVGElement* contextElement)
+    : m_requiredFeatures(SVGStaticStringList::create(contextElement, SVGNames::requiredFeaturesAttr))
+    , m_requiredExtensions(SVGStaticStringList::create(contextElement, SVGNames::requiredExtensionsAttr))
+    , m_systemLanguage(SVGStaticStringList::create(contextElement, SVGNames::systemLanguageAttr))
 {
-    static const SVGPropertyInfo* s_propertyInfo = 0;
-    if (!s_propertyInfo) {
-        s_propertyInfo = new SVGPropertyInfo(AnimatedUnknown,
-                                             PropertyIsReadWrite,
-                                             SVGNames::requiredFeaturesAttr,
-                                             SVGNames::requiredFeaturesAttr.localName(),
-                                             &SVGElement::synchronizeRequiredFeatures,
-                                             0);
-    }
-    return s_propertyInfo;
+    ASSERT(contextElement);
+
+    contextElement->addToPropertyMap(m_requiredFeatures);
+    contextElement->addToPropertyMap(m_requiredExtensions);
+    contextElement->addToPropertyMap(m_systemLanguage);
 }
 
-// Define custom non-animated property 'requiredExtensions'.
-const SVGPropertyInfo* SVGTests::requiredExtensionsPropertyInfo()
-{
-    static const SVGPropertyInfo* s_propertyInfo = 0;
-    if (!s_propertyInfo) {
-        s_propertyInfo = new SVGPropertyInfo(AnimatedUnknown,
-                                             PropertyIsReadWrite,
-                                             SVGNames::requiredExtensionsAttr,
-                                             SVGNames::requiredExtensionsAttr.localName(),
-                                             &SVGElement::synchronizeRequiredExtensions,
-                                             0);
-    }
-    return s_propertyInfo;
-}
-
-// Define custom non-animated property 'systemLanguage'.
-const SVGPropertyInfo* SVGTests::systemLanguagePropertyInfo()
-{
-    static const SVGPropertyInfo* s_propertyInfo = 0;
-    if (!s_propertyInfo) {
-        s_propertyInfo = new SVGPropertyInfo(AnimatedUnknown,
-                                             PropertyIsReadWrite,
-                                             SVGNames::systemLanguageAttr,
-                                             SVGNames::systemLanguageAttr.localName(),
-                                             &SVGElement::synchronizeSystemLanguage,
-                                             0);
-    }
-    return s_propertyInfo;
-}
-
-SVGTests::SVGTests()
-    : m_requiredFeatures(SVGNames::requiredFeaturesAttr)
-    , m_requiredExtensions(SVGNames::requiredExtensionsAttr)
-    , m_systemLanguage(SVGNames::systemLanguageAttr)
-{
-}
-
-SVGAttributeToPropertyMap& SVGTests::attributeToPropertyMap()
-{
-    DEFINE_STATIC_LOCAL(SVGAttributeToPropertyMap, map, ());
-    if (!map.isEmpty())
-        return map;
-    map.addProperty(requiredFeaturesPropertyInfo());
-    map.addProperty(requiredExtensionsPropertyInfo());
-    map.addProperty(systemLanguagePropertyInfo());
-    return map;
-}
-
-bool SVGTests::hasExtension(const String&) const
+bool SVGTests::hasExtension(SVGTests*, const String&)
 {
     // FIXME: Implement me!
     return false;
@@ -100,21 +49,34 @@
 
 bool SVGTests::isValid() const
 {
-    unsigned featuresSize = m_requiredFeatures.value.size();
-    for (unsigned i = 0; i < featuresSize; ++i) {
-        String value = m_requiredFeatures.value.at(i);
-        if (value.isEmpty() || !DOMImplementation::hasFeature(value, String()))
+    if (m_requiredFeatures->isSpecified()) {
+        const Vector<String>& requiredFeatures = m_requiredFeatures->value()->values();
+        Vector<String>::const_iterator it = requiredFeatures.begin();
+        Vector<String>::const_iterator itEnd = requiredFeatures.end();
+        for (; it != itEnd; ++it) {
+            if (it->isEmpty() || !DOMImplementation::hasFeature(*it, String()))
+                return false;
+        }
+    }
+
+    if (m_systemLanguage->isSpecified()) {
+        bool matchFound = false;
+
+        const Vector<String>& systemLanguage = m_systemLanguage->value()->values();
+        Vector<String>::const_iterator it = systemLanguage.begin();
+        Vector<String>::const_iterator itEnd = systemLanguage.end();
+        for (; it != itEnd; ++it) {
+            if (*it == defaultLanguage().string().substring(0, 2)) {
+                matchFound = true;
+                break;
+            }
+        }
+
+        if (!matchFound)
             return false;
     }
 
-    unsigned systemLanguageSize = m_systemLanguage.value.size();
-    for (unsigned i = 0; i < systemLanguageSize; ++i) {
-        String value = m_systemLanguage.value.at(i);
-        if (value != defaultLanguage().substring(0, 2))
-            return false;
-    }
-
-    if (!m_requiredExtensions.value.isEmpty())
+    if (!m_requiredExtensions->value()->values().isEmpty())
         return false;
 
     return true;
@@ -122,20 +84,22 @@
 
 bool SVGTests::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
-    if (name == SVGNames::requiredFeaturesAttr) {
-        m_requiredFeatures.value.reset(value);
-        return true;
-    }
-    if (name == SVGNames::requiredExtensionsAttr) {
-        m_requiredExtensions.value.reset(value);
-        return true;
-    }
-    if (name == SVGNames::systemLanguageAttr) {
-        m_systemLanguage.value.reset(value);
-        return true;
-    }
+    // FIXME: Should handle exceptions here.
+    // This is safe as of now, as the current impl of SVGStringList::setValueAsString never fails.
+    SVGParsingError parseError = NoError;
 
-    return false;
+    if (name == SVGNames::requiredFeaturesAttr)
+        m_requiredFeatures->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::requiredExtensionsAttr)
+        m_requiredExtensions->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::systemLanguageAttr)
+        m_systemLanguage->setBaseValueAsString(value, parseError);
+    else
+        return false;
+
+    ASSERT(parseError == NoError);
+
+    return true;
 }
 
 bool SVGTests::isKnownAttribute(const QualifiedName& attrName)
@@ -152,49 +116,4 @@
     supportedAttributes.add(SVGNames::systemLanguageAttr);
 }
 
-void SVGTests::synchronizeRequiredFeatures(SVGElement* contextElement)
-{
-    ASSERT(contextElement);
-    if (!m_requiredFeatures.shouldSynchronize)
-        return;
-    AtomicString value(m_requiredFeatures.value.valueAsString());
-    m_requiredFeatures.synchronize(contextElement, requiredFeaturesPropertyInfo()->attributeName, value);
-}
-
-void SVGTests::synchronizeRequiredExtensions(SVGElement* contextElement)
-{
-    ASSERT(contextElement);
-    if (!m_requiredExtensions.shouldSynchronize)
-        return;
-    AtomicString value(m_requiredExtensions.value.valueAsString());
-    m_requiredExtensions.synchronize(contextElement, requiredExtensionsPropertyInfo()->attributeName, value);
-}
-
-void SVGTests::synchronizeSystemLanguage(SVGElement* contextElement)
-{
-    ASSERT(contextElement);
-    if (!m_systemLanguage.shouldSynchronize)
-        return;
-    AtomicString value(m_systemLanguage.value.valueAsString());
-    m_systemLanguage.synchronize(contextElement, systemLanguagePropertyInfo()->attributeName, value);
-}
-
-SVGStringList& SVGTests::requiredFeatures()
-{
-    m_requiredFeatures.shouldSynchronize = true;
-    return m_requiredFeatures.value;
-}
-
-SVGStringList& SVGTests::requiredExtensions()
-{
-    m_requiredExtensions.shouldSynchronize = true;
-    return m_requiredExtensions.value;
-}
-
-SVGStringList& SVGTests::systemLanguage()
-{
-    m_systemLanguage.shouldSynchronize = true;
-    return m_systemLanguage.value;
-}
-
 }
diff --git a/Source/core/svg/SVGTests.h b/Source/core/svg/SVGTests.h
index 7df0e22..3113f51 100644
--- a/Source/core/svg/SVGTests.h
+++ b/Source/core/svg/SVGTests.h
@@ -21,8 +21,7 @@
 #ifndef SVGTests_h
 #define SVGTests_h
 
-#include "core/svg/SVGStringList.h"
-#include "core/svg/properties/SVGAnimatedPropertyMacros.h"
+#include "core/svg/SVGStaticStringList.h"
 #include "wtf/HashSet.h"
 
 namespace WebCore {
@@ -33,11 +32,11 @@
 
 class SVGTests {
 public:
-    SVGStringList& requiredFeatures();
-    SVGStringList& requiredExtensions();
-    SVGStringList& systemLanguage();
+    static SVGStringListTearOff* requiredFeatures(SVGTests* object) { return object->m_requiredFeatures->tearOff(); }
+    static SVGStringListTearOff* requiredExtensions(SVGTests* object) { return object->m_requiredExtensions->tearOff(); }
+    static SVGStringListTearOff* systemLanguage(SVGTests* object) { return object->m_systemLanguage->tearOff(); }
 
-    bool hasExtension(const String&) const;
+    static bool hasExtension(SVGTests*, const String&);
     bool isValid() const;
 
     bool parseAttribute(const QualifiedName&, const AtomicString&);
@@ -45,27 +44,13 @@
 
     void addSupportedAttributes(HashSet<QualifiedName>&);
 
-    static SVGAttributeToPropertyMap& attributeToPropertyMap();
-
 protected:
-    SVGTests();
-
-    void synchronizeRequiredFeatures(SVGElement* contextElement);
-    void synchronizeRequiredExtensions(SVGElement* contextElement);
-    void synchronizeSystemLanguage(SVGElement* contextElement);
+    SVGTests(SVGElement* contextElement);
 
 private:
-    // Custom 'requiredFeatures' property
-    static const SVGPropertyInfo* requiredFeaturesPropertyInfo();
-    SVGSynchronizableAnimatedProperty<SVGStringList> m_requiredFeatures;
-
-    // Custom 'requiredExtensions' property
-    static const SVGPropertyInfo* requiredExtensionsPropertyInfo();
-    SVGSynchronizableAnimatedProperty<SVGStringList> m_requiredExtensions;
-
-    // Custom 'systemLanguage' property
-    static const SVGPropertyInfo* systemLanguagePropertyInfo();
-    SVGSynchronizableAnimatedProperty<SVGStringList> m_systemLanguage;
+    RefPtr<SVGStaticStringList> m_requiredFeatures;
+    RefPtr<SVGStaticStringList> m_requiredExtensions;
+    RefPtr<SVGStaticStringList> m_systemLanguage;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGTests.idl b/Source/core/svg/SVGTests.idl
index 0842cc1..591a86b 100644
--- a/Source/core/svg/SVGTests.idl
+++ b/Source/core/svg/SVGTests.idl
@@ -25,8 +25,7 @@
  */
 
 [
-    NoInterfaceObject,
-    LegacyImplementedInBaseClass
+    NoInterfaceObject
 ] interface SVGTests {
     readonly attribute SVGStringList requiredFeatures;
     readonly attribute SVGStringList requiredExtensions;
diff --git a/Source/core/svg/SVGTextContentElement.cpp b/Source/core/svg/SVGTextContentElement.cpp
index a1901ab..c5b8e0f 100644
--- a/Source/core/svg/SVGTextContentElement.cpp
+++ b/Source/core/svg/SVGTextContentElement.cpp
@@ -25,6 +25,7 @@
 #include "CSSValueKeywords.h"
 #include "SVGNames.h"
 #include "XMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/editing/FrameSelection.h"
@@ -36,71 +37,52 @@
 
 namespace WebCore {
 
-// Define custom animated property 'textLength'.
-const SVGPropertyInfo* SVGTextContentElement::textLengthPropertyInfo()
-{
-    static const SVGPropertyInfo* s_propertyInfo = 0;
-    if (!s_propertyInfo) {
-        s_propertyInfo = new SVGPropertyInfo(AnimatedLength,
-                                             PropertyIsReadWrite,
-                                             SVGNames::textLengthAttr,
-                                             SVGNames::textLengthAttr.localName(),
-                                             &SVGTextContentElement::synchronizeTextLength,
-                                             &SVGTextContentElement::lookupOrCreateTextLengthWrapper);
-    }
-    return s_propertyInfo;
-}
-
 // Animated property definitions
+
+// SVGTextContentElement's 'textLength' attribute needs special handling.
+// It should return getComputedTextLength() when textLength is not specified manually.
+class SVGAnimatedTextLength FINAL : public SVGAnimatedLength {
+public:
+    static PassRefPtr<SVGAnimatedTextLength> create(SVGTextContentElement* contextElement)
+    {
+        return adoptRef(new SVGAnimatedTextLength(contextElement));
+    }
+
+    virtual SVGLengthTearOff* baseVal() OVERRIDE
+    {
+        SVGTextContentElement* textContentElement = toSVGTextContentElement(contextElement());
+        if (!textContentElement->textLengthIsSpecifiedByUser())
+            baseValue()->newValueSpecifiedUnits(LengthTypeNumber, textContentElement->getComputedTextLength());
+
+        return SVGAnimatedLength::baseVal();
+    }
+
+private:
+    SVGAnimatedTextLength(SVGTextContentElement* contextElement)
+        : SVGAnimatedLength(contextElement, SVGNames::textLengthAttr, SVGLength::create(LengthModeOther))
+    {
+    }
+};
+
 DEFINE_ANIMATED_ENUMERATION(SVGTextContentElement, SVGNames::lengthAdjustAttr, LengthAdjust, lengthAdjust, SVGLengthAdjustType)
-DEFINE_ANIMATED_BOOLEAN(SVGTextContentElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTextContentElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(textLength)
     REGISTER_LOCAL_ANIMATED_PROPERTY(lengthAdjust)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGTextContentElement::SVGTextContentElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
-    , m_textLength(LengthModeOther)
-    , m_specifiedTextLength(LengthModeOther)
+    , m_textLength(SVGAnimatedTextLength::create(this))
+    , m_textLengthIsSpecifiedByUser(false)
     , m_lengthAdjust(SVGLengthAdjustSpacing)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_textLength);
     registerAnimatedPropertiesForSVGTextContentElement();
 }
 
-void SVGTextContentElement::synchronizeTextLength(SVGElement* contextElement)
-{
-    ASSERT(contextElement);
-    SVGTextContentElement* ownerType = toSVGTextContentElement(contextElement);
-    if (!ownerType->m_textLength.shouldSynchronize)
-        return;
-    AtomicString value(SVGPropertyTraits<SVGLength>::toString(ownerType->m_specifiedTextLength));
-    ownerType->m_textLength.synchronize(ownerType, textLengthPropertyInfo()->attributeName, value);
-}
-
-PassRefPtr<SVGAnimatedProperty> SVGTextContentElement::lookupOrCreateTextLengthWrapper(SVGElement* contextElement)
-{
-    ASSERT(contextElement);
-    SVGTextContentElement* ownerType = toSVGTextContentElement(contextElement);
-    return SVGAnimatedProperty::lookupOrCreateWrapper<SVGTextContentElement, SVGAnimatedLength, SVGLength>
-           (ownerType, textLengthPropertyInfo(), ownerType->m_textLength.value);
-}
-
-PassRefPtr<SVGAnimatedLength> SVGTextContentElement::textLength()
-{
-    DEFINE_STATIC_LOCAL(SVGLength, defaultTextLength, (LengthModeOther));
-    if (m_specifiedTextLength == defaultTextLength)
-        m_textLength.value.newValueSpecifiedUnits(LengthTypeNumber, getComputedTextLength(), ASSERT_NO_EXCEPTION);
-
-    m_textLength.shouldSynchronize = true;
-    return static_pointer_cast<SVGAnimatedLength>(lookupOrCreateTextLengthWrapper(this));
-
-}
-
 unsigned SVGTextContentElement::getNumberOfChars()
 {
     document().updateLayoutIgnorePendingStylesheets();
@@ -119,7 +101,7 @@
 
     unsigned numberOfChars = getNumberOfChars();
     if (charnum >= numberOfChars) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("charnum", charnum, getNumberOfChars()));
         return 0.0f;
     }
 
@@ -129,40 +111,43 @@
     return SVGTextQuery(renderer()).subStringLength(charnum, nchars);
 }
 
-SVGPoint SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionState& exceptionState)
+PassRefPtr<SVGPointTearOff> SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionState& exceptionState)
 {
     document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return FloatPoint();
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("charnum", charnum, getNumberOfChars()));
+        return 0;
     }
 
-    return SVGTextQuery(renderer()).startPositionOfCharacter(charnum);
+    FloatPoint point = SVGTextQuery(renderer()).startPositionOfCharacter(charnum);
+    return SVGPointTearOff::create(SVGPoint::create(point), 0, PropertyIsNotAnimVal);
 }
 
-SVGPoint SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionState& exceptionState)
+PassRefPtr<SVGPointTearOff> SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionState& exceptionState)
 {
     document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return FloatPoint();
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("charnum", charnum, getNumberOfChars()));
+        return 0;
     }
 
-    return SVGTextQuery(renderer()).endPositionOfCharacter(charnum);
+    FloatPoint point = SVGTextQuery(renderer()).endPositionOfCharacter(charnum);
+    return SVGPointTearOff::create(SVGPoint::create(point), 0, PropertyIsNotAnimVal);
 }
 
-SVGRect SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionState& exceptionState)
+PassRefPtr<SVGRectTearOff> SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionState& exceptionState)
 {
     document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
-        return SVGRect();
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("charnum", charnum, getNumberOfChars()));
+        return 0;
     }
 
-    return SVGTextQuery(renderer()).extentOfCharacter(charnum);
+    FloatRect rect = SVGTextQuery(renderer()).extentOfCharacter(charnum);
+    return SVGRectTearOff::create(SVGRect::create(rect), 0, PropertyIsNotAnimVal);
 }
 
 float SVGTextContentElement::getRotationOfChar(unsigned charnum, ExceptionState& exceptionState)
@@ -170,24 +155,24 @@
     document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("charnum", charnum, getNumberOfChars()));
         return 0.0f;
     }
 
     return SVGTextQuery(renderer()).rotationOfCharacter(charnum);
 }
 
-int SVGTextContentElement::getCharNumAtPosition(const SVGPoint& point)
+int SVGTextContentElement::getCharNumAtPosition(PassRefPtr<SVGPointTearOff> point, ExceptionState& exceptionState)
 {
     document().updateLayoutIgnorePendingStylesheets();
-    return SVGTextQuery(renderer()).characterNumberAtPosition(point);
+    return SVGTextQuery(renderer()).characterNumberAtPosition(point->target()->value());
 }
 
 void SVGTextContentElement::selectSubString(unsigned charnum, unsigned nchars, ExceptionState& exceptionState)
 {
     unsigned numberOfChars = getNumberOfChars();
     if (charnum >= numberOfChars) {
-        exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("charnum", charnum, getNumberOfChars()));
         return;
     }
 
@@ -213,10 +198,9 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGLangSpace::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::lengthAdjustAttr);
         supportedAttributes.add(SVGNames::textLengthAttr);
+        supportedAttributes.add(XMLNames::spaceAttr);
     }
     return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
@@ -253,9 +237,8 @@
         if (propertyValue > 0)
             setLengthAdjustBaseValue(propertyValue);
     } else if (name == SVGNames::textLengthAttr) {
-        m_textLength.value = SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths);
-    } else if (SVGExternalResourcesRequired::parseAttribute(name, value)) {
-    } else if (SVGLangSpace::parseAttribute(name, value)) {
+        m_textLength->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (name.matches(XMLNames::spaceAttr)) {
     } else
         ASSERT_NOT_REACHED();
 
@@ -269,10 +252,10 @@
         return;
     }
 
-    SVGElementInstance::InvalidationGuard invalidationGuard(this);
-
     if (attrName == SVGNames::textLengthAttr)
-        m_specifiedTextLength = m_textLength.value;
+        m_textLengthIsSpecifiedByUser = true;
+
+    SVGElementInstance::InvalidationGuard invalidationGuard(this);
 
     if (RenderObject* renderer = this->renderer())
         RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
diff --git a/Source/core/svg/SVGTextContentElement.h b/Source/core/svg/SVGTextContentElement.h
index db0b622..1bd13f1 100644
--- a/Source/core/svg/SVGTextContentElement.h
+++ b/Source/core/svg/SVGTextContentElement.h
@@ -24,8 +24,8 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGPointTearOff.h"
 
 namespace WebCore {
 
@@ -66,8 +66,9 @@
     }
 };
 
-class SVGTextContentElement : public SVGGraphicsElement,
-                              public SVGExternalResourcesRequired {
+class SVGAnimatedTextLength;
+
+class SVGTextContentElement : public SVGGraphicsElement {
 public:
     // Forward declare enumerations in the W3C naming scheme, for IDL generation.
     enum {
@@ -79,46 +80,36 @@
     unsigned getNumberOfChars();
     float getComputedTextLength();
     float getSubStringLength(unsigned charnum, unsigned nchars, ExceptionState&);
-    SVGPoint getStartPositionOfChar(unsigned charnum, ExceptionState&);
-    SVGPoint getEndPositionOfChar(unsigned charnum, ExceptionState&);
-    SVGRect getExtentOfChar(unsigned charnum, ExceptionState&);
+    PassRefPtr<SVGPointTearOff> getStartPositionOfChar(unsigned charnum, ExceptionState&);
+    PassRefPtr<SVGPointTearOff> getEndPositionOfChar(unsigned charnum, ExceptionState&);
+    PassRefPtr<SVGRectTearOff> getExtentOfChar(unsigned charnum, ExceptionState&);
     float getRotationOfChar(unsigned charnum, ExceptionState&);
-    int getCharNumAtPosition(const SVGPoint&);
+    int getCharNumAtPosition(PassRefPtr<SVGPointTearOff>, ExceptionState&);
     void selectSubString(unsigned charnum, unsigned nchars, ExceptionState&);
 
     static SVGTextContentElement* elementFromRenderer(RenderObject*);
 
-    // textLength is not declared using the standard DECLARE_ANIMATED_LENGTH macro
-    // as its getter needs special handling (return getComputedTextLength(), instead of m_textLength).
-    SVGLength& specifiedTextLength() { return m_specifiedTextLength; }
-    PassRefPtr<SVGAnimatedLength> textLength();
-    static const SVGPropertyInfo* textLengthPropertyInfo();
+    SVGAnimatedLength* textLength() { return m_textLength.get(); }
+    bool textLengthIsSpecifiedByUser() { return m_textLengthIsSpecifiedByUser; }
 
 protected:
     SVGTextContentElement(const QualifiedName&, Document&);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
-
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
-    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE FINAL;
+    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE FINAL;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
 private:
-    virtual bool isTextContent() const { return true; }
+    virtual bool isTextContent() const OVERRIDE FINAL { return true; }
 
-    // Custom 'textLength' property
-    static void synchronizeTextLength(SVGElement* contextElement);
-    static PassRefPtr<SVGAnimatedProperty> lookupOrCreateTextLengthWrapper(SVGElement* contextElement);
-    mutable SVGSynchronizableAnimatedProperty<SVGLength> m_textLength;
-    SVGLength m_specifiedTextLength;
-
+    RefPtr<SVGAnimatedLength> m_textLength;
+    bool m_textLengthIsSpecifiedByUser;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGTextContentElement)
         DECLARE_ANIMATED_ENUMERATION(LengthAdjust, lengthAdjust, SVGLengthAdjustType)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGTextContentElement.idl b/Source/core/svg/SVGTextContentElement.idl
index f4ce37d..f16b1f9 100644
--- a/Source/core/svg/SVGTextContentElement.idl
+++ b/Source/core/svg/SVGTextContentElement.idl
@@ -23,7 +23,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGTextContentElement : SVGGraphicsElement {
+[
+    StrictTypeChecking,
+] interface SVGTextContentElement : SVGGraphicsElement {
     // lengthAdjust Types
     const unsigned short LENGTHADJUST_UNKNOWN          = 0;
     const unsigned short LENGTHADJUST_SPACING          = 1;
@@ -39,10 +41,7 @@
     [RaisesException] SVGPoint getEndPositionOfChar(unsigned long offset);
     [RaisesException] SVGRect getExtentOfChar(unsigned long offset);
     [RaisesException] float getRotationOfChar(unsigned long offset);
-    long getCharNumAtPosition(SVGPoint point);
+    [RaisesException] long getCharNumAtPosition(SVGPoint point);
     [RaisesException] void selectSubString(unsigned long offset, unsigned long length);
 };
 
-// FIXME: SVGTextContentElement is not supposed to implement SVGExternalResourcesRequired.
-SVGTextContentElement implements SVGExternalResourcesRequired;
-
diff --git a/Source/core/svg/SVGTextElement.cpp b/Source/core/svg/SVGTextElement.cpp
index 7806ed1..523ab0a 100644
--- a/Source/core/svg/SVGTextElement.cpp
+++ b/Source/core/svg/SVGTextElement.cpp
@@ -69,18 +69,4 @@
     return new RenderSVGText(this);
 }
 
-bool SVGTextElement::childShouldCreateRenderer(const Node& child) const
-{
-    if (child.isTextNode()
-        || child.hasTagName(SVGNames::aTag)
-#if ENABLE(SVG_FONTS)
-        || child.hasTagName(SVGNames::altGlyphTag)
-#endif
-        || child.hasTagName(SVGNames::textPathTag)
-        || child.hasTagName(SVGNames::tspanTag))
-        return true;
-
-    return false;
-}
-
 }
diff --git a/Source/core/svg/SVGTextElement.h b/Source/core/svg/SVGTextElement.h
index b52204c..28284a1 100644
--- a/Source/core/svg/SVGTextElement.h
+++ b/Source/core/svg/SVGTextElement.h
@@ -30,15 +30,14 @@
 public:
     static PassRefPtr<SVGTextElement> create(Document&);
 
-    virtual AffineTransform animatedLocalTransform() const;
+    virtual AffineTransform animatedLocalTransform() const OVERRIDE;
 
 private:
     explicit SVGTextElement(Document&);
 
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const Node& child) const;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGTextElement, hasTagName(SVGNames::textTag));
diff --git a/Source/core/svg/SVGTextPathElement.cpp b/Source/core/svg/SVGTextPathElement.cpp
index b3f2e1b..2697861 100644
--- a/Source/core/svg/SVGTextPathElement.cpp
+++ b/Source/core/svg/SVGTextPathElement.cpp
@@ -30,26 +30,25 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGTextPathElement, SVGNames::startOffsetAttr, StartOffset, startOffset)
 DEFINE_ANIMATED_ENUMERATION(SVGTextPathElement, SVGNames::methodAttr, Method, method, SVGTextPathMethodType)
 DEFINE_ANIMATED_ENUMERATION(SVGTextPathElement, SVGNames::spacingAttr, Spacing, spacing, SVGTextPathSpacingType)
-DEFINE_ANIMATED_STRING(SVGTextPathElement, XLinkNames::hrefAttr, Href, href)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTextPathElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(startOffset)
     REGISTER_LOCAL_ANIMATED_PROPERTY(method)
     REGISTER_LOCAL_ANIMATED_PROPERTY(spacing)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextContentElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGTextPathElement::SVGTextPathElement(Document& document)
     : SVGTextContentElement(SVGNames::textPathTag, document)
-    , m_startOffset(LengthModeOther)
+    , SVGURIReference(this)
+    , m_startOffset(SVGAnimatedLength::create(this, SVGNames::startOffsetAttr, SVGLength::create(LengthModeOther)))
     , m_method(SVGTextPathMethodAlign)
     , m_spacing(SVGTextPathSpacingExact)
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_startOffset);
     registerAnimatedPropertiesForSVGTextPathElement();
 }
 
@@ -84,11 +83,11 @@
 {
     SVGParsingError parseError = NoError;
 
-    if (!isSupportedAttribute(name))
+    if (!isSupportedAttribute(name)) {
         SVGTextContentElement::parseAttribute(name, value);
-    else if (name == SVGNames::startOffsetAttr)
-        setStartOffsetBaseValue(SVGLength::construct(LengthModeOther, value, parseError));
-    else if (name == SVGNames::methodAttr) {
+    } else if (name == SVGNames::startOffsetAttr) {
+        m_startOffset->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::methodAttr) {
         SVGTextPathMethodType propertyValue = SVGPropertyTraits<SVGTextPathMethodType>::fromString(value);
         if (propertyValue > 0)
             setMethodBaseValue(propertyValue);
@@ -96,9 +95,10 @@
         SVGTextPathSpacingType propertyValue = SVGPropertyTraits<SVGTextPathSpacingType>::fromString(value);
         if (propertyValue > 0)
             setSpacingBaseValue(propertyValue);
-    } else if (SVGURIReference::parseAttribute(name, value)) {
-    } else
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else {
         ASSERT_NOT_REACHED();
+    }
 
     reportAttributeParsingError(parseError, name, value);
 }
@@ -129,16 +129,6 @@
     return new RenderSVGTextPath(this);
 }
 
-bool SVGTextPathElement::childShouldCreateRenderer(const Node& child) const
-{
-    if (child.isTextNode()
-        || child.hasTagName(SVGNames::aTag)
-        || child.hasTagName(SVGNames::tspanTag))
-        return true;
-
-    return false;
-}
-
 bool SVGTextPathElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (parentNode()
@@ -155,8 +145,8 @@
     if (!inDocument())
         return;
 
-    String id;
-    Element* target = SVGURIReference::targetElementFromIRIString(hrefCurrentValue(), document(), &id);
+    AtomicString id;
+    Element* target = SVGURIReference::targetElementFromIRIString(hrefString(), document(), &id);
     if (!target) {
         // Do not register as pending if we are already pending this resource.
         if (document().accessSVGExtensions()->isElementPendingResource(this, id))
@@ -189,7 +179,7 @@
 
 bool SVGTextPathElement::selfHasRelativeLengths() const
 {
-    return startOffsetCurrentValue().isRelative()
+    return m_startOffset->currentValue()->isRelative()
         || SVGTextContentElement::selfHasRelativeLengths();
 }
 
diff --git a/Source/core/svg/SVGTextPathElement.h b/Source/core/svg/SVGTextPathElement.h
index 2b7a38c..aff4f1d 100644
--- a/Source/core/svg/SVGTextPathElement.h
+++ b/Source/core/svg/SVGTextPathElement.h
@@ -111,6 +111,8 @@
 
     static PassRefPtr<SVGTextPathElement> create(Document&);
 
+    SVGAnimatedLength* startOffset() const { return m_startOffset.get(); }
+
 private:
     explicit SVGTextPathElement(Document&);
 
@@ -118,25 +120,23 @@
 
     void clearResourceReferences();
 
-    virtual void buildPendingResource();
+    virtual void buildPendingResource() OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const Node& child) const;
-    virtual bool rendererIsNeeded(const RenderStyle&);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
-    virtual bool selfHasRelativeLengths() const;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
+    RefPtr<SVGAnimatedLength> m_startOffset;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGTextPathElement)
-        DECLARE_ANIMATED_LENGTH(StartOffset, startOffset)
         DECLARE_ANIMATED_ENUMERATION(Method, method, SVGTextPathMethodType)
         DECLARE_ANIMATED_ENUMERATION(Spacing, spacing, SVGTextPathSpacingType)
-        DECLARE_ANIMATED_STRING(Href, href)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
diff --git a/Source/core/svg/SVGTextPositioningElement.cpp b/Source/core/svg/SVGTextPositioningElement.cpp
index 664ba23..b9340cc 100644
--- a/Source/core/svg/SVGTextPositioningElement.cpp
+++ b/Source/core/svg/SVGTextPositioningElement.cpp
@@ -32,25 +32,26 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH_LIST(SVGTextPositioningElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH_LIST(SVGTextPositioningElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH_LIST(SVGTextPositioningElement, SVGNames::dxAttr, Dx, dx)
-DEFINE_ANIMATED_LENGTH_LIST(SVGTextPositioningElement, SVGNames::dyAttr, Dy, dy)
-DEFINE_ANIMATED_NUMBER_LIST(SVGTextPositioningElement, SVGNames::rotateAttr, Rotate, rotate)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTextPositioningElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(dx)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(dy)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(rotate)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextContentElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGTextPositioningElement::SVGTextPositioningElement(const QualifiedName& tagName, Document& document)
     : SVGTextContentElement(tagName, document)
+    , m_x(SVGAnimatedLengthList::create(this, SVGNames::xAttr, SVGLengthList::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLengthList::create(this, SVGNames::yAttr, SVGLengthList::create(LengthModeHeight)))
+    , m_dx(SVGAnimatedLengthList::create(this, SVGNames::dxAttr, SVGLengthList::create(LengthModeWidth)))
+    , m_dy(SVGAnimatedLengthList::create(this, SVGNames::dyAttr, SVGLengthList::create(LengthModeHeight)))
+    , m_rotate(SVGAnimatedNumberList::create(this, SVGNames::rotateAttr, SVGNumberList::create()))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_dx);
+    addToPropertyMap(m_dy);
+    addToPropertyMap(m_rotate);
     registerAnimatedPropertiesForSVGTextPositioningElement();
 }
 
@@ -74,47 +75,22 @@
         return;
     }
 
-    if (name == SVGNames::xAttr) {
-        SVGLengthList newList;
-        newList.parse(value, LengthModeWidth);
-        detachAnimatedXListWrappers(newList.size());
-        setXBaseValue(newList);
-        return;
-    }
+    SVGParsingError parseError = NoError;
 
-    if (name == SVGNames::yAttr) {
-        SVGLengthList newList;
-        newList.parse(value, LengthModeHeight);
-        detachAnimatedYListWrappers(newList.size());
-        setYBaseValue(newList);
-        return;
-    }
+    if (name == SVGNames::xAttr)
+        m_x->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::yAttr)
+        m_y->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::dxAttr)
+        m_dx->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::dyAttr)
+        m_dy->setBaseValueAsString(value, parseError);
+    else if (name == SVGNames::rotateAttr)
+        m_rotate->setBaseValueAsString(value, parseError);
+    else
+        ASSERT_NOT_REACHED();
 
-    if (name == SVGNames::dxAttr) {
-        SVGLengthList newList;
-        newList.parse(value, LengthModeWidth);
-        detachAnimatedDxListWrappers(newList.size());
-        setDxBaseValue(newList);
-        return;
-    }
-
-    if (name == SVGNames::dyAttr) {
-        SVGLengthList newList;
-        newList.parse(value, LengthModeHeight);
-        detachAnimatedDyListWrappers(newList.size());
-        setDyBaseValue(newList);
-        return;
-    }
-
-    if (name == SVGNames::rotateAttr) {
-        SVGNumberList newList;
-        newList.parse(value);
-        detachAnimatedRotateListWrappers(newList.size());
-        setRotateBaseValue(newList);
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGTextPositioningElement::svgAttributeChanged(const QualifiedName& attrName)
@@ -167,7 +143,7 @@
         && !node->hasTagName(SVGNames::tspanTag))
         return 0;
 
-    return static_cast<SVGTextPositioningElement*>(node);
+    return toSVGTextPositioningElement(node);
 }
 
 }
diff --git a/Source/core/svg/SVGTextPositioningElement.h b/Source/core/svg/SVGTextPositioningElement.h
index 665315c..126cf87 100644
--- a/Source/core/svg/SVGTextPositioningElement.h
+++ b/Source/core/svg/SVGTextPositioningElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGTextPositioningElement_h
 #define SVGTextPositioningElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedLengthList.h"
 #include "core/svg/SVGAnimatedNumberList.h"
 #include "core/svg/SVGTextContentElement.h"
@@ -31,22 +32,36 @@
 public:
     static SVGTextPositioningElement* elementFromRenderer(RenderObject*);
 
+    SVGAnimatedLengthList* x() { return m_x.get(); }
+    SVGAnimatedLengthList* y() { return m_y.get(); }
+    SVGAnimatedLengthList* dx() { return m_dx.get(); }
+    SVGAnimatedLengthList* dy() { return m_dy.get(); }
+    SVGAnimatedNumberList* rotate() { return m_rotate.get(); }
+
 protected:
     SVGTextPositioningElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
-    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE FINAL;
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE FINAL;
+    virtual bool isTextPositioning() const OVERRIDE FINAL { return true; }
 
+    RefPtr<SVGAnimatedLengthList> m_x;
+    RefPtr<SVGAnimatedLengthList> m_y;
+    RefPtr<SVGAnimatedLengthList> m_dx;
+    RefPtr<SVGAnimatedLengthList> m_dy;
+    RefPtr<SVGAnimatedNumberList> m_rotate;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGTextPositioningElement)
-        DECLARE_ANIMATED_LENGTH_LIST(X, x)
-        DECLARE_ANIMATED_LENGTH_LIST(Y, y)
-        DECLARE_ANIMATED_LENGTH_LIST(Dx, dx)
-        DECLARE_ANIMATED_LENGTH_LIST(Dy, dy)
-        DECLARE_ANIMATED_NUMBER_LIST(Rotate, rotate)
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline bool isSVGTextPositioningElement(const Node& node)
+{
+    return node.isSVGElement() && toSVGElement(node).isTextPositioning();
+}
+
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGTextPositioningElement);
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGTitleElement.h b/Source/core/svg/SVGTitleElement.h
index 21c3127..d3294ae 100644
--- a/Source/core/svg/SVGTitleElement.h
+++ b/Source/core/svg/SVGTitleElement.h
@@ -34,9 +34,9 @@
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
+    virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGTransform.idl b/Source/core/svg/SVGTransform.idl
index 99d7fc2..96c0058 100644
--- a/Source/core/svg/SVGTransform.idl
+++ b/Source/core/svg/SVGTransform.idl
@@ -19,7 +19,9 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface SVGTransform {
+[
+    StrictTypeChecking,
+] interface SVGTransform {
     // Transform Types
     const unsigned short SVG_TRANSFORM_UNKNOWN = 0;
     const unsigned short SVG_TRANSFORM_MATRIX = 1;
@@ -33,11 +35,11 @@
     [ImplementedAs=svgMatrix] readonly attribute SVGMatrix matrix;
     readonly attribute float angle;
 
-    [StrictTypeChecking] void setMatrix(SVGMatrix matrix);
-    [StrictTypeChecking] void setTranslate(float tx, float ty);
-    [StrictTypeChecking] void setScale(float sx, float sy);
-    [StrictTypeChecking] void setRotate(float angle, float cx, float cy);
-    [StrictTypeChecking] void setSkewX(float angle);
-    [StrictTypeChecking] void setSkewY(float angle);
+    void setMatrix(SVGMatrix matrix);
+    void setTranslate(float tx, float ty);
+    void setScale(float sx, float sy);
+    void setRotate(float angle, float cx, float cy);
+    void setSkewX(float angle);
+    void setSkewY(float angle);
 };
 
diff --git a/Source/core/svg/SVGTransformList.idl b/Source/core/svg/SVGTransformList.idl
index bb6f659..fe57a7a 100644
--- a/Source/core/svg/SVGTransformList.idl
+++ b/Source/core/svg/SVGTransformList.idl
@@ -24,18 +24,20 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface SVGTransformList {
+[
+    StrictTypeChecking,
+] interface SVGTransformList {
     readonly attribute unsigned long numberOfItems;
 
     [RaisesException] void clear();
-    [StrictTypeChecking, RaisesException] SVGTransform initialize(SVGTransform item);
-    [StrictTypeChecking, RaisesException] SVGTransform getItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGTransform insertItemBefore(SVGTransform item, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGTransform replaceItem(SVGTransform item, unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGTransform removeItem(unsigned long index);
-    [StrictTypeChecking, RaisesException] SVGTransform appendItem(SVGTransform item);
+    [RaisesException] SVGTransform initialize(SVGTransform item);
+    [RaisesException] SVGTransform getItem(unsigned long index);
+    [RaisesException] SVGTransform insertItemBefore(SVGTransform item, unsigned long index);
+    [RaisesException] SVGTransform replaceItem(SVGTransform item, unsigned long index);
+    [RaisesException] SVGTransform removeItem(unsigned long index);
+    [RaisesException] SVGTransform appendItem(SVGTransform item);
 
-    [StrictTypeChecking, RaisesException] SVGTransform createSVGTransformFromMatrix(SVGMatrix matrix);
+    SVGTransform createSVGTransformFromMatrix(SVGMatrix matrix);
 
     [RaisesException] SVGTransform consolidate();
 };
diff --git a/Source/core/svg/SVGURIReference.cpp b/Source/core/svg/SVGURIReference.cpp
index 02cd99f..240dd7f 100644
--- a/Source/core/svg/SVGURIReference.cpp
+++ b/Source/core/svg/SVGURIReference.cpp
@@ -19,22 +19,19 @@
  */
 
 #include "config.h"
-
 #include "core/svg/SVGURIReference.h"
 
 #include "XLinkNames.h"
+#include "core/svg/SVGElement.h"
 #include "platform/weborigin/KURL.h"
 
 namespace WebCore {
 
-bool SVGURIReference::parseAttribute(const QualifiedName& name, const AtomicString& value)
+SVGURIReference::SVGURIReference(SVGElement* element)
+    : m_href(SVGAnimatedString::create(element, XLinkNames::hrefAttr, SVGString::create()))
 {
-    if (name.matches(XLinkNames::hrefAttr)) {
-        setHrefBaseValue(value);
-        return true;
-    }
-
-    return false;
+    ASSERT(element);
+    element->addToPropertyMap(m_href);
 }
 
 bool SVGURIReference::isKnownAttribute(const QualifiedName& attrName)
@@ -42,27 +39,27 @@
     return attrName.matches(XLinkNames::hrefAttr);
 }
 
-String SVGURIReference::fragmentIdentifierFromIRIString(const String& url, const Document& document)
+AtomicString SVGURIReference::fragmentIdentifierFromIRIString(const String& url, const Document& document)
 {
     size_t start = url.find('#');
     if (start == kNotFound)
-        return emptyString();
+        return emptyAtom;
 
     KURL base = start ? KURL(document.baseURI(), url.substring(0, start)) : document.baseURI();
     if (equalIgnoringFragmentIdentifier(base, document.url()))
-        return url.substring(start + 1);
+        return AtomicString(url.substring(start + 1));
 
-    return emptyString();
+    return emptyAtom;
 }
 
-static inline KURL urlFromIRIStringWithFragmentIdentifier(const String& url, const Document& document, String& fragmentIdentifier)
+static inline KURL urlFromIRIStringWithFragmentIdentifier(const String& url, const Document& document, AtomicString& fragmentIdentifier)
 {
     size_t startOfFragmentIdentifier = url.find('#');
     if (startOfFragmentIdentifier == kNotFound)
         return KURL();
 
     // Exclude the '#' character when determining the fragmentIdentifier.
-    fragmentIdentifier = url.substring(startOfFragmentIdentifier + 1);
+    fragmentIdentifier = AtomicString(url.substring(startOfFragmentIdentifier + 1));
     if (startOfFragmentIdentifier) {
         KURL base(document.baseURI(), url.substring(0, startOfFragmentIdentifier));
         return KURL(base, url.substring(startOfFragmentIdentifier));
@@ -71,10 +68,10 @@
     return KURL(document.baseURI(), url.substring(startOfFragmentIdentifier));
 }
 
-Element* SVGURIReference::targetElementFromIRIString(const String& iri, const Document& document, String* fragmentIdentifier, Document* externalDocument)
+Element* SVGURIReference::targetElementFromIRIString(const String& iri, const Document& document, AtomicString* fragmentIdentifier, Document* externalDocument)
 {
     // If there's no fragment identifier contained within the IRI string, we can't lookup an element.
-    String id;
+    AtomicString id;
     KURL url = urlFromIRIStringWithFragmentIdentifier(iri, document, id);
     if (url == KURL())
         return 0;
@@ -103,4 +100,13 @@
     supportedAttributes.add(XLinkNames::hrefAttr);
 }
 
+bool SVGURIReference::parseAttribute(const QualifiedName& name, const AtomicString& value, SVGParsingError& parseError)
+{
+    if (name.matches(XLinkNames::hrefAttr)) {
+        m_href->setBaseValueAsString(value, parseError);
+        return true;
+    }
+    return false;
+}
+
 }
diff --git a/Source/core/svg/SVGURIReference.h b/Source/core/svg/SVGURIReference.h
index f73a23b..93d4d07 100644
--- a/Source/core/svg/SVGURIReference.h
+++ b/Source/core/svg/SVGURIReference.h
@@ -22,6 +22,7 @@
 #define SVGURIReference_h
 
 #include "core/dom/Document.h"
+#include "core/svg/SVGAnimatedString.h"
 
 namespace WebCore {
 
@@ -32,12 +33,11 @@
 public:
     virtual ~SVGURIReference() { }
 
-    bool parseAttribute(const QualifiedName&, const AtomicString&);
     bool isKnownAttribute(const QualifiedName&);
     void addSupportedAttributes(HashSet<QualifiedName>&);
 
-    static String fragmentIdentifierFromIRIString(const String&, const Document&);
-    static Element* targetElementFromIRIString(const String&, const Document&, String* = 0, Document* = 0);
+    static AtomicString fragmentIdentifierFromIRIString(const String&, const Document&);
+    static Element* targetElementFromIRIString(const String&, const Document&, AtomicString* = 0, Document* = 0);
 
     static inline bool isExternalURIReference(const String& uri, const Document& document)
     {
@@ -50,8 +50,19 @@
         return !equalIgnoringFragmentIdentifier(url, document.url());
     }
 
+    // SVGURIReference JS API.
+    static SVGAnimatedString* href(SVGURIReference* object) { return object->href(); }
+
+    SVGAnimatedString* href() const { return m_href.get(); }
+    const String& hrefString() const { return m_href->currentValue()->value(); }
+
+    bool parseAttribute(const QualifiedName&, const AtomicString& value, SVGParsingError&);
+
 protected:
-    virtual void setHrefBaseValue(const String&) = 0;
+    explicit SVGURIReference(SVGElement*);
+
+private:
+    RefPtr<SVGAnimatedString> m_href;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGURIReference.idl b/Source/core/svg/SVGURIReference.idl
index bcc0efa..2e2d49f 100644
--- a/Source/core/svg/SVGURIReference.idl
+++ b/Source/core/svg/SVGURIReference.idl
@@ -25,8 +25,7 @@
  */
 
 [
-    NoInterfaceObject,
-    LegacyImplementedInBaseClass
+    NoInterfaceObject
 ] interface SVGURIReference {
     readonly attribute SVGAnimatedString href;
 };
diff --git a/Source/core/svg/SVGUnknownElement.h b/Source/core/svg/SVGUnknownElement.h
index 93dd832..8e6e73d 100644
--- a/Source/core/svg/SVGUnknownElement.h
+++ b/Source/core/svg/SVGUnknownElement.h
@@ -41,7 +41,7 @@
 //
 // The main purpose of this class at the moment is to override rendererIsNeeded() to return
 // false to make sure we don't attempt to render such elements.
-class SVGUnknownElement : public SVGElement {
+class SVGUnknownElement FINAL : public SVGElement {
 public:
     static PassRefPtr<SVGUnknownElement> create(const QualifiedName& tagName, Document& document)
     {
diff --git a/Source/core/svg/SVGUseElement.cpp b/Source/core/svg/SVGUseElement.cpp
index 3afd6f3..5f27308 100644
--- a/Source/core/svg/SVGUseElement.cpp
+++ b/Source/core/svg/SVGUseElement.cpp
@@ -52,29 +52,18 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::xAttr, X, x)
-DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::yAttr, Y, y)
-DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::widthAttr, Width, width)
-DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::heightAttr, Height, height)
-DEFINE_ANIMATED_STRING(SVGUseElement, XLinkNames::hrefAttr, Href, href)
-DEFINE_ANIMATED_BOOLEAN(SVGUseElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGUseElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(x)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(y)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(width)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(height)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGUseElement::SVGUseElement(Document& document, bool wasInsertedByParser)
     : SVGGraphicsElement(SVGNames::useTag, document)
-    , m_x(LengthModeWidth)
-    , m_y(LengthModeHeight)
-    , m_width(LengthModeWidth)
-    , m_height(LengthModeHeight)
+    , SVGURIReference(this)
+    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth)))
+    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight)))
+    , m_width(SVGAnimatedLength::create(this, SVGNames::widthAttr, SVGLength::create(LengthModeWidth)))
+    , m_height(SVGAnimatedLength::create(this, SVGNames::heightAttr, SVGLength::create(LengthModeHeight)))
     , m_wasInsertedByParser(wasInsertedByParser)
     , m_haveFiredLoadEvent(false)
     , m_needsShadowTreeRecreation(false)
@@ -82,6 +71,11 @@
 {
     ASSERT(hasCustomStyleCallbacks());
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_x);
+    addToPropertyMap(m_y);
+    addToPropertyMap(m_width);
+    addToPropertyMap(m_height);
     registerAnimatedPropertiesForSVGUseElement();
 }
 
@@ -122,8 +116,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGLangSpace::addSupportedAttributes(supportedAttributes);
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         SVGURIReference::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::xAttr);
         supportedAttributes.add(SVGNames::yAttr);
@@ -137,21 +129,20 @@
 {
     SVGParsingError parseError = NoError;
 
-    if (!isSupportedAttribute(name))
+    if (!isSupportedAttribute(name)) {
         SVGGraphicsElement::parseAttribute(name, value);
-    else if (name == SVGNames::xAttr)
-        setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
-    else if (name == SVGNames::yAttr)
-        setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (name == SVGNames::widthAttr)
-        setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
-    else if (name == SVGNames::heightAttr)
-        setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGLangSpace::parseAttribute(name, value)
-             || SVGExternalResourcesRequired::parseAttribute(name, value)
-             || SVGURIReference::parseAttribute(name, value)) {
-    } else
+    } else if (name == SVGNames::xAttr) {
+        m_x->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::yAttr) {
+        m_y->setBaseValueAsString(value, AllowNegativeLengths, parseError);
+    } else if (name == SVGNames::widthAttr) {
+        m_width->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (name == SVGNames::heightAttr) {
+        m_height->setBaseValueAsString(value, ForbidNegativeLengths, parseError);
+    } else if (SVGURIReference::parseAttribute(name, value, parseError)) {
+    } else {
         ASSERT_NOT_REACHED();
+    }
 
     reportAttributeParsingError(parseError, name, value);
 }
@@ -159,7 +150,7 @@
 #if !ASSERT_DISABLED
 static inline bool isWellFormedDocument(Document* document)
 {
-    if (document->isSVGDocument() || document->isXHTMLDocument())
+    if (document->isXMLDocument())
         return static_cast<XMLDocumentParser*>(document->parser())->wellFormed();
     return true;
 }
@@ -173,9 +164,13 @@
         return InsertionDone;
     ASSERT(!m_targetElementInstance || !isWellFormedDocument(&document()));
     ASSERT(!hasPendingResources() || !isWellFormedDocument(&document()));
-    if (!m_wasInsertedByParser)
+    if (!m_wasInsertedByParser) {
         buildPendingResource();
-    SVGExternalResourcesRequired::insertedIntoDocument(this);
+
+        if (!isStructurallyExternal()) {
+            sendSVGLoadEventIfPossibleAsynchronously();
+        }
+    }
     return InsertionDone;
 }
 
@@ -188,7 +183,7 @@
 
 Document* SVGUseElement::referencedDocument() const
 {
-    if (!isExternalURIReference(hrefCurrentValue(), document()))
+    if (!isExternalURIReference(hrefString(), document()))
         return &document();
     return externalDocument();
 }
@@ -225,13 +220,10 @@
         return;
     }
 
-    if (SVGExternalResourcesRequired::handleAttributeChange(this, attrName))
-        return;
-
     if (SVGURIReference::isKnownAttribute(attrName)) {
-        bool isExternalReference = isExternalURIReference(hrefCurrentValue(), document());
+        bool isExternalReference = isExternalURIReference(hrefString(), document());
         if (isExternalReference) {
-            KURL url = document().completeURL(hrefCurrentValue());
+            KURL url = document().completeURL(hrefString());
             if (url.hasFragmentIdentifier()) {
                 FetchRequest request(ResourceRequest(url.string()), localName());
                 setDocumentResource(document().fetcher()->fetchSVGDocument(request));
@@ -249,28 +241,9 @@
     if (!renderer)
         return;
 
-    if (SVGLangSpace::isKnownAttribute(attrName)
-        || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
-        invalidateShadowTree();
-        return;
-    }
-
     ASSERT_NOT_REACHED();
 }
 
-void SVGUseElement::attach(const AttachContext& context)
-{
-    if (m_needsShadowTreeRecreation)
-        buildPendingResource();
-    SVGGraphicsElement::attach(context);
-}
-
-void SVGUseElement::willRecalcStyle(StyleRecalcChange)
-{
-    if (!m_wasInsertedByParser && m_needsShadowTreeRecreation && renderer() && needsStyleRecalc())
-        buildPendingResource();
-}
-
 #ifdef DUMP_INSTANCE_TREE
 static void dumpInstanceTree(unsigned int& depth, String& text, SVGElementInstance* targetInstance)
 {
@@ -379,6 +352,14 @@
     return false;
 }
 
+void SVGUseElement::scheduleShadowTreeRecreation()
+{
+    if (!referencedDocument() || isInShadowTree())
+        return;
+    m_needsShadowTreeRecreation = true;
+    document().scheduleUseShadowTreeUpdate(*this);
+}
+
 void SVGUseElement::clearResourceReferences()
 {
     // FIXME: We should try to optimize this, to at least allow partial reclones.
@@ -391,6 +372,7 @@
     }
 
     m_needsShadowTreeRecreation = false;
+    document().unscheduleUseShadowTreeUpdate(*this);
 
     document().accessSVGExtensions()->removeAllTargetReferencesForElement(this);
 }
@@ -403,8 +385,8 @@
     if (!inDocument())
         return;
 
-    String id;
-    Element* target = SVGURIReference::targetElementFromIRIString(hrefCurrentValue(), document(), &id, externalDocument());
+    AtomicString id;
+    Element* target = SVGURIReference::targetElementFromIRIString(hrefString(), document(), &id, externalDocument());
     if (!target || !target->inDocument()) {
         // If we can't find the target of an external element, just give up.
         // We can't observe if the target somewhen enters the external document, nor should we do it.
@@ -557,7 +539,7 @@
             toSVGGraphicsElement(n)->toClipPath(path);
             // FIXME: Avoid manual resolution of x/y here. Its potentially harmful.
             SVGLengthContext lengthContext(this);
-            path.translate(FloatSize(xCurrentValue().value(lengthContext), yCurrentValue().value(lengthContext)));
+            path.translate(FloatSize(m_x->currentValue()->value(lengthContext), m_y->currentValue()->value(lengthContext)));
             path.transform(animatedLocalTransform());
         }
     }
@@ -639,7 +621,7 @@
 bool SVGUseElement::hasCycleUseReferencing(SVGUseElement* use, SVGElementInstance* targetInstance, SVGElement*& newTarget)
 {
     ASSERT(referencedDocument());
-    Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefCurrentValue(), *referencedDocument());
+    Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefString(), *referencedDocument());
     newTarget = 0;
     if (targetElement && targetElement->isSVGElement())
         newTarget = toSVGElement(targetElement);
@@ -713,7 +695,7 @@
         ASSERT(!use->resourceIsStillLoading());
 
         ASSERT(referencedDocument());
-        Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefCurrentValue(), *referencedDocument());
+        Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefString(), *referencedDocument());
         SVGElement* target = 0;
         if (targetElement && targetElement->isSVGElement())
             target = toSVGElement(targetElement);
@@ -829,12 +811,13 @@
 
     if (originalElement->hasTagName(SVGNames::useTag)) {
         // <use> gets replaced by <g>
-        ASSERT(target->nodeName() == SVGNames::gTag);
+        ASSERT(AtomicString(target->nodeName()) == SVGNames::gTag);
     } else if (originalElement->hasTagName(SVGNames::symbolTag)) {
         // <symbol> gets replaced by <svg>
-        ASSERT(target->nodeName() == SVGNames::svgTag);
-    } else
-        ASSERT(target->nodeName() == originalElement->nodeName());
+        ASSERT(AtomicString(target->nodeName()) == SVGNames::svgTag);
+    } else {
+        ASSERT(AtomicString(target->nodeName()) == originalElement->nodeName());
+    }
 
     SVGElement* element = 0;
     if (target->isSVGElement())
@@ -893,8 +876,7 @@
 {
     if (!inActiveDocument() || m_needsShadowTreeRecreation)
         return;
-    m_needsShadowTreeRecreation = true;
-    setNeedsStyleRecalc();
+    scheduleShadowTreeRecreation();
     invalidateDependentShadowTrees();
 }
 
@@ -927,10 +909,10 @@
 
 bool SVGUseElement::selfHasRelativeLengths() const
 {
-    if (xCurrentValue().isRelative()
-        || yCurrentValue().isRelative()
-        || widthCurrentValue().isRelative()
-        || heightCurrentValue().isRelative())
+    if (m_x->currentValue()->isRelative()
+        || m_y->currentValue()->isRelative()
+        || m_width->currentValue()->isRelative()
+        || m_height->currentValue()->isRelative())
         return true;
 
     if (!m_targetElementInstance)
@@ -951,8 +933,16 @@
     invalidateShadowTree();
     if (resource->errorOccurred())
         dispatchEvent(Event::create(EventTypeNames::error));
-    else if (!resource->wasCanceled())
-        SVGExternalResourcesRequired::dispatchLoadEvent(this);
+    else if (!resource->wasCanceled()) {
+        if (m_wasInsertedByParser && m_haveFiredLoadEvent)
+            return;
+        if (!isStructurallyExternal())
+            return;
+
+        ASSERT(!m_haveFiredLoadEvent);
+        m_haveFiredLoadEvent = true;
+        sendSVGLoadEventIfPossible();
+    }
 }
 
 bool SVGUseElement::resourceIsStillLoading()
@@ -978,7 +968,6 @@
 void SVGUseElement::finishParsingChildren()
 {
     SVGGraphicsElement::finishParsingChildren();
-    SVGExternalResourcesRequired::finishParsingChildren();
     if (m_wasInsertedByParser) {
         buildPendingResource();
         m_wasInsertedByParser = false;
diff --git a/Source/core/svg/SVGUseElement.h b/Source/core/svg/SVGUseElement.h
index 800af8f..a7a0d5e 100644
--- a/Source/core/svg/SVGUseElement.h
+++ b/Source/core/svg/SVGUseElement.h
@@ -25,7 +25,6 @@
 #include "core/fetch/DocumentResource.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGURIReference.h"
 
@@ -35,7 +34,6 @@
 class SVGElementInstance;
 
 class SVGUseElement FINAL : public SVGGraphicsElement,
-                            public SVGExternalResourcesRequired,
                             public SVGURIReference,
                             public DocumentResourceClient {
 public:
@@ -50,34 +48,39 @@
 
     RenderObject* rendererClipChild() const;
 
+    SVGAnimatedLength* x() const { return m_x.get(); }
+    SVGAnimatedLength* y() const { return m_y.get(); }
+    SVGAnimatedLength* width() const { return m_width.get(); }
+    SVGAnimatedLength* height() const { return m_height.get(); }
+
+    virtual void buildPendingResource() OVERRIDE;
+
 private:
     SVGUseElement(Document&, bool wasInsertedByParser);
 
-    virtual bool isValid() const { return SVGTests::isValid(); }
+    virtual bool isStructurallyExternal() const OVERRIDE { return !hrefString().isNull() && isExternalURIReference(hrefString(), document()); }
+
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void buildPendingResource();
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
+    virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
-
-    virtual RenderObject* createRenderer(RenderStyle*);
-    virtual void toClipPath(Path&);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+    virtual void toClipPath(Path&) OVERRIDE;
 
     void clearResourceReferences();
     void buildShadowAndInstanceTree(SVGElement* target);
     void detachInstance();
 
-    virtual bool haveLoadedRequiredResources() { return SVGExternalResourcesRequired::haveLoadedRequiredResources(); }
+    void scheduleShadowTreeRecreation();
+    virtual bool haveLoadedRequiredResources() OVERRIDE { return !isStructurallyExternal() || m_haveFiredLoadEvent; }
 
-    virtual void finishParsingChildren();
-    virtual bool selfHasRelativeLengths() const;
+    virtual void finishParsingChildren() OVERRIDE;
+    virtual bool selfHasRelativeLengths() const OVERRIDE;
 
     // Instance tree handling
     void buildInstanceTree(SVGElement* target, SVGElementInstance* targetInstance, bool& foundCycle, bool foundUse);
@@ -96,26 +99,20 @@
     void transferUseAttributesToReplacedElement(SVGElement* from, SVGElement* to) const;
     void transferEventListenersToShadowTree(SVGElementInstance* target);
 
+    RefPtr<SVGAnimatedLength> m_x;
+    RefPtr<SVGAnimatedLength> m_y;
+    RefPtr<SVGAnimatedLength> m_width;
+    RefPtr<SVGAnimatedLength> m_height;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGUseElement)
-        DECLARE_ANIMATED_LENGTH(X, x)
-        DECLARE_ANIMATED_LENGTH(Y, y)
-        DECLARE_ANIMATED_LENGTH(Width, width)
-        DECLARE_ANIMATED_LENGTH(Height, height)
-        DECLARE_ANIMATED_STRING(Href, href)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
     bool resourceIsStillLoading();
     Document* externalDocument() const;
     bool instanceTreeIsLoading(SVGElementInstance*);
-    virtual void notifyFinished(Resource*);
+    virtual void notifyFinished(Resource*) OVERRIDE;
     Document* referencedDocument() const;
     void setDocumentResource(ResourcePtr<DocumentResource>);
 
-    // SVGExternalResourcesRequired
-    virtual void setHaveFiredLoadEvent(bool haveFiredLoadEvent) { m_haveFiredLoadEvent = haveFiredLoadEvent; }
-    virtual bool isParserInserted() const { return m_wasInsertedByParser; }
-    virtual bool haveFiredLoadEvent() const { return m_haveFiredLoadEvent; }
     virtual Timer<SVGElement>* svgLoadEventTimer() OVERRIDE { return &m_svgLoadEventTimer; }
 
     bool m_wasInsertedByParser;
diff --git a/Source/core/svg/SVGUseElement.idl b/Source/core/svg/SVGUseElement.idl
index eb5d82c..9aee55c 100644
--- a/Source/core/svg/SVGUseElement.idl
+++ b/Source/core/svg/SVGUseElement.idl
@@ -33,7 +33,6 @@
     readonly attribute SVGElementInstance animatedInstanceRoot;
 };
 
-SVGUseElement implements SVGExternalResourcesRequired;
 SVGUseElement implements SVGTests;
 SVGUseElement implements SVGURIReference;
 
diff --git a/Source/core/svg/SVGVKernElement.h b/Source/core/svg/SVGVKernElement.h
index f8837bf..d431f06 100644
--- a/Source/core/svg/SVGVKernElement.h
+++ b/Source/core/svg/SVGVKernElement.h
@@ -39,7 +39,7 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGVKernElement, hasTagName(SVGNames::vkernTag));
diff --git a/Source/core/svg/SVGViewElement.cpp b/Source/core/svg/SVGViewElement.cpp
index c72604a..f3dcb44 100644
--- a/Source/core/svg/SVGViewElement.cpp
+++ b/Source/core/svg/SVGViewElement.cpp
@@ -22,27 +22,22 @@
 
 #include "core/svg/SVGViewElement.h"
 
-
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_BOOLEAN(SVGViewElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
-DEFINE_ANIMATED_RECT(SVGViewElement, SVGNames::viewBoxAttr, ViewBox, viewBox)
-DEFINE_ANIMATED_PRESERVEASPECTRATIO(SVGViewElement, SVGNames::preserveAspectRatioAttr, PreserveAspectRatio, preserveAspectRatio)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGViewElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(viewBox)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAspectRatio)
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGViewElement::SVGViewElement(Document& document)
     : SVGElement(SVGNames::viewTag, document)
-    , m_zoomAndPan(SVGZoomAndPanMagnify)
-    , m_viewTarget(SVGNames::viewTargetAttr)
+    , SVGFitToViewBox(this)
+    , m_viewTarget(SVGStaticStringList::create(this, SVGNames::viewTargetAttr))
 {
     ScriptWrappable::init(this);
+
+    addToPropertyMap(m_viewTarget);
     registerAnimatedPropertiesForSVGViewElement();
 }
 
@@ -55,7 +50,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         SVGFitToViewBox::addSupportedAttributes(supportedAttributes);
         SVGZoomAndPan::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::viewTargetAttr);
@@ -70,19 +64,17 @@
         return;
     }
 
-    if (name == SVGNames::viewTargetAttr) {
-        viewTarget().reset(value);
-        return;
+    SVGParsingError parseError = NoError;
+
+    if (SVGFitToViewBox::parseAttribute(name, value, document(), parseError)) {
+    } else if (SVGZoomAndPan::parseAttribute(name, value)) {
+    } else if (name == SVGNames::viewTargetAttr) {
+        m_viewTarget->setBaseValueAsString(value, parseError);
+    } else {
+        ASSERT_NOT_REACHED();
     }
 
-    if (SVGExternalResourcesRequired::parseAttribute(name, value))
-        return;
-    if (SVGFitToViewBox::parseAttribute(this, name, value))
-        return;
-    if (SVGZoomAndPan::parseAttribute(this, name, value))
-        return;
-
-    ASSERT_NOT_REACHED();
+    reportAttributeParsingError(parseError, name, value);
 }
 
 }
diff --git a/Source/core/svg/SVGViewElement.h b/Source/core/svg/SVGViewElement.h
index 3069cbf..9c44814 100644
--- a/Source/core/svg/SVGViewElement.h
+++ b/Source/core/svg/SVGViewElement.h
@@ -23,18 +23,14 @@
 
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
-#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
-#include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFitToViewBox.h"
-#include "core/svg/SVGStringList.h"
+#include "core/svg/SVGStaticStringList.h"
 #include "core/svg/SVGZoomAndPan.h"
 
 namespace WebCore {
 
 class SVGViewElement FINAL : public SVGElement,
-                             public SVGExternalResourcesRequired,
                              public SVGFitToViewBox,
                              public SVGZoomAndPan {
 public:
@@ -43,9 +39,7 @@
     using SVGElement::ref;
     using SVGElement::deref;
 
-    SVGStringList& viewTarget() { return m_viewTarget; }
-    SVGZoomAndPanType zoomAndPan() const { return m_zoomAndPan; }
-    void setZoomAndPan(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
+    SVGStringListTearOff* viewTarget() { return m_viewTarget->tearOff(); }
 
 private:
     explicit SVGViewElement(Document&);
@@ -54,16 +48,11 @@
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
+    RefPtr<SVGStaticStringList> m_viewTarget;
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGViewElement)
-        DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
-        DECLARE_ANIMATED_RECT(ViewBox, viewBox)
-        DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    SVGZoomAndPanType m_zoomAndPan;
-    SVGStringList m_viewTarget;
 };
 
 DEFINE_NODE_TYPE_CASTS(SVGViewElement, hasTagName(SVGNames::viewTag));
diff --git a/Source/core/svg/SVGViewElement.idl b/Source/core/svg/SVGViewElement.idl
index 4b7a25d..7f95023 100644
--- a/Source/core/svg/SVGViewElement.idl
+++ b/Source/core/svg/SVGViewElement.idl
@@ -27,7 +27,6 @@
     readonly attribute SVGStringList viewTarget;
 };
 
-SVGViewElement implements SVGExternalResourcesRequired;
 SVGViewElement implements SVGFitToViewBox;
 SVGViewElement implements SVGZoomAndPan;
 
diff --git a/Source/core/svg/SVGViewSpec.cpp b/Source/core/svg/SVGViewSpec.cpp
index b320107..adcea68 100644
--- a/Source/core/svg/SVGViewSpec.cpp
+++ b/Source/core/svg/SVGViewSpec.cpp
@@ -21,44 +21,12 @@
 #include "core/svg/SVGViewSpec.h"
 
 #include "SVGNames.h"
-#include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/svg/SVGAnimatedTransformList.h"
 #include "core/svg/SVGParserUtilities.h"
 
 namespace WebCore {
 
-// Define custom animated property 'viewBox'.
-const SVGPropertyInfo* SVGViewSpec::viewBoxPropertyInfo()
-{
-    static const SVGPropertyInfo* s_propertyInfo = 0;
-    if (!s_propertyInfo) {
-        s_propertyInfo = new SVGPropertyInfo(AnimatedRect,
-                                             PropertyIsReadOnly,
-                                             SVGNames::viewBoxAttr,
-                                             viewBoxIdentifier(),
-                                             0,
-                                             0);
-    }
-    return s_propertyInfo;
-}
-
-// Define custom animated property 'preserveAspectRatio'.
-const SVGPropertyInfo* SVGViewSpec::preserveAspectRatioPropertyInfo()
-{
-    static const SVGPropertyInfo* s_propertyInfo = 0;
-    if (!s_propertyInfo) {
-        s_propertyInfo = new SVGPropertyInfo(AnimatedPreserveAspectRatio,
-                                             PropertyIsReadOnly,
-                                             SVGNames::preserveAspectRatioAttr,
-                                             preserveAspectRatioIdentifier(),
-                                             0,
-                                             0);
-    }
-    return s_propertyInfo;
-}
-
-
 // Define custom non-animated property 'transform'.
 const SVGPropertyInfo* SVGViewSpec::transformPropertyInfo()
 {
@@ -74,24 +42,19 @@
     return s_propertyInfo;
 }
 
-SVGViewSpec::SVGViewSpec(WeakPtr<SVGSVGElement> contextElement)
-    : m_contextElement(contextElement)
-    , m_zoomAndPan(SVGZoomAndPanMagnify)
+SVGViewSpec::SVGViewSpec(SVGSVGElement* contextElement)
+    // Note: We make |viewBox| and |preserveAspectRatio|'s contextElement the target element of SVGViewSpec.
+    // This contextElement will be only used for keeping this alive from the tearoff.
+    // SVGSVGElement holds a strong-ref to this SVGViewSpec, so this is kept alive as:
+    // AnimatedProperty tearoff -(contextElement)-> SVGSVGElement -(RefPtr)-> SVGViewSpec.
+    : SVGFitToViewBox(contextElement, PropertyMapPolicySkip) // Note: addToPropertyMap is not needed, as SVGViewSpec do not correspond to an element.
+    , m_contextElement(contextElement)
 {
     ASSERT(m_contextElement);
     ScriptWrappable::init(this);
-}
 
-const AtomicString& SVGViewSpec::viewBoxIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGViewSpecViewBoxAttribute", AtomicString::ConstructFromLiteral));
-    return s_identifier;
-}
-
-const AtomicString& SVGViewSpec::preserveAspectRatioIdentifier()
-{
-    DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGViewSpecPreserveAspectRatioAttribute", AtomicString::ConstructFromLiteral));
-    return s_identifier;
+    viewBox()->setReadOnly();
+    preserveAspectRatio()->setReadOnly();
 }
 
 const AtomicString& SVGViewSpec::transformIdentifier()
@@ -100,10 +63,9 @@
     return s_identifier;
 }
 
-void SVGViewSpec::setZoomAndPan(unsigned short, ExceptionState& exceptionState)
+String SVGViewSpec::preserveAspectRatioString() const
 {
-    // SVGViewSpec and all of its content is read-only.
-    exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+    return preserveAspectRatio()->baseValue()->valueAsString();
 }
 
 void SVGViewSpec::setTransformString(const String& transform)
@@ -114,7 +76,7 @@
     SVGTransformList newList;
     newList.parse(transform);
 
-    if (SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGElement, SVGAnimatedTransformList>(m_contextElement.get(), transformPropertyInfo()))
+    if (SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGElement, SVGAnimatedTransformList>(m_contextElement, transformPropertyInfo()))
         static_cast<SVGAnimatedTransformList*>(wrapper)->detachListWrappers(newList.size());
 
     m_transform = newList;
@@ -127,19 +89,14 @@
 
 String SVGViewSpec::viewBoxString() const
 {
-    return SVGPropertyTraits<SVGRect>::toString(viewBoxBaseValue());
-}
-
-String SVGViewSpec::preserveAspectRatioString() const
-{
-    return SVGPropertyTraits<SVGPreserveAspectRatio>::toString(preserveAspectRatioBaseValue());
+    return viewBox()->currentValue()->valueAsString();
 }
 
 SVGElement* SVGViewSpec::viewTarget() const
 {
     if (!m_contextElement)
         return 0;
-    Element* element = m_contextElement.get()->treeScope().getElementById(m_viewTargetString);
+    Element* element = m_contextElement->treeScope().getElementById(AtomicString(m_viewTargetString));
     if (!element || !element->isSVGElement())
         return 0;
     return toSVGElement(element);
@@ -153,34 +110,6 @@
     return static_cast<SVGTransformListPropertyTearOff*>(static_pointer_cast<SVGAnimatedTransformList>(lookupOrCreateTransformWrapper(this))->animVal());
 }
 
-PassRefPtr<SVGAnimatedRect> SVGViewSpec::viewBox()
-{
-    if (!m_contextElement)
-        return 0;
-    return static_pointer_cast<SVGAnimatedRect>(lookupOrCreateViewBoxWrapper(this));
-}
-
-PassRefPtr<SVGAnimatedPreserveAspectRatio> SVGViewSpec::preserveAspectRatio()
-{
-    if (!m_contextElement)
-        return 0;
-    return static_pointer_cast<SVGAnimatedPreserveAspectRatio>(lookupOrCreatePreserveAspectRatioWrapper(this));
-}
-
-PassRefPtr<SVGAnimatedProperty> SVGViewSpec::lookupOrCreateViewBoxWrapper(SVGViewSpec* ownerType)
-{
-    ASSERT(ownerType);
-    ASSERT(ownerType->contextElement());
-    return SVGAnimatedProperty::lookupOrCreateWrapper<SVGElement, SVGAnimatedRect, SVGRect>(ownerType->contextElement(), viewBoxPropertyInfo(), ownerType->m_viewBox);
-}
-
-PassRefPtr<SVGAnimatedProperty> SVGViewSpec::lookupOrCreatePreserveAspectRatioWrapper(SVGViewSpec* ownerType)
-{
-    ASSERT(ownerType);
-    ASSERT(ownerType->contextElement());
-    return SVGAnimatedProperty::lookupOrCreateWrapper<SVGElement, SVGAnimatedPreserveAspectRatio, SVGPreserveAspectRatio>(ownerType->contextElement(), preserveAspectRatioPropertyInfo(), ownerType->m_preserveAspectRatio);
-}
-
 PassRefPtr<SVGAnimatedProperty> SVGViewSpec::lookupOrCreateTransformWrapper(SVGViewSpec* ownerType)
 {
     ASSERT(ownerType);
@@ -188,12 +117,21 @@
     return SVGAnimatedProperty::lookupOrCreateWrapper<SVGElement, SVGAnimatedTransformList, SVGTransformList>(ownerType->contextElement(), transformPropertyInfo(), ownerType->m_transform);
 }
 
+void SVGViewSpec::detachContextElement()
+{
+    clearViewBox();
+    clearPreserveAspectRatio();
+    m_contextElement = 0;
+}
+
 void SVGViewSpec::reset()
 {
-    m_zoomAndPan = SVGZoomAndPanMagnify;
+    resetZoomAndPan();
     m_transform.clear();
-    m_viewBox = SVGRect();
-    m_preserveAspectRatio = SVGPreserveAspectRatio();
+    updateViewBox(FloatRect());
+    ASSERT(preserveAspectRatio());
+    preserveAspectRatio()->baseValue()->setAlign(SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMID);
+    preserveAspectRatio()->baseValue()->setMeetOrSlice(SVGPreserveAspectRatio::SVG_MEETORSLICE_MEET);
     m_viewTargetString = emptyString();
 }
 
@@ -220,10 +158,13 @@
                 if (ptr >= end || *ptr != '(')
                     return false;
                 ptr++;
-                SVGRect viewBox;
-                if (!SVGFitToViewBox::parseViewBox(&m_contextElement.get()->document(), ptr, end, viewBox, false))
+                float x = 0.0f;
+                float y = 0.0f;
+                float width = 0.0f;
+                float height = 0.0f;
+                if (!(parseNumber(ptr, end, x) && parseNumber(ptr, end, y) && parseNumber(ptr, end, width) && parseNumber(ptr, end, height, false)))
                     return false;
-                setViewBoxBaseValue(viewBox);
+                updateViewBox(FloatRect(x, y, width, height));
                 if (ptr >= end || *ptr != ')')
                     return false;
                 ptr++;
@@ -245,7 +186,7 @@
             if (ptr >= end || *ptr != '(')
                 return false;
             ptr++;
-            if (!parseZoomAndPan(ptr, end, m_zoomAndPan))
+            if (!parseZoomAndPan(ptr, end))
                 return false;
             if (ptr >= end || *ptr != ')')
                 return false;
@@ -256,10 +197,8 @@
             if (ptr >= end || *ptr != '(')
                 return false;
             ptr++;
-            SVGPreserveAspectRatio preserveAspectRatio;
-            if (!preserveAspectRatio.parse(ptr, end, false))
+            if (!preserveAspectRatio()->baseValue()->parse(ptr, end, false))
                 return false;
-            setPreserveAspectRatioBaseValue(preserveAspectRatio);
             if (ptr >= end || *ptr != ')')
                 return false;
             ptr++;
diff --git a/Source/core/svg/SVGViewSpec.h b/Source/core/svg/SVGViewSpec.h
index c5d742f..a3e9473 100644
--- a/Source/core/svg/SVGViewSpec.h
+++ b/Source/core/svg/SVGViewSpec.h
@@ -21,8 +21,6 @@
 #define SVGViewSpec_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
-#include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGFitToViewBox.h"
 #include "core/svg/SVGSVGElement.h"
 #include "core/svg/SVGTransformList.h"
@@ -31,7 +29,6 @@
 
 namespace WebCore {
 
-class ExceptionState;
 class SVGTransformListPropertyTearOff;
 
 class SVGViewSpec FINAL : public RefCounted<SVGViewSpec>, public ScriptWrappable, public SVGZoomAndPan, public SVGFitToViewBox {
@@ -39,7 +36,7 @@
     using RefCounted<SVGViewSpec>::ref;
     using RefCounted<SVGViewSpec>::deref;
 
-    static PassRefPtr<SVGViewSpec> create(WeakPtr<SVGSVGElement> contextElement)
+    static PassRefPtr<SVGViewSpec> create(SVGSVGElement* contextElement)
     {
         return adoptRef(new SVGViewSpec(contextElement));
     }
@@ -58,53 +55,28 @@
     void setViewTargetString(const String& string) { m_viewTargetString = string; }
     String viewTargetString() const { return m_viewTargetString; }
 
-    SVGZoomAndPanType zoomAndPan() const { return m_zoomAndPan; }
-    void setZoomAndPan(unsigned short zoomAndPan) { setZoomAndPanBaseValue(zoomAndPan); }
-    void setZoomAndPan(unsigned short, ExceptionState&);
-    void setZoomAndPanBaseValue(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
-
-    SVGElement* contextElement() const { return m_contextElement.get(); }
+    SVGElement* contextElement() const { return m_contextElement; }
+    void detachContextElement();
 
     // Custom non-animated 'transform' property.
     SVGTransformListPropertyTearOff* transform();
     SVGTransformList transformBaseValue() const { return m_transform; }
 
-    // Custom animated 'viewBox' property.
-    PassRefPtr<SVGAnimatedRect> viewBox();
-    SVGRect& viewBoxCurrentValue() { return m_viewBox; }
-    SVGRect viewBoxBaseValue() const { return m_viewBox; }
-    void setViewBoxBaseValue(const SVGRect& viewBox) { m_viewBox = viewBox; }
-
-    // Custom animated 'preserveAspectRatio' property.
-    PassRefPtr<SVGAnimatedPreserveAspectRatio> preserveAspectRatio();
-    SVGPreserveAspectRatio& preserveAspectRatioCurrentValue() { return m_preserveAspectRatio; }
-    SVGPreserveAspectRatio preserveAspectRatioBaseValue() const { return m_preserveAspectRatio; }
-    void setPreserveAspectRatioBaseValue(const SVGPreserveAspectRatio& preserveAspectRatio) { m_preserveAspectRatio = preserveAspectRatio; }
-
 private:
-    explicit SVGViewSpec(WeakPtr<SVGSVGElement>);
+    explicit SVGViewSpec(SVGSVGElement*);
 
     static const SVGPropertyInfo* transformPropertyInfo();
-    static const SVGPropertyInfo* viewBoxPropertyInfo();
-    static const SVGPropertyInfo* preserveAspectRatioPropertyInfo();
 
     static const AtomicString& transformIdentifier();
-    static const AtomicString& viewBoxIdentifier();
-    static const AtomicString& preserveAspectRatioIdentifier();
 
     static PassRefPtr<SVGAnimatedProperty> lookupOrCreateTransformWrapper(SVGViewSpec* contextElement);
-    static PassRefPtr<SVGAnimatedProperty> lookupOrCreateViewBoxWrapper(SVGViewSpec* contextElement);
-    static PassRefPtr<SVGAnimatedProperty> lookupOrCreatePreserveAspectRatioWrapper(SVGViewSpec* contextElement);
 
     template<typename CharType>
     bool parseViewSpecInternal(const CharType* ptr, const CharType* end);
 
-    WeakPtr<SVGSVGElement> m_contextElement;
-
-    SVGZoomAndPanType m_zoomAndPan;
+    // FIXME(oilpan): This is back-ptr to be cleared from contextElement.
+    SVGSVGElement* m_contextElement;
     SVGTransformList m_transform;
-    SVGRect m_viewBox;
-    SVGPreserveAspectRatio m_preserveAspectRatio;
     String m_viewTargetString;
 };
 
diff --git a/Source/core/svg/SVGViewSpec.idl b/Source/core/svg/SVGViewSpec.idl
index 80b1d80..f5bb3a4 100644
--- a/Source/core/svg/SVGViewSpec.idl
+++ b/Source/core/svg/SVGViewSpec.idl
@@ -30,10 +30,7 @@
       readonly attribute DOMString preserveAspectRatioString;
       readonly attribute DOMString transformString;
       readonly attribute DOMString viewTargetString;
-
-      // SVGZoomAndPan
-      [RaisesException=Setter] attribute unsigned short zoomAndPan;
 };
 
 SVGViewSpec implements SVGFitToViewBox;
-
+SVGViewSpec implements SVGZoomAndPan;
diff --git a/Source/core/svg/SVGZoomAndPan.cpp b/Source/core/svg/SVGZoomAndPan.cpp
index 450152c..714d043 100644
--- a/Source/core/svg/SVGZoomAndPan.cpp
+++ b/Source/core/svg/SVGZoomAndPan.cpp
@@ -1,6 +1,7 @@
 /*
  * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
  * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -19,13 +20,24 @@
  */
 
 #include "config.h"
-
 #include "core/svg/SVGZoomAndPan.h"
 
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionState.h"
 #include "core/svg/SVGParserUtilities.h"
 
 namespace WebCore {
 
+SVGZoomAndPan::SVGZoomAndPan()
+    : m_zoomAndPan(SVGZoomAndPanMagnify)
+{
+}
+
+void SVGZoomAndPan::resetZoomAndPan()
+{
+    m_zoomAndPan = SVGZoomAndPanMagnify;
+}
+
 bool SVGZoomAndPan::isKnownAttribute(const QualifiedName& attrName)
 {
     return attrName == SVGNames::zoomAndPanAttr;
@@ -53,29 +65,20 @@
     return false;
 }
 
-bool SVGZoomAndPan::parseZoomAndPan(const LChar*& start, const LChar* end, SVGZoomAndPanType& zoomAndPan)
+bool SVGZoomAndPan::parseZoomAndPan(const LChar*& start, const LChar* end)
 {
-    return parseZoomAndPanInternal(start, end, zoomAndPan);
+    return parseZoomAndPanInternal(start, end, m_zoomAndPan);
 }
 
-bool SVGZoomAndPan::parseZoomAndPan(const UChar*& start, const UChar* end, SVGZoomAndPanType& zoomAndPan)
+bool SVGZoomAndPan::parseZoomAndPan(const UChar*& start, const UChar* end)
 {
-    return parseZoomAndPanInternal(start, end, zoomAndPan);
+    return parseZoomAndPanInternal(start, end, m_zoomAndPan);
 }
 
-NO_RETURN_DUE_TO_ASSERT void SVGZoomAndPan::ref()
+void SVGZoomAndPan::setZoomAndPan(SVGViewSpec*, unsigned short, ExceptionState& exceptionState)
 {
-    ASSERT_NOT_REACHED();
-}
-
-NO_RETURN_DUE_TO_ASSERT void SVGZoomAndPan::deref()
-{
-    ASSERT_NOT_REACHED();
-}
-
-NO_RETURN_DUE_TO_ASSERT void SVGZoomAndPan::setZoomAndPan(unsigned short)
-{
-    ASSERT_NOT_REACHED();
+    // SVGViewSpec and all of its content is read-only.
+    exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::readOnly());
 }
 
 }
diff --git a/Source/core/svg/SVGZoomAndPan.h b/Source/core/svg/SVGZoomAndPan.h
index b1432eb..5b5c69c 100644
--- a/Source/core/svg/SVGZoomAndPan.h
+++ b/Source/core/svg/SVGZoomAndPan.h
@@ -1,6 +1,7 @@
 /*
  * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
  * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
+ * Copyright (C) 2014 Samsung Electronics. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -27,6 +28,9 @@
 
 namespace WebCore {
 
+class ExceptionState;
+class SVGViewSpec;
+
 enum SVGZoomAndPanType {
     SVGZoomAndPanUnknown = 0,
     SVGZoomAndPanDisable,
@@ -52,38 +56,42 @@
         return static_cast<SVGZoomAndPanType>(number);
     }
 
-    static bool parseZoomAndPan(const LChar*& start, const LChar* end, SVGZoomAndPanType&);
-    static bool parseZoomAndPan(const UChar*& start, const UChar* end, SVGZoomAndPanType&);
+    bool parseZoomAndPan(const LChar*& start, const LChar* end);
+    bool parseZoomAndPan(const UChar*& start, const UChar* end);
 
-    template<class SVGElementTarget>
-    static bool parseAttribute(SVGElementTarget* target, const QualifiedName& name, const AtomicString& value)
+    bool parseAttribute(const QualifiedName& name, const AtomicString& value)
     {
-        ASSERT(target);
         if (name == SVGNames::zoomAndPanAttr) {
-            SVGZoomAndPanType zoomAndPan = SVGZoomAndPanUnknown;
+            m_zoomAndPan = SVGZoomAndPanUnknown;
             if (!value.isEmpty()) {
                 if (value.is8Bit()) {
                     const LChar* start = value.characters8();
-                    parseZoomAndPan(start, start + value.length(), zoomAndPan);
+                    parseZoomAndPan(start, start + value.length());
                 } else {
                     const UChar* start = value.characters16();
-                    parseZoomAndPan(start, start + value.length(), zoomAndPan);
+                    parseZoomAndPan(start, start + value.length());
                 }
             }
-            target->setZoomAndPan(zoomAndPan);
             return true;
         }
 
         return false;
     }
 
-    SVGZoomAndPanType zoomAndPan() const { return SVGZoomAndPanUnknown; }
+    // SVGZoomAndPan JS API.
+    static SVGZoomAndPanType zoomAndPan(SVGZoomAndPan* object) { return object->m_zoomAndPan; }
+    static void setZoomAndPan(SVGZoomAndPan* object, unsigned short value, ExceptionState&) { object->setZoomAndPan(value); }
+    static void setZoomAndPan(SVGViewSpec*, unsigned short, ExceptionState&);
 
-    // These methods only exist to allow us to compile V8/JSSVGZoomAndPan.*.
-    // These are never called, and thus ASSERT_NOT_REACHED.
-    void ref();
-    void deref();
-    void setZoomAndPan(unsigned short);
+    void setZoomAndPan(unsigned short value) { m_zoomAndPan = parseFromNumber(value); }
+    SVGZoomAndPanType zoomAndPan() const { return m_zoomAndPan; }
+
+protected:
+    SVGZoomAndPan();
+    void resetZoomAndPan();
+
+private:
+    SVGZoomAndPanType m_zoomAndPan;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGZoomAndPan.idl b/Source/core/svg/SVGZoomAndPan.idl
index 42149bd..ae3ab58 100644
--- a/Source/core/svg/SVGZoomAndPan.idl
+++ b/Source/core/svg/SVGZoomAndPan.idl
@@ -25,13 +25,11 @@
  */
 
 [
-    NoInterfaceObject,
-    LegacyImplementedInBaseClass
+    NoInterfaceObject
 ] interface SVGZoomAndPan {
     const unsigned short SVG_ZOOMANDPAN_UNKNOWN = 0;
     const unsigned short SVG_ZOOMANDPAN_DISABLE = 1;
     const unsigned short SVG_ZOOMANDPAN_MAGNIFY = 2;
 
-    attribute unsigned short zoomAndPan;
+    [RaisesException=Setter] attribute unsigned short zoomAndPan;
 };
-
diff --git a/Source/core/svg/SVGZoomEvent.cpp b/Source/core/svg/SVGZoomEvent.cpp
index fe5d283..a65cca3 100644
--- a/Source/core/svg/SVGZoomEvent.cpp
+++ b/Source/core/svg/SVGZoomEvent.cpp
@@ -23,6 +23,8 @@
 #include "core/svg/SVGZoomEvent.h"
 
 #include "core/events/ThreadLocalEventNames.h"
+#include "core/svg/SVGPointTearOff.h"
+#include "core/svg/SVGRectTearOff.h"
 
 namespace WebCore {
 
@@ -33,9 +35,11 @@
     ScriptWrappable::init(this);
 }
 
-SVGRect SVGZoomEvent::zoomRectScreen() const
+PassRefPtr<SVGRectTearOff> SVGZoomEvent::zoomRectScreen() const
 {
-    return m_zoomRectScreen;
+    RefPtr<SVGRectTearOff> rectTearOff = SVGRectTearOff::create(SVGRect::create(), 0, PropertyIsNotAnimVal);
+    rectTearOff->setIsReadOnlyProperty();
+    return rectTearOff.release();
 }
 
 float SVGZoomEvent::previousScale() const
@@ -48,9 +52,11 @@
     m_previousScale = scale;
 }
 
-SVGPoint SVGZoomEvent::previousTranslate() const
+PassRefPtr<SVGPointTearOff> SVGZoomEvent::previousTranslate() const
 {
-    return m_previousTranslate;
+    RefPtr<SVGPointTearOff> pointTearOff = SVGPointTearOff::create(SVGPoint::create(m_previousTranslate), 0, PropertyIsNotAnimVal);
+    pointTearOff->setIsReadOnlyProperty();
+    return pointTearOff.release();
 }
 
 float SVGZoomEvent::newScale() const
@@ -63,9 +69,11 @@
     m_newScale = scale;
 }
 
-SVGPoint SVGZoomEvent::newTranslate() const
+PassRefPtr<SVGPointTearOff> SVGZoomEvent::newTranslate() const
 {
-    return m_newTranslate;
+    RefPtr<SVGPointTearOff> pointTearOff = SVGPointTearOff::create(SVGPoint::create(m_newTranslate), 0, PropertyIsNotAnimVal);
+    pointTearOff->setIsReadOnlyProperty();
+    return pointTearOff.release();
 }
 
 const AtomicString& SVGZoomEvent::interfaceName() const
diff --git a/Source/core/svg/SVGZoomEvent.h b/Source/core/svg/SVGZoomEvent.h
index 59d31ae..c6aaa5c 100644
--- a/Source/core/svg/SVGZoomEvent.h
+++ b/Source/core/svg/SVGZoomEvent.h
@@ -28,24 +28,24 @@
 
 namespace WebCore {
 
-class SVGZoomEvent : public UIEvent {
+class SVGZoomEvent FINAL : public UIEvent {
 public:
     static PassRefPtr<SVGZoomEvent> create() { return adoptRef(new SVGZoomEvent); }
 
     // 'SVGZoomEvent' functions
-    SVGRect zoomRectScreen() const;
+    PassRefPtr<SVGRectTearOff> zoomRectScreen() const;
 
     float previousScale() const;
     void setPreviousScale(float);
 
-    SVGPoint previousTranslate() const;
+    PassRefPtr<SVGPointTearOff> previousTranslate() const;
 
     float newScale() const;
     void setNewScale(float);
 
-    SVGPoint newTranslate() const;
+    PassRefPtr<SVGPointTearOff> newTranslate() const;
 
-    virtual const AtomicString& interfaceName() const;
+    virtual const AtomicString& interfaceName() const OVERRIDE;
 
 private:
     SVGZoomEvent();
@@ -53,10 +53,8 @@
     float m_newScale;
     float m_previousScale;
 
-    SVGRect m_zoomRectScreen;
-
-    SVGPoint m_newTranslate;
-    SVGPoint m_previousTranslate;
+    FloatPoint m_newTranslate;
+    FloatPoint m_previousTranslate;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGZoomEvent.idl b/Source/core/svg/SVGZoomEvent.idl
index 48bb357..bb7e2ac 100644
--- a/Source/core/svg/SVGZoomEvent.idl
+++ b/Source/core/svg/SVGZoomEvent.idl
@@ -26,8 +26,8 @@
 interface SVGZoomEvent : UIEvent {
     readonly attribute SVGRect zoomRectScreen;
     readonly attribute float previousScale;
-    [Immutable] readonly attribute SVGPoint previousTranslate;
+    readonly attribute SVGPoint previousTranslate;
     readonly attribute float newScale;
-    [Immutable] readonly attribute SVGPoint newTranslate;
+    readonly attribute SVGPoint newTranslate;
 };
 
diff --git a/Source/core/svg/animation/SMILTimeContainer.cpp b/Source/core/svg/animation/SMILTimeContainer.cpp
index 71dc1c2..c41555d 100644
--- a/Source/core/svg/animation/SMILTimeContainer.cpp
+++ b/Source/core/svg/animation/SMILTimeContainer.cpp
@@ -54,6 +54,8 @@
 
 SMILTimeContainer::~SMILTimeContainer()
 {
+    cancelAnimationFrame();
+    ASSERT(!m_timer.isActive());
 #ifndef NDEBUG
     ASSERT(!m_preventScheduledAnimationsChanges);
 #endif
@@ -70,7 +72,7 @@
 #endif
 
     ElementAttributePair key(target, attributeName);
-    OwnPtr<AnimationsVector>& scheduled = m_scheduledAnimations.add(key, nullptr).iterator->value;
+    OwnPtr<AnimationsVector>& scheduled = m_scheduledAnimations.add(key, nullptr).storedValue->value;
     if (!scheduled)
         scheduled = adoptPtr(new AnimationsVector);
     ASSERT(!scheduled->contains(animation));
@@ -101,7 +103,7 @@
 {
     // Schedule updateAnimations() to be called asynchronously so multiple intervals
     // can change with updateAnimations() only called once at the end.
-    startTimer(0);
+    scheduleAnimationFrame();
 }
 
 SMILTime SMILTimeContainer::elapsed() const
@@ -115,11 +117,6 @@
     return currentTime() + m_accumulatedActiveTime - lastResumeTime();
 }
 
-bool SMILTimeContainer::isActive() const
-{
-    return m_beginTime && !isPaused();
-}
-
 bool SMILTimeContainer::isPaused() const
 {
     return m_pauseTime;
@@ -143,7 +140,7 @@
 
     if (m_pauseTime) {
         m_pauseTime = now;
-        m_timer.stop();
+        cancelAnimationFrame();
     }
 }
 
@@ -154,7 +151,7 @@
 
     if (m_beginTime) {
         m_accumulatedActiveTime += m_pauseTime - lastResumeTime();
-        m_timer.stop();
+        cancelAnimationFrame();
     }
     m_resumeTime = 0;
 }
@@ -165,7 +162,7 @@
     m_resumeTime = currentTime();
 
     m_pauseTime = 0;
-    startTimer(0);
+    scheduleAnimationFrame();
 }
 
 void SMILTimeContainer::setElapsed(SMILTime time)
@@ -177,7 +174,7 @@
     }
 
     if (m_beginTime)
-        m_timer.stop();
+        cancelAnimationFrame();
 
     double now = currentTime();
     m_beginTime = now - time.value();
@@ -206,22 +203,39 @@
     updateAnimations(time, true);
 }
 
-void SMILTimeContainer::startTimer(SMILTime fireTime, SMILTime minimumDelay)
+bool SMILTimeContainer::isTimelineRunning() const
 {
-    if (!m_beginTime || isPaused())
+    return m_beginTime && !isPaused();
+}
+
+void SMILTimeContainer::scheduleAnimationFrame(SMILTime fireTime)
+{
+    if (!isTimelineRunning())
         return;
 
     if (!fireTime.isFinite())
         return;
 
-    SMILTime delay = max(fireTime - elapsed(), minimumDelay);
+    SMILTime delay = max(fireTime - elapsed(), SMILTime(animationFrameDelay));
     m_timer.startOneShot(delay.value());
 }
 
+void SMILTimeContainer::scheduleAnimationFrame()
+{
+    if (!isTimelineRunning())
+        return;
+
+    m_timer.startOneShot(0);
+}
+
+void SMILTimeContainer::cancelAnimationFrame()
+{
+    m_timer.stop();
+}
+
 void SMILTimeContainer::timerFired(Timer<SMILTimeContainer>*)
 {
-    ASSERT(m_beginTime);
-    ASSERT(!m_pauseTime);
+    ASSERT(isTimelineRunning());
     updateAnimations(elapsed());
 }
 
@@ -237,7 +251,7 @@
 
 struct PriorityCompare {
     PriorityCompare(SMILTime elapsed) : m_elapsed(elapsed) {}
-    bool operator()(SVGSMILElement* a, SVGSMILElement* b)
+    bool operator()(const RefPtr<SVGSMILElement>& a, const RefPtr<SVGSMILElement>& b)
     {
         // FIXME: This should also consider possible timing relations between the elements.
         SMILTime aBegin = a->intervalBegin();
@@ -252,13 +266,6 @@
     SMILTime m_elapsed;
 };
 
-void SMILTimeContainer::sortByPriority(Vector<SVGSMILElement*>& smilElements, SMILTime elapsed)
-{
-    if (m_documentOrderIndexesDirty)
-        updateDocumentOrderIndexes();
-    std::sort(smilElements.begin(), smilElements.end(), PriorityCompare(elapsed));
-}
-
 void SMILTimeContainer::updateAnimations(SMILTime elapsed, bool seekToTime)
 {
     SMILTime earliestFireTime = SMILTime::unresolved();
@@ -269,7 +276,10 @@
     m_preventScheduledAnimationsChanges = true;
 #endif
 
-    AnimationsVector animationsToApply;
+    if (m_documentOrderIndexesDirty)
+        updateDocumentOrderIndexes();
+
+    Vector<RefPtr<SVGSMILElement> >  animationsToApply;
     GroupedAnimationsMap::iterator end = m_scheduledAnimations.end();
     for (GroupedAnimationsMap::iterator it = m_scheduledAnimations.begin(); it != end; ++it) {
         AnimationsVector* scheduled = it->value.get();
@@ -278,7 +288,7 @@
         // In case of a tie, document order decides.
         // FIXME: This should also consider timing relationships between the elements. Dependents
         // have higher priority.
-        sortByPriority(*scheduled, elapsed);
+        std::sort(scheduled->begin(), scheduled->end(), PriorityCompare(elapsed));
 
         SVGSMILElement* resultElement = 0;
         unsigned size = scheduled->size();
@@ -289,6 +299,7 @@
             ASSERT(animation->hasValidAttributeName());
 
             // Results are accumulated to the first animation that animates and contributes to a particular element/attribute pair.
+            // FIXME: we should ensure that resultElement is of an appropriate type.
             if (!resultElement) {
                 if (!animation->hasValidAttributeType())
                     continue;
@@ -308,12 +319,14 @@
             animationsToApply.append(resultElement);
     }
 
+    std::sort(animationsToApply.begin(), animationsToApply.end(), PriorityCompare(elapsed));
+
     unsigned animationsToApplySize = animationsToApply.size();
     if (!animationsToApplySize) {
 #ifndef NDEBUG
         m_preventScheduledAnimationsChanges = false;
 #endif
-        startTimer(earliestFireTime, animationFrameDelay);
+        scheduleAnimationFrame(earliestFireTime);
         return;
     }
 
@@ -325,7 +338,23 @@
     m_preventScheduledAnimationsChanges = false;
 #endif
 
-    startTimer(earliestFireTime, animationFrameDelay);
+    scheduleAnimationFrame(earliestFireTime);
+
+    for (unsigned i = 0; i < animationsToApplySize; ++i) {
+        if (animationsToApply[i]->inDocument() && animationsToApply[i]->isSVGDiscardElement()) {
+            RefPtr<SVGSMILElement> animDiscard = animationsToApply[i];
+            RefPtr<SVGElement> targetElement = animDiscard->targetElement();
+            if (targetElement && targetElement->inDocument()) {
+                targetElement->remove(IGNORE_EXCEPTION);
+                ASSERT(!targetElement->inDocument());
+            }
+
+            if (animDiscard->inDocument()) {
+                animDiscard->remove(IGNORE_EXCEPTION);
+                ASSERT(!animDiscard->inDocument());
+            }
+        }
+    }
 }
 
 }
diff --git a/Source/core/svg/animation/SMILTimeContainer.h b/Source/core/svg/animation/SMILTimeContainer.h
index 86b24ab..bff4ae9 100644
--- a/Source/core/svg/animation/SMILTimeContainer.h
+++ b/Source/core/svg/animation/SMILTimeContainer.h
@@ -53,7 +53,6 @@
 
     SMILTime elapsed() const;
 
-    bool isActive() const;
     bool isPaused() const;
     bool isStarted() const;
 
@@ -67,12 +66,14 @@
 private:
     SMILTimeContainer(SVGSVGElement* owner);
 
+    bool isTimelineRunning() const;
+    void scheduleAnimationFrame(SMILTime fireTime);
+    void scheduleAnimationFrame();
+    void cancelAnimationFrame();
     void timerFired(Timer<SMILTimeContainer>*);
-    void startTimer(SMILTime fireTime, SMILTime minimumDelay = 0);
     void updateAnimations(SMILTime elapsed, bool seekToTime = false);
 
     void updateDocumentOrderIndexes();
-    void sortByPriority(Vector<SVGSMILElement*>& smilElements, SMILTime elapsed);
     double lastResumeTime() const { return m_resumeTime ? m_resumeTime : m_beginTime; }
 
     double m_beginTime;
diff --git a/Source/core/svg/animation/SVGSMILElement.cpp b/Source/core/svg/animation/SVGSMILElement.cpp
index 7dbc0ae..20ac8cd 100644
--- a/Source/core/svg/animation/SVGSMILElement.cpp
+++ b/Source/core/svg/animation/SVGSMILElement.cpp
@@ -29,6 +29,7 @@
 #include "SVGNames.h"
 #include "XLinkNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "bindings/v8/ScriptEventListener.h"
 #include "core/dom/Document.h"
 #include "core/events/EventListener.h"
 #include "core/events/EventSender.h"
@@ -45,14 +46,14 @@
 
 namespace WebCore {
 
-class RepeatEvent : public Event {
+class RepeatEvent FINAL : public Event {
 public:
     static PassRefPtr<RepeatEvent> create(const AtomicString& type, int repeat)
     {
         return adoptRef(new RepeatEvent(type, false, false, repeat));
     }
 
-    ~RepeatEvent() { }
+    virtual ~RepeatEvent() { }
 
     int repeat() const { return m_repeat; }
 protected:
@@ -98,7 +99,7 @@
 // This is used for duration type time values that can't be negative.
 static const double invalidCachedTime = -1.;
 
-class ConditionEventListener : public EventListener {
+class ConditionEventListener FINAL : public EventListener {
 public:
     static PassRefPtr<ConditionEventListener> create(SVGSMILElement* animation, SVGSMILElement::Condition* condition)
     {
@@ -112,7 +113,7 @@
             : 0;
     }
 
-    virtual bool operator==(const EventListener& other);
+    virtual bool operator==(const EventListener& other) OVERRIDE;
 
     void disconnectAnimation()
     {
@@ -127,7 +128,7 @@
     {
     }
 
-    virtual void handleEvent(ExecutionContext*, Event*);
+    virtual void handleEvent(ExecutionContext*, Event*) OVERRIDE;
 
     SVGSMILElement* m_animation;
     SVGSMILElement::Condition* m_condition;
@@ -161,7 +162,7 @@
     : SVGElement(tagName, doc)
     , m_attributeName(anyQName())
     , m_targetElement(0)
-    , m_conditionsConnected(false)
+    , m_syncBaseConditionsConnected(false)
     , m_hasEndEventConditions(false)
     , m_isWaitingForFirstInterval(true)
     , m_intervalBegin(SMILTime::unresolved())
@@ -183,24 +184,31 @@
 
 SVGSMILElement::~SVGSMILElement()
 {
-    clearResourceReferences();
+    clearResourceAndEventBaseReferences();
     smilEndEventSender().cancelEvent(this);
     smilBeginEventSender().cancelEvent(this);
     smilRepeatEventSender().cancelEvent(this);
     smilRepeatNEventSender().cancelEvent(this);
-    disconnectConditions();
+    clearConditions();
     if (m_timeContainer && m_targetElement && hasValidAttributeName())
         m_timeContainer->unschedule(this, m_targetElement, m_attributeName);
 }
 
-void SVGSMILElement::clearResourceReferences()
+void SVGSMILElement::clearResourceAndEventBaseReferences()
 {
     document().accessSVGExtensions()->removeAllTargetReferencesForElement(this);
 }
 
+void SVGSMILElement::clearConditions()
+{
+    disconnectSyncBaseConditions();
+    disconnectEventBaseConditions();
+    m_conditions.clear();
+}
+
 void SVGSMILElement::buildPendingResource()
 {
-    clearResourceReferences();
+    clearResourceAndEventBaseReferences();
 
     if (!inDocument()) {
         // Reset the target element if we are no longer in the document.
@@ -208,8 +216,8 @@
         return;
     }
 
-    String id;
-    String href = getAttribute(XLinkNames::hrefAttr);
+    AtomicString id;
+    AtomicString href = getAttribute(XLinkNames::hrefAttr);
     Element* target;
     if (href.isEmpty())
         target = parentNode() && parentNode()->isElementNode() ? toElement(parentNode()) : 0;
@@ -237,6 +245,7 @@
         // that leads to relayout/repainting now informs us, so we can react to it.
         document().accessSVGExtensions()->addElementReferencingTarget(this, svgTarget);
     }
+    connectEventBaseConditions();
 }
 
 static inline QualifiedName constructQualifiedName(const SVGElement* svgElement, const AtomicString& attributeName)
@@ -318,8 +327,8 @@
 void SVGSMILElement::removedFrom(ContainerNode* rootParent)
 {
     if (rootParent->inDocument()) {
-        clearResourceReferences();
-        disconnectConditions();
+        clearResourceAndEventBaseReferences();
+        clearConditions();
         setTargetElement(0);
         setAttributeName(anyQName());
         animationAttributeChanged();
@@ -501,22 +510,26 @@
 {
     if (name == SVGNames::beginAttr) {
         if (!m_conditions.isEmpty()) {
-            disconnectConditions();
-            m_conditions.clear();
+            clearConditions();
             parseBeginOrEnd(fastGetAttribute(SVGNames::endAttr), End);
         }
         parseBeginOrEnd(value.string(), Begin);
         if (inDocument())
-            connectConditions();
+            connectSyncBaseConditions();
     } else if (name == SVGNames::endAttr) {
         if (!m_conditions.isEmpty()) {
-            disconnectConditions();
-            m_conditions.clear();
+            clearConditions();
             parseBeginOrEnd(fastGetAttribute(SVGNames::beginAttr), Begin);
         }
         parseBeginOrEnd(value.string(), End);
         if (inDocument())
-            connectConditions();
+            connectSyncBaseConditions();
+    } else if (name == SVGNames::onbeginAttr) {
+        setAttributeEventListener(EventTypeNames::beginEvent, createAttributeEventListener(this, name, value));
+    } else if (name == SVGNames::onendAttr) {
+        setAttributeEventListener(EventTypeNames::endEvent, createAttributeEventListener(this, name, value));
+    } else if (name == SVGNames::onrepeatAttr) {
+        setAttributeEventListener(EventTypeNames::repeatEvent, createAttributeEventListener(this, name, value));
     } else
         SVGElement::parseAttribute(name, value);
 }
@@ -555,43 +568,71 @@
     animationAttributeChanged();
 }
 
-inline Element* SVGSMILElement::eventBaseFor(const Condition& condition)
+inline SVGElement* SVGSMILElement::eventBaseFor(const Condition& condition)
 {
-    return condition.m_baseID.isEmpty() ? targetElement() : treeScope().getElementById(condition.m_baseID);
+    Element* eventBase = condition.m_baseID.isEmpty() ? targetElement() : treeScope().getElementById(AtomicString(condition.m_baseID));
+    if (eventBase && eventBase->isSVGElement())
+        return toSVGElement(eventBase);
+    return 0;
 }
 
-void SVGSMILElement::connectConditions()
+void SVGSMILElement::connectSyncBaseConditions()
 {
-    if (m_conditionsConnected)
-        disconnectConditions();
-    m_conditionsConnected = true;
+    if (m_syncBaseConditionsConnected)
+        disconnectSyncBaseConditions();
+    m_syncBaseConditionsConnected = true;
     for (unsigned n = 0; n < m_conditions.size(); ++n) {
         Condition& condition = m_conditions[n];
-        if (condition.m_type == Condition::EventBase) {
-            ASSERT(!condition.m_syncbase);
-            Element* eventBase = eventBaseFor(condition);
-            if (!eventBase)
-                continue;
-            ASSERT(!condition.m_eventListener);
-            condition.m_eventListener = ConditionEventListener::create(this, &condition);
-            eventBase->addEventListener(condition.m_name, condition.m_eventListener, false);
-        } else if (condition.m_type == Condition::Syncbase) {
+        if (condition.m_type == Condition::Syncbase) {
             ASSERT(!condition.m_baseID.isEmpty());
-            condition.m_syncbase = treeScope().getElementById(condition.m_baseID);
+            condition.m_syncbase = treeScope().getElementById(AtomicString(condition.m_baseID));
             if (!condition.m_syncbase || !isSVGSMILElement(*condition.m_syncbase)) {
                 condition.m_syncbase = 0;
                 continue;
             }
-            toSVGSMILElement(condition.m_syncbase.get())->addTimeDependent(this);
+            toSVGSMILElement(condition.m_syncbase.get())->addSyncBaseDependent(this);
         }
     }
 }
 
-void SVGSMILElement::disconnectConditions()
+void SVGSMILElement::disconnectSyncBaseConditions()
 {
-    if (!m_conditionsConnected)
+    if (!m_syncBaseConditionsConnected)
         return;
-    m_conditionsConnected = false;
+    m_syncBaseConditionsConnected = false;
+    for (unsigned n = 0; n < m_conditions.size(); ++n) {
+        Condition& condition = m_conditions[n];
+        if (condition.m_type == Condition::Syncbase) {
+            if (condition.m_syncbase)
+                toSVGSMILElement(condition.m_syncbase.get())->removeSyncBaseDependent(this);
+            condition.m_syncbase = 0;
+        }
+    }
+}
+
+void SVGSMILElement::connectEventBaseConditions()
+{
+    disconnectEventBaseConditions();
+    for (unsigned n = 0; n < m_conditions.size(); ++n) {
+        Condition& condition = m_conditions[n];
+        if (condition.m_type == Condition::EventBase) {
+            ASSERT(!condition.m_syncbase);
+            SVGElement* eventBase = eventBaseFor(condition);
+            if (!eventBase) {
+                if (!condition.m_baseID.isEmpty() && !document().accessSVGExtensions()->isElementPendingResource(this, AtomicString(condition.m_baseID)))
+                    document().accessSVGExtensions()->addPendingResource(AtomicString(condition.m_baseID), this);
+                continue;
+            }
+            ASSERT(!condition.m_eventListener);
+            condition.m_eventListener = ConditionEventListener::create(this, &condition);
+            eventBase->addEventListener(AtomicString(condition.m_name), condition.m_eventListener, false);
+            document().accessSVGExtensions()->addElementReferencingTarget(this, eventBase);
+        }
+    }
+}
+
+void SVGSMILElement::disconnectEventBaseConditions()
+{
     for (unsigned n = 0; n < m_conditions.size(); ++n) {
         Condition& condition = m_conditions[n];
         if (condition.m_type == Condition::EventBase) {
@@ -603,16 +644,12 @@
             // no guarantee that eventBaseFor() will be able to find our condition's
             // original eventBase. So, we also have to disconnect ourselves from
             // our condition event listener, in case it later fires.
-            Element* eventBase = eventBaseFor(condition);
+            SVGElement* eventBase = eventBaseFor(condition);
             if (eventBase)
-                eventBase->removeEventListener(condition.m_name, condition.m_eventListener.get(), false);
+                eventBase->removeEventListener(AtomicString(condition.m_name), condition.m_eventListener.get(), false);
             condition.m_eventListener->disconnectAnimation();
             condition.m_eventListener = 0;
-        } else if (condition.m_type == Condition::Syncbase) {
-            if (condition.m_syncbase)
-                toSVGSMILElement(condition.m_syncbase.get())->removeTimeDependent(this);
         }
-        condition.m_syncbase = 0;
     }
 }
 
@@ -644,7 +681,7 @@
     if (m_targetElement) {
         // Clear values that may depend on the previous target.
         clearAnimatedType(m_targetElement);
-        disconnectConditions();
+        disconnectSyncBaseConditions();
     }
 
     // If the animation state is not Inactive, always reset to a clear state before leaving the old target element.
@@ -659,11 +696,6 @@
     return m_timeContainer ? m_timeContainer->elapsed() : 0;
 }
 
-bool SVGSMILElement::isInactive() const
-{
-     return m_activeState == Inactive;
-}
-
 bool SVGSMILElement::isFrozen() const
 {
     return m_activeState == Frozen;
@@ -763,9 +795,9 @@
     endListChanged(eventTime);
 }
 
-inline SMILTime extractTimeFromVector(const SMILTimeWithOrigin* position)
+inline bool compareTimes(const SMILTimeWithOrigin& left, const SMILTimeWithOrigin& right)
 {
-    return position->time();
+    return left.time() < right.time();
 }
 
 SMILTime SVGSMILElement::findInstanceTime(BeginOrEnd beginOrEnd, SMILTime minimumTime, bool equalsMinimumOK) const
@@ -776,21 +808,17 @@
     if (!sizeOfList)
         return beginOrEnd == Begin ? SMILTime::unresolved() : SMILTime::indefinite();
 
-    const SMILTimeWithOrigin* result = approximateBinarySearch<const SMILTimeWithOrigin, SMILTime>(list, sizeOfList, minimumTime, extractTimeFromVector);
+    const SMILTimeWithOrigin dummyTimeWithOrigin(minimumTime, SMILTimeWithOrigin::ParserOrigin);
+    const SMILTimeWithOrigin* result = std::lower_bound(list.begin(), list.end(), dummyTimeWithOrigin, compareTimes);
     int indexOfResult = result - list.begin();
-    ASSERT_WITH_SECURITY_IMPLICATION(indexOfResult < sizeOfList);
-
-    if (list[indexOfResult].time() < minimumTime && indexOfResult < sizeOfList - 1)
-        ++indexOfResult;
-
+    if (indexOfResult == sizeOfList)
+        return SMILTime::unresolved();
     const SMILTime& currentTime = list[indexOfResult].time();
 
     // The special value "indefinite" does not yield an instance time in the begin list.
     if (currentTime.isIndefinite() && beginOrEnd == Begin)
         return SMILTime::unresolved();
 
-    if (currentTime < minimumTime)
-        return SMILTime::unresolved();
     if (currentTime > minimumTime)
         return currentTime;
 
@@ -972,18 +1000,18 @@
         m_timeContainer->notifyIntervalsChanged();
 }
 
-void SVGSMILElement::checkRestart(SMILTime elapsed)
+SVGSMILElement::RestartedInterval SVGSMILElement::maybeRestartInterval(SMILTime elapsed)
 {
     ASSERT(!m_isWaitingForFirstInterval);
     ASSERT(elapsed >= m_intervalBegin);
 
     Restart restart = this->restart();
     if (restart == RestartNever)
-        return;
+        return DidNotRestartInterval;
 
     if (elapsed < m_intervalEnd) {
         if (restart != RestartAlways)
-            return;
+            return DidNotRestartInterval;
         SMILTime nextBegin = findInstanceTime(Begin, m_intervalBegin, false);
         if (nextBegin < m_intervalEnd) {
             m_intervalEnd = nextBegin;
@@ -991,8 +1019,11 @@
         }
     }
 
-    if (elapsed >= m_intervalEnd)
-        resolveNextInterval();
+    if (elapsed >= m_intervalEnd) {
+        if (resolveNextInterval())
+            return DidRestartInterval;
+    }
+    return DidNotRestartInterval;
 }
 
 void SVGSMILElement::seekToIntervalCorrespondingToTime(SMILTime elapsed)
@@ -1100,8 +1131,8 @@
     ASSERT(m_timeContainer);
     ASSERT(m_isWaitingForFirstInterval || m_intervalBegin.isFinite());
 
-    if (!m_conditionsConnected)
-        connectConditions();
+    if (!m_syncBaseConditionsConnected)
+        connectSyncBaseConditions();
 
     if (!m_intervalBegin.isFinite()) {
         ASSERT(m_activeState == Inactive);
@@ -1139,7 +1170,7 @@
 
     unsigned repeat = 0;
     float percent = calculateAnimationPercentAndRepeat(elapsed, repeat);
-    checkRestart(elapsed);
+    RestartedInterval restartedInterval = maybeRestartInterval(elapsed);
 
     ActiveState oldActiveState = m_activeState;
     m_activeState = determineActiveState(elapsed);
@@ -1150,7 +1181,7 @@
         resetAnimatedType();
 
     if (animationIsContributing) {
-        if (oldActiveState == Inactive) {
+        if (oldActiveState == Inactive || restartedInterval == DidRestartInterval) {
             smilBeginEventSender().dispatchEventSoon(this);
             startedActiveInterval();
         }
@@ -1163,10 +1194,10 @@
         m_lastRepeat = repeat;
     }
 
-    if (oldActiveState == Active && m_activeState != Active) {
+    if ((oldActiveState == Active && m_activeState != Active) || restartedInterval == DidRestartInterval) {
         smilEndEventSender().dispatchEventSoon(this);
         endedActiveInterval();
-        if (m_activeState != Frozen && this == resultElement)
+        if (restartedInterval == DidNotRestartInterval && m_activeState != Frozen && this == resultElement)
             clearAnimatedType(m_targetElement);
     }
 
@@ -1197,8 +1228,8 @@
     if (!loopBreaker.add(this).isNewEntry)
         return;
 
-    TimeDependentSet::iterator end = m_timeDependents.end();
-    for (TimeDependentSet::iterator it = m_timeDependents.begin(); it != end; ++it) {
+    TimeDependentSet::iterator end = m_syncBaseDependents.end();
+    for (TimeDependentSet::iterator it = m_syncBaseDependents.begin(); it != end; ++it) {
         SVGSMILElement* dependent = *it;
         dependent->createInstanceTimesFromSyncbase(this);
     }
@@ -1220,7 +1251,8 @@
                 time = syncbase->m_intervalBegin + condition.m_offset;
             else
                 time = syncbase->m_intervalEnd + condition.m_offset;
-            ASSERT(time.isFinite());
+            if (!time.isFinite())
+                continue;
             if (condition.m_beginOrEnd == Begin)
                 addBeginTime(elapsed(), time);
             else
@@ -1229,16 +1261,16 @@
     }
 }
 
-void SVGSMILElement::addTimeDependent(SVGSMILElement* animation)
+void SVGSMILElement::addSyncBaseDependent(SVGSMILElement* animation)
 {
-    m_timeDependents.add(animation);
+    m_syncBaseDependents.add(animation);
     if (m_intervalBegin.isFinite())
         animation->createInstanceTimesFromSyncbase(this);
 }
 
-void SVGSMILElement::removeTimeDependent(SVGSMILElement* animation)
+void SVGSMILElement::removeSyncBaseDependent(SVGSMILElement* animation)
 {
-    m_timeDependents.remove(animation);
+    m_syncBaseDependents.remove(animation);
 }
 
 void SVGSMILElement::handleConditionEvent(Event* event, Condition* condition)
diff --git a/Source/core/svg/animation/SVGSMILElement.h b/Source/core/svg/animation/SVGSMILElement.h
index 44c4fa1..d66d599 100644
--- a/Source/core/svg/animation/SVGSMILElement.h
+++ b/Source/core/svg/animation/SVGSMILElement.h
@@ -87,7 +87,6 @@
     SMILTime elapsed() const;
 
     SMILTime intervalBegin() const { return m_intervalBegin; }
-    SMILTime intervalEnd() const { return m_intervalEnd; }
     SMILTime previousIntervalBegin() const { return m_previousIntervalBegin; }
     SMILTime simpleDuration() const;
 
@@ -101,22 +100,23 @@
     static SMILTime parseOffsetValue(const String&);
 
     bool isContributing(SMILTime elapsed) const;
-    bool isInactive() const;
     bool isFrozen() const;
 
     unsigned documentOrderIndex() const { return m_documentOrderIndex; }
     void setDocumentOrderIndex(unsigned index) { m_documentOrderIndex = index; }
 
-    virtual bool isAdditive() const = 0;
     virtual void resetAnimatedType() = 0;
     virtual void clearAnimatedType(SVGElement* targetElement) = 0;
     virtual void applyResultsToTarget() = 0;
 
-    void connectConditions();
+    void connectSyncBaseConditions();
+    void connectEventBaseConditions();
 
     void dispatchPendingEvent(SMILEventSender*);
     void dispatchRepeatEvents(unsigned);
 
+    virtual bool isSVGDiscardElement() const { return false; }
+
 protected:
     void addBeginTime(SMILTime eventTime, SMILTime endTime, SMILTimeWithOrigin::Origin = SMILTimeWithOrigin::ParserOrigin);
     void addEndTime(SMILTime eventTime, SMILTime endTime, SMILTimeWithOrigin::Origin = SMILTimeWithOrigin::ParserOrigin);
@@ -128,8 +128,9 @@
     virtual void setAttributeName(const QualifiedName&);
 
 private:
-    void buildPendingResource();
-    void clearResourceReferences();
+    virtual void buildPendingResource() OVERRIDE;
+    void clearResourceAndEventBaseReferences();
+    void clearConditions();
 
     virtual void startedActiveInterval() = 0;
     void endedActiveInterval();
@@ -148,7 +149,13 @@
     void resolveInterval(bool first, SMILTime& beginResult, SMILTime& endResult) const;
     SMILTime resolveActiveEnd(SMILTime resolvedBegin, SMILTime resolvedEnd) const;
     SMILTime repeatingDuration() const;
-    void checkRestart(SMILTime elapsed);
+
+    enum RestartedInterval {
+        DidNotRestartInterval,
+        DidRestartInterval
+    };
+
+    RestartedInterval maybeRestartInterval(SMILTime elapsed);
     void beginListChanged(SMILTime eventTime);
     void endListChanged(SMILTime eventTime);
 
@@ -173,17 +180,18 @@
     };
     bool parseCondition(const String&, BeginOrEnd beginOrEnd);
     void parseBeginOrEnd(const String&, BeginOrEnd beginOrEnd);
-    Element* eventBaseFor(const Condition&);
+    SVGElement* eventBaseFor(const Condition&);
 
-    void disconnectConditions();
+    void disconnectSyncBaseConditions();
+    void disconnectEventBaseConditions();
 
     // Event base timing
     void handleConditionEvent(Event*, Condition*);
 
     void notifyDependentsIntervalChanged();
     void createInstanceTimesFromSyncbase(SVGSMILElement* syncbase);
-    void addTimeDependent(SVGSMILElement*);
-    void removeTimeDependent(SVGSMILElement*);
+    void addSyncBaseDependent(SVGSMILElement*);
+    void removeSyncBaseDependent(SVGSMILElement*);
 
     enum ActiveState {
         Inactive,
@@ -200,13 +208,13 @@
     mutable SVGElement* m_targetElement;
 
     Vector<Condition> m_conditions;
-    bool m_conditionsConnected;
+    bool m_syncBaseConditionsConnected;
     bool m_hasEndEventConditions;
 
     bool m_isWaitingForFirstInterval;
 
     typedef HashSet<SVGSMILElement*> TimeDependentSet;
-    TimeDependentSet m_timeDependents;
+    TimeDependentSet m_syncBaseDependents;
 
     // Instance time lists
     Vector<SMILTimeWithOrigin> m_beginTimes;
@@ -241,7 +249,7 @@
 inline bool isSVGSMILElement(const Node& node)
 {
     return node.hasTagName(SVGNames::setTag) || node.hasTagName(SVGNames::animateTag) || node.hasTagName(SVGNames::animateMotionTag)
-        || node.hasTagName(SVGNames::animateTransformTag) || node.hasTagName(SVGNames::animateColorTag);
+        || node.hasTagName(SVGNames::animateTransformTag) || node.hasTagName((SVGNames::discardTag));
 }
 
 DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGSMILElement);
diff --git a/Source/core/svg/graphics/SVGImage.cpp b/Source/core/svg/graphics/SVGImage.cpp
index 0a844dd..3299c72 100644
--- a/Source/core/svg/graphics/SVGImage.cpp
+++ b/Source/core/svg/graphics/SVGImage.cpp
@@ -31,11 +31,11 @@
 
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/shadow/ComposedTreeWalker.h"
-#include "core/loader/DocumentLoader.h"
+#include "core/loader/FrameLoadRequest.h"
 #include "core/page/Chrome.h"
 #include "core/frame/Frame.h"
 #include "core/frame/FrameView.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/svg/RenderSVGRoot.h"
 #include "core/svg/SVGDocument.h"
@@ -99,10 +99,13 @@
     while (Node* node = walker.get()) {
         if (node->hasTagName(SVGNames::foreignObjectTag))
             return false;
-        if (node->hasTagName(SVGNames::imageTag))
-            return toSVGImageElement(node)->currentFrameHasSingleSecurityOrigin();
-        if (node->hasTagName(SVGNames::feImageTag))
-            return toSVGFEImageElement(node)->currentFrameHasSingleSecurityOrigin();
+        if (node->hasTagName(SVGNames::imageTag)) {
+            if (!toSVGImageElement(node)->currentFrameHasSingleSecurityOrigin())
+                return false;
+        } else if (node->hasTagName(SVGNames::feImageTag)) {
+            if (!toSVGFEImageElement(node)->currentFrameHasSingleSecurityOrigin())
+                return false;
+        }
         walker.next();
     }
 
@@ -242,8 +245,12 @@
     GraphicsContextStateSaver stateSaver(*context);
     context->setCompositeOperation(compositeOp, blendMode);
     context->clip(enclosingIntRect(dstRect));
-    if (compositeOp != CompositeSourceOver)
+
+    bool compositingRequiresTransparencyLayer = compositeOp != CompositeSourceOver || blendMode != blink::WebBlendModeNormal;
+    if (compositingRequiresTransparencyLayer) {
         context->beginTransparencyLayer(1);
+        context->setCompositeOperation(CompositeSourceOver, blink::WebBlendModeNormal);
+    }
 
     FloatSize scale(dstRect.width() / srcRect.width(), dstRect.height() / srcRect.height());
 
@@ -263,7 +270,7 @@
 
     view->paint(context, enclosingIntRect(srcRect));
 
-    if (compositeOp != CompositeSourceOver)
+    if (compositingRequiresTransparencyLayer)
         context->endLayer();
 
     stateSaver.restore();
@@ -324,10 +331,10 @@
 
     intrinsicWidth = rootElement->intrinsicWidth();
     intrinsicHeight = rootElement->intrinsicHeight();
-    if (rootElement->preserveAspectRatioCurrentValue().align() == SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE)
+    if (rootElement->preserveAspectRatio()->currentValue()->align() == SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE)
         return;
 
-    intrinsicRatio = rootElement->viewBoxCurrentValue().size();
+    intrinsicRatio = rootElement->viewBox()->currentValue()->value().size();
     if (intrinsicRatio.isEmpty() && intrinsicWidth.isFixed() && intrinsicHeight.isFixed())
         intrinsicRatio = FloatSize(floatValueForLength(intrinsicWidth, 0), floatValueForLength(intrinsicHeight, 0));
 }
@@ -370,7 +377,7 @@
         return true;
 
     if (allDataReceived) {
-        static FrameLoaderClient* dummyFrameLoaderClient =  new EmptyFrameLoaderClient;
+        static FrameLoaderClient* dummyFrameLoaderClient = new EmptyFrameLoaderClient;
 
         Page::PageClients pageClients;
         fillWithEmptyClients(pageClients);
@@ -389,7 +396,7 @@
         m_page->settings().setPluginsEnabled(false);
         m_page->settings().setAcceleratedCompositingEnabled(false);
 
-        RefPtr<Frame> frame = Frame::create(FrameInit::create(0, m_page.get(), dummyFrameLoaderClient));
+        RefPtr<Frame> frame = Frame::create(FrameInit::create(0, &m_page->frameHost(), dummyFrameLoaderClient));
         frame->setView(FrameView::create(frame.get()));
         frame->init();
         FrameLoader& loader = frame->loader();
@@ -399,10 +406,7 @@
         frame->view()->setCanHaveScrollbars(false); // SVG Images will always synthesize a viewBox, if it's not available, and thus never see scrollbars.
         frame->view()->setTransparent(true); // SVG Images are transparent.
 
-        ASSERT(loader.activeDocumentLoader()); // DocumentLoader should have been created by frame->init().
-        DocumentWriter* writer = loader.activeDocumentLoader()->beginWriting("image/svg+xml", "UTF-8");
-        writer->addData(data()->data(), data()->size());
-        loader.activeDocumentLoader()->endWriting(writer);
+        loader.load(FrameLoadRequest(0, blankURL(), SubstituteData(data(), "image/svg+xml", "UTF-8", KURL(), ForceSynchronousLoad)));
         // Set the intrinsic size before a container size is available.
         m_intrinsicSize = containerSize();
     }
diff --git a/Source/core/svg/graphics/SVGImage.h b/Source/core/svg/graphics/SVGImage.h
index 19838c9..14cbf4f 100644
--- a/Source/core/svg/graphics/SVGImage.h
+++ b/Source/core/svg/graphics/SVGImage.h
@@ -39,7 +39,7 @@
 class SVGImageChromeClient;
 class SVGImageForContainer;
 
-class SVGImage : public Image {
+class SVGImage FINAL : public Image {
 public:
     static PassRefPtr<SVGImage> create(ImageObserver* observer)
     {
@@ -64,6 +64,9 @@
 
     virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() OVERRIDE;
 
+    // Returns the SVG image document's frame.
+    FrameView* frameView() const;
+
 private:
     friend class AXRenderObject;
     friend class SVGImageChromeClient;
@@ -71,8 +74,6 @@
 
     virtual ~SVGImage();
 
-    // Returns the SVG image document's frame.
-    FrameView* frameView() const;
 
     virtual String filenameExtension() const OVERRIDE;
 
diff --git a/Source/core/svg/graphics/SVGImageChromeClient.cpp b/Source/core/svg/graphics/SVGImageChromeClient.cpp
new file mode 100644
index 0000000..51ddd37
--- /dev/null
+++ b/Source/core/svg/graphics/SVGImageChromeClient.cpp
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2012 Apple Inc. 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.
+ * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ *     its contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "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 APPLE OR ITS 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.
+ */
+
+#include "config.h"
+#include "core/svg/graphics/SVGImageChromeClient.h"
+
+#include "core/frame/FrameView.h"
+#include "core/svg/graphics/SVGImage.h"
+#include "platform/graphics/ImageObserver.h"
+
+namespace WebCore {
+
+SVGImageChromeClient::SVGImageChromeClient(SVGImage* image)
+    : m_image(image)
+    , m_animationTimer(this, &SVGImageChromeClient::animationTimerFired)
+{
+}
+
+bool SVGImageChromeClient::isSVGImageChromeClient() const
+{
+    return true;
+}
+
+void SVGImageChromeClient::chromeDestroyed()
+{
+    m_image = 0;
+}
+
+void SVGImageChromeClient::invalidateContentsAndRootView(const IntRect& r)
+{
+    // If m_image->m_page is null, we're being destructed, don't fire changedInRect() in that case.
+    if (m_image && m_image->imageObserver() && m_image->m_page)
+        m_image->imageObserver()->changedInRect(m_image, r);
+}
+
+void SVGImageChromeClient::scheduleAnimation()
+{
+    // Because a single SVGImage can be shared by multiple pages, we can't key
+    // our svg image layout on the page's real animation frame. Therefore, we
+    // run this fake animation timer to trigger layout in SVGImages. The name,
+    // "animationTimer", is to match the new requestAnimationFrame-based layout
+    // approach.
+    if (m_animationTimer.isActive())
+        return;
+    m_animationTimer.startOneShot(0);
+}
+
+void SVGImageChromeClient::animationTimerFired(Timer<SVGImageChromeClient>*)
+{
+    // In principle, we should call requestAnimationFrame callbacks here, but
+    // we know there aren't any because script is forbidden inside SVGImages.
+    if (m_image)
+        m_image->frameView()->layout();
+}
+
+}
diff --git a/Source/core/svg/graphics/SVGImageChromeClient.h b/Source/core/svg/graphics/SVGImageChromeClient.h
index 914980a..d1457d7 100644
--- a/Source/core/svg/graphics/SVGImageChromeClient.h
+++ b/Source/core/svg/graphics/SVGImageChromeClient.h
@@ -30,42 +30,30 @@
 #define SVGImageChromeClient_h
 
 #include "core/loader/EmptyClients.h"
-#include "platform/graphics/ImageObserver.h"
+#include "platform/Timer.h"
 
 namespace WebCore {
 
-class SVGImageChromeClient : public EmptyChromeClient {
+class SVGImageChromeClient FINAL : public EmptyChromeClient {
     WTF_MAKE_NONCOPYABLE(SVGImageChromeClient); WTF_MAKE_FAST_ALLOCATED;
 public:
-    SVGImageChromeClient(SVGImage* image)
-        : m_image(image)
-    {
-    }
+    explicit SVGImageChromeClient(SVGImage*);
+    virtual bool isSVGImageChromeClient() const OVERRIDE;
 
-    virtual bool isSVGImageChromeClient() const { return true; }
     SVGImage* image() const { return m_image; }
 
 private:
-    virtual void chromeDestroyed()
-    {
-        m_image = 0;
-    }
+    virtual void chromeDestroyed() OVERRIDE;
+    virtual void invalidateContentsAndRootView(const IntRect&) OVERRIDE;
+    virtual void scheduleAnimation() OVERRIDE;
 
-    virtual void invalidateContentsAndRootView(const IntRect& r)
-    {
-        // If m_image->m_page is null, we're being destructed, don't fire changedInRect() in that case.
-        if (m_image && m_image->imageObserver() && m_image->m_page)
-            m_image->imageObserver()->changedInRect(m_image, r);
-    }
+    void animationTimerFired(Timer<SVGImageChromeClient>*);
 
     SVGImage* m_image;
+    Timer<SVGImageChromeClient> m_animationTimer;
 };
 
-inline SVGImageChromeClient* toSVGImageChromeClient(ChromeClient* client)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!client || client->isSVGImageChromeClient());
-    return static_cast<SVGImageChromeClient*>(client);
-}
+DEFINE_TYPE_CASTS(SVGImageChromeClient, ChromeClient, client, client->isSVGImageChromeClient(), client.isSVGImageChromeClient());
 
 }
 
diff --git a/Source/core/svg/graphics/SVGImageForContainer.h b/Source/core/svg/graphics/SVGImageForContainer.h
index 4ea589e..aea94bc 100644
--- a/Source/core/svg/graphics/SVGImageForContainer.h
+++ b/Source/core/svg/graphics/SVGImageForContainer.h
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-class SVGImageForContainer : public Image {
+class SVGImageForContainer FINAL : public Image {
 public:
     static PassRefPtr<SVGImageForContainer> create(SVGImage* image, const FloatSize& containerSize, float zoom)
     {
diff --git a/Source/core/svg/graphics/filters/SVGFEImage.cpp b/Source/core/svg/graphics/filters/SVGFEImage.cpp
index ab2d6ca..f4995da 100644
--- a/Source/core/svg/graphics/filters/SVGFEImage.cpp
+++ b/Source/core/svg/graphics/filters/SVGFEImage.cpp
@@ -26,18 +26,21 @@
 #include "core/svg/graphics/filters/SVGFEImage.h"
 
 #include "SkBitmapSource.h"
+#include "SkPictureImageFilter.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/svg/SVGRenderingContext.h"
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGURIReference.h"
+#include "platform/graphics/DisplayList.h"
 #include "platform/graphics/GraphicsContext.h"
 #include "platform/graphics/filters/Filter.h"
+#include "platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "platform/text/TextStream.h"
 #include "platform/transforms/AffineTransform.h"
 
 namespace WebCore {
 
-FEImage::FEImage(Filter* filter, PassRefPtr<Image> image, const SVGPreserveAspectRatio& preserveAspectRatio)
+FEImage::FEImage(Filter* filter, PassRefPtr<Image> image, PassRefPtr<SVGPreserveAspectRatio> preserveAspectRatio)
     : FilterEffect(filter)
     , m_image(image)
     , m_document(0)
@@ -45,7 +48,7 @@
 {
 }
 
-FEImage::FEImage(Filter* filter, Document& document, const String& href, const SVGPreserveAspectRatio& preserveAspectRatio)
+FEImage::FEImage(Filter* filter, Document& document, const String& href, PassRefPtr<SVGPreserveAspectRatio> preserveAspectRatio)
     : FilterEffect(filter)
     , m_document(&document)
     , m_href(href)
@@ -53,31 +56,58 @@
 {
 }
 
-PassRefPtr<FEImage> FEImage::createWithImage(Filter* filter, PassRefPtr<Image> image, const SVGPreserveAspectRatio& preserveAspectRatio)
+PassRefPtr<FEImage> FEImage::createWithImage(Filter* filter, PassRefPtr<Image> image, PassRefPtr<SVGPreserveAspectRatio> preserveAspectRatio)
 {
     return adoptRef(new FEImage(filter, image, preserveAspectRatio));
 }
 
-PassRefPtr<FEImage> FEImage::createWithIRIReference(Filter* filter, Document& document, const String& href, const SVGPreserveAspectRatio& preserveAspectRatio)
+PassRefPtr<FEImage> FEImage::createWithIRIReference(Filter* filter, Document& document, const String& href, PassRefPtr<SVGPreserveAspectRatio> preserveAspectRatio)
 {
     return adoptRef(new FEImage(filter, document, href, preserveAspectRatio));
 }
 
-void FEImage::determineAbsolutePaintRect()
+static FloatRect getRendererRepaintRect(RenderObject* renderer)
 {
-    FloatRect paintRect = filter()->absoluteTransform().mapRect(filterPrimitiveSubregion());
-    FloatRect srcRect;
-    if (m_image) {
-        srcRect.setSize(m_image->size());
-        m_preserveAspectRatio.transformRect(paintRect, srcRect);
-    } else if (RenderObject* renderer = referencedRenderer())
-        srcRect = filter()->absoluteTransform().mapRect(renderer->repaintRectInLocalCoordinates());
+    return renderer->localToParentTransform().mapRect(
+        renderer->repaintRectInLocalCoordinates());
+}
 
+FloatRect FEImage::determineAbsolutePaintRect(const FloatRect& originalRequestedRect)
+{
+    RenderObject* renderer = referencedRenderer();
+    if (!m_image && !renderer)
+        return FloatRect();
+
+    FloatRect requestedRect = originalRequestedRect;
     if (clipsToBounds())
-        paintRect.intersect(maxEffectRect());
-    else
-        paintRect.unite(maxEffectRect());
-    setAbsolutePaintRect(enclosingIntRect(paintRect));
+        requestedRect.intersect(maxEffectRect());
+
+    FloatRect destRect = filter()->mapLocalRectToAbsoluteRect(filterPrimitiveSubregion());
+    FloatRect srcRect;
+    if (renderer) {
+        srcRect = getRendererRepaintRect(renderer);
+        SVGElement* contextNode = toSVGElement(renderer->node());
+
+        if (contextNode->hasRelativeLengths()) {
+            // FIXME: This fixes relative lengths but breaks non-relative ones (see crbug/260709).
+            SVGLengthContext lengthContext(contextNode);
+            FloatSize viewportSize;
+            if (lengthContext.determineViewport(viewportSize)) {
+                srcRect = makeMapBetweenRects(FloatRect(FloatPoint(), viewportSize), destRect).mapRect(srcRect);
+            }
+        } else {
+            srcRect = filter()->mapLocalRectToAbsoluteRect(srcRect);
+            srcRect.move(destRect.x(), destRect.y());
+        }
+        destRect.intersect(srcRect);
+    } else {
+        srcRect = FloatRect(FloatPoint(), m_image->size());
+        m_preserveAspectRatio->transformRect(destRect, srcRect);
+    }
+
+    destRect.intersect(requestedRect);
+    addAbsolutePaintRect(destRect);
+    return destRect;
 }
 
 RenderObject* FEImage::referencedRenderer() const
@@ -99,44 +129,40 @@
     ImageBuffer* resultImage = createImageBufferResult();
     if (!resultImage)
         return;
-
-    FloatRect destRect = filter()->absoluteTransform().mapRect(filterPrimitiveSubregion());
-
-    FloatRect srcRect;
-    if (renderer)
-        srcRect = filter()->absoluteTransform().mapRect(renderer->repaintRectInLocalCoordinates());
-    else {
-        srcRect = FloatRect(FloatPoint(), m_image->size());
-        m_preserveAspectRatio.transformRect(destRect, srcRect);
-    }
-
     IntPoint paintLocation = absolutePaintRect().location();
-    destRect.move(-paintLocation.x(), -paintLocation.y());
+    resultImage->context()->translate(-paintLocation.x(), -paintLocation.y());
 
     // FEImage results are always in ColorSpaceDeviceRGB
     setResultColorSpace(ColorSpaceDeviceRGB);
 
-    if (renderer) {
-        SVGElement* contextNode = toSVGElement(renderer->node());
-        if (contextNode->hasRelativeLengths()) {
-            SVGLengthContext lengthContext(contextNode);
-            FloatSize viewportSize;
+    FloatRect destRect = filter()->mapLocalRectToAbsoluteRect(filterPrimitiveSubregion());
+    FloatRect srcRect;
 
-            // If we're referencing an element with percentage units, eg. <rect with="30%"> those values were resolved against the viewport.
-            // Build up a transformation that maps from the viewport space to the filter primitive subregion.
-            if (lengthContext.determineViewport(viewportSize))
-                resultImage->context()->concatCTM(makeMapBetweenRects(FloatRect(FloatPoint(), viewportSize), destRect));
-        } else {
-            const AffineTransform& absoluteTransform = filter()->absoluteTransform();
-            resultImage->context()->concatCTM(absoluteTransform);
-        }
+    if (!renderer) {
+        srcRect = FloatRect(FloatPoint(), m_image->size());
+        m_preserveAspectRatio->transformRect(destRect, srcRect);
 
-        AffineTransform contentTransformation;
-        SVGRenderingContext::renderSubtree(resultImage->context(), renderer, contentTransformation);
+        resultImage->context()->drawImage(m_image.get(), destRect, srcRect);
         return;
     }
 
-    resultImage->context()->drawImage(m_image.get(), destRect, srcRect);
+    SVGElement* contextNode = toSVGElement(renderer->node());
+    if (contextNode->hasRelativeLengths()) {
+        // FIXME: This fixes relative lengths but breaks non-relative ones (see crbug/260709).
+        SVGLengthContext lengthContext(contextNode);
+        FloatSize viewportSize;
+
+        // If we're referencing an element with percentage units, eg. <rect with="30%"> those values were resolved against the viewport.
+        // Build up a transformation that maps from the viewport space to the filter primitive subregion.
+        if (lengthContext.determineViewport(viewportSize))
+            resultImage->context()->concatCTM(makeMapBetweenRects(FloatRect(FloatPoint(), viewportSize), destRect));
+    } else {
+        resultImage->context()->translate(destRect.x(), destRect.y());
+        resultImage->context()->concatCTM(filter()->absoluteTransform());
+    }
+
+    AffineTransform contentTransformation;
+    SVGRenderingContext::renderSubtree(resultImage->context(), renderer, contentTransformation);
 }
 
 TextStream& FEImage::externalRepresentation(TextStream& ts, int indent) const
@@ -145,7 +171,7 @@
     if (m_image)
         imageSize = m_image->size();
     else if (RenderObject* renderer = referencedRenderer())
-        imageSize = enclosingIntRect(renderer->repaintRectInLocalCoordinates()).size();
+        imageSize = enclosingIntRect(getRendererRepaintRect(renderer)).size();
     writeIndent(ts, indent);
     ts << "[feImage";
     FilterEffect::externalRepresentation(ts);
@@ -154,15 +180,65 @@
     return ts;
 }
 
+PassRefPtr<SkImageFilter> FEImage::createImageFilterForRenderer(RenderObject* renderer, SkiaImageFilterBuilder* builder)
+{
+    FloatRect dstRect = filterPrimitiveSubregion();
+
+    AffineTransform transform;
+    SVGElement* contextNode = toSVGElement(renderer->node());
+
+    if (contextNode->hasRelativeLengths()) {
+        SVGLengthContext lengthContext(contextNode);
+        FloatSize viewportSize;
+
+        // If we're referencing an element with percentage units, eg. <rect with="30%"> those values were resolved against the viewport.
+        // Build up a transformation that maps from the viewport space to the filter primitive subregion.
+        if (lengthContext.determineViewport(viewportSize))
+            transform = makeMapBetweenRects(FloatRect(FloatPoint(), viewportSize), dstRect);
+    } else {
+        transform.translate(dstRect.x(), dstRect.y());
+    }
+
+    GraphicsContext* context = builder->context();
+    if (!context)
+        return adoptRef(new SkBitmapSource(SkBitmap()));
+    AffineTransform contentTransformation;
+    context->save();
+    context->beginRecording(FloatRect(FloatPoint(), dstRect.size()));
+    context->concatCTM(transform);
+    SVGRenderingContext::renderSubtree(context, renderer, contentTransformation);
+    RefPtr<DisplayList> displayList = context->endRecording();
+    context->restore();
+    RefPtr<SkImageFilter> result = adoptRef(new SkPictureImageFilter(displayList->picture(), dstRect));
+    return result.release();
+}
+
 PassRefPtr<SkImageFilter> FEImage::createImageFilter(SkiaImageFilterBuilder* builder)
 {
-    if (!m_image)
-        return 0;
+    RenderObject* renderer = referencedRenderer();
+    if (!m_image && !renderer)
+        return adoptRef(new SkBitmapSource(SkBitmap()));
+
+    setOperatingColorSpace(ColorSpaceDeviceRGB);
+
+    if (renderer)
+        return createImageFilterForRenderer(renderer, builder);
+
+    FloatRect srcRect = FloatRect(FloatPoint(), m_image->size());
+    FloatRect dstRect = filterPrimitiveSubregion();
+
+    // FIXME: CSS image filters currently do not seem to set filter primitive
+    // subregion correctly if unspecified. So default to srcRect size if so.
+    if (dstRect.isEmpty())
+        dstRect = srcRect;
+
+    m_preserveAspectRatio->transformRect(dstRect, srcRect);
 
     if (!m_image->nativeImageForCurrentFrame())
-        return 0;
+        return adoptRef(new SkBitmapSource(SkBitmap()));
 
-    return adoptRef(new SkBitmapSource(m_image->nativeImageForCurrentFrame()->bitmap()));
+    RefPtr<SkImageFilter> result = adoptRef(new SkBitmapSource(m_image->nativeImageForCurrentFrame()->bitmap(), srcRect, dstRect));
+    return result.release();
 }
 
 } // namespace WebCore
diff --git a/Source/core/svg/graphics/filters/SVGFEImage.h b/Source/core/svg/graphics/filters/SVGFEImage.h
index b82f673..e9b481a 100644
--- a/Source/core/svg/graphics/filters/SVGFEImage.h
+++ b/Source/core/svg/graphics/filters/SVGFEImage.h
@@ -33,32 +33,33 @@
 class Image;
 class RenderObject;
 
-class FEImage : public FilterEffect {
+class FEImage FINAL : public FilterEffect {
 public:
-    static PassRefPtr<FEImage> createWithImage(Filter*, PassRefPtr<Image>, const SVGPreserveAspectRatio&);
-    static PassRefPtr<FEImage> createWithIRIReference(Filter*, Document&, const String&, const SVGPreserveAspectRatio&);
+    static PassRefPtr<FEImage> createWithImage(Filter*, PassRefPtr<Image>, PassRefPtr<SVGPreserveAspectRatio>);
+    static PassRefPtr<FEImage> createWithIRIReference(Filter*, Document&, const String&, PassRefPtr<SVGPreserveAspectRatio>);
 
-    virtual void determineAbsolutePaintRect();
+    virtual FloatRect determineAbsolutePaintRect(const FloatRect& requestedRect) OVERRIDE;
 
-    virtual FilterEffectType filterEffectType() const { return FilterEffectTypeImage; }
+    virtual FilterEffectType filterEffectType() const OVERRIDE { return FilterEffectTypeImage; }
 
-    virtual TextStream& externalRepresentation(TextStream&, int indention) const;
+    virtual TextStream& externalRepresentation(TextStream&, int indention) const OVERRIDE;
     virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
 
 private:
     virtual ~FEImage() { }
-    FEImage(Filter*, PassRefPtr<Image>, const SVGPreserveAspectRatio&);
-    FEImage(Filter*, Document&, const String&, const SVGPreserveAspectRatio&);
+    FEImage(Filter*, PassRefPtr<Image>, PassRefPtr<SVGPreserveAspectRatio>);
+    FEImage(Filter*, Document&, const String&, PassRefPtr<SVGPreserveAspectRatio>);
     RenderObject* referencedRenderer() const;
 
     virtual void applySoftware() OVERRIDE;
+    PassRefPtr<SkImageFilter> createImageFilterForRenderer(RenderObject* rendererer, SkiaImageFilterBuilder*);
 
     RefPtr<Image> m_image;
 
     // m_document will never be a dangling reference. See https://bugs.webkit.org/show_bug.cgi?id=99243
     Document* m_document;
     String m_href;
-    SVGPreserveAspectRatio m_preserveAspectRatio;
+    PassRefPtr<SVGPreserveAspectRatio> m_preserveAspectRatio;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/graphics/filters/SVGFilter.cpp b/Source/core/svg/graphics/filters/SVGFilter.cpp
index d7b9107..bd6fefd 100644
--- a/Source/core/svg/graphics/filters/SVGFilter.cpp
+++ b/Source/core/svg/graphics/filters/SVGFilter.cpp
@@ -25,14 +25,13 @@
 
 namespace WebCore {
 
-SVGFilter::SVGFilter(const AffineTransform& absoluteTransform, const FloatRect& absoluteSourceDrawingRegion, const FloatRect& targetBoundingBox, const FloatRect& filterRegion, bool effectBBoxMode)
+SVGFilter::SVGFilter(const AffineTransform& absoluteTransform, const IntRect& absoluteSourceDrawingRegion, const FloatRect& targetBoundingBox, const FloatRect& filterRegion, bool effectBBoxMode)
     : Filter(absoluteTransform)
     , m_absoluteSourceDrawingRegion(absoluteSourceDrawingRegion)
     , m_targetBoundingBox(targetBoundingBox)
     , m_effectBBoxMode(effectBBoxMode)
 {
     setFilterRegion(filterRegion);
-    setAbsoluteFilterRegion(absoluteTransform.mapRect(filterRegion));
 }
 
 float SVGFilter::applyHorizontalScale(float value) const
@@ -49,7 +48,7 @@
     return Filter::applyVerticalScale(value);
 }
 
-PassRefPtr<SVGFilter> SVGFilter::create(const AffineTransform& absoluteTransform, const FloatRect& absoluteSourceDrawingRegion, const FloatRect& targetBoundingBox, const FloatRect& filterRegion, bool effectBBoxMode)
+PassRefPtr<SVGFilter> SVGFilter::create(const AffineTransform& absoluteTransform, const IntRect& absoluteSourceDrawingRegion, const FloatRect& targetBoundingBox, const FloatRect& filterRegion, bool effectBBoxMode)
 {
     return adoptRef(new SVGFilter(absoluteTransform, absoluteSourceDrawingRegion, targetBoundingBox, filterRegion, effectBBoxMode));
 }
diff --git a/Source/core/svg/graphics/filters/SVGFilter.h b/Source/core/svg/graphics/filters/SVGFilter.h
index ad30b39..511dcc6 100644
--- a/Source/core/svg/graphics/filters/SVGFilter.h
+++ b/Source/core/svg/graphics/filters/SVGFilter.h
@@ -32,20 +32,20 @@
 
 namespace WebCore {
 
-class SVGFilter : public Filter {
+class SVGFilter FINAL : public Filter {
 public:
-    static PassRefPtr<SVGFilter> create(const AffineTransform&, const FloatRect&, const FloatRect&, const FloatRect&, bool);
+    static PassRefPtr<SVGFilter> create(const AffineTransform&, const IntRect&, const FloatRect&, const FloatRect&, bool);
 
-    virtual float applyHorizontalScale(float value) const;
-    virtual float applyVerticalScale(float value) const;
+    virtual float applyHorizontalScale(float value) const OVERRIDE;
+    virtual float applyVerticalScale(float value) const OVERRIDE;
 
-    virtual FloatRect sourceImageRect() const { return m_absoluteSourceDrawingRegion; }
+    virtual IntRect sourceImageRect() const OVERRIDE { return m_absoluteSourceDrawingRegion; }
     FloatRect targetBoundingBox() const { return m_targetBoundingBox; }
 
 private:
-    SVGFilter(const AffineTransform& absoluteTransform, const FloatRect& absoluteSourceDrawingRegion, const FloatRect& targetBoundingBox, const FloatRect& filterRegion, bool effectBBoxMode);
+    SVGFilter(const AffineTransform& absoluteTransform, const IntRect& absoluteSourceDrawingRegion, const FloatRect& targetBoundingBox, const FloatRect& filterRegion, bool effectBBoxMode);
 
-    FloatRect m_absoluteSourceDrawingRegion;
+    IntRect m_absoluteSourceDrawingRegion;
     FloatRect m_targetBoundingBox;
     bool m_effectBBoxMode;
 };
diff --git a/Source/core/svg/properties/NewSVGAnimatedProperty.cpp b/Source/core/svg/properties/NewSVGAnimatedProperty.cpp
new file mode 100644
index 0000000..707c982
--- /dev/null
+++ b/Source/core/svg/properties/NewSVGAnimatedProperty.cpp
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#include "config.h"
+#include "core/svg/properties/NewSVGAnimatedProperty.h"
+
+#include "core/svg/SVGElement.h"
+
+namespace WebCore {
+
+NewSVGAnimatedPropertyBase::NewSVGAnimatedPropertyBase(AnimatedPropertyType type, SVGElement* contextElement, const QualifiedName& attributeName)
+    : m_type(type)
+    , m_isReadOnly(false)
+    , m_isAnimating(false)
+    , m_contextElement(contextElement)
+    , m_attributeName(attributeName)
+{
+    ASSERT(m_contextElement);
+    ASSERT(m_attributeName != nullQName());
+    // FIXME: setContextElement should be delayed until V8 wrapper is created.
+    // FIXME: oilpan: or we can remove this backref ptr hack in oilpan.
+    m_contextElement->setContextElement();
+}
+
+NewSVGAnimatedPropertyBase::~NewSVGAnimatedPropertyBase()
+{
+    ASSERT(!isAnimating());
+}
+
+void NewSVGAnimatedPropertyBase::animationStarted()
+{
+    ASSERT(!isAnimating());
+    m_isAnimating = true;
+}
+
+void NewSVGAnimatedPropertyBase::animValWillChange()
+{
+    ASSERT(isAnimating());
+}
+
+void NewSVGAnimatedPropertyBase::animValDidChange()
+{
+    ASSERT(isAnimating());
+}
+
+void NewSVGAnimatedPropertyBase::animationEnded()
+{
+    ASSERT(isAnimating());
+    m_isAnimating = false;
+}
+
+void NewSVGAnimatedPropertyBase::synchronizeAttribute()
+{
+    ASSERT(needsSynchronizeAttribute());
+    AtomicString value(currentValueBase()->valueAsString());
+    m_contextElement->setSynchronizedLazyAttribute(m_attributeName, value);
+}
+
+bool NewSVGAnimatedPropertyBase::isSpecified() const
+{
+    return isAnimating() || contextElement()->hasAttribute(attributeName());
+}
+
+void NewSVGAnimatedPropertyBase::commitChange()
+{
+    contextElement()->invalidateSVGAttributes();
+    contextElement()->svgAttributeChanged(m_attributeName);
+}
+
+} // namespace WebCore
diff --git a/Source/core/svg/properties/NewSVGAnimatedProperty.h b/Source/core/svg/properties/NewSVGAnimatedProperty.h
new file mode 100644
index 0000000..25db5c9
--- /dev/null
+++ b/Source/core/svg/properties/NewSVGAnimatedProperty.h
@@ -0,0 +1,321 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+G*     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef NewSVGAnimatedProperty_h
+#define NewSVGAnimatedProperty_h
+
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/svg/SVGParsingError.h"
+#include "core/svg/properties/NewSVGPropertyTearOff.h"
+#include "core/svg/properties/SVGPropertyInfo.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class SVGElement;
+
+class NewSVGAnimatedPropertyBase : public RefCounted<NewSVGAnimatedPropertyBase> {
+public:
+    virtual ~NewSVGAnimatedPropertyBase();
+
+    virtual NewSVGPropertyBase* currentValueBase() = 0;
+
+    virtual void animationStarted();
+    virtual PassRefPtr<NewSVGPropertyBase> createAnimatedValue() = 0;
+    virtual void setAnimatedValue(PassRefPtr<NewSVGPropertyBase>) = 0;
+    virtual void animationEnded();
+    virtual void animValWillChange();
+    virtual void animValDidChange();
+
+    virtual bool needsSynchronizeAttribute() = 0;
+    virtual void synchronizeAttribute();
+
+    AnimatedPropertyType type() const
+    {
+        return m_type;
+    }
+
+    SVGElement* contextElement() const
+    {
+        return m_contextElement;
+    }
+
+    const QualifiedName& attributeName() const
+    {
+        return m_attributeName;
+    }
+
+    bool isAnimating() const
+    {
+        return m_isAnimating;
+    }
+
+    bool isReadOnly() const
+    {
+        return m_isReadOnly;
+    }
+
+    void setReadOnly()
+    {
+        m_isReadOnly = true;
+    }
+
+    bool isSpecified() const;
+
+protected:
+    NewSVGAnimatedPropertyBase(AnimatedPropertyType, SVGElement*, const QualifiedName& attributeName);
+    void commitChange();
+
+private:
+    const AnimatedPropertyType m_type;
+    bool m_isReadOnly;
+    bool m_isAnimating;
+
+    // This reference is kept alive from V8 wrapper
+    SVGElement* m_contextElement;
+
+    const QualifiedName& m_attributeName;
+
+    WTF_MAKE_NONCOPYABLE(NewSVGAnimatedPropertyBase);
+};
+
+template <typename Property>
+class NewSVGAnimatedPropertyCommon : public NewSVGAnimatedPropertyBase {
+public:
+    Property* baseValue()
+    {
+        return m_baseValue.get();
+    }
+
+    Property* currentValue()
+    {
+        return m_currentValue ? m_currentValue.get() : m_baseValue.get();
+    }
+
+    const Property* currentValue() const
+    {
+        return const_cast<NewSVGAnimatedPropertyCommon*>(this)->currentValue();
+    }
+
+    virtual NewSVGPropertyBase* currentValueBase() OVERRIDE
+    {
+        return currentValue();
+    }
+
+    void setBaseValueAsString(const String& value, SVGParsingError& parseError)
+    {
+        TrackExceptionState es;
+
+        m_baseValue->setValueAsString(value, es);
+
+        if (es.hadException())
+            parseError = ParsingAttributeFailedError;
+    }
+
+    virtual PassRefPtr<NewSVGPropertyBase> createAnimatedValue() OVERRIDE
+    {
+        return m_baseValue->clone();
+    }
+
+    virtual void setAnimatedValue(PassRefPtr<NewSVGPropertyBase> passValue) OVERRIDE
+    {
+        ASSERT(isAnimating());
+
+        RefPtr<NewSVGPropertyBase> value = passValue;
+        ASSERT(value->type() == Property::classType());
+        m_currentValue = static_pointer_cast<Property>(value.release());
+    }
+
+    virtual void animationEnded() OVERRIDE
+    {
+        NewSVGAnimatedPropertyBase::animationEnded();
+
+        ASSERT(m_currentValue);
+        m_currentValue.clear();
+    }
+
+protected:
+    NewSVGAnimatedPropertyCommon(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<Property> initialValue)
+        : NewSVGAnimatedPropertyBase(Property::classType(), contextElement, attributeName)
+        , m_baseValue(initialValue)
+    {
+    }
+
+private:
+    RefPtr<Property> m_baseValue;
+    RefPtr<Property> m_currentValue;
+};
+
+// Implementation of SVGAnimatedProperty which uses primitive types.
+// This is for classes which return primitive type for its "animVal".
+// Examples are SVGAnimatedBoolean, SVGAnimatedNumber, etc.
+template <typename Property, typename TearOffType = typename Property::TearOffType, typename PrimitiveType = typename Property::PrimitiveType>
+class NewSVGAnimatedProperty : public NewSVGAnimatedPropertyCommon<Property> {
+public:
+    static PassRefPtr<NewSVGAnimatedProperty<Property> > create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<Property> initialValue)
+    {
+        return adoptRef(new NewSVGAnimatedProperty<Property>(contextElement, attributeName, initialValue));
+    }
+
+    virtual bool needsSynchronizeAttribute() OVERRIDE
+    {
+        // DOM attribute synchronization is only needed if tear-off is being touched from javascript or the property is being animated.
+        // This prevents unnecessary attribute creation on target element.
+        return m_baseValueUpdated || this->isAnimating();
+    }
+
+    virtual void synchronizeAttribute() OVERRIDE
+    {
+        NewSVGAnimatedPropertyBase::synchronizeAttribute();
+        m_baseValueUpdated = false;
+    }
+
+    // SVGAnimated* DOM Spec implementations:
+
+    // baseVal()/setBaseVal()/animVal() are only to be used from SVG DOM implementation.
+    // Use currentValue() from C++ code.
+    PrimitiveType baseVal()
+    {
+        return this->baseValue()->value();
+    }
+
+    void setBaseVal(PrimitiveType value, WebCore::ExceptionState& exceptionState)
+    {
+        if (this->isReadOnly()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only.");
+            return;
+        }
+
+        this->baseValue()->setValue(value);
+        m_baseValueUpdated = true;
+
+        ASSERT(this->attributeName() != nullQName());
+        this->contextElement()->invalidateSVGAttributes();
+        this->contextElement()->svgAttributeChanged(this->attributeName());
+    }
+
+    PrimitiveType animVal()
+    {
+        return this->currentValue()->value();
+    }
+
+protected:
+    NewSVGAnimatedProperty(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<Property> initialValue)
+        : NewSVGAnimatedPropertyCommon<Property>(contextElement, attributeName, initialValue)
+        , m_baseValueUpdated(false)
+    {
+    }
+
+    bool m_baseValueUpdated;
+};
+
+// Implementation of SVGAnimatedProperty which uses tear-off value types.
+// These classes has "void" for its PrimitiveType.
+// This is for classes which return special type for its "animVal".
+// Examples are SVGAnimatedLength, SVGAnimatedRect, SVGAnimated*List, etc.
+template <typename Property, typename TearOffType>
+class NewSVGAnimatedProperty<Property, TearOffType, void> : public NewSVGAnimatedPropertyCommon<Property> {
+public:
+    static PassRefPtr<NewSVGAnimatedProperty<Property> > create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<Property> initialValue)
+    {
+        return adoptRef(new NewSVGAnimatedProperty<Property>(contextElement, attributeName, initialValue));
+    }
+
+    virtual void setAnimatedValue(PassRefPtr<NewSVGPropertyBase> value) OVERRIDE
+    {
+        NewSVGAnimatedPropertyCommon<Property>::setAnimatedValue(value);
+        updateAnimValTearOffIfNeeded();
+    }
+
+    virtual void animationEnded() OVERRIDE
+    {
+        NewSVGAnimatedPropertyCommon<Property>::animationEnded();
+        updateAnimValTearOffIfNeeded();
+    }
+
+    virtual bool needsSynchronizeAttribute() OVERRIDE
+    {
+        // DOM attribute synchronization is only needed if tear-off is being touched from javascript or the property is being animated.
+        // This prevents unnecessary attribute creation on target element.
+        return m_baseValTearOff || this->isAnimating();
+    }
+
+    // SVGAnimated* DOM Spec implementations:
+
+    // baseVal()/animVal() are only to be used from SVG DOM implementation.
+    // Use currentValue() from C++ code.
+    virtual TearOffType* baseVal()
+    {
+        if (!m_baseValTearOff) {
+            m_baseValTearOff = TearOffType::create(this->baseValue(), this->contextElement(), PropertyIsNotAnimVal, this->attributeName());
+            if (this->isReadOnly())
+                m_baseValTearOff->setIsReadOnlyProperty();
+        }
+
+        return m_baseValTearOff.get();
+    }
+
+    TearOffType* animVal()
+    {
+        if (!m_animValTearOff)
+            m_animValTearOff = TearOffType::create(this->currentValue(), this->contextElement(), PropertyIsAnimVal, this->attributeName());
+
+        return m_animValTearOff.get();
+    }
+
+protected:
+    NewSVGAnimatedProperty(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtr<Property> initialValue)
+        : NewSVGAnimatedPropertyCommon<Property>(contextElement, attributeName, initialValue)
+    {
+    }
+
+private:
+    void updateAnimValTearOffIfNeeded()
+    {
+        if (m_animValTearOff)
+            m_animValTearOff->setTarget(this->currentValue());
+    }
+
+    // When still (not animated):
+    //     Both m_animValTearOff and m_baseValTearOff target m_baseValue.
+    // When animated:
+    //     m_animValTearOff targets m_currentValue.
+    //     m_baseValTearOff targets m_baseValue.
+    RefPtr<TearOffType> m_baseValTearOff;
+    RefPtr<TearOffType> m_animValTearOff;
+};
+
+}
+
+#endif // NewSVGAnimatedProperty_h
diff --git a/Source/core/svg/properties/NewSVGListPropertyHelper.h b/Source/core/svg/properties/NewSVGListPropertyHelper.h
new file mode 100644
index 0000000..0192e34
--- /dev/null
+++ b/Source/core/svg/properties/NewSVGListPropertyHelper.h
@@ -0,0 +1,366 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef NewSVGListPropertyHelper_h
+#define NewSVGListPropertyHelper_h
+
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/svg/properties/NewSVGProperty.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+// This is an implementation of the SVG*List property spec:
+// http://www.w3.org/TR/SVG/single-page.html#types-InterfaceSVGLengthList
+template<typename Derived, typename ItemProperty>
+class NewSVGListPropertyHelper : public NewSVGPropertyBase {
+public:
+    typedef ItemProperty ItemPropertyType;
+
+    NewSVGListPropertyHelper()
+        : NewSVGPropertyBase(Derived::classType())
+    {
+    }
+
+    ~NewSVGListPropertyHelper()
+    {
+        clear();
+    }
+
+    // used from Blink C++ code:
+
+    ItemPropertyType* at(size_t index)
+    {
+        ASSERT(index < m_values.size());
+        ASSERT(m_values.at(index)->ownerList() == this);
+        return m_values.at(index).get();
+    }
+
+    const ItemPropertyType* at(size_t index) const
+    {
+        return const_cast<NewSVGListPropertyHelper<Derived, ItemProperty>*>(this)->at(index);
+    }
+
+    class ConstIterator {
+    private:
+        typedef typename Vector<RefPtr<ItemPropertyType> >::const_iterator WrappedType;
+
+    public:
+        ConstIterator(WrappedType it)
+            : m_it(it)
+        {
+        }
+
+        ConstIterator& operator++() { ++m_it; return *this; }
+
+        bool operator==(const ConstIterator& o) const { return m_it == o.m_it; }
+        bool operator!=(const ConstIterator& o) const { return m_it != o.m_it; }
+
+        PassRefPtr<ItemPropertyType> operator*() { return *m_it; }
+        PassRefPtr<ItemPropertyType> operator->() { return *m_it; }
+
+    private:
+        WrappedType m_it;
+    };
+
+    ConstIterator begin() const
+    {
+        return ConstIterator(m_values.begin());
+    }
+
+    ConstIterator end() const
+    {
+        return ConstIterator(m_values.end());
+    }
+
+    void append(PassRefPtr<ItemPropertyType> passNewItem)
+    {
+        RefPtr<ItemPropertyType> newItem = passNewItem;
+
+        ASSERT(newItem);
+        m_values.append(newItem);
+        newItem->setOwnerList(this);
+    }
+
+    bool operator==(const Derived&) const;
+    bool operator!=(const Derived& other) const
+    {
+        return !(*this == other);
+    }
+
+    bool isEmpty() const
+    {
+        return !numberOfItems();
+    }
+
+    // SVGList*Property DOM spec:
+
+    size_t numberOfItems() const
+    {
+        return m_values.size();
+    }
+
+    void clear();
+
+    PassRefPtr<ItemPropertyType> initialize(PassRefPtr<ItemPropertyType>);
+    PassRefPtr<ItemPropertyType> getItem(size_t, ExceptionState&);
+    PassRefPtr<ItemPropertyType> insertItemBefore(PassRefPtr<ItemPropertyType>, size_t);
+    PassRefPtr<ItemPropertyType> removeItem(size_t, ExceptionState&);
+    PassRefPtr<ItemPropertyType> appendItem(PassRefPtr<ItemPropertyType>);
+    PassRefPtr<ItemPropertyType> replaceItem(PassRefPtr<ItemPropertyType>, size_t, ExceptionState&);
+
+protected:
+    void deepCopy(PassRefPtr<Derived>);
+
+private:
+    inline bool checkIndexBound(size_t, ExceptionState&);
+    bool removeFromOldOwnerListAndAdjustIndex(PassRefPtr<ItemPropertyType>, size_t* indexToModify);
+    size_t findItem(PassRefPtr<ItemPropertyType>);
+
+    Vector<RefPtr<ItemPropertyType> > m_values;
+
+    static PassRefPtr<Derived> toDerived(PassRefPtr<NewSVGPropertyBase> passBase)
+    {
+        if (!passBase)
+            return 0;
+
+        RefPtr<NewSVGPropertyBase> base = passBase;
+        ASSERT(base->type() == Derived::classType());
+        return static_pointer_cast<Derived>(base.release());
+    }
+};
+
+template<typename Derived, typename ItemProperty>
+bool NewSVGListPropertyHelper<Derived, ItemProperty>::operator==(const Derived& other) const
+{
+    if (numberOfItems() != other.numberOfItems())
+        return false;
+
+    size_t length = numberOfItems();
+    for (size_t i = 0; i < length; ++i) {
+        if (*at(i) != *other.at(i))
+            return false;
+    }
+
+    return true;
+}
+
+template<typename Derived, typename ItemProperty>
+void NewSVGListPropertyHelper<Derived, ItemProperty>::clear()
+{
+    // detach all list items as they are no longer part of this list
+    typename Vector<RefPtr<ItemPropertyType> >::const_iterator it = m_values.begin();
+    typename Vector<RefPtr<ItemPropertyType> >::const_iterator itEnd = m_values.end();
+    for (; it != itEnd; ++it) {
+        ASSERT((*it)->ownerList() == this);
+        (*it)->setOwnerList(0);
+    }
+
+    m_values.clear();
+}
+
+template<typename Derived, typename ItemProperty>
+PassRefPtr<ItemProperty> NewSVGListPropertyHelper<Derived, ItemProperty>::initialize(PassRefPtr<ItemProperty> passNewItem)
+{
+    RefPtr<ItemPropertyType> newItem = passNewItem;
+
+    // Spec: If the inserted item is already in a list, it is removed from its previous list before it is inserted into this list.
+    removeFromOldOwnerListAndAdjustIndex(newItem, 0);
+
+    // Spec: Clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter.
+    clear();
+    append(newItem);
+    return newItem.release();
+}
+
+template<typename Derived, typename ItemProperty>
+PassRefPtr<ItemProperty> NewSVGListPropertyHelper<Derived, ItemProperty>::getItem(size_t index, ExceptionState& exceptionState)
+{
+    if (!checkIndexBound(index, exceptionState))
+        return 0;
+
+    ASSERT(index < m_values.size());
+    ASSERT(m_values.at(index)->ownerList() == this);
+    return m_values.at(index);
+}
+
+template<typename Derived, typename ItemProperty>
+PassRefPtr<ItemProperty> NewSVGListPropertyHelper<Derived, ItemProperty>::insertItemBefore(PassRefPtr<ItemProperty> passNewItem, size_t index)
+{
+    // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list.
+    if (index > m_values.size())
+        index = m_values.size();
+
+    RefPtr<ItemPropertyType> newItem = passNewItem;
+
+    // Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
+    if (!removeFromOldOwnerListAndAdjustIndex(newItem, &index)) {
+        // Inserting the item before itself is a no-op.
+        return newItem.release();
+    }
+
+    // Spec: Inserts a new item into the list at the specified position. The index of the item before which the new item is to be
+    // inserted. The first item is number 0. If the index is equal to 0, then the new item is inserted at the front of the list.
+    m_values.insert(index, newItem);
+    newItem->setOwnerList(this);
+
+    return newItem.release();
+}
+
+template<typename Derived, typename ItemProperty>
+PassRefPtr<ItemProperty> NewSVGListPropertyHelper<Derived, ItemProperty>::removeItem(size_t index, ExceptionState& exceptionState)
+{
+    if (index >= m_values.size()) {
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("index", index, m_values.size()));
+        return 0;
+    }
+    ASSERT(m_values.at(index)->ownerList() == this);
+    RefPtr<ItemPropertyType> oldItem = m_values.at(index);
+    m_values.remove(index);
+    oldItem->setOwnerList(0);
+    return oldItem.release();
+}
+
+template<typename Derived, typename ItemProperty>
+PassRefPtr<ItemProperty> NewSVGListPropertyHelper<Derived, ItemProperty>::appendItem(PassRefPtr<ItemProperty> passNewItem)
+{
+    RefPtr<ItemPropertyType> newItem = passNewItem;
+
+    // Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
+    removeFromOldOwnerListAndAdjustIndex(newItem, 0);
+
+    // Append the value and wrapper at the end of the list.
+    append(newItem);
+
+    return newItem.release();
+}
+
+template<typename Derived, typename ItemProperty>
+PassRefPtr<ItemProperty> NewSVGListPropertyHelper<Derived, ItemProperty>::replaceItem(PassRefPtr<ItemProperty> passNewItem, size_t index, ExceptionState& exceptionState)
+{
+    if (!checkIndexBound(index, exceptionState))
+        return 0;
+
+    RefPtr<ItemPropertyType> newItem = passNewItem;
+
+    // Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
+    // Spec: If the item is already in this list, note that the index of the item to replace is before the removal of the item.
+    if (!removeFromOldOwnerListAndAdjustIndex(newItem, &index)) {
+        // Replacing the item with itself is a no-op.
+        return newItem.release();
+    }
+
+    if (m_values.isEmpty()) {
+        // 'newItem' already lived in our list, we removed it, and now we're empty, which means there's nothing to replace.
+        exceptionState.throwDOMException(IndexSizeError, String::format("Failed to replace the provided item at index %zu.", index));
+        return 0;
+    }
+
+    // Update the value at the desired position 'index'.
+    RefPtr<ItemPropertyType>& position = m_values[index];
+    ASSERT(position->ownerList() == this);
+    position->setOwnerList(0);
+    position = newItem;
+    newItem->setOwnerList(this);
+
+    return newItem.release();
+}
+
+template<typename Derived, typename ItemProperty>
+bool NewSVGListPropertyHelper<Derived, ItemProperty>::checkIndexBound(size_t index, ExceptionState& exceptionState)
+{
+    if (index >= m_values.size()) {
+        exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("index", index, m_values.size()));
+        return false;
+    }
+
+    return true;
+}
+
+template<typename Derived, typename ItemProperty>
+bool NewSVGListPropertyHelper<Derived, ItemProperty>::removeFromOldOwnerListAndAdjustIndex(PassRefPtr<ItemPropertyType> passItem, size_t* indexToModify)
+{
+    RefPtr<ItemPropertyType> item = passItem;
+    ASSERT(item);
+    RefPtr<Derived> ownerList = toDerived(item->ownerList());
+    if (!ownerList)
+        return true;
+
+    // Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
+    // 'newItem' is already living in another list. If it's not our list, synchronize the other lists wrappers after the removal.
+    bool livesInOtherList = ownerList.get() != this;
+    size_t indexToRemove = ownerList->findItem(item);
+    ASSERT(indexToRemove != WTF::kNotFound);
+
+    // Do not remove newItem if already in this list at the target index.
+    if (!livesInOtherList && indexToModify && indexToRemove == *indexToModify)
+        return false;
+
+    ownerList->removeItem(indexToRemove, ASSERT_NO_EXCEPTION);
+
+    if (!indexToModify)
+        return true;
+
+    // If the item lived in our list, adjust the insertion index.
+    if (!livesInOtherList) {
+        size_t& index = *indexToModify;
+        // Spec: If the item is already in this list, note that the index of the item to (replace|insert before) is before the removal of the item.
+        if (static_cast<size_t>(indexToRemove) < index)
+            --index;
+    }
+
+    return true;
+}
+
+template<typename Derived, typename ItemProperty>
+size_t NewSVGListPropertyHelper<Derived, ItemProperty>::findItem(PassRefPtr<ItemPropertyType> item)
+{
+    return m_values.find(item);
+}
+
+template<typename Derived, typename ItemProperty>
+void NewSVGListPropertyHelper<Derived, ItemProperty>::deepCopy(PassRefPtr<Derived> passFrom)
+{
+    RefPtr<Derived> from = passFrom;
+
+    clear();
+    typename Vector<RefPtr<ItemPropertyType> >::const_iterator it = from->m_values.begin();
+    typename Vector<RefPtr<ItemPropertyType> >::const_iterator itEnd = from->m_values.end();
+    for (; it != itEnd; ++it) {
+        append((*it)->clone());
+    }
+}
+
+}
+
+#endif // NewSVGListPropertyHelper_h
diff --git a/Source/core/svg/properties/NewSVGListPropertyTearOffHelper.h b/Source/core/svg/properties/NewSVGListPropertyTearOffHelper.h
new file mode 100644
index 0000000..b5ec8ca
--- /dev/null
+++ b/Source/core/svg/properties/NewSVGListPropertyTearOffHelper.h
@@ -0,0 +1,199 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef NewSVGListPropertyTearOffHelper_h
+#define NewSVGListPropertyTearOffHelper_h
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/svg/properties/NewSVGPropertyTearOff.h"
+#include "wtf/HashMap.h"
+
+namespace WebCore {
+
+template<typename Derived, typename ListProperty>
+class NewSVGListPropertyTearOffHelper : public NewSVGPropertyTearOff<ListProperty> {
+public:
+    typedef ListProperty ListPropertyType;
+    typedef typename ListPropertyType::ItemPropertyType ItemPropertyType;
+    typedef typename ItemPropertyType::TearOffType ItemTearOffType;
+
+    // SVG*List DOM interface:
+
+    // WebIDL requires "unsigned long" type instead of size_t.
+    unsigned long numberOfItems()
+    {
+        return toDerived()->target()->numberOfItems();
+    }
+
+    void clear(ExceptionState& exceptionState)
+    {
+        if (toDerived()->isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return;
+        }
+
+        toDerived()->target()->clear();
+    }
+
+    PassRefPtr<ItemTearOffType> initialize(PassRefPtr<ItemTearOffType> passItem, ExceptionState& exceptionState)
+    {
+        RefPtr<ItemTearOffType> item = passItem;
+
+        if (toDerived()->isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return 0;
+        }
+
+        if (!item) {
+            exceptionState.throwTypeError("Lists must be initialized with a valid item.");
+            return 0;
+        }
+
+        RefPtr<ItemPropertyType> value = toDerived()->target()->initialize(cloneTargetIfNeeded(item));
+        toDerived()->commitChange();
+
+        return createItemTearOff(value.release());
+    }
+
+    PassRefPtr<ItemTearOffType> getItem(unsigned long index, ExceptionState& exceptionState)
+    {
+        RefPtr<ItemPropertyType> value = toDerived()->target()->getItem(index, exceptionState);
+        return createItemTearOff(value.release());
+    }
+
+    PassRefPtr<ItemTearOffType> insertItemBefore(PassRefPtr<ItemTearOffType> passItem, unsigned long index, ExceptionState& exceptionState)
+    {
+        RefPtr<ItemTearOffType> item = passItem;
+
+        if (toDerived()->isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return 0;
+        }
+
+        if (!item) {
+            exceptionState.throwTypeError("An invalid item cannot be inserted to a list.");
+            return 0;
+        }
+
+        RefPtr<ItemPropertyType> value = toDerived()->target()->insertItemBefore(cloneTargetIfNeeded(item), index);
+        toDerived()->commitChange();
+
+        return createItemTearOff(value.release());
+    }
+
+    PassRefPtr<ItemTearOffType> replaceItem(PassRefPtr<ItemTearOffType> passItem, unsigned long index, ExceptionState& exceptionState)
+    {
+        RefPtr<ItemTearOffType> item = passItem;
+
+        if (toDerived()->isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return 0;
+        }
+
+        if (!item) {
+            exceptionState.throwTypeError("An invalid item cannot be replaced with an existing list item.");
+            return 0;
+        }
+
+        RefPtr<ItemPropertyType> value = toDerived()->target()->replaceItem(cloneTargetIfNeeded(item), index, exceptionState);
+        toDerived()->commitChange();
+
+        return createItemTearOff(value.release());
+    }
+
+    PassRefPtr<ItemTearOffType> removeItem(unsigned long index, ExceptionState& exceptionState)
+    {
+        RefPtr<ItemPropertyType> value = toDerived()->target()->removeItem(index, exceptionState);
+        toDerived()->commitChange();
+
+        return createItemTearOff(value.release());
+    }
+
+    PassRefPtr<ItemTearOffType> appendItem(PassRefPtr<ItemTearOffType> passItem, ExceptionState& exceptionState)
+    {
+        RefPtr<ItemTearOffType> item = passItem;
+
+        if (toDerived()->isImmutable()) {
+            exceptionState.throwDOMException(NoModificationAllowedError, "The object is read-only.");
+            return 0;
+        }
+
+        if (!item) {
+            exceptionState.throwTypeError("An invalid item cannot be appended to a list.");
+            return 0;
+        }
+
+        RefPtr<ItemPropertyType> value = toDerived()->target()->appendItem(cloneTargetIfNeeded(item));
+        toDerived()->commitChange();
+
+        return createItemTearOff(value.release());
+    }
+
+protected:
+    NewSVGListPropertyTearOffHelper(PassRefPtr<ListPropertyType> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+        : NewSVGPropertyTearOff<ListPropertyType>(target, contextElement, propertyIsAnimVal, attributeName)
+    {
+    }
+
+    PassRefPtr<ItemPropertyType> cloneTargetIfNeeded(PassRefPtr<ItemTearOffType> passNewItem)
+    {
+        RefPtr<ItemTearOffType> newItem = passNewItem;
+
+        // |newItem| is immutable, OR
+        // |newItem| belongs to a SVGElement, but it does not belong to an animated list
+        // (for example: "textElement.x.baseVal.appendItem(rectElement.width.baseVal)")
+        if (newItem->isImmutable()
+            || (newItem->contextElement() && !newItem->target()->ownerList())) {
+            // We have to copy the incoming |newItem|, as we're not allowed to insert this tear off as is into our wrapper cache.
+            // Otherwise we'll end up having two tearoffs that operate on the same SVGProperty. Consider the example above:
+            // SVGRectElements SVGAnimatedLength 'width' property baseVal points to the same tear off object
+            // that's inserted into SVGTextElements SVGAnimatedLengthList 'x'. textElement.x.baseVal.getItem(0).value += 150 would
+            // mutate the rectElement width _and_ the textElement x list. That's obviously wrong, take care of that.
+            return newItem->target()->clone();
+        }
+
+        return newItem->target();
+    }
+
+    PassRefPtr<ItemTearOffType> createItemTearOff(PassRefPtr<ItemPropertyType> value)
+    {
+        if (!value)
+            return 0;
+
+        return ItemTearOffType::create(value, toDerived()->contextElement(), toDerived()->propertyIsAnimVal(), toDerived()->attributeName());
+    }
+
+private:
+    Derived* toDerived() { return static_cast<Derived*>(this); }
+};
+
+}
+
+#endif // NewSVGListPropertyTearOffHelper_h
diff --git a/Source/core/svg/properties/NewSVGProperty.h b/Source/core/svg/properties/NewSVGProperty.h
new file mode 100644
index 0000000..5767e94
--- /dev/null
+++ b/Source/core/svg/properties/NewSVGProperty.h
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef NewSVGProperty_h
+#define NewSVGProperty_h
+
+#include "core/svg/properties/SVGPropertyInfo.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class ExceptionState;
+class QualifiedName;
+class SVGElement;
+class SVGAnimationElement;
+
+class NewSVGPropertyBase : public RefCounted<NewSVGPropertyBase> {
+    WTF_MAKE_NONCOPYABLE(NewSVGPropertyBase);
+
+public:
+    // Properties do not have a primitive type by default
+    typedef void PrimitiveType;
+
+    virtual ~NewSVGPropertyBase()
+    {
+        ASSERT(!m_ownerList);
+    }
+
+    // FIXME: remove this in WebAnimations transition.
+    // This is used from SVGAnimatedNewPropertyAnimator for its animate-by-string implementation.
+    virtual PassRefPtr<NewSVGPropertyBase> cloneForAnimation(const String&) const = 0;
+
+    virtual String valueAsString() const = 0;
+
+    // FIXME: remove below and just have this inherit AnimatableValue in WebAnimations transition.
+    virtual void add(PassRefPtr<NewSVGPropertyBase>, SVGElement*) = 0;
+    virtual void calculateAnimatedValue(SVGAnimationElement*, float percentage, unsigned repeatCount, PassRefPtr<NewSVGPropertyBase> from, PassRefPtr<NewSVGPropertyBase> to, PassRefPtr<NewSVGPropertyBase> toAtEndOfDurationValue, SVGElement*) = 0;
+    virtual float calculateDistance(PassRefPtr<NewSVGPropertyBase> to, SVGElement*) = 0;
+
+    AnimatedPropertyType type()
+    {
+        return m_type;
+    }
+
+    NewSVGPropertyBase* ownerList() const
+    {
+        return m_ownerList;
+    }
+
+    void setOwnerList(NewSVGPropertyBase* ownerList)
+    {
+        // Previous owner list must be cleared before setting new owner list.
+        ASSERT((!ownerList && m_ownerList) || (ownerList && !m_ownerList));
+
+        m_ownerList = ownerList;
+    }
+
+protected:
+    explicit NewSVGPropertyBase(AnimatedPropertyType type)
+        : m_type(type)
+        , m_ownerList(0)
+    {
+    }
+
+private:
+    const AnimatedPropertyType m_type;
+
+    // FIXME: oilpan: This is kept as a raw ptr to break reference cycle. Should be Member in oilpan.
+    NewSVGPropertyBase* m_ownerList;
+};
+
+}
+
+#endif // NewSVGProperty_h
diff --git a/Source/core/rendering/LayoutIndicator.cpp b/Source/core/svg/properties/NewSVGPropertyTearOff.cpp
similarity index 79%
copy from Source/core/rendering/LayoutIndicator.cpp
copy to Source/core/svg/properties/NewSVGPropertyTearOff.cpp
index a57c53c..ab8eefd 100644
--- a/Source/core/rendering/LayoutIndicator.cpp
+++ b/Source/core/svg/properties/NewSVGPropertyTearOff.cpp
@@ -29,14 +29,20 @@
  */
 
 #include "config.h"
-#include "core/rendering/LayoutIndicator.h"
+#include "core/svg/properties/NewSVGPropertyTearOff.h"
+
+#include "core/svg/SVGElement.h"
 
 namespace WebCore {
 
-#ifndef NDEBUG
-
-size_t LayoutIndicator::s_inLayout = 0;
-
-#endif
-
+void NewSVGPropertyTearOffBase::commitChange()
+{
+    ASSERT(!isImmutable());
+    if (!contextElement() || isAnimVal())
+        return;
+    ASSERT(m_attributeName != nullQName());
+    contextElement()->invalidateSVGAttributes();
+    contextElement()->svgAttributeChanged(m_attributeName);
 }
+
+} // namespace WebCore
diff --git a/Source/core/svg/properties/NewSVGPropertyTearOff.h b/Source/core/svg/properties/NewSVGPropertyTearOff.h
new file mode 100644
index 0000000..d569580
--- /dev/null
+++ b/Source/core/svg/properties/NewSVGPropertyTearOff.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * 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.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "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 THE COPYRIGHT
+ * OWNER 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.
+ */
+
+#ifndef NewSVGPropertyTearOff_h
+#define NewSVGPropertyTearOff_h
+
+#include "core/dom/QualifiedName.h"
+#include "core/svg/properties/NewSVGProperty.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+enum PropertyIsAnimValType {
+    PropertyIsNotAnimVal,
+    PropertyIsAnimVal
+};
+
+class NewSVGPropertyTearOffBase : public RefCounted<NewSVGPropertyTearOffBase> {
+public:
+    virtual ~NewSVGPropertyTearOffBase() { }
+
+    PropertyIsAnimValType propertyIsAnimVal() const
+    {
+        return m_propertyIsAnimVal;
+    }
+
+    bool isAnimVal() const
+    {
+        return m_propertyIsAnimVal == PropertyIsAnimVal;
+    }
+
+    bool isReadOnlyProperty() const
+    {
+        return m_isReadOnlyProperty;
+    }
+
+    void setIsReadOnlyProperty()
+    {
+        m_isReadOnlyProperty = true;
+    }
+
+    bool isImmutable() const
+    {
+        return isReadOnlyProperty() || isAnimVal();
+    }
+
+    virtual void commitChange();
+
+    SVGElement* contextElement()
+    {
+        return m_contextElement;
+    }
+
+    const QualifiedName& attributeName()
+    {
+        return m_attributeName;
+    }
+
+    virtual AnimatedPropertyType type() const = 0;
+
+protected:
+    NewSVGPropertyTearOffBase(SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+        : m_contextElement(contextElement)
+        , m_propertyIsAnimVal(propertyIsAnimVal)
+        , m_isReadOnlyProperty(false)
+        , m_attributeName(attributeName)
+    {
+    }
+
+private:
+    // These references are kept alive from V8 wrapper to prevent reference cycles
+    SVGElement* m_contextElement;
+
+    PropertyIsAnimValType m_propertyIsAnimVal;
+    bool m_isReadOnlyProperty;
+    QualifiedName m_attributeName;
+};
+
+template <typename Property>
+class NewSVGPropertyTearOff : public NewSVGPropertyTearOffBase {
+public:
+    Property* target()
+    {
+        return m_target.get();
+    }
+
+    void setTarget(PassRefPtr<Property> target)
+    {
+        m_target = target;
+    }
+
+    virtual AnimatedPropertyType type() const OVERRIDE
+    {
+        return Property::classType();
+    }
+
+protected:
+    NewSVGPropertyTearOff(PassRefPtr<Property> target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = nullQName())
+        : NewSVGPropertyTearOffBase(contextElement, propertyIsAnimVal, attributeName)
+        , m_target(target)
+    {
+        ASSERT(m_target);
+    }
+
+private:
+    RefPtr<Property> m_target;
+};
+
+}
+
+#endif // NewSVGPropertyTearOff_h
diff --git a/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h b/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
index 962e7f3..dd90980 100644
--- a/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
@@ -32,8 +32,13 @@
     virtual void setBaseVal(const unsigned& property, ExceptionState& exceptionState)
     {
         // All SVG enumeration values, that are allowed to be set via SVG DOM start with 1, 0 corresponds to unknown and is not settable through SVG DOM.
-        if (!property || property > SVGPropertyTraits<EnumType>::highestEnumValue()) {
-            exceptionState.throwUninformativeAndGenericTypeError();
+        if (!property) {
+            exceptionState.throwTypeError("The enumeration value provided is 0, which is not settable.");
+            return;
+        }
+
+        if (property > SVGPropertyTraits<EnumType>::highestEnumValue()) {
+            exceptionState.throwTypeError("The enumeration value provided (" + String::number(property) + ") is larger than the largest allowed value (" + String::number(SVGPropertyTraits<EnumType>::highestEnumValue()) + ").");
             return;
         }
         SVGAnimatedStaticPropertyTearOff<unsigned>::setBaseVal(property, exceptionState);
diff --git a/Source/core/svg/properties/SVGAnimatedPathSegListPropertyTearOff.h b/Source/core/svg/properties/SVGAnimatedPathSegListPropertyTearOff.h
index dfdb6d4..fb1f47c 100644
--- a/Source/core/svg/properties/SVGAnimatedPathSegListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGAnimatedPathSegListPropertyTearOff.h
@@ -29,16 +29,16 @@
 
 namespace WebCore {
 
-class SVGAnimatedPathSegListPropertyTearOff : public SVGAnimatedListPropertyTearOff<SVGPathSegList> {
+class SVGAnimatedPathSegListPropertyTearOff FINAL : public SVGAnimatedListPropertyTearOff<SVGPathSegList> {
 public:
-    virtual SVGListProperty<SVGPathSegList>* baseVal()
+    virtual SVGListProperty<SVGPathSegList>* baseVal() OVERRIDE
     {
         if (!m_baseVal)
             m_baseVal = SVGPathSegListPropertyTearOff::create(this, BaseValRole, PathSegUnalteredRole, m_values, m_wrappers);
         return static_cast<SVGListProperty<SVGPathSegList>*>(m_baseVal.get());
     }
 
-    virtual SVGListProperty<SVGPathSegList>* animVal()
+    virtual SVGListProperty<SVGPathSegList>* animVal() OVERRIDE
     {
         if (!m_animVal)
             m_animVal = SVGPathSegListPropertyTearOff::create(this, AnimValRole, PathSegUnalteredRole, m_values, m_wrappers);
diff --git a/Source/core/svg/properties/SVGAnimatedProperty.cpp b/Source/core/svg/properties/SVGAnimatedProperty.cpp
index 2258ad9..b1e1e78 100644
--- a/Source/core/svg/properties/SVGAnimatedProperty.cpp
+++ b/Source/core/svg/properties/SVGAnimatedProperty.cpp
@@ -56,8 +56,13 @@
         }
     }
 
-    for (Vector<SVGAnimatedPropertyDescription>::const_iterator it = keysToRemove.begin(); it != keysToRemove.end(); ++it)
+    for (Vector<SVGAnimatedPropertyDescription>::const_iterator it = keysToRemove.begin(); it != keysToRemove.end(); ++it) {
+        // http://crbug.com/333156 :
+        // There are cases where detachAnimatedPropertiesForElement is called recursively from ~SVGAnimatedProperty.
+        // This below protect makes this function safe by deferring the recursive call until we finish touching the HashMap.
+        RefPtr<SVGAnimatedProperty> protect = cache->get(*it);
         cache->remove(*it);
+    }
 }
 
 void SVGAnimatedProperty::commitChange()
diff --git a/Source/core/svg/properties/SVGAnimatedPropertyMacros.h b/Source/core/svg/properties/SVGAnimatedPropertyMacros.h
index 74e377f..b6658a8 100644
--- a/Source/core/svg/properties/SVGAnimatedPropertyMacros.h
+++ b/Source/core/svg/properties/SVGAnimatedPropertyMacros.h
@@ -103,6 +103,14 @@
                          &OwnerType::lookupOrCreate##UpperProperty##Wrapper)); \
     return &s_propertyInfo; \
 } \
+bool OwnerType::LowerProperty##Specified() const \
+{ \
+    if (TearOffType* wrapper = SVGAnimatedProperty::lookupWrapper<UseOwnerType, TearOffType>(this, LowerProperty##PropertyInfo())) { \
+        if (wrapper->isAnimating()) \
+            return true; \
+    } \
+    return hasAttribute(SVGDOMAttributeIdentifier); \
+} \
 PropertyType& OwnerType::LowerProperty##CurrentValue() const \
 { \
     if (TearOffType* wrapper = SVGAnimatedProperty::lookupWrapper<UseOwnerType, TearOffType>(this, LowerProperty##PropertyInfo())) { \
@@ -161,6 +169,7 @@
 #define DECLARE_ANIMATED_PROPERTY(TearOffType, PropertyType, UpperProperty, LowerProperty) \
 public: \
     static const SVGPropertyInfo* LowerProperty##PropertyInfo(); \
+    bool LowerProperty##Specified() const; \
     PropertyType& LowerProperty##CurrentValue() const; \
     PropertyType& LowerProperty##BaseValue() const; \
     void set##UpperProperty##BaseValue(const PropertyType& type); \
diff --git a/Source/core/svg/properties/SVGAnimatedPropertyTearOff.h b/Source/core/svg/properties/SVGAnimatedPropertyTearOff.h
index c425b3b..2216274 100644
--- a/Source/core/svg/properties/SVGAnimatedPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGAnimatedPropertyTearOff.h
@@ -27,7 +27,7 @@
 namespace WebCore {
 
 template<typename PropertyType>
-class SVGAnimatedPropertyTearOff : public SVGAnimatedProperty, public ScriptWrappable {
+class SVGAnimatedPropertyTearOff FINAL : public SVGAnimatedProperty, public ScriptWrappable {
 public:
     typedef SVGPropertyTearOff<PropertyType> PropertyTearOff;
     typedef PropertyType ContentType;
diff --git a/Source/core/svg/properties/SVGAnimatedTransformListPropertyTearOff.h b/Source/core/svg/properties/SVGAnimatedTransformListPropertyTearOff.h
index 0bc26c4..daa7e6e 100644
--- a/Source/core/svg/properties/SVGAnimatedTransformListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGAnimatedTransformListPropertyTearOff.h
@@ -28,14 +28,14 @@
 
 class SVGAnimatedTransformListPropertyTearOff : public SVGAnimatedListPropertyTearOff<SVGTransformList> {
 public:
-    virtual SVGListPropertyTearOff<SVGTransformList>* baseVal()
+    virtual SVGListPropertyTearOff<SVGTransformList>* baseVal() OVERRIDE
     {
         if (!m_baseVal)
             m_baseVal = SVGTransformListPropertyTearOff::create(this, BaseValRole, m_values, m_wrappers);
         return static_cast<SVGListPropertyTearOff<SVGTransformList>*>(m_baseVal.get());
     }
 
-    virtual SVGListPropertyTearOff<SVGTransformList>* animVal()
+    virtual SVGListPropertyTearOff<SVGTransformList>* animVal() OVERRIDE
     {
         if (!m_animVal)
             m_animVal = SVGTransformListPropertyTearOff::create(this, AnimValRole, m_values, m_wrappers);
diff --git a/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp b/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp
index cabeb22..a483d41 100644
--- a/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp
+++ b/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp
@@ -118,13 +118,13 @@
 {
     ASSERT(attributeName != anyQName());
     AttributeToPropertiesMap::AddResult addResult = m_map.add(attributeName, PassOwnPtr<PropertiesVector>());
-    PropertiesVector* vector = addResult.iterator->value.get();
+    PropertiesVector* vector = addResult.storedValue->value.get();
     if (addResult.isNewEntry) {
         ASSERT(!vector);
-        vector = (addResult.iterator->value = adoptPtr(new PropertiesVector)).get();
+        vector = (addResult.storedValue->value = adoptPtr(new PropertiesVector)).get();
     }
     ASSERT(vector);
-    ASSERT(addResult.iterator->value.get() == vector);
+    ASSERT(addResult.storedValue->value.get() == vector);
     return vector;
 }
 
diff --git a/Source/core/svg/properties/SVGListProperty.h b/Source/core/svg/properties/SVGListProperty.h
index 27e8d66..49d1217 100644
--- a/Source/core/svg/properties/SVGListProperty.h
+++ b/Source/core/svg/properties/SVGListProperty.h
@@ -20,6 +20,7 @@
 #ifndef SVGListProperty_h
 #define SVGListProperty_h
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/svg/properties/SVGPropertyTearOff.h"
@@ -52,7 +53,7 @@
     bool canAlterList(ExceptionState& exceptionState) const
     {
         if (m_role == AnimValRole) {
-            exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+            exceptionState.throwDOMException(NoModificationAllowedError, ExceptionMessages::readOnly("the property is an animation value"));
             return false;
         }
 
@@ -147,7 +148,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            exceptionState.throwUninformativeAndGenericTypeError();
+            exceptionState.throwTypeError("The PassListItemType provided is invalid.");
             return 0;
         }
 
@@ -172,7 +173,7 @@
     bool canGetItem(unsigned index, ExceptionState& exceptionState)
     {
         if (index >= m_values->size()) {
-            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("index", index, m_values->size()));
             return false;
         }
 
@@ -241,7 +242,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            exceptionState.throwUninformativeAndGenericTypeError();
+            exceptionState.throwTypeError("The PassListItemType provided is invalid.");
             return 0;
         }
 
@@ -274,7 +275,7 @@
             return false;
 
         if (index >= m_values->size()) {
-            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("index", index, m_values->size()));
             return false;
         }
 
@@ -295,7 +296,7 @@
 
         if (m_values->isEmpty()) {
             // 'newItem' already lived in our list, we removed it, and now we're empty, which means there's nothing to replace.
-            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwDOMException(IndexSizeError, "The new item lived in this list, and has been removed.");
             return ListItemType();
         }
 
@@ -314,7 +315,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            exceptionState.throwUninformativeAndGenericTypeError();
+            exceptionState.throwTypeError("The PassListItemType provided is invalid.");
             return 0;
         }
 
@@ -329,7 +330,7 @@
         if (m_values->isEmpty()) {
             ASSERT(m_wrappers->isEmpty());
             // 'passNewItem' already lived in our list, we removed it, and now we're empty, which means there's nothing to replace.
-            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwDOMException(IndexSizeError, "The new item lived in this list, and has been removed.");
             return 0;
         }
 
@@ -353,7 +354,7 @@
             return false;
 
         if (index >= m_values->size()) {
-            exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
+            exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("index", index, m_values->size()));
             return false;
         }
 
@@ -417,7 +418,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            exceptionState.throwUninformativeAndGenericTypeError();
+            exceptionState.throwTypeError("The PassListItemType provided is invalid.");
             return 0;
         }
 
diff --git a/Source/core/svg/properties/SVGListPropertyTearOff.h b/Source/core/svg/properties/SVGListPropertyTearOff.h
index 7f14109..48af096 100644
--- a/Source/core/svg/properties/SVGListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGListPropertyTearOff.h
@@ -137,15 +137,6 @@
         ASSERT(m_animatedProperty);
     }
 
-    virtual bool isReadOnly() const
-    {
-        if (m_role == AnimValRole)
-            return true;
-        if (m_animatedProperty && m_animatedProperty->isReadOnly())
-            return true;
-        return false;
-    }
-
     virtual void commitChange()
     {
         ASSERT(m_values);
diff --git a/Source/core/svg/properties/SVGMatrixTearOff.h b/Source/core/svg/properties/SVGMatrixTearOff.h
index 80ac600..42675fd 100644
--- a/Source/core/svg/properties/SVGMatrixTearOff.h
+++ b/Source/core/svg/properties/SVGMatrixTearOff.h
@@ -25,7 +25,7 @@
 
 namespace WebCore {
 
-class SVGMatrixTearOff : public SVGPropertyTearOff<SVGMatrix> {
+class SVGMatrixTearOff FINAL : public SVGPropertyTearOff<SVGMatrix> {
 public:
     // Used for child types (baseVal/animVal) of a SVGAnimated* property (for example: SVGAnimatedLength::baseVal()).
     // Also used for list tear offs (for example: text.x.baseVal.getItem(0)).
@@ -52,7 +52,7 @@
         return result.release();
     }
 
-    virtual void commitChange()
+    virtual void commitChange() OVERRIDE
     {
         if (m_parent) {
             // This is a tear-off from a SVGPropertyTearOff<SVGTransform>.
@@ -64,6 +64,15 @@
         }
     }
 
+    // SVGMatrixTearOff can be a child tear-off of a SVGTransform tear-off,
+    // which means that |m_value| may be pointing inside |m_value| of the other tear-off.
+    // This method is called from the parent SVGTransform tear-off when |m_parent->m_value| is updated,
+    // so that |this->m_value| would point to valid location.
+    virtual void setValueForMatrixIfNeeded(SVGTransform* transform) OVERRIDE
+    {
+        setValue(transform->svgMatrix());
+    }
+
     SVGPropertyTearOff<SVGTransform>* parent() { return m_parent; }
 
 private:
diff --git a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
index 48cb03a..58c0720 100644
--- a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
+++ b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -62,7 +62,7 @@
 {
     // Not specified, but FF/Opera do it this way, and it's just sane.
     if (!passNewItem) {
-        exceptionState.throwUninformativeAndGenericTypeError();
+        exceptionState.throwTypeError("The PassListItemType provided is invalid.");
         return 0;
     }
 
diff --git a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
index 4a755f7..abec416 100644
--- a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
@@ -28,7 +28,7 @@
 
 class SVGPathElement;
 
-class SVGPathSegListPropertyTearOff : public SVGListProperty<SVGPathSegList> {
+class SVGPathSegListPropertyTearOff FINAL : public SVGListProperty<SVGPathSegList> {
 public:
     typedef SVGListProperty<SVGPathSegList> Base;
     typedef SVGAnimatedListPropertyTearOff<SVGPathSegList> AnimatedListPropertyTearOff;
@@ -75,7 +75,7 @@
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            exceptionState.throwUninformativeAndGenericTypeError();
+            exceptionState.throwTypeError("The PassListItemType provided is invalid.");
             return 0;
         }
 
@@ -90,7 +90,7 @@
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            exceptionState.throwUninformativeAndGenericTypeError();
+            exceptionState.throwTypeError("The PassListItemType provided is invalid.");
             return 0;
         }
 
@@ -106,7 +106,7 @@
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            exceptionState.throwUninformativeAndGenericTypeError();
+            exceptionState.throwTypeError("The PassListItemType provided is invalid.");
             return 0;
         }
 
@@ -126,29 +126,20 @@
 
     using Base::m_role;
 
-    virtual bool isReadOnly() const
-    {
-        if (m_role == AnimValRole)
-            return true;
-        if (m_animatedProperty && m_animatedProperty->isReadOnly())
-            return true;
-        return false;
-    }
-
-    virtual void commitChange()
+    virtual void commitChange() OVERRIDE
     {
         ASSERT(m_values);
         m_values->commitChange(m_animatedProperty->contextElement(), ListModificationUnknown);
     }
 
-    virtual void commitChange(ListModification listModification)
+    virtual void commitChange(ListModification listModification) OVERRIDE
     {
         ASSERT(m_values);
         m_values->commitChange(m_animatedProperty->contextElement(), listModification);
     }
 
     virtual bool processIncomingListItemValue(const ListItemType& newItem, unsigned* indexToModify) OVERRIDE;
-    virtual bool processIncomingListItemWrapper(RefPtr<ListItemTearOff>&, unsigned*)
+    virtual bool processIncomingListItemWrapper(RefPtr<ListItemTearOff>&, unsigned*) OVERRIDE
     {
         ASSERT_NOT_REACHED();
         return true;
diff --git a/Source/core/svg/properties/SVGProperty.h b/Source/core/svg/properties/SVGProperty.h
index 3ccc289..ebb454c 100644
--- a/Source/core/svg/properties/SVGProperty.h
+++ b/Source/core/svg/properties/SVGProperty.h
@@ -34,7 +34,6 @@
 public:
     virtual ~SVGProperty() { }
 
-    virtual bool isReadOnly() const = 0;
     virtual void commitChange() = 0;
 };
 
diff --git a/Source/core/svg/properties/SVGPropertyInfo.h b/Source/core/svg/properties/SVGPropertyInfo.h
index f77be4f..598bc39 100644
--- a/Source/core/svg/properties/SVGPropertyInfo.h
+++ b/Source/core/svg/properties/SVGPropertyInfo.h
@@ -46,10 +46,12 @@
     AnimatedNumberList,
     AnimatedNumberOptionalNumber,
     AnimatedPath,
+    AnimatedPoint,
     AnimatedPoints,
     AnimatedPreserveAspectRatio,
     AnimatedRect,
     AnimatedString,
+    AnimatedStringList,
     AnimatedTransformList,
     AnimatedUnknown
 };
diff --git a/Source/core/svg/properties/SVGPropertyTearOff.h b/Source/core/svg/properties/SVGPropertyTearOff.h
index c9fe65b..8d5609a 100644
--- a/Source/core/svg/properties/SVGPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGPropertyTearOff.h
@@ -27,8 +27,12 @@
 
 namespace WebCore {
 
+class SVGTransform;
+
 class SVGPropertyTearOffBase : public SVGProperty {
 public:
+    virtual void setValueForMatrixIfNeeded(SVGTransform*) { }
+
     virtual void detachWrapper() = 0;
 };
 
@@ -60,6 +64,9 @@
             detachChildren();
             delete m_value;
         }
+
+        updateChildrenTearOffs(&value);
+
         m_valueIsCopy = false;
         m_value = &value;
     }
@@ -111,7 +118,7 @@
         m_animatedProperty->commitChange();
     }
 
-    virtual bool isReadOnly() const
+    bool isReadOnly() const
     {
         if (m_role == AnimValRole)
             return true;
@@ -157,6 +164,21 @@
         m_childTearOffs.clear();
     }
 
+    // Update m_value of children tear-offs.
+    // Currently only SVGTransform has child tear-offs.
+    void updateChildrenTearOffs(SVGTransform* transform)
+    {
+        for (Vector<WeakPtr<SVGPropertyTearOffBase> >::iterator iter = m_childTearOffs.begin(); iter != m_childTearOffs.end(); iter++) {
+            if (iter->get())
+                iter->get()->setValueForMatrixIfNeeded(transform);
+        }
+    }
+
+    void updateChildrenTearOffs(void*)
+    {
+        // Tear-offs for other types do not have child tear-offs.
+    }
+
     SVGElement* m_contextElement;
     SVGAnimatedProperty* m_animatedProperty;
     SVGPropertyRole m_role;
diff --git a/Source/core/svg/properties/SVGStaticListPropertyTearOff.h b/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
index 596a551..aee312d 100644
--- a/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
@@ -89,11 +89,6 @@
         m_contextElement->setContextElement();
     }
 
-    virtual bool isReadOnly() const
-    {
-        return m_role == AnimValRole;
-    }
-
     virtual void commitChange()
     {
         ASSERT(m_values);
diff --git a/Source/core/svg/properties/SVGStaticPropertyTearOff.h b/Source/core/svg/properties/SVGStaticPropertyTearOff.h
index 93d1cc5..bc6bddd 100644
--- a/Source/core/svg/properties/SVGStaticPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGStaticPropertyTearOff.h
@@ -30,7 +30,7 @@
 #pragma pack(push, 16)
 #endif
 template<typename ContextElement, typename PropertyType>
-class SVGStaticPropertyTearOff : public SVGPropertyTearOff<PropertyType> {
+class SVGStaticPropertyTearOff FINAL : public SVGPropertyTearOff<PropertyType> {
 public:
     typedef SVGStaticPropertyTearOff<ContextElement, PropertyType> Self;
     typedef void (ContextElement::*UpdateMethod)();
@@ -43,7 +43,7 @@
         return adoptRef(new Self(contextElement, value, update));
     }
 
-    virtual void commitChange() { (m_contextElement.get()->*m_update)(); }
+    virtual void commitChange() OVERRIDE { (m_contextElement.get()->*m_update)(); }
 
 private:
     SVGStaticPropertyTearOff(ContextElement* contextElement, PropertyType& value, UpdateMethod update)
diff --git a/Source/core/svg/properties/SVGTransformListPropertyTearOff.h b/Source/core/svg/properties/SVGTransformListPropertyTearOff.h
index 2ec007f..3b7d6da 100644
--- a/Source/core/svg/properties/SVGTransformListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGTransformListPropertyTearOff.h
@@ -39,13 +39,9 @@
         return adoptRef(new SVGTransformListPropertyTearOff(animatedProperty, role, values, wrappers));
     }
 
-    PassRefPtr<SVGPropertyTearOff<SVGTransform> > createSVGTransformFromMatrix(SVGPropertyTearOff<SVGMatrix>* matrix, ExceptionState& exceptionState)
+    PassRefPtr<SVGPropertyTearOff<SVGTransform> > createSVGTransformFromMatrix(SVGPropertyTearOff<SVGMatrix>* matrix)
     {
         ASSERT(m_values);
-        if (!matrix) {
-            exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
-            return 0;
-        }
         return SVGPropertyTearOff<SVGTransform>::create(m_values->createSVGTransformFromMatrix(matrix->propertyReference()));
     }
 
diff --git a/Source/core/testing/DummyPageHolder.cpp b/Source/core/testing/DummyPageHolder.cpp
index e409550..424e07d 100644
--- a/Source/core/testing/DummyPageHolder.cpp
+++ b/Source/core/testing/DummyPageHolder.cpp
@@ -54,7 +54,7 @@
 
     m_page = adoptPtr(new Page(m_pageClients));
 
-    m_frame = Frame::create(FrameInit::create(0, m_page.get(), &m_frameLoaderClient));
+    m_frame = Frame::create(FrameInit::create(0, &m_page->frameHost(), &m_frameLoaderClient));
     m_frame->setView(FrameView::create(m_frame.get(), initialViewSize));
     m_frame->init();
 }
diff --git a/Source/core/testing/GCObservation.idl b/Source/core/testing/GCObservation.idl
index 6c2d8e8..aaed5c2 100644
--- a/Source/core/testing/GCObservation.idl
+++ b/Source/core/testing/GCObservation.idl
@@ -28,7 +28,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-interface GCObservation {
+[
+    NoInterfaceObject,  // testing interfaces do not appear on global objects
+] interface GCObservation {
     // Technically, this is true if the object was "near death"; the
     // object may have been kept alive through a weak handle. Having
     // been collected is the common case, though.
diff --git a/Source/core/testing/InspectorFrontendClientLocal.cpp b/Source/core/testing/InspectorFrontendClientLocal.cpp
index d683e55..f61a422 100644
--- a/Source/core/testing/InspectorFrontendClientLocal.cpp
+++ b/Source/core/testing/InspectorFrontendClientLocal.cpp
@@ -36,7 +36,7 @@
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorFrontendHost.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "platform/Timer.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebThread.h"
diff --git a/Source/core/testing/InspectorFrontendClientLocal.h b/Source/core/testing/InspectorFrontendClientLocal.h
index a97b8d8..4fa3580 100644
--- a/Source/core/testing/InspectorFrontendClientLocal.h
+++ b/Source/core/testing/InspectorFrontendClientLocal.h
@@ -44,21 +44,21 @@
 class InspectorFrontendHost;
 class Page;
 
-class InspectorFrontendClientLocal : public InspectorFrontendClient {
+class InspectorFrontendClientLocal FINAL : public InspectorFrontendClient {
     WTF_MAKE_NONCOPYABLE(InspectorFrontendClientLocal); WTF_MAKE_FAST_ALLOCATED;
 public:
     InspectorFrontendClientLocal(InspectorController&, Page*);
     virtual ~InspectorFrontendClientLocal();
 
-    virtual void windowObjectCleared();
+    virtual void windowObjectCleared() OVERRIDE;
 
     virtual void inspectedURLChanged(const String&) OVERRIDE { }
 
-    virtual void sendMessageToBackend(const String& message);
+    virtual void sendMessageToBackend(const String& message) OVERRIDE;
 
     virtual void sendMessageToEmbedder(const String&) OVERRIDE { }
 
-    virtual bool isUnderTest() { return true; }
+    virtual bool isUnderTest() OVERRIDE { return true; }
 
 private:
     Page* m_frontendPage;
diff --git a/Source/core/testing/InternalProfilers.idl b/Source/core/testing/InternalProfilers.idl
index 7030e9e..5ad4863 100644
--- a/Source/core/testing/InternalProfilers.idl
+++ b/Source/core/testing/InternalProfilers.idl
@@ -29,7 +29,7 @@
  */
 
 [
-    NoInterfaceObject
+    NoInterfaceObject,  // testing interfaces do not appear on global objects
 ] interface InternalProfilers {
     void startHeapProfiling(DOMString prefix);
     void stopHeapProfiling();
diff --git a/Source/core/testing/InternalSettings.cpp b/Source/core/testing/InternalSettings.cpp
index ff273c5..12b3953 100644
--- a/Source/core/testing/InternalSettings.cpp
+++ b/Source/core/testing/InternalSettings.cpp
@@ -30,27 +30,28 @@
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/frame/Settings.h"
+#include "core/inspector/InspectorController.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
 #include "platform/ColorChooser.h"
 #include "platform/Supplementable.h"
 #include "platform/text/LocaleToScriptMapping.h"
 
 #define InternalSettingsGuardForSettingsReturn(returnValue) \
     if (!settings()) { \
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
+        exceptionState.throwDOMException(InvalidAccessError, "The settings object cannot be obtained."); \
         return returnValue; \
     }
 
 #define InternalSettingsGuardForSettings()  \
     if (!settings()) { \
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
+        exceptionState.throwDOMException(InvalidAccessError, "The settings object cannot be obtained."); \
         return; \
     }
 
 #define InternalSettingsGuardForPage() \
     if (!page()) { \
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
+        exceptionState.throwDOMException(InvalidAccessError, "The page object cannot be obtained."); \
         return; \
     }
 
@@ -61,6 +62,7 @@
     , m_originalAuthorShadowDOMForAnyElementEnabled(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
     , m_originalExperimentalWebSocketEnabled(settings->experimentalWebSocketEnabled())
     , m_originalStyleScoped(RuntimeEnabledFeatures::styleScopedEnabled())
+    , m_originalCSP(RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled())
     , m_originalOverlayScrollbarsEnabled(RuntimeEnabledFeatures::overlayScrollbarsEnabled())
     , m_originalEditingBehavior(settings->editingBehaviorType())
     , m_originalTextAutosizingEnabled(settings->textAutosizingEnabled())
@@ -69,13 +71,13 @@
     , m_originalMediaTypeOverride(settings->mediaTypeOverride())
     , m_originalMockScrollbarsEnabled(settings->mockScrollbarsEnabled())
     , m_langAttributeAwareFormControlUIEnabled(RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
-    , m_imagesEnabled(settings->areImagesEnabled())
+    , m_imagesEnabled(settings->imagesEnabled())
     , m_shouldDisplaySubtitles(settings->shouldDisplaySubtitles())
     , m_shouldDisplayCaptions(settings->shouldDisplayCaptions())
     , m_shouldDisplayTextDescriptions(settings->shouldDisplayTextDescriptions())
     , m_defaultVideoPosterURL(settings->defaultVideoPosterURL())
-    , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->isCompositorDrivenAcceleratedScrollingEnabled())
-    , m_originalLayerSquashingEnabled(settings->isLayerSquashingEnabled())
+    , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->compositorDrivenAcceleratedScrollingEnabled())
+    , m_originalLayerSquashingEnabled(settings->layerSquashingEnabled())
     , m_originalPasswordGenerationDecorationEnabled(settings->passwordGenerationDecorationEnabled())
 {
 }
@@ -86,6 +88,7 @@
     RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(m_originalAuthorShadowDOMForAnyElementEnabled);
     settings->setExperimentalWebSocketEnabled(m_originalExperimentalWebSocketEnabled);
     RuntimeEnabledFeatures::setStyleScopedEnabled(m_originalStyleScoped);
+    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(m_originalCSP);
     RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(m_originalOverlayScrollbarsEnabled);
     settings->setEditingBehaviorType(m_originalEditingBehavior);
     settings->setTextAutosizingEnabled(m_originalTextAutosizingEnabled);
@@ -151,6 +154,7 @@
 
     m_backup.restoreTo(settings());
     m_backup = Backup(settings());
+    m_backup.m_originalTextAutosizingEnabled = settings()->textAutosizingEnabled();
 
     InternalSettingsGenerated::resetToConsistentState();
 }
@@ -183,6 +187,11 @@
     RuntimeEnabledFeatures::setStyleScopedEnabled(enabled);
 }
 
+void InternalSettings::setExperimentalContentSecurityPolicyFeaturesEnabled(bool enabled)
+{
+    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(enabled);
+}
+
 void InternalSettings::setOverlayScrollbarsEnabled(bool enabled)
 {
     RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);
@@ -216,80 +225,81 @@
     settings()->setLayerSquashingEnabled(enabled);
 }
 
-void InternalSettings::setStandardFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
+void InternalSettings::setStandardFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     UScriptCode code = scriptNameToCode(script);
     if (code == USCRIPT_INVALID_CODE)
         return;
     settings()->genericFontFamilySettings().setStandard(family, code);
-    m_page->setNeedsRecalcStyleInAllFrames();
+    settings()->notifyGenericFontFamilyChange();
 }
 
-void InternalSettings::setSerifFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
+void InternalSettings::setSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     UScriptCode code = scriptNameToCode(script);
     if (code == USCRIPT_INVALID_CODE)
         return;
     settings()->genericFontFamilySettings().setSerif(family, code);
-    m_page->setNeedsRecalcStyleInAllFrames();
+    settings()->notifyGenericFontFamilyChange();
 }
 
-void InternalSettings::setSansSerifFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
+void InternalSettings::setSansSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     UScriptCode code = scriptNameToCode(script);
     if (code == USCRIPT_INVALID_CODE)
         return;
     settings()->genericFontFamilySettings().setSansSerif(family, code);
-    m_page->setNeedsRecalcStyleInAllFrames();
+    settings()->notifyGenericFontFamilyChange();
 }
 
-void InternalSettings::setFixedFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
+void InternalSettings::setFixedFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     UScriptCode code = scriptNameToCode(script);
     if (code == USCRIPT_INVALID_CODE)
         return;
     settings()->genericFontFamilySettings().setFixed(family, code);
-    m_page->setNeedsRecalcStyleInAllFrames();
+    settings()->notifyGenericFontFamilyChange();
 }
 
-void InternalSettings::setCursiveFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
+void InternalSettings::setCursiveFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     UScriptCode code = scriptNameToCode(script);
     if (code == USCRIPT_INVALID_CODE)
         return;
     settings()->genericFontFamilySettings().setCursive(family, code);
-    m_page->setNeedsRecalcStyleInAllFrames();
+    settings()->notifyGenericFontFamilyChange();
 }
 
-void InternalSettings::setFantasyFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
+void InternalSettings::setFantasyFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     UScriptCode code = scriptNameToCode(script);
     if (code == USCRIPT_INVALID_CODE)
         return;
     settings()->genericFontFamilySettings().setFantasy(family, code);
-    m_page->setNeedsRecalcStyleInAllFrames();
+    settings()->notifyGenericFontFamilyChange();
 }
 
-void InternalSettings::setPictographFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
+void InternalSettings::setPictographFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     UScriptCode code = scriptNameToCode(script);
     if (code == USCRIPT_INVALID_CODE)
         return;
     settings()->genericFontFamilySettings().setPictograph(family, code);
-    m_page->setNeedsRecalcStyleInAllFrames();
+    settings()->notifyGenericFontFamilyChange();
 }
 
 void InternalSettings::setTextAutosizingEnabled(bool enabled, ExceptionState& exceptionState)
 {
     InternalSettingsGuardForSettings();
     settings()->setTextAutosizingEnabled(enabled);
+    m_page->inspectorController().setTextAutosizingEnabled(enabled);
 }
 
 void InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState& exceptionState)
@@ -327,7 +337,7 @@
     else if (equalIgnoringCase(editingBehavior, "android"))
         settings()->setEditingBehaviorType(EditingAndroidBehavior);
     else
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The editing behavior type provided ('" + editingBehavior + "') is invalid.");
 }
 
 void InternalSettings::setLangAttributeAwareFormControlUIEnabled(bool enabled)
diff --git a/Source/core/testing/InternalSettings.h b/Source/core/testing/InternalSettings.h
index cc064ba..587d44d 100644
--- a/Source/core/testing/InternalSettings.h
+++ b/Source/core/testing/InternalSettings.h
@@ -42,7 +42,7 @@
 class Page;
 class Settings;
 
-class InternalSettings : public InternalSettingsGenerated {
+class InternalSettings FINAL : public InternalSettingsGenerated {
 public:
     class Backup {
     public:
@@ -53,6 +53,7 @@
         bool m_originalAuthorShadowDOMForAnyElementEnabled;
         bool m_originalExperimentalWebSocketEnabled;
         bool m_originalStyleScoped;
+        bool m_originalCSP;
         bool m_originalOverlayScrollbarsEnabled;
         EditingBehaviorType m_originalEditingBehavior;
         bool m_originalTextAutosizingEnabled;
@@ -81,13 +82,13 @@
     virtual ~InternalSettings();
     void resetToConsistentState();
 
-    void setStandardFontFamily(const String& family, const String& script, ExceptionState&);
-    void setSerifFontFamily(const String& family, const String& script, ExceptionState&);
-    void setSansSerifFontFamily(const String& family, const String& script, ExceptionState&);
-    void setFixedFontFamily(const String& family, const String& script, ExceptionState&);
-    void setCursiveFontFamily(const String& family, const String& script, ExceptionState&);
-    void setFantasyFontFamily(const String& family, const String& script, ExceptionState&);
-    void setPictographFontFamily(const String& family, const String& script, ExceptionState&);
+    void setStandardFontFamily(const AtomicString& family, const String& script, ExceptionState&);
+    void setSerifFontFamily(const AtomicString& family, const String& script, ExceptionState&);
+    void setSansSerifFontFamily(const AtomicString& family, const String& script, ExceptionState&);
+    void setFixedFontFamily(const AtomicString& family, const String& script, ExceptionState&);
+    void setCursiveFontFamily(const AtomicString& family, const String& script, ExceptionState&);
+    void setFantasyFontFamily(const AtomicString& family, const String& script, ExceptionState&);
+    void setPictographFontFamily(const AtomicString& family, const String& script, ExceptionState&);
 
     void setDefaultVideoPosterURL(const String& url, ExceptionState&);
     void setEditingBehavior(const String&, ExceptionState&);
@@ -118,6 +119,7 @@
     void setLangAttributeAwareFormControlUIEnabled(bool);
     void setOverlayScrollbarsEnabled(bool);
     void setStyleScopedEnabled(bool);
+    void setExperimentalContentSecurityPolicyFeaturesEnabled(bool);
 
 private:
     explicit InternalSettings(Page*);
diff --git a/Source/core/testing/InternalSettings.idl b/Source/core/testing/InternalSettings.idl
index d4f5984..69686ce 100644
--- a/Source/core/testing/InternalSettings.idl
+++ b/Source/core/testing/InternalSettings.idl
@@ -24,6 +24,7 @@
  */
 
 [
+    NoInterfaceObject,  // testing interfaces do not appear on global objects
 ] interface InternalSettings : InternalSettingsGenerated {
     // All methods which access Page::settings() can raise an exception
     // when the page cannot be accessed. (Such as during page tear-down.)
@@ -63,4 +64,5 @@
     void setLangAttributeAwareFormControlUIEnabled(boolean enabled);
     void setOverlayScrollbarsEnabled(boolean enabled);
     void setStyleScopedEnabled(boolean enabled);
+    void setExperimentalContentSecurityPolicyFeaturesEnabled(boolean enabled);
 };
diff --git a/Source/core/testing/Internals.cpp b/Source/core/testing/Internals.cpp
index 09f98dc..6061954 100644
--- a/Source/core/testing/Internals.cpp
+++ b/Source/core/testing/Internals.cpp
@@ -40,6 +40,8 @@
 #include "RuntimeEnabledFeatures.h"
 #include "TypeConversions.h"
 #include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/ScriptFunction.h"
+#include "bindings/v8/ScriptPromise.h"
 #include "bindings/v8/SerializedScriptValue.h"
 #include "bindings/v8/V8ThrowException.h"
 #include "core/animation/DocumentTimeline.h"
@@ -56,6 +58,7 @@
 #include "core/dom/Element.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/FullscreenElementStack.h"
+#include "core/dom/NodeRenderStyle.h"
 #include "core/dom/PseudoElement.h"
 #include "core/dom/Range.h"
 #include "core/dom/StaticNodeList.h"
@@ -75,7 +78,6 @@
 #include "core/fetch/ResourceFetcher.h"
 #include "core/frame/DOMPoint.h"
 #include "core/frame/Frame.h"
-#include "core/history/HistoryItem.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLMediaElement.h"
@@ -92,6 +94,7 @@
 #include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/FrameLoader.h"
+#include "core/loader/HistoryItem.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/frame/DOMWindow.h"
@@ -100,8 +103,7 @@
 #include "core/page/Page.h"
 #include "core/page/PagePopupController.h"
 #include "core/page/PrintContext.h"
-#include "core/page/Settings.h"
-#include "core/frame/animation/AnimationController.h"
+#include "core/frame/Settings.h"
 #include "core/rendering/CompositedLayerMapping.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
@@ -120,10 +122,13 @@
 #include "platform/graphics/GraphicsLayer.h"
 #include "platform/graphics/filters/FilterOperation.h"
 #include "platform/graphics/filters/FilterOperations.h"
-#include "platform/graphics/gpu/SharedGraphicsContext3D.h"
 #include "platform/weborigin/SchemeRegistry.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebGraphicsContext3D.h"
+#include "public/platform/WebGraphicsContext3DProvider.h"
 #include "public/platform/WebLayer.h"
 #include "wtf/InstanceCounter.h"
+#include "wtf/PassOwnPtr.h"
 #include "wtf/dtoa.h"
 #include "wtf/text/StringBuffer.h"
 
@@ -194,9 +199,8 @@
     page->setDeviceScaleFactor(1);
     page->setIsCursorVisible(true);
     page->setPageScaleFactor(1, IntPoint(0, 0));
-    page->setPagination(Pagination());
     TextRun::setAllowsRoundingHacks(false);
-    WebCore::overrideUserPreferredLanguages(Vector<String>());
+    WebCore::overrideUserPreferredLanguages(Vector<AtomicString>());
     delete s_pagePopupDriver;
     s_pagePopupDriver = 0;
     page->chrome().client().resetPagePopupDriver();
@@ -214,7 +218,6 @@
 Internals::Internals(Document* document)
     : ContextLifecycleObserver(document)
     , m_runtimeFlags(InternalRuntimeFlags::create())
-    , m_scrollingCoordinator(document->page() ? document->page()->scrollingCoordinator() : 0)
 {
 }
 
@@ -282,7 +285,7 @@
 {
     Document* document = contextDocument();
     if (!document) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No context document is available.");
         return 0;
     }
 
@@ -291,6 +294,21 @@
     return document->styleEngine()->resolverAccessCount() - beforeCount;
 }
 
+unsigned Internals::needsLayoutCount(ExceptionState& exceptionState) const
+{
+    Frame* contextFrame = frame();
+    if (!contextFrame) {
+        exceptionState.throwDOMException(InvalidAccessError, "No context frame is available.");
+        return 0;
+    }
+
+    bool isPartial;
+    unsigned needsLayoutObjects;
+    unsigned totalObjects;
+    contextFrame->countObjectsNeedingLayout(needsLayoutObjects, totalObjects, isPartial);
+    return needsLayoutObjects;
+}
+
 bool Internals::isPreloaded(const String& url)
 {
     Document* document = contextDocument();
@@ -339,71 +357,69 @@
     return document->ensureStyleResolver().statsTotals()->report();
 }
 
-PassRefPtr<Element> Internals::createContentElement(ExceptionState& exceptionState)
+bool Internals::isSharingStyle(Element* element1, Element* element2, ExceptionState& exceptionState) const
 {
-    Document* document = contextDocument();
-    if (!document) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
-        return 0;
+    if (!element1 || !element2) {
+        exceptionState.throwDOMException(InvalidAccessError, String::format("The %s element provided is invalid.", element1 ? "second" : "first"));
+        return false;
     }
-
-    return HTMLContentElement::create(*document);
+    return element1->renderStyle() == element2->renderStyle();
 }
 
 bool Internals::isValidContentSelect(Element* insertionPoint, ExceptionState& exceptionState)
 {
     if (!insertionPoint || !insertionPoint->isInsertionPoint()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The insertion point provided is invalid.");
         return false;
     }
 
-    return isHTMLContentElement(insertionPoint) && toHTMLContentElement(insertionPoint)->isSelectValid();
+    return insertionPoint->hasTagName(contentTag) && toHTMLContentElement(insertionPoint)->isSelectValid();
 }
 
 Node* Internals::treeScopeRootNode(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
 
-    return node->treeScope().rootNode();
+    return &node->treeScope().rootNode();
 }
 
 Node* Internals::parentTreeScope(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
     const TreeScope* parentTreeScope = node->treeScope().parentTreeScope();
-    return parentTreeScope ? parentTreeScope->rootNode() : 0;
+    return parentTreeScope ? &parentTreeScope->rootNode() : 0;
 }
 
-bool Internals::hasSelectorForIdInShadow(Element* host, const String& idValue, ExceptionState& exceptionState)
+bool Internals::hasSelectorForIdInShadow(Element* host, const AtomicString& idValue, ExceptionState& exceptionState)
 {
     if (!host || !host->shadow()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The host element provided is invalid, or does not have a shadow.");
         return 0;
     }
 
     return host->shadow()->ensureSelectFeatureSet().hasSelectorForId(idValue);
 }
 
-bool Internals::hasSelectorForClassInShadow(Element* host, const String& className, ExceptionState& exceptionState)
+bool Internals::hasSelectorForClassInShadow(Element* host, const AtomicString& className, ExceptionState& exceptionState)
 {
     if (!host || !host->shadow()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The host element provided is invalid, or does not have a shadow.");
         return 0;
     }
 
     return host->shadow()->ensureSelectFeatureSet().hasSelectorForClass(className);
 }
 
-bool Internals::hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionState& exceptionState)
+bool Internals::hasSelectorForAttributeInShadow(Element* host, const AtomicString& attributeName, ExceptionState& exceptionState)
 {
     if (!host || !host->shadow()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The host element provided is invalid, or does not have a shadow.");
         return 0;
     }
 
@@ -413,7 +429,7 @@
 bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionState& exceptionState)
 {
     if (!host || !host->shadow()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The host element provided is invalid, or does not have a shadow.");
         return 0;
     }
 
@@ -440,7 +456,7 @@
 unsigned short Internals::compareTreeScopePosition(const Node* node1, const Node* node2, ExceptionState& exceptionState) const
 {
     if (!node1 || !node2) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, String::format("The %s node provided is invalid.", node1 ? "second" : "first"));
         return 0;
     }
     const TreeScope* treeScope1 = node1->isDocumentNode() ? static_cast<const TreeScope*>(toDocument(node1)) :
@@ -448,7 +464,7 @@
     const TreeScope* treeScope2 = node2->isDocumentNode() ? static_cast<const TreeScope*>(toDocument(node2)) :
         node2->isShadowRoot() ? static_cast<const TreeScope*>(toShadowRoot(node2)) : 0;
     if (!treeScope1 || !treeScope2) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, String::format("The %s node is neither a document node, nor a shadow root.", treeScope1 ? "second" : "first"));
         return 0;
     }
     return treeScope1->comparePosition(*treeScope2);
@@ -458,24 +474,21 @@
 {
     Frame* contextFrame = frame();
     Document* document = contextFrame->document();
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-        return document->timeline()->numberOfActiveAnimationsForTesting() + document->transitionTimeline()->numberOfActiveAnimationsForTesting();
-    return contextFrame->animation().numberOfActiveAnimations(document);
+    return document->timeline()->numberOfActiveAnimationsForTesting() + document->transitionTimeline()->numberOfActiveAnimationsForTesting();
 }
 
 void Internals::pauseAnimations(double pauseTime, ExceptionState& exceptionState)
 {
     if (pauseTime < 0) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The pauseTime provided is negative.");
         return;
     }
 
-    if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
-        frame()->document()->timeline()->pauseAnimationsForTesting(pauseTime);
-        frame()->document()->transitionTimeline()->pauseAnimationsForTesting(pauseTime);
-    } else {
-        frame()->animation().pauseAnimationsForTesting(pauseTime);
-    }
+    // https://code.google.com/p/chromium/issues/detail?id=343760
+    DisableCompositingQueryAsserts disabler;
+
+    frame()->document()->timeline()->pauseAnimationsForTesting(pauseTime);
+    frame()->document()->transitionTimeline()->pauseAnimationsForTesting(pauseTime);
 }
 
 bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionState& exceptionState) const
@@ -483,7 +496,7 @@
     if (root && root->isShadowRoot())
         return toShadowRoot(root)->containsShadowElements();
 
-    exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    exceptionState.throwDOMException(InvalidAccessError, "The root node provided is invalid.");
     return 0;
 }
 
@@ -492,14 +505,14 @@
     if (root && root->isShadowRoot())
         return toShadowRoot(root)->containsContentElements();
 
-    exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    exceptionState.throwDOMException(InvalidAccessError, "The root node provided is invalid.");
     return 0;
 }
 
 size_t Internals::countElementShadow(const Node* root, ExceptionState& exceptionState) const
 {
     if (!root || !root->isShadowRoot()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The root node provided is invalid.");
         return 0;
     }
     return toShadowRoot(root)->childShadowRootCount();
@@ -508,7 +521,7 @@
 Node* Internals::nextSiblingByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -519,7 +532,7 @@
 Node* Internals::firstChildByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -530,7 +543,7 @@
 Node* Internals::lastChildByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -541,7 +554,7 @@
 Node* Internals::nextNodeByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -552,7 +565,7 @@
 Node* Internals::previousNodeByWalker(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
     ComposedTreeWalker walker(node);
@@ -563,13 +576,13 @@
 String Internals::elementRenderTreeAsText(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return String();
     }
 
     String representation = externalRepresentation(element);
     if (representation.isEmpty()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided has no external representation.");
         return String();
     }
 
@@ -581,14 +594,14 @@
     if (scope && (scope->isElementNode() || scope->isShadowRoot()))
         return scope->numberOfScopedHTMLStyleChildren();
 
-    exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    exceptionState.throwDOMException(InvalidAccessError, "The scope provided is invalid.");
     return 0;
 }
 
 PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node, ExceptionState& exceptionState) const
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
 
@@ -596,19 +609,6 @@
     return CSSComputedStyleDeclaration::create(node, allowVisitedStyle);
 }
 
-ShadowRoot* Internals::ensureShadowRoot(Element* host, ExceptionState& exceptionState)
-{
-    if (!host) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
-        return 0;
-    }
-
-    if (ElementShadow* shadow = host->shadow())
-        return shadow->youngestShadowRoot();
-
-    return host->createShadowRoot(exceptionState).get();
-}
-
 ShadowRoot* Internals::shadowRoot(Element* host, ExceptionState& exceptionState)
 {
     // FIXME: Internals::shadowRoot() in tests should be converted to youngestShadowRoot() or oldestShadowRoot().
@@ -619,7 +619,7 @@
 ShadowRoot* Internals::youngestShadowRoot(Element* host, ExceptionState& exceptionState)
 {
     if (!host) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The host element provided is invalid.");
         return 0;
     }
 
@@ -631,7 +631,7 @@
 ShadowRoot* Internals::oldestShadowRoot(Element* host, ExceptionState& exceptionState)
 {
     if (!host) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The host element provided is invalid.");
         return 0;
     }
 
@@ -643,27 +643,17 @@
 ShadowRoot* Internals::youngerShadowRoot(Node* shadow, ExceptionState& exceptionState)
 {
     if (!shadow || !shadow->isShadowRoot()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is not a valid shadow root.");
         return 0;
     }
 
     return toShadowRoot(shadow)->youngerShadowRoot();
 }
 
-ShadowRoot* Internals::olderShadowRoot(Node* shadow, ExceptionState& exceptionState)
-{
-    if (!shadow || !shadow->isShadowRoot()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
-        return 0;
-    }
-
-    return toShadowRoot(shadow)->olderShadowRoot();
-}
-
 String Internals::shadowRootType(const Node* root, ExceptionState& exceptionState) const
 {
     if (!root || !root->isShadowRoot()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is not a valid shadow root.");
         return String();
     }
 
@@ -678,29 +668,29 @@
     }
 }
 
-String Internals::shadowPseudoId(Element* element, ExceptionState& exceptionState)
+const AtomicString& Internals::shadowPseudoId(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
-        return String();
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
+        return nullAtom;
     }
 
-    return element->shadowPseudoId().string();
+    return element->shadowPseudoId();
 }
 
-void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionState& exceptionState)
+void Internals::setShadowPseudoId(Element* element, const AtomicString& id, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return;
     }
 
-    return element->setPseudo(id);
+    return element->setShadowPseudoId(id);
 }
 
 String Internals::visiblePlaceholder(Element* element)
 {
-    if (element && isHTMLTextFormControlElement(element)) {
+    if (element && isHTMLTextFormControlElement(*element)) {
         if (toHTMLTextFormControlElement(element)->placeholderShouldBeVisible())
             return toHTMLTextFormControlElement(element)->placeholderElement()->textContent();
     }
@@ -712,14 +702,29 @@
 {
     if (!element->hasTagName(inputTag))
         return;
-    toHTMLInputElement(element)->selectColorInColorChooser(Color(colorValue));
+    Color color;
+    if (!color.setFromString(colorValue))
+        return;
+    toHTMLInputElement(element)->selectColorInColorChooser(color);
+}
+
+bool Internals::hasAutofocusRequest(Document* document)
+{
+    if (!document)
+        document = contextDocument();
+    return document->autofocusElement();
+}
+
+bool Internals::hasAutofocusRequest()
+{
+    return hasAutofocusRequest(0);
 }
 
 Vector<String> Internals::formControlStateOfHistoryItem(ExceptionState& exceptionState)
 {
     HistoryItem* mainItem = frame()->loader().currentItem();
     if (!mainItem) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No history item is available.");
         return Vector<String>();
     }
     return mainItem->documentState();
@@ -729,7 +734,7 @@
 {
     HistoryItem* mainItem = frame()->loader().currentItem();
     if (!mainItem) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No history item is available.");
         return;
     }
     mainItem->setDocumentState(state);
@@ -759,7 +764,7 @@
 {
     Document* document = contextDocument();
     if (!document || !document->view()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's viewport cannot be retrieved." : "No context document can be obtained.");
         return ClientRect::create();
     }
 
@@ -770,7 +775,7 @@
 {
     Document* document = contextDocument();
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "No context document can be obtained.");
         return ClientRect::create();
     }
 
@@ -780,7 +785,7 @@
 PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return ClientRect::create();
     }
 
@@ -794,7 +799,7 @@
 PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->page()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's Page cannot be retrieved." : "No context document can be obtained.");
         return ClientRectList::create();
     }
 
@@ -806,13 +811,13 @@
 unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
 
     DocumentMarker::MarkerTypes markerTypes = 0;
     if (!markerTypesFrom(markerType, markerTypes)) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The marker type provided ('" + markerType + "') is invalid.");
         return 0;
     }
 
@@ -822,7 +827,7 @@
 unsigned Internals::activeMarkerCountForNode(Node* node, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
 
@@ -842,13 +847,13 @@
 DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return 0;
     }
 
     DocumentMarker::MarkerTypes markerTypes = 0;
     if (!markerTypesFrom(markerType, markerTypes)) {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
+        exceptionState.throwDOMException(SyntaxError, "The marker type provided ('" + markerType + "') is invalid.");
         return 0;
     }
 
@@ -883,17 +888,25 @@
 void Internals::setMarkersActive(Node* node, unsigned startOffset, unsigned endOffset, bool active, ExceptionState& exceptionState)
 {
     if (!node) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The node provided is invalid.");
         return;
     }
 
     node->document().markers()->setMarkersActive(node, startOffset, endOffset, active);
 }
 
+void Internals::setMarkedTextMatchesAreHighlighted(Document* document, bool highlight, ExceptionState&)
+{
+    if (!document || !document->frame())
+        return;
+
+    document->frame()->editor().setMarkedTextMatchesAreHighlighted(highlight);
+}
+
 void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionState& exceptionState)
 {
     if (!document || !document->view()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's view cannot be retrieved." : "The document provided is invalid.");
         return;
     }
 
@@ -908,39 +921,10 @@
     frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
 }
 
-void Internals::setPagination(Document* document, const String& mode, int gap, int pageLength, ExceptionState& exceptionState)
-{
-    if (!document || !document->page()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
-        return;
-    }
-    Page* page = document->page();
-
-    Pagination pagination;
-    if (mode == "Unpaginated")
-        pagination.mode = Pagination::Unpaginated;
-    else if (mode == "LeftToRightPaginated")
-        pagination.mode = Pagination::LeftToRightPaginated;
-    else if (mode == "RightToLeftPaginated")
-        pagination.mode = Pagination::RightToLeftPaginated;
-    else if (mode == "TopToBottomPaginated")
-        pagination.mode = Pagination::TopToBottomPaginated;
-    else if (mode == "BottomToTopPaginated")
-        pagination.mode = Pagination::BottomToTopPaginated;
-    else {
-        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
-        return;
-    }
-
-    pagination.gap = gap;
-    pagination.pageLength = pageLength;
-    page->setPagination(pagination);
-}
-
 String Internals::viewportAsText(Document* document, float, int availableWidth, int availableHeight, ExceptionState& exceptionState)
 {
     if (!document || !document->page()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's page cannot be retrieved." : "The document provided is invalid.");
         return String();
     }
 
@@ -980,74 +964,83 @@
 bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionState& exceptionState)
 {
     if (!textField) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return false;
     }
 
     if (textField->hasTagName(inputTag))
         return toHTMLInputElement(textField)->lastChangeWasUserEdit();
 
-    // FIXME: We should be using hasTagName instead but Windows port doesn't link QualifiedNames properly.
-    if (textField->tagName() == "TEXTAREA")
+    if (textField->hasTagName(textareaTag))
         return toHTMLTextAreaElement(textField)->lastChangeWasUserEdit();
 
-    exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+    exceptionState.throwDOMException(InvalidNodeTypeError, "The element provided is not a TEXTAREA.");
     return false;
 }
 
 bool Internals::elementShouldAutoComplete(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return false;
     }
 
     if (element->hasTagName(inputTag))
         return toHTMLInputElement(element)->shouldAutocomplete();
 
-    exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+    exceptionState.throwDOMException(InvalidNodeTypeError, "The element provided is not an INPUT.");
     return false;
 }
 
 String Internals::suggestedValue(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return String();
     }
 
-    if (!element->hasTagName(inputTag)) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+    if (!element->isFormControlElement()) {
+        exceptionState.throwDOMException(InvalidNodeTypeError, "The element provided is not a form control element.");
         return String();
     }
 
-    return toHTMLInputElement(element)->suggestedValue();
+    String suggestedValue;
+    if (element->hasTagName(inputTag))
+        suggestedValue = toHTMLInputElement(element)->suggestedValue();
+
+    if (element->hasTagName(textareaTag))
+        suggestedValue = toHTMLTextAreaElement(element)->suggestedValue();
+    return suggestedValue;
 }
 
 void Internals::setSuggestedValue(Element* element, const String& value, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return;
     }
 
-    if (!element->hasTagName(inputTag)) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+    if (!element->isFormControlElement()) {
+        exceptionState.throwDOMException(InvalidNodeTypeError, "The element provided is not a form control element.");
         return;
     }
 
-    toHTMLInputElement(element)->setSuggestedValue(value);
+    if (element->hasTagName(inputTag))
+        toHTMLInputElement(element)->setSuggestedValue(value);
+
+    if (element->hasTagName(textareaTag))
+        toHTMLTextAreaElement(element)->setSuggestedValue(value);
 }
 
 void Internals::setEditingValue(Element* element, const String& value, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return;
     }
 
     if (!element->hasTagName(inputTag)) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
+        exceptionState.throwDOMException(InvalidNodeTypeError, "The element provided is not an INPUT.");
         return;
     }
 
@@ -1057,7 +1050,7 @@
 void Internals::setAutofilled(Element* element, bool enabled, ExceptionState& exceptionState)
 {
     if (!element->isFormControlElement()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidNodeTypeError, "The element provided is not a form control element.");
         return;
     }
     toHTMLFormControlElement(element)->setAutofilled(enabled);
@@ -1066,28 +1059,17 @@
 void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionState& exceptionState)
 {
     if (!element || !element->document().view()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidNodeTypeError, element ? "No view can be obtained from the provided element's document." : "The element provided is invalid.");
         return;
     }
     FrameView* frameView = element->document().view();
     frameView->scrollElementToRect(element, IntRect(x, y, w, h));
 }
 
-void Internals::paintControlTints(Document* document, ExceptionState& exceptionState)
-{
-    if (!document || !document->view()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
-        return;
-    }
-
-    FrameView* frameView = document->view();
-    frameView->paintControlTints();
-}
-
 PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionState& exceptionState)
 {
     if (!scope) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The scope element provided is invalid.");
         return 0;
     }
 
@@ -1100,7 +1082,7 @@
 unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionState& exceptionState)
 {
     if (!scope || !range) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, scope ? "The Range provided is invalid." : "The scope element provided is invalid.");
         return 0;
     }
 
@@ -1113,7 +1095,7 @@
 unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionState& exceptionState)
 {
     if (!scope || !range) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, scope ? "The Range provided is invalid." : "The scope element provided is invalid.");
         return 0;
     }
 
@@ -1126,7 +1108,7 @@
 String Internals::rangeAsText(const Range* range, ExceptionState& exceptionState)
 {
     if (!range) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The Range provided is invalid.");
         return String();
     }
 
@@ -1136,7 +1118,7 @@
 PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return 0;
     }
 
@@ -1158,7 +1140,7 @@
 Node* Internals::touchNodeAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return 0;
     }
 
@@ -1176,7 +1158,7 @@
 PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return 0;
     }
 
@@ -1198,7 +1180,7 @@
 Node* Internals::touchNodeAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return 0;
     }
 
@@ -1216,7 +1198,7 @@
 PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return 0;
     }
 
@@ -1240,7 +1222,7 @@
     SpellCheckRequester* requester = spellCheckRequester(document);
 
     if (!requester) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No spell check requestor can be obtained for the provided document.");
         return -1;
     }
 
@@ -1252,27 +1234,32 @@
     SpellCheckRequester* requester = spellCheckRequester(document);
 
     if (!requester) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No spell check requestor can be obtained for the provided document.");
         return -1;
     }
 
     return requester->lastProcessedSequence();
 }
 
-Vector<String> Internals::userPreferredLanguages() const
+Vector<AtomicString> Internals::userPreferredLanguages() const
 {
     return WebCore::userPreferredLanguages();
 }
 
+// Optimally, the bindings generator would pass a Vector<AtomicString> here but
+// this is not supported yet.
 void Internals::setUserPreferredLanguages(const Vector<String>& languages)
 {
-    WebCore::overrideUserPreferredLanguages(languages);
+    Vector<AtomicString> atomicLanguages;
+    for (size_t i = 0; i < languages.size(); ++i)
+        atomicLanguages.append(AtomicString(languages[i]));
+    WebCore::overrideUserPreferredLanguages(atomicLanguages);
 }
 
 unsigned Internals::wheelEventHandlerCount(Document* document, ExceptionState& exceptionState)
 {
     if (!document) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No context document is available.");
         return 0;
     }
 
@@ -1282,7 +1269,7 @@
 unsigned Internals::touchEventHandlerCount(Document* document, ExceptionState& exceptionState)
 {
     if (!document) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No context document is available.");
         return 0;
     }
 
@@ -1401,7 +1388,7 @@
 PassRefPtr<LayerRectList> Internals::touchEventTargetLayerRects(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->view() || !document->page() || document != contextDocument()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The document provided is invalid.");
         return 0;
     }
 
@@ -1428,7 +1415,7 @@
     unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame() || !document->frame()->view()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No view can be obtained from the provided document.");
         return 0;
     }
 
@@ -1600,7 +1587,7 @@
 {
     Page* page = contextDocument()->frame()->page();
     if (!page) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No page can be obtained from the current context document.");
         return;
     }
     page->inspectorController().setResourcesDataSizeLimitsFromInternals(maximumResourcesContentSize, maximumSingleResourceContentSize);
@@ -1632,7 +1619,7 @@
 bool Internals::isPageBoxVisible(Document* document, int pageNumber, ExceptionState& exceptionState)
 {
     if (!document) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No context document is available.");
         return false;
     }
 
@@ -1652,7 +1639,7 @@
 static PassRefPtr<NodeList> paintOrderList(Element* element, ExceptionState& exceptionState, RenderLayerStackingNode::PaintOrderListType type)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return 0;
     }
 
@@ -1660,13 +1647,13 @@
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, renderer ? "The provided element's renderer is not a box." : "The provided element has no renderer.");
         return 0;
     }
 
     RenderLayer* layer = toRenderBox(renderer)->layer();
     if (!layer) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No render layer can be obtained from the provided element.");
         return 0;
     }
 
@@ -1688,7 +1675,7 @@
 bool Internals::scrollsWithRespectTo(Element* element1, Element* element2, ExceptionState& exceptionState)
 {
     if (!element1 || !element2) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, String::format("The %s element provided is invalid.", element1 ? "second" : "first"));
         return 0;
     }
 
@@ -1696,15 +1683,19 @@
 
     RenderObject* renderer1 = element1->renderer();
     RenderObject* renderer2 = element2->renderer();
-    if (!renderer1 || !renderer2 || !renderer1->isBox() || !renderer2->isBox()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    if (!renderer1 || !renderer1->isBox()) {
+        exceptionState.throwDOMException(InvalidAccessError, renderer1 ? "The first provided element's renderer is not a box." : "The first provided element has no renderer.");
+        return 0;
+    }
+    if (!renderer2 || !renderer2->isBox()) {
+        exceptionState.throwDOMException(InvalidAccessError, renderer2 ? "The second provided element's renderer is not a box." : "The second provided element has no renderer.");
         return 0;
     }
 
     RenderLayer* layer1 = toRenderBox(renderer1)->layer();
     RenderLayer* layer2 = toRenderBox(renderer2)->layer();
     if (!layer1 || !layer2) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, String::format("No render layer can be obtained from the %s provided element.", layer1 ? "second" : "first"));
         return 0;
     }
 
@@ -1714,7 +1705,7 @@
 bool Internals::isUnclippedDescendant(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return 0;
     }
 
@@ -1722,13 +1713,13 @@
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, renderer ? "The provided element's renderer is not a box." : "The provided element has no renderer.");
         return 0;
     }
 
     RenderLayer* layer = toRenderBox(renderer)->layer();
     if (!layer) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No render layer can be obtained from the provided element.");
         return 0;
     }
 
@@ -1738,7 +1729,7 @@
 bool Internals::needsCompositedScrolling(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return 0;
     }
 
@@ -1746,13 +1737,13 @@
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, renderer ? "The provided element's renderer is not a box." : "The provided element has no renderer.");
         return 0;
     }
 
     RenderLayer* layer = toRenderBox(renderer)->layer();
     if (!layer) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No render layer can be obtained from the provided element.");
         return 0;
     }
 
@@ -1762,7 +1753,7 @@
 String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return String();
     }
 
@@ -1772,7 +1763,7 @@
 String Internals::elementLayerTreeAsText(Element* element, unsigned flags, ExceptionState& exceptionState) const
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return String();
     }
 
@@ -1780,7 +1771,7 @@
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, renderer ? "The provided element's renderer is not a box." : "The provided element has no renderer.");
         return String();
     }
 
@@ -1798,19 +1789,19 @@
 static RenderLayer* getRenderLayerForElement(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return 0;
     }
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, renderer ? "The provided element's renderer is not a box." : "The provided element has no renderer.");
         return 0;
     }
 
     RenderLayer* layer = toRenderBox(renderer)->layer();
     if (!layer) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No render layer can be obtained from the provided element.");
         return 0;
     }
 
@@ -1820,7 +1811,7 @@
 void Internals::setNeedsCompositedScrolling(Element* element, unsigned needsCompositedScrolling, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return;
     }
 
@@ -1833,7 +1824,7 @@
 String Internals::repaintRectsAsText(Document* document, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return String();
     }
 
@@ -1843,7 +1834,7 @@
 PassRefPtr<ClientRectList> Internals::repaintRects(Element* element, ExceptionState& exceptionState) const
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return 0;
     }
 
@@ -1858,8 +1849,7 @@
         }
     }
 
-    // It's an error to call this on an element that's not composited.
-    exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+    exceptionState.throwDOMException(InvalidAccessError, "The provided element is not composited.");
     return 0;
 }
 
@@ -1871,7 +1861,7 @@
 String Internals::mainThreadScrollingReasons(Document* document, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return String();
     }
 
@@ -1879,7 +1869,7 @@
     document->updateLayout();
     RenderView* view = document->renderView();
     if (view->compositor())
-        view->compositor()->updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
+        view->compositor()->updateCompositingLayers();
 
     Page* page = document->page();
     if (!page)
@@ -1891,7 +1881,7 @@
 PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(Document* document, ExceptionState& exceptionState) const
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return 0;
     }
 
@@ -1905,7 +1895,7 @@
 void Internals::garbageCollectDocumentResources(Document* document, ExceptionState& exceptionState) const
 {
     if (!document) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No context document is available.");
         return;
     }
     ResourceFetcher* fetcher = document->fetcher();
@@ -1973,7 +1963,7 @@
 String Internals::pageProperty(String propertyName, int pageNumber, ExceptionState& exceptionState) const
 {
     if (!frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No frame is available.");
         return String();
     }
 
@@ -1983,7 +1973,7 @@
 String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionState& exceptionState) const
 {
     if (!frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No frame is available.");
         return String();
     }
 
@@ -1994,7 +1984,7 @@
 {
     Document* document = contextDocument();
     if (!document || !document->page()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's page cannot be retrieved." : "No context document can be obtained.");
         return;
     }
     Page* page = document->page();
@@ -2004,7 +1994,7 @@
 void Internals::setIsCursorVisible(Document* document, bool isVisible, ExceptionState& exceptionState)
 {
     if (!document || !document->page()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's page cannot be retrieved." : "No context document can be obtained.");
         return;
     }
     document->page()->setIsCursorVisible(isVisible);
@@ -2067,7 +2057,7 @@
 void Internals::startTrackingRepaints(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->view()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's view cannot be retrieved." : "The document provided is invalid.");
         return;
     }
 
@@ -2078,7 +2068,7 @@
 void Internals::stopTrackingRepaints(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->view()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's view cannot be retrieved." : "The document provided is invalid.");
         return;
     }
 
@@ -2101,7 +2091,7 @@
     } else if (node->hasTagName(HTMLNames::iframeTag)) {
         document = toHTMLIFrameElement(node)->contentDocument();
     } else {
-        exceptionState.throwUninformativeAndGenericDOMException(TypeError);
+        exceptionState.throwDOMException(TypeError, "The node provided is neither a document nor an IFrame.");
         return;
     }
     document->updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasksSynchronously);
@@ -2120,7 +2110,7 @@
 PassRefPtr<ClientRectList> Internals::annotatedRegions(Document* document, bool draggable, ExceptionState& exceptionState)
 {
     if (!document || !document->view()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's view cannot be retrieved." : "The document provided is invalid.");
         return ClientRectList::create();
     }
 
@@ -2192,7 +2182,7 @@
 String Internals::getCurrentCursorInfo(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "The document provided is invalid.");
         return String();
     }
 
@@ -2244,7 +2234,7 @@
 {
     Document* document = contextDocument();
     if (!document || !document->frame()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's frame cannot be retrieved." : "No context document can be obtained.");
         return 0;
     }
 
@@ -2254,7 +2244,7 @@
 String Internals::markerTextForListItem(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return String();
     }
     return WebCore::markerTextForListItem(element);
@@ -2263,7 +2253,7 @@
 String Internals::getImageSourceURL(Element* element, ExceptionState& exceptionState)
 {
     if (!element) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
         return String();
     }
     return element->imageSourceURL();
@@ -2272,7 +2262,7 @@
 String Internals::baseURL(Document* document, ExceptionState& exceptionState)
 {
     if (!document) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, "No context document is available.");
         return String();
     }
 
@@ -2296,10 +2286,11 @@
 
 bool Internals::loseSharedGraphicsContext3D()
 {
-    RefPtr<GraphicsContext3D> sharedContext = SharedGraphicsContext3D::get();
-    if (!sharedContext)
+    OwnPtr<blink::WebGraphicsContext3DProvider> sharedProvider = adoptPtr(blink::Platform::current()->createSharedOffscreenGraphicsContext3DProvider());
+    if (!sharedProvider)
         return false;
-    sharedContext->extensions()->loseContextCHROMIUM(Extensions3D::GUILTY_CONTEXT_RESET_ARB, Extensions3D::INNOCENT_CONTEXT_RESET_ARB);
+    blink::WebGraphicsContext3D* sharedContext = sharedProvider->context3d();
+    sharedContext->loseContextCHROMIUM(GL_GUILTY_CONTEXT_RESET_EXT, GL_INNOCENT_CONTEXT_RESET_EXT);
     // To prevent tests that call loseSharedGraphicsContext3D from being
     // flaky, we call finish so that the context is guaranteed to be lost
     // synchronously (i.e. before returning).
@@ -2310,7 +2301,7 @@
 void Internals::forceCompositingUpdate(Document* document, ExceptionState& exceptionState)
 {
     if (!document || !document->renderView()) {
-        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's render view cannot be retrieved." : "The document provided is invalid.");
         return;
     }
 
@@ -2318,7 +2309,65 @@
 
     RenderView* view = document->renderView();
     if (view->compositor())
-        view->compositor()->updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
+        view->compositor()->updateCompositingLayers();
+}
+
+bool Internals::isCompositorFramePending(Document* document, ExceptionState& exceptionState)
+{
+    if (!document || !document->renderView()) {
+        exceptionState.throwDOMException(InvalidAccessError, document ? "The document's render view cannot be retrieved." : "The document provided is invalid.");
+        return false;
+    }
+
+    return document->page()->chrome().client().isCompositorFramePending();
+}
+
+void Internals::setZoomFactor(float factor)
+{
+    frame()->setPageZoomFactor(factor);
+}
+
+void Internals::setShouldRevealPassword(Element* element, bool reveal, ExceptionState& exceptionState)
+{
+    if (!element || !element->hasTagName(inputTag)) {
+        exceptionState.throwDOMException(InvalidAccessError, "The element provided is invalid.");
+        return;
+    }
+
+    return toHTMLInputElement(element)->setShouldRevealPassword(reveal);
+}
+
+namespace {
+
+class AddOneFunction : public ScriptFunction {
+public:
+    static PassOwnPtr<ScriptFunction> create(ExecutionContext* context)
+    {
+        return adoptPtr(new AddOneFunction(toIsolate(context)));
+    }
+
+private:
+    AddOneFunction(v8::Isolate* isolate)
+        : ScriptFunction(isolate)
+    {
+    }
+
+    virtual ScriptValue call(ScriptValue value) OVERRIDE
+    {
+        v8::Local<v8::Value> v8Value = value.v8Value();
+        v8::Isolate* isolate = value.isolate();
+        ASSERT(v8Value->IsNumber());
+        int intValue = v8Value.As<v8::Integer>()->Value();
+        ScriptValue result  = ScriptValue(v8::Integer::New(isolate, intValue + 1), isolate);
+        return result;
+    }
+};
+
+} // namespace
+
+ScriptPromise Internals::addOneToPromise(ExecutionContext* context, ScriptPromise promise)
+{
+    return promise.then(AddOneFunction::create(context));
 }
 
 }
diff --git a/Source/core/testing/Internals.h b/Source/core/testing/Internals.h
index 7edb8d3..cadc681 100644
--- a/Source/core/testing/Internals.h
+++ b/Source/core/testing/Internals.h
@@ -28,6 +28,7 @@
 #define Internals_h
 
 #include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "bindings/v8/ScriptPromise.h"
 #include "bindings/v8/ScriptValue.h"
 #include "core/css/CSSComputedStyleDeclaration.h"
 #include "core/dom/ContextLifecycleObserver.h"
@@ -66,7 +67,7 @@
 class ShadowRoot;
 class TypeConversions;
 
-class Internals : public RefCounted<Internals>
+class Internals FINAL : public RefCounted<Internals>
     , public ContextLifecycleObserver {
 public:
     static PassRefPtr<Internals> create(Document*);
@@ -89,33 +90,32 @@
     String styleResolverStatsReport(ExceptionState&) const;
     String styleResolverStatsTotalsReport(ExceptionState&) const;
 
+    bool isSharingStyle(Element*, Element*, ExceptionState&) const;
+
     size_t numberOfScopedHTMLStyleChildren(const Node*, ExceptionState&) const;
     PassRefPtr<CSSComputedStyleDeclaration> computedStyleIncludingVisitedInfo(Node*, ExceptionState&) const;
 
-    ShadowRoot* ensureShadowRoot(Element* host, ExceptionState&);
     ShadowRoot* shadowRoot(Element* host, ExceptionState&);
     ShadowRoot* youngestShadowRoot(Element* host, ExceptionState&);
     ShadowRoot* oldestShadowRoot(Element* host, ExceptionState&);
     ShadowRoot* youngerShadowRoot(Node* shadow, ExceptionState&);
-    ShadowRoot* olderShadowRoot(Node* shadow, ExceptionState&);
     String shadowRootType(const Node*, ExceptionState&) const;
     bool hasShadowInsertionPoint(const Node*, ExceptionState&) const;
     bool hasContentElement(const Node*, ExceptionState&) const;
     size_t countElementShadow(const Node*, ExceptionState&) const;
-    String shadowPseudoId(Element*, ExceptionState&);
-    void setShadowPseudoId(Element*, const String&, ExceptionState&);
+    const AtomicString& shadowPseudoId(Element*, ExceptionState&);
+    void setShadowPseudoId(Element*, const AtomicString&, ExceptionState&);
 
     // CSS Animation / Transition testing.
     unsigned numberOfActiveAnimations() const;
     void pauseAnimations(double pauseTime, ExceptionState&);
 
-    PassRefPtr<Element> createContentElement(ExceptionState&);
     bool isValidContentSelect(Element* insertionPoint, ExceptionState&);
     Node* treeScopeRootNode(Node*, ExceptionState&);
     Node* parentTreeScope(Node*, ExceptionState&);
-    bool hasSelectorForIdInShadow(Element* host, const String& idValue, ExceptionState&);
-    bool hasSelectorForClassInShadow(Element* host, const String& className, ExceptionState&);
-    bool hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionState&);
+    bool hasSelectorForIdInShadow(Element* host, const AtomicString& idValue, ExceptionState&);
+    bool hasSelectorForClassInShadow(Element* host, const AtomicString& className, ExceptionState&);
+    bool hasSelectorForAttributeInShadow(Element* host, const AtomicString& attributeName, ExceptionState&);
     bool hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionState&);
     unsigned short compareTreeScopePosition(const Node*, const Node*, ExceptionState&) const;
 
@@ -127,9 +127,12 @@
     Node* previousNodeByWalker(Node*, ExceptionState&);
 
     unsigned updateStyleAndReturnAffectedElementCount(ExceptionState&) const;
+    unsigned needsLayoutCount(ExceptionState&) const;
 
     String visiblePlaceholder(Element*);
     void selectColorInColorChooser(Element*, const String& colorValue);
+    bool hasAutofocusRequest(Document*);
+    bool hasAutofocusRequest();
     Vector<String> formControlStateOfHistoryItem(ExceptionState&);
     void setFormControlStateOfHistoryItem(const Vector<String>&, ExceptionState&);
     void setEnableMockPagePopup(bool, ExceptionState&);
@@ -149,22 +152,19 @@
     String markerDescriptionForNode(Node*, const String& markerType, unsigned index, ExceptionState&);
     void addTextMatchMarker(const Range*, bool isActive);
     void setMarkersActive(Node*, unsigned startOffset, unsigned endOffset, bool, ExceptionState&);
+    void setMarkedTextMatchesAreHighlighted(Document*, bool, ExceptionState&);
 
     void setScrollViewPosition(Document*, long x, long y, ExceptionState&);
-    void setPagination(Document* document, const String& mode, int gap, ExceptionState& ec) { setPagination(document, mode, gap, 0, ec); }
-    void setPagination(Document*, const String& mode, int gap, int pageLength, ExceptionState&);
     String viewportAsText(Document*, float devicePixelRatio, int availableWidth, int availableHeight, ExceptionState&);
 
     bool wasLastChangeUserEdit(Element* textField, ExceptionState&);
     bool elementShouldAutoComplete(Element* inputElement, ExceptionState&);
-    String suggestedValue(Element* inputElement, ExceptionState&);
-    void setSuggestedValue(Element* inputElement, const String&, ExceptionState&);
+    String suggestedValue(Element*, ExceptionState&);
+    void setSuggestedValue(Element*, const String&, ExceptionState&);
     void setEditingValue(Element* inputElement, const String&, ExceptionState&);
     void setAutofilled(Element*, bool enabled, ExceptionState&);
     void scrollElementToRect(Element*, long x, long y, long w, long h, ExceptionState&);
 
-    void paintControlTints(Document*, ExceptionState&);
-
     PassRefPtr<Range> rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionState&);
     unsigned locationFromRange(Element* scope, const Range*, ExceptionState&);
     unsigned lengthFromRange(Element* scope, const Range*, ExceptionState&);
@@ -179,7 +179,7 @@
     int lastSpellCheckRequestSequence(Document*, ExceptionState&);
     int lastSpellCheckProcessedSequence(Document*, ExceptionState&);
 
-    Vector<String> userPreferredLanguages() const;
+    Vector<AtomicString> userPreferredLanguages() const;
     void setUserPreferredLanguages(const Vector<String>&);
 
     unsigned wheelEventHandlerCount(Document*, ExceptionState&);
@@ -303,6 +303,14 @@
 
     void forceCompositingUpdate(Document*, ExceptionState&);
 
+    bool isCompositorFramePending(Document*, ExceptionState&);
+
+    void setZoomFactor(float);
+
+    void setShouldRevealPassword(Element*, bool, ExceptionState&);
+
+    ScriptPromise addOneToPromise(ExecutionContext*, ScriptPromise);
+
 private:
     explicit Internals(Document*);
     Document* contextDocument() const;
@@ -314,7 +322,6 @@
     RefPtr<DOMWindow> m_frontendWindow;
     OwnPtr<InspectorFrontendChannelDummy> m_frontendChannel;
     RefPtr<InternalRuntimeFlags> m_runtimeFlags;
-    RefPtr<ScrollingCoordinator> m_scrollingCoordinator;
     RefPtr<InternalProfilers> m_profilers;
 };
 
diff --git a/Source/core/testing/Internals.idl b/Source/core/testing/Internals.idl
index d137ae9..082be3d 100644
--- a/Source/core/testing/Internals.idl
+++ b/Source/core/testing/Internals.idl
@@ -25,7 +25,8 @@
  */
 
 [
-    DoNotCheckConstants
+    DoNotCheckConstants,
+    NoInterfaceObject,  // testing interfaces do not appear on global objects
 ] interface Internals {
     DOMString address(Node node);
 
@@ -41,15 +42,15 @@
     [RaisesException] DOMString styleResolverStatsReport();
     [RaisesException] DOMString styleResolverStatsTotalsReport();
 
+    [RaisesException] boolean isSharingStyle(Element element1, Element element2);
+
     [RaisesException] unsigned long numberOfScopedHTMLStyleChildren(Node scope);
     [RaisesException] CSSStyleDeclaration computedStyleIncludingVisitedInfo(Node node);
 
-    [RaisesException] ShadowRoot ensureShadowRoot(Element host);
     [RaisesException] ShadowRoot shadowRoot(Element host);
     [RaisesException] ShadowRoot youngestShadowRoot(Element host);
     [RaisesException] ShadowRoot oldestShadowRoot(Element host);
     [RaisesException] ShadowRoot youngerShadowRoot(Node root);
-    [RaisesException] ShadowRoot olderShadowRoot(Node root);
 
     [RaisesException] DOMString shadowRootType(Node root);
     [RaisesException] boolean hasShadowInsertionPoint(Node root);
@@ -57,7 +58,6 @@
     [RaisesException] unsigned long countElementShadow(Node Root);
     [RaisesException] DOMString shadowPseudoId(Element element);
     [RaisesException] void setShadowPseudoId(Element element, DOMString id);
-    [RaisesException] Element createContentElement();
     [RaisesException] boolean isValidContentSelect(Element contentElement);
     [RaisesException] Node treeScopeRootNode(Node node);
     [RaisesException] Node parentTreeScope(Node node);
@@ -67,6 +67,7 @@
     [RaisesException] boolean hasSelectorForPseudoClassInShadow(Element host, DOMString pseudoClass);
     [RaisesException] unsigned short compareTreeScopePosition(Node treeScope1, Node treeScope2);
     [RaisesException] unsigned long updateStyleAndReturnAffectedElementCount();
+    [RaisesException] unsigned long needsLayoutCount();
 
     // CSS Animation and Transition testing.
     unsigned long numberOfActiveAnimations();
@@ -82,6 +83,8 @@
 
     void selectColorInColorChooser(Element element, DOMString colorValue);
 
+    // If the argument is omitted, the top-level document is used.
+    boolean hasAutofocusRequest(optional Document document);
     [RaisesException] DOMString[] formControlStateOfHistoryItem();
     [RaisesException] void setFormControlStateOfHistoryItem(sequence<DOMString> values);
     [RaisesException] void setEnableMockPagePopup(boolean enabled);
@@ -101,11 +104,10 @@
     [RaisesException] DOMString markerDescriptionForNode(Node node, DOMString markerType, unsigned long index);
     void addTextMatchMarker(Range range, boolean isActive);
     [RaisesException] void setMarkersActive(Node node, unsigned long startOffset, unsigned long endOffset, boolean active);
+    [RaisesException] void setMarkedTextMatchesAreHighlighted(Document document, boolean highlight);
 
     [RaisesException] void setScrollViewPosition(Document document, long x, long y);
 
-    [RaisesException] void setPagination(Document document, DOMString mode, long gap, optional long pageLength);
-
     [RaisesException] DOMString viewportAsText(Document document,
                                                float devicePixelRatio,
                                                long availableWidth,
@@ -118,8 +120,6 @@
     [RaisesException] void setEditingValue(Element inputElement, DOMString value);
     [RaisesException] void setAutofilled(Element inputElement, boolean enabled);
 
-    [RaisesException] void paintControlTints(Document document);
-
     [RaisesException] void scrollElementToRect(Element element, long x, long y, long w, long h);
 
     [RaisesException] Range rangeFromLocationAndLength(Element scope, long rangeLocation, long rangeLength);
@@ -270,4 +270,11 @@
     boolean loseSharedGraphicsContext3D();
 
     [RaisesException] void forceCompositingUpdate(Document document);
+    [RaisesException] boolean isCompositorFramePending(Document document);
+
+    void setZoomFactor(float factor);
+
+    [RaisesException] void setShouldRevealPassword(Element element, boolean reveal);
+
+    [CallWith=ExecutionContext] Promise addOneToPromise(Promise promise);
 };
diff --git a/Source/core/testing/LayerRect.idl b/Source/core/testing/LayerRect.idl
index 8a4d8e1..7cc2f5b 100644
--- a/Source/core/testing/LayerRect.idl
+++ b/Source/core/testing/LayerRect.idl
@@ -29,6 +29,7 @@
  */
 
 [
+    NoInterfaceObject,  // testing interfaces do not appear on global objects
 ] interface LayerRect {
     readonly attribute Node layerRootNode;
     readonly attribute DOMString layerType;
diff --git a/Source/core/testing/LayerRectList.idl b/Source/core/testing/LayerRectList.idl
index 9dd2ca7..03e63c5 100644
--- a/Source/core/testing/LayerRectList.idl
+++ b/Source/core/testing/LayerRectList.idl
@@ -29,6 +29,7 @@
  */
 
 [
+    NoInterfaceObject,  // testing interfaces do not appear on global objects
 ] interface LayerRectList {
     readonly attribute unsigned long length;
     getter LayerRect item(unsigned long index);
diff --git a/Source/core/testing/MallocStatistics.idl b/Source/core/testing/MallocStatistics.idl
index dd3459b..663fabb 100644
--- a/Source/core/testing/MallocStatistics.idl
+++ b/Source/core/testing/MallocStatistics.idl
@@ -24,6 +24,7 @@
  */
 
 [
+    NoInterfaceObject,  // testing interfaces do not appear on global objects
 ] interface MallocStatistics {
     readonly attribute unsigned long reservedVMBytes;
     readonly attribute unsigned long committedVMBytes;
diff --git a/Source/core/testing/MockPagePopupDriver.cpp b/Source/core/testing/MockPagePopupDriver.cpp
index 56cc248..e0a789e 100644
--- a/Source/core/testing/MockPagePopupDriver.cpp
+++ b/Source/core/testing/MockPagePopupDriver.cpp
@@ -30,8 +30,7 @@
 #include "CSSValueKeywords.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/html/HTMLIFrameElement.h"
-#include "core/loader/DocumentLoader.h"
-#include "core/loader/DocumentWriter.h"
+#include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
 #include "core/frame/Frame.h"
 #include "core/page/PagePopup.h"
@@ -69,12 +68,10 @@
     m_iframe->setInlineStyleProperty(CSSPropertyTop, originBoundsInRootView.maxY(), CSSPrimitiveValue::CSS_PX, true);
     if (document->body())
         document->body()->appendChild(m_iframe.get());
-    Frame* contentFrame = m_iframe->contentFrame();
-    DocumentWriter* writer = contentFrame->loader().activeDocumentLoader()->beginWriting("text/html", "UTF-8");
     const char scriptToSetUpPagePopupController[] = "<script>window.pagePopupController = parent.internals.pagePopupController;</script>";
-    writer->addData(scriptToSetUpPagePopupController, sizeof(scriptToSetUpPagePopupController));
-    m_popupClient->writeDocument(*writer);
-    contentFrame->loader().activeDocumentLoader()->endWriting(writer);
+    RefPtr<SharedBuffer> data = SharedBuffer::create(scriptToSetUpPagePopupController, sizeof(scriptToSetUpPagePopupController));
+    m_popupClient->writeDocument(data.get());
+    m_iframe->contentFrame()->loader().load(FrameLoadRequest(0, blankURL(), SubstituteData(data, "text/html", "UTF-8", KURL(), ForceSynchronousLoad)));
 }
 
 PassRefPtr<MockPagePopup> MockPagePopup::create(PagePopupClient* client, const IntRect& originBoundsInRootView, Frame* mainFrame)
diff --git a/Source/core/testing/MockPagePopupDriver.h b/Source/core/testing/MockPagePopupDriver.h
index e1f90aa..b69b553 100644
--- a/Source/core/testing/MockPagePopupDriver.h
+++ b/Source/core/testing/MockPagePopupDriver.h
@@ -38,7 +38,7 @@
 class PagePopup;
 class PagePopupController;
 
-class MockPagePopupDriver : public PagePopupDriver {
+class MockPagePopupDriver FINAL : public PagePopupDriver {
 public:
     static PassOwnPtr<MockPagePopupDriver> create(Frame* mainFrame);
     virtual ~MockPagePopupDriver();
diff --git a/Source/core/testing/TypeConversions.idl b/Source/core/testing/TypeConversions.idl
index 7a70cc5..b87b984 100644
--- a/Source/core/testing/TypeConversions.idl
+++ b/Source/core/testing/TypeConversions.idl
@@ -24,6 +24,7 @@
  */
 
 [
+    NoInterfaceObject,  // testing interfaces do not appear on global objects
 ] interface TypeConversions {
     attribute long testLong;
     [EnforceRange, ImplementedAs=testLong] attribute long testEnforceRangeLong;
diff --git a/Source/core/testing/v8/WebCoreTestSupport.cpp b/Source/core/testing/v8/WebCoreTestSupport.cpp
index f28fecb..45e2e70 100644
--- a/Source/core/testing/v8/WebCoreTestSupport.cpp
+++ b/Source/core/testing/v8/WebCoreTestSupport.cpp
@@ -43,7 +43,7 @@
 {
     v8::Context::Scope contextScope(context);
     v8::HandleScope scope(context->GetIsolate());
-    ExecutionContext* scriptContext = getExecutionContext();
+    ExecutionContext* scriptContext = currentExecutionContext(context->GetIsolate());
     if (scriptContext->isDocument())
         context->Global()->Set(v8::String::NewFromUtf8(context->GetIsolate(), Internals::internalsId), toV8(Internals::create(toDocument(scriptContext)), v8::Handle<v8::Object>(), context->GetIsolate()));
 }
@@ -57,7 +57,7 @@
     v8::Context::Scope contextScope(context);
     v8::HandleScope scope(context->GetIsolate());
 
-    ExecutionContext* scriptContext = getExecutionContext();
+    ExecutionContext* scriptContext = currentExecutionContext(context->GetIsolate());
     Page* page = toDocument(scriptContext)->frame()->page();
     Internals::resetToConsistentState(page);
     InternalSettings::from(page)->resetToConsistentState();
diff --git a/Source/core/timing/MemoryInfo.cpp b/Source/core/timing/MemoryInfo.cpp
index 1955f15..3bb0821 100644
--- a/Source/core/timing/MemoryInfo.cpp
+++ b/Source/core/timing/MemoryInfo.cpp
@@ -33,7 +33,7 @@
 
 #include <limits>
 #include "core/frame/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/MainThread.h"
 #include "wtf/MathExtras.h"
diff --git a/Source/core/timing/Performance.h b/Source/core/timing/Performance.h
index 8dfe0be..65111a6 100644
--- a/Source/core/timing/Performance.h
+++ b/Source/core/timing/Performance.h
@@ -53,11 +53,11 @@
 class ResourceTimingInfo;
 class UserTiming;
 
-class Performance : public ScriptWrappable, public RefCounted<Performance>, public DOMWindowProperty, public EventTargetWithInlineData {
+class Performance FINAL : public ScriptWrappable, public RefCounted<Performance>, public DOMWindowProperty, public EventTargetWithInlineData {
     REFCOUNTED_EVENT_TARGET(Performance);
 public:
     static PassRefPtr<Performance> create(Frame* frame) { return adoptRef(new Performance(frame)); }
-    ~Performance();
+    virtual ~Performance();
 
     virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual ExecutionContext* executionContext() const OVERRIDE;
diff --git a/Source/core/timing/Performance.idl b/Source/core/timing/Performance.idl
index b29b83e..762f6b0 100644
--- a/Source/core/timing/Performance.idl
+++ b/Source/core/timing/Performance.idl
@@ -54,12 +54,6 @@
     [RaisesException,MeasureAs=UnprefixedUserTiming] void measure(DOMString measureName, [Default=NullString] optional DOMString startMark, [Default=NullString] optional DOMString endMark);
     [MeasureAs=UnprefixedUserTiming] void clearMeasures([Default=NullString] optional DOMString measureName);
 
-    [RaisesException,DeprecateAs=PrefixedUserTiming,ImplementedAs=mark] void webkitMark(DOMString markName);
-    [DeprecateAs=PrefixedUserTiming,ImplementedAs=clearMarks] void webkitClearMarks([Default=NullString] optional  DOMString markName);
-
-    [RaisesException,DeprecateAs=PrefixedUserTiming,ImplementedAs=measure] void webkitMeasure(DOMString measureName, [Default=NullString] optional DOMString startMark, [Default=NullString] optional DOMString endMark);
-    [DeprecateAs=PrefixedUserTiming,ImplementedAs=clearMeasures] void webkitClearMeasures([Default=NullString] optional DOMString measureName);
-
     // See http://www.w3.org/TR/hr-time/ for details.
     double now();
 };
diff --git a/Source/core/timing/PerformanceMark.h b/Source/core/timing/PerformanceMark.h
index 793a7cd..8e8b589 100644
--- a/Source/core/timing/PerformanceMark.h
+++ b/Source/core/timing/PerformanceMark.h
@@ -32,11 +32,11 @@
 
 namespace WebCore {
 
-class PerformanceMark : public PerformanceEntry {
+class PerformanceMark FINAL : public PerformanceEntry {
 public:
     static PassRefPtr<PerformanceMark> create(const String& name, double startTime) { return adoptRef(new PerformanceMark(name, startTime)); }
 
-    virtual bool isMark() { return true; }
+    virtual bool isMark() OVERRIDE { return true; }
 
 private:
     PerformanceMark(const String& name, double startTime) : PerformanceEntry(name, "mark", startTime, startTime)
@@ -44,7 +44,7 @@
         ScriptWrappable::init(this);
     }
 
-    ~PerformanceMark() { }
+    virtual ~PerformanceMark() { }
 };
 
 }
diff --git a/Source/core/timing/PerformanceMeasure.h b/Source/core/timing/PerformanceMeasure.h
index 9d24142..acab8e5 100644
--- a/Source/core/timing/PerformanceMeasure.h
+++ b/Source/core/timing/PerformanceMeasure.h
@@ -32,18 +32,18 @@
 
 namespace WebCore {
 
-class PerformanceMeasure : public PerformanceEntry {
+class PerformanceMeasure FINAL : public PerformanceEntry {
 public:
     static PassRefPtr<PerformanceMeasure> create(const String& name, double startTime, double endTime) { return adoptRef(new PerformanceMeasure(name, startTime, endTime)); }
 
-    virtual bool isMeasure() { return true; }
+    virtual bool isMeasure() OVERRIDE { return true; }
 
 private:
     PerformanceMeasure(const String& name, double startTime, double endTime) : PerformanceEntry(name, "measure", startTime, endTime)
     {
         ScriptWrappable::init(this);
     }
-    ~PerformanceMeasure() { }
+    virtual ~PerformanceMeasure() { }
 };
 
 }
diff --git a/Source/core/timing/PerformanceNavigation.h b/Source/core/timing/PerformanceNavigation.h
index 2444b39..c635942 100644
--- a/Source/core/timing/PerformanceNavigation.h
+++ b/Source/core/timing/PerformanceNavigation.h
@@ -40,7 +40,7 @@
 
 class Frame;
 
-class PerformanceNavigation : public RefCounted<PerformanceNavigation>, public ScriptWrappable, public DOMWindowProperty {
+class PerformanceNavigation FINAL : public RefCounted<PerformanceNavigation>, public ScriptWrappable, public DOMWindowProperty {
 public:
     static PassRefPtr<PerformanceNavigation> create(Frame* frame) { return adoptRef(new PerformanceNavigation(frame)); }
 
diff --git a/Source/core/timing/PerformanceResourceTiming.h b/Source/core/timing/PerformanceResourceTiming.h
index 2c1c7ad..fd286f3 100644
--- a/Source/core/timing/PerformanceResourceTiming.h
+++ b/Source/core/timing/PerformanceResourceTiming.h
@@ -45,7 +45,7 @@
 class ResourceResponse;
 class ResourceTimingInfo;
 
-class PerformanceResourceTiming : public PerformanceEntry {
+class PerformanceResourceTiming FINAL : public PerformanceEntry {
 public:
     static PassRefPtr<PerformanceResourceTiming> create(const ResourceTimingInfo& info, Document* requestingDocument, double startTime, double lastRedirectEndTime, bool m_allowTimingDetails, bool m_allowRedirectDetails)
     {
@@ -71,11 +71,11 @@
     double responseStart() const;
     double responseEnd() const;
 
-    virtual bool isResource() { return true; }
+    virtual bool isResource() OVERRIDE { return true; }
 
 private:
     PerformanceResourceTiming(const ResourceTimingInfo&, Document* requestingDocument, double startTime, double lastRedirectEndTime, bool m_allowTimingDetails, bool m_allowRedirectDetails);
-    ~PerformanceResourceTiming();
+    virtual ~PerformanceResourceTiming();
 
     AtomicString m_initiatorType;
     RefPtr<ResourceLoadTiming> m_timing;
diff --git a/Source/core/timing/PerformanceTiming.cpp b/Source/core/timing/PerformanceTiming.cpp
index 0aa305e..6312694 100644
--- a/Source/core/timing/PerformanceTiming.cpp
+++ b/Source/core/timing/PerformanceTiming.cpp
@@ -349,7 +349,9 @@
 {
     ASSERT(monotonicSeconds >= 0);
     const DocumentLoadTiming* timing = documentLoadTiming();
-    ASSERT(timing);
+    if (!timing)
+        return 0;
+
     return toIntegerMilliseconds(timing->monotonicTimeToPseudoWallTime(monotonicSeconds));
 }
 
diff --git a/Source/core/timing/PerformanceTiming.h b/Source/core/timing/PerformanceTiming.h
index cd8ffae..640b47e 100644
--- a/Source/core/timing/PerformanceTiming.h
+++ b/Source/core/timing/PerformanceTiming.h
@@ -44,7 +44,7 @@
 class Frame;
 class ResourceLoadTiming;
 
-class PerformanceTiming : public RefCounted<PerformanceTiming>, public ScriptWrappable, public DOMWindowProperty {
+class PerformanceTiming FINAL : public RefCounted<PerformanceTiming>, public ScriptWrappable, public DOMWindowProperty {
 public:
     static PassRefPtr<PerformanceTiming> create(Frame* frame) { return adoptRef(new PerformanceTiming(frame)); }
 
diff --git a/Source/core/webcore.target.darwin-arm.mk b/Source/core/webcore.target.darwin-arm.mk
index ee62396..8dfb3b7 100644
--- a/Source/core/webcore.target.darwin-arm.mk
+++ b/Source/core/webcore.target.darwin-arm.mk
@@ -14,11 +14,10 @@
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_dom_gyp)/third_party_WebKit_Source_core_webcore_dom_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_html_gyp)/third_party_WebKit_Source_core_webcore_html_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_platform_gyp)/third_party_WebKit_Source_core_webcore_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_remaining_gyp)/third_party_WebKit_Source_core_webcore_remaining_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_rendering_gyp)/third_party_WebKit_Source_core_webcore_rendering_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_svg_gyp)/third_party_WebKit_Source_core_webcore_svg_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_derived_gyp)/third_party_WebKit_Source_core_webcore_derived_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_generated_gyp)/third_party_WebKit_Source_core_webcore_generated_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,GYP,third_party_npapi_npapi_gyp)/npapi.stamp \
diff --git a/Source/core/webcore.target.darwin-mips.mk b/Source/core/webcore.target.darwin-mips.mk
index ee62396..8dfb3b7 100644
--- a/Source/core/webcore.target.darwin-mips.mk
+++ b/Source/core/webcore.target.darwin-mips.mk
@@ -14,11 +14,10 @@
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_dom_gyp)/third_party_WebKit_Source_core_webcore_dom_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_html_gyp)/third_party_WebKit_Source_core_webcore_html_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_platform_gyp)/third_party_WebKit_Source_core_webcore_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_remaining_gyp)/third_party_WebKit_Source_core_webcore_remaining_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_rendering_gyp)/third_party_WebKit_Source_core_webcore_rendering_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_svg_gyp)/third_party_WebKit_Source_core_webcore_svg_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_derived_gyp)/third_party_WebKit_Source_core_webcore_derived_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_generated_gyp)/third_party_WebKit_Source_core_webcore_generated_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,GYP,third_party_npapi_npapi_gyp)/npapi.stamp \
diff --git a/Source/core/webcore.target.darwin-x86.mk b/Source/core/webcore.target.darwin-x86.mk
index ee62396..8dfb3b7 100644
--- a/Source/core/webcore.target.darwin-x86.mk
+++ b/Source/core/webcore.target.darwin-x86.mk
@@ -14,11 +14,10 @@
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_dom_gyp)/third_party_WebKit_Source_core_webcore_dom_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_html_gyp)/third_party_WebKit_Source_core_webcore_html_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_platform_gyp)/third_party_WebKit_Source_core_webcore_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_remaining_gyp)/third_party_WebKit_Source_core_webcore_remaining_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_rendering_gyp)/third_party_WebKit_Source_core_webcore_rendering_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_svg_gyp)/third_party_WebKit_Source_core_webcore_svg_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_derived_gyp)/third_party_WebKit_Source_core_webcore_derived_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_generated_gyp)/third_party_WebKit_Source_core_webcore_generated_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,GYP,third_party_npapi_npapi_gyp)/npapi.stamp \
diff --git a/Source/core/webcore.target.linux-arm.mk b/Source/core/webcore.target.linux-arm.mk
index ee62396..8dfb3b7 100644
--- a/Source/core/webcore.target.linux-arm.mk
+++ b/Source/core/webcore.target.linux-arm.mk
@@ -14,11 +14,10 @@
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_dom_gyp)/third_party_WebKit_Source_core_webcore_dom_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_html_gyp)/third_party_WebKit_Source_core_webcore_html_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_platform_gyp)/third_party_WebKit_Source_core_webcore_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_remaining_gyp)/third_party_WebKit_Source_core_webcore_remaining_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_rendering_gyp)/third_party_WebKit_Source_core_webcore_rendering_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_svg_gyp)/third_party_WebKit_Source_core_webcore_svg_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_derived_gyp)/third_party_WebKit_Source_core_webcore_derived_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_generated_gyp)/third_party_WebKit_Source_core_webcore_generated_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,GYP,third_party_npapi_npapi_gyp)/npapi.stamp \
diff --git a/Source/core/webcore.target.linux-mips.mk b/Source/core/webcore.target.linux-mips.mk
index ee62396..8dfb3b7 100644
--- a/Source/core/webcore.target.linux-mips.mk
+++ b/Source/core/webcore.target.linux-mips.mk
@@ -14,11 +14,10 @@
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_dom_gyp)/third_party_WebKit_Source_core_webcore_dom_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_html_gyp)/third_party_WebKit_Source_core_webcore_html_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_platform_gyp)/third_party_WebKit_Source_core_webcore_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_remaining_gyp)/third_party_WebKit_Source_core_webcore_remaining_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_rendering_gyp)/third_party_WebKit_Source_core_webcore_rendering_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_svg_gyp)/third_party_WebKit_Source_core_webcore_svg_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_derived_gyp)/third_party_WebKit_Source_core_webcore_derived_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_generated_gyp)/third_party_WebKit_Source_core_webcore_generated_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,GYP,third_party_npapi_npapi_gyp)/npapi.stamp \
diff --git a/Source/core/webcore.target.linux-x86.mk b/Source/core/webcore.target.linux-x86.mk
index ee62396..8dfb3b7 100644
--- a/Source/core/webcore.target.linux-x86.mk
+++ b/Source/core/webcore.target.linux-x86.mk
@@ -14,11 +14,10 @@
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_dom_gyp)/third_party_WebKit_Source_core_webcore_dom_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_html_gyp)/third_party_WebKit_Source_core_webcore_html_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_platform_gyp)/third_party_WebKit_Source_core_webcore_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_remaining_gyp)/third_party_WebKit_Source_core_webcore_remaining_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_rendering_gyp)/third_party_WebKit_Source_core_webcore_rendering_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_svg_gyp)/third_party_WebKit_Source_core_webcore_svg_gyp.a \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_derived_gyp)/third_party_WebKit_Source_core_webcore_derived_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_core_webcore_generated_gyp)/third_party_WebKit_Source_core_webcore_generated_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,GYP,third_party_npapi_npapi_gyp)/npapi.stamp \
diff --git a/Source/core/webcore_derived.target.linux-arm.mk b/Source/core/webcore_derived.target.linux-arm.mk
deleted file mode 100644
index 599d8e5..0000000
--- a/Source/core/webcore_derived.target.linux-arm.mk
+++ /dev/null
@@ -1,720 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_derived_gyp
-LOCAL_MODULE_SUFFIX := .a
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_canvas_script_source_gyp)/injected_canvas_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_script_source_gyp)/injected_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_debugger_script_source_gyp)/debugger_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_derived_sources_gyp)/make_platform_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a \
-	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
-	$(call intermediates-dir-for,GYP,third_party_npapi_npapi_gyp)/npapi.stamp \
-	$(call intermediates-dir-for,GYP,v8_tools_gyp_v8_gyp)/v8.stamp
-
-GYP_GENERATED_OUTPUTS :=
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-$(gyp_intermediate_dir)/V8DerivedSources01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources01.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources02.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources03.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources04.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources05.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources06.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources07.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources08.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources09.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources10.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources11.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources12.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources13.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources14.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources15.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources16.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources17.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources18.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSPropertyNames.cpp: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSValueKeywords.cpp: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/Event.cpp: $(gyp_shared_intermediate_dir)/blink/Event.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/EventNames.cpp: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/EventTargetNames.cpp: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/EventTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InputTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/SVGNames.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XLinkNames.cpp: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XMLNSNames.cpp: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSGrammar.cpp: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XPathGrammar.cpp: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorFrontend.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorFrontend.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorBackendDispatcher.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorBackendDispatcher.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorTypeBuilder.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorTypeBuilder.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorInstrumentationImpl.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationImpl.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/StylePropertyShorthand.cpp: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/StyleBuilder.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp
-	mkdir -p $(@D); cp $< $@
-LOCAL_GENERATED_SOURCES := \
-	$(gyp_intermediate_dir)/V8DerivedSources01.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources02.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources03.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources04.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources05.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources06.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources07.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources08.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources09.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources10.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources11.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources12.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources13.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources14.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources15.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources16.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
-	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
-	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
-	$(gyp_intermediate_dir)/Event.cpp \
-	$(gyp_intermediate_dir)/EventNames.cpp \
-	$(gyp_intermediate_dir)/EventTargetNames.cpp \
-	$(gyp_intermediate_dir)/EventTypeNames.cpp \
-	$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp \
-	$(gyp_intermediate_dir)/HTMLElementFactory.cpp \
-	$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp \
-	$(gyp_intermediate_dir)/HTMLNames.cpp \
-	$(gyp_intermediate_dir)/InputTypeNames.cpp \
-	$(gyp_intermediate_dir)/MathMLNames.cpp \
-	$(gyp_intermediate_dir)/SVGNames.cpp \
-	$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp \
-	$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp \
-	$(gyp_intermediate_dir)/XLinkNames.cpp \
-	$(gyp_intermediate_dir)/XMLNSNames.cpp \
-	$(gyp_intermediate_dir)/XMLNames.cpp \
-	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
-	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
-	$(gyp_intermediate_dir)/CSSParser.cpp \
-	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
-	$(gyp_intermediate_dir)/CSSGrammar.cpp \
-	$(gyp_intermediate_dir)/XPathGrammar.cpp \
-	$(gyp_intermediate_dir)/InspectorFrontend.cpp \
-	$(gyp_intermediate_dir)/InspectorBackendDispatcher.cpp \
-	$(gyp_intermediate_dir)/InspectorTypeBuilder.cpp \
-	$(gyp_intermediate_dir)/InspectorInstrumentationImpl.cpp \
-	$(gyp_intermediate_dir)/SVGElementFactory.cpp \
-	$(gyp_intermediate_dir)/V8SVGElementWrapperFactory.cpp \
-	$(gyp_intermediate_dir)/StylePropertyShorthand.cpp \
-	$(gyp_intermediate_dir)/StyleBuilder.cpp \
-	$(gyp_intermediate_dir)/StyleBuilderFunctions.cpp
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS := \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(gyp_shared_intermediate_dir)/blink
-
-LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/bindings/v8/ActiveDOMCallback.cpp \
-	third_party/WebKit/Source/bindings/v8/ArrayValue.cpp \
-	third_party/WebKit/Source/bindings/v8/BindingSecurity.cpp \
-	third_party/WebKit/Source/bindings/v8/CustomElementBinding.cpp \
-	third_party/WebKit/Source/bindings/v8/CustomElementConstructorBuilder.cpp \
-	third_party/WebKit/Source/bindings/v8/CustomElementWrapper.cpp \
-	third_party/WebKit/Source/bindings/v8/DOMDataStore.cpp \
-	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
-	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
-	third_party/WebKit/Source/bindings/v8/ExceptionMessages.cpp \
-	third_party/WebKit/Source/bindings/v8/ExceptionState.cpp \
-	third_party/WebKit/Source/bindings/v8/ExceptionStatePlaceholder.cpp \
-	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
-	third_party/WebKit/Source/bindings/v8/NPV8Object.cpp \
-	third_party/WebKit/Source/bindings/v8/PageScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/RetainedDOMInfo.cpp \
-	third_party/WebKit/Source/bindings/v8/ScheduledAction.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptCallStackFactory.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptController.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptFunctionCall.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptGCEvent.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptHeapSnapshot.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptObject.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptPreprocessor.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptProfiler.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptPromise.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptPromiseResolver.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptRegexp.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptScope.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptState.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptString.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptValue.cpp \
-	third_party/WebKit/Source/bindings/v8/SerializedScriptValue.cpp \
-	third_party/WebKit/Source/bindings/v8/V8AbstractEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Binding.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Callback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8CustomElementLifecycleCallbacks.cpp \
-	third_party/WebKit/Source/bindings/v8/V8DOMConfiguration.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ErrorHandler.cpp \
-	third_party/WebKit/Source/bindings/v8/V8DOMWrapper.cpp \
-	third_party/WebKit/Source/bindings/v8/V8EventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/V8EventListenerList.cpp \
-	third_party/WebKit/Source/bindings/v8/V8GCController.cpp \
-	third_party/WebKit/Source/bindings/v8/V8GCForContextDispose.cpp \
-	third_party/WebKit/Source/bindings/v8/V8HiddenPropertyName.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Initializer.cpp \
-	third_party/WebKit/Source/bindings/v8/V8LazyEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/V8MutationCallback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8NPObject.cpp \
-	third_party/WebKit/Source/bindings/v8/V8NPUtils.cpp \
-	third_party/WebKit/Source/bindings/v8/V8NodeFilterCondition.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ObjectConstructor.cpp \
-	third_party/WebKit/Source/bindings/v8/V8PerContextData.cpp \
-	third_party/WebKit/Source/bindings/v8/V8PerIsolateData.cpp \
-	third_party/WebKit/Source/bindings/v8/V8RecursionScope.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ScriptRunner.cpp \
-	third_party/WebKit/Source/bindings/v8/V8StringResource.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ThrowException.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Utilities.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ValueCache.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WindowShell.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
-	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8BiquadFilterNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustomHelpers.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CSSRuleCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CSSStyleDeclarationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CSSValueCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CanvasRenderingContext2DCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CanvasRenderingContextCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CryptoCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CustomEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CustomSQLStatementErrorCallback.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CustomXPathNSResolver.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DataViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerGlobalScopeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EntryCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EntrySyncCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EventTargetCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ErrorEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8FileCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8FileReaderCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8FormDataCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8GeolocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLAllCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCanvasElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLDocumentCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HistoryCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ImageDataCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8InjectedScriptHostCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8InjectedScriptManager.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MutationObserverCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeListCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8OscillatorNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PopStateEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PromiseCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SQLResultSetRowListCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGLengthCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8TextTrackCueCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8TrackEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WindowCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerGlobalScopeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCryptoCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8XMLHttpRequestCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8XSLTProcessorCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/npruntime.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-fno-tree-sra \
-	-fuse-ld=gold \
-	-Wno-psabi \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-fno-tree-sra \
-	-fuse-ld=gold \
-	-Wno-psabi \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-
-LOCAL_LDFLAGS_Debug := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-Wl,-z,relro \
-	-Wl,-z,now \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--icf=safe \
-	-Wl,--fatal-warnings \
-	-Wl,--gc-sections \
-	-Wl,--warn-shared-textrel \
-	-Wl,-O1 \
-	-Wl,--as-needed
-
-
-LOCAL_LDFLAGS_Release := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-Wl,-z,relro \
-	-Wl,-z,now \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--icf=safe \
-	-Wl,-O1 \
-	-Wl,--as-needed \
-	-Wl,--gc-sections \
-	-Wl,--fatal-warnings \
-	-Wl,--warn-shared-textrel
-
-
-LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
-
-LOCAL_STATIC_LIBRARIES := \
-	skia_skia_library_gyp
-
-# Enable grouping to fix circular references
-LOCAL_GROUP_STATIC_LIBRARIES := true
-
-LOCAL_SHARED_LIBRARIES := \
-	libstlport \
-	libdl
-
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_derived_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_derived
-webcore_derived: third_party_WebKit_Source_core_webcore_derived_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_derived.target.linux-mips.mk b/Source/core/webcore_derived.target.linux-mips.mk
deleted file mode 100644
index 37e4ee3..0000000
--- a/Source/core/webcore_derived.target.linux-mips.mk
+++ /dev/null
@@ -1,714 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_derived_gyp
-LOCAL_MODULE_SUFFIX := .a
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_canvas_script_source_gyp)/injected_canvas_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_script_source_gyp)/injected_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_debugger_script_source_gyp)/debugger_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_derived_sources_gyp)/make_platform_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a \
-	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
-	$(call intermediates-dir-for,GYP,third_party_npapi_npapi_gyp)/npapi.stamp \
-	$(call intermediates-dir-for,GYP,v8_tools_gyp_v8_gyp)/v8.stamp
-
-GYP_GENERATED_OUTPUTS :=
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-$(gyp_intermediate_dir)/V8DerivedSources01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources01.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources02.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources03.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources04.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources05.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources06.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources07.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources08.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources09.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources10.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources11.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources12.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources13.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources14.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources15.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources16.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources17.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources18.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSPropertyNames.cpp: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSValueKeywords.cpp: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/Event.cpp: $(gyp_shared_intermediate_dir)/blink/Event.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/EventNames.cpp: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/EventTargetNames.cpp: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/EventTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InputTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/SVGNames.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XLinkNames.cpp: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XMLNSNames.cpp: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSGrammar.cpp: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XPathGrammar.cpp: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorFrontend.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorFrontend.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorBackendDispatcher.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorBackendDispatcher.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorTypeBuilder.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorTypeBuilder.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorInstrumentationImpl.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationImpl.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/StylePropertyShorthand.cpp: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/StyleBuilder.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp
-	mkdir -p $(@D); cp $< $@
-LOCAL_GENERATED_SOURCES := \
-	$(gyp_intermediate_dir)/V8DerivedSources01.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources02.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources03.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources04.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources05.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources06.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources07.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources08.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources09.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources10.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources11.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources12.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources13.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources14.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources15.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources16.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
-	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
-	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
-	$(gyp_intermediate_dir)/Event.cpp \
-	$(gyp_intermediate_dir)/EventNames.cpp \
-	$(gyp_intermediate_dir)/EventTargetNames.cpp \
-	$(gyp_intermediate_dir)/EventTypeNames.cpp \
-	$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp \
-	$(gyp_intermediate_dir)/HTMLElementFactory.cpp \
-	$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp \
-	$(gyp_intermediate_dir)/HTMLNames.cpp \
-	$(gyp_intermediate_dir)/InputTypeNames.cpp \
-	$(gyp_intermediate_dir)/MathMLNames.cpp \
-	$(gyp_intermediate_dir)/SVGNames.cpp \
-	$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp \
-	$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp \
-	$(gyp_intermediate_dir)/XLinkNames.cpp \
-	$(gyp_intermediate_dir)/XMLNSNames.cpp \
-	$(gyp_intermediate_dir)/XMLNames.cpp \
-	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
-	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
-	$(gyp_intermediate_dir)/CSSParser.cpp \
-	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
-	$(gyp_intermediate_dir)/CSSGrammar.cpp \
-	$(gyp_intermediate_dir)/XPathGrammar.cpp \
-	$(gyp_intermediate_dir)/InspectorFrontend.cpp \
-	$(gyp_intermediate_dir)/InspectorBackendDispatcher.cpp \
-	$(gyp_intermediate_dir)/InspectorTypeBuilder.cpp \
-	$(gyp_intermediate_dir)/InspectorInstrumentationImpl.cpp \
-	$(gyp_intermediate_dir)/SVGElementFactory.cpp \
-	$(gyp_intermediate_dir)/V8SVGElementWrapperFactory.cpp \
-	$(gyp_intermediate_dir)/StylePropertyShorthand.cpp \
-	$(gyp_intermediate_dir)/StyleBuilder.cpp \
-	$(gyp_intermediate_dir)/StyleBuilderFunctions.cpp
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS := \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(gyp_shared_intermediate_dir)/blink
-
-LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/bindings/v8/ActiveDOMCallback.cpp \
-	third_party/WebKit/Source/bindings/v8/ArrayValue.cpp \
-	third_party/WebKit/Source/bindings/v8/BindingSecurity.cpp \
-	third_party/WebKit/Source/bindings/v8/CustomElementBinding.cpp \
-	third_party/WebKit/Source/bindings/v8/CustomElementConstructorBuilder.cpp \
-	third_party/WebKit/Source/bindings/v8/CustomElementWrapper.cpp \
-	third_party/WebKit/Source/bindings/v8/DOMDataStore.cpp \
-	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
-	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
-	third_party/WebKit/Source/bindings/v8/ExceptionMessages.cpp \
-	third_party/WebKit/Source/bindings/v8/ExceptionState.cpp \
-	third_party/WebKit/Source/bindings/v8/ExceptionStatePlaceholder.cpp \
-	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
-	third_party/WebKit/Source/bindings/v8/NPV8Object.cpp \
-	third_party/WebKit/Source/bindings/v8/PageScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/RetainedDOMInfo.cpp \
-	third_party/WebKit/Source/bindings/v8/ScheduledAction.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptCallStackFactory.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptController.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptFunctionCall.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptGCEvent.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptHeapSnapshot.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptObject.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptPreprocessor.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptProfiler.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptPromise.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptPromiseResolver.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptRegexp.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptScope.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptState.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptString.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptValue.cpp \
-	third_party/WebKit/Source/bindings/v8/SerializedScriptValue.cpp \
-	third_party/WebKit/Source/bindings/v8/V8AbstractEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Binding.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Callback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8CustomElementLifecycleCallbacks.cpp \
-	third_party/WebKit/Source/bindings/v8/V8DOMConfiguration.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ErrorHandler.cpp \
-	third_party/WebKit/Source/bindings/v8/V8DOMWrapper.cpp \
-	third_party/WebKit/Source/bindings/v8/V8EventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/V8EventListenerList.cpp \
-	third_party/WebKit/Source/bindings/v8/V8GCController.cpp \
-	third_party/WebKit/Source/bindings/v8/V8GCForContextDispose.cpp \
-	third_party/WebKit/Source/bindings/v8/V8HiddenPropertyName.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Initializer.cpp \
-	third_party/WebKit/Source/bindings/v8/V8LazyEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/V8MutationCallback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8NPObject.cpp \
-	third_party/WebKit/Source/bindings/v8/V8NPUtils.cpp \
-	third_party/WebKit/Source/bindings/v8/V8NodeFilterCondition.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ObjectConstructor.cpp \
-	third_party/WebKit/Source/bindings/v8/V8PerContextData.cpp \
-	third_party/WebKit/Source/bindings/v8/V8PerIsolateData.cpp \
-	third_party/WebKit/Source/bindings/v8/V8RecursionScope.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ScriptRunner.cpp \
-	third_party/WebKit/Source/bindings/v8/V8StringResource.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ThrowException.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Utilities.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ValueCache.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WindowShell.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
-	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8BiquadFilterNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustomHelpers.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CSSRuleCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CSSStyleDeclarationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CSSValueCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CanvasRenderingContext2DCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CanvasRenderingContextCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CryptoCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CustomEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CustomSQLStatementErrorCallback.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CustomXPathNSResolver.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DataViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerGlobalScopeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EntryCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EntrySyncCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EventTargetCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ErrorEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8FileCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8FileReaderCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8FormDataCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8GeolocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLAllCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCanvasElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLDocumentCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HistoryCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ImageDataCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8InjectedScriptHostCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8InjectedScriptManager.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MutationObserverCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeListCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8OscillatorNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PopStateEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PromiseCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SQLResultSetRowListCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGLengthCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8TextTrackCueCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8TrackEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WindowCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerGlobalScopeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCryptoCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8XMLHttpRequestCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8XSLTProcessorCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/npruntime.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-EL \
-	-mhard-float \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-EL \
-	-mhard-float \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-
-LOCAL_LDFLAGS_Debug := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-EL \
-	-Wl,--no-keep-memory \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--fatal-warnings \
-	-Wl,--gc-sections \
-	-Wl,--warn-shared-textrel \
-	-Wl,-O1 \
-	-Wl,--as-needed
-
-
-LOCAL_LDFLAGS_Release := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-EL \
-	-Wl,--no-keep-memory \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,-O1 \
-	-Wl,--as-needed \
-	-Wl,--gc-sections \
-	-Wl,--fatal-warnings \
-	-Wl,--warn-shared-textrel
-
-
-LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
-
-LOCAL_STATIC_LIBRARIES := \
-	skia_skia_library_gyp
-
-# Enable grouping to fix circular references
-LOCAL_GROUP_STATIC_LIBRARIES := true
-
-LOCAL_SHARED_LIBRARIES := \
-	libstlport \
-	libdl
-
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_derived_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_derived
-webcore_derived: third_party_WebKit_Source_core_webcore_derived_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_derived.target.linux-x86.mk b/Source/core/webcore_derived.target.linux-x86.mk
deleted file mode 100644
index ae875d2..0000000
--- a/Source/core/webcore_derived.target.linux-x86.mk
+++ /dev/null
@@ -1,720 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_derived_gyp
-LOCAL_MODULE_SUFFIX := .a
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_canvas_script_source_gyp)/injected_canvas_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_script_source_gyp)/injected_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_debugger_script_source_gyp)/debugger_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_derived_sources_gyp)/make_platform_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a \
-	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
-	$(call intermediates-dir-for,GYP,third_party_npapi_npapi_gyp)/npapi.stamp \
-	$(call intermediates-dir-for,GYP,v8_tools_gyp_v8_gyp)/v8.stamp
-
-GYP_GENERATED_OUTPUTS :=
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-$(gyp_intermediate_dir)/V8DerivedSources01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources01.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources02.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources03.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources04.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources05.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources06.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources07.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources08.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources09.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources10.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources11.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources12.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources13.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources14.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources15.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources16.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources17.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources18.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSPropertyNames.cpp: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSValueKeywords.cpp: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/Event.cpp: $(gyp_shared_intermediate_dir)/blink/Event.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/EventNames.cpp: $(gyp_shared_intermediate_dir)/blink/EventNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/EventTargetNames.cpp: $(gyp_shared_intermediate_dir)/blink/EventTargetNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/EventTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/EventTypeNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/FetchInitiatorTypeNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLElementLookupTrie.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InputTypeNames.cpp: $(gyp_shared_intermediate_dir)/blink/InputTypeNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/SVGNames.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XLinkNames.cpp: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XMLNSNames.cpp: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XMLNames.cpp: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLEntityTable.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLEntityTable.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSGrammar.cpp: $(gyp_shared_intermediate_dir)/blink/CSSGrammar.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/XPathGrammar.cpp: $(gyp_shared_intermediate_dir)/blink/XPathGrammar.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorFrontend.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorFrontend.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorBackendDispatcher.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorBackendDispatcher.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorTypeBuilder.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorTypeBuilder.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/InspectorInstrumentationImpl.cpp: $(gyp_shared_intermediate_dir)/blink/InspectorInstrumentationImpl.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8SVGElementWrapperFactory.cpp: $(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/StylePropertyShorthand.cpp: $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/StyleBuilder.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp
-	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp
-	mkdir -p $(@D); cp $< $@
-LOCAL_GENERATED_SOURCES := \
-	$(gyp_intermediate_dir)/V8DerivedSources01.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources02.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources03.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources04.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources05.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources06.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources07.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources08.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources09.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources10.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources11.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources12.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources13.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources14.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources15.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources16.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
-	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
-	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
-	$(gyp_intermediate_dir)/Event.cpp \
-	$(gyp_intermediate_dir)/EventNames.cpp \
-	$(gyp_intermediate_dir)/EventTargetNames.cpp \
-	$(gyp_intermediate_dir)/EventTypeNames.cpp \
-	$(gyp_intermediate_dir)/FetchInitiatorTypeNames.cpp \
-	$(gyp_intermediate_dir)/HTMLElementFactory.cpp \
-	$(gyp_intermediate_dir)/HTMLElementLookupTrie.cpp \
-	$(gyp_intermediate_dir)/HTMLNames.cpp \
-	$(gyp_intermediate_dir)/InputTypeNames.cpp \
-	$(gyp_intermediate_dir)/MathMLNames.cpp \
-	$(gyp_intermediate_dir)/SVGNames.cpp \
-	$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp \
-	$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp \
-	$(gyp_intermediate_dir)/XLinkNames.cpp \
-	$(gyp_intermediate_dir)/XMLNSNames.cpp \
-	$(gyp_intermediate_dir)/XMLNames.cpp \
-	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
-	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
-	$(gyp_intermediate_dir)/CSSParser.cpp \
-	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
-	$(gyp_intermediate_dir)/CSSGrammar.cpp \
-	$(gyp_intermediate_dir)/XPathGrammar.cpp \
-	$(gyp_intermediate_dir)/InspectorFrontend.cpp \
-	$(gyp_intermediate_dir)/InspectorBackendDispatcher.cpp \
-	$(gyp_intermediate_dir)/InspectorTypeBuilder.cpp \
-	$(gyp_intermediate_dir)/InspectorInstrumentationImpl.cpp \
-	$(gyp_intermediate_dir)/SVGElementFactory.cpp \
-	$(gyp_intermediate_dir)/V8SVGElementWrapperFactory.cpp \
-	$(gyp_intermediate_dir)/StylePropertyShorthand.cpp \
-	$(gyp_intermediate_dir)/StyleBuilder.cpp \
-	$(gyp_intermediate_dir)/StyleBuilderFunctions.cpp
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS := \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(gyp_shared_intermediate_dir)/blink
-
-LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/bindings/v8/ActiveDOMCallback.cpp \
-	third_party/WebKit/Source/bindings/v8/ArrayValue.cpp \
-	third_party/WebKit/Source/bindings/v8/BindingSecurity.cpp \
-	third_party/WebKit/Source/bindings/v8/CustomElementBinding.cpp \
-	third_party/WebKit/Source/bindings/v8/CustomElementConstructorBuilder.cpp \
-	third_party/WebKit/Source/bindings/v8/CustomElementWrapper.cpp \
-	third_party/WebKit/Source/bindings/v8/DOMDataStore.cpp \
-	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
-	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
-	third_party/WebKit/Source/bindings/v8/ExceptionMessages.cpp \
-	third_party/WebKit/Source/bindings/v8/ExceptionState.cpp \
-	third_party/WebKit/Source/bindings/v8/ExceptionStatePlaceholder.cpp \
-	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
-	third_party/WebKit/Source/bindings/v8/NPV8Object.cpp \
-	third_party/WebKit/Source/bindings/v8/PageScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/RetainedDOMInfo.cpp \
-	third_party/WebKit/Source/bindings/v8/ScheduledAction.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptCallStackFactory.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptController.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptFunctionCall.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptGCEvent.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptHeapSnapshot.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptObject.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptPreprocessor.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptProfiler.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptPromise.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptPromiseResolver.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptRegexp.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptScope.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptState.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptString.cpp \
-	third_party/WebKit/Source/bindings/v8/ScriptValue.cpp \
-	third_party/WebKit/Source/bindings/v8/SerializedScriptValue.cpp \
-	third_party/WebKit/Source/bindings/v8/V8AbstractEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Binding.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Callback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8CustomElementLifecycleCallbacks.cpp \
-	third_party/WebKit/Source/bindings/v8/V8DOMConfiguration.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ErrorHandler.cpp \
-	third_party/WebKit/Source/bindings/v8/V8DOMWrapper.cpp \
-	third_party/WebKit/Source/bindings/v8/V8EventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/V8EventListenerList.cpp \
-	third_party/WebKit/Source/bindings/v8/V8GCController.cpp \
-	third_party/WebKit/Source/bindings/v8/V8GCForContextDispose.cpp \
-	third_party/WebKit/Source/bindings/v8/V8HiddenPropertyName.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Initializer.cpp \
-	third_party/WebKit/Source/bindings/v8/V8LazyEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/V8MutationCallback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8NPObject.cpp \
-	third_party/WebKit/Source/bindings/v8/V8NPUtils.cpp \
-	third_party/WebKit/Source/bindings/v8/V8NodeFilterCondition.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ObjectConstructor.cpp \
-	third_party/WebKit/Source/bindings/v8/V8PerContextData.cpp \
-	third_party/WebKit/Source/bindings/v8/V8PerIsolateData.cpp \
-	third_party/WebKit/Source/bindings/v8/V8RecursionScope.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ScriptRunner.cpp \
-	third_party/WebKit/Source/bindings/v8/V8StringResource.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ThrowException.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Utilities.cpp \
-	third_party/WebKit/Source/bindings/v8/V8ValueCache.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WindowShell.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
-	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
-	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8BiquadFilterNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8BlobCustomHelpers.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CSSRuleCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CSSStyleDeclarationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CSSValueCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CanvasRenderingContext2DCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CanvasRenderingContextCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CryptoCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CustomEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CustomSQLStatementErrorCallback.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8CustomXPathNSResolver.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DataViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerGlobalScopeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EntryCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EntrySyncCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8EventTargetCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ErrorEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8FileCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8FileReaderCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8FormDataCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8GeolocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLAllCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCanvasElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLDocumentCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HistoryCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8ImageDataCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8InjectedScriptHostCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8InjectedScriptManager.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MutationObserverCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeListCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8OscillatorNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PopStateEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8PromiseCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SQLResultSetRowListCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGLengthCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8TextTrackCueCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8TrackEventCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WindowCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerGlobalScopeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCryptoCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8XMLHttpRequestCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8XSLTProcessorCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/npruntime.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-m32 \
-	-mmmx \
-	-march=pentium4 \
-	-msse2 \
-	-mfpmath=sse \
-	-fuse-ld=gold \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-fno-stack-protector \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-m32 \
-	-mmmx \
-	-march=pentium4 \
-	-msse2 \
-	-mfpmath=sse \
-	-fuse-ld=gold \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-fno-stack-protector \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
-	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-
-LOCAL_LDFLAGS_Debug := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-m32 \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--fatal-warnings \
-	-Wl,--gc-sections \
-	-Wl,--warn-shared-textrel \
-	-Wl,-O1 \
-	-Wl,--as-needed
-
-
-LOCAL_LDFLAGS_Release := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-m32 \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,-O1 \
-	-Wl,--as-needed \
-	-Wl,--gc-sections \
-	-Wl,--fatal-warnings \
-	-Wl,--warn-shared-textrel
-
-
-LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
-
-LOCAL_STATIC_LIBRARIES := \
-	skia_skia_library_gyp
-
-# Enable grouping to fix circular references
-LOCAL_GROUP_STATIC_LIBRARIES := true
-
-LOCAL_SHARED_LIBRARIES := \
-	libstlport \
-	libdl
-
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_derived_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_derived
-webcore_derived: third_party_WebKit_Source_core_webcore_derived_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_dom.target.darwin-arm.mk b/Source/core/webcore_dom.target.darwin-arm.mk
index 921bc41..992b695 100644
--- a/Source/core/webcore_dom.target.darwin-arm.mk
+++ b/Source/core/webcore_dom.target.darwin-arm.mk
@@ -32,10 +32,9 @@
 	third_party/WebKit/Source/core/dom/CharacterData.cpp \
 	third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp \
 	third_party/WebKit/Source/core/dom/ChildNodeList.cpp \
-	third_party/WebKit/Source/core/dom/ClassNodeList.cpp \
+	third_party/WebKit/Source/core/dom/ClassCollection.cpp \
 	third_party/WebKit/Source/core/dom/ClientRect.cpp \
 	third_party/WebKit/Source/core/dom/ClientRectList.cpp \
-	third_party/WebKit/Source/core/dom/Clipboard.cpp \
 	third_party/WebKit/Source/core/dom/Comment.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
@@ -43,10 +42,9 @@
 	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItemList.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/Document.cpp \
+	third_party/WebKit/Source/core/dom/DocumentEncodingData.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFragment.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFullscreen.cpp \
 	third_party/WebKit/Source/core/dom/DocumentInit.cpp \
@@ -58,13 +56,12 @@
 	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
-	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
 	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp \
+	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollector.cpp \
 	third_party/WebKit/Source/core/dom/DocumentType.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
 	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
-	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
@@ -74,7 +71,9 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp \
 	third_party/WebKit/Source/core/dom/Element.cpp \
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
+	third_party/WebKit/Source/core/dom/ElementDataCache.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
+	third_party/WebKit/Source/core/dom/EmptyNodeList.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -89,8 +88,6 @@
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverRegistration.cpp \
 	third_party/WebKit/Source/core/dom/MutationRecord.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlow.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodeMap.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodesCollection.cpp \
 	third_party/WebKit/Source/core/dom/NameNodeList.cpp \
@@ -99,9 +96,8 @@
 	third_party/WebKit/Source/core/dom/NodeFilter.cpp \
 	third_party/WebKit/Source/core/dom/NodeFilterCondition.cpp \
 	third_party/WebKit/Source/core/dom/NodeIterator.cpp \
-	third_party/WebKit/Source/core/dom/NodeList.cpp \
 	third_party/WebKit/Source/core/dom/NodeRareData.cpp \
-	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
+	third_party/WebKit/Source/core/dom/RenderTreeBuilder.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -121,17 +117,21 @@
 	third_party/WebKit/Source/core/dom/ScriptRunner.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/XMLDocument.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElement.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskDispatcher.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskImportStep.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskQueue.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
@@ -145,10 +145,10 @@
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
+	third_party/WebKit/Source/core/dom/StyleSheetCandidate.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
-	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
-	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
+	third_party/WebKit/Source/core/dom/TagCollection.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
@@ -157,6 +157,7 @@
 	third_party/WebKit/Source/core/dom/Traversal.cpp \
 	third_party/WebKit/Source/core/dom/TreeScope.cpp \
 	third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp \
+	third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/TreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/UserActionElementSet.cpp \
 	third_party/WebKit/Source/core/dom/ViewportDescription.cpp \
@@ -170,12 +171,10 @@
 	third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp \
 	third_party/WebKit/Source/core/events/ErrorEvent.cpp \
 	third_party/WebKit/Source/core/events/Event.cpp \
-	third_party/WebKit/Source/core/events/EventContext.cpp \
 	third_party/WebKit/Source/core/events/EventDispatcher.cpp \
 	third_party/WebKit/Source/core/events/EventDispatchMediator.cpp \
 	third_party/WebKit/Source/core/events/EventListenerMap.cpp \
 	third_party/WebKit/Source/core/events/EventPath.cpp \
-	third_party/WebKit/Source/core/events/EventRetargeter.cpp \
 	third_party/WebKit/Source/core/events/EventTarget.cpp \
 	third_party/WebKit/Source/core/events/FocusEvent.cpp \
 	third_party/WebKit/Source/core/events/GenericEventQueue.cpp \
@@ -186,6 +185,7 @@
 	third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/events/MutationEvent.cpp \
 	third_party/WebKit/Source/core/events/NavigatorEvents.cpp \
+	third_party/WebKit/Source/core/events/NodeEventContext.cpp \
 	third_party/WebKit/Source/core/events/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/events/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/events/PopStateEvent.cpp \
@@ -194,7 +194,9 @@
 	third_party/WebKit/Source/core/events/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/events/TextEvent.cpp \
 	third_party/WebKit/Source/core/events/TouchEvent.cpp \
+	third_party/WebKit/Source/core/events/TouchEventContext.cpp \
 	third_party/WebKit/Source/core/events/TransitionEvent.cpp \
+	third_party/WebKit/Source/core/events/TreeScopeEventContext.cpp \
 	third_party/WebKit/Source/core/events/UIEvent.cpp \
 	third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp \
 	third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp \
@@ -229,14 +231,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -247,7 +250,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -256,17 +258,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -274,13 +273,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -308,7 +309,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -348,7 +349,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -380,14 +380,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -398,7 +399,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -407,17 +407,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -425,13 +422,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -460,7 +459,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -500,7 +499,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_dom.target.darwin-mips.mk b/Source/core/webcore_dom.target.darwin-mips.mk
index b943ef2..3eeb867 100644
--- a/Source/core/webcore_dom.target.darwin-mips.mk
+++ b/Source/core/webcore_dom.target.darwin-mips.mk
@@ -32,10 +32,9 @@
 	third_party/WebKit/Source/core/dom/CharacterData.cpp \
 	third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp \
 	third_party/WebKit/Source/core/dom/ChildNodeList.cpp \
-	third_party/WebKit/Source/core/dom/ClassNodeList.cpp \
+	third_party/WebKit/Source/core/dom/ClassCollection.cpp \
 	third_party/WebKit/Source/core/dom/ClientRect.cpp \
 	third_party/WebKit/Source/core/dom/ClientRectList.cpp \
-	third_party/WebKit/Source/core/dom/Clipboard.cpp \
 	third_party/WebKit/Source/core/dom/Comment.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
@@ -43,10 +42,9 @@
 	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItemList.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/Document.cpp \
+	third_party/WebKit/Source/core/dom/DocumentEncodingData.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFragment.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFullscreen.cpp \
 	third_party/WebKit/Source/core/dom/DocumentInit.cpp \
@@ -58,13 +56,12 @@
 	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
-	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
 	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp \
+	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollector.cpp \
 	third_party/WebKit/Source/core/dom/DocumentType.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
 	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
-	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
@@ -74,7 +71,9 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp \
 	third_party/WebKit/Source/core/dom/Element.cpp \
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
+	third_party/WebKit/Source/core/dom/ElementDataCache.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
+	third_party/WebKit/Source/core/dom/EmptyNodeList.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -89,8 +88,6 @@
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverRegistration.cpp \
 	third_party/WebKit/Source/core/dom/MutationRecord.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlow.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodeMap.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodesCollection.cpp \
 	third_party/WebKit/Source/core/dom/NameNodeList.cpp \
@@ -99,9 +96,8 @@
 	third_party/WebKit/Source/core/dom/NodeFilter.cpp \
 	third_party/WebKit/Source/core/dom/NodeFilterCondition.cpp \
 	third_party/WebKit/Source/core/dom/NodeIterator.cpp \
-	third_party/WebKit/Source/core/dom/NodeList.cpp \
 	third_party/WebKit/Source/core/dom/NodeRareData.cpp \
-	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
+	third_party/WebKit/Source/core/dom/RenderTreeBuilder.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -121,17 +117,21 @@
 	third_party/WebKit/Source/core/dom/ScriptRunner.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/XMLDocument.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElement.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskDispatcher.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskImportStep.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskQueue.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
@@ -145,10 +145,10 @@
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
+	third_party/WebKit/Source/core/dom/StyleSheetCandidate.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
-	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
-	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
+	third_party/WebKit/Source/core/dom/TagCollection.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
@@ -157,6 +157,7 @@
 	third_party/WebKit/Source/core/dom/Traversal.cpp \
 	third_party/WebKit/Source/core/dom/TreeScope.cpp \
 	third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp \
+	third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/TreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/UserActionElementSet.cpp \
 	third_party/WebKit/Source/core/dom/ViewportDescription.cpp \
@@ -170,12 +171,10 @@
 	third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp \
 	third_party/WebKit/Source/core/events/ErrorEvent.cpp \
 	third_party/WebKit/Source/core/events/Event.cpp \
-	third_party/WebKit/Source/core/events/EventContext.cpp \
 	third_party/WebKit/Source/core/events/EventDispatcher.cpp \
 	third_party/WebKit/Source/core/events/EventDispatchMediator.cpp \
 	third_party/WebKit/Source/core/events/EventListenerMap.cpp \
 	third_party/WebKit/Source/core/events/EventPath.cpp \
-	third_party/WebKit/Source/core/events/EventRetargeter.cpp \
 	third_party/WebKit/Source/core/events/EventTarget.cpp \
 	third_party/WebKit/Source/core/events/FocusEvent.cpp \
 	third_party/WebKit/Source/core/events/GenericEventQueue.cpp \
@@ -186,6 +185,7 @@
 	third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/events/MutationEvent.cpp \
 	third_party/WebKit/Source/core/events/NavigatorEvents.cpp \
+	third_party/WebKit/Source/core/events/NodeEventContext.cpp \
 	third_party/WebKit/Source/core/events/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/events/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/events/PopStateEvent.cpp \
@@ -194,7 +194,9 @@
 	third_party/WebKit/Source/core/events/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/events/TextEvent.cpp \
 	third_party/WebKit/Source/core/events/TouchEvent.cpp \
+	third_party/WebKit/Source/core/events/TouchEventContext.cpp \
 	third_party/WebKit/Source/core/events/TransitionEvent.cpp \
+	third_party/WebKit/Source/core/events/TreeScopeEventContext.cpp \
 	third_party/WebKit/Source/core/events/UIEvent.cpp \
 	third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp \
 	third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp \
@@ -228,14 +230,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -246,7 +249,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -255,17 +257,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -273,13 +272,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -307,7 +308,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -347,7 +348,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -378,14 +378,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -396,7 +397,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -405,17 +405,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -423,13 +420,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -458,7 +457,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -498,7 +497,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_dom.target.darwin-x86.mk b/Source/core/webcore_dom.target.darwin-x86.mk
index 7ba6967..78f67d4 100644
--- a/Source/core/webcore_dom.target.darwin-x86.mk
+++ b/Source/core/webcore_dom.target.darwin-x86.mk
@@ -32,10 +32,9 @@
 	third_party/WebKit/Source/core/dom/CharacterData.cpp \
 	third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp \
 	third_party/WebKit/Source/core/dom/ChildNodeList.cpp \
-	third_party/WebKit/Source/core/dom/ClassNodeList.cpp \
+	third_party/WebKit/Source/core/dom/ClassCollection.cpp \
 	third_party/WebKit/Source/core/dom/ClientRect.cpp \
 	third_party/WebKit/Source/core/dom/ClientRectList.cpp \
-	third_party/WebKit/Source/core/dom/Clipboard.cpp \
 	third_party/WebKit/Source/core/dom/Comment.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
@@ -43,10 +42,9 @@
 	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItemList.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/Document.cpp \
+	third_party/WebKit/Source/core/dom/DocumentEncodingData.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFragment.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFullscreen.cpp \
 	third_party/WebKit/Source/core/dom/DocumentInit.cpp \
@@ -58,13 +56,12 @@
 	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
-	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
 	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp \
+	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollector.cpp \
 	third_party/WebKit/Source/core/dom/DocumentType.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
 	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
-	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
@@ -74,7 +71,9 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp \
 	third_party/WebKit/Source/core/dom/Element.cpp \
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
+	third_party/WebKit/Source/core/dom/ElementDataCache.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
+	third_party/WebKit/Source/core/dom/EmptyNodeList.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -89,8 +88,6 @@
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverRegistration.cpp \
 	third_party/WebKit/Source/core/dom/MutationRecord.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlow.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodeMap.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodesCollection.cpp \
 	third_party/WebKit/Source/core/dom/NameNodeList.cpp \
@@ -99,9 +96,8 @@
 	third_party/WebKit/Source/core/dom/NodeFilter.cpp \
 	third_party/WebKit/Source/core/dom/NodeFilterCondition.cpp \
 	third_party/WebKit/Source/core/dom/NodeIterator.cpp \
-	third_party/WebKit/Source/core/dom/NodeList.cpp \
 	third_party/WebKit/Source/core/dom/NodeRareData.cpp \
-	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
+	third_party/WebKit/Source/core/dom/RenderTreeBuilder.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -121,17 +117,21 @@
 	third_party/WebKit/Source/core/dom/ScriptRunner.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/XMLDocument.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElement.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskDispatcher.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskImportStep.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskQueue.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
@@ -145,10 +145,10 @@
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
+	third_party/WebKit/Source/core/dom/StyleSheetCandidate.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
-	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
-	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
+	third_party/WebKit/Source/core/dom/TagCollection.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
@@ -157,6 +157,7 @@
 	third_party/WebKit/Source/core/dom/Traversal.cpp \
 	third_party/WebKit/Source/core/dom/TreeScope.cpp \
 	third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp \
+	third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/TreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/UserActionElementSet.cpp \
 	third_party/WebKit/Source/core/dom/ViewportDescription.cpp \
@@ -170,12 +171,10 @@
 	third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp \
 	third_party/WebKit/Source/core/events/ErrorEvent.cpp \
 	third_party/WebKit/Source/core/events/Event.cpp \
-	third_party/WebKit/Source/core/events/EventContext.cpp \
 	third_party/WebKit/Source/core/events/EventDispatcher.cpp \
 	third_party/WebKit/Source/core/events/EventDispatchMediator.cpp \
 	third_party/WebKit/Source/core/events/EventListenerMap.cpp \
 	third_party/WebKit/Source/core/events/EventPath.cpp \
-	third_party/WebKit/Source/core/events/EventRetargeter.cpp \
 	third_party/WebKit/Source/core/events/EventTarget.cpp \
 	third_party/WebKit/Source/core/events/FocusEvent.cpp \
 	third_party/WebKit/Source/core/events/GenericEventQueue.cpp \
@@ -186,6 +185,7 @@
 	third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/events/MutationEvent.cpp \
 	third_party/WebKit/Source/core/events/NavigatorEvents.cpp \
+	third_party/WebKit/Source/core/events/NodeEventContext.cpp \
 	third_party/WebKit/Source/core/events/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/events/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/events/PopStateEvent.cpp \
@@ -194,7 +194,9 @@
 	third_party/WebKit/Source/core/events/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/events/TextEvent.cpp \
 	third_party/WebKit/Source/core/events/TouchEvent.cpp \
+	third_party/WebKit/Source/core/events/TouchEventContext.cpp \
 	third_party/WebKit/Source/core/events/TransitionEvent.cpp \
+	third_party/WebKit/Source/core/events/TreeScopeEventContext.cpp \
 	third_party/WebKit/Source/core/events/UIEvent.cpp \
 	third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp \
 	third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp \
@@ -230,15 +232,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -249,7 +252,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -258,17 +260,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -276,13 +275,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -310,7 +311,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -349,7 +350,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -382,17 +382,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -403,7 +402,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -412,17 +410,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -430,13 +425,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -465,7 +462,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -504,7 +501,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_dom.target.linux-arm.mk b/Source/core/webcore_dom.target.linux-arm.mk
index 921bc41..992b695 100644
--- a/Source/core/webcore_dom.target.linux-arm.mk
+++ b/Source/core/webcore_dom.target.linux-arm.mk
@@ -32,10 +32,9 @@
 	third_party/WebKit/Source/core/dom/CharacterData.cpp \
 	third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp \
 	third_party/WebKit/Source/core/dom/ChildNodeList.cpp \
-	third_party/WebKit/Source/core/dom/ClassNodeList.cpp \
+	third_party/WebKit/Source/core/dom/ClassCollection.cpp \
 	third_party/WebKit/Source/core/dom/ClientRect.cpp \
 	third_party/WebKit/Source/core/dom/ClientRectList.cpp \
-	third_party/WebKit/Source/core/dom/Clipboard.cpp \
 	third_party/WebKit/Source/core/dom/Comment.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
@@ -43,10 +42,9 @@
 	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItemList.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/Document.cpp \
+	third_party/WebKit/Source/core/dom/DocumentEncodingData.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFragment.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFullscreen.cpp \
 	third_party/WebKit/Source/core/dom/DocumentInit.cpp \
@@ -58,13 +56,12 @@
 	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
-	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
 	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp \
+	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollector.cpp \
 	third_party/WebKit/Source/core/dom/DocumentType.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
 	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
-	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
@@ -74,7 +71,9 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp \
 	third_party/WebKit/Source/core/dom/Element.cpp \
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
+	third_party/WebKit/Source/core/dom/ElementDataCache.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
+	third_party/WebKit/Source/core/dom/EmptyNodeList.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -89,8 +88,6 @@
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverRegistration.cpp \
 	third_party/WebKit/Source/core/dom/MutationRecord.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlow.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodeMap.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodesCollection.cpp \
 	third_party/WebKit/Source/core/dom/NameNodeList.cpp \
@@ -99,9 +96,8 @@
 	third_party/WebKit/Source/core/dom/NodeFilter.cpp \
 	third_party/WebKit/Source/core/dom/NodeFilterCondition.cpp \
 	third_party/WebKit/Source/core/dom/NodeIterator.cpp \
-	third_party/WebKit/Source/core/dom/NodeList.cpp \
 	third_party/WebKit/Source/core/dom/NodeRareData.cpp \
-	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
+	third_party/WebKit/Source/core/dom/RenderTreeBuilder.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -121,17 +117,21 @@
 	third_party/WebKit/Source/core/dom/ScriptRunner.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/XMLDocument.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElement.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskDispatcher.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskImportStep.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskQueue.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
@@ -145,10 +145,10 @@
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
+	third_party/WebKit/Source/core/dom/StyleSheetCandidate.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
-	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
-	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
+	third_party/WebKit/Source/core/dom/TagCollection.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
@@ -157,6 +157,7 @@
 	third_party/WebKit/Source/core/dom/Traversal.cpp \
 	third_party/WebKit/Source/core/dom/TreeScope.cpp \
 	third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp \
+	third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/TreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/UserActionElementSet.cpp \
 	third_party/WebKit/Source/core/dom/ViewportDescription.cpp \
@@ -170,12 +171,10 @@
 	third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp \
 	third_party/WebKit/Source/core/events/ErrorEvent.cpp \
 	third_party/WebKit/Source/core/events/Event.cpp \
-	third_party/WebKit/Source/core/events/EventContext.cpp \
 	third_party/WebKit/Source/core/events/EventDispatcher.cpp \
 	third_party/WebKit/Source/core/events/EventDispatchMediator.cpp \
 	third_party/WebKit/Source/core/events/EventListenerMap.cpp \
 	third_party/WebKit/Source/core/events/EventPath.cpp \
-	third_party/WebKit/Source/core/events/EventRetargeter.cpp \
 	third_party/WebKit/Source/core/events/EventTarget.cpp \
 	third_party/WebKit/Source/core/events/FocusEvent.cpp \
 	third_party/WebKit/Source/core/events/GenericEventQueue.cpp \
@@ -186,6 +185,7 @@
 	third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/events/MutationEvent.cpp \
 	third_party/WebKit/Source/core/events/NavigatorEvents.cpp \
+	third_party/WebKit/Source/core/events/NodeEventContext.cpp \
 	third_party/WebKit/Source/core/events/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/events/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/events/PopStateEvent.cpp \
@@ -194,7 +194,9 @@
 	third_party/WebKit/Source/core/events/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/events/TextEvent.cpp \
 	third_party/WebKit/Source/core/events/TouchEvent.cpp \
+	third_party/WebKit/Source/core/events/TouchEventContext.cpp \
 	third_party/WebKit/Source/core/events/TransitionEvent.cpp \
+	third_party/WebKit/Source/core/events/TreeScopeEventContext.cpp \
 	third_party/WebKit/Source/core/events/UIEvent.cpp \
 	third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp \
 	third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp \
@@ -229,14 +231,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -247,7 +250,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -256,17 +258,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -274,13 +273,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -308,7 +309,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -348,7 +349,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -380,14 +380,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -398,7 +399,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -407,17 +407,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -425,13 +422,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -460,7 +459,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -500,7 +499,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_dom.target.linux-mips.mk b/Source/core/webcore_dom.target.linux-mips.mk
index b943ef2..3eeb867 100644
--- a/Source/core/webcore_dom.target.linux-mips.mk
+++ b/Source/core/webcore_dom.target.linux-mips.mk
@@ -32,10 +32,9 @@
 	third_party/WebKit/Source/core/dom/CharacterData.cpp \
 	third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp \
 	third_party/WebKit/Source/core/dom/ChildNodeList.cpp \
-	third_party/WebKit/Source/core/dom/ClassNodeList.cpp \
+	third_party/WebKit/Source/core/dom/ClassCollection.cpp \
 	third_party/WebKit/Source/core/dom/ClientRect.cpp \
 	third_party/WebKit/Source/core/dom/ClientRectList.cpp \
-	third_party/WebKit/Source/core/dom/Clipboard.cpp \
 	third_party/WebKit/Source/core/dom/Comment.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
@@ -43,10 +42,9 @@
 	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItemList.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/Document.cpp \
+	third_party/WebKit/Source/core/dom/DocumentEncodingData.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFragment.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFullscreen.cpp \
 	third_party/WebKit/Source/core/dom/DocumentInit.cpp \
@@ -58,13 +56,12 @@
 	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
-	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
 	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp \
+	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollector.cpp \
 	third_party/WebKit/Source/core/dom/DocumentType.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
 	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
-	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
@@ -74,7 +71,9 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp \
 	third_party/WebKit/Source/core/dom/Element.cpp \
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
+	third_party/WebKit/Source/core/dom/ElementDataCache.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
+	third_party/WebKit/Source/core/dom/EmptyNodeList.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -89,8 +88,6 @@
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverRegistration.cpp \
 	third_party/WebKit/Source/core/dom/MutationRecord.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlow.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodeMap.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodesCollection.cpp \
 	third_party/WebKit/Source/core/dom/NameNodeList.cpp \
@@ -99,9 +96,8 @@
 	third_party/WebKit/Source/core/dom/NodeFilter.cpp \
 	third_party/WebKit/Source/core/dom/NodeFilterCondition.cpp \
 	third_party/WebKit/Source/core/dom/NodeIterator.cpp \
-	third_party/WebKit/Source/core/dom/NodeList.cpp \
 	third_party/WebKit/Source/core/dom/NodeRareData.cpp \
-	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
+	third_party/WebKit/Source/core/dom/RenderTreeBuilder.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -121,17 +117,21 @@
 	third_party/WebKit/Source/core/dom/ScriptRunner.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/XMLDocument.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElement.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskDispatcher.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskImportStep.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskQueue.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
@@ -145,10 +145,10 @@
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
+	third_party/WebKit/Source/core/dom/StyleSheetCandidate.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
-	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
-	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
+	third_party/WebKit/Source/core/dom/TagCollection.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
@@ -157,6 +157,7 @@
 	third_party/WebKit/Source/core/dom/Traversal.cpp \
 	third_party/WebKit/Source/core/dom/TreeScope.cpp \
 	third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp \
+	third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/TreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/UserActionElementSet.cpp \
 	third_party/WebKit/Source/core/dom/ViewportDescription.cpp \
@@ -170,12 +171,10 @@
 	third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp \
 	third_party/WebKit/Source/core/events/ErrorEvent.cpp \
 	third_party/WebKit/Source/core/events/Event.cpp \
-	third_party/WebKit/Source/core/events/EventContext.cpp \
 	third_party/WebKit/Source/core/events/EventDispatcher.cpp \
 	third_party/WebKit/Source/core/events/EventDispatchMediator.cpp \
 	third_party/WebKit/Source/core/events/EventListenerMap.cpp \
 	third_party/WebKit/Source/core/events/EventPath.cpp \
-	third_party/WebKit/Source/core/events/EventRetargeter.cpp \
 	third_party/WebKit/Source/core/events/EventTarget.cpp \
 	third_party/WebKit/Source/core/events/FocusEvent.cpp \
 	third_party/WebKit/Source/core/events/GenericEventQueue.cpp \
@@ -186,6 +185,7 @@
 	third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/events/MutationEvent.cpp \
 	third_party/WebKit/Source/core/events/NavigatorEvents.cpp \
+	third_party/WebKit/Source/core/events/NodeEventContext.cpp \
 	third_party/WebKit/Source/core/events/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/events/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/events/PopStateEvent.cpp \
@@ -194,7 +194,9 @@
 	third_party/WebKit/Source/core/events/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/events/TextEvent.cpp \
 	third_party/WebKit/Source/core/events/TouchEvent.cpp \
+	third_party/WebKit/Source/core/events/TouchEventContext.cpp \
 	third_party/WebKit/Source/core/events/TransitionEvent.cpp \
+	third_party/WebKit/Source/core/events/TreeScopeEventContext.cpp \
 	third_party/WebKit/Source/core/events/UIEvent.cpp \
 	third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp \
 	third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp \
@@ -228,14 +230,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -246,7 +249,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -255,17 +257,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -273,13 +272,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -307,7 +308,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -347,7 +348,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -378,14 +378,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -396,7 +397,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -405,17 +405,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -423,13 +420,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -458,7 +457,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -498,7 +497,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_dom.target.linux-x86.mk b/Source/core/webcore_dom.target.linux-x86.mk
index 7ba6967..78f67d4 100644
--- a/Source/core/webcore_dom.target.linux-x86.mk
+++ b/Source/core/webcore_dom.target.linux-x86.mk
@@ -32,10 +32,9 @@
 	third_party/WebKit/Source/core/dom/CharacterData.cpp \
 	third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp \
 	third_party/WebKit/Source/core/dom/ChildNodeList.cpp \
-	third_party/WebKit/Source/core/dom/ClassNodeList.cpp \
+	third_party/WebKit/Source/core/dom/ClassCollection.cpp \
 	third_party/WebKit/Source/core/dom/ClientRect.cpp \
 	third_party/WebKit/Source/core/dom/ClientRectList.cpp \
-	third_party/WebKit/Source/core/dom/Clipboard.cpp \
 	third_party/WebKit/Source/core/dom/Comment.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
@@ -43,10 +42,9 @@
 	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
-	third_party/WebKit/Source/core/dom/DataTransferItemList.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/Document.cpp \
+	third_party/WebKit/Source/core/dom/DocumentEncodingData.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFragment.cpp \
 	third_party/WebKit/Source/core/dom/DocumentFullscreen.cpp \
 	third_party/WebKit/Source/core/dom/DocumentInit.cpp \
@@ -58,13 +56,12 @@
 	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
-	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
 	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp \
+	third_party/WebKit/Source/core/dom/DocumentStyleSheetCollector.cpp \
 	third_party/WebKit/Source/core/dom/DocumentType.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
 	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
-	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
@@ -74,7 +71,9 @@
 	third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp \
 	third_party/WebKit/Source/core/dom/Element.cpp \
 	third_party/WebKit/Source/core/dom/ElementData.cpp \
+	third_party/WebKit/Source/core/dom/ElementDataCache.cpp \
 	third_party/WebKit/Source/core/dom/ElementRareData.cpp \
+	third_party/WebKit/Source/core/dom/EmptyNodeList.cpp \
 	third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp \
 	third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp \
@@ -89,8 +88,6 @@
 	third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp \
 	third_party/WebKit/Source/core/dom/MutationObserverRegistration.cpp \
 	third_party/WebKit/Source/core/dom/MutationRecord.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlow.cpp \
-	third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodeMap.cpp \
 	third_party/WebKit/Source/core/dom/NamedNodesCollection.cpp \
 	third_party/WebKit/Source/core/dom/NameNodeList.cpp \
@@ -99,9 +96,8 @@
 	third_party/WebKit/Source/core/dom/NodeFilter.cpp \
 	third_party/WebKit/Source/core/dom/NodeFilterCondition.cpp \
 	third_party/WebKit/Source/core/dom/NodeIterator.cpp \
-	third_party/WebKit/Source/core/dom/NodeList.cpp \
 	third_party/WebKit/Source/core/dom/NodeRareData.cpp \
-	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
+	third_party/WebKit/Source/core/dom/RenderTreeBuilder.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -121,17 +117,21 @@
 	third_party/WebKit/Source/core/dom/ScriptRunner.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/XMLDocument.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElement.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp \
-	third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskDispatcher.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskImportStep.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskQueue.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementMicrotaskResolutionStep.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp \
+	third_party/WebKit/Source/core/dom/custom/CustomElementScheduler.cpp \
 	third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp \
@@ -145,10 +145,10 @@
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
 	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
+	third_party/WebKit/Source/core/dom/StyleSheetCandidate.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
-	third_party/WebKit/Source/core/dom/StyleTreeScopeTracker.cpp \
-	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
+	third_party/WebKit/Source/core/dom/TagCollection.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
@@ -157,6 +157,7 @@
 	third_party/WebKit/Source/core/dom/Traversal.cpp \
 	third_party/WebKit/Source/core/dom/TreeScope.cpp \
 	third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp \
+	third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/TreeWalker.cpp \
 	third_party/WebKit/Source/core/dom/UserActionElementSet.cpp \
 	third_party/WebKit/Source/core/dom/ViewportDescription.cpp \
@@ -170,12 +171,10 @@
 	third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp \
 	third_party/WebKit/Source/core/events/ErrorEvent.cpp \
 	third_party/WebKit/Source/core/events/Event.cpp \
-	third_party/WebKit/Source/core/events/EventContext.cpp \
 	third_party/WebKit/Source/core/events/EventDispatcher.cpp \
 	third_party/WebKit/Source/core/events/EventDispatchMediator.cpp \
 	third_party/WebKit/Source/core/events/EventListenerMap.cpp \
 	third_party/WebKit/Source/core/events/EventPath.cpp \
-	third_party/WebKit/Source/core/events/EventRetargeter.cpp \
 	third_party/WebKit/Source/core/events/EventTarget.cpp \
 	third_party/WebKit/Source/core/events/FocusEvent.cpp \
 	third_party/WebKit/Source/core/events/GenericEventQueue.cpp \
@@ -186,6 +185,7 @@
 	third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/events/MutationEvent.cpp \
 	third_party/WebKit/Source/core/events/NavigatorEvents.cpp \
+	third_party/WebKit/Source/core/events/NodeEventContext.cpp \
 	third_party/WebKit/Source/core/events/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/events/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/events/PopStateEvent.cpp \
@@ -194,7 +194,9 @@
 	third_party/WebKit/Source/core/events/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/events/TextEvent.cpp \
 	third_party/WebKit/Source/core/events/TouchEvent.cpp \
+	third_party/WebKit/Source/core/events/TouchEventContext.cpp \
 	third_party/WebKit/Source/core/events/TransitionEvent.cpp \
+	third_party/WebKit/Source/core/events/TreeScopeEventContext.cpp \
 	third_party/WebKit/Source/core/events/UIEvent.cpp \
 	third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp \
 	third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp \
@@ -230,15 +232,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -249,7 +252,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -258,17 +260,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -276,13 +275,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -310,7 +311,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -349,7 +350,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -382,17 +382,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -403,7 +402,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -412,17 +410,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -430,13 +425,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -465,7 +462,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -504,7 +501,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_derived.target.darwin-arm.mk b/Source/core/webcore_generated.target.darwin-arm.mk
similarity index 84%
rename from Source/core/webcore_derived.target.darwin-arm.mk
rename to Source/core/webcore_generated.target.darwin-arm.mk
index 599d8e5..ff7a9a2 100644
--- a/Source/core/webcore_derived.target.darwin-arm.mk
+++ b/Source/core/webcore_generated.target.darwin-arm.mk
@@ -3,7 +3,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_derived_gyp
+LOCAL_MODULE := third_party_WebKit_Source_core_webcore_generated_gyp
 LOCAL_MODULE_SUFFIX := .a
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,15 +12,15 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_canvas_script_source_gyp)/injected_canvas_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_script_source_gyp)/injected_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_debugger_script_source_gyp)/debugger_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_derived_sources_gyp)/make_platform_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_generated_gyp)/make_platform_generated.stamp \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
@@ -32,43 +32,43 @@
 # Make sure our deps and generated files are built first.
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
-$(gyp_intermediate_dir)/V8DerivedSources01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources01.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings01.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources02.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings02.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources03.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings03.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources04.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings04.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources05.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings05.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources06.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings06.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources07.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings07.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources08.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings08.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources09.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings09.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources10.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings10.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources11.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings11.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources12.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings12.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources13.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings13.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources14.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings14.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources15.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings15.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources16.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings16.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources17.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings17.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources18.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings18.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings19.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSPropertyNames.cpp: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp
 	mkdir -p $(@D); cp $< $@
@@ -110,7 +110,7 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
+$(gyp_intermediate_dir)/BisonCSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
 	mkdir -p $(@D); cp $< $@
@@ -137,25 +137,25 @@
 $(gyp_intermediate_dir)/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp
 	mkdir -p $(@D); cp $< $@
 LOCAL_GENERATED_SOURCES := \
-	$(gyp_intermediate_dir)/V8DerivedSources01.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources02.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources03.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources04.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources05.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources06.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources07.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources08.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources09.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources10.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources11.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources12.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources13.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources14.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources15.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources16.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
@@ -176,7 +176,7 @@
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
 	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
-	$(gyp_intermediate_dir)/CSSParser.cpp \
+	$(gyp_intermediate_dir)/BisonCSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
 	$(gyp_intermediate_dir)/XPathGrammar.cpp \
@@ -241,7 +241,6 @@
 	third_party/WebKit/Source/bindings/v8/V8EventListenerList.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCController.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCForContextDispose.cpp \
-	third_party/WebKit/Source/bindings/v8/V8HiddenPropertyName.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Initializer.cpp \
 	third_party/WebKit/Source/bindings/v8/V8LazyEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8MutationCallback.cpp \
@@ -261,7 +260,6 @@
 	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
@@ -282,6 +280,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8ElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntrySyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
@@ -296,7 +295,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLDocumentCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -307,14 +305,11 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MutationObserverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8NodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8OscillatorNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
@@ -324,7 +319,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGLengthCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
@@ -368,14 +362,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -386,7 +381,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -395,17 +389,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -413,13 +404,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -452,7 +445,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -492,7 +485,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -524,14 +516,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -542,7 +535,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -551,17 +543,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -569,13 +558,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -609,7 +600,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -649,7 +640,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -711,10 +701,10 @@
 
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_derived_gyp
+gyp_all_modules: third_party_WebKit_Source_core_webcore_generated_gyp
 
 # Alias gyp target name.
-.PHONY: webcore_derived
-webcore_derived: third_party_WebKit_Source_core_webcore_derived_gyp
+.PHONY: webcore_generated
+webcore_generated: third_party_WebKit_Source_core_webcore_generated_gyp
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_derived.target.darwin-mips.mk b/Source/core/webcore_generated.target.darwin-mips.mk
similarity index 84%
rename from Source/core/webcore_derived.target.darwin-mips.mk
rename to Source/core/webcore_generated.target.darwin-mips.mk
index 37e4ee3..bf10518 100644
--- a/Source/core/webcore_derived.target.darwin-mips.mk
+++ b/Source/core/webcore_generated.target.darwin-mips.mk
@@ -3,7 +3,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_derived_gyp
+LOCAL_MODULE := third_party_WebKit_Source_core_webcore_generated_gyp
 LOCAL_MODULE_SUFFIX := .a
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,15 +12,15 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_canvas_script_source_gyp)/injected_canvas_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_script_source_gyp)/injected_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_debugger_script_source_gyp)/debugger_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_derived_sources_gyp)/make_platform_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_generated_gyp)/make_platform_generated.stamp \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
@@ -32,43 +32,43 @@
 # Make sure our deps and generated files are built first.
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
-$(gyp_intermediate_dir)/V8DerivedSources01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources01.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings01.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources02.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings02.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources03.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings03.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources04.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings04.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources05.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings05.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources06.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings06.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources07.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings07.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources08.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings08.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources09.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings09.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources10.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings10.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources11.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings11.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources12.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings12.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources13.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings13.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources14.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings14.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources15.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings15.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources16.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings16.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources17.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings17.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources18.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings18.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings19.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSPropertyNames.cpp: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp
 	mkdir -p $(@D); cp $< $@
@@ -110,7 +110,7 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
+$(gyp_intermediate_dir)/BisonCSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
 	mkdir -p $(@D); cp $< $@
@@ -137,25 +137,25 @@
 $(gyp_intermediate_dir)/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp
 	mkdir -p $(@D); cp $< $@
 LOCAL_GENERATED_SOURCES := \
-	$(gyp_intermediate_dir)/V8DerivedSources01.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources02.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources03.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources04.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources05.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources06.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources07.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources08.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources09.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources10.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources11.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources12.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources13.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources14.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources15.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources16.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
@@ -176,7 +176,7 @@
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
 	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
-	$(gyp_intermediate_dir)/CSSParser.cpp \
+	$(gyp_intermediate_dir)/BisonCSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
 	$(gyp_intermediate_dir)/XPathGrammar.cpp \
@@ -241,7 +241,6 @@
 	third_party/WebKit/Source/bindings/v8/V8EventListenerList.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCController.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCForContextDispose.cpp \
-	third_party/WebKit/Source/bindings/v8/V8HiddenPropertyName.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Initializer.cpp \
 	third_party/WebKit/Source/bindings/v8/V8LazyEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8MutationCallback.cpp \
@@ -261,7 +260,6 @@
 	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
@@ -282,6 +280,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8ElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntrySyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
@@ -296,7 +295,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLDocumentCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -307,14 +305,11 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MutationObserverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8NodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8OscillatorNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
@@ -324,7 +319,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGLengthCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
@@ -367,14 +361,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -385,7 +380,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -394,17 +388,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -412,13 +403,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -451,7 +444,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -491,7 +484,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -522,14 +514,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -540,7 +533,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -549,17 +541,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -567,13 +556,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -607,7 +598,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -647,7 +638,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -705,10 +695,10 @@
 
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_derived_gyp
+gyp_all_modules: third_party_WebKit_Source_core_webcore_generated_gyp
 
 # Alias gyp target name.
-.PHONY: webcore_derived
-webcore_derived: third_party_WebKit_Source_core_webcore_derived_gyp
+.PHONY: webcore_generated
+webcore_generated: third_party_WebKit_Source_core_webcore_generated_gyp
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_derived.target.darwin-x86.mk b/Source/core/webcore_generated.target.darwin-x86.mk
similarity index 84%
rename from Source/core/webcore_derived.target.darwin-x86.mk
rename to Source/core/webcore_generated.target.darwin-x86.mk
index ae875d2..96b8300 100644
--- a/Source/core/webcore_derived.target.darwin-x86.mk
+++ b/Source/core/webcore_generated.target.darwin-x86.mk
@@ -3,7 +3,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_derived_gyp
+LOCAL_MODULE := third_party_WebKit_Source_core_webcore_generated_gyp
 LOCAL_MODULE_SUFFIX := .a
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,15 +12,15 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_canvas_script_source_gyp)/injected_canvas_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_script_source_gyp)/injected_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_debugger_script_source_gyp)/debugger_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_derived_sources_gyp)/make_platform_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_generated_gyp)/make_platform_generated.stamp \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
@@ -32,43 +32,43 @@
 # Make sure our deps and generated files are built first.
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
-$(gyp_intermediate_dir)/V8DerivedSources01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources01.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings01.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources02.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings02.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources03.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings03.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources04.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings04.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources05.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings05.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources06.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings06.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources07.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings07.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources08.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings08.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources09.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings09.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources10.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings10.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources11.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings11.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources12.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings12.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources13.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings13.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources14.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings14.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources15.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings15.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources16.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings16.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources17.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings17.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources18.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings18.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings19.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSPropertyNames.cpp: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp
 	mkdir -p $(@D); cp $< $@
@@ -110,7 +110,7 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
+$(gyp_intermediate_dir)/BisonCSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
 	mkdir -p $(@D); cp $< $@
@@ -137,25 +137,25 @@
 $(gyp_intermediate_dir)/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp
 	mkdir -p $(@D); cp $< $@
 LOCAL_GENERATED_SOURCES := \
-	$(gyp_intermediate_dir)/V8DerivedSources01.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources02.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources03.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources04.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources05.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources06.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources07.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources08.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources09.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources10.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources11.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources12.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources13.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources14.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources15.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources16.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
@@ -176,7 +176,7 @@
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
 	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
-	$(gyp_intermediate_dir)/CSSParser.cpp \
+	$(gyp_intermediate_dir)/BisonCSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
 	$(gyp_intermediate_dir)/XPathGrammar.cpp \
@@ -241,7 +241,6 @@
 	third_party/WebKit/Source/bindings/v8/V8EventListenerList.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCController.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCForContextDispose.cpp \
-	third_party/WebKit/Source/bindings/v8/V8HiddenPropertyName.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Initializer.cpp \
 	third_party/WebKit/Source/bindings/v8/V8LazyEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8MutationCallback.cpp \
@@ -261,7 +260,6 @@
 	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
@@ -282,6 +280,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8ElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntrySyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
@@ -296,7 +295,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLDocumentCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -307,14 +305,11 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MutationObserverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8NodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8OscillatorNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
@@ -324,7 +319,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGLengthCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
@@ -369,15 +363,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -388,7 +383,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -397,17 +391,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -415,13 +406,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -454,7 +447,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -493,7 +486,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -526,17 +518,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -547,7 +538,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -556,17 +546,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -574,13 +561,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -614,7 +603,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -653,7 +642,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -711,10 +699,10 @@
 
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_derived_gyp
+gyp_all_modules: third_party_WebKit_Source_core_webcore_generated_gyp
 
 # Alias gyp target name.
-.PHONY: webcore_derived
-webcore_derived: third_party_WebKit_Source_core_webcore_derived_gyp
+.PHONY: webcore_generated
+webcore_generated: third_party_WebKit_Source_core_webcore_generated_gyp
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_derived.target.darwin-arm.mk b/Source/core/webcore_generated.target.linux-arm.mk
similarity index 84%
copy from Source/core/webcore_derived.target.darwin-arm.mk
copy to Source/core/webcore_generated.target.linux-arm.mk
index 599d8e5..ff7a9a2 100644
--- a/Source/core/webcore_derived.target.darwin-arm.mk
+++ b/Source/core/webcore_generated.target.linux-arm.mk
@@ -3,7 +3,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_derived_gyp
+LOCAL_MODULE := third_party_WebKit_Source_core_webcore_generated_gyp
 LOCAL_MODULE_SUFFIX := .a
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,15 +12,15 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_canvas_script_source_gyp)/injected_canvas_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_script_source_gyp)/injected_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_debugger_script_source_gyp)/debugger_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_derived_sources_gyp)/make_platform_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_generated_gyp)/make_platform_generated.stamp \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
@@ -32,43 +32,43 @@
 # Make sure our deps and generated files are built first.
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
-$(gyp_intermediate_dir)/V8DerivedSources01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources01.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings01.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources02.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings02.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources03.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings03.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources04.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings04.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources05.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings05.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources06.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings06.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources07.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings07.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources08.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings08.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources09.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings09.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources10.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings10.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources11.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings11.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources12.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings12.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources13.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings13.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources14.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings14.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources15.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings15.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources16.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings16.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources17.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings17.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources18.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings18.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings19.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSPropertyNames.cpp: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp
 	mkdir -p $(@D); cp $< $@
@@ -110,7 +110,7 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
+$(gyp_intermediate_dir)/BisonCSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
 	mkdir -p $(@D); cp $< $@
@@ -137,25 +137,25 @@
 $(gyp_intermediate_dir)/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp
 	mkdir -p $(@D); cp $< $@
 LOCAL_GENERATED_SOURCES := \
-	$(gyp_intermediate_dir)/V8DerivedSources01.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources02.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources03.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources04.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources05.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources06.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources07.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources08.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources09.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources10.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources11.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources12.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources13.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources14.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources15.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources16.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
@@ -176,7 +176,7 @@
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
 	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
-	$(gyp_intermediate_dir)/CSSParser.cpp \
+	$(gyp_intermediate_dir)/BisonCSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
 	$(gyp_intermediate_dir)/XPathGrammar.cpp \
@@ -241,7 +241,6 @@
 	third_party/WebKit/Source/bindings/v8/V8EventListenerList.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCController.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCForContextDispose.cpp \
-	third_party/WebKit/Source/bindings/v8/V8HiddenPropertyName.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Initializer.cpp \
 	third_party/WebKit/Source/bindings/v8/V8LazyEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8MutationCallback.cpp \
@@ -261,7 +260,6 @@
 	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
@@ -282,6 +280,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8ElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntrySyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
@@ -296,7 +295,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLDocumentCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -307,14 +305,11 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MutationObserverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8NodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8OscillatorNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
@@ -324,7 +319,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGLengthCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
@@ -368,14 +362,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -386,7 +381,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -395,17 +389,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -413,13 +404,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -452,7 +445,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -492,7 +485,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -524,14 +516,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -542,7 +535,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -551,17 +543,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -569,13 +558,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -609,7 +600,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -649,7 +640,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -711,10 +701,10 @@
 
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_derived_gyp
+gyp_all_modules: third_party_WebKit_Source_core_webcore_generated_gyp
 
 # Alias gyp target name.
-.PHONY: webcore_derived
-webcore_derived: third_party_WebKit_Source_core_webcore_derived_gyp
+.PHONY: webcore_generated
+webcore_generated: third_party_WebKit_Source_core_webcore_generated_gyp
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_derived.target.darwin-mips.mk b/Source/core/webcore_generated.target.linux-mips.mk
similarity index 84%
copy from Source/core/webcore_derived.target.darwin-mips.mk
copy to Source/core/webcore_generated.target.linux-mips.mk
index 37e4ee3..bf10518 100644
--- a/Source/core/webcore_derived.target.darwin-mips.mk
+++ b/Source/core/webcore_generated.target.linux-mips.mk
@@ -3,7 +3,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_derived_gyp
+LOCAL_MODULE := third_party_WebKit_Source_core_webcore_generated_gyp
 LOCAL_MODULE_SUFFIX := .a
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,15 +12,15 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_canvas_script_source_gyp)/injected_canvas_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_script_source_gyp)/injected_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_debugger_script_source_gyp)/debugger_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_derived_sources_gyp)/make_platform_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_generated_gyp)/make_platform_generated.stamp \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
@@ -32,43 +32,43 @@
 # Make sure our deps and generated files are built first.
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
-$(gyp_intermediate_dir)/V8DerivedSources01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources01.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings01.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources02.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings02.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources03.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings03.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources04.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings04.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources05.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings05.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources06.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings06.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources07.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings07.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources08.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings08.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources09.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings09.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources10.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings10.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources11.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings11.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources12.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings12.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources13.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings13.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources14.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings14.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources15.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings15.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources16.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings16.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources17.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings17.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources18.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings18.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings19.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSPropertyNames.cpp: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp
 	mkdir -p $(@D); cp $< $@
@@ -110,7 +110,7 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
+$(gyp_intermediate_dir)/BisonCSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
 	mkdir -p $(@D); cp $< $@
@@ -137,25 +137,25 @@
 $(gyp_intermediate_dir)/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp
 	mkdir -p $(@D); cp $< $@
 LOCAL_GENERATED_SOURCES := \
-	$(gyp_intermediate_dir)/V8DerivedSources01.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources02.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources03.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources04.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources05.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources06.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources07.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources08.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources09.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources10.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources11.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources12.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources13.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources14.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources15.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources16.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
@@ -176,7 +176,7 @@
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
 	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
-	$(gyp_intermediate_dir)/CSSParser.cpp \
+	$(gyp_intermediate_dir)/BisonCSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
 	$(gyp_intermediate_dir)/XPathGrammar.cpp \
@@ -241,7 +241,6 @@
 	third_party/WebKit/Source/bindings/v8/V8EventListenerList.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCController.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCForContextDispose.cpp \
-	third_party/WebKit/Source/bindings/v8/V8HiddenPropertyName.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Initializer.cpp \
 	third_party/WebKit/Source/bindings/v8/V8LazyEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8MutationCallback.cpp \
@@ -261,7 +260,6 @@
 	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
@@ -282,6 +280,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8ElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntrySyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
@@ -296,7 +295,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLDocumentCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -307,14 +305,11 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MutationObserverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8NodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8OscillatorNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
@@ -324,7 +319,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGLengthCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
@@ -367,14 +361,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -385,7 +380,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -394,17 +388,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -412,13 +403,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -451,7 +444,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -491,7 +484,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -522,14 +514,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -540,7 +533,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -549,17 +541,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -567,13 +556,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -607,7 +598,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -647,7 +638,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -705,10 +695,10 @@
 
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_derived_gyp
+gyp_all_modules: third_party_WebKit_Source_core_webcore_generated_gyp
 
 # Alias gyp target name.
-.PHONY: webcore_derived
-webcore_derived: third_party_WebKit_Source_core_webcore_derived_gyp
+.PHONY: webcore_generated
+webcore_generated: third_party_WebKit_Source_core_webcore_generated_gyp
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_derived.target.darwin-x86.mk b/Source/core/webcore_generated.target.linux-x86.mk
similarity index 84%
copy from Source/core/webcore_derived.target.darwin-x86.mk
copy to Source/core/webcore_generated.target.linux-x86.mk
index ae875d2..96b8300 100644
--- a/Source/core/webcore_derived.target.darwin-x86.mk
+++ b/Source/core/webcore_generated.target.linux-x86.mk
@@ -3,7 +3,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_derived_gyp
+LOCAL_MODULE := third_party_WebKit_Source_core_webcore_generated_gyp
 LOCAL_MODULE_SUFFIX := .a
 LOCAL_MODULE_TAGS := optional
 gyp_intermediate_dir := $(call local-intermediates-dir)
@@ -12,15 +12,15 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_canvas_script_source_gyp)/injected_canvas_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_injected_script_source_gyp)/injected_script_source.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_debugger_script_source_gyp)/debugger_script_source.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_derived_sources_gyp)/make_platform_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_platform_make_platform_generated_gyp)/make_platform_generated.stamp \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
@@ -32,43 +32,43 @@
 # Make sure our deps and generated files are built first.
 LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
 
-$(gyp_intermediate_dir)/V8DerivedSources01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources01.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings01.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources02.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings02.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources03.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings03.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources04.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings04.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources05.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings05.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources06.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings06.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources07.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings07.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources08.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings08.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources09.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings09.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources10.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings10.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources11.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings11.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources12.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings12.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources13.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings13.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources14.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings14.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources15.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings15.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources16.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings16.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources17.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings17.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources18.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings18.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/V8DerivedSources19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8DerivedSources19.cpp
+$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp: $(gyp_shared_intermediate_dir)/blink/bindings/V8GeneratedBindings19.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSPropertyNames.cpp: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp
 	mkdir -p $(@D); cp $< $@
@@ -110,7 +110,7 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/CSSTokenizer.cpp: $(gyp_shared_intermediate_dir)/blink/CSSTokenizer.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/CSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp
+$(gyp_intermediate_dir)/BisonCSSParser.cpp: $(gyp_shared_intermediate_dir)/blink/BisonCSSParser.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/HTMLMetaElement.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLMetaElement.cpp
 	mkdir -p $(@D); cp $< $@
@@ -137,25 +137,25 @@
 $(gyp_intermediate_dir)/StyleBuilderFunctions.cpp: $(gyp_shared_intermediate_dir)/blink/StyleBuilderFunctions.cpp
 	mkdir -p $(@D); cp $< $@
 LOCAL_GENERATED_SOURCES := \
-	$(gyp_intermediate_dir)/V8DerivedSources01.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources02.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources03.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources04.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources05.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources06.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources07.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources08.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources09.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources10.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources11.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources12.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources13.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources14.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources15.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources16.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources17.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources18.cpp \
-	$(gyp_intermediate_dir)/V8DerivedSources19.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings01.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings02.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings03.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings04.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings05.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings06.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings07.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings08.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings09.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings10.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings11.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings12.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings13.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings14.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings15.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings16.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings17.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings18.cpp \
+	$(gyp_intermediate_dir)/V8GeneratedBindings19.cpp \
 	$(gyp_intermediate_dir)/CSSPropertyNames.cpp \
 	$(gyp_intermediate_dir)/CSSValueKeywords.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
@@ -176,7 +176,7 @@
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
 	$(gyp_intermediate_dir)/CSSTokenizer.cpp \
-	$(gyp_intermediate_dir)/CSSParser.cpp \
+	$(gyp_intermediate_dir)/BisonCSSParser.cpp \
 	$(gyp_intermediate_dir)/HTMLMetaElement.cpp \
 	$(gyp_intermediate_dir)/CSSGrammar.cpp \
 	$(gyp_intermediate_dir)/XPathGrammar.cpp \
@@ -241,7 +241,6 @@
 	third_party/WebKit/Source/bindings/v8/V8EventListenerList.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCController.cpp \
 	third_party/WebKit/Source/bindings/v8/V8GCForContextDispose.cpp \
-	third_party/WebKit/Source/bindings/v8/V8HiddenPropertyName.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Initializer.cpp \
 	third_party/WebKit/Source/bindings/v8/V8LazyEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8MutationCallback.cpp \
@@ -261,7 +260,6 @@
 	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioNodeCustom.cpp \
@@ -282,6 +280,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8ElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EntrySyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8EventCustom.cpp \
@@ -296,7 +295,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLDocumentCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFormControlsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLFrameElementCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLOptionsCollectionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8HTMLPlugInElementCustom.cpp \
@@ -307,14 +305,11 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MutationObserverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8NodeCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8NodeListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8OscillatorNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
@@ -324,7 +319,6 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGElementCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8SVGLengthCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SVGPathSegCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8StyleSheetCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8TextCustom.cpp \
@@ -369,15 +363,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -388,7 +383,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -397,17 +391,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -415,13 +406,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -454,7 +447,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -493,7 +486,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -526,17 +518,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -547,7 +538,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -556,17 +546,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -574,13 +561,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -614,7 +603,7 @@
 	$(LOCAL_PATH)/skia/config \
 	$(LOCAL_PATH)/third_party/khronos \
 	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(LOCAL_PATH)/third_party/ots/include \
 	$(LOCAL_PATH)/third_party/zlib \
 	$(PWD)/external/icu4c/common \
@@ -653,7 +642,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -711,10 +699,10 @@
 
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_derived_gyp
+gyp_all_modules: third_party_WebKit_Source_core_webcore_generated_gyp
 
 # Alias gyp target name.
-.PHONY: webcore_derived
-webcore_derived: third_party_WebKit_Source_core_webcore_derived_gyp
+.PHONY: webcore_generated
+webcore_generated: third_party_WebKit_Source_core_webcore_generated_gyp
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_html.target.darwin-arm.mk b/Source/core/webcore_html.target.darwin-arm.mk
index fd4df88..5d6322c 100644
--- a/Source/core/webcore_html.target.darwin-arm.mk
+++ b/Source/core/webcore_html.target.darwin-arm.mk
@@ -69,8 +69,8 @@
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportChild.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportData.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportStateResolver.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -84,6 +84,8 @@
 	third_party/WebKit/Source/core/html/HTMLMeterElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLModElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLNameCollection.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoEmbedElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLObjectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp \
@@ -96,6 +98,8 @@
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRTElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRubyElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSelectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSourceElement.cpp \
@@ -118,6 +122,7 @@
 	third_party/WebKit/Source/core/html/HTMLUListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLVideoElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp \
+	third_party/WebKit/Source/core/html/HTMLWBRElement.cpp \
 	third_party/WebKit/Source/core/html/ImageData.cpp \
 	third_party/WebKit/Source/core/html/ImageDocument.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
@@ -190,7 +195,6 @@
 	third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp \
-	third_party/WebKit/Source/core/html/forms/CheckedRadioButtons.cpp \
 	third_party/WebKit/Source/core/html/forms/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateTimeFieldsState.cpp \
@@ -205,6 +209,7 @@
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp \
+	third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp \
 	third_party/WebKit/Source/core/html/forms/RadioInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/RangeInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ResetInputType.cpp \
@@ -229,7 +234,6 @@
 	third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLEntitySearch.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLFormattingElementList.cpp \
-	third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp \
@@ -245,6 +249,7 @@
 	third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp \
 	third_party/WebKit/Source/core/html/parser/TextDocumentParser.cpp \
+	third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp \
 	third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp \
@@ -257,11 +262,10 @@
 	third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControlsAndroid.cpp \
 	third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp \
@@ -269,7 +273,6 @@
 	third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp \
-	third_party/WebKit/Source/core/html/ime/Composition.cpp \
 	third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp \
 	third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp \
 	third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp \
@@ -277,6 +280,7 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCue.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
+	third_party/WebKit/Source/core/html/track/TrackBase.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
@@ -284,6 +288,7 @@
 	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTScanner.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
@@ -314,14 +319,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -332,7 +338,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -341,17 +346,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -359,13 +361,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -393,7 +397,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -433,7 +437,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -465,14 +468,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -483,7 +487,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -492,17 +495,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -510,13 +510,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -545,7 +547,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -585,7 +587,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_html.target.darwin-mips.mk b/Source/core/webcore_html.target.darwin-mips.mk
index ab9008f..70d3e59 100644
--- a/Source/core/webcore_html.target.darwin-mips.mk
+++ b/Source/core/webcore_html.target.darwin-mips.mk
@@ -69,8 +69,8 @@
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportChild.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportData.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportStateResolver.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -84,6 +84,8 @@
 	third_party/WebKit/Source/core/html/HTMLMeterElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLModElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLNameCollection.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoEmbedElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLObjectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp \
@@ -96,6 +98,8 @@
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRTElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRubyElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSelectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSourceElement.cpp \
@@ -118,6 +122,7 @@
 	third_party/WebKit/Source/core/html/HTMLUListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLVideoElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp \
+	third_party/WebKit/Source/core/html/HTMLWBRElement.cpp \
 	third_party/WebKit/Source/core/html/ImageData.cpp \
 	third_party/WebKit/Source/core/html/ImageDocument.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
@@ -190,7 +195,6 @@
 	third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp \
-	third_party/WebKit/Source/core/html/forms/CheckedRadioButtons.cpp \
 	third_party/WebKit/Source/core/html/forms/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateTimeFieldsState.cpp \
@@ -205,6 +209,7 @@
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp \
+	third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp \
 	third_party/WebKit/Source/core/html/forms/RadioInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/RangeInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ResetInputType.cpp \
@@ -229,7 +234,6 @@
 	third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLEntitySearch.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLFormattingElementList.cpp \
-	third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp \
@@ -245,6 +249,7 @@
 	third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp \
 	third_party/WebKit/Source/core/html/parser/TextDocumentParser.cpp \
+	third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp \
 	third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp \
@@ -257,11 +262,10 @@
 	third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControlsAndroid.cpp \
 	third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp \
@@ -269,7 +273,6 @@
 	third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp \
-	third_party/WebKit/Source/core/html/ime/Composition.cpp \
 	third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp \
 	third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp \
 	third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp \
@@ -277,6 +280,7 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCue.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
+	third_party/WebKit/Source/core/html/track/TrackBase.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
@@ -284,6 +288,7 @@
 	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTScanner.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
@@ -313,14 +318,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -331,7 +337,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -340,17 +345,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -358,13 +360,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -392,7 +396,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -432,7 +436,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -463,14 +466,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -481,7 +485,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -490,17 +493,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -508,13 +508,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -543,7 +545,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -583,7 +585,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_html.target.darwin-x86.mk b/Source/core/webcore_html.target.darwin-x86.mk
index 9c1aabb..6aab4b0 100644
--- a/Source/core/webcore_html.target.darwin-x86.mk
+++ b/Source/core/webcore_html.target.darwin-x86.mk
@@ -69,8 +69,8 @@
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportChild.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportData.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportStateResolver.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -84,6 +84,8 @@
 	third_party/WebKit/Source/core/html/HTMLMeterElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLModElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLNameCollection.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoEmbedElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLObjectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp \
@@ -96,6 +98,8 @@
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRTElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRubyElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSelectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSourceElement.cpp \
@@ -118,6 +122,7 @@
 	third_party/WebKit/Source/core/html/HTMLUListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLVideoElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp \
+	third_party/WebKit/Source/core/html/HTMLWBRElement.cpp \
 	third_party/WebKit/Source/core/html/ImageData.cpp \
 	third_party/WebKit/Source/core/html/ImageDocument.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
@@ -190,7 +195,6 @@
 	third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp \
-	third_party/WebKit/Source/core/html/forms/CheckedRadioButtons.cpp \
 	third_party/WebKit/Source/core/html/forms/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateTimeFieldsState.cpp \
@@ -205,6 +209,7 @@
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp \
+	third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp \
 	third_party/WebKit/Source/core/html/forms/RadioInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/RangeInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ResetInputType.cpp \
@@ -229,7 +234,6 @@
 	third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLEntitySearch.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLFormattingElementList.cpp \
-	third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp \
@@ -245,6 +249,7 @@
 	third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp \
 	third_party/WebKit/Source/core/html/parser/TextDocumentParser.cpp \
+	third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp \
 	third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp \
@@ -257,11 +262,10 @@
 	third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControlsAndroid.cpp \
 	third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp \
@@ -269,7 +273,6 @@
 	third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp \
-	third_party/WebKit/Source/core/html/ime/Composition.cpp \
 	third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp \
 	third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp \
 	third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp \
@@ -277,6 +280,7 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCue.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
+	third_party/WebKit/Source/core/html/track/TrackBase.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
@@ -284,6 +288,7 @@
 	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTScanner.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
@@ -315,15 +320,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -334,7 +340,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -343,17 +348,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -361,13 +363,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -395,7 +399,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -434,7 +438,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -467,17 +470,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -488,7 +490,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -497,17 +498,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -515,13 +513,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -550,7 +550,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -589,7 +589,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_html.target.linux-arm.mk b/Source/core/webcore_html.target.linux-arm.mk
index fd4df88..5d6322c 100644
--- a/Source/core/webcore_html.target.linux-arm.mk
+++ b/Source/core/webcore_html.target.linux-arm.mk
@@ -69,8 +69,8 @@
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportChild.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportData.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportStateResolver.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -84,6 +84,8 @@
 	third_party/WebKit/Source/core/html/HTMLMeterElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLModElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLNameCollection.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoEmbedElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLObjectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp \
@@ -96,6 +98,8 @@
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRTElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRubyElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSelectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSourceElement.cpp \
@@ -118,6 +122,7 @@
 	third_party/WebKit/Source/core/html/HTMLUListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLVideoElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp \
+	third_party/WebKit/Source/core/html/HTMLWBRElement.cpp \
 	third_party/WebKit/Source/core/html/ImageData.cpp \
 	third_party/WebKit/Source/core/html/ImageDocument.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
@@ -190,7 +195,6 @@
 	third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp \
-	third_party/WebKit/Source/core/html/forms/CheckedRadioButtons.cpp \
 	third_party/WebKit/Source/core/html/forms/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateTimeFieldsState.cpp \
@@ -205,6 +209,7 @@
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp \
+	third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp \
 	third_party/WebKit/Source/core/html/forms/RadioInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/RangeInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ResetInputType.cpp \
@@ -229,7 +234,6 @@
 	third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLEntitySearch.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLFormattingElementList.cpp \
-	third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp \
@@ -245,6 +249,7 @@
 	third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp \
 	third_party/WebKit/Source/core/html/parser/TextDocumentParser.cpp \
+	third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp \
 	third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp \
@@ -257,11 +262,10 @@
 	third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControlsAndroid.cpp \
 	third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp \
@@ -269,7 +273,6 @@
 	third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp \
-	third_party/WebKit/Source/core/html/ime/Composition.cpp \
 	third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp \
 	third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp \
 	third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp \
@@ -277,6 +280,7 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCue.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
+	third_party/WebKit/Source/core/html/track/TrackBase.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
@@ -284,6 +288,7 @@
 	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTScanner.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
@@ -314,14 +319,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -332,7 +338,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -341,17 +346,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -359,13 +361,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -393,7 +397,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -433,7 +437,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -465,14 +468,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -483,7 +487,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -492,17 +495,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -510,13 +510,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -545,7 +547,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -585,7 +587,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_html.target.linux-mips.mk b/Source/core/webcore_html.target.linux-mips.mk
index ab9008f..70d3e59 100644
--- a/Source/core/webcore_html.target.linux-mips.mk
+++ b/Source/core/webcore_html.target.linux-mips.mk
@@ -69,8 +69,8 @@
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportChild.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportData.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportStateResolver.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -84,6 +84,8 @@
 	third_party/WebKit/Source/core/html/HTMLMeterElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLModElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLNameCollection.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoEmbedElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLObjectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp \
@@ -96,6 +98,8 @@
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRTElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRubyElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSelectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSourceElement.cpp \
@@ -118,6 +122,7 @@
 	third_party/WebKit/Source/core/html/HTMLUListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLVideoElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp \
+	third_party/WebKit/Source/core/html/HTMLWBRElement.cpp \
 	third_party/WebKit/Source/core/html/ImageData.cpp \
 	third_party/WebKit/Source/core/html/ImageDocument.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
@@ -190,7 +195,6 @@
 	third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp \
-	third_party/WebKit/Source/core/html/forms/CheckedRadioButtons.cpp \
 	third_party/WebKit/Source/core/html/forms/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateTimeFieldsState.cpp \
@@ -205,6 +209,7 @@
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp \
+	third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp \
 	third_party/WebKit/Source/core/html/forms/RadioInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/RangeInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ResetInputType.cpp \
@@ -229,7 +234,6 @@
 	third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLEntitySearch.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLFormattingElementList.cpp \
-	third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp \
@@ -245,6 +249,7 @@
 	third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp \
 	third_party/WebKit/Source/core/html/parser/TextDocumentParser.cpp \
+	third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp \
 	third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp \
@@ -257,11 +262,10 @@
 	third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControlsAndroid.cpp \
 	third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp \
@@ -269,7 +273,6 @@
 	third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp \
-	third_party/WebKit/Source/core/html/ime/Composition.cpp \
 	third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp \
 	third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp \
 	third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp \
@@ -277,6 +280,7 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCue.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
+	third_party/WebKit/Source/core/html/track/TrackBase.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
@@ -284,6 +288,7 @@
 	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTScanner.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
@@ -313,14 +318,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -331,7 +337,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -340,17 +345,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -358,13 +360,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -392,7 +396,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -432,7 +436,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -463,14 +466,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -481,7 +485,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -490,17 +493,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -508,13 +508,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -543,7 +545,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -583,7 +585,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_html.target.linux-x86.mk b/Source/core/webcore_html.target.linux-x86.mk
index 9c1aabb..6aab4b0 100644
--- a/Source/core/webcore_html.target.linux-x86.mk
+++ b/Source/core/webcore_html.target.linux-x86.mk
@@ -69,8 +69,8 @@
 	third_party/WebKit/Source/core/html/HTMLImport.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportsController.cpp \
 	third_party/WebKit/Source/core/html/HTMLImportChild.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportData.cpp \
-	third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportLoader.cpp \
+	third_party/WebKit/Source/core/html/HTMLImportStateResolver.cpp \
 	third_party/WebKit/Source/core/html/HTMLInputElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLLIElement.cpp \
@@ -84,6 +84,8 @@
 	third_party/WebKit/Source/core/html/HTMLMeterElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLModElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLNameCollection.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoEmbedElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLNoScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLObjectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp \
@@ -96,6 +98,8 @@
 	third_party/WebKit/Source/core/html/HTMLPreElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLProgressElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLQuoteElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRTElement.cpp \
+	third_party/WebKit/Source/core/html/HTMLRubyElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLScriptElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSelectElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLSourceElement.cpp \
@@ -118,6 +122,7 @@
 	third_party/WebKit/Source/core/html/HTMLUListElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLVideoElement.cpp \
 	third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp \
+	third_party/WebKit/Source/core/html/HTMLWBRElement.cpp \
 	third_party/WebKit/Source/core/html/ImageData.cpp \
 	third_party/WebKit/Source/core/html/ImageDocument.cpp \
 	third_party/WebKit/Source/core/html/LabelableElement.cpp \
@@ -190,7 +195,6 @@
 	third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp \
-	third_party/WebKit/Source/core/html/forms/CheckedRadioButtons.cpp \
 	third_party/WebKit/Source/core/html/forms/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/DateTimeFieldsState.cpp \
@@ -205,6 +209,7 @@
 	third_party/WebKit/Source/core/html/forms/MonthInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/NumberInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp \
+	third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp \
 	third_party/WebKit/Source/core/html/forms/RadioInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/RangeInputType.cpp \
 	third_party/WebKit/Source/core/html/forms/ResetInputType.cpp \
@@ -229,7 +234,6 @@
 	third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLEntitySearch.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLFormattingElementList.cpp \
-	third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp \
@@ -245,6 +249,7 @@
 	third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp \
 	third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp \
 	third_party/WebKit/Source/core/html/parser/TextDocumentParser.cpp \
+	third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp \
 	third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp \
 	third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp \
@@ -257,11 +262,10 @@
 	third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp \
 	third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp \
-	third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControls.cpp \
+	third_party/WebKit/Source/core/html/shadow/MediaControlsAndroid.cpp \
 	third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp \
@@ -269,7 +273,6 @@
 	third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp \
 	third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp \
-	third_party/WebKit/Source/core/html/ime/Composition.cpp \
 	third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp \
 	third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp \
 	third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp \
@@ -277,6 +280,7 @@
 	third_party/WebKit/Source/core/html/track/TextTrackCue.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp \
 	third_party/WebKit/Source/core/html/track/TextTrackList.cpp \
+	third_party/WebKit/Source/core/html/track/TrackBase.cpp \
 	third_party/WebKit/Source/core/html/track/TrackEvent.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp \
@@ -284,6 +288,7 @@
 	third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp \
+	third_party/WebKit/Source/core/html/track/vtt/VTTScanner.cpp \
 	third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
 
 
@@ -315,15 +320,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -334,7 +340,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -343,17 +348,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -361,13 +363,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -395,7 +399,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -434,7 +438,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -467,17 +470,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -488,7 +490,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -497,17 +498,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -515,13 +513,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -550,7 +550,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -589,7 +589,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_platform.target.darwin-arm.mk b/Source/core/webcore_platform.target.darwin-arm.mk
deleted file mode 100644
index 1c81dcd..0000000
--- a/Source/core/webcore_platform.target.darwin-arm.mk
+++ /dev/null
@@ -1,411 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_platform_gyp
-LOCAL_MODULE_SUFFIX := .a
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a
-
-GYP_GENERATED_OUTPUTS :=
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-LOCAL_GENERATED_SOURCES :=
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS :=
-
-LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
-	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
-	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
-	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
-	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
-	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-fno-tree-sra \
-	-fuse-ld=gold \
-	-Wno-psabi \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-fno-tree-sra \
-	-fuse-ld=gold \
-	-Wno-psabi \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-
-LOCAL_LDFLAGS_Debug := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-Wl,-z,relro \
-	-Wl,-z,now \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--icf=safe \
-	-Wl,--fatal-warnings \
-	-Wl,--gc-sections \
-	-Wl,--warn-shared-textrel \
-	-Wl,-O1 \
-	-Wl,--as-needed
-
-
-LOCAL_LDFLAGS_Release := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-Wl,-z,relro \
-	-Wl,-z,now \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--icf=safe \
-	-Wl,-O1 \
-	-Wl,--as-needed \
-	-Wl,--gc-sections \
-	-Wl,--fatal-warnings \
-	-Wl,--warn-shared-textrel
-
-
-LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
-
-LOCAL_STATIC_LIBRARIES := \
-	skia_skia_library_gyp
-
-# Enable grouping to fix circular references
-LOCAL_GROUP_STATIC_LIBRARIES := true
-
-LOCAL_SHARED_LIBRARIES := \
-	libstlport \
-	libdl
-
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_platform_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform
-webcore_platform: third_party_WebKit_Source_core_webcore_platform_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform.target.darwin-mips.mk b/Source/core/webcore_platform.target.darwin-mips.mk
deleted file mode 100644
index 4243d24..0000000
--- a/Source/core/webcore_platform.target.darwin-mips.mk
+++ /dev/null
@@ -1,405 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_platform_gyp
-LOCAL_MODULE_SUFFIX := .a
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a
-
-GYP_GENERATED_OUTPUTS :=
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-LOCAL_GENERATED_SOURCES :=
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS :=
-
-LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
-	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
-	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
-	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
-	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
-	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-EL \
-	-mhard-float \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-EL \
-	-mhard-float \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-
-LOCAL_LDFLAGS_Debug := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-EL \
-	-Wl,--no-keep-memory \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--fatal-warnings \
-	-Wl,--gc-sections \
-	-Wl,--warn-shared-textrel \
-	-Wl,-O1 \
-	-Wl,--as-needed
-
-
-LOCAL_LDFLAGS_Release := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-EL \
-	-Wl,--no-keep-memory \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,-O1 \
-	-Wl,--as-needed \
-	-Wl,--gc-sections \
-	-Wl,--fatal-warnings \
-	-Wl,--warn-shared-textrel
-
-
-LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
-
-LOCAL_STATIC_LIBRARIES := \
-	skia_skia_library_gyp
-
-# Enable grouping to fix circular references
-LOCAL_GROUP_STATIC_LIBRARIES := true
-
-LOCAL_SHARED_LIBRARIES := \
-	libstlport \
-	libdl
-
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_platform_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform
-webcore_platform: third_party_WebKit_Source_core_webcore_platform_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform.target.darwin-x86.mk b/Source/core/webcore_platform.target.darwin-x86.mk
deleted file mode 100644
index 693e961..0000000
--- a/Source/core/webcore_platform.target.darwin-x86.mk
+++ /dev/null
@@ -1,411 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_platform_gyp
-LOCAL_MODULE_SUFFIX := .a
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a
-
-GYP_GENERATED_OUTPUTS :=
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-LOCAL_GENERATED_SOURCES :=
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS :=
-
-LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
-	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
-	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
-	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
-	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
-	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-m32 \
-	-mmmx \
-	-march=pentium4 \
-	-msse2 \
-	-mfpmath=sse \
-	-fuse-ld=gold \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-fno-stack-protector \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-m32 \
-	-mmmx \
-	-march=pentium4 \
-	-msse2 \
-	-mfpmath=sse \
-	-fuse-ld=gold \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-fno-stack-protector \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-
-LOCAL_LDFLAGS_Debug := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-m32 \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--fatal-warnings \
-	-Wl,--gc-sections \
-	-Wl,--warn-shared-textrel \
-	-Wl,-O1 \
-	-Wl,--as-needed
-
-
-LOCAL_LDFLAGS_Release := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-m32 \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,-O1 \
-	-Wl,--as-needed \
-	-Wl,--gc-sections \
-	-Wl,--fatal-warnings \
-	-Wl,--warn-shared-textrel
-
-
-LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
-
-LOCAL_STATIC_LIBRARIES := \
-	skia_skia_library_gyp
-
-# Enable grouping to fix circular references
-LOCAL_GROUP_STATIC_LIBRARIES := true
-
-LOCAL_SHARED_LIBRARIES := \
-	libstlport \
-	libdl
-
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_platform_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform
-webcore_platform: third_party_WebKit_Source_core_webcore_platform_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform.target.linux-arm.mk b/Source/core/webcore_platform.target.linux-arm.mk
deleted file mode 100644
index 1c81dcd..0000000
--- a/Source/core/webcore_platform.target.linux-arm.mk
+++ /dev/null
@@ -1,411 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_platform_gyp
-LOCAL_MODULE_SUFFIX := .a
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a
-
-GYP_GENERATED_OUTPUTS :=
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-LOCAL_GENERATED_SOURCES :=
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS :=
-
-LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
-	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
-	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
-	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
-	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
-	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-fno-tree-sra \
-	-fuse-ld=gold \
-	-Wno-psabi \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-fno-tree-sra \
-	-fuse-ld=gold \
-	-Wno-psabi \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-abi \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-
-LOCAL_LDFLAGS_Debug := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-Wl,-z,relro \
-	-Wl,-z,now \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--icf=safe \
-	-Wl,--fatal-warnings \
-	-Wl,--gc-sections \
-	-Wl,--warn-shared-textrel \
-	-Wl,-O1 \
-	-Wl,--as-needed
-
-
-LOCAL_LDFLAGS_Release := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-Wl,-z,relro \
-	-Wl,-z,now \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--icf=safe \
-	-Wl,-O1 \
-	-Wl,--as-needed \
-	-Wl,--gc-sections \
-	-Wl,--fatal-warnings \
-	-Wl,--warn-shared-textrel
-
-
-LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
-
-LOCAL_STATIC_LIBRARIES := \
-	skia_skia_library_gyp
-
-# Enable grouping to fix circular references
-LOCAL_GROUP_STATIC_LIBRARIES := true
-
-LOCAL_SHARED_LIBRARIES := \
-	libstlport \
-	libdl
-
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_platform_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform
-webcore_platform: third_party_WebKit_Source_core_webcore_platform_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform.target.linux-mips.mk b/Source/core/webcore_platform.target.linux-mips.mk
deleted file mode 100644
index 4243d24..0000000
--- a/Source/core/webcore_platform.target.linux-mips.mk
+++ /dev/null
@@ -1,405 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_platform_gyp
-LOCAL_MODULE_SUFFIX := .a
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a
-
-GYP_GENERATED_OUTPUTS :=
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-LOCAL_GENERATED_SOURCES :=
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS :=
-
-LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
-	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
-	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
-	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
-	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
-	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-EL \
-	-mhard-float \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	-fstack-protector \
-	--param=ssp-buffer-size=4 \
-	 \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-EL \
-	-mhard-float \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fstack-protector \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-
-LOCAL_LDFLAGS_Debug := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-EL \
-	-Wl,--no-keep-memory \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--fatal-warnings \
-	-Wl,--gc-sections \
-	-Wl,--warn-shared-textrel \
-	-Wl,-O1 \
-	-Wl,--as-needed
-
-
-LOCAL_LDFLAGS_Release := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-EL \
-	-Wl,--no-keep-memory \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,-O1 \
-	-Wl,--as-needed \
-	-Wl,--gc-sections \
-	-Wl,--fatal-warnings \
-	-Wl,--warn-shared-textrel
-
-
-LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
-
-LOCAL_STATIC_LIBRARIES := \
-	skia_skia_library_gyp
-
-# Enable grouping to fix circular references
-LOCAL_GROUP_STATIC_LIBRARIES := true
-
-LOCAL_SHARED_LIBRARIES := \
-	libstlport \
-	libdl
-
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_platform_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform
-webcore_platform: third_party_WebKit_Source_core_webcore_platform_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_platform.target.linux-x86.mk b/Source/core/webcore_platform.target.linux-x86.mk
deleted file mode 100644
index 693e961..0000000
--- a/Source/core/webcore_platform.target.linux-x86.mk
+++ /dev/null
@@ -1,411 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_CLASS := STATIC_LIBRARIES
-LOCAL_MODULE := third_party_WebKit_Source_core_webcore_platform_gyp
-LOCAL_MODULE_SUFFIX := .a
-LOCAL_MODULE_TAGS := optional
-gyp_intermediate_dir := $(call local-intermediates-dir)
-gyp_shared_intermediate_dir := $(call intermediates-dir-for,GYP,shared)
-
-# Make sure our deps are built first.
-GYP_TARGET_DEPENDENCIES := \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,skia_skia_library_gyp)/skia_skia_library_gyp.a
-
-GYP_GENERATED_OUTPUTS :=
-
-# Make sure our deps and generated files are built first.
-LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) $(GYP_GENERATED_OUTPUTS)
-
-LOCAL_GENERATED_SOURCES :=
-
-GYP_COPIED_SOURCE_ORIGIN_DIRS :=
-
-LOCAL_SRC_FILES := \
-	third_party/WebKit/Source/core/platform/DragImage.cpp \
-	third_party/WebKit/Source/core/platform/Pasteboard.cpp \
-	third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
-	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
-	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp \
-	third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp \
-	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
-	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
-	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
-	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
-	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Debug := \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-m32 \
-	-mmmx \
-	-march=pentium4 \
-	-msse2 \
-	-mfpmath=sse \
-	-fuse-ld=gold \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-fno-stack-protector \
-	-Os \
-	-g \
-	-fomit-frame-pointer \
-	-fdata-sections \
-	-ffunction-sections
-
-MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=1' \
-	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
-	'-D_DEBUG'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Debug := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Debug := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-# Flags passed to both C and C++ files.
-MY_CFLAGS_Release := \
-	--param=ssp-buffer-size=4 \
-	-Werror \
-	-fno-exceptions \
-	-fno-strict-aliasing \
-	-Wall \
-	-Wno-unused-parameter \
-	-Wno-missing-field-initializers \
-	-fvisibility=hidden \
-	-pipe \
-	-fPIC \
-	-m32 \
-	-mmmx \
-	-march=pentium4 \
-	-msse2 \
-	-mfpmath=sse \
-	-fuse-ld=gold \
-	-ffunction-sections \
-	-funwind-tables \
-	-g \
-	-fno-short-enums \
-	-finline-limit=64 \
-	-Wa,--noexecstack \
-	-U_FORTIFY_SOURCE \
-	-Wno-extra \
-	-Wno-ignored-qualifiers \
-	-Wno-type-limits \
-	-fno-stack-protector \
-	-Os \
-	-fno-ident \
-	-fdata-sections \
-	-ffunction-sections \
-	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
-
-MY_DEFS_Release := \
-	'-DANGLE_DX11' \
-	'-DV8_DEPRECATION_WARNINGS' \
-	'-D_FILE_OFFSET_BITS=64' \
-	'-DNO_TCMALLOC' \
-	'-DDISABLE_NACL' \
-	'-DCHROMIUM_BUILD' \
-	'-DUSE_LIBJPEG_TURBO=1' \
-	'-DUSE_PROPRIETARY_CODECS' \
-	'-DENABLE_CONFIGURATION_POLICY' \
-	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
-	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
-	'-DUSE_OPENSSL=1' \
-	'-DENABLE_EGLIMAGE=1' \
-	'-DCLD_VERSION=1' \
-	'-DENABLE_PRINTING=1' \
-	'-DENABLE_MANAGED_USERS=1' \
-	'-DBLINK_IMPLEMENTATION=1' \
-	'-DINSIDE_BLINK' \
-	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_SVG_FONTS=1' \
-	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
-	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
-	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
-	'-DENABLE_INPUT_SPEECH=0' \
-	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
-	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
-	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DU_USING_ICU_NAMESPACE=0' \
-	'-DSK_ENABLE_INST_COUNT=0' \
-	'-DSK_SUPPORT_GPU=1' \
-	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
-	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
-	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
-	'-DGR_GL_IGNORE_ES3_MSAA=0' \
-	'-DSK_BUILD_FOR_ANDROID' \
-	'-DSK_USE_POSIX_THREADS' \
-	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
-	'-DCHROME_PNG_WRITE_SUPPORT' \
-	'-DPNG_USER_CONFIG' \
-	'-DLIBXML_STATIC' \
-	'-DLIBXSLT_STATIC' \
-	'-D__STDC_CONSTANT_MACROS' \
-	'-D__STDC_FORMAT_MACROS' \
-	'-DANDROID' \
-	'-D__GNU_SOURCE=1' \
-	'-DUSE_STLPORT=1' \
-	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
-	'-DCHROME_BUILD_ID=""' \
-	'-DNDEBUG' \
-	'-DNVALGRIND' \
-	'-DDYNAMIC_ANNOTATIONS_ENABLED=0' \
-	'-D_FORTIFY_SOURCE=2'
-
-
-# Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES_Release := \
-	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
-	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
-	$(LOCAL_PATH)/third_party/WebKit/Source \
-	$(LOCAL_PATH) \
-	$(LOCAL_PATH)/skia/config \
-	$(LOCAL_PATH)/third_party/khronos \
-	$(LOCAL_PATH)/gpu \
-	$(LOCAL_PATH)/third_party/WebKit \
-	$(gyp_shared_intermediate_dir)/blink \
-	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
-	$(PWD)/external/icu4c/common \
-	$(PWD)/external/icu4c/i18n \
-	$(LOCAL_PATH)/third_party/skia/src/core \
-	$(LOCAL_PATH)/third_party/skia/include/core \
-	$(LOCAL_PATH)/third_party/skia/include/effects \
-	$(LOCAL_PATH)/third_party/skia/include/pdf \
-	$(LOCAL_PATH)/third_party/skia/include/gpu \
-	$(LOCAL_PATH)/third_party/skia/include/lazy \
-	$(LOCAL_PATH)/third_party/skia/include/pathops \
-	$(LOCAL_PATH)/third_party/skia/include/pipe \
-	$(LOCAL_PATH)/third_party/skia/include/ports \
-	$(LOCAL_PATH)/third_party/skia/include/utils \
-	$(LOCAL_PATH)/skia/ext \
-	$(LOCAL_PATH)/third_party/iccjpeg \
-	$(LOCAL_PATH)/third_party/libpng \
-	$(LOCAL_PATH)/third_party/libwebp \
-	$(LOCAL_PATH)/third_party/libxml/linux/include \
-	$(LOCAL_PATH)/third_party/libxml/src/include \
-	$(LOCAL_PATH)/third_party/libxslt \
-	$(LOCAL_PATH)/third_party/npapi \
-	$(LOCAL_PATH)/third_party/npapi/bindings \
-	$(LOCAL_PATH)/third_party/ots/include \
-	$(LOCAL_PATH)/third_party/qcms/src \
-	$(LOCAL_PATH)/third_party/sqlite \
-	$(LOCAL_PATH)/third_party/zlib \
-	$(LOCAL_PATH)/v8/include \
-	$(PWD)/frameworks/wilhelm/include \
-	$(PWD)/bionic \
-	$(PWD)/external/stlport/stlport
-
-
-# Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS_Release := \
-	-fno-rtti \
-	-fno-threadsafe-statics \
-	-fvisibility-inlines-hidden \
-	-Wsign-compare \
-	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
-	-Wno-non-virtual-dtor \
-	-Wno-sign-promo
-
-
-LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
-LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
-### Rules for final target.
-
-LOCAL_LDFLAGS_Debug := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-m32 \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,--fatal-warnings \
-	-Wl,--gc-sections \
-	-Wl,--warn-shared-textrel \
-	-Wl,-O1 \
-	-Wl,--as-needed
-
-
-LOCAL_LDFLAGS_Release := \
-	-Wl,-z,now \
-	-Wl,-z,relro \
-	-Wl,-z,noexecstack \
-	-fPIC \
-	-m32 \
-	-fuse-ld=gold \
-	-nostdlib \
-	-Wl,--no-undefined \
-	-Wl,--exclude-libs=ALL \
-	-Wl,-O1 \
-	-Wl,--as-needed \
-	-Wl,--gc-sections \
-	-Wl,--fatal-warnings \
-	-Wl,--warn-shared-textrel
-
-
-LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
-
-LOCAL_STATIC_LIBRARIES := \
-	skia_skia_library_gyp
-
-# Enable grouping to fix circular references
-LOCAL_GROUP_STATIC_LIBRARIES := true
-
-LOCAL_SHARED_LIBRARIES := \
-	libstlport \
-	libdl
-
-# Add target alias to "gyp_all_modules" target.
-.PHONY: gyp_all_modules
-gyp_all_modules: third_party_WebKit_Source_core_webcore_platform_gyp
-
-# Alias gyp target name.
-.PHONY: webcore_platform
-webcore_platform: third_party_WebKit_Source_core_webcore_platform_gyp
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/Source/core/webcore_prerequisites.target.darwin-arm.mk b/Source/core/webcore_prerequisites.target.darwin-arm.mk
index 4006ff8..f378660 100644
--- a/Source/core/webcore_prerequisites.target.darwin-arm.mk
+++ b/Source/core/webcore_prerequisites.target.darwin-arm.mk
@@ -18,15 +18,15 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_heap_blink_heap_gyp)/third_party_WebKit_Source_heap_blink_heap_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_src_translator_gyp)/third_party_angle_src_translator_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_iccjpeg_iccjpeg_gyp)/third_party_iccjpeg_iccjpeg_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_libpng_libpng_gyp)/third_party_libpng_libpng_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
diff --git a/Source/core/webcore_prerequisites.target.darwin-mips.mk b/Source/core/webcore_prerequisites.target.darwin-mips.mk
index 4006ff8..f378660 100644
--- a/Source/core/webcore_prerequisites.target.darwin-mips.mk
+++ b/Source/core/webcore_prerequisites.target.darwin-mips.mk
@@ -18,15 +18,15 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_heap_blink_heap_gyp)/third_party_WebKit_Source_heap_blink_heap_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_src_translator_gyp)/third_party_angle_src_translator_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_iccjpeg_iccjpeg_gyp)/third_party_iccjpeg_iccjpeg_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_libpng_libpng_gyp)/third_party_libpng_libpng_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
diff --git a/Source/core/webcore_prerequisites.target.darwin-x86.mk b/Source/core/webcore_prerequisites.target.darwin-x86.mk
index 4006ff8..f378660 100644
--- a/Source/core/webcore_prerequisites.target.darwin-x86.mk
+++ b/Source/core/webcore_prerequisites.target.darwin-x86.mk
@@ -18,15 +18,15 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_heap_blink_heap_gyp)/third_party_WebKit_Source_heap_blink_heap_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_src_translator_gyp)/third_party_angle_src_translator_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_iccjpeg_iccjpeg_gyp)/third_party_iccjpeg_iccjpeg_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_libpng_libpng_gyp)/third_party_libpng_libpng_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
diff --git a/Source/core/webcore_prerequisites.target.linux-arm.mk b/Source/core/webcore_prerequisites.target.linux-arm.mk
index 4006ff8..f378660 100644
--- a/Source/core/webcore_prerequisites.target.linux-arm.mk
+++ b/Source/core/webcore_prerequisites.target.linux-arm.mk
@@ -18,15 +18,15 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_heap_blink_heap_gyp)/third_party_WebKit_Source_heap_blink_heap_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_src_translator_gyp)/third_party_angle_src_translator_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_iccjpeg_iccjpeg_gyp)/third_party_iccjpeg_iccjpeg_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_libpng_libpng_gyp)/third_party_libpng_libpng_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
diff --git a/Source/core/webcore_prerequisites.target.linux-mips.mk b/Source/core/webcore_prerequisites.target.linux-mips.mk
index 4006ff8..f378660 100644
--- a/Source/core/webcore_prerequisites.target.linux-mips.mk
+++ b/Source/core/webcore_prerequisites.target.linux-mips.mk
@@ -18,15 +18,15 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_heap_blink_heap_gyp)/third_party_WebKit_Source_heap_blink_heap_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_src_translator_gyp)/third_party_angle_src_translator_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_iccjpeg_iccjpeg_gyp)/third_party_iccjpeg_iccjpeg_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_libpng_libpng_gyp)/third_party_libpng_libpng_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
diff --git a/Source/core/webcore_prerequisites.target.linux-x86.mk b/Source/core/webcore_prerequisites.target.linux-x86.mk
index 4006ff8..f378660 100644
--- a/Source/core/webcore_prerequisites.target.linux-x86.mk
+++ b/Source/core/webcore_prerequisites.target.linux-x86.mk
@@ -18,15 +18,15 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_derived_sources_gyp)/make_core_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_generated_bindings_gyp)/generated_bindings.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_core_generated_gyp)/make_core_generated.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_heap_blink_heap_gyp)/third_party_WebKit_Source_heap_blink_heap_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_platform_blink_platform_gyp)/third_party_WebKit_Source_platform_blink_platform_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,gpu_gles2_c_lib_gyp)/gpu_gles2_c_lib_gyp.a \
 	$(call intermediates-dir-for,GYP,skia_skia_gyp)/skia.stamp \
-	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_dx11_src_translator_gyp)/third_party_angle_dx11_src_translator_gyp.a \
+	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_angle_src_translator_gyp)/third_party_angle_src_translator_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_iccjpeg_iccjpeg_gyp)/third_party_iccjpeg_iccjpeg_gyp.a \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_libpng_libpng_gyp)/third_party_libpng_libpng_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_libwebp_libwebp_gyp)/webp.stamp \
diff --git a/Source/core/webcore_remaining.target.darwin-arm.mk b/Source/core/webcore_remaining.target.darwin-arm.mk
index 3638375..32d8a9c 100644
--- a/Source/core/webcore_remaining.target.darwin-arm.mk
+++ b/Source/core/webcore_remaining.target.darwin-arm.mk
@@ -75,17 +75,29 @@
 	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
+	third_party/WebKit/Source/core/animation/AnimationTranslationUtil.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
+	third_party/WebKit/Source/core/animation/ElementAnimation.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
-	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
+	third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
+	third_party/WebKit/Source/core/animation/TimedItemTiming.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationData.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationDataList.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPropertyAnimation.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
+	third_party/WebKit/Source/core/clipboard/Clipboard.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObject.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItemList.cpp \
+	third_party/WebKit/Source/core/clipboard/Pasteboard.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp \
@@ -112,7 +124,7 @@
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
-	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
@@ -122,11 +134,10 @@
 	third_party/WebKit/Source/core/css/CSSInitialValue.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp \
-	third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp \
 	third_party/WebKit/Source/core/css/CSSMatrix.cpp \
+	third_party/WebKit/Source/core/css/CSSMarkup.cpp \
 	third_party/WebKit/Source/core/css/CSSMediaRule.cpp \
-	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
 	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
@@ -135,20 +146,16 @@
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
 	third_party/WebKit/Source/core/css/CSSPropertySourceData.cpp \
 	third_party/WebKit/Source/core/css/CSSReflectValue.cpp \
-	third_party/WebKit/Source/core/css/CSSRegionRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRuleList.cpp \
+	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp \
-	third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp \
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
-	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
 	third_party/WebKit/Source/core/css/CSSShadowValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
-	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp \
 	third_party/WebKit/Source/core/css/CSSTransformValue.cpp \
@@ -156,15 +163,15 @@
 	third_party/WebKit/Source/core/css/CSSValue.cpp \
 	third_party/WebKit/Source/core/css/CSSValueList.cpp \
 	third_party/WebKit/Source/core/css/CSSValuePool.cpp \
-	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
+	third_party/WebKit/Source/core/css/Counter.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
-	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
+	third_party/WebKit/Source/core/css/FontFaceCache.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
-	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
 	third_party/WebKit/Source/core/css/MediaFeatureNames.cpp \
 	third_party/WebKit/Source/core/css/MediaList.cpp \
 	third_party/WebKit/Source/core/css/MediaQuery.cpp \
@@ -174,10 +181,12 @@
 	third_party/WebKit/Source/core/css/MediaQueryListListener.cpp \
 	third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp \
 	third_party/WebKit/Source/core/css/PageRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/Pair.cpp \
 	third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/RGBColor.cpp \
 	third_party/WebKit/Source/core/css/RuleFeature.cpp \
 	third_party/WebKit/Source/core/css/RuleSet.cpp \
+	third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSParser.cpp \
 	third_party/WebKit/Source/core/css/SelectorChecker.cpp \
@@ -194,14 +203,15 @@
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
 	third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/analyzer/DescendantInvalidationSet.cpp \
 	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp \
-	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
+	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
@@ -224,6 +234,7 @@
 	third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/EditCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditingBehavior.cpp \
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
@@ -241,7 +252,6 @@
 	third_party/WebKit/Source/core/editing/InsertTextCommand.cpp \
 	third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp \
 	third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp \
-	third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp \
 	third_party/WebKit/Source/core/editing/MoveSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/PlainTextRange.cpp \
 	third_party/WebKit/Source/core/editing/RemoveCSSPropertyCommand.cpp \
@@ -252,12 +262,10 @@
 	third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp \
-	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
-	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
+	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeContainingElementCommand.cpp \
@@ -274,28 +282,26 @@
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
-	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
 	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
 	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
-	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
-	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
 	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
@@ -303,7 +309,35 @@
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
 	third_party/WebKit/Source/core/fileapi/Stream.cpp \
-	third_party/WebKit/Source/core/history/HistoryItem.cpp \
+	third_party/WebKit/Source/core/frame/BarProp.cpp \
+	third_party/WebKit/Source/core/frame/Console.cpp \
+	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
+	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp \
+	third_party/WebKit/Source/core/frame/Frame.cpp \
+	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
+	third_party/WebKit/Source/core/frame/FrameHost.cpp \
+	third_party/WebKit/Source/core/frame/FrameView.cpp \
+	third_party/WebKit/Source/core/frame/History.cpp \
+	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
+	third_party/WebKit/Source/core/frame/Location.cpp \
+	third_party/WebKit/Source/core/frame/Navigator.cpp \
+	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/PageConsole.cpp \
+	third_party/WebKit/Source/core/frame/Screen.cpp \
+	third_party/WebKit/Source/core/frame/Settings.cpp \
+	third_party/WebKit/Source/core/frame/SettingsDelegate.cpp \
+	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
 	third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp \
@@ -316,7 +350,6 @@
 	third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptModule.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorBaseAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp \
@@ -328,15 +361,12 @@
 	third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHistory.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp \
+	third_party/WebKit/Source/core/inspector/InspectorInspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp \
@@ -351,8 +381,8 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
+	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
 	third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp \
@@ -379,7 +409,7 @@
 	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
-	third_party/WebKit/Source/core/loader/HistoryController.cpp \
+	third_party/WebKit/Source/core/loader/HistoryItem.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -395,81 +425,44 @@
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridge.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
-	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
-	third_party/WebKit/Source/core/frame/Console.cpp \
-	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
 	third_party/WebKit/Source/core/page/ContextMenuController.cpp \
 	third_party/WebKit/Source/core/page/CreateWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp \
 	third_party/WebKit/Source/core/page/DOMSelection.cpp \
-	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
 	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
-	third_party/WebKit/Source/core/frame/Frame.cpp \
-	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
-	third_party/WebKit/Source/core/frame/FrameView.cpp \
-	third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp \
-	third_party/WebKit/Source/core/frame/History.cpp \
-	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/frame/Location.cpp \
-	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/page/HistoryController.cpp \
+	third_party/WebKit/Source/core/page/InjectedStyleSheets.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
-	third_party/WebKit/Source/core/frame/Navigator.cpp \
-	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/SmartClip.cpp \
 	third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
-	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
 	third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PagePopupClient.cpp \
+	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PageScaleConstraints.cpp \
 	third_party/WebKit/Source/core/page/PageSerializer.cpp \
 	third_party/WebKit/Source/core/page/PageVisibilityState.cpp \
-	third_party/WebKit/Source/core/timing/Performance.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/page/PointerLockController.cpp \
 	third_party/WebKit/Source/core/page/PrintContext.cpp \
-	third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp \
-	third_party/WebKit/Source/core/frame/Screen.cpp \
-	third_party/WebKit/Source/core/page/Settings.cpp \
 	third_party/WebKit/Source/core/page/SpatialNavigation.cpp \
-	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
-	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationController.cpp \
-	third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp \
 	third_party/WebKit/Source/core/plugins/DOMMimeType.cpp \
@@ -482,7 +475,16 @@
 	third_party/WebKit/Source/core/speech/SpeechInputResult.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
+	third_party/WebKit/Source/core/storage/StorageArea.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
+	third_party/WebKit/Source/core/storage/StorageNamespace.cpp \
+	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/timing/Performance.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
@@ -492,18 +494,17 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
 	third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp \
-	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/DOMParser.cpp \
+	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp \
 	third_party/WebKit/Source/core/xml/XMLErrors.cpp \
 	third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp \
@@ -530,7 +531,9 @@
 	third_party/WebKit/Source/core/xml/XSLTExtensions.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessor.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp \
-	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp
+	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -561,14 +564,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -579,7 +583,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -588,17 +591,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -606,13 +606,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -640,7 +642,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -680,7 +682,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -713,14 +714,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -731,7 +733,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -740,17 +741,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -758,13 +756,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -793,7 +793,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -833,7 +833,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_remaining.target.darwin-mips.mk b/Source/core/webcore_remaining.target.darwin-mips.mk
index 7f503c2..ef63598 100644
--- a/Source/core/webcore_remaining.target.darwin-mips.mk
+++ b/Source/core/webcore_remaining.target.darwin-mips.mk
@@ -75,17 +75,29 @@
 	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
+	third_party/WebKit/Source/core/animation/AnimationTranslationUtil.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
+	third_party/WebKit/Source/core/animation/ElementAnimation.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
-	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
+	third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
+	third_party/WebKit/Source/core/animation/TimedItemTiming.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationData.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationDataList.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPropertyAnimation.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
+	third_party/WebKit/Source/core/clipboard/Clipboard.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObject.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItemList.cpp \
+	third_party/WebKit/Source/core/clipboard/Pasteboard.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp \
@@ -112,7 +124,7 @@
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
-	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
@@ -122,11 +134,10 @@
 	third_party/WebKit/Source/core/css/CSSInitialValue.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp \
-	third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp \
 	third_party/WebKit/Source/core/css/CSSMatrix.cpp \
+	third_party/WebKit/Source/core/css/CSSMarkup.cpp \
 	third_party/WebKit/Source/core/css/CSSMediaRule.cpp \
-	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
 	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
@@ -135,20 +146,16 @@
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
 	third_party/WebKit/Source/core/css/CSSPropertySourceData.cpp \
 	third_party/WebKit/Source/core/css/CSSReflectValue.cpp \
-	third_party/WebKit/Source/core/css/CSSRegionRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRuleList.cpp \
+	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp \
-	third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp \
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
-	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
 	third_party/WebKit/Source/core/css/CSSShadowValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
-	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp \
 	third_party/WebKit/Source/core/css/CSSTransformValue.cpp \
@@ -156,15 +163,15 @@
 	third_party/WebKit/Source/core/css/CSSValue.cpp \
 	third_party/WebKit/Source/core/css/CSSValueList.cpp \
 	third_party/WebKit/Source/core/css/CSSValuePool.cpp \
-	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
+	third_party/WebKit/Source/core/css/Counter.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
-	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
+	third_party/WebKit/Source/core/css/FontFaceCache.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
-	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
 	third_party/WebKit/Source/core/css/MediaFeatureNames.cpp \
 	third_party/WebKit/Source/core/css/MediaList.cpp \
 	third_party/WebKit/Source/core/css/MediaQuery.cpp \
@@ -174,10 +181,12 @@
 	third_party/WebKit/Source/core/css/MediaQueryListListener.cpp \
 	third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp \
 	third_party/WebKit/Source/core/css/PageRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/Pair.cpp \
 	third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/RGBColor.cpp \
 	third_party/WebKit/Source/core/css/RuleFeature.cpp \
 	third_party/WebKit/Source/core/css/RuleSet.cpp \
+	third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSParser.cpp \
 	third_party/WebKit/Source/core/css/SelectorChecker.cpp \
@@ -194,14 +203,15 @@
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
 	third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/analyzer/DescendantInvalidationSet.cpp \
 	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp \
-	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
+	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
@@ -224,6 +234,7 @@
 	third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/EditCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditingBehavior.cpp \
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
@@ -241,7 +252,6 @@
 	third_party/WebKit/Source/core/editing/InsertTextCommand.cpp \
 	third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp \
 	third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp \
-	third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp \
 	third_party/WebKit/Source/core/editing/MoveSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/PlainTextRange.cpp \
 	third_party/WebKit/Source/core/editing/RemoveCSSPropertyCommand.cpp \
@@ -252,12 +262,10 @@
 	third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp \
-	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
-	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
+	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeContainingElementCommand.cpp \
@@ -274,28 +282,26 @@
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
-	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
 	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
 	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
-	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
-	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
 	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
@@ -303,7 +309,35 @@
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
 	third_party/WebKit/Source/core/fileapi/Stream.cpp \
-	third_party/WebKit/Source/core/history/HistoryItem.cpp \
+	third_party/WebKit/Source/core/frame/BarProp.cpp \
+	third_party/WebKit/Source/core/frame/Console.cpp \
+	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
+	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp \
+	third_party/WebKit/Source/core/frame/Frame.cpp \
+	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
+	third_party/WebKit/Source/core/frame/FrameHost.cpp \
+	third_party/WebKit/Source/core/frame/FrameView.cpp \
+	third_party/WebKit/Source/core/frame/History.cpp \
+	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
+	third_party/WebKit/Source/core/frame/Location.cpp \
+	third_party/WebKit/Source/core/frame/Navigator.cpp \
+	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/PageConsole.cpp \
+	third_party/WebKit/Source/core/frame/Screen.cpp \
+	third_party/WebKit/Source/core/frame/Settings.cpp \
+	third_party/WebKit/Source/core/frame/SettingsDelegate.cpp \
+	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
 	third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp \
@@ -316,7 +350,6 @@
 	third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptModule.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorBaseAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp \
@@ -328,15 +361,12 @@
 	third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHistory.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp \
+	third_party/WebKit/Source/core/inspector/InspectorInspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp \
@@ -351,8 +381,8 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
+	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
 	third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp \
@@ -379,7 +409,7 @@
 	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
-	third_party/WebKit/Source/core/loader/HistoryController.cpp \
+	third_party/WebKit/Source/core/loader/HistoryItem.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -395,81 +425,44 @@
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridge.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
-	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
-	third_party/WebKit/Source/core/frame/Console.cpp \
-	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
 	third_party/WebKit/Source/core/page/ContextMenuController.cpp \
 	third_party/WebKit/Source/core/page/CreateWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp \
 	third_party/WebKit/Source/core/page/DOMSelection.cpp \
-	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
 	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
-	third_party/WebKit/Source/core/frame/Frame.cpp \
-	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
-	third_party/WebKit/Source/core/frame/FrameView.cpp \
-	third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp \
-	third_party/WebKit/Source/core/frame/History.cpp \
-	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/frame/Location.cpp \
-	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/page/HistoryController.cpp \
+	third_party/WebKit/Source/core/page/InjectedStyleSheets.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
-	third_party/WebKit/Source/core/frame/Navigator.cpp \
-	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/SmartClip.cpp \
 	third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
-	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
 	third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PagePopupClient.cpp \
+	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PageScaleConstraints.cpp \
 	third_party/WebKit/Source/core/page/PageSerializer.cpp \
 	third_party/WebKit/Source/core/page/PageVisibilityState.cpp \
-	third_party/WebKit/Source/core/timing/Performance.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/page/PointerLockController.cpp \
 	third_party/WebKit/Source/core/page/PrintContext.cpp \
-	third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp \
-	third_party/WebKit/Source/core/frame/Screen.cpp \
-	third_party/WebKit/Source/core/page/Settings.cpp \
 	third_party/WebKit/Source/core/page/SpatialNavigation.cpp \
-	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
-	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationController.cpp \
-	third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp \
 	third_party/WebKit/Source/core/plugins/DOMMimeType.cpp \
@@ -482,7 +475,16 @@
 	third_party/WebKit/Source/core/speech/SpeechInputResult.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
+	third_party/WebKit/Source/core/storage/StorageArea.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
+	third_party/WebKit/Source/core/storage/StorageNamespace.cpp \
+	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/timing/Performance.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
@@ -492,18 +494,17 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
 	third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp \
-	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/DOMParser.cpp \
+	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp \
 	third_party/WebKit/Source/core/xml/XMLErrors.cpp \
 	third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp \
@@ -530,7 +531,9 @@
 	third_party/WebKit/Source/core/xml/XSLTExtensions.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessor.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp \
-	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp
+	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -560,14 +563,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -578,7 +582,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -587,17 +590,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -605,13 +605,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -639,7 +641,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -679,7 +681,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -711,14 +712,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -729,7 +731,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -738,17 +739,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -756,13 +754,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -791,7 +791,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -831,7 +831,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_remaining.target.darwin-x86.mk b/Source/core/webcore_remaining.target.darwin-x86.mk
index 2a23d00..101789b 100644
--- a/Source/core/webcore_remaining.target.darwin-x86.mk
+++ b/Source/core/webcore_remaining.target.darwin-x86.mk
@@ -75,17 +75,29 @@
 	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
+	third_party/WebKit/Source/core/animation/AnimationTranslationUtil.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
+	third_party/WebKit/Source/core/animation/ElementAnimation.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
-	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
+	third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
+	third_party/WebKit/Source/core/animation/TimedItemTiming.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationData.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationDataList.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPropertyAnimation.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
+	third_party/WebKit/Source/core/clipboard/Clipboard.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObject.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItemList.cpp \
+	third_party/WebKit/Source/core/clipboard/Pasteboard.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp \
@@ -112,7 +124,7 @@
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
-	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
@@ -122,11 +134,10 @@
 	third_party/WebKit/Source/core/css/CSSInitialValue.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp \
-	third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp \
 	third_party/WebKit/Source/core/css/CSSMatrix.cpp \
+	third_party/WebKit/Source/core/css/CSSMarkup.cpp \
 	third_party/WebKit/Source/core/css/CSSMediaRule.cpp \
-	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
 	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
@@ -135,20 +146,16 @@
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
 	third_party/WebKit/Source/core/css/CSSPropertySourceData.cpp \
 	third_party/WebKit/Source/core/css/CSSReflectValue.cpp \
-	third_party/WebKit/Source/core/css/CSSRegionRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRuleList.cpp \
+	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp \
-	third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp \
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
-	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
 	third_party/WebKit/Source/core/css/CSSShadowValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
-	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp \
 	third_party/WebKit/Source/core/css/CSSTransformValue.cpp \
@@ -156,15 +163,15 @@
 	third_party/WebKit/Source/core/css/CSSValue.cpp \
 	third_party/WebKit/Source/core/css/CSSValueList.cpp \
 	third_party/WebKit/Source/core/css/CSSValuePool.cpp \
-	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
+	third_party/WebKit/Source/core/css/Counter.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
-	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
+	third_party/WebKit/Source/core/css/FontFaceCache.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
-	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
 	third_party/WebKit/Source/core/css/MediaFeatureNames.cpp \
 	third_party/WebKit/Source/core/css/MediaList.cpp \
 	third_party/WebKit/Source/core/css/MediaQuery.cpp \
@@ -174,10 +181,12 @@
 	third_party/WebKit/Source/core/css/MediaQueryListListener.cpp \
 	third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp \
 	third_party/WebKit/Source/core/css/PageRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/Pair.cpp \
 	third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/RGBColor.cpp \
 	third_party/WebKit/Source/core/css/RuleFeature.cpp \
 	third_party/WebKit/Source/core/css/RuleSet.cpp \
+	third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSParser.cpp \
 	third_party/WebKit/Source/core/css/SelectorChecker.cpp \
@@ -194,14 +203,15 @@
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
 	third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/analyzer/DescendantInvalidationSet.cpp \
 	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp \
-	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
+	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
@@ -224,6 +234,7 @@
 	third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/EditCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditingBehavior.cpp \
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
@@ -241,7 +252,6 @@
 	third_party/WebKit/Source/core/editing/InsertTextCommand.cpp \
 	third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp \
 	third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp \
-	third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp \
 	third_party/WebKit/Source/core/editing/MoveSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/PlainTextRange.cpp \
 	third_party/WebKit/Source/core/editing/RemoveCSSPropertyCommand.cpp \
@@ -252,12 +262,10 @@
 	third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp \
-	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
-	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
+	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeContainingElementCommand.cpp \
@@ -274,28 +282,26 @@
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
-	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
 	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
 	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
-	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
-	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
 	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
@@ -303,7 +309,35 @@
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
 	third_party/WebKit/Source/core/fileapi/Stream.cpp \
-	third_party/WebKit/Source/core/history/HistoryItem.cpp \
+	third_party/WebKit/Source/core/frame/BarProp.cpp \
+	third_party/WebKit/Source/core/frame/Console.cpp \
+	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
+	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp \
+	third_party/WebKit/Source/core/frame/Frame.cpp \
+	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
+	third_party/WebKit/Source/core/frame/FrameHost.cpp \
+	third_party/WebKit/Source/core/frame/FrameView.cpp \
+	third_party/WebKit/Source/core/frame/History.cpp \
+	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
+	third_party/WebKit/Source/core/frame/Location.cpp \
+	third_party/WebKit/Source/core/frame/Navigator.cpp \
+	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/PageConsole.cpp \
+	third_party/WebKit/Source/core/frame/Screen.cpp \
+	third_party/WebKit/Source/core/frame/Settings.cpp \
+	third_party/WebKit/Source/core/frame/SettingsDelegate.cpp \
+	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
 	third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp \
@@ -316,7 +350,6 @@
 	third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptModule.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorBaseAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp \
@@ -328,15 +361,12 @@
 	third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHistory.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp \
+	third_party/WebKit/Source/core/inspector/InspectorInspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp \
@@ -351,8 +381,8 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
+	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
 	third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp \
@@ -379,7 +409,7 @@
 	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
-	third_party/WebKit/Source/core/loader/HistoryController.cpp \
+	third_party/WebKit/Source/core/loader/HistoryItem.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -395,81 +425,44 @@
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridge.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
-	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
-	third_party/WebKit/Source/core/frame/Console.cpp \
-	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
 	third_party/WebKit/Source/core/page/ContextMenuController.cpp \
 	third_party/WebKit/Source/core/page/CreateWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp \
 	third_party/WebKit/Source/core/page/DOMSelection.cpp \
-	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
 	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
-	third_party/WebKit/Source/core/frame/Frame.cpp \
-	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
-	third_party/WebKit/Source/core/frame/FrameView.cpp \
-	third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp \
-	third_party/WebKit/Source/core/frame/History.cpp \
-	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/frame/Location.cpp \
-	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/page/HistoryController.cpp \
+	third_party/WebKit/Source/core/page/InjectedStyleSheets.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
-	third_party/WebKit/Source/core/frame/Navigator.cpp \
-	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/SmartClip.cpp \
 	third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
-	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
 	third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PagePopupClient.cpp \
+	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PageScaleConstraints.cpp \
 	third_party/WebKit/Source/core/page/PageSerializer.cpp \
 	third_party/WebKit/Source/core/page/PageVisibilityState.cpp \
-	third_party/WebKit/Source/core/timing/Performance.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/page/PointerLockController.cpp \
 	third_party/WebKit/Source/core/page/PrintContext.cpp \
-	third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp \
-	third_party/WebKit/Source/core/frame/Screen.cpp \
-	third_party/WebKit/Source/core/page/Settings.cpp \
 	third_party/WebKit/Source/core/page/SpatialNavigation.cpp \
-	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
-	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationController.cpp \
-	third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp \
 	third_party/WebKit/Source/core/plugins/DOMMimeType.cpp \
@@ -482,7 +475,16 @@
 	third_party/WebKit/Source/core/speech/SpeechInputResult.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
+	third_party/WebKit/Source/core/storage/StorageArea.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
+	third_party/WebKit/Source/core/storage/StorageNamespace.cpp \
+	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/timing/Performance.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
@@ -492,18 +494,17 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
 	third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp \
-	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/DOMParser.cpp \
+	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp \
 	third_party/WebKit/Source/core/xml/XMLErrors.cpp \
 	third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp \
@@ -530,7 +531,9 @@
 	third_party/WebKit/Source/core/xml/XSLTExtensions.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessor.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp \
-	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp
+	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -562,15 +565,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -581,7 +585,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -590,17 +593,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -608,13 +608,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -642,7 +644,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -681,7 +683,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -715,17 +716,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -736,7 +736,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -745,17 +744,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -763,13 +759,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -798,7 +796,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -837,7 +835,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_remaining.target.linux-arm.mk b/Source/core/webcore_remaining.target.linux-arm.mk
index 3638375..32d8a9c 100644
--- a/Source/core/webcore_remaining.target.linux-arm.mk
+++ b/Source/core/webcore_remaining.target.linux-arm.mk
@@ -75,17 +75,29 @@
 	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
+	third_party/WebKit/Source/core/animation/AnimationTranslationUtil.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
+	third_party/WebKit/Source/core/animation/ElementAnimation.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
-	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
+	third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
+	third_party/WebKit/Source/core/animation/TimedItemTiming.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationData.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationDataList.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPropertyAnimation.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
+	third_party/WebKit/Source/core/clipboard/Clipboard.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObject.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItemList.cpp \
+	third_party/WebKit/Source/core/clipboard/Pasteboard.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp \
@@ -112,7 +124,7 @@
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
-	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
@@ -122,11 +134,10 @@
 	third_party/WebKit/Source/core/css/CSSInitialValue.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp \
-	third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp \
 	third_party/WebKit/Source/core/css/CSSMatrix.cpp \
+	third_party/WebKit/Source/core/css/CSSMarkup.cpp \
 	third_party/WebKit/Source/core/css/CSSMediaRule.cpp \
-	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
 	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
@@ -135,20 +146,16 @@
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
 	third_party/WebKit/Source/core/css/CSSPropertySourceData.cpp \
 	third_party/WebKit/Source/core/css/CSSReflectValue.cpp \
-	third_party/WebKit/Source/core/css/CSSRegionRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRuleList.cpp \
+	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp \
-	third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp \
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
-	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
 	third_party/WebKit/Source/core/css/CSSShadowValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
-	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp \
 	third_party/WebKit/Source/core/css/CSSTransformValue.cpp \
@@ -156,15 +163,15 @@
 	third_party/WebKit/Source/core/css/CSSValue.cpp \
 	third_party/WebKit/Source/core/css/CSSValueList.cpp \
 	third_party/WebKit/Source/core/css/CSSValuePool.cpp \
-	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
+	third_party/WebKit/Source/core/css/Counter.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
-	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
+	third_party/WebKit/Source/core/css/FontFaceCache.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
-	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
 	third_party/WebKit/Source/core/css/MediaFeatureNames.cpp \
 	third_party/WebKit/Source/core/css/MediaList.cpp \
 	third_party/WebKit/Source/core/css/MediaQuery.cpp \
@@ -174,10 +181,12 @@
 	third_party/WebKit/Source/core/css/MediaQueryListListener.cpp \
 	third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp \
 	third_party/WebKit/Source/core/css/PageRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/Pair.cpp \
 	third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/RGBColor.cpp \
 	third_party/WebKit/Source/core/css/RuleFeature.cpp \
 	third_party/WebKit/Source/core/css/RuleSet.cpp \
+	third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSParser.cpp \
 	third_party/WebKit/Source/core/css/SelectorChecker.cpp \
@@ -194,14 +203,15 @@
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
 	third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/analyzer/DescendantInvalidationSet.cpp \
 	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp \
-	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
+	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
@@ -224,6 +234,7 @@
 	third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/EditCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditingBehavior.cpp \
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
@@ -241,7 +252,6 @@
 	third_party/WebKit/Source/core/editing/InsertTextCommand.cpp \
 	third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp \
 	third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp \
-	third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp \
 	third_party/WebKit/Source/core/editing/MoveSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/PlainTextRange.cpp \
 	third_party/WebKit/Source/core/editing/RemoveCSSPropertyCommand.cpp \
@@ -252,12 +262,10 @@
 	third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp \
-	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
-	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
+	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeContainingElementCommand.cpp \
@@ -274,28 +282,26 @@
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
-	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
 	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
 	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
-	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
-	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
 	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
@@ -303,7 +309,35 @@
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
 	third_party/WebKit/Source/core/fileapi/Stream.cpp \
-	third_party/WebKit/Source/core/history/HistoryItem.cpp \
+	third_party/WebKit/Source/core/frame/BarProp.cpp \
+	third_party/WebKit/Source/core/frame/Console.cpp \
+	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
+	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp \
+	third_party/WebKit/Source/core/frame/Frame.cpp \
+	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
+	third_party/WebKit/Source/core/frame/FrameHost.cpp \
+	third_party/WebKit/Source/core/frame/FrameView.cpp \
+	third_party/WebKit/Source/core/frame/History.cpp \
+	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
+	third_party/WebKit/Source/core/frame/Location.cpp \
+	third_party/WebKit/Source/core/frame/Navigator.cpp \
+	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/PageConsole.cpp \
+	third_party/WebKit/Source/core/frame/Screen.cpp \
+	third_party/WebKit/Source/core/frame/Settings.cpp \
+	third_party/WebKit/Source/core/frame/SettingsDelegate.cpp \
+	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
 	third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp \
@@ -316,7 +350,6 @@
 	third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptModule.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorBaseAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp \
@@ -328,15 +361,12 @@
 	third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHistory.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp \
+	third_party/WebKit/Source/core/inspector/InspectorInspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp \
@@ -351,8 +381,8 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
+	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
 	third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp \
@@ -379,7 +409,7 @@
 	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
-	third_party/WebKit/Source/core/loader/HistoryController.cpp \
+	third_party/WebKit/Source/core/loader/HistoryItem.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -395,81 +425,44 @@
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridge.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
-	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
-	third_party/WebKit/Source/core/frame/Console.cpp \
-	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
 	third_party/WebKit/Source/core/page/ContextMenuController.cpp \
 	third_party/WebKit/Source/core/page/CreateWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp \
 	third_party/WebKit/Source/core/page/DOMSelection.cpp \
-	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
 	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
-	third_party/WebKit/Source/core/frame/Frame.cpp \
-	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
-	third_party/WebKit/Source/core/frame/FrameView.cpp \
-	third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp \
-	third_party/WebKit/Source/core/frame/History.cpp \
-	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/frame/Location.cpp \
-	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/page/HistoryController.cpp \
+	third_party/WebKit/Source/core/page/InjectedStyleSheets.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
-	third_party/WebKit/Source/core/frame/Navigator.cpp \
-	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/SmartClip.cpp \
 	third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
-	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
 	third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PagePopupClient.cpp \
+	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PageScaleConstraints.cpp \
 	third_party/WebKit/Source/core/page/PageSerializer.cpp \
 	third_party/WebKit/Source/core/page/PageVisibilityState.cpp \
-	third_party/WebKit/Source/core/timing/Performance.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/page/PointerLockController.cpp \
 	third_party/WebKit/Source/core/page/PrintContext.cpp \
-	third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp \
-	third_party/WebKit/Source/core/frame/Screen.cpp \
-	third_party/WebKit/Source/core/page/Settings.cpp \
 	third_party/WebKit/Source/core/page/SpatialNavigation.cpp \
-	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
-	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationController.cpp \
-	third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp \
 	third_party/WebKit/Source/core/plugins/DOMMimeType.cpp \
@@ -482,7 +475,16 @@
 	third_party/WebKit/Source/core/speech/SpeechInputResult.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
+	third_party/WebKit/Source/core/storage/StorageArea.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
+	third_party/WebKit/Source/core/storage/StorageNamespace.cpp \
+	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/timing/Performance.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
@@ -492,18 +494,17 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
 	third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp \
-	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/DOMParser.cpp \
+	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp \
 	third_party/WebKit/Source/core/xml/XMLErrors.cpp \
 	third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp \
@@ -530,7 +531,9 @@
 	third_party/WebKit/Source/core/xml/XSLTExtensions.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessor.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp \
-	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp
+	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -561,14 +564,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -579,7 +583,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -588,17 +591,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -606,13 +606,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -640,7 +642,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -680,7 +682,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -713,14 +714,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -731,7 +733,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -740,17 +741,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -758,13 +756,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -793,7 +793,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -833,7 +833,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_remaining.target.linux-mips.mk b/Source/core/webcore_remaining.target.linux-mips.mk
index 7f503c2..ef63598 100644
--- a/Source/core/webcore_remaining.target.linux-mips.mk
+++ b/Source/core/webcore_remaining.target.linux-mips.mk
@@ -75,17 +75,29 @@
 	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
+	third_party/WebKit/Source/core/animation/AnimationTranslationUtil.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
+	third_party/WebKit/Source/core/animation/ElementAnimation.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
-	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
+	third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
+	third_party/WebKit/Source/core/animation/TimedItemTiming.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationData.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationDataList.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPropertyAnimation.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
+	third_party/WebKit/Source/core/clipboard/Clipboard.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObject.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItemList.cpp \
+	third_party/WebKit/Source/core/clipboard/Pasteboard.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp \
@@ -112,7 +124,7 @@
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
-	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
@@ -122,11 +134,10 @@
 	third_party/WebKit/Source/core/css/CSSInitialValue.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp \
-	third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp \
 	third_party/WebKit/Source/core/css/CSSMatrix.cpp \
+	third_party/WebKit/Source/core/css/CSSMarkup.cpp \
 	third_party/WebKit/Source/core/css/CSSMediaRule.cpp \
-	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
 	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
@@ -135,20 +146,16 @@
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
 	third_party/WebKit/Source/core/css/CSSPropertySourceData.cpp \
 	third_party/WebKit/Source/core/css/CSSReflectValue.cpp \
-	third_party/WebKit/Source/core/css/CSSRegionRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRuleList.cpp \
+	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp \
-	third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp \
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
-	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
 	third_party/WebKit/Source/core/css/CSSShadowValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
-	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp \
 	third_party/WebKit/Source/core/css/CSSTransformValue.cpp \
@@ -156,15 +163,15 @@
 	third_party/WebKit/Source/core/css/CSSValue.cpp \
 	third_party/WebKit/Source/core/css/CSSValueList.cpp \
 	third_party/WebKit/Source/core/css/CSSValuePool.cpp \
-	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
+	third_party/WebKit/Source/core/css/Counter.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
-	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
+	third_party/WebKit/Source/core/css/FontFaceCache.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
-	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
 	third_party/WebKit/Source/core/css/MediaFeatureNames.cpp \
 	third_party/WebKit/Source/core/css/MediaList.cpp \
 	third_party/WebKit/Source/core/css/MediaQuery.cpp \
@@ -174,10 +181,12 @@
 	third_party/WebKit/Source/core/css/MediaQueryListListener.cpp \
 	third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp \
 	third_party/WebKit/Source/core/css/PageRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/Pair.cpp \
 	third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/RGBColor.cpp \
 	third_party/WebKit/Source/core/css/RuleFeature.cpp \
 	third_party/WebKit/Source/core/css/RuleSet.cpp \
+	third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSParser.cpp \
 	third_party/WebKit/Source/core/css/SelectorChecker.cpp \
@@ -194,14 +203,15 @@
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
 	third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/analyzer/DescendantInvalidationSet.cpp \
 	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp \
-	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
+	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
@@ -224,6 +234,7 @@
 	third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/EditCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditingBehavior.cpp \
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
@@ -241,7 +252,6 @@
 	third_party/WebKit/Source/core/editing/InsertTextCommand.cpp \
 	third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp \
 	third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp \
-	third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp \
 	third_party/WebKit/Source/core/editing/MoveSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/PlainTextRange.cpp \
 	third_party/WebKit/Source/core/editing/RemoveCSSPropertyCommand.cpp \
@@ -252,12 +262,10 @@
 	third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp \
-	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
-	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
+	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeContainingElementCommand.cpp \
@@ -274,28 +282,26 @@
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
-	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
 	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
 	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
-	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
-	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
 	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
@@ -303,7 +309,35 @@
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
 	third_party/WebKit/Source/core/fileapi/Stream.cpp \
-	third_party/WebKit/Source/core/history/HistoryItem.cpp \
+	third_party/WebKit/Source/core/frame/BarProp.cpp \
+	third_party/WebKit/Source/core/frame/Console.cpp \
+	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
+	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp \
+	third_party/WebKit/Source/core/frame/Frame.cpp \
+	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
+	third_party/WebKit/Source/core/frame/FrameHost.cpp \
+	third_party/WebKit/Source/core/frame/FrameView.cpp \
+	third_party/WebKit/Source/core/frame/History.cpp \
+	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
+	third_party/WebKit/Source/core/frame/Location.cpp \
+	third_party/WebKit/Source/core/frame/Navigator.cpp \
+	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/PageConsole.cpp \
+	third_party/WebKit/Source/core/frame/Screen.cpp \
+	third_party/WebKit/Source/core/frame/Settings.cpp \
+	third_party/WebKit/Source/core/frame/SettingsDelegate.cpp \
+	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
 	third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp \
@@ -316,7 +350,6 @@
 	third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptModule.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorBaseAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp \
@@ -328,15 +361,12 @@
 	third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHistory.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp \
+	third_party/WebKit/Source/core/inspector/InspectorInspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp \
@@ -351,8 +381,8 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
+	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
 	third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp \
@@ -379,7 +409,7 @@
 	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
-	third_party/WebKit/Source/core/loader/HistoryController.cpp \
+	third_party/WebKit/Source/core/loader/HistoryItem.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -395,81 +425,44 @@
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridge.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
-	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
-	third_party/WebKit/Source/core/frame/Console.cpp \
-	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
 	third_party/WebKit/Source/core/page/ContextMenuController.cpp \
 	third_party/WebKit/Source/core/page/CreateWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp \
 	third_party/WebKit/Source/core/page/DOMSelection.cpp \
-	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
 	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
-	third_party/WebKit/Source/core/frame/Frame.cpp \
-	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
-	third_party/WebKit/Source/core/frame/FrameView.cpp \
-	third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp \
-	third_party/WebKit/Source/core/frame/History.cpp \
-	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/frame/Location.cpp \
-	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/page/HistoryController.cpp \
+	third_party/WebKit/Source/core/page/InjectedStyleSheets.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
-	third_party/WebKit/Source/core/frame/Navigator.cpp \
-	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/SmartClip.cpp \
 	third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
-	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
 	third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PagePopupClient.cpp \
+	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PageScaleConstraints.cpp \
 	third_party/WebKit/Source/core/page/PageSerializer.cpp \
 	third_party/WebKit/Source/core/page/PageVisibilityState.cpp \
-	third_party/WebKit/Source/core/timing/Performance.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/page/PointerLockController.cpp \
 	third_party/WebKit/Source/core/page/PrintContext.cpp \
-	third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp \
-	third_party/WebKit/Source/core/frame/Screen.cpp \
-	third_party/WebKit/Source/core/page/Settings.cpp \
 	third_party/WebKit/Source/core/page/SpatialNavigation.cpp \
-	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
-	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationController.cpp \
-	third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp \
 	third_party/WebKit/Source/core/plugins/DOMMimeType.cpp \
@@ -482,7 +475,16 @@
 	third_party/WebKit/Source/core/speech/SpeechInputResult.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
+	third_party/WebKit/Source/core/storage/StorageArea.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
+	third_party/WebKit/Source/core/storage/StorageNamespace.cpp \
+	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/timing/Performance.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
@@ -492,18 +494,17 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
 	third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp \
-	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/DOMParser.cpp \
+	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp \
 	third_party/WebKit/Source/core/xml/XMLErrors.cpp \
 	third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp \
@@ -530,7 +531,9 @@
 	third_party/WebKit/Source/core/xml/XSLTExtensions.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessor.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp \
-	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp
+	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -560,14 +563,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -578,7 +582,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -587,17 +590,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -605,13 +605,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -639,7 +641,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -679,7 +681,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -711,14 +712,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -729,7 +731,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -738,17 +739,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -756,13 +754,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -791,7 +791,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -831,7 +831,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_remaining.target.linux-x86.mk b/Source/core/webcore_remaining.target.linux-x86.mk
index 2a23d00..101789b 100644
--- a/Source/core/webcore_remaining.target.linux-x86.mk
+++ b/Source/core/webcore_remaining.target.linux-x86.mk
@@ -75,17 +75,29 @@
 	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/AnimationStack.cpp \
+	third_party/WebKit/Source/core/animation/AnimationTranslationUtil.cpp \
 	third_party/WebKit/Source/core/animation/CompositorAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentAnimations.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
+	third_party/WebKit/Source/core/animation/ElementAnimation.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
-	third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp \
+	third_party/WebKit/Source/core/animation/KeyframeEffectModel.cpp \
 	third_party/WebKit/Source/core/animation/Player.cpp \
 	third_party/WebKit/Source/core/animation/TimedItem.cpp \
+	third_party/WebKit/Source/core/animation/TimedItemTiming.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationData.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSAnimationDataList.cpp \
 	third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp \
+	third_party/WebKit/Source/core/animation/css/CSSPropertyAnimation.cpp \
 	third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp \
+	third_party/WebKit/Source/core/clipboard/Clipboard.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObject.cpp \
+	third_party/WebKit/Source/core/clipboard/DataObjectItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItem.cpp \
+	third_party/WebKit/Source/core/clipboard/DataTransferItemList.cpp \
+	third_party/WebKit/Source/core/clipboard/Pasteboard.cpp \
 	third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp \
@@ -112,7 +124,7 @@
 	third_party/WebKit/Source/core/css/CSSFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGradientValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp \
-	third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp \
+	third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.cpp \
 	third_party/WebKit/Source/core/css/CSSGroupingRule.cpp \
 	third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp \
 	third_party/WebKit/Source/core/css/CSSImageSetValue.cpp \
@@ -122,11 +134,10 @@
 	third_party/WebKit/Source/core/css/CSSInitialValue.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp \
 	third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp \
-	third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp \
 	third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp \
 	third_party/WebKit/Source/core/css/CSSMatrix.cpp \
+	third_party/WebKit/Source/core/css/CSSMarkup.cpp \
 	third_party/WebKit/Source/core/css/CSSMediaRule.cpp \
-	third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSOMUtils.cpp \
 	third_party/WebKit/Source/core/css/CSSPageRule.cpp \
 	third_party/WebKit/Source/core/css/CSSParserMode.cpp \
@@ -135,20 +146,16 @@
 	third_party/WebKit/Source/core/css/CSSProperty.cpp \
 	third_party/WebKit/Source/core/css/CSSPropertySourceData.cpp \
 	third_party/WebKit/Source/core/css/CSSReflectValue.cpp \
-	third_party/WebKit/Source/core/css/CSSRegionRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRule.cpp \
 	third_party/WebKit/Source/core/css/CSSRuleList.cpp \
+	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp \
-	third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp \
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
-	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
 	third_party/WebKit/Source/core/css/CSSShadowValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
-	third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp \
 	third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp \
 	third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp \
 	third_party/WebKit/Source/core/css/CSSTransformValue.cpp \
@@ -156,15 +163,15 @@
 	third_party/WebKit/Source/core/css/CSSValue.cpp \
 	third_party/WebKit/Source/core/css/CSSValueList.cpp \
 	third_party/WebKit/Source/core/css/CSSValuePool.cpp \
-	third_party/WebKit/Source/core/css/CSSVariablesMap.cpp \
 	third_party/WebKit/Source/core/css/CSSViewportRule.cpp \
+	third_party/WebKit/Source/core/css/Counter.cpp \
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
-	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontFace.cpp \
+	third_party/WebKit/Source/core/css/FontFaceCache.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
-	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
 	third_party/WebKit/Source/core/css/MediaFeatureNames.cpp \
 	third_party/WebKit/Source/core/css/MediaList.cpp \
 	third_party/WebKit/Source/core/css/MediaQuery.cpp \
@@ -174,10 +181,12 @@
 	third_party/WebKit/Source/core/css/MediaQueryListListener.cpp \
 	third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp \
 	third_party/WebKit/Source/core/css/PageRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/Pair.cpp \
 	third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/RGBColor.cpp \
 	third_party/WebKit/Source/core/css/RuleFeature.cpp \
 	third_party/WebKit/Source/core/css/RuleSet.cpp \
+	third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/SVGCSSParser.cpp \
 	third_party/WebKit/Source/core/css/SelectorChecker.cpp \
@@ -194,14 +203,15 @@
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
 	third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp \
+	third_party/WebKit/Source/core/css/analyzer/DescendantInvalidationSet.cpp \
 	third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp \
 	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp \
-	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/MatchResult.cpp \
+	third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp \
 	third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp \
@@ -224,6 +234,7 @@
 	third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/EditCommand.cpp \
+	third_party/WebKit/Source/core/editing/EditingBehavior.cpp \
 	third_party/WebKit/Source/core/editing/EditingStyle.cpp \
 	third_party/WebKit/Source/core/editing/Editor.cpp \
 	third_party/WebKit/Source/core/editing/EditorCommand.cpp \
@@ -241,7 +252,6 @@
 	third_party/WebKit/Source/core/editing/InsertTextCommand.cpp \
 	third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp \
 	third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp \
-	third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp \
 	third_party/WebKit/Source/core/editing/MoveSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/PlainTextRange.cpp \
 	third_party/WebKit/Source/core/editing/RemoveCSSPropertyCommand.cpp \
@@ -252,12 +262,10 @@
 	third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp \
-	third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp \
 	third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp \
 	third_party/WebKit/Source/core/editing/SmartReplaceICU.cpp \
-	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp \
-	third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp \
+	third_party/WebKit/Source/core/editing/SpellChecker.cpp \
 	third_party/WebKit/Source/core/editing/SplitElementCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp \
 	third_party/WebKit/Source/core/editing/SplitTextNodeContainingElementCommand.cpp \
@@ -274,28 +282,26 @@
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
-	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
 	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
 	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
+	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
-	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
-	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
-	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
 	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
@@ -303,7 +309,35 @@
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
 	third_party/WebKit/Source/core/fileapi/Stream.cpp \
-	third_party/WebKit/Source/core/history/HistoryItem.cpp \
+	third_party/WebKit/Source/core/frame/BarProp.cpp \
+	third_party/WebKit/Source/core/frame/Console.cpp \
+	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
+	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
+	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
+	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringCompositingUpdate.cpp \
+	third_party/WebKit/Source/core/frame/DeprecatedScheduleStyleRecalcDuringLayout.cpp \
+	third_party/WebKit/Source/core/frame/Frame.cpp \
+	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
+	third_party/WebKit/Source/core/frame/FrameHost.cpp \
+	third_party/WebKit/Source/core/frame/FrameView.cpp \
+	third_party/WebKit/Source/core/frame/History.cpp \
+	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
+	third_party/WebKit/Source/core/frame/Location.cpp \
+	third_party/WebKit/Source/core/frame/Navigator.cpp \
+	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/PageConsole.cpp \
+	third_party/WebKit/Source/core/frame/Screen.cpp \
+	third_party/WebKit/Source/core/frame/Settings.cpp \
+	third_party/WebKit/Source/core/frame/SettingsDelegate.cpp \
+	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
+	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
 	third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp \
@@ -316,7 +350,6 @@
 	third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp \
 	third_party/WebKit/Source/core/inspector/InjectedScriptModule.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorBaseAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp \
@@ -328,15 +361,12 @@
 	third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorHistory.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp \
+	third_party/WebKit/Source/core/inspector/InspectorInspectorAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp \
@@ -351,8 +381,8 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
-	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
+	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
 	third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp \
@@ -379,7 +409,7 @@
 	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
-	third_party/WebKit/Source/core/loader/HistoryController.cpp \
+	third_party/WebKit/Source/core/loader/HistoryItem.cpp \
 	third_party/WebKit/Source/core/loader/ImageLoader.cpp \
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
@@ -395,81 +425,44 @@
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridge.cpp \
+	third_party/WebKit/Source/core/loader/WorkerLoaderClientBridgeSyncHelper.cpp \
 	third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp \
 	third_party/WebKit/Source/core/page/AutoscrollController.cpp \
-	third_party/WebKit/Source/core/frame/BarProp.cpp \
 	third_party/WebKit/Source/core/page/Chrome.cpp \
-	third_party/WebKit/Source/core/frame/Console.cpp \
-	third_party/WebKit/Source/core/frame/ConsoleBase.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp \
-	third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp \
 	third_party/WebKit/Source/core/page/ContextMenuController.cpp \
 	third_party/WebKit/Source/core/page/CreateWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp \
 	third_party/WebKit/Source/core/page/DOMSelection.cpp \
-	third_party/WebKit/Source/core/frame/DOMTimer.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindow.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp \
 	third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp \
-	third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp \
 	third_party/WebKit/Source/core/page/DragController.cpp \
 	third_party/WebKit/Source/core/page/DragData.cpp \
 	third_party/WebKit/Source/core/page/EventHandler.cpp \
 	third_party/WebKit/Source/core/page/EventSource.cpp \
 	third_party/WebKit/Source/core/page/FocusController.cpp \
-	third_party/WebKit/Source/core/frame/Frame.cpp \
-	third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
-	third_party/WebKit/Source/core/frame/FrameView.cpp \
-	third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp \
-	third_party/WebKit/Source/core/frame/History.cpp \
-	third_party/WebKit/Source/core/frame/ImageBitmap.cpp \
-	third_party/WebKit/Source/core/frame/Location.cpp \
-	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/page/HistoryController.cpp \
+	third_party/WebKit/Source/core/page/InjectedStyleSheets.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
-	third_party/WebKit/Source/core/frame/Navigator.cpp \
-	third_party/WebKit/Source/core/frame/NavigatorID.cpp \
+	third_party/WebKit/Source/core/frame/SmartClip.cpp \
 	third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
-	third_party/WebKit/Source/core/page/PageConsole.cpp \
 	third_party/WebKit/Source/core/page/PageGroup.cpp \
 	third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp \
-	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PagePopupClient.cpp \
+	third_party/WebKit/Source/core/page/PagePopupController.cpp \
 	third_party/WebKit/Source/core/page/PageScaleConstraints.cpp \
 	third_party/WebKit/Source/core/page/PageSerializer.cpp \
 	third_party/WebKit/Source/core/page/PageVisibilityState.cpp \
-	third_party/WebKit/Source/core/timing/Performance.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
-	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/page/PointerLockController.cpp \
 	third_party/WebKit/Source/core/page/PrintContext.cpp \
-	third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp \
-	third_party/WebKit/Source/core/frame/Screen.cpp \
-	third_party/WebKit/Source/core/page/Settings.cpp \
 	third_party/WebKit/Source/core/page/SpatialNavigation.cpp \
-	third_party/WebKit/Source/core/frame/SuspendableTimer.cpp \
 	third_party/WebKit/Source/core/page/TouchAdjustment.cpp \
 	third_party/WebKit/Source/core/page/TouchDisambiguation.cpp \
-	third_party/WebKit/Source/core/frame/UseCounter.cpp \
 	third_party/WebKit/Source/core/page/WindowFeatures.cpp \
 	third_party/WebKit/Source/core/page/WindowFocusAllowedIndicator.cpp \
-	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp \
-	third_party/WebKit/Source/core/frame/animation/AnimationController.cpp \
-	third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp \
-	third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.cpp \
 	third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp \
 	third_party/WebKit/Source/core/plugins/DOMMimeType.cpp \
@@ -482,7 +475,16 @@
 	third_party/WebKit/Source/core/speech/SpeechInputResult.cpp \
 	third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
+	third_party/WebKit/Source/core/storage/StorageArea.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
+	third_party/WebKit/Source/core/storage/StorageNamespace.cpp \
+	third_party/WebKit/Source/core/timing/MemoryInfo.cpp \
+	third_party/WebKit/Source/core/timing/Performance.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceEntry.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceTiming.cpp \
+	third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
@@ -492,18 +494,17 @@
 	third_party/WebKit/Source/core/workers/Worker.cpp \
 	third_party/WebKit/Source/core/workers/WorkerConsole.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
-	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerNavigator.cpp \
 	third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
 	third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
-	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp \
-	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/DOMParser.cpp \
+	third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp \
 	third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp \
 	third_party/WebKit/Source/core/xml/XMLErrors.cpp \
 	third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp \
@@ -530,7 +531,9 @@
 	third_party/WebKit/Source/core/xml/XSLTExtensions.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessor.cpp \
 	third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp \
-	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp
+	third_party/WebKit/Source/core/xml/XSLTUnicodeSort.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp \
+	third_party/WebKit/Source/core/xml/parser/XMLDocumentParserScope.cpp
 
 
 # Flags passed to both C and C++ files.
@@ -562,15 +565,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -581,7 +585,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -590,17 +593,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -608,13 +608,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -642,7 +644,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -681,7 +683,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -715,17 +716,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -736,7 +736,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -745,17 +744,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -763,13 +759,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -798,7 +796,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -837,7 +835,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_rendering.target.darwin-arm.mk b/Source/core/webcore_rendering.target.darwin-arm.mk
index e02686e..af08054 100644
--- a/Source/core/webcore_rendering.target.darwin-arm.mk
+++ b/Source/core/webcore_rendering.target.darwin-arm.mk
@@ -26,7 +26,6 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
-	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
@@ -37,21 +36,17 @@
 	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp \
-	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
-	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestLocation.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestResult.cpp \
+	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
+	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/InlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
-	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
-	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
-	third_party/WebKit/Source/core/rendering/Pagination.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
@@ -73,8 +68,8 @@
 	third_party/WebKit/Source/core/rendering/RenderFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFullScreen.cpp \
-	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp \
+	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp \
 	third_party/WebKit/Source/core/rendering/RenderIFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderImage.cpp \
@@ -83,15 +78,16 @@
 	third_party/WebKit/Source/core/rendering/RenderInline.cpp \
 	third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayer.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerBlendInfo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -105,8 +101,6 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderPart.cpp \
@@ -149,10 +143,14 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
-	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
+	third_party/WebKit/Source/core/rendering/ScrollAlignment.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
+	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
-	third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp \
+	third_party/WebKit/Source/core/rendering/line/BreakingContext.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineBreaker.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineWidth.cpp \
+	third_party/WebKit/Source/core/rendering/line/TrailingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
@@ -173,12 +171,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowList.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFilterData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleGeneratedImage.cpp \
@@ -221,14 +216,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -239,7 +235,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -248,17 +243,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -266,13 +258,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -300,7 +294,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -340,7 +334,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -372,14 +365,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -390,7 +384,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -399,17 +392,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -417,13 +407,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -452,7 +444,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -492,7 +484,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_rendering.target.darwin-mips.mk b/Source/core/webcore_rendering.target.darwin-mips.mk
index 9012ce7..5dee352 100644
--- a/Source/core/webcore_rendering.target.darwin-mips.mk
+++ b/Source/core/webcore_rendering.target.darwin-mips.mk
@@ -26,7 +26,6 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
-	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
@@ -37,21 +36,17 @@
 	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp \
-	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
-	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestLocation.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestResult.cpp \
+	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
+	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/InlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
-	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
-	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
-	third_party/WebKit/Source/core/rendering/Pagination.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
@@ -73,8 +68,8 @@
 	third_party/WebKit/Source/core/rendering/RenderFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFullScreen.cpp \
-	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp \
+	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp \
 	third_party/WebKit/Source/core/rendering/RenderIFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderImage.cpp \
@@ -83,15 +78,16 @@
 	third_party/WebKit/Source/core/rendering/RenderInline.cpp \
 	third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayer.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerBlendInfo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -105,8 +101,6 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderPart.cpp \
@@ -149,10 +143,14 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
-	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
+	third_party/WebKit/Source/core/rendering/ScrollAlignment.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
+	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
-	third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp \
+	third_party/WebKit/Source/core/rendering/line/BreakingContext.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineBreaker.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineWidth.cpp \
+	third_party/WebKit/Source/core/rendering/line/TrailingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
@@ -173,12 +171,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowList.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFilterData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleGeneratedImage.cpp \
@@ -220,14 +215,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -238,7 +234,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -247,17 +242,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -265,13 +257,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -299,7 +293,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -339,7 +333,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -370,14 +363,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -388,7 +382,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -397,17 +390,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -415,13 +405,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -450,7 +442,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -490,7 +482,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_rendering.target.darwin-x86.mk b/Source/core/webcore_rendering.target.darwin-x86.mk
index f1e7363..4078373 100644
--- a/Source/core/webcore_rendering.target.darwin-x86.mk
+++ b/Source/core/webcore_rendering.target.darwin-x86.mk
@@ -26,7 +26,6 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
-	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
@@ -37,21 +36,17 @@
 	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp \
-	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
-	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestLocation.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestResult.cpp \
+	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
+	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/InlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
-	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
-	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
-	third_party/WebKit/Source/core/rendering/Pagination.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
@@ -73,8 +68,8 @@
 	third_party/WebKit/Source/core/rendering/RenderFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFullScreen.cpp \
-	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp \
+	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp \
 	third_party/WebKit/Source/core/rendering/RenderIFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderImage.cpp \
@@ -83,15 +78,16 @@
 	third_party/WebKit/Source/core/rendering/RenderInline.cpp \
 	third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayer.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerBlendInfo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -105,8 +101,6 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderPart.cpp \
@@ -149,10 +143,14 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
-	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
+	third_party/WebKit/Source/core/rendering/ScrollAlignment.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
+	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
-	third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp \
+	third_party/WebKit/Source/core/rendering/line/BreakingContext.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineBreaker.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineWidth.cpp \
+	third_party/WebKit/Source/core/rendering/line/TrailingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
@@ -173,12 +171,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowList.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFilterData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleGeneratedImage.cpp \
@@ -223,15 +218,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -242,7 +238,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -251,17 +246,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -269,13 +261,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -303,7 +297,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -342,7 +336,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -376,17 +369,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -397,7 +389,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -406,17 +397,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -424,13 +412,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -459,7 +449,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -498,7 +488,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_rendering.target.linux-arm.mk b/Source/core/webcore_rendering.target.linux-arm.mk
index e02686e..af08054 100644
--- a/Source/core/webcore_rendering.target.linux-arm.mk
+++ b/Source/core/webcore_rendering.target.linux-arm.mk
@@ -26,7 +26,6 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
-	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
@@ -37,21 +36,17 @@
 	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp \
-	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
-	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestLocation.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestResult.cpp \
+	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
+	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/InlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
-	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
-	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
-	third_party/WebKit/Source/core/rendering/Pagination.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
@@ -73,8 +68,8 @@
 	third_party/WebKit/Source/core/rendering/RenderFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFullScreen.cpp \
-	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp \
+	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp \
 	third_party/WebKit/Source/core/rendering/RenderIFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderImage.cpp \
@@ -83,15 +78,16 @@
 	third_party/WebKit/Source/core/rendering/RenderInline.cpp \
 	third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayer.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerBlendInfo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -105,8 +101,6 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderPart.cpp \
@@ -149,10 +143,14 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
-	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
+	third_party/WebKit/Source/core/rendering/ScrollAlignment.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
+	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
-	third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp \
+	third_party/WebKit/Source/core/rendering/line/BreakingContext.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineBreaker.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineWidth.cpp \
+	third_party/WebKit/Source/core/rendering/line/TrailingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
@@ -173,12 +171,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowList.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFilterData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleGeneratedImage.cpp \
@@ -221,14 +216,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -239,7 +235,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -248,17 +243,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -266,13 +258,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -300,7 +294,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -340,7 +334,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -372,14 +365,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -390,7 +384,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -399,17 +392,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -417,13 +407,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -452,7 +444,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -492,7 +484,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_rendering.target.linux-mips.mk b/Source/core/webcore_rendering.target.linux-mips.mk
index 9012ce7..5dee352 100644
--- a/Source/core/webcore_rendering.target.linux-mips.mk
+++ b/Source/core/webcore_rendering.target.linux-mips.mk
@@ -26,7 +26,6 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
-	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
@@ -37,21 +36,17 @@
 	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp \
-	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
-	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestLocation.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestResult.cpp \
+	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
+	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/InlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
-	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
-	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
-	third_party/WebKit/Source/core/rendering/Pagination.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
@@ -73,8 +68,8 @@
 	third_party/WebKit/Source/core/rendering/RenderFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFullScreen.cpp \
-	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp \
+	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp \
 	third_party/WebKit/Source/core/rendering/RenderIFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderImage.cpp \
@@ -83,15 +78,16 @@
 	third_party/WebKit/Source/core/rendering/RenderInline.cpp \
 	third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayer.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerBlendInfo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -105,8 +101,6 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderPart.cpp \
@@ -149,10 +143,14 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
-	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
+	third_party/WebKit/Source/core/rendering/ScrollAlignment.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
+	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
-	third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp \
+	third_party/WebKit/Source/core/rendering/line/BreakingContext.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineBreaker.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineWidth.cpp \
+	third_party/WebKit/Source/core/rendering/line/TrailingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
@@ -173,12 +171,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowList.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFilterData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleGeneratedImage.cpp \
@@ -220,14 +215,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -238,7 +234,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -247,17 +242,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -265,13 +257,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -299,7 +293,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -339,7 +333,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -370,14 +363,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -388,7 +382,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -397,17 +390,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -415,13 +405,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -450,7 +442,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -490,7 +482,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_rendering.target.linux-x86.mk b/Source/core/webcore_rendering.target.linux-x86.mk
index f1e7363..4078373 100644
--- a/Source/core/webcore_rendering.target.linux-x86.mk
+++ b/Source/core/webcore_rendering.target.linux-x86.mk
@@ -26,7 +26,6 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
-	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
@@ -37,21 +36,17 @@
 	third_party/WebKit/Source/core/rendering/FloatingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
 	third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp \
-	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
-	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestLocation.cpp \
 	third_party/WebKit/Source/core/rendering/HitTestResult.cpp \
+	third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp \
+	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/InlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp \
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
-	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
-	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
-	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
-	third_party/WebKit/Source/core/rendering/Pagination.cpp \
+	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
@@ -73,8 +68,8 @@
 	third_party/WebKit/Source/core/rendering/RenderFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderFullScreen.cpp \
-	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp \
+	third_party/WebKit/Source/core/rendering/RenderGrid.cpp \
 	third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp \
 	third_party/WebKit/Source/core/rendering/RenderIFrame.cpp \
 	third_party/WebKit/Source/core/rendering/RenderImage.cpp \
@@ -83,15 +78,16 @@
 	third_party/WebKit/Source/core/rendering/RenderInline.cpp \
 	third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayer.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerBlendInfo.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
+	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp \
-	third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderLineBoxList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderListItem.cpp \
@@ -105,8 +101,6 @@
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp \
-	third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObject.cpp \
 	third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp \
 	third_party/WebKit/Source/core/rendering/RenderPart.cpp \
@@ -149,10 +143,14 @@
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
-	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
+	third_party/WebKit/Source/core/rendering/ScrollAlignment.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
+	third_party/WebKit/Source/core/rendering/TextAutosizer.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
-	third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp \
+	third_party/WebKit/Source/core/rendering/line/BreakingContext.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineBreaker.cpp \
+	third_party/WebKit/Source/core/rendering/line/LineWidth.cpp \
+	third_party/WebKit/Source/core/rendering/line/TrailingObjects.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp \
@@ -173,12 +171,9 @@
 	third_party/WebKit/Source/core/rendering/style/ShadowList.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp \
+	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleFetchedShader.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.cpp \
-	third_party/WebKit/Source/core/rendering/style/StyleDeprecatedFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFilterData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.cpp \
 	third_party/WebKit/Source/core/rendering/style/StyleGeneratedImage.cpp \
@@ -223,15 +218,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -242,7 +238,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -251,17 +246,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -269,13 +261,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -303,7 +297,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -342,7 +336,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -376,17 +369,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -397,7 +389,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -406,17 +397,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -424,13 +412,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -459,7 +449,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -498,7 +488,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_svg.target.darwin-arm.mk b/Source/core/webcore_svg.target.darwin-arm.mk
index 014290d..73b1426 100644
--- a/Source/core/webcore_svg.target.darwin-arm.mk
+++ b/Source/core/webcore_svg.target.darwin-arm.mk
@@ -85,23 +85,16 @@
 	third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedColor.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedLength.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGAnimatedNewPropertyAnimator.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumber.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedPath.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPreserveAspectRatio.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedRect.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedString.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTransformList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTypeAnimator.cpp \
@@ -109,6 +102,7 @@
 	third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGCircleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGColor.cpp \
@@ -116,13 +110,13 @@
 	third_party/WebKit/Source/core/svg/SVGCursorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDefsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDescElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGDiscardElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocument.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp \
 	third_party/WebKit/Source/core/svg/SVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp \
@@ -169,10 +163,12 @@
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
-	third_party/WebKit/Source/core/svg/SVGLangSpace.cpp \
+	third_party/WebKit/Source/core/svg/SVGInteger.cpp \
+	third_party/WebKit/Source/core/svg/SVGIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGLength.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthContext.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
@@ -180,6 +176,9 @@
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberOptionalNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPaint.cpp \
 	third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp \
@@ -197,18 +196,26 @@
 	third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp \
 	third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp \
 	third_party/WebKit/Source/core/svg/SVGPatternElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGPoint.cpp \
+	third_party/WebKit/Source/core/svg/SVGPointTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGPointList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolyElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp \
+	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatioTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRect.cpp \
 	third_party/WebKit/Source/core/svg/SVGRectElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRectTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGSVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGScriptElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSetElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGStaticStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStopElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGString.cpp \
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
+	third_party/WebKit/Source/core/svg/SVGStringListTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
@@ -234,11 +241,14 @@
 	third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp \
 	third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp \
+	third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGAnimatedProperty.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGPropertyTearOff.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -271,14 +281,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -289,7 +300,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -298,17 +308,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -316,13 +323,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -350,7 +359,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -390,7 +399,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -422,14 +430,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -440,7 +449,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -449,17 +457,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -467,13 +472,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -502,7 +509,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -542,7 +549,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_svg.target.darwin-mips.mk b/Source/core/webcore_svg.target.darwin-mips.mk
index c776885..86b1983 100644
--- a/Source/core/webcore_svg.target.darwin-mips.mk
+++ b/Source/core/webcore_svg.target.darwin-mips.mk
@@ -85,23 +85,16 @@
 	third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedColor.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedLength.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGAnimatedNewPropertyAnimator.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumber.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedPath.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPreserveAspectRatio.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedRect.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedString.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTransformList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTypeAnimator.cpp \
@@ -109,6 +102,7 @@
 	third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGCircleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGColor.cpp \
@@ -116,13 +110,13 @@
 	third_party/WebKit/Source/core/svg/SVGCursorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDefsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDescElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGDiscardElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocument.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp \
 	third_party/WebKit/Source/core/svg/SVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp \
@@ -169,10 +163,12 @@
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
-	third_party/WebKit/Source/core/svg/SVGLangSpace.cpp \
+	third_party/WebKit/Source/core/svg/SVGInteger.cpp \
+	third_party/WebKit/Source/core/svg/SVGIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGLength.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthContext.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
@@ -180,6 +176,9 @@
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberOptionalNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPaint.cpp \
 	third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp \
@@ -197,18 +196,26 @@
 	third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp \
 	third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp \
 	third_party/WebKit/Source/core/svg/SVGPatternElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGPoint.cpp \
+	third_party/WebKit/Source/core/svg/SVGPointTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGPointList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolyElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp \
+	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatioTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRect.cpp \
 	third_party/WebKit/Source/core/svg/SVGRectElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRectTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGSVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGScriptElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSetElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGStaticStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStopElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGString.cpp \
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
+	third_party/WebKit/Source/core/svg/SVGStringListTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
@@ -234,11 +241,14 @@
 	third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp \
 	third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp \
+	third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGAnimatedProperty.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGPropertyTearOff.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -270,14 +280,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -288,7 +299,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -297,17 +307,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -315,13 +322,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -349,7 +358,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -389,7 +398,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -420,14 +428,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -438,7 +447,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -447,17 +455,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -465,13 +470,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -500,7 +507,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -540,7 +547,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_svg.target.darwin-x86.mk b/Source/core/webcore_svg.target.darwin-x86.mk
index 0c11453..1d1888f 100644
--- a/Source/core/webcore_svg.target.darwin-x86.mk
+++ b/Source/core/webcore_svg.target.darwin-x86.mk
@@ -85,23 +85,16 @@
 	third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedColor.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedLength.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGAnimatedNewPropertyAnimator.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumber.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedPath.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPreserveAspectRatio.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedRect.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedString.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTransformList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTypeAnimator.cpp \
@@ -109,6 +102,7 @@
 	third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGCircleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGColor.cpp \
@@ -116,13 +110,13 @@
 	third_party/WebKit/Source/core/svg/SVGCursorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDefsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDescElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGDiscardElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocument.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp \
 	third_party/WebKit/Source/core/svg/SVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp \
@@ -169,10 +163,12 @@
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
-	third_party/WebKit/Source/core/svg/SVGLangSpace.cpp \
+	third_party/WebKit/Source/core/svg/SVGInteger.cpp \
+	third_party/WebKit/Source/core/svg/SVGIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGLength.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthContext.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
@@ -180,6 +176,9 @@
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberOptionalNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPaint.cpp \
 	third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp \
@@ -197,18 +196,26 @@
 	third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp \
 	third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp \
 	third_party/WebKit/Source/core/svg/SVGPatternElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGPoint.cpp \
+	third_party/WebKit/Source/core/svg/SVGPointTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGPointList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolyElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp \
+	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatioTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRect.cpp \
 	third_party/WebKit/Source/core/svg/SVGRectElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRectTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGSVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGScriptElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSetElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGStaticStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStopElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGString.cpp \
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
+	third_party/WebKit/Source/core/svg/SVGStringListTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
@@ -234,11 +241,14 @@
 	third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp \
 	third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp \
+	third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGAnimatedProperty.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGPropertyTearOff.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -272,15 +282,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -291,7 +302,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -300,17 +310,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -318,13 +325,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -352,7 +361,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -391,7 +400,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -424,17 +432,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -445,7 +452,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -454,17 +460,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -472,13 +475,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -507,7 +512,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -546,7 +551,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_svg.target.linux-arm.mk b/Source/core/webcore_svg.target.linux-arm.mk
index 014290d..73b1426 100644
--- a/Source/core/webcore_svg.target.linux-arm.mk
+++ b/Source/core/webcore_svg.target.linux-arm.mk
@@ -85,23 +85,16 @@
 	third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedColor.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedLength.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGAnimatedNewPropertyAnimator.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumber.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedPath.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPreserveAspectRatio.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedRect.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedString.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTransformList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTypeAnimator.cpp \
@@ -109,6 +102,7 @@
 	third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGCircleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGColor.cpp \
@@ -116,13 +110,13 @@
 	third_party/WebKit/Source/core/svg/SVGCursorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDefsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDescElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGDiscardElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocument.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp \
 	third_party/WebKit/Source/core/svg/SVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp \
@@ -169,10 +163,12 @@
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
-	third_party/WebKit/Source/core/svg/SVGLangSpace.cpp \
+	third_party/WebKit/Source/core/svg/SVGInteger.cpp \
+	third_party/WebKit/Source/core/svg/SVGIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGLength.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthContext.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
@@ -180,6 +176,9 @@
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberOptionalNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPaint.cpp \
 	third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp \
@@ -197,18 +196,26 @@
 	third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp \
 	third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp \
 	third_party/WebKit/Source/core/svg/SVGPatternElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGPoint.cpp \
+	third_party/WebKit/Source/core/svg/SVGPointTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGPointList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolyElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp \
+	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatioTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRect.cpp \
 	third_party/WebKit/Source/core/svg/SVGRectElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRectTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGSVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGScriptElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSetElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGStaticStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStopElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGString.cpp \
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
+	third_party/WebKit/Source/core/svg/SVGStringListTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
@@ -234,11 +241,14 @@
 	third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp \
 	third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp \
+	third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGAnimatedProperty.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGPropertyTearOff.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -271,14 +281,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -289,7 +300,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -298,17 +308,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -316,13 +323,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -350,7 +359,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -390,7 +399,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -422,14 +430,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -440,7 +449,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -449,17 +457,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -467,13 +472,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -502,7 +509,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -542,7 +549,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-abi \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_svg.target.linux-mips.mk b/Source/core/webcore_svg.target.linux-mips.mk
index c776885..86b1983 100644
--- a/Source/core/webcore_svg.target.linux-mips.mk
+++ b/Source/core/webcore_svg.target.linux-mips.mk
@@ -85,23 +85,16 @@
 	third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedColor.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedLength.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGAnimatedNewPropertyAnimator.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumber.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedPath.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPreserveAspectRatio.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedRect.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedString.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTransformList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTypeAnimator.cpp \
@@ -109,6 +102,7 @@
 	third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGCircleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGColor.cpp \
@@ -116,13 +110,13 @@
 	third_party/WebKit/Source/core/svg/SVGCursorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDefsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDescElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGDiscardElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocument.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp \
 	third_party/WebKit/Source/core/svg/SVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp \
@@ -169,10 +163,12 @@
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
-	third_party/WebKit/Source/core/svg/SVGLangSpace.cpp \
+	third_party/WebKit/Source/core/svg/SVGInteger.cpp \
+	third_party/WebKit/Source/core/svg/SVGIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGLength.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthContext.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
@@ -180,6 +176,9 @@
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberOptionalNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPaint.cpp \
 	third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp \
@@ -197,18 +196,26 @@
 	third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp \
 	third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp \
 	third_party/WebKit/Source/core/svg/SVGPatternElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGPoint.cpp \
+	third_party/WebKit/Source/core/svg/SVGPointTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGPointList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolyElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp \
+	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatioTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRect.cpp \
 	third_party/WebKit/Source/core/svg/SVGRectElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRectTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGSVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGScriptElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSetElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGStaticStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStopElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGString.cpp \
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
+	third_party/WebKit/Source/core/svg/SVGStringListTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
@@ -234,11 +241,14 @@
 	third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp \
 	third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp \
+	third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGAnimatedProperty.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGPropertyTearOff.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -270,14 +280,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -288,7 +299,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -297,17 +307,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -315,13 +322,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -349,7 +358,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -389,7 +398,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -420,14 +428,15 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
-	-fomit-frame-pointer
+	-fomit-frame-pointer \
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -438,7 +447,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -447,17 +455,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -465,13 +470,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -500,7 +507,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -540,7 +547,6 @@
 	-Wsign-compare \
 	-Wno-c++0x-compat \
 	-Wno-uninitialized \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/webcore_svg.target.linux-x86.mk b/Source/core/webcore_svg.target.linux-x86.mk
index 0c11453..1d1888f 100644
--- a/Source/core/webcore_svg.target.linux-x86.mk
+++ b/Source/core/webcore_svg.target.linux-x86.mk
@@ -85,23 +85,16 @@
 	third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedColor.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedLength.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGAnimatedNewPropertyAnimator.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumber.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedNumberOptionalNumber.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedPath.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedPreserveAspectRatio.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedRect.cpp \
-	third_party/WebKit/Source/core/svg/SVGAnimatedString.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTransformList.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimatedTypeAnimator.cpp \
@@ -109,6 +102,7 @@
 	third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGBoolean.cpp \
 	third_party/WebKit/Source/core/svg/SVGCircleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGColor.cpp \
@@ -116,13 +110,13 @@
 	third_party/WebKit/Source/core/svg/SVGCursorElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDefsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDescElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGDiscardElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocument.cpp \
 	third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp \
 	third_party/WebKit/Source/core/svg/SVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp \
@@ -169,10 +163,12 @@
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
-	third_party/WebKit/Source/core/svg/SVGLangSpace.cpp \
+	third_party/WebKit/Source/core/svg/SVGInteger.cpp \
+	third_party/WebKit/Source/core/svg/SVGIntegerOptionalInteger.cpp \
 	third_party/WebKit/Source/core/svg/SVGLength.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthContext.cpp \
 	third_party/WebKit/Source/core/svg/SVGLengthList.cpp \
+	third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGLineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMPathElement.cpp \
@@ -180,6 +176,9 @@
 	third_party/WebKit/Source/core/svg/SVGMaskElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberOptionalNumber.cpp \
+	third_party/WebKit/Source/core/svg/SVGNumberTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGNumberList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPaint.cpp \
 	third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp \
@@ -197,18 +196,26 @@
 	third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp \
 	third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp \
 	third_party/WebKit/Source/core/svg/SVGPatternElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGPoint.cpp \
+	third_party/WebKit/Source/core/svg/SVGPointTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGPointList.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolyElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp \
+	third_party/WebKit/Source/core/svg/SVGPreserveAspectRatioTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRect.cpp \
 	third_party/WebKit/Source/core/svg/SVGRectElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGRectTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGSVGElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGScriptElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSetElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGStaticStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStopElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGString.cpp \
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
+	third_party/WebKit/Source/core/svg/SVGStringListTearOff.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
@@ -234,11 +241,14 @@
 	third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp \
 	third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp \
+	third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.cpp \
 	third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGAnimatedProperty.cpp \
+	third_party/WebKit/Source/core/svg/properties/NewSVGPropertyTearOff.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGAttributeToPropertyMap.cpp \
 	third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -272,15 +282,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-g \
 	-fomit-frame-pointer \
 	-fdata-sections \
-	-ffunction-sections
+	-ffunction-sections \
+	-funwind-tables
 
 MY_DEFS_Debug := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -291,7 +302,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -300,17 +310,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -318,13 +325,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -352,7 +361,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -391,7 +400,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
@@ -424,17 +432,16 @@
 	-Wno-extra \
 	-Wno-ignored-qualifiers \
 	-Wno-type-limits \
+	-Wno-unused-but-set-variable \
 	-fno-stack-protector \
 	-Os \
 	-fno-ident \
 	-fdata-sections \
 	-ffunction-sections \
 	-fomit-frame-pointer \
-	-fno-unwind-tables \
-	-fno-asynchronous-unwind-tables
+	-funwind-tables
 
 MY_DEFS_Release := \
-	'-DANGLE_DX11' \
 	'-DV8_DEPRECATION_WARNINGS' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -445,7 +452,6 @@
 	'-DENABLE_CONFIGURATION_POLICY' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
 	'-DSYSTEM_NATIVELY_SIGNALS_MEMORY_PRESSURE' \
-	'-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
@@ -454,17 +460,14 @@
 	'-DBLINK_IMPLEMENTATION=1' \
 	'-DINSIDE_BLINK' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
-	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=0' \
 	'-DENABLE_HARFBUZZ_ON_WINDOWS=1' \
-	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_ORIENTATION_EVENTS=1' \
-	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
@@ -472,13 +475,15 @@
 	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
 	'-DSK_ENABLE_LEGACY_API_ALIASING=1' \
 	'-DSK_ATTR_DEPRECATED=SK_NOTHING_ARG1' \
-	'-DSK_SUPPORT_LEGACY_COLORTYPE=1' \
 	'-DGR_GL_IGNORE_ES3_MSAA=0' \
+	'-DSK_SUPPORT_LEGACY_COMPATIBLEDEVICE_CONFIG=1' \
+	'-DSK_SUPPORT_LEGACY_PUBLICEFFECTCONSTRUCTORS=1' \
 	'-DSK_BUILD_FOR_ANDROID' \
 	'-DSK_USE_POSIX_THREADS' \
 	'-DSK_DEFERRED_CANVAS_USES_FACTORIES=1' \
 	'-DCHROME_PNG_WRITE_SUPPORT' \
 	'-DPNG_USER_CONFIG' \
+	'-DCHROME_PNG_READ_PACK_SUPPORT' \
 	'-DLIBXML_STATIC' \
 	'-DLIBXSLT_STATIC' \
 	'-D__STDC_CONSTANT_MACROS' \
@@ -507,7 +512,7 @@
 	$(LOCAL_PATH)/third_party/WebKit \
 	$(gyp_shared_intermediate_dir)/blink \
 	$(gyp_shared_intermediate_dir)/blink/bindings \
-	$(LOCAL_PATH)/third_party/angle_dx11/include \
+	$(LOCAL_PATH)/third_party/angle/include \
 	$(PWD)/external/icu4c/common \
 	$(PWD)/external/icu4c/i18n \
 	$(LOCAL_PATH)/third_party/skia/src/core \
@@ -546,7 +551,6 @@
 	-fvisibility-inlines-hidden \
 	-Wsign-compare \
 	-Wno-c++0x-compat \
-	-Wno-error=c++0x-compat \
 	-Wno-non-virtual-dtor \
 	-Wno-sign-promo
 
diff --git a/Source/core/workers/AbstractWorker.cpp b/Source/core/workers/AbstractWorker.cpp
index a617c23..aa07055 100644
--- a/Source/core/workers/AbstractWorker.cpp
+++ b/Source/core/workers/AbstractWorker.cpp
@@ -63,7 +63,7 @@
         return KURL();
     }
 
-    if (executionContext()->contentSecurityPolicy() && !executionContext()->contentSecurityPolicy()->allowScriptFromSource(scriptURL)) {
+    if (executionContext()->contentSecurityPolicy() && !executionContext()->contentSecurityPolicy()->allowWorkerContextFromSource(scriptURL)) {
         exceptionState.throwSecurityError("Access to the script at '" + scriptURL.elidedString() + "' is denied by the document's Content Security Policy.");
         return KURL();
     }
diff --git a/Source/core/workers/AbstractWorker.h b/Source/core/workers/AbstractWorker.h
index 775f2e6..213d7c9 100644
--- a/Source/core/workers/AbstractWorker.h
+++ b/Source/core/workers/AbstractWorker.h
@@ -51,9 +51,9 @@
     REFCOUNTED_EVENT_TARGET(AbstractWorker);
 public:
     // EventTarget APIs
-    virtual ExecutionContext* executionContext() const OVERRIDE { return ActiveDOMObject::executionContext(); }
+    virtual ExecutionContext* executionContext() const OVERRIDE FINAL { return ActiveDOMObject::executionContext(); }
 
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
+    DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(error);
 
     AbstractWorker(ExecutionContext*);
     virtual ~AbstractWorker();
diff --git a/Source/core/workers/AbstractWorker.idl b/Source/core/workers/AbstractWorker.idl
index 9c13c6f..1b643f7 100644
--- a/Source/core/workers/AbstractWorker.idl
+++ b/Source/core/workers/AbstractWorker.idl
@@ -30,8 +30,7 @@
  */
 
 [
-    NoInterfaceObject,
-    LegacyImplementedInBaseClass
+    NoInterfaceObject
 ] interface AbstractWorker {
     attribute EventHandler onerror;
 };
diff --git a/Source/core/workers/DedicatedWorkerGlobalScope.h b/Source/core/workers/DedicatedWorkerGlobalScope.h
index 1555111..c689d79 100644
--- a/Source/core/workers/DedicatedWorkerGlobalScope.h
+++ b/Source/core/workers/DedicatedWorkerGlobalScope.h
@@ -40,7 +40,7 @@
 class DedicatedWorkerThread;
 struct WorkerThreadStartupData;
 
-class DedicatedWorkerGlobalScope : public WorkerGlobalScope {
+class DedicatedWorkerGlobalScope FINAL : public WorkerGlobalScope {
 public:
     typedef WorkerGlobalScope Base;
     static PassRefPtr<DedicatedWorkerGlobalScope> create(DedicatedWorkerThread*, PassOwnPtr<WorkerThreadStartupData>, double timeOrigin);
diff --git a/Source/core/workers/DedicatedWorkerGlobalScope.idl b/Source/core/workers/DedicatedWorkerGlobalScope.idl
index 659a5f5..1ef0663 100644
--- a/Source/core/workers/DedicatedWorkerGlobalScope.idl
+++ b/Source/core/workers/DedicatedWorkerGlobalScope.idl
@@ -29,9 +29,8 @@
  */
 
 [
-    GlobalContext=DedicatedWorkerGlobalScope
+    GlobalContext=DedicatedWorkerGlobalScope,
 ] interface DedicatedWorkerGlobalScope : WorkerGlobalScope {
-    [Custom, RaisesException] void postMessage(any message, optional Array messagePorts);
+    [Custom, RaisesException] void postMessage(any message, optional MessagePort[] messagePorts);
     attribute EventHandler onmessage;
 };
-
diff --git a/Source/core/workers/DedicatedWorkerThread.h b/Source/core/workers/DedicatedWorkerThread.h
index c8f44c7..3ae1871 100644
--- a/Source/core/workers/DedicatedWorkerThread.h
+++ b/Source/core/workers/DedicatedWorkerThread.h
@@ -38,7 +38,7 @@
 class WorkerObjectProxy;
 struct WorkerThreadStartupData;
 
-class DedicatedWorkerThread : public WorkerThread {
+class DedicatedWorkerThread FINAL : public WorkerThread {
 public:
     static PassRefPtr<DedicatedWorkerThread> create(WorkerLoaderProxy&, WorkerObjectProxy&, double timeOrigin, PassOwnPtr<WorkerThreadStartupData>);
     WorkerObjectProxy& workerObjectProxy() const { return m_workerObjectProxy; }
diff --git a/Source/core/workers/SharedWorker.cpp b/Source/core/workers/SharedWorker.cpp
index 35dbb17..331c8cd 100644
--- a/Source/core/workers/SharedWorker.cpp
+++ b/Source/core/workers/SharedWorker.cpp
@@ -37,9 +37,11 @@
 #include "core/dom/ExecutionContext.h"
 #include "core/dom/MessageChannel.h"
 #include "core/dom/MessagePort.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Page.h"
+#include "core/frame/Frame.h"
 #include "core/frame/UseCounter.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/loader/FrameLoader.h"
+#include "core/loader/FrameLoaderClient.h"
 #include "core/workers/SharedWorkerRepositoryClient.h"
 #include "platform/weborigin/KURL.h"
 #include "platform/weborigin/SecurityOrigin.h"
@@ -57,7 +59,7 @@
     ASSERT(isMainThread());
     ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
 
-    UseCounter::count(toDocument(context)->domWindow(), UseCounter::SharedWorkerStart);
+    UseCounter::count(context, UseCounter::SharedWorkerStart);
 
     RefPtr<SharedWorker> worker = adoptRef(new SharedWorker(context));
 
@@ -79,8 +81,8 @@
     if (scriptURL.isEmpty())
         return 0;
 
-    if (document->page() && document->page()->sharedWorkerRepositoryClient())
-        document->page()->sharedWorkerRepositoryClient()->connect(worker.get(), remotePort.release(), scriptURL, name, exceptionState);
+    if (document->frame()->loader().client()->sharedWorkerRepositoryClient())
+        document->frame()->loader().client()->sharedWorkerRepositoryClient()->connect(worker.get(), remotePort.release(), scriptURL, name, exceptionState);
 
     return worker.release();
 }
diff --git a/Source/core/workers/SharedWorker.h b/Source/core/workers/SharedWorker.h
index 8f7902a..b19fd41 100644
--- a/Source/core/workers/SharedWorker.h
+++ b/Source/core/workers/SharedWorker.h
@@ -33,12 +33,13 @@
 #define SharedWorker_h
 
 #include "core/workers/AbstractWorker.h"
+#include "platform/Supplementable.h"
 
 namespace WebCore {
 
 class ExceptionState;
 
-class SharedWorker : public AbstractWorker, public ScriptWrappable {
+class SharedWorker FINAL : public AbstractWorker, public ScriptWrappable, public Supplementable<SharedWorker> {
 public:
     static PassRefPtr<SharedWorker> create(ExecutionContext*, const String& url, const String& name, ExceptionState&);
     virtual ~SharedWorker();
diff --git a/Source/core/workers/SharedWorkerGlobalScope.h b/Source/core/workers/SharedWorkerGlobalScope.h
index a87e0a6..8dae3bb 100644
--- a/Source/core/workers/SharedWorkerGlobalScope.h
+++ b/Source/core/workers/SharedWorkerGlobalScope.h
@@ -40,7 +40,7 @@
     class MessageEvent;
     class SharedWorkerThread;
 
-    class SharedWorkerGlobalScope : public WorkerGlobalScope {
+    class SharedWorkerGlobalScope FINAL : public WorkerGlobalScope {
     public:
         typedef WorkerGlobalScope Base;
         static PassRefPtr<SharedWorkerGlobalScope> create(const String& name, SharedWorkerThread*, PassOwnPtr<WorkerThreadStartupData>);
diff --git a/Source/core/workers/Worker.cpp b/Source/core/workers/Worker.cpp
index cd1d102..f75b7ac 100644
--- a/Source/core/workers/Worker.cpp
+++ b/Source/core/workers/Worker.cpp
@@ -54,7 +54,7 @@
 {
     ASSERT(isMainThread());
     Document* document = toDocument(context);
-    UseCounter::count(document->domWindow(), UseCounter::WorkerStart);
+    UseCounter::count(context, UseCounter::WorkerStart);
     ASSERT(document->page());
     WorkerGlobalScopeProxyProvider* proxyProvider = WorkerGlobalScopeProxyProvider::from(document->page());
     ASSERT(proxyProvider);
diff --git a/Source/core/workers/Worker.h b/Source/core/workers/Worker.h
index 6271fae..1f1067b 100644
--- a/Source/core/workers/Worker.h
+++ b/Source/core/workers/Worker.h
@@ -46,7 +46,7 @@
 class WorkerGlobalScopeProxy;
 class WorkerScriptLoader;
 
-class Worker : public AbstractWorker, public ScriptWrappable, private WorkerScriptLoaderClient {
+class Worker FINAL : public AbstractWorker, public ScriptWrappable, private WorkerScriptLoaderClient {
 public:
     static PassRefPtr<Worker> create(ExecutionContext*, const String& url, ExceptionState&);
     virtual ~Worker();
diff --git a/Source/core/workers/Worker.idl b/Source/core/workers/Worker.idl
index 6017569..5d9f11a 100644
--- a/Source/core/workers/Worker.idl
+++ b/Source/core/workers/Worker.idl
@@ -34,7 +34,7 @@
 
     attribute EventHandler onmessage;
 
-    [Custom, RaisesException] void postMessage(SerializedScriptValue message, optional Array messagePorts);
+    [Custom, RaisesException] void postMessage(SerializedScriptValue message, optional MessagePort[] messagePorts);
     void terminate();
 };
 
diff --git a/Source/core/workers/WorkerConsole.cpp b/Source/core/workers/WorkerConsole.cpp
index 0142a93..f4a819e 100644
--- a/Source/core/workers/WorkerConsole.cpp
+++ b/Source/core/workers/WorkerConsole.cpp
@@ -31,17 +31,10 @@
 
 #include "core/workers/WorkerConsole.h"
 
-#include "bindings/v8/ScriptCallStackFactory.h"
-#include "bindings/v8/ScriptProfiler.h"
-#include "core/inspector/InspectorConsoleInstrumentation.h"
-#include "core/inspector/ScriptArguments.h"
 #include "core/inspector/ScriptCallStack.h"
-#include "core/inspector/ScriptProfile.h"
-#include "core/inspector/WorkerInspectorController.h"
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerReportingProxy.h"
 #include "core/workers/WorkerThread.h"
-#include "platform/TraceEvent.h"
 
 
 namespace WebCore {
@@ -69,11 +62,6 @@
     return m_scope->executionContext();
 }
 
-bool WorkerConsole::profilerEnabled()
-{
-    return InspectorInstrumentation::profilerEnabled(m_scope);
-}
-
 // FIXME: add memory getter
 
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerConsole.h b/Source/core/workers/WorkerConsole.h
index b39002d..a2ef40d 100644
--- a/Source/core/workers/WorkerConsole.h
+++ b/Source/core/workers/WorkerConsole.h
@@ -30,7 +30,6 @@
 #ifndef WorkerConsole_h
 #define WorkerConsole_h
 
-#include "bindings/v8/ScriptState.h"
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/inspector/ConsoleAPITypes.h"
 #include "core/frame/ConsoleBase.h"
@@ -44,7 +43,7 @@
 
 class ScriptArguments;
 
-class WorkerConsole : public RefCounted<WorkerConsole>, public ConsoleBase, public ScriptWrappable {
+class WorkerConsole FINAL : public RefCounted<WorkerConsole>, public ConsoleBase, public ScriptWrappable {
 public:
     using RefCounted<WorkerConsole>::ref;
     using RefCounted<WorkerConsole>::deref;
@@ -53,15 +52,14 @@
     virtual ~WorkerConsole();
 
 protected:
-    virtual ExecutionContext* context();
+    virtual ExecutionContext* context() OVERRIDE;
     virtual void reportMessageToClient(MessageLevel, const String& message, PassRefPtr<ScriptCallStack>) OVERRIDE;
-    virtual bool profilerEnabled();
 
 private:
     explicit WorkerConsole(WorkerGlobalScope*);
 
-    virtual void refConsole() { ref(); }
-    virtual void derefConsole() { deref(); }
+    virtual void refConsole() OVERRIDE { ref(); }
+    virtual void derefConsole() OVERRIDE { deref(); }
 
     WorkerGlobalScope* m_scope;
 };
diff --git a/Source/core/workers/WorkerEventQueue.h b/Source/core/workers/WorkerEventQueue.h
index 6a66901..cdbd169 100644
--- a/Source/core/workers/WorkerEventQueue.h
+++ b/Source/core/workers/WorkerEventQueue.h
@@ -39,7 +39,7 @@
 class Node;
 class ExecutionContext;
 
-class WorkerEventQueue : public EventQueue {
+class WorkerEventQueue FINAL : public EventQueue {
     WTF_MAKE_FAST_ALLOCATED;
 public:
 
diff --git a/Source/core/workers/WorkerGlobalScope.cpp b/Source/core/workers/WorkerGlobalScope.cpp
index cd8daa3..e7e302d 100644
--- a/Source/core/workers/WorkerGlobalScope.cpp
+++ b/Source/core/workers/WorkerGlobalScope.cpp
@@ -88,9 +88,6 @@
     setClient(this);
     setSecurityOrigin(SecurityOrigin::create(url));
     m_workerClients->reattachThread();
-
-    // Notify proxy that a new WorkerGlobalScope has been created and started.
-    this->thread()->workerReportingProxy().workerGlobalScopeStarted();
 }
 
 WorkerGlobalScope::~WorkerGlobalScope()
@@ -109,7 +106,7 @@
 void WorkerGlobalScope::applyContentSecurityPolicyFromString(const String& policy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
 {
     setContentSecurityPolicy(ContentSecurityPolicy::create(this));
-    contentSecurityPolicy()->didReceiveHeader(policy, contentSecurityPolicyType);
+    contentSecurityPolicy()->didReceiveHeader(policy, contentSecurityPolicyType, ContentSecurityPolicy::HeaderSourceHTTP);
 }
 
 ExecutionContext* WorkerGlobalScope::executionContext() const
diff --git a/Source/core/workers/WorkerGlobalScope.h b/Source/core/workers/WorkerGlobalScope.h
index 8bdcf17..08fa1ee 100644
--- a/Source/core/workers/WorkerGlobalScope.h
+++ b/Source/core/workers/WorkerGlobalScope.h
@@ -63,9 +63,9 @@
     public:
         virtual ~WorkerGlobalScope();
 
-        virtual bool isWorkerGlobalScope() const OVERRIDE { return true; }
+        virtual bool isWorkerGlobalScope() const OVERRIDE FINAL { return true; }
 
-        virtual ExecutionContext* executionContext() const OVERRIDE;
+        virtual ExecutionContext* executionContext() const OVERRIDE FINAL;
 
         virtual bool isSharedWorkerGlobalScope() const { return false; }
         virtual bool isDedicatedWorkerGlobalScope() const { return false; }
@@ -74,8 +74,8 @@
         const KURL& url() const { return m_url; }
         KURL completeURL(const String&) const;
 
-        virtual String userAgent(const KURL&) const;
-        virtual void disableEval(const String& errorMessage) OVERRIDE;
+        virtual String userAgent(const KURL&) const OVERRIDE FINAL;
+        virtual void disableEval(const String& errorMessage) OVERRIDE FINAL;
 
         WorkerScriptController* script() { return m_script.get(); }
         void clearScript() { m_script.clear(); }
@@ -83,7 +83,7 @@
 
         WorkerThread* thread() const { return m_thread; }
 
-        virtual void postTask(PassOwnPtr<ExecutionContextTask>) OVERRIDE; // Executes the task on context's thread asynchronously.
+        virtual void postTask(PassOwnPtr<ExecutionContextTask>) OVERRIDE FINAL; // Executes the task on context's thread asynchronously.
 
         // WorkerGlobalScope
         WorkerGlobalScope* self() { return this; }
@@ -98,13 +98,13 @@
         WorkerNavigator* navigator() const;
 
         // ExecutionContextClient
-        virtual WorkerEventQueue* eventQueue() const OVERRIDE;
-        virtual SecurityContext& securityContext() OVERRIDE { return *this; }
+        virtual WorkerEventQueue* eventQueue() const OVERRIDE FINAL;
+        virtual SecurityContext& securityContext() OVERRIDE FINAL { return *this; }
 
-        virtual bool isContextThread() const OVERRIDE;
-        virtual bool isJSExecutionForbidden() const OVERRIDE;
+        virtual bool isContextThread() const OVERRIDE FINAL;
+        virtual bool isJSExecutionForbidden() const OVERRIDE FINAL;
 
-        virtual double timerAlignmentInterval() const OVERRIDE;
+        virtual double timerAlignmentInterval() const OVERRIDE FINAL;
 
         WorkerInspectorController* workerInspectorController() { return m_workerInspectorController.get(); }
         // These methods are used for GC marking. See JSWorkerGlobalScope::visitChildrenVirtual(SlotVisitor&) in
@@ -148,17 +148,17 @@
         void addMessageToWorkerConsole(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
 
     private:
-        virtual void refExecutionContext() OVERRIDE { ref(); }
-        virtual void derefExecutionContext() OVERRIDE { deref(); }
+        virtual void refExecutionContext() OVERRIDE FINAL { ref(); }
+        virtual void derefExecutionContext() OVERRIDE FINAL { deref(); }
 
-        virtual const KURL& virtualURL() const OVERRIDE;
-        virtual KURL virtualCompleteURL(const String&) const;
+        virtual const KURL& virtualURL() const OVERRIDE FINAL;
+        virtual KURL virtualCompleteURL(const String&) const OVERRIDE FINAL;
 
-        virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE;
-        virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* = 0) OVERRIDE;
+        virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE FINAL;
+        virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* = 0) OVERRIDE FINAL;
 
-        virtual EventTarget* errorEventTarget() OVERRIDE;
-        virtual void didUpdateSecurityOrigin() OVERRIDE { }
+        virtual EventTarget* errorEventTarget() OVERRIDE FINAL;
+        virtual void didUpdateSecurityOrigin() OVERRIDE FINAL { }
 
         KURL m_url;
         String m_userAgent;
@@ -183,11 +183,7 @@
         double m_timeOrigin;
     };
 
-inline WorkerGlobalScope* toWorkerGlobalScope(ExecutionContext* context)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!context || context->isWorkerGlobalScope());
-    return static_cast<WorkerGlobalScope*>(context);
-}
+DEFINE_TYPE_CASTS(WorkerGlobalScope, ExecutionContext, context, context->isWorkerGlobalScope(), context.isWorkerGlobalScope());
 
 } // namespace WebCore
 
diff --git a/Source/core/workers/WorkerLoaderProxy.h b/Source/core/workers/WorkerLoaderProxy.h
index 4cb4002..c3ebc9a 100644
--- a/Source/core/workers/WorkerLoaderProxy.h
+++ b/Source/core/workers/WorkerLoaderProxy.h
@@ -49,10 +49,9 @@
         // Posts a task to the thread which runs the loading code (normally, the main thread).
         virtual void postTaskToLoader(PassOwnPtr<ExecutionContextTask>) = 0;
 
-        // Posts callbacks from loading code to the WorkerGlobalScope. The 'mode' is used to differentiate
-        // specific synchronous loading requests so they can be 'nested', per spec.
+        // Posts callbacks from loading code to the WorkerGlobalScope.
         // Returns true if the task was posted successfully.
-        virtual bool postTaskForModeToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask>, const String& mode) = 0;
+        virtual bool postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask>) = 0;
     };
 
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerLocation.idl b/Source/core/workers/WorkerLocation.idl
index c3dd851..64ed9e0 100644
--- a/Source/core/workers/WorkerLocation.idl
+++ b/Source/core/workers/WorkerLocation.idl
@@ -31,5 +31,4 @@
 ] interface WorkerLocation {
 };
 
-// force rebuild: crbug.com/307023
 WorkerLocation implements URLUtilsReadOnly;
diff --git a/Source/core/workers/WorkerMessagingProxy.cpp b/Source/core/workers/WorkerMessagingProxy.cpp
index a34d8e1..0a15e5d 100644
--- a/Source/core/workers/WorkerMessagingProxy.cpp
+++ b/Source/core/workers/WorkerMessagingProxy.cpp
@@ -141,13 +141,13 @@
         m_queuedEarlyTasks.append(MessageWorkerGlobalScopeTask::create(message, channels));
 }
 
-bool WorkerMessagingProxy::postTaskForModeToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task, const String& mode)
+bool WorkerMessagingProxy::postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task)
 {
     if (m_askedToTerminate)
         return false;
 
     ASSERT(m_workerThread);
-    m_workerThread->runLoop().postTaskForMode(task, mode);
+    m_workerThread->runLoop().postTask(task);
     return true;
 }
 
diff --git a/Source/core/workers/WorkerMessagingProxy.h b/Source/core/workers/WorkerMessagingProxy.h
index c943374..4fcdd73 100644
--- a/Source/core/workers/WorkerMessagingProxy.h
+++ b/Source/core/workers/WorkerMessagingProxy.h
@@ -45,7 +45,7 @@
     class Worker;
     class WorkerClients;
 
-    class WorkerMessagingProxy : public WorkerGlobalScopeProxy, public WorkerLoaderProxy {
+    class WorkerMessagingProxy FINAL : public WorkerGlobalScopeProxy, public WorkerLoaderProxy {
         WTF_MAKE_NONCOPYABLE(WorkerMessagingProxy); WTF_MAKE_FAST_ALLOCATED;
     public:
         WorkerMessagingProxy(Worker*, PassOwnPtr<WorkerClients>);
@@ -76,7 +76,7 @@
         // These methods are called on different threads to schedule loading
         // requests and to send callbacks back to WorkerGlobalScope.
         virtual void postTaskToLoader(PassOwnPtr<ExecutionContextTask>) OVERRIDE;
-        virtual bool postTaskForModeToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask>, const String& mode) OVERRIDE;
+        virtual bool postTaskToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask>) OVERRIDE;
 
         void workerThreadCreated(PassRefPtr<DedicatedWorkerThread>);
 
diff --git a/Source/core/workers/WorkerNavigator.h b/Source/core/workers/WorkerNavigator.h
index 61c0618..850d706 100644
--- a/Source/core/workers/WorkerNavigator.h
+++ b/Source/core/workers/WorkerNavigator.h
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class WorkerNavigator : public RefCounted<WorkerNavigator>, public ScriptWrappable, public NavigatorBase, public Supplementable<WorkerNavigator> {
+class WorkerNavigator FINAL : public RefCounted<WorkerNavigator>, public ScriptWrappable, public NavigatorBase, public Supplementable<WorkerNavigator> {
 public:
     static PassRefPtr<WorkerNavigator> create(const String& userAgent) { return adoptRef(new WorkerNavigator(userAgent)); }
     virtual ~WorkerNavigator();
diff --git a/Source/core/workers/WorkerObjectProxy.h b/Source/core/workers/WorkerObjectProxy.h
index 8b727a1..56266ef 100644
--- a/Source/core/workers/WorkerObjectProxy.h
+++ b/Source/core/workers/WorkerObjectProxy.h
@@ -38,41 +38,41 @@
 
 namespace WebCore {
 
-    class ExecutionContext;
-    class WorkerMessagingProxy;
+class ExecutionContext;
+class WorkerMessagingProxy;
 
-    // A proxy to talk to the worker object. This object is created on the
-    // worker object thread (i.e. usually the main thread), passed on to
-    // the worker thread, and used just to proxy messages to the
-    // WorkerMessagingProxy on the worker object thread.
-    //
-    // Used only by Dedicated Worker.
-    class WorkerObjectProxy : public WorkerReportingProxy {
-    public:
-        static PassOwnPtr<WorkerObjectProxy> create(ExecutionContext*, WorkerMessagingProxy*);
-        ~WorkerObjectProxy() { }
+// A proxy to talk to the worker object. This object is created on the
+// worker object thread (i.e. usually the main thread), passed on to
+// the worker thread, and used just to proxy messages to the
+// WorkerMessagingProxy on the worker object thread.
+//
+// Used only by Dedicated Worker.
+class WorkerObjectProxy FINAL : public WorkerReportingProxy {
+public:
+    static PassOwnPtr<WorkerObjectProxy> create(ExecutionContext*, WorkerMessagingProxy*);
+    virtual ~WorkerObjectProxy() { }
 
-        void postMessageToWorkerObject(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>);
+    void postMessageToWorkerObject(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>);
 
-        void confirmMessageFromWorkerObject(bool hasPendingActivity);
-        void reportPendingActivity(bool hasPendingActivity);
+    void confirmMessageFromWorkerObject(bool hasPendingActivity);
+    void reportPendingActivity(bool hasPendingActivity);
 
-        // WorkerReportingProxy overrides.
-        virtual void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) OVERRIDE;
-        virtual void reportConsoleMessage(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) OVERRIDE;
-        virtual void postMessageToPageInspector(const String&) OVERRIDE;
-        virtual void updateInspectorStateCookie(const String&) OVERRIDE;
-        virtual void workerGlobalScopeStarted() OVERRIDE { }
-        virtual void workerGlobalScopeClosed() OVERRIDE;
-        virtual void workerGlobalScopeDestroyed() OVERRIDE;
+    // WorkerReportingProxy overrides.
+    virtual void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) OVERRIDE;
+    virtual void reportConsoleMessage(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) OVERRIDE;
+    virtual void postMessageToPageInspector(const String&) OVERRIDE;
+    virtual void updateInspectorStateCookie(const String&) OVERRIDE;
+    virtual void workerGlobalScopeStarted(WorkerGlobalScope*) OVERRIDE { }
+    virtual void workerGlobalScopeClosed() OVERRIDE;
+    virtual void workerGlobalScopeDestroyed() OVERRIDE;
 
-    private:
-        WorkerObjectProxy(ExecutionContext*, WorkerMessagingProxy*);
+private:
+    WorkerObjectProxy(ExecutionContext*, WorkerMessagingProxy*);
 
-        // These objects always outlive this proxy.
-        ExecutionContext* m_executionContext;
-        WorkerMessagingProxy* m_messagingProxy;
-    };
+    // These objects always outlive this proxy.
+    ExecutionContext* m_executionContext;
+    WorkerMessagingProxy* m_messagingProxy;
+};
 
 } // namespace WebCore
 
diff --git a/Source/core/workers/WorkerReportingProxy.h b/Source/core/workers/WorkerReportingProxy.h
index 75b1389..0d0ccb0 100644
--- a/Source/core/workers/WorkerReportingProxy.h
+++ b/Source/core/workers/WorkerReportingProxy.h
@@ -36,25 +36,27 @@
 
 namespace WebCore {
 
-    // APIs used by workers to report console activity.
-    class WorkerReportingProxy {
-    public:
-        virtual ~WorkerReportingProxy() {}
+class WorkerGlobalScope;
 
-        virtual void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) = 0;
-        virtual void reportConsoleMessage(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) = 0;
-        virtual void postMessageToPageInspector(const String&) = 0;
-        virtual void updateInspectorStateCookie(const String&) = 0;
+// APIs used by workers to report console activity.
+class WorkerReportingProxy {
+public:
+    virtual ~WorkerReportingProxy() { }
 
-        // Invoked when the new WorkerGlobalScope is started.
-        virtual void workerGlobalScopeStarted() = 0;
+    virtual void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) = 0;
+    virtual void reportConsoleMessage(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) = 0;
+    virtual void postMessageToPageInspector(const String&) = 0;
+    virtual void updateInspectorStateCookie(const String&) = 0;
 
-        // Invoked when close() is invoked on the worker context.
-        virtual void workerGlobalScopeClosed() = 0;
+    // Invoked when the new WorkerGlobalScope is started.
+    virtual void workerGlobalScopeStarted(WorkerGlobalScope*) = 0;
 
-        // Invoked when the thread has stopped.
-        virtual void workerGlobalScopeDestroyed() = 0;
-    };
+    // Invoked when close() is invoked on the worker context.
+    virtual void workerGlobalScopeClosed() = 0;
+
+    // Invoked when the thread has stopped.
+    virtual void workerGlobalScopeDestroyed() = 0;
+};
 
 } // namespace WebCore
 
diff --git a/Source/core/workers/WorkerRunLoop.cpp b/Source/core/workers/WorkerRunLoop.cpp
index b7ad2fd..f015c82 100644
--- a/Source/core/workers/WorkerRunLoop.cpp
+++ b/Source/core/workers/WorkerRunLoop.cpp
@@ -34,6 +34,7 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerThread.h"
+#include "heap/ThreadState.h"
 #include "platform/PlatformThreadData.h"
 #include "platform/SharedTimer.h"
 #include "platform/ThreadTimers.h"
@@ -41,6 +42,11 @@
 
 namespace WebCore {
 
+static String defaultMode()
+{
+    return String();
+}
+
 class WorkerRunLoop::Task {
     WTF_MAKE_NONCOPYABLE(Task); WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -93,7 +99,7 @@
 public:
     ModePredicate(const String& mode)
         : m_mode(mode)
-        , m_defaultMode(mode == WorkerRunLoop::defaultMode())
+        , m_defaultMode(mode == defaultMode())
     {
     }
 
@@ -124,11 +130,6 @@
     ASSERT(!m_nestedCount);
 }
 
-String WorkerRunLoop::defaultMode()
-{
-    return String();
-}
-
 class RunLoopSetup {
     WTF_MAKE_NONCOPYABLE(RunLoopSetup);
 public:
@@ -160,6 +161,7 @@
     ModePredicate modePredicate(defaultMode());
     MessageQueueWaitResult result;
     do {
+        ThreadState::current()->safePoint(ThreadState::NoHeapPointersOnStack);
         result = runInMode(context, modePredicate, WaitForMessage);
     } while (result != MessageQueueTerminated);
     runCleanupTasks(context);
@@ -204,7 +206,11 @@
                 }
             }
         }
-        task = m_messageQueue.waitForMessageFilteredWithTimeout(result, predicate, absoluteTime);
+
+        {
+            ThreadState::SafePointScope safePointScope(ThreadState::NoHeapPointersOnStack);
+            task = m_messageQueue.waitForMessageFilteredWithTimeout(result, predicate, absoluteTime);
+        }
     } while (result == MessageQueueTimeout && nextTimeoutEventIsIdleWatchdog);
 
     // If the context is closing, don't execute any further JavaScript tasks (per section 4.1.1 of the Web Workers spec).
@@ -269,9 +275,4 @@
     return m_messageQueue.append(Task::create(task, mode.isolatedCopy()));
 }
 
-bool WorkerRunLoop::postTaskForMode(const Closure& closure, const String& mode)
-{
-    return postTaskForMode(CallClosureTask::create(closure), mode);
-}
-
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerRunLoop.h b/Source/core/workers/WorkerRunLoop.h
index 88d1b3a..3f3f59f 100644
--- a/Source/core/workers/WorkerRunLoop.h
+++ b/Source/core/workers/WorkerRunLoop.h
@@ -68,12 +68,9 @@
 
         // Returns true if the loop is still alive, false if it has been terminated.
         bool postTaskForMode(PassOwnPtr<ExecutionContextTask>, const String& mode);
-        bool postTaskForMode(const Closure&, const String& mode);
 
         unsigned long createUniqueId() { return ++m_uniqueId; }
 
-        static String defaultMode();
-
         class Task;
 
     private:
diff --git a/Source/core/workers/WorkerScriptLoader.cpp b/Source/core/workers/WorkerScriptLoader.cpp
index 1ed0d43..ba33a8b 100644
--- a/Source/core/workers/WorkerScriptLoader.cpp
+++ b/Source/core/workers/WorkerScriptLoader.cpp
@@ -29,7 +29,7 @@
 #include "core/workers/WorkerScriptLoader.h"
 
 #include "core/dom/ExecutionContext.h"
-#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/loader/WorkerThreadableLoader.h"
 #include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerScriptLoaderClient.h"
@@ -66,7 +66,6 @@
     ThreadableLoaderOptions options;
     options.allowCredentials = AllowStoredCredentials;
     options.crossOriginRequestPolicy = crossOriginRequestPolicy;
-    options.sendLoadCallbacks = SendCallbacks;
     // FIXME: Should we add EnforceScriptSrcDirective here?
     options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy;
 
@@ -86,7 +85,6 @@
     ThreadableLoaderOptions options;
     options.allowCredentials = AllowStoredCredentials;
     options.crossOriginRequestPolicy = crossOriginRequestPolicy;
-    options.sendLoadCallbacks = SendCallbacks;
 
     // During create, callbacks may happen which remove the last reference to this object.
     RefPtr<WorkerScriptLoader> protect(this);
diff --git a/Source/core/workers/WorkerScriptLoader.h b/Source/core/workers/WorkerScriptLoader.h
index e403851..8e64a09 100644
--- a/Source/core/workers/WorkerScriptLoader.h
+++ b/Source/core/workers/WorkerScriptLoader.h
@@ -45,7 +45,7 @@
     class TextResourceDecoder;
     class WorkerScriptLoaderClient;
 
-    class WorkerScriptLoader : public RefCounted<WorkerScriptLoader>, public ThreadableLoaderClient {
+    class WorkerScriptLoader FINAL : public RefCounted<WorkerScriptLoader>, public ThreadableLoaderClient {
         WTF_MAKE_FAST_ALLOCATED;
     public:
         static PassRefPtr<WorkerScriptLoader> create()
@@ -82,7 +82,7 @@
         friend class WTF::RefCounted<WorkerScriptLoader>;
 
         WorkerScriptLoader();
-        ~WorkerScriptLoader();
+        virtual ~WorkerScriptLoader();
 
         PassOwnPtr<ResourceRequest> createResourceRequest();
         void notifyFinished();
diff --git a/Source/core/workers/WorkerThread.cpp b/Source/core/workers/WorkerThread.cpp
index 6f842e8..1776622 100644
--- a/Source/core/workers/WorkerThread.cpp
+++ b/Source/core/workers/WorkerThread.cpp
@@ -32,12 +32,15 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/workers/DedicatedWorkerGlobalScope.h"
 #include "core/workers/WorkerClients.h"
+#include "core/workers/WorkerReportingProxy.h"
 #include "core/workers/WorkerThreadStartupData.h"
+#include "heap/ThreadState.h"
 #include "modules/webdatabase/DatabaseManager.h"
 #include "modules/webdatabase/DatabaseTask.h"
 #include "platform/PlatformThreadData.h"
 #include "platform/weborigin/KURL.h"
 #include "public/platform/Platform.h"
+#include "public/platform/WebWaitableEvent.h"
 #include "public/platform/WebWorkerRunLoop.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/text/WTFString.h"
@@ -70,6 +73,7 @@
     , m_workerReportingProxy(workerReportingProxy)
     , m_startupData(startupData)
     , m_notificationClient(0)
+    , m_shutdownEvent(adoptPtr(blink::Platform::current()->createWaitableEvent()))
 {
     MutexLocker lock(threadSetMutex());
     workerThreads().add(this);
@@ -108,7 +112,7 @@
 
     {
         MutexLocker lock(m_threadCreationMutex);
-
+        ThreadState::attach();
         m_workerGlobalScope = createWorkerGlobalScope(m_startupData.release());
 
         if (m_runLoop.terminated()) {
@@ -121,6 +125,9 @@
     // ~WorkerScriptController.
     blink::Platform::current()->didStartWorkerRunLoop(blink::WebWorkerRunLoop(&m_runLoop));
 
+    // Notify proxy that a new WorkerGlobalScope has been created and started.
+    m_workerReportingProxy.workerGlobalScopeStarted(m_workerGlobalScope.get());
+
     WorkerScriptController* script = m_workerGlobalScope->script();
     InspectorInstrumentation::willEvaluateWorkerScript(workerGlobalScope(), startMode);
     script->evaluate(ScriptSourceCode(sourceCode, scriptURL));
@@ -135,11 +142,17 @@
     // We cannot let any objects survive past thread exit, because no other thread will run GC or otherwise destroy them.
     m_workerGlobalScope = 0;
 
+    // Cleanup thread heap which causes all objects to be finalized.
+    // After this call thread heap must be empty.
+    ThreadState::current()->cleanup();
+
     // Clean up PlatformThreadData before WTF::WTFThreadData goes away!
     PlatformThreadData::current().destroy();
 
     // The thread object may be already destroyed from notification now, don't try to access "this".
     detachThread(threadID);
+
+    ThreadState::detach();
 }
 
 void WorkerThread::runEventLoop()
@@ -203,9 +216,16 @@
 
 void WorkerThread::stop()
 {
+    // Prevent the deadlock between GC and an attempt to stop a thread.
+    ThreadState::SafePointScope safePointScope(ThreadState::HeapPointersOnStack);
+
     // Mutex protection is necessary because stop() can be called before the context is fully created.
     MutexLocker lock(m_threadCreationMutex);
 
+    // Signal the thread to notify that the thread's stopping.
+    if (m_shutdownEvent)
+        m_shutdownEvent->signal();
+
     // Ensure that tasks are being handled by thread event loop. If script execution weren't forbidden, a while(1) loop in JS could keep the thread alive forever.
     if (m_workerGlobalScope) {
         m_workerGlobalScope->script()->scheduleExecutionTermination();
diff --git a/Source/core/workers/WorkerThread.h b/Source/core/workers/WorkerThread.h
index 83bf3f4..a58d1e7 100644
--- a/Source/core/workers/WorkerThread.h
+++ b/Source/core/workers/WorkerThread.h
@@ -35,6 +35,10 @@
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 
+namespace blink {
+class WebWaitableEvent;
+}
+
 namespace WebCore {
 
     class KURL;
@@ -53,6 +57,10 @@
         bool start();
         void stop();
 
+        // Can be used to wait for this worker thread to shut down.
+        // (This is signalled on the main thread, so it's assumed to be waited on the worker context thread)
+        blink::WebWaitableEvent* shutdownEvent() { return m_shutdownEvent.get(); }
+
         bool isCurrentThread() const;
         WorkerRunLoop& runLoop() { return m_runLoop; }
         WorkerLoaderProxy& workerLoaderProxy() const { return m_workerLoaderProxy; }
@@ -93,6 +101,9 @@
         OwnPtr<WorkerThreadStartupData> m_startupData;
 
         NotificationClient* m_notificationClient;
+
+        // Used to signal thread shutdown.
+        OwnPtr<blink::WebWaitableEvent> m_shutdownEvent;
     };
 
 } // namespace WebCore
diff --git a/Source/core/xml/DocumentXPathEvaluator.h b/Source/core/xml/DocumentXPathEvaluator.h
index 769a449..04a39f9 100644
--- a/Source/core/xml/DocumentXPathEvaluator.h
+++ b/Source/core/xml/DocumentXPathEvaluator.h
@@ -36,7 +36,7 @@
 class XPathExpression;
 class XPathResult;
 
-class DocumentXPathEvaluator : public DocumentSupplement {
+class DocumentXPathEvaluator FINAL : public DocumentSupplement {
 public:
     virtual ~DocumentXPathEvaluator();
 
diff --git a/Source/core/xml/DocumentXPathEvaluator.idl b/Source/core/xml/DocumentXPathEvaluator.idl
index ebe0ef4..3ef7c2d 100644
--- a/Source/core/xml/DocumentXPathEvaluator.idl
+++ b/Source/core/xml/DocumentXPathEvaluator.idl
@@ -16,6 +16,7 @@
  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  * Boston, MA 02110-1301, USA.
  */
+
 partial interface Document {
     // DOM Level 3 XPath (XPathEvaluator interface)
     [RaisesException] XPathExpression createExpression([Default=Undefined] optional DOMString expression,
diff --git a/Source/core/xml/NativeXPathNSResolver.h b/Source/core/xml/NativeXPathNSResolver.h
index 7952310..45d5a66 100644
--- a/Source/core/xml/NativeXPathNSResolver.h
+++ b/Source/core/xml/NativeXPathNSResolver.h
@@ -33,7 +33,7 @@
 
 class Node;
 
-class NativeXPathNSResolver : public XPathNSResolver {
+class NativeXPathNSResolver FINAL : public XPathNSResolver {
 public:
     static PassRefPtr<NativeXPathNSResolver> create(PassRefPtr<Node> node) { return adoptRef(new NativeXPathNSResolver(node)); }
     virtual ~NativeXPathNSResolver();
diff --git a/Source/core/xml/XMLHttpRequest.cpp b/Source/core/xml/XMLHttpRequest.cpp
index 80c758c..adf3672 100644
--- a/Source/core/xml/XMLHttpRequest.cpp
+++ b/Source/core/xml/XMLHttpRequest.cpp
@@ -32,16 +32,16 @@
 #include "core/editing/markup.h"
 #include "core/events/Event.h"
 #include "core/fetch/CrossOriginAccessControl.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/fileapi/Blob.h"
 #include "core/fileapi/File.h"
 #include "core/fileapi/Stream.h"
 #include "core/frame/ContentSecurityPolicy.h"
 #include "core/html/DOMFormData.h"
 #include "core/html/HTMLDocument.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/ThreadableLoader.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
 #include "core/xml/XMLHttpRequestProgressEvent.h"
 #include "core/xml/XMLHttpRequestUpload.h"
 #include "platform/Logging.h"
@@ -517,7 +517,7 @@
 
 void XMLHttpRequest::open(const AtomicString& method, const KURL& url, bool async, ExceptionState& exceptionState)
 {
-    WTF_LOG(Network, "XMLHttpRequest %p open('%s', '%s', %d)", this, method.string().utf8().data(), url.elidedString().utf8().data(), async);
+    WTF_LOG(Network, "XMLHttpRequest %p open('%s', '%s', %d)", this, method.utf8().data(), url.elidedString().utf8().data(), async);
 
     if (!internalAbort())
         return;
@@ -818,7 +818,6 @@
         request.addHTTPHeaderFields(m_requestHeaders);
 
     ThreadableLoaderOptions options;
-    options.sendLoadCallbacks = SendCallbacks;
     options.sniffContent = DoNotSniffContent;
     options.preflightPolicy = uploadEvents ? ForcePreflight : ConsiderPreflight;
     options.allowCredentials = (m_sameOriginRequest || m_includeCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials;
@@ -1107,7 +1106,7 @@
 {
     HTTPHeaderMap::AddResult result = m_requestHeaders.add(name, value);
     if (!result.isNewEntry)
-        result.iterator->value = result.iterator->value + ", " + value;
+        result.storedValue->value = result.storedValue->value + ", " + value;
 }
 
 const AtomicString& XMLHttpRequest::getRequestHeader(const AtomicString& name) const
@@ -1187,9 +1186,7 @@
 
 bool XMLHttpRequest::responseIsXML() const
 {
-    // FIXME: Remove the lower() call when DOMImplementation.isXMLMIMEType() is modified
-    //        to do case insensitive MIME type matching.
-    return DOMImplementation::isXMLMIMEType(responseMIMEType().lower());
+    return DOMImplementation::isXMLMIMEType(responseMIMEType());
 }
 
 int XMLHttpRequest::status() const
@@ -1264,7 +1261,7 @@
 
     clearVariablesForLoading();
 
-    InspectorInstrumentation::didFinishXHRLoading(executionContext(), this, this, identifier, m_responseText, m_url, m_lastSendURL, m_lastSendLineNumber);
+    InspectorInstrumentation::didFinishXHRLoading(executionContext(), this, this, identifier, m_responseText, m_method, m_url, m_lastSendURL, m_lastSendLineNumber);
 
     // Prevent dropProtection releasing the last reference, and retain |this| until the end of this method.
     RefPtr<XMLHttpRequest> protect(this);
diff --git a/Source/core/xml/XMLHttpRequest.h b/Source/core/xml/XMLHttpRequest.h
index 00bde33..6cd13dc 100644
--- a/Source/core/xml/XMLHttpRequest.h
+++ b/Source/core/xml/XMLHttpRequest.h
@@ -53,12 +53,12 @@
 
 typedef int ExceptionCode;
 
-class XMLHttpRequest : public ScriptWrappable, public RefCounted<XMLHttpRequest>, public XMLHttpRequestEventTarget, private ThreadableLoaderClient, public ActiveDOMObject {
+class XMLHttpRequest FINAL : public ScriptWrappable, public RefCounted<XMLHttpRequest>, public XMLHttpRequestEventTarget, private ThreadableLoaderClient, public ActiveDOMObject {
     WTF_MAKE_FAST_ALLOCATED;
     REFCOUNTED_EVENT_TARGET(XMLHttpRequest);
 public:
     static PassRefPtr<XMLHttpRequest> create(ExecutionContext*, PassRefPtr<SecurityOrigin> = 0);
-    ~XMLHttpRequest();
+    virtual ~XMLHttpRequest();
 
     // These exact numeric values are important because JS expects them.
     enum State {
@@ -84,10 +84,10 @@
         DropProtectionAsync,
     };
 
-    virtual void contextDestroyed();
-    virtual void suspend();
-    virtual void resume();
-    virtual void stop();
+    virtual void contextDestroyed() OVERRIDE;
+    virtual void suspend() OVERRIDE;
+    virtual void resume() OVERRIDE;
+    virtual void stop() OVERRIDE;
 
     virtual const AtomicString& interfaceName() const OVERRIDE;
     virtual ExecutionContext* executionContext() const OVERRIDE;
@@ -149,15 +149,15 @@
     Document* document() const;
     SecurityOrigin* securityOrigin() const;
 
-    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
-    virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&);
-    virtual void didReceiveData(const char* data, int dataLength);
+    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
+    virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&) OVERRIDE;
+    virtual void didReceiveData(const char* data, int dataLength) OVERRIDE;
     // When "blob" is specified as the responseType attribute, didDownloadData
     // is called instead of didReceiveData.
-    virtual void didDownloadData(int dataLength);
-    virtual void didFinishLoading(unsigned long identifier, double finishTime);
-    virtual void didFail(const ResourceError&);
-    virtual void didFailRedirectCheck();
+    virtual void didDownloadData(int dataLength) OVERRIDE;
+    virtual void didFinishLoading(unsigned long identifier, double finishTime) OVERRIDE;
+    virtual void didFail(const ResourceError&) OVERRIDE;
+    virtual void didFailRedirectCheck() OVERRIDE;
 
     AtomicString responseMIMEType() const;
     bool responseIsXML() const;
diff --git a/Source/core/xml/XMLHttpRequest.idl b/Source/core/xml/XMLHttpRequest.idl
index 56e032a..2fba4d6 100644
--- a/Source/core/xml/XMLHttpRequest.idl
+++ b/Source/core/xml/XMLHttpRequest.idl
@@ -38,8 +38,6 @@
 
 [
     ActiveDOMObject,
-    Constructor,
-    ConstructorCallWith=ExecutionContext,
     CustomConstructor(optional XMLHttpRequestOptions options),
     GlobalContext=Window&WorkerGlobalScope,
 ] interface XMLHttpRequest : XMLHttpRequestEventTarget {
diff --git a/Source/core/xml/XMLHttpRequestProgressEvent.h b/Source/core/xml/XMLHttpRequestProgressEvent.h
index c6ab4a4..f636515 100644
--- a/Source/core/xml/XMLHttpRequestProgressEvent.h
+++ b/Source/core/xml/XMLHttpRequestProgressEvent.h
@@ -32,7 +32,7 @@
 
 namespace WebCore {
 
-class XMLHttpRequestProgressEvent : public ProgressEvent {
+class XMLHttpRequestProgressEvent FINAL : public ProgressEvent {
 public:
     static PassRefPtr<XMLHttpRequestProgressEvent> create()
     {
@@ -47,7 +47,7 @@
     unsigned long long position() const { return loaded(); }
     unsigned long long totalSize() const { return total(); }
 
-    virtual const AtomicString& interfaceName() const { return EventNames::XMLHttpRequestProgressEvent; }
+    virtual const AtomicString& interfaceName() const OVERRIDE { return EventNames::XMLHttpRequestProgressEvent; }
 
 private:
     XMLHttpRequestProgressEvent()
diff --git a/Source/core/xml/XMLHttpRequestProgressEventThrottle.h b/Source/core/xml/XMLHttpRequestProgressEventThrottle.h
index 36f5e3a..06681eb 100644
--- a/Source/core/xml/XMLHttpRequestProgressEventThrottle.h
+++ b/Source/core/xml/XMLHttpRequestProgressEventThrottle.h
@@ -45,7 +45,7 @@
 
 // This implements the XHR2 progress event dispatching: "dispatch a progress event called progress
 // about every 50ms or for every byte received, whichever is least frequent".
-class XMLHttpRequestProgressEventThrottle : public TimerBase {
+class XMLHttpRequestProgressEventThrottle FINAL : public TimerBase {
 public:
     explicit XMLHttpRequestProgressEventThrottle(EventTarget*);
     virtual ~XMLHttpRequestProgressEventThrottle();
@@ -61,7 +61,7 @@
 private:
     static const double minimumProgressEventDispatchingIntervalInSeconds;
 
-    virtual void fired();
+    virtual void fired() OVERRIDE;
     void dispatchDeferredEvents(Timer<XMLHttpRequestProgressEventThrottle>*);
     bool flushDeferredProgressEvent();
     void deliverProgressEvent();
diff --git a/Source/core/xml/XMLHttpRequestUpload.h b/Source/core/xml/XMLHttpRequestUpload.h
index d7a63da..2c3924a 100644
--- a/Source/core/xml/XMLHttpRequestUpload.h
+++ b/Source/core/xml/XMLHttpRequestUpload.h
@@ -44,7 +44,7 @@
 class ExecutionContext;
 class XMLHttpRequest;
 
-class XMLHttpRequestUpload : public ScriptWrappable, public XMLHttpRequestEventTarget {
+class XMLHttpRequestUpload FINAL : public ScriptWrappable, public XMLHttpRequestEventTarget {
 public:
     static PassOwnPtr<XMLHttpRequestUpload> create(XMLHttpRequest* xmlHttpRequest)
     {
diff --git a/Source/core/xml/XPathFunctions.cpp b/Source/core/xml/XPathFunctions.cpp
index 978d858..c3a7433 100644
--- a/Source/core/xml/XPathFunctions.cpp
+++ b/Source/core/xml/XPathFunctions.cpp
@@ -29,6 +29,7 @@
 #include "core/xml/XPathFunctions.h"
 
 #include "XMLNames.h"
+#include "core/dom/Attr.h"
 #include "core/dom/Element.h"
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/TreeScope.h"
@@ -71,159 +72,159 @@
 
 static HashMap<String, FunctionRec>* functionMap;
 
-class FunLast : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NumberValue; }
+class FunLast FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 public:
     FunLast() { setIsContextSizeSensitive(true); }
 };
 
-class FunPosition : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NumberValue; }
+class FunPosition FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 public:
     FunPosition() { setIsContextPositionSensitive(true); }
 };
 
-class FunCount : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NumberValue; }
+class FunCount FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 };
 
-class FunId : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NodeSetValue; }
+class FunId FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NodeSetValue; }
 };
 
-class FunLocalName : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunLocalName FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 public:
     FunLocalName() { setIsContextNodeSensitive(true); } // local-name() with no arguments uses context node.
 };
 
-class FunNamespaceURI : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunNamespaceURI FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 public:
     FunNamespaceURI() { setIsContextNodeSensitive(true); } // namespace-uri() with no arguments uses context node.
 };
 
-class FunName : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunName FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 public:
     FunName() { setIsContextNodeSensitive(true); } // name() with no arguments uses context node.
 };
 
-class FunString : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunString FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 public:
     FunString() { setIsContextNodeSensitive(true); } // string() with no arguments uses context node.
 };
 
-class FunConcat : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunConcat FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 };
 
-class FunStartsWith : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::BooleanValue; }
+class FunStartsWith FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::BooleanValue; }
 };
 
-class FunContains : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::BooleanValue; }
+class FunContains FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::BooleanValue; }
 };
 
-class FunSubstringBefore : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunSubstringBefore FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 };
 
-class FunSubstringAfter : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunSubstringAfter FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 };
 
-class FunSubstring : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunSubstring FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 };
 
-class FunStringLength : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NumberValue; }
+class FunStringLength FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 public:
     FunStringLength() { setIsContextNodeSensitive(true); } // string-length() with no arguments uses context node.
 };
 
-class FunNormalizeSpace : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunNormalizeSpace FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 public:
     FunNormalizeSpace() { setIsContextNodeSensitive(true); } // normalize-space() with no arguments uses context node.
 };
 
-class FunTranslate : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::StringValue; }
+class FunTranslate FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 };
 
-class FunBoolean : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::BooleanValue; }
+class FunBoolean FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::BooleanValue; }
 };
 
-class FunNot : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::BooleanValue; }
+class FunNot FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::BooleanValue; }
 };
 
-class FunTrue : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::BooleanValue; }
+class FunTrue FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::BooleanValue; }
 };
 
-class FunFalse : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::BooleanValue; }
+class FunFalse FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::BooleanValue; }
 };
 
-class FunLang : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::BooleanValue; }
+class FunLang FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::BooleanValue; }
 public:
     FunLang() { setIsContextNodeSensitive(true); } // lang() always works on context node.
 };
 
-class FunNumber : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NumberValue; }
+class FunNumber FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 public:
     FunNumber() { setIsContextNodeSensitive(true); } // number() with no arguments uses context node.
 };
 
-class FunSum : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NumberValue; }
+class FunSum FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 };
 
-class FunFloor : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NumberValue; }
+class FunFloor FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 };
 
-class FunCeiling : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NumberValue; }
+class FunCeiling FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 };
 
-class FunRound : public Function {
-    virtual Value evaluate() const;
-    virtual Value::Type resultType() const { return Value::NumberValue; }
+class FunRound FINAL : public Function {
+    virtual Value evaluate() const OVERRIDE;
+    virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 public:
     static double round(double);
 };
@@ -299,7 +300,7 @@
         setIsContextNodeSensitive(false);
 
     Vector<OwnPtr<Expression> >::iterator end = args.end();
-    for (Vector<OwnPtr<Expression> >::iterator it = args.begin(); it != end; it++)
+    for (Vector<OwnPtr<Expression> >::iterator it = args.begin(); it != end; ++it)
         addSubExpression(it->release());
 }
 
@@ -349,7 +350,7 @@
 
         // If there are several nodes with the same id, id() should return the first one.
         // In WebKit, getElementById behaves so, too, although its behavior in this case is formally undefined.
-        Node* node = contextScope.getElementById(idList.substring(startPos, endPos - startPos));
+        Node* node = contextScope.getElementById(AtomicString(idList.substring(startPos, endPos - startPos)));
         if (node && resultSet.add(node).isNewEntry)
             result.append(node);
 
@@ -364,7 +365,7 @@
 static inline String expandedNameLocalPart(Node* node)
 {
     // The local part of an XPath expanded-name matches DOM local name for most node types, except for namespace nodes and processing instruction nodes.
-    ASSERT(node->nodeType() != Node::XPATH_NAMESPACE_NODE); // Not supported yet.
+    // But note that Blink does not support namespace nodes.
     if (node->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
         return toProcessingInstruction(node)->target();
     return node->localName().string();
@@ -372,7 +373,19 @@
 
 static inline String expandedName(Node* node)
 {
-    const AtomicString& prefix = node->prefix();
+    AtomicString prefix;
+
+    switch (node->nodeType()) {
+    case Node::ELEMENT_NODE:
+        prefix = toElement(node)->prefix();
+        break;
+    case Node::ATTRIBUTE_NODE:
+        prefix = toAttr(node)->prefix();
+        break;
+    default:
+        break;
+    }
+
     return prefix.isEmpty() ? expandedNameLocalPart(node) : prefix + ":" + expandedNameLocalPart(node);
 }
 
diff --git a/Source/core/xml/XPathGrammar.y b/Source/core/xml/XPathGrammar.y
index f40b3ce..6911fcf 100644
--- a/Source/core/xml/XPathGrammar.y
+++ b/Source/core/xml/XPathGrammar.y
@@ -429,7 +429,7 @@
     FilterExpr '/' RelativeLocationPath
     {
         $3->setAbsolute(true);
-        $$ = new Path(static_cast<Filter*>($1), $3);
+        $$ = new Path($1, $3);
         parser->unregisterParseNode($1);
         parser->unregisterParseNode($3);
         parser->registerParseNode($$);
@@ -439,7 +439,7 @@
     {
         $3->insertFirstStep($2);
         $3->setAbsolute(true);
-        $$ = new Path(static_cast<Filter*>($1), $3);
+        $$ = new Path($1, $3);
         parser->unregisterParseNode($1);
         parser->unregisterParseNode($2);
         parser->unregisterParseNode($3);
diff --git a/Source/core/xml/XPathParser.cpp b/Source/core/xml/XPathParser.cpp
index 3c6579f..04f1ebf 100644
--- a/Source/core/xml/XPathParser.cpp
+++ b/Source/core/xml/XPathParser.cpp
@@ -41,7 +41,6 @@
 using namespace Unicode;
 using namespace XPath;
 
-extern int xpathyyparse(WebCore::XPath::Parser*);
 #include "XPathGrammar.h"
 
 Parser* Parser::currentParser = 0;
diff --git a/Source/core/xml/XPathParser.h b/Source/core/xml/XPathParser.h
index 07a3f8d..e3f4cf0 100644
--- a/Source/core/xml/XPathParser.h
+++ b/Source/core/xml/XPathParser.h
@@ -31,6 +31,13 @@
 #include "core/xml/XPathStep.h"
 
 namespace WebCore {
+namespace XPath {
+class Parser;
+}
+}
+int xpathyyparse(WebCore::XPath::Parser*);
+
+namespace WebCore {
 
 class ExceptionState;
 class XPathNSResolver;
diff --git a/Source/core/xml/XPathPath.cpp b/Source/core/xml/XPathPath.cpp
index dbc2550..80e57b3 100644
--- a/Source/core/xml/XPathPath.cpp
+++ b/Source/core/xml/XPathPath.cpp
@@ -185,7 +185,7 @@
     m_steps.insert(0, step);
 }
 
-Path::Path(Filter* filter, LocationPath* path)
+Path::Path(Expression* filter, LocationPath* path)
     : m_filter(filter)
     , m_path(path)
 {
diff --git a/Source/core/xml/XPathPath.h b/Source/core/xml/XPathPath.h
index f501926..18016a8 100644
--- a/Source/core/xml/XPathPath.h
+++ b/Source/core/xml/XPathPath.h
@@ -37,50 +37,50 @@
         class Predicate;
         class Step;
 
-        class Filter : public Expression {
+        class Filter FINAL : public Expression {
         public:
             Filter(PassOwnPtr<Expression>, Vector<OwnPtr<Predicate> >&);
             virtual ~Filter();
 
-            virtual Value evaluate() const;
+            virtual Value evaluate() const OVERRIDE;
 
         private:
-            virtual Value::Type resultType() const { return Value::NodeSetValue; }
+            virtual Value::Type resultType() const OVERRIDE { return Value::NodeSetValue; }
 
             OwnPtr<Expression> m_expr;
             Vector<OwnPtr<Predicate> > m_predicates;
         };
 
-        class LocationPath : public Expression {
+        class LocationPath FINAL : public Expression {
         public:
             LocationPath();
             virtual ~LocationPath();
             void setAbsolute(bool value) { m_absolute = value; setIsContextNodeSensitive(!m_absolute); }
 
-            virtual Value evaluate() const;
+            virtual Value evaluate() const OVERRIDE;
             void evaluate(NodeSet& nodes) const; // nodes is an input/output parameter
 
             void appendStep(Step* step);
             void insertFirstStep(Step* step);
 
         private:
-            virtual Value::Type resultType() const { return Value::NodeSetValue; }
+            virtual Value::Type resultType() const OVERRIDE { return Value::NodeSetValue; }
 
             Vector<Step*> m_steps;
             bool m_absolute;
         };
 
-        class Path : public Expression {
+        class Path FINAL : public Expression {
         public:
-            Path(Filter*, LocationPath*);
+            Path(Expression*, LocationPath*);
             virtual ~Path();
 
-            virtual Value evaluate() const;
+            virtual Value evaluate() const OVERRIDE;
 
         private:
-            virtual Value::Type resultType() const { return Value::NodeSetValue; }
+            virtual Value::Type resultType() const OVERRIDE { return Value::NodeSetValue; }
 
-            Filter* m_filter;
+            Expression* m_filter;
             LocationPath* m_path;
         };
 
diff --git a/Source/core/xml/XPathPredicate.h b/Source/core/xml/XPathPredicate.h
index 0b506f2..3ad8a0a 100644
--- a/Source/core/xml/XPathPredicate.h
+++ b/Source/core/xml/XPathPredicate.h
@@ -34,73 +34,73 @@
 
     namespace XPath {
 
-        class Number : public Expression {
+        class Number FINAL : public Expression {
         public:
             explicit Number(double);
         private:
-            virtual Value evaluate() const;
-            virtual Value::Type resultType() const { return Value::NumberValue; }
+            virtual Value evaluate() const OVERRIDE;
+            virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 
             Value m_value;
         };
 
-        class StringExpression : public Expression {
+        class StringExpression FINAL : public Expression {
         public:
             explicit StringExpression(const String&);
         private:
-            virtual Value evaluate() const;
-            virtual Value::Type resultType() const { return Value::StringValue; }
+            virtual Value evaluate() const OVERRIDE;
+            virtual Value::Type resultType() const OVERRIDE { return Value::StringValue; }
 
             Value m_value;
         };
 
-        class Negative : public Expression {
+        class Negative FINAL : public Expression {
         private:
-            virtual Value evaluate() const;
-            virtual Value::Type resultType() const { return Value::NumberValue; }
+            virtual Value evaluate() const OVERRIDE;
+            virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
         };
 
-        class NumericOp : public Expression {
+        class NumericOp FINAL : public Expression {
         public:
             enum Opcode {
                 OP_Add, OP_Sub, OP_Mul, OP_Div, OP_Mod
             };
             NumericOp(Opcode, PassOwnPtr<Expression> lhs, PassOwnPtr<Expression> rhs);
         private:
-            virtual Value evaluate() const;
-            virtual Value::Type resultType() const { return Value::NumberValue; }
+            virtual Value evaluate() const OVERRIDE;
+            virtual Value::Type resultType() const OVERRIDE { return Value::NumberValue; }
 
             Opcode m_opcode;
         };
 
-        class EqTestOp : public Expression {
+        class EqTestOp FINAL : public Expression {
         public:
             enum Opcode { OP_EQ, OP_NE, OP_GT, OP_LT, OP_GE, OP_LE };
             EqTestOp(Opcode, PassOwnPtr<Expression> lhs, PassOwnPtr<Expression> rhs);
-            virtual Value evaluate() const;
+            virtual Value evaluate() const OVERRIDE;
         private:
-            virtual Value::Type resultType() const { return Value::BooleanValue; }
+            virtual Value::Type resultType() const OVERRIDE { return Value::BooleanValue; }
             bool compare(const Value&, const Value&) const;
 
             Opcode m_opcode;
         };
 
-        class LogicalOp : public Expression {
+        class LogicalOp FINAL : public Expression {
         public:
             enum Opcode { OP_And, OP_Or };
             LogicalOp(Opcode, PassOwnPtr<Expression> lhs, PassOwnPtr<Expression> rhs);
         private:
-            virtual Value::Type resultType() const { return Value::BooleanValue; }
+            virtual Value::Type resultType() const OVERRIDE { return Value::BooleanValue; }
             bool shortCircuitOn() const;
-            virtual Value evaluate() const;
+            virtual Value evaluate() const OVERRIDE;
 
             Opcode m_opcode;
         };
 
-        class Union : public Expression {
+        class Union FINAL : public Expression {
         private:
-            virtual Value evaluate() const;
-            virtual Value::Type resultType() const { return Value::NodeSetValue; }
+            virtual Value evaluate() const OVERRIDE;
+            virtual Value::Type resultType() const OVERRIDE { return Value::NodeSetValue; }
         };
 
         class Predicate {
diff --git a/Source/core/xml/XPathStep.cpp b/Source/core/xml/XPathStep.cpp
index 4687257..56d7d69 100644
--- a/Source/core/xml/XPathStep.cpp
+++ b/Source/core/xml/XPathStep.cpp
@@ -149,8 +149,6 @@
     switch (axis) {
         case Step::AttributeAxis:
             return Node::ATTRIBUTE_NODE;
-        case Step::NamespaceAxis:
-            return Node::XPATH_NAMESPACE_NODE;
         default:
             return Node::ELEMENT_NODE;
     }
@@ -283,8 +281,7 @@
             return;
         }
         case FollowingSiblingAxis:
-            if (context->nodeType() == Node::ATTRIBUTE_NODE ||
-                 context->nodeType() == Node::XPATH_NAMESPACE_NODE)
+            if (context->nodeType() == Node::ATTRIBUTE_NODE)
                 return;
 
             for (Node* n = context->nextSibling(); n; n = n->nextSibling())
@@ -292,8 +289,7 @@
                     nodes.append(n);
             return;
         case PrecedingSiblingAxis:
-            if (context->nodeType() == Node::ATTRIBUTE_NODE ||
-                 context->nodeType() == Node::XPATH_NAMESPACE_NODE)
+            if (context->nodeType() == Node::ATTRIBUTE_NODE)
                 return;
 
             for (Node* n = context->previousSibling(); n; n = n->previousSibling())
@@ -362,7 +358,7 @@
             return;
         }
         case NamespaceAxis:
-            // XPath namespace nodes are not implemented yet.
+            // XPath namespace nodes are not implemented.
             return;
         case SelfAxis:
             if (nodeMatches(context, SelfAxis, m_nodeTest))
diff --git a/Source/core/xml/XPathStep.h b/Source/core/xml/XPathStep.h
index b148aae..cc6bb09 100644
--- a/Source/core/xml/XPathStep.h
+++ b/Source/core/xml/XPathStep.h
@@ -38,7 +38,7 @@
 
 class Predicate;
 
-class Step : public ParseNode {
+class Step FINAL : public ParseNode {
     WTF_MAKE_NONCOPYABLE(Step);
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -94,7 +94,7 @@
 
     Step(Axis, const NodeTest&);
     Step(Axis, const NodeTest&, Vector<OwnPtr<Predicate> >&);
-    ~Step();
+    virtual ~Step();
 
     void optimize();
 
diff --git a/Source/core/xml/XPathUtil.cpp b/Source/core/xml/XPathUtil.cpp
index 5e266fa..b36abf3 100644
--- a/Source/core/xml/XPathUtil.cpp
+++ b/Source/core/xml/XPathUtil.cpp
@@ -47,7 +47,6 @@
         case Node::COMMENT_NODE:
         case Node::TEXT_NODE:
         case Node::CDATA_SECTION_NODE:
-        case Node::XPATH_NAMESPACE_NODE:
             return node->nodeValue();
         default:
             if (isRootDomNode(node) || node->nodeType() == Node::ELEMENT_NODE) {
@@ -79,12 +78,9 @@
         case Node::DOCUMENT_NODE:
         case Node::ELEMENT_NODE:
         case Node::PROCESSING_INSTRUCTION_NODE:
-        case Node::XPATH_NAMESPACE_NODE:
             return true;
         case Node::DOCUMENT_FRAGMENT_NODE:
         case Node::DOCUMENT_TYPE_NODE:
-        case Node::ENTITY_NODE:
-        case Node::NOTATION_NODE:
             return false;
         case Node::TEXT_NODE:
             return !(node->parentNode() && node->parentNode()->isAttributeNode());
diff --git a/Source/core/xml/XPathVariableReference.h b/Source/core/xml/XPathVariableReference.h
index e494a46..a53599e 100644
--- a/Source/core/xml/XPathVariableReference.h
+++ b/Source/core/xml/XPathVariableReference.h
@@ -33,12 +33,12 @@
     namespace XPath {
 
         // Variable references are not used with XPathEvaluator.
-        class VariableReference : public Expression {
+        class VariableReference FINAL : public Expression {
         public:
             explicit VariableReference(const String& name);
         private:
-            virtual Value evaluate() const;
-            virtual Value::Type resultType() const { ASSERT_NOT_REACHED(); return Value::NumberValue; }
+            virtual Value evaluate() const OVERRIDE;
+            virtual Value::Type resultType() const OVERRIDE { ASSERT_NOT_REACHED(); return Value::NumberValue; }
             String m_name;
         };
 
diff --git a/Source/core/xml/XSLImportRule.h b/Source/core/xml/XSLImportRule.h
index 954e046..4d9a77a 100644
--- a/Source/core/xml/XSLImportRule.h
+++ b/Source/core/xml/XSLImportRule.h
@@ -33,7 +33,7 @@
 
 class XSLStyleSheetResource;
 
-class XSLImportRule : private StyleSheetResourceClient {
+class XSLImportRule FINAL : private StyleSheetResourceClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassOwnPtr<XSLImportRule> create(XSLStyleSheet* parentSheet, const String& href)
@@ -56,7 +56,7 @@
 private:
     XSLImportRule(XSLStyleSheet* parentSheet, const String& href);
 
-    virtual void setXSLStyleSheet(const String& href, const KURL& baseURL, const String& sheet);
+    virtual void setXSLStyleSheet(const String& href, const KURL& baseURL, const String& sheet) OVERRIDE;
 
     XSLStyleSheet* m_parentStyleSheet;
     String m_strHref;
diff --git a/Source/core/xml/XSLStyleSheet.h b/Source/core/xml/XSLStyleSheet.h
index 17f9984..2a3c9bc 100644
--- a/Source/core/xml/XSLStyleSheet.h
+++ b/Source/core/xml/XSLStyleSheet.h
@@ -36,7 +36,7 @@
 class ResourceFetcher;
 class XSLImportRule;
 
-class XSLStyleSheet : public StyleSheet {
+class XSLStyleSheet FINAL : public StyleSheet {
 public:
     static PassRefPtr<XSLStyleSheet> create(XSLImportRule* parentImport, const String& originalURL, const KURL& finalURL)
     {
diff --git a/Source/core/xml/XSLStyleSheetLibxslt.cpp b/Source/core/xml/XSLStyleSheetLibxslt.cpp
index 398afdd..38cd4ba 100644
--- a/Source/core/xml/XSLStyleSheetLibxslt.cpp
+++ b/Source/core/xml/XSLStyleSheetLibxslt.cpp
@@ -26,7 +26,7 @@
 #include "core/dom/Node.h"
 #include "core/dom/TransformSource.h"
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
+#include "core/frame/FrameHost.h"
 #include "core/xml/XSLImportRule.h"
 #include "core/xml/XSLTProcessor.h"
 #include "core/xml/parser/XMLDocumentParserScope.h"
@@ -130,8 +130,8 @@
 
     PageConsole* console = 0;
     Frame* frame = ownerDocument()->frame();
-    if (frame && frame->page())
-        console = &frame->page()->console();
+    if (frame && frame->host())
+        console = &frame->host()->console();
 
     XMLDocumentParserScope scope(fetcher(), XSLTProcessor::genericErrorFunc, XSLTProcessor::parseErrorFunc, console);
     XMLParserInput input(source);
diff --git a/Source/core/xml/XSLTProcessor.cpp b/Source/core/xml/XSLTProcessor.cpp
index 61ca31b..48fd5cf 100644
--- a/Source/core/xml/XSLTProcessor.cpp
+++ b/Source/core/xml/XSLTProcessor.cpp
@@ -92,7 +92,7 @@
     }
 
     DocumentEncodingData data;
-    data.encoding = sourceEncoding.isEmpty() ? UTF8Encoding() : WTF::TextEncoding(sourceEncoding);
+    data.setEncoding(sourceEncoding.isEmpty() ? UTF8Encoding() : WTF::TextEncoding(sourceEncoding));
     result->setEncodingData(data);
     result->setContent(documentSource);
 
diff --git a/Source/core/xml/XSLTProcessorLibxslt.cpp b/Source/core/xml/XSLTProcessorLibxslt.cpp
index 18f571d..d1a6b12 100644
--- a/Source/core/xml/XSLTProcessorLibxslt.cpp
+++ b/Source/core/xml/XSLTProcessorLibxslt.cpp
@@ -34,8 +34,8 @@
 #include "core/fetch/Resource.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/frame/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/PageConsole.h"
+#include "core/frame/FrameHost.h"
+#include "core/frame/PageConsole.h"
 #include "core/xml/XSLStyleSheet.h"
 #include "core/xml/XSLTExtensions.h"
 #include "core/xml/XSLTUnicodeSort.h"
@@ -110,8 +110,8 @@
 
         PageConsole* console = 0;
         Frame* frame = globalProcessor->xslStylesheet()->ownerDocument()->frame();
-        if (frame && frame->page())
-            console = &frame->page()->console();
+        if (frame && frame->host())
+            console = &frame->host()->console();
         xmlSetStructuredErrorFunc(console, XSLTProcessor::parseErrorFunc);
         xmlSetGenericErrorFunc(console, XSLTProcessor::genericErrorFunc);
 
diff --git a/Source/core/xml/parser/XMLDocumentParser.cpp b/Source/core/xml/parser/XMLDocumentParser.cpp
index 36c329f..10106ae 100644
--- a/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -48,11 +48,11 @@
 #include "core/dom/TransformSource.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/ScriptResource.h"
-#include "core/fetch/TextResourceDecoder.h"
 #include "core/frame/Frame.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLTemplateElement.h"
 #include "core/html/parser/HTMLEntityParser.h"
+#include "core/html/parser/TextResourceDecoder.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/ImageLoader.h"
 #include "core/frame/UseCounter.h"
@@ -471,8 +471,8 @@
     if (errorOccurred)
         scriptLoader->dispatchErrorEvent();
     else if (!wasCanceled) {
-        if (scriptLoader->executePotentiallyCrossOriginScript(sourceCode))
-            scriptLoader->dispatchLoadEvent();
+        scriptLoader->executeScript(sourceCode);
+        scriptLoader->dispatchLoadEvent();
     }
 
     m_scriptElement = 0;
@@ -1000,7 +1000,7 @@
     else
         pushCurrentNode(newElement.get());
 
-    if (isHTMLHtmlElement(newElement.get()))
+    if (newElement->hasTagName(HTMLNames::htmlTag))
         toHTMLHtmlElement(newElement)->insertedByParser();
 
     if (!m_parsingFragment && isFirstElement && document()->frame())
@@ -1024,7 +1024,8 @@
     exitText();
 
     RefPtr<ContainerNode> n = m_currentNode;
-    n->finishParsingChildren();
+    if (m_currentNode->isElementNode())
+        toElement(n.get())->finishParsingChildren();
 
     if (!scriptingContentIsAllowed(parserContentPolicy()) && n->isElementNode() && toScriptLoaderIfPossible(toElement(n))) {
         popCurrentNode();
@@ -1102,28 +1103,15 @@
     if (isStopped())
         return;
 
-#if HAVE(VASPRINTF)
-    char* formattedMessage;
-    if (vasprintf(&formattedMessage, message, args) == -1)
-        return;
-#else
     char formattedMessage[1024];
     vsnprintf(formattedMessage, sizeof(formattedMessage) - 1, message, args);
-#endif
 
     if (m_parserPaused) {
         m_pendingCallbacks.append(adoptPtr(new PendingErrorCallback(type, reinterpret_cast<const xmlChar*>(formattedMessage), lineNumber(), columnNumber())));
-#if HAVE(VASPRINTF)
-        free(formattedMessage);
-#endif
         return;
     }
 
     handleError(type, formattedMessage, textPosition());
-
-#if HAVE(VASPRINTF)
-    free(formattedMessage);
-#endif
 }
 
 void XMLDocumentParser::processingInstruction(const String& target, const String& data)
@@ -1148,7 +1136,7 @@
 
     m_currentNode->parserAppendChild(pi.get());
 
-    pi->finishParsingChildren();
+    pi->setCreatedByParser(false);
 
     if (pi->isCSS())
         m_sawCSS = true;
diff --git a/Source/core/xml/parser/XMLDocumentParser.h b/Source/core/xml/parser/XMLDocumentParser.h
index 2db50a0..294c02d 100644
--- a/Source/core/xml/parser/XMLDocumentParser.h
+++ b/Source/core/xml/parser/XMLDocumentParser.h
@@ -63,7 +63,7 @@
         xmlParserCtxtPtr m_context;
     };
 
-    class XMLDocumentParser : public ScriptableDocumentParser, public ResourceClient {
+    class XMLDocumentParser FINAL : public ScriptableDocumentParser, public ResourceClient {
         WTF_MAKE_FAST_ALLOCATED;
     public:
         static PassRefPtr<XMLDocumentParser> create(Document* document, FrameView* view)
@@ -75,7 +75,7 @@
             return adoptRef(new XMLDocumentParser(fragment, element, parserContentPolicy));
         }
 
-        ~XMLDocumentParser();
+        virtual ~XMLDocumentParser();
 
         // Exposed for callbacks:
         void handleError(XMLErrors::ErrorType, const char* message, TextPosition);
@@ -88,9 +88,9 @@
         static bool parseDocumentFragment(const String&, DocumentFragment*, Element* parent = 0, ParserContentPolicy = AllowScriptingContent);
 
         // Used by the XMLHttpRequest to check if the responseXML was well formed.
-        virtual bool wellFormed() const { return !m_sawError; }
+        virtual bool wellFormed() const OVERRIDE { return !m_sawError; }
 
-        TextPosition textPosition() const;
+        virtual TextPosition textPosition() const OVERRIDE;
 
         static bool supportsXMLVersion(const String&);
 
@@ -105,17 +105,17 @@
         XMLDocumentParser(DocumentFragment*, Element*, ParserContentPolicy);
 
         // From DocumentParser
-        virtual void insert(const SegmentedString&);
-        virtual void append(PassRefPtr<StringImpl>);
-        virtual void finish();
-        virtual bool isWaitingForScripts() const;
-        virtual void stopParsing();
-        virtual void detach();
-        virtual OrdinalNumber lineNumber() const;
+        virtual void insert(const SegmentedString&) OVERRIDE;
+        virtual void append(PassRefPtr<StringImpl>) OVERRIDE;
+        virtual void finish() OVERRIDE;
+        virtual bool isWaitingForScripts() const OVERRIDE;
+        virtual void stopParsing() OVERRIDE;
+        virtual void detach() OVERRIDE;
+        virtual OrdinalNumber lineNumber() const OVERRIDE;
         OrdinalNumber columnNumber() const;
 
         // from ResourceClient
-        virtual void notifyFinished(Resource*);
+        virtual void notifyFinished(Resource*) OVERRIDE;
 
         void end();
 
diff --git a/Source/core/xml/xmlattrs.in b/Source/core/xml/xmlattrs.in
index 6cc47be..a054fe5 100644
--- a/Source/core/xml/xmlattrs.in
+++ b/Source/core/xml/xmlattrs.in
@@ -1,4 +1,5 @@
 namespace="XML"
+namespacePrefix="xml"
 namespaceURI="http://www.w3.org/XML/1998/namespace"
 
 base